diff --git a/.clang-tidy b/.clang-tidy deleted file mode 100644 index cc55fefd25..0000000000 --- a/.clang-tidy +++ /dev/null @@ -1,19 +0,0 @@ ---- -Checks: ' -bugprone-*, --bugprone-integer-division, --bugprone-narrowing-conversions, -performance-*, -clang-analyzer-*, -misc-*, --misc-unused-parameters, -modernize-*, --modernize-avoid-c-arrays, --modernize-deprecated-headers, --modernize-use-auto, --modernize-use-using, --modernize-use-nullptr, --modernize-use-trailing-return-type, -' -CheckOptions: -... diff --git a/.codespellignore b/.codespellignore index 9d7022f1b1..70bd7ca970 100644 --- a/.codespellignore +++ b/.codespellignore @@ -3,3 +3,5 @@ REGIST PullRequest cancelled indeces +FOF +NoO diff --git a/.dockerignore b/.dockerignore deleted file mode 100644 index cfc34e5848..0000000000 --- a/.dockerignore +++ /dev/null @@ -1,39 +0,0 @@ -**/.git -.DS_Store -*.dylib -*.DSYM -*.d -*.pyc -*.pyo -.*.swp -.*.swo -.*.un~ -*.tmp -*.o -*.o-* -*.os -*.os-* -*.so -*.a - -venv/ -.venv/ - -notebooks -phone -massivemap -neos -installer -chffr/app2 -chffr/backend/env -selfdrive/nav -selfdrive/baseui -selfdrive/test/simulator2 -**/cache_data -xx/plus -xx/community -xx/projects -!xx/projects/eon_testing_master -!xx/projects/map3d -xx/ops -xx/junk diff --git a/.gitattributes b/.gitattributes index cc1605a132..1cf541aa3a 100644 --- a/.gitattributes +++ b/.gitattributes @@ -7,15 +7,8 @@ *.png filter=lfs diff=lfs merge=lfs -text *.gif filter=lfs diff=lfs merge=lfs -text *.ttf filter=lfs diff=lfs merge=lfs -text +*.otf filter=lfs diff=lfs merge=lfs -text *.wav filter=lfs diff=lfs merge=lfs -text -selfdrive/car/tests/test_models_segs.txt filter=lfs diff=lfs merge=lfs -text -system/hardware/tici/updater filter=lfs diff=lfs merge=lfs -text -third_party/**/*.a filter=lfs diff=lfs merge=lfs -text -third_party/**/*.so filter=lfs diff=lfs merge=lfs -text -third_party/**/*.so.* filter=lfs diff=lfs merge=lfs -text -third_party/**/*.dylib filter=lfs diff=lfs merge=lfs -text -third_party/acados/*/t_renderer filter=lfs diff=lfs merge=lfs -text -third_party/qt5/larch64/bin/lrelease filter=lfs diff=lfs merge=lfs -text -third_party/qt5/larch64/bin/lupdate filter=lfs diff=lfs merge=lfs -text -third_party/catch2/include/catch2/catch.hpp filter=lfs diff=lfs merge=lfs -text +openpilot/selfdrive/car/tests/test_models_segs.txt filter=lfs diff=lfs merge=lfs -text +openpilot/common/hardware/tici/updater filter=lfs diff=lfs merge=lfs -text diff --git a/.github/ISSUE_TEMPLATE/enhancement.md b/.github/ISSUE_TEMPLATE/enhancement.md deleted file mode 100644 index 330b9b1101..0000000000 --- a/.github/ISSUE_TEMPLATE/enhancement.md +++ /dev/null @@ -1,8 +0,0 @@ ---- -name: Enhancement -about: For openpilot enhancement suggestions -title: '' -labels: 'enhancement' -assignees: '' ---- - diff --git a/.github/labeler.yaml b/.github/labeler.yaml index e91764bb37..e8d4057bb1 100644 --- a/.github/labeler.yaml +++ b/.github/labeler.yaml @@ -1,6 +1,6 @@ ci: - changed-files: - - any-glob-to-all-files: "{.github/**,**/test_*,Jenkinsfile}" + - any-glob-to-all-files: "{.github/**,**/test_*,**/test/**,Jenkinsfile}" chore: - changed-files: @@ -8,24 +8,24 @@ chore: car: - changed-files: - - any-glob-to-all-files: '{selfdrive/car/**,opendbc_repo}' + - any-glob-to-all-files: '{openpilot/selfdrive/car/**,opendbc_repo}' simulation: - changed-files: - - any-glob-to-all-files: 'tools/sim/**' + - any-glob-to-all-files: 'openpilot/tools/sim/**' ui: - changed-files: - - any-glob-to-all-files: '{selfdrive/ui/**,system/ui/**}' + - any-glob-to-all-files: '{openpilot/selfdrive/assets/**,openpilot/selfdrive/ui/**,openpilot/system/ui/**}' tools: - changed-files: - - any-glob-to-all-files: 'tools/**' + - any-glob-to-all-files: 'openpilot/tools/**' multilanguage: - changed-files: - - any-glob-to-all-files: 'selfdrive/ui/translations/**' + - any-glob-to-all-files: 'openpilot/selfdrive/ui/translations/**' autonomy: - changed-files: - - any-glob-to-all-files: "{selfdrive/modeld/models/**,selfdrive/test/process_replay/model_replay_ref_commit,sunnypilot/modeld*/models/**}" + - any-glob-to-all-files: "{openpilot/selfdrive/modeld/models/**,openpilot/selfdrive/test/process_replay/model_replay_ref_commit,openpilot/sunnypilot/modeld*/models/**}" diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 2b4a5ed48f..b986273097 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -44,8 +44,8 @@ Explain how you tested this bug fix. **Checklist** -- [ ] added entry to CAR in selfdrive/car/*/values.py and ran `selfdrive/car/docs.py` to generate new docs -- [ ] test route added to [routes.py](https://github.com/commaai/openpilot/blob/master/selfdrive/car/tests/routes.py) +- [ ] added entry to CAR in openpilot/selfdrive/car/*/values.py and ran `openpilot/selfdrive/car/docs.py` to generate new docs +- [ ] test route added to [routes.py](https://github.com/commaai/openpilot/blob/master/openpilot/selfdrive/car/tests/routes.py) - [ ] route with openpilot: - [ ] route with stock system: - [ ] car harness used (if comma doesn't sell it, put N/A): diff --git a/.github/workflows/auto-cache/action.yaml b/.github/workflows/auto-cache/action.yaml deleted file mode 100644 index 377b1eedcd..0000000000 --- a/.github/workflows/auto-cache/action.yaml +++ /dev/null @@ -1,58 +0,0 @@ -name: 'automatically cache based on current runner' - -inputs: - path: - description: 'path to cache' - required: true - key: - description: 'key' - required: true - restore-keys: - description: 'restore-keys' - required: true - save: - description: 'whether to save the cache' - default: 'true' - required: false -outputs: - cache-hit: - description: 'cache hit occurred' - value: ${{ (contains(runner.name, 'nsc') && steps.ns-cache.outputs.cache-hit) || - (!contains(runner.name, 'nsc') && inputs.save != 'false' && steps.gha-cache.outputs.cache-hit) || - (!contains(runner.name, 'nsc') && inputs.save == 'false' && steps.gha-cache-ro.outputs.cache-hit) }} - -runs: - using: "composite" - steps: - - name: setup namespace cache - id: ns-cache - if: ${{ contains(runner.name, 'nsc') }} - uses: namespacelabs/nscloud-cache-action@v1 - with: - path: ${{ inputs.path }} - - - name: setup github cache - id: gha-cache - if: ${{ !contains(runner.name, 'nsc') && inputs.save != 'false' }} - uses: 'actions/cache@v4' - with: - path: ${{ inputs.path }} - key: ${{ inputs.key }} - restore-keys: ${{ inputs.restore-keys }} - - - name: setup github cache - id: gha-cache-ro - if: ${{ !contains(runner.name, 'nsc') && inputs.save == 'false' }} - uses: 'actions/cache/restore@v4' - with: - path: ${{ inputs.path }} - key: ${{ inputs.key }} - restore-keys: ${{ inputs.restore-keys }} - - # make the directory manually in case we didn't get a hit, so it doesn't fail on future steps - - id: scons-cache-setup - shell: bash - run: | - mkdir -p ${{ inputs.path }} - sudo chmod -R 777 ${{ inputs.path }} - sudo chown -R $USER ${{ inputs.path }} diff --git a/.github/workflows/auto_pr_review.yaml b/.github/workflows/auto_pr_review.yaml index d3cfa60d92..29149d8652 100644 --- a/.github/workflows/auto_pr_review.yaml +++ b/.github/workflows/auto_pr_review.yaml @@ -1,7 +1,7 @@ name: "PR review" on: pull_request_target: - types: [opened, reopened, synchronize, edited] + types: [ opened, reopened, synchronize, edited ] jobs: labeler: @@ -12,38 +12,38 @@ jobs: issues: write runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 with: submodules: false # Label PRs - - uses: actions/labeler@v5.0.0 + - uses: actions/labeler@v6 with: dot: true configuration-path: .github/labeler.yaml # Check PR target branch - name: check branch - uses: Vankka/pr-target-branch-action@def32ec9d93514138d6ac0132ee62e120a72aed5 + uses: Vankka/pr-target-branch-action@5da68a42bcb7b43d39104295a876a6f3f8d7908b if: github.repository == 'sunnypilot/sunnypilot' env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: - target: /^(?!master-new$).*/ + target: /^(?!master$).*/ exclude: /sunnypilot:.*/ change-to: ${{ github.base_ref }} already-exists-action: close_this - already-exists-comment: "Your PR should be made against the `master-new` branch" + already-exists-comment: "Your PR should be made against the `master` branch" update-pr-labels: name: Update fork's PR Labels runs-on: ubuntu-latest if: (github.event.pull_request.head.repo.fork && (contains(github.event_name, 'pull_request') && github.event.action == 'synchronize')) - env: - PR_LABEL: 'dev-c3' + env: + PR_LABEL: 'dev' TRUST_FORK_PR_LABEL: 'trust-fork-pr' steps: - - name: Check if PR has dev-c3 label + - name: Check if PR has dev label id: check-labels uses: actions/github-script@v7 with: @@ -55,33 +55,33 @@ jobs: repo: context.repo.repo, issue_number: prNumber }); - + const hasDevC3Label = labels.some(label => label.name === process.env.PR_LABEL); const hasTrustLabel = labels.some(label => label.name === process.env.TRUST_FORK_PR_LABEL); - + console.log(`PR #${prNumber} has ${process.env.PR_LABEL} label: ${hasDevC3Label}`); console.log(`PR #${prNumber} has ${process.env.TRUST_FORK_PR_LABEL} label: ${hasTrustLabel}`); - - core.setOutput('has-dev-c3', hasDevC3Label ? 'true' : 'false'); + + core.setOutput('has-dev', hasDevC3Label ? 'true' : 'false'); core.setOutput('has-trust', hasTrustLabel ? 'true' : 'false'); - + - name: Remove trust-fork-pr label if present - if: steps.check-labels.outputs.has-dev-c3 == 'true' && steps.check-labels.outputs.has-trust == 'true' + if: steps.check-labels.outputs.has-dev == 'true' && steps.check-labels.outputs.has-trust == 'true' uses: actions/github-script@v7 with: github-token: ${{ secrets.GITHUB_TOKEN }} script: | const prNumber = context.payload.pull_request.number; - + await github.rest.issues.removeLabel({ owner: context.repo.owner, repo: context.repo.repo, issue_number: prNumber, name: process.env.TRUST_FORK_PR_LABEL }); - + console.log(`Removed '${process.env.TRUST_FORK_PR_LABEL}' label from PR #${prNumber} as it received new commits`); - + // Add a comment to the PR await github.rest.issues.createComment({ owner: context.repo.owner, diff --git a/.github/workflows/badges.yaml b/.github/workflows/badges.yaml deleted file mode 100644 index 505148beac..0000000000 --- a/.github/workflows/badges.yaml +++ /dev/null @@ -1,37 +0,0 @@ -name: badges -on: - schedule: - - cron: '0 * * * *' - workflow_dispatch: - -env: - BASE_IMAGE: openpilot-base - DOCKER_REGISTRY: ghcr.io/commaai - RUN: docker run --shm-size 2G -v $PWD:/tmp/openpilot -w /tmp/openpilot -e PYTHONPATH=/tmp/openpilot -e NUM_JOBS -e JOB_ID -e GITHUB_ACTION -e GITHUB_REF -e GITHUB_HEAD_REF -e GITHUB_SHA -e GITHUB_REPOSITORY -e GITHUB_RUN_ID -v $GITHUB_WORKSPACE/.ci_cache/scons_cache:/tmp/scons_cache -v $GITHUB_WORKSPACE/.ci_cache/comma_download_cache:/tmp/comma_download_cache -v $GITHUB_WORKSPACE/.ci_cache/openpilot_cache:/tmp/openpilot_cache $DOCKER_REGISTRY/$BASE_IMAGE:latest /bin/bash -c - -jobs: - badges: - name: create badges - runs-on: ubuntu-latest - if: github.repository == 'sunnypilot/sunnypilot' - permissions: - contents: write - steps: - - uses: actions/checkout@v4 - with: - submodules: true - - uses: ./.github/workflows/setup-with-retry - - name: Push badges - run: | - ${{ env.RUN }} "scons -j$(nproc) && python3 selfdrive/ui/translations/create_badges.py" - - rm .gitattributes - - git checkout --orphan badges - git rm -rf --cached . - git config user.email "badge-researcher@sunnypilot.ai" - git config user.name "Badge Researcher" - - git add translation_badge.svg - git commit -m "Add/Update badges" - git push -f origin HEAD diff --git a/.github/workflows/build-all-tinygrad-models.yaml b/.github/workflows/build-all-tinygrad-models.yaml new file mode 100644 index 0000000000..0eedb04703 --- /dev/null +++ b/.github/workflows/build-all-tinygrad-models.yaml @@ -0,0 +1,306 @@ +name: Build and push all tinygrad models + +on: + workflow_dispatch: + inputs: + set_min_version: + description: 'Minimum selector version required for the models (see helpers.py or readme.md)' + required: true + type: string + +jobs: + setup: + runs-on: ubuntu-latest + outputs: + json_version: ${{ steps.get-json.outputs.json_version }} + recompiled_dir: ${{ steps.create-recompiled-dir.outputs.recompiled_dir }} + json_file: ${{ steps.get-json.outputs.json_file }} + model_matrix: ${{ steps.set-matrix.outputs.model_matrix }} + tinygrad_ref: ${{ steps.get-tinygrad-ref.outputs.tinygrad_ref }} + steps: + - name: Checkout sunnypilot repo + uses: actions/checkout@v4 + with: + repository: sunnypilot/sunnypilot + path: sunnypilot + submodules: recursive + + - name: Get tinygrad_repo ref + id: get-tinygrad-ref + run: | + cd sunnypilot + export PYTHONPATH=$(pwd) + ref=$(python3 openpilot/sunnypilot/models/tinygrad_ref.py) + echo "tinygrad_ref=$ref" >> $GITHUB_OUTPUT + echo "tinygrad_ref is $ref" + + - name: Checkout docs repo (sunnypilot-models, gh-pages) + uses: actions/checkout@v4 + with: + repository: sunnypilot/sunnypilot-models + ref: gh-pages + path: docs + ssh-key: ${{ secrets.CI_SUNNYPILOT_DOCS_PRIVATE_KEY }} + + - name: Get next JSON version to use (from GitHub docs repo) + id: get-json + run: | + cd docs/docs + latest=$(ls driving_models_v*.json | sed -E 's/.*_v([0-9]+)\.json/\1/' | sort -n | tail -1) + next=$((latest+1)) + json_file="driving_models_v${next}.json" + cp "driving_models_v${latest}.json" "$json_file" + echo "json_file=docs/docs/$json_file" >> $GITHUB_OUTPUT + echo "json_version=$((next+0))" >> $GITHUB_OUTPUT + echo "SRC_JSON_FILE=docs/docs/driving_models_v${latest}.json" >> $GITHUB_ENV + + - name: Extract tinygrad models + id: set-matrix + working-directory: docs/docs + run: | + jq -c '[.bundles[] | select(.runner=="tinygrad") | {ref, display_name: (.display_name | gsub(" \\([^)]*\\)"; "")), is_20hz}]' "$(basename "${SRC_JSON_FILE}")" > matrix.json + echo "model_matrix=$(cat matrix.json)" >> $GITHUB_OUTPUT + + - name: Set up SSH + uses: webfactory/ssh-agent@v0.9.0 + with: + ssh-private-key: ${{ secrets.GITLAB_SSH_PRIVATE_KEY }} + - run: | + mkdir -p ~/.ssh + ssh-keyscan -H gitlab.com >> ~/.ssh/known_hosts + + - name: Clone GitLab docs repo and create new recompiled dir + id: create-recompiled-dir + env: + GIT_SSH_COMMAND: 'ssh -o UserKnownHostsFile=~/.ssh/known_hosts' + run: | + git clone --depth 1 --filter=tree:0 --sparse git@gitlab.com:sunnypilot/public/${{ vars.MODELS_GITLAB }} gitlab_docs + cd gitlab_docs + git checkout main + git sparse-checkout set --no-cone models/ + cd models + latest_dir=$(ls -d recompiled* 2>/dev/null | sed -E 's/recompiled([0-9]+)/\1/' | sort -n | tail -1) + if [[ -z "$latest_dir" ]]; then + next_dir=1 + else + next_dir=$((latest_dir+1)) + fi + recompiled_dir="${next_dir}" + mkdir -p "recompiled${recompiled_dir}" + touch "recompiled${recompiled_dir}/.gitkeep" + cd ../.. + echo "recompiled_dir=$recompiled_dir" >> $GITHUB_OUTPUT + + - name: Push empty recompiled dir to GitLab + run: | + cd gitlab_docs + git add models/recompiled${{ steps.create-recompiled-dir.outputs.recompiled_dir }} + git config --global user.name "GitHub Action" + git config --global user.email "action@github.com" + git commit -m "Add recompiled${{ steps.create-recompiled-dir.outputs.recompiled_dir }} for build-all" || echo "No changes to commit" + git push origin main + + - name: Push new JSON to GitHub docs repo + run: | + cd docs + git pull origin gh-pages + git add docs/"$(basename ${{ steps.get-json.outputs.json_file }})" + git config --global user.name "GitHub Action" + git config --global user.email "action@github.com" + git commit -m "Add new ${{ steps.get-json.outputs.json_file }} for build-all" || echo "No changes to commit" + git push origin gh-pages + + get_and_build: + needs: [setup] + strategy: + matrix: + model: ${{ fromJson(needs.setup.outputs.model_matrix) }} + fail-fast: false + uses: ./.github/workflows/build-single-tinygrad-model.yaml + with: + upstream_branch: ${{ matrix.model.ref }} + custom_name: ${{ matrix.model.display_name }} + is_20hz: ${{ matrix.model.is_20hz }} + recompiled_dir: ${{ needs.setup.outputs.recompiled_dir }} + json_version: ${{ needs.setup.outputs.json_version }} + secrets: inherit + + retry_failed_models: + needs: [setup, get_and_build] + runs-on: ubuntu-latest + if: ${{ needs.setup.result != 'failure' && !cancelled() }} + outputs: + retry_matrix: ${{ steps.set-retry-matrix.outputs.retry_matrix }} + steps: + - uses: actions/download-artifact@v4 + with: + pattern: model-* + path: output + + - id: set-retry-matrix + run: | + echo '${{ needs.setup.outputs.model_matrix }}' > matrix.json + built=(); while IFS= read -r line; do built+=("$line"); done < <( + find output -maxdepth 1 -name 'model-*' -printf "%f\n" | sed -E 's/^model-//' | sed -E 's/-[0-9]+$//' | sed -E 's/ \([^)]*\)//' | awk '{gsub(/^ +| +$/, ""); print}' + ) + jq -c --argjson built "$(printf '%s\n' "${built[@]}" | jq -R . | jq -s .)" \ + 'map(select(.display_name as $n | ($built | index($n | gsub("^ +| +$"; "")) | not)))' matrix.json > retry_matrix.json + echo "retry_matrix=$(cat retry_matrix.json)" >> $GITHUB_OUTPUT + + retry_get_and_build: + needs: [setup, get_and_build, retry_failed_models] + if: ${{ needs.get_and_build.result == 'failure' || (needs.retry_failed_models.outputs.retry_matrix != '[]' && needs.retry_failed_models.outputs.retry_matrix != '') }} + strategy: + matrix: + model: ${{ fromJson(needs.retry_failed_models.outputs.retry_matrix) }} + fail-fast: false + uses: ./.github/workflows/build-single-tinygrad-model.yaml + with: + upstream_branch: ${{ matrix.model.ref }} + custom_name: ${{ matrix.model.display_name }} + is_20hz: ${{ matrix.model.is_20hz }} + recompiled_dir: ${{ needs.setup.outputs.recompiled_dir }} + json_version: ${{ needs.setup.outputs.json_version }} + artifact_suffix: -retry + secrets: inherit + + publish_models: + name: Publish models sequentially + needs: [setup, get_and_build, retry_failed_models, retry_get_and_build] + if: ${{ !cancelled() && (needs.get_and_build.result != 'failure' || needs.retry_get_and_build.result == 'success' || (needs.retry_failed_models.outputs.retry_matrix != '[]' && needs.retry_failed_models.outputs.retry_matrix != '')) }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + max-parallel: 1 + matrix: + model: ${{ fromJson(needs.setup.outputs.model_matrix) }} + env: + RECOMPILED_DIR: recompiled${{ needs.setup.outputs.recompiled_dir }} + JSON_FILE: ${{ needs.setup.outputs.json_file }} + ARTIFACT_NAME_INPUT: ${{ matrix.model.display_name }} + steps: + - name: Set up SSH + uses: webfactory/ssh-agent@v0.9.0 + with: + ssh-private-key: ${{ secrets.GITLAB_SSH_PRIVATE_KEY }} + + - name: Add GitLab.com SSH key to known_hosts + run: | + mkdir -p ~/.ssh + ssh-keyscan -H gitlab.com >> ~/.ssh/known_hosts + + - name: Clone GitLab docs repo + env: + GIT_SSH_COMMAND: 'ssh -o UserKnownHostsFile=~/.ssh/known_hosts' + run: | + echo "Cloning GitLab" + git clone --depth 1 --filter=tree:0 --sparse git@gitlab.com:sunnypilot/public/${{ vars.MODELS_GITLAB }} gitlab_docs + cd gitlab_docs + echo "checkout models/${RECOMPILED_DIR}" + git sparse-checkout set --no-cone models/${RECOMPILED_DIR} + git checkout main + cd .. + + - name: Checkout docs repo + uses: actions/checkout@v4 + with: + repository: sunnypilot/sunnypilot-models + ref: gh-pages + path: docs + ssh-key: ${{ secrets.CI_SUNNYPILOT_DOCS_PRIVATE_KEY }} + + - name: Validate recompiled dir and JSON version + run: | + if [ ! -d "gitlab_docs/models/$RECOMPILED_DIR" ]; then + echo "Recompiled dir $RECOMPILED_DIR does not exist in GitLab repo" + exit 1 + fi + if [ ! -f "$JSON_FILE" ]; then + echo "JSON file $JSON_FILE does not exist!" + exit 1 + fi + + - name: Download artifact name file + uses: actions/download-artifact@v4 + with: + name: artifact-name-${{ env.ARTIFACT_NAME_INPUT }} + path: artifact_name + + - name: Read artifact name + id: read-artifact-name + run: | + ARTIFACT_NAME=$(cat artifact_name/artifact_name.txt) + echo "artifact_name=$ARTIFACT_NAME" >> $GITHUB_OUTPUT + + - name: Download model artifact + uses: actions/download-artifact@v4 + with: + name: ${{ steps.read-artifact-name.outputs.artifact_name }} + path: output + + - name: Remove onnx files bc not needed for recompiled dir since they already exist from single build + run: | + find output -type f -name '*.onnx' -delete + find output -type f -name 'big_*.pkl' -delete + find output -type f -name 'dmonitoring_model_tinygrad.pkl' -delete + + - name: Copy model artifacts to gitlab + env: + ARTIFACT_NAME: ${{ steps.read-artifact-name.outputs.artifact_name }} + run: | + ARTIFACT_DIR="gitlab_docs/models/${RECOMPILED_DIR}/${ARTIFACT_NAME}" + mkdir -p "$ARTIFACT_DIR" + for path in output/*; do + if [ "$(basename "$path")" = "artifact_name.txt" ]; then + continue + fi + name="$(basename "$path")" + if [ -d "$path" ]; then + mkdir -p "$ARTIFACT_DIR/$name" + cp -r "$path"/* "$ARTIFACT_DIR/$name/" + echo "Copied dir $name -> $ARTIFACT_DIR/$name" + else + cp "$path" "$ARTIFACT_DIR/" + echo "Copied file $name -> $ARTIFACT_DIR/" + fi + done + + - name: Push recompiled dir to GitLab + env: + GITLAB_SSH_PRIVATE_KEY: ${{ secrets.GITLAB_SSH_PRIVATE_KEY }} + run: | + cd gitlab_docs + git checkout main + git pull origin main + for d in models/"$RECOMPILED_DIR"/*/; do + git sparse-checkout add "$d" + done + git add models/"$RECOMPILED_DIR" + git config --global user.name "GitHub Action" + git config --global user.email "action@github.com" + git commit -m "Update $RECOMPILED_DIR with model from build-all-tinygrad-models" || echo "No changes to commit" + git push origin main + - run: | + cd docs + git pull origin gh-pages + + - name: update json + run: | + ARGS="" + [ -n "${{ inputs.set_min_version }}" ] && ARGS="$ARGS --set-min-version \"${{ inputs.set_min_version }}\"" + ARGS="$ARGS --sort-by-date" + ARGS="$ARGS --tinygrad-ref \"${{ needs.setup.outputs.tinygrad_ref }}\"" + eval python3 docs/json_parser.py \ + --json-path "$JSON_FILE" \ + --recompiled-dir "gitlab_docs/models/$RECOMPILED_DIR" \ + $ARGS + + - name: Push updated json to GitHub + run: | + cd docs + git config --global user.name "GitHub Action" + git config --global user.email "action@github.com" + git checkout gh-pages + git add docs/"$(basename $JSON_FILE)" + git commit -m "Update $(basename $JSON_FILE) after recompiling model" || echo "No changes to commit" + git push origin gh-pages diff --git a/.github/workflows/build-single-tinygrad-model.yaml b/.github/workflows/build-single-tinygrad-model.yaml new file mode 100644 index 0000000000..f10f1b71a3 --- /dev/null +++ b/.github/workflows/build-single-tinygrad-model.yaml @@ -0,0 +1,238 @@ +name: Build Single Tinygrad Model and Push + +on: + workflow_call: + inputs: + upstream_branch: + description: 'Upstream commit to build from' + required: true + type: string + custom_name: + description: 'Custom name for the model (no date, only name)' + required: false + type: string + recompiled_dir: + description: 'Existing recompiled directory number (e.g. 3 for recompiled3)' + required: true + type: string + json_version: + description: 'driving_models version number to update (e.g. 5 for driving_models_v5.json)' + required: true + type: string + artifact_suffix: + description: 'Suffix for artifact name' + required: false + type: string + default: '' + is_20hz: + description: 'Is this a 20Hz model' + required: false + type: boolean + default: true + bypass_push: + description: 'Bypass pushing to GitLab for build-all' + required: false + default: true + type: boolean + workflow_dispatch: + inputs: + upstream_branch: + description: 'Upstream commit to build from' + required: true + type: string + custom_name: + description: 'Custom name for the model (no date, only name)' + required: false + type: string + is_20hz: + description: 'Is this a 20Hz model' + required: false + type: boolean + default: true + recompiled_dir: + description: 'Existing recompiled directory number (e.g. 3 for recompiled3)' + required: true + type: string + json_version: + description: 'driving_models version number to update (e.g. 5 for driving_models_v5.json)' + required: true + type: string + model_folder: + description: 'Model folder' + type: choice + default: 'None' + options: + - None + - Simple Plan Models + - Space Lab Models + - TR Models + - DTR Models + - Custom Merge Models + - FOF series models + - Other + custom_model_folder: + description: 'Custom model folder name (if "Other" selected)' + required: false + type: string + generation: + description: 'Model generation' + required: false + type: string + version: + description: 'Minimum selector version' + required: false + type: string +env: + RECOMPILED_DIR: recompiled${{ inputs.recompiled_dir }} + JSON_FILE: docs/docs/driving_models_v${{ inputs.json_version }}.json + +jobs: + build_model: + uses: ./.github/workflows/sunnypilot-build-model.yaml + with: + upstream_branch: ${{ inputs.upstream_branch }} + custom_name: ${{ inputs.custom_name || inputs.upstream_branch }} + is_20hz: ${{ inputs.is_20hz }} + artifact_suffix: ${{ inputs.artifact_suffix }} + secrets: inherit + + publish_model: + if: ${{ !inputs.bypass_push && !cancelled() }} + concurrency: + group: gitlab-push-${{ inputs.recompiled_dir }} + cancel-in-progress: false + needs: build_model + runs-on: ubuntu-latest + steps: + - name: Set up SSH + uses: webfactory/ssh-agent@v0.9.0 + with: + ssh-private-key: ${{ secrets.GITLAB_SSH_PRIVATE_KEY }} + + - name: Add GitLab.com SSH key to known_hosts + run: | + mkdir -p ~/.ssh + ssh-keyscan -H gitlab.com >> ~/.ssh/known_hosts + + - name: Clone GitLab docs repo + env: + GIT_SSH_COMMAND: 'ssh -o UserKnownHostsFile=~/.ssh/known_hosts' + run: | + echo "Cloning GitLab" + git clone --depth 1 --filter=tree:0 --sparse git@gitlab.com:sunnypilot/public/${{ vars.MODELS_GITLAB }} gitlab_docs + cd gitlab_docs + echo "checkout models/${RECOMPILED_DIR}" + git sparse-checkout set --no-cone models/${RECOMPILED_DIR} + git checkout main + cd .. + + - name: Checkout docs repo + uses: actions/checkout@v4 + with: + repository: sunnypilot/sunnypilot-models + ref: gh-pages + path: docs + ssh-key: ${{ secrets.CI_SUNNYPILOT_DOCS_PRIVATE_KEY }} + + - name: Validate recompiled dir and JSON version + run: | + if [ ! -d "gitlab_docs/models/$RECOMPILED_DIR" ]; then + echo "Recompiled dir $RECOMPILED_DIR does not exist in GitLab repo" + exit 1 + fi + if [ ! -f "$JSON_FILE" ]; then + echo "JSON file $JSON_FILE does not exist!" + exit 1 + fi + + - name: Download artifact name file + uses: actions/download-artifact@v4 + with: + name: artifact-name-${{ inputs.custom_name || inputs.upstream_branch }} + path: artifact_name + + - name: Read artifact name + id: read-artifact-name + run: | + ARTIFACT_NAME=$(cat artifact_name/artifact_name.txt) + echo "artifact_name=$ARTIFACT_NAME" >> $GITHUB_OUTPUT + + - name: Download and extract model artifact + uses: actions/download-artifact@v4 + with: + name: ${{ steps.read-artifact-name.outputs.artifact_name }} + path: output + + - name: Remove unwanted files + run: | + find output -type f -name 'dmonitoring_model_tinygrad.pkl' -delete + find output -type f -name 'dmonitoring_model.onnx' -delete + + - name: Copy model artifact(s) to GitLab recompiled dir + env: + ARTIFACT_NAME: ${{ steps.read-artifact-name.outputs.artifact_name }} + run: | + ARTIFACT_DIR="gitlab_docs/models/${RECOMPILED_DIR}/${ARTIFACT_NAME}" + mkdir -p "$ARTIFACT_DIR" + for path in output/*; do + if [ "$(basename "$path")" = "artifact_name.txt" ]; then + continue + fi + name="$(basename "$path")" + if [ -d "$path" ]; then + mkdir -p "$ARTIFACT_DIR/$name" + cp -r "$path"/* "$ARTIFACT_DIR/$name/" + echo "Copied dir $name -> $ARTIFACT_DIR/$name" + else + cp "$path" "$ARTIFACT_DIR/" + echo "Copied file $name -> $ARTIFACT_DIR/" + fi + done + + - name: Push recompiled dir to GitLab + env: + GITLAB_SSH_PRIVATE_KEY: ${{ secrets.GITLAB_SSH_PRIVATE_KEY }} + run: | + cd gitlab_docs + git checkout main + git pull origin main + for d in models/"$RECOMPILED_DIR"/*/; do + git sparse-checkout add "$d" + done + git add models/"$RECOMPILED_DIR" + git config --global user.name "GitHub Action" + git config --global user.email "action@github.com" + git commit -m "Create/Update $RECOMPILED_DIR with new/updated model from build-single-tinygrad-model" || echo "No changes to commit" + git push origin main + + - run: | + cd docs + git pull origin gh-pages + + - name: Run json_parser.py to update JSON + run: | + FOLDER="${{ inputs.model_folder }}" + if [ "$FOLDER" = "Other" ]; then + FOLDER="${{ inputs.custom_model_folder }}" + fi + ARGS="" + if [ "$FOLDER" != "None" ] && [ -n "$FOLDER" ]; then + ARGS="$ARGS --model-folder \"$FOLDER\"" + fi + [ -n "${{ inputs.generation }}" ] && ARGS="$ARGS --generation \"${{ inputs.generation }}\"" + [ -n "${{ inputs.version }}" ] && ARGS="$ARGS --version \"${{ inputs.version }}\"" + eval python3 docs/json_parser.py \ + --json-path "$JSON_FILE" \ + --recompiled-dir "gitlab_docs/models/$RECOMPILED_DIR" \ + --sort-by-date \ + $ARGS + + - name: Push updated JSON to GitHub docs repo + run: | + cd docs + git config --global user.name "GitHub Action" + git config --global user.email "action@github.com" + git checkout gh-pages + git add docs/"$(basename $JSON_FILE)" + git commit -m "Update $(basename $JSON_FILE) after recompiling model" || echo "No changes to commit" + git push origin gh-pages diff --git a/.github/workflows/cereal_validation.yaml b/.github/workflows/cereal_validation.yaml index 5d75b6bc13..0c87688bf1 100644 --- a/.github/workflows/cereal_validation.yaml +++ b/.github/workflows/cereal_validation.yaml @@ -4,10 +4,9 @@ on: push: branches: - master - - master-new pull_request: paths: - - 'cereal/**' + - 'openpilot/cereal/**' workflow_dispatch: workflow_call: inputs: @@ -17,61 +16,82 @@ on: type: string concurrency: - group: cereal-validation-ci-run-${{ inputs.run_number }}-${{ github.event_name == 'push' && (github.ref == 'refs/heads/master' || github.ref == 'refs/heads/master-new') && github.run_id || github.head_ref || github.ref }}-${{ github.workflow }}-${{ github.event_name }} + group: cereal-validation-ci-run-${{ inputs.run_number }}-${{ github.event_name == 'push' && github.ref == 'refs/heads/master' && github.run_id || github.head_ref || github.ref }}-${{ github.workflow }}-${{ github.event_name }} cancel-in-progress: true env: - PYTHONWARNINGS: error - BASE_IMAGE: openpilot-base - BUILD: selfdrive/test/docker_build.sh base - RUN: docker run --shm-size 2G -v $PWD:/tmp/openpilot -w /tmp/openpilot -e CI=1 -e PYTHONWARNINGS=error -e FILEREADER_CACHE=1 -e PYTHONPATH=/tmp/openpilot -e NUM_JOBS -e JOB_ID -e GITHUB_ACTION -e GITHUB_REF -e GITHUB_HEAD_REF -e GITHUB_SHA -e GITHUB_REPOSITORY -e GITHUB_RUN_ID -v $GITHUB_WORKSPACE/.ci_cache/scons_cache:/tmp/scons_cache -v $GITHUB_WORKSPACE/.ci_cache/comma_download_cache:/tmp/comma_download_cache -v $GITHUB_WORKSPACE/.ci_cache/openpilot_cache:/tmp/openpilot_cache $BASE_IMAGE /bin/bash -c + CI: 1 jobs: - generate_cereal_artifact: - name: Generate cereal validation artifacts - runs-on: ubuntu-24.04 - steps: - - uses: actions/checkout@v4 - with: - submodules: true - - uses: ./.github/workflows/setup-with-retry - - name: Build openpilot - run: ${{ env.RUN }} "scons -j$(nproc) cereal" - - name: Generate the log file - run: | - ${{ env.RUN }} "cereal/messaging/tests/validate_sp_cereal_upstream.py -g -f schema_instances.bin" && \ - ls -la - ls -la cereal/messaging/tests - - name: 'Prepare artifact' - run: | - mkdir -p "cereal/messaging/tests/cereal_validations" - cp cereal/messaging/tests/validate_sp_cereal_upstream.py "cereal/messaging/tests/cereal_validations/validate_sp_cereal_upstream.py" - cp schema_instances.bin "cereal/messaging/tests/cereal_validations/schema_instances.bin" - - name: 'Upload Artifact' - uses: actions/upload-artifact@v4 - with: - name: cereal_validations - path: cereal/messaging/tests/cereal_validations - validate_cereal_with_upstream: name: Validate cereal with Upstream runs-on: ubuntu-24.04 - needs: generate_cereal_artifact steps: - - uses: actions/checkout@v4 + - name: Checkout sunnypilot cereal + uses: actions/checkout@v6 + with: + sparse-checkout: | + openpilot/cereal + uv.lock + submodules: false + + - name: Init sunnypilot opendbc submodule + run: git submodule update --init --depth 1 opendbc_repo + + - name: Locate sunnypilot capnp import paths + id: locate-sp-capnp + run: | + SP_IMPORT_ARGS="" + SP_CAR_CAPNP=$(find opendbc_repo -maxdepth 4 -name car.capnp -path '*/opendbc/car/car.capnp' -printf '%h\n' -quit) + if [ -n "$SP_CAR_CAPNP" ]; then + SP_IMPORT_ARGS="-I $SP_CAR_CAPNP" + echo "Found sunnypilot car.capnp at: $SP_CAR_CAPNP" + fi + echo "import_args=$SP_IMPORT_ARGS" >> "$GITHUB_OUTPUT" + + - name: Checkout upstream openpilot + uses: actions/checkout@v6 with: repository: 'commaai/openpilot' - submodules: true + path: upstream_openpilot ref: "refs/heads/master" - - uses: ./.github/workflows/setup-with-retry - - name: Build openpilot - run: ${{ env.RUN }} "scons -j$(nproc) cereal" - - name: Download build artifacts - uses: actions/download-artifact@v4 - with: - name: cereal_validations - path: cereal/messaging/tests/cereal_validations - - name: 'Run the validation' + + - name: Init upstream opendbc submodule + working-directory: upstream_openpilot + run: git submodule update --init --depth 1 opendbc_repo + + - name: Locate upstream capnp paths + id: locate-capnp run: | - chmod +x cereal/messaging/tests/cereal_validations/validate_sp_cereal_upstream.py - ${{ env.RUN }} "cereal/messaging/tests/cereal_validations/validate_sp_cereal_upstream.py -r -f cereal/messaging/tests/cereal_validations/schema_instances.bin" + CEREAL_DIR=$(find upstream_openpilot -maxdepth 4 -name log.capnp -path '*/cereal/log.capnp' -printf '%h\n' -quit) + if [ -z "$CEREAL_DIR" ]; then + echo "::error::Could not locate cereal/log.capnp in upstream openpilot" + exit 1 + fi + echo "cereal_dir=$CEREAL_DIR" >> "$GITHUB_OUTPUT" + echo "Found upstream cereal at: $CEREAL_DIR" + + IMPORT_ARGS="" + CAR_CAPNP=$(find upstream_openpilot -maxdepth 5 -name car.capnp -path '*/opendbc/car/car.capnp' -printf '%h\n' -quit) + if [ -n "$CAR_CAPNP" ]; then + IMPORT_ARGS="-I $CAR_CAPNP" + echo "Found car.capnp at: $CAR_CAPNP" + fi + echo "import_args=$IMPORT_ARGS" >> "$GITHUB_OUTPUT" + + - name: Install pycapnp + run: | + PYCAPNP_VER=$(python3 -c "import re; m=re.search(r'name = \"pycapnp\"\nversion = \"([^\"]+)\"', open('uv.lock').read()); print(m.group(1))") + pip install "pycapnp==${PYCAPNP_VER}" + + - name: Generate sunnypilot schema + run: | + python3 openpilot/cereal/messaging/tests/validate_sp_cereal_upstream.py \ + -g -f /tmp/sp_schema.json --cereal-dir openpilot/cereal \ + ${{ steps.locate-sp-capnp.outputs.import_args }} + + - name: Validate against upstream + run: | + python3 openpilot/cereal/messaging/tests/validate_sp_cereal_upstream.py \ + -r -f /tmp/sp_schema.json --cereal-dir ${{ steps.locate-capnp.outputs.cereal_dir }} \ + ${{ steps.locate-capnp.outputs.import_args }} diff --git a/.github/workflows/ci_weekly_report.yaml b/.github/workflows/ci_weekly_report.yaml deleted file mode 100644 index b96a5a56a8..0000000000 --- a/.github/workflows/ci_weekly_report.yaml +++ /dev/null @@ -1,101 +0,0 @@ -name: weekly CI test report -on: - schedule: - - cron: '37 9 * * 1' # 9:37AM UTC -> 2:37AM PST every monday - workflow_dispatch: - inputs: - ci_runs: - description: 'The amount of runs to trigger in CI test report' -concurrency: - group: ${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: true - -env: - CI_RUNS: ${{ github.event.inputs.ci_runs || '50' }} - -jobs: - setup: - if: github.repository == 'sunnypilot/sunnypilot' - runs-on: ubuntu-latest - outputs: - ci_runs: ${{ steps.ci_runs_setup.outputs.matrix }} - steps: - - id: ci_runs_setup - name: CI_RUNS=${{ env.CI_RUNS }} - run: | - matrix=$(python3 -c "import json; print(json.dumps({ 'run_number' : list(range(${{ env.CI_RUNS }})) }))") - echo "matrix=$matrix" >> $GITHUB_OUTPUT - - ci_matrix_run: - needs: [ setup ] - strategy: - fail-fast: false - matrix: ${{fromJSON(needs.setup.outputs.ci_runs)}} - uses: sunnypilot/sunnypilot/.github/workflows/ci_weekly_run.yaml@master - with: - run_number: ${{ matrix.run_number }} - - report: - needs: [ci_matrix_run] - runs-on: ubuntu-latest - if: always() - steps: - - name: Get job results - uses: actions/github-script@v7 - id: get-job-results - with: - script: | - const jobs = await github - .paginate("GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt}/jobs", { - owner: "commaai", - repo: "${{ github.event.repository.name }}", - run_id: "${{ github.run_id }}", - attempt: "${{ github.run_attempt }}", - }) - var report = {} - jobs.slice(1, jobs.length-1).forEach(job => { - if (job.conclusion === "skipped") return; - const jobName = job.name.split(" / ")[2]; - const runRegex = /\((.*?)\)/; - const run = job.name.match(runRegex)[1]; - report[jobName] = report[jobName] || { successes: [], failures: [], canceled: [] }; - switch (job.conclusion) { - case "success": - report[jobName].successes.push({ "run_number": run, "link": job.html_url}); break; - case "failure": - report[jobName].failures.push({ "run_number": run, "link": job.html_url }); break; - case "canceled": - report[jobName].canceled.push({ "run_number": run, "link": job.html_url }); break; - } - }); - return JSON.stringify({"jobs": report}); - - - name: Add job results to summary - env: - JOB_RESULTS: ${{ fromJSON(steps.get-job-results.outputs.result) }} - run: | - cat <> template.html - - - - - - - - - - - {% for key in jobs.keys() %} - - - - - - {% endfor %} -
Job✅ Passing❌ Failure Details
{% for i in range(5) %}{% if i+1 <= (5 * jobs[key]["successes"]|length // ${{ env.CI_RUNS }}) %}🟩{% else %}🟥{% endif %}{% endfor%}{{ key }}{{ 100 * jobs[key]["successes"]|length // ${{ env.CI_RUNS }} }}%{% if jobs[key]["failures"]|length > 0 %}
{% for failure in jobs[key]["failures"] %}Log for run #{{ failure['run_number'] }}
{% endfor %}
{% else %}{% endif %}
- EOF - - pip install jinja2-cli - echo $JOB_RESULTS | jinja2 template.html > report.html - echo "# CI Test Report - ${{ env.CI_RUNS }} Runs" >> $GITHUB_STEP_SUMMARY - cat report.html >> $GITHUB_STEP_SUMMARY diff --git a/.github/workflows/ci_weekly_run.yaml b/.github/workflows/ci_weekly_run.yaml deleted file mode 100644 index a2a8ab31a2..0000000000 --- a/.github/workflows/ci_weekly_run.yaml +++ /dev/null @@ -1,17 +0,0 @@ -name: weekly CI test run -on: - workflow_call: - inputs: - run_number: - required: true - type: string - -concurrency: - group: ci-run-${{ inputs.run_number }}-${{ github.ref }} - cancel-in-progress: true - -jobs: - selfdrive_tests: - uses: sunnypilot/sunnypilot/.github/workflows/selfdrive_tests.yaml@master - with: - run_number: ${{ inputs.run_number }} diff --git a/.github/workflows/compile-openpilot/action.yaml b/.github/workflows/compile-openpilot/action.yaml deleted file mode 100644 index 87590b41cb..0000000000 --- a/.github/workflows/compile-openpilot/action.yaml +++ /dev/null @@ -1,21 +0,0 @@ -name: 'compile openpilot' - -runs: - using: "composite" - steps: - - shell: bash - name: Build openpilot with all flags - run: | - ${{ env.RUN }} "scons -j$(nproc)" - ${{ env.RUN }} "release/check-dirty.sh" - - shell: bash - name: Cleanup scons cache and rebuild - run: | - ${{ env.RUN }} "rm -rf /tmp/scons_cache/* && \ - scons -j$(nproc) --cache-populate" - - name: Save scons cache - uses: actions/cache/save@v4 - if: (github.ref == 'refs/heads/master' || github.ref == 'refs/heads/master-new') - with: - path: .ci_cache/scons_cache - key: scons-${{ runner.arch }}-${{ env.CACHE_COMMIT_DATE }}-${{ github.sha }} diff --git a/.github/workflows/diff_report.yaml b/.github/workflows/diff_report.yaml new file mode 100644 index 0000000000..0f706ea2ed --- /dev/null +++ b/.github/workflows/diff_report.yaml @@ -0,0 +1,57 @@ +name: diff report + +on: + pull_request_target: + types: [opened, synchronize, reopened] + +jobs: + comment: + name: comment + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: read + pull-requests: write + actions: read + steps: + - name: Wait for process replay + id: wait + continue-on-error: true + uses: lewagon/wait-on-check-action@1d57e2c51a58d812d2765e036a028b6bdb5a6154 + with: + ref: ${{ github.event.pull_request.head.sha }} + check-name: process replay + repo-token: ${{ secrets.GITHUB_TOKEN }} + allowed-conclusions: success,failure + wait-interval: 20 + - name: Get tests run ID + if: steps.wait.outcome == 'success' + id: tests-run + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + run_id=$(gh api \ + "repos/${{ github.repository }}/actions/workflows/tests.yaml/runs?event=pull_request&head_sha=${{ github.event.pull_request.head.sha }}&per_page=1" \ + --jq '.workflow_runs[0].id // empty') + if [ -z "$run_id" ]; then + echo "No tests.yaml run found for ${{ github.event.pull_request.head.sha }}" >&2 + exit 1 + fi + echo "run-id=$run_id" >> "$GITHUB_OUTPUT" + - name: Download diff + if: steps.wait.outcome == 'success' + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + repository: ${{ github.repository }} + run-id: ${{ steps.tests-run.outputs.run-id }} + name: diff_report_${{ github.event.number }} + path: . + - name: Comment on PR + if: steps.wait.outcome == 'success' + uses: thollander/actions-comment-pull-request@24bffb9b452ba05a4f3f77933840a6a841d1b32b + with: + file-path: diff_report.txt + comment-tag: diff_report + pr-number: ${{ github.event.number }} + github-token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/docs.yaml b/.github/workflows/docs.yaml index ce225034d9..0af94ba0da 100644 --- a/.github/workflows/docs.yaml +++ b/.github/workflows/docs.yaml @@ -22,19 +22,19 @@ jobs: steps: - uses: commaai/timeout@v1 - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 with: submodules: true # Build - name: Build docs run: | - # TODO: can we install just the "docs" dependency group without the normal deps? - pip install mkdocs - mkdocs build + git lfs pull + pip install zensical + python scripts/docs.py build # Push to docs.comma.ai - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 if: github.ref == 'refs/heads/master' && github.repository == 'sunnypilot/sunnypilot' with: path: openpilot-docs @@ -45,7 +45,7 @@ jobs: run: | set -x - source release/identity.sh + source tools/release/identity.sh cd openpilot-docs git checkout --orphan tmp diff --git a/.github/workflows/jenkins-pr-trigger.yaml b/.github/workflows/jenkins-pr-trigger.yaml index db1d524018..ebb14d5dba 100644 --- a/.github/workflows/jenkins-pr-trigger.yaml +++ b/.github/workflows/jenkins-pr-trigger.yaml @@ -5,14 +5,54 @@ on: types: [created, edited] jobs: - # TODO: gc old branches in a separate job in this workflow + cleanup-branches: + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - name: Delete stale Jenkins branches + uses: actions/github-script@v9 + with: + script: | + const cutoff = Date.now() - 24 * 60 * 60 * 1000; + const prefixes = ['tmp-jenkins', '__jenkins']; + + for await (const response of github.paginate.iterator(github.rest.repos.listBranches, { + owner: context.repo.owner, + repo: context.repo.repo, + per_page: 100, + })) { + for (const branch of response.data) { + if (!prefixes.some(p => branch.name.startsWith(p))) continue; + + const { data: commit } = await github.rest.repos.getCommit({ + owner: context.repo.owner, + repo: context.repo.repo, + ref: branch.commit.sha, + }); + + const commitDate = new Date(commit.commit.committer.date).getTime(); + if (commitDate < cutoff) { + console.log(`Deleting branch: ${branch.name} (last commit: ${commit.commit.committer.date})`); + await github.rest.git.deleteRef({ + owner: context.repo.owner, + repo: context.repo.repo, + ref: `heads/${branch.name}`, + }); + } + } + } + scan-comments: runs-on: ubuntu-latest if: ${{ github.event.issue.pull_request }} + permissions: + contents: write + issues: write steps: - name: Check for trigger phrase id: check_comment - uses: actions/github-script@v7 + uses: actions/github-script@v9 with: script: | const triggerPhrase = "trigger-jenkins"; @@ -32,7 +72,7 @@ jobs: - name: Checkout repository if: steps.check_comment.outputs.result == 'true' - uses: actions/checkout@v4 + uses: actions/checkout@v7 with: ref: refs/pull/${{ github.event.issue.number }}/head @@ -43,3 +83,14 @@ jobs: git config --global user.email "github-actions[bot]@users.noreply.github.com" git checkout -b tmp-jenkins-${{ github.event.issue.number }} GIT_LFS_SKIP_PUSH=1 git push -f origin tmp-jenkins-${{ github.event.issue.number }} + + - name: Delete trigger comment + if: steps.check_comment.outputs.result == 'true' && always() + uses: actions/github-script@v9 + with: + script: | + await github.rest.issues.deleteComment({ + owner: context.repo.owner, + repo: context.repo.repo, + comment_id: context.payload.comment.id, + }); diff --git a/.github/workflows/lfs-maintenance.yaml b/.github/workflows/lfs-maintenance.yaml index 954dc9128d..3b92996f82 100644 --- a/.github/workflows/lfs-maintenance.yaml +++ b/.github/workflows/lfs-maintenance.yaml @@ -9,11 +9,11 @@ on: - cron: '0 0 * * *' # Runs at 00:00 UTC every day push: branches: - - 'master-new' + - 'master' pull_request: branches: - - 'master-new' - workflow_dispatch: # enables manual triggering + - 'master' + workflow_dispatch: # enables manual triggering inputs: upstream_branch: default: 'master' @@ -30,7 +30,7 @@ jobs: with: repository: 'commaai/openpilot' ref: ${{ inputs.upstream_branch }} - + - name: LFS Fetch run: | git lfs fetch @@ -48,7 +48,7 @@ jobs: - name: Add GitLab public keys run: | ssh-keyscan -H gitlab.com >> ~/.ssh/known_hosts - + - name: Ensure branch run: | if git symbolic-ref -q HEAD >/dev/null; then @@ -65,8 +65,21 @@ jobs: echo ' pushurl = ${{ env.LFS_PUSH_URL }}' >> .lfsconfig echo ' locksverify = false' >> .lfsconfig + - name: Configure LFS transfer settings + run: | + git config lfs.activitytimeout 300 + git config lfs.transfer.maxretries 5 + git config lfs.concurrenttransfers 4 + - name: Push LFS id: sync-and-commit run: | git lfs ls-files -l - git lfs push --all origin \ No newline at end of file + for attempt in 1 2 3; do + echo "Push attempt $attempt..." + git lfs push --all origin && exit 0 + echo "Attempt $attempt failed, retrying in 30s..." + sleep 30 + done + echo "All push attempts failed" + exit 1 diff --git a/.github/workflows/model_review.yaml b/.github/workflows/model_review.yaml index 0e1825864c..82c732dc3b 100644 --- a/.github/workflows/model_review.yaml +++ b/.github/workflows/model_review.yaml @@ -4,7 +4,7 @@ on: pull_request: types: [opened, reopened, synchronize] paths: - - 'selfdrive/modeld/models/*.onnx' + - 'openpilot/selfdrive/modeld/models/*.onnx' workflow_dispatch: jobs: @@ -16,27 +16,27 @@ jobs: if: github.repository == 'commaai/openpilot' steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v7 + with: + submodules: true - name: Checkout master - uses: actions/checkout@v4 + uses: actions/checkout@v7 with: ref: master path: base - run: git lfs pull - run: cd base && git lfs pull - - run: pip install onnx - - name: scripts/reporter.py id: report run: | echo "content<> $GITHUB_OUTPUT echo "## Model Review" >> $GITHUB_OUTPUT - MASTER_PATH=${{ github.workspace }}/base python scripts/reporter.py >> $GITHUB_OUTPUT + PYTHONPATH=${{ github.workspace }} MASTER_PATH=${{ github.workspace }}/base python scripts/reporter.py >> $GITHUB_OUTPUT echo "EOF" >> $GITHUB_OUTPUT - name: Post model report comment - uses: marocchino/sticky-pull-request-comment@baa7203ed60924babbe5dcd0ac8eae3b66ec5e16 + uses: marocchino/sticky-pull-request-comment@0ea0beb66eb9baf113663a64ec522f60e49231c0 with: header: model-review message: ${{ steps.report.outputs.content }} \ No newline at end of file diff --git a/.github/workflows/post-to-discourse/action.yml b/.github/workflows/post-to-discourse/action.yml new file mode 100644 index 0000000000..55232ce0e1 --- /dev/null +++ b/.github/workflows/post-to-discourse/action.yml @@ -0,0 +1,105 @@ +name: 'Post to Discourse' +description: 'Posts a message to a Discourse topic (existing or new)' + +inputs: + discourse-url: + description: 'Discourse instance URL (e.g., https://discourse.example.com)' + required: true + api-key: + description: 'Discourse API key' + required: true + api-username: + description: 'Discourse API username' + required: true + topic-id: + description: 'Discourse topic ID to post to (use this OR category-id + title)' + required: false + category-id: + description: 'Category ID for new topic (required if topic-id not provided)' + required: false + title: + description: 'Title for new topic (required if topic-id not provided)' + required: false + message: + description: 'Message content (markdown supported)' + required: true + +outputs: + post-number: + description: 'The post number in the topic' + value: ${{ steps.post.outputs.post_number }} + post-url: + description: 'Direct URL to the post' + value: ${{ steps.post.outputs.post_url }} + topic-id: + description: 'The topic ID (useful when creating a new topic)' + value: ${{ steps.post.outputs.topic_id }} + +runs: + using: "composite" + steps: + - name: Post to Discourse + id: post + shell: bash + run: | + # Validate inputs + if [ -z "${{ inputs.topic-id }}" ] && ([ -z "${{ inputs.category-id }}" ] || [ -z "${{ inputs.title }}" ]); then + echo "❌ Error: Must provide either topic-id OR both category-id and title" + exit 1 + fi + + if [ -n "${{ inputs.topic-id }}" ] && ([ -n "${{ inputs.category-id }}" ] || [ -n "${{ inputs.title }}" ]); then + echo "⚠️ Warning: Both topic-id and category-id/title provided. Will post to existing topic." + fi + + # Determine if creating new topic or posting to existing + if [ -n "${{ inputs.topic-id }}" ]; then + echo "📝 Posting to existing topic ID: ${{ inputs.topic-id }}" + + # Create JSON payload for posting to existing topic + PAYLOAD=$(jq -n \ + --arg content '${{ inputs.message }}' \ + --arg topic_id "${{ inputs.topic-id }}" \ + '{topic_id: $topic_id, raw: $content}') + else + echo "✨ Creating new topic: ${{ inputs.title }}" + + # Create JSON payload for new topic + PAYLOAD=$(jq -n \ + --arg content '${{ inputs.message }}' \ + --arg title "${{ inputs.title }}" \ + --arg category "${{ inputs.category-id }}" \ + '{title: $title, category: ($category | tonumber), raw: $content}') + fi + + # Post to Discourse + RESPONSE=$(curl -s -w "\n%{http_code}" \ + -X POST "${{ inputs.discourse-url }}/posts.json" \ + -H "Content-Type: application/json" \ + -H "Api-Key: ${{ inputs.api-key }}" \ + -H "Api-Username: ${{ inputs.api-username }}" \ + -d "$PAYLOAD") + + HTTP_CODE=$(echo "$RESPONSE" | tail -n1) + BODY=$(echo "$RESPONSE" | sed '$d') + + if [ "$HTTP_CODE" -ge 200 ] && [ "$HTTP_CODE" -lt 300 ]; then + echo "✅ Successfully posted to Discourse!" + + POST_NUMBER=$(echo "$BODY" | jq -r '.post_number // "unknown"') + TOPIC_ID=$(echo "$BODY" | jq -r '.topic_id // "${{ inputs.topic-id }}"') + POST_URL="${{ inputs.discourse-url }}/t/${TOPIC_ID}/${POST_NUMBER}" + + echo "post_number=${POST_NUMBER}" >> $GITHUB_OUTPUT + echo "post_url=${POST_URL}" >> $GITHUB_OUTPUT + echo "topic_id=${TOPIC_ID}" >> $GITHUB_OUTPUT + + echo "Topic ID: ${TOPIC_ID}" + echo "Post number: ${POST_NUMBER}" + echo "URL: ${POST_URL}" + else + echo "❌ Failed to post to Discourse" + echo "HTTP Code: ${HTTP_CODE}" + echo "Response: ${BODY}" + exit 1 + fi \ No newline at end of file diff --git a/.github/workflows/prebuilt.yaml b/.github/workflows/prebuilt.yaml index 61e3f3bc4f..aeb0f11d84 100644 --- a/.github/workflows/prebuilt.yaml +++ b/.github/workflows/prebuilt.yaml @@ -6,7 +6,7 @@ on: env: DOCKER_LOGIN: docker login ghcr.io -u ${{ github.actor }} -p ${{ secrets.GITHUB_TOKEN }} - BUILD: selfdrive/test/docker_build.sh prebuilt + BUILD: release/ci/docker_build_sp.sh jobs: build_prebuilt: @@ -28,8 +28,8 @@ jobs: wait-interval: 30 running-workflow-name: 'build prebuilt' repo-token: ${{ secrets.GITHUB_TOKEN }} - check-regexp: ^((?!.*(build master-ci).*).)*$ - - uses: actions/checkout@v4 + check-regexp: ^((?!.*(build master-ci|create badges).*).)*$ + - uses: actions/checkout@v6 with: submodules: true - run: git lfs pull diff --git a/.github/workflows/release-drafter.yml b/.github/workflows/release-drafter.yml index 62712a770c..c072e98e24 100644 --- a/.github/workflows/release-drafter.yml +++ b/.github/workflows/release-drafter.yml @@ -3,7 +3,6 @@ name: Release Drafter on: push: branches: - - master-new - master tags: - 'v*' diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index d2228a2079..56aa126684 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -5,38 +5,27 @@ on: workflow_dispatch: jobs: - build_masterci: - name: build master-ci - env: - ImageOS: ubuntu24 - container: - image: ghcr.io/commaai/openpilot-base:latest + build___nightly: + name: build __nightly runs-on: ubuntu-latest if: github.repository == 'sunnypilot/sunnypilot' permissions: checks: read contents: write steps: - - name: Install wait-on-check-action dependencies - run: | - sudo apt-get update - sudo apt-get install -y libyaml-dev - name: Wait for green check mark if: ${{ github.event_name == 'schedule' }} - uses: lewagon/wait-on-check-action@ccfb013c15c8afb7bf2b7c028fb74dc5a068cccc + uses: lewagon/wait-on-check-action@1d57e2c51a58d812d2765e036a028b6bdb5a6154 with: ref: master wait-interval: 30 - running-workflow-name: 'build master-ci' + running-workflow-name: 'build __nightly' repo-token: ${{ secrets.GITHUB_TOKEN }} - check-regexp: ^((?!.*(build prebuilt).*).)*$ - - uses: actions/checkout@v4 + check-regexp: ^((?!.*(build prebuilt|create badges).*).)*$ + - uses: actions/checkout@v4 # checkout version > v4 breaks nightly release script with: submodules: true fetch-depth: 0 - - name: Pull LFS - run: | - git config --global --add safe.directory '*' - git lfs pull - - name: Push master-ci - run: BRANCH=__nightly release/build_devel.sh + - run: ./tools/op.sh setup + - name: Push __nightly + run: BRANCH=__nightly tools/release/build_stripped.sh diff --git a/.github/workflows/repo-maintenance.yaml b/.github/workflows/repo-maintenance.yaml index 6bd86ce7e9..87556b4011 100644 --- a/.github/workflows/repo-maintenance.yaml +++ b/.github/workflows/repo-maintenance.yaml @@ -3,70 +3,127 @@ name: repo maintenance on: schedule: - cron: "0 14 * * 1" # every Monday at 2am UTC (6am PST) + pull_request: + types: [closed] workflow_dispatch: env: - BASE_IMAGE: openpilot-base - BUILD: selfdrive/test/docker_build.sh base - RUN: docker run --shm-size 2G -v $PWD:/tmp/openpilot -w /tmp/openpilot -e CI=1 -e PYTHONWARNINGS=error -e FILEREADER_CACHE=1 -e PYTHONPATH=/tmp/openpilot -e NUM_JOBS -e JOB_ID -e GITHUB_ACTION -e GITHUB_REF -e GITHUB_HEAD_REF -e GITHUB_SHA -e GITHUB_REPOSITORY -e GITHUB_RUN_ID -v $GITHUB_WORKSPACE/.ci_cache/scons_cache:/tmp/scons_cache -v $GITHUB_WORKSPACE/.ci_cache/comma_download_cache:/tmp/comma_download_cache -v $GITHUB_WORKSPACE/.ci_cache/openpilot_cache:/tmp/openpilot_cache $BASE_IMAGE /bin/bash -c + PYTHONPATH: ${{ github.workspace }} jobs: - update_translations: - runs-on: ubuntu-latest - if: github.repository == 'commaai/openpilot' - steps: - - uses: actions/checkout@v4 - - uses: ./.github/workflows/setup-with-retry - - name: Update translations - run: | - ${{ env.RUN }} "python3 selfdrive/ui/update_translations.py --vanish" - - name: Create Pull Request - uses: peter-evans/create-pull-request@9153d834b60caba6d51c9b9510b087acf9f33f83 - with: - author: Vehicle Researcher - commit-message: "Update translations" - title: "[bot] Update translations" - body: "Automatic PR from repo-maintenance -> update_translations" - branch: "update-translations" - base: "master" - delete-branch: true - labels: bot - package_updates: name: package_updates runs-on: ubuntu-latest - container: - image: ghcr.io/commaai/openpilot-base:latest - if: github.repository == 'sunnypilot/sunnypilot' + if: >- + github.repository == 'sunnypilot/sunnypilot' && + (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 with: submodules: true + - run: ./tools/op.sh setup - name: uv lock + run: uv lock --upgrade + - name: uv pip tree + id: pip_tree run: | - python3 -m ensurepip --upgrade - pip3 install uv - uv lock --upgrade + echo 'PIP_TREE<> $GITHUB_OUTPUT + uv pip tree >> $GITHUB_OUTPUT + echo 'EOF' >> $GITHUB_OUTPUT + - name: venv size + id: venv_size + run: | + echo 'VENV_SIZE<> $GITHUB_OUTPUT + echo "Total: $(du -sh .venv | cut -f1)" >> $GITHUB_OUTPUT + echo "" >> $GITHUB_OUTPUT + echo "Top 10 by size:" >> $GITHUB_OUTPUT + du -sh .venv/lib/python*/site-packages/* 2>/dev/null \ + | grep -v '\.dist-info' \ + | grep -v '__pycache__' \ + | sort -rh \ + | head -10 \ + | while IFS=$'\t' read size path; do echo "$size ${path##*/}"; done >> $GITHUB_OUTPUT + echo 'EOF' >> $GITHUB_OUTPUT - name: bump submodules run: | - git config --global --add safe.directory '*' + git config submodule.msgq.update none + git config submodule.rednose_repo.update none + git config submodule.teleoprtc_repo.update none + git config submodule.tinygrad.update none git submodule update --remote git add . - name: update car docs run: | - export PYTHONPATH="$PWD" - scons -j$(nproc) --minimal opendbc_repo - python selfdrive/car/docs.py + python openpilot/selfdrive/car/docs.py git add docs/CARS.md - name: Create Pull Request - uses: peter-evans/create-pull-request@9153d834b60caba6d51c9b9510b087acf9f33f83 + uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 with: - author: Vehicle Researcher - token: ${{ secrets.ACTIONS_CREATE_PR_PAT }} + author: github-actions[bot] + token: ${{ github.repository == 'commaai/openpilot' && secrets.ACTIONS_CREATE_PR_PAT || secrets.GITHUB_TOKEN }} commit-message: Update Python packages title: '[bot] Update Python packages' branch: auto-package-updates base: master delete-branch: true - body: 'Automatic PR from repo-maintenance -> package_updates' + body: | + Automatic PR from repo-maintenance -> package_updates + + ``` + $ du -sh .venv && du -sh .venv/lib/python*/site-packages/* | sort -rh | head -10 + ${{ steps.venv_size.outputs.VENV_SIZE }} + ``` + + ``` + $ uv pip tree + ${{ steps.pip_tree.outputs.PIP_TREE }} + ``` labels: bot + + cleanup_closed_branches: + if: github.repository == 'commaai/openpilot' + runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: read + steps: + - uses: actions/github-script@v9 + with: + script: | + const { owner, repo } = context.repo; + const upstream = `${owner}/${repo}`; + + const closed = context.payload.pull_request; + if (closed) { + if (closed.head.repo?.full_name === upstream) { + await github.rest.git.deleteRef({ owner, repo, ref: `heads/${closed.head.ref}` }).catch(console.log); + } + return; + } + + for await (const response of github.paginate.iterator(github.rest.pulls.list, { + owner, + repo, + state: 'closed', + per_page: 100, + })) { + for (const pr of response.data) { + if (pr.head.repo?.full_name !== upstream) continue; + + const branch = pr.head.ref; + try { + await github.rest.git.deleteRef({ + owner, + repo, + ref: `heads/${branch}`, + }); + console.log(`Deleted branch ${branch} (PR #${pr.number})`); + } catch (error) { + if (error.status === 422 || error.status === 403) { + console.log(`Skipping branch ${branch} (PR #${pr.number}): ${error.message}`); + continue; + } + throw error; + } + } + } diff --git a/.github/workflows/selfdrive_tests.yaml b/.github/workflows/selfdrive_tests.yaml deleted file mode 100644 index f8897258c6..0000000000 --- a/.github/workflows/selfdrive_tests.yaml +++ /dev/null @@ -1,366 +0,0 @@ -name: selfdrive - -on: - push: - branches: - - master - - master-new - pull_request: - workflow_dispatch: - workflow_call: - inputs: - run_number: - default: '1' - required: true - type: string - -concurrency: - group: selfdrive-tests-ci-run-${{ inputs.run_number }}-${{ github.event_name == 'push' && (github.ref == 'refs/heads/master' || github.ref == 'refs/heads/master-new') && github.run_id || github.head_ref || github.ref }}-${{ github.workflow }}-${{ github.event_name }} - cancel-in-progress: true - -env: - REPORT_NAME: report-${{ inputs.run_number || '1' }}-${{ github.event_name == 'push' && (github.ref == 'refs/heads/master' || github.ref == 'refs/heads/master-new') && 'master' || github.event.number }} - PYTHONWARNINGS: error - BASE_IMAGE: openpilot-base - AZURE_TOKEN: ${{ secrets.AZURE_COMMADATACI_OPENPILOTCI_TOKEN }} - - DOCKER_LOGIN: docker login ghcr.io -u ${{ github.actor }} -p ${{ secrets.GITHUB_TOKEN }} - BUILD: selfdrive/test/docker_build.sh base - - RUN: docker run --shm-size 2G -v $PWD:/tmp/openpilot -w /tmp/openpilot -e CI=1 -e PYTHONWARNINGS=error -e FILEREADER_CACHE=1 -e PYTHONPATH=/tmp/openpilot -e NUM_JOBS -e JOB_ID -e GITHUB_ACTION -e GITHUB_REF -e GITHUB_HEAD_REF -e GITHUB_SHA -e GITHUB_REPOSITORY -e GITHUB_RUN_ID -v $GITHUB_WORKSPACE/.ci_cache/scons_cache:/tmp/scons_cache -v $GITHUB_WORKSPACE/.ci_cache/comma_download_cache:/tmp/comma_download_cache -v $GITHUB_WORKSPACE/.ci_cache/openpilot_cache:/tmp/openpilot_cache $BASE_IMAGE /bin/bash -c - - PYTEST: pytest --continue-on-collection-errors --cov --cov-report=xml --cov-append --durations=0 --durations-min=5 --hypothesis-seed 0 -n logical - -jobs: - build_release: - if: github.repository == 'commaai/openpilot' # build_release blocked for the time being to only comma as we may have a different process. - name: build release - runs-on: - - 'ubuntu-24.04' - env: - STRIPPED_DIR: /tmp/releasepilot - steps: - - uses: actions/checkout@v4 - with: - submodules: true - - name: Getting LFS files - uses: nick-fields/retry@7152eba30c6575329ac0576536151aca5a72780e - with: - timeout_minutes: 2 - max_attempts: 3 - command: git lfs pull - - name: Build devel - timeout-minutes: 1 - run: TARGET_DIR=$STRIPPED_DIR release/build_devel.sh - - uses: ./.github/workflows/setup-with-retry - - name: Build openpilot and run checks - timeout-minutes: ${{ ((steps.restore-scons-cache.outputs.cache-hit == 'true') && 10 || 30) }} # allow more time when we missed the scons cache - run: | - cd $STRIPPED_DIR - ${{ env.RUN }} "python3 system/manager/build.py" - - name: Run tests - timeout-minutes: 1 - run: | - cd $STRIPPED_DIR - ${{ env.RUN }} "release/check-dirty.sh" - - name: Check submodules - if: github.repository == 'sunnypilot/sunnypilot' - timeout-minutes: 3 - run: release/check-submodules.sh - - build: - runs-on: - - 'ubuntu-24.04' - steps: - - uses: actions/checkout@v4 - with: - submodules: true - - name: Setup docker push - if: github.ref == 'refs/heads/master' && github.event_name != 'pull_request' && github.repository == 'commaai/openpilot' - run: | - echo "PUSH_IMAGE=true" >> "$GITHUB_ENV" - $DOCKER_LOGIN - - uses: ./.github/workflows/setup-with-retry - - uses: ./.github/workflows/compile-openpilot - timeout-minutes: 30 - - build_mac: - name: build macOS - runs-on: ${{ ((github.repository == 'commaai/openpilot') && ((github.event_name != 'pull_request') || (github.event.pull_request.head.repo.full_name == 'commaai/openpilot'))) && 'namespace-profile-macos-8x14' || 'macos-latest' }} - steps: - - uses: actions/checkout@v4 - with: - submodules: true - - run: echo "CACHE_COMMIT_DATE=$(git log -1 --pretty='format:%cd' --date=format:'%Y-%m-%d-%H:%M')" >> $GITHUB_ENV - - name: Homebrew cache - uses: ./.github/workflows/auto-cache - with: - path: ~/Library/Caches/Homebrew - key: brew-macos-${{ env.CACHE_COMMIT_DATE }}-${{ github.sha }} - restore-keys: | - brew-macos-${{ env.CACHE_COMMIT_DATE }} - brew-macos - - name: Install dependencies - run: ./tools/mac_setup.sh - env: - # package install has DeprecationWarnings - PYTHONWARNINGS: default - - name: Save Homebrew cache - uses: actions/cache/save@v4 - if: (github.ref == 'refs/heads/master' || github.ref == 'refs/heads/master-new') - with: - path: ~/Library/Caches/Homebrew - key: brew-macos-${{ env.CACHE_COMMIT_DATE }}-${{ github.sha }} - - run: git lfs pull - - name: Getting scons cache - uses: ./.github/workflows/auto-cache - with: - path: /tmp/scons_cache - key: scons-${{ runner.arch }}-macos-${{ env.CACHE_COMMIT_DATE }}-${{ github.sha }} - restore-keys: | - scons-${{ runner.arch }}-macos-${{ env.CACHE_COMMIT_DATE }} - scons-${{ runner.arch }}-macos - - name: Building openpilot - run: . .venv/bin/activate && scons -j$(nproc) - - name: Save scons cache - uses: actions/cache/save@v4 - if: (github.ref == 'refs/heads/master' || github.ref == 'refs/heads/master-new') - with: - path: /tmp/scons_cache - key: scons-${{ runner.arch }}-macos-${{ env.CACHE_COMMIT_DATE }}-${{ github.sha }} - - static_analysis: - name: static analysis - runs-on: - - 'ubuntu-latest' - env: - PYTHONWARNINGS: default - steps: - - uses: actions/checkout@v4 - with: - submodules: true - - uses: ./.github/workflows/setup-with-retry - - name: Static analysis - timeout-minutes: 1 - run: ${{ env.RUN }} "scripts/lint/lint.sh" - - unit_tests: - name: unit tests - runs-on: - - 'ubuntu-24.04' - steps: - - uses: actions/checkout@v4 - with: - submodules: true - - uses: ./.github/workflows/setup-with-retry - - name: Build openpilot - run: ${{ env.RUN }} "scons -j$(nproc)" - - name: Run unit tests - timeout-minutes: ${{ contains(runner.name, 'nsc') && 1 || 20 }} - run: | - ${{ env.RUN }} "$PYTEST --collect-only -m 'not slow' &> /dev/null && \ - MAX_EXAMPLES=1 $PYTEST -m 'not slow' && \ - ./selfdrive/ui/tests/create_test_translations.sh && \ - QT_QPA_PLATFORM=offscreen ./selfdrive/ui/tests/test_translations && \ - chmod -R 777 /tmp/comma_download_cache" - - name: "Upload coverage to Codecov" - uses: codecov/codecov-action@v4 - with: - name: ${{ github.job }} - env: - CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} - - process_replay: - name: process replay - if: github.repository == 'commaai/openpilot' # disable process_replay for forks - runs-on: - - 'ubuntu-24.04' - steps: - - uses: actions/checkout@v4 - with: - submodules: true - - uses: ./.github/workflows/setup-with-retry - - name: Cache test routes - id: dependency-cache - uses: actions/cache@v4 - with: - path: .ci_cache/comma_download_cache - key: proc-replay-${{ hashFiles('selfdrive/test/process_replay/ref_commit', 'selfdrive/test/process_replay/test_processes.py') }} - - name: Build openpilot - run: | - ${{ env.RUN }} "scons -j$(nproc)" - - name: Run replay - timeout-minutes: ${{ contains(runner.name, 'nsc') && (steps.dependency-cache.outputs.cache-hit == 'true') && 1 || 20 }} - run: | - ${{ env.RUN }} "coverage run selfdrive/test/process_replay/test_processes.py -j$(nproc) && \ - chmod -R 777 /tmp/comma_download_cache && \ - coverage combine && \ - coverage xml" - - name: Print diff - id: print-diff - if: always() - run: cat selfdrive/test/process_replay/diff.txt - - uses: actions/upload-artifact@v4 - if: always() - continue-on-error: true - with: - name: process_replay_diff.txt - path: selfdrive/test/process_replay/diff.txt - - name: Upload reference logs - if: ${{ failure() && steps.print-diff.outcome == 'success' && github.repository == 'commaai/openpilot' && env.AZURE_TOKEN != '' }} - run: | - ${{ env.RUN }} "unset PYTHONWARNINGS && AZURE_TOKEN='$AZURE_TOKEN' python3 selfdrive/test/process_replay/test_processes.py -j$(nproc) --upload-only" - - name: Run regen - if: false - timeout-minutes: 4 - run: | - ${{ env.RUN }} "ONNXCPU=1 $PYTEST selfdrive/test/process_replay/test_regen.py && \ - chmod -R 777 /tmp/comma_download_cache" - - name: "Upload coverage to Codecov" - uses: codecov/codecov-action@v4 - with: - name: ${{ github.job }} - env: - CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} - - test_cars: - name: cars - runs-on: - - 'ubuntu-24.04' - strategy: - fail-fast: false - matrix: - job: [0, 1, 2, 3] - steps: - - uses: actions/checkout@v4 - with: - submodules: true - - uses: ./.github/workflows/setup-with-retry - - name: Cache test routes - id: routes-cache - uses: actions/cache@v4 - with: - path: .ci_cache/comma_download_cache - key: car_models-${{ hashFiles('selfdrive/car/tests/test_models.py', 'opendbc/car/tests/routes.py') }}-${{ matrix.job }} - - name: Build openpilot - run: ${{ env.RUN }} "scons -j$(nproc)" - - name: Test car models - timeout-minutes: ${{ contains(runner.name, 'nsc') && (steps.routes-cache.outputs.cache-hit == 'true') && 1 || 6 }} - run: | - ${{ env.RUN }} "MAX_EXAMPLES=1 $PYTEST selfdrive/car/tests/test_models.py && \ - chmod -R 777 /tmp/comma_download_cache" - env: - NUM_JOBS: 4 - JOB_ID: ${{ matrix.job }} - - name: "Upload coverage to Codecov" - uses: codecov/codecov-action@v4 - with: - name: ${{ github.job }}-${{ matrix.job }} - env: - CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} - - car_docs_diff: - name: PR comments - runs-on: ubuntu-latest - #if: github.event_name == 'pull_request' - if: false # TODO: run this in opendbc? - steps: - - uses: actions/checkout@v4 - with: - submodules: true - ref: ${{ github.event.pull_request.base.ref }} - - run: git lfs pull - - uses: ./.github/workflows/setup-with-retry - - name: Get base car info - run: | - ${{ env.RUN }} "scons -j$(nproc) && python3 selfdrive/debug/dump_car_docs.py --path /tmp/openpilot_cache/base_car_docs" - sudo chown -R $USER:$USER ${{ github.workspace }} - - uses: actions/checkout@v4 - with: - submodules: true - path: current - - run: cd current && git lfs pull - - name: Save car docs diff - id: save_diff - run: | - cd current - ${{ env.RUN }} "scons -j$(nproc)" - output=$(${{ env.RUN }} "python3 selfdrive/debug/print_docs_diff.py --path /tmp/openpilot_cache/base_car_docs") - output="${output//$'\n'/'%0A'}" - echo "::set-output name=diff::$output" - - name: Find comment - if: ${{ env.AZURE_TOKEN != '' }} - uses: peter-evans/find-comment@3eae4d37986fb5a8592848f6a574fdf654e61f9e - id: fc - with: - issue-number: ${{ github.event.pull_request.number }} - body-includes: This PR makes changes to - - name: Update comment - if: ${{ steps.save_diff.outputs.diff != '' && env.AZURE_TOKEN != '' }} - uses: peter-evans/create-or-update-comment@71345be0265236311c031f5c7866368bd1eff043 - with: - comment-id: ${{ steps.fc.outputs.comment-id }} - issue-number: ${{ github.event.pull_request.number }} - body: "${{ steps.save_diff.outputs.diff }}" - edit-mode: replace - - name: Delete comment - if: ${{ steps.fc.outputs.comment-id != '' && steps.save_diff.outputs.diff == '' && env.AZURE_TOKEN != '' }} - uses: actions/github-script@v7 - with: - script: | - github.rest.issues.deleteComment({ - owner: context.repo.owner, - repo: context.repo.repo, - comment_id: ${{ steps.fc.outputs.comment-id }} - }) - - simulator_driving: - name: simulator driving - runs-on: - - 'ubuntu-24.04' - if: (github.repository == 'commaai/openpilot') && ((github.event_name != 'pull_request') || (github.event.pull_request.head.repo.full_name == 'commaai/openpilot')) - steps: - - uses: actions/checkout@v4 - with: - submodules: true - - uses: ./.github/workflows/setup-with-retry - - name: Build openpilot - run: | - ${{ env.RUN }} "scons -j$(nproc)" - - name: Driving test - timeout-minutes: 1 - run: | - ${{ env.RUN }} "source selfdrive/test/setup_xvfb.sh && \ - source selfdrive/test/setup_vsound.sh && \ - CI=1 pytest -s tools/sim/tests/test_metadrive_bridge.py" - - create_ui_report: - # This job name needs to be the same as UI_JOB_NAME in ui_preview.yaml - name: Create UI Report - runs-on: - - 'ubuntu-24.04' - steps: - - uses: actions/checkout@v4 - with: - submodules: true - - uses: ./.github/workflows/setup-with-retry - - name: caching frames - id: frames-cache - uses: actions/cache@v4 - with: - path: .ci_cache/comma_download_cache - key: ui_screenshots_test_${{ hashFiles('selfdrive/ui/tests/test_ui/run.py') }} - - name: Build openpilot - run: ${{ env.RUN }} "scons -j$(nproc)" - - name: Create Test Report - timeout-minutes: ${{ ((steps.frames-cache.outputs.cache-hit == 'true') && 2 || 4) }} - run: > - ${{ env.RUN }} "PYTHONWARNINGS=ignore && - source selfdrive/test/setup_xvfb.sh && - CACHE_ROOT=/tmp/comma_download_cache python3 selfdrive/ui/tests/test_ui/run.py && - chmod -R 777 /tmp/comma_download_cache" - - name: Upload Test Report - uses: actions/upload-artifact@v4 - with: - name: ${{ env.REPORT_NAME }} - path: selfdrive/ui/tests/test_ui/report_1/screenshots diff --git a/.github/workflows/setup-with-retry/action.yaml b/.github/workflows/setup-with-retry/action.yaml deleted file mode 100644 index ad297403cf..0000000000 --- a/.github/workflows/setup-with-retry/action.yaml +++ /dev/null @@ -1,37 +0,0 @@ -name: 'openpilot env setup, with retry on failure' - -inputs: - docker_hub_pat: - description: 'Auth token for Docker Hub, required for BuildJet jobs' - required: false - default: '' - sleep_time: - description: 'Time to sleep between retries' - required: false - default: 30 - -runs: - using: "composite" - steps: - - id: setup1 - uses: ./.github/workflows/setup - continue-on-error: true - with: - is_retried: true - - if: steps.setup1.outcome == 'failure' - shell: bash - run: sleep ${{ inputs.sleep_time }} - - id: setup2 - if: steps.setup1.outcome == 'failure' - uses: ./.github/workflows/setup - continue-on-error: true - with: - is_retried: true - - if: steps.setup2.outcome == 'failure' - shell: bash - run: sleep ${{ inputs.sleep_time }} - - id: setup3 - if: steps.setup2.outcome == 'failure' - uses: ./.github/workflows/setup - with: - is_retried: true diff --git a/.github/workflows/setup/action.yaml b/.github/workflows/setup/action.yaml deleted file mode 100644 index 70177885a7..0000000000 --- a/.github/workflows/setup/action.yaml +++ /dev/null @@ -1,56 +0,0 @@ -name: 'openpilot env setup' - -inputs: - is_retried: - description: 'A mock param that asserts that we use the setup-with-retry instead of this action directly' - required: false - default: 'false' - -runs: - using: "composite" - steps: - # assert that this action is retried using the setup-with-retry - - shell: bash - if: ${{ inputs.is_retried == 'false' }} - run: | - echo "You should not run this action directly. Use setup-with-retry instead" - exit 1 - - - shell: bash - name: No retries! - run: | - if [ "${{ github.run_attempt }}" -gt ${{ github.event.pull_request.head.repo.fork && github.event.pull_request.author_association == 'NONE' && 2 || 1}} ]; then - echo -e "\033[0;31m##################################################" - echo -e "\033[0;31m Retries not allowed! Fix the flaky test! " - echo -e "\033[0;31m##################################################\033[0m" - exit 1 - fi - - # do this after checkout to ensure our custom LFS config is used to pull from GitLab - - shell: bash - run: git lfs pull - - # build cache - - id: date - shell: bash - run: echo "CACHE_COMMIT_DATE=$(git log -1 --pretty='format:%cd' --date=format:'%Y-%m-%d-%H:%M')" >> $GITHUB_ENV - - shell: bash - run: echo "$CACHE_COMMIT_DATE" - - id: scons-cache - uses: ./.github/workflows/auto-cache - with: - path: .ci_cache/scons_cache - key: scons-${{ runner.arch }}-${{ env.CACHE_COMMIT_DATE }}-${{ github.sha }} - restore-keys: | - scons-${{ runner.arch }}-${{ env.CACHE_COMMIT_DATE }} - scons-${{ runner.arch }} - # as suggested here: https://github.com/moby/moby/issues/32816#issuecomment-910030001 - - id: normalize-file-permissions - shell: bash - name: Normalize file permissions to ensure a consistent docker build cache - run: | - find . -type f -executable -not -perm 755 -exec chmod 755 {} \; - find . -type f -not -executable -not -perm 644 -exec chmod 644 {} \; - # build our docker image - - shell: bash - run: eval ${{ env.BUILD }} diff --git a/.github/workflows/stale.yaml b/.github/workflows/stale.yaml index cc29813952..dab61bf3b4 100644 --- a/.github/workflows/stale.yaml +++ b/.github/workflows/stale.yaml @@ -5,14 +5,15 @@ on: workflow_dispatch: env: - DAYS_BEFORE_PR_CLOSE: 2 - DAYS_BEFORE_PR_STALE: 9 + DAYS_BEFORE_PR_CLOSE: 7 + DAYS_BEFORE_PR_STALE: 24 + DAYS_BEFORE_PR_STALE_DRAFT: 30 jobs: stale: runs-on: ubuntu-latest steps: - - uses: actions/stale@v9 + - uses: actions/stale@v10 with: exempt-all-milestones: true @@ -24,6 +25,28 @@ jobs: exempt-pr-labels: "ignore stale,needs testing" # if wip or it needs testing from the community, don't mark as stale days-before-pr-stale: ${{ env.DAYS_BEFORE_PR_STALE }} days-before-pr-close: ${{ env.DAYS_BEFORE_PR_CLOSE }} + exempt-draft-pr: false + + # issue config + days-before-issue-stale: -1 # ignore issues for now + + # same as above, but give draft PRs more time + stale_drafts: + runs-on: ubuntu-latest + steps: + - uses: actions/stale@v10 + with: + exempt-all-milestones: true + + # pull request config + stale-pr-message: 'This PR has had no activity for ${{ env.DAYS_BEFORE_PR_STALE_DRAFT }} days. It will be automatically closed in ${{ env.DAYS_BEFORE_PR_CLOSE }} days if there is no activity.' + close-pr-message: 'This PR has been automatically closed due to inactivity. Feel free to re-open once activity resumes.' + stale-pr-label: stale + delete-branch: ${{ github.event.pull_request.head.repo.full_name == 'commaai/openpilot' }} # only delete branches on the main repo + exempt-pr-labels: "ignore stale,needs testing" # if wip or it needs testing from the community, don't mark as stale + days-before-pr-stale: ${{ env.DAYS_BEFORE_PR_STALE_DRAFT }} + days-before-pr-close: ${{ env.DAYS_BEFORE_PR_CLOSE }} + exempt-draft-pr: true # issue config days-before-issue-stale: -1 # ignore issues for now diff --git a/.github/workflows/sunnypilot-build-model.yaml b/.github/workflows/sunnypilot-build-model.yaml index dc02d1d8d2..acb75af55e 100644 --- a/.github/workflows/sunnypilot-build-model.yaml +++ b/.github/workflows/sunnypilot-build-model.yaml @@ -6,9 +6,30 @@ env: SCONS_CACHE_DIR: ${{ github.workspace }}/release/ci/scons_cache UPSTREAM_REPO: "commaai/openpilot" TINYGRAD_PATH: ${{ github.workspace }}/tinygrad_repo - MODELS_DIR: ${{ github.workspace }}/selfdrive/modeld/models + MODELS_DIR: ${{ github.workspace }}/openpilot/selfdrive/modeld/models on: + workflow_call: + inputs: + upstream_branch: + description: 'Upstream branch to build from' + required: true + default: 'master' + type: string + custom_name: + description: 'Custom name for the model (no date, only name)' + required: false + type: string + is_20hz: + description: 'Is this a 20Hz model' + required: false + type: boolean + default: true + artifact_suffix: + description: 'Suffix for artifact name' + required: false + type: string + default: '' workflow_dispatch: inputs: upstream_branch: @@ -32,34 +53,53 @@ run-name: Build model [${{ inputs.custom_name || inputs.upstream_branch }}] from jobs: get_model: runs-on: ubuntu-latest + env: + REF: ${{ inputs.upstream_branch }} outputs: model_date: ${{ steps.commit-date.outputs.model_date }} steps: - - uses: actions/checkout@v4 + # Note: To allow dynamic models from both openpilot and sunnypilot (merges/mashups), we try commaai as default, + # and fallback to sunnypilot if the ref checkout fails. + - name: Checkout commaai/openpilot + id: checkout_upstream + continue-on-error: true + uses: actions/checkout@v4 with: - repository: ${{ env.UPSTREAM_REPO }} - ref: ${{ github.event.inputs.upstream_branch }} + repository: commaai/openpilot + ref: ${{ inputs.upstream_branch }} submodules: recursive + path: openpilot + + - name: Fallback to sunnypilot/sunnypilot + if: steps.checkout_upstream.outcome == 'failure' + uses: actions/checkout@v4 + with: + repository: sunnypilot/sunnypilot + ref: ${{ inputs.upstream_branch }} + submodules: recursive + path: openpilot - name: Get commit date id: commit-date run: | - # Get the commit date in YYYY-MM-DD format + cd ${{ github.workspace }}/openpilot commit_date=$(git log -1 --format=%cd --date=format:'%B %d, %Y') echo "model_date=${commit_date}" >> $GITHUB_OUTPUT cat $GITHUB_OUTPUT - - run: git lfs pull + - run: | + cd ${{ github.workspace }}/openpilot + git lfs pull - name: 'Upload Artifact' uses: actions/upload-artifact@v4 with: - name: models - path: ${{ github.workspace }}/selfdrive/modeld/models/*.onnx + name: models-${{ env.REF }}${{ inputs.artifact_suffix }} + path: ${{ github.workspace }}/openpilot/openpilot/selfdrive/modeld/models/*.onnx build_model: - runs-on: self-hosted + runs-on: [self-hosted, tici] needs: get_model env: MODEL_NAME: ${{ inputs.custom_name || inputs.upstream_branch }} (${{ needs.get_model.outputs.model_date }}) - + REF: ${{ inputs.upstream_branch }} steps: - uses: actions/checkout@v4 with: @@ -71,7 +111,7 @@ jobs: with: path: ${{env.SCONS_CACHE_DIR}} key: scons-${{ runner.os }}-${{ runner.arch }}-${{ github.head_ref || github.ref_name }}-model-${{ github.sha }} - # Note: GitHub Actions enforces cache isolation between different build sources (PR builds, workflow dispatches, etc.) + # Note: GitHub Actions enforces cache isolation between different build sources (PR builds, workflow dispatches, etc.) # for security. Only caches from the default branch are shared across all builds. This is by design and cannot be overridden. restore-keys: | scons-${{ runner.os }}-${{ runner.arch }}-${{ github.head_ref || github.ref_name }}-model @@ -88,7 +128,10 @@ jobs: # Set up common environment source /etc/profile; export UV_PROJECT_ENVIRONMENT=${HOME}/venv + export UV_PYTHON_PREFERENCE=managed + export UV_PYTHON_INSTALL_DIR=${HOME}/uv/python export VIRTUAL_ENV=$UV_PROJECT_ENVIRONMENT + uv sync printenv >> $GITHUB_ENV if [[ "${{ runner.debug }}" == "1" ]]; then cat $GITHUB_OUTPUT @@ -108,32 +151,80 @@ jobs: if [[ "${{ runner.debug }}" == "1" ]]; then printenv fi + source ${UV_PROJECT_ENVIRONMENT}/bin/activate PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --disable rm -rf ${{ env.MODELS_DIR }}/*.onnx - name: Download model artifacts uses: actions/download-artifact@v4 with: - name: models - path: ${{ github.workspace }}/selfdrive/modeld/models + name: models-${{ env.REF }}${{ inputs.artifact_suffix }} + path: ${{ env.MODELS_DIR }} + - run: | + rm -f ${{ env.MODELS_DIR }}/{dmonitoring_model,big_driving_policy,big_driving_vision}.onnx - name: Build Model run: | source /etc/profile export UV_PROJECT_ENVIRONMENT=${HOME}/venv export VIRTUAL_ENV=$UV_PROJECT_ENVIRONMENT - export PYTHONPATH="${PYTHONPATH}:${{ env.TINYGRAD_PATH }}" + export PYTHONPATH="${PYTHONPATH}:${{ env.TINYGRAD_PATH }}:${{ github.workspace }}" - # Loop through all .onnx files + COMPILE_MODELD="${{ github.workspace }}/openpilot/sunnypilot/modeld_v2/compile_modeld.py" + MODEL_SIZE=$(python3 -c "from openpilot.common.transformations.model import MEDMODEL_INPUT_SIZE as s; print(f'{s[0]}x{s[1]}')") + CAMERA_RES=$(python3 -c "from openpilot.common.transformations.camera import _ar_ox_fisheye as a, _os_fisheye as o; print(f'{a.width}x{a.height} {o.width}x{o.height}')") + TG_FLAGS="DEV=QCOM IMAGE=1 FLOAT16=1 NOLOCALS=1 JIT_BATCH_SIZE=0 OPENPILOT_HACKS=1" + + # Generate metadata for all ONNX files find "${{ env.MODELS_DIR }}" -maxdepth 1 -name '*.onnx' | while IFS= read -r onnx_file; do - base_name=$(basename "$onnx_file" .onnx) - output_file="${{ env.MODELS_DIR }}/${base_name}_tinygrad.pkl" - - echo "Compiling: $onnx_file -> $output_file" - QCOM=1 python3 "${{ env.TINYGRAD_PATH }}/examples/openpilot/compile3.py" "$onnx_file" "$output_file" - QCOM=1 python3 "${{ env.MODELS_DIR }}/../get_model_metadata.py" "$onnx_file" || true + echo "Generating metadata: $onnx_file" + env ${TG_FLAGS} python3 "${{ env.MODELS_DIR }}/../get_model_metadata.py" "$onnx_file" || true done + # Detect model type and build compile args + VISION_ONNX="${{ env.MODELS_DIR }}/driving_vision.onnx" + POLICY_ONNX="${{ env.MODELS_DIR }}/driving_policy.onnx" + OFF_POLICY_ONNX="${{ env.MODELS_DIR }}/driving_off_policy.onnx" + ON_POLICY_ONNX="${{ env.MODELS_DIR }}/driving_on_policy.onnx" + SUPERCOMBO_ONNX="${{ env.MODELS_DIR }}/supercombo.onnx" + + MODEL_TYPE="" ONNX_ARGS="" OUTPUT_NAME="" + if [ -f "$VISION_ONNX" ]; then + ONNX_ARGS="--vision-onnx $VISION_ONNX" + if [ -f "$ON_POLICY_ONNX" ] && [ -f "$OFF_POLICY_ONNX" ]; then + MODEL_TYPE=vision_multi_policy + ONNX_ARGS="$ONNX_ARGS --off-policy-onnx $OFF_POLICY_ONNX --on-policy-onnx $ON_POLICY_ONNX" + elif [ -f "$OFF_POLICY_ONNX" ] && [ -f "$POLICY_ONNX" ]; then + MODEL_TYPE=vision_multi_policy + ONNX_ARGS="$ONNX_ARGS --policy-onnx $POLICY_ONNX --off-policy-onnx $OFF_POLICY_ONNX" + elif [ -f "$POLICY_ONNX" ]; then + MODEL_TYPE=vision_policy + ONNX_ARGS="$ONNX_ARGS --policy-onnx $POLICY_ONNX" + fi + elif [ -f "$SUPERCOMBO_ONNX" ]; then + MODEL_TYPE=supercombo + ONNX_ARGS="--supercombo-onnx $SUPERCOMBO_ONNX" + fi + + if [ -n "$MODEL_TYPE" ]; then + echo "Detected: $MODEL_TYPE -> driving_tinygrad.pkl" + env ${TG_FLAGS} python3 "$COMPILE_MODELD" \ + --model-type $MODEL_TYPE \ + --model-size $MODEL_SIZE \ + --camera-resolutions $CAMERA_RES \ + $ONNX_ARGS \ + --output "${{ env.MODELS_DIR }}/driving_tinygrad.pkl" + fi + + - name: Validate Model Outputs + run: | + source /etc/profile + export UV_PROJECT_ENVIRONMENT=${HOME}/venv + export VIRTUAL_ENV=$UV_PROJECT_ENVIRONMENT + python3 "${{ github.workspace }}/release/ci/model_generator.py" \ + --validate-only \ + --model-dir "${{ env.MODELS_DIR }}" + - name: Prepare Output run: | sudo rm -rf ${{ env.OUTPUT_DIR }} @@ -142,8 +233,9 @@ jobs: # Copy the model files rsync -avm \ --include='*.dlc' \ - --include='*.thneed' \ --include='*.pkl' \ + --include='*.chunk*' \ + --include='*.chunkmanifest' \ --include='*.onnx' \ --exclude='*' \ --delete-excluded \ @@ -157,13 +249,24 @@ jobs: --upstream-branch "${{ inputs.upstream_branch }}" \ ${{ inputs.is_20hz && '--is-20hz' || '' }} + - name: Write artifact name to file + run: echo "model-${{ env.MODEL_NAME }}${{ inputs.artifact_suffix }}-${{ github.run_number }}" > ${{ env.OUTPUT_DIR }}/artifact_name.txt + - name: Upload Build Artifacts + id: upload-artifact uses: actions/upload-artifact@v4 with: - name: model-${{ env.MODEL_NAME }}-${{ github.run_number }} + name: model-${{ env.MODEL_NAME }}${{ inputs.artifact_suffix }}-${{ github.run_number }} path: ${{ env.OUTPUT_DIR }} + - name: Upload artifact name file + uses: actions/upload-artifact@v4 + with: + name: artifact-name-${{ inputs.custom_name || inputs.upstream_branch }} + path: ${{ env.OUTPUT_DIR }}/artifact_name.txt + - name: Re-enable powersave if: always() run: | + source ${UV_PROJECT_ENVIRONMENT}/bin/activate PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --enable diff --git a/.github/workflows/sunnypilot-build-prebuilt.yaml b/.github/workflows/sunnypilot-build-prebuilt.yaml index 6cd5023a17..12a3a7bce0 100644 --- a/.github/workflows/sunnypilot-build-prebuilt.yaml +++ b/.github/workflows/sunnypilot-build-prebuilt.yaml @@ -6,57 +6,121 @@ env: CI_DIR: ${{ github.workspace }}/release/ci SCONS_CACHE_DIR: ${{ github.workspace }}/release/ci/scons_cache PUBLIC_REPO_URL: "https://github.com/sunnypilot/sunnypilot" - + # Branch configurations - STAGING_C3_SOURCE_BRANCH: ${{ vars.STAGING_C3_SOURCE_BRANCH || 'master-new' }} # vars are set on repo settings. - DEV_C3_SOURCE_BRANCH: ${{ vars.DEV_C3_SOURCE_BRANCH || 'master-dev-c3-new' }} # vars are set on repo settings. - - # Target branch configurations - STAGING_TARGET_BRANCH: ${{ vars.STAGING_TARGET_BRANCH || 'staging-c3-new' }} # vars are set on repo settings. - DEV_TARGET_BRANCH: ${{ vars.DEV_TARGET_BRANCH || 'dev-c3-new' }} # vars are set on repo settings. - RELEASE_TARGET_BRANCH: ${{ vars.RELEASE_TARGET_BRANCH || 'release-c3-new' }} # vars are set on repo settings. - + STAGING_SOURCE_BRANCH: 'master' + # Runtime configuration SOURCE_BRANCH: "${{ github.head_ref || github.ref_name }}" on: push: - branches: [ master, master-new, master-dev-c3-new ] - tags: [ '*' ] + branches: [ master, master-dev ] + tags: [ 'release/*' ] pull_request_target: types: [ labeled ] workflow_dispatch: inputs: wait_for_tests: - description: 'Wait for selfdrive_tests to finish' + description: 'Wait for tests to finish' required: false type: boolean default: false jobs: + prepare_strategy: + runs-on: ubuntu-24.04 + if: (!contains(github.event_name, 'pull_request') || (github.event.action == 'labeled' && github.event.label.name == 'prebuilt')) + outputs: + environment: ${{ steps.strategy.outputs.environment }} + new_branch: ${{ steps.strategy.outputs.new_branch }} + extra_version_identifier: ${{ steps.strategy.outputs.extra_version_identifier }} + version: ${{ steps.strategy.outputs.version }} + cancel_publish_in_progress: ${{ steps.strategy.outputs.cancel_publish_in_progress }} + publish_concurrency_group: ${{ steps.strategy.outputs.publish_concurrency_group }} + is_stable_branch: ${{ steps.strategy.outputs.is_stable_branch }} + build: ${{ steps.strategy.outputs.build }} + steps: + - uses: actions/checkout@v4 + - name: Extract deploy strategy + id: strategy + run: | + echo '::group::Strategy Extraction' + BRANCH="${{ github.head_ref || github.ref_name }}" + echo "Current branch: $BRANCH" + + STRATEGY_JSON='${{ vars.DEPLOY_STRATEGY }}' + CONFIG=$(echo "$STRATEGY_JSON" | jq -r --arg branch "$BRANCH" ' + .configs[] | select(.branch == $branch) + ') + + BUILD="$(date '+%Y.%m.%d')-${{ github.run_number }}" + if [[ -z "$CONFIG" || "$CONFIG" == "null" ]]; then + echo "No exact strategy match found. Falling back to feature/fork logic." + IS_FORK="${{ github.event.pull_request.head.repo.fork && 'true' || 'false' }}" + FORK_SUFFIX=$( [[ "$IS_FORK" == "true" ]] && echo "-fork" || echo "" ) + NEW_BRANCH="${BRANCH}${FORK_SUFFIX}-prebuilt" + + echo "new_branch=$NEW_BRANCH" >> $GITHUB_OUTPUT + echo "version=$BUILD" >> $GITHUB_OUTPUT + echo "cancel_publish_in_progress=true" >> $GITHUB_OUTPUT + echo "publish_concurrency_group=publish-${BRANCH}" >> $GITHUB_OUTPUT + echo "environment=feature-branch" >> $GITHUB_OUTPUT + echo "extra_version_identifier=feature-branch" >> $GITHUB_OUTPUT + else + echo "Matched config: $CONFIG" + environment=$(echo "$CONFIG" | jq -r '.environment') + echo "environment=$environment" >> $GITHUB_OUTPUT + echo "new_branch=$(echo "$CONFIG" | jq -r '.target_branch')" >> $GITHUB_OUTPUT + cancel="$(echo "$CONFIG" | jq -r '.cancel_publish_in_progress')"; + echo "cancel_publish_in_progress=$( [ "$cancel" = "null" ] && echo "true" || echo $cancel)" >> $GITHUB_OUTPUT + echo "publish_concurrency_group=publish-${BRANCH}$( [ "$cancel" = "null" ] || [ "$cancel" = "true" ] || echo "${{ github.sha }}" )" >> $GITHUB_OUTPUT + + is_stable_branch="$(echo "$CONFIG" | jq -r '.stable_branch // false')"; + echo "is_stable_branch=$is_stable_branch" >> $GITHUB_OUTPUT + + stable_version=$(cat openpilot/sunnypilot/common/version.h | grep SUNNYPILOT_VERSION | sed -e 's/[^0-9|.]//g'); + echo "version=$([ "$is_stable_branch" = "true" ] && echo "$stable_version" || echo "$BUILD")" >> $GITHUB_OUTPUT + echo "extra_version_identifier=${environment}" >> $GITHUB_OUTPUT + fi + echo "build=$BUILD" >> $GITHUB_OUTPUT + cat $GITHUB_OUTPUT + validate_tests: runs-on: ubuntu-24.04 - if: ((github.event_name == 'workflow_dispatch' && inputs.wait_for_tests) || contains(github.event_name, 'pull_request') && (github.event.action == 'labeled' && github.event.label.name == 'prebuilt')) + needs: [ prepare_strategy ] + if: ${{ + ((github.event_name == 'workflow_dispatch' && inputs.wait_for_tests) || + (github.event_name == 'push' && needs.prepare_strategy.outputs.is_stable_branch == 'true') || + contains(github.event_name, 'pull_request') && (github.event.action == 'labeled' && github.event.label.name == 'prebuilt')) + }} steps: - uses: actions/checkout@v4 - name: Wait for Tests uses: ./.github/workflows/wait-for-action # Path to where you place the action with: - workflow: selfdrive_tests.yaml # The workflow file to monitor + workflow: tests.yaml # The workflow file to monitor github-token: ${{ secrets.GITHUB_TOKEN }} + should-wait-for-start: ${{ github.event_name == 'push' && 'true' || 'false' }} build: - needs: [ validate_tests ] + needs: [ validate_tests, prepare_strategy ] concurrency: group: build-${{ github.head_ref || github.ref_name }} cancel-in-progress: false - runs-on: self-hosted + runs-on: [self-hosted, tici] outputs: - new_branch: ${{ steps.set-env.outputs.new_branch }} - version: ${{ steps.set-env.outputs.version }} - extra_version_identifier: ${{ steps.set-env.outputs.extra_version_identifier }} - commit_sha: ${{ steps.set-env.outputs.commit_sha }} - if: ${{ (always() && !failure() && !cancelled()) && (!contains(github.event_name, 'pull_request') || (github.event.action == 'labeled' && github.event.label.name == 'prebuilt')) }} + new_branch: ${{ needs.prepare_strategy.outputs.new_branch }} + version: ${{ needs.prepare_strategy.outputs.version }} + extra_version_identifier: ${{ needs.prepare_strategy.outputs.extra_version_identifier }} + commit_sha: ${{ github.sha }} + if: ${{ + (always() && !cancelled() && !failure()) && + needs.prepare_strategy.result == 'success' && + (needs.validate_tests.result == 'success' || needs.validate_tests.result == 'skipped') && + (!contains(github.event_name, 'pull_request') || + (github.event.action == 'labeled' && github.event.label.name == 'prebuilt')) + }} steps: - uses: actions/checkout@v4 with: @@ -70,74 +134,28 @@ jobs: with: path: ${{env.SCONS_CACHE_DIR}} key: scons-${{ runner.os }}-${{ runner.arch }}-${{ env.SOURCE_BRANCH }}-${{ github.sha }} - # Note: GitHub Actions enforces cache isolation between different build sources (PR builds, workflow dispatches, etc.) + # Note: GitHub Actions enforces cache isolation between different build sources (PR builds, workflow dispatches, etc.) # for security. Only caches from the default branch are shared across all builds. This is by design and cannot be overridden. restore-keys: | scons-${{ runner.os }}-${{ runner.arch }}-${{ env.SOURCE_BRANCH }} - scons-${{ runner.os }}-${{ runner.arch }}-${{ env.STAGING_C3_SOURCE_BRANCH }} + scons-${{ runner.os }}-${{ runner.arch }}-${{ env.STAGING_SOURCE_BRANCH }} scons-${{ runner.os }}-${{ runner.arch }} - - name: Set Feature Branch Prebuilt Configuration - id: set_feature_configuration - if: ( - !(env.SOURCE_BRANCH == env.DEV_C3_SOURCE_BRANCH) && - !(env.SOURCE_BRANCH == env.STAGING_C3_SOURCE_BRANCH) && - !(startsWith(github.ref, 'refs/tags/')) - ) - run: | - echo "NEW_BRANCH=${{ env.SOURCE_BRANCH }}${{ github.event.pull_request.head.repo.fork && '-fork' || '' }}-prebuilt" >> $GITHUB_ENV - echo "VERSION=$(date '+%Y.%m.%d')-${{ github.run_number }}" >> $GITHUB_ENV - - - name: Set dev-c3-new prebuilt Configuration - id: set_dev_configuration - if: ( - steps.set_feature_configuration.outcome == 'skipped' && - env.SOURCE_BRANCH == env.DEV_C3_SOURCE_BRANCH - ) - run: | - echo "NEW_BRANCH=${{ env.DEV_TARGET_BRANCH }}" >> $GITHUB_ENV - echo "VERSION=$(date '+%Y.%m.%d')-${{ github.run_number }}" >> $GITHUB_ENV - echo "EXTRA_VERSION_IDENTIFIER=${{ github.run_number }}" >> $GITHUB_ENV - - - name: Set staging-c3-new prebuilt Configuration - id: set_staging_configuration - if: ( - steps.set_feature_configuration.outcome == 'skipped' && - !contains(github.event_name, 'pull_request') && - steps.set_dev_configuration.outcome == 'skipped' && - (env.SOURCE_BRANCH == env.STAGING_C3_SOURCE_BRANCH) - ) - run: | - echo "NEW_BRANCH=${{ env.STAGING_TARGET_BRANCH }}" >> $GITHUB_ENV - echo "EXTRA_VERSION_IDENTIFIER=staging" >> $GITHUB_ENV - echo "VERSION=$(cat common/version.h | grep COMMA_VERSION | sed -e 's/[^0-9|.]//g')-staging" >> $GITHUB_ENV - - - name: Set release-c3-new prebuilt Configuration - id: set_tag_configuration - if: ( - steps.set_feature_configuration.outcome == 'skipped' && - !contains(github.event_name, 'pull_request') && - steps.set_staging_configuration.outcome == 'skipped' && - startsWith(github.ref, 'refs/tags/') - ) - run: | - echo "NEW_BRANCH=${{ env.RELEASE_TARGET_BRANCH }}" >> $GITHUB_ENV - echo "EXTRA_VERSION_IDENTIFIER=release" >> $GITHUB_ENV - echo "VERSION=$(cat common/version.h | grep COMMA_VERSION | sed -e 's/[^0-9|.]//g')-release" >> $GITHUB_ENV - - name: Set environment variables id: set-env run: | - # Write to GITHUB_OUTPUT from environment variables - echo "new_branch=$NEW_BRANCH" >> $GITHUB_OUTPUT - [[ ! -z "$EXTRA_VERSION_IDENTIFIER" ]] && echo "extra_version_identifier=$EXTRA_VERSION_IDENTIFIER" >> $GITHUB_OUTPUT - [[ ! -z "$VERSION" ]] && echo "version=$VERSION" >> $GITHUB_OUTPUT + echo "new_branch=${{ needs.prepare_strategy.outputs.new_branch }}" >> $GITHUB_OUTPUT + echo "version=${{ needs.prepare_strategy.outputs.version }}" >> $GITHUB_OUTPUT + echo "extra_version_identifier=${{ needs.prepare_strategy.outputs.extra_version_identifier }}" >> $GITHUB_OUTPUT echo "commit_sha=${{ github.sha }}" >> $GITHUB_OUTPUT - + # Set up common environment source /etc/profile; export UV_PROJECT_ENVIRONMENT=${HOME}/venv + export UV_PYTHON_PREFERENCE=managed + export UV_PYTHON_INSTALL_DIR=${HOME}/uv/python export VIRTUAL_ENV=$UV_PROJECT_ENVIRONMENT + uv sync printenv >> $GITHUB_ENV if [[ "${{ runner.debug }}" == "1" ]]; then cat $GITHUB_OUTPUT @@ -157,14 +175,27 @@ jobs: if [[ "${{ runner.debug }}" == "1" ]]; then printenv fi + source ${UV_PROJECT_ENVIRONMENT}/bin/activate PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --disable - name: Build Main Project run: | export PYTHONPATH="$BUILD_DIR" - ./release/release_files.py | sort | uniq | rsync -rRl${RUNNER_DEBUG:+v} --files-from=- . $BUILD_DIR/ + ./tools/release/release_files.py | sort | uniq | rsync -rRl${RUNNER_DEBUG:+v} --files-from=- . $BUILD_DIR/ cd $BUILD_DIR + ln -sfn msgq_repo/msgq msgq + ln -sfn opendbc_repo/opendbc opendbc + ln -sfn rednose_repo/rednose rednose + ln -sfn teleoprtc_repo/teleoprtc teleoprtc + ln -sfn tinygrad_repo/tinygrad tinygrad sed -i '/from .board.jungle import PandaJungle, PandaJungleDFU/s/^/#/' panda/__init__.py + echo "Building sunnypilot's modeld_v2..." + scons -j$(nproc) cache_dir=${{env.SCONS_CACHE_DIR}} --minimal openpilot/sunnypilot/modeld_v2 + echo "Building sunnypilot's locationd..." + scons -j2 cache_dir=${{env.SCONS_CACHE_DIR}} --minimal openpilot/sunnypilot/selfdrive/locationd + echo "Building openpilot's locationd..." + scons -j1 cache_dir=${{env.SCONS_CACHE_DIR}} --minimal openpilot/selfdrive/locationd + echo "Building rest of sunnypilot" scons -j$(nproc) cache_dir=${{env.SCONS_CACHE_DIR}} --minimal touch ${BUILD_DIR}/prebuilt if [[ "${{ runner.debug }}" == "1" ]]; then @@ -176,37 +207,27 @@ jobs: sudo rm -rf ${OUTPUT_DIR} mkdir -p ${OUTPUT_DIR} rsync -am${RUNNER_DEBUG:+v} \ - --include='**/panda/board/' \ - --include='**/panda/board/obj' \ - --include='**/panda/board/obj/panda.bin.signed' \ - --include='**/panda/board/obj/panda_h7.bin.signed' \ - --include='**/panda/board/obj/bootstub.panda.bin' \ - --include='**/panda/board/obj/bootstub.panda_h7.bin' \ --exclude='.sconsign.dblite' \ --exclude='*.a' \ --exclude='*.o' \ --exclude='*.os' \ --exclude='*.pyc' \ --exclude='moc_*' \ - --exclude='*.cc' \ + --exclude='__pycache__' \ --exclude='Jenkinsfile' \ - --exclude='supercombo.onnx' \ - --exclude='**/panda/board/*' \ - --exclude='**/panda/board/obj/**' \ - --exclude='**/panda/certs/' \ - --exclude='**/panda/crypto/' \ --exclude='**/release/' \ --exclude='**/.github/' \ - --exclude='**/selfdrive/ui/replay/' \ + --exclude='**/openpilot/selfdrive/ui/replay/' \ --exclude='**/__pycache__/' \ - --exclude='**/selfdrive/ui/*.h' \ - --exclude='**/selfdrive/ui/**/*.h' \ - --exclude='**/selfdrive/ui/qt/offroad/sunnypilot/' \ --exclude='${{env.SCONS_CACHE_DIR}}' \ --exclude='**/.git/' \ --exclude='**/SConstruct' \ --exclude='**/SConscript' \ --exclude='**/.venv/' \ + --exclude='openpilot/selfdrive/modeld/models/*.onnx*' \ + --exclude='openpilot/sunnypilot/modeld*/models/*.onnx*' \ + --exclude='openpilot/third_party/*x86*' \ + --exclude='openpilot/third_party/*Darwin*' \ --delete-excluded \ --chown=comma:comma \ ${BUILD_DIR}/ ${OUTPUT_DIR}/ @@ -225,17 +246,21 @@ jobs: - name: Re-enable powersave if: always() run: | + source ${UV_PROJECT_ENVIRONMENT}/bin/activate PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --enable publish: concurrency: - group: publish-${{ github.head_ref || github.ref_name }} - cancel-in-progress: true - if: ${{ (always() && !failure() && !cancelled()) && (!contains(github.event_name, 'pull_request') || (github.event.action == 'labeled' && github.event.label.name == 'prebuilt')) }} - needs: [ build ] + # We do a bit of a hack here to avoid canceling the publishing job if a new commit comes in while we're publishing by adding the sha to the group name. + # This means that if multiple commits come in while we're publishing, they will be queued up and publish one after the other. + # Otherwise, if a job is waiting to be published due to environment wait time, it would be canceled by a new commit and restart the wait time. + group: ${{ needs.prepare_strategy.outputs.publish_concurrency_group }} + cancel-in-progress: ${{ needs.prepare_strategy.outputs.cancel_publish_in_progress == 'true' }} + if: ${{ (always() && !cancelled() && !failure()) && needs.build.result == 'success' && needs.prepare_strategy.result == 'success' && (!contains(github.event_name, 'pull_request') || (github.event.action == 'labeled' && github.event.label.name == 'prebuilt')) }} + needs: [ build, prepare_strategy ] runs-on: ubuntu-24.04 - environment: ${{ (contains(fromJSON(vars.AUTO_DEPLOY_PREBUILT_BRANCHES), github.head_ref || github.ref_name) || contains(github.event.pull_request.labels.*.name, 'prebuilt')) && 'auto-deploy' || 'feature-branch' }} + environment: ${{ needs.prepare_strategy.outputs.environment }} steps: - uses: actions/checkout@v4 @@ -267,8 +292,8 @@ jobs: "${{ needs.build.outputs.new_branch }}" \ "${{ needs.build.outputs.version }}" \ "https://x-access-token:${{github.token}}@github.com/sunnypilot/sunnypilot.git" \ - "-${{ needs.build.outputs.extra_version_identifier }}" - + "${{ needs.build.outputs.extra_version_identifier }}" + echo "" echo "---- ℹ️ To update the list of branches that auto deploy prebuilts -----" echo "" @@ -276,38 +301,60 @@ jobs: echo "2. Current value: ${{ vars.AUTO_DEPLOY_PREBUILT_BRANCHES }}" echo "3. Update as needed (JSON array with no spaces)" + - name: Tag ${{ needs.prepare_strategy.outputs.environment }} + if: ${{ needs.prepare_strategy.outputs.is_stable_branch == 'true' && (github.event_name != 'push' || !startsWith(github.ref, 'refs/tags/')) }} + run: | + TAG="${{ needs.prepare_strategy.outputs.environment }}/${{ needs.prepare_strategy.outputs.version }}/${{ needs.prepare_strategy.outputs.build }}" + git tag -f -a ${TAG} -m "${{ needs.prepare_strategy.outputs.environment }} @ ${{ needs.prepare_strategy.outputs.version }} of build ${{ needs.build.outputs.build }}." + git push -f origin ${TAG} + notify: - needs: [ build, publish ] + needs: + - prepare_strategy + - build + - publish runs-on: ubuntu-24.04 - if: ${{ (always() && !failure() && !cancelled()) && (!contains(github.event_name, 'pull_request') || (github.event.action == 'labeled' && github.event.label.name == 'prebuilt')) }} + if: ${{ (always() && !cancelled() && !failure()) + && needs.publish.result == 'success' + && (!contains(github.event_name, 'pull_request') || (github.event.action == 'labeled' && github.event.label.name == 'prebuilt')) + && (fromJSON(vars.DEV_FEEDBACK_NOTIFICATION_BRANCHES_V2)[github.head_ref || github.ref_name] != null) }} steps: - uses: actions/checkout@v4 - - name: Setup Alpine Linux environment - uses: jirutka/setup-alpine@v1.2.0 - with: - packages: 'jq gettext curl' - - name: Send Discord Notification - env: - DISCORD_WEBHOOK: ${{ contains(fromJSON(vars.DEV_FEEDBACK_NOTIFICATION_BRANCHES), env.SOURCE_BRANCH) && secrets.DISCORD_DEV_FEEDBACK_CHANNEL_WEBHOOK || secrets.DISCORD_DEV_PRIVATE_CHANNEL_WEBHOOK }} + - name: Prepare notification message + id: message run: | - TEMPLATE='${{ vars.DISCORD_GENERAL_UPDATE_NOTICE }}' - export EXTRA_VERSION_IDENTIFIER="${{ needs.build.outputs.extra_version_identifier }}" - export VERSION="${{ needs.build.outputs.version }}" - export branch_name=${{ env.SOURCE_BRANCH }} - export new_branch=${{ needs.build.outputs.new_branch }} - export extra_version_identifier=${{ needs.build.outputs.extra_version_identifier || github.run_number}} - echo ${TEMPLATE} | envsubst | jq -c '.' | tee payload.json - curl -X POST -H "Content-Type: application/json" -d @payload.json $DISCORD_WEBHOOK - - echo "" - echo "---- ℹ️ To update the list of branches that notify to dev-feedback -----" - echo "" - echo "1. Go to: ${{ github.server_url }}/${{ github.repository }}/settings/variables/actions/DEV_FEEDBACK_NOTIFICATION_BRANCHES" - echo "2. Current value: ${{ vars.DEV_FEEDBACK_NOTIFICATION_BRANCHES }}" - echo "3. Update as needed (JSON array with no spaces)" - shell: alpine.sh {0} - + TEMPLATE='${{ vars.DISCOURSE_GENERAL_UPDATE_NOTICE }}' + export VERSION="${{ needs.prepare_strategy.outputs.version }}" + export branch_name="${{ env.SOURCE_BRANCH }}" + export new_branch="${{ needs.prepare_strategy.outputs.new_branch }}" + export commit_sha="${{ github.sha }}" + export commit_short_sha="${{ github.sha }}" + export commit_short_sha="${commit_short_sha:0:7}" + export extra_version_identifier="${{ needs.prepare_strategy.outputs.extra_version_identifier || github.run_number }}" + export PUBLIC_REPO_URL="${{ env.PUBLIC_REPO_URL }}" + + MESSAGE=$(cat << 'EOF' | envsubst + ${{ vars.DISCOURSE_GENERAL_UPDATE_NOTICE }} + EOF + ) + + { + echo 'content<> $GITHUB_OUTPUT + shell: bash + + - name: Post to Discourse + uses: ./.github/workflows/post-to-discourse + with: + discourse-url: ${{ vars.DISCOURSE_URL }} + api-key: ${{ secrets.DISCOURSE_API_KEY }} + api-username: "system" + topic-id: ${{ fromJSON(vars.DEV_FEEDBACK_NOTIFICATION_BRANCHES_V2)[github.head_ref || github.ref_name].topic_id }} + message: ${{ steps.message.outputs.content }} + manage-pr-labels: name: Remove prebuilt label runs-on: ubuntu-latest @@ -326,7 +373,7 @@ jobs: owner: context.repo.owner, repo: context.repo.repo, issue_number: prNumber, - name: process.env.LABEL + name: process.env.LABELf }); console.log(`Removed '${process.env.LABEL}' label from PR #${prNumber}`); diff --git a/.github/workflows/sunnypilot-master-dev-c3-prep.yaml b/.github/workflows/sunnypilot-master-dev-c3-prep.yaml deleted file mode 100644 index 031be6a50d..0000000000 --- a/.github/workflows/sunnypilot-master-dev-c3-prep.yaml +++ /dev/null @@ -1,224 +0,0 @@ -name: Build dev-c3-new - -env: - DEFAULT_SOURCE_BRANCH: "master-new" - DEFAULT_TARGET_BRANCH: "master-dev-c3-new" - PR_LABEL: "dev-c3" - LFS_URL: 'https://gitlab.com/sunnypilot/public/sunnypilot-new-lfs.git/info/lfs' - LFS_PUSH_URL: 'ssh://git@gitlab.com/sunnypilot/public/sunnypilot-new-lfs.git' - -on: - push: - branches: - - master - - master-new - pull_request_target: - types: [ labeled ] - branches: - - 'master' - - 'master-new' - workflow_dispatch: - inputs: - source_branch: - description: 'Source branch to reset from' - required: true - default: 'master-new' - type: string - target_branch: - description: 'Target branch to reset and squash into' - required: true - default: 'master-dev-c3-new' - type: string - cancel_in_progress: - description: 'Cancel any in-progress runs of this workflow' - required: false - default: true - type: boolean - -concurrency: - group: ${{ github.workflow }} - cancel-in-progress: ${{ inputs.cancel_in_progress || github.event_name == 'push' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch) }} - -jobs: - reset-and-squash: - runs-on: ubuntu-latest - if: ( - (github.event_name == 'workflow_dispatch') - || (github.event_name == 'push' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch)) - || (contains(github.event_name, 'pull_request') && ((github.event.action == 'labeled' && (github.event.label.name == 'dev-c3' || github.event.label.name == 'trust-fork-pr') && contains(github.event.pull_request.labels.*.name, 'dev-c3')))) - ) - steps: - - uses: actions/checkout@v4 - with: - fetch-depth: 0 # Fetch all history for all branches - token: ${{ secrets.GITHUB_TOKEN }} - - - name: Wait for Tests - uses: ./.github/workflows/wait-for-action # Path to where you place the action - if: ( - (github.event_name == 'push' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch)) - || (contains(github.event_name, 'pull_request') && ((github.event.action == 'labeled' && (github.event.label.name == 'dev-c3' || github.event.label.name == 'trust-fork-pr') && contains(github.event.pull_request.labels.*.name, 'dev-c3')))) - ) - with: - workflow: selfdrive_tests.yaml # The workflow file to monitor - github-token: ${{ secrets.GITHUB_TOKEN }} - - - name: Configure Git - run: | - git config --global user.name 'github-actions[bot]' - git config --global user.email 'github-actions[bot]@users.noreply.github.com' - - - name: Set up SSH - uses: webfactory/ssh-agent@v0.9.0 - with: - ssh-private-key: ${{ secrets.SSH_PRIVATE_KEY }} - - - name: Add GitLab public keys - run: | - ssh-keyscan -H gitlab.com >> ~/.ssh/known_hosts - - - name: Set up Python - uses: actions/setup-python@v5 - with: - python-version: '3.10' - - - name: Install dependencies - run: | - python -m pip install --upgrade pip - pip install PyGithub - - - name: Check branches exist - run: | - # Check if source branch exists - if ! git ls-remote --heads origin ${{ inputs.source_branch || env.DEFAULT_SOURCE_BRANCH }} | grep -q "${{ inputs.source_branch || env.DEFAULT_SOURCE_BRANCH }}"; then - echo "Source branch ${{ inputs.source_branch || env.DEFAULT_SOURCE_BRANCH }} does not exist!" - exit 1 - fi - - # Make sure we have the latest source branch - git fetch origin ${{ inputs.source_branch || env.DEFAULT_SOURCE_BRANCH }} - - # Check if target branch exists - if ! git ls-remote --heads origin ${{ inputs.target_branch || env.DEFAULT_TARGET_BRANCH }} | grep -q "${{ inputs.target_branch || env.DEFAULT_TARGET_BRANCH }}"; then - echo "Target branch ${{ inputs.target_branch || env.DEFAULT_TARGET_BRANCH }} does not exist, creating it from ${{ inputs.source_branch || env.DEFAULT_SOURCE_BRANCH }}" - git checkout -b ${{ inputs.target_branch || env.DEFAULT_TARGET_BRANCH }} origin/${{ inputs.source_branch || env.DEFAULT_SOURCE_BRANCH }} - git push origin ${{ inputs.target_branch || env.DEFAULT_TARGET_BRANCH }} - else - # Fetch target branch if it exists - git fetch origin ${{ inputs.target_branch || env.DEFAULT_TARGET_BRANCH }} - fi - - - name: Reset target branch - run: | - echo "Resetting ${{ inputs.target_branch || env.DEFAULT_TARGET_BRANCH }} to match ${{ inputs.source_branch || env.DEFAULT_SOURCE_BRANCH }}" - # Delete if exists and recreate pointing to source - git branch -D ${{ inputs.target_branch || env.DEFAULT_TARGET_BRANCH }} || true - git branch ${{ inputs.target_branch || env.DEFAULT_TARGET_BRANCH }} origin/${{ inputs.source_branch || env.DEFAULT_SOURCE_BRANCH }} - - - name: Get PRs to squash - id: get-prs - run: | - # Use GitHub API to get PRs with specific label, ordered by creation date - PR_LIST=$(gh api graphql -f query=' - query($label:String!) { - search(query: $label, type:ISSUE, first:100) { - nodes { - ... on PullRequest { - number - headRefName - title - createdAt - labels(last:10) { - nodes { - name - } - } - headRepository { - name - nameWithOwner - url - isFork - } - commits(last: 1) { - nodes { - commit { - statusCheckRollup { - state - } - } - } - } - } - } - } - }' -F label="is:pr is:open label:${PR_LABEL} draft:false sort:created-asc") - - echo "PR_LIST=${PR_LIST}" >> $GITHUB_OUTPUT - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - - - name: Process PRs - run: | - cp ${{ github.workspace }}/release/ci/squash_and_merge.py /tmp/squash_and_merge.py && \ - chmod +x /tmp/squash_and_merge.py && \ - python3 ${{ github.workspace }}/release/ci/squash_and_merge_prs.py \ - --pr-data '${{ steps.get-prs.outputs.PR_LIST }}' \ - --target-branch ${{ inputs.target_branch || env.DEFAULT_TARGET_BRANCH }} \ - --squash-script-path '/tmp/squash_and_merge.py' - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - - - name: Update LFS Config - run: | - echo '[lfs]' > .lfsconfig - echo ' url = ${{ env.LFS_URL }}' >> .lfsconfig - echo ' pushurl = ${{ env.LFS_PUSH_URL }}' >> .lfsconfig - echo ' locksverify = false' >> .lfsconfig - - - name: Push changes if there are diffs - id: push-changes # Add an id so we can reference this step - run: | - TARGET_BRANCH="${{ inputs.target_branch || env.DEFAULT_TARGET_BRANCH }}" - - # Fetch the latest from remote - git fetch origin $TARGET_BRANCH - - # Check for diffs between local and remote - if git diff $TARGET_BRANCH origin/$TARGET_BRANCH --quiet; then - echo "No changes to push - local and remote branches are identical" - echo "has_changes=false" >> $GITHUB_OUTPUT - exit 0 - fi - - # If we get here, there are diffs, so push - if ! git push origin $TARGET_BRANCH --force; then - echo "Failed to push changes to $TARGET_BRANCH" - exit 1 - fi - - echo "Branch $TARGET_BRANCH has been reset and updated with squashed PRs" - echo "has_changes=true" >> $GITHUB_OUTPUT - - - name: Trigger and wait for selfdrive tests - if: steps.push-changes.outputs.has_changes == 'true' - run: | - echo "Triggering selfdrive tests..." - gh workflow run selfdrive_tests.yaml --ref "${{ inputs.target_branch || env.DEFAULT_TARGET_BRANCH }}" - - echo "Sleeping for 120s to give plenty of time for the action to start and then we wait" - sleep 120 - - echo "Getting latest run ID..." - RUN_ID=$(gh run list --workflow=selfdrive_tests.yaml --branch="${{ inputs.target_branch || env.DEFAULT_TARGET_BRANCH }}" --limit=1 --json databaseId --jq '.[0].databaseId') - - echo "Watching run ID: $RUN_ID" - gh run watch "$RUN_ID" - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - - - name: Trigger prebuilt workflow - if: success() && steps.push-changes.outputs.has_changes == 'true' - run: | - gh workflow run sunnypilot-build-prebuilt.yaml --ref "${{ inputs.target_branch || env.DEFAULT_TARGET_BRANCH }}" - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/sunnypilot-master-dev-prep.yaml b/.github/workflows/sunnypilot-master-dev-prep.yaml new file mode 100644 index 0000000000..1cb574764b --- /dev/null +++ b/.github/workflows/sunnypilot-master-dev-prep.yaml @@ -0,0 +1,243 @@ +name: Build dev + +env: + DEFAULT_SOURCE_BRANCH: "master" + DEFAULT_TARGET_BRANCH: "master-dev" + LFS_URL: 'https://gitlab.com/sunnypilot/public/sunnypilot-new-lfs.git/info/lfs' + LFS_PUSH_URL: 'ssh://git@gitlab.com/sunnypilot/public/sunnypilot-new-lfs.git' + +on: + push: + branches: + - master + pull_request_target: + types: [ labeled ] + branches: + - 'master' + workflow_dispatch: + inputs: + source_branch: + description: 'Source branch to reset from' + required: true + default: 'master' + type: string + target_branch: + description: 'Target branch to reset and squash into' + required: true + default: 'master-dev' + type: string + cancel_in_progress: + description: 'Cancel any in-progress runs of this workflow' + required: false + default: true + type: boolean + +concurrency: + group: ${{ github.workflow }} + cancel-in-progress: ${{ inputs.cancel_in_progress || github.event_name == 'push' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch) }} + +jobs: + reset-and-squash: + runs-on: ubuntu-latest + if: ( + (github.event_name == 'workflow_dispatch') + || (github.event_name == 'push' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch)) + || (contains(github.event_name, 'pull_request') && ((github.event.action == 'labeled' && (github.event.label.name == vars.PREBUILT_PR_LABEL || github.event.label.name == 'trust-fork-pr') && contains(github.event.pull_request.labels.*.name, vars.PREBUILT_PR_LABEL)))) + ) + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 # Fetch all history for all branches + token: ${{ secrets.GITHUB_TOKEN }} + persist-credentials: false + + - name: Wait for Tests + uses: ./.github/workflows/wait-for-action # Path to where you place the action + if: ( + (github.event_name == 'push' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch)) + || (contains(github.event_name, 'pull_request') && ((github.event.action == 'labeled' && (github.event.label.name == vars.PREBUILT_PR_LABEL || github.event.label.name == 'trust-fork-pr') && contains(github.event.pull_request.labels.*.name, vars.PREBUILT_PR_LABEL)))) + ) + with: + workflow: tests.yaml # The workflow file to monitor + github-token: ${{ secrets.GITHUB_TOKEN }} + + - name: Configure Git + run: | + git config --global user.name 'github-actions[bot]' + git config --global user.email 'github-actions[bot]@users.noreply.github.com' + + - name: Set up SSH + uses: webfactory/ssh-agent@v0.9.0 + with: + ssh-private-key: ${{ secrets.SSH_PRIVATE_KEY }} + + - name: Add GitLab public keys + run: | + ssh-keyscan -H gitlab.com >> ~/.ssh/known_hosts + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: '3.10' + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install PyGithub + + - name: Check branches exist + run: | + # Check if source branch exists + if ! git ls-remote --heads origin ${{ inputs.source_branch || env.DEFAULT_SOURCE_BRANCH }} | grep -q "${{ inputs.source_branch || env.DEFAULT_SOURCE_BRANCH }}"; then + echo "Source branch ${{ inputs.source_branch || env.DEFAULT_SOURCE_BRANCH }} does not exist!" + exit 1 + fi + + # Make sure we have the latest source branch + git fetch origin ${{ inputs.source_branch || env.DEFAULT_SOURCE_BRANCH }} + + # Check if target branch exists + if ! git ls-remote --heads origin ${{ inputs.target_branch || env.DEFAULT_TARGET_BRANCH }} | grep -q "${{ inputs.target_branch || env.DEFAULT_TARGET_BRANCH }}"; then + echo "Target branch ${{ inputs.target_branch || env.DEFAULT_TARGET_BRANCH }} does not exist, creating it from ${{ inputs.source_branch || env.DEFAULT_SOURCE_BRANCH }}" + git checkout -b ${{ inputs.target_branch || env.DEFAULT_TARGET_BRANCH }} origin/${{ inputs.source_branch || env.DEFAULT_SOURCE_BRANCH }} + git push origin ${{ inputs.target_branch || env.DEFAULT_TARGET_BRANCH }} + else + # Fetch target branch if it exists + git fetch origin ${{ inputs.target_branch || env.DEFAULT_TARGET_BRANCH }} + fi + + - name: Reset target branch + run: | + echo "Resetting ${{ inputs.target_branch || env.DEFAULT_TARGET_BRANCH }} to match ${{ inputs.source_branch || env.DEFAULT_SOURCE_BRANCH }}" + # Delete if exists and recreate pointing to source + git branch -D ${{ inputs.target_branch || env.DEFAULT_TARGET_BRANCH }} || true + git branch ${{ inputs.target_branch || env.DEFAULT_TARGET_BRANCH }} origin/${{ inputs.source_branch || env.DEFAULT_SOURCE_BRANCH }} + + - name: Get PRs to squash + id: get-prs + run: | + # Use GitHub API to get PRs with specific label, ordered by creation date + PR_LIST=$(gh api graphql -f query=' + query($search_query:String!) { + search(query: $search_query, type:ISSUE, first:40) { + nodes { + ... on PullRequest { + number + headRefName + title + createdAt + labels(last:10) { + nodes { + name + } + } + headRepository { + name + nameWithOwner + url + isFork + } + commits(last: 1) { + nodes { + commit { + statusCheckRollup { + state + } + } + } + } + } + } + } + }' -F search_query="repo:${{ github.repository }} is:pr is:open label:${{ vars.PREBUILT_PR_LABEL }},${{ vars.PREBUILT_PR_LABEL }}-c3 draft:false sort:created-asc") + + PR_LIST=${PR_LIST//\'/} + echo "PR_LIST=${PR_LIST}" >> $GITHUB_OUTPUT + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Process PRs + run: | + cp ${{ github.workspace }}/release/ci/squash_and_merge.py /tmp/squash_and_merge.py && \ + chmod +x /tmp/squash_and_merge.py && \ + python3 ${{ github.workspace }}/release/ci/squash_and_merge_prs.py \ + --pr-data '${{ steps.get-prs.outputs.PR_LIST }}' \ + --target-branch ${{ inputs.target_branch || env.DEFAULT_TARGET_BRANCH }} \ + --squash-script-path '/tmp/squash_and_merge.py' + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Update LFS Config + run: | + echo '[lfs]' > .lfsconfig + echo ' url = ${{ env.LFS_URL }}' >> .lfsconfig + echo ' pushurl = ${{ env.LFS_PUSH_URL }}' >> .lfsconfig + echo ' locksverify = false' >> .lfsconfig + + - name: Restore workflows from source + run: | + TARGET_BRANCH="${{ inputs.target_branch || env.DEFAULT_TARGET_BRANCH }}" + SOURCE_BRANCH="${{ inputs.source_branch || env.DEFAULT_SOURCE_BRANCH }}" + + # Ensure we are on the target branch + git checkout $TARGET_BRANCH + + echo "Restoring .github/workflows from $SOURCE_BRANCH" + git checkout origin/$SOURCE_BRANCH -- .github/workflows + + if ! git diff --cached --quiet; then + echo "Workflows differ. Committing restoration." + git commit -m "chore: restore .github/workflows from $SOURCE_BRANCH" + else + echo "Workflows match $SOURCE_BRANCH." + fi + + - uses: actions/create-github-app-token@v2 + id: ci-token + with: + app-id: ${{ secrets.CI_GITHUB_ACTIONS_TOKEN_APP_ID }} + private-key: ${{ secrets.CI_GITHUB_ACTIONS_TOKEN_APP_PRIVATE_KEY }} + + - name: Push changes if there are diffs + id: push-changes + run: | + TARGET_BRANCH="${{ inputs.target_branch || env.DEFAULT_TARGET_BRANCH }}" + + # Use the App Token to set the remote URL with authentication + git remote set-url origin "https://x-access-token:${{ steps.ci-token.outputs.token }}@github.com/${{ github.repository }}.git" + + # Fetch the latest from remote + git fetch origin $TARGET_BRANCH + + # Check for diffs between local and remote + if git diff $TARGET_BRANCH origin/$TARGET_BRANCH --quiet; then + echo "No changes to push - local and remote branches are identical" + echo "has_changes=false" >> $GITHUB_OUTPUT + exit 0 + fi + + # Push with the authenticated origin + if ! git push origin $TARGET_BRANCH --force; then + echo "Failed to push changes to $TARGET_BRANCH" + exit 1 + fi + + echo "Branch $TARGET_BRANCH has been reset and updated with squashed PRs" + echo "has_changes=true" >> $GITHUB_OUTPUT + + - name: Trigger and wait for selfdrive tests + if: steps.push-changes.outputs.has_changes == 'true' + run: | + echo "Triggering selfdrive tests..." + gh workflow run tests.yaml --ref "${{ inputs.target_branch || env.DEFAULT_TARGET_BRANCH }}" + + echo "Sleeping for 120s to give plenty of time for the action to start and then we wait" + sleep 120 + + echo "Getting latest run ID..." + RUN_ID=$(gh run list --workflow=tests.yaml --branch="${{ inputs.target_branch || env.DEFAULT_TARGET_BRANCH }}" --limit=1 --json databaseId --jq '.[0].databaseId') + + echo "Watching run ID: $RUN_ID" + gh run watch "$RUN_ID" + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/test-discourse.yaml.yml b/.github/workflows/test-discourse.yaml.yml new file mode 100644 index 0000000000..fadaec4eaa --- /dev/null +++ b/.github/workflows/test-discourse.yaml.yml @@ -0,0 +1,78 @@ +name: Debug Discourse Posting + +on: + push: + +jobs: + test-discourse-post: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Post test message to Discourse + uses: ./.github/workflows/post-to-discourse + with: + discourse-url: ${{ vars.DISCOURSE_URL }} + api-key: ${{ secrets.DISCOURSE_API_KEY }} + api-username: ${{ secrets.DISCOURSE_API_USERNAME }} + topic-id: ${{ vars.DISCOURSE_UPDATES_TOPIC_ID }} + message: | + ## 🧪 Test Post from GitHub Actions + + **This is a test post to verify Discourse integration** + + - **Workflow**: ${{ github.workflow }} + - **Run Number**: #${{ github.run_number }} + - **Branch**: `${{ github.ref_name }}` + - **Commit**: ${{ github.sha }} + - **Actor**: @${{ github.actor }} + - **Timestamp**: ${{ github.event.head_commit.timestamp }} + + --- + + ### Fake Build Info (for testing) + - **Version**: 0.9.8-test + - **Build**: #42 + - **Branch**: release-test + + [View workflow run](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}) + + *This is an automated test message. Drive safe! 🚗💨* + + + - name: Create topic on Discourse + uses: ./.github/workflows/post-to-discourse + with: + discourse-url: ${{ vars.DISCOURSE_URL }} + api-key: ${{ secrets.DISCOURSE_API_KEY }} + api-username: ${{ secrets.DISCOURSE_API_USERNAME }} + #topic-id: ${{ vars.DISCOURSE_UPDATES_TOPIC_ID }} + category-id: 4 + title: "This is a test of a new topic instead of a reply" + message: | + ## 🧪 Test Post from GitHub Actions + + **This is a test post to verify Discourse integration** + + - **Workflow**: ${{ github.workflow }} + - **Run Number**: #${{ github.run_number }} + - **Branch**: `${{ github.ref_name }}` + - **Commit**: ${{ github.sha }} + - **Actor**: @${{ github.actor }} + - **Timestamp**: ${{ github.event.head_commit.timestamp }} + + --- + + ### Fake Build Info (for testing) + - **Version**: 0.9.8-test + - **Build**: #42 + - **Branch**: release-test + + [View workflow run](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}) + + *This is an automated test message. Drive safe! 🚗💨* + - name: Display results + if: always() + run: | + echo "::notice::Discourse post test completed" + echo "Check your Discourse topic to verify the post appeared correctly" \ No newline at end of file diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml new file mode 100644 index 0000000000..b5f941fc76 --- /dev/null +++ b/.github/workflows/tests.yaml @@ -0,0 +1,251 @@ +name: tests + +on: + push: + branches: + - master + pull_request: + workflow_dispatch: + workflow_call: + inputs: + run_number: + default: '1' + required: true + type: string + +concurrency: + group: tests-ci-run-${{ inputs.run_number }}-${{ github.event_name == 'push' && github.ref == 'refs/heads/master' && github.run_id || github.head_ref || github.ref }}-${{ github.workflow }}-${{ github.event_name }} + cancel-in-progress: true + +env: + CI: 1 + PYTHONPATH: ${{ github.workspace }} + PYTEST: pytest --continue-on-collection-errors --durations=0 -n logical + +jobs: + build_release: + name: build release + runs-on: ${{ + (github.repository == 'commaai/openpilot') && + ((github.event_name != 'pull_request') || + (github.event.pull_request.head.repo.full_name == 'commaai/openpilot')) + && fromJSON('["namespace-profile-amd64-8x16"]') + || fromJSON('["ubuntu-24.04"]') }} + env: + STRIPPED_DIR: /tmp/releasepilot + PYTHONPATH: /tmp/releasepilot + steps: + - uses: actions/checkout@v7 + with: + submodules: true + - name: Getting LFS files + uses: nick-fields/retry@ad984534de44a9489a53aefd81eb77f87c70dc60 + with: + timeout_minutes: 2 + max_attempts: 3 + command: git lfs pull + - name: Build devel + timeout-minutes: 3 + run: TARGET_DIR=$STRIPPED_DIR tools/release/build_stripped.sh + - run: ./tools/op.sh setup + - name: Build openpilot and run checks + timeout-minutes: 30 + working-directory: ${{ env.STRIPPED_DIR }} + run: python3 openpilot/system/manager/build.py + - name: Run tests + timeout-minutes: 1 + working-directory: ${{ env.STRIPPED_DIR }} + run: tools/release/check-dirty.sh + - name: Check submodules + if: github.repository == 'sunnypilot/sunnypilot' + timeout-minutes: 3 + run: | + if [ "${{ github.ref }}" != "refs/heads/master" ]; then + git fetch origin master:refs/remotes/origin/master + + SUBMODULE_PATHS=$(git diff origin/master HEAD --name-only | grep -E '^[^/]+$' | while read path; do + if git ls-files --stage "$path" | grep -q "^160000"; then + echo "$path" + fi + done | tr '\n' ' ') + + if [ -n "$SUBMODULE_PATHS" ]; then + echo "Changed submodule paths: $SUBMODULE_PATHS" + export SUBMODULE_PATHS="$SUBMODULE_PATHS" + export CHECK_PR_REFS=true + fi + fi + tools/release/check-submodules.sh + + build_mac: + name: build macOS + runs-on: ${{ ((github.repository == 'commaai/openpilot') && ((github.event_name != 'pull_request') || (github.event.pull_request.head.repo.full_name == 'commaai/openpilot'))) && 'namespace-profile-macos-8x14' || 'macos-latest' }} + steps: + - uses: actions/checkout@v7 + - name: Remove Homebrew from environment + run: | + FILTERED=$(echo "$PATH" | tr ':' '\n' | grep -v '/opt/homebrew' | tr '\n' ':') + echo "PATH=${FILTERED}/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin" >> $GITHUB_ENV + - run: ./tools/op.sh setup + - name: Building openpilot + run: scons + + static_analysis: + name: static analysis + runs-on: ${{ + (github.repository == 'commaai/openpilot') && + ((github.event_name != 'pull_request') || + (github.event.pull_request.head.repo.full_name == 'commaai/openpilot')) + && fromJSON('["namespace-profile-amd64-8x16"]') + || fromJSON('["ubuntu-24.04"]') }} + steps: + - uses: actions/checkout@v7 + - run: ./tools/op.sh setup + - name: Static analysis + timeout-minutes: 1 + run: scripts/lint/lint.sh + + unit_tests: + name: unit tests + runs-on: ${{ + (github.repository == 'commaai/openpilot') && + ((github.event_name != 'pull_request') || + (github.event.pull_request.head.repo.full_name == 'commaai/openpilot')) + && fromJSON('["namespace-profile-amd64-8x16"]') + || fromJSON('["ubuntu-24.04"]') }} + steps: + - uses: actions/checkout@v7 + - run: ./tools/op.sh setup + - name: Install raylib headless dependencies + if: ${{ !contains(runner.name, 'nsc') }} + run: sudo apt-get install -y --no-install-recommends libgles2 libegl1 + - name: Build openpilot + run: scons + - name: Run unit tests + timeout-minutes: ${{ contains(runner.name, 'nsc') && 2 || 999 }} + env: + RAYLIB_BACKEND: headless + run: | + # Pre-compile Python bytecode so each pytest worker doesn't need to + $PYTEST --collect-only -m 'not slow' -qq + MAX_EXAMPLES=1 $PYTEST -m 'not slow' + + process_replay: + name: process replay + if: false # disable process_replay for forks + runs-on: ${{ + (github.repository == 'commaai/openpilot') && + ((github.event_name != 'pull_request') || + (github.event.pull_request.head.repo.full_name == 'commaai/openpilot')) + && fromJSON('["namespace-profile-amd64-8x16"]') + || fromJSON('["ubuntu-24.04"]') }} + steps: + - uses: actions/checkout@v7 + - run: ./tools/op.sh setup + - name: Build openpilot + run: scons + - name: Run replay + timeout-minutes: ${{ contains(runner.name, 'nsc') && 2 || 20 }} + continue-on-error: ${{ github.ref == 'refs/heads/master' }} + run: openpilot/selfdrive/test/process_replay/test_processes.py -j$(nproc) + - name: Print diff + id: print-diff + if: always() + run: cat openpilot/selfdrive/test/process_replay/diff.txt + - name: Print diff report + if: always() + run: cat openpilot/selfdrive/test/process_replay/diff_report.txt + - uses: actions/upload-artifact@v7 + if: always() + continue-on-error: true + with: + name: process_replay_diff.txt + path: openpilot/selfdrive/test/process_replay/diff.txt + - name: Upload diff report + uses: actions/upload-artifact@v7 + if: always() && github.event_name == 'pull_request' + continue-on-error: true + with: + name: diff_report_${{ github.event.number }} + path: openpilot/selfdrive/test/process_replay/diff_report.txt + - name: Checkout ci-artifacts + if: github.repository == 'commaai/openpilot' && github.ref == 'refs/heads/master' + uses: actions/checkout@v7 + with: + repository: commaai/ci-artifacts + ssh-key: ${{ secrets.CI_ARTIFACTS_DEPLOY_KEY }} + path: ${{ github.workspace }}/ci-artifacts + - name: Prepare refs + if: github.repository == 'commaai/openpilot' && github.ref == 'refs/heads/master' + working-directory: ${{ github.workspace }}/ci-artifacts + run: | + git config user.name "GitHub Actions Bot" + git config user.email "<>" + git fetch origin process-replay || true + git checkout process-replay 2>/dev/null || git checkout --orphan process-replay + cp ${{ github.workspace }}/openpilot/selfdrive/test/process_replay/fakedata/*.zst . + echo "${{ github.sha }}" > ref_commit + git add . + git commit -m "process-replay refs for ${{ github.repository }}@${{ github.sha }}" || echo "No changes to commit" + - name: Push refs + if: github.repository == 'commaai/openpilot' && github.ref == 'refs/heads/master' + uses: nick-fields/retry@ad984534de44a9489a53aefd81eb77f87c70dc60 + with: + timeout_minutes: 2 + max_attempts: 3 + command: cd ${{ github.workspace }}/ci-artifacts && git push origin process-replay --force + - name: Run regen + if: false + timeout-minutes: 4 + env: + ONNXCPU: 1 + run: $PYTEST openpilot/selfdrive/test/process_replay/test_regen.py + + simulator_driving: + name: simulator driving + runs-on: ${{ + (github.repository == 'commaai/openpilot') && + ((github.event_name != 'pull_request') || + (github.event.pull_request.head.repo.full_name == 'commaai/openpilot')) + && fromJSON('["namespace-profile-amd64-8x16"]') + || fromJSON('["ubuntu-24.04"]') }} + if: false # FIXME: Started to timeout recently + steps: + - uses: actions/checkout@v7 + - run: ./tools/op.sh setup + - name: Build openpilot + run: scons + - name: Driving test + timeout-minutes: 2 + env: + # MetaDrive renders offscreen through panda3d's EGL pipe on llvmpipe + EGL_PLATFORM: surfaceless + run: pytest -s openpilot/tools/sim/tests/test_metadrive_bridge.py + + create_ui_report: + name: Create UI Report + runs-on: ${{ + (github.repository == 'commaai/openpilot') && + ((github.event_name != 'pull_request') || + (github.event.pull_request.head.repo.full_name == 'commaai/openpilot')) + && fromJSON('["namespace-profile-amd64-8x16"]') + || fromJSON('["ubuntu-24.04"]') }} + steps: + - uses: actions/checkout@v7 + - run: ./tools/op.sh setup + - name: Install raylib headless dependencies + if: ${{ !contains(runner.name, 'nsc') }} + run: sudo apt-get install -y --no-install-recommends libgles2 libegl1 + - name: Build openpilot + run: scons + - name: Create UI Report + env: + RAYLIB_BACKEND: headless + run: | + python3 openpilot/selfdrive/ui/tests/diff/replay.py + python3 openpilot/selfdrive/ui/tests/diff/replay.py --big + - name: Upload UI Report + uses: actions/upload-artifact@v7 + with: + name: ui-report-${{ inputs.run_number || '1' }}-${{ github.event_name == 'push' && github.ref == 'refs/heads/master' && 'master' || github.event.number }} + path: openpilot/selfdrive/ui/tests/diff/report diff --git a/.github/workflows/ui_preview.yaml b/.github/workflows/ui_preview.yaml index f9b24e0f2c..8b7b63f344 100644 --- a/.github/workflows/ui_preview.yaml +++ b/.github/workflows/ui_preview.yaml @@ -3,21 +3,25 @@ on: push: branches: - master - - master-new pull_request_target: types: [assigned, opened, synchronize, reopened, edited] branches: - 'master' - - 'master-new' paths: - - 'selfdrive/ui/**' + - 'openpilot/selfdrive/assets/**' + - 'openpilot/selfdrive/ui/**' + - 'openpilot/system/ui/**' workflow_dispatch: env: UI_JOB_NAME: "Create UI Report" - REPORT_NAME: ${{ github.event_name == 'push' && (github.ref == 'refs/heads/master' || github.ref == 'refs/heads/master-new') && 'master' || github.event.number }} - SHA: ${{ github.event_name == 'push' && (github.ref == 'refs/heads/master' || github.ref == 'refs/heads/master-new') && github.sha || github.event.pull_request.head.sha }} - BRANCH_NAME: "openpilot/pr-${{ github.event.number }}" + REPORT_NAME: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' && 'master' || github.event.number }} + SHA: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' && github.sha || github.event.pull_request.head.sha }} + BRANCH_NAME: "openpilot/pr-${{ github.event.number }}-ui-preview" + REPORT_FILES_BRANCH_NAME: "mici-raylib-ui-reports" + + # variant:video_prefix:master_branch + VARIANTS: "mici:mici_ui_replay:openpilot_master_ui_mici_raylib big:tizi_ui_replay:openpilot_master_ui_big_raylib" jobs: preview: @@ -30,11 +34,12 @@ jobs: pull-requests: write actions: read steps: - - name: Waiting for ui generation to start - run: sleep 30 + - uses: actions/checkout@v7 + with: + submodules: true - name: Waiting for ui generation to end - uses: lewagon/wait-on-check-action@v1.3.4 + uses: lewagon/wait-on-check-action@1d57e2c51a58d812d2765e036a028b6bdb5a6154 with: ref: ${{ env.SHA }} check-name: ${{ env.UI_JOB_NAME }} @@ -48,110 +53,93 @@ jobs: echo "run_id=$(curl https://api.github.com/repos/${{ github.repository }}/commits/${{ env.SHA }}/check-runs | jq -r '.check_runs[] | select(.name == "${{ env.UI_JOB_NAME }}") | .html_url | capture("(?[0-9]+)") | .number')" >> $GITHUB_OUTPUT - name: Getting proposed ui - id: download-artifact - uses: dawidd6/action-download-artifact@v6 + uses: dawidd6/action-download-artifact@b6e2e70617bc3265edd6dab6c906732b2f1ae151 with: github_token: ${{ secrets.GITHUB_TOKEN }} run_id: ${{ steps.get_run_id.outputs.run_id }} search_artifacts: true - name: report-1-${{ env.REPORT_NAME }} + name: ui-report-1-${{ env.REPORT_NAME }} path: ${{ github.workspace }}/pr_ui - - name: Getting master ui - uses: actions/checkout@v4 + - name: Getting mici master ui + uses: actions/checkout@v7 with: repository: sunnypilot/ci-artifacts ssh-key: ${{ secrets.CI_ARTIFACTS_DEPLOY_KEY }} - path: ${{ github.workspace }}/master_ui - ref: openpilot_master_ui + path: ${{ github.workspace }}/master_mici + ref: openpilot_master_ui_mici_raylib + + - name: Getting big master ui + uses: actions/checkout@v7 + with: + repository: sunnypilot/ci-artifacts + ssh-key: ${{ secrets.CI_ARTIFACTS_DEPLOY_KEY }} + path: ${{ github.workspace }}/master_big + ref: openpilot_master_ui_big_raylib - name: Saving new master ui - if: (github.ref == 'refs/heads/master' || github.ref == 'refs/heads/master-new') && github.event_name == 'push' - working-directory: ${{ github.workspace }}/master_ui + if: github.ref == 'refs/heads/master' && github.event_name == 'push' run: | - git checkout --orphan=new_master_ui - git rm -rf * - git branch -D openpilot_master_ui - git branch -m openpilot_master_ui - git config user.name "GitHub Actions Bot" - git config user.email "<>" - mv ${{ github.workspace }}/pr_ui/*.png . - git add . - git commit -m "screenshots for commit ${{ env.SHA }}" - git push origin openpilot_master_ui --force + for variant in $VARIANTS; do + IFS=':' read -r name video branch <<< "$variant" + master_dir="${{ github.workspace }}/master_${name}" + cd "$master_dir" + git checkout --orphan=new_branch + git rm -rf * + git branch -D "$branch" + git branch -m "$branch" + git config user.name "GitHub Actions Bot" + git config user.email "<>" + cp "${{ github.workspace }}/pr_ui/${video}.mp4" . + git add . + git commit -m "${name} video for commit ${{ env.SHA }}" + git push origin "$branch" --force + done - - name: Finding diff + - name: Setup FFmpeg + uses: AnimMouse/setup-ffmpeg@178e0b4a408f06ce40d896c3cd79f50fa6f8b0c3 + + - name: Finding diffs if: github.event_name == 'pull_request_target' id: find_diff - run: >- - sudo apt-get update && sudo apt-get install -y imagemagick + run: | + export PYTHONPATH=${{ github.workspace }} + baseurl="https://github.com/sunnypilot/ci-artifacts/raw/refs/heads/${{ env.BRANCH_NAME }}" - scenes=$(find ${{ github.workspace }}/pr_ui/*.png -type f -printf "%f\n" | cut -d '.' -f 1 | grep -v 'pair_device') - A=($scenes) + COMMENT="" + for variant in $VARIANTS; do + IFS=':' read -r name video _ <<< "$variant" + diff_name="${name}_diff" - DIFF="" - TABLE="
All Screenshots" - TABLE="${TABLE}" + mv "${{ github.workspace }}/pr_ui/${video}.mp4" "${{ github.workspace }}/pr_ui/${video}_proposed.mp4" + cp "${{ github.workspace }}/master_${name}/${video}.mp4" "${{ github.workspace }}/pr_ui/${video}_master.mp4" - for ((i=0; i<${#A[*]}; i=i+1)); - do - # Check if the master file exists - if [ ! -f "${{ github.workspace }}/master_ui/${A[$i]}.png" ]; then - # This is a new file in PR UI that doesn't exist in master - DIFF="${DIFF}
" - DIFF="${DIFF}${A[$i]} : \$\${\\color{cyan}\\text{NEW}}\$\$" - DIFF="${DIFF}
" + diff_exit_code=0 + python3 ${{ github.workspace }}/openpilot/selfdrive/ui/tests/diff/diff.py \ + "${{ github.workspace }}/pr_ui/${video}_master.mp4" \ + "${{ github.workspace }}/pr_ui/${video}_proposed.mp4" \ + "${diff_name}.html" --basedir "$baseurl" --no-open || diff_exit_code=$? - DIFF="${DIFF}" - DIFF="${DIFF} " - DIFF="${DIFF}" + cp "${{ github.workspace }}/openpilot/selfdrive/ui/tests/diff/report/${diff_name}.html" "${{ github.workspace }}/pr_ui/" + cp "${{ github.workspace }}/openpilot/selfdrive/ui/tests/diff/report/${diff_name}.mp4" "${{ github.workspace }}/pr_ui/" - DIFF="${DIFF}
" - DIFF="${DIFF}
" - elif ! compare -fuzz 2% -highlight-color DeepSkyBlue1 -lowlight-color Black -compose Src ${{ github.workspace }}/master_ui/${A[$i]}.png ${{ github.workspace }}/pr_ui/${A[$i]}.png ${{ github.workspace }}/pr_ui/${A[$i]}_diff.png; then - convert ${{ github.workspace }}/pr_ui/${A[$i]}_diff.png -transparent black mask.png - composite mask.png ${{ github.workspace }}/master_ui/${A[$i]}.png composite_diff.png - convert -delay 100 ${{ github.workspace }}/master_ui/${A[$i]}.png composite_diff.png -loop 0 ${{ github.workspace }}/pr_ui/${A[$i]}_diff.gif - - mv ${{ github.workspace }}/master_ui/${A[$i]}.png ${{ github.workspace }}/pr_ui/${A[$i]}_master_ref.png - - DIFF="${DIFF}
" - DIFF="${DIFF}${A[$i]} : \$\${\\color{red}\\text{DIFFERENT}}\$\$" - DIFF="${DIFF}" - - DIFF="${DIFF}" - DIFF="${DIFF} " - DIFF="${DIFF} " - DIFF="${DIFF}" - - DIFF="${DIFF}" - DIFF="${DIFF} " - DIFF="${DIFF} " - DIFF="${DIFF}" - - DIFF="${DIFF}
master proposed
diff composite diff
" - DIFF="${DIFF}
" + REPORT_URL="https://sunnypilot.github.io/ci-artifacts/${diff_name}_pr_${{ github.event.number }}.html" + if [ $diff_exit_code -eq 0 ]; then + COMMENT+="**${name}**: Videos are identical! [View Diff Report]($REPORT_URL)"$'\n' else - rm -f ${{ github.workspace }}/pr_ui/${A[$i]}_diff.png - fi - - INDEX=$(($i % 2)) - if [[ $INDEX -eq 0 ]]; then - TABLE="${TABLE}" - fi - TABLE="${TABLE} " - if [[ $INDEX -eq 1 || $(($i + 1)) -eq ${#A[*]} ]]; then - TABLE="${TABLE}" + COMMENT+="**${name}**: ⚠️ Videos differ! [View Diff Report]($REPORT_URL)"$'\n' fi done - TABLE="${TABLE}" - - echo "DIFF=$DIFF$TABLE" >> "$GITHUB_OUTPUT" + { + echo "COMMENT<> "$GITHUB_OUTPUT" - name: Saving proposed ui if: github.event_name == 'pull_request_target' - working-directory: ${{ github.workspace }}/master_ui + working-directory: ${{ github.workspace }}/master_mici run: | git config user.name "GitHub Actions Bot" git config user.email "<>" @@ -159,17 +147,29 @@ jobs: git rm -rf * mv ${{ github.workspace }}/pr_ui/* . git add . - git commit -m "screenshots for PR #${{ github.event.number }}" + git commit -m "ui videos for PR #${{ github.event.number }}" git push origin ${{ env.BRANCH_NAME }} --force - - name: Comment Screenshots on PR + # Append diff reports to report files branch + git fetch origin ${{ env.REPORT_FILES_BRANCH_NAME }} + git checkout ${{ env.REPORT_FILES_BRANCH_NAME }} + for variant in $VARIANTS; do + IFS=':' read -r name _ _ <<< "$variant" + diff_name="${name}_diff" + cp "${{ github.workspace }}/openpilot/selfdrive/ui/tests/diff/report/${diff_name}.html" "${diff_name}_pr_${{ github.event.number }}.html" + git add "${diff_name}_pr_${{ github.event.number }}.html" + done + git commit -m "ui diff reports for PR #${{ github.event.number }}" || echo "No changes to commit" + git push origin ${{ env.REPORT_FILES_BRANCH_NAME }} + + - name: Comment on PR if: github.event_name == 'pull_request_target' - uses: thollander/actions-comment-pull-request@v2 + uses: thollander/actions-comment-pull-request@24bffb9b452ba05a4f3f77933840a6a841d1b32b with: message: | - + ## UI Preview - ${{ steps.find_diff.outputs.DIFF }} - comment_tag: run_id_screenshots - pr_number: ${{ github.event.number }} - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + ${{ steps.find_diff.outputs.COMMENT }} + comment-tag: run_id_ui_preview + pr-number: ${{ github.event.number }} + github-token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/wait-for-action/action.yaml b/.github/workflows/wait-for-action/action.yaml index 9cde4cf076..01bc614618 100644 --- a/.github/workflows/wait-for-action/action.yaml +++ b/.github/workflows/wait-for-action/action.yaml @@ -4,7 +4,7 @@ inputs: workflow: description: 'The workflow file name to monitor' required: true - default: 'selfdrive_tests.yaml' + default: 'tests.yaml' branch: description: 'The branch to monitor (defaults to current branch)' required: false diff --git a/.gitignore b/.gitignore index b556885632..a033f70507 100644 --- a/.gitignore +++ b/.gitignore @@ -10,15 +10,23 @@ venv/ .overlay_init .overlay_consistent .sconsign.dblite -model2.png a.out .hypothesis +.cache/ +bin/ -/docs_site/ +# created at launch for TICI PYTHONPATH (PC uses editable installs via pyproject.toml) +/msgq +/opendbc +/rednose +/teleoprtc +/tinygrad +*.mp4 *.dylib *.DSYM *.d +*.pem *.pyc *.pyo .*.swp @@ -35,76 +43,60 @@ a.out *.class *.pyxbldc *.vcd -*.qm +*.mo *_pyx.cpp +*.stats +*.pkl +*.pkl* config.json -clcache compile_commands.json compare_runtime*.html +openpilot/selfdrive/modeld/models/tg_input_devices.json -persist -selfdrive/pandad/pandad -cereal/services.h -cereal/gen -cereal/messaging/bridge -selfdrive/mapd/default_speeds_by_region.json -system/proclogd/proclogd -selfdrive/ui/translations/tmp -selfdrive/test/longitudinal_maneuvers/out -selfdrive/car/tests/cars_dump -system/camerad/camerad -system/camerad/test/ae_gray_test - -notebooks -hyperthneed -provisioning +# build artifacts +docs_site/ +openpilot/selfdrive/pandad/pandad +openpilot/cereal/services.h +openpilot/cereal/gen +openpilot/cereal/messaging/bridge +openpilot/selfdrive/ui/translations/tmp +openpilot/selfdrive/car/tests/cars_dump +openpilot/system/camerad/camerad +openpilot/system/camerad/test/ae_gray_test .coverage* coverage.xml htmlcov -pandaextra - -.mypy_cache/ -flycheck_* - -cppcheck_report.txt -comma*.sh - -selfdrive/modeld/thneed/compile -selfdrive/modeld/models/*.thneed -selfdrive/modeld/models/*.pkl -sunnypilot/modeld*/thneed/compile -sunnypilot/modeld*/models/*.thneed -sunnypilot/modeld*/models/*.pkl +# openpilot log files *.bz2 *.zst +*.rlog build/ !**/.gitkeep -poetry.toml -Pipfile ### VisualStudioCode ### +*.vsix +.history +.ionide .vscode/* +.history/ !.vscode/settings.json !.vscode/tasks.json !.vscode/launch.json !.vscode/extensions.json !.vscode/*.code-snippets -# Local History for Visual Studio Code -.history/ - -# Built Visual Studio Code Extensions -*.vsix - -### VisualStudioCode Patch ### -# Ignore all local history of files -.history -.ionide +# agents +.claude/ +.context/ +PLAN.md +TASK.md +CLAUDE.md +SKILL.md ### JetBrains ### !.idea/customTargets.xml diff --git a/.gitmodules b/.gitmodules index af2dea6495..a2d892d07f 100644 --- a/.gitmodules +++ b/.gitmodules @@ -15,7 +15,7 @@ url = https://github.com/commaai/teleoprtc [submodule "tinygrad"] path = tinygrad_repo - url = https://github.com/tinygrad/tinygrad.git + url = https://github.com/sunnypilot/tinygrad.git [submodule "sunnypilot/neural_network_data"] - path = sunnypilot/neural_network_data + path = openpilot/sunnypilot/neural_network_data url = https://github.com/sunnypilot/neural-network-data.git diff --git a/.idea/customTargets.xml b/.idea/customTargets.xml index 772000ec3a..c852a7a3b4 100644 --- a/.idea/customTargets.xml +++ b/.idea/customTargets.xml @@ -21,5 +21,12 @@ + + + + + + + \ No newline at end of file diff --git a/.idea/tools/External Tools.xml b/.idea/tools/External Tools.xml index fa2375e2ee..b5b27ed491 100644 --- a/.idea/tools/External Tools.xml +++ b/.idea/tools/External Tools.xml @@ -2,7 +2,7 @@ @@ -16,7 +16,14 @@ + + + + diff --git a/.python-version b/.python-version new file mode 100644 index 0000000000..28d9a01b1f --- /dev/null +++ b/.python-version @@ -0,0 +1 @@ +3.12.13 diff --git a/.run/Build Debug.run.xml b/.run/Build Debug.run.xml index beddbc15d5..a1b6ae24ea 100644 --- a/.run/Build Debug.run.xml +++ b/.run/Build Debug.run.xml @@ -1,5 +1,5 @@ - + diff --git a/.run/Build_BIG_UI.run.xml b/.run/Build_BIG_UI.run.xml new file mode 100644 index 0000000000..b58b1bf1b7 --- /dev/null +++ b/.run/Build_BIG_UI.run.xml @@ -0,0 +1,26 @@ + + + + + \ No newline at end of file diff --git a/.run/Build_SMALL_UI.run.xml b/.run/Build_SMALL_UI.run.xml new file mode 100644 index 0000000000..6c231c83f8 --- /dev/null +++ b/.run/Build_SMALL_UI.run.xml @@ -0,0 +1,23 @@ + + + + + \ No newline at end of file diff --git a/.run/Debug Route Controls.run.xml b/.run/Debug Route Controls.run.xml new file mode 100644 index 0000000000..a42e065eb7 --- /dev/null +++ b/.run/Debug Route Controls.run.xml @@ -0,0 +1,27 @@ + + + + + \ No newline at end of file diff --git a/.run/Replay for controls + ui.run.xml b/.run/Replay for controls + ui.run.xml new file mode 100644 index 0000000000..3adf7e3eee --- /dev/null +++ b/.run/Replay for controls + ui.run.xml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/.run/replay for controls.run.xml b/.run/replay for controls.run.xml new file mode 100644 index 0000000000..79a4365e2a --- /dev/null +++ b/.run/replay for controls.run.xml @@ -0,0 +1,7 @@ + + + + + + \ No newline at end of file diff --git a/.vscode/launch.json b/.vscode/launch.json index a6b341d9ea..5a052a112a 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -6,9 +6,9 @@ "type": "pickString", "description": "Select the process to debug", "options": [ - "selfdrive/controls/controlsd.py", - "system/timed/timed.py", - "tools/sim/run_bridge.py" + "openpilot/selfdrive/controls/controlsd.py", + "openpilot/system/timed/timed.py", + "openpilot/tools/sim/run_bridge.py" ] }, { @@ -16,13 +16,18 @@ "type": "pickString", "description": "Select the process to debug", "options": [ - "selfdrive/ui/ui" + "openpilot/selfdrive/ui/ui" ] }, { "id": "args", "description": "Arguments to pass to the process", "type": "promptString" + }, + { + "id": "replayArg", + "type": "promptString", + "description": "Enter route or segment to replay." } ], "configurations": [ @@ -40,7 +45,44 @@ "type": "cppdbg", "request": "launch", "program": "${workspaceFolder}/${input:cpp_process}", - "cwd": "${workspaceFolder}", + "cwd": "${workspaceFolder}" + }, + { + "name": "Attach LLDB to Replay drive", + "type": "lldb", + "request": "attach", + "pid": "${command:pickMyProcess}", + "sourceMap": { + ".": "${workspaceFolder}/opendbc/safety" + }, + "initCommands": [ + "script import time; time.sleep(3)" + ] + }, + { + "name": "Replay drive", + "type": "debugpy", + "request": "launch", + "program": "${workspaceFolder}/opendbc/safety/tests/safety_replay/replay_drive.py", + "args": [ + "${input:replayArg}" + ], + "console": "integratedTerminal", + "justMyCode": false, + "env": { + "PYTHONPATH": "${workspaceFolder}" + }, + "subProcess": true, + "stopOnEntry": false + } + ], + "compounds": [ + { + "name": "Replay drive + Safety LLDB", + "configurations": [ + "Replay drive", + "Attach LLDB to Replay drive" + ] } ] } \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json index f0731c362d..68f6b90371 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -17,11 +17,5 @@ "**/.git", "**/.venv", "**/__pycache__", - // exclude directories that should be using the symlinked version - "common/**", - "selfdrive/**", - "system/**", - "third_party/**", - "tools/**", ] } diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000000..aeb2a969c8 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,1320 @@ +sunnypilot Version 2026.002.000 (2026-06-28) +======================== +* What's Changed (sunnypilot/sunnypilot) + * ui: update gates for certain toggles by @sunnyhaibin in https://github.com/sunnypilot/sunnypilot/pull/1830 + * release: ignore upstream IsReleaseBranch by @sunnyhaibin in https://github.com/sunnypilot/sunnypilot/pull/1831 + * manager: disable DEVELOPMENT_ONLY reset by @sunnyhaibin in https://github.com/sunnypilot/sunnypilot/pull/1833 + * sunnylink: fix max time offroad values by @nayan8teen in https://github.com/sunnypilot/sunnypilot/pull/1835 + * ui: show default model name by @nayan8teen in https://github.com/sunnypilot/sunnypilot/pull/1837 + * sunnylink: add CarParams fallback for brand-specific capabilities by @sunnyhaibin in https://github.com/sunnypilot/sunnypilot/pull/1839 + * sunnylink SDUI: tweak DisableUpdate param for clarity by @sunnyhaibin in https://github.com/sunnypilot/sunnypilot/pull/1842 + * Revert "DM: Lancia Delta HF Integrale model" by @sunnyhaibin in https://github.com/sunnypilot/sunnypilot/pull/1849 + * modeld_v2: safe model validation by @Discountchubbs in https://github.com/sunnypilot/sunnypilot/pull/1855 + * Revert "deprecate `carState.brake`" for Honda Gas Interceptor by @mvl-boston in https://github.com/sunnypilot/sunnypilot/pull/1860 + * sunnylink: deprecate legacy params metadata by @sunnyhaibin in https://github.com/sunnypilot/sunnypilot/pull/1862 + * ui: reset Enforce Torque Control and NNLC if both are enabled by @sunnyhaibin in https://github.com/sunnypilot/sunnypilot/pull/1863 +* What's Changed (sunnypilot/opendbc) + * Rivian: suppress ACM hold-the-wheel warning during MADS-only lateral by @lukasloetkolben in https://github.com/sunnypilot/opendbc/pull/465 + * Sync: `commaai/opendbc:master` → `sunnypilot/opendbc:master` by @sunnyhaibin in https://github.com/sunnypilot/opendbc/pull/479 + * safety: add option to ignore frequency check for RX checks by @sunnyhaibin in https://github.com/sunnypilot/opendbc/pull/480 + * Revert "deprecate carState.brake" for Honda Gas Interceptor by @mvl-boston in https://github.com/sunnypilot/opendbc/pull/481 +* New Contributors (sunnypilot/sunnypilot) + * @mvl-boston made their first contribution in https://github.com/sunnypilot/sunnypilot/pull/1860 +* Full Changelog: https://github.com/sunnypilot/sunnypilot/compare/v2026.001.007...v2026.002.000 +************************ +* Synced with commaai's openpilot (v0.11.1) + * master commit 69e2c321e49760e52f7983eaa0a5f77cb95de637 (June 02, 2026) +* New driver monitoring model +* Improved image processing pipeline for driver camera +* Improved thermal policy for comma four +* Acura MDX 2022-24 support thanks to mvl-boston! +* Rivian R1S and R1T 2025 support thanks to lukasloetkolben! + +sunnypilot Version 2026.001.000 (2026-05-06) +======================== +* What's Changed (sunnypilot/sunnypilot) + * Complete rewrite of the user interface from Qt C++ to Raylib Python + * comma four support + * ui: sunnypilot toggle style by @nayan8teen + * ui: fix scroll panel mouse wheel behavior by @nayan8teen + * ui: sunnypilot panels by @nayan8teen + * sunnylink: centralize key pair handling in sunnylink registration by @devtekve + * ui: reimplement sunnypilot branding with Raylib by @sunnyhaibin + * ui: Platform Selector by @Discountchubbs + * ui: vehicle brand settings by @Discountchubbs + * ui: sunnylink client-side implementation by @nayan8teen + * ui: `NetworkUISP` by @Discountchubbs + * ui: add sunnypilot font by @nayan8teen + * ui: sunnypilot sponsor tier color mapping by @sunnyhaibin + * ui: sunnylink panel by @nayan8teen + * ui: Models panel by @Discountchubbs + * ui: software panel by @Discountchubbs + * modeld_v2: support planplus outputs by @Discountchubbs + * ui: OSM panel by @Discountchubbs + * ui: Developer panel extension by @Discountchubbs + * sunnylink: Vehicle Selector support by @sunnyhaibin + * [TIZI/TICI] ui: Developer Metrics by @rav4kumar + * [comma 4] ui: sunnylink panel by @nayan8teen + * ui: lateral-only and longitudinal-only UI statuses support by @royjr + * sunnylink: elliptic curve keys support and improve key path handling by @nayan8teen + * sunnylink: block remote modification of SSH key parameters by @zikeji + * [TIZI/TICI] ui: rainbow path by @rav4kumar + * [TIZI/TICI] ui: chevron metrics by @rav4kumar + * ui: include MADS enabled state to `engaged` check by @sunnyhaibin + * Toyota: Enforce Factory Longitudinal Control by @sunnyhaibin + * ui: fix malformed dongle ID display on the PC if dongleID is not set by @dzid26 + * SL: Re enable and validate ingestion of swaglogs by @devtekve + * modeld_v2: planplus model tuning by @Discountchubbs + * ui: fix Always Offroad button visibility by @nayan8teen + * Reimplement sunnypilot Terms of Service & sunnylink Consent Screens by @sunnyhaibin + * [TIZI/TICI] ui: update dmoji position and Developer UI adjustments by @rav4kumar + * modeld: configurable camera offset by @Discountchubbs + * [TIZI/TICI] ui: sunnylink status on sidebar by @Copilot + * ui: Global Brightness Override by @nayan8teen + * ui: Customizable Interactive Timeout by @sunnyhaibin + * sunnylink: add units to param metadata by @nayan8teen + * ui: Customizable Onroad Brightness by @sunnyhaibin + * [TIZI/TICI] ui: Steering panel by @nayan8teen + * [TIZI/TICI] ui: Rocket Fuel by @rav4kumar + * [TIZI/TICI] ui: MICI style turn signals by @rav4kumar + * [TIZI/TICI] ui: MICI style blindspot indicators by @sunnyhaibin + * [MICI] ui: display blindspot indicators when available by @rav4kumar + * [TIZI/TICI] ui: Road Name by @rav4kumar + * [TIZI/TICI] ui: Blue "Exit Always Offroad" button by @dzid26 + * [TIZI/TICI] ui: Speed Limit by @rav4kumar + * Reapply "latcontrol_torque: lower kp and lower friction threshold (commaai/openpilot#36619)" by @sunnyhaibin + * [TIZI/TICI] ui: steering arc by @royjr + * [TIZI/TICI] ui: Smart Cruise Control elements by @sunnyhaibin + * [TIZI/TICI] ui: Green Light and Lead Departure elements by @sunnyhaibin + * [TIZI/TICI] ui: standstill timer by @sunnyhaibin + * [MICI] ui: driving models selector by @Discountchubbs + * [TIZI/TICI] ui: Hide vEgo and True vEgo by @sunnyhaibin + * [TIZI/TICI] ui: Visuals panel by @nayan8teen + * Device: Retain QuickBoot state after op switch by @nayan8teen + * [TIZI/TICI] ui: Trips panel by @sunnyhaibin + * [TIZI/TICI] ui: dynamic ICBM status by @sunnyhaibin + * [TIZI/TICI] ui: Cruise panel by @sunnyhaibin + * ui: better wake mode support by @nayan8teen + * Pause Lateral Control with Blinker: Post-Blinker Delay by @CHaucke89 + * SCC-V: Use p97 for predicted lateral accel by @yasu-oh + * Controls: Support for Torque Lateral Control v0 Tune by @sunnyhaibin + * [TIZI/TICI] ui: ensure null checks for `CarParams` and `CarParamsSP` by @sunnyhaibin + * [TIZI/TICI] ui: use `vCruiseCluster` and `vEgoCluster` for SLA `preActive` by @sunnyhaibin + * Fix display of values when using use_float_scaling by @CHaucke89 + * models: fix default & index "0" by @nayan8teen + * [TIZI/TICI] visuals: Improved speed limit by @angaz + * ICBM: ensure button timers update on disable to clear stale presses by @jamesmikesell + * [TIZI/TICI] ui: simplify Smart Cruise Control text rendering by @sunnyhaibin + * controlsd: fix steer_limited_by_safety not updating under MADS by @zephleggett + * soundd: trigger timeout warning during MADS lateral-only by @zephleggett + * pandad: flasher for Rivian long upgrade module by @lukasloetkolben + * modeld_v2: tinygrad transformation warp by @Discountchubbs + * tools: block `manage_sunnylinkd` in sim startup script by @sunnyhaibin + * [MICI] ui: need superclass `_render` in `HudRendererSP` by @sunnyhaibin + * [TIZI/TICI] ui: Speed Limit Assist active status by @sunnyhaibin + * ui: reimplement "Screen Off" option to Onroad Brightness by @sunnyhaibin + * ui: don't hide steering wheel when blindspot disabled by @royjr + * ui: Speed Limit Assist `preActive` improvements by @sunnyhaibin + * ui: consolidate Speed Limit Assist `preActive` status rendering by @sunnyhaibin + * [MICI] ui: Speed Limit Assist `preActive` status by @sunnyhaibin + * sunnypilot modeld: remove thneed modeld by @Discountchubbs + * modeld_v2: decouple planplus scaling from accel by @Discountchubbs + * sunnylink: Handle exceptions in `getParamsAllKeysV1` to log crashes by @devtekve + * [TIZI/TICI] ui: Developer UI cleanup by @sunnyhaibin + * [TIZI/TICI] ui: dynamic alert size by @nayan8teen + * i18n(fr): Add French translations by @didlawowo + * Toyota: Stop and Go Hack (Alpha) by @sunnyhaibin + * ui: `AlertFadeAnimator` for longitudinal-related statuses by @sunnyhaibin + * pandad: gate unsupported pandas before flashing by @sunnyhaibin + * Rivian: Flash xnor's Longitudinal Upgrade Kit prior supported panda check by @lukasloetkolben + * [TIZI/TICI] ui: add back gate steering arc behind toggle by @sunnyhaibin + * ui: gate Onroad Brightness Delay on readiness by @sunnyhaibin + * ui: add new timer options for Onroad Brightness Delay by @sunnyhaibin + * [TIZI/TICI] ui: branch switcher is always available by @sunnyhaibin + * pandad: always prioritize internal panda by @sunnyhaibin + * sunnylinkd: fetch compressed params schema by @sunnyhaibin + * sunnypilot locationd: remove unused car_ekf filter by @sunnyhaibin + * modeld_v2: update deprecated temporalPose ref by @sunnyhaibin + * NNLC: restore pre-v1 PID gains in torque extension by @mmmorks + * MADS safety: enable heartbeat and lateral controls mismatch checks by @sunnyhaibin + * [MICI] ui: models panel enhancements by @nayan8teen + * [TIZI/TICI] ui: fix unintended selection while scrolling in TreeOptionDialog by @TheSecurityDev + * tools: script for video concatenation by @Discountchubbs + * tools: profile memory usage by @Discountchubbs + * [TIZI/TICI] ui: remove per-frame param sync by @sunnyhaibin + * [MICI] ui: always offroad by @nayan8teen + * controls: always default Torque Lateral Control to v0 Tune by @sunnyhaibin + * Revert "controls: always default Torque Lateral Control to v0 Tune" by @sunnyhaibin + * Reapply "controls: always default Torque Lateral Control to v0 Tune" (#1806) by @sunnyhaibin + * [MICI] ui: add sunnylink info & connectivity check by @nayan8teen + * sunnylink: Remove unused API endpoint by @devtekve + * DM: wheel touch enforcement in MADS by @sunnyhaibin + * torque: show static override values in Dev UI & gate `useParams` on custom torque tune by @sunnyhaibin + * MADS: suppress espActive event when long is not engaged by @sunnyhaibin + * sunnylink: SDUI by @sunnyhaibin + * [MICI] ui: align upstream changes with sunnypilot settings buttons by @nayan8teen + * ui: fix cellular toggles by @AmyJeanes + * sunnylink: switch athena domain by @devtekve + * Platform List: dynamically migrate CarPlatformBundle by @sunnyhaibin +* What's Changed (sunnypilot/opendbc) + * Honda: DBC for Accord 9th Generation by @mvl-boston + * FCA: update tire stiffness values for `RAM_HD` by @dparring + * Honda: Nidec hybrid baseline brake support by @mvl-boston + * Subaru Global Gen2: bump steering limits and update tuning by @sunnyhaibin + * Toyota: Enforce Stock Longitudinal Control by @rav4kumar + * Nissan: use MADS enabled status for LKAS HUD logic by @downquark7 + * Reapply "Lateral: lower friction threshold (#2915)" (#378) by @sunnyhaibin + * HKG: add KIA_FORTE_2019_NON_SCC fingerprint by @royjr + * Nissan: Parse cruise control buttons by @downquark7 + * Rivian: Add stalk down ACC behavior to match stock Rivian by @lukasloetkolben + * Tesla: remove `TESLA_MODEL_X` from `dashcamOnly` by @ssysm + * Hyundai Longitudinal: refactor tuning by @Discountchubbs + * Tesla: add fingerprint for Model 3 Performance HW4 by @sunnyhaibin + * Toyota: do not disable radar when smartDSU or CAN Filter detected by @sunnyhaibin + * Honda: add missing `GasInterceptor` messages to Taiwan Odyssey DBC by @mvl-boston + * GM: remove `CHEVROLET_EQUINOX_NON_ACC_3RD_GEN` from `dashcamOnly` by @sunnyhaibin + * GM: remove `CHEVROLET_BOLT_NON_ACC_2ND_GEN` from `dashcamOnly` by @sunnyhaibin + * Hyundai Longitudinal: deprecate ramp update for dynamic tune by @Discountchubbs + * Rivian: long upgrade messages on bus 1 by @lukasloetkolben + * Toyota: Stop and Go Hack (Alpha) by @sunnyhaibin + * Toyota: gate Smart DSU behind Alpha Longitudinal by @sunnyhaibin + * Toyota: Gas Interceptor always set `standstill_req` by @sunnyhaibin + * MADS safety: dedicated `controls_allowed_lateral` by @sunnyhaibin + * Platform List: include community supported platforms by @sunnyhaibin +* New Contributors (sunnypilot/sunnypilot) + * @TheSecurityDev made their first contribution in "ui: fix sidebar scroll in UI screenshots" + * @zikeji made their first contribution in "sunnylink: block remote modification of SSH key parameters" + * @Candy0707 made their first contribution in "[TIZI/TICI] ui: Fix misaligned turn signals and blindspot indicators with sidebar" + * @CHaucke89 made their first contribution in "Pause Lateral Control with Blinker: Post-Blinker Delay" + * @yasu-oh made their first contribution in "SCC-V: Use p97 for predicted lateral accel" + * @angaz made their first contribution in "[TIZI/TICI] visuals: Improved speed limit" + * @jamesmikesell made their first contribution in "ICBM: ensure button timers update on disable to clear stale presses" + * @zephleggett made their first contribution in "controlsd: fix steer_limited_by_safety not updating under MADS" + * @lukasloetkolben made their first contribution in "pandad: flasher for Rivian long upgrade module" + * @didlawowo made their first contribution in "i18n(fr): Add French translations" + * @mmmorks made their first contribution in "NNLC: restore pre-v1 PID gains in torque extension" +* New Contributors (sunnypilot/opendbc) + * @AmyJeanes made their first contribution in "Tesla: Fix stock LKAS being blocked when MADS is enabled" + * @mvl-boston made their first contribution in "Honda: Update Clarity brake to renamed DBC message name" + * @dzid26 made their first contribution in "Tesla: Parse speed limit from CAN" + * @firestar5683 made their first contribution in "GM: Non-ACC platforms with steering only support" + * @downquark7 made their first contribution in "Nissan: use MADS enabled status for LKAS HUD logic" + * @royjr made their first contribution in "HKG: add KIA_FORTE_2019_NON_SCC fingerprint" + * @ssysm made their first contribution in "Tesla: remove `TESLA_MODEL_X` from `dashcamOnly`" +* Full Changelog: https://github.com/sunnypilot/sunnypilot/compare/v2025.002.000...v2026.001.000 +************************ +* Synced with commaai's openpilot (v0.11.1) + * master commit c001f3c9b490a80e69539f0af6022f6e07ceb721 (April 16, 2026) +* New driver monitoring model +* Improved image processing pipeline for driver camera +* Rivian R1S and R1T 2025 support thanks to lukasloetkolben! +* New driving model #36798 + * Fully trained using a learned simulator + * Improved longitudinal performance in Experimental mode +* Reduce comma four standby power usage by 77% to 52 mW +* Kia K7 2017 support thanks to royjr! +* Lexus LS 2018 support thanks to Hacheoy! +* Improved inter-process communication memory efficiency +* comma four support + +sunnypilot Version 2025.002.000 (2025-11-06) +======================== +* What's Changed (sunnypilot/sunnypilot) + * models: bump model json to v8 by @Discountchubbs + * Bug: Model UI Crash Fix by @nayan8teen + * controlsd: add `CP_SP` to `get_pid_accel_limits` by @THERoenPR + * sunnylink: update uploader button logic to support novice tier and above by @devtekve + * Tesla: Coop Steering by @AmyJeanes + * ui: update discord references and add forum widget by @devtekve + * ui: Fix spacing in sunnylink panel by @devtekve + * docs: Update README installation branches and discord links by @mpurnell1 in + * stats: sunnylink integration by @devtekve + * bug: Fix initial registration for sunnylink by @devtekve +* What's Changed (sunnypilot/opendbc) + * Honda: add brake hold messages for Clarity by @mvl-boston + * interface: add `CP_SP` to `get_pid_accel_limits` method signature by @roenthomas + * Honda: use fixed accel min/max constants for Gas Interceptor by @roenthomas + * Tesla: Coop Steering by @AmyJeanes +* New Contributors (sunnypilot/sunnypilot) + * @THERoenPR made their first contribution in "controlsd: add `CP_SP` to `get_pid_accel_limits`" + * @AmyJeanes made their first contribution in "Tesla: Coop Steering" + * @mpurnell1 made their first contribution in "docs: Update README installation branches and discord links" +* Full Changelog: https://github.com/sunnypilot/sunnypilot/compare/v2025.001.000...v2025.002.000 + +sunnypilot Version 2025.001.000 (2025-10-25) +======================== +* 🛠️ Major rewrite + * Most features are intended to be identical to previous versions with slight improvements + * Fully adopts upstream commaai’s openpilot, opendbc (car interface and safety), and panda test suites to ensure consistent safety compliance and reliability across all systems + * Added regression testing to verify expected behavior and maintain stability across core modules + * Aligns with comma.ai’s safety policy: preserving driver monitoring, actuation checks, and safety test suite coverage + * Some features have not yet been reimplemented in this rewrite and are temporarily disabled in this release. They may return in future releases once fully ported and validated. See the end of the changelog to get a list of what's not going to be present. +* 🌟 Major Features & Systems + * Modular Assistive Driving System (MADS) + * Complete driving assistance framework + * Driving Model Manager + * Custom driving model selection with support for about 86 models (as of writing), from Night Strike (October 2023) up to The Cool People’s Models (October 2025) + * Neural Network Lateral Control (NNLC) (Formerly NNFF) + * Advanced torque-based lateral control + * Dynamic Experimental Control (DEC) + * Intelligent longitudinal control adaptation + * Speed Limit Assist (SLA) + * Comprehensive speed limit integration featuring @pfeiferj's `mapd` for offline map limits downloads, a Speed Limit Resolver for sourcing data (from car, map, combined, etc), on-screen UI for Speed Limit Information/Warning, and Speed Limit Assist (SLA) to adjust cruise speed automatically. + * Currently disabled for Tesla with sunnypilot Longitudinal Control in release and Rivian with sunnypilot Longitudinal Control in all branches + * May return in future releases + * Intelligent Cruise Button Management (ICBM) + * System designed to manage the vehicle’s speed by sending cruise control button commands to the car’s ECU. + * Smart Cruise Control Map & Vision (SCC-M / SCC-V) + * When using any form of long control (sunnypilot longitudinal control or ICBM) it will control the speed at which you enter and perform a turn by leveraging map data (SCC-M) and/or by leveraging what the model sees about the curve ahead (SCC-V) + * Vehicle Selector + * If your vehicle isn’t fingerprinted automatically, you can still use the vehicle selector to get it working + * sunnylink Integration + * Cloud connectivity and settings backup/restore + * PENDING: The infrastructure is ready for remote setting management, including remote driving model switching. An announcement will be made when this is ready to use in current and future releases. + * External Storage Support + * Expanded storage options + * mapd Integration (thanks to @pfeiferj) + * Allow downloading OpenStreetMap databases for your area, which could be useful for Speed Limit Assist (SLA) +* User Interface Enhancements + * Complete UI Redesign from Default openpilot Experience + * A total overhaul of the sunnypilot offroad user interface for a modern and intuitive experience. + * New Settings Panels + * Reorganized settings into dedicated panels: Steering, Longitudinal, Vehicle, Models, Visuals, Display, and Trips. + * Advanced Controls Toggle + * Out of the box experience has a slightly reduced set of settings for a lower barrier of entry, once you are ready, you can get a few extra settings by toggling on the Advanced Controls. + * Models Panel + * A dedicated panel for model management, featuring a download manager, model folders, a favorites system, fuzzy search, and a cache refresh button. + * Visuals & Display + * Extensive customization options including brightness controls, custom interactivity timeouts, green light indicator, lead vehicle indicator, on-screen turn signals, blind spot indicators, lead chevron info, standstill timer, road name display, and a Tesla-like 🌈 rainbow road path. + * Screen Off while driving + * Options to turn the screen off while driving and customize wake-up behavior for alerts. + * Branch & Platform Selectors + * Improved software management with a searchable branch selector and a platform selector that displays the current fingerprint. + * Developer UI + * An enhanced developer UI with better alert positioning and an integrated error log viewer. + * Convenience Features + * Added an “Exit Offroad” button, “Always Offroad” mode, Quiet Mode, and customizable max time offroad settings. + * OpenStreetMap Database Downloader + * The OpenStreetMap database downloader now includes a search feature for easily finding areas. +* Model and AI Improvements + * Modular Model Backend + * Major refactor of `modeld` to support modular runners (SNPE, thneed, tinygrad) and dynamic model inputs. + * Enhanced Model Outputs + * Models now provide additional outputs like “turn desires” for improved control. + * Live Parameter Adjustments + * Support for live delay adjustments and software delay controls directly from the UI. + * Model Management + * Added model caching, automatic refresh capabilities, and shape inference from inputs for better compatibility. +* Control Systems + * Pause Lateral on Blinker + * Option to temporarily pause lateral control when the turn signal is active. + * Custom ACC Setpoint Increments + * Configure custom increments for adjusting the ACC set speed for applicable vehicle platforms. + * Steering on Brake Press + * Customizable steering behavior when the brake pedal is pressed. + * Enforce Torque Lateral Control + * New customized settings for fine-tuning torque-based steering. + * Automatic Lane Change + * Support for automatic lane changes, including a mode to disable it. +* Technical Infrastructure + * Custom Cereal Implementation + * Migrated sunnypilot-specific events, car parameters, and car controls to a dedicated cereal for better compatibility and performance. + * Car Interface Abstractions + * Refactored car interfaces to support brand-specific settings and easier integration. + * Param Store Caching + * Implemented a cache for the parameter store to reduce startup times, with support for live parameter updates. + * Enhanced Error Handling + * Improved exception management and Sentry logging for better stability and debugging. + * Docker & CI/CD + * Full Docker image support, a dedicated GitHub runner service, and comprehensive improvements to the entire CI/CD pipeline for automated testing, building, and releasing. +* Bug Fixes and Stability + * Registration Requirement Removed + * No longer necessary to register the device to go onroad. + * Panda Firmware Checks + * Improved firmware checks to gracefully handle deprecated Panda devices. + * Numerous Fixes + * Addressed a wide range of bugs across the system for a more stable and reliable experience. +* Developer Experience + * CLion IDE integration and external tools + * Comprehensive testing and build automation + * Model building and publishing automation + * UI preview generation and testing + * Release drafting and version management + * Code quality and maintenance workflows +* Translations and Localization + * Korean translation updates + * Automated translation management system +* ❌ Removed + * Navigate on openpilot (NoO) + * Navigate on openpilot (NoO) has been removed as upstream is prioritizing improving the driving model’s capabilities and simplifying the training stack. + * The feature may return in a future upstream release by comma.ai once model improvements from upstream make it more reliable. + * Visuals: Rocket Fuel + * Visuals: Displaying Braking Status + * Vehicle: Toyota - Enforce Stock Longitudinal Control + * Subaru: Increase Steering Torque + * Longitudinal: Acceleration Personality + * UI: Display CPU Temperature on Sidebar + * Lateral: Block Lane Change with Road Edge Detection + * UI: Display DM Camera in Reverse Gear + * UI: Auto-hide Selected UI Elements + * Visuals: Display End-to-End Longitudinal Status + * Toyota: Stop and Go Hack (alpha) + * Visuals: Onroad Settings + * Honda: Serial Steering Support + * Volkswagen: Non-ACC Platforms Support + * Longitudinal: Dynamic Personality + * Honda Nidec: Allow Stock Longitudinal Control + * Lateral Planner: Dynamic Lane Profile + * Lateral Planner: Laneful Mode + * Lateral: Custom Camera and Path Offsets + * Toyota: Door Controls +* New Contributors (sunnypilot/sunnypilot) + * @royjr made their first contribution in "NNLC: bump max similarity for higher accuracy (#704)" + * @nayan8teen made their first contribution in "UI: Update AbstractControlSP_SELECTOR and OptionControlSP (#800)" + * @wtogami made their first contribution in "TOYOTA_RAV4_PRIME NNLC tuning gen 1 (#850)" + * @dparring made their first contribution in "FCA: Ram 1500 improvements (#797)" + * @Kirito3481 made their first contribution in "Update ko-kr translation (#1167)" + * @michael-was-taken made their first contribution in "Reorder README tables: show -new branches first (#1191)" + * @dzid26 made their first contribution in "params: Fix loading delay on startup (#1297)" + * @HazZelnutz made their first contribution in "Visuals: Turn signals on screen when blinker is used (#1291)" + * @sirmuskrat made their first contribution in "ui: openpilot Longitudinal Control → sunnypilot Longitudinal Control (#1422)" +* New Contributors (sunnypilot/opendbc) + * @chrispypatt made their first contribution in "Toyota: SecOC Longitudinal Control (sunnypilot/opendbc#93)" + * @Discountchubbs made their first contribution in "Hyundai: EPS FW For 2022 KIA_NIRO_EV SCC (sunnypilot/opendbc#118)" + * @lukasloetkolben made their first contribution in "Tesla: enableBsm is always true (sunnypilot/opendbc#163)" + * @roenthomas made their first contribution in "Honda: int flag for modified EPS configs (sunnypilot/opendbc#254)" + * @AmyJeanes made their first contribution in "Tesla: Fix stock LKAS being blocked when MADS is enabled (sunnypilot/opendbc#286)" + * @mvl-boston made their first contribution in "Honda: Update Clarity brake to renamed DBC message name (sunnypilot/opendbc#282)" + * @dzid26 made their first contribution in "Tesla: Parse speed limit from CAN (sunnypilot/opendbc#308)" + * @firestar5683 made their first contribution in "GM: Non-ACC platforms with steering only support (sunnypilot/opendbc#229)" +************************ +* Synced with commaai's openpilot (v0.10.1) + * master commit c9dbf97649a27117be6d5955a49e2d4253337288 (September 12, 2025) +* New driving model + * World Model: removed global localization inputs + * World Model: 2x the number of parameters + * World Model: trained on 4x the number of segments + * Driving Vision Model: trained on 4x the number of segments +* Honda City 2023 support thanks to vanillagorillaa and drFritz! +* Honda N-Box 2018 support thanks to miettal! +* Honda Odyssey 2021-25 support thanks to csouers and MVL! + +sunnypilot - 0.9.7.1 (2024-06-13) +======================== +* New driving model + * Inputs the past curvature for smoother and more accurate lateral control + * Simplified neural network architecture in the model's last layers + * Minor fixes to desire augmentation and weight decay +* New driver monitoring model + * Improved end-to-end bit for phone detection +* Adjust driving personality with the follow distance button +* Support for hybrid variants of supported Ford models +* Fingerprinting without the OBD-II port on all cars +* Improved fuzzy fingerprinting for Ford and Volkswagen +************************ +* UPDATED: Synced with commaai's openpilot + * master commit f8cb04e (June 10, 2024) +* NEW❗: sunnylink (Alpha early access) + * NEW❗: Config/Settings Backup + * Remotely back up and restore sunnypilot settings easily + * Device registration with sunnylink ensures a secure, integrated experience across services + * AES encryption derived from the device's RSA private key is used for utmost security + * Settings are encrypted on-device, transmitted securely via HTTPS, and stored encrypted on sunnylink + * Prevents loss of settings after device resets, offering peace of mind through end-to-end encryption + * Early alpha access to all current and previous GitHub Sponsors and Patreon supporters + * GitHub account pairing from device settings scanning QR code + * Pairing your account will allow you to access features via our API (still WIP but accessible if you dig a little on our code 😉) + * Allow inheritance of your sponsorship status, allowing you to get extra features and early access whenever applicable +* NEW❗: iOS Siri Shortcuts Navigation support thanks to twilsonco and mike86437! + * iOS and macOS Shortcuts to quickly set navigation destinations from your iOS device + * comma Prime support + * Personal Mapbox/Amap/Google Maps token support + * Instructions on how to set up your iOS Siri Shortcuts: https://routinehub.co/shortcut/17677/ +* NEW❗: Forced Offroad mode + * Force sunnypilot in the offroad state even when the car is on + * When Forced Offroad mode is on, allows changing offroad-only settings even when the car is turned on + * To engage/disengage Force Offroad, go to Settings -> Device panel +* UPDATED: Auto Lane Change Timer -> Auto Lane Change by Blinker + * NEW❗: New "Off" option to disable lane change by blinker +* UPDATED: Pause Lateral Below Speed with Blinker + * NEW❗: Customizable Pause Lateral Speed + * Pause lateral actuation with blinker when traveling below the desired speed selected. Default is 20 MPH or 32 km/h. +* UPDATED: Hyundai CAN Longitudinal + * Auto-enable radar tracks on platforms with applicable Mando radar +* UPDATED: Hyundai CAN-FD Camera-based SCC + * NEW❗: Parse lead info for camera-based SCC platforms with longitudinal support + * Improve lead tracking when using openpilot longitudinal +* RE-ENABLED: Map-based Turn Speed Control (M-TSC) for supported platforms + * openpilot Longitudinal Control available cars + * Custom Stock Longitudinal Control available cars +* UPDATED: Continued support for comma Pedal + * In response to the official deprecation of support for comma Pedal in the upstream, sunnypilot will continue maintaining software support for comma Pedal +* UPDATED: Driving Model Selector v4 + * NEW❗: Driving Model additions + * North Dakota (April 29, 2024) - NDv2 + * WD40 (April 09, 2024) - WD40 + * Duck Amigo (March 18, 2024) - DA + * Recertified Herbalist (March 01, 2024) - CHLR + * Legacy Driving Models with Navigate on openpilot (NoO) support + * Includes Duck Amigo and all preceding models +* UPDATED: Bumping mapd by [@pfeiferj](https://github.com/pfeiferj) to version [v1.9.0](https://github.com/pfeiferj/mapd/releases/tag/v1.9.0) thanks to pfeiferj! +* UPDATED: Reset Mapbox Access Token -> Reset Access Tokens for Map Services + * Reset self-service access tokens for Mapbox, Amap, and Google Maps +* UPDATED: Upstream native support for Gap Adjust Cruise +* UPDATED: Neural Network Lateral Control (NNLC) + * Due to upstream changes with platform simplifications, most platforms will match and fallback to combined platform model + * This will be updated when the new mapping of platforms are restructured (thanks @twilsonco 😉) +* UI Updates + * Display Metrics Below Chevron + * NEW❗: Metrics is now being displayed below the chevron instead of above + * NEW❗: Display both Distance and Speed simultaneously + * NEW❗: View sunnylink connectivity status on the left sidebar! + +sunnypilot - 0.9.6.2 (2024-05-29) +======================== +* REMOVED: Screen Recorder + * Screen Recorder is removed due to unnecessary resource usage + * An improved version will be available in the near future. Stay tuned! + +sunnypilot - 0.9.6.1 (2024-02-27) +======================== +* New driving model + * Vision model trained on more data + * Improved driving performance + * Directly outputs curvature for lateral control +* New driver monitoring model + * Trained on larger dataset +* AGNOS 9 +* comma body streaming and controls over WebRTC +* Improved fuzzy fingerprinting for many makes and models +* Alpha longitudinal support for new Toyota models +* Chevrolet Equinox 2019-22 support thanks to JasonJShuler and nworb-cire! +* Dodge Durango 2020-21 support +* Hyundai Staria 2023 support thanks to sunnyhaibin! +* Kia Niro Plug-in Hybrid 2022 support thanks to sunnyhaibin! +* Lexus LC 2024 support thanks to nelsonjchen! +* Toyota RAV4 2023-24 support +* Toyota RAV4 Hybrid 2023-24 support +************************ +* UPDATED: Synced with commaai's openpilot + * master commit db57a21 (February 22, 2024) + * v0.9.6 release (February 27, 2024) +* UPDATED: Dynamic Experimental Control (DEC) + * Synced with dragonpilot-community/dragonpilot:beta3 commit f4ee52f +* NEW❗: Default Driving Model: Certified Herbalist v2 (February 13, 2024) +* UPDATED: Driving Model Selector v3 + * NEW❗: Driving Model additions + * Certified Herbalist v2 (February 13, 2024) - CHv2 + * Certified Herbalist (February 5, 2024) - CH + * Los Angeles v2 (January 24, 2024) - LAv2 + * Los Angeles (January 22, 2024) - LAv1 + * NEW❗: Model Caching thanks to DevTekVE! + * Model caching allows the selection of previously downloaded Driving Model + * Users can now access cached versions of selected models, eliminating redundant downloads for previously fetched models + * Legacy Driving Models support + * New Delhi (December 21, 2023) - ND + * Blue Diamond v2 (December 11, 2023) - BDv2 + * Blue Diamond (November 18, 2023) - BDv1 + * Farmville (November 7, 2023) - FV + * Night Strike (October 3, 2023) - NS + * Certain features are deprecated with newer Driving Models + * Dynamic Lane Profile (DLP) + * Custom Offsets +* UPDATED: Dynamic Lane Profile (DLP) + * Continued support for Legacy Driving Models (e.g., ND, BDv2, BDv1, FV, NS) + * Deprecated support for newer Driving Models (e.g., CHv2, CH, LAv2, LAv1) +* UPDATED: Custom Offsets + * Continued support for Legacy Driving Models (e.g., ND, BDv2, BDv1, FV, NS) + * Deprecated support for newer Driving Models (e.g., CHv2, CH, LAv2, LAv1) +* UPDATED: Hyundai/Kia/Genesis - ESCC Radar Interceptor + * Message parsing improvements with the latest firmware update: https://github.com/sunnypilot/panda/tree/test-escc-smdps +* UI Updates + * NEW❗: Visuals: Display Feature Status toggle + * Display the statuses of certain features on the driving screen + * NEW❗: Visuals: Enable Onroad Settings toggle + * Display the Onroad Settings button on the driving screen to adjust feature options on the driving screen, without navigating into the settings menu + * REMOVED: "Device ambient" temperature option on the sidebar +* FIXED: New comma 3X support +* FIXED: New comma eSIM support +* Bug fixes and performance improvements + +sunnypilot - 0.9.5.3 (2023-12-24) +======================== +* UPDATED: Dynamic Experimental Control (DEC) + * Synced with dragonpilot-community/dragonpilot:lp-dp-beta2 commit 578d38b +* UPDATED: Driving Model Selector v2 + * Driving models sort in descending order based on availability date + * Experimental/unmerged driving models are only available in "dev-c3" branch + * To select and use experimental driving models, navigate to "Software" panel, select the "dev-c3" branch, and check for update +* UPDATED: Vision-based Turn Speed Control (V-TSC) implementation + * Refactored implementation thanks to pfeiferj! + * More accurate and consistent velocity calculation to achieve smoother longitudinal control in curves +* NEW❗: Speed Limit Warning + * Display alert and/or chime to warn the driver when the cruising speed is faster than the speed limit plus the Warning Offset + * Customizable Warning Offset, independent of Speed Limit Control (SLC)'s Limit Offset +* UPDATED: Speed Limit Source Policy + * Selectable speed limit source for Speed Limit Control and Speed Limit Warning + * Applicable to: Speed Limit Control, Speed Limit Warning +* UPDATED: Speed Limit Control (SLC) + * Engage Mode: Removed "Warning Only" mode - this has been replaced by the new Speed Limit Warning sub-menu +* UPDATED: OpenStreetMap (OSM) implementation + * Refactored implementation thanks to pfeiferj! + * Less resource impact + * Significantly smaller sizes with databases + * All regions are available to download + * Weekly map updates thanks to pfeiferj! + * Increased the font size of the road name + * C3X-specific changes + * Altitude (ALT.) display on Developer UI + * Current street name on top of driving screen when "OSM Debug UI" is enabled +* UPDATED: Map-based Turn Speed Control (M-TSC) implementation + * Only available in "staging-c3" and "dev-c3" branches. If you are using "release-c3" branch, navigate to "Software" panel, select the desired target branch, and check for update + * Refactored implementation thanks to pfeiferj! + * Based on the new OpenStreetMap implementation + * Improved predicted curvature calculations from OpenStreetMap data +* UI updates + * RE-ENABLED: Navigation: Full screen support + * Display the map view in full screen + * To switch back to driving view, tap on the border edge +* Hyundai Bayon Non-SCC 2019 support thanks to polein78! + +sunnypilot - 0.9.5.2 (2023-12-07) +======================== +* NEW❗: MADS: Allow Navigate on openpilot in Chill Mode + * Allow navigation to feed map view into the driving model while using Chill Mode + * Support all platforms, including platforms that do not support openpilot longitudinal control & Experimental Mode +* NEW❗: Neural Network Lateral Controller + * Formerly known as "NNFF", this replaces the lateral "torque" controller with one using a neural network trained on each car's (actually, each separate EPS firmware) driving data for increased controls accuracy + * Contact @twilsonco in the sunnypilot Discord server with feedback, or to provide log data for your car if your car is currently unsupported +* NEW❗: Driving Model Selector + * Easily switch between driving models without reinstalling branches. Offering immediate access to the latest models upon release + * An internet connection is required for downloading models. Each model switch currently involves downloading the model again. Future updates may allow for offline switching + * Warning is displayed for metered connections to avoid unexpected data usage if on cellular data + * Change driving models via **Settings -> Software -> Current Driving Model**. +* NEW❗: Hyundai CAN longitudinal: + * NEW❗: Enable radar tracks for certain Santa Fe platforms + * Internal Combustion Engine (ICE) 2021-23 + * Hybrid 2022-23 + * Plug-in Hybrid 2022-23 +* NEW❗: Lane Change: When manually braking with steering engaged, turning on the turn signal will default to Nudge mode +* Volkswagen MQB CC only platforms (radar or no radar) support thanks to jyoung8607! + +sunnypilot - 0.9.5.1 (2023-11-17) +======================== +* UPDATED: Synced with commaai's master commit e94c3c5 +* NEW❗: Farmville driving model +* NEW❗: Onroad Settings Panel + * Onroad buttons (i.e., DLP, GAC) moved to its dedicated panel + * Driving Personality + * Dynamic Lane Profile (DLP) + * Dynamic Experimental Control (DEC) + * Speed Limit Control (SLC) +* NEW❗: Display main feature status on onroad view in real-time + * GAP - Driving Personality + * DLP - Dynamic Lane Profile + * DEC - Dynamic Experimental Control + * SLC - Speed Limit Control +* NEW❗: Dynamic Experimental Control (DEC) thanks to dragonpilot-community! + * Automatically determines and selects between openpilot ACC and openpilot End to End longitudinal based on conditions for a more natural drive + * Dynamic Experimental Control is only active while in Experimental Mode + * When Dynamic Experimental Control is ON, initially setting cruise speed will set to the vehicle's current speed +* NEW❗: Hyundai CAN longitudinal: + * NEW❗: Parse lead info for camera-based SCC platforms + * Improve lead tracking when using openpilot longitudinal + * NEW❗: Parse lead distance to display on car cluster + * Introduced better lead distance calculation to display on the car's cluster, replacing the binary "lead visible" indication on the SCC cluster + * Lead distance is now categorized into different ranges for more detailed and comprehensive information to the driver similar to how stock ACC does it + * NEW❗: Parse speed limit sign recognition from camera for certain supported platforms +* NEW❗: Subaru - Stop and Go auto-resume support thanks to martinl! + * Global (excluding Gen 2 and Hybrid) and Pre-Global support +* NEW❗: Toyota - Stop and Go hack + * Allow some Toyota/Lexus cars to auto resume during stop and go traffic + * Only applicable to certain models and model years +* NEW❗: Toyota: ZSS support thanks to dragonpilot-community and ErichMoraga! +* NEW❗: MSPA (Cereal structs refactor) + * Make sunnypilot Parsable Again - @sshane + * sunnypilot is now parsable with stock openpilot tools +* NEW❗: Display 3D buildings on map thanks to jakethesnake420! +* openpilot Longitudianl Control capable cars only + * UPDATED: Gap Adjust Cruise is now a part of Driving Personality + * [DISTANCE/FOLLOW DISTANCE/GAP DISTANCE] physical button on the steering wheel to select Driving Personality on by default + * Status now viewable in onroad view or Onroad Settings Panel + * REMOVED: Gap Adjust Cruise toggle +* UPDATED: Speed Limit Control (SLC) + * NEW❗: Speed Limit Engage Mode + * Select the desired mode to set the cruising speed to the speed limit + * Warning Only: Warn the driver when the vehicle is driven faster than the speed limit + * Auto: Automatic speed adjustment on motorways based on speed limit data + * User Confirm: Inform the driver to change set speed of Adaptive Cruise Control to help the driver stay within the speed limit + * Supported platforms + * openpilot Longitudinal Control available cars (Excluding certain Toyota/Lexus, Ford, explained below) + * Custom Stock Longitudinal Control available cars + * Unsupported platforms + * Toyota/Lexus and Ford - most platforms do not allow us to control the PCM's set speed, requires testers to verify + * NEW❗: Speed limit source selector + * Select the desired precedence order of sources used to adapt cruise speed to road limits +* UPDATED: Custom Stock Longitudinal Control + * RE-ENABLED: Hyundai/Kia/Genesis CAN-FD platforms +* UPDATED: Custom Offsets reimplementation + * Camera Offset only works in Laneful (Laneful Only or Laneful in Auto mode when using Dynamic Lane Profile) + * Path Offset can be applied to both Laneless and Laneful +* UPDATED: Refactored Torque Lateral Control custom tuning menu + * NEW❗: Less Restrict Settings for Self-Tune (Beta) + * NEW❗: Custom Tuning for setting offline and live values in real-time +* UPDATED: Auto-detect custom Mapbox token if a personal Mapbox token is provided + * REMOVED: "Enable Mapbox Navigation" toggle +* UI updates + * New Settings menu redesign and improved interactions +* FIXED: Retain hotspot/tethering state was not consistently saved +* FIXED: Map stuck in "Map Loading" if comma Prime is active +* FIXED: OpenStreetMap implementation on C3X devices + * M-TSC + * Altitude (ALT.) display on Developer UI + * Current street name on top of driving screen when "OSM Debug UI" is enabled +* Hyundai Kona Non-SCC 2019 support thanks to Quex! +* Kia Seltos Non-SCC 2023-24 support thanks to Moodkiller and jeroid_! + +sunnypilot - 0.9.4.1 (2023-08-11) +======================== +* UPDATED: Synced with commaai's 0.9.4 release +* NEW❗: Moonrise driving model +* NEW❗: Ford upstream models support +* UPDATED: Dynamic Lane Profile selector in the "SP - Controls" menu +* REMOVED: Dynamic Lane Profile driving screen UI button +* FIXED: Disallow torque lateral control for angle control platforms (e.g. Ford, Nissan, Tesla) + * Torque lateral control cannot be used by angle control platforms, and would cause a "Controls Unresponsive" error if Torque lateral control is enforced in settings +* REMOVED: Speed Limit Style override +* Honda Accord 2016-17 support thanks to mlocoteta! + * Serial Steering hardware required. For more information, see https://github.com/mlocoteta/serialSteeringHardware +* mapd: utilize advisory speed limit in curves (#142) thanks to pfeiferj! + +sunnypilot - 0.9.3.1 (2023-07-09) +======================== +* UPDATED: Synced with commaai's 0.9.3 release +* NEW❗: Display Temperature on Sidebar toggle + * Display Ambient temperature, memory temperature, CPU core with the highest temperature, GPU temperature, or max of Memory/CPU/GPU on the sidebar + * Replace "Display CPU Temperature on Sidebar" toggle +* NEW❗: Hot Coffee driving model +* NEW❗: HKG CAN: Smoother Stopping Performance (Beta) toggle + * Smoother stopping behind a stopped car or desired stopping event. + * This is only applicable to HKG CAN platforms using openpilot longitudinal control +* NEW❗: Toyota: TSS2 longitudinal: Custom Tuning + * Smoother longitudinal performance for Toyota/Lexus TSS2/LSS2 cars thanks to dragonpilot-community! +* NEW❗: Enable Screen Recorder toggle + * Enable this will display a button on the onroad screen to toggle on or off real-time screen recording with UI elements. +* IMPROVED: Dynamic Lane Profile: when using Laneline planner via Laneline Mode or Auto Mode, enforce Laneless planner while traveling below 10 MPH or 16 km/h +* REMOVED: Display CPU Temperature on Sidebar + +sunnypilot - 0.9.2.3 (2023-06-18) +======================== +* NEW❗: Auto Lane Change: Delay with Blind Spot + * Toggle to enable a delay timer for seamless lane changes when blind spot monitoring (BSM) detects an obstructing vehicle, ensuring safe maneuvering +* NEW❗: Driving Screen Off: Wake with Non-Critical Events + * When Driving Screen Off Timer is not set to "Always On": + * Enabled: Wake the brightness of the screen to display all events + * Disabled: Wake the brightness of the screen to display critical events + * Currently, all non-nudge modes are default to continue lane change after 1 seconds of blind spot detection +* NEW❗: Fleet Manager PIN Requirement toggle + * User can now enable or disable PIN requirement on the comma device before accessing Fleet Manager +* NEW❗: Reset all sunnypilot settings toggle +* NEW❗: Turn signals display on screen when blinker is used + * Green: Blinker is on + * Red: Blinker is on, car detected in the adjacent blind spot or road edge detected +* IMPROVED: mapd: better exceptions handling when loading dependencies +* UPDATED: Green Traffic Light Chime no longer displays an orange border when executed +* FIXED: mapd: Road name flashing caused by desync with last GPS timestamp +* FIXED: Ram HD (2500/3500): Ignore paramsd sanity check + * Live parameters have trouble with self-tuning on this platform with upstream openpilot 0.9.2 +* Hyundai: Longitudinal support for CAN-based Camera SCC cars thanks to Zack1010OP's Patreon sponsor! + +sunnypilot - 0.9.2.2 (2023-06-13) +======================== +* NEW❗: Toyota: Allow M.A.D.S. toggling with LKAS Button (Beta) +* IMPROVED: Ram: cruise button handling + +sunnypilot - 0.9.2.1 (2023-06-10) +======================== +* UPDATED: Synced with commaai's 0.9.2 release +* UPDATED: feature revamp with better stability +* UPDATED: + * M.A.D.S. + * Path color becomes LIGHT ORANGE during Driver Steering Override + * Gap Adjust Cruise (now known as Driving Personality in upstream openpilot 0.9.3): + * Updated profiles and jerk changes + * Experimental Mode support + * Three settings: Stock, Aggressive, and Maniac + * Stock is recommended and the default + * In Aggressive/Maniac mode, lead follow distance is shorter and quicker gas/brake response + * Dynamic Lane Profile + * Display blue borders on both sides of the driving path when Laneline mode is being used in the planner + * Auto Mode optimization + * Permanent: Laneless during Auto Lane Change execution + * Mapd + * OpenStreetMap Database: new regions added + * Developer UI (Dev UI) + * REMOVED: 2-column design + * NEW❗: 1-column + 1-row design + * Custom Stock Longitudinal Control + * NEW❗: Chrysler/Jeep/Ram support + * NEW❗: Mazda support + * NEW❗: Volkswagen PQ support + * DISABLED: Hyundai/Kia/Genesis CAN-FD platforms +* NEW❗: Switch between Chill (openpilot ACC) and Experimental (E2E longitudinal) with DISTANCE button on the steering wheel + * To switch between Chill and Experimental Mode: press and hold the DISTANCE button on the steering wheel for over 0.5 second + * All openpilot longitudinal capable cars support +* NEW❗: Nicki Minaj driving model +* NEW❗: Nissan and Mazda upstream models support +* NEW❗: Pre-Global Subaru upstream models support +* NEW❗: Display End-to-end Longitudinal Status (Beta) + * Display an icon that appears when the End-to-end model decides to start or stop +* NEW❗: Green Traffic Light Chime (Beta) + * A chime will play when the traffic light you are waiting for turns green, and you have no vehicle in front of you. +* NEW❗: Lead Vehicle Departure Alert + * Notify when the leading vehicle drives away +* NEW❗: Speedometer: Display True Speed + * Display the true vehicle current speed from wheel speed sensors. +* NEW❗: Speedometer: Hide from Onroad Screen +* NEW❗: Auto-Hide UI Buttons + * Hide UI buttons on driving screen after a 30-second timeout. Tap on the screen at anytime to reveal the UI buttons + * Applicable to Dynamic Lane Profile (DLP) and Gap Adjust Cruise (GAC) +* NEW❗: Display DM Camera in Reverse Gear + * Show Driver Monitoring camera while the car is in reverse gear +* NEW❗: Block Lane Change: Road Edge Detection (Beta) + * Block lane change when road edge is detected on the stalk actuated side +* NEW❗: Display CPU Temperature on Sidebar + * Display the CPU core with the highest temperature on the sidebar +* NEW❗: Display current driving model in Software settings +* NEW❗: HKG: smartMDPS automatic detection (installed with applicable firmware) +* FIXED: Unintended siren/alarm from the comma device if the vehicle is turned off too quickly in PARK gear +* FIXED: mapd: Exception handling for loading dependencies +* Fleet Manager via Browser support thanks to actuallylemoncurd, AlexandreSato, ntegan1, and royjr! + * Access your dashcam footage, screen recordings, and error logs when the car is turned off + * Connect to the device via Wi-Fi, mobile hotspot, or tethering on the comma device, then navigate to http://ipAddress:5050 to access. +* Honda Clarity 2018-22 support thanks to mcallbosco, vanillagorillaa and wirelessnet2! +* Ram: Steer to 0/7 MPH support thanks to vincentw56! +* Retain hotspot/tethering state across reboots thanks to rogerioaguas! + +sunnypilot - Version Latest (2023-02-22) +======================== +* UPDATED: Synced with commaai's master branch - 2023.02.19-04:52:00:GMT - 0.9.2 +* Refactor sunnypilot features to be more stable + +sunnypilot - Version Latest (2022-12-16) +======================== +* UPDATED: Synced with commaai's master branch - 2022.12.16-06:31:00:GMT - 0.9.1 +* NEW❗: GM: + * NEW❗: Gap Adjust Cruise support - Chill, Normal, Aggressive + * NEW❗: Experimental Mode: Hold DISTANCE button on the steering wheel for 0.5 second to switch between Experimental Mode and Chill Mode +* REMOVED❌: Toytoa: SnG Hack + * This method is not recommended and may cause some cars to not behave as expected + * SDSU is strongly recommended to enable SnG for Toyota vehicles without SnG from factory +* commaai: radard: add missing accel data for vision-only leads (commaai/openpilot#26619) - pending PR + * VOACC performance is drastically improved when using Chill Mode +* IMPROVED: M.A.D.S. events handling +* IMPROVED: UI: screen recorder button change +* IMPROVED: OpenStreetMap Offline Database optimization +* FIXED: Toyota: vehicles' LKAS button no longer has a delay with toggling M.A.D.S. +* FIXED: Toyota: brake pedal press at standstill causing Cruise Fault +* FIXED: Volkswagen MQB: reduce Camera Malfunction occurrences (requires testing) +* Bug fixes and performance improvements + +sunnypilot - Version Latest (2022-12-10) +======================== +* IMPROVED: NEW❗ Developer UI design + * Second column metrics is now moved to the bottom of the screen + * ACC. = Acceleration + * L.S. = Lead Speed + * E.T. = EPS Torque + * B.D. = Bearing Degree + * FRI. = Friction + * L.A. = Lateral Acceleration + * ALT. = Altitude +* Bug fixes and performance improvements + +sunnypilot - Version Latest (2022-12-07) +======================== +* NEW❗: Screen Recorder support thanks to neokii and Kumar! +* NEW❗: End-to-end longitudinal start/stop status icon + * Only appears when Experimental Mode is enabled +* NEW❗: End-to-end longitudinal car chime when starting + * Hyundai/Kia/Genesis CAN platform, Honda/Acura Bosch/Nidec, Toyota/Lexus + * i.e. Traffic light turns green, stop sign ready to go, etc. + * Only appears when Experimental Mode is enabled AND longitudinal control is disengaged +* Bug fixes and performance improvements + +sunnypilot - Version Latest (2022-12-05) +======================== +* UPDATED: Synced with commaai's master branch - 2022.12.04-22:46:00:GMT - 0.9.1 +* Bug fixes and performance improvements + +sunnypilot - Version Latest (2022-11-12) +======================== +* UPDATED: Synced with commaai's master branch - 2022.11.12-10:02:00:GMT - 0.8.17 +* FIXED: CAN Error for CAN HKG cars that do not have navigation from the factory +* Bug fixes and performance improvements + +sunnypilot - Version Latest (2022-11-11) +======================== +* UPDATED: Synced with commaai's master branch - 2022.11.11-21:22:00:GMT - 0.8.17 +* commaai: AGNOS 6.2 (commaai/openpilot#26441) +* NEW❗: Speed Limit Control - HKG - add speed limit from car's navigation head unit + * Compatible with certain models, trims, and model years +* DISABLED: FCA: RAM HD - steer down to 0 +* FIXED: UI: End-to-end longitudinal button on driving screen synchronization +* FIXED: Honda: Longitudinal status with set cruise speed now displays properly in the car's dashboard +* Bug fixes and performance improvements + +sunnypilot - Version Latest (2022-11-08) +======================== +* ADDED: New Zealand offline OpenStreetMap database + +sunnypilot - Version Latest (2022-11-04) +======================== +* UPDATED: Synced with commaai's master branch - 2022.11.05-01:44:00:GMT - 0.8.17 +* RE-ENABLED: Dynamic Lane Profile - preserves lanelines + * Can be found in "SP - Controls" menu +* NEW❗: DLP: switch to laneless for current/future curves thanks to @twilsonco! + * Can be found in "SP - Controls" menu +* NEW❗: UI: Road Camera Selector + * Enable this will display a button on the driving screen to select the driving camera + * Can be found in "SP - Visuals" menu +* NEW❗: Controls: Camera & Path Custom Offsets + * Only applicable to laneline mode when using Dynamic Lane Profile +* NEW❗: Buttons on driving screen are now sorted based on priority and availability +* Bug fixes and performance improvements + +sunnypilot - Version Latest (2022-10-28) +======================== +* UPDATED: Synced with commaai's master branch - 2022.10.28-03:53:00:GMT - 0.8.17 +* Bug fixes and performance improvements + +sunnypilot - Version Latest (2022-10-26) +======================== +* UPDATED: Synced with commaai's master branch - 2022.10.26-06:20:00:GMT - 0.8.17 +* Bug fixes and performance improvements + +sunnypilot - Version Latest (2022-10-25) +======================== +* UPDATED: Synced with commaai's master branch - 2022.10.25-23:53:00:GMT - 0.8.17 +* Pre-Global Subaru support thanks to @martinl! +* NEW❗: Speed Limit values turn red when current speed is higher than posted speed limit +* Bug fixes and performance improvements + +sunnypilot - Version Latest (2022-10-23) +======================== +* UPDATED: Synced with commaai's master branch - 2022.10.22-23:15:00:GMT - 0.8.17 +* IMPROVED: Custom Stock Longitudinal Control - HKG - only allow engagement on user button press +* IMPROVED: Custom Stock Longitudinal Control - Volkswagen MQB & PQ - more consistent set speed change +* Bug fixes and performance improvements + +sunnypilot - Version Latest (2022-10-21) +======================== +* UPDATED: Synced with commaai's master branch - 2022.10.21-17:33:00:GMT - 0.8.17 +* IMPROVED: Custom Stock Longitudinal Control - Volkswagen MQB & PQ - more predictable button send logic +* Bug fixes and performance improvements + +sunnypilot - Version Latest (2022-10-20) +======================== +* UPDATED: Synced with commaai's master branch - 2022.10.20-20:25:00:GMT - 0.8.17 +* Bug fixes and performance improvements + +sunnypilot - Version Latest (2022-10-19) +======================== +* UPDATED: Synced with commaai's master branch - 2022.10.19-08:31:00:GMT - 0.8.17 +* IMPROVED: Controls: Speed Limit Control - accelerator press only disengage if "Disengage on Accelerator Pedal" is enabled +* Bug fixes and performance improvements + +sunnypilot - Version Latest (2022-10-18) +======================== +* UPDATED: Synced with commaai's master branch - 2022.10.18-04:44:00:GMT - 0.8.17 +* RE-ENABLED: Volkswagen MQB & PQ with Custom Stock Longitudinal Control +* NEW❗: Steering Rate Cost Live Tune + * Enables live tune for Steering Rate Cost. Lower value allows steering wheel to move more freely at low speed + * Can be found in "SP - Controls" menu +* FIXED: MADS: GM - include Regen Paddle logic thanks to @twilsonco! +* Bug fixes and performance improvements + +sunnypilot - Version Latest (2022-10-17) +======================== +* UPDATED: Synced with commaai's master branch - 2022.10.17-23:54:00:GMT+1 - 0.8.17 +* ENABLED: "Custom Stock Longitudinal Control" toggle for CAN-FD cars +* FIXED: HKG CAN-FD: Could not engage when openpilot longitudinal is enabled +* Bug fixes and performance improvements + +sunnypilot - Version Latest (2022-10-13) +======================== +* UPDATED: Synced with commaai's master branch - 2022.10.13-19:43:00:GMT+1 - 0.8.17 +* ADDED: Live Tmux toggle + * Can be found in "SP - General" menu +* IMPROVED: OpenStreetMap Database Update - only check for database update with explicit user decision +* Bug fixes and performance improvements + +sunnypilot - Version Latest (2022-10-11) +======================== +* ADDED: Hyundai openpilot longitudinal improvements - huge thanks to @aragon7777! +* ADDED: Check for OpenStreetMap Database Update button +* UPDATED: commaai: Low speed lateral control improvements (commaai:openpilot#26022, bbcd448) - pending PR +* FIXED: MUTCD speed limit spacing adjusts dynamically when no subtext is shown (i.e., speed limit offset, distance to next speed limit) +* FIXED: MADS: Intermittent CAN Error when engaging for Toyota Prius TSS-P +* Bug fixes and performance improvements + +sunnypilot - Version Latest (2022-10-09) +======================== +* ADDED: commaai: Low speed lateral control improvements (commaai:openpilot#26022, bca288bb) - pending PR +* FIXED: MADS: Intermittent CAN Error when engaging for Toyota Prius TSS-P +* IMPROVED: mapd: stop signs and other supported traffic_calming tags are now slowing/stopping as expected +* Bug fixes and performance improvements + +sunnypilot - Version Latest (2022-10-08) +======================== +* UPDATED: Synced with commaai's master branch - 2022.10.08-12:07:00:GMT+1 - 0.8.17 +* FIXED: MADS: Intermittent CAN Error when engaging for Toyota Prius TSS-P +* IMPROVED: mapd: Speed Humps are now set at 20 MPH or 32 km/h +* IMPROVED: OpenStreetMap Offline Database download experience +* Bug fixes and performance improvements + +sunnypilot - Version Latest (2022-10-07) +======================== +* UPDATED: Synced with commaai's master branch - 2022.10.07-08:16:00:GMT - 0.8.17 +* NEW❗: OpenStreetMap database can now be downloaded locally for offline use + * Now offering US South, US West, US Northeast, US Florida, Taiwan, and South Africa + * Databases updated - 2022.10.05-03:30:00:GMT +* NEW❗: mapd: Stop Sign, Yield, Speed Bump, Speed Hump, Sharp Curve support - huge thanks to @move-fast and @dragonpilot-community! + * Go to https://openstreetmap.org and start mapping out your area! +* Bug fixes and performance improvements + +sunnypilot - Version Latest (2022-09-30) +======================== +* UPDATED: Synced with commaai's master branch - 2022.09.30-22:43:00:GMT - 0.8.17 +* RE-ADDED: Torque Lateral Controller Live Tune Menu +* Bug fixes and performance improvements + +sunnypilot - Version Latest (2022-09-23) +======================== +* ADDED: Developer UI: latAccelFactorFiltered & frictionCoefficientFiltered values displays in green if Torque is using live params +* Bug fixes and performance improvements + +sunnypilot - Version Latest (2022-09-22) +======================== +* UPDATED: Synced with commaai's master branch - 2022.09.19-22:19:00:GMT - 0.8.17 +* NEW❗: Toggle to explicitly enable Custom Stock Longitudinal Control + * Applicable cars only: Honda, Hyundai/Kia/Genesis + * Settings -> Toggles menu + +sunnypilot - Version Latest (2022-09-21) +======================== +* UPDATED: Synced with commaai's master branch - 2022.09.19-22:19:00:GMT - 0.8.17 +* ADDED: Toggle to enable Live Torque (self/auto tune) with Torque lateral controller + * To enable, first enable "Enforce Torque Lateral Controller" toggle +* UPDATED: New metrics in Developer UI (when Live Torque is enabled) + * REMOVED: latAccelFactorRaw & frictionCoefficientRaw from torqued + * ADDED: latAccelFactorFiltered & frictionCoefficientFiltered from torqued +* REMOVED: Temporary remove Torque Lateral Controller Live Tune Menu + +sunnypilot - Version Latest (2022-09-20) +======================== +* UPDATED: Synced with commaai's master branch - 2022.09.19-22:19:00:GMT - 0.8.17 +* ADDED: Toggle to enable Live Torque (self/auto tune) with Torque lateral controller + * To enable, first enable "Enforce Torque Lateral Controller" toggle +* REMOVED: Temporary remove Torque Lateral Controller Live Tune Menu + +sunnypilot - Version Latest (2022-09-18) +======================== +* UPDATED: Synced with commaai's master branch - 2022.09.17-11:23:00:GMT - 0.8.17 +* ADDED: Kia Forte Non-SCC 2019 support for @askalice +* FIXED: Torque Lateral Control Live Tune now syncs with commaai:openpilot#25822 +* FIXED: mapd dependencies no longer need to be re-downloaded after unknown reboots + +sunnypilot - Version Latest (2022-09-17) +======================== +* UPDATED: Synced with commaai's master branch - 2022.09.17-11:23:00:GMT - 0.8.17 +* NEW❗: Non SCC HKG support + * Custom Stock Longitudinal Control + * ❗No❗ openpilot longitudinal control +* FIXED: Honda Bosch random low-value set speed changes + +sunnypilot - Version Latest (2022-09-16) +======================== +* UPDATED: Synced with commaai's master branch - 2022.09.16-20:23:00:GMT - 0.8.17 + +sunnypilot - Version Latest (2022-09-15) +======================== +* UPDATED: Synced with commaai's master branch - 2022.09.16-02:00:00:GMT - 0.8.17 +* FIXED: Block additional auto lane change actions if blinker stays on after the first lane change +* REVERTED: Some Toyota with LKAS button no longer requires double press to engage/disengage M.A.D.S. + +sunnypilot - Version Latest (2022-09-14)u +======================== +* UPDATED: Synced with commaai's master branch - 2022.09.11-02:47:00:GMT - 0.8.17 +* NEW❗: GM models supported in Force Car Recognition (FCR) + * Under "SP - Vehicles" +* NEW❗: Prompt to select car in "SP - Vehicles" if car unrecognized on startup +* FIXED: Some Toyota with LKAS button no longer requires double press to engage/disengage M.A.D.S. +* UPDATED: ESCC: Use radar tracks from radar if available + +sunnypilot - Version Latest (2022-09-13) +======================== +* UPDATED: Synced with commaai's master branch - 2022.09.11-02:47:00:GMT - 0.8.17 +* NEW❗: New metric in Developer UI + * Actual Lateral Acceleration (Roll Compensated) + +sunnypilot - Version Latest (2022-09-12) +======================== +* UPDATED: Synced with commaai's master branch - 2022.09.11-02:47:00:GMT - 0.8.17 +* FIXED: Honda Nidec models not gaining speed when longitudinal engaged + +sunnypilot - Version Latest (2022-09-11) +======================== +* UPDATED: Synced with commaai's master branch - 2022.09.11-02:47:00:GMT - 0.8.17 +* NEW❗: Hyundai Enhanced SCC now forwards FCW and AEB signals and commands from radar to car +* RE-ENABLED: MADS Status Icon toggle + +sunnypilot - Version Latest (2022-09-10) +======================== +* UPDATED: Synced with commaai's master branch - 2022.09.11-02:47:00:GMT - 0.8.17 +* NEW❗: RAM improvement implementation thanks to realfast! +* DISABLED: Chrysler/Jeep/Ram with Custom Stock Longitudinal Control +* DISABLED: Volkswagen MQB & PQ with Custom Stock Longitudinal Control + +sunnypilot - Version Latest (2022-09-09) +======================== +* UPDATED: Synced with commaai's master branch - 2022.09.09-07:35:00:GMT - 0.8.17 +* NEW❗: MADS now supporting General Motors (GM) +* ADDED: Custom Stock Longitudinal Control - Volkswagen + * MQB & PQ +* ADDED: Reverse ACC Change + * ACC +/-: Short=5, Long=1 +* ADDED: Custom Stock Longitudinal Control + * Hyundai/Kia/Genesis + * Honda Bosch +* ADDED: Hyundai: 2015-16 Genesis resume from standstill fix (commaai:openpilot#25579) - pending PR +* Vision Turn Speed Control re-enabled +* Disable Onroad Uploads toggle re-enabled + +sunnypilot - Version Latest (2022-09-08) +======================== +* UPDATED: Synced with commaai's master branch - 2022.09.08-04:05:00:GMT - 0.8.17 +* NEW❗: Block lane change initiation while brake is pressed + +sunnypilot - Version Latest (2022-09-07) +======================== +* UPDATED: Synced with commaai's master branch - 2022.09.08-04:05:00:GMT - 0.8.17 +* NEW❗: Display End-to-end longitudinal 🌮 on screen + * NEW❗: Hold DISTANCE button on the steering wheel for 1 second to switch between E2E Long and ACC mode + * Enable toggle on the driving screen to switch between modes with End-to-end longitudinal + * Only applicable to cars with openpilot longitudinal control +* NEW❗: Block lane change initiation while brake is pressed +* REMOVED: Dynamic Lane Profile - upstream laneless model is now on by default +* REMOVED: hyundai: consistent start from stop (commaai:openpilot#25672) - pending PR + +sunnypilot - Version Latest (2022-09-06) +======================== +* UPDATED: Synced with commaai's master branch - 2022.09.06 - 0.8.17 +* NEW❗: Display useful metrics above the chevron that tracks the lead car + * Under "SP - Visuals" menu + * Only applicable to cars with openpilot longitudinal control +* ADDED: hyundai: consistent start from stop (commaai:openpilot#25672) - pending PR +* FIXED: Vienna speed limit interface now scales properly with the outer box +* REMOVED: Hyundai long improvements (commaai:openpilot#25604) - closed PR + +sunnypilot - Version Latest (2022-09-05) +======================== +* UPDATED: Synced with commaai's master branch - 2022.09.03 - 0.8.17 +* NEW❗: Speed Limit Control (SLC) interface integrated with upstream +* NEW❗: Speed limit from active navigation is now prioritized for Speed Limit Control +* NEW❗: MUTCD (U.S.) or Vienna (E.U.) speed limit interfaces can now be selected under "SP - Controls" + +sunnypilot - Version Latest (2022-09-04) +======================== +* UPDATED: Synced with commaai's master branch - 2022.09.03 - 0.8.17 +* FIXED: Gap Adjust Cruise status now displays properly on screen +* FIXED: mapd - missing index in list caused mapd to crash +* REMOVED: Temporary removed Vision Turn Speed Control + +sunnypilot - Version Latest (2022-09-03) +======================== +* UPDATED: Synced with commaai's master branch - 2022.09.03 - 0.8.17 +* ADDED: New border colors for different operation engagements +* ADDED: UI: Show barrier when car detected in blind spot + * Only applicable to cars that have BSM detection with openpilot +* FIXED: Cruise Cancel button no longer display prompt if cruise not engaged +* TWEAKED: Update changelogs on startup in Settings -> Software -> Version +* REMOVED: Upload Raw Logs and Full Resolution Videos toggles + +sunnypilot - Version Latest (2022-08-31) +======================== +* UPDATED: Synced with commaai's master branch - 2022.08.31 - 0.8.17 +* ADDED: New border colors for different operation engagements +* ADDED: UI: Show barrier when car detected in blind spot + * Only applicable to cars that have BSM detection with openpilot +* FIXED: Cruise Cancel button no longer display prompt if cruise not engaged +* REMOVED: Upload Raw Logs and Full Resolution Videos toggles + +sunnypilot - Version 0.8.16 (2022-07-16) +======================== +* Sync with commaai's master branches +* NEW❗: Add toggle to pause lateral actuation below 30 MPH / 50 KM/H +* IMPROVED: Better controls mismatch handling +* IMPROVED: Less frequent Low Memory alert +* IMPROVED: Only allow lateral control when in forward gears +* IMPROVED: Better alerts handling on gear changes + +sunnypilot - Version 0.8.14-1.3 (2022-06-29) +======================== +* Hyundai/Kia/Genesis + * NEW❗: MADS: Add GAP/Distance button on the steering wheel to engage/disengage + * To engage/disengage MADS: Hold the button for 0.5 second +* NEW❗: Dynamic Lane Profile: Add toggle to enable "Laneless for Curves in Auto Lane" +* HOTFIX🛠: Improve Torque lateral control and reduce ping pong for some Toyota cars + * Torque control: higher low speed gains and better steering angle deadzone logic +* Developer UI: Remove Distance Traveled, replace with Memory Usage % + * This may have a potential to fix the Low Memory alert that may appear + +sunnypilot - Version 0.8.14-1 (2022-06-27) +======================== +* HOTFIX🛠: Honda, Toyota, Volkswagen now initialized correctly with Torque Lateral Live Tune + +sunnypilot - Version 0.8.14-1 (2022-06-27) +======================== +* NEW❗: Added toggle to enable updates for sunnypilot +* HOTFIX🛠: Volkswagen car list now displays properly in Force Car Recognition menu +* REVERTED: Honda - temporary removes CRUISE (MAIN) for MADS engagement + * LKAS button continues to be used for MADS engagement/disengagement + +sunnypilot - Version 0.8.14-1 (2022-06-26) +======================== +Visit https://bit.ly/sunnyreadme for more details +* sunnypilot 0.8.14 release - based on openpilot 0.8.14 devel +* "0.8.14-prod-c3" branch only supports comma three + * If you have a comma two, EON, or other devices than a comma three, visit sunnyhaibin's discord server for more details: https://discord.gg/wRW3meAgtx +* Mono-branch support + * Honda/Acura + * Hyundai/Kia/Genesis + * Toyota/Lexus + * Volkswagen MQB +* Modified Assistive Driving Safety (MADS) Mode + * NEW❗: CRUISE (MAIN) now engages MADS for all supported car makes + * NEW❗: Added toggle to disable disengaging Automatic Lane Centering (ALC) on the brake pedal +* Dynamic Lane Profile (DLP) +* NEW❗: Gap Adjust Cruise (GAC) + * openpilot longitudinal cars can now adjust between the lead car's following distance gap via 3 modes: + * Steering Wheel (SW) | User Interface (UI) | Steering Wheel + User Interface (SW+UI) +* NEW❗: Custom Camera & Path Offsets +* NEW❗: Torque Lateral Control from openpilot 0.8.15 master (as of 2022-06-15) +* NEW❗: Torque Lateral Control Live Tune Menu +* NEW❗: Speed Limit Sign from openpilot 0.8.15 master (as of 2022-06-22) +* NEW❗: Mapbox Speed Limit data will now be utilized in Speed Limit Control (SLC) + * Speed limit data will be utilized in the following availability: + * Mapbox (active navigation) -> OpenStreetMap -> Car Interface (Toyota's TSR) +* Custom Stock Longitudinal Control + * NEW❗: Volkswagen MQB + * Honda + * Hyundai/Kia/Genesis +* NEW❗: Mapbox navigation support for non-Prime users + * Visit sunnyhaibin's discord server for more details: https://discord.gg/wRW3meAgtx +* Hyundai/Kia/Genesis + * NEW❗: Enhanced SCC (ESCC) Support + * Requires hardware modification. Visit sunnyhaibin's discord server for more details: https://discord.gg/wRW3meAgtx + * NEW❗: Smart MDPS (SMDPS) Support - Auto-detection + * Requires hardware modification and custom firmware for the SMDPS. Visit sunnyhaibin's discord server for more details: https://discord.gg/wRW3meAgtx +* Toyota/Lexus + * NEW❗: Added toggle to enforce stock longitudinal control + +sunnypilot - Version 0.8.12-4 +======================== +* NEW❗: Custom Stock Longitudinal Control by setting the target speed via openpilot's "MAX" speed thanks to multikyd! + * Speed Limit Control + * Vision-based Turn Control + * Map-based Turn Control +* NEW❗: HDA status integration with Custom Stock Longitudinal Control on applicable HKG cars only +* NEW❗: Roll Compensation and SteerRatio fix from comma's 0.8.13 +* NEW❗: Dev UI to display different metrics on screen + * Click on the "MAX" box on the top left of the openpilot display to toggle different metrics display + * Lead car relative distance; Lead car relative speed; Actual steering degree; Desired steering degree; Engine RPM; Longitudinal acceleration; Lead car actual speed; EPS torque; Current altitude; Compass direction +* NEW❗: Stand Still Timer to display time spent at a stop with M.A.D.S engaged (i.e., stop lights, stop signs, traffic congestions) +* NEW❗: Current car speed text turns red when the car is braking +* NEW❗: Export GPS tracks into GPX files and upload to OSM thanks to eFini! +* NEW❗: Enable ACC and M.A.D.S with a single press of the RES+/SET- button +* NEW❗: ACC +/-: Short=5, Long=1 + * Change the ACC +/- buttons behavior with cruise speed change in openpilot + * Disabled (Stock): Short=1, Long=5 + * Enabled: Short=5, Long=1 +* NEW❗: Speed Limit Value Offset (not %)* + * Set speed limit higher or lower than actual speed limit for a more personalized drive. + * *To use this feature, turn off "Enable Speed Limit % Offset"* +* NEW❗: Dedicated icon to show the status of M.A.D.S. +* NEW❗: No Offroad Fix for non-official devices that cannot shut down after the car is turned off +* NEW❗: Stop N' Go Resume Alternative + * Offer alternative behavior to auto resume when stopped behind a lead car using stock SCC/ACC. This feature removes the repeating prompt chime when stopped and/or allows some cars to use auto resume (i.e., Genesis) +* IMPROVED: Show the lead car icon in the car's dashboard when a lead car is detected by openpilot's camera vision +* FIXED: MADS button unintentionally set MAX when using stock longitudinal control thanks to Spektor56! + +sunnypilot - Version 0.8.12-3 +======================== +* NEW❗: Bypass "System Malfunction" alert toggle + * Prevent openpilot from returning the "System Malfunction" alert that hinders the ability use openpilot +* FIXED: Hyundai/Kia/Genesis Brake Hold Active now outputs the correct events on screen with M.A.D.S. engaged + +sunnypilot - Version 0.8.12-2 +======================== +* NEW❗: Disable M.A.D.S. toggle to disable the beloved M.A.D.S. feature + * Enable Stock openpilot engagement/disengagement +* ADJUST: Initialize Driving Screen Off Brightness at 50% + +sunnypilot - Version 0.8.12-1 +======================== +* sunnypilot 0.8.12 release - based on openpilot 0.8.12 devel +* Dedicated Hyundai/Kia/Genesis branch support +* NEW❗: OpenStreetMap integration thanks to the Move Fast team! + * NEW❗: Vision-based Turn Control + * NEW❗: Map-Data-based Turn Control + * NEW❗: Speed Limit Control w/ optional Speed Limit Offset + * NEW❗: OpenStreetMap integration debug UI + * Only available to openpilot longitudinal enabled cars +* NEW❗: Hands on Wheel Monitoring according to EU r079r4e regulation +* NEW❗: Disable Onroad Uploads for data-limited Wi-Fi hotspots when using OpenStreetMap related features +* NEW❗: Fast Boot (Prebuilt) +* NEW❗: Auto Lane Change Timer +* NEW❗: Screen Brightness Control (Global) +* NEW❗: Driving Screen Off Timer +* NEW❗: Driving Screen Off Brightness (%) +* NEW❗: Max Time Offroad +* Improved user feedback with M.A.D.S. operations thanks to Spektor56! + * Lane Path + * Green🟢 (Laneful), Red🔴 (Laneless): M.A.D.S. engaged + * White⚪: M.A.D.S. suspended or disengaged + * Black⚫: M.A.D.S. engaged, steering is being manually override by user + * Screen border now only illuminates Green when SCC/ACC is engaged + +sunnypilot - Version 0.8.10-1 (Unreleased) +======================== +* sunnypilot 0.8.10 release - based on openpilot 0.8.10 `devel` +* Add Toyota cars to Force Car Recognition + +sunnypilot - Version 0.8.9-4 +======================== +* Hyundai: Fix Ioniq Hybrid signals + +sunnypilot - Version 0.8.9-3 +======================== +* Update home screen brand and version structure + +sunnypilot - Version 0.8.9-2 +======================== +* Added additional Sonata Hybrid Firmware Versions +* Features + * Modified Assistive Driving Safety (MADS) Mode + * Dynamic Lane Profile (DLP) + * Quiet Drive 🤫 + * Force Car Recognition (FCR) + * PID Controller: add kd into the stock PID controller + +sunnypilot - Version 0.8.9-1 +======================== +* First changelog! +* Features + * Modified Assistive Driving Safety (MADS) Mode + * Dynamic Lane Profile (DLP) + * Quiet Drive 🤫 + * Force Car Recognition (FCR) + * PID Controller: add kd into the stock PID controller diff --git a/Dockerfile.openpilot b/Dockerfile.openpilot deleted file mode 100644 index d85be77121..0000000000 --- a/Dockerfile.openpilot +++ /dev/null @@ -1,12 +0,0 @@ -FROM ghcr.io/commaai/openpilot-base:latest - -ENV PYTHONUNBUFFERED=1 - -ENV OPENPILOT_PATH=/home/batman/openpilot - -RUN mkdir -p ${OPENPILOT_PATH} -WORKDIR ${OPENPILOT_PATH} - -COPY . ${OPENPILOT_PATH}/ - -RUN scons --cache-readonly -j$(nproc) diff --git a/Dockerfile.openpilot_base b/Dockerfile.openpilot_base deleted file mode 100644 index 04fb589bf6..0000000000 --- a/Dockerfile.openpilot_base +++ /dev/null @@ -1,82 +0,0 @@ -FROM ubuntu:24.04 - -ENV PYTHONUNBUFFERED=1 - -ENV DEBIAN_FRONTEND=noninteractive -RUN apt-get update && \ - apt-get install -y --no-install-recommends sudo tzdata locales ssh pulseaudio xvfb x11-xserver-utils gnome-screenshot python3-tk python3-dev && \ - rm -rf /var/lib/apt/lists/* - -RUN sed -i -e 's/# en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/' /etc/locale.gen && locale-gen -ENV LANG=en_US.UTF-8 -ENV LANGUAGE=en_US:en -ENV LC_ALL=en_US.UTF-8 - -COPY tools/install_ubuntu_dependencies.sh /tmp/tools/ -RUN /tmp/tools/install_ubuntu_dependencies.sh && \ - rm -rf /var/lib/apt/lists/* /tmp/* && \ - cd /usr/lib/gcc/arm-none-eabi/* && \ - rm -rf arm/ thumb/nofp thumb/v6* thumb/v8* thumb/v7+fp thumb/v7-r+fp.sp - -# Add OpenCL -RUN apt-get update && apt-get install -y --no-install-recommends \ - apt-utils \ - alien \ - unzip \ - tar \ - curl \ - xz-utils \ - dbus \ - gcc-arm-none-eabi \ - tmux \ - vim \ - libx11-6 \ - wget \ - && rm -rf /var/lib/apt/lists/* - -RUN mkdir -p /tmp/opencl-driver-intel && \ - cd /tmp/opencl-driver-intel && \ - wget https://github.com/intel/llvm/releases/download/2024-WW14/oclcpuexp-2024.17.3.0.09_rel.tar.gz && \ - wget https://github.com/oneapi-src/oneTBB/releases/download/v2021.12.0/oneapi-tbb-2021.12.0-lin.tgz && \ - mkdir -p /opt/intel/oclcpuexp_2024.17.3.0.09_rel && \ - cd /opt/intel/oclcpuexp_2024.17.3.0.09_rel && \ - tar -zxvf /tmp/opencl-driver-intel/oclcpuexp-2024.17.3.0.09_rel.tar.gz && \ - mkdir -p /etc/OpenCL/vendors && \ - echo /opt/intel/oclcpuexp_2024.17.3.0.09_rel/x64/libintelocl.so > /etc/OpenCL/vendors/intel_expcpu.icd && \ - cd /opt/intel && \ - tar -zxvf /tmp/opencl-driver-intel/oneapi-tbb-2021.12.0-lin.tgz && \ - ln -s /opt/intel/oneapi-tbb-2021.12.0/lib/intel64/gcc4.8/libtbb.so /opt/intel/oclcpuexp_2024.17.3.0.09_rel/x64 && \ - ln -s /opt/intel/oneapi-tbb-2021.12.0/lib/intel64/gcc4.8/libtbbmalloc.so /opt/intel/oclcpuexp_2024.17.3.0.09_rel/x64 && \ - ln -s /opt/intel/oneapi-tbb-2021.12.0/lib/intel64/gcc4.8/libtbb.so.12 /opt/intel/oclcpuexp_2024.17.3.0.09_rel/x64 && \ - ln -s /opt/intel/oneapi-tbb-2021.12.0/lib/intel64/gcc4.8/libtbbmalloc.so.2 /opt/intel/oclcpuexp_2024.17.3.0.09_rel/x64 && \ - mkdir -p /etc/ld.so.conf.d && \ - echo /opt/intel/oclcpuexp_2024.17.3.0.09_rel/x64 > /etc/ld.so.conf.d/libintelopenclexp.conf && \ - ldconfig -f /etc/ld.so.conf.d/libintelopenclexp.conf && \ - cd / && \ - rm -rf /tmp/opencl-driver-intel - -ENV NVIDIA_VISIBLE_DEVICES=all -ENV NVIDIA_DRIVER_CAPABILITIES=graphics,utility,compute -ENV QTWEBENGINE_DISABLE_SANDBOX=1 - -RUN dbus-uuidgen > /etc/machine-id -RUN apt-get update && apt-get install -y fonts-noto-cjk fonts-noto-color-emoji - -ARG USER=batman -ARG USER_UID=1001 -RUN useradd -m -s /bin/bash -u $USER_UID $USER -RUN usermod -aG sudo $USER -RUN echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers -USER $USER - -COPY --chown=$USER pyproject.toml uv.lock /home/$USER -COPY --chown=$USER tools/install_python_dependencies.sh /home/$USER/tools/ - -ENV VIRTUAL_ENV=/home/$USER/.venv -ENV PATH="$VIRTUAL_ENV/bin:$PATH" -RUN cd /home/$USER && \ - tools/install_python_dependencies.sh && \ - rm -rf tools/ pyproject.toml uv.lock .cache - -USER root -RUN sudo git config --global --add safe.directory /tmp/openpilot diff --git a/Jenkinsfile b/Jenkinsfile index a14bf59299..d57e9502aa 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -12,7 +12,7 @@ def retryWithDelay(int maxRetries, int delay, Closure body) { def device(String ip, String step_label, String cmd) { withCredentials([file(credentialsId: 'id_rsa', variable: 'key_file')]) { def ssh_cmd = """ -ssh -o ConnectTimeout=5 -o ServerAliveInterval=5 -o ServerAliveCountMax=2 -o BatchMode=yes -o StrictHostKeyChecking=no -i ${key_file} 'comma@${ip}' exec /usr/bin/bash <<'END' +ssh -o ControlMaster=auto -o ControlPath=/tmp/ssh_control_%C -o ControlPersist=yes -o ConnectTimeout=5 -o ServerAliveInterval=5 -o ServerAliveCountMax=2 -o BatchMode=yes -o StrictHostKeyChecking=no -i ${key_file} 'comma@${ip}' exec /usr/bin/bash <<'END' set -e @@ -22,7 +22,7 @@ shopt -s huponexit # kill all child processes when the shell exits export CI=1 export PYTHONWARNINGS=error -export LOGPRINT=debug +#export LOGPRINT=debug # this has gotten too spammy... export TEST_DIR=${env.TEST_DIR} export SOURCE_DIR=${env.SOURCE_DIR} export GIT_BRANCH=${env.GIT_BRANCH} @@ -63,6 +63,8 @@ if [ -f /data/openpilot/launch_env.sh ]; then source /data/openpilot/launch_env.sh fi +export LD_LIBRARY_PATH="\$(python -c 'import ffmpeg; print(ffmpeg.LIB_DIR)'):/usr/local/lib:\${LD_LIBRARY_PATH:-}" + ln -snf ${env.TEST_DIR} /data/pythonpath cd ${env.TEST_DIR} || true @@ -93,7 +95,7 @@ def deviceStage(String stageName, String deviceType, List extra_env, def steps) retry (3) { def date = sh(script: 'date', returnStdout: true).trim(); device(device_ip, "set time", "date -s '" + date + "'") - device(device_ip, "git checkout", extra + "\n" + readFile("selfdrive/test/setup_device_ci.sh")) + device(device_ip, "git checkout", extra + "\n" + readFile("openpilot/selfdrive/test/setup_device_ci.sh")) } steps.each { item -> def name = item[0] @@ -166,8 +168,8 @@ node { env.GIT_BRANCH = checkout(scm).GIT_BRANCH env.GIT_COMMIT = checkout(scm).GIT_COMMIT - def excludeBranches = ['__nightly', 'devel', 'devel-staging', 'release3', 'release3-staging', - 'testing-closet*', 'hotfix-*'] + def excludeBranches = ['__nightly', 'devel', 'devel-staging', + 'release-tizi', 'release-tizi-staging', 'release-mici', 'release-mici-staging', 'testing-closet*', 'hotfix-*'] def excludeRegex = excludeBranches.join('|').replaceAll('\\*', '.*') if (env.BRANCH_NAME != 'master' && !env.BRANCH_NAME.contains('__jenkins_loop_')) { @@ -178,21 +180,21 @@ node { try { if (env.BRANCH_NAME == 'devel-staging') { - deviceStage("build release3-staging", "tici-needs-can", [], [ - step("build release3-staging", "RELEASE_BRANCH=release3-staging $SOURCE_DIR/release/build_release.sh"), + deviceStage("build release-tizi-staging", "tizi-needs-can", [], [ + step("build release-tizi-staging", "RELEASE_BRANCH=release-tizi-staging,release-mici-staging $SOURCE_DIR/tools/release/build_release.sh"), ]) } if (env.BRANCH_NAME == '__nightly') { parallel ( 'nightly': { - deviceStage("build nightly", "tici-needs-can", [], [ - step("build nightly", "RELEASE_BRANCH=nightly $SOURCE_DIR/release/build_release.sh"), + deviceStage("build nightly", "tizi-needs-can", [], [ + step("build nightly", "RELEASE_BRANCH=nightly $SOURCE_DIR/tools/release/build_release.sh"), ]) }, 'nightly-dev': { - deviceStage("build nightly-dev", "tici-needs-can", [], [ - step("build nightly-dev", "PANDA_DEBUG_BUILD=1 RELEASE_BRANCH=nightly-dev $SOURCE_DIR/release/build_release.sh"), + deviceStage("build nightly-dev", "tizi-needs-can", [], [ + step("build nightly-dev", "PANDA_DEBUG_BUILD=1 RELEASE_BRANCH=nightly-dev $SOURCE_DIR/tools/release/build_release.sh"), ]) }, ) @@ -200,77 +202,53 @@ node { if (!env.BRANCH_NAME.matches(excludeRegex)) { parallel ( - // tici tests 'onroad tests': { - deviceStage("onroad", "tici-needs-can", ["UNSAFE=1"], [ - step("build openpilot", "cd system/manager && ./build.py"), - step("check dirty", "release/check-dirty.sh"), - step("onroad tests", "pytest selfdrive/test/test_onroad.py -s", [timeout: 60]), + deviceStage("onroad", "tizi-needs-can", ["UNSAFE=1"], [ + step("build openpilot", "cd openpilot/system/manager && ./build.py"), + step("check dirty", "tools/release/check-dirty.sh"), + step("onroad tests", "pytest openpilot/selfdrive/test/test_onroad.py -s", [timeout: 60]), ]) }, 'HW + Unit Tests': { - deviceStage("tici-hardware", "tici-common", ["UNSAFE=1"], [ - step("build", "cd system/manager && ./build.py"), - step("test pandad", "pytest selfdrive/pandad/tests/test_pandad.py", [diffPaths: ["panda", "selfdrive/pandad/"]]), - step("test power draw", "pytest -s system/hardware/tici/tests/test_power_draw.py"), - step("test encoder", "LD_LIBRARY_PATH=/usr/local/lib pytest system/loggerd/tests/test_encoder.py", [diffPaths: ["system/loggerd/"]]), - step("test pigeond", "pytest system/ubloxd/tests/test_pigeond.py", [diffPaths: ["system/ubloxd/"]]), - step("test manager", "pytest system/manager/test/test_manager.py"), - ]) - }, - 'loopback': { - deviceStage("loopback", "tici-loopback", ["UNSAFE=1"], [ - step("build openpilot", "cd system/manager && ./build.py"), - step("test pandad loopback", "pytest selfdrive/pandad/tests/test_pandad_loopback.py"), - ]) - }, - 'camerad AR0231': { - deviceStage("AR0231", "tici-ar0231", ["UNSAFE=1"], [ - step("build", "cd system/manager && ./build.py"), - step("test camerad", "pytest system/camerad/test/test_camerad.py", [timeout: 60]), - step("test exposure", "pytest system/camerad/test/test_exposure.py"), + deviceStage("tizi-hardware", "tizi-common", ["UNSAFE=1"], [ + step("build", "cd openpilot/system/manager && ./build.py"), + step("test power draw", "pytest -s openpilot/selfdrive/test//test_power_draw.py"), + step("test encoder", "pytest openpilot/system/loggerd/tests/test_encoder.py", [diffPaths: ["openpilot/system/loggerd/"]]), + step("test manager", "pytest openpilot/system/manager/test/test_manager.py"), ]) }, 'camerad OX03C10': { - deviceStage("OX03C10", "tici-ox03c10", ["UNSAFE=1"], [ - step("build", "cd system/manager && ./build.py"), - step("test camerad", "pytest system/camerad/test/test_camerad.py", [timeout: 60]), - step("test exposure", "pytest system/camerad/test/test_exposure.py"), + deviceStage("OX03C10", "tizi-ox03c10", ["UNSAFE=1"], [ + step("build", "cd openpilot/system/manager && ./build.py"), + step("test pandad", "pytest openpilot/selfdrive/pandad/tests/test_pandad.py"), + step("test camerad", "pytest openpilot/system/camerad/test/test_camerad.py", [timeout: 90]), ]) }, 'camerad OS04C10': { deviceStage("OS04C10", "tici-os04c10", ["UNSAFE=1"], [ - step("build", "cd system/manager && ./build.py"), - step("test camerad", "pytest system/camerad/test/test_camerad.py", [timeout: 60]), - step("test exposure", "pytest system/camerad/test/test_exposure.py"), + step("build", "cd openpilot/system/manager && ./build.py"), + step("test pandad", "pytest openpilot/selfdrive/pandad/tests/test_pandad.py"), + step("test camerad", "pytest openpilot/system/camerad/test/test_camerad.py", [timeout: 90]), ]) }, 'sensord': { - deviceStage("LSM + MMC", "tici-lsmc", ["UNSAFE=1"], [ - step("build", "cd system/manager && ./build.py"), - step("test sensord", "pytest system/sensord/tests/test_sensord.py"), - ]) - deviceStage("BMX + LSM", "tici-bmx-lsm", ["UNSAFE=1"], [ - step("build", "cd system/manager && ./build.py"), - step("test sensord", "pytest system/sensord/tests/test_sensord.py"), + deviceStage("LSM + MMC", "tizi-lsmc", ["UNSAFE=1"], [ + step("build", "cd openpilot/system/manager && ./build.py"), + step("test sensord", "pytest openpilot/system/sensord/tests/test_sensord.py"), ]) }, 'replay': { - deviceStage("model-replay", "tici-replay", ["UNSAFE=1"], [ - step("build", "cd system/manager && ./build.py", [diffPaths: ["selfdrive/modeld/", "tinygrad_repo", "selfdrive/test/process_replay/model_replay.py"]]), - step("model replay", "selfdrive/test/process_replay/model_replay.py", [diffPaths: ["selfdrive/modeld/", "tinygrad_repo", "selfdrive/test/process_replay/model_replay.py"]]), + deviceStage("model-replay", "tizi-replay", ["UNSAFE=1"], [ + step("build", "cd openpilot/system/manager && ./build.py", [diffPaths: ["openpilot/selfdrive/modeld/", "tinygrad_repo", "openpilot/selfdrive/test/process_replay/model_replay.py"]]), + step("model replay", "openpilot/selfdrive/test/process_replay/model_replay.py", [diffPaths: ["openpilot/selfdrive/modeld/", "tinygrad_repo", "openpilot/selfdrive/test/process_replay/model_replay.py"]]), ]) }, 'tizi': { deviceStage("tizi", "tizi", ["UNSAFE=1"], [ - step("build openpilot", "cd system/manager && ./build.py"), - step("test pandad loopback", "SINGLE_PANDA=1 pytest selfdrive/pandad/tests/test_pandad_loopback.py"), - step("test pandad spi", "pytest selfdrive/pandad/tests/test_pandad_spi.py"), - step("test pandad", "pytest selfdrive/pandad/tests/test_pandad.py", [diffPaths: ["panda", "selfdrive/pandad/"]]), - step("test amp", "pytest system/hardware/tici/tests/test_amplifier.py"), - // TODO: enable once new AGNOS is available - // step("test esim", "pytest system/hardware/tici/tests/test_esim.py"), - step("test qcomgpsd", "pytest system/qcomgpsd/tests/test_qcomgpsd.py", [diffPaths: ["system/qcomgpsd/"]]), + step("build openpilot", "cd openpilot/system/manager && ./build.py"), + step("test pandad loopback", "pytest openpilot/selfdrive/pandad/tests/test_pandad_loopback.py"), + step("test pandad spi", "pytest openpilot/selfdrive/pandad/tests/test_pandad_spi.py"), + step("test amp", "pytest openpilot/common/hardware/tici/tests/test_amplifier.py"), ]) }, diff --git a/README.md b/README.md index 897852b03f..71fbb00e4c 100644 --- a/README.md +++ b/README.md @@ -3,68 +3,23 @@ ## 🌞 What is sunnypilot? [sunnypilot](https://github.com/sunnyhaibin/sunnypilot) is a fork of comma.ai's openpilot, an open source driver assistance system. sunnypilot offers the user a unique driving experience for over 300+ supported car makes and models with modified behaviors of driving assist engagements. sunnypilot complies with comma.ai's safety rules as accurately as possible. -## 💭 Join our Discord -Join the official sunnypilot Discord server to stay up to date with all the latest features and be a part of shaping the future of sunnypilot! -* https://discord.gg/sunnypilot - - ![](https://dcbadge.vercel.app/api/server/wRW3meAgtx?style=flat) ![Discord Shield](https://discordapp.com/api/guilds/880416502577266699/widget.png?style=shield) +## 💭 Join our Community Forum +Join the official sunnypilot community forum to stay up to date with all the latest features and be a part of shaping the future of sunnypilot! +* https://community.sunnypilot.ai/ ## Documentation https://docs.sunnypilot.ai/ is your one stop shop for everything from features to installation to FAQ about the sunnypilot ## 🚘 Running on a dedicated device in a car -* A supported device to run this software - * a [comma three](https://comma.ai/shop/products/three) or a [C3X](https://comma.ai/shop/comma-3x) -* This software -* One of [the 300+ supported cars](https://github.com/commaai/openpilot/blob/master/docs/CARS.md). We support Honda, Toyota, Hyundai, Nissan, Kia, Chrysler, Lexus, Acura, Audi, VW, Ford and more. If your car is not supported but has adaptive cruise control and lane-keeping assist, it's likely able to run sunnypilot. -* A [car harness](https://comma.ai/shop/products/car-harness) to connect to your car - -Detailed instructions for [how to mount the device in a car](https://comma.ai/setup). +First, check out this list of items you'll need to [get started](https://community.sunnypilot.ai/t/getting-started-using-sunnypilot-in-your-supported-car/251). ## Installation -Please refer to [Recommended Branches](#-recommended-branches) to find your preferred/supported branch. This guide will assume you want to install the latest `release-c3` branch. - -* sunnypilot not installed or you installed a version before 0.8.17? - 1. [Factory reset/uninstall](https://github.com/commaai/openpilot/wiki/FAQ#how-can-i-reset-the-device) the previous software if you have another software/fork installed. - 2. After factory reset/uninstall and upon reboot, select `Custom Software` when given the option. - 3. Input the installation URL per [Recommended Branches](#-recommended-branches). Example: ```release-c3.sunnypilot.ai```. - 4. Complete the rest of the installation following the onscreen instructions. - -* sunnypilot already installed and you installed a version after 0.8.17? - 1. On the comma three, go to `Settings` ▶️ `Software`. - 2. At the `Download` option, press `CHECK`. This will fetch the list of latest branches from sunnypilot. - 3. At the `Target Branch` option, press `SELECT` to open the Target Branch selector. - 4. Scroll to select the desired branch per Recommended Branches (see below). Example: `release-c3` - -| Branch | Installation URL | -|:------------:|:--------------------------------:| -| `release-c3` | https://release-c3.sunnypilot.ai | -| `staging-c3` | https://staging-c3.sunnypilot.ai | -| `dev-c3` | https://dev-c3.sunnypilot.ai | - -### If you want to use our newest branches (our rewrite) -> [!TIP] ->You can see the rewrite state on our [rewrite project board](https://github.com/orgs/sunnypilot/projects/2), and to install the new branches, you can use the following links - - -> [!IMPORTANT] -> It is recommended to [re-flash AGNOS](https://flash.comma.ai/) if you intend to downgrade from the new branches. -> You can still restore the latest sunnylink backup made on the old branches. - -| Branch | Installation URL | -|:----------------:|:---------------------------------------------:| -| `staging-c3-new` | `https://staging-c3-new.sunnypilot.ai` | -| `dev-c3-new` | `https://dev-c3-new.sunnypilot.ai` | -| `custom-branch` | `https://install.sunnypilot.ai/{branch_name}` | -| `release-c3-new` | **Not yet available**. | - -> [!TIP] -> Do you require further assistance with software installation? Join the [sunnypilot Discord server](https://discord.sunnypilot.com) and message us in the `#installation-help` channel. +Next, refer to the sunnypilot community forum for [installation instructions](https://community.sunnypilot.ai/t/read-before-installing-sunnypilot/254), as well as a complete list of [Recommended Branch Installations](https://community.sunnypilot.ai/t/recommended-branch-installations/235). ## 🎆 Pull Requests We welcome both pull requests and issues on GitHub. Bug fixes are encouraged. -Pull requests should be against the most current `master-new` branch. +Pull requests should be against the most current `master` branch. ## 📊 User Data @@ -73,7 +28,7 @@ By default, sunnypilot uploads the driving data to comma servers. You can also a sunnypilot is open source software. The user is free to disable data collection if they wish to do so. sunnypilot logs the road-facing camera, CAN, GPS, IMU, magnetometer, thermal sensors, crashes, and operating system logs. -The driver-facing camera is only logged if you explicitly opt-in in settings. The microphone is not recorded. +The driver-facing camera and microphone are only logged if you explicitly opt-in in settings. By using this software, you understand that use of this software or its related services will generate certain types of user data, which may be logged and stored at the sole discretion of comma. By accepting this agreement, you grant an irrevocable, perpetual, worldwide right to comma for the use of this data. diff --git a/RELEASES.md b/RELEASES.md index 91652d6dc7..770a7c40fe 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -1,6 +1,67 @@ -Version 0.9.10 (2025-06-30) +Version 0.11.2 (2026-06-15) ======================== + +Version 0.11.1 (2026-05-18) +======================== +* New driver monitoring model +* Improved image processing pipeline for driver camera +* Improved thermal policy for comma four +* Acura MDX 2022-24 support thanks to mvl-boston! +* Rivian R1S and R1T 2025 support thanks to lukasloetkolben! + +Version 0.11.0 (2026-03-17) +======================== +* New driving model #36798 + * Fully trained using a learned simulator + * Improved longitudinal performance in Experimental mode +* Reduce comma four standby power usage by 77% to 52 mW +* Kia K7 2017 support thanks to royjr! +* Lexus LS 2018 support thanks to Hacheoy! + +Version 0.10.3 (2025-12-17) +======================== +* New driving model #36249 + * New temporal policy architecture + * New on-policy training physics noise model +* New driver monitoring model #36409 + * Trained on a new dataset, including comma four data +* Improved inter-process communication memory efficiency + +Version 0.10.2 (2025-11-19) +======================== +* comma four support + +Version 0.10.1 (2025-09-08) +======================== +* New driving model #36276 + * World Model: removed global localization inputs + * World Model: 2x the number of parameters + * World Model: trained on 4x the number of segments + * VAE Compression Model: new architecture and training objective + * Driving Vision Model: trained on 4x the number of segments +* New Driver Monitoring model #36198 +* Acura TLX 2021 support thanks to MVL! +* Honda City 2023 support thanks to vanillagorillaa and drFritz! +* Honda N-Box 2018 support thanks to miettal! +* Honda Odyssey 2021-25 support thanks to csouers and MVL! +* Honda Passport 2026 support thanks to vanillagorillaa and MVL! + +Version 0.10.0 (2025-08-05) +======================== +* New driving model + * New training architecture + * Described in our CVPR paper: "Learning to Drive from a World Model" + * Longitudinal MPC replaced by E2E planning from World Model in Experimental Mode + * Action from lateral MPC as training objective replaced by E2E planning from World Model + * Low-speed lead car ground-truth fixes +* Enable live-learned steering actuation delay +* Opt-in audio recording for dashcam video +* Acura MDX 2025 support thanks to vanillagorillaa and MVL! +* Honda Accord 2023-25 support thanks to vanillagorillaa and MVL! +* Honda CR-V 2023-25 support thanks to vanillagorillaa and MVL! +* Honda Pilot 2023-25 support thanks to vanillagorillaa and MVL! + Version 0.9.9 (2025-05-23) ======================== * New driving model @@ -1043,7 +1104,7 @@ Version 0.2.1 (2016-12-14) Version 0.2 (2016-12-12) ========================= - * Car/Radar abstraction layers have shipped, see cereal/car.capnp + * Car/Radar abstraction layers have shipped, see openpilot/cereal/car.capnp * controlsd has been refactored * Shipped plant model and testing maneuvers * visiond exits more gracefully now diff --git a/SConstruct b/SConstruct index 77c8525896..8cf191daab 100644 --- a/SConstruct +++ b/SConstruct @@ -3,352 +3,266 @@ import subprocess import sys import sysconfig import platform +import shlex +import importlib import numpy as np import SCons.Errors +from SCons.Defaults import _stripixes + +TICI = os.path.isfile('/TICI') SCons.Warnings.warningAsException(True) -# pending upstream fix - https://github.com/SCons/scons/issues/4461 -#SetOption('warn', 'all') - -TICI = os.path.isfile('/TICI') -AGNOS = TICI - Decider('MD5-timestamp') -SetOption('num_jobs', int(os.cpu_count()/2)) - -AddOption('--kaitai', - action='store_true', - help='Regenerate kaitai struct parsers') - -AddOption('--asan', - action='store_true', - help='turn on ASAN') - -AddOption('--ubsan', - action='store_true', - help='turn on UBSan') - -AddOption('--coverage', - action='store_true', - help='build with test coverage options') - -AddOption('--clazy', - action='store_true', - help='build with clazy') - -AddOption('--compile_db', - action='store_true', - help='build clang compilation database') - -AddOption('--ccflags', - action='store', - type='string', - default='', - help='pass arbitrary flags over the command line') - -AddOption('--external-sconscript', - action='store', - metavar='FILE', - dest='external_sconscript', - help='add an external SConscript to the build') - -AddOption('--mutation', - action='store_true', - help='generate mutation-ready code') +SetOption('num_jobs', max(1, int(os.cpu_count()/(1 if "CI" in os.environ else 2)))) +AddOption('--ccflags', action='store', type='string', default='', help='pass arbitrary flags over the command line') +AddOption('--verbose', action='store_true', default=False, help='show full build commands') +release = not os.path.exists(File('#.gitattributes').abspath) # file absent on release branch, see release_files.py AddOption('--minimal', action='store_false', dest='extras', - default=os.path.exists(File('#.lfsconfig').abspath), # minimal by default on release branch (where there's no LFS) + default=(not TICI and not release), help='the minimum build to run openpilot. no tests, tools, etc.') -AddOption('--stock-ui', - action='store_true', - dest='stock_ui', - default=False, - help='Build stock openpilot UI instead of sunnypilot UI') +submodule_python_paths = [ + Dir("#").abspath, + Dir("#msgq_repo").abspath, + Dir("#opendbc_repo").abspath, + Dir("#rednose_repo").abspath, + Dir("#teleoprtc_repo").abspath, + Dir("#tinygrad_repo").abspath, +] +for p in reversed(submodule_python_paths): + if p not in sys.path: + sys.path.insert(0, p) -## Architecture name breakdown (arch) -## - larch64: linux tici aarch64 -## - aarch64: linux pc aarch64 -## - x86_64: linux pc x64 -## - Darwin: mac x64 or arm64 -real_arch = arch = subprocess.check_output(["uname", "-m"], encoding='utf8').rstrip() +if external_pythonpath := os.environ.get("PYTHONPATH"): + submodule_python_paths += [p for p in external_pythonpath.split(os.pathsep) if p and p not in submodule_python_paths] + +# Detect platform +arch = subprocess.check_output(["uname", "-m"], encoding='utf8').rstrip() if platform.system() == "Darwin": arch = "Darwin" - brew_prefix = subprocess.check_output(['brew', '--prefix'], encoding='utf8').strip() -elif arch == "aarch64" and AGNOS: +elif arch == "aarch64" and TICI: arch = "larch64" -assert arch in ["larch64", "aarch64", "x86_64", "Darwin"] +assert arch in [ + "larch64", # linux tici arm64 + "aarch64", # linux pc arm64 + "x86_64", # linux pc x64 + "Darwin", # macOS arm64 (x86 not supported) +] -lenv = { - "PATH": os.environ['PATH'], - "LD_LIBRARY_PATH": [Dir(f"#third_party/acados/{arch}/lib").abspath], - "PYTHONPATH": Dir("#").abspath + ':' + Dir(f"#third_party/acados").abspath, +pkg_names = ['acados', 'bzip2', 'capnproto', 'catch2', 'eigen', 'ffmpeg', 'json11', 'ncurses', 'zeromq', 'zstd'] +pkgs = [importlib.import_module(name) for name in pkg_names] +acados = pkgs[pkg_names.index('acados')] +ffmpeg = pkgs[pkg_names.index('ffmpeg')] +# Shared package ships .so/.dylib; older device venvs still have static .a only. +# Keep static link deps (x264/z/va/drm) when the installed package is static so +# TICI CI works without upgrading the device venv yet. +# TODO: drop the static fallback once device venvs have comma-deps-ffmpeg>=7.1.0.post94 +_ffmpeg_lib_names = os.listdir(ffmpeg.LIB_DIR) if os.path.isdir(ffmpeg.LIB_DIR) else [] +ffmpeg_shared = any( + n.startswith('libavcodec.so') or (n.startswith('libavcodec') and n.endswith('.dylib')) + for n in _ffmpeg_lib_names +) +ffmpeg_libs = ['avformat', 'avcodec', 'swresample', 'avutil'] +if not ffmpeg_shared: + ffmpeg_libs += ['x264', 'z'] + if arch != "Darwin": + ffmpeg_libs += ['va', 'va-drm', 'drm'] +acados_include_dirs = [ + acados.INCLUDE_DIR, + os.path.join(acados.INCLUDE_DIR, "blasfeo", "include"), + os.path.join(acados.INCLUDE_DIR, "hpipm", "include"), +] - "ACADOS_SOURCE_DIR": Dir("#third_party/acados").abspath, - "ACADOS_PYTHON_INTERFACE_PATH": Dir("#third_party/acados/acados_template").abspath, - "TERA_PATH": Dir("#").abspath + f"/third_party/acados/{arch}/t_renderer" + +# ***** enforce a whitelist of system libraries ***** +# this prevents silently relying on a 3rd party package, +# e.g. apt-installed libusb. all libraries should either +# be distributed with all Linux distros and macOS, or +# vendored in commaai/dependencies. +allowed_system_libs = { + "EGL", "GLESv2", "GL", + "Qt5Charts", "Qt5Core", "Qt5Gui", "Qt5Widgets", + "dl", "drm", "gbm", "m", "pthread", } -rpath = lenv["LD_LIBRARY_PATH"].copy() +def _resolve_lib(env, name): + for d in env.Flatten(env.get('LIBPATH', [])): + p = Dir(str(d)).abspath + for ext in ('.a', '.so', '.dylib'): + f = File(os.path.join(p, f'lib{name}{ext}')) + if f.exists() or f.has_builder(): + return name + if name in allowed_system_libs: + return name + raise SCons.Errors.UserError(f"Unexpected non-vendored library '{name}'") -if arch == "larch64": - cpppath = [ - "#third_party/opencl/include", - ] - - libpath = [ - "/usr/local/lib", - "/system/vendor/lib64", - f"#third_party/acados/{arch}/lib", - ] - - libpath += [ - "#third_party/snpe/larch64", - "#third_party/libyuv/larch64/lib", - "/usr/lib/aarch64-linux-gnu" - ] - cflags = ["-DQCOM2", "-mcpu=cortex-a57"] - cxxflags = ["-DQCOM2", "-mcpu=cortex-a57"] - rpath += ["/usr/local/lib"] -else: - cflags = [] - cxxflags = [] - cpppath = [] - rpath += [] - - # MacOS - if arch == "Darwin": - libpath = [ - f"#third_party/libyuv/{arch}/lib", - f"#third_party/acados/{arch}/lib", - f"{brew_prefix}/lib", - f"{brew_prefix}/opt/openssl@3.0/lib", - "/System/Library/Frameworks/OpenGL.framework/Libraries", - ] - - cflags += ["-DGL_SILENCE_DEPRECATION"] - cxxflags += ["-DGL_SILENCE_DEPRECATION"] - cpppath += [ - f"{brew_prefix}/include", - f"{brew_prefix}/opt/openssl@3.0/include", - ] - lenv["DYLD_LIBRARY_PATH"] = lenv["LD_LIBRARY_PATH"] - # Linux - else: - libpath = [ - f"#third_party/acados/{arch}/lib", - f"#third_party/libyuv/{arch}/lib", - "/usr/lib", - "/usr/local/lib", - ] - - if arch == "x86_64": - libpath += [ - f"#third_party/snpe/{arch}" - ] - rpath += [ - Dir(f"#third_party/snpe/{arch}").abspath, - ] - -if GetOption('asan'): - ccflags = ["-fsanitize=address", "-fno-omit-frame-pointer"] - ldflags = ["-fsanitize=address"] -elif GetOption('ubsan'): - ccflags = ["-fsanitize=undefined"] - ldflags = ["-fsanitize=undefined"] -else: - ccflags = [] - ldflags = [] - -# no --as-needed on mac linker -if arch != "Darwin": - ldflags += ["-Wl,--as-needed", "-Wl,--no-undefined"] - -if not GetOption('stock_ui'): - cflags += ["-DSUNNYPILOT"] - cxxflags += ["-DSUNNYPILOT"] - -ccflags_option = GetOption('ccflags') -if ccflags_option: - ccflags += ccflags_option.split(' ') +def _libflags(target, source, env, for_signature): + libs = [] + lp = env.subst('$LIBLITERALPREFIX') + for lib in env.Flatten(env.get('LIBS', [])): + if isinstance(lib, str): + if os.sep in lib or lib.startswith('#'): + libs.append(File(lib)) + elif lib.startswith('-') or (lp and lib.startswith(lp)): + libs.append(lib) + else: + libs.append(_resolve_lib(env, lib)) + else: + libs.append(lib) + return _stripixes(env['LIBLINKPREFIX'], libs, env['LIBLINKSUFFIX'], + env['LIBPREFIXES'], env['LIBSUFFIXES'], env, env['LIBLITERALPREFIX']) env = Environment( - ENV=lenv, + ENV={ + "PATH": os.environ['PATH'], + "PYTHONPATH": os.pathsep.join(submodule_python_paths), + "ACADOS_SOURCE_DIR": acados.DIR, + "ACADOS_PYTHON_INTERFACE_PATH": acados.TEMPLATE_DIR, + "TERA_PATH": acados.TERA_PATH + }, CCFLAGS=[ "-g", "-fPIC", "-O2", "-Wunused", "-Werror", - "-Wshadow", + "-Wshadow" if arch in ("Darwin", "larch64") else "-Wshadow=local", "-Wno-unknown-warning-option", "-Wno-inconsistent-missing-override", "-Wno-c99-designator", "-Wno-reorder-init-list", "-Wno-vla-cxx-extension", - ] + cflags + ccflags, - - CPPPATH=cpppath + [ + ], + CFLAGS=["-std=gnu11"], + CXXFLAGS=["-std=c++1z"], + CPPPATH=[ + "#openpilot", + "#msgq_repo", # #include "msgq/..." + "#opendbc_repo", # #include "opendbc/..." + "#rednose_repo", # #include "rednose/..." + "#rednose_repo/rednose", # #include "logger/..." (rednose package root) + "#openpilot/cereal/gen/cpp", + acados_include_dirs, + [x.INCLUDE_DIR for x in pkgs], "#", - "#third_party/acados/include", - "#third_party/acados/include/blasfeo/include", - "#third_party/acados/include/hpipm/include", - "#third_party/catch2/include", - "#third_party/libyuv/include", - "#third_party/json11", - "#third_party/linux/include", - "#third_party/snpe/include", - "#third_party", - "#msgq", ], - - CC='clang', - CXX='clang++', - LINKFLAGS=ldflags, - - RPATH=rpath, - - CFLAGS=["-std=gnu11"] + cflags, - CXXFLAGS=["-std=c++1z"] + cxxflags, - LIBPATH=libpath + [ + LIBPATH=[ + "#openpilot/common", "#msgq_repo", - "#third_party", - "#selfdrive/pandad", - "#common", - "#rednose/helpers", + "#openpilot/selfdrive/pandad", + "#rednose_repo/rednose/helpers", + [x.LIB_DIR for x in pkgs], ], + RPATH=[ffmpeg.LIB_DIR] if ffmpeg_shared else [], CYTHONCFILESUFFIX=".cpp", COMPILATIONDB_USE_ABSPATH=True, - REDNOSE_ROOT="#", + REDNOSE_ROOT="#rednose_repo", tools=["default", "cython", "compilation_db", "rednose_filter"], toolpath=["#site_scons/site_tools", "#rednose_repo/site_scons/site_tools"], ) - +# SCons' Darwin linker tool doesn't define the variables used to expand RPATH. if arch == "Darwin": - # RPATH is not supported on macOS, instead use the linker flags - darwin_rpath_link_flags = [f"-Wl,-rpath,{path}" for path in env["RPATH"]] - env["LINKFLAGS"] += darwin_rpath_link_flags + env["RPATHPREFIX"] = "-Wl,-rpath," + env["RPATHSUFFIX"] = "" + env["_RPATH"] = "${_concat(RPATHPREFIX, RPATH, RPATHSUFFIX, __env__)}" +if arch != "larch64": + env['_LIBFLAGS'] = _libflags -if GetOption('compile_db'): - env.CompilationDatabase('compile_commands.json') +# Arch-specific flags and paths +if arch == "larch64": + env["CC"] = "clang" + env["CXX"] = "clang++" + env.Append(LIBPATH=[ + "/usr/lib/aarch64-linux-gnu", + ]) + arch_flags = ["-D__TICI__", "-mcpu=cortex-a57", "-DQCOM2"] + env.Append(CCFLAGS=arch_flags) + env.Append(CXXFLAGS=arch_flags) +elif arch == "Darwin": + env.Append(LIBPATH=[ + "/System/Library/Frameworks/OpenGL.framework/Libraries", + ]) + env.Append(CCFLAGS=["-DGL_SILENCE_DEPRECATION"]) + env.Append(CXXFLAGS=["-DGL_SILENCE_DEPRECATION"]) -# Setup cache dir -default_cache_dir = '/data/scons_cache' if AGNOS else '/tmp/scons_cache' -cache_dir = ARGUMENTS.get('cache_dir', default_cache_dir) -CacheDir(cache_dir) -Clean(["."], cache_dir) +_extra_cc = shlex.split(GetOption('ccflags') or '') +if _extra_cc: + env.Append(CCFLAGS=_extra_cc) -node_interval = 5 -node_count = 0 -def progress_function(node): - global node_count - node_count += node_interval - sys.stderr.write("progress: %d\n" % node_count) +# no --as-needed on mac linker +if arch != "Darwin": + env.Append(LINKFLAGS=["-Wl,--as-needed", "-Wl,--no-undefined"]) -if os.environ.get('SCONS_PROGRESS'): - Progress(progress_function, interval=node_interval) +# Shorter build output: show brief descriptions instead of full commands. +# Full command lines are still printed on failure by scons. +if not GetOption('verbose'): + for action, short in ( + ("CC", "CC"), + ("CXX", "CXX"), + ("LINK", "LINK"), + ("SHCC", "CC"), + ("SHCXX", "CXX"), + ("SHLINK", "LINK"), + ("AR", "AR"), + ("RANLIB", "RANLIB"), + ("AS", "AS"), + ): + env[f"{action}COMSTR"] = f" [{short}] $TARGET" -# Cython build environment -py_include = sysconfig.get_paths()['include'] +# ********** Cython build environment ********** envCython = env.Clone() -envCython["CPPPATH"] += [py_include, np.get_include()] -envCython["CCFLAGS"] += ["-Wno-#warnings", "-Wno-shadow", "-Wno-deprecated-declarations"] +envCython["CPPPATH"] += [sysconfig.get_paths()['include'], np.get_include()] +envCython["CCFLAGS"] += ["-Wno-#warnings", "-Wno-cpp", "-Wno-shadow", "-Wno-deprecated-declarations"] envCython["CCFLAGS"].remove("-Werror") envCython["LIBS"] = [] if arch == "Darwin": - envCython["LINKFLAGS"] = ["-bundle", "-undefined", "dynamic_lookup"] + darwin_rpath_link_flags + envCython["LINKFLAGS"] = env["LINKFLAGS"] + ["-bundle", "-undefined", "dynamic_lookup"] else: envCython["LINKFLAGS"] = ["-pthread", "-shared"] np_version = SCons.Script.Value(np.__version__) Export('envCython', 'np_version') -# Qt build environment -qt_env = env.Clone() -qt_modules = ["Widgets", "Gui", "Core", "Network", "Concurrent", "DBus", "Xml"] +Export('env', 'arch', 'acados', 'release', 'ffmpeg_libs') -qt_libs = [] -if arch == "Darwin": - qt_env['QTDIR'] = f"{brew_prefix}/opt/qt@5" - qt_dirs = [ - os.path.join(qt_env['QTDIR'], "include"), - ] - qt_dirs += [f"{qt_env['QTDIR']}/include/Qt{m}" for m in qt_modules] - qt_env["LINKFLAGS"] += ["-F" + os.path.join(qt_env['QTDIR'], "lib")] - qt_env["FRAMEWORKS"] += [f"Qt{m}" for m in qt_modules] + ["OpenGL"] - qt_env.AppendENVPath('PATH', os.path.join(qt_env['QTDIR'], "bin")) -else: - qt_install_prefix = subprocess.check_output(['qmake', '-query', 'QT_INSTALL_PREFIX'], encoding='utf8').strip() - qt_install_headers = subprocess.check_output(['qmake', '-query', 'QT_INSTALL_HEADERS'], encoding='utf8').strip() +# Setup cache dir +default_cache_dir = '/data/scons_cache' if arch == "larch64" else '/tmp/scons_cache' +cache_dir = ARGUMENTS.get('cache_dir', default_cache_dir) +cache_size_limit = 4e9 if "CI" in os.environ else 2e9 +CacheDir(cache_dir) +Clean(["."], cache_dir) - qt_env['QTDIR'] = qt_install_prefix - qt_dirs = [ - f"{qt_install_headers}", - ] +def prune_cache_dir(target=None, source=None, env=None): + cache_files = sorted((os.path.join(root, f) for root, _, files in os.walk(cache_dir) for f in files), key=os.path.getmtime) + cache_size = sum(os.path.getsize(f) for f in cache_files) + for f in cache_files: + if cache_size < cache_size_limit: + break + cache_size -= os.path.getsize(f) + os.unlink(f) - qt_gui_path = os.path.join(qt_install_headers, "QtGui") - qt_gui_dirs = [d for d in os.listdir(qt_gui_path) if os.path.isdir(os.path.join(qt_gui_path, d))] - qt_dirs += [f"{qt_install_headers}/QtGui/{qt_gui_dirs[0]}/QtGui", ] if qt_gui_dirs else [] - qt_dirs += [f"{qt_install_headers}/Qt{m}" for m in qt_modules] - - qt_libs = [f"Qt5{m}" for m in qt_modules] - if arch == "larch64": - qt_libs += ["GLESv2", "wayland-client"] - qt_env.PrependENVPath('PATH', Dir("#third_party/qt5/larch64/bin/").abspath) - elif arch != "Darwin": - qt_libs += ["GL"] -qt_env['QT3DIR'] = qt_env['QTDIR'] -qt_env.Tool('qt3') - -qt_env['CPPPATH'] += qt_dirs + ["#third_party/qrcode"] -qt_flags = [ - "-D_REENTRANT", - "-DQT_NO_DEBUG", - "-DQT_WIDGETS_LIB", - "-DQT_GUI_LIB", - "-DQT_CORE_LIB", - "-DQT_MESSAGELOGCONTEXT", -] -qt_env['CXXFLAGS'] += qt_flags -qt_env['LIBPATH'] += ['#selfdrive/ui', ] -qt_env['LIBS'] = qt_libs - -if GetOption("clazy"): - checks = [ - "level0", - "level1", - "no-range-loop", - "no-non-pod-global-static", - ] - qt_env['CXX'] = 'clazy' - qt_env['ENV']['CLAZY_IGNORE_DIRS'] = qt_dirs[0] - qt_env['ENV']['CLAZY_CHECKS'] = ','.join(checks) - -Export('env', 'qt_env', 'arch', 'real_arch') +# ********** start building stuff ********** # Build common module -SConscript(['common/SConscript']) -Import('_common', '_gpucommon') - +SConscript(['openpilot/common/SConscript']) +Import('_common') common = [_common, 'json11', 'zmq'] -gpucommon = [_gpucommon] - -Export('common', 'gpucommon') +Export('common') # Build messaging (cereal + msgq + socketmaster + their dependencies) # Enable swaglog include in submodules env_swaglog = env.Clone() env_swaglog['CXXFLAGS'].append('-DSWAGLOG="\\"common/swaglog.h\\""') SConscript(['msgq_repo/SConscript'], exports={'env': env_swaglog}) -SConscript(['opendbc_repo/SConscript'], exports={'env': env_swaglog}) -SConscript(['cereal/SConscript']) +SConscript(['openpilot/cereal/SConscript']) Import('socketmaster', 'msgq') messaging = [socketmaster, msgq, 'capnp', 'kj',] @@ -359,34 +273,79 @@ Export('messaging') SConscript(['panda/SConscript']) # Build rednose library -SConscript(['rednose/SConscript']) +SConscript(['rednose_repo/rednose/SConscript']) # Build system services SConscript([ - 'system/ubloxd/SConscript', - 'system/loggerd/SConscript', + 'openpilot/system/loggerd/SConscript', ]) -if arch != "Darwin": - SConscript([ - 'system/logcatd/SConscript', - 'system/proclogd/SConscript', - ]) if arch == "larch64": - SConscript(['system/camerad/SConscript']) + SConscript(['openpilot/system/camerad/SConscript']) -# Build openpilot -SConscript(['third_party/SConscript']) +# Build selfdrive +SConscript([ + 'openpilot/selfdrive/pandad/SConscript', + 'openpilot/selfdrive/controls/lib/longitudinal_mpc_lib/SConscript', + 'openpilot/selfdrive/locationd/SConscript', + 'openpilot/selfdrive/modeld/SConscript', + 'openpilot/selfdrive/ui/SConscript', +]) -SConscript(['selfdrive/SConscript']) +SConscript(['openpilot/sunnypilot/SConscript']) -SConscript(['sunnypilot/SConscript']) +# Build desktop-only tools +if GetOption('extras') and arch != "larch64": + SConscript([ + 'openpilot/tools/replay/SConscript', + 'openpilot/tools/cabana/SConscript', + 'openpilot/tools/jotpluggler/SConscript', + ]) -if Dir('#tools/cabana/').exists() and GetOption('extras'): - SConscript(['tools/replay/SConscript']) - if arch != "larch64": - SConscript(['tools/cabana/SConscript']) -external_sconscript = GetOption('external_sconscript') -if external_sconscript: - SConscript([external_sconscript]) +env.CompilationDatabase('compile_commands.json') + +# progress output +def count_scons_nodes(nodes): + seen = set() + stack = list(nodes) + + while stack: + node = stack.pop().disambiguate() + if node in seen: + continue + seen.add(node) + if hasattr(node, 'has_builder') and node.has_builder(): + build_product_nodes.add(node) + executor = node.get_executor() + if executor is not None: + stack += executor.get_all_prerequisites() + executor.get_all_children() + + return len(seen) + +progress_interval = 5 +progress_count = 0 +build_product_nodes = set() +progress_total = max(1, count_scons_nodes(env.arg2nodes(BUILD_TARGETS or [Dir('.')], env.fs.Entry))) + +def progress_function(node): + global progress_count + if progress_count >= progress_total: + return + progress_count = min(progress_count + progress_interval, progress_total) + progress = round(100. * progress_count / progress_total, 1) + sys.stderr.write("\rBuilding: %5.1f%%" % progress if sys.stderr.isatty() else "progress: %.1f\n" % progress) + if progress == 100. and sys.stderr.isatty(): + sys.stderr.write("\n") + sys.stderr.flush() + +Progress(progress_function, interval=progress_interval) +AddPostAction(BUILD_TARGETS or [Dir('.')], prune_cache_dir) + +def check_build_product_size(target, source, env): + limit = 50 * 1024 * 1024 # GitHub max size + for t in target: + if hasattr(t, 'isfile') and t.isfile() and (size := os.path.getsize(t.abspath)) > limit: + raise SCons.Errors.UserError(f"{t} is {size / (1024 * 1024):.1f} MiB, exceeding the {limit / (1024 * 1024):.1f} MiB limit") +if not GetOption('extras'): + AddPostAction(list(build_product_nodes), Action(check_build_product_size, None)) diff --git a/cereal/README.md b/cereal/README.md deleted file mode 100644 index 45e859c09c..0000000000 --- a/cereal/README.md +++ /dev/null @@ -1,95 +0,0 @@ -# What is cereal? - -cereal is the messaging system for openpilot. It uses [msgq](https://github.com/commaai/msgq) as a pub/sub backend, and [Cap'n proto](https://capnproto.org/capnp-tool.html) for serialization of the structs. - - -## Messaging Spec - -You'll find the message types in [log.capnp](log.capnp). It uses [Cap'n proto](https://capnproto.org/capnp-tool.html) and defines one struct called `Event`. - -All `Events` have a `logMonoTime` and a `valid`. Then a big union defines the packet type. - -### Best Practices - -- **All fields must describe quantities in SI units**, unless otherwise specified in the field name. -- In the context of the message they are in, field names should be completely unambiguous. -- All values should be easy to plot and be human-readable with minimal parsing. - -### Maintaining backwards-compatibility - -When making changes to the messaging spec you want to maintain backwards-compatibility, such that old logs can -be parsed with a new version of cereal. Adding structs and adding members to structs is generally safe, most other -things are not. Read more details [here](https://capnproto.org/language.html). - -### Custom forks - -Forks of [openpilot](https://github.com/commaai/openpilot) might want to add things to the messaging -spec, however this could conflict with future changes made in mainline cereal/openpilot. Rebasing against mainline openpilot -then means breaking backwards-compatibility with all old logs of your fork. So we added reserved events in -[custom.capnp](custom.capnp) that we will leave empty in mainline cereal/openpilot. **If you only modify those, you can ensure your -fork will remain backwards-compatible with all versions of mainline openpilot and your fork.** - -An example of compatible changes: -```diff -diff --git a/cereal/custom.capnp b/cereal/custom.capnp -index 3348e859e..3365c7b98 100644 ---- a/cereal/custom.capnp -+++ b/cereal/custom.capnp -@@ -10,7 +10,11 @@ $Cxx.namespace("cereal"); - # DO rename the structs - # DON'T change the identifier (e.g. @0x81c2f05a394cf4af) - --struct CustomReserved0 @0x81c2f05a394cf4af { -+struct SteeringInfo @0x81c2f05a394cf4af { -+ active @0 :Bool; -+ steeringAngleDeg @1 :Float32; -+ steeringRateDeg @2 :Float32; -+ steeringAccelDeg @3 :Float32; - } - - struct CustomReserved1 @0xaedffd8f31e7b55d { -diff --git a/cereal/log.capnp b/cereal/log.capnp -index 1209f3fd9..b189f58b6 100644 ---- a/cereal/log.capnp -+++ b/cereal/log.capnp -@@ -2558,14 +2558,14 @@ struct Event { - - # DO change the name of the field - # DON'T change anything after the "@" -- customReservedRawData0 @124 :Data; -+ rawCanData @124 :Data; - customReservedRawData1 @125 :Data; - customReservedRawData2 @126 :Data; - - # DO change the name of the field and struct - # DON'T change the ID (e.g. @107) - # DON'T change which struct it points to -- customReserved0 @107 :Custom.CustomReserved0; -+ steeringInfo @107 :Custom.SteeringInfo; - customReserved1 @108 :Custom.CustomReserved1; - customReserved2 @109 :Custom.CustomReserved2; - customReserved3 @110 :Custom.CustomReserved3; -``` - ---- - -Example ---- -```python -import cereal.messaging as messaging - -# in subscriber -sm = messaging.SubMaster(['sensorEvents']) -while 1: - sm.update() - print(sm['sensorEvents']) - -``` - -```python -# in publisher -pm = messaging.PubMaster(['sensorEvents']) -dat = messaging.new_message('sensorEvents', size=1) -dat.sensorEvents[0] = {"gyro": {"v": [0.1, -0.1, 0.1]}} -pm.send('sensorEvents', dat) -``` diff --git a/cereal/SConscript b/cereal/SConscript deleted file mode 100644 index a58a9490ce..0000000000 --- a/cereal/SConscript +++ /dev/null @@ -1,20 +0,0 @@ -Import('env', 'common', 'msgq') - -cereal_dir = Dir('.') -gen_dir = Dir('gen') - -# Build cereal -schema_files = ['log.capnp', 'car.capnp', 'legacy.capnp', 'custom.capnp'] -env.Command([f'gen/cpp/{s}.c++' for s in schema_files] + [f'gen/cpp/{s}.h' for s in schema_files], - schema_files, - f"capnpc --src-prefix={cereal_dir.path} $SOURCES -o c++:{gen_dir.path}/cpp/") - -cereal = env.Library('cereal', [f'gen/cpp/{s}.c++' for s in schema_files]) - -# Build messaging -services_h = env.Command(['services.h'], ['services.py'], 'python3 ' + cereal_dir.path + '/services.py > $TARGET') -env.Program('messaging/bridge', ['messaging/bridge.cc', 'messaging/msgq_to_zmq.cc'], LIBS=[msgq, common, 'pthread']) - -socketmaster = env.Library('socketmaster', ['messaging/socketmaster.cc']) - -Export('cereal', 'socketmaster') diff --git a/cereal/__init__.py b/cereal/__init__.py deleted file mode 100644 index 93f4d77227..0000000000 --- a/cereal/__init__.py +++ /dev/null @@ -1,11 +0,0 @@ -import os -import capnp -from importlib.resources import as_file, files - -capnp.remove_import_hook() - -with as_file(files("cereal")) as fspath: - CEREAL_PATH = fspath.as_posix() - log = capnp.load(os.path.join(CEREAL_PATH, "log.capnp")) - car = capnp.load(os.path.join(CEREAL_PATH, "car.capnp")) - custom = capnp.load(os.path.join(CEREAL_PATH, "custom.capnp")) diff --git a/cereal/car.capnp b/cereal/car.capnp deleted file mode 120000 index 4bc7f89b1f..0000000000 --- a/cereal/car.capnp +++ /dev/null @@ -1 +0,0 @@ -../opendbc_repo/opendbc/car/car.capnp \ No newline at end of file diff --git a/cereal/custom.capnp b/cereal/custom.capnp deleted file mode 100644 index c9e4f3e16d..0000000000 --- a/cereal/custom.capnp +++ /dev/null @@ -1,269 +0,0 @@ -using Cxx = import "./include/c++.capnp"; -$Cxx.namespace("cereal"); - -@0xb526ba661d550a59; - -# custom.capnp: a home for empty structs reserved for custom forks -# These structs are guaranteed to remain reserved and empty in mainline -# cereal, so use these if you want custom events in your fork. - -# DO rename the structs -# DON'T change the identifier (e.g. @0x81c2f05a394cf4af) - -struct ModularAssistiveDrivingSystem { - state @0 :ModularAssistiveDrivingSystemState; - enabled @1 :Bool; - active @2 :Bool; - available @3 :Bool; - - enum ModularAssistiveDrivingSystemState { - disabled @0; - paused @1; - enabled @2; - softDisabling @3; - overriding @4; - } -} - -struct SelfdriveStateSP @0x81c2f05a394cf4af { - mads @0 :ModularAssistiveDrivingSystem; -} - -struct ModelManagerSP @0xaedffd8f31e7b55d { - activeBundle @0 :ModelBundle; - selectedBundle @1 :ModelBundle; - availableBundles @2 :List(ModelBundle); - - struct DownloadUri { - uri @0 :Text; - sha256 @1 :Text; - } - - enum DownloadStatus { - notDownloading @0; - downloading @1; - downloaded @2; - cached @3; - failed @4; - } - - struct DownloadProgress { - status @0 :DownloadStatus; - progress @1 :Float32; - eta @2 :UInt32; - } - - struct Artifact { - fileName @0 :Text; - downloadUri @1 :DownloadUri; - downloadProgress @2 :DownloadProgress; - } - - struct Model { - type @0 :Type; - artifact @1 :Artifact; # Main artifact - metadata @2 :Artifact; # Metadata artifact - - enum Type { - supercombo @0; - navigation @1; - vision @2; - policy @3; - } - } - - enum Runner { - snpe @0; - tinygrad @1; - stock @2; - } - - struct Override { - key @0 :Text; - value @1 :Text; - } - - struct ModelBundle { - index @0 :UInt32; - internalName @1 :Text; - displayName @2 :Text; - models @3 :List(Model); - status @4 :DownloadStatus; - generation @5 :UInt32; - environment @6 :Text; - runner @7 :Runner; - is20hz @8 :Bool; - ref @9 :Text; - minimumSelectorVersion @10 :UInt32; - overrides @11 :List(Override); - } -} - -struct LongitudinalPlanSP @0xf35cc4560bbf6ec2 { - dec @0 :DynamicExperimentalControl; - - struct DynamicExperimentalControl { - state @0 :DynamicExperimentalControlState; - enabled @1 :Bool; - active @2 :Bool; - - enum DynamicExperimentalControlState { - acc @0; - blended @1; - } - } -} - -struct OnroadEventSP @0xda96579883444c35 { - events @0 :List(Event); - - struct Event { - name @0 :EventName; - - # event types - enable @1 :Bool; - noEntry @2 :Bool; - warning @3 :Bool; # alerts presented only when enabled or soft disabling - userDisable @4 :Bool; - softDisable @5 :Bool; - immediateDisable @6 :Bool; - preEnable @7 :Bool; - permanent @8 :Bool; # alerts presented regardless of openpilot state - overrideLateral @10 :Bool; - overrideLongitudinal @9 :Bool; - } - - enum EventName { - lkasEnable @0; - lkasDisable @1; - manualSteeringRequired @2; - manualLongitudinalRequired @3; - silentLkasEnable @4; - silentLkasDisable @5; - silentBrakeHold @6; - silentWrongGear @7; - silentReverseGear @8; - silentDoorOpen @9; - silentSeatbeltNotLatched @10; - silentParkBrake @11; - controlsMismatchLateral @12; - hyundaiRadarTracksConfirmed @13; - experimentalModeSwitched @14; - wrongCarModeAlertOnly @15; - pedalPressedAlertOnly @16; - } -} - -struct CarParamsSP @0x80ae746ee2596b11 { - flags @0 :UInt32; # flags for car specific quirks in sunnypilot - safetyParam @1 : Int16; # flags for sunnypilot's custom safety flags - - neuralNetworkLateralControl @2 :NeuralNetworkLateralControl; - - struct NeuralNetworkLateralControl { - model @0 :Model; - fuzzyFingerprint @1 :Bool; - - struct Model { - path @0 :Text; - name @1 :Text; - } - } -} - -struct CarControlSP @0xa5cd762cd951a455 { - mads @0 :ModularAssistiveDrivingSystem; - params @1 :List(Param); - - struct Param { - key @0 :Text; - value @1 :Text; - } -} - -struct BackupManagerSP @0xf98d843bfd7004a3 { - backupStatus @0 :Status; - restoreStatus @1 :Status; - backupProgress @2 :Float32; - restoreProgress @3 :Float32; - lastError @4 :Text; - currentBackup @5 :BackupInfo; - backupHistory @6 :List(BackupInfo); - - enum Status { - idle @0; - inProgress @1; - completed @2; - failed @3; - } - - struct Version { - major @0 :UInt16; - minor @1 :UInt16; - patch @2 :UInt16; - build @3 :UInt16; - branch @4 :Text; - } - - struct MetadataEntry { - key @0 :Text; - value @1 :Text; - tags @2 :List(Text); - } - - struct BackupInfo { - deviceId @0 :Text; - version @1 :UInt32; - config @2 :Text; - isEncrypted @3 :Bool; - createdAt @4 :Text; # ISO timestamp - updatedAt @5 :Text; # ISO timestamp - sunnypilotVersion @6 :Version; - backupMetadata @7 :List(MetadataEntry); - } -} - -struct CarStateSP @0xb86e6369214c01c8 { -} - -struct LiveMapDataSP @0xf416ec09499d9d19 { - speedLimitValid @0 :Bool; - speedLimit @1 :Float32; - speedLimitAheadValid @2 :Bool; - speedLimitAhead @3 :Float32; - speedLimitAheadDistance @4 :Float32; - roadName @5 :Text; -} - -struct CustomReserved9 @0xa1680744031fdb2d { -} - -struct CustomReserved10 @0xcb9fd56c7057593a { -} - -struct CustomReserved11 @0xc2243c65e0340384 { -} - -struct CustomReserved12 @0x9ccdc8676701b412 { -} - -struct CustomReserved13 @0xcd96dafb67a082d0 { -} - -struct CustomReserved14 @0xb057204d7deadf3f { -} - -struct CustomReserved15 @0xbd443b539493bc68 { -} - -struct CustomReserved16 @0xfc6241ed8877b611 { -} - -struct CustomReserved17 @0xa30662f84033036c { -} - -struct CustomReserved18 @0xc86a3d38d13eb3ef { -} - -struct CustomReserved19 @0xa4f1eb3323f5f582 { -} diff --git a/cereal/legacy.capnp b/cereal/legacy.capnp deleted file mode 100644 index a8fa5e4a1f..0000000000 --- a/cereal/legacy.capnp +++ /dev/null @@ -1,574 +0,0 @@ -using Cxx = import "./include/c++.capnp"; -$Cxx.namespace("cereal"); - -@0x80ef1ec4889c2a63; - -# legacy.capnp: a home for deprecated structs - -struct LogRotate @0x9811e1f38f62f2d1 { - segmentNum @0 :Int32; - path @1 :Text; -} - -struct LiveUI @0xc08240f996aefced { - rearViewCam @0 :Bool; - alertText1 @1 :Text; - alertText2 @2 :Text; - awarenessStatus @3 :Float32; -} - -struct UiLayoutState @0x88dcce08ad29dda0 { - activeApp @0 :App; - sidebarCollapsed @1 :Bool; - mapEnabled @2 :Bool; - mockEngaged @3 :Bool; - - enum App @0x9917470acf94d285 { - home @0; - music @1; - nav @2; - settings @3; - none @4; - } -} - -struct OrbslamCorrection @0x8afd33dc9b35e1aa { - correctionMonoTime @0 :UInt64; - prePositionECEF @1 :List(Float64); - postPositionECEF @2 :List(Float64); - prePoseQuatECEF @3 :List(Float32); - postPoseQuatECEF @4 :List(Float32); - numInliers @5 :UInt32; -} - -struct EthernetPacket @0xa99a9d5b33cf5859 { - pkt @0 :Data; - ts @1 :Float32; -} - -struct CellInfo @0xcff7566681c277ce { - timestamp @0 :UInt64; - repr @1 :Text; # android toString() for now -} - -struct WifiScan @0xd4df5a192382ba0b { - bssid @0 :Text; - ssid @1 :Text; - capabilities @2 :Text; - frequency @3 :Int32; - level @4 :Int32; - timestamp @5 :Int64; - - centerFreq0 @6 :Int32; - centerFreq1 @7 :Int32; - channelWidth @8 :ChannelWidth; - operatorFriendlyName @9 :Text; - venueName @10 :Text; - is80211mcResponder @11 :Bool; - passpoint @12 :Bool; - - distanceCm @13 :Int32; - distanceSdCm @14 :Int32; - - enum ChannelWidth @0xcb6a279f015f6b51 { - w20Mhz @0; - w40Mhz @1; - w80Mhz @2; - w160Mhz @3; - w80Plus80Mhz @4; - } -} - -struct LiveEventData @0x94b7baa90c5c321e { - name @0 :Text; - value @1 :Int32; -} - -struct ModelData @0xb8aad62cffef28a9 { - frameId @0 :UInt32; - frameAge @12 :UInt32; - frameDropPerc @13 :Float32; - timestampEof @9 :UInt64; - modelExecutionTime @14 :Float32; - gpuExecutionTime @16 :Float32; - rawPred @15 :Data; - - path @1 :PathData; - leftLane @2 :PathData; - rightLane @3 :PathData; - lead @4 :LeadData; - freePath @6 :List(Float32); - - settings @5 :ModelSettings; - leadFuture @7 :LeadData; - speed @8 :List(Float32); - meta @10 :MetaData; - longitudinal @11 :LongitudinalData; - - struct PathData @0x8817eeea389e9f08 { - points @0 :List(Float32); - prob @1 :Float32; - std @2 :Float32; - stds @3 :List(Float32); - poly @4 :List(Float32); - validLen @5 :Float32; - } - - struct LeadData @0xd1c9bef96d26fa91 { - dist @0 :Float32; - prob @1 :Float32; - std @2 :Float32; - relVel @3 :Float32; - relVelStd @4 :Float32; - relY @5 :Float32; - relYStd @6 :Float32; - relA @7 :Float32; - relAStd @8 :Float32; - } - - struct ModelSettings @0xa26e3710efd3e914 { - bigBoxX @0 :UInt16; - bigBoxY @1 :UInt16; - bigBoxWidth @2 :UInt16; - bigBoxHeight @3 :UInt16; - boxProjection @4 :List(Float32); - yuvCorrection @5 :List(Float32); - inputTransform @6 :List(Float32); - } - - struct MetaData @0x9744f25fb60f2bf8 { - engagedProb @0 :Float32; - desirePrediction @1 :List(Float32); - brakeDisengageProb @2 :Float32; - gasDisengageProb @3 :Float32; - steerOverrideProb @4 :Float32; - desireState @5 :List(Float32); - } - - struct LongitudinalData @0xf98f999c6a071122 { - distances @2 :List(Float32); - speeds @0 :List(Float32); - accelerations @1 :List(Float32); - } -} - -struct ECEFPoint @0xc25bbbd524983447 { - x @0 :Float64; - y @1 :Float64; - z @2 :Float64; -} - -struct ECEFPointDEPRECATED @0xe10e21168db0c7f7 { - x @0 :Float32; - y @1 :Float32; - z @2 :Float32; -} - -struct GPSPlannerPoints @0xab54c59699f8f9f3 { - curPosDEPRECATED @0 :ECEFPointDEPRECATED; - pointsDEPRECATED @1 :List(ECEFPointDEPRECATED); - curPos @6 :ECEFPoint; - points @7 :List(ECEFPoint); - valid @2 :Bool; - trackName @3 :Text; - speedLimit @4 :Float32; - accelTarget @5 :Float32; -} - -struct GPSPlannerPlan @0xf5ad1d90cdc1dd6b { - valid @0 :Bool; - poly @1 :List(Float32); - trackName @2 :Text; - speed @3 :Float32; - acceleration @4 :Float32; - pointsDEPRECATED @5 :List(ECEFPointDEPRECATED); - points @6 :List(ECEFPoint); - xLookahead @7 :Float32; -} - -struct UiNavigationEvent @0x90c8426c3eaddd3b { - type @0: Type; - status @1: Status; - distanceTo @2: Float32; - endRoadPointDEPRECATED @3: ECEFPointDEPRECATED; - endRoadPoint @4: ECEFPoint; - - enum Type @0xe8db07dcf8fcea05 { - none @0; - laneChangeLeft @1; - laneChangeRight @2; - mergeLeft @3; - mergeRight @4; - turnLeft @5; - turnRight @6; - } - - enum Status @0xb9aa88c75ef99a1f { - none @0; - passive @1; - approaching @2; - active @3; - } -} - -struct LiveLocationData @0xb99b2bc7a57e8128 { - status @0 :UInt8; - - # 3D fix - lat @1 :Float64; - lon @2 :Float64; - alt @3 :Float32; # m - - # speed - speed @4 :Float32; # m/s - - # NED velocity components - vNED @5 :List(Float32); - - # roll, pitch, heading (x,y,z) - roll @6 :Float32; # WRT to center of earth? - pitch @7 :Float32; # WRT to center of earth? - heading @8 :Float32; # WRT to north? - - # what are these? - wanderAngle @9 :Float32; - trackAngle @10 :Float32; - - # car frame -- https://upload.wikimedia.org/wikipedia/commons/f/f5/RPY_angles_of_cars.png - - # gyro, in car frame, deg/s - gyro @11 :List(Float32); - - # accel, in car frame, m/s^2 - accel @12 :List(Float32); - - accuracy @13 :Accuracy; - - source @14 :SensorSource; - # if we are fixing a location in the past - fixMonoTime @15 :UInt64; - - gpsWeek @16 :Int32; - timeOfWeek @17 :Float64; - - positionECEF @18 :List(Float64); - poseQuatECEF @19 :List(Float32); - pitchCalibration @20 :Float32; - yawCalibration @21 :Float32; - imuFrame @22 :List(Float32); - - struct Accuracy @0x943dc4625473b03f { - pNEDError @0 :List(Float32); - vNEDError @1 :List(Float32); - rollError @2 :Float32; - pitchError @3 :Float32; - headingError @4 :Float32; - ellipsoidSemiMajorError @5 :Float32; - ellipsoidSemiMinorError @6 :Float32; - ellipsoidOrientationError @7 :Float32; - } - - enum SensorSource @0xc871d3cc252af657 { - applanix @0; - kalman @1; - orbslam @2; - timing @3; - dummy @4; - } -} - -struct OrbOdometry @0xd7700859ed1f5b76 { - # timing first - startMonoTime @0 :UInt64; - endMonoTime @1 :UInt64; - - # fundamental matrix and error - f @2: List(Float64); - err @3: Float64; - - # number of inlier points - inliers @4: Int32; - - # for debug only - # indexed by endMonoTime features - # value is startMonoTime feature match - # -1 if no match - matches @5: List(Int16); -} - -struct OrbFeatures @0xcd60164a8a0159ef { - timestampEof @0 :UInt64; - # transposed arrays of normalized image coordinates - # len(xs) == len(ys) == len(descriptors) * 32 - xs @1 :List(Float32); - ys @2 :List(Float32); - descriptors @3 :Data; - octaves @4 :List(Int8); - - # match index to last OrbFeatures - # -1 if no match - timestampLastEof @5 :UInt64; - matches @6: List(Int16); -} - -struct OrbFeaturesSummary @0xd500d30c5803fa4f { - timestampEof @0 :UInt64; - timestampLastEof @1 :UInt64; - - featureCount @2 :UInt16; - matchCount @3 :UInt16; - computeNs @4 :UInt64; -} - -struct OrbKeyFrame @0xc8233c0345e27e24 { - # this is a globally unique id for the KeyFrame - id @0: UInt64; - - # this is the location of the KeyFrame - pos @1: ECEFPoint; - - # these are the features in the world - # len(dpos) == len(descriptors) * 32 - dpos @2 :List(ECEFPoint); - descriptors @3 :Data; -} - -struct KalmanOdometry @0x92e21bb7ea38793a { - trans @0 :List(Float32); # m/s in device frame - rot @1 :List(Float32); # rad/s in device frame - transStd @2 :List(Float32); # std m/s in device frame - rotStd @3 :List(Float32); # std rad/s in device frame -} - -struct OrbObservation @0x9b326d4e436afec7 { - observationMonoTime @0 :UInt64; - normalizedCoordinates @1 :List(Float32); - locationECEF @2 :List(Float64); - matchDistance @3: UInt32; -} - -struct CalibrationFeatures @0x8fdfadb254ea867a { - frameId @0 :UInt32; - - p0 @1 :List(Float32); - p1 @2 :List(Float32); - status @3 :List(Int8); -} - -struct NavStatus @0xbd8822120928120c { - isNavigating @0 :Bool; - currentAddress @1 :Address; - - struct Address @0xce7cd672cacc7814 { - title @0 :Text; - lat @1 :Float64; - lng @2 :Float64; - house @3 :Text; - address @4 :Text; - street @5 :Text; - city @6 :Text; - state @7 :Text; - country @8 :Text; - } -} - -struct NavUpdate @0xdb98be6565516acb { - isNavigating @0 :Bool; - curSegment @1 :Int32; - segments @2 :List(Segment); - - struct LatLng @0x9eaef9187cadbb9b { - lat @0 :Float64; - lng @1 :Float64; - } - - struct Segment @0xa5b39b4fc4d7da3f { - from @0 :LatLng; - to @1 :LatLng; - updateTime @2 :Int32; - distance @3 :Int32; - crossTime @4 :Int32; - exitNo @5 :Int32; - instruction @6 :Instruction; - - parts @7 :List(LatLng); - - enum Instruction @0xc5417a637451246f { - turnLeft @0; - turnRight @1; - keepLeft @2; - keepRight @3; - straight @4; - roundaboutExitNumber @5; - roundaboutExit @6; - roundaboutTurnLeft @7; - unkn8 @8; - roundaboutStraight @9; - unkn10 @10; - roundaboutTurnRight @11; - unkn12 @12; - roundaboutUturn @13; - unkn14 @14; - arrive @15; - exitLeft @16; - exitRight @17; - unkn18 @18; - uturn @19; - # ... - } - } -} - -struct TrafficEvent @0xacfa74a094e62626 { - type @0 :Type; - distance @1 :Float32; - action @2 :Action; - resuming @3 :Bool; - - enum Type @0xd85d75253435bf4b { - stopSign @0; - lightRed @1; - lightYellow @2; - lightGreen @3; - stopLight @4; - } - - enum Action @0xa6f6ce72165ccb49 { - none @0; - yield @1; - stop @2; - resumeReady @3; - } - -} - - -struct AndroidGnss @0xdfdf30d03fc485bd { - union { - measurements @0 :Measurements; - navigationMessage @1 :NavigationMessage; - } - - struct Measurements @0xa20710d4f428d6cd { - clock @0 :Clock; - measurements @1 :List(Measurement); - - struct Clock @0xa0e27b453a38f450 { - timeNanos @0 :Int64; - hardwareClockDiscontinuityCount @1 :Int32; - - hasTimeUncertaintyNanos @2 :Bool; - timeUncertaintyNanos @3 :Float64; - - hasLeapSecond @4 :Bool; - leapSecond @5 :Int32; - - hasFullBiasNanos @6 :Bool; - fullBiasNanos @7 :Int64; - - hasBiasNanos @8 :Bool; - biasNanos @9 :Float64; - - hasBiasUncertaintyNanos @10 :Bool; - biasUncertaintyNanos @11 :Float64; - - hasDriftNanosPerSecond @12 :Bool; - driftNanosPerSecond @13 :Float64; - - hasDriftUncertaintyNanosPerSecond @14 :Bool; - driftUncertaintyNanosPerSecond @15 :Float64; - } - - struct Measurement @0xd949bf717d77614d { - svId @0 :Int32; - constellation @1 :Constellation; - - timeOffsetNanos @2 :Float64; - state @3 :Int32; - receivedSvTimeNanos @4 :Int64; - receivedSvTimeUncertaintyNanos @5 :Int64; - cn0DbHz @6 :Float64; - pseudorangeRateMetersPerSecond @7 :Float64; - pseudorangeRateUncertaintyMetersPerSecond @8 :Float64; - accumulatedDeltaRangeState @9 :Int32; - accumulatedDeltaRangeMeters @10 :Float64; - accumulatedDeltaRangeUncertaintyMeters @11 :Float64; - - hasCarrierFrequencyHz @12 :Bool; - carrierFrequencyHz @13 :Float32; - hasCarrierCycles @14 :Bool; - carrierCycles @15 :Int64; - hasCarrierPhase @16 :Bool; - carrierPhase @17 :Float64; - hasCarrierPhaseUncertainty @18 :Bool; - carrierPhaseUncertainty @19 :Float64; - hasSnrInDb @20 :Bool; - snrInDb @21 :Float64; - - multipathIndicator @22 :MultipathIndicator; - - enum Constellation @0x9ef1f3ff0deb5ffb { - unknown @0; - gps @1; - sbas @2; - glonass @3; - qzss @4; - beidou @5; - galileo @6; - } - - enum State @0xcbb9490adce12d72 { - unknown @0; - codeLock @1; - bitSync @2; - subframeSync @3; - towDecoded @4; - msecAmbiguous @5; - symbolSync @6; - gloStringSync @7; - gloTodDecoded @8; - bdsD2BitSync @9; - bdsD2SubframeSync @10; - galE1bcCodeLock @11; - galE1c2ndCodeLock @12; - galE1bPageSync @13; - sbasSync @14; - } - - enum MultipathIndicator @0xc04e7b6231d4caa8 { - unknown @0; - detected @1; - notDetected @2; - } - } - } - - struct NavigationMessage @0xe2517b083095fd4e { - type @0 :Int32; - svId @1 :Int32; - messageId @2 :Int32; - submessageId @3 :Int32; - data @4 :Data; - status @5 :Status; - - enum Status @0xec1ff7996b35366f { - unknown @0; - parityPassed @1; - parityRebuilt @2; - } - } -} - -struct LidarPts @0xe3d6685d4e9d8f7a { - r @0 :List(UInt16); # uint16 m*500.0 - theta @1 :List(UInt16); # uint16 deg*100.0 - reflect @2 :List(UInt8); # uint8 0-255 - - # For storing out of file. - idx @3 :UInt64; - - # For storing in file - pkt @4 :Data; -} - - diff --git a/cereal/messaging/__init__.py b/cereal/messaging/__init__.py deleted file mode 100644 index b03285f80a..0000000000 --- a/cereal/messaging/__init__.py +++ /dev/null @@ -1,257 +0,0 @@ -# must be built with scons -from msgq.ipc_pyx import Context, Poller, SubSocket, PubSocket, SocketEventHandle, toggle_fake_events, \ - set_fake_prefix, get_fake_prefix, delete_fake_prefix, wait_for_one_event -from msgq.ipc_pyx import MultiplePublishersError, IpcError -from msgq import fake_event_handle, pub_sock, sub_sock, drain_sock_raw -import msgq - -import os -import capnp -import time - -from typing import Optional, List, Union, Dict - -from cereal import log -from cereal.services import SERVICE_LIST -from openpilot.common.util import MovingAverage - -NO_TRAVERSAL_LIMIT = 2**64-1 - - -def reset_context(): - msgq.context = Context() - - -def log_from_bytes(dat: bytes, struct: capnp.lib.capnp._StructModule = log.Event) -> capnp.lib.capnp._DynamicStructReader: - with struct.from_bytes(dat, traversal_limit_in_words=NO_TRAVERSAL_LIMIT) as msg: - return msg - - -def new_message(service: Optional[str], size: Optional[int] = None, **kwargs) -> capnp.lib.capnp._DynamicStructBuilder: - args = { - 'valid': False, - 'logMonoTime': int(time.monotonic() * 1e9), - **kwargs - } - dat = log.Event.new_message(**args) - if service is not None: - if size is None: - dat.init(service) - else: - dat.init(service, size) - return dat - - -def drain_sock(sock: SubSocket, wait_for_one: bool = False) -> List[capnp.lib.capnp._DynamicStructReader]: - """Receive all message currently available on the queue""" - msgs = drain_sock_raw(sock, wait_for_one=wait_for_one) - return [log_from_bytes(m) for m in msgs] - - -# TODO: print when we drop packets? -def recv_sock(sock: SubSocket, wait: bool = False) -> Optional[capnp.lib.capnp._DynamicStructReader]: - """Same as drain sock, but only returns latest message. Consider using conflate instead.""" - dat = None - - while 1: - if wait and dat is None: - recv = sock.receive() - else: - recv = sock.receive(non_blocking=True) - - if recv is None: # Timeout hit - break - - dat = recv - - if dat is not None: - dat = log_from_bytes(dat) - - return dat - - -def recv_one(sock: SubSocket) -> Optional[capnp.lib.capnp._DynamicStructReader]: - dat = sock.receive() - if dat is not None: - dat = log_from_bytes(dat) - return dat - - -def recv_one_or_none(sock: SubSocket) -> Optional[capnp.lib.capnp._DynamicStructReader]: - dat = sock.receive(non_blocking=True) - if dat is not None: - dat = log_from_bytes(dat) - return dat - - -def recv_one_retry(sock: SubSocket) -> capnp.lib.capnp._DynamicStructReader: - """Keep receiving until we get a message""" - while True: - dat = sock.receive() - if dat is not None: - return log_from_bytes(dat) - - -class FrequencyTracker: - def __init__(self, service_freq: float, update_freq: float, is_poll: bool): - freq = max(min(service_freq, update_freq), 1.) - if is_poll: - min_freq = max_freq = freq - else: - max_freq = min(freq, update_freq) - if service_freq >= 2 * update_freq: - min_freq = update_freq - elif update_freq >= 2* service_freq: - min_freq = freq - else: - min_freq = min(freq, freq / 2.) - - self.min_freq = min_freq * 0.8 - self.max_freq = max_freq * 1.2 - self.avg_dt = MovingAverage(int(10 * freq)) - self.recent_avg_dt = MovingAverage(int(freq)) - self.prev_time = 0.0 - - def record_recv_time(self, cur_time: float) -> None: - # TODO: Handle case where cur_time is less than prev_time - if self.prev_time > 1e-5: - dt = cur_time - self.prev_time - - self.avg_dt.add_value(dt) - self.recent_avg_dt.add_value(dt) - - self.prev_time = cur_time - - @property - def valid(self) -> bool: - if self.avg_dt.count == 0: - return False - - avg_freq = 1.0 / self.avg_dt.get_average() - if self.min_freq <= avg_freq <= self.max_freq: - return True - - avg_freq_recent = 1.0 / self.recent_avg_dt.get_average() - return self.min_freq <= avg_freq_recent <= self.max_freq - - -class SubMaster: - def __init__(self, services: List[str], poll: Optional[str] = None, - ignore_alive: Optional[List[str]] = None, ignore_avg_freq: Optional[List[str]] = None, - ignore_valid: Optional[List[str]] = None, addr: str = "127.0.0.1", frequency: Optional[float] = None): - self.frame = -1 - self.services = services - self.seen = {s: False for s in services} - self.updated = {s: False for s in services} - self.recv_time = {s: 0. for s in services} - self.recv_frame = {s: 0 for s in services} - self.sock = {} - self.data = {} - self.logMonoTime = {s: 0 for s in services} - - # zero-frequency / on-demand services are always alive and presumed valid; all others must pass checks - on_demand = {s: SERVICE_LIST[s].frequency <= 1e-5 for s in services} - self.static_freq_services = set(s for s in services if not on_demand[s]) - self.alive = {s: on_demand[s] for s in services} - self.freq_ok = {s: on_demand[s] for s in services} - self.valid = {s: on_demand[s] for s in services} - - self.freq_tracker: Dict[str, FrequencyTracker] = {} - self.poller = Poller() - polled_services = set([poll, ] if poll is not None else services) - self.non_polled_services = set(services) - polled_services - - self.ignore_average_freq = [] if ignore_avg_freq is None else ignore_avg_freq - self.ignore_alive = [] if ignore_alive is None else ignore_alive - self.ignore_valid = [] if ignore_valid is None else ignore_valid - - self.simulation = bool(int(os.getenv("SIMULATION", "0"))) - - # if freq and poll aren't specified, assume the max to be conservative - assert frequency is None or poll is None, "Do not specify 'frequency' - frequency of the polled service will be used." - self.update_freq = frequency or max([SERVICE_LIST[s].frequency for s in polled_services]) - - for s in services: - p = self.poller if s not in self.non_polled_services else None - self.sock[s] = sub_sock(s, poller=p, addr=addr, conflate=True) - - try: - data = new_message(s) - except capnp.lib.capnp.KjException: - data = new_message(s, 0) # lists - - self.data[s] = getattr(data.as_reader(), s) - self.freq_tracker[s] = FrequencyTracker(SERVICE_LIST[s].frequency, self.update_freq, s == poll) - - def __getitem__(self, s: str) -> capnp.lib.capnp._DynamicStructReader: - return self.data[s] - - def _check_avg_freq(self, s: str) -> bool: - return SERVICE_LIST[s].frequency > 0.99 and (s not in self.ignore_average_freq) and (s not in self.ignore_alive) - - def update(self, timeout: int = 100) -> None: - msgs = [] - for sock in self.poller.poll(timeout): - msgs.append(recv_one_or_none(sock)) - - # non-blocking receive for non-polled sockets - for s in self.non_polled_services: - msgs.append(recv_one_or_none(self.sock[s])) - self.update_msgs(time.monotonic(), msgs) - - def update_msgs(self, cur_time: float, msgs: List[capnp.lib.capnp._DynamicStructReader]) -> None: - self.frame += 1 - self.updated = dict.fromkeys(self.services, False) - for msg in msgs: - if msg is None: - continue - - s = msg.which() - self.seen[s] = True - self.updated[s] = True - - self.freq_tracker[s].record_recv_time(cur_time) - self.recv_time[s] = cur_time - self.recv_frame[s] = self.frame - self.data[s] = getattr(msg, s) - self.logMonoTime[s] = msg.logMonoTime - self.valid[s] = msg.valid - - for s in self.static_freq_services: - # alive if delay is within 10x the expected frequency; checks relaxed in simulator - self.alive[s] = (cur_time - self.recv_time[s]) < (10. / SERVICE_LIST[s].frequency) or (self.seen[s] and self.simulation) - self.freq_ok[s] = self.freq_tracker[s].valid or self.simulation - - def all_alive(self, service_list: Optional[List[str]] = None) -> bool: - return all(self.alive[s] for s in (service_list or self.services) if s not in self.ignore_alive) - - def all_freq_ok(self, service_list: Optional[List[str]] = None) -> bool: - return all(self.freq_ok[s] for s in (service_list or self.services) if self._check_avg_freq(s)) - - def all_valid(self, service_list: Optional[List[str]] = None) -> bool: - return all(self.valid[s] for s in (service_list or self.services) if s not in self.ignore_valid) - - def all_checks(self, service_list: Optional[List[str]] = None) -> bool: - return self.all_alive(service_list) and self.all_freq_ok(service_list) and self.all_valid(service_list) - - -class PubMaster: - def __init__(self, services: List[str]): - self.sock = {} - for s in services: - self.sock[s] = pub_sock(s) - - def send(self, s: str, dat: Union[bytes, capnp.lib.capnp._DynamicStructBuilder]) -> None: - if not isinstance(dat, bytes): - dat = dat.to_bytes() - self.sock[s].send(dat) - - def wait_for_readers_to_update(self, s: str, timeout: int, dt: float = 0.05) -> bool: - for _ in range(int(timeout*(1./dt))): - if self.sock[s].all_readers_updated(): - return True - time.sleep(dt) - return False - - def all_readers_updated(self, s: str) -> bool: - return self.sock[s].all_readers_updated() # type: ignore diff --git a/cereal/messaging/msgq_to_zmq.h b/cereal/messaging/msgq_to_zmq.h deleted file mode 100644 index ebdbe5df69..0000000000 --- a/cereal/messaging/msgq_to_zmq.h +++ /dev/null @@ -1,37 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include - -#define private public -#include "msgq/impl_msgq.h" -#include "msgq/impl_zmq.h" - -class MsgqToZmq { -public: - MsgqToZmq() {} - void run(const std::vector &endpoints, const std::string &ip); - -protected: - void registerSockets(); - void zmqMonitorThread(); - - struct SocketPair { - std::string endpoint; - std::unique_ptr pub_sock; - std::unique_ptr sub_sock; - int connected_clients = 0; - }; - - std::unique_ptr msgq_context; - std::unique_ptr zmq_context; - std::mutex mutex; - std::condition_variable cv; - std::unique_ptr msgq_poller; - std::map sub2pub; - std::vector socket_pairs; -}; diff --git a/cereal/messaging/tests/test_services.py b/cereal/messaging/tests/test_services.py deleted file mode 100644 index 8bfd2ea978..0000000000 --- a/cereal/messaging/tests/test_services.py +++ /dev/null @@ -1,21 +0,0 @@ -import os -import tempfile -from typing import Dict -from parameterized import parameterized - -import cereal.services as services -from cereal.services import SERVICE_LIST - - -class TestServices: - - @parameterized.expand(SERVICE_LIST.keys()) - def test_services(self, s): - service = SERVICE_LIST[s] - assert service.frequency <= 104 - assert service.decimation != 0 - - def test_generated_header(self): - with tempfile.NamedTemporaryFile(suffix=".h") as f: - ret = os.system(f"python3 {services.__file__} > {f.name} && clang++ {f.name} -std=c++11") - assert ret == 0, "generated services header is not valid C" diff --git a/cereal/messaging/tests/validate_sp_cereal_upstream.py b/cereal/messaging/tests/validate_sp_cereal_upstream.py deleted file mode 100755 index 9ccd6533ce..0000000000 --- a/cereal/messaging/tests/validate_sp_cereal_upstream.py +++ /dev/null @@ -1,222 +0,0 @@ -#!/usr/bin/env python3 -import argparse -import sys -from typing import Any, List, Tuple - -DEBUG = False - - -def print_debug(string: str) -> None: - if DEBUG: - print(string) - - -def create_schema_instance(struct: Any, prop: Tuple[str, Any]) -> Any: - """ - Create a new instance of a schema type, handling different field types. - - Args: - struct: The Cap'n Proto schema structure - prop: A tuple containing the field name and field metadata - - Returns: - A new initialized schema instance - """ - struct_instance = struct.new_message() - field_name, field_metadata = prop - - try: - field_type = field_metadata.proto.slot.type.which() - - # Initialize different types of fields - if field_type in ('list', 'text', 'data'): - struct_instance.init(field_name, 1) - print_debug(f"Initialized list/text/data field: {field_name}") - elif field_type in ('struct', 'object'): - struct_instance.init(field_name) - print_debug(f"Initialized struct/object field: {field_name}") - - return struct_instance - - except Exception as e: - print(f"Error creating instance for {field_name}: {e}") - return None - - -def get_schema_fields(schema_struct: Any) -> List[Tuple[str, Any]]: - """ - Retrieve all fields from a given schema structure. - - Args: - schema_struct: The Cap'n Proto schema structure - - Returns: - A list of field names and their metadata - """ - try: - # Get all fields from the schema - schema_fields = list(schema_struct.schema.fields.items()) - - print_debug("Discovered schema fields:") - for field_name, field_metadata in schema_fields: - print_debug(f"- {field_name}") - - return schema_fields - - except Exception as e: - print(f"Error retrieving schema fields: {e}") - return [] - - -def generate_schema_instances(schema_struct: Any) -> List[Any]: - """ - Generate instances for all fields in a given schema. - - Args: - schema_struct: The Cap'n Proto schema structure - - Returns: - A list of schema instances - """ - schema_fields = get_schema_fields(schema_struct) - instances = [] - - for field_prop in schema_fields: - try: - instance = create_schema_instance(schema_struct, field_prop) - if instance is not None: - instances.append(instance) - except Exception as e: - print(f"Skipping field due to error: {e}") - - print(f"Generated {len(instances)} schema instances") - return instances - - -def persist_instances(instances: List[Any], filename: str) -> None: - """ - Write schema instances to a binary file. - - Args: - instances: List of schema instances - filename: Output file path - """ - try: - with open(filename, 'wb') as f: - for instance in instances: - f.write(instance.to_bytes()) - - print(f"Successfully wrote {len(instances)} instances to {filename}") - - except Exception as e: - print(f"Error persisting instances: {e}") - sys.exit(1) - - -def read_instances(filename: str, schema_type: Any) -> List[Any]: - """ - Read schema instances from a binary file. - - Args: - filename: Input file path - schema_type: The schema type to use for reading - - Returns: - A list of read schema instances - """ - try: - with open(filename, 'rb') as f: - data = f.read() - - instances = list(schema_type.read_multiple_bytes(data)) - - print(f"Read {len(instances)} instances from {filename}") - return instances - - except Exception as e: - print(f"Error reading instances: {e}") - sys.exit(1) - - -def compare_schemas(original_instances: List[Any], read_instances: List[Any]) -> bool: - """ - Compare original and read-back instances to detect potential breaking changes. - - Args: - original_instances: List of originally generated instances - read_instances: List of instances read back from file - - Returns: - Boolean indicating whether schemas appear compatible - """ - if len(original_instances) != len(read_instances): - print("❌ Schema Compatibility Warning: Instance count mismatch") - return False - - compatible = True - for struct in read_instances: - try: - getattr(struct, struct.which()) # Attempting to access the field to validate readability - except Exception as e: - print(f"❌ Structural change detected: {struct.which()} is not readable.\nFull error: {e}") - compatible = False - - return compatible - - -def main(): - """ - CLI entry point for schema compatibility testing. - """ - # Setup argument parser - parser = argparse.ArgumentParser( - description='Cap\'n Proto Schema Compatibility Testing Tool', - epilog='Test schema compatibility by generating and reading back instances.' - ) - - # Add mutually exclusive group for generation or reading mode - mode_group = parser.add_mutually_exclusive_group(required=True) - mode_group.add_argument('-g', '--generate', action='store_true', - help='Generate schema instances') - mode_group.add_argument('-r', '--read', action='store_true', - help='Read and validate schema instances') - - # Common arguments - parser.add_argument('-f', '--file', - default='schema_instances.bin', - help='Output/input binary file (default: schema_instances.bin)') - - # Parse arguments - args = parser.parse_args() - - # Import the schema dynamically - try: - from cereal import log - schema_type = log.Event - except ImportError: - print("Error: Unable to import schema. Ensure 'cereal' is installed.") - sys.exit(1) - - # Execute based on mode - if args.generate: - print("🔧 Generating Schema Instances") - instances = generate_schema_instances(schema_type) - persist_instances(instances, args.file) - print("✅ Instance generation complete") - - elif args.read: - print("🔍 Reading and Validating Schema Instances") - generated_instances = generate_schema_instances(schema_type) - read_back_instances = read_instances(args.file, schema_type) - - # Compare schemas - if compare_schemas(generated_instances, read_back_instances): - print("✅ Schema Compatibility: No breaking changes detected") - sys.exit(0) - else: - print("❌ Potential Schema Breaking Changes Detected") - sys.exit(1) - - -if __name__ == "__main__": - main() diff --git a/cereal/services.py b/cereal/services.py deleted file mode 100755 index 3e72041b72..0000000000 --- a/cereal/services.py +++ /dev/null @@ -1,134 +0,0 @@ -#!/usr/bin/env python3 -from typing import Optional - - -class Service: - def __init__(self, should_log: bool, frequency: float, decimation: Optional[int] = None): - self.should_log = should_log - self.frequency = frequency - self.decimation = decimation - - -_services: dict[str, tuple] = { - # service: (should_log, frequency, qlog decimation (optional)) - # note: the "EncodeIdx" packets will still be in the log - "gyroscope": (True, 104., 104), - "gyroscope2": (True, 100., 100), - "accelerometer": (True, 104., 104), - "accelerometer2": (True, 100., 100), - "magnetometer": (True, 25.), - "lightSensor": (True, 100., 100), - "temperatureSensor": (True, 2., 200), - "temperatureSensor2": (True, 2., 200), - "gpsNMEA": (True, 9.), - "deviceState": (True, 2., 1), - "touch": (True, 20., 1), - "can": (True, 100., 2053), # decimation gives ~3 msgs in a full segment - "controlsState": (True, 100., 10), - "selfdriveState": (True, 100., 10), - "pandaStates": (True, 10., 1), - "peripheralState": (True, 2., 1), - "radarState": (True, 20., 5), - "roadEncodeIdx": (False, 20., 1), - "liveTracks": (True, 20.), - "sendcan": (True, 100., 139), - "logMessage": (True, 0.), - "errorLogMessage": (True, 0., 1), - "liveCalibration": (True, 4., 4), - "liveTorqueParameters": (True, 4., 1), - "liveDelay": (True, 4., 1), - "androidLog": (True, 0.), - "carState": (True, 100., 10), - "carControl": (True, 100., 10), - "carOutput": (True, 100., 10), - "longitudinalPlan": (True, 20., 10), - "driverAssistance": (True, 20., 20), - "procLog": (True, 0.5, 15), - "gpsLocationExternal": (True, 10., 10), - "gpsLocation": (True, 1., 1), - "ubloxGnss": (True, 10.), - "qcomGnss": (True, 2.), - "gnssMeasurements": (True, 10., 10), - "clocks": (True, 0.1, 1), - "ubloxRaw": (True, 20.), - "livePose": (True, 20., 4), - "liveParameters": (True, 20., 5), - "cameraOdometry": (True, 20., 10), - "thumbnail": (True, 1 / 60., 1), - "onroadEvents": (True, 1., 1), - "carParams": (True, 0.02, 1), - "roadCameraState": (True, 20., 20), - "driverCameraState": (True, 20., 20), - "driverEncodeIdx": (False, 20., 1), - "driverStateV2": (True, 20., 10), - "driverMonitoringState": (True, 20., 10), - "wideRoadEncodeIdx": (False, 20., 1), - "wideRoadCameraState": (True, 20., 20), - "drivingModelData": (True, 20., 10), - "modelV2": (True, 20.), - "managerState": (True, 2., 1), - "uploaderState": (True, 0., 1), - "navInstruction": (True, 1., 10), - "navRoute": (True, 0.), - "navThumbnail": (True, 0.), - "qRoadEncodeIdx": (False, 20.), - "userFlag": (True, 0., 1), - "microphone": (True, 10., 10), - - # sunnypilot - "modelManagerSP": (False, 1., 1), - "backupManagerSP": (False, 1., 1), - "selfdriveStateSP": (True, 100., 10), - "longitudinalPlanSP": (True, 20., 10), - "onroadEventsSP": (True, 1., 1), - "carParamsSP": (True, 0.02, 1), - "carControlSP": (True, 100., 10), - "carStateSP": (True, 100., 10), - "liveMapDataSP": (True, 1., 1), - - # debug - "uiDebug": (True, 0., 1), - "testJoystick": (True, 0.), - "alertDebug": (True, 20., 5), - "roadEncodeData": (False, 20.), - "driverEncodeData": (False, 20.), - "wideRoadEncodeData": (False, 20.), - "qRoadEncodeData": (False, 20.), - "livestreamWideRoadEncodeIdx": (False, 20.), - "livestreamRoadEncodeIdx": (False, 20.), - "livestreamDriverEncodeIdx": (False, 20.), - "livestreamWideRoadEncodeData": (False, 20.), - "livestreamRoadEncodeData": (False, 20.), - "livestreamDriverEncodeData": (False, 20.), - "customReservedRawData0": (True, 0.), - "customReservedRawData1": (True, 0.), - "customReservedRawData2": (True, 0.), -} -SERVICE_LIST = {name: Service(*vals) for - idx, (name, vals) in enumerate(_services.items())} - - -def build_header(): - h = "" - h += "/* THIS IS AN AUTOGENERATED FILE, PLEASE EDIT services.py */\n" - h += "#ifndef __SERVICES_H\n" - h += "#define __SERVICES_H\n" - - h += "#include \n" - h += "#include \n" - - h += "struct service { std::string name; bool should_log; int frequency; int decimation; };\n" - h += "static std::map services = {\n" - for k, v in SERVICE_LIST.items(): - should_log = "true" if v.should_log else "false" - decimation = -1 if v.decimation is None else v.decimation - h += ' { "%s", {"%s", %s, %d, %d}},\n' % \ - (k, k, should_log, v.frequency, decimation) - h += "};\n" - - h += "#endif\n" - return h - - -if __name__ == "__main__": - print(build_header()) diff --git a/codecov.yml b/codecov.yml deleted file mode 100644 index 519e7d1a38..0000000000 --- a/codecov.yml +++ /dev/null @@ -1,13 +0,0 @@ -comment: false -coverage: - status: - project: - default: - informational: true - patch: off - -ignore: - - "**/test_*.py" - - "selfdrive/test/**" - - "system/version.py" # codecov changes depending on if we are in a branch or not - - "tools" diff --git a/common/.gitignore b/common/.gitignore deleted file mode 100644 index ce1da4c53c..0000000000 --- a/common/.gitignore +++ /dev/null @@ -1 +0,0 @@ -*.cpp diff --git a/common/SConscript b/common/SConscript deleted file mode 100644 index 3cdb6fc5a2..0000000000 --- a/common/SConscript +++ /dev/null @@ -1,35 +0,0 @@ -Import('env', 'envCython', 'arch') - -common_libs = [ - 'params.cc', - 'swaglog.cc', - 'util.cc', - 'watchdog.cc', - 'ratekeeper.cc' -] - -_common = env.Library('common', common_libs, LIBS="json11") - -files = [ - 'clutil.cc', -] - -_gpucommon = env.Library('gpucommon', files) -Export('_common', '_gpucommon') - -if GetOption('extras'): - env.Program('tests/test_common', - ['tests/test_runner.cc', 'tests/test_params.cc', 'tests/test_util.cc', 'tests/test_swaglog.cc'], - LIBS=[_common, 'json11', 'zmq', 'pthread']) - -# Cython bindings -params_python = envCython.Program('params_pyx.so', 'params_pyx.pyx', LIBS=envCython['LIBS'] + [_common, 'zmq', 'json11']) - -SConscript([ - 'transformations/SConscript', -]) - -Import('transformations_python') -common_python = [params_python, transformations_python] - -Export('common_python') diff --git a/common/api/__init__.py b/common/api/__init__.py deleted file mode 100644 index 3e238ccc7a..0000000000 --- a/common/api/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -from openpilot.common.api.comma_connect import CommaConnectApi - - -class Api: - def __init__(self, dongle_id): - self.service = CommaConnectApi(dongle_id) - - def request(self, method, endpoint, **params): - return self.service.request(method, endpoint, **params) - - def get(self, *args, **kwargs): - return self.service.get(*args, **kwargs) - - def post(self, *args, **kwargs): - return self.service.post(*args, **kwargs) - - def get_token(self, expiry_hours=1): - return self.service.get_token(expiry_hours) - - -def api_get(endpoint, method='GET', timeout=None, access_token=None, **params): - return CommaConnectApi(None).api_get(endpoint, method, timeout, access_token, **params) diff --git a/common/api/base.py b/common/api/base.py deleted file mode 100644 index d40b47d49d..0000000000 --- a/common/api/base.py +++ /dev/null @@ -1,56 +0,0 @@ -import jwt -import requests -import unicodedata -from datetime import datetime, timedelta, UTC -from openpilot.system.hardware.hw import Paths -from openpilot.system.version import get_version - - -class BaseApi: - def __init__(self, dongle_id, api_host, user_agent="openpilot-"): - self.dongle_id = dongle_id - self.api_host = api_host - self.user_agent = user_agent - with open(f'{Paths.persist_root()}/comma/id_rsa') as f: - self.private_key = f.read() - - def get(self, *args, **kwargs): - return self.request('GET', *args, **kwargs) - - def post(self, *args, **kwargs): - return self.request('POST', *args, **kwargs) - - def request(self, method, endpoint, timeout=None, access_token=None, **params): - return self.api_get(endpoint, method=method, timeout=timeout, access_token=access_token, **params) - - def _get_token(self, expiry_hours=1, **extra_payload): - now = datetime.now(UTC).replace(tzinfo=None) - payload = { - 'identity': self.dongle_id, - 'nbf': now, - 'iat': now, - 'exp': now + timedelta(hours=expiry_hours), - **extra_payload - } - token = jwt.encode(payload, self.private_key, algorithm='RS256') - if isinstance(token, bytes): - token = token.decode('utf8') - return token - - def get_token(self, expiry_hours=1): - return self._get_token(expiry_hours) - - def remove_non_ascii_chars(self, text): - normalized_text = unicodedata.normalize('NFD', text) - ascii_encoded_text = normalized_text.encode('ascii', 'ignore') - return ascii_encoded_text.decode() - - def api_get(self, endpoint, method='GET', timeout=None, access_token=None, json=None, **params): - headers = {} - if access_token is not None: - headers['Authorization'] = "JWT " + access_token - - version = self.remove_non_ascii_chars(get_version()) - headers['User-Agent'] = self.user_agent + version - - return requests.request(method, f"{self.api_host}/{endpoint}", timeout=timeout, headers=headers, json=json, params=params) diff --git a/common/basedir.py b/common/basedir.py deleted file mode 100644 index 6b4811e53c..0000000000 --- a/common/basedir.py +++ /dev/null @@ -1,4 +0,0 @@ -import os - - -BASEDIR = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "../")) diff --git a/common/clutil.cc b/common/clutil.cc deleted file mode 100644 index f8381a7e09..0000000000 --- a/common/clutil.cc +++ /dev/null @@ -1,98 +0,0 @@ -#include "common/clutil.h" - -#include -#include -#include - -#include "common/util.h" -#include "common/swaglog.h" - -namespace { // helper functions - -template -std::string get_info(Func get_info_func, Id id, Name param_name) { - size_t size = 0; - CL_CHECK(get_info_func(id, param_name, 0, NULL, &size)); - std::string info(size, '\0'); - CL_CHECK(get_info_func(id, param_name, size, info.data(), NULL)); - return info; -} -inline std::string get_platform_info(cl_platform_id id, cl_platform_info name) { return get_info(&clGetPlatformInfo, id, name); } -inline std::string get_device_info(cl_device_id id, cl_device_info name) { return get_info(&clGetDeviceInfo, id, name); } - -void cl_print_info(cl_platform_id platform, cl_device_id device) { - size_t work_group_size = 0; - cl_device_type device_type = 0; - clGetDeviceInfo(device, CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(work_group_size), &work_group_size, NULL); - clGetDeviceInfo(device, CL_DEVICE_TYPE, sizeof(device_type), &device_type, NULL); - const char *type_str = "Other..."; - switch (device_type) { - case CL_DEVICE_TYPE_CPU: type_str ="CL_DEVICE_TYPE_CPU"; break; - case CL_DEVICE_TYPE_GPU: type_str = "CL_DEVICE_TYPE_GPU"; break; - case CL_DEVICE_TYPE_ACCELERATOR: type_str = "CL_DEVICE_TYPE_ACCELERATOR"; break; - } - - LOGD("vendor: %s", get_platform_info(platform, CL_PLATFORM_VENDOR).c_str()); - LOGD("platform version: %s", get_platform_info(platform, CL_PLATFORM_VERSION).c_str()); - LOGD("profile: %s", get_platform_info(platform, CL_PLATFORM_PROFILE).c_str()); - LOGD("extensions: %s", get_platform_info(platform, CL_PLATFORM_EXTENSIONS).c_str()); - LOGD("name: %s", get_device_info(device, CL_DEVICE_NAME).c_str()); - LOGD("device version: %s", get_device_info(device, CL_DEVICE_VERSION).c_str()); - LOGD("max work group size: %zu", work_group_size); - LOGD("type = %d, %s", (int)device_type, type_str); -} - -void cl_print_build_errors(cl_program program, cl_device_id device) { - cl_build_status status; - clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_STATUS, sizeof(status), &status, NULL); - size_t log_size; - clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, 0, NULL, &log_size); - std::string log(log_size, '\0'); - clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, log_size, &log[0], NULL); - - LOGE("build failed; status=%d, log: %s", status, log.c_str()); -} - -} // namespace - -cl_device_id cl_get_device_id(cl_device_type device_type) { - cl_uint num_platforms = 0; - CL_CHECK(clGetPlatformIDs(0, NULL, &num_platforms)); - std::unique_ptr platform_ids = std::make_unique(num_platforms); - CL_CHECK(clGetPlatformIDs(num_platforms, &platform_ids[0], NULL)); - - for (size_t i = 0; i < num_platforms; ++i) { - LOGD("platform[%zu] CL_PLATFORM_NAME: %s", i, get_platform_info(platform_ids[i], CL_PLATFORM_NAME).c_str()); - - // Get first device - if (cl_device_id device_id = NULL; clGetDeviceIDs(platform_ids[i], device_type, 1, &device_id, NULL) == 0 && device_id) { - cl_print_info(platform_ids[i], device_id); - return device_id; - } - } - LOGE("No valid openCL platform found"); - assert(0); - return nullptr; -} - -cl_context cl_create_context(cl_device_id device_id) { - return CL_CHECK_ERR(clCreateContext(NULL, 1, &device_id, NULL, NULL, &err)); -} - -void cl_release_context(cl_context context) { - clReleaseContext(context); -} - -cl_program cl_program_from_file(cl_context ctx, cl_device_id device_id, const char* path, const char* args) { - return cl_program_from_source(ctx, device_id, util::read_file(path), args); -} - -cl_program cl_program_from_source(cl_context ctx, cl_device_id device_id, const std::string& src, const char* args) { - const char *csrc = src.c_str(); - cl_program prg = CL_CHECK_ERR(clCreateProgramWithSource(ctx, 1, &csrc, NULL, &err)); - if (int err = clBuildProgram(prg, 1, &device_id, args, NULL, NULL); err != 0) { - cl_print_build_errors(prg, device_id); - assert(0); - } - return prg; -} diff --git a/common/clutil.h b/common/clutil.h deleted file mode 100644 index b364e79d45..0000000000 --- a/common/clutil.h +++ /dev/null @@ -1,28 +0,0 @@ -#pragma once - -#ifdef __APPLE__ -#include -#else -#include -#endif - -#include - -#define CL_CHECK(_expr) \ - do { \ - assert(CL_SUCCESS == (_expr)); \ - } while (0) - -#define CL_CHECK_ERR(_expr) \ - ({ \ - cl_int err = CL_INVALID_VALUE; \ - __typeof__(_expr) _ret = _expr; \ - assert(_ret&& err == CL_SUCCESS); \ - _ret; \ - }) - -cl_device_id cl_get_device_id(cl_device_type device_type); -cl_context cl_create_context(cl_device_id device_id); -void cl_release_context(cl_context context); -cl_program cl_program_from_source(cl_context ctx, cl_device_id device_id, const std::string& src, const char* args = nullptr); -cl_program cl_program_from_file(cl_context ctx, cl_device_id device_id, const char* path, const char* args); diff --git a/common/conversions.py b/common/conversions.py deleted file mode 100644 index b02b33c625..0000000000 --- a/common/conversions.py +++ /dev/null @@ -1,19 +0,0 @@ -import numpy as np - -class Conversions: - # Speed - MPH_TO_KPH = 1.609344 - KPH_TO_MPH = 1. / MPH_TO_KPH - MS_TO_KPH = 3.6 - KPH_TO_MS = 1. / MS_TO_KPH - MS_TO_MPH = MS_TO_KPH * KPH_TO_MPH - MPH_TO_MS = MPH_TO_KPH * KPH_TO_MS - MS_TO_KNOTS = 1.9438 - KNOTS_TO_MS = 1. / MS_TO_KNOTS - - # Angle - DEG_TO_RAD = np.pi / 180. - RAD_TO_DEG = 1. / DEG_TO_RAD - - # Mass - LB_TO_KG = 0.453592 diff --git a/common/dict_helpers.py b/common/dict_helpers.py deleted file mode 100644 index 62cff63b58..0000000000 --- a/common/dict_helpers.py +++ /dev/null @@ -1,9 +0,0 @@ -# remove all keys that end in DEPRECATED -def strip_deprecated_keys(d): - for k in list(d.keys()): - if isinstance(k, str): - if k.endswith('DEPRECATED'): - d.pop(k) - elif isinstance(d[k], dict): - strip_deprecated_keys(d[k]) - return d diff --git a/common/file_helpers.py b/common/file_helpers.py deleted file mode 100644 index b0d889f163..0000000000 --- a/common/file_helpers.py +++ /dev/null @@ -1,58 +0,0 @@ -import io -import os -import tempfile -import contextlib -import zstandard as zstd - -LOG_COMPRESSION_LEVEL = 10 # little benefit up to level 15. level ~17 is a small step change - - -class CallbackReader: - """Wraps a file, but overrides the read method to also - call a callback function with the number of bytes read so far.""" - def __init__(self, f, callback, *args): - self.f = f - self.callback = callback - self.cb_args = args - self.total_read = 0 - - def __getattr__(self, attr): - return getattr(self.f, attr) - - def read(self, *args, **kwargs): - chunk = self.f.read(*args, **kwargs) - self.total_read += len(chunk) - self.callback(*self.cb_args, self.total_read) - return chunk - - -@contextlib.contextmanager -def atomic_write_in_dir(path: str, mode: str = 'w', buffering: int = -1, encoding: str = None, newline: str = None, - overwrite: bool = False): - """Write to a file atomically using a temporary file in the same directory as the destination file.""" - dir_name = os.path.dirname(path) - - if not overwrite and os.path.exists(path): - raise FileExistsError(f"File '{path}' already exists. To overwrite it, set 'overwrite' to True.") - - with tempfile.NamedTemporaryFile(mode=mode, buffering=buffering, encoding=encoding, newline=newline, dir=dir_name, delete=False) as tmp_file: - yield tmp_file - tmp_file_name = tmp_file.name - os.replace(tmp_file_name, path) - - -def get_upload_stream(filepath: str, should_compress: bool) -> tuple[io.BufferedIOBase, int]: - if not should_compress: - file_size = os.path.getsize(filepath) - file_stream = open(filepath, "rb") - return file_stream, file_size - - # Compress the file on the fly - compressed_stream = io.BytesIO() - compressor = zstd.ZstdCompressor(level=LOG_COMPRESSION_LEVEL) - - with open(filepath, "rb") as f: - compressor.copy_stream(f, compressed_stream) - compressed_size = compressed_stream.tell() - compressed_stream.seek(0) - return compressed_stream, compressed_size diff --git a/common/filter_simple.py b/common/filter_simple.py deleted file mode 100644 index 9ea6fe3070..0000000000 --- a/common/filter_simple.py +++ /dev/null @@ -1,17 +0,0 @@ -class FirstOrderFilter: - def __init__(self, x0, rc, dt, initialized=True): - self.x = x0 - self.dt = dt - self.update_alpha(rc) - self.initialized = initialized - - def update_alpha(self, rc): - self.alpha = self.dt / (rc + self.dt) - - def update(self, x): - if self.initialized: - self.x = (1. - self.alpha) * self.x + self.alpha * x - else: - self.initialized = True - self.x = x - return self.x diff --git a/common/git.py b/common/git.py deleted file mode 100644 index 4406bf96b1..0000000000 --- a/common/git.py +++ /dev/null @@ -1,42 +0,0 @@ -from functools import cache -import subprocess -from openpilot.common.run import run_cmd, run_cmd_default - - -@cache -def get_commit(cwd: str = None, branch: str = "HEAD") -> str: - return run_cmd_default(["git", "rev-parse", branch], cwd=cwd) - - -@cache -def get_commit_date(cwd: str = None, commit: str = "HEAD") -> str: - return run_cmd_default(["git", "show", "--no-patch", "--format='%ct %ci'", commit], cwd=cwd) - - -@cache -def get_short_branch(cwd: str = None) -> str: - return run_cmd_default(["git", "rev-parse", "--abbrev-ref", "HEAD"], cwd=cwd) - - -@cache -def get_branch(cwd: str = None) -> str: - return run_cmd_default(["git", "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"], cwd=cwd) - - -@cache -def get_origin(cwd: str = None) -> str: - try: - local_branch = run_cmd(["git", "name-rev", "--name-only", "HEAD"], cwd=cwd) - tracking_remote = run_cmd(["git", "config", "branch." + local_branch + ".remote"], cwd=cwd) - return run_cmd(["git", "config", "remote." + tracking_remote + ".url"], cwd=cwd) - except subprocess.CalledProcessError: # Not on a branch, fallback - return run_cmd_default(["git", "config", "--get", "remote.origin.url"], cwd=cwd) - - -@cache -def get_normalized_origin(cwd: str = None) -> str: - return get_origin(cwd) \ - .replace("git@", "", 1) \ - .replace(".git", "", 1) \ - .replace("https://", "", 1) \ - .replace(":", "/", 1) diff --git a/common/mat.h b/common/mat.h deleted file mode 100644 index 8e10d61971..0000000000 --- a/common/mat.h +++ /dev/null @@ -1,85 +0,0 @@ -#pragma once - -typedef struct vec3 { - float v[3]; -} vec3; - -typedef struct vec4 { - float v[4]; -} vec4; - -typedef struct mat3 { - float v[3*3]; -} mat3; - -typedef struct mat4 { - float v[4*4]; -} mat4; - -static inline mat3 matmul3(const mat3 &a, const mat3 &b) { - mat3 ret = {{0.0}}; - for (int r=0; r<3; r++) { - for (int c=0; c<3; c++) { - float v = 0.0; - for (int k=0; k<3; k++) { - v += a.v[r*3+k] * b.v[k*3+c]; - } - ret.v[r*3+c] = v; - } - } - return ret; -} - -static inline vec3 matvecmul3(const mat3 &a, const vec3 &b) { - vec3 ret = {{0.0}}; - for (int r=0; r<3; r++) { - for (int c=0; c<3; c++) { - ret.v[r] += a.v[r*3+c] * b.v[c]; - } - } - return ret; -} - -static inline mat4 matmul(const mat4 &a, const mat4 &b) { - mat4 ret = {{0.0}}; - for (int r=0; r<4; r++) { - for (int c=0; c<4; c++) { - float v = 0.0; - for (int k=0; k<4; k++) { - v += a.v[r*4+k] * b.v[k*4+c]; - } - ret.v[r*4+c] = v; - } - } - return ret; -} - -static inline vec4 matvecmul(const mat4 &a, const vec4 &b) { - vec4 ret = {{0.0}}; - for (int r=0; r<4; r++) { - for (int c=0; c<4; c++) { - ret.v[r] += a.v[r*4+c] * b.v[c]; - } - } - return ret; -} - -// scales the input and output space of a transformation matrix -// that assumes pixel-center origin. -static inline mat3 transform_scale_buffer(const mat3 &in, float s) { - // in_pt = ( transform(out_pt/s + 0.5) - 0.5) * s - - mat3 transform_out = {{ - 1.0f/s, 0.0f, 0.5f, - 0.0f, 1.0f/s, 0.5f, - 0.0f, 0.0f, 1.0f, - }}; - - mat3 transform_in = {{ - s, 0.0f, -0.5f*s, - 0.0f, s, -0.5f*s, - 0.0f, 0.0f, 1.0f, - }}; - - return matmul3(transform_in, matmul3(in, transform_out)); -} diff --git a/common/mock/__init__.py b/common/mock/__init__.py deleted file mode 100644 index 4b01dfe841..0000000000 --- a/common/mock/__init__.py +++ /dev/null @@ -1,50 +0,0 @@ -""" -Utilities for generating mock messages for testing. -example in common/tests/test_mock.py -""" - - -import functools -import threading -from cereal.messaging import PubMaster -from cereal.services import SERVICE_LIST -from openpilot.common.mock.generators import generate_livePose -from openpilot.common.realtime import Ratekeeper - - -MOCK_GENERATOR = { - "livePose": generate_livePose -} - - -def generate_messages_loop(services: list[str], done: threading.Event): - pm = PubMaster(services) - rk = Ratekeeper(100) - i = 0 - while not done.is_set(): - for s in services: - should_send = i % (100/SERVICE_LIST[s].frequency) == 0 - if should_send: - message = MOCK_GENERATOR[s]() - pm.send(s, message) - i += 1 - rk.keep_time() - - -def mock_messages(services: list[str] | str): - if isinstance(services, str): - services = [services] - - def decorator(func): - @functools.wraps(func) - def wrapper(*args, **kwargs): - done = threading.Event() - t = threading.Thread(target=generate_messages_loop, args=(services, done)) - t.start() - try: - return func(*args, **kwargs) - finally: - done.set() - t.join() - return wrapper - return decorator diff --git a/common/model.h b/common/model.h deleted file mode 100644 index 596819256a..0000000000 --- a/common/model.h +++ /dev/null @@ -1 +0,0 @@ -#define DEFAULT_MODEL "Vegetarian Filet o Fish (Default)" diff --git a/common/params.py b/common/params.py deleted file mode 100644 index 66808083dc..0000000000 --- a/common/params.py +++ /dev/null @@ -1,18 +0,0 @@ -from openpilot.common.params_pyx import Params, ParamKeyType, UnknownKeyName -assert Params -assert ParamKeyType -assert UnknownKeyName - -if __name__ == "__main__": - import sys - - params = Params() - key = sys.argv[1] - assert params.check_key(key), f"unknown param: {key}" - - if len(sys.argv) == 3: - val = sys.argv[2] - print(f"SET: {key} = {val}") - params.put(key, val) - elif len(sys.argv) == 2: - print(f"GET: {key} = {params.get(key)}") diff --git a/common/params_keys.h b/common/params_keys.h deleted file mode 100644 index 047a81870e..0000000000 --- a/common/params_keys.h +++ /dev/null @@ -1,212 +0,0 @@ -#pragma once - -#include -#include - -inline static std::unordered_map keys = { - {"AccessToken", CLEAR_ON_MANAGER_START | DONT_LOG}, - {"AdbEnabled", PERSISTENT}, - {"AlwaysOnDM", PERSISTENT}, - {"ApiCache_Device", PERSISTENT}, - {"ApiCache_FirehoseStats", PERSISTENT}, - {"AssistNowToken", PERSISTENT}, - {"AthenadPid", PERSISTENT}, - {"AthenadUploadQueue", PERSISTENT}, - {"AthenadRecentlyViewedRoutes", PERSISTENT}, - {"BootCount", PERSISTENT}, - {"CalibrationParams", PERSISTENT}, - {"CameraDebugExpGain", CLEAR_ON_MANAGER_START}, - {"CameraDebugExpTime", CLEAR_ON_MANAGER_START}, - {"CarBatteryCapacity", PERSISTENT}, - {"CarParams", CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION}, - {"CarParamsCache", CLEAR_ON_MANAGER_START}, - {"CarParamsPersistent", PERSISTENT}, - {"CarParamsPrevRoute", PERSISTENT}, - {"CompletedTrainingVersion", PERSISTENT}, - {"ControlsReady", CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION}, - {"CurrentBootlog", PERSISTENT}, - {"CurrentRoute", CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION}, - {"DisableLogging", CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION}, - {"DisablePowerDown", PERSISTENT | BACKUP}, - {"DisableUpdates", PERSISTENT | BACKUP}, - {"DisengageOnAccelerator", PERSISTENT | BACKUP}, - {"DongleId", PERSISTENT}, - {"DoReboot", CLEAR_ON_MANAGER_START}, - {"DoShutdown", CLEAR_ON_MANAGER_START}, - {"DoUninstall", CLEAR_ON_MANAGER_START}, - {"AlphaLongitudinalEnabled", PERSISTENT | DEVELOPMENT_ONLY | BACKUP}, - {"ExperimentalMode", PERSISTENT | BACKUP}, - {"ExperimentalModeConfirmed", PERSISTENT | BACKUP}, - {"FirmwareQueryDone", CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION}, - {"ForcePowerDown", PERSISTENT}, - {"GitBranch", PERSISTENT}, - {"GitCommit", PERSISTENT}, - {"GitCommitDate", PERSISTENT}, - {"GitDiff", PERSISTENT}, - {"GithubSshKeys", PERSISTENT | BACKUP}, - {"GithubUsername", PERSISTENT | BACKUP}, - {"GitRemote", PERSISTENT}, - {"GsmApn", PERSISTENT | BACKUP}, - {"GsmMetered", PERSISTENT | BACKUP}, - {"GsmRoaming", PERSISTENT | BACKUP}, - {"HardwareSerial", PERSISTENT}, - {"HasAcceptedTerms", PERSISTENT}, - {"InstallDate", PERSISTENT}, - {"IsDriverViewEnabled", CLEAR_ON_MANAGER_START}, - {"IsEngaged", PERSISTENT}, - {"IsLdwEnabled", PERSISTENT | BACKUP}, - {"IsMetric", PERSISTENT | BACKUP}, - {"IsOffroad", CLEAR_ON_MANAGER_START}, - {"IsOnroad", PERSISTENT}, - {"IsRhdDetected", PERSISTENT}, - {"IsReleaseBranch", CLEAR_ON_MANAGER_START}, - {"IsTakingSnapshot", CLEAR_ON_MANAGER_START}, - {"IsTestedBranch", CLEAR_ON_MANAGER_START}, - {"JoystickDebugMode", CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION}, - {"LanguageSetting", PERSISTENT | BACKUP}, - {"LastAthenaPingTime", CLEAR_ON_MANAGER_START}, - {"LastGPSPosition", PERSISTENT}, - {"LastManagerExitReason", CLEAR_ON_MANAGER_START}, - {"LastOffroadStatusPacket", CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION}, - {"LastPowerDropDetected", CLEAR_ON_MANAGER_START}, - {"LastUpdateException", CLEAR_ON_MANAGER_START}, - {"LastUpdateTime", PERSISTENT}, - {"LiveDelay", PERSISTENT | BACKUP}, - {"LiveParameters", PERSISTENT}, - {"LiveParametersV2", PERSISTENT}, - {"LiveTorqueParameters", PERSISTENT | DONT_LOG}, - {"LocationFilterInitialState", PERSISTENT}, - {"LongitudinalManeuverMode", CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION}, - {"LongitudinalPersonality", PERSISTENT | BACKUP}, - {"NetworkMetered", PERSISTENT}, - {"ObdMultiplexingChanged", CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION}, - {"ObdMultiplexingEnabled", CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION}, - {"Offroad_BadNvme", CLEAR_ON_MANAGER_START}, - {"Offroad_CarUnrecognized", CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION}, - {"Offroad_ConnectivityNeeded", CLEAR_ON_MANAGER_START}, - {"Offroad_ConnectivityNeededPrompt", CLEAR_ON_MANAGER_START}, - {"Offroad_IsTakingSnapshot", CLEAR_ON_MANAGER_START}, - {"Offroad_NeosUpdate", CLEAR_ON_MANAGER_START}, - {"Offroad_NoFirmware", CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION}, - {"Offroad_Recalibration", CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION}, - {"Offroad_StorageMissing", CLEAR_ON_MANAGER_START}, - {"Offroad_TemperatureTooHigh", CLEAR_ON_MANAGER_START}, - {"Offroad_UnofficialHardware", CLEAR_ON_MANAGER_START}, - {"Offroad_UpdateFailed", CLEAR_ON_MANAGER_START}, - {"OnroadCycleRequested", CLEAR_ON_MANAGER_START}, - {"OpenpilotEnabledToggle", PERSISTENT | BACKUP}, - {"PandaHeartbeatLost", CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION}, - {"PandaSomResetTriggered", CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION}, - {"PandaSignatures", CLEAR_ON_MANAGER_START}, - {"PrimeType", PERSISTENT}, - {"RecordFront", PERSISTENT | BACKUP}, - {"RecordFrontLock", PERSISTENT}, // for the internal fleet - {"SecOCKey", PERSISTENT | DONT_LOG}, // Candidate for | BACKUP - {"RouteCount", PERSISTENT}, - {"SnoozeUpdate", CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION}, - {"SshEnabled", PERSISTENT | BACKUP}, - {"TermsVersion", PERSISTENT}, - {"TrainingVersion", PERSISTENT}, - {"UbloxAvailable", PERSISTENT}, - {"UpdateAvailable", CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION}, - {"UpdateFailedCount", CLEAR_ON_MANAGER_START}, - {"UpdaterAvailableBranches", PERSISTENT}, - {"UpdaterCurrentDescription", CLEAR_ON_MANAGER_START}, - {"UpdaterCurrentReleaseNotes", CLEAR_ON_MANAGER_START}, - {"UpdaterFetchAvailable", CLEAR_ON_MANAGER_START}, - {"UpdaterNewDescription", CLEAR_ON_MANAGER_START}, - {"UpdaterNewReleaseNotes", CLEAR_ON_MANAGER_START}, - {"UpdaterState", CLEAR_ON_MANAGER_START}, - {"UpdaterTargetBranch", CLEAR_ON_MANAGER_START}, - {"UpdaterLastFetchTime", PERSISTENT}, - {"Version", PERSISTENT}, - - // --- sunnypilot params --- // - {"ApiCache_DriveStats", PERSISTENT}, - {"AutoLaneChangeBsmDelay", PERSISTENT}, - {"AutoLaneChangeTimer", PERSISTENT}, - {"BlinkerMinLateralControlSpeed", PERSISTENT | BACKUP}, - {"BlinkerPauseLateralControl", PERSISTENT | BACKUP}, - {"CarParamsSP", CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION}, - {"CarParamsSPCache", CLEAR_ON_MANAGER_START}, - {"CarParamsSPPersistent", PERSISTENT}, - {"CarPlatformBundle", PERSISTENT}, - {"CustomAccIncrementsEnabled", PERSISTENT | BACKUP}, - {"CustomAccLongPressIncrement", PERSISTENT | BACKUP}, - {"CustomAccShortPressIncrement", PERSISTENT | BACKUP}, - {"DeviceBootMode", PERSISTENT | BACKUP}, - {"EnableGithubRunner", PERSISTENT | BACKUP}, - {"MaxTimeOffroad", PERSISTENT | BACKUP}, - {"Brightness", PERSISTENT | BACKUP}, - {"ModelRunnerTypeCache", CLEAR_ON_ONROAD_TRANSITION}, - {"OffroadMode", CLEAR_ON_MANAGER_START}, - {"QuietMode", PERSISTENT | BACKUP}, - - // MADS params - {"Mads", PERSISTENT | BACKUP}, - {"MadsMainCruiseAllowed", PERSISTENT | BACKUP}, - {"MadsSteeringMode", PERSISTENT | BACKUP}, - {"MadsUnifiedEngagementMode", PERSISTENT | BACKUP}, - - // Model Manager params - {"ModelManager_ActiveBundle", PERSISTENT}, - {"ModelManager_DownloadIndex", CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION}, - {"ModelManager_LastSyncTime", CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION}, - {"ModelManager_ModelsCache", PERSISTENT | BACKUP}, - - // Neural Network Lateral Control - {"NeuralNetworkLateralControl", PERSISTENT | BACKUP}, - - // sunnylink params - {"EnableSunnylinkUploader", PERSISTENT | BACKUP}, - {"LastSunnylinkPingTime", CLEAR_ON_MANAGER_START}, - {"SunnylinkCache_Roles", PERSISTENT}, - {"SunnylinkCache_Users", PERSISTENT}, - {"SunnylinkDongleId", PERSISTENT}, - {"SunnylinkdPid", PERSISTENT}, - {"SunnylinkEnabled", PERSISTENT}, - - // Backup Manager params - {"BackupManager_CreateBackup", PERSISTENT}, - {"BackupManager_RestoreVersion", PERSISTENT}, - - // sunnypilot car specific params - {"HyundaiLongitudinalTuning", PERSISTENT}, - - {"DynamicExperimentalControl", PERSISTENT}, - {"BlindSpot", PERSISTENT | BACKUP}, - - // model panel params - {"LagdToggle", PERSISTENT | BACKUP}, - - // mapd - {"MapAdvisorySpeedLimit", CLEAR_ON_ONROAD_TRANSITION}, - {"MapdVersion", PERSISTENT}, - {"MapSpeedLimit", CLEAR_ON_ONROAD_TRANSITION}, - {"NextMapSpeedLimit", CLEAR_ON_ONROAD_TRANSITION}, - {"Offroad_OSMUpdateRequired", CLEAR_ON_MANAGER_START}, - {"OsmDbUpdatesCheck", CLEAR_ON_MANAGER_START}, // mapd database update happens with device ON, reset on boot - {"OSMDownloadBounds", PERSISTENT}, - {"OsmDownloadedDate", PERSISTENT}, - {"OSMDownloadLocations", PERSISTENT}, - {"OSMDownloadProgress", CLEAR_ON_MANAGER_START}, - {"OsmLocal", PERSISTENT}, - {"OsmLocationName", PERSISTENT}, - {"OsmLocationTitle", PERSISTENT}, - {"OsmLocationUrl", PERSISTENT}, - {"OsmStateName", PERSISTENT}, - {"OsmStateTitle", PERSISTENT}, - {"OsmWayTest", PERSISTENT}, - {"RoadName", CLEAR_ON_ONROAD_TRANSITION}, - - // Tuning keys - {"EnableHkgTuningAngleSmoothingFactor", PERSISTENT | BACKUP}, - {"HkgTuningAngleMinTorqueReductionGain", PERSISTENT | BACKUP}, - {"HkgTuningAngleMaxTorqueReductionGain", PERSISTENT | BACKUP}, - {"HkgTuningAngleActiveTorqueReductionGain", PERSISTENT | BACKUP}, - {"HkgTuningOverridingCycles", PERSISTENT | BACKUP}, - {"HkgAngleLiveTuning", CLEAR_ON_MANAGER_START}, - - {"AdasDrvEcuInterceptorEnabled", PERSISTENT | BACKUP} - -}; diff --git a/common/params_pyx.pyx b/common/params_pyx.pyx deleted file mode 100644 index e851020d83..0000000000 --- a/common/params_pyx.pyx +++ /dev/null @@ -1,124 +0,0 @@ -# distutils: language = c++ -# cython: language_level = 3 -from libcpp cimport bool -from libcpp.string cimport string -from libcpp.vector cimport vector - -cdef extern from "common/params.h": - cpdef enum ParamKeyType: - PERSISTENT - CLEAR_ON_MANAGER_START - CLEAR_ON_ONROAD_TRANSITION - CLEAR_ON_OFFROAD_TRANSITION - DEVELOPMENT_ONLY - BACKUP - ALL - - cdef cppclass c_Params "Params": - c_Params(string) except + nogil - string get(string, bool) nogil - bool getBool(string, bool) nogil - int remove(string) nogil - int put(string, string) nogil - void putNonBlocking(string, string) nogil - void putBoolNonBlocking(string, bool) nogil - int putBool(string, bool) nogil - bool checkKey(string) nogil - string getParamPath(string) nogil - void clearAll(ParamKeyType) - vector[string] allKeys(ParamKeyType) - - -def ensure_bytes(v): - return v.encode() if isinstance(v, str) else v - -class UnknownKeyName(Exception): - pass - -cdef class Params: - cdef c_Params* p - cdef str d - - def __cinit__(self, d=""): - cdef string path = d.encode() - with nogil: - self.p = new c_Params(path) - self.d = d - - def __reduce__(self): - return (type(self), (self.d,)) - - def __dealloc__(self): - del self.p - - def clear_all(self, tx_type=ParamKeyType.ALL): - self.p.clearAll(tx_type) - - def check_key(self, key): - key = ensure_bytes(key) - if not self.p.checkKey(key): - raise UnknownKeyName(key) - return key - - def get(self, key, bool block=False, encoding=None): - cdef string k = self.check_key(key) - cdef string val - with nogil: - val = self.p.get(k, block) - - if val == b"": - if block: - # If we got no value while running in blocked mode - # it means we got an interrupt while waiting - raise KeyboardInterrupt - else: - return None - - return val if encoding is None else val.decode(encoding) - - def get_bool(self, key, bool block=False): - cdef string k = self.check_key(key) - cdef bool r - with nogil: - r = self.p.getBool(k, block) - return r - - def put(self, key, dat): - """ - Warning: This function blocks until the param is written to disk! - In very rare cases this can take over a second, and your code will hang. - Use the put_nonblocking, put_bool_nonblocking in time sensitive code, but - in general try to avoid writing params as much as possible. - """ - cdef string k = self.check_key(key) - cdef string dat_bytes = ensure_bytes(dat) - with nogil: - self.p.put(k, dat_bytes) - - def put_bool(self, key, bool val): - cdef string k = self.check_key(key) - with nogil: - self.p.putBool(k, val) - - def put_nonblocking(self, key, dat): - cdef string k = self.check_key(key) - cdef string dat_bytes = ensure_bytes(dat) - with nogil: - self.p.putNonBlocking(k, dat_bytes) - - def put_bool_nonblocking(self, key, bool val): - cdef string k = self.check_key(key) - with nogil: - self.p.putBoolNonBlocking(k, val) - - def remove(self, key): - cdef string k = self.check_key(key) - with nogil: - self.p.remove(k) - - def get_param_path(self, key=""): - cdef string key_bytes = ensure_bytes(key) - return self.p.getParamPath(key_bytes).decode("utf-8") - - def all_keys(self, type=ParamKeyType.ALL): - return self.p.allKeys(type) diff --git a/common/pid.py b/common/pid.py deleted file mode 100644 index f2ab935f45..0000000000 --- a/common/pid.py +++ /dev/null @@ -1,70 +0,0 @@ -import numpy as np -from numbers import Number - -class PIDController: - def __init__(self, k_p, k_i, k_f=0., k_d=0., pos_limit=1e308, neg_limit=-1e308, rate=100): - self._k_p = k_p - self._k_i = k_i - self._k_d = k_d - self.k_f = k_f # feedforward gain - if isinstance(self._k_p, Number): - self._k_p = [[0], [self._k_p]] - if isinstance(self._k_i, Number): - self._k_i = [[0], [self._k_i]] - if isinstance(self._k_d, Number): - self._k_d = [[0], [self._k_d]] - - self.pos_limit = pos_limit - self.neg_limit = neg_limit - - self.i_unwind_rate = 0.3 / rate - self.i_rate = 1.0 / rate - self.speed = 0.0 - - self.reset() - - @property - def k_p(self): - return np.interp(self.speed, self._k_p[0], self._k_p[1]) - - @property - def k_i(self): - return np.interp(self.speed, self._k_i[0], self._k_i[1]) - - @property - def k_d(self): - return np.interp(self.speed, self._k_d[0], self._k_d[1]) - - @property - def error_integral(self): - return self.i/self.k_i - - def reset(self): - self.p = 0.0 - self.i = 0.0 - self.d = 0.0 - self.f = 0.0 - self.control = 0 - - def update(self, error, error_rate=0.0, speed=0.0, override=False, feedforward=0., freeze_integrator=False): - self.speed = speed - - self.p = float(error) * self.k_p - self.f = feedforward * self.k_f - self.d = error_rate * self.k_d - - if override: - self.i -= self.i_unwind_rate * float(np.sign(self.i)) - else: - if not freeze_integrator: - self.i = self.i + error * self.k_i * self.i_rate - - # Clip i to prevent exceeding control limits - control_no_i = self.p + self.d + self.f - control_no_i = np.clip(control_no_i, self.neg_limit, self.pos_limit) - self.i = np.clip(self.i, self.neg_limit - control_no_i, self.pos_limit - control_no_i) - - control = self.p + self.i + self.d + self.f - - self.control = np.clip(control, self.neg_limit, self.pos_limit) - return self.control diff --git a/common/prefix.h b/common/prefix.h deleted file mode 100644 index 2612c05d4f..0000000000 --- a/common/prefix.h +++ /dev/null @@ -1,39 +0,0 @@ -#pragma once - -#include -#include - -#include "common/params.h" -#include "common/util.h" -#include "system/hardware/hw.h" - -class OpenpilotPrefix { -public: - OpenpilotPrefix(std::string prefix = {}) { - if (prefix.empty()) { - prefix = util::random_string(15); - } - msgq_path = Path::shm_path() + "/" + prefix; - bool ret = util::create_directories(msgq_path, 0777); - assert(ret); - setenv("OPENPILOT_PREFIX", prefix.c_str(), 1); - } - - ~OpenpilotPrefix() { - auto param_path = Params().getParamPath(); - if (util::file_exists(param_path)) { - std::string real_path = util::readlink(param_path); - system(util::string_format("rm %s -rf", real_path.c_str()).c_str()); - unlink(param_path.c_str()); - } - if (getenv("COMMA_CACHE") == nullptr) { - system(util::string_format("rm %s -rf", Path::download_cache_root().c_str()).c_str()); - } - system(util::string_format("rm %s -rf", Path::comma_home().c_str()).c_str()); - system(util::string_format("rm %s -rf", msgq_path.c_str()).c_str()); - unsetenv("OPENPILOT_PREFIX"); - } - -private: - std::string msgq_path; -}; diff --git a/common/prefix.py b/common/prefix.py deleted file mode 100644 index 762ae70fb4..0000000000 --- a/common/prefix.py +++ /dev/null @@ -1,53 +0,0 @@ -import os -import shutil -import uuid - - -from openpilot.common.params import Params -from openpilot.system.hardware import PC -from openpilot.system.hardware.hw import Paths -from openpilot.system.hardware.hw import DEFAULT_DOWNLOAD_CACHE_ROOT - -class OpenpilotPrefix: - def __init__(self, prefix: str = None, clean_dirs_on_exit: bool = True, shared_download_cache: bool = False): - self.prefix = prefix if prefix else str(uuid.uuid4().hex[0:15]) - self.msgq_path = os.path.join(Paths.shm_path(), self.prefix) - self.clean_dirs_on_exit = clean_dirs_on_exit - self.shared_download_cache = shared_download_cache - - def __enter__(self): - self.original_prefix = os.environ.get('OPENPILOT_PREFIX', None) - os.environ['OPENPILOT_PREFIX'] = self.prefix - try: - os.mkdir(self.msgq_path) - except FileExistsError: - pass - os.makedirs(Paths.log_root(), exist_ok=True) - - if self.shared_download_cache: - os.environ["COMMA_CACHE"] = DEFAULT_DOWNLOAD_CACHE_ROOT - - return self - - def __exit__(self, exc_type, exc_obj, exc_tb): - if self.clean_dirs_on_exit: - self.clean_dirs() - try: - del os.environ['OPENPILOT_PREFIX'] - if self.original_prefix is not None: - os.environ['OPENPILOT_PREFIX'] = self.original_prefix - except KeyError: - pass - return False - - def clean_dirs(self): - symlink_path = Params().get_param_path() - if os.path.exists(symlink_path): - shutil.rmtree(os.path.realpath(symlink_path), ignore_errors=True) - os.remove(symlink_path) - shutil.rmtree(self.msgq_path, ignore_errors=True) - if PC: - shutil.rmtree(Paths.log_root(), ignore_errors=True) - if not os.environ.get("COMMA_CACHE", False): - shutil.rmtree(Paths.download_cache_root(), ignore_errors=True) - shutil.rmtree(Paths.comma_home(), ignore_errors=True) diff --git a/common/retry.py b/common/retry.py deleted file mode 100644 index 9bd4ac9522..0000000000 --- a/common/retry.py +++ /dev/null @@ -1,30 +0,0 @@ -import time -import functools - -from openpilot.common.swaglog import cloudlog - - -def retry(attempts=3, delay=1.0, ignore_failure=False): - def decorator(func): - @functools.wraps(func) - def wrapper(*args, **kwargs): - for _ in range(attempts): - try: - return func(*args, **kwargs) - except Exception: - cloudlog.exception(f"{func.__name__} failed, trying again") - time.sleep(delay) - - if ignore_failure: - cloudlog.error(f"{func.__name__} failed after retry") - else: - raise Exception(f"{func.__name__} failed after retry") - return wrapper - return decorator - - -if __name__ == "__main__": - @retry(attempts=10) - def abc(): - raise ValueError("abc failed :(") - abc() diff --git a/common/run.py b/common/run.py deleted file mode 100644 index 06deb6388d..0000000000 --- a/common/run.py +++ /dev/null @@ -1,13 +0,0 @@ -import subprocess - - -def run_cmd(cmd: list[str], cwd=None, env=None) -> str: - return subprocess.check_output(cmd, encoding='utf8', cwd=cwd, env=env).strip() - - -def run_cmd_default(cmd: list[str], default: str = "", cwd=None, env=None) -> str: - try: - return run_cmd(cmd, cwd=cwd, env=env) - except subprocess.CalledProcessError: - return default - diff --git a/common/spinner.py b/common/spinner.py deleted file mode 100755 index 12a816eaf8..0000000000 --- a/common/spinner.py +++ /dev/null @@ -1,52 +0,0 @@ -import os -import subprocess -from openpilot.common.basedir import BASEDIR - - -class Spinner: - def __init__(self): - try: - self.spinner_proc = subprocess.Popen(["./spinner.py"], - stdin=subprocess.PIPE, - cwd=os.path.join(BASEDIR, "system", "ui"), - close_fds=True) - except OSError: - self.spinner_proc = None - - def __enter__(self): - return self - - def update(self, spinner_text: str): - if self.spinner_proc is not None: - self.spinner_proc.stdin.write(spinner_text.encode('utf8') + b"\n") - try: - self.spinner_proc.stdin.flush() - except BrokenPipeError: - pass - - def update_progress(self, cur: float, total: float): - self.update(str(round(100 * cur / total))) - - def close(self): - if self.spinner_proc is not None: - self.spinner_proc.kill() - try: - self.spinner_proc.communicate(timeout=2.) - except subprocess.TimeoutExpired: - print("WARNING: failed to kill spinner") - self.spinner_proc = None - - def __del__(self): - self.close() - - def __exit__(self, exc_type, exc_value, traceback): - self.close() - - -if __name__ == "__main__": - import time - with Spinner() as s: - s.update("Spinner text") - time.sleep(5.0) - print("gone") - time.sleep(5.0) diff --git a/common/tests/test_file_helpers.py b/common/tests/test_file_helpers.py deleted file mode 100644 index a9977c2362..0000000000 --- a/common/tests/test_file_helpers.py +++ /dev/null @@ -1,19 +0,0 @@ -import os -from uuid import uuid4 - -from openpilot.common.file_helpers import atomic_write_in_dir - - -class TestFileHelpers: - def run_atomic_write_func(self, atomic_write_func): - path = f"/tmp/tmp{uuid4()}" - with atomic_write_func(path) as f: - f.write("test") - assert not os.path.exists(path) - - with open(path) as f: - assert f.read() == "test" - os.remove(path) - - def test_atomic_write_in_dir(self): - self.run_atomic_write_func(atomic_write_in_dir) diff --git a/common/tests/test_params.cc b/common/tests/test_params.cc deleted file mode 100644 index f8d6c79f55..0000000000 --- a/common/tests/test_params.cc +++ /dev/null @@ -1,27 +0,0 @@ -#include "catch2/catch.hpp" -#define private public -#include "common/params.h" -#include "common/util.h" - -TEST_CASE("params_nonblocking_put") { - char tmp_path[] = "/tmp/asyncWriter_XXXXXX"; - const std::string param_path = mkdtemp(tmp_path); - auto param_names = {"CarParams", "IsMetric"}; - { - Params params(param_path); - for (const auto &name : param_names) { - params.putNonBlocking(name, "1"); - // param is empty - REQUIRE(params.get(name).empty()); - } - - // check if thread is running - REQUIRE(params.future.valid()); - REQUIRE(params.future.wait_for(std::chrono::milliseconds(0)) == std::future_status::timeout); - } - // check results - Params p(param_path); - for (const auto &name : param_names) { - REQUIRE(p.get(name) == "1"); - } -} diff --git a/common/tests/test_params.py b/common/tests/test_params.py deleted file mode 100644 index 16cbc45295..0000000000 --- a/common/tests/test_params.py +++ /dev/null @@ -1,109 +0,0 @@ -import pytest -import os -import threading -import time -import uuid - -from openpilot.common.params import Params, ParamKeyType, UnknownKeyName - -class TestParams: - def setup_method(self): - self.params = Params() - - def test_params_put_and_get(self): - self.params.put("DongleId", "cb38263377b873ee") - assert self.params.get("DongleId") == b"cb38263377b873ee" - - def test_params_non_ascii(self): - st = b"\xe1\x90\xff" - self.params.put("CarParams", st) - assert self.params.get("CarParams") == st - - def test_params_get_cleared_manager_start(self): - self.params.put("CarParams", "test") - self.params.put("DongleId", "cb38263377b873ee") - assert self.params.get("CarParams") == b"test" - - undefined_param = self.params.get_param_path(uuid.uuid4().hex) - with open(undefined_param, "w") as f: - f.write("test") - assert os.path.isfile(undefined_param) - - self.params.clear_all(ParamKeyType.CLEAR_ON_MANAGER_START) - assert self.params.get("CarParams") is None - assert self.params.get("DongleId") is not None - assert not os.path.isfile(undefined_param) - - def test_params_two_things(self): - self.params.put("DongleId", "bob") - self.params.put("AthenadPid", "123") - assert self.params.get("DongleId") == b"bob" - assert self.params.get("AthenadPid") == b"123" - - def test_params_get_block(self): - def _delayed_writer(): - time.sleep(0.1) - self.params.put("CarParams", "test") - threading.Thread(target=_delayed_writer).start() - assert self.params.get("CarParams") is None - assert self.params.get("CarParams", True) == b"test" - - def test_params_unknown_key_fails(self): - with pytest.raises(UnknownKeyName): - self.params.get("swag") - - with pytest.raises(UnknownKeyName): - self.params.get_bool("swag") - - with pytest.raises(UnknownKeyName): - self.params.put("swag", "abc") - - with pytest.raises(UnknownKeyName): - self.params.put_bool("swag", True) - - def test_remove_not_there(self): - assert self.params.get("CarParams") is None - self.params.remove("CarParams") - assert self.params.get("CarParams") is None - - def test_get_bool(self): - self.params.remove("IsMetric") - assert not self.params.get_bool("IsMetric") - - self.params.put_bool("IsMetric", True) - assert self.params.get_bool("IsMetric") - - self.params.put_bool("IsMetric", False) - assert not self.params.get_bool("IsMetric") - - self.params.put("IsMetric", "1") - assert self.params.get_bool("IsMetric") - - self.params.put("IsMetric", "0") - assert not self.params.get_bool("IsMetric") - - def test_put_non_blocking_with_get_block(self): - q = Params() - def _delayed_writer(): - time.sleep(0.1) - Params().put_nonblocking("CarParams", "test") - threading.Thread(target=_delayed_writer).start() - assert q.get("CarParams") is None - assert q.get("CarParams", True) == b"test" - - def test_put_bool_non_blocking_with_get_block(self): - q = Params() - def _delayed_writer(): - time.sleep(0.1) - Params().put_bool_nonblocking("CarParams", True) - threading.Thread(target=_delayed_writer).start() - assert q.get("CarParams") is None - assert q.get("CarParams", True) == b"1" - - def test_params_all_keys(self): - keys = Params().all_keys() - - # sanity checks - assert len(keys) > 20 - assert len(keys) == len(set(keys)) - assert b"CarParams" in keys diff --git a/common/transformations/.gitignore b/common/transformations/.gitignore deleted file mode 100644 index a67290f09a..0000000000 --- a/common/transformations/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -transformations -transformations.cpp diff --git a/common/transformations/SConscript b/common/transformations/SConscript deleted file mode 100644 index 4ac73a165e..0000000000 --- a/common/transformations/SConscript +++ /dev/null @@ -1,5 +0,0 @@ -Import('env', 'envCython') - -transformations = env.Library('transformations', ['orientation.cc', 'coordinates.cc']) -transformations_python = envCython.Program('transformations.so', 'transformations.pyx') -Export('transformations', 'transformations_python') diff --git a/common/transformations/camera.py b/common/transformations/camera.py deleted file mode 100644 index 2e68b5e37c..0000000000 --- a/common/transformations/camera.py +++ /dev/null @@ -1,179 +0,0 @@ -import itertools -import numpy as np -from dataclasses import dataclass - -import openpilot.common.transformations.orientation as orient - -## -- hardcoded hardware params -- -@dataclass(frozen=True) -class CameraConfig: - width: int - height: int - focal_length: float - - @property - def size(self): - return (self.width, self.height) - - @property - def intrinsics(self): - # aka 'K' aka camera_frame_from_view_frame - return np.array([ - [self.focal_length, 0.0, float(self.width)/2], - [0.0, self.focal_length, float(self.height)/2], - [0.0, 0.0, 1.0] - ]) - - @property - def intrinsics_inv(self): - # aka 'K_inv' aka view_frame_from_camera_frame - return np.linalg.inv(self.intrinsics) - -@dataclass(frozen=True) -class _NoneCameraConfig(CameraConfig): - width: int = 0 - height: int = 0 - focal_length: float = 0 - -@dataclass(frozen=True) -class DeviceCameraConfig: - fcam: CameraConfig - dcam: CameraConfig - ecam: CameraConfig - - def all_cams(self): - for cam in ['fcam', 'dcam', 'ecam']: - if not isinstance(getattr(self, cam), _NoneCameraConfig): - yield cam, getattr(self, cam) - -_ar_ox_fisheye = CameraConfig(1928, 1208, 567.0) # focal length probably wrong? magnification is not consistent across frame -_os_fisheye = CameraConfig(2688 // 2, 1520 // 2, 567.0 / 4 * 3) -_ar_ox_config = DeviceCameraConfig(CameraConfig(1928, 1208, 2648.0), _ar_ox_fisheye, _ar_ox_fisheye) -_os_config = DeviceCameraConfig(CameraConfig(2688 // 2, 1520 // 2, 1522.0 * 3 / 4), _os_fisheye, _os_fisheye) -_neo_config = DeviceCameraConfig(CameraConfig(1164, 874, 910.0), CameraConfig(816, 612, 650.0), _NoneCameraConfig()) - -DEVICE_CAMERAS = { - # A "device camera" is defined by a device type and sensor - - # sensor type was never set on eon/neo/two - ("neo", "unknown"): _neo_config, - # unknown here is AR0231, field was added with OX03C10 support - ("tici", "unknown"): _ar_ox_config, - - # before deviceState.deviceType was set, assume tici AR config - ("unknown", "ar0231"): _ar_ox_config, - ("unknown", "ox03c10"): _ar_ox_config, - - # simulator (emulates a tici) - ("pc", "unknown"): _ar_ox_config, -} -prods = itertools.product(('tici', 'tizi', 'mici'), (('ar0231', _ar_ox_config), ('ox03c10', _ar_ox_config), ('os04c10', _os_config))) -DEVICE_CAMERAS.update({(d, c[0]): c[1] for d, c in prods}) - -# device/mesh : x->forward, y-> right, z->down -# view : x->right, y->down, z->forward -device_frame_from_view_frame = np.array([ - [ 0., 0., 1.], - [ 1., 0., 0.], - [ 0., 1., 0.] -]) -view_frame_from_device_frame = device_frame_from_view_frame.T - - -# aka 'extrinsic_matrix' -# road : x->forward, y -> left, z->up -def get_view_frame_from_road_frame(roll, pitch, yaw, height): - device_from_road = orient.rot_from_euler([roll, pitch, yaw]).dot(np.diag([1, -1, -1])) - view_from_road = view_frame_from_device_frame.dot(device_from_road) - return np.hstack((view_from_road, [[0], [height], [0]])) - - - -# aka 'extrinsic_matrix' -def get_view_frame_from_calib_frame(roll, pitch, yaw, height): - device_from_calib= orient.rot_from_euler([roll, pitch, yaw]) - view_from_calib = view_frame_from_device_frame.dot(device_from_calib) - return np.hstack((view_from_calib, [[0], [height], [0]])) - - -def vp_from_ke(m): - """ - Computes the vanishing point from the product of the intrinsic and extrinsic - matrices C = KE. - - The vanishing point is defined as lim x->infinity C (x, 0, 0, 1).T - """ - return (m[0, 0]/m[2, 0], m[1, 0]/m[2, 0]) - - -def roll_from_ke(m): - # note: different from calibration.h/RollAnglefromKE: i think that one's just wrong - return np.arctan2(-(m[1, 0] - m[1, 1] * m[2, 0] / m[2, 1]), - -(m[0, 0] - m[0, 1] * m[2, 0] / m[2, 1])) - - -def normalize(img_pts, intrinsics): - # normalizes image coordinates - # accepts single pt or array of pts - intrinsics_inv = np.linalg.inv(intrinsics) - img_pts = np.array(img_pts) - input_shape = img_pts.shape - img_pts = np.atleast_2d(img_pts) - img_pts = np.hstack((img_pts, np.ones((img_pts.shape[0], 1)))) - img_pts_normalized = img_pts.dot(intrinsics_inv.T) - img_pts_normalized[(img_pts < 0).any(axis=1)] = np.nan - return img_pts_normalized[:, :2].reshape(input_shape) - - -def denormalize(img_pts, intrinsics, width=np.inf, height=np.inf): - # denormalizes image coordinates - # accepts single pt or array of pts - img_pts = np.array(img_pts) - input_shape = img_pts.shape - img_pts = np.atleast_2d(img_pts) - img_pts = np.hstack((img_pts, np.ones((img_pts.shape[0], 1), dtype=img_pts.dtype))) - img_pts_denormalized = img_pts.dot(intrinsics.T) - if np.isfinite(width): - img_pts_denormalized[img_pts_denormalized[:, 0] > width] = np.nan - img_pts_denormalized[img_pts_denormalized[:, 0] < 0] = np.nan - if np.isfinite(height): - img_pts_denormalized[img_pts_denormalized[:, 1] > height] = np.nan - img_pts_denormalized[img_pts_denormalized[:, 1] < 0] = np.nan - return img_pts_denormalized[:, :2].reshape(input_shape) - - -def get_calib_from_vp(vp, intrinsics): - vp_norm = normalize(vp, intrinsics) - yaw_calib = np.arctan(vp_norm[0]) - pitch_calib = -np.arctan(vp_norm[1]*np.cos(yaw_calib)) - roll_calib = 0 - return roll_calib, pitch_calib, yaw_calib - - -def device_from_ecef(pos_ecef, orientation_ecef, pt_ecef): - # device from ecef frame - # device frame is x -> forward, y-> right, z -> down - # accepts single pt or array of pts - input_shape = pt_ecef.shape - pt_ecef = np.atleast_2d(pt_ecef) - ecef_from_device_rot = orient.rotations_from_quats(orientation_ecef) - device_from_ecef_rot = ecef_from_device_rot.T - pt_ecef_rel = pt_ecef - pos_ecef - pt_device = np.einsum('jk,ik->ij', device_from_ecef_rot, pt_ecef_rel) - return pt_device.reshape(input_shape) - - -def img_from_device(pt_device): - # img coordinates from pts in device frame - # first transforms to view frame, then to img coords - # accepts single pt or array of pts - input_shape = pt_device.shape - pt_device = np.atleast_2d(pt_device) - pt_view = np.einsum('jk,ik->ij', view_frame_from_device_frame, pt_device) - - # This function should never return negative depths - pt_view[pt_view[:, 2] < 0] = np.nan - - pt_img = pt_view/pt_view[:, 2:3] - return pt_img.reshape(input_shape)[:, :2] - diff --git a/common/transformations/transformations.pxd b/common/transformations/transformations.pxd deleted file mode 100644 index fe32e18dea..0000000000 --- a/common/transformations/transformations.pxd +++ /dev/null @@ -1,72 +0,0 @@ -# cython: language_level=3 -from libcpp cimport bool - -cdef extern from "orientation.cc": - pass - -cdef extern from "orientation.hpp": - cdef cppclass Quaternion "Eigen::Quaterniond": - Quaternion() - Quaternion(double, double, double, double) - double w() - double x() - double y() - double z() - - cdef cppclass Vector3 "Eigen::Vector3d": - Vector3() - Vector3(double, double, double) - double operator()(int) - - cdef cppclass Matrix3 "Eigen::Matrix3d": - Matrix3() - Matrix3(double*) - - double operator()(int, int) - - Quaternion euler2quat(const Vector3 &) - Vector3 quat2euler(const Quaternion &) - Matrix3 quat2rot(const Quaternion &) - Quaternion rot2quat(const Matrix3 &) - Vector3 rot2euler(const Matrix3 &) - Matrix3 euler2rot(const Vector3 &) - Matrix3 rot_matrix(double, double, double) - Vector3 ecef_euler_from_ned(const ECEF &, const Vector3 &) - Vector3 ned_euler_from_ecef(const ECEF &, const Vector3 &) - - -cdef extern from "coordinates.cc": - cdef struct ECEF: - double x - double y - double z - - cdef struct NED: - double n - double e - double d - - cdef struct Geodetic: - double lat - double lon - double alt - bool radians - - ECEF geodetic2ecef(const Geodetic &) - Geodetic ecef2geodetic(const ECEF &) - - cdef cppclass LocalCoord_c "LocalCoord": - Matrix3 ned2ecef_matrix - Matrix3 ecef2ned_matrix - - LocalCoord_c(const Geodetic &, const ECEF &) - LocalCoord_c(const Geodetic &) - LocalCoord_c(const ECEF &) - - NED ecef2ned(const ECEF &) - ECEF ned2ecef(const NED &) - NED geodetic2ned(const Geodetic &) - Geodetic ned2geodetic(const NED &) - -cdef extern from "coordinates.hpp": - pass diff --git a/common/transformations/transformations.pyx b/common/transformations/transformations.pyx deleted file mode 100644 index ae045c369d..0000000000 --- a/common/transformations/transformations.pyx +++ /dev/null @@ -1,173 +0,0 @@ -# distutils: language = c++ -# cython: language_level = 3 -from openpilot.common.transformations.transformations cimport Matrix3, Vector3, Quaternion -from openpilot.common.transformations.transformations cimport ECEF, NED, Geodetic - -from openpilot.common.transformations.transformations cimport euler2quat as euler2quat_c -from openpilot.common.transformations.transformations cimport quat2euler as quat2euler_c -from openpilot.common.transformations.transformations cimport quat2rot as quat2rot_c -from openpilot.common.transformations.transformations cimport rot2quat as rot2quat_c -from openpilot.common.transformations.transformations cimport euler2rot as euler2rot_c -from openpilot.common.transformations.transformations cimport rot2euler as rot2euler_c -from openpilot.common.transformations.transformations cimport rot_matrix as rot_matrix_c -from openpilot.common.transformations.transformations cimport ecef_euler_from_ned as ecef_euler_from_ned_c -from openpilot.common.transformations.transformations cimport ned_euler_from_ecef as ned_euler_from_ecef_c -from openpilot.common.transformations.transformations cimport geodetic2ecef as geodetic2ecef_c -from openpilot.common.transformations.transformations cimport ecef2geodetic as ecef2geodetic_c -from openpilot.common.transformations.transformations cimport LocalCoord_c - - -import numpy as np -cimport numpy as np - -cdef np.ndarray[double, ndim=2] matrix2numpy(Matrix3 m): - return np.array([ - [m(0, 0), m(0, 1), m(0, 2)], - [m(1, 0), m(1, 1), m(1, 2)], - [m(2, 0), m(2, 1), m(2, 2)], - ]) - -cdef Matrix3 numpy2matrix(np.ndarray[double, ndim=2, mode="fortran"] m): - assert m.shape[0] == 3 - assert m.shape[1] == 3 - return Matrix3(m.data) - -cdef ECEF list2ecef(ecef): - cdef ECEF e - e.x = ecef[0] - e.y = ecef[1] - e.z = ecef[2] - return e - -cdef NED list2ned(ned): - cdef NED n - n.n = ned[0] - n.e = ned[1] - n.d = ned[2] - return n - -cdef Geodetic list2geodetic(geodetic): - cdef Geodetic g - g.lat = geodetic[0] - g.lon = geodetic[1] - g.alt = geodetic[2] - return g - -def euler2quat_single(euler): - cdef Vector3 e = Vector3(euler[0], euler[1], euler[2]) - cdef Quaternion q = euler2quat_c(e) - return [q.w(), q.x(), q.y(), q.z()] - -def quat2euler_single(quat): - cdef Quaternion q = Quaternion(quat[0], quat[1], quat[2], quat[3]) - cdef Vector3 e = quat2euler_c(q) - return [e(0), e(1), e(2)] - -def quat2rot_single(quat): - cdef Quaternion q = Quaternion(quat[0], quat[1], quat[2], quat[3]) - cdef Matrix3 r = quat2rot_c(q) - return matrix2numpy(r) - -def rot2quat_single(rot): - cdef Matrix3 r = numpy2matrix(np.asfortranarray(rot, dtype=np.double)) - cdef Quaternion q = rot2quat_c(r) - return [q.w(), q.x(), q.y(), q.z()] - -def euler2rot_single(euler): - cdef Vector3 e = Vector3(euler[0], euler[1], euler[2]) - cdef Matrix3 r = euler2rot_c(e) - return matrix2numpy(r) - -def rot2euler_single(rot): - cdef Matrix3 r = numpy2matrix(np.asfortranarray(rot, dtype=np.double)) - cdef Vector3 e = rot2euler_c(r) - return [e(0), e(1), e(2)] - -def rot_matrix(roll, pitch, yaw): - return matrix2numpy(rot_matrix_c(roll, pitch, yaw)) - -def ecef_euler_from_ned_single(ecef_init, ned_pose): - cdef ECEF init = list2ecef(ecef_init) - cdef Vector3 pose = Vector3(ned_pose[0], ned_pose[1], ned_pose[2]) - - cdef Vector3 e = ecef_euler_from_ned_c(init, pose) - return [e(0), e(1), e(2)] - -def ned_euler_from_ecef_single(ecef_init, ecef_pose): - cdef ECEF init = list2ecef(ecef_init) - cdef Vector3 pose = Vector3(ecef_pose[0], ecef_pose[1], ecef_pose[2]) - - cdef Vector3 e = ned_euler_from_ecef_c(init, pose) - return [e(0), e(1), e(2)] - -def geodetic2ecef_single(geodetic): - cdef Geodetic g = list2geodetic(geodetic) - cdef ECEF e = geodetic2ecef_c(g) - return [e.x, e.y, e.z] - -def ecef2geodetic_single(ecef): - cdef ECEF e = list2ecef(ecef) - cdef Geodetic g = ecef2geodetic_c(e) - return [g.lat, g.lon, g.alt] - - -cdef class LocalCoord: - cdef LocalCoord_c * lc - - def __init__(self, geodetic=None, ecef=None): - assert (geodetic is not None) or (ecef is not None) - if geodetic is not None: - self.lc = new LocalCoord_c(list2geodetic(geodetic)) - elif ecef is not None: - self.lc = new LocalCoord_c(list2ecef(ecef)) - - @property - def ned2ecef_matrix(self): - return matrix2numpy(self.lc.ned2ecef_matrix) - - @property - def ecef2ned_matrix(self): - return matrix2numpy(self.lc.ecef2ned_matrix) - - @property - def ned_from_ecef_matrix(self): - return self.ecef2ned_matrix - - @property - def ecef_from_ned_matrix(self): - return self.ned2ecef_matrix - - @classmethod - def from_geodetic(cls, geodetic): - return cls(geodetic=geodetic) - - @classmethod - def from_ecef(cls, ecef): - return cls(ecef=ecef) - - def ecef2ned_single(self, ecef): - assert self.lc - cdef ECEF e = list2ecef(ecef) - cdef NED n = self.lc.ecef2ned(e) - return [n.n, n.e, n.d] - - def ned2ecef_single(self, ned): - assert self.lc - cdef NED n = list2ned(ned) - cdef ECEF e = self.lc.ned2ecef(n) - return [e.x, e.y, e.z] - - def geodetic2ned_single(self, geodetic): - assert self.lc - cdef Geodetic g = list2geodetic(geodetic) - cdef NED n = self.lc.geodetic2ned(g) - return [n.n, n.e, n.d] - - def ned2geodetic_single(self, ned): - assert self.lc - cdef NED n = list2ned(ned) - cdef Geodetic g = self.lc.ned2geodetic(n) - return [g.lat, g.lon, g.alt] - - def __dealloc__(self): - del self.lc diff --git a/common/util.cc b/common/util.cc deleted file mode 100644 index a853faed04..0000000000 --- a/common/util.cc +++ /dev/null @@ -1,309 +0,0 @@ -#include "common/util.h" - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef __linux__ -#include -#include -#ifndef __USE_GNU -#define __USE_GNU -#endif -#include -#endif // __linux__ - -namespace util { - -void set_thread_name(const char* name) { -#ifdef __linux__ - // pthread_setname_np is dumb (fails instead of truncates) - prctl(PR_SET_NAME, (unsigned long)name, 0, 0, 0); -#endif -} - -int set_realtime_priority(int level) { -#ifdef __linux__ - long tid = syscall(SYS_gettid); - - // should match python using chrt - struct sched_param sa; - memset(&sa, 0, sizeof(sa)); - sa.sched_priority = level; - return sched_setscheduler(tid, SCHED_FIFO, &sa); -#else - return -1; -#endif -} - -int set_core_affinity(std::vector cores) { -#ifdef __linux__ - long tid = syscall(SYS_gettid); - cpu_set_t cpu; - - CPU_ZERO(&cpu); - for (const int n : cores) { - CPU_SET(n, &cpu); - } - return sched_setaffinity(tid, sizeof(cpu), &cpu); -#else - return -1; -#endif -} - -int set_file_descriptor_limit(uint64_t limit_val) { - struct rlimit limit; - int status; - - if ((status = getrlimit(RLIMIT_NOFILE, &limit)) < 0) - return status; - - limit.rlim_cur = limit_val; - if ((status = setrlimit(RLIMIT_NOFILE, &limit)) < 0) - return status; - - return 0; -} - -std::string read_file(const std::string& fn) { - std::ifstream f(fn, std::ios::binary | std::ios::in); - if (f.is_open()) { - f.seekg(0, std::ios::end); - int size = f.tellg(); - if (f.good() && size > 0) { - std::string result(size, '\0'); - f.seekg(0, std::ios::beg); - f.read(result.data(), size); - // return either good() or has reached end-of-file (e.g. /sys/power/wakeup_count) - if (f.good() || f.eof()) { - result.resize(f.gcount()); - return result; - } - } - // fallback for files created on read, e.g. procfs - std::stringstream buffer; - buffer << f.rdbuf(); - return buffer.str(); - } - return std::string(); -} - -std::map read_files_in_dir(const std::string &path) { - std::map ret; - DIR *d = opendir(path.c_str()); - if (!d) return ret; - - struct dirent *de = NULL; - while ((de = readdir(d))) { - if (de->d_type != DT_DIR) { - ret[de->d_name] = util::read_file(path + "/" + de->d_name); - } - } - - closedir(d); - return ret; -} - -int write_file(const char* path, const void* data, size_t size, int flags, mode_t mode) { - int fd = HANDLE_EINTR(open(path, flags, mode)); - if (fd == -1) { - return -1; - } - ssize_t n = HANDLE_EINTR(write(fd, data, size)); - close(fd); - return (n >= 0 && (size_t)n == size) ? 0 : -1; -} - -FILE* safe_fopen(const char* filename, const char* mode) { - FILE* fp = NULL; - do { - fp = fopen(filename, mode); - } while ((nullptr == fp) && (errno == EINTR)); - return fp; -} - -size_t safe_fwrite(const void* ptr, size_t size, size_t count, FILE* stream) { - size_t written = 0; - do { - size_t ret = ::fwrite((void*)((char *)ptr + written * size), size, count - written, stream); - if (ret == 0 && errno != EINTR) break; - written += ret; - } while (written != count); - return written; -} - -int safe_fflush(FILE *stream) { - int ret = EOF; - do { - ret = fflush(stream); - } while ((EOF == ret) && (errno == EINTR)); - return ret; -} - -int safe_ioctl(int fd, unsigned long request, void *argp) { - int ret; - do { - ret = ioctl(fd, request, argp); - } while ((ret == -1) && (errno == EINTR)); - return ret; -} - -std::string readlink(const std::string &path) { - char buff[4096]; - ssize_t len = ::readlink(path.c_str(), buff, sizeof(buff)-1); - if (len != -1) { - buff[len] = '\0'; - return std::string(buff); - } - return ""; -} - -bool file_exists(const std::string& fn) { - struct stat st = {}; - return stat(fn.c_str(), &st) != -1; -} - -static bool createDirectory(std::string dir, mode_t mode) { - auto verify_dir = [](const std::string& dir) -> bool { - struct stat st = {}; - return (stat(dir.c_str(), &st) == 0 && (st.st_mode & S_IFMT) == S_IFDIR); - }; - // remove trailing /'s - while (dir.size() > 1 && dir.back() == '/') { - dir.pop_back(); - } - // try to mkdir this directory - if (mkdir(dir.c_str(), mode) == 0) return true; - if (errno == EEXIST) return verify_dir(dir); - if (errno != ENOENT) return false; - - // mkdir failed because the parent dir doesn't exist, so try to create it - size_t slash = dir.rfind('/'); - if ((slash == std::string::npos || slash < 1) || - !createDirectory(dir.substr(0, slash), mode)) { - return false; - } - - // try again - if (mkdir(dir.c_str(), mode) == 0) return true; - return errno == EEXIST && verify_dir(dir); -} - -bool create_directories(const std::string& dir, mode_t mode) { - if (dir.empty()) return false; - return createDirectory(dir, mode); -} - -std::string getenv(const char* key, std::string default_val) { - const char* val = ::getenv(key); - return val ? val : default_val; -} - -int getenv(const char* key, int default_val) { - const char* val = ::getenv(key); - return val ? atoi(val) : default_val; -} - -float getenv(const char* key, float default_val) { - const char* val = ::getenv(key); - return val ? atof(val) : default_val; -} - -std::string hexdump(const uint8_t* in, const size_t size) { - std::stringstream ss; - ss << std::hex << std::setfill('0'); - for (size_t i = 0; i < size; i++) { - ss << std::setw(2) << static_cast(in[i]); - } - return ss.str(); -} - -int random_int(int min, int max) { - std::random_device dev; - std::mt19937 rng(dev()); - std::uniform_int_distribution dist(min, max); - return dist(rng); -} - -std::string random_string(std::string::size_type length) { - const std::string chrs = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; - std::mt19937 rg{std::random_device{}()}; - std::uniform_int_distribution pick(0, chrs.length() - 1); - std::string s; - s.reserve(length); - while (length--) { - s += chrs[pick(rg)]; - } - return s; -} - -bool starts_with(const std::string &s1, const std::string &s2) { - return strncmp(s1.c_str(), s2.c_str(), s2.size()) == 0; -} - -bool ends_with(const std::string& s, const std::string& suffix) { - return s.size() >= suffix.size() && - strcmp(s.c_str() + (s.size() - suffix.size()), suffix.c_str()) == 0; -} - -std::string strip(const std::string &str) { - auto should_trim = [](unsigned char ch) { - return std::isspace(ch) || ch == '\0'; - }; - - size_t start = 0; - while (start < str.size() && should_trim(static_cast(str[start]))) { - start++; - } - - if (start == str.size()) { - return ""; - } - - size_t end = str.size() - 1; - while (end > 0 && should_trim(static_cast(str[end]))) { - end--; - } - - return str.substr(start, end - start + 1); -} - -std::string check_output(const std::string& command) { - char buffer[128]; - std::string result; - std::unique_ptr pipe(popen(command.c_str(), "r"), pclose); - - if (!pipe) { - return ""; - } - - while (fgets(buffer, std::size(buffer), pipe.get()) != nullptr) { - result += std::string(buffer); - } - - return result; -} - -bool system_time_valid() { - // Default to August 26, 2024 - tm min_tm = {.tm_year = 2024 - 1900, .tm_mon = 7, .tm_mday = 26}; - time_t min_date = mktime(&min_tm); - - struct stat st; - if (stat("/lib/systemd/systemd", &st) == 0) { - min_date = std::max(min_date, st.st_mtime + 86400); // Add 1 day (86400 seconds) - } - - return time(nullptr) > min_date; -} - -} // namespace util diff --git a/common/util.h b/common/util.h deleted file mode 100644 index 4fb4b13fae..0000000000 --- a/common/util.h +++ /dev/null @@ -1,187 +0,0 @@ -#pragma once - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// keep trying if x gets interrupted by a signal -#define HANDLE_EINTR(x) \ - ({ \ - decltype(x) ret_; \ - int try_cnt = 0; \ - do { \ - ret_ = (x); \ - } while (ret_ == -1 && errno == EINTR && try_cnt++ < 100); \ - ret_; \ - }) - -#ifndef sighandler_t -typedef void (*sighandler_t)(int sig); -#endif - -const double MILE_TO_KM = 1.609344; -const double KM_TO_MILE = 1. / MILE_TO_KM; -const double MS_TO_KPH = 3.6; -const double MS_TO_MPH = MS_TO_KPH * KM_TO_MILE; -const double METER_TO_MILE = KM_TO_MILE / 1000.0; -const double METER_TO_FOOT = 3.28084; - -#define ALIGNED_SIZE(x, align) (((x) + (align)-1) & ~((align)-1)) - -namespace util { - -void set_thread_name(const char* name); -int set_realtime_priority(int level); -int set_core_affinity(std::vector cores); -int set_file_descriptor_limit(uint64_t limit); - -// ***** math helpers ***** - -// map x from [a1, a2] to [b1, b2] -template -T map_val(T x, T a1, T a2, T b1, T b2) { - x = std::clamp(x, a1, a2); - T ra = a2 - a1; - T rb = b2 - b1; - return (x - a1) * rb / ra + b1; -} - -// ***** string helpers ***** - -template -std::string string_format(const std::string& format, Args... args) { - size_t size = snprintf(nullptr, 0, format.c_str(), args...) + 1; - std::unique_ptr buf(new char[size]); - snprintf(buf.get(), size, format.c_str(), args...); - return std::string(buf.get(), buf.get() + size - 1); -} - -std::string getenv(const char* key, std::string default_val = ""); -int getenv(const char* key, int default_val); -float getenv(const char* key, float default_val); - -std::string hexdump(const uint8_t* in, const size_t size); -bool starts_with(const std::string &s1, const std::string &s2); -bool ends_with(const std::string &s, const std::string &suffix); -std::string strip(const std::string &str); - -// ***** random helpers ***** -int random_int(int min, int max); -std::string random_string(std::string::size_type length); - -// **** file helpers ***** -std::string read_file(const std::string& fn); -std::map read_files_in_dir(const std::string& path); -int write_file(const char* path, const void* data, size_t size, int flags = O_WRONLY, mode_t mode = 0664); - -FILE* safe_fopen(const char* filename, const char* mode); -size_t safe_fwrite(const void * ptr, size_t size, size_t count, FILE * stream); -int safe_fflush(FILE *stream); -int safe_ioctl(int fd, unsigned long request, void *argp); - -std::string readlink(const std::string& path); -bool file_exists(const std::string& fn); -bool create_directories(const std::string &dir, mode_t mode); - -std::string check_output(const std::string& command); - -bool system_time_valid(); - -inline void sleep_for(const int milliseconds) { - if (milliseconds > 0) { - std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds)); - } -} - -} // namespace util - -class ExitHandler { -public: - ExitHandler() { - std::signal(SIGINT, (sighandler_t)set_do_exit); - std::signal(SIGTERM, (sighandler_t)set_do_exit); - -#ifndef __APPLE__ - std::signal(SIGPWR, (sighandler_t)set_do_exit); -#endif - } - inline static std::atomic power_failure = false; - inline static std::atomic signal = 0; - inline operator bool() { return do_exit; } - inline ExitHandler& operator=(bool v) { - signal = 0; - do_exit = v; - return *this; - } -private: - static void set_do_exit(int sig) { -#ifndef __APPLE__ - power_failure = (sig == SIGPWR); -#endif - signal = sig; - do_exit = true; - } - inline static std::atomic do_exit = false; -}; - -struct unique_fd { - unique_fd(int fd = -1) : fd_(fd) {} - unique_fd& operator=(unique_fd&& uf) { - fd_ = uf.fd_; - uf.fd_ = -1; - return *this; - } - ~unique_fd() { - if (fd_ != -1) close(fd_); - } - operator int() const { return fd_; } - int fd_; -}; - -class FirstOrderFilter { -public: - FirstOrderFilter(float x0, float ts, float dt, bool initialized = true) { - k_ = (dt / ts) / (1.0 + dt / ts); - x_ = x0; - initialized_ = initialized; - } - inline float update(float x) { - if (initialized_) { - x_ = (1. - k_) * x_ + k_ * x; - } else { - initialized_ = true; - x_ = x; - } - return x_; - } - inline void reset(float x) { x_ = x; } - inline float x(){ return x_; } - -private: - float x_, k_; - bool initialized_; -}; - -template -void update_max_atomic(std::atomic& max, T const& value) { - T prev = max; - while (prev < value && !max.compare_exchange_weak(prev, value)) {} -} - -typedef struct Rect { - int x; - int y; - int w; - int h; -} Rect; diff --git a/common/util.py b/common/util.py deleted file mode 100644 index e6ddb46e7b..0000000000 --- a/common/util.py +++ /dev/null @@ -1,46 +0,0 @@ -import os -import subprocess - -def sudo_write(val: str, path: str) -> None: - try: - with open(path, 'w') as f: - f.write(str(val)) - except PermissionError: - os.system(f"sudo chmod a+w {path}") - try: - with open(path, 'w') as f: - f.write(str(val)) - except PermissionError: - # fallback for debugfs files - os.system(f"sudo su -c 'echo {val} > {path}'") - -def sudo_read(path: str) -> str: - try: - return subprocess.check_output(f"sudo cat {path}", shell=True, encoding='utf8').strip() - except Exception: - return "" - -class MovingAverage: - def __init__(self, window_size: int): - self.window_size: int = window_size - self.buffer: list[float] = [0.0] * window_size - self.index: int = 0 - self.count: int = 0 - self.sum: float = 0.0 - - def add_value(self, new_value: float): - # Update the sum: subtract the value being replaced and add the new value - self.sum -= self.buffer[self.index] - self.buffer[self.index] = new_value - self.sum += new_value - - # Update the index in a circular manner - self.index = (self.index + 1) % self.window_size - - # Track the number of added values (for partial windows) - self.count = min(self.count + 1, self.window_size) - - def get_average(self) -> float: - if self.count == 0: - return float('nan') - return self.sum / self.count diff --git a/common/version.h b/common/version.h deleted file mode 100644 index 67b69da7c7..0000000000 --- a/common/version.h +++ /dev/null @@ -1 +0,0 @@ -#define COMMA_VERSION "0.9.10" diff --git a/common/watchdog.cc b/common/watchdog.cc deleted file mode 100644 index 44e8c83e6d..0000000000 --- a/common/watchdog.cc +++ /dev/null @@ -1,12 +0,0 @@ -#include - -#include "common/watchdog.h" -#include "common/util.h" -#include "system/hardware/hw.h" - -const std::string watchdog_fn_prefix = Path::shm_path() + "/wd_"; // + - -bool watchdog_kick(uint64_t ts) { - static std::string fn = watchdog_fn_prefix + std::to_string(getpid()); - return util::write_file(fn.c_str(), &ts, sizeof(ts), O_WRONLY | O_CREAT) > 0; -} diff --git a/common/watchdog.h b/common/watchdog.h deleted file mode 100644 index 12dd2ca035..0000000000 --- a/common/watchdog.h +++ /dev/null @@ -1,5 +0,0 @@ -#pragma once - -#include - -bool watchdog_kick(uint64_t ts); diff --git a/common/watchdog.py b/common/watchdog.py deleted file mode 100644 index ddb6f744e9..0000000000 --- a/common/watchdog.py +++ /dev/null @@ -1,22 +0,0 @@ -import os -import time -import struct -from openpilot.system.hardware.hw import Paths - -WATCHDOG_FN = f"{Paths.shm_path()}/wd_" -_LAST_KICK = 0.0 - -def kick_watchdog(): - global _LAST_KICK - current_time = time.monotonic() - - if current_time - _LAST_KICK < 1.0: - return - - try: - with open(f"{WATCHDOG_FN}{os.getpid()}", 'wb') as f: - f.write(struct.pack('Hardware Needed
 |Video|Setup Video| |---|---|---|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:| -|Acura|ILX 2016-18|Technology Plus Package or AcuraWatch Plus|openpilot|26 mph|25 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Acura|ILX 2019|All|openpilot|26 mph|25 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Acura|RDX 2016-18|AcuraWatch Plus or Advance Package|openpilot|26 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Acura|RDX 2019-21|All|openpilot available[1](#footnotes)|0 mph|3 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Audi|A3 2014-19|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Audi|A3 Sportback e-tron 2017-18|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Audi|Q2 2018|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Audi|Q3 2019-24|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Audi|RS3 2018|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Audi|S3 2015-17|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Chevrolet|Bolt EUV 2022-23|Premier or Premier Redline Trim without Super Cruise Package|openpilot available[1](#footnotes)|3 mph|6 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 GM connector
- 1 comma 3X
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Chevrolet|Bolt EV 2022-23|2LT Trim with Adaptive Cruise Control Package|openpilot available[1](#footnotes)|3 mph|6 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 GM connector
- 1 comma 3X
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Chevrolet|Equinox 2019-22|Adaptive Cruise Control (ACC)|openpilot available[1](#footnotes)|3 mph|6 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 GM connector
- 1 comma 3X
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Chevrolet|Silverado 1500 2020-21|Safety Package II|openpilot available[1](#footnotes)|0 mph|6 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 GM connector
- 1 comma 3X
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Chevrolet|Trailblazer 2021-22|Adaptive Cruise Control (ACC)|openpilot available[1](#footnotes)|3 mph|6 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 GM connector
- 1 comma 3X
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Chrysler|Pacifica 2017-18|Adaptive Cruise Control (ACC)|Stock|0 mph|9 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 FCA connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Chrysler|Pacifica 2019-20|Adaptive Cruise Control (ACC)|Stock|0 mph|39 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 FCA connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Chrysler|Pacifica 2021-23|All|Stock|0 mph|39 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 FCA connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Chrysler|Pacifica Hybrid 2017-18|Adaptive Cruise Control (ACC)|Stock|0 mph|9 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 FCA connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Chrysler|Pacifica Hybrid 2019-24|Adaptive Cruise Control (ACC)|Stock|0 mph|39 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 FCA connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|comma|body|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|None||| -|CUPRA|Ateca 2018-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Dodge|Durango 2020-21|Adaptive Cruise Control (ACC)|Stock|0 mph|39 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 FCA connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Ford|Bronco Sport 2021-24|Co-Pilot360 Assist+|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 angled mount (8 degrees)
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Ford|Escape 2020-22|Co-Pilot360 Assist+|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Ford|Escape 2023-24|Co-Pilot360 Assist+|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q4 connector
- 1 USB-C coupler
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||https://www.youtube.com/watch?v=uUGkH6C_EQU| -|Ford|Escape Hybrid 2020-22|Co-Pilot360 Assist+|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Ford|Escape Hybrid 2023-24|Co-Pilot360 Assist+|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q4 connector
- 1 USB-C coupler
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||https://www.youtube.com/watch?v=uUGkH6C_EQU| -|Ford|Escape Plug-in Hybrid 2020-22|Co-Pilot360 Assist+|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Ford|Escape Plug-in Hybrid 2023-24|Co-Pilot360 Assist+|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q4 connector
- 1 USB-C coupler
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||https://www.youtube.com/watch?v=uUGkH6C_EQU| -|Ford|Expedition 2022-24|Co-Pilot360 Assist 2.0|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q4 connector
- 1 USB-C coupler
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||https://www.youtube.com/watch?v=MewJc9LYp9M| -|Ford|Explorer 2020-24|Co-Pilot360 Assist+|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Ford|Explorer Hybrid 2020-24|Co-Pilot360 Assist+|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Ford|F-150 2021-23|Co-Pilot360 Assist 2.0|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q4 connector
- 1 USB-C coupler
- 1 angled mount (8 degrees)
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||https://www.youtube.com/watch?v=MewJc9LYp9M| -|Ford|F-150 Hybrid 2021-23|Co-Pilot360 Assist 2.0|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q4 connector
- 1 USB-C coupler
- 1 angled mount (8 degrees)
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||https://www.youtube.com/watch?v=MewJc9LYp9M| -|Ford|Focus 2018[3](#footnotes)|Adaptive Cruise Control with Lane Centering|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Ford|Focus Hybrid 2018[3](#footnotes)|Adaptive Cruise Control with Lane Centering|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Ford|Kuga 2020-23|Adaptive Cruise Control with Lane Centering|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Ford|Kuga Hybrid 2020-23|Adaptive Cruise Control with Lane Centering|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Ford|Kuga Hybrid 2024|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q4 connector
- 1 USB-C coupler
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||https://www.youtube.com/watch?v=uUGkH6C_EQU| -|Ford|Kuga Plug-in Hybrid 2020-23|Adaptive Cruise Control with Lane Centering|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Ford|Kuga Plug-in Hybrid 2024|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q4 connector
- 1 USB-C coupler
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||https://www.youtube.com/watch?v=uUGkH6C_EQU| -|Ford|Maverick 2022|LARIAT Luxury|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 angled mount (8 degrees)
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Ford|Maverick 2023-24|Co-Pilot360 Assist|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 angled mount (8 degrees)
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Ford|Maverick Hybrid 2022|LARIAT Luxury|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 angled mount (8 degrees)
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Ford|Maverick Hybrid 2023-24|Co-Pilot360 Assist|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 angled mount (8 degrees)
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Ford|Mustang Mach-E 2021-24|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q4 connector
- 1 USB-C coupler
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||https://www.youtube.com/watch?v=uUGkH6C_EQU| -|Ford|Ranger 2024|Adaptive Cruise Control with Lane Centering|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q4 connector
- 1 USB-C coupler
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||https://www.youtube.com/watch?v=uUGkH6C_EQU| -|Genesis|G70 2018|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai F connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Genesis|G70 2019-21|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai F connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Genesis|G70 2022-23|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai L connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Genesis|G80 2017|All|Stock|19 mph|37 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Hyundai J connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Genesis|G80 2018-19|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai H connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Genesis|G80 (2.5T Advanced Trim, with HDA II) 2024[6](#footnotes)|Highway Driving Assist II|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai P connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Genesis|G90 2017-20|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai C connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Genesis|GV60 (Advanced Trim) 2023[6](#footnotes)|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Genesis|GV60 (Performance Trim) 2022-23[6](#footnotes)|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Genesis|GV70 (2.5T Trim, without HDA II) 2022-24[6](#footnotes)|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai L connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Genesis|GV70 (3.5T Trim, without HDA II) 2022-23[6](#footnotes)|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai M connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Genesis|GV70 Electrified (Australia Only) 2022[6](#footnotes)|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai Q connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Genesis|GV70 Electrified (with HDA II) 2023-24[6](#footnotes)|Highway Driving Assist II|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai Q connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Genesis|GV80 2023[6](#footnotes)|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai M connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|GMC|Sierra 1500 2020-21|Driver Alert Package II|openpilot available[1](#footnotes)|0 mph|6 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 GM connector
- 1 comma 3X
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Honda|Accord 2018-22|All|openpilot available[1](#footnotes)|0 mph|3 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Honda|Accord Hybrid 2018-22|All|openpilot available[1](#footnotes)|0 mph|3 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Honda|Civic 2016-18|Honda Sensing|openpilot|0 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Honda|Civic 2019-21|All|openpilot available[1](#footnotes)|0 mph|2 mph[5](#footnotes)|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Honda|Civic 2022-24|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch B connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Honda|Civic Hatchback 2017-21|Honda Sensing|openpilot available[1](#footnotes)|0 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Honda|Civic Hatchback 2022-24|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch B connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Honda|Civic Hatchback Hybrid 2025|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch B connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Honda|Civic Hatchback Hybrid (Europe only) 2023|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch B connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Honda|CR-V 2015-16|Touring Trim|openpilot|26 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Honda|CR-V 2017-22|Honda Sensing|openpilot available[1](#footnotes)|0 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Honda|CR-V Hybrid 2017-22|Honda Sensing|openpilot available[1](#footnotes)|0 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Honda|e 2020|All|openpilot available[1](#footnotes)|0 mph|3 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Honda|Fit 2018-20|Honda Sensing|openpilot|26 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Honda|Freed 2020|Honda Sensing|openpilot|26 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Honda|HR-V 2019-22|Honda Sensing|openpilot|26 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Honda|HR-V 2023-25|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch B connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Honda|Insight 2019-22|All|openpilot available[1](#footnotes)|0 mph|3 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Honda|Inspire 2018|All|openpilot available[1](#footnotes)|0 mph|3 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Honda|Odyssey 2018-20|Honda Sensing|openpilot|26 mph|0 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Honda|Passport 2019-25|All|openpilot|26 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Honda|Pilot 2016-22|Honda Sensing|openpilot|26 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Honda|Ridgeline 2017-25|Honda Sensing|openpilot|26 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Azera 2022|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Azera Hybrid 2019|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai C connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Azera Hybrid 2020|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Custin 2023|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Elantra 2017-18|Smart Cruise Control (SCC)|Stock|19 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Hyundai B connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Elantra 2019|Smart Cruise Control (SCC)|Stock|19 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Hyundai G connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Elantra 2021-23|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Elantra GT 2017-20|Smart Cruise Control (SCC)|Stock|0 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai E connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Elantra Hybrid 2021-23|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Genesis 2015-16|Smart Cruise Control (SCC)|Stock|19 mph|37 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Hyundai J connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|i30 2017-19|Smart Cruise Control (SCC)|Stock|0 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai E connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Ioniq 5 (Southeast Asia and Europe only) 2022-24[6](#footnotes)|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai Q connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Ioniq 5 (with HDA II) 2022-24[6](#footnotes)|Highway Driving Assist II|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai Q connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Ioniq 5 (without HDA II) 2022-24[6](#footnotes)|Highway Driving Assist|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Ioniq 6 (with HDA II) 2023-24[6](#footnotes)|Highway Driving Assist II|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai P connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Ioniq Electric 2019|Smart Cruise Control (SCC)|Stock|0 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai C connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Ioniq Electric 2020|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai H connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Ioniq Hybrid 2017-19|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai C connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Ioniq Hybrid 2020-22|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai H connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Ioniq Plug-in Hybrid 2019|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai C connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Ioniq Plug-in Hybrid 2020-22|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai H connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Kona 2020|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|6 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Hyundai B connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Kona Electric 2018-21|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai G connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Kona Electric 2022-23|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai O connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Kona Electric (with HDA II, Korea only) 2023[6](#footnotes)|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai R connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Kona Hybrid 2020|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai I connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Nexo 2021|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai H connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Palisade 2020-22|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai H connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Santa Cruz 2022-24[6](#footnotes)|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai N connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Santa Fe 2019-20|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai D connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Santa Fe 2021-23|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai L connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Santa Fe Hybrid 2022-23|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai L connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Santa Fe Plug-in Hybrid 2022-23|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai L connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Sonata 2018-19|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai E connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Sonata 2020-23|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Sonata Hybrid 2020-23|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Staria 2023[6](#footnotes)|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Tucson 2021|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Hyundai L connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Tucson 2022[6](#footnotes)|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai N connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Tucson 2023-24[6](#footnotes)|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai N connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Tucson Diesel 2019|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai L connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Tucson Hybrid 2022-24[6](#footnotes)|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai N connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Tucson Plug-in Hybrid 2024[6](#footnotes)|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai N connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Hyundai|Veloster 2019-20|Smart Cruise Control (SCC)|Stock|5 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Hyundai E connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Jeep|Grand Cherokee 2016-18|Adaptive Cruise Control (ACC)|Stock|0 mph|9 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 FCA connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Jeep|Grand Cherokee 2019-21|Adaptive Cruise Control (ACC)|Stock|0 mph|39 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 FCA connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Kia|Carnival 2022-24[6](#footnotes)|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Kia|Carnival (China only) 2023[6](#footnotes)|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Kia|Ceed 2019-21|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai E connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Kia|EV6 (Southeast Asia only) 2022-24[6](#footnotes)|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai P connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Kia|EV6 (with HDA II) 2022-24[6](#footnotes)|Highway Driving Assist II|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai P connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Kia|EV6 (without HDA II) 2022-24[6](#footnotes)|Highway Driving Assist|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai L connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Kia|Forte 2019-21|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|6 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Hyundai G connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Kia|Forte 2022-23|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai E connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Kia|K5 2021-24|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Kia|K5 Hybrid 2020-22|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Kia|K8 Hybrid (with HDA II) 2023[6](#footnotes)|Highway Driving Assist II|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai Q connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Kia|Niro EV 2019|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai H connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Kia|Niro EV 2020|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai F connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Kia|Niro EV 2021|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai C connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Kia|Niro EV 2022|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai H connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Kia|Niro EV (with HDA II) 2025[6](#footnotes)|Highway Driving Assist II|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai R connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Kia|Niro EV (without HDA II) 2023-25[6](#footnotes)|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Kia|Niro Hybrid 2018|All|Stock|10 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Hyundai C connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Kia|Niro Hybrid 2021|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai D connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Kia|Niro Hybrid 2022|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai F connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Kia|Niro Hybrid 2023[6](#footnotes)|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Kia|Niro Plug-in Hybrid 2018-19|All|Stock|10 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Hyundai C connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Kia|Niro Plug-in Hybrid 2020|Smart Cruise Control (SCC)|Stock|0 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai D connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Kia|Niro Plug-in Hybrid 2021|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai D connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Kia|Niro Plug-in Hybrid 2022|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai F connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Kia|Optima 2017|Advanced Smart Cruise Control|Stock|0 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai B connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Kia|Optima 2019-20|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai G connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Kia|Optima Hybrid 2019|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai H connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Kia|Seltos 2021|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Kia|Sorento 2018|Advanced Smart Cruise Control & LKAS|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai E connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Kia|Sorento 2019|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai E connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Kia|Sorento 2021-23[6](#footnotes)|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Kia|Sorento Hybrid 2021-23[6](#footnotes)|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Kia|Sorento Plug-in Hybrid 2022-23[6](#footnotes)|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Kia|Sportage 2023-24[6](#footnotes)|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai N connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Kia|Sportage Hybrid 2023[6](#footnotes)|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai N connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Kia|Stinger 2018-20|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai C connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Kia|Stinger 2022-23|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Kia|Telluride 2020-22|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai H connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Lexus|CT Hybrid 2017-18|Lexus Safety System+|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Lexus|ES 2017-18|All|openpilot available[2](#footnotes)|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Lexus|ES 2019-25|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Lexus|ES Hybrid 2017-18|All|openpilot available[2](#footnotes)|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Lexus|ES Hybrid 2019-25|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Lexus|GS F 2016|All|Stock|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Lexus|IS 2017-19|All|Stock|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Lexus|IS 2022-24|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Lexus|LC 2024|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Lexus|NX 2018-19|All|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Lexus|NX 2020-21|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Lexus|NX Hybrid 2018-19|All|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Lexus|NX Hybrid 2020-21|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Lexus|RC 2018-20|All|Stock|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Lexus|RC 2023|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Lexus|RX 2016|Lexus Safety System+|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Lexus|RX 2017-19|All|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Lexus|RX 2020-22|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Lexus|RX Hybrid 2016|Lexus Safety System+|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Lexus|RX Hybrid 2017-19|All|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Lexus|RX Hybrid 2020-22|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Lexus|UX Hybrid 2019-24|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Lincoln|Aviator 2020-24|Co-Pilot360 Plus|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Lincoln|Aviator Plug-in Hybrid 2020-24|Co-Pilot360 Plus|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|MAN|eTGE 2020-24|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|31 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 angled mount (8 degrees)
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|MAN|TGE 2017-24|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|31 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 angled mount (8 degrees)
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Mazda|CX-5 2022-25|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Mazda connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Mazda|CX-9 2021-23|All|Stock|0 mph|28 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Mazda connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Nissan[7](#footnotes)|Altima 2019-20|ProPILOT Assist|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Nissan B connector
- 1 USB-C coupler
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Nissan[7](#footnotes)|Leaf 2018-23|ProPILOT Assist|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Nissan A connector
- 1 USB-C coupler
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Nissan[7](#footnotes)|Rogue 2018-20|ProPILOT Assist|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Nissan A connector
- 1 USB-C coupler
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Nissan[7](#footnotes)|X-Trail 2017|ProPILOT Assist|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Nissan A connector
- 1 USB-C coupler
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Ram|1500 2019-24|Adaptive Cruise Control (ACC)|Stock|0 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ram connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Rivian|R1S 2022-24|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Rivian A connector
- 1 USB-C coupler
- 1 angled mount (8 degrees)
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||https://youtu.be/uaISd1j7Z4U| -|Rivian|R1T 2022-24|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Rivian A connector
- 1 USB-C coupler
- 1 angled mount (8 degrees)
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||https://youtu.be/uaISd1j7Z4U| -|SEAT|Ateca 2016-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|SEAT|Leon 2014-20|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Subaru|Ascent 2019-21|All[8](#footnotes)|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Subaru A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
||| -|Subaru|Crosstrek 2018-19|EyeSight Driver Assistance[8](#footnotes)|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Subaru A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
||| -|Subaru|Crosstrek 2020-23|EyeSight Driver Assistance[8](#footnotes)|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Subaru A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
||| -|Subaru|Forester 2019-21|All[8](#footnotes)|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Subaru A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
||| -|Subaru|Impreza 2017-19|EyeSight Driver Assistance[8](#footnotes)|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Subaru A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
||| -|Subaru|Impreza 2020-22|EyeSight Driver Assistance[8](#footnotes)|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Subaru A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
||| -|Subaru|Legacy 2020-22|All[8](#footnotes)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Subaru B connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
||| -|Subaru|Outback 2020-22|All[8](#footnotes)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Subaru B connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
||| -|Subaru|XV 2018-19|EyeSight Driver Assistance[8](#footnotes)|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Subaru A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
||| -|Subaru|XV 2020-21|EyeSight Driver Assistance[8](#footnotes)|openpilot available[1,9](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Subaru A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
||| -|Škoda|Fabia 2022-23[15](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
[17](#footnotes)||| -|Škoda|Kamiq 2021-23[13,15](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
[17](#footnotes)||| -|Škoda|Karoq 2019-23[15](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Škoda|Kodiaq 2017-23[15](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Škoda|Octavia 2015-19[15](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Škoda|Octavia RS 2016[15](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Škoda|Octavia Scout 2017-19[15](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Škoda|Scala 2020-23[15](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
[17](#footnotes)||| -|Škoda|Superb 2015-22[15](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Tesla[11](#footnotes)|Model 3 (with HW3) 2019-23[10](#footnotes)|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Tesla A connector
- 1 USB-C coupler
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Tesla[11](#footnotes)|Model 3 (with HW4) 2024-25[10](#footnotes)|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Tesla B connector
- 1 USB-C coupler
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Tesla[11](#footnotes)|Model Y (with HW3) 2020-23[10](#footnotes)|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Tesla A connector
- 1 USB-C coupler
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Tesla[11](#footnotes)|Model Y (with HW4) 2024[10](#footnotes)|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Tesla B connector
- 1 USB-C coupler
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|Alphard 2019-20|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|Alphard Hybrid 2021|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|Avalon 2016|Toyota Safety Sense P|openpilot available[2](#footnotes)|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|Avalon 2017-18|All|openpilot available[2](#footnotes)|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|Avalon 2019-21|All|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|Avalon 2022|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|Avalon Hybrid 2019-21|All|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|Avalon Hybrid 2022|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|C-HR 2017-20|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|C-HR 2021|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|C-HR Hybrid 2017-20|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|C-HR Hybrid 2021-22|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|Camry 2018-20|All|Stock|0 mph[12](#footnotes)|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|Camry 2021-24|All|openpilot|0 mph[12](#footnotes)|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|Camry Hybrid 2018-20|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|Camry Hybrid 2021-24|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|Corolla 2017-19|All|openpilot available[2](#footnotes)|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|Corolla 2020-22|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|Corolla Cross (Non-US only) 2020-23|All|openpilot|17 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|Corolla Cross Hybrid (Non-US only) 2020-22|All|openpilot|17 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|Corolla Hatchback 2019-22|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|Corolla Hybrid 2020-22|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|Corolla Hybrid (South America only) 2020-23|All|openpilot|17 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|Highlander 2017-19|All|openpilot available[2](#footnotes)|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|Highlander 2020-23|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|Highlander Hybrid 2017-19|All|openpilot available[2](#footnotes)|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|Highlander Hybrid 2020-23|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|Mirai 2021|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|Prius 2016|Toyota Safety Sense P|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|Prius 2017-20|All|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|Prius 2021-22|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|Prius Prime 2017-20|All|openpilot available[2](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|Prius Prime 2021-22|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|Prius v 2017|Toyota Safety Sense P|openpilot available[2](#footnotes)|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|RAV4 2016|Toyota Safety Sense P|openpilot available[2](#footnotes)|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|RAV4 2017-18|All|openpilot available[2](#footnotes)|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|RAV4 2019-21|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|RAV4 2022|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|RAV4 2023-25|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|RAV4 Hybrid 2016|Toyota Safety Sense P|openpilot available[2](#footnotes)|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|RAV4 Hybrid 2017-18|All|openpilot available[2](#footnotes)|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|RAV4 Hybrid 2019-21|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|RAV4 Hybrid 2022|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|RAV4 Hybrid 2023-25|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Toyota|Sienna 2018-20|All|openpilot available[2](#footnotes)|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Toyota A connector
- 1 comma 3X
- 1 comma power v3
- 1 harness box
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Volkswagen|Arteon 2018-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Volkswagen|Arteon eHybrid 2020-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Volkswagen|Arteon R 2020-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Volkswagen|Arteon Shooting Brake 2020-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Volkswagen|Atlas 2018-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Volkswagen|Atlas Cross Sport 2020-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Volkswagen|California 2021-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|31 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 angled mount (8 degrees)
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Volkswagen|Caravelle 2020|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|31 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 angled mount (8 degrees)
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Volkswagen|CC 2018-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Volkswagen|Crafter 2017-24|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|31 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 angled mount (8 degrees)
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Volkswagen|e-Crafter 2018-24|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|31 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 angled mount (8 degrees)
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Volkswagen|e-Golf 2014-20|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Volkswagen|Golf 2015-20|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Volkswagen|Golf Alltrack 2015-19|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Volkswagen|Golf GTD 2015-20|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Volkswagen|Golf GTE 2015-20|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Volkswagen|Golf GTI 2015-21|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Volkswagen|Golf R 2015-19|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Volkswagen|Golf SportsVan 2015-20|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Volkswagen|Grand California 2019-24|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|31 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 angled mount (8 degrees)
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Volkswagen|Jetta 2018-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Volkswagen|Jetta GLI 2021-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Volkswagen|Passat 2015-22[14](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Volkswagen|Passat Alltrack 2015-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Volkswagen|Passat GTE 2015-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Volkswagen|Polo 2018-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
[17](#footnotes)||| -|Volkswagen|Polo GTI 2018-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
[17](#footnotes)||| -|Volkswagen|T-Cross 2021|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
[17](#footnotes)||| -|Volkswagen|T-Roc 2018-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Volkswagen|Taos 2022-24|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Volkswagen|Teramont 2018-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Volkswagen|Teramont Cross Sport 2021-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Volkswagen|Teramont X 2021-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Volkswagen|Tiguan 2018-24|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Volkswagen|Tiguan eHybrid 2021-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| -|Volkswagen|Touran 2016-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 USB-C coupler
- 1 VW J533 connector
- 1 comma 3X
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
- 1 right angle OBD-C cable (1.5 ft)
Buy Here
||| +|Acura|ILX 2016-18|Technology Plus Package or AcuraWatch Plus|openpilot|26 mph|25 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Acura|ILX 2019|All|openpilot|26 mph|25 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Acura|MDX 2022-24|All|openpilot available[1,5](#footnotes)|0 mph|43 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Acura|MDX 2025-26|All except Type S|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch C connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Acura|RDX 2016-18|AcuraWatch Plus or Advance Package|openpilot|26 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Acura|RDX 2019-21|All|openpilot available[1,5](#footnotes)|0 mph|3 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Acura|TLX 2021-22|All|openpilot available[1,5](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Acura|TLX 2025|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch C connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Audi[12](#footnotes)|A3 2014-19|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Audi[12](#footnotes)|A3 Sportback e-tron 2017-18|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Audi[12](#footnotes)|Q2 2018|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Audi[12](#footnotes)|Q3 2019-24|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Audi[12](#footnotes)|RS3 2018|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Audi[12](#footnotes)|S3 2015-17|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Chevrolet|Bolt EUV 2022-23|Premier or Premier Redline Trim, without Super Cruise Package|openpilot available[1](#footnotes)|3 mph|6 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 GM connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 harness box
- 1 mount
Buy Here
||| +|Chevrolet|Bolt EV 2022-23|2LT Trim with Adaptive Cruise Control Package|openpilot available[1](#footnotes)|3 mph|6 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 GM connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 harness box
- 1 mount
Buy Here
||| +|Chevrolet|Equinox 2019-22|Adaptive Cruise Control (ACC)|openpilot available[1](#footnotes)|3 mph|6 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 GM connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 harness box
- 1 mount
Buy Here
||| +|Chevrolet|Silverado 1500 2020-21|Safety Package II|openpilot available[1](#footnotes)|0 mph|6 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 GM connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 harness box
- 1 mount
Buy Here
||| +|Chevrolet|Trailblazer 2021-22|Adaptive Cruise Control (ACC)|openpilot available[1](#footnotes)|3 mph|6 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 GM connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 harness box
- 1 mount
Buy Here
||| +|Chrysler|Pacifica 2017-18|Adaptive Cruise Control (ACC)|Stock|0 mph|9 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 FCA connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Chrysler|Pacifica 2019-20|Adaptive Cruise Control (ACC)|Stock|0 mph|39 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 FCA connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Chrysler|Pacifica 2021-23|All|Stock|0 mph|39 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 FCA connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Chrysler|Pacifica Hybrid 2017-18|Adaptive Cruise Control (ACC)|Stock|0 mph|9 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 FCA connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Chrysler|Pacifica Hybrid 2019-25|Adaptive Cruise Control (ACC)|Stock|0 mph|39 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 FCA connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|comma|body|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|None||| +|CUPRA[12](#footnotes)|Ateca 2018-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Dodge|Durango 2020-21|Adaptive Cruise Control (ACC)|Stock|0 mph|39 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 FCA connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Ford|Bronco Sport 2021-24|Co-Pilot360 Assist+|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Ford|Escape 2020-22|Co-Pilot360 Assist+|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Ford|Escape 2023-24|Co-Pilot360 Assist+|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q4 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Ford|Escape Hybrid 2020-22|Co-Pilot360 Assist+|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Ford|Escape Hybrid 2023-24|Co-Pilot360 Assist+|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q4 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Ford|Escape Plug-in Hybrid 2020-22|Co-Pilot360 Assist+|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Ford|Escape Plug-in Hybrid 2023-24|Co-Pilot360 Assist+|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q4 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Ford|Expedition 2022-24|Co-Pilot360 Assist 2.0|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q4 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Ford|Explorer 2020-24|Co-Pilot360 Assist+|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Ford|Explorer Hybrid 2020-24|Co-Pilot360 Assist+|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Ford|F-150 2021-23|Co-Pilot360 Assist 2.0|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q4 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Ford|F-150 Hybrid 2021-23|Co-Pilot360 Assist 2.0|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q4 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Ford|Focus 2018-22[2](#footnotes)|Adaptive Cruise Control with Lane Centering|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Ford|Focus Hybrid 2018-22[2](#footnotes)|Adaptive Cruise Control with Lane Centering|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Ford|Kuga 2020-23|Adaptive Cruise Control with Lane Centering|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Ford|Kuga Hybrid 2020-23|Adaptive Cruise Control with Lane Centering|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Ford|Kuga Hybrid 2024|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q4 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Ford|Kuga Plug-in Hybrid 2020-23|Adaptive Cruise Control with Lane Centering|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Ford|Kuga Plug-in Hybrid 2024|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q4 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Ford|Maverick 2022|LARIAT Luxury|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Ford|Maverick 2023-24|Co-Pilot360 Assist|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Ford|Maverick Hybrid 2022|LARIAT Luxury|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Ford|Maverick Hybrid 2023-24|Co-Pilot360 Assist|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Ford|Mustang Mach-E 2021-24|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q4 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Ford|Ranger 2024|Adaptive Cruise Control with Lane Centering|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q4 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Genesis|G70 2018|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai F connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Genesis|G70 2019-21|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai F connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Genesis|G70 2022-23|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai L connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Genesis|G80 2017|All|Stock|19 mph|37 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Hyundai J connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Genesis|G80 2018-19|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai H connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Genesis|G80 (2.5T Advanced Trim, with HDA II) 2024|Highway Driving Assist II|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai P connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Genesis|G90 2017-20|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai C connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Genesis|GV60 (Advanced Trim) 2023|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Genesis|GV60 (Performance Trim) 2022-23|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Genesis|GV70 (2.5T Trim, without HDA II) 2022-24|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai L connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Genesis|GV70 (3.5T Trim, without HDA II) 2022-23|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai M connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Genesis|GV70 Electrified (Australia Only) 2022|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai Q connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Genesis|GV70 Electrified (with HDA II) 2023-24|Highway Driving Assist II|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai Q connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Genesis|GV80 2023|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai M connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|GMC|Sierra 1500 2020-21|Driver Alert Package II|openpilot available[1](#footnotes)|0 mph|6 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 GM connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Accord 2018-22|All|openpilot available[1,5](#footnotes)|0 mph|3 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Accord 2023-25|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch C connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Accord Hybrid 2018-22|All|openpilot available[1,5](#footnotes)|0 mph|3 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Accord Hybrid 2023-25|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch C connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|City (Brazil only) 2023|All|openpilot available[1,5](#footnotes)|0 mph|14 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch B connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Civic 2016-18|Honda Sensing|openpilot|0 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Civic 2019-21|All|openpilot available[1,5](#footnotes)|0 mph|2 mph[4](#footnotes)|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Civic 2022-24|All|openpilot available[1,5](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch B connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Civic Hatchback 2017-18|Honda Sensing|openpilot available[1,5](#footnotes)|0 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Civic Hatchback 2019-21|All|openpilot available[1,5](#footnotes)|0 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Civic Hatchback 2022-24|All|openpilot available[1,5](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch B connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Civic Hatchback Hybrid 2025-26|All|openpilot available[1,5](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch B connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Civic Hatchback Hybrid (Europe only) 2023|All|openpilot available[1,5](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch B connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Civic Hybrid 2025-26|All|openpilot available[1,5](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch B connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|CR-V 2015-16|Touring Trim|openpilot|26 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|CR-V 2017-22|Honda Sensing|openpilot available[1,5](#footnotes)|0 mph|15 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|CR-V 2023-26|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch C connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|CR-V Hybrid 2017-22|Honda Sensing|openpilot available[1,5](#footnotes)|0 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|CR-V Hybrid 2023-26|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch C connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|e 2020|All|openpilot available[1,5](#footnotes)|0 mph|3 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Fit 2018-20|Honda Sensing|openpilot|26 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Freed 2020|Honda Sensing|openpilot|26 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|HR-V 2019-22|Honda Sensing|openpilot|26 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|HR-V 2023-25|All|openpilot available[1,5](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch B connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Insight 2019-22|All|openpilot available[1,5](#footnotes)|0 mph|3 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Inspire 2018|All|openpilot available[1,5](#footnotes)|0 mph|3 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|N-Box 2018|All|openpilot available[1,5](#footnotes)|0 mph|11 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Odyssey 2018-20|Honda Sensing|openpilot|26 mph|0 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Odyssey 2021-26|All|openpilot available[1,5](#footnotes)|0 mph|43 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Odyssey (Singapore) 2021|Honda Sensing|openpilot|19 mph|0 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Odyssey (Taiwan) 2018-19|Honda Sensing|openpilot|19 mph|0 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Passport 2019-25|All|openpilot|26 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Passport 2026|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch C connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Pilot 2016-22|Honda Sensing|openpilot|26 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Pilot 2023-25|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Honda Bosch C connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Honda|Ridgeline 2017-25|Honda Sensing|openpilot|26 mph|12 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Honda Nidec connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Azera 2022|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Azera Hybrid 2019|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai C connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Azera Hybrid 2020|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Custin 2023|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Elantra 2017-18|Smart Cruise Control (SCC)|Stock|19 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Hyundai B connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Elantra 2019|Smart Cruise Control (SCC)|Stock|19 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Hyundai G connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Elantra 2021-23|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Elantra GT 2017-20|Smart Cruise Control (SCC)|Stock|0 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai E connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Elantra Hybrid 2021-23|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Genesis 2015-16|Smart Cruise Control (SCC)|Stock|19 mph|37 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Hyundai J connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|i30 2017-19|Smart Cruise Control (SCC)|Stock|0 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai E connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Ioniq 5 (Southeast Asia and Europe only) 2022-24|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai Q connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Ioniq 5 (with HDA II) 2022-24|Highway Driving Assist II|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai Q connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Ioniq 5 (without HDA II) 2022-24|Highway Driving Assist|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Ioniq 6 (with HDA II) 2023-24|Highway Driving Assist II|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai P connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Ioniq 6 (without HDA II) 2023-24|Highway Driving Assist|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai L connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Ioniq Electric 2019|Smart Cruise Control (SCC)|Stock|0 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai C connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Ioniq Electric 2020|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai H connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Ioniq Hybrid 2017-19|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai C connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Ioniq Hybrid 2020-22|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai H connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Ioniq Plug-in Hybrid 2019|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai C connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Ioniq Plug-in Hybrid 2020-22|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai H connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Kona 2020|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|6 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Hyundai B connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Kona 2022-23|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai O connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Kona Electric 2018-21|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai G connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Kona Electric 2022-23|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai O connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Kona Electric (with HDA II, Korea only) 2023|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai R connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Kona Hybrid 2020|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai I connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Nexo 2021|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai H connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Palisade 2020-22|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai H connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Santa Cruz 2022-24|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai N connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Santa Fe 2019-20|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai D connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Santa Fe 2021-23|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai L connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Santa Fe Hybrid 2022-23|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai L connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Santa Fe Plug-in Hybrid 2022-23|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai L connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Sonata 2018-19|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai E connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Sonata 2020-23|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Sonata Hybrid 2020-23|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Staria 2023|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Tucson 2021|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Hyundai L connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Tucson 2022|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai N connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Tucson 2023-24|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai N connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Tucson Diesel 2019|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai L connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Tucson Hybrid 2022-24|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai N connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Tucson Plug-in Hybrid 2024|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai N connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Hyundai|Veloster 2019-20|Smart Cruise Control (SCC)|Stock|5 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Hyundai E connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Jeep|Grand Cherokee 2016-18|Adaptive Cruise Control (ACC)|Stock|0 mph|9 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 FCA connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Jeep|Grand Cherokee 2019-21|Adaptive Cruise Control (ACC)|Stock|0 mph|39 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 FCA connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Carnival 2022-24|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Carnival (China only) 2023|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Ceed 2019-21|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai E connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|EV6 (Southeast Asia only) 2022-24|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai P connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|EV6 (with HDA II) 2022-24|Highway Driving Assist II|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai P connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|EV6 (without HDA II) 2022-24|Highway Driving Assist|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai L connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Forte 2019-21|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|6 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Hyundai G connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Forte 2022-23|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai E connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|K5 2021-24|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|K5 Hybrid 2020-22|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|K7 2017|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai C connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|K8 Hybrid (with HDA II) 2023|Highway Driving Assist II|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai Q connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Niro EV 2019|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai H connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Niro EV 2020|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai F connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Niro EV 2021|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai C connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Niro EV 2022|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai H connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Niro EV (with HDA II) 2024-25|Highway Driving Assist II|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai R connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Niro EV (without HDA II) 2023-25|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Niro Hybrid 2018|Smart Cruise Control (SCC)|Stock|10 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Hyundai C connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Niro Hybrid 2021|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai D connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Niro Hybrid 2022|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai F connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Niro Hybrid 2023-24|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Niro Plug-in Hybrid 2018-19|All|Stock|10 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Hyundai C connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Niro Plug-in Hybrid 2020|Smart Cruise Control (SCC)|Stock|0 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai D connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Niro Plug-in Hybrid 2021|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai D connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Niro Plug-in Hybrid 2022|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai F connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Optima 2017|Advanced Smart Cruise Control|Stock|0 mph|32 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai B connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Optima 2019-20|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai G connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Optima Hybrid 2019|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai H connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Seltos 2021|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Sorento 2018|Advanced Smart Cruise Control & LKAS|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai E connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Sorento 2019|Smart Cruise Control (SCC)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai E connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Sorento 2021-23|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Sorento Hybrid 2021-23|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Sorento Plug-in Hybrid 2022-23|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Sportage 2023-24|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai N connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Sportage Hybrid 2023|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai N connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Stinger 2018-20|Smart Cruise Control (SCC)|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai C connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Stinger 2022-23|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai K connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Kia|Telluride 2020-22|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Hyundai H connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|CT Hybrid 2017-18|Lexus Safety System+|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|ES 2017-18|All|Stock|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|ES 2019-25|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|ES Hybrid 2017-18|All|Stock|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|ES Hybrid 2019-25|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|GS F 2016|All|Stock|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|IS 2017-19|All|Stock|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|IS 2022-24|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|LC 2024-25|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|LS 2018|All except Lexus Safety System+ A|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|NX 2018-19|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|NX 2020-21|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|NX Hybrid 2018-19|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|NX Hybrid 2020-21|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|RC 2018-20|All|Stock|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|RC 2023|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|RX 2016|Lexus Safety System+|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|RX 2017-19|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|RX 2020-22|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|RX Hybrid 2016|Lexus Safety System+|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|RX Hybrid 2017-19|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|RX Hybrid 2020-22|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lexus|UX Hybrid 2019-24|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lincoln|Aviator 2020-24|Co-Pilot360 Plus|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Lincoln|Aviator Plug-in Hybrid 2020-24|Co-Pilot360 Plus|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Ford Q3 connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|MAN[12](#footnotes)|eTGE 2020-24|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|31 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|MAN[12](#footnotes)|TGE 2017-24|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|31 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Mazda|CX-5 2022-25|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Mazda connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Mazda|CX-9 2021-23|All|Stock|0 mph|28 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 Mazda connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Nissan[6](#footnotes)|Altima 2019-24|ProPILOT Assist|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Nissan B connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Nissan[6](#footnotes)|Leaf 2018-23|ProPILOT Assist|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Nissan A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Nissan[6](#footnotes)|Rogue 2018-20|ProPILOT Assist|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Nissan A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Nissan[6](#footnotes)|X-Trail 2017|ProPILOT Assist|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 Nissan A connector
- 1 OBD-C cable (2 ft)
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Ram|1500 2019-24|Adaptive Cruise Control (ACC)|Stock|32 mph|1 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Ram connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Ram|2500 2020-24|Adaptive Cruise Control (ACC)|Stock|0 mph|36 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Ram connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Ram|3500 2019-22|Adaptive Cruise Control (ACC)|Stock|0 mph|36 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Ram connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Rivian|R1S 2022-24|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Rivian A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Rivian|R1S 2025|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Rivian B connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Rivian|R1T 2022-24|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Rivian A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Rivian|R1T 2025|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Rivian B connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|SEAT[12](#footnotes)|Ateca 2016-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|SEAT[12](#footnotes)|Leon 2014-20|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Subaru|Ascent 2019-21|All[7](#footnotes)|openpilot available[1,8](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Subaru A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
||| +|Subaru|Crosstrek 2018-19|EyeSight Driver Assistance[7](#footnotes)|openpilot available[1,8](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Subaru A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
||| +|Subaru|Crosstrek 2020-23|EyeSight Driver Assistance[7](#footnotes)|openpilot available[1,8](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Subaru A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
||| +|Subaru|Forester 2017-18|EyeSight Driver Assistance[7](#footnotes)|Stock|0 mph|0 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Subaru A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
||| +|Subaru|Forester 2019-21|All[7](#footnotes)|openpilot available[1,8](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Subaru A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
||| +|Subaru|Impreza 2017-19|EyeSight Driver Assistance[7](#footnotes)|openpilot available[1,8](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Subaru A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
||| +|Subaru|Impreza 2020-22|EyeSight Driver Assistance[7](#footnotes)|openpilot available[1,8](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Subaru A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
||| +|Subaru|Legacy 2015-18|EyeSight Driver Assistance[7](#footnotes)|Stock|0 mph|0 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Subaru A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
||| +|Subaru|Legacy 2020-22|All[7](#footnotes)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Subaru B connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
||| +|Subaru|Outback 2015-17|EyeSight Driver Assistance[7](#footnotes)|Stock|0 mph|0 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Subaru A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
||| +|Subaru|Outback 2018-19|EyeSight Driver Assistance[7](#footnotes)|Stock|0 mph|0 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Subaru A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
||| +|Subaru|Outback 2020-22|All[7](#footnotes)|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Subaru B connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
||| +|Subaru|XV 2018-19|EyeSight Driver Assistance[7](#footnotes)|openpilot available[1,8](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-empty.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Subaru A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
||| +|Subaru|XV 2020-21|EyeSight Driver Assistance[7](#footnotes)|openpilot available[1,8](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Subaru A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
Tools- 1 Pry Tool
- 1 Socket Wrench 8mm or 5/16" (deep)
||| +|Škoda|Fabia 2022-23[15](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
[17](#footnotes)||| +|Škoda|Kamiq 2021-23[13,15](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
[17](#footnotes)||| +|Škoda[12](#footnotes)|Karoq 2019-23[15](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Škoda[12](#footnotes)|Kodiaq 2017-23[15](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Škoda[12](#footnotes)|Octavia 2015-19[15](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Škoda[12](#footnotes)|Octavia RS 2016[15](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Škoda[12](#footnotes)|Octavia Scout 2017-19[15](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Škoda|Scala 2020-23[15](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
[17](#footnotes)||| +|Škoda[12](#footnotes)|Superb 2015-22[15](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Tesla[10](#footnotes)|Model 3 (with HW3) 2019-23[9](#footnotes)|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Tesla A connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Tesla[10](#footnotes)|Model 3 (with HW4) 2024-25[9](#footnotes)|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Tesla B connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Tesla[10](#footnotes)|Model Y (with HW3) 2020-23[9](#footnotes)|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Tesla A connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Tesla[10](#footnotes)|Model Y (with HW4) 2024-25[9](#footnotes)|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Tesla B connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Toyota|Alphard 2019-20|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Alphard Hybrid 2021|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Avalon 2016|Toyota Safety Sense P|Stock|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Avalon 2017-18|All|Stock|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Avalon 2019-21|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Avalon 2022|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Avalon Hybrid 2019-21|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Avalon Hybrid 2022|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|C-HR 2017-20|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|C-HR 2021|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|C-HR Hybrid 2017-20|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|C-HR Hybrid 2021-22|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Camry 2018-20|All|Stock|0 mph[11](#footnotes)|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Camry 2021-24|All|openpilot|0 mph[11](#footnotes)|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Camry Hybrid 2018-20|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Camry Hybrid 2021-24|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Corolla 2017-19|All|Stock|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Corolla 2020-22|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Corolla Cross (Non-US only) 2020-23|All|openpilot|17 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Corolla Cross Hybrid (Non-US only) 2020-22|All|openpilot|17 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Corolla Hatchback 2019-22|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Corolla Hybrid 2020-22|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Corolla Hybrid (South America only) 2020-23|All|openpilot|17 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Highlander 2017-19|All|Stock|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Highlander 2020-23|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Highlander Hybrid 2017-19|All|Stock|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Highlander Hybrid 2020-23|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Mirai 2021|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Prius 2016|Toyota Safety Sense P|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Prius 2017-20|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Prius 2021-22|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Prius Prime 2017-20|All|Stock|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Prius Prime 2021-22|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Prius v 2017|Toyota Safety Sense P|Stock|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|RAV4 2016|Toyota Safety Sense P|Stock|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|RAV4 2017-18|All|Stock|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|RAV4 2019-21|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|RAV4 2022|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|RAV4 2023-25|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|RAV4 Hybrid 2016|Toyota Safety Sense P|Stock|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|RAV4 Hybrid 2017-18|All|Stock|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|RAV4 Hybrid 2019-21|All|openpilot|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|RAV4 Hybrid 2022|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|RAV4 Hybrid 2023-25|All|openpilot available[1](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Toyota|Sienna 2018-20|All|Stock|19 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 Toyota A connector
- 1 comma four
- 1 comma power v3
- 1 harness box
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Arteon 2018-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Arteon eHybrid 2020-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Arteon R 2020-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Arteon Shooting Brake 2020-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Atlas 2018-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Atlas Cross Sport 2020-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|California 2021-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|31 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Caravelle 2020|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|31 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|CC 2018-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Crafter 2017-24|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|31 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|e-Crafter 2018-24|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|31 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|e-Golf 2014-20|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Golf 2015-20|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Golf Alltrack 2015-19|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Golf GTD 2015-20|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Golf GTE 2015-20|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Golf GTI 2015-21|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-empty.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Golf R 2015-19|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Golf SportsVan 2015-20|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Grand California 2019-24|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|31 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Jetta 2019-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Jetta GLI 2021-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen|Passat 2015-22[14](#footnotes)|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Passat Alltrack 2015-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Passat GTE 2015-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen|Polo 2018-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
[17](#footnotes)||| +|Volkswagen|Polo GTI 2018-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
[17](#footnotes)||| +|Volkswagen|T-Cross 2021|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
[17](#footnotes)||| +|Volkswagen[12](#footnotes)|T-Roc 2018-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Taos 2022-24|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Teramont 2018-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Teramont Cross Sport 2021-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Teramont X 2021-22|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Tiguan 2018-24|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Tiguan eHybrid 2021-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| +|Volkswagen[12](#footnotes)|Touran 2016-23|Adaptive Cruise Control (ACC) & Lane Assist|openpilot available[1,16](#footnotes)|0 mph|0 mph|[![star](assets/icon-star-full.svg)](##)|[![star](assets/icon-star-full.svg)](##)|
Parts- 1 OBD-C cable (2 ft)
- 1 VW J533 connector
- 1 comma four
- 1 harness box
- 1 long OBD-C cable (9.5 ft)
- 1 mount
Buy Here
||| ### Footnotes -1openpilot Longitudinal Control (Alpha) is available behind a toggle; the toggle is only available in non-release branches such as `devel` or `nightly-dev`.
-2By default, this car will use the stock Adaptive Cruise Control (ACC) for longitudinal control. If the Driver Support Unit (DSU) is disconnected, openpilot ACC will replace stock ACC. NOTE: disconnecting the DSU disables Automatic Emergency Braking (AEB).
-3Refers only to the Focus Mk4 (C519) available in Europe/China/Taiwan/Australasia, not the Focus Mk3 (C346) in North and South America/Southeast Asia.
-4See more setup details for GM.
-52019 Honda Civic 1.6L Diesel Sedan does not have ALC below 12mph.
-6Requires a CAN FD panda kit if not using comma 3X for this CAN FD car.
-7See more setup details for Nissan.
-8In the non-US market, openpilot requires the car to come equipped with EyeSight with Lane Keep Assistance.
-9Enabling longitudinal control (alpha) will disable all EyeSight functionality, including AEB, LDW, and RAB.
-10Some 2023 model years have HW4. To check which hardware type your vehicle has, look for Autopilot computer under Software -> Additional Vehicle Information on your vehicle's touchscreen. See this page for more information.
-11See more setup details for Tesla.
-12openpilot operates above 28mph for Camry 4CYL L, 4CYL LE and 4CYL SE which don't have Full-Speed Range Dynamic Radar Cruise Control.
+1openpilot Longitudinal Control (Alpha) is available behind a toggle; the toggle is only available in non-release branches such as `nightly-dev`.
+2Refers only to the Focus Mk4 (C519) available in Europe/China/Taiwan/Australasia, not the Focus Mk3 (C346) in North and South America/Southeast Asia.
+3See more setup details for GM.
+42019 Honda Civic 1.6L Diesel Sedan does not have ALC below 12mph.
+5Enabling longitudinal control (alpha) will disable all CMBS functionality, including AEB and FCW.
+6See more setup details for Nissan.
+7In the non-US market, openpilot requires the car to come equipped with EyeSight with Lane Keep Assistance.
+8Enabling longitudinal control (alpha) will disable all EyeSight functionality, including AEB, LDW, and RAB.
+9Some 2023 model years have HW4. To check which hardware type your vehicle has, look for Autopilot computer under Software -> Additional Vehicle Information on your vehicle's touchscreen. See this page for more information.
+10See more setup details for Tesla.
+11openpilot operates above 28mph for Camry 4CYL L, 4CYL LE and 4CYL SE which don't have Full-Speed Range Dynamic Radar Cruise Control.
+12The J533 harness plugs in at the CAN gateway under the dashboard, just above the steering column. More information can be found at this guide.
13Not including the China market Kamiq, which is based on the (currently) unsupported PQ34 platform.
14Refers only to the MQB-based European B8 Passat, not the NMS Passat in the USA/China/Mideast markets.
-15Some Škoda vehicles are equipped with heated windshields, which are known to block GPS signal needed for some comma 3X functionality.
+15Some Škoda vehicles are equipped with heated windshields, which are known to block GPS signal needed for some comma four functionality.
16Only available for vehicles using a gateway (J533) harness. At this time, vehicles using a camera harness are limited to using stock ACC.
17Model-years 2022 and beyond may have a combined CAN gateway and BCM, which is supported by openpilot in software, but doesn't yet have a harness available from the comma store.
@@ -356,7 +385,7 @@ If your car has the following packages or features, then it's a good candidate f | Make | Required Package/Features | | ---- | ------------------------- | -| Acura | Any car with AcuraWatch Plus will work. AcuraWatch Plus comes standard on many newer models. | +| Acura | Any car with AcuraWatch will work. AcuraWatch comes standard on many newer models. | | Ford | Any car with Lane Centering will likely work. | | Honda | Any car with Honda Sensing will work. Honda Sensing comes standard on many newer models. | | Subaru | Any car with EyeSight will work. EyeSight comes standard on many newer models. | diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md index 1950db8a05..cbeb5f6d3a 100644 --- a/docs/CONTRIBUTING.md +++ b/docs/CONTRIBUTING.md @@ -6,20 +6,20 @@ Development is coordinated through [Discord](https://discord.comma.ai) and GitHu ### Getting Started -* Setup your [development environment](../tools/) +* Set up your [development environment](/tools/) * Join our [Discord](https://discord.comma.ai) * Docs are at https://docs.comma.ai and https://blog.comma.ai ## What contributions are we looking for? **openpilot's priorities are [safety](SAFETY.md), stability, quality, and features, in that order.** -openpilot is part of comma's mission to *solve self-driving cars while delivering shippable intermediaries*, and all development is towards that goal. +openpilot is part of comma's mission to *solve self-driving cars while delivering shippable intermediaries*, and all development is towards that goal. ### What gets merged? The probability of a pull request being merged is a function of its value to the project and the effort it will take us to get it merged. If a PR offers *some* value but will take lots of time to get merged, it will be closed. -Simple, well-tested bug fixes are the easiest to merge, and new features are the hardest to get merged. +Simple, well-tested bug fixes are the easiest to merge, and new features are the hardest to get merged. All of these are examples of good PRs: * typo fix: https://github.com/commaai/openpilot/pull/30678 @@ -29,17 +29,17 @@ All of these are examples of good PRs: ### What doesn't get merged? -* **style changes**: code is art, and it's up to the author to make it beautiful +* **style changes**: code is art, and it's up to the author to make it beautiful * **500+ line PRs**: clean it up, break it up into smaller PRs, or both * **PRs without a clear goal**: every PR must have a singular and clear goal * **UI design**: we do not have a good review process for this yet * **New features**: We believe openpilot is mostly feature-complete, and the rest is a matter of refinement and fixing bugs. As a result of this, most feature PRs will be immediately closed, however the beauty of open source is that forks can and do offer features that upstream openpilot doesn't. -* **Negative expected value**: This a class of PRs that makes an improvement, but the risk or validation costs more than the improvement. The risk can be mitigated by first getting a failing test merged. +* **Negative expected value**: This is a class of PRs that makes an improvement, but the risk or validation costs more than the improvement. The risk can be mitigated by first getting a failing test merged. ### First contribution [Projects / openpilot bounties](https://github.com/orgs/commaai/projects/26/views/1?pane=info) is the best place to get started and goes in-depth on what's expected when working on a bounty. -There's lot of bounties that don't require a comma 3/3X or a car. +There are a lot of bounties that don't require a comma four or a car. ## Pull Requests @@ -68,6 +68,6 @@ A good pull request has all of the following: ### A guide for forks In order for your fork's data to be eligible for the training set: -* **Your cereal messaging structs must be [compatible](../cereal#custom-forks)** +* **Your cereal messaging structs must be [compatible](../openpilot/cereal#custom-forks)** * **The definitions of all the stock messaging structs must not change**: Do not change how any of the fields are set, including everything from `selfdriveState.enabled` to `carState.steeringAngleDeg`. Instead, create your own structs and set them however you'd like. * **Do not include cars that are not supported in upstream platforms**: Instead, create new opendbc platforms for cars that you'd like to support outside of upstream, even if it's just a trim-level difference. diff --git a/docs/DEBUGGING_SAFETY.md b/docs/DEBUGGING_SAFETY.md new file mode 100644 index 0000000000..cd0a46b446 --- /dev/null +++ b/docs/DEBUGGING_SAFETY.md @@ -0,0 +1,30 @@ +# Debugging Panda Safety with Replay Drive + LLDB + +## 1. Start the debugger in VS Code + +* Select **Replay drive + Safety LLDB**. +* Enter the route or segment when prompted. +[](https://github.com/user-attachments/assets/b0cc320a-083e-46a7-a9f8-ca775bbe5604) + +## 2. Attach LLDB + +* When prompted, pick the running **`replay_drive` process**. +* ⚠️ Attach quickly, or `replay_drive` will start consuming messages. + +> [!TIP] +> Add a Python breakpoint at the start of `replay_drive.py` to pause execution and give yourself time to attach LLDB. + +## 3. Set breakpoints in VS Code +Breakpoints can be set directly in `modes/xxx.h` (or any C file). +No extra LLDB commands are required — just place breakpoints in the editor. + +## 4. Resume execution +Once attached, you can step through both Python (on the replay) and C safety code as CAN logs are replayed. + +> [!NOTE] +> * Use short routes for quicker iteration. +> * Pause `replay_drive` early to avoid wasting log messages. + +## Video + +View a demo of this workflow on the PR that added it: https://github.com/commaai/openpilot/pull/36055#issue-3352911578 \ No newline at end of file diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md new file mode 100644 index 0000000000..e803a3fb8a --- /dev/null +++ b/docs/DEVELOPMENT.md @@ -0,0 +1,24 @@ +# Docs development + +The `docs/` tree is the source for [docs.comma.ai](https://docs.comma.ai). +The site is updated on pushes to master by this [workflow](../.github/workflows/docs.yaml). + +Those commands must be run in the root directory of openpilot, **not /docs** + +**1. Install the docs dependencies** +``` bash +uv pip install .[docs] +``` + +**2. Build the new site** +``` bash +docs build +``` + +**3. Run the new site locally** +``` bash +docs serve +``` + +References: +* https://zensical.org/docs/ diff --git a/docs/README.md b/docs/README.md deleted file mode 100644 index 08dd4fa8bc..0000000000 --- a/docs/README.md +++ /dev/null @@ -1,26 +0,0 @@ -# openpilot docs - -This is the source for [docs.comma.ai](https://docs.comma.ai). -The site is updated on pushes to master by this [workflow](../.github/workflows/docs.yaml). - -## Development -NOTE: Those commands must be run in the root directory of openpilot, **not /docs** - -**1. Install the docs dependencies** -``` bash -pip install .[docs] -``` - -**2. Build the new site** -``` bash -mkdocs build -``` - -**3. Run the new site locally** -``` bash -mkdocs serve -``` - -References: -* https://www.mkdocs.org/getting-started/ -* https://github.com/ntno/mkdocs-terminal diff --git a/docs/SAFETY.md b/docs/SAFETY.md index 18a450a395..5857c6d5b5 100644 --- a/docs/SAFETY.md +++ b/docs/SAFETY.md @@ -4,8 +4,8 @@ openpilot is an Adaptive Cruise Control (ACC) and Automated Lane Centering (ALC) Like other ACC and ALC systems, openpilot is a failsafe passive system and it requires the driver to be alert and to pay attention at all times. -In order to enforce driver alertness, openpilot includes a driver monitoring feature -that alerts the driver when distracted. +To assist the driver in maintaining alertness, openpilot includes a driver monitoring feature +that alerts when it detects driver distraction. However, even with an attentive driver, we must make further efforts for the system to be safe. We repeat, **driver alertness is necessary, but not sufficient, for openpilot to be @@ -16,7 +16,7 @@ industry standards of safety for Level 2 Driver Assistance Systems. In particula ISO26262 guidelines, including those from [pertinent documents](https://www.nhtsa.gov/sites/nhtsa.dot.gov/files/documents/13498a_812_573_alcsystemreport.pdf) released by NHTSA. In addition, we impose strict coding guidelines (like [MISRA C : 2012](https://www.misra.org.uk/what-is-misra/)) on parts of openpilot that are safety relevant. We also perform software-in-the-loop, -hardware-in-the-loop and in-vehicle tests before each software release. +hardware-in-the-loop, and in-vehicle tests before each software release. Following Hazard and Risk Analysis and FMEA, at a very high level, we have designed openpilot ensuring two main safety requirements. @@ -29,8 +29,18 @@ ensuring two main safety requirements. For additional safety implementation details, refer to [panda safety model](https://github.com/commaai/panda#safety-model). For vehicle specific implementation of the safety concept, refer to [opendbc/safety/safety](https://github.com/commaai/opendbc/tree/master/opendbc/safety/safety). -**Extra note**: comma.ai strongly discourages the use of openpilot forks with safety code either missing or - not fully meeting the above requirements. +[^1]: For these actuator limits we observe ISO11270 and ISO15622. Lateral limits described there translate to 0.9 seconds of maximum actuation to achieve a 1m lateral deviation. -[^1]: For these actuator limits we observe ISO11270 and ISO15622. Lateral limits described there translate to 0.9 seconds of maximum actuation to achieve a 1m lateral deviation. +--- +### Forks of openpilot + +* Do not disable or nerf [driver monitoring](https://github.com/commaai/openpilot/tree/master/openpilot/selfdrive/monitoring) +* Do not disable or nerf [excessive actuation checks](https://github.com/commaai/openpilot/tree/master/openpilot/selfdrive/selfdrived/helpers.py) +* If your fork modifies any of the code in `opendbc/safety/`: + * your fork cannot use the openpilot trademark + * your fork must preserve the full [safety test suite](https://github.com/commaai/opendbc/tree/master/opendbc/safety/tests) and all tests must pass, including any new coverage required by the fork's changes + +Failure to comply with these standards will get you and your users banned from comma.ai servers. + +**comma.ai strongly discourages the use of openpilot forks with safety code either missing or not fully meeting the above requirements.** diff --git a/docs/assets/comma-logo.png b/docs/assets/comma-logo.png new file mode 120000 index 0000000000..2838d92bfb --- /dev/null +++ b/docs/assets/comma-logo.png @@ -0,0 +1 @@ +../../selfdrive/assets/icons_mici/settings/comma_icon.png \ No newline at end of file diff --git a/docs/car-porting/brand-port.md b/docs/car-porting/brand-port.md deleted file mode 100644 index a3daa7a848..0000000000 --- a/docs/car-porting/brand-port.md +++ /dev/null @@ -1,5 +0,0 @@ -# Developing a car brand port - -A brand port is a port of openpilot to a substantially new car brand or platform within a brand. - -Here's an example of one: https://github.com/commaai/openpilot/pull/23331. diff --git a/docs/car-porting/model-port.md b/docs/car-porting/model-port.md deleted file mode 100644 index e148a40ecb..0000000000 --- a/docs/car-porting/model-port.md +++ /dev/null @@ -1,5 +0,0 @@ -# Developing a car model port - -A model port is a port of openpilot to a new car model within an already supported brand. Model ports are easier than brand ports because the car's existing APIs are already known. - -Here's an example of one: https://github.com/commaai/openpilot/pull/30672/. diff --git a/docs/car-porting/what-is-a-car-port.md b/docs/car-porting/what-is-a-car-port.md deleted file mode 100644 index 55cce94da1..0000000000 --- a/docs/car-porting/what-is-a-car-port.md +++ /dev/null @@ -1,39 +0,0 @@ -# What is a car port? - -A car port enables openpilot support on a particular car. Each car model openpilot supports needs to be individually ported. The complexity of a car port varies depending on many factors including: - -* existing openpilot support for similar cars -* architecture and APIs available in the car - - -# Structure of a car port - -Virtually all car-specific code is contained in two other repositories: [opendbc](https://github.com/commaai/opendbc) and [panda](https://github.com/commaai/panda). - -## opendbc - -Each car brand is supported by a standard interface structure in `opendbc/car/[brand]`: - -* `interface.py`: Interface for the car, defines the CarInterface class -* `carstate.py`: Reads CAN messages from the car and builds openpilot CarState messages -* `carcontroller.py`: Control logic for executing openpilot CarControl actions on the car -* `[brand]can.py`: Composes CAN messages for carcontroller to send -* `values.py`: Limits for actuation, general constants for cars, and supported car documentation -* `radar_interface.py`: Interface for parsing radar points from the car, if applicable - -## panda - -* `board/safety/safety_[brand].h`: Brand-specific safety logic -* `tests/safety/test_[brand].py`: Brand-specific safety CI tests - -## openpilot - -For historical reasons, openpilot still contains a small amount of car-specific logic. This will eventually be migrated to opendbc or otherwise removed. - -* `selfdrive/car/car_specific.py`: Brand-specific event logic - -# Overview - -[Jason Young](https://github.com/jyoung8607) gave a talk at COMMA_CON with an overview of the car porting process. The talk is available on YouTube: - -https://www.youtube.com/watch?v=XxPS5TpTUnI diff --git a/docs/concepts/glossary.md b/docs/concepts/glossary.md index a09b0f0785..4f4dd54756 100644 --- a/docs/concepts/glossary.md +++ b/docs/concepts/glossary.md @@ -1,9 +1,3 @@ # openpilot glossary -* **onroad**: openpilot's system state while ignition is on -* **offroad**: openpilot's system state while ignition is off -* **route**: a route is a recording of an onroad session -* **segment**: routes are split into one minute chunks called segments. -* **comma connect**: the web viewer for all your routes; check it out at [connect.comma.ai](https://connect.comma.ai). -* **panda**: this is the secondary processor on the device that implements the functional safety and directly talks to the car over CAN. See the [panda repo](https://github.com/commaai/panda). -* **comma 3X**: the latest hardware by comma.ai for running openpilot. more info at [comma.ai/shop](https://comma.ai/shop). +{{GLOSSARY_DEFINITIONS}} diff --git a/docs/concepts/logs.md b/docs/concepts/logs.md index 46ab2897df..dd954d4c76 100644 --- a/docs/concepts/logs.md +++ b/docs/concepts/logs.md @@ -2,13 +2,13 @@ openpilot records routes in one minute chunks called segments. A route starts on the rising edge of ignition and ends on the falling edge. -Check out our [Python library](https://github.com/commaai/openpilot/blob/master/tools/lib/logreader.py) for reading openpilot logs. Also checkout our [tools](https://github.com/commaai/openpilot/tree/master/tools) to replay and view your data. These are the same tools we use to debug and develop openpilot. +Check out our [Python library](https://github.com/commaai/openpilot/blob/master/openpilot/tools/lib/logreader.py) for reading openpilot logs. Also checkout our [tools](https://github.com/commaai/openpilot/tree/master/openpilot/tools) to replay and view your data. These are the same tools we use to debug and develop openpilot. For each segment, openpilot records the following log types: -## rlog.bz2 +## rlog.zst -rlogs contain all the messages passed amongst openpilot's processes. See [cereal/services.py](https://github.com/commaai/cereal/blob/master/services.py) for a list of all the logged services. They're a bzip2 archive of the serialized capnproto messages. +rlogs contain all the messages passed amongst openpilot's processes. See [openpilot/cereal/services.py](https://github.com/commaai/openpilot/blob/master/openpilot/cereal/services.py) for a list of all the logged services. They're a zstd archive of the serialized [Cap’n Proto](https://capnproto.org/) messages. ## {f,e,d}camera.hevc @@ -18,12 +18,10 @@ Each camera stream is H.265 encoded and written to its respective file. * `ecamera.hevc` is the wide road camera * `dcamera.hevc` is the driver camera -## qlog.bz2 & qcamera.ts - -qlogs are a decimated subset of the rlogs. Check out [cereal/services.py](https://github.com/commaai/cereal/blob/master/services.py) for the decimation. +## qlog.zst & qcamera.ts +qlogs are a decimated subset of the rlogs. Check out [openpilot/cereal/services.py](https://github.com/commaai/openpilot/blob/master/openpilot/cereal/services.py) for the decimation. qcameras are H.264 encoded, lower res versions of the fcamera.hevc. The video shown in [comma connect](https://connect.comma.ai/) is from the qcameras. - -qlogs and qcameras are designed to be small enough to upload instantly on slow internet and store forever, yet useful enough for most analysis and debugging. +qlogs and qcameras are designed to be small enough to upload instantly on slow internet, yet useful enough for most analysis and debugging. diff --git a/docs/contributing/feedback.md b/docs/contributing/feedback.md new file mode 100644 index 0000000000..335d24e13a --- /dev/null +++ b/docs/contributing/feedback.md @@ -0,0 +1,36 @@ +# How to Give Feedback + +Feedback is one of the highest leverage ways to contribute to openpilot as a user. + +## Driving + +Got feedback about how your car drives? +Join the community Discord, then use the form in `#submit-feedback`. + +Before posting feedback, please ensure: + +- **openpilot is up to date** you should be on the latest openpilot release or nightly +- **both road-facing cameras have a clear view** your windshield is clean, lenses are clean, etc. +- **your device is mounted properly** your device must be mounted horizontally center and relatively high on the windshield + +## Driver Monitoring + +If you find DM annoying while being perfectly attentive, these are likely false positives and we want to fix them! +In general, driver monitoring feedback is very actionable, and we can fix your complaint within a release cycle. + +To post your feedback: + +1. Join the [community Discord](https://discord.comma.ai). +2. If driver camera recording is toggled off, temporarily enable driver camera recording in the settings until you reproduce the issue. +3. Using comma connect, identify the relevant segment and upload the segment's logs and driver camera. +4. Post the segment in the `#openpilot-experience` channel on Discord with a good description. + +Before posting feedback, please ensure: + +- **openpilot is up to date** you should be on the latest openpilot release or nightly +- **the driver camera has a clear view of the driver** ensure nothing blocks view of the driver (e.g. a cable), the lens is clean, etc. +- **your device is mounted properly** your device must be mounted horizontally center and relatively high on the windshield + +## Other bugs + +Got an issue with something else? Open an issue on our [GitHub issue tracker](https://github.com/commaai/openpilot/issues/new/choose). diff --git a/docs/contributing/roadmap.md b/docs/contributing/roadmap.md index 1262017a0b..ae27a5461c 100644 --- a/docs/contributing/roadmap.md +++ b/docs/contributing/roadmap.md @@ -7,25 +7,11 @@ This is the roadmap for the next major openpilot releases. Also check out * [Bounties](https://comma.ai/bounties) for paid individual issues * [#current-projects](https://discord.com/channels/469524606043160576/1249579909739708446) in Discord for discussion on work-in-progress projects -## openpilot 0.10 - -openpilot 0.10 will be the first release with a driving policy trained in -a [learned simulator](https://youtu.be/EqQNZXqzFSI). - -* Driving model trained in a learned simulator -* Always-on driver monitoring (behind a toggle) -* GPS removed from the driving stack -* 100KB qlogs -* `nightly` pushed after 1000 hours of hardware-in-the-loop testing -* Car interface code moved into [opendbc](https://github.com/commaai/opendbc) -* openpilot on PC for Linux x86, Linux arm64, and Mac (Apple Silicon) - ## openpilot 1.0 openpilot 1.0 will feature a fully end-to-end driving policy. * End-to-end longitudinal control in Chill mode -* Automatic Emergency Braking (AEB) * Driver monitoring with sleep detection * Rolling updates/releases pushed out by CI * [panda safety 1.0](https://github.com/orgs/commaai/projects/27) diff --git a/docs/css/tooltip.css b/docs/css/tooltip.css deleted file mode 100644 index b9a54f793f..0000000000 --- a/docs/css/tooltip.css +++ /dev/null @@ -1,44 +0,0 @@ -[data-tooltip] { - position: relative; - display: inline-block; - border-bottom: 1px dotted black; -} - -[data-tooltip] .tooltip-content { - width: max-content; - max-width: 25em; - position: absolute; - top: 100%; - left: 50%; - transform: translateX(-50%); - background-color: white; - color: #404040; - box-shadow: 0 4px 14px 0 rgba(0,0,0,.2), 0 0 0 1px rgba(0,0,0,.05); - padding: 10px; - font: 14px/1.5 Lato, proxima-nova, Helvetica Neue, Arial, sans-serif; - text-decoration: none; - opacity: 0; - visibility: hidden; - transition: opacity 0.1s, visibility 0s; - z-index: 1000; - pointer-events: none; /* Prevent accidental interaction */ -} - -[data-tooltip]:hover .tooltip-content { - opacity: 1; - visibility: visible; - pointer-events: auto; /* Allow interaction when visible */ -} - -.tooltip-content .tooltip-glossary-link { - display: inline-block; - margin-top: 8px; - font-size: 12px; - color: #007bff; - text-decoration: none; -} - -.tooltip-content .tooltip-glossary-link:hover { - color: #0056b3; - text-decoration: underline; -} diff --git a/docs/ext/glossary.py b/docs/ext/glossary.py new file mode 100644 index 0000000000..9bbf3c78d7 --- /dev/null +++ b/docs/ext/glossary.py @@ -0,0 +1,216 @@ +import posixpath +import re +import tomllib +import xml.etree.ElementTree as ET +from pathlib import Path + +from markdown.extensions import Extension +from markdown.preprocessors import Preprocessor +from markdown.treeprocessors import Treeprocessor + +from zensical.extensions.links import LinksTreeprocessor + +GlossaryTerm = tuple[str, re.Pattern[str], str] + +GLOSSARY_FILE = Path(__file__).with_name("glossary.toml") +GLOSSARY_PAGE = "concepts/glossary.md" +GLOSSARY_PLACEHOLDER = "{{GLOSSARY_DEFINITIONS}}" + +SKIP_TAGS = { + "a", + "code", + "h1", + "h2", + "h3", + "h4", + "h5", + "h6", + "kbd", + "pre", + "script", + "style", +} + +def clean_tooltip(description: str) -> str: + text = re.sub(r"\[([^\]]+)]\([^)]+\)", r"\1", description) + text = re.sub(r"`([^`]+)`", r"\1", text) + text = re.sub(r"[*_~]", "", text) + return re.sub(r"\s+", " ", text).strip() + + +def load_glossary() -> tuple[list[GlossaryTerm], str]: + with GLOSSARY_FILE.open("rb") as f: + glossary_data = tomllib.load(f).get("glossary", {}) + + glossary: list[GlossaryTerm] = [] + rendered = [] + for key, value in glossary_data.items(): + label = str(key).strip().replace("_", " ") + description = str(value).strip() + if not description: + continue + + slug = label.replace(" ", "-").replace("_", "-").lower() + glossary.append((slug, re.compile(rf"(?**{label}**: {description}') + + return glossary, "\n".join(rendered) + + +class GlossaryPreprocessor(Preprocessor): + def __init__(self, md, glossary: str): + super().__init__(md) + self.glossary = glossary + + def run(self, lines: list[str]) -> list[str]: + markdown = "\n".join(lines) + if GLOSSARY_PLACEHOLDER not in markdown: + return lines + return markdown.replace(GLOSSARY_PLACEHOLDER, self.glossary).splitlines() + + +class GlossaryTreeprocessor(Treeprocessor): + def __init__(self, md, glossary: list[GlossaryTerm]): + super().__init__(md) + self.glossary = glossary + self.seen: set[str] = set() + + def run(self, root: ET.Element) -> None: + at = self.md.treeprocessors.get_index_for_name("zrelpath") + processor = self.md.treeprocessors[at] + if not isinstance(processor, LinksTreeprocessor): + raise TypeError("Links processor not registered") + if processor.path == GLOSSARY_PAGE: + return + + self.seen.clear() + glossary_href = f"{posixpath.relpath(GLOSSARY_PAGE, posixpath.dirname(processor.path) or '.')}#" + self._walk(root, glossary_href) + + def _walk(self, element: ET.Element, glossary_href: str) -> None: + if element.tag in SKIP_TAGS or element.attrib.get("data-glossary-skip") is not None: + return + + self._replace(element, glossary_href) + + idx = 0 + while idx < len(element): + child = element[idx] + self._walk(child, glossary_href) + idx = self._replace(element, glossary_href, idx) + 1 + + def _replace(self, parent: ET.Element, glossary_href: str, index: int | None = None) -> int: + child = None if index is None else parent[index] + text = parent.text if child is None else child.tail + pieces = self._pieces(text or "", glossary_href) + if not pieces: + return -1 if index is None else index + + if child is None: + parent.text = pieces[0] if isinstance(pieces[0], str) else "" + # Insert replacements for parent.text before the first existing child. + insert_at = -1 + else: + assert index is not None + child.tail = pieces[0] if isinstance(pieces[0], str) else "" + insert_at = index + + start = 1 if isinstance(pieces[0], str) else 0 + previous = child + + for piece in pieces[start:]: + if isinstance(piece, str): + previous.tail = (previous.tail or "") + piece + continue + + insert_at += 1 + parent.insert(insert_at, piece) + previous = piece + + return insert_at + + def _pieces(self, text: str, glossary_href: str) -> list[str | ET.Element]: + if not text.strip(): + return [] + + pieces: list[str | ET.Element] = [] + cursor = 0 + + while True: + best = None + for slug, pattern, tooltip in self.glossary: + if slug in self.seen: + continue + + found = pattern.search(text, cursor) + if found is None: + continue + + candidate = (slug, tooltip, found.start(), found.end()) + if best is None: + best = candidate + continue + + _, _, best_start, best_end = best + _, _, current_start, current_end = candidate + if current_start < best_start: + best = candidate + continue + + if current_start == best_start and current_end - current_start > best_end - best_start: + best = candidate + + if best is None: + break + + slug, tooltip, start, end = best + if start > cursor: + pieces.append(text[cursor:start]) + + link = ET.Element( + "a", + { + "class": "glossary-term", + "data-glossary-term": "", + "href": f"{glossary_href}{slug}", + }, + ) + ET.SubElement(link, "span", {"class": "glossary-term__label"}).text = text[start:end] + ET.SubElement( + link, + "span", + { + "class": "glossary-term__tooltip", + "data-search-exclude": "", + }, + ).text = tooltip + pieces.append(link) + self.seen.add(slug) + cursor = end + + if not pieces: + return [] + if cursor < len(text): + pieces.append(text[cursor:]) + return pieces + + +class GlossaryExtension(Extension): + def extendMarkdown(self, md) -> None: + md.registerExtension(self) + glossary, rendered = load_glossary() + + md.preprocessors.register( + GlossaryPreprocessor(md, rendered), + "docs-ext-glossary-preprocessor", + 27, + ) + md.treeprocessors.register( + GlossaryTreeprocessor(md, glossary), + "docs-ext-glossary-treeprocessor", + 0, + ) + + +def makeExtension(**kwargs) -> GlossaryExtension: + return GlossaryExtension(**kwargs) diff --git a/docs/ext/glossary.toml b/docs/ext/glossary.toml new file mode 100644 index 0000000000..62408d9ddd --- /dev/null +++ b/docs/ext/glossary.toml @@ -0,0 +1,8 @@ +[glossary] +onroad = "openpilot's system state while ignition is on." +offroad = "openpilot's system state while ignition is off." +route = "A route is a recording of an onroad session." +segment = "Routes are split into one minute chunks called segments." +"comma connect" = "The web viewer for all your routes; check it out at [connect.comma.ai](https://connect.comma.ai)." +panda = "The secondary processor on the device that implements the functional safety and directly talks to the car over CAN. See the [panda repo](https://github.com/commaai/panda)." +"comma four" = "The latest hardware by comma.ai for running openpilot. More info at [comma.ai/shop/comma-four](https://www.comma.ai/shop/comma-four)." diff --git a/docs/getting-started/what-is-openpilot.md b/docs/getting-started/what-is-openpilot.md deleted file mode 100644 index b3c56c8410..0000000000 --- a/docs/getting-started/what-is-openpilot.md +++ /dev/null @@ -1,12 +0,0 @@ -# What is openpilot? - -[openpilot](http://github.com/commaai/openpilot) is an open source driver assistance system. Currently, openpilot performs the functions of Adaptive Cruise Control (ACC), Automated Lane Centering (ALC), Forward Collision Warning (FCW), and Lane Departure Warning (LDW) for a growing variety of [supported car makes, models, and model years](https://github.com/commaai/openpilot/blob/master/docs/CARS.md). In addition, while openpilot is engaged, a camera-based Driver Monitoring (DM) feature alerts distracted and asleep drivers. See more about [the vehicle integration](https://github.com/commaai/openpilot/blob/master/docs/INTEGRATION.md) and [limitations](https://github.com/commaai/openpilot/blob/master/docs/LIMITATIONS.md). - - -## How do I use it? - -openpilot is designed to be used on the comma 3X. - -## How does it work? - -In short, openpilot uses the car's existing APIs for the built-in [ADAS](https://en.wikipedia.org/wiki/Advanced_driver-assistance_system) system and simply provides better acceleration, braking, and steering inputs than the stock system. diff --git a/docs/hooks/glossary.py b/docs/hooks/glossary.py deleted file mode 100644 index e2fa3d51e0..0000000000 --- a/docs/hooks/glossary.py +++ /dev/null @@ -1,68 +0,0 @@ -import re -import tomllib - -def load_glossary(file_path="docs/glossary.toml"): - with open(file_path, "rb") as f: - glossary_data = tomllib.load(f) - return glossary_data.get("glossary", {}) - -def generate_anchor_id(name): - return name.replace(" ", "-").replace("_", "-").lower() - -def format_markdown_term(name, definition): - anchor_id = generate_anchor_id(name) - markdown = f"* [**{name.replace('_', ' ').title()}**](#{anchor_id})" - if definition.get("abbreviation"): - markdown += f" *({definition['abbreviation']})*" - if definition.get("description"): - markdown += f": {definition['description']}\n" - return markdown - -def glossary_markdown(vocabulary): - markdown = "" - for category, terms in vocabulary.items(): - markdown += f"## {category.replace('_', ' ').title()}\n\n" - for name, definition in terms.items(): - markdown += format_markdown_term(name, definition) - return markdown - -def format_tooltip_html(term_key, definition, html): - display_term = term_key.replace("_", " ").title() - clean_description = re.sub(r"\[(.+)]\(.+\)", r"\1", definition["description"]) - glossary_link = ( - f"Glossary🔗" - ) - return re.sub( - re.escape(display_term), - lambda - match: f"{match.group(0)}{clean_description} {glossary_link}", - html, - flags=re.IGNORECASE, - ) - -def apply_tooltip(_term_key, _definition, pattern, html): - return re.sub( - pattern, - lambda match: format_tooltip_html(_term_key, _definition, match.group(0)), - html, - flags=re.IGNORECASE, - ) - -def tooltip_html(vocabulary, html): - for _category, terms in vocabulary.items(): - for term_key, definition in terms.items(): - if definition.get("description"): - pattern = rf"(?)(?!\([^)]*\))" - html = apply_tooltip(term_key, definition, pattern, html) - return html - -# Page Hooks -def on_page_markdown(markdown, **kwargs): - glossary = load_glossary() - return markdown.replace("{{GLOSSARY_DEFINITIONS}}", glossary_markdown(glossary)) - -def on_page_content(html, **kwargs): - if kwargs.get("page").title == "Glossary": - return html - glossary = load_glossary() - return tooltip_html(glossary, html) diff --git a/docs/how-to/car-port.md b/docs/how-to/car-port.md new file mode 100644 index 0000000000..c4106f91a7 --- /dev/null +++ b/docs/how-to/car-port.md @@ -0,0 +1,51 @@ +# What is a car port? + +A car port enables openpilot support on a particular car. Each car model openpilot supports needs to be individually ported. The complexity of a car port varies depending on many factors including: + +* existing openpilot support for similar cars +* architecture and APIs available in the car + + +# Structure of a car port + +All car-specific code is contained in the [opendbc](https://github.com/commaai/opendbc) project. + +## opendbc + +Each car brand is supported by a standard interface structure in `opendbc/car/[brand]`: + +* `interface.py`: Interface for the car, defines the CarInterface class +* `carstate.py`: Reads CAN messages from the car and builds openpilot CarState messages +* `carcontroller.py`: Control logic for executing openpilot CarControl actions on the car +* `[brand]can.py`: Composes CAN messages for carcontroller to send +* `values.py`: Limits for actuation, general constants for cars, and supported car documentation +* `radar_interface.py`: Interface for parsing radar points from the car, if applicable + +## safety + +* `opendbc/safety/modes/[brand].h`: Brand-specific safety logic +* `opendbc/safety/tests/test_[brand].py`: Brand-specific safety CI tests + +## openpilot + +For historical reasons, openpilot still contains a small amount of car-specific logic. This will eventually be migrated to opendbc or otherwise removed. + +* `openpilot/selfdrive/car/car_specific.py`: Brand-specific event logic + +# How do I port car? + +[Jason Young](https://github.com/jyoung8607) gave a talk at COMMA_CON with an overview of the car porting process. The talk is available on YouTube: + +https://www.youtube.com/watch?v=XxPS5TpTUnI + +## Brand Port + +A brand port is a port of openpilot to a substantially new car brand or platform within a brand. + +Here's an example of one: https://github.com/commaai/openpilot/pull/23331. + +## Model Port + +A model port is a port of openpilot to a new car model within an already supported brand. Model ports are easier than brand ports because the car's existing APIs are already known. + +Here's an example of one: https://github.com/commaai/openpilot/pull/30672/. diff --git a/docs/how-to/connect-to-comma.md b/docs/how-to/connect-to-comma.md index cbaccaae6a..e4e322f111 100644 --- a/docs/how-to/connect-to-comma.md +++ b/docs/how-to/connect-to-comma.md @@ -1,15 +1,15 @@ -# connect to a comma 3/3X +# connect to a comma 3X or comma four -A comma 3/3X is a normal [Linux](https://github.com/commaai/agnos-builder) computer that exposes [SSH](https://wiki.archlinux.org/title/Secure_Shell) and a [serial console](https://wiki.archlinux.org/title/Working_with_the_serial_console). +A comma device is a normal [Linux](https://github.com/commaai/agnos-builder) computer that exposes [SSH](https://wiki.archlinux.org/title/Secure_Shell) and a [serial console](https://wiki.archlinux.org/title/Working_with_the_serial_console). ## Serial Console -On both the comma three and 3X, the serial console is accessible from the main OBD-C port. -Connect the comma 3/3X to your computer with a normal USB C cable, or use a [comma serial](https://comma.ai/shop/comma-serial) for steady 12V power. +On the comma 3X, the serial console is accessible from the main OBD-C port, forwarded through the panda. +Access it using `panda/scripts/som_debug.sh`. -On the comma three, the serial console is exposed through a UART-to-USB chip, and `tools/scripts/serial.sh` can be used to connect. +comma four also exposes a serial console, albeit through an internal debug connector. Dedicated debug hardware coming soon to the comma shop. -On the comma 3X, the serial console is accessible through the [panda](https://github.com/commaai/panda) using the `panda/tests/som_debug.sh` script. +Login to the default user with: * Username: `comma` * Password: `comma` @@ -25,7 +25,7 @@ In order to SSH into your device, you'll need a GitHub account with SSH keys. Se * Port: `22` Here's an example command for connecting to your device using its tethered connection:
-`ssh comma@192.168.43.1` +`ssh comma@192.168.43.1 -i ~/.ssh/my_github_key` For doing development work on device, it's recommended to use [SSH agent forwarding](https://docs.github.com/en/developers/overview/using-ssh-agent-forwarding). @@ -45,7 +45,7 @@ In order to use ADB on your device, you'll need to perform the following steps u * Here's an example command for connecting to your device using its tethered connection: `adb connect 192.168.43.1:5555` > [!NOTE] -> The default port for ADB is 5555 on the comma 3/3X. +> The default port for ADB is 5555. For more info on ADB, see the [Android Debug Bridge (ADB) documentation](https://developer.android.com/tools/adb). @@ -55,7 +55,7 @@ The public keys are only fetched from your GitHub account once. In order to upda The `id_rsa` key in this directory only works while your device is in the setup state with no software installed. After installation, that default key will be removed. -#### ssh.comma.ai proxy +## ssh.comma.ai proxy With a [comma prime subscription](https://comma.ai/connect), you can SSH into your comma device from anywhere. @@ -79,6 +79,7 @@ Host ssh.comma.ai ``` ssh -i ~/.ssh/my_github_key -o ProxyCommand="ssh -i ~/.ssh/my_github_key -W %h:%p -p %p %h@ssh.comma.ai" comma@ffffffffffffffff ``` + (Replace `ffffffffffffffff` with your dongle_id) ### ssh.comma.ai host key fingerprint diff --git a/docs/how-to/replay-a-drive.md b/docs/how-to/replay-a-drive.md index 084b6bf825..129e7b8301 100644 --- a/docs/how-to/replay-a-drive.md +++ b/docs/how-to/replay-a-drive.md @@ -5,10 +5,10 @@ Replaying is a critical tool for openpilot development and debugging. ## Replaying a route *Hardware required: none* -Just run `tools/replay/replay --demo`. +Just run `openpilot/tools/replay/replay --demo`. ## Replaying CAN data -*Hardware required: jungle and comma 3/3X* +*Hardware required: jungle and comma four* 1. Connect your PC to a jungle. 2. diff --git a/docs/how-to/turn-the-speed-blue.md b/docs/how-to/turn-the-speed-blue.md index 64f4475dfa..5cfa8e176a 100644 --- a/docs/how-to/turn-the-speed-blue.md +++ b/docs/how-to/turn-the-speed-blue.md @@ -1,11 +1,11 @@ # Turn the speed blue *A getting started guide for openpilot development* -In 30 minutes, we'll get an openpilot development environment setup on your computer and make some changes to openpilot's UI. +In 30 minutes, we'll get an openpilot development environment set up on your computer and make some changes to openpilot's UI. -And if you have a comma 3/3X, we'll deploy the change to your device for testing. +And if you have a comma four, we'll deploy the change to your device for testing. -## 1. Setup your development environment +## 1. Set up your development environment Run this to clone openpilot and install all the dependencies: ```bash @@ -20,7 +20,7 @@ source .venv/bin/activate Then, compile openpilot: ```bash -scons -j$(nproc) +scons ``` ## 2. Run replay @@ -28,10 +28,10 @@ scons -j$(nproc) We'll run the `replay` tool with the demo route to get data streaming for testing our UI changes. ```bash # in terminal 1 -tools/replay/replay --demo +openpilot/tools/replay/replay --demo # in terminal 2 -selfdrive/ui/ui +./openpilot/selfdrive/ui/ui.py ``` The openpilot UI should launch and show a replay of the demo route. @@ -43,39 +43,36 @@ If you have your own comma device, you can replace `--demo` with one of your own Now let’s update the speed display color in the UI. -Search for the function responsible for rendering UI text: +Search for the function responsible for rendering the current speed: ```bash -git grep "drawText" selfdrive/ui/qt/onroad/hud.cc +git grep "_draw_current_speed" openpilot/selfdrive/ui/onroad/hud_renderer.py ``` -You’ll find the relevant code inside `selfdrive/ui/qt/onroad/hud.cc`, in this function: +You'll find the relevant code inside `openpilot/selfdrive/ui/onroad/hud_renderer.py`, in this function: -```cpp -void HudRenderer::drawText(QPainter &p, int x, int y, const QString &text, int alpha) { - QRect real_rect = p.fontMetrics().boundingRect(text); - real_rect.moveCenter({x, y - real_rect.height() / 2}); - - p.setPen(QColor(0xff, 0xff, 0xff, alpha)); // <- this sets the speed text color - p.drawText(real_rect.x(), real_rect.bottom(), text); -} +```python +def _draw_current_speed(self, rect: rl.Rectangle) -> None: + """Draw the current vehicle speed and unit.""" + speed_text = str(round(self.speed)) + speed_text_size = measure_text_cached(self._font_bold, speed_text, FONT_SIZES.current_speed) + speed_pos = rl.Vector2(rect.x + rect.width / 2 - speed_text_size.x / 2, 180 - speed_text_size.y / 2) + rl.draw_text_ex(self._font_bold, speed_text, speed_pos, FONT_SIZES.current_speed, 0, COLORS.white) # <- this sets the speed text color ``` -Change the `QColor(...)` line to make it **blue** instead of white. A nice soft blue is `#8080FF`, which translates to: +Change `COLORS.white` to make it **blue** instead of white. A nice soft blue is `#8080FF`, which you can change inline: ```diff -- p.setPen(QColor(0xff, 0xff, 0xff, alpha)); -+ p.setPen(QColor(0x80, 0x80, 0xFF, alpha)); +- rl.draw_text_ex(self._font_bold, speed_text, speed_pos, FONT_SIZES.current_speed, 0, COLORS.white) ++ rl.draw_text_ex(self._font_bold, speed_text, speed_pos, FONT_SIZES.current_speed, 0, rl.Color(0x80, 0x80, 0xFF, 255)) ``` -This change will tint all speed-related UI text to blue with the same transparency (`alpha`). - --- -## 4. Rebuild the UI +## 4. Re-run the UI -After making changes, rebuild Openpilot so your new UI is compiled: +After making changes, re-run the UI to see your new UI: ```bash -scons -j$(nproc) && selfdrive/ui/ui +./openpilot/selfdrive/ui/ui.py ``` ![](https://blog.comma.ai/img/blue_speed_ui.png) diff --git a/docs/index.md b/docs/index.md deleted file mode 120000 index 74ea27aeeb..0000000000 --- a/docs/index.md +++ /dev/null @@ -1 +0,0 @@ -getting-started/what-is-openpilot.md \ No newline at end of file diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 0000000000..6fab2b979b --- /dev/null +++ b/docs/index.md @@ -0,0 +1,12 @@ +# What is openpilot? + +[openpilot](http://github.com/commaai/openpilot) is an open source driver assistance system. Currently, openpilot performs the functions of Adaptive Cruise Control (ACC), Automated Lane Centering (ALC), Forward Collision Warning (FCW), and Lane Departure Warning (LDW) for a growing variety of [supported car makes, models, and model years](https://github.com/commaai/openpilot/blob/master/docs/CARS.md). In addition, while openpilot is engaged, a camera-based Driver Monitoring (DM) feature alerts distracted and asleep drivers. See more about [the vehicle integration](https://github.com/commaai/openpilot/blob/master/docs/INTEGRATION.md) and [limitations](https://github.com/commaai/openpilot/blob/master/docs/LIMITATIONS.md). + + +## How do I use it? + +openpilot is designed to be used on the comma four. + +## How does it work? + +In short, openpilot uses the car's existing APIs for the built-in [ADAS](https://en.wikipedia.org/wiki/Advanced_driver-assistance_system) system and simply provides better acceleration, braking, and steering inputs than the stock system. diff --git a/docs/stylesheets/extra.css b/docs/stylesheets/extra.css new file mode 100644 index 0000000000..36ce354af1 --- /dev/null +++ b/docs/stylesheets/extra.css @@ -0,0 +1,42 @@ +.md-logo img { + filter: invert(1); +} + +.glossary-term { + position: relative; + color: inherit; + text-decoration: none; +} + +.glossary-term__label { + border-bottom: 1px dotted currentColor; +} + +.glossary-term__tooltip { + position: absolute; + top: calc(100% + 0.4rem); + left: 50%; + width: max-content; + max-width: min(30rem, 80vw); + padding: 0.65rem 0.8rem; + border-radius: 0.6rem; + background: rgb(26 26 26 / 96%); + color: white; + box-shadow: 0 0.6rem 1.8rem rgb(0 0 0 / 22%); + font-size: 0.85rem; + line-height: 1.45; + opacity: 0; + pointer-events: none; + transform: translateX(-50%) translateY(-0.15rem); + transition: opacity 120ms ease, transform 120ms ease; + visibility: hidden; + z-index: 20; +} + +.glossary-term:hover .glossary-term__tooltip, +.glossary-term:focus-visible .glossary-term__tooltip, +.glossary-term:focus-within .glossary-term__tooltip { + opacity: 1; + transform: translateX(-50%) translateY(0); + visibility: visible; +} diff --git a/launch_chffrplus.sh b/launch_chffrplus.sh index d4689aae53..4f767f3b19 100755 --- a/launch_chffrplus.sh +++ b/launch_chffrplus.sh @@ -7,6 +7,7 @@ source "$DIR/launch_env.sh" function agnos_init { # TODO: move this to agnos sudo rm -f /data/etc/NetworkManager/system-connections/*.nmmeta + rm -f /data/scons_cache/config.lock # set success flag for current boot slot sudo abctl --set_success @@ -18,12 +19,12 @@ function agnos_init { # Check if AGNOS update is required if [ $(< /VERSION) != "$AGNOS_VERSION" ]; then - AGNOS_PY="$DIR/system/hardware/tici/agnos.py" - MANIFEST="$DIR/system/hardware/tici/agnos.json" + AGNOS_PY="$DIR/openpilot/common/hardware/tici/agnos.py" + MANIFEST="$DIR/openpilot/system/hardware/tici/agnos.json" if $AGNOS_PY --verify $MANIFEST; then sudo reboot fi - $DIR/system/hardware/tici/updater $AGNOS_PY $MANIFEST + $DIR/openpilot/common/hardware/tici/updater $AGNOS_PY $MANIFEST fi } @@ -69,6 +70,14 @@ function launch { ln -sfn $(pwd) /data/pythonpath export PYTHONPATH="$PWD" + # submodule package symlinks for PYTHONPATH imports on device. + # on PC these come from editable installs via pyproject.toml / uv. + ln -sfn msgq_repo/msgq msgq + ln -sfn opendbc_repo/opendbc opendbc + ln -sfn rednose_repo/rednose rednose + ln -sfn teleoprtc_repo/teleoprtc teleoprtc + ln -sfn tinygrad_repo/tinygrad tinygrad + # hardware specific init if [ -f /AGNOS ]; then agnos_init @@ -78,7 +87,7 @@ function launch { tmux capture-pane -pq -S-1000 > /tmp/launch_log # start manager - cd system/manager + cd openpilot/system/manager if [ ! -f $DIR/prebuilt ]; then ./build.py fi diff --git a/launch_env.sh b/launch_env.sh index b0bff4e57f..3e0ca602b4 100755 --- a/launch_env.sh +++ b/launch_env.sh @@ -6,8 +6,17 @@ export NUMEXPR_NUM_THREADS=1 export OPENBLAS_NUM_THREADS=1 export VECLIB_MAXIMUM_THREADS=1 +# models get lower priority than ui +# - ui is ~5ms +# - modeld is 20ms +# - DM is 10ms +# in order to run ui at 60fps (16.67ms), we need to allow +# it to preempt the model workloads. we have enough +# headroom for this until ui is moved to the CPU. +export QCOM_PRIORITY=12 + if [ -z "$AGNOS_VERSION" ]; then - export AGNOS_VERSION="12.4" + export AGNOS_VERSION="18.5" fi export STAGING_ROOT="/data/safe_staging" diff --git a/mkdocs.yml b/mkdocs.yml deleted file mode 100644 index a66d1c76d4..0000000000 --- a/mkdocs.yml +++ /dev/null @@ -1,44 +0,0 @@ -site_name: openpilot docs -repo_url: https://github.com/commaai/openpilot/ -site_url: https://docs.comma.ai - -exclude_docs: README.md - -strict: true -docs_dir: docs -site_dir: docs_site/ - -hooks: - - docs/hooks/glossary.py -extra_css: - - css/tooltip.css -theme: - name: readthedocs - navigation_depth: 3 - -nav: - - Getting Started: - - What is openpilot?: getting-started/what-is-openpilot.md - - How-to: - - Turn the speed blue: how-to/turn-the-speed-blue.md - - Connect to a comma 3/3X: how-to/connect-to-comma.md - # - Make your first pull request: how-to/make-first-pr.md - #- Replay a drive: how-to/replay-a-drive.md - - Concepts: - - Logs: concepts/logs.md - - Safety: concepts/safety.md - - Glossary: concepts/glossary.md - - Car Porting: - - What is a car port?: car-porting/what-is-a-car-port.md - - Porting a car brand: car-porting/brand-port.md - - Porting a car model: car-porting/model-port.md - - Contributing: - - Roadmap: contributing/roadmap.md - #- Architecture: contributing/architecture.md - - Contributing Guide →: https://github.com/commaai/openpilot/blob/master/docs/CONTRIBUTING.md - - Links: - - Blog →: https://blog.comma.ai - - Bounties →: https://comma.ai/bounties - - GitHub →: https://github.com/commaai - - Discord →: https://discord.comma.ai - - X →: https://x.com/comma_ai diff --git a/msgq b/msgq deleted file mode 120000 index df09146f62..0000000000 --- a/msgq +++ /dev/null @@ -1 +0,0 @@ -msgq_repo/msgq \ No newline at end of file diff --git a/msgq_repo b/msgq_repo index fd7bd0df50..bb6cc57ef4 160000 --- a/msgq_repo +++ b/msgq_repo @@ -1 +1 @@ -Subproject commit fd7bd0df50a95dca3f180705721aa1fa300aef0f +Subproject commit bb6cc57ef4d9a3f9952d9ca84bfa580575e7e2a0 diff --git a/opendbc b/opendbc deleted file mode 120000 index 7cd9a5bd1e..0000000000 --- a/opendbc +++ /dev/null @@ -1 +0,0 @@ -opendbc_repo/opendbc \ No newline at end of file diff --git a/opendbc_repo b/opendbc_repo index 2c5d97a7c1..d6113f8440 160000 --- a/opendbc_repo +++ b/opendbc_repo @@ -1 +1 @@ -Subproject commit 2c5d97a7c1eaf494f300cd47fd4dda4e48e2904f +Subproject commit d6113f84405b3eff8f994c8313bfa64e01e57983 diff --git a/openpilot/cereal/README.md b/openpilot/cereal/README.md new file mode 100644 index 0000000000..17f27fd742 --- /dev/null +++ b/openpilot/cereal/README.md @@ -0,0 +1,95 @@ +# What is cereal? + +cereal is the messaging system for openpilot. It uses [msgq](https://github.com/commaai/msgq) as a pub/sub backend, and [Cap'n proto](https://capnproto.org/capnp-tool.html) for serialization of the structs. + + +## Messaging Spec + +You'll find the message types in [log.capnp](log.capnp). It uses [Cap'n proto](https://capnproto.org/capnp-tool.html) and defines one struct called `Event`. + +All `Events` have a `logMonoTime` and a `valid`. Then a big union defines the packet type. + +### Best Practices + +- **All fields must describe quantities in SI units**, unless otherwise specified in the field name. +- In the context of the message they are in, field names should be completely unambiguous. +- All values should be easy to plot and be human-readable with minimal parsing. + +### Maintaining backwards-compatibility + +When making changes to the messaging spec you want to maintain backwards-compatibility, such that old logs can +be parsed with a new version of cereal. Adding structs and adding members to structs is generally safe, most other +things are not. Read more details [here](https://capnproto.org/language.html). + +### Custom forks + +Forks of [openpilot](https://github.com/commaai/openpilot) might want to add things to the messaging +spec, however this could conflict with future changes made in mainline openpilot's cereal spec. Rebasing against mainline openpilot +then means breaking backwards-compatibility with all old logs of your fork. So we added reserved events in +[custom.capnp](custom.capnp) that we will leave empty in mainline openpilot's cereal spec. **If you only modify those, you can ensure your +fork will remain backwards-compatible with all versions of mainline openpilot and your fork.** + +An example of compatible changes: +```diff +diff --git a/openpilot/cereal/custom.capnp b/openpilot/cereal/custom.capnp +index 3348e859e..3365c7b98 100644 +--- a/openpilot/cereal/custom.capnp ++++ b/openpilot/cereal/custom.capnp +@@ -10,7 +10,11 @@ $Cxx.namespace("cereal"); + # DO rename the structs + # DON'T change the identifier (e.g. @0x81c2f05a394cf4af) + +-struct CustomReserved0 @0x81c2f05a394cf4af { ++struct SteeringInfo @0x81c2f05a394cf4af { ++ active @0 :Bool; ++ steeringAngleDeg @1 :Float32; ++ steeringRateDeg @2 :Float32; ++ steeringAccelDeg @3 :Float32; + } + + struct CustomReserved1 @0xaedffd8f31e7b55d { +diff --git a/openpilot/cereal/log.capnp b/openpilot/cereal/log.capnp +index 1209f3fd9..b189f58b6 100644 +--- a/openpilot/cereal/log.capnp ++++ b/openpilot/cereal/log.capnp +@@ -2558,14 +2558,14 @@ struct Event { + + # DO change the name of the field + # DON'T change anything after the "@" +- customReservedRawData0 @124 :Data; ++ rawCanData @124 :Data; + customReservedRawData1 @125 :Data; + customReservedRawData2 @126 :Data; + + # DO change the name of the field and struct + # DON'T change the ID (e.g. @107) + # DON'T change which struct it points to +- customReserved0 @107 :Custom.CustomReserved0; ++ steeringInfo @107 :Custom.SteeringInfo; + customReserved1 @108 :Custom.CustomReserved1; + customReserved2 @109 :Custom.CustomReserved2; + customReserved3 @110 :Custom.CustomReserved3; +``` + +--- + +Example +--- +```python +import openpilot.cereal.messaging as messaging + +# in subscriber +sm = messaging.SubMaster(['sensorEvents']) +while 1: + sm.update() + print(sm['sensorEvents']) + +``` + +```python +# in publisher +pm = messaging.PubMaster(['sensorEvents']) +dat = messaging.new_message('sensorEvents', size=1) +dat.sensorEvents[0] = {"gyro": {"v": [0.1, -0.1, 0.1]}} +pm.send('sensorEvents', dat) +``` diff --git a/openpilot/cereal/SConscript b/openpilot/cereal/SConscript new file mode 100644 index 0000000000..bee7620b1e --- /dev/null +++ b/openpilot/cereal/SConscript @@ -0,0 +1,22 @@ +Import('env', 'common', 'msgq') + +cereal_dir = Dir('.') +gen_dir = Dir('gen') + +# Build cereal +schema_files = ['log.capnp', 'deprecated.capnp', 'custom.capnp'] +car_capnp = '#opendbc_repo/opendbc/car/car.capnp' +all_output = schema_files + ['car.capnp'] +env.Command([f'gen/cpp/{s}.c++' for s in all_output] + [f'gen/cpp/{s}.h' for s in all_output], + schema_files + [car_capnp], + f"capnpc --src-prefix={cereal_dir.path} --src-prefix=opendbc_repo/opendbc/car --import-path=opendbc_repo/opendbc/car $SOURCES -o c++:{gen_dir.path}/cpp/") + +cereal = env.Library('cereal', [f'gen/cpp/{s}.c++' for s in all_output]) + +# Build messaging +services_h = env.Command(['services.h'], ['services.py'], 'python3 ' + cereal_dir.path + '/services.py > $TARGET') +env.Program('messaging/bridge', ['messaging/bridge.cc', 'messaging/msgq_to_zmq.cc', 'messaging/bridge_zmq.cc'], LIBS=[msgq, common, 'pthread']) + +socketmaster = env.Library('socketmaster', ['messaging/socketmaster.cc']) + +Export('cereal', 'socketmaster') diff --git a/openpilot/cereal/__init__.py b/openpilot/cereal/__init__.py new file mode 100644 index 0000000000..d4a43a8474 --- /dev/null +++ b/openpilot/cereal/__init__.py @@ -0,0 +1,11 @@ +import os +import capnp +from importlib.resources import as_file, files + +capnp.remove_import_hook() + +with as_file(files("openpilot.cereal")) as fspath, as_file(files("opendbc")) as opendbc_path: + CEREAL_PATH = fspath.as_posix() + opendbc_import_path = os.path.join(os.path.realpath(opendbc_path.as_posix()), 'car') + log = capnp.load(os.path.join(CEREAL_PATH, "log.capnp"), imports=[opendbc_import_path]) + custom = capnp.load(os.path.join(CEREAL_PATH, "custom.capnp"), imports=[opendbc_import_path]) diff --git a/openpilot/cereal/custom.capnp b/openpilot/cereal/custom.capnp new file mode 100644 index 0000000000..e78f7a75c7 --- /dev/null +++ b/openpilot/cereal/custom.capnp @@ -0,0 +1,487 @@ +using Cxx = import "/include/c++.capnp"; +$Cxx.namespace("cereal"); + +@0xb526ba661d550a59; + +# custom.capnp: a home for empty structs reserved for custom forks +# These structs are guaranteed to remain reserved and empty in mainline +# cereal, so use these if you want custom events in your fork. + +# DO rename the structs +# DON'T change the identifier (e.g. @0x81c2f05a394cf4af) + +struct ModularAssistiveDrivingSystem { + state @0 :ModularAssistiveDrivingSystemState; + enabled @1 :Bool; + active @2 :Bool; + available @3 :Bool; + + enum ModularAssistiveDrivingSystemState { + disabled @0; + paused @1; + enabled @2; + softDisabling @3; + overriding @4; + } +} + +struct IntelligentCruiseButtonManagement { + state @0 :IntelligentCruiseButtonManagementState; + sendButton @1 :SendButtonState; + vTarget @2 :Float32; + + enum IntelligentCruiseButtonManagementState { + inactive @0; # No button press or default state + preActive @1; # Pre-active state before transitioning to increasing or decreasing + increasing @2; # Increasing speed + decreasing @3; # Decreasing speed + holding @4; # Holding steady speed + } + + enum SendButtonState { + none @0; + increase @1; + decrease @2; + } +} + +# Same struct as Log.RadarState.LeadData +struct LeadData { + dRel @0 :Float32; + yRel @1 :Float32; + vRel @2 :Float32; + aRel @3 :Float32; + vLead @4 :Float32; + dPath @6 :Float32; + vLat @7 :Float32; + vLeadK @8 :Float32; + aLeadK @9 :Float32; + fcw @10 :Bool; + status @11 :Bool; + aLeadTau @12 :Float32; + modelProb @13 :Float32; + radar @14 :Bool; + radarTrackId @15 :Int32 = -1; + + aLeadDEPRECATED @5 :Float32; +} + +struct SelfdriveStateSP @0x81c2f05a394cf4af { + mads @0 :ModularAssistiveDrivingSystem; + intelligentCruiseButtonManagement @1 :IntelligentCruiseButtonManagement; + + enum AudibleAlert { + none @0; + + engage @1; + disengage @2; + refuse @3; + + warningSoft @4; + warningImmediate @5; + + prompt @6; + promptRepeat @7; + promptDistracted @8; + + # unused, these are reserved for upstream events so we don't collide + reserved9 @9; + reserved10 @10; + reserved11 @11; + reserved12 @12; + reserved13 @13; + reserved14 @14; + reserved15 @15; + reserved16 @16; + reserved17 @17; + reserved18 @18; + reserved19 @19; + reserved20 @20; + reserved21 @21; + reserved22 @22; + reserved23 @23; + reserved24 @24; + reserved25 @25; + reserved26 @26; + reserved27 @27; + reserved28 @28; + reserved29 @29; + reserved30 @30; + + promptSingleLow @31; + promptSingleHigh @32; + } +} + +struct ModelManagerSP @0xaedffd8f31e7b55d { + activeBundle @0 :ModelBundle; + selectedBundle @1 :ModelBundle; + availableBundles @2 :List(ModelBundle); + + struct DownloadUri { + uri @0 :Text; + sha256 @1 :Text; + } + + enum DownloadStatus { + notDownloading @0; + downloading @1; + downloaded @2; + cached @3; + failed @4; + } + + struct DownloadProgress { + status @0 :DownloadStatus; + progress @1 :Float32; + eta @2 :UInt32; + } + + struct Artifact { + fileName @0 :Text; + downloadUri @1 :DownloadUri; + downloadProgress @2 :DownloadProgress; + } + + struct Model { + type @0 :Type; + artifact @1 :Artifact; # Main artifact + metadata @2 :Artifact; # Metadata artifact + + enum Type { + supercombo @0; + navigation @1; + vision @2; + policy @3; + offPolicy @4; + onPolicy @5; + } + } + + enum Runner { + snpe @0; + tinygrad @1; + stock @2; + } + + struct Override { + key @0 :Text; + value @1 :Text; + } + + struct ModelBundle { + index @0 :UInt32; + internalName @1 :Text; + displayName @2 :Text; + models @3 :List(Model); + status @4 :DownloadStatus; + generation @5 :UInt32; + environment @6 :Text; + runner @7 :Runner; + is20hz @8 :Bool; + ref @9 :Text; + minimumSelectorVersion @10 :UInt32; + overrides @11 :List(Override); + } +} + +struct LongitudinalPlanSP @0xf35cc4560bbf6ec2 { + dec @0 :DynamicExperimentalControl; + longitudinalPlanSource @1 :LongitudinalPlanSource; + smartCruiseControl @2 :SmartCruiseControl; + speedLimit @3 :SpeedLimit; + vTarget @4 :Float32; + aTarget @5 :Float32; + events @6 :List(OnroadEventSP.Event); + e2eAlerts @7 :E2eAlerts; + + struct DynamicExperimentalControl { + state @0 :DynamicExperimentalControlState; + enabled @1 :Bool; + active @2 :Bool; + + enum DynamicExperimentalControlState { + acc @0; + blended @1; + } + } + + struct SmartCruiseControl { + vision @0 :Vision; + map @1 :Map; + + struct Vision { + state @0 :VisionState; + vTarget @1 :Float32; + aTarget @2 :Float32; + currentLateralAccel @3 :Float32; + maxPredictedLateralAccel @4 :Float32; + enabled @5 :Bool; + active @6 :Bool; + } + + struct Map { + state @0 :MapState; + vTarget @1 :Float32; + aTarget @2 :Float32; + enabled @3 :Bool; + active @4 :Bool; + } + + enum VisionState { + disabled @0; # System disabled or inactive. + enabled @1; # No predicted substantial turn on vision range. + entering @2; # A substantial turn is predicted ahead, adapting speed to turn comfort levels. + turning @3; # Actively turning. Managing acceleration to provide a roll on turn feeling. + leaving @4; # Road ahead straightens. Start to allow positive acceleration. + overriding @5; # System overriding with manual control. + } + + enum MapState { + disabled @0; # System disabled or inactive. + enabled @1; # No predicted substantial turn on map range. + turning @2; # Actively turning. Managing acceleration to provide a roll on turn feeling. + overriding @3; # System overriding with manual control. + } + } + + struct SpeedLimit { + resolver @0 :Resolver; + assist @1 :Assist; + + struct Resolver { + speedLimit @0 :Float32; + distToSpeedLimit @1 :Float32; + source @2 :Source; + speedLimitOffset @3 :Float32; + speedLimitLast @4 :Float32; + speedLimitFinal @5 :Float32; + speedLimitFinalLast @6 :Float32; + speedLimitValid @7 :Bool; + speedLimitLastValid @8 :Bool; + } + + struct Assist { + state @0 :AssistState; + enabled @1 :Bool; + active @2 :Bool; + vTarget @3 :Float32; + aTarget @4 :Float32; + } + + enum Source { + none @0; + car @1; + map @2; + } + + enum AssistState { + disabled @0; + inactive @1; # No speed limit set or not enabled by parameter. + preActive @2; + pending @3; # Awaiting new speed limit. + adapting @4; # Reducing speed to match new speed limit. + active @5; # Cruising at speed limit. + } + } + + enum LongitudinalPlanSource { + cruise @0; + sccVision @1; + sccMap @2; + speedLimitAssist @3; + } + + struct E2eAlerts { + greenLightAlert @0 :Bool; + leadDepartAlert @1 :Bool; + } +} + +struct OnroadEventSP @0xda96579883444c35 { + events @0 :List(Event); + + struct Event { + name @0 :EventName; + + # event types + enable @1 :Bool; + noEntry @2 :Bool; + warning @3 :Bool; # alerts presented only when enabled or soft disabling + userDisable @4 :Bool; + softDisable @5 :Bool; + immediateDisable @6 :Bool; + preEnable @7 :Bool; + permanent @8 :Bool; # alerts presented regardless of openpilot state + overrideLateral @10 :Bool; + overrideLongitudinal @9 :Bool; + } + + enum EventName { + lkasEnable @0; + lkasDisable @1; + manualSteeringRequired @2; + manualLongitudinalRequired @3; + silentLkasEnable @4; + silentLkasDisable @5; + silentBrakeHold @6; + silentWrongGear @7; + silentReverseGear @8; + silentDoorOpen @9; + silentSeatbeltNotLatched @10; + silentParkBrake @11; + controlsMismatchLateral @12; + hyundaiRadarTracksConfirmed @13; + experimentalModeSwitched @14; + wrongCarModeAlertOnly @15; + pedalPressedAlertOnly @16; + laneTurnLeft @17; + laneTurnRight @18; + speedLimitPreActive @19; + speedLimitActive @20; + speedLimitChanged @21; + speedLimitPending @22; + e2eChime @23; + } +} + +struct CarParamsSP @0x80ae746ee2596b11 { + flags @0 :UInt32; # flags for car specific quirks in sunnypilot + safetyParam @1 : Int16; # flags for sunnypilot's custom safety flags + pcmCruiseSpeed @3 :Bool; + intelligentCruiseButtonManagementAvailable @4 :Bool; + enableGasInterceptor @5 :Bool; + + neuralNetworkLateralControl @2 :NeuralNetworkLateralControl; + + struct NeuralNetworkLateralControl { + model @0 :Model; + fuzzyFingerprint @1 :Bool; + + struct Model { + path @0 :Text; + name @1 :Text; + } + } +} + +struct CarControlSP @0xa5cd762cd951a455 { + mads @0 :ModularAssistiveDrivingSystem; + params @1 :List(Param); + leadOne @2 :LeadData; + leadTwo @3 :LeadData; + intelligentCruiseButtonManagement @4 :IntelligentCruiseButtonManagement; + + struct Param { + key @0 :Text; + type @2 :ParamType; + value @3 :Data; + + valueDEPRECATED @1 :Text; # The data type change may cause issues with backwards compatibility. + } + + enum ParamType { + string @0; + bool @1; + int @2; + float @3; + time @4; + json @5; + bytes @6; + } +} + +struct BackupManagerSP @0xf98d843bfd7004a3 { + backupStatus @0 :Status; + restoreStatus @1 :Status; + backupProgress @2 :Float32; + restoreProgress @3 :Float32; + lastError @4 :Text; + currentBackup @5 :BackupInfo; + backupHistory @6 :List(BackupInfo); + + enum Status { + idle @0; + inProgress @1; + completed @2; + failed @3; + } + + struct Version { + major @0 :UInt16; + minor @1 :UInt16; + patch @2 :UInt16; + build @3 :UInt16; + branch @4 :Text; + } + + struct MetadataEntry { + key @0 :Text; + value @1 :Text; + tags @2 :List(Text); + } + + struct BackupInfo { + deviceId @0 :Text; + version @1 :UInt32; + config @2 :Text; + isEncrypted @3 :Bool; + createdAt @4 :Text; # ISO timestamp + updatedAt @5 :Text; # ISO timestamp + sunnypilotVersion @6 :Version; + backupMetadata @7 :List(MetadataEntry); + } +} + +struct CarStateSP @0xb86e6369214c01c8 { + speedLimit @0 :Float32; +} + +struct LiveMapDataSP @0xf416ec09499d9d19 { + speedLimitValid @0 :Bool; + speedLimit @1 :Float32; + speedLimitAheadValid @2 :Bool; + speedLimitAhead @3 :Float32; + speedLimitAheadDistance @4 :Float32; + roadName @5 :Text; +} + +struct ModelDataV2SP @0xa1680744031fdb2d { + laneTurnDirection @0 :TurnDirection; + + enum TurnDirection { + none @0; + turnLeft @1; + turnRight @2; + } +} + +struct CustomReserved10 @0xcb9fd56c7057593a { +} + +struct CustomReserved11 @0xc2243c65e0340384 { +} + +struct CustomReserved12 @0x9ccdc8676701b412 { +} + +struct CustomReserved13 @0xcd96dafb67a082d0 { +} + +struct CustomReserved14 @0xb057204d7deadf3f { +} + +struct CustomReserved15 @0xbd443b539493bc68 { +} + +struct CustomReserved16 @0xfc6241ed8877b611 { +} + +struct CustomReserved17 @0xa30662f84033036c { +} + +struct CustomReserved18 @0xc86a3d38d13eb3ef { +} + +struct CustomReserved19 @0xa4f1eb3323f5f582 { +} diff --git a/openpilot/cereal/deprecated.capnp b/openpilot/cereal/deprecated.capnp new file mode 100644 index 0000000000..37153e4d62 --- /dev/null +++ b/openpilot/cereal/deprecated.capnp @@ -0,0 +1,777 @@ +using Cxx = import "/include/c++.capnp"; +$Cxx.namespace("cereal"); + +@0x80ef1ec4889c2a63; + +# deprecated.capnp: a home for deprecated structs + +struct LogRotate @0x9811e1f38f62f2d1 { + segmentNum @0 :Int32; + path @1 :Text; +} + +struct LiveUI @0xc08240f996aefced { + rearViewCam @0 :Bool; + alertText1 @1 :Text; + alertText2 @2 :Text; + awarenessStatus @3 :Float32; +} + +struct UiLayoutState @0x88dcce08ad29dda0 { + activeApp @0 :App; + sidebarCollapsed @1 :Bool; + mapEnabled @2 :Bool; + mockEngaged @3 :Bool; + + enum App @0x9917470acf94d285 { + home @0; + music @1; + nav @2; + settings @3; + none @4; + } +} + +struct OrbslamCorrection @0x8afd33dc9b35e1aa { + correctionMonoTime @0 :UInt64; + prePositionECEF @1 :List(Float64); + postPositionECEF @2 :List(Float64); + prePoseQuatECEF @3 :List(Float32); + postPoseQuatECEF @4 :List(Float32); + numInliers @5 :UInt32; +} + +struct EthernetPacket @0xa99a9d5b33cf5859 { + pkt @0 :Data; + ts @1 :Float32; +} + +struct CellInfo @0xcff7566681c277ce { + timestamp @0 :UInt64; + repr @1 :Text; # android toString() for now +} + +struct WifiScan @0xd4df5a192382ba0b { + bssid @0 :Text; + ssid @1 :Text; + capabilities @2 :Text; + frequency @3 :Int32; + level @4 :Int32; + timestamp @5 :Int64; + + centerFreq0 @6 :Int32; + centerFreq1 @7 :Int32; + channelWidth @8 :ChannelWidth; + operatorFriendlyName @9 :Text; + venueName @10 :Text; + is80211mcResponder @11 :Bool; + passpoint @12 :Bool; + + distanceCm @13 :Int32; + distanceSdCm @14 :Int32; + + enum ChannelWidth @0xcb6a279f015f6b51 { + w20Mhz @0; + w40Mhz @1; + w80Mhz @2; + w160Mhz @3; + w80Plus80Mhz @4; + } +} + +struct LiveEventData @0x94b7baa90c5c321e { + name @0 :Text; + value @1 :Int32; +} + +struct ModelData @0xb8aad62cffef28a9 { + frameId @0 :UInt32; + frameAge @12 :UInt32; + frameDropPerc @13 :Float32; + timestampEof @9 :UInt64; + modelExecutionTime @14 :Float32; + gpuExecutionTime @16 :Float32; + rawPred @15 :Data; + + path @1 :PathData; + leftLane @2 :PathData; + rightLane @3 :PathData; + lead @4 :LeadData; + freePath @6 :List(Float32); + + settings @5 :ModelSettings; + leadFuture @7 :LeadData; + speed @8 :List(Float32); + meta @10 :MetaData; + longitudinal @11 :LongitudinalData; + + struct PathData @0x8817eeea389e9f08 { + points @0 :List(Float32); + prob @1 :Float32; + std @2 :Float32; + stds @3 :List(Float32); + poly @4 :List(Float32); + validLen @5 :Float32; + } + + struct LeadData @0xd1c9bef96d26fa91 { + dist @0 :Float32; + prob @1 :Float32; + std @2 :Float32; + relVel @3 :Float32; + relVelStd @4 :Float32; + relY @5 :Float32; + relYStd @6 :Float32; + relA @7 :Float32; + relAStd @8 :Float32; + } + + struct ModelSettings @0xa26e3710efd3e914 { + bigBoxX @0 :UInt16; + bigBoxY @1 :UInt16; + bigBoxWidth @2 :UInt16; + bigBoxHeight @3 :UInt16; + boxProjection @4 :List(Float32); + yuvCorrection @5 :List(Float32); + inputTransform @6 :List(Float32); + } + + struct MetaData @0x9744f25fb60f2bf8 { + engagedProb @0 :Float32; + desirePrediction @1 :List(Float32); + brakeDisengageProb @2 :Float32; + gasDisengageProb @3 :Float32; + steerOverrideProb @4 :Float32; + desireState @5 :List(Float32); + } + + struct LongitudinalData @0xf98f999c6a071122 { + distances @2 :List(Float32); + speeds @0 :List(Float32); + accelerations @1 :List(Float32); + } +} + +struct ECEFPoint @0xc25bbbd524983447 { + x @0 :Float64; + y @1 :Float64; + z @2 :Float64; +} + +struct ECEFPointDEPRECATED @0xe10e21168db0c7f7 { + x @0 :Float32; + y @1 :Float32; + z @2 :Float32; +} + +struct GPSPlannerPoints @0xab54c59699f8f9f3 { + curPosDEPRECATED @0 :ECEFPointDEPRECATED; + pointsDEPRECATED @1 :List(ECEFPointDEPRECATED); + curPos @6 :ECEFPoint; + points @7 :List(ECEFPoint); + valid @2 :Bool; + trackName @3 :Text; + speedLimit @4 :Float32; + accelTarget @5 :Float32; +} + +struct GPSPlannerPlan @0xf5ad1d90cdc1dd6b { + valid @0 :Bool; + poly @1 :List(Float32); + trackName @2 :Text; + speed @3 :Float32; + acceleration @4 :Float32; + pointsDEPRECATED @5 :List(ECEFPointDEPRECATED); + points @6 :List(ECEFPoint); + xLookahead @7 :Float32; +} + +struct UiNavigationEvent @0x90c8426c3eaddd3b { + type @0: Type; + status @1: Status; + distanceTo @2: Float32; + endRoadPointDEPRECATED @3: ECEFPointDEPRECATED; + endRoadPoint @4: ECEFPoint; + + enum Type @0xe8db07dcf8fcea05 { + none @0; + laneChangeLeft @1; + laneChangeRight @2; + mergeLeft @3; + mergeRight @4; + turnLeft @5; + turnRight @6; + } + + enum Status @0xb9aa88c75ef99a1f { + none @0; + passive @1; + approaching @2; + active @3; + } +} + +struct LiveLocationData @0xb99b2bc7a57e8128 { + status @0 :UInt8; + + # 3D fix + lat @1 :Float64; + lon @2 :Float64; + alt @3 :Float32; # m + + # speed + speed @4 :Float32; # m/s + + # NED velocity components + vNED @5 :List(Float32); + + # roll, pitch, heading (x,y,z) + roll @6 :Float32; # WRT to center of earth? + pitch @7 :Float32; # WRT to center of earth? + heading @8 :Float32; # WRT to north? + + # what are these? + wanderAngle @9 :Float32; + trackAngle @10 :Float32; + + # car frame -- https://upload.wikimedia.org/wikipedia/commons/f/f5/RPY_angles_of_cars.png + + # gyro, in car frame, deg/s + gyro @11 :List(Float32); + + # accel, in car frame, m/s^2 + accel @12 :List(Float32); + + accuracy @13 :Accuracy; + + source @14 :SensorSource; + # if we are fixing a location in the past + fixMonoTime @15 :UInt64; + + gpsWeek @16 :Int32; + timeOfWeek @17 :Float64; + + positionECEF @18 :List(Float64); + poseQuatECEF @19 :List(Float32); + pitchCalibration @20 :Float32; + yawCalibration @21 :Float32; + imuFrame @22 :List(Float32); + + struct Accuracy @0x943dc4625473b03f { + pNEDError @0 :List(Float32); + vNEDError @1 :List(Float32); + rollError @2 :Float32; + pitchError @3 :Float32; + headingError @4 :Float32; + ellipsoidSemiMajorError @5 :Float32; + ellipsoidSemiMinorError @6 :Float32; + ellipsoidOrientationError @7 :Float32; + } + + enum SensorSource @0xc871d3cc252af657 { + applanix @0; + kalman @1; + orbslam @2; + timing @3; + dummy @4; + } +} + +struct OrbOdometry @0xd7700859ed1f5b76 { + # timing first + startMonoTime @0 :UInt64; + endMonoTime @1 :UInt64; + + # fundamental matrix and error + f @2: List(Float64); + err @3: Float64; + + # number of inlier points + inliers @4: Int32; + + # for debug only + # indexed by endMonoTime features + # value is startMonoTime feature match + # -1 if no match + matches @5: List(Int16); +} + +struct OrbFeatures @0xcd60164a8a0159ef { + timestampEof @0 :UInt64; + # transposed arrays of normalized image coordinates + # len(xs) == len(ys) == len(descriptors) * 32 + xs @1 :List(Float32); + ys @2 :List(Float32); + descriptors @3 :Data; + octaves @4 :List(Int8); + + # match index to last OrbFeatures + # -1 if no match + timestampLastEof @5 :UInt64; + matches @6: List(Int16); +} + +struct OrbFeaturesSummary @0xd500d30c5803fa4f { + timestampEof @0 :UInt64; + timestampLastEof @1 :UInt64; + + featureCount @2 :UInt16; + matchCount @3 :UInt16; + computeNs @4 :UInt64; +} + +struct OrbKeyFrame @0xc8233c0345e27e24 { + # this is a globally unique id for the KeyFrame + id @0: UInt64; + + # this is the location of the KeyFrame + pos @1: ECEFPoint; + + # these are the features in the world + # len(dpos) == len(descriptors) * 32 + dpos @2 :List(ECEFPoint); + descriptors @3 :Data; +} + +struct KalmanOdometry @0x92e21bb7ea38793a { + trans @0 :List(Float32); # m/s in device frame + rot @1 :List(Float32); # rad/s in device frame + transStd @2 :List(Float32); # std m/s in device frame + rotStd @3 :List(Float32); # std rad/s in device frame +} + +struct OrbObservation @0x9b326d4e436afec7 { + observationMonoTime @0 :UInt64; + normalizedCoordinates @1 :List(Float32); + locationECEF @2 :List(Float64); + matchDistance @3: UInt32; +} + +struct CalibrationFeatures @0x8fdfadb254ea867a { + frameId @0 :UInt32; + + p0 @1 :List(Float32); + p1 @2 :List(Float32); + status @3 :List(Int8); +} + +struct NavStatus @0xbd8822120928120c { + isNavigating @0 :Bool; + currentAddress @1 :Address; + + struct Address @0xce7cd672cacc7814 { + title @0 :Text; + lat @1 :Float64; + lng @2 :Float64; + house @3 :Text; + address @4 :Text; + street @5 :Text; + city @6 :Text; + state @7 :Text; + country @8 :Text; + } +} + +struct NavUpdate @0xdb98be6565516acb { + isNavigating @0 :Bool; + curSegment @1 :Int32; + segments @2 :List(Segment); + + struct LatLng @0x9eaef9187cadbb9b { + lat @0 :Float64; + lng @1 :Float64; + } + + struct Segment @0xa5b39b4fc4d7da3f { + from @0 :LatLng; + to @1 :LatLng; + updateTime @2 :Int32; + distance @3 :Int32; + crossTime @4 :Int32; + exitNo @5 :Int32; + instruction @6 :Instruction; + + parts @7 :List(LatLng); + + enum Instruction @0xc5417a637451246f { + turnLeft @0; + turnRight @1; + keepLeft @2; + keepRight @3; + straight @4; + roundaboutExitNumber @5; + roundaboutExit @6; + roundaboutTurnLeft @7; + unkn8 @8; + roundaboutStraight @9; + unkn10 @10; + roundaboutTurnRight @11; + unkn12 @12; + roundaboutUturn @13; + unkn14 @14; + arrive @15; + exitLeft @16; + exitRight @17; + unkn18 @18; + uturn @19; + # ... + } + } +} + +struct TrafficEvent @0xacfa74a094e62626 { + type @0 :Type; + distance @1 :Float32; + action @2 :Action; + resuming @3 :Bool; + + enum Type @0xd85d75253435bf4b { + stopSign @0; + lightRed @1; + lightYellow @2; + lightGreen @3; + stopLight @4; + } + + enum Action @0xa6f6ce72165ccb49 { + none @0; + yield @1; + stop @2; + resumeReady @3; + } + +} + + +struct AndroidGnss @0xdfdf30d03fc485bd { + union { + measurements @0 :Measurements; + navigationMessage @1 :NavigationMessage; + } + + struct Measurements @0xa20710d4f428d6cd { + clock @0 :Clock; + measurements @1 :List(Measurement); + + struct Clock @0xa0e27b453a38f450 { + timeNanos @0 :Int64; + hardwareClockDiscontinuityCount @1 :Int32; + + hasTimeUncertaintyNanos @2 :Bool; + timeUncertaintyNanos @3 :Float64; + + hasLeapSecond @4 :Bool; + leapSecond @5 :Int32; + + hasFullBiasNanos @6 :Bool; + fullBiasNanos @7 :Int64; + + hasBiasNanos @8 :Bool; + biasNanos @9 :Float64; + + hasBiasUncertaintyNanos @10 :Bool; + biasUncertaintyNanos @11 :Float64; + + hasDriftNanosPerSecond @12 :Bool; + driftNanosPerSecond @13 :Float64; + + hasDriftUncertaintyNanosPerSecond @14 :Bool; + driftUncertaintyNanosPerSecond @15 :Float64; + } + + struct Measurement @0xd949bf717d77614d { + svId @0 :Int32; + constellation @1 :Constellation; + + timeOffsetNanos @2 :Float64; + state @3 :Int32; + receivedSvTimeNanos @4 :Int64; + receivedSvTimeUncertaintyNanos @5 :Int64; + cn0DbHz @6 :Float64; + pseudorangeRateMetersPerSecond @7 :Float64; + pseudorangeRateUncertaintyMetersPerSecond @8 :Float64; + accumulatedDeltaRangeState @9 :Int32; + accumulatedDeltaRangeMeters @10 :Float64; + accumulatedDeltaRangeUncertaintyMeters @11 :Float64; + + hasCarrierFrequencyHz @12 :Bool; + carrierFrequencyHz @13 :Float32; + hasCarrierCycles @14 :Bool; + carrierCycles @15 :Int64; + hasCarrierPhase @16 :Bool; + carrierPhase @17 :Float64; + hasCarrierPhaseUncertainty @18 :Bool; + carrierPhaseUncertainty @19 :Float64; + hasSnrInDb @20 :Bool; + snrInDb @21 :Float64; + + multipathIndicator @22 :MultipathIndicator; + + enum Constellation @0x9ef1f3ff0deb5ffb { + unknown @0; + gps @1; + sbas @2; + glonass @3; + qzss @4; + beidou @5; + galileo @6; + } + + enum State @0xcbb9490adce12d72 { + unknown @0; + codeLock @1; + bitSync @2; + subframeSync @3; + towDecoded @4; + msecAmbiguous @5; + symbolSync @6; + gloStringSync @7; + gloTodDecoded @8; + bdsD2BitSync @9; + bdsD2SubframeSync @10; + galE1bcCodeLock @11; + galE1c2ndCodeLock @12; + galE1bPageSync @13; + sbasSync @14; + } + + enum MultipathIndicator @0xc04e7b6231d4caa8 { + unknown @0; + detected @1; + notDetected @2; + } + } + } + + struct NavigationMessage @0xe2517b083095fd4e { + type @0 :Int32; + svId @1 :Int32; + messageId @2 :Int32; + submessageId @3 :Int32; + data @4 :Data; + status @5 :Status; + + enum Status @0xec1ff7996b35366f { + unknown @0; + parityPassed @1; + parityRebuilt @2; + } + } +} + +struct LidarPts @0xe3d6685d4e9d8f7a { + r @0 :List(UInt16); # uint16 m*500.0 + theta @1 :List(UInt16); # uint16 deg*100.0 + reflect @2 :List(UInt8); # uint8 0-255 + + # For storing out of file. + idx @3 :UInt64; + + # For storing in file + pkt @4 :Data; +} + +struct LiveTracksDEPRECATED @0xb16f60103159415a { + trackId @0 :Int32; + dRel @1 :Float32; + yRel @2 :Float32; + vRel @3 :Float32; + aRel @4 :Float32; + timeStamp @5 :Float32; + status @6 :Float32; + currentTime @7 :Float32; + stationary @8 :Bool; + oncoming @9 :Bool; +} + +struct LiveMpcData @0x92a5e332a85f32a0 { + x @0 :List(Float32); + y @1 :List(Float32); + psi @2 :List(Float32); + curvature @3 :List(Float32); + qpIterations @4 :UInt32; + calculationTime @5 :UInt64; + cost @6 :Float64; +} + +struct LiveLongitudinalMpcData @0xe7e17c434f865ae2 { + xEgo @0 :List(Float32); + vEgo @1 :List(Float32); + aEgo @2 :List(Float32); + xLead @3 :List(Float32); + vLead @4 :List(Float32); + aLead @5 :List(Float32); + aLeadTau @6 :Float32; # lead accel time constant + qpIterations @7 :UInt32; + mpcId @8 :UInt32; + calculationTime @9 :UInt64; + cost @10 :Float64; +} + +struct DriverStateDEPRECATED @0xb83c6cc593ed0a00 { + frameId @0 :UInt32; + modelExecutionTime @14 :Float32; + dspExecutionTime @16 :Float32; + rawPredictions @15 :Data; + + faceOrientation @3 :List(Float32); + facePosition @4 :List(Float32); + faceProb @5 :Float32; + leftEyeProb @6 :Float32; + rightEyeProb @7 :Float32; + leftBlinkProb @8 :Float32; + rightBlinkProb @9 :Float32; + faceOrientationStd @11 :List(Float32); + facePositionStd @12 :List(Float32); + sunglassesProb @13 :Float32; + poorVision @17 :Float32; + partialFace @18 :Float32; + distractedPose @19 :Float32; + distractedEyes @20 :Float32; + eyesOnRoad @21 :Float32; + phoneUse @22 :Float32; + occludedProb @23 :Float32; + + readyProb @24 :List(Float32); + notReadyProb @25 :List(Float32); + + irPwrDEPRECATED @10 :Float32; + descriptorDEPRECATED @1 :List(Float32); + stdDEPRECATED @2 :Float32; +} + +struct NavModelData @0xac3de5c437be057a { + frameId @0 :UInt32; + locationMonoTime @6 :UInt64; + modelExecutionTime @1 :Float32; + dspExecutionTime @2 :Float32; + features @3 :List(Float32); + # predicted future position + position @4 :XYData; + desirePrediction @5 :List(Float32); + + # All SI units and in device frame + struct XYData @0xbe09e615b2507e26 { + x @0 :List(Float32); + y @1 :List(Float32); + xStd @2 :List(Float32); + yStd @3 :List(Float32); + } +} + +struct AndroidBuildInfo @0xfe2919d5c21f426c { + board @0 :Text; + bootloader @1 :Text; + brand @2 :Text; + device @3 :Text; + display @4 :Text; + fingerprint @5 :Text; + hardware @6 :Text; + host @7 :Text; + id @8 :Text; + manufacturer @9 :Text; + model @10 :Text; + product @11 :Text; + radioVersion @12 :Text; + serial @13 :Text; + supportedAbis @14 :List(Text); + tags @15 :Text; + time @16 :Int64; + type @17 :Text; + user @18 :Text; + + versionCodename @19 :Text; + versionRelease @20 :Text; + versionSdk @21 :Int32; + versionSecurityPatch @22 :Text; +} + +struct AndroidSensor @0x9b513b93a887dbcd { + id @0 :Int32; + name @1 :Text; + vendor @2 :Text; + version @3 :Int32; + handle @4 :Int32; + type @5 :Int32; + maxRange @6 :Float32; + resolution @7 :Float32; + power @8 :Float32; + minDelay @9 :Int32; + fifoReservedEventCount @10 :UInt32; + fifoMaxEventCount @11 :UInt32; + stringType @12 :Text; + maxDelay @13 :Int32; +} + +struct IosBuildInfo @0xd97e3b28239f5580 { + appVersion @0 :Text; + appBuild @1 :UInt32; + osVersion @2 :Text; + deviceModel @3 :Text; +} + +enum FrameTypeDEPRECATED @0xa37f0d8558e193fd { + unknown @0; + neo @1; + chffrAndroid @2; + front @3; +} + +struct AndroidCaptureResult @0xbcc3efbac41d2048 { + sensitivity @0 :Int32; + frameDuration @1 :Int64; + exposureTime @2 :Int64; + rollingShutterSkew @3 :UInt64; + colorCorrectionTransform @4 :List(Int32); + colorCorrectionGains @5 :List(Float32); + displayRotation @6 :Int8; +} + +enum UsbPowerModeDEPRECATED @0xa8883583b32c9877 { + none @0; + client @1; + cdp @2; + dcp @3; +} + +struct LateralINDIState @0x939463348632375e { + active @0 :Bool; + steeringAngleDeg @1 :Float32; + steeringRateDeg @2 :Float32; + steeringAccelDeg @3 :Float32; + rateSetPoint @4 :Float32; + accelSetPoint @5 :Float32; + accelError @6 :Float32; + delayedOutput @7 :Float32; + delta @8 :Float32; + output @9 :Float32; + saturated @10 :Bool; + steeringAngleDesiredDeg @11 :Float32; + steeringRateDesiredDeg @12 :Float32; +} + +struct LateralLQRState @0x9024e2d790c82ade { + active @0 :Bool; + steeringAngleDeg @1 :Float32; + i @2 :Float32; + output @3 :Float32; + lqrOutput @4 :Float32; + saturated @5 :Bool; + steeringAngleDesiredDeg @6 :Float32; +} + +struct LateralPlannerSolution @0x84caeca5a6b4acfe { + x @0 :List(Float32); + y @1 :List(Float32); + yaw @2 :List(Float32); + yawRate @3 :List(Float32); + xStd @4 :List(Float32); + yStd @5 :List(Float32); + yawStd @6 :List(Float32); + yawRateStd @7 :List(Float32); +} + +struct GpsTrajectory @0x8cfeb072f5301000 { + x @0 :List(Float32); + y @1 :List(Float32); +} diff --git a/cereal/include/c++.capnp b/openpilot/cereal/include/c++.capnp similarity index 100% rename from cereal/include/c++.capnp rename to openpilot/cereal/include/c++.capnp diff --git a/cereal/log.capnp b/openpilot/cereal/log.capnp similarity index 75% rename from cereal/log.capnp rename to openpilot/cereal/log.capnp index 7c7983d147..1eaaa3098b 100644 --- a/cereal/log.capnp +++ b/openpilot/cereal/log.capnp @@ -1,8 +1,8 @@ -using Cxx = import "./include/c++.capnp"; +using Cxx = import "/include/c++.capnp"; $Cxx.namespace("cereal"); -using Car = import "car.capnp"; -using Legacy = import "legacy.capnp"; +using Car = import "/car.capnp"; +using Deprecated = import "deprecated.capnp"; using Custom = import "custom.capnp"; @0xf3b1f17e25a4285b; @@ -68,12 +68,12 @@ struct OnroadEvent @0xc4fa6047f024e718 { longitudinalManeuver @30; steerTempUnavailableSilent @31; resumeRequired @32; - preDriverDistracted @33; - promptDriverDistracted @34; - driverDistracted @35; - preDriverUnresponsive @36; - promptDriverUnresponsive @37; - driverUnresponsive @38; + driverDistracted1 @33; + driverDistracted2 @34; + driverDistracted3 @35; + driverUnresponsive1 @36; + driverUnresponsive2 @37; + driverUnresponsive3 @38; belowSteerSpeed @39; lowBattery @40; accFaulted @41; @@ -87,6 +87,8 @@ struct OnroadEvent @0xc4fa6047f024e718 { laneChange @50; lowMemory @51; stockAeb @52; + stockLkas @98; + lateralManeuver @99; ldw @53; carUnrecognized @54; invalidLkasSetting @55; @@ -127,7 +129,9 @@ struct OnroadEvent @0xc4fa6047f024e718 { espActive @90; personalityChanged @91; aeb @92; - userFlag @95; + userBookmark @95; + excessiveActuation @96; + audioFeedback @97; soundsUnavailableDEPRECATED @47; } @@ -188,66 +192,16 @@ struct InitData { espVersion @3 :Text; } - # ***** deprecated stuff ***** - gctxDEPRECATED @1 :Text; - androidBuildInfo @5 :AndroidBuildInfo; - androidSensorsDEPRECATED @6 :List(AndroidSensor); - chffrAndroidExtraDEPRECATED @7 :ChffrAndroidExtra; - iosBuildInfoDEPRECATED @14 :IosBuildInfo; - - struct AndroidBuildInfo { - board @0 :Text; - bootloader @1 :Text; - brand @2 :Text; - device @3 :Text; - display @4 :Text; - fingerprint @5 :Text; - hardware @6 :Text; - host @7 :Text; - id @8 :Text; - manufacturer @9 :Text; - model @10 :Text; - product @11 :Text; - radioVersion @12 :Text; - serial @13 :Text; - supportedAbis @14 :List(Text); - tags @15 :Text; - time @16 :Int64; - type @17 :Text; - user @18 :Text; - - versionCodename @19 :Text; - versionRelease @20 :Text; - versionSdk @21 :Int32; - versionSecurityPatch @22 :Text; - } - - struct AndroidSensor { - id @0 :Int32; - name @1 :Text; - vendor @2 :Text; - version @3 :Int32; - handle @4 :Int32; - type @5 :Int32; - maxRange @6 :Float32; - resolution @7 :Float32; - power @8 :Float32; - minDelay @9 :Int32; - fifoReservedEventCount @10 :UInt32; - fifoMaxEventCount @11 :UInt32; - stringType @12 :Text; - maxDelay @13 :Int32; - } - struct ChffrAndroidExtra { allCameraCharacteristics @0 :Map(Text, Text); } - struct IosBuildInfo { - appVersion @0 :Text; - appBuild @1 :UInt32; - osVersion @2 :Text; - deviceModel @3 :Text; + deprecated :group { + gctx @1 :Text; + androidBuildInfo @5 :Deprecated.AndroidBuildInfo; + androidSensors @6 :List(Deprecated.AndroidSensor); + chffrAndroidExtra @7 :ChffrAndroidExtra; + iosBuildInfo @14 :Deprecated.IosBuildInfo; } } @@ -276,13 +230,6 @@ struct FrameData { temperaturesC @24 :List(Float32); - enum FrameTypeDEPRECATED { - unknown @0; - neo @1; - chffrAndroid @2; - front @3; - } - sensor @26 :ImageSensor; enum ImageSensor { unknown @0; @@ -291,26 +238,19 @@ struct FrameData { os04c10 @3; } - frameLengthDEPRECATED @3 :Int32; - globalGainDEPRECATED @5 :Int32; - frameTypeDEPRECATED @7 :FrameTypeDEPRECATED; - androidCaptureResultDEPRECATED @9 :AndroidCaptureResult; - lensPosDEPRECATED @11 :Int32; - lensSagDEPRECATED @12 :Float32; - lensErrDEPRECATED @13 :Float32; - lensTruePosDEPRECATED @14 :Float32; - focusValDEPRECATED @16 :List(Int16); - focusConfDEPRECATED @17 :List(UInt8); - sharpnessScoreDEPRECATED @18 :List(UInt16); - recoverStateDEPRECATED @19 :Int32; - struct AndroidCaptureResult { - sensitivity @0 :Int32; - frameDuration @1 :Int64; - exposureTime @2 :Int64; - rollingShutterSkew @3 :UInt64; - colorCorrectionTransform @4 :List(Int32); - colorCorrectionGains @5 :List(Float32); - displayRotation @6 :Int8; + deprecated :group { + frameLength @3 :Int32; + globalGain @5 :Int32; + frameType @7 :Deprecated.FrameTypeDEPRECATED; + androidCaptureResult @9 :Deprecated.AndroidCaptureResult; + lensPos @11 :Int32; + lensSag @12 :Float32; + lensErr @13 :Float32; + lensTruePos @14 :Float32; + focusVal @16 :List(Int16); + focusConf @17 :List(UInt8); + sharpnessScore @18 :List(UInt16); + recoverState @19 :Int32; } } @@ -333,13 +273,8 @@ struct GPSNMEAData { nmea @2 :Text; } -# android sensor_event_t struct SensorEventData { - version @0 :Int32; - sensor @1 :Int32; - type @2 :Int32; timestamp @3 :Int64; - uncalibratedDEPRECATED @10 :Bool; union { acceleration @4 :SensorVec; @@ -357,7 +292,10 @@ struct SensorEventData { struct SensorVec { v @0 :List(Float32); - status @1 :Int8; + + deprecated :group { + status @1 :Int8; + } } enum SensorSource { @@ -374,6 +312,14 @@ struct SensorEventData { lsm6ds3trc @10; mmc5603nj @11; } + + # formerly based on android sensor_event_t + deprecated :group { + version @0 :Int32; + sensor @1 :Int32; + type @2 :Int32; + uncalibrated @10 :Bool; + } } # android struct GpsLocation @@ -459,12 +405,19 @@ struct CanData { address @0 :UInt32; dat @2 :Data; src @3 :UInt8; - busTimeDEPRECATED @1 :UInt16; + + deprecated :group { + busTime @1 :UInt16; + } } struct DeviceState @0xa4d8b5af2aa492eb { deviceType @45 :InitData.DeviceType; + # usb + chestnutPresent @51 :Bool; + usbState @52 :UsbState; + networkType @22 :NetworkType; networkInfo @31 :NetworkInfo; networkStrength @24 :NetworkStrength; @@ -492,12 +445,12 @@ struct DeviceState @0xa4d8b5af2aa492eb { gpuTempC @27 :List(Float32); dspTempC @49 :Float32; memoryTempC @28 :Float32; - nvmeTempC @35 :List(Float32); modemTempC @36 :List(Float32); pmicTempC @39 :List(Float32); intakeTempC @46 :Float32; exhaustTempC @47 :Float32; - caseTempC @48 :Float32; + gnssTempC @48 :Float32; + bottomSocTempC @50 :Float32; maxTempC @44 :Float32; # max of other temps, used to control fan thermalZones @38 :List(ThermalZone); thermalStatus @14 :ThermalStatus; @@ -511,10 +464,10 @@ struct DeviceState @0xa4d8b5af2aa492eb { } enum ThermalStatus { - green @0; - yellow @1; - red @2; - danger @3; + ok @0; + warmDEPRECATED @1; + overheated @2; + critical @3; } enum NetworkType { @@ -549,25 +502,27 @@ struct DeviceState @0xa4d8b5af2aa492eb { wwanRx @1 :Int64; } - # deprecated - cpu0DEPRECATED @0 :UInt16; - cpu1DEPRECATED @1 :UInt16; - cpu2DEPRECATED @2 :UInt16; - cpu3DEPRECATED @3 :UInt16; - memDEPRECATED @4 :UInt16; - gpuDEPRECATED @5 :UInt16; - batDEPRECATED @6 :UInt32; - pa0DEPRECATED @21 :UInt16; - cpuUsagePercentDEPRECATED @20 :Int8; - batteryStatusDEPRECATED @9 :Text; - batteryVoltageDEPRECATED @16 :Int32; - batteryTempCDEPRECATED @29 :Float32; - batteryPercentDEPRECATED @8 :Int16; - batteryCurrentDEPRECATED @15 :Int32; - chargingErrorDEPRECATED @17 :Bool; - chargingDisabledDEPRECATED @18 :Bool; - usbOnlineDEPRECATED @12 :Bool; - ambientTempCDEPRECATED @30 :Float32; + deprecated :group { + cpu0 @0 :UInt16; + cpu1 @1 :UInt16; + cpu2 @2 :UInt16; + cpu3 @3 :UInt16; + mem @4 :UInt16; + gpu @5 :UInt16; + bat @6 :UInt32; + pa0 @21 :UInt16; + cpuUsagePercent @20 :Int8; + batteryStatus @9 :Text; + batteryVoltage @16 :Int32; + batteryTempC @29 :Float32; + batteryPercent @8 :Int16; + batteryCurrent @15 :Int32; + chargingError @17 :Bool; + chargingDisabled @18 :Bool; + usbOnline @12 :Bool; + ambientTempC @30 :Float32; + nvmeTempC @35 :List(Float32); + } } struct PandaState @0xa7649e2575e4591e { @@ -583,13 +538,13 @@ struct PandaState @0xa7649e2575e4591e { heartbeatLost @22 :Bool; interruptLoad @25 :Float32; fanPower @28 :UInt8; - fanStallCount @34 :UInt8; - spiChecksumErrorCount @33 :UInt16; + spiErrorCount @33 :UInt16; harnessStatus @21 :HarnessStatus; sbu1Voltage @35 :Float32; sbu2Voltage @36 :Float32; + soundOutputLevel @37 :UInt16; # can health canState0 @29 :PandaCanState; @@ -608,6 +563,11 @@ struct PandaState @0xa7649e2575e4591e { voltage @0 :UInt32; current @1 :UInt32; + # these fields are not used by openpilot, but they're + # reserved for forks building alternate experiences. + controlsAllowedLateral @38 :Bool; + controlsAllowedLongitudinal @39 :Bool; + enum FaultStatus { none @0; faultTemp @1; @@ -704,14 +664,17 @@ struct PandaState @0xa7649e2575e4591e { } } - gasInterceptorDetectedDEPRECATED @4 :Bool; - startedSignalDetectedDEPRECATED @5 :Bool; - hasGpsDEPRECATED @6 :Bool; - gmlanSendErrsDEPRECATED @9 :UInt32; - fanSpeedRpmDEPRECATED @11 :UInt16; - usbPowerModeDEPRECATED @12 :PeripheralState.UsbPowerModeDEPRECATED; - safetyParamDEPRECATED @20 :Int16; - safetyParam2DEPRECATED @26 :UInt32; + deprecated :group { + gasInterceptorDetected @4 :Bool; + startedSignalDetected @5 :Bool; + hasGps @6 :Bool; + gmlanSendErrs @9 :UInt32; + fanSpeedRpm @11 :UInt16; + usbPowerMode @12 :Deprecated.UsbPowerModeDEPRECATED; + safetyParam @20 :Int16; + safetyParam2 @26 :UInt32; + fanStallCount @34 :UInt8; + } } struct PeripheralState { @@ -720,53 +683,67 @@ struct PeripheralState { current @2 :UInt32; fanSpeedRpm @3 :UInt16; - usbPowerModeDEPRECATED @4 :UsbPowerModeDEPRECATED; - enum UsbPowerModeDEPRECATED @0xa8883583b32c9877 { - none @0; - client @1; - cdp @2; - dcp @3; + deprecated :group { + usbPowerMode @4 :Deprecated.UsbPowerModeDEPRECATED; + } +} + +struct UsbState { + devices @0 :List(Device); + + struct Device { + busnum @0 :UInt8; + devnum @1 :UInt8; + vendorId @2 :UInt16; + productId @3 :UInt16; + speedMbps @4 :UInt16; + manufacturer @6 :Text; + product @5 :Text; + linkErrorCount @7 :UInt16; } } struct RadarState @0x9a185389d6fdd05f { - mdMonoTime @6 :UInt64; - carStateMonoTime @11 :UInt64; + mdMonoTime @6 :UInt64; # for debugging radarErrors @13 :Car.RadarData.Error; leadOne @3 :LeadData; leadTwo @4 :LeadData; struct LeadData { - dRel @0 :Float32; - yRel @1 :Float32; - vRel @2 :Float32; - aRel @3 :Float32; - vLead @4 :Float32; - dPath @6 :Float32; - vLat @7 :Float32; - vLeadK @8 :Float32; - aLeadK @9 :Float32; - fcw @10 :Bool; - status @11 :Bool; - aLeadTau @12 :Float32; - modelProb @13 :Float32; - radar @14 :Bool; - radarTrackId @15 :Int32 = -1; + dRel @0 :Float32; # m from the front bumper of the car + yRel @1 :Float32; # m in car frame, left positive + vRel @2 :Float32; # m/s relative longitudinal speed + vLead @4 :Float32; # m/s absolute lead speed + vLeadK @8 :Float32; # kalman-filtered lead speed + aLeadK @9 :Float32; # kalman-filtered lead accel + present @11 :Bool; # true if a lead is present + aLeadTau @12 :Float32; # lead accel time constant + modelProb @13 :Float32; # vision model lead probability + radar @14 :Bool; # true if lead is radar-matched (vs vision-only) + radarTrackId @15 :Int32 = -1; # for debugging - aLeadDEPRECATED @5 :Float32; + deprecated :group { + aRel @3 :Float32; + aLead @5 :Float32; + dPath @6 :Float32; + vLat @7 :Float32; + fcw @10 :Bool; + } } - # deprecated - ftMonoTimeDEPRECATED @7 :UInt64; - warpMatrixDEPRECATED @0 :List(Float32); - angleOffsetDEPRECATED @1 :Float32; - calStatusDEPRECATED @2 :Int8; - calCycleDEPRECATED @8 :Int32; - calPercDEPRECATED @9 :Int8; - canMonoTimesDEPRECATED @10 :List(UInt64); - cumLagMsDEPRECATED @5 :Float32; - radarErrorsDEPRECATED @12 :List(Car.RadarData.ErrorDEPRECATED); + deprecated :group { + ftMonoTime @7 :UInt64; + warpMatrix @0 :List(Float32); + angleOffset @1 :Float32; + calStatus @2 :Int8; + calCycle @8 :Int32; + calPerc @9 :Int8; + canMonoTimes @10 :List(UInt64); + cumLagMs @5 :Float32; + carStateMonoTime @11 :UInt64; + radarErrors @12 :List(Car.RadarData.ErrorDEPRECATED); + } } struct LiveCalibrationData { @@ -784,10 +761,6 @@ struct LiveCalibrationData { wideFromDeviceEuler @10 :List(Float32); height @12 :List(Float32); - warpMatrixDEPRECATED @0 :List(Float32); - calStatusDEPRECATED @1 :Int8; - warpMatrix2DEPRECATED @5 :List(Float32); - warpMatrixBigDEPRECATED @6 :List(Float32); enum Status { uncalibrated @0; @@ -795,19 +768,13 @@ struct LiveCalibrationData { invalid @2; recalibrating @3; } -} -struct LiveTracksDEPRECATED { - trackId @0 :Int32; - dRel @1 :Float32; - yRel @2 :Float32; - vRel @3 :Float32; - aRel @4 :Float32; - timeStamp @5 :Float32; - status @6 :Float32; - currentTime @7 :Float32; - stationary @8 :Bool; - oncoming @9 :Bool; + deprecated :group { + warpMatrix @0 :List(Float32); + calStatus @1 :Int8; + warpMatrix2 @5 :List(Float32); + warpMatrixBig @6 :List(Float32); + } } struct SelfdriveState { @@ -823,13 +790,31 @@ struct SelfdriveState { alertStatus @5 :AlertStatus; alertSize @6 :AlertSize; alertType @7 :Text; - alertSound @8 :Car.CarControl.HUDControl.AudibleAlert; + alertSound @13 :AudibleAlert; alertHudVisual @12 :Car.CarControl.HUDControl.VisualAlert; # configurable driving settings experimentalMode @10 :Bool; personality @11 :LongitudinalPersonality; + enum AudibleAlert { + none @0; + + engage @1; + disengage @2; + refuse @3; + + warningSoft @4; + warningImmediate @5; + + prompt @6; + promptRepeat @7; + promptDistracted @8; + + preAlert @9; + complete @10; + } + enum OpenpilotState @0xdbe58b96d2d1ac61 { disabled @0; preEnabled @1; @@ -850,6 +835,10 @@ struct SelfdriveState { mid @2; full @3; } + + deprecated :group { + alertSound @8 :Car.CarControl.HUDControl.AudibleAlert; + } } struct ControlsState @0x97ff69c53601abf1 { @@ -870,25 +859,9 @@ struct ControlsState @0x97ff69c53601abf1 { debugState @59 :LateralDebugState; torqueState @60 :LateralTorqueState; - curvatureStateDEPRECATED @65 :LateralCurvatureState; - lqrStateDEPRECATED @55 :LateralLQRState; - indiStateDEPRECATED @52 :LateralINDIState; - } - - struct LateralINDIState { - active @0 :Bool; - steeringAngleDeg @1 :Float32; - steeringRateDeg @2 :Float32; - steeringAccelDeg @3 :Float32; - rateSetPoint @4 :Float32; - accelSetPoint @5 :Float32; - accelError @6 :Float32; - delayedOutput @7 :Float32; - delta @8 :Float32; - output @9 :Float32; - saturated @10 :Bool; - steeringAngleDesiredDeg @11 :Float32; - steeringRateDesiredDeg @12 :Float32; + curvatureState @65 :LateralCurvatureState; + lqrStateDEPRECATED @55 :Deprecated.LateralLQRState; + indiStateDEPRECATED @52 :Deprecated.LateralINDIState; } struct LateralPIDState { @@ -916,18 +889,10 @@ struct ControlsState @0x97ff69c53601abf1 { saturated @7 :Bool; actualLateralAccel @9 :Float32; desiredLateralAccel @10 :Float32; + desiredLateralJerk @11 :Float32; + version @12 :Int32; } - struct LateralLQRState { - active @0 :Bool; - steeringAngleDeg @1 :Float32; - i @2 :Float32; - output @3 :Float32; - lqrOutput @4 :Float32; - saturated @5 :Bool; - steeringAngleDesiredDeg @6 :Float32; - } - struct LateralAngleState { active @0 :Bool; steeringAngleDeg @1 :Float32; @@ -936,7 +901,14 @@ struct ControlsState @0x97ff69c53601abf1 { steeringAngleDesiredDeg @4 :Float32; } - struct LateralCurvatureState { + struct LateralDebugState { + active @0 :Bool; + steeringAngleDeg @1 :Float32; + output @2 :Float32; + saturated @3 :Bool; + } + + struct LateralCurvatureState @0xad9d8095c06f7c61 { active @0 :Bool; actualCurvature @1 :Float32; desiredCurvature @2 :Float32; @@ -948,65 +920,59 @@ struct ControlsState @0x97ff69c53601abf1 { saturated @8 :Bool; } - struct LateralDebugState { - active @0 :Bool; - steeringAngleDeg @1 :Float32; - output @2 :Float32; - saturated @3 :Bool; + deprecated :group { + vEgo @0 :Float32; + vEgoRaw @32 :Float32; + aEgo @1 :Float32; + canMonoTime @16 :UInt64; + radarStateMonoTime @17 :UInt64; + mdMonoTime @18 :UInt64; + yActual @6 :Float32; + yDes @7 :Float32; + upSteer @8 :Float32; + uiSteer @9 :Float32; + ufSteer @34 :Float32; + aTargetMin @10 :Float32; + aTargetMax @11 :Float32; + rearViewCam @23 :Bool; + driverMonitoringOn @43 :Bool; + hudLead @14 :Int32; + alertSound @45 :Text; + angleModelBias @27 :Float32; + gpsPlannerActive @40 :Bool; + decelForTurn @47 :Bool; + decelForModel @54 :Bool; + awarenessStatus @26 :Float32; + angleSteers @13 :Float32; + vCurvature @46 :Float32; + mapValid @49 :Bool; + jerkFactor @12 :Float32; + steerOverride @20 :Bool; + steeringAngleDesiredDeg @29 :Float32; + canMonoTimes @21 :List(UInt64); + desiredCurvatureRate @62 :Float32; + canErrorCounter @57 :UInt32; + vPid @2 :Float32; + alertBlinkingRate @42 :Float32; + alertText1 @24 :Text; + alertText2 @25 :Text; + alertStatus @38 :SelfdriveState.AlertStatus; + alertSize @39 :SelfdriveState.AlertSize; + alertType @44 :Text; + alertSound2 @56 :SelfdriveState.AudibleAlert; + engageable @41 :Bool; # can OP be engaged? + state @31 :SelfdriveState.OpenpilotState; + enabled @19 :Bool; + active @36 :Bool; + experimentalMode @64 :Bool; + personality @66 :LongitudinalPersonality; + vCruise @22 :Float32; # actual set speed + vCruiseCluster @63 :Float32; # set speed to display in the UI + startMonoTime @48 :UInt64; + cumLagMs @15 :Float32; + aTarget @35 :Float32; + vTargetLead @3 :Float32; } - - # deprecated - vEgoDEPRECATED @0 :Float32; - vEgoRawDEPRECATED @32 :Float32; - aEgoDEPRECATED @1 :Float32; - canMonoTimeDEPRECATED @16 :UInt64; - radarStateMonoTimeDEPRECATED @17 :UInt64; - mdMonoTimeDEPRECATED @18 :UInt64; - yActualDEPRECATED @6 :Float32; - yDesDEPRECATED @7 :Float32; - upSteerDEPRECATED @8 :Float32; - uiSteerDEPRECATED @9 :Float32; - ufSteerDEPRECATED @34 :Float32; - aTargetMinDEPRECATED @10 :Float32; - aTargetMaxDEPRECATED @11 :Float32; - rearViewCamDEPRECATED @23 :Bool; - driverMonitoringOnDEPRECATED @43 :Bool; - hudLeadDEPRECATED @14 :Int32; - alertSoundDEPRECATED @45 :Text; - angleModelBiasDEPRECATED @27 :Float32; - gpsPlannerActiveDEPRECATED @40 :Bool; - decelForTurnDEPRECATED @47 :Bool; - decelForModelDEPRECATED @54 :Bool; - awarenessStatusDEPRECATED @26 :Float32; - angleSteersDEPRECATED @13 :Float32; - vCurvatureDEPRECATED @46 :Float32; - mapValidDEPRECATED @49 :Bool; - jerkFactorDEPRECATED @12 :Float32; - steerOverrideDEPRECATED @20 :Bool; - steeringAngleDesiredDegDEPRECATED @29 :Float32; - canMonoTimesDEPRECATED @21 :List(UInt64); - desiredCurvatureRateDEPRECATED @62 :Float32; - canErrorCounterDEPRECATED @57 :UInt32; - vPidDEPRECATED @2 :Float32; - alertBlinkingRateDEPRECATED @42 :Float32; - alertText1DEPRECATED @24 :Text; - alertText2DEPRECATED @25 :Text; - alertStatusDEPRECATED @38 :SelfdriveState.AlertStatus; - alertSizeDEPRECATED @39 :SelfdriveState.AlertSize; - alertTypeDEPRECATED @44 :Text; - alertSound2DEPRECATED @56 :Car.CarControl.HUDControl.AudibleAlert; - engageableDEPRECATED @41 :Bool; # can OP be engaged? - stateDEPRECATED @31 :SelfdriveState.OpenpilotState; - enabledDEPRECATED @19 :Bool; - activeDEPRECATED @36 :Bool; - experimentalModeDEPRECATED @64 :Bool; - personalityDEPRECATED @66 :LongitudinalPersonality; - vCruiseDEPRECATED @22 :Float32; # actual set speed - vCruiseClusterDEPRECATED @63 :Float32; # set speed to display in the UI - startMonoTimeDEPRECATED @48 :UInt64; - cumLagMsDEPRECATED @15 :Float32; - aTargetDEPRECATED @35 :Float32; - vTargetLeadDEPRECATED @3 :Float32; } struct DrivingModelData { @@ -1076,24 +1042,18 @@ struct ModelDataV2 { roadEdgeStds @14 :List(Float32); # predicted lead cars - leads @11 :List(LeadDataV2); leadsV3 @18 :List(LeadDataV3); meta @12 :MetaData; confidence @23: ConfidenceClass; - # Model perceived motion - temporalPose @21 :Pose; - # e2e lateral planner action @26: Action; - gpuExecutionTimeDEPRECATED @17 :Float32; - navEnabledDEPRECATED @22 :Bool; - locationMonoTimeDEPRECATED @24 :UInt64; - lateralPlannerSolutionDEPRECATED @25: LateralPlannerSolution; + lateralPlannerSolutionDEPRECATED @25: Deprecated.LateralPlannerSolution; + leadsDEPRECATED @11 :List(LeadDataV2DEPRECATED); - struct LeadDataV2 { + struct LeadDataV2DEPRECATED { prob @0 :Float32; # probability that car is your lead at time t t @1 :Float32; @@ -1133,10 +1093,11 @@ struct ModelDataV2 { laneChangeDirection @9 :LaneChangeDirection; - # deprecated - brakeDisengageProbDEPRECATED @2 :Float32; - gasDisengageProbDEPRECATED @3 :Float32; - steerOverrideProbDEPRECATED @4 :Float32; + deprecated :group { + brakeDisengageProb @2 :Float32; + gasDisengageProb @3 :Float32; + steerOverrideProb @4 :Float32; + } } enum ConfidenceClass { @@ -1164,22 +1125,18 @@ struct ModelDataV2 { rotStd @3 :List(Float32); # std rad/s in device frame } - struct LateralPlannerSolution { - x @0 :List(Float32); - y @1 :List(Float32); - yaw @2 :List(Float32); - yawRate @3 :List(Float32); - xStd @4 :List(Float32); - yStd @5 :List(Float32); - yawStd @6 :List(Float32); - yawRateStd @7 :List(Float32); - } - struct Action { desiredCurvature @0 :Float32; desiredAcceleration @1 :Float32; shouldStop @2 :Bool; } + + deprecated :group { + temporalPose @21 :Pose; + gpuExecutionTime @17 :Float32; + navEnabled @22 :Bool; + locationMonoTime @24 :UInt64; + } } struct EncodeIndex { @@ -1216,7 +1173,7 @@ struct EncodeIndex { } } -struct AndroidLogEntry { +struct OperatingSystemLogEntry { id @0 :UInt8; ts @1 :UInt64; priority @2 :UInt8; @@ -1234,6 +1191,10 @@ struct DriverAssistance { # FCW, AEB, etc. will go here } +struct LateralManeuverPlan { + desiredCurvature @0 :Float32; # 1/m +} + struct LongitudinalPlan @0xe00b5b3eba12876c { modelMonoTime @9 :UInt64; hasLead @7 :Bool; @@ -1261,38 +1222,35 @@ struct LongitudinalPlan @0xe00b5b3eba12876c { e2e @4; } - # deprecated - vCruiseDEPRECATED @16 :Float32; - aCruiseDEPRECATED @17 :Float32; - vTargetDEPRECATED @3 :Float32; - vTargetFutureDEPRECATED @14 :Float32; - vStartDEPRECATED @26 :Float32; - aStartDEPRECATED @27 :Float32; - vMaxDEPRECATED @20 :Float32; - radarStateMonoTimeDEPRECATED @10 :UInt64; - jerkFactorDEPRECATED @6 :Float32; - hasLeftLaneDEPRECATED @23 :Bool; - hasRightLaneDEPRECATED @24 :Bool; - aTargetMinDEPRECATED @4 :Float32; - aTargetMaxDEPRECATED @5 :Float32; - lateralValidDEPRECATED @0 :Bool; - longitudinalValidDEPRECATED @2 :Bool; - dPolyDEPRECATED @1 :List(Float32); - laneWidthDEPRECATED @11 :Float32; - vCurvatureDEPRECATED @21 :Float32; - decelForTurnDEPRECATED @22 :Bool; - mapValidDEPRECATED @25 :Bool; - radarValidDEPRECATED @28 :Bool; - radarCanErrorDEPRECATED @30 :Bool; - commIssueDEPRECATED @31 :Bool; - eventsDEPRECATED @13 :List(Car.OnroadEventDEPRECATED); - gpsTrajectoryDEPRECATED @12 :GpsTrajectory; - gpsPlannerActiveDEPRECATED @19 :Bool; - personalityDEPRECATED @36 :LongitudinalPersonality; - struct GpsTrajectory { - x @0 :List(Float32); - y @1 :List(Float32); + deprecated :group { + vCruise @16 :Float32; + aCruise @17 :Float32; + vTarget @3 :Float32; + vTargetFuture @14 :Float32; + vStart @26 :Float32; + aStart @27 :Float32; + vMax @20 :Float32; + radarStateMonoTime @10 :UInt64; + jerkFactor @6 :Float32; + hasLeftLane @23 :Bool; + hasRightLane @24 :Bool; + aTargetMin @4 :Float32; + aTargetMax @5 :Float32; + lateralValid @0 :Bool; + longitudinalValid @2 :Bool; + dPoly @1 :List(Float32); + laneWidth @11 :Float32; + vCurvature @21 :Float32; + decelForTurn @22 :Bool; + mapValid @25 :Bool; + radarValid @28 :Bool; + radarCanError @30 :Bool; + commIssue @31 :Bool; + events @13 :List(Car.OnroadEventDEPRECATED); + gpsTrajectory @12 :Deprecated.GpsTrajectory; + gpsPlannerActive @19 :Bool; + personality @36 :LongitudinalPersonality; } } struct UiPlan { @@ -1303,11 +1261,7 @@ struct UiPlan { struct LateralPlan @0xe1e9318e2ae8b51e { modelMonoTime @31 :UInt64; - laneWidthDEPRECATED @0 :Float32; - lProbDEPRECATED @5 :Float32; - rProbDEPRECATED @7 :Float32; dPathPoints @20 :List(Float32); - dProbDEPRECATED @21 :Float32; mpcSolutionValid @9 :Bool; desire @17 :Desire; @@ -1329,30 +1283,35 @@ struct LateralPlan @0xe1e9318e2ae8b51e { u @1 :List(Float32); } - # deprecated - curvatureDEPRECATED @22 :Float32; - curvatureRateDEPRECATED @23 :Float32; - rawCurvatureDEPRECATED @24 :Float32; - rawCurvatureRateDEPRECATED @25 :Float32; - cProbDEPRECATED @3 :Float32; - dPolyDEPRECATED @1 :List(Float32); - cPolyDEPRECATED @2 :List(Float32); - lPolyDEPRECATED @4 :List(Float32); - rPolyDEPRECATED @6 :List(Float32); - modelValidDEPRECATED @12 :Bool; - commIssueDEPRECATED @15 :Bool; - posenetValidDEPRECATED @16 :Bool; - sensorValidDEPRECATED @14 :Bool; - paramsValidDEPRECATED @10 :Bool; - steeringAngleDegDEPRECATED @8 :Float32; # deg - steeringRateDegDEPRECATED @13 :Float32; # deg/s - angleOffsetDegDEPRECATED @11 :Float32; + deprecated :group { + laneWidth @0 :Float32; + lProb @5 :Float32; + rProb @7 :Float32; + dProb @21 :Float32; + curvature @22 :Float32; + curvatureRate @23 :Float32; + rawCurvature @24 :Float32; + rawCurvatureRate @25 :Float32; + cProb @3 :Float32; + dPoly @1 :List(Float32); + cPoly @2 :List(Float32); + lPoly @4 :List(Float32); + rPoly @6 :List(Float32); + modelValid @12 :Bool; + commIssue @15 :Bool; + posenetValid @16 :Bool; + sensorValid @14 :Bool; + paramsValid @10 :Bool; + steeringAngleDeg @8 :Float32; # deg + steeringRateDeg @13 :Float32; # deg/s + angleOffsetDeg @11 :Float32; + } } struct LiveLocationKalman { # More info on reference frames: - # https://github.com/commaai/openpilot/tree/master/common/transformations + # https://github.com/commaai/openpilot/tree/master/openpilot/common/transformations positionECEF @0 : Measurement; positionGeodetic @1 : Measurement; @@ -1409,7 +1368,7 @@ struct LiveLocationKalman { struct LivePose { # More info on reference frames: - # https://github.com/commaai/openpilot/tree/master/common/transformations + # https://github.com/commaai/openpilot/tree/master/openpilot/common/transformations orientationNED @0 :XYZMeasurement; velocityDevice @1 :XYZMeasurement; accelerationDevice @2 :XYZMeasurement; @@ -1419,6 +1378,8 @@ struct LivePose { posenetOK @5 :Bool = false; sensorsOK @6 :Bool = false; + timestamp @8 :UInt64; + debugFilterState @7 :FilterState; struct XYZMeasurement { @@ -1473,6 +1434,11 @@ struct ProcLog { cmdline @15 :List(Text); exe @16 :Text; + + # from /proc//smaps_rollup (proportional/private memory) + memPss @17 :UInt64; # Pss — shared pages split by mapper count + memPssAnon @18 :UInt64; # Pss_Anon — private anonymous (heap, stack) + memPssShmem @19 :UInt64; # Pss_Shmem — proportional MSGQ/tmpfs share } struct CPUTimes { @@ -1534,7 +1500,10 @@ struct GnssMeasurements { # Satellite position and velocity [x,y,z] satPos @7 :List(Float64); satVel @8 :List(Float64); - ephemerisSourceDEPRECATED @9 :EphemerisSourceDEPRECATED; + + deprecated :group { + ephemerisSource @9 :EphemerisSourceDEPRECATED; + } } struct EphemerisSourceDEPRECATED { @@ -1689,7 +1658,6 @@ struct UbloxGnss { iDot @26 :Float64; codesL2 @27 :Float64; - gpsWeekDEPRECATED @28 :Float64; l2 @29 :Float64; svAcc @30 :Float64; @@ -1709,6 +1677,10 @@ struct UbloxGnss { towCount @40 :UInt32; toeWeek @41 :UInt16; tocWeek @42 :UInt16; + + deprecated :group { + gpsWeek @28 :Float64; + } } struct IonoData { @@ -1787,7 +1759,6 @@ struct UbloxGnss { age @17 :UInt8; svHealth @18 :UInt8; - tkDEPRECATED @19 :UInt16; tb @20 :UInt16; tauN @21 :Float64; @@ -1799,12 +1770,16 @@ struct UbloxGnss { p3 @26 :UInt8; p4 @27 :UInt8; - freqNumDEPRECATED @28 :UInt32; n4 @29 :UInt8; nt @30 :UInt16; freqNum @31 :Int16; tkSeconds @32 :UInt32; + + deprecated :group { + tk @19 :UInt16; + freqNum @28 :UInt32; + } } } @@ -2105,34 +2080,12 @@ struct QcomGnss @0xde94674b07ae51c1 { struct Clocks { wallTimeNanos @3 :UInt64; # unix epoch time - bootTimeNanosDEPRECATED @0 :UInt64; - monotonicNanosDEPRECATED @1 :UInt64; - monotonicRawNanosDEPRECATD @2 :UInt64; - modemUptimeMillisDEPRECATED @4 :UInt64; -} - -struct LiveMpcData { - x @0 :List(Float32); - y @1 :List(Float32); - psi @2 :List(Float32); - curvature @3 :List(Float32); - qpIterations @4 :UInt32; - calculationTime @5 :UInt64; - cost @6 :Float64; -} - -struct LiveLongitudinalMpcData { - xEgo @0 :List(Float32); - vEgo @1 :List(Float32); - aEgo @2 :List(Float32); - xLead @3 :List(Float32); - vLead @4 :List(Float32); - aLead @5 :List(Float32); - aLeadTau @6 :Float32; # lead accel time constant - qpIterations @7 :UInt32; - mpcId @8 :UInt32; - calculationTime @9 :UInt64; - cost @10 :Float64; + deprecated :group { + bootTimeNanos @0 :UInt64; + monotonicNanos @1 :UInt64; + monotonicRawNanos @2 :UInt64; + modemUptimeMillis @4 :UInt64; + } } struct Joystick { @@ -2144,13 +2097,10 @@ struct Joystick { struct DriverStateV2 { frameId @0 :UInt32; modelExecutionTime @1 :Float32; - dspExecutionTimeDEPRECATED @2 :Float32; gpuExecutionTime @8 :Float32; rawPredictions @3 :Data; - poorVisionProb @4 :Float32; wheelOnRightProb @5 :Float32; - leftDriverData @6 :DriverData; rightDriverData @7 :DriverData; @@ -2165,45 +2115,23 @@ struct DriverStateV2 { leftBlinkProb @7 :Float32; rightBlinkProb @8 :Float32; sunglassesProb @9 :Float32; - occludedProb @10 :Float32; - readyProb @11 :List(Float32); - notReadyProb @12 :List(Float32); + phoneProb @13 :Float32; + sleepProb @14 :Float32; + + deprecated :group { + notReadyProb @12 :List(Float32); + occludedProb @10 :Float32; + readyProb @11 :List(Float32); + } + } + + deprecated :group { + dspExecutionTime @2 :Float32; + poorVisionProb @4 :Float32; } } -struct DriverStateDEPRECATED @0xb83c6cc593ed0a00 { - frameId @0 :UInt32; - modelExecutionTime @14 :Float32; - dspExecutionTime @16 :Float32; - rawPredictions @15 :Data; - - faceOrientation @3 :List(Float32); - facePosition @4 :List(Float32); - faceProb @5 :Float32; - leftEyeProb @6 :Float32; - rightEyeProb @7 :Float32; - leftBlinkProb @8 :Float32; - rightBlinkProb @9 :Float32; - faceOrientationStd @11 :List(Float32); - facePositionStd @12 :List(Float32); - sunglassesProb @13 :Float32; - poorVision @17 :Float32; - partialFace @18 :Float32; - distractedPose @19 :Float32; - distractedEyes @20 :Float32; - eyesOnRoad @21 :Float32; - phoneUse @22 :Float32; - occludedProb @23 :Float32; - - readyProb @24 :List(Float32); - notReadyProb @25 :List(Float32); - - irPwrDEPRECATED @10 :Float32; - descriptorDEPRECATED @1 :List(Float32); - stdDEPRECATED @2 :Float32; -} - -struct DriverMonitoringState @0xb83cda094a1da284 { +struct DriverMonitoringStateDEPRECATED @0xb83cda094a1da284 { events @18 :List(OnroadEvent); faceDetected @1 :Bool; isDistracted @2 :Bool; @@ -2220,10 +2148,92 @@ struct DriverMonitoringState @0xb83cda094a1da284 { hiStdCount @14 :UInt32; isActiveMode @16 :Bool; isRHD @4 :Bool; + uncertainCount @19 :UInt32; - isPreviewDEPRECATED @15 :Bool; - rhdCheckedDEPRECATED @5 :Bool; - eventsDEPRECATED @0 :List(Car.OnroadEventDEPRECATED); + deprecated :group { + phoneProbOffset @20 :Float32; + phoneProbValidCount @21 :UInt32; + isPreview @15 :Bool; + rhdChecked @5 :Bool; + events @0 :List(Car.OnroadEventDEPRECATED); + } +} + +struct DriverMonitoringState { + lockout @0 :Bool; + lockoutCount @15 :Int8; + lockoutMinutesRemaining @11 :Int8; + alert3Count @12 :Int8; + noResponseCount @13 :Int8; + noResponseForceDecel @14 :Bool; + + alwaysOn @3 :Bool; + alwaysOnLockout @4 :Bool; + + alertLevel @5 :AlertLevel; + activePolicy @6 :MonitoringPolicy; + isRHD @7 :Bool; + rhdCalibration @8 :CalibrationState; + + visionPolicyState @9 :VisionPolicyState; + wheeltouchPolicyState @10 :WheeltouchPolicyState; + + enum AlertLevel { + # ordinal must match the name to prevent bugs + # comparing against the raw ordinal value + none @0; + one @1; + two @2; + three @3; + } + + enum MonitoringPolicy { + wheeltouch @0; + vision @1; + } + + struct VisionPolicyState { + awarenessPercent @0 :Int8; + awarenessStep @1 :Float32; + isDistracted @2 :Bool; + distractedTypes @3 :DistractedTypes; + + faceDetected @4 :Bool; + pose @5 :Pose; + wheeltouchFallbackPercent @6 :Int8; + uncertainOffroadAlertPercent @7 :Int8; + + struct DistractedTypes { + pose @0: Bool; + eye @1: Bool; + phone @2: Bool; + } + + struct Pose { + pitch @0 :Float32; + yaw @1 :Float32; + pitchCalib @2 :CalibrationState; + yawCalib @3 :CalibrationState; + calibrated @4 :Bool; + uncertainty @5 :Float32; + } + } + + struct WheeltouchPolicyState { + awarenessPercent @0 :Int8; + awarenessStep @1 :Float32; + driverInteracting @2 :Bool; + } + + struct CalibrationState { + calibratedPercent @0 :Int8; + offset @1 :Float32; + } + + deprecated :group { + alertCountLockoutPercent @1 :Int8; + alertTimeLockoutPercent @2 :Int8; + } } struct Boot { @@ -2232,8 +2242,10 @@ struct Boot { commands @5 :Map(Text, Data); launchLog @3 :Text; - lastKmsgDEPRECATED @1 :Data; - lastPmsgDEPRECATED @2 :Data; + deprecated :group { + lastKmsg @1 :Data; + lastPmsg @2 :Data; + } } struct LiveParametersData { @@ -2258,13 +2270,16 @@ struct LiveParametersData { steerRatioValid @19 :Bool = true; stiffnessFactorValid @20 :Bool = true; - yawRateDEPRECATED @7 :Float32; - filterStateDEPRECATED @15 :LiveLocationKalman.Measurement; struct FilterState { value @0 : List(Float64); std @1 : List(Float64); } + + deprecated :group { + yawRate @7 :Float32; + filterState @15 :LiveLocationKalman.Measurement; + } } struct LiveTorqueParametersData { @@ -2293,6 +2308,7 @@ struct LiveDelayData { lateralDelayEstimateStd @5 :Float32; points @4 :List(Float32); calPerc @6 :Int8; + version @7 :Int32; enum Status { unestimated @0; @@ -2346,7 +2362,8 @@ struct Sentinel { } struct UIDebug { - drawTimeMillis @0 :Float32; + cpuTimeMillis @0 :Float32; + frameTimeMillis @1 :Float32; } struct ManagerState { @@ -2434,25 +2451,6 @@ struct MapRenderState { frameId @2: UInt32; } -struct NavModelData { - frameId @0 :UInt32; - locationMonoTime @6 :UInt64; - modelExecutionTime @1 :Float32; - dspExecutionTime @2 :Float32; - features @3 :List(Float32); - # predicted future position - position @4 :XYData; - desirePrediction @5 :List(Float32); - - # All SI units and in device frame - struct XYData { - x @0 :List(Float32); - y @1 :List(Float32); - xStd @2 :List(Float32); - yStd @3 :List(Float32); - } -} - struct EncodeData { idx @0 :EncodeIndex; data @1 :Data; @@ -2467,16 +2465,29 @@ struct DebugAlert { alertText2 @1 :Text; } -struct UserFlag { +struct UserBookmark @0xfe346a9de48d9b50 { } -struct Microphone { +struct SoundPressure @0xdc24138990726023 { soundPressure @0 :Float32; # uncalibrated, A-weighted soundPressureWeighted @3 :Float32; soundPressureWeightedDb @1 :Float32; - filteredSoundPressureWeightedDb @2 :Float32; + + deprecated :group { + filteredSoundPressureWeightedDb @2 :Float32; + } +} + +struct AudioData { + data @0 :Data; + sampleRate @1 :UInt32; +} + +struct AudioFeedback { + audio @0 :AudioData; + blockNum @1 :UInt16; } struct Touch { @@ -2500,18 +2511,14 @@ struct Event { boot @60 :Boot; # ********** openpilot daemon msgs ********** - gpsNMEA @3 :GPSNMEAData; can @5 :List(CanData); controlsState @7 :ControlsState; selfdriveState @130 :SelfdriveState; gyroscope @99 :SensorEventData; - gyroscope2 @100 :SensorEventData; accelerometer @98 :SensorEventData; - accelerometer2 @101 :SensorEventData; magnetometer @95 :SensorEventData; lightSensor @96 :SensorEventData; temperatureSensor @97 :SensorEventData; - temperatureSensor2 @123 :SensorEventData; pandaStates @81 :List(PandaState); peripheralState @80 :PeripheralState; radarState @13 :RadarState; @@ -2528,7 +2535,6 @@ struct Event { qcomGnss @31 :QcomGnss; gpsLocationExternal @48 :GpsLocationData; gpsLocation @21 :GpsLocationData; - gnssMeasurements @91 :GnssMeasurements; liveParameters @61 :LiveParametersData; liveTorqueParameters @94 :LiveTorqueParametersData; liveDelay @146 : LiveDelayData; @@ -2536,7 +2542,7 @@ struct Event { thumbnail @66: Thumbnail; onroadEvents @134: List(OnroadEvent); carParams @69: Car.CarParams; - driverMonitoringState @71: DriverMonitoringState; + driverMonitoringState @151 :DriverMonitoringState; livePose @129 :LivePose; modelV2 @75 :ModelDataV2; drivingModelData @128 :DrivingModelData; @@ -2556,12 +2562,12 @@ struct Event { livestreamDriverEncodeIdx @119 :EncodeIndex; # microphone data - microphone @103 :Microphone; + soundPressure @103 :SoundPressure; + rawAudioData @147 :AudioData; # systems stuff - androidLog @20 :AndroidLogEntry; + operatingSystemLog @20 :OperatingSystemLogEntry; managerState @78 :ManagerState; - uploaderState @79 :UploaderState; procLog @33 :ProcLog; clocks @35 :Clocks; deviceState @6 :DeviceState; @@ -2571,16 +2577,16 @@ struct Event { # touch frame touch @135 :List(Touch); - # navigation - navInstruction @82 :NavInstruction; - navRoute @83 :NavRoute; - navThumbnail @84: Thumbnail; - mapRenderState @105: MapRenderState; - # UI services - userFlag @93 :UserFlag; uiDebug @102 :UIDebug; + # driving feedback + userBookmark @93 :UserBookmark; + bookmarkButton @148 :UserBookmark; + audioFeedback @149 :AudioFeedback; + + lateralManeuverPlan @150 :LateralManeuverPlan; + # *********** debug *********** testJoystick @52 :Joystick; roadEncodeData @86 :EncodeData; @@ -2613,7 +2619,7 @@ struct Event { backupManagerSP @113 :Custom.BackupManagerSP; carStateSP @114 :Custom.CarStateSP; liveMapDataSP @115 :Custom.LiveMapDataSP; - customReserved9 @116 :Custom.CustomReserved9; + modelDataV2SP @116 :Custom.ModelDataV2SP; customReserved10 @136 :Custom.CustomReserved10; customReserved11 @137 :Custom.CustomReserved11; customReserved12 @138 :Custom.CustomReserved12; @@ -2626,48 +2632,59 @@ struct Event { customReserved19 @145 :Custom.CustomReserved19; # *********** legacy + deprecated *********** - model @9 :Legacy.ModelData; # TODO: rename modelV2 and mark this as deprecated - liveMpcDEPRECATED @36 :LiveMpcData; - liveLongitudinalMpcDEPRECATED @37 :LiveLongitudinalMpcData; - liveLocationKalmanLegacyDEPRECATED @51 :Legacy.LiveLocationData; - orbslamCorrectionDEPRECATED @45 :Legacy.OrbslamCorrection; - liveUIDEPRECATED @14 :Legacy.LiveUI; + model @9 :Deprecated.ModelData; # TODO: rename modelV2 and mark this as deprecated + liveMpcDEPRECATED @36 :Deprecated.LiveMpcData; + liveLongitudinalMpcDEPRECATED @37 :Deprecated.LiveLongitudinalMpcData; + liveLocationKalmanDeprecatedDEPRECATED @51 :Deprecated.LiveLocationData; + orbslamCorrectionDEPRECATED @45 :Deprecated.OrbslamCorrection; + liveUIDEPRECATED @14 :Deprecated.LiveUI; sensorEventDEPRECATED @4 :SensorEventData; - liveEventDEPRECATED @8 :List(Legacy.LiveEventData); - liveLocationDEPRECATED @25 :Legacy.LiveLocationData; - ethernetDataDEPRECATED @26 :List(Legacy.EthernetPacket); - cellInfoDEPRECATED @28 :List(Legacy.CellInfo); - wifiScanDEPRECATED @29 :List(Legacy.WifiScan); - uiNavigationEventDEPRECATED @50 :Legacy.UiNavigationEvent; + liveEventDEPRECATED @8 :List(Deprecated.LiveEventData); + liveLocationDEPRECATED @25 :Deprecated.LiveLocationData; + ethernetDataDEPRECATED @26 :List(Deprecated.EthernetPacket); + cellInfoDEPRECATED @28 :List(Deprecated.CellInfo); + wifiScanDEPRECATED @29 :List(Deprecated.WifiScan); + uiNavigationEventDEPRECATED @50 :Deprecated.UiNavigationEvent; liveMapDataDEPRECATED @62 :LiveMapDataDEPRECATED; - gpsPlannerPointsDEPRECATED @40 :Legacy.GPSPlannerPoints; - gpsPlannerPlanDEPRECATED @41 :Legacy.GPSPlannerPlan; + gpsPlannerPointsDEPRECATED @40 :Deprecated.GPSPlannerPoints; + gpsPlannerPlanDEPRECATED @41 :Deprecated.GPSPlannerPlan; applanixRawDEPRECATED @42 :Data; - androidGnssDEPRECATED @30 :Legacy.AndroidGnss; - lidarPtsDEPRECATED @32 :Legacy.LidarPts; - navStatusDEPRECATED @38 :Legacy.NavStatus; - trafficEventsDEPRECATED @43 :List(Legacy.TrafficEvent); - liveLocationTimingDEPRECATED @44 :Legacy.LiveLocationData; - liveLocationCorrectedDEPRECATED @46 :Legacy.LiveLocationData; - navUpdateDEPRECATED @27 :Legacy.NavUpdate; - orbObservationDEPRECATED @47 :List(Legacy.OrbObservation); - locationDEPRECATED @49 :Legacy.LiveLocationData; - orbOdometryDEPRECATED @53 :Legacy.OrbOdometry; - orbFeaturesDEPRECATED @54 :Legacy.OrbFeatures; - applanixLocationDEPRECATED @55 :Legacy.LiveLocationData; - orbKeyFrameDEPRECATED @56 :Legacy.OrbKeyFrame; - orbFeaturesSummaryDEPRECATED @58 :Legacy.OrbFeaturesSummary; - featuresDEPRECATED @10 :Legacy.CalibrationFeatures; - kalmanOdometryDEPRECATED @65 :Legacy.KalmanOdometry; - uiLayoutStateDEPRECATED @57 :Legacy.UiLayoutState; + androidGnssDEPRECATED @30 :Deprecated.AndroidGnss; + lidarPtsDEPRECATED @32 :Deprecated.LidarPts; + navStatusDEPRECATED @38 :Deprecated.NavStatus; + trafficEventsDEPRECATED @43 :List(Deprecated.TrafficEvent); + liveLocationTimingDEPRECATED @44 :Deprecated.LiveLocationData; + liveLocationCorrectedDEPRECATED @46 :Deprecated.LiveLocationData; + navUpdateDEPRECATED @27 :Deprecated.NavUpdate; + orbObservationDEPRECATED @47 :List(Deprecated.OrbObservation); + locationDEPRECATED @49 :Deprecated.LiveLocationData; + orbOdometryDEPRECATED @53 :Deprecated.OrbOdometry; + orbFeaturesDEPRECATED @54 :Deprecated.OrbFeatures; + applanixLocationDEPRECATED @55 :Deprecated.LiveLocationData; + orbKeyFrameDEPRECATED @56 :Deprecated.OrbKeyFrame; + orbFeaturesSummaryDEPRECATED @58 :Deprecated.OrbFeaturesSummary; + featuresDEPRECATED @10 :Deprecated.CalibrationFeatures; + kalmanOdometryDEPRECATED @65 :Deprecated.KalmanOdometry; + uiLayoutStateDEPRECATED @57 :Deprecated.UiLayoutState; pandaStateDEPRECATED @12 :PandaState; - driverStateDEPRECATED @59 :DriverStateDEPRECATED; + driverStateDEPRECATED @59 :Deprecated.DriverStateDEPRECATED; sensorEventsDEPRECATED @11 :List(SensorEventData); lateralPlanDEPRECATED @64 :LateralPlan; - navModelDEPRECATED @104 :NavModelData; + navModelDEPRECATED @104 :Deprecated.NavModelData; uiPlanDEPRECATED @106 :UiPlan; - liveLocationKalmanDEPRECATED @72 :LiveLocationKalman; - liveTracksDEPRECATED @16 :List(LiveTracksDEPRECATED); + liveLocationKalman @72 :LiveLocationKalman; + liveTracksDEPRECATED @16 :List(Deprecated.LiveTracksDEPRECATED); onroadEventsDEPRECATED @68: List(Car.OnroadEventDEPRECATED); + gyroscope2DEPRECATED @100 :SensorEventData; + accelerometer2DEPRECATED @101 :SensorEventData; + temperatureSensor2DEPRECATED @123 :SensorEventData; + driverMonitoringStateDEPRECATED @71 :DriverMonitoringStateDEPRECATED; + gpsNMEADEPRECATED @3 :GPSNMEAData; + uploaderStateDEPRECATED @79 :UploaderState; + navInstructionDEPRECATED @82 :NavInstruction; + navRouteDEPRECATED @83 :NavRoute; + navThumbnailDEPRECATED @84 :Thumbnail; + gnssMeasurementsDEPRECATED @91 :GnssMeasurements; + mapRenderStateDEPRECATED @105: MapRenderState; } } diff --git a/openpilot/cereal/messaging/__init__.py b/openpilot/cereal/messaging/__init__.py new file mode 100644 index 0000000000..dcc54baeb0 --- /dev/null +++ b/openpilot/cereal/messaging/__init__.py @@ -0,0 +1,300 @@ +# must be built with scons +from msgq import fake_event_handle, drain_sock_raw, MultiplePublishersError, IpcError, \ + Context, Poller, SubSocket, PubSocket, SocketEventHandle, toggle_fake_events, \ + set_fake_prefix, get_fake_prefix, delete_fake_prefix, wait_for_one_event +import msgq +import os +import capnp +import time + +from typing import Union + +from openpilot.cereal import log +from openpilot.cereal.services import SERVICE_LIST +from openpilot.common.utils import MovingAverage + +__all__ = ( + "NO_TRAVERSAL_LIMIT", + "Context", + "FrequencyTracker", + "IpcError", + "MultiplePublishersError", + "Poller", + "PubMaster", + "PubSocket", + "SocketEventHandle", + "SubMaster", + "SubSocket", + "delete_fake_prefix", + "drain_sock", + "drain_sock_raw", + "fake_event_handle", + "get_fake_prefix", + "log_from_bytes", + "new_message", + "pub_sock", + "recv_one", + "recv_one_or_none", + "recv_one_retry", + "recv_sock", + "reset_context", + "set_fake_prefix", + "sub_sock", + "toggle_fake_events", + "wait_for_one_event", +) + +NO_TRAVERSAL_LIMIT = 2**64-1 + + +def pub_sock(endpoint: str) -> PubSocket: + service = SERVICE_LIST.get(endpoint) + segment_size = service.queue_size if service else 0 + return msgq.pub_sock(endpoint, segment_size) + + +def sub_sock(endpoint: str, poller: Poller | None = None, addr: str = "127.0.0.1", + conflate: bool = False, timeout: int | None = None) -> SubSocket: + service = SERVICE_LIST.get(endpoint) + segment_size = service.queue_size if service else 0 + return msgq.sub_sock(endpoint, poller=poller, addr=addr, conflate=conflate, + timeout=timeout, segment_size=segment_size) + + +def reset_context(): + msgq.context = Context() + + +def log_from_bytes(dat: bytes, struct: capnp.lib.capnp._StructModule = log.Event) -> capnp.lib.capnp._DynamicStructReader: + with struct.from_bytes(dat, traversal_limit_in_words=NO_TRAVERSAL_LIMIT) as msg: + return msg + + +def new_message(service: str | None, size: int | None = None, **kwargs) -> capnp.lib.capnp._DynamicStructBuilder: + args = { + 'valid': False, + 'logMonoTime': int(time.monotonic() * 1e9), + **kwargs + } + dat = log.Event.new_message(**args) + if service is not None: + if size is None: + dat.init(service) + else: + dat.init(service, size) + return dat + + +def drain_sock(sock: SubSocket, wait_for_one: bool = False) -> list[capnp.lib.capnp._DynamicStructReader]: + """Receive all message currently available on the queue""" + msgs = drain_sock_raw(sock, wait_for_one=wait_for_one) + return [log_from_bytes(m) for m in msgs] + + +# TODO: print when we drop packets? +def recv_sock(sock: SubSocket, wait: bool = False) -> capnp.lib.capnp._DynamicStructReader | None: + """Same as drain sock, but only returns latest message. Consider using conflate instead.""" + dat = None + + while 1: + if wait and dat is None: + recv = sock.receive() + else: + recv = sock.receive(non_blocking=True) + + if recv is None: # Timeout hit + break + + dat = recv + + if dat is not None: + dat = log_from_bytes(dat) + + return dat + + +def recv_one(sock: SubSocket) -> capnp.lib.capnp._DynamicStructReader | None: + dat = sock.receive() + if dat is not None: + dat = log_from_bytes(dat) + return dat + + +def recv_one_or_none(sock: SubSocket) -> capnp.lib.capnp._DynamicStructReader | None: + dat = sock.receive(non_blocking=True) + if dat is not None: + dat = log_from_bytes(dat) + return dat + + +def recv_one_retry(sock: SubSocket) -> capnp.lib.capnp._DynamicStructReader: + """Keep receiving until we get a message""" + while True: + dat = sock.receive() + if dat is not None: + return log_from_bytes(dat) + + +class FrequencyTracker: + def __init__(self, service_freq: float, update_freq: float, is_poll: bool): + freq = max(min(service_freq, update_freq), 1.) + if is_poll: + min_freq = max_freq = freq + else: + max_freq = min(freq, update_freq) + if service_freq >= 2 * update_freq: + min_freq = update_freq + elif update_freq >= 2* service_freq: + min_freq = freq + else: + min_freq = min(freq, freq / 2.) + + self.min_freq = min_freq * 0.8 + self.max_freq = max_freq * 1.2 + self.avg_dt = MovingAverage(int(10 * freq)) + self.recent_avg_dt = MovingAverage(int(freq)) + self.prev_time = 0.0 + + def record_recv_time(self, cur_time: float) -> None: + # TODO: Handle case where cur_time is less than prev_time + if self.prev_time > 1e-5: + dt = cur_time - self.prev_time + + self.avg_dt.add_value(dt) + self.recent_avg_dt.add_value(dt) + + self.prev_time = cur_time + + @property + def valid(self) -> bool: + if self.avg_dt.count == 0: + return False + + avg_freq = 1.0 / self.avg_dt.get_average() + if self.min_freq <= avg_freq <= self.max_freq: + return True + + avg_freq_recent = 1.0 / self.recent_avg_dt.get_average() + return self.min_freq <= avg_freq_recent <= self.max_freq + + +class SubMaster: + def __init__(self, services: list[str], poll: str | None = None, + ignore_alive: list[str] | None = None, ignore_avg_freq: list[str] | None = None, + ignore_valid: list[str] | None = None, addr: str = "127.0.0.1", frequency: float | None = None): + self.frame = -1 + self.services = services + self.seen = dict.fromkeys(services, False) + self.updated = dict.fromkeys(services, False) + self.recv_time = dict.fromkeys(services, 0.0) + self.recv_frame = dict.fromkeys(services, 0) + self.sock = {} + self.data = {} + self.logMonoTime = dict.fromkeys(services, 0) + + # zero-frequency / on-demand services are always alive and presumed valid; all others must pass checks + on_demand = {s: SERVICE_LIST[s].frequency <= 1e-5 for s in services} + self.static_freq_services = {s for s in services if not on_demand[s]} + self.alive = {s: on_demand[s] for s in services} + self.freq_ok = {s: on_demand[s] for s in services} + self.valid = {s: on_demand[s] for s in services} + + self.freq_tracker: dict[str, FrequencyTracker] = {} + self.poller = Poller() + polled_services = set([poll, ] if poll is not None else services) + self.non_polled_services = set(services) - polled_services + + self.ignore_average_freq = [] if ignore_avg_freq is None else ignore_avg_freq + self.ignore_alive = [] if ignore_alive is None else ignore_alive + self.ignore_valid = [] if ignore_valid is None else ignore_valid + + self.simulation = bool(int(os.getenv("SIMULATION", "0"))) + + # if freq and poll aren't specified, assume the max to be conservative + assert frequency is None or poll is None, "Do not specify 'frequency' - frequency of the polled service will be used." + self.update_freq = frequency or max([SERVICE_LIST[s].frequency for s in polled_services]) + + for s in services: + p = self.poller if s not in self.non_polled_services else None + self.sock[s] = sub_sock(s, poller=p, addr=addr, conflate=True) + + try: + data = new_message(s) + except capnp.lib.capnp.KjException: + data = new_message(s, 0) # lists + + self.data[s] = getattr(data.as_reader(), s) + self.freq_tracker[s] = FrequencyTracker(SERVICE_LIST[s].frequency, self.update_freq, s == poll) + + def __getitem__(self, s: str) -> capnp.lib.capnp._DynamicStructReader: + return self.data[s] + + def _check_avg_freq(self, s: str) -> bool: + return SERVICE_LIST[s].frequency > 0.99 and (s not in self.ignore_average_freq) and (s not in self.ignore_alive) + + def update(self, timeout: int = 100) -> None: + msgs = [] + for sock in self.poller.poll(timeout): + msgs.append(recv_one_or_none(sock)) + + # non-blocking receive for non-polled sockets + for s in self.non_polled_services: + msgs.append(recv_one_or_none(self.sock[s])) + self.update_msgs(time.monotonic(), msgs) + + def update_msgs(self, cur_time: float, msgs: list[capnp.lib.capnp._DynamicStructReader]) -> None: + self.frame += 1 + self.updated = dict.fromkeys(self.services, False) + for msg in msgs: + if msg is None: + continue + + s = msg.which() + self.seen[s] = True + self.updated[s] = True + + self.freq_tracker[s].record_recv_time(cur_time) + self.recv_time[s] = cur_time + self.recv_frame[s] = self.frame + self.data[s] = getattr(msg, s) + self.logMonoTime[s] = msg.logMonoTime + self.valid[s] = msg.valid + + for s in self.static_freq_services: + # alive if delay is within 10x the expected frequency; checks relaxed in simulator + self.alive[s] = (cur_time - self.recv_time[s]) < (10. / SERVICE_LIST[s].frequency) or (self.seen[s] and self.simulation) + self.freq_ok[s] = self.freq_tracker[s].valid or self.simulation + + def all_alive(self, service_list: list[str] | None = None) -> bool: + return all(self.alive[s] for s in (service_list or self.services) if s not in self.ignore_alive) + + def all_freq_ok(self, service_list: list[str] | None = None) -> bool: + return all(self.freq_ok[s] for s in (service_list or self.services) if self._check_avg_freq(s)) + + def all_valid(self, service_list: list[str] | None = None) -> bool: + return all(self.valid[s] for s in (service_list or self.services) if s not in self.ignore_valid) + + def all_checks(self, service_list: list[str] | None = None) -> bool: + return self.all_alive(service_list) and self.all_freq_ok(service_list) and self.all_valid(service_list) + + +class PubMaster: + def __init__(self, services: list[str]): + self.sock = {} + for s in services: + self.sock[s] = pub_sock(s) + + def send(self, s: str, dat: Union[bytes, capnp.lib.capnp._DynamicStructBuilder]) -> None: + if not isinstance(dat, bytes): + dat = dat.to_bytes() + self.sock[s].send(dat) + + def wait_for_readers_to_update(self, s: str, timeout: int, dt: float = 0.05) -> bool: + try: + self.sock[s].wait_for_readers(timeout=timeout, interval=dt) + return True + except TimeoutError: + return False + + def all_readers_updated(self, s: str) -> bool: + return self.sock[s].all_readers_updated() diff --git a/cereal/messaging/bridge.cc b/openpilot/cereal/messaging/bridge.cc similarity index 75% rename from cereal/messaging/bridge.cc rename to openpilot/cereal/messaging/bridge.cc index 69ecd188e1..ee3d5e93ca 100644 --- a/cereal/messaging/bridge.cc +++ b/openpilot/cereal/messaging/bridge.cc @@ -1,7 +1,7 @@ #include -#include "cereal/messaging/msgq_to_zmq.h" -#include "cereal/services.h" +#include "openpilot/cereal/messaging/msgq_to_zmq.h" +#include "openpilot/cereal/services.h" #include "common/util.h" ExitHandler do_exit; @@ -25,15 +25,16 @@ void msgq_to_zmq(const std::vector &endpoints, const std::string &i } void zmq_to_msgq(const std::vector &endpoints, const std::string &ip) { - auto poller = std::make_unique(); - auto pub_context = std::make_unique(); - auto sub_context = std::make_unique(); - std::map sub2pub; + auto poller = std::make_unique(); + auto pub_context = std::make_unique(); + auto sub_context = std::make_unique(); + std::map sub2pub; for (auto endpoint : endpoints) { - auto pub_sock = new MSGQPubSocket(); - auto sub_sock = new ZMQSubSocket(); - pub_sock->connect(pub_context.get(), endpoint); + auto pub_sock = new PubSocket(); + auto sub_sock = new BridgeZmqSubSocket(); + size_t queue_size = services.at(endpoint).queue_size; + pub_sock->connect(pub_context.get(), endpoint, true, queue_size); sub_sock->connect(sub_context.get(), endpoint, ip, false); poller->registerSocket(sub_sock); diff --git a/openpilot/cereal/messaging/bridge_zmq.cc b/openpilot/cereal/messaging/bridge_zmq.cc new file mode 100644 index 0000000000..72d4345d03 --- /dev/null +++ b/openpilot/cereal/messaging/bridge_zmq.cc @@ -0,0 +1,170 @@ +#include "openpilot/cereal/messaging/bridge_zmq.h" + +#include +#include +#include + +static size_t fnv1a_hash(const std::string &str) { + const size_t fnv_prime = 0x100000001b3; + size_t hash_value = 0xcbf29ce484222325; + for (char c : str) { + hash_value ^= (unsigned char)c; + hash_value *= fnv_prime; + } + return hash_value; +} + +// FIXME: This is a hack to get the port number from the socket name, might have collisions. +static int get_port(std::string endpoint) { + size_t hash_value = fnv1a_hash(endpoint); + int start_port = 8023; + int max_port = 65535; + return start_port + (hash_value % (max_port - start_port)); +} + +BridgeZmqContext::BridgeZmqContext() { + context = zmq_ctx_new(); +} + +BridgeZmqContext::~BridgeZmqContext() { + if (context != nullptr) { + zmq_ctx_term(context); + } +} + +void BridgeZmqMessage::init(size_t sz) { + size = sz; + data = new char[size]; +} + +void BridgeZmqMessage::init(char *d, size_t sz) { + size = sz; + data = new char[size]; + memcpy(data, d, size); +} + +void BridgeZmqMessage::close() { + if (size > 0) { + delete[] data; + } + data = nullptr; + size = 0; +} + +BridgeZmqMessage::~BridgeZmqMessage() { + close(); +} + +int BridgeZmqSubSocket::connect(BridgeZmqContext *context, std::string endpoint, std::string address, bool conflate, bool check_endpoint) { + sock = zmq_socket(context->getRawContext(), ZMQ_SUB); + if (sock == nullptr) { + return -1; + } + + zmq_setsockopt(sock, ZMQ_SUBSCRIBE, "", 0); + + if (conflate) { + int arg = 1; + zmq_setsockopt(sock, ZMQ_CONFLATE, &arg, sizeof(int)); + } + + int reconnect_ivl = 500; + zmq_setsockopt(sock, ZMQ_RECONNECT_IVL_MAX, &reconnect_ivl, sizeof(reconnect_ivl)); + + full_endpoint = "tcp://" + address + ":"; + if (check_endpoint) { + full_endpoint += std::to_string(get_port(endpoint)); + } else { + full_endpoint += endpoint; + } + + return zmq_connect(sock, full_endpoint.c_str()); +} + +void BridgeZmqSubSocket::setTimeout(int timeout) { + zmq_setsockopt(sock, ZMQ_RCVTIMEO, &timeout, sizeof(int)); +} + +Message *BridgeZmqSubSocket::receive(bool non_blocking) { + zmq_msg_t msg; + assert(zmq_msg_init(&msg) == 0); + + int flags = non_blocking ? ZMQ_DONTWAIT : 0; + int rc = zmq_msg_recv(&msg, sock, flags); + + Message *ret = nullptr; + if (rc >= 0) { + ret = new BridgeZmqMessage; + ret->init((char *)zmq_msg_data(&msg), zmq_msg_size(&msg)); + } + + zmq_msg_close(&msg); + return ret; +} + +BridgeZmqSubSocket::~BridgeZmqSubSocket() { + if (sock != nullptr) { + zmq_close(sock); + } +} + +int BridgeZmqPubSocket::connect(BridgeZmqContext *context, std::string endpoint, bool check_endpoint) { + sock = zmq_socket(context->getRawContext(), ZMQ_PUB); + if (sock == nullptr) { + return -1; + } + + full_endpoint = "tcp://*:"; + if (check_endpoint) { + full_endpoint += std::to_string(get_port(endpoint)); + } else { + full_endpoint += endpoint; + } + + // ZMQ pub sockets cannot be shared between processes, so we need to ensure pid stays the same. + pid = getpid(); + + return zmq_bind(sock, full_endpoint.c_str()); +} + +int BridgeZmqPubSocket::sendMessage(Message *message) { + assert(pid == getpid()); + return zmq_send(sock, message->getData(), message->getSize(), ZMQ_DONTWAIT); +} + +int BridgeZmqPubSocket::send(char *data, size_t size) { + assert(pid == getpid()); + return zmq_send(sock, data, size, ZMQ_DONTWAIT); +} + +BridgeZmqPubSocket::~BridgeZmqPubSocket() { + if (sock != nullptr) { + zmq_close(sock); + } +} + +void BridgeZmqPoller::registerSocket(BridgeZmqSubSocket *socket) { + assert(num_polls + 1 < (sizeof(polls) / sizeof(polls[0]))); + polls[num_polls].socket = socket->getRawSocket(); + polls[num_polls].events = ZMQ_POLLIN; + + sockets.push_back(socket); + num_polls++; +} + +std::vector BridgeZmqPoller::poll(int timeout) { + std::vector ret; + + int rc = zmq_poll(polls, num_polls, timeout); + if (rc < 0) { + return ret; + } + + for (size_t i = 0; i < num_polls; i++) { + if (polls[i].revents) { + ret.push_back(sockets[i]); + } + } + + return ret; +} diff --git a/openpilot/cereal/messaging/bridge_zmq.h b/openpilot/cereal/messaging/bridge_zmq.h new file mode 100644 index 0000000000..ebdbc56c24 --- /dev/null +++ b/openpilot/cereal/messaging/bridge_zmq.h @@ -0,0 +1,72 @@ +#pragma once + +#include +#include +#include + +#include + +#include "msgq/ipc.h" + +class BridgeZmqContext { +public: + BridgeZmqContext(); + void *getRawContext() { return context; } + ~BridgeZmqContext(); + +private: + void *context = nullptr; +}; + +class BridgeZmqMessage : public Message { +public: + void init(size_t size); + void init(char *data, size_t size); + void close(); + size_t getSize() { return size; } + char *getData() { return data; } + ~BridgeZmqMessage(); + +private: + char *data = nullptr; + size_t size = 0; +}; + +class BridgeZmqSubSocket { +public: + int connect(BridgeZmqContext *context, std::string endpoint, std::string address, bool conflate = false, bool check_endpoint = true); + void setTimeout(int timeout); + Message *receive(bool non_blocking = false); + void *getRawSocket() { return sock; } + ~BridgeZmqSubSocket(); + +private: + void *sock = nullptr; + std::string full_endpoint; +}; + +class BridgeZmqPubSocket { +public: + int connect(BridgeZmqContext *context, std::string endpoint, bool check_endpoint = true); + int sendMessage(Message *message); + int send(char *data, size_t size); + void *getRawSocket() { return sock; } + ~BridgeZmqPubSocket(); + +private: + void *sock = nullptr; + std::string full_endpoint; + int pid = -1; +}; + +class BridgeZmqPoller { +public: + void registerSocket(BridgeZmqSubSocket *socket); + std::vector poll(int timeout); + +private: + static constexpr size_t MAX_BRIDGE_ZMQ_POLLERS = 128; + std::vector sockets; + zmq_pollitem_t polls[MAX_BRIDGE_ZMQ_POLLERS] = {}; + size_t num_polls = 0; +}; diff --git a/cereal/messaging/messaging.h b/openpilot/cereal/messaging/messaging.h similarity index 98% rename from cereal/messaging/messaging.h rename to openpilot/cereal/messaging/messaging.h index fb9c261f2b..933e0b9f15 100644 --- a/cereal/messaging/messaging.h +++ b/openpilot/cereal/messaging/messaging.h @@ -8,7 +8,7 @@ #include -#include "cereal/gen/cpp/log.capnp.h" +#include "openpilot/cereal/gen/cpp/log.capnp.h" #include "common/timing.h" #include "msgq/ipc.h" diff --git a/cereal/messaging/msgq_to_zmq.cc b/openpilot/cereal/messaging/msgq_to_zmq.cc similarity index 87% rename from cereal/messaging/msgq_to_zmq.cc rename to openpilot/cereal/messaging/msgq_to_zmq.cc index ce626f2aad..adea00f923 100644 --- a/cereal/messaging/msgq_to_zmq.cc +++ b/openpilot/cereal/messaging/msgq_to_zmq.cc @@ -1,7 +1,8 @@ -#include "cereal/messaging/msgq_to_zmq.h" +#include "openpilot/cereal/messaging/msgq_to_zmq.h" #include +#include "openpilot/cereal/services.h" #include "common/util.h" extern ExitHandler do_exit; @@ -21,14 +22,14 @@ static std::string recv_zmq_msg(void *sock) { } void MsgqToZmq::run(const std::vector &endpoints, const std::string &ip) { - zmq_context = std::make_unique(); - msgq_context = std::make_unique(); + zmq_context = std::make_unique(); + msgq_context = std::make_unique(); // Create ZMQPubSockets for each endpoint for (const auto &endpoint : endpoints) { auto &socket_pair = socket_pairs.emplace_back(); socket_pair.endpoint = endpoint; - socket_pair.pub_sock = std::make_unique(); + socket_pair.pub_sock = std::make_unique(); int ret = socket_pair.pub_sock->connect(zmq_context.get(), endpoint); if (ret != 0) { printf("Failed to create ZMQ publisher for [%s]: %s\n", endpoint.c_str(), zmq_strerror(zmq_errno())); @@ -48,7 +49,7 @@ void MsgqToZmq::run(const std::vector &endpoints, const std::string for (auto sub_sock : msgq_poller->poll(100)) { // Process messages for each socket - ZMQPubSocket *pub_sock = sub2pub.at(sub_sock); + BridgeZmqPubSocket *pub_sock = sub2pub.at(sub_sock); for (int i = 0; i < MAX_MESSAGES_PER_SOCKET; ++i) { auto msg = std::unique_ptr(sub_sock->receive(true)); if (!msg) break; @@ -71,7 +72,7 @@ void MsgqToZmq::zmqMonitorThread() { // Set up ZMQ monitor for each pub socket for (int i = 0; i < socket_pairs.size(); ++i) { std::string addr = "inproc://op-bridge-monitor-" + std::to_string(i); - zmq_socket_monitor(socket_pairs[i].pub_sock->sock, addr.c_str(), ZMQ_EVENT_ACCEPTED | ZMQ_EVENT_DISCONNECTED); + zmq_socket_monitor(socket_pairs[i].pub_sock->getRawSocket(), addr.c_str(), ZMQ_EVENT_ACCEPTED | ZMQ_EVENT_DISCONNECTED); void *monitor_socket = zmq_socket(zmq_context->getRawContext(), ZMQ_PAIR); zmq_connect(monitor_socket, addr.c_str()); @@ -108,7 +109,8 @@ void MsgqToZmq::zmqMonitorThread() { if (++pair.connected_clients == 1) { // Create new MSGQ subscriber socket and map to ZMQ publisher pair.sub_sock = std::make_unique(); - pair.sub_sock->connect(msgq_context.get(), pair.endpoint, "127.0.0.1"); + size_t queue_size = services.at(pair.endpoint).queue_size; + pair.sub_sock->connect(msgq_context.get(), pair.endpoint, "127.0.0.1", false, true, queue_size); sub2pub[pair.sub_sock.get()] = pair.pub_sock.get(); registerSockets(); } @@ -128,7 +130,7 @@ void MsgqToZmq::zmqMonitorThread() { // Clean up monitor sockets for (int i = 0; i < pollitems.size(); ++i) { - zmq_socket_monitor(socket_pairs[i].pub_sock->sock, nullptr, 0); + zmq_socket_monitor(socket_pairs[i].pub_sock->getRawSocket(), nullptr, 0); zmq_close(pollitems[i].socket); } cv.notify_one(); diff --git a/openpilot/cereal/messaging/msgq_to_zmq.h b/openpilot/cereal/messaging/msgq_to_zmq.h new file mode 100644 index 0000000000..a34f0ebbf0 --- /dev/null +++ b/openpilot/cereal/messaging/msgq_to_zmq.h @@ -0,0 +1,36 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "msgq/impl_msgq.h" +#include "openpilot/cereal/messaging/bridge_zmq.h" + +class MsgqToZmq { +public: + MsgqToZmq() {} + void run(const std::vector &endpoints, const std::string &ip); + +protected: + void registerSockets(); + void zmqMonitorThread(); + + struct SocketPair { + std::string endpoint; + std::unique_ptr pub_sock; + std::unique_ptr sub_sock; + int connected_clients = 0; + }; + + std::unique_ptr msgq_context; + std::unique_ptr zmq_context; + std::mutex mutex; + std::condition_variable cv; + std::unique_ptr msgq_poller; + std::map sub2pub; + std::vector socket_pairs; +}; diff --git a/cereal/messaging/socketmaster.cc b/openpilot/cereal/messaging/socketmaster.cc similarity index 95% rename from cereal/messaging/socketmaster.cc rename to openpilot/cereal/messaging/socketmaster.cc index 1a7a48980e..dd285a0c8e 100644 --- a/cereal/messaging/socketmaster.cc +++ b/openpilot/cereal/messaging/socketmaster.cc @@ -3,8 +3,8 @@ #include #include -#include "cereal/services.h" -#include "cereal/messaging/messaging.h" +#include "openpilot/cereal/services.h" +#include "openpilot/cereal/messaging/messaging.h" const bool SIMULATION = (getenv("SIMULATION") != nullptr) && (std::string(getenv("SIMULATION")) == "1"); @@ -33,7 +33,7 @@ MessageContext message_context; struct SubMaster::SubMessage { std::string name; SubSocket *socket = nullptr; - int freq = 0; + float freq = 0.0f; bool updated = false, alive = false, valid = false, ignore_alive; uint64_t rcv_time = 0, rcv_frame = 0; void *allocated_msg_reader = nullptr; @@ -50,7 +50,7 @@ SubMaster::SubMaster(const std::vector &service_list, const std::v assert(services.count(std::string(name)) > 0); service serv = services.at(std::string(name)); - SubSocket *socket = SubSocket::create(message_context.context(), name, address ? address : "127.0.0.1", true); + SubSocket *socket = SubSocket::create(message_context.context(), name, address ? address : "127.0.0.1", true, true, serv.queue_size); assert(socket != 0); bool is_polled = inList(poll, name) || poll.empty(); if (is_polled) poller_->registerSocket(socket); @@ -187,7 +187,8 @@ SubMaster::~SubMaster() { PubMaster::PubMaster(const std::vector &service_list) { for (auto name : service_list) { assert(services.count(name) > 0); - PubSocket *socket = PubSocket::create(message_context.context(), name); + service serv = services.at(std::string(name)); + PubSocket *socket = PubSocket::create(message_context.context(), name, true, serv.queue_size); assert(socket); sockets_[name] = socket; } diff --git a/cereal/messaging/tests/__init__.py b/openpilot/cereal/messaging/tests/__init__.py similarity index 100% rename from cereal/messaging/tests/__init__.py rename to openpilot/cereal/messaging/tests/__init__.py diff --git a/cereal/messaging/tests/test_messaging.py b/openpilot/cereal/messaging/tests/test_messaging.py similarity index 80% rename from cereal/messaging/tests/test_messaging.py rename to openpilot/cereal/messaging/tests/test_messaging.py index 6234a11c08..92d77f1b35 100644 --- a/cereal/messaging/tests/test_messaging.py +++ b/openpilot/cereal/messaging/tests/test_messaging.py @@ -1,16 +1,15 @@ -import os import capnp import multiprocessing import numbers import random import threading import time -from parameterized import parameterized -import pytest +from openpilot.common.parameterized import parameterized -from cereal import log, car -import cereal.messaging as messaging -from cereal.services import SERVICE_LIST +from openpilot.cereal import log +from opendbc.car.structs import car +import openpilot.cereal.messaging as messaging +from openpilot.cereal.services import SERVICE_LIST events = [evt for evt in log.Event.schema.union_fields if evt in SERVICE_LIST.keys()] @@ -23,14 +22,10 @@ def random_socks(num_socks=10): def random_bytes(length=1000): return bytes([random.randrange(0xFF) for _ in range(length)]) -def zmq_sleep(t=1): - if "ZMQ" in os.environ: - time.sleep(t) - # TODO: this should take any capnp struct and returrn a msg with random populated data def random_carstate(): - fields = ["vEgo", "aEgo", "gas", "steeringAngleDeg"] + fields = ["vEgo", "aEgo", "steeringTorque", "steeringAngleDeg"] msg = messaging.new_message("carState") cs = msg.carState for f in fields: @@ -52,16 +47,6 @@ def delayed_send(delay, sock, dat): class TestMessaging: - def setUp(self): - # TODO: ZMQ tests are too slow; all sleeps will need to be - # replaced with logic to block on the necessary condition - if "ZMQ" in os.environ: - pytest.skip() - - # ZMQ pub socket takes too long to die - # sleep to prevent multiple publishers error between tests - zmq_sleep() - @parameterized.expand(events) def test_new_message(self, evt): try: @@ -88,7 +73,6 @@ class TestMessaging: sock = "carState" pub_sock = messaging.pub_sock(sock) sub_sock = messaging.sub_sock(sock, timeout=1000) - zmq_sleep() # no wait and no msgs in queue msgs = func(sub_sock) @@ -109,7 +93,6 @@ class TestMessaging: sock = "carState" pub_sock = messaging.pub_sock(sock) sub_sock = messaging.sub_sock(sock, timeout=100) - zmq_sleep() # no wait and no msg in queue, socket should timeout recvd = messaging.recv_sock(sub_sock) @@ -128,7 +111,6 @@ class TestMessaging: sock = "carState" pub_sock = messaging.pub_sock(sock) sub_sock = messaging.sub_sock(sock, timeout=1000) - zmq_sleep() # no msg in queue, socket should timeout recvd = messaging.recv_one(sub_sock) @@ -141,12 +123,10 @@ class TestMessaging: assert isinstance(recvd, capnp._DynamicStructReader) assert_carstate(msg.carState, recvd.carState) - @pytest.mark.xfail(condition="ZMQ" in os.environ, reason='ZMQ detected') def test_recv_one_or_none(self): sock = "carState" pub_sock = messaging.pub_sock(sock) sub_sock = messaging.sub_sock(sock) - zmq_sleep() # no msg in queue, socket shouldn't block recvd = messaging.recv_one_or_none(sub_sock) @@ -164,21 +144,18 @@ class TestMessaging: sock_timeout = 0.1 pub_sock = messaging.pub_sock(sock) sub_sock = messaging.sub_sock(sock, timeout=round(sock_timeout*1000)) - zmq_sleep() - # this test doesn't work with ZMQ since multiprocessing interrupts it - if "ZMQ" not in os.environ: - # wait 5 socket timeouts and make sure it's still retrying - p = multiprocessing.Process(target=messaging.recv_one_retry, args=(sub_sock,)) - p.start() - time.sleep(sock_timeout*5) - assert p.is_alive() - p.terminate() + # wait 5 socket timeouts and make sure it's still retrying + p = multiprocessing.Process(target=messaging.recv_one_retry, args=(sub_sock,)) + p.start() + time.sleep(sock_timeout*5) + assert p.is_alive() + p.terminate() # wait 5 socket timeouts before sending msg = random_carstate() - delayed_send(sock_timeout*5, pub_sock, msg.to_bytes()) start_time = time.monotonic() + delayed_send(sock_timeout*5, pub_sock, msg.to_bytes()) recvd = messaging.recv_one_retry(sub_sock) assert (time.monotonic() - start_time) >= sock_timeout*5 assert isinstance(recvd, capnp._DynamicStructReader) diff --git a/cereal/messaging/tests/test_pub_sub_master.py b/openpilot/cereal/messaging/tests/test_pub_sub_master.py similarity index 83% rename from cereal/messaging/tests/test_pub_sub_master.py rename to openpilot/cereal/messaging/tests/test_pub_sub_master.py index e47e713393..7353764aea 100644 --- a/cereal/messaging/tests/test_pub_sub_master.py +++ b/openpilot/cereal/messaging/tests/test_pub_sub_master.py @@ -1,21 +1,16 @@ import random import time -from typing import Sized, cast +from typing import cast +from collections.abc import Sized -import cereal.messaging as messaging -from cereal.messaging.tests.test_messaging import events, random_sock, random_socks, \ - random_bytes, random_carstate, assert_carstate, \ - zmq_sleep -from cereal.services import SERVICE_LIST +import openpilot.cereal.messaging as messaging +from openpilot.cereal.messaging.tests.test_messaging import events, random_sock, random_socks, \ + random_bytes, random_carstate, assert_carstate +from openpilot.cereal.services import SERVICE_LIST class TestSubMaster: - def setup_method(self): - # ZMQ pub socket takes too long to die - # sleep to prevent multiple publishers error between tests - zmq_sleep(3) - def test_init(self): sm = messaging.SubMaster(events) for p in [sm.updated, sm.recv_time, sm.recv_frame, sm.alive, @@ -42,7 +37,6 @@ class TestSubMaster: sock = "carState" pub_sock = messaging.pub_sock(sock) sm = messaging.SubMaster([sock,]) - zmq_sleep() msg = random_carstate() pub_sock.send(msg.to_bytes()) @@ -54,7 +48,6 @@ class TestSubMaster: sock = "carState" pub_sock = messaging.pub_sock(sock) sm = messaging.SubMaster([sock,]) - zmq_sleep() for i in range(10): msg = messaging.new_message(sock) @@ -86,26 +79,18 @@ class TestSubMaster: "cameraOdometry": (20, 10), "liveCalibration": (4, 4), "carParams": (None, None), - "userFlag": (None, None), + "userBookmark": (None, None), } for service, (max_freq, min_freq) in checks.items(): if max_freq is not None: + assert min_freq is not None assert sm._check_avg_freq(service) assert sm.freq_tracker[service].max_freq == max_freq*1.2 assert sm.freq_tracker[service].min_freq == min_freq*0.8 else: assert not sm._check_avg_freq(service) - def test_alive(self): - pass - - def test_ignore_alive(self): - pass - - def test_valid(self): - pass - # SubMaster should always conflate def test_conflate(self): sock = "carState" @@ -124,11 +109,6 @@ class TestSubMaster: class TestPubMaster: - def setup_method(self): - # ZMQ pub socket takes too long to die - # sleep to prevent multiple publishers error between tests - zmq_sleep(3) - def test_init(self): messaging.PubMaster(events) @@ -136,7 +116,6 @@ class TestPubMaster: socks = random_socks() pm = messaging.PubMaster(socks) sub_socks = {s: messaging.sub_sock(s, conflate=True, timeout=1000) for s in socks} - zmq_sleep() # PubMaster accepts either a capnp msg builder or bytes for capnp in [True, False]: diff --git a/openpilot/cereal/messaging/tests/test_services.py b/openpilot/cereal/messaging/tests/test_services.py new file mode 100644 index 0000000000..9ae7c3d840 --- /dev/null +++ b/openpilot/cereal/messaging/tests/test_services.py @@ -0,0 +1,21 @@ +import subprocess +import tempfile + +from openpilot.common.parameterized import parameterized + +import openpilot.cereal.services as services +from openpilot.cereal.services import SERVICE_LIST + + +class TestServices: + + @parameterized.expand(SERVICE_LIST.keys()) + def test_services(self, s): + service = SERVICE_LIST[s] + assert service.frequency <= 104 + assert service.decimation != 0 + + def test_generated_header(self): + with tempfile.NamedTemporaryFile(suffix=".h") as f: + ret = subprocess.run(f"python3 {services.__file__} > {f.name} && clang++ {f.name} -std=c++11", shell=True).returncode + assert ret == 0, "generated services header is not valid C" diff --git a/openpilot/cereal/messaging/tests/validate_sp_cereal_upstream.py b/openpilot/cereal/messaging/tests/validate_sp_cereal_upstream.py new file mode 100755 index 0000000000..543b8b1b3e --- /dev/null +++ b/openpilot/cereal/messaging/tests/validate_sp_cereal_upstream.py @@ -0,0 +1,165 @@ +#!/usr/bin/env python3 +"""Validate sunnypilot routes are parseable by stock commaai/openpilot. + +Cap'n Proto is wire-compatible across renames, type relocations, and +additive fields. The only breaking change is a union variant that +upstream doesn't recognize — an unknown discriminant makes the entire +union unreadable. + +This script checks: for every struct with a union that exists in both +schemas, does sunnypilot introduce union variants upstream doesn't have? +""" + +from __future__ import annotations + +import argparse +import json +import os +import sys +from typing import Any + +NO_DISCRIMINANT = 0xFFFF + + +def hex_id(value: int) -> str: + return f"0x{value:016x}" + + +def encode_struct(schema: Any) -> dict: + node = schema.node + fields = [] + for name, field in schema.fields.items(): + proto = field.proto + ordinal = proto.ordinal.explicit if proto.ordinal.which() == "explicit" else None + discriminant = proto.discriminantValue if proto.discriminantValue != NO_DISCRIMINANT else None + fields.append({"name": name, "ordinal": ordinal, "discriminant": discriminant}) + return { + "typeId": hex_id(node.id), + "displayName": node.displayName, + "hasUnion": node.struct.discriminantCount > 0, + "fields": fields, + } + + +def _child_struct_schema(field: Any) -> Any: + proto = field.proto + if proto.which() == "group": + return field.schema + type_node = proto.slot.type + which = type_node.which() + if which == "struct": + return field.schema + if which == "list": + container = field.schema + element_type = type_node.list.elementType + while element_type.which() == "list": + container = container.elementType + element_type = element_type.list.elementType + if element_type.which() == "struct": + return container.elementType + return None + + +def collect_schema(root: Any) -> dict[str, dict]: + structs: dict[str, dict] = {} + stack = [root] + while stack: + schema = stack.pop() + type_id = hex_id(schema.node.id) + if type_id in structs: + continue + structs[type_id] = encode_struct(schema) + for _name, field in schema.fields.items(): + try: + child = _child_struct_schema(field) + except Exception: + child = None + if child is not None: + stack.append(child) + return structs + + +def load_log(cereal_dir: str, extra_imports: list[str] | None = None) -> Any: + import capnp + cereal_dir = os.path.abspath(cereal_dir) + capnp.remove_import_hook() + imports = [cereal_dir] + [os.path.abspath(p) for p in (extra_imports or [])] + return capnp.load(os.path.join(cereal_dir, "log.capnp"), imports=imports) + + +def dump_schema(cereal_dir: str, path: str, extra_imports: list[str] | None = None) -> None: + log = load_log(cereal_dir, extra_imports) + payload = { + "root": hex_id(log.Event.schema.node.id), + "structs": collect_schema(log.Event.schema), + } + with open(path, "w", encoding="utf-8") as handle: + json.dump(payload, handle, indent=2, sort_keys=True) + print(f"wrote schema dump with {len(payload['structs'])} structs to {path}") + + +def compare(sunnypilot_dump: dict, upstream_dump: dict) -> list[str]: + violations: list[str] = [] + sunnypilot_structs = sunnypilot_dump["structs"] + upstream_structs = upstream_dump["structs"] + + for type_id, sp_struct in sunnypilot_structs.items(): + if not sp_struct["hasUnion"]: + continue + up_struct = upstream_structs.get(type_id) + if up_struct is None: + continue + + up_ordinals = {f["ordinal"] for f in up_struct["fields"] if f.get("discriminant") is not None} + display = sp_struct["displayName"] + + for field in sp_struct["fields"]: + if field.get("discriminant") is None: + continue + if field["ordinal"] not in up_ordinals: + violations.append( + f"{display} @{field['ordinal']} '{field['name']}': " + f"union variant not present upstream (discriminant={field['discriminant']})" + ) + + return violations + + +def run_read(cereal_dir: str, peer_path: str, extra_imports: list[str] | None = None) -> int: + log = load_log(cereal_dir, extra_imports) + with open(peer_path, "r", encoding="utf-8") as f: + peer_dump = json.load(f) + local_dump = { + "root": hex_id(log.Event.schema.node.id), + "structs": collect_schema(log.Event.schema), + } + violations = compare(sunnypilot_dump=peer_dump, upstream_dump=local_dump) + + if not violations: + print("cereal compat OK: upstream can parse sunnypilot routes.") + return 0 + + print(f"cereal compat FAIL ({len(violations)} leaked union variant(s)):") + for v in violations: + print(f" {v}") + return 1 + + +def main() -> int: + parser = argparse.ArgumentParser(description="sunnypilot cereal upstream compat check") + mode = parser.add_mutually_exclusive_group(required=True) + mode.add_argument("-g", "--generate", action="store_true", help="dump local schema to JSON") + mode.add_argument("-r", "--read", action="store_true", help="validate against peer schema") + parser.add_argument("-f", "--file", default="schema.json", help="JSON file path") + parser.add_argument("--cereal-dir", required=True, help="path to cereal directory") + parser.add_argument("-I", "--import-path", action="append", default=[], help="extra capnp import paths") + args = parser.parse_args() + + if args.generate: + dump_schema(args.cereal_dir, args.file, args.import_path) + return 0 + return run_read(args.cereal_dir, args.file, args.import_path) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/openpilot/cereal/services.py b/openpilot/cereal/services.py new file mode 100755 index 0000000000..88931b480d --- /dev/null +++ b/openpilot/cereal/services.py @@ -0,0 +1,135 @@ +#!/usr/bin/env python3 +from enum import IntEnum + + +# TODO: this should be automatically determined using the capnp schema +class QueueSize(IntEnum): + BIG = 10 * 1024 * 1024 # 10MB - video frames, large AI outputs + MEDIUM = 2 * 1024 * 1024 # 2MB - high freq (CAN), livestream + SMALL = 250 * 1024 # 250KB - most services + + +class Service: + def __init__(self, should_log: bool, frequency: float, decimation: int | None = None, + queue_size: QueueSize = QueueSize.SMALL): + self.should_log = should_log + self.frequency = frequency + self.decimation = decimation + self.queue_size = queue_size + + +_services: dict[str, tuple] = { + # service: (should_log, frequency, qlog decimation (optional)) + # note: the "EncodeIdx" packets will still be in the log + "gyroscope": (True, 104., 104), + "accelerometer": (True, 104., 104), + "temperatureSensor": (True, 2., 200), + "deviceState": (True, 2., 1), + "touch": (True, 20., 1), + "can": (True, 100., 2053, QueueSize.BIG), # decimation gives ~3 msgs in a full segment + "controlsState": (True, 100., 10, QueueSize.MEDIUM), + "selfdriveState": (True, 100., 10), + "pandaStates": (True, 10., 1), + "peripheralState": (True, 2., 1), + "radarState": (True, 20., 5), + "roadEncodeIdx": (False, 20., 1), + "liveTracks": (True, 20.), + "sendcan": (True, 100., 139, QueueSize.MEDIUM), + "logMessage": (True, 0., None, QueueSize.BIG), + "errorLogMessage": (True, 0., 1, QueueSize.BIG), + "liveCalibration": (True, 4., 4), + "liveTorqueParameters": (True, 4., 1), + "liveDelay": (True, 4., 1), + "operatingSystemLog": (True, 0.), + "carState": (True, 100., 10), + "carControl": (True, 100., 10), + "carOutput": (True, 100., 10), + "longitudinalPlan": (True, 20., 10), + "lateralManeuverPlan": (True, 20.), + "driverAssistance": (True, 20., 20), + "procLog": (True, 0.5, 15, QueueSize.BIG), + "gpsLocationExternal": (True, 10., 10), + "gpsLocation": (True, 1., 1), + "ubloxGnss": (True, 10.), + "qcomGnss": (True, 2.), + "clocks": (True, 0.1, 1), + "ubloxRaw": (True, 20.), + "livePose": (True, 20., 4), + "liveParameters": (True, 20., 5), + "cameraOdometry": (True, 20., 10), + "thumbnail": (True, 1 / 60., 1), + "onroadEvents": (True, 1., 1), + "carParams": (True, 0.02, 1), + "roadCameraState": (True, 20., 20), + "driverCameraState": (True, 20., 20), + "driverEncodeIdx": (False, 20., 1), + "driverStateV2": (True, 20., 10), + "driverMonitoringState": (True, 20., 10), + "wideRoadEncodeIdx": (False, 20., 1), + "wideRoadCameraState": (True, 20., 20), + "drivingModelData": (True, 20., 10), + "modelV2": (True, 20., None, QueueSize.BIG), + "managerState": (True, 2., 1), + "qRoadEncodeIdx": (False, 20.), + "userBookmark": (True, 0., 1), + "soundPressure": (True, 10., 10), + "rawAudioData": (False, 20.), + "bookmarkButton": (True, 0., 1), + "audioFeedback": (True, 0., 1), + "roadEncodeData": (False, 20., None, QueueSize.BIG), + "driverEncodeData": (False, 20., None, QueueSize.BIG), + "wideRoadEncodeData": (False, 20., None, QueueSize.BIG), + "qRoadEncodeData": (False, 20., None, QueueSize.BIG), + + # sunnypilot + "modelManagerSP": (False, 1., 1, QueueSize.BIG), + "backupManagerSP": (False, 1., 1, QueueSize.BIG), + "selfdriveStateSP": (True, 100., 10), + "longitudinalPlanSP": (True, 20., 10), + "onroadEventsSP": (True, 1., 1), + "carParamsSP": (True, 0.02, 1), + "carControlSP": (True, 100., 10), + "carStateSP": (True, 100., 10), + "liveMapDataSP": (True, 1., 1), + "modelDataV2SP": (True, 20., None, QueueSize.BIG), + "liveLocationKalman": (True, 20.), + + # debug + "uiDebug": (True, 0., 1), + "testJoystick": (True, 0.), + "alertDebug": (True, 20., 5), + "livestreamWideRoadEncodeIdx": (False, 20.), + "livestreamRoadEncodeIdx": (False, 20.), + "livestreamDriverEncodeIdx": (False, 20.), + "livestreamWideRoadEncodeData": (False, 20., None, QueueSize.MEDIUM), + "livestreamRoadEncodeData": (False, 20., None, QueueSize.MEDIUM), + "livestreamDriverEncodeData": (False, 20., None, QueueSize.MEDIUM), + "customReservedRawData0": (True, 0.), +} +SERVICE_LIST = {name: Service(*vals) for + idx, (name, vals) in enumerate(_services.items())} + + +def build_header(): + h = "" + h += "/* THIS IS AN AUTOGENERATED FILE, PLEASE EDIT services.py */\n" + h += "#ifndef __SERVICES_H\n" + h += "#define __SERVICES_H\n" + + h += "#include \n" + h += "#include \n" + + h += "struct service { std::string name; bool should_log; float frequency; int decimation; size_t queue_size; };\n" + h += "static std::map services = {\n" + for k, v in SERVICE_LIST.items(): + should_log = "true" if v.should_log else "false" + decimation = -1 if v.decimation is None else v.decimation + h += f' {{ "{k}", {{"{k}", {should_log}, {v.frequency:f}, {decimation:d}, {v.queue_size:d}}}}},\n' + h += "};\n" + + h += "#endif\n" + return h + + +if __name__ == "__main__": + print(build_header()) diff --git a/openpilot/common b/openpilot/common deleted file mode 120000 index 60d3b0a6a8..0000000000 --- a/openpilot/common +++ /dev/null @@ -1 +0,0 @@ -../common \ No newline at end of file diff --git a/openpilot/common/SConscript b/openpilot/common/SConscript new file mode 100644 index 0000000000..13935b80d5 --- /dev/null +++ b/openpilot/common/SConscript @@ -0,0 +1,24 @@ +Import('env', 'envCython') + +common_libs = [ + 'params.cc', + 'swaglog.cc', + 'util.cc', + 'ratekeeper.cc', + 'yuv.cc', +] + +_common = env.Library('common', common_libs, LIBS="json11") +Export('_common') + +if GetOption('extras'): + env.Program('tests/test_common', + ['tests/test_runner.cc', 'tests/test_util.cc', 'tests/test_swaglog.cc'], + LIBS=[_common, 'json11', 'zmq', 'pthread']) + +# Cython bindings +params_python = envCython.Program('params_pyx.so', 'params_pyx.pyx', LIBS=envCython['LIBS'] + [_common, 'zmq', 'json11']) + +common_python = [params_python] + +Export('common_python') diff --git a/common/__init__.py b/openpilot/common/__init__.py similarity index 100% rename from common/__init__.py rename to openpilot/common/__init__.py diff --git a/openpilot/common/api/__init__.py b/openpilot/common/api/__init__.py new file mode 100644 index 0000000000..45c73e2a05 --- /dev/null +++ b/openpilot/common/api/__init__.py @@ -0,0 +1,26 @@ +from openpilot.common.api.comma_connect import CommaConnectApi + + +class Api: + def __init__(self, dongle_id): + self.service = CommaConnectApi(dongle_id) + + def request(self, method, endpoint, **params): + return self.service.request(method, endpoint, **params) + + def get(self, *args, **kwargs): + return self.service.get(*args, **kwargs) + + def post(self, *args, **kwargs): + return self.service.post(*args, **kwargs) + + def get_token(self, payload_extra=None, expiry_hours=1): + return self.service.get_token(payload_extra, expiry_hours) + + +def api_get(endpoint, method='GET', timeout=None, access_token=None, session=None, **params): + return CommaConnectApi(None).api_get(endpoint, method, timeout, access_token, session, **params) + + +def get_key_pair() -> tuple[str, str, str] | tuple[None, None, None]: + return CommaConnectApi(None).get_key_pair() diff --git a/openpilot/common/api/base.py b/openpilot/common/api/base.py new file mode 100644 index 0000000000..32dd5a1ed7 --- /dev/null +++ b/openpilot/common/api/base.py @@ -0,0 +1,73 @@ +import jwt +import os +import requests +import unicodedata +from datetime import datetime, timedelta, UTC +from openpilot.common.hardware.hw import Paths +from openpilot.common.version import get_version + +# name: jwt signature algorithm +KEYS = {"id_rsa": "RS256", + "id_ecdsa": "ES256"} + + +class BaseApi: + def __init__(self, dongle_id, api_host, user_agent="openpilot-"): + self.dongle_id = dongle_id + self.api_host = api_host + self.user_agent = user_agent + self.jwt_algorithm, self.private_key, _ = self.get_key_pair() + + def get(self, *args, **kwargs): + return self.request('GET', *args, **kwargs) + + def post(self, *args, **kwargs): + return self.request('POST', *args, **kwargs) + + def request(self, method, endpoint, timeout=None, access_token=None, **params): + return self.api_get(endpoint, method=method, timeout=timeout, access_token=access_token, **params) + + def _get_token(self, payload_extra=None, expiry_hours=1, **extra_payload): + now = datetime.now(UTC).replace(tzinfo=None) + payload = { + 'identity': self.dongle_id, + 'nbf': now, + 'iat': now, + 'exp': now + timedelta(hours=expiry_hours), + **extra_payload + } + if payload_extra is not None: + payload.update(payload_extra) + assert self.private_key is not None + token = jwt.encode(payload, self.private_key, algorithm=self.jwt_algorithm) + if isinstance(token, bytes): + token = token.decode('utf8') + return token + + def get_token(self, payload_extra=None, expiry_hours=1): + return self._get_token(payload_extra, expiry_hours) + + def remove_non_ascii_chars(self, text): + normalized_text = unicodedata.normalize('NFD', text) + ascii_encoded_text = normalized_text.encode('ascii', 'ignore') + return ascii_encoded_text.decode() + + def api_get(self, endpoint, method='GET', timeout=None, access_token=None, session=None, json=None, **params): + headers = {} + if access_token is not None: + headers['Authorization'] = "JWT " + access_token + + version = self.remove_non_ascii_chars(get_version()) + headers['User-Agent'] = self.user_agent + version + + # TODO: add session to Api + req = requests if session is None else session + return req.request(method, f"{self.api_host}/{endpoint}", timeout=timeout, headers=headers, json=json, params=params) + + @staticmethod + def get_key_pair() -> tuple[str, str, str] | tuple[None, None, None]: + for key in KEYS: + if os.path.isfile(Paths.persist_root() + f'/comma/{key}') and os.path.isfile(Paths.persist_root() + f'/comma/{key}.pub'): + with open(Paths.persist_root() + f'/comma/{key}') as private, open(Paths.persist_root() + f'/comma/{key}.pub') as public: + return KEYS[key], private.read(), public.read() + return None, None, None diff --git a/common/api/comma_connect.py b/openpilot/common/api/comma_connect.py similarity index 100% rename from common/api/comma_connect.py rename to openpilot/common/api/comma_connect.py diff --git a/openpilot/common/basedir.py b/openpilot/common/basedir.py new file mode 100644 index 0000000000..49b092d930 --- /dev/null +++ b/openpilot/common/basedir.py @@ -0,0 +1,4 @@ +import os + + +BASEDIR = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "../..")) diff --git a/openpilot/common/constants.py b/openpilot/common/constants.py new file mode 100644 index 0000000000..7ca425c4b2 --- /dev/null +++ b/openpilot/common/constants.py @@ -0,0 +1,23 @@ +import numpy as np + +# conversions +class CV: + # Speed + MPH_TO_KPH = 1.609344 + KPH_TO_MPH = 1. / MPH_TO_KPH + MS_TO_KPH = 3.6 + KPH_TO_MS = 1. / MS_TO_KPH + MS_TO_MPH = MS_TO_KPH * KPH_TO_MPH + MPH_TO_MS = MPH_TO_KPH * KPH_TO_MS + MS_TO_KNOTS = 1.9438 + KNOTS_TO_MS = 1. / MS_TO_KNOTS + + # Angle + DEG_TO_RAD = np.pi / 180. + RAD_TO_DEG = 1. / DEG_TO_RAD + + # Mass + LB_TO_KG = 0.453592 + + +ACCELERATION_DUE_TO_GRAVITY = 9.81 # m/s^2 diff --git a/openpilot/common/esim/__init__.py b/openpilot/common/esim/__init__.py new file mode 100644 index 0000000000..5f83412c07 --- /dev/null +++ b/openpilot/common/esim/__init__.py @@ -0,0 +1,3 @@ +from openpilot.common.esim.base import LPABase, LPAError, LPAProfileNotFoundError, Profile + +__all__ = ["LPABase", "LPAError", "LPAProfileNotFoundError", "Profile"] diff --git a/openpilot/common/esim/base.py b/openpilot/common/esim/base.py new file mode 100644 index 0000000000..b783a630b2 --- /dev/null +++ b/openpilot/common/esim/base.py @@ -0,0 +1,55 @@ +from abc import ABC, abstractmethod +from dataclasses import dataclass + + +class LPAError(RuntimeError): + pass + + +class LPAProfileNotFoundError(LPAError): + pass + + +@dataclass +class Profile: + iccid: str + nickname: str + enabled: bool + provider: str + + @property + def is_comma(self) -> bool: + return self.provider == 'Webbing' and self.iccid.startswith('8985235') + + +class LPABase(ABC): + @abstractmethod + def list_profiles(self) -> list[Profile]: + pass + + @abstractmethod + def get_active_profile(self) -> Profile | None: + pass + + @abstractmethod + def delete_profile(self, iccid: str) -> None: + pass + + @abstractmethod + def download_profile(self, qr: str, nickname: str | None = None) -> None: + pass + + @abstractmethod + def nickname_profile(self, iccid: str, nickname: str) -> None: + pass + + @abstractmethod + def switch_profile(self, iccid: str) -> None: + pass + + def process_notifications(self) -> None: + pass + + @abstractmethod + def is_euicc(self) -> bool: + pass diff --git a/openpilot/common/esim/esim.py b/openpilot/common/esim/esim.py new file mode 100755 index 0000000000..8456d4dd47 --- /dev/null +++ b/openpilot/common/esim/esim.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 + +import argparse +from openpilot.common.hardware import HARDWARE +from openpilot.common.esim.base import LPABase, Profile + + +def sorted_profiles(lpa: LPABase) -> list[Profile]: + return sorted(lpa.list_profiles(), key=lambda p: p.iccid) + + +def resolve_iccid(lpa: LPABase, ref: str) -> str: + # ref is either a 1-based index into the sorted list, or a literal iccid + if ref.isdigit(): + profiles = sorted_profiles(lpa) + idx = int(ref) - 1 + if not 0 <= idx < len(profiles): + raise SystemExit(f'no profile at index {ref} (have {len(profiles)})') + return profiles[idx].iccid + return ref + + +def print_profiles(lpa: LPABase) -> None: + profiles = sorted_profiles(lpa) + print(f'\n{len(profiles)} profile{"s" if len(profiles) != 1 else ""}:') + for i, p in enumerate(profiles, start=1): + print(f'{i}. {p.iccid} (nickname: {p.nickname or ""}) (provider: {p.provider}) - {"enabled" if p.enabled else "disabled"}') + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(prog='esim.py', description='manage eSIM profiles on your comma device', epilog='comma.ai') + sub = parser.add_subparsers(dest='cmd') + + sub.add_parser('list', help='list profiles') + + p_switch = sub.add_parser('switch', help='switch to profile') + p_switch.add_argument('profile', help='iccid or 1-based index from `list`') + + p_delete = sub.add_parser('delete', help='delete profile (warning: this cannot be undone)') + p_delete.add_argument('profile', help='iccid or 1-based index from `list`') + + p_download = sub.add_parser('download', help='download a profile using QR code (format: LPA:1$rsp.truphone.com$QRF-SPEEDTEST)') + p_download.add_argument('qr') + p_download.add_argument('name') + + p_nickname = sub.add_parser('nickname', help='update the nickname for a profile') + p_nickname.add_argument('profile', help='iccid or 1-based index from `list`') + p_nickname.add_argument('name') + + args = parser.parse_args() + + lpa = HARDWARE.get_sim_lpa() + if args.cmd == 'switch': + lpa.switch_profile(resolve_iccid(lpa, args.profile)) + elif args.cmd == 'delete': + iccid = resolve_iccid(lpa, args.profile) + confirm = input(f'are you sure you want to delete profile {iccid}? (y/N) ') + if confirm == 'y': + lpa.delete_profile(iccid) + else: + print('cancelled') + exit(0) + elif args.cmd == 'download': + lpa.download_profile(args.qr, args.name) + elif args.cmd == 'nickname': + lpa.nickname_profile(resolve_iccid(lpa, args.profile), args.name) + else: + if args.cmd is None: + parser.print_help() + print_profiles(lpa) diff --git a/openpilot/common/esim/gsma_ci_bundle.pem b/openpilot/common/esim/gsma_ci_bundle.pem new file mode 100644 index 0000000000..3ee7fd1252 --- /dev/null +++ b/openpilot/common/esim/gsma_ci_bundle.pem @@ -0,0 +1,133 @@ +# GSMA Certificate Issuer (CI) bundle for eSIM RSP +# Source: https://euicc-manual.osmocom.org/docs/pki/ci/bundle.pem + +issuer= + countryName = CH + organizationName = OISTE Foundation + commonName = OISTE GSMA CI G1 +notBefore=2024-01-16 23:17:39Z +notAfter=2059-01-07 23:17:38Z +-----BEGIN CERTIFICATE----- +MIIB9zCCAZ2gAwIBAgIUSpBSCCDYPOEG/IFHUCKpZ2pIAQMwCgYIKoZIzj0EAwIw +QzELMAkGA1UEBhMCQ0gxGTAXBgNVBAoMEE9JU1RFIEZvdW5kYXRpb24xGTAXBgNV +BAMMEE9JU1RFIEdTTUEgQ0kgRzEwIBcNMjQwMTE2MjMxNzM5WhgPMjA1OTAxMDcy +MzE3MzhaMEMxCzAJBgNVBAYTAkNIMRkwFwYDVQQKDBBPSVNURSBGb3VuZGF0aW9u +MRkwFwYDVQQDDBBPSVNURSBHU01BIENJIEcxMFkwEwYHKoZIzj0CAQYIKoZIzj0D +AQcDQgAEvZ3s3PFC4NgrCcCMmHJ6DJ66uzAHuLcvjJnOn+TtBNThS7YHLDyHCa2v +7D+zTP+XTtgqgcLoB56Gha9EQQQ4xKNtMGswDwYDVR0TAQH/BAUwAwEB/zAQBgNV +HREECTAHiAVghXQFDjAXBgNVHSABAf8EDTALMAkGB2eBEgECAQAwHQYDVR0OBBYE +FEwnlnrSDBSzkelgHkHmBK1XwCIvMA4GA1UdDwEB/wQEAwIBBjAKBggqhkjOPQQD +AgNIADBFAiBVcywTj017jKpAQ+gwy4MqK2hQvzve6lkvQkgSP6ykHwIhAI0KFwCD +jnPbmcJsG41hUrWNlf+IcrMvFuYii0DasBNi +-----END CERTIFICATE----- +issuer= + organizationName = GSM Association + commonName = GSM Association - RSP2 Root CI1 +notBefore=2017-02-22 00:00:00Z +notAfter=2052-02-21 23:59:59Z +-----BEGIN CERTIFICATE----- +MIICSTCCAe+gAwIBAgIQbmhWeneg7nyF7hg5Y9+qejAKBggqhkjOPQQDAjBEMRgw +FgYDVQQKEw9HU00gQXNzb2NpYXRpb24xKDAmBgNVBAMTH0dTTSBBc3NvY2lhdGlv +biAtIFJTUDIgUm9vdCBDSTEwIBcNMTcwMjIyMDAwMDAwWhgPMjA1MjAyMjEyMzU5 +NTlaMEQxGDAWBgNVBAoTD0dTTSBBc3NvY2lhdGlvbjEoMCYGA1UEAxMfR1NNIEFz +c29jaWF0aW9uIC0gUlNQMiBSb290IENJMTBZMBMGByqGSM49AgEGCCqGSM49AwEH +A0IABJ1qutL0HCMX52GJ6/jeibsAqZfULWj/X10p/Min6seZN+hf5llovbCNuB2n +unLz+O8UD0SUCBUVo8e6n9X1TuajgcAwgb0wDgYDVR0PAQH/BAQDAgEGMA8GA1Ud +EwEB/wQFMAMBAf8wEwYDVR0RBAwwCogIKwYBBAGC6WAwFwYDVR0gAQH/BA0wCzAJ +BgdngRIBAgEAME0GA1UdHwRGMEQwQqBAoD6GPGh0dHA6Ly9nc21hLWNybC5zeW1h +dXRoLmNvbS9vZmZsaW5lY2EvZ3NtYS1yc3AyLXJvb3QtY2kxLmNybDAdBgNVHQ4E +FgQUgTcPUSXQsdQI1MOyMubSXnlb6/swCgYIKoZIzj0EAwIDSAAwRQIgIJdYsOMF +WziPK7l8nh5mu0qiRiVf25oa9ullG/OIASwCIQDqCmDrYf+GziHXBOiwJwnBaeBO +aFsiLzIEOaUuZwdNUw== +-----END CERTIFICATE----- +issuer= + countryName = US + organizationName = Entrust, Inc. + organizationalUnitName = See www.entrust.net/legal-terms + organizationalUnitName = (c) 2016 Entrust, Inc. - for authorized use only + commonName = Entrust eSIM Certification Authority +notBefore=2016-11-16 16:04:02Z +notAfter=2051-10-16 16:34:02Z +-----BEGIN CERTIFICATE----- +MIIC6DCCAo2gAwIBAgIRAIy4GT7M5nHsAAAAAFgsinowCgYIKoZIzj0EAwIwgbkx +CzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1FbnRydXN0LCBJbmMuMSgwJgYDVQQLEx9T +ZWUgd3d3LmVudHJ1c3QubmV0L2xlZ2FsLXRlcm1zMTkwNwYDVQQLEzAoYykgMjAx +NiBFbnRydXN0LCBJbmMuIC0gZm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxLTArBgNV +BAMTJEVudHJ1c3QgZVNJTSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAgFw0xNjEx +MTYxNjA0MDJaGA8yMDUxMTAxNjE2MzQwMlowgbkxCzAJBgNVBAYTAlVTMRYwFAYD +VQQKEw1FbnRydXN0LCBJbmMuMSgwJgYDVQQLEx9TZWUgd3d3LmVudHJ1c3QubmV0 +L2xlZ2FsLXRlcm1zMTkwNwYDVQQLEzAoYykgMjAxNiBFbnRydXN0LCBJbmMuIC0g +Zm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxLTArBgNVBAMTJEVudHJ1c3QgZVNJTSBD +ZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IA +BAdzwGHeQ1Wb2f4DmHTByR5/IWL3JugQ1U3908a++bHdlt+TTA7K4c5cYZ+51Yz/ +hg/bacxguPDh9uQUK6Wg3a6jcjBwMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/ +BAQDAgEGMBcGA1UdIAEB/wQNMAswCQYHZ4ESAQIBADAVBgNVHREEDjAMiApghkgB +hvpsFAoAMB0GA1UdDgQWBBQWcEt/NR42B/GMS3AAXDoAPf1BSjAKBggqhkjOPQQD +AgNJADBGAiEAspjXMvaBZyAg86Z0AAtT0yBRAi1EyaAfNz9kDJeAE04CIQC3efj8 +ATL7/tDBOhANy3cK8PS/1NIlu9vqMLCZsZvJ0Q== +-----END CERTIFICATE----- +issuer= + countryName = FR + organizationName = OBERTHUR TECHNOLOGIES + organizationalUnitName = TELECOM + commonName = MC4 OT ROOT CI v1 +notBefore=2016-11-15 00:00:01Z +notAfter=2046-11-08 23:59:59Z +-----BEGIN CERTIFICATE----- +MIICOjCCAeGgAwIBAgIBATAKBggqhkjOPQQDAjBbMQswCQYDVQQGEwJGUjEeMBwG +A1UEChMVT0JFUlRIVVIgVEVDSE5PTE9HSUVTMRAwDgYDVQQLEwdURUxFQ09NMRow +GAYDVQQDExFNQzQgT1QgUk9PVCBDSSB2MTAeFw0xNjExMTUwMDAwMDFaFw00NjEx +MDgyMzU5NTlaMFsxCzAJBgNVBAYTAkZSMR4wHAYDVQQKExVPQkVSVEhVUiBURUNI +Tk9MT0dJRVMxEDAOBgNVBAsTB1RFTEVDT00xGjAYBgNVBAMTEU1DNCBPVCBST09U +IENJIHYxMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEHb/Gajt3OZxuaDSklBQE +D4lOd6PGPLSvtfkM952ubdyy45tJwAeA0eEii0CLrFT6tcfXkW+H/5mQyMRXaAUk +T6OBlTCBkjAfBgNVHSMEGDAWgBTNbmC3LXoGPLyEYluR6A/jBAbhPjAdBgNVHQ4E +FgQUzW5gty16Bjy8hGJbkegP4wQG4T4wDgYDVR0PAQH/BAQDAgAGMBcGA1UdIAEB +/wQNMAswCQYHZ4ESAQIBADAWBgNVHREEDzANiAsrBgEEAYHvb7OITTAPBgNVHRMB +Af8EBTADAQH/MAoGCCqGSM49BAMCA0cAMEQCIEw4Nc7f2fDtoH+6ON/bknfDQxmT +ikThXjhpLtSrSKN2AiAxHxgC87L0FDnH8dJNlkdGX9c0JIx6oLheIplfS6k+jg== +-----END CERTIFICATE----- +issuer= + commonName = SubMan V4.2 CI Google Pixel + organizationName = Giesecke and Devrient GmbH + organizationalUnitName = Mobile Security + countryName = DE +notBefore=2017-05-10 00:00:00Z +notAfter=2027-05-10 00:00:00Z +-----BEGIN CERTIFICATE----- +MIICaTCCAg6gAwIBAgICASwwCgYIKoZIzj0EAwIwczElMCMGA1UEAxMcIFN1Yk1h +biBWNC4yIENJIEdvb2dsZSBQaXhlbDEjMCEGA1UEChMaR2llc2Vja2UgYW5kIERl +dnJpZW50IEdtYkgxGDAWBgNVBAsTD01vYmlsZSBTZWN1cml0eTELMAkGA1UEBhMC +REUwHhcNMTcwNTEwMDAwMDAwWhcNMjcwNTEwMDAwMDAwWjBzMSUwIwYDVQQDExwg +U3ViTWFuIFY0LjIgQ0kgR29vZ2xlIFBpeGVsMSMwIQYDVQQKExpHaWVzZWNrZSBh +bmQgRGV2cmllbnQgR21iSDEYMBYGA1UECxMPTW9iaWxlIFNlY3VyaXR5MQswCQYD +VQQGEwJERTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABHNorfaJsGzqWNawyAhl +IAv9QL2/+b9RsUoso06t/dKX1MRr5CUJ51acvv5TAFhQKIml+dwLbFnV5aO+8W6Z +wxajgZEwgY4wHwYDVR0jBBgwFoAUtg8LiX/WMLiM/tYWH46oCMU4KsMwHQYDVR0O +BBYEFLYPC4l/1jC4jP7WFh+OqAjFOCrDMA4GA1UdDwEB/wQEAwIBBjAXBgNVHSAB +Af8EDTALMAkGB2eBEgECAQAwDwYDVR0TAQH/BAUwAwEB/zASBgNVHREECzAJiAcr +BgEEAdwPMAoGCCqGSM49BAMCA0kAMEYCIQDpoZcuAQrjATW8U+AWqMUJ0dY6nWW1 +R1QmFzVZ1yMXSwIhALCvRqkCtgiavdeFeSgsSNbY5Fhd+QoCltuSh1U4TE7A +-----END CERTIFICATE----- +issuer= + countryName = DE + commonName = SubMan V4.2 CI + organizationName = Giesecke and Devrient + organizationalUnitName = Mobile Security +notBefore=2016-08-12 13:51:48Z +notAfter=2026-08-12 13:51:48Z +-----BEGIN CERTIFICATE----- +MIICUjCCAfigAwIBAgIDQgAAMAoGCCqGSM49BAMCMGAxCzAJBgNVBAYTAkRFMRcw +FQYDVQQDEw5TdWJNYW4gVjQuMiBDSTEeMBwGA1UEChMVR2llc2Vja2UgYW5kIERl +dnJpZW50MRgwFgYDVQQLEw9Nb2JpbGUgU2VjdXJpdHkwHhcNMTYwODEyMTM1MTQ4 +WhcNMjYwODEyMTM1MTQ4WjBgMQswCQYDVQQGEwJERTEXMBUGA1UEAxMOU3ViTWFu +IFY0LjIgQ0kxHjAcBgNVBAoTFUdpZXNlY2tlIGFuZCBEZXZyaWVudDEYMBYGA1UE +CxMPTW9iaWxlIFNlY3VyaXR5MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEYIgl +VQr9wbXOlwPp8qMg5Df08Cli9Mc+lpr3Lwa9PlVA3QWlLeX4GfD4H3phLBqVIa17 +yHttmtheTxi0KoEqhKOBoDCBnTAdBgNVHQ4EFgQU6lOt7zMpuVCa/XVf1Ei4LcG8 +7P8wDgYDVR0PAQH/BAQDAgEGMBcGA1UdIAEB/wQNMAswCQYHZ4ESAQIBADAPBgNV +HRMBAf8EBTADAQH/MBIGA1UdEQQLMAmIBysGAQQB3A8wLgYDVR0fBCcwJTAjoCGg +H4YdaHR0cDovL2dpLWRlLmNvbS90ZXN0LmNybC5wZW0wCgYIKoZIzj0EAwIDSAAw +RQIhAMMx2L/VHDiOW+Fl/OuFmhCdizYM17Yn9zAVieKO2T0iAiANWtCMmY+DzkqK +yHxBFX0U2tBd682zP4DpgRt8j3Ylew== +-----END CERTIFICATE----- diff --git a/openpilot/common/esim/lpa.py b/openpilot/common/esim/lpa.py new file mode 100644 index 0000000000..80138b54ae --- /dev/null +++ b/openpilot/common/esim/lpa.py @@ -0,0 +1,791 @@ +# SGP.22 v2.3: https://www.gsma.com/solutions-and-impact/technologies/esim/wp-content/uploads/2021/07/SGP.22-v2.3.pdf + +import atexit +import base64 +import fcntl +import hashlib +import os +import requests +import subprocess +import sys +import termios +import time + +from collections.abc import Callable, Generator +from contextlib import contextmanager +from typing import Any + +from pathlib import Path + +from openpilot.common.time_helpers import system_time_valid +from openpilot.common.esim.base import LPABase, LPAError, LPAProfileNotFoundError, Profile +from openpilot.common.serial import Serial, SerialException + +GSMA_CI_BUNDLE = str(Path(__file__).parent / "gsma_ci_bundle.pem") + +DEFAULT_DEVICE = "/dev/modem_at0" +DEFAULT_BAUD = 9600 +DEFAULT_TIMEOUT = 5.0 +# https://euicc-manual.osmocom.org/docs/lpa/applet-id/ +ISDR_AID = "A0000005591010FFFFFFFF8900000100" +ES10X_MSS = 120 +HTTP_TIMEOUT = 30 +OPEN_ISDR_RETRIES = 10 +OPEN_ISDR_RETRY_DELAY_S = 0.25 +OPEN_ISDR_RESET_ATTEMPT = 5 +SEND_APDU_RETRIES = 3 +LOCK_FILE = '/dev/shm/modem.lock' +DEBUG = os.environ.get("DEBUG") == "1" + + +# TLV Tags +TAG_ICCID = 0x5A +TAG_STATUS = 0x80 +TAG_EUICC_INFO = 0xBF20 +TAG_PREPARE_DOWNLOAD = 0xBF21 +TAG_BPP_COMMAND = 0xBF23 +TAG_PROFILE_METADATA = 0xBF25 +TAG_INSTALL_RESULT_DATA = 0xBF27 +TAG_LIST_NOTIFICATION = 0xBF28 +TAG_SET_NICKNAME = 0xBF29 +TAG_RETRIEVE_NOTIFICATION = 0xBF2B +TAG_PROFILE_INFO_LIST = 0xBF2D +TAG_EUICC_CHALLENGE = 0xBF2E +TAG_NOTIFICATION_METADATA = 0xBF2F +TAG_NOTIFICATION_SENT = 0xBF30 +TAG_ENABLE_PROFILE = 0xBF31 +TAG_DELETE_PROFILE = 0xBF33 +TAG_BPP = 0xBF36 +TAG_PROFILE_INSTALL_RESULT = 0xBF37 +TAG_AUTH_SERVER = 0xBF38 +TAG_CANCEL_SESSION = 0xBF41 +TAG_OK = 0xA0 + +PROFILE_OK = 0x00 +PROFILE_NOT_IN_DISABLED_STATE = 0x02 +PROFILE_CAT_BUSY = 0x05 + +PROFILE_ERROR_CODES = { + 0x01: "iccidOrAidNotFound", PROFILE_NOT_IN_DISABLED_STATE: "profileNotInDisabledState", + 0x03: "disallowedByPolicy", 0x04: "wrongProfileReenabling", + PROFILE_CAT_BUSY: "catBusy", 0x06: "undefinedError", +} +AUTH_SERVER_ERROR_CODES = { + 0x01: "eUICCVerificationFailed", 0x02: "eUICCCertificateExpired", + 0x03: "eUICCCertificateRevoked", 0x05: "invalidServerSignature", + 0x06: "euiccCiPKUnknown", 0x0A: "matchingIdRefused", + 0x10: "insufficientMemory", +} +BPP_COMMAND_NAMES = { + 0: "initialiseSecureChannel", 1: "configureISDP", 2: "storeMetadata", + 3: "storeMetadata2", 4: "replaceSessionKeys", 5: "loadProfileElements", +} +BPP_ERROR_REASONS = { + 1: "incorrectInputValues", 2: "invalidSignature", 3: "invalidTransactionId", + 4: "unsupportedCrtValues", 5: "unsupportedRemoteOperationType", + 6: "unsupportedProfileClass", 7: "scp03tStructureError", 8: "scp03tSecurityError", + 9: "iccidAlreadyExistsOnEuicc", 10: "insufficientMemoryForProfile", + 11: "installInterrupted", 12: "peProcessingError", 13: "dataMismatch", + 14: "invalidNAA", +} +BPP_ERROR_MESSAGES = { + 9: "This eSIM profile is already installed on this device.", + 10: "Not enough memory on the eUICC to install this profile.", + 12: "Profile installation failed. The QR code may have already been used.", +} + +# SGP.22 §5.2.6 SM-DP+ reason/subject codes mapped to user-friendly messages +ES9P_ERROR_MESSAGES: dict[tuple[str, str], str] = { + ('3.8', '8.2.6'): "This eSIM profile is already installed on another device. Please use a new QR code.", + ('3.8', '8.2.1'): "This eSIM profile has expired. Please request a new QR code.", + ('3.8', '8.1'): "The SM-DP+ server refused this request.", + ('3.1', '8.2.6'): "This eSIM profile has been revoked by the carrier.", + ('3.9', '8.2.6'): "This eSIM profile download has already been completed.", + ('2.1', '8.8'): "The device is not compatible with this eSIM profile.", + ('1.2', '8.1'): "The SM-DP+ server is temporarily unavailable. Try again later.", +} + +NOTIFICATION_OPERATIONS = {0x80: "install", 0x40: "enable", 0x20: "disable", 0x10: "delete"} + +STATE_LABELS = {0: "disabled", 1: "enabled", 255: "unknown"} +ICON_LABELS = {0: "jpeg", 1: "png", 255: "unknown"} +CLASS_LABELS = {0: "test", 1: "provisioning", 2: "operational", 255: "unknown"} + +# TLV tag -> (field_name, decoder) +FieldMap = dict[int, tuple[str, Callable[[bytes], Any]]] + + +def b64e(data: bytes) -> str: + return base64.b64encode(data).decode("ascii") + + +def base64_trim(s: str) -> str: + return "".join(c for c in s if c not in "\n\r \t") + + +def b64d(s: str) -> bytes: + return base64.b64decode(base64_trim(s)) + + +class AtClient: + def __init__(self, device: str, baud: int, timeout: float) -> None: + self.channel: str | None = None + self._device = device + self._baud = baud + self._timeout = timeout + self._serial: Serial | None = None + + def send_raw(self, data: bytes) -> None: + self._ensure_serial() + self._serial.reset_input_buffer() + self._serial.write(data) + self._serial.flush() + + def close(self) -> None: + try: + if self.channel: + try: + self.query(f"AT+CCHC={self.channel}") + except (RuntimeError, TimeoutError): + pass + self.channel = None + finally: + if self._serial: + self._serial.close() + + def _send(self, cmd: str) -> None: + if DEBUG: + print(f"SER >> {cmd}", file=sys.stderr) + self._serial.write((cmd + "\r").encode("ascii")) + + def _expect(self) -> list[str]: + lines: list[str] = [] + while True: + raw = self._serial.readline() + if not raw: + raise TimeoutError("AT command timed out") + line = raw.decode(errors="ignore").strip() + if not line: + continue + if DEBUG: + print(f"SER << {line}", file=sys.stderr) + if line == "OK": + return lines + if line == "ERROR" or line.startswith("+CME ERROR"): + raise RuntimeError(f"AT command failed: {line}") + lines.append(line) + + def _ensure_serial(self, reconnect: bool = False) -> None: + if reconnect: + self.channel = None + try: + if self._serial: + self._serial.close() + except Exception: + pass + self._serial = None + if self._serial is None: + self._serial = Serial(self._device, baudrate=self._baud, timeout=self._timeout) + + def query(self, cmd: str) -> list[str]: + self._ensure_serial() + try: + self._send(cmd) + return self._expect() + except SerialException: + self._ensure_serial(reconnect=True) + self._send(cmd) + return self._expect() + + def _open_isdr_once(self) -> None: + if self.channel: + try: + self.query(f"AT+CCHC={self.channel}") + except RuntimeError: + pass + self.channel = None + # drain any unsolicited responses before opening + if self._serial: + try: + self._serial.reset_input_buffer() + except (OSError, SerialException, termios.error): + self._ensure_serial(reconnect=True) + for line in self.query(f'AT+CCHO="{ISDR_AID}"'): + if line.startswith("+CCHO:") and (ch := line.split(":", 1)[1].strip()): + self.channel = ch + return + raise RuntimeError("Failed to open ISD-R application") + + def _reset_modem(self) -> None: + if self._serial: + try: + self._serial.close() + except Exception: + pass + self._serial = None + subprocess.run(['/usr/comma/lte/lte.sh', 'start'], capture_output=True) + + def open_isdr(self) -> None: + for attempt in range(OPEN_ISDR_RETRIES): + try: + self._open_isdr_once() + return + except (RuntimeError, TimeoutError, termios.error, SerialException): + time.sleep(OPEN_ISDR_RETRY_DELAY_S) + if attempt == OPEN_ISDR_RESET_ATTEMPT: + self._reset_modem() + raise RuntimeError("Failed to open ISD-R after retries") + + def send_apdu(self, apdu: bytes) -> tuple[bytes, int, int]: + for attempt in range(SEND_APDU_RETRIES): + try: + if not self.channel: + self.open_isdr() + hex_payload = apdu.hex().upper() + for line in self.query(f'AT+CGLA={self.channel},{len(hex_payload)},"{hex_payload}"'): + if line.startswith("+CGLA:"): + parts = line.split(":", 1)[1].split(",", 1) + if len(parts) == 2: + data = bytes.fromhex(parts[1].strip().strip('"')) + if len(data) >= 2: + return data[:-2], data[-2], data[-1] + raise RuntimeError("Missing +CGLA response") + except (RuntimeError, ValueError): + self.channel = None + if attempt == SEND_APDU_RETRIES - 1: + raise + raise RuntimeError("send_apdu failed") + + +# --- TLV utilities --- + +def iter_tlv(data: bytes, with_positions: bool = False) -> Generator: + idx, length = 0, len(data) + while idx < length: + start_pos = idx + tag = data[idx] + idx += 1 + if tag & 0x1F == 0x1F: # Multi-byte tag + tag_value = tag + while idx < length: + next_byte = data[idx] + idx += 1 + tag_value = (tag_value << 8) | next_byte + if not (next_byte & 0x80): + break + else: + tag_value = tag + if idx >= length: + break + size = data[idx] + idx += 1 + if size & 0x80: # Multi-byte length + num_bytes = size & 0x7F + if idx + num_bytes > length: + break + size = int.from_bytes(data[idx : idx + num_bytes], "big") + idx += num_bytes + if idx + size > length: + break + value = data[idx : idx + size] + idx += size + yield (tag_value, value, start_pos, idx) if with_positions else (tag_value, value) + + +def find_tag(data: bytes, target: int) -> bytes | None: + return next((v for t, v in iter_tlv(data) if t == target), None) + + +def require_tag(data: bytes, target: int, label: str = "") -> bytes: + v = find_tag(data, target) + if v is None: + raise RuntimeError(f"Missing {label or f'tag 0x{target:X}'}") + return v + + +def tbcd_to_string(raw: bytes) -> str: + return "".join(str(n) for b in raw for n in (b & 0x0F, b >> 4) if n <= 9) + + +def string_to_tbcd(s: str) -> bytes: + digits = [int(c) for c in s if c.isdigit()] + return bytes(digits[i] | ((digits[i + 1] if i + 1 < len(digits) else 0xF) << 4) for i in range(0, len(digits), 2)) + + +def encode_tlv(tag: int, value: bytes) -> bytes: + tag_bytes = bytes([(tag >> 8) & 0xFF, tag & 0xFF]) if tag > 255 else bytes([tag]) + vlen = len(value) + if vlen <= 127: + return tag_bytes + bytes([vlen]) + value + length_bytes = vlen.to_bytes((vlen.bit_length() + 7) // 8, "big") + return tag_bytes + bytes([0x80 | len(length_bytes)]) + length_bytes + value + + +def int_bytes(n: int) -> bytes: + """Encode a positive integer as minimal big-endian bytes (at least 1 byte).""" + return n.to_bytes((n.bit_length() + 7) // 8 or 1, "big") + + +PROFILE: FieldMap = { + TAG_ICCID: ("iccid", tbcd_to_string), + 0x4F: ("isdpAid", lambda v: v.hex().upper()), + 0x9F70: ("profileState", lambda v: STATE_LABELS.get(v[0], "unknown")), + 0x90: ("profileNickname", lambda v: v.decode("utf-8", errors="ignore") or None), + 0x91: ("serviceProviderName", lambda v: v.decode("utf-8", errors="ignore") or None), + 0x92: ("profileName", lambda v: v.decode("utf-8", errors="ignore") or None), + 0x93: ("iconType", lambda v: ICON_LABELS.get(v[0], "unknown")), + 0x94: ("icon", b64e), + 0x95: ("profileClass", lambda v: CLASS_LABELS.get(v[0], "unknown")), +} + + +def decode_struct(data: bytes, field_map: FieldMap) -> dict[str, Any]: + """Parse TLV data using a {tag: (field_name, decoder)} map into a dict.""" + result: dict[str, Any] = {name: None for name, _ in field_map.values()} + for tag, value in iter_tlv(data): + if (field := field_map.get(tag)): + result[field[0]] = field[1](value) + return result + + +# --- ES10x command transport --- + +def es10x_command(client: AtClient, data: bytes) -> bytes: + response = bytearray() + sequence = 0 + offset = 0 + while offset < len(data): + chunk = data[offset : offset + ES10X_MSS] + offset += len(chunk) + is_last = offset == len(data) + apdu = bytes([0x80, 0xE2, 0x91 if is_last else 0x11, sequence & 0xFF, len(chunk)]) + chunk + segment, sw1, sw2 = client.send_apdu(apdu) + response.extend(segment) + while True: + if sw1 == 0x61: # More data available + segment, sw1, sw2 = client.send_apdu(bytes([0x80, 0xC0, 0x00, 0x00, sw2 or 0])) + response.extend(segment) + continue + if (sw1 & 0xF0) == 0x90: + break + raise RuntimeError(f"APDU failed with SW={sw1:02X}{sw2:02X}") + sequence += 1 + return bytes(response) + + +# --- Profile operations --- + +NOTIFICATION: FieldMap = { + TAG_STATUS: ("seqNumber", lambda v: int.from_bytes(v, "big")), + 0x81: ("profileManagementOperation", + lambda v: NOTIFICATION_OPERATIONS.get(next((m for m in NOTIFICATION_OPERATIONS if len(v) >= 2 and v[1] & m), 0), "unknown")), + 0x0C: ("notificationAddress", lambda v: v.decode("utf-8", errors="ignore")), + TAG_ICCID: ("iccid", tbcd_to_string), +} + + +def decode_profiles(blob: bytes) -> list[dict]: + root = require_tag(blob, TAG_PROFILE_INFO_LIST, "ProfileInfoList") + list_ok = find_tag(root, TAG_OK) + if list_ok is None: + return [] + return [decode_struct(value, PROFILE) for tag, value in iter_tlv(list_ok) if tag == 0xE3] + + +def list_profiles(client: AtClient) -> list[dict]: + return decode_profiles(es10x_command(client, TAG_PROFILE_INFO_LIST.to_bytes(2, "big") + b"\x00")) + + +def set_profile_nickname(client: AtClient, iccid: str, nickname: str) -> None: + nickname_bytes = nickname.encode("utf-8") + if len(nickname_bytes) > 64: + raise ValueError("Profile nickname must be 64 bytes or less") + content = encode_tlv(TAG_ICCID, string_to_tbcd(iccid)) + encode_tlv(0x90, nickname_bytes) + response = es10x_command(client, encode_tlv(TAG_SET_NICKNAME, content)) + code = require_tag(require_tag(response, TAG_SET_NICKNAME, "SetNicknameResponse"), TAG_STATUS, "SetNickname status")[0] + if code == 0x01: + raise LPAError(f"profile {iccid} not found") + if code != 0x00: + raise RuntimeError(f"SetNickname failed with status 0x{code:02X}") + + +# --- ES9P HTTP --- + +def es9p_request(smdp_address: str, endpoint: str, payload: dict, error_prefix: str = "Request", session: requests.Session | None = None) -> dict: + url = f"https://{smdp_address}/gsma/rsp2/es9plus/{endpoint}" + headers = {"User-Agent": "gsma-rsp-lpad", "X-Admin-Protocol": "gsma/rsp/v2.3.0", "Content-Type": "application/json"} + http = session or requests + resp = http.post(url, json=payload, headers=headers, timeout=HTTP_TIMEOUT, verify=GSMA_CI_BUNDLE) + resp.raise_for_status() + if not resp.content: + return {} + data = resp.json() + if "header" in data and "functionExecutionStatus" in data["header"]: + status = data["header"]["functionExecutionStatus"] + if status.get("status") == "Failed": + sd = status.get("statusCodeData", {}) + reason = sd.get("reasonCode", "unknown") + subject = sd.get("subjectCode", "unknown") + msg = ES9P_ERROR_MESSAGES.get((reason, subject), + f"{error_prefix} failed: {reason}/{subject} - {sd.get('message', 'unknown')}") + raise RuntimeError(msg) + return data + + +# --- Notifications --- + +def list_notifications(client: AtClient) -> list[dict]: + response = es10x_command(client, encode_tlv(TAG_LIST_NOTIFICATION, b"")) + root = require_tag(response, TAG_LIST_NOTIFICATION, "ListNotificationResponse") + metadata_list = find_tag(root, TAG_OK) + if metadata_list is None: + return [] + return [decode_struct(value, NOTIFICATION) for tag, value in iter_tlv(metadata_list) if tag == TAG_NOTIFICATION_METADATA] + + +def process_notifications(client: AtClient) -> None: + for notification in list_notifications(client): + seq_number, smdp_address = notification["seqNumber"], notification["notificationAddress"] + try: + request = encode_tlv(TAG_RETRIEVE_NOTIFICATION, encode_tlv(TAG_OK, encode_tlv(TAG_STATUS, int_bytes(seq_number)))) + response = es10x_command(client, request) + content = require_tag(require_tag(response, TAG_RETRIEVE_NOTIFICATION, "RetrieveNotificationsListResponse"), + TAG_OK, "RetrieveNotificationsListResponse") + pending_notif = next((v for t, v in iter_tlv(content) if t in (TAG_PROFILE_INSTALL_RESULT, 0x30)), None) + if pending_notif is None: + raise RuntimeError("Missing PendingNotification") + + es9p_request(smdp_address, "handleNotification", {"pendingNotification": b64e(pending_notif)}, "HandleNotification") + + response = es10x_command(client, encode_tlv(TAG_NOTIFICATION_SENT, encode_tlv(TAG_STATUS, int_bytes(seq_number)))) + root = require_tag(response, TAG_NOTIFICATION_SENT, "NotificationSentResponse") + if int.from_bytes(require_tag(root, TAG_STATUS, "RemoveNotificationFromList status"), "big") != 0: + raise RuntimeError("RemoveNotificationFromList failed") + except Exception as e: + print(f"notification {seq_number} failed: {e}", file=sys.stderr) + + +# --- Authentication & Download --- + +def get_challenge_and_info(client: AtClient) -> tuple[bytes, bytes]: + challenge_resp = es10x_command(client, encode_tlv(TAG_EUICC_CHALLENGE, b"")) + challenge = require_tag(require_tag(challenge_resp, TAG_EUICC_CHALLENGE, "GetEuiccDataResponse"), + TAG_STATUS, "challenge in response") + info_resp = es10x_command(client, encode_tlv(TAG_EUICC_INFO, b"")) + require_tag(info_resp, TAG_EUICC_INFO, "GetEuiccInfo1Response") + return challenge, info_resp + + +def authenticate_server(client: AtClient, b64_signed1: str, b64_sig1: str, b64_pk_id: str, b64_cert: str, matching_id: str) -> str: + tac = bytes([0x35, 0x29, 0x06, 0x11]) + device_info = encode_tlv(TAG_STATUS, tac) + encode_tlv(0xA1, b"") + ctx_inner = encode_tlv(TAG_STATUS, matching_id.encode("utf-8")) + encode_tlv(0xA1, device_info) + content = b64d(b64_signed1) + b64d(b64_sig1) + b64d(b64_pk_id) + b64d(b64_cert) + encode_tlv(0xA0, ctx_inner) + response = es10x_command(client, encode_tlv(TAG_AUTH_SERVER, content)) + root = require_tag(response, TAG_AUTH_SERVER, "AuthenticateServerResponse") + error_tag = find_tag(root, 0xA1) + if error_tag is not None: + code = int.from_bytes(error_tag, "big") if error_tag else 0 + raise RuntimeError(f"AuthenticateServer rejected by eUICC: {AUTH_SERVER_ERROR_CODES.get(code, 'unknown')} (0x{code:02X})") + return b64e(response) + + +def prepare_download(client: AtClient, b64_signed2: str, b64_sig2: str, b64_cert: str, cc: str | None = None) -> str: + smdp_signed2 = b64d(b64_signed2) + smdp_signature2 = b64d(b64_sig2) + smdp_certificate = b64d(b64_cert) + smdp_signed2_root = find_tag(smdp_signed2, 0x30) + if smdp_signed2_root is None: + raise RuntimeError("Invalid smdpSigned2") + transaction_id = find_tag(smdp_signed2_root, TAG_STATUS) + cc_required_flag = find_tag(smdp_signed2_root, 0x01) + if transaction_id is None or cc_required_flag is None: + raise RuntimeError("Invalid smdpSigned2") + content = smdp_signed2 + smdp_signature2 + if int.from_bytes(cc_required_flag, "big") != 0: + if not cc: + raise RuntimeError("Confirmation code required but not provided") + content += encode_tlv(0x04, hashlib.sha256(hashlib.sha256(cc.encode("utf-8")).digest() + transaction_id).digest()) + content += smdp_certificate + response = es10x_command(client, encode_tlv(TAG_PREPARE_DOWNLOAD, content)) + require_tag(response, TAG_PREPARE_DOWNLOAD, "PrepareDownloadResponse") + return b64e(response) + + +def _parse_tlv_header_len(data: bytes) -> int: + tag_len = 2 if data[0] & 0x1F == 0x1F else 1 + length_byte = data[tag_len] + return tag_len + (1 + (length_byte & 0x7F) if length_byte & 0x80 else 1) + + +def _split_bpp(bpp: bytes) -> list[bytes]: + """Split a BoundProfilePackage into APDU chunks per SGP.22 §5.7.6.""" + root_value = None + for tag, value, start, end in iter_tlv(bpp, with_positions=True): + if tag == TAG_BPP: + root_value = value + val_start = start + _parse_tlv_header_len(bpp[start:end]) + break + if root_value is None: + raise RuntimeError("Invalid BoundProfilePackage") + + chunks: list[bytes] = [] + for tag, value, start, end in iter_tlv(root_value, with_positions=True): + if tag == TAG_BPP_COMMAND: + chunks.append(bpp[0 : val_start + end]) + elif tag in (0xA0, 0xA2): + chunks.append(bpp[val_start + start : val_start + end]) + elif tag in (0xA1, 0xA3): + hdr_len = _parse_tlv_header_len(root_value[start:end]) + chunks.append(bpp[val_start + start : val_start + start + hdr_len]) + for _, _, cs, ce in iter_tlv(value, with_positions=True): + chunks.append(value[cs:ce]) + return chunks + + +def _parse_install_result(response: bytes) -> dict[str, Any] | None: + """Parse a ProfileInstallResult from an APDU response, or None if not present.""" + root = find_tag(response, TAG_PROFILE_INSTALL_RESULT) + if not root: + return None + result_data = find_tag(root, TAG_INSTALL_RESULT_DATA) + if not result_data: + return None + result: dict[str, Any] = {"seqNumber": 0, "success": False, "bppCommandId": None, "errorReason": None} + notif_meta = find_tag(result_data, TAG_NOTIFICATION_METADATA) + if notif_meta: + seq_num = find_tag(notif_meta, TAG_STATUS) + if seq_num: + result["seqNumber"] = int.from_bytes(seq_num, "big") + final_result = find_tag(result_data, 0xA2) + if final_result: + for tag, value in iter_tlv(final_result): + if tag == 0xA0: + result["success"] = True + elif tag == 0xA1: + bpp_cmd = find_tag(value, TAG_STATUS) + if bpp_cmd: + result["bppCommandId"] = int.from_bytes(bpp_cmd, "big") + err = find_tag(value, 0x81) + if err: + result["errorReason"] = int.from_bytes(err, "big") + return result + + +def load_bpp(client: AtClient, b64_bpp: str) -> dict: + bpp = b64d(b64_bpp) + result = None + for chunk in _split_bpp(bpp): + response = es10x_command(client, chunk) + if response and (parsed := _parse_install_result(response)): + result = parsed + break + + if result is None: + raise RuntimeError("Profile installation failed: no result from eUICC") + if not result["success"] and result["errorReason"] is not None: + msg = BPP_ERROR_MESSAGES.get(result["errorReason"]) + if not msg: + cmd_name = BPP_COMMAND_NAMES.get(result["bppCommandId"], f"unknown({result['bppCommandId']})") + err_name = BPP_ERROR_REASONS.get(result["errorReason"], f"unknown({result['errorReason']})") + msg = f"Profile installation failed at {cmd_name}: {err_name}" + raise RuntimeError(msg) + if not result["success"]: + raise RuntimeError("Profile installation failed: no result from eUICC") + return result + + +def parse_metadata(b64_metadata: str) -> dict: + root = find_tag(b64d(b64_metadata), TAG_PROFILE_METADATA) + if root is None: + raise RuntimeError("Invalid profileMetadata") + return decode_struct(root, PROFILE) + + +def cancel_session(client: AtClient, transaction_id: bytes, reason: int = 127) -> str: + content = encode_tlv(0x80, transaction_id) + encode_tlv(0x81, bytes([reason])) + response = es10x_command(client, encode_tlv(TAG_CANCEL_SESSION, content)) + return b64e(response) + + +def parse_lpa_activation_code(activation_code: str) -> tuple[str, str]: + """Parse 'LPA:1$smdp.example.com$MATCHING-ID' into (smdp_address, matching_id).""" + if not activation_code.startswith("LPA:"): + raise ValueError("Invalid activation code format") + parts = activation_code[4:].split("$") + if len(parts) != 3: + raise ValueError("Invalid activation code format") + return parts[1], parts[2] + + +def _b64_field(data: dict, key: str) -> str: + return base64_trim(data[key]) + + +def _cancel_session_safe(client: AtClient, smdp: str, tx_id: str, session: requests.Session) -> None: + b64_cancel = "" + try: + b64_cancel = cancel_session(client, b64d(tx_id)) + except Exception: + pass + try: + es9p_request(smdp, "cancelSession", {"transactionId": tx_id, "cancelSessionResponse": b64_cancel}, "CancelSession", session=session) + except Exception: + pass + + +def download_profile(client: AtClient, activation_code: str) -> str: + """Download and install an eSIM profile. Returns the ICCID of the installed profile.""" + if not system_time_valid(): + raise RuntimeError("System time is not set; TLS certificate validation requires a valid clock") + smdp, matching_id = parse_lpa_activation_code(activation_code) + challenge, euicc_info = get_challenge_and_info(client) + session = requests.Session() + tx_id = None + + try: + # step 1: initiate authentication + auth = es9p_request(smdp, "initiateAuthentication", { + "smdpAddress": smdp, "euiccChallenge": b64e(challenge), + "euiccInfo1": b64e(euicc_info), "matchingId": matching_id, + }, "Authentication", session=session) + tx_id = _b64_field(auth, "transactionId") + + # step 2: authenticate server + b64_auth = authenticate_server(client, + _b64_field(auth, "serverSigned1"), _b64_field(auth, "serverSignature1"), + _b64_field(auth, "euiccCiPKIdToBeUsed"), _b64_field(auth, "serverCertificate"), + matching_id) + + # step 3: authenticate client + get metadata + cli = es9p_request(smdp, "authenticateClient", { + "transactionId": tx_id, "authenticateServerResponse": b64_auth, + }, "Authentication", session=session) + iccid = parse_metadata(_b64_field(cli, "profileMetadata"))["iccid"] + + # step 4: prepare download + b64_prep = prepare_download(client, + _b64_field(cli, "smdpSigned2"), _b64_field(cli, "smdpSignature2"), + _b64_field(cli, "smdpCertificate")) + + # step 5: get and install bound profile package + bpp = es9p_request(smdp, "getBoundProfilePackage", { + "transactionId": tx_id, "prepareDownloadResponse": b64_prep, + }, "GetBoundProfilePackage", session=session) + load_bpp(client, _b64_field(bpp, "boundProfilePackage")) + return iccid + except Exception: + if tx_id: + _cancel_session_safe(client, smdp, tx_id, session) + raise + finally: + session.close() + + +class TiciLPA(LPABase): + def __init__(self): + if hasattr(self, '_client'): + return + self._client = AtClient(DEFAULT_DEVICE, DEFAULT_BAUD, DEFAULT_TIMEOUT) + atexit.register(self._client.close) + + @contextmanager + def _acquire_lock(self): + fd = os.open(LOCK_FILE, os.O_CREAT | os.O_RDWR) + try: + fcntl.flock(fd, fcntl.LOCK_EX) + yield + finally: + fcntl.flock(fd, fcntl.LOCK_UN) + os.close(fd) + + @contextmanager + def _acquire_channel(self): + with self._acquire_lock(): + try: + self._client.open_isdr() + yield + finally: + if self._client.channel: + try: + self._client.query(f"AT+CCHC={self._client.channel}") + except (RuntimeError, TimeoutError): + pass + self._client.channel = None + + def list_profiles(self) -> list[Profile]: + with self._acquire_channel(): + return [ + Profile( + iccid=p.get("iccid", ""), + nickname=p.get("profileNickname") or "", + enabled=p.get("profileState") == "enabled", + provider=p.get("serviceProviderName") or "", + ) + for p in list_profiles(self._client) + ] + + def get_active_profile(self) -> Profile | None: + return None + + def process_notifications(self) -> None: + if not system_time_valid(): + raise RuntimeError("System time is not set; TLS certificate validation requires a valid clock") + with self._acquire_channel(): + process_notifications(self._client) + + def delete_profile(self, iccid: str) -> None: + profile = next((p for p in self.list_profiles() if p.iccid == iccid), None) + if profile is None: + raise LPAProfileNotFoundError(f"profile not found: {iccid}") + if profile.is_comma: + raise LPAError("refusing to delete a comma profile") + with self._acquire_channel(): + request = encode_tlv(TAG_DELETE_PROFILE, encode_tlv(TAG_ICCID, string_to_tbcd(iccid))) + response = es10x_command(self._client, request) + code = require_tag(require_tag(response, TAG_DELETE_PROFILE, "DeleteProfileResponse"), TAG_STATUS, "DeleteProfile status")[0] + if code != PROFILE_OK: + raise LPAError(f"DeleteProfile failed: {PROFILE_ERROR_CODES.get(code, 'unknown')} (0x{code:02X})") + + def download_profile(self, qr: str, nickname: str | None = None) -> None: + with self._acquire_channel(): + iccid = download_profile(self._client, qr) + if nickname and iccid: + set_profile_nickname(self._client, iccid, nickname) + + def nickname_profile(self, iccid: str, nickname: str) -> None: + with self._acquire_channel(): + set_profile_nickname(self._client, iccid, nickname) + + def _enable_profile(self, iccid: str) -> int: + inner = encode_tlv(TAG_OK, encode_tlv(TAG_ICCID, string_to_tbcd(iccid))) + inner += b'\x01\x01\x01' # refreshFlag=1 + response = es10x_command(self._client, encode_tlv(TAG_ENABLE_PROFILE, inner)) + return require_tag(require_tag(response, TAG_ENABLE_PROFILE, "EnableProfileResponse"), TAG_STATUS, "EnableProfile status")[0] + + def switch_profile(self, iccid: str) -> None: + with self._acquire_channel(): + code = self._enable_profile(iccid) + if code == PROFILE_CAT_BUSY: # stale eUICC transaction, reset and retry + self._client._reset_modem() + self._client.open_isdr() + code = self._enable_profile(iccid) + if code not in (PROFILE_OK, PROFILE_NOT_IN_DISABLED_STATE): + raise LPAError(f"EnableProfile failed: {PROFILE_ERROR_CODES.get(code, 'unknown')} (0x{code:02X})") + + def is_euicc(self) -> bool: + # +CCHO: -> ISD-R applet present, eUICC. Any error -> non-eUICC. + with self._acquire_lock(): + try: + lines = self._client.query(f'AT+CCHO="{ISDR_AID}"') + except RuntimeError: + return False + for line in lines: + if line.startswith("+CCHO:") and (ch := line.split(":", 1)[1].strip()): + try: + self._client.query(f"AT+CCHC={ch}") + except (RuntimeError, TimeoutError): + pass + self._client.channel = None + return True + return False diff --git a/openpilot/common/file_chunker.py b/openpilot/common/file_chunker.py new file mode 100755 index 0000000000..2d080c3fff --- /dev/null +++ b/openpilot/common/file_chunker.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +import io +import sys +import math +import os +from pathlib import Path + +CHUNK_SIZE = 45 * 1024 * 1024 # 45MB, under GitHub's 50MB limit + +def get_chunk_name(name, idx, num_chunks): + return f"{name}.chunk{idx+1:02d}of{num_chunks:02d}" + +def get_manifest_path(name): + return f"{name}.chunkmanifest" + +def _chunk_paths(path, num_chunks): + return [get_manifest_path(path)] + [get_chunk_name(path, i, num_chunks) for i in range(num_chunks)] + +def get_chunk_targets(path, file_size): + num_chunks = math.ceil(file_size / CHUNK_SIZE) + return _chunk_paths(path, num_chunks) + +def chunk_file(path, targets): + manifest_path, *chunk_paths = targets + actual_num_chunks = max(1, math.ceil(os.path.getsize(path) / CHUNK_SIZE)) + assert len(chunk_paths) >= actual_num_chunks, f"Allowed {len(chunk_paths)} chunks but needs at least {actual_num_chunks}, for path {path}" + with open(path, 'rb') as f: + for chunk_path in chunk_paths: + with open(chunk_path, 'wb') as out: + out.write(f.read(CHUNK_SIZE)) + Path(manifest_path).write_text(str(len(chunk_paths))) + os.remove(path) + +def get_existing_chunks(path): + if os.path.isfile(path): + return [path] + if os.path.isfile(manifest := get_manifest_path(path)): + num_chunks = int(Path(manifest).read_text().strip()) + return _chunk_paths(path, num_chunks) + raise FileNotFoundError(path) + +class ChunkStream(io.RawIOBase): + def __init__(self, paths): + self._paths = iter(paths) + self._f = None + + def readable(self): + return True + + def readinto(self, b): + n = 0 + view = memoryview(b) + while n < len(b): + if self._f is None: + p = next(self._paths, None) + if p is None: + break + self._f = open(p, 'rb') + count = self._f.readinto(view[n:]) + if not count: + self._f.close() + self._f = None + continue + n += count + return n + +def open_file_chunked(path): + manifest_path = get_manifest_path(path) + if os.path.isfile(manifest_path): + num_chunks = int(Path(manifest_path).read_text().strip()) + paths = [get_chunk_name(path, i, num_chunks) for i in range(num_chunks)] + elif os.path.isfile(path): + paths = [path] + else: + raise FileNotFoundError(path) + return io.BufferedReader(ChunkStream(paths)) + + +if __name__ == "__main__": + path = sys.argv[1] + chunk_paths = get_chunk_targets(path, os.path.getsize(path)) + chunk_file(path, chunk_paths) diff --git a/openpilot/common/filter_simple.py b/openpilot/common/filter_simple.py new file mode 100644 index 0000000000..b28c3d68f5 --- /dev/null +++ b/openpilot/common/filter_simple.py @@ -0,0 +1,34 @@ +class FirstOrderFilter: + def __init__(self, x0, rc, dt, initialized=True): + self.x = x0 + self.dt = dt + self.update_alpha(rc) + self.initialized = initialized + + def update_alpha(self, rc): + self.alpha = self.dt / (rc + self.dt) + + def update(self, x): + if self.initialized: + self.x = (1. - self.alpha) * self.x + self.alpha * x + else: + self.initialized = True + self.x = x + return self.x + + +class BounceFilter(FirstOrderFilter): + def __init__(self, x0, rc, dt, initialized=True, bounce=2): + self.velocity = FirstOrderFilter(0.0, 0.15, dt) + self.bounce = bounce + super().__init__(x0, rc, dt, initialized) + + def update(self, x): + super().update(x) + scale = self.dt / (1.0 / 60.0) # tuned at 60 fps + self.velocity.x += (x - self.x) * self.bounce * scale * self.dt + self.velocity.update(0.0) + if abs(self.velocity.x) < 1e-3: + self.velocity.x = 0.0 + self.x += self.velocity.x + return self.x diff --git a/openpilot/common/git.py b/openpilot/common/git.py new file mode 100644 index 0000000000..6b662e5719 --- /dev/null +++ b/openpilot/common/git.py @@ -0,0 +1,42 @@ +from functools import cache +import subprocess +from openpilot.common.utils import run_cmd, run_cmd_default + + +@cache +def get_commit(cwd: str | None = None, branch: str = "HEAD") -> str: + return run_cmd_default(["git", "rev-parse", branch], cwd=cwd) + + +@cache +def get_commit_date(cwd: str | None = None, commit: str = "HEAD") -> str: + return run_cmd_default(["git", "show", "--no-patch", "--format='%ct %ci'", commit], cwd=cwd) + + +@cache +def get_short_branch(cwd: str | None = None) -> str: + return run_cmd_default(["git", "rev-parse", "--abbrev-ref", "HEAD"], cwd=cwd) + + +@cache +def get_branch(cwd: str | None = None) -> str: + return run_cmd_default(["git", "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"], cwd=cwd) + + +@cache +def get_origin(cwd: str | None = None) -> str: + try: + local_branch = run_cmd(["git", "name-rev", "--name-only", "HEAD"], cwd=cwd) + tracking_remote = run_cmd(["git", "config", "branch." + local_branch + ".remote"], cwd=cwd) + return run_cmd(["git", "config", "remote." + tracking_remote + ".url"], cwd=cwd) + except subprocess.CalledProcessError: # Not on a branch, fallback + return run_cmd_default(["git", "config", "--get", "remote.origin.url"], cwd=cwd) + + +@cache +def get_normalized_origin(cwd: str | None = None) -> str: + return get_origin(cwd) \ + .replace("git@", "", 1) \ + .replace(".git", "", 1) \ + .replace("https://", "", 1) \ + .replace(":", "/", 1) diff --git a/common/gpio.py b/openpilot/common/gpio.py similarity index 100% rename from common/gpio.py rename to openpilot/common/gpio.py diff --git a/common/gps.py b/openpilot/common/gps.py similarity index 100% rename from common/gps.py rename to openpilot/common/gps.py diff --git a/openpilot/common/hardware/__init__.py b/openpilot/common/hardware/__init__.py new file mode 100644 index 0000000000..3387d8a0ca --- /dev/null +++ b/openpilot/common/hardware/__init__.py @@ -0,0 +1,16 @@ +import os +from typing import cast + +from openpilot.common.hardware.base import HardwareBase +from openpilot.common.hardware.tici.hardware import Tici +from openpilot.common.hardware.pc.hardware import Pc + +TICI = os.path.isfile('/TICI') +AGNOS = os.path.isfile('/AGNOS') +PC = not TICI + + +if TICI: + HARDWARE = cast(HardwareBase, Tici()) +else: + HARDWARE = cast(HardwareBase, Pc()) diff --git a/openpilot/common/hardware/base.h b/openpilot/common/hardware/base.h new file mode 100644 index 0000000000..f4546adfa8 --- /dev/null +++ b/openpilot/common/hardware/base.h @@ -0,0 +1,25 @@ +#pragma once + +#include +#include +#include +#include + +#include "openpilot/cereal/gen/cpp/log.capnp.h" + +// no-op base hw class +class HardwareNone { +public: + static std::string get_name() { return ""; } + static cereal::InitData::DeviceType get_device_type() { return cereal::InitData::DeviceType::UNKNOWN; } + + static std::string get_serial() { return "cccccc"; } + + static std::map get_init_logs() { + return {}; + } + + static void set_ir_power(int percentage) {} + + static bool PC() { return false; } +}; diff --git a/openpilot/common/hardware/base.py b/openpilot/common/hardware/base.py new file mode 100644 index 0000000000..5d8f7770dc --- /dev/null +++ b/openpilot/common/hardware/base.py @@ -0,0 +1,161 @@ +import os +from abc import abstractmethod, ABC +from dataclasses import dataclass, fields + +from openpilot.cereal import log +from openpilot.common.esim.base import LPABase + +NetworkType = log.DeviceState.NetworkType +NetworkStrength = log.DeviceState.NetworkStrength + +@dataclass +class ThermalZone: + # a zone from /sys/class/thermal/thermal_zone* + name: str # a.k.a type + scale: float = 1000. # scale to get degrees in C + zone_number = -1 + + def read(self) -> float: + if self.zone_number < 0: + for n in os.listdir("/sys/devices/virtual/thermal"): + if not n.startswith("thermal_zone"): + continue + with open(os.path.join("/sys/devices/virtual/thermal", n, "type")) as f: + if f.read().strip() == self.name: + self.zone_number = int(n.removeprefix("thermal_zone")) + break + + try: + with open(f"/sys/devices/virtual/thermal/thermal_zone{self.zone_number}/temp") as f: + return int(f.read()) / self.scale + except FileNotFoundError: + return 0 + +@dataclass +class ThermalConfig: + cpu: list[ThermalZone] | None = None + gpu: list[ThermalZone] | None = None + dsp: ThermalZone | None = None + pmic: list[ThermalZone] | None = None + memory: ThermalZone | None = None + intake: ThermalZone | None = None + exhaust: ThermalZone | None = None + gnss: ThermalZone | None = None + bottomSoc: ThermalZone | None = None + + def get_msg(self): + ret = {} + for f in fields(ThermalConfig): + v = getattr(self, f.name) + if v is not None: + if isinstance(v, list): + ret[f.name + "TempC"] = [x.read() for x in v] + else: + ret[f.name + "TempC"] = v.read() + return ret + +class HardwareBase(ABC): + @staticmethod + def get_cmdline() -> dict[str, str]: + with open('/proc/cmdline') as f: + cmdline = f.read() + return {kv[0]: kv[1] for kv in [s.split('=') for s in cmdline.split(' ')] if len(kv) == 2} + + @staticmethod + def read_param_file(path, parser, default=0): + try: + with open(path) as f: + return parser(f.read()) + except Exception: + return default + + def booted(self) -> bool: + return True + + def reboot(self, reason=None): + print("REBOOT!") + + def uninstall(self): + print("uninstall") + + def get_os_version(self): + return None + + @abstractmethod + def get_device_type(self): + pass + + def get_imei(self) -> str: + return "" + + def get_serial(self): + return "" + + def get_network_info(self): + return None + + def get_network_type(self): + return NetworkType.none + + def get_sim_info(self): + return { + 'sim_id': '', + 'mcc_mnc': None, + 'network_type': ["Unknown"], + 'sim_state': ["ABSENT"], + 'data_connected': False + } + + def get_sim_lpa(self) -> LPABase: + raise NotImplementedError("SIM LPA not available") + + def get_network_strength(self, network_type): + return NetworkStrength.unknown + + def get_network_metered(self, network_type) -> bool: + return network_type not in (NetworkType.none, NetworkType.wifi, NetworkType.ethernet) + + def get_current_power_draw(self): + return 0 + + def get_som_power_draw(self): + return 0 + + def shutdown(self): + print("SHUTDOWN!") + + def get_thermal_config(self): + return ThermalConfig() + + def set_display_power(self, on: bool): + pass + + def set_screen_brightness(self, percentage): + pass + + def get_screen_brightness(self): + return 0 + + def set_power_save(self, powersave_enabled): + pass + + def get_gpu_usage_percent(self): + return 0 + + def get_modem_temperatures(self): + return [] + + def initialize_hardware(self): + pass + + def reset_internal_panda(self): + pass + + def recover_internal_panda(self): + pass + + def get_modem_data_usage(self): + return -1, -1 + + def set_ir_power(self, percent: int): + pass diff --git a/openpilot/common/hardware/hw.h b/openpilot/common/hardware/hw.h new file mode 100644 index 0000000000..7681479ccc --- /dev/null +++ b/openpilot/common/hardware/hw.h @@ -0,0 +1,62 @@ +#pragma once + +#include + +#include "common/hardware/base.h" +#include "common/util.h" + +#if __TICI__ +#include "common/hardware/tici/hardware.h" +#define Hardware HardwareTici +#else +#include "common/hardware/pc/hardware.h" +#define Hardware HardwarePC +#endif + +namespace Path { + inline std::string openpilot_prefix() { + return util::getenv("OPENPILOT_PREFIX", ""); + } + + inline std::string comma_home() { + return util::getenv("HOME") + "/.comma" + Path::openpilot_prefix(); + } + + inline std::string log_root() { + if (const char *env = getenv("LOG_ROOT")) { + return env; + } + return Hardware::PC() ? Path::comma_home() + "/media/0/realdata" : "/data/media/0/realdata"; + } + + inline std::string params() { + return util::getenv("PARAMS_ROOT", Hardware::PC() ? (Path::comma_home() + "/params") : "/data/params"); + } + + inline std::string rsa_file() { + return Hardware::PC() ? Path::comma_home() + "/persist/comma/id_rsa" : "/persist/comma/id_rsa"; + } + + inline std::string swaglog_ipc() { + return "ipc:///tmp/logmessage" + Path::openpilot_prefix(); + } + + inline std::string download_cache_root() { + if (const char *env = getenv("COMMA_CACHE")) { + return env; + } + return "/tmp/comma_download_cache" + Path::openpilot_prefix() + "/"; + } + + inline std::string shm_path() { + #ifdef __APPLE__ + return"/tmp"; + #else + return "/dev/shm"; + #endif + } + + inline std::string model_root() { + return Hardware::PC() ? Path::comma_home() + "/media/0/models" : "/data/media/0/models"; + } +} // namespace Path diff --git a/system/hardware/hw.py b/openpilot/common/hardware/hw.py similarity index 88% rename from system/hardware/hw.py rename to openpilot/common/hardware/hw.py index 5e40fff136..245856fa16 100644 --- a/system/hardware/hw.py +++ b/openpilot/common/hardware/hw.py @@ -2,7 +2,7 @@ import os import platform from pathlib import Path -from openpilot.system.hardware import PC +from openpilot.common.hardware import PC DEFAULT_DOWNLOAD_CACHE_ROOT = "/tmp/comma_download_cache" @@ -20,6 +20,10 @@ class Paths: else: return '/data/media/0/realdata/' + @staticmethod + def log_root_external() -> str: + return '/mnt/external_realdata/' + @staticmethod def swaglog_root() -> str: if PC: @@ -51,6 +55,13 @@ class Paths: else: return "/data/stats/" + @staticmethod + def stats_sp_root() -> str: + if PC: + return str(Path(Paths.comma_home()) / "stats") + else: + return "/data/stats_sp/" + @staticmethod def config_root() -> str: if PC: diff --git a/common/tests/__init__.py b/openpilot/common/hardware/pc/__init__.py similarity index 100% rename from common/tests/__init__.py rename to openpilot/common/hardware/pc/__init__.py diff --git a/openpilot/common/hardware/pc/hardware.h b/openpilot/common/hardware/pc/hardware.h new file mode 100644 index 0000000000..2c43b43292 --- /dev/null +++ b/openpilot/common/hardware/pc/hardware.h @@ -0,0 +1,12 @@ +#pragma once + +#include + +#include "common/hardware/base.h" + +class HardwarePC : public HardwareNone { +public: + static std::string get_name() { return "pc"; } + static cereal::InitData::DeviceType get_device_type() { return cereal::InitData::DeviceType::PC; } + static bool PC() { return true; } +}; diff --git a/openpilot/common/hardware/pc/hardware.py b/openpilot/common/hardware/pc/hardware.py new file mode 100644 index 0000000000..b4aa56c904 --- /dev/null +++ b/openpilot/common/hardware/pc/hardware.py @@ -0,0 +1,10 @@ +from openpilot.cereal import log +from openpilot.common.hardware.base import HardwareBase + +class Pc(HardwareBase): + def get_device_type(self): + return "pc" + + def get_network_type(self): + # some stuff is gated on wifi, so just assume for now + return log.DeviceState.NetworkType.wifi diff --git a/openpilot/common/hardware/tici/__init__.py b/openpilot/common/hardware/tici/__init__.py new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/openpilot/common/hardware/tici/__init__.py @@ -0,0 +1 @@ + diff --git a/openpilot/common/hardware/tici/agnos.json b/openpilot/common/hardware/tici/agnos.json new file mode 100644 index 0000000000..f22a57db75 --- /dev/null +++ b/openpilot/common/hardware/tici/agnos.json @@ -0,0 +1,84 @@ +[ + { + "name": "xbl", + "url": "https://commadist.azureedge.net/agnosupdate/xbl-e8acf2a9cc7f0ce84cb803bfea9477f765c0d7b4daf26048e59651b9e6a7bfbb.img.xz", + "hash": "e8acf2a9cc7f0ce84cb803bfea9477f765c0d7b4daf26048e59651b9e6a7bfbb", + "hash_raw": "e8acf2a9cc7f0ce84cb803bfea9477f765c0d7b4daf26048e59651b9e6a7bfbb", + "size": 3282256, + "sparse": false, + "full_check": true, + "has_ab": true, + "ondevice_hash": "bea7f1a24428c3ededf672fa4fc78baf180cfbd8aafb77c974655b38517283e3" + }, + { + "name": "xbl_config", + "url": "https://commadist.azureedge.net/agnosupdate/xbl_config-758552ecf92b5569677197783bf0ccb73d7f961685308e45d3276ac9dd974f85.img.xz", + "hash": "758552ecf92b5569677197783bf0ccb73d7f961685308e45d3276ac9dd974f85", + "hash_raw": "758552ecf92b5569677197783bf0ccb73d7f961685308e45d3276ac9dd974f85", + "size": 98124, + "sparse": false, + "full_check": true, + "has_ab": true, + "ondevice_hash": "fb18cde08a98a168961ecd357e92474823046752b94e112f59fe51a6acd7197d" + }, + { + "name": "abl", + "url": "https://commadist.azureedge.net/agnosupdate/abl-b6fba807b9bcd66a31f2afb0eba5163ec239693ad32e2e4200f6c356adfe098c.img.xz", + "hash": "b6fba807b9bcd66a31f2afb0eba5163ec239693ad32e2e4200f6c356adfe098c", + "hash_raw": "b6fba807b9bcd66a31f2afb0eba5163ec239693ad32e2e4200f6c356adfe098c", + "size": 274432, + "sparse": false, + "full_check": true, + "has_ab": true, + "ondevice_hash": "b6fba807b9bcd66a31f2afb0eba5163ec239693ad32e2e4200f6c356adfe098c" + }, + { + "name": "aop", + "url": "https://commadist.azureedge.net/agnosupdate/aop-78b2287ca219a0811b3004c523fa0f4749e4d1fd92be3aba61699305b7943ad1.img.xz", + "hash": "78b2287ca219a0811b3004c523fa0f4749e4d1fd92be3aba61699305b7943ad1", + "hash_raw": "78b2287ca219a0811b3004c523fa0f4749e4d1fd92be3aba61699305b7943ad1", + "size": 184364, + "sparse": false, + "full_check": true, + "has_ab": true, + "ondevice_hash": "6c9135446bd3fc075fcee59b887a12e49029ab1f98ed8d6d1e32c73569d47de3" + }, + { + "name": "devcfg", + "url": "https://commadist.azureedge.net/agnosupdate/devcfg-f71df3a86958c093ba3969254c4db025187eef9385427f1ade946742939b43cc.img.xz", + "hash": "f71df3a86958c093ba3969254c4db025187eef9385427f1ade946742939b43cc", + "hash_raw": "f71df3a86958c093ba3969254c4db025187eef9385427f1ade946742939b43cc", + "size": 40336, + "sparse": false, + "full_check": true, + "has_ab": true, + "ondevice_hash": "2a67971602012c1b43544964709da13c322786b456a8e78568b117e8b1540ce3" + }, + { + "name": "boot", + "url": "https://commadist.azureedge.net/agnosupdate/boot-19ff57b68e219e4503fcaca716967098d5d0a1de8af833f04dbf13b99aeb4d39.img.xz", + "hash": "19ff57b68e219e4503fcaca716967098d5d0a1de8af833f04dbf13b99aeb4d39", + "hash_raw": "19ff57b68e219e4503fcaca716967098d5d0a1de8af833f04dbf13b99aeb4d39", + "size": 17487872, + "sparse": false, + "full_check": true, + "has_ab": true, + "ondevice_hash": "ddfe93cc6a8531af92ee331d9bbaeae2f1d933bdb38e579769dc9fe7998eb626" + }, + { + "name": "system", + "url": "https://commadist.azureedge.net/agnosupdate/system-a396dd98ffd49614fb198d1b022a0c7a6d0a1e563c20ce11b0a975105ab50724.img.xz", + "hash": "4dc41c2c072f5f5d5cd484cd6173049cd96acfb9a67bc20049775585fe881539", + "hash_raw": "a396dd98ffd49614fb198d1b022a0c7a6d0a1e563c20ce11b0a975105ab50724", + "size": 4718592000, + "sparse": true, + "full_check": false, + "has_ab": true, + "ondevice_hash": "cf1229630b7a2b8497705bca4ba947dbf0c217418ff4febff571aa4f4a878134", + "alt": { + "hash": "a396dd98ffd49614fb198d1b022a0c7a6d0a1e563c20ce11b0a975105ab50724", + "url": "https://commadist.azureedge.net/agnosupdate/system-a396dd98ffd49614fb198d1b022a0c7a6d0a1e563c20ce11b0a975105ab50724.img", + "size": 4718592000 + } + } +] \ No newline at end of file diff --git a/system/hardware/tici/agnos.py b/openpilot/common/hardware/tici/agnos.py similarity index 80% rename from system/hardware/tici/agnos.py rename to openpilot/common/hardware/tici/agnos.py index f5261953d5..b3b5e05176 100755 --- a/system/hardware/tici/agnos.py +++ b/openpilot/common/hardware/tici/agnos.py @@ -10,19 +10,16 @@ from collections.abc import Generator import requests -import openpilot.system.updated.casync.casync as casync - SPARSE_CHUNK_FMT = struct.Struct('H2xI4x') -CAIBX_URL = "https://commadist.azureedge.net/agnosupdate/" -AGNOS_MANIFEST_FILE = "system/hardware/tici/agnos.json" +AGNOS_MANIFEST_FILE = "openpilot/system/hardware/tici/agnos.json" class StreamingDecompressor: def __init__(self, url: str) -> None: self.buf = b"" - self.req = requests.get(url, stream=True, headers={'Accept-Encoding': None}, timeout=60) + self.req = requests.get(url, stream=True, headers={'Accept-Encoding': 'identity'}, timeout=60) self.it = self.req.iter_content(chunk_size=1024 * 1024) self.decompressor = lzma.LZMADecompressor(format=lzma.FORMAT_AUTO) self.eof = False @@ -187,50 +184,6 @@ def extract_compressed_image(target_slot_number: int, partition: dict, cloudlog) os.sync() -def extract_casync_image(target_slot_number: int, partition: dict, cloudlog): - path = get_partition_path(target_slot_number, partition) - seed_path = path[:-1] + ('b' if path[-1] == 'a' else 'a') - - target = casync.parse_caibx(partition['casync_caibx']) - - sources: list[tuple[str, casync.ChunkReader, casync.ChunkDict]] = [] - - # First source is the current partition. - try: - raw_hash = get_raw_hash(seed_path, partition['size']) - caibx_url = f"{CAIBX_URL}{partition['name']}-{raw_hash}.caibx" - - try: - cloudlog.info(f"casync fetching {caibx_url}") - sources += [('seed', casync.FileChunkReader(seed_path), casync.build_chunk_dict(casync.parse_caibx(caibx_url)))] - except requests.RequestException: - cloudlog.error(f"casync failed to load {caibx_url}") - except Exception: - cloudlog.exception("casync failed to hash seed partition") - - # Second source is the target partition, this allows for resuming - sources += [('target', casync.FileChunkReader(path), casync.build_chunk_dict(target))] - - # Finally we add the remote source to download any missing chunks - sources += [('remote', casync.RemoteChunkReader(partition['casync_store']), casync.build_chunk_dict(target))] - - last_p = 0 - - def progress(cur): - nonlocal last_p - p = int(cur / partition['size'] * 100) - if p != last_p: - last_p = p - print(f"Installing {partition['name']}: {p}", flush=True) - - stats = casync.extract(target, sources, path, progress) - cloudlog.error(f'casync done {json.dumps(stats)}') - - os.sync() - if not verify_partition(target_slot_number, partition, force_full_check=True): - raise Exception(f"Raw hash mismatch '{partition['hash_raw'].lower()}'") - - def flash_partition(target_slot_number: int, partition: dict, cloudlog, standalone=False): cloudlog.info(f"Downloading and writing {partition['name']}") @@ -245,10 +198,7 @@ def flash_partition(target_slot_number: int, partition: dict, cloudlog, standalo path = get_partition_path(target_slot_number, partition) - if ('casync_caibx' in partition) and not standalone: - extract_casync_image(target_slot_number, partition, cloudlog) - else: - extract_compressed_image(target_slot_number, partition, cloudlog) + extract_compressed_image(target_slot_number, partition, cloudlog) # Write hash after successful flash if not full_check: @@ -278,7 +228,7 @@ def flash_agnos_update(manifest_path: str, target_slot_number: int, cloudlog, st cloudlog.info(f"Target slot {target_slot_number}") # set target slot as unbootable - os.system(f"abctl --set_unbootable {target_slot_number}") + subprocess.run(f"abctl --set_unbootable {target_slot_number}", shell=True) for partition in update: success = False diff --git a/system/hardware/tici/all-partitions.json b/openpilot/common/hardware/tici/all-partitions.json similarity index 75% rename from system/hardware/tici/all-partitions.json rename to openpilot/common/hardware/tici/all-partitions.json index d28b48128b..80a0f7702e 100644 --- a/system/hardware/tici/all-partitions.json +++ b/openpilot/common/hardware/tici/all-partitions.json @@ -97,14 +97,14 @@ }, { "name": "persist", - "url": "https://commadist.azureedge.net/agnosupdate/persist-9814b07851292f510f3794b767489f38ab379a99f0ea75dc620ad2d3a496d54d.img.xz", - "hash": "9814b07851292f510f3794b767489f38ab379a99f0ea75dc620ad2d3a496d54d", - "hash_raw": "9814b07851292f510f3794b767489f38ab379a99f0ea75dc620ad2d3a496d54d", - "size": 33554432, + "url": "https://commadist.azureedge.net/agnosupdate/persist-d6af4ec18df180c7417353b52a9e05e43a6480b29425f087874136436cefe786.img.xz", + "hash": "d6af4ec18df180c7417353b52a9e05e43a6480b29425f087874136436cefe786", + "hash_raw": "d6af4ec18df180c7417353b52a9e05e43a6480b29425f087874136436cefe786", + "size": 4096, "sparse": false, "full_check": true, "has_ab": false, - "ondevice_hash": "9814b07851292f510f3794b767489f38ab379a99f0ea75dc620ad2d3a496d54d" + "ondevice_hash": "d6af4ec18df180c7417353b52a9e05e43a6480b29425f087874136436cefe786" }, { "name": "systemrw", @@ -130,47 +130,47 @@ }, { "name": "xbl", - "url": "https://commadist.azureedge.net/agnosupdate/xbl-6710967ca9701f205d7ab19c3a9b0dd2f547e65b3d96048b7c2b03755aafa0f1.img.xz", - "hash": "6710967ca9701f205d7ab19c3a9b0dd2f547e65b3d96048b7c2b03755aafa0f1", - "hash_raw": "6710967ca9701f205d7ab19c3a9b0dd2f547e65b3d96048b7c2b03755aafa0f1", + "url": "https://commadist.azureedge.net/agnosupdate/xbl-e8acf2a9cc7f0ce84cb803bfea9477f765c0d7b4daf26048e59651b9e6a7bfbb.img.xz", + "hash": "e8acf2a9cc7f0ce84cb803bfea9477f765c0d7b4daf26048e59651b9e6a7bfbb", + "hash_raw": "e8acf2a9cc7f0ce84cb803bfea9477f765c0d7b4daf26048e59651b9e6a7bfbb", "size": 3282256, "sparse": false, "full_check": true, "has_ab": true, - "ondevice_hash": "003a17ab1be68a696f7efe4c9938e8be511d4aacfc2f3211fc896bdc1681d089" + "ondevice_hash": "bea7f1a24428c3ededf672fa4fc78baf180cfbd8aafb77c974655b38517283e3" }, { "name": "xbl_config", - "url": "https://commadist.azureedge.net/agnosupdate/xbl_config-63922cfbfdf4ab87986c4ba8f3a4df5bf28414b3f71a29ec5947336722215535.img.xz", - "hash": "63922cfbfdf4ab87986c4ba8f3a4df5bf28414b3f71a29ec5947336722215535", - "hash_raw": "63922cfbfdf4ab87986c4ba8f3a4df5bf28414b3f71a29ec5947336722215535", + "url": "https://commadist.azureedge.net/agnosupdate/xbl_config-758552ecf92b5569677197783bf0ccb73d7f961685308e45d3276ac9dd974f85.img.xz", + "hash": "758552ecf92b5569677197783bf0ccb73d7f961685308e45d3276ac9dd974f85", + "hash_raw": "758552ecf92b5569677197783bf0ccb73d7f961685308e45d3276ac9dd974f85", "size": 98124, "sparse": false, "full_check": true, "has_ab": true, - "ondevice_hash": "2a855dd636cc94718b64bea83a44d0a31741ecaa8f72a63613ff348ec7404091" + "ondevice_hash": "fb18cde08a98a168961ecd357e92474823046752b94e112f59fe51a6acd7197d" }, { "name": "abl", - "url": "https://commadist.azureedge.net/agnosupdate/abl-32a2174b5f764e95dfc54cf358ba01752943b1b3b90e626149c3da7d5f1830b6.img.xz", - "hash": "32a2174b5f764e95dfc54cf358ba01752943b1b3b90e626149c3da7d5f1830b6", - "hash_raw": "32a2174b5f764e95dfc54cf358ba01752943b1b3b90e626149c3da7d5f1830b6", + "url": "https://commadist.azureedge.net/agnosupdate/abl-b6fba807b9bcd66a31f2afb0eba5163ec239693ad32e2e4200f6c356adfe098c.img.xz", + "hash": "b6fba807b9bcd66a31f2afb0eba5163ec239693ad32e2e4200f6c356adfe098c", + "hash_raw": "b6fba807b9bcd66a31f2afb0eba5163ec239693ad32e2e4200f6c356adfe098c", "size": 274432, "sparse": false, "full_check": true, "has_ab": true, - "ondevice_hash": "32a2174b5f764e95dfc54cf358ba01752943b1b3b90e626149c3da7d5f1830b6" + "ondevice_hash": "b6fba807b9bcd66a31f2afb0eba5163ec239693ad32e2e4200f6c356adfe098c" }, { "name": "aop", - "url": "https://commadist.azureedge.net/agnosupdate/aop-21370172e590bd4ea907a558bcd6df20dc7a6c7d38b8e62fdde18f4a512ba9e9.img.xz", - "hash": "21370172e590bd4ea907a558bcd6df20dc7a6c7d38b8e62fdde18f4a512ba9e9", - "hash_raw": "21370172e590bd4ea907a558bcd6df20dc7a6c7d38b8e62fdde18f4a512ba9e9", + "url": "https://commadist.azureedge.net/agnosupdate/aop-78b2287ca219a0811b3004c523fa0f4749e4d1fd92be3aba61699305b7943ad1.img.xz", + "hash": "78b2287ca219a0811b3004c523fa0f4749e4d1fd92be3aba61699305b7943ad1", + "hash_raw": "78b2287ca219a0811b3004c523fa0f4749e4d1fd92be3aba61699305b7943ad1", "size": 184364, "sparse": false, "full_check": true, "has_ab": true, - "ondevice_hash": "c1be2f4aac5b3af49b904b027faec418d05efd7bd5144eb4fdfcba602bcf2180" + "ondevice_hash": "6c9135446bd3fc075fcee59b887a12e49029ab1f98ed8d6d1e32c73569d47de3" }, { "name": "bluetooth", @@ -207,14 +207,14 @@ }, { "name": "devcfg", - "url": "https://commadist.azureedge.net/agnosupdate/devcfg-d7d7e52963bbedbbf8a7e66847579ca106a0a729ce2cf60f4b8d8ea4b535d620.img.xz", - "hash": "d7d7e52963bbedbbf8a7e66847579ca106a0a729ce2cf60f4b8d8ea4b535d620", - "hash_raw": "d7d7e52963bbedbbf8a7e66847579ca106a0a729ce2cf60f4b8d8ea4b535d620", + "url": "https://commadist.azureedge.net/agnosupdate/devcfg-f71df3a86958c093ba3969254c4db025187eef9385427f1ade946742939b43cc.img.xz", + "hash": "f71df3a86958c093ba3969254c4db025187eef9385427f1ade946742939b43cc", + "hash_raw": "f71df3a86958c093ba3969254c4db025187eef9385427f1ade946742939b43cc", "size": 40336, "sparse": false, "full_check": true, "has_ab": true, - "ondevice_hash": "17b229668b20305ff8fa3cd5f94716a3aaa1e5bf9d1c24117eff7f2f81ae719f" + "ondevice_hash": "2a67971602012c1b43544964709da13c322786b456a8e78568b117e8b1540ce3" }, { "name": "devinfo", @@ -339,62 +339,51 @@ }, { "name": "boot", - "url": "https://commadist.azureedge.net/agnosupdate/boot-4de8f892dbac3fa3fee1efe68ca76e23e75812e81a6577d00d52e2da1ef624ef.img.xz", - "hash": "4de8f892dbac3fa3fee1efe68ca76e23e75812e81a6577d00d52e2da1ef624ef", - "hash_raw": "4de8f892dbac3fa3fee1efe68ca76e23e75812e81a6577d00d52e2da1ef624ef", - "size": 18479104, + "url": "https://commadist.azureedge.net/agnosupdate/boot-8806802b195a5b1396a3ae8dd92a8b7711dc522f6aceafd820e871bae5c8a6d8.img.xz", + "hash": "8806802b195a5b1396a3ae8dd92a8b7711dc522f6aceafd820e871bae5c8a6d8", + "hash_raw": "8806802b195a5b1396a3ae8dd92a8b7711dc522f6aceafd820e871bae5c8a6d8", + "size": 17487872, "sparse": false, "full_check": true, "has_ab": true, - "ondevice_hash": "8d7094d774faa4e801e36b403a31b53b913b31d086f4dc682d2f64710c557e8a" + "ondevice_hash": "edca8bee1531e66953d107eeceeed2dc7b3ca46417e49d55508f94e58bf95db8" }, { "name": "system", - "url": "https://commadist.azureedge.net/agnosupdate/system-4bc3951f4aa3f70c53837dc2542d8b0666d37103b353fd81417cc7de1bbebe39.img.xz", - "hash": "cccd7073d067027396f2afd49874729757db0bbbc79853a0bf2938bd356fe164", - "hash_raw": "4bc3951f4aa3f70c53837dc2542d8b0666d37103b353fd81417cc7de1bbebe39", - "size": 5368709120, + "url": "https://commadist.azureedge.net/agnosupdate/system-ef0d879302cb29e72110e9c8d3f947c830fd7d37c8192744fc9dbea1af78501f.img.xz", + "hash": "78acfe16a7b62a3a91fc7a81f40a693e4468cec1c69df7d0b1e550aacc646113", + "hash_raw": "ef0d879302cb29e72110e9c8d3f947c830fd7d37c8192744fc9dbea1af78501f", + "size": 4718592000, "sparse": true, "full_check": false, "has_ab": true, - "ondevice_hash": "c7707f16ce7d977748677cc354e250943b4ff6c21b9a19a492053d32397cf9ec", + "ondevice_hash": "743142c5a898f27b2a1029cca42c8a5d5d1fc0096414422b850fe84c8d0b8342", "alt": { - "hash": "4bc3951f4aa3f70c53837dc2542d8b0666d37103b353fd81417cc7de1bbebe39", - "url": "https://commadist.azureedge.net/agnosupdate/system-4bc3951f4aa3f70c53837dc2542d8b0666d37103b353fd81417cc7de1bbebe39.img", - "size": 5368709120 + "hash": "ef0d879302cb29e72110e9c8d3f947c830fd7d37c8192744fc9dbea1af78501f", + "url": "https://commadist.azureedge.net/agnosupdate/system-ef0d879302cb29e72110e9c8d3f947c830fd7d37c8192744fc9dbea1af78501f.img", + "size": 4718592000 } }, { "name": "userdata_90", - "url": "https://commadist.azureedge.net/agnosupdate/userdata_90-f0c675e0fae420870c9ba8979fa246b170f4f1a7a04b49609b55b6bdfa8c1b21.img.xz", - "hash": "3d8a007bae088c5959eb9b82454013f91868946d78380fecea2b1afdfb575c02", - "hash_raw": "f0c675e0fae420870c9ba8979fa246b170f4f1a7a04b49609b55b6bdfa8c1b21", + "url": "https://commadist.azureedge.net/agnosupdate/userdata_90-14a3fc6e9bd148b9deebf6ae9df2f1b3b759e629b337e41b6895864cdd51f630.img.xz", + "hash": "52160dd01b30b3dc572226e8d549a034b03bc328e80f1f4cd6a857b6dd447687", + "hash_raw": "14a3fc6e9bd148b9deebf6ae9df2f1b3b759e629b337e41b6895864cdd51f630", "size": 96636764160, "sparse": true, "full_check": true, "has_ab": false, - "ondevice_hash": "5bfbabb8ff96b149056aa75d5b7e66a7cdd9cb4bcefe23b922c292f7f3a43462" + "ondevice_hash": "3bbc052c7793087946b0cd668c1778f930084f6b00896aeebd193dfce53fa518" }, { "name": "userdata_89", - "url": "https://commadist.azureedge.net/agnosupdate/userdata_89-06fc52be37b42690ed7b4f8c66c4611309a2dea9fca37dd9d27d1eff302eb1bf.img.xz", - "hash": "443f136484294b210318842d09fb618d5411c8bdbab9f7421d8c89eb291a8d3f", - "hash_raw": "06fc52be37b42690ed7b4f8c66c4611309a2dea9fca37dd9d27d1eff302eb1bf", + "url": "https://commadist.azureedge.net/agnosupdate/userdata_89-425c69d021f4ee2f767963bf7b991d1a492485fa465c5f5d001e1cf7de3d62a0.img.xz", + "hash": "02a8c5512754d7781d930d242be3fad01fbce652297c69dfe8722dc92b18dc09", + "hash_raw": "425c69d021f4ee2f767963bf7b991d1a492485fa465c5f5d001e1cf7de3d62a0", "size": 95563022336, "sparse": true, "full_check": true, "has_ab": false, - "ondevice_hash": "67db02b29a7e4435951c64cc962a474d048ed444aa912f3494391417cd51a074" - }, - { - "name": "userdata_30", - "url": "https://commadist.azureedge.net/agnosupdate/userdata_30-06679488f0c5c3fcfd5f351133050751cd189f705e478a979c45fc4a166d18a6.img.xz", - "hash": "875b580cb786f290a842e9187fd945657561886123eb3075a26f7995a18068f6", - "hash_raw": "06679488f0c5c3fcfd5f351133050751cd189f705e478a979c45fc4a166d18a6", - "size": 32212254720, - "sparse": true, - "full_check": true, - "has_ab": false, - "ondevice_hash": "16e27ba3c5cf9f0394ce6235ba6021b8a2de293fdb08399f8ca832fa5e4d0b9d" + "ondevice_hash": "3667d500f91b08a4671d7c09623eb6ae8fc905d9273893b50689e214005c7fa6" } ] \ No newline at end of file diff --git a/openpilot/common/hardware/tici/amplifier.py b/openpilot/common/hardware/tici/amplifier.py new file mode 100755 index 0000000000..09436e6ff4 --- /dev/null +++ b/openpilot/common/hardware/tici/amplifier.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python3 +import time +from collections import namedtuple + +from openpilot.common.i2c import SMBus + +# https://datasheets.maximintegrated.com/en/ds/MAX98089.pdf + +AmpConfig = namedtuple('AmpConfig', ['name', 'value', 'register', 'offset', 'mask']) + +CONFIG = [ + AmpConfig("MCLK prescaler", 0b01, 0x10, 4, 0b00110000), + AmpConfig("PM: enable speakers", 0b11, 0x4D, 4, 0b00110000), + AmpConfig("PM: enable DACs", 0b11, 0x4D, 0, 0b00000011), + AmpConfig("Enable PLL1", 0b1, 0x12, 7, 0b10000000), + AmpConfig("Enable PLL2", 0b1, 0x1A, 7, 0b10000000), + AmpConfig("DAI1: I2S mode", 0b00100, 0x14, 2, 0b01111100), + AmpConfig("DAI2: I2S mode", 0b00100, 0x1C, 2, 0b01111100), + AmpConfig("DAI1 Passband filtering: music mode", 0b1, 0x18, 7, 0b10000000), + AmpConfig("DAI1 voice mode gain (DV1G)", 0b00, 0x2F, 4, 0b00110000), + AmpConfig("DAI1 attenuation (DV1)", 0x0, 0x2F, 0, 0b00001111), + AmpConfig("DAI2 attenuation (DV2)", 0x0, 0x31, 0, 0b00001111), + AmpConfig("DAI2: DC blocking", 0b1, 0x20, 0, 0b00000001), + AmpConfig("DAI2: High sample rate", 0b0, 0x20, 3, 0b00001000), + AmpConfig("ALC enable", 0b1, 0x43, 7, 0b10000000), + AmpConfig("ALC/excursion limiter release time", 0b101, 0x43, 4, 0b01110000), + AmpConfig("ALC multiband enable", 0b1, 0x43, 3, 0b00001000), + AmpConfig("DAI1 EQ enable", 0b0, 0x49, 0, 0b00000001), + AmpConfig("DAI2 EQ clip detection disabled", 0b1, 0x32, 4, 0b00010000), + AmpConfig("DAI2 EQ attenuation", 0x5, 0x32, 0, 0b00001111), + AmpConfig("Excursion limiter upper corner freq", 0b100, 0x41, 4, 0b01110000), + AmpConfig("Excursion limiter lower corner freq", 0b00, 0x41, 0, 0b00000011), + AmpConfig("Excursion limiter threshold", 0b000, 0x42, 0, 0b00001111), + AmpConfig("Distortion limit (THDCLP)", 0x6, 0x46, 4, 0b11110000), + AmpConfig("Distortion limiter release time constant", 0b0, 0x46, 0, 0b00000001), + AmpConfig("Right DAC input mixer: DAI1 left", 0b0, 0x22, 3, 0b00001000), + AmpConfig("Right DAC input mixer: DAI1 right", 0b0, 0x22, 2, 0b00000100), + AmpConfig("Right DAC input mixer: DAI2 left", 0b1, 0x22, 1, 0b00000010), + AmpConfig("Right DAC input mixer: DAI2 right", 0b0, 0x22, 0, 0b00000001), + AmpConfig("DAI1 audio port selector", 0b10, 0x16, 6, 0b11000000), + AmpConfig("DAI2 audio port selector", 0b01, 0x1E, 6, 0b11000000), + AmpConfig("Enable left digital microphone", 0b1, 0x48, 5, 0b00100000), + AmpConfig("Enable right digital microphone", 0b1, 0x48, 4, 0b00010000), + AmpConfig("Enhanced volume smoothing disabled", 0b0, 0x49, 7, 0b10000000), + AmpConfig("Volume adjustment smoothing disabled", 0b0, 0x49, 6, 0b01000000), + AmpConfig("Zero-crossing detection disabled", 0b0, 0x49, 5, 0b00100000), + + AmpConfig("Left speaker output from left DAC", 0b1, 0x2B, 0, 0b11111111), + AmpConfig("Right speaker output from right DAC", 0b1, 0x2C, 0, 0b11111111), + AmpConfig("Left Speaker Mixer Gain", 0b00, 0x2D, 0, 0b00000011), + AmpConfig("Right Speaker Mixer Gain", 0b00, 0x2D, 2, 0b00001100), + AmpConfig("Left speaker output volume", 0x17, 0x3D, 0, 0b00011111), + AmpConfig("Right speaker output volume", 0x17, 0x3E, 0, 0b00011111), + + AmpConfig("DAI2 EQ enable", 0b0, 0x49, 1, 0b00000010), + AmpConfig("DAI2: DC blocking", 0b0, 0x20, 0, 0b00000001), + AmpConfig("ALC enable", 0b0, 0x43, 7, 0b10000000), + AmpConfig("DAI2 EQ attenuation", 0x2, 0x32, 0, 0b00001111), + AmpConfig("Excursion limiter upper corner freq", 0b001, 0x41, 4, 0b01110000), + AmpConfig("Excursion limiter threshold", 0b100, 0x42, 0, 0b00001111), + AmpConfig("Distortion limit (THDCLP)", 0x0, 0x46, 4, 0b11110000), + AmpConfig("Distortion limiter release time constant", 0b1, 0x46, 0, 0b00000001), + AmpConfig("Left DAC input mixer: DAI1 left", 0b0, 0x22, 7, 0b10000000), + AmpConfig("Left DAC input mixer: DAI1 right", 0b0, 0x22, 6, 0b01000000), + AmpConfig("Left DAC input mixer: DAI2 left", 0b1, 0x22, 5, 0b00100000), + AmpConfig("Left DAC input mixer: DAI2 right", 0b0, 0x22, 4, 0b00010000), + AmpConfig("Right DAC input mixer: DAI2 left", 0b0, 0x22, 1, 0b00000010), + AmpConfig("Right DAC input mixer: DAI2 right", 0b1, 0x22, 0, 0b00000001), + AmpConfig("Volume adjustment smoothing disabled", 0b1, 0x49, 6, 0b01000000), +] + +class Amplifier: + AMP_I2C_BUS = 0 + AMP_ADDRESS = 0x10 + + def __init__(self, debug=False): + self.debug = debug + + def _get_shutdown_config(self, amp_disabled: bool) -> AmpConfig: + return AmpConfig("Global shutdown", 0b0 if amp_disabled else 0b1, 0x51, 7, 0b10000000) + + def _set_configs(self, configs: list[AmpConfig]) -> None: + with SMBus(self.AMP_I2C_BUS) as bus: + for config in configs: + if self.debug: + print(f"Setting \"{config.name}\" to {config.value}:") + + old_value = bus.read_byte_data(self.AMP_ADDRESS, config.register, force=True) + new_value = (old_value & (~config.mask)) | ((config.value << config.offset) & config.mask) + bus.write_byte_data(self.AMP_ADDRESS, config.register, new_value, force=True) + + if self.debug: + print(f" Changed {hex(config.register)}: {hex(old_value)} -> {hex(new_value)}") + + def set_configs(self, configs: list[AmpConfig]) -> bool: + # retry in case panda is using the amp + tries = 15 + backoff = 0. + for i in range(tries): + try: + self._set_configs(configs) + return True + except OSError: + backoff += 0.1 + time.sleep(backoff) + print(f"Failed to set amp config, {tries - i - 1} retries left") + return False + + def set_global_shutdown(self, amp_disabled: bool) -> bool: + return self.set_configs([self._get_shutdown_config(amp_disabled), ]) + + def initialize_configuration(self) -> bool: + cfgs = [ + self._get_shutdown_config(True), + *CONFIG, + self._get_shutdown_config(False), + ] + return self.set_configs(cfgs) + + +if __name__ == "__main__": + amp = Amplifier() + amp.initialize_configuration() diff --git a/openpilot/common/hardware/tici/hardware.h b/openpilot/common/hardware/tici/hardware.h new file mode 100644 index 0000000000..a1a8090c35 --- /dev/null +++ b/openpilot/common/hardware/tici/hardware.h @@ -0,0 +1,87 @@ +#pragma once + +#include +#include +#include +#include +#include // for std::clamp + +#include "common/util.h" +#include "common/hardware/base.h" + +class HardwareTici : public HardwareNone { +public: + static std::string get_name() { + static const std::string name = []() { + std::string model = util::read_file("/sys/firmware/devicetree/base/model"); + return util::strip(model.substr(std::string("comma ").size())); + }(); + return name; + } + + static cereal::InitData::DeviceType get_device_type() { + static const std::map device_map = { + {"tizi", cereal::InitData::DeviceType::TIZI}, + {"mici", cereal::InitData::DeviceType::MICI} + }; + static const auto it = device_map.find(get_name()); + assert(it != device_map.end()); + return it->second; + } + + static std::string get_serial() { + static std::string serial(""); + if (serial.empty()) { + std::ifstream stream("/proc/cmdline"); + std::string cmdline; + std::getline(stream, cmdline); + + auto start = cmdline.find("serialno="); + if (start == std::string::npos) { + serial = "cccccc"; + } else { + auto end = cmdline.find(" ", start + 9); + serial = cmdline.substr(start + 9, end - start - 9); + } + } + return serial; + } + + static void set_ir_power(int percent) { + auto device = get_device_type(); + if (device == cereal::InitData::DeviceType::TIZI) { + return; + } + + int value = util::map_val(std::clamp(percent, 0, 100), 0, 100, 0, 300); + std::ofstream("/sys/class/leds/led:switch_2/brightness") << 0 << "\n"; + std::ofstream("/sys/class/leds/led:torch_2/brightness") << value << "\n"; + std::ofstream("/sys/class/leds/led:switch_2/brightness") << value << "\n"; + } + + static std::map get_init_logs() { + std::map ret = { + {"/BUILD", util::read_file("/BUILD")}, + {"lsblk", util::check_output("lsblk -o NAME,SIZE,STATE,VENDOR,MODEL,REV,SERIAL")}, + {"SOM ID", util::read_file("/sys/devices/platform/vendor/vendor:gpio-som-id/som_id")}, + }; + + std::string bs = util::check_output("abctl --boot_slot"); + ret["boot slot"] = bs.substr(0, bs.find_first_of("\n")); + + std::string temp = util::read_file("/dev/disk/by-partlabel/ssd"); + temp.erase(temp.find_last_not_of(std::string("\0\r\n", 3))+1); + ret["boot temp"] = temp; + + // TODO: log something from system and boot + for (std::string part : {"xbl", "abl", "aop", "devcfg", "xbl_config"}) { + for (std::string slot : {"a", "b"}) { + std::string partition = part + "_" + slot; + std::string hash = util::check_output("sha256sum /dev/disk/by-partlabel/" + partition); + ret[partition] = hash.substr(0, hash.find_first_of(" ")); + } + } + + return ret; + } +}; diff --git a/openpilot/common/hardware/tici/hardware.py b/openpilot/common/hardware/tici/hardware.py new file mode 100644 index 0000000000..aa125ed97d --- /dev/null +++ b/openpilot/common/hardware/tici/hardware.py @@ -0,0 +1,419 @@ +import configparser +import json +import os +import socket +import subprocess +import time +from functools import cached_property, lru_cache +from pathlib import Path + +from openpilot.cereal import log +from openpilot.common.utils import sudo_read, sudo_write +from openpilot.common.gpio import gpio_set, gpio_init, get_irqs_for_action +from openpilot.common.esim.base import LPABase +from openpilot.common.hardware.base import HardwareBase, ThermalConfig, ThermalZone +from openpilot.common.esim.lpa import TiciLPA +from openpilot.common.hardware.tici.pins import GPIO +from openpilot.common.hardware.tici.amplifier import Amplifier + +MODEM_STATE_PATH = "/dev/shm/modem" + +NetworkType = log.DeviceState.NetworkType +NetworkStrength = log.DeviceState.NetworkStrength + + +def affine_irq(val, action): + irqs = get_irqs_for_action(action) + if len(irqs) == 0: + print(f"No IRQs found for '{action}'") + return + + for i in irqs: + sudo_write(str(val), f"/proc/irq/{i}/smp_affinity_list") + +@lru_cache +def get_device_type(): + # lru_cache and cache can cause memory leaks when used in classes + with open("/sys/firmware/devicetree/base/model") as f: + model = f.read().strip('\x00') + return model.split('comma ')[-1] + +def wpa_supplicant_cmd(cmd: str, timeout: float = 0.2) -> dict[str, str]: + with socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) as sock: + sock.settimeout(timeout) + sock.bind(f"\0openpilot-wpa-{os.getpid()}-{time.monotonic_ns()}") + sock.connect("/run/wpa_supplicant/wlan0") + sock.send(cmd.encode()) + + while True: + out = sock.recv(8192).decode("utf-8", "replace") + if out.startswith("<"): + continue + if out.startswith("FAIL"): + return {} + return dict(l.split("=", 1) for l in out.splitlines() if "=" in l) + +def get_default_route_iface(): + with open("/proc/net/route") as f: + routes = [(int(route[6]), route[0]) for line in f.readlines()[1:] if (route := line.split())[1] == "00000000" and int(route[3], 16) & 0x1] + return min(routes)[1] if routes else None + +class Tici(HardwareBase): + @cached_property + def amplifier(self): + if self.get_device_type() == "mici": + return None + return Amplifier() + + def get_modem_state(self) -> dict: + try: + with open(MODEM_STATE_PATH) as f: + return json.load(f) + except (FileNotFoundError, json.JSONDecodeError): + return {} + + def get_os_version(self): + with open("/VERSION") as f: + return f.read().strip() + + def get_device_type(self): + return get_device_type() + + def reboot(self, reason=None): + subprocess.check_output(["sudo", "reboot"]) + + def uninstall(self): + Path("/data/__system_reset__").touch() + os.sync() + self.reboot() + + def get_serial(self): + return self.get_cmdline()['androidboot.serialno'] + + def get_voltage(self): + with open("/sys/class/hwmon/hwmon1/in1_input") as f: + return int(f.read()) + + def get_current(self): + with open("/sys/class/hwmon/hwmon1/curr1_input") as f: + return int(f.read()) + + def set_ir_power(self, percent: int): + if self.get_device_type() == "tizi": + return + + value = int((percent / 100) * 300) + with open("/sys/class/leds/led:switch_2/brightness", "w") as f: + f.write("0\n") + with open("/sys/class/leds/led:torch_2/brightness", "w") as f: + f.write(f"{value}\n") + with open("/sys/class/leds/led:switch_2/brightness", "w") as f: + f.write(f"{value}\n") + + def get_network_type(self): + try: + if (iface := get_default_route_iface()): + if iface.startswith('wlan'): + return NetworkType.wifi + if iface.startswith('eth'): + return NetworkType.ethernet + except Exception: + pass + + ms = self.get_modem_state() + if ms.get('connected'): + nt = ms.get('network_type', '') + if nt == 'nr': + return NetworkType.cell5G + elif nt == 'lte': + return NetworkType.cell4G + elif nt in ('utran', 'umts'): + return NetworkType.cell3G + elif nt == 'gsm': + return NetworkType.cell2G + return NetworkType.none + + def get_sim_info(self): + ms = self.get_modem_state() + sim_id = ms.get('iccid', '') + return { + 'sim_id': sim_id, + 'mcc_mnc': ms.get('mcc_mnc') or None, + 'network_type': ["Unknown"], + 'sim_state': ["ABSENT"] if not sim_id else ["READY"], + 'data_connected': ms.get('connected', False), + } + + def get_sim_lpa(self) -> LPABase: + return TiciLPA() + + def get_imei(self): + return self.get_modem_state().get('imei', '') + + def get_network_info(self): + if self.get_device_type() == "mici": + return None + + ms = self.get_modem_state() + return { + 'technology': ms.get('network_type', '').upper() if ms.get('network_type') else '', + 'operator': ms.get('operator', ''), + 'band': ms.get('band', ''), + 'channel': ms.get('channel', 0), + 'extra': ms.get('extra', ''), + 'state': ms.get('state', 'UNKNOWN'), + } + + def parse_strength(self, percentage): + if percentage < 25: + return NetworkStrength.poor + elif percentage < 50: + return NetworkStrength.moderate + elif percentage < 75: + return NetworkStrength.good + else: + return NetworkStrength.great + + def get_network_strength(self, network_type): + network_strength = NetworkStrength.unknown + + try: + if network_type == NetworkType.none: + pass + elif network_type == NetworkType.ethernet: + network_strength = NetworkStrength.great + elif network_type == NetworkType.wifi: + rssi = wpa_supplicant_cmd("SIGNAL_POLL").get("RSSI") + if rssi is not None: + dbm = int(rssi) + if -100 < dbm <= 0: + network_strength = self.parse_strength(120 + max(-100, min(-20, dbm))) + else: # Cellular + network_strength = self.parse_strength(self.get_modem_state().get('signal_quality', 0)) + except Exception: + pass + + return network_strength + + def get_network_metered(self, network_type) -> bool: + if network_type in (NetworkType.cell2G, NetworkType.cell3G, NetworkType.cell4G, NetworkType.cell5G): + from openpilot.common.params import Params + return Params().get_bool("GsmMetered") + try: + if network_type == NetworkType.wifi: + ssid = wpa_supplicant_cmd("STATUS").get("ssid", "") + if ssid: + # wpa_supplicant escapes non-printable bytes as \xNN; NM keyfile stores ASCII SSIDs as a literal and others as a byte;byte; list + ssid_bytes = ssid.encode().decode('unicode_escape').encode('latin-1') + ssid_keyfile_list = ';'.join(str(b) for b in ssid_bytes) + ';' + + nm_dirs = ("/run/NetworkManager/system-connections", "/data/etc/NetworkManager/system-connections") + for fpath in (p for d in nm_dirs for p in Path(d).glob("*.nmconnection")): + raw = sudo_read(str(fpath)) + if not raw: + continue + cp = configparser.ConfigParser(interpolation=None) + try: + cp.read_string(raw) + keyfile_ssid = cp.get("wifi", "ssid", fallback="") + if keyfile_ssid != ssid and keyfile_ssid != ssid_keyfile_list: + continue + metered = cp.getint("connection", "metered", fallback=0) + except (configparser.Error, ValueError): + continue + if metered == 1: # NM_METERED_YES + return True + if metered == 2: # NM_METERED_NO + return False + break + except Exception: + pass + + return super().get_network_metered(network_type) + + def get_modem_temperatures(self): + return self.get_modem_state().get('temperatures', []) + + def get_current_power_draw(self): + return (self.read_param_file("/sys/class/hwmon/hwmon1/power1_input", int) / 1e6) + + def get_som_power_draw(self): + return (self.read_param_file("/sys/class/power_supply/bms/voltage_now", int) * self.read_param_file("/sys/class/power_supply/bms/current_now", int) / 1e12) + + def shutdown(self): + subprocess.run("sudo poweroff", shell=True) + + def get_thermal_config(self): + intake, exhaust, gnss, bottomSoc = None, None, None, None + if self.get_device_type() == "mici": + gnss = ThermalZone("gnss") + intake = ThermalZone("intake") + exhaust = ThermalZone("exhaust") + bottomSoc = ThermalZone("bottom_soc") + return ThermalConfig(cpu=[ThermalZone(f"cpu{i}-silver-usr") for i in range(4)] + + [ThermalZone(f"cpu{i}-gold-usr") for i in range(4)], + gpu=[ThermalZone("gpu0-usr"), ThermalZone("gpu1-usr")], + dsp=ThermalZone("compute-hvx-usr"), + memory=ThermalZone("ddr-usr"), + pmic=[ThermalZone("pm8998_tz"), ThermalZone("pm8005_tz")], + intake=intake, + exhaust=exhaust, + gnss=gnss, + bottomSoc=bottomSoc) + + def set_display_power(self, on): + try: + with open("/sys/class/backlight/panel0-backlight/bl_power", "w") as f: + f.write("0" if on else "4") + except Exception: + pass + + def set_screen_brightness(self, percentage): + try: + with open("/sys/class/backlight/panel0-backlight/max_brightness") as f: + max_brightness = float(f.read().strip()) + + val = int(percentage * (max_brightness / 100.)) + with open("/sys/class/backlight/panel0-backlight/brightness", "w") as f: + f.write(str(val)) + except Exception: + pass + + def get_screen_brightness(self): + try: + with open("/sys/class/backlight/panel0-backlight/max_brightness") as f: + max_brightness = float(f.read().strip()) + + with open("/sys/class/backlight/panel0-backlight/brightness") as f: + return int(float(f.read()) / (max_brightness / 100.)) + except Exception: + return 0 + + def set_power_save(self, powersave_enabled): + # amplifier, 100mW at idle + if self.amplifier is not None: + self.amplifier.set_global_shutdown(amp_disabled=powersave_enabled) + if not powersave_enabled: + self.amplifier.initialize_configuration() + + # *** CPU config *** + + # offline big cluster + for i in range(4, 8): + val = '0' if powersave_enabled else '1' + sudo_write(val, f'/sys/devices/system/cpu/cpu{i}/online') + + for n in ('0', '4'): + if powersave_enabled and n == '4': + continue + gov = 'ondemand' if powersave_enabled else 'performance' + sudo_write(gov, f'/sys/devices/system/cpu/cpufreq/policy{n}/scaling_governor') + if not powersave_enabled: + # cap max core freq to 1689 Mhz + sudo_write('1689600', f'/sys/devices/system/cpu/cpufreq/policy{n}/scaling_max_freq') + + # *** IRQ config *** + + # GPU, modeld core + affine_irq(7, "kgsl-3d0") + + # camerad core + camera_irqs = ("a5", "cci", "cpas_camnoc", "cpas-cdm", "csid", "ife", "csid-lite", "ife-lite") + for n in camera_irqs: + affine_irq(6, n) + + def get_gpu_usage_percent(self): + try: + with open('/sys/class/kgsl/kgsl-3d0/gpubusy') as f: + used, total = f.read().strip().split() + return 100.0 * int(used) / int(total) + except Exception: + return 0 + + def initialize_hardware(self): + if self.amplifier is not None: + self.amplifier.initialize_configuration() + + # Allow hardwared to write engagement status to kmsg + subprocess.run("sudo chmod a+w /dev/kmsg", shell=True) + + # Ensure fan gpio is enabled so fan runs until shutdown, also turned on at boot by the ABL + gpio_init(GPIO.SOM_ST_IO, True) + gpio_set(GPIO.SOM_ST_IO, True) + + # *** IRQ config *** + + # mask off big cluster from default affinity + sudo_write("f", "/proc/irq/default_smp_affinity") + + # move these off the default core + affine_irq(1, "msm_vidc") # encoders + affine_irq(1, "i2c_geni") # sensors + + # *** GPU config *** + # https://github.com/commaai/agnos-kernel-sdm845/blob/master/arch/arm64/boot/dts/qcom/sdm845-gpu.dtsi#L216 + affine_irq(5, "fts_ts") # touch + affine_irq(5, "msm_drm") # display + sudo_write("1", "/sys/class/kgsl/kgsl-3d0/min_pwrlevel") + sudo_write("1", "/sys/class/kgsl/kgsl-3d0/max_pwrlevel") + sudo_write("1", "/sys/class/kgsl/kgsl-3d0/force_bus_on") + sudo_write("1", "/sys/class/kgsl/kgsl-3d0/force_clk_on") + sudo_write("1", "/sys/class/kgsl/kgsl-3d0/force_rail_on") + sudo_write("1000", "/sys/class/kgsl/kgsl-3d0/idle_timer") + sudo_write("performance", "/sys/class/kgsl/kgsl-3d0/devfreq/governor") + sudo_write("710", "/sys/class/kgsl/kgsl-3d0/max_clock_mhz") + + # setup governors + sudo_write("performance", "/sys/class/devfreq/soc:qcom,cpubw/governor") + sudo_write("performance", "/sys/class/devfreq/soc:qcom,memlat-cpu0/governor") + sudo_write("performance", "/sys/class/devfreq/soc:qcom,memlat-cpu4/governor") + + # *** VIDC (encoder) config *** + sudo_write("N", "/sys/kernel/debug/msm_vidc/clock_scaling") + sudo_write("Y", "/sys/kernel/debug/msm_vidc/disable_thermal_mitigation") + + # pandad core + affine_irq(3, "spi_geni") # SPI + try: + pid = subprocess.check_output(["pgrep", "-f", "spi0"], encoding='utf8').strip() + subprocess.call(["sudo", "chrt", "-f", "-p", "1", pid]) + subprocess.call(["sudo", "taskset", "-pc", "3", pid]) + except subprocess.CalledProcessError as e: + print(str(e)) + + def get_modem_data_usage(self): + ms = self.get_modem_state() + return ms.get('tx_bytes', -1), ms.get('rx_bytes', -1) + + def reset_internal_panda(self): + gpio_init(GPIO.STM_RST_N, True) + gpio_init(GPIO.STM_BOOT0, True) + + gpio_set(GPIO.STM_RST_N, True) + gpio_set(GPIO.STM_BOOT0, False) + time.sleep(0.01) + gpio_set(GPIO.STM_RST_N, False) + + def recover_internal_panda(self): + gpio_init(GPIO.STM_RST_N, True) + gpio_init(GPIO.STM_BOOT0, True) + + gpio_set(GPIO.STM_RST_N, True) + gpio_set(GPIO.STM_BOOT0, True) + time.sleep(0.01) + gpio_set(GPIO.STM_RST_N, False) + time.sleep(0.01) + gpio_set(GPIO.STM_BOOT0, False) + + def booted(self): + # this normally boots within 8s, but on rare occasions takes 30+s + encoder_state = sudo_read("/sys/kernel/debug/msm_vidc/core0/info") + if "Core state: 0" in encoder_state and (time.monotonic() < 60*2): + return False + return True + +if __name__ == "__main__": + t = Tici() + t.initialize_hardware() + t.set_power_save(False) + print(t.get_sim_info()) diff --git a/system/hardware/tici/id_rsa b/openpilot/common/hardware/tici/id_rsa similarity index 100% rename from system/hardware/tici/id_rsa rename to openpilot/common/hardware/tici/id_rsa diff --git a/openpilot/common/hardware/tici/modem.py b/openpilot/common/hardware/tici/modem.py new file mode 100755 index 0000000000..54251d4815 --- /dev/null +++ b/openpilot/common/hardware/tici/modem.py @@ -0,0 +1,592 @@ +#!/usr/bin/env python3 +import fcntl +import json +import logging +import os +import signal +import subprocess +import tempfile +import time + +from ipaddress import IPv4Address, AddressValueError + +from enum import Enum + +from openpilot.common.serial import Serial + +logging.basicConfig( + level=logging.INFO, + format="%(asctime)s.%(msecs)03d %(levelname)-7s modem: %(message)s", + datefmt="%H:%M:%S", +) + +AT_PORT = "/dev/modem_at0" +PPP_PORT = "/dev/modem_at1" +STATE_PATH = "/dev/shm/modem" +AT_LOCK = "/dev/shm/modem.lock" # shared with LPA +AT_INIT = [ + "ATE0", # disable command echo + "ATV1", # verbose result codes (CONNECT/BUSY/NO CARRIER, not numeric) + "AT+CMEE=1", # numeric +CME ERROR codes on failures (per 3GPP 27.007) + "ATX4", # extended result codes: busy + dial tone detection, line speed in CONNECT + "AT&C1", # DCD pin follows carrier state (V.250 default) + "AT+CREG=2", # registration URCs include location info + "AT+CGREG=2", # GPRS registration URCs include location info +] +CREG = {0: "not_registered", 1: "home", 2: "searching", 3: "denied", 4: "unknown", 5: "roaming"} +# 3GPP TS 27.007 +COPS -> network type +NETWORK_TYPE = {0: "gsm", 1: "gsm", 3: "gsm", 8: "gsm", + 2: "utran", 4: "utran", 5: "utran", 6: "utran", + 7: "lte", 9: "lte", 10: "lte", + 11: "nr", 12: "nr", 13: "nr"} + +DIAL_CID = 1 +WEBBING_ICCID_PREFIX = "8985235" + +PPPD_CMD = [ + "sudo", "pppd", PPP_PORT, "460800", "noauth", "nodetach", "noipdefault", "usepeerdns", + "nodefaultroute", "connect", + "/usr/sbin/chat -v ABORT 'NO CARRIER' ABORT 'NO DIALTONE' ABORT 'BUSY' " + + f"ABORT 'NO ANSWER' ABORT 'ERROR' TIMEOUT 5 '' AT OK ATD*99***{DIAL_CID}# CONNECT ''", + "lcp-echo-interval", "30", "lcp-echo-failure", "4", "mtu", "1500", "mru", "1500", + "novj", "novjccomp", "ipcp-accept-local", "ipcp-accept-remote", "nomagic", + "user", '""', "password", '""', +] +INITIAL_STATE: dict[str, object] = { + "seconds_since_boot": 0, + "state": "INITIALIZING", + "connected": False, "ip_address": "", + "iccid": "", "mcc_mnc": "", "imei": "", "modem_version": "", + "signal_strength": 0, "signal_quality": 0, + "network_type": "unknown", "operator": "", "band": "", "channel": 0, + "registration": "unknown", "temperatures": [], "extra": "", + "tx_bytes": 0, "rx_bytes": 0, +} + + +class State(Enum): + INITIALIZING = "INITIALIZING" + SEARCHING = "SEARCHING" + CONNECTING = "CONNECTING" + CONNECTED = "CONNECTED" + DISCONNECTING = "DISCONNECTING" + + +STATE_WAIT = 1.0 # seconds to wait after each state handler returns + + +class PPPSession: + """Owns pppd lifecycle, fail tracking, and PPP routing.""" + MAX_FAILS = 3 + + def __init__(self): + self._proc: subprocess.Popen | None = None + self._fails = 0 + self._peer = "" + + def start(self): + self._proc = subprocess.Popen(PPPD_CMD, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + self._peer = "" + logging.info(f"PPP dialing CID {DIAL_CID}") + + def kill(self): + subprocess.run(["sudo", "killall", "-9", "pppd"], capture_output=True) + self._peer = "" + + @staticmethod + def reset_data_port(): + """Drop DTR on PPP_PORT so the modem terminates any stuck PPP session.""" + try: + with Serial(PPP_PORT, baudrate=460800, timeout=1) as s: + s.dtr = False + time.sleep(0.2) + s.dtr = True + except Exception as e: + logging.warning(f"data port reset failed: {e}") + + def has_exited(self) -> bool: + return self._proc is not None and self._proc.poll() is not None + + def reset_fail_counter(self): + self._fails = 0 + + def record_fail(self) -> bool: + """Bump fail counter; return True if at the give-up limit.""" + self._fails += 1 + return self._fails >= self.MAX_FAILS + + @property + def fails(self) -> int: + return self._fails + + def maybe_install_routes(self, ip: str, peer: str) -> bool: + """Install routes if peer changed; kill the session on failure so the state machine reconnects.""" + if not peer or peer == self._peer: + return False + try: + IPv4Address(ip) + IPv4Address(peer) + except AddressValueError: + logging.warning(f"refusing route install with non-IPv4 ip={ip!r} peer={peer!r}") + self.kill() + return False + self.cleanup_routes() + cmds = [ + ["sudo", "ip", "route", "add", "default", "via", peer, "dev", "ppp0", "metric", "1000"], + ["sudo", "ip", "route", "add", "default", "via", peer, "dev", "ppp0", "table", "1000"], + ["sudo", "ip", "rule", "add", "from", ip, "table", "1000"], + ] + for cmd in cmds: + r = subprocess.run(cmd, capture_output=True, text=True) + if r.returncode != 0: + logging.warning(f"route install failed ({' '.join(cmd[1:])}): {r.stderr.strip()}") + self.cleanup_routes() + self.kill() + return False + logging.info(f"route set up for {ip} via {peer}") + self._peer = peer + return True + + def maybe_install_dns(self, dns_servers: list[str]) -> bool: + """Register DNS servers with systemd-resolved; kill the session on failure to force a retry.""" + if not dns_servers: + return False + for cmd in (["sudo", "resolvectl", "dns", "ppp0", *dns_servers], + ["sudo", "resolvectl", "default-route", "ppp0", "yes"]): + r = subprocess.run(cmd, capture_output=True, text=True) + if r.returncode != 0: + logging.warning(f"resolvectl failed ({' '.join(cmd[1:])}): {r.stderr.strip()}") + self.kill() + return False + logging.info(f"resolvectl: ppp0 DNS = {dns_servers}") + return True + + @staticmethod + def cleanup_routes(): + subprocess.run(["sudo", "ip", "route", "del", "default", "dev", "ppp0"], capture_output=True) + subprocess.run(["sudo", "ip", "route", "flush", "table", "1000"], capture_output=True) + # rules don't have a flush; delete until none remain + while subprocess.run(["sudo", "ip", "rule", "del", "table", "1000"], capture_output=True).returncode == 0: + pass + subprocess.run(["sudo", "resolvectl", "revert", "ppp0"], capture_output=True) + + +class Modem: + def __init__(self): + self._ppp = PPPSession() + self._sim_change = False + self._apn = "" # blank = network-provided via PCO + self._roaming_allowed = True + self.running = True + self.S = INITIAL_STATE.copy() + + @staticmethod + def _read_param(key): + try: + with open(f"/data/params/d/{key}") as f: + return f.read().strip() + except FileNotFoundError: + return "" + + @staticmethod + def _parse_reg(v: str) -> str: + try: + return CREG.get(int(v.split(",")[1].strip('"')), "unknown") + except (ValueError, IndexError): + return "unknown" + + @staticmethod + def _has_modem_manager() -> bool: + return os.path.isfile("/lib/systemd/system/ModemManager.service") + + def _is_roaming_allowed(self) -> bool: + if self.S["iccid"].startswith(WEBBING_ICCID_PREFIX): + return True + return self._read_param("GsmRoaming") == "1" + + def _publish_state(self, **kwargs): + self.S.update(kwargs) + self.S["seconds_since_boot"] = time.monotonic() + with tempfile.NamedTemporaryFile(mode="w", dir="/dev/shm", delete=False) as f: + json.dump(self.S, f, indent=2) + os.chmod(f.name, 0o644) + os.replace(f.name, STATE_PATH) + + def _at(self, cmd): + """Send AT command, return response lines. [] on error or if LPA holds port.""" + fd = os.open(AT_LOCK, os.O_CREAT | os.O_RDWR, 0o666) + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError: + os.close(fd) + return [] + try: + with Serial(AT_PORT, baudrate=9600, timeout=5) as ser: + ser.reset_input_buffer() + ser.write((cmd + "\r").encode()) + lines = [] + while True: + raw = ser.readline() + if not raw: + raise TimeoutError("AT timeout") + line = raw.decode(errors="ignore").strip() + if not line: + continue + if line == "OK": + break + if line == "ERROR" or line.startswith("+CME ERROR"): + raise RuntimeError(line) + lines.append(line) + return lines + except (RuntimeError, TimeoutError, OSError) as e: + logging.info(f"AT {cmd} failed: {e}") + return [] + finally: + fcntl.flock(fd, fcntl.LOCK_UN) + os.close(fd) + + def _atv(self, cmd, pfx): + for line in self._at(cmd): + if pfx in line and ":" in line: + return line.split(":", 1)[1].strip() + return None + + def _init_at_channel(self) -> bool: + """Run AT_INIT and confirm ATE0 took effect. Returns False if echo is still on.""" + for c in AT_INIT: + self._at(c) + r = self._at("AT+CGMI") + return bool(r) and not r[0].startswith("AT") + + def _configure_modem(self, modem_version: str): + if not modem_version.startswith("EG25"): + return + cmds = [ + # clear initial EPS bearer APN (some carriers reject the default) + 'AT+CGDCONT=0,"IP",""', + + # SIM hot swap + 'AT+QSIMDET=1,0', + 'AT+QSIMSTAT=1', + + # configure modem as data-centric + 'AT+QNVW=5280,0,"0102000000000000"', + 'AT+QNVFW="/nv/item_files/ims/IMS_enable",00', + 'AT+QNVFW="/nv/item_files/modem/mmode/ue_usage_setting",01', + ] + for c in cmds: + self._at(c) + + def _do_initializing(self): + if not os.path.exists(AT_PORT): + return State.INITIALIZING + logging.info("port found, initializing") + self._ppp.kill() + self._ppp.cleanup_routes() + + if not self._init_at_channel(): + logging.warning("AT echo still on, retrying") + return State.INITIALIZING + + identity = self._read_identity() + if not identity["iccid"] or not identity["imei"]: + logging.warning(f"identity read incomplete: {identity}, retrying") + return State.INITIALIZING + + self._configure_modem(identity["modem_version"]) + + self.S.update(identity) + self._apn = self._read_param("GsmApn") + self._roaming_allowed = self._is_roaming_allowed() + # blank APN lets the carrier supply one via PCO + self._at(f'AT+CGDCONT={DIAL_CID},"IP","{self._apn}"') + logging.info(f"APN '{self._apn or '(network-provided)'}' written to CID {DIAL_CID}, roaming={'on' if self._roaming_allowed else 'off'}") + + self._sim_change = False # clear since we just re-read identity with the new SIM + self._publish_state(**identity) + return State.SEARCHING + + def _read_identity(self): + def first_line(cmd): + r = self._at(cmd) + return r[0].strip() if r else "" + + imei = first_line("AT+CGSN") + if not (imei.isdigit() and 14 <= len(imei) <= 17): # 3GPP TS 23.003 + imei = "" + + iccid = (self._atv("AT+QCCID", "+QCCID:") or "").rstrip("F") + if not iccid.isdigit(): + iccid = "" + + imsi = first_line("AT+CIMI") + mcc_mnc = imsi[:6] if imsi.isdigit() and len(imsi) >= 6 else "" + + modem_version = first_line("AT+GMR") + + logging.info(f"imei={imei} iccid={iccid} mcc_mnc={mcc_mnc} ver={modem_version}") + return {"imei": imei, "iccid": iccid, "mcc_mnc": mcc_mnc, "modem_version": modem_version} + + def _do_searching(self): + new_roaming = self._is_roaming_allowed() + if new_roaming != self._roaming_allowed: + logging.info(f"roaming changed: {self._roaming_allowed} -> {new_roaming}") + self._roaming_allowed = new_roaming + + v = self._atv("AT+CREG?", "+CREG:") + if not v: + return self._searching_idle() + + reg = self._parse_reg(v) + greg = self._parse_reg(self._atv("AT+CGREG?", "+CGREG:") or "") + logging.debug(f"creg={reg} cgreg={greg} roaming_allowed={self._roaming_allowed}") + + if reg == "roaming" and not self._roaming_allowed: + self._publish_state(registration=reg) + return State.SEARCHING + + if reg in ("home", "roaming") and greg in ("home", "roaming"): + self._publish_state(registration=reg) + return State.CONNECTING + + if reg != self.S.get("registration"): + self._publish_state(registration=reg) + return self._searching_idle() + + def _searching_idle(self): + if self._sim_change or not os.path.exists(AT_PORT): + logging.info(f"-> reconnecting (sim_change={self._sim_change} port={os.path.exists(AT_PORT)})") + return State.DISCONNECTING + return State.SEARCHING + + def _do_connecting(self): + logging.info("starting pppd") + self._ppp.reset_fail_counter() + self._sim_change = False + self._ppp.start() + return State.CONNECTED + + def _handle_pppd_exit(self): + if self._sim_change or not os.path.exists(AT_PORT): + return State.DISCONNECTING + give_up = self._ppp.record_fail() + if give_up: + logging.warning(f"PPP fail {self._ppp.fails}/{self._ppp.MAX_FAILS}, reconnecting") + return State.DISCONNECTING + logging.warning(f"PPP fail {self._ppp.fails}/{self._ppp.MAX_FAILS}, retrying") + self._ppp.reset_data_port() + if not os.path.exists(AT_PORT): + return State.DISCONNECTING + self._ppp.start() + return State.CONNECTED + + def _params_changed(self) -> bool: + new_apn = self._read_param("GsmApn") + if new_apn != self._apn: + logging.info(f"GsmApn changed: '{self._apn}' -> '{new_apn}'") + return True + new_roaming = self._is_roaming_allowed() + if new_roaming != self._roaming_allowed: + logging.info(f"roaming changed: {self._roaming_allowed} -> {new_roaming}") + return True + return False + + def _check_iccid(self, state): + if state in (State.INITIALIZING, State.DISCONNECTING) or not self.S["iccid"]: + return + iccid = (self._atv("AT+QCCID", "+QCCID:") or "").rstrip("F") + if iccid and iccid != self.S["iccid"]: + logging.warning(f"iccid changed: {self.S['iccid']} -> {iccid}") + self._sim_change = True + + def _do_connected(self): + if self._ppp.has_exited(): + return self._handle_pppd_exit() + + if self._sim_change or not os.path.exists(AT_PORT) or self._params_changed(): + return State.DISCONNECTING + + self._poll() + return State.CONNECTED + + def _do_disconnecting(self): + logging.warning("reconnecting") + self._publish_state(**INITIAL_STATE) + self._ppp.kill() + self._ppp.cleanup_routes() + self._ppp.reset_data_port() + self._sim_change = False + return State.INITIALIZING + + def _poll_signal(self) -> dict: + v = self._atv("AT+CSQ", "+CSQ:") + if not v: + return {} + try: + rssi = int(v.split(",")[0]) + if rssi == 99: + return {} + return {"signal_strength": rssi, "signal_quality": min(100, int(rssi / 31 * 100))} + except (ValueError, IndexError): + return {} + + def _poll_operator(self) -> dict: + v = self._atv("AT+COPS?", "+COPS:") + if not v: + return {} + p = v.split(",") + out: dict = {} + try: + if len(p) >= 3: + out["operator"] = p[2].strip('"') + if len(p) >= 4: + out["network_type"] = NETWORK_TYPE.get(int(p[3]), "unknown") + except (ValueError, IndexError): + pass + return out + + def _poll_band(self) -> dict: + v = self._atv("AT+QNWINFO", "+QNWINFO:") + if not v: + return {} + info = v.replace('"', '').split(",") + try: + if len(info) >= 4: + return {"band": info[2], "channel": int(info[3])} + except ValueError: + pass + return {} + + def _poll_extra(self) -> dict: + v = self._atv('AT+QENG="servingcell"', "+QENG:") + return {"extra": v.replace('"', '')} if v else {} + + def _poll_temps(self) -> dict: + v = self._atv("AT+QTEMP", "+QTEMP:") + if not v: + return {} + try: + return {"temperatures": [t for t in (int(x) for x in v.split(",") if x.strip()) if t != 255]} + except (ValueError, IndexError): + return {} + + def _poll_iface(self) -> dict: + try: + r = subprocess.run(["ip", "-4", "addr", "show", "ppp0"], capture_output=True, text=True, timeout=2) + ip, peer = "", "" + for line in r.stdout.splitlines(): + # `inet 10.x.x.x peer 10.64.64.64/32 ...` + parts = line.strip().split() + if "inet" in parts: + i = parts.index("inet") + ip = parts[i + 1].split("/")[0] + if "peer" in parts: + peer = parts[parts.index("peer") + 1].split("/")[0] + break + if ip: + if self._ppp.maybe_install_routes(ip, peer): + self._ppp.maybe_install_dns(self._read_cellular_dns()) + return {"ip_address": ip, "connected": True} + if self.S["connected"]: + return {"connected": False, "ip_address": ""} + except Exception: + pass + return {} + + def _read_cellular_dns(self) -> list[str]: + v = self._atv(f"AT+CGCONTRDP={DIAL_CID}", "+CGCONTRDP:") + if not v: + return [] + # +CGCONTRDP: ,,,,,,,... + fields = [f.strip().strip('"') for f in v.split(",")] + dns_servers = [] + for d in fields[5:7]: + try: + dns_servers.append(str(IPv4Address(d))) + except (AddressValueError, ValueError): + pass + if not dns_servers: + dns_servers = [ + "8.8.8.8", # Google + "1.1.1.1", # Cloudflare + ] + logging.warning(f"no cellular DNS servers reported by modem: {v!r}; using fallback {dns_servers}") + return dns_servers + + def _poll_byte_counters(self) -> dict: + try: + with open("/sys/class/net/ppp0/statistics/tx_bytes") as f: + tx = int(f.read().strip()) + with open("/sys/class/net/ppp0/statistics/rx_bytes") as f: + rx = int(f.read().strip()) + except Exception: + return {} + return {"tx_bytes": tx, "rx_bytes": rx} + + def _poll(self): + s: dict = {} + for fn in (self._poll_signal, self._poll_operator, self._poll_band, + self._poll_extra, self._poll_temps, self._poll_iface, + self._poll_byte_counters): + s.update(fn()) + if s: + self._publish_state(**s) + + def run(self): + logging.info("starting") + self._publish_state(state=State.INITIALIZING.value) + if self._has_modem_manager(): + subprocess.run(["sudo", "systemctl", "mask", "--runtime", "ModemManager"], capture_output=True) + subprocess.run(["sudo", "systemctl", "stop", "ModemManager"], capture_output=True) + self._ppp.kill() + + state = State.INITIALIZING + + handlers = { + State.INITIALIZING: self._do_initializing, + State.SEARCHING: self._do_searching, + State.CONNECTING: self._do_connecting, + State.CONNECTED: self._do_connected, + State.DISCONNECTING: self._do_disconnecting, + } + + while self.running: + try: + self._check_iccid(state) + prev = state + state = handlers[state]() + if state != prev: + self._publish_state(state=state.value) + logging.info(f"{prev.value} -> {state.value}") + except Exception: + logging.exception(f"error in {state.value}") + state = State.DISCONNECTING + time.sleep(STATE_WAIT) + + def stop(self): + self.running = False + self._ppp.kill() + self._ppp.cleanup_routes() + try: + os.remove(STATE_PATH) + except FileNotFoundError: + pass + if self._has_modem_manager(): + subprocess.run(["sudo", "systemctl", "unmask", "--runtime", "ModemManager"], capture_output=True) + subprocess.run(["sudo", "systemctl", "start", "ModemManager"], capture_output=True) + + +def main(): + m = Modem() + + def _sig(*_): + m.running = False + + signal.signal(signal.SIGINT, _sig) + signal.signal(signal.SIGTERM, _sig) + m.run() + m.stop() + + +if __name__ == "__main__": + main() diff --git a/system/hardware/tici/pins.py b/openpilot/common/hardware/tici/pins.py similarity index 84% rename from system/hardware/tici/pins.py rename to openpilot/common/hardware/tici/pins.py index 747278d1ec..bdbea591fb 100644 --- a/system/hardware/tici/pins.py +++ b/openpilot/common/hardware/tici/pins.py @@ -1,5 +1,3 @@ -# TODO: these are also defined in a header - # GPIO pin definitions class GPIO: # both GPIO_STM_RST_N and GPIO_LTE_RST_N are misnamed, they are high to reset @@ -26,7 +24,4 @@ class GPIO: CAM2_RSTN = 12 # Sensor interrupts - BMX055_ACCEL_INT = 21 - BMX055_GYRO_INT = 23 - BMX055_MAGN_INT = 87 LSM_INT = 84 diff --git a/system/hardware/tici/power_monitor.py b/openpilot/common/hardware/tici/power_monitor.py similarity index 100% rename from system/hardware/tici/power_monitor.py rename to openpilot/common/hardware/tici/power_monitor.py diff --git a/openpilot/common/hardware/tici/tests/__init__.py b/openpilot/common/hardware/tici/tests/__init__.py new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/openpilot/common/hardware/tici/tests/__init__.py @@ -0,0 +1 @@ + diff --git a/system/hardware/tici/tests/test_agnos_updater.py b/openpilot/common/hardware/tici/tests/test_agnos_updater.py similarity index 100% rename from system/hardware/tici/tests/test_agnos_updater.py rename to openpilot/common/hardware/tici/tests/test_agnos_updater.py diff --git a/system/hardware/tici/tests/test_amplifier.py b/openpilot/common/hardware/tici/tests/test_amplifier.py similarity index 81% rename from system/hardware/tici/tests/test_amplifier.py rename to openpilot/common/hardware/tici/tests/test_amplifier.py index 3f75436db1..3e36ff3a3d 100644 --- a/system/hardware/tici/tests/test_amplifier.py +++ b/openpilot/common/hardware/tici/tests/test_amplifier.py @@ -1,12 +1,10 @@ import pytest import time -import random import subprocess from panda import Panda -from openpilot.system.hardware import TICI, HARDWARE -from openpilot.system.hardware.tici.hardware import Tici -from openpilot.system.hardware.tici.amplifier import Amplifier +from openpilot.common.hardware import TICI, HARDWARE +from openpilot.common.hardware.tici.amplifier import Amplifier class TestAmplifier: @@ -39,7 +37,7 @@ class TestAmplifier: def test_init(self): amp = Amplifier(debug=True) - r = amp.initialize_configuration(Tici().get_device_type()) + r = amp.initialize_configuration() assert r assert self._check_for_i2c_errors(False) @@ -58,10 +56,10 @@ class TestAmplifier: time.sleep(0.1) self.panda.set_siren(True) - time.sleep(random.randint(0, 5)) + time.sleep(0.1) amp = Amplifier(debug=True) - r = amp.initialize_configuration(Tici().get_device_type()) + r = amp.initialize_configuration() assert r if self._check_for_i2c_errors(True): diff --git a/openpilot/common/hardware/tici/updater b/openpilot/common/hardware/tici/updater new file mode 100755 index 0000000000..44b82d0c54 --- /dev/null +++ b/openpilot/common/hardware/tici/updater @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3a94ab8395f20d20a9d5a2a2bacca0694f072df8421cf13adca6250d28065bdc +size 24709205 diff --git a/openpilot/common/hardware/usb.py b/openpilot/common/hardware/usb.py new file mode 100644 index 0000000000..983002b538 --- /dev/null +++ b/openpilot/common/hardware/usb.py @@ -0,0 +1,73 @@ +from pathlib import Path + +CHESTNUT_VENDOR_ID = 0xADD1 +CHESTNUT_PRODUCT_ID = 0x0001 +USB_DEVICES_PATH = Path("/sys/bus/usb/devices") + + +def read(path: Path) -> str | None: + try: + return path.read_text().strip() + except OSError: + return None + + +def read_int(path: Path, base: int = 10) -> int: + try: + return int(path.read_text(), base) + except (OSError, ValueError): + return 0 + + +def usb_devices() -> list[Path]: + try: + devices = (d for d in USB_DEVICES_PATH.glob("*") if (d / "idVendor").exists()) + return sorted(devices, key=lambda p: p.name) + except OSError: + return [] + + +def controller(device: Path) -> Path | None: + try: + return next((parent for parent in device.resolve().parents if parent.name.endswith(".ssusb")), None) + except OSError: + return None + + +def get_usb_state() -> list[dict]: + devices = [] + for device in usb_devices(): + vendor_id = read_int(device / "idVendor", 16) + product_id = read_int(device / "idProduct", 16) + ctrl = controller(device) + devices.append({ + "busnum": read_int(device / "busnum"), + "devnum": read_int(device / "devnum"), + "vendorId": vendor_id, + "productId": product_id, + "speedMbps": read_int(device / "speed"), + "manufacturer": read(device / "manufacturer") or "", + "product": read(device / "product") or "", + "linkErrorCount": read_int(ctrl / "portli", 0) & 0xFFFF if ctrl is not None else 0, + }) + return devices + + +def set_usb_state(device_state, devices: list[dict]) -> None: + entries = device_state.usbState.init('devices', len(devices)) + + chestnut_present = False + for entry, device in zip(entries, devices, strict=True): + entry.busnum = device["busnum"] + entry.devnum = device["devnum"] + entry.vendorId = device["vendorId"] + entry.productId = device["productId"] + entry.speedMbps = device["speedMbps"] + entry.manufacturer = device["manufacturer"] + entry.product = device["product"] + entry.linkErrorCount = device["linkErrorCount"] + + if (entry.vendorId, entry.productId) == (CHESTNUT_VENDOR_ID, CHESTNUT_PRODUCT_ID): + chestnut_present = True + + device_state.chestnutPresent = chestnut_present diff --git a/openpilot/common/i2c.py b/openpilot/common/i2c.py new file mode 100644 index 0000000000..1dfaa659ad --- /dev/null +++ b/openpilot/common/i2c.py @@ -0,0 +1,81 @@ +import os +import fcntl +import ctypes + +# I2C constants from /usr/include/linux/i2c-dev.h +I2C_SLAVE = 0x0703 +I2C_SLAVE_FORCE = 0x0706 +I2C_SMBUS = 0x0720 + +# SMBus transfer types +I2C_SMBUS_READ = 1 +I2C_SMBUS_WRITE = 0 +I2C_SMBUS_BYTE_DATA = 2 +I2C_SMBUS_I2C_BLOCK_DATA = 8 + +I2C_SMBUS_BLOCK_MAX = 32 + + +class _I2cSmbusData(ctypes.Union): + _fields_ = [ + ("byte", ctypes.c_uint8), + ("word", ctypes.c_uint16), + ("block", ctypes.c_uint8 * (I2C_SMBUS_BLOCK_MAX + 2)), + ] + + +class _I2cSmbusIoctlData(ctypes.Structure): + _fields_ = [ + ("read_write", ctypes.c_uint8), + ("command", ctypes.c_uint8), + ("size", ctypes.c_uint32), + ("data", ctypes.POINTER(_I2cSmbusData)), + ] + + +class SMBus: + def __init__(self, bus: int): + self._fd = os.open(f'/dev/i2c-{bus}', os.O_RDWR) + + def __enter__(self) -> 'SMBus': + return self + + def __exit__(self, *args) -> None: + self.close() + + def close(self) -> None: + if hasattr(self, '_fd') and self._fd >= 0: + os.close(self._fd) + self._fd = -1 + + def _set_address(self, addr: int, force: bool = False) -> None: + ioctl_arg = I2C_SLAVE_FORCE if force else I2C_SLAVE + fcntl.ioctl(self._fd, ioctl_arg, addr) + + def _smbus_access(self, read_write: int, command: int, size: int, data: _I2cSmbusData) -> None: + ioctl_data = _I2cSmbusIoctlData(read_write, command, size, ctypes.pointer(data)) + fcntl.ioctl(self._fd, I2C_SMBUS, ioctl_data) + + def read_byte_data(self, addr: int, register: int, force: bool = False) -> int: + self._set_address(addr, force) + data = _I2cSmbusData() + self._smbus_access(I2C_SMBUS_READ, register, I2C_SMBUS_BYTE_DATA, data) + return int(data.byte) + + def write_byte_data(self, addr: int, register: int, value: int, force: bool = False) -> None: + self._set_address(addr, force) + data = _I2cSmbusData() + data.byte = value & 0xFF + self._smbus_access(I2C_SMBUS_WRITE, register, I2C_SMBUS_BYTE_DATA, data) + + def read_i2c_block_data(self, addr: int, register: int, length: int, force: bool = False) -> list[int]: + self._set_address(addr, force) + if not (0 <= length <= I2C_SMBUS_BLOCK_MAX): + raise ValueError(f"length must be 0..{I2C_SMBUS_BLOCK_MAX}") + + data = _I2cSmbusData() + data.block[0] = length + self._smbus_access(I2C_SMBUS_READ, register, I2C_SMBUS_I2C_BLOCK_DATA, data) + read_len = int(data.block[0]) or length + read_len = min(read_len, length) + return [int(b) for b in data.block[1 : read_len + 1]] diff --git a/openpilot/common/linux.py b/openpilot/common/linux.py new file mode 100644 index 0000000000..73ea77b509 --- /dev/null +++ b/openpilot/common/linux.py @@ -0,0 +1,50 @@ +class LinuxSystemStats: + def __init__(self) -> None: + self._last_cpu_times = self._read_cpu_times() + + @staticmethod + def _read_cpu_times() -> dict[int, tuple[int, int]]: + cpu_times = {} + with open('/proc/stat') as f: + for line in f: + name, *values = line.split() + if not name.startswith('cpu') or not name[3:].isdigit(): + continue + + times = [int(value) for value in values] + idle = sum(times[3:5]) + total = sum(times[:8]) + cpu_times[int(name[3:])] = (idle, total) + return cpu_times + + def cpu_usage_percent(self) -> list[float]: + current_cpu_times = self._read_cpu_times() + usage = [] + for cpu, (idle, total) in sorted(current_cpu_times.items()): + last_times = self._last_cpu_times.get(cpu) + if last_times is None: + usage.append(0.) + continue + + last_idle, last_total = last_times + idle_delta = idle - last_idle + total_delta = total - last_total + if idle_delta < 0 or total_delta <= 0: + usage.append(0.) + else: + usage.append(max(0., min(100., 100. * (total_delta - idle_delta) / total_delta))) + + self._last_cpu_times = current_cpu_times + return usage + + @staticmethod + def memory_usage_percent() -> float: + memory = {} + with open('/proc/meminfo') as f: + for line in f: + key, value, *_ = line.split() + if key in ('MemTotal:', 'MemAvailable:'): + memory[key] = int(value) + + total = memory['MemTotal:'] + return max(0., min(100., 100. * (total - memory['MemAvailable:']) / total)) diff --git a/common/logging_extra.py b/openpilot/common/logging_extra.py similarity index 100% rename from common/logging_extra.py rename to openpilot/common/logging_extra.py diff --git a/common/markdown.py b/openpilot/common/markdown.py similarity index 100% rename from common/markdown.py rename to openpilot/common/markdown.py diff --git a/openpilot/common/mock/__init__.py b/openpilot/common/mock/__init__.py new file mode 100644 index 0000000000..ff4dd32b92 --- /dev/null +++ b/openpilot/common/mock/__init__.py @@ -0,0 +1,50 @@ +""" +Utilities for generating mock messages for testing. +example in openpilot/common/tests/test_mock.py +""" + + +import functools +import threading +from openpilot.cereal.messaging import PubMaster +from openpilot.cereal.services import SERVICE_LIST +from openpilot.common.mock.generators import generate_livePose +from openpilot.common.realtime import Ratekeeper + + +MOCK_GENERATOR = { + "livePose": generate_livePose +} + + +def generate_messages_loop(services: list[str], done: threading.Event): + pm = PubMaster(services) + rk = Ratekeeper(100) + i = 0 + while not done.is_set(): + for s in services: + should_send = i % (100/SERVICE_LIST[s].frequency) == 0 + if should_send: + message = MOCK_GENERATOR[s]() + pm.send(s, message) + i += 1 + rk.keep_time() + + +def mock_messages(services: list[str] | str): + if isinstance(services, str): + services = [services] + + def decorator(func): + @functools.wraps(func) + def wrapper(*args, **kwargs): + done = threading.Event() + t = threading.Thread(target=generate_messages_loop, args=(services, done)) + t.start() + try: + return func(*args, **kwargs) + finally: + done.set() + t.join() + return wrapper + return decorator diff --git a/common/mock/generators.py b/openpilot/common/mock/generators.py similarity index 91% rename from common/mock/generators.py rename to openpilot/common/mock/generators.py index 5cd9c88a56..28a3b98e58 100644 --- a/common/mock/generators.py +++ b/openpilot/common/mock/generators.py @@ -1,4 +1,4 @@ -from cereal import messaging +from openpilot.cereal import messaging def generate_livePose(): diff --git a/openpilot/common/parameterized.py b/openpilot/common/parameterized.py new file mode 100644 index 0000000000..f36d649dad --- /dev/null +++ b/openpilot/common/parameterized.py @@ -0,0 +1,54 @@ +import re +import sys +import pytest +import inspect + + +def _to_safe_name(s): + return re.sub(r"[^a-zA-Z0-9_]+", "_", str(s)).strip("_") + + +class parameterized: + @staticmethod + def expand(cases): + cases = list(cases) + + if not cases: + return lambda func: pytest.mark.skip("no parameterized cases")(func) + + def decorator(func): + params = [p for p in inspect.signature(func).parameters if p != 'self'] + normalized = [c if isinstance(c, tuple) else (c,) for c in cases] + # Infer arg count from first case so extra params (e.g. from @given) are left untouched + expand_params = params[: len(normalized[0])] + if len(expand_params) == 1: + return pytest.mark.parametrize(expand_params[0], [c[0] for c in normalized])(func) + return pytest.mark.parametrize(', '.join(expand_params), normalized)(func) + + return decorator + + +def parameterized_class(attrs, input_list=None): + if isinstance(attrs, list) and (not attrs or isinstance(attrs[0], dict)): + params_list = attrs + else: + assert input_list is not None + attr_names = (attrs,) if isinstance(attrs, str) else tuple(attrs) + params_list = [dict(zip(attr_names, v if isinstance(v, (tuple, list)) else (v,), strict=False)) for v in input_list] + + def decorator(cls): + globs = sys._getframe(1).f_globals + for i, params in enumerate(params_list): + # append sanitized string param values so pytest -k can filter by them + suffix = "_".join(filter(None, (_to_safe_name(v) for v in params.values() if isinstance(v, str)))) + name = f"{cls.__name__}_{i}" + (f"_{suffix}" if suffix else "") + new_cls = type(name, (cls,), dict(params)) + new_cls.__module__ = cls.__module__ + new_cls.__test__ = True # override inherited False so pytest collects this subclass + globs[name] = new_cls + # Don't collect the un-parametrised base, but return it so outer decorators + # (e.g. @pytest.mark.skip) land on it and propagate to subclasses via MRO. + cls.__test__ = False + return cls + + return decorator diff --git a/common/params.cc b/openpilot/common/params.cc similarity index 91% rename from common/params.cc rename to openpilot/common/params.cc index 0a8821c37a..bed6827e5a 100644 --- a/common/params.cc +++ b/openpilot/common/params.cc @@ -12,7 +12,7 @@ #include "common/queue.h" #include "common/swaglog.h" #include "common/util.h" -#include "system/hardware/hw.h" +#include "common/hardware/hw.h" namespace { @@ -103,10 +103,10 @@ Params::~Params() { assert(queue.empty()); } -std::vector Params::allKeys(ParamKeyType type) const { +std::vector Params::allKeys(ParamKeyFlag flag) const { std::vector ret; for (auto &p : keys) { - if (type == ALL || (p.second & type)) { + if (flag == ALL || (p.second.flags & flag)) { ret.push_back(p.first); } } @@ -117,8 +117,16 @@ bool Params::checkKey(const std::string &key) { return keys.find(key) != keys.end(); } +ParamKeyFlag Params::getKeyFlag(const std::string &key) { + return static_cast(keys[key].flags); +} + ParamKeyType Params::getKeyType(const std::string &key) { - return static_cast(keys[key]); + return keys[key].type; +} + +std::optional Params::getKeyDefaultValue(const std::string &key) { + return keys[key].default_value; } int Params::put(const char* key, const char* value, size_t value_size) { @@ -197,17 +205,17 @@ std::map Params::readAll() { return util::read_files_in_dir(getParamPath()); } -void Params::clearAll(ParamKeyType key_type) { +void Params::clearAll(ParamKeyFlag key_flag) { FileLock file_lock(params_path + "/.lock"); - // 1) delete params of key_type + // 1) delete params of key_flag // 2) delete files that are not defined in the keys. if (DIR *d = opendir(getParamPath().c_str())) { struct dirent *de = NULL; while ((de = readdir(d))) { if (de->d_type != DT_DIR) { auto it = keys.find(de->d_name); - if (it == keys.end() || (it->second & key_type)) { + if (it == keys.end() || (it->second.flags & key_flag)) { unlink(getParamPath(de->d_name).c_str()); } } diff --git a/common/params.h b/openpilot/common/params.h similarity index 76% rename from common/params.h rename to openpilot/common/params.h index 73e21a3fee..de4f9b435f 100644 --- a/common/params.h +++ b/openpilot/common/params.h @@ -2,6 +2,7 @@ #include #include +#include #include #include #include @@ -9,17 +10,34 @@ #include "common/queue.h" -enum ParamKeyType { +enum ParamKeyFlag { PERSISTENT = 0x02, CLEAR_ON_MANAGER_START = 0x04, CLEAR_ON_ONROAD_TRANSITION = 0x08, CLEAR_ON_OFFROAD_TRANSITION = 0x10, DONT_LOG = 0x20, DEVELOPMENT_ONLY = 0x40, - BACKUP = 0x80, + CLEAR_ON_IGNITION_ON = 0x80, + BACKUP = 0x100, ALL = 0xFFFFFFFF }; +enum ParamKeyType { + STRING = 0, // must be utf-8 decodable + BOOL = 1, + INT = 2, + FLOAT = 3, + TIME = 4, // ISO 8601 + JSON = 5, + BYTES = 6 +}; + +struct ParamKeyAttributes { + uint32_t flags; + ParamKeyType type; + std::optional default_value = std::nullopt; +}; + class Params { public: explicit Params(const std::string &path = {}); @@ -28,16 +46,18 @@ public: Params(const Params&) = delete; Params& operator=(const Params&) = delete; - std::vector allKeys(ParamKeyType type = ALL) const; + std::vector allKeys(ParamKeyFlag flag = ALL) const; bool checkKey(const std::string &key); + ParamKeyFlag getKeyFlag(const std::string &key); ParamKeyType getKeyType(const std::string &key); + std::optional getKeyDefaultValue(const std::string &key); inline std::string getParamPath(const std::string &key = {}) { return params_path + params_prefix + (key.empty() ? "" : "/" + key); } // Delete a value int remove(const std::string &key); - void clearAll(ParamKeyType type); + void clearAll(ParamKeyFlag flag); // helpers for reading values std::string get(const std::string &key, bool block = false); diff --git a/openpilot/common/params.py b/openpilot/common/params.py new file mode 100644 index 0000000000..8af80c04bb --- /dev/null +++ b/openpilot/common/params.py @@ -0,0 +1,19 @@ +from openpilot.common.params_pyx import Params, ParamKeyFlag, ParamKeyType, UnknownKeyName +assert Params +assert ParamKeyFlag +assert ParamKeyType +assert UnknownKeyName + +if __name__ == "__main__": + import sys + + params = Params() + key = sys.argv[1] + assert params.check_key(key), f"unknown param: {key}" + + if len(sys.argv) == 3: + val = sys.argv[2] + print(f"SET: {key} = {val}") + params.put(key, val, block=True) + elif len(sys.argv) == 2: + print(f"GET: {key} = {params.get(key)}") diff --git a/openpilot/common/params_keys.h b/openpilot/common/params_keys.h new file mode 100644 index 0000000000..3c39fc5f53 --- /dev/null +++ b/openpilot/common/params_keys.h @@ -0,0 +1,281 @@ +#pragma once + +#include +#include + +#include "openpilot/cereal/gen/cpp/log.capnp.h" + +inline static std::unordered_map keys = { + {"AccessToken", {CLEAR_ON_MANAGER_START | DONT_LOG, STRING}}, + {"AdbEnabled", {PERSISTENT | BACKUP, BOOL}}, + {"AlwaysOnDM", {PERSISTENT | BACKUP, BOOL}}, + {"ApiCache_Device", {PERSISTENT, STRING}}, + {"ApiCache_FirehoseStats", {PERSISTENT, JSON}}, + {"AssistNowToken", {PERSISTENT, STRING}}, + {"AthenadPid", {PERSISTENT, INT}}, + {"AthenadUploadQueue", {PERSISTENT, JSON}}, + {"AthenadRecentlyViewedRoutes", {PERSISTENT, STRING}}, + {"BootCount", {PERSISTENT, INT}}, + {"CalibrationParams", {PERSISTENT, BYTES}}, + {"CameraDebugExpGain", {CLEAR_ON_MANAGER_START, STRING}}, + {"CameraDebugExpTime", {CLEAR_ON_MANAGER_START, STRING}}, + {"CarBatteryCapacity", {PERSISTENT, INT}}, + {"CarParams", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, BYTES}}, + {"CarParamsCache", {CLEAR_ON_MANAGER_START, BYTES}}, + {"CarParamsPersistent", {PERSISTENT, BYTES}}, + {"CarParamsPrevRoute", {PERSISTENT, BYTES}}, + {"CompletedTrainingVersion", {PERSISTENT, STRING, "0"}}, + {"ControlsReady", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, BOOL}}, + {"CurrentBootlog", {PERSISTENT, STRING}}, + {"CurrentRoute", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, STRING}}, + {"DisableLogging", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, BOOL}}, + {"DisablePowerDown", {PERSISTENT | BACKUP, BOOL}}, + {"DisableUpdates", {PERSISTENT | BACKUP, BOOL, "0"}}, + {"DisengageOnAccelerator", {PERSISTENT | BACKUP, BOOL, "0"}}, + {"DongleId", {PERSISTENT, STRING}}, + {"DoReboot", {CLEAR_ON_MANAGER_START, BOOL}}, + {"DoShutdown", {CLEAR_ON_MANAGER_START, BOOL}}, + {"DoUninstall", {CLEAR_ON_MANAGER_START, BOOL}}, + {"DriverTooDistracted", {CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_ON, BOOL}}, + {"DriverLockoutCount", {CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_ON, INT, "0"}}, + {"AlphaLongitudinalEnabled", {PERSISTENT | DEVELOPMENT_ONLY | BACKUP, BOOL}}, + {"ExperimentalMode", {PERSISTENT | BACKUP, BOOL}}, + {"ExperimentalModeConfirmed", {PERSISTENT | BACKUP, BOOL}}, + {"FirmwareQueryDone", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, BOOL}}, + {"ForcePowerDown", {PERSISTENT, BOOL}}, + {"GitBranch", {PERSISTENT, STRING}}, + {"GitCommit", {PERSISTENT, STRING}}, + {"GitCommitDate", {PERSISTENT, STRING}}, + {"GitDiff", {PERSISTENT, STRING}}, + {"GithubSshKeys", {PERSISTENT | BACKUP, STRING}}, + {"GithubUsername", {PERSISTENT | BACKUP, STRING}}, + {"GitRemote", {PERSISTENT, STRING}}, + {"GsmApn", {PERSISTENT | BACKUP, STRING}}, + {"GsmMetered", {PERSISTENT | BACKUP, BOOL, "1"}}, + {"GsmRoaming", {PERSISTENT | BACKUP, BOOL}}, + {"HardwareSerial", {PERSISTENT, STRING}}, + {"HasAcceptedTerms", {PERSISTENT, STRING, "0"}}, + {"InstallDate", {PERSISTENT, TIME}}, + {"IsDriverViewEnabled", {CLEAR_ON_MANAGER_START, BOOL}}, + {"IsEngaged", {PERSISTENT, BOOL}}, + {"IsLdwEnabled", {PERSISTENT | BACKUP, BOOL}}, + {"IsLiveStreaming", {CLEAR_ON_MANAGER_START, BOOL}}, + {"IsMetric", {PERSISTENT | BACKUP, BOOL}}, + {"IsOffroad", {CLEAR_ON_MANAGER_START, BOOL}}, + {"IsRhdDetected", {PERSISTENT, BOOL}}, + {"IsReleaseBranch", {CLEAR_ON_MANAGER_START, BOOL}}, + {"IsTestedBranch", {CLEAR_ON_MANAGER_START, BOOL}}, + {"JoystickDebugMode", {CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION, BOOL}}, + {"LanguageSetting", {PERSISTENT | BACKUP, STRING, "en"}}, + {"LastAthenaPingTime", {CLEAR_ON_MANAGER_START, INT}}, + {"LastGPSPosition", {PERSISTENT, STRING}}, + {"LastManagerExitReason", {CLEAR_ON_MANAGER_START, STRING}}, + {"LastOffroadStatusPacket", {CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION, JSON}}, + {"LastAgnosPowerMonitorShutdown", {CLEAR_ON_MANAGER_START, STRING}}, + {"LastPowerDropDetected", {CLEAR_ON_MANAGER_START, STRING}}, + {"LastUpdateException", {CLEAR_ON_MANAGER_START, STRING}}, + {"LastUpdateRouteCount", {PERSISTENT, INT, "0"}}, + {"LastUpdateTime", {PERSISTENT, TIME}}, + {"LastUpdateUptimeOnroad", {PERSISTENT, FLOAT, "0.0"}}, + {"LiveDelay", {PERSISTENT | BACKUP, BYTES}}, + {"LiveParameters", {PERSISTENT, JSON}}, + {"LiveParametersV2", {PERSISTENT, BYTES}}, + {"LivestreamEncoderBitrate", {CLEAR_ON_MANAGER_START | DONT_LOG, INT}}, + {"LivestreamRequestKeyframe", {CLEAR_ON_MANAGER_START | DONT_LOG, BOOL}}, + {"LiveTorqueParameters", {PERSISTENT | DONT_LOG, BYTES}}, + {"LocationFilterInitialState", {PERSISTENT, BYTES}}, + {"LateralManeuverMode", {CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION, BOOL}}, + {"LongitudinalManeuverMode", {CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION, BOOL}}, + {"LongitudinalPersonality", {PERSISTENT | BACKUP, INT, std::to_string(static_cast(cereal::LongitudinalPersonality::STANDARD))}}, + {"NetworkMetered", {PERSISTENT | BACKUP, BOOL}}, + {"ObdMultiplexingChanged", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, BOOL}}, + {"ObdMultiplexingEnabled", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, BOOL}}, + {"Offroad_CarUnrecognized", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, JSON}}, + {"Offroad_ConnectivityNeeded", {CLEAR_ON_MANAGER_START, JSON}}, + {"Offroad_ConnectivityNeededPrompt", {CLEAR_ON_MANAGER_START, JSON}}, + {"Offroad_ExcessiveActuation", {PERSISTENT, JSON}}, + {"Offroad_NeosUpdate", {CLEAR_ON_MANAGER_START, JSON}}, + {"Offroad_NoFirmware", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, JSON}}, + {"Offroad_Recalibration", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, JSON}}, + {"Offroad_TemperatureTooHigh", {CLEAR_ON_MANAGER_START, JSON}}, + {"Offroad_UnregisteredHardware", {CLEAR_ON_MANAGER_START, JSON}}, + {"Offroad_UpdateFailed", {CLEAR_ON_MANAGER_START, JSON}}, + {"Offroad_DriverMonitoringUncertain", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, JSON}}, + {"OnroadCycleRequested", {CLEAR_ON_MANAGER_START, BOOL}}, + {"OpenpilotEnabledToggle", {PERSISTENT | BACKUP, BOOL, "1"}}, + {"PandaHeartbeatLost", {CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION, BOOL}}, + {"PrimeType", {PERSISTENT, INT}}, + {"RecordAudio", {PERSISTENT | BACKUP, BOOL}}, + {"RecordAudioFeedback", {PERSISTENT | BACKUP, BOOL, "0"}}, + {"RecordFront", {PERSISTENT | BACKUP, BOOL}}, + {"RecordFrontLock", {PERSISTENT, BOOL}}, // for the internal fleet + {"SecOCKey", {PERSISTENT | DONT_LOG | BACKUP, STRING}}, + {"ShowDebugInfo", {PERSISTENT, BOOL}}, + {"RouteCount", {PERSISTENT, INT, "0"}}, + {"SnoozeUpdate", {CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION, BOOL}}, + {"SshEnabled", {PERSISTENT | BACKUP, BOOL}}, + {"TermsVersion", {PERSISTENT, STRING}}, + {"TorqueBar", {PERSISTENT | BACKUP, BOOL, "0"}}, + {"TrainingVersion", {PERSISTENT, STRING}}, + {"UbloxAvailable", {PERSISTENT, BOOL}}, + {"UpdateAvailable", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, BOOL}}, + {"UpdateFailedCount", {CLEAR_ON_MANAGER_START, INT}}, + {"UpdaterAvailableBranches", {PERSISTENT, STRING}}, + {"UpdaterCurrentDescription", {CLEAR_ON_MANAGER_START, STRING}}, + {"UpdaterCurrentReleaseNotes", {CLEAR_ON_MANAGER_START, BYTES}}, + {"UpdaterFetchAvailable", {CLEAR_ON_MANAGER_START, BOOL}}, + {"UpdaterNewDescription", {CLEAR_ON_MANAGER_START, STRING}}, + {"UpdaterNewReleaseNotes", {CLEAR_ON_MANAGER_START, BYTES}}, + {"UpdaterState", {CLEAR_ON_MANAGER_START, STRING}}, + {"UpdaterTargetBranch", {CLEAR_ON_MANAGER_START, STRING}}, + {"UpdaterLastFetchTime", {PERSISTENT, TIME}}, + {"UptimeOffroad", {PERSISTENT, FLOAT, "0.0"}}, + {"UptimeOnroad", {PERSISTENT, FLOAT, "0.0"}}, + {"UsbGpuPresent", {CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION, BOOL}}, + {"UsbGpuCompiled", {CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION, BOOL}}, + {"Version", {PERSISTENT, STRING}}, + + // --- sunnypilot params --- // + {"ApiCache_DriveStats", {PERSISTENT, JSON}}, + {"AutoLaneChangeBsmDelay", {PERSISTENT | BACKUP, BOOL, "0"}}, + {"AutoLaneChangeTimer", {PERSISTENT | BACKUP, INT, "0"}}, + {"BlinkerLateralReengageDelay", {PERSISTENT | BACKUP, INT, "0"}}, // seconds + {"BlinkerMinLateralControlSpeed", {PERSISTENT | BACKUP, INT, "20"}}, // MPH or km/h + {"BlinkerPauseLateralControl", {PERSISTENT | BACKUP, INT, "0"}}, + {"Brightness", {PERSISTENT | BACKUP, INT, "0"}}, + {"CarList", {PERSISTENT, JSON}}, + {"CarParamsSP", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, BYTES}}, + {"CarParamsSPCache", {CLEAR_ON_MANAGER_START, BYTES}}, + {"CarParamsSPPersistent", {PERSISTENT, BYTES}}, + {"CarPlatformBundle", {PERSISTENT | BACKUP, JSON}}, + {"ChevronInfo", {PERSISTENT | BACKUP, INT, "4"}}, + {"CompletedSunnylinkConsentVersion", {PERSISTENT, STRING, "0"}}, + {"CustomAccIncrementsEnabled", {PERSISTENT | BACKUP, BOOL, "0"}}, + {"CustomAccLongPressIncrement", {PERSISTENT | BACKUP, INT, "5"}}, + {"CustomAccShortPressIncrement", {PERSISTENT | BACKUP, INT, "1"}}, + {"DeviceBootMode", {PERSISTENT | BACKUP, INT, "0"}}, + {"DevUIInfo", {PERSISTENT | BACKUP, INT, "0"}}, + {"EnableCopyparty", {PERSISTENT | BACKUP, BOOL}}, + {"EnableGithubRunner", {PERSISTENT | BACKUP, BOOL}}, + {"GreenLightAlert", {PERSISTENT | BACKUP, BOOL, "0"}}, + {"GithubRunnerSufficientVoltage", {CLEAR_ON_MANAGER_START , BOOL}}, + {"HasAcceptedTermsSP", {PERSISTENT, STRING, "0"}}, + {"HideVEgoUI", {PERSISTENT | BACKUP, BOOL, "0"}}, + {"IntelligentCruiseButtonManagement", {PERSISTENT | BACKUP , BOOL}}, + {"InteractivityTimeout", {PERSISTENT | BACKUP, INT, "0"}}, + {"IsDevelopmentBranch", {CLEAR_ON_MANAGER_START, BOOL}}, + {"IsReleaseSpBranch", {CLEAR_ON_MANAGER_START, BOOL}}, + {"LastGPSPositionLLK", {PERSISTENT, STRING}}, + {"LeadDepartAlert", {PERSISTENT | BACKUP, BOOL, "0"}}, + {"MaxTimeOffroad", {PERSISTENT | BACKUP, INT, "1800"}}, + {"ModelRunnerTypeCache", {CLEAR_ON_ONROAD_TRANSITION, INT}}, + {"OffroadMode", {CLEAR_ON_MANAGER_START, BOOL}}, + {"Offroad_TiciSupport", {CLEAR_ON_MANAGER_START, JSON}}, + {"OnroadScreenOffBrightness", {PERSISTENT | BACKUP, INT, "0"}}, + {"OnroadScreenOffBrightnessMigrated", {PERSISTENT | BACKUP, STRING, "0.0"}}, + {"OnroadScreenOffTimer", {PERSISTENT | BACKUP, INT, "15"}}, + {"OnroadScreenOffTimerMigrated", {PERSISTENT | BACKUP, STRING, "0.0"}}, + {"OnroadUploads", {PERSISTENT | BACKUP, BOOL, "1"}}, + {"QuickBootToggle", {PERSISTENT | BACKUP, BOOL, "0"}}, + {"QuietMode", {PERSISTENT | BACKUP, BOOL, "0"}}, + {"RainbowMode", {PERSISTENT | BACKUP, BOOL, "0"}}, + {"RocketFuel", {PERSISTENT | BACKUP, BOOL, "0"}}, + {"ShowAdvancedControls", {PERSISTENT | BACKUP, BOOL, "0"}}, + {"ShowTurnSignals", {PERSISTENT | BACKUP, BOOL, "0"}}, + {"StandstillTimer", {PERSISTENT | BACKUP, BOOL, "0"}}, + {"TrueVEgoUI", {PERSISTENT | BACKUP, BOOL, "0"}}, + + // MADS params + {"Mads", {PERSISTENT | BACKUP, BOOL, "1"}}, + {"MadsMainCruiseAllowed", {PERSISTENT | BACKUP, BOOL, "1"}}, + {"MadsSteeringMode", {PERSISTENT | BACKUP, INT, "0"}}, + {"MadsUnifiedEngagementMode", {PERSISTENT | BACKUP, BOOL, "1"}}, + + // Model Manager params + {"ModelManager_ActiveBundle", {PERSISTENT, JSON}}, + {"ModelManager_ClearCache", {CLEAR_ON_MANAGER_START, BOOL}}, + {"ModelManager_DownloadIndex", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, INT}}, + {"ModelManager_Favs", {PERSISTENT | BACKUP, STRING}}, + {"ModelManager_LastSyncTime", {CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION, INT, "0"}}, + {"ModelManager_ModelsCache", {PERSISTENT | BACKUP, JSON}}, + + // Neural Network Lateral Control + {"NeuralNetworkLateralControl", {PERSISTENT | BACKUP, BOOL, "0"}}, + + // sunnylink params + {"EnableSunnylinkUploader", {PERSISTENT | BACKUP, BOOL}}, + {"LastSunnylinkPingTime", {CLEAR_ON_MANAGER_START, INT}}, + {"ParamsVersion", {PERSISTENT, INT}}, + {"SunnylinkCache_Roles", {PERSISTENT, STRING}}, + {"SunnylinkCache_Users", {PERSISTENT, STRING}}, + {"SunnylinkDongleId", {PERSISTENT, STRING}}, + {"SunnylinkdPid", {PERSISTENT, INT}}, + {"SunnylinkEnabled", {PERSISTENT, BOOL, "1"}}, + {"SunnylinkTempFault", {CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION, BOOL, "0"}}, + + // Backup Manager params + {"BackupManager_CreateBackup", {PERSISTENT, BOOL}}, + {"BackupManager_RestoreVersion", {PERSISTENT, STRING}}, + + // sunnypilot car specific params + {"HyundaiLongitudinalTuning", {PERSISTENT | BACKUP, INT, "0"}}, + {"SubaruStopAndGo", {PERSISTENT | BACKUP, BOOL, "0"}}, + {"SubaruStopAndGoManualParkingBrake", {PERSISTENT | BACKUP, BOOL, "0"}}, + {"TeslaCoopSteering", {PERSISTENT | BACKUP, BOOL, "0"}}, + {"ToyotaEnforceStockLongitudinal", {PERSISTENT | BACKUP, BOOL, "0"}}, + {"ToyotaStopAndGoHack", {PERSISTENT | BACKUP, BOOL, "0"}}, + + {"DynamicExperimentalControl", {PERSISTENT | BACKUP, BOOL, "0"}}, + {"BlindSpot", {PERSISTENT | BACKUP, BOOL, "0"}}, + + // sunnypilot model params + {"CameraOffset", {PERSISTENT | BACKUP, FLOAT, "0.0"}}, + {"LagdToggle", {PERSISTENT | BACKUP, BOOL, "1"}}, + {"LagdToggleDelay", {PERSISTENT | BACKUP, FLOAT, "0.2"}}, + {"LagdValueCache", {PERSISTENT, FLOAT, "0.2"}}, + {"LaneTurnDesire", {PERSISTENT | BACKUP, BOOL, "0"}}, + {"LaneTurnValue", {PERSISTENT | BACKUP, FLOAT, "19.0"}}, + {"PlanplusControl", {PERSISTENT | BACKUP, FLOAT, "1.0"}}, + + // mapd + {"MapAdvisorySpeedLimit", {CLEAR_ON_ONROAD_TRANSITION, FLOAT}}, + {"MapdVersion", {PERSISTENT, STRING}}, + {"MapSpeedLimit", {CLEAR_ON_ONROAD_TRANSITION, FLOAT, "0.0"}}, + {"NextMapSpeedLimit", {CLEAR_ON_ONROAD_TRANSITION, JSON}}, + {"Offroad_OSMUpdateRequired", {CLEAR_ON_MANAGER_START, JSON}}, + {"OsmDbUpdatesCheck", {CLEAR_ON_MANAGER_START, BOOL}}, // mapd database update happens with device ON, reset on boot + {"OSMDownloadBounds", {PERSISTENT, STRING}}, + {"OsmDownloadedDate", {PERSISTENT, STRING, "0.0"}}, + {"OSMDownloadLocations", {PERSISTENT, JSON}}, + {"OSMDownloadProgress", {CLEAR_ON_MANAGER_START, JSON}}, + {"OsmLocal", {PERSISTENT, BOOL}}, + {"OsmLocationName", {PERSISTENT, STRING}}, + {"OsmLocationTitle", {PERSISTENT, STRING}}, + {"OsmLocationUrl", {PERSISTENT, STRING}}, + {"OsmStateName", {PERSISTENT, STRING, "All"}}, + {"OsmStateTitle", {PERSISTENT, STRING}}, + {"OsmWayTest", {PERSISTENT, STRING}}, + {"RoadName", {CLEAR_ON_ONROAD_TRANSITION, STRING}}, + {"RoadNameToggle", {PERSISTENT | BACKUP, BOOL, "0"}}, + + // Speed Limit + {"SpeedLimitMode", {PERSISTENT | BACKUP, INT, "1"}}, + {"SpeedLimitOffsetType", {PERSISTENT | BACKUP, INT, "0"}}, + {"SpeedLimitPolicy", {PERSISTENT | BACKUP, INT, "3"}}, + {"SpeedLimitValueOffset", {PERSISTENT | BACKUP, INT, "0"}}, + + // Smart Cruise Control + {"MapTargetVelocities", {CLEAR_ON_ONROAD_TRANSITION, STRING}}, + {"SmartCruiseControlMap", {PERSISTENT | BACKUP, BOOL, "0"}}, + {"SmartCruiseControlVision", {PERSISTENT | BACKUP, BOOL, "0"}}, + + // Torque lateral control custom params + {"CustomTorqueParams", {PERSISTENT | BACKUP , BOOL}}, + {"EnforceTorqueControl", {PERSISTENT | BACKUP, BOOL}}, + {"LiveTorqueParamsToggle", {PERSISTENT | BACKUP , BOOL}}, + {"LiveTorqueParamsRelaxedToggle", {PERSISTENT | BACKUP , BOOL}}, + {"TorqueControlTune", {PERSISTENT | BACKUP, FLOAT, "0.0"}}, + {"TorqueParamsOverrideEnabled", {PERSISTENT | BACKUP, BOOL, "0"}}, + {"TorqueParamsOverrideFriction", {PERSISTENT | BACKUP, FLOAT, "0.1"}}, + {"TorqueParamsOverrideLatAccelFactor", {PERSISTENT | BACKUP, FLOAT, "2.5"}}, +}; diff --git a/openpilot/common/params_pyx.pyx b/openpilot/common/params_pyx.pyx new file mode 100644 index 0000000000..9a952f6ebe --- /dev/null +++ b/openpilot/common/params_pyx.pyx @@ -0,0 +1,192 @@ +# distutils: language = c++ +# cython: language_level = 3 +import builtins +import datetime +import json +from libcpp cimport bool +from libcpp.string cimport string +from libcpp.vector cimport vector +from libcpp.optional cimport optional + +from openpilot.common.swaglog import cloudlog + +cdef extern from "common/params.h": + cpdef enum ParamKeyFlag: + PERSISTENT + CLEAR_ON_MANAGER_START + CLEAR_ON_ONROAD_TRANSITION + CLEAR_ON_OFFROAD_TRANSITION + DEVELOPMENT_ONLY + CLEAR_ON_IGNITION_ON + BACKUP + ALL + + cpdef enum ParamKeyType: + STRING + BOOL + INT + FLOAT + TIME + JSON + BYTES + + cdef cppclass c_Params "Params": + c_Params(string) except + nogil + string get(string, bool) nogil + bool getBool(string, bool) nogil + int remove(string) nogil + int put(string, string) nogil + void putNonBlocking(string, string) nogil + void putBoolNonBlocking(string, bool) nogil + int putBool(string, bool) nogil + bool checkKey(string) nogil + ParamKeyType getKeyType(string) nogil + optional[string] getKeyDefaultValue(string) nogil + string getParamPath(string) nogil + void clearAll(ParamKeyFlag) + vector[string] allKeys(ParamKeyFlag) + +PYTHON_2_CPP = { + (str, STRING): lambda v: v, + (builtins.bool, BOOL): lambda v: "1" if v else "0", + (int, INT): str, + (float, FLOAT): str, + (datetime.datetime, TIME): lambda v: v.isoformat(), + (dict, JSON): json.dumps, + (list, JSON): json.dumps, + (bytes, BYTES): lambda v: v, +} +CPP_2_PYTHON = { + STRING: lambda v: v.decode("utf-8"), + BOOL: lambda v: v == b"1", + INT: int, + FLOAT: float, + TIME: lambda v: datetime.datetime.fromisoformat(v.decode("utf-8")), + JSON: json.loads, + BYTES: lambda v: v, +} + +def ensure_bytes(v): + return v.encode() if isinstance(v, str) else v + +class UnknownKeyName(Exception): + pass + +cdef class Params: + cdef c_Params* p + cdef str d + + def __cinit__(self, d=""): + cdef string path = d.encode() + with nogil: + self.p = new c_Params(path) + self.d = d + + def __reduce__(self): + return (type(self), (self.d,)) + + def __dealloc__(self): + del self.p + + def clear_all(self, tx_flag=ParamKeyFlag.ALL): + self.p.clearAll(tx_flag) + + def check_key(self, key): + key = ensure_bytes(key) + if not self.p.checkKey(key): + raise UnknownKeyName(key) + return key + + def python2cpp(self, proposed_type, expected_type, value, key): + cast = PYTHON_2_CPP.get((proposed_type, expected_type)) + if cast: + return cast(value) + raise TypeError(f"Type mismatch while writing param {key}: {proposed_type=} {expected_type=} {value=}") + + def _cpp2python(self, t, value, default, key): + if value is None: + return None + try: + return CPP_2_PYTHON[t](value) + except (KeyError, TypeError, ValueError): + cloudlog.warning(f"Failed to cast param {key} with {value=} from type {t=}") + return self._cpp2python(t, default, None, key) + + def get(self, key, bool block=False, bool return_default=False): + cdef string k = self.check_key(key) + cdef ParamKeyType t = self.p.getKeyType(k) + cdef optional[string] default = self.p.getKeyDefaultValue(k) + cdef string val + with nogil: + val = self.p.get(k, block) + + default_val = (default.value() if default.has_value() else None) if return_default else None + if val == b"": + if block: + # If we got no value while running in blocked mode + # it means we got an interrupt while waiting + raise KeyboardInterrupt + else: + return self._cpp2python(t, default_val, None, key) + return self._cpp2python(t, val, default_val, key) + + def get_bool(self, key, bool block=False): + cdef string k = self.check_key(key) + cdef bool r + with nogil: + r = self.p.getBool(k, block) + return r + + def _put_cast(self, key, dat): + cdef string k = self.check_key(key) + cdef ParamKeyType t = self.p.getKeyType(k) + return ensure_bytes(self.python2cpp(type(dat), t, dat, key)) + + def put(self, key, dat, bool block = False): + """ + Warning: block=True blocks until the param is written to disk! + In very rare cases this can take over a second, and your code will hang. + Use block=False in time sensitive code, but in general try to avoid + writing params as much as possible. + """ + cdef string k = self.check_key(key) + cdef string dat_bytes = self._put_cast(key, dat) + with nogil: + if block: + self.p.put(k, dat_bytes) + else: + self.p.putNonBlocking(k, dat_bytes) + + def put_bool(self, key, bool val, bool block = False): + cdef string k = self.check_key(key) + with nogil: + if block: + self.p.putBool(k, val) + else: + self.p.putBoolNonBlocking(k, val) + + def remove(self, key): + cdef string k = self.check_key(key) + with nogil: + self.p.remove(k) + + def get_param_path(self, key=""): + cdef string key_bytes = ensure_bytes(key) + return self.p.getParamPath(key_bytes).decode("utf-8") + + def get_type(self, key): + return self.p.getKeyType(self.check_key(key)) + + def all_keys(self, flag=ParamKeyFlag.ALL): + return self.p.allKeys(flag) + + def get_default_value(self, key): + cdef string k = self.check_key(key) + cdef ParamKeyType t = self.p.getKeyType(k) + cdef optional[string] default = self.p.getKeyDefaultValue(k) + return self._cpp2python(t, default.value(), None, key) if default.has_value() else None + + def cpp2python(self, key, value): + cdef string k = self.check_key(key) + cdef ParamKeyType t = self.p.getKeyType(k) + return self._cpp2python(t, value, None, key) diff --git a/openpilot/common/pid.py b/openpilot/common/pid.py new file mode 100644 index 0000000000..f541baf05c --- /dev/null +++ b/openpilot/common/pid.py @@ -0,0 +1,59 @@ +import numpy as np +from collections.abc import Sequence + +Gain = int | float | tuple[Sequence[float], Sequence[float]] | list[list[float]] + +class PIDController: + def __init__(self, k_p: Gain, k_i: Gain, k_d: Gain = 0., pos_limit=1e308, neg_limit=-1e308, rate=100): + self._k_p = ([0], [k_p]) if isinstance(k_p, (int, float)) else k_p + self._k_i = ([0], [k_i]) if isinstance(k_i, (int, float)) else k_i + self._k_d = ([0], [k_d]) if isinstance(k_d, (int, float)) else k_d + + self.set_limits(pos_limit, neg_limit) + + self.i_dt = 1.0 / rate + self.speed = 0.0 + + self.reset() + + @property + def k_p(self): + return np.interp(self.speed, self._k_p[0], self._k_p[1]) + + @property + def k_i(self): + return np.interp(self.speed, self._k_i[0], self._k_i[1]) + + @property + def k_d(self): + return np.interp(self.speed, self._k_d[0], self._k_d[1]) + + def reset(self): + self.p = 0.0 + self.i = 0.0 + self.d = 0.0 + self.f = 0.0 + self.control = 0 + + def set_limits(self, pos_limit, neg_limit): + self.pos_limit = pos_limit + self.neg_limit = neg_limit + + def update(self, error, error_rate=0.0, speed=0.0, feedforward=0., freeze_integrator=False): + self.speed = speed + self.p = self.k_p * float(error) + self.d = self.k_d * error_rate + self.f = feedforward + + if not freeze_integrator: + i = self.i + self.k_i * self.i_dt * error + + # Don't allow windup if already clipping + test_control = self.p + i + self.d + self.f + i_upperbound = self.i if test_control > self.pos_limit else self.pos_limit + i_lowerbound = self.i if test_control < self.neg_limit else self.neg_limit + self.i = np.clip(i, i_lowerbound, i_upperbound) + + control = self.p + self.i + self.d + self.f + self.control = np.clip(control, self.neg_limit, self.pos_limit) + return self.control diff --git a/openpilot/common/prefix.h b/openpilot/common/prefix.h new file mode 100644 index 0000000000..89f346b9e5 --- /dev/null +++ b/openpilot/common/prefix.h @@ -0,0 +1,43 @@ +#pragma once + +#include +#include + +#include "common/params.h" +#include "common/util.h" +#include "common/hardware/hw.h" + +class OpenpilotPrefix { +public: + OpenpilotPrefix(std::string prefix = {}) { + if (prefix.empty()) { + prefix = util::random_string(15); + } +#ifdef __APPLE__ + msgq_path = "/tmp/msgq_" + prefix; +#else + msgq_path = "/dev/shm/msgq_" + prefix; +#endif + bool ret = util::create_directories(msgq_path, 0777); + assert(ret); + setenv("OPENPILOT_PREFIX", prefix.c_str(), 1); + } + + ~OpenpilotPrefix() { + auto param_path = Params().getParamPath(); + if (util::file_exists(param_path)) { + std::string real_path = util::readlink(param_path); + util::check_system(util::string_format("rm %s -rf", real_path.c_str())); + unlink(param_path.c_str()); + } + if (getenv("COMMA_CACHE") == nullptr) { + util::check_system(util::string_format("rm %s -rf", Path::download_cache_root().c_str())); + } + util::check_system(util::string_format("rm %s -rf", Path::comma_home().c_str())); + util::check_system(util::string_format("rm %s -rf", msgq_path.c_str())); + unsetenv("OPENPILOT_PREFIX"); + } + +private: + std::string msgq_path; +}; diff --git a/openpilot/common/prefix.py b/openpilot/common/prefix.py new file mode 100644 index 0000000000..d0be8997ae --- /dev/null +++ b/openpilot/common/prefix.py @@ -0,0 +1,61 @@ +import os +import platform +import shutil +import uuid + + +from openpilot.common.params import Params +from openpilot.common.hardware import PC +from openpilot.common.hardware.hw import Paths +from openpilot.common.hardware.hw import DEFAULT_DOWNLOAD_CACHE_ROOT + +class OpenpilotPrefix: + def __init__(self, prefix: str | None = None, create_dirs_on_enter: bool = True, clean_dirs_on_exit: bool = True, shared_download_cache: bool = False): + self.prefix = prefix if prefix else str(uuid.uuid4().hex[0:15]) + shm_path = "/tmp" if platform.system() == "Darwin" else "/dev/shm" + self.msgq_path = os.path.join(shm_path, "msgq_" + self.prefix) + self.create_dirs_on_enter = create_dirs_on_enter + self.clean_dirs_on_exit = clean_dirs_on_exit + self.shared_download_cache = shared_download_cache + + def __enter__(self): + self.original_prefix = os.environ.get('OPENPILOT_PREFIX', None) + os.environ['OPENPILOT_PREFIX'] = self.prefix + + if self.create_dirs_on_enter: + self.create_dirs() + + if self.shared_download_cache: + os.environ["COMMA_CACHE"] = DEFAULT_DOWNLOAD_CACHE_ROOT + + return self + + def __exit__(self, exc_type, exc_obj, exc_tb): + if self.clean_dirs_on_exit: + self.clean_dirs() + try: + del os.environ['OPENPILOT_PREFIX'] + if self.original_prefix is not None: + os.environ['OPENPILOT_PREFIX'] = self.original_prefix + except KeyError: + pass + return False + + def create_dirs(self): + try: + os.mkdir(self.msgq_path) + except FileExistsError: + pass + os.makedirs(Paths.log_root(), exist_ok=True) + + def clean_dirs(self): + symlink_path = Params().get_param_path() + if os.path.exists(symlink_path): + shutil.rmtree(os.path.realpath(symlink_path), ignore_errors=True) + os.remove(symlink_path) + shutil.rmtree(self.msgq_path, ignore_errors=True) + if PC: + shutil.rmtree(Paths.log_root(), ignore_errors=True) + if not os.environ.get("COMMA_CACHE", False): + shutil.rmtree(Paths.download_cache_root(), ignore_errors=True) + shutil.rmtree(Paths.comma_home(), ignore_errors=True) diff --git a/common/queue.h b/openpilot/common/queue.h similarity index 100% rename from common/queue.h rename to openpilot/common/queue.h diff --git a/common/ratekeeper.cc b/openpilot/common/ratekeeper.cc similarity index 82% rename from common/ratekeeper.cc rename to openpilot/common/ratekeeper.cc index 7e63815168..a79acd7d51 100644 --- a/common/ratekeeper.cc +++ b/openpilot/common/ratekeeper.cc @@ -6,9 +6,9 @@ #include "common/timing.h" #include "common/util.h" -RateKeeper::RateKeeper(const std::string &name, float rate, float print_delay_threshold) - : name(name), - print_delay_threshold(std::max(0.f, print_delay_threshold)) { +RateKeeper::RateKeeper(const std::string &name_, float rate, float print_delay_threshold_) + : name(name_), + print_delay_threshold(std::max(0.f, print_delay_threshold_)) { interval = 1 / rate; last_monitor_time = seconds_since_boot(); next_frame_time = last_monitor_time + interval; diff --git a/common/ratekeeper.h b/openpilot/common/ratekeeper.h similarity index 100% rename from common/ratekeeper.h rename to openpilot/common/ratekeeper.h diff --git a/common/realtime.py b/openpilot/common/realtime.py similarity index 92% rename from common/realtime.py rename to openpilot/common/realtime.py index 57926b4c4f..e0b9e8a3a5 100644 --- a/common/realtime.py +++ b/openpilot/common/realtime.py @@ -6,8 +6,8 @@ import time from setproctitle import getproctitle -from openpilot.common.util import MovingAverage -from openpilot.system.hardware import PC +from openpilot.common.utils import MovingAverage +from openpilot.common.hardware import PC # time step for each process @@ -28,6 +28,11 @@ class Priority: CTRL_HIGH = 53 +def drop_realtime() -> None: + if sys.platform == 'linux' and not PC: + os.sched_setscheduler(0, os.SCHED_OTHER, os.sched_param(0)) + + def set_core_affinity(cores: list[int]) -> None: if sys.platform == 'linux' and not PC: os.sched_setaffinity(0, cores) diff --git a/openpilot/common/serial.py b/openpilot/common/serial.py new file mode 100644 index 0000000000..68083f40a6 --- /dev/null +++ b/openpilot/common/serial.py @@ -0,0 +1,272 @@ +import errno +import fcntl +import os +import select +import struct +import termios +import time + + +# Modem control lines (linux/termios.h); fall back to common x86_64 values. +TIOCMBIS = getattr(termios, "TIOCMBIS", 0x5416) +TIOCMBIC = getattr(termios, "TIOCMBIC", 0x5417) +TIOCM_DTR = getattr(termios, "TIOCM_DTR", 0x002) +TIOCM_RTS = getattr(termios, "TIOCM_RTS", 0x004) +_TIOCM_DTR = struct.pack("I", TIOCM_DTR) +_TIOCM_RTS = struct.pack("I", TIOCM_RTS) + + +class SerialException(OSError): + pass + + +class Serial: + def __init__(self, port: str, baudrate: int = 9600, timeout: float | None = None, *, + rtscts: bool = False, dsrdtr: bool = False, exclusive: bool = False): + self._port = port + self._baudrate = baudrate + self._timeout = timeout + self._rtscts = rtscts + self._dsrdtr = dsrdtr + self._exclusive = exclusive + self._dtr = True + self._fd = -1 + self.open() + + def __enter__(self): + return self + + def __exit__(self, *args) -> None: + self.close() + + @property + def fd(self) -> int: + self._ensure_open() + return self._fd + + @property + def baudrate(self) -> int: + return self._baudrate + + @baudrate.setter + def baudrate(self, value: int) -> None: + self._baudrate = int(value) + if self._fd >= 0: + self._configure() + + @property + def dtr(self) -> bool: + return self._dtr + + @dtr.setter + def dtr(self, value: bool) -> None: + self._dtr = bool(value) + if self._fd >= 0: + self._set_line(TIOCM_DTR, _TIOCM_DTR, self._dtr) + + def open(self) -> None: + if self._fd >= 0: + return + try: + self._fd = os.open(self._port, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK) + except OSError as e: + self._fd = -1 + raise SerialException(e.errno, f"could not open port {self._port}: {e}") from e + + try: + if self._exclusive: + try: + fcntl.flock(self._fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError as e: + raise SerialException(e.errno, f"could not exclusively lock port {self._port}: {e}") from e + + self._configure() + + # When not using hardware DSR/DTR handshaking, drive lines ourselves. + if not self._dsrdtr: + try: + self._set_line(TIOCM_DTR, _TIOCM_DTR, self._dtr) + if not self._rtscts: + self._set_line(TIOCM_RTS, _TIOCM_RTS, True) + except OSError as e: + if e.errno not in (errno.EINVAL, errno.ENOTTY): + raise + + self.reset_input_buffer() + except BaseException: + self._close_fd() + raise + + def close(self) -> None: + self._close_fd() + + def read(self, size: int = 1) -> bytes: + self._ensure_open() + if size <= 0: + return b"" + + buf = bytearray() + deadline = self._deadline() + while len(buf) < size: + remaining = None if deadline is None else max(0.0, deadline - time.monotonic()) + if not self._wait_readable(remaining): + break + try: + chunk = os.read(self._fd, size - len(buf)) + except InterruptedError: + continue + except OSError as e: + if e.errno in (errno.EAGAIN, errno.EWOULDBLOCK): + if self._timeout == 0: + break + continue + raise SerialException(e.errno, f"read failed: {e}") from e + if not chunk: + break + buf.extend(chunk) + return bytes(buf) + + def readline(self) -> bytes: + self._ensure_open() + buf = bytearray() + deadline = self._deadline() + while True: + remaining = None if deadline is None else max(0.0, deadline - time.monotonic()) + if deadline is not None and remaining == 0.0 and not buf: + # match pyserial: timed-out readline returns empty + if not self._wait_readable(0.0): + return b"" + elif not self._wait_readable(remaining): + return bytes(buf) + + try: + chunk = os.read(self._fd, 1) + except InterruptedError: + continue + except OSError as e: + if e.errno in (errno.EAGAIN, errno.EWOULDBLOCK): + if self._timeout == 0: + return bytes(buf) + continue + raise SerialException(e.errno, f"read failed: {e}") from e + if not chunk: + return bytes(buf) + buf.extend(chunk) + if chunk == b"\n": + return bytes(buf) + + def write(self, data: bytes) -> int: + self._ensure_open() + if not data: + return 0 + view = memoryview(data) + total = 0 + while total < len(data): + try: + n = os.write(self._fd, view[total:]) + except InterruptedError: + continue + except OSError as e: + if e.errno in (errno.EAGAIN, errno.EWOULDBLOCK): + select.select([], [self._fd], [], None) + continue + raise SerialException(e.errno, f"write failed: {e}") from e + if n == 0: + raise SerialException("write returned 0") + total += n + return total + + def flush(self) -> None: + self._ensure_open() + termios.tcdrain(self._fd) + + def reset_input_buffer(self) -> None: + self._ensure_open() + termios.tcflush(self._fd, termios.TCIFLUSH) + + def reset_output_buffer(self) -> None: + self._ensure_open() + termios.tcflush(self._fd, termios.TCOFLUSH) + + def _close_fd(self) -> None: + if self._fd >= 0: + try: + if self._exclusive: + fcntl.flock(self._fd, fcntl.LOCK_UN) + except OSError: + pass + try: + os.close(self._fd) + except OSError: + pass + self._fd = -1 + + def _ensure_open(self) -> None: + if self._fd < 0: + raise SerialException("port is not open") + + def _deadline(self) -> float | None: + if self._timeout is None: + return None + if self._timeout == 0: + return time.monotonic() + return time.monotonic() + self._timeout + + def _wait_readable(self, timeout: float | None) -> bool: + """Return True if fd is readable. timeout None blocks; 0 polls.""" + if timeout is not None and timeout < 0: + timeout = 0.0 + try: + ready, _, _ = select.select([self._fd], [], [], timeout) + except InterruptedError: + return False + return bool(ready) + + def _baud_constant(self, baudrate: int) -> int: + try: + return getattr(termios, f"B{baudrate}") + except AttributeError as e: + raise ValueError(f"unsupported baud rate: {baudrate}") from e + + def _configure(self) -> None: + self._ensure_open() + try: + attrs = termios.tcgetattr(self._fd) + except termios.error as e: + raise SerialException(f"could not get port attributes: {e}") from e + + iflag, oflag, cflag, lflag, _ispeed, _ospeed, cc = attrs + + # raw binary 8N1 + iflag = 0 + oflag = 0 + lflag = 0 + cflag |= termios.CLOCAL | termios.CREAD + cflag &= ~termios.CSIZE + cflag |= termios.CS8 + cflag &= ~(termios.PARENB | termios.PARODD | termios.CSTOPB) + + if hasattr(termios, "CRTSCTS"): + if self._rtscts: + cflag |= termios.CRTSCTS + else: + cflag &= ~termios.CRTSCTS + + speed = self._baud_constant(self._baudrate) + cc = list(cc) + # Non-blocking reads are handled via select + O_NONBLOCK; keep VMIN/VTIME at 0. + cc[termios.VMIN] = 0 + cc[termios.VTIME] = 0 + + try: + termios.tcsetattr(self._fd, termios.TCSANOW, [iflag, oflag, cflag, lflag, speed, speed, cc]) + except termios.error as e: + raise SerialException(f"could not configure port: {e}") from e + + # Keep the fd non-blocking so timeout=0 and select work consistently. + flags = fcntl.fcntl(self._fd, fcntl.F_GETFL) + fcntl.fcntl(self._fd, fcntl.F_SETFL, flags | os.O_NONBLOCK) + + def _set_line(self, _bit: int, packed: bytes, enabled: bool) -> None: + request = TIOCMBIS if enabled else TIOCMBIC + fcntl.ioctl(self._fd, request, packed) diff --git a/common/simple_kalman.py b/openpilot/common/simple_kalman.py similarity index 100% rename from common/simple_kalman.py rename to openpilot/common/simple_kalman.py diff --git a/openpilot/common/spinner.py b/openpilot/common/spinner.py new file mode 100755 index 0000000000..f152285138 --- /dev/null +++ b/openpilot/common/spinner.py @@ -0,0 +1,52 @@ +import os +import subprocess +from openpilot.common.basedir import BASEDIR + + +class Spinner: + def __init__(self): + try: + self.spinner_proc = subprocess.Popen(["./spinner.py"], + stdin=subprocess.PIPE, + cwd=os.path.join(BASEDIR, "openpilot/system", "ui"), + close_fds=True) + except OSError: + self.spinner_proc = None + + def __enter__(self): + return self + + def update(self, spinner_text: str): + if self.spinner_proc is not None: + self.spinner_proc.stdin.write(spinner_text.encode('utf8') + b"\n") + try: + self.spinner_proc.stdin.flush() + except BrokenPipeError: + pass + + def update_progress(self, cur: float, total: float): + self.update(str(round(100 * cur / total))) + + def close(self): + if self.spinner_proc is not None: + self.spinner_proc.kill() + try: + self.spinner_proc.communicate(timeout=2.) + except subprocess.TimeoutExpired: + print("WARNING: failed to kill spinner") + self.spinner_proc = None + + def __del__(self): + self.close() + + def __exit__(self, exc_type, exc_value, traceback): + self.close() + + +if __name__ == "__main__": + import time + with Spinner() as s: + s.update("Spinner text") + time.sleep(5.0) + print("gone") + time.sleep(5.0) diff --git a/common/stat_live.py b/openpilot/common/stat_live.py similarity index 100% rename from common/stat_live.py rename to openpilot/common/stat_live.py diff --git a/common/swaglog.cc b/openpilot/common/swaglog.cc similarity index 96% rename from common/swaglog.cc rename to openpilot/common/swaglog.cc index 62a405a2b6..9834098929 100644 --- a/common/swaglog.cc +++ b/openpilot/common/swaglog.cc @@ -11,9 +11,11 @@ #include #include -#include "third_party/json11/json11.hpp" +#include "json11/json11.hpp" #include "common/version.h" -#include "system/hardware/hw.h" +#include "common/hardware/hw.h" + +#include "sunnypilot/common/version.h" class SwaglogState { public: @@ -56,7 +58,7 @@ public: if (char* daemon_name = getenv("MANAGER_DAEMON")) { ctx_j["daemon"] = daemon_name; } - ctx_j["version"] = COMMA_VERSION; + ctx_j["version"] = SUNNYPILOT_VERSION; ctx_j["dirty"] = !getenv("CLEAN"); ctx_j["device"] = Hardware::get_name(); } diff --git a/common/swaglog.h b/openpilot/common/swaglog.h similarity index 100% rename from common/swaglog.h rename to openpilot/common/swaglog.h diff --git a/common/swaglog.py b/openpilot/common/swaglog.py similarity index 97% rename from common/swaglog.py rename to openpilot/common/swaglog.py index d009f00e76..8b629b3fba 100644 --- a/common/swaglog.py +++ b/openpilot/common/swaglog.py @@ -8,7 +8,7 @@ from logging.handlers import BaseRotatingHandler import zmq from openpilot.common.logging_extra import SwagLogger, SwagFormatter, SwagLogFileFormatter -from openpilot.system.hardware.hw import Paths +from openpilot.common.hardware.hw import Paths def get_file_handler(): @@ -27,7 +27,7 @@ class SwaglogRotatingFileHandler(BaseRotatingHandler): self.log_files = self.get_existing_logfiles() log_indexes = [f.split(".")[-1] for f in self.log_files] self.last_file_idx = max([int(i) for i in log_indexes if i.isdigit()] or [-1]) - self.last_rollover = None + self.last_rollover = 0.0 self.doRollover() def _open(self): @@ -39,7 +39,7 @@ class SwaglogRotatingFileHandler(BaseRotatingHandler): return stream def get_existing_logfiles(self): - log_files = list() + log_files = [] base_dir = os.path.dirname(self.base_filename) for fn in os.listdir(base_dir): fp = os.path.join(base_dir, fn) diff --git a/common/tests/.gitignore b/openpilot/common/tests/.gitignore similarity index 100% rename from common/tests/.gitignore rename to openpilot/common/tests/.gitignore diff --git a/common/transformations/__init__.py b/openpilot/common/tests/__init__.py similarity index 100% rename from common/transformations/__init__.py rename to openpilot/common/tests/__init__.py diff --git a/openpilot/common/tests/test_file_helpers.py b/openpilot/common/tests/test_file_helpers.py new file mode 100644 index 0000000000..c2b880f873 --- /dev/null +++ b/openpilot/common/tests/test_file_helpers.py @@ -0,0 +1,19 @@ +import os +from uuid import uuid4 + +from openpilot.common.utils import atomic_write + + +class TestFileHelpers: + def run_atomic_write_func(self, atomic_write_func): + path = f"/tmp/tmp{uuid4()}" + with atomic_write_func(path) as f: + f.write("test") + assert not os.path.exists(path) + + with open(path) as f: + assert f.read() == "test" + os.remove(path) + + def test_atomic_write(self): + self.run_atomic_write_func(atomic_write) diff --git a/common/tests/test_markdown.py b/openpilot/common/tests/test_markdown.py similarity index 85% rename from common/tests/test_markdown.py rename to openpilot/common/tests/test_markdown.py index d3c7e02c69..7e04bf2920 100644 --- a/common/tests/test_markdown.py +++ b/openpilot/common/tests/test_markdown.py @@ -6,7 +6,7 @@ from openpilot.common.markdown import parse_markdown class TestMarkdown: def test_all_release_notes(self): - with open(os.path.join(BASEDIR, "RELEASES.md")) as f: + with open(os.path.join(BASEDIR, "CHANGELOG.md")) as f: release_notes = f.read().split("\n\n") assert len(release_notes) > 10 diff --git a/openpilot/common/tests/test_params.py b/openpilot/common/tests/test_params.py new file mode 100644 index 0000000000..bbd411bc37 --- /dev/null +++ b/openpilot/common/tests/test_params.py @@ -0,0 +1,141 @@ +import pytest +import datetime +import os +import threading +import time +import uuid + +from openpilot.common.params import Params, ParamKeyFlag, UnknownKeyName + +class TestParams: + def setup_method(self): + self.params = Params() + + def test_params_put_and_get(self): + self.params.put("DongleId", "cb38263377b873ee", block=True) + assert self.params.get("DongleId") == "cb38263377b873ee" + + def test_params_non_ascii(self): + st = b"\xe1\x90\xff" + self.params.put("CarParams", st, block=True) + assert self.params.get("CarParams") == st + + def test_params_get_cleared_manager_start(self): + self.params.put("CarParams", b"test", block=True) + self.params.put("DongleId", "cb38263377b873ee", block=True) + assert self.params.get("CarParams") == b"test" + + undefined_param = self.params.get_param_path(uuid.uuid4().hex) + with open(undefined_param, "w") as f: + f.write("test") + assert os.path.isfile(undefined_param) + + self.params.clear_all(ParamKeyFlag.CLEAR_ON_MANAGER_START) + assert self.params.get("CarParams") is None + assert self.params.get("DongleId") is not None + assert not os.path.isfile(undefined_param) + + def test_params_two_things(self): + self.params.put("DongleId", "bob", block=True) + self.params.put("AthenadPid", 123, block=True) + assert self.params.get("DongleId") == "bob" + assert self.params.get("AthenadPid") == 123 + + def test_params_get_block(self): + def _delayed_writer(): + time.sleep(0.1) + self.params.put("CarParams", b"test", block=True) + threading.Thread(target=_delayed_writer).start() + assert self.params.get("CarParams") is None + assert self.params.get("CarParams", block=True) == b"test" + + def test_params_unknown_key_fails(self): + with pytest.raises(UnknownKeyName): + self.params.get("swag") + + with pytest.raises(UnknownKeyName): + self.params.get_bool("swag") + + with pytest.raises(UnknownKeyName): + self.params.put("swag", "abc", block=True) + + with pytest.raises(UnknownKeyName): + self.params.put_bool("swag", True, block=True) + + def test_remove_not_there(self): + assert self.params.get("CarParams") is None + self.params.remove("CarParams") + assert self.params.get("CarParams") is None + + def test_get_bool(self): + self.params.remove("IsMetric") + assert not self.params.get_bool("IsMetric") + + self.params.put_bool("IsMetric", True, block=True) + assert self.params.get_bool("IsMetric") + + self.params.put_bool("IsMetric", False, block=True) + assert not self.params.get_bool("IsMetric") + + self.params.put("IsMetric", True, block=True) + assert self.params.get_bool("IsMetric") + + self.params.put("IsMetric", False, block=True) + assert not self.params.get_bool("IsMetric") + + def test_put_non_blocking_with_get_block(self): + q = Params() + def _delayed_writer(): + time.sleep(0.1) + Params().put("CarParams", b"test") + threading.Thread(target=_delayed_writer).start() + assert q.get("CarParams") is None + assert q.get("CarParams", True) == b"test" + + def test_put_bool_non_blocking_with_get_block(self): + q = Params() + def _delayed_writer(): + time.sleep(0.1) + Params().put_bool("CarParams", True) + threading.Thread(target=_delayed_writer).start() + assert q.get("CarParams") is None + assert q.get("CarParams", True) == b"1" + + def test_params_all_keys(self): + keys = Params().all_keys() + + # sanity checks + assert len(keys) > 20 + assert len(keys) == len(set(keys)) + assert b"CarParams" in keys + + def test_params_default_value(self): + self.params.remove("LanguageSetting") + self.params.remove("LongitudinalPersonality") + self.params.remove("LiveParametersV2") + + assert self.params.get("LanguageSetting") is None + assert self.params.get("LanguageSetting", return_default=False) is None + assert isinstance(self.params.get("LanguageSetting", return_default=True), str) + assert isinstance(self.params.get("LongitudinalPersonality", return_default=True), int) + assert self.params.get("LiveParametersV2") is None + assert self.params.get("LiveParametersV2", return_default=True) is None + + def test_params_get_type(self): + # json + self.params.put("ApiCache_FirehoseStats", {"a": 0}, block=True) + assert self.params.get("ApiCache_FirehoseStats") == {"a": 0} + + # int + self.params.put("BootCount", 1441, block=True) + assert self.params.get("BootCount") == 1441 + + # bool + self.params.put("AdbEnabled", True, block=True) + assert self.params.get("AdbEnabled") + assert isinstance(self.params.get("AdbEnabled"), bool) + + # time + now = datetime.datetime.now(datetime.UTC) + self.params.put("InstallDate", now, block=True) + assert self.params.get("InstallDate") == now diff --git a/common/tests/test_runner.cc b/openpilot/common/tests/test_runner.cc similarity index 100% rename from common/tests/test_runner.cc rename to openpilot/common/tests/test_runner.cc diff --git a/common/tests/test_simple_kalman.py b/openpilot/common/tests/test_simple_kalman.py similarity index 100% rename from common/tests/test_simple_kalman.py rename to openpilot/common/tests/test_simple_kalman.py diff --git a/common/tests/test_swaglog.cc b/openpilot/common/tests/test_swaglog.cc similarity index 93% rename from common/tests/test_swaglog.cc rename to openpilot/common/tests/test_swaglog.cc index 09bc4c3795..9a76b78fd5 100644 --- a/common/tests/test_swaglog.cc +++ b/openpilot/common/tests/test_swaglog.cc @@ -6,8 +6,10 @@ #include "common/swaglog.h" #include "common/util.h" #include "common/version.h" -#include "system/hardware/hw.h" -#include "third_party/json11/json11.hpp" +#include "common/hardware/hw.h" +#include "json11/json11.hpp" + +#include "sunnypilot/common/version.h" std::string daemon_name = "testy"; std::string dongle_id = "test_dongle_id"; @@ -53,7 +55,7 @@ void recv_log(int thread_cnt, int thread_msg_cnt) { REQUIRE(ctx["dongle_id"].string_value() == dongle_id); REQUIRE(ctx["dirty"].bool_value() == true); - REQUIRE(ctx["version"].string_value() == COMMA_VERSION); + REQUIRE(ctx["version"].string_value() == SUNNYPILOT_VERSION); std::string device = Hardware::get_name(); REQUIRE(ctx["device"].string_value() == device); diff --git a/common/tests/test_util.cc b/openpilot/common/tests/test_util.cc similarity index 90% rename from common/tests/test_util.cc rename to openpilot/common/tests/test_util.cc index de87fa3e06..d927b98a4d 100644 --- a/common/tests/test_util.cc +++ b/openpilot/common/tests/test_util.cc @@ -36,7 +36,7 @@ TEST_CASE("util::read_file") { REQUIRE(util::read_file(filename).empty()); std::string content = random_bytes(64 * 1024); - write(fd, content.c_str(), content.size()); + REQUIRE(write(fd, content.c_str(), content.size()) == (ssize_t)content.size()); std::string ret = util::read_file(filename); bool equal = (ret == content); REQUIRE(equal); @@ -114,12 +114,12 @@ TEST_CASE("util::safe_fwrite") { } TEST_CASE("util::create_directories") { - system("rm /tmp/test_create_directories -rf"); + REQUIRE(system("rm /tmp/test_create_directories -rf") == 0); std::string dir = "/tmp/test_create_directories/a/b/c/d/e/f"; - auto check_dir_permissions = [](const std::string &dir, mode_t mode) -> bool { + auto check_dir_permissions = [](const std::string &path, mode_t mode) -> bool { struct stat st = {}; - return stat(dir.c_str(), &st) == 0 && (st.st_mode & S_IFMT) == S_IFDIR && (st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO)) == mode; + return stat(path.c_str(), &st) == 0 && (st.st_mode & S_IFMT) == S_IFDIR && (st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO)) == mode; }; SECTION("create_directories") { @@ -132,7 +132,7 @@ TEST_CASE("util::create_directories") { } SECTION("a file exists with the same name") { REQUIRE(util::create_directories(dir, 0755)); - int f = open((dir + "/file").c_str(), O_RDWR | O_CREAT); + int f = open((dir + "/file").c_str(), O_RDWR | O_CREAT, 0644); REQUIRE(f != -1); close(f); REQUIRE(util::create_directories(dir + "/file", 0755) == false); diff --git a/common/text_window.py b/openpilot/common/text_window.py similarity index 98% rename from common/text_window.py rename to openpilot/common/text_window.py index 358243d1f1..94cfa7811e 100755 --- a/common/text_window.py +++ b/openpilot/common/text_window.py @@ -10,7 +10,7 @@ class TextWindow: try: self.text_proc = subprocess.Popen(["./text.py", text], stdin=subprocess.PIPE, - cwd=os.path.join(BASEDIR, "system", "ui"), + cwd=os.path.join(BASEDIR, "openpilot/system", "ui"), close_fds=True) except OSError: self.text_proc = None diff --git a/common/time_helpers.py b/openpilot/common/time_helpers.py similarity index 79% rename from common/time_helpers.py rename to openpilot/common/time_helpers.py index 8564e270c2..c709182d45 100644 --- a/common/time_helpers.py +++ b/openpilot/common/time_helpers.py @@ -2,6 +2,7 @@ import datetime from pathlib import Path MIN_DATE = datetime.datetime(year=2025, month=2, day=21) +MAX_DATE = datetime.datetime(year=2035, month=1, day=1) def min_date(): # on systemd systems, the default time is the systemd build time @@ -12,4 +13,4 @@ def min_date(): return MIN_DATE def system_time_valid(): - return datetime.datetime.now() > min_date() + return min_date() < datetime.datetime.now() < MAX_DATE diff --git a/common/timeout.py b/openpilot/common/timeout.py similarity index 100% rename from common/timeout.py rename to openpilot/common/timeout.py diff --git a/common/timing.h b/openpilot/common/timing.h similarity index 100% rename from common/timing.h rename to openpilot/common/timing.h diff --git a/common/transformations/README.md b/openpilot/common/transformations/README.md similarity index 100% rename from common/transformations/README.md rename to openpilot/common/transformations/README.md diff --git a/common/transformations/tests/__init__.py b/openpilot/common/transformations/__init__.py similarity index 100% rename from common/transformations/tests/__init__.py rename to openpilot/common/transformations/__init__.py diff --git a/openpilot/common/transformations/camera.py b/openpilot/common/transformations/camera.py new file mode 100644 index 0000000000..ada9c5b398 --- /dev/null +++ b/openpilot/common/transformations/camera.py @@ -0,0 +1,178 @@ +import itertools +import numpy as np +from dataclasses import dataclass + +import openpilot.common.transformations.orientation as orient + +## -- hardcoded hardware params -- +@dataclass(frozen=True) +class CameraConfig: + width: int + height: int + focal_length: float + + @property + def size(self): + return (self.width, self.height) + + @property + def intrinsics(self): + # aka 'K' aka camera_frame_from_view_frame + return np.array([ + [self.focal_length, 0.0, float(self.width)/2], + [0.0, self.focal_length, float(self.height)/2], + [0.0, 0.0, 1.0] + ]) + + @property + def intrinsics_inv(self): + # aka 'K_inv' aka view_frame_from_camera_frame + return np.linalg.inv(self.intrinsics) + +@dataclass(frozen=True) +class _NoneCameraConfig(CameraConfig): + width: int = 0 + height: int = 0 + focal_length: float = 0 + +@dataclass(frozen=True) +class DeviceCameraConfig: + fcam: CameraConfig + dcam: CameraConfig + ecam: CameraConfig + + def all_cams(self): + for cam in ['fcam', 'dcam', 'ecam']: + if not isinstance(getattr(self, cam), _NoneCameraConfig): + yield cam, getattr(self, cam) + +_ar_ox_fisheye = CameraConfig(1928, 1208, 567.0) # focal length probably wrong? magnification is not consistent across frame +_os_fisheye = CameraConfig(2688 // 2, 1520 // 2, 567.0 / 4 * 3) +_ar_ox_config = DeviceCameraConfig(CameraConfig(1928, 1208, 2648.0), _ar_ox_fisheye, _ar_ox_fisheye) +_os_config = DeviceCameraConfig(CameraConfig(2688 // 2, 1520 // 2, 1522.0 * 3 / 4), _os_fisheye, _os_fisheye) +_neo_config = DeviceCameraConfig(CameraConfig(1164, 874, 910.0), CameraConfig(816, 612, 650.0), _NoneCameraConfig()) + +DEVICE_CAMERAS: dict[tuple[str, str], DeviceCameraConfig] = { + # A "device camera" is defined by a device type and sensor + + # sensor type was never set on eon/neo/two + ("neo", "unknown"): _neo_config, + # unknown here is AR0231, field was added with OX03C10 support + ("tici", "unknown"): _ar_ox_config, + + # before deviceState.deviceType was set, assume tici AR config + ("unknown", "ar0231"): _ar_ox_config, + ("unknown", "ox03c10"): _ar_ox_config, + + # simulator (emulates a tici) + ("pc", "unknown"): _ar_ox_config, +} +prods = itertools.product(('tici', 'tizi', 'mici'), (('ar0231', _ar_ox_config), ('ox03c10', _ar_ox_config), ('os04c10', _os_config))) +DEVICE_CAMERAS.update({(d, c[0]): c[1] for d, c in prods}) + +# device/mesh : x->forward, y-> right, z->down +# view : x->right, y->down, z->forward +device_frame_from_view_frame = np.array([ + [ 0., 0., 1.], + [ 1., 0., 0.], + [ 0., 1., 0.] +]) +view_frame_from_device_frame = device_frame_from_view_frame.T + + +# aka 'extrinsic_matrix' +# road : x->forward, y -> left, z->up +def get_view_frame_from_road_frame(roll, pitch, yaw, height): + device_from_road = orient.rot_from_euler([roll, pitch, yaw]).dot(np.diag([1, -1, -1])) + view_from_road = view_frame_from_device_frame.dot(device_from_road) + return np.hstack((view_from_road, [[0], [height], [0]])) + + + +# aka 'extrinsic_matrix' +def get_view_frame_from_calib_frame(roll, pitch, yaw, height): + device_from_calib= orient.rot_from_euler([roll, pitch, yaw]) + view_from_calib = view_frame_from_device_frame.dot(device_from_calib) + return np.hstack((view_from_calib, [[0], [height], [0]])) + + +def vp_from_ke(m): + """ + Computes the vanishing point from the product of the intrinsic and extrinsic + matrices C = KE. + + The vanishing point is defined as lim x->infinity C (x, 0, 0, 1).T + """ + return (m[0, 0]/m[2, 0], m[1, 0]/m[2, 0]) + + +def roll_from_ke(m): + # note: different from calibration.h/RollAnglefromKE: i think that one's just wrong + return np.arctan2(-(m[1, 0] - m[1, 1] * m[2, 0] / m[2, 1]), + -(m[0, 0] - m[0, 1] * m[2, 0] / m[2, 1])) + + +def normalize(img_pts, intrinsics): + # normalizes image coordinates + # accepts single pt or array of pts + intrinsics_inv = np.linalg.inv(intrinsics) + img_pts = np.array(img_pts) + input_shape = img_pts.shape + img_pts = np.atleast_2d(img_pts) + img_pts = np.hstack((img_pts, np.ones((img_pts.shape[0], 1)))) + img_pts_normalized = img_pts.dot(intrinsics_inv.T) + img_pts_normalized[(img_pts < 0).any(axis=1)] = np.nan + return img_pts_normalized[:, :2].reshape(input_shape) + + +def denormalize(img_pts, intrinsics, width=np.inf, height=np.inf): + # denormalizes image coordinates + # accepts single pt or array of pts + img_pts = np.array(img_pts) + input_shape = img_pts.shape + img_pts = np.atleast_2d(img_pts) + img_pts = np.hstack((img_pts, np.ones((img_pts.shape[0], 1), dtype=img_pts.dtype))) + img_pts_denormalized = img_pts.dot(intrinsics.T) + if np.isfinite(width): + img_pts_denormalized[img_pts_denormalized[:, 0] > width] = np.nan + img_pts_denormalized[img_pts_denormalized[:, 0] < 0] = np.nan + if np.isfinite(height): + img_pts_denormalized[img_pts_denormalized[:, 1] > height] = np.nan + img_pts_denormalized[img_pts_denormalized[:, 1] < 0] = np.nan + return img_pts_denormalized[:, :2].reshape(input_shape) + + +def get_calib_from_vp(vp, intrinsics): + vp_norm = normalize(vp, intrinsics) + yaw_calib = np.arctan(vp_norm[0]) + pitch_calib = -np.arctan(vp_norm[1]*np.cos(yaw_calib)) + roll_calib = 0 + return roll_calib, pitch_calib, yaw_calib + + +def device_from_ecef(pos_ecef, orientation_ecef, pt_ecef): + # device from ecef frame + # device frame is x -> forward, y-> right, z -> down + # accepts single pt or array of pts + input_shape = pt_ecef.shape + pt_ecef = np.atleast_2d(pt_ecef) + ecef_from_device_rot = orient.rotations_from_quats(orientation_ecef) + device_from_ecef_rot = ecef_from_device_rot.T + pt_ecef_rel = pt_ecef - pos_ecef + pt_device = np.einsum('jk,ik->ij', device_from_ecef_rot, pt_ecef_rel) + return pt_device.reshape(input_shape) + + +def img_from_device(pt_device): + # img coordinates from pts in device frame + # first transforms to view frame, then to img coords + # accepts single pt or array of pts + input_shape = pt_device.shape + pt_device = np.atleast_2d(pt_device) + pt_view = np.einsum('jk,ik->ij', view_frame_from_device_frame, pt_device) + + # This function should never return negative depths + pt_view[pt_view[:, 2] < 0] = np.nan + + pt_img = pt_view/pt_view[:, 2:3] + return pt_img.reshape(input_shape)[:, :2] diff --git a/common/transformations/coordinates.py b/openpilot/common/transformations/coordinates.py similarity index 100% rename from common/transformations/coordinates.py rename to openpilot/common/transformations/coordinates.py diff --git a/common/transformations/model.py b/openpilot/common/transformations/model.py similarity index 100% rename from common/transformations/model.py rename to openpilot/common/transformations/model.py diff --git a/common/transformations/orientation.py b/openpilot/common/transformations/orientation.py similarity index 95% rename from common/transformations/orientation.py rename to openpilot/common/transformations/orientation.py index 86e6a6c347..d2ccda13a5 100644 --- a/common/transformations/orientation.py +++ b/openpilot/common/transformations/orientation.py @@ -25,11 +25,10 @@ def numpy_wrap(function, input_shape, output_shape) -> Callable[..., np.ndarray] # Add empty dimension if inputs is not a list if len(shape) == len(input_shape): - inp.shape = (1, ) + inp.shape + inp = inp.reshape((1, ) + inp.shape) result = np.asarray([function(*args, i) for i in inp]) - result.shape = out_shape - return result + return result.reshape(out_shape) return f diff --git a/selfdrive/__init__.py b/openpilot/common/transformations/tests/__init__.py similarity index 100% rename from selfdrive/__init__.py rename to openpilot/common/transformations/tests/__init__.py diff --git a/common/transformations/tests/test_coordinates.py b/openpilot/common/transformations/tests/test_coordinates.py similarity index 84% rename from common/transformations/tests/test_coordinates.py rename to openpilot/common/transformations/tests/test_coordinates.py index 11a6bf70ee..0b5d1c36df 100644 --- a/common/transformations/tests/test_coordinates.py +++ b/openpilot/common/transformations/tests/test_coordinates.py @@ -102,3 +102,36 @@ class TestNED: np.testing.assert_allclose(converter.ned2ecef(ned_offsets_batch), ecef_positions_offset_batch, rtol=1e-9, atol=1e-7) + + def test_errors(self): + # Test wrong shape/type for geodetic2ecef + # numpy_wrap raises IndexError for scalar input + with np.testing.assert_raises(IndexError): + coord.geodetic2ecef(1.0) + + with np.testing.assert_raises_regex(ValueError, "Geodetic must be size 3"): + coord.geodetic2ecef([0, 0]) + + with np.testing.assert_raises_regex(ValueError, "Geodetic must be size 3"): + coord.geodetic2ecef([0, 0, 0, 0]) + + with np.testing.assert_raises(TypeError): + coord.geodetic2ecef(['a', 'b', 'c']) + + # Test LocalCoord constructor errors + with np.testing.assert_raises(ValueError): + coord.LocalCoord.from_geodetic([0, 0]) + + with np.testing.assert_raises(ValueError): + coord.LocalCoord.from_geodetic(1) + + with np.testing.assert_raises(TypeError): + coord.LocalCoord.from_geodetic(['a', 'b', 'c']) + + # Test wrong shape/type for ecef2geodetic + with np.testing.assert_raises(ValueError): + coord.ecef2geodetic([1, 2]) + with np.testing.assert_raises(ValueError): + coord.ecef2geodetic([1, 2, 3, 4]) + with np.testing.assert_raises(IndexError): + coord.ecef2geodetic(1.0) diff --git a/common/transformations/tests/test_orientation.py b/openpilot/common/transformations/tests/test_orientation.py similarity index 81% rename from common/transformations/tests/test_orientation.py rename to openpilot/common/transformations/tests/test_orientation.py index 55fbc6581e..1bf94115c8 100644 --- a/common/transformations/tests/test_orientation.py +++ b/openpilot/common/transformations/tests/test_orientation.py @@ -1,4 +1,5 @@ import numpy as np +import pytest from openpilot.common.transformations.orientation import euler2quat, quat2euler, euler2rot, rot2euler, \ rot2quat, quat2rot, \ @@ -59,3 +60,32 @@ class TestOrientation: np.testing.assert_allclose(ned_eulers[i], ned_euler_from_ecef(ecef_positions[i], eulers[i]), rtol=1e-7) #np.testing.assert_allclose(eulers[i], ecef_euler_from_ned(ecef_positions[i], ned_eulers[i]), rtol=1e-7) # np.testing.assert_allclose(ned_eulers, ned_euler_from_ecef(ecef_positions, eulers), rtol=1e-7) + + def test_inputs(self): + with pytest.raises(ValueError): + euler2quat([1, 2]) + + with pytest.raises(ValueError): + quat2rot([1, 2, 3]) + + with pytest.raises(IndexError): + rot2quat(np.zeros((2, 2))) + + def test_euler_rot_consistency(self): + rpy = [0.1, 0.2, 0.3] + R = euler2rot(rpy) + + # R -> q -> R + q = rot2quat(R) + R_new = quat2rot(q) + np.testing.assert_allclose(R, R_new, atol=1e-15) + + # q -> R -> Euler (quat2euler) -> R + rpy_new = quat2euler(q) + R_new2 = euler2rot(rpy_new) + np.testing.assert_allclose(R, R_new2, atol=1e-15) + + # R -> Euler (rot2euler) -> R + rpy_from_rot = rot2euler(R) + R_new3 = euler2rot(rpy_from_rot) + np.testing.assert_allclose(R, R_new3, atol=1e-15) diff --git a/openpilot/common/transformations/transformations.py b/openpilot/common/transformations/transformations.py new file mode 100644 index 0000000000..5cb6220f95 --- /dev/null +++ b/openpilot/common/transformations/transformations.py @@ -0,0 +1,342 @@ +import numpy as np + + +# Constants +a = 6378137.0 +b = 6356752.3142 +esq = 6.69437999014e-3 +e1sq = 6.73949674228e-3 + + +def geodetic2ecef_single(g): + """ + Convert geodetic coordinates (latitude, longitude, altitude) to ECEF. + """ + try: + if len(g) != 3: + raise ValueError("Geodetic must be size 3") + except TypeError: + raise ValueError("Geodetic must be a sequence of length 3") from None + + lat, lon, alt = g + lat = np.radians(lat) + lon = np.radians(lon) + xi = np.sqrt(1.0 - esq * np.sin(lat)**2) + x = (a / xi + alt) * np.cos(lat) * np.cos(lon) + y = (a / xi + alt) * np.cos(lat) * np.sin(lon) + z = (a / xi * (1.0 - esq) + alt) * np.sin(lat) + return np.array([x, y, z]) + + +def ecef2geodetic_single(e): + """ + Convert ECEF to geodetic coordinates using Ferrari's solution. + """ + x, y, z = e + r = np.sqrt(x**2 + y**2) + Esq = a**2 - b**2 + F = 54 * b**2 * z**2 + G = r**2 + (1 - esq) * z**2 - esq * Esq + C = (esq**2 * F * r**2) / (G**3) + S = np.cbrt(1 + C + np.sqrt(C**2 + 2 * C)) + P = F / (3 * (S + 1 / S + 1)**2 * G**2) + Q = np.sqrt(1 + 2 * esq**2 * P) + r_0 = -(P * esq * r) / (1 + Q) + np.sqrt(0.5 * a**2 * (1 + 1.0 / Q) - P * (1 - esq) * z**2 / (Q * (1 + Q)) - 0.5 * P * r**2) + U = np.sqrt((r - esq * r_0)**2 + z**2) + V = np.sqrt((r - esq * r_0)**2 + (1 - esq) * z**2) + Z_0 = b**2 * z / (a * V) + h = U * (1 - b**2 / (a * V)) + lat = np.arctan((z + e1sq * Z_0) / r) + lon = np.arctan2(y, x) + return np.array([np.degrees(lat), np.degrees(lon), h]) + + +def euler2quat_single(euler): + """ + Convert Euler angles (roll, pitch, yaw) to a quaternion. + Rotation order: Z-Y-X (yaw, pitch, roll). + """ + phi, theta, psi = euler + + c_phi, s_phi = np.cos(phi / 2), np.sin(phi / 2) + c_theta, s_theta = np.cos(theta / 2), np.sin(theta / 2) + c_psi, s_psi = np.cos(psi / 2), np.sin(psi / 2) + + w = c_phi * c_theta * c_psi + s_phi * s_theta * s_psi + x = s_phi * c_theta * c_psi - c_phi * s_theta * s_psi + y = c_phi * s_theta * c_psi + s_phi * c_theta * s_psi + z = c_phi * c_theta * s_psi - s_phi * s_theta * c_psi + + if w < 0: + return np.array([-w, -x, -y, -z]) + return np.array([w, x, y, z]) + + +def quat2euler_single(q): + """ + Convert a quaternion to Euler angles (roll, pitch, yaw). + """ + w, x, y, z = q + gamma = np.arctan2(2 * (w * x + y * z), 1 - 2 * (x**2 + y**2)) + sin_arg = 2 * (w * y - z * x) + sin_arg = np.clip(sin_arg, -1.0, 1.0) + theta = np.arcsin(sin_arg) + psi = np.arctan2(2 * (w * z + x * y), 1 - 2 * (y**2 + z**2)) + return np.array([gamma, theta, psi]) + + +def quat2rot_single(q): + """ + Convert a quaternion to a 3x3 rotation matrix. + """ + w, x, y, z = q + xx, yy, zz = x * x, y * y, z * z + xy, xz, yz = x * y, x * z, y * z + wx, wy, wz = w * x, w * y, w * z + + mat = np.array([ + [1 - 2 * (yy + zz), 2 * (xy - wz), 2 * (xz + wy)], + [2 * (xy + wz), 1 - 2 * (xx + zz), 2 * (yz - wx)], + [2 * (xz - wy), 2 * (yz + wx), 1 - 2 * (xx + yy)] + ]) + return mat + + +def rot2quat_single(rot): + """ + Convert a 3x3 rotation matrix to a quaternion. + """ + trace = np.trace(rot) + if trace > 0: + s = 0.5 / np.sqrt(trace + 1.0) + w = 0.25 / s + x = (rot[2, 1] - rot[1, 2]) * s + y = (rot[0, 2] - rot[2, 0]) * s + z = (rot[1, 0] - rot[0, 1]) * s + else: + if rot[0, 0] > rot[1, 1] and rot[0, 0] > rot[2, 2]: + s = 2.0 * np.sqrt(1.0 + rot[0, 0] - rot[1, 1] - rot[2, 2]) + w = (rot[2, 1] - rot[1, 2]) / s + x = 0.25 * s + y = (rot[0, 1] + rot[1, 0]) / s + z = (rot[0, 2] + rot[2, 0]) / s + elif rot[1, 1] > rot[2, 2]: + s = 2.0 * np.sqrt(1.0 + rot[1, 1] - rot[0, 0] - rot[2, 2]) + w = (rot[0, 2] - rot[2, 0]) / s + x = (rot[0, 1] + rot[1, 0]) / s + y = 0.25 * s + z = (rot[1, 2] + rot[2, 1]) / s + else: + s = 2.0 * np.sqrt(1.0 + rot[2, 2] - rot[0, 0] - rot[1, 1]) + w = (rot[1, 0] - rot[0, 1]) / s + x = (rot[0, 2] + rot[2, 0]) / s + y = (rot[1, 2] + rot[2, 1]) / s + z = 0.25 * s + + if w < 0: + return np.array([-w, -x, -y, -z]) + return np.array([w, x, y, z]) + + +def euler2rot_single(euler): + """ + Convert Euler angles (roll, pitch, yaw) to a 3x3 rotation matrix. + Rotation order: Z-Y-X (yaw, pitch, roll). + """ + phi, theta, psi = euler + + cx, sx = np.cos(phi), np.sin(phi) + cy, sy = np.cos(theta), np.sin(theta) + cz, sz = np.cos(psi), np.sin(psi) + + Rx = np.array([[1, 0, 0], [0, cx, -sx], [0, sx, cx]]) + Ry = np.array([[cy, 0, sy], [0, 1, 0], [-sy, 0, cy]]) + Rz = np.array([[cz, -sz, 0], [sz, cz, 0], [0, 0, 1]]) + + return Rz @ Ry @ Rx + + +def rot2euler_single(rot): + """ + Convert a 3x3 rotation matrix to Euler angles (roll, pitch, yaw). + """ + return quat2euler_single(rot2quat_single(rot)) + + +def rot_matrix(roll, pitch, yaw): + """ + Create a 3x3 rotation matrix from roll, pitch, and yaw angles. + """ + return euler2rot_single([roll, pitch, yaw]) + + +def axis_angle_to_rot(axis, angle): + """ + Convert an axis-angle representation to a 3x3 rotation matrix. + """ + c = np.cos(angle / 2) + s = np.sin(angle / 2) + q = np.array([c, s*axis[0], s*axis[1], s*axis[2]]) + return quat2rot_single(q) + + +class LocalCoord: + """ + A class to handle conversions between ECEF and local NED coordinates. + """ + def __init__(self, geodetic=None, ecef=None): + """ + Initialize LocalCoord with either geodetic or ECEF coordinates. + """ + if geodetic is not None: + self.init_ecef = geodetic2ecef_single(geodetic) + lat, lon, _ = geodetic + elif ecef is not None: + self.init_ecef = np.array(ecef) + lat, lon, _ = ecef2geodetic_single(ecef) + else: + raise ValueError("Must provide geodetic or ecef") + + lat = np.radians(lat) + lon = np.radians(lon) + + self.ned2ecef_matrix = np.array([ + [-np.sin(lat) * np.cos(lon), -np.sin(lon), -np.cos(lat) * np.cos(lon)], + [-np.sin(lat) * np.sin(lon), np.cos(lon), -np.cos(lat) * np.sin(lon)], + [np.cos(lat), 0, -np.sin(lat)] + ]) + self.ecef2ned_matrix = self.ned2ecef_matrix.T + + @classmethod + def from_geodetic(cls, geodetic): + """ + Create a LocalCoord instance from geodetic coordinates. + """ + return cls(geodetic=geodetic) + + @classmethod + def from_ecef(cls, ecef): + """ + Create a LocalCoord instance from ECEF coordinates. + """ + return cls(ecef=ecef) + + def ecef2ned_single(self, ecef): + """ + Convert a single ECEF point to NED coordinates relative to the origin. + """ + return self.ecef2ned_matrix @ (ecef - self.init_ecef) + + def ned2ecef_single(self, ned): + """ + Convert a single NED point to ECEF coordinates. + """ + return self.ned2ecef_matrix @ ned + self.init_ecef + + def geodetic2ned_single(self, geodetic): + """ + Convert a single geodetic point to NED coordinates. + """ + ecef = geodetic2ecef_single(geodetic) + return self.ecef2ned_single(ecef) + + def ned2geodetic_single(self, ned): + """ + Convert a single NED point to geodetic coordinates. + """ + ecef = self.ned2ecef_single(ned) + return ecef2geodetic_single(ecef) + + @property + def ned_from_ecef_matrix(self): + """ + Returns the rotation matrix from ECEF to NED coordinates. + """ + return self.ecef2ned_matrix + + @property + def ecef_from_ned_matrix(self): + """ + Returns the rotation matrix from NED to ECEF coordinates. + """ + return self.ned2ecef_matrix + + +def ecef_euler_from_ned_single(ecef_init, ned_pose): + """ + Convert NED Euler angles (roll, pitch, yaw) at a given ECEF origin + to equivalent ECEF Euler angles. + """ + converter = LocalCoord(ecef=ecef_init) + zero = np.array(ecef_init) + + x0 = converter.ned2ecef_single([1, 0, 0]) - zero + y0 = converter.ned2ecef_single([0, 1, 0]) - zero + z0 = converter.ned2ecef_single([0, 0, 1]) - zero + + phi, theta, psi = ned_pose + + x1 = axis_angle_to_rot(z0, psi) @ x0 + y1 = axis_angle_to_rot(z0, psi) @ y0 + z1 = axis_angle_to_rot(z0, psi) @ z0 + + x2 = axis_angle_to_rot(y1, theta) @ x1 + y2 = axis_angle_to_rot(y1, theta) @ y1 + z2 = axis_angle_to_rot(y1, theta) @ z1 + + x3 = axis_angle_to_rot(x2, phi) @ x2 + y3 = axis_angle_to_rot(x2, phi) @ y2 + + x0 = np.array([1.0, 0, 0]) + y0 = np.array([0, 1.0, 0]) + z0 = np.array([0, 0, 1.0]) + + psi_out = np.arctan2(np.dot(x3, y0), np.dot(x3, x0)) + theta_out = np.arctan2(-np.dot(x3, z0), np.sqrt(np.dot(x3, x0)**2 + np.dot(x3, y0)**2)) + + y2 = axis_angle_to_rot(z0, psi_out) @ y0 + z2 = axis_angle_to_rot(y2, theta_out) @ z0 + + phi_out = np.arctan2(np.dot(y3, z2), np.dot(y3, y2)) + + return np.array([phi_out, theta_out, psi_out]) + + +def ned_euler_from_ecef_single(ecef_init, ecef_pose): + """ + Convert ECEF Euler angles (roll, pitch, yaw) at a given ECEF origin + to equivalent NED Euler angles. + """ + converter = LocalCoord(ecef=ecef_init) + + x0 = np.array([1.0, 0, 0]) + y0 = np.array([0, 1.0, 0]) + z0 = np.array([0, 0, 1.0]) + + phi, theta, psi = ecef_pose + + x1 = axis_angle_to_rot(z0, psi) @ x0 + y1 = axis_angle_to_rot(z0, psi) @ y0 + z1 = axis_angle_to_rot(z0, psi) @ z0 + + x2 = axis_angle_to_rot(y1, theta) @ x1 + y2 = axis_angle_to_rot(y1, theta) @ y1 + z2 = axis_angle_to_rot(y1, theta) @ z1 + + x3 = axis_angle_to_rot(x2, phi) @ x2 + y3 = axis_angle_to_rot(x2, phi) @ y2 + + zero = np.array(ecef_init) + x0 = converter.ned2ecef_single([1, 0, 0]) - zero + y0 = converter.ned2ecef_single([0, 1, 0]) - zero + z0 = converter.ned2ecef_single([0, 0, 1]) - zero + + psi_out = np.arctan2(np.dot(x3, y0), np.dot(x3, x0)) + theta_out = np.arctan2(-np.dot(x3, z0), np.sqrt(np.dot(x3, x0)**2 + np.dot(x3, y0)**2)) + + y2 = axis_angle_to_rot(z0, psi_out) @ y0 + z2 = axis_angle_to_rot(y2, theta_out) @ z0 + + phi_out = np.arctan2(np.dot(y3, z2), np.dot(y3, y2)) + + return np.array([phi_out, theta_out, psi_out]) diff --git a/openpilot/common/util.cc b/openpilot/common/util.cc new file mode 100644 index 0000000000..84b47e187e --- /dev/null +++ b/openpilot/common/util.cc @@ -0,0 +1,317 @@ +#include "common/util.h" +#include "common/swaglog.h" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef __linux__ +#include +#include +#ifndef __USE_GNU +#define __USE_GNU +#endif +#include +#endif // __linux__ + +namespace util { + +void set_thread_name(const char* name) { +#ifdef __linux__ + // pthread_setname_np is dumb (fails instead of truncates) + prctl(PR_SET_NAME, (unsigned long)name, 0, 0, 0); +#endif +} + +int set_realtime_priority(int level) { +#ifdef __linux__ + long tid = syscall(SYS_gettid); + + // should match python using chrt + struct sched_param sa; + memset(&sa, 0, sizeof(sa)); + sa.sched_priority = level; + return sched_setscheduler(tid, SCHED_FIFO, &sa); +#else + return -1; +#endif +} + +int set_core_affinity(std::vector cores) { +#ifdef __linux__ + long tid = syscall(SYS_gettid); + cpu_set_t cpu; + + CPU_ZERO(&cpu); + for (const int n : cores) { + CPU_SET(n, &cpu); + } + return sched_setaffinity(tid, sizeof(cpu), &cpu); +#else + return -1; +#endif +} + +int set_file_descriptor_limit(uint64_t limit_val) { + struct rlimit limit; + int status; + + if ((status = getrlimit(RLIMIT_NOFILE, &limit)) < 0) + return status; + + limit.rlim_cur = limit_val; + if ((status = setrlimit(RLIMIT_NOFILE, &limit)) < 0) + return status; + + return 0; +} + +std::string read_file(const std::string& fn) { + std::ifstream f(fn, std::ios::binary | std::ios::in); + if (f.is_open()) { + f.seekg(0, std::ios::end); + std::streamsize size = f.tellg(); + // seekg and tellg on a directory doesn't return pos_type(-1) but max(streamsize) + if (f.good() && size > 0 && size < std::numeric_limits::max()) { + std::string result(size, '\0'); + f.seekg(0, std::ios::beg); + f.read(result.data(), size); + // return either good() or has reached end-of-file (e.g. /sys/power/wakeup_count) + if (f.good() || f.eof()) { + result.resize(f.gcount()); + return result; + } + } + // fallback for files created on read, e.g. procfs + std::stringstream buffer; + buffer << f.rdbuf(); + return buffer.str(); + } + return std::string(); +} + +std::map read_files_in_dir(const std::string &path) { + std::map ret; + DIR *d = opendir(path.c_str()); + if (!d) return ret; + + struct dirent *de = NULL; + while ((de = readdir(d))) { + if (de->d_type != DT_DIR) { + ret[de->d_name] = util::read_file(path + "/" + de->d_name); + } + } + + closedir(d); + return ret; +} + +int write_file(const char* path, const void* data, size_t size, int flags, mode_t mode) { + int fd = HANDLE_EINTR(open(path, flags, mode)); + if (fd == -1) { + return -1; + } + ssize_t n = HANDLE_EINTR(write(fd, data, size)); + close(fd); + return (n >= 0 && (size_t)n == size) ? 0 : -1; +} + +FILE* safe_fopen(const char* filename, const char* mode) { + FILE* fp = NULL; + do { + fp = fopen(filename, mode); + } while ((nullptr == fp) && (errno == EINTR)); + return fp; +} + +size_t safe_fwrite(const void* ptr, size_t size, size_t count, FILE* stream) { + size_t written = 0; + do { + size_t ret = ::fwrite((void*)((char *)ptr + written * size), size, count - written, stream); + if (ret == 0 && errno != EINTR) break; + written += ret; + } while (written != count); + return written; +} + +int safe_fflush(FILE *stream) { + int ret = EOF; + do { + ret = fflush(stream); + } while ((EOF == ret) && (errno == EINTR)); + return ret; +} + +int safe_ioctl(int fd, unsigned long request, void *argp, const char* exception_msg) { + int ret; + do { + ret = ioctl(fd, request, argp); + } while ((ret == -1) && (errno == EINTR)); + + if (ret == -1 && exception_msg) { + LOGE("safe_ioctl error: %s %s(%d) (fd: %d request: %lx argp: %p)", exception_msg, strerror(errno), errno, fd, request, argp); + throw std::runtime_error(exception_msg); + } + return ret; +} + +std::string readlink(const std::string &path) { + char buff[4096]; + ssize_t len = ::readlink(path.c_str(), buff, sizeof(buff)-1); + if (len != -1) { + buff[len] = '\0'; + return std::string(buff); + } + return ""; +} + +bool file_exists(const std::string& fn) { + struct stat st = {}; + return stat(fn.c_str(), &st) != -1; +} + +static bool createDirectory(std::string dir, mode_t mode) { + auto verify_dir = [](const std::string& path) -> bool { + struct stat st = {}; + return (stat(path.c_str(), &st) == 0 && (st.st_mode & S_IFMT) == S_IFDIR); + }; + // remove trailing /'s + while (dir.size() > 1 && dir.back() == '/') { + dir.pop_back(); + } + // try to mkdir this directory + if (mkdir(dir.c_str(), mode) == 0) return true; + if (errno == EEXIST) return verify_dir(dir); + if (errno != ENOENT) return false; + + // mkdir failed because the parent dir doesn't exist, so try to create it + size_t slash = dir.rfind('/'); + if ((slash == std::string::npos || slash < 1) || + !createDirectory(dir.substr(0, slash), mode)) { + return false; + } + + // try again + if (mkdir(dir.c_str(), mode) == 0) return true; + return errno == EEXIST && verify_dir(dir); +} + +bool create_directories(const std::string& dir, mode_t mode) { + if (dir.empty()) return false; + return createDirectory(dir, mode); +} + +std::string getenv(const char* key, std::string default_val) { + const char* val = ::getenv(key); + return val ? val : default_val; +} + +int getenv(const char* key, int default_val) { + const char* val = ::getenv(key); + return val ? atoi(val) : default_val; +} + +float getenv(const char* key, float default_val) { + const char* val = ::getenv(key); + return val ? atof(val) : default_val; +} + +std::string hexdump(const uint8_t* in, const size_t size) { + std::stringstream ss; + ss << std::hex << std::setfill('0'); + for (size_t i = 0; i < size; i++) { + ss << std::setw(2) << static_cast(in[i]); + } + return ss.str(); +} + +int random_int(int min, int max) { + std::random_device dev; + std::mt19937 rng(dev()); + std::uniform_int_distribution dist(min, max); + return dist(rng); +} + +std::string random_string(std::string::size_type length) { + const std::string chrs = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + std::mt19937 rg{std::random_device{}()}; + std::uniform_int_distribution pick(0, chrs.length() - 1); + std::string s; + s.reserve(length); + while (length--) { + s += chrs[pick(rg)]; + } + return s; +} + +bool starts_with(const std::string &s1, const std::string &s2) { + return strncmp(s1.c_str(), s2.c_str(), s2.size()) == 0; +} + +bool ends_with(const std::string& s, const std::string& suffix) { + return s.size() >= suffix.size() && + strcmp(s.c_str() + (s.size() - suffix.size()), suffix.c_str()) == 0; +} + +std::string strip(const std::string &str) { + auto should_trim = [](unsigned char ch) { + return std::isspace(ch) || ch == '\0'; + }; + + size_t start = 0; + while (start < str.size() && should_trim(static_cast(str[start]))) { + start++; + } + + if (start == str.size()) { + return ""; + } + + size_t end = str.size() - 1; + while (end > 0 && should_trim(static_cast(str[end]))) { + end--; + } + + return str.substr(start, end - start + 1); +} + +std::string check_output(const std::string& command) { + char buffer[128]; + std::string result; + std::unique_ptr pipe(popen(command.c_str(), "r"), pclose); + + if (!pipe) { + return ""; + } + + while (fgets(buffer, std::size(buffer), pipe.get()) != nullptr) { + result += std::string(buffer); + } + + return result; +} + +bool system_time_valid() { + // Default to August 26, 2024 + tm min_tm = {.tm_mday = 26, .tm_mon = 7, .tm_year = 2024 - 1900}; + time_t min_date = mktime(&min_tm); + + struct stat st; + if (stat("/lib/systemd/systemd", &st) == 0) { + min_date = std::max(min_date, st.st_mtime + 86400); // Add 1 day (86400 seconds) + } + + return time(nullptr) > min_date; +} + +} // namespace util diff --git a/openpilot/common/util.h b/openpilot/common/util.h new file mode 100644 index 0000000000..98c2883538 --- /dev/null +++ b/openpilot/common/util.h @@ -0,0 +1,195 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// keep trying if x gets interrupted by a signal +#define HANDLE_EINTR(x) \ + ({ \ + decltype(x) ret_; \ + int try_cnt = 0; \ + do { \ + ret_ = (x); \ + } while (ret_ == -1 && errno == EINTR && try_cnt++ < 100); \ + ret_; \ + }) + +#ifndef sighandler_t +typedef void (*sighandler_t)(int sig); +#endif + +const double MILE_TO_KM = 1.609344; +const double KM_TO_MILE = 1. / MILE_TO_KM; +const double MS_TO_KPH = 3.6; +const double MS_TO_MPH = MS_TO_KPH * KM_TO_MILE; +const double METER_TO_MILE = KM_TO_MILE / 1000.0; +const double METER_TO_FOOT = 3.28084; +const double METER_TO_KM = 1. / 1000.0; + +#define ALIGNED_SIZE(x, align) (((x) + (align)-1) & ~((align)-1)) + +namespace util { + +void set_thread_name(const char* name); +int set_realtime_priority(int level); +int set_core_affinity(std::vector cores); +int set_file_descriptor_limit(uint64_t limit); + +// ***** math helpers ***** + +// map x from [a1, a2] to [b1, b2] +template +T map_val(T x, T a1, T a2, T b1, T b2) { + x = std::clamp(x, a1, a2); + T ra = a2 - a1; + T rb = b2 - b1; + return (x - a1) * rb / ra + b1; +} + +// ***** string helpers ***** + +template +std::string string_format(const std::string& format, Args... args) { + size_t size = snprintf(nullptr, 0, format.c_str(), args...) + 1; + std::unique_ptr buf(new char[size]); + snprintf(buf.get(), size, format.c_str(), args...); + return std::string(buf.get(), buf.get() + size - 1); +} + +std::string getenv(const char* key, std::string default_val = ""); +int getenv(const char* key, int default_val); +float getenv(const char* key, float default_val); + +std::string hexdump(const uint8_t* in, const size_t size); +bool starts_with(const std::string &s1, const std::string &s2); +bool ends_with(const std::string &s, const std::string &suffix); +std::string strip(const std::string &str); + +// ***** random helpers ***** +int random_int(int min, int max); +std::string random_string(std::string::size_type length); + +// **** file helpers ***** +std::string read_file(const std::string& fn); +std::map read_files_in_dir(const std::string& path); +int write_file(const char* path, const void* data, size_t size, int flags = O_WRONLY, mode_t mode = 0664); + +FILE* safe_fopen(const char* filename, const char* mode); +size_t safe_fwrite(const void * ptr, size_t size, size_t count, FILE * stream); +int safe_fflush(FILE *stream); +int safe_ioctl(int fd, unsigned long request, void *argp, const char* exception_msg = nullptr); + +std::string readlink(const std::string& path); +bool file_exists(const std::string& fn); +bool create_directories(const std::string &dir, mode_t mode); + +std::string check_output(const std::string& command); + +inline void check_system(const std::string& cmd) { + int ret = std::system(cmd.c_str()); + if (ret != 0) { + fprintf(stderr, "system command failed (%d): %s\n", ret, cmd.c_str()); + } +} + +bool system_time_valid(); + +inline void sleep_for(const int milliseconds) { + if (milliseconds > 0) { + std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds)); + } +} + +} // namespace util + +class ExitHandler { +public: + ExitHandler() { + std::signal(SIGINT, (sighandler_t)set_do_exit); + std::signal(SIGTERM, (sighandler_t)set_do_exit); + +#ifndef __APPLE__ + std::signal(SIGPWR, (sighandler_t)set_do_exit); +#endif + } + inline static std::atomic power_failure = false; + inline static std::atomic signal = 0; + inline operator bool() { return do_exit; } + inline ExitHandler& operator=(bool v) { + signal = 0; + do_exit = v; + return *this; + } +private: + static void set_do_exit(int sig) { +#ifndef __APPLE__ + power_failure = (sig == SIGPWR); +#endif + signal = sig; + do_exit = true; + } + inline static std::atomic do_exit = false; +}; + +struct unique_fd { + unique_fd(int fd = -1) : fd_(fd) {} + unique_fd& operator=(unique_fd&& uf) { + fd_ = uf.fd_; + uf.fd_ = -1; + return *this; + } + ~unique_fd() { + if (fd_ != -1) close(fd_); + } + operator int() const { return fd_; } + int fd_; +}; + +class FirstOrderFilter { +public: + FirstOrderFilter(float x0, float ts, float dt, bool initialized = true) { + k_ = (dt / ts) / (1.0 + dt / ts); + x_ = x0; + initialized_ = initialized; + } + inline float update(float x) { + if (initialized_) { + x_ = (1. - k_) * x_ + k_ * x; + } else { + initialized_ = true; + x_ = x; + } + return x_; + } + inline void reset(float x) { x_ = x; } + inline float x(){ return x_; } + +private: + float x_, k_; + bool initialized_; +}; + +template +void update_max_atomic(std::atomic& max, T const& value) { + T prev = max; + while (prev < value && !max.compare_exchange_weak(prev, value)) {} +} + +typedef struct Rect { + int x; + int y; + int w; + int h; +} Rect; diff --git a/openpilot/common/utils.py b/openpilot/common/utils.py new file mode 100644 index 0000000000..22d024fca7 --- /dev/null +++ b/openpilot/common/utils.py @@ -0,0 +1,272 @@ +import io +import os +import tempfile +import contextlib +import subprocess +import time +import functools +from subprocess import Popen, PIPE, TimeoutExpired +import zstandard as zstd + +LOG_COMPRESSION_LEVEL = 10 # little benefit up to level 15. level ~17 is a small step change + +class Timer: + """Simple lap timer for profiling sequential operations.""" + + def __init__(self): + self._start = self._lap = time.monotonic() + self._sections = {} + + def lap(self, name): + now = time.monotonic() + self._sections[name] = now - self._lap + self._lap = now + + @property + def total(self): + return time.monotonic() - self._start + + def fmt(self, duration): + parts = ", ".join(f"{k}={v:.2f}s" + (f" ({duration/v:.0f}x)" if k == 'render' and v > 0 else "") for k, v in self._sections.items()) + total = self.total + realtime = f"{duration/total:.1f}x realtime" if total > 0 else "N/A" + return f"{duration}s in {total:.1f}s ({realtime}) | {parts}" + +def sudo_write(val: str, path: str) -> None: + try: + with open(path, 'w') as f: + f.write(str(val)) + except PermissionError: + subprocess.run(f"sudo chmod a+w {path}", shell=True) + try: + with open(path, 'w') as f: + f.write(str(val)) + except PermissionError: + # fallback for debugfs files + subprocess.run(f"sudo su -c 'echo {val} > {path}'", shell=True) + + +def sudo_read(path: str) -> str: + try: + return subprocess.check_output(["sudo", "cat", "--", path], encoding='utf8').strip() + except Exception: + return "" + + +class MovingAverage: + def __init__(self, window_size: int): + self.window_size: int = window_size + self.buffer: list[float] = [0.0] * window_size + self.index: int = 0 + self.count: int = 0 + self.sum: float = 0.0 + + def add_value(self, new_value: float): + # Update the sum: subtract the value being replaced and add the new value + self.sum -= self.buffer[self.index] + self.buffer[self.index] = new_value + self.sum += new_value + + # Update the index in a circular manner + self.index = (self.index + 1) % self.window_size + + # Track the number of added values (for partial windows) + self.count = min(self.count + 1, self.window_size) + + def get_average(self) -> float: + if self.count == 0: + return float('nan') + return self.sum / self.count + + +class CallbackReader: + """Wraps a file, but overrides the read method to also + call a callback function with the number of bytes read so far.""" + + def __init__(self, f, callback, *args): + self.f = f + self.callback = callback + self.cb_args = args + self.total_read = 0 + + def __getattr__(self, attr): + return getattr(self.f, attr) + + def read(self, *args, **kwargs): + chunk = self.f.read(*args, **kwargs) + self.total_read += len(chunk) + self.callback(*self.cb_args, self.total_read) + return chunk + + +@contextlib.contextmanager +def atomic_write(path: str, mode: str = 'w', buffering: int = -1, encoding: str | None = None, newline: str | None = None, + overwrite: bool = False): + """Write to a file atomically using a temporary file in the same directory as the destination file.""" + dir_name = os.path.dirname(path) + + if not overwrite and os.path.exists(path): + raise FileExistsError(f"File '{path}' already exists. To overwrite it, set 'overwrite' to True.") + + with tempfile.NamedTemporaryFile(mode=mode, buffering=buffering, encoding=encoding, newline=newline, dir=dir_name, delete=False) as tmp_file: + yield tmp_file + tmp_file_name = tmp_file.name + os.replace(tmp_file_name, path) + + +def get_upload_stream(filepath: str, should_compress: bool) -> tuple[io.BufferedIOBase, int]: + if not should_compress: + file_size = os.path.getsize(filepath) + file_stream = open(filepath, "rb") + return file_stream, file_size + + # Compress the file on the fly + compressed_stream = io.BytesIO() + compressor = zstd.ZstdCompressor(level=LOG_COMPRESSION_LEVEL) + + with open(filepath, "rb") as f: + compressor.copy_stream(f, compressed_stream) + compressed_size = compressed_stream.tell() + compressed_stream.seek(0) + return compressed_stream, compressed_size + + +# remove all keys that end in DEPRECATED, plus any "deprecated" group +def strip_deprecated_keys(d): + for k in list(d.keys()): + if isinstance(k, str): + if k.endswith('DEPRECATED') or k == 'deprecated': + d.pop(k) + elif isinstance(d[k], dict): + strip_deprecated_keys(d[k]) + return d + + +def run_cmd(cmd: list[str], cwd=None, env=None) -> str: + return subprocess.check_output(cmd, encoding='utf8', cwd=cwd, env=env).strip() + + +def run_cmd_default(cmd: list[str], default: str = "", cwd=None, env=None) -> str: + try: + return run_cmd(cmd, cwd=cwd, env=env) + except subprocess.CalledProcessError: + return default + + +@contextlib.contextmanager +def managed_proc(cmd: list[str], env: dict[str, str]): + proc = Popen(cmd, env=env, stdout=PIPE, stderr=PIPE) + try: + yield proc + finally: + if proc.poll() is None: + proc.terminate() + try: + proc.wait(timeout=5) + except TimeoutExpired: + proc.kill() + + +def tabulate(tabular_data, headers=(), tablefmt="simple", floatfmt="g", stralign="left", numalign=None): + rows = [list(row) for row in tabular_data] + + def fmt(val): + if isinstance(val, str): + return val + if isinstance(val, (bool, int)): + return str(val) + try: + return format(val, floatfmt) + except (TypeError, ValueError): + return str(val) + + formatted = [[fmt(c) for c in row] for row in rows] + hdrs = [str(h) for h in headers] if headers else None + + ncols = max((len(r) for r in formatted), default=0) + if hdrs: + ncols = max(ncols, len(hdrs)) + if ncols == 0: + return "" + + for r in formatted: + r.extend([""] * (ncols - len(r))) + if hdrs: + hdrs.extend([""] * (ncols - len(hdrs))) + + widths = [0] * ncols + if hdrs: + for i in range(ncols): + widths[i] = len(hdrs[i]) + for row in formatted: + for i in range(ncols): + widths[i] = max(widths[i], max(len(ln) for ln in row[i].split('\n'))) + + def _align(s, w): + if stralign == "center": + return s.center(w) + return s.ljust(w) + + if tablefmt == "html": + parts = [""] + if hdrs: + parts.append("") + parts.append("" + "".join(f"" for h in hdrs) + "") + parts.append("") + parts.append("") + for row in formatted: + parts.append("" + "".join(f"" for c in row) + "") + parts.append("") + parts.append("
{h}
{c}
") + return "\n".join(parts) + + if tablefmt == "simple_grid": + def _sep(left, mid, right): + return left + mid.join("\u2500" * (w + 2) for w in widths) + right + + top, mid_sep, bot = _sep("\u250c", "\u252c", "\u2510"), _sep("\u251c", "\u253c", "\u2524"), _sep("\u2514", "\u2534", "\u2518") + + def _fmt_row(cells): + split = [c.split('\n') for c in cells] + nlines = max(len(s) for s in split) + for s in split: + s.extend([""] * (nlines - len(s))) + return ["\u2502" + "\u2502".join(f" {_align(split[i][li], widths[i])} " for i in range(ncols)) + "\u2502" for li in range(nlines)] + + lines = [top] + if hdrs: + lines.extend(_fmt_row(hdrs)) + lines.append(mid_sep) + for ri, row in enumerate(formatted): + lines.extend(_fmt_row(row)) + lines.append(mid_sep if ri < len(formatted) - 1 else bot) + return "\n".join(lines) + + # simple + gap = " " + lines = [] + if hdrs: + lines.append(gap.join(h.ljust(w) for h, w in zip(hdrs, widths, strict=True))) + lines.append(gap.join("-" * w for w in widths)) + for row in formatted: + lines.append(gap.join(_align(row[i], widths[i]) for i in range(ncols))) + return "\n".join(lines) + + +def retry(attempts=3, delay=1.0, ignore_failure=False): + def decorator(func): + @functools.wraps(func) + def wrapper(*args, **kwargs): + for _ in range(attempts): + try: + return func(*args, **kwargs) + except Exception: + print(f"{func.__name__} failed, trying again") + time.sleep(delay) + + if ignore_failure: + print(f"{func.__name__} failed after retry") + else: + raise Exception(f"{func.__name__} failed after retry") + return wrapper + return decorator diff --git a/openpilot/common/version.h b/openpilot/common/version.h new file mode 100644 index 0000000000..5a09588e22 --- /dev/null +++ b/openpilot/common/version.h @@ -0,0 +1 @@ +#define COMMA_VERSION "0.11.2" diff --git a/openpilot/common/version.py b/openpilot/common/version.py new file mode 100755 index 0000000000..77ee79d5ef --- /dev/null +++ b/openpilot/common/version.py @@ -0,0 +1,216 @@ +#!/usr/bin/env python3 +from dataclasses import dataclass +from functools import cache +import json +import os +import pathlib +import subprocess + +from openpilot.common.basedir import BASEDIR +from openpilot.common.swaglog import cloudlog +from openpilot.common.git import get_commit, get_origin, get_branch, get_short_branch, get_commit_date + +RELEASE_SP_BRANCHES = ['release-c3', 'release', 'release-tizi', 'release-tici', 'release-tizi-staging', 'release-tici-staging'] +TESTED_SP_BRANCHES = ['staging-c3', 'staging-c3-new', 'staging'] +MASTER_SP_BRANCHES = ['master'] +RELEASE_BRANCHES = ['release-tizi-staging', 'release-mici-staging', 'release-tizi', 'release-mici', 'nightly'] +TESTED_BRANCHES = RELEASE_BRANCHES + ['devel-staging', 'nightly-dev'] + RELEASE_SP_BRANCHES + TESTED_SP_BRANCHES + +SP_BRANCH_MIGRATIONS = { + ("tici", "staging-c3-new"): "staging-tici", + ("tici", "dev-c3-new"): "staging-tici", + ("tici", "master"): "master-tici", + ("tici", "master-dev-c3-new"): "master-tici", + ("tizi", "staging-c3-new"): "staging", + ("tizi", "dev-c3-new"): "dev", + ("tizi", "master-dev-c3-new"): "master-dev", + ("tizi", "release3"): "release-tizi", + ("tizi", "release3-staging"): "release-tizi-staging", + ("mici", "release3"): "release-mici", + ("mici", "release3-staging"): "release-mici-staging", + ("tici", "hkg-angle-steering-2025"): "hkg-angle-steering-2025-tici", + ("tici", "hkg-angle-steering-2025-prebuilt"): "hkg-angle-steering-2025-tici-prebuilt" +} + +BUILD_METADATA_FILENAME = "build.json" + +training_version: str = "0.2.0" +terms_version: str = "2" +terms_version_sp: str = "1.0" +sunnylink_consent_version: str = "1.0" +sunnylink_consent_declined: str = "-1" + + +def get_version(path: str = BASEDIR) -> str: + with open(os.path.join(path, "openpilot", "sunnypilot", "common", "version.h")) as _versionf: + version = _versionf.read().split('"')[1] + return version + + +def get_release_notes(path: str = BASEDIR) -> str: + with open(os.path.join(path, "CHANGELOG.md")) as f: + return f.read().split('\n\n', 1)[0] + + +@cache +def is_prebuilt(path: str = BASEDIR) -> bool: + return os.path.exists(os.path.join(path, 'prebuilt')) + + +@cache +def is_dirty(cwd: str = BASEDIR) -> bool: + if not get_origin() or not get_short_branch(): + return True + + dirty = False + try: + # Actually check dirty files + if not is_prebuilt(cwd): + # This is needed otherwise touched files might show up as modified + try: + subprocess.check_call(["git", "update-index", "--refresh"], cwd=cwd) + except subprocess.CalledProcessError: + pass + + branch = get_branch() + if not branch: + return True + dirty = (subprocess.call(["git", "diff-index", "--quiet", branch, "--"], cwd=cwd)) != 0 + except subprocess.CalledProcessError: + cloudlog.exception("git subprocess failed while checking dirty") + dirty = True + + return dirty + + +@dataclass +class OpenpilotMetadata: + version: str + release_notes: str + git_commit: str + git_origin: str + git_commit_date: str + build_style: str + is_dirty: bool # whether there are local changes + + @property + def short_version(self) -> str: + return self.version.split('-')[0] + + @property + def comma_remote(self) -> bool: + # note to fork maintainers, this is used for release metrics. please do not + # touch this to get rid of the orange startup alert. there's better ways to do that + return self.git_normalized_origin == "github.com/commaai/openpilot" + + @property + def sunnypilot_remote(self) -> bool: + return self.git_normalized_origin in ("github.com/sunnypilot/sunnypilot", + "github.com/sunnypilot/openpilot", + "github.com/sunnyhaibin/sunnypilot", + "github.com/sunnyhaibin/openpilot") + + @property + def git_normalized_origin(self) -> str: + return self.git_origin \ + .replace("git@", "", 1) \ + .replace(".git", "", 1) \ + .replace("https://", "", 1) \ + .replace(":", "/", 1) + + +@dataclass +class BuildMetadata: + channel: str + openpilot: OpenpilotMetadata + + @property + def tested_channel(self) -> bool: + return self.channel in TESTED_BRANCHES + + @property + def release_channel(self) -> bool: + return self.channel in RELEASE_BRANCHES + + @property + def release_sp_channel(self) -> bool: + return self.channel in RELEASE_SP_BRANCHES + + @property + def canonical(self) -> str: + return f"{self.openpilot.version}-{self.openpilot.git_commit}-{self.openpilot.build_style}" + + @property + def ui_description(self) -> str: + return f"{self.openpilot.version} / {self.openpilot.git_commit[:6]} / {self.channel}" + + @property + def master_channel(self) -> bool: + return self.channel in MASTER_SP_BRANCHES + + @property + def development_channel(self) -> bool: + return self.channel == "dev" or self.channel.startswith("dev-") or self.channel.endswith("-prebuilt") + + @property + def channel_type(self) -> str: + if self.channel.endswith("-tici"): + return "tici" + elif self.development_channel: + return "development" + elif self.tested_channel: + return "staging" + elif self.master_channel: + return "master" + elif self.release_channel or self.release_sp_channel: + return "release" + else: + return "feature" + + +def build_metadata_from_dict(build_metadata: dict) -> BuildMetadata: + channel = build_metadata.get("channel", "unknown") + openpilot_metadata = build_metadata.get("openpilot", {}) + version = openpilot_metadata.get("version", "unknown") + release_notes = openpilot_metadata.get("release_notes", "unknown") + git_commit = openpilot_metadata.get("git_commit", "unknown") + git_origin = openpilot_metadata.get("git_origin", "unknown") + git_commit_date = openpilot_metadata.get("git_commit_date", "unknown") + build_style = openpilot_metadata.get("build_style", "unknown") + return BuildMetadata(channel, + OpenpilotMetadata( + version=version, + release_notes=release_notes, + git_commit=git_commit, + git_origin=git_origin, + git_commit_date=git_commit_date, + build_style=build_style, + is_dirty=False)) + + +def get_build_metadata(path: str = BASEDIR) -> BuildMetadata: + build_metadata_path = pathlib.Path(path) / BUILD_METADATA_FILENAME + + if build_metadata_path.exists(): + build_metadata = json.loads(build_metadata_path.read_text()) + return build_metadata_from_dict(build_metadata) + + git_folder = pathlib.Path(path) / ".git" + + if git_folder.exists(): + return BuildMetadata(get_short_branch(path), + OpenpilotMetadata( + version=get_version(path), + release_notes=get_release_notes(path), + git_commit=get_commit(path), + git_origin=get_origin(path), + git_commit_date=get_commit_date(path), + build_style="unknown", + is_dirty=is_dirty(path))) + + cloudlog.exception("unable to get build metadata") + raise Exception("invalid build metadata") + + +if __name__ == "__main__": + print(get_build_metadata()) diff --git a/openpilot/common/yuv.cc b/openpilot/common/yuv.cc new file mode 100644 index 0000000000..a7a64fb594 --- /dev/null +++ b/openpilot/common/yuv.cc @@ -0,0 +1,132 @@ +#include "common/yuv.h" + +#include +#include + +namespace yuv { + +namespace { + +inline uint8_t clamp_u8(int v) { + return static_cast(std::clamp(v, 0, 255)); +} + +void copy_plane(const uint8_t *src, int src_stride, + uint8_t *dst, int dst_stride, + int width, int height) { + if (src_stride == width && dst_stride == width) { + std::memcpy(dst, src, static_cast(width) * height); + return; + } + for (int y = 0; y < height; ++y) { + std::memcpy(dst + y * dst_stride, src + y * src_stride, width); + } +} + +void scale_plane_point(const uint8_t *src, int src_stride, int src_width, int src_height, + uint8_t *dst, int dst_stride, int dst_width, int dst_height) { + if (src_width == dst_width && src_height == dst_height) { + copy_plane(src, src_stride, dst, dst_stride, dst_width, dst_height); + return; + } + for (int y = 0; y < dst_height; ++y) { + const int sy = y * src_height / dst_height; + const uint8_t *src_row = src + sy * src_stride; + uint8_t *dst_row = dst + y * dst_stride; + for (int x = 0; x < dst_width; ++x) { + dst_row[x] = src_row[x * src_width / dst_width]; + } + } +} + +// BT.601 limited range → RGB (integer form used widely, incl. similar to libyuv). +inline void yuv_to_rgb(int y, int u, int v, uint8_t *r, uint8_t *g, uint8_t *b) { + const int c = (y - 16) * 298; + const int d = u - 128; + const int e = v - 128; + *r = clamp_u8((c + 409 * e + 128) >> 8); + *g = clamp_u8((c - 100 * d - 208 * e + 128) >> 8); + *b = clamp_u8((c + 516 * d + 128) >> 8); +} + +} // namespace + +void nv12_to_i420(const uint8_t *src_y, int src_stride_y, + const uint8_t *src_uv, int src_stride_uv, + uint8_t *dst_y, int dst_stride_y, + uint8_t *dst_u, int dst_stride_u, + uint8_t *dst_v, int dst_stride_v, + int width, int height) { + copy_plane(src_y, src_stride_y, dst_y, dst_stride_y, width, height); + + const int uv_width = width / 2; + const int uv_height = height / 2; + for (int y = 0; y < uv_height; ++y) { + const uint8_t *uv = src_uv + y * src_stride_uv; + uint8_t *u = dst_u + y * dst_stride_u; + uint8_t *v = dst_v + y * dst_stride_v; + for (int x = 0; x < uv_width; ++x) { + u[x] = uv[2 * x]; + v[x] = uv[2 * x + 1]; + } + } +} + +void i420_to_nv12(const uint8_t *src_y, int src_stride_y, + const uint8_t *src_u, int src_stride_u, + const uint8_t *src_v, int src_stride_v, + uint8_t *dst_y, int dst_stride_y, + uint8_t *dst_uv, int dst_stride_uv, + int width, int height) { + copy_plane(src_y, src_stride_y, dst_y, dst_stride_y, width, height); + + const int uv_width = width / 2; + const int uv_height = height / 2; + for (int y = 0; y < uv_height; ++y) { + const uint8_t *u = src_u + y * src_stride_u; + const uint8_t *v = src_v + y * src_stride_v; + uint8_t *uv = dst_uv + y * dst_stride_uv; + for (int x = 0; x < uv_width; ++x) { + uv[2 * x] = u[x]; + uv[2 * x + 1] = v[x]; + } + } +} + +void i420_scale(const uint8_t *src_y, int src_stride_y, + const uint8_t *src_u, int src_stride_u, + const uint8_t *src_v, int src_stride_v, + int src_width, int src_height, + uint8_t *dst_y, int dst_stride_y, + uint8_t *dst_u, int dst_stride_u, + uint8_t *dst_v, int dst_stride_v, + int dst_width, int dst_height) { + scale_plane_point(src_y, src_stride_y, src_width, src_height, + dst_y, dst_stride_y, dst_width, dst_height); + scale_plane_point(src_u, src_stride_u, src_width / 2, src_height / 2, + dst_u, dst_stride_u, dst_width / 2, dst_height / 2); + scale_plane_point(src_v, src_stride_v, src_width / 2, src_height / 2, + dst_v, dst_stride_v, dst_width / 2, dst_height / 2); +} + +void nv12_to_rgba(const uint8_t *src_y, int src_stride_y, + const uint8_t *src_uv, int src_stride_uv, + uint8_t *dst_rgba, int dst_stride_rgba, + int width, int height) { + for (int y = 0; y < height; ++y) { + const uint8_t *y_row = src_y + y * src_stride_y; + const uint8_t *uv_row = src_uv + (y / 2) * src_stride_uv; + uint8_t *dst = dst_rgba + y * dst_stride_rgba; + for (int x = 0; x < width; ++x) { + const int uv_x = (x & ~1); + uint8_t r, g, b; + yuv_to_rgb(y_row[x], uv_row[uv_x], uv_row[uv_x + 1], &r, &g, &b); + dst[4 * x + 0] = r; + dst[4 * x + 1] = g; + dst[4 * x + 2] = b; + dst[4 * x + 3] = 255; + } + } +} + +} // namespace yuv diff --git a/openpilot/common/yuv.h b/openpilot/common/yuv.h new file mode 100644 index 0000000000..7ab096f764 --- /dev/null +++ b/openpilot/common/yuv.h @@ -0,0 +1,42 @@ +#pragma once + +#include + +// NV12: Y plane + interleaved UV. I420: planar Y, U, V. + +namespace yuv { + +// Deinterleave NV12 UV into planar I420. +void nv12_to_i420(const uint8_t *src_y, int src_stride_y, + const uint8_t *src_uv, int src_stride_uv, + uint8_t *dst_y, int dst_stride_y, + uint8_t *dst_u, int dst_stride_u, + uint8_t *dst_v, int dst_stride_v, + int width, int height); + +// Interleave planar I420 UV into NV12. +void i420_to_nv12(const uint8_t *src_y, int src_stride_y, + const uint8_t *src_u, int src_stride_u, + const uint8_t *src_v, int src_stride_v, + uint8_t *dst_y, int dst_stride_y, + uint8_t *dst_uv, int dst_stride_uv, + int width, int height); + +// Point-sample scale I420 (equivalent to libyuv::I420Scale + kFilterNone). +void i420_scale(const uint8_t *src_y, int src_stride_y, + const uint8_t *src_u, int src_stride_u, + const uint8_t *src_v, int src_stride_v, + int src_width, int src_height, + uint8_t *dst_y, int dst_stride_y, + uint8_t *dst_u, int dst_stride_u, + uint8_t *dst_v, int dst_stride_v, + int dst_width, int dst_height); + +// Convert NV12 to packed RGBA (R,G,B,A bytes — suitable for GL_RGBA). +// BT.601 limited-range, matching common libyuv defaults. +void nv12_to_rgba(const uint8_t *src_y, int src_stride_y, + const uint8_t *src_uv, int src_stride_uv, + uint8_t *dst_rgba, int dst_stride_rgba, + int width, int height); + +} diff --git a/openpilot/selfdrive b/openpilot/selfdrive deleted file mode 120000 index e005fd0d04..0000000000 --- a/openpilot/selfdrive +++ /dev/null @@ -1 +0,0 @@ -../selfdrive/ \ No newline at end of file diff --git a/selfdrive/car/__init__.py b/openpilot/selfdrive/__init__.py similarity index 100% rename from selfdrive/car/__init__.py rename to openpilot/selfdrive/__init__.py diff --git a/openpilot/selfdrive/assets/.gitignore b/openpilot/selfdrive/assets/.gitignore new file mode 100644 index 0000000000..2d97f8b111 --- /dev/null +++ b/openpilot/selfdrive/assets/.gitignore @@ -0,0 +1,2 @@ +fonts/*.fnt +fonts/*.png diff --git a/openpilot/selfdrive/assets/assets.qrc b/openpilot/selfdrive/assets/assets.qrc new file mode 100644 index 0000000000..72e2f7f3c0 --- /dev/null +++ b/openpilot/selfdrive/assets/assets.qrc @@ -0,0 +1,20 @@ + + + @BOOTSTRAP_ICONS_SVG@ + images/button_continue_triangle.svg + icons/circled_check.svg + icons/circled_slash.svg + icons/eye_open.svg + icons/eye_closed.svg + icons/close.svg + icons/lock_closed.svg + icons/checkmark.svg + icons/warning.png + icons/wifi_strength_low.svg + icons/wifi_strength_medium.svg + icons/wifi_strength_high.svg + icons/wifi_strength_full.svg + + ../ui/translations/languages.json + + diff --git a/selfdrive/assets/body/awake.gif b/openpilot/selfdrive/assets/body/awake.gif similarity index 100% rename from selfdrive/assets/body/awake.gif rename to openpilot/selfdrive/assets/body/awake.gif diff --git a/selfdrive/assets/body/sleep.gif b/openpilot/selfdrive/assets/body/sleep.gif similarity index 100% rename from selfdrive/assets/body/sleep.gif rename to openpilot/selfdrive/assets/body/sleep.gif diff --git a/selfdrive/assets/compress-images.sh b/openpilot/selfdrive/assets/compress-images.sh similarity index 100% rename from selfdrive/assets/compress-images.sh rename to openpilot/selfdrive/assets/compress-images.sh diff --git a/openpilot/selfdrive/assets/fonts/Audiowide-Regular.ttf b/openpilot/selfdrive/assets/fonts/Audiowide-Regular.ttf new file mode 100644 index 0000000000..1b6913947b --- /dev/null +++ b/openpilot/selfdrive/assets/fonts/Audiowide-Regular.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:434a720871336d359378beff5ebff3f9fd654d958693d272c7c6f2e271c7e41c +size 47676 diff --git a/selfdrive/assets/fonts/Inter-Black.ttf b/openpilot/selfdrive/assets/fonts/Inter-Black.ttf similarity index 100% rename from selfdrive/assets/fonts/Inter-Black.ttf rename to openpilot/selfdrive/assets/fonts/Inter-Black.ttf diff --git a/selfdrive/assets/fonts/Inter-Bold.ttf b/openpilot/selfdrive/assets/fonts/Inter-Bold.ttf similarity index 100% rename from selfdrive/assets/fonts/Inter-Bold.ttf rename to openpilot/selfdrive/assets/fonts/Inter-Bold.ttf diff --git a/selfdrive/assets/fonts/Inter-ExtraBold.ttf b/openpilot/selfdrive/assets/fonts/Inter-ExtraBold.ttf similarity index 100% rename from selfdrive/assets/fonts/Inter-ExtraBold.ttf rename to openpilot/selfdrive/assets/fonts/Inter-ExtraBold.ttf diff --git a/selfdrive/assets/fonts/Inter-ExtraLight.ttf b/openpilot/selfdrive/assets/fonts/Inter-ExtraLight.ttf similarity index 100% rename from selfdrive/assets/fonts/Inter-ExtraLight.ttf rename to openpilot/selfdrive/assets/fonts/Inter-ExtraLight.ttf diff --git a/selfdrive/assets/fonts/Inter-Light.ttf b/openpilot/selfdrive/assets/fonts/Inter-Light.ttf similarity index 100% rename from selfdrive/assets/fonts/Inter-Light.ttf rename to openpilot/selfdrive/assets/fonts/Inter-Light.ttf diff --git a/selfdrive/assets/fonts/Inter-Medium.ttf b/openpilot/selfdrive/assets/fonts/Inter-Medium.ttf similarity index 100% rename from selfdrive/assets/fonts/Inter-Medium.ttf rename to openpilot/selfdrive/assets/fonts/Inter-Medium.ttf diff --git a/selfdrive/assets/fonts/Inter-Regular.ttf b/openpilot/selfdrive/assets/fonts/Inter-Regular.ttf similarity index 100% rename from selfdrive/assets/fonts/Inter-Regular.ttf rename to openpilot/selfdrive/assets/fonts/Inter-Regular.ttf diff --git a/selfdrive/assets/fonts/Inter-SemiBold.ttf b/openpilot/selfdrive/assets/fonts/Inter-SemiBold.ttf similarity index 100% rename from selfdrive/assets/fonts/Inter-SemiBold.ttf rename to openpilot/selfdrive/assets/fonts/Inter-SemiBold.ttf diff --git a/selfdrive/assets/fonts/Inter-Thin.ttf b/openpilot/selfdrive/assets/fonts/Inter-Thin.ttf similarity index 100% rename from selfdrive/assets/fonts/Inter-Thin.ttf rename to openpilot/selfdrive/assets/fonts/Inter-Thin.ttf diff --git a/selfdrive/assets/fonts/JetBrainsMono-Medium.ttf b/openpilot/selfdrive/assets/fonts/JetBrainsMono-Medium.ttf similarity index 100% rename from selfdrive/assets/fonts/JetBrainsMono-Medium.ttf rename to openpilot/selfdrive/assets/fonts/JetBrainsMono-Medium.ttf diff --git a/openpilot/selfdrive/assets/fonts/NotoColorEmoji.ttf b/openpilot/selfdrive/assets/fonts/NotoColorEmoji.ttf new file mode 100644 index 0000000000..778e821ce3 --- /dev/null +++ b/openpilot/selfdrive/assets/fonts/NotoColorEmoji.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:93cdc4ee9aa40e2afceecc63da0ca05ec7aab4bec991ece51a6b52389f48a477 +size 10788068 diff --git a/openpilot/selfdrive/assets/fonts/process.py b/openpilot/selfdrive/assets/fonts/process.py new file mode 100755 index 0000000000..62ae6ec684 --- /dev/null +++ b/openpilot/selfdrive/assets/fonts/process.py @@ -0,0 +1,136 @@ +#!/usr/bin/env python3 +from pathlib import Path +import json + +import pyray as rl + +FONT_DIR = Path(__file__).resolve().parent +SELFDRIVE_DIR = FONT_DIR.parents[1] +TRANSLATIONS_DIR = SELFDRIVE_DIR / "ui" / "translations" +LANGUAGES_FILE = TRANSLATIONS_DIR / "languages.json" + +GLYPH_PADDING = 6 +EXTRA_CHARS = "–‑✓×°§•X⚙✕◀▶✔⌫⇧␣○●↳çêüñ–‑✓×°§•€£¥" +UNIFONT_LANGUAGES = {"th", "zh-CHT", "zh-CHS", "ko", "ja"} + + +def _languages(): + if not LANGUAGES_FILE.exists(): + return {} + with LANGUAGES_FILE.open(encoding="utf-8") as f: + return json.load(f) + + +def _char_sets(): + base = set(map(chr, range(32, 127))) | set(EXTRA_CHARS) + unifont = set(base) + + for language, code in _languages().items(): + unifont.update(language) + po_path = TRANSLATIONS_DIR / f"app_{code}.po" + try: + chars = set(po_path.read_text(encoding="utf-8")) + except FileNotFoundError: + continue + (unifont if code in UNIFONT_LANGUAGES else base).update(chars) + + return tuple(sorted(ord(c) for c in base)), tuple(sorted(ord(c) for c in unifont)) + + +def _glyph_metrics(glyphs, rects, glyph_count: int): + entries = [] + min_offset_y, max_extent = None, 0 + for idx in range(glyph_count): + glyph = glyphs[idx] + rect = rects[idx] + width = int(round(rect.width)) + height = int(round(rect.height)) + offset_y = int(round(glyph.offsetY)) + min_offset_y = offset_y if min_offset_y is None else min(min_offset_y, offset_y) + max_extent = max(max_extent, offset_y + height) + entries.append({ + "id": glyph.value, + "x": int(round(rect.x)), + "y": int(round(rect.y)), + "width": width, + "height": height, + "xoffset": int(round(glyph.offsetX)), + "yoffset": offset_y, + "xadvance": int(round(glyph.advanceX)), + }) + + if min_offset_y is None: + raise RuntimeError("No glyphs were generated") + + line_height = int(round(max_extent - min_offset_y)) + base = int(round(max_extent)) + return entries, line_height, base + + +def _write_bmfont(path: Path, font_size: int, face: str, atlas_name: str, line_height: int, base: int, atlas_size, entries): + # TODO: why doesn't raylib calculate these metrics correctly? + if line_height != font_size: + print("using font size for line height", atlas_name) + line_height = font_size + lines = [ + f"info face=\"{face}\" size=-{font_size} bold=0 italic=0 charset=\"\" unicode=1 stretchH=100 smooth=0 aa=1 padding=0,0,0,0 spacing=0,0 outline=0", + f"common lineHeight={line_height} base={base} scaleW={atlas_size[0]} scaleH={atlas_size[1]} pages=1 packed=0 alphaChnl=0 redChnl=4 greenChnl=4 blueChnl=4", + f"page id=0 file=\"{atlas_name}\"", + f"chars count={len(entries)}", + ] + for entry in entries: + lines.append( + ("char id={id:<4} x={x:<5} y={y:<5} width={width:<5} height={height:<5} " + + "xoffset={xoffset:<5} yoffset={yoffset:<5} xadvance={xadvance:<5} page=0 chnl=15").format(**entry) + ) + path.write_text("\n".join(lines) + "\n") + + +def _process_font(font_path: Path, codepoints: tuple[int, ...]): + print(f"Processing {font_path.name}...") + + font_size = { + "unifont.otf": 16, # unifont is only 16x8 or 16x16 pixels per glyph + }.get(font_path.name, 200) + + data = font_path.read_bytes() + file_buf = rl.ffi.new("unsigned char[]", data) + cp_buffer = rl.ffi.new("int[]", codepoints) + cp_ptr = rl.ffi.cast("int *", cp_buffer) + glyph_count = rl.ffi.new("int *", len(codepoints)) + glyphs = rl.load_font_data( + rl.ffi.cast("unsigned char *", file_buf), len(data), font_size, cp_ptr, len(codepoints), + rl.FontType.FONT_DEFAULT, glyph_count + ) + if glyphs == rl.ffi.NULL: + raise RuntimeError("raylib failed to load font data") + + rects_ptr = rl.ffi.new("Rectangle **") + image = rl.gen_image_font_atlas(glyphs, rects_ptr, glyph_count[0], font_size, GLYPH_PADDING, 0) + if image.width == 0 or image.height == 0: + raise RuntimeError("raylib returned an empty atlas") + + rects = rects_ptr[0] + atlas_name = f"{font_path.stem}.png" + atlas_path = FONT_DIR / atlas_name + entries, line_height, base = _glyph_metrics(glyphs, rects, glyph_count[0]) + + if not rl.export_image(image, atlas_path.as_posix()): + raise RuntimeError("Failed to export atlas image") + + _write_bmfont(FONT_DIR / f"{font_path.stem}.fnt", font_size, font_path.stem, atlas_name, line_height, base, (image.width, image.height), entries) + + +def main(): + base_cp, unifont_cp = _char_sets() + fonts = sorted(FONT_DIR.glob("*.ttf")) + sorted(FONT_DIR.glob("*.otf")) + for font in fonts: + if "emoji" in font.name.lower(): + continue + glyphs = unifont_cp if font.stem.lower().startswith("unifont") else base_cp + _process_font(font, glyphs) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/openpilot/selfdrive/assets/fonts/unifont.otf b/openpilot/selfdrive/assets/fonts/unifont.otf new file mode 100644 index 0000000000..b85597b1f4 --- /dev/null +++ b/openpilot/selfdrive/assets/fonts/unifont.otf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9712a9bc089af7ddc06e0826aa84f2ee23ed2f1a1dddaf2a89c2483e753a8475 +size 5321484 diff --git a/selfdrive/assets/icons/arrow-right.png b/openpilot/selfdrive/assets/icons/arrow-right.png similarity index 100% rename from selfdrive/assets/icons/arrow-right.png rename to openpilot/selfdrive/assets/icons/arrow-right.png diff --git a/selfdrive/assets/icons/backspace.png b/openpilot/selfdrive/assets/icons/backspace.png similarity index 100% rename from selfdrive/assets/icons/backspace.png rename to openpilot/selfdrive/assets/icons/backspace.png diff --git a/selfdrive/assets/icons/calibration.png b/openpilot/selfdrive/assets/icons/calibration.png similarity index 100% rename from selfdrive/assets/icons/calibration.png rename to openpilot/selfdrive/assets/icons/calibration.png diff --git a/selfdrive/assets/icons/capslock-fill.png b/openpilot/selfdrive/assets/icons/capslock-fill.png similarity index 100% rename from selfdrive/assets/icons/capslock-fill.png rename to openpilot/selfdrive/assets/icons/capslock-fill.png diff --git a/selfdrive/assets/icons/checkmark.png b/openpilot/selfdrive/assets/icons/checkmark.png similarity index 100% rename from selfdrive/assets/icons/checkmark.png rename to openpilot/selfdrive/assets/icons/checkmark.png diff --git a/selfdrive/assets/icons/checkmark.svg b/openpilot/selfdrive/assets/icons/checkmark.svg similarity index 100% rename from selfdrive/assets/icons/checkmark.svg rename to openpilot/selfdrive/assets/icons/checkmark.svg diff --git a/selfdrive/assets/icons/chevron_right.png b/openpilot/selfdrive/assets/icons/chevron_right.png similarity index 100% rename from selfdrive/assets/icons/chevron_right.png rename to openpilot/selfdrive/assets/icons/chevron_right.png diff --git a/selfdrive/assets/icons/chffr_wheel.png b/openpilot/selfdrive/assets/icons/chffr_wheel.png similarity index 100% rename from selfdrive/assets/icons/chffr_wheel.png rename to openpilot/selfdrive/assets/icons/chffr_wheel.png diff --git a/selfdrive/assets/icons/circled_check.png b/openpilot/selfdrive/assets/icons/circled_check.png similarity index 100% rename from selfdrive/assets/icons/circled_check.png rename to openpilot/selfdrive/assets/icons/circled_check.png diff --git a/selfdrive/assets/icons/circled_check.svg b/openpilot/selfdrive/assets/icons/circled_check.svg similarity index 100% rename from selfdrive/assets/icons/circled_check.svg rename to openpilot/selfdrive/assets/icons/circled_check.svg diff --git a/selfdrive/assets/icons/circled_slash.png b/openpilot/selfdrive/assets/icons/circled_slash.png similarity index 100% rename from selfdrive/assets/icons/circled_slash.png rename to openpilot/selfdrive/assets/icons/circled_slash.png diff --git a/selfdrive/assets/icons/circled_slash.svg b/openpilot/selfdrive/assets/icons/circled_slash.svg similarity index 100% rename from selfdrive/assets/icons/circled_slash.svg rename to openpilot/selfdrive/assets/icons/circled_slash.svg diff --git a/selfdrive/assets/icons/close.png b/openpilot/selfdrive/assets/icons/close.png similarity index 100% rename from selfdrive/assets/icons/close.png rename to openpilot/selfdrive/assets/icons/close.png diff --git a/selfdrive/assets/icons/close.svg b/openpilot/selfdrive/assets/icons/close.svg similarity index 100% rename from selfdrive/assets/icons/close.svg rename to openpilot/selfdrive/assets/icons/close.svg diff --git a/selfdrive/assets/icons/close2.png b/openpilot/selfdrive/assets/icons/close2.png similarity index 100% rename from selfdrive/assets/icons/close2.png rename to openpilot/selfdrive/assets/icons/close2.png diff --git a/selfdrive/assets/icons/close2.svg b/openpilot/selfdrive/assets/icons/close2.svg similarity index 100% rename from selfdrive/assets/icons/close2.svg rename to openpilot/selfdrive/assets/icons/close2.svg diff --git a/selfdrive/assets/icons/couch.png b/openpilot/selfdrive/assets/icons/couch.png similarity index 100% rename from selfdrive/assets/icons/couch.png rename to openpilot/selfdrive/assets/icons/couch.png diff --git a/selfdrive/assets/icons/couch.svg b/openpilot/selfdrive/assets/icons/couch.svg similarity index 100% rename from selfdrive/assets/icons/couch.svg rename to openpilot/selfdrive/assets/icons/couch.svg diff --git a/selfdrive/assets/icons/disengage_on_accelerator.png b/openpilot/selfdrive/assets/icons/disengage_on_accelerator.png similarity index 100% rename from selfdrive/assets/icons/disengage_on_accelerator.png rename to openpilot/selfdrive/assets/icons/disengage_on_accelerator.png diff --git a/selfdrive/assets/icons/disengage_on_accelerator.svg b/openpilot/selfdrive/assets/icons/disengage_on_accelerator.svg similarity index 100% rename from selfdrive/assets/icons/disengage_on_accelerator.svg rename to openpilot/selfdrive/assets/icons/disengage_on_accelerator.svg diff --git a/selfdrive/assets/icons/driver_face.png b/openpilot/selfdrive/assets/icons/driver_face.png similarity index 100% rename from selfdrive/assets/icons/driver_face.png rename to openpilot/selfdrive/assets/icons/driver_face.png diff --git a/selfdrive/assets/icons/experimental.png b/openpilot/selfdrive/assets/icons/experimental.png similarity index 100% rename from selfdrive/assets/icons/experimental.png rename to openpilot/selfdrive/assets/icons/experimental.png diff --git a/selfdrive/assets/icons/experimental.svg b/openpilot/selfdrive/assets/icons/experimental.svg similarity index 100% rename from selfdrive/assets/icons/experimental.svg rename to openpilot/selfdrive/assets/icons/experimental.svg diff --git a/selfdrive/assets/icons/experimental_grey.png b/openpilot/selfdrive/assets/icons/experimental_grey.png similarity index 100% rename from selfdrive/assets/icons/experimental_grey.png rename to openpilot/selfdrive/assets/icons/experimental_grey.png diff --git a/selfdrive/assets/icons/experimental_grey.svg b/openpilot/selfdrive/assets/icons/experimental_grey.svg similarity index 100% rename from selfdrive/assets/icons/experimental_grey.svg rename to openpilot/selfdrive/assets/icons/experimental_grey.svg diff --git a/selfdrive/assets/icons/experimental_white.png b/openpilot/selfdrive/assets/icons/experimental_white.png similarity index 100% rename from selfdrive/assets/icons/experimental_white.png rename to openpilot/selfdrive/assets/icons/experimental_white.png diff --git a/selfdrive/assets/icons/experimental_white.svg b/openpilot/selfdrive/assets/icons/experimental_white.svg similarity index 100% rename from selfdrive/assets/icons/experimental_white.svg rename to openpilot/selfdrive/assets/icons/experimental_white.svg diff --git a/selfdrive/assets/icons/eye_closed.png b/openpilot/selfdrive/assets/icons/eye_closed.png similarity index 100% rename from selfdrive/assets/icons/eye_closed.png rename to openpilot/selfdrive/assets/icons/eye_closed.png diff --git a/selfdrive/assets/icons/eye_closed.svg b/openpilot/selfdrive/assets/icons/eye_closed.svg similarity index 100% rename from selfdrive/assets/icons/eye_closed.svg rename to openpilot/selfdrive/assets/icons/eye_closed.svg diff --git a/selfdrive/assets/icons/eye_open.png b/openpilot/selfdrive/assets/icons/eye_open.png similarity index 100% rename from selfdrive/assets/icons/eye_open.png rename to openpilot/selfdrive/assets/icons/eye_open.png diff --git a/selfdrive/assets/icons/eye_open.svg b/openpilot/selfdrive/assets/icons/eye_open.svg similarity index 100% rename from selfdrive/assets/icons/eye_open.svg rename to openpilot/selfdrive/assets/icons/eye_open.svg diff --git a/openpilot/selfdrive/assets/icons/eyes_crossed.png b/openpilot/selfdrive/assets/icons/eyes_crossed.png new file mode 100644 index 0000000000..af2122cd9a --- /dev/null +++ b/openpilot/selfdrive/assets/icons/eyes_crossed.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4def42b5faffc6a8f747c210d24c3a1a8a7f82891738ff7f3317091e63326ba5 +size 1083 diff --git a/openpilot/selfdrive/assets/icons/eyes_open.png b/openpilot/selfdrive/assets/icons/eyes_open.png new file mode 100644 index 0000000000..ad9afc3a3e --- /dev/null +++ b/openpilot/selfdrive/assets/icons/eyes_open.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:52019b72834e478588114584820313af866d2d7a737591a166c413ccaab6acf5 +size 931 diff --git a/openpilot/selfdrive/assets/icons/link.png b/openpilot/selfdrive/assets/icons/link.png new file mode 100644 index 0000000000..8a795c05b8 --- /dev/null +++ b/openpilot/selfdrive/assets/icons/link.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a69514fe68dd1b4c73f28771640dcba10fc40989d1c7e771cb48bfd830fef206 +size 5713 diff --git a/selfdrive/assets/icons/lock_closed.png b/openpilot/selfdrive/assets/icons/lock_closed.png similarity index 100% rename from selfdrive/assets/icons/lock_closed.png rename to openpilot/selfdrive/assets/icons/lock_closed.png diff --git a/selfdrive/assets/icons/lock_closed.svg b/openpilot/selfdrive/assets/icons/lock_closed.svg similarity index 100% rename from selfdrive/assets/icons/lock_closed.svg rename to openpilot/selfdrive/assets/icons/lock_closed.svg diff --git a/selfdrive/assets/icons/menu.png b/openpilot/selfdrive/assets/icons/menu.png similarity index 100% rename from selfdrive/assets/icons/menu.png rename to openpilot/selfdrive/assets/icons/menu.png diff --git a/selfdrive/assets/icons/metric.png b/openpilot/selfdrive/assets/icons/metric.png similarity index 100% rename from selfdrive/assets/icons/metric.png rename to openpilot/selfdrive/assets/icons/metric.png diff --git a/openpilot/selfdrive/assets/icons/microphone.png b/openpilot/selfdrive/assets/icons/microphone.png new file mode 100644 index 0000000000..6cb9cc0254 --- /dev/null +++ b/openpilot/selfdrive/assets/icons/microphone.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9fc1f7f31d41f26ea7d6f52b3096f7a91844a3b897bc233a8489253c46f0403b +size 6324 diff --git a/selfdrive/assets/icons/minus.png b/openpilot/selfdrive/assets/icons/minus.png similarity index 100% rename from selfdrive/assets/icons/minus.png rename to openpilot/selfdrive/assets/icons/minus.png diff --git a/selfdrive/assets/icons/monitoring.png b/openpilot/selfdrive/assets/icons/monitoring.png similarity index 100% rename from selfdrive/assets/icons/monitoring.png rename to openpilot/selfdrive/assets/icons/monitoring.png diff --git a/selfdrive/assets/icons/network.png b/openpilot/selfdrive/assets/icons/network.png similarity index 100% rename from selfdrive/assets/icons/network.png rename to openpilot/selfdrive/assets/icons/network.png diff --git a/selfdrive/assets/icons/road.png b/openpilot/selfdrive/assets/icons/road.png similarity index 100% rename from selfdrive/assets/icons/road.png rename to openpilot/selfdrive/assets/icons/road.png diff --git a/selfdrive/assets/icons/settings.png b/openpilot/selfdrive/assets/icons/settings.png similarity index 100% rename from selfdrive/assets/icons/settings.png rename to openpilot/selfdrive/assets/icons/settings.png diff --git a/selfdrive/assets/icons/shell.png b/openpilot/selfdrive/assets/icons/shell.png similarity index 100% rename from selfdrive/assets/icons/shell.png rename to openpilot/selfdrive/assets/icons/shell.png diff --git a/selfdrive/assets/icons/shift-fill.png b/openpilot/selfdrive/assets/icons/shift-fill.png similarity index 100% rename from selfdrive/assets/icons/shift-fill.png rename to openpilot/selfdrive/assets/icons/shift-fill.png diff --git a/selfdrive/assets/icons/shift.png b/openpilot/selfdrive/assets/icons/shift.png similarity index 100% rename from selfdrive/assets/icons/shift.png rename to openpilot/selfdrive/assets/icons/shift.png diff --git a/selfdrive/assets/icons/speed_limit.png b/openpilot/selfdrive/assets/icons/speed_limit.png similarity index 100% rename from selfdrive/assets/icons/speed_limit.png rename to openpilot/selfdrive/assets/icons/speed_limit.png diff --git a/selfdrive/assets/icons/triangle.png b/openpilot/selfdrive/assets/icons/triangle.png similarity index 100% rename from selfdrive/assets/icons/triangle.png rename to openpilot/selfdrive/assets/icons/triangle.png diff --git a/selfdrive/assets/icons/triangle.svg b/openpilot/selfdrive/assets/icons/triangle.svg similarity index 100% rename from selfdrive/assets/icons/triangle.svg rename to openpilot/selfdrive/assets/icons/triangle.svg diff --git a/selfdrive/assets/icons/warning.png b/openpilot/selfdrive/assets/icons/warning.png similarity index 100% rename from selfdrive/assets/icons/warning.png rename to openpilot/selfdrive/assets/icons/warning.png diff --git a/selfdrive/assets/icons/wifi_strength_full.png b/openpilot/selfdrive/assets/icons/wifi_strength_full.png similarity index 100% rename from selfdrive/assets/icons/wifi_strength_full.png rename to openpilot/selfdrive/assets/icons/wifi_strength_full.png diff --git a/selfdrive/assets/icons/wifi_strength_full.svg b/openpilot/selfdrive/assets/icons/wifi_strength_full.svg similarity index 100% rename from selfdrive/assets/icons/wifi_strength_full.svg rename to openpilot/selfdrive/assets/icons/wifi_strength_full.svg diff --git a/selfdrive/assets/icons/wifi_strength_high.png b/openpilot/selfdrive/assets/icons/wifi_strength_high.png similarity index 100% rename from selfdrive/assets/icons/wifi_strength_high.png rename to openpilot/selfdrive/assets/icons/wifi_strength_high.png diff --git a/selfdrive/assets/icons/wifi_strength_high.svg b/openpilot/selfdrive/assets/icons/wifi_strength_high.svg similarity index 100% rename from selfdrive/assets/icons/wifi_strength_high.svg rename to openpilot/selfdrive/assets/icons/wifi_strength_high.svg diff --git a/selfdrive/assets/icons/wifi_strength_low.png b/openpilot/selfdrive/assets/icons/wifi_strength_low.png similarity index 100% rename from selfdrive/assets/icons/wifi_strength_low.png rename to openpilot/selfdrive/assets/icons/wifi_strength_low.png diff --git a/selfdrive/assets/icons/wifi_strength_low.svg b/openpilot/selfdrive/assets/icons/wifi_strength_low.svg similarity index 100% rename from selfdrive/assets/icons/wifi_strength_low.svg rename to openpilot/selfdrive/assets/icons/wifi_strength_low.svg diff --git a/selfdrive/assets/icons/wifi_strength_medium.png b/openpilot/selfdrive/assets/icons/wifi_strength_medium.png similarity index 100% rename from selfdrive/assets/icons/wifi_strength_medium.png rename to openpilot/selfdrive/assets/icons/wifi_strength_medium.png diff --git a/selfdrive/assets/icons/wifi_strength_medium.svg b/openpilot/selfdrive/assets/icons/wifi_strength_medium.svg similarity index 100% rename from selfdrive/assets/icons/wifi_strength_medium.svg rename to openpilot/selfdrive/assets/icons/wifi_strength_medium.svg diff --git a/selfdrive/assets/icons/wifi_uploading.png b/openpilot/selfdrive/assets/icons/wifi_uploading.png similarity index 100% rename from selfdrive/assets/icons/wifi_uploading.png rename to openpilot/selfdrive/assets/icons/wifi_uploading.png diff --git a/selfdrive/assets/icons/wifi_uploading.svg b/openpilot/selfdrive/assets/icons/wifi_uploading.svg similarity index 100% rename from selfdrive/assets/icons/wifi_uploading.svg rename to openpilot/selfdrive/assets/icons/wifi_uploading.svg diff --git a/openpilot/selfdrive/assets/icons_mici/adb_short.png b/openpilot/selfdrive/assets/icons_mici/adb_short.png new file mode 100644 index 0000000000..c49226c858 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/adb_short.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:263598da73c577c01cebd31ae78f45969ef8b335be1a5f55d54a696bb2982c0a +size 2062 diff --git a/openpilot/selfdrive/assets/icons_mici/alerts_bell.png b/openpilot/selfdrive/assets/icons_mici/alerts_bell.png new file mode 100644 index 0000000000..5d775425eb --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/alerts_bell.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4ce1d357acadd798939b398cce1761ceb05564b44f2a5bc6865c7842e60e79f2 +size 1474 diff --git a/openpilot/selfdrive/assets/icons_mici/alerts_pill.png b/openpilot/selfdrive/assets/icons_mici/alerts_pill.png new file mode 100644 index 0000000000..29ab2ad5b3 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/alerts_pill.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b3fe73cd1a24c05346a9b4a02e4f900a314c83a422beb38b0f88f91389582cd4 +size 3960 diff --git a/openpilot/selfdrive/assets/icons_mici/body.png b/openpilot/selfdrive/assets/icons_mici/body.png new file mode 100644 index 0000000000..2f7bb779d1 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/body.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6b45f88128430fb50ef51c8e08b8e2a1c8fbe0b5c3a08de9f5d9d59bc1edc82e +size 4545 diff --git a/openpilot/selfdrive/assets/icons_mici/buttons/button_circle.png b/openpilot/selfdrive/assets/icons_mici/buttons/button_circle.png new file mode 100644 index 0000000000..b6f4cc9d12 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/buttons/button_circle.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f92e5f0b7fc50c3b64bd18ecee8a8d518017b5461104de76dee6feb0f4f0d70d +size 7496 diff --git a/openpilot/selfdrive/assets/icons_mici/buttons/button_circle_disabled.png b/openpilot/selfdrive/assets/icons_mici/buttons/button_circle_disabled.png new file mode 100644 index 0000000000..d2104df4e1 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/buttons/button_circle_disabled.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:947aa3beb7eff6afb44101daf0aeaae7b7f31961c273df00eec0ca8359233c56 +size 5175 diff --git a/openpilot/selfdrive/assets/icons_mici/buttons/button_circle_pressed.png b/openpilot/selfdrive/assets/icons_mici/buttons/button_circle_pressed.png new file mode 100644 index 0000000000..9db0c2cd81 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/buttons/button_circle_pressed.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:70d4236bcfd3aa8f100b81179c1e0f193c6ffbd84769c4a516be4381e62b270a +size 18666 diff --git a/openpilot/selfdrive/assets/icons_mici/buttons/button_circle_red.png b/openpilot/selfdrive/assets/icons_mici/buttons/button_circle_red.png new file mode 100644 index 0000000000..68ae400b1e --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/buttons/button_circle_red.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b48d8a191979f27dae8a336f99d944008e2536f698c58cffa5f3dddc17429b45 +size 11451 diff --git a/openpilot/selfdrive/assets/icons_mici/buttons/button_circle_red_pressed.png b/openpilot/selfdrive/assets/icons_mici/buttons/button_circle_red_pressed.png new file mode 100644 index 0000000000..e61a678c1c --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/buttons/button_circle_red_pressed.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ed07f72339cf1c3926a2cb7314f9baa099bcdb3f8bc89a9084661b71334b0526 +size 32599 diff --git a/openpilot/selfdrive/assets/icons_mici/buttons/button_rectangle.png b/openpilot/selfdrive/assets/icons_mici/buttons/button_rectangle.png new file mode 100644 index 0000000000..4ccf6995b1 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/buttons/button_rectangle.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5dedb4139a7ddeafcdaf050144769e490643820db726201a15250e1042eb6d15 +size 7982 diff --git a/openpilot/selfdrive/assets/icons_mici/buttons/button_rectangle_disabled.png b/openpilot/selfdrive/assets/icons_mici/buttons/button_rectangle_disabled.png new file mode 100644 index 0000000000..5e891588f5 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/buttons/button_rectangle_disabled.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d527dcff61fa66902681706b4916586244b8cf0520086ac980ff782ab2d99ce7 +size 4778 diff --git a/openpilot/selfdrive/assets/icons_mici/buttons/button_rectangle_pressed.png b/openpilot/selfdrive/assets/icons_mici/buttons/button_rectangle_pressed.png new file mode 100644 index 0000000000..2cbf1cedb8 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/buttons/button_rectangle_pressed.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c6b1b0f1270a596b5ac150dee8ade54794de55b2033a529d4a17176f688aa6f0 +size 56738 diff --git a/openpilot/selfdrive/assets/icons_mici/buttons/slider_bg.png b/openpilot/selfdrive/assets/icons_mici/buttons/slider_bg.png new file mode 100644 index 0000000000..9164f74bad --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/buttons/slider_bg.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1ca620a05e9e69351b9bbcfcf021dae11fde26be50d7f1a39257d319f6303616 +size 9779 diff --git a/openpilot/selfdrive/assets/icons_mici/buttons/toggle_dot_disabled.png b/openpilot/selfdrive/assets/icons_mici/buttons/toggle_dot_disabled.png new file mode 100644 index 0000000000..1ff4db45a5 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/buttons/toggle_dot_disabled.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:89ac033d879beeb0a7fa1919838e0ec64b1a625a4aafc14f7b990c607a79b676 +size 2220 diff --git a/openpilot/selfdrive/assets/icons_mici/buttons/toggle_dot_enabled.png b/openpilot/selfdrive/assets/icons_mici/buttons/toggle_dot_enabled.png new file mode 100644 index 0000000000..5bb4d778f8 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/buttons/toggle_dot_enabled.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:532bf0e8535e3f9bc13af13029a27d6c14ae788d52224b6c65623334f62fada0 +size 6048 diff --git a/openpilot/selfdrive/assets/icons_mici/buttons/toggle_pill_disabled.png b/openpilot/selfdrive/assets/icons_mici/buttons/toggle_pill_disabled.png new file mode 100644 index 0000000000..555c16e095 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/buttons/toggle_pill_disabled.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7891a628bd9cedc1097114e89fcec4a50a88021c7d6c63f1329d087be9e1783e +size 3065 diff --git a/openpilot/selfdrive/assets/icons_mici/buttons/toggle_pill_enabled.png b/openpilot/selfdrive/assets/icons_mici/buttons/toggle_pill_enabled.png new file mode 100644 index 0000000000..d95039da92 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/buttons/toggle_pill_enabled.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ad31da78544edd18d0ac154670f22d1cd1ac57f50576002f04701d22c59502a8 +size 8257 diff --git a/openpilot/selfdrive/assets/icons_mici/egpu.png b/openpilot/selfdrive/assets/icons_mici/egpu.png new file mode 100644 index 0000000000..dc2bc8e276 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/egpu.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ec3dcf64cbc34251d8423cb8b3b31d743e93d14002dec43c389a857cb7e8eb17 +size 10875 diff --git a/openpilot/selfdrive/assets/icons_mici/egpu_gray.png b/openpilot/selfdrive/assets/icons_mici/egpu_gray.png new file mode 100644 index 0000000000..a6aeb84689 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/egpu_gray.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7409c53d7c72681c24982fd83b56ce70f80797c9c0f936d9296a5c18557ac472 +size 7279 diff --git a/openpilot/selfdrive/assets/icons_mici/exclamation_point.png b/openpilot/selfdrive/assets/icons_mici/exclamation_point.png new file mode 100644 index 0000000000..ede3b638bc --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/exclamation_point.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:254b7f753b70c964847b686f0f71af751f2f49beea6ede4aeb333fe06062a257 +size 2289 diff --git a/openpilot/selfdrive/assets/icons_mici/experimental_mode.png b/openpilot/selfdrive/assets/icons_mici/experimental_mode.png new file mode 100644 index 0000000000..75850d08f5 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/experimental_mode.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:01841b602632c66ab14a8e52b874a1623f09641dc2ef0620f4e2d00bb4a913f3 +size 16243 diff --git a/openpilot/selfdrive/assets/icons_mici/microphone.png b/openpilot/selfdrive/assets/icons_mici/microphone.png new file mode 100644 index 0000000000..9af8f2f455 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/microphone.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:744dbaa68ee74e300cd46439bad79449c860e1c5c027304b0f382bd5383fba77 +size 6817 diff --git a/openpilot/selfdrive/assets/icons_mici/offroad_alerts/big_alert.png b/openpilot/selfdrive/assets/icons_mici/offroad_alerts/big_alert.png new file mode 100644 index 0000000000..142367d0e6 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/offroad_alerts/big_alert.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aeee7f049879caff52320fab5f286cf3fd6a52c820cd8e150ff242e53a14176f +size 14774 diff --git a/openpilot/selfdrive/assets/icons_mici/offroad_alerts/big_alert_pressed.png b/openpilot/selfdrive/assets/icons_mici/offroad_alerts/big_alert_pressed.png new file mode 100644 index 0000000000..2ff01024d9 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/offroad_alerts/big_alert_pressed.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0b59ddada9c9e0e7972ead27396ebe6c10fd2352687b18ff6b476f61f74d80bf +size 46106 diff --git a/openpilot/selfdrive/assets/icons_mici/offroad_alerts/green_wheel.png b/openpilot/selfdrive/assets/icons_mici/offroad_alerts/green_wheel.png new file mode 100644 index 0000000000..08181ca35f --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/offroad_alerts/green_wheel.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3b11ee84d48972a2499cb29f01594d77a1a39692f6424a315a3f83262bc16087 +size 13481 diff --git a/openpilot/selfdrive/assets/icons_mici/offroad_alerts/medium_alert.png b/openpilot/selfdrive/assets/icons_mici/offroad_alerts/medium_alert.png new file mode 100644 index 0000000000..91a7b43c5a --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/offroad_alerts/medium_alert.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:46d08a8a08b42d466ff45d8ad6d2578e345dcbb1c06c126ad361873d9d35eaec +size 12877 diff --git a/openpilot/selfdrive/assets/icons_mici/offroad_alerts/medium_alert_pressed.png b/openpilot/selfdrive/assets/icons_mici/offroad_alerts/medium_alert_pressed.png new file mode 100644 index 0000000000..09ca2d08d5 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/offroad_alerts/medium_alert_pressed.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:42ea275e5fe0a8a0e2fddb5a4a8487806fb22850115ea3646ee8f213d5fd6bb6 +size 37202 diff --git a/openpilot/selfdrive/assets/icons_mici/offroad_alerts/orange_warning.png b/openpilot/selfdrive/assets/icons_mici/offroad_alerts/orange_warning.png new file mode 100644 index 0000000000..52e6836d4b --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/offroad_alerts/orange_warning.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d548405a65ba4d4590c55866612dc6aa0e78d9278fc864ef60fe3e463edf4a68 +size 12169 diff --git a/openpilot/selfdrive/assets/icons_mici/offroad_alerts/red_warning.png b/openpilot/selfdrive/assets/icons_mici/offroad_alerts/red_warning.png new file mode 100644 index 0000000000..df608d3518 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/offroad_alerts/red_warning.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b6fc63326d34fbe72f6daf104d101ce19e547dbfe134427c067c957a7179df74 +size 12124 diff --git a/openpilot/selfdrive/assets/icons_mici/offroad_alerts/small_alert.png b/openpilot/selfdrive/assets/icons_mici/offroad_alerts/small_alert.png new file mode 100644 index 0000000000..0a50b6a1ca --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/offroad_alerts/small_alert.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cfbf38672a893fd1d8fadf942354d2511e2436814a9af0e5c188cbb427fc6c70 +size 12281 diff --git a/openpilot/selfdrive/assets/icons_mici/offroad_alerts/small_alert_pressed.png b/openpilot/selfdrive/assets/icons_mici/offroad_alerts/small_alert_pressed.png new file mode 100644 index 0000000000..865355ef01 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/offroad_alerts/small_alert_pressed.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a7102850bcfb075a285041cecb546559374a905403ab3b9814fa6097d2d822dd +size 34680 diff --git a/openpilot/selfdrive/assets/icons_mici/onroad/blind_spot_left.png b/openpilot/selfdrive/assets/icons_mici/onroad/blind_spot_left.png new file mode 100644 index 0000000000..fdc189b858 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/onroad/blind_spot_left.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:77b20a8c478d982412d556afb3a035b80b4aa9fe7a86aea761af4a42147d9435 +size 45297 diff --git a/openpilot/selfdrive/assets/icons_mici/onroad/bookmark.png b/openpilot/selfdrive/assets/icons_mici/onroad/bookmark.png new file mode 100644 index 0000000000..305561f509 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/onroad/bookmark.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fd91685bf656e828648acf035a4737acb2c4709e8514cf0aa0a10fa470a9bb60 +size 11580 diff --git a/openpilot/selfdrive/assets/icons_mici/onroad/driver_monitoring/dm_background.png b/openpilot/selfdrive/assets/icons_mici/onroad/driver_monitoring/dm_background.png new file mode 100644 index 0000000000..4129b13d92 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/onroad/driver_monitoring/dm_background.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cb89d9f11cf44992f92142aa5ad84e1ac700a2601aff2abab373e2a822af149e +size 11678 diff --git a/openpilot/selfdrive/assets/icons_mici/onroad/driver_monitoring/dm_cone.png b/openpilot/selfdrive/assets/icons_mici/onroad/driver_monitoring/dm_cone.png new file mode 100644 index 0000000000..6974b6d8e2 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/onroad/driver_monitoring/dm_cone.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5f5d4b7bd406114945e53f4d56089102ee83ba7d0a4590a371f7acab90c7ad53 +size 1862 diff --git a/openpilot/selfdrive/assets/icons_mici/onroad/driver_monitoring/dm_person.png b/openpilot/selfdrive/assets/icons_mici/onroad/driver_monitoring/dm_person.png new file mode 100644 index 0000000000..5b917f3a4a --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/onroad/driver_monitoring/dm_person.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e2772c6a9fe9c57099d347ad49f0cb7c906593f1fdf0e6dde96d104baf0200b0 +size 1365 diff --git a/openpilot/selfdrive/assets/icons_mici/onroad/eye_fill.png b/openpilot/selfdrive/assets/icons_mici/onroad/eye_fill.png new file mode 100644 index 0000000000..78758a9809 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/onroad/eye_fill.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:07310879d093108435c0011846ae1184966db86443bc6e7ca036a6fa6123700b +size 4983 diff --git a/openpilot/selfdrive/assets/icons_mici/onroad/eye_orange.png b/openpilot/selfdrive/assets/icons_mici/onroad/eye_orange.png new file mode 100644 index 0000000000..932c71260b --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/onroad/eye_orange.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7be447e56d649e0362ef650494b484e140a01ead31799ce43b266f5781c918d2 +size 36473 diff --git a/openpilot/selfdrive/assets/icons_mici/onroad/glasses.png b/openpilot/selfdrive/assets/icons_mici/onroad/glasses.png new file mode 100644 index 0000000000..006972fd39 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/onroad/glasses.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:56de402482b5987ed9a0ff3f793a1c89f857304b34fbb8a3deb5b5d4a332be1c +size 3688 diff --git a/openpilot/selfdrive/assets/icons_mici/onroad/onroad_fade.png b/openpilot/selfdrive/assets/icons_mici/onroad/onroad_fade.png new file mode 100644 index 0000000000..3f823061b9 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/onroad/onroad_fade.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2aa6d04ba038f15a92868de6e6c7b04f624b4fe89d03bc3e9c4cd44cb729b24e +size 38317 diff --git a/openpilot/selfdrive/assets/icons_mici/onroad/turn_signal_left.png b/openpilot/selfdrive/assets/icons_mici/onroad/turn_signal_left.png new file mode 100644 index 0000000000..97b5cf1443 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/onroad/turn_signal_left.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f9f7d0554c0c79ab605c1119ffdef0a4f55196e53b75a65b6ac5218911e24a02 +size 45701 diff --git a/openpilot/selfdrive/assets/icons_mici/settings.png b/openpilot/selfdrive/assets/icons_mici/settings.png new file mode 100644 index 0000000000..4ba7df9fdf --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:14b457d2dc19d8658f525cc6989c9cfcf0edaf695b18767514242acbdbe2a6dd +size 2198 diff --git a/openpilot/selfdrive/assets/icons_mici/settings/comma_icon.png b/openpilot/selfdrive/assets/icons_mici/settings/comma_icon.png new file mode 100644 index 0000000000..dd38a8938f --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings/comma_icon.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7ad4ee47ec6470f788a026f95ed86bf344f64f9cf3186c9c78927233d2694a1d +size 1388 diff --git a/openpilot/selfdrive/assets/icons_mici/settings/developer/ssh.png b/openpilot/selfdrive/assets/icons_mici/settings/developer/ssh.png new file mode 100644 index 0000000000..0f17d04eca --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings/developer/ssh.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b26133bee089627202d5e89a4e939ad23aaceb5d8e26d7381b1aea3ef892f2ee +size 2620 diff --git a/openpilot/selfdrive/assets/icons_mici/settings/developer_icon.png b/openpilot/selfdrive/assets/icons_mici/settings/developer_icon.png new file mode 100644 index 0000000000..f9d553c7c3 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings/developer_icon.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ebb4f7ad9fd2f9fb3c69a38fbc00cbe690809b0ff202ffd4768ae5b699acc035 +size 1759 diff --git a/openpilot/selfdrive/assets/icons_mici/settings/device/cameras.png b/openpilot/selfdrive/assets/icons_mici/settings/device/cameras.png new file mode 100644 index 0000000000..ae9a88c4dc --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings/device/cameras.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5f47e636025e044977f278a35546e0fc971f48fd53c2eeafd3508e95c35f378f +size 3117 diff --git a/openpilot/selfdrive/assets/icons_mici/settings/device/fcc_logo.png b/openpilot/selfdrive/assets/icons_mici/settings/device/fcc_logo.png new file mode 100644 index 0000000000..f29b24fd09 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings/device/fcc_logo.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3cac8546d19e75a9edcbc0721a887fd74c8a3c41bfe19e36186b2b2bcabdae98 +size 1817 diff --git a/openpilot/selfdrive/assets/icons_mici/settings/device/info.png b/openpilot/selfdrive/assets/icons_mici/settings/device/info.png new file mode 100644 index 0000000000..9a29c46d0d --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings/device/info.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:66858a5d3302333485fa391f7a9bb3a9b1ab4ae881e7fb47b04c3a4507011c94 +size 2613 diff --git a/openpilot/selfdrive/assets/icons_mici/settings/device/lkas.png b/openpilot/selfdrive/assets/icons_mici/settings/device/lkas.png new file mode 100644 index 0000000000..80d37d4d5c --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings/device/lkas.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a05a41e66c7a24d461a4bbcdab0979031e5900e1db270af52ca363f0bed521f5 +size 2028 diff --git a/openpilot/selfdrive/assets/icons_mici/settings/device/pair.png b/openpilot/selfdrive/assets/icons_mici/settings/device/pair.png new file mode 100644 index 0000000000..807d44335d --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings/device/pair.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:678483230831d0a7d3dcad5f067a7b641e5d2ae0db477665dfc6c53a675eba18 +size 1779 diff --git a/openpilot/selfdrive/assets/icons_mici/settings/device/power.png b/openpilot/selfdrive/assets/icons_mici/settings/device/power.png new file mode 100644 index 0000000000..711f1a4ab9 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings/device/power.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a34885e79f42d19b7777dd07e7ab51df344880cb770c48e0baaddb177c2ae938 +size 2228 diff --git a/openpilot/selfdrive/assets/icons_mici/settings/device/reboot.png b/openpilot/selfdrive/assets/icons_mici/settings/device/reboot.png new file mode 100644 index 0000000000..298a85c504 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings/device/reboot.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1356fe3ddda14568e9be1dca4e16ca9048852e3a27a3f531cd58d7d368485a82 +size 2362 diff --git a/openpilot/selfdrive/assets/icons_mici/settings/device/uninstall.png b/openpilot/selfdrive/assets/icons_mici/settings/device/uninstall.png new file mode 100644 index 0000000000..53f8bc0e7d --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings/device/uninstall.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:50a8ce4fa8ff7f5b0f56ba0dc65b4802dc0be2dc0967b5cb3a15e3b79a4e513e +size 2424 diff --git a/openpilot/selfdrive/assets/icons_mici/settings/device/up_to_date.png b/openpilot/selfdrive/assets/icons_mici/settings/device/up_to_date.png new file mode 100644 index 0000000000..e09f7d3308 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings/device/up_to_date.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:61bc44b6e0f99640434d6abcb64880c7bf575eda5cdcf7d74cba7d73307dd39a +size 2739 diff --git a/openpilot/selfdrive/assets/icons_mici/settings/device/update.png b/openpilot/selfdrive/assets/icons_mici/settings/device/update.png new file mode 100644 index 0000000000..498c066191 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings/device/update.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f28cdeaba9146521335bc11ad60a8e0368eb0ed1381e88b35a12a6138ba22ed6 +size 2409 diff --git a/openpilot/selfdrive/assets/icons_mici/settings/device_icon.png b/openpilot/selfdrive/assets/icons_mici/settings/device_icon.png new file mode 100644 index 0000000000..6a716e4dfd --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings/device_icon.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2273629450aa870f0964dd285721c35d3d313fb8b4684122215a65844ae744d0 +size 1888 diff --git a/openpilot/selfdrive/assets/icons_mici/settings/firehose.png b/openpilot/selfdrive/assets/icons_mici/settings/firehose.png new file mode 100644 index 0000000000..37451c0482 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings/firehose.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:416656861380981acc114e5285b448d6e4dc42b98539d0ba16821cbc3db89208 +size 1364 diff --git a/openpilot/selfdrive/assets/icons_mici/settings/horizontal_scroll_indicator.png b/openpilot/selfdrive/assets/icons_mici/settings/horizontal_scroll_indicator.png new file mode 100644 index 0000000000..39dd7b1947 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings/horizontal_scroll_indicator.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:af8d5ecb6468442361462aa838a2d234b1256b8139418be8ef2962e4350cfbef +size 2176 diff --git a/openpilot/selfdrive/assets/icons_mici/settings/keyboard/backspace.png b/openpilot/selfdrive/assets/icons_mici/settings/keyboard/backspace.png new file mode 100644 index 0000000000..53ff00c2ae --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings/keyboard/backspace.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:69bb4a401429c3fdf473778f751288b2aafea27eb13f09b20e83d55212f084ba +size 1963 diff --git a/openpilot/selfdrive/assets/icons_mici/settings/keyboard/caps_lock.png b/openpilot/selfdrive/assets/icons_mici/settings/keyboard/caps_lock.png new file mode 100644 index 0000000000..2d173bfc9f --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings/keyboard/caps_lock.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:563c211fd98018e24418235602e596f3a481f04fddde0a14590e563474fcffd2 +size 1423 diff --git a/openpilot/selfdrive/assets/icons_mici/settings/keyboard/caps_lower.png b/openpilot/selfdrive/assets/icons_mici/settings/keyboard/caps_lower.png new file mode 100644 index 0000000000..a3ce71f049 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings/keyboard/caps_lower.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6f81811ea9cdc409d5549035ca928c76e22396193e1cefb6cacab3747ee0c297 +size 1142 diff --git a/openpilot/selfdrive/assets/icons_mici/settings/keyboard/caps_upper.png b/openpilot/selfdrive/assets/icons_mici/settings/keyboard/caps_upper.png new file mode 100644 index 0000000000..7c147bc07b --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings/keyboard/caps_upper.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:60875e73dd9659122c9248d8e99d5cfd301d68dabeec2cb42cebce812c9baae9 +size 1102 diff --git a/openpilot/selfdrive/assets/icons_mici/settings/keyboard/enter.png b/openpilot/selfdrive/assets/icons_mici/settings/keyboard/enter.png new file mode 100644 index 0000000000..0b7fc95c51 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings/keyboard/enter.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3dd956d5ccfce01a01bea74ef59c9e73dfca406a5ff9ac62417203afa6027fba +size 5620 diff --git a/openpilot/selfdrive/assets/icons_mici/settings/keyboard/enter_disabled.png b/openpilot/selfdrive/assets/icons_mici/settings/keyboard/enter_disabled.png new file mode 100644 index 0000000000..251d5d8d14 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings/keyboard/enter_disabled.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1dd1c2308872729d58adab390030ae9c987dc7908f0c39391651ea2b6cb620c5 +size 2445 diff --git a/openpilot/selfdrive/assets/icons_mici/settings/keyboard/keyboard_background.png b/openpilot/selfdrive/assets/icons_mici/settings/keyboard/keyboard_background.png new file mode 100644 index 0000000000..8c2c068d41 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings/keyboard/keyboard_background.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:399e7ff9dea6710244827c91014f1a08d8ae989dce922928d6b7f7504b15ba79 +size 11321 diff --git a/openpilot/selfdrive/assets/icons_mici/settings/keyboard/space.png b/openpilot/selfdrive/assets/icons_mici/settings/keyboard/space.png new file mode 100644 index 0000000000..3d61109721 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings/keyboard/space.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f431e428772991323ee3ce662479e1ab29c3d80a72b93cf9c9673716ba245d5f +size 654 diff --git a/openpilot/selfdrive/assets/icons_mici/settings/network/cell_strength_full.png b/openpilot/selfdrive/assets/icons_mici/settings/network/cell_strength_full.png new file mode 100644 index 0000000000..13f70386d4 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings/network/cell_strength_full.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fb7af523411c5ed75c6e1418dfc2a379486f6dbd7f2f1c281d3ff54e1ea7810e +size 777 diff --git a/openpilot/selfdrive/assets/icons_mici/settings/network/cell_strength_high.png b/openpilot/selfdrive/assets/icons_mici/settings/network/cell_strength_high.png new file mode 100644 index 0000000000..1fea6d23b8 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings/network/cell_strength_high.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:db86e176e016458fcff00d40e37636a808977e0cc01bcc9c04b31a1001562de8 +size 936 diff --git a/openpilot/selfdrive/assets/icons_mici/settings/network/cell_strength_low.png b/openpilot/selfdrive/assets/icons_mici/settings/network/cell_strength_low.png new file mode 100644 index 0000000000..d763f86c7f --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings/network/cell_strength_low.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1cd0b3a00db36ee7eacf5887d07d40e5351fb441d98643a02df4c742cd1e935d +size 945 diff --git a/openpilot/selfdrive/assets/icons_mici/settings/network/cell_strength_medium.png b/openpilot/selfdrive/assets/icons_mici/settings/network/cell_strength_medium.png new file mode 100644 index 0000000000..148ee63e99 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings/network/cell_strength_medium.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:25724acfe0c261070b103ef5933053d5dd8b726ece42d0e5f715f05c67be2294 +size 956 diff --git a/openpilot/selfdrive/assets/icons_mici/settings/network/cell_strength_none.png b/openpilot/selfdrive/assets/icons_mici/settings/network/cell_strength_none.png new file mode 100644 index 0000000000..c6d82ac316 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings/network/cell_strength_none.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cb0aeb6260bcd0642204f842112479f4b19b350db9addae5e14c9c5131bcf956 +size 781 diff --git a/openpilot/selfdrive/assets/icons_mici/settings/network/new/forget_button.png b/openpilot/selfdrive/assets/icons_mici/settings/network/new/forget_button.png new file mode 100644 index 0000000000..541433be76 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings/network/new/forget_button.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6ccb5f2298389ae36df87de84d85440ee5a82c50e803c9bd362c9b89ea45aa69 +size 6611 diff --git a/openpilot/selfdrive/assets/icons_mici/settings/network/new/forget_button_pressed.png b/openpilot/selfdrive/assets/icons_mici/settings/network/new/forget_button_pressed.png new file mode 100644 index 0000000000..26cc8b4fca --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings/network/new/forget_button_pressed.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d9f17c82b2f349d107d27c69418f054be1f1753f970c7d3d3520c1e65de00511 +size 12894 diff --git a/openpilot/selfdrive/assets/icons_mici/settings/network/new/lock.png b/openpilot/selfdrive/assets/icons_mici/settings/network/new/lock.png new file mode 100644 index 0000000000..65bd71f654 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings/network/new/lock.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7488c1aa69b728387b2cf300a614cc64e3c2305d2b509c14cf44cad65d20d85c +size 2509 diff --git a/openpilot/selfdrive/assets/icons_mici/settings/network/new/trash.png b/openpilot/selfdrive/assets/icons_mici/settings/network/new/trash.png new file mode 100644 index 0000000000..81e5f13e43 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings/network/new/trash.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9074162bf0469fc5ab0b5711a121289a983c887161df269ac120edd8fd024499 +size 1533 diff --git a/openpilot/selfdrive/assets/icons_mici/settings/network/tethering.png b/openpilot/selfdrive/assets/icons_mici/settings/network/tethering.png new file mode 100644 index 0000000000..4bb416b0b1 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings/network/tethering.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b1e322ea6e57b05b3515fcd4e9100f890e6ff80607c11360b7927fa5a9765beb +size 2752 diff --git a/openpilot/selfdrive/assets/icons_mici/settings/network/wifi_strength_full.png b/openpilot/selfdrive/assets/icons_mici/settings/network/wifi_strength_full.png new file mode 100644 index 0000000000..fe81ffa572 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings/network/wifi_strength_full.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:73c76e5240bdff64c1d1ed0ac2bb9c3fadb2fd61fbf8dc710b812757af8bcf6c +size 2026 diff --git a/openpilot/selfdrive/assets/icons_mici/settings/network/wifi_strength_low.png b/openpilot/selfdrive/assets/icons_mici/settings/network/wifi_strength_low.png new file mode 100644 index 0000000000..2649cc89dc --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings/network/wifi_strength_low.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e66cc6174a54177793c42ef3525a9aa1592e05b0abb677442c7226269d1371a5 +size 2196 diff --git a/openpilot/selfdrive/assets/icons_mici/settings/network/wifi_strength_medium.png b/openpilot/selfdrive/assets/icons_mici/settings/network/wifi_strength_medium.png new file mode 100644 index 0000000000..8881833375 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings/network/wifi_strength_medium.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7948a9234f2bc996aefb3a9e58a37c06ebbf54e8e4596e47800f78ef7e81961f +size 2231 diff --git a/openpilot/selfdrive/assets/icons_mici/settings/network/wifi_strength_none.png b/openpilot/selfdrive/assets/icons_mici/settings/network/wifi_strength_none.png new file mode 100644 index 0000000000..848d7849a2 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings/network/wifi_strength_none.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a57ea402448dacc2026631174e448b6254698fe92309221576400cbf28196936 +size 2195 diff --git a/openpilot/selfdrive/assets/icons_mici/settings/network/wifi_strength_slash.png b/openpilot/selfdrive/assets/icons_mici/settings/network/wifi_strength_slash.png new file mode 100644 index 0000000000..4457a3fcd2 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings/network/wifi_strength_slash.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7e6d166bdbbcdc106e7cd4a44ba85848888f18a6ef34e86daac8e12a3f519443 +size 2318 diff --git a/openpilot/selfdrive/assets/icons_mici/settings/software.png b/openpilot/selfdrive/assets/icons_mici/settings/software.png new file mode 100644 index 0000000000..5cf528cbdd --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/settings/software.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c4c38772e6080aa4b8bf5212d3619e949775468c64f3edb88a1a426d767c38d2 +size 1579 diff --git a/openpilot/selfdrive/assets/icons_mici/setup/cancel.png b/openpilot/selfdrive/assets/icons_mici/setup/cancel.png new file mode 100644 index 0000000000..f50cc9ef3f --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/setup/cancel.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a6892bd4d9b14b587fa491a6d608562e38819b4c618b1d7a3e8c384f05d52a2b +size 1245 diff --git a/openpilot/selfdrive/assets/icons_mici/setup/continue.png b/openpilot/selfdrive/assets/icons_mici/setup/continue.png new file mode 100644 index 0000000000..7a67bb0c96 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/setup/continue.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3428d8fcf2ecf9542c524706124f82b7fc809453c63418c9234ac9df5d85bd24 +size 10074 diff --git a/openpilot/selfdrive/assets/icons_mici/setup/continue_disabled.png b/openpilot/selfdrive/assets/icons_mici/setup/continue_disabled.png new file mode 100644 index 0000000000..8a2bcc2ffe --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/setup/continue_disabled.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b2810add4943dd4f20a984ed6011b520925919a58d5c0dd0d846fc4d7f8a1d02 +size 7109 diff --git a/openpilot/selfdrive/assets/icons_mici/setup/continue_pressed.png b/openpilot/selfdrive/assets/icons_mici/setup/continue_pressed.png new file mode 100644 index 0000000000..3eaee7bf1c --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/setup/continue_pressed.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3a3a87454a3d2f1ebb327211062c52480de945673dcfd137c5da3df8fa98d731 +size 22400 diff --git a/openpilot/selfdrive/assets/icons_mici/setup/driver_monitoring/dm_check.png b/openpilot/selfdrive/assets/icons_mici/setup/driver_monitoring/dm_check.png new file mode 100644 index 0000000000..dfb9799b0b --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/setup/driver_monitoring/dm_check.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2290105f9b055b3c3d482d883d148de3418cad07b653133b0f61137e1976c407 +size 1412 diff --git a/openpilot/selfdrive/assets/icons_mici/setup/driver_monitoring/dm_question.png b/openpilot/selfdrive/assets/icons_mici/setup/driver_monitoring/dm_question.png new file mode 100644 index 0000000000..fa29be1827 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/setup/driver_monitoring/dm_question.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ec9691d2572e2e084f0b3c99a1dcd0daadf5040d16c02347ffec9dd5466c061a +size 1438 diff --git a/openpilot/selfdrive/assets/icons_mici/setup/factory_reset.png b/openpilot/selfdrive/assets/icons_mici/setup/factory_reset.png new file mode 100644 index 0000000000..bcb3ea92cb --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/setup/factory_reset.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:122a614d1aa26187507951f932160eebfddfebcb4293e78f8d23e350fc97bc0f +size 11489 diff --git a/openpilot/selfdrive/assets/icons_mici/setup/green_dm.png b/openpilot/selfdrive/assets/icons_mici/setup/green_dm.png new file mode 100644 index 0000000000..87f4ffe788 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/setup/green_dm.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8b6d7747dd6bbf47d9782fc0d847c224b933f6616218ade1f9220018aa9d6acc +size 15052 diff --git a/openpilot/selfdrive/assets/icons_mici/setup/green_info.png b/openpilot/selfdrive/assets/icons_mici/setup/green_info.png new file mode 100644 index 0000000000..57e005abd6 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/setup/green_info.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5055bc385a1de674e6f3cbafdb611ee4b1088de2a3c357bce76f6a192226c952 +size 14154 diff --git a/openpilot/selfdrive/assets/icons_mici/setup/orange_dm.png b/openpilot/selfdrive/assets/icons_mici/setup/orange_dm.png new file mode 100644 index 0000000000..97df767a98 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/setup/orange_dm.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9c45ab0b949c1c71651f9f48cf6ff10196d64eb85e042b063e92b1d7ca02dcb5 +size 13155 diff --git a/openpilot/selfdrive/assets/icons_mici/setup/red_warning.png b/openpilot/selfdrive/assets/icons_mici/setup/red_warning.png new file mode 100644 index 0000000000..387794cf13 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/setup/red_warning.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e8e8bc3c15df7512a81b902e47fb069eff1370c833095d3b25f3866efb815fff +size 11123 diff --git a/openpilot/selfdrive/assets/icons_mici/setup/reset_failed.png b/openpilot/selfdrive/assets/icons_mici/setup/reset_failed.png new file mode 100644 index 0000000000..680df97cbc --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/setup/reset_failed.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8d5b8f76e5f47e77e5af3016ebdbe548ad3bc9af83a1111b3214bf4017c95a28 +size 11792 diff --git a/openpilot/selfdrive/assets/icons_mici/setup/restore.png b/openpilot/selfdrive/assets/icons_mici/setup/restore.png new file mode 100644 index 0000000000..5c62086f64 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/setup/restore.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:63c1499106621a4d927c21b2b04c87235a927216d9f513a0205f0fe03b8c799b +size 12320 diff --git a/openpilot/selfdrive/assets/icons_mici/setup/small_button.png b/openpilot/selfdrive/assets/icons_mici/setup/small_button.png new file mode 100644 index 0000000000..1ee01aeac2 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/setup/small_button.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:13919cf5df3137fdffdb8cc53a1215f13bf478a780ca8614234b7af0cdc0e766 +size 5409 diff --git a/openpilot/selfdrive/assets/icons_mici/setup/small_button_disabled.png b/openpilot/selfdrive/assets/icons_mici/setup/small_button_disabled.png new file mode 100644 index 0000000000..da8bb3eefd --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/setup/small_button_disabled.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6ed258d8e0531c19705953ded065c6d5e14929728a2909d8d4e335898fa5d080 +size 4056 diff --git a/openpilot/selfdrive/assets/icons_mici/setup/small_button_pressed.png b/openpilot/selfdrive/assets/icons_mici/setup/small_button_pressed.png new file mode 100644 index 0000000000..6e30f47fba --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/setup/small_button_pressed.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c032fd71ccfebe161827de420771e7927fe1ed799e615e24d458cfd79fead7f7 +size 7875 diff --git a/openpilot/selfdrive/assets/icons_mici/setup/small_slider/slider_arrow.png b/openpilot/selfdrive/assets/icons_mici/setup/small_slider/slider_arrow.png new file mode 100644 index 0000000000..acf5b17414 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/setup/small_slider/slider_arrow.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:75a6557935075a646b17d083202832daafb263d4cfa38aea2af407afc04e2ef4 +size 1312 diff --git a/openpilot/selfdrive/assets/icons_mici/setup/small_slider/slider_bg_larger.png b/openpilot/selfdrive/assets/icons_mici/setup/small_slider/slider_bg_larger.png new file mode 100644 index 0000000000..11c3ae2d3f --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/setup/small_slider/slider_bg_larger.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:950d55fd7294fb05c10ba9944537c02637776497c159e1b7d145c73f0f9d3253 +size 7119 diff --git a/openpilot/selfdrive/assets/icons_mici/setup/small_slider/slider_black_rounded_rectangle.png b/openpilot/selfdrive/assets/icons_mici/setup/small_slider/slider_black_rounded_rectangle.png new file mode 100644 index 0000000000..683587a060 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/setup/small_slider/slider_black_rounded_rectangle.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:61281d3e3ef5ac5a8fe75405a93c2096bf235f090b27832e986444e3fb85715e +size 7427 diff --git a/openpilot/selfdrive/assets/icons_mici/setup/small_slider/slider_black_rounded_rectangle_pressed.png b/openpilot/selfdrive/assets/icons_mici/setup/small_slider/slider_black_rounded_rectangle_pressed.png new file mode 100644 index 0000000000..470bfc50c0 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/setup/small_slider/slider_black_rounded_rectangle_pressed.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d1dd642ae4708cc7a837e8ef8b4c75f578654d241f8c854249c2b1ade640ceca +size 14058 diff --git a/openpilot/selfdrive/assets/icons_mici/setup/small_slider/slider_green_rounded_rectangle.png b/openpilot/selfdrive/assets/icons_mici/setup/small_slider/slider_green_rounded_rectangle.png new file mode 100644 index 0000000000..88e6985f12 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/setup/small_slider/slider_green_rounded_rectangle.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5ba98ab2b75f0c1f8fdffb9eab0a742645b80ef4ca404c007f374a5e0fd48d8c +size 10254 diff --git a/openpilot/selfdrive/assets/icons_mici/setup/small_slider/slider_green_rounded_rectangle_pressed.png b/openpilot/selfdrive/assets/icons_mici/setup/small_slider/slider_green_rounded_rectangle_pressed.png new file mode 100644 index 0000000000..999cdafcc7 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/setup/small_slider/slider_green_rounded_rectangle_pressed.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4545fdbaf67402b28b18644a7353a0620250ece6416c1b0ce0e27c758817b042 +size 26729 diff --git a/openpilot/selfdrive/assets/icons_mici/setup/start_button.png b/openpilot/selfdrive/assets/icons_mici/setup/start_button.png new file mode 100644 index 0000000000..58d8a8b748 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/setup/start_button.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5e993247160edcbc9c3cba3efa93169028568d484bcfd0bf64f3e3a7ec7556c0 +size 18608 diff --git a/openpilot/selfdrive/assets/icons_mici/setup/start_button_pressed.png b/openpilot/selfdrive/assets/icons_mici/setup/start_button_pressed.png new file mode 100644 index 0000000000..564de0bef7 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/setup/start_button_pressed.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1c4f1002ecde9a2b33779c2e784a39b492b4c8d76abc063e935ce0aa971925dd +size 65513 diff --git a/openpilot/selfdrive/assets/icons_mici/setup/warning.png b/openpilot/selfdrive/assets/icons_mici/setup/warning.png new file mode 100644 index 0000000000..1b7839f47f --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/setup/warning.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7584d32ac0231381e38646fdac2f71b4517905ef22024f01bd9e124d3918f33a +size 9194 diff --git a/openpilot/selfdrive/assets/icons_mici/ssh_short.png b/openpilot/selfdrive/assets/icons_mici/ssh_short.png new file mode 100644 index 0000000000..699ddd72e8 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/ssh_short.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ef1735e6effcb625ea618fa35a6b908b28ca483d5997e15241d48e2d3d29819e +size 1433 diff --git a/openpilot/selfdrive/assets/icons_mici/turn_intent_left.png b/openpilot/selfdrive/assets/icons_mici/turn_intent_left.png new file mode 100644 index 0000000000..3934200c9d --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/turn_intent_left.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:001cb8227eaaff5367055395d9b3ccd5822f9a47276091832d8ad28b074d77c9 +size 914 diff --git a/openpilot/selfdrive/assets/icons_mici/wheel.png b/openpilot/selfdrive/assets/icons_mici/wheel.png new file mode 100644 index 0000000000..a43bcb3b99 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/wheel.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8cf9c6361ed82551eb99e028e0a75ff56b72ca856ccf7c9a76afe6745434980a +size 2720 diff --git a/openpilot/selfdrive/assets/icons_mici/wheel_critical.png b/openpilot/selfdrive/assets/icons_mici/wheel_critical.png new file mode 100644 index 0000000000..676b0b4d71 --- /dev/null +++ b/openpilot/selfdrive/assets/icons_mici/wheel_critical.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4c3d9082b295f9e5ddef93f8d4e9cb961ea2374c7affd26394bbccb26e7137b2 +size 11023 diff --git a/selfdrive/assets/images/button_continue_triangle.png b/openpilot/selfdrive/assets/images/button_continue_triangle.png similarity index 100% rename from selfdrive/assets/images/button_continue_triangle.png rename to openpilot/selfdrive/assets/images/button_continue_triangle.png diff --git a/selfdrive/assets/images/button_continue_triangle.svg b/openpilot/selfdrive/assets/images/button_continue_triangle.svg similarity index 100% rename from selfdrive/assets/images/button_continue_triangle.svg rename to openpilot/selfdrive/assets/images/button_continue_triangle.svg diff --git a/selfdrive/assets/images/button_flag.png b/openpilot/selfdrive/assets/images/button_flag.png similarity index 100% rename from selfdrive/assets/images/button_flag.png rename to openpilot/selfdrive/assets/images/button_flag.png diff --git a/selfdrive/assets/images/button_home.png b/openpilot/selfdrive/assets/images/button_home.png similarity index 100% rename from selfdrive/assets/images/button_home.png rename to openpilot/selfdrive/assets/images/button_home.png diff --git a/selfdrive/assets/images/button_settings.png b/openpilot/selfdrive/assets/images/button_settings.png similarity index 100% rename from selfdrive/assets/images/button_settings.png rename to openpilot/selfdrive/assets/images/button_settings.png diff --git a/selfdrive/assets/images/spinner_comma.png b/openpilot/selfdrive/assets/images/spinner_comma.png similarity index 100% rename from selfdrive/assets/images/spinner_comma.png rename to openpilot/selfdrive/assets/images/spinner_comma.png diff --git a/selfdrive/assets/images/spinner_track.png b/openpilot/selfdrive/assets/images/spinner_track.png similarity index 100% rename from selfdrive/assets/images/spinner_track.png rename to openpilot/selfdrive/assets/images/spinner_track.png diff --git a/selfdrive/assets/offroad/fcc.html b/openpilot/selfdrive/assets/offroad/fcc.html similarity index 100% rename from selfdrive/assets/offroad/fcc.html rename to openpilot/selfdrive/assets/offroad/fcc.html diff --git a/openpilot/selfdrive/assets/offroad/mici_fcc.html b/openpilot/selfdrive/assets/offroad/mici_fcc.html new file mode 100644 index 0000000000..e6e4189128 --- /dev/null +++ b/openpilot/selfdrive/assets/offroad/mici_fcc.html @@ -0,0 +1,16 @@ +

HVIN: comma four

+

FCC ID: 2BFC6-MICI

+

IC: 32232-MICI

+

Contains FCC ID: XMR2023EG916QGL

+

Contains IC: 10224A-023EG916QGL

+

+This device contains licence-exempt transmitter(s)/receiver(s) that comply with Innovation, Science and Economic Development +Canada's licence-exempt RSS(s) and complies with part 15 of the FCC Rules. Operation is subject to the following two conditions:
+1. This device may not cause harmful interference.
+2. This device must accept any interference received, including interference that may cause undesired operation of the device.
+

+L'émetteur/récepteur exempt de licence contenu dans le présent appareil est conforme aux CNR d'Innovation, Sciences +et Développement économique Canada applicables aux appareils radio exempts de licence. L'exploitation est autorisée +aux deux conditions suivantes :
+1. L'appareil ne doit pas produire de brouillage.
+2. L'appareil doit accepter tout brouillage radioélectrique subi, même si le brouillage est susceptible d'en compromettre
diff --git a/selfdrive/assets/prep-svg.sh b/openpilot/selfdrive/assets/prep-svg.sh similarity index 92% rename from selfdrive/assets/prep-svg.sh rename to openpilot/selfdrive/assets/prep-svg.sh index 2332cd25c5..567c17da32 100755 --- a/selfdrive/assets/prep-svg.sh +++ b/openpilot/selfdrive/assets/prep-svg.sh @@ -3,7 +3,7 @@ set -e DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )" ICONS_DIR="$DIR/icons" -BOOTSTRAP_SVG="$DIR/../../third_party/bootstrap/bootstrap-icons.svg" +BOOTSTRAP_SVG="$(python3 -c 'import bootstrap_icons; print(bootstrap_icons.SVG_PATH)')" ICON_IDS=( arrow-right diff --git a/openpilot/selfdrive/assets/sounds/complete.wav b/openpilot/selfdrive/assets/sounds/complete.wav new file mode 100644 index 0000000000..f85d48f315 --- /dev/null +++ b/openpilot/selfdrive/assets/sounds/complete.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3027da9834adf9c71177bc3086f8de3018ce22e4725b694d635723c5b3c860cd +size 97120 diff --git a/openpilot/selfdrive/assets/sounds/critical.wav b/openpilot/selfdrive/assets/sounds/critical.wav new file mode 100644 index 0000000000..f36aa1bacd --- /dev/null +++ b/openpilot/selfdrive/assets/sounds/critical.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ca29ff46fbd6d00cc02596de8c9abfbf1cacdc6a7b2f98b27a74d24c790da004 +size 52374 diff --git a/openpilot/selfdrive/assets/sounds/disengage.wav b/openpilot/selfdrive/assets/sounds/disengage.wav new file mode 100644 index 0000000000..7db1d31911 --- /dev/null +++ b/openpilot/selfdrive/assets/sounds/disengage.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6f47633b5082b911e79dd13fc2d1f4c2a9d44d2fe0860f3d390ffc4e3d772f7d +size 97120 diff --git a/selfdrive/assets/sounds/disengage.wav b/openpilot/selfdrive/assets/sounds/disengage_tizi.wav similarity index 100% rename from selfdrive/assets/sounds/disengage.wav rename to openpilot/selfdrive/assets/sounds/disengage_tizi.wav diff --git a/openpilot/selfdrive/assets/sounds/dm_critical.wav b/openpilot/selfdrive/assets/sounds/dm_critical.wav new file mode 100644 index 0000000000..9a4171444f --- /dev/null +++ b/openpilot/selfdrive/assets/sounds/dm_critical.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:538271820d618046009bb456e930598f2736dd1a6174c11925ec3912581b05c1 +size 52374 diff --git a/openpilot/selfdrive/assets/sounds/dm_warning.wav b/openpilot/selfdrive/assets/sounds/dm_warning.wav new file mode 100644 index 0000000000..52124b0801 --- /dev/null +++ b/openpilot/selfdrive/assets/sounds/dm_warning.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:634fad6590295ef2e73d5f7e5aecbb5dd245a0f7692f1e300c2ebac95aabb8e3 +size 73026 diff --git a/openpilot/selfdrive/assets/sounds/engage.wav b/openpilot/selfdrive/assets/sounds/engage.wav new file mode 100644 index 0000000000..a984e2f3da --- /dev/null +++ b/openpilot/selfdrive/assets/sounds/engage.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a380fe0a022856b302841a0dd19b71eab318c6b08ec851f128942758a7f1631a +size 97120 diff --git a/selfdrive/assets/sounds/engage.wav b/openpilot/selfdrive/assets/sounds/engage_tizi.wav similarity index 100% rename from selfdrive/assets/sounds/engage.wav rename to openpilot/selfdrive/assets/sounds/engage_tizi.wav diff --git a/openpilot/selfdrive/assets/sounds/make_beeps.py b/openpilot/selfdrive/assets/sounds/make_beeps.py new file mode 100644 index 0000000000..6161e80e74 --- /dev/null +++ b/openpilot/selfdrive/assets/sounds/make_beeps.py @@ -0,0 +1,19 @@ +import numpy as np +from scipy.io import wavfile + + +sr = 48000 +max_int16 = 2**15 - 1 + +def harmonic_beep(freq, duration_seconds): + n_total = int(sr * duration_seconds) + + signal = np.sin(2 * np.pi * freq * np.arange(n_total) / sr) + x = np.arange(n_total) + exp_scale = np.exp(-x/5.5e3) + return max_int16 * signal * exp_scale + +engage_beep = harmonic_beep(1661.219, 0.5) +wavfile.write("engage.wav", sr, engage_beep.astype(np.int16)) +disengage_beep = harmonic_beep(1318.51, 0.5) +wavfile.write("disengage.wav", sr, disengage_beep.astype(np.int16)) diff --git a/openpilot/selfdrive/assets/sounds/pre_alert.wav b/openpilot/selfdrive/assets/sounds/pre_alert.wav new file mode 100644 index 0000000000..d8240a1717 --- /dev/null +++ b/openpilot/selfdrive/assets/sounds/pre_alert.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cc9e67cfaba77e8e4f4049f0add9238660e4cf8f886c6915600d8f47a30c98db +size 97120 diff --git a/openpilot/selfdrive/assets/sounds/prompt_single_high.wav b/openpilot/selfdrive/assets/sounds/prompt_single_high.wav new file mode 100644 index 0000000000..202483d17f --- /dev/null +++ b/openpilot/selfdrive/assets/sounds/prompt_single_high.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dbfa5858c0a672411ffdc691efdecb06d01ae458cc1df409bcf3fdeaa4756f72 +size 34638 diff --git a/openpilot/selfdrive/assets/sounds/prompt_single_low.wav b/openpilot/selfdrive/assets/sounds/prompt_single_low.wav new file mode 100644 index 0000000000..925401ea27 --- /dev/null +++ b/openpilot/selfdrive/assets/sounds/prompt_single_low.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:db9671bb03e01f119bba1eb6cc0507e0f039ac4e5b7f9f839a87071c52e86e56 +size 44416 diff --git a/openpilot/selfdrive/assets/sounds/refuse.wav b/openpilot/selfdrive/assets/sounds/refuse.wav new file mode 100644 index 0000000000..10026d7be9 --- /dev/null +++ b/openpilot/selfdrive/assets/sounds/refuse.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:081d64ca28a84a59ff5e6aea4732865b8687585938b8a287bc7e6a49d0646508 +size 97120 diff --git a/openpilot/selfdrive/assets/sounds/warning.wav b/openpilot/selfdrive/assets/sounds/warning.wav new file mode 100644 index 0000000000..bb71a0176a --- /dev/null +++ b/openpilot/selfdrive/assets/sounds/warning.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1bb440f424c989c06e203bfba0b32d39aede8f6c78a9b335e5e778460202b601 +size 73026 diff --git a/selfdrive/assets/training/step0.png b/openpilot/selfdrive/assets/training/step0.png similarity index 100% rename from selfdrive/assets/training/step0.png rename to openpilot/selfdrive/assets/training/step0.png diff --git a/selfdrive/assets/training/step1.png b/openpilot/selfdrive/assets/training/step1.png similarity index 100% rename from selfdrive/assets/training/step1.png rename to openpilot/selfdrive/assets/training/step1.png diff --git a/selfdrive/assets/training/step10.png b/openpilot/selfdrive/assets/training/step10.png similarity index 100% rename from selfdrive/assets/training/step10.png rename to openpilot/selfdrive/assets/training/step10.png diff --git a/selfdrive/assets/training/step11.png b/openpilot/selfdrive/assets/training/step11.png similarity index 100% rename from selfdrive/assets/training/step11.png rename to openpilot/selfdrive/assets/training/step11.png diff --git a/selfdrive/assets/training/step12.png b/openpilot/selfdrive/assets/training/step12.png similarity index 100% rename from selfdrive/assets/training/step12.png rename to openpilot/selfdrive/assets/training/step12.png diff --git a/selfdrive/assets/training/step13.png b/openpilot/selfdrive/assets/training/step13.png similarity index 100% rename from selfdrive/assets/training/step13.png rename to openpilot/selfdrive/assets/training/step13.png diff --git a/selfdrive/assets/training/step14.png b/openpilot/selfdrive/assets/training/step14.png similarity index 100% rename from selfdrive/assets/training/step14.png rename to openpilot/selfdrive/assets/training/step14.png diff --git a/selfdrive/assets/training/step15.png b/openpilot/selfdrive/assets/training/step15.png similarity index 100% rename from selfdrive/assets/training/step15.png rename to openpilot/selfdrive/assets/training/step15.png diff --git a/selfdrive/assets/training/step16.png b/openpilot/selfdrive/assets/training/step16.png similarity index 100% rename from selfdrive/assets/training/step16.png rename to openpilot/selfdrive/assets/training/step16.png diff --git a/selfdrive/assets/training/step17.png b/openpilot/selfdrive/assets/training/step17.png similarity index 100% rename from selfdrive/assets/training/step17.png rename to openpilot/selfdrive/assets/training/step17.png diff --git a/selfdrive/assets/training/step18.png b/openpilot/selfdrive/assets/training/step18.png similarity index 100% rename from selfdrive/assets/training/step18.png rename to openpilot/selfdrive/assets/training/step18.png diff --git a/selfdrive/assets/training/step2.png b/openpilot/selfdrive/assets/training/step2.png similarity index 100% rename from selfdrive/assets/training/step2.png rename to openpilot/selfdrive/assets/training/step2.png diff --git a/selfdrive/assets/training/step3.png b/openpilot/selfdrive/assets/training/step3.png similarity index 100% rename from selfdrive/assets/training/step3.png rename to openpilot/selfdrive/assets/training/step3.png diff --git a/selfdrive/assets/training/step4.png b/openpilot/selfdrive/assets/training/step4.png similarity index 100% rename from selfdrive/assets/training/step4.png rename to openpilot/selfdrive/assets/training/step4.png diff --git a/selfdrive/assets/training/step5.png b/openpilot/selfdrive/assets/training/step5.png similarity index 100% rename from selfdrive/assets/training/step5.png rename to openpilot/selfdrive/assets/training/step5.png diff --git a/selfdrive/assets/training/step6.png b/openpilot/selfdrive/assets/training/step6.png similarity index 100% rename from selfdrive/assets/training/step6.png rename to openpilot/selfdrive/assets/training/step6.png diff --git a/selfdrive/assets/training/step7.png b/openpilot/selfdrive/assets/training/step7.png similarity index 100% rename from selfdrive/assets/training/step7.png rename to openpilot/selfdrive/assets/training/step7.png diff --git a/selfdrive/assets/training/step8.png b/openpilot/selfdrive/assets/training/step8.png similarity index 100% rename from selfdrive/assets/training/step8.png rename to openpilot/selfdrive/assets/training/step8.png diff --git a/selfdrive/assets/training/step9.png b/openpilot/selfdrive/assets/training/step9.png similarity index 100% rename from selfdrive/assets/training/step9.png rename to openpilot/selfdrive/assets/training/step9.png diff --git a/selfdrive/car/CARS_template.md b/openpilot/selfdrive/car/CARS_template.md similarity index 95% rename from selfdrive/car/CARS_template.md rename to openpilot/selfdrive/car/CARS_template.md index 463683fd3c..35804ff1fa 100644 --- a/selfdrive/car/CARS_template.md +++ b/openpilot/selfdrive/car/CARS_template.md @@ -1,12 +1,12 @@ {% set footnote_tag = '[{}](#footnotes)' %} {% set star_icon = '[![star](assets/icon-star-{}.svg)](##)' %} -{% set video_icon = '' %} +{% set video_icon = '' %} {# Force hardware column wider by using a blank image with max width. #} {% set width_tag = '%s
 ' %} {% set hardware_col_name = 'Hardware Needed' %} {% set wide_hardware_col_name = width_tag|format(hardware_col_name) -%} - + # Supported Cars @@ -42,7 +42,7 @@ If your car has the following packages or features, then it's a good candidate f | Make | Required Package/Features | | ---- | ------------------------- | -| Acura | Any car with AcuraWatch Plus will work. AcuraWatch Plus comes standard on many newer models. | +| Acura | Any car with AcuraWatch will work. AcuraWatch comes standard on many newer models. | | Ford | Any car with Lane Centering will likely work. | | Honda | Any car with Honda Sensing will work. Honda Sensing comes standard on many newer models. | | Subaru | Any car with EyeSight will work. EyeSight comes standard on many newer models. | diff --git a/selfdrive/car/tests/__init__.py b/openpilot/selfdrive/car/__init__.py similarity index 100% rename from selfdrive/car/tests/__init__.py rename to openpilot/selfdrive/car/__init__.py diff --git a/openpilot/selfdrive/car/car_specific.py b/openpilot/selfdrive/car/car_specific.py new file mode 100644 index 0000000000..244a8e3b07 --- /dev/null +++ b/openpilot/selfdrive/car/car_specific.py @@ -0,0 +1,188 @@ +from openpilot.cereal import log +from opendbc.car.structs import car +from opendbc.car import DT_CTRL, structs +from opendbc.car.car_helpers import interfaces +from opendbc.car.interfaces import MAX_CTRL_SPEED +from opendbc.car.toyota.values import ToyotaFlags + +from openpilot.selfdrive.selfdrived.events import Events + +ButtonType = structs.CarState.ButtonEvent.Type +GearShifter = structs.CarState.GearShifter +EventName = log.OnroadEvent.EventName +NetworkLocation = structs.CarParams.NetworkLocation + + +class CarSpecificEvents: + def __init__(self, CP: structs.CarParams): + self.CP = CP + + self.steering_unpressed = 0 + self.low_speed_alert = False + self.no_steer_warning = False + self.silent_steer_warning = True + + def update(self, CS: car.CarState, CS_prev: car.CarState, CC: car.CarControl): + if self.CP.brand in ('body', 'mock'): + return Events() + + events = self.create_common_events(CS, CS_prev) + + if self.CP.brand == 'chrysler': + # Low speed steer alert hysteresis logic + if self.CP.minSteerSpeed > 0. and CS.vEgo < (self.CP.minSteerSpeed + 0.5): + self.low_speed_alert = True + elif CS.vEgo > (self.CP.minSteerSpeed + 1.): + self.low_speed_alert = False + if self.low_speed_alert: + events.add(EventName.belowSteerSpeed) + + elif self.CP.brand == 'honda': + if self.CP.pcmCruise and CS.vEgo < self.CP.minEnableSpeed: + events.add(EventName.belowEngageSpeed) + + if self.CP.pcmCruise: + # we engage when pcm is active (rising edge) + if CS.cruiseState.enabled and not CS_prev.cruiseState.enabled: + events.add(EventName.pcmEnable) + elif not CS.cruiseState.enabled and (CC.actuators.accel >= 0. or not self.CP.openpilotLongitudinalControl): + # it can happen that car cruise disables while comma system is enabled: need to + # keep braking if needed or if the speed is very low + if CS.vEgo < self.CP.minEnableSpeed + 2.: + # non loud alert if cruise disables below 25mph as expected (+ a little margin) + events.add(EventName.speedTooLow) + else: + events.add(EventName.cruiseDisabled) + if self.CP.minEnableSpeed > 0 and CS.vEgo < 0.001: + events.add(EventName.manualRestart) + + elif self.CP.brand == 'toyota': + # TODO: when we check for unexpected disengagement, check gear not S1, S2, S3 + if self.CP.openpilotLongitudinalControl: + # Only can leave standstill when planner wants to move + if CS.cruiseState.standstill and not CS.brakePressed and (CC.cruiseControl.resume or self.CP.flags & ToyotaFlags.HYBRID.value): + events.add(EventName.resumeRequired) + if CS.vEgo < self.CP.minEnableSpeed: + events.add(EventName.belowEngageSpeed) + if CC.actuators.accel > 0.3: + # some margin on the actuator to not false trigger cancellation while stopping + events.add(EventName.speedTooLow) + if CS.vEgo < 0.001: + # while in standstill, send a user alert + events.add(EventName.manualRestart) + + elif self.CP.brand == 'gm': + # Enabling at a standstill with brake is allowed + # TODO: verify 17 Volt can enable for the first time at a stop and allow for all GMs + if CS.vEgo < self.CP.minEnableSpeed and not (CS.standstill and CS.brakePressed and + self.CP.networkLocation == NetworkLocation.fwdCamera): + events.add(EventName.belowEngageSpeed) + if CS.cruiseState.standstill: + events.add(EventName.resumeRequired) + + elif self.CP.brand == 'volkswagen': + if self.CP.openpilotLongitudinalControl: + if CS.vEgo < self.CP.minEnableSpeed + 0.5: + events.add(EventName.belowEngageSpeed) + if CC.enabled and CS.vEgo < self.CP.minEnableSpeed: + events.add(EventName.speedTooLow) + + # TODO: this needs to be implemented generically in carState struct + # if CC.eps_timer_soft_disable_alert: + # events.add(EventName.steerTimeLimit) + + return events + + def create_common_events(self, CS: structs.CarState, CS_prev: car.CarState): + events = Events() + + CI = interfaces[self.CP.carFingerprint] + # TODO: cleanup the honda-specific logic + pcm_enable = self.CP.pcmCruise and self.CP.brand != 'honda' + # TODO: on some hyundai cars, the cancel button is also the pause/resume button, + # so only use it for cancel when running openpilot longitudinal + allow_button_cancel = self.CP.brand != 'hyundai' + + if CS.doorOpen: + events.add(EventName.doorOpen) + if CS.seatbeltUnlatched: + events.add(EventName.seatbeltNotLatched) + if CS.gearShifter != GearShifter.drive and CS.gearShifter not in CI.DRIVABLE_GEARS: + events.add(EventName.wrongGear) + if CS.gearShifter == GearShifter.reverse: + events.add(EventName.reverseGear) + if not CS.cruiseState.available: + events.add(EventName.wrongCarMode) + if CS.espDisabled: + events.add(EventName.espDisabled) + if CS.espActive: + events.add(EventName.espActive) + if CS.stockFcw: + events.add(EventName.stockFcw) + if CS.stockAeb: + events.add(EventName.stockAeb) + if CS.stockLkas: + events.add(EventName.stockLkas) + if CS.vEgo > MAX_CTRL_SPEED: + events.add(EventName.speedTooHigh) + if CS.cruiseState.nonAdaptive: + events.add(EventName.wrongCruiseMode) + if CS.brakeHoldActive and self.CP.openpilotLongitudinalControl: + events.add(EventName.brakeHold) + if CS.parkingBrake: + events.add(EventName.parkBrake) + if CS.accFaulted: + events.add(EventName.accFaulted) + if CS.steeringPressed: + events.add(EventName.steerOverride) + if CS.steeringDisengage and not CS_prev.steeringDisengage: + events.add(EventName.steerDisengage) + if CS.brakePressed and CS.standstill: + events.add(EventName.preEnableStandstill) + if CS.gasPressed: + events.add(EventName.gasPressedOverride) + if CS.vehicleSensorsInvalid: + events.add(EventName.vehicleSensorsInvalid) + if CS.invalidLkasSetting: + events.add(EventName.invalidLkasSetting) + if CS.lowSpeedAlert: + events.add(EventName.belowSteerSpeed) + if CS.buttonEnable: + events.add(EventName.buttonEnable) + + # Handle cancel button presses + for b in CS.buttonEvents: + # Disable on rising and falling edge of cancel for both stock and OP long + # TODO: only check the cancel button with openpilot longitudinal on all brands to match panda safety + if b.type == ButtonType.cancel and (allow_button_cancel or not self.CP.pcmCruise): + events.add(EventName.buttonCancel) + + # Handle permanent and temporary steering faults + self.steering_unpressed = 0 if CS.steeringPressed else self.steering_unpressed + 1 + if CS.steerFaultTemporary: + if CS.steeringPressed and (not CS_prev.steerFaultTemporary or self.no_steer_warning): + self.no_steer_warning = True + else: + self.no_steer_warning = False + + # if the user overrode recently, show a less harsh alert + if self.silent_steer_warning or CS.standstill or self.steering_unpressed < int(1.5 / DT_CTRL): + self.silent_steer_warning = True + events.add(EventName.steerTempUnavailableSilent) + else: + events.add(EventName.steerTempUnavailable) + else: + self.no_steer_warning = False + self.silent_steer_warning = False + if CS.steerFaultPermanent: + events.add(EventName.steerUnavailable) + + # we engage when pcm is active (rising edge) + # enabling can optionally be blocked by the car interface + if pcm_enable: + if CS.cruiseState.enabled and not CS_prev.cruiseState.enabled and not CS.blockPcmEnable: + events.add(EventName.pcmEnable) + elif not CS.cruiseState.enabled: + events.add(EventName.pcmDisable) + + return events diff --git a/selfdrive/car/card.py b/openpilot/selfdrive/car/card.py similarity index 88% rename from selfdrive/car/card.py rename to openpilot/selfdrive/car/card.py index 8448af56db..d9b7b4bb5a 100755 --- a/selfdrive/car/card.py +++ b/openpilot/selfdrive/car/card.py @@ -1,12 +1,12 @@ #!/usr/bin/env python3 -import json import os import time import threading -import cereal.messaging as messaging +import openpilot.cereal.messaging as messaging -from cereal import car, log, custom +from openpilot.cereal import log, custom +from opendbc.car.structs import car from openpilot.common.params import Params from openpilot.common.realtime import config_realtime_process, Priority, Ratekeeper @@ -20,7 +20,6 @@ from opendbc.car.car_helpers import get_car, interfaces from opendbc.car.interfaces import CarInterfaceBase, RadarInterfaceBase from openpilot.selfdrive.pandad import can_capnp_to_list, can_list_to_can_capnp from openpilot.selfdrive.car.cruise import VCruiseHelper -from openpilot.selfdrive.car.car_specific import MockCarState from openpilot.selfdrive.car.helpers import convert_carControlSP, convert_to_capnp from openpilot.sunnypilot.mads.helpers import set_alternative_experience, set_car_specific_params @@ -39,7 +38,7 @@ def obd_callback(params: Params) -> ObdCallback: if params.get_bool("ObdMultiplexingEnabled") != obd_multiplexing: cloudlog.warning(f"Setting OBD multiplexing to {obd_multiplexing}") params.remove("ObdMultiplexingChanged") - params.put_bool("ObdMultiplexingEnabled", obd_multiplexing) + params.put_bool("ObdMultiplexingEnabled", obd_multiplexing, block=True) params.get_bool("ObdMultiplexingChanged", block=True) cloudlog.warning("OBD multiplexing set successfully") return set_obd_multiplexing @@ -72,7 +71,7 @@ class Car: def __init__(self, CI=None, RI=None) -> None: self.can_sock = messaging.sub_sock('can', timeout=20) - self.sm = messaging.SubMaster(['pandaStates', 'carControl', 'onroadEvents'] + ['carControlSP']) + self.sm = messaging.SubMaster(['pandaStates', 'carControl', 'onroadEvents'] + ['carControlSP', 'longitudinalPlanSP']) self.pm = messaging.PubMaster(['sendcan', 'carState', 'carParams', 'carOutput', 'liveTracks'] + ['carParamsSP', 'carStateSP']) self.can_rcv_cum_timeout_counter = 0 @@ -88,7 +87,8 @@ class Car: self.can_callbacks = can_comm_callbacks(self.can_sock, self.pm.sock['sendcan']) - is_release = self.params.get_bool("IsReleaseBranch") + is_release = False # self.params.get_bool("IsReleaseBranch") + is_release_sp = self.params.get_bool("IsReleaseSpBranch") if CI is None: # wait for one pandaState and one CAN packet @@ -99,7 +99,6 @@ class Car: break alpha_long_allowed = self.params.get_bool("AlphaLongitudinalEnabled") - num_pandas = len(messaging.recv_one_retry(self.sm.sock['pandaStates']).pandaStates) cached_params = None cached_params_raw = self.params.get("CarParamsCache") @@ -107,23 +106,25 @@ class Car: with car.CarParams.from_bytes(cached_params_raw) as _cached_params: cached_params = _cached_params - fixed_fingerprint = json.loads(self.params.get("CarPlatformBundle", encoding='utf-8') or "{}").get("platform", None) + fixed_fingerprint = (self.params.get("CarPlatformBundle") or {}).get("platform", None) + init_params_list_sp = sunnypilot_interfaces.initialize_params(self.params) - self.CI = get_car(*self.can_callbacks, obd_callback(self.params), alpha_long_allowed, is_release, num_pandas, cached_params, fixed_fingerprint) + self.CI = get_car(*self.can_callbacks, obd_callback(self.params), alpha_long_allowed, is_release, cached_params, + fixed_fingerprint, init_params_list_sp, is_release_sp) sunnypilot_interfaces.setup_interfaces(self.CI, self.params) self.RI = interfaces[self.CI.CP.carFingerprint].RadarInterface(self.CI.CP, self.CI.CP_SP) self.CP = self.CI.CP self.CP_SP = self.CI.CP_SP # continue onto next fingerprinting step in pandad - self.params.put_bool("FirmwareQueryDone", True) + self.params.put_bool("FirmwareQueryDone", True, block=True) else: self.CI, self.CP, self.CP_SP = CI, CI.CP, CI.CP_SP self.RI = RI self.CP.alternativeExperience = 0 # mads - set_alternative_experience(self.CP, self.params) + set_alternative_experience(self.CP, self.CP_SP, self.params) set_car_specific_params(self.CP, self.CP_SP, self.params) # Dynamic Experimental Control @@ -137,17 +138,17 @@ class Car: safety_config.safetyModel = structs.CarParams.SafetyModel.noOutput self.CP.safetyConfigs = [safety_config] - if self.CP.secOcRequired and not is_release: + if self.CP.secOcRequired: # Copy user key if available try: with open("/cache/params/SecOCKey") as f: user_key = f.readline().strip() if len(user_key) == 32: - self.params.put("SecOCKey", user_key) + self.params.put("SecOCKey", user_key, block=True) except Exception: pass - secoc_key = self.params.get("SecOCKey", encoding='utf8') + secoc_key = self.params.get("SecOCKey") if secoc_key is not None: saved_secoc_key = bytes.fromhex(secoc_key.strip()) if len(saved_secoc_key) == 16: @@ -161,24 +162,23 @@ class Car: # Write previous route's CarParams prev_cp = self.params.get("CarParamsPersistent") if prev_cp is not None: - self.params.put("CarParamsPrevRoute", prev_cp) + self.params.put("CarParamsPrevRoute", prev_cp, block=True) # Write CarParams for controls and radard cp_bytes = self.CP.to_bytes() - self.params.put("CarParams", cp_bytes) - self.params.put_nonblocking("CarParamsCache", cp_bytes) - self.params.put_nonblocking("CarParamsPersistent", cp_bytes) + self.params.put("CarParams", cp_bytes, block=True) + self.params.put("CarParamsCache", cp_bytes) + self.params.put("CarParamsPersistent", cp_bytes) # Write CarParamsSP for controls # convert to pycapnp representation for caching and logging self.CP_SP_capnp = convert_to_capnp(self.CP_SP) cp_sp_bytes = self.CP_SP_capnp.to_bytes() - self.params.put("CarParamsSP", cp_sp_bytes) - self.params.put_nonblocking("CarParamsSPCache", cp_sp_bytes) - self.params.put_nonblocking("CarParamsSPPersistent", cp_sp_bytes) + self.params.put("CarParamsSP", cp_sp_bytes, block=True) + self.params.put("CarParamsSPCache", cp_sp_bytes) + self.params.put("CarParamsSPPersistent", cp_sp_bytes) - self.mock_carstate = MockCarState() - self.v_cruise_helper = VCruiseHelper(self.CP) + self.v_cruise_helper = VCruiseHelper(self.CP, self.CP_SP) self.is_metric = self.params.get_bool("IsMetric") self.experimental_mode = self.params.get_bool("ExperimentalMode") @@ -198,8 +198,6 @@ class Car: # Update carState from CAN CS, CS_SP = self.CI.update(can_list) CS_SP = convert_to_capnp(CS_SP) - if self.CP.brand == 'mock': - CS, CS_SP = self.mock_carstate.update(CS, CS_SP) # Update radar tracks from CAN RD: structs.RadarDataT | None = self.RI.update(can_list) @@ -215,6 +213,7 @@ class Car: if can_rcv_valid and REPLAY: self.can_log_mono_time = messaging.log_from_bytes(can_strs[0]).logMonoTime + self.v_cruise_helper.update_speed_limit_assist(self.is_metric, self.sm['longitudinalPlanSP']) self.v_cruise_helper.update_v_cruise(CS, self.sm['carControl'].enabled, self.is_metric) if self.sm['carControl'].enabled and not self.CC_prev.enabled: # Use CarState w/ buttons from the step selfdrived enables on @@ -276,7 +275,7 @@ class Car: # TODO: this can make us miss at least a few cycles when doing an ECU knockout self.CI.init(self.CP, self.CP_SP, *self.can_callbacks) # signal pandad to switch to car safety mode - self.params.put_bool_nonblocking("ControlsReady", True) + self.params.put_bool("ControlsReady", True) if self.sm.all_alive(['carControl']): # send car controls over can diff --git a/openpilot/selfdrive/car/cruise.py b/openpilot/selfdrive/car/cruise.py new file mode 100644 index 0000000000..b554c1a978 --- /dev/null +++ b/openpilot/selfdrive/car/cruise.py @@ -0,0 +1,154 @@ +import math +import numpy as np + +from opendbc.car.structs import car +from openpilot.common.constants import CV +from openpilot.sunnypilot.selfdrive.car.cruise_ext import VCruiseHelperSP + + +# WARNING: this value was determined based on the model's training distribution, +# model predictions above this speed can be unpredictable +# V_CRUISE's are in kph +V_CRUISE_MIN = 8 +V_CRUISE_MAX = 145 +V_CRUISE_UNSET = 255 +V_CRUISE_INITIAL = 40 +V_CRUISE_INITIAL_EXPERIMENTAL_MODE = 105 +IMPERIAL_INCREMENT = round(CV.MPH_TO_KPH, 1) # round here to avoid rounding errors incrementing set speed + +ButtonEvent = car.CarState.ButtonEvent +ButtonType = car.CarState.ButtonEvent.Type +CRUISE_LONG_PRESS = 50 +CRUISE_NEAREST_FUNC = { + ButtonType.accelCruise: math.ceil, + ButtonType.decelCruise: math.floor, +} +CRUISE_INTERVAL_SIGN = { + ButtonType.accelCruise: +1, + ButtonType.decelCruise: -1, +} + + +class VCruiseHelper(VCruiseHelperSP): + def __init__(self, CP, CP_SP): + VCruiseHelperSP.__init__(self, CP, CP_SP) + self.CP = CP + self.v_cruise_kph = V_CRUISE_UNSET + self.v_cruise_cluster_kph = V_CRUISE_UNSET + self.v_cruise_kph_last = 0 + self.button_timers = {ButtonType.decelCruise: 0, ButtonType.accelCruise: 0} + self.button_change_states = {btn: {"standstill": False, "enabled": False} for btn in self.button_timers} + + @property + def v_cruise_initialized(self): + return self.v_cruise_kph != V_CRUISE_UNSET + + def update_v_cruise(self, CS, enabled, is_metric): + self.v_cruise_kph_last = self.v_cruise_kph + + self.get_minimum_set_speed(is_metric) + + _enabled = self.update_enabled_state(CS, enabled) + + if CS.cruiseState.available: + if not self.CP.pcmCruise or (not self.CP_SP.pcmCruiseSpeed and _enabled): + # if stock cruise is completely disabled, then we can use our own set speed logic + self._update_v_cruise_non_pcm(CS, _enabled, is_metric) + self.update_speed_limit_assist_v_cruise_non_pcm() + self.v_cruise_cluster_kph = self.v_cruise_kph + else: + self.v_cruise_kph = CS.cruiseState.speed * CV.MS_TO_KPH + self.v_cruise_cluster_kph = CS.cruiseState.speedCluster * CV.MS_TO_KPH + if CS.cruiseState.speed == 0: + self.v_cruise_kph = V_CRUISE_UNSET + self.v_cruise_cluster_kph = V_CRUISE_UNSET + elif CS.cruiseState.speed == -1: + self.v_cruise_kph = -1 + self.v_cruise_cluster_kph = -1 + else: + self.v_cruise_kph = V_CRUISE_UNSET + self.v_cruise_cluster_kph = V_CRUISE_UNSET + + if not self.CP.pcmCruise or not self.CP_SP.pcmCruiseSpeed: + self.update_button_timers(CS, enabled) + + def _update_v_cruise_non_pcm(self, CS, enabled, is_metric): + # handle button presses. TODO: this should be in state_control, but a decelCruise press + # would have the effect of both enabling and changing speed is checked after the state transition + if not enabled: + return + + long_press = False + button_type = None + + v_cruise_delta = 1. if is_metric else IMPERIAL_INCREMENT + + for b in CS.buttonEvents: + if b.type.raw in self.button_timers and not b.pressed: + if self.button_timers[b.type.raw] > CRUISE_LONG_PRESS: + return # end long press + button_type = b.type.raw + break + else: + for k, timer in self.button_timers.items(): + if timer and timer % CRUISE_LONG_PRESS == 0: + button_type = k + long_press = True + break + + if button_type is None: + return + + # Don't adjust speed when pressing resume to exit standstill + cruise_standstill = self.button_change_states[button_type]["standstill"] or CS.cruiseState.standstill + if button_type == ButtonType.accelCruise and cruise_standstill: + return + + # Don't adjust speed if we've enabled since the button was depressed (some ports enable on rising edge) + if not self.button_change_states[button_type]["enabled"]: + return + + # Speed Limit Assist for Non PCM long cars. + # True: Disallow set speed changes when user confirmed the target set speed during preActive state + # False: Allow set speed changes as SLA is not requesting user confirmation + if self.update_speed_limit_assist_pre_active_confirmed(button_type): + return + + long_press, v_cruise_delta = VCruiseHelperSP.update_v_cruise_delta(self, long_press, v_cruise_delta) + if long_press and self.v_cruise_kph % v_cruise_delta != 0: # partial interval + self.v_cruise_kph = CRUISE_NEAREST_FUNC[button_type](self.v_cruise_kph / v_cruise_delta) * v_cruise_delta + else: + self.v_cruise_kph += v_cruise_delta * CRUISE_INTERVAL_SIGN[button_type] + + # If set is pressed while overriding, clip cruise speed to minimum of vEgo + if CS.gasPressed and button_type in (ButtonType.decelCruise, ButtonType.setCruise): + self.v_cruise_kph = max(self.v_cruise_kph, CS.vEgo * CV.MS_TO_KPH) + + self.v_cruise_kph = np.clip(round(self.v_cruise_kph, 1), self.v_cruise_min, V_CRUISE_MAX) + + def update_button_timers(self, CS, enabled): + # increment timer for buttons still pressed + for k in self.button_timers: + if self.button_timers[k] > 0: + self.button_timers[k] += 1 + + for b in CS.buttonEvents: + if b.type.raw in self.button_timers: + # Start/end timer and store current state on change of button pressed + self.button_timers[b.type.raw] = 1 if b.pressed else 0 + self.button_change_states[b.type.raw] = {"standstill": CS.cruiseState.standstill, "enabled": enabled} + + def initialize_v_cruise(self, CS, experimental_mode: bool, dynamic_experimental_control: bool) -> None: + # initializing is handled by the PCM + if self.CP.pcmCruise: + return + + initial_experimental_mode = experimental_mode and not dynamic_experimental_control + initial = V_CRUISE_INITIAL_EXPERIMENTAL_MODE if initial_experimental_mode else V_CRUISE_INITIAL + + if any(b.type in (ButtonType.accelCruise, ButtonType.resumeCruise) for b in CS.buttonEvents) and self.v_cruise_initialized: + self.v_cruise_kph = self.v_cruise_kph_last + else: + self.v_cruise_kph = int(round(np.clip(CS.vEgo * CV.MS_TO_KPH, initial, V_CRUISE_MAX))) + + self.v_cruise_cluster_kph = self.v_cruise_kph diff --git a/openpilot/selfdrive/car/docs.py b/openpilot/selfdrive/car/docs.py new file mode 100755 index 0000000000..ea7a70688e --- /dev/null +++ b/openpilot/selfdrive/car/docs.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python3 +import argparse +import os + +from openpilot.common.basedir import BASEDIR +from opendbc.car.docs import get_all_car_docs, generate_cars_md + +CARS_MD_OUT = os.path.join(BASEDIR, "docs", "CARS.md") +CARS_MD_TEMPLATE = os.path.join(BASEDIR, "openpilot/selfdrive", "car", "CARS_template.md") + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Auto generates supported cars documentation", + formatter_class=argparse.ArgumentDefaultsHelpFormatter) + + parser.add_argument("--template", default=CARS_MD_TEMPLATE, help="Override default template filename") + parser.add_argument("--out", default=CARS_MD_OUT, help="Override default generated filename") + args = parser.parse_args() + + with open(args.out, 'w') as f: + f.write(generate_cars_md(get_all_car_docs(), args.template)) + print(f"Generated and written to {args.out}") diff --git a/openpilot/selfdrive/car/helpers.py b/openpilot/selfdrive/car/helpers.py new file mode 100644 index 0000000000..ec9e3efeeb --- /dev/null +++ b/openpilot/selfdrive/car/helpers.py @@ -0,0 +1,67 @@ +import capnp +from typing import Any + +from openpilot.cereal import custom +from opendbc.car import structs + +_FIELDS = '__dataclass_fields__' # copy of dataclasses._FIELDS + + +def is_dataclass(obj): + """Similar to dataclasses.is_dataclass without instance type check checking""" + return hasattr(obj, _FIELDS) + + +def _asdictref_inner(obj) -> dict[str, Any] | Any: + if is_dataclass(obj): + ret = {} + for field in getattr(obj, _FIELDS): # similar to dataclasses.fields() + ret[field] = _asdictref_inner(getattr(obj, field)) + return ret + elif isinstance(obj, (tuple, list)): + return type(obj)(_asdictref_inner(v) for v in obj) + else: + return obj + + +def asdictref(obj) -> dict[str, Any]: + """ + Similar to dataclasses.asdict without recursive type checking and copy.deepcopy + Note that the resulting dict will contain references to the original struct as a result + """ + if not is_dataclass(obj): + raise TypeError("asdictref() should be called on dataclass instances") + + return _asdictref_inner(obj) + + +def convert_to_capnp(struct: structs.CarParamsSP | structs.CarStateSP) -> capnp.lib.capnp._DynamicStructBuilder: + struct_dict = asdictref(struct) + + if isinstance(struct, structs.CarParamsSP): + struct_capnp = custom.CarParamsSP.new_message(**struct_dict) + elif isinstance(struct, structs.CarStateSP): + struct_capnp = custom.CarStateSP.new_message(**struct_dict) + else: + raise ValueError(f"Unsupported struct type: {type(struct)}") + + return struct_capnp + + +def convert_carControlSP(struct: capnp.lib.capnp._DynamicStructReader) -> structs.CarControlSP: + # TODO: recursively handle any car struct as needed + def remove_deprecated(s: dict) -> dict: + return {k: v for k, v in s.items() if not k.endswith('DEPRECATED')} + + struct_dict = struct.to_dict() + struct_dataclass = structs.CarControlSP(**remove_deprecated({k: v for k, v in struct_dict.items() if not isinstance(k, dict)})) + + struct_dataclass.mads = structs.ModularAssistiveDrivingSystem(**remove_deprecated(struct_dict.get('mads', {}))) + # struct_dataclass.params = [structs.CarControlSP.Param(**remove_deprecated(p)) for p in struct_dict.get('params', [])] + struct_dataclass.leadOne = structs.LeadData(**remove_deprecated(struct_dict.get('leadOne', {}))) + struct_dataclass.leadTwo = structs.LeadData(**remove_deprecated(struct_dict.get('leadTwo', {}))) + struct_dataclass.intelligentCruiseButtonManagement = structs.IntelligentCruiseButtonManagement( + **remove_deprecated(struct_dict.get('intelligentCruiseButtonManagement', {})) + ) + + return struct_dataclass diff --git a/selfdrive/controls/__init__.py b/openpilot/selfdrive/car/tests/__init__.py similarity index 100% rename from selfdrive/controls/__init__.py rename to openpilot/selfdrive/car/tests/__init__.py diff --git a/openpilot/selfdrive/car/tests/big_cars_test.sh b/openpilot/selfdrive/car/tests/big_cars_test.sh new file mode 100755 index 0000000000..456fc698c5 --- /dev/null +++ b/openpilot/selfdrive/car/tests/big_cars_test.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash + +SCRIPT_DIR=$(dirname "$0") +BASEDIR=$(realpath "$SCRIPT_DIR/../../../../") +cd $BASEDIR + +export MAX_EXAMPLES=300 +export INTERNAL_SEG_CNT=300 +export INTERNAL_SEG_LIST=openpilot/selfdrive/car/tests/test_models_segs.txt + +cd openpilot/selfdrive/car/tests && pytest test_models.py test_car_interfaces.py diff --git a/openpilot/selfdrive/car/tests/test_car_interfaces.py b/openpilot/selfdrive/car/tests/test_car_interfaces.py new file mode 100644 index 0000000000..3c4587cbc6 --- /dev/null +++ b/openpilot/selfdrive/car/tests/test_car_interfaces.py @@ -0,0 +1,70 @@ +import os +import hypothesis.strategies as st +from hypothesis import Phase, given, settings +from openpilot.common.parameterized import parameterized + +from openpilot.cereal import custom +from opendbc.car.structs import car +from opendbc.car import DT_CTRL +from opendbc.car.structs import CarParams +from opendbc.car.tests.test_car_interfaces import get_fuzzy_car_interface +from opendbc.car.mock.values import CAR as MOCK +from opendbc.car.values import PLATFORMS +from openpilot.selfdrive.car.helpers import convert_carControlSP +from openpilot.selfdrive.controls.lib.latcontrol_angle import LatControlAngle +from openpilot.selfdrive.controls.lib.latcontrol_pid import LatControlPID +from openpilot.selfdrive.controls.lib.latcontrol_torque import LatControlTorque +from openpilot.selfdrive.controls.lib.longcontrol import LongControl +from openpilot.selfdrive.test.fuzzy_generation import FuzzyGenerator + +from openpilot.sunnypilot.selfdrive.car import interfaces as sunnypilot_interfaces + +MAX_EXAMPLES = int(os.environ.get('MAX_EXAMPLES', '60')) + + +class TestCarInterfaces: + # FIXME: Due to the lists used in carParams, Phase.target is very slow and will cause + # many generated examples to overrun when max_examples > ~20, don't use it + @parameterized.expand([(car,) for car in sorted(PLATFORMS)] + [MOCK.MOCK]) + @settings(max_examples=MAX_EXAMPLES, deadline=None, + phases=(Phase.reuse, Phase.generate, Phase.shrink)) + @given(data=st.data()) + def test_car_interfaces(self, car_name, data): + car_interface = get_fuzzy_car_interface(car_name, data.draw) + car_params = car_interface.CP.as_reader() + car_params_sp = car_interface.CP_SP + sunnypilot_interfaces.setup_interfaces(car_interface) + + cc_msg = FuzzyGenerator.get_random_msg(data.draw, car.CarControl, real_floats=True) + cc_sp_msg = FuzzyGenerator.get_random_msg(data.draw, custom.CarControlSP, real_floats=True) + # Run car interface + now_nanos = 0 + CC = car.CarControl.new_message(**cc_msg) + CC = CC.as_reader() + CC_SP = custom.CarControlSP.new_message(**cc_sp_msg) + CC_SP = convert_carControlSP(CC_SP.as_reader()) + for _ in range(10): + car_interface.update([]) + car_interface.apply(CC, CC_SP, now_nanos) + now_nanos += DT_CTRL * 1e9 # 10 ms + + CC = car.CarControl.new_message(**cc_msg) + CC.enabled = True + CC.latActive = True + CC.longActive = True + CC = CC.as_reader() + for _ in range(10): + car_interface.update([]) + car_interface.apply(CC, CC_SP, now_nanos) + now_nanos += DT_CTRL * 1e9 # 10ms + + # Test controller initialization + # TODO: wait until card refactor is merged to run controller a few times, + # hypothesis also slows down significantly with just one more message draw + LongControl(car_params, car_params_sp) + if car_params.steerControlType == CarParams.SteerControlType.angle: + LatControlAngle(car_params, car_params_sp, car_interface, DT_CTRL) + elif car_params.lateralTuning.which() == 'pid': + LatControlPID(car_params, car_params_sp, car_interface, DT_CTRL) + elif car_params.lateralTuning.which() == 'torque': + LatControlTorque(car_params, car_params_sp, car_interface, DT_CTRL) diff --git a/selfdrive/car/tests/test_cruise_speed.py b/openpilot/selfdrive/car/tests/test_cruise_speed.py similarity index 91% rename from selfdrive/car/tests/test_cruise_speed.py rename to openpilot/selfdrive/car/tests/test_cruise_speed.py index dd78b77680..c0b6ac979f 100644 --- a/selfdrive/car/tests/test_cruise_speed.py +++ b/openpilot/selfdrive/car/tests/test_cruise_speed.py @@ -2,11 +2,12 @@ import pytest import itertools import numpy as np -from parameterized import parameterized_class -from cereal import log +from openpilot.common.parameterized import parameterized_class +from openpilot.cereal import log from openpilot.selfdrive.car.cruise import VCruiseHelper, V_CRUISE_MIN, V_CRUISE_MAX, V_CRUISE_INITIAL, IMPERIAL_INCREMENT -from cereal import car -from openpilot.common.conversions import Conversions as CV +from openpilot.cereal import custom +from opendbc.car.structs import car +from openpilot.common.constants import CV from openpilot.selfdrive.test.longitudinal_maneuvers.maneuver import Maneuver ButtonEvent = car.CarState.ButtonEvent @@ -44,12 +45,13 @@ class TestCruiseSpeed: assert simulation_steady_state == pytest.approx(cruise_speed, abs=.01), f'Did not reach {self.speed} m/s' -# TODO: test pcmCruise -@parameterized_class(('pcm_cruise',), [(False,)]) +# TODO: test pcmCruise and pcmCruiseSpeed +@parameterized_class(('pcm_cruise', 'pcm_cruise_speed'), [(False, True)]) class TestVCruiseHelper: def setup_method(self): self.CP = car.CarParams(pcmCruise=self.pcm_cruise) - self.v_cruise_helper = VCruiseHelper(self.CP) + self.CP_SP = custom.CarParamsSP(pcmCruiseSpeed=self.pcm_cruise_speed) + self.v_cruise_helper = VCruiseHelper(self.CP, self.CP_SP) self.reset_cruise_speed_state() def reset_cruise_speed_state(self): @@ -93,7 +95,7 @@ class TestVCruiseHelper: self.enable(V_CRUISE_INITIAL * CV.KPH_TO_MS, False, False) # Expected diff on enabling. Speed should not change on falling edge of pressed - assert not pressed == self.v_cruise_helper.v_cruise_kph == self.v_cruise_helper.v_cruise_kph_last + assert (not pressed) == (self.v_cruise_helper.v_cruise_kph == self.v_cruise_helper.v_cruise_kph_last) def test_resume_in_standstill(self): """ diff --git a/openpilot/selfdrive/car/tests/test_docs.py b/openpilot/selfdrive/car/tests/test_docs.py new file mode 100644 index 0000000000..8ccbfb5a79 --- /dev/null +++ b/openpilot/selfdrive/car/tests/test_docs.py @@ -0,0 +1,11 @@ +from opendbc.car.docs import generate_cars_md, get_all_car_docs +from openpilot.selfdrive.car.docs import CARS_MD_TEMPLATE + + +class TestCarDocs: + @classmethod + def setup_class(cls): + cls.all_cars = get_all_car_docs() + + def test_generator(self): + generate_cars_md(self.all_cars, CARS_MD_TEMPLATE) diff --git a/selfdrive/car/tests/test_models.py b/openpilot/selfdrive/car/tests/test_models.py similarity index 90% rename from selfdrive/car/tests/test_models.py rename to openpilot/selfdrive/car/tests/test_models.py index 0fc6716dd3..b98890838f 100644 --- a/selfdrive/car/tests/test_models.py +++ b/openpilot/selfdrive/car/tests/test_models.py @@ -3,13 +3,11 @@ import copy import os import pytest import random -import unittest # noqa: TID251 +import unittest from collections import defaultdict, Counter -from functools import partial import hypothesis.strategies as st from hypothesis import Phase, given, settings -from parameterized import parameterized_class - +from openpilot.common.parameterized import parameterized_class from opendbc.car import DT_CTRL, gen_empty_fingerprint, structs from opendbc.car.can_definitions import CanData from opendbc.car.car_helpers import FRAME_FINGERPRINT, interfaces @@ -22,14 +20,22 @@ from opendbc.safety.tests.libsafety import libsafety_py from openpilot.common.basedir import BASEDIR from openpilot.selfdrive.pandad import can_capnp_to_list from openpilot.selfdrive.test.helpers import read_segment_list -from openpilot.system.hardware.hw import DEFAULT_DOWNLOAD_CACHE_ROOT -from openpilot.tools.lib.logreader import LogReader, LogsUnavailable, openpilotci_source_zst, openpilotci_source, internal_source, \ - internal_source_zst, comma_api_source, auto_source +from openpilot.common.hardware.hw import DEFAULT_DOWNLOAD_CACHE_ROOT +from openpilot.tools.lib.logreader import LogReader, LogsUnavailable, openpilotci_source, internal_source, comma_api_source +from openpilot.tools.lib.file_sources import Source from openpilot.tools.lib.route import SegmentName SafetyModel = car.CarParams.SafetyModel SteerControlType = structs.CarParams.SteerControlType +# panda safety stores angle_meas in brand-specific CAN units (angle_deg_to_can in opendbc/safety/modes/*.h). +ANGLE_DEG_TO_CAN = { + "tesla": -10, + "toyota": 17.452007, + "nissan": 100, + "psa": 10, +} + NUM_JOBS = int(os.environ.get("NUM_JOBS", "1")) JOB_ID = int(os.environ.get("JOB_ID", "0")) INTERNAL_SEG_LIST = os.environ.get("INTERNAL_SEG_LIST", "") @@ -126,9 +132,8 @@ class TestCarModelBase(unittest.TestCase): segment_range = f"{cls.test_route.route}/{seg}" try: - source = partial(auto_source, sources=[internal_source, internal_source_zst] if len(INTERNAL_SEG_LIST) else \ - [openpilotci_source_zst, openpilotci_source, comma_api_source]) - lr = LogReader(segment_range, source=source, sort_by_time=True) + sources: list[Source] = [internal_source] if len(INTERNAL_SEG_LIST) else [openpilotci_source, comma_api_source] + lr = LogReader(segment_range, sources=sources, sort_by_time=True) return cls.get_testing_data_from_logreader(lr) except (LogsUnavailable, AssertionError): pass @@ -154,7 +159,7 @@ class TestCarModelBase(unittest.TestCase): cls.CarInterface = interfaces[cls.platform] cls.CP = cls.CarInterface.get_params(cls.platform, cls.fingerprint, car_fw, alpha_long, False, docs=False) - cls.CP_SP = cls.CarInterface.get_params_sp(cls.CP, cls.platform, cls.fingerprint, car_fw, alpha_long, docs=False) + cls.CP_SP = cls.CarInterface.get_params_sp(cls.CP, cls.platform, cls.fingerprint, car_fw, alpha_long, False, docs=False) assert cls.CP assert cls.CP_SP assert cls.CP.carFingerprint == cls.platform @@ -187,19 +192,18 @@ class TestCarModelBase(unittest.TestCase): # make sure car params are within a valid range self.assertGreater(self.CP.mass, 1) - if self.CP.steerControlType != SteerControlType.angle: + if self.CP.steerControlType not in (SteerControlType.angle, SteerControlType.curvature): tuning = self.CP.lateralTuning.which() if tuning == 'pid': self.assertTrue(len(self.CP.lateralTuning.pid.kpV)) elif tuning == 'torque': - self.assertTrue(self.CP.lateralTuning.torque.kf > 0) + self.assertTrue(self.CP.lateralTuning.torque.latAccelFactor > 0) else: raise Exception("unknown tuning") def test_car_interface(self): # TODO: also check for checksum violations from can parser can_invalid_cnt = 0 - can_valid = False CC = structs.CarControl().as_reader() CC_SP = structs.CarControlSP() @@ -207,11 +211,8 @@ class TestCarModelBase(unittest.TestCase): CS, _ = self.CI.update(msg) self.CI.apply(CC, CC_SP, msg[0]) - if CS.canValid: - can_valid = True - # wait max of 2s for low frequency msgs to be seen - if i > 200 or can_valid: + if i > 250: can_invalid_cnt += not CS.canValid self.assertEqual(can_invalid_cnt, 0) @@ -257,7 +258,7 @@ class TestCarModelBase(unittest.TestCase): # Don't check relay malfunction on disabled routes (relay closed), # or before fingerprinting is done (elm327 and noOutput) - if self.openpilot_enabled and t / 1e4 > self.car_safety_mode_frame: + if self.car_safety_mode_frame is not None and t / 1e4 > self.car_safety_mode_frame: self.assertFalse(self.safety.get_relay_malfunction()) else: self.safety.set_relay_malfunction(False) @@ -331,7 +332,7 @@ class TestCarModelBase(unittest.TestCase): vehicle_speed_seen = self.CP.steerControlType == SteerControlType.angle and not self.CP.notCar - for dat in msgs: + for n, dat in enumerate(msgs): # due to panda updating state selectively, only edges are expected to match # TODO: warm up CarState with real CAN messages to check edge of both sources # (eg. toyota's gasPressed is the inverse of a signal being set) @@ -350,6 +351,8 @@ class TestCarModelBase(unittest.TestCase): can = [(int(time.monotonic() * 1e9), [CanData(address=address, dat=dat, src=bus)])] CS, _ = self.CI.update(can) + if n < 5: # CANParser warmup time + continue if self.safety.get_gas_pressed_prev() != prev_panda_gas: self.assertEqual(CS.gasPressed, self.safety.get_gas_pressed_prev()) @@ -369,7 +372,7 @@ class TestCarModelBase(unittest.TestCase): if self.safety.get_steering_disengage_prev() != prev_panda_steering_disengage: self.assertEqual(CS.steeringDisengage, self.safety.get_steering_disengage_prev()) - if self.safety.get_vehicle_moving() != prev_panda_vehicle_moving: + if self.safety.get_vehicle_moving() != prev_panda_vehicle_moving and not self.CP.notCar: self.assertEqual(not CS.standstill, self.safety.get_vehicle_moving()) # check vehicle speed if angle control car or available @@ -427,7 +430,7 @@ class TestCarModelBase(unittest.TestCase): # TODO: check rest of panda's carstate (steering, ACC main on, etc.) checks['gasPressed'] += CS.gasPressed != self.safety.get_gas_pressed_prev() - checks['standstill'] += CS.standstill == self.safety.get_vehicle_moving() + checks['standstill'] += (CS.standstill == self.safety.get_vehicle_moving()) and not self.CP.notCar # check vehicle speed if angle control car or available if self.safety.get_vehicle_speed_min() > 0 or self.safety.get_vehicle_speed_max() > 0: @@ -438,10 +441,18 @@ class TestCarModelBase(unittest.TestCase): checks['vEgoRaw'] += (v_ego_raw > (self.safety.get_vehicle_speed_max() + 1e-3) or v_ego_raw < (self.safety.get_vehicle_speed_min() - 1e-3)) + # check steering angle for angle control cars (panda stores angle_meas in CAN units) + # ford and VW MEB excluded since they track curvature, not steering angle + # TODO: add curvature check, standardize CAN units to rm brand specific ANGLE_DEG_TO_CAN + if self.CP.steerControlType == SteerControlType.angle and not self.CP.notCar and self.CP.brand not in ("ford", "volkswagen"): + angle_can = (CS.steeringAngleDeg + CS.steeringAngleOffsetDeg) * ANGLE_DEG_TO_CAN[self.CP.brand] + checks['steeringAngleDeg'] += (angle_can > (self.safety.get_angle_meas_max() + 1) or + angle_can < (self.safety.get_angle_meas_min() - 1)) + # TODO: remove this exception once this mismatch is resolved brake_pressed = CS.brakePressed if CS.brakePressed and not self.safety.get_brake_pressed_prev(): - if self.CP.carFingerprint in (HONDA.HONDA_PILOT, HONDA.HONDA_RIDGELINE) and CS.brake > 0.05: + if self.CP.carFingerprint in (HONDA.HONDA_PILOT, HONDA.HONDA_RIDGELINE) and CS.deprecated.brake > 0.05: brake_pressed = False checks['brakePressed'] += brake_pressed != self.safety.get_brake_pressed_prev() checks['regenBraking'] += CS.regenBraking != self.safety.get_regen_braking_prev() diff --git a/selfdrive/car/tests/test_models_segs.txt b/openpilot/selfdrive/car/tests/test_models_segs.txt similarity index 100% rename from selfdrive/car/tests/test_models_segs.txt rename to openpilot/selfdrive/car/tests/test_models_segs.txt diff --git a/selfdrive/controls/lib/__init__.py b/openpilot/selfdrive/controls/__init__.py similarity index 100% rename from selfdrive/controls/lib/__init__.py rename to openpilot/selfdrive/controls/__init__.py diff --git a/openpilot/selfdrive/controls/controlsd.py b/openpilot/selfdrive/controls/controlsd.py new file mode 100755 index 0000000000..d9c0b445d8 --- /dev/null +++ b/openpilot/selfdrive/controls/controlsd.py @@ -0,0 +1,264 @@ +#!/usr/bin/env python3 +import math +from numbers import Number + +from openpilot.cereal import log +from opendbc.car.structs import car +import openpilot.cereal.messaging as messaging +from openpilot.common.constants import CV +from openpilot.common.params import Params +from openpilot.common.realtime import config_realtime_process, DT_CTRL, Priority, Ratekeeper +from openpilot.common.swaglog import cloudlog + +from opendbc.car.car_helpers import interfaces +from opendbc.car.vehicle_model import VehicleModel +from openpilot.selfdrive.controls.lib.drive_helpers import clip_curvature +from openpilot.selfdrive.controls.lib.latcontrol import LatControl +from openpilot.selfdrive.controls.lib.latcontrol_pid import LatControlPID +from openpilot.selfdrive.controls.lib.latcontrol_angle import LatControlAngle, STEER_ANGLE_SATURATION_THRESHOLD +from openpilot.selfdrive.controls.lib.latcontrol_curvature import LatControlCurvature +from openpilot.selfdrive.controls.lib.latcontrol_torque import LatControlTorque +from openpilot.selfdrive.controls.lib.longcontrol import LongControl +from openpilot.selfdrive.modeld.modeld import LAT_SMOOTH_SECONDS +from openpilot.selfdrive.locationd.helpers import PoseCalibrator, Pose + +from openpilot.sunnypilot.selfdrive.controls.controlsd_ext import ControlsExt + +State = log.SelfdriveState.OpenpilotState +LaneChangeState = log.LaneChangeState +LaneChangeDirection = log.LaneChangeDirection + +ACTUATOR_FIELDS = tuple(car.CarControl.Actuators.schema.fields.keys()) + + +class Controls(ControlsExt): + def __init__(self) -> None: + self.params = Params() + cloudlog.info("controlsd is waiting for CarParams") + self.CP = messaging.log_from_bytes(self.params.get("CarParams", block=True), car.CarParams) + cloudlog.info("controlsd got CarParams") + + # Initialize sunnypilot controlsd extension and base model state + ControlsExt.__init__(self, self.CP, self.params) + + self.CI = interfaces[self.CP.carFingerprint](self.CP, self.CP_SP) + + self.sm = messaging.SubMaster(['liveDelay', 'liveParameters', 'liveTorqueParameters', 'modelV2', 'selfdriveState', + 'liveCalibration', 'livePose', 'longitudinalPlan', 'lateralManeuverPlan', 'carState', 'carOutput', + 'driverMonitoringState', 'onroadEvents', 'driverAssistance', 'liveDelay'] + self.sm_services_ext, + poll='selfdriveState') + self.pm = messaging.PubMaster(['carControl', 'controlsState'] + self.pm_services_ext) + + self.steer_limited_by_safety = False + self.curvature = 0.0 + self.desired_curvature = 0.0 + + self.pose_calibrator = PoseCalibrator() + self.calibrated_pose: Pose | None = None + + self.LoC = LongControl(self.CP, self.CP_SP) + self.VM = VehicleModel(self.CP) + self.LaC: LatControl + if self.CP.steerControlType == car.CarParams.SteerControlType.angle: + self.LaC = LatControlAngle(self.CP, self.CP_SP, self.CI, DT_CTRL) + elif self.CP.steerControlType == car.CarParams.SteerControlType.curvature: + self.LaC = LatControlCurvature(self.CP, self.CP_SP, self.CI, DT_CTRL) + elif self.CP.lateralTuning.which() == 'pid': + self.LaC = LatControlPID(self.CP, self.CP_SP, self.CI, DT_CTRL) + elif self.CP.lateralTuning.which() == 'torque': + self.LaC = LatControlTorque(self.CP, self.CP_SP, self.CI, DT_CTRL) + + self.LaC = ControlsExt.initialize_lateral_control(self, self.LaC, self.CI, DT_CTRL) + + def update(self): + self.sm.update(15) + if self.sm.updated["liveCalibration"]: + self.pose_calibrator.feed_live_calib(self.sm['liveCalibration']) + if self.sm.updated["livePose"]: + device_pose = Pose.from_live_pose(self.sm['livePose']) + self.calibrated_pose = self.pose_calibrator.build_calibrated_pose(device_pose) + + def state_control(self): + CS = self.sm['carState'] + + # Update VehicleModel + lp = self.sm['liveParameters'] + x = max(lp.stiffnessFactor, 0.1) + sr = max(lp.steerRatio, 0.1) + self.VM.update_params(x, sr) + + steer_angle_without_offset = math.radians(CS.steeringAngleDeg - lp.angleOffsetDeg) + self.curvature = -self.VM.calc_curvature(steer_angle_without_offset, CS.vEgo, lp.roll) + + # Update Torque Params + if self.CP.lateralTuning.which() == 'torque': + torque_params = self.sm['liveTorqueParameters'] + if self.sm.all_checks(['liveTorqueParameters']) and torque_params.useParams: + self.LaC.update_live_torque_params(torque_params.latAccelFactorFiltered, torque_params.latAccelOffsetFiltered, + torque_params.frictionCoefficientFiltered) + + self.LaC.extension.update_limits() + + self.LaC.extension.update_model_v2(self.sm['modelV2']) + + self.LaC.extension.update_lateral_lag(self.lat_delay) + + long_plan = self.sm['longitudinalPlan'] + model_v2 = self.sm['modelV2'] + + CC = car.CarControl.new_message() + CC.enabled = self.sm['selfdriveState'].enabled + + # Check which actuators can be enabled + standstill = abs(CS.vEgo) <= max(self.CP.minSteerSpeed, 0.3) or CS.standstill + + # Get which state to use for active lateral control + _lat_active = self.get_lat_active(self.sm) + + CC.latActive = _lat_active and not CS.steerFaultTemporary and not CS.steerFaultPermanent and \ + (not standstill or self.CP.steerAtStandstill) + CC.longActive = CC.enabled and not any(e.overrideLongitudinal for e in self.sm['onroadEvents']) and \ + (self.CP.openpilotLongitudinalControl or not self.CP_SP.pcmCruiseSpeed) + + actuators = CC.actuators + actuators.longControlState = self.LoC.long_control_state + + # Enable blinkers while lane changing + if model_v2.meta.laneChangeState != LaneChangeState.off: + CC.leftBlinker = model_v2.meta.laneChangeDirection == LaneChangeDirection.left + CC.rightBlinker = model_v2.meta.laneChangeDirection == LaneChangeDirection.right + + if not CC.latActive: + self.LaC.reset() + if not CC.longActive: + self.LoC.reset() + + # accel PID loop + pid_accel_limits = self.CI.get_pid_accel_limits(self.CP, self.CP_SP, CS.vEgo, CS.vCruise * CV.KPH_TO_MS) + actuators.accel = float(self.LoC.update(CC.longActive, CS, long_plan.aTarget, long_plan.shouldStop, pid_accel_limits)) + + # Steering PID loop and lateral MPC + # Reset desired curvature to current to avoid violating the limits on engage + if self.sm.valid['lateralManeuverPlan']: + new_desired_curvature = self.sm['lateralManeuverPlan'].desiredCurvature if CC.latActive else self.curvature + else: + new_desired_curvature = model_v2.action.desiredCurvature if CC.latActive else self.curvature + self.desired_curvature, curvature_limited = clip_curvature(CS.vEgo, self.desired_curvature, new_desired_curvature, lp.roll) + lat_delay = self.sm["liveDelay"].lateralDelay + LAT_SMOOTH_SECONDS + + actuators.curvature = self.desired_curvature + steer, lateral_output, lac_log = self.LaC.update(CC.latActive, CS, self.VM, lp, + self.steer_limited_by_safety, self.desired_curvature, + self.calibrated_pose, curvature_limited, lat_delay) + actuators.torque = float(steer) + if self.CP.steerControlType == car.CarParams.SteerControlType.curvature: + actuators.curvature = float(lateral_output) + else: + actuators.steeringAngleDeg = float(lateral_output) + # Ensure no NaNs/Infs + for p in ACTUATOR_FIELDS: + attr = getattr(actuators, p) + if not isinstance(attr, Number): + continue + + if not math.isfinite(attr): + cloudlog.error(f"actuators.{p} not finite {actuators.to_dict()}") + setattr(actuators, p, 0.0) + + return CC, lac_log + + def publish(self, CC, lac_log): + CS = self.sm['carState'] + + # Orientation and angle rates can be useful for carcontroller + # Only calibrated (car) frame is relevant for the carcontroller + CC.currentCurvature = self.curvature + if self.calibrated_pose is not None: + CC.orientationNED = self.calibrated_pose.orientation.xyz.tolist() + CC.angularVelocity = self.calibrated_pose.angular_velocity.xyz.tolist() + + CC.cruiseControl.override = CC.enabled and not CC.longActive and (self.CP.openpilotLongitudinalControl or not self.CP_SP.pcmCruiseSpeed) + CC.cruiseControl.cancel = CS.cruiseState.enabled and (not CC.enabled or not self.CP.pcmCruise) + CC.cruiseControl.resume = CC.enabled and CS.cruiseState.standstill and not self.sm['longitudinalPlan'].shouldStop + + hudControl = CC.hudControl + hudControl.setSpeed = float(CS.vCruiseCluster * CV.KPH_TO_MS) + hudControl.speedVisible = CC.enabled + hudControl.lanesVisible = CC.enabled + hudControl.leadVisible = self.sm['longitudinalPlan'].hasLead + hudControl.leadDistanceBars = self.sm['selfdriveState'].personality.raw + 1 + hudControl.visualAlert = self.sm['selfdriveState'].alertHudVisual + + hudControl.rightLaneVisible = True + hudControl.leftLaneVisible = True + if self.sm.valid['driverAssistance']: + hudControl.leftLaneDepart = self.sm['driverAssistance'].leftLaneDeparture + hudControl.rightLaneDepart = self.sm['driverAssistance'].rightLaneDeparture + + if self.get_lat_active(self.sm): + CO = self.sm['carOutput'] + if self.CP.steerControlType == car.CarParams.SteerControlType.angle: + self.steer_limited_by_safety = abs(CC.actuators.steeringAngleDeg - CO.actuatorsOutput.steeringAngleDeg) > \ + STEER_ANGLE_SATURATION_THRESHOLD + else: + self.steer_limited_by_safety = abs(CC.actuators.torque - CO.actuatorsOutput.torque) > 1e-2 + + # TODO: both controlsState and carControl valids should be set by + # sm.all_checks(), but this creates a circular dependency + + # controlsState + dat = messaging.new_message('controlsState') + dat.valid = CS.canValid + cs = dat.controlsState + + cs.curvature = self.curvature + cs.longitudinalPlanMonoTime = self.sm.logMonoTime['longitudinalPlan'] + cs.lateralPlanMonoTime = self.sm.logMonoTime['modelV2'] + cs.desiredCurvature = self.desired_curvature + cs.longControlState = self.LoC.long_control_state + cs.upAccelCmd = float(self.LoC.pid.p) + cs.uiAccelCmd = float(self.LoC.pid.i) + cs.ufAccelCmd = float(self.LoC.pid.f) + cs.forceDecel = bool(self.sm['driverMonitoringState'].noResponseForceDecel or + (self.sm['selfdriveState'].state == State.softDisabling)) + + # trigger the car's stock driver monitoring escalation + CC.driverMonitoringEscalation = cs.forceDecel + + lat_tuning = self.CP.lateralTuning.which() + if self.CP.steerControlType == car.CarParams.SteerControlType.angle: + cs.lateralControlState.angleState = lac_log + elif self.CP.steerControlType == car.CarParams.SteerControlType.curvature: + cs.lateralControlState.curvatureState = lac_log + elif lat_tuning == 'pid': + cs.lateralControlState.pidState = lac_log + elif lat_tuning == 'torque': + cs.lateralControlState.torqueState = lac_log + + self.pm.send('controlsState', dat) + + # carControl + cc_send = messaging.new_message('carControl') + cc_send.valid = CS.canValid + cc_send.carControl = CC + self.pm.send('carControl', cc_send) + + def run(self): + rk = Ratekeeper(100, print_delay_threshold=None) + while True: + self.update() + CC, lac_log = self.state_control() + self.publish(CC, lac_log) + self.get_params_sp(self.sm) + self.run_ext(self.sm, self.pm) + rk.monitor_time() + + +def main(): + config_realtime_process(4, Priority.CTRL_HIGH) + controls = Controls() + controls.run() + + +if __name__ == "__main__": + main() diff --git a/selfdrive/controls/lib/lateral_mpc_lib/__init__.py b/openpilot/selfdrive/controls/lib/__init__.py similarity index 100% rename from selfdrive/controls/lib/lateral_mpc_lib/__init__.py rename to openpilot/selfdrive/controls/lib/__init__.py diff --git a/openpilot/selfdrive/controls/lib/desire_helper.py b/openpilot/selfdrive/controls/lib/desire_helper.py new file mode 100644 index 0000000000..df4e5c56ab --- /dev/null +++ b/openpilot/selfdrive/controls/lib/desire_helper.py @@ -0,0 +1,104 @@ +from openpilot.cereal import log, custom +from openpilot.common.constants import CV +from openpilot.common.realtime import DT_MDL +from openpilot.sunnypilot.selfdrive.controls.lib.auto_lane_change import AutoLaneChangeController, AutoLaneChangeMode +from openpilot.sunnypilot.selfdrive.controls.lib.lane_turn_desire import LaneTurnController + +LaneChangeState = log.LaneChangeState +LaneChangeDirection = log.LaneChangeDirection +TurnDirection = custom.ModelDataV2SP.TurnDirection + +LANE_CHANGE_SPEED_MIN = 20 * CV.MPH_TO_MS +LANE_CHANGE_TIME_MAX = 10. +LANE_CHANGE_START_TIME = 0.5 + +TURN_DESIRES = { + TurnDirection.none: log.Desire.none, + TurnDirection.turnLeft: log.Desire.turnLeft, + TurnDirection.turnRight: log.Desire.turnRight, +} + +class DesireHelper: + def __init__(self): + self.lane_change_state = LaneChangeState.off + self.lane_change_direction = LaneChangeDirection.none + self.lane_change_timer = 0.0 + self.prev_one_blinker = False + self.desire = log.Desire.none + self.alc = AutoLaneChangeController(self) + self.lane_turn_controller = LaneTurnController(self) + self.lane_turn_direction = TurnDirection.none + + @staticmethod + def get_lane_change_direction(CS): + return LaneChangeDirection.left if CS.leftBlinker else LaneChangeDirection.right + + def update(self, carstate, lateral_active, lane_change_prob): + self.alc.update_params() + self.lane_turn_controller.update_params() + v_ego = carstate.vEgo + one_blinker = carstate.leftBlinker != carstate.rightBlinker + below_lane_change_speed = v_ego < LANE_CHANGE_SPEED_MIN + + # Lane turn controller update + self.lane_turn_controller.update_lane_turn(blindspot_left=carstate.leftBlindspot, blindspot_right=carstate.rightBlindspot, + left_blinker=carstate.leftBlinker, right_blinker=carstate.rightBlinker, v_ego=v_ego) + self.lane_turn_direction = self.lane_turn_controller.get_turn_direction() + + if not lateral_active or self.lane_change_timer > LANE_CHANGE_TIME_MAX or self.alc.lane_change_set_timer == AutoLaneChangeMode.OFF: + self.lane_change_state = LaneChangeState.off + self.lane_change_direction = LaneChangeDirection.none + self.lane_change_timer = 0.0 + else: + if self.lane_change_state == LaneChangeState.off and one_blinker and not self.prev_one_blinker and not below_lane_change_speed: + self.lane_change_state = LaneChangeState.preLaneChange + self.lane_change_timer = 0.0 + # Initialize lane change direction to prevent UI alert flicker + self.lane_change_direction = self.get_lane_change_direction(carstate) + + elif self.lane_change_state == LaneChangeState.preLaneChange: + # Update lane change direction + self.lane_change_direction = self.get_lane_change_direction(carstate) + + torque_applied = carstate.steeringPressed and \ + ((carstate.steeringTorque > 0 and self.lane_change_direction == LaneChangeDirection.left) or + (carstate.steeringTorque < 0 and self.lane_change_direction == LaneChangeDirection.right)) + + blindspot_detected = ((carstate.leftBlindspot and self.lane_change_direction == LaneChangeDirection.left) or + (carstate.rightBlindspot and self.lane_change_direction == LaneChangeDirection.right)) + + self.alc.update_lane_change(blindspot_detected, carstate.brakePressed) + + if not one_blinker or below_lane_change_speed: + self.lane_change_state = LaneChangeState.off + self.lane_change_direction = LaneChangeDirection.none + self.lane_change_timer = 0.0 + elif (torque_applied or self.alc.auto_lane_change_allowed) and not blindspot_detected: + self.lane_change_state = LaneChangeState.laneChangeStarting + self.lane_change_timer = 0.0 + + elif self.lane_change_state == LaneChangeState.laneChangeStarting: + self.lane_change_timer += DT_MDL + + if lane_change_prob < 0.02 and self.lane_change_timer >= LANE_CHANGE_START_TIME: + self.lane_change_timer = 0.0 + if one_blinker: + self.lane_change_state = LaneChangeState.preLaneChange + self.lane_change_direction = self.get_lane_change_direction(carstate) + else: + self.lane_change_state = LaneChangeState.off + self.lane_change_direction = LaneChangeDirection.none + + self.prev_one_blinker = one_blinker and lateral_active + + if self.lane_turn_direction != TurnDirection.none: + self.desire = TURN_DESIRES[self.lane_turn_direction] + else: + self.desire = log.Desire.none + if self.lane_change_state == LaneChangeState.laneChangeStarting: + if self.lane_change_direction == LaneChangeDirection.left: + self.desire = log.Desire.laneChangeLeft + elif self.lane_change_direction == LaneChangeDirection.right: + self.desire = log.Desire.laneChangeRight + + self.alc.update_state() diff --git a/openpilot/selfdrive/controls/lib/drive_helpers.py b/openpilot/selfdrive/controls/lib/drive_helpers.py new file mode 100644 index 0000000000..497f8d1bdf --- /dev/null +++ b/openpilot/selfdrive/controls/lib/drive_helpers.py @@ -0,0 +1,72 @@ +import numpy as np +from openpilot.common.constants import ACCELERATION_DUE_TO_GRAVITY +from openpilot.common.realtime import DT_CTRL, DT_MDL + +MIN_SPEED = 1.0 +CONTROL_N = 17 +CAR_ROTATION_RADIUS = 0.0 +# This is a turn radius smaller than most cars can achieve +MAX_CURVATURE = 0.2 +MAX_VEL_ERR = 5.0 # m/s +MIN_STABLE_DELAY = 0.3 + +# EU guidelines +MAX_LATERAL_JERK = 5.0 # m/s^3 +MAX_LATERAL_ACCEL_NO_ROLL = 3.0 # m/s^2 + + +def should_stop(v_ego: float, a_target: float) -> bool: + return bool(v_ego < 0.25 and a_target < 0.1) + +def clamp(val, min_val, max_val): + clamped_val = float(np.clip(val, min_val, max_val)) + return clamped_val, clamped_val != val + +def smooth_value(val, prev_val, tau, dt=DT_MDL): + alpha = 1 - np.exp(-dt/tau) if tau > 0 else 1 + return alpha * val + (1 - alpha) * prev_val + +def clip_curvature(v_ego, prev_curvature, new_curvature, roll) -> tuple[float, bool]: + # This function respects ISO lateral jerk and acceleration limits + a max curvature + v_ego = max(v_ego, MIN_SPEED) + max_curvature_rate = MAX_LATERAL_JERK / (v_ego ** 2) # inexact calculation, check https://github.com/commaai/openpilot/pull/24755 + new_curvature = np.clip(new_curvature, + prev_curvature - max_curvature_rate * DT_CTRL, + prev_curvature + max_curvature_rate * DT_CTRL) + + roll_compensation = roll * ACCELERATION_DUE_TO_GRAVITY + max_lat_accel = MAX_LATERAL_ACCEL_NO_ROLL + roll_compensation + min_lat_accel = -MAX_LATERAL_ACCEL_NO_ROLL + roll_compensation + new_curvature, limited_accel = clamp(new_curvature, min_lat_accel / v_ego ** 2, max_lat_accel / v_ego ** 2) + + new_curvature, limited_max_curv = clamp(new_curvature, -MAX_CURVATURE, MAX_CURVATURE) + return float(new_curvature), limited_accel or limited_max_curv + + +def get_accel_from_plan(speeds, accels, t_idxs, action_t=DT_MDL): + if len(speeds) == len(t_idxs): + v_now = speeds[0] + a_now = accels[0] + if action_t < MIN_STABLE_DELAY: + v_target = v_now + (action_t / MIN_STABLE_DELAY) * (np.interp(MIN_STABLE_DELAY, t_idxs, speeds) - v_now) + else: + v_target = np.interp(action_t, t_idxs, speeds) + a_target = 2 * (v_target - v_now) / (action_t) - a_now + else: + v_now = 0.0 + v_target = 0.0 + a_target = 0.0 + return a_target, should_stop(v_now, a_target) + +def curv_from_psis(psi_target, psi_rate, vego, action_t): + vego = np.clip(vego, MIN_SPEED, np.inf) + curv_from_psi = psi_target / (vego * action_t) + return 2*curv_from_psi - psi_rate / vego + +def get_curvature_from_plan(yaws, yaw_rates, t_idxs, vego, action_t): + if action_t < MIN_STABLE_DELAY: + psi_target = (action_t / MIN_STABLE_DELAY) * np.interp(MIN_STABLE_DELAY, t_idxs, yaws) + else: + psi_target = np.interp(action_t, t_idxs, yaws) + psi_rate = yaw_rates[0] + return curv_from_psis(psi_target, psi_rate, vego, action_t) diff --git a/openpilot/selfdrive/controls/lib/latcontrol.py b/openpilot/selfdrive/controls/lib/latcontrol.py new file mode 100644 index 0000000000..5519d37296 --- /dev/null +++ b/openpilot/selfdrive/controls/lib/latcontrol.py @@ -0,0 +1,31 @@ +import numpy as np +from abc import abstractmethod, ABC +from openpilot.selfdrive.locationd.helpers import Pose + + +class LatControl(ABC): + def __init__(self, CP, CP_SP, CI, dt): + self.dt = dt + self.sat_limit = CP.steerLimitTimer + self.sat_time = 0. + self.sat_check_min_speed = 10. + + # we define the steer torque scale as [-1.0...1.0] + self.steer_max = 1.0 + + @abstractmethod + def update(self, active: bool, CS, VM, params, steer_limited_by_safety: bool, desired_curvature: float, calibrated_pose: Pose | None, + curvature_limited: bool, lat_delay: float): + pass + + def reset(self): + self.sat_time = 0. + + def _check_saturation(self, saturated, CS, steer_limited_by_safety, curvature_limited): + # Saturated only if control output is not being limited by car torque/angle rate limits + if (saturated or curvature_limited) and CS.vEgo > self.sat_check_min_speed and not steer_limited_by_safety and not CS.steeringPressed: + self.sat_time += self.dt + else: + self.sat_time -= self.dt + self.sat_time = np.clip(self.sat_time, 0.0, self.sat_limit) + return self.sat_time > (self.sat_limit - 1e-3) diff --git a/openpilot/selfdrive/controls/lib/latcontrol_angle.py b/openpilot/selfdrive/controls/lib/latcontrol_angle.py new file mode 100644 index 0000000000..18ccbae57b --- /dev/null +++ b/openpilot/selfdrive/controls/lib/latcontrol_angle.py @@ -0,0 +1,37 @@ +import math + +from openpilot.cereal import log +from openpilot.selfdrive.controls.lib.latcontrol import LatControl + +# TODO This is speed dependent +STEER_ANGLE_SATURATION_THRESHOLD = 2.5 # Degrees + + +class LatControlAngle(LatControl): + def __init__(self, CP, CP_SP, CI, dt): + super().__init__(CP, CP_SP, CI, dt) + self.sat_check_min_speed = 5. + self.use_steer_limited_by_safety = CP.brand in ("tesla", "hyundai") + + def update(self, active, CS, VM, params, steer_limited_by_safety, desired_curvature, calibrated_pose, curvature_limited, lat_delay): + angle_log = log.ControlsState.LateralAngleState.new_message() + + if not active: + angle_log.active = False + angle_steers_des = float(CS.steeringAngleDeg) + else: + angle_log.active = True + angle_steers_des = math.degrees(VM.get_steer_from_curvature(-desired_curvature, CS.vEgo, params.roll)) + angle_steers_des += params.angleOffsetDeg + + if self.use_steer_limited_by_safety: + # these cars' carcontrollers calculate max lateral accel and jerk, so we can rely on carOutput for saturation + angle_control_saturated = steer_limited_by_safety + else: + # for cars which use a method of limiting torque such as a torque signal (Nissan and Toyota) + # or relying on EPS (Ford Q3), carOutput does not capture maxing out torque # TODO: this can be improved + angle_control_saturated = abs(angle_steers_des - CS.steeringAngleDeg) > STEER_ANGLE_SATURATION_THRESHOLD + angle_log.saturated = bool(self._check_saturation(angle_control_saturated, CS, False, curvature_limited)) + angle_log.steeringAngleDeg = float(CS.steeringAngleDeg) + angle_log.steeringAngleDesiredDeg = angle_steers_des + return 0, float(angle_steers_des), angle_log diff --git a/openpilot/selfdrive/controls/lib/latcontrol_curvature.py b/openpilot/selfdrive/controls/lib/latcontrol_curvature.py new file mode 100644 index 0000000000..3dfe691e10 --- /dev/null +++ b/openpilot/selfdrive/controls/lib/latcontrol_curvature.py @@ -0,0 +1,58 @@ +import math + +from openpilot.cereal import log +from openpilot.common.pid import PIDController +from openpilot.selfdrive.controls.lib.latcontrol import LatControl +from openpilot.selfdrive.controls.lib.drive_helpers import MAX_CURVATURE + +CURVATURE_SATURATION_THRESHOLD = 1e-3 # 1/m + + +class LatControlCurvature(LatControl): + def __init__(self, CP, CP_SP, CI, dt): + super().__init__(CP, CP_SP, CI, dt) + self.sat_check_min_speed = 5. + if CP.lateralTuning.which() == 'pid': + ct = CP.lateralTuning.pid + self.pid = PIDController((ct.kpBP, ct.kpV), (ct.kiBP, ct.kiV), + pos_limit=MAX_CURVATURE, neg_limit=-MAX_CURVATURE, rate=1 / dt) + self.kf = ct.kf + else: + self.pid = None + self.kf = 1. + + def reset(self): + super().reset() + if self.pid is not None: + self.pid.reset() + + def update(self, active, CS, VM, params, steer_limited_by_safety, desired_curvature, calibrated_pose, curvature_limited, lat_delay): + curvature_log = log.ControlsState.LateralCurvatureState.new_message() + actual_curvature = -VM.calc_curvature(math.radians(CS.steeringAngleDeg - params.angleOffsetDeg), CS.vEgo, params.roll) + error = desired_curvature - actual_curvature + + if not active: + output_curvature = 0.0 + curvature_log.active = False + if self.pid is not None: + self.pid.reset() + elif self.pid is None or CS.steeringPressed: + # no PID or override: feedforward only + if self.pid is not None: + self.pid.reset() + output_curvature = self.kf * desired_curvature + curvature_log.active = True + else: + output_curvature = self.pid.update(error, speed=CS.vEgo, feedforward=self.kf * desired_curvature) + curvature_log.p = float(self.pid.p) + curvature_log.i = float(self.pid.i) + curvature_log.f = float(self.pid.f) + curvature_log.active = True + + curvature_log.error = float(error) + curvature_log.actualCurvature = float(actual_curvature) + curvature_log.desiredCurvature = float(desired_curvature) + curvature_log.output = float(output_curvature) + curvature_log.saturated = bool(self._check_saturation(abs(error) > CURVATURE_SATURATION_THRESHOLD, CS, + False, curvature_limited)) + return 0.0, float(output_curvature), curvature_log diff --git a/openpilot/selfdrive/controls/lib/latcontrol_pid.py b/openpilot/selfdrive/controls/lib/latcontrol_pid.py new file mode 100644 index 0000000000..214f4724d1 --- /dev/null +++ b/openpilot/selfdrive/controls/lib/latcontrol_pid.py @@ -0,0 +1,49 @@ +import math + +from openpilot.cereal import log +from openpilot.selfdrive.controls.lib.latcontrol import LatControl +from openpilot.common.pid import PIDController + + +class LatControlPID(LatControl): + def __init__(self, CP, CP_SP, CI, dt): + super().__init__(CP, CP_SP, CI, dt) + self.pid = PIDController((CP.lateralTuning.pid.kpBP, CP.lateralTuning.pid.kpV), + (CP.lateralTuning.pid.kiBP, CP.lateralTuning.pid.kiV), + pos_limit=self.steer_max, neg_limit=-self.steer_max) + self.ff_factor = CP.lateralTuning.pid.kf + self.get_steer_feedforward = CI.get_steer_feedforward_function() + + def update(self, active, CS, VM, params, steer_limited_by_safety, desired_curvature, calibrated_pose, curvature_limited, lat_delay): + pid_log = log.ControlsState.LateralPIDState.new_message() + pid_log.steeringAngleDeg = float(CS.steeringAngleDeg) + pid_log.steeringRateDeg = float(CS.steeringRateDeg) + + angle_steers_des_no_offset = math.degrees(VM.get_steer_from_curvature(-desired_curvature, CS.vEgo, params.roll)) + angle_steers_des = angle_steers_des_no_offset + params.angleOffsetDeg + error = angle_steers_des - CS.steeringAngleDeg + + pid_log.steeringAngleDesiredDeg = angle_steers_des + pid_log.angleError = error + if not active: + output_torque = 0.0 + pid_log.active = False + + else: + # offset does not contribute to resistive torque + ff = self.ff_factor * self.get_steer_feedforward(angle_steers_des_no_offset, CS.vEgo) + freeze_integrator = steer_limited_by_safety or CS.steeringPressed or CS.vEgo < 5 + + output_torque = self.pid.update(error, + feedforward=ff, + speed=CS.vEgo, + freeze_integrator=freeze_integrator) + + pid_log.active = True + pid_log.p = float(self.pid.p) + pid_log.i = float(self.pid.i) + pid_log.f = float(self.pid.f) + pid_log.output = float(output_torque) + pid_log.saturated = bool(self._check_saturation(self.steer_max - abs(output_torque) < 1e-3, CS, steer_limited_by_safety, curvature_limited)) + + return output_torque, angle_steers_des, pid_log diff --git a/openpilot/selfdrive/controls/lib/latcontrol_torque.py b/openpilot/selfdrive/controls/lib/latcontrol_torque.py new file mode 100644 index 0000000000..952234de99 --- /dev/null +++ b/openpilot/selfdrive/controls/lib/latcontrol_torque.py @@ -0,0 +1,122 @@ +import math +import numpy as np +from collections import deque + +from openpilot.cereal import log +from opendbc.car.lateral import FRICTION_THRESHOLD, get_friction +from openpilot.common.constants import ACCELERATION_DUE_TO_GRAVITY +from openpilot.common.filter_simple import FirstOrderFilter +from openpilot.selfdrive.controls.lib.latcontrol import LatControl +from openpilot.common.pid import PIDController + +from openpilot.sunnypilot.selfdrive.controls.lib.latcontrol_torque_ext import LatControlTorqueExt + +# At higher speeds (25+mph) we can assume: +# Lateral acceleration achieved by a specific car correlates to +# torque applied to the steering rack. It does not correlate to +# wheel slip, or to speed. + +# This controller applies torque to achieve desired lateral +# accelerations. To compensate for the low speed effects the +# proportional gain is increased at low speeds by the PID controller. +# Additionally, there is friction in the steering wheel that needs +# to be overcome to move it at all, this is compensated for too. + +KP = 0.8 +KI = 0.15 + +INTERP_SPEEDS = [1, 1.5, 2.0, 3.0, 5, 7.5, 10, 15, 30] +KP_INTERP = [250, 120, 65, 30, 11.5, 5.5, 3.5, 2.0, KP] + +LP_FILTER_CUTOFF_HZ = 1.2 +JERK_LOOKAHEAD_SECONDS = 0.19 +JERK_GAIN = 0.3 +LAT_ACCEL_REQUEST_BUFFER_SECONDS = 1.0 +VERSION = 1 + +class LatControlTorque(LatControl): + def __init__(self, CP, CP_SP, CI, dt): + super().__init__(CP, CP_SP, CI, dt) + self.torque_params = CP.lateralTuning.torque.as_builder() + self.torque_from_lateral_accel = CI.torque_from_lateral_accel() + self.lateral_accel_from_torque = CI.lateral_accel_from_torque() + self.pid = PIDController([INTERP_SPEEDS, KP_INTERP], KI, rate=1/self.dt) + self.update_limits() + self.steering_angle_deadzone_deg = self.torque_params.steeringAngleDeadzoneDeg + self.lat_accel_request_buffer_len = int(LAT_ACCEL_REQUEST_BUFFER_SECONDS / self.dt) + self.lat_accel_request_buffer = deque([0.] * self.lat_accel_request_buffer_len , maxlen=self.lat_accel_request_buffer_len) + self.lookahead_frames = int(JERK_LOOKAHEAD_SECONDS / self.dt) + self.jerk_filter = FirstOrderFilter(0.0, 1 / (2 * np.pi * LP_FILTER_CUTOFF_HZ), self.dt) + + self.extension = LatControlTorqueExt(self, CP, CP_SP, CI) + + def update_live_torque_params(self, latAccelFactor, latAccelOffset, friction): + self.torque_params.latAccelFactor = latAccelFactor + self.torque_params.latAccelOffset = latAccelOffset + self.torque_params.friction = friction + self.update_limits() + + def update_limits(self): + self.pid.set_limits(self.lateral_accel_from_torque(self.steer_max, self.torque_params), + self.lateral_accel_from_torque(-self.steer_max, self.torque_params)) + + def update(self, active, CS, VM, params, steer_limited_by_safety, desired_curvature, calibrated_pose, curvature_limited, lat_delay): + # Override torque params from extension + if self.extension.update_override_torque_params(self.torque_params): + self.update_limits() + + pid_log = log.ControlsState.LateralTorqueState.new_message() + pid_log.version = VERSION + measured_curvature = -VM.calc_curvature(math.radians(CS.steeringAngleDeg - params.angleOffsetDeg), CS.vEgo, params.roll) + measurement = measured_curvature * CS.vEgo ** 2 + future_desired_lateral_accel = desired_curvature * CS.vEgo ** 2 + self.lat_accel_request_buffer.append(future_desired_lateral_accel) + + roll_compensation = params.roll * ACCELERATION_DUE_TO_GRAVITY + curvature_deadzone = abs(VM.calc_curvature(math.radians(self.steering_angle_deadzone_deg), CS.vEgo, 0.0)) + lateral_accel_deadzone = curvature_deadzone * CS.vEgo ** 2 + + delay_frames = int(np.clip(lat_delay / self.dt + 1, 1, self.lat_accel_request_buffer_len)) + expected_lateral_accel = self.lat_accel_request_buffer[-delay_frames] + setpoint = expected_lateral_accel + error = setpoint - measurement + + lookahead_idx = int(np.clip(-delay_frames + self.lookahead_frames, -self.lat_accel_request_buffer_len+1, -2)) + raw_lateral_jerk = (self.lat_accel_request_buffer[lookahead_idx+1] - self.lat_accel_request_buffer[lookahead_idx-1]) / (2 * self.dt) + desired_lateral_jerk = self.jerk_filter.update(raw_lateral_jerk) + gravity_adjusted_future_lateral_accel = future_desired_lateral_accel - roll_compensation + ff = gravity_adjusted_future_lateral_accel + # latAccelOffset corrects roll compensation bias from device roll misalignment relative to car roll + ff -= self.torque_params.latAccelOffset + ff += get_friction(error + JERK_GAIN * desired_lateral_jerk, lateral_accel_deadzone, FRICTION_THRESHOLD, self.torque_params) + + if not active: + output_torque = 0.0 + pid_log.active = False + else: + # do error correction in lateral acceleration space, convert at end to handle non-linear torque responses correctly + pid_log.error = float(error) + + freeze_integrator = steer_limited_by_safety or CS.steeringPressed or CS.vEgo < 5 + output_lataccel = self.pid.update(pid_log.error, speed=CS.vEgo, feedforward=ff, freeze_integrator=freeze_integrator) + output_torque = self.torque_from_lateral_accel(output_lataccel, self.torque_params) + + # Lateral acceleration torque controller extension updates + # Overrides pid_log.error and output_torque + pid_log, output_torque = self.extension.update(CS, VM, self.pid, params, ff, pid_log, setpoint, measurement, calibrated_pose, roll_compensation, + future_desired_lateral_accel, measurement, lateral_accel_deadzone, gravity_adjusted_future_lateral_accel, + desired_curvature, measured_curvature, steer_limited_by_safety, output_torque) + + pid_log.active = True + pid_log.p = float(self.pid.p) + pid_log.i = float(self.pid.i) + pid_log.d = float(self.pid.d) + pid_log.f = float(self.pid.f) + pid_log.output = float(-output_torque) # TODO: log lat accel? + pid_log.actualLateralAccel = float(measurement) + pid_log.desiredLateralAccel = float(setpoint) + pid_log.desiredLateralJerk = float(desired_lateral_jerk) + pid_log.saturated = bool(self._check_saturation(self.steer_max - abs(output_torque) < 1e-3, CS, steer_limited_by_safety, curvature_limited)) + + # TODO left is positive in this convention + return -output_torque, 0.0, pid_log diff --git a/selfdrive/controls/lib/ldw.py b/openpilot/selfdrive/controls/lib/ldw.py similarity index 94% rename from selfdrive/controls/lib/ldw.py rename to openpilot/selfdrive/controls/lib/ldw.py index caf03fec73..6db59791cc 100644 --- a/selfdrive/controls/lib/ldw.py +++ b/openpilot/selfdrive/controls/lib/ldw.py @@ -1,6 +1,6 @@ -from cereal import log +from openpilot.cereal import log from openpilot.common.realtime import DT_CTRL -from openpilot.common.conversions import Conversions as CV +from openpilot.common.constants import CV CAMERA_OFFSET = 0.04 diff --git a/openpilot/selfdrive/controls/lib/longcontrol.py b/openpilot/selfdrive/controls/lib/longcontrol.py new file mode 100644 index 0000000000..e3b612e79f --- /dev/null +++ b/openpilot/selfdrive/controls/lib/longcontrol.py @@ -0,0 +1,81 @@ +import numpy as np +from opendbc.car.structs import car +from openpilot.common.realtime import DT_CTRL +from openpilot.selfdrive.controls.lib.drive_helpers import CONTROL_N +from openpilot.common.pid import PIDController +from openpilot.selfdrive.modeld.constants import ModelConstants + +CONTROL_N_T_IDX = ModelConstants.T_IDXS[:CONTROL_N] + +LongCtrlState = car.CarControl.Actuators.LongControlState + + +def long_control_state_trans(CP_SP, active, long_control_state, + should_stop, brake_pressed, cruise_standstill): + # Gas Interceptor + cruise_standstill = cruise_standstill and not CP_SP.enableGasInterceptor + + starting_condition = (not should_stop and + not cruise_standstill and + not brake_pressed) + + if not active: + long_control_state = LongCtrlState.off + + else: + if long_control_state == LongCtrlState.off: + if not starting_condition: + long_control_state = LongCtrlState.stopping + else: + long_control_state = LongCtrlState.pid + + elif long_control_state == LongCtrlState.stopping: + if starting_condition: + long_control_state = LongCtrlState.pid + + elif long_control_state == LongCtrlState.pid: + if should_stop: + long_control_state = LongCtrlState.stopping + + return long_control_state + +class LongControl: + def __init__(self, CP, CP_SP): + self.CP = CP + self.CP_SP = CP_SP + self.long_control_state = LongCtrlState.off + self.pid = PIDController((CP.longitudinalTuning.kpBP, CP.longitudinalTuning.kpV), + (CP.longitudinalTuning.kiBP, CP.longitudinalTuning.kiV), + rate=1 / DT_CTRL) + self.last_output_accel = 0.0 + + def reset(self): + self.pid.reset() + + def update(self, active, CS, a_target, should_stop, accel_limits): + """Update longitudinal control. This updates the state machine and runs a PID loop""" + self.pid.neg_limit = accel_limits[0] + self.pid.pos_limit = accel_limits[1] + + self.long_control_state = long_control_state_trans(self.CP_SP, active, self.long_control_state, + should_stop, CS.brakePressed, + CS.cruiseState.standstill) + if self.long_control_state == LongCtrlState.off: + self.reset() + output_accel = 0. + + elif self.long_control_state == LongCtrlState.stopping: + output_accel = self.last_output_accel + if output_accel > self.CP.stopAccel: + output_accel = min(output_accel, 0.0) + # TODO: can we just go straight to stopAccel? + output_accel -= 1.0 * DT_CTRL # m/s^2/s while trying to stop + self.reset() + + else: # LongCtrlState.pid + error = a_target - CS.aEgo + output_accel = self.pid.update(error, speed=CS.vEgo, + feedforward=a_target) + + self.last_output_accel = np.clip(output_accel, accel_limits[0], accel_limits[1]) + return self.last_output_accel diff --git a/selfdrive/controls/lib/longitudinal_mpc_lib/.gitignore b/openpilot/selfdrive/controls/lib/longitudinal_mpc_lib/.gitignore similarity index 100% rename from selfdrive/controls/lib/longitudinal_mpc_lib/.gitignore rename to openpilot/selfdrive/controls/lib/longitudinal_mpc_lib/.gitignore diff --git a/openpilot/selfdrive/controls/lib/longitudinal_mpc_lib/SConscript b/openpilot/selfdrive/controls/lib/longitudinal_mpc_lib/SConscript new file mode 100644 index 0000000000..636ef0fb21 --- /dev/null +++ b/openpilot/selfdrive/controls/lib/longitudinal_mpc_lib/SConscript @@ -0,0 +1,109 @@ +Import('env', 'envCython', 'arch', 'msgq_python', 'common_python', 'np_version', 'acados') + +gen = "c_generated_code" + +casadi_model = [ + f'{gen}/long_model/long_expl_ode_fun.c', + f'{gen}/long_model/long_expl_vde_forw.c', +] + +casadi_cost_y = [ + f'{gen}/long_cost/long_cost_y_fun.c', + f'{gen}/long_cost/long_cost_y_fun_jac_ut_xt.c', + f'{gen}/long_cost/long_cost_y_hess.c', +] + +casadi_cost_e = [ + f'{gen}/long_cost/long_cost_y_e_fun.c', + f'{gen}/long_cost/long_cost_y_e_fun_jac_ut_xt.c', + f'{gen}/long_cost/long_cost_y_e_hess.c', +] + +casadi_cost_0 = [ + f'{gen}/long_cost/long_cost_y_0_fun.c', + f'{gen}/long_cost/long_cost_y_0_fun_jac_ut_xt.c', + f'{gen}/long_cost/long_cost_y_0_hess.c', +] + +casadi_constraints = [ + f'{gen}/long_constraints/long_constr_h_fun.c', + f'{gen}/long_constraints/long_constr_h_fun_jac_uxt_zt.c', +] + +build_files = [f'{gen}/acados_solver_long.c'] + casadi_model + casadi_cost_y + casadi_cost_e + \ + casadi_cost_0 + casadi_constraints + +# extra generated files used to trigger a rebuild +generated_files = [ + f'{gen}/Makefile', + + f'{gen}/main_long.c', + f'{gen}/main_sim_long.c', + f'{gen}/acados_solver_long.h', + f'{gen}/acados_sim_solver_long.h', + f'{gen}/acados_sim_solver_long.c', + f'{gen}/acados_solver.pxd', + + f'{gen}/long_model/long_expl_vde_adj.c', + + f'{gen}/long_model/long_model.h', + f'{gen}/long_constraints/long_constraints.h', + f'{gen}/long_cost/long_cost.h', +] + build_files + +acados_include_dir = Dir(acados.INCLUDE_DIR) +acados_template_dir = Dir(acados.TEMPLATE_DIR) + +source_list = ['long_mpc.py', + '#openpilot/selfdrive/modeld/constants.py', + acados_include_dir.File('acados_c/ocp_nlp_interface.h'), + acados_template_dir.File('c_templates_tera/acados_solver.in.c'), +] + +lenv = env.Clone() +copied_acados_libs = [] +if arch != "Darwin": + for lib in ["libacados.so", "libblasfeo.so", "libhpipm.so", "libqpOASES_e.so.3.1"]: + copied_acados_libs += lenv.Command(f"{gen}/{lib}", Dir(acados.LIB_DIR).File(lib), [Mkdir(Dir(gen)), Copy("$TARGET", "$SOURCE")]) + lenv["RPATH"] += [lenv.Literal('\\$$ORIGIN')] +else: + acados_rel_path = Dir(gen).rel_path(Dir(acados.LIB_DIR)) + lenv["RPATH"] += [lenv.Literal(f'\\$$ORIGIN/{acados_rel_path}')] +lenv.Clean(generated_files, Dir(gen)) +generated_long = lenv.Command(generated_files, + source_list, + f"cd {Dir('.').abspath} && python3 long_mpc.py") +lenv.Depends(generated_long, [msgq_python, common_python]) + +lenv["CFLAGS"].append("-DACADOS_WITH_QPOASES") +lenv["CXXFLAGS"].append("-DACADOS_WITH_QPOASES") +lenv["CCFLAGS"].append("-Wno-unused") +if arch != "Darwin": + lenv["LINKFLAGS"].append("-Wl,--disable-new-dtags") +else: + lenv["LINKFLAGS"].append("-Wl,-install_name,@loader_path/libacados_ocp_solver_long.dylib") + lenv["LINKFLAGS"].append(f"-Wl,-rpath,@loader_path/{acados_rel_path}") +lib_solver = lenv.SharedLibrary(f"{gen}/acados_ocp_solver_long", + build_files, + LIBS=['m', 'acados', 'hpipm', 'blasfeo', 'qpOASES_e']) + +# generate cython stuff +acados_ocp_solver_pyx = acados_template_dir.File('acados_ocp_solver_pyx.pyx') +acados_ocp_solver_common = acados_template_dir.File('acados_solver_common.pxd') +libacados_ocp_solver_pxd = File(f'{gen}/acados_solver.pxd') +libacados_ocp_solver_c = File(f'{gen}/acados_ocp_solver_pyx.c') + +lenv2 = envCython.Clone() +lenv2["LIBPATH"] += [lib_solver[0].dir.abspath] +lenv2["RPATH"] += [lenv2.Literal('\\$$ORIGIN')] +lenv2.Command(libacados_ocp_solver_c, + [acados_ocp_solver_pyx, acados_ocp_solver_common, libacados_ocp_solver_pxd], + f'cython' + \ + f' -o {libacados_ocp_solver_c.get_labspath()}' + \ + f' -I {libacados_ocp_solver_pxd.get_dir().get_labspath()}' + \ + f' -I {acados_ocp_solver_common.get_dir().get_labspath()}' + \ + f' {acados_ocp_solver_pyx.get_labspath()}') +lib_cython = lenv2.Program(f'{gen}/acados_ocp_solver_pyx.so', [libacados_ocp_solver_c], LIBS=['acados_ocp_solver_long']) +lenv2.Depends(lib_cython, lib_solver) +lenv2.Depends(lib_cython, copied_acados_libs) +lenv2.Depends(libacados_ocp_solver_c, np_version) diff --git a/selfdrive/controls/lib/longitudinal_mpc_lib/__init__.py b/openpilot/selfdrive/controls/lib/longitudinal_mpc_lib/__init__.py similarity index 100% rename from selfdrive/controls/lib/longitudinal_mpc_lib/__init__.py rename to openpilot/selfdrive/controls/lib/longitudinal_mpc_lib/__init__.py diff --git a/openpilot/selfdrive/controls/lib/longitudinal_mpc_lib/long_mpc.py b/openpilot/selfdrive/controls/lib/longitudinal_mpc_lib/long_mpc.py new file mode 100755 index 0000000000..de1ba0c278 --- /dev/null +++ b/openpilot/selfdrive/controls/lib/longitudinal_mpc_lib/long_mpc.py @@ -0,0 +1,385 @@ +#!/usr/bin/env python3 +import os +import time +import numpy as np +from openpilot.cereal import log +from opendbc.car.interfaces import ACCEL_MIN, ACCEL_MAX +from openpilot.common.realtime import DT_MDL +from openpilot.common.swaglog import cloudlog +# WARNING: imports outside of constants will not trigger a rebuild +from openpilot.selfdrive.modeld.constants import index_function +from openpilot.selfdrive.controls.radard import _LEAD_ACCEL_TAU + +if __name__ == '__main__': # generating code + from acados.acados_template import AcadosModel, AcadosOcp, AcadosOcpSolver +else: + from openpilot.selfdrive.controls.lib.longitudinal_mpc_lib.c_generated_code.acados_ocp_solver_pyx import AcadosOcpSolverCython + +from casadi import SX, vertcat + +MODEL_NAME = 'long' +LONG_MPC_DIR = os.path.dirname(os.path.abspath(__file__)) +EXPORT_DIR = os.path.join(LONG_MPC_DIR, "c_generated_code") +JSON_FILE = os.path.join(LONG_MPC_DIR, "acados_ocp_long.json") + +LongitudinalPlanSource = log.LongitudinalPlan.LongitudinalPlanSource +MPC_SOURCES = (LongitudinalPlanSource.lead0, LongitudinalPlanSource.lead1, LongitudinalPlanSource.cruise) + +X_DIM = 3 +U_DIM = 1 +PARAM_DIM = 6 +COST_E_DIM = 5 +COST_DIM = COST_E_DIM + 1 +CONSTR_DIM = 4 + +X_EGO_OBSTACLE_COST = 3. +X_EGO_COST = 0. +V_EGO_COST = 0. +A_EGO_COST = 0. +J_EGO_COST = 5. +A_CHANGE_COST = 200. +DANGER_ZONE_COST = 100. +CRASH_DISTANCE = .25 +LEAD_DANGER_FACTOR = 0.75 +LIMIT_COST = 1e6 +ACADOS_SOLVER_TYPE = 'SQP_RTI' + +# Fewer timestamps don't hurt performance and lead to +# much better convergence of the MPC with low iterations +N = 12 +MAX_T = 10.0 +T_IDXS_LST = [index_function(idx, max_val=MAX_T, max_idx=N) for idx in range(N+1)] + +T_IDXS = np.array(T_IDXS_LST) +FCW_IDXS = T_IDXS < 5.0 +T_DIFFS = np.diff(T_IDXS, prepend=[0.]) +COMFORT_BRAKE = 2.5 +STOP_DISTANCE = 6.0 +CRUISE_MIN_ACCEL = -1.2 +CRUISE_MAX_ACCEL = 1.6 +MIN_X_LEAD_FACTOR = 0.5 + +def get_jerk_factor(personality=log.LongitudinalPersonality.standard): + if personality==log.LongitudinalPersonality.relaxed: + return 1.0 + elif personality==log.LongitudinalPersonality.standard: + return 1.0 + elif personality==log.LongitudinalPersonality.aggressive: + return 0.5 + else: + raise NotImplementedError("Longitudinal personality not supported") + + +def get_T_FOLLOW(personality=log.LongitudinalPersonality.standard): + if personality==log.LongitudinalPersonality.relaxed: + return 1.75 + elif personality==log.LongitudinalPersonality.standard: + return 1.45 + elif personality==log.LongitudinalPersonality.aggressive: + return 1.25 + else: + raise NotImplementedError("Longitudinal personality not supported") + +def get_stopped_equivalence_factor(v_lead): + return (v_lead**2) / (2 * COMFORT_BRAKE) + +def get_safe_obstacle_distance(v_ego, t_follow): + return (v_ego**2) / (2 * COMFORT_BRAKE) + t_follow * v_ego + STOP_DISTANCE + +def gen_long_model(): + model = AcadosModel() + model.name = MODEL_NAME + + # states + x_ego, v_ego, a_ego = SX.sym('x_ego'), SX.sym('v_ego'), SX.sym('a_ego') + model.x = vertcat(x_ego, v_ego, a_ego) + + # controls + j_ego = SX.sym('j_ego') + model.u = vertcat(j_ego) + + # xdot + x_ego_dot = SX.sym('x_ego_dot') + v_ego_dot = SX.sym('v_ego_dot') + a_ego_dot = SX.sym('a_ego_dot') + model.xdot = vertcat(x_ego_dot, v_ego_dot, a_ego_dot) + + # live parameters + a_min = SX.sym('a_min') + a_max = SX.sym('a_max') + x_obstacle = SX.sym('x_obstacle') + a_prev = SX.sym('a_prev') + lead_t_follow = SX.sym('lead_t_follow') + lead_danger_factor = SX.sym('lead_danger_factor') + model.p = vertcat(a_min, a_max, x_obstacle, a_prev, lead_t_follow, lead_danger_factor) + + # dynamics model + f_expl = vertcat(v_ego, a_ego, j_ego) + model.f_impl_expr = model.xdot - f_expl + model.f_expl_expr = f_expl + return model + +def gen_long_ocp(): + ocp = AcadosOcp() + ocp.model = gen_long_model() + + Tf = T_IDXS[-1] + + # set dimensions + ocp.dims.N = N + + # set cost module + ocp.cost.cost_type = 'NONLINEAR_LS' + ocp.cost.cost_type_e = 'NONLINEAR_LS' + + QR = np.zeros((COST_DIM, COST_DIM)) + Q = np.zeros((COST_E_DIM, COST_E_DIM)) + + ocp.cost.W = QR + ocp.cost.W_e = Q + + x_ego, v_ego, a_ego = ocp.model.x[0], ocp.model.x[1], ocp.model.x[2] + j_ego = ocp.model.u[0] + + a_min, a_max = ocp.model.p[0], ocp.model.p[1] + x_obstacle = ocp.model.p[2] + a_prev = ocp.model.p[3] + lead_t_follow = ocp.model.p[4] + lead_danger_factor = ocp.model.p[5] + + ocp.cost.yref = np.zeros((COST_DIM, )) + ocp.cost.yref_e = np.zeros((COST_E_DIM, )) + + desired_dist_comfort = get_safe_obstacle_distance(v_ego, lead_t_follow) + + # The main cost in normal operation is how close you are to the "desired" distance + # from an obstacle at every timestep. This obstacle can be a lead car + # or other object. In e2e mode we can use x_position targets as a cost + # instead. + costs = [((x_obstacle - x_ego) - (desired_dist_comfort)) / (v_ego + 10.), + x_ego, + v_ego, + a_ego, + a_ego - a_prev, + j_ego] + ocp.model.cost_y_expr = vertcat(*costs) + ocp.model.cost_y_expr_e = vertcat(*costs[:-1]) + + # Constraints on speed, acceleration and desired distance to + # the obstacle, which is treated as a slack constraint so it + # behaves like an asymmetrical cost. + constraints = vertcat(v_ego, + (a_ego - a_min), + (a_max - a_ego), + ((x_obstacle - x_ego) - lead_danger_factor * (desired_dist_comfort)) / (v_ego + 10.)) + ocp.model.con_h_expr = constraints + + x0 = np.zeros(X_DIM) + ocp.constraints.x0 = x0 + ocp.parameter_values = np.array([-1.2, 1.2, 0.0, 0.0, get_T_FOLLOW(), LEAD_DANGER_FACTOR]) + + + # We put all constraint cost weights to 0 and only set them at runtime + cost_weights = np.zeros(CONSTR_DIM) + ocp.cost.zl = cost_weights + ocp.cost.Zl = cost_weights + ocp.cost.Zu = cost_weights + ocp.cost.zu = cost_weights + + ocp.constraints.lh = np.zeros(CONSTR_DIM) + ocp.constraints.uh = 1e4*np.ones(CONSTR_DIM) + ocp.constraints.idxsh = np.arange(CONSTR_DIM) + + # The HPIPM solver can give decent solutions even when it is stopped early + # Which is critical for our purpose where compute time is strictly bounded + # We use HPIPM in the SPEED_ABS mode, which ensures fastest runtime. This + # does not cause issues since the problem is well bounded. + ocp.solver_options.qp_solver = 'PARTIAL_CONDENSING_HPIPM' + ocp.solver_options.hessian_approx = 'GAUSS_NEWTON' + ocp.solver_options.integrator_type = 'ERK' + ocp.solver_options.nlp_solver_type = ACADOS_SOLVER_TYPE + ocp.solver_options.qp_solver_cond_N = 1 + + # More iterations take too much time and less lead to inaccurate convergence in + # some situations. Ideally we would run just 1 iteration to ensure fixed runtime. + ocp.solver_options.qp_solver_iter_max = 10 + ocp.solver_options.qp_tol = 1e-3 + + # set prediction horizon + ocp.solver_options.tf = Tf + ocp.solver_options.shooting_nodes = T_IDXS + + ocp.code_export_directory = EXPORT_DIR + return ocp + + +class LongitudinalMpc: + def __init__(self, dt=DT_MDL): + self.dt = dt + self.solver = AcadosOcpSolverCython(MODEL_NAME, ACADOS_SOLVER_TYPE, N) + self.reset() + self.source = LongitudinalPlanSource.cruise + + def reset(self): + self.solver.reset() + + self.x_sol = np.zeros((N+1, X_DIM)) + self.u_sol = np.zeros((N, 1)) + self.v_solution = np.zeros(N+1) + self.a_solution = np.zeros(N+1) + self.j_solution = np.zeros(N) + self.a_prev = np.array(self.a_solution) + self.yref = np.zeros((N+1, COST_DIM)) + + for i in range(N): + self.solver.cost_set(i, "yref", self.yref[i]) + self.solver.cost_set(N, "yref", self.yref[N][:COST_E_DIM]) + + self.params = np.zeros((N+1, PARAM_DIM)) + for i in range(N+1): + self.solver.set(i, 'x', np.zeros(X_DIM)) + + self.last_cloudlog_t = 0 + self.crash_cnt = 0.0 + self.solution_status = 0 + # timers + self.solve_time = 0.0 + self.x0 = np.zeros(X_DIM) + self.set_weights() + + def set_cost_weights(self, cost_weights, constraint_cost_weights): + W = np.asfortranarray(np.diag(cost_weights)) + for i in range(N): + # TODO don't hardcode A_CHANGE_COST idx + # reduce the cost on (a-a_prev) later in the horizon. + W[4,4] = cost_weights[4] * np.interp(T_IDXS[i], [0.0, 1.0, 2.0], [1.0, 1.0, 0.0]) + self.solver.cost_set(i, 'W', W) + # Setting the slice without the copy make the array not contiguous, + # causing issues with the C interface. + self.solver.cost_set(N, 'W', np.copy(W[:COST_E_DIM, :COST_E_DIM])) + + # Set L2 slack cost on lower bound constraints + Zl = np.array(constraint_cost_weights) + for i in range(N): + self.solver.cost_set(i, 'Zl', Zl) + + def set_weights(self, prev_accel_constraint=True, personality=log.LongitudinalPersonality.standard): + jerk_factor = get_jerk_factor(personality) + a_change_cost = A_CHANGE_COST if prev_accel_constraint else 0 + cost_weights = [X_EGO_OBSTACLE_COST, X_EGO_COST, V_EGO_COST, A_EGO_COST, jerk_factor * a_change_cost, jerk_factor * J_EGO_COST] + constraint_cost_weights = [LIMIT_COST, LIMIT_COST, LIMIT_COST, DANGER_ZONE_COST] + self.set_cost_weights(cost_weights, constraint_cost_weights) + + def set_cur_state(self, v, a): + v_prev = self.x0[1] + self.x0[1] = v + self.x0[2] = a + if abs(v_prev - v) > 2.: # probably only helps if v < v_prev + for i in range(N+1): + self.solver.set(i, 'x', self.x0) + + @staticmethod + def extrapolate_lead(x_lead, v_lead, a_lead, a_lead_tau): + a_lead_traj = a_lead * np.exp(-a_lead_tau * (T_IDXS**2)/2.) + v_lead_traj = np.clip(v_lead + np.cumsum(T_DIFFS * a_lead_traj), 0.0, 1e8) + x_lead_traj = x_lead + np.cumsum(T_DIFFS * v_lead_traj) + lead_xv = np.column_stack((x_lead_traj, v_lead_traj)) + return lead_xv + + def process_lead(self, lead): + v_ego = self.x0[1] + if lead is not None and lead.present: + x_lead = lead.dRel + v_lead = lead.vLead + a_lead = lead.aLeadK + a_lead_tau = lead.aLeadTau + else: + # Fake a fast lead car, so mpc can keep running in the same mode + x_lead = 50.0 + v_lead = v_ego + 10.0 + a_lead = 0.0 + a_lead_tau = _LEAD_ACCEL_TAU + + # MPC will not converge if immediate crash is expected + # Clip lead distance to what is still possible to brake for + min_x_lead = MIN_X_LEAD_FACTOR * (v_ego + v_lead) * (v_ego - v_lead) / (-ACCEL_MIN * 2) + x_lead = np.clip(x_lead, min_x_lead, 1e8) + v_lead = np.clip(v_lead, 0.0, 1e8) + a_lead = np.clip(a_lead, -10., 5.) + lead_xv = self.extrapolate_lead(x_lead, v_lead, a_lead, a_lead_tau) + return lead_xv + + def update(self, radarstate, v_cruise, personality=log.LongitudinalPersonality.standard): + t_follow = get_T_FOLLOW(personality) + v_ego = self.x0[1] + + lead_xv_0 = self.process_lead(radarstate.leadOne) + lead_xv_1 = self.process_lead(radarstate.leadTwo) + + # To estimate a safe distance from a moving lead, we calculate how much stopping + # distance that lead needs as a minimum. We can add that to the current distance + # and then treat that as a stopped car/obstacle at this new distance. + lead_0_obstacle = lead_xv_0[:,0] + get_stopped_equivalence_factor(lead_xv_0[:,1]) + lead_1_obstacle = lead_xv_1[:,0] + get_stopped_equivalence_factor(lead_xv_1[:,1]) + + # Fake an obstacle for cruise, this ensures smooth acceleration to set speed + # when the leads are no factor. + v_lower = v_ego + (T_IDXS * CRUISE_MIN_ACCEL * 1.05) + # TODO does this make sense when max_a is negative? + v_upper = v_ego + (T_IDXS * CRUISE_MAX_ACCEL * 1.05) + v_cruise_clipped = np.clip(v_cruise * np.ones(N+1), v_lower, v_upper) + cruise_obstacle = np.cumsum(T_DIFFS * v_cruise_clipped) + get_safe_obstacle_distance(v_cruise_clipped, t_follow) + + x_obstacles = np.column_stack([lead_0_obstacle, lead_1_obstacle, cruise_obstacle]) + self.source = MPC_SOURCES[np.argmin(x_obstacles[0])] + + self.yref[:,:] = 0.0 + for i in range(N): + self.solver.set(i, "yref", self.yref[i]) + self.solver.set(N, "yref", self.yref[N][:COST_E_DIM]) + + self.params[:,0] = ACCEL_MIN + self.params[:,1] = ACCEL_MAX + self.params[:,2] = np.min(x_obstacles, axis=1) + self.params[:,3] = np.copy(self.a_prev) + self.params[:,4] = t_follow + self.params[:,5] = LEAD_DANGER_FACTOR + + self.run() + if (np.any(lead_xv_0[FCW_IDXS,0] - self.x_sol[FCW_IDXS,0] < CRASH_DISTANCE) and + radarstate.leadOne.modelProb > 0.9): + self.crash_cnt += 1 + else: + self.crash_cnt = 0 + + def run(self): + for i in range(N+1): + self.solver.set(i, 'p', self.params[i]) + self.solver.constraints_set(0, "lbx", self.x0) + self.solver.constraints_set(0, "ubx", self.x0) + + self.solution_status = self.solver.solve() + self.solve_time = float(self.solver.get_stats('time_tot')[0]) + + for i in range(N+1): + self.x_sol[i] = self.solver.get(i, 'x') + for i in range(N): + self.u_sol[i] = self.solver.get(i, 'u') + + self.v_solution = self.x_sol[:,1] + self.a_solution = self.x_sol[:,2] + self.j_solution = self.u_sol[:,0] + + self.a_prev = np.interp(T_IDXS + self.dt, T_IDXS, self.a_solution) + + t = time.monotonic() + if self.solution_status != 0: + if t > self.last_cloudlog_t + 5.0: + self.last_cloudlog_t = t + cloudlog.warning(f"Long mpc reset, solution_status: {self.solution_status}") + self.reset() + + +if __name__ == "__main__": + ocp = gen_long_ocp() + AcadosOcpSolver.generate(ocp, json_file=JSON_FILE) diff --git a/openpilot/selfdrive/controls/lib/longitudinal_planner.py b/openpilot/selfdrive/controls/lib/longitudinal_planner.py new file mode 100755 index 0000000000..6eaed7370d --- /dev/null +++ b/openpilot/selfdrive/controls/lib/longitudinal_planner.py @@ -0,0 +1,183 @@ +#!/usr/bin/env python3 +import math +import numpy as np + +import openpilot.cereal.messaging as messaging +from opendbc.car.interfaces import ACCEL_MIN, ACCEL_MAX +from openpilot.common.constants import CV +from openpilot.common.filter_simple import FirstOrderFilter +from openpilot.common.realtime import DT_MDL +from openpilot.selfdrive.modeld.constants import ModelConstants +from openpilot.selfdrive.controls.lib.longcontrol import LongCtrlState +from openpilot.selfdrive.controls.lib.longitudinal_mpc_lib.long_mpc import LongitudinalMpc, LongitudinalPlanSource +from openpilot.selfdrive.controls.lib.longitudinal_mpc_lib.long_mpc import T_IDXS as T_IDXS_MPC +from openpilot.selfdrive.controls.lib.drive_helpers import CONTROL_N, get_accel_from_plan +from openpilot.selfdrive.car.cruise import V_CRUISE_MAX, V_CRUISE_UNSET +from openpilot.common.swaglog import cloudlog + +from openpilot.sunnypilot.selfdrive.controls.lib.longitudinal_planner import LongitudinalPlannerSP + +A_CRUISE_MAX_VALS = [1.6, 1.2, 0.8, 0.6] +A_CRUISE_MAX_BP = [0., 10.0, 25., 40.] +CONTROL_N_T_IDX = ModelConstants.T_IDXS[:CONTROL_N] +ALLOW_THROTTLE_THRESHOLD = 0.4 +MIN_ALLOW_THROTTLE_SPEED = 2.5 + +# Lookup table for turns +_A_TOTAL_MAX_V = [1.7, 3.2] +_A_TOTAL_MAX_BP = [20., 40.] + +def get_max_accel(v_ego): + return np.interp(v_ego, A_CRUISE_MAX_BP, A_CRUISE_MAX_VALS) + +def get_coast_accel(pitch): + return np.sin(pitch) * -5.65 - 0.3 # fitted from data using xx/projects/allow_throttle/compute_coast_accel.py + +def limit_accel_in_turns(v_ego, angle_steers, a_target, CP): + """ + This function returns a limited long acceleration allowed, depending on the existing lateral acceleration + this should avoid accelerating when losing the target in turns + """ + # FIXME: This function to calculate lateral accel is incorrect and should use the VehicleModel + # The lookup table for turns should also be updated if we do this + a_total_max = np.interp(v_ego, _A_TOTAL_MAX_BP, _A_TOTAL_MAX_V) + a_y = v_ego ** 2 * angle_steers * CV.DEG_TO_RAD / (CP.steerRatio * CP.wheelbase) + a_x_allowed = math.sqrt(max(a_total_max ** 2 - a_y ** 2, 0.)) + + return [a_target[0], min(a_target[1], a_x_allowed)] + + +class LongitudinalPlanner(LongitudinalPlannerSP): + def __init__(self, CP, CP_SP, init_v=0.0, init_a=0.0, dt=DT_MDL): + self.CP = CP + self.mpc = LongitudinalMpc(dt=dt) + LongitudinalPlannerSP.__init__(self, self.CP, CP_SP, self.mpc) + self.fcw = False + self.dt = dt + self.allow_throttle = True + + self.a_desired = init_a + self.v_desired_filter = FirstOrderFilter(init_v, 2.0, self.dt) + self.prev_accel_clip = [ACCEL_MIN, ACCEL_MAX] + self.output_a_target = 0.0 + self.output_should_stop = False + + self.v_desired_trajectory = np.zeros(CONTROL_N) + self.a_desired_trajectory = np.zeros(CONTROL_N) + self.j_desired_trajectory = np.zeros(CONTROL_N) + + def update(self, sm): + LongitudinalPlannerSP.update(self, sm) + + if len(sm['carControl'].orientationNED) == 3: + accel_coast = get_coast_accel(sm['carControl'].orientationNED[1]) + else: + accel_coast = ACCEL_MAX + + v_ego = sm['carState'].vEgo + v_cruise_kph = min(sm['carState'].vCruise, V_CRUISE_MAX) + v_cruise = v_cruise_kph * CV.KPH_TO_MS + v_cruise_initialized = sm['carState'].vCruise != V_CRUISE_UNSET + + long_control_off = sm['controlsState'].longControlState == LongCtrlState.off + force_slow_decel = sm['controlsState'].forceDecel + + # Reset current state when not engaged, or user is controlling the speed + reset_state = long_control_off if self.CP.openpilotLongitudinalControl else not sm['selfdriveState'].enabled + # PCM cruise speed may be updated a few cycles later, check if initialized + reset_state = reset_state or not v_cruise_initialized + + # No change cost when user is controlling the speed, or when standstill + prev_accel_constraint = not (reset_state or sm['carState'].standstill) + + accel_clip = [ACCEL_MIN, get_max_accel(v_ego)] + steer_angle_without_offset = sm['carState'].steeringAngleDeg - sm['liveParameters'].angleOffsetDeg + accel_clip = limit_accel_in_turns(v_ego, steer_angle_without_offset, accel_clip, self.CP) + + if reset_state: + self.v_desired_filter.x = v_ego + # Clip aEgo to cruise limits to prevent large accelerations when becoming active + self.a_desired = np.clip(sm['carState'].aEgo, accel_clip[0], accel_clip[1]) + + # Prevent divergence, smooth in current v_ego + self.v_desired_filter.x = max(0.0, self.v_desired_filter.update(v_ego)) + throttle_probs = sm['modelV2'].meta.disengagePredictions.gasPressProbs + throttle_prob = throttle_probs[1] if len(throttle_probs) > 1 else 1.0 + # Don't clip at low speeds since throttle_prob doesn't account for creep + self.allow_throttle = throttle_prob > ALLOW_THROTTLE_THRESHOLD or v_ego <= MIN_ALLOW_THROTTLE_SPEED + + if not self.allow_throttle: + clipped_accel_coast = max(accel_coast, accel_clip[0]) + clipped_accel_coast_interp = np.interp(v_ego, [MIN_ALLOW_THROTTLE_SPEED, MIN_ALLOW_THROTTLE_SPEED*2], [accel_clip[1], clipped_accel_coast]) + accel_clip[1] = min(accel_clip[1], clipped_accel_coast_interp) + + # Get new v_cruise and a_desired from Smart Cruise Control and Speed Limit Assist + v_cruise, self.a_desired = LongitudinalPlannerSP.update_targets(self, sm, self.v_desired_filter.x, self.a_desired, v_cruise) + + if force_slow_decel: + v_cruise = 0.0 + + self.mpc.set_weights(prev_accel_constraint, personality=sm['selfdriveState'].personality) + self.mpc.set_cur_state(self.v_desired_filter.x, self.a_desired) + self.mpc.update(sm['radarState'], v_cruise, personality=sm['selfdriveState'].personality) + + self.v_desired_trajectory = np.interp(CONTROL_N_T_IDX, T_IDXS_MPC, self.mpc.v_solution) + self.a_desired_trajectory = np.interp(CONTROL_N_T_IDX, T_IDXS_MPC, self.mpc.a_solution) + self.j_desired_trajectory = np.interp(CONTROL_N_T_IDX, T_IDXS_MPC[:-1], self.mpc.j_solution) + + # TODO counter is only needed because radar is glitchy, remove once radar is gone + self.fcw = self.mpc.crash_cnt > 2 and not sm['carState'].standstill + if self.fcw: + cloudlog.info("FCW triggered") + + # Interpolate 0.05 seconds and save as starting point for next iteration + a_prev = self.a_desired + self.a_desired = float(np.interp(self.dt, CONTROL_N_T_IDX, self.a_desired_trajectory)) + self.v_desired_filter.x = self.v_desired_filter.x + self.dt * (self.a_desired + a_prev) / 2.0 + + action_t = self.CP.longitudinalActuatorDelay + DT_MDL + output_a_target_mpc, output_should_stop_mpc = get_accel_from_plan(self.v_desired_trajectory, self.a_desired_trajectory, CONTROL_N_T_IDX, + action_t=action_t) + output_a_target_e2e = sm['modelV2'].action.desiredAcceleration + output_should_stop_e2e = sm['modelV2'].action.shouldStop + + if self.is_e2e(sm): + output_a_target = min(output_a_target_e2e, output_a_target_mpc) + self.output_should_stop = output_should_stop_e2e or output_should_stop_mpc + if output_a_target < output_a_target_mpc: + self.mpc.source = LongitudinalPlanSource.e2e + else: + output_a_target = output_a_target_mpc + self.output_should_stop = output_should_stop_mpc + + for idx in range(2): + accel_clip[idx] = np.clip(accel_clip[idx], self.prev_accel_clip[idx] - 0.05, self.prev_accel_clip[idx] + 0.05) + self.output_a_target = np.clip(output_a_target, accel_clip[0], accel_clip[1]) + self.prev_accel_clip = accel_clip + + def publish(self, sm, pm): + plan_send = messaging.new_message('longitudinalPlan') + + plan_send.valid = sm.all_checks(service_list=['carState', 'controlsState', 'selfdriveState', 'radarState']) + + longitudinalPlan = plan_send.longitudinalPlan + longitudinalPlan.modelMonoTime = sm.logMonoTime['modelV2'] + longitudinalPlan.processingDelay = (plan_send.logMonoTime / 1e9) - sm.logMonoTime['modelV2'] + longitudinalPlan.solverExecutionTime = self.mpc.solve_time + + longitudinalPlan.speeds = self.v_desired_trajectory.tolist() + longitudinalPlan.accels = self.a_desired_trajectory.tolist() + longitudinalPlan.jerks = self.j_desired_trajectory.tolist() + + longitudinalPlan.hasLead = sm['radarState'].leadOne.present + longitudinalPlan.longitudinalPlanSource = self.mpc.source + longitudinalPlan.fcw = self.fcw + + longitudinalPlan.aTarget = float(self.output_a_target) + longitudinalPlan.shouldStop = bool(self.output_should_stop) + longitudinalPlan.allowBrake = True + longitudinalPlan.allowThrottle = bool(self.allow_throttle) + + pm.send('longitudinalPlan', plan_send) + + self.publish_longitudinal_plan_sp(sm, pm) diff --git a/openpilot/selfdrive/controls/plannerd.py b/openpilot/selfdrive/controls/plannerd.py new file mode 100755 index 0000000000..3a05ea174b --- /dev/null +++ b/openpilot/selfdrive/controls/plannerd.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python3 +from openpilot.cereal import custom +from opendbc.car.structs import car +from openpilot.common.gps import get_gps_location_service +from openpilot.common.params import Params +from openpilot.common.realtime import Priority, config_realtime_process +from openpilot.common.swaglog import cloudlog +from openpilot.selfdrive.controls.lib.ldw import LaneDepartureWarning +from openpilot.selfdrive.controls.lib.longitudinal_planner import LongitudinalPlanner +import openpilot.cereal.messaging as messaging + + +def main(): + config_realtime_process(5, Priority.CTRL_LOW) + + cloudlog.info("plannerd is waiting for CarParams") + params = Params() + CP = messaging.log_from_bytes(params.get("CarParams", block=True), car.CarParams) + cloudlog.info("plannerd got CarParams: %s", CP.brand) + + cloudlog.info("plannerd is waiting for CarParamsSP") + CP_SP = messaging.log_from_bytes(params.get("CarParamsSP", block=True), custom.CarParamsSP) + cloudlog.info("plannerd got CarParamsSP") + + gps_location_service = get_gps_location_service(params) + ignore_services = ["liveMapDataSP", gps_location_service] + + ldw = LaneDepartureWarning() + longitudinal_planner = LongitudinalPlanner(CP, CP_SP) + pm = messaging.PubMaster(['longitudinalPlan', 'driverAssistance', 'longitudinalPlanSP']) + sm = messaging.SubMaster(['carControl', 'carState', 'controlsState', 'liveParameters', 'radarState', 'modelV2', 'selfdriveState', + 'liveMapDataSP', 'carStateSP', gps_location_service], + poll='carState', ignore_alive=ignore_services, ignore_avg_freq=ignore_services, ignore_valid=ignore_services) + + while True: + sm.update() + longitudinal_planner.sla.update_car_state(sm['carState']) + if sm.updated['modelV2']: + longitudinal_planner.update(sm) + longitudinal_planner.publish(sm, pm) + + ldw.update(sm.frame, sm['modelV2'], sm['carState'], sm['carControl']) + msg = messaging.new_message('driverAssistance') + msg.valid = sm.all_checks(['carState', 'carControl', 'modelV2', 'liveParameters']) + msg.driverAssistance.leftLaneDeparture = ldw.left + msg.driverAssistance.rightLaneDeparture = ldw.right + pm.send('driverAssistance', msg) + + +if __name__ == "__main__": + main() diff --git a/selfdrive/controls/radard.py b/openpilot/selfdrive/controls/radard.py similarity index 86% rename from selfdrive/controls/radard.py rename to openpilot/selfdrive/controls/radard.py index bee4244054..5db5865e75 100755 --- a/selfdrive/controls/radard.py +++ b/openpilot/selfdrive/controls/radard.py @@ -5,7 +5,8 @@ from collections import deque from typing import Any import capnp -from cereal import messaging, log, car, custom +from openpilot.cereal import messaging, log, custom +from opendbc.car.structs import car from openpilot.common.filter_simple import FirstOrderFilter from openpilot.common.params import Params from openpilot.common.realtime import DT_MDL, Priority, config_realtime_process @@ -26,7 +27,6 @@ SPEED, ACCEL = 0, 1 # Kalman filter states enum # stationary qualification parameters V_EGO_STATIONARY = 4. # no stationary object flag below this speed -RADAR_TO_CENTER = 2.7 # (deprecated) RADAR is ~ 2.7m ahead from center of car RADAR_TO_CAMERA = 1.52 # RADAR is ~ 1.5m ahead from center of mesh frame @@ -62,13 +62,12 @@ class Track: self.K_K = kalman_params.K self.kf = KF1D([[v_lead], [0.0]], self.K_A, self.K_C, self.K_K) - def update(self, d_rel: float, y_rel: float, v_rel: float, v_lead: float, measured: float): + def update(self, d_rel: float, y_rel: float, v_rel: float, v_lead: float): # relative values, copy self.dRel = d_rel # LONG_DIST self.yRel = y_rel # -LAT_DIST self.vRel = v_rel # REL_SPEED self.vLead = v_lead - self.measured = measured # measured or estimate # computed velocity and accelerations if self.cnt > 0: @@ -94,8 +93,7 @@ class Track: "vLeadK": float(self.vLeadK), "aLeadK": float(self.aLeadK), "aLeadTau": float(self.aLeadTau.x), - "status": True, - "fcw": self.is_potential_fcw(model_prob), + "present": True, "modelProb": model_prob, "radar": True, "radarTrackId": self.identifier, @@ -106,9 +104,6 @@ class Track: # Radar points closer than 0.75, are almost always glitches on toyota radars return abs(self.yRel) < 1.0 and (v_ego < V_EGO_STATIONARY) and (0.75 < self.dRel < 25) - def is_potential_fcw(self, model_prob: float): - return model_prob > .9 - def __str__(self): ret = f"x: {self.dRel:4.1f} y: {self.yRel:4.1f} v: {self.vRel:4.1f} a: {self.aLeadK:4.1f}" return ret @@ -142,7 +137,7 @@ def match_vision_to_track(v_ego: float, lead: capnp._DynamicStructReader, tracks return None -def get_RadarState_from_vision(lead_msg: capnp._DynamicStructReader, v_ego: float, model_v_ego: float): +def get_RadarState_from_vision(lead_msg: capnp._DynamicStructReader, v_ego: float, model_v_ego: float, lead_prob: float): lead_v_rel_pred = lead_msg.v[0] - model_v_ego return { "dRel": float(lead_msg.x[0] - RADAR_TO_CAMERA), @@ -152,28 +147,28 @@ def get_RadarState_from_vision(lead_msg: capnp._DynamicStructReader, v_ego: floa "vLeadK": float(v_ego + lead_v_rel_pred), "aLeadK": float(lead_msg.a[0]), "aLeadTau": 0.3, - "fcw": False, - "modelProb": float(lead_msg.prob), - "status": True, + "modelProb": float(lead_prob), + "present": True, "radar": False, "radarTrackId": -1, } def get_lead(v_ego: float, ready: bool, tracks: dict[int, Track], lead_msg: capnp._DynamicStructReader, - model_v_ego: float, CP: structs.CarParams, CP_SP: structs.CarParamsSP, low_speed_override: bool = True) -> dict[str, Any]: + model_v_ego: float, lead_prob: float, CP: structs.CarParams, CP_SP: structs.CarParamsSP, + low_speed_override: bool = True) -> dict[str, Any]: # Determine leads, this is where the essential logic happens - if len(tracks) > 0 and ready and lead_msg.prob > .5: + if len(tracks) > 0 and ready and lead_prob > .5: track = match_vision_to_track(v_ego, lead_msg, tracks) else: track = None - lead_dict = {'status': False} + lead_dict = {'present': False} if track is not None: - lead_dict = track.get_RadarState(lead_msg.prob) + lead_dict = track.get_RadarState(lead_prob) lead_dict = get_custom_yrel(CP, CP_SP, lead_dict, lead_msg) - elif (track is None) and ready and (lead_msg.prob > .5): - lead_dict = get_RadarState_from_vision(lead_msg, v_ego, model_v_ego) + elif (track is None) and ready and (lead_prob > .5): + lead_dict = get_RadarState_from_vision(lead_msg, v_ego, model_v_ego, lead_prob) if low_speed_override: low_speed_tracks = [c for c in tracks.values() if c.potential_low_speed_lead(v_ego)] @@ -181,7 +176,7 @@ def get_lead(v_ego: float, ready: bool, tracks: dict[int, Track], lead_msg: capn closest_track = min(low_speed_tracks, key=lambda c: c.dRel) # Only choose new track if it is actually closer than the previous one - if (not lead_dict['status']) or (closest_track.dRel < lead_dict['dRel']): + if (not lead_dict['present']) or (closest_track.dRel < lead_dict['dRel']): lead_dict = closest_track.get_RadarState() return lead_dict @@ -205,6 +200,7 @@ class RadarD: self.tracks: dict[int, Track] = {} self.kalman_params = KalmanParams(DT_MDL) + self.lead_prob_filters = [FirstOrderFilter(0.0, 0.2, DT_MDL) for _ in range(2)] self.v_ego = 0.0 self.v_ego_hist = deque([0.0], maxlen=int(round(delay / DT_MDL))+1) @@ -224,7 +220,7 @@ class RadarD: self.v_ego_hist.append(self.v_ego) self.last_v_ego_frame = sm.recv_frame['carState'] - ar_pts = {pt.trackId: [pt.dRel, pt.yRel, pt.vRel, pt.measured] for pt in rr.points} + ar_pts = {pt.trackId: [pt.dRel, pt.yRel, pt.vRel] for pt in rr.points} # *** remove missing points from meta data *** for ids in list(self.tracks.keys()): @@ -241,14 +237,13 @@ class RadarD: # create the track if it doesn't exist or it's a new track if ids not in self.tracks: self.tracks[ids] = Track(ids, v_lead, self.kalman_params) - self.tracks[ids].update(rpt[0], rpt[1], rpt[2], v_lead, rpt[3]) + self.tracks[ids].update(rpt[0], rpt[1], rpt[2], v_lead) # *** publish radarState *** self.radar_state_valid = sm.all_checks() self.radar_state = log.RadarState.new_message() self.radar_state.mdMonoTime = sm.logMonoTime['modelV2'] self.radar_state.radarErrors = rr.errors - self.radar_state.carStateMonoTime = sm.logMonoTime['carState'] if len(sm['modelV2'].velocity.x): model_v_ego = sm['modelV2'].velocity.x[0] @@ -256,8 +251,18 @@ class RadarD: model_v_ego = self.v_ego leads_v3 = sm['modelV2'].leadsV3 if len(leads_v3) > 1: - self.radar_state.leadOne = get_lead(self.v_ego, self.ready, self.tracks, leads_v3[0], model_v_ego, self.CP, self.CP_SP, low_speed_override=True) - self.radar_state.leadTwo = get_lead(self.v_ego, self.ready, self.tracks, leads_v3[1], model_v_ego, self.CP, self.CP_SP, low_speed_override=False) + for i in range(2): + # Asymmetric filter on lead prob to keep lead when uncertain + lead_prob = leads_v3[i].prob + if lead_prob > self.lead_prob_filters[i].x: + self.lead_prob_filters[i].x = lead_prob + else: + self.lead_prob_filters[i].update(lead_prob) + + self.radar_state.leadOne = get_lead(self.v_ego, self.ready, self.tracks, leads_v3[0], model_v_ego, self.lead_prob_filters[0].x, + self.CP, self.CP_SP, low_speed_override=True) + self.radar_state.leadTwo = get_lead(self.v_ego, self.ready, self.tracks, leads_v3[1], model_v_ego, self.lead_prob_filters[1].x, + self.CP, self.CP_SP, low_speed_override=False) def publish(self, pm: messaging.PubMaster): assert self.radar_state is not None diff --git a/selfdrive/controls/lib/tests/__init__.py b/openpilot/selfdrive/controls/tests/__init__.py similarity index 100% rename from selfdrive/controls/lib/tests/__init__.py rename to openpilot/selfdrive/controls/tests/__init__.py diff --git a/openpilot/selfdrive/controls/tests/test_following_distance.py b/openpilot/selfdrive/controls/tests/test_following_distance.py new file mode 100644 index 0000000000..fcabce0387 --- /dev/null +++ b/openpilot/selfdrive/controls/tests/test_following_distance.py @@ -0,0 +1,46 @@ +import pytest +import itertools +from openpilot.common.parameterized import parameterized_class + +from openpilot.cereal import log + +from openpilot.selfdrive.controls.lib.longitudinal_mpc_lib.long_mpc import get_safe_obstacle_distance, get_stopped_equivalence_factor, get_T_FOLLOW +from openpilot.selfdrive.test.longitudinal_maneuvers.maneuver import Maneuver + + +def desired_follow_distance(v_ego, v_lead, t_follow=None): + if t_follow is None: + t_follow = get_T_FOLLOW() + return get_safe_obstacle_distance(v_ego, t_follow) - get_stopped_equivalence_factor(v_lead) + +def run_following_distance_simulation(v_lead, t_end=100.0, e2e=False, personality=0): + man = Maneuver( + '', + duration=t_end, + initial_speed=float(v_lead), + lead_relevancy=True, + initial_distance_lead=100, + speed_lead_values=[v_lead], + breakpoints=[0.], + e2e=e2e, + personality=personality, + ) + valid, output = man.evaluate() + assert valid + return output[-1,2] - output[-1,1] + + +@parameterized_class(("e2e", "personality", "speed"), itertools.product( + [True, False], # e2e + [log.LongitudinalPersonality.relaxed, # personality + log.LongitudinalPersonality.standard, + log.LongitudinalPersonality.aggressive], + [0,10,35])) # speed +class TestFollowingDistance: + def test_following_distance(self): + v_lead = float(self.speed) + simulation_steady_state = run_following_distance_simulation(v_lead, e2e=self.e2e, personality=self.personality) + correct_steady_state = desired_follow_distance(v_lead, v_lead, get_T_FOLLOW(self.personality)) + err_ratio = 0.2 if self.e2e else 0.1 + abs_err_margin = 0.5 if v_lead > 0.0 else 1.15 + assert simulation_steady_state == pytest.approx(correct_steady_state, abs=err_ratio * correct_steady_state + abs_err_margin) diff --git a/selfdrive/controls/lib/tests/test_latcontrol.py b/openpilot/selfdrive/controls/tests/test_latcontrol.py similarity index 80% rename from selfdrive/controls/lib/tests/test_latcontrol.py rename to openpilot/selfdrive/controls/tests/test_latcontrol.py index 727f68195f..52e6912d6d 100644 --- a/selfdrive/controls/lib/tests/test_latcontrol.py +++ b/openpilot/selfdrive/controls/tests/test_latcontrol.py @@ -1,11 +1,14 @@ -from parameterized import parameterized +from openpilot.common.parameterized import parameterized -from cereal import car, log +from openpilot.cereal import log +from opendbc.car.structs import car from opendbc.car.car_helpers import interfaces from opendbc.car.honda.values import CAR as HONDA from opendbc.car.toyota.values import CAR as TOYOTA from opendbc.car.nissan.values import CAR as NISSAN +from opendbc.car.gm.values import CAR as GM from opendbc.car.vehicle_model import VehicleModel +from openpilot.common.realtime import DT_CTRL from openpilot.selfdrive.car.helpers import convert_to_capnp from openpilot.selfdrive.controls.lib.latcontrol_pid import LatControlPID from openpilot.selfdrive.controls.lib.latcontrol_torque import LatControlTorque @@ -17,7 +20,8 @@ from openpilot.sunnypilot.selfdrive.car import interfaces as sunnypilot_interfac class TestLatControl: - @parameterized.expand([(HONDA.HONDA_CIVIC, LatControlPID), (TOYOTA.TOYOTA_RAV4, LatControlTorque), (NISSAN.NISSAN_LEAF, LatControlAngle)]) + @parameterized.expand([(HONDA.HONDA_CIVIC, LatControlPID), (TOYOTA.TOYOTA_RAV4, LatControlTorque), + (NISSAN.NISSAN_LEAF, LatControlAngle), (GM.CHEVROLET_BOLT_EUV, LatControlTorque)]) def test_saturation(self, car_name, controller): CarInterface = interfaces[car_name] CP = CarInterface.get_non_essential_params(car_name) @@ -27,7 +31,7 @@ class TestLatControl: CP_SP = convert_to_capnp(CP_SP) VM = VehicleModel(CP) - controller = controller(CP.as_reader(), CP_SP.as_reader(), CI) + controller = controller(CP.as_reader(), CP_SP.as_reader(), CI, DT_CTRL) CS = car.CarState.new_message() CS.vEgo = 30 @@ -40,13 +44,13 @@ class TestLatControl: # Saturate for curvature limited and controller limited for _ in range(1000): - _, _, lac_log = controller.update(True, CS, VM, params, False, 0, pose, True) + _, _, lac_log = controller.update(True, CS, VM, params, False, 0, pose, True, 0.2) assert lac_log.saturated for _ in range(1000): - _, _, lac_log = controller.update(True, CS, VM, params, False, 0, pose, False) + _, _, lac_log = controller.update(True, CS, VM, params, False, 0, pose, False, 0.2) assert not lac_log.saturated for _ in range(1000): - _, _, lac_log = controller.update(True, CS, VM, params, False, 1, pose, False) + _, _, lac_log = controller.update(True, CS, VM, params, False, 1, pose, False, 0.2) assert lac_log.saturated diff --git a/openpilot/selfdrive/controls/tests/test_latcontrol_torque_buffer.py b/openpilot/selfdrive/controls/tests/test_latcontrol_torque_buffer.py new file mode 100644 index 0000000000..dc634f20fd --- /dev/null +++ b/openpilot/selfdrive/controls/tests/test_latcontrol_torque_buffer.py @@ -0,0 +1,48 @@ +from openpilot.common.parameterized import parameterized + +from openpilot.cereal import log +from opendbc.car.structs import car +from opendbc.car.car_helpers import interfaces +from opendbc.car.toyota.values import CAR as TOYOTA +from opendbc.car.vehicle_model import VehicleModel +from openpilot.common.realtime import DT_CTRL +from openpilot.selfdrive.controls.lib.latcontrol_torque import LatControlTorque, LAT_ACCEL_REQUEST_BUFFER_SECONDS + +from openpilot.selfdrive.car.helpers import convert_to_capnp +from openpilot.selfdrive.locationd.helpers import Pose +from openpilot.common.mock.generators import generate_livePose +from openpilot.sunnypilot.selfdrive.car import interfaces as sunnypilot_interfaces + +def get_controller(car_name): + CarInterface = interfaces[car_name] + CP = CarInterface.get_non_essential_params(car_name) + CP_SP = CarInterface.get_non_essential_params_sp(CP, car_name) + CI = CarInterface(CP, CP_SP) + sunnypilot_interfaces.setup_interfaces(CI) + CP_SP = convert_to_capnp(CP_SP) + VM = VehicleModel(CP) + controller = LatControlTorque(CP.as_reader(), CP_SP.as_reader(), CI, DT_CTRL) + return controller, VM + +class TestLatControlTorqueBuffer: + + @parameterized.expand([(TOYOTA.TOYOTA_COROLLA_TSS2,)]) + def test_request_buffer_consistency(self, car_name): + buffer_steps = int(LAT_ACCEL_REQUEST_BUFFER_SECONDS / DT_CTRL) + controller, VM = get_controller(car_name) + + CS = car.CarState.new_message() + CS.vEgo = 30 + CS.steeringPressed = False + params = log.LiveParametersData.new_message() + + lp = generate_livePose() + pose = Pose.from_live_pose(lp.livePose) + + for _ in range(buffer_steps): + controller.update(True, CS, VM, params, False, 0.001, pose, False, 0.2) + assert all(val != 0 for val in controller.lat_accel_request_buffer) + + for _ in range(buffer_steps): + controller.update(False, CS, VM, params, False, 0.0, pose, False, 0.2) + assert all(val == 0 for val in controller.lat_accel_request_buffer) diff --git a/selfdrive/controls/tests/test_leads.py b/openpilot/selfdrive/controls/tests/test_leads.py similarity index 96% rename from selfdrive/controls/tests/test_leads.py rename to openpilot/selfdrive/controls/tests/test_leads.py index 77384fea20..1956bb34ec 100644 --- a/selfdrive/controls/tests/test_leads.py +++ b/openpilot/selfdrive/controls/tests/test_leads.py @@ -1,4 +1,4 @@ -import cereal.messaging as messaging +import openpilot.cereal.messaging as messaging from opendbc.car.toyota.values import CAR as TOYOTA from openpilot.selfdrive.test.process_replay import replay_process_with_name diff --git a/openpilot/selfdrive/controls/tests/test_longcontrol.py b/openpilot/selfdrive/controls/tests/test_longcontrol.py new file mode 100644 index 0000000000..b2906b4574 --- /dev/null +++ b/openpilot/selfdrive/controls/tests/test_longcontrol.py @@ -0,0 +1,43 @@ +from openpilot.cereal import custom +from openpilot.selfdrive.controls.lib.longcontrol import LongCtrlState, long_control_state_trans + + +class TestLongControlStateTransition: + + def test_stay_stopped(self): + CP_SP = custom.CarParamsSP.new_message() + active = True + current_state = LongCtrlState.stopping + next_state = long_control_state_trans(CP_SP, active, current_state, + should_stop=True, brake_pressed=False, cruise_standstill=False) + assert next_state == LongCtrlState.stopping + next_state = long_control_state_trans(CP_SP, active, current_state, + should_stop=False, brake_pressed=True, cruise_standstill=False) + assert next_state == LongCtrlState.stopping + next_state = long_control_state_trans(CP_SP, active, current_state, + should_stop=False, brake_pressed=False, cruise_standstill=True) + assert next_state == LongCtrlState.stopping + next_state = long_control_state_trans(CP_SP, active, current_state, + should_stop=False, brake_pressed=False, cruise_standstill=False) + assert next_state == LongCtrlState.pid + active = False + next_state = long_control_state_trans(CP_SP, active, current_state, + should_stop=False, brake_pressed=False, cruise_standstill=False) + assert next_state == LongCtrlState.off + +def test_engage(): + CP_SP = custom.CarParamsSP.new_message() + active = True + current_state = LongCtrlState.off + next_state = long_control_state_trans(CP_SP, active, current_state, + should_stop=True, brake_pressed=False, cruise_standstill=False) + assert next_state == LongCtrlState.stopping + next_state = long_control_state_trans(CP_SP, active, current_state, + should_stop=False, brake_pressed=True, cruise_standstill=False) + assert next_state == LongCtrlState.stopping + next_state = long_control_state_trans(CP_SP, active, current_state, + should_stop=False, brake_pressed=False, cruise_standstill=True) + assert next_state == LongCtrlState.stopping + next_state = long_control_state_trans(CP_SP, active, current_state, + should_stop=False, brake_pressed=False, cruise_standstill=False) + assert next_state == LongCtrlState.pid diff --git a/openpilot/selfdrive/controls/tests/test_torqued_lat_accel_offset.py b/openpilot/selfdrive/controls/tests/test_torqued_lat_accel_offset.py new file mode 100644 index 0000000000..7599eb1e7b --- /dev/null +++ b/openpilot/selfdrive/controls/tests/test_torqued_lat_accel_offset.py @@ -0,0 +1,72 @@ +import numpy as np +from openpilot.cereal import messaging +from opendbc.car.structs import car +from opendbc.car import ACCELERATION_DUE_TO_GRAVITY +from opendbc.car import structs +from opendbc.car.lateral import get_friction, FRICTION_THRESHOLD +from openpilot.common.realtime import DT_MDL +from openpilot.selfdrive.locationd.torqued import TorqueEstimator, MIN_BUCKET_POINTS, POINTS_PER_BUCKET, STEER_BUCKET_BOUNDS + +LA_ERR_STD = 1.0 +INPUT_NOISE_STD = 0.08 +V_EGO = 30.0 + +WARMUP_BUCKET_POINTS = (1.5*MIN_BUCKET_POINTS).astype(int) +STRAIGHT_ROAD_LA_BOUNDS = (0.02, 0.03) + +ROLL_BIAS_DEG = 2.0 +ROLL_COMPENSATION_BIAS = ACCELERATION_DUE_TO_GRAVITY*float(np.sin(np.deg2rad(ROLL_BIAS_DEG))) +TORQUE_TUNE = structs.CarParams.LateralTorqueTuning(latAccelFactor=2.0, latAccelOffset=0.0, friction=0.2) +TORQUE_TUNE_BIASED = structs.CarParams.LateralTorqueTuning(latAccelFactor=2.0, latAccelOffset=-ROLL_COMPENSATION_BIAS, friction=0.2) + +def generate_inputs(torque_tune, la_err_std, input_noise_std=None): + rng = np.random.default_rng(0) + steer_torques = np.concat([rng.uniform(bnd[0], bnd[1], pts) for bnd, pts in zip(STEER_BUCKET_BOUNDS, WARMUP_BUCKET_POINTS, strict=True)]) + la_errs = rng.normal(scale=la_err_std, size=steer_torques.size) + frictions = np.array([get_friction(la_err, 0.0, FRICTION_THRESHOLD, torque_tune) for la_err in la_errs]) + lat_accels = torque_tune.latAccelFactor*steer_torques + torque_tune.latAccelOffset + frictions + if input_noise_std is not None: + steer_torques += rng.normal(scale=input_noise_std, size=steer_torques.size) + lat_accels += rng.normal(scale=input_noise_std, size=steer_torques.size) + return steer_torques, lat_accels + +def get_warmed_up_estimator(steer_torques, lat_accels): + est = TorqueEstimator(car.CarParams()) + for steer_torque, lat_accel in zip(steer_torques, lat_accels, strict=True): + est.filtered_points.add_point(steer_torque, lat_accel) + return est + +def simulate_straight_road_msgs(est): + carControl = messaging.new_message('carControl').carControl + carOutput = messaging.new_message('carOutput').carOutput + carState = messaging.new_message('carState').carState + livePose = messaging.new_message('livePose').livePose + carControl.latActive = True + carState.vEgo = V_EGO + carState.steeringPressed = False + ts = DT_MDL*np.arange(2*POINTS_PER_BUCKET) + steer_torques = np.concat((np.linspace(-0.03, -0.02, POINTS_PER_BUCKET), np.linspace(0.02, 0.03, POINTS_PER_BUCKET))) + lat_accels = TORQUE_TUNE.latAccelFactor * steer_torques + for t, steer_torque, lat_accel in zip(ts, steer_torques, lat_accels, strict=True): + carOutput.actuatorsOutput.torque = float(-steer_torque) + livePose.orientationNED = {'x': float(np.deg2rad(ROLL_BIAS_DEG)), 'valid': True} + livePose.angularVelocityDevice = {'z': float(lat_accel / V_EGO), 'valid': True} + livePose.inputsOK, livePose.sensorsOK, livePose.posenetOK = True, True, True + livePose.timestamp = int(t * 1e9) + for which, msg in (('carControl', carControl), ('carOutput', carOutput), ('carState', carState), ('livePose', livePose)): + est.handle_log(t, which, msg) + +class TestTorquedLatAccelOffset: + def test_estimated_offset(self): + steer_torques, lat_accels = generate_inputs(TORQUE_TUNE_BIASED, la_err_std=LA_ERR_STD, input_noise_std=INPUT_NOISE_STD) + est = get_warmed_up_estimator(steer_torques, lat_accels) + msg = est.get_msg() + # TODO add lataccelfactor and friction check when we have more accurate estimates + assert abs(msg.liveTorqueParameters.latAccelOffsetRaw - TORQUE_TUNE_BIASED.latAccelOffset) < 0.1 + + def test_straight_road_roll_bias(self): + steer_torques, lat_accels = generate_inputs(TORQUE_TUNE, la_err_std=LA_ERR_STD, input_noise_std=INPUT_NOISE_STD) + est = get_warmed_up_estimator(steer_torques, lat_accels) + simulate_straight_road_msgs(est) + msg = est.get_msg() + assert (msg.liveTorqueParameters.latAccelOffsetRaw < -0.05) and np.isfinite(msg.liveTorqueParameters.latAccelOffsetRaw) diff --git a/selfdrive/locationd/SConscript b/openpilot/selfdrive/locationd/SConscript similarity index 100% rename from selfdrive/locationd/SConscript rename to openpilot/selfdrive/locationd/SConscript diff --git a/selfdrive/controls/tests/__init__.py b/openpilot/selfdrive/locationd/__init__.py similarity index 100% rename from selfdrive/controls/tests/__init__.py rename to openpilot/selfdrive/locationd/__init__.py diff --git a/selfdrive/locationd/calibrationd.py b/openpilot/selfdrive/locationd/calibrationd.py similarity index 96% rename from selfdrive/locationd/calibrationd.py rename to openpilot/selfdrive/locationd/calibrationd.py index 59f30dbf77..b9616bf632 100755 --- a/selfdrive/locationd/calibrationd.py +++ b/openpilot/selfdrive/locationd/calibrationd.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 ''' This process finds calibration values. More info on what these calibration values -are can be found here https://github.com/commaai/openpilot/tree/master/common/transformations +are can be found here https://github.com/commaai/openpilot/tree/master/openpilot/common/transformations While the roll calibration is a real value that can be estimated, here we assume it's zero, and the image input into the neural network is not corrected for roll. ''' @@ -11,10 +11,11 @@ import capnp import numpy as np from typing import NoReturn -from cereal import log, car -import cereal.messaging as messaging -from openpilot.system.hardware import HARDWARE -from openpilot.common.conversions import Conversions as CV +from openpilot.cereal import log +from opendbc.car.structs import car +import openpilot.cereal.messaging as messaging +from openpilot.common.hardware import HARDWARE +from openpilot.common.constants import CV from openpilot.common.params import Params from openpilot.common.realtime import config_realtime_process from openpilot.common.transformations.orientation import rot_from_euler, euler_from_rot @@ -47,7 +48,7 @@ DEBUG = os.getenv("DEBUG") is not None def is_calibration_valid(rpy: np.ndarray) -> bool: - return (PITCH_LIMITS[0] < rpy[1] < PITCH_LIMITS[1]) and (YAW_LIMITS[0] < rpy[2] < YAW_LIMITS[1]) # type: ignore + return (PITCH_LIMITS[0] < rpy[1] < PITCH_LIMITS[1]) and (YAW_LIMITS[0] < rpy[2] < YAW_LIMITS[1]) def sanity_clip(rpy: np.ndarray) -> np.ndarray: @@ -92,7 +93,7 @@ class Calibrator: valid_blocks: int = 0, wide_from_device_euler_init: np.ndarray = WIDE_FROM_DEVICE_EULER_INIT, height_init: np.ndarray = HEIGHT_INIT, - smooth_from: np.ndarray = None) -> None: + smooth_from: np.ndarray | None = None) -> None: if not np.isfinite(rpy_init).all(): self.rpy = RPY_INIT.copy() else: @@ -167,7 +168,7 @@ class Calibrator: write_this_cycle = (self.idx == 0) and (self.block_idx % (INPUTS_WANTED//5) == 5) if self.param_put and write_this_cycle: - self.params.put_nonblocking("CalibrationParams", self.get_msg(True).to_bytes()) + self.params.put("CalibrationParams", self.get_msg(True).to_bytes()) def handle_v_ego(self, v_ego: float) -> None: self.v_ego = v_ego diff --git a/openpilot/selfdrive/locationd/helpers.py b/openpilot/selfdrive/locationd/helpers.py new file mode 100644 index 0000000000..5e3fa16027 --- /dev/null +++ b/openpilot/selfdrive/locationd/helpers.py @@ -0,0 +1,185 @@ +import numpy as np +from collections.abc import Sequence +from typing import Any +from functools import cache + +from openpilot.cereal import log +from openpilot.common.transformations.orientation import rot_from_euler, euler_from_rot + + +@cache +def fft_next_good_size(n: int) -> int: + """ + smallest composite of 2, 3, 5, 7, 11 that is >= n + inspired by pocketfft + """ + if n <= 6: + return n + best, f2 = 2 * n, 1 + while f2 < best: + f23 = f2 + while f23 < best: + f235 = f23 + while f235 < best: + f2357 = f235 + while f2357 < best: + f235711 = f2357 + while f235711 < best: + best = f235711 if f235711 >= n else best + f235711 *= 11 + f2357 *= 7 + f235 *= 5 + f23 *= 3 + f2 *= 2 + return best + + +def parabolic_peak_interp(R, max_index): + if max_index == 0 or max_index == len(R) - 1: + return max_index + + y_m1, y_0, y_p1 = R[max_index - 1], R[max_index], R[max_index + 1] + offset = 0.5 * (y_p1 - y_m1) / (2 * y_0 - y_p1 - y_m1) + + return max_index + offset + + +def rotate_cov(rot_matrix, cov_in): + return rot_matrix @ cov_in @ rot_matrix.T + + +def rotate_std(rot_matrix, std_in): + return np.sqrt(np.diag(rotate_cov(rot_matrix, np.diag(std_in**2)))) + + +class NPQueue: + def __init__(self, maxlen: int, rowsize: int) -> None: + self.maxlen = maxlen + self.arr = np.empty((0, rowsize)) + + def __len__(self) -> int: + return len(self.arr) + + def append(self, pt: list[float]) -> None: + if len(self.arr) < self.maxlen: + self.arr = np.append(self.arr, [pt], axis=0) + else: + self.arr[:-1] = self.arr[1:] + self.arr[-1] = pt + + +class PointBuckets: + def __init__(self, x_bounds: list[tuple[float, float]], min_points: Sequence[float], min_points_total: int, points_per_bucket: int, rowsize: int) -> None: + self._rng = np.random.default_rng() + self.x_bounds = x_bounds + self.buckets = {bounds: NPQueue(maxlen=points_per_bucket, rowsize=rowsize) for bounds in x_bounds} + self.buckets_min_points = dict(zip(x_bounds, min_points, strict=True)) + self.min_points_total = min_points_total + + def __len__(self) -> int: + return sum([len(v) for v in self.buckets.values()]) + + def is_valid(self) -> bool: + individual_buckets_valid = all(len(v) >= min_pts for v, min_pts in zip(self.buckets.values(), self.buckets_min_points.values(), strict=True)) + total_points_valid = self.__len__() >= self.min_points_total + return individual_buckets_valid and total_points_valid + + def get_valid_percent(self) -> int: + total_points_perc = min(self.__len__() / self.min_points_total * 100, 100) + individual_buckets_perc = min(min(len(v) / min_pts * 100 for v, min_pts in + zip(self.buckets.values(), self.buckets_min_points.values(), strict=True)), 100) + return int((total_points_perc + individual_buckets_perc) / 2) + + def is_calculable(self) -> bool: + return all(len(v) > 0 for v in self.buckets.values()) + + def add_point(self, x: float, y: float) -> None: + raise NotImplementedError + + def get_points(self, num_points: int | None = None) -> Any: + points = np.vstack([x.arr for x in self.buckets.values()]) + if num_points is None: + return points + return points[self._rng.choice(np.arange(len(points)), min(len(points), num_points), replace=False)] + + def load_points(self, points: Sequence[Sequence[float]]) -> None: + for point in points: + self.add_point(*point) + + +class ParameterEstimator: + """ Base class for parameter estimators """ + def reset(self) -> None: + raise NotImplementedError + + def handle_log(self, t: int, which: str, msg: log.Event) -> None: + raise NotImplementedError + + def get_msg(self, valid: bool, with_points: bool) -> log.Event: + raise NotImplementedError + + +class Measurement: + x, y, z = (property(lambda self: self.xyz[0]), property(lambda self: self.xyz[1]), property(lambda self: self.xyz[2])) + x_std, y_std, z_std = (property(lambda self: self.xyz_std[0]), property(lambda self: self.xyz_std[1]), property(lambda self: self.xyz_std[2])) + roll, pitch, yaw = x, y, z + roll_std, pitch_std, yaw_std = x_std, y_std, z_std + + def __init__(self, xyz: np.ndarray, xyz_std: np.ndarray): + self.xyz: np.ndarray = xyz + self.xyz_std: np.ndarray = xyz_std + + @classmethod + def from_measurement_xyz(cls, measurement: log.LivePose.XYZMeasurement) -> 'Measurement': + return cls( + xyz=np.array([measurement.x, measurement.y, measurement.z]), + xyz_std=np.array([measurement.xStd, measurement.yStd, measurement.zStd]) + ) + + +class Pose: + def __init__(self, orientation: Measurement, velocity: Measurement, acceleration: Measurement, angular_velocity: Measurement): + self.orientation = orientation + self.velocity = velocity + self.acceleration = acceleration + self.angular_velocity = angular_velocity + + @classmethod + def from_live_pose(cls, live_pose: log.LivePose) -> 'Pose': + return Pose( + orientation=Measurement.from_measurement_xyz(live_pose.orientationNED), + velocity=Measurement.from_measurement_xyz(live_pose.velocityDevice), + acceleration=Measurement.from_measurement_xyz(live_pose.accelerationDevice), + angular_velocity=Measurement.from_measurement_xyz(live_pose.angularVelocityDevice) + ) + + +class PoseCalibrator: + def __init__(self): + self.calib_valid = False + self.calib_from_device = np.eye(3) + + def _transform_calib_from_device(self, meas: Measurement): + new_xyz = self.calib_from_device @ meas.xyz + new_xyz_std = rotate_std(self.calib_from_device, meas.xyz_std) + return Measurement(new_xyz, new_xyz_std) + + def _ned_from_calib(self, orientation: Measurement): + ned_from_device = rot_from_euler(orientation.xyz) + ned_from_calib = ned_from_device @ self.calib_from_device.T + ned_from_calib_euler_meas = Measurement(euler_from_rot(ned_from_calib), np.full(3, np.nan)) + return ned_from_calib_euler_meas + + def build_calibrated_pose(self, pose: Pose) -> Pose: + ned_from_calib_euler = self._ned_from_calib(pose.orientation) + angular_velocity_calib = self._transform_calib_from_device(pose.angular_velocity) + acceleration_calib = self._transform_calib_from_device(pose.acceleration) + velocity_calib = self._transform_calib_from_device(pose.velocity) + + return Pose(ned_from_calib_euler, velocity_calib, acceleration_calib, angular_velocity_calib) + + def feed_live_calib(self, live_calib: log.LiveCalibrationData): + calib_rpy = np.array(live_calib.rpyCalib) + device_from_calib = rot_from_euler(calib_rpy) + self.calib_from_device = device_from_calib.T + self.calib_valid = live_calib.calStatus == log.LiveCalibrationData.Status.calibrated diff --git a/selfdrive/locationd/lagd.py b/openpilot/selfdrive/locationd/lagd.py similarity index 82% rename from selfdrive/locationd/lagd.py rename to openpilot/selfdrive/locationd/lagd.py index e6767db473..da2c53fd11 100755 --- a/selfdrive/locationd/lagd.py +++ b/openpilot/selfdrive/locationd/lagd.py @@ -5,13 +5,16 @@ import capnp from collections import deque from functools import partial -import cereal.messaging as messaging -from cereal import car, log -from cereal.services import SERVICE_LIST +import openpilot.cereal.messaging as messaging +from openpilot.cereal import log +from opendbc.car.structs import car +from openpilot.cereal.services import SERVICE_LIST +from openpilot.common.constants import CV from openpilot.common.params import Params from openpilot.common.realtime import config_realtime_process from openpilot.common.swaglog import cloudlog from openpilot.selfdrive.locationd.helpers import PoseCalibrator, Pose, fft_next_good_size, parabolic_peak_interp +from openpilot.sunnypilot.livedelay.lagd_toggle import LagdToggle BLOCK_SIZE = 100 BLOCK_NUM = 50 @@ -19,18 +22,36 @@ BLOCK_NUM_NEEDED = 5 MOVING_WINDOW_SEC = 60.0 MIN_OKAY_WINDOW_SEC = 25.0 MIN_RECOVERY_BUFFER_SEC = 2.0 -MIN_VEGO = 15.0 +MIN_VEGO = 50.0 * CV.MPH_TO_MS MIN_ABS_YAW_RATE = 0.0 MAX_YAW_RATE_SANITY_CHECK = 1.0 MIN_NCC = 0.95 -MAX_LAG = 1.0 +MAX_LAG = 0.65 +MIN_LAG = 0.15 MAX_LAG_STD = 0.1 MAX_LAT_ACCEL = 2.0 MAX_LAT_ACCEL_DIFF = 0.6 +MIN_LAT_ACCEL_RANGE = 0.5 MIN_CONFIDENCE = 0.7 CORR_BORDER_OFFSET = 5 LAG_CANDIDATE_CORR_THRESHOLD = 0.9 +SMOOTH_K = 5 +SMOOTH_SIGMA = 1.0 +VERSION = 1 # bump this to invalidate old parameter caches + + +def masked_symmetric_moving_average(x: np.ndarray, mask: np.ndarray, k: int, sigma: float) -> np.ndarray: + assert k >= 1 and k % 2 == 1, "k must be positive and odd" + pad = k // 2 + i = np.arange(k) - pad + w = np.exp(-0.5 * (i / sigma) ** 2) + w /= w.sum() + xp = np.pad(x * mask, pad, mode="edge") + mp = np.pad(mask, pad, mode="edge") + num = np.convolve(xp, w, mode="valid") + den = np.convolve(mp, w, mode="valid") + return np.divide(num, den, out=np.full_like(num, np.nan, dtype=np.float64), where=den != 0) def masked_normalized_cross_correlation(expected_sig: np.ndarray, actual_sig: np.ndarray, mask: np.ndarray, n: int): """ @@ -157,8 +178,7 @@ class LateralLagEstimator: block_count: int = BLOCK_NUM, min_valid_block_count: int = BLOCK_NUM_NEEDED, block_size: int = BLOCK_SIZE, window_sec: float = MOVING_WINDOW_SEC, okay_window_sec: float = MIN_OKAY_WINDOW_SEC, min_recovery_buffer_sec: float = MIN_RECOVERY_BUFFER_SEC, min_vego: float = MIN_VEGO, min_yr: float = MIN_ABS_YAW_RATE, min_ncc: float = MIN_NCC, - max_lat_accel: float = MAX_LAT_ACCEL, max_lat_accel_diff: float = MAX_LAT_ACCEL_DIFF, min_confidence: float = MIN_CONFIDENCE, - enabled: bool = True): + max_lat_accel: float = MAX_LAT_ACCEL, max_lat_accel_diff: float = MAX_LAT_ACCEL_DIFF, min_confidence: float = MIN_CONFIDENCE): self.dt = dt self.window_sec = window_sec self.okay_window_sec = okay_window_sec @@ -173,7 +193,6 @@ class LateralLagEstimator: self.min_confidence = min_confidence self.max_lat_accel = max_lat_accel self.max_lat_accel_diff = max_lat_accel_diff - self.enabled = enabled self.t = 0.0 self.lat_active = False @@ -208,7 +227,7 @@ class LateralLagEstimator: liveDelay = msg.liveDelay valid_mean_lag, valid_std, current_mean_lag, current_std = self.block_avg.get() - if self.enabled and self.block_avg.valid_blocks >= self.min_valid_block_count and not np.isnan(valid_mean_lag) and not np.isnan(valid_std): + if self.block_avg.valid_blocks >= self.min_valid_block_count and not np.isnan(valid_mean_lag) and not np.isnan(valid_std): if valid_std > MAX_LAG_STD: liveDelay.status = log.LiveDelayData.Status.invalid else: @@ -217,7 +236,7 @@ class LateralLagEstimator: liveDelay.status = log.LiveDelayData.Status.unestimated if liveDelay.status == log.LiveDelayData.Status.estimated: - liveDelay.lateralDelay = valid_mean_lag + liveDelay.lateralDelay = min(MAX_LAG, max(MIN_LAG, valid_mean_lag)) else: liveDelay.lateralDelay = self.initial_lag @@ -233,6 +252,7 @@ class LateralLagEstimator: (self.min_valid_block_count * self.block_size), 100) if debug: liveDelay.points = self.block_avg.values.flatten().tolist() + liveDelay.version = VERSION return msg @@ -295,12 +315,15 @@ class LateralLagEstimator: times, desired, actual, okay = self.points.get() # check if there are any new valid data points since the last update - is_valid = self.points_valid() + is_valid = self.points_valid() and (actual.max() - actual.min() >= MIN_LAT_ACCEL_RANGE) if self.last_estimate_t != 0 and times[0] <= self.last_estimate_t: new_values_start_idx = next(-i for i, t in enumerate(reversed(times)) if t <= self.last_estimate_t) is_valid = is_valid and not (new_values_start_idx == 0 or not np.any(okay[new_values_start_idx:])) - delay, corr, confidence = self.actuator_delay(desired, actual, okay, self.dt, MAX_LAG) + desired = masked_symmetric_moving_average(desired, okay, SMOOTH_K, SMOOTH_SIGMA) + actual = masked_symmetric_moving_average(actual, okay, SMOOTH_K, SMOOTH_SIGMA) + + delay, corr, confidence = self.actuator_delay(desired, actual, okay, self.dt, MIN_LAG, MAX_LAG) if corr < self.min_ncc or confidence < self.min_confidence or not is_valid: return @@ -308,27 +331,28 @@ class LateralLagEstimator: self.last_estimate_t = self.t @staticmethod - def actuator_delay(expected_sig: np.ndarray, actual_sig: np.ndarray, mask: np.ndarray, dt: float, max_lag: float) -> tuple[float, float, float]: + def actuator_delay(expected_sig: np.ndarray, actual_sig: np.ndarray, mask: np.ndarray, + dt: float, min_lag: float, max_lag: float) -> tuple[float, float, float]: assert len(expected_sig) == len(actual_sig) - max_lag_samples = int(max_lag / dt) - padded_size = fft_next_good_size(len(expected_sig) + max_lag_samples) + min_lag_samples, max_lag_samples, one_sec_samples = int(round(min_lag / dt)), int(round(max_lag / dt)), int(round(1.0 / dt)) + padded_size = fft_next_good_size(len(expected_sig) + max(max_lag_samples, one_sec_samples)) ncc = masked_normalized_cross_correlation(expected_sig, actual_sig, mask, padded_size) - # only consider lags from 0 to max_lag - roi = np.s_[len(expected_sig) - 1: len(expected_sig) - 1 + max_lag_samples] - extended_roi = np.s_[roi.start - CORR_BORDER_OFFSET: roi.stop + CORR_BORDER_OFFSET] - roi_ncc = ncc[roi] - extended_roi_ncc = ncc[extended_roi] + # only consider lags from ranges: + roi = np.s_[len(expected_sig) - 1 + min_lag_samples: len(expected_sig) - 1 + max_lag_samples] # min_lag - max_lag range + threshold_roi = np.s_[len(expected_sig) - 1: len(expected_sig) - 1 + one_sec_samples] # 0 - 1 second range + confidence_roi = np.s_[threshold_roi.start - CORR_BORDER_OFFSET: threshold_roi.stop + CORR_BORDER_OFFSET] # threshold range +/- border + roi_ncc, confidence_roi_ncc, threshold_roi_ncc = ncc[roi], ncc[confidence_roi], ncc[threshold_roi] max_corr_index = np.argmax(roi_ncc) corr = roi_ncc[max_corr_index] - lag = parabolic_peak_interp(roi_ncc, max_corr_index) * dt + lag = parabolic_peak_interp(roi_ncc, max_corr_index) * dt + min_lag # to estimate lag confidence, gather all high-correlation candidates and see how spread they are # if e.g. 0.8 and 0.4 are both viable, this is an ambiguous case - ncc_thresh = (roi_ncc.max() - roi_ncc.min()) * LAG_CANDIDATE_CORR_THRESHOLD + roi_ncc.min() - good_lag_candidate_mask = extended_roi_ncc >= ncc_thresh + ncc_thresh = (threshold_roi_ncc.max() - threshold_roi_ncc.min()) * LAG_CANDIDATE_CORR_THRESHOLD + threshold_roi_ncc.min() + good_lag_candidate_mask = confidence_roi_ncc >= ncc_thresh good_lag_candidate_edges = np.diff(good_lag_candidate_mask.astype(int), prepend=0, append=0) starts, ends = np.where(good_lag_candidate_edges == 1)[0], np.where(good_lag_candidate_edges == -1)[0] - 1 run_idx = np.searchsorted(starts, max_corr_index + CORR_BORDER_OFFSET, side='right') - 1 @@ -349,9 +373,10 @@ def retrieve_initial_lag(params: Params, CP: car.CarParams): if last_CP.carFingerprint != CP.carFingerprint: raise Exception("Car model mismatch") - lag, valid_blocks, status = ld.lateralDelayEstimate, ld.validBlocks, ld.status + lag, valid_blocks, status, version = ld.lateralDelayEstimate, ld.validBlocks, ld.status, ld.version assert valid_blocks <= BLOCK_NUM, "Invalid number of valid blocks" assert status != log.LiveDelayData.Status.invalid, "Lag estimate is invalid" + assert version == VERSION, f"Lag estimate is from a different version (got {version}, expected {VERSION})" return lag, valid_blocks except Exception as e: cloudlog.error(f"Failed to retrieve initial lag: {e}") @@ -371,14 +396,13 @@ def main(): params = Params() CP = messaging.log_from_bytes(params.get("CarParams", block=True), car.CarParams) - # TODO: remove me, lagd is in shadow mode on release - is_release = params.get_bool("IsReleaseBranch") - - lag_learner = LateralLagEstimator(CP, 1. / SERVICE_LIST['livePose'].frequency, enabled=not is_release) + lag_learner = LateralLagEstimator(CP, 1. / SERVICE_LIST['livePose'].frequency) if (initial_lag_params := retrieve_initial_lag(params, CP)) is not None: lag, valid_blocks = initial_lag_params lag_learner.reset(lag, valid_blocks) + lagd_toggle = LagdToggle(CP) + while True: sm.update() if sm.all_checks(): @@ -396,4 +420,7 @@ def main(): pm.send('liveDelay', lag_msg_dat) if sm.frame % 1200 == 0: # cache every 60 seconds - params.put_nonblocking("LiveDelay", lag_msg_dat) + params.put("LiveDelay", lag_msg_dat) + + if sm.frame % 60 == 0: # read from and write to params every 3 seconds + lagd_toggle.update(lag_msg) diff --git a/selfdrive/locationd/locationd.py b/openpilot/selfdrive/locationd/locationd.py similarity index 94% rename from selfdrive/locationd/locationd.py rename to openpilot/selfdrive/locationd/locationd.py index f6a0935ed9..eb3c42fce2 100755 --- a/selfdrive/locationd/locationd.py +++ b/openpilot/selfdrive/locationd/locationd.py @@ -6,8 +6,8 @@ import numpy as np from enum import Enum from collections import defaultdict -from cereal import log, messaging -from cereal.services import SERVICE_LIST +from openpilot.cereal import log, messaging +from openpilot.cereal.services import SERVICE_LIST from openpilot.common.transformations.orientation import rot_from_euler from openpilot.common.realtime import config_realtime_process from openpilot.common.params import Params @@ -28,6 +28,9 @@ INPUT_INVALID_LIMIT = 2.0 # 1 (camodo) / 9 (sensor) bad input[s] ignored INPUT_INVALID_RECOVERY = 10.0 # ~10 secs to resume after exceeding allowed bad inputs by one POSENET_STD_INITIAL_VALUE = 10.0 POSENET_STD_HIST_HALF = 20 +CAM_ODO_POSE_DELAY = 0.1 # dependent on the vision model context frames and temporal frequency (current model is 5 fps with 2 context frames) +CAM_ODO_ROT_STD_MULT = 10 +CAM_ODO_TRANS_STD_MULT = 4 def calculate_invalid_input_decay(invalid_limit, recovery_time, frequency): @@ -63,7 +66,7 @@ class LocationEstimator: self.observations = {kind: np.zeros(3, dtype=np.float32) for kind in obs_kinds} self.observation_errors = {kind: np.zeros(3, dtype=np.float32) for kind in obs_kinds} - def reset(self, t: float, x_initial: np.ndarray = PoseKalman.initial_x, P_initial: np.ndarray = PoseKalman.initial_P): + def reset(self, t: float | None, x_initial: np.ndarray = PoseKalman.initial_x, P_initial: np.ndarray = PoseKalman.initial_P): self.kf.init_state(x_initial, covs=P_initial, filter_time=t) def _validate_sensor_source(self, source: log.SensorEventData.SensorSource): @@ -155,6 +158,8 @@ class LocationEstimator: self.device_from_calib = rot_from_euler(calib) elif which == "cameraOdometry": + # camera odometry is delayed depending on the model context frames and temporal frequency + t = msg.timestampEof * 1e-9 - CAM_ODO_POSE_DELAY if not self._validate_timestamp(t): return HandleLogResult.TIMING_INVALID @@ -177,8 +182,8 @@ class LocationEstimator: self.posenet_stds[-1] = trans_calib_std[0] # Multiply by N to avoid to high certainty in kalman filter because of temporally correlated noise - rot_calib_std *= 10 - trans_calib_std *= 2 + rot_calib_std *= CAM_ODO_ROT_STD_MULT + trans_calib_std *= CAM_ODO_TRANS_STD_MULT rot_device_std = rotate_std(self.device_from_calib, rot_calib_std) trans_device_std = rotate_std(self.device_from_calib, trans_calib_std) @@ -201,9 +206,11 @@ class LocationEstimator: self._finite_check(t, new_x, new_P) return HandleLogResult.SUCCESS - def get_msg(self, sensors_valid: bool, inputs_valid: bool, filter_valid: bool): + def get_msg(self, sensors_valid: bool, inputs_valid: bool, filter_initialized: bool): state, cov = self.kf.x, self.kf.P std = np.sqrt(np.diag(cov)) + filter_time_valid = bool(np.isfinite(self.kf.t)) + filter_valid = filter_initialized and filter_time_valid orientation_ned, orientation_ned_std = state[States.NED_ORIENTATION], std[States.NED_ORIENTATION] velocity_device, velocity_device_std = state[States.DEVICE_VELOCITY], std[States.DEVICE_VELOCITY] @@ -234,6 +241,7 @@ class LocationEstimator: livePose.inputsOK = inputs_valid livePose.posenetOK = not std_spike or self.car_speed <= 5.0 livePose.sensorsOK = sensors_valid + livePose.timestamp = int(np.nan_to_num(self.kf.t) * 1e9) return msg diff --git a/selfdrive/locationd/models/.gitignore b/openpilot/selfdrive/locationd/models/.gitignore similarity index 100% rename from selfdrive/locationd/models/.gitignore rename to openpilot/selfdrive/locationd/models/.gitignore diff --git a/selfdrive/debug/__init__.py b/openpilot/selfdrive/locationd/models/__init__.py similarity index 100% rename from selfdrive/debug/__init__.py rename to openpilot/selfdrive/locationd/models/__init__.py diff --git a/openpilot/selfdrive/locationd/models/car_kf.py b/openpilot/selfdrive/locationd/models/car_kf.py new file mode 100755 index 0000000000..27cc4ef9c9 --- /dev/null +++ b/openpilot/selfdrive/locationd/models/car_kf.py @@ -0,0 +1,180 @@ +#!/usr/bin/env python3 +import math +import sys +from typing import Any + +import numpy as np + +from openpilot.common.constants import ACCELERATION_DUE_TO_GRAVITY +from openpilot.selfdrive.locationd.models.constants import ObservationKind +from openpilot.common.swaglog import cloudlog + +from rednose.helpers.kalmanfilter import KalmanFilter + +if __name__ == '__main__': # Generating sympy + import sympy as sp + from rednose.helpers.ekf_sym import gen_code +else: + from rednose.helpers.ekf_sym_pyx import EKF_sym_pyx + + +i = 0 + +def _slice(n): + global i + s = slice(i, i + n) + i += n + + return s + + +class States: + # Vehicle model params + STIFFNESS = _slice(1) # [-] + STEER_RATIO = _slice(1) # [-] + ANGLE_OFFSET = _slice(1) # [rad] + ANGLE_OFFSET_FAST = _slice(1) # [rad] + + VELOCITY = _slice(2) # (x, y) [m/s] + YAW_RATE = _slice(1) # [rad/s] + STEER_ANGLE = _slice(1) # [rad] + ROAD_ROLL = _slice(1) # [rad] + + +class CarKalman(KalmanFilter): + name = 'car' + + initial_x = np.array([ + 1.0, + 15.0, + 0.0, + 0.0, + + 10.0, 0.0, + 0.0, + 0.0, + 0.0 + ]) + + # process noise + Q = np.diag([ + (.05 / 100)**2, + .01**2, + math.radians(0.02)**2, + math.radians(0.25)**2, + + .1**2, .01**2, + math.radians(0.1)**2, + math.radians(0.1)**2, + math.radians(1)**2, + ]) + P_initial = Q.copy() + + obs_noise: dict[int, Any] = { + ObservationKind.STEER_ANGLE: np.atleast_2d(math.radians(0.05)**2), + ObservationKind.ANGLE_OFFSET_FAST: np.atleast_2d(math.radians(10.0)**2), + ObservationKind.ROAD_ROLL: np.atleast_2d(math.radians(1.0)**2), + ObservationKind.STEER_RATIO: np.atleast_2d(5.0**2), + ObservationKind.STIFFNESS: np.atleast_2d(0.5**2), + ObservationKind.ROAD_FRAME_X_SPEED: np.atleast_2d(0.1**2), + } + + global_vars = [ + 'mass', + 'rotational_inertia', + 'center_to_front', + 'center_to_rear', + 'stiffness_front', + 'stiffness_rear', + ] + + @staticmethod + def generate_code(generated_dir): + dim_state = CarKalman.initial_x.shape[0] + name = CarKalman.name + + # Linearized single-track lateral dynamics, equations 7.211-7.213 + # Massimo Guiggiani, The Science of Vehicle Dynamics: Handling, Braking, and Ride of Road and Race Cars + # Springer Cham, 2023. doi: https://doi.org/10.1007/978-3-031-06461-6 + + # globals + global_vars = [sp.Symbol(name) for name in CarKalman.global_vars] + m, j, aF, aR, cF_orig, cR_orig = global_vars + + # make functions and jacobians with sympy + # state variables + state_sym = sp.MatrixSymbol('state', dim_state, 1) + state = sp.Matrix(state_sym) + + # Vehicle model constants + sf = state[States.STIFFNESS, :][0, 0] + + cF, cR = sf * cF_orig, sf * cR_orig + angle_offset = state[States.ANGLE_OFFSET, :][0, 0] + angle_offset_fast = state[States.ANGLE_OFFSET_FAST, :][0, 0] + theta = state[States.ROAD_ROLL, :][0, 0] + sa = state[States.STEER_ANGLE, :][0, 0] + + sR = state[States.STEER_RATIO, :][0, 0] + u, v = state[States.VELOCITY, :] + r = state[States.YAW_RATE, :][0, 0] + + A = sp.Matrix(np.zeros((2, 2))) + A[0, 0] = -(cF + cR) / (m * u) + A[0, 1] = -(cF * aF - cR * aR) / (m * u) - u + A[1, 0] = -(cF * aF - cR * aR) / (j * u) + A[1, 1] = -(cF * aF**2 + cR * aR**2) / (j * u) + + B = sp.Matrix(np.zeros((2, 1))) + B[0, 0] = cF / m / sR + B[1, 0] = (cF * aF) / j / sR + + C = sp.Matrix(np.zeros((2, 1))) + C[0, 0] = ACCELERATION_DUE_TO_GRAVITY + C[1, 0] = 0 + + x = sp.Matrix([v, r]) # lateral velocity, yaw rate + x_dot = A * x + B * (sa - angle_offset - angle_offset_fast) - C * theta + + dt = sp.Symbol('dt') + state_dot = sp.Matrix(np.zeros((dim_state, 1))) + state_dot[States.VELOCITY.start + 1, 0] = x_dot[0] + state_dot[States.YAW_RATE.start, 0] = x_dot[1] + + # Basic descretization, 1st order integrator + # Can be pretty bad if dt is big + f_sym = state + dt * state_dot + + # + # Observation functions + # + obs_eqs = [ + [sp.Matrix([r]), ObservationKind.ROAD_FRAME_YAW_RATE, None], + [sp.Matrix([u, v]), ObservationKind.ROAD_FRAME_XY_SPEED, None], + [sp.Matrix([u]), ObservationKind.ROAD_FRAME_X_SPEED, None], + [sp.Matrix([sa]), ObservationKind.STEER_ANGLE, None], + [sp.Matrix([angle_offset_fast]), ObservationKind.ANGLE_OFFSET_FAST, None], + [sp.Matrix([sR]), ObservationKind.STEER_RATIO, None], + [sp.Matrix([sf]), ObservationKind.STIFFNESS, None], + [sp.Matrix([theta]), ObservationKind.ROAD_ROLL, None], + ] + + gen_code(generated_dir, name, f_sym, dt, state_sym, obs_eqs, dim_state, dim_state, global_vars=global_vars) + + def __init__(self, generated_dir): + dim_state, dim_state_err = CarKalman.initial_x.shape[0], CarKalman.P_initial.shape[0] + self.filter = EKF_sym_pyx(generated_dir, CarKalman.name, CarKalman.Q, CarKalman.initial_x, CarKalman.P_initial, + dim_state, dim_state_err, global_vars=CarKalman.global_vars, logger=cloudlog) + + def set_globals(self, mass, rotational_inertia, center_to_front, center_to_rear, stiffness_front, stiffness_rear): + self.filter.set_global("mass", mass) + self.filter.set_global("rotational_inertia", rotational_inertia) + self.filter.set_global("center_to_front", center_to_front) + self.filter.set_global("center_to_rear", center_to_rear) + self.filter.set_global("stiffness_front", stiffness_front) + self.filter.set_global("stiffness_rear", stiffness_rear) + + +if __name__ == "__main__": + generated_dir = sys.argv[2] + CarKalman.generate_code(generated_dir) diff --git a/selfdrive/locationd/models/constants.py b/openpilot/selfdrive/locationd/models/constants.py similarity index 100% rename from selfdrive/locationd/models/constants.py rename to openpilot/selfdrive/locationd/models/constants.py diff --git a/selfdrive/locationd/models/pose_kf.py b/openpilot/selfdrive/locationd/models/pose_kf.py similarity index 97% rename from selfdrive/locationd/models/pose_kf.py rename to openpilot/selfdrive/locationd/models/pose_kf.py index 020e51ad6e..a8ff80c713 100755 --- a/selfdrive/locationd/models/pose_kf.py +++ b/openpilot/selfdrive/locationd/models/pose_kf.py @@ -47,13 +47,13 @@ class PoseKalman(KalmanFilter): # process noise Q = np.diag([0.001**2, 0.001**2, 0.001**2, 0.01**2, 0.01**2, 0.01**2, - 0.1**2, 0.1**2, 0.1**2, + 0.085**2, 0.085**2, 0.085**2, (0.005 / 100)**2, (0.005 / 100)**2, (0.005 / 100)**2, 3**2, 3**2, 3**2, 0.005**2, 0.005**2, 0.005**2]) obs_noise = {ObservationKind.PHONE_GYRO: np.diag([0.025**2, 0.025**2, 0.025**2]), - ObservationKind.PHONE_ACCEL: np.diag([.5**2, .5**2, .5**2]), + ObservationKind.PHONE_ACCEL: np.diag([0.75**2, 0.75**2, 0.75**2]), ObservationKind.CAMERA_ODO_TRANSLATION: np.diag([0.5**2, 0.5**2, 0.5**2]), ObservationKind.CAMERA_ODO_ROTATION: np.diag([0.05**2, 0.05**2, 0.05**2])} diff --git a/selfdrive/locationd/paramsd.py b/openpilot/selfdrive/locationd/paramsd.py similarity index 90% rename from selfdrive/locationd/paramsd.py rename to openpilot/selfdrive/locationd/paramsd.py index ec15f501ae..c1088a8180 100755 --- a/selfdrive/locationd/paramsd.py +++ b/openpilot/selfdrive/locationd/paramsd.py @@ -1,11 +1,11 @@ #!/usr/bin/env python3 import os -import json import numpy as np import capnp -import cereal.messaging as messaging -from cereal import car, log +import openpilot.cereal.messaging as messaging +from openpilot.cereal import log +from opendbc.car.structs import car from openpilot.common.params import Params from openpilot.common.realtime import config_realtime_process, DT_MDL from openpilot.selfdrive.locationd.models.car_kf import CarKalman, ObservationKind, States @@ -66,6 +66,7 @@ class VehicleParamsLearner: def handle_log(self, t: float, which: str, msg: capnp._DynamicStructReader): if which == 'livePose': + t = msg.timestamp * 1e-9 device_pose = Pose.from_live_pose(msg) calibrated_pose = self.calibrator.build_calibrated_pose(device_pose) @@ -128,8 +129,8 @@ class VehicleParamsLearner: if not self.active: # Reset time when stopped so uncertainty doesn't grow - self.kf.filter.set_filter_time(t) # type: ignore - self.kf.filter.reset_rewind() # type: ignore + self.kf.filter.set_filter_time(t) + self.kf.filter.reset_rewind() def get_msg(self, valid: bool, debug: bool = False) -> capnp._DynamicStructBuilder: x = self.kf.x @@ -199,26 +200,6 @@ def check_valid_with_hysteresis(current_valid: bool, val: float, threshold: floa return current_valid -# TODO: Remove this function after few releases (added in 0.9.9) -def migrate_cached_vehicle_params_if_needed(params: Params): - last_parameters_data_old = params.get("LiveParameters") - last_parameters_data = params.get("LiveParametersV2") - if last_parameters_data_old is None or last_parameters_data is not None: - return - - try: - last_parameters_dict = json.loads(last_parameters_data_old) - last_parameters_msg = messaging.new_message('liveParameters') - last_parameters_msg.liveParameters.valid = True - last_parameters_msg.liveParameters.steerRatio = last_parameters_dict['steerRatio'] - last_parameters_msg.liveParameters.stiffnessFactor = last_parameters_dict['stiffnessFactor'] - last_parameters_msg.liveParameters.angleOffsetAverageDeg = last_parameters_dict['angleOffsetAverageDeg'] - params.put("LiveParametersV2", last_parameters_msg.to_bytes()) - except Exception as e: - cloudlog.error(f"Failed to perform parameter migration: {e}") - params.remove("LiveParameters") - - def retrieve_initial_vehicle_params(params: Params, CP: car.CarParams, replay: bool, debug: bool): last_parameters_data = params.get("LiveParametersV2") last_carparams_data = params.get("CarParamsPrevRoute") @@ -273,8 +254,6 @@ def main(): params = Params() CP = messaging.log_from_bytes(params.get("CarParams", block=True), car.CarParams) - migrate_cached_vehicle_params_if_needed(params) - steer_ratio, stiffness_factor, angle_offset_deg, pInitial = retrieve_initial_vehicle_params(params, CP, REPLAY, DEBUG) learner = VehicleParamsLearner(CP, steer_ratio, stiffness_factor, np.radians(angle_offset_deg), pInitial) @@ -291,7 +270,7 @@ def main(): msg_dat = msg.to_bytes() if sm.frame % 1200 == 0: # once a minute - params.put_nonblocking("LiveParametersV2", msg_dat) + params.put("LiveParametersV2", msg_dat) pm.send('liveParameters', msg_dat) diff --git a/selfdrive/locationd/__init__.py b/openpilot/selfdrive/locationd/test/__init__.py similarity index 100% rename from selfdrive/locationd/__init__.py rename to openpilot/selfdrive/locationd/test/__init__.py diff --git a/selfdrive/locationd/test/test_calibrationd.py b/openpilot/selfdrive/locationd/test/test_calibrationd.py similarity index 97% rename from selfdrive/locationd/test/test_calibrationd.py rename to openpilot/selfdrive/locationd/test/test_calibrationd.py index df61b6a7c7..f862b369fe 100644 --- a/selfdrive/locationd/test/test_calibrationd.py +++ b/openpilot/selfdrive/locationd/test/test_calibrationd.py @@ -2,8 +2,8 @@ import random import numpy as np -import cereal.messaging as messaging -from cereal import log +import openpilot.cereal.messaging as messaging +from openpilot.cereal import log from openpilot.common.params import Params from openpilot.selfdrive.locationd.calibrationd import Calibrator, INPUTS_NEEDED, INPUTS_WANTED, BLOCK_SIZE, MIN_SPEED_FILTER, \ MAX_YAW_RATE_FILTER, SMOOTH_CYCLES, HEIGHT_INIT, MAX_ALLOWED_PITCH_SPREAD, MAX_ALLOWED_YAW_SPREAD @@ -36,7 +36,7 @@ class TestCalibrationd: msg.liveCalibration.validBlocks = random.randint(1, 10) msg.liveCalibration.rpyCalib = [random.random() for _ in range(3)] msg.liveCalibration.height = [random.random() for _ in range(1)] - Params().put("CalibrationParams", msg.to_bytes()) + Params().put("CalibrationParams", msg.to_bytes(), block=True) c = Calibrator(param_put=True) np.testing.assert_allclose(msg.liveCalibration.rpyCalib, c.rpy) diff --git a/openpilot/selfdrive/locationd/test/test_lagd.py b/openpilot/selfdrive/locationd/test/test_lagd.py new file mode 100644 index 0000000000..efaba6ead9 --- /dev/null +++ b/openpilot/selfdrive/locationd/test/test_lagd.py @@ -0,0 +1,153 @@ +import random +import numpy as np +import time +import pytest + +from openpilot.cereal import messaging, log +from opendbc.car.structs import car +from openpilot.selfdrive.locationd.lagd import LateralLagEstimator, retrieve_initial_lag, masked_normalized_cross_correlation, \ + BLOCK_NUM_NEEDED, BLOCK_SIZE, MIN_OKAY_WINDOW_SEC, VERSION, MIN_LAG, MAX_LAG +from openpilot.selfdrive.test.process_replay.migration import migrate, migrate_carParams +from openpilot.selfdrive.locationd.test.test_locationd_scenarios import TEST_ROUTE +from openpilot.common.params import Params +from openpilot.tools.lib.logreader import LogReader +from openpilot.common.hardware import PC + +MAX_ERR_FRAMES = 1 +DT = 0.05 +LAGD_MIN_LAG_FRAMES, LAGD_MAX_LAG_FRAMES = int(round(MIN_LAG / DT)), int(round(MAX_LAG / DT)) + + +def process_messages(estimator, lag_frames, n_frames, vego=25.0, rejection_threshold=0.0): + for i in range(n_frames): + t = i * estimator.dt + desired_la = np.cos(10 * t) * 0.3 + actual_la = np.cos(10 * (t - lag_frames * estimator.dt)) * 0.3 + + # if sample is masked out, set it to desired value (no lag) + rejected = random.uniform(0, 1) < rejection_threshold + if rejected: + actual_la = desired_la + + desired_cuvature = float(desired_la / (vego ** 2)) + actual_yr = float(actual_la / vego) + msgs = [ + (t, "carControl", car.CarControl(latActive=not rejected)), + (t, "carState", car.CarState(vEgo=vego, steeringPressed=False)), + (t, "controlsState", log.ControlsState(desiredCurvature=desired_cuvature)), + (t, "livePose", log.LivePose(angularVelocityDevice=log.LivePose.XYZMeasurement(z=actual_yr, valid=True), + posenetOK=True, inputsOK=True)), + (t, "liveCalibration", log.LiveCalibrationData(rpyCalib=[0, 0, 0], calStatus=log.LiveCalibrationData.Status.calibrated)), + ] + for t, w, m in msgs: + estimator.handle_log(t, w, m) + estimator.update_points() + estimator.update_estimate() + + +class TestLagd: + def test_read_saved_params(self): + params = Params() + + lr = migrate(LogReader(TEST_ROUTE), [migrate_carParams]) + CP = next(m for m in lr if m.which() == "carParams").carParams + + msg = messaging.new_message('liveDelay') + msg.liveDelay.lateralDelayEstimate = random.random() + msg.liveDelay.validBlocks = random.randint(1, 10) + msg.liveDelay.version = VERSION + params.put("LiveDelay", msg.to_bytes(), block=True) + params.put("CarParamsPrevRoute", CP.as_builder().to_bytes(), block=True) + + saved_lag_params = retrieve_initial_lag(params, CP) + assert saved_lag_params is not None + + lag, valid_blocks = saved_lag_params + assert lag == msg.liveDelay.lateralDelayEstimate + assert valid_blocks == msg.liveDelay.validBlocks + + def test_read_invalid_saved_params(self, subtests): + params = Params() + + lr = migrate(LogReader(TEST_ROUTE), [migrate_carParams]) + CP = next(m for m in lr if m.which() == "carParams").carParams + + for msg_dict in [{'version': 0}, {'status': 'invalid'}, {'validBlocks': 100}]: + with subtests.test(msg=f"liveDelay={msg_dict}"): + msg = messaging.new_message('liveDelay') + msg.liveDelay = msg_dict + params.put("LiveDelay", msg.to_bytes(), block=True) + params.put("CarParamsPrevRoute", CP.as_builder().to_bytes(), block=True) + assert retrieve_initial_lag(params, CP) is None + + def test_ncc(self): + rng = np.random.default_rng() + lag_frames = random.randint(1, 19) + + desired_sig = np.sin(np.arange(0.0, 10.0, 0.1)) + actual_sig = np.sin(np.arange(0.0, 10.0, 0.1) - lag_frames * 0.1) + mask = np.ones(len(desired_sig), dtype=bool) + + corr = masked_normalized_cross_correlation(desired_sig, actual_sig, mask, 200)[len(desired_sig) - 1:len(desired_sig) + 20] + assert np.argmax(corr) == lag_frames + + # add some noise + desired_sig += rng.normal(0, 0.05, len(desired_sig)) + actual_sig += rng.normal(0, 0.05, len(actual_sig)) + corr = masked_normalized_cross_correlation(desired_sig, actual_sig, mask, 200)[len(desired_sig) - 1:len(desired_sig) + 20] + assert np.argmax(corr) in range(lag_frames - MAX_ERR_FRAMES, lag_frames + MAX_ERR_FRAMES + 1) + + # mask out 40% of the values, and make them noise + mask = rng.choice([True, False], size=len(desired_sig), p=[0.6, 0.4]) + desired_sig[~mask] = rng.normal(0, 1, size=np.sum(~mask)) + actual_sig[~mask] = rng.normal(0, 1, size=np.sum(~mask)) + corr = masked_normalized_cross_correlation(desired_sig, actual_sig, mask, 200)[len(desired_sig) - 1:len(desired_sig) + 20] + assert np.argmax(corr) in range(lag_frames - MAX_ERR_FRAMES, lag_frames + MAX_ERR_FRAMES + 1) + + def test_empty_estimator(self): + mocked_CP = car.CarParams(steerActuatorDelay=0.5) + estimator = LateralLagEstimator(mocked_CP, DT) + msg = estimator.get_msg(True) + assert msg.liveDelay.status == 'unestimated' + assert np.allclose(msg.liveDelay.lateralDelay, estimator.initial_lag) + assert np.allclose(msg.liveDelay.lateralDelayEstimate, estimator.initial_lag) + assert msg.liveDelay.validBlocks == 0 + assert msg.liveDelay.calPerc == 0 + + def test_estimator_basics(self, subtests): + for lag_frames in range(LAGD_MIN_LAG_FRAMES, LAGD_MAX_LAG_FRAMES - 1): + with subtests.test(msg=f"lag_frames={lag_frames}"): + mocked_CP = car.CarParams(steerActuatorDelay=0.5) + estimator = LateralLagEstimator(mocked_CP, DT, min_recovery_buffer_sec=0.0, min_yr=0.0) + process_messages(estimator, lag_frames, int(MIN_OKAY_WINDOW_SEC / DT) + BLOCK_NUM_NEEDED * BLOCK_SIZE) + msg = estimator.get_msg(True) + assert msg.liveDelay.status == 'estimated' + assert np.allclose(msg.liveDelay.lateralDelay, lag_frames * DT, atol=0.01) + assert np.allclose(msg.liveDelay.lateralDelayEstimate, lag_frames * DT, atol=0.01) + assert np.allclose(msg.liveDelay.lateralDelayEstimateStd, 0.0, atol=0.01) + assert msg.liveDelay.validBlocks == BLOCK_NUM_NEEDED + assert msg.liveDelay.calPerc == 100 + + def test_estimator_masking(self): + mocked_CP, lag_frames = car.CarParams(steerActuatorDelay=0.5), random.randint(LAGD_MIN_LAG_FRAMES, LAGD_MAX_LAG_FRAMES - 1) + estimator = LateralLagEstimator(mocked_CP, DT, min_recovery_buffer_sec=0.0, min_yr=0.0, min_valid_block_count=1) + process_messages(estimator, lag_frames, (int(MIN_OKAY_WINDOW_SEC / DT) + BLOCK_SIZE) * 2, rejection_threshold=0.4) + msg = estimator.get_msg(True) + assert np.allclose(msg.liveDelay.lateralDelayEstimate, lag_frames * DT, atol=0.01) + assert np.allclose(msg.liveDelay.lateralDelayEstimateStd, 0.0, atol=0.01) + assert msg.liveDelay.calPerc == 100 + + @pytest.mark.skipif(PC, reason="only on device") + def test_estimator_performance(self): + mocked_CP = car.CarParams(steerActuatorDelay=0.5) + estimator = LateralLagEstimator(mocked_CP, DT) + + ds = [] + for _ in range(1000): + st = time.perf_counter() + estimator.update_points() + estimator.update_estimate() + d = time.perf_counter() - st + ds.append(d) + + assert np.mean(ds) < DT diff --git a/selfdrive/locationd/test/test_locationd_scenarios.py b/openpilot/selfdrive/locationd/test/test_locationd_scenarios.py similarity index 94% rename from selfdrive/locationd/test/test_locationd_scenarios.py rename to openpilot/selfdrive/locationd/test/test_locationd_scenarios.py index 0ea7ac183f..04d2d6b55b 100644 --- a/selfdrive/locationd/test/test_locationd_scenarios.py +++ b/openpilot/selfdrive/locationd/test/test_locationd_scenarios.py @@ -3,6 +3,7 @@ from collections import defaultdict from enum import Enum from openpilot.tools.lib.logreader import LogReader +from openpilot.selfdrive.locationd.lagd import masked_symmetric_moving_average from openpilot.selfdrive.test.process_replay.migration import migrate_all from openpilot.selfdrive.test.process_replay.process_replay import replay_process_with_name @@ -15,6 +16,7 @@ SELECT_COMPARE_FIELDS = { 'inputs_flag': ['inputsOK'], 'sensors_flag': ['sensorsOK'], } +SMOOTH_FIELDS = ['yaw_rate', 'roll'] JUNK_IDX = 100 CONSISTENT_SPIKES_COUNT = 10 @@ -32,10 +34,12 @@ class Scenario(Enum): def get_select_fields_data(logs): + def sig_smooth(signal): + return masked_symmetric_moving_average(signal, np.ones_like(signal), 5, 1.0) def get_nested_keys(msg, keys): - val = None + val = msg for key in keys: - val = getattr(msg if val is None else val, key) if isinstance(key, str) else val[key] + val = getattr(val, key) if isinstance(key, str) else val[key] return val lp = [x.livePose for x in logs if x.which() == 'livePose'] data = defaultdict(list) @@ -44,6 +48,8 @@ def get_select_fields_data(logs): data[key].append(get_nested_keys(msg, fields)) for key in data: data[key] = np.array(data[key][JUNK_IDX:], dtype=float) + if key in SMOOTH_FIELDS: + data[key] = sig_smooth(data[key]) return data @@ -110,7 +116,7 @@ class TestLocationdScenarios: """ orig_data, replayed_data = run_scenarios(Scenario.BASE, self.logs) assert np.allclose(orig_data['yaw_rate'], replayed_data['yaw_rate'], atol=np.radians(0.35)) - assert np.allclose(orig_data['roll'], replayed_data['roll'], atol=np.radians(0.55)) + assert np.allclose(orig_data['roll'], replayed_data['roll'], atol=np.radians(0.35)) def test_gyro_off(self): """ @@ -135,7 +141,7 @@ class TestLocationdScenarios: """ orig_data, replayed_data = run_scenarios(Scenario.GYRO_SPIKE_MIDWAY, self.logs) assert np.allclose(orig_data['yaw_rate'], replayed_data['yaw_rate'], atol=np.radians(0.35)) - assert np.allclose(orig_data['roll'], replayed_data['roll'], atol=np.radians(0.55)) + assert np.allclose(orig_data['roll'], replayed_data['roll'], atol=np.radians(0.35)) assert np.all(replayed_data['inputs_flag'] == orig_data['inputs_flag']) assert np.all(replayed_data['sensors_flag'] == orig_data['sensors_flag']) @@ -169,7 +175,7 @@ class TestLocationdScenarios: """ orig_data, replayed_data = run_scenarios(Scenario.ACCEL_SPIKE_MIDWAY, self.logs) assert np.allclose(orig_data['yaw_rate'], replayed_data['yaw_rate'], atol=np.radians(0.35)) - assert np.allclose(orig_data['roll'], replayed_data['roll'], atol=np.radians(0.55)) + assert np.allclose(orig_data['roll'], replayed_data['roll'], atol=np.radians(0.35)) def test_single_timing_spike(self): """ diff --git a/openpilot/selfdrive/locationd/test/test_paramsd.py b/openpilot/selfdrive/locationd/test/test_paramsd.py new file mode 100644 index 0000000000..74135cb875 --- /dev/null +++ b/openpilot/selfdrive/locationd/test/test_paramsd.py @@ -0,0 +1,38 @@ +import random +import numpy as np + +from openpilot.cereal import messaging +from openpilot.selfdrive.locationd.paramsd import retrieve_initial_vehicle_params +from openpilot.selfdrive.locationd.models.car_kf import CarKalman +from openpilot.selfdrive.locationd.test.test_locationd_scenarios import TEST_ROUTE +from openpilot.selfdrive.test.process_replay.migration import migrate, migrate_carParams +from openpilot.common.params import Params +from openpilot.tools.lib.logreader import LogReader + + +def get_random_live_parameters(CP): + msg = messaging.new_message("liveParameters") + msg.liveParameters.steerRatio = (random.random() + 0.5) * CP.steerRatio + msg.liveParameters.stiffnessFactor = random.random() + msg.liveParameters.angleOffsetAverageDeg = random.random() + msg.liveParameters.debugFilterState.std = [random.random() for _ in range(CarKalman.P_initial.shape[0])] + return msg + + +class TestParamsd: + def test_read_saved_params(self): + params = Params() + + lr = migrate(LogReader(TEST_ROUTE), [migrate_carParams]) + CP = next(m for m in lr if m.which() == "carParams").carParams + + msg = get_random_live_parameters(CP) + params.put("LiveParametersV2", msg.to_bytes(), block=True) + params.put("CarParamsPrevRoute", CP.as_builder().to_bytes(), block=True) + + sr, sf, offset, p_init = retrieve_initial_vehicle_params(params, CP, replay=True, debug=True) + np.testing.assert_allclose(sr, msg.liveParameters.steerRatio) + np.testing.assert_allclose(sf, msg.liveParameters.stiffnessFactor) + np.testing.assert_allclose(offset, msg.liveParameters.angleOffsetAverageDeg) + np.testing.assert_equal(p_init.shape, CarKalman.P_initial.shape) + np.testing.assert_allclose(np.diagonal(p_init), msg.liveParameters.debugFilterState.std) diff --git a/openpilot/selfdrive/locationd/test/test_torqued.py b/openpilot/selfdrive/locationd/test/test_torqued.py new file mode 100644 index 0000000000..4d337178a0 --- /dev/null +++ b/openpilot/selfdrive/locationd/test/test_torqued.py @@ -0,0 +1,26 @@ +from opendbc.car.structs import car +from openpilot.selfdrive.locationd.torqued import TorqueEstimator + + +class TestTorqued: + def test_cal_percent(self): + est = TorqueEstimator(car.CarParams()) + msg = est.get_msg() + assert msg.liveTorqueParameters.calPerc == 0 + + for (low, high), min_pts in zip(est.filtered_points.buckets.keys(), + est.filtered_points.buckets_min_points.values(), strict=True): + for _ in range(int(min_pts)): + est.filtered_points.add_point((low + high) / 2.0, 0.0) + + # enough bucket points, but not enough total points + msg = est.get_msg() + assert msg.liveTorqueParameters.calPerc == (len(est.filtered_points) / est.min_points_total * 100 + 100) / 2 + + # add enough points to bucket with most capacity + key = list(est.filtered_points.buckets)[0] + for _ in range(est.min_points_total - len(est.filtered_points)): + est.filtered_points.add_point((key[0] + key[1]) / 2.0, 0.0) + + msg = est.get_msg() + assert msg.liveTorqueParameters.calPerc == 100 diff --git a/selfdrive/locationd/torqued.py b/openpilot/selfdrive/locationd/torqued.py similarity index 88% rename from selfdrive/locationd/torqued.py rename to openpilot/selfdrive/locationd/torqued.py index 23bd99931b..1d4aa8bc35 100755 --- a/selfdrive/locationd/torqued.py +++ b/openpilot/selfdrive/locationd/torqued.py @@ -1,15 +1,19 @@ #!/usr/bin/env python3 +import os import numpy as np from collections import deque, defaultdict -import cereal.messaging as messaging -from cereal import car, log -from opendbc.car.vehicle_model import ACCELERATION_DUE_TO_GRAVITY +import openpilot.cereal.messaging as messaging +from openpilot.cereal import log +from opendbc.car.structs import car +from openpilot.common.constants import ACCELERATION_DUE_TO_GRAVITY from openpilot.common.params import Params from openpilot.common.realtime import config_realtime_process, DT_MDL from openpilot.common.filter_simple import FirstOrderFilter from openpilot.common.swaglog import cloudlog from openpilot.selfdrive.locationd.helpers import PointBuckets, ParameterEstimator, PoseCalibrator, Pose +from openpilot.sunnypilot.livedelay.helpers import get_lat_delay +from openpilot.sunnypilot.selfdrive.locationd.torqued_ext import TorqueEstimatorExt HISTORY = 5 # secs POINTS_PER_BUCKET = 1500 @@ -32,7 +36,7 @@ MIN_BUCKET_POINTS = np.array([100, 300, 500, 500, 500, 500, 300, 100]) MIN_ENGAGE_BUFFER = 2 # secs VERSION = 1 # bump this to invalidate old parameter caches -ALLOWED_CARS = ['toyota', 'hyundai', 'rivian'] +ALLOWED_CARS = ['toyota', 'hyundai', 'rivian', 'honda', 'volkswagen'] def slope2rot(slope): @@ -49,20 +53,23 @@ class TorqueBuckets(PointBuckets): break -class TorqueEstimator(ParameterEstimator): +class TorqueEstimator(ParameterEstimator, TorqueEstimatorExt): def __init__(self, CP, decimated=False, track_all_points=False): + ParameterEstimator.__init__(self) + TorqueEstimatorExt.__init__(self, CP) + self.CP = CP self.hist_len = int(HISTORY / DT_MDL) self.lag = 0.0 self.track_all_points = track_all_points # for offline analysis, without max lateral accel or max steer torque filters if decimated: - self.min_bucket_points = MIN_BUCKET_POINTS / 10 + self.min_bucket_points: list[float] = (MIN_BUCKET_POINTS / 10).tolist() self.min_points_total = MIN_POINTS_TOTAL_QLOG self.fit_points = FIT_POINTS_TOTAL_QLOG self.factor_sanity = FACTOR_SANITY_QLOG self.friction_sanity = FRICTION_SANITY_QLOG else: - self.min_bucket_points = MIN_BUCKET_POINTS + self.min_bucket_points = MIN_BUCKET_POINTS.tolist() self.min_points_total = MIN_POINTS_TOTAL self.fit_points = FIT_POINTS_TOTAL self.factor_sanity = FACTOR_SANITY @@ -79,6 +86,8 @@ class TorqueEstimator(ParameterEstimator): self.calibrator = PoseCalibrator() + TorqueEstimatorExt.initialize_custom_params(self, decimated) + self.reset() initial_params = { @@ -95,6 +104,7 @@ class TorqueEstimator(ParameterEstimator): # try to restore cached params params = Params() + self.params = params params_cache = params.get("CarParamsPrevRoute") torque_cache = params.get("LiveTorqueParameters") if params_cache is not None and torque_cache is not None: @@ -110,9 +120,10 @@ class TorqueEstimator(ParameterEstimator): 'latAccelOffset': cache_ltp.latAccelOffsetFiltered, 'frictionCoefficient': cache_ltp.frictionCoefficientFiltered } - initial_params['points'] = cache_ltp.points + cached_points: list[list[float]] = [list(point) for point in cache_ltp.points] + initial_params['points'] = cached_points self.decay = cache_ltp.decay - self.filtered_points.load_points(initial_params['points']) + self.filtered_points.load_points(cached_points) cloudlog.info("restored torque params from cache") except Exception: cloudlog.exception("failed to restore cached torque params") @@ -176,10 +187,12 @@ class TorqueEstimator(ParameterEstimator): elif which == "liveCalibration": self.calibrator.feed_live_calib(msg) elif which == "liveDelay": - self.lag = msg.lateralDelay + self.lag = get_lat_delay(self.params, msg.lateralDelay) # calculate lateral accel from past steering torque elif which == "livePose": - if len(self.raw_points['steer_torque']) == self.hist_len: + is_valid = msg.angularVelocityDevice.valid and msg.orientationNED.valid and msg.inputsOK and msg.sensorsOK and msg.posenetOK + if len(self.raw_points['steer_torque']) == self.hist_len and is_valid: + t = msg.timestamp * 1e-9 device_pose = Pose.from_live_pose(msg) calibrated_pose = self.calibrator.build_calibrated_pose(device_pose) angular_velocity_calibrated = calibrated_pose.angular_velocity @@ -242,6 +255,8 @@ class TorqueEstimator(ParameterEstimator): def main(demo=False): config_realtime_process([0, 1, 2, 3], 5) + DEBUG = bool(int(os.getenv("DEBUG", "0"))) + pm = messaging.PubMaster(['liveTorqueParameters']) sm = messaging.SubMaster(['carControl', 'carOutput', 'carState', 'liveCalibration', 'livePose', 'liveDelay'], poll='livePose') @@ -256,14 +271,16 @@ def main(demo=False): t = sm.logMonoTime[which] * 1e-9 estimator.handle_log(t, which, sm[which]) + TorqueEstimatorExt.update_use_params(estimator) + # 4Hz driven by livePose if sm.frame % 5 == 0: - pm.send('liveTorqueParameters', estimator.get_msg(valid=sm.all_checks())) + pm.send('liveTorqueParameters', estimator.get_msg(valid=sm.all_checks(), with_points=DEBUG)) # Cache points every 60 seconds while onroad if sm.frame % 240 == 0: msg = estimator.get_msg(valid=sm.all_checks(), with_points=True) - params.put_nonblocking("LiveTorqueParameters", msg.to_bytes()) + params.put("LiveTorqueParameters", msg.to_bytes()) if __name__ == "__main__": diff --git a/openpilot/selfdrive/modeld/SConscript b/openpilot/selfdrive/modeld/SConscript new file mode 100644 index 0000000000..5f6281556f --- /dev/null +++ b/openpilot/selfdrive/modeld/SConscript @@ -0,0 +1,140 @@ +import glob +import json +import os +import sys, subprocess +from SCons.Script import Action, Value +from openpilot.common.file_chunker import chunk_file, get_chunk_targets, get_existing_chunks +from openpilot.common.transformations.camera import _ar_ox_fisheye, _os_fisheye +from openpilot.common.transformations.model import MEDMODEL_INPUT_SIZE, DM_INPUT_SIZE +from openpilot.selfdrive.modeld.constants import ModelConstants +from openpilot.selfdrive.modeld.helpers import TG_INPUT_DEVICES_PATH, usbgpu_present, modeld_pkl_path + + +CAMERA_CONFIGS = [ + (_ar_ox_fisheye.width, _ar_ox_fisheye.height), # tici: 1928x1208 + (_os_fisheye.width, _os_fisheye.height), # mici: 1344x760 +] + +Import('env', 'arch') +chunker_file = File("#openpilot/common/file_chunker.py") +lenv = env.Clone() + +tinygrad_root = env.Dir("#").abspath +tinygrad_files = ["#"+x for x in glob.glob(env.Dir("#tinygrad_repo").relpath + "/**", recursive=True, root_dir=tinygrad_root) + if 'pycache' not in x and os.path.isfile(os.path.join(tinygrad_root, x))] + +def estimate_pickle_max_size(onnx_size): + return 1.2 * onnx_size + 10 * 1024 * 1024 # 20% + 10MB is plenty + +# get fastest TG config +# probe in subprocess so usbgpu locks gets released on process exit +def probe_devices(): + return set(subprocess.run( + [sys.executable, '-c', 'from tinygrad import Device\nprint("\\n".join(Device.get_available_devices()))'], + capture_output=True, text=True, check=True).stdout.strip().splitlines()) + +available = probe_devices() +if 'CUDA' in available: + tg_backend = 'CUDA' + tg_flags = f'DEV={tg_backend}' +elif 'QCOM' in available: + tg_backend = 'QCOM' + tg_flags = f'DEV={tg_backend} IMAGE=1 FLOAT16=1 NOLOCALS=1 JIT_BATCH_SIZE=0 OPENPILOT_HACKS=1' +else: + tg_backend = 'CPU' + tg_flags = f'DEV=CPU' if arch == 'Darwin' else 'DEV=CPU:LLVM' + +tg_devices = { # which device to put jit inputs to at runtime + 'openpilot.selfdrive.modeld.modeld': { + 'default': {'WARP_DEV': tg_backend, 'QUEUE_DEV': tg_backend}, + 'usbgpu': {'WARP_DEV': tg_backend, 'QUEUE_DEV': 'AMD'} + }, + 'openpilot.selfdrive.modeld.dmonitoringmodeld': { + 'default': {'DEV': tg_backend} + }, +} + +USBGPU = usbgpu_present() # or release # TODO always build big model on release +if USBGPU: + usbgpu_tg_flags = f'DEBUG=2 DEV=USB+AMD:LLVM WARP_DEV={tg_backend} FLOAT16=1 JIT_BATCH_SIZE=0 GMMU=0' + # the USB+AMD GPU takes an exclusive flock; serialize all targets that touch it + usbgpu_lock = File("models/.usb_gpu.lock").abspath + +def write_tg_devices(target, source, env): + with open(str(target[0]), "w") as f: + json.dump(tg_devices, f) + f.write("\n") + +tg_devices_node = lenv.Command( + str(TG_INPUT_DEVICES_PATH), + [Value(tg_devices)], + write_tg_devices, +) + +# tinygrad calls brew which needs a $HOME in the env +mac_brew_string = f'HOME={os.path.expanduser("~")}' if arch == 'Darwin' else '' + +modeld_dir = Dir("#openpilot/selfdrive/modeld").abspath +compile_modeld_script = [ + File(f"{modeld_dir}/compile_modeld.py"), + File(f"{modeld_dir}/get_model_metadata.py"), + File("#openpilot/system/camerad/cameras/nv12_info.py"), + File("#openpilot/common/hardware/hw.py"), +] +model_w, model_h = MEDMODEL_INPUT_SIZE +frame_skip = ModelConstants.MODEL_RUN_FREQ // ModelConstants.MODEL_CONTEXT_FREQ + +for usbgpu in [False, True] if USBGPU else [False]: + target_pkl_path = File(modeld_pkl_path(usbgpu)).abspath + # BIG_INTO_SMALL=1 builds the default target from the big model, e.g. to test it without a USB GPU + file_prefix, cmd_flags = ('big_', usbgpu_tg_flags) if usbgpu else ('big_' if os.getenv('BIG_INTO_SMALL') else '', tg_flags) + driving_onnx_deps = get_existing_chunks(File(f"models/{file_prefix}driving_supercombo.onnx").abspath) + camera_res_args = ' '.join(f'{cw}x{ch}' for cw, ch in CAMERA_CONFIGS) + cmd = (f'{cmd_flags} {mac_brew_string} python3 {modeld_dir}/compile_modeld.py ' + f'--model-size {model_w}x{model_h} ' + f'--camera-resolutions {camera_res_args} ' + f'--onnx {File(f"models/{file_prefix}driving_supercombo.onnx").abspath} ' + f'--output {target_pkl_path} --frame-skip {frame_skip}') + onnx_sizes_sum = sum(os.path.getsize(f) for f in driving_onnx_deps) + chunk_targets = get_chunk_targets(target_pkl_path, estimate_pickle_max_size(onnx_sizes_sum)) + def do_chunk(target, source, env, pkl=target_pkl_path, chunks=chunk_targets): + chunk_file(pkl, chunks) + node = lenv.Command( + chunk_targets, + tinygrad_files + compile_modeld_script + driving_onnx_deps + [Value(chunk_targets), chunker_file], + [cmd, Action(do_chunk, " [CHUNK] $TARGET")], + ) + if usbgpu: + lenv.SideEffect(usbgpu_lock, node) + +# get model metadata +fn = File(f"models/dmonitoring_model").abspath +script_files = [File(Dir("#openpilot/selfdrive/modeld").File("get_model_metadata.py").abspath)] +cmd = f'{tg_flags} {mac_brew_string} python3 {Dir("#openpilot/selfdrive/modeld").abspath}/get_model_metadata.py {fn}.onnx' +lenv.Command(fn + "_metadata.pkl", [fn + ".onnx"] + tinygrad_files + script_files + [tg_devices_node], cmd) + +dm_w, dm_h = DM_INPUT_SIZE +compile_dm_warp_script = [File(f"{modeld_dir}/compile_dm_warp.py")] +for cam_w, cam_h in CAMERA_CONFIGS: + dm_pkl_path = File(f"models/dm_warp_{cam_w}x{cam_h}_tinygrad.pkl").abspath + cmd = (f'{tg_flags} {mac_brew_string} python3 {modeld_dir}/compile_dm_warp.py ' + f'--camera-resolution {cam_w}x{cam_h} --warp-to {dm_w}x{dm_h} ' + f'--output {dm_pkl_path}') + lenv.Command(dm_pkl_path, tinygrad_files + compile_dm_warp_script + compile_modeld_script + [tg_devices_node], cmd) + +def tg_compile(flags, model_name): + pythonpath_string = 'PYTHONPATH="${PYTHONPATH}:' + env.Dir("#tinygrad_repo").abspath + '"' + fn = File(f"models/{model_name}").abspath + pkl = fn + "_tinygrad.pkl" + onnx_path = fn + ".onnx" + chunk_targets = get_chunk_targets(pkl, estimate_pickle_max_size(os.path.getsize(onnx_path))) + def do_chunk(target, source, env): + chunk_file(pkl, chunk_targets) + return lenv.Command( + chunk_targets, + [onnx_path] + tinygrad_files + [Value(chunk_targets), chunker_file, tg_devices_node], + [f'{pythonpath_string} {flags} python3 {Dir("#tinygrad_repo").abspath}/examples/openpilot/compile3.py {fn}.onnx {pkl}', + Action(do_chunk, " [CHUNK] $TARGET")], + ) + +tg_compile(tg_flags, 'dmonitoring_model') diff --git a/selfdrive/locationd/models/__init__.py b/openpilot/selfdrive/modeld/__init__.py similarity index 100% rename from selfdrive/locationd/models/__init__.py rename to openpilot/selfdrive/modeld/__init__.py diff --git a/openpilot/selfdrive/modeld/compile_dm_warp.py b/openpilot/selfdrive/modeld/compile_dm_warp.py new file mode 100755 index 0000000000..16e0d39fbb --- /dev/null +++ b/openpilot/selfdrive/modeld/compile_dm_warp.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python3 +import argparse +import pickle +import time + +from tinygrad.tensor import Tensor +from tinygrad.device import Device +from tinygrad.engine.jit import TinyJit + +from openpilot.system.camerad.cameras.nv12_info import get_nv12_info +from openpilot.selfdrive.modeld.compile_modeld import NV12Frame, warp_perspective_tinygrad, _parse_size + + +def make_warp_dm(nv12: NV12Frame, dm_w, dm_h): + cam_w, cam_h, stride, _, _, _ = nv12 + stride_pad = stride - cam_w + + def warp_dm(input_frame, M_inv): + M_inv = M_inv.to(Device.DEFAULT).realize() + return warp_perspective_tinygrad(input_frame[:cam_h*stride], M_inv, + (dm_w, dm_h), (cam_h, cam_w), stride_pad, border_fill_val=16).reshape(-1, dm_h * dm_w) # Y + return warp_dm + + +def compile_dm_warp(nv12: NV12Frame, dm_w, dm_h, pkl_path): + print(f"Compiling DM warp for {nv12.width}x{nv12.height} -> {dm_w}x{dm_h}...") + + warp_dm_jit = TinyJit(make_warp_dm(nv12, dm_w, dm_h), prune=True) + + for i in range(10): + frame = Tensor.randint(nv12.size, low=0, high=256, dtype='uint8').realize() + M_inv = Tensor(Tensor.randn(3, 3).mul(8).realize().numpy(), device='NPY') + Device.default.synchronize() + st = time.perf_counter() + warp_dm_jit(frame, M_inv).realize() + mt = time.perf_counter() + Device.default.synchronize() + et = time.perf_counter() + print(f" [{i+1}/10] enqueue {(mt-st)*1e3:6.2f} ms -- total {(et-st)*1e3:6.2f} ms") + + with open(pkl_path, "wb") as f: + pickle.dump(warp_dm_jit, f) + print(f" Saved to {pkl_path}") + + +if __name__ == "__main__": + p = argparse.ArgumentParser() + p.add_argument('--camera-resolution', type=_parse_size, required=True, help='camera resolution WxH') + p.add_argument('--warp-to', type=_parse_size, required=True, help='DM input WxH') + p.add_argument('--output', required=True) + args = p.parse_args() + + cam_w, cam_h = args.camera_resolution + nv12 = NV12Frame(cam_w, cam_h, *get_nv12_info(cam_w, cam_h)) + dm_w, dm_h = args.warp_to + compile_dm_warp(nv12, dm_w, dm_h, args.output) diff --git a/openpilot/selfdrive/modeld/compile_modeld.py b/openpilot/selfdrive/modeld/compile_modeld.py new file mode 100755 index 0000000000..ebc3f21a13 --- /dev/null +++ b/openpilot/selfdrive/modeld/compile_modeld.py @@ -0,0 +1,340 @@ +#!/usr/bin/env python3 +import argparse +import atexit +import math +import os +import pickle +import tempfile +import time +import shutil +from functools import partial +from collections import namedtuple + +import numpy as np + +from openpilot.selfdrive.modeld.helpers import dump_oob, load_oob +from openpilot.selfdrive.modeld.usbgpu_link import wait_usbgpu_link + +def _patch_tinygrad_fetch_fw(): + import hashlib + import pathlib + import zstandard + from tinygrad import helpers + _orig = helpers.fetch_fw + def fetch_fw(path, name, sha256): + p = pathlib.Path(f"/lib/firmware/{path}/{name}.zst") + if p.is_file(): + blob = zstandard.ZstdDecompressor().stream_reader(p.read_bytes()).read() + if hashlib.sha256(blob).hexdigest() == sha256: + return blob + return _orig(path, name, sha256) + helpers.fetch_fw = fetch_fw +_patch_tinygrad_fetch_fw() + +def _patch_tinygrad_buffer_reduce(): + from tinygrad.device import Buffer + def __reduce_ex__(self, protocol): + buf = None + if self._base is not None: + return self.__class__, (self.device, self.size, self.dtype, None, None, None, 0, self.base, self.offset, self.is_allocated()) + if self.device == "NPY": + return self.__class__, (self.device, self.size, self.dtype, self._buf, self.options, None, self.uop_refcount) + if self.is_allocated(): + buf = bytearray(self.nbytes) + self.copyout(memoryview(buf)) + if protocol >= 5: + buf = pickle.PickleBuffer(buf) + return self.__class__, (self.device, self.size, self.dtype, None, self.options, buf, self.uop_refcount) + Buffer.__reduce_ex__ = __reduce_ex__ +_patch_tinygrad_buffer_reduce() + +from tinygrad.tensor import Tensor +from tinygrad.helpers import Context +from tinygrad.device import Device +from tinygrad.engine.jit import TinyJit + + +NV12Frame = namedtuple("NV12Frame", ['width', 'height', 'stride', 'y_height', 'uv_height', 'size']) +WARP_INPUTS = ['tfm', 'big_tfm'] +POLICY_INPUTS = ['img_q', 'big_img_q', 'feat_q', 'desire_q', 'packed_npy_inputs'] + +UV_SCALE_MATRIX = np.array([[0.5, 0, 0], [0, 0.5, 0], [0, 0, 1]], dtype=np.float32) +UV_SCALE_MATRIX_INV = np.linalg.inv(UV_SCALE_MATRIX) + +WARP_DEV = os.getenv('WARP_DEV') + + +def make_random_images(keys, shape, device=None): + return {k: Tensor.randint(shape, low=0, high=256, dtype='uint8', device=device).realize() for k in keys} + + +def warp_perspective_tinygrad(src_flat, M_inv, dst_shape, src_shape, stride_pad, border_fill_val=None): + w_dst, h_dst = dst_shape + h_src, w_src = src_shape + + x = Tensor.arange(w_dst).reshape(1, w_dst).expand(h_dst, w_dst).reshape(-1) + y = Tensor.arange(h_dst).reshape(h_dst, 1).expand(h_dst, w_dst).reshape(-1) + + # inline 3x3 matmul as elementwise to avoid reduce op (enables fusion with gather) + src_x = M_inv[0, 0] * x + M_inv[0, 1] * y + M_inv[0, 2] + src_y = M_inv[1, 0] * x + M_inv[1, 1] * y + M_inv[1, 2] + src_w = M_inv[2, 0] * x + M_inv[2, 1] * y + M_inv[2, 2] + + src_x = src_x / src_w + src_y = src_y / src_w + + x_round = Tensor.round(src_x) + y_round = Tensor.round(src_y) + x_nn_clipped = x_round.clip(0, w_src - 1).cast('int') + y_nn_clipped = y_round.clip(0, h_src - 1).cast('int') + idx = y_nn_clipped * (w_src + stride_pad) + x_nn_clipped + sampled = src_flat[idx] + + if border_fill_val is None: + return sampled + + in_bounds = ((x_round >= 0) & (x_round <= w_src - 1) & + (y_round >= 0) & (y_round <= h_src - 1)).cast(sampled.dtype) + return sampled * in_bounds + Tensor(border_fill_val, dtype=sampled.dtype) * (1 - in_bounds) + + +def frames_to_tensor(frames): + H = (frames.shape[0] * 2) // 3 + W = frames.shape[1] + in_img1 = Tensor.cat(frames[0:H:2, 0::2], + frames[1:H:2, 0::2], + frames[0:H:2, 1::2], + frames[1:H:2, 1::2], + frames[H:H+H//4].reshape((H//2, W//2)), + frames[H+H//4:H+H//2].reshape((H//2, W//2)), dim=0).reshape((6, H//2, W//2)) + return in_img1 + + +def make_frame_prepare(nv12: NV12Frame, model_w, model_h): + cam_w, cam_h, stride, y_height, uv_height, _ = nv12 + uv_offset = stride * y_height + stride_pad = stride - cam_w + + def frame_prepare_tinygrad(input_frame, M_inv): + # UV_SCALE @ M_inv @ UV_SCALE_INV simplifies to elementwise scaling + M_inv_uv = M_inv * Tensor([[1.0, 1.0, 0.5], [1.0, 1.0, 0.5], [2.0, 2.0, 1.0]], device=WARP_DEV) + # deinterleave NV12 UV plane (UVUV... -> separate U, V) + uv = input_frame[uv_offset:uv_offset + uv_height * stride].reshape(uv_height, stride) + with Context(SPLIT_REDUCEOP=0): + y = warp_perspective_tinygrad(input_frame[:cam_h*stride], + M_inv, (model_w, model_h), + (cam_h, cam_w), stride_pad).realize() + u = warp_perspective_tinygrad(uv[:cam_h//2, :cam_w:2].flatten(), + M_inv_uv, (model_w//2, model_h//2), + (cam_h//2, cam_w//2), 0).realize() + v = warp_perspective_tinygrad(uv[:cam_h//2, 1:cam_w:2].flatten(), + M_inv_uv, (model_w//2, model_h//2), + (cam_h//2, cam_w//2), 0).realize() + yuv = y.cat(u).cat(v).reshape((model_h * 3 // 2, model_w)) + tensor = frames_to_tensor(yuv) + return tensor + return frame_prepare_tinygrad + + +def make_warp_input_queues(vision_input_shapes, frame_skip, device): + img = vision_input_shapes['img'] # (1, 12, 128, 256) + n_frames = img[1] // 6 + img_buf_shape = (frame_skip * (n_frames - 1) + 1, 6, img[2], img[3]) + + npy = { + 'tfm': np.zeros((3, 3), dtype=np.float32), + 'big_tfm': np.zeros((3, 3), dtype=np.float32), + } + input_queues = { + 'img_q': Tensor(np.zeros(img_buf_shape, dtype=np.uint8), device=device).contiguous().realize(), + 'big_img_q': Tensor(np.zeros(img_buf_shape, dtype=np.uint8), device=device).contiguous().realize(), + **{k: Tensor(v, device='NPY').realize() for k, v in npy.items()}, + } + return input_queues, npy + + +def get_policy_npy_shapes(input_shapes): + dp = input_shapes['desire_pulse'] # (1, 25, 8) + tc = input_shapes['traffic_convention'] # (1, 2) + at = input_shapes['action_t'] # (1, 2) + fb = input_shapes['features_buffer'] # (1, 24, 512) + # TODO prev_feat shouldn't exist and be handled inside the JIT, but corrupt on QCOM for now + shapes = {'desire': (dp[2],), 'traffic_convention': tuple(tc), 'action_t': tuple(at), 'prev_feat': (fb[0], fb[2])} + return shapes, [math.prod(s) for s in shapes.values()] + + +def make_input_queues(input_shapes, frame_skip, device): + input_queues, npy = make_warp_input_queues(input_shapes, frame_skip, device) + + fb = input_shapes['features_buffer'] # (1, 24, 512), past features only; the model appends the current frame's feature + dp = input_shapes['desire_pulse'] # (1, 25, 8) + + shapes, sizes = get_policy_npy_shapes(input_shapes) + packed_npy_inputs = np.zeros(sum(sizes), dtype=np.float32) + # views into the packed inputs, to be refilled at runtime + npy.update({k: v.reshape(s) for (k, s), v in zip(shapes.items(), np.split(packed_npy_inputs, np.cumsum(sizes[:-1])), strict=True)}) + input_queues.update({ + 'feat_q': Tensor(np.zeros((frame_skip * fb[1], fb[0], fb[2]), dtype=np.float32), device=device).contiguous().realize(), + 'desire_q': Tensor(np.zeros((frame_skip * dp[1], dp[0], dp[2]), dtype=np.float32), device=device).contiguous().realize(), + 'packed_npy_inputs': Tensor(packed_npy_inputs, device='NPY').realize(), + }) + return input_queues, npy + + +def shift_and_sample(buf, new_val, sample_fn): + buf.assign(buf[1:].cat(new_val, dim=0).contiguous()) + return sample_fn(buf) + + +def sample_skip(buf, frame_skip): + return buf[::frame_skip].contiguous().flatten(0, 1).unsqueeze(0) + + +def sample_desire(buf, frame_skip): + return buf.reshape(-1, frame_skip, *buf.shape[1:]).max(1).flatten(0, 1).unsqueeze(0) + + +def make_warp(nv12, model_w, model_h, frame_skip): + frame_prepare = make_frame_prepare(nv12, model_w, model_h) + + def warp(tfm, big_tfm, frame, big_frame): + tfm = tfm.to(WARP_DEV) + big_tfm = big_tfm.to(WARP_DEV) + Tensor.realize(tfm, big_tfm) + + warped_frame = frame_prepare(frame, tfm).unsqueeze(0) + warped_big_frame = frame_prepare(big_frame, big_tfm).unsqueeze(0) + return Tensor.cat(warped_frame, warped_big_frame) + + return warp + + +def make_run_policy(model_runner, model_metadata, frame_skip): + sample_desire_fn = partial(sample_desire, frame_skip=frame_skip) + sample_skip_fn = partial(sample_skip, frame_skip=frame_skip) + npy_shapes, npy_sizes = get_policy_npy_shapes(model_metadata['input_shapes']) + + def run_policy(warped, img_q, big_img_q, feat_q, desire_q, packed_npy_inputs): + packed_npy_inputs = packed_npy_inputs.to(Device.DEFAULT) + warped = warped.to(Device.DEFAULT) + Tensor.realize(packed_npy_inputs, warped) + + img = shift_and_sample(img_q, warped[0:1], sample_skip_fn) + big_img = shift_and_sample(big_img_q, warped[1:2], sample_skip_fn) + + desire, traffic_convention, action_t, prev_feat = (t.reshape(s) for t, s in zip(packed_npy_inputs.split(npy_sizes), npy_shapes.values(), strict=True)) + desire_buf = shift_and_sample(desire_q, desire.reshape(1, 1, -1), sample_desire_fn) + feat_buf = shift_and_sample(feat_q, prev_feat.reshape(1, 1, -1), sample_skip_fn) + + inputs = { + 'img': img, + 'big_img': big_img, + 'features_buffer': feat_buf, + 'desire_pulse': desire_buf, + 'traffic_convention': traffic_convention, + 'action_t': action_t, + } + out = next(iter(model_runner(inputs).values())).cast('float32') + return out, + return run_policy + + +def compile_jit(jit, make_random_inputs, input_keys, make_queues): + SEED = 42 + def random_inputs_run(fn, seed, test_val=None, test_buffers=None, expect_match=True): + input_queues, npy = make_queues(Device.DEFAULT) + rng = np.random.default_rng(seed) + Tensor.manual_seed(seed) + + testing = test_val is not None or test_buffers is not None + n_runs = 1 if testing else 3 + + for i in range(n_runs): + for v in npy.values(): + v[:] = rng.standard_normal(v.shape).astype(v.dtype) + Device.default.synchronize() + random_inputs = make_random_inputs() + st = time.perf_counter() + outs = fn(**{k: input_queues[k] for k in input_keys}, **random_inputs) + mt = time.perf_counter() + Device.default.synchronize() + et = time.perf_counter() + print(f" [{i+1}/{n_runs}] enqueue {(mt-st)*1e3:6.2f} ms -- total {(et-st)*1e3:6.2f} ms") + + if i == 0: + val = [np.copy(v.numpy()) for v in outs] + buffers = [np.copy(v.numpy().copy()) for v in input_queues.values()] + + if test_val is not None: + match = all(np.array_equal(a, b) for a, b in zip(val, test_val, strict=True)) + assert match == expect_match, f"outputs {'differ from' if expect_match else 'match'} baseline (seed={seed})" + if test_buffers is not None: + match = all(np.array_equal(a, b) for a, b in zip(buffers, test_buffers, strict=True)) + assert match == expect_match, f"buffers {'differ from' if expect_match else 'match'} baseline (seed={seed})" + return val, buffers + + print('capture + replay') + test_val, test_buffers = random_inputs_run(jit, SEED) + print('pickle round trip') + with tempfile.TemporaryFile(dir=".") as f: + dump_oob(jit, f) + f.seek(0) + jit = load_oob(f) + random_inputs_run(jit, SEED, test_val, test_buffers, expect_match=True) + random_inputs_run(jit, SEED+1, test_val, test_buffers, expect_match=False) + return jit + + +def _parse_size(s): + w, h = s.lower().split('x') + return int(w), int(h) + + +def read_file_chunked_to_disk(path): + from openpilot.common.file_chunker import open_file_chunked + tmp_path = f'{path}.unchunked' + with open(tmp_path, 'wb') as f, open_file_chunked(path) as src: + shutil.copyfileobj(src, f) + atexit.register(lambda: os.path.exists(tmp_path) and os.remove(tmp_path)) + return tmp_path + + +if __name__ == "__main__": + from tinygrad.nn.onnx import OnnxRunner + from openpilot.system.camerad.cameras.nv12_info import get_nv12_info + from openpilot.selfdrive.modeld.get_model_metadata import make_metadata_dict + p = argparse.ArgumentParser() + p.add_argument('--model-size', type=_parse_size, required=True, help='model input WxH') + p.add_argument('--camera-resolutions', type=_parse_size, nargs='+', required=True, + help='camera resolutions WxH (one or more)') + p.add_argument('--onnx', required=True) + p.add_argument('--output', required=True) + p.add_argument('--frame-skip', type=int, required=True) + args = p.parse_args() + + if 'USB+AMD' in os.environ.get('DEV', ''): + wait_usbgpu_link() + + model_path = read_file_chunked_to_disk(args.onnx) + model_w, model_h = args.model_size + + model_runner = OnnxRunner(model_path) + out = {'metadata': make_metadata_dict(model_path)} + + run_policy_jit = TinyJit(make_run_policy(model_runner, out['metadata'], args.frame_skip), prune=True) + + make_policy_queues = partial(make_input_queues, out['metadata']['input_shapes'], args.frame_skip) + make_random_model_inputs = partial(make_random_images, keys=['warped'], shape=(2, 6, *out['metadata']['input_shapes']['img'][2:]), device=WARP_DEV) + out['run_policy'] = compile_jit(run_policy_jit, make_random_model_inputs, POLICY_INPUTS, + make_policy_queues) + + for cam_w, cam_h in args.camera_resolutions: + nv12 = NV12Frame(cam_w, cam_h, *get_nv12_info(cam_w, cam_h)) + make_random_warp_inputs = partial(make_random_images, keys=['frame', 'big_frame'], shape=nv12.size, device=WARP_DEV) + warp = TinyJit(make_warp(nv12, model_w, model_h, args.frame_skip), prune=True) + make_warp_queues = partial(make_warp_input_queues, out['metadata']['input_shapes'], args.frame_skip) + out[(cam_w,cam_h)] = compile_jit(warp, make_random_warp_inputs, WARP_INPUTS, make_warp_queues) + + with open(args.output, "wb") as f: + dump_oob(out, f) + print(f"Saved JITs to {args.output} ({os.path.getsize(args.output) / 1e6:.2f} MB)") diff --git a/openpilot/selfdrive/modeld/constants.py b/openpilot/selfdrive/modeld/constants.py new file mode 100644 index 0000000000..0fb09262d0 --- /dev/null +++ b/openpilot/selfdrive/modeld/constants.py @@ -0,0 +1,88 @@ +import numpy as np + +def index_function(idx, max_val=192, max_idx=32): + return (max_val) * ((idx/max_idx)**2) + +class ModelConstants: + # time and distance indices + IDX_N = 33 + T_IDXS = [index_function(idx, max_val=10.0) for idx in range(IDX_N)] + X_IDXS = [index_function(idx, max_val=192.0) for idx in range(IDX_N)] + LEAD_T_IDXS = [0., 2., 4., 6., 8., 10.] + LEAD_T_OFFSETS = [0., 2., 4.] + META_T_IDXS = [2., 4., 6., 8., 10.] + + # model inputs constants + N_FRAMES = 2 + MODEL_RUN_FREQ = 20 + MODEL_CONTEXT_FREQ = 5 # "model_trained_fps" + + FEATURE_LEN = 512 + + DESIRE_LEN = 8 + TRAFFIC_CONVENTION_LEN = 2 + LAT_PLANNER_STATE_LEN = 4 + LATERAL_CONTROL_PARAMS_LEN = 2 + PREV_DESIRED_CURV_LEN = 1 + + # model outputs constants + FCW_THRESHOLDS_5MS2 = np.array([.05, .05, .15, .15, .15], dtype=np.float32) + FCW_THRESHOLDS_3MS2 = np.array([.7, .7], dtype=np.float32) + FCW_5MS2_PROBS_WIDTH = 5 + FCW_3MS2_PROBS_WIDTH = 2 + + DISENGAGE_WIDTH = 5 + POSE_WIDTH = 6 + WIDE_FROM_DEVICE_WIDTH = 3 + LEAD_WIDTH = 4 + LANE_LINES_WIDTH = 2 + ROAD_EDGES_WIDTH = 2 + PLAN_WIDTH = 15 + ACTION_WIDTH = 2 + DESIRE_PRED_WIDTH = 8 + LAT_PLANNER_SOLUTION_WIDTH = 4 + DESIRED_CURV_WIDTH = 1 + + NUM_LANE_LINES = 4 + NUM_ROAD_EDGES = 2 + + LEAD_TRAJ_LEN = 6 + DESIRE_PRED_LEN = 4 + + PLAN_MHP_N = 5 + LEAD_MHP_N = 2 + PLAN_MHP_SELECTION = 1 + LEAD_MHP_SELECTION = 3 + + FCW_THRESHOLD_5MS2_HIGH = 0.15 + FCW_THRESHOLD_5MS2_LOW = 0.05 + FCW_THRESHOLD_3MS2 = 0.7 + + CONFIDENCE_BUFFER_LEN = 5 + RYG_GREEN = 0.01165 + RYG_YELLOW = 0.06157 + + POLY_PATH_DEGREE = 4 + +# model outputs slices +class Plan: + POSITION = slice(0, 3) + VELOCITY = slice(3, 6) + ACCELERATION = slice(6, 9) + T_FROM_CURRENT_EULER = slice(9, 12) + ORIENTATION_RATE = slice(12, 15) + +class Meta: + ENGAGED = slice(0, 1) + # next 2, 4, 6, 8, 10 seconds + GAS_DISENGAGE = slice(1, 31, 6) + BRAKE_DISENGAGE = slice(2, 31, 6) + STEER_OVERRIDE = slice(3, 31, 6) + HARD_BRAKE_3 = slice(4, 31, 6) + HARD_BRAKE_4 = slice(5, 31, 6) + HARD_BRAKE_5 = slice(6, 31, 6) + # next 0, 2, 4, 6, 8, 10 seconds + GAS_PRESS = slice(31, 55, 4) + BRAKE_PRESS = slice(32, 55, 4) + LEFT_BLINKER = slice(33, 55, 4) + RIGHT_BLINKER = slice(34, 55, 4) diff --git a/openpilot/selfdrive/modeld/dmonitoringmodeld.py b/openpilot/selfdrive/modeld/dmonitoringmodeld.py new file mode 100755 index 0000000000..554407a223 --- /dev/null +++ b/openpilot/selfdrive/modeld/dmonitoringmodeld.py @@ -0,0 +1,156 @@ +#!/usr/bin/env python3 +import os +from openpilot.selfdrive.modeld.helpers import MODELS_DIR, get_tg_input_devices +from tinygrad.tensor import Tensor +import time +import pickle +import numpy as np + +from openpilot.cereal import messaging +from openpilot.cereal.messaging import PubMaster, SubMaster +from msgq.visionipc import VisionIpcClient, VisionStreamType, VisionBuf +from openpilot.common.swaglog import cloudlog +from openpilot.common.realtime import config_realtime_process +from openpilot.common.transformations.model import dmonitoringmodel_intrinsics +from openpilot.common.transformations.camera import _ar_ox_fisheye, _os_fisheye +from openpilot.system.camerad.cameras.nv12_info import get_nv12_info +from openpilot.common.file_chunker import open_file_chunked +from openpilot.selfdrive.modeld.parse_model_outputs import sigmoid, safe_exp + +PROCESS_NAME = "openpilot.selfdrive.modeld.dmonitoringmodeld" +SEND_RAW_PRED = os.getenv('SEND_RAW_PRED') +MODEL_PKL_PATH = MODELS_DIR / 'dmonitoring_model_tinygrad.pkl' +METADATA_PATH = MODELS_DIR / 'dmonitoring_model_metadata.pkl' + + +class ModelState: + inputs: dict[str, np.ndarray] + output: np.ndarray + + def __init__(self, cam_w: int, cam_h: int): + self.DEV = get_tg_input_devices(PROCESS_NAME, usbgpu=False)['DEV'] + with open(METADATA_PATH, 'rb') as f: + model_metadata = pickle.load(f) + self.input_shapes = model_metadata['input_shapes'] + self.output_slices = model_metadata['output_slices'] + + self.numpy_inputs = { + 'calib': np.zeros(self.input_shapes['calib'], dtype=np.float32), + } + + self.warp_inputs_np = {'transform': np.zeros((3,3), dtype=np.float32)} + self.warp_inputs = {k: Tensor(v, device='NPY') for k,v in self.warp_inputs_np.items()} + self.frame_buf_params = get_nv12_info(cam_w, cam_h) + self.tensor_inputs = {k: Tensor(v, device='NPY').realize() for k,v in self.numpy_inputs.items()} + self._blob_cache : dict[int, Tensor] = {} + self.model_run = pickle.load(open_file_chunked(str(MODEL_PKL_PATH))) + with open(MODELS_DIR / f'dm_warp_{cam_w}x{cam_h}_tinygrad.pkl', "rb") as f: + self.image_warp = pickle.load(f) + + def run(self, buf: VisionBuf, calib: np.ndarray, transform: np.ndarray) -> tuple[np.ndarray, float]: + self.numpy_inputs['calib'][0,:] = calib + + t1 = time.perf_counter() + + ptr = np.frombuffer(buf.data, dtype=np.uint8).ctypes.data + # There is a ringbuffer of imgs, just cache tensors pointing to all of them + if ptr not in self._blob_cache: + self._blob_cache[ptr] = Tensor.from_blob(ptr, (self.frame_buf_params[3],), dtype='uint8', device=self.DEV) + + self.warp_inputs_np['transform'][:] = transform[:] + self.tensor_inputs['input_img'] = self.image_warp(self._blob_cache[ptr], self.warp_inputs['transform']) + + output = self.model_run(**self.tensor_inputs).numpy().flatten() + + t2 = time.perf_counter() + return output, t2 - t1 + +def slice_outputs(model_outputs, output_slices): + return {k: model_outputs[np.newaxis, v] for k,v in output_slices.items()} + +def parse_model_output(model_output): + parsed = {} + parsed['wheel_on_right'] = sigmoid(model_output['wheel_on_right']) + for ds_suffix in ['lhd', 'rhd']: + face_descs = model_output[f'face_descs_{ds_suffix}'] + parsed[f'face_descs_{ds_suffix}'] = face_descs[:, :-6] + parsed[f'face_descs_{ds_suffix}_std'] = safe_exp(face_descs[:, -6:]) + for key in ['face_prob', 'left_eye_prob', 'right_eye_prob','left_blink_prob', 'right_blink_prob', 'sunglasses_prob', 'using_phone_prob', 'sleep_prob']: + parsed[f'{key}_{ds_suffix}'] = sigmoid(model_output[f'{key}_{ds_suffix}']) + return parsed + +def fill_driver_data(msg, model_output, ds_suffix): + msg.faceOrientation = model_output[f'face_descs_{ds_suffix}'][0, :3].tolist() + msg.faceOrientationStd = model_output[f'face_descs_{ds_suffix}_std'][0, :3].tolist() + msg.facePosition = model_output[f'face_descs_{ds_suffix}'][0, 3:5].tolist() + msg.facePositionStd = model_output[f'face_descs_{ds_suffix}_std'][0, 3:5].tolist() + msg.faceProb = model_output[f'face_prob_{ds_suffix}'][0, 0].item() + msg.leftEyeProb = model_output[f'left_eye_prob_{ds_suffix}'][0, 0].item() + msg.rightEyeProb = model_output[f'right_eye_prob_{ds_suffix}'][0, 0].item() + msg.leftBlinkProb = model_output[f'left_blink_prob_{ds_suffix}'][0, 0].item() + msg.rightBlinkProb = model_output[f'right_blink_prob_{ds_suffix}'][0, 0].item() + msg.sunglassesProb = model_output[f'sunglasses_prob_{ds_suffix}'][0, 0].item() + msg.phoneProb = model_output[f'using_phone_prob_{ds_suffix}'][0, 0].item() + msg.sleepProb = model_output[f'sleep_prob_{ds_suffix}'][0, 0].item() + +def get_driverstate_packet(model_output, frame_id: int, location_ts: int, exec_time: float, gpu_exec_time: float): + msg = messaging.new_message('driverStateV2', valid=True) + ds = msg.driverStateV2 + ds.frameId = frame_id + ds.modelExecutionTime = exec_time + ds.gpuExecutionTime = gpu_exec_time + ds.rawPredictions = model_output['raw_pred'] + ds.wheelOnRightProb = model_output['wheel_on_right'][0, 0].item() + fill_driver_data(ds.leftDriverData, model_output, 'lhd') + fill_driver_data(ds.rightDriverData, model_output, 'rhd') + return msg + + +def main(): + config_realtime_process(7, 5) + + cloudlog.warning("connecting to driver stream") + vipc_client = VisionIpcClient("camerad", VisionStreamType.VISION_STREAM_DRIVER, True) + while not vipc_client.connect(False): + time.sleep(0.1) + assert vipc_client.is_connected() + cloudlog.warning(f"connected with buffer size: {vipc_client.buffer_len}") + + model = ModelState(vipc_client.width, vipc_client.height) + cloudlog.warning("models loaded, dmonitoringmodeld starting") + + sm = SubMaster(["liveCalibration"]) + pm = PubMaster(["driverStateV2"]) + + calib = np.zeros(model.numpy_inputs['calib'].size, dtype=np.float32) + model_transform = None + + while True: + buf = vipc_client.recv() + if buf is None: + continue + + if model_transform is None: + cam = _os_fisheye if buf.width == _os_fisheye.width else _ar_ox_fisheye + model_transform = np.linalg.inv(np.dot(dmonitoringmodel_intrinsics, np.linalg.inv(cam.intrinsics))).astype(np.float32) + + sm.update(0) + if sm.updated["liveCalibration"]: + calib[:] = np.array(sm["liveCalibration"].rpyCalib) + + t1 = time.perf_counter() + model_output, gpu_execution_time = model.run(buf, calib, model_transform) + t2 = time.perf_counter() + raw_pred = model_output.tobytes() if SEND_RAW_PRED else b'' + model_output = slice_outputs(model_output, model.output_slices) + model_output = parse_model_output(model_output) + model_output['raw_pred'] = raw_pred + msg = get_driverstate_packet(model_output, vipc_client.frame_id, vipc_client.timestamp_sof, t2 - t1, gpu_execution_time) + pm.send("driverStateV2", msg) + + +if __name__ == "__main__": + try: + main() + except KeyboardInterrupt: + cloudlog.warning("got SIGINT") diff --git a/openpilot/selfdrive/modeld/fill_model_msg.py b/openpilot/selfdrive/modeld/fill_model_msg.py new file mode 100644 index 0000000000..c4c973bb78 --- /dev/null +++ b/openpilot/selfdrive/modeld/fill_model_msg.py @@ -0,0 +1,192 @@ +import os +import capnp +import numpy as np +from openpilot.cereal import log +from openpilot.selfdrive.modeld.constants import ModelConstants, Plan, Meta +from openpilot.sunnypilot.models.helpers import plan_x_idxs_helper + +SEND_RAW_PRED = os.getenv('SEND_RAW_PRED') + +ConfidenceClass = log.ModelDataV2.ConfidenceClass + + +class PublishState: + def __init__(self): + self.disengage_buffer = np.zeros(ModelConstants.CONFIDENCE_BUFFER_LEN*ModelConstants.DISENGAGE_WIDTH, dtype=np.float32) + self.prev_brake_5ms2_probs = np.zeros(ModelConstants.FCW_5MS2_PROBS_WIDTH, dtype=np.float32) + self.prev_brake_3ms2_probs = np.zeros(ModelConstants.FCW_3MS2_PROBS_WIDTH, dtype=np.float32) + +def fill_xyzt(builder, t, x, y, z, x_std=None, y_std=None, z_std=None): + builder.t = t + builder.x = x.tolist() + builder.y = y.tolist() + builder.z = z.tolist() + if x_std is not None: + builder.xStd = x_std.tolist() + if y_std is not None: + builder.yStd = y_std.tolist() + if z_std is not None: + builder.zStd = z_std.tolist() + +def fill_xyvat(builder, t, x, y, v, a, x_std=None, y_std=None, v_std=None, a_std=None): + builder.t = t + builder.x = x.tolist() + builder.y = y.tolist() + builder.v = v.tolist() + builder.a = a.tolist() + if x_std is not None: + builder.xStd = x_std.tolist() + if y_std is not None: + builder.yStd = y_std.tolist() + if v_std is not None: + builder.vStd = v_std.tolist() + if a_std is not None: + builder.aStd = a_std.tolist() + +def fill_xyz_poly(builder, degree, x, y, z): + xyz = np.stack([x, y, z], axis=1) + coeffs = np.polynomial.polynomial.polyfit(ModelConstants.T_IDXS, xyz, deg=degree) + builder.xCoefficients = coeffs[:, 0].tolist() + builder.yCoefficients = coeffs[:, 1].tolist() + builder.zCoefficients = coeffs[:, 2].tolist() + +def fill_lane_line_meta(builder, lane_lines, lane_line_probs): + builder.leftY = lane_lines[1].y[0] + builder.leftProb = lane_line_probs[1] + builder.rightY = lane_lines[2].y[0] + builder.rightProb = lane_line_probs[2] + +def fill_driving_model_data(msg: capnp._DynamicStructBuilder, modelv2_send: capnp._DynamicStructBuilder) -> None: + msg.valid = modelv2_send.valid + modelV2 = modelv2_send.modelV2 + driving_model_data = msg.drivingModelData + driving_model_data.frameId = modelV2.frameId + driving_model_data.frameIdExtra = modelV2.frameIdExtra + driving_model_data.frameDropPerc = modelV2.frameDropPerc + driving_model_data.modelExecutionTime = modelV2.modelExecutionTime + driving_model_data.action = modelV2.action + driving_model_data.meta.laneChangeState = modelV2.meta.laneChangeState + driving_model_data.meta.laneChangeDirection = modelV2.meta.laneChangeDirection + fill_lane_line_meta(driving_model_data.laneLineMeta, modelV2.laneLines, modelV2.laneLineProbs) + fill_xyz_poly(driving_model_data.path, ModelConstants.POLY_PATH_DEGREE, modelV2.position.x, modelV2.position.y, modelV2.position.z) + +def fill_model_msg(msg: capnp._DynamicStructBuilder, net_output_data: dict[str, np.ndarray], action: log.ModelDataV2.Action, + publish_state: PublishState, vipc_frame_id: int, vipc_frame_id_extra: int, + frame_id: int, frame_drop: float, timestamp_eof: int, model_execution_time: float, + valid: bool) -> None: + frame_age = frame_id - vipc_frame_id if frame_id > vipc_frame_id else 0 + frame_drop_perc = frame_drop * 100 + msg.valid = valid + + modelV2 = msg.modelV2 + modelV2.frameId = vipc_frame_id + modelV2.frameIdExtra = vipc_frame_id_extra + modelV2.frameAge = frame_age + modelV2.frameDropPerc = frame_drop_perc + modelV2.timestampEof = timestamp_eof + modelV2.modelExecutionTime = model_execution_time + + # plan + fill_xyzt(modelV2.position, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.POSITION].T, *net_output_data['plan_stds'][0,:,Plan.POSITION].T) + fill_xyzt(modelV2.velocity, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.VELOCITY].T) + fill_xyzt(modelV2.acceleration, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.ACCELERATION].T) + fill_xyzt(modelV2.orientation, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.T_FROM_CURRENT_EULER].T) + fill_xyzt(modelV2.orientationRate, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.ORIENTATION_RATE].T) + + # action + modelV2.action = action + + # times at X_IDXS of edges and lines + LINE_T_IDXS: list[float] = plan_x_idxs_helper(ModelConstants, Plan, net_output_data) + + # lane lines + modelV2.init('laneLines', 4) + for i in range(4): + lane_line = modelV2.laneLines[i] + fill_xyzt(lane_line, LINE_T_IDXS, np.array(ModelConstants.X_IDXS), net_output_data['lane_lines'][0,i,:,0], net_output_data['lane_lines'][0,i,:,1]) + modelV2.laneLineStds = net_output_data['lane_lines_stds'][0,:,0,0].tolist() + modelV2.laneLineProbs = net_output_data['lane_lines_prob'][0,1::2].tolist() + + # road edges + modelV2.init('roadEdges', 2) + for i in range(2): + road_edge = modelV2.roadEdges[i] + fill_xyzt(road_edge, LINE_T_IDXS, np.array(ModelConstants.X_IDXS), net_output_data['road_edges'][0,i,:,0], net_output_data['road_edges'][0,i,:,1]) + modelV2.roadEdgeStds = net_output_data['road_edges_stds'][0,:,0,0].tolist() + + # leads + modelV2.init('leadsV3', 3) + for i in range(3): + lead = modelV2.leadsV3[i] + fill_xyvat(lead, ModelConstants.LEAD_T_IDXS, *net_output_data['lead'][0,i].T, *net_output_data['lead_stds'][0,i].T) + lead.prob = net_output_data['lead_prob'][0,i].tolist() + lead.probTime = ModelConstants.LEAD_T_OFFSETS[i] + + # meta + meta = modelV2.meta + meta.desireState = net_output_data['desire_state'][0].reshape(-1).tolist() + meta.desirePrediction = net_output_data['desire_pred'][0].reshape(-1).tolist() + meta.engagedProb = net_output_data['meta'][0,Meta.ENGAGED].item() + meta.init('disengagePredictions') + disengage_predictions = meta.disengagePredictions + disengage_predictions.t = ModelConstants.META_T_IDXS + disengage_predictions.brakeDisengageProbs = net_output_data['meta'][0,Meta.BRAKE_DISENGAGE].tolist() + disengage_predictions.gasDisengageProbs = net_output_data['meta'][0,Meta.GAS_DISENGAGE].tolist() + disengage_predictions.steerOverrideProbs = net_output_data['meta'][0,Meta.STEER_OVERRIDE].tolist() + disengage_predictions.brake3MetersPerSecondSquaredProbs = net_output_data['meta'][0,Meta.HARD_BRAKE_3].tolist() + disengage_predictions.brake4MetersPerSecondSquaredProbs = net_output_data['meta'][0,Meta.HARD_BRAKE_4].tolist() + disengage_predictions.brake5MetersPerSecondSquaredProbs = net_output_data['meta'][0,Meta.HARD_BRAKE_5].tolist() + disengage_predictions.gasPressProbs = net_output_data['meta'][0,Meta.GAS_PRESS].tolist() + disengage_predictions.brakePressProbs = net_output_data['meta'][0,Meta.BRAKE_PRESS].tolist() + + publish_state.prev_brake_5ms2_probs[:-1] = publish_state.prev_brake_5ms2_probs[1:] + publish_state.prev_brake_5ms2_probs[-1] = net_output_data['meta'][0,Meta.HARD_BRAKE_5][0] + publish_state.prev_brake_3ms2_probs[:-1] = publish_state.prev_brake_3ms2_probs[1:] + publish_state.prev_brake_3ms2_probs[-1] = net_output_data['meta'][0,Meta.HARD_BRAKE_3][0] + hard_brake_predicted = (publish_state.prev_brake_5ms2_probs > ModelConstants.FCW_THRESHOLDS_5MS2).all() and \ + (publish_state.prev_brake_3ms2_probs > ModelConstants.FCW_THRESHOLDS_3MS2).all() + meta.hardBrakePredicted = hard_brake_predicted.item() + + # confidence + if vipc_frame_id % (2*ModelConstants.MODEL_RUN_FREQ) == 0: + # any disengage prob + brake_disengage_probs = net_output_data['meta'][0,Meta.BRAKE_DISENGAGE] + gas_disengage_probs = net_output_data['meta'][0,Meta.GAS_DISENGAGE] + steer_override_probs = net_output_data['meta'][0,Meta.STEER_OVERRIDE] + any_disengage_probs = 1-((1-brake_disengage_probs)*(1-gas_disengage_probs)*(1-steer_override_probs)) + # independent disengage prob for each 2s slice + ind_disengage_probs = np.r_[any_disengage_probs[0], np.diff(any_disengage_probs) / (1 - any_disengage_probs[:-1])] + # rolling buf for 2, 4, 6, 8, 10s + publish_state.disengage_buffer[:-ModelConstants.DISENGAGE_WIDTH] = publish_state.disengage_buffer[ModelConstants.DISENGAGE_WIDTH:] + publish_state.disengage_buffer[-ModelConstants.DISENGAGE_WIDTH:] = ind_disengage_probs + + score = 0. + for i in range(ModelConstants.DISENGAGE_WIDTH): + score += publish_state.disengage_buffer[i*ModelConstants.DISENGAGE_WIDTH+ModelConstants.DISENGAGE_WIDTH-1-i].item() / ModelConstants.DISENGAGE_WIDTH + if score < ModelConstants.RYG_GREEN: + modelV2.confidence = ConfidenceClass.green + elif score < ModelConstants.RYG_YELLOW: + modelV2.confidence = ConfidenceClass.yellow + else: + modelV2.confidence = ConfidenceClass.red + + # raw prediction if enabled + if SEND_RAW_PRED: + modelV2.rawPredictions = net_output_data['raw_pred'].tobytes() + +def fill_pose_msg(msg: capnp._DynamicStructBuilder, net_output_data: dict[str, np.ndarray], + vipc_frame_id: int, vipc_dropped_frames: int, timestamp_eof: int, live_calib_seen: bool) -> None: + msg.valid = live_calib_seen & (vipc_dropped_frames < 1) + cameraOdometry = msg.cameraOdometry + + cameraOdometry.frameId = vipc_frame_id + cameraOdometry.timestampEof = timestamp_eof + + cameraOdometry.trans = net_output_data['pose'][0,:3].tolist() + cameraOdometry.rot = net_output_data['pose'][0,3:].tolist() + cameraOdometry.wideFromDeviceEuler = net_output_data['wide_from_device_euler'][0,:].tolist() + cameraOdometry.roadTransformTrans = net_output_data['road_transform'][0,:3].tolist() + cameraOdometry.transStd = net_output_data['pose_stds'][0,:3].tolist() + cameraOdometry.rotStd = net_output_data['pose_stds'][0,3:].tolist() + cameraOdometry.wideFromDeviceEulerStd = net_output_data['wide_from_device_euler_stds'][0,:].tolist() + cameraOdometry.roadTransformTransStd = net_output_data['road_transform_stds'][0,:3].tolist() diff --git a/openpilot/selfdrive/modeld/get_model_metadata.py b/openpilot/selfdrive/modeld/get_model_metadata.py new file mode 100755 index 0000000000..e4c173957a --- /dev/null +++ b/openpilot/selfdrive/modeld/get_model_metadata.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +import sys +import pathlib +import codecs +import pickle +from typing import Any + +from tinygrad.nn.onnx import OnnxPBParser + + +class MetadataOnnxPBParser(OnnxPBParser): + def _parse_ModelProto(self) -> dict: + obj: dict[str, Any] = {"graph": {"input": [], "output": []}, "metadata_props": []} + for fid, wire_type in self._parse_message(self.reader.len): + match fid: + case 7: + obj["graph"] = self._parse_GraphProto() + case 14: + obj["metadata_props"].append(self._parse_StringStringEntryProto()) + case _: + self.reader.skip_field(wire_type) + return obj + + +def get_name_and_shape(value_info: dict[str, Any]) -> tuple[str, tuple[int, ...]]: + shape = tuple(int(dim) if isinstance(dim, int) else 0 for dim in value_info["parsed_type"].shape) + name = value_info["name"] + return name, shape + + +def get_metadata_value_by_name(model: dict[str, Any], name: str) -> str | Any: + for prop in model["metadata_props"]: + if prop["key"] == name: + return prop["value"] + return None + + +def make_metadata_dict(model_path): + model = MetadataOnnxPBParser(model_path).parse() + output_slices = get_metadata_value_by_name(model, 'output_slices') + assert output_slices is not None, 'output_slices not found in metadata' + return { + 'model_checkpoint': get_metadata_value_by_name(model, 'model_checkpoint'), + 'output_slices': pickle.loads(codecs.decode(output_slices.encode(), "base64")), + 'input_shapes': dict(get_name_and_shape(x) for x in model["graph"]["input"]), + 'output_shapes': dict(get_name_and_shape(x) for x in model["graph"]["output"]), + } + + +if __name__ == "__main__": + model_path = pathlib.Path(sys.argv[1]) + metadata_path = model_path.parent / (model_path.stem + '_metadata.pkl') + with open(metadata_path, 'wb') as f: + pickle.dump(make_metadata_dict(model_path), f) + print(f'saved metadata to {metadata_path}') diff --git a/openpilot/selfdrive/modeld/helpers.py b/openpilot/selfdrive/modeld/helpers.py new file mode 100644 index 0000000000..608bc6aa64 --- /dev/null +++ b/openpilot/selfdrive/modeld/helpers.py @@ -0,0 +1,59 @@ +import io +import json +import pickle +import shutil +import struct +import tempfile +from pathlib import Path + +MODELS_DIR = Path(__file__).resolve().parent / 'models' +TG_INPUT_DEVICES_PATH = MODELS_DIR / 'tg_input_devices.json' +USBGPU_VID = 0xADD1 +USBGPU_PID = 0x0001 + + +def get_tg_input_devices(process_name: str, usbgpu: bool): + with open(TG_INPUT_DEVICES_PATH) as f: + return json.load(f)[process_name]['default' if not usbgpu else 'usbgpu'] + +def modeld_pkl_path(usbgpu: bool): + prefix = 'big_' if usbgpu else '' + return MODELS_DIR / f'{prefix}driving_tinygrad.pkl' + +def dump_oob(obj, f): + with tempfile.TemporaryFile(dir=".") as tmp: + def buffer_callback(pb: pickle.PickleBuffer): + m = pb.raw() + tmp.write(struct.pack(' bool: + for d in Path("/sys/bus/usb/devices").glob("*"): + try: + if int((d / "idVendor").read_text(), 16) == USBGPU_VID and \ + int((d / "idProduct").read_text(), 16) == USBGPU_PID: + return True + except Exception: + pass + return False diff --git a/openpilot/selfdrive/modeld/modeld.py b/openpilot/selfdrive/modeld/modeld.py new file mode 100755 index 0000000000..1ca1a71f35 --- /dev/null +++ b/openpilot/selfdrive/modeld/modeld.py @@ -0,0 +1,338 @@ +#!/usr/bin/env python3 +import os +os.environ['GMMU'] = '0' # for usbgpu fast loading, noop for qcom +from tinygrad.tensor import Tensor +import time +import numpy as np +import openpilot.cereal.messaging as messaging +from openpilot.cereal import log +from opendbc.car.structs import car +from openpilot.cereal.messaging import PubMaster, SubMaster +from msgq.visionipc import VisionIpcClient, VisionStreamType, VisionBuf +from opendbc.car.car_helpers import get_demo_car_params +from openpilot.common.swaglog import cloudlog +from openpilot.common.params import Params +from openpilot.common.filter_simple import FirstOrderFilter +from openpilot.common.realtime import config_realtime_process, DT_MDL +from openpilot.common.transformations.camera import DEVICE_CAMERAS +from openpilot.system.camerad.cameras.nv12_info import get_nv12_info +from openpilot.common.transformations.model import get_warp_matrix +from openpilot.selfdrive.controls.lib.desire_helper import DesireHelper +from openpilot.selfdrive.controls.lib.drive_helpers import get_accel_from_plan, smooth_value, get_curvature_from_plan +from openpilot.selfdrive.modeld.parse_model_outputs import Parser +from openpilot.selfdrive.modeld.compile_modeld import make_input_queues, WARP_INPUTS, POLICY_INPUTS +from openpilot.selfdrive.modeld.fill_model_msg import fill_model_msg, fill_driving_model_data, fill_pose_msg, PublishState +from openpilot.common.file_chunker import open_file_chunked, get_manifest_path +from openpilot.selfdrive.modeld.constants import ModelConstants, Plan +from openpilot.selfdrive.modeld.helpers import usbgpu_present, modeld_pkl_path, get_tg_input_devices, load_oob +from openpilot.selfdrive.modeld.usbgpu_link import wait_usbgpu_link + +from openpilot.sunnypilot.livedelay.helpers import get_lat_delay +from openpilot.sunnypilot.modeld_v2.modeld_base import ModelStateBase + +PROCESS_NAME = "openpilot.selfdrive.modeld.modeld" +SEND_RAW_PRED = os.getenv('SEND_RAW_PRED') + +LAT_SMOOTH_SECONDS = 0.0 +LONG_SMOOTH_SECONDS = 0.3 +MIN_LAT_CONTROL_SPEED = 0.3 + + +def get_action_from_model(model_output: dict[str, np.ndarray], prev_action: log.ModelDataV2.Action, + lat_action_t: float, long_action_t: float, v_ego: float) -> log.ModelDataV2.Action: + if 'action' not in model_output: + plan = model_output['plan'][0] + desired_accel, should_stop = get_accel_from_plan(plan[:,Plan.VELOCITY][:,0], + plan[:,Plan.ACCELERATION][:,0], + ModelConstants.T_IDXS, + action_t=long_action_t) + desired_curvature = get_curvature_from_plan(plan[:,Plan.T_FROM_CURRENT_EULER][:,2], + plan[:,Plan.ORIENTATION_RATE][:,2], + ModelConstants.T_IDXS, + v_ego, + lat_action_t) + else: + desired_accel = model_output['action'][0,1] + desired_curvature = model_output['action'][0,0] / (max(1.0, v_ego))**2 + should_stop = (v_ego < 0.3 and desired_accel < 0.1) + desired_accel = smooth_value(desired_accel, prev_action.desiredAcceleration, LONG_SMOOTH_SECONDS) + if v_ego > MIN_LAT_CONTROL_SPEED: + desired_curvature = smooth_value(desired_curvature, prev_action.desiredCurvature, LAT_SMOOTH_SECONDS) + else: + desired_curvature = prev_action.desiredCurvature + + return log.ModelDataV2.Action(desiredCurvature=float(desired_curvature), + desiredAcceleration=float(desired_accel), + shouldStop=bool(should_stop)) + + +class FrameMeta: + frame_id: int = 0 + timestamp_sof: int = 0 + timestamp_eof: int = 0 + + def __init__(self, vipc=None): + if vipc is not None: + self.frame_id, self.timestamp_sof, self.timestamp_eof = vipc.frame_id, vipc.timestamp_sof, vipc.timestamp_eof + + +class ModelState(ModelStateBase): + prev_desire: np.ndarray # for tracking the rising edge of the pulse + + def __init__(self, cam_w: int, cam_h: int, usbgpu: bool): + ModelStateBase.__init__(self) + self.LAT_SMOOTH_SECONDS = LAT_SMOOTH_SECONDS + input_devices = get_tg_input_devices(PROCESS_NAME, usbgpu) + self.WARP_DEV, self.QUEUE_DEV = input_devices['WARP_DEV'], input_devices['QUEUE_DEV'] + jits = load_oob(open_file_chunked(modeld_pkl_path(usbgpu))) + metadata = jits['metadata'] + self.input_shapes = metadata['input_shapes'] + self.vision_input_names = [k for k in self.input_shapes if 'img' in k] + self.output_slices = metadata['output_slices'] + + self.prev_desire = np.zeros(ModelConstants.DESIRE_LEN, dtype=np.float32) + + self.frame_skip = ModelConstants.MODEL_RUN_FREQ // ModelConstants.MODEL_CONTEXT_FREQ + self.input_queues, self.npy = make_input_queues(self.input_shapes, self.frame_skip, device=self.QUEUE_DEV) + self.full_frames: dict[str, Tensor] = {} + self._blob_cache: dict[tuple[str, int], Tensor] = {} + self.parser = Parser() + self.frame_buf_params = {k: get_nv12_info(cam_w, cam_h) for k in ('img', 'big_img')} + self.run_policy = jits['run_policy'] + self.warp = jits[(cam_w,cam_h)] + + def slice_outputs(self, model_outputs: np.ndarray, output_slices: dict[str, slice]) -> dict[str, np.ndarray]: + parsed_model_outputs = {k: model_outputs[np.newaxis, v] for k,v in output_slices.items()} + return parsed_model_outputs + + def run(self, bufs: dict[str, VisionBuf], transforms: dict[str, np.ndarray], + inputs: dict[str, np.ndarray]) -> dict[str, np.ndarray] | None: + for key in bufs.keys(): + ptr = np.frombuffer(bufs[key].data, dtype=np.uint8).ctypes.data + yuv_size = self.frame_buf_params[key][3] + # There is a ringbuffer of imgs, just cache tensors pointing to all of them + cache_key = (key, ptr) + if cache_key not in self._blob_cache: + self._blob_cache[cache_key] = Tensor.from_blob(ptr, (yuv_size,), dtype='uint8', device=self.WARP_DEV) + self.full_frames[key] = self._blob_cache[cache_key] + + # Model decides when action is completed, so desire input is just a pulse triggered on rising edge + inputs['desire_pulse'][0] = 0 + self.npy['desire'][:] = np.where(inputs['desire_pulse'] - self.prev_desire > .99, inputs['desire_pulse'], 0) + self.prev_desire[:] = inputs['desire_pulse'] + self.npy['traffic_convention'][:] = inputs['traffic_convention'] + self.npy['action_t'][:] = inputs['action_t'] + self.npy['tfm'][:,:] = transforms['img'][:,:] + self.npy['big_tfm'][:,:] = transforms['big_img'][:,:] + + warped = self.warp(**{k: self.input_queues[k] for k in WARP_INPUTS}, frame=self.full_frames['img'], big_frame=self.full_frames['big_img']) + + outs, = self.run_policy( + **{k: self.input_queues[k] for k in POLICY_INPUTS if k in self.input_queues}, warped=warped + ) + model_output = outs.numpy()[0] + outputs_dict = self.parser.parse_outputs(self.slice_outputs(model_output, self.output_slices)) + self.npy['prev_feat'][:] = model_output[self.output_slices['hidden_state']] + + if SEND_RAW_PRED: + outputs_dict['raw_pred'] = model_output.copy() + return outputs_dict + + +def main(demo=False): + cloudlog.warning("modeld init") + + _present = usbgpu_present() + _compiled = os.path.isfile(get_manifest_path(modeld_pkl_path(usbgpu=True))) + USBGPU = _present and _compiled + params = Params() + params.put_bool("UsbGpuPresent", _present) + params.put_bool("UsbGpuCompiled", _compiled) + + config_realtime_process(7, 54) + + # visionipc clients + while True: + available_streams = VisionIpcClient.available_streams("camerad", block=False) + if available_streams: + use_extra_client = VisionStreamType.VISION_STREAM_WIDE_ROAD in available_streams and VisionStreamType.VISION_STREAM_ROAD in available_streams + main_wide_camera = VisionStreamType.VISION_STREAM_ROAD not in available_streams + break + time.sleep(.1) + + vipc_client_main_stream = VisionStreamType.VISION_STREAM_WIDE_ROAD if main_wide_camera else VisionStreamType.VISION_STREAM_ROAD + vipc_client_main = VisionIpcClient("camerad", vipc_client_main_stream, True) + vipc_client_extra = VisionIpcClient("camerad", VisionStreamType.VISION_STREAM_WIDE_ROAD, False) + cloudlog.warning(f"vision stream set up, main_wide_camera: {main_wide_camera}, use_extra_client: {use_extra_client}") + + while not vipc_client_main.connect(False): + time.sleep(0.1) + while use_extra_client and not vipc_client_extra.connect(False): + time.sleep(0.1) + + cloudlog.warning(f"connected main cam with buffer size: {vipc_client_main.buffer_len} ({vipc_client_main.width} x {vipc_client_main.height})") + if use_extra_client: + cloudlog.warning(f"connected extra cam with buffer size: {vipc_client_extra.buffer_len} ({vipc_client_extra.width} x {vipc_client_extra.height})") + + if USBGPU: + wait_usbgpu_link() + st = time.monotonic() + cloudlog.warning("loading model") + model = ModelState(vipc_client_main.width, vipc_client_main.height, USBGPU) + cloudlog.warning(f"models loaded in {time.monotonic() - st:.1f}s, modeld starting") + + # messaging + pm = PubMaster(["modelV2", "drivingModelData", "cameraOdometry", "modelDataV2SP"]) + sm = SubMaster(["deviceState", "carState", "roadCameraState", "liveCalibration", "driverMonitoringState", "carControl", "liveDelay"]) + + publish_state = PublishState() + params = Params() + + # setup filter to track dropped frames + frame_dropped_filter = FirstOrderFilter(0., 10., 1. / ModelConstants.MODEL_RUN_FREQ) + frame_id = 0 + last_vipc_frame_id = 0 + run_count = 0 + + model_transform_main = np.zeros((3, 3), dtype=np.float32) + model_transform_extra = np.zeros((3, 3), dtype=np.float32) + live_calib_seen = False + buf_main, buf_extra = None, None + meta_main = FrameMeta() + meta_extra = FrameMeta() + + if demo: + CP = get_demo_car_params() + else: + CP = messaging.log_from_bytes(params.get("CarParams", block=True), car.CarParams) + cloudlog.info("modeld got CarParams: %s", CP.brand) + + # TODO this needs more thought, use .2s extra for now to estimate other delays + # TODO Move smooth seconds to action function + long_delay = CP.longitudinalActuatorDelay + LONG_SMOOTH_SECONDS + prev_action = log.ModelDataV2.Action() + + DH = DesireHelper() + + while True: + # Keep receiving frames until we are at least 1 frame ahead of previous extra frame + while meta_main.timestamp_sof < meta_extra.timestamp_sof + 25000000: + buf_main = vipc_client_main.recv() + meta_main = FrameMeta(vipc_client_main) + if buf_main is None: + break + + if buf_main is None: + cloudlog.debug("vipc_client_main no frame") + continue + + if use_extra_client: + # Keep receiving extra frames until frame id matches main camera + while True: + buf_extra = vipc_client_extra.recv() + meta_extra = FrameMeta(vipc_client_extra) + if buf_extra is None or meta_main.timestamp_sof < meta_extra.timestamp_sof + 25000000: + break + + if buf_extra is None: + cloudlog.debug("vipc_client_extra no frame") + continue + + if abs(meta_main.timestamp_sof - meta_extra.timestamp_sof) > 10000000: + cloudlog.error(f"frames out of sync! main: {meta_main.frame_id} ({meta_main.timestamp_sof / 1e9:.5f}),\ + extra: {meta_extra.frame_id} ({meta_extra.timestamp_sof / 1e9:.5f})") + + else: + # Use single camera + buf_extra = buf_main + meta_extra = meta_main + + sm.update(0) + desire = DH.desire + is_rhd = sm["driverMonitoringState"].isRHD + frame_id = sm["roadCameraState"].frameId + v_ego = max(sm["carState"].vEgo, 0.) + if sm.frame % 60 == 0: + model.lat_delay = get_lat_delay(params, sm["liveDelay"].lateralDelay) + lat_delay = model.lat_delay + LAT_SMOOTH_SECONDS + if sm.updated["liveCalibration"] and sm.seen['roadCameraState'] and sm.seen['deviceState']: + device_from_calib_euler = np.array(sm["liveCalibration"].rpyCalib, dtype=np.float32) + dc = DEVICE_CAMERAS[(str(sm['deviceState'].deviceType), str(sm['roadCameraState'].sensor))] + model_transform_main = get_warp_matrix(device_from_calib_euler, dc.ecam.intrinsics if main_wide_camera else dc.fcam.intrinsics, False).astype(np.float32) + has_wide_camera = use_extra_client or main_wide_camera + model_transform_extra = get_warp_matrix(device_from_calib_euler, dc.ecam.intrinsics if has_wide_camera else dc.fcam.intrinsics, True).astype(np.float32) + live_calib_seen = True + + traffic_convention = np.zeros(2) + traffic_convention[int(is_rhd)] = 1 + + vec_desire = np.zeros(ModelConstants.DESIRE_LEN, dtype=np.float32) + if desire >= 0 and desire < ModelConstants.DESIRE_LEN: + vec_desire[desire] = 1 + + # tracked dropped frames + vipc_dropped_frames = max(0, meta_main.frame_id - last_vipc_frame_id - 1) + frames_dropped = frame_dropped_filter.update(min(vipc_dropped_frames, 10)) + if run_count < 10: # let frame drops warm up + frame_dropped_filter.x = 0. + frames_dropped = 0. + run_count = run_count + 1 + + frame_drop_ratio = frames_dropped / (1 + frames_dropped) + + bufs = {name: buf_extra if 'big' in name else buf_main for name in model.vision_input_names} + transforms = {name: model_transform_extra if 'big' in name else model_transform_main for name in model.vision_input_names} + frame_delay = DT_MDL # compensate for time passed since the frame was captured: current_time - timestamp_eof is 50ms on average + action_delay = DT_MDL / 2 # middle of the interval between model output (current state) and next frame (expected state) + lat_action_t = lat_delay + frame_delay + action_delay + long_action_t = long_delay + frame_delay + action_delay + inputs: dict[str, np.ndarray] = { + 'desire_pulse': vec_desire, + 'traffic_convention': traffic_convention, + 'action_t': np.array([lat_action_t, long_action_t], dtype=np.float32), + } + + mt1 = time.perf_counter() + model_output = model.run(bufs, transforms, inputs) + mt2 = time.perf_counter() + model_execution_time = mt2 - mt1 + + if model_output is not None: + modelv2_send = messaging.new_message('modelV2') + drivingdata_send = messaging.new_message('drivingModelData') + posenet_send = messaging.new_message('cameraOdometry') + mdv2sp_send = messaging.new_message('modelDataV2SP') + + action = get_action_from_model(model_output, prev_action, lat_action_t, long_action_t, v_ego) + prev_action = action + fill_model_msg(modelv2_send, model_output, action, + publish_state, meta_main.frame_id, meta_extra.frame_id, frame_id, + frame_drop_ratio, meta_main.timestamp_eof, model_execution_time, live_calib_seen) + + desire_state = modelv2_send.modelV2.meta.desireState + l_lane_change_prob = desire_state[log.Desire.laneChangeLeft] + r_lane_change_prob = desire_state[log.Desire.laneChangeRight] + lane_change_prob = l_lane_change_prob + r_lane_change_prob + DH.update(sm['carState'], sm['carControl'].latActive, lane_change_prob) + modelv2_send.modelV2.meta.laneChangeState = DH.lane_change_state + modelv2_send.modelV2.meta.laneChangeDirection = DH.lane_change_direction + mdv2sp_send.modelDataV2SP.laneTurnDirection = DH.lane_turn_direction + + fill_driving_model_data(drivingdata_send, modelv2_send) + fill_pose_msg(posenet_send, model_output, meta_main.frame_id, vipc_dropped_frames, meta_main.timestamp_eof, live_calib_seen) + pm.send('modelV2', modelv2_send) + pm.send('drivingModelData', drivingdata_send) + pm.send('cameraOdometry', posenet_send) + pm.send('modelDataV2SP', mdv2sp_send) + last_vipc_frame_id = meta_main.frame_id + + +if __name__ == "__main__": + try: + import argparse + parser = argparse.ArgumentParser() + parser.add_argument('--demo', action='store_true', help='A boolean for demo mode.') + args = parser.parse_args() + main(demo=args.demo) + except KeyboardInterrupt: + cloudlog.warning("got SIGINT") diff --git a/openpilot/selfdrive/modeld/models/README.md b/openpilot/selfdrive/modeld/models/README.md new file mode 100644 index 0000000000..0055a0f1e3 --- /dev/null +++ b/openpilot/selfdrive/modeld/models/README.md @@ -0,0 +1,2 @@ +## Neural networks in openpilot +To view the architecture of the ONNX networks, you can use [netron](https://netron.app/) diff --git a/selfdrive/locationd/test/__init__.py b/openpilot/selfdrive/modeld/models/__init__.py similarity index 100% rename from selfdrive/locationd/test/__init__.py rename to openpilot/selfdrive/modeld/models/__init__.py diff --git a/openpilot/selfdrive/modeld/models/big_driving_supercombo.onnx b/openpilot/selfdrive/modeld/models/big_driving_supercombo.onnx new file mode 100644 index 0000000000..4a04bd7833 --- /dev/null +++ b/openpilot/selfdrive/modeld/models/big_driving_supercombo.onnx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a501760a9d1d5fef0eab2b8c5d122d06124fc26dc8e0782e0aa94b82a208f0ff +size 1757355221 diff --git a/openpilot/selfdrive/modeld/models/dmonitoring_model.onnx b/openpilot/selfdrive/modeld/models/dmonitoring_model.onnx new file mode 100644 index 0000000000..bd3f2c85a6 --- /dev/null +++ b/openpilot/selfdrive/modeld/models/dmonitoring_model.onnx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3e7b31dfbc0a5234f1baf196513b77fc6af12204b8a8ffe8ee0417e48352f316 +size 7494962 diff --git a/openpilot/selfdrive/modeld/models/driving_supercombo.onnx b/openpilot/selfdrive/modeld/models/driving_supercombo.onnx new file mode 100644 index 0000000000..f0672eab48 --- /dev/null +++ b/openpilot/selfdrive/modeld/models/driving_supercombo.onnx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:659727c4d4839adc4992a254409a54259a8756a743f2d567bf5fdc6579f8009b +size 60881999 diff --git a/openpilot/selfdrive/modeld/parse_model_outputs.py b/openpilot/selfdrive/modeld/parse_model_outputs.py new file mode 100644 index 0000000000..839c20f7cc --- /dev/null +++ b/openpilot/selfdrive/modeld/parse_model_outputs.py @@ -0,0 +1,120 @@ +import numpy as np +from openpilot.selfdrive.modeld.constants import ModelConstants + +def safe_exp(x, out=None): + # -11 is around 10**14, more causes float16 overflow + return np.exp(np.clip(x, -np.inf, 11), out=out) + +def sigmoid(x): + return 1. / (1. + safe_exp(-x)) + +def softmax(x, axis=-1): + x -= np.max(x, axis=axis, keepdims=True) + if x.dtype == np.float32 or x.dtype == np.float64: + safe_exp(x, out=x) + else: + x = safe_exp(x) + x /= np.sum(x, axis=axis, keepdims=True) + return x + +class Parser: + def __init__(self, ignore_missing=False): + self.ignore_missing = ignore_missing + + def check_missing(self, outs, name): + missing = name not in outs + if missing and not self.ignore_missing: + raise ValueError(f"Missing output {name}") + return missing + + def parse_categorical_crossentropy(self, name, outs, out_shape=None): + if self.check_missing(outs, name): + return + raw = outs[name] + if out_shape is not None: + raw = raw.reshape((raw.shape[0],) + out_shape) + outs[name] = softmax(raw, axis=-1) + + def parse_binary_crossentropy(self, name, outs): + if self.check_missing(outs, name): + return + raw = outs[name] + outs[name] = sigmoid(raw) + + def parse_mdn(self, name, outs, in_N=0, out_N=1, out_shape=()): + if self.check_missing(outs, name): + return + raw = outs[name] + raw = raw.reshape((raw.shape[0], max(in_N, 1), -1)) + + n_values = (raw.shape[2] - out_N)//2 + pred_mu = raw[:,:,:n_values] + pred_std = safe_exp(raw[:,:,n_values: 2*n_values]) + + if in_N > 1: + weights = np.zeros((raw.shape[0], in_N, out_N), dtype=raw.dtype) + for i in range(out_N): + weights[:,:,i - out_N] = softmax(raw[:,:,i - out_N], axis=-1) + + if out_N == 1: + for fidx in range(weights.shape[0]): + idxs = np.argsort(weights[fidx][:,0])[::-1] + weights[fidx] = weights[fidx][idxs] + pred_mu[fidx] = pred_mu[fidx][idxs] + pred_std[fidx] = pred_std[fidx][idxs] + full_shape = tuple([raw.shape[0], in_N] + list(out_shape)) + outs[name + '_weights'] = weights + outs[name + '_hypotheses'] = pred_mu.reshape(full_shape) + outs[name + '_stds_hypotheses'] = pred_std.reshape(full_shape) + + pred_mu_final = np.zeros((raw.shape[0], out_N, n_values), dtype=raw.dtype) + pred_std_final = np.zeros((raw.shape[0], out_N, n_values), dtype=raw.dtype) + for fidx in range(weights.shape[0]): + for hidx in range(out_N): + idxs = np.argsort(weights[fidx,:,hidx])[::-1] + pred_mu_final[fidx, hidx] = pred_mu[fidx, idxs[0]] + pred_std_final[fidx, hidx] = pred_std[fidx, idxs[0]] + else: + pred_mu_final = pred_mu + pred_std_final = pred_std + + if out_N > 1: + final_shape = tuple([raw.shape[0], out_N] + list(out_shape)) + else: + final_shape = tuple([raw.shape[0],] + list(out_shape)) + outs[name] = pred_mu_final.reshape(final_shape) + outs[name + '_stds'] = pred_std_final.reshape(final_shape) + + def is_mhp(self, outs, name, shape): + if self.check_missing(outs, name): + return False + if outs[name].shape[1] == 2 * shape: + return False + return True + + def parse_vision_outputs(self, outs: dict[str, np.ndarray]) -> dict[str, np.ndarray]: + self.parse_mdn('pose', outs, in_N=0, out_N=0, out_shape=(ModelConstants.POSE_WIDTH,)) + self.parse_mdn('wide_from_device_euler', outs, in_N=0, out_N=0, out_shape=(ModelConstants.WIDE_FROM_DEVICE_WIDTH,)) + self.parse_mdn('road_transform', outs, in_N=0, out_N=0, out_shape=(ModelConstants.POSE_WIDTH,)) + self.parse_mdn('lane_lines', outs, in_N=0, out_N=0, out_shape=(ModelConstants.NUM_LANE_LINES,ModelConstants.IDX_N,ModelConstants.LANE_LINES_WIDTH)) + self.parse_mdn('road_edges', outs, in_N=0, out_N=0, out_shape=(ModelConstants.NUM_ROAD_EDGES,ModelConstants.IDX_N,ModelConstants.LANE_LINES_WIDTH)) + self.parse_binary_crossentropy('lane_lines_prob', outs) + self.parse_categorical_crossentropy('desire_pred', outs, out_shape=(ModelConstants.DESIRE_PRED_LEN,ModelConstants.DESIRE_PRED_WIDTH)) + self.parse_binary_crossentropy('meta', outs) + self.parse_binary_crossentropy('lead_prob', outs) + lead_mhp = self.is_mhp(outs, 'lead', ModelConstants.LEAD_MHP_SELECTION * ModelConstants.LEAD_TRAJ_LEN * ModelConstants.LEAD_WIDTH) + lead_in_N, lead_out_N = (ModelConstants.LEAD_MHP_N, ModelConstants.LEAD_MHP_SELECTION) if lead_mhp else (0, 0) + lead_out_shape = (ModelConstants.LEAD_TRAJ_LEN, ModelConstants.LEAD_WIDTH) if lead_mhp else \ + (ModelConstants.LEAD_MHP_SELECTION, ModelConstants.LEAD_TRAJ_LEN, ModelConstants.LEAD_WIDTH) + self.parse_mdn('lead', outs, in_N=lead_in_N, out_N=lead_out_N, out_shape=lead_out_shape) + return outs + + def parse_policy_outputs(self, outs: dict[str, np.ndarray]) -> dict[str, np.ndarray]: + self.parse_mdn('plan', outs, in_N=0, out_N=0, out_shape=(ModelConstants.IDX_N, ModelConstants.PLAN_WIDTH)) + self.parse_categorical_crossentropy('desire_state', outs, out_shape=(ModelConstants.DESIRE_PRED_WIDTH,)) + return outs + + def parse_outputs(self, outs: dict[str, np.ndarray]) -> dict[str, np.ndarray]: + outs = self.parse_vision_outputs(outs) + outs = self.parse_policy_outputs(outs) + return outs diff --git a/openpilot/selfdrive/modeld/usbgpu_link.py b/openpilot/selfdrive/modeld/usbgpu_link.py new file mode 100644 index 0000000000..ef12cba939 --- /dev/null +++ b/openpilot/selfdrive/modeld/usbgpu_link.py @@ -0,0 +1,34 @@ +import time +from pathlib import Path + +from openpilot.common.swaglog import cloudlog +from openpilot.common.hardware.usb import CHESTNUT_VENDOR_ID, CHESTNUT_PRODUCT_ID, usb_devices, controller, read_int + +STABLE_SECONDS = 2.0 +STABLE_THRESHOLD = 5.0 # link errors per second + + +def _chestnut_portli() -> Path | None: + for device in usb_devices(): + if read_int(device / "idVendor", 16) == CHESTNUT_VENDOR_ID and \ + read_int(device / "idProduct", 16) == CHESTNUT_PRODUCT_ID: + ctrl = controller(device) + if ctrl is not None and (ctrl / "portli").exists(): + return ctrl / "portli" + return None + + +def wait_usbgpu_link(timeout: float = 30.0) -> None: + portli = _chestnut_portli() + if portli is None: + return + + t0 = time.monotonic() + while time.monotonic() - t0 < timeout: + start = read_int(portli, 0) + time.sleep(STABLE_SECONDS) + rate = (read_int(portli, 0) - start) / STABLE_SECONDS + if rate <= STABLE_THRESHOLD: + return + cloudlog.warning(f"usbgpu link not stable: {rate:.0f} errors/s") + cloudlog.error("usbgpu link never stabilized") diff --git a/openpilot/selfdrive/monitoring/dmonitoringd.py b/openpilot/selfdrive/monitoring/dmonitoringd.py new file mode 100755 index 0000000000..085a13fcb1 --- /dev/null +++ b/openpilot/selfdrive/monitoring/dmonitoringd.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python3 +import openpilot.cereal.messaging as messaging +from openpilot.common.params import Params +from openpilot.common.realtime import config_realtime_process +from openpilot.selfdrive.monitoring.policy import DriverMonitoring + + +def dmonitoringd_thread(): + config_realtime_process([0, 1, 2, 3], 5) + + params = Params() + pm = messaging.PubMaster(['driverMonitoringState']) + sm = messaging.SubMaster(['driverStateV2', 'liveCalibration', 'carState', 'selfdriveState', 'modelV2', + 'carControl'], poll='driverStateV2') + + DM = DriverMonitoring(rhd_saved=params.get_bool("IsRhdDetected"), always_on=params.get_bool("AlwaysOnDM")) + demo_mode=False + + # 20Hz <- dmonitoringmodeld + while True: + sm.update() + if not sm.updated['driverStateV2']: + # iterate when model has new output + continue + + valid = sm.all_checks() + if demo_mode and sm.valid['driverStateV2']: + DM.run_step(sm, demo=True) + elif valid: + DM.run_step(sm, demo=demo_mode) + + # publish + dat = DM.get_state_packet(valid=valid) + pm.send('driverMonitoringState', dat) + + # load live always-on toggle + if sm['driverStateV2'].frameId % 40 == 1: + DM.always_on = params.get_bool("AlwaysOnDM") + demo_mode = params.get_bool("IsDriverViewEnabled") + + # save rhd virtual toggle every 5 mins + if (sm['driverStateV2'].frameId % 6000 == 0 and not demo_mode and + DM.wheelpos_offsetter.filtered_stat.n > DM.settings._WHEELPOS_FILTER_MIN_COUNT and + DM.wheel_on_right == (DM.wheelpos_offsetter.filtered_stat.M > DM.settings._WHEELPOS_THRESHOLD)): + params.put_bool("IsRhdDetected", DM.wheel_on_right) + +def main(): + dmonitoringd_thread() + + +if __name__ == '__main__': + main() diff --git a/openpilot/selfdrive/monitoring/policy.py b/openpilot/selfdrive/monitoring/policy.py new file mode 100644 index 0000000000..1489e9c798 --- /dev/null +++ b/openpilot/selfdrive/monitoring/policy.py @@ -0,0 +1,468 @@ +from collections import defaultdict +from math import atan2, radians +import numpy as np + +from openpilot.cereal import log +from opendbc.car.structs import car +import openpilot.cereal.messaging as messaging +from openpilot.common.realtime import DT_DMON +from openpilot.common.filter_simple import FirstOrderFilter +from openpilot.common.params import Params +from openpilot.common.stat_live import RunningStatFilter +from openpilot.common.transformations.camera import DEVICE_CAMERAS + +AlertLevel = log.DriverMonitoringState.AlertLevel +MonitoringPolicy = log.DriverMonitoringState.MonitoringPolicy + +def to_percent(v): + return int(min(max(v * 100., 0.), 100.)) + +# ****************************************************************************************** +# NOTE: To fork maintainers. +# Disabling or nerfing safety features will get you and your users banned from our servers. +# We recommend that you do not change these numbers from the defaults. +# ****************************************************************************************** + +class DRIVER_MONITOR_SETTINGS: + def __init__(self): + # https://eur-lex.europa.eu/legal-content/EN/TXT/PDF/?uri=OJ:L_202501899 + self._ALERT_MIN_SPEED = 2.8 # 10 km/h + + self._WHEELTOUCH_POLICY_ALERT_1_TIMEOUT = 5. + self._WHEELTOUCH_POLICY_ALERT_2_TIMEOUT = 15. + self._WHEELTOUCH_POLICY_ALERT_3_TIMEOUT = 25. + self._VISION_POLICY_ALERT_1_TIMEOUT = 5. + self._VISION_POLICY_ALERT_2_TIMEOUT = 8. + self._VISION_POLICY_ALERT_3_TIMEOUT = 13. + + # no response = alert_3 sustained for certain amount of time + self._NO_RESPONSE_TIMEOUT = 5. + + # lockout specs + self._MAX_ALERT_3 = 2 + self._MAX_NO_RESPONSE = 1 + self._LOCKOUT_TIMES = [int(60 * n_min / DT_DMON) for n_min in [1, 5, 15, 30]] + + self._TIMEOUT_RECOVERY_FACTOR_MAX = 5. + self._TIMEOUT_RECOVERY_FACTOR_MIN = 1.25 + + self._FACE_THRESHOLD = 0.7 + self._EYE_THRESHOLD = 0.65 + self._SG_THRESHOLD = 0.9 + self._BLINK_THRESHOLD = 0.865 + self._PHONE_THRESH = 0.5 + self._POSE_PITCH_THRESHOLD = 0.3133 + self._POSE_PITCH_THRESHOLD_SLACK = 0.3237 + self._POSE_PITCH_THRESHOLD_STRICT = self._POSE_PITCH_THRESHOLD + self._POSE_YAW_THRESHOLD = 0.4020 + self._POSE_YAW_THRESHOLD_SLACK = 0.5042 + self._POSE_YAW_THRESHOLD_STRICT = self._POSE_YAW_THRESHOLD + self._POSE_YAW_MIN_STEER_DEG = 30 + self._POSE_YAW_STEER_FACTOR = 0.15 + self._POSE_YAW_STEER_MAX_OFFSET = 0.3927 + self._PITCH_NATURAL_OFFSET = 0.011 # initial value before offset is learned + self._PITCH_NATURAL_THRESHOLD = 0.449 + self._YAW_NATURAL_OFFSET = 0.075 # initial value before offset is learned + self._PITCH_NATURAL_VAR = 3*0.01 + self._YAW_NATURAL_VAR = 3*0.05 + self._PITCH_MAX_OFFSET = 0.124 + self._PITCH_MIN_OFFSET = -0.0881 + self._YAW_MAX_OFFSET = 0.289 + self._YAW_MIN_OFFSET = -0.0246 + + self._DCAM_UNCERTAIN_ALERT_THRESHOLD = 0.1 + self._DCAM_UNCERTAIN_ALERT_COUNT = int(60 / DT_DMON) + self._DCAM_UNCERTAIN_RESET_COUNT = int(2 / DT_DMON) + self._HI_STD_THRESHOLD = 0.3 + self._HI_STD_FALLBACK_TIME = int(10 / DT_DMON) # fall back to wheel touch if model is uncertain for 10s + self._DISTRACTED_FILTER_TS = 0.25 # 0.6Hz + + self._POSE_CALIB_MIN_SPEED = 13 # 30 mph + self._POSE_OFFSET_MIN_COUNT = int(60 / DT_DMON) # valid data counts before calibration completes, 1min cumulative + self._POSE_OFFSET_MAX_COUNT = int(360 / DT_DMON) # stop deweighting new data after 6 min, aka "short term memory" + self._WHEELPOS_CALIB_MIN_SPEED = 11 + self._WHEELPOS_THRESHOLD = 0.5 + self._WHEELPOS_FILTER_MIN_COUNT = int(15 / DT_DMON) # allow 15 seconds to converge wheel side + self._WHEELPOS_DATA_AVG = 0.03 + self._WHEELPOS_DATA_VAR = 3*5.5e-5 + self._WHEELPOS_MAX_COUNT = -1 + +class DriverPose: + def __init__(self, settings): + pitch_filter_raw_priors = (settings._PITCH_NATURAL_OFFSET, settings._PITCH_NATURAL_VAR, 2) + yaw_filter_raw_priors = (settings._YAW_NATURAL_OFFSET, settings._YAW_NATURAL_VAR, 2) + self.yaw = 0. + self.pitch = 0. + self.pitch_offsetter = RunningStatFilter(raw_priors=pitch_filter_raw_priors, max_trackable=settings._POSE_OFFSET_MAX_COUNT) + self.yaw_offsetter = RunningStatFilter(raw_priors=yaw_filter_raw_priors, max_trackable=settings._POSE_OFFSET_MAX_COUNT) + self.calibrated = False + self.low_std = True + self.cfactor_pitch = 1. + self.cfactor_yaw = 1. + self.steer_yaw_offset = 0. + +class DriverBlink: + def __init__(self): + self.left = 0. + self.right = 0. + +# model output refers to center of undistorted+leveled image +ref_undistorted_cam = DEVICE_CAMERAS[("tici", "ar0231")].dcam +dcam_undistorted_FL = 598.0 +dcam_undistorted_W, dcam_undistorted_H = (ref_undistorted_cam.width, ref_undistorted_cam.height) + +def face_orientation_from_model(orient_model, pos_model, rpy_calib): + pitch_model = orient_model[0] + yaw_model = orient_model[1] + + face_pixel_position = ((pos_model[0]+0.5)*dcam_undistorted_W, (pos_model[1]+0.5)*dcam_undistorted_H) + yaw_focal_angle = atan2(face_pixel_position[0] - dcam_undistorted_W//2, dcam_undistorted_FL) + pitch_focal_angle = atan2(face_pixel_position[1] - dcam_undistorted_H//2, dcam_undistorted_FL) + + pitch = pitch_model + pitch_focal_angle + yaw = -yaw_model + yaw_focal_angle + + pitch -= rpy_calib[1] + yaw -= rpy_calib[2] + return pitch, yaw + + +class DriverMonitoring: + def __init__(self, rhd_saved=False, settings=None, always_on=False): + # init policy settings + self.settings = settings if settings is not None else DRIVER_MONITOR_SETTINGS() + + # init driver status + wheelpos_filter_raw_priors = (self.settings._WHEELPOS_DATA_AVG, self.settings._WHEELPOS_DATA_VAR, 2) + self.wheelpos_offsetter = RunningStatFilter(raw_priors=wheelpos_filter_raw_priors, max_trackable=self.settings._WHEELPOS_MAX_COUNT) + self.pose = DriverPose(settings=self.settings) + self.blink = DriverBlink() + self.phone_prob = 0. + + self.alert_level = AlertLevel.none + self.always_on = always_on + self.distracted_types = defaultdict(bool) + self.driver_distracted = False + self.driver_distraction_filter = FirstOrderFilter(0., self.settings._DISTRACTED_FILTER_TS, DT_DMON) + self.wheel_on_right = False + self.wheel_on_right_last = None + self.wheel_on_right_default = rhd_saved + self.face_detected = False + self.alert_3_cnt = 0 + self.cnt_since_alert_3 = 0 + self.no_response_timeout = int(self.settings._NO_RESPONSE_TIMEOUT / DT_DMON) + self.no_response_cnt = 0 + self.lockout_active = Params().get_bool("DriverTooDistracted") + self.lockout_count = Params().get("DriverLockoutCount") or 0 + self.lockout_duration = self.settings._LOCKOUT_TIMES[min(max(self.lockout_count - 1, 0), len(self.settings._LOCKOUT_TIMES) - 1)] + self.lockout_time_elapsed = 0 + self.step_change = 0. + self.active_policy = MonitoringPolicy.vision + self.driver_interacting = False + self.is_model_uncertain = False + self.hi_stds = 0 + self.model_std_max = 0. + self.threshold_alert_1 = 0. + self.threshold_alert_2 = 0. + self.dcam_uncertain_cnt = 0 + self.dcam_reset_cnt = 0 + + self._reset_awareness() + self._set_policy(MonitoringPolicy.vision) + + def _reset_awareness(self): + self.awareness = 1. + self.last_vision_awareness = 1. + self.last_wheeltouch_awareness = 1. + + def _set_policy(self, target_policy): + if self.active_policy == MonitoringPolicy.vision and self.awareness <= self.threshold_alert_2: + if target_policy == MonitoringPolicy.vision: + self.step_change = DT_DMON / self.settings._VISION_POLICY_ALERT_3_TIMEOUT + else: + self.step_change = 0. + return # no exploit after orange alert + elif self.awareness <= 0.: + return + + if target_policy == MonitoringPolicy.vision: + # when falling back from passive mode to active mode, reset awareness to avoid false alert + if self.active_policy != MonitoringPolicy.vision: + self.last_wheeltouch_awareness = self.awareness + self.awareness = self.last_vision_awareness + + self.threshold_alert_1 = 1. - self.settings._VISION_POLICY_ALERT_1_TIMEOUT / self.settings._VISION_POLICY_ALERT_3_TIMEOUT + self.threshold_alert_2 = 1. - self.settings._VISION_POLICY_ALERT_2_TIMEOUT / self.settings._VISION_POLICY_ALERT_3_TIMEOUT + self.step_change = DT_DMON / self.settings._VISION_POLICY_ALERT_3_TIMEOUT + self.active_policy = MonitoringPolicy.vision + else: + if self.active_policy == MonitoringPolicy.vision: + self.last_vision_awareness = self.awareness + self.awareness = self.last_wheeltouch_awareness + + self.threshold_alert_1 = 1. - self.settings._WHEELTOUCH_POLICY_ALERT_1_TIMEOUT / self.settings._WHEELTOUCH_POLICY_ALERT_3_TIMEOUT + self.threshold_alert_2 = 1. - self.settings._WHEELTOUCH_POLICY_ALERT_2_TIMEOUT / self.settings._WHEELTOUCH_POLICY_ALERT_3_TIMEOUT + self.step_change = DT_DMON / self.settings._WHEELTOUCH_POLICY_ALERT_3_TIMEOUT + self.active_policy = MonitoringPolicy.wheeltouch + + def _set_pose_strictness(self, brake_disengage_prob, car_speed): + bp = brake_disengage_prob + k1 = max(-0.00156*((car_speed-16)**2)+0.6, 0.2) + bp_normal = max(min(bp / k1, 0.5),0) + self.pose.cfactor_pitch = np.interp(bp_normal, [0, 0.5], + [self.settings._POSE_PITCH_THRESHOLD_SLACK, + self.settings._POSE_PITCH_THRESHOLD_STRICT]) / self.settings._POSE_PITCH_THRESHOLD + self.pose.cfactor_yaw = np.interp(bp_normal, [0, 0.5], + [self.settings._POSE_YAW_THRESHOLD_SLACK, + self.settings._POSE_YAW_THRESHOLD_STRICT]) / self.settings._POSE_YAW_THRESHOLD + + def _get_distracted_types(self): + self.distracted_types = defaultdict(bool) + + if not self.pose.calibrated: + pitch_error = self.pose.pitch - self.settings._PITCH_NATURAL_OFFSET + yaw_error = self.pose.yaw - self.settings._YAW_NATURAL_OFFSET + else: + pitch_error = self.pose.pitch - min(max(self.pose.pitch_offsetter.filtered_stat.mean(), + self.settings._PITCH_MIN_OFFSET), self.settings._PITCH_MAX_OFFSET) + yaw_error = self.pose.yaw - min(max(self.pose.yaw_offsetter.filtered_stat.mean(), + self.settings._YAW_MIN_OFFSET), self.settings._YAW_MAX_OFFSET) + pitch_error = 0 if pitch_error > 0 else abs(pitch_error) # no positive pitch limit + + if yaw_error * self.pose.steer_yaw_offset > 0: # unidirectional + yaw_error = max(abs(yaw_error) - min(abs(self.pose.steer_yaw_offset), self.settings._POSE_YAW_STEER_MAX_OFFSET), 0.) + else: + yaw_error = abs(yaw_error) + + pitch_threshold = self.settings._POSE_PITCH_THRESHOLD * self.pose.cfactor_pitch if self.pose.calibrated else self.settings._PITCH_NATURAL_THRESHOLD + yaw_threshold = self.settings._POSE_YAW_THRESHOLD * self.pose.cfactor_yaw + + self.distracted_types['pose'] = bool((pitch_error > pitch_threshold) or (yaw_error > yaw_threshold)) + self.distracted_types['eye'] = bool((self.blink.left + self.blink.right)*0.5 > self.settings._BLINK_THRESHOLD) + self.distracted_types['phone'] = bool(self.phone_prob > self.settings._PHONE_THRESH) + + def _update_states(self, driver_state, cal_rpy, car_speed, op_engaged, lowspeed, demo_mode=False, steering_angle_deg=0.): + rhd_pred = driver_state.wheelOnRightProb + # calibrates only when there's movement and either face detected + if car_speed > self.settings._WHEELPOS_CALIB_MIN_SPEED and (driver_state.leftDriverData.faceProb > self.settings._FACE_THRESHOLD or + driver_state.rightDriverData.faceProb > self.settings._FACE_THRESHOLD): + self.wheelpos_offsetter.push_and_update(rhd_pred) + + wheelpos_calibrated = self.wheelpos_offsetter.filtered_stat.n >= self.settings._WHEELPOS_FILTER_MIN_COUNT + + if wheelpos_calibrated or demo_mode: + self.wheel_on_right = self.wheelpos_offsetter.filtered_stat.M > self.settings._WHEELPOS_THRESHOLD + else: + self.wheel_on_right = self.wheel_on_right_default # use default/saved if calibration is unfinished + # make sure no switching when engaged + if op_engaged and self.wheel_on_right_last is not None and self.wheel_on_right_last != self.wheel_on_right and not demo_mode: + self.wheel_on_right = self.wheel_on_right_last + driver_data = driver_state.rightDriverData if self.wheel_on_right else driver_state.leftDriverData + if not all(len(x) > 0 for x in (driver_data.faceOrientation, driver_data.facePosition, + driver_data.faceOrientationStd, driver_data.facePositionStd)): + return + + self.face_detected = driver_data.faceProb > self.settings._FACE_THRESHOLD + self.pose.pitch, self.pose.yaw = face_orientation_from_model(driver_data.faceOrientation, driver_data.facePosition, cal_rpy) + steer_d = max(abs(steering_angle_deg) - self.settings._POSE_YAW_MIN_STEER_DEG, 0.) + self.pose.steer_yaw_offset = radians(steer_d) * -np.sign(steering_angle_deg) * self.settings._POSE_YAW_STEER_FACTOR + if self.wheel_on_right: + self.pose.yaw *= -1 + self.pose.steer_yaw_offset *= -1 + self.wheel_on_right_last = self.wheel_on_right + self.model_std_max = max(driver_data.faceOrientationStd[0], driver_data.faceOrientationStd[1]) + self.pose.low_std = self.model_std_max < self.settings._HI_STD_THRESHOLD + self.blink.left = driver_data.leftBlinkProb * (driver_data.leftEyeProb > self.settings._EYE_THRESHOLD) \ + * (driver_data.sunglassesProb < self.settings._SG_THRESHOLD) + self.blink.right = driver_data.rightBlinkProb * (driver_data.rightEyeProb > self.settings._EYE_THRESHOLD) \ + * (driver_data.sunglassesProb < self.settings._SG_THRESHOLD) + self.phone_prob = driver_data.phoneProb + + self._get_distracted_types() + self.driver_distracted = any(self.distracted_types.values()) and driver_data.faceProb > self.settings._FACE_THRESHOLD and self.pose.low_std + self.driver_distraction_filter.update(self.driver_distracted) + + # only update offsetter when driver is actively driving the car above a certain speed + if self.face_detected and car_speed > self.settings._POSE_CALIB_MIN_SPEED and self.pose.low_std and (not op_engaged or not self.driver_distracted): + self.pose.pitch_offsetter.push_and_update(self.pose.pitch) + self.pose.yaw_offsetter.push_and_update(self.pose.yaw) + + self.pose.calibrated = self.pose.pitch_offsetter.filtered_stat.n >= self.settings._POSE_OFFSET_MIN_COUNT and \ + self.pose.yaw_offsetter.filtered_stat.n >= self.settings._POSE_OFFSET_MIN_COUNT + + if self.face_detected and not self.driver_distracted: + dcam_uncertain = self.model_std_max > self.settings._DCAM_UNCERTAIN_ALERT_THRESHOLD + if dcam_uncertain and not lowspeed: + self.dcam_uncertain_cnt += 1 + self.dcam_reset_cnt = 0 + else: + self.dcam_reset_cnt += 1 + if self.dcam_reset_cnt > self.settings._DCAM_UNCERTAIN_RESET_COUNT: + self.dcam_uncertain_cnt = 0 + + self.is_model_uncertain = self.hi_stds >= self.settings._HI_STD_FALLBACK_TIME + self._set_policy(MonitoringPolicy.vision if self.face_detected and not self.is_model_uncertain else MonitoringPolicy.wheeltouch) + if self.face_detected and not self.pose.low_std and not self.driver_distracted: + self.hi_stds += 1 + elif self.face_detected and self.pose.low_std: + self.hi_stds = 0 + + def _update_events(self, driver_engaged, op_engaged, lowspeed, wrong_gear): + self.alert_level = AlertLevel.none + self.driver_interacting = driver_engaged + + if self.alert_3_cnt >= self.settings._MAX_ALERT_3 or self.no_response_cnt >= self.settings._MAX_NO_RESPONSE: + if not self.lockout_active: + self.lockout_count += 1 + self.lockout_duration = self.settings._LOCKOUT_TIMES[min(self.lockout_count - 1, len(self.settings._LOCKOUT_TIMES) - 1)] + Params().put("DriverLockoutCount", self.lockout_count) + self.lockout_active = True + + if self.lockout_active: + self.lockout_time_elapsed += 1 + if self.lockout_time_elapsed > self.lockout_duration: + self.lockout_active = False + self.alert_3_cnt = 0 + self.cnt_since_alert_3 = 0 + self.no_response_cnt = 0 + self.lockout_time_elapsed = 0 + + always_on_valid = self.always_on and not wrong_gear + if (self.driver_interacting and self.awareness > 0 and self.active_policy == MonitoringPolicy.wheeltouch) or \ + (not always_on_valid and not op_engaged) or \ + (always_on_valid and not op_engaged and self.awareness <= 0): + # always reset on disengage with normal mode; disengage resets only on red if always on + self._reset_awareness() + return + + awareness_prev = self.awareness + _reaching_alert_1 = self.awareness - self.step_change <= self.threshold_alert_1 + _reaching_alert_3 = self.awareness - self.step_change <= 0 + lowspeed_exemption = lowspeed and _reaching_alert_1 + always_on_exemption = always_on_valid and not op_engaged and _reaching_alert_3 + + if self.awareness > 0 and \ + ((self.driver_distraction_filter.x < 0.37 and self.face_detected and self.pose.low_std) or lowspeed_exemption): + if self.driver_interacting: + self._reset_awareness() + return + # only restore awareness when paying attention and alert is not red + self.awareness = min(self.awareness + ((self.settings._TIMEOUT_RECOVERY_FACTOR_MAX-self.settings._TIMEOUT_RECOVERY_FACTOR_MIN)* + (1.-self.awareness)+self.settings._TIMEOUT_RECOVERY_FACTOR_MIN)*self.step_change, 1.) + if self.awareness == 1.: + self.last_wheeltouch_awareness = min(self.last_wheeltouch_awareness + self.step_change, 1.) + # don't display alert banner when awareness is recovering and has cleared orange + if self.awareness > self.threshold_alert_2: + return + + certainly_distracted = self.driver_distraction_filter.x > 0.63 and self.driver_distracted and self.face_detected + maybe_distracted = self.is_model_uncertain or not self.face_detected + + if certainly_distracted or maybe_distracted: + # should always be counting if distracted unless at low speed and reaching green + # also will not be reaching 0 if DM is active when not engaged + if not (lowspeed_exemption or always_on_exemption): + self.awareness = max(self.awareness - self.step_change, -0.1) + + if self.awareness <= 0.: + # terminal alert: disengagement required + self.alert_level = AlertLevel.three + if awareness_prev > 0.: + self.alert_3_cnt += 1 + self.cnt_since_alert_3 = 0 + else: + self.cnt_since_alert_3 += 1 + if self.cnt_since_alert_3 == self.no_response_timeout: + self.no_response_cnt += 1 + else: + if self.awareness <= self.threshold_alert_2: + self.alert_level = AlertLevel.two + elif self.awareness <= self.threshold_alert_1: + self.alert_level = AlertLevel.one + + def get_state_packet(self, valid=True): + # build driverMonitoringState packet + dat = messaging.new_message('driverMonitoringState', valid=valid) + dm = dat.driverMonitoringState + + dm.lockout = self.lockout_active + dm.lockoutCount = self.lockout_count + if self.lockout_active: + dm.lockoutMinutesRemaining = max(1, round((self.lockout_duration - self.lockout_time_elapsed) * DT_DMON / 60.)) + dm.alert3Count = self.alert_3_cnt + dm.noResponseCount = self.no_response_cnt + dm.noResponseForceDecel = self.alert_level == AlertLevel.three and self.cnt_since_alert_3 >= self.no_response_timeout + dm.alwaysOn = self.always_on + dm.alwaysOnLockout = self.always_on and self.awareness <= self.threshold_alert_2 + dm.alertLevel = self.alert_level + dm.activePolicy = self.active_policy + dm.isRHD = self.wheel_on_right + dm.rhdCalibration.calibratedPercent = to_percent(self.wheelpos_offsetter.filtered_stat.n / self.settings._WHEELPOS_FILTER_MIN_COUNT) + dm.rhdCalibration.offset = self.wheelpos_offsetter.filtered_stat.M + + dm.visionPolicyState.awarenessPercent = to_percent(self.last_vision_awareness if self.active_policy != MonitoringPolicy.vision else self.awareness) + dm.visionPolicyState.awarenessStep = self.step_change if self.active_policy == MonitoringPolicy.vision else 0. + dm.visionPolicyState.isDistracted = self.driver_distracted + dm.visionPolicyState.distractedTypes.pose = self.distracted_types['pose'] + dm.visionPolicyState.distractedTypes.eye = self.distracted_types['eye'] + dm.visionPolicyState.distractedTypes.phone = self.distracted_types['phone'] + dm.visionPolicyState.faceDetected = self.face_detected + dm.visionPolicyState.pose.pitch = self.pose.pitch + dm.visionPolicyState.pose.yaw = self.pose.yaw + dm.visionPolicyState.pose.calibrated = self.pose.calibrated + dm.visionPolicyState.pose.pitchCalib.calibratedPercent = to_percent(self.pose.pitch_offsetter.filtered_stat.n / self.settings._POSE_OFFSET_MIN_COUNT) + dm.visionPolicyState.pose.pitchCalib.offset = self.pose.pitch_offsetter.filtered_stat.M + dm.visionPolicyState.pose.yawCalib.calibratedPercent = to_percent(self.pose.yaw_offsetter.filtered_stat.n / self.settings._POSE_OFFSET_MIN_COUNT) + dm.visionPolicyState.pose.yawCalib.offset = self.pose.yaw_offsetter.filtered_stat.M + dm.visionPolicyState.pose.uncertainty = self.model_std_max + dm.visionPolicyState.wheeltouchFallbackPercent = to_percent(self.hi_stds / self.settings._HI_STD_FALLBACK_TIME) + dm.visionPolicyState.uncertainOffroadAlertPercent = to_percent(self.dcam_uncertain_cnt / self.settings._DCAM_UNCERTAIN_ALERT_COUNT) + + dm.wheeltouchPolicyState.awarenessPercent = to_percent(self.last_wheeltouch_awareness if self.active_policy == MonitoringPolicy.vision else self.awareness) + dm.wheeltouchPolicyState.awarenessStep = 0. if self.active_policy == MonitoringPolicy.vision else self.step_change + dm.wheeltouchPolicyState.driverInteracting = self.driver_interacting + return dat + + def run_step(self, sm, demo=False): + if demo: + car_speed = 30 + enabled = True + wrong_gear = False + lowspeed = False + driver_engaged = False + brake_disengage_prob = 1.0 + steering_angle_deg = 0.0 + rpyCalib = [0., 0., 0.] + else: + car_speed = sm['carState'].vEgo + enabled = sm['selfdriveState'].enabled or sm['carControl'].latActive + wrong_gear = sm['carState'].gearShifter not in (car.CarState.GearShifter.drive, car.CarState.GearShifter.low) + lowspeed = car_speed < self.settings._ALERT_MIN_SPEED + driver_engaged = sm['carState'].steeringPressed or (sm['selfdriveState'].enabled and sm['carState'].gasPressed) + brake_disengage_prob = sm['modelV2'].meta.disengagePredictions.brakeDisengageProbs[0] # brake disengage prob in next 2s + steering_angle_deg = sm['carState'].steeringAngleDeg + rpyCalib = sm['liveCalibration'].rpyCalib + + self._set_pose_strictness( + brake_disengage_prob=brake_disengage_prob, + car_speed=car_speed, + ) + + # Parse data from dmonitoringmodeld + self._update_states( + driver_state=sm['driverStateV2'], + cal_rpy=rpyCalib, + car_speed=car_speed, + op_engaged=enabled, + lowspeed=lowspeed, + demo_mode=demo, + steering_angle_deg=steering_angle_deg, + ) + + # Update distraction events + self._update_events( + driver_engaged=driver_engaged, + op_engaged=enabled, + lowspeed=lowspeed, + wrong_gear=wrong_gear, + ) diff --git a/openpilot/selfdrive/monitoring/test_monitoring.py b/openpilot/selfdrive/monitoring/test_monitoring.py new file mode 100644 index 0000000000..accf496b47 --- /dev/null +++ b/openpilot/selfdrive/monitoring/test_monitoring.py @@ -0,0 +1,277 @@ +import pytest + +from openpilot.cereal import log +from opendbc.car.structs import car +from openpilot.common.realtime import DT_DMON +from openpilot.selfdrive.monitoring.policy import DriverMonitoring, DRIVER_MONITOR_SETTINGS + +EventName = log.OnroadEvent.EventName +dm_settings = DRIVER_MONITOR_SETTINGS() + +TEST_TIMESPAN = 120 # seconds +DISTRACTED_SECONDS_TO_ORANGE = dm_settings._VISION_POLICY_ALERT_2_TIMEOUT + 1 +DISTRACTED_SECONDS_TO_RED = dm_settings._VISION_POLICY_ALERT_3_TIMEOUT + 1 +INVISIBLE_SECONDS_TO_ORANGE = dm_settings._WHEELTOUCH_POLICY_ALERT_2_TIMEOUT + 1 +INVISIBLE_SECONDS_TO_RED = dm_settings._WHEELTOUCH_POLICY_ALERT_3_TIMEOUT + 1 + +def make_msg(face_detected, distracted=False, model_uncertain=False): + ds = log.DriverStateV2.new_message() + ds.leftDriverData.faceOrientation = [0., 0., 0.] + ds.leftDriverData.facePosition = [0., 0.] + ds.leftDriverData.faceProb = 1. * face_detected + ds.leftDriverData.leftEyeProb = 1. + ds.leftDriverData.rightEyeProb = 1. + ds.leftDriverData.leftBlinkProb = 1. * distracted + ds.leftDriverData.rightBlinkProb = 1. * distracted + ds.leftDriverData.faceOrientationStd = [1.*model_uncertain, 1.*model_uncertain, 1.*model_uncertain] + ds.leftDriverData.facePositionStd = [1.*model_uncertain, 1.*model_uncertain] + # TODO: test both separately when e2e is used + ds.leftDriverData.phoneProb = 0. + return ds + + +# driver state from neural net, 10Hz +msg_NO_FACE_DETECTED = make_msg(False) +msg_ATTENTIVE = make_msg(True) +msg_DISTRACTED = make_msg(True, distracted=True) +msg_ATTENTIVE_UNCERTAIN = make_msg(True, model_uncertain=True) +msg_DISTRACTED_UNCERTAIN = make_msg(True, distracted=True, model_uncertain=True) +msg_DISTRACTED_BUT_SOMEHOW_UNCERTAIN = make_msg(True, distracted=True, model_uncertain=dm_settings._HI_STD_THRESHOLD*1.5) + +# driver interaction with car +car_interaction_DETECTED = True +car_interaction_NOT_DETECTED = False + +# some common state vectors +always_no_face = [msg_NO_FACE_DETECTED] * int(TEST_TIMESPAN / DT_DMON) +always_attentive = [msg_ATTENTIVE] * int(TEST_TIMESPAN / DT_DMON) +always_distracted = [msg_DISTRACTED] * int(TEST_TIMESPAN / DT_DMON) +always_true = [True] * int(TEST_TIMESPAN / DT_DMON) +always_false = [False] * int(TEST_TIMESPAN / DT_DMON) + +class TestMonitoring: + def _run_seq(self, msgs, interaction, engaged, lowspeed): + DM = DriverMonitoring() + alert_lvls = [] + for idx in range(len(msgs)): + DM._update_states(msgs[idx], [0, 0, 0], 0, engaged[idx], lowspeed[idx]) + # cal_rpy and car_speed don't matter here + + # evaluate events at 10Hz for tests + DM._update_events(interaction[idx], engaged[idx], lowspeed[idx], 0) + alert_lvls.append(DM.alert_level) + assert len(alert_lvls) == len(msgs), f"got {len(alert_lvls)} for {len(msgs)} driverState input msgs" + return alert_lvls, DM + + + # engaged, driver is attentive all the time + def test_fully_aware_driver(self): + alert_lvls, d_status = self._run_seq(always_attentive, always_false, always_true, always_false) + assert all(a == 0 for a in alert_lvls) + assert d_status.active_policy == log.DriverMonitoringState.MonitoringPolicy.vision + + # engaged, driver is distracted and does nothing + def test_fully_distracted_driver(self): + alert_lvls, d_status = self._run_seq(always_distracted, always_false, always_true, always_false) + s = d_status.settings + assert alert_lvls[int(s._VISION_POLICY_ALERT_1_TIMEOUT / 2 / DT_DMON)] == 0 + assert alert_lvls[int((s._VISION_POLICY_ALERT_1_TIMEOUT + \ + (s._VISION_POLICY_ALERT_2_TIMEOUT - s._VISION_POLICY_ALERT_1_TIMEOUT) / 2) / DT_DMON)] == 1 + assert alert_lvls[int((s._VISION_POLICY_ALERT_2_TIMEOUT + \ + (s._VISION_POLICY_ALERT_3_TIMEOUT - s._VISION_POLICY_ALERT_2_TIMEOUT) / 2) / DT_DMON)] == 2 + assert alert_lvls[int((s._VISION_POLICY_ALERT_3_TIMEOUT + \ + (TEST_TIMESPAN - 10 - s._VISION_POLICY_ALERT_3_TIMEOUT) / 2) / DT_DMON)] == 3 + assert isinstance(d_status.awareness, float) + + # engaged, distracted past red and beyond the no-response window -> unavailability response + lockout + def test_distracted_lockout(self): + alert_lvls, d_status = self._run_seq(always_distracted, always_false, always_true, always_false) + assert alert_lvls[int(DISTRACTED_SECONDS_TO_RED / DT_DMON)] == 3 + assert d_status.lockout_active + assert d_status.lockout_time_elapsed > 0 + assert d_status.lockout_count >= 1 + + # no face -> wheeltouch red, sustained past the no-response timeout -> unavailability response + lockout + def test_invisible_lockout(self): + _, d_status = self._run_seq(always_no_face, always_false, always_true, always_false) + assert d_status.active_policy == log.DriverMonitoringState.MonitoringPolicy.wheeltouch + assert d_status.lockout_active + assert d_status.lockout_count >= 1 + + # engaged, no face detected the whole time, no action + def test_fully_invisible_driver(self): + alert_lvls, d_status = self._run_seq(always_no_face, always_false, always_true, always_false) + s = d_status.settings + assert alert_lvls[int(s._WHEELTOUCH_POLICY_ALERT_1_TIMEOUT / 2 / DT_DMON)] == 0 + assert alert_lvls[int((s._WHEELTOUCH_POLICY_ALERT_1_TIMEOUT + \ + (s._WHEELTOUCH_POLICY_ALERT_2_TIMEOUT - s._WHEELTOUCH_POLICY_ALERT_1_TIMEOUT) / 2) / DT_DMON)] == 1 + assert alert_lvls[int((s._WHEELTOUCH_POLICY_ALERT_2_TIMEOUT + \ + (s._WHEELTOUCH_POLICY_ALERT_3_TIMEOUT - s._WHEELTOUCH_POLICY_ALERT_2_TIMEOUT) / 2) / DT_DMON)] == 2 + assert alert_lvls[int((s._WHEELTOUCH_POLICY_ALERT_3_TIMEOUT + \ + (TEST_TIMESPAN - 10 - s._WHEELTOUCH_POLICY_ALERT_3_TIMEOUT) / 2) / DT_DMON)] == 3 + assert d_status.active_policy == log.DriverMonitoringState.MonitoringPolicy.wheeltouch + + # engaged, down to orange, driver pays attention, back to normal; then down to orange, driver touches wheel + # - should have short orange recovery time and no green afterwards; wheel touch only recovers when paying attention + def test_normal_driver(self): + ds_vector = [msg_DISTRACTED] * int(DISTRACTED_SECONDS_TO_ORANGE/DT_DMON) + \ + [msg_ATTENTIVE] * int(DISTRACTED_SECONDS_TO_ORANGE/DT_DMON) + \ + [msg_DISTRACTED] * int((DISTRACTED_SECONDS_TO_ORANGE+2)/DT_DMON) + \ + [msg_ATTENTIVE] * (int(TEST_TIMESPAN/DT_DMON)-int((DISTRACTED_SECONDS_TO_ORANGE*3+2)/DT_DMON)) + interaction_vector = [car_interaction_NOT_DETECTED] * int(DISTRACTED_SECONDS_TO_ORANGE*3/DT_DMON) + \ + [car_interaction_DETECTED] * (int(TEST_TIMESPAN/DT_DMON)-int(DISTRACTED_SECONDS_TO_ORANGE*3/DT_DMON)) + alert_lvls, _ = self._run_seq(ds_vector, interaction_vector, always_true, always_false) + assert alert_lvls[int(DISTRACTED_SECONDS_TO_ORANGE*0.5/DT_DMON)] == 0 + assert alert_lvls[int((DISTRACTED_SECONDS_TO_ORANGE-0.1)/DT_DMON)] == 2 + assert alert_lvls[int(DISTRACTED_SECONDS_TO_ORANGE*1.5/DT_DMON)] == 0 + assert alert_lvls[int((DISTRACTED_SECONDS_TO_ORANGE*3-0.1)/DT_DMON)] == 2 + assert alert_lvls[int((DISTRACTED_SECONDS_TO_ORANGE*3+0.1)/DT_DMON)] == 2 + assert alert_lvls[int((DISTRACTED_SECONDS_TO_ORANGE*3+2.5)/DT_DMON)] == 0 + + # engaged, down to orange, driver dodges camera, then comes back still distracted, down to red, \ + # driver dodges, and then touches wheel to no avail, disengages and reengages + # - orange/red alert should remain after disappearance, and only disengaging clears red + def test_biggest_comma_fan(self): + _invisible_time = 2 # seconds + ds_vector = always_distracted[:] + interaction_vector = always_false[:] + op_vector = always_true[:] + ds_vector[int(DISTRACTED_SECONDS_TO_ORANGE/DT_DMON):int((DISTRACTED_SECONDS_TO_ORANGE+_invisible_time)/DT_DMON)] \ + = [msg_NO_FACE_DETECTED] * int(_invisible_time/DT_DMON) + ds_vector[int((DISTRACTED_SECONDS_TO_RED+_invisible_time)/DT_DMON):int((DISTRACTED_SECONDS_TO_RED+2*_invisible_time)/DT_DMON)] \ + = [msg_NO_FACE_DETECTED] * int(_invisible_time/DT_DMON) + interaction_vector[int((DISTRACTED_SECONDS_TO_RED+2*_invisible_time+0.5)/DT_DMON):int((DISTRACTED_SECONDS_TO_RED+2*_invisible_time+1.5)/DT_DMON)] \ + = [True] * int(1/DT_DMON) + op_vector[int((DISTRACTED_SECONDS_TO_RED+2*_invisible_time+2.5)/DT_DMON):int((DISTRACTED_SECONDS_TO_RED+2*_invisible_time+3)/DT_DMON)] \ + = [False] * int(0.5/DT_DMON) + alert_lvls, _ = self._run_seq(ds_vector, interaction_vector, op_vector, always_false) + assert alert_lvls[int((DISTRACTED_SECONDS_TO_ORANGE+0.5*_invisible_time)/DT_DMON)] == 2 + assert alert_lvls[int((DISTRACTED_SECONDS_TO_RED+1.5*_invisible_time)/DT_DMON)] == 3 + assert alert_lvls[int((DISTRACTED_SECONDS_TO_RED+2*_invisible_time+1.5)/DT_DMON)] == 3 + assert alert_lvls[int((DISTRACTED_SECONDS_TO_RED+2*_invisible_time+3.5)/DT_DMON)] == 0 + + # engaged, invisible driver, down to orange, driver touches wheel; then down to orange again, driver appears + # - both actions should clear the alert, but momentary appearance should not + def test_sometimes_transparent_commuter(self): + for _visible_time in (0.5, 10): + ds_vector = always_no_face[:]*2 + interaction_vector = always_false[:]*2 + ds_vector[int((2*INVISIBLE_SECONDS_TO_ORANGE+1)/DT_DMON):int((2*INVISIBLE_SECONDS_TO_ORANGE+1+_visible_time)/DT_DMON)] = \ + [msg_ATTENTIVE] * int(_visible_time/DT_DMON) + interaction_vector[int((INVISIBLE_SECONDS_TO_ORANGE)/DT_DMON):int((INVISIBLE_SECONDS_TO_ORANGE+1)/DT_DMON)] = [True] * int(1/DT_DMON) + alert_lvls, _ = self._run_seq(ds_vector, interaction_vector, 2*always_true, 2*always_false) + assert alert_lvls[int(dm_settings._WHEELTOUCH_POLICY_ALERT_1_TIMEOUT/2/DT_DMON)] == 0 + assert alert_lvls[int((INVISIBLE_SECONDS_TO_ORANGE-0.1)/DT_DMON)] == 2 + assert alert_lvls[int((INVISIBLE_SECONDS_TO_ORANGE+0.1)/DT_DMON)] == 0 + if _visible_time == 0.5: + assert alert_lvls[int((INVISIBLE_SECONDS_TO_ORANGE*2+1-0.1)/DT_DMON)] == 2 + assert alert_lvls[int((INVISIBLE_SECONDS_TO_ORANGE*2+1+0.1+_visible_time)/DT_DMON)] == 2 + elif _visible_time == 10: + assert alert_lvls[int((INVISIBLE_SECONDS_TO_ORANGE*2+1-0.1)/DT_DMON)] == 2 + assert alert_lvls[int((INVISIBLE_SECONDS_TO_ORANGE*2+1+0.1+_visible_time)/DT_DMON)] == 0 + + # engaged, invisible driver, down to red, driver appears and then touches wheel, then disengages/reengages + # - only disengage will clear the alert + def test_last_second_responder(self): + _visible_time = 2 # seconds + ds_vector = always_no_face[:] + interaction_vector = always_false[:] + op_vector = always_true[:] + ds_vector[int(INVISIBLE_SECONDS_TO_RED/DT_DMON):int((INVISIBLE_SECONDS_TO_RED+_visible_time)/DT_DMON)] = [msg_ATTENTIVE] * int(_visible_time/DT_DMON) + interaction_vector[int((INVISIBLE_SECONDS_TO_RED+_visible_time)/DT_DMON):int((INVISIBLE_SECONDS_TO_RED+_visible_time+1)/DT_DMON)] = [True] * int(1/DT_DMON) + op_vector[int((INVISIBLE_SECONDS_TO_RED+_visible_time+1)/DT_DMON):int((INVISIBLE_SECONDS_TO_RED+_visible_time+0.5)/DT_DMON)] = [False] * int(0.5/DT_DMON) + alert_lvls, _ = self._run_seq(ds_vector, interaction_vector, op_vector, always_false) + assert alert_lvls[int(dm_settings._WHEELTOUCH_POLICY_ALERT_1_TIMEOUT/2/DT_DMON)] == 0 + assert alert_lvls[int((INVISIBLE_SECONDS_TO_ORANGE-0.1)/DT_DMON)] == 2 + assert alert_lvls[int((INVISIBLE_SECONDS_TO_RED-0.1)/DT_DMON)] == 3 + assert alert_lvls[int((INVISIBLE_SECONDS_TO_RED+0.5*_visible_time)/DT_DMON)] == 3 + assert alert_lvls[int((INVISIBLE_SECONDS_TO_RED+_visible_time+0.5)/DT_DMON)] == 3 + assert alert_lvls[int((INVISIBLE_SECONDS_TO_RED+_visible_time+1+0.1)/DT_DMON)] == 0 + + # disengaged, always distracted driver + # - dm should stay quiet when not engaged + def test_pure_dashcam_user(self): + alert_lvls, _ = self._run_seq(always_distracted, always_false, always_false, always_false) + assert all(a == 0 for a in alert_lvls) + + # engaged, car stops at traffic light, down to orange, no action, then car starts moving + # - should only reach green when stopped, but continues counting down on launch + def test_long_traffic_light_victim(self): + _redlight_time = 60 # seconds + lowspeed_vector = always_true[:] + lowspeed_vector[int(_redlight_time/DT_DMON):] = [False] * int((TEST_TIMESPAN-_redlight_time)/DT_DMON) + alert_lvls, d_status = self._run_seq(always_distracted, always_false, always_true, lowspeed_vector) + s = d_status.settings + assert alert_lvls[int((_redlight_time-0.1)/DT_DMON)] == 0 + _alert_1_to_2 = s._VISION_POLICY_ALERT_2_TIMEOUT - s._VISION_POLICY_ALERT_1_TIMEOUT + assert alert_lvls[int((_redlight_time+0.5)/DT_DMON)] == 1 + assert alert_lvls[int((_redlight_time+_alert_1_to_2+0.5)/DT_DMON)] == 2 + + # engaged, distracted while moving, then car stops after reaching orange + # - should reset timer to pre green at low speed + def test_distracted_then_stops(self): + _stop_time = DISTRACTED_SECONDS_TO_ORANGE + 1 # stop 1 second after reaching orange + lowspeed_vector = always_false[:] + lowspeed_vector[int(_stop_time/DT_DMON):] = [True] * int((TEST_TIMESPAN-_stop_time)/DT_DMON) + alert_lvls, _ = self._run_seq(always_distracted, always_false, always_true, lowspeed_vector) + # just before and briefly after stopping: orange alert; goes away quickly after stopped + assert alert_lvls[int((_stop_time+0.1)/DT_DMON)] == 2 + assert alert_lvls[int((_stop_time+0.5)/DT_DMON)] == 0 + + # engaged, model is somehow uncertain and driver is distracted + # - should fall back to wheel touch after uncertain alert + def test_somehow_indecisive_model(self): + ds_vector = [msg_DISTRACTED_BUT_SOMEHOW_UNCERTAIN] * int(TEST_TIMESPAN/DT_DMON) + interaction_vector = always_false[:] + alert_lvls, d_status = self._run_seq(ds_vector, interaction_vector, always_true, always_false) + s = d_status.settings + assert alert_lvls[int((INVISIBLE_SECONDS_TO_ORANGE-1+DT_DMON*s._HI_STD_FALLBACK_TIME-0.1)/DT_DMON)] == 1 + assert alert_lvls[int((INVISIBLE_SECONDS_TO_ORANGE-1+DT_DMON*s._HI_STD_FALLBACK_TIME+0.1)/DT_DMON)] == 2 + assert alert_lvls[int((INVISIBLE_SECONDS_TO_RED-1+DT_DMON*s._HI_STD_FALLBACK_TIME+0.1)/DT_DMON)] == 3 + + +def _build_sm(selfdrive_enabled, lat_active, steering_pressed, gas_pressed): + cs = car.CarState.new_message() + cs.vEgo = 30.0 + cs.gearShifter = car.CarState.GearShifter.drive + cs.steeringPressed = steering_pressed + cs.gasPressed = gas_pressed + ss = log.SelfdriveState.new_message() + ss.enabled = selfdrive_enabled + cc = car.CarControl.new_message() + cc.latActive = lat_active + mv2 = log.ModelDataV2.new_message() + mv2.meta.disengagePredictions.brakeDisengageProbs = [0.0] + lc = log.LiveCalibrationData.new_message() + lc.rpyCalib = [0.0, 0.0, 0.0] + return { + 'carState': cs, 'selfdriveState': ss, 'carControl': cc, + 'modelV2': mv2, 'liveCalibration': lc, 'driverStateV2': make_msg(False), + } + + +@pytest.mark.parametrize("selfdrive_enabled, lat_active, steering, gas, expected_op_engaged, expected_driver_engaged", [ + (False, False, False, False, False, False), # disabled + (True, False, False, False, True, False), # OP enabled + (False, True, False, False, True, False), # MADS lat-only + (True, True, False, False, True, False), # both active + (False, True, False, True, True, False), # MADS lat-only + gas + (True, True, False, True, True, True), # full op + gas: override + (False, True, True, False, True, True), # MADS lat-only + wheel touch: override +]) +def test_run_step_engagement(selfdrive_enabled, lat_active, steering, gas, + expected_op_engaged, expected_driver_engaged): + sm = _build_sm(selfdrive_enabled, lat_active, steering, gas) + dm = DriverMonitoring() + captured = {} + orig = dm._update_events + + def spy(driver_engaged, op_engaged, lowspeed, wrong_gear): + captured['driver_engaged'] = driver_engaged + captured['op_engaged'] = op_engaged + return orig(driver_engaged, op_engaged, lowspeed, wrong_gear) + + object.__setattr__(dm, '_update_events', spy) + dm.run_step(sm, demo=False) + assert captured['op_engaged'] == expected_op_engaged + assert captured['driver_engaged'] == expected_driver_engaged diff --git a/openpilot/selfdrive/pandad/.gitignore b/openpilot/selfdrive/pandad/.gitignore new file mode 100644 index 0000000000..cb292405c9 --- /dev/null +++ b/openpilot/selfdrive/pandad/.gitignore @@ -0,0 +1,3 @@ +pandad +pandad_api_impl.cpp +tests/test_pandad_canprotocol diff --git a/openpilot/selfdrive/pandad/SConscript b/openpilot/selfdrive/pandad/SConscript new file mode 100644 index 0000000000..fd59db9853 --- /dev/null +++ b/openpilot/selfdrive/pandad/SConscript @@ -0,0 +1,10 @@ +Import('env', 'arch', 'common', 'messaging') + +if arch != "Darwin": + libs = [common, messaging, 'pthread'] + panda = env.Library('panda', ['panda.cc', 'spi.cc']) + + env.Program('pandad', ['main.cc', 'pandad.cc', 'panda_safety.cc'], LIBS=[panda] + libs) + + if GetOption('extras'): + env.Program('tests/test_pandad_canprotocol', ['tests/test_pandad_canprotocol.cc'], LIBS=[panda] + libs) diff --git a/openpilot/selfdrive/pandad/__init__.py b/openpilot/selfdrive/pandad/__init__.py new file mode 100644 index 0000000000..0c17e886a2 --- /dev/null +++ b/openpilot/selfdrive/pandad/__init__.py @@ -0,0 +1,3 @@ +from openpilot.selfdrive.pandad.pandad_api_impl import can_list_to_can_capnp, can_capnp_to_list +assert can_list_to_can_capnp +assert can_capnp_to_list diff --git a/openpilot/selfdrive/pandad/main.cc b/openpilot/selfdrive/pandad/main.cc new file mode 100644 index 0000000000..08e88b6163 --- /dev/null +++ b/openpilot/selfdrive/pandad/main.cc @@ -0,0 +1,22 @@ +#include + +#include "selfdrive/pandad/pandad.h" +#include "common/swaglog.h" +#include "common/util.h" +#include "common/hardware/hw.h" + +int main(int argc, char *argv[]) { + LOGW("starting pandad"); + + if (!Hardware::PC()) { + int err; + err = util::set_realtime_priority(54); + assert(err == 0); + err = util::set_core_affinity({3}); + assert(err == 0); + } + + std::string serial = (argc > 1) ? argv[1] : ""; + pandad_main_thread(serial); + return 0; +} diff --git a/openpilot/selfdrive/pandad/panda.cc b/openpilot/selfdrive/pandad/panda.cc new file mode 100644 index 0000000000..cb5266d253 --- /dev/null +++ b/openpilot/selfdrive/pandad/panda.cc @@ -0,0 +1,290 @@ +#include "selfdrive/pandad/panda.h" + +#include + +#include +#include +#include + +#include "openpilot/cereal/messaging/messaging.h" +#include "common/swaglog.h" +#include "common/util.h" + +const bool PANDAD_MAXOUT = getenv("PANDAD_MAXOUT") != nullptr; + +Panda::Panda(std::string serial) { + handle = std::make_unique(serial); + LOGW("connected to %s over SPI", serial.c_str()); + + hw_type = get_hw_type(); + can_reset_communications(); +} + +bool Panda::connected() { + return handle->connected; +} + +bool Panda::comms_healthy() { + return handle->comms_healthy; +} + +std::string Panda::hw_serial() { + return handle->hw_serial; +} + +std::vector Panda::list() { + return PandaSpiHandle::list(); +} + +void Panda::set_safety_model(cereal::CarParams::SafetyModel safety_model, uint16_t safety_param) { + handle->control_write(0xdc, (uint16_t)safety_model, safety_param); +} + +void Panda::set_alternative_experience(uint16_t alternative_experience, uint16_t safety_param_sp) { + handle->control_write(0xdf, alternative_experience, safety_param_sp); +} + +std::string Panda::serial_read(int port_number) { + std::string ret; + char buffer[USBPACKET_MAX_SIZE] = {}; + + while (true) { + int bytes_read = handle->control_read(0xe0, port_number, 0, (unsigned char *)buffer, USBPACKET_MAX_SIZE); + if (bytes_read <= 0) { + break; + } + ret.append(buffer, bytes_read); + } + + return ret; +} + +void Panda::set_uart_baud(int uart, int rate) { + handle->control_write(0xe4, uart, int(rate / 300)); +} + +cereal::PandaState::PandaType Panda::get_hw_type() { + unsigned char hw_query[1] = {0}; + + handle->control_read(0xc1, 0, 0, hw_query, 1); + return (cereal::PandaState::PandaType)(hw_query[0]); +} + +void Panda::set_fan_speed(uint16_t fan_speed) { + handle->control_write(0xb1, fan_speed, 0); +} + +uint16_t Panda::get_fan_speed() { + uint16_t fan_speed_rpm = 0; + handle->control_read(0xb2, 0, 0, (unsigned char*)&fan_speed_rpm, sizeof(fan_speed_rpm)); + return fan_speed_rpm; +} + +void Panda::set_ir_pwr(uint16_t ir_pwr) { + handle->control_write(0xb0, ir_pwr, 0); +} + +std::optional Panda::get_state() { + health_t health {0}; + int err = handle->control_read(0xd2, 0, 0, (unsigned char*)&health, sizeof(health)); + return err >= 0 ? std::make_optional(health) : std::nullopt; +} + +std::optional Panda::get_can_state(uint16_t can_number) { + can_health_t can_health {0}; + int err = handle->control_read(0xc2, can_number, 0, (unsigned char*)&can_health, sizeof(can_health)); + return err >= 0 ? std::make_optional(can_health) : std::nullopt; +} + +void Panda::set_loopback(bool loopback) { + handle->control_write(0xe5, loopback, 0); +} + +std::optional> Panda::get_firmware_version() { + std::vector fw_sig_buf(128); + int read_1 = handle->control_read(0xd3, 0, 0, &fw_sig_buf[0], 64); + int read_2 = handle->control_read(0xd4, 0, 0, &fw_sig_buf[64], 64); + return ((read_1 == 64) && (read_2 == 64)) ? std::make_optional(fw_sig_buf) : std::nullopt; +} + +std::optional Panda::get_serial() { + char serial_buf[17] = {'\0'}; + int err = handle->control_read(0xd0, 0, 0, (uint8_t*)serial_buf, 16); + return err >= 0 ? std::make_optional(serial_buf) : std::nullopt; +} + +bool Panda::up_to_date() { + if (auto fw_sig = get_firmware_version()) { + for (auto fn : { "panda.bin.signed", "panda_h7.bin.signed" }) { + auto content = util::read_file(std::string("../../../panda/board/obj/") + fn); + if (content.size() >= fw_sig->size() && + memcmp(content.data() + content.size() - fw_sig->size(), fw_sig->data(), fw_sig->size()) == 0) { + return true; + } + } + } + return false; +} + +void Panda::set_power_saving(bool power_saving) { + handle->control_write(0xe7, power_saving, 0); +} + +void Panda::enable_deepsleep() { + handle->control_write(0xfb, 0, 0); +} + +void Panda::send_heartbeat(bool engaged, bool engaged_mads) { + handle->control_write(0xf3, engaged, engaged_mads); +} + +void Panda::set_can_speed_kbps(uint16_t bus, uint16_t speed) { + handle->control_write(0xde, bus, (speed * 10)); +} + +void Panda::set_can_fd_auto(uint16_t bus, bool enabled) { + handle->control_write(0xe8, bus, enabled); +} + +void Panda::set_data_speed_kbps(uint16_t bus, uint16_t speed) { + handle->control_write(0xf9, bus, (speed * 10)); +} + +void Panda::set_canfd_non_iso(uint16_t bus, bool non_iso) { + handle->control_write(0xfc, bus, non_iso); +} + +static uint8_t len_to_dlc(uint8_t len) { + if (len <= 8) { + return len; + } + if (len <= 24) { + return 8 + ((len - 8) / 4) + ((len % 4) ? 1 : 0); + } else { + return 11 + (len / 16) + ((len % 16) ? 1 : 0); + } +} + +void Panda::pack_can_buffer(const capnp::List::Reader &can_data_list, + std::function write_func) { + int32_t pos = 0; + uint8_t send_buf[2 * USB_TX_SOFT_LIMIT]; + + for (const auto &cmsg : can_data_list) { + // check if the message is intended for this panda + uint8_t bus = cmsg.getSrc(); + if (bus >= PANDA_BUS_OFFSET) { + continue; + } + auto can_data = cmsg.getDat(); + uint8_t data_len_code = len_to_dlc(can_data.size()); + assert(can_data.size() <= 64); + assert(can_data.size() == dlc_to_len[data_len_code]); + + can_header header = {}; + header.addr = cmsg.getAddress(); + header.extended = (cmsg.getAddress() >= 0x800) ? 1 : 0; + header.data_len_code = data_len_code; + header.bus = bus; + header.checksum = 0; + + memcpy(&send_buf[pos], (uint8_t *)&header, sizeof(can_header)); + memcpy(&send_buf[pos + sizeof(can_header)], (uint8_t *)can_data.begin(), can_data.size()); + uint32_t msg_size = sizeof(can_header) + can_data.size(); + + // set checksum + ((can_header *) &send_buf[pos])->checksum = calculate_checksum(&send_buf[pos], msg_size); + + pos += msg_size; + + if (pos >= USB_TX_SOFT_LIMIT) { + write_func(send_buf, pos); + pos = 0; + } + } + + // send remaining packets + if (pos > 0) write_func(send_buf, pos); +} + +void Panda::can_send(const capnp::List::Reader &can_data_list) { + pack_can_buffer(can_data_list, [=](uint8_t* data, size_t size) { + handle->bulk_write(3, data, size, 5); + }); +} + +bool Panda::can_receive(std::vector& out_vec) { + // Check if enough space left in buffer to store RECV_SIZE data + assert(receive_buffer_size + RECV_SIZE <= sizeof(receive_buffer)); + + int recv = handle->bulk_read(0x81, &receive_buffer[receive_buffer_size], RECV_SIZE); + if (!comms_healthy()) { + return false; + } + + if (PANDAD_MAXOUT) { + static uint8_t junk[RECV_SIZE]; + handle->bulk_read(0xab, junk, RECV_SIZE - recv); + } + + bool ret = true; + if (recv > 0) { + receive_buffer_size += recv; + ret = unpack_can_buffer(receive_buffer, receive_buffer_size, out_vec); + } + return ret; +} + +void Panda::can_reset_communications() { + handle->control_write(0xc0, 0, 0); +} + +bool Panda::unpack_can_buffer(uint8_t *data, uint32_t &size, std::vector &out_vec) { + int pos = 0; + + while (pos <= size - sizeof(can_header)) { + can_header header; + memcpy(&header, &data[pos], sizeof(can_header)); + + const uint8_t data_len = dlc_to_len[header.data_len_code]; + if (pos + sizeof(can_header) + data_len > size) { + // we don't have all the data for this message yet + break; + } + + if (calculate_checksum(&data[pos], sizeof(can_header) + data_len) != 0) { + LOGE("Panda CAN checksum failed"); + size = 0; + can_reset_communications(); + return false; + } + + can_frame &canData = out_vec.emplace_back(); + canData.address = header.addr; + canData.src = header.bus; + if (header.rejected) { + canData.src += CAN_REJECTED_BUS_OFFSET; + } + if (header.returned) { + canData.src += CAN_RETURNED_BUS_OFFSET; + } + + canData.dat.assign((char *)&data[pos + sizeof(can_header)], data_len); + + pos += sizeof(can_header) + data_len; + } + + // move the overflowing data to the beginning of the buffer for the next round + memmove(data, &data[pos], size - pos); + size -= pos; + + return true; +} + +uint8_t Panda::calculate_checksum(uint8_t *data, uint32_t len) { + uint8_t checksum = 0U; + for (uint32_t i = 0U; i < len; i++) { + checksum ^= data[i]; + } + return checksum; +} diff --git a/openpilot/selfdrive/pandad/panda.h b/openpilot/selfdrive/pandad/panda.h new file mode 100644 index 0000000000..1c5e4a5504 --- /dev/null +++ b/openpilot/selfdrive/pandad/panda.h @@ -0,0 +1,98 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "openpilot/cereal/gen/cpp/car.capnp.h" +#include "openpilot/cereal/gen/cpp/log.capnp.h" +#include "panda/board/health.h" +#include "panda/board/can.h" +#include "selfdrive/pandad/panda_comms.h" + +#define USB_TX_SOFT_LIMIT (0x100U) +#define USBPACKET_MAX_SIZE (0x40) + +#define RECV_SIZE (0x4000U) + +#define CAN_REJECTED_BUS_OFFSET 0xC0U +#define CAN_RETURNED_BUS_OFFSET 0x80U + +#define PANDA_BUS_OFFSET 4 + +struct __attribute__((packed)) can_header { + uint8_t reserved : 1; + uint8_t bus : 3; + uint8_t data_len_code : 4; + uint8_t rejected : 1; + uint8_t returned : 1; + uint8_t extended : 1; + uint32_t addr : 29; + uint8_t checksum : 8; +}; + +struct can_frame { + long address; + std::string dat; + long src; +}; + + +class Panda { +private: + std::unique_ptr handle; + +public: + Panda(std::string serial); + + cereal::PandaState::PandaType hw_type = cereal::PandaState::PandaType::UNKNOWN; + + bool connected(); + bool comms_healthy(); + std::string hw_serial(); + + // Static functions + static std::vector list(); + + // Panda functionality + cereal::PandaState::PandaType get_hw_type(); + void set_safety_model(cereal::CarParams::SafetyModel safety_model, uint16_t safety_param=0U); + void set_alternative_experience(uint16_t alternative_experience, uint16_t safety_param_sp=0U); + std::string serial_read(int port_number = 0); + void set_uart_baud(int uart, int rate); + void set_fan_speed(uint16_t fan_speed); + uint16_t get_fan_speed(); + void set_ir_pwr(uint16_t ir_pwr); + std::optional get_state(); + std::optional get_can_state(uint16_t can_number); + void set_loopback(bool loopback); + std::optional> get_firmware_version(); + bool up_to_date(); + std::optional get_serial(); + void set_power_saving(bool power_saving); + void enable_deepsleep(); + void send_heartbeat(bool engaged, bool engaged_mads); + void set_can_speed_kbps(uint16_t bus, uint16_t speed); + void set_can_fd_auto(uint16_t bus, bool enabled); + void set_data_speed_kbps(uint16_t bus, uint16_t speed); + void set_canfd_non_iso(uint16_t bus, bool non_iso); + void can_send(const capnp::List::Reader &can_data_list); + bool can_receive(std::vector& out_vec); + void can_reset_communications(); + +protected: + // for unit tests + uint8_t receive_buffer[RECV_SIZE + sizeof(can_header) + 64]; + uint32_t receive_buffer_size = 0; + + Panda() {} + void pack_can_buffer(const capnp::List::Reader &can_data_list, + std::function write_func); + bool unpack_can_buffer(uint8_t *data, uint32_t &size, std::vector &out_vec); + uint8_t calculate_checksum(uint8_t *data, uint32_t len); +}; diff --git a/openpilot/selfdrive/pandad/panda_comms.h b/openpilot/selfdrive/pandad/panda_comms.h new file mode 100644 index 0000000000..cdfb5019b6 --- /dev/null +++ b/openpilot/selfdrive/pandad/panda_comms.h @@ -0,0 +1,52 @@ +#pragma once + +#include +#include +#include +#include +#include + + +#define TIMEOUT 0 +#define SPI_BUF_SIZE 2048 + + +class PandaSpiHandle { +public: + std::string hw_serial; + std::atomic connected = true; + std::atomic comms_healthy = true; + + PandaSpiHandle(std::string serial); + ~PandaSpiHandle(); + + int control_write(uint8_t request, uint16_t param1, uint16_t param2, unsigned int timeout=TIMEOUT); + int control_read(uint8_t request, uint16_t param1, uint16_t param2, unsigned char *data, uint16_t length, unsigned int timeout=TIMEOUT); + int bulk_write(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout=TIMEOUT); + int bulk_read(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout=TIMEOUT); + void cleanup(); + + static std::vector list(); + +private: + int spi_fd = -1; + uint8_t tx_buf[SPI_BUF_SIZE]; + uint8_t rx_buf[SPI_BUF_SIZE]; + inline static std::recursive_mutex hw_lock; + + struct __attribute__((packed)) spi_header { + uint8_t sync; + uint8_t endpoint; + uint16_t tx_len; + uint16_t max_rx_len; + }; + + int wait_for_ack(uint8_t ack, uint8_t tx, unsigned int timeout, unsigned int length); + int bulk_transfer(uint8_t endpoint, uint8_t *tx_data, uint16_t tx_len, uint8_t *rx_data, uint16_t rx_len, unsigned int timeout); + int spi_transfer(uint8_t endpoint, uint8_t *tx_data, uint16_t tx_len, uint8_t *rx_data, uint16_t max_rx_len, unsigned int timeout); + int spi_transfer_retry(uint8_t endpoint, uint8_t *tx_data, uint16_t tx_len, uint8_t *rx_data, uint16_t max_rx_len, unsigned int timeout); + int lltransfer(struct spi_ioc_transfer &t); + + spi_header header; + uint32_t xfer_count = 0; +}; diff --git a/openpilot/selfdrive/pandad/panda_safety.cc b/openpilot/selfdrive/pandad/panda_safety.cc new file mode 100644 index 0000000000..bcec99190a --- /dev/null +++ b/openpilot/selfdrive/pandad/panda_safety.cc @@ -0,0 +1,84 @@ +#include "selfdrive/pandad/pandad.h" +#include "openpilot/cereal/messaging/messaging.h" +#include "common/swaglog.h" + +void PandaSafety::configureSafetyMode(bool is_onroad) { + if (is_onroad && !safety_configured_) { + updateMultiplexingMode(); + + auto car_params = fetchCarParams(); + if (!car_params.empty()) { + LOGW("got %lu bytes CarParams", car_params[0].size()); + LOGW("got %lu bytes CarParamsSP", car_params[1].size()); + setSafetyMode(car_params); + safety_configured_ = true; + } + } else if (!is_onroad) { + initialized_ = false; + safety_configured_ = false; + log_once_ = false; + } +} + +void PandaSafety::updateMultiplexingMode() { + // Initialize to ELM327 without OBD multiplexing for initial fingerprinting + if (!initialized_) { + prev_obd_multiplexing_ = false; + panda_->set_safety_model(cereal::CarParams::SafetyModel::ELM327, 1U); + initialized_ = true; + } + + // Switch between multiplexing modes based on the OBD multiplexing request + bool obd_multiplexing_requested = params_.getBool("ObdMultiplexingEnabled"); + if (obd_multiplexing_requested != prev_obd_multiplexing_) { + const uint16_t safety_param = obd_multiplexing_requested ? 0U : 1U; + panda_->set_safety_model(cereal::CarParams::SafetyModel::ELM327, safety_param); + prev_obd_multiplexing_ = obd_multiplexing_requested; + params_.putBool("ObdMultiplexingChanged", true); + } +} + +// TODO-SP: Use structs instead of vector +std::vector PandaSafety::fetchCarParams() { + if (!params_.getBool("FirmwareQueryDone")) { + return {}; + } + + if (!log_once_) { + LOGW("Finished FW query, Waiting for params to set safety model"); + log_once_ = true; + } + + if (!params_.getBool("ControlsReady")) { + return {}; + } + return {params_.get("CarParams"), params_.get("CarParamsSP")}; +} + +// TODO-SP: Use structs instead of vector +void PandaSafety::setSafetyMode(const std::vector ¶ms_string) { + AlignedBuffer aligned_buf; + AlignedBuffer aligned_buf_sp; + + capnp::FlatArrayMessageReader cmsg(aligned_buf.align(params_string[0].data(), params_string[0].size())); + cereal::CarParams::Reader car_params = cmsg.getRoot(); + + capnp::FlatArrayMessageReader cmsg_sp(aligned_buf_sp.align(params_string[1].data(), params_string[1].size())); + cereal::CarParamsSP::Reader car_params_sp = cmsg_sp.getRoot(); + + auto safety_configs = car_params.getSafetyConfigs(); + uint16_t alternative_experience = car_params.getAlternativeExperience(); + uint16_t safety_param_sp = car_params_sp.getSafetyParam(); + + cereal::CarParams::SafetyModel safety_model = safety_configs[0].getSafetyModel(); + uint16_t safety_param = safety_configs[0].getSafetyParam(); + + LOGW("setting safety model: %d, param: %d, alternative experience: %d, param_sp: %d", (int)safety_model, safety_param, alternative_experience, safety_param_sp); + panda_->set_alternative_experience(alternative_experience, safety_param_sp); + panda_->set_safety_model(safety_model, safety_param); +} + +bool PandaSafety::getOffroadMode() { + auto offroad_mode = params_.getBool("OffroadMode"); + return offroad_mode; +} diff --git a/openpilot/selfdrive/pandad/pandad.cc b/openpilot/selfdrive/pandad/pandad.cc new file mode 100644 index 0000000000..250ad5a481 --- /dev/null +++ b/openpilot/selfdrive/pandad/pandad.cc @@ -0,0 +1,468 @@ +#include "selfdrive/pandad/pandad.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "openpilot/cereal/gen/cpp/car.capnp.h" +#include "openpilot/cereal/messaging/messaging.h" +#include "openpilot/cereal/services.h" +#include "common/ratekeeper.h" +#include "common/swaglog.h" +#include "common/timing.h" +#include "common/util.h" +#include "common/hardware/hw.h" + +#define MAX_IR_PANDA_VAL 50 +#define CUTOFF_IL 400 +#define SATURATE_IL 1000 + +ExitHandler do_exit; + +bool check_connected(Panda *panda) { + if (!panda->connected()) { + do_exit = true; + return false; + } + return true; +} + +bool process_mads_heartbeat(SubMaster *sm) { + const auto &mads = (*sm)["selfdriveStateSP"].getSelfdriveStateSP().getMads(); + return sm->allAliveAndValid({"selfdriveStateSP"}) && mads.getEnabled(); +} + +Panda *connect(std::string serial) { + std::unique_ptr panda; + try { + panda = std::make_unique(serial); + } catch (std::exception &e) { + return nullptr; + } + + // common panda config + if (getenv("BOARDD_LOOPBACK")) { + panda->set_loopback(true); + } + //panda->enable_deepsleep(); + + for (int i = 0; i < PANDA_CAN_CNT; i++) { + panda->set_can_fd_auto(i, true); + } + + bool is_supported_panda = std::find(SUPPORTED_PANDA_TYPES.begin(), SUPPORTED_PANDA_TYPES.end(), panda->hw_type) != SUPPORTED_PANDA_TYPES.end(); + + if (!is_supported_panda) { + LOGW("panda %s is not supported (hw_type: %i), skipping firmware check...", panda->hw_serial().c_str(), static_cast(panda->hw_type)); + return panda.release(); + } + + if (!panda->up_to_date() && !getenv("BOARDD_SKIP_FW_CHECK")) { + throw std::runtime_error("Panda firmware out of date. Run pandad.py to update."); + } + + return panda.release(); +} + +void can_send_thread(Panda *panda, bool fake_send) { + util::set_thread_name("pandad_can_send"); + + AlignedBuffer aligned_buf; + std::unique_ptr context(Context::create()); + std::unique_ptr subscriber(SubSocket::create(context.get(), "sendcan", "127.0.0.1", false, true, services.at("sendcan").queue_size)); + assert(subscriber != NULL); + subscriber->setTimeout(100); + + // run as fast as messages come in + while (!do_exit && check_connected(panda)) { + std::unique_ptr msg(subscriber->receive()); + if (!msg) { + continue; + } + + capnp::FlatArrayMessageReader cmsg(aligned_buf.align(msg.get())); + cereal::Event::Reader event = cmsg.getRoot(); + + // Don't send if older than 1 second + if ((nanos_since_boot() - event.getLogMonoTime() < 1e9) && !fake_send) { + LOGT("sending sendcan to panda: %s", (panda->hw_serial()).c_str()); + panda->can_send(event.getSendcan()); + LOGT("sendcan sent to panda: %s", (panda->hw_serial()).c_str()); + } else { + LOGE("sendcan too old to send: %" PRIu64 ", %" PRIu64, nanos_since_boot(), event.getLogMonoTime()); + } + } +} + +void can_recv(Panda *panda, PubMaster *pm) { + static std::vector raw_can_data; + { + raw_can_data.clear(); + bool comms_healthy = panda->can_receive(raw_can_data); + + MessageBuilder msg; + auto evt = msg.initEvent(); + evt.setValid(comms_healthy); + auto canData = evt.initCan(raw_can_data.size()); + for (size_t i = 0; i < raw_can_data.size(); ++i) { + canData[i].setAddress(raw_can_data[i].address); + canData[i].setDat(kj::arrayPtr((uint8_t*)raw_can_data[i].dat.data(), raw_can_data[i].dat.size())); + canData[i].setSrc(raw_can_data[i].src); + } + pm->send("can", msg); + } +} + +void fill_panda_state(cereal::PandaState::Builder &ps, cereal::PandaState::PandaType hw_type, const health_t &health) { + ps.setVoltage(health.voltage_pkt); + ps.setCurrent(health.current_pkt); + ps.setUptime(health.uptime_pkt); + ps.setSafetyTxBlocked(health.safety_tx_blocked_pkt); + ps.setSafetyRxInvalid(health.safety_rx_invalid_pkt); + ps.setIgnitionLine(health.ignition_line_pkt); + ps.setIgnitionCan(health.ignition_can_pkt); + ps.setControlsAllowed(health.controls_allowed_pkt); + ps.setTxBufferOverflow(health.tx_buffer_overflow_pkt); + ps.setRxBufferOverflow(health.rx_buffer_overflow_pkt); + ps.setPandaType(hw_type); + ps.setSafetyModel(cereal::CarParams::SafetyModel(health.safety_mode_pkt)); + ps.setSafetyParam(health.safety_param_pkt); + ps.setFaultStatus(cereal::PandaState::FaultStatus(health.fault_status_pkt)); + ps.setPowerSaveEnabled((bool)(health.power_save_enabled_pkt)); + ps.setHeartbeatLost((bool)(health.heartbeat_lost_pkt)); + ps.setAlternativeExperience(health.alternative_experience_pkt); + ps.setHarnessStatus(cereal::PandaState::HarnessStatus(health.car_harness_status_pkt)); + ps.setInterruptLoad(health.interrupt_load_pkt); + ps.setFanPower(health.fan_power); + ps.setSafetyRxChecksInvalid((bool)(health.safety_rx_checks_invalid_pkt)); + ps.setSpiErrorCount(health.spi_error_count_pkt); + ps.setSbu1Voltage(health.sbu1_voltage_mV / 1000.0f); + ps.setSbu2Voltage(health.sbu2_voltage_mV / 1000.0f); + ps.setSoundOutputLevel(health.sound_output_level_pkt); + ps.setControlsAllowedLateral(health.controls_allowed_lateral_pkt); + ps.setControlsAllowedLongitudinal(health.controls_allowed_longitudinal_pkt); +} + +void fill_panda_can_state(cereal::PandaState::PandaCanState::Builder &cs, const can_health_t &can_health) { + cs.setBusOff((bool)can_health.bus_off); + cs.setBusOffCnt(can_health.bus_off_cnt); + cs.setErrorWarning((bool)can_health.error_warning); + cs.setErrorPassive((bool)can_health.error_passive); + cs.setLastError(cereal::PandaState::PandaCanState::LecErrorCode(can_health.last_error)); + cs.setLastStoredError(cereal::PandaState::PandaCanState::LecErrorCode(can_health.last_stored_error)); + cs.setLastDataError(cereal::PandaState::PandaCanState::LecErrorCode(can_health.last_data_error)); + cs.setLastDataStoredError(cereal::PandaState::PandaCanState::LecErrorCode(can_health.last_data_stored_error)); + cs.setReceiveErrorCnt(can_health.receive_error_cnt); + cs.setTransmitErrorCnt(can_health.transmit_error_cnt); + cs.setTotalErrorCnt(can_health.total_error_cnt); + cs.setTotalTxLostCnt(can_health.total_tx_lost_cnt); + cs.setTotalRxLostCnt(can_health.total_rx_lost_cnt); + cs.setTotalTxCnt(can_health.total_tx_cnt); + cs.setTotalRxCnt(can_health.total_rx_cnt); + cs.setTotalFwdCnt(can_health.total_fwd_cnt); + cs.setCanSpeed(can_health.can_speed); + cs.setCanDataSpeed(can_health.can_data_speed); + cs.setCanfdEnabled(can_health.canfd_enabled); + cs.setBrsEnabled(can_health.brs_enabled); + cs.setCanfdNonIso(can_health.canfd_non_iso); + cs.setIrq0CallRate(can_health.irq0_call_rate); + cs.setIrq1CallRate(can_health.irq1_call_rate); + cs.setIrq2CallRate(can_health.irq2_call_rate); + cs.setCanCoreResetCnt(can_health.can_core_reset_cnt); +} + +std::optional send_panda_states(PubMaster *pm, Panda *panda, bool is_onroad, bool spoofing_started, bool always_offroad) { + // build msg + MessageBuilder msg; + auto evt = msg.initEvent(); + auto pss = evt.initPandaStates(1); + + auto health_opt = panda->get_state(); + if (!health_opt) { + return std::nullopt; + } + + health_t health = *health_opt; + + std::array can_health{}; + for (uint32_t i = 0; i < PANDA_CAN_CNT; i++) { + auto can_health_opt = panda->get_can_state(i); + if (!can_health_opt) { + return std::nullopt; + } + can_health[i] = *can_health_opt; + } + + if (spoofing_started) { + health.ignition_line_pkt = 1; + } + + bool ignition_local = ((health.ignition_line_pkt != 0) || (health.ignition_can_pkt != 0)) && !always_offroad; + + // Make sure CAN buses are live: safety_setter_thread does not work if Panda CAN are silent and there is only one other CAN node + if (health.safety_mode_pkt == (uint8_t)(cereal::CarParams::SafetyModel::SILENT)) { + panda->set_safety_model(cereal::CarParams::SafetyModel::NO_OUTPUT); + } + + bool power_save_desired = !ignition_local; + if (health.power_save_enabled_pkt != power_save_desired) { + panda->set_power_saving(power_save_desired); + } + + // set safety mode to NO_OUTPUT when car is off or we're not onroad. ELM327 is an alternative if we want to leverage athenad/connect + bool should_close_relay = !ignition_local || !is_onroad; + if (should_close_relay && (health.safety_mode_pkt != (uint8_t)(cereal::CarParams::SafetyModel::NO_OUTPUT))) { + panda->set_safety_model(cereal::CarParams::SafetyModel::NO_OUTPUT); + } + + if (!panda->comms_healthy()) { + evt.setValid(false); + } + + auto ps = pss[0]; + fill_panda_state(ps, panda->hw_type, health); + + auto cs = std::array{ps.initCanState0(), ps.initCanState1(), ps.initCanState2()}; + for (uint32_t j = 0; j < PANDA_CAN_CNT; j++) { + fill_panda_can_state(cs[j], can_health[j]); + } + + // Convert faults bitset to capnp list + std::bitset fault_bits(health.faults_pkt); + auto faults = ps.initFaults(fault_bits.count()); + + size_t j = 0; + for (size_t f = size_t(cereal::PandaState::FaultType::RELAY_MALFUNCTION); + f <= size_t(cereal::PandaState::FaultType::HEARTBEAT_LOOP_WATCHDOG); f++) { + if (fault_bits.test(f)) { + faults.set(j, cereal::PandaState::FaultType(f)); + j++; + } + } + + pm->send("pandaStates", msg); + return ignition_local; +} + +void send_peripheral_state(Panda *panda, PubMaster *pm) { + auto health_opt = panda->get_state(); + if (!health_opt) { + return; + } + + // build msg + MessageBuilder msg; + auto evt = msg.initEvent(); + evt.setValid(panda->comms_healthy()); + + auto ps = evt.initPeripheralState(); + ps.setPandaType(panda->hw_type); + + health_t health = *health_opt; + ps.setVoltage(health.voltage_pkt); + ps.setCurrent(health.current_pkt); + + uint16_t fan_speed_rpm = panda->get_fan_speed(); + ps.setFanSpeedRpm(fan_speed_rpm); + + pm->send("peripheralState", msg); +} + +void process_panda_state(Panda *panda, PubMaster *pm, bool engaged, bool engaged_mads, bool is_onroad, bool spoofing_started, bool always_offroad) { + auto ignition_opt = send_panda_states(pm, panda, is_onroad, spoofing_started, always_offroad); + if (!ignition_opt) { + LOGE("Failed to get ignition_opt"); + return; + } + + // check if we should have pandad reconnect + if (!ignition_opt.value()) { + if (!panda->comms_healthy()) { + LOGE("Reconnecting, communication to panda not healthy"); + do_exit = true; + } + } + + panda->send_heartbeat(engaged, engaged_mads); +} + +void process_peripheral_state(Panda *panda, PubMaster *pm, bool no_fan_control, bool is_onroad) { + static Params params; + static SubMaster sm({"deviceState", "driverCameraState"}); + + static uint64_t last_driver_camera_t = 0; + static uint16_t prev_fan_speed = 999; + static int ir_pwr = 0; + static int prev_ir_pwr = 999; + static uint32_t prev_frame_id = UINT32_MAX; + static bool driver_view = false; + static bool not_car = false; + static bool not_car_checked = false; + + // TODO: can we merge these? + static FirstOrderFilter integ_lines_filter(0, 30.0, 0.05); + static FirstOrderFilter integ_lines_filter_driver_view(0, 5.0, 0.05); + + { + sm.update(0); + if (sm.updated("deviceState") && !no_fan_control) { + // Fan speed + uint16_t fan_speed = sm["deviceState"].getDeviceState().getFanSpeedPercentDesired(); + if (fan_speed != prev_fan_speed || sm.frame % 100 == 0) { + panda->set_fan_speed(fan_speed); + prev_fan_speed = fan_speed; + } + } + + if (sm.updated("driverCameraState")) { + auto event = sm["driverCameraState"]; + int cur_integ_lines = event.getDriverCameraState().getIntegLines(); + + // reset the filter when camerad restarts + if (event.getDriverCameraState().getFrameId() < prev_frame_id) { + integ_lines_filter.reset(0); + integ_lines_filter_driver_view.reset(0); + driver_view = params.getBool("IsDriverViewEnabled"); + } + prev_frame_id = event.getDriverCameraState().getFrameId(); + + cur_integ_lines = (driver_view ? integ_lines_filter_driver_view : integ_lines_filter).update(cur_integ_lines); + last_driver_camera_t = event.getLogMonoTime(); + + if (cur_integ_lines <= CUTOFF_IL) { + ir_pwr = 0; + } else if (cur_integ_lines > SATURATE_IL) { + ir_pwr = 100; + } else { + ir_pwr = 100 * (cur_integ_lines - CUTOFF_IL) / (SATURATE_IL - CUTOFF_IL); + } + } + + // Disable IR on input timeout + if (nanos_since_boot() - last_driver_camera_t > 1e9) { + ir_pwr = 0; + } + + // turn off IR leds if body + if (!not_car_checked && is_onroad) { + std::string cp_bytes = params.get("CarParams"); + if (cp_bytes.size() > 0) { + AlignedBuffer aligned_buf; + capnp::FlatArrayMessageReader cmsg(aligned_buf.align(cp_bytes.data(), cp_bytes.size())); + cereal::CarParams::Reader CP = cmsg.getRoot(); + not_car = CP.getNotCar(); + not_car_checked = true; + } + } + if (not_car) { + ir_pwr = 0; + } + + if (ir_pwr != prev_ir_pwr || sm.frame % 100 == 0) { + int16_t ir_panda = util::map_val(ir_pwr, 0, 100, 0, MAX_IR_PANDA_VAL); + panda->set_ir_pwr(ir_panda); + Hardware::set_ir_power(ir_pwr); + prev_ir_pwr = ir_pwr; + } + } +} + +void pandad_run(Panda *panda) { + const bool no_fan_control = getenv("NO_FAN_CONTROL") != nullptr; + const bool spoofing_started = getenv("STARTED") != nullptr; + const bool fake_send = getenv("FAKESEND") != nullptr; + + // Start helper thread for event-driven sendcan. + std::thread send_thread(can_send_thread, panda, fake_send); + + RateKeeper rk("pandad", 100); + SubMaster sm({"selfdriveState", "deviceState", "selfdriveStateSP"}); + PubMaster pm({"can", "pandaStates", "peripheralState"}); + PandaSafety panda_safety(panda); + bool engaged = false; + bool engaged_mads = false; + bool is_onroad = false; + bool always_offroad = false; + + // Main loop: receive CAN first, then process lower priority panda and peripheral state. + while (!do_exit && check_connected(panda)) { + can_recv(panda, &pm); + + // Process peripheral state at 20 Hz + if (rk.frame() % 5 == 0) { + process_peripheral_state(panda, &pm, no_fan_control, is_onroad); + } + + // Process panda state at 10 Hz + if (rk.frame() % 10 == 0) { + sm.update(0); + engaged = sm.allAliveAndValid({"selfdriveState"}) && sm["selfdriveState"].getSelfdriveState().getEnabled(); + if (sm.updated("deviceState")) { + is_onroad = sm["deviceState"].getDeviceState().getStarted(); + } + engaged_mads = process_mads_heartbeat(&sm); + always_offroad = panda_safety.getOffroadMode(); + process_panda_state(panda, &pm, engaged, engaged_mads, is_onroad, spoofing_started, always_offroad); + panda_safety.configureSafetyMode(is_onroad); + } + + // Send out peripheralState at 2Hz + if (rk.frame() % 50 == 0) { + send_peripheral_state(panda, &pm); + } + + // Forward logs from panda to cloudlog if available + std::string log = panda->serial_read(); + if (!log.empty()) { + if (log.find("Register 0x") != std::string::npos) { + // Log register divergent faults as errors + LOGE("%s", log.c_str()); + } else { + LOGD("%s", log.c_str()); + } + } + + rk.keepTime(); + } + + // Close relay on exit to prevent a fault + if (is_onroad && !engaged) { + if (panda->connected()) { + panda->set_safety_model(cereal::CarParams::SafetyModel::NO_OUTPUT); + } + } + + send_thread.join(); +} + +void pandad_main_thread(std::string serial) { + if (serial.empty()) { + auto serials = Panda::list(); + + if (serials.empty()) { + LOGW("no pandas found, exiting"); + return; + } + serial = serials[0]; + } + + LOGW("connecting to panda: %s", serial.c_str()); + + Panda *panda = nullptr; + while (!do_exit) { + panda = connect(serial); + if (panda) break; + util::sleep_for(100); + } + + if (!do_exit) { + LOGW("connected to panda"); + pandad_run(panda); + } + + delete panda; +} diff --git a/openpilot/selfdrive/pandad/pandad.h b/openpilot/selfdrive/pandad/pandad.h new file mode 100644 index 0000000000..1558d0469e --- /dev/null +++ b/openpilot/selfdrive/pandad/pandad.h @@ -0,0 +1,35 @@ +#pragma once + +#include + +#include "common/params.h" +#include "selfdrive/pandad/panda.h" + +void pandad_main_thread(std::string serial); + +// deprecated devices +static const std::vector SUPPORTED_PANDA_TYPES = { + cereal::PandaState::PandaType::RED_PANDA, + cereal::PandaState::PandaType::TRES, + cereal::PandaState::PandaType::CUATRO, +}; + + +class PandaSafety { +public: + PandaSafety(Panda *panda) : panda_(panda) {} + void configureSafetyMode(bool is_onroad); + bool getOffroadMode(); + +private: + void updateMultiplexingMode(); + std::vector fetchCarParams(); + void setSafetyMode(const std::vector ¶ms_string); + + bool initialized_ = false; + bool log_once_ = false; + bool safety_configured_ = false; + bool prev_obd_multiplexing_ = false; + Panda *panda_; + Params params_; +}; diff --git a/openpilot/selfdrive/pandad/pandad.py b/openpilot/selfdrive/pandad/pandad.py new file mode 100755 index 0000000000..a618dacccd --- /dev/null +++ b/openpilot/selfdrive/pandad/pandad.py @@ -0,0 +1,145 @@ +#!/usr/bin/env python3 +# simple pandad wrapper that updates the panda first +import os +import usb1 +import time +import signal +import subprocess + +from panda import Panda, PandaDFU, PandaProtocolMismatch, McuType, FW_PATH +from openpilot.common.basedir import BASEDIR +from openpilot.common.params import Params +from openpilot.common.hardware import HARDWARE +from openpilot.common.swaglog import cloudlog + +from openpilot.sunnypilot.selfdrive.pandad.rivian_long_flasher import flash_rivian_long + + +def get_expected_signature() -> bytes: + fn = os.path.join(FW_PATH, McuType.H7.config.app_fn) + return Panda.get_signature_from_firmware(fn) + +def flash_panda(panda_serial: str): + panda = Panda(panda_serial) + + # skip flashing if the detected panda is not supported + if panda.get_type() not in Panda.SUPPORTED_DEVICES: + cloudlog.warning(f"Panda {panda_serial} is not supported (hw_type: {panda.get_type()}), skipping flash...") + panda.close() + return + + fw_signature = get_expected_signature() + internal_panda = panda.is_internal() + + panda_version = "bootstub" if panda.bootstub else panda.get_version() + panda_signature = b"" if panda.bootstub else panda.get_signature() + cloudlog.warning(f"Panda {panda_serial} connected, version: {panda_version}, signature {panda_signature.hex()[:16]}, expected {fw_signature.hex()[:16]}") + + if panda.bootstub or panda_signature != fw_signature: + cloudlog.info("Panda firmware out of date, update required") + panda.flash() + cloudlog.info("Done flashing") + + if panda.bootstub: + bootstub_version = panda.get_version() + cloudlog.info(f"Flashed firmware not booting, flashing development bootloader. {bootstub_version=}, {internal_panda=}") + if internal_panda: + HARDWARE.recover_internal_panda() + panda.recover(reset=(not internal_panda)) + cloudlog.info("Done flashing bootstub") + + if panda.bootstub: + cloudlog.info("Panda still not booting, exiting") + raise AssertionError + + panda_signature = panda.get_signature() + if panda_signature != fw_signature: + cloudlog.info("Version mismatch after flashing, exiting") + raise AssertionError + + panda.close() + + +def check_panda_support(panda_serials: list[str]) -> list[str]: + spi_serials = set(Panda.spi_list()) + for serial in panda_serials: + if serial in spi_serials: + return [serial] + + for serial in panda_serials: + panda = Panda(serial) + is_internal = panda.is_internal() + panda.close() + if is_internal: + return [serial] + + return [] + + +def main() -> None: + # signal pandad to close the relay and exit + def signal_handler(signum, frame): + cloudlog.info(f"Caught signal {signum}, exiting") + nonlocal do_exit + do_exit = True + if process is not None: + process.send_signal(signal.SIGINT) + + process = None + do_exit = False + signal.signal(signal.SIGINT, signal_handler) + + # check health for lost heartbeat + try: + for s in Panda.list(): + with Panda(s) as p: + health = p.health() + if p.is_internal() and health["heartbeat_lost"]: + Params().put_bool("PandaHeartbeatLost", True, block=True) + cloudlog.event("heartbeat lost", deviceState=health) + except Exception: + cloudlog.exception("pandad.uncaught_exception") + + count = 0 + while not do_exit: + try: + cloudlog.event("pandad.flash_and_connect", count=count) + if (count % 2) == 0: + HARDWARE.reset_internal_panda() + else: + HARDWARE.recover_internal_panda() + count += 1 + + # Flash all Pandas in DFU mode + for serial in PandaDFU.list(): + cloudlog.info(f"Panda in DFU mode found, flashing recovery {serial}") + PandaDFU(serial).recover() + time.sleep(1) + + panda_serials = Panda.list() + if len(panda_serials): + # custom flasher for xnor's Rivian Longitudinal Upgrade Kit + flash_rivian_long(panda_serials) + # find the internal supported panda (e.g. skip external Black Panda) + panda_serials = check_panda_support(panda_serials) + + assert len(panda_serials) == 1 + cloudlog.info(f"{len(panda_serials)} panda found, connecting - {panda_serials}") + flash_panda(panda_serials[0]) + + # run real pandad + os.environ['MANAGER_DAEMON'] = 'pandad' + process = subprocess.Popen(["./pandad"], cwd=os.path.join(BASEDIR, "openpilot/selfdrive/pandad")) + process.wait() + # TODO: wrap all panda exceptions in a base panda exception + except (usb1.USBErrorNoDevice, usb1.USBErrorPipe): + # a panda was disconnected while setting everything up. let's try again + cloudlog.exception("Panda USB exception while setting up") + except PandaProtocolMismatch: + cloudlog.exception("pandad.protocol_mismatch") + except Exception: + cloudlog.exception("pandad.uncaught_exception") + + +if __name__ == "__main__": + main() diff --git a/openpilot/selfdrive/pandad/pandad_api_impl.py b/openpilot/selfdrive/pandad/pandad_api_impl.py new file mode 100644 index 0000000000..9da277d73a --- /dev/null +++ b/openpilot/selfdrive/pandad/pandad_api_impl.py @@ -0,0 +1,88 @@ +import time +from openpilot.cereal import log + +NO_TRAVERSAL_LIMIT = 2**64 - 1 + +# Cache schema fields for faster access (avoids string lookup on each field access) +_cached_reader_fields = None # (address_field, dat_field, src_field) for reading +_cached_writer_fields = None # (address_field, dat_field, src_field) for writing + + +def _get_reader_fields(schema): + """Get cached schema field objects for reading.""" + global _cached_reader_fields + if _cached_reader_fields is None: + fields = schema.fields + _cached_reader_fields = (fields['address'], fields['dat'], fields['src']) + return _cached_reader_fields + + +def _get_writer_fields(schema): + """Get cached schema field objects for writing.""" + global _cached_writer_fields + if _cached_writer_fields is None: + fields = schema.fields + _cached_writer_fields = (fields['address'], fields['dat'], fields['src']) + return _cached_writer_fields + + +def can_list_to_can_capnp(can_msgs, msgtype='can', valid=True): + """Convert list of CAN messages to Cap'n Proto serialized bytes. + + Args: + can_msgs: List of tuples [(address, data_bytes, src), ...] + msgtype: 'can' or 'sendcan' + valid: Whether the event is valid + + Returns: + Cap'n Proto serialized bytes + """ + global _cached_writer_fields + + dat = log.Event.new_message(valid=valid, logMonoTime=int(time.monotonic() * 1e9)) + can_data = dat.init(msgtype, len(can_msgs)) + + # Cache schema fields on first call + if _cached_writer_fields is None and len(can_msgs) > 0: + _cached_writer_fields = _get_writer_fields(can_data[0].schema) + + if _cached_writer_fields is not None: + addr_f, dat_f, src_f = _cached_writer_fields + for i, msg in enumerate(can_msgs): + f = can_data[i] + f._set_by_field(addr_f, msg[0]) + f._set_by_field(dat_f, msg[1]) + f._set_by_field(src_f, msg[2]) + + return dat.to_bytes() + + +def can_capnp_to_list(strings, msgtype='can'): + """Convert Cap'n Proto serialized bytes to list of CAN messages. + + Args: + strings: Tuple/list of serialized Cap'n Proto bytes + msgtype: 'can' or 'sendcan' + + Returns: + List of tuples [(nanos, [(address, data, src), ...]), ...] + """ + global _cached_reader_fields + result = [] + + for s in strings: + with log.Event.from_bytes(s, traversal_limit_in_words=NO_TRAVERSAL_LIMIT) as event: + frames = getattr(event, msgtype) + + # Cache schema fields on first frame for faster access + if _cached_reader_fields is None and len(frames) > 0: + _cached_reader_fields = _get_reader_fields(frames[0].schema) + + if _cached_reader_fields is not None: + addr_f, dat_f, src_f = _cached_reader_fields + frame_list = [(f._get_by_field(addr_f), f._get_by_field(dat_f), f._get_by_field(src_f)) for f in frames] + else: + frame_list = [] + + result.append((event.logMonoTime, frame_list)) + return result diff --git a/selfdrive/pandad/spi.cc b/openpilot/selfdrive/pandad/spi.cc similarity index 87% rename from selfdrive/pandad/spi.cc rename to openpilot/selfdrive/pandad/spi.cc index 108b11b9dc..f54c26e506 100644 --- a/selfdrive/pandad/spi.cc +++ b/openpilot/selfdrive/pandad/spi.cc @@ -1,4 +1,3 @@ -#ifndef __APPLE__ #include #include #include @@ -33,7 +32,7 @@ const std::string SPI_DEVICE = "/dev/spidev0.0"; class LockEx { public: - LockEx(int fd, std::recursive_mutex &m) : fd(fd), m(m) { + LockEx(int fd_, std::recursive_mutex &m_) : fd(fd_), m(m_) { m.lock(); flock(fd, LOCK_EX); } @@ -55,7 +54,7 @@ private: util::hexdump(tx_buf, std::min((int)header.tx_len, 8)).c_str()); \ } while (0) -PandaSpiHandle::PandaSpiHandle(std::string serial) : PandaCommsHandle(serial) { +PandaSpiHandle::PandaSpiHandle(std::string serial) { int ret; const int uid_len = 12; uint8_t uid[uid_len] = {0}; @@ -66,58 +65,44 @@ PandaSpiHandle::PandaSpiHandle(std::string serial) : PandaCommsHandle(serial) { // 50MHz is the max of the 845. note that some older // revs of the comma three may not support this speed uint32_t spi_speed = 50000000; - - if (!util::file_exists(SPI_DEVICE)) { - goto fail; - } - - spi_fd = open(SPI_DEVICE.c_str(), O_RDWR); - if (spi_fd < 0) { - LOGE("failed opening SPI device %d", spi_fd); - goto fail; - } - - // SPI settings - ret = util::safe_ioctl(spi_fd, SPI_IOC_WR_MODE, &spi_mode); - if (ret < 0) { - LOGE("failed setting SPI mode %d", ret); - goto fail; - } - - ret = util::safe_ioctl(spi_fd, SPI_IOC_WR_MAX_SPEED_HZ, &spi_speed); - if (ret < 0) { - LOGE("failed setting SPI speed"); - goto fail; - } - - ret = util::safe_ioctl(spi_fd, SPI_IOC_WR_BITS_PER_WORD, &spi_bits_per_word); - if (ret < 0) { - LOGE("failed setting SPI bits per word"); - goto fail; - } - - // get hw UID/serial - ret = control_read(0xc3, 0, 0, uid, uid_len, 100); - if (ret == uid_len) { - std::stringstream stream; - for (int i = 0; i < uid_len; i++) { - stream << std::hex << std::setw(2) << std::setfill('0') << int(uid[i]); + try { + if (!util::file_exists(SPI_DEVICE)) { + throw std::runtime_error("Error connecting to panda: SPI device not found"); } - hw_serial = stream.str(); - } else { - LOGD("failed to get serial %d", ret); - goto fail; - } - if (!serial.empty() && (serial != hw_serial)) { - goto fail; - } + spi_fd = open(SPI_DEVICE.c_str(), O_RDWR); + if (spi_fd < 0) { + LOGE("failed opening SPI device %d", spi_fd); + throw std::runtime_error("Error connecting to panda: failed to open SPI device"); + } + // SPI settings + util::safe_ioctl(spi_fd, SPI_IOC_WR_MODE, &spi_mode, "failed setting SPI mode"); + util::safe_ioctl(spi_fd, SPI_IOC_WR_MAX_SPEED_HZ, &spi_speed, "failed setting SPI speed"); + util::safe_ioctl(spi_fd, SPI_IOC_WR_BITS_PER_WORD, &spi_bits_per_word, "failed setting SPI bits per word"); + + // get hw UID/serial + ret = control_read(0xc3, 0, 0, uid, uid_len, 100); + if (ret == uid_len) { + std::stringstream stream; + for (int i = 0; i < uid_len; i++) { + stream << std::hex << std::setw(2) << std::setfill('0') << int(uid[i]); + } + hw_serial = stream.str(); + } else { + LOGD("failed to get serial %d", ret); + throw std::runtime_error("Error connecting to panda: failed to get serial"); + } + + if (!serial.empty() && (serial != hw_serial)) { + throw std::runtime_error("Error connecting to panda: serial mismatch"); + } + + } catch (...) { + cleanup(); + throw; + } return; - -fail: - cleanup(); - throw std::runtime_error("Error connecting to panda"); } PandaSpiHandle::~PandaSpiHandle() { @@ -421,4 +406,3 @@ fail: if (ret >= 0) ret = -1; return ret; } -#endif diff --git a/selfdrive/modeld/__init__.py b/openpilot/selfdrive/pandad/tests/__init__.py similarity index 100% rename from selfdrive/modeld/__init__.py rename to openpilot/selfdrive/pandad/tests/__init__.py diff --git a/selfdrive/pandad/tests/bootstub.panda_h7.bin b/openpilot/selfdrive/pandad/tests/bootstub.panda_h7.bin similarity index 100% rename from selfdrive/pandad/tests/bootstub.panda_h7.bin rename to openpilot/selfdrive/pandad/tests/bootstub.panda_h7.bin diff --git a/openpilot/selfdrive/pandad/tests/test_pandad.py b/openpilot/selfdrive/pandad/tests/test_pandad.py new file mode 100644 index 0000000000..0f8fd9fc1a --- /dev/null +++ b/openpilot/selfdrive/pandad/tests/test_pandad.py @@ -0,0 +1,81 @@ +import os +import pytest +import time + +import openpilot.cereal.messaging as messaging +from openpilot.cereal import log +from openpilot.common.gpio import gpio_set, gpio_init +from panda import Panda, PandaDFU +from openpilot.system.manager.process_config import managed_processes +from openpilot.common.hardware import HARDWARE +from openpilot.common.hardware.tici.pins import GPIO + +HERE = os.path.dirname(os.path.realpath(__file__)) + + +@pytest.mark.tici +class TestPandad: + def teardown_method(self): + managed_processes['pandad'].stop() + + def _run_test(self, timeout=30) -> float: + st = time.monotonic() + sm = messaging.SubMaster(['pandaStates']) + + managed_processes['pandad'].start() + while (time.monotonic() - st) < timeout: + sm.update(10) + if len(sm['pandaStates']) and sm['pandaStates'][0].pandaType != log.PandaState.PandaType.unknown: + break + dt = time.monotonic() - st + managed_processes['pandad'].stop() + + if len(sm['pandaStates']) == 0 or sm['pandaStates'][0].pandaType == log.PandaState.PandaType.unknown: + raise Exception("pandad failed to start") + + return dt + + def _go_to_dfu(self): + HARDWARE.recover_internal_panda() + assert Panda.wait_for_dfu(None, 10) + + def _flash_bootstub(self, fn): + self._go_to_dfu() + pd = PandaDFU(None) + if fn is None: + fn = os.path.join(HERE, pd.get_mcu_type().config.bootstub_fn) + with open(fn, "rb") as f: + pd.program_bootstub(f.read()) + HARDWARE.reset_internal_panda() + + def test_in_dfu(self): + HARDWARE.recover_internal_panda() + self._run_test() + + def test_in_bootstub(self): + with Panda() as p: + p.reset(enter_bootstub=True) + assert p.bootstub + self._run_test() + + def test_in_reset(self): + gpio_init(GPIO.STM_RST_N, True) + gpio_set(GPIO.STM_RST_N, True) + assert not Panda.list() + self._run_test() + + def test_release_to_devel_bootstub(self): + st = time.monotonic() + self._flash_bootstub(None) + print("flash done", time.monotonic() - st) + self._run_test() + + def test_recover_from_bad_bootstub(self): + self._go_to_dfu() + with PandaDFU(None) as pd: + pd._handle.program(pd.get_mcu_type().config.bootstub_address, b"\x00"*100) + HARDWARE.reset_internal_panda() + assert not Panda.list() + assert not PandaDFU.list() + + self._run_test() diff --git a/openpilot/selfdrive/pandad/tests/test_pandad_canprotocol.cc b/openpilot/selfdrive/pandad/tests/test_pandad_canprotocol.cc new file mode 100644 index 0000000000..83339a4c1c --- /dev/null +++ b/openpilot/selfdrive/pandad/tests/test_pandad_canprotocol.cc @@ -0,0 +1,135 @@ +#define CATCH_CONFIG_MAIN +#define CATCH_CONFIG_ENABLE_BENCHMARKING + +#include + +#include "catch2/catch.hpp" +#include "openpilot/cereal/messaging/messaging.h" +#include "common/util.h" +#include "selfdrive/pandad/panda.h" + +struct PandaTest : public Panda { + PandaTest(int can_list_size, cereal::PandaState::PandaType hw_type); + void test_can_send(); + void test_can_recv(uint32_t chunk_size = 0); + void test_chunked_can_recv(); + + std::map test_data; + int can_list_size = 0; + int total_pakets_size = 0; + MessageBuilder msg; + capnp::List::Reader can_data_list; +}; + +PandaTest::PandaTest(int can_list_size_, cereal::PandaState::PandaType hw_type_) : can_list_size(can_list_size_), Panda() { + this->hw_type = hw_type_; + int data_limit = ((hw_type == cereal::PandaState::PandaType::RED_PANDA) ? std::size(dlc_to_len) : 8); + // prepare test data + for (int i = 0; i < data_limit; ++i) { + std::random_device rd; + std::independent_bits_engine rbe(rd()); + + int data_len = dlc_to_len[i]; + std::string bytes(data_len, '\0'); + std::generate(bytes.begin(), bytes.end(), std::ref(rbe)); + test_data[data_len] = bytes; + } + + // generate can messages for this panda + auto can_list = msg.initEvent().initSendcan(can_list_size); + for (uint8_t i = 0; i < can_list_size; ++i) { + auto can = can_list[i]; + uint32_t id = util::random_int(0, std::size(dlc_to_len) - 1); + const std::string &dat = test_data[dlc_to_len[id]]; + can.setAddress(i); + can.setSrc(util::random_int(0, 2)); + can.setDat(kj::ArrayPtr((uint8_t *)dat.data(), dat.size())); + total_pakets_size += sizeof(can_header) + dat.size(); + } + + can_data_list = can_list.asReader(); + INFO("test " << can_list_size << " packets, total size " << total_pakets_size); +} + +void PandaTest::test_can_send() { + std::vector unpacked_data; + this->pack_can_buffer(can_data_list, [&](uint8_t *chunk, size_t size) { + unpacked_data.insert(unpacked_data.end(), chunk, &chunk[size]); + }); + REQUIRE(unpacked_data.size() == total_pakets_size); + + int cnt = 0; + INFO("test can message integrity"); + for (int pos = 0, pckt_len = 0; pos < unpacked_data.size(); pos += pckt_len) { + can_header header; + memcpy(&header, &unpacked_data[pos], sizeof(can_header)); + const uint8_t data_len = dlc_to_len[header.data_len_code]; + pckt_len = sizeof(can_header) + data_len; + + REQUIRE(header.addr == cnt); + REQUIRE(test_data.find(data_len) != test_data.end()); + const std::string &dat = test_data[data_len]; + REQUIRE(memcmp(dat.data(), &unpacked_data[pos + sizeof(can_header)], dat.size()) == 0); + ++cnt; + } + REQUIRE(cnt == can_list_size); +} + +void PandaTest::test_can_recv(uint32_t rx_chunk_size) { + std::vector frames; + this->pack_can_buffer(can_data_list, [&](uint8_t *data, uint32_t size) { + if (rx_chunk_size == 0) { + REQUIRE(this->unpack_can_buffer(data, size, frames)); + } else { + this->receive_buffer_size = 0; + uint32_t pos = 0; + + while (pos < size) { + uint32_t chunk_size = std::min(rx_chunk_size, size - pos); + memcpy(&this->receive_buffer[this->receive_buffer_size], &data[pos], chunk_size); + this->receive_buffer_size += chunk_size; + pos += chunk_size; + + REQUIRE(this->unpack_can_buffer(this->receive_buffer, this->receive_buffer_size, frames)); + } + } + }); + + REQUIRE(frames.size() == can_list_size); + for (int i = 0; i < frames.size(); ++i) { + REQUIRE(frames[i].address == i); + REQUIRE(test_data.find(frames[i].dat.size()) != test_data.end()); + const std::string &dat = test_data[frames[i].dat.size()]; + REQUIRE(memcmp(dat.data(), frames[i].dat.data(), dat.size()) == 0); + } +} + +TEST_CASE("send/recv CAN 2.0 packets") { + auto can_list_size = GENERATE(1, 3, 5, 10, 30, 60, 100, 200); + PandaTest test(can_list_size, cereal::PandaState::PandaType::DOS); + + SECTION("can_send") { + test.test_can_send(); + } + SECTION("can_receive") { + test.test_can_recv(); + } + SECTION("chunked_can_receive") { + test.test_can_recv(0x40); + } +} + +TEST_CASE("send/recv CAN FD packets") { + auto can_list_size = GENERATE(1, 3, 5, 10, 30, 60, 100, 200); + PandaTest test(can_list_size, cereal::PandaState::PandaType::RED_PANDA); + + SECTION("can_send") { + test.test_can_send(); + } + SECTION("can_receive") { + test.test_can_recv(); + } + SECTION("chunked_can_receive") { + test.test_can_recv(0x40); + } +} diff --git a/selfdrive/pandad/tests/test_pandad_loopback.py b/openpilot/selfdrive/pandad/tests/test_pandad_loopback.py similarity index 76% rename from selfdrive/pandad/tests/test_pandad_loopback.py rename to openpilot/selfdrive/pandad/tests/test_pandad_loopback.py index bf1c557128..0d0aa80046 100644 --- a/selfdrive/pandad/tests/test_pandad_loopback.py +++ b/openpilot/selfdrive/pandad/tests/test_pandad_loopback.py @@ -6,55 +6,59 @@ import pytest from collections import defaultdict from pprint import pprint -import cereal.messaging as messaging -from cereal import car, log +import openpilot.cereal.messaging as messaging +from openpilot.cereal import log +from opendbc.car.structs import car from opendbc.car.can_definitions import CanData -from openpilot.common.retry import retry +from openpilot.common.utils import retry from openpilot.common.params import Params from openpilot.common.timeout import Timeout from openpilot.selfdrive.pandad import can_list_to_can_capnp -from openpilot.system.hardware import TICI from openpilot.selfdrive.test.helpers import with_processes +def publish_device_state(pm, started): + msg = messaging.new_message('deviceState') + msg.deviceState.started = started + pm.send('deviceState', msg) + @retry(attempts=3) -def setup_pandad(num_pandas): +def setup_pandad(): params = Params() params.clear_all() - params.put_bool("IsOnroad", False) + pm = messaging.PubMaster(['deviceState']) sm = messaging.SubMaster(['pandaStates']) + publish_device_state(pm, False) with Timeout(90, "pandad didn't start"): while sm.recv_frame['pandaStates'] < 1 or len(sm['pandaStates']) == 0 or \ any(ps.pandaType == log.PandaState.PandaType.unknown for ps in sm['pandaStates']): - sm.update(1000) - - found_pandas = len(sm['pandaStates']) - assert num_pandas == found_pandas, "connected pandas ({found_pandas}) doesn't match expected panda count ({num_pandas}). \ - connect another panda for multipanda tests." + publish_device_state(pm, False) + sm.update(100) # pandad safety setting relies on these params cp = car.CarParams.new_message() safety_config = car.CarParams.SafetyConfig.new_message() safety_config.safetyModel = car.CarParams.SafetyModel.allOutput - cp.safetyConfigs = [safety_config]*num_pandas + cp.safetyConfigs = [safety_config] - params.put_bool("IsOnroad", True) - params.put_bool("FirmwareQueryDone", True) - params.put_bool("ControlsReady", True) - params.put("CarParams", cp.to_bytes()) + params.put_bool("FirmwareQueryDone", True, block=True) + params.put_bool("ControlsReady", True, block=True) + params.put("CarParams", cp.to_bytes(), block=True) + publish_device_state(pm, True) with Timeout(90, "pandad didn't set safety mode"): while any(ps.safetyModel != car.CarParams.SafetyModel.allOutput for ps in sm['pandaStates']): - sm.update(1000) + publish_device_state(pm, True) + sm.update(100) -def send_random_can_messages(sendcan, count, num_pandas=1): +def send_random_can_messages(sendcan, count): sent_msgs = defaultdict(set) for _ in range(count): to_send = [] for __ in range(random.randrange(20)): - bus = random.choice([b for b in range(3*num_pandas) if b % 4 != 3]) + bus = random.choice(range(3)) addr = random.randrange(1, 1<<29) dat = bytes(random.getrandbits(8) for _ in range(random.randrange(1, 9))) if (addr, dat) in sent_msgs[bus]: @@ -74,8 +78,7 @@ class TestBoarddLoopback: @with_processes(['pandad']) def test_loopback(self): - num_pandas = 2 if TICI and "SINGLE_PANDA" not in os.environ else 1 - setup_pandad(num_pandas) + setup_pandad() sendcan = messaging.pub_sock('sendcan') can = messaging.sub_sock('can', conflate=False, timeout=100) @@ -86,7 +89,7 @@ class TestBoarddLoopback: for i in range(n): print(f"pandad loopback {i}/{n}") - sent_msgs = send_random_can_messages(sendcan, random.randrange(20, 100), num_pandas) + sent_msgs = send_random_can_messages(sendcan, random.randrange(20, 100)) sent_loopback = copy.deepcopy(sent_msgs) sent_loopback.update({k+128: copy.deepcopy(v) for k, v in sent_msgs.items()}) diff --git a/selfdrive/pandad/tests/test_pandad_spi.py b/openpilot/selfdrive/pandad/tests/test_pandad_spi.py similarity index 85% rename from selfdrive/pandad/tests/test_pandad_spi.py rename to openpilot/selfdrive/pandad/tests/test_pandad_spi.py index 9f7cc3b029..2bc302b47c 100644 --- a/selfdrive/pandad/tests/test_pandad_spi.py +++ b/openpilot/selfdrive/pandad/tests/test_pandad_spi.py @@ -4,9 +4,9 @@ import numpy as np import pytest import random -import cereal.messaging as messaging -from cereal.services import SERVICE_LIST -from openpilot.system.hardware import HARDWARE +import openpilot.cereal.messaging as messaging +from openpilot.cereal.services import SERVICE_LIST +from openpilot.common.timeout import Timeout from openpilot.selfdrive.test.helpers import with_processes from openpilot.selfdrive.pandad.tests.test_pandad_loopback import setup_pandad, send_random_can_messages @@ -16,8 +16,6 @@ JUNGLE_SPAM = "JUNGLE_SPAM" in os.environ class TestBoarddSpi: @classmethod def setup_class(cls): - if HARDWARE.get_device_type() == 'tici': - pytest.skip("only for spi pandas") os.environ['STARTED'] = '1' os.environ['SPI_ERR_PROB'] = '0.001' if not JUNGLE_SPAM: @@ -25,20 +23,25 @@ class TestBoarddSpi: @with_processes(['pandad']) def test_spi_corruption(self, subtests): - setup_pandad(1) + setup_pandad() sendcan = messaging.pub_sock('sendcan') socks = {s: messaging.sub_sock(s, conflate=False, timeout=100) for s in ('can', 'pandaStates', 'peripheralState')} - time.sleep(2) - for s in socks.values(): - messaging.drain_sock_raw(s) + readiness_services = {'pandaStates', 'peripheralState'} + ready = set() + with Timeout(2, "pandad services didn't become ready"): + while not readiness_services <= ready: + for service, sock in socks.items(): + if messaging.drain_sock_raw(sock): + ready.add(service) + time.sleep(0.01) total_recv_count = 0 total_sent_count = 0 - sent_msgs = {bus: list() for bus in range(3)} + sent_msgs = {bus: [] for bus in range(3)} st = time.monotonic() - ts = {s: list() for s in socks.keys()} + ts = {s: [] for s in socks.keys()} for _ in range(int(os.getenv("TEST_TIME", "20"))): # send some CAN messages if not JUNGLE_SPAM: @@ -83,7 +86,6 @@ class TestBoarddSpi: ps = m.peripheralState assert ps.pandaType == "tres" assert 4000 < ps.voltage < 14000 - assert 50 < ps.current < 1000 assert ps.fanSpeedRpm < 10000 time.sleep(0.5) diff --git a/selfdrive/selfdrived/alertmanager.py b/openpilot/selfdrive/selfdrived/alertmanager.py similarity index 92% rename from selfdrive/selfdrived/alertmanager.py rename to openpilot/selfdrive/selfdrived/alertmanager.py index 79897404e4..3be56381cf 100644 --- a/selfdrive/selfdrived/alertmanager.py +++ b/openpilot/selfdrive/selfdrived/alertmanager.py @@ -10,15 +10,15 @@ from openpilot.selfdrive.selfdrived.events import Alert from openpilot.sunnypilot.selfdrive.selfdrived.events_base import EmptyAlert -with open(os.path.join(BASEDIR, "selfdrive/selfdrived/alerts_offroad.json")) as f: +with open(os.path.join(BASEDIR, "openpilot/selfdrive/selfdrived/alerts_offroad.json")) as f: OFFROAD_ALERTS = json.load(f) -def set_offroad_alert(alert: str, show_alert: bool, extra_text: str = None) -> None: +def set_offroad_alert(alert: str, show_alert: bool, extra_text: str | None = None) -> None: if show_alert: a = copy.copy(OFFROAD_ALERTS[alert]) a['extra'] = extra_text or '' - Params().put(alert, json.dumps(a)) + Params().put(alert, a, block=True) else: Params().remove(alert) diff --git a/openpilot/selfdrive/selfdrived/alerts_offroad.json b/openpilot/selfdrive/selfdrived/alerts_offroad.json new file mode 100644 index 0000000000..c90497e8c1 --- /dev/null +++ b/openpilot/selfdrive/selfdrived/alerts_offroad.json @@ -0,0 +1,54 @@ +{ + "Offroad_TemperatureTooHigh": { + "text": "Device temperature too high. System cooling down before starting. Current internal component temperature: %1", + "severity": 0 + }, + "Offroad_ConnectivityNeededPrompt": { + "text": "Immediately connect to the internet to check for updates. If you do not connect to the internet, sunnypilot won't engage in %1", + "severity": 0, + "_comment": "Set extra field to number of days" + }, + "Offroad_ConnectivityNeeded": { + "text": "Connect to internet to check for updates. sunnypilot won't automatically start until it connects to internet to check for updates.", + "severity": 1 + }, + "Offroad_UpdateFailed": { + "text": "Unable to download updates\n%1", + "severity": 1, + "_comment": "Set extra field to the failed reason." + }, + "Offroad_NeosUpdate": { + "text": "An update to your device's operating system is downloading in the background. You will be prompted to update when it's ready to install.", + "severity": 0 + }, + "Offroad_UnregisteredHardware": { + "text": "Failed to register with comma.ai backend. It will not connect or upload to comma.ai servers, and receives no support from comma.ai. If this is a device purchased at comma.ai/shop, open a ticket at https://comma.ai/support.", + "severity": 1 + }, + "Offroad_CarUnrecognized": { + "text": "sunnypilot was unable to identify your car. Your car is either unsupported or its ECUs are not recognized. Please submit a pull request to add the firmware versions to the proper vehicle. Need help? Join discord.comma.ai.", + "severity": 0 + }, + "Offroad_Recalibration": { + "text": "sunnypilot detected a change in the device's mounting position. Ensure the device is fully seated in the mount and the mount is firmly secured to the windshield.", + "severity": 0 + }, + "Offroad_OSMUpdateRequired": { + "text": "OpenStreetMap database is out of date. New maps must be downloaded if you wish to continue using OpenStreetMap data for Enhanced Speed Control and road name display.\n\n%1", + "severity": 0 + }, + "Offroad_DriverMonitoringUncertain": { + "text": "Poor visibility detected for driver monitoring. Ensure the device has a clear view of the driver. This can be checked in the device settings. Extreme lighting conditions and/or unconventional mounting positions may also trigger this alert.", + "severity": 0 + }, + "Offroad_ExcessiveActuation": { + "text": "Excessive %1 actuation detected on your last drive. Please contact support at https://comma.ai/support and share your device's Dongle ID for troubleshooting.", + "severity": 1, + "_comment": "Set extra field to lateral or longitudinal." + }, + "Offroad_TiciSupport": { + "text": "Unsupported branch detected - The current version of %1 branch is no longer supported on the comma three. Please go to [Device > Software] and install a supported branch with -tici in the branch name for the comma three.", + "severity": 1, + "_comment": "Set extra field to the current branch name." + } +} diff --git a/openpilot/selfdrive/selfdrived/events.py b/openpilot/selfdrive/selfdrived/events.py new file mode 100755 index 0000000000..d7eaaf70c4 --- /dev/null +++ b/openpilot/selfdrive/selfdrived/events.py @@ -0,0 +1,961 @@ +#!/usr/bin/env python3 +import math +import os + +from openpilot.cereal import log +from opendbc.car.structs import car +import openpilot.cereal.messaging as messaging +from openpilot.common.constants import CV +from openpilot.common.git import get_short_branch +from openpilot.common.realtime import DT_CTRL +from openpilot.selfdrive.locationd.calibrationd import MIN_SPEED_FILTER +from openpilot.system.micd import SAMPLE_RATE, SAMPLE_BUFFER +from openpilot.selfdrive.ui.feedback.feedbackd import FEEDBACK_MAX_DURATION +from openpilot.common.hardware import HARDWARE + +from openpilot.sunnypilot.selfdrive.selfdrived.events_base import EventsBase, Priority, ET, Alert, \ + NoEntryAlert, SoftDisableAlert, UserSoftDisableAlert, ImmediateDisableAlert, EngagementAlert, NormalPermanentAlert, \ + StartupAlert, AlertCallbackType, wrong_car_mode_alert + + +AlertSize = log.SelfdriveState.AlertSize +AlertStatus = log.SelfdriveState.AlertStatus +VisualAlert = car.CarControl.HUDControl.VisualAlert +AudibleAlert = log.SelfdriveState.AudibleAlert +EventName = log.OnroadEvent.EventName + + +# get event name from enum +EVENT_NAME = {v: k for k, v in EventName.schema.enumerants.items()} + + +class Events(EventsBase): + def __init__(self): + super().__init__() + self.event_counters = dict.fromkeys(EVENTS.keys(), 0) + + def get_events_mapping(self) -> dict[int, dict[str, Alert | AlertCallbackType]]: + return EVENTS + + def get_event_name(self, event: int): + return EVENT_NAME[event] + + def get_event_msg_type(self): + return log.OnroadEvent + + + +# ********** helper functions ********** +def get_display_speed(speed_ms: float, metric: bool) -> str: + speed = int(round(speed_ms * (CV.MS_TO_KPH if metric else CV.MS_TO_MPH))) + unit = 'km/h' if metric else 'mph' + return f"{speed} {unit}" + + +# ********** alert callback functions ********** + + +def soft_disable_alert(alert_text_2: str) -> AlertCallbackType: + def func(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + if soft_disable_time < int(0.5 / DT_CTRL): + return ImmediateDisableAlert(alert_text_2) + return SoftDisableAlert(alert_text_2) + return func + +def user_soft_disable_alert(alert_text_2: str) -> AlertCallbackType: + def func(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + if soft_disable_time < int(0.5 / DT_CTRL): + return ImmediateDisableAlert(alert_text_2) + return UserSoftDisableAlert(alert_text_2) + return func + +def startup_master_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + branch = get_short_branch() # Ensure get_short_branch is cached to avoid lags on startup + if "REPLAY" in os.environ: + branch = "replay" + + return StartupAlert("WARNING: This branch is not tested", branch, alert_status=AlertStatus.userPrompt) + +def below_engage_speed_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + return NoEntryAlert(f"Drive above {get_display_speed(CP.minEnableSpeed, metric)} to engage") + + +def below_steer_speed_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + return Alert( + f"Steer Assist Unavailable Below {get_display_speed(CP.minSteerSpeed, metric)}", + "", + AlertStatus.userPrompt, AlertSize.small, + Priority.LOW, VisualAlert.none, AudibleAlert.prompt, 0.4) + + +def calibration_incomplete_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + first_word = 'Recalibrating' if sm['liveCalibration'].calStatus == log.LiveCalibrationData.Status.recalibrating else 'Calibrating' + return Alert( + f"{first_word}: {sm['liveCalibration'].calPerc:.0f}%", + f"Drive Above {get_display_speed(MIN_SPEED_FILTER, metric)}", + AlertStatus.normal, AlertSize.mid, + Priority.LOWEST, VisualAlert.none, AudibleAlert.none, .2) + + +def too_distracted_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + if sm['driverMonitoringState'].lockout: + mins_left = sm['driverMonitoringState'].lockoutMinutesRemaining + return NoEntryAlert("Too Distracted", f"{mins_left} minute{'s' if mins_left != 1 else ''} Left", priority=Priority.HIGH) + return NoEntryAlert("Pay Attention to Engage", priority=Priority.HIGH) + + +def audio_feedback_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + duration = FEEDBACK_MAX_DURATION - ((sm['audioFeedback'].blockNum + 1) * SAMPLE_BUFFER / SAMPLE_RATE) + return NormalPermanentAlert( + "Recording Audio Feedback", + f"{round(duration)} second{'s' if round(duration) != 1 else ''} remaining. Press again to save early.", + priority=Priority.LOW) + + +# *** debug alerts *** + +def out_of_space_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + full_perc = round(100. - sm['deviceState'].freeSpacePercent) + return NormalPermanentAlert("Out of Storage", f"{full_perc}% full") + + +def posenet_invalid_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + mdl = sm['modelV2'].velocity.x[0] if len(sm['modelV2'].velocity.x) else math.nan + err = CS.vEgo - mdl + msg = f"Speed Error: {err:.1f} m/s" + return NoEntryAlert(msg, alert_text_1="Posenet Speed Invalid") + + +def process_not_running_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + not_running = [p.name for p in sm['managerState'].processes if not p.running and p.shouldBeRunning] + msg = ', '.join(not_running) + return NoEntryAlert(msg, alert_text_1="Process Not Running") + + +def comm_issue_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + bs = [s for s in sm.data.keys() if not sm.all_checks([s, ])] + msg = ', '.join(bs[:4]) # can't fit too many on one line + return NoEntryAlert(msg, alert_text_1="Communication Issue Between Processes") + + +def camera_malfunction_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + all_cams = ('roadCameraState', 'driverCameraState', 'wideRoadCameraState') + bad_cams = [s.replace('State', '') for s in all_cams if s in sm.data.keys() and not sm.all_checks([s, ])] + return NormalPermanentAlert("Camera Malfunction", ', '.join(bad_cams)) + + +def calibration_invalid_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + rpy = sm['liveCalibration'].rpyCalib + yaw = math.degrees(rpy[2] if len(rpy) == 3 else math.nan) + pitch = math.degrees(rpy[1] if len(rpy) == 3 else math.nan) + angles = f"Remount Device (Pitch: {pitch:.1f}°, Yaw: {yaw:.1f}°)" + return NormalPermanentAlert("Calibration Invalid", angles) + + +def paramsd_invalid_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + if not sm['liveParameters'].angleOffsetValid: + angle_offset_deg = sm['liveParameters'].angleOffsetDeg + title = "Steering misalignment detected" + text = f"Angle offset too high (Offset: {angle_offset_deg:.1f}°)" + elif not sm['liveParameters'].steerRatioValid: + steer_ratio = sm['liveParameters'].steerRatio + title = "Steer ratio mismatch" + text = f"Steering rack geometry may be off (Ratio: {steer_ratio:.1f})" + elif not sm['liveParameters'].stiffnessFactorValid: + stiffness_factor = sm['liveParameters'].stiffnessFactor + title = "Abnormal tire stiffness" + text = f"Check tires, pressure, or alignment (Factor: {stiffness_factor:.1f})" + else: + return NoEntryAlert("paramsd Temporary Error") + + return NoEntryAlert(alert_text_1=title, alert_text_2=text) + +def overheat_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + cpu = max(sm['deviceState'].cpuTempC, default=0.) + gpu = max(sm['deviceState'].gpuTempC, default=0.) + temp = max((cpu, gpu, sm['deviceState'].memoryTempC)) + return NormalPermanentAlert("System Overheated", f"{temp:.0f} °C") + + +def low_memory_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + return NormalPermanentAlert("Low Memory", f"{sm['deviceState'].memoryUsagePercent}% used") + + +def high_cpu_usage_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + x = max(sm['deviceState'].cpuUsagePercent, default=0.) + return NormalPermanentAlert("High CPU Usage", f"{x}% used") + + +def modeld_lagging_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + return NormalPermanentAlert("Driving Model Lagging", f"{sm['modelV2'].frameDropPerc:.1f}% frames dropped") + + +def joystick_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + gb = sm['carControl'].actuators.accel / 4. + steer = sm['carControl'].actuators.torque + vals = f"Gas: {round(gb * 100.)}%, Steer: {round(steer * 100.)}%" + return NormalPermanentAlert("Joystick Mode", vals) + + +def longitudinal_maneuver_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + ad = sm['alertDebug'] + audible_alert = AudibleAlert.prompt if 'Active' in ad.alertText1 else AudibleAlert.none + alert_status = AlertStatus.userPrompt if 'Active' in ad.alertText1 else AlertStatus.normal + alert_size = AlertSize.mid if ad.alertText2 else AlertSize.small + return Alert(ad.alertText1, ad.alertText2, + alert_status, alert_size, + Priority.LOW, VisualAlert.none, audible_alert, 0.2) + + +def personality_changed_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + personality = str(personality).title() + return NormalPermanentAlert(f"Driving Personality: {personality}", duration=1.5) + + +def invalid_lkas_setting_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + text = "Toggle stock LKAS on or off to engage" + if CP.brand == "tesla": + text = "Switch to Traffic-Aware Cruise Control to engage" + elif CP.brand == "mazda": + text = "Enable your car's LKAS to engage" + elif CP.brand == "nissan": + text = "Disable your car's stock LKAS to engage" + return NormalPermanentAlert("Invalid LKAS setting", text) + + + +EVENTS: dict[int, dict[str, Alert | AlertCallbackType]] = { + # ********** events with no alerts ********** + + EventName.stockFcw: {}, + EventName.actuatorsApiUnavailable: {}, + + # ********** events only containing alerts displayed in all states ********** + + EventName.joystickDebug: { + ET.WARNING: joystick_alert, + ET.PERMANENT: NormalPermanentAlert("Joystick Mode"), + }, + + EventName.longitudinalManeuver: { + ET.WARNING: longitudinal_maneuver_alert, + ET.PERMANENT: NormalPermanentAlert("Longitudinal Maneuver Mode", + "Ensure road ahead is clear"), + }, + + EventName.lateralManeuver: { + ET.WARNING: longitudinal_maneuver_alert, + ET.PERMANENT: NormalPermanentAlert("Lateral Maneuver Mode"), + }, + + EventName.selfdriveInitializing: { + ET.NO_ENTRY: NoEntryAlert("System Initializing"), + }, + + EventName.startup: { + ET.PERMANENT: StartupAlert("Be ready to take over at any time") + }, + + EventName.startupMaster: { + ET.PERMANENT: startup_master_alert, + }, + + EventName.startupNoControl: { + ET.PERMANENT: StartupAlert("Dashcam mode"), + ET.NO_ENTRY: NoEntryAlert("Dashcam mode"), + }, + + EventName.startupNoCar: { + ET.PERMANENT: StartupAlert("Dashcam mode for unsupported car"), + }, + + EventName.startupNoSecOcKey: { + ET.PERMANENT: NormalPermanentAlert("Dashcam Mode", + "Security Key Not Available", + priority=Priority.HIGH), + }, + + EventName.dashcamMode: { + ET.PERMANENT: NormalPermanentAlert("Dashcam Mode", + priority=Priority.LOWEST), + }, + + EventName.invalidLkasSetting: { + ET.PERMANENT: invalid_lkas_setting_alert, + ET.NO_ENTRY: NoEntryAlert("Invalid LKAS setting"), + }, + + EventName.cruiseMismatch: { + #ET.PERMANENT: ImmediateDisableAlert("openpilot failed to cancel cruise"), + }, + + # openpilot doesn't recognize the car. This switches openpilot into a + # read-only mode. This can be solved by adding your fingerprint. + # See https://github.com/commaai/openpilot/wiki/Fingerprinting for more information + EventName.carUnrecognized: { + ET.PERMANENT: NormalPermanentAlert("Dashcam Mode", + "Car Unrecognized", + priority=Priority.LOWEST), + }, + + EventName.aeb: { + ET.PERMANENT: Alert( + "BRAKE!", + "Emergency Braking: Risk of Collision", + AlertStatus.critical, AlertSize.full, + Priority.HIGHEST, VisualAlert.fcw, AudibleAlert.none, 2.), + ET.NO_ENTRY: NoEntryAlert("AEB: Risk of Collision"), + }, + + EventName.stockAeb: { + ET.PERMANENT: Alert( + "BRAKE!", + "Stock AEB: Risk of Collision", + AlertStatus.critical, AlertSize.full, + Priority.HIGHEST, VisualAlert.fcw, AudibleAlert.none, 2.), + ET.NO_ENTRY: NoEntryAlert("Stock AEB: Risk of Collision"), + }, + + EventName.stockLkas: { + ET.NO_ENTRY: NoEntryAlert("Stock LKAS: Lane Departure Detected"), + }, + + EventName.fcw: { + ET.PERMANENT: Alert( + "BRAKE!", + "Risk of Collision", + AlertStatus.critical, AlertSize.full, + Priority.HIGHEST, VisualAlert.fcw, AudibleAlert.warningSoft, 2.), + }, + + EventName.ldw: { + ET.PERMANENT: Alert( + "Lane Departure Detected", + "", + AlertStatus.userPrompt, AlertSize.small, + Priority.LOW, VisualAlert.ldw, AudibleAlert.prompt, 3.), + }, + + # ********** events only containing alerts that display while engaged ********** + + EventName.steerTempUnavailableSilent: { + ET.WARNING: Alert( + "Steering Assist Temporarily Unavailable", + "", + AlertStatus.userPrompt, AlertSize.small, + Priority.LOW, VisualAlert.steerRequired, AudibleAlert.prompt, 1.8), + }, + + EventName.driverDistracted1: { + ET.PERMANENT: Alert( + "Pay Attention", + "", + AlertStatus.normal, AlertSize.small, + Priority.LOW, VisualAlert.none, AudibleAlert.preAlert, .1), + }, + + EventName.driverDistracted2: { + ET.PERMANENT: Alert( + "Pay Attention", + "Driver Distracted", + AlertStatus.userPrompt, AlertSize.mid, + Priority.MID, VisualAlert.steerRequired, AudibleAlert.promptDistracted, .1), + }, + + EventName.driverDistracted3: { + ET.PERMANENT: Alert( + "DISENGAGE IMMEDIATELY", + "Driver Distracted", + AlertStatus.critical, AlertSize.full, + Priority.HIGH, VisualAlert.steerRequired, AudibleAlert.warningImmediate, .1), + }, + + EventName.driverUnresponsive1: { + ET.PERMANENT: Alert( + "Touch Steering Wheel: No Face Detected", + "", + AlertStatus.normal, AlertSize.small, + Priority.LOW, VisualAlert.steerRequired, AudibleAlert.none, .1), + }, + + EventName.driverUnresponsive2: { + ET.PERMANENT: Alert( + "Touch Steering Wheel", + "Driver Unresponsive", + AlertStatus.userPrompt, AlertSize.mid, + Priority.MID, VisualAlert.steerRequired, AudibleAlert.promptDistracted, .1), + }, + + EventName.driverUnresponsive3: { + ET.PERMANENT: Alert( + "DISENGAGE IMMEDIATELY", + "Driver Unresponsive", + AlertStatus.critical, AlertSize.full, + Priority.HIGH, VisualAlert.steerRequired, AudibleAlert.warningImmediate, .1), + }, + + EventName.manualRestart: { + ET.WARNING: Alert( + "TAKE CONTROL", + "Resume Driving Manually", + AlertStatus.userPrompt, AlertSize.mid, + Priority.LOW, VisualAlert.none, AudibleAlert.none, .2), + }, + + EventName.resumeRequired: { + ET.WARNING: Alert( + "Press Resume to Exit Standstill", + "", + AlertStatus.userPrompt, AlertSize.small, + Priority.LOW, VisualAlert.none, AudibleAlert.none, .2), + }, + + EventName.belowSteerSpeed: { + ET.WARNING: below_steer_speed_alert, + }, + + EventName.preLaneChangeLeft: { + ET.WARNING: Alert( + "Steer Left to Start Lane Change Once Safe", + "", + AlertStatus.normal, AlertSize.small, + Priority.LOW, VisualAlert.none, AudibleAlert.none, .1), + }, + + EventName.preLaneChangeRight: { + ET.WARNING: Alert( + "Steer Right to Start Lane Change Once Safe", + "", + AlertStatus.normal, AlertSize.small, + Priority.LOW, VisualAlert.none, AudibleAlert.none, .1), + }, + + EventName.laneChangeBlocked: { + ET.WARNING: Alert( + "Car Detected in Blindspot", + "", + AlertStatus.userPrompt, AlertSize.small, + Priority.LOW, VisualAlert.none, AudibleAlert.prompt, .1), + }, + + EventName.laneChange: { + ET.WARNING: Alert( + "Changing Lanes", + "", + AlertStatus.normal, AlertSize.small, + Priority.LOW, VisualAlert.none, AudibleAlert.none, .1), + }, + + EventName.steerSaturated: { + ET.WARNING: Alert( + "Take Control", + "Turn Exceeds Steering Limit", + AlertStatus.userPrompt, AlertSize.mid, + Priority.LOW, VisualAlert.steerRequired, AudibleAlert.promptRepeat, 2.), + }, + + # Thrown when the fan is driven at >50% but is not rotating + EventName.fanMalfunction: { + ET.PERMANENT: NormalPermanentAlert("Fan Malfunction", "Likely Hardware Issue"), + }, + + # Camera is not outputting frames + EventName.cameraMalfunction: { + ET.PERMANENT: camera_malfunction_alert, + ET.SOFT_DISABLE: soft_disable_alert("Camera Malfunction"), + ET.NO_ENTRY: NoEntryAlert("Camera Malfunction: Reboot Your Device"), + }, + # Camera framerate too low + EventName.cameraFrameRate: { + ET.PERMANENT: NormalPermanentAlert("Camera Frame Rate Low", "Reboot your Device"), + ET.SOFT_DISABLE: soft_disable_alert("Camera Frame Rate Low"), + ET.NO_ENTRY: NoEntryAlert("Camera Frame Rate Low: Reboot Your Device"), + }, + + # Unused + + EventName.locationdTemporaryError: { + ET.NO_ENTRY: NoEntryAlert("locationd Temporary Error"), + ET.SOFT_DISABLE: soft_disable_alert("locationd Temporary Error"), + }, + + EventName.locationdPermanentError: { + ET.NO_ENTRY: NoEntryAlert("locationd Permanent Error"), + ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("locationd Permanent Error"), + ET.PERMANENT: NormalPermanentAlert("locationd Permanent Error"), + }, + + # openpilot tries to learn certain parameters about your car by observing + # how the car behaves to steering inputs from both human and openpilot driving. + # This includes: + # - steer ratio: gear ratio of the steering rack. Steering angle divided by tire angle + # - tire stiffness: how much grip your tires have + # - angle offset: most steering angle sensors are offset and measure a non zero angle when driving straight + # This alert is thrown when any of these values exceed a sanity check. This can be caused by + # bad alignment or bad sensor data. If this happens consistently consider creating an issue on GitHub + EventName.paramsdTemporaryError: { + ET.NO_ENTRY: paramsd_invalid_alert, + ET.SOFT_DISABLE: soft_disable_alert("paramsd Temporary Error"), + }, + + EventName.paramsdPermanentError: { + ET.NO_ENTRY: NoEntryAlert("paramsd Permanent Error"), + ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("paramsd Permanent Error"), + ET.PERMANENT: NormalPermanentAlert("paramsd Permanent Error"), + }, + + # ********** events that affect controls state transitions ********** + + EventName.pcmEnable: { + ET.ENABLE: EngagementAlert(AudibleAlert.engage), + }, + + EventName.buttonEnable: { + ET.ENABLE: EngagementAlert(AudibleAlert.engage), + }, + + EventName.pcmDisable: { + ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), + }, + + EventName.buttonCancel: { + ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), + ET.NO_ENTRY: NoEntryAlert("Cancel Pressed"), + }, + + EventName.brakeHold: { + ET.WARNING: Alert( + "Press Resume to Exit Brake Hold", + "", + AlertStatus.userPrompt, AlertSize.small, + Priority.LOW, VisualAlert.none, AudibleAlert.none, .2), + }, + + EventName.parkBrake: { + ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), + ET.NO_ENTRY: NoEntryAlert("Parking Brake Engaged"), + }, + + EventName.pedalPressed: { + ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), + ET.NO_ENTRY: NoEntryAlert("Pedal Pressed", + visual_alert=VisualAlert.brakePressed), + }, + + EventName.steerDisengage: { + ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), + ET.NO_ENTRY: NoEntryAlert("Steering Pressed"), + }, + + EventName.preEnableStandstill: { + ET.PRE_ENABLE: Alert( + "Release Brake to Engage", + "", + AlertStatus.normal, AlertSize.small, + Priority.LOWEST, VisualAlert.none, AudibleAlert.none, .1, creation_delay=1.), + }, + + EventName.gasPressedOverride: { + ET.OVERRIDE_LONGITUDINAL: Alert( + "", + "", + AlertStatus.normal, AlertSize.none, + Priority.LOWEST, VisualAlert.none, AudibleAlert.none, .1), + }, + + EventName.steerOverride: { + ET.OVERRIDE_LATERAL: Alert( + "", + "", + AlertStatus.normal, AlertSize.none, + Priority.LOWEST, VisualAlert.none, AudibleAlert.none, .1), + }, + + EventName.wrongCarMode: { + ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), + ET.NO_ENTRY: wrong_car_mode_alert, + }, + + EventName.resumeBlocked: { + ET.NO_ENTRY: NoEntryAlert("Press Set to Engage"), + }, + + EventName.wrongCruiseMode: { + ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), + ET.NO_ENTRY: NoEntryAlert("Adaptive Cruise Disabled"), + }, + + EventName.steerTempUnavailable: { + ET.SOFT_DISABLE: soft_disable_alert("Steering Assist Temporarily Unavailable"), + ET.NO_ENTRY: NoEntryAlert("Steering Temporarily Unavailable"), + }, + + EventName.steerTimeLimit: { + ET.SOFT_DISABLE: soft_disable_alert("Vehicle Steering Time Limit"), + ET.NO_ENTRY: NoEntryAlert("Vehicle Steering Time Limit"), + }, + + EventName.outOfSpace: { + ET.PERMANENT: out_of_space_alert, + ET.NO_ENTRY: NoEntryAlert("Out of Storage"), + }, + + EventName.belowEngageSpeed: { + ET.NO_ENTRY: below_engage_speed_alert, + }, + + EventName.sensorDataInvalid: { + ET.PERMANENT: Alert( + "Sensor Data Invalid", + "Possible Hardware Issue", + AlertStatus.normal, AlertSize.mid, + Priority.LOWER, VisualAlert.none, AudibleAlert.none, .2, creation_delay=1.), + ET.NO_ENTRY: NoEntryAlert("Sensor Data Invalid"), + ET.SOFT_DISABLE: soft_disable_alert("Sensor Data Invalid"), + }, + + EventName.noGps: { + }, + + EventName.tooDistracted: { + ET.NO_ENTRY: too_distracted_alert, + }, + + EventName.excessiveActuation: { + ET.SOFT_DISABLE: soft_disable_alert("Excessive Actuation"), + ET.NO_ENTRY: NoEntryAlert("Excessive Actuation"), + }, + + EventName.overheat: { + ET.PERMANENT: overheat_alert, + ET.SOFT_DISABLE: soft_disable_alert("System Overheated"), + ET.NO_ENTRY: NoEntryAlert("System Overheated"), + }, + + EventName.wrongGear: { + ET.SOFT_DISABLE: user_soft_disable_alert("Gear not D"), + ET.NO_ENTRY: NoEntryAlert("Gear not D"), + }, + + # This alert is thrown when the calibration angles are outside of the acceptable range. + # For example if the device is pointed too much to the left or the right. + # Usually this can only be solved by removing the mount from the windshield completely, + # and attaching while making sure the device is pointed straight forward and is level. + # See https://comma.ai/setup for more information + EventName.calibrationInvalid: { + ET.PERMANENT: calibration_invalid_alert, + ET.SOFT_DISABLE: soft_disable_alert("Calibration Invalid: Remount Device & Recalibrate"), + ET.NO_ENTRY: NoEntryAlert("Calibration Invalid: Remount Device & Recalibrate"), + }, + + EventName.calibrationIncomplete: { + ET.PERMANENT: calibration_incomplete_alert, + ET.SOFT_DISABLE: soft_disable_alert("Calibration Incomplete"), + ET.NO_ENTRY: NoEntryAlert("Calibration in Progress"), + }, + + EventName.calibrationRecalibrating: { + ET.PERMANENT: calibration_incomplete_alert, + ET.SOFT_DISABLE: soft_disable_alert("Device Remount Detected: Recalibrating"), + ET.NO_ENTRY: NoEntryAlert("Remount Detected: Recalibrating"), + }, + + EventName.doorOpen: { + ET.SOFT_DISABLE: user_soft_disable_alert("Door Open"), + ET.NO_ENTRY: NoEntryAlert("Door Open"), + }, + + EventName.seatbeltNotLatched: { + ET.SOFT_DISABLE: user_soft_disable_alert("Seatbelt Unlatched"), + ET.NO_ENTRY: NoEntryAlert("Seatbelt Unlatched"), + }, + + EventName.espDisabled: { + ET.SOFT_DISABLE: soft_disable_alert("Electronic Stability Control Disabled"), + ET.NO_ENTRY: NoEntryAlert("Electronic Stability Control Disabled"), + }, + + EventName.lowBattery: { + ET.SOFT_DISABLE: soft_disable_alert("Low Battery"), + ET.NO_ENTRY: NoEntryAlert("Low Battery"), + }, + + # Different openpilot services communicate between each other at a certain + # interval. If communication does not follow the regular schedule this alert + # is thrown. This can mean a service crashed, did not broadcast a message for + # ten times the regular interval, or the average interval is more than 10% too high. + EventName.commIssue: { + ET.SOFT_DISABLE: soft_disable_alert("Communication Issue Between Processes"), + ET.NO_ENTRY: comm_issue_alert, + }, + EventName.commIssueAvgFreq: { + ET.SOFT_DISABLE: soft_disable_alert("Low Communication Rate Between Processes"), + ET.NO_ENTRY: NoEntryAlert("Low Communication Rate Between Processes"), + }, + + EventName.selfdrivedLagging: { + ET.SOFT_DISABLE: soft_disable_alert("System Lagging"), + ET.NO_ENTRY: NoEntryAlert("Selfdrive Process Lagging: Reboot Your Device"), + }, + + # Thrown when manager detects a service exited unexpectedly while driving + EventName.processNotRunning: { + ET.NO_ENTRY: process_not_running_alert, + ET.SOFT_DISABLE: soft_disable_alert("Process Not Running"), + }, + + EventName.radarFault: { + ET.SOFT_DISABLE: soft_disable_alert("Radar Error: Restart the Car"), + ET.NO_ENTRY: NoEntryAlert("Radar Error: Restart the Car"), + }, + + EventName.radarTempUnavailable: { + ET.SOFT_DISABLE: soft_disable_alert("Radar Temporarily Unavailable"), + ET.NO_ENTRY: NoEntryAlert("Radar Temporarily Unavailable"), + }, + + # Every frame from the camera should be processed by the model. If modeld + # is not processing frames fast enough they have to be dropped. This alert is + # thrown when over 20% of frames are dropped. + EventName.modeldLagging: { + ET.SOFT_DISABLE: soft_disable_alert("Driving Model Lagging"), + ET.NO_ENTRY: NoEntryAlert("Driving Model Lagging"), + ET.PERMANENT: modeld_lagging_alert, + }, + + # Besides predicting the path, lane lines and lead car data the model also + # predicts the current velocity and rotation speed of the car. If the model is + # very uncertain about the current velocity while the car is moving, this + # usually means the model has trouble understanding the scene. This is used + # as a heuristic to warn the driver. + EventName.posenetInvalid: { + ET.SOFT_DISABLE: soft_disable_alert("Posenet Speed Invalid"), + ET.NO_ENTRY: posenet_invalid_alert, + }, + + # When the localizer detects an acceleration of more than 40 m/s^2 (~4G) we + # alert the driver the device might have fallen from the windshield. + EventName.deviceFalling: { + ET.SOFT_DISABLE: soft_disable_alert("Device Fell Off Mount"), + ET.NO_ENTRY: NoEntryAlert("Device Fell Off Mount"), + }, + + EventName.lowMemory: { + ET.SOFT_DISABLE: soft_disable_alert("Low Memory: Reboot Your Device"), + ET.PERMANENT: low_memory_alert, + ET.NO_ENTRY: NoEntryAlert("Low Memory: Reboot Your Device"), + }, + + EventName.accFaulted: { + ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("Cruise Fault: Restart the Car"), + ET.PERMANENT: NormalPermanentAlert("Cruise Fault: Restart the car to engage"), + ET.NO_ENTRY: NoEntryAlert("Cruise Fault: Restart the Car"), + }, + + EventName.espActive: { + ET.SOFT_DISABLE: soft_disable_alert("Electronic Stability Control Active"), + ET.NO_ENTRY: NoEntryAlert("Electronic Stability Control Active"), + }, + + EventName.controlsMismatch: { + ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("Controls Mismatch"), + ET.NO_ENTRY: NoEntryAlert("Controls Mismatch"), + }, + + # Sometimes the USB stack on the device can get into a bad state + # causing the connection to the panda to be lost + EventName.usbError: { + ET.SOFT_DISABLE: soft_disable_alert("USB Error: Reboot Your Device"), + ET.PERMANENT: NormalPermanentAlert("USB Error: Reboot Your Device"), + ET.NO_ENTRY: NoEntryAlert("USB Error: Reboot Your Device"), + }, + + # This alert can be thrown for the following reasons: + # - No CAN data received at all + # - CAN data is received, but some message are not received at the right frequency + # If you're not writing a new car port, this is usually cause by faulty wiring + EventName.canError: { + ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("Unknown Vehicle Variant"), + ET.PERMANENT: Alert( + "Unknown Vehicle Variant", + "", + AlertStatus.normal, AlertSize.small, + Priority.LOW, VisualAlert.none, AudibleAlert.none, 1., creation_delay=1.), + ET.NO_ENTRY: NoEntryAlert("Unknown Vehicle Variant"), + }, + + EventName.canBusMissing: { + ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("CAN Bus Disconnected"), + ET.PERMANENT: Alert( + "CAN Bus Disconnected: Likely Faulty Cable", + "", + AlertStatus.normal, AlertSize.small, + Priority.LOW, VisualAlert.none, AudibleAlert.none, 1., creation_delay=1.), + ET.NO_ENTRY: NoEntryAlert("CAN Bus Disconnected: Check Connections"), + }, + + EventName.steerUnavailable: { + ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("LKAS Fault: Restart the Car"), + ET.PERMANENT: NormalPermanentAlert("LKAS Fault: Restart the car to engage"), + ET.NO_ENTRY: NoEntryAlert("LKAS Fault: Restart the Car"), + }, + + EventName.reverseGear: { + ET.PERMANENT: Alert( + "Reverse\nGear", + "", + AlertStatus.normal, AlertSize.full, + Priority.LOWEST, VisualAlert.none, AudibleAlert.none, .2, creation_delay=0.5), + ET.USER_DISABLE: ImmediateDisableAlert("Reverse Gear"), + ET.NO_ENTRY: NoEntryAlert("Reverse Gear"), + }, + + # On cars that use stock ACC the car can decide to cancel ACC for various reasons. + # When this happens we can no long control the car so the user needs to be warned immediately. + EventName.cruiseDisabled: { + ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("Cruise Is Off"), + }, + + # When the relay in the harness box opens the CAN bus between the LKAS camera + # and the rest of the car is separated. When messages from the LKAS camera + # are received on the car side this usually means the relay hasn't opened correctly + # and this alert is thrown. + EventName.relayMalfunction: { + ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("Harness Relay Malfunction"), + ET.PERMANENT: NormalPermanentAlert("Harness Relay Malfunction", "Check Hardware"), + ET.NO_ENTRY: NoEntryAlert("Harness Relay Malfunction"), + }, + + EventName.speedTooLow: { + ET.IMMEDIATE_DISABLE: Alert( + "openpilot Canceled", + "Speed too low", + AlertStatus.normal, AlertSize.mid, + Priority.HIGH, VisualAlert.none, AudibleAlert.disengage, 3.), + }, + + # When the car is driving faster than most cars in the training data, the model outputs can be unpredictable. + EventName.speedTooHigh: { + ET.WARNING: Alert( + "Speed Too High", + "Model uncertain at this speed", + AlertStatus.userPrompt, AlertSize.mid, + Priority.HIGH, VisualAlert.steerRequired, AudibleAlert.promptRepeat, 4.), + ET.NO_ENTRY: NoEntryAlert("Slow down to engage"), + }, + + EventName.vehicleSensorsInvalid: { + ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("Vehicle Sensors Invalid"), + ET.PERMANENT: NormalPermanentAlert("Vehicle Sensors Calibrating", "Drive to Calibrate"), + ET.NO_ENTRY: NoEntryAlert("Vehicle Sensors Calibrating"), + }, + + EventName.personalityChanged: { + ET.WARNING: personality_changed_alert, + }, + + EventName.userBookmark: { + ET.PERMANENT: NormalPermanentAlert("Bookmark Saved", duration=1.5), + }, + + EventName.audioFeedback: { + ET.PERMANENT: audio_feedback_alert, + }, +} + + +if HARDWARE.get_device_type() == 'mici': + EVENTS.update({ + EventName.driverDistracted1: { + ET.PERMANENT: Alert( + "Pay Attention", + "", + AlertStatus.normal, AlertSize.small, + Priority.LOW, VisualAlert.none, AudibleAlert.preAlert, 2), + }, + EventName.driverDistracted2: { + ET.PERMANENT: Alert( + "Pay Attention", + "Driver Distracted", + AlertStatus.userPrompt, AlertSize.mid, + Priority.MID, VisualAlert.steerRequired, AudibleAlert.promptDistracted, 1), + }, + EventName.resumeRequired: { + ET.WARNING: Alert( + "Press Resume", + "", + AlertStatus.userPrompt, AlertSize.small, + Priority.LOW, VisualAlert.none, AudibleAlert.none, .2), + }, + EventName.preLaneChangeLeft: { + ET.WARNING: Alert( + "Steer Left", + "Confirm Lane Change", + AlertStatus.normal, AlertSize.mid, + Priority.LOW, VisualAlert.none, AudibleAlert.none, .1), + }, + EventName.preLaneChangeRight: { + ET.WARNING: Alert( + "Steer Right", + "Confirm Lane Change", + AlertStatus.normal, AlertSize.mid, + Priority.LOW, VisualAlert.none, AudibleAlert.none, .1), + }, + EventName.laneChangeBlocked: { + ET.WARNING: Alert( + "Car in Blindspot", + "", + AlertStatus.userPrompt, AlertSize.small, + Priority.LOW, VisualAlert.none, AudibleAlert.prompt, .1), + }, + EventName.steerSaturated: { + ET.WARNING: Alert( + "take control", + "turn exceeds limit", + AlertStatus.userPrompt, AlertSize.mid, + Priority.LOW, VisualAlert.steerRequired, AudibleAlert.promptRepeat, 2.), + }, + EventName.calibrationIncomplete: { + ET.PERMANENT: calibration_incomplete_alert, + ET.SOFT_DISABLE: soft_disable_alert("Calibration Incomplete"), + ET.NO_ENTRY: NoEntryAlert("Calibrating"), + }, + EventName.reverseGear: { + ET.PERMANENT: Alert( + "Reverse", + "", + AlertStatus.normal, AlertSize.full, + Priority.LOWEST, VisualAlert.none, AudibleAlert.none, .2, creation_delay=0.5), + ET.USER_DISABLE: ImmediateDisableAlert("Reverse"), + ET.NO_ENTRY: NoEntryAlert("Reverse"), + }, + }) + + +if __name__ == '__main__': + # print all alerts by type and priority + from openpilot.cereal.services import SERVICE_LIST + from collections import defaultdict + + event_names = {v: k for k, v in EventName.schema.enumerants.items()} + alerts_by_type: dict[str, dict[Priority, list[str]]] = defaultdict(lambda: defaultdict(list)) + + CP = car.CarParams.new_message() + CS = car.CarState.new_message() + sm = messaging.SubMaster(list(SERVICE_LIST.keys())) + + for i, alerts in EVENTS.items(): + for et, alert in alerts.items(): + if not isinstance(alert, Alert): + alert = alert(CP, CS, sm, False, 1, log.LongitudinalPersonality.standard) + alerts_by_type[et][alert.priority].append(event_names[i]) + + all_alerts: dict[str, list[tuple[Priority, list[str]]]] = {} + for et, priority_alerts in alerts_by_type.items(): + all_alerts[et] = sorted(priority_alerts.items(), key=lambda x: x[0], reverse=True) + + for status, evs in sorted(all_alerts.items(), key=lambda x: x[0]): + print(f"**** {status} ****") + for p, alert_list in evs: + print(f" {repr(p)}:") + print(" ", ', '.join(alert_list), "\n") diff --git a/openpilot/selfdrive/selfdrived/helpers.py b/openpilot/selfdrive/selfdrived/helpers.py new file mode 100644 index 0000000000..3b3c44ecaf --- /dev/null +++ b/openpilot/selfdrive/selfdrived/helpers.py @@ -0,0 +1,55 @@ +import math +from enum import StrEnum, auto + +from openpilot.cereal import messaging +from opendbc.car.structs import car +from openpilot.common.realtime import DT_CTRL +from openpilot.selfdrive.locationd.helpers import Pose +from opendbc.car import ACCELERATION_DUE_TO_GRAVITY +from opendbc.car.lateral import ISO_LATERAL_ACCEL +from opendbc.car.interfaces import ACCEL_MIN, ACCEL_MAX + +MIN_EXCESSIVE_ACTUATION_COUNT = int(0.25 / DT_CTRL) +MIN_LATERAL_ENGAGE_BUFFER = int(1 / DT_CTRL) + + +class ExcessiveActuationType(StrEnum): + LONGITUDINAL = auto() + LATERAL = auto() + + +class ExcessiveActuationCheck: + def __init__(self): + self._excessive_counter = 0 + self._engaged_counter = 0 + + def update(self, sm: messaging.SubMaster, CS: car.CarState, calibrated_pose: Pose) -> ExcessiveActuationType | None: + # CS.aEgo can be noisy to bumps in the road, transitioning from standstill, losing traction, etc. + # longitudinal + accel_calibrated = calibrated_pose.acceleration.x + excessive_long_actuation = sm['carControl'].longActive and (accel_calibrated > ACCEL_MAX * 2 or accel_calibrated < ACCEL_MIN * 2) + + # lateral + yaw_rate = calibrated_pose.angular_velocity.yaw + roll = sm['liveParameters'].roll + roll_compensated_lateral_accel = (CS.vEgo * yaw_rate) - (math.sin(roll) * ACCELERATION_DUE_TO_GRAVITY) + + # Prevent false positives after overriding + excessive_lat_actuation = False + self._engaged_counter = self._engaged_counter + 1 if sm['carControl'].latActive and not CS.steeringPressed else 0 + if self._engaged_counter > MIN_LATERAL_ENGAGE_BUFFER: + if abs(roll_compensated_lateral_accel) > ISO_LATERAL_ACCEL * 2: + excessive_lat_actuation = True + + # livePose acceleration can be noisy due to bad mounting or aliased livePose measurements + livepose_valid = abs(CS.aEgo - accel_calibrated) < 2 + self._excessive_counter = self._excessive_counter + 1 if livepose_valid and (excessive_long_actuation or excessive_lat_actuation) else 0 + + excessive_type = None + if self._excessive_counter > MIN_EXCESSIVE_ACTUATION_COUNT: + if excessive_long_actuation: + excessive_type = ExcessiveActuationType.LONGITUDINAL + else: + excessive_type = ExcessiveActuationType.LATERAL + + return excessive_type diff --git a/selfdrive/selfdrived/selfdrived.py b/openpilot/selfdrive/selfdrived/selfdrived.py similarity index 78% rename from selfdrive/selfdrived/selfdrived.py rename to openpilot/selfdrive/selfdrived/selfdrived.py index dfda2c31f7..2edc0bce18 100755 --- a/selfdrive/selfdrived/selfdrived.py +++ b/openpilot/selfdrive/selfdrived/selfdrived.py @@ -3,9 +3,10 @@ import os import time import threading -import cereal.messaging as messaging +import openpilot.cereal.messaging as messaging -from cereal import car, log, custom +from openpilot.cereal import log, custom +from opendbc.car.structs import car from msgq.visionipc import VisionIpcClient, VisionStreamType @@ -15,21 +16,26 @@ from openpilot.common.swaglog import cloudlog from openpilot.common.gps import get_gps_location_service from openpilot.selfdrive.car.car_specific import CarSpecificEvents +from openpilot.selfdrive.locationd.helpers import PoseCalibrator, Pose from openpilot.selfdrive.selfdrived.events import Events, ET +from openpilot.selfdrive.selfdrived.helpers import ExcessiveActuationCheck from openpilot.selfdrive.selfdrived.state import StateMachine from openpilot.selfdrive.selfdrived.alertmanager import AlertManager, set_offroad_alert -from openpilot.system.hardware import HARDWARE -from openpilot.system.version import get_build_metadata +from openpilot.common.version import get_build_metadata +from openpilot.common.hardware import HARDWARE from openpilot.sunnypilot.mads.mads import ModularAssistiveDrivingSystem +from openpilot.sunnypilot import get_sanitize_int_param from openpilot.sunnypilot.selfdrive.car.car_specific import CarSpecificEventsSP from openpilot.sunnypilot.selfdrive.car.cruise_helpers import CruiseHelper +from openpilot.sunnypilot.selfdrive.car.intelligent_cruise_button_management.controller import IntelligentCruiseButtonManagement from openpilot.sunnypilot.selfdrive.selfdrived.events import EventsSP REPLAY = "REPLAY" in os.environ SIMULATION = "SIMULATION" in os.environ TESTING_CLOSET = "TESTING_CLOSET" in os.environ + LONGITUDINAL_PERSONALITY_MAP = {v: k for k, v in log.LongitudinalPersonality.schema.enumerants.items()} ThermalStatus = log.DeviceState.ThermalStatus @@ -40,6 +46,9 @@ LaneChangeDirection = log.LaneChangeDirection EventName = log.OnroadEvent.EventName ButtonType = car.CarState.ButtonEvent.Type SafetyModel = car.CarParams.SafetyModel +AlertLevel = log.DriverMonitoringState.AlertLevel +MonitoringPolicy = log.DriverMonitoringState.MonitoringPolicy +TurnDirection = custom.ModelDataV2SP.TurnDirection IGNORED_SAFETY_MODES = (SafetyModel.silent, SafetyModel.noOutput) @@ -67,6 +76,11 @@ class SelfdriveD(CruiseHelper): self.car_events = CarSpecificEvents(self.CP) + self.pose_calibrator = PoseCalibrator() + self.calibrated_pose: Pose | None = None + self.excessive_actuation_check = ExcessiveActuationCheck() + self.excessive_actuation = self.params.get("Offroad_ExcessiveActuation") is not None + # Setup sockets self.pm = messaging.PubMaster(['selfdriveState', 'onroadEvents'] + ['selfdriveStateSP', 'onroadEventsSP']) @@ -78,7 +92,7 @@ class SelfdriveD(CruiseHelper): # TODO: de-couple selfdrived with card/conflate on carState without introducing controls mismatches self.car_state_sock = messaging.sub_sock('carState', timeout=20) - ignore = self.sensor_packets + self.gps_packets + ['alertDebug'] + ignore = self.sensor_packets + self.gps_packets + ['alertDebug', 'lateralManeuverPlan'] + ['modelDataV2SP'] if SIMULATION: ignore += ['driverCameraState', 'managerState'] if REPLAY: @@ -87,7 +101,8 @@ class SelfdriveD(CruiseHelper): self.sm = messaging.SubMaster(['deviceState', 'pandaStates', 'peripheralState', 'modelV2', 'liveCalibration', 'carOutput', 'driverMonitoringState', 'longitudinalPlan', 'livePose', 'liveDelay', 'managerState', 'liveParameters', 'radarState', 'liveTorqueParameters', - 'controlsState', 'carControl', 'driverAssistance', 'alertDebug', 'userFlag'] + \ + 'controlsState', 'carControl', 'driverAssistance', 'alertDebug', 'userBookmark', 'audioFeedback', + 'lateralManeuverPlan', 'modelDataV2SP', 'longitudinalPlanSP'] + \ self.camera_packets + self.sensor_packets + self.gps_packets, ignore_alive=ignore, ignore_avg_freq=ignore, ignore_valid=ignore, frequency=int(1/DT_CTRL)) @@ -121,21 +136,25 @@ class SelfdriveD(CruiseHelper): self.logged_comm_issue = None self.not_running_prev = None self.experimental_mode = False - self.personality = self.read_personality_param() + self.personality = get_sanitize_int_param( + "LongitudinalPersonality", + min(log.LongitudinalPersonality.schema.enumerants.values()), + max(log.LongitudinalPersonality.schema.enumerants.values()), + self.params + ) self.recalibrating_seen = False + self.dm_lockout_set = False + self.dm_uncertain_alerted = False self.state_machine = StateMachine() self.rk = Ratekeeper(100, print_delay_threshold=None) - # some comma three with NVMe experience NVMe dropouts mid-drive that - # cause loggerd to crash on write, so ignore it only on that platform - self.ignored_processes = set() - nvme_expected = os.path.exists('/dev/nvme0n1') or (not os.path.isfile("/persist/comma/living-in-the-moment")) - if HARDWARE.get_device_type() == 'tici' and nvme_expected: - self.ignored_processes = {'loggerd', } - self.ignored_processes.update({'mapd'}) + self.ignored_processes = {'mapd', } # Determine startup event - self.startup_event = EventName.startup if build_metadata.openpilot.comma_remote and build_metadata.tested_channel else EventName.startupMaster + is_remote = build_metadata.openpilot.comma_remote or build_metadata.openpilot.sunnypilot_remote + self.startup_event = EventName.startup if is_remote and build_metadata.tested_channel else EventName.startupMaster + if HARDWARE.get_device_type() == 'mici': + self.startup_event = None if not car_recognized: self.startup_event = EventName.startupNoCar elif car_recognized and self.CP.passive: @@ -153,8 +172,9 @@ class SelfdriveD(CruiseHelper): self.events_sp_prev = [] self.mads = ModularAssistiveDrivingSystem(self) + self.icbm = IntelligentCruiseButtonManagement(self.CP, self.CP_SP) - self.car_events_sp = CarSpecificEventsSP(self.CP, self.params) + self.car_events_sp = CarSpecificEventsSP(self.CP, self.CP_SP) CruiseHelper.__init__(self, self.CP) @@ -168,7 +188,10 @@ class SelfdriveD(CruiseHelper): self.events.add(EventName.joystickDebug) self.startup_event = None - if self.sm.recv_frame['alertDebug'] > 0: + if self.sm.recv_frame['lateralManeuverPlan'] > 0: + self.events.add(EventName.lateralManeuver) + self.startup_event = None + elif self.sm.recv_frame['alertDebug'] > 0: self.events.add(EventName.longitudinalManeuver) self.startup_event = None @@ -182,9 +205,12 @@ class SelfdriveD(CruiseHelper): self.events.add(EventName.selfdriveInitializing) return - # Check for user flag (bookmark) press - if self.sm.updated['userFlag']: - self.events.add(EventName.userFlag) + # Check for user bookmark press (bookmark button or end of LKAS button feedback) + if self.sm.updated['userBookmark']: + self.events.add(EventName.userBookmark) + + if self.sm.updated['audioFeedback']: + self.events.add(EventName.audioFeedback) # Don't add any more events while in dashcam mode if self.CP.passive: @@ -195,8 +221,31 @@ class SelfdriveD(CruiseHelper): if not self.CP.pcmCruise and CS.vCruise > 250 and resume_pressed: self.events.add(EventName.resumeBlocked) + # Handle DM if not self.CP.notCar: - self.events.add_from_msg(self.sm['driverMonitoringState'].events) + # Block engaging until lockout times out or ignition reset + if self.sm['driverMonitoringState'].lockout and not self.dm_lockout_set: + self.params.put_bool("DriverTooDistracted", True) + self.dm_lockout_set = True + elif not self.sm['driverMonitoringState'].lockout and self.dm_lockout_set: + self.params.remove("DriverTooDistracted") + self.dm_lockout_set = False + # No entry conditions + if self.sm['driverMonitoringState'].lockout or self.sm['driverMonitoringState'].alwaysOnLockout: + self.events.add(EventName.tooDistracted) + # Alerts + vision_dm = self.sm['driverMonitoringState'].activePolicy == MonitoringPolicy.vision + if self.sm['driverMonitoringState'].alertLevel == AlertLevel.one: + self.events.add(EventName.driverDistracted1 if vision_dm else EventName.driverUnresponsive1) + elif self.sm['driverMonitoringState'].alertLevel == AlertLevel.two: + self.events.add(EventName.driverDistracted2 if vision_dm else EventName.driverUnresponsive2) + elif self.sm['driverMonitoringState'].alertLevel == AlertLevel.three: + self.events.add(EventName.driverDistracted3 if vision_dm else EventName.driverUnresponsive3) + # Warn consistent DM uncertainty + if self.sm['driverMonitoringState'].visionPolicyState.uncertainOffroadAlertPercent >= 100 and not self.dm_uncertain_alerted: + set_offroad_alert("Offroad_DriverMonitoringUncertain", True) + self.dm_uncertain_alerted = True + self.events_sp.add_from_msg(self.sm['longitudinalPlanSP'].events) # Add car events, ignore if CAN isn't valid if CS.canValid: @@ -208,7 +257,7 @@ class SelfdriveD(CruiseHelper): if self.CP.notCar: # wait for everything to init first - if self.sm.frame > int(5. / DT_CTRL) and self.initialized: + if self.sm.frame > int(2. / DT_CTRL) and self.initialized: # body always wants to enable self.events.add(EventName.pcmEnable) @@ -219,7 +268,7 @@ class SelfdriveD(CruiseHelper): self.events.add(EventName.pedalPressed) # Create events for temperature, disk space, and memory - if self.sm['deviceState'].thermalStatus >= ThermalStatus.red: + if self.sm['deviceState'].thermalStatus >= ThermalStatus.overheated: self.events.add(EventName.overheat) if self.sm['deviceState'].freeSpacePercent < 7 and not SIMULATION: self.events.add(EventName.outOfSpace) @@ -253,6 +302,26 @@ class SelfdriveD(CruiseHelper): if self.sm['driverAssistance'].leftLaneDeparture or self.sm['driverAssistance'].rightLaneDeparture: self.events.add(EventName.ldw) + # ****************************************************************************************** + # NOTE: To fork maintainers. + # Disabling or nerfing safety features will get you and your users banned from our servers. + # We recommend that you do not change these numbers from the defaults. + if self.sm.updated['liveCalibration']: + self.pose_calibrator.feed_live_calib(self.sm['liveCalibration']) + if self.sm.updated['livePose']: + device_pose = Pose.from_live_pose(self.sm['livePose']) + self.calibrated_pose = self.pose_calibrator.build_calibrated_pose(device_pose) + + if self.calibrated_pose is not None: + excessive_actuation = self.excessive_actuation_check.update(self.sm, CS, self.calibrated_pose) + if not self.excessive_actuation and excessive_actuation is not None: + set_offroad_alert("Offroad_ExcessiveActuation", True, extra_text=str(excessive_actuation)) + self.excessive_actuation = True + + if self.excessive_actuation: + self.events.add(EventName.excessiveActuation) + # ****************************************************************************************** + # Handle lane change if self.sm['modelV2'].meta.laneChangeState == LaneChangeState.preLaneChange: direction = self.sm['modelV2'].meta.laneChangeDirection @@ -268,6 +337,13 @@ class SelfdriveD(CruiseHelper): LaneChangeState.laneChangeFinishing): self.events.add(EventName.laneChange) + # Handle lane turn + lane_turn_direction = self.sm['modelDataV2SP'].laneTurnDirection + if lane_turn_direction == TurnDirection.turnLeft: + self.events_sp.add(custom.OnroadEventSP.EventName.laneTurnLeft) + elif lane_turn_direction == TurnDirection.turnRight: + self.events_sp.add(custom.OnroadEventSP.EventName.laneTurnRight) + for i, pandaState in enumerate(self.sm['pandaStates']): # All pandas must match the list of safetyConfigs, and if outside this list, must be silent or noOutput if i < len(self.CP.safetyConfigs): @@ -304,12 +380,12 @@ class SelfdriveD(CruiseHelper): self.events.add(EventName.cameraFrameRate) if not REPLAY and self.rk.lagging: self.events.add(EventName.selfdrivedLagging) - if not self.sm.valid['radarState']: + if self.CP.openpilotLongitudinalControl: if self.sm['radarState'].radarErrors.canError: self.events.add(EventName.canError) elif self.sm['radarState'].radarErrors.radarUnavailableTemporary: self.events.add(EventName.radarTempUnavailable) - else: + elif any(self.sm['radarState'].radarErrors.to_dict().values()): self.events.add(EventName.radarFault) if not self.sm.valid['pandaStates']: self.events.add(EventName.usbError) @@ -392,7 +468,7 @@ class SelfdriveD(CruiseHelper): # TODO: fix simulator if not SIMULATION or REPLAY: - if self.sm['modelV2'].frameDropPerc > 20: + if self.sm['modelV2'].frameDropPerc > 1: self.events.add(EventName.modeldLagging) # mute canBusMissing event if in Park, as it sometimes may trigger a false alarm with MADS in Paused state @@ -406,13 +482,15 @@ class SelfdriveD(CruiseHelper): if any(not be.pressed and be.type == ButtonType.gapAdjustCruise for be in CS.buttonEvents): if not self.experimental_mode_switched: self.personality = (self.personality - 1) % 3 - self.params.put_nonblocking('LongitudinalPersonality', str(self.personality)) + self.params.put('LongitudinalPersonality', self.personality) self.events.add(EventName.personalityChanged) self.experimental_mode_switched = False + self.icbm.run(CS, self.sm['carControl'], self.sm['longitudinalPlanSP'], self.is_metric) + def data_sample(self): - car_state = messaging.recv_one(self.car_state_sock) - CS = car_state.carState if car_state else self.CS_prev + _car_state = messaging.recv_one(self.car_state_sock) + CS = _car_state.carState if _car_state else self.CS_prev self.sm.update(0) @@ -514,6 +592,11 @@ class SelfdriveD(CruiseHelper): mads.active = self.mads.active mads.available = self.mads.enabled_toggle + icbm = ss_sp.intelligentCruiseButtonManagement + icbm.state = self.icbm.state + icbm.sendButton = self.icbm.cruise_button + icbm.vTarget = self.icbm.v_target + self.pm.send('selfdriveStateSP', ss_sp_msg) # onroadEventsSP - logged every second or on change @@ -537,19 +620,13 @@ class SelfdriveD(CruiseHelper): self.CS_prev = CS - def read_personality_param(self): - try: - return int(self.params.get('LongitudinalPersonality')) - except (ValueError, TypeError): - return log.LongitudinalPersonality.standard - def params_thread(self, evt): while not evt.is_set(): self.is_metric = self.params.get_bool("IsMetric") self.is_ldw_enabled = self.params.get_bool("IsLdwEnabled") self.disengage_on_accelerator = self.params.get_bool("DisengageOnAccelerator") self.experimental_mode = self.params.get_bool("ExperimentalMode") and self.CP.openpilotLongitudinalControl - self.personality = self.read_personality_param() + self.personality = self.params.get("LongitudinalPersonality", return_default=True) self.mads.read_params() time.sleep(0.1) diff --git a/openpilot/selfdrive/selfdrived/state.py b/openpilot/selfdrive/selfdrived/state.py new file mode 100644 index 0000000000..eca0019503 --- /dev/null +++ b/openpilot/selfdrive/selfdrived/state.py @@ -0,0 +1,98 @@ +from openpilot.cereal import log +from openpilot.selfdrive.selfdrived.events import Events, ET +from openpilot.common.realtime import DT_CTRL + +State = log.SelfdriveState.OpenpilotState + +SOFT_DISABLE_TIME = 3 # seconds +ACTIVE_STATES = (State.enabled, State.softDisabling, State.overriding) +ENABLED_STATES = (State.preEnabled, *ACTIVE_STATES) + +class StateMachine: + def __init__(self): + self.current_alert_types = [ET.PERMANENT] + self.state = State.disabled + self.soft_disable_timer = 0 + + def update(self, events: Events): + # decrement the soft disable timer at every step, as it's reset on + # entrance in SOFT_DISABLING state + self.soft_disable_timer = max(0, self.soft_disable_timer - 1) + + self.current_alert_types = [ET.PERMANENT] + + # ENABLED, SOFT DISABLING, PRE ENABLING, OVERRIDING + if self.state != State.disabled: + # user and immediate disable always have priority in a non-disabled state + if events.contains(ET.IMMEDIATE_DISABLE): + self.state = State.disabled + self.current_alert_types.append(ET.IMMEDIATE_DISABLE) + + elif events.contains(ET.USER_DISABLE): + self.state = State.disabled + self.current_alert_types.append(ET.USER_DISABLE) + + else: + # ENABLED + if self.state == State.enabled: + if events.contains(ET.SOFT_DISABLE): + self.state = State.softDisabling + self.soft_disable_timer = int(SOFT_DISABLE_TIME / DT_CTRL) + self.current_alert_types.append(ET.SOFT_DISABLE) + + elif events.contains(ET.OVERRIDE_LATERAL) or events.contains(ET.OVERRIDE_LONGITUDINAL): + self.state = State.overriding + self.current_alert_types += [ET.OVERRIDE_LATERAL, ET.OVERRIDE_LONGITUDINAL] + + # SOFT DISABLING + elif self.state == State.softDisabling: + if not events.contains(ET.SOFT_DISABLE): + # no more soft disabling condition, so go back to ENABLED + self.state = State.enabled + + elif self.soft_disable_timer > 0: + self.current_alert_types.append(ET.SOFT_DISABLE) + + elif self.soft_disable_timer <= 0: + self.state = State.disabled + + # PRE ENABLING + elif self.state == State.preEnabled: + if not events.contains(ET.PRE_ENABLE): + self.state = State.enabled + else: + self.current_alert_types.append(ET.PRE_ENABLE) + + # OVERRIDING + elif self.state == State.overriding: + if events.contains(ET.SOFT_DISABLE): + self.state = State.softDisabling + self.soft_disable_timer = int(SOFT_DISABLE_TIME / DT_CTRL) + self.current_alert_types.append(ET.SOFT_DISABLE) + elif not (events.contains(ET.OVERRIDE_LATERAL) or events.contains(ET.OVERRIDE_LONGITUDINAL)): + self.state = State.enabled + else: + self.current_alert_types += [ET.OVERRIDE_LATERAL, ET.OVERRIDE_LONGITUDINAL] + + # DISABLED + elif self.state == State.disabled: + if events.contains(ET.ENABLE): + if events.contains(ET.NO_ENTRY): + self.current_alert_types.append(ET.NO_ENTRY) + + else: + if events.contains(ET.PRE_ENABLE): + self.state = State.preEnabled + elif events.contains(ET.OVERRIDE_LATERAL) or events.contains(ET.OVERRIDE_LONGITUDINAL): + self.state = State.overriding + else: + self.state = State.enabled + self.current_alert_types.append(ET.ENABLE) + + # Check if openpilot is engaged and actuators are enabled + enabled = self.state in ENABLED_STATES + active = self.state in ACTIVE_STATES + if active: + self.current_alert_types.append(ET.WARNING) + return enabled, active + diff --git a/selfdrive/selfdrived/tests/test_alertmanager.py b/openpilot/selfdrive/selfdrived/tests/test_alertmanager.py similarity index 100% rename from selfdrive/selfdrived/tests/test_alertmanager.py rename to openpilot/selfdrive/selfdrived/tests/test_alertmanager.py diff --git a/selfdrive/selfdrived/tests/test_alerts.py b/openpilot/selfdrive/selfdrived/tests/test_alerts.py similarity index 89% rename from selfdrive/selfdrived/tests/test_alerts.py rename to openpilot/selfdrive/selfdrived/tests/test_alerts.py index 75365b7a52..0210c138da 100644 --- a/selfdrive/selfdrived/tests/test_alerts.py +++ b/openpilot/selfdrive/selfdrived/tests/test_alerts.py @@ -4,8 +4,9 @@ import os import random from PIL import Image, ImageDraw, ImageFont -from cereal import log, car -from cereal.messaging import SubMaster +from openpilot.cereal import log +from opendbc.car.structs import car +from openpilot.cereal.messaging import SubMaster from openpilot.common.basedir import BASEDIR from openpilot.common.params import Params from openpilot.selfdrive.selfdrived.events import Alert, EVENTS, ET @@ -14,7 +15,7 @@ from openpilot.selfdrive.test.process_replay.process_replay import CONFIGS AlertSize = log.SelfdriveState.AlertSize -OFFROAD_ALERTS_PATH = os.path.join(BASEDIR, "selfdrive/selfdrived/alerts_offroad.json") +OFFROAD_ALERTS_PATH = os.path.join(BASEDIR, "openpilot/selfdrive/selfdrived/alerts_offroad.json") # TODO: add callback alerts ALERTS = [] @@ -47,7 +48,7 @@ class TestAlerts: # ensure alert text doesn't exceed allowed width def test_alert_text_length(self): - font_path = os.path.join(BASEDIR, "selfdrive/assets/fonts") + font_path = os.path.join(BASEDIR, "openpilot/selfdrive/assets/fonts") regular_font_path = os.path.join(font_path, "Inter-SemiBold.ttf") bold_font_path = os.path.join(font_path, "Inter-Bold.ttf") semibold_font_path = os.path.join(font_path, "Inter-SemiBold.ttf") @@ -63,7 +64,7 @@ class TestAlerts: for alert in ALERTS: if not isinstance(alert, Alert): - alert = alert(self.CP, self.CS, self.sm, metric=False, soft_disable_time=100, personality=log.LongitudinalPersonality.standard) + alert = alert(self.CP, self.CS, self.sm, False, 100, log.LongitudinalPersonality.standard) # for full size alerts, both text fields wrap the text, # so it's unlikely that they would go past the max width @@ -111,7 +112,7 @@ class TestAlerts: alert = copy.copy(self.offroad_alerts[a]) set_offroad_alert(a, True) alert['extra'] = '' - assert json.dumps(alert) == params.get(a, encoding='utf8') + assert alert == params.get(a) # then delete it set_offroad_alert(a, False) @@ -125,6 +126,6 @@ class TestAlerts: alert = self.offroad_alerts[a] set_offroad_alert(a, True, extra_text="a"*i) - written_alert = json.loads(params.get(a, encoding='utf8')) + written_alert = params.get(a) assert "a"*i == written_alert['extra'] assert alert["text"] == written_alert['text'] diff --git a/selfdrive/selfdrived/tests/test_state_machine.py b/openpilot/selfdrive/selfdrived/tests/test_state_machine.py similarity index 95% rename from selfdrive/selfdrived/tests/test_state_machine.py rename to openpilot/selfdrive/selfdrived/tests/test_state_machine.py index b720f48f1e..ec8f068039 100644 --- a/selfdrive/selfdrived/tests/test_state_machine.py +++ b/openpilot/selfdrive/selfdrived/tests/test_state_machine.py @@ -1,4 +1,4 @@ -from cereal import log +from openpilot.cereal import log from openpilot.common.realtime import DT_CTRL from openpilot.selfdrive.selfdrived.state import StateMachine, SOFT_DISABLE_TIME from openpilot.selfdrive.selfdrived.events import Events, ET, EVENTS, NormalPermanentAlert @@ -13,11 +13,11 @@ ALL_STATES = tuple(State.schema.enumerants.values()) ENABLE_EVENT_TYPES = (ET.ENABLE, ET.PRE_ENABLE, ET.OVERRIDE_LATERAL, ET.OVERRIDE_LONGITUDINAL) -def make_event(event_types): - event = {} +def make_event(event_types: list[str | None]): + EVENTS[0] = {} for ev in event_types: - event[ev] = NormalPermanentAlert("alert") - EVENTS[0] = event + if ev is not None: + EVENTS[0][ev] = NormalPermanentAlert("alert") return 0 diff --git a/openpilot/selfdrive/test/.gitignore b/openpilot/selfdrive/test/.gitignore new file mode 100644 index 0000000000..377696afae --- /dev/null +++ b/openpilot/selfdrive/test/.gitignore @@ -0,0 +1,8 @@ +out/ + +process_replay/diff.txt +process_replay/model_diff.txt +process_replay/fakedata/ +valgrind_logs.txt + +*.hevc diff --git a/selfdrive/modeld/models/__init__.py b/openpilot/selfdrive/test/__init__.py similarity index 100% rename from selfdrive/modeld/models/__init__.py rename to openpilot/selfdrive/test/__init__.py diff --git a/selfdrive/test/cpp_harness.py b/openpilot/selfdrive/test/cpp_harness.py similarity index 100% rename from selfdrive/test/cpp_harness.py rename to openpilot/selfdrive/test/cpp_harness.py diff --git a/selfdrive/test/fuzzy_generation.py b/openpilot/selfdrive/test/fuzzy_generation.py similarity index 92% rename from selfdrive/test/fuzzy_generation.py rename to openpilot/selfdrive/test/fuzzy_generation.py index 94eb0dfaa6..c97221ae9e 100644 --- a/selfdrive/test/fuzzy_generation.py +++ b/openpilot/selfdrive/test/fuzzy_generation.py @@ -4,7 +4,7 @@ from typing import Any from collections.abc import Callable from functools import cache -from cereal import log +from openpilot.cereal import log DrawType = Callable[[st.SearchStrategy], Any] @@ -44,10 +44,10 @@ class FuzzyGenerator: except capnp.lib.capnp.KjException: return self.generate_struct(field.schema) - def generate_struct(self, schema: capnp.lib.capnp._StructSchema, event: str = None) -> st.SearchStrategy[dict[str, Any]]: + def generate_struct(self, schema: capnp.lib.capnp._StructSchema, event: str | None = None) -> st.SearchStrategy[dict[str, Any]]: single_fill: tuple[str, ...] = (event,) if event else (self.draw(st.sampled_from(schema.union_fields)),) if schema.union_fields else () - fields_to_generate = schema.non_union_fields + single_fill - return st.fixed_dictionaries({field: self.generate_field(schema.fields[field]) for field in fields_to_generate if not field.endswith('DEPRECATED')}) + fields_to_generate = [f for f in schema.non_union_fields + single_fill if not f.endswith('DEPRECATED') and f != 'deprecated'] + return st.fixed_dictionaries({field: self.generate_field(schema.fields[field]) for field in fields_to_generate}) @staticmethod @cache diff --git a/openpilot/selfdrive/test/helpers.py b/openpilot/selfdrive/test/helpers.py new file mode 100644 index 0000000000..9d954216b8 --- /dev/null +++ b/openpilot/selfdrive/test/helpers.py @@ -0,0 +1,165 @@ +import contextlib +import http.server +import os +import threading +import time +import pytest + +from functools import wraps + +import openpilot.cereal.messaging as messaging +from openpilot.common.params import Params +from openpilot.system.manager.process_config import managed_processes +from openpilot.common.version import training_version, terms_version + + +def set_params_enabled(): + os.environ['FINGERPRINT'] = "TOYOTA_COROLLA_TSS2" + os.environ['LOGPRINT'] = "debug" + + params = Params() + params.put("HasAcceptedTerms", terms_version, block=True) + params.put("CompletedTrainingVersion", training_version, block=True) + params.put_bool("OpenpilotEnabledToggle", True, block=True) + + # valid calib + msg = messaging.new_message('liveCalibration') + msg.liveCalibration.validBlocks = 20 + msg.liveCalibration.rpyCalib = [0.0, 0.0, 0.0] + params.put("CalibrationParams", msg.to_bytes(), block=True) + +def release_only(f): + @wraps(f) + def wrap(self, *args, **kwargs): + if "RELEASE" not in os.environ: + pytest.skip("This test is only for release branches") + f(self, *args, **kwargs) + return wrap + + +def collect_logs(services, duration): + socks = [messaging.sub_sock(s, conflate=False, timeout=100) for s in services] + logs = [] + start = time.monotonic() + while time.monotonic() - start < duration: + for s in socks: + logs.extend(messaging.drain_sock(s)) + return logs + + +@contextlib.contextmanager +def log_collector(services): + """Background thread that continuously drains messages from services. + Use when the main thread needs to do blocking work (e.g. capturing images).""" + socks = [messaging.sub_sock(s, conflate=False, timeout=100) for s in services] + raw_logs = [] + lock = threading.Lock() + stop_event = threading.Event() + + def _drain(): + while not stop_event.is_set(): + for s in socks: + msgs = messaging.drain_sock(s) + if msgs: + with lock: + raw_logs.extend(msgs) + time.sleep(0.01) + + thread = threading.Thread(target=_drain, daemon=True) + thread.start() + try: + yield raw_logs, lock + finally: + stop_event.set() + thread.join(timeout=2) + + +@contextlib.contextmanager +def processes_context(processes, init_time=0, ignore_stopped=None): + ignore_stopped = [] if ignore_stopped is None else ignore_stopped + + # start and assert started + for n, p in enumerate(processes): + managed_processes[p].start() + if n < len(processes) - 1: + time.sleep(init_time) + + assert all(managed_processes[name].proc.exitcode is None for name in processes) + + try: + yield [managed_processes[name] for name in processes] + # assert processes are still started + assert all(managed_processes[name].proc.exitcode is None for name in processes if name not in ignore_stopped) + finally: + for p in processes: + managed_processes[p].stop() + + +def with_processes(processes, init_time=0, ignore_stopped=None): + def wrapper(func): + @wraps(func) + def wrap(*args, **kwargs): + with processes_context(processes, init_time, ignore_stopped): + return func(*args, **kwargs) + + return wrap + return wrapper + + +def noop(*args, **kwargs): + pass + + +def read_segment_list(segment_list_path): + with open(segment_list_path) as f: + seg_list = f.read().splitlines() + + return [(platform[2:], segment) for platform, segment in zip(seg_list[::2], seg_list[1::2], strict=True)] + + +@contextlib.contextmanager +def http_server_context(handler, setup=None): + host = '127.0.0.1' + server = http.server.HTTPServer((host, 0), handler) + port = server.server_port + t = threading.Thread(target=server.serve_forever) + t.start() + + if setup is not None: + setup(host, port) + + try: + yield (host, port) + finally: + server.shutdown() + server.server_close() + t.join() + + +def with_http_server(func, handler=http.server.BaseHTTPRequestHandler, setup=None): + @wraps(func) + def inner(*args, **kwargs): + with http_server_context(handler, setup) as (host, port): + return func(*args, f"http://{host}:{port}", **kwargs) + return inner + + +def DirectoryHttpServer(directory) -> type[http.server.SimpleHTTPRequestHandler]: + # creates an http server that serves files from directory + class Handler(http.server.SimpleHTTPRequestHandler): + API_NO_RESPONSE = False + API_BAD_RESPONSE = False + + def do_GET(self): + if self.API_NO_RESPONSE: + return + + if self.API_BAD_RESPONSE: + self.send_response(500, "") + return + super().do_GET() + + def __init__(self, *args, **kwargs): + super().__init__(*args, directory=str(directory), **kwargs) + + return Handler diff --git a/selfdrive/test/longitudinal_maneuvers/.gitignore b/openpilot/selfdrive/test/longitudinal_maneuvers/.gitignore similarity index 100% rename from selfdrive/test/longitudinal_maneuvers/.gitignore rename to openpilot/selfdrive/test/longitudinal_maneuvers/.gitignore diff --git a/selfdrive/modeld/tests/__init__.py b/openpilot/selfdrive/test/longitudinal_maneuvers/__init__.py similarity index 100% rename from selfdrive/modeld/tests/__init__.py rename to openpilot/selfdrive/test/longitudinal_maneuvers/__init__.py diff --git a/selfdrive/test/longitudinal_maneuvers/maneuver.py b/openpilot/selfdrive/test/longitudinal_maneuvers/maneuver.py similarity index 97% rename from selfdrive/test/longitudinal_maneuvers/maneuver.py rename to openpilot/selfdrive/test/longitudinal_maneuvers/maneuver.py index dfd5b3e109..ba0379f2d7 100644 --- a/selfdrive/test/longitudinal_maneuvers/maneuver.py +++ b/openpilot/selfdrive/test/longitudinal_maneuvers/maneuver.py @@ -60,7 +60,8 @@ class Maneuver: log['distance_lead'], log['speed'], speed_lead, - log['acceleration']])) + log['acceleration'], + log['d_rel']])) if d_rel < .4 and (self.only_radar or prob_lead > 0.5): print("Crashed!!!!") diff --git a/selfdrive/test/longitudinal_maneuvers/plant.py b/openpilot/selfdrive/test/longitudinal_maneuvers/plant.py similarity index 89% rename from selfdrive/test/longitudinal_maneuvers/plant.py rename to openpilot/selfdrive/test/longitudinal_maneuvers/plant.py index b8c6adb436..abbd6be1d6 100755 --- a/selfdrive/test/longitudinal_maneuvers/plant.py +++ b/openpilot/selfdrive/test/longitudinal_maneuvers/plant.py @@ -2,8 +2,8 @@ import time import numpy as np -from cereal import log -import cereal.messaging as messaging +from openpilot.cereal import log +import openpilot.cereal.messaging as messaging from openpilot.common.realtime import Ratekeeper, DT_MDL from openpilot.selfdrive.controls.lib.longcontrol import LongCtrlState from openpilot.selfdrive.modeld.constants import ModelConstants @@ -51,7 +51,9 @@ class Plant: from opendbc.car.honda.values import CAR from opendbc.car.honda.interface import CarInterface - self.planner = LongitudinalPlanner(CarInterface.get_non_essential_params(CAR.HONDA_CIVIC), init_v=self.speed) + CP = CarInterface.get_non_essential_params(CAR.HONDA_CIVIC) + CP_SP = CarInterface.get_non_essential_params_sp(CP, CAR.HONDA_CIVIC) + self.planner = LongitudinalPlanner(CP, CP_SP, init_v=self.speed) @property def current_time(self): @@ -67,6 +69,9 @@ class Plant: lp = messaging.new_message('liveParameters') car_control = messaging.new_message('carControl') model = messaging.new_message('modelV2') + car_state_sp = messaging.new_message('carStateSP') + live_map_data_sp = messaging.new_message('liveMapDataSP') + gps_data = messaging.new_message('gpsLocation') a_lead = (v_lead - self.v_lead_prev)/self.ts self.v_lead_prev = v_lead @@ -89,14 +94,14 @@ class Plant: lead.dRel = float(d_rel) lead.yRel = 0.0 lead.vRel = float(v_rel) - lead.aRel = float(a_lead - self.acceleration) lead.vLead = float(v_lead) lead.vLeadK = float(v_lead) lead.aLeadK = float(a_lead) # TODO use real radard logic for this lead.aLeadTau = float(_LEAD_ACCEL_TAU) - lead.status = status + lead.present = status lead.modelProb = float(prob_lead) + lead.radar = True if not self.only_lead2: radar.radarState.leadOne = lead radar.radarState.leadTwo = lead @@ -133,9 +138,14 @@ class Plant: 'controlsState': control.controlsState, 'selfdriveState': ss.selfdriveState, 'liveParameters': lp.liveParameters, - 'modelV2': model.modelV2} + 'modelV2': model.modelV2, + 'carStateSP': car_state_sp.carStateSP, + 'liveMapDataSP': live_map_data_sp.liveMapDataSP, + 'gpsLocation': gps_data.gpsLocation} self.planner.update(sm) self.acceleration = self.planner.output_a_target + if self.planner.output_should_stop: + self.acceleration = min(-0.5, self.acceleration) self.speed = self.speed + self.acceleration * self.ts self.should_stop = self.planner.output_should_stop fcw = self.planner.fcw diff --git a/selfdrive/test/longitudinal_maneuvers/test_longitudinal.py b/openpilot/selfdrive/test/longitudinal_maneuvers/test_longitudinal.py similarity index 98% rename from selfdrive/test/longitudinal_maneuvers/test_longitudinal.py rename to openpilot/selfdrive/test/longitudinal_maneuvers/test_longitudinal.py index ab1800b4fb..b8f97c5041 100644 --- a/selfdrive/test/longitudinal_maneuvers/test_longitudinal.py +++ b/openpilot/selfdrive/test/longitudinal_maneuvers/test_longitudinal.py @@ -1,5 +1,5 @@ import itertools -from parameterized import parameterized_class +from openpilot.common.parameterized import parameterized_class from openpilot.selfdrive.controls.lib.longitudinal_mpc_lib.long_mpc import STOP_DISTANCE from openpilot.selfdrive.test.longitudinal_maneuvers.maneuver import Maneuver @@ -170,7 +170,7 @@ def create_maneuvers(kwargs): initial_speed=0., lead_relevancy=True, initial_distance_lead=STOP_DISTANCE, - speed_lead_values=[0., 0., 2.], + speed_lead_values=[0., 0., 7.], breakpoints=[1., 10., 15.], ensure_start=True, **kwargs, diff --git a/openpilot/selfdrive/test/mem_usage.py b/openpilot/selfdrive/test/mem_usage.py new file mode 100644 index 0000000000..02b7934466 --- /dev/null +++ b/openpilot/selfdrive/test/mem_usage.py @@ -0,0 +1,209 @@ +import os +from collections import defaultdict + +import numpy as np + +from openpilot.common.utils import tabulate + +DEMO_ROUTE = "5beb9b58bd12b691/0000010a--a51155e496" +MB = 1024 * 1024 +TABULATE_OPTS = {"tablefmt": "simple_grid", "stralign": "center", "numalign": "center"} + + +def _get_procs(): + from openpilot.selfdrive.test.test_onroad import PROCS + return PROCS + + +def is_openpilot_proc(name): + if any(p in name for p in _get_procs()): + return True + # catch openpilot processes not in PROCS (athenad, manager, etc.) + return 'openpilot' in name or name.startswith(('selfdrive.', 'system.')) + + +def get_proc_name(proc): + if len(proc.cmdline) > 0: + return list(proc.cmdline)[0] + return proc.name + + +def pct(val_mb, total_mb): + return val_mb / total_mb * 100 if total_mb else 0 + + +def has_pss(proc_logs): + """Check if logs contain PSS data (new field, not in old logs).""" + try: + for proc in proc_logs[-1].procLog.procs: + if proc.memPss > 0: + return True + except AttributeError: + pass + return False + + +def print_summary(proc_logs, device_states): + mem = proc_logs[-1].procLog.mem + total = mem.total / MB + used = (mem.total - mem.available) / MB + cached = mem.cached / MB + shared = mem.shared / MB + buffers = mem.buffers / MB + + lines = [ + f" Total: {total:.0f} MB", + f" Used (total-avail): {used:.0f} MB ({pct(used, total):.0f}%)", + f" Cached: {cached:.0f} MB ({pct(cached, total):.0f}%) Buffers: {buffers:.0f} MB ({pct(buffers, total):.0f}%)", + f" Shared/MSGQ: {shared:.0f} MB ({pct(shared, total):.0f}%)", + ] + + if device_states: + mem_pcts = [m.deviceState.memoryUsagePercent for m in device_states] + lines.append(f" deviceState memory: {np.min(mem_pcts)}-{np.max(mem_pcts)}% (avg {np.mean(mem_pcts):.0f}%)") + + print("\n-- Memory Summary --") + print("\n".join(lines)) + return total + + +def collect_per_process_mem(proc_logs, use_pss): + """Collect per-process memory samples. Returns {name: {metric: [values_per_sample_in_MB]}}.""" + by_proc = defaultdict(lambda: defaultdict(list)) + + for msg in proc_logs: + sample = defaultdict(lambda: defaultdict(float)) + for proc in msg.procLog.procs: + name = get_proc_name(proc) + sample[name]['rss'] += proc.memRss / MB + if use_pss: + sample[name]['pss'] += proc.memPss / MB + sample[name]['pss_anon'] += proc.memPssAnon / MB + sample[name]['pss_shmem'] += proc.memPssShmem / MB + + for name, metrics in sample.items(): + for metric, val in metrics.items(): + by_proc[name][metric].append(val) + + return by_proc + + +def _has_pss_detail(by_proc) -> bool: + """Check if any process has non-zero pss_anon/pss_shmem (unavailable on some kernels).""" + return any(sum(v.get('pss_anon', [])) > 0 or sum(v.get('pss_shmem', [])) > 0 for v in by_proc.values()) + + +def process_table_rows(by_proc, total_mb, use_pss, show_detail): + """Build table rows. Returns (rows, total_row).""" + mem_key = 'pss' if use_pss else 'rss' + rows = [] + for name in sorted(by_proc, key=lambda n: np.mean(by_proc[n][mem_key]), reverse=True): + m = by_proc[name] + vals = m[mem_key] + avg = round(np.mean(vals)) + row = [name, f"{avg} MB", f"{round(np.max(vals))} MB", f"{round(pct(avg, total_mb), 1)}%"] + if show_detail: + row.append(f"{round(np.mean(m['pss_anon']))} MB") + row.append(f"{round(np.mean(m['pss_shmem']))} MB") + rows.append(row) + + # Total row + total_row = None + if by_proc: + max_samples = max(len(v[mem_key]) for v in by_proc.values()) + totals = [] + for i in range(max_samples): + s = sum(v[mem_key][i] for v in by_proc.values() if i < len(v[mem_key])) + totals.append(s) + avg_total = round(np.mean(totals)) + total_row = ["TOTAL", f"{avg_total} MB", f"{round(np.max(totals))} MB", f"{round(pct(avg_total, total_mb), 1)}%"] + if show_detail: + total_row.append(f"{round(sum(np.mean(v['pss_anon']) for v in by_proc.values()))} MB") + total_row.append(f"{round(sum(np.mean(v['pss_shmem']) for v in by_proc.values()))} MB") + + return rows, total_row + + +def print_process_tables(op_procs, other_procs, total_mb, use_pss): + all_procs = {**op_procs, **other_procs} + show_detail = use_pss and _has_pss_detail(all_procs) + + header = ["process", "avg", "max", "%"] + if show_detail: + header += ["anon", "shmem"] + + op_rows, op_total = process_table_rows(op_procs, total_mb, use_pss, show_detail) + # filter other: >5MB avg and not bare interpreter paths (test infra noise) + other_filtered = {n: v for n, v in other_procs.items() + if np.mean(v['pss' if use_pss else 'rss']) > 5.0 + and os.path.basename(n.split()[0]) not in ('python', 'python3')} + other_rows, other_total = process_table_rows(other_filtered, total_mb, use_pss, show_detail) + + rows = op_rows + if op_total: + rows.append(op_total) + if other_rows: + sep_width = len(header) + rows.append([""] * sep_width) + rows.extend(other_rows) + if other_total: + other_total[0] = "TOTAL (other)" + rows.append(other_total) + + metric = "PSS (no shared double-count)" if use_pss else "RSS (includes shared, overcounts)" + print(f"\n-- Per-Process Memory: {metric} --") + print(tabulate(rows, header, **TABULATE_OPTS)) + + +def print_memory_accounting(proc_logs, op_procs, other_procs, total_mb, use_pss): + last = proc_logs[-1].procLog.mem + used = (last.total - last.available) / MB + shared = last.shared / MB + cached_buf = (last.buffers + last.cached) / MB - shared # shared (MSGQ) is in Cached; separate it + msgq = shared + + mem_key = 'pss' if use_pss else 'rss' + op_total = sum(v[mem_key][-1] for v in op_procs.values()) if op_procs else 0 + other_total = sum(v[mem_key][-1] for v in other_procs.values()) if other_procs else 0 + proc_sum = op_total + other_total + remainder = used - (cached_buf + msgq) - proc_sum + + if not use_pss: + # RSS double-counts shared; add back once to partially correct + remainder += shared + + header = ["", "MB", "%", ""] + label = "PSS" if use_pss else "RSS*" + rows = [ + ["Used (total - avail)", f"{used:.0f}", f"{pct(used, total_mb):.1f}", "memory in use by the system"], + [" Cached + Buffers", f"{cached_buf:.0f}", f"{pct(cached_buf, total_mb):.1f}", "pagecache + fs metadata, reclaimable"], + [" MSGQ (shared)", f"{msgq:.0f}", f"{pct(msgq, total_mb):.1f}", "/dev/shm tmpfs, also in process PSS"], + [f" openpilot {label}", f"{op_total:.0f}", f"{pct(op_total, total_mb):.1f}", "sum of openpilot process memory"], + [f" other {label}", f"{other_total:.0f}", f"{pct(other_total, total_mb):.1f}", "sum of non-openpilot process memory"], + [" kernel/ION/GPU", f"{remainder:.0f}", f"{pct(remainder, total_mb):.1f}", "slab, ION/DMA-BUF, GPU, page tables"], + ] + note = "" if use_pss else " (*RSS overcounts shared mem)" + print(f"\n-- Memory Accounting (last sample){note} --") + print(tabulate(rows, header, tablefmt="simple_grid", stralign="right")) + + +def print_report(proc_logs, device_states=None): + """Print full memory analysis report. Can be called from tests or CLI.""" + if not proc_logs: + print("No procLog messages found") + return + + print(f"{len(proc_logs)} procLog samples, {len(device_states or [])} deviceState samples") + + use_pss = has_pss(proc_logs) + if not use_pss: + print(" (no PSS data — re-record with updated proclogd for accurate numbers)") + + total_mb = print_summary(proc_logs, device_states or []) + + by_proc = collect_per_process_mem(proc_logs, use_pss) + op_procs = {n: v for n, v in by_proc.items() if is_openpilot_proc(n)} + other_procs = {n: v for n, v in by_proc.items() if not is_openpilot_proc(n)} + + print_process_tables(op_procs, other_procs, total_mb, use_pss) + print_memory_accounting(proc_logs, op_procs, other_procs, total_mb, use_pss) diff --git a/openpilot/selfdrive/test/process_replay/README.md b/openpilot/selfdrive/test/process_replay/README.md new file mode 100644 index 0000000000..28f3b7cd2a --- /dev/null +++ b/openpilot/selfdrive/test/process_replay/README.md @@ -0,0 +1,125 @@ +# Process replay + +Process replay is a regression test designed to identify any changes in the output of a process. This test replays a segment through individual processes and compares the output to a known good replay. Each make is represented in the test with a segment. + +If the test fails, make sure that you didn't unintentionally change anything. If there are intentional changes, the reference logs will be updated. + +Use `test_processes.py` to run the test locally. +Log files are cached by default. Use `DISABLE_FILEREADER_CACHE='1' test_processes.py` to disable caching. + +Currently the following processes are tested: + +* controlsd +* radard +* plannerd +* calibrationd +* dmonitoringd +* locationd +* paramsd +* ubloxd +* torqued + +### Usage +``` +Usage: test_processes.py [-h] [--whitelist-procs PROCS] [--whitelist-cars CARS] [--blacklist-procs PROCS] + [--blacklist-cars CARS] [--ignore-fields FIELDS] [--ignore-msgs MSGS] [--update-refs] +Regression test to identify changes in a process's output +optional arguments: + -h, --help show this help message and exit + --whitelist-procs PROCS Whitelist given processes from the test (e.g. controlsd) + --whitelist-cars WHITELIST_CARS Whitelist given cars from the test (e.g. HONDA) + --blacklist-procs BLACKLIST_PROCS Blacklist given processes from the test (e.g. controlsd) + --blacklist-cars BLACKLIST_CARS Blacklist given cars from the test (e.g. HONDA) + --ignore-fields IGNORE_FIELDS Extra fields or msgs to ignore (e.g. driverMonitoringState.events) + --ignore-msgs IGNORE_MSGS Msgs to ignore (e.g. onroadEvents) + --update-refs Updates reference logs using current commit +``` + +## Forks + +openpilot forks can use this test with their own reference logs, by default `test_proccesses.py` saves logs locally. + +To generate new logs: + +`./test_processes.py` + +Then, check in the new logs using git-lfs. Make sure to also update the `ref_commit` file to the current commit. + +## API + +Process replay test suite exposes programmatic APIs for simultaneously running processes or groups of processes on provided logs. + +```py +def replay_process_with_name(name: Union[str, Iterable[str]], lr: LogIterable, *args, **kwargs) -> List[capnp._DynamicStructReader]: + +def replay_process( + cfg: Union[ProcessConfig, Iterable[ProcessConfig]], lr: LogIterable, frs: Optional[Dict[str, Any]] = None, + fingerprint: Optional[str] = None, return_all_logs: bool = False, custom_params: Optional[Dict[str, Any]] = None, disable_progress: bool = False +) -> List[capnp._DynamicStructReader]: +``` + +Example usage: +```py +from openpilot.selfdrive.test.process_replay import replay_process_with_name +from openpilot.tools.lib.logreader import LogReader + +lr = LogReader(...) + +# provide a name of the process to replay +output_logs = replay_process_with_name('locationd', lr) + +# or list of names +output_logs = replay_process_with_name(['ubloxd', 'locationd'], lr) +``` + +Supported processes: +* controlsd +* radard +* plannerd +* calibrationd +* dmonitoringd +* locationd +* paramsd +* ubloxd +* torqued +* modeld +* dmonitoringmodeld + +Certain processes may require an initial state, which is usually supplied within `Params` and persisting from segment to segment (e.g CalibrationParams, LiveParameters). The `custom_params` is dictionary used to prepopulate `Params` with arbitrary values. The `get_custom_params_from_lr` helper is provided to fetch meaningful values from log files. + +```py +from openpilot.selfdrive.test.process_replay import get_custom_params_from_lr + +previous_segment_lr = LogReader(...) +current_segment_lr = LogReader(...) + +custom_params = get_custom_params_from_lr(previous_segment_lr, 'last') + +output_logs = replay_process_with_name('calibrationd', lr, custom_params=custom_params) +``` + +Replaying processes that use VisionIPC (e.g. modeld, dmonitoringmodeld) require additional `frs` dictionary with camera states as keys and `FrameReader` objects as values. + +```py +from openpilot.tools.lib.framereader import FrameReader + +frs = { + 'roadCameraState': FrameReader(...), + 'wideRoadCameraState': FrameReader(...), + 'driverCameraState': FrameReader(...), +} + +output_logs = replay_process_with_name(['modeld', 'dmonitoringmodeld'], lr, frs=frs) +``` + +To capture stdout/stderr of the replayed process, `captured_output_store` can be provided. + +```py +output_store = dict() +# pass dictionary by reference, it will be filled with standard outputs - even if process replay fails +output_logs = replay_process_with_name(['radard', 'plannerd'], lr, captured_output_store=output_store) + +# entries with captured output in format { 'out': '...', 'err': '...' } will be added to provided dictionary for each replayed process +print(output_store['radard']['out']) # radard stdout +print(output_store['radard']['err']) # radard stderr +``` diff --git a/selfdrive/test/process_replay/__init__.py b/openpilot/selfdrive/test/process_replay/__init__.py similarity index 100% rename from selfdrive/test/process_replay/__init__.py rename to openpilot/selfdrive/test/process_replay/__init__.py diff --git a/selfdrive/test/process_replay/capture.py b/openpilot/selfdrive/test/process_replay/capture.py similarity index 100% rename from selfdrive/test/process_replay/capture.py rename to openpilot/selfdrive/test/process_replay/capture.py diff --git a/openpilot/selfdrive/test/process_replay/compare_logs.py b/openpilot/selfdrive/test/process_replay/compare_logs.py new file mode 100755 index 0000000000..4c522c9150 --- /dev/null +++ b/openpilot/selfdrive/test/process_replay/compare_logs.py @@ -0,0 +1,189 @@ +#!/usr/bin/env python3 +import sys +import math +import capnp +import numbers +from collections import Counter + +from openpilot.tools.lib.logreader import LogReader + +EPSILON = sys.float_info.epsilon + +_DynamicStructReader = capnp.lib.capnp._DynamicStructReader +_DynamicListReader = capnp.lib.capnp._DynamicListReader +_DynamicEnum = capnp.lib.capnp._DynamicEnum + + +def remove_ignored_fields(msg, ignore): + msg = msg.as_builder() + for key in ignore: + attr = msg + keys = key.split(".") + if msg.which() != keys[0] and len(keys) > 1: + continue + + for k in keys[:-1]: + # indexing into list + if k.isdigit(): + attr = attr[int(k)] + else: + attr = getattr(attr, k) + + v = getattr(attr, keys[-1]) + if isinstance(v, bool): + val = False + elif isinstance(v, numbers.Number): + val = 0 + elif isinstance(v, (list, capnp.lib.capnp._DynamicListBuilder)): + val = [] + else: + raise NotImplementedError(f"Unknown type: {type(v)}") + setattr(attr, keys[-1], val) + return msg + + +def _diff_capnp(r1, r2, path, tolerance): + """Walk two capnp struct readers and yield (action, dotted_path, value) diffs. + + Floats are compared with the given tolerance (combined absolute+relative). + """ + schema = r1.schema + + for fname in schema.non_union_fields: + child_path = path + (fname,) + v1 = getattr(r1, fname) + v2 = getattr(r2, fname) + yield from _diff_capnp_values(v1, v2, child_path, tolerance) + + if schema.union_fields: + w1, w2 = r1.which(), r2.which() + if w1 != w2: + yield 'change', '.'.join(path), (w1, w2) + else: + child_path = path + (w1,) + v1, v2 = getattr(r1, w1), getattr(r2, w2) + yield from _diff_capnp_values(v1, v2, child_path, tolerance) + + +def _diff_capnp_values(v1, v2, path, tolerance): + if isinstance(v1, _DynamicStructReader): + yield from _diff_capnp(v1, v2, path, tolerance) + + elif isinstance(v1, _DynamicListReader): + dot = '.'.join(path) + n1, n2 = len(v1), len(v2) + n = min(n1, n2) + for i in range(n): + yield from _diff_capnp_values(v1[i], v2[i], path + (str(i),), tolerance) + if n2 > n: + yield 'add', dot, [(i, v2[i]) for i in range(n, n2)] + if n1 > n: + yield 'remove', dot, list(reversed([(i, v1[i]) for i in range(n, n1)])) + + elif isinstance(v1, _DynamicEnum): + s1, s2 = str(v1), str(v2) + if s1 != s2: + yield 'change', '.'.join(path), (s1, s2) + + elif isinstance(v1, float): + if not (v1 == v2 or ( + math.isfinite(v1) and math.isfinite(v2) and + abs(v1 - v2) <= max(tolerance, tolerance * max(abs(v1), abs(v2))) + )): + yield 'change', '.'.join(path), (v1, v2) + + else: + if v1 != v2: + yield 'change', '.'.join(path), (v1, v2) + + +def compare_logs(log1, log2, ignore_fields=None, ignore_msgs=None, tolerance=None,): + if ignore_fields is None: + ignore_fields = [] + if ignore_msgs is None: + ignore_msgs = [] + tolerance = EPSILON if tolerance is None else tolerance + + log1, log2 = ( + [m for m in log if m.which() not in ignore_msgs] + for log in (log1, log2) + ) + + if len(log1) != len(log2): + cnt1 = Counter(m.which() for m in log1) + cnt2 = Counter(m.which() for m in log2) + raise Exception(f"logs are not same length: {len(log1)} VS {len(log2)}\n\t\t{cnt1}\n\t\t{cnt2}") + + diff = [] + for msg1, msg2 in zip(log1, log2, strict=True): + if msg1.which() != msg2.which(): + raise Exception("msgs not aligned between logs") + + msg1 = remove_ignored_fields(msg1, ignore_fields) + msg2 = remove_ignored_fields(msg2, ignore_fields) + + if msg1.to_bytes() != msg2.to_bytes(): + dd = list(_diff_capnp(msg1.as_reader(), msg2.as_reader(), (), tolerance)) + diff.extend(dd) + return diff + + +def format_process_diff(diff): + diff_short, diff_long = "", "" + + if isinstance(diff, str): + diff_short += f" {diff}\n" + diff_long += f"\t{diff}\n" + else: + cnt: dict[str, int] = {} + for d in diff: + diff_long += f"\t{str(d)}\n" + + k = str(d[1]) + cnt[k] = 1 if k not in cnt else cnt[k] + 1 + + for k, v in sorted(cnt.items()): + diff_short += f" {k}: {v}\n" + + return diff_short, diff_long + + +def format_diff(results, log_paths, ref_commit): + diff_short, diff_long = "", "" + diff_long += f"***** tested against commit {ref_commit} *****\n" + + failed = False + for segment, result in list(results.items()): + diff_short += f"***** results for segment {segment} *****\n" + diff_long += f"***** differences for segment {segment} *****\n" + + for proc, diff in list(result.items()): + diff_long += f"*** process: {proc} ***\n" + diff_long += f"\tref: {log_paths[segment][proc]['ref']}\n" + diff_long += f"\tnew: {log_paths[segment][proc]['new']}\n\n" + + diff_short += f" {proc}\n" + + if isinstance(diff, str) or len(diff): + diff_short += f" ref: {log_paths[segment][proc]['ref']}\n" + diff_short += f" new: {log_paths[segment][proc]['new']}\n\n" + failed = True + + proc_diff_short, proc_diff_long = format_process_diff(diff) + + diff_long += proc_diff_long + diff_short += proc_diff_short + + return diff_short, diff_long, failed + + +if __name__ == "__main__": + log1 = list(LogReader(sys.argv[1])) + log2 = list(LogReader(sys.argv[2])) + ignore_fields = sys.argv[3:] or ["logMonoTime"] + results = {"segment": {"proc": compare_logs(log1, log2, ignore_fields)}} + log_paths = {"segment": {"proc": {"ref": sys.argv[1], "new": sys.argv[2]}}} + diff_short, diff_long, failed = format_diff(results, log_paths, None) + + print(diff_long) + print(diff_short) diff --git a/openpilot/selfdrive/test/process_replay/diff_report.py b/openpilot/selfdrive/test/process_replay/diff_report.py new file mode 100644 index 0000000000..c6c1f01abd --- /dev/null +++ b/openpilot/selfdrive/test/process_replay/diff_report.py @@ -0,0 +1,93 @@ +import os +from collections import defaultdict +from opendbc.car.tests.car_diff import format_diff, format_numeric_diffs +from openpilot.selfdrive.test.process_replay.compare_logs import compare_logs +from openpilot.selfdrive.test.process_replay.process_replay import PROC_REPLAY_DIR + + +class MsgWrap: + """Adapter so to_dict() includes defaults""" + def __init__(self, msg): + self._msg = msg + def to_dict(self) -> dict: + return self._msg.to_dict(verbose=True) + + +def diff_process(cfg, ref_msgs, new_msgs) -> tuple | None: + ref = defaultdict(list) + new = defaultdict(list) + for m in ref_msgs: + if m.which() in cfg.subs: + ref[m.which()].append(m) + for m in new_msgs: + if m.which() in cfg.subs: + new[m.which()].append(m) + + diffs = [] + for sub in cfg.subs: + if len(ref[sub]) != len(new[sub]): + diffs.append((f"{sub} (message count)", 0, (len(ref[sub]), len(new[sub])), 0)) + for i, (r, n) in enumerate(zip(ref[sub], new[sub], strict=False)): + for d in compare_logs([r], [n], cfg.ignore, tolerance=cfg.tolerance): + if d[0] == "change": + a, b = d[2] + if a != a and b != b: + continue + diffs.append((d[1], i, d[2], r.logMonoTime)) + elif d[0] in ("add", "remove"): + for item in d[2]: + if item[1] != item[1]: + continue + diffs.append((f"{d[1]}.{item[0]}", i, (d[0], item[1]), r.logMonoTime)) + return (diffs, ref, new) if diffs else None + + +def diff_format(diffs, ref, new, field) -> list[str]: + if any(part.isdigit() for part in field.split(".")): + return format_numeric_diffs(diffs) + msg_type = field.split(".")[0] + ref_ts = [(m.logMonoTime, MsgWrap(m)) for m in ref.get(msg_type, [])] + new_wrapped = [MsgWrap(m) for m in new.get(msg_type, [])] + if not ref_ts or not new_wrapped: + return format_numeric_diffs(diffs) + return format_diff(diffs, ref_ts, new_wrapped, field) + + +def diff_report(replay_diffs, segments) -> None: + seg_to_plat = {seg: plat for plat, seg in segments} + + with_diffs, errors, n_passed = [], [], 0 + for seg, proc, data in replay_diffs: + plat = seg_to_plat.get(seg, "UNKNOWN") + if data is None: + n_passed += 1 + elif isinstance(data, str): + errors.append((plat, seg, proc, data)) + else: + with_diffs.append((plat, seg, proc, data)) + + icon = "⚠️" if with_diffs else "✅" + lines = [ + "## Process replay diff report", + "Replays driving segments through this PR and compares the behavior to master.", + "Please review any changes carefully to ensure they are expected.\n", + f"{icon} {len(with_diffs)} changed, {n_passed} passed, {len(errors)} errors", + ] + + for plat, seg, proc, err in errors: + lines.append(f"\nERROR {plat} - {seg} [{proc}]: {err}") + + if with_diffs: + lines.append("
Show changes\n\n```") + for plat, seg, proc, (diffs, ref, new) in with_diffs: + lines.append(f"\n{plat} - {seg} [{proc}]") + by_field = defaultdict(list) + for d in diffs: + by_field[d[0]].append(d) + for field, fd in sorted(by_field.items()): + lines.append(f"\n {field} ({len(fd)} diffs)") + lines.extend(diff_format(fd, ref, new, field)) + lines.append("```\n
") + + with open(os.path.join(PROC_REPLAY_DIR, "diff_report.txt"), "w") as f: + f.write("\n".join(lines)) diff --git a/openpilot/selfdrive/test/process_replay/migration.py b/openpilot/selfdrive/test/process_replay/migration.py new file mode 100644 index 0000000000..9b0fd2b91f --- /dev/null +++ b/openpilot/selfdrive/test/process_replay/migration.py @@ -0,0 +1,529 @@ +from collections import defaultdict +from collections.abc import Callable +from typing import cast +import capnp +import functools +import traceback + +from openpilot.cereal import messaging, log +from opendbc.car.structs import car +from opendbc.car.fingerprints import MIGRATION +from opendbc.car.toyota.values import EPS_SCALE, ToyotaSafetyFlags +from opendbc.car.ford.values import CAR as FORD, FordFlags, FordSafetyFlags +from opendbc.car.hyundai.values import HyundaiSafetyFlags +from opendbc.car.gm.values import GMSafetyFlags +from openpilot.selfdrive.modeld.constants import ModelConstants +from openpilot.selfdrive.modeld.fill_model_msg import fill_xyz_poly, fill_lane_line_meta +from openpilot.selfdrive.test.process_replay.vision_meta import meta_from_encode_index +from openpilot.selfdrive.controls.lib.drive_helpers import CONTROL_N, get_accel_from_plan +from openpilot.system.manager.process_config import managed_processes +from openpilot.tools.lib.logreader import LogIterable + +MessageWithIndex = tuple[int, capnp.lib.capnp._DynamicStructReader] +MigrationOps = tuple[list[tuple[int, capnp.lib.capnp._DynamicStructReader]], list[capnp.lib.capnp._DynamicStructReader], list[int]] +MigrationFunc = Callable[[list[MessageWithIndex]], MigrationOps] + + +# rules for migration functions +# 1. must use the decorator @migration(inputs=[...], product="...") and MigrationFunc signature +# 2. it only gets the messages that are in the inputs list +# 3. product is the message type created by the migration function, and the function will be skipped if product type already exists in lr +# 4. it must return a list of operations to be applied to the logreader (replace, add, delete) +# 5. all migration functions must be independent of each other +def migrate_all(lr: LogIterable, manager_states: bool = False, panda_states: bool = False, camera_states: bool = False, + live_location_kalman: bool = True): + migrations = [ + migrate_sensorEvents, + migrate_carParams, + migrate_gpsLocation, + migrate_deviceState, + migrate_carOutput, + migrate_controlsState, + migrate_carState, + migrate_livePose, + migrate_liveTracks, + migrate_driverAssistance, + migrate_drivingModelData, + migrate_onroadEvents, + migrate_driverMonitoringState, + migrate_longitudinalPlan, + ] + if manager_states: + migrations.append(migrate_managerState) + if panda_states: + migrations.extend([migrate_pandaStates, migrate_peripheralState]) + if camera_states: + migrations.append(migrate_cameraStates) + if live_location_kalman: + migrations.append(migrate_liveLocationKalman) + + return migrate(lr, migrations) + + +def migrate(lr: LogIterable, migration_funcs: list[MigrationFunc]): + lr = list(lr) + grouped = defaultdict(list) + for i, msg in enumerate(lr): + grouped[msg.which()].append(i) + + replace_ops, add_ops, del_ops = [], [], [] + for migration in migration_funcs: + assert hasattr(migration, "inputs") and hasattr(migration, "product"), "Migration functions must use @migration decorator" + if migration.product in grouped: # skip if product already exists + continue + + sorted_indices = sorted(ii for i in cast(list[str], migration.inputs) for ii in grouped.get(i, [])) + msg_gen = [(i, lr[i]) for i in sorted_indices] + r_ops, a_ops, d_ops = migration(msg_gen) + replace_ops.extend(r_ops) + add_ops.extend(a_ops) + del_ops.extend(d_ops) + + for index, msg in replace_ops: + lr[index] = msg + for index in sorted(del_ops, reverse=True): + del lr[index] + for msg in add_ops: + lr.append(msg) + lr = sorted(lr, key=lambda x: x.logMonoTime) + + return lr + + +def as_reader(builder) -> capnp.lib.capnp._DynamicStructReader: + return log.Event.from_bytes(builder.to_bytes()).__enter__() # round-trip through bytes, 2x faster and 30x less memory than builder.as_reader() + + +def migration(inputs: list[str], product: str|None=None): + def decorator(func): + @functools.wraps(func) + def wrapper(*args, **kwargs): + return func(*args, **kwargs) + wrapper.inputs = inputs + wrapper.product = product + return wrapper + return decorator + + +def migrate_onroad_event(event: capnp.lib.capnp._DynamicStructReader): + event_dict = event.to_dict() + try: + return log.OnroadEvent(**event_dict) + except capnp.lib.capnp.KjException as e: + # Ignore legacy events the current schema no longer defines. + if "enum has no such enumerant" in str(e): + return None + raise + + +@migration(inputs=["longitudinalPlan", "carParams"]) +def migrate_longitudinalPlan(msgs): + ops = [] + + needs_migration = all(msg.longitudinalPlan.aTarget == 0.0 for _, msg in msgs if msg.which() == 'longitudinalPlan') + CP = next((m.carParams for _, m in msgs if m.which() == 'carParams'), None) + if not needs_migration or CP is None: + return [], [], [] + + for index, msg in msgs: + if msg.which() != 'longitudinalPlan': + continue + new_msg = msg.as_builder() + a_target, should_stop = get_accel_from_plan(msg.longitudinalPlan.speeds, msg.longitudinalPlan.accels, ModelConstants.T_IDXS[:CONTROL_N]) + new_msg.longitudinalPlan.aTarget, new_msg.longitudinalPlan.shouldStop = float(a_target), bool(should_stop) + ops.append((index, as_reader(new_msg))) + return ops, [], [] + + +@migration(inputs=["longitudinalPlan"], product="driverAssistance") +def migrate_driverAssistance(msgs): + add_ops = [] + for _, msg in msgs: + new_msg = messaging.new_message('driverAssistance', valid=True, logMonoTime=msg.logMonoTime) + add_ops.append(as_reader(new_msg)) + return [], add_ops, [] + + +@migration(inputs=["modelV2"], product="drivingModelData") +def migrate_drivingModelData(msgs): + add_ops = [] + for _, msg in msgs: + dmd = messaging.new_message('drivingModelData', valid=msg.valid, logMonoTime=msg.logMonoTime) + for field in ["frameId", "frameIdExtra", "frameDropPerc", "modelExecutionTime", "action"]: + setattr(dmd.drivingModelData, field, getattr(msg.modelV2, field)) + for meta_field in ["laneChangeState", "laneChangeState"]: + setattr(dmd.drivingModelData.meta, meta_field, getattr(msg.modelV2.meta, meta_field)) + if len(msg.modelV2.laneLines) and len(msg.modelV2.laneLineProbs): + fill_lane_line_meta(dmd.drivingModelData.laneLineMeta, msg.modelV2.laneLines, msg.modelV2.laneLineProbs) + if all(len(a) for a in [msg.modelV2.position.x, msg.modelV2.position.y, msg.modelV2.position.z]): + fill_xyz_poly(dmd.drivingModelData.path, ModelConstants.POLY_PATH_DEGREE, msg.modelV2.position.x, msg.modelV2.position.y, msg.modelV2.position.z) + add_ops.append(as_reader(dmd)) + return [], add_ops, [] + + +@migration(inputs=["liveTracksDEPRECATED"], product="liveTracks") +def migrate_liveTracks(msgs): + ops = [] + for index, msg in msgs: + new_msg = messaging.new_message('liveTracks') + new_msg.valid = msg.valid + new_msg.logMonoTime = msg.logMonoTime + + pts = [] + for track in msg.liveTracksDEPRECATED: + pt = car.RadarData.RadarPoint() + pt.trackId = track.trackId + + pt.dRel = track.dRel + pt.yRel = track.yRel + pt.vRel = track.vRel + pts.append(pt) + + new_msg.liveTracks.points = pts + ops.append((index, as_reader(new_msg))) + return ops, [], [] + + +@migration(inputs=["liveLocationKalmanDEPRECATED"], product="livePose") +def migrate_liveLocationKalman(msgs): + nans = [float('nan')] * 3 + ops = [] + for index, msg in msgs: + m = messaging.new_message('livePose') + m.valid = msg.valid + m.logMonoTime = msg.logMonoTime + m.livePose.timestamp = msg.logMonoTime + for field in ["orientationNED", "velocityDevice", "accelerationDevice", "angularVelocityDevice"]: + lp_field, llk_field = getattr(m.livePose, field), getattr(msg.liveLocationKalmanDEPRECATED, field) + lp_field.x, lp_field.y, lp_field.z = llk_field.value or nans + lp_field.xStd, lp_field.yStd, lp_field.zStd = llk_field.std or nans + lp_field.valid = llk_field.valid + for flag in ["inputsOK", "posenetOK", "sensorsOK"]: + setattr(m.livePose, flag, getattr(msg.liveLocationKalmanDEPRECATED, flag)) + ops.append((index, as_reader(m))) + return ops, [], [] + + +@migration(inputs=["livePose"]) +def migrate_livePose(msgs): + ops = [] + needs_migration = all(msg.livePose.timestamp == 0 for _, msg in msgs if msg.which() == 'livePose') + if not needs_migration: + return [], [], [] + + for index, msg in msgs: + if msg.which() == "livePose": + new_msg = msg.as_builder() + new_msg.livePose.timestamp = msg.logMonoTime + ops.append((index, as_reader(new_msg))) + return ops, [], [] + + +@migration(inputs=["controlsState"], product="selfdriveState") +def migrate_controlsState(msgs): + add_ops = [] + for _, msg in msgs: + m = messaging.new_message('selfdriveState') + m.valid = msg.valid + m.logMonoTime = msg.logMonoTime + ss = m.selfdriveState + for field in ("enabled", "active", "state", "engageable", "alertText1", "alertText2", + "alertStatus", "alertSize", "alertType", "experimentalMode", + "personality"): + setattr(ss, field, getattr(msg.controlsState.deprecated, field)) + add_ops.append(as_reader(m)) + return [], add_ops, [] + + +@migration(inputs=["carState", "controlsState"]) +def migrate_carState(msgs): + ops = [] + last_cs = None + for index, msg in msgs: + if msg.which() == 'controlsState': + last_cs = msg + elif msg.which() == 'carState' and last_cs is not None: + if last_cs.controlsState.deprecated.vCruise - msg.carState.vCruise > 0.1: + msg = msg.as_builder() + msg.carState.vCruise = last_cs.controlsState.deprecated.vCruise + msg.carState.vCruiseCluster = last_cs.controlsState.deprecated.vCruiseCluster + ops.append((index, as_reader(msg))) + return ops, [], [] + + +@migration(inputs=["managerState"]) +def migrate_managerState(msgs): + ops = [] + for index, msg in msgs: + new_msg = msg.as_builder() + new_msg.managerState.processes = [{'name': name, 'running': True} for name in managed_processes] + ops.append((index, as_reader(new_msg))) + return ops, [], [] + + +@migration(inputs=["gpsLocation", "gpsLocationExternal"]) +def migrate_gpsLocation(msgs): + ops = [] + for index, msg in msgs: + new_msg = msg.as_builder() + g = getattr(new_msg, new_msg.which()) + # hasFix is a newer field + if not g.hasFix and g.flags == 1: + g.hasFix = True + ops.append((index, as_reader(new_msg))) + return ops, [], [] + + +@migration(inputs=["deviceState", "initData"]) +def migrate_deviceState(msgs): + init_data = next((m.initData for _, m in msgs if m.which() == 'initData'), None) + device_state = next((m.deviceState for _, m in msgs if m.which() == 'deviceState'), None) + if init_data is None or device_state is None: + return [], [], [] + + ops = [] + for i, msg in msgs: + if msg.which() == 'deviceState': + n = msg.as_builder() + n.deviceState.deviceType = init_data.deviceType + ops.append((i, as_reader(n))) + return ops, [], [] + + +@migration(inputs=["carControl"], product="carOutput") +def migrate_carOutput(msgs): + add_ops = [] + for _, msg in msgs: + co = messaging.new_message('carOutput') + co.valid = msg.valid + co.logMonoTime = msg.logMonoTime + co.carOutput.actuatorsOutput = msg.carControl.deprecated.actuatorsOutput + add_ops.append(as_reader(co)) + return [], add_ops, [] + + +@migration(inputs=["pandaStates", "pandaStateDEPRECATED", "carParams"]) +def migrate_pandaStates(msgs): + # TODO: safety param migration should be handled automatically + safety_param_migration = { + "TOYOTA_PRIUS": EPS_SCALE["TOYOTA_PRIUS"] | ToyotaSafetyFlags.STOCK_LONGITUDINAL, + "TOYOTA_RAV4": EPS_SCALE["TOYOTA_RAV4"] | ToyotaSafetyFlags.ALT_BRAKE, + "KIA_EV6": HyundaiSafetyFlags.EV_GAS | HyundaiSafetyFlags.CANFD_LKA_STEER_MSG, + "CHEVROLET_VOLT": GMSafetyFlags.EV, + "CHEVROLET_BOLT_EUV": GMSafetyFlags.EV | GMSafetyFlags.HW_CAM, + } + # TODO: get new Ford route + safety_param_migration |= dict.fromkeys((set(FORD) - FORD.with_flags(FordFlags.CANFD)), FordSafetyFlags.LONG_CONTROL) + + # Migrate safety param base on carParams + CP = next((m.carParams for _, m in msgs if m.which() == 'carParams'), None) + assert CP is not None, "carParams message not found" + fingerprint = MIGRATION.get(CP.carFingerprint, CP.carFingerprint) + if fingerprint in safety_param_migration: + safety_param = safety_param_migration[fingerprint].value + elif len(CP.safetyConfigs): + safety_param = CP.safetyConfigs[0].safetyParam + if CP.safetyConfigs[0].deprecated.safetyParam != 0: + safety_param = CP.safetyConfigs[0].deprecated.safetyParam + else: + safety_param = CP.deprecated.safetyParam + + ops = [] + for index, msg in msgs: + if msg.which() == 'pandaStateDEPRECATED': + new_msg = messaging.new_message('pandaStates', 1) + new_msg.valid = msg.valid + new_msg.logMonoTime = msg.logMonoTime + new_msg.pandaStates[0] = msg.pandaStateDEPRECATED + new_msg.pandaStates[0].safetyParam = safety_param + ops.append((index, as_reader(new_msg))) + elif msg.which() == 'pandaStates': + new_msg = msg.as_builder() + new_msg.pandaStates[-1].safetyParam = safety_param + # Clear DISABLE_DISENGAGE_ON_GAS bit to fix controls mismatch + new_msg.pandaStates[-1].alternativeExperience &= ~1 + ops.append((index, as_reader(new_msg))) + return ops, [], [] + + +@migration(inputs=["pandaStates", "pandaStateDEPRECATED"], product="peripheralState") +def migrate_peripheralState(msgs): + add_ops = [] + + which = "pandaStates" if any(msg.which() == "pandaStates" for _, msg in msgs) else "pandaStateDEPRECATED" + for _, msg in msgs: + if msg.which() != which: + continue + new_msg = messaging.new_message("peripheralState") + new_msg.valid = msg.valid + new_msg.logMonoTime = msg.logMonoTime + add_ops.append(as_reader(new_msg)) + return [], add_ops, [] + + +@migration(inputs=["roadEncodeIdx", "wideRoadEncodeIdx", "driverEncodeIdx", "roadCameraState", "wideRoadCameraState", "driverCameraState"]) +def migrate_cameraStates(msgs): + add_ops, del_ops = [], [] + frame_to_encode_id = defaultdict(dict) + # just for encodeId fallback mechanism + min_frame_id = defaultdict(lambda: float('inf')) + + for _, msg in msgs: + if msg.which() not in ["roadEncodeIdx", "wideRoadEncodeIdx", "driverEncodeIdx"]: + continue + + encode_index = getattr(msg, msg.which()) + meta = meta_from_encode_index(msg.which()) + + assert encode_index.segmentId < 1200, f"Encoder index segmentId greater that 1200: {msg.which()} {encode_index.segmentId}" + frame_to_encode_id[meta.camera_state][encode_index.frameId] = encode_index.segmentId + + for index, msg in msgs: + if msg.which() not in ["roadCameraState", "wideRoadCameraState", "driverCameraState"]: + continue + + camera_state = getattr(msg, msg.which()) + min_frame_id[msg.which()] = min(min_frame_id[msg.which()], camera_state.frameId) + + encode_id = frame_to_encode_id[msg.which()].get(camera_state.frameId) + if encode_id is None: + print(f"Missing encoded frame for camera feed {msg.which()} with frameId: {camera_state.frameId}") + if len(frame_to_encode_id[msg.which()]) != 0: + del_ops.append(index) + continue + + # fallback mechanism for logs without encodeIdx (e.g. logs from before 2022 with dcamera recording disabled) + # try to fake encode_id by subtracting lowest frameId + encode_id = camera_state.frameId - min_frame_id[msg.which()] + print(f"Faking encodeId to {encode_id} for camera feed {msg.which()} with frameId: {camera_state.frameId}") + + new_msg = messaging.new_message(msg.which()) + new_camera_state = getattr(new_msg, new_msg.which()) + new_camera_state.sensor = camera_state.sensor + new_camera_state.frameId = encode_id + new_camera_state.encodeId = encode_id + # timestampSof was added later so it might be missing on some old segments + if camera_state.timestampSof == 0 and camera_state.timestampEof > 25000000: + new_camera_state.timestampSof = camera_state.timestampEof - 18000000 + else: + new_camera_state.timestampSof = camera_state.timestampSof + new_camera_state.timestampEof = camera_state.timestampEof + new_msg.logMonoTime = msg.logMonoTime + new_msg.valid = msg.valid + + del_ops.append(index) + add_ops.append(as_reader(new_msg)) + return [], add_ops, del_ops + + +@migration(inputs=["carParams"]) +def migrate_carParams(msgs): + ops = [] + for index, msg in msgs: + CP = msg.as_builder() + CP.carParams.carFingerprint = MIGRATION.get(CP.carParams.carFingerprint, CP.carParams.carFingerprint) + for car_fw in CP.carParams.carFw: + car_fw.brand = CP.carParams.brand + ops.append((index, as_reader(CP))) + return ops, [], [] + + +@migration(inputs=["sensorEventsDEPRECATED"], product="sensorEvents") +def migrate_sensorEvents(msgs): + add_ops, del_ops = [], [] + for index, msg in msgs: + # migrate to split sensor events + for evt in msg.sensorEventsDEPRECATED: + # build new message for each sensor type + sensor_service = '' + if evt.which() == 'acceleration': + sensor_service = 'accelerometer' + elif evt.which() == 'gyro' or evt.which() == 'gyroUncalibrated': + sensor_service = 'gyroscope' + elif evt.which() == 'light' or evt.which() == 'proximity': + sensor_service = 'lightSensor' + elif evt.which() == 'magnetic' or evt.which() == 'magneticUncalibrated': + sensor_service = 'magnetometer' + elif evt.which() == 'temperature': + sensor_service = 'temperatureSensor' + + m = messaging.new_message(sensor_service) + m.valid = True + m.logMonoTime = msg.logMonoTime + + m_dat = getattr(m, sensor_service) + m_dat.source = evt.source + m_dat.timestamp = evt.timestamp + setattr(m_dat, evt.which(), getattr(evt, evt.which())) + + add_ops.append(as_reader(m)) + del_ops.append(index) + return [], add_ops, del_ops + + +@migration(inputs=["onroadEventsDEPRECATED"], product="onroadEvents") +def migrate_onroadEvents(msgs): + ops = [] + for index, msg in msgs: + onroadEvents = [] + for event in msg.onroadEventsDEPRECATED: + try: + if not str(event.name).endswith('DEPRECATED'): + migrated_event = migrate_onroad_event(event) + if migrated_event is not None: + onroadEvents.append(migrated_event) + except RuntimeError: # Member was null + traceback.print_exc() + + new_msg = messaging.new_message('onroadEvents', len(onroadEvents)) + new_msg.valid = msg.valid + new_msg.logMonoTime = msg.logMonoTime + new_msg.onroadEvents = onroadEvents + ops.append((index, as_reader(new_msg))) + + return ops, [], [] + + +@migration(inputs=["driverMonitoringStateDEPRECATED"]) +def migrate_driverMonitoringState(msgs): + ops = [] + for index, msg in msgs: + old = msg.driverMonitoringStateDEPRECATED + new_msg = messaging.new_message('driverMonitoringState', valid=msg.valid, logMonoTime=msg.logMonoTime) + dm = new_msg.driverMonitoringState + dm.isRHD = old.isRHD + dm.activePolicy = log.DriverMonitoringState.MonitoringPolicy.vision if old.isActiveMode else \ + log.DriverMonitoringState.MonitoringPolicy.wheeltouch + + AlertLevel = log.DriverMonitoringState.AlertLevel + event_to_alert_level = { + 'driverDistracted1': AlertLevel.one, 'driverUnresponsive1': AlertLevel.one, + 'driverDistracted2': AlertLevel.two, 'driverUnresponsive2': AlertLevel.two, + 'driverDistracted3': AlertLevel.three, 'driverUnresponsive3': AlertLevel.three, + } + for event in old.events: + level = event_to_alert_level.get(str(event.name)) + if level is not None: + dm.alertLevel = level + break + dm.lockout = any(str(event.name) == 'tooDistracted' for event in old.events) + + dm.visionPolicyState.awarenessPercent = int(max(0, min(100, (old.awarenessStatus if old.isActiveMode else old.awarenessActive) * 100))) + dm.visionPolicyState.awarenessStep = old.stepChange if old.isActiveMode else 0. + dm.visionPolicyState.isDistracted = old.isDistracted + dm.visionPolicyState.distractedTypes.pose = bool(old.distractedType & 1) + dm.visionPolicyState.distractedTypes.eye = bool(old.distractedType & 2) + dm.visionPolicyState.distractedTypes.phone = bool(old.distractedType & 4) + dm.visionPolicyState.faceDetected = old.faceDetected + dm.visionPolicyState.pose.pitchCalib.offset = old.posePitchOffset + dm.visionPolicyState.pose.pitchCalib.calibratedPercent = int(min(100, old.posePitchValidCount / 1200 * 100)) + dm.visionPolicyState.pose.yawCalib.offset = old.poseYawOffset + dm.visionPolicyState.pose.yawCalib.calibratedPercent = int(min(100, old.poseYawValidCount / 1200 * 100)) + dm.visionPolicyState.pose.calibrated = old.posePitchValidCount >= 1200 and old.poseYawValidCount >= 1200 + dm.visionPolicyState.wheeltouchFallbackPercent = int(min(100, old.hiStdCount / 200 * 100)) + dm.visionPolicyState.uncertainOffroadAlertPercent = int(min(100, old.uncertainCount / 1200 * 100)) + dm.wheeltouchPolicyState.awarenessPercent = int(max(0, min(100, (old.awarenessPassive if old.isActiveMode else old.awarenessStatus) * 100))) + dm.wheeltouchPolicyState.awarenessStep = 0. if old.isActiveMode else old.stepChange + ops.append((index, as_reader(new_msg))) + + return ops, [], [] diff --git a/selfdrive/test/process_replay/model_replay.py b/openpilot/selfdrive/test/process_replay/model_replay.py similarity index 98% rename from selfdrive/test/process_replay/model_replay.py rename to openpilot/selfdrive/test/process_replay/model_replay.py index 59b8cf8250..3e5616e702 100755 --- a/selfdrive/test/process_replay/model_replay.py +++ b/openpilot/selfdrive/test/process_replay/model_replay.py @@ -9,10 +9,10 @@ from itertools import zip_longest import matplotlib.pyplot as plt import numpy as np -from tabulate import tabulate +from openpilot.common.utils import tabulate from openpilot.common.git import get_commit -from openpilot.system.hardware import PC +from openpilot.common.hardware import PC from openpilot.tools.lib.openpilotci import get_url from openpilot.selfdrive.test.process_replay.compare_logs import compare_logs, format_diff from openpilot.selfdrive.test.process_replay.process_replay import get_process_config, replay_process @@ -34,8 +34,8 @@ GITHUB = GithubUtils(API_TOKEN, DATA_TOKEN) EXEC_TIMINGS = [ # model, instant max, average max - ("modelV2", 0.035, 0.025), - ("driverStateV2", 0.02, 0.015), + ("modelV2", 0.05, 0.028), + ("driverStateV2", 0.05, 0.018), ] def get_log_fn(test_route, ref="master"): @@ -77,7 +77,7 @@ def generate_report(proposed, master, tmp, commit): (lambda x: get_idx_if_non_empty(x.leftDriverData.faceProb), "leftDriverData.faceProb"), (lambda x: get_idx_if_non_empty(x.leftDriverData.faceOrientation, 0), "leftDriverData.faceOrientation0"), (lambda x: get_idx_if_non_empty(x.leftDriverData.leftBlinkProb), "leftDriverData.leftBlinkProb"), - (lambda x: get_idx_if_non_empty(x.leftDriverData.notReadyProb, 0), "leftDriverData.notReadyProb0"), + (lambda x: get_idx_if_non_empty(x.leftDriverData.phoneProb), "leftDriverData.phoneProb"), (lambda x: get_idx_if_non_empty(x.rightDriverData.faceProb), "rightDriverData.faceProb"), ], "driverStateV2") diff --git a/selfdrive/test/process_replay/process_replay.py b/openpilot/selfdrive/test/process_replay/process_replay.py similarity index 81% rename from selfdrive/test/process_replay/process_replay.py rename to openpilot/selfdrive/test/process_replay/process_replay.py index bc5ccf7845..fc3463b376 100755 --- a/selfdrive/test/process_replay/process_replay.py +++ b/openpilot/selfdrive/test/process_replay/process_replay.py @@ -4,25 +4,29 @@ import time import copy import heapq import signal -from collections import Counter, OrderedDict +import numpy as np +from collections import Counter from dataclasses import dataclass, field +from itertools import islice from typing import Any from collections.abc import Callable, Iterable from tqdm import tqdm import capnp -from openpilot.system.hardware.hw import Paths +from openpilot.common.hardware.hw import Paths -import cereal.messaging as messaging -from cereal import car -from cereal.services import SERVICE_LIST +import openpilot.cereal.messaging as messaging +from opendbc.car.structs import car +from openpilot.cereal.services import SERVICE_LIST from msgq.visionipc import VisionIpcServer, get_endpoint_name as vipc_get_endpoint_name +from opendbc.car.can_definitions import CanData from opendbc.car.car_helpers import get_car, interfaces from openpilot.common.params import Params from openpilot.common.prefix import OpenpilotPrefix from openpilot.common.timeout import Timeout from openpilot.common.realtime import DT_CTRL -from openpilot.selfdrive.car.card import can_comm_callbacks, convert_to_capnp +from openpilot.system.camerad.cameras.nv12_info import get_nv12_info from openpilot.system.manager.process_config import managed_processes +from openpilot.selfdrive.car.card import convert_to_capnp from openpilot.selfdrive.test.process_replay.vision_meta import meta_from_camera_state, available_streams from openpilot.selfdrive.test.process_replay.migration import migrate_all from openpilot.selfdrive.test.process_replay.capture import ProcessOutputCapture @@ -30,22 +34,10 @@ from openpilot.tools.lib.logreader import LogIterable from openpilot.tools.lib.framereader import FrameReader # Numpy gives different results based on CPU features after version 19 -NUMPY_TOLERANCE = 1e-7 +NUMPY_TOLERANCE = 1e-2 PROC_REPLAY_DIR = os.path.dirname(os.path.abspath(__file__)) FAKEDATA = os.path.join(PROC_REPLAY_DIR, "fakedata/") -class DummySocket: - def __init__(self): - self.data: list[bytes] = [] - - def receive(self, non_blocking: bool = False) -> bytes | None: - if non_blocking: - return None - - return self.data.pop() - - def send(self, data: bytes): - self.data.append(data) class LauncherWithCapture: def __init__(self, capture: ProcessOutputCapture, launcher: Callable): @@ -63,8 +55,7 @@ class ReplayContext: self.pubs = cfg.pubs self.main_pub = cfg.main_pub self.main_pub_drained = cfg.main_pub_drained - self.unlocked_pubs = cfg.unlocked_pubs - assert(len(self.pubs) != 0 or self.main_pub is not None) + assert len(self.pubs) != 0 or self.main_pub is not None def __enter__(self): self.open_context() @@ -79,9 +70,8 @@ class ReplayContext: messaging.set_fake_prefix(self.proc_name) if self.main_pub is None: - self.events = OrderedDict() - pubs_with_events = [pub for pub in self.pubs if pub not in self.unlocked_pubs] - for pub in pubs_with_events: + self.events = {} + for pub in self.pubs: self.events[pub] = messaging.fake_event_handle(pub, enable=True) else: self.events = {self.main_pub: messaging.fake_event_handle(self.main_pub, enable=True)} @@ -138,19 +128,25 @@ class ProcessConfig: processing_time: float = 0.001 timeout: int = 30 simulation: bool = True + # Set to service process receives on first main_pub: str | None = None - main_pub_drained: bool = True + main_pub_drained: bool = False vision_pubs: list[str] = field(default_factory=list) ignore_alive_pubs: list[str] = field(default_factory=list) - unlocked_pubs: list[str] = field(default_factory=list) + + def __post_init__(self): + # If the process is polling a service, we can just lock that one to speed up replay + if self.main_pub is None and isinstance(self.should_recv_callback, MessageBasedRcvCallback): + self.main_pub = self.should_recv_callback.trigger_msg_type class ProcessContainer: def __init__(self, cfg: ProcessConfig): - self.prefix = OpenpilotPrefix(clean_dirs_on_exit=False) + self.prefix = OpenpilotPrefix(create_dirs_on_enter=False, clean_dirs_on_exit=False) self.cfg = copy.deepcopy(cfg) self.process = copy.deepcopy(managed_processes[cfg.proc_name]) self.msg_queue: list[capnp._DynamicStructReader] = [] + self.last_input_log_mono_time: int = -1 self.cnt = 0 self.pm: messaging.PubMaster | None = None self.sockets: list[messaging.SubSocket] | None = None @@ -196,9 +192,9 @@ class ProcessContainer: params = Params() for k, v in params_config.items(): if isinstance(v, bool): - params.put_bool(k, v) + params.put_bool(k, v, block=True) else: - params.put(k, v) + params.put(k, v, block=True) self.environ_config = environ_config @@ -211,7 +207,8 @@ class ProcessContainer: if meta.camera_state in self.cfg.vision_pubs: assert frs[meta.camera_state].pix_fmt == 'nv12' frame_size = (frs[meta.camera_state].w, frs[meta.camera_state].h) - vipc_server.create_buffers(meta.stream, 2, *frame_size) + stride, y_height, _, yuv_size = get_nv12_info(frame_size[0], frame_size[1]) + vipc_server.create_buffers_with_sizes(meta.stream, 2, frame_size[0], frame_size[1], yuv_size, stride, stride * y_height) vipc_server.start_listener() self.vipc_server = vipc_server @@ -219,8 +216,7 @@ class ProcessContainer: def _start_process(self): if self.capture is not None: - self.process.launcher = LauncherWithCapture(self.capture, self.process.launcher) - self.process.prepare() + self.process.launcher = LauncherWithCapture(self.capture, self.process.launcher) # ty: ignore[invalid-assignment] # intentional wrapper self.process.start() def start( @@ -229,6 +225,7 @@ class ProcessContainer: fingerprint: str | None, capture_output: bool ): with self.prefix as p: + self.prefix.create_dirs() self._setup_env(params_config, environ_config) if self.cfg.config_callback is not None: @@ -254,11 +251,6 @@ class ProcessContainer: if self.cfg.init_callback is not None: self.cfg.init_callback(self.rc, self.pm, all_msgs, fingerprint) - # wait for process to startup - with Timeout(10, error_msg=f"timed out waiting for process to start: {repr(self.cfg.proc_name)}"): - while not all(self.pm.all_readers_updated(s) for s in self.cfg.pubs if s not in self.cfg.ignore_alive_pubs): - time.sleep(0) - def stop(self): with self.prefix: self.process.signal(signal.SIGKILL) @@ -267,50 +259,70 @@ class ProcessContainer: self.prefix.clean_dirs() self._clean_env() + def get_output_msgs(self, start_time: int): + assert self.rc and self.sockets + + output_msgs = [] + self.rc.wait_for_recv_called() + for socket in self.sockets: + ms = messaging.drain_sock(socket) + for m in ms: + m = m.as_builder() + assert start_time > 0, "start_time must be positive" + m.logMonoTime = start_time + int(self.cfg.processing_time * 1e9) + output_msgs.append(m.as_reader()) + return output_msgs + def run_step(self, msg: capnp._DynamicStructReader, frs: dict[str, FrameReader] | None) -> list[capnp._DynamicStructReader]: assert self.rc and self.pm and self.sockets and self.process.proc output_msgs = [] - with self.prefix, Timeout(self.cfg.timeout, error_msg=f"timed out testing process {repr(self.cfg.proc_name)}"): - end_of_cycle = True - if self.cfg.should_recv_callback is not None: - end_of_cycle = self.cfg.should_recv_callback(msg, self.cfg, self.cnt) - - self.msg_queue.append(msg) - if end_of_cycle: - self.rc.wait_for_recv_called() + end_of_cycle = True + if self.cfg.should_recv_callback is not None: + end_of_cycle = self.cfg.should_recv_callback(msg, self.cfg, self.cnt) + self.msg_queue.append(msg) + if end_of_cycle: + with self.prefix, Timeout(self.cfg.timeout, error_msg=f"timed out testing process {repr(self.cfg.proc_name)}"): # call recv to let sub-sockets reconnect, after we know the process is ready if self.cnt == 0: for s in self.sockets: messaging.recv_one_or_none(s) - # empty recv on drained pub indicates the end of messages, only do that if there're any + # certain processes use drain_sock. need to cause empty recv to break from this loop trigger_empty_recv = False if self.cfg.main_pub and self.cfg.main_pub_drained: - trigger_empty_recv = next((True for m in self.msg_queue if m.which() == self.cfg.main_pub), False) + trigger_empty_recv = any(m.which() == self.cfg.main_pub for m in self.msg_queue) + + # get output msgs from previous inputs + output_msgs = self.get_output_msgs(self.last_input_log_mono_time) for m in self.msg_queue: self.pm.send(m.which(), m.as_builder()) + self.last_input_log_mono_time = max(self.last_input_log_mono_time, m.logMonoTime) # send frames if needed if self.vipc_server is not None and m.which() in self.cfg.vision_pubs: camera_state = getattr(m, m.which()) camera_meta = meta_from_camera_state(m.which()) assert frs is not None img = frs[m.which()].get(camera_state.frameId) - self.vipc_server.send(camera_meta.stream, img.flatten().tobytes(), + + h, w = frs[m.which()].h, frs[m.which()].w + stride, y_height, _, yuv_size = get_nv12_info(w, h) + uv_offset = stride * y_height + padded_img = np.zeros(((uv_offset //stride) + (h // 2), stride)) + padded_img[:h, :w] = img[:h * w].reshape((-1, w)) + padded_img[uv_offset // stride:uv_offset // stride + h // 2, :w] = img[h * w:].reshape((-1, w)) + img_bytes = np.zeros((yuv_size,), dtype=np.uint8) + img_bytes[:padded_img.size] = padded_img.flatten() + + self.vipc_server.send(camera_meta.stream, img_bytes.tobytes(), camera_state.frameId, camera_state.timestampSof, camera_state.timestampEof) self.msg_queue = [] self.rc.unlock_sockets() - self.rc.wait_for_next_recv(trigger_empty_recv) - - for socket in self.sockets: - ms = messaging.drain_sock(socket) - for m in ms: - m = m.as_builder() - m.logMonoTime = msg.logMonoTime + int(self.cfg.processing_time * 1e9) - output_msgs.append(m.as_reader()) + if trigger_empty_recv: + self.rc.unlock_sockets() self.cnt += 1 assert self.process.proc.is_alive() @@ -320,7 +332,7 @@ class ProcessContainer: def card_fingerprint_callback(rc, pm, msgs, fingerprint): print("start fingerprinting") params = Params() - canmsgs = [msg for msg in msgs if msg.which() == "can"][:300] + canmsgs = list(islice((m for m in msgs if m.which() == "can"), 300)) # card expects one arbitrary can and pandaState rc.send_sync(pm, "can", messaging.new_message("can", 1)) @@ -345,34 +357,25 @@ def get_car_params_callback(rc, pm, msgs, fingerprint): CP = CarInterface.get_non_essential_params(fingerprint) CP_SP = CarInterface.get_non_essential_params_sp(CP, fingerprint) else: - can = DummySocket() - sendcan = DummySocket() - - canmsgs = [msg for msg in msgs if msg.which() == "can"] + can_msgs = ([CanData(can.address, can.dat, can.src) for can in m.can] for m in msgs if m.which() == "can") cached_params_raw = params.get("CarParamsCache") - has_cached_cp = cached_params_raw is not None - assert len(canmsgs) != 0, "CAN messages are required for fingerprinting" - assert os.environ.get("SKIP_FW_QUERY", False) or has_cached_cp, \ + assert next(can_msgs, None), "CAN messages are required for fingerprinting" + assert os.environ.get("SKIP_FW_QUERY", False) or cached_params_raw is not None, \ "CarParamsCache is required for fingerprinting. Make sure to keep carParams msgs in the logs." - for m in canmsgs[:300]: - can.send(m.as_builder().to_bytes()) - can_callbacks = can_comm_callbacks(can, sendcan) + def can_recv(wait_for_one: bool = False) -> list[list[CanData]]: + return [next(can_msgs, [])] cached_params = None - if has_cached_cp: + if cached_params_raw is not None: with car.CarParams.from_bytes(cached_params_raw) as _cached_params: cached_params = _cached_params - _CI = get_car(*can_callbacks, lambda obd: None, Params().get_bool("AlphaLongitudinalEnabled"), False, cached_params=cached_params) + _CI = get_car(can_recv, lambda _msgs: None, lambda obd: None, params.get_bool("AlphaLongitudinalEnabled"), False, cached_params=cached_params) CP, CP_SP = _CI.CP, _CI.CP_SP - params.put("CarParams", CP.to_bytes()) - params.put("CarParamsSP", convert_to_capnp(CP_SP).to_bytes()) - - -def selfdrived_rcv_callback(msg, cfg, frame): - return (frame - 1) == 0 or msg.which() == 'carState' + params.put("CarParams", CP.to_bytes(), block=True) + params.put("CarParamsSP", convert_to_capnp(CP_SP).to_bytes(), block=True) def card_rcv_callback(msg, cfg, frame): @@ -389,21 +392,6 @@ def card_rcv_callback(msg, cfg, frame): return len(socks) > 0 -def calibration_rcv_callback(msg, cfg, frame): - # calibrationd publishes 1 calibrationData every 5 cameraOdometry packets. - # should_recv always true to increment frame - return (frame - 1) == 0 or msg.which() == 'cameraOdometry' - - -def torqued_rcv_callback(msg, cfg, frame): - # should_recv always true to increment frame - return (frame - 1) == 0 or msg.which() == 'livePose' - - -def dmonitoringmodeld_rcv_callback(msg, cfg, frame): - return msg.which() == "driverCameraState" - - class ModeldCameraSyncRcvCallback: def __init__(self): self.road_present = False @@ -428,26 +416,13 @@ class ModeldCameraSyncRcvCallback: class MessageBasedRcvCallback: - def __init__(self, trigger_msg_type): + def __init__(self, trigger_msg_type: str, first_frame: bool = False): self.trigger_msg_type = trigger_msg_type + self.first_frame = first_frame def __call__(self, msg, cfg, frame): - return msg.which() == self.trigger_msg_type - - -class FrequencyBasedRcvCallback: - def __init__(self, trigger_msg_type): - self.trigger_msg_type = trigger_msg_type - - def __call__(self, msg, cfg, frame): - if msg.which() != self.trigger_msg_type: - return False - - resp_sockets = [ - s for s in cfg.subs - if frame % max(1, int(SERVICE_LIST[msg.which()].frequency / SERVICE_LIST[s].frequency)) == 0 - ] - return bool(len(resp_sockets)) + # publish on first frame or trigger msg + return ((frame - 1) == 0 and self.first_frame) or msg.which() == self.trigger_msg_type def selfdrived_config_callback(params, cfg, lr): @@ -462,16 +437,16 @@ CONFIGS = [ proc_name="selfdrived", pubs=[ "carState", "deviceState", "pandaStates", "peripheralState", "liveCalibration", "driverMonitoringState", - "longitudinalPlan", "livePose", "liveDelay", "liveParameters", "radarState", - "modelV2", "driverCameraState", "roadCameraState", "wideRoadCameraState", "managerState", - "liveTorqueParameters", "accelerometer", "gyroscope", "carOutput", - "gpsLocationExternal", "gpsLocation", "controlsState", "carControl", "driverAssistance", "alertDebug", + "longitudinalPlan", "livePose", "liveDelay", "liveParameters", "radarState", "modelV2", + "driverCameraState", "roadCameraState", "wideRoadCameraState", "managerState", "liveTorqueParameters", + "accelerometer", "gyroscope", "carOutput", "gpsLocationExternal", "gpsLocation", "controlsState", + "carControl", "driverAssistance", "alertDebug", "audioFeedback", ], subs=["selfdriveState", "onroadEvents"], ignore=["logMonoTime"], config_callback=selfdrived_config_callback, init_callback=get_car_params_callback, - should_recv_callback=selfdrived_rcv_callback, + should_recv_callback=MessageBasedRcvCallback("carState", True), tolerance=NUMPY_TOLERANCE, processing_time=0.004, ), @@ -496,6 +471,7 @@ CONFIGS = [ tolerance=NUMPY_TOLERANCE, processing_time=0.004, main_pub="can", + main_pub_drained=True, ), ProcessConfig( proc_name="radard", @@ -503,7 +479,7 @@ CONFIGS = [ subs=["radarState"], ignore=["logMonoTime"], init_callback=get_car_params_callback, - should_recv_callback=FrequencyBasedRcvCallback("modelV2"), + should_recv_callback=MessageBasedRcvCallback("modelV2"), ), ProcessConfig( proc_name="plannerd", @@ -511,7 +487,7 @@ CONFIGS = [ subs=["longitudinalPlan", "driverAssistance"], ignore=["logMonoTime", "longitudinalPlan.processingDelay", "longitudinalPlan.solverExecutionTime"], init_callback=get_car_params_callback, - should_recv_callback=FrequencyBasedRcvCallback("modelV2"), + should_recv_callback=MessageBasedRcvCallback("modelV2"), tolerance=NUMPY_TOLERANCE, ), ProcessConfig( @@ -520,14 +496,14 @@ CONFIGS = [ subs=["liveCalibration"], ignore=["logMonoTime"], init_callback=get_car_params_callback, - should_recv_callback=calibration_rcv_callback, + should_recv_callback=MessageBasedRcvCallback("cameraOdometry", True), ), ProcessConfig( proc_name="dmonitoringd", pubs=["driverStateV2", "liveCalibration", "carState", "modelV2", "selfdriveState"], subs=["driverMonitoringState"], ignore=["logMonoTime"], - should_recv_callback=FrequencyBasedRcvCallback("driverStateV2"), + should_recv_callback=MessageBasedRcvCallback("driverStateV2"), tolerance=NUMPY_TOLERANCE, ), ProcessConfig( @@ -535,11 +511,11 @@ CONFIGS = [ pubs=[ "cameraOdometry", "accelerometer", "gyroscope", "liveCalibration", "carState" ], - subs=["livePose"], + subs=["liveLocationKalman", "livePose"], ignore=["logMonoTime"], should_recv_callback=MessageBasedRcvCallback("cameraOdometry"), tolerance=NUMPY_TOLERANCE, - unlocked_pubs=["accelerometer", "gyroscope"], + processing_time=0.01, ), ProcessConfig( proc_name="paramsd", @@ -547,7 +523,7 @@ CONFIGS = [ subs=["liveParameters"], ignore=["logMonoTime"], init_callback=get_car_params_callback, - should_recv_callback=FrequencyBasedRcvCallback("livePose"), + should_recv_callback=MessageBasedRcvCallback("livePose"), tolerance=NUMPY_TOLERANCE, processing_time=0.004, ), @@ -572,7 +548,7 @@ CONFIGS = [ subs=["liveTorqueParameters"], ignore=["logMonoTime"], init_callback=get_car_params_callback, - should_recv_callback=torqued_rcv_callback, + should_recv_callback=MessageBasedRcvCallback("livePose", True), tolerance=NUMPY_TOLERANCE, ), ProcessConfig( @@ -584,7 +560,6 @@ CONFIGS = [ tolerance=NUMPY_TOLERANCE, processing_time=0.020, main_pub=vipc_get_endpoint_name("camerad", meta_from_camera_state("roadCameraState").stream), - main_pub_drained=False, vision_pubs=["roadCameraState", "wideRoadCameraState"], ignore_alive_pubs=["wideRoadCameraState"], init_callback=get_car_params_callback, @@ -594,11 +569,10 @@ CONFIGS = [ pubs=["liveCalibration", "driverCameraState"], subs=["driverStateV2"], ignore=["logMonoTime", "driverStateV2.modelExecutionTime", "driverStateV2.gpuExecutionTime"], - should_recv_callback=dmonitoringmodeld_rcv_callback, + should_recv_callback=MessageBasedRcvCallback("driverCameraState"), tolerance=NUMPY_TOLERANCE, processing_time=0.020, main_pub=vipc_get_endpoint_name("camerad", meta_from_camera_state("driverCameraState").stream), - main_pub_drained=False, vision_pubs=["driverCameraState"], ignore_alive_pubs=["driverCameraState"], ), @@ -637,7 +611,7 @@ def get_custom_params_from_lr(lr: LogIterable, initial_state: str = "first") -> if len(live_calibration) > 0: custom_params["CalibrationParams"] = live_calibration[msg_index].as_builder().to_bytes() if len(live_parameters) > 0: - custom_params["LiveParameters"] = live_parameters[msg_index].as_builder().to_bytes() + custom_params["LiveParametersV2"] = live_parameters[msg_index].as_builder().to_bytes() if len(live_torque_parameters) > 0: custom_params["LiveTorqueParameters"] = live_torque_parameters[msg_index].as_builder().to_bytes() @@ -656,14 +630,14 @@ def replay_process_with_name(name: str | Iterable[str], lr: LogIterable, *args, def replay_process( - cfg: ProcessConfig | Iterable[ProcessConfig], lr: LogIterable, frs: dict[str, FrameReader] = None, - fingerprint: str = None, return_all_logs: bool = False, custom_params: dict[str, Any] = None, - captured_output_store: dict[str, dict[str, str]] = None, disable_progress: bool = False + cfg: ProcessConfig | Iterable[ProcessConfig], lr: LogIterable, frs: dict[str, FrameReader] | None = None, + fingerprint: str | None = None, return_all_logs: bool = False, custom_params: dict[str, Any] | None = None, + captured_output_store: dict[str, dict[str, str]] | None = None, disable_progress: bool = False ) -> list[capnp._DynamicStructReader]: - if isinstance(cfg, Iterable): - cfgs = list(cfg) - else: + if isinstance(cfg, ProcessConfig): cfgs = [cfg] + else: + cfgs = list(cfg) all_msgs = migrate_all(lr, manager_states=True, @@ -706,8 +680,8 @@ def _replay_multi_process( all_msgs = sorted(lr, key=lambda msg: msg.logMonoTime) log_msgs = [] + containers = [] try: - containers = [] for cfg in cfgs: container = ProcessContainer(cfg) containers.append(container) @@ -742,6 +716,11 @@ def _replay_multi_process( internal_pub_queue.append(m) heapq.heappush(internal_pub_index_heap, (m.logMonoTime, len(internal_pub_queue) - 1)) log_msgs.extend(output_msgs) + + # flush last set of messages from each process + for container in containers: + last_time = container.last_input_log_mono_time if container.last_input_log_mono_time > 0 else int(time.monotonic() * 1e9) + log_msgs.extend(container.get_output_msgs(last_time)) finally: for container in containers: container.stop() diff --git a/selfdrive/test/process_replay/regen.py b/openpilot/selfdrive/test/process_replay/regen.py similarity index 98% rename from selfdrive/test/process_replay/regen.py rename to openpilot/selfdrive/test/process_replay/regen.py index ec35a5c3ac..c501a4b250 100755 --- a/selfdrive/test/process_replay/regen.py +++ b/openpilot/selfdrive/test/process_replay/regen.py @@ -16,7 +16,7 @@ from openpilot.tools.lib.openpilotci import get_url def regen_segment( - lr: LogIterable, frs: dict[str, Any] = None, + lr: LogIterable, frs: dict[str, Any] | None = None, processes: Iterable[ProcessConfig] = CONFIGS, disable_tqdm: bool = False ) -> list[capnp._DynamicStructReader]: all_msgs = sorted(lr, key=lambda m: m.logMonoTime) diff --git a/selfdrive/test/process_replay/regen_all.py b/openpilot/selfdrive/test/process_replay/regen_all.py similarity index 100% rename from selfdrive/test/process_replay/regen_all.py rename to openpilot/selfdrive/test/process_replay/regen_all.py diff --git a/selfdrive/test/process_replay/test_fuzzy.py b/openpilot/selfdrive/test/process_replay/test_fuzzy.py similarity index 94% rename from selfdrive/test/process_replay/test_fuzzy.py rename to openpilot/selfdrive/test/process_replay/test_fuzzy.py index 723112163e..372b368608 100644 --- a/selfdrive/test/process_replay/test_fuzzy.py +++ b/openpilot/selfdrive/test/process_replay/test_fuzzy.py @@ -2,9 +2,9 @@ import copy import os from hypothesis import given, HealthCheck, Phase, settings import hypothesis.strategies as st -from parameterized import parameterized +from openpilot.common.parameterized import parameterized -from cereal import log +from openpilot.cereal import log from opendbc.car.toyota.values import CAR as TOYOTA from openpilot.selfdrive.test.fuzzy_generation import FuzzyGenerator import openpilot.selfdrive.test.process_replay.process_replay as pr diff --git a/openpilot/selfdrive/test/process_replay/test_processes.py b/openpilot/selfdrive/test/process_replay/test_processes.py new file mode 100755 index 0000000000..d9d827add5 --- /dev/null +++ b/openpilot/selfdrive/test/process_replay/test_processes.py @@ -0,0 +1,235 @@ +#!/usr/bin/env python3 +import argparse +import concurrent.futures +import os +import sys +import traceback +from collections import defaultdict +from tqdm import tqdm +from typing import Any +from opendbc.car.car_helpers import interface_names +from openpilot.common.git import get_commit +from openpilot.tools.lib.openpilotci import get_url +from openpilot.selfdrive.test.process_replay.compare_logs import compare_logs, format_diff +from openpilot.selfdrive.test.process_replay.diff_report import diff_process, diff_report +from openpilot.selfdrive.test.process_replay.process_replay import CONFIGS, PROC_REPLAY_DIR, FAKEDATA, replay_process, \ + check_most_messages_valid +from openpilot.tools.lib.filereader import FileReader +from openpilot.tools.lib.logreader import LogReader, save_log +from openpilot.tools.lib.url_file import URLFile + +source_segments = [ + ("HYUNDAI", "02c45f73a2e5c6e9|2021-01-01--19-08-22--1"), # HYUNDAI.HYUNDAI_SONATA + ("HYUNDAI2", "d545129f3ca90f28|2022-11-07--20-43-08--3"), # HYUNDAI.HYUNDAI_KIA_EV6 (+ QCOM GPS) + ("TOYOTA", "0982d79ebb0de295|2021-01-04--17-13-21--13"), # TOYOTA.TOYOTA_PRIUS + ("TOYOTA2", "0982d79ebb0de295|2021-01-03--20-03-36--6"), # TOYOTA.TOYOTA_RAV4 + ("TOYOTA3", "8011d605be1cbb77|000000cc--8e8d8ec716--6"), # TOYOTA.TOYOTA_COROLLA_TSS2 + ("HONDA", "eb140f119469d9ab|2021-06-12--10-46-24--27"), # HONDA.HONDA_CIVIC (NIDEC) + ("HONDA2", "7d2244f34d1bbcda|2021-06-25--12-25-37--26"), # HONDA.HONDA_ACCORD (BOSCH) + ("CHRYSLER", "4deb27de11bee626|2021-02-20--11-28-55--8"), # CHRYSLER.CHRYSLER_PACIFICA_2018_HYBRID + ("RAM", "17fc16d840fe9d21|2023-04-26--13-28-44--5"), # CHRYSLER.RAM_1500_5TH_GEN + ("SUBARU", "341dccd5359e3c97|2022-09-12--10-35-33--3"), # SUBARU.SUBARU_OUTBACK + ("GM", "376bf99325883932|2022-10-27--13-41-22--1"), # GM.CHEVROLET_BOLT_EUV + ("NISSAN", "35336926920f3571|2021-02-12--18-38-48--46"), # NISSAN.NISSAN_XTRAIL + ("VOLKSWAGEN", "de9592456ad7d144|2021-06-29--11-00-15--6"), # VOLKSWAGEN.VOLKSWAGEN_GOLF + # FIXME the sensor timings are bad in mazda segment, we're not fully testing it, but it should be replaced + ("MAZDA", "bd6a637565e91581|2021-10-30--15-14-53--4"), # MAZDA.MAZDA_CX9_2021 + ("FORD", "54827bf84c38b14f|2023-01-26--21-59-07--4"), # FORD.FORD_BRONCO_SPORT_MK1 + ("RIVIAN", "bc095dc92e101734|000000db--ee9fe46e57--1"), # RIVIAN.RIVIAN_R1_GEN1 + ("TESLA", "2c912ca5de3b1ee9|0000025d--6eb6bcbca4--4"), # TESLA.TESLA_MODEL_Y + + # Enable when port is tested and dashcamOnly is no longer set + #("VOLKSWAGEN2", "3cfdec54aa035f3f|2022-07-19--23-45-10--2"), # VOLKSWAGEN.VOLKSWAGEN_PASSAT_NMS +] + +segments = [ + ("HYUNDAI", "regenAA0FC4ED71E|2025-04-08--22-57-50--0"), + ("HYUNDAI2", "regenAFB9780D823|2025-04-08--23-00-34--0"), + ("TOYOTA", "regen218A4DCFAA1|2025-04-08--22-57-51--0"), + # TODO: get new RAV4 route without enableDsu + # ("TOYOTA2", "regen107352E20EB|2025-04-08--22-57-46--0"), + ("TOYOTA3", "regen1455E3B4BDF|2025-04-09--03-26-06--0"), + ("HONDA", "regenB328FF8BA0A|2025-04-08--22-57-45--0"), + ("HONDA2", "regen6170C8C9A35|2025-04-08--22-57-46--0"), + ("CHRYSLER", "regen5B28FC2A437|2025-04-08--23-04-24--0"), + ("RAM", "regenBF81EA96E08|2025-04-08--23-06-54--0"), + ("SUBARU", "regen7366F13F6A1|2025-04-08--23-07-07--0"), + ("GM", "regen1271097D038|2025-04-09--03-26-00--0"), + ("NISSAN", "regen15D60604EAB|2025-04-08--23-06-59--0"), + ("VOLKSWAGEN", "regen0F2F06C9539|2025-04-08--23-06-56--0"), + ("MAZDA", "regenACF84CCF482|2024-08-30--03-21-55--0"), + ("FORD", "regen755D8CB1E1F|2025-04-08--23-13-43--0"), + ("RIVIAN", "regen5FCAC896BBE|2025-04-08--23-13-35--0"), + ("TESLA", "2c912ca5de3b1ee9|0000025d--6eb6bcbca4--4"), +] + +# dashcamOnly makes don't need to be tested until a full port is done +excluded_interfaces = ["mock", "body", "psa"] + +BASE_URL = "https://raw.githubusercontent.com/commaai/ci-artifacts/refs/heads/process-replay/" +REF_COMMIT_FN = os.path.join(PROC_REPLAY_DIR, "ref_commit") +EXCLUDED_PROCS = {"modeld", "dmonitoringmodeld"} + + +def run_test_process(data): + segment, cfg, args, cur_log_fn, ref_log_path, lr_dat = data + ref_log_msgs = list(LogReader(ref_log_path)) + lr = LogReader.from_bytes(lr_dat) + res, log_msgs = test_process(cfg, lr, segment, ref_log_msgs, cur_log_fn, args.ignore_fields, args.ignore_msgs) + # save logs so we can update refs + save_log(cur_log_fn, log_msgs) + try: + diff_data = diff_process(cfg, ref_log_msgs, log_msgs) + except Exception: + diff_data = traceback.format_exc() + return (segment, cfg.proc_name, res, diff_data) + + +def get_log_data(segment): + r, n = segment.rsplit("--", 1) + with FileReader(get_url(r, n, "rlog.zst")) as f: + return (segment, f.read()) + + +def test_process(cfg, lr, segment, ref_log_msgs, new_log_path, ignore_fields=None, ignore_msgs=None): + if ignore_fields is None: + ignore_fields = [] + if ignore_msgs is None: + ignore_msgs = [] + + try: + log_msgs = replay_process(cfg, lr, disable_progress=True) + except Exception as e: + raise Exception("failed on segment: " + segment) from e + + if not check_most_messages_valid(log_msgs): + return f"Route did not have enough valid messages: {new_log_path}", log_msgs + + # skip this check if the segment is using qcom gps + if cfg.proc_name != 'ubloxd' or any(m.which() in cfg.pubs for m in lr): + seen_msgs = {m.which() for m in log_msgs} + expected_msgs = set(cfg.subs) + if seen_msgs != expected_msgs: + return f"Expected messages: {expected_msgs}, but got: {seen_msgs}", log_msgs + + try: + return compare_logs(ref_log_msgs, log_msgs, ignore_fields + cfg.ignore, ignore_msgs, cfg.tolerance), log_msgs + except Exception as e: + return str(e), log_msgs + + +if __name__ == "__main__": + all_cars = {car for car, _ in segments} + all_procs = {cfg.proc_name for cfg in CONFIGS if cfg.proc_name not in EXCLUDED_PROCS} + + cpu_count = os.cpu_count() or 1 + + parser = argparse.ArgumentParser(description="Regression test to identify changes in a process's output") + parser.add_argument("--whitelist-procs", type=str, nargs="*", default=all_procs, + help="Whitelist given processes from the test (e.g. controlsd)") + parser.add_argument("--whitelist-cars", type=str, nargs="*", default=all_cars, + help="Whitelist given cars from the test (e.g. HONDA)") + parser.add_argument("--blacklist-procs", type=str, nargs="*", default=[], + help="Blacklist given processes from the test (e.g. controlsd)") + parser.add_argument("--blacklist-cars", type=str, nargs="*", default=[], + help="Blacklist given cars from the test (e.g. HONDA)") + parser.add_argument("--ignore-fields", type=str, nargs="*", default=[], + help="Extra fields or msgs to ignore (e.g. driverMonitoringState.events)") + parser.add_argument("--ignore-msgs", type=str, nargs="*", default=[], + help="Msgs to ignore (e.g. carEvents)") + parser.add_argument("--update-refs", action="store_true", + help="Updates reference logs using current commit") + parser.add_argument("-j", "--jobs", type=int, default=max(cpu_count - 2, 1), + help="Max amount of parallel jobs") + args = parser.parse_args() + + tested_procs = set(args.whitelist_procs) - set(args.blacklist_procs) + tested_cars = set(args.whitelist_cars) - set(args.blacklist_cars) + tested_cars = {c.upper() for c in tested_cars} + + full_test = (tested_procs == all_procs) and (tested_cars == all_cars) and all(len(x) == 0 for x in (args.ignore_fields, args.ignore_msgs)) + os.makedirs(os.path.dirname(FAKEDATA), exist_ok=True) + + if args.update_refs: + assert full_test, "Need to run full test when updating refs" + + try: + with open(REF_COMMIT_FN) as f: + ref_commit = f.read().strip() + except FileNotFoundError: + ref_commit = URLFile(BASE_URL + "ref_commit", cache=False).read().decode().strip() + + cur_commit = get_commit() + if not cur_commit: + raise Exception("Couldn't get current commit") + + print(f"***** testing against commit {ref_commit} *****") + + # check to make sure all car brands are tested + if full_test: + untested = (set(interface_names) - set(excluded_interfaces)) - {c.lower() for c in tested_cars} + assert len(untested) == 0, f"Cars missing routes: {str(untested)}" + + log_paths: defaultdict[str, dict[str, dict[str, str]]] = defaultdict(lambda: defaultdict(dict)) + with concurrent.futures.ProcessPoolExecutor(max_workers=args.jobs) as pool: + download_segments = [seg for car, seg in segments if car in tested_cars] + log_data: dict[str, LogReader] = {} + p1 = pool.map(get_log_data, download_segments) + for segment, lr in tqdm(p1, desc="Getting Logs", total=len(download_segments)): + log_data[segment] = lr + + pool_args: Any = [] + for car_brand, segment in segments: + if car_brand not in tested_cars: + continue + + for cfg in CONFIGS: + if cfg.proc_name not in tested_procs: + continue + + # to speed things up, we only test all segments on card + if cfg.proc_name not in ('card', 'controlsd', 'lagd') and car_brand not in ('HYUNDAI', 'TOYOTA'): + continue + + cur_log_fn = os.path.join(FAKEDATA, f"{segment}_{cfg.proc_name}_{cur_commit}.zst".replace("|", "_")) + if args.update_refs: # reference logs will not exist if routes were just regenerated + route, seg_num = segment.rsplit("--", 1) + ref_log_path = get_url(route, seg_num, "rlog.zst") + else: + ref_log_fn = os.path.join(FAKEDATA, f"{segment}_{cfg.proc_name}_{ref_commit}.zst".replace("|", "_")) + ref_log_path = ref_log_fn if os.path.exists(ref_log_fn) else BASE_URL + os.path.basename(ref_log_fn) + + pool_args.append((segment, cfg, args, cur_log_fn, ref_log_path, log_data[segment])) + + log_paths[segment][cfg.proc_name]['ref'] = ref_log_path + log_paths[segment][cfg.proc_name]['new'] = cur_log_fn + + results: Any = defaultdict(dict) + diffs: list = [] + p2 = pool.map(run_test_process, pool_args) + for (segment, proc, result, diff_data) in tqdm(p2, desc="Running Tests", total=len(pool_args)): + results[segment][proc] = result + diffs.append((segment, proc, diff_data)) + + diff_short, diff_long, failed = format_diff(results, log_paths, ref_commit) + if not args.update_refs: + with open(os.path.join(PROC_REPLAY_DIR, "diff.txt"), "w") as f: + f.write(diff_long) + print(diff_short) + + try: + diff_report(diffs, segments) + except Exception: + print(f"failed to generate diff report:\n{traceback.format_exc()}") + + if failed: + print("TEST FAILED") + else: + print("TEST SUCCEEDED") + + else: + with open(REF_COMMIT_FN, "w") as f: + f.write(cur_commit) + print(f"\n\nUpdated reference logs for commit: {cur_commit}") + + sys.exit(int(failed)) diff --git a/selfdrive/test/process_replay/test_regen.py b/openpilot/selfdrive/test/process_replay/test_regen.py similarity index 96% rename from selfdrive/test/process_replay/test_regen.py rename to openpilot/selfdrive/test/process_replay/test_regen.py index 5f26daf786..f4942e486c 100644 --- a/selfdrive/test/process_replay/test_regen.py +++ b/openpilot/selfdrive/test/process_replay/test_regen.py @@ -1,4 +1,4 @@ -from parameterized import parameterized +from openpilot.common.parameterized import parameterized from openpilot.selfdrive.test.process_replay.regen import regen_segment from openpilot.selfdrive.test.process_replay.process_replay import check_openpilot_enabled diff --git a/selfdrive/test/process_replay/vision_meta.py b/openpilot/selfdrive/test/process_replay/vision_meta.py similarity index 100% rename from selfdrive/test/process_replay/vision_meta.py rename to openpilot/selfdrive/test/process_replay/vision_meta.py diff --git a/selfdrive/test/scons_build_test.sh b/openpilot/selfdrive/test/scons_build_test.sh similarity index 82% rename from selfdrive/test/scons_build_test.sh rename to openpilot/selfdrive/test/scons_build_test.sh index 5ffdb4379e..6f6eafcad1 100755 --- a/selfdrive/test/scons_build_test.sh +++ b/openpilot/selfdrive/test/scons_build_test.sh @@ -2,7 +2,7 @@ set -e SCRIPT_DIR=$(dirname "$0") -BASEDIR=$(realpath "$SCRIPT_DIR/../../") +BASEDIR=$(realpath "$SCRIPT_DIR/../../../") cd $BASEDIR # tests that our build system's dependencies are configured properly, @@ -13,7 +13,7 @@ cd $BASEDIR cd $BASEDIR/opendbc_repo/ scons --clean -scons --no-cache --random -j$(nproc) +scons --no-cache --random if ! scons -q; then echo "FAILED: all build products not up to date after first pass." exit 1 diff --git a/openpilot/selfdrive/test/setup_device_ci.sh b/openpilot/selfdrive/test/setup_device_ci.sh new file mode 100755 index 0000000000..60631ce037 --- /dev/null +++ b/openpilot/selfdrive/test/setup_device_ci.sh @@ -0,0 +1,156 @@ +#!/usr/bin/env bash + +set -e +set -x + + +if [ -z "$SOURCE_DIR" ]; then + echo "SOURCE_DIR must be set" + exit 1 +fi + +if [ -z "$GIT_COMMIT" ]; then + echo "GIT_COMMIT must be set" + exit 1 +fi + +if [ -z "$TEST_DIR" ]; then + echo "TEST_DIR must be set" + exit 1 +fi + +# prevent storage from filling up +rm -rf /data/media/0/realdata/* + +rm -rf /data/safe_staging/ || true +if [ -d /data/safe_staging/ ]; then + sudo umount /data/safe_staging/merged/ || true + rm -rf /data/safe_staging/ || true +fi + +CONTINUE_PATH="/data/continue.sh" +tee $CONTINUE_PATH << EOF +#!/usr/bin/env bash + +sudo abctl --set_success + +# patch sshd config +sudo mount -o rw,remount / +sudo sed -i "s,/data/params/d/GithubSshKeys,/usr/comma/setup_keys," /etc/ssh/sshd_config +sudo systemctl daemon-reload +sudo systemctl restart ssh +sudo systemctl restart NetworkManager +sudo systemctl disable ssh-param-watcher.path +sudo systemctl disable ssh-param-watcher.service +sudo mount -o ro,remount / +sudo systemctl stop power_monitor + +while true; do + if ! sudo systemctl is-active -q ssh; then + sudo systemctl start ssh + fi + sleep 5s +done + +sleep infinity +EOF +chmod +x $CONTINUE_PATH + +export GIT_LFS_SKIP_SMUDGE=1 +pull_lfs() { + # The big driving model is not used on these devices yet. Keep its pointer in + # the worktree, but don't download or copy the 1.8 GB LFS object. + LFS_EXCLUDE="openpilot/selfdrive/modeld/models/big_driving_supercombo.onnx" + + git config --local lfs.fetchexclude "$LFS_EXCLUDE" + git lfs pull --exclude="$LFS_EXCLUDE" + if git cat-file -e "HEAD:$LFS_EXCLUDE"; then + rm -f "$LFS_EXCLUDE" + git checkout -- "$LFS_EXCLUDE" + + # `git lfs prune` retains objects referenced by HEAD, even when excluded. + # Remove this one explicitly so safe checkout doesn't rsync it either. + oid=$(git show "HEAD:$LFS_EXCLUDE" | sed -n 's/^oid sha256://p') + lfs_objects=$(git lfs env | sed -n 's/^LocalMediaDir=//p') + if [[ "$oid" =~ ^[0-9a-f]{64}$ && -n "$lfs_objects" ]]; then + rm -f "$lfs_objects/${oid:0:2}/${oid:2:2}/$oid" + fi + fi +} + +safe_checkout() { + # completely clean TEST_DIR + + cd $SOURCE_DIR + + # cleanup orphaned locks + find .git -type f -name "*.lock" -exec rm {} + + + git reset --hard + git fetch --no-tags --no-recurse-submodules -j4 --verbose --depth 1 origin $GIT_COMMIT + find . -maxdepth 1 -not -path './.git' -not -name '.' -not -name '..' -exec rm -rf '{}' \; + git reset --hard $GIT_COMMIT + git checkout $GIT_COMMIT + git clean -xdff + git submodule sync + git submodule foreach --recursive "git reset --hard && git clean -xdff" + git submodule update --init --recursive + git submodule foreach --recursive "git reset --hard && git clean -xdff" + + pull_lfs + + echo "git checkout done, t=$SECONDS" + du -hs $SOURCE_DIR $SOURCE_DIR/.git + + rsync -a --delete $SOURCE_DIR $TEST_DIR +} + +unsafe_checkout() {( set -e + # checkout directly in test dir, leave old build products + + cd $TEST_DIR + + # cleanup orphaned locks + find .git -type f -name "*.lock" -exec rm {} + + + git fetch --no-tags --no-recurse-submodules -j8 --verbose --depth 1 origin $GIT_COMMIT + git checkout --force --no-recurse-submodules $GIT_COMMIT + git reset --hard $GIT_COMMIT + git clean -dff + git submodule sync + git submodule foreach --recursive "git reset --hard && git clean -df" + git submodule update --init --recursive + git submodule foreach --recursive "git reset --hard && git clean -df" + + pull_lfs +)} + +export GIT_PACK_THREADS=8 + +# set up environment +if [ ! -d "$SOURCE_DIR" ]; then + git clone https://github.com/commaai/openpilot.git $SOURCE_DIR +fi + +if [ ! -z "$UNSAFE" ]; then + echo "trying unsafe checkout" + set +e + unsafe_checkout + if [[ "$?" -ne 0 ]]; then + safe_checkout + fi + set -e +else + echo "doing safe checkout" + safe_checkout +fi + +# submodule package symlinks for PYTHONPATH imports on device (same as launch_chffrplus.sh) +cd $TEST_DIR +ln -sfn msgq_repo/msgq msgq +ln -sfn opendbc_repo/opendbc opendbc +ln -sfn rednose_repo/rednose rednose +ln -sfn teleoprtc_repo/teleoprtc teleoprtc +ln -sfn tinygrad_repo/tinygrad tinygrad + +echo "$TEST_DIR synced with $GIT_COMMIT, t=$SECONDS" diff --git a/selfdrive/test/test_onroad.py b/openpilot/selfdrive/test/test_onroad.py similarity index 81% rename from selfdrive/test/test_onroad.py rename to openpilot/selfdrive/test/test_onroad.py index f98e3bd88c..b15d890452 100644 --- a/selfdrive/test/test_onroad.py +++ b/openpilot/selfdrive/test/test_onroad.py @@ -8,18 +8,17 @@ import time import numpy as np from collections import Counter, defaultdict from pathlib import Path -from tabulate import tabulate +from openpilot.common.utils import tabulate -from cereal import log -import cereal.messaging as messaging -from cereal.services import SERVICE_LIST +from openpilot.cereal import log +import openpilot.cereal.messaging as messaging +from openpilot.cereal.services import SERVICE_LIST from openpilot.common.basedir import BASEDIR from openpilot.common.timeout import Timeout from openpilot.common.params import Params from openpilot.selfdrive.selfdrived.events import EVENTS, ET from openpilot.selfdrive.test.helpers import set_params_enabled, release_only -from openpilot.system.hardware import HARDWARE -from openpilot.system.hardware.hw import Paths +from openpilot.common.hardware.hw import Paths from openpilot.tools.lib.logreader import LogReader from openpilot.tools.lib.log_time_series import msgs_to_time_series @@ -33,53 +32,44 @@ CPU usage budget TEST_DURATION = 25 LOG_OFFSET = 8 -MAX_TOTAL_CPU = 280. # total for all 8 cores +MAX_TOTAL_CPU = 350. # total for all 8 cores PROCS = { # Baseline CPU usage by process - "selfdrive.controls.controlsd": 16.0, - "selfdrive.selfdrived.selfdrived": 16.0, - "selfdrive.car.card": 26.0, + "openpilot.selfdrive.controls.controlsd": 16.0, + "openpilot.selfdrive.selfdrived.selfdrived": 16.0, + "openpilot.selfdrive.car.card": 26.0, "./loggerd": 14.0, "./encoderd": 13.0, "./camerad": 10.0, - "selfdrive.controls.plannerd": 8.0, - "./ui": 18.0, - "system.sensord.sensord": 13.0, - "selfdrive.controls.radard": 2.0, - "selfdrive.modeld.modeld": 22.0, - "selfdrive.modeld.dmonitoringmodeld": 18.0, - "system.hardware.hardwared": 4.0, - "selfdrive.locationd.calibrationd": 2.0, - "selfdrive.locationd.torqued": 5.0, - "selfdrive.locationd.locationd": 25.0, - "selfdrive.locationd.paramsd": 9.0, - "selfdrive.locationd.lagd": 11.0, - "selfdrive.ui.soundd": 3.0, - "selfdrive.monitoring.dmonitoringd": 4.0, - "./proclogd": 2.0, - "system.logmessaged": 1.0, - "system.tombstoned": 0, - "./logcatd": 1.0, - "system.micd": 5.0, - "system.timed": 0, - "selfdrive.pandad.pandad": 0, - "system.statsd": 1.0, - "system.loggerd.uploader": 15.0, - "system.loggerd.deleter": 1.0, + "openpilot.selfdrive.controls.plannerd": 8.0, + "openpilot.selfdrive.ui.ui": 40.0, + "openpilot.system.sensord.sensord": 13.0, + "openpilot.selfdrive.controls.radard": 2.0, + "openpilot.selfdrive.modeld.modeld": 22.0, + "openpilot.selfdrive.modeld.dmonitoringmodeld": 18.0, + "openpilot.system.hardware.hardwared": 4.0, + "openpilot.selfdrive.locationd.calibrationd": 2.0, + "openpilot.selfdrive.locationd.torqued": 5.0, + "openpilot.selfdrive.locationd.locationd": 25.0, + "openpilot.selfdrive.locationd.paramsd": 9.0, + "openpilot.selfdrive.locationd.lagd": 11.0, + "openpilot.selfdrive.ui.soundd": 3.0, + "openpilot.selfdrive.ui.feedback.feedbackd": 1.0, + "openpilot.selfdrive.monitoring.dmonitoringd": 4.0, + "openpilot.system.proclogd": 7.0, + "openpilot.system.logmessaged": 1.0, + "openpilot.system.tombstoned": 0, + "openpilot.system.journald": 1.0, + "openpilot.system.micd": 5.0, + "openpilot.system.timed": 0, + "openpilot.selfdrive.pandad.pandad": 0, + "openpilot.system.loggerd.uploader": 15.0, + "openpilot.system.loggerd.deleter": 1.0, + "./pandad": 19.0, + "openpilot.system.qcomgpsd.qcomgpsd": 1.0, + "openpilot.common.hardware.tici.modem": 10.0, } -PROCS.update({ - "tici": { - "./pandad": 5.0, - "./ubloxd": 1.0, - "system.ubloxd.pigeond": 6.0, - }, - "tizi": { - "./pandad": 19.0, - "system.qcomgpsd.qcomgpsd": 1.0, - } -}.get(HARDWARE.get_device_type(), {})) - TIMINGS = { # rtols: max/min, rsd "can": [2.5, 0.35], @@ -128,9 +118,10 @@ class TestOnroad: # setup env params = Params() params.remove("CurrentRoute") - params.put_bool("RecordFront", True) + params.put_bool("RecordFront", True, block=True) set_params_enabled() os.environ['REPLAY'] = '1' + os.environ['MSGQ_PREALLOC'] = '1' os.environ['TESTING_CLOSET'] = '1' if os.path.exists(Paths.log_root()): shutil.rmtree(Paths.log_root()) @@ -138,7 +129,7 @@ class TestOnroad: # start manager and run openpilot for TEST_DURATION proc = None try: - manager_path = os.path.join(BASEDIR, "system/manager/manager.py") + manager_path = os.path.join(BASEDIR, "openpilot/system/manager/manager.py") cls.manager_st = time.monotonic() proc = subprocess.Popen(["python", manager_path]) @@ -147,7 +138,7 @@ class TestOnroad: while not sm.seen['carState']: sm.update(1000) - route = params.get("CurrentRoute", encoding="utf-8") + route = params.get("CurrentRoute") assert route is not None segs = list(Path(Paths.log_root()).glob(f"{route}--*")) @@ -184,12 +175,13 @@ class TestOnroad: if s in ('ubloxGnss', 'ubloxRaw', 'gnssMeasurements', 'gpsLocation', 'gpsLocationExternal', 'qcomGnss'): continue + duration = TEST_DURATION - 5.0 # subtract some selfdrived initializing time with subtests.test(service=s): - assert len(msgs) >= math.floor(SERVICE_LIST[s].frequency*int(TEST_DURATION*0.8)) + assert len(msgs) >= math.floor(SERVICE_LIST[s].frequency*int(duration*0.8)) def test_manager_starting_time(self): st = self.ts['managerState']['t'][0] - assert (st - self.manager_st) < 12.5, f"manager.py took {st - self.manager_st}s to publish the first 'managerState' msg" + assert (st - self.manager_st) < 15.0, f"manager.py took {st - self.manager_st}s to publish the first 'managerState' msg" def test_cloudlog_size(self): msgs = self.msgs['logMessage'] @@ -216,7 +208,9 @@ class TestOnroad: result += "-------------- UI Draw Timing ------------------\n" result += "------------------------------------------------\n" - ts = self.ts['uiDebug']['drawTimeMillis'] + # other processes preempt ui while starting up + offset = int(20 * LOG_OFFSET) + ts = self.ts['uiDebug']['cpuTimeMillis'][offset:] result += f"min {min(ts):.2f}ms\n" result += f"max {max(ts):.2f}ms\n" result += f"std {np.std(ts):.2f}ms\n" @@ -225,7 +219,7 @@ class TestOnroad: print(result) assert max(ts) < 250. - assert np.mean(ts) < 10. + assert np.mean(ts) < 20. # TODO: ~6-11ms, increase consistency #self.assertLess(np.std(ts), 5.) # some slow frames are expected since camerad/modeld can preempt ui @@ -289,13 +283,17 @@ class TestOnroad: print("\n------------------------------------------------") print("--------------- Memory Usage -------------------") print("------------------------------------------------") + + from openpilot.selfdrive.test.mem_usage import print_report + print_report(self.msgs['procLog'], self.msgs['deviceState']) + offset = int(SERVICE_LIST['deviceState'].frequency * LOG_OFFSET) mems = [m.deviceState.memoryUsagePercent for m in self.msgs['deviceState'][offset:]] - print("Memory usage: ", mems) + print("MSGQ (/dev/shm/) usage: ", subprocess.check_output(["du", "-hs", "/dev/shm"]).split()[0].decode()) # check for big leaks. note that memory usage is # expected to go up while the MSGQ buffers fill up - assert np.average(mems) <= 65, "Average memory usage above 65%" + assert np.average(mems) <= 80, "Average memory usage too high" assert np.max(np.diff(mems)) <= 4, "Max memory increase too high" assert np.average(np.diff(mems)) <= 1, "Average memory increase too high" @@ -332,25 +330,28 @@ class TestOnroad: assert np.all(eof_sof_diff > 0) assert np.all(eof_sof_diff < 50*1e6) - first_fid = {c: min(self.ts[c]['frameId']) for c in cams} + first_fid = {min(self.ts[c]['frameId']) for c in cams} + assert len(first_fid) == 1, "Cameras don't start on same frame ID" if cam.endswith('CameraState'): # camerad guarantees that all cams start on frame ID 0 # (note loggerd also needs to start up fast enough to catch it) - assert set(first_fid.values()) == {0, }, "Cameras don't start on frame ID 0" - else: - # encoder guarantees all cams start on the same frame ID - assert len(set(first_fid.values())) == 1, "Cameras don't start on same frame ID" + assert next(iter(first_fid)) < 100, "Cameras start on frame ID too high" # we don't do a full segment rotation, so these might not match exactly - last_fid = {c: max(self.ts[c]['frameId']) for c in cams} - assert max(last_fid.values()) - min(last_fid.values()) < 10 + last_fid = {max(self.ts[c]['frameId']) for c in cams} + assert max(last_fid) - min(last_fid) < 10 - start, end = min(first_fid.values()), min(last_fid.values()) + start, end = min(first_fid), min(last_fid) for i in range(end-start): - ts = {c: round(self.ts[c]['timestampSof'][i]/1e6, 1) for c in cams} + # road and wide cameras (first two) should be synced within 2ms + ts = {c: round(self.ts[c]['timestampSof'][i]/1e6, 1) for c in cams[:2]} diff = (max(ts.values()) - min(ts.values())) assert diff < 2, f"Cameras not synced properly: frame_id={start+i}, {diff=:.1f}ms, {ts=}" + # driver camera should be staggered ~25ms from road camera + offset_ms = abs(self.ts[cams[2]]['timestampSof'][i] - self.ts[cams[0]]['timestampSof'][i]) / 1e6 + assert 20 < offset_ms < 30, f"driver camera stagger out of range at frame {start+i}: {offset_ms:.1f}ms" + def test_camera_encoder_matches(self, subtests): # sanity check that the frame metadata is consistent with the encoded frames pairs = [('roadCameraState', 'roadEncodeIdx'), @@ -370,23 +371,6 @@ class TestOnroad: assert enc_sof == cam_sof, f"SOF mismatch: frameId={fid}, enc_sof={enc_sof}, cam_sof={cam_sof}" assert enc_eof == cam_eof, f"EOF mismatch: frameId={fid}, enc_eof={enc_eof}, cam_eof={cam_eof}" - def test_mpc_execution_timings(self): - result = "\n" - result += "------------------------------------------------\n" - result += "----------------- MPC Timing ------------------\n" - result += "------------------------------------------------\n" - - cfgs = [("longitudinalPlan", 0.05, 0.05),] - for (s, instant_max, avg_max) in cfgs: - ts = [getattr(m, s).solverExecutionTime for m in self.msgs[s]] - assert max(ts) < instant_max, f"high '{s}' execution time: {max(ts)}" - assert np.mean(ts) < avg_max, f"high avg '{s}' execution time: {np.mean(ts)}" - result += f"'{s}' execution time: min {min(ts):.5f}s\n" - result += f"'{s}' execution time: max {max(ts):.5f}s\n" - result += f"'{s}' execution time: mean {np.mean(ts):.5f}s\n" - result += "------------------------------------------------\n" - print(result) - def test_model_execution_timings(self, subtests): result = "\n" result += "------------------------------------------------\n" @@ -401,9 +385,7 @@ class TestOnroad: ("driverStateV2", 0.3, 0.05), ] for (s, instant_max, avg_max) in cfgs: - ts = [getattr(m, s).modelExecutionTime for m in self.msgs[s]] - # TODO some init can happen in first iteration - ts = ts[1:] + ts = [getattr(m, s).modelExecutionTime for m in self.msgs[s] if (m.logMonoTime*1e-9 - self.ts[s]['t'][0]) > LOG_OFFSET] result += f"'{s}' execution time: min {min(ts):.5f}s\n" result += f"'{s}' execution time: max {max(ts):.5f}s\n" result += f"'{s}' execution time: mean {np.mean(ts):.5f}s\n" diff --git a/system/hardware/tici/tests/test_power_draw.py b/openpilot/selfdrive/test/test_power_draw.py similarity index 86% rename from system/hardware/tici/tests/test_power_draw.py rename to openpilot/selfdrive/test/test_power_draw.py index db0fab884c..9bc012ceaa 100644 --- a/system/hardware/tici/tests/test_power_draw.py +++ b/openpilot/selfdrive/test/test_power_draw.py @@ -3,18 +3,18 @@ import pytest import time import numpy as np from dataclasses import dataclass -from tabulate import tabulate +from openpilot.common.utils import tabulate -import cereal.messaging as messaging -from cereal.services import SERVICE_LIST +import openpilot.cereal.messaging as messaging +from openpilot.cereal.services import SERVICE_LIST from opendbc.car.car_helpers import get_demo_car_params from openpilot.common.mock import mock_messages from openpilot.common.params import Params -from openpilot.system.hardware.tici.power_monitor import get_power +from openpilot.common.hardware.tici.power_monitor import get_power from openpilot.system.manager.process_config import managed_processes from openpilot.system.manager.manager import manager_cleanup -SAMPLE_TIME = 8 # seconds to sample power +SAMPLE_TIME = 2 # seconds to sample power MAX_WARMUP_TIME = 30 # seconds to wait for SAMPLE_TIME consecutive valid samples @dataclass @@ -31,9 +31,9 @@ class Proc: PROCS = [ - Proc(['camerad'], 1.75, msgs=['roadCameraState', 'wideRoadCameraState', 'driverCameraState']), - Proc(['modeld'], 1.12, atol=0.2, msgs=['modelV2']), - Proc(['dmonitoringmodeld'], 0.6, msgs=['driverStateV2']), + Proc(['camerad'], 1.65, atol=0.4, msgs=['roadCameraState', 'wideRoadCameraState', 'driverCameraState']), + Proc(['modeld'], 1.5, atol=0.2, msgs=['modelV2']), + Proc(['dmonitoringmodeld'], 0.65, atol=0.35, msgs=['driverStateV2']), Proc(['encoderd'], 0.23, msgs=[]), ] @@ -42,10 +42,7 @@ PROCS = [ class TestPowerDraw: def setup_method(self): - Params().put("CarParams", get_demo_car_params().to_bytes()) - - # wait a bit for power save to disable - time.sleep(5) + Params().put("CarParams", get_demo_car_params().to_bytes(), block=True) def teardown_method(self): manager_cleanup() diff --git a/selfdrive/test/update_ci_routes.py b/openpilot/selfdrive/test/update_ci_routes.py similarity index 96% rename from selfdrive/test/update_ci_routes.py rename to openpilot/selfdrive/test/update_ci_routes.py index 2bf06b4860..40f74ee93c 100755 --- a/selfdrive/test/update_ci_routes.py +++ b/openpilot/selfdrive/test/update_ci_routes.py @@ -6,7 +6,6 @@ import sys from collections.abc import Iterable from tqdm import tqdm - from opendbc.car.tests.routes import routes as test_car_models_routes from openpilot.selfdrive.test.process_replay.test_processes import source_segments as replay_segments from openpilot.tools.lib.azure_container import AzureContainer @@ -19,7 +18,7 @@ SOURCES: list[AzureContainer] = [ DEST = OpenpilotCIContainer -def upload_route(path: str, exclude_patterns: Iterable[str] = None) -> None: +def upload_route(path: str, exclude_patterns: Iterable[str] | None = None) -> None: if exclude_patterns is None: exclude_patterns = [r'dcamera\.hevc'] diff --git a/openpilot/selfdrive/ui/.gitignore b/openpilot/selfdrive/ui/.gitignore new file mode 100644 index 0000000000..30ae77d885 --- /dev/null +++ b/openpilot/selfdrive/ui/.gitignore @@ -0,0 +1,4 @@ +installer/installers/* + +tests/diff/report +.coverage diff --git a/openpilot/selfdrive/ui/SConscript b/openpilot/selfdrive/ui/SConscript new file mode 100644 index 0000000000..d187b4ca3c --- /dev/null +++ b/openpilot/selfdrive/ui/SConscript @@ -0,0 +1,55 @@ +from pathlib import Path +import importlib.util + +Import('env', 'arch', 'common') + +# build the fonts +generator = File("#openpilot/selfdrive/assets/fonts/process.py") +source_files = Glob("#openpilot/selfdrive/assets/fonts/*.ttf") + Glob("#openpilot/selfdrive/assets/fonts/*.otf") +output_files = [ + (f"#{Path(f.path).with_suffix('.fnt')}", f"#{Path(f.path).with_suffix('.png')}") + for f in source_files + if "NotoColor" not in f.name +] +env.Command( + target=output_files, + source=[generator, source_files], + action=f"python3 {generator}", +) + + +if GetOption('extras') and arch == "larch64": + # build installers + raylib_dir = Path(importlib.util.find_spec("raylib").submodule_search_locations[0]) / "install" + raylib_env = env.Clone() + raylib_env['CPPPATH'] += [str(raylib_dir / "include")] + raylib_env['LIBPATH'] += [str(raylib_dir / "lib")] + raylib_env['LINKFLAGS'].append('-Wl,-strip-debug') + + raylib_libs = common + ["raylib_comma", "GLESv2", "EGL", "gbm", "drm"] + + release = "release3" + installers = [ + ("openpilot", release), + ("openpilot_test", f"{release}-staging"), + ("openpilot_nightly", "nightly"), + ("openpilot_internal", "nightly-dev"), + ] + + cont = raylib_env.Command("installer/continue_openpilot.o", "installer/continue_openpilot.sh", + "ld -r -b binary -o $TARGET $SOURCE") + inter = raylib_env.Command("installer/inter_ttf.o", "installer/inter-ascii.ttf", + "ld -r -b binary -o $TARGET $SOURCE") + inter_bold = raylib_env.Command("installer/inter_bold.o", "../assets/fonts/Inter-Bold.ttf", + "ld -r -b binary -o $TARGET $SOURCE") + inter_light = raylib_env.Command("installer/inter_light.o", "../assets/fonts/Inter-Light.ttf", + "ld -r -b binary -o $TARGET $SOURCE") + for name, branch in installers: + d = {'BRANCH': f"'\"{branch}\"'"} + if "internal" in name: + d['INTERNAL'] = "1" + + obj = raylib_env.Object(f"installer/installers/installer_{name}.o", ["installer/installer.cc"], CPPDEFINES=d) + f = raylib_env.Program(f"installer/installers/installer_{name}", [obj, cont, inter, inter_bold, inter_light], LIBS=raylib_libs) + # keep installers small + assert f[0].get_size() < 2500*1e3, f[0].get_size() diff --git a/openpilot/selfdrive/ui/__init__.py b/openpilot/selfdrive/ui/__init__.py new file mode 100644 index 0000000000..b07e842f1a --- /dev/null +++ b/openpilot/selfdrive/ui/__init__.py @@ -0,0 +1 @@ +UI_BORDER_SIZE = 30 diff --git a/selfdrive/pandad/tests/__init__.py b/openpilot/selfdrive/ui/body/__init__.py similarity index 100% rename from selfdrive/pandad/tests/__init__.py rename to openpilot/selfdrive/ui/body/__init__.py diff --git a/openpilot/selfdrive/ui/body/animations.py b/openpilot/selfdrive/ui/body/animations.py new file mode 100644 index 0000000000..302f8989bf --- /dev/null +++ b/openpilot/selfdrive/ui/body/animations.py @@ -0,0 +1,281 @@ +from dataclasses import dataclass +from enum import Enum +import time + + +class AnimationMode(Enum): + ONCE_FORWARD = 1 + ONCE_FORWARD_BACKWARD = 2 + REPEAT_FORWARD = 3 + REPEAT_FORWARD_BACKWARD = 4 + + +@dataclass +class Animation: + frames: list[list[tuple[int, int]]] + starting_frames: list[list[tuple[int, int]]] | None = None # played once before the main loop + frame_duration: float = 0.15 # seconds each frame is shown + mode: AnimationMode = AnimationMode.REPEAT_FORWARD_BACKWARD + repeat_interval: float = 5.0 # seconds between animation restarts (only for REPEAT modes) + hold_end: float = 0.0 # seconds to hold the last frame before playing backward (only for *_BACKWARD modes) + left_turn_remove: list[tuple[int, int]] | None = None # dots to remove from frame when turning left + right_turn_remove: list[tuple[int, int]] | None = None # dots to remove from frame when turning right + + +# --- Animation Helper Functions --- + +def _mirror(dots: list[tuple[int, int]]) -> list[tuple[int, int]]: + """Mirror a component from the left side of the face to the right""" + return [(r, 15 - c) for r, c in dots] + + +def _mirror_no_flip(dots: list[tuple[int, int]]) -> list[tuple[int, int]]: + """Move a component to the mirrored position on the right half without flipping its shape.""" + min_c = min(c for _, c in dots) + max_c = max(c for _, c in dots) + return [(r, 15 - max_c - min_c + c) for r, c in dots] + + +def _shift(dots: list[tuple[int, int]], rc: tuple[int, int]) -> list[tuple[int, int]]: + dr, dc = rc + return [(r + dr, c + dc) for r, c in dots] + + +def _make_frame(left_eye: list[tuple[int, int]], right_eye: list[tuple[int, int]], + left_brow: list[tuple[int, int]], right_brow: list[tuple[int, int]], + mouth: list[tuple[int, int]]) -> list[tuple[int, int]]: + return left_eye + left_brow + right_eye + right_brow + mouth + + +# --- Animation Helper Components --- + +# Eyes (left side) +EYE_OPEN = [ + (2, 2), (2, 3), +(3, 1), (3, 2), (3, 3), (3, 4), +(4, 1), (4, 2), (4, 3), (4, 4), + (5, 2), (5, 3) +] +EYE_HALF = [ +(4, 1), (4, 2), (4, 3), (4, 4), + (5, 2), (5, 3) +] +EYE_CLOSED = [ +(4, 1), (4, 4), + (5, 2), (5, 3), +] +EYE_LEFT_LOOK = [ + (2, 2), (2, 3), +(3, 1), (3, 2), +(4, 1), (4, 2), + (5, 2), (5, 3), +] +EYE_RIGHT_LOOK = [ + (2, 2), (2, 3), + (3, 3), (3, 4), + (4, 3), (4, 4), + (5, 2), (5, 3), +] + +# Eyebrows (left side) +BROW_HIGH = [ + (0, 1), (0, 2), +(1, 0), +] +BROW_LOWERED = [ + (1, 1), (1, 2), +(2, 0) +] +BROW_STRAIGHT = [(1, 0), (1, 1), (1, 2)] +BROW_DOWN = [ +(0, 1), (0, 2), + (1, 3) +] + +# Mouths (centered, not mirrored) +MOUTH_SMILE = [ +(6, 6), (6, 9), + (7, 7), (7, 8), +] +MOUTH_NORMAL = [(7, 7), (7, 8)] +MOUTH_SAD = [ + (6, 7), (6, 8), +(7, 6), (7, 9) +] + +# --- Animations --- + +NORMAL = Animation( + frames=[ + _make_frame(EYE_OPEN, _mirror(EYE_OPEN), BROW_HIGH, _mirror(BROW_HIGH), MOUTH_SMILE), + _make_frame(EYE_HALF, _mirror(EYE_HALF), BROW_HIGH, _mirror(BROW_HIGH), MOUTH_SMILE), + _make_frame(EYE_CLOSED, _mirror(EYE_CLOSED), BROW_LOWERED, _mirror(BROW_LOWERED), MOUTH_SMILE), + ], + left_turn_remove=[ + (3, 3), (3, 4), + (4, 3), (4, 4), + ] + _mirror_no_flip([ + (3, 1), (3, 2), + (4, 1), (4, 2), + ]), + right_turn_remove=[ + (3, 1), (3, 2), + (4, 1), (4, 2), + ] + _mirror_no_flip([ + (3, 3), (3, 4), + (4, 3), (4, 4), + ]) +) + +ASLEEP = Animation( + frames=[ + _make_frame(EYE_CLOSED, _mirror(EYE_CLOSED), [], [], MOUTH_NORMAL), + ], +) + +SLEEPY = Animation( + frames=[ + _make_frame(EYE_CLOSED, _mirror(EYE_CLOSED), _shift(BROW_STRAIGHT, (1, 0)), [], MOUTH_NORMAL), + _make_frame(EYE_HALF, _mirror(EYE_CLOSED), BROW_LOWERED, [], MOUTH_NORMAL), + _make_frame(EYE_OPEN, _mirror(EYE_CLOSED), BROW_HIGH, [], MOUTH_NORMAL) + ], + frame_duration=0.25, + mode=AnimationMode.ONCE_FORWARD_BACKWARD, + repeat_interval=10, + hold_end=1.5, +) + +INQUISITIVE = Animation( + frames=[ + _make_frame(EYE_OPEN, _mirror(EYE_OPEN), BROW_HIGH, _mirror(BROW_HIGH), MOUTH_SMILE), + + _make_frame(EYE_LEFT_LOOK, _mirror(EYE_RIGHT_LOOK), BROW_HIGH, _mirror(BROW_HIGH), MOUTH_SMILE), + _make_frame(_shift(EYE_LEFT_LOOK, (0, -1)), _shift(_mirror(EYE_RIGHT_LOOK), (0, -1)), BROW_HIGH, _mirror(BROW_HIGH), MOUTH_SMILE), + _make_frame(_shift(EYE_LEFT_LOOK, (0, -1)), _shift(_mirror(EYE_RIGHT_LOOK), (0, -1)), BROW_HIGH, _mirror(BROW_HIGH), MOUTH_SMILE), + _make_frame(_shift(EYE_LEFT_LOOK, (0, -1)), _shift(_mirror(EYE_RIGHT_LOOK), (0, -1)), BROW_HIGH, _mirror(BROW_HIGH), MOUTH_SMILE), + _make_frame(EYE_LEFT_LOOK, _mirror(EYE_RIGHT_LOOK), BROW_HIGH, _mirror(BROW_HIGH), MOUTH_SMILE), + + _make_frame(EYE_RIGHT_LOOK, _mirror(EYE_LEFT_LOOK), BROW_HIGH, _mirror(BROW_HIGH), MOUTH_SMILE), + _make_frame(_shift(EYE_RIGHT_LOOK, (0, 1)), _shift(_mirror(EYE_LEFT_LOOK), (0, 1)), BROW_HIGH, _mirror(BROW_HIGH), MOUTH_SMILE), + _make_frame(_shift(EYE_RIGHT_LOOK, (0, 1)), _shift(_mirror(EYE_LEFT_LOOK), (0, 1)), BROW_HIGH, _mirror(BROW_HIGH), MOUTH_SMILE), + _make_frame(_shift(EYE_RIGHT_LOOK, (0, 1)), _shift(_mirror(EYE_LEFT_LOOK), (0, 1)), BROW_HIGH, _mirror(BROW_HIGH), MOUTH_SMILE), + _make_frame(EYE_RIGHT_LOOK, _mirror(EYE_LEFT_LOOK), BROW_HIGH, _mirror(BROW_HIGH), MOUTH_SMILE), + + _make_frame(EYE_OPEN, _mirror(EYE_OPEN), BROW_HIGH, _mirror(BROW_HIGH), MOUTH_SMILE), + ], + mode=AnimationMode.REPEAT_FORWARD, + frame_duration=0.15, + repeat_interval=10 +) + +WINK = Animation( + frames=[ + _make_frame(EYE_OPEN, _mirror(EYE_OPEN), BROW_HIGH, _mirror(BROW_HIGH), MOUTH_SMILE), + _make_frame(EYE_OPEN, _mirror(EYE_CLOSED), BROW_HIGH, _mirror(_shift(BROW_DOWN, (0, 2))), MOUTH_SMILE), + ], + mode=AnimationMode.ONCE_FORWARD_BACKWARD, + frame_duration=0.75, +) + + +# --- Face Animator Class --- + +class FaceAnimator: + def __init__(self, animation: Animation): + self._animation = animation + self._next: Animation | None = None + self._start_time = time.monotonic() + self._rewinding = False + self._rewind_start: float = 0.0 + self._rewind_from: int = 0 + self._seen_nonzero = False + + def set_animation(self, animation: Animation): + if animation is not self._animation: + self._next = animation + + def get_dots(self) -> list[tuple[int, int]]: + now = time.monotonic() + elapsed = now - self._start_time + + # Handle rewind for forward-only animations + if self._rewinding: + rewind_elapsed = now - self._rewind_start + frames_back = round(rewind_elapsed / self._animation.frame_duration) + frame_index = self._rewind_from - frames_back + if frame_index <= 0: + if self._next is None: + self._rewinding = False + return self._animation.frames[0] + return self._switch_to_next(now, self._next) + return self._animation.frames[frame_index] + + # Play starting frames first (once) + starting = self._animation.starting_frames or [] + starting_duration = len(starting) * self._animation.frame_duration + if starting and elapsed < starting_duration: + frame_index = min(int(elapsed / self._animation.frame_duration), len(starting) - 1) + return starting[frame_index] + + # Main loop + loop_elapsed = elapsed - starting_duration if starting else elapsed + frame_index = _get_frame_index(self._animation, loop_elapsed, gap_first=bool(starting)) + + if frame_index != 0: + self._seen_nonzero = True + + if self._next is not None: + if frame_index == 0 and (len(self._animation.frames) == 1 or self._seen_nonzero): + return self._switch_to_next(now, self._next) + # No natural return to frame 0 — start rewinding + if self._animation.mode in (AnimationMode.ONCE_FORWARD, AnimationMode.REPEAT_FORWARD): + self._rewinding = True + self._rewind_start = now + self._rewind_from = frame_index + + return self._animation.frames[frame_index] + + def _switch_to_next(self, now: float, animation: Animation) -> list[tuple[int, int]]: + self._animation = animation + self._next = None + self._rewinding = False + self._seen_nonzero = False + self._start_time = now + return self._animation.frames[0] + + +def _get_frame_index(animation: Animation, elapsed: float, gap_first: bool = False) -> int: + """Get the current frame index given elapsed time and animation mode.""" + num_frames = len(animation.frames) + if num_frames == 1: + return 0 + + fd = animation.frame_duration + has_backward = animation.mode in (AnimationMode.ONCE_FORWARD_BACKWARD, AnimationMode.REPEAT_FORWARD_BACKWARD) + repeats = animation.mode in (AnimationMode.REPEAT_FORWARD, AnimationMode.REPEAT_FORWARD_BACKWARD) + + forward_duration = num_frames * fd + backward_frames = max(num_frames - 2, 0) if has_backward else 0 + hold = animation.hold_end if has_backward else 0.0 + cycle_duration = forward_duration + hold + backward_frames * fd + + if not repeats: + t = min(elapsed, cycle_duration) + else: + t = (elapsed + cycle_duration if gap_first else elapsed) % animation.repeat_interval + + # Forward phase + if t < forward_duration: + return min(int(t / fd), num_frames - 1) + t -= forward_duration + + # Hold at last frame + if t < hold: + return num_frames - 1 + t -= hold + + # Backward phase + if backward_frames and t < backward_frames * fd: + return num_frames - 2 - min(int(t / fd), backward_frames - 1) + + return 0 if has_backward else num_frames - 1 diff --git a/selfdrive/test/__init__.py b/openpilot/selfdrive/ui/body/layouts/__init__.py similarity index 100% rename from selfdrive/test/__init__.py rename to openpilot/selfdrive/ui/body/layouts/__init__.py diff --git a/openpilot/selfdrive/ui/body/layouts/onroad.py b/openpilot/selfdrive/ui/body/layouts/onroad.py new file mode 100644 index 0000000000..d7e9f419cc --- /dev/null +++ b/openpilot/selfdrive/ui/body/layouts/onroad.py @@ -0,0 +1,93 @@ +import time +import pyray as rl + +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.label import UnifiedLabel +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.selfdrive.ui.body.animations import FaceAnimator, ASLEEP, INQUISITIVE, NORMAL, SLEEPY + +GRID_COLS = 16 +GRID_ROWS = 8 +DOT_RADIUS = 50 if gui_app.big_ui() else 10 + +IDLE_TIMEOUT = 30.0 # seconds of no joystick input before playing INQUISITIVE +IDLE_STEER_THRESH = 0.5 # degrees — below this counts as no input +IDLE_SPEED_THRESH = 0.01 # m/s — below this counts as no input + + +# This class is used both in BIG (tizi) and small (mici) UIs +class BodyLayout(Widget): + def __init__(self): + super().__init__() + self._animator = FaceAnimator(ASLEEP) + self._turning_left = False + self._turning_right = False + self._last_input_time = time.monotonic() + self._was_active = False + self._offroad_label = UnifiedLabel("turn on ignition to use", 95 if gui_app.big_ui() else 45, FontWeight.DISPLAY, + alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER, + alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE) + + def draw_dot_grid(self, rect: rl.Rectangle, dots: list[tuple[int, int]], color: rl.Color): + spacing = min(rect.height / GRID_ROWS, rect.width / GRID_COLS) + + grid_w = (GRID_COLS - 1) * spacing + grid_h = (GRID_ROWS - 1) * spacing + + offset_x = rect.x + (rect.width - grid_w) / 2 + offset_y = rect.y + (rect.height - grid_h) / 2 + + for row, col in dots: + x = int(offset_x + col * spacing) + y = int(offset_y + row * spacing) + rl.draw_circle(x, y, DOT_RADIUS, color) + + def _update_state(self): + super()._update_state() + + sm = ui_state.sm + + if ui_state.is_onroad(): + if not self._was_active: + self._last_input_time = time.monotonic() + self._was_active = True + + cs = sm['carState'] + has_input = abs(cs.steeringAngleDeg) > IDLE_STEER_THRESH or abs(cs.vEgo) > IDLE_SPEED_THRESH + if has_input: + self._last_input_time = time.monotonic() + + if time.monotonic() - self._last_input_time > IDLE_TIMEOUT: + self._animator.set_animation(INQUISITIVE) + else: + self._animator.set_animation(NORMAL) + else: + self._was_active = False + self._animator.set_animation(ASLEEP) + + steer = sm['testJoystick'].axes[1] if len(sm['testJoystick'].axes) > 1 else 0 + self._turning_left = steer <= -0.05 + self._turning_right = steer >= 0.05 + + # play animation on screen tap + def _handle_mouse_release(self, mouse_pos): + super()._handle_mouse_release(mouse_pos) + if not self._was_active: + self._animator.set_animation(SLEEPY) + + def _render(self, rect: rl.Rectangle): + dots = self._animator.get_dots() + animation = self._animator._animation + if self._turning_left and animation.left_turn_remove: + remove_set = set(animation.left_turn_remove) + dots = [d for d in dots if d not in remove_set] + elif self._turning_right and animation.right_turn_remove: + remove_set = set(animation.right_turn_remove) + dots = [d for d in dots if d not in remove_set] + self.draw_dot_grid(rect, dots, rl.WHITE) + + if ui_state.is_offroad(): + rl.draw_rectangle(int(self.rect.x), int(self.rect.y), int(self.rect.width), int(self.rect.height), rl.Color(0, 0, 0, 175)) + upper_half = rl.Rectangle(rect.x, rect.y, rect.width, rect.height / 2) + self._offroad_label.render(upper_half) diff --git a/openpilot/selfdrive/ui/feedback/feedbackd.py b/openpilot/selfdrive/ui/feedback/feedbackd.py new file mode 100755 index 0000000000..8056a580c6 --- /dev/null +++ b/openpilot/selfdrive/ui/feedback/feedbackd.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python3 +import openpilot.cereal.messaging as messaging +from openpilot.common.params import Params +from openpilot.common.swaglog import cloudlog +from opendbc.car.structs import car +from openpilot.system.micd import SAMPLE_RATE, SAMPLE_BUFFER + +FEEDBACK_MAX_DURATION = 10.0 +ButtonType = car.CarState.ButtonEvent.Type + + +def main(): + params = Params() + pm = messaging.PubMaster(['userBookmark', 'audioFeedback']) + sm = messaging.SubMaster(['rawAudioData', 'bookmarkButton', 'carState', 'selfdriveStateSP']) + should_record_audio = False + block_num = 0 + waiting_for_release = False + early_stop_triggered = False + + while True: + sm.update() + should_send_bookmark = False + + # TODO: https://github.com/commaai/openpilot/issues/36015 + # only allow the LKAS button to record feedback when MADS is disabled + if False and sm.updated['carState'] and sm['carState'].canValid and not sm['selfdriveStateSP'].mads.available: + for be in sm['carState'].buttonEvents: + if be.type == ButtonType.lkas: + if be.pressed: + if not should_record_audio: + if params.get_bool("RecordAudioFeedback"): # Start recording on first press if toggle set + should_record_audio = True + block_num = 0 + waiting_for_release = False + early_stop_triggered = False + cloudlog.info("LKAS button pressed - starting 10-second audio feedback") + else: + should_send_bookmark = True # immediately send bookmark if toggle false + cloudlog.info("LKAS button pressed - bookmarking") + elif should_record_audio and not waiting_for_release: # Wait for release of second press to stop recording early + waiting_for_release = True + elif waiting_for_release: # Second press released + waiting_for_release = False + early_stop_triggered = True + cloudlog.info("LKAS button released - ending recording early") + + if should_record_audio and sm.updated['rawAudioData']: + raw_audio = sm['rawAudioData'] + msg = messaging.new_message('audioFeedback', valid=True) + msg.audioFeedback.audio.data = raw_audio.data + msg.audioFeedback.audio.sampleRate = raw_audio.sampleRate + msg.audioFeedback.blockNum = block_num + block_num += 1 + if (block_num * SAMPLE_BUFFER / SAMPLE_RATE) >= FEEDBACK_MAX_DURATION or early_stop_triggered: # Check for timeout or early stop + should_send_bookmark = True # send bookmark at end of audio segment + should_record_audio = False + early_stop_triggered = False + cloudlog.info("10-second recording completed or second button press - stopping audio feedback") + pm.send('audioFeedback', msg) + + if sm.updated['bookmarkButton']: + cloudlog.info("Bookmark button pressed!") + should_send_bookmark = True + + if should_send_bookmark: + msg = messaging.new_message('userBookmark', valid=True) + pm.send('userBookmark', msg) + + +if __name__ == '__main__': + main() diff --git a/selfdrive/ui/installer/continue_openpilot.sh b/openpilot/selfdrive/ui/installer/continue_openpilot.sh similarity index 100% rename from selfdrive/ui/installer/continue_openpilot.sh rename to openpilot/selfdrive/ui/installer/continue_openpilot.sh diff --git a/openpilot/selfdrive/ui/installer/installer.cc b/openpilot/selfdrive/ui/installer/installer.cc new file mode 100644 index 0000000000..07e824c649 --- /dev/null +++ b/openpilot/selfdrive/ui/installer/installer.cc @@ -0,0 +1,270 @@ +#include +#include +#include +#include + +#include "common/swaglog.h" +#include "common/util.h" +#include "common/hardware/hw.h" +#include "raylib.h" + +int freshClone(); +int cachedFetch(const std::string &cache); +int executeGitCommand(const std::string &cmd); + +std::string get_str(std::string const s) { + std::string::size_type pos = s.find('?'); + assert(pos != std::string::npos); + return s.substr(0, pos); +} + +// Leave some extra space for the fork installer +const std::string GIT_URL = get_str("https://github.com/commaai/openpilot.git" "? "); +const std::string BRANCH_STR = get_str(BRANCH "? "); + +#define GIT_SSH_URL "git@github.com:commaai/openpilot.git" +#define CONTINUE_PATH "/data/continue.sh" + +const std::string INSTALL_PATH = "/data/openpilot"; +const std::string VALID_CACHE_PATH = "/data/.openpilot_cache"; + +#define TMP_INSTALL_PATH "/data/tmppilot" + +const int FONT_SIZE = 160; + +extern const uint8_t str_continue[] asm("_binary_selfdrive_ui_installer_continue_openpilot_sh_start"); +extern const uint8_t str_continue_end[] asm("_binary_selfdrive_ui_installer_continue_openpilot_sh_end"); +extern const uint8_t inter_ttf[] asm("_binary_selfdrive_ui_installer_inter_ascii_ttf_start"); +extern const uint8_t inter_ttf_end[] asm("_binary_selfdrive_ui_installer_inter_ascii_ttf_end"); +extern const uint8_t inter_light_ttf[] asm("_binary_selfdrive_assets_fonts_Inter_Light_ttf_start"); +extern const uint8_t inter_light_ttf_end[] asm("_binary_selfdrive_assets_fonts_Inter_Light_ttf_end"); +extern const uint8_t inter_bold_ttf[] asm("_binary_selfdrive_assets_fonts_Inter_Bold_ttf_start"); +extern const uint8_t inter_bold_ttf_end[] asm("_binary_selfdrive_assets_fonts_Inter_Bold_ttf_end"); + +Font font_inter; +Font font_roman; +Font font_display; + +const bool tici_device = Hardware::get_device_type() == cereal::InitData::DeviceType::TICI || + Hardware::get_device_type() == cereal::InitData::DeviceType::TIZI; + +std::vector tici_prebuilt_branches = {"release3", "release-tici", "release3-staging", "nightly", "nightly-dev"}; +std::string migrated_branch; + +void branchMigration() { + migrated_branch = BRANCH_STR; + cereal::InitData::DeviceType device_type = Hardware::get_device_type(); + if (device_type == cereal::InitData::DeviceType::TICI) { + if (std::find(tici_prebuilt_branches.begin(), tici_prebuilt_branches.end(), BRANCH_STR) != tici_prebuilt_branches.end()) { + migrated_branch = "release-tici"; + } else if (BRANCH_STR == "master") { + migrated_branch = "master-tici"; + } + } else if (device_type == cereal::InitData::DeviceType::TIZI) { + if (BRANCH_STR == "release3") { + migrated_branch = "release-tizi"; + } else if (BRANCH_STR == "release3-staging") { + migrated_branch = "release-tizi-staging"; + } + } else if (device_type == cereal::InitData::DeviceType::MICI) { + if (BRANCH_STR == "release3") { + migrated_branch = "release-mici"; + } else if (BRANCH_STR == "release3-staging") { + migrated_branch = "release-mici-staging"; + } + } +} + +void run(const char* cmd) { + int err = std::system(cmd); + assert(err == 0); +} + +void finishInstall() { + BeginDrawing(); + ClearBackground(BLACK); + if (tici_device) { + const char *m = "Finishing install..."; + int text_width = MeasureText(m, FONT_SIZE); + DrawTextEx(font_display, m, (Vector2){(float)(GetScreenWidth() - text_width)/2 + FONT_SIZE, (float)(GetScreenHeight() - FONT_SIZE)/2}, FONT_SIZE, 0, WHITE); + } else { + DrawTextEx(font_display, "finishing setup", (Vector2){12, 0}, 77, 0, (Color){255, 255, 255, (unsigned char)(255 * 0.9)}); + } + EndDrawing(); + util::sleep_for(60 * 1000); +} + +void renderProgress(int progress) { + BeginDrawing(); + ClearBackground(BLACK); + if (tici_device) { + DrawTextEx(font_inter, "Installing...", (Vector2){150, 290}, 110, 0, WHITE); + Rectangle bar = {150, 570, (float)GetScreenWidth() - 300, 72}; + DrawRectangleRec(bar, (Color){41, 41, 41, 255}); + progress = std::clamp(progress, 0, 100); + bar.width *= progress / 100.0f; + DrawRectangleRec(bar, (Color){70, 91, 234, 255}); + DrawTextEx(font_inter, (std::to_string(progress) + "%").c_str(), (Vector2){150, 670}, 85, 0, WHITE); + } else { + DrawTextEx(font_display, "installing...", (Vector2){12, 0}, 77, 0, (Color){255, 255, 255, (unsigned char)(255 * 0.9)}); + const std::string percent_str = std::to_string(progress) + "%"; + DrawTextEx(font_inter, percent_str.c_str(), (Vector2){12, (float)(GetScreenHeight() - 154 + 20)}, 154, 0, + (Color){255, 255, 255, (unsigned char)(255 * 0.9 * 0.65)}); + } + + EndDrawing(); +} + +int doInstall() { + // wait for valid time + while (!util::system_time_valid()) { + util::sleep_for(500); + LOGD("Waiting for valid time"); + } + + // cleanup previous install attempts + run("rm -rf " TMP_INSTALL_PATH); + + // do the install + if (util::file_exists(INSTALL_PATH) && util::file_exists(VALID_CACHE_PATH)) { + return cachedFetch(INSTALL_PATH); + } else { + return freshClone(); + } +} + +int freshClone() { + LOGD("Doing fresh clone"); + std::string cmd = util::string_format("git clone --progress %s -b %s --depth=1 --recurse-submodules %s 2>&1", + GIT_URL.c_str(), migrated_branch.c_str(), TMP_INSTALL_PATH); + return executeGitCommand(cmd); +} + +int cachedFetch(const std::string &cache) { + LOGD("Fetching with cache: %s", cache.c_str()); + + run(util::string_format("cp -rp %s %s", cache.c_str(), TMP_INSTALL_PATH).c_str()); + run(util::string_format("cd %s && git remote set-url origin %s", TMP_INSTALL_PATH, GIT_URL.c_str()).c_str()); + run(util::string_format("cd %s && git remote set-branches --add origin %s", TMP_INSTALL_PATH, migrated_branch.c_str()).c_str()); + + renderProgress(10); + + return executeGitCommand(util::string_format("cd %s && git fetch --progress origin %s 2>&1", TMP_INSTALL_PATH, migrated_branch.c_str())); +} + +int executeGitCommand(const std::string &cmd) { + static const std::array stages = { + // prefix, weight in percentage + std::pair{"Receiving objects: ", 91}, + std::pair{"Resolving deltas: ", 2}, + std::pair{"Updating files: ", 7}, + }; + + FILE *pipe = popen(cmd.c_str(), "r"); + if (!pipe) return -1; + + char buffer[512]; + while (fgets(buffer, sizeof(buffer), pipe) != nullptr) { + std::string line(buffer); + int base = 0; + for (const auto &[text, weight] : stages) { + if (line.find(text) != std::string::npos) { + size_t percentPos = line.find("%"); + if (percentPos != std::string::npos && percentPos >= 3) { + int percent = std::stoi(line.substr(percentPos - 3, 3)); + int progress = base + int(percent / 100. * weight); + renderProgress(progress); + } + break; + } + base += weight; + } + } + return pclose(pipe); +} + +void cloneFinished(int exitCode) { + LOGD("git finished with %d", exitCode); + assert(exitCode == 0); + + renderProgress(100); + + // ensure correct branch is checked out + int err = chdir(TMP_INSTALL_PATH); + assert(err == 0); + run(("git checkout " + migrated_branch).c_str()); + run(("git reset --hard origin/" + migrated_branch).c_str()); + run("git submodule update --init"); + + // move into place + run(("rm -f " + VALID_CACHE_PATH).c_str()); + run(("rm -rf " + INSTALL_PATH).c_str()); + run(util::string_format("mv %s %s", TMP_INSTALL_PATH, INSTALL_PATH.c_str()).c_str()); + +#ifdef INTERNAL + run("mkdir -p /data/params/d/"); + + // https://github.com/commaci2.keys + const std::string ssh_keys = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIMX2kU8eBZyEWmbq0tjMPxksWWVuIV/5l64GabcYbdpI"; + std::map params = { + {"SshEnabled", "1"}, + {"RecordFrontLock", "1"}, + {"GithubSshKeys", ssh_keys}, + }; + for (const auto& [key, value] : params) { + std::ofstream param; + param.open("/data/params/d/" + key); + param << value; + param.close(); + } + run(("cd " + INSTALL_PATH + " && " + "git remote set-url origin --push " GIT_SSH_URL " && " + "git config --replace-all remote.origin.fetch \"+refs/heads/*:refs/remotes/origin/*\"").c_str()); +#endif + + // write continue.sh + FILE *of = fopen("/data/continue.sh.new", "wb"); + assert(of != NULL); + + size_t num = str_continue_end - str_continue; + size_t num_written = fwrite(str_continue, 1, num, of); + assert(num == num_written); + fclose(of); + + run("chmod +x /data/continue.sh.new"); + run("mv /data/continue.sh.new " CONTINUE_PATH); + + // wait for the installed software's UI to take over + finishInstall(); +} + +int main(int argc, char *argv[]) { + if (tici_device) { + InitWindow(2160, 1080, "Installer"); + } else { + InitWindow(536, 240, "Installer"); + } + + font_inter = LoadFontFromMemory(".ttf", inter_ttf, inter_ttf_end - inter_ttf, FONT_SIZE, NULL, 0); + font_roman = LoadFontFromMemory(".ttf", inter_light_ttf, inter_light_ttf_end - inter_light_ttf, FONT_SIZE, NULL, 0); + font_display = LoadFontFromMemory(".ttf", inter_bold_ttf, inter_bold_ttf_end - inter_bold_ttf, FONT_SIZE, NULL, 0); + SetTextureFilter(font_inter.texture, TEXTURE_FILTER_BILINEAR); + SetTextureFilter(font_roman.texture, TEXTURE_FILTER_BILINEAR); + SetTextureFilter(font_display.texture, TEXTURE_FILTER_BILINEAR); + + branchMigration(); + + if (util::file_exists(CONTINUE_PATH)) { + finishInstall(); + } else { + renderProgress(0); + int result = doInstall(); + cloneFinished(result); + } + + CloseWindow(); + UnloadFont(font_inter); + UnloadFont(font_roman); + UnloadFont(font_display); + return 0; +} diff --git a/selfdrive/ui/installer/inter-ascii.ttf b/openpilot/selfdrive/ui/installer/inter-ascii.ttf similarity index 100% rename from selfdrive/ui/installer/inter-ascii.ttf rename to openpilot/selfdrive/ui/installer/inter-ascii.ttf diff --git a/selfdrive/test/longitudinal_maneuvers/__init__.py b/openpilot/selfdrive/ui/layouts/__init__.py similarity index 100% rename from selfdrive/test/longitudinal_maneuvers/__init__.py rename to openpilot/selfdrive/ui/layouts/__init__.py diff --git a/openpilot/selfdrive/ui/layouts/home.py b/openpilot/selfdrive/ui/layouts/home.py new file mode 100644 index 0000000000..be231dcd4b --- /dev/null +++ b/openpilot/selfdrive/ui/layouts/home.py @@ -0,0 +1,233 @@ +import time +import pyray as rl +from collections.abc import Callable +from enum import IntEnum +from openpilot.common.params import Params +from openpilot.selfdrive.ui.widgets.offroad_alerts import UpdateAlert, OffroadAlert +from openpilot.selfdrive.ui.widgets.exp_mode_button import ExperimentalModeButton +from openpilot.selfdrive.ui.widgets.prime import PrimeWidget +from openpilot.selfdrive.ui.widgets.setup import SetupWidget +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.lib.application import gui_app, FontWeight, MousePos +from openpilot.system.ui.lib.multilang import tr, trn +from openpilot.system.ui.widgets.label import gui_label +from openpilot.system.ui.widgets import Widget + +HEADER_HEIGHT = 80 +HEAD_BUTTON_FONT_SIZE = 40 +CONTENT_MARGIN = 40 +SPACING = 25 +RIGHT_COLUMN_WIDTH = 750 +REFRESH_INTERVAL = 10.0 + + +class HomeLayoutState(IntEnum): + HOME = 0 + UPDATE = 1 + ALERTS = 2 + + +class HomeLayout(Widget): + def __init__(self): + super().__init__() + self.params = Params() + + self.update_alert = UpdateAlert() + self.offroad_alert = OffroadAlert() + + self._layout_widgets = {HomeLayoutState.UPDATE: self.update_alert, HomeLayoutState.ALERTS: self.offroad_alert} + + self.current_state = HomeLayoutState.HOME + self.last_refresh = 0 + self.settings_callback: Callable[[], None] | None = None + + self.update_available = False + self.alert_count = 0 + self._version_text = "" + self._prev_update_available = False + self._prev_alerts_present = False + + self.header_rect = rl.Rectangle(0, 0, 0, 0) + self.content_rect = rl.Rectangle(0, 0, 0, 0) + self.left_column_rect = rl.Rectangle(0, 0, 0, 0) + self.right_column_rect = rl.Rectangle(0, 0, 0, 0) + + self.update_notif_rect = rl.Rectangle(0, 0, 200, HEADER_HEIGHT - 10) + self.alert_notif_rect = rl.Rectangle(0, 0, 220, HEADER_HEIGHT - 10) + + self._prime_widget = PrimeWidget() + self._setup_widget = SetupWidget() + + self._exp_mode_button = ExperimentalModeButton() + self._setup_callbacks() + + def show_event(self): + super().show_event() + self._exp_mode_button.show_event() + self.last_refresh = time.monotonic() + self._refresh() + + def _setup_callbacks(self): + self.update_alert.set_dismiss_callback(lambda: self._set_state(HomeLayoutState.HOME)) + self.offroad_alert.set_dismiss_callback(lambda: self._set_state(HomeLayoutState.HOME)) + self._exp_mode_button.set_click_callback(lambda: self.settings_callback() if self.settings_callback else None) + + def set_settings_callback(self, callback: Callable): + self.settings_callback = callback + + def _set_state(self, state: HomeLayoutState): + # propagate show/hide events + if state != self.current_state: + if state == HomeLayoutState.HOME: + self._exp_mode_button.show_event() + + if state in self._layout_widgets: + self._layout_widgets[state].show_event() + if self.current_state in self._layout_widgets: + self._layout_widgets[self.current_state].hide_event() + + self.current_state = state + + def _render(self, rect: rl.Rectangle): + current_time = time.monotonic() + if current_time - self.last_refresh >= REFRESH_INTERVAL: + self._refresh() + self.last_refresh = current_time + + self._render_header() + + # Render content based on current state + if self.current_state == HomeLayoutState.HOME: + self._render_home_content() + elif self.current_state == HomeLayoutState.UPDATE: + self._render_update_view() + elif self.current_state == HomeLayoutState.ALERTS: + self._render_alerts_view() + + def _update_state(self): + self.header_rect = rl.Rectangle( + self._rect.x + CONTENT_MARGIN, self._rect.y + CONTENT_MARGIN, self._rect.width - 2 * CONTENT_MARGIN, HEADER_HEIGHT + ) + + content_y = self._rect.y + CONTENT_MARGIN + HEADER_HEIGHT + SPACING + content_height = self._rect.height - CONTENT_MARGIN - HEADER_HEIGHT - SPACING - CONTENT_MARGIN + + self.content_rect = rl.Rectangle( + self._rect.x + CONTENT_MARGIN, content_y, self._rect.width - 2 * CONTENT_MARGIN, content_height + ) + + left_width = self.content_rect.width - RIGHT_COLUMN_WIDTH - SPACING + + self.left_column_rect = rl.Rectangle(self.content_rect.x, self.content_rect.y, left_width, self.content_rect.height) + + self.right_column_rect = rl.Rectangle( + self.content_rect.x + left_width + SPACING, self.content_rect.y, RIGHT_COLUMN_WIDTH, self.content_rect.height + ) + + self.update_notif_rect.x = self.header_rect.x + self.update_notif_rect.y = self.header_rect.y + (self.header_rect.height - 60) // 2 + + notif_x = self.header_rect.x + (220 if self.update_available else 0) + self.alert_notif_rect.x = notif_x + self.alert_notif_rect.y = self.header_rect.y + (self.header_rect.height - 60) // 2 + + def _handle_mouse_release(self, mouse_pos: MousePos): + super()._handle_mouse_release(mouse_pos) + + if self.update_available and rl.check_collision_point_rec(mouse_pos, self.update_notif_rect): + self._set_state(HomeLayoutState.UPDATE) + elif self.alert_count > 0 and rl.check_collision_point_rec(mouse_pos, self.alert_notif_rect): + self._set_state(HomeLayoutState.ALERTS) + + def _render_header(self): + font = gui_app.font(FontWeight.MEDIUM) + + version_text_width = self.header_rect.width + + # Update notification button + if self.update_available: + version_text_width -= self.update_notif_rect.width + + # Highlight if currently viewing updates + highlight_color = rl.Color(75, 95, 255, 255) if self.current_state == HomeLayoutState.UPDATE else rl.Color(54, 77, 239, 255) + rl.draw_rectangle_rounded(self.update_notif_rect, 0.3, 10, highlight_color) + + text = tr("UPDATE") + text_size = measure_text_cached(font, text, HEAD_BUTTON_FONT_SIZE) + text_x = self.update_notif_rect.x + (self.update_notif_rect.width - text_size.x) // 2 + text_y = self.update_notif_rect.y + (self.update_notif_rect.height - text_size.y) // 2 + rl.draw_text_ex(font, text, rl.Vector2(int(text_x), int(text_y)), HEAD_BUTTON_FONT_SIZE, 0, rl.WHITE) + + # Alert notification button + if self.alert_count > 0: + version_text_width -= self.alert_notif_rect.width + + # Highlight if currently viewing alerts + highlight_color = rl.Color(255, 70, 70, 255) if self.current_state == HomeLayoutState.ALERTS else rl.Color(226, 44, 44, 255) + rl.draw_rectangle_rounded(self.alert_notif_rect, 0.3, 10, highlight_color) + + alert_text = trn("{} ALERT", "{} ALERTS", self.alert_count).format(self.alert_count) + text_size = measure_text_cached(font, alert_text, HEAD_BUTTON_FONT_SIZE) + text_x = self.alert_notif_rect.x + (self.alert_notif_rect.width - text_size.x) // 2 + text_y = self.alert_notif_rect.y + (self.alert_notif_rect.height - text_size.y) // 2 + rl.draw_text_ex(font, alert_text, rl.Vector2(int(text_x), int(text_y)), HEAD_BUTTON_FONT_SIZE, 0, rl.WHITE) + + # Version text (right aligned) + if self.update_available or self.alert_count > 0: + version_text_width -= SPACING * 1.5 + + version_rect = rl.Rectangle(self.header_rect.x + self.header_rect.width - version_text_width, self.header_rect.y, + version_text_width, self.header_rect.height) + gui_label(version_rect, self._version_text, 48, rl.WHITE, alignment=rl.GuiTextAlignment.TEXT_ALIGN_RIGHT) + + def _render_home_content(self): + self._render_left_column() + self._render_right_column() + + def _render_update_view(self): + self.update_alert.render(self.content_rect) + + def _render_alerts_view(self): + self.offroad_alert.render(self.content_rect) + + def _render_left_column(self): + self._prime_widget.render(self.left_column_rect) + + def _render_right_column(self): + exp_height = 125 + exp_rect = rl.Rectangle( + self.right_column_rect.x, self.right_column_rect.y, self.right_column_rect.width, exp_height + ) + self._exp_mode_button.render(exp_rect) + + setup_rect = rl.Rectangle( + self.right_column_rect.x, + self.right_column_rect.y + exp_height + SPACING, + self.right_column_rect.width, + self.right_column_rect.height - exp_height - SPACING, + ) + self._setup_widget.render(setup_rect) + + def _refresh(self): + self._version_text = self._get_version_text() + update_available = self.update_alert.refresh() + alert_count = self.offroad_alert.refresh() + alerts_present = alert_count > 0 + + # Show panels on transition from no alert/update to any alerts/update + if not update_available and not alerts_present: + self._set_state(HomeLayoutState.HOME) + elif update_available and ((not self._prev_update_available) or (not alerts_present and self.current_state == HomeLayoutState.ALERTS)): + self._set_state(HomeLayoutState.UPDATE) + elif alerts_present and ((not self._prev_alerts_present) or (not update_available and self.current_state == HomeLayoutState.UPDATE)): + self._set_state(HomeLayoutState.ALERTS) + + self.update_available = update_available + self.alert_count = alert_count + self._prev_update_available = update_available + self._prev_alerts_present = alerts_present + + def _get_version_text(self) -> str: + brand = "sunnypilot" + description = self.params.get("UpdaterCurrentDescription") + return f"{brand} {description}" if description else brand diff --git a/openpilot/selfdrive/ui/layouts/main.py b/openpilot/selfdrive/ui/layouts/main.py new file mode 100644 index 0000000000..2b8bac22c2 --- /dev/null +++ b/openpilot/selfdrive/ui/layouts/main.py @@ -0,0 +1,134 @@ +import pyray as rl +from enum import IntEnum +import openpilot.cereal.messaging as messaging +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.widgets import Widget +from openpilot.selfdrive.ui.layouts.sidebar import Sidebar, SIDEBAR_WIDTH +from openpilot.selfdrive.ui.layouts.home import HomeLayout +from openpilot.selfdrive.ui.layouts.settings.settings import SettingsLayout, PanelType +from openpilot.selfdrive.ui.onroad.augmented_road_view import AugmentedRoadView +from openpilot.selfdrive.ui.ui_state import device, ui_state +from openpilot.selfdrive.ui.layouts.onboarding import OnboardingWindow +from openpilot.selfdrive.ui.body.layouts.onroad import BodyLayout + +if gui_app.sunnypilot_ui(): + from openpilot.selfdrive.ui.sunnypilot.layouts.settings.settings import SettingsLayoutSP as SettingsLayout + + +class MainState(IntEnum): + HOME = 0 + SETTINGS = 1 + ONROAD = 2 + + +class MainLayout(Widget): + def __init__(self): + super().__init__() + + self._pm = messaging.PubMaster(['bookmarkButton']) + + self._sidebar = Sidebar() + self._current_mode = MainState.HOME + self._prev_onroad = False + + # Initialize layouts + self._home_layout = HomeLayout() + self._home_body_layout = BodyLayout() + self._layouts: dict[MainState, Widget] = { + MainState.HOME: self._home_layout, + MainState.SETTINGS: SettingsLayout(), + MainState.ONROAD: AugmentedRoadView(), + } + + self._sidebar_rect = rl.Rectangle(0, 0, 0, 0) + self._content_rect = rl.Rectangle(0, 0, 0, 0) + + # Set callbacks + self._setup_callbacks() + + gui_app.push_widget(self) + + # Start onboarding if terms or training not completed, make sure to push after self + self._onboarding_window = OnboardingWindow() + if not self._onboarding_window.completed: + gui_app.push_widget(self._onboarding_window) + + def _render(self, _): + self._handle_onroad_transition() + self._render_main_content() + + def _setup_callbacks(self): + self._sidebar.set_callbacks(on_settings=self._on_settings_clicked, + on_flag=self._on_bookmark_clicked, + open_settings=lambda: self.open_settings(PanelType.TOGGLES)) + self._layouts[MainState.HOME]._setup_widget.set_open_settings_callback(lambda: self.open_settings(PanelType.FIREHOSE)) + self._layouts[MainState.HOME].set_settings_callback(lambda: self.open_settings(PanelType.TOGGLES)) + self._layouts[MainState.SETTINGS].set_callbacks(on_close=self._set_mode_for_state) + + for layout in (self._layouts[MainState.ONROAD], self._home_body_layout): + layout.set_click_callback(self._on_onroad_clicked) + + device.add_interactive_timeout_callback(self._set_mode_for_state) + ui_state.add_on_body_changed_callbacks(self._on_body_changed) + + def _update_layout_rects(self): + self._sidebar_rect = rl.Rectangle(self._rect.x, self._rect.y, SIDEBAR_WIDTH, self._rect.height) + + x_offset = SIDEBAR_WIDTH if self._sidebar.is_visible else 0 + self._content_rect = rl.Rectangle(self._rect.x + x_offset, self._rect.y, self._rect.width - x_offset, self._rect.height) + + def _handle_onroad_transition(self): + if ui_state.started != self._prev_onroad: + self._prev_onroad = ui_state.started + + self._set_mode_for_state() + + def _set_mode_for_state(self): + # Don't go onroad if body, home is onroad + if ui_state.is_body: + self._set_current_layout(MainState.HOME) + self._sidebar.set_visible(not ui_state.ignition) + return + + if ui_state.started: + # Don't hide sidebar from interactive timeout + if self._current_mode != MainState.ONROAD: + self._sidebar.set_visible(False) + self._set_current_layout(MainState.ONROAD) + else: + self._set_current_layout(MainState.HOME) + self._sidebar.set_visible(True) + + def _set_current_layout(self, layout: MainState): + if layout != self._current_mode: + self._layouts[self._current_mode].hide_event() + self._current_mode = layout + self._layouts[self._current_mode].show_event() + + def open_settings(self, panel_type: PanelType): + self._layouts[MainState.SETTINGS].set_current_panel(panel_type) + self._set_current_layout(MainState.SETTINGS) + self._sidebar.set_visible(False) + + def _on_settings_clicked(self): + self.open_settings(PanelType.DEVICE) + + def _on_bookmark_clicked(self): + user_bookmark = messaging.new_message('bookmarkButton') + user_bookmark.valid = True + self._pm.send('bookmarkButton', user_bookmark) + + def _on_onroad_clicked(self): + self._sidebar.set_visible(not self._sidebar.is_visible) + + def _on_body_changed(self): + self._layouts[MainState.HOME] = self._home_body_layout if ui_state.is_body else self._home_layout + self._set_mode_for_state() + + def _render_main_content(self): + # Render sidebar + if self._sidebar.is_visible: + self._sidebar.render(self._sidebar_rect) + + content_rect = self._content_rect if self._sidebar.is_visible else self._rect + self._layouts[self._current_mode].render(content_rect) diff --git a/openpilot/selfdrive/ui/layouts/onboarding.py b/openpilot/selfdrive/ui/layouts/onboarding.py new file mode 100644 index 0000000000..df14415c60 --- /dev/null +++ b/openpilot/selfdrive/ui/layouts/onboarding.py @@ -0,0 +1,244 @@ +import os +import re +import threading +from enum import IntEnum + +import pyray as rl +from openpilot.common.basedir import BASEDIR +from openpilot.system.ui.lib.application import FontWeight, gui_app +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.button import Button, ButtonStyle +from openpilot.system.ui.widgets.label import Label +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.common.version import terms_version, training_version, terms_version_sp + +from openpilot.selfdrive.ui.sunnypilot.layouts.onboarding import SunnylinkOnboarding + +DEBUG = False + +STEP_RECTS = [rl.Rectangle(104, 800, 633, 175), rl.Rectangle(1835, 0, 2159, 1080), rl.Rectangle(1835, 0, 2156, 1080), + rl.Rectangle(1526, 473, 427, 472), rl.Rectangle(1643, 441, 217, 223), rl.Rectangle(1835, 0, 2155, 1080), + rl.Rectangle(1786, 591, 267, 236), rl.Rectangle(1353, 0, 804, 1080), rl.Rectangle(1458, 485, 633, 211), + rl.Rectangle(95, 794, 1158, 187), rl.Rectangle(1560, 170, 392, 397), rl.Rectangle(1835, 0, 2159, 1080), + rl.Rectangle(1351, 0, 807, 1080), rl.Rectangle(1835, 0, 2158, 1080), rl.Rectangle(1531, 82, 441, 920), + rl.Rectangle(1336, 438, 490, 393), rl.Rectangle(1835, 0, 2159, 1080), rl.Rectangle(1835, 0, 2159, 1080), + rl.Rectangle(87, 795, 1187, 186)] + +DM_RECORD_STEP = 9 +DM_RECORD_YES_RECT = rl.Rectangle(695, 794, 558, 187) + +RESTART_TRAINING_RECT = rl.Rectangle(87, 795, 472, 186) + + +class OnboardingState(IntEnum): + TERMS = 0 + ONBOARDING = 1 + DECLINE = 2 + SUNNYLINK_CONSENT = 3 + + +class TrainingGuide(Widget): + def __init__(self, completed_callback=None): + super().__init__() + self._completed_callback = completed_callback + + self._step = 0 + self._load_image_paths() + + # Load first image now so we show something immediately + self._textures = [gui_app.texture(self._image_paths[0])] + self._image_objs = [] + + threading.Thread(target=self._preload_thread, daemon=True).start() + + def _load_image_paths(self): + paths = [fn for fn in os.listdir(os.path.join(BASEDIR, "openpilot/selfdrive/assets/training")) if re.match(r'^step\d*\.png$', fn)] + paths = sorted(paths, key=lambda x: int(re.search(r'\d+', x).group())) + self._image_paths = [os.path.join(BASEDIR, "openpilot/selfdrive/assets/training", fn) for fn in paths] + + def _preload_thread(self): + # PNG loading is slow in raylib, so we preload in a thread and upload to GPU in main thread + # We've already loaded the first image on init + for path in self._image_paths[1:]: + self._image_objs.append(gui_app._load_image_from_path(path)) + + def _handle_mouse_release(self, mouse_pos): + if rl.check_collision_point_rec(mouse_pos, STEP_RECTS[self._step]): + # Record DM camera? + if self._step == DM_RECORD_STEP: + yes = rl.check_collision_point_rec(mouse_pos, DM_RECORD_YES_RECT) + print(f"putting RecordFront to {yes}") + ui_state.params.put_bool("RecordFront", yes, block=True) + + # Restart training? + elif self._step == len(self._image_paths) - 1: + if rl.check_collision_point_rec(mouse_pos, RESTART_TRAINING_RECT): + self._step = -1 + + self._step += 1 + + # Finished? + if self._step >= len(self._image_paths): + self._step = 0 + if self._completed_callback: + self._completed_callback() + + # NOTE: this pops OnboardingWindow during real onboarding + gui_app.pop_widget() + + def _update_state(self): + if len(self._image_objs): + self._textures.append(gui_app._load_texture_from_image(self._image_objs.pop(0))) + + def _render(self, _): + # Safeguard against fast tapping + step = min(self._step, len(self._textures) - 1) + rl.draw_texture_ex(self._textures[step], rl.Vector2(0, 0), 0.0, 1.0, rl.WHITE) + + # progress bar + if 0 < step < len(STEP_RECTS) - 1: + h = 20 + w = int((step / (len(STEP_RECTS) - 1)) * self._rect.width) + rl.draw_rectangle(int(self._rect.x), int(self._rect.y + self._rect.height - h), + w, h, rl.Color(70, 91, 234, 255)) + + if DEBUG: + rl.draw_rectangle_lines_ex(STEP_RECTS[step], 3, rl.RED) + + return -1 + + +class TermsPage(Widget): + def __init__(self, on_accept=None, on_decline=None): + super().__init__() + self._on_accept = on_accept + self._on_decline = on_decline + + self._title = Label(tr("Welcome to sunnypilot"), font_size=90, font_weight=FontWeight.BOLD, text_alignment=rl.GuiTextAlignment.TEXT_ALIGN_LEFT) + self._desc = Label(tr("You must accept the Terms of Service to use sunnypilot. Read the latest terms at https://sunnypilot.ai/terms before continuing."), + font_size=90, font_weight=FontWeight.MEDIUM, text_alignment=rl.GuiTextAlignment.TEXT_ALIGN_LEFT) + + self._decline_btn = Button(tr("Decline"), click_callback=on_decline) + self._accept_btn = Button(tr("Agree"), button_style=ButtonStyle.PRIMARY, click_callback=on_accept) + + def _render(self, _): + welcome_x = self._rect.x + 95 + welcome_y = self._rect.y + 165 + welcome_rect = rl.Rectangle(welcome_x, welcome_y, self._rect.width - welcome_x, 90) + self._title.render(welcome_rect) + + desc_x = welcome_x + # TODO: Label doesn't top align when wrapping + desc_y = welcome_y - 100 + desc_rect = rl.Rectangle(desc_x, desc_y, self._rect.width - desc_x, self._rect.height - desc_y - 250) + self._desc.render(desc_rect) + + btn_y = self._rect.y + self._rect.height - 160 - 45 + btn_width = (self._rect.width - 45 * 3) / 2 + self._decline_btn.render(rl.Rectangle(self._rect.x + 45, btn_y, btn_width, 160)) + self._accept_btn.render(rl.Rectangle(self._rect.x + 45 * 2 + btn_width, btn_y, btn_width, 160)) + + if DEBUG: + rl.draw_rectangle_lines_ex(welcome_rect, 3, rl.RED) + rl.draw_rectangle_lines_ex(desc_rect, 3, rl.RED) + + return -1 + + +class DeclinePage(Widget): + def __init__(self, back_callback=None): + super().__init__() + self._text = Label(tr("You must accept the Terms of Service in order to use sunnypilot."), + font_size=90, font_weight=FontWeight.MEDIUM, text_alignment=rl.GuiTextAlignment.TEXT_ALIGN_LEFT) + self._back_btn = Button(tr("Back"), click_callback=back_callback) + self._uninstall_btn = Button(tr("Decline, uninstall sunnypilot"), button_style=ButtonStyle.DANGER, + click_callback=self._on_uninstall_clicked) + + def _on_uninstall_clicked(self): + ui_state.params.put_bool("DoUninstall", True, block=True) + gui_app.request_close() + + def _render(self, _): + btn_y = self._rect.y + self._rect.height - 160 - 45 + btn_width = (self._rect.width - 45 * 3) / 2 + self._back_btn.render(rl.Rectangle(self._rect.x + 45, btn_y, btn_width, 160)) + self._uninstall_btn.render(rl.Rectangle(self._rect.x + 45 * 2 + btn_width, btn_y, btn_width, 160)) + + # text rect in middle of top and button + text_height = btn_y - (200 + 45) + text_rect = rl.Rectangle(self._rect.x + 165, self._rect.y + (btn_y - text_height) / 2 + 10, self._rect.width - (165 * 2), text_height) + if DEBUG: + rl.draw_rectangle_lines_ex(text_rect, 3, rl.RED) + self._text.render(text_rect) + + +class OnboardingWindow(Widget): + def __init__(self): + super().__init__() + self._accepted_terms: bool = ui_state.params.get("HasAcceptedTerms") == terms_version + self._training_done: bool = ui_state.params.get("CompletedTrainingVersion") == training_version + + self._state = OnboardingState.TERMS if not self._accepted_terms else OnboardingState.ONBOARDING + + # Windows + self._terms = TermsPage(on_accept=self._on_terms_accepted, on_decline=self._on_terms_declined) + self._training_guide: TrainingGuide | None = None + self._decline_page = DeclinePage(back_callback=self._on_decline_back) + + # sunnylink consent pages + self._accepted_terms = self._accepted_terms and ui_state.params.get("HasAcceptedTermsSP") == terms_version_sp + self._sunnylink = SunnylinkOnboarding() + if not self._accepted_terms: + self._state = OnboardingState.TERMS + elif not self._sunnylink.completed: + self._state = OnboardingState.SUNNYLINK_CONSENT + elif not self._training_done: + self._state = OnboardingState.ONBOARDING + else: + self._state = OnboardingState.ONBOARDING + + @property + def completed(self) -> bool: + return self._accepted_terms and self._sunnylink.completed and self._training_done + + def _on_terms_declined(self): + self._state = OnboardingState.DECLINE + + def _on_decline_back(self): + self._state = OnboardingState.TERMS + + def _on_terms_accepted(self): + ui_state.params.put("HasAcceptedTerms", terms_version, block=True) + ui_state.params.put("HasAcceptedTermsSP", terms_version_sp, block=True) + if not self._sunnylink.completed: + self._state = OnboardingState.SUNNYLINK_CONSENT + elif not self._training_done: + self._state = OnboardingState.ONBOARDING + else: + gui_app.pop_widget() + + def _on_completed_training(self): + ui_state.params.put("CompletedTrainingVersion", training_version, block=True) + + def _render(self, _): + if self._training_guide is None: + self._training_guide = TrainingGuide(completed_callback=self._on_completed_training) + + if self._state == OnboardingState.TERMS: + self._terms.render(self._rect) + elif self._state == OnboardingState.SUNNYLINK_CONSENT: + self._sunnylink.render(self._rect) + if self._sunnylink.completed: + if not self._training_done: + self._state = OnboardingState.ONBOARDING + else: + gui_app.pop_widget() + elif self._state == OnboardingState.ONBOARDING: + if not self._training_done: + self._training_guide.render(self._rect) + else: + gui_app.pop_widget() + elif self._state == OnboardingState.DECLINE: + self._decline_page.render(self._rect) + return -1 diff --git a/openpilot/selfdrive/ui/layouts/settings/common.py b/openpilot/selfdrive/ui/layouts/settings/common.py new file mode 100644 index 0000000000..bba8606e64 --- /dev/null +++ b/openpilot/selfdrive/ui/layouts/settings/common.py @@ -0,0 +1,5 @@ +from openpilot.selfdrive.ui.ui_state import ui_state + + +def restart_needed_callback(_=None): + ui_state.params.put_bool("OnroadCycleRequested", True) diff --git a/openpilot/selfdrive/ui/layouts/settings/developer.py b/openpilot/selfdrive/ui/layouts/settings/developer.py new file mode 100644 index 0000000000..ef9c7f9e03 --- /dev/null +++ b/openpilot/selfdrive/ui/layouts/settings/developer.py @@ -0,0 +1,211 @@ +from openpilot.common.params import Params +from openpilot.selfdrive.ui.widgets.ssh_key import ssh_key_item +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.list_view import toggle_item +from openpilot.system.ui.widgets.scroller_tici import Scroller +from openpilot.system.ui.widgets.confirm_dialog import ConfirmDialog +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.lib.multilang import tr, tr_noop +from openpilot.system.ui.widgets import DialogResult + +if gui_app.sunnypilot_ui(): + from openpilot.system.ui.sunnypilot.widgets.list_view import toggle_item_sp as toggle_item + +# Description constants +DESCRIPTIONS = { + 'enable_adb': tr_noop( + "ADB (Android Debug Bridge) allows connecting to your device over USB or over the network. " + + "See https://docs.comma.ai/how-to/connect-to-comma for more info." + ), + 'ssh_key': tr_noop( + "Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username " + + "other than your own. A comma employee will NEVER ask you to add their GitHub username." + ), + 'alpha_longitudinal': tr_noop( + "WARNING: sunnypilot longitudinal control is in alpha for this car and may disable Automatic Emergency Braking (AEB).

" + + "On this car, sunnypilot defaults to the car's built-in ACC instead of sunnypilot's longitudinal control. " + + "Enable this to switch to sunnypilot longitudinal control. " + + "Enabling Experimental mode is recommended when enabling sunnypilot longitudinal control alpha. " + + "Changing this setting will restart sunnypilot if the car is powered on." + ), +} + + +class DeveloperLayout(Widget): + def __init__(self): + super().__init__() + self._params = Params() + self._is_release = False # self._params.get_bool("IsReleaseBranch") + + # Build items and keep references for callbacks/state updates + self._adb_toggle = toggle_item( + lambda: tr("Enable ADB"), + description=lambda: tr(DESCRIPTIONS["enable_adb"]), + initial_state=self._params.get_bool("AdbEnabled"), + callback=self._on_enable_adb, + enabled=ui_state.is_offroad, + ) + + # SSH enable toggle + SSH key management + self._ssh_toggle = toggle_item( + lambda: tr("Enable SSH"), + description="", + initial_state=self._params.get_bool("SshEnabled"), + callback=self._on_enable_ssh, + ) + self._ssh_keys = ssh_key_item(lambda: tr("SSH Keys"), description=lambda: tr(DESCRIPTIONS["ssh_key"])) + + self._joystick_toggle = toggle_item( + lambda: tr("Joystick Debug Mode"), + description="", + initial_state=self._params.get_bool("JoystickDebugMode"), + callback=self._on_joystick_debug_mode, + enabled=ui_state.is_offroad, + ) + + self._long_maneuver_toggle = toggle_item( + lambda: tr("Longitudinal Maneuver Mode"), + description="", + initial_state=self._params.get_bool("LongitudinalManeuverMode"), + callback=self._on_long_maneuver_mode, + ) + + self._lat_maneuver_toggle = toggle_item( + lambda: tr("Lateral Maneuver Mode"), + description="", + initial_state=self._params.get_bool("LateralManeuverMode"), + callback=self._on_lat_maneuver_mode, + ) + + self._alpha_long_toggle = toggle_item( + lambda: tr("sunnypilot Longitudinal Control (Alpha)"), + description=lambda: tr(DESCRIPTIONS["alpha_longitudinal"]), + initial_state=self._params.get_bool("AlphaLongitudinalEnabled"), + callback=self._on_alpha_long_enabled, + enabled=lambda: not ui_state.engaged, + ) + + self._ui_debug_toggle = toggle_item( + lambda: tr("UI Debug Mode"), + description="", + initial_state=self._params.get_bool("ShowDebugInfo"), + callback=self._on_enable_ui_debug, + ) + self._on_enable_ui_debug(self._params.get_bool("ShowDebugInfo")) + + self._scroller = Scroller([ + self._adb_toggle, + self._ssh_toggle, + self._ssh_keys, + self._joystick_toggle, + self._long_maneuver_toggle, + self._lat_maneuver_toggle, + self._alpha_long_toggle, + self._ui_debug_toggle, + ], line_separator=True, spacing=0) + + # Toggles should be not available to change in onroad state + ui_state.add_offroad_transition_callback(self._update_toggles) + + def _render(self, rect): + self._scroller.render(rect) + + def show_event(self): + super().show_event() + self._scroller.show_event() + self._update_toggles() + + def _update_toggles(self): + ui_state.update_params() + + # Hide non-release toggles on release builds + # TODO: we can do an onroad cycle, but alpha long toggle requires a deinit function to re-enable radar and not fault + for item in (self._joystick_toggle, self._long_maneuver_toggle, self._lat_maneuver_toggle, self._alpha_long_toggle): + item.set_visible(not self._is_release) + + # CP gating + if ui_state.CP is not None: + alpha_avail = ui_state.CP.alphaLongitudinalAvailable + if not alpha_avail or self._is_release: + self._alpha_long_toggle.set_visible(False) + self._params.remove("AlphaLongitudinalEnabled") + else: + self._alpha_long_toggle.set_visible(True) + + long_man_enabled = ui_state.has_longitudinal_control and ui_state.is_offroad() + self._long_maneuver_toggle.action_item.set_enabled(long_man_enabled) + self._lat_maneuver_toggle.action_item.set_enabled(ui_state.is_offroad()) + else: + self._long_maneuver_toggle.action_item.set_enabled(False) + self._lat_maneuver_toggle.action_item.set_enabled(False) + self._alpha_long_toggle.set_visible(False) + + # TODO: make a param control list item so we don't need to manage internal state as much here + # refresh toggles from params to mirror external changes + for key, item in ( + ("AdbEnabled", self._adb_toggle), + ("SshEnabled", self._ssh_toggle), + ("JoystickDebugMode", self._joystick_toggle), + ("LongitudinalManeuverMode", self._long_maneuver_toggle), + ("LateralManeuverMode", self._lat_maneuver_toggle), + ("AlphaLongitudinalEnabled", self._alpha_long_toggle), + ("ShowDebugInfo", self._ui_debug_toggle), + ): + item.action_item.set_state(self._params.get_bool(key)) + + def _on_enable_ui_debug(self, state: bool): + self._params.put_bool("ShowDebugInfo", state, block=True) + gui_app.set_show_touches(state) + gui_app.set_show_fps(state) + gui_app.set_show_mouse_coords(state) + + def _on_enable_adb(self, state: bool): + self._params.put_bool("AdbEnabled", state, block=True) + + def _on_enable_ssh(self, state: bool): + self._params.put_bool("SshEnabled", state, block=True) + + def _on_joystick_debug_mode(self, state: bool): + self._params.put_bool("JoystickDebugMode", state, block=True) + self._params.put_bool("LongitudinalManeuverMode", False, block=True) + self._long_maneuver_toggle.action_item.set_state(False) + self._params.put_bool("LateralManeuverMode", False, block=True) + self._lat_maneuver_toggle.action_item.set_state(False) + + def _on_long_maneuver_mode(self, state: bool): + self._params.put_bool("LongitudinalManeuverMode", state, block=True) + self._params.put_bool("JoystickDebugMode", False, block=True) + self._joystick_toggle.action_item.set_state(False) + self._params.put_bool("LateralManeuverMode", False, block=True) + self._lat_maneuver_toggle.action_item.set_state(False) + + def _on_lat_maneuver_mode(self, state: bool): + self._params.put_bool("LateralManeuverMode", state, block=True) + self._params.put_bool("ExperimentalMode", False, block=True) + self._params.put_bool("JoystickDebugMode", False, block=True) + self._joystick_toggle.action_item.set_state(False) + self._params.put_bool("LongitudinalManeuverMode", False, block=True) + self._long_maneuver_toggle.action_item.set_state(False) + + def _on_alpha_long_enabled(self, state: bool): + if state: + def confirm_callback(result: DialogResult): + if result == DialogResult.CONFIRM: + self._params.put_bool("AlphaLongitudinalEnabled", True, block=True) + self._params.put_bool("OnroadCycleRequested", True, block=True) + self._update_toggles() + else: + self._alpha_long_toggle.action_item.set_state(False) + + # show confirmation dialog + content = (f"

{self._alpha_long_toggle.title}


" + + f"

{self._alpha_long_toggle.description}

") + + dlg = ConfirmDialog(content, tr("Enable"), rich=True, callback=confirm_callback) + gui_app.push_widget(dlg) + + else: + self._params.put_bool("AlphaLongitudinalEnabled", False, block=True) + self._params.put_bool("OnroadCycleRequested", True, block=True) + self._update_toggles() diff --git a/openpilot/selfdrive/ui/layouts/settings/device.py b/openpilot/selfdrive/ui/layouts/settings/device.py new file mode 100644 index 0000000000..8844623b6e --- /dev/null +++ b/openpilot/selfdrive/ui/layouts/settings/device.py @@ -0,0 +1,196 @@ +import os +import math + +from openpilot.cereal import messaging, log +from openpilot.common.basedir import BASEDIR +from openpilot.common.params import Params +from openpilot.common.swaglog import cloudlog +from openpilot.selfdrive.ui.onroad.driver_camera_dialog import DriverCameraDialog +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.selfdrive.ui.layouts.onboarding import TrainingGuide +from openpilot.selfdrive.ui.widgets.pairing_dialog import PairingDialog +from openpilot.system.ui.lib.application import FontWeight, gui_app +from openpilot.system.ui.lib.multilang import multilang, tr, tr_noop +from openpilot.system.ui.widgets import Widget, DialogResult +from openpilot.system.ui.widgets.confirm_dialog import ConfirmDialog, alert_dialog +from openpilot.system.ui.widgets.html_render import HtmlModal +from openpilot.system.ui.widgets.list_view import text_item, button_item, dual_button_item +from openpilot.system.ui.widgets.option_dialog import MultiOptionDialog +from openpilot.system.ui.widgets.scroller_tici import Scroller + +if gui_app.sunnypilot_ui(): + from openpilot.system.ui.sunnypilot.widgets.list_view import button_item_sp as button_item + +# Description constants +DESCRIPTIONS = { + 'pair_device': tr_noop("Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer."), + 'driver_camera': tr_noop("Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off)"), + 'reset_calibration': tr_noop("sunnypilot requires the device to be mounted within 4° left or right and within 5° up or 9° down."), + 'review_guide': tr_noop("Review the rules, features, and limitations of sunnypilot"), +} + + +class DeviceLayout(Widget): + def __init__(self): + super().__init__() + + self._params = Params() + self._select_language_dialog: MultiOptionDialog | None = None + self._fcc_dialog: HtmlModal | None = None + self._training_guide: TrainingGuide | None = None + + items = self._initialize_items() + self._scroller = Scroller(items, line_separator=True, spacing=0) + + ui_state.add_offroad_transition_callback(self._offroad_transition) + + def _initialize_items(self): + self._pair_device_btn = button_item(lambda: tr("Pair Device"), lambda: tr("PAIR"), lambda: tr(DESCRIPTIONS['pair_device']), + callback=lambda: gui_app.push_widget(PairingDialog())) + self._pair_device_btn.set_visible(lambda: not ui_state.prime_state.is_paired()) + + self._reset_calib_btn = button_item(lambda: tr("Reset Calibration"), lambda: tr("RESET"), lambda: tr(DESCRIPTIONS['reset_calibration']), + callback=self._reset_calibration_prompt) + self._reset_calib_btn.set_description_opened_callback(self._update_calib_description) + + self._power_off_btn = dual_button_item(lambda: tr("Reboot"), lambda: tr("Power Off"), + left_callback=self._reboot_prompt, right_callback=self._power_off_prompt) + + items = [ + text_item(lambda: tr("Dongle ID"), self._params.get("DongleId") or (lambda: tr("N/A"))), + text_item(lambda: tr("Serial"), self._params.get("HardwareSerial") or (lambda: tr("N/A"))), + self._pair_device_btn, + button_item(lambda: tr("Driver Camera"), lambda: tr("PREVIEW"), lambda: tr(DESCRIPTIONS['driver_camera']), + callback=lambda: gui_app.push_widget(DriverCameraDialog()), enabled=ui_state.is_offroad), + self._reset_calib_btn, + button_item(lambda: tr("Review Training Guide"), lambda: tr("REVIEW"), lambda: tr(DESCRIPTIONS['review_guide']), + self._on_review_training_guide, enabled=ui_state.is_offroad), + button_item(lambda: tr("Regulatory"), lambda: tr("VIEW"), callback=self._on_regulatory, enabled=ui_state.is_offroad), + button_item(lambda: tr("Change Language"), lambda: tr("CHANGE"), callback=self._show_language_dialog), + self._power_off_btn, + ] + return items + + def _offroad_transition(self): + self._power_off_btn.action_item.right_button.set_visible(ui_state.is_offroad()) + + def show_event(self): + super().show_event() + self._scroller.show_event() + + def _render(self, rect): + self._scroller.render(rect) + + def _show_language_dialog(self): + def handle_language_selection(result: DialogResult): + if result == DialogResult.CONFIRM and self._select_language_dialog: + selected_language = multilang.languages[self._select_language_dialog.selection] + multilang.change_language(selected_language) + self._update_calib_description() + self._select_language_dialog = None + + self._select_language_dialog = MultiOptionDialog(tr("Select a language"), multilang.languages, multilang.codes[multilang.language], + option_font_weight=FontWeight.UNIFONT, callback=handle_language_selection) + gui_app.push_widget(self._select_language_dialog) + + def _reset_calibration_prompt(self): + if ui_state.engaged: + gui_app.push_widget(alert_dialog(tr("Disengage to Reset Calibration"))) + return + + def reset_calibration(result: DialogResult): + # Check engaged again in case it changed while the dialog was open + if ui_state.engaged or result != DialogResult.CONFIRM: + return + + self._params.remove("CalibrationParams") + self._params.remove("LiveTorqueParameters") + self._params.remove("LiveParametersV2") + self._params.remove("LiveDelay") + self._params.put_bool("OnroadCycleRequested", True, block=True) + self._update_calib_description() + + dialog = ConfirmDialog(tr("Are you sure you want to reset calibration?"), tr("Reset"), callback=reset_calibration) + gui_app.push_widget(dialog) + + def _update_calib_description(self): + desc = tr(DESCRIPTIONS['reset_calibration']) + + calib_bytes = self._params.get("CalibrationParams") + if calib_bytes: + try: + calib = messaging.log_from_bytes(calib_bytes, log.Event).liveCalibration + + if calib.calStatus != log.LiveCalibrationData.Status.uncalibrated: + pitch = math.degrees(calib.rpyCalib[1]) + yaw = math.degrees(calib.rpyCalib[2]) + desc += tr(" Your device is pointed {:.1f}° {} and {:.1f}° {}.").format(abs(pitch), tr("down") if pitch > 0 else tr("up"), + abs(yaw), tr("left") if yaw > 0 else tr("right")) + except Exception: + cloudlog.exception("invalid CalibrationParams") + + lag_perc = 0 + lag_bytes = self._params.get("LiveDelay") + if lag_bytes: + try: + lag_perc = messaging.log_from_bytes(lag_bytes, log.Event).liveDelay.calPerc + except Exception: + cloudlog.exception("invalid LiveDelay") + if lag_perc < 100: + desc += tr("

Steering lag calibration is {}% complete.").format(lag_perc) + else: + desc += tr("

Steering lag calibration is complete.") + + torque_bytes = self._params.get("LiveTorqueParameters") + if torque_bytes: + try: + torque = messaging.log_from_bytes(torque_bytes, log.Event).liveTorqueParameters + # don't add for non-torque cars + if torque.useParams: + torque_perc = torque.calPerc + if torque_perc < 100: + desc += tr(" Steering torque response calibration is {}% complete.").format(torque_perc) + else: + desc += tr(" Steering torque response calibration is complete.") + except Exception: + cloudlog.exception("invalid LiveTorqueParameters") + + desc += "

" + desc += tr("sunnypilot is continuously calibrating, resetting is rarely required. " + + "Resetting calibration will restart sunnypilot if the car is powered on.") + + self._reset_calib_btn.set_description(desc) + + def _reboot_prompt(self): + if ui_state.engaged: + gui_app.push_widget(alert_dialog(tr("Disengage to Reboot"))) + return + + def perform_reboot(result: DialogResult): + if not ui_state.engaged and result == DialogResult.CONFIRM: + self._params.put_bool("DoReboot", True) + + dialog = ConfirmDialog(tr("Are you sure you want to reboot?"), tr("Reboot"), callback=perform_reboot) + gui_app.push_widget(dialog) + + def _power_off_prompt(self): + if ui_state.engaged: + gui_app.push_widget(alert_dialog(tr("Disengage to Power Off"))) + return + + def perform_power_off(result: DialogResult): + if not ui_state.engaged and result == DialogResult.CONFIRM: + self._params.put_bool("DoShutdown", True) + + dialog = ConfirmDialog(tr("Are you sure you want to power off?"), tr("Power Off"), callback=perform_power_off) + gui_app.push_widget(dialog) + + def _on_regulatory(self): + if not self._fcc_dialog: + self._fcc_dialog = HtmlModal(os.path.join(BASEDIR, "openpilot/selfdrive/assets/offroad/fcc.html")) + gui_app.push_widget(self._fcc_dialog) + + def _on_review_training_guide(self): + if not self._training_guide: + self._training_guide = TrainingGuide() + gui_app.push_widget(self._training_guide) diff --git a/openpilot/selfdrive/ui/layouts/settings/firehose.py b/openpilot/selfdrive/ui/layouts/settings/firehose.py new file mode 100644 index 0000000000..8ac6fe3d23 --- /dev/null +++ b/openpilot/selfdrive/ui/layouts/settings/firehose.py @@ -0,0 +1,91 @@ +import pyray as rl + +from openpilot.system.ui.lib.application import gui_app, FontWeight, FONT_SCALE +from openpilot.system.ui.lib.multilang import tr, tr_noop +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.lib.scroll_panel import GuiScrollPanel +from openpilot.system.ui.lib.wrap_text import wrap_text +from openpilot.selfdrive.ui.mici.layouts.settings.firehose import FirehoseLayoutBase + +TITLE = tr_noop("Firehose Mode") +DESCRIPTION = tr_noop( + "sunnypilot learns to drive by watching humans, like you, drive.\n\n" + + "Firehose Mode allows you to maximize your training data uploads to improve " + + "openpilot's driving models. More data means bigger models, which means better Experimental Mode." +) +INSTRUCTIONS = tr_noop( + "For maximum effectiveness, bring your device inside and connect to a good USB-C adapter and Wi-Fi weekly.\n\n" + + "Firehose Mode can also work while you're driving if connected to a hotspot or unlimited SIM card.\n\n\n" + + "Frequently Asked Questions\n\n" + + "Does it matter how or where I drive? Nope, just drive as you normally would.\n\n" + + "Do all of my segments get pulled in Firehose Mode? No, we selectively pull a subset of your segments.\n\n" + + "What's a good USB-C adapter? Any fast phone or laptop charger should be fine.\n\n" + + "Does it matter which software I run? Yes, only upstream openpilot (and particular forks) are able to be used for training." +) + + +class FirehoseLayout(FirehoseLayoutBase): + def __init__(self): + super().__init__() + self._scroll_panel = GuiScrollPanel() + + def _render(self, rect: rl.Rectangle): + # Calculate content dimensions + content_rect = rl.Rectangle(rect.x, rect.y, rect.width, self._content_height) + + # Handle scrolling and render with clipping + scroll_offset = self._scroll_panel.update(rect, content_rect) + rl.begin_scissor_mode(int(rect.x), int(rect.y), int(rect.width), int(rect.height)) + self._content_height = self._render_content(rect, scroll_offset) + rl.end_scissor_mode() + + def _render_content(self, rect: rl.Rectangle, scroll_offset: float) -> int: + x = int(rect.x + 40) + y = int(rect.y + 40 + scroll_offset) + w = int(rect.width - 80) + + # Title (centered) + title_text = tr(TITLE) # live translate + title_font = gui_app.font(FontWeight.MEDIUM) + text_width = measure_text_cached(title_font, title_text, 100).x + title_x = rect.x + (rect.width - text_width) / 2 + rl.draw_text_ex(title_font, title_text, rl.Vector2(title_x, y), 100, 0, rl.WHITE) + y += 200 + + # Description + y = self._draw_wrapped_text(x, y, w, tr(DESCRIPTION), gui_app.font(FontWeight.NORMAL), 45, rl.WHITE) + y += 40 + 20 + + # Separator + rl.draw_rectangle(x, y, w, 2, self.GRAY) + y += 30 + 20 + + # Status + status_text, status_color = self._get_status() + y = self._draw_wrapped_text(x, y, w, status_text, gui_app.font(FontWeight.BOLD), 60, status_color) + y += 20 + 20 + + # TODO: add back once reliable + # Contribution count (if available) + #if self._segment_count > 0: + # contrib_text = trn("{} segment of your driving is in the training dataset so far.", + # "{} segments of your driving is in the training dataset so far.", self._segment_count).format(self._segment_count) + # y = self._draw_wrapped_text(x, y, w, contrib_text, gui_app.font(FontWeight.BOLD), 52, rl.WHITE) + # y += 20 + 20 + + # Separator + rl.draw_rectangle(x, y, w, 2, self.GRAY) + y += 30 + 20 + + # Instructions + y = self._draw_wrapped_text(x, y, w, tr(INSTRUCTIONS), gui_app.font(FontWeight.NORMAL), 40, self.LIGHT_GRAY) + + # bottom margin + remove effect of scroll offset + return int(round(y - self._scroll_panel.offset + 40)) + + def _draw_wrapped_text(self, x, y, width, text, font, font_size, color): + wrapped = wrap_text(font, text, font_size, width) + for line in wrapped: + rl.draw_text_ex(font, line, rl.Vector2(x, y), font_size, 0, color) + y += font_size * FONT_SCALE + return round(y) diff --git a/openpilot/selfdrive/ui/layouts/settings/settings.py b/openpilot/selfdrive/ui/layouts/settings/settings.py new file mode 100644 index 0000000000..48b75e5dbd --- /dev/null +++ b/openpilot/selfdrive/ui/layouts/settings/settings.py @@ -0,0 +1,173 @@ +import pyray as rl +from dataclasses import dataclass, field +from enum import IntEnum +from collections.abc import Callable +from openpilot.selfdrive.ui.layouts.settings.developer import DeveloperLayout +from openpilot.selfdrive.ui.layouts.settings.device import DeviceLayout +from openpilot.selfdrive.ui.layouts.settings.firehose import FirehoseLayout +from openpilot.selfdrive.ui.layouts.settings.software import SoftwareLayout +from openpilot.selfdrive.ui.layouts.settings.toggles import TogglesLayout +from openpilot.system.ui.lib.application import gui_app, FontWeight, MousePos +from openpilot.system.ui.lib.multilang import tr, tr_noop +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.lib.wifi_manager import WifiManager +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.network import NetworkUI + +# Constants +SIDEBAR_WIDTH = 500 +CLOSE_BTN_SIZE = 200 +CLOSE_ICON_SIZE = 70 +NAV_BTN_HEIGHT = 110 +PANEL_MARGIN = 50 + +# Colors +SIDEBAR_COLOR = rl.BLACK +PANEL_COLOR = rl.Color(41, 41, 41, 255) +CLOSE_BTN_COLOR = rl.Color(41, 41, 41, 255) +CLOSE_BTN_PRESSED = rl.Color(59, 59, 59, 255) +TEXT_NORMAL = rl.Color(128, 128, 128, 255) +TEXT_SELECTED = rl.WHITE + + +class PanelType(IntEnum): + DEVICE = 0 + NETWORK = 1 + TOGGLES = 2 + SOFTWARE = 3 + FIREHOSE = 4 + DEVELOPER = 5 + + +@dataclass +class PanelInfo: + name: str + instance: Widget + button_rect: rl.Rectangle = field(default_factory=lambda: rl.Rectangle(0, 0, 0, 0)) + + +class SettingsLayout(Widget): + def __init__(self): + super().__init__() + self._current_panel = PanelType.DEVICE + + # Panel configuration + wifi_manager = WifiManager() + wifi_manager.set_active(False) + + self._panels = { + PanelType.DEVICE: PanelInfo(tr_noop("Device"), DeviceLayout()), + PanelType.NETWORK: PanelInfo(tr_noop("Network"), NetworkUI(wifi_manager)), + PanelType.TOGGLES: PanelInfo(tr_noop("Toggles"), TogglesLayout()), + PanelType.SOFTWARE: PanelInfo(tr_noop("Software"), SoftwareLayout()), + PanelType.FIREHOSE: PanelInfo(tr_noop("Firehose"), FirehoseLayout()), + PanelType.DEVELOPER: PanelInfo(tr_noop("Developer"), DeveloperLayout()), + } + + self._font_medium = gui_app.font(FontWeight.MEDIUM) + self._close_icon = gui_app.texture("icons/close2.png", CLOSE_ICON_SIZE, CLOSE_ICON_SIZE) + + # Callbacks + self._close_callback: Callable | None = None + + def set_callbacks(self, on_close: Callable): + self._close_callback = on_close + + def _render(self, rect: rl.Rectangle): + # Calculate layout + sidebar_rect = rl.Rectangle(rect.x, rect.y, SIDEBAR_WIDTH, rect.height) + panel_rect = rl.Rectangle(rect.x + SIDEBAR_WIDTH, rect.y, rect.width - SIDEBAR_WIDTH, rect.height) + + # Draw components + self._draw_sidebar(sidebar_rect) + self._draw_current_panel(panel_rect) + + def _draw_sidebar(self, rect: rl.Rectangle): + rl.draw_rectangle_rec(rect, SIDEBAR_COLOR) + + # Close button + close_btn_rect = rl.Rectangle( + rect.x + (rect.width - CLOSE_BTN_SIZE) / 2, rect.y + 60, CLOSE_BTN_SIZE, CLOSE_BTN_SIZE + ) + + pressed = (rl.is_mouse_button_down(rl.MouseButton.MOUSE_BUTTON_LEFT) and + rl.check_collision_point_rec(rl.get_mouse_position(), close_btn_rect)) + close_color = CLOSE_BTN_PRESSED if pressed else CLOSE_BTN_COLOR + rl.draw_rectangle_rounded(close_btn_rect, 1.0, 20, close_color) + + icon_color = rl.Color(255, 255, 255, 255) if not pressed else rl.Color(220, 220, 220, 255) + icon_dest = rl.Rectangle( + close_btn_rect.x + (close_btn_rect.width - self._close_icon.width) / 2, + close_btn_rect.y + (close_btn_rect.height - self._close_icon.height) / 2, + self._close_icon.width, + self._close_icon.height, + ) + rl.draw_texture_pro( + self._close_icon, + rl.Rectangle(0, 0, self._close_icon.width, self._close_icon.height), + icon_dest, + rl.Vector2(0, 0), + 0, + icon_color, + ) + + # Store close button rect for click detection + self._close_btn_rect = close_btn_rect + + # Navigation buttons + y = rect.y + 300 + for panel_type, panel_info in self._panels.items(): + button_rect = rl.Rectangle(rect.x + 50, y, rect.width - 150, NAV_BTN_HEIGHT) + + # Button styling + is_selected = panel_type == self._current_panel + text_color = TEXT_SELECTED if is_selected else TEXT_NORMAL + # Draw button text (right-aligned) + panel_name = tr(panel_info.name) + text_size = measure_text_cached(self._font_medium, panel_name, 65) + text_pos = rl.Vector2( + button_rect.x + button_rect.width - text_size.x, button_rect.y + (button_rect.height - text_size.y) / 2 + ) + rl.draw_text_ex(self._font_medium, panel_name, text_pos, 65, 0, text_color) + + # Store button rect for click detection + panel_info.button_rect = button_rect + + y += NAV_BTN_HEIGHT + + def _draw_current_panel(self, rect: rl.Rectangle): + rl.draw_rectangle_rounded( + rl.Rectangle(rect.x + 10, rect.y + 10, rect.width - 20, rect.height - 20), 0.04, 30, PANEL_COLOR + ) + content_rect = rl.Rectangle(rect.x + PANEL_MARGIN, rect.y + 25, rect.width - (PANEL_MARGIN * 2), rect.height - 50) + # rl.draw_rectangle_rounded(content_rect, 0.03, 30, PANEL_COLOR) + panel = self._panels[self._current_panel] + if panel.instance: + panel.instance.render(content_rect) + + def _handle_mouse_release(self, mouse_pos: MousePos) -> None: + # Check close button + if rl.check_collision_point_rec(mouse_pos, self._close_btn_rect): + if self._close_callback: + self._close_callback() + return + + # Check navigation buttons + for panel_type, panel_info in self._panels.items(): + if rl.check_collision_point_rec(mouse_pos, panel_info.button_rect): + self.set_current_panel(panel_type) + return + + def set_current_panel(self, panel_type: PanelType): + if panel_type != self._current_panel: + self._panels[self._current_panel].instance.hide_event() + self._current_panel = panel_type + self._panels[self._current_panel].instance.show_event() + + def show_event(self): + super().show_event() + self._panels[self._current_panel].instance.show_event() + + def hide_event(self): + super().hide_event() + self._panels[self._current_panel].instance.hide_event() diff --git a/openpilot/selfdrive/ui/layouts/settings/software.py b/openpilot/selfdrive/ui/layouts/settings/software.py new file mode 100644 index 0000000000..d0016797fc --- /dev/null +++ b/openpilot/selfdrive/ui/layouts/settings/software.py @@ -0,0 +1,206 @@ +import subprocess +import time +import datetime +from openpilot.common.time_helpers import system_time_valid +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.lib.multilang import tr, trn +from openpilot.system.ui.widgets import Widget, DialogResult +from openpilot.system.ui.widgets.confirm_dialog import ConfirmDialog +from openpilot.system.ui.widgets.list_view import button_item, text_item, ListItem +from openpilot.system.ui.widgets.option_dialog import MultiOptionDialog +from openpilot.system.ui.widgets.scroller_tici import Scroller + +if gui_app.sunnypilot_ui(): + from openpilot.system.ui.sunnypilot.widgets.list_view import button_item_sp as button_item + +# TODO: remove this. updater fails to respond on startup if time is not correct +UPDATED_TIMEOUT = 10 # seconds to wait for updated to respond + +# Mapping updater internal states to translated display strings +STATE_TO_DISPLAY_TEXT = { + "checking...": tr("checking..."), + "downloading...": tr("downloading..."), + "finalizing update...": tr("finalizing update..."), +} + + +def time_ago(date: datetime.datetime | None) -> str: + if not date: + return tr("never") + + if not system_time_valid(): + return date.strftime("%a %b %d %Y") + + now = datetime.datetime.now(datetime.UTC) + if date.tzinfo is None: + date = date.replace(tzinfo=datetime.UTC) + + diff_seconds = int((now - date).total_seconds()) + if diff_seconds < 60: + return tr("now") + if diff_seconds < 3600: + m = diff_seconds // 60 + return trn("{} minute ago", "{} minutes ago", m).format(m) + if diff_seconds < 86400: + h = diff_seconds // 3600 + return trn("{} hour ago", "{} hours ago", h).format(h) + if diff_seconds < 604800: + d = diff_seconds // 86400 + return trn("{} day ago", "{} days ago", d).format(d) + return date.strftime("%a %b %d %Y") + + +class SoftwareLayout(Widget): + def __init__(self): + super().__init__() + + self._onroad_label = ListItem(lambda: tr("Updates are only downloaded while the car is off.")) + self._version_item = text_item(lambda: tr("Current Version"), ui_state.params.get("UpdaterCurrentDescription") or "") + self._download_btn = button_item(lambda: tr("Download"), lambda: tr("CHECK"), callback=self._on_download_update) + + # Install button is initially hidden + self._install_btn = button_item(lambda: tr("Install Update"), lambda: tr("INSTALL"), callback=self._on_install_update) + self._install_btn.set_visible(False) + + # Track waiting-for-updater transition to avoid brief re-enable while still idle + self._waiting_for_updater = False + self._waiting_start_ts: float = 0.0 + + # Branch switcher + self._branch_btn = button_item(lambda: tr("Target Branch"), lambda: tr("SELECT"), callback=self._on_select_branch) + self._branch_btn.action_item.set_value(ui_state.params.get("UpdaterTargetBranch") or "") + self._branch_dialog: MultiOptionDialog | None = None + + self._scroller = Scroller([ + self._onroad_label, + self._version_item, + self._download_btn, + self._install_btn, + self._branch_btn, + button_item(lambda: tr("Uninstall"), lambda: tr("UNINSTALL"), callback=self._on_uninstall), + ], line_separator=True, spacing=0) + + def show_event(self): + super().show_event() + self._scroller.show_event() + + def _render(self, rect): + self._scroller.render(rect) + + def _update_state(self): + # Show/hide onroad warning + self._onroad_label.set_visible(ui_state.is_onroad()) + + # Update current version and release notes + current_desc = ui_state.params.get("UpdaterCurrentDescription") or "" + current_release_notes = (ui_state.params.get("UpdaterCurrentReleaseNotes") or b"").decode("utf-8", "replace") + self._version_item.action_item.set_text(current_desc) + self._version_item.set_description(current_release_notes) + + # Update download button visibility and state + self._download_btn.set_visible(ui_state.is_offroad()) + + updater_state = ui_state.params.get("UpdaterState") or "idle" + failed_count = ui_state.params.get("UpdateFailedCount") or 0 + fetch_available = ui_state.params.get_bool("UpdaterFetchAvailable") + update_available = ui_state.params.get_bool("UpdateAvailable") + + if updater_state != "idle": + # Updater responded + self._waiting_for_updater = False + self._download_btn.action_item.set_enabled(False) + # Use the mapping, with a fallback to the original state string + display_text = STATE_TO_DISPLAY_TEXT.get(updater_state, updater_state) + self._download_btn.action_item.set_value(display_text) + else: + if failed_count > 0: + self._download_btn.action_item.set_value(tr("failed to check for update")) + self._download_btn.action_item.set_text(tr("CHECK")) + elif fetch_available: + self._download_btn.action_item.set_value(tr("update available")) + self._download_btn.action_item.set_text(tr("DOWNLOAD")) + else: + last_update = ui_state.params.get("LastUpdateTime") + if last_update: + formatted = time_ago(last_update) + self._download_btn.action_item.set_value(tr("up to date, last checked {}").format(formatted)) + else: + self._download_btn.action_item.set_value(tr("up to date, last checked never")) + self._download_btn.action_item.set_text(tr("CHECK")) + + # If we've been waiting too long without a state change, reset state + if self._waiting_for_updater and (time.monotonic() - self._waiting_start_ts > UPDATED_TIMEOUT): + self._waiting_for_updater = False + + # Only enable if we're not waiting for updater to flip out of idle + self._download_btn.action_item.set_enabled(not self._waiting_for_updater) + + # Update target branch button value + current_branch = ui_state.params.get("UpdaterTargetBranch") or "" + self._branch_btn.action_item.set_value(current_branch) + + # Update install button + self._install_btn.set_visible(ui_state.is_offroad() and update_available) + if update_available: + new_desc = ui_state.params.get("UpdaterNewDescription") or "" + new_release_notes = (ui_state.params.get("UpdaterNewReleaseNotes") or b"").decode("utf-8", "replace") + self._install_btn.action_item.set_text(tr("INSTALL")) + self._install_btn.action_item.set_value(new_desc) + self._install_btn.set_description(new_release_notes) + # Enable install button for testing (like Qt showEvent) + self._install_btn.action_item.set_enabled(True) + else: + self._install_btn.set_visible(False) + + def _on_download_update(self): + # Check if we should start checking or start downloading + self._download_btn.action_item.set_enabled(False) + if self._download_btn.action_item.text == tr("CHECK"): + # Start checking for updates + self._waiting_for_updater = True + self._waiting_start_ts = time.monotonic() + subprocess.run("pkill -SIGUSR1 -f openpilot.system.updated.updated", shell=True) + else: + # Start downloading + self._waiting_for_updater = True + self._waiting_start_ts = time.monotonic() + subprocess.run("pkill -SIGHUP -f openpilot.system.updated.updated", shell=True) + + def _on_uninstall(self): + def handle_uninstall_confirmation(result: DialogResult): + if result == DialogResult.CONFIRM: + ui_state.params.put_bool("DoUninstall", True, block=True) + + dialog = ConfirmDialog(tr("Are you sure you want to uninstall?"), tr("Uninstall"), callback=handle_uninstall_confirmation) + gui_app.push_widget(dialog) + + def _on_install_update(self): + # Trigger reboot to install update + self._install_btn.action_item.set_enabled(False) + ui_state.params.put_bool("DoReboot", True, block=True) + + def _on_select_branch(self): + # Get available branches and order + current_git_branch = ui_state.params.get("GitBranch") or "" + branches_str = ui_state.params.get("UpdaterAvailableBranches") or "" + branches = [b for b in branches_str.split(",") if b] + + for b in [current_git_branch, "devel-staging", "devel", "nightly", "nightly-dev", "master"]: + if b in branches: + branches.remove(b) + branches.insert(0, b) + + current_target = ui_state.params.get("UpdaterTargetBranch") or "" + + def handle_selection(result: DialogResult): + # Confirmed selection + if result == DialogResult.CONFIRM and self._branch_dialog is not None and self._branch_dialog.selection: + selection = self._branch_dialog.selection + ui_state.params.put("UpdaterTargetBranch", selection, block=True) + self._branch_btn.action_item.set_value(selection) + subprocess.run("pkill -SIGUSR1 -f openpilot.system.updated.updated", shell=True) + self._branch_dialog = None + + self._branch_dialog = MultiOptionDialog(tr("Select a branch"), branches, current_target, callback=handle_selection) + gui_app.push_widget(self._branch_dialog) diff --git a/openpilot/selfdrive/ui/layouts/settings/toggles.py b/openpilot/selfdrive/ui/layouts/settings/toggles.py new file mode 100644 index 0000000000..ee76b7e4cc --- /dev/null +++ b/openpilot/selfdrive/ui/layouts/settings/toggles.py @@ -0,0 +1,249 @@ +from openpilot.cereal import log +from openpilot.common.params import Params, UnknownKeyName +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.list_view import multiple_button_item, toggle_item +from openpilot.system.ui.widgets.scroller_tici import Scroller +from openpilot.system.ui.widgets.confirm_dialog import ConfirmDialog +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.lib.multilang import tr, tr_noop +from openpilot.system.ui.widgets import DialogResult +from openpilot.selfdrive.ui.ui_state import ui_state + +if gui_app.sunnypilot_ui(): + from openpilot.system.ui.sunnypilot.widgets.list_view import toggle_item_sp as toggle_item + from openpilot.system.ui.sunnypilot.widgets.list_view import multiple_button_item_sp as multiple_button_item + +PERSONALITY_TO_INT = log.LongitudinalPersonality.schema.enumerants + +# Description constants +DESCRIPTIONS = { + "OpenpilotEnabledToggle": tr_noop( + "Use the sunnypilot system for adaptive cruise control and lane keep driver assistance. " + + "Your attention is required at all times to use this feature." + ), + "DisengageOnAccelerator": tr_noop("When enabled, pressing the accelerator pedal will disengage sunnypilot."), + "LongitudinalPersonality": tr_noop( + "Standard is recommended. In aggressive mode, sunnypilot will follow lead cars closer and be more aggressive with the gas and brake. " + + "In relaxed mode sunnypilot will stay further away from lead cars. On supported cars, you can cycle through these personalities with " + + "your steering wheel distance button." + ), + "IsLdwEnabled": tr_noop( + "Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line " + + "without a turn signal activated while driving over 31 mph (50 km/h)." + ), + "AlwaysOnDM": tr_noop("Enable driver monitoring even when sunnypilot is not engaged."), + 'RecordFront': tr_noop("Upload data from the driver facing camera and help improve the driver monitoring algorithm."), + "IsMetric": tr_noop("Display speed in km/h instead of mph."), + "RecordAudio": tr_noop("Record and store microphone audio while driving. The audio will be included in the dashcam video in comma connect."), +} + + +class TogglesLayout(Widget): + def __init__(self): + super().__init__() + self._params = Params() + self._is_release = False # self._params.get_bool("IsReleaseBranch") + + # param, title, desc, icon, needs_restart + self._toggle_defs = { + "OpenpilotEnabledToggle": ( + lambda: tr("Enable sunnypilot"), + DESCRIPTIONS["OpenpilotEnabledToggle"], + "chffr_wheel.png", + True, + ), + "ExperimentalMode": ( + lambda: tr("Experimental Mode"), + "", + "experimental_white.png", + False, + ), + "DisengageOnAccelerator": ( + lambda: tr("Disengage on Accelerator Pedal"), + DESCRIPTIONS["DisengageOnAccelerator"], + "disengage_on_accelerator.png", + False, + ), + "IsLdwEnabled": ( + lambda: tr("Enable Lane Departure Warnings"), + DESCRIPTIONS["IsLdwEnabled"], + "warning.png", + False, + ), + "AlwaysOnDM": ( + lambda: tr("Always-On Driver Monitoring"), + DESCRIPTIONS["AlwaysOnDM"], + "monitoring.png", + False, + ), + "RecordFront": ( + lambda: tr("Record and Upload Driver Camera"), + DESCRIPTIONS["RecordFront"], + "monitoring.png", + True, + ), + "RecordAudio": ( + lambda: tr("Record and Upload Microphone Audio"), + DESCRIPTIONS["RecordAudio"], + "microphone.png", + True, + ), + "IsMetric": ( + lambda: tr("Use Metric System"), + DESCRIPTIONS["IsMetric"], + "metric.png", + False, + ), + } + + self._long_personality_setting = multiple_button_item( + lambda: tr("Driving Personality"), + lambda: tr(DESCRIPTIONS["LongitudinalPersonality"]), + buttons=[lambda: tr("Aggressive"), lambda: tr("Standard"), lambda: tr("Relaxed")], + button_width=300, + callback=self._set_longitudinal_personality, + selected_index=self._params.get("LongitudinalPersonality", return_default=True), + icon="speed_limit.png" + ) + + self._toggles = {} + self._locked_toggles = set() + for param, (title, desc, icon, needs_restart) in self._toggle_defs.items(): + toggle = toggle_item( + title, + desc, + self._params.get_bool(param), + callback=lambda state, p=param: self._toggle_callback(state, p), + icon=icon, + ) + + try: + locked = self._params.get_bool(param + "Lock") + except UnknownKeyName: + locked = False + toggle.action_item.set_enabled(not locked) + + # Make description callable for live translation + additional_desc = "" + if needs_restart and not locked: + additional_desc = tr("Changing this setting will restart sunnypilot if the car is powered on.") + toggle.set_description(lambda og_desc=toggle.description, add_desc=additional_desc: tr(og_desc) + (" " + tr(add_desc) if add_desc else "")) + + # track for engaged state updates + if locked: + self._locked_toggles.add(param) + + self._toggles[param] = toggle + + # insert longitudinal personality after NDOG toggle + if param == "DisengageOnAccelerator": + self._toggles["LongitudinalPersonality"] = self._long_personality_setting + + self._update_experimental_mode_icon() + self._scroller = Scroller(list(self._toggles.values()), line_separator=True, spacing=0) + + ui_state.add_engaged_transition_callback(self._update_toggles) + + def _update_state(self): + if ui_state.sm.updated["selfdriveState"]: + personality = PERSONALITY_TO_INT[ui_state.sm["selfdriveState"].personality] + if personality != ui_state.personality and ui_state.started: + self._long_personality_setting.action_item.set_selected_button(personality) + ui_state.personality = personality + + def show_event(self): + super().show_event() + self._scroller.show_event() + self._update_toggles() + + def _update_toggles(self): + ui_state.update_params() + + e2e_description = tr( + "sunnypilot defaults to driving in chill mode. Experimental mode enables alpha-level features that aren't ready for chill mode. " + + "Experimental features are listed below:
" + + "

End-to-End Longitudinal Control


" + + "Let the driving model control the gas and brakes. sunnypilot will drive as it thinks a human would, including stopping for red lights and stop signs. " + + "Since the driving model decides the speed to drive, the set speed will only act as an upper bound. This is an alpha quality feature; " + + "mistakes should be expected.
" + + "

New Driving Visualization


" + + "The driving visualization will transition to the road-facing wide-angle camera at low speeds to better show some turns. " + + "The Experimental mode logo will also be shown in the top right corner." + ) + + if ui_state.CP is not None: + if ui_state.has_longitudinal_control: + self._toggles["ExperimentalMode"].action_item.set_enabled(True) + self._toggles["ExperimentalMode"].set_description(e2e_description) + self._long_personality_setting.action_item.set_enabled(True) + else: + # no long for now + self._toggles["ExperimentalMode"].action_item.set_enabled(False) + self._toggles["ExperimentalMode"].action_item.set_state(False) + self._long_personality_setting.action_item.set_enabled(False) + self._params.remove("ExperimentalMode") + + unavailable = tr("Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control.") + + long_desc = unavailable + " " + tr("sunnypilot longitudinal control may come in a future update.") + if ui_state.CP.alphaLongitudinalAvailable: + if self._is_release: + long_desc = unavailable + " " + tr("An alpha version of sunnypilot longitudinal control can be tested, along with " + + "Experimental mode, on non-release branches.") + else: + long_desc = tr("Enable the sunnypilot longitudinal control (alpha) toggle to allow Experimental mode.") + + self._toggles["ExperimentalMode"].set_description("" + long_desc + "

" + e2e_description) + else: + self._toggles["ExperimentalMode"].set_description(e2e_description) + + self._update_experimental_mode_icon() + + # TODO: make a param control list item so we don't need to manage internal state as much here + # refresh toggles from params to mirror external changes + for param in self._toggle_defs: + self._toggles[param].action_item.set_state(self._params.get_bool(param)) + + # these toggles need restart, block while engaged + for toggle_def in self._toggle_defs: + if self._toggle_defs[toggle_def][3] and toggle_def not in self._locked_toggles: + self._toggles[toggle_def].action_item.set_enabled(not ui_state.engaged) + + def _render(self, rect): + self._scroller.render(rect) + + def _update_experimental_mode_icon(self): + icon = "experimental.png" if self._toggles["ExperimentalMode"].action_item.get_state() else "experimental_white.png" + self._toggles["ExperimentalMode"].set_icon(icon) + + def _handle_experimental_mode_toggle(self, state: bool): + confirmed = self._params.get_bool("ExperimentalModeConfirmed") + if state and not confirmed: + def confirm_callback(result: DialogResult): + if result == DialogResult.CONFIRM: + self._params.put_bool("ExperimentalMode", True, block=True) + self._params.put_bool("ExperimentalModeConfirmed", True, block=True) + else: + self._toggles["ExperimentalMode"].action_item.set_state(False) + self._update_experimental_mode_icon() + + # show confirmation dialog + content = (f"

{self._toggles['ExperimentalMode'].title}


" + + f"

{self._toggles['ExperimentalMode'].description}

") + dlg = ConfirmDialog(content, tr("Enable"), rich=True, callback=confirm_callback) + gui_app.push_widget(dlg) + else: + self._update_experimental_mode_icon() + self._params.put_bool("ExperimentalMode", state, block=True) + + def _toggle_callback(self, state: bool, param: str): + if param == "ExperimentalMode": + self._handle_experimental_mode_toggle(state) + return + + self._params.put_bool(param, state, block=True) + if self._toggle_defs[param][3]: + self._params.put_bool("OnroadCycleRequested", True, block=True) + + def _set_longitudinal_personality(self, button_index: int): + self._params.put("LongitudinalPersonality", button_index, block=True) diff --git a/openpilot/selfdrive/ui/layouts/sidebar.py b/openpilot/selfdrive/ui/layouts/sidebar.py new file mode 100644 index 0000000000..f950edaa46 --- /dev/null +++ b/openpilot/selfdrive/ui/layouts/sidebar.py @@ -0,0 +1,238 @@ +import pyray as rl +import time +from dataclasses import dataclass +from collections.abc import Callable +from openpilot.cereal import log +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.ui.lib.application import gui_app, FontWeight, MousePos, FONT_SCALE +from openpilot.system.ui.lib.multilang import tr, tr_noop +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.widgets import Widget + +from openpilot.selfdrive.ui.sunnypilot.layouts.sidebar import SidebarSP + +SIDEBAR_WIDTH = 300 +METRIC_HEIGHT = 126 +METRIC_WIDTH = 240 +METRIC_MARGIN = 30 +FONT_SIZE = 35 + +SETTINGS_BTN = rl.Rectangle(50, 35, 200, 117) +HOME_BTN = rl.Rectangle(60, 860, 180, 180) + +ThermalStatus = log.DeviceState.ThermalStatus +NetworkType = log.DeviceState.NetworkType + + +# Color scheme +class Colors: + WHITE = rl.WHITE + WHITE_DIM = rl.Color(255, 255, 255, 85) + GRAY = rl.Color(84, 84, 84, 255) + + # Status colors + GOOD = rl.WHITE + WARNING = rl.Color(218, 202, 37, 255) + DANGER = rl.Color(201, 34, 49, 255) + + # UI elements + METRIC_BORDER = rl.Color(255, 255, 255, 85) + BUTTON_NORMAL = rl.WHITE + BUTTON_PRESSED = rl.Color(255, 255, 255, 166) + + +NETWORK_TYPES = { + NetworkType.none: tr_noop("--"), + NetworkType.wifi: tr_noop("Wi-Fi"), + NetworkType.ethernet: tr_noop("ETH"), + NetworkType.cell2G: tr_noop("2G"), + NetworkType.cell3G: tr_noop("3G"), + NetworkType.cell4G: tr_noop("LTE"), + NetworkType.cell5G: tr_noop("5G"), +} + + +@dataclass(slots=True) +class MetricData: + label: str + value: str + color: rl.Color + + def update(self, label: str, value: str, color: rl.Color): + self.label = label + self.value = value + self.color = color + + +class Sidebar(Widget, SidebarSP): + def __init__(self): + Widget.__init__(self) + SidebarSP.__init__(self) + self._net_type = NETWORK_TYPES[NetworkType.none] + self._net_strength = 0 + + self._temp_status = MetricData(tr_noop("TEMP"), tr_noop("GOOD"), Colors.GOOD) + self._panda_status = MetricData(tr_noop("VEHICLE"), tr_noop("ONLINE"), Colors.GOOD) + self._connect_status = MetricData(tr_noop("CONNECT"), tr_noop("OFFLINE"), Colors.WARNING) + self._recording_audio = False + + self._home_img = gui_app.texture("images/button_home.png", HOME_BTN.width, HOME_BTN.height) + self._flag_img = gui_app.texture("images/button_flag.png", HOME_BTN.width, HOME_BTN.height) + self._settings_img = gui_app.texture("images/button_settings.png", SETTINGS_BTN.width, SETTINGS_BTN.height) + self._mic_img = gui_app.texture("icons/microphone.png", 30, 30) + self._mic_indicator_rect = rl.Rectangle(0, 0, 0, 0) + self._font_regular = gui_app.font(FontWeight.NORMAL) + self._font_bold = gui_app.font(FontWeight.SEMI_BOLD) + + # Callbacks + self._on_settings_click: Callable | None = None + self._on_flag_click: Callable | None = None + self._open_settings_callback: Callable | None = None + + def set_callbacks(self, on_settings: Callable | None = None, on_flag: Callable | None = None, + open_settings: Callable | None = None): + self._on_settings_click = on_settings + self._on_flag_click = on_flag + self._open_settings_callback = open_settings + + def _render(self, rect: rl.Rectangle): + # Background + rl.draw_rectangle_rec(rect, rl.BLACK) + + self._draw_buttons(rect) + self._draw_network_indicator(rect) + self._draw_metrics(rect) + + def _update_state(self): + sm = ui_state.sm + if not sm.updated['deviceState']: + return + + device_state = sm['deviceState'] + + self._recording_audio = ui_state.recording_audio + self._update_network_status(device_state) + self._update_temperature_status(device_state) + self._update_connection_status(device_state) + self._update_panda_status() + SidebarSP._update_sunnylink_status(self) + + def _update_network_status(self, device_state): + self._net_type = NETWORK_TYPES.get(device_state.networkType.raw, tr_noop("Unknown")) + strength = device_state.networkStrength + self._net_strength = max(0, min(5, strength.raw + 1)) if strength.raw > 0 else 0 + + def _update_temperature_status(self, device_state): + thermal_status = device_state.thermalStatus + + if thermal_status == ThermalStatus.ok: + self._temp_status.update(tr_noop("TEMP"), tr_noop("GOOD"), Colors.GOOD) + else: + self._temp_status.update(tr_noop("TEMP"), tr_noop("HIGH"), Colors.DANGER) + + def _update_connection_status(self, device_state): + last_ping = device_state.lastAthenaPingTime + if last_ping == 0: + self._connect_status.update(tr_noop("CONNECT"), tr_noop("OFFLINE"), Colors.WARNING) + elif time.monotonic_ns() - last_ping < 80_000_000_000: # 80 seconds in nanoseconds + self._connect_status.update(tr_noop("CONNECT"), tr_noop("ONLINE"), Colors.GOOD) + else: + self._connect_status.update(tr_noop("CONNECT"), tr_noop("ERROR"), Colors.DANGER) + + def _update_panda_status(self): + if ui_state.panda_type == log.PandaState.PandaType.unknown: + self._panda_status.update(tr_noop("NO"), tr_noop("PANDA"), Colors.DANGER) + else: + self._panda_status.update(tr_noop("VEHICLE"), tr_noop("ONLINE"), Colors.GOOD) + + def _handle_mouse_release(self, mouse_pos: MousePos): + if rl.check_collision_point_rec(mouse_pos, SETTINGS_BTN): + if self._on_settings_click: + self._on_settings_click() + elif rl.check_collision_point_rec(mouse_pos, HOME_BTN) and ui_state.started: + if self._on_flag_click: + self._on_flag_click() + elif self._recording_audio and rl.check_collision_point_rec(mouse_pos, self._mic_indicator_rect): + if self._open_settings_callback: + self._open_settings_callback() + + def _draw_buttons(self, rect: rl.Rectangle): + mouse_pos = rl.get_mouse_position() + mouse_down = self.is_pressed and rl.is_mouse_button_down(rl.MouseButton.MOUSE_BUTTON_LEFT) + + # Settings button + settings_down = mouse_down and rl.check_collision_point_rec(mouse_pos, SETTINGS_BTN) + tint = Colors.BUTTON_PRESSED if settings_down else Colors.BUTTON_NORMAL + rl.draw_texture_ex(self._settings_img, rl.Vector2(SETTINGS_BTN.x, SETTINGS_BTN.y), 0.0, 1.0, tint) + + # Home/Flag button + flag_pressed = mouse_down and rl.check_collision_point_rec(mouse_pos, HOME_BTN) + button_img = self._flag_img if ui_state.started else self._home_img + + tint = Colors.BUTTON_PRESSED if (ui_state.started and flag_pressed) else Colors.BUTTON_NORMAL + rl.draw_texture_ex(button_img, rl.Vector2(HOME_BTN.x, HOME_BTN.y), 0.0, 1.0, tint) + + # Microphone button + if self._recording_audio: + self._mic_indicator_rect = rl.Rectangle(rect.x + rect.width - 130, rect.y + 245, 75, 40) + + mic_pressed = mouse_down and rl.check_collision_point_rec(mouse_pos, self._mic_indicator_rect) + bg_color = rl.Color(Colors.DANGER.r, Colors.DANGER.g, Colors.DANGER.b, int(255 * 0.65)) if mic_pressed else Colors.DANGER + + rl.draw_rectangle_rounded(self._mic_indicator_rect, 1, 10, bg_color) + rl.draw_texture_ex(self._mic_img, rl.Vector2(self._mic_indicator_rect.x + (self._mic_indicator_rect.width - self._mic_img.width) / 2, + self._mic_indicator_rect.y + (self._mic_indicator_rect.height - self._mic_img.height) / 2), 0.0, 1.0, Colors.WHITE) + + def _draw_network_indicator(self, rect: rl.Rectangle): + # Signal strength dots + x_start = rect.x + 58 + y_pos = rect.y + 196 + dot_size = 27 + dot_spacing = 37 + + for i in range(5): + color = Colors.WHITE if i < self._net_strength else Colors.GRAY + x = int(x_start + i * dot_spacing + dot_size // 2) + y = int(y_pos + dot_size // 2) + rl.draw_circle(x, y, dot_size // 2, color) + + # Network type text + text_y = rect.y + 247 + text_pos = rl.Vector2(rect.x + 58, text_y) + rl.draw_text_ex(self._font_regular, tr(self._net_type), text_pos, FONT_SIZE, 0, Colors.WHITE) + + def _draw_metrics(self, rect: rl.Rectangle): + if gui_app.sunnypilot_ui(): + metrics, start_y, spacing = SidebarSP._draw_metrics_w_sunnylink(self, rect, self._temp_status, self._panda_status, self._connect_status) + for idx, metric in enumerate(metrics): + self._draw_metric(rect, metric, start_y + idx * spacing) + + return + + metrics = [(self._temp_status, 338), (self._panda_status, 496), (self._connect_status, 654)] + + for metric, y_offset in metrics: + self._draw_metric(rect, metric, rect.y + y_offset) + + def _draw_metric(self, rect: rl.Rectangle, metric: MetricData, y: float): + metric_rect = rl.Rectangle(rect.x + METRIC_MARGIN, y, METRIC_WIDTH, METRIC_HEIGHT) + # Draw colored left edge (clipped rounded rectangle) + edge_rect = rl.Rectangle(metric_rect.x + 4, metric_rect.y + 4, 100, 118) + rl.begin_scissor_mode(int(metric_rect.x + 4), int(metric_rect.y), 18, int(metric_rect.height)) + rl.draw_rectangle_rounded(edge_rect, 0.3, 10, metric.color) + rl.end_scissor_mode() + + # Draw border + rl.draw_rectangle_rounded_lines_ex(metric_rect, 0.3, 10, 2, Colors.METRIC_BORDER) + + # Draw label and value + labels = [tr(metric.label), tr(metric.value)] + text_y = metric_rect.y + (metric_rect.height / 2 - len(labels) * FONT_SIZE * FONT_SCALE) + for text in labels: + text_size = measure_text_cached(self._font_bold, text, FONT_SIZE) + text_y += text_size.y + text_pos = rl.Vector2( + metric_rect.x + 22 + (metric_rect.width - 22 - text_size.x) / 2, + text_y + ) + rl.draw_text_ex(self._font_bold, text, text_pos, FONT_SIZE, 0, Colors.WHITE) diff --git a/openpilot/selfdrive/ui/lib/api_helpers.py b/openpilot/selfdrive/ui/lib/api_helpers.py new file mode 100644 index 0000000000..8ed1c22a63 --- /dev/null +++ b/openpilot/selfdrive/ui/lib/api_helpers.py @@ -0,0 +1,18 @@ +import time +from functools import lru_cache +from openpilot.common.api import Api +from openpilot.common.time_helpers import system_time_valid + +TOKEN_EXPIRY_HOURS = 2 + + +@lru_cache(maxsize=1) +def _get_token(dongle_id: str, t: int): + if not system_time_valid(): + raise RuntimeError("System time is not valid, cannot generate token") + + return Api(dongle_id).get_token(expiry_hours=TOKEN_EXPIRY_HOURS) + + +def get_token(dongle_id: str): + return _get_token(dongle_id, int(time.monotonic() / (TOKEN_EXPIRY_HOURS / 2 * 60 * 60))) diff --git a/openpilot/selfdrive/ui/lib/prime_state.py b/openpilot/selfdrive/ui/lib/prime_state.py new file mode 100644 index 0000000000..b57380ac57 --- /dev/null +++ b/openpilot/selfdrive/ui/lib/prime_state.py @@ -0,0 +1,109 @@ +from enum import IntEnum +import os +import requests +import threading +import time + +from openpilot.common.api import api_get +from openpilot.common.params import Params +from openpilot.common.realtime import drop_realtime +from openpilot.common.swaglog import cloudlog +from openpilot.system.athena.registration import UNREGISTERED_DONGLE_ID +from openpilot.selfdrive.ui.lib.api_helpers import get_token + + +class PrimeType(IntEnum): + UNKNOWN = -2 + UNPAIRED = -1 + NONE = 0 + MAGENTA = 1 + LITE = 2 + BLUE = 3 + MAGENTA_NEW = 4 + PURPLE = 5 + + +class PrimeState: + FETCH_INTERVAL = 5.0 # seconds between API calls + API_TIMEOUT = 10.0 # seconds for API requests + SLEEP_INTERVAL = 0.5 # seconds to sleep between checks in the worker thread + + def __init__(self): + self._params = Params() + self._lock = threading.Lock() + self._session = requests.Session() # reuse session to reduce SSL handshake overhead + self.prime_type: PrimeType = self._load_initial_state() + + self._running = False + self._thread = None + + def _load_initial_state(self) -> PrimeType: + prime_type_str = os.getenv("PRIME_TYPE") or self._params.get("PrimeType") + try: + if prime_type_str is not None: + return PrimeType(int(prime_type_str)) + except (ValueError, TypeError): + pass + return PrimeType.UNKNOWN + + def _fetch_prime_status(self) -> None: + dongle_id = self._params.get("DongleId") + if not dongle_id or dongle_id == UNREGISTERED_DONGLE_ID: + return + + try: + identity_token = get_token(dongle_id) + response = api_get(f"v1.1/devices/{dongle_id}", timeout=self.API_TIMEOUT, access_token=identity_token, session=self._session) + if response.status_code == 200: + data = response.json() + is_paired = data.get("is_paired", False) + prime_type = data.get("prime_type", 0) + self.set_type(PrimeType(prime_type) if is_paired else PrimeType.UNPAIRED) + except Exception as e: + cloudlog.error(f"Failed to fetch prime status: {e}") + + def set_type(self, prime_type: PrimeType) -> None: + with self._lock: + if prime_type != self.prime_type: + self.prime_type = prime_type + self._params.put("PrimeType", int(prime_type)) + cloudlog.info(f"Prime type updated to {prime_type}") + + def _worker_thread(self) -> None: + drop_realtime() + from openpilot.selfdrive.ui.ui_state import ui_state, device + while self._running: + if not ui_state.started and device._awake: + self._fetch_prime_status() + + for _ in range(int(self.FETCH_INTERVAL / self.SLEEP_INTERVAL)): + if not self._running: + break + time.sleep(self.SLEEP_INTERVAL) + + def start(self) -> None: + if self._thread and self._thread.is_alive(): + return + self._running = True + self._thread = threading.Thread(target=self._worker_thread, daemon=True) + self._thread.start() + + def stop(self) -> None: + self._running = False + if self._thread and self._thread.is_alive(): + self._thread.join(timeout=1.0) + + def get_type(self) -> PrimeType: + with self._lock: + return self.prime_type + + def is_prime(self) -> bool: + with self._lock: + return bool(self.prime_type > PrimeType.NONE) + + def is_paired(self) -> bool: + with self._lock: + return self.prime_type > PrimeType.UNPAIRED + + def __del__(self): + self.stop() diff --git a/selfdrive/ui/__init__.py b/openpilot/selfdrive/ui/mici/layouts/__init__.py similarity index 100% rename from selfdrive/ui/__init__.py rename to openpilot/selfdrive/ui/mici/layouts/__init__.py diff --git a/openpilot/selfdrive/ui/mici/layouts/home.py b/openpilot/selfdrive/ui/mici/layouts/home.py new file mode 100644 index 0000000000..4c4dfac520 --- /dev/null +++ b/openpilot/selfdrive/ui/mici/layouts/home.py @@ -0,0 +1,262 @@ +import datetime +import time + +from openpilot.cereal import log +import pyray as rl +from collections.abc import Callable +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.layouts import HBoxLayout +from openpilot.system.ui.widgets.icon_widget import IconWidget +from openpilot.system.ui.widgets.label import UnifiedLabel, gui_label +from openpilot.system.ui.lib.application import gui_app, FontWeight, MousePos +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.common.version import RELEASE_BRANCHES + +HEAD_BUTTON_FONT_SIZE = 40 +HOME_PADDING = 8 +ALERTS_ZONE_WIDTH = 180 + +NetworkType = log.DeviceState.NetworkType + +NETWORK_TYPES = { + NetworkType.none: "Offline", + NetworkType.wifi: "WiFi", + NetworkType.cell2G: "2G", + NetworkType.cell3G: "3G", + NetworkType.cell4G: "LTE", + NetworkType.cell5G: "5G", + NetworkType.ethernet: "Ethernet", +} + + +class AlertsPill(Widget): + ICON_OFFSET = 12 + COUNT_OFFSET = 40 + + def __init__(self): + super().__init__() + self.set_rect(rl.Rectangle(0, 0, 104, 52)) + + self._pill_bg_txt = gui_app.texture("icons_mici/alerts_pill.png", 104, 52) + self._icon_red = gui_app.texture("icons_mici/offroad_alerts/red_warning.png", 36, 36) + self._icon_orange = gui_app.texture("icons_mici/offroad_alerts/orange_warning.png", 36, 36) + self._icon_green = gui_app.texture("icons_mici/offroad_alerts/green_wheel.png", 36, 36) + self._alert_count_callback: Callable[[], int] | None = None + self._max_severity_callback: Callable[[], int | None] | None = None + + def set_alert_count_callback(self, callback: Callable[[], int] | None, + severity_callback: Callable[[], int | None] | None = None): + self._alert_count_callback = callback + self._max_severity_callback = severity_callback + + def _render(self, _): + alert_count = self._alert_count_callback() if self._alert_count_callback else 0 + if alert_count > 0: + pill_w, pill_h = self._pill_bg_txt.width, self._pill_bg_txt.height + rl.draw_texture_ex(self._pill_bg_txt, rl.Vector2(self.rect.x, self.rect.y), 0.0, 1.0, rl.WHITE) + + severity = self._max_severity_callback() if self._max_severity_callback else None + if severity == -1: + warning_txt = self._icon_green + elif severity is not None and severity > 0: + warning_txt = self._icon_red + else: + warning_txt = self._icon_orange + + warn_x = self.rect.x + self.ICON_OFFSET + warn_y = self.rect.y + (pill_h - warning_txt.height) / 2 + rl.draw_texture_ex(warning_txt, rl.Vector2(warn_x, warn_y), 0.0, 1.0, rl.WHITE) + + count_rect = rl.Rectangle(self.rect.x + self.COUNT_OFFSET, self.rect.y, pill_w - self.COUNT_OFFSET, pill_h) + gui_label(count_rect, str(alert_count), font_size=36, + alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER, + alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE) + + +class NetworkIcon(Widget): + def __init__(self): + super().__init__() + self.set_rect(rl.Rectangle(0, 0, 54, 44)) # max size of all icons + self._net_type = NetworkType.none + self._net_strength = 0 + + self._wifi_slash_txt = gui_app.texture("icons_mici/settings/network/wifi_strength_slash.png", 50, 44) + self._wifi_none_txt = gui_app.texture("icons_mici/settings/network/wifi_strength_none.png", 50, 37) + self._wifi_low_txt = gui_app.texture("icons_mici/settings/network/wifi_strength_low.png", 50, 37) + self._wifi_medium_txt = gui_app.texture("icons_mici/settings/network/wifi_strength_medium.png", 50, 37) + self._wifi_full_txt = gui_app.texture("icons_mici/settings/network/wifi_strength_full.png", 50, 37) + + self._cell_none_txt = gui_app.texture("icons_mici/settings/network/cell_strength_none.png", 54, 36) + self._cell_low_txt = gui_app.texture("icons_mici/settings/network/cell_strength_low.png", 54, 36) + self._cell_medium_txt = gui_app.texture("icons_mici/settings/network/cell_strength_medium.png", 54, 36) + self._cell_high_txt = gui_app.texture("icons_mici/settings/network/cell_strength_high.png", 54, 36) + self._cell_full_txt = gui_app.texture("icons_mici/settings/network/cell_strength_full.png", 54, 36) + + def _update_state(self): + device_state = ui_state.sm['deviceState'] + self._net_type = device_state.networkType + strength = device_state.networkStrength + self._net_strength = max(0, min(5, strength.raw + 1)) if strength.raw > 0 else 0 + + def _render(self, _): + if self._net_type == NetworkType.wifi: + # There is no 1 + draw_net_txt = {0: self._wifi_none_txt, + 2: self._wifi_low_txt, + 3: self._wifi_medium_txt, + 4: self._wifi_full_txt, + 5: self._wifi_full_txt}.get(self._net_strength, self._wifi_low_txt) + elif self._net_type in (NetworkType.cell2G, NetworkType.cell3G, NetworkType.cell4G, NetworkType.cell5G): + draw_net_txt = {0: self._cell_none_txt, + 2: self._cell_low_txt, + 3: self._cell_medium_txt, + 4: self._cell_high_txt, + 5: self._cell_full_txt}.get(self._net_strength, self._cell_none_txt) + else: + draw_net_txt = self._wifi_slash_txt + + draw_x = self._rect.x + (self._rect.width - draw_net_txt.width) / 2 + draw_y = self._rect.y + (self._rect.height - draw_net_txt.height) / 2 + + if draw_net_txt == self._wifi_slash_txt: + # Offset by difference in height between slashless and slash icons to make center align match + draw_y -= (self._wifi_slash_txt.height - self._wifi_none_txt.height) / 2 + + rl.draw_texture_ex(draw_net_txt, rl.Vector2(draw_x, draw_y), 0.0, 1.0, rl.Color(255, 255, 255, int(255 * 0.9))) + + +class MiciHomeLayout(Widget): + def __init__(self): + super().__init__() + self._on_settings_click: Callable | None = None + self._on_alerts_click: Callable | None = None + self._alert_count_callback: Callable[[], int] | None = None + + self._mouse_down_t: None | float = None + self._did_long_press = False + self._is_pressed_prev = False + + self._version_text = self._get_version_text() + + self._experimental_icon = IconWidget("icons_mici/experimental_mode.png", (48, 48)) + self._egpu_icon = IconWidget("icons_mici/egpu.png", (50, 37)) + self._egpu_icon_gray = IconWidget("icons_mici/egpu_gray.png", (50, 37)) + self._mic_icon = IconWidget("icons_mici/microphone.png", (32, 46)) + self._body_icon = IconWidget("icons_mici/body.png", (54, 37)) + + self._alerts_pill = AlertsPill() + + self._status_bar_layout = HBoxLayout([ + IconWidget("icons_mici/settings.png", (48, 48), opacity=0.9), + NetworkIcon(), + self._experimental_icon, + self._egpu_icon, + self._egpu_icon_gray, + self._body_icon, + self._mic_icon, + ], spacing=18) + + self._openpilot_label = UnifiedLabel("sunnypilot", font_size=96, font_weight=FontWeight.DISPLAY, max_width=480, wrap_text=False) + self._version_label = UnifiedLabel("", font_size=36, font_weight=FontWeight.ROMAN, max_width=480, wrap_text=False) + self._large_version_label = UnifiedLabel("", font_size=64, text_color=rl.GRAY, font_weight=FontWeight.ROMAN, max_width=480, wrap_text=False) + self._date_label = UnifiedLabel("", font_size=36, text_color=rl.GRAY, font_weight=FontWeight.ROMAN, max_width=480, wrap_text=False) + self._branch_label = UnifiedLabel("", font_size=36, text_color=rl.GRAY, font_weight=FontWeight.ROMAN, scroll=True) + self._version_commit_label = UnifiedLabel("", font_size=36, text_color=rl.GRAY, font_weight=FontWeight.ROMAN, max_width=480, wrap_text=False) + + def _update_state(self): + if self.is_pressed and not self._is_pressed_prev: + self._mouse_down_t = time.monotonic() + elif not self.is_pressed and self._is_pressed_prev: + self._mouse_down_t = None + self._did_long_press = False + self._is_pressed_prev = self.is_pressed + + if self._mouse_down_t is not None: + if time.monotonic() - self._mouse_down_t > 0.5: + # long gating for experimental mode - only allow toggle if longitudinal control is available + if ui_state.has_longitudinal_control: + ui_state.experimental_mode = not ui_state.experimental_mode + ui_state.params.put("ExperimentalMode", ui_state.experimental_mode, block=True) + self._mouse_down_t = None + self._did_long_press = True + + def set_callbacks(self, on_settings: Callable | None = None, on_alerts: Callable | None = None, + alert_count_callback: Callable[[], int] | None = None, + max_severity_callback: Callable[[], int | None] | None = None): + self._on_settings_click = on_settings + self._on_alerts_click = on_alerts + self._alert_count_callback = alert_count_callback + self._alerts_pill.set_alert_count_callback(alert_count_callback, max_severity_callback) + + def _handle_mouse_release(self, mouse_pos: MousePos): + if not self._did_long_press: + relative_x = mouse_pos.x - self.rect.x + has_alerts = self._alert_count_callback and self._alert_count_callback() > 0 + if has_alerts and relative_x > self.rect.width - ALERTS_ZONE_WIDTH: + if self._on_alerts_click: + self._on_alerts_click() + elif self._on_settings_click: + self._on_settings_click() + self._did_long_press = False + + def _get_version_text(self) -> tuple[str, str, str, str] | None: + version = ui_state.params.get("Version") + branch = ui_state.params.get("GitBranch") + commit = ui_state.params.get("GitCommit") + + if not all((version, branch, commit)): + return None + + commit_date_raw = ui_state.params.get("GitCommitDate") + try: + # GitCommitDate format from get_commit_date(): '%ct %ci' e.g. "'1708012345 2024-02-15 ...'" + unix_ts = int(commit_date_raw.strip("'").split()[0]) + date_str = datetime.datetime.fromtimestamp(unix_ts).strftime("%b %d") + except (ValueError, IndexError, TypeError, AttributeError): + date_str = "" + + return version, branch, commit[:7], date_str + + def _render(self, _): + # TODO: why is there extra space here to get it to be flush? + text_pos = rl.Vector2(self.rect.x - 2 + HOME_PADDING, self.rect.y - 16) + self._openpilot_label.set_position(text_pos.x, text_pos.y) + self._openpilot_label.render() + + if self._version_text is not None: + # release branch + release_branch = self._version_text[1] in RELEASE_BRANCHES + version_pos = rl.Rectangle(text_pos.x, text_pos.y + self._openpilot_label.font_size + 16, 100, 44) + self._version_label.set_text(self._version_text[0]) + self._version_label.set_position(version_pos.x, version_pos.y) + self._version_label.render() + + self._date_label.set_text(" " + self._version_text[3]) + self._date_label.set_position(version_pos.x + self._version_label.text_width + 10, version_pos.y) + self._date_label.render() + + self._branch_label.set_max_width(gui_app.width - self._version_label.text_width - self._date_label.text_width - 32) + self._branch_label.set_text(" " + ("release" if release_branch else self._version_text[1])) + self._branch_label.set_position(version_pos.x + self._version_label.text_width + self._date_label.text_width + 20, version_pos.y) + self._branch_label.render() + + if not release_branch: + # 2nd line + self._version_commit_label.set_text(self._version_text[2]) + self._version_commit_label.set_position(version_pos.x, version_pos.y + self._date_label.font_size + 7) + self._version_commit_label.render() + + # ***** Center-aligned bottom section icons ***** + self._experimental_icon.set_visible(ui_state.experimental_mode) + self._egpu_icon.set_visible(ui_state.usbgpu and ui_state.usbgpu_compiled) + self._egpu_icon_gray.set_visible(ui_state.usbgpu and not ui_state.usbgpu_compiled) + self._mic_icon.set_visible(ui_state.recording_audio) + self._body_icon.set_visible(bool(ui_state.is_body)) + + footer_rect = rl.Rectangle(self.rect.x + HOME_PADDING, self.rect.y + self.rect.height - 48, self.rect.width - HOME_PADDING, 48) + self._status_bar_layout.render(footer_rect) + + # TODO: add alignment to hboxlayout and add to there + self._alerts_pill.set_position(self.rect.x + self.rect.width - self._alerts_pill.rect.width - HOME_PADDING, + self.rect.y + self.rect.height - self._alerts_pill.rect.height) + self._alerts_pill.render() diff --git a/openpilot/selfdrive/ui/mici/layouts/main.py b/openpilot/selfdrive/ui/mici/layouts/main.py new file mode 100644 index 0000000000..6356a2bc9d --- /dev/null +++ b/openpilot/selfdrive/ui/mici/layouts/main.py @@ -0,0 +1,151 @@ +import pyray as rl +import openpilot.cereal.messaging as messaging +from openpilot.selfdrive.ui.mici.layouts.home import MiciHomeLayout +from openpilot.selfdrive.ui.mici.layouts.settings.settings import SettingsLayout +from openpilot.selfdrive.ui.mici.layouts.offroad_alerts import MiciOffroadAlerts +from openpilot.selfdrive.ui.mici.onroad.augmented_road_view import AugmentedRoadView +from openpilot.selfdrive.ui.ui_state import device, ui_state +from openpilot.selfdrive.ui.mici.layouts.onboarding import OnboardingWindow +from openpilot.selfdrive.ui.body.layouts.onroad import BodyLayout +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.scroller import Scroller +from openpilot.system.ui.lib.application import gui_app + +if gui_app.sunnypilot_ui(): + from openpilot.selfdrive.ui.sunnypilot.mici.layouts.settings import SettingsLayoutSP as SettingsLayout + +ONROAD_DELAY = 2.5 # seconds + + +class MiciMainLayout(Scroller): + def __init__(self): + super().__init__(snap_items=True, spacing=0, pad=0, scroll_indicator=False, edge_shadows=False) + + self._pm = messaging.PubMaster(['bookmarkButton']) + + self._prev_onroad = False + self._prev_standstill = False + self._onroad_time_delay: float | None = None + self._setup = False + + # Initialize widgets + self._home_layout = MiciHomeLayout() + self._alerts_layout = MiciOffroadAlerts() + self._settings_layout = SettingsLayout() + self._car_onroad_layout = AugmentedRoadView(bookmark_callback=self._on_bookmark_clicked) + self._body_onroad_layout = BodyLayout() + + # Initialize widget rects + for widget in (self._home_layout, self._alerts_layout, self._settings_layout, + self._car_onroad_layout, self._body_onroad_layout): + # TODO: set parent rect and use it if never passed rect from render (like in Scroller) + widget.set_rect(rl.Rectangle(0, 0, gui_app.width, gui_app.height)) + + self._scroller.add_widgets([ + self._alerts_layout, + self._home_layout, + self._car_onroad_layout, + self._body_onroad_layout, + ]) + self._scroller.set_reset_scroll_at_show(False) + + # Disable scrolling when onroad is interacting with bookmark + self._scroller.set_scrolling_enabled(lambda: not self._car_onroad_layout.is_swiping_left()) + + # Set callbacks + self._setup_callbacks() + + gui_app.add_nav_stack_tick(self._handle_transitions) + gui_app.push_widget(self) + + # Start onboarding if terms or training not completed, make sure to push after self + self._onboarding_window = OnboardingWindow(lambda: gui_app.pop_widgets_to(self)) + if not self._onboarding_window.completed: + gui_app.push_widget(self._onboarding_window) + + @property + def _onroad_layout(self) -> Widget: + # For scroll_to + return self._body_onroad_layout if ui_state.is_body else self._car_onroad_layout + + def _setup_callbacks(self): + self._home_layout.set_callbacks( + on_settings=lambda: gui_app.push_widget(self._settings_layout), + on_alerts=lambda: self._scroll_to(self._alerts_layout), + alert_count_callback=self._alerts_layout.active_alerts, + max_severity_callback=self._alerts_layout.max_severity, + ) + for layout in (self._car_onroad_layout, self._body_onroad_layout): + layout.set_click_callback(lambda: self._scroll_to(self._home_layout)) + + device.add_interactive_timeout_callback(self._on_interactive_timeout) + ui_state.add_on_body_changed_callbacks(self._on_body_changed) + + def _scroll_to(self, layout: Widget): + layout_x = int(layout.rect.x) + self._scroller.scroll_to(layout_x, smooth=True) + + def _update_state(self): + super()._update_state() + # TODO: Hack to run alert updates while not in view. Add a nav stack tick? + self._alerts_layout._update_state() + + def _render(self, _): + if not self._setup: + if self._alerts_layout.active_alerts() > 0: + self._scroller.scroll_to(self._alerts_layout.rect.x) + else: + self._scroller.scroll_to(self._rect.width) + self._setup = True + + # Render + super()._render(self._rect) + + def _handle_transitions(self): + # Don't pop if onboarding + if gui_app.widget_in_stack(self._onboarding_window): + return + + if ui_state.started != self._prev_onroad: + self._prev_onroad = ui_state.started + + # onroad: after delay, pop nav stack and scroll to onroad + # offroad: immediately scroll to home, but don't pop nav stack (can stay in settings) + if ui_state.started: + self._onroad_time_delay = rl.get_time() + else: + self._scroll_to(self._home_layout) + + # FIXME: these two pops can interrupt user interacting in the settings + if self._onroad_time_delay is not None and rl.get_time() - self._onroad_time_delay >= ONROAD_DELAY: + gui_app.pop_widgets_to(self, lambda: self._scroll_to(self._onroad_layout)) + self._onroad_time_delay = None + + # When car leaves standstill, pop nav stack and scroll to onroad + CS = ui_state.sm["carState"] + if not CS.standstill and self._prev_standstill: + gui_app.pop_widgets_to(self, lambda: self._scroll_to(self._onroad_layout)) + self._prev_standstill = CS.standstill + + def _on_interactive_timeout(self): + # Don't pop if onboarding + if gui_app.widget_in_stack(self._onboarding_window): + return + + if ui_state.started: + # Don't pop if at standstill + if not ui_state.sm["carState"].standstill: + gui_app.pop_widgets_to(self, lambda: self._scroll_to(self._onroad_layout)) + else: + # Screen turns off on timeout offroad, so pop immediately without animation + gui_app.pop_widgets_to(self, instant=True) + self._scroll_to(self._home_layout) + + def _on_bookmark_clicked(self): + user_bookmark = messaging.new_message('bookmarkButton') + user_bookmark.valid = True + self._pm.send('bookmarkButton', user_bookmark) + + def _on_body_changed(self): + self._car_onroad_layout.set_visible(not ui_state.is_body) + self._body_onroad_layout.set_visible(bool(ui_state.is_body)) diff --git a/openpilot/selfdrive/ui/mici/layouts/offroad_alerts.py b/openpilot/selfdrive/ui/mici/layouts/offroad_alerts.py new file mode 100644 index 0000000000..879ac76df5 --- /dev/null +++ b/openpilot/selfdrive/ui/mici/layouts/offroad_alerts.py @@ -0,0 +1,324 @@ +import pyray as rl +import re +import threading +import time +from dataclasses import dataclass +from enum import IntEnum +from openpilot.common.params import Params +from openpilot.common.realtime import drop_realtime +from openpilot.selfdrive.selfdrived.alertmanager import OFFROAD_ALERTS +from openpilot.common.hardware import HARDWARE +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.label import UnifiedLabel +from openpilot.system.ui.widgets.scroller import Scroller +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.lib.multilang import tr + +REFRESH_INTERVAL = 5.0 # seconds + + +class AlertSize(IntEnum): + SMALL = 0 + MEDIUM = 1 + BIG = 2 + + +@dataclass +class AlertData: + key: str + text: str + severity: int + visible: bool = False + + +class AlertItem(Widget): + # TODO: click should always go somewhere: home or specific settings pane + """Individual alert item widget with background image and text.""" + ALERT_WIDTH = 520 + ALERT_HEIGHT_SMALL = 212 + ALERT_HEIGHT_MED = 240 + ALERT_HEIGHT_BIG = 324 + ALERT_PADDING = 28 + ICON_SIZE = 64 + ICON_MARGIN = 12 + TEXT_COLOR = rl.Color(255, 255, 255, int(255 * 0.9)) + TITLE_BODY_SPACING = 24 + + def __init__(self, alert_data: AlertData): + super().__init__() + self.alert_data = alert_data + + # Load background textures + self._bg_small = gui_app.texture("icons_mici/offroad_alerts/small_alert.png", self.ALERT_WIDTH, self.ALERT_HEIGHT_SMALL) + self._bg_small_pressed = gui_app.texture("icons_mici/offroad_alerts/small_alert_pressed.png", self.ALERT_WIDTH, self.ALERT_HEIGHT_SMALL) + self._bg_medium = gui_app.texture("icons_mici/offroad_alerts/medium_alert.png", self.ALERT_WIDTH, self.ALERT_HEIGHT_MED) + self._bg_medium_pressed = gui_app.texture("icons_mici/offroad_alerts/medium_alert_pressed.png", self.ALERT_WIDTH, self.ALERT_HEIGHT_MED) + self._bg_big = gui_app.texture("icons_mici/offroad_alerts/big_alert.png", self.ALERT_WIDTH, self.ALERT_HEIGHT_BIG) + self._bg_big_pressed = gui_app.texture("icons_mici/offroad_alerts/big_alert_pressed.png", self.ALERT_WIDTH, self.ALERT_HEIGHT_BIG) + + # Load warning icons + self._icon_orange = gui_app.texture("icons_mici/offroad_alerts/orange_warning.png", self.ICON_SIZE, self.ICON_SIZE) + self._icon_red = gui_app.texture("icons_mici/offroad_alerts/red_warning.png", self.ICON_SIZE, self.ICON_SIZE) + self._icon_green = gui_app.texture("icons_mici/offroad_alerts/green_wheel.png", self.ICON_SIZE, self.ICON_SIZE) + + self._title_label = UnifiedLabel(text="", font_size=32, font_weight=FontWeight.SEMI_BOLD, text_color=self.TEXT_COLOR, + alignment=rl.GuiTextAlignment.TEXT_ALIGN_LEFT, + alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_TOP, line_height=0.95) + + self._body_label = UnifiedLabel(text="", font_size=28, font_weight=FontWeight.ROMAN, text_color=self.TEXT_COLOR, + alignment=rl.GuiTextAlignment.TEXT_ALIGN_LEFT, + alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_BOTTOM, line_height=0.95) + + self._title_text = "" + self._body_text = "" + self._alert_size = AlertSize.SMALL + + self._update_content() + + def _split_text(self, text: str) -> tuple[str, str]: + """Split text into title (first sentence) and body (remaining text).""" + # Find the end of the first sentence (period, exclamation, or question mark followed by space or end) + match = re.search(r'[.!?](?:\s+|$)', text) + if match: + # Found a sentence boundary - split at the end of the sentence + title = text[:match.start()].strip() + body = text[match.end():].strip() + return title, body + else: + # No sentence boundary found, return full text as title + return "", text + + def _update_content(self): + """Update text and calculate height.""" + if not self.alert_data.visible or not self.alert_data.text: + self.set_visible(False) + return + + self.set_visible(True) + + # Split text into title and body + self._title_text, self._body_text = self._split_text(self.alert_data.text) + + # Calculate text width (alert width minus padding and icon space on right) + title_width = self.ALERT_WIDTH - (self.ALERT_PADDING * 2) - self.ICON_SIZE - self.ICON_MARGIN + body_width = self.ALERT_WIDTH - (self.ALERT_PADDING * 2) + + # Update labels + self._title_label.set_text(self._title_text) + self._body_label.set_text(self._body_text) + + # Calculate content height + title_height = self._title_label.get_content_height(title_width) if self._title_text else 0 + body_height = self._body_label.get_content_height(body_width) if self._body_text else 0 + spacing = self.TITLE_BODY_SPACING if (self._title_text and self._body_text) else 0 + total_text_height = title_height + spacing + body_height + + # Determine which background size to use based on content height + min_height_with_padding = total_text_height + (self.ALERT_PADDING * 2) + if min_height_with_padding > self.ALERT_HEIGHT_MED: + self._alert_size = AlertSize.BIG + height = self.ALERT_HEIGHT_BIG + elif min_height_with_padding > self.ALERT_HEIGHT_SMALL: + self._alert_size = AlertSize.MEDIUM + height = self.ALERT_HEIGHT_MED + else: + self._alert_size = AlertSize.SMALL + height = self.ALERT_HEIGHT_SMALL + + # Set rect size + self.set_rect(rl.Rectangle(0, 0, self.ALERT_WIDTH, height)) + + def update_alert_data(self, alert_data: AlertData): + """Update alert data and refresh display.""" + self.alert_data = alert_data + self._update_content() + + def _render(self, _): + if not self.alert_data.visible or not self.alert_data.text: + return + + # Choose background based on size + if self._alert_size == AlertSize.BIG: + bg_texture = self._bg_big_pressed if self.is_pressed else self._bg_big + elif self._alert_size == AlertSize.MEDIUM: + bg_texture = self._bg_medium_pressed if self.is_pressed else self._bg_medium + else: # AlertSize.SMALL + bg_texture = self._bg_small_pressed if self.is_pressed else self._bg_small + + # Draw background + rl.draw_texture_ex(bg_texture, rl.Vector2(self._rect.x, self._rect.y), 0.0, 1.0, rl.WHITE) + + # Calculate text area (left side, avoiding icon on right) + title_width = self.ALERT_WIDTH - (self.ALERT_PADDING * 2) - self.ICON_SIZE - self.ICON_MARGIN + body_width = self.ALERT_WIDTH - (self.ALERT_PADDING * 2) + text_x = self._rect.x + self.ALERT_PADDING + text_y = self._rect.y + self.ALERT_PADDING + + # Draw title label + if self._title_text: + title_rect = rl.Rectangle( + text_x, + text_y, + title_width, + self._title_label.get_content_height(title_width), + ) + self._title_label.render(title_rect) + text_y += title_rect.height + self.TITLE_BODY_SPACING + + # Draw body label + if self._body_text: + body_rect = rl.Rectangle( + text_x, + text_y, + body_width, + self._rect.height - text_y + self._rect.y - self.ALERT_PADDING, + ) + self._body_label.render(body_rect) + + # Draw warning icon on the right side + # Use green icon for update alerts (severity = -1), red for high severity, orange for low severity + if self.alert_data.severity == -1: + icon_texture = self._icon_green + elif self.alert_data.severity > 0: + icon_texture = self._icon_red + else: + icon_texture = self._icon_orange + icon_x = self._rect.x + self.ALERT_WIDTH - self.ALERT_PADDING - self.ICON_SIZE + icon_y = self._rect.y + self.ALERT_PADDING + rl.draw_texture_ex(icon_texture, rl.Vector2(icon_x, icon_y), 0.0, 1.0, rl.WHITE) + + +class MiciOffroadAlerts(Scroller): + """Offroad alerts layout with vertical scrolling.""" + + def __init__(self): + # Create vertical scroller + super().__init__(horizontal=False, spacing=12, pad=0) + self.params = Params() + self.sorted_alerts: list[AlertData] = [] + self.alert_items: list[AlertItem] = [] + + # Create empty state label + self._empty_label = UnifiedLabel(tr("no alerts"), 65, FontWeight.DISPLAY, rl.WHITE, + alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER, + alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE) + + # Build initial alert list + self._build_alerts() + + # Start param thread + self._pending_params: dict | None = None + self._params_thread = threading.Thread(target=self._params_worker, daemon=True) + self._params_thread.start() + + def active_alerts(self) -> int: + return sum(alert.visible for alert in self.sorted_alerts) + + def max_severity(self) -> int | None: + return max((alert.severity for alert in self.sorted_alerts if alert.visible), default=None) + + def scrolling(self): + return self._scroller.scroll_panel.is_touch_valid() + + def _build_alerts(self): + """Build sorted list of alerts from OFFROAD_ALERTS.""" + self.sorted_alerts = [] + + # Add UpdateAvailable alert at the top (severity = -1 to indicate special handling) + update_alert_data = AlertData(key="UpdateAvailable", text="", severity=-1) + self.sorted_alerts.append(update_alert_data) + update_alert_item = AlertItem(update_alert_data) + update_alert_item.set_click_callback(lambda: HARDWARE.reboot()) + self.alert_items.append(update_alert_item) + self._scroller.add_widget(update_alert_item) + + # Add regular alerts sorted by severity + for key, config in sorted(OFFROAD_ALERTS.items(), key=lambda x: x[1].get("severity", 0), reverse=True): + severity = config.get("severity", 0) + alert_data = AlertData(key=key, text="", severity=severity) + self.sorted_alerts.append(alert_data) + + # Create alert item widget + alert_item = AlertItem(alert_data) + self.alert_items.append(alert_item) + self._scroller.add_widget(alert_item) + + def _params_worker(self): + drop_realtime() + while True: + self._pending_params = ({"UpdaterNewDescription": self.params.get("UpdaterNewDescription")} | + {alert_data.key: self.params.get(alert_data.key) for alert_data in self.sorted_alerts}) + time.sleep(REFRESH_INTERVAL) + + def _refresh(self, pending_params: dict) -> int: + """Refresh alerts from params and return active count.""" + active_count = 0 + + # Handle UpdateAvailable alert specially + update_available = pending_params["UpdateAvailable"] + update_alert_data = next((alert_data for alert_data in self.sorted_alerts if alert_data.key == "UpdateAvailable"), None) + + if update_alert_data: + if update_available: + version_string = "" + + # Get new version description and parse version and date + new_desc = pending_params["UpdaterNewDescription"] or "" + if new_desc: + # format: "version / branch / commit / date" + parts = new_desc.split(" / ") + if len(parts) > 3: + version, date = parts[0], parts[3] + version_string = f"\nsunnypilot {version}, {date}\n" + + update_alert_data.text = f"Update available {version_string}. Click to update. Read the release notes at blog.comma.ai." + update_alert_data.visible = True + active_count += 1 + else: + update_alert_data.text = "" + update_alert_data.visible = False + + # Handle regular alerts + for alert_data in self.sorted_alerts: + if alert_data.key == "UpdateAvailable": + continue # Skip, already handled above + + text = "" + alert_json = pending_params[alert_data.key] + + if alert_json: + text = alert_json.get("text", "").replace("%1", alert_json.get("extra", "")) + + if text and not alert_data.visible: + # Bump newly visible alerts to the top, severity sort keeps it at the top of its category + widget = next(w for w in self._scroller.items if w.alert_data is alert_data) + self._scroller.items.remove(widget) + self._scroller.items.insert(0, widget) + alert_data.text = text + alert_data.visible = bool(text) + + if alert_data.visible: + active_count += 1 + + # Update alert items (they reference the same alert_data objects) + for alert_item in self.alert_items: + alert_item.update_alert_data(alert_item.alert_data) + + self._scroller.items.sort(key=lambda w: -w.alert_data.severity) + + return active_count + + def _update_state(self): + """Periodically refresh alerts.""" + # Refresh alerts when thread updates params + pending_params = self._pending_params + if pending_params is not None: + self._refresh(pending_params) + self._pending_params = None + + def _render(self, rect: rl.Rectangle): + """Render the alerts scroller or empty state.""" + if self.active_alerts() == 0: + self._empty_label.render(rect) + else: + self._scroller.render(rect) diff --git a/openpilot/selfdrive/ui/mici/layouts/onboarding.py b/openpilot/selfdrive/ui/mici/layouts/onboarding.py new file mode 100644 index 0000000000..3c5ad27a17 --- /dev/null +++ b/openpilot/selfdrive/ui/mici/layouts/onboarding.py @@ -0,0 +1,437 @@ +import math +import numpy as np +import qrcode +import pyray as rl +from collections.abc import Callable +from openpilot.common.filter_simple import FirstOrderFilter +from openpilot.system.ui.lib.application import FontWeight, gui_app +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.button import SmallCircleIconButton +from openpilot.system.ui.widgets.scroller import NavScroller, Scroller +from openpilot.system.ui.widgets.nav_widget import NavWidget +from openpilot.system.ui.mici_setup import GreyBigButton, BigPillButton +from openpilot.system.ui.widgets.label import gui_label +from openpilot.system.ui.lib.multilang import tr +from openpilot.common.version import terms_version, training_version, terms_version_sp +from openpilot.common.version import sunnylink_consent_version, sunnylink_consent_declined +from openpilot.selfdrive.ui.ui_state import ui_state, device +from openpilot.selfdrive.ui.mici.widgets.dialog import BigConfirmationCircleButton +from openpilot.selfdrive.ui.mici.onroad.driver_state import DriverStateRenderer +from openpilot.selfdrive.ui.mici.onroad.driver_camera_dialog import BaseDriverCameraDialog +from openpilot.selfdrive.ui.sunnypilot.mici.layouts.onboarding import SunnylinkConsentPage + + +class DriverCameraSetupDialog(BaseDriverCameraDialog): + def __init__(self): + super().__init__() + self.driver_state_renderer = DriverStateRenderer(inset=True) + self.driver_state_renderer.set_rect(rl.Rectangle(0, 0, 120, 120)) + self.driver_state_renderer.load_icons() + self.driver_state_renderer.set_force_active(True) + + def _render(self, rect): + rl.begin_scissor_mode(int(rect.x), int(rect.y), int(rect.width), int(rect.height)) + self._camera_view._render(rect) + + if not self._camera_view.frame: + gui_label(rect, tr("camera starting"), font_size=64, font_weight=FontWeight.BOLD, + alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER) + rl.end_scissor_mode() + return + + # Position dmoji on opposite side from driver + is_rhd = self.driver_state_renderer.is_rhd + self.driver_state_renderer.set_position( + rect.x + 8 if is_rhd else rect.x + rect.width - self.driver_state_renderer.rect.width - 8, + rect.y + 8, + ) + self.driver_state_renderer.render() + + self._draw_face_detection(rect) + + rl.end_scissor_mode() + + +class TrainingGuidePreDMTutorial(NavScroller): + def __init__(self, continue_callback: Callable[[], None]): + super().__init__() + + continue_button = BigPillButton("next") + continue_button.set_click_callback(continue_callback) + + self._scroller.add_widgets([ + GreyBigButton("driver monitoring\ncheck", "scroll to continue", + gui_app.texture("icons_mici/setup/green_dm.png", 64, 64)), + GreyBigButton("", "Next, we'll check if comma four can detect the driver properly."), + GreyBigButton("", "sunnypilot uses the cabin camera to check if the driver is distracted."), + GreyBigButton("", "If it does not have a clear view of the driver, unplug and remount before continuing."), + continue_button, + ]) + + def show_event(self): + super().show_event() + # Get driver monitoring model ready for next step + ui_state.params.put_bool("IsDriverViewEnabled", True) + + +class DMBadFaceDetected(NavScroller): + def __init__(self): + super().__init__() + + back_button = BigPillButton("back") + back_button.set_click_callback(self.dismiss) + + self._scroller.add_widgets([ + GreyBigButton("looking for driver", "make sure comma\nfour can see your face", + gui_app.texture("icons_mici/setup/orange_dm.png", 64, 64)), + GreyBigButton("", "Remount if your face is blocked, or driver monitoring has difficulty tracking your face."), + back_button, + ]) + + +class TrainingGuideDMTutorial(NavWidget): + PROGRESS_DURATION = 4 + LOOKING_THRESHOLD_DEG = 30.0 + + def __init__(self, continue_callback: Callable[[], None]): + super().__init__() + + self._back_button = SmallCircleIconButton(gui_app.texture("icons_mici/setup/driver_monitoring/dm_question.png", 28, 48)) + self._back_button.set_click_callback(lambda: gui_app.push_widget(self._bad_face_page)) + self._back_button.set_touch_valid_callback(lambda: self.enabled and not self.is_dismissing) # for nav stack + self._good_button = SmallCircleIconButton(gui_app.texture("icons_mici/setup/driver_monitoring/dm_check.png", 42, 42)) + self._good_button.set_touch_valid_callback(lambda: self.enabled and not self.is_dismissing) # for nav stack + + self._good_button.set_click_callback(continue_callback) + self._good_button.set_enabled(False) + + self._progress = FirstOrderFilter(0.0, 0.5, 1 / gui_app.target_fps) + self._dialog = DriverCameraSetupDialog() + self._bad_face_page = DMBadFaceDetected() + + # Disable driver monitoring model when device times out for inactivity + def inactivity_callback(): + ui_state.params.put_bool("IsDriverViewEnabled", False) + + device.add_interactive_timeout_callback(inactivity_callback) + + def show_event(self): + super().show_event() + self._dialog.show_event() + self._progress.x = 0.0 + + def _update_state(self): + super()._update_state() + if device.awake and not ui_state.params.get_bool("IsDriverViewEnabled"): + ui_state.params.put_bool("IsDriverViewEnabled", True) + + sm = ui_state.sm + if sm.recv_frame.get("driverMonitoringState", 0) == 0: + return + + dm_state = sm["driverMonitoringState"] + driver_data = self._dialog.driver_state_renderer.get_driver_data() + + if len(driver_data.faceOrientation) == 3: + pitch, yaw, _ = driver_data.faceOrientation + looking_center = abs(math.degrees(pitch)) < self.LOOKING_THRESHOLD_DEG and abs(math.degrees(yaw)) < self.LOOKING_THRESHOLD_DEG + else: + looking_center = False + + # stay at 100% once reached + in_bad_face = gui_app.get_active_widget() == self._bad_face_page + if ((dm_state.visionPolicyState.faceDetected and looking_center) or self._progress.x > 0.99) and not in_bad_face: + slow = self._progress.x < 0.25 + duration = self.PROGRESS_DURATION * 2 if slow else self.PROGRESS_DURATION + self._progress.x += 1.0 / (duration * gui_app.target_fps) + self._progress.x = min(1.0, self._progress.x) + else: + self._progress.update(0.0) + + self._good_button.set_enabled(self._progress.x >= 0.999) + + def _render(self, _): + self._dialog.render(self._rect) + + gradient_y = int(self._rect.y + self._rect.height - 80) + gradient_h = int(self._rect.y) + int(self._rect.height) - gradient_y + rl.draw_rectangle_gradient_v(int(self._rect.x), gradient_y, + int(self._rect.width), gradient_h, rl.BLANK, rl.BLACK) + + # draw white ring around dm icon to indicate progress + ring_thickness = 8 + + # DM icon is 120x120, positioned on opposite side from driver + dm_size = 120 + is_rhd = self._dialog.driver_state_renderer._is_rhd + dm_center_x = (self._rect.x + dm_size / 2 + 8) if is_rhd else (self._rect.x + self._rect.width - dm_size / 2 - 8) + dm_center_y = self._rect.y + dm_size / 2 + 8 + icon_edge_radius = dm_size / 2 + outer_radius = icon_edge_radius + 1 # 2px outward from icon edge + inner_radius = outer_radius - ring_thickness # Inset by ring_thickness + start_angle = 90.0 # Start from bottom + end_angle = start_angle + self._progress.x * 360.0 # Clockwise + + # Fade in alpha + current_angle = end_angle - start_angle + alpha = int(np.interp(current_angle, [0.0, 45.0], [0, 255])) + + # White to green + color_t = np.clip(np.interp(current_angle, [45.0, 360.0], [0.0, 1.0]), 0.0, 1.0) + r = int(np.interp(color_t, [0.0, 1.0], [255, 0])) + g = int(np.interp(color_t, [0.0, 1.0], [255, 255])) + b = int(np.interp(color_t, [0.0, 1.0], [255, 64])) + ring_color = rl.Color(r, g, b, alpha) + + rl.draw_ring( + rl.Vector2(dm_center_x, dm_center_y), + inner_radius, + outer_radius, + start_angle, + end_angle, + 36, + ring_color, + ) + + if self._dialog._camera_view.frame: + self._back_button.render(rl.Rectangle( + self._rect.x + 8, + self._rect.y + self._rect.height - self._back_button.rect.height, + self._back_button.rect.width, + self._back_button.rect.height, + )) + + self._good_button.render(rl.Rectangle( + self._rect.x + self._rect.width - self._good_button.rect.width - 8, + self._rect.y + self._rect.height - self._good_button.rect.height, + self._good_button.rect.width, + self._good_button.rect.height, + )) + + # rounded border + rl.begin_scissor_mode(int(self._rect.x), int(self._rect.y), int(self._rect.width), int(self._rect.height)) + rl.draw_rectangle_rounded_lines_ex(self._rect, 0.2 * 1.02, 10, 50, rl.BLACK) + rl.end_scissor_mode() + + +class TrainingGuideRecordFront(NavScroller): + def __init__(self, continue_callback: Callable[[], None]): + super().__init__() + + def on_accept(): + ui_state.params.put_bool("RecordFront", True) + continue_callback() + + def on_decline(): + ui_state.params.put_bool("RecordFront", False) + continue_callback() + + self._accept_button = BigConfirmationCircleButton("allow data uploading", gui_app.texture("icons_mici/setup/driver_monitoring/dm_check.png", 64, 64), + on_accept, exit_on_confirm=False) + + self._decline_button = BigConfirmationCircleButton("no, don't upload", gui_app.texture("icons_mici/setup/cancel.png", 64, 64), on_decline, + exit_on_confirm=False) + + self._scroller.add_widgets([ + GreyBigButton("driver camera data", "do you want to share video data for training?", + gui_app.texture("icons_mici/setup/green_dm.png", 64, 64)), + GreyBigButton("", "Sharing your data with comma helps improve openpilot and sunnypilot for everyone."), + self._accept_button, + self._decline_button, + ]) + + +class TrainingGuideAttentionNotice(Scroller): + def __init__(self, continue_callback: Callable[[], None]): + super().__init__() + + continue_button = BigPillButton("next") + continue_button.set_click_callback(continue_callback) + + self._scroller.add_widgets([ + GreyBigButton("what is sunnypilot?", "scroll to continue", + gui_app.texture("icons_mici/setup/green_info.png", 64, 64)), + GreyBigButton("", "1. sunnypilot is a driver assistance system."), + GreyBigButton("", "2. You must pay attention at all times."), + GreyBigButton("", "3. You must be ready to take over at any time."), + GreyBigButton("", "4. You are fully responsible for driving the car."), + continue_button, + ]) + + +class TrainingGuide(NavWidget): + def __init__(self, completed_callback: Callable[[], None]): + super().__init__() + + self._steps = [ + TrainingGuideAttentionNotice(continue_callback=lambda: gui_app.push_widget(self._steps[1])), + TrainingGuidePreDMTutorial(continue_callback=lambda: gui_app.push_widget(self._steps[2])), + TrainingGuideDMTutorial(continue_callback=lambda: gui_app.push_widget(self._steps[3])), + TrainingGuideRecordFront(continue_callback=completed_callback), + ] + + self._child(self._steps[0]) + self._steps[0].set_enabled(lambda: self.enabled and not self.is_dismissing) # for nav stack + + def _render(self, _): + self._steps[0].render(self._rect) + + +class QRCodeWidget(Widget): + def __init__(self, url: str, size: int = 170): + super().__init__() + self.set_rect(rl.Rectangle(0, 0, size, size)) + self._size = size + self._qr_texture: rl.Texture | None = None + self._generate_qr(url) + + def _generate_qr(self, url: str): + qr = qrcode.QRCode(version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=0) + qr.add_data(url) + qr.make(fit=True) + + pil_img = qr.make_image(fill_color="white", back_color="black").convert('RGBA') + img_array = np.array(pil_img, dtype=np.uint8) + + rl_image = rl.Image() + rl_image.data = rl.ffi.cast("void *", img_array.ctypes.data) + rl_image.width = pil_img.width + rl_image.height = pil_img.height + rl_image.mipmaps = 1 + rl_image.format = rl.PixelFormat.PIXELFORMAT_UNCOMPRESSED_R8G8B8A8 + + self._qr_texture = rl.load_texture_from_image(rl_image) + + def _render(self, _): + if self._qr_texture: + scale = self._size / self._qr_texture.height + rl.draw_texture_ex(self._qr_texture, rl.Vector2(round(self._rect.x), round(self._rect.y)), 0.0, scale, rl.WHITE) + + def __del__(self): + if self._qr_texture and self._qr_texture.id != 0: + rl.unload_texture(self._qr_texture) + + +class TermsPage(Scroller): + def __init__(self, on_accept, on_decline): + super().__init__() + + self._accept_button = BigConfirmationCircleButton("accept\nterms", gui_app.texture("icons_mici/setup/driver_monitoring/dm_check.png", 64, 64), on_accept) + self._decline_button = BigConfirmationCircleButton("decline &\nuninstall", gui_app.texture("icons_mici/setup/cancel.png", 64, 64), on_decline, + red=True, exit_on_confirm=False) + + self._terms_header = GreyBigButton("terms of\nservice", "scroll to continue", + gui_app.texture("icons_mici/setup/green_info.png", 64, 64)) + self._must_accept_card = GreyBigButton("", "You must accept the Terms of Service to use sunnypilot.") + + self._scroller.add_widgets([ + self._terms_header, + GreyBigButton("swipe for QR code", "or go to https://sunnypilot.ai/terms", + gui_app.texture("icons_mici/setup/small_slider/slider_arrow.png", 64, 56, flip_x=True)), + QRCodeWidget("https://sunnypilot.ai/terms"), + self._must_accept_card, + self._accept_button, + self._decline_button, + ]) + + def _render(self, _): + rl.draw_rectangle_rec(self._rect, rl.BLACK) + super()._render(_) + + +class OnboardingWindow(Widget): + def __init__(self, completed_callback: Callable[[], None]): + super().__init__() + self._completed_callback = completed_callback + self._accepted_terms: bool = (ui_state.params.get("HasAcceptedTerms") == terms_version and + ui_state.params.get("HasAcceptedTermsSP") == terms_version_sp) + self._training_done: bool = ui_state.params.get("CompletedTrainingVersion") == training_version + self._sunnylink_consent_done: bool = ui_state.params.get("CompletedSunnylinkConsentVersion") in { + sunnylink_consent_version, sunnylink_consent_declined + } + + self.set_rect(rl.Rectangle(0, 0, gui_app.width, gui_app.height)) + + # Windows — all pushed onto nav stack, _terms is always rendered as base layer + self._terms = TermsPage(on_accept=self._on_terms_accepted, on_decline=self._on_uninstall) + self._terms.set_enabled(lambda: self.enabled) # for nav stack + + self._sunnylink_consent = SunnylinkConsentPage( + on_accept=self._on_sunnylink_accepted, + on_decline=self._on_sunnylink_declined, + ) + + self._training_guide = TrainingGuide(completed_callback=self._on_completed_training) + self._training_guide.set_enabled(lambda: self.enabled) # for nav stack + + self._needs_initial_push = False + + def _on_uninstall(self): + ui_state.params.put_bool("DoUninstall", True, block=True) + + def show_event(self): + super().show_event() + device.set_override_interactive_timeout(300) + device.set_offroad_brightness(100) + self._needs_initial_push = True + + def hide_event(self): + super().hide_event() + # FIXME: when nav stack sends hide event to widget 2 below on push, this needs to be moved + device.set_override_interactive_timeout(None) + device.set_offroad_brightness(None) + + @property + def completed(self) -> bool: + return self._accepted_terms and self._sunnylink_consent_done and self._training_done + + def close(self): + ui_state.params.put_bool("IsDriverViewEnabled", False) + self._completed_callback() + + def _on_terms_accepted(self): + ui_state.params.put("HasAcceptedTerms", terms_version, block=True) + ui_state.params.put("HasAcceptedTermsSP", terms_version_sp, block=True) + self._accepted_terms = True + if not self._sunnylink_consent_done: + gui_app.push_widget(self._sunnylink_consent) + elif not self._training_done: + gui_app.push_widget(self._training_guide) + else: + self.close() + + def _on_sunnylink_accepted(self): + ui_state.params.put("CompletedSunnylinkConsentVersion", sunnylink_consent_version, block=True) + ui_state.params.put_bool("SunnylinkEnabled", True) + self._sunnylink_consent_done = True + if not self._training_done: + gui_app.push_widget(self._training_guide) + else: + self.close() + + def _on_sunnylink_declined(self): + ui_state.params.put("CompletedSunnylinkConsentVersion", sunnylink_consent_declined, block=True) + ui_state.params.put_bool("SunnylinkEnabled", False) + self._sunnylink_consent_done = True + if not self._training_done: + gui_app.push_widget(self._training_guide) + else: + self.close() + + def _on_completed_training(self): + ui_state.params.put("CompletedTrainingVersion", training_version, block=True) + self._training_done = True + self.close() + + def _render(self, _): + rl.draw_rectangle_rec(self._rect, rl.BLACK) + + # Deferred from show_event to avoid nested push_widget re-enable bug + if self._needs_initial_push: + self._needs_initial_push = False + if self._accepted_terms and not self._sunnylink_consent_done: + gui_app.push_widget(self._sunnylink_consent) + elif self._accepted_terms and self._sunnylink_consent_done and not self._training_done: + gui_app.push_widget(self._training_guide) + + self._terms.render(self._rect) diff --git a/openpilot/selfdrive/ui/mici/layouts/settings/developer.py b/openpilot/selfdrive/ui/mici/layouts/settings/developer.py new file mode 100644 index 0000000000..2d7dc0899d --- /dev/null +++ b/openpilot/selfdrive/ui/mici/layouts/settings/developer.py @@ -0,0 +1,200 @@ +from collections.abc import Callable +from openpilot.common.time_helpers import system_time_valid +from openpilot.system.ui.widgets.scroller import NavScroller +from openpilot.selfdrive.ui.mici.widgets.button import BigButton, BigToggle, BigParamControl, BigCircleParamControl, GreyBigButton +from openpilot.selfdrive.ui.mici.widgets.dialog import BigDialog, BigInputDialog, BigConfirmationCircleButton +from openpilot.system.ui.lib.application import gui_app +from openpilot.selfdrive.ui.layouts.settings.common import restart_needed_callback +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.selfdrive.ui.widgets.ssh_key import SshKeyFetcher + + +class AlphaLongConfirmPage(NavScroller): + def __init__(self, on_confirm: Callable[[], None]): + super().__init__() + + accept = BigConfirmationCircleButton("enable alpha\nlongitudinal", + gui_app.texture("icons_mici/setup/driver_monitoring/dm_check.png", 64, 64), + lambda: self.dismiss(on_confirm)) + + self._scroller.add_widgets([ + GreyBigButton("enabling alpha longitudinal", "scroll to continue", + gui_app.texture("icons_mici/setup/warning.png", 64, 64)), + GreyBigButton("", "WARNING: alpha longitudinal control may disable Automatic Emergency Braking (AEB)"), + GreyBigButton("", "On this car, openpilot defaults to the stock system's built-in ACC."), + GreyBigButton("", "Enabling this will switch to openpilot longitudinal control."), + GreyBigButton("", "Using Experimental mode is recommended with openpilot longitudinal control alpha."), + GreyBigButton("", "Changing this setting will restart openpilot if the car is powered on."), + accept, + ]) + + +class DeveloperLayoutMici(NavScroller): + def __init__(self): + super().__init__() + self._ssh_fetcher = SshKeyFetcher(ui_state.params) + + def github_username_callback(username: str): + if username: + self._ssh_keys_btn.set_value("Loading...") + self._ssh_keys_btn.set_enabled(False) + + def on_response(error): + self._ssh_keys_btn.set_enabled(True) + if error is None: + self._ssh_keys_btn.set_value(username) + else: + self._ssh_keys_btn.set_value("Not set") + gui_app.push_widget(BigDialog("", error)) + + self._ssh_fetcher.fetch(username, on_response) + else: + self._ssh_fetcher.clear() + self._ssh_keys_btn.set_value("Not set") + + def ssh_keys_callback(): + github_username = ui_state.params.get("GithubUsername") or "" + dlg = BigInputDialog("enter GitHub username...", github_username, minimum_length=0, confirm_callback=github_username_callback) + if not system_time_valid(): + dlg = BigDialog("", "Please connect to Wi-Fi to fetch your key.") + gui_app.push_widget(dlg) + return + gui_app.push_widget(dlg) + + txt_ssh = gui_app.texture("icons_mici/settings/developer/ssh.png", 56, 64) + github_username = ui_state.params.get("GithubUsername") or "" + self._ssh_keys_btn = BigButton("SSH keys", "Not set" if not github_username else github_username, icon=txt_ssh) + self._ssh_keys_btn.set_click_callback(ssh_keys_callback) + + # adb, ssh, ssh keys, debug mode, joystick debug mode, longitudinal maneuver mode, ip address + # ******** Main Scroller ******** + self._adb_toggle = BigCircleParamControl(gui_app.texture("icons_mici/adb_short.png", 82, 82), "AdbEnabled", icon_offset=(0, 12)) + self._ssh_toggle = BigCircleParamControl(gui_app.texture("icons_mici/ssh_short.png", 82, 82), "SshEnabled", icon_offset=(0, 12)) + self._joystick_toggle = BigToggle("joystick debug mode", + initial_state=ui_state.params.get_bool("JoystickDebugMode"), + toggle_callback=self._on_joystick_debug_mode) + self._long_maneuver_toggle = BigToggle("longitudinal maneuver mode", + initial_state=ui_state.params.get_bool("LongitudinalManeuverMode"), + toggle_callback=self._on_long_maneuver_mode) + self._lat_maneuver_toggle = BigToggle("lateral maneuver mode", + initial_state=ui_state.params.get_bool("LateralManeuverMode"), + toggle_callback=self._on_lat_maneuver_mode) + self._alpha_long_toggle = BigToggle("alpha longitudinal", + initial_state=ui_state.params.get_bool("AlphaLongitudinalEnabled"), + toggle_callback=self._on_alpha_long_enabled) + self._debug_mode_toggle = BigParamControl("ui debug mode", "ShowDebugInfo", + toggle_callback=lambda checked: (gui_app.set_show_touches(checked), + gui_app.set_show_fps(checked))) + + self._scroller.add_widgets([ + self._adb_toggle, + self._ssh_toggle, + self._ssh_keys_btn, + self._joystick_toggle, + self._long_maneuver_toggle, + self._lat_maneuver_toggle, + self._alpha_long_toggle, + self._debug_mode_toggle, + ]) + + # Toggle lists + self._refresh_toggles = ( + ("AdbEnabled", self._adb_toggle), + ("SshEnabled", self._ssh_toggle), + ("JoystickDebugMode", self._joystick_toggle), + ("LongitudinalManeuverMode", self._long_maneuver_toggle), + ("LateralManeuverMode", self._lat_maneuver_toggle), + ("AlphaLongitudinalEnabled", self._alpha_long_toggle), + ("ShowDebugInfo", self._debug_mode_toggle), + ) + onroad_blocked_toggles = (self._adb_toggle, self._joystick_toggle) + release_blocked_toggles = (self._joystick_toggle, self._long_maneuver_toggle, self._lat_maneuver_toggle, self._alpha_long_toggle) + engaged_blocked_toggles = (self._long_maneuver_toggle, self._lat_maneuver_toggle, self._alpha_long_toggle) + + # Hide non-release toggles on release builds + for item in release_blocked_toggles: + item.set_visible(not ui_state.is_release) + + # Disable toggles that require offroad + for item in onroad_blocked_toggles: + item.set_enabled(lambda: ui_state.is_offroad()) + + # Disable toggles that require not engaged + for item in engaged_blocked_toggles: + item.set_enabled(lambda: not ui_state.engaged) + + # Set initial state + if ui_state.params.get_bool("ShowDebugInfo"): + gui_app.set_show_touches(True) + gui_app.set_show_fps(True) + + ui_state.add_offroad_transition_callback(self._update_toggles) + + def _update_state(self): + super()._update_state() + self._ssh_fetcher.update() + + def show_event(self): + super().show_event() + self._update_toggles() + + def _update_toggles(self): + ui_state.update_params() + + # CP gating + if ui_state.CP is not None: + alpha_avail = ui_state.CP.alphaLongitudinalAvailable + if not alpha_avail or ui_state.is_release: + self._alpha_long_toggle.set_visible(False) + ui_state.params.remove("AlphaLongitudinalEnabled") + else: + self._alpha_long_toggle.set_visible(True) + + long_man_enabled = ui_state.has_longitudinal_control and ui_state.is_offroad() + self._long_maneuver_toggle.set_enabled(long_man_enabled) + self._lat_maneuver_toggle.set_enabled(ui_state.is_offroad()) + else: + self._long_maneuver_toggle.set_enabled(False) + self._lat_maneuver_toggle.set_enabled(False) + self._alpha_long_toggle.set_visible(False) + + # Refresh toggles from params to mirror external changes + for key, item in self._refresh_toggles: + item.set_checked(ui_state.params.get_bool(key)) + + def _on_joystick_debug_mode(self, state: bool): + ui_state.params.put_bool("JoystickDebugMode", state, block=True) + ui_state.params.put_bool("LongitudinalManeuverMode", False, block=True) + self._long_maneuver_toggle.set_checked(False) + ui_state.params.put_bool("LateralManeuverMode", False, block=True) + self._lat_maneuver_toggle.set_checked(False) + + def _on_long_maneuver_mode(self, state: bool): + ui_state.params.put_bool("LongitudinalManeuverMode", state, block=True) + ui_state.params.put_bool("JoystickDebugMode", False, block=True) + self._joystick_toggle.set_checked(False) + ui_state.params.put_bool("LateralManeuverMode", False, block=True) + self._lat_maneuver_toggle.set_checked(False) + restart_needed_callback() + + def _on_lat_maneuver_mode(self, state: bool): + ui_state.params.put_bool("LateralManeuverMode", state, block=True) + ui_state.params.put_bool("ExperimentalMode", False, block=True) + ui_state.params.put_bool("JoystickDebugMode", False, block=True) + self._joystick_toggle.set_checked(False) + ui_state.params.put_bool("LongitudinalManeuverMode", False, block=True) + self._long_maneuver_toggle.set_checked(False) + restart_needed_callback() + + def _on_alpha_long_enabled(self, state: bool): + def do_toggle(_state: bool): + ui_state.params.put_bool("AlphaLongitudinalEnabled", _state, block=True) + restart_needed_callback() + self._update_toggles() + + if state: + # Don't show enabled state until confirm + self._alpha_long_toggle.set_checked(False) + gui_app.push_widget(AlphaLongConfirmPage(lambda: do_toggle(True))) + else: + do_toggle(False) diff --git a/openpilot/selfdrive/ui/mici/layouts/settings/device.py b/openpilot/selfdrive/ui/mici/layouts/settings/device.py new file mode 100644 index 0000000000..7f4a9ab0b8 --- /dev/null +++ b/openpilot/selfdrive/ui/mici/layouts/settings/device.py @@ -0,0 +1,218 @@ +import os +import pyray as rl +from collections.abc import Callable + +from openpilot.common.basedir import BASEDIR +from openpilot.common.params import Params +from openpilot.common.time_helpers import system_time_valid +from openpilot.system.ui.widgets.scroller import NavRawScrollPanel, NavScroller +from openpilot.selfdrive.ui.mici.widgets.button import BigButton, BigCircleButton +from openpilot.selfdrive.ui.mici.widgets.dialog import BigDialog, BigConfirmationDialog +from openpilot.selfdrive.ui.mici.widgets.pairing_dialog import PairingDialog +from openpilot.selfdrive.ui.mici.onroad.driver_camera_dialog import DriverCameraDialog +from openpilot.selfdrive.ui.mici.layouts.onboarding import TrainingGuide, TermsPage +from openpilot.system.ui.lib.application import gui_app, FontWeight, MousePos +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.widgets import Widget +from openpilot.selfdrive.ui.ui_state import device, ui_state +from openpilot.system.ui.widgets.label import UnifiedLabel +from openpilot.system.ui.widgets.html_render import HtmlRenderer +from openpilot.system.athena.registration import UNREGISTERED_DONGLE_ID + + +class ReviewTermsPage(TermsPage, NavScroller): + """TermsPage with NavWidget swipe-to-dismiss for reviewing in device settings.""" + def __init__(self): + super().__init__(on_accept=self.dismiss, on_decline=self.dismiss) + self._terms_header.set_visible(False) + self._must_accept_card.set_visible(False) + self._accept_button.set_visible(False) + self._decline_button.set_visible(False) + + +class ReviewTrainingGuide(TrainingGuide): + def show_event(self): + super().show_event() + device.set_override_interactive_timeout(300) + + def hide_event(self): + super().hide_event() + device.set_override_interactive_timeout(None) + ui_state.params.put_bool("IsDriverViewEnabled", False) + + +class MiciFccModal(NavRawScrollPanel): + def __init__(self, file_path: str | None = None, text: str | None = None): + super().__init__() + self._content = HtmlRenderer(file_path=file_path, text=text) + self._fcc_logo = gui_app.texture("icons_mici/settings/device/fcc_logo.png", 76, 64) + + def _render(self, rect: rl.Rectangle): + content_height = self._content.get_total_height(int(rect.width)) + content_height += self._fcc_logo.height + 20 + + scroll_content_rect = rl.Rectangle(rect.x, rect.y, rect.width, content_height) + scroll_offset = round(self._scroll_panel.update(rect, scroll_content_rect.height)) + + fcc_pos = rl.Vector2(rect.x + 20, rect.y + 20 + scroll_offset) + + scroll_content_rect.y += scroll_offset + self._fcc_logo.height + 20 + self._content.render(scroll_content_rect) + + rl.draw_texture_ex(self._fcc_logo, fcc_pos, 0.0, 1.0, rl.WHITE) + + +def _engaged_confirmation_click(callback: Callable, action_text: str, icon: rl.Texture, exit_on_confirm: bool = True, red: bool = False): + if not ui_state.engaged: + def confirm_callback(): + # Check engaged again in case it changed while the dialog was open + # TODO: if true, we stay on the dialog if not exit_on_confirm until normal onroad timeout + if not ui_state.engaged: + callback() + + gui_app.push_widget(BigConfirmationDialog(f"slide to\n{action_text.lower()}", icon, confirm_callback, exit_on_confirm=exit_on_confirm, red=red)) + else: + gui_app.push_widget(BigDialog("", f"Disengage to {action_text}")) + + +class EngagedConfirmationCircleButton(BigCircleButton): + def __init__(self, title: str, icon: rl.Texture, callback: Callable[[], None], exit_on_confirm: bool = True, + red: bool = False, icon_offset: tuple[int, int] = (0, 0)): + super().__init__(icon, red, icon_offset) + self.set_click_callback(lambda: _engaged_confirmation_click(callback, title, icon, exit_on_confirm=exit_on_confirm, red=red)) + + +class EngagedConfirmationButton(BigButton): + def __init__(self, text: str, action_text: str, icon: rl.Texture, callback: Callable[[], None], + exit_on_confirm: bool = True, red: bool = False): + super().__init__(text, "", icon) + self.set_click_callback(lambda: _engaged_confirmation_click(callback, action_text, icon, exit_on_confirm=exit_on_confirm, red=red)) + + +class DeviceInfoLayoutMici(Widget): + def __init__(self): + super().__init__() + + self.set_rect(rl.Rectangle(0, 0, 360, 180)) + + params = Params() + subheader_color = rl.Color(255, 255, 255, int(255 * 0.9 * 0.65)) + max_width = int(self._rect.width - 20) + self._dongle_id_label = UnifiedLabel("device ID", 48, max_width=max_width, font_weight=FontWeight.DISPLAY, wrap_text=False) + self._dongle_id_text_label = UnifiedLabel(params.get("DongleId") or 'N/A', 32, max_width=max_width, text_color=subheader_color, + font_weight=FontWeight.ROMAN, wrap_text=False) + + self._serial_number_label = UnifiedLabel("serial", 48, max_width=max_width, font_weight=FontWeight.DISPLAY, wrap_text=False) + self._serial_number_text_label = UnifiedLabel(params.get("HardwareSerial") or 'N/A', 32, max_width=max_width, text_color=subheader_color, + font_weight=FontWeight.ROMAN, wrap_text=False) + + def _render(self, _): + self._dongle_id_label.set_position(self._rect.x + 20, self._rect.y - 10) + self._dongle_id_label.render() + + self._dongle_id_text_label.set_position(self._rect.x + 20, self._rect.y + 68 - 25) + self._dongle_id_text_label.render() + + self._serial_number_label.set_position(self._rect.x + 20, self._rect.y + 114 - 30) + self._serial_number_label.render() + + self._serial_number_text_label.set_position(self._rect.x + 20, self._rect.y + 161 - 25) + self._serial_number_text_label.render() + + +class PairBigButton(BigButton): + def __init__(self): + super().__init__("pair", "connect.comma.ai", gui_app.texture("icons_mici/settings/comma_icon.png", 33, 60)) + + def _get_label_font_size(self): + return 64 + + def _update_state(self): + super()._update_state() + + if ui_state.prime_state.is_paired(): + self.set_text("paired") + if ui_state.prime_state.is_prime(): + self.set_value("subscribed") + else: + self.set_value("upgrade to prime") + else: + self.set_text("pair") + self.set_value("connect.comma.ai") + + def _handle_mouse_release(self, mouse_pos: MousePos): + super()._handle_mouse_release(mouse_pos) + + # TODO: show ad dialog when clicked if not prime + if ui_state.prime_state.is_paired(): + return + dlg: BigDialog | PairingDialog + if not system_time_valid(): + dlg = BigDialog("", tr("Please connect to Wi-Fi to complete initial pairing.")) + elif UNREGISTERED_DONGLE_ID == (ui_state.params.get("DongleId") or UNREGISTERED_DONGLE_ID): + dlg = BigDialog("", tr("Device must be registered with the comma.ai backend to pair.")) + else: + dlg = PairingDialog() + gui_app.push_widget(dlg) + + +class DeviceLayoutMici(NavScroller): + def __init__(self): + super().__init__() + + self._fcc_dialog: MiciFccModal | None = None + + def power_off_callback(): + ui_state.params.put_bool("DoShutdown", True, block=True) + + def reboot_callback(): + ui_state.params.put_bool("DoReboot", True, block=True) + + def reset_calibration_callback(): + params = ui_state.params + params.remove("CalibrationParams") + params.remove("LiveTorqueParameters") + params.remove("LiveParametersV2") + params.remove("LiveDelay") + params.put_bool("OnroadCycleRequested", True, block=True) + + reset_calibration_btn = EngagedConfirmationButton("reset calibration", "reset", gui_app.texture("icons_mici/settings/device/lkas.png", 122, 64), + reset_calibration_callback) + + reboot_btn = EngagedConfirmationCircleButton("reboot", gui_app.texture("icons_mici/settings/device/reboot.png", 64, 70), + reboot_callback, exit_on_confirm=False) + + self._power_off_btn = EngagedConfirmationCircleButton("power off", gui_app.texture("icons_mici/settings/device/power.png", 64, 66), + power_off_callback, exit_on_confirm=False, red=True) + self._power_off_btn.set_visible(lambda: not ui_state.ignition) + + regulatory_btn = BigButton("regulatory info", "", gui_app.texture("icons_mici/settings/device/info.png", 64, 64)) + regulatory_btn.set_click_callback(self._on_regulatory) + + driver_cam_btn = BigButton("driver\ncamera preview", "", gui_app.texture("icons_mici/settings/device/cameras.png", 64, 64)) + driver_cam_btn.set_click_callback(lambda: gui_app.push_widget(DriverCameraDialog())) + driver_cam_btn.set_enabled(lambda: ui_state.is_offroad()) + + review_training_guide_btn = BigButton("review\ntraining guide", "", gui_app.texture("icons_mici/settings/device/info.png", 64, 64)) + review_training_guide_btn.set_click_callback(lambda: gui_app.push_widget(ReviewTrainingGuide(completed_callback=lambda: gui_app.pop_widgets_to(self)))) + review_training_guide_btn.set_enabled(lambda: ui_state.is_offroad()) + + terms_btn = BigButton("terms &\nconditions", "", gui_app.texture("icons_mici/settings/device/info.png", 64, 64)) + terms_btn.set_click_callback(lambda: gui_app.push_widget(ReviewTermsPage())) + + self._scroller.add_widgets([ + DeviceInfoLayoutMici(), + PairBigButton(), + review_training_guide_btn, + driver_cam_btn, + terms_btn, + regulatory_btn, + reset_calibration_btn, + reboot_btn, + self._power_off_btn, + ]) + + def _on_regulatory(self): + if not self._fcc_dialog: + self._fcc_dialog = MiciFccModal(os.path.join(BASEDIR, "openpilot/selfdrive/assets/offroad/mici_fcc.html")) + gui_app.push_widget(self._fcc_dialog) diff --git a/openpilot/selfdrive/ui/mici/layouts/settings/firehose.py b/openpilot/selfdrive/ui/mici/layouts/settings/firehose.py new file mode 100644 index 0000000000..5e3b6da2cc --- /dev/null +++ b/openpilot/selfdrive/ui/mici/layouts/settings/firehose.py @@ -0,0 +1,224 @@ +import requests +import threading +import time +import pyray as rl + +from openpilot.common.api import api_get +from openpilot.common.params import Params +from openpilot.common.realtime import drop_realtime +from openpilot.common.swaglog import cloudlog +from openpilot.selfdrive.ui.lib.api_helpers import get_token +from openpilot.selfdrive.ui.ui_state import ui_state, device +from openpilot.system.athena.registration import UNREGISTERED_DONGLE_ID +from openpilot.system.ui.lib.application import gui_app, FontWeight, FONT_SCALE +from openpilot.system.ui.lib.wrap_text import wrap_text +from openpilot.system.ui.lib.scroll_panel2 import GuiScrollPanel2 +from openpilot.system.ui.lib.multilang import tr, trn, tr_noop +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.scroller import NavRawScrollPanel + +TITLE = tr_noop("Firehose Mode") +DESCRIPTION = tr_noop( + "sunnypilot learns to drive by watching humans, like you, drive.\n\n" + + "Firehose Mode allows you to maximize your training data uploads to improve " + + "openpilot's driving models. More data means bigger models, which means better Experimental Mode." +) +INSTRUCTIONS_INTRO = tr_noop( + "For maximum effectiveness, bring your device inside and connect to a good USB-C adapter and Wi-Fi weekly.\n\n" + + "Firehose Mode can also work while you're driving if connected to a hotspot or unlimited SIM card." +) +FAQ_HEADER = tr_noop("Frequently Asked Questions") +FAQ_ITEMS = [ + (tr_noop("Does it matter how or where I drive?"), tr_noop("Nope, just drive as you normally would.")), + (tr_noop("Do all of my segments get pulled in Firehose Mode?"), tr_noop("No, we selectively pull a subset of your segments.")), + (tr_noop("What's a good USB-C adapter?"), tr_noop("Any fast phone or laptop charger should be fine.")), + (tr_noop("Does it matter which software I run?"), tr_noop("Yes, only upstream openpilot (and particular forks) are able to be used for training.")), +] + + +class FirehoseLayoutBase(Widget): + PARAM_KEY = "ApiCache_FirehoseStats" + GREEN = rl.Color(46, 204, 113, 255) + RED = rl.Color(231, 76, 60, 255) + GRAY = rl.Color(68, 68, 68, 255) + LIGHT_GRAY = rl.Color(228, 228, 228, 255) + UPDATE_INTERVAL = 30 # seconds + + def __init__(self): + super().__init__() + self._params = Params() + self._session = requests.Session() # reuse session to reduce SSL handshake overhead + self._segment_count = self._get_segment_count() + + self._scroll_panel = GuiScrollPanel2(horizontal=False) + self._content_height = 0 + + self._running = True + self._update_thread = threading.Thread(target=self._update_loop, daemon=True) + self._update_thread.start() + + def __del__(self): + self._running = False + try: + if self._update_thread and self._update_thread.is_alive(): + self._update_thread.join(timeout=1.0) + except Exception: + pass + + def show_event(self): + super().show_event() + self._scroll_panel.set_offset(0) + + def _get_segment_count(self) -> int: + stats = self._params.get(self.PARAM_KEY) + if not stats: + return 0 + try: + return int(stats.get("firehose", 0)) + except Exception: + cloudlog.exception(f"Failed to decode firehose stats: {stats}") + return 0 + + def _render(self, rect: rl.Rectangle): + # compute total content height for scrolling + content_height = self._measure_content_height(rect) + scroll_offset = self._scroll_panel.update(rect, content_height) + + # start drawing with offset + x = rect.x + 40 + y = rect.y + 40 + scroll_offset + w = rect.width - 80 + + # Title + title_text = tr(TITLE) + title_font = gui_app.font(FontWeight.BOLD) + title_size = 64 + rl.draw_text_ex(title_font, title_text, rl.Vector2(x, y), title_size, 0, rl.WHITE) + y += int(title_size * FONT_SCALE) + 20 + + # Description + y = self._draw_wrapped_text(x, y, w, tr(DESCRIPTION), gui_app.font(FontWeight.ROMAN), 36, rl.WHITE) + y += 20 + + # Separator + rl.draw_rectangle_rec(rl.Rectangle(x, y, w, 2), self.GRAY) + y += 20 + + # Status + status_text, status_color = self._get_status() + y = self._draw_wrapped_text(x, y, w, status_text, gui_app.font(FontWeight.BOLD), 48, status_color) + y += 20 + + # Contribution count (if available) + if self._segment_count > 0: + contrib_text = trn("{} segment of your driving is in the training dataset so far.", + "{} segments of your driving is in the training dataset so far.", self._segment_count).format(self._segment_count) + y = self._draw_wrapped_text(x, y, w, contrib_text, gui_app.font(FontWeight.BOLD), 42, rl.WHITE) + y += 20 + + # Separator + rl.draw_rectangle_rec(rl.Rectangle(x, y, w, 2), self.GRAY) + y += 20 + + # Instructions intro + y = self._draw_wrapped_text(x, y, w, tr(INSTRUCTIONS_INTRO), gui_app.font(FontWeight.ROMAN), 32, self.LIGHT_GRAY) + y += 20 + + # FAQ Header + y = self._draw_wrapped_text(x, y, w, tr(FAQ_HEADER), gui_app.font(FontWeight.BOLD), 44, rl.WHITE) + y += 20 + + # FAQ Items + for question, answer in FAQ_ITEMS: + y = self._draw_wrapped_text(x, y, w, tr(question), gui_app.font(FontWeight.BOLD), 32, self.LIGHT_GRAY) + y = self._draw_wrapped_text(x, y, w, tr(answer), gui_app.font(FontWeight.ROMAN), 32, self.LIGHT_GRAY) + y += 20 + + def _draw_wrapped_text(self, x, y, width, text, font, font_size, color): + wrapped = wrap_text(font, text, font_size, width) + for line in wrapped: + rl.draw_text_ex(font, line, rl.Vector2(x, y), font_size, 0, color) + y += int(font_size * FONT_SCALE) + return y + + def _measure_content_height(self, rect: rl.Rectangle) -> int: + # Rough measurement using the same wrapping as rendering + w = int(rect.width - 80) + y = 40 + + # Title + title_size = 72 + y += int(title_size * FONT_SCALE) + 20 + + # Description + desc_lines = wrap_text(gui_app.font(FontWeight.ROMAN), tr(DESCRIPTION), 36, w) + y += int(len(desc_lines) * 36 * FONT_SCALE) + 20 + + # Separator + Status + y += 2 + 20 + status_text, _ = self._get_status() + status_lines = wrap_text(gui_app.font(FontWeight.BOLD), status_text, 48, w) + y += int(len(status_lines) * 48 * FONT_SCALE) + 20 + + # Contribution count + if self._segment_count > 0: + contrib_text = trn("{} segment of your driving is in the training dataset so far.", + "{} segments of your driving is in the training dataset so far.", self._segment_count).format(self._segment_count) + contrib_lines = wrap_text(gui_app.font(FontWeight.BOLD), contrib_text, 42, w) + y += int(len(contrib_lines) * 42 * FONT_SCALE) + 20 + + # Separator + Instructions + y += 2 + 20 + + # Instructions intro + intro_lines = wrap_text(gui_app.font(FontWeight.ROMAN), tr(INSTRUCTIONS_INTRO), 32, w) + y += int(len(intro_lines) * 32 * FONT_SCALE) + 20 + + # FAQ Header + faq_header_lines = wrap_text(gui_app.font(FontWeight.BOLD), tr(FAQ_HEADER), 44, w) + y += int(len(faq_header_lines) * 44 * FONT_SCALE) + 20 + + # FAQ Items + for question, answer in FAQ_ITEMS: + q_lines = wrap_text(gui_app.font(FontWeight.BOLD), tr(question), 32, w) + y += int(len(q_lines) * 32 * FONT_SCALE) + a_lines = wrap_text(gui_app.font(FontWeight.ROMAN), tr(answer), 32, w) + y += int(len(a_lines) * 32 * FONT_SCALE) + 20 + + # bottom padding + y += 40 + return y + + def _get_status(self) -> tuple[str, rl.Color]: + network_type = ui_state.sm["deviceState"].networkType + network_metered = ui_state.sm["deviceState"].networkMetered + + if not network_metered and network_type != 0: # Not metered and connected + return tr("ACTIVE"), self.GREEN + else: + return tr("INACTIVE: connect to an unmetered network"), self.RED + + def _fetch_firehose_stats(self): + try: + dongle_id = self._params.get("DongleId") + if not dongle_id or dongle_id == UNREGISTERED_DONGLE_ID: + return + identity_token = get_token(dongle_id) + response = api_get(f"v1/devices/{dongle_id}/firehose_stats", access_token=identity_token, session=self._session) + if response.status_code == 200: + data = response.json() + self._segment_count = data.get("firehose", 0) + self._params.put(self.PARAM_KEY, data) + except Exception as e: + cloudlog.error(f"Failed to fetch firehose stats: {e}") + + def _update_loop(self): + drop_realtime() + while self._running: + if not ui_state.started and device._awake: + self._fetch_firehose_stats() + time.sleep(self.UPDATE_INTERVAL) + + +class FirehoseLayout(NavRawScrollPanel, FirehoseLayoutBase): + pass diff --git a/openpilot/selfdrive/ui/mici/layouts/settings/network/__init__.py b/openpilot/selfdrive/ui/mici/layouts/settings/network/__init__.py new file mode 100644 index 0000000000..ddbab4b478 --- /dev/null +++ b/openpilot/selfdrive/ui/mici/layouts/settings/network/__init__.py @@ -0,0 +1,60 @@ +import pyray as rl + +from openpilot.selfdrive.ui.mici.layouts.settings.network.wifi_ui import WifiIcon +from openpilot.selfdrive.ui.mici.widgets.button import BigButton +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.lib.wifi_manager import WifiManager, ConnectStatus, SecurityType, normalize_ssid + + +class WifiNetworkButton(BigButton): + def __init__(self, wifi_manager: WifiManager): + self._wifi_manager = wifi_manager + self._lock_txt = gui_app.texture("icons_mici/settings/network/new/lock.png", 28, 36) + self._draw_lock = False + + self._wifi_slash_txt = gui_app.texture("icons_mici/settings/network/wifi_strength_slash.png", 64, 56) + self._wifi_low_txt = gui_app.texture("icons_mici/settings/network/wifi_strength_low.png", 64, 47) + self._wifi_medium_txt = gui_app.texture("icons_mici/settings/network/wifi_strength_medium.png", 64, 47) + self._wifi_full_txt = gui_app.texture("icons_mici/settings/network/wifi_strength_full.png", 64, 47) + + super().__init__("wi-fi", "not connected", self._wifi_slash_txt, scroll=True) + + def _update_state(self): + super()._update_state() + + # Update wi-fi button with ssid and ip address + # TODO: make sure we handle hidden ssids + wifi_state = self._wifi_manager.wifi_state + display_network = next((n for n in self._wifi_manager.networks if n.ssid == wifi_state.ssid), None) + if wifi_state.status == ConnectStatus.CONNECTING: + self.set_text(normalize_ssid(wifi_state.ssid or "wi-fi")) + self.set_value("starting" if self._wifi_manager.is_tethering_active() else "connecting...") + elif wifi_state.status == ConnectStatus.CONNECTED: + self.set_text(normalize_ssid(wifi_state.ssid or "wi-fi")) + self.set_value(self._wifi_manager.ipv4_address or "obtaining IP...") + else: + display_network = None + self.set_text("wi-fi") + self.set_value("not connected") + + if display_network is not None: + strength = WifiIcon.get_strength_icon_idx(display_network.strength) + self.set_icon(self._wifi_full_txt if strength == 2 else self._wifi_medium_txt if strength == 1 else self._wifi_low_txt) + self._draw_lock = display_network.security_type not in (SecurityType.OPEN, SecurityType.UNSUPPORTED) + elif self._wifi_manager.is_tethering_active(): + # takes a while to get Network + self.set_icon(self._wifi_full_txt) + self._draw_lock = True + else: + self.set_icon(self._wifi_slash_txt) + self._draw_lock = False + + def _draw_content(self, btn_y: float): + super()._draw_content(btn_y) + # Render lock icon at lower right of wifi icon if secured + if self._draw_lock: + icon_x = self._rect.x + self._rect.width - 30 - self._txt_icon.width + icon_y = btn_y + 30 + lock_x = icon_x + self._txt_icon.width - self._lock_txt.width + 7 + lock_y = icon_y + self._txt_icon.height - self._lock_txt.height + 8 + rl.draw_texture_ex(self._lock_txt, (lock_x, lock_y), 0.0, 1.0, rl.WHITE) diff --git a/openpilot/selfdrive/ui/mici/layouts/settings/network/network_layout.py b/openpilot/selfdrive/ui/mici/layouts/settings/network/network_layout.py new file mode 100644 index 0000000000..58b3d0c77d --- /dev/null +++ b/openpilot/selfdrive/ui/mici/layouts/settings/network/network_layout.py @@ -0,0 +1,141 @@ +from openpilot.system.ui.widgets.scroller import NavScroller +from openpilot.selfdrive.ui.mici.layouts.settings.network import WifiNetworkButton +from openpilot.selfdrive.ui.mici.layouts.settings.network.wifi_ui import WifiUIMici +from openpilot.selfdrive.ui.mici.widgets.button import BigButton, BigMultiToggle, BigParamControl, BigToggle +from openpilot.selfdrive.ui.mici.widgets.dialog import BigInputDialog +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.selfdrive.ui.lib.prime_state import PrimeType +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.lib.wifi_manager import WifiManager, Network, MeteredType + + +class NetworkLayoutMici(NavScroller): + def __init__(self): + super().__init__() + + self._wifi_manager = WifiManager() + self._wifi_manager.set_active(False) + self._wifi_ui = WifiUIMici(self._wifi_manager) + + self._wifi_manager.add_callbacks( + networks_updated=self._on_network_updated, + ) + + # ******** Tethering ******** + def tethering_toggle_callback(checked: bool): + self._tethering_toggle_btn.set_enabled(False) + self._tethering_password_btn.set_enabled(False) + self._network_metered_btn.set_enabled(False) + self._wifi_manager.set_tethering_active(checked) + + self._tethering_toggle_btn = BigToggle("enable tethering", "", toggle_callback=tethering_toggle_callback) + + def tethering_password_callback(password: str): + if password: + self._tethering_toggle_btn.set_enabled(False) + self._tethering_password_btn.set_enabled(False) + self._wifi_manager.set_tethering_password(password) + + def tethering_password_clicked(): + tethering_password = self._wifi_manager.tethering_password + dlg = BigInputDialog("enter password...", tethering_password, minimum_length=8, + confirm_callback=tethering_password_callback) + gui_app.push_widget(dlg) + + txt_tethering = gui_app.texture("icons_mici/settings/network/tethering.png", 64, 54) + self._tethering_password_btn = BigButton("tethering password", "", txt_tethering) + self._tethering_password_btn.set_click_callback(tethering_password_clicked) + + # ******** Network Metered ******** + def network_metered_callback(value: str): + self._network_metered_btn.set_enabled(False) + metered = { + 'default': MeteredType.UNKNOWN, + 'metered': MeteredType.YES, + 'unmetered': MeteredType.NO + }.get(value, MeteredType.UNKNOWN) + self._wifi_manager.set_current_network_metered(metered) + + # TODO: signal for current network metered type when changing networks, this is wrong until you press it once + # TODO: disable when not connected + self._network_metered_btn = BigMultiToggle("network usage", ["default", "metered", "unmetered"], select_callback=network_metered_callback) + self._network_metered_btn.set_enabled(False) + + self._wifi_button = WifiNetworkButton(self._wifi_manager) + self._wifi_button.set_click_callback(lambda: gui_app.push_widget(self._wifi_ui)) + + # ******** Advanced settings ******** + # ******** Roaming toggle ******** + self._roaming_btn = BigParamControl("enable roaming", "GsmRoaming") + + # ******** APN settings ******** + self._apn_btn = BigButton("apn settings", "edit") + self._apn_btn.set_click_callback(self._edit_apn) + + # ******** Cellular metered toggle ******** + self._cellular_metered_btn = BigParamControl("cellular metered", "GsmMetered") + + # Main scroller ---------------------------------- + self._scroller.add_widgets([ + self._wifi_button, + self._network_metered_btn, + self._tethering_toggle_btn, + self._tethering_password_btn, + # /* Advanced settings + self._roaming_btn, + self._apn_btn, + self._cellular_metered_btn, + # */ + ]) + + def _update_state(self): + super()._update_state() + + # If not using prime SIM, show GSM settings and enable IPv4 forwarding + show_cell_settings = ui_state.prime_state.get_type() in (PrimeType.NONE, PrimeType.LITE) + self._wifi_manager.set_ipv4_forward(show_cell_settings) + self._roaming_btn.set_visible(show_cell_settings) + self._apn_btn.set_visible(show_cell_settings) + self._cellular_metered_btn.set_visible(show_cell_settings) + + def show_event(self): + super().show_event() + self._wifi_manager.set_active(True) + + # Process wifi callbacks while at any point in the nav stack + gui_app.add_nav_stack_tick(self._wifi_manager.process_callbacks) + + def hide_event(self): + super().hide_event() + self._wifi_manager.set_active(False) + + gui_app.remove_nav_stack_tick(self._wifi_manager.process_callbacks) + + def _edit_apn(self): + def update_apn(apn: str): + apn = apn.strip() + if apn == "": + ui_state.params.remove("GsmApn") + else: + ui_state.params.put("GsmApn", apn) + + current_apn = ui_state.params.get("GsmApn") or "" + dlg = BigInputDialog("enter APN...", current_apn, minimum_length=0, confirm_callback=update_apn) + gui_app.push_widget(dlg) + + def _on_network_updated(self, networks: list[Network]): + # Update tethering state + tethering_active = self._wifi_manager.is_tethering_active() + # TODO: use real signals (like activated/settings changed, etc.) to speed up re-enabling buttons + self._tethering_toggle_btn.set_enabled(True) + self._tethering_password_btn.set_enabled(True) + self._network_metered_btn.set_enabled(lambda: not tethering_active and bool(self._wifi_manager.ipv4_address)) + self._tethering_toggle_btn.set_checked(tethering_active) + + # Update network metered + self._network_metered_btn.set_value( + { + MeteredType.UNKNOWN: 'default', + MeteredType.YES: 'metered', + MeteredType.NO: 'unmetered' + }.get(self._wifi_manager.current_network_metered, 'default')) diff --git a/openpilot/selfdrive/ui/mici/layouts/settings/network/wifi_ui.py b/openpilot/selfdrive/ui/mici/layouts/settings/network/wifi_ui.py new file mode 100644 index 0000000000..8404faf9f7 --- /dev/null +++ b/openpilot/selfdrive/ui/mici/layouts/settings/network/wifi_ui.py @@ -0,0 +1,391 @@ +import math +import numpy as np +import pyray as rl +from collections.abc import Callable + +from openpilot.common.swaglog import cloudlog +from openpilot.selfdrive.ui.mici.widgets.dialog import BigInputDialog, BigConfirmationDialog +from openpilot.selfdrive.ui.mici.widgets.button import BigButton, LABEL_COLOR +from openpilot.system.ui.lib.application import gui_app, MousePos, FontWeight +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.scroller import NavScroller +from openpilot.system.ui.lib.wifi_manager import WifiManager, Network, SecurityType, normalize_ssid + + +class LoadingAnimation(Widget): + RADIUS = 8 + SPACING = 24 # center-to-center: diameter (16) + gap (8) + Y_MAG = 11.2 + + def __init__(self): + super().__init__() + w = self.SPACING * 2 + self.RADIUS * 2 + h = self.RADIUS * 2 + int(self.Y_MAG) + self.set_rect(rl.Rectangle(0, 0, w, h)) + + def _render(self, _): + # Balls rest at bottom center; bounce upward + base_x = int(self._rect.x + self._rect.width / 2) + base_y = int(self._rect.y + self._rect.height - self.RADIUS) + + for i in range(3): + x = base_x + (i - 1) * self.SPACING + y = int(base_y + min(math.sin((rl.get_time() - i * 0.2) * 4) * self.Y_MAG, 0)) + alpha = int(np.interp(base_y - y, [0, self.Y_MAG], [255 * 0.45, 255 * 0.9])) + rl.draw_circle(x, y, self.RADIUS, rl.Color(255, 255, 255, alpha)) + + +class WifiIcon(Widget): + def __init__(self, network: Network): + super().__init__() + self.set_rect(rl.Rectangle(0, 0, 48 + 5, 36 + 5)) + + self._wifi_slash_txt = gui_app.texture("icons_mici/settings/network/wifi_strength_slash.png", 48, 42) + self._wifi_low_txt = gui_app.texture("icons_mici/settings/network/wifi_strength_low.png", 48, 36) + self._wifi_medium_txt = gui_app.texture("icons_mici/settings/network/wifi_strength_medium.png", 48, 36) + self._wifi_full_txt = gui_app.texture("icons_mici/settings/network/wifi_strength_full.png", 48, 36) + self._lock_txt = gui_app.texture("icons_mici/settings/network/new/lock.png", 21, 27) + + self._network: Network = network + self._network_missing = False # if network disappeared from scan results + + def update_network(self, network: Network): + self._network = network + + def set_network_missing(self, missing: bool): + self._network_missing = missing + + @staticmethod + def get_strength_icon_idx(strength: int) -> int: + return round(strength / 100 * 2) + + def _render(self, _): + # Determine which wifi strength icon to use + strength = self.get_strength_icon_idx(self._network.strength) + if self._network_missing: + strength_icon = self._wifi_slash_txt + elif strength == 2: + strength_icon = self._wifi_full_txt + elif strength == 1: + strength_icon = self._wifi_medium_txt + else: + strength_icon = self._wifi_low_txt + + rl.draw_texture_ex(strength_icon, (self._rect.x, self._rect.y + self._rect.height - strength_icon.height), 0.0, 1.0, rl.WHITE) + + # Render lock icon at lower right of wifi icon if secured + if self._network.security_type not in (SecurityType.OPEN, SecurityType.UNSUPPORTED): + lock_x = self._rect.x + self._rect.width - self._lock_txt.width + lock_y = self._rect.y + self._rect.height - self._lock_txt.height + 6 + rl.draw_texture_ex(self._lock_txt, (lock_x, lock_y), 0.0, 1.0, rl.WHITE) + + +class WifiButton(BigButton): + LABEL_PADDING = 98 + LABEL_WIDTH = 402 - 98 - 28 # button width - left padding - right padding + SUB_LABEL_WIDTH = 402 - BigButton.LABEL_HORIZONTAL_PADDING * 2 + + def __init__(self, network: Network, wifi_manager: WifiManager): + super().__init__(normalize_ssid(network.ssid), scroll=True) + + self._network = network + self._wifi_manager = wifi_manager + + self._wifi_icon = WifiIcon(network) + self._forget_btn = ForgetButton(self._forget_network) + self._check_txt = gui_app.texture("icons_mici/setup/driver_monitoring/dm_check.png", 32, 32) + + # Eager state (not sourced from Network) + self._network_missing = False + self._network_forgetting = False + self._wrong_password = False + + def update_network(self, network: Network): + self._network = network + self._wifi_icon.update_network(network) + + # We can assume network is not missing if got new Network + self._network_missing = False + self._wifi_icon.set_network_missing(False) + if self._is_connected or self._is_connecting: + self._wrong_password = False + + @property + def network_forgetting(self) -> bool: + return self._network_forgetting + + def _forget_network(self): + if self._network_forgetting: + return + + self._network_forgetting = True + self._wifi_manager.forget_connection(self._network.ssid) + + def on_forgotten(self): + self._network_forgetting = False + + def set_network_missing(self, missing: bool): + self._network_missing = missing + self._wifi_icon.set_network_missing(missing) + + def set_wrong_password(self): + self._wrong_password = True + self.trigger_shake() + + @property + def network(self) -> Network: + return self._network + + @property + def _show_forget_btn(self): + if self._network.is_tethering or self._network_forgetting: + return False + + return (self._is_saved and not self._wrong_password) or self._is_connecting + + def _handle_mouse_release(self, mouse_pos: MousePos): + if self._show_forget_btn and rl.check_collision_point_rec(mouse_pos, self._forget_btn.rect): + return + super()._handle_mouse_release(mouse_pos) + + def _get_label_font_size(self): + return 48 + + def _draw_content(self, btn_y: float): + self._label.set_color(LABEL_COLOR) + label_rect = rl.Rectangle(self._rect.x + self.LABEL_PADDING, btn_y + self.LABEL_VERTICAL_PADDING, + self.LABEL_WIDTH, self._rect.height - self.LABEL_VERTICAL_PADDING * 2) + self._label.render(label_rect) + + if self.value: + sub_label_x = self._rect.x + self.LABEL_HORIZONTAL_PADDING + label_y = btn_y + self._rect.height - self.LABEL_VERTICAL_PADDING + sub_label_w = self.SUB_LABEL_WIDTH - (self._forget_btn.rect.width if self._show_forget_btn else 0) + sub_label_height = self._sub_label.get_content_height(sub_label_w) + + if self._is_connected and not self._network_forgetting: + check_y = int(label_y - sub_label_height + (sub_label_height - self._check_txt.height) / 2) + rl.draw_texture_ex(self._check_txt, rl.Vector2(sub_label_x, check_y), 0.0, 1.0, rl.Color(255, 255, 255, int(255 * 0.9 * 0.65))) + sub_label_x += self._check_txt.width + 14 + + sub_label_rect = rl.Rectangle(sub_label_x, label_y - sub_label_height, sub_label_w, sub_label_height) + self._sub_label.render(sub_label_rect) + + # Wifi icon + self._wifi_icon.render(rl.Rectangle( + self._rect.x + 30, + btn_y + 30, + self._wifi_icon.rect.width, + self._wifi_icon.rect.height, + )) + + # Forget button + if self._show_forget_btn: + self._forget_btn.render(rl.Rectangle( + self._rect.x + self._rect.width - self._forget_btn.rect.width, + btn_y + self._rect.height - self._forget_btn.rect.height, + self._forget_btn.rect.width, + self._forget_btn.rect.height, + )) + + def set_touch_valid_callback(self, touch_callback: Callable[[], bool]) -> None: + super().set_touch_valid_callback(lambda: touch_callback() and not self._forget_btn.is_pressed) + self._forget_btn.set_touch_valid_callback(touch_callback) + + @property + def _is_saved(self): + return self._wifi_manager.is_connection_saved(self._network.ssid) + + @property + def _is_connecting(self): + return self._wifi_manager.connecting_to_ssid == self._network.ssid + + @property + def _is_connected(self): + return self._wifi_manager.connected_ssid == self._network.ssid + + def _update_state(self): + super()._update_state() + + if any((self._network_missing, self._is_connecting, self._is_connected, self._network_forgetting, + self._network.security_type == SecurityType.UNSUPPORTED)): + self.set_enabled(False) + self._sub_label.set_color(rl.Color(255, 255, 255, int(255 * 0.585))) + self._sub_label.set_font_weight(FontWeight.ROMAN) + + if self._network_forgetting: + self.set_value("forgetting...") + elif self._is_connecting: + self.set_value("starting..." if self._network.is_tethering else "connecting...") + elif self._is_connected: + self.set_value("tethering" if self._network.is_tethering else "connected") + elif self._network_missing: + # after connecting/connected since NM will still attempt to connect/stay connected for a while + self.set_value("not in range") + else: + self.set_value("unsupported") + + else: # saved, wrong password, or unknown + self.set_value("wrong password" if self._wrong_password else "connect") + self.set_enabled(True) + self._sub_label.set_color(rl.Color(255, 255, 255, int(255 * 0.9))) + self._sub_label.set_font_weight(FontWeight.SEMI_BOLD) + + +class ForgetButton(Widget): + MARGIN = 12 # bottom and right + + def __init__(self, forget_network: Callable): + super().__init__() + self._forget_network = forget_network + + self._bg_txt = gui_app.texture("icons_mici/settings/network/new/forget_button.png", 84, 84) + self._bg_pressed_txt = gui_app.texture("icons_mici/settings/network/new/forget_button_pressed.png", 84, 84) + self._trash_txt = gui_app.texture("icons_mici/settings/network/new/trash.png", 29, 35) + self.set_rect(rl.Rectangle(0, 0, 84 + self.MARGIN * 2, 84 + self.MARGIN * 2)) + + def _handle_mouse_release(self, mouse_pos: MousePos): + super()._handle_mouse_release(mouse_pos) + dlg = BigConfirmationDialog("slide to forget", gui_app.texture("icons_mici/settings/network/new/trash.png", 54, 64), self._forget_network, red=True) + gui_app.push_widget(dlg) + + def _render(self, _): + bg_txt = self._bg_pressed_txt if self.is_pressed else self._bg_txt + rl.draw_texture_ex(bg_txt, (self._rect.x + (self._rect.width - self._bg_txt.width) / 2, + self._rect.y + (self._rect.height - self._bg_txt.height) / 2), 0, 1.0, rl.WHITE) + + trash_x = self._rect.x + (self._rect.width - self._trash_txt.width) / 2 + trash_y = self._rect.y + (self._rect.height - self._trash_txt.height) / 2 + rl.draw_texture_ex(self._trash_txt, (trash_x, trash_y), 0, 1.0, rl.WHITE) + + +class ScanningButton(BigButton): + def __init__(self): + super().__init__("", "searching for networks") + self.set_enabled(False) + self._loading_animation = LoadingAnimation() + + def _draw_content(self, btn_y: float): + super()._draw_content(btn_y) + anim = self._loading_animation + x = self._rect.x + self._rect.width - anim.rect.width - 40 + y = btn_y + self._rect.height - anim.rect.height - 30 + anim.set_position(x, y) + anim.render() + + +class WifiUIMici(NavScroller): + def __init__(self, wifi_manager: WifiManager): + super().__init__() + + self._scanning_btn = ScanningButton() + + self._wifi_manager = wifi_manager + self._networks: dict[str, Network] = {} + + self._wifi_manager.add_callbacks( + need_auth=self._on_need_auth, + forgotten=self._on_forgotten, + networks_updated=self._on_network_updated, + ) + + @property + def any_network_forgetting(self) -> bool: + # TODO: deactivate before forget and add DISCONNECTING state + return any(btn.network_forgetting for btn in self._scroller.items if isinstance(btn, WifiButton)) + + def show_event(self): + # Re-sort scroller items and update from latest scan results + super().show_event() + self._wifi_manager.set_active(True) + self._networks = {n.ssid: n for n in self._wifi_manager.networks} + self._update_buttons(re_sort=True) + + def _on_network_updated(self, networks: list[Network]): + self._networks = {network.ssid: network for network in networks} + self._update_buttons() + + def _update_buttons(self, re_sort: bool = False): + # Update existing buttons, add new ones to the end + existing = {btn.network.ssid: btn for btn in self._scroller.items if isinstance(btn, WifiButton)} + + for network in self._networks.values(): + if network.ssid in existing: + existing[network.ssid].update_network(network) + else: + btn = WifiButton(network, self._wifi_manager) + btn.set_click_callback(lambda ssid=network.ssid: self._connect_to_network(ssid)) + self._scroller.add_widget(btn) + + if re_sort: + # Remove stale buttons and sort to match scan order, preserving eager state + btn_map = {btn.network.ssid: btn for btn in self._scroller.items if isinstance(btn, WifiButton)} + self._scroller.items[:] = [btn_map[ssid] for ssid in self._networks if ssid in btn_map] + else: + # Mark networks no longer in scan results (display handled by _update_state) + for btn in self._scroller.items: + if isinstance(btn, WifiButton) and btn.network.ssid not in self._networks: + btn.set_network_missing(True) + + # Keep scanning button at the end + items = self._scroller.items + if self._scanning_btn in items: + items.append(items.pop(items.index(self._scanning_btn))) + else: + self._scroller.add_widget(self._scanning_btn) + + def _connect_with_password(self, ssid: str, password: str): + self._wifi_manager.connect_to_network(ssid, password) + self._move_network_to_front(ssid, scroll=True) + + def _connect_to_network(self, ssid: str): + network = self._networks.get(ssid) + if network is None: + cloudlog.warning(f"Trying to connect to unknown network: {ssid}") + return + + if self._wifi_manager.is_connection_saved(network.ssid): + self._wifi_manager.activate_connection(network.ssid) + elif network.security_type == SecurityType.OPEN: + self._wifi_manager.connect_to_network(network.ssid, "") + else: + self._on_need_auth(network.ssid, False) + return + + self._move_network_to_front(ssid, scroll=True) + + def _on_need_auth(self, ssid, incorrect_password=True): + if incorrect_password: + for btn in self._scroller.items: + if isinstance(btn, WifiButton) and btn.network.ssid == ssid: + btn.set_wrong_password() + break + return + + dlg = BigInputDialog("enter password...", "", minimum_length=8, + confirm_callback=lambda _password: self._connect_with_password(ssid, _password)) + gui_app.push_widget(dlg) + + def _on_forgotten(self, ssid): + # For eager UI forget + for btn in self._scroller.items: + if isinstance(btn, WifiButton) and btn.network.ssid == ssid: + btn.on_forgotten() + + def _move_network_to_front(self, ssid: str | None, scroll: bool = False): + # Move connecting/connected network to the front with animation + front_btn_idx = next((i for i, btn in enumerate(self._scroller.items) + if isinstance(btn, WifiButton) and + btn.network.ssid == ssid), None) if ssid else None + + if front_btn_idx is not None and front_btn_idx > 0: + self._scroller.move_item(front_btn_idx, 0) + + if scroll: + # Scroll to the new position of the network + self._scroller.scroll_to(self._scroller.scroll_panel.get_offset(), smooth=True, block_widget_interaction=True) + + def _update_state(self): + super()._update_state() + + self._move_network_to_front(self._wifi_manager.wifi_state.ssid) diff --git a/openpilot/selfdrive/ui/mici/layouts/settings/settings.py b/openpilot/selfdrive/ui/mici/layouts/settings/settings.py new file mode 100644 index 0000000000..56a953a65d --- /dev/null +++ b/openpilot/selfdrive/ui/mici/layouts/settings/settings.py @@ -0,0 +1,58 @@ +from openpilot.common.params import Params +from openpilot.system.ui.widgets.scroller import NavScroller +from openpilot.selfdrive.ui.mici.widgets.button import BigButton +from openpilot.selfdrive.ui.mici.layouts.settings.toggles import TogglesLayoutMici +from openpilot.selfdrive.ui.mici.layouts.settings.network.network_layout import NetworkLayoutMici +from openpilot.selfdrive.ui.mici.layouts.settings.device import DeviceLayoutMici, PairBigButton +from openpilot.selfdrive.ui.mici.layouts.settings.developer import DeveloperLayoutMici +from openpilot.selfdrive.ui.mici.layouts.settings.software import SoftwareLayoutMici +from openpilot.selfdrive.ui.mici.layouts.settings.firehose import FirehoseLayout +from openpilot.system.ui.lib.application import gui_app, FontWeight + + +class SettingsBigButton(BigButton): + def _get_label_font_size(self): + return 64 + + +class SettingsLayout(NavScroller): + def __init__(self): + super().__init__() + self._params = Params() + + toggles_panel = TogglesLayoutMici() + toggles_btn = SettingsBigButton("toggles", "", gui_app.texture("icons_mici/settings.png", 64, 64)) + toggles_btn.set_click_callback(lambda: gui_app.push_widget(toggles_panel)) + + network_panel = NetworkLayoutMici() + network_btn = SettingsBigButton("network", "", gui_app.texture("icons_mici/settings/network/wifi_strength_full.png", 76, 56)) + network_btn.set_click_callback(lambda: gui_app.push_widget(network_panel)) + + device_panel = DeviceLayoutMici() + device_btn = SettingsBigButton("device", "", gui_app.texture("icons_mici/settings/device_icon.png", 72, 58)) + device_btn.set_click_callback(lambda: gui_app.push_widget(device_panel)) + + software_panel = SoftwareLayoutMici() + software_btn = SettingsBigButton("software", "", gui_app.texture("icons_mici/settings/software.png", 64, 75)) + software_btn.set_click_callback(lambda: gui_app.push_widget(software_panel)) + + developer_panel = DeveloperLayoutMici() + developer_btn = SettingsBigButton("developer", "", gui_app.texture("icons_mici/settings/developer_icon.png", 64, 60)) + developer_btn.set_click_callback(lambda: gui_app.push_widget(developer_panel)) + + firehose_panel = FirehoseLayout() + firehose_btn = SettingsBigButton("firehose", "", gui_app.texture("icons_mici/settings/firehose.png", 52, 62)) + firehose_btn.set_click_callback(lambda: gui_app.push_widget(firehose_panel)) + + self._scroller.add_widgets([ + toggles_btn, + network_btn, + device_btn, + software_btn, + PairBigButton(), + #BigDialogButton("manual", "", "icons_mici/settings/manual_icon.png", "Check out the mici user\nmanual at comma.ai/setup"), + firehose_btn, + developer_btn, + ]) + + self._font_medium = gui_app.font(FontWeight.MEDIUM) diff --git a/openpilot/selfdrive/ui/mici/layouts/settings/software.py b/openpilot/selfdrive/ui/mici/layouts/settings/software.py new file mode 100644 index 0000000000..d71982ca26 --- /dev/null +++ b/openpilot/selfdrive/ui/mici/layouts/settings/software.py @@ -0,0 +1,274 @@ +import subprocess +import threading +import pyray as rl +from enum import IntEnum +from collections.abc import Callable + +from openpilot.common.time_helpers import system_time_valid +from openpilot.selfdrive.ui.mici.layouts.settings.device import EngagedConfirmationButton +from openpilot.selfdrive.ui.mici.widgets.button import BigButton +from openpilot.selfdrive.ui.mici.widgets.dialog import BigDialog +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.ui.lib.application import gui_app, FontWeight, MousePos +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.label import UnifiedLabel +from openpilot.system.ui.widgets.scroller import NavScroller + +UPDATER_TIMEOUT = 10.0 # seconds to wait for updater to respond + + +def _split_description(desc: str) -> tuple[str, str, str, str] | None: + # UpdaterCurrentDescription/UpdaterNewDescription format: "version / branch / commit / date" + parts = [p.strip() for p in desc.split(" / ")] + if len(parts) != 4: + return None + version, branch, commit, date = parts + return version, branch, commit, date + + +class UpdaterState(IntEnum): + IDLE = 0 + WAITING_FOR_UPDATER = 1 + UPDATER_RESPONDING = 2 + + +class SoftwareInfoLayoutMici(Widget): + def __init__(self): + super().__init__() + + self.set_rect(rl.Rectangle(0, 0, 360, 180)) + + subheader_color = rl.Color(255, 255, 255, int(255 * 0.9 * 0.65)) + max_width = int(self._rect.width - 20) + self._version_label = UnifiedLabel("version", 48, max_width=max_width, font_weight=FontWeight.DISPLAY, wrap_text=False) + self._version_text_label = UnifiedLabel("", 32, max_width=max_width, text_color=subheader_color, + font_weight=FontWeight.ROMAN, wrap_text=False) + + self._branch_label = UnifiedLabel("branch", 48, max_width=max_width, font_weight=FontWeight.DISPLAY, wrap_text=False) + self._branch_text_label = UnifiedLabel("", 32, max_width=max_width, text_color=subheader_color, + font_weight=FontWeight.ROMAN, wrap_text=False) + + def _update_state(self): + desc = _split_description(ui_state.params.get("UpdaterCurrentDescription") or "") + if desc is not None: + version, branch, commit, date = desc + self._version_text_label.set_text(f"{version} ({date})") + self._branch_text_label.set_text(f"{branch} ({commit})") + else: + self._version_text_label.set_text(ui_state.params.get("Version") or "N/A") + self._branch_text_label.set_text(ui_state.params.get("GitBranch") or "N/A") + + def _render(self, _): + self._version_label.set_position(self._rect.x + 20, self._rect.y - 10) + self._version_label.render() + + self._version_text_label.set_position(self._rect.x + 20, self._rect.y + 68 - 25) + self._version_text_label.render() + + self._branch_label.set_position(self._rect.x + 20, self._rect.y + 114 - 30) + self._branch_label.render() + + self._branch_text_label.set_position(self._rect.x + 20, self._rect.y + 161 - 25) + self._branch_text_label.render() + + +class CheckUpdateButton(BigButton): + def __init__(self): + self._txt_update_icon = gui_app.texture("icons_mici/settings/device/update.png", 64, 75) + self._txt_up_to_date_icon = gui_app.texture("icons_mici/settings/device/up_to_date.png", 64, 64) + super().__init__("check for update", "", self._txt_update_icon) + + self._waiting_for_updater_t: float | None = None + self._hide_value_t: float | None = None + self._state: UpdaterState = UpdaterState.IDLE + + ui_state.add_offroad_transition_callback(self.offroad_transition) + + def offroad_transition(self): + if ui_state.is_offroad(): + self.set_enabled(True) + + def _handle_mouse_release(self, mouse_pos: MousePos): + super()._handle_mouse_release(mouse_pos) + + if not system_time_valid(): + dlg = BigDialog("", tr("Please connect to Wi-Fi to update.")) + gui_app.push_widget(dlg) + return + + self.set_enabled(False) + self._state = UpdaterState.WAITING_FOR_UPDATER + self.set_icon(self._txt_update_icon) + + def run(): + if self.get_value() == "download update": + subprocess.run("pkill -SIGHUP -f openpilot.system.updated.updated", shell=True) + else: + subprocess.run("pkill -SIGUSR1 -f openpilot.system.updated.updated", shell=True) + + threading.Thread(target=run, daemon=True).start() + + def set_value(self, value: str): + super().set_value(value) + if value: + self.set_text("") + else: + self.set_text("check for update") + + def _update_state(self): + super()._update_state() + + if ui_state.started: + self.set_enabled(False) + return + + updater_state = ui_state.params.get("UpdaterState") or "" + failed_count = ui_state.params.get("UpdateFailedCount") or 0 + failed = int(failed_count) > 0 + + if self._state == UpdaterState.WAITING_FOR_UPDATER: + self.set_rotate_icon(True) + if updater_state != "idle": + self._state = UpdaterState.UPDATER_RESPONDING + + # Recover from updater not responding (time invalid shortly after boot) + if self._waiting_for_updater_t is None: + self._waiting_for_updater_t = rl.get_time() + + if self._waiting_for_updater_t is not None and rl.get_time() - self._waiting_for_updater_t > UPDATER_TIMEOUT: + self.set_rotate_icon(False) + self.set_value("updater failed\nto respond") + self._state = UpdaterState.IDLE + self._hide_value_t = rl.get_time() + + elif self._state == UpdaterState.UPDATER_RESPONDING: + if updater_state == "idle": + self.set_rotate_icon(False) + self._state = UpdaterState.IDLE + self._hide_value_t = rl.get_time() + else: + if self.get_value() != updater_state: + self.set_value(updater_state) + + elif self._state == UpdaterState.IDLE: + self.set_rotate_icon(False) + if failed: + self.set_enabled(True) # allow retry when failure came from updater param + if self.get_value() != "failed to update": + self.set_value("failed to update") + + elif ui_state.params.get_bool("UpdaterFetchAvailable"): + self.set_enabled(True) + if self.get_value() != "download update": + self.set_value("download update") + + elif self._hide_value_t is not None: + self.set_enabled(True) + if self.get_value() == "checking...": + self.set_value("up to date") + self.set_icon(self._txt_up_to_date_icon) + + # Hide previous text after short amount of time (up to date or failed) + if rl.get_time() - self._hide_value_t > 3.0: + self._hide_value_t = None + self.set_value("") + self.set_icon(self._txt_update_icon) + else: + if self.get_value() != "": + self.set_value("") + + if self._state != UpdaterState.WAITING_FOR_UPDATER: + self._waiting_for_updater_t = None + + +class InstallUpdateButton(BigButton): + def __init__(self): + super().__init__("install update", "", gui_app.texture("icons_mici/settings/device/reboot.png", 64, 70)) + self.set_visible(lambda: ui_state.is_offroad() and ui_state.params.get_bool("UpdateAvailable")) + + def _update_state(self): + super()._update_state() + + desc = _split_description(ui_state.params.get("UpdaterNewDescription") or "") + value = f"{desc[0]} ({desc[1]})" if desc is not None else "" + if self.get_value() != value: + self.set_value(value) + + def _handle_mouse_release(self, mouse_pos: MousePos): + super()._handle_mouse_release(mouse_pos) + + self.set_enabled(False) + + def run(): + ui_state.params.put_bool("DoReboot", True, block=True) + + threading.Thread(target=run, daemon=True).start() + + +class BranchSelectPage(NavScroller): + def __init__(self, on_select: Callable[[str], None]): + super().__init__() + + params = ui_state.params + current_git_branch = params.get("GitBranch") or "" + branches_str = params.get("UpdaterAvailableBranches") or "" + branches = [b for b in branches_str.split(",") if b] + + for b in [current_git_branch, "devel-staging", "devel", "nightly", "nightly-dev", "master"]: + if b in branches: + branches.remove(b) + branches.insert(0, b) + + current_target = params.get("UpdaterTargetBranch") or "" + check_icon = gui_app.texture("icons_mici/settings/device/up_to_date.png", 64, 64) + + buttons = [] + for branch in branches: + btn = BigButton(branch, "", check_icon if branch == current_target else None, scroll=True) + btn.set_click_callback(lambda b=branch: self.dismiss(lambda: on_select(b))) + buttons.append(btn) + self._scroller.add_widgets(buttons) + + +class TargetBranchButton(BigButton): + def __init__(self): + super().__init__("target branch", ui_state.params.get("UpdaterTargetBranch") or "") + self.set_click_callback(self._on_click) + self.set_visible(not ui_state.params.get_bool("IsTestedBranch")) + self.set_enabled(lambda: ui_state.is_offroad()) + + def _update_state(self): + super()._update_state() + + target = ui_state.params.get("UpdaterTargetBranch") or "" + if self.get_value() != target: + self.set_value(target) + + def _on_click(self): + gui_app.push_widget(BranchSelectPage(self._on_select)) + + def _on_select(self, branch: str): + ui_state.params.put("UpdaterTargetBranch", branch, block=True) + self.set_value(branch) + subprocess.run("pkill -SIGUSR1 -f openpilot.system.updated.updated", shell=True) + + +class SoftwareLayoutMici(NavScroller): + def __init__(self): + super().__init__() + + def uninstall_openpilot_callback(): + ui_state.params.put_bool("DoUninstall", True, block=True) + + uninstall_openpilot_btn = EngagedConfirmationButton("uninstall sunnypilot", "uninstall", + gui_app.texture("icons_mici/settings/device/uninstall.png", 64, 64), + uninstall_openpilot_callback, exit_on_confirm=False) + + self._scroller.add_widgets([ + SoftwareInfoLayoutMici(), + CheckUpdateButton(), + InstallUpdateButton(), + TargetBranchButton(), + uninstall_openpilot_btn, + ]) diff --git a/openpilot/selfdrive/ui/mici/layouts/settings/toggles.py b/openpilot/selfdrive/ui/mici/layouts/settings/toggles.py new file mode 100644 index 0000000000..52bbb65e6a --- /dev/null +++ b/openpilot/selfdrive/ui/mici/layouts/settings/toggles.py @@ -0,0 +1,87 @@ +from openpilot.cereal import log + +from openpilot.system.ui.widgets.scroller import NavScroller +from openpilot.selfdrive.ui.mici.widgets.button import BigParamControl, BigMultiParamToggle +from openpilot.system.ui.lib.application import gui_app +from openpilot.selfdrive.ui.layouts.settings.common import restart_needed_callback +from openpilot.selfdrive.ui.ui_state import ui_state + +PERSONALITY_TO_INT = log.LongitudinalPersonality.schema.enumerants + + +class TogglesLayoutMici(NavScroller): + def __init__(self): + super().__init__() + + self._personality_toggle = BigMultiParamToggle("driving personality", "LongitudinalPersonality", ["aggressive", "standard", "relaxed"]) + self._experimental_btn = BigParamControl("experimental mode", "ExperimentalMode") + is_metric_toggle = BigParamControl("use metric units", "IsMetric") + ldw_toggle = BigParamControl("lane departure warnings", "IsLdwEnabled") + always_on_dm_toggle = BigParamControl("always-on driver monitor", "AlwaysOnDM") + record_front = BigParamControl("record & upload driver camera", "RecordFront", toggle_callback=restart_needed_callback) + record_mic = BigParamControl("record & upload mic audio", "RecordAudio", toggle_callback=restart_needed_callback) + enable_openpilot = BigParamControl("enable sunnypilot", "OpenpilotEnabledToggle", toggle_callback=restart_needed_callback) + + self._scroller.add_widgets([ + self._personality_toggle, + self._experimental_btn, + is_metric_toggle, + ldw_toggle, + always_on_dm_toggle, + record_front, + record_mic, + enable_openpilot, + ]) + + # Toggle lists + self._refresh_toggles = ( + ("ExperimentalMode", self._experimental_btn), + ("IsMetric", is_metric_toggle), + ("IsLdwEnabled", ldw_toggle), + ("AlwaysOnDM", always_on_dm_toggle), + ("RecordFront", record_front), + ("RecordAudio", record_mic), + ("OpenpilotEnabledToggle", enable_openpilot), + ) + + enable_openpilot.set_enabled(lambda: not ui_state.engaged) + record_front.set_enabled(False if ui_state.params.get_bool("RecordFrontLock") else (lambda: not ui_state.engaged)) + record_mic.set_enabled(lambda: not ui_state.engaged) + + if ui_state.params.get_bool("ShowDebugInfo"): + gui_app.set_show_touches(True) + gui_app.set_show_fps(True) + + ui_state.add_engaged_transition_callback(self._update_toggles) + + def _update_state(self): + super()._update_state() + + if ui_state.sm.updated["selfdriveState"]: + personality = PERSONALITY_TO_INT[ui_state.sm["selfdriveState"].personality] + if personality != ui_state.personality and ui_state.started: + self._personality_toggle.set_value(self._personality_toggle._options[personality]) + ui_state.personality = personality + + def show_event(self): + super().show_event() + self._update_toggles() + + def _update_toggles(self): + ui_state.update_params() + + # CP gating for experimental mode + if ui_state.CP is not None: + if ui_state.has_longitudinal_control: + self._experimental_btn.set_visible(True) + self._personality_toggle.set_visible(True) + else: + # no long for now + self._experimental_btn.set_visible(False) + self._experimental_btn.set_checked(False) + self._personality_toggle.set_visible(False) + ui_state.params.remove("ExperimentalMode") + + # Refresh toggles from params to mirror external changes + for key, item in self._refresh_toggles: + item.set_checked(ui_state.params.get_bool(key)) diff --git a/openpilot/selfdrive/ui/mici/onroad/__init__.py b/openpilot/selfdrive/ui/mici/onroad/__init__.py new file mode 100644 index 0000000000..bb45117b94 --- /dev/null +++ b/openpilot/selfdrive/ui/mici/onroad/__init__.py @@ -0,0 +1,12 @@ +import pyray as rl + +SIDE_PANEL_WIDTH = 60 + + +def blend_colors(a: rl.Color, b: rl.Color, f: float) -> rl.Color: + h0, s0, v0 = (hsv0 := rl.color_to_hsv(a)).x, hsv0.y, hsv0.z + h1, s1, v1 = (hsv1 := rl.color_to_hsv(b)).x, hsv1.y, hsv1.z + dh = ((h1 - h0 + 180) % 360) - 180 # shortest hue delta + return rl.color_from_hsv((h0 + f * dh) % 360, + s0 + f * (s1 - s0), + v0 + f * (v1 - v0)) diff --git a/openpilot/selfdrive/ui/mici/onroad/alert_renderer.py b/openpilot/selfdrive/ui/mici/onroad/alert_renderer.py new file mode 100644 index 0000000000..016e09a0f1 --- /dev/null +++ b/openpilot/selfdrive/ui/mici/onroad/alert_renderer.py @@ -0,0 +1,372 @@ +import time +from enum import StrEnum +from typing import NamedTuple +import pyray as rl +import random +import string +from dataclasses import dataclass +from openpilot.cereal import messaging, log +from opendbc.car.structs import car +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.common.filter_simple import BounceFilter, FirstOrderFilter +from openpilot.common.hardware import TICI +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.label import UnifiedLabel + +from openpilot.selfdrive.ui.sunnypilot.onroad.speed_limit import SpeedLimitAlertRenderer + +AlertSize = log.SelfdriveState.AlertSize +AlertStatus = log.SelfdriveState.AlertStatus + +ALERT_MARGIN = 18 + +ALERT_FONT_SMALL = 66 - 50 +ALERT_FONT_BIG = 88 - 40 + +SELFDRIVE_STATE_TIMEOUT = 5 # Seconds +SELFDRIVE_UNRESPONSIVE_TIMEOUT = 10 # Seconds + +# Constants +ALERT_COLORS = { + AlertStatus.normal: rl.Color(0, 0, 0, 255), + AlertStatus.userPrompt: rl.Color(255, 115, 0, 255), + AlertStatus.critical: rl.Color(255, 0, 21, 255), +} + +TURN_SIGNAL_BLINK_PERIOD = 1 / (80 / 60) # Mazda heartbeat turn signal BPM + +DEBUG = False + + +class IconSide(StrEnum): + left = 'left' + right = 'right' + + +class IconLayout(NamedTuple): + texture: rl.Texture + side: IconSide + margin_x: int + margin_y: int + alpha: float = 255.0 + + +class AlertLayout(NamedTuple): + text_rect: rl.Rectangle + icon: IconLayout | None + + +@dataclass +class Alert: + text1: str = "" + text2: str = "" + size: int = 0 + status: int = 0 + visual_alert: int = car.CarControl.HUDControl.VisualAlert.none + alert_type: str = "" + + +# Pre-defined alert instances +ALERT_STARTUP_PENDING = Alert( + text1="sunnypilot Unavailable", + text2="Waiting to start", + size=AlertSize.mid, + status=AlertStatus.normal, +) + +ALERT_CRITICAL_TIMEOUT = Alert( + text1="TAKE CONTROL IMMEDIATELY", + text2="System Unresponsive", + size=AlertSize.full, + status=AlertStatus.critical, +) + +ALERT_CRITICAL_REBOOT = Alert( + text1="System Unresponsive", + text2="Reboot Device", + size=AlertSize.full, + status=AlertStatus.critical, +) + + +class AlertRenderer(Widget, SpeedLimitAlertRenderer): + def __init__(self): + Widget.__init__(self) + SpeedLimitAlertRenderer.__init__(self) + + self._alert_text1_label = UnifiedLabel(text="", font_size=ALERT_FONT_BIG, font_weight=FontWeight.DISPLAY, line_height=0.86, + letter_spacing=-0.02) + self._alert_text2_label = UnifiedLabel(text="", font_size=ALERT_FONT_SMALL, font_weight=FontWeight.ROMAN, line_height=0.86, + letter_spacing=0.025) + + self._prev_alert: Alert | None = None + self._text_gen_time = 0 + self._alert_text2_gen = '' + + # animation filters + # TODO: use 0.1 but with proper alert height calculation + self._alert_y_filter = BounceFilter(0, 0.1, 1 / gui_app.target_fps) + self._alpha_filter = FirstOrderFilter(0, 0.05, 1 / gui_app.target_fps) + + self._turn_signal_timer = 0.0 + self._turn_signal_alpha_filter = FirstOrderFilter(0.0, 0.3, 1 / gui_app.target_fps) + self._last_icon_side: IconSide | None = None + + self._load_icons() + + def _load_icons(self): + self._txt_turn_signal_left = gui_app.texture('icons_mici/onroad/turn_signal_left.png', 104, 96) + self._txt_turn_signal_right = gui_app.texture('icons_mici/onroad/turn_signal_left.png', 104, 96, flip_x=True) + self._txt_blind_spot_left = gui_app.texture('icons_mici/onroad/blind_spot_left.png', 134, 150) + self._txt_blind_spot_right = gui_app.texture('icons_mici/onroad/blind_spot_left.png', 134, 150, flip_x=True) + + def get_alert(self, sm: messaging.SubMaster) -> Alert | None: + """Generate the current alert based on selfdrive state.""" + ss = sm['selfdriveState'] + + # Check if selfdriveState messages have stopped arriving + if not sm.updated['selfdriveState']: + recv_frame = sm.recv_frame['selfdriveState'] + time_since_onroad = time.monotonic() - ui_state.started_time + + # 1. Never received selfdriveState since going onroad + waiting_for_startup = recv_frame < ui_state.started_frame + if waiting_for_startup and time_since_onroad > 5: + return ALERT_STARTUP_PENDING + + # 2. Lost communication with selfdriveState after receiving it + if TICI and not waiting_for_startup: + ss_missing = time.monotonic() - sm.recv_time['selfdriveState'] + if ss_missing > SELFDRIVE_STATE_TIMEOUT: + if ss.enabled and (ss_missing - SELFDRIVE_STATE_TIMEOUT) < SELFDRIVE_UNRESPONSIVE_TIMEOUT: + return ALERT_CRITICAL_TIMEOUT + return ALERT_CRITICAL_REBOOT + + # No alert if size is none + if ss.alertSize == 0: + return None + + # Return current alert + ret = Alert(text1=ss.alertText1, text2=ss.alertText2, size=ss.alertSize.raw, status=ss.alertStatus.raw, + visual_alert=ss.alertHudVisual, alert_type=ss.alertType) + self._prev_alert = ret + return ret + + def will_render(self) -> tuple[Alert | None, bool]: + alert = self.get_alert(ui_state.sm) + return alert or self._prev_alert, alert is None + + def _icon_helper(self, alert: Alert) -> AlertLayout: + icon_side = None + txt_icon = None + icon_alpha = 255.0 + icon_margin_x = 20 + icon_margin_y = 18 + + # alert_type format is "EventName/eventType" (e.g., "preLaneChangeLeft/warning") + event_name = alert.alert_type.split('/')[0] if alert.alert_type else '' + + if event_name == 'preLaneChangeLeft': + icon_side = IconSide.left + txt_icon = self._txt_turn_signal_left + icon_margin_x = 2 + icon_margin_y = 5 + + elif event_name == 'preLaneChangeRight': + icon_side = IconSide.right + txt_icon = self._txt_turn_signal_right + icon_margin_x = 2 + icon_margin_y = 5 + + elif event_name == 'laneChange': + icon_side = self._last_icon_side + txt_icon = self._txt_turn_signal_left if self._last_icon_side == 'left' else self._txt_turn_signal_right + icon_margin_x = 2 + icon_margin_y = 5 + + elif event_name == 'laneChangeBlocked': + CS = ui_state.sm['carState'] + if CS.leftBlinker: + icon_side = IconSide.left + elif CS.rightBlinker: + icon_side = IconSide.right + else: + icon_side = self._last_icon_side + txt_icon = self._txt_blind_spot_left if icon_side == 'left' else self._txt_blind_spot_right + icon_margin_x = 8 + icon_margin_y = 0 + + elif event_name == 'speedLimitPreActive': + icon_side, txt_icon, icon_alpha, icon_margin_x, icon_margin_y = SpeedLimitAlertRenderer.speed_limit_pre_active_icon_helper(self) + + else: + self._turn_signal_timer = 0.0 + + self._last_icon_side = icon_side + + # create text rect based on icon presence + text_x = self._rect.x + ALERT_MARGIN + text_width = self._rect.width - ALERT_MARGIN + if icon_side == 'left': + text_x = self._rect.x + self._txt_turn_signal_right.width + text_width = self._rect.width - ALERT_MARGIN - self._txt_turn_signal_right.width + elif icon_side == 'right': + text_x = self._rect.x + ALERT_MARGIN + text_width = self._rect.width - ALERT_MARGIN - self._txt_turn_signal_right.width + + text_rect = rl.Rectangle( + text_x, + self._alert_y_filter.x, + text_width, + self._rect.height, + ) + icon_layout = IconLayout(txt_icon, icon_side, icon_margin_x, icon_margin_y, icon_alpha) if txt_icon is not None and icon_side is not None else None + return AlertLayout(text_rect, icon_layout) + + def _render(self, rect: rl.Rectangle) -> bool: + alert = self.get_alert(ui_state.sm) + + # Animate fade and slide in/out + self._alert_y_filter.update(self._rect.y - 50 if alert is None else self._rect.y) + self._alpha_filter.update(0 if alert is None else 1) + + if gui_app.sunnypilot_ui(): + ui_state.onroad_brightness_handle_alerts(ui_state, alert) + + if alert is None: + # If still animating out, keep the previous alert + if self._alpha_filter.x > 0.01 and self._prev_alert is not None: + alert = self._prev_alert + else: + self._prev_alert = None + return False + + self._draw_background(alert) + + # update speed limit UI states + SpeedLimitAlertRenderer.update(self) + + alert_layout = self._icon_helper(alert) + self._draw_text(alert, alert_layout) + self._draw_icons(alert_layout) + + return True + + def _draw_icons(self, alert_layout: AlertLayout) -> None: + if alert_layout.icon is None: + return + + if time.monotonic() - self._turn_signal_timer > TURN_SIGNAL_BLINK_PERIOD: + self._turn_signal_timer = time.monotonic() + self._turn_signal_alpha_filter.x = 255 * 2 + else: + self._turn_signal_alpha_filter.update(255 * 0.2) + + if alert_layout.icon.side == 'left': + pos_x = int(self._rect.x + alert_layout.icon.margin_x) + else: + pos_x = int(self._rect.x + self._rect.width - alert_layout.icon.margin_x - alert_layout.icon.texture.width) + + if alert_layout.icon.texture not in (self._txt_turn_signal_left, self._txt_turn_signal_right): + icon_alpha = alert_layout.icon.alpha + else: + icon_alpha = int(min(self._turn_signal_alpha_filter.x, 255)) + + rl.draw_texture_ex(alert_layout.icon.texture, rl.Vector2(pos_x, self._rect.y + alert_layout.icon.margin_y), 0.0, 1.0, + rl.Color(255, 255, 255, int(icon_alpha * self._alpha_filter.x))) + + def _draw_background(self, alert: Alert) -> None: + # draw top gradient for alert text at top + color = ALERT_COLORS.get(alert.status, ALERT_COLORS[AlertStatus.normal]) + color = rl.Color(color.r, color.g, color.b, int(255 * 0.90 * self._alpha_filter.x)) + translucent_color = rl.Color(color.r, color.g, color.b, int(0 * self._alpha_filter.x)) + + small_alert_height = round(self._rect.height * 0.583) # 140px at mici height + medium_alert_height = round(self._rect.height * 0.833) # 200px at mici height + + # alert_type format is "EventName/eventType" (e.g., "preLaneChangeLeft/warning") + event_name = alert.alert_type.split('/')[0] if alert.alert_type else '' + + if event_name == 'preLaneChangeLeft': + bg_height = small_alert_height + elif event_name == 'preLaneChangeRight': + bg_height = small_alert_height + elif event_name == 'laneChange': + bg_height = small_alert_height + elif event_name == 'laneChangeBlocked': + bg_height = medium_alert_height + else: + bg_height = int(self._rect.height) + + solid_height = round(bg_height * 0.2) + rl.draw_rectangle(int(self._rect.x), int(self._rect.y), int(self._rect.width), solid_height, color) + rl.draw_rectangle_gradient_v(int(self._rect.x), int(self._rect.y + solid_height), int(self._rect.width), + int(bg_height - solid_height), + color, translucent_color) + + def _draw_text(self, alert: Alert, alert_layout: AlertLayout) -> None: + icon_side = alert_layout.icon.side if alert_layout.icon is not None else None + + # TODO: hack + alert_text1 = alert.text1.lower().replace('calibrating: ', 'calibrating:\n') + can_draw_second_line = False + # TODO: there should be a common way to determine font size based on text length to maximize rect + if len(alert_text1) <= 12: + can_draw_second_line = True + font_size = 92 - 10 + elif len(alert_text1) <= 16: + can_draw_second_line = True + font_size = 70 + else: + font_size = 64 - 10 + + if icon_side is not None: + font_size -= 10 + + color = rl.Color(255, 255, 255, int(255 * 0.9 * self._alpha_filter.x)) + + text1_y_offset = 11 if font_size >= 70 else 4 + text_rect1 = rl.Rectangle( + alert_layout.text_rect.x, + alert_layout.text_rect.y - text1_y_offset, + alert_layout.text_rect.width, + alert_layout.text_rect.height, + ) + self._alert_text1_label.set_text(alert_text1) + self._alert_text1_label.set_text_color(color) + self._alert_text1_label.set_font_size(font_size) + self._alert_text1_label.set_alignment(rl.GuiTextAlignment.TEXT_ALIGN_LEFT if icon_side != 'left' else rl.GuiTextAlignment.TEXT_ALIGN_RIGHT) + self._alert_text1_label.render(text_rect1) + + alert_text2 = alert.text2.lower() + + # randomize chars and length for testing + if DEBUG: + if time.monotonic() - self._text_gen_time > 0.5: + self._alert_text2_gen = ''.join(random.choices(string.ascii_lowercase + ' ', k=random.randint(0, 40))) + self._text_gen_time = time.monotonic() + alert_text2 = self._alert_text2_gen or alert_text2 + + if can_draw_second_line and alert_text2: + last_line_h = self._alert_text1_label.rect.y + self._alert_text1_label.get_content_height(int(alert_layout.text_rect.width)) + last_line_h -= 4 + if len(alert_text2) > 18: + small_font_size = 36 + elif len(alert_text2) > 24: + small_font_size = 32 + else: + small_font_size = 40 + text_rect2 = rl.Rectangle( + alert_layout.text_rect.x, + last_line_h, + alert_layout.text_rect.width, + alert_layout.text_rect.height - last_line_h + ) + color = rl.Color(255, 255, 255, int(255 * 0.65 * self._alpha_filter.x)) + + self._alert_text2_label.set_text(alert_text2) + self._alert_text2_label.set_text_color(color) + self._alert_text2_label.set_font_size(small_font_size) + self._alert_text2_label.set_alignment(rl.GuiTextAlignment.TEXT_ALIGN_LEFT if icon_side != 'left' else rl.GuiTextAlignment.TEXT_ALIGN_RIGHT) + self._alert_text2_label.render(text_rect2) diff --git a/openpilot/selfdrive/ui/mici/onroad/augmented_road_view.py b/openpilot/selfdrive/ui/mici/onroad/augmented_road_view.py new file mode 100644 index 0000000000..b5b9a54be8 --- /dev/null +++ b/openpilot/selfdrive/ui/mici/onroad/augmented_road_view.py @@ -0,0 +1,379 @@ +import numpy as np +import pyray as rl +from openpilot.cereal import log +from opendbc.car.structs import car +from msgq.visionipc import VisionStreamType +from openpilot.selfdrive.ui.ui_state import ui_state, UIStatus +from openpilot.selfdrive.ui.mici.onroad import SIDE_PANEL_WIDTH +from openpilot.selfdrive.ui.mici.onroad.alert_renderer import AlertRenderer +from openpilot.selfdrive.ui.mici.onroad.driver_state import DriverStateRenderer +from openpilot.selfdrive.ui.mici.onroad.hud_renderer import HudRenderer +from openpilot.selfdrive.ui.mici.onroad.model_renderer import ModelRenderer +from openpilot.selfdrive.ui.mici.onroad.confidence_ball import ConfidenceBall +from openpilot.selfdrive.ui.mici.onroad.cameraview import CameraView +from openpilot.system.ui.lib.application import FontWeight, gui_app, MousePos, MouseEvent +from openpilot.system.ui.widgets.label import UnifiedLabel +from openpilot.system.ui.widgets import Widget +from openpilot.common.filter_simple import BounceFilter +from openpilot.common.transformations.camera import DEVICE_CAMERAS, DeviceCameraConfig, view_frame_from_device_frame +from openpilot.common.transformations.orientation import rot_from_euler +from enum import IntEnum + +if gui_app.sunnypilot_ui(): + from openpilot.selfdrive.ui.sunnypilot.mici.onroad.hud_renderer import HudRendererSP as HudRenderer + from openpilot.selfdrive.ui.sunnypilot.ui_state import OnroadTimerStatus + +OpState = log.SelfdriveState.OpenpilotState +CALIBRATED = log.LiveCalibrationData.Status.calibrated +ROAD_CAM = VisionStreamType.VISION_STREAM_ROAD +WIDE_CAM = VisionStreamType.VISION_STREAM_WIDE_ROAD +DEFAULT_DEVICE_CAMERA = DEVICE_CAMERAS["tici", "ar0231"] + + +class BookmarkState(IntEnum): + HIDDEN = 0 + DRAGGING = 1 + TRIGGERED = 2 + +WIDE_CAM_MAX_SPEED = 5.0 # m/s (10 mph) +ROAD_CAM_MIN_SPEED = 10 # m/s (25 mph) + +CAM_Y_OFFSET = 20 + + +class BookmarkIcon(Widget): + PEEK_THRESHOLD = 50 # If icon peeks out this much, snap it fully visible + FULL_VISIBLE_OFFSET = 200 # How far onscreen when fully visible + HIDDEN_OFFSET = -50 # How far offscreen when hidden + + def __init__(self, bookmark_callback): + super().__init__() + self._bookmark_callback = bookmark_callback + self._icon = gui_app.texture("icons_mici/onroad/bookmark.png", 180, 180) + self._offset_filter = BounceFilter(0.0, 0.1, 1 / gui_app.target_fps) + + # State + self._interacting = False + self._state = BookmarkState.HIDDEN + self._swipe_start_x = 0.0 + self._swipe_current_x = 0.0 + self._is_swiping = False + self._is_swiping_left: bool = False + self._triggered_time: float = 0.0 + + def is_swiping_left(self) -> bool: + """Check if currently swiping left (for scroller to disable).""" + return self._is_swiping_left + + def interacting(self): + interacting, self._interacting = self._interacting, False + return interacting + + def _update_state(self): + if self._state == BookmarkState.DRAGGING: + # Allow pulling past activated position with rubber band effect + swipe_offset = self._swipe_start_x - self._swipe_current_x + swipe_offset = min(swipe_offset, self.FULL_VISIBLE_OFFSET + 50) + self._offset_filter.update(swipe_offset) + + elif self._state == BookmarkState.TRIGGERED: + # Continue animating to fully visible + self._offset_filter.update(self.FULL_VISIBLE_OFFSET) + # Stay in TRIGGERED state for 1 second + if rl.get_time() - self._triggered_time >= 1.5: + self._state = BookmarkState.HIDDEN + + elif self._state == BookmarkState.HIDDEN: + self._offset_filter.update(self.HIDDEN_OFFSET) + + if self._offset_filter.x < 1e-3: + self._interacting = False + + def _handle_mouse_event(self, mouse_event: MouseEvent): + if not ui_state.started: + return + + if mouse_event.left_pressed: + # Store relative position within widget + self._swipe_start_x = mouse_event.pos.x + self._swipe_current_x = mouse_event.pos.x + self._is_swiping = True + self._is_swiping_left = False + self._state = BookmarkState.DRAGGING + + elif mouse_event.left_down and self._is_swiping: + self._swipe_current_x = mouse_event.pos.x + swipe_offset = self._swipe_start_x - self._swipe_current_x + self._is_swiping_left = swipe_offset > 0 + if self._is_swiping_left: + self._interacting = True + + elif mouse_event.left_released: + if self._is_swiping: + swipe_distance = self._swipe_start_x - self._swipe_current_x + + # If peeking past threshold, transition to animating to fully visible and bookmark + if swipe_distance > self.PEEK_THRESHOLD: + self._state = BookmarkState.TRIGGERED + self._triggered_time = rl.get_time() + self._bookmark_callback() + else: + # Otherwise, transition back to hidden + self._state = BookmarkState.HIDDEN + + # Reset swipe state + self._is_swiping = False + self._is_swiping_left = False + + def _render(self, _): + """Render the bookmark icon.""" + if self._offset_filter.x > 0: + icon_x = self.rect.x + self.rect.width - round(self._offset_filter.x) + icon_y = self.rect.y + (self.rect.height - self._icon.height) / 2 # Vertically centered + rl.draw_texture_ex(self._icon, rl.Vector2(icon_x, icon_y), 0.0, 1.0, rl.WHITE) + + +class AugmentedRoadView(CameraView): + def __init__(self, bookmark_callback=None, stream_type: VisionStreamType = VisionStreamType.VISION_STREAM_ROAD): + super().__init__("camerad", stream_type) + self._bookmark_callback = bookmark_callback + self._set_placeholder_color(rl.BLACK) + + self.device_camera: DeviceCameraConfig | None = None + self.view_from_calib = view_frame_from_device_frame.copy() + self.view_from_wide_calib = view_frame_from_device_frame.copy() + + self._matrix_cache_key: tuple | None = None + self._cached_matrix: np.ndarray | None = None + self._content_rect = rl.Rectangle() + self._last_click_time = 0.0 + + # Bookmark icon with swipe gesture + self._bookmark_icon = BookmarkIcon(bookmark_callback) + + self._model_renderer = ModelRenderer() + self._hud_renderer = HudRenderer() + self._alert_renderer = AlertRenderer() + self._driver_state_renderer = DriverStateRenderer() + self._confidence_ball = ConfidenceBall() + self._offroad_label = UnifiedLabel("start the car to\nuse sunnypilot", 54, FontWeight.DISPLAY, + text_color=rl.Color(255, 255, 255, int(255 * 0.9)), + alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER, + alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE) + + self._fade_texture = gui_app.texture("icons_mici/onroad/onroad_fade.png") + + def is_swiping_left(self) -> bool: + """Check if currently swiping left (for scroller to disable).""" + return self._bookmark_icon.is_swiping_left() + + def _update_state(self): + super()._update_state() + + # update offroad label + if ui_state.panda_type == log.PandaState.PandaType.unknown: + self._offroad_label.set_text("system booting") + elif ui_state.ignition and not ui_state.started: + self._offroad_label.set_text("openpilot can't start\ncheck alerts") + else: + self._offroad_label.set_text("start the car to\nuse sunnypilot") + + def _handle_mouse_release(self, mouse_pos: MousePos): + # Don't trigger click callback if bookmark was triggered + if not self._bookmark_icon.interacting(): + super()._handle_mouse_release(mouse_pos) + + def _render(self, _): + # Draw text if not onroad + if not ui_state.started: + rl.draw_rectangle_rec(self.rect, rl.BLACK) + self._offroad_label.render(self._rect) + return + + self._switch_stream_if_needed(ui_state.sm) + + # Update calibration before rendering + self._update_calibration() + + # Create inner content area with border padding + self._content_rect = rl.Rectangle( + self.rect.x, + self.rect.y, + self.rect.width - SIDE_PANEL_WIDTH, + self.rect.height, + ) + + # Enable scissor mode to clip all rendering within content rectangle boundaries + # This creates a rendering viewport that prevents graphics from drawing outside the border + rl.begin_scissor_mode( + int(self._content_rect.x), + int(self._content_rect.y), + int(self._content_rect.width), + int(self._content_rect.height) + ) + + # Render the base camera view + super()._render(self._content_rect) + + # Draw all UI overlays + self._model_renderer.render(self._content_rect) + + # Fade out bottom of overlays for looks + rl.draw_texture_ex(self._fade_texture, rl.Vector2(self._content_rect.x, self._content_rect.y), 0.0, 1.0, rl.WHITE) + + alert_to_render, not_animating_out = self._alert_renderer.will_render() + + # Hide DMoji when disengaged unless AlwaysOnDM is enabled + should_draw_dmoji = (not self._hud_renderer.drawing_top_icons() and + (ui_state.status != UIStatus.DISENGAGED or ui_state.always_on_dm)) + self._driver_state_renderer.set_should_draw(should_draw_dmoji) + self._driver_state_renderer.set_position(self._rect.x + 16, self._rect.y + 10) + self._driver_state_renderer.render() + + self._hud_renderer.set_can_draw_top_icons(alert_to_render is None) + self._hud_renderer.set_wheel_critical_icon(alert_to_render is not None and not not_animating_out and + alert_to_render.visual_alert == car.CarControl.HUDControl.VisualAlert.steerRequired) + self._alert_renderer.render(self._content_rect) + self._hud_renderer.render(self._content_rect) + + # Draw fake rounded border + rl.draw_rectangle_rounded_lines_ex(self._content_rect, 0.2 * 1.02, 10, 50, rl.BLACK) + + # End clipping region + rl.end_scissor_mode() + + # Custom UI extension point - add custom overlays here + # Use self._content_rect for positioning within camera bounds + self._confidence_ball.render(self.rect) + + self._bookmark_icon.render(self.rect) + + def _switch_stream_if_needed(self, sm): + if sm['selfdriveState'].experimentalMode and WIDE_CAM in self.available_streams: + v_ego = sm['carState'].vEgo + if v_ego < WIDE_CAM_MAX_SPEED: + target = WIDE_CAM + elif v_ego > ROAD_CAM_MIN_SPEED: + target = ROAD_CAM + else: + # Hysteresis zone - keep current stream + target = self.stream_type + else: + target = ROAD_CAM + + if self.stream_type != target: + self.switch_stream(target) + + def _update_calibration(self): + # Update device camera if not already set + sm = ui_state.sm + if not self.device_camera and sm.seen['roadCameraState'] and sm.seen['deviceState']: + self.device_camera = DEVICE_CAMERAS[(str(sm['deviceState'].deviceType), str(sm['roadCameraState'].sensor))] + + # Check if live calibration data is available and valid + if not (sm.updated["liveCalibration"] and sm.valid['liveCalibration']): + return + + calib = sm['liveCalibration'] + if len(calib.rpyCalib) != 3 or calib.calStatus != CALIBRATED: + return + + # Update view_from_calib matrix + device_from_calib = rot_from_euler(calib.rpyCalib) + self.view_from_calib = view_frame_from_device_frame @ device_from_calib + + # Update wide calibration if available + if hasattr(calib, 'wideFromDeviceEuler') and len(calib.wideFromDeviceEuler) == 3: + wide_from_device = rot_from_euler(calib.wideFromDeviceEuler) + self.view_from_wide_calib = view_frame_from_device_frame @ wide_from_device @ device_from_calib + + def _calc_frame_matrix(self, rect: rl.Rectangle) -> np.ndarray: + cache_key = ( + ui_state.sm.recv_frame['liveCalibration'], + int(self._content_rect.width), + int(self._content_rect.height), + self.stream_type, + round(ui_state.sm['carState'].vEgo, 1), + ) + + if cache_key == self._matrix_cache_key and self._cached_matrix is not None: + return self._cached_matrix + + # Get camera configuration + device_camera = self.device_camera or DEFAULT_DEVICE_CAMERA + is_wide_camera = self.stream_type == WIDE_CAM + intrinsic = device_camera.ecam.intrinsics if is_wide_camera else device_camera.fcam.intrinsics + calibration = self.view_from_wide_calib if is_wide_camera else self.view_from_calib + if is_wide_camera: + zoom = 0.7 * 1.5 + else: + zoom = np.interp(ui_state.sm['carState'].vEgo, [10, 30], [0.8, 1.0]) + + # Calculate transforms for vanishing point + inf_point = np.array([1000.0, 0.0, 0.0]) + calib_transform = intrinsic @ calibration + kep = calib_transform @ inf_point + + # Calculate center points and dimensions + w, h = self._content_rect.width, self._content_rect.height + cx, cy = intrinsic[0, 2], intrinsic[1, 2] + + # Ensure zoom views the whole area + zoom = max(zoom, w / (2 * cx), h / (2 * cy)) + + # Calculate max allowed offsets with margins + margin = 5 + max_x_offset = max(0.0, cx * zoom - w / 2 - margin) + max_y_offset = max(0.0, cy * zoom - h / 2 - margin) + + # Calculate and clamp offsets to prevent out-of-bounds issues + try: + if abs(kep[2]) > 1e-6: + x_offset = np.clip((kep[0] / kep[2] - cx) * zoom, -max_x_offset, max_x_offset) + y_offset = np.clip((kep[1] / kep[2] - cy) * zoom + CAM_Y_OFFSET, -max_y_offset, max_y_offset) + else: + x_offset, y_offset = 0, 0 + except (ZeroDivisionError, OverflowError): + x_offset, y_offset = 0, 0 + + # Cache the computed transformation matrix to avoid recalculations + self._matrix_cache_key = cache_key + self._cached_matrix = np.array([ + [zoom * 2 * cx / w, 0, -x_offset / w * 2], + [0, zoom * 2 * cy / h, -y_offset / h * 2], + [0, 0, 1.0] + ]) + + # built without rect.x/y so cache stays hot during scroll. ModelRenderer adds offset at draw time + video_transform = np.array([ + [zoom, 0.0, (w / 2 - x_offset) - (cx * zoom)], + [0.0, zoom, (h / 2 - y_offset) - (cy * zoom)], + [0.0, 0.0, 1.0] + ]) + self._model_renderer.set_transform(video_transform @ calib_transform) + + return self._cached_matrix + + def show_event(self): + if gui_app.sunnypilot_ui(): + ui_state.reset_onroad_sleep_timer(OnroadTimerStatus.RESUME) + + def hide_event(self): + if gui_app.sunnypilot_ui(): + ui_state.reset_onroad_sleep_timer(OnroadTimerStatus.PAUSE) + + +if __name__ == "__main__": + gui_app.init_window("OnRoad Camera View") + road_camera_view = AugmentedRoadView(lambda: None, stream_type=ROAD_CAM) + print("***press space to switch camera view***") + try: + for _ in gui_app.render(): + ui_state.update() + if rl.is_key_released(rl.KeyboardKey.KEY_SPACE): + if WIDE_CAM in road_camera_view.available_streams: + stream = ROAD_CAM if road_camera_view.stream_type == WIDE_CAM else WIDE_CAM + road_camera_view.switch_stream(stream) + road_camera_view.render(rl.Rectangle(0, 0, gui_app.width, gui_app.height)) + finally: + road_camera_view.close() diff --git a/openpilot/selfdrive/ui/mici/onroad/cameraview.py b/openpilot/selfdrive/ui/mici/onroad/cameraview.py new file mode 100644 index 0000000000..82e4865c76 --- /dev/null +++ b/openpilot/selfdrive/ui/mici/onroad/cameraview.py @@ -0,0 +1,413 @@ +import platform +import numpy as np +import pyray as rl + +from msgq.visionipc import VisionIpcClient, VisionStreamType, VisionBuf +from openpilot.common.swaglog import cloudlog +from openpilot.common.hardware import TICI +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.lib.egl import init_egl, create_egl_image, destroy_egl_image, bind_egl_image_to_texture, EGLImage +from openpilot.system.ui.widgets import Widget +from openpilot.selfdrive.ui.ui_state import ui_state, UIStatus + +CONNECTION_RETRY_INTERVAL = 0.2 # seconds between connection attempts + +VERSION = """ +#version 300 es +precision mediump float; +""" +if platform.system() == "Darwin": + VERSION = """ + #version 330 core + """ + + +VERTEX_SHADER = VERSION + """ +in vec3 vertexPosition; +in vec2 vertexTexCoord; +in vec3 vertexNormal; +in vec4 vertexColor; +uniform mat4 mvp; +out vec2 fragTexCoord; +out vec4 fragColor; +void main() { + fragTexCoord = vertexTexCoord; + fragColor = vertexColor; + gl_Position = mvp * vec4(vertexPosition, 1.0); +} +""" + +# Choose fragment shader based on platform capabilities +if TICI: + FRAME_FRAGMENT_SHADER = """ + #version 300 es + #extension GL_OES_EGL_image_external_essl3 : enable + precision mediump float; + in vec2 fragTexCoord; + uniform samplerExternalOES texture0; + out vec4 fragColor; + uniform int engaged; + uniform int enhance_driver; + + void main() { + vec4 color = texture(texture0, fragTexCoord); + if (engaged == 1) { + float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114)); // Luma + color.rgb = mix(vec3(gray), color.rgb, 0.2); // 20% saturation + color.rgb = clamp((color.rgb - 0.5) * 1.2 + 0.5, 0.0, 1.0); // +20% contrast + color.rgb = pow(color.rgb, vec3(1.0/1.28)); + fragColor = vec4(color.rgb, color.a); + } else { + color.rgb *= 0.85; // 85% opacity + } + if (enhance_driver == 1) { + float brightness = 1.1; + color.rgb = color.rgb + 0.15; + color.rgb = clamp((color.rgb - 0.5) * (brightness * 0.8) + 0.5, 0.0, 1.0); + color.rgb = color.rgb * color.rgb * (3.0 - 2.0 * color.rgb); + color.rgb = pow(color.rgb, vec3(0.8)); + } + fragColor = vec4(color.rgb, color.a); + } + """ +else: + FRAME_FRAGMENT_SHADER = VERSION + """ + in vec2 fragTexCoord; + uniform sampler2D texture0; + uniform sampler2D texture1; + out vec4 fragColor; + uniform int engaged; + uniform int enhance_driver; + + void main() { + float y = texture(texture0, fragTexCoord).r; + vec2 uv = texture(texture1, fragTexCoord).ra - 0.5; + vec3 rgb = vec3(y + 1.402*uv.y, y - 0.344*uv.x - 0.714*uv.y, y + 1.772*uv.x); + if (engaged == 1) { + float gray = dot(rgb, vec3(0.299, 0.587, 0.114)); + rgb = mix(vec3(gray), rgb, 0.2); // 20% saturation + rgb = clamp((rgb - 0.5) * 1.2 + 0.5, 0.0, 1.0); // +20% contrast + } else { + rgb *= 0.85; // 85% opacity + } + // TODO: the images out of camerad need some more correction and + // the ui should apply a gamma curve for the device display + if (enhance_driver == 1) { + float brightness = 1.1; + rgb = rgb + 0.15; + rgb = clamp((rgb - 0.5) * (brightness * 0.8) + 0.5, 0.0, 1.0); + rgb = rgb * rgb * (3.0 - 2.0 * rgb); + rgb = pow(rgb, vec3(0.8)); + } + fragColor = vec4(rgb, 1.0); + } + """ + + +class CameraView(Widget): + def __init__(self, name: str, stream_type: VisionStreamType): + super().__init__() + self._name = name + # Primary stream + self.client = VisionIpcClient(name, stream_type, conflate=True) + self._stream_type = stream_type + self.available_streams: list[VisionStreamType] = [] + + # Target stream for switching + self._target_client: VisionIpcClient | None = None + self._target_stream_type: VisionStreamType | None = None + self._switching: bool = False + + self._texture_needs_update = True + self.last_connection_attempt: float = 0.0 + self.shader = rl.load_shader_from_memory(VERTEX_SHADER, FRAME_FRAGMENT_SHADER) + self._texture1_loc: int = rl.get_shader_location(self.shader, "texture1") if not TICI else -1 + self._engaged_loc = rl.get_shader_location(self.shader, "engaged") + self._engaged_val = rl.ffi.new("int[1]", [1]) + self._enhance_driver_loc = rl.get_shader_location(self.shader, "enhance_driver") + self._enhance_driver_val = rl.ffi.new("int[1]", [1 if stream_type == VisionStreamType.VISION_STREAM_DRIVER else 0]) + + self.frame: VisionBuf | None = None + self.texture_y: rl.Texture | None = None + self.texture_uv: rl.Texture | None = None + + # EGL resources + self.egl_images: dict[int, EGLImage] = {} + self.egl_texture: rl.Texture | None = None + + self._placeholder_color: rl.Color | None = None + + # Initialize EGL for zero-copy rendering on TICI + if TICI: + if not init_egl(): + raise RuntimeError("Failed to initialize EGL") + + # Create a 1x1 pixel placeholder texture for EGL image binding + temp_image = rl.gen_image_color(1, 1, rl.BLACK) + self.egl_texture = rl.load_texture_from_image(temp_image) + rl.unload_image(temp_image) + + ui_state.add_offroad_transition_callback(self._offroad_transition) + + def _offroad_transition(self): + # Drain queued SubSocket messages to prevent old frames from showing when going + # onroad. Qt had a separate thread which drains the VisionIpcClient SubSocket for us. + if self.client and self.client.is_connected(): + while self.client.recv(timeout_ms=0) is not None: + pass + self.frame = None + + def _set_placeholder_color(self, color: rl.Color): + """Set a placeholder color to be drawn when no frame is available.""" + self._placeholder_color = color + + def switch_stream(self, stream_type: VisionStreamType) -> None: + if self._stream_type == stream_type: + return + + if self._switching and self._target_stream_type == stream_type: + return + + cloudlog.debug(f'Preparing switch from {self._stream_type} to {stream_type}') + + if self._target_client: + del self._target_client + + self._target_stream_type = stream_type + self._target_client = VisionIpcClient(self._name, stream_type, conflate=True) + self._switching = True + + @property + def stream_type(self) -> VisionStreamType: + return self._stream_type + + def close(self) -> None: + self._clear_textures() + + # Clean up EGL texture + if TICI and self.egl_texture: + rl.unload_texture(self.egl_texture) + self.egl_texture = None + + # Clean up shader + if self.shader and self.shader.id: + rl.unload_shader(self.shader) + self.shader.id = 0 + + self.frame = None + self.available_streams.clear() + self.client = None + + def __del__(self): + self.close() + + def _calc_frame_matrix(self, rect: rl.Rectangle) -> np.ndarray: + if not self.frame: + return np.eye(3) + + # Calculate aspect ratios + widget_aspect_ratio = rect.width / rect.height + frame_aspect_ratio = self.frame.width / self.frame.height + + # Calculate scaling factors to maintain aspect ratio + zx = min(frame_aspect_ratio / widget_aspect_ratio, 1.0) + zy = min(widget_aspect_ratio / frame_aspect_ratio, 1.0) + + return np.array([ + [zx, 0.0, 0.0], + [0.0, zy, 0.0], + [0.0, 0.0, 1.0] + ]) + + def _render(self, rect: rl.Rectangle, /): + if self._switching: + self._handle_switch() + + if not self._ensure_connection(): + self._draw_placeholder(rect) + return + + # Try to get a new buffer without blocking + buffer = self.client.recv(timeout_ms=0) + if buffer: + self._texture_needs_update = True + self.frame = buffer + elif not self.client.is_connected(): + # ensure we clear the displayed frame when the connection is lost + self.frame = None + + if not self.frame: + self._draw_placeholder(rect) + return + + transform = self._calc_frame_matrix(rect) + src_rect = rl.Rectangle(0, 0, float(self.frame.width), float(self.frame.height)) + # Flip driver camera horizontally + if self._stream_type == VisionStreamType.VISION_STREAM_DRIVER: + src_rect.width = -src_rect.width + + # Calculate scale + scale_x = rect.width * transform[0, 0] # zx + scale_y = rect.height * transform[1, 1] # zy + + # Calculate base position (centered) + x_offset = rect.x + (rect.width - scale_x) / 2 + y_offset = rect.y + (rect.height - scale_y) / 2 + + x_offset += transform[0, 2] * rect.width / 2 + y_offset += transform[1, 2] * rect.height / 2 + + dst_rect = rl.Rectangle(x_offset, y_offset, scale_x, scale_y) + + # Render with appropriate method + if TICI: + self._render_egl(src_rect, dst_rect) + else: + self._render_textures(src_rect, dst_rect) + + def _draw_placeholder(self, rect: rl.Rectangle): + if self._placeholder_color: + rl.draw_rectangle_rec(rect, self._placeholder_color) + + def _render_egl(self, src_rect: rl.Rectangle, dst_rect: rl.Rectangle) -> None: + """Render using EGL for direct buffer access""" + if self.frame is None or self.egl_texture is None: + return + + idx = self.frame.idx + egl_image = self.egl_images.get(idx) + + # Create EGL image if needed + if egl_image is None: + egl_image = create_egl_image(self.frame.width, self.frame.height, self.frame.stride, self.frame.fd, self.frame.uv_offset) + if egl_image: + self.egl_images[idx] = egl_image + else: + return + + # Update texture dimensions to match current frame + self.egl_texture.width = self.frame.width + self.egl_texture.height = self.frame.height + + # Bind the EGL image to our texture + bind_egl_image_to_texture(self.egl_texture.id, egl_image) + + # Render with shader + rl.begin_shader_mode(self.shader) + self._update_texture_color_filtering() + rl.draw_texture_pro(self.egl_texture, src_rect, dst_rect, rl.Vector2(0, 0), 0.0, rl.WHITE) + rl.end_shader_mode() + + def _render_textures(self, src_rect: rl.Rectangle, dst_rect: rl.Rectangle) -> None: + """Render using texture copies""" + if not self.texture_y or not self.texture_uv or self.frame is None: + return + + # Update textures with new frame data + if self._texture_needs_update: + y_data = self.frame.data[: self.frame.uv_offset] + uv_data = self.frame.data[self.frame.uv_offset:] + + rl.update_texture(self.texture_y, rl.ffi.cast("void *", rl.ffi.from_buffer(y_data))) + rl.update_texture(self.texture_uv, rl.ffi.cast("void *", rl.ffi.from_buffer(uv_data))) + self._texture_needs_update = False + + # Render with shader + rl.begin_shader_mode(self.shader) + self._update_texture_color_filtering() + rl.set_shader_value_texture(self.shader, self._texture1_loc, self.texture_uv) + rl.draw_texture_pro(self.texture_y, src_rect, dst_rect, rl.Vector2(0, 0), 0.0, rl.WHITE) + rl.end_shader_mode() + + def _update_texture_color_filtering(self): + self._engaged_val[0] = 1 if ui_state.status != UIStatus.DISENGAGED else 0 + rl.set_shader_value(self.shader, self._engaged_loc, self._engaged_val, rl.ShaderUniformDataType.SHADER_UNIFORM_INT) + rl.set_shader_value(self.shader, self._enhance_driver_loc, self._enhance_driver_val, rl.ShaderUniformDataType.SHADER_UNIFORM_INT) + + def _ensure_connection(self) -> bool: + if not self.client.is_connected(): + self.frame = None + self.available_streams.clear() + + # Throttle connection attempts + current_time = rl.get_time() + if current_time - self.last_connection_attempt < CONNECTION_RETRY_INTERVAL: + return False + self.last_connection_attempt = current_time + + if not self.client.connect(False) or not self.client.num_buffers: + return False + + cloudlog.debug(f"Connected to {self._name} stream: {self._stream_type}, buffers: {self.client.num_buffers}") + self._initialize_textures() + self.available_streams = self.client.available_streams(self._name, block=False) + + return True + + def _handle_switch(self) -> None: + """Check if target stream is ready and switch immediately.""" + if not self._target_client or not self._switching: + return + + # Try to connect target if needed + if not self._target_client.is_connected(): + if not self._target_client.connect(False) or not self._target_client.num_buffers: + return + + cloudlog.debug(f"Target stream connected: {self._target_stream_type}") + + # Check if target has frames ready + target_frame = self._target_client.recv(timeout_ms=0) + if target_frame: + self.frame = target_frame # Update current frame to target frame + self._complete_switch() + + def _complete_switch(self) -> None: + """Instantly switch to target stream.""" + cloudlog.debug(f"Switching to {self._target_stream_type}") + # Clean up current resources + if self.client: + del self.client + + # Switch to target + self.client = self._target_client + self._stream_type = self._target_stream_type + self._texture_needs_update = True + + # Reset state + self._target_client = None + self._target_stream_type = None + self._switching = False + + # Initialize textures for new stream + self._initialize_textures() + + def _initialize_textures(self): + self._clear_textures() + if not TICI: + self.texture_y = rl.load_texture_from_image(rl.Image(None, int(self.client.stride), + int(self.client.height), 1, rl.PixelFormat.PIXELFORMAT_UNCOMPRESSED_GRAYSCALE)) + self.texture_uv = rl.load_texture_from_image(rl.Image(None, int(self.client.stride // 2), + int(self.client.height // 2), 1, rl.PixelFormat.PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA)) + + def _clear_textures(self): + if self.texture_y and self.texture_y.id: + rl.unload_texture(self.texture_y) + self.texture_y = None + + if self.texture_uv and self.texture_uv.id: + rl.unload_texture(self.texture_uv) + self.texture_uv = None + + # Clean up EGL resources + if TICI: + for data in self.egl_images.values(): + destroy_egl_image(data) + self.egl_images = {} + + +if __name__ == "__main__": + gui_app.init_window("camera view") + road = CameraView("camerad", VisionStreamType.VISION_STREAM_ROAD) + for _ in gui_app.render(): + road.render(rl.Rectangle(0, 0, gui_app.width, gui_app.height)) diff --git a/openpilot/selfdrive/ui/mici/onroad/confidence_ball.py b/openpilot/selfdrive/ui/mici/onroad/confidence_ball.py new file mode 100644 index 0000000000..54699eab54 --- /dev/null +++ b/openpilot/selfdrive/ui/mici/onroad/confidence_ball.py @@ -0,0 +1,86 @@ +import math +import pyray as rl +from openpilot.selfdrive.ui.mici.onroad import SIDE_PANEL_WIDTH +from openpilot.selfdrive.ui.ui_state import ui_state, UIStatus +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.lib.application import gui_app +from openpilot.common.filter_simple import FirstOrderFilter + +from openpilot.selfdrive.ui.sunnypilot.mici.onroad.confidence_ball import ConfidenceBallSP + + +def draw_circle_gradient(center_x: float, center_y: float, radius: int, + top: rl.Color, bottom: rl.Color) -> None: + # Draw a square with the gradient + rl.draw_rectangle_gradient_v(int(center_x - radius), int(center_y - radius), + radius * 2, radius * 2, + top, bottom) + + # Paint over square with a ring + outer_radius = math.ceil(radius * math.sqrt(2)) + 1 + rl.draw_ring(rl.Vector2(int(center_x), int(center_y)), radius, outer_radius, + 0.0, 360.0, + 20, rl.BLACK) + + +class ConfidenceBall(Widget, ConfidenceBallSP): + def __init__(self, demo: bool = False): + Widget.__init__(self) + ConfidenceBallSP.__init__(self) + self._demo = demo + self._confidence_filter = FirstOrderFilter(-0.5, 0.5, 1 / gui_app.target_fps) + + def update_filter(self, value: float): + self._confidence_filter.update(value) + + def _update_state(self): + if self._demo: + return + + # animate status dot in from bottom + if ui_state.status == UIStatus.DISENGAGED: + self._confidence_filter.update(-0.5) + elif ui_state.status in (UIStatus.LAT_ONLY, UIStatus.LONG_ONLY): + self._confidence_filter.update(1 - max(self.get_animate_status_probs() or [1])) + else: + self._confidence_filter.update((1 - max(ui_state.sm['modelV2'].meta.disengagePredictions.brakeDisengageProbs or [1])) * + (1 - max(ui_state.sm['modelV2'].meta.disengagePredictions.steerOverrideProbs or [1]))) + + def _render(self, _): + content_rect = rl.Rectangle( + self.rect.x + self.rect.width - SIDE_PANEL_WIDTH, + self.rect.y, + SIDE_PANEL_WIDTH, + self.rect.height, + ) + + status_dot_radius = 24 + dot_height = (1 - self._confidence_filter.x) * (content_rect.height - 2 * status_dot_radius) + status_dot_radius + dot_height = self._rect.y + dot_height + + # confidence zones + if ui_state.status == UIStatus.ENGAGED or self._demo: + if self._confidence_filter.x > 0.5: + top_dot_color = rl.Color(0, 255, 204, 255) + bottom_dot_color = rl.Color(0, 255, 38, 255) + elif self._confidence_filter.x > 0.2: + top_dot_color = rl.Color(255, 200, 0, 255) + bottom_dot_color = rl.Color(255, 115, 0, 255) + else: + top_dot_color = rl.Color(255, 0, 21, 255) + bottom_dot_color = rl.Color(255, 0, 89, 255) + + elif ui_state.status in (UIStatus.LAT_ONLY, UIStatus.LONG_ONLY): + top_dot_color = bottom_dot_color = self.get_lat_long_dot_color() + + elif ui_state.status == UIStatus.OVERRIDE: + top_dot_color = rl.Color(255, 255, 255, 255) + bottom_dot_color = rl.Color(82, 82, 82, 255) + + else: + top_dot_color = rl.Color(50, 50, 50, 255) + bottom_dot_color = rl.Color(13, 13, 13, 255) + + draw_circle_gradient(content_rect.x + content_rect.width - status_dot_radius, + dot_height, status_dot_radius, + top_dot_color, bottom_dot_color) diff --git a/openpilot/selfdrive/ui/mici/onroad/driver_camera_dialog.py b/openpilot/selfdrive/ui/mici/onroad/driver_camera_dialog.py new file mode 100644 index 0000000000..e81877b402 --- /dev/null +++ b/openpilot/selfdrive/ui/mici/onroad/driver_camera_dialog.py @@ -0,0 +1,248 @@ +import pyray as rl +from openpilot.cereal import log, messaging +from msgq.visionipc import VisionStreamType +from openpilot.selfdrive.ui.mici.onroad.cameraview import CameraView +from openpilot.selfdrive.ui.mici.onroad.driver_state import DriverStateRenderer +from openpilot.selfdrive.ui.ui_state import ui_state, device +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.nav_widget import NavWidget +from openpilot.system.ui.widgets.label import gui_label + + +class DriverCameraView(CameraView): + def _calc_frame_matrix(self, rect: rl.Rectangle): + base = super()._calc_frame_matrix(rect) + driver_view_ratio = 1.5 + base[0, 0] *= driver_view_ratio + base[1, 1] *= driver_view_ratio + return base + + +class BaseDriverCameraDialog(Widget): + # Not a NavWidget so training guide can use this without back navigation + def __init__(self): + super().__init__() + self._camera_view = DriverCameraView("camerad", VisionStreamType.VISION_STREAM_DRIVER) + self.driver_state_renderer = DriverStateRenderer(lines=True) + self.driver_state_renderer.set_rect(rl.Rectangle(0, 0, 200, 200)) + self.driver_state_renderer.load_icons() + self._pm: messaging.PubMaster | None = None + + # Load eye icons + self._eye_fill_texture = None + self._eye_orange_texture = None + self._eye_size = 74 + self._glasses_texture = None + self._glasses_size = 171 + + self._load_eye_textures() + + def show_event(self): + super().show_event() + ui_state.params.put_bool("IsDriverViewEnabled", True) + self._publish_alert_sound(None) + device.set_override_interactive_timeout(300) + ui_state.params.remove("DriverTooDistracted") + self._pm = messaging.PubMaster(['selfdriveState']) + + def hide_event(self): + super().hide_event() + ui_state.params.put_bool("IsDriverViewEnabled", False) + device.set_override_interactive_timeout(None) + + def _handle_mouse_release(self, _): + ui_state.params.remove("DriverTooDistracted") + + def __del__(self): + self.close() + + def close(self): + if self._camera_view: + self._camera_view.close() + + def _update_state(self): + if self._camera_view: + self._camera_view._update_state() + # Enable driver state renderer to show Dmoji in preview + self.driver_state_renderer.set_should_draw(True) + self.driver_state_renderer.set_force_active(True) + super()._update_state() + + def _render(self, rect): + rl.begin_scissor_mode(int(rect.x), int(rect.y), int(rect.width), int(rect.height)) + self._camera_view._render(rect) + + if not self._camera_view.frame: + gui_label(rect, tr("camera starting"), font_size=54, font_weight=FontWeight.BOLD, + alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER) + rl.end_scissor_mode() + self._publish_alert_sound(None) + return + + driver_data = self._draw_face_detection(rect) + if driver_data is not None: + self._draw_eyes(rect, driver_data) + + # Position dmoji on opposite side from driver + driver_state_rect = ( + rect.x if self.driver_state_renderer.is_rhd else rect.x + rect.width - self.driver_state_renderer.rect.width, + rect.y + (rect.height - self.driver_state_renderer.rect.height) / 2, + ) + self.driver_state_renderer.set_position(*driver_state_rect) + self.driver_state_renderer.render() + + # Render driver monitoring alerts + self._render_dm_alerts(rect) + + rl.end_scissor_mode() + return + + def _publish_alert_sound(self, dm_state): + """Publish selfdriveState with only alertSound field set""" + if self._pm is None: + return + + AudibleAlert = log.SelfdriveState.AudibleAlert + ALERT_SOUNDS = { + 'one': AudibleAlert.preAlert, + 'two': AudibleAlert.promptDistracted, + 'three': AudibleAlert.warningImmediate, + } + msg = messaging.new_message('selfdriveState') + if dm_state is not None: + msg.selfdriveState.alertSound = ALERT_SOUNDS.get(str(dm_state.alertLevel), AudibleAlert.none) + self._pm.send('selfdriveState', msg) + + def _render_dm_alerts(self, rect: rl.Rectangle): + """Render driver monitoring event names""" + dm_state = ui_state.sm["driverMonitoringState"] + self._publish_alert_sound(dm_state) + + is_vision = dm_state.activePolicy == log.DriverMonitoringState.MonitoringPolicy.vision + awareness_pct = dm_state.visionPolicyState.awarenessPercent if is_vision else dm_state.wheeltouchPolicyState.awarenessPercent + gui_label(rl.Rectangle(rect.x + 2, rect.y + 2, rect.width, rect.height), + f"Awareness: {awareness_pct:.0f}%", font_size=44, font_weight=FontWeight.MEDIUM, + alignment=rl.GuiTextAlignment.TEXT_ALIGN_RIGHT, + alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_TOP, + color=rl.Color(0, 0, 0, 180)) + gui_label(rect, f"Awareness: {awareness_pct:.0f}%", font_size=44, font_weight=FontWeight.MEDIUM, + alignment=rl.GuiTextAlignment.TEXT_ALIGN_RIGHT, + alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_TOP, + color=rl.Color(255, 255, 255, int(255 * 0.9))) + + if dm_state.alertLevel == log.DriverMonitoringState.AlertLevel.none: + return + + # Show alert level + alert_level_str = f"{'Pay Attention' if is_vision else 'Touch Wheel'} - level {dm_state.alertLevel}" + alignment = rl.GuiTextAlignment.TEXT_ALIGN_RIGHT if self.driver_state_renderer.is_rhd else rl.GuiTextAlignment.TEXT_ALIGN_LEFT + + shadow_rect = rl.Rectangle(rect.x + 2, rect.y + 2, rect.width, rect.height) + gui_label(shadow_rect, alert_level_str, font_size=40, font_weight=FontWeight.BOLD, + alignment=alignment, + alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_BOTTOM, + color=rl.Color(0, 0, 0, 180)) + gui_label(rect, alert_level_str, font_size=40, font_weight=FontWeight.BOLD, + alignment=alignment, + alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_BOTTOM, + color=rl.Color(255, 255, 255, int(255 * 0.9))) + + def _load_eye_textures(self): + """Lazy load eye textures""" + if self._eye_fill_texture is None: + self._eye_fill_texture = gui_app.texture("icons_mici/onroad/eye_fill.png", self._eye_size, self._eye_size) + if self._eye_orange_texture is None: + self._eye_orange_texture = gui_app.texture("icons_mici/onroad/eye_orange.png", self._eye_size, self._eye_size) + if self._glasses_texture is None: + self._glasses_texture = gui_app.texture("icons_mici/onroad/glasses.png", self._glasses_size, self._glasses_size) + + def _draw_face_detection(self, rect: rl.Rectangle): + dm_state = ui_state.sm["driverMonitoringState"] + driver_data = self.driver_state_renderer.get_driver_data() + if not dm_state.visionPolicyState.faceDetected: + return + + # Get face position and orientation + face_x, face_y = driver_data.facePosition + face_std = max(driver_data.faceOrientationStd[0], driver_data.faceOrientationStd[1]) + alpha = 0.7 + if face_std > 0.15: + alpha = max(0.7 - (face_std - 0.15) * 3.5, 0.0) + + # use approx instead of distort_points + # TODO: replace with distort_points + tici_x = 1080.0 - 1714.0 * face_x + tici_y = -135.0 + (504.0 + abs(face_x) * 112.0) + (1205.0 - abs(face_x) * 724.0) * face_y + + # Tici coords are relative to center, scale offset + offset_x = (tici_x - 1080.0) * 1.25 + offset_y = (tici_y - 540.0) * 1.25 + + # Map to mici screen (scale from 2160x1080 to rect dimensions) + scale_x = rect.width / 2160.0 + scale_y = rect.height / 1080.0 + fbox_x = rect.x + rect.width / 2 + offset_x * scale_x + fbox_y = rect.y + rect.height / 2 + offset_y * scale_y + box_size = 75 + line_thickness = 3 + + line_color = rl.Color(255, 255, 255, int(alpha * 255)) + rl.draw_rectangle_rounded_lines_ex( + rl.Rectangle(fbox_x - box_size / 2, fbox_y - box_size / 2, box_size, box_size), + 35.0 / box_size / 2, + line_thickness, + line_thickness, + line_color, + ) + return driver_data + + def _draw_eyes(self, rect: rl.Rectangle, driver_data): + # Draw eye indicators based on eye probabilities + eye_offset_x = 10 + eye_offset_y = 10 + eye_spacing = self._eye_size + 15 + + left_eye_x = rect.x + eye_offset_x + left_eye_y = rect.y + eye_offset_y + left_eye_prob = driver_data.leftEyeProb + + right_eye_x = rect.x + eye_offset_x + eye_spacing + right_eye_y = rect.y + eye_offset_y + right_eye_prob = driver_data.rightEyeProb + + # Draw eyes with opacity based on probability + for eye_x, eye_y, eye_prob in [(left_eye_x, left_eye_y, left_eye_prob), (right_eye_x, right_eye_y, right_eye_prob)]: + fill_opacity = eye_prob + orange_opacity = 1.0 - eye_prob + + rl.draw_texture_v(self._eye_orange_texture, (eye_x, eye_y), rl.Color(255, 255, 255, int(255 * orange_opacity))) + rl.draw_texture_v(self._eye_fill_texture, (eye_x, eye_y), rl.Color(255, 255, 255, int(255 * fill_opacity))) + + # Draw sunglasses indicator based on sunglasses probability + # Position glasses centered between the two eyes at top left + glasses_x = rect.x + eye_offset_x - 4 + glasses_y = rect.y + glasses_pos = rl.Vector2(glasses_x, glasses_y) + glasses_prob = driver_data.sunglassesProb + rl.draw_texture_v(self._glasses_texture, glasses_pos, rl.Color(70, 80, 161, int(255 * glasses_prob))) + + +class DriverCameraDialog(NavWidget, BaseDriverCameraDialog): + def __init__(self): + super().__init__() + # TODO: this can grow unbounded, should be given some thought + device.add_interactive_timeout_callback(gui_app.pop_widget) + + +if __name__ == "__main__": + gui_app.init_window("Driver Camera View (mici)") + + driver_camera_view = DriverCameraDialog() + gui_app.push_widget(driver_camera_view) + try: + for _ in gui_app.render(): + ui_state.update() + finally: + driver_camera_view.close() diff --git a/openpilot/selfdrive/ui/mici/onroad/driver_state.py b/openpilot/selfdrive/ui/mici/onroad/driver_state.py new file mode 100644 index 0000000000..85b90704ac --- /dev/null +++ b/openpilot/selfdrive/ui/mici/onroad/driver_state.py @@ -0,0 +1,216 @@ +import pyray as rl +import numpy as np +import math +from openpilot.cereal import log +from openpilot.common.filter_simple import FirstOrderFilter +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.widgets import Widget +from openpilot.selfdrive.ui.ui_state import ui_state + + +AlertSize = log.SelfdriveState.AlertSize + +DEBUG = False + +# TODO: Only left for DM preview, remove +LOOKING_CENTER_THRESHOLD_UPPER = math.radians(6) +LOOKING_CENTER_THRESHOLD_LOWER = math.radians(3) + +CONE_COLOR_GREEN = (0, 255, 64) +CONE_COLOR_ORANGE = (255, 115, 0) + + +class DriverStateRenderer(Widget): + BASE_SIZE = 60 + LINES_ANGLE_INCREMENT = 5 + LINES_STALE_ANGLES = 3.0 # seconds + AWARENESS_UNFULL_PERCENT = 95 # ~0.5s + + def __init__(self, lines: bool = False, inset: bool = False): + super().__init__() + self.set_rect(rl.Rectangle(0, 0, self.BASE_SIZE, self.BASE_SIZE)) + self._lines = lines + self._inset = inset + + # In line mode, track smoothed angles + assert 360 % self.LINES_ANGLE_INCREMENT == 0 + self._head_angles = {i * self.LINES_ANGLE_INCREMENT: FirstOrderFilter(0.0, 0.1, 1 / gui_app.target_fps) for i in range(360 // self.LINES_ANGLE_INCREMENT)} + + self._is_active = False + self._is_rhd = False + self._face_detected = False + self._face_pitch = 0. + self._face_yaw = 0. + self._should_draw = False + self._force_active = False + self._looking_center = False + self._awareness_unfull = False + + self._fade_filter = FirstOrderFilter(0.0, 0.05, 1 / gui_app.target_fps) + self._color_fade_filter = FirstOrderFilter(1.0, 0.05, 1 / gui_app.target_fps) # 1.0 = full green, 0.0 = full orange + self._pitch_filter = FirstOrderFilter(0.0, 0.05, 1 / gui_app.target_fps, initialized=False) + self._yaw_filter = FirstOrderFilter(0.0, 0.05, 1 / gui_app.target_fps, initialized=False) + self._rotation_filter = FirstOrderFilter(0.0, 0.1, 1 / gui_app.target_fps, initialized=False) + self._looking_center_filter = FirstOrderFilter(0.0, 0.1, 1 / gui_app.target_fps) + + # Load the driver face icons + self.load_icons() + + def load_icons(self): + """Load or reload the driver face icon texture""" + cone_and_person_size = round(52 / self.BASE_SIZE * self._rect.width) + + # If inset is enabled, push cone and person smaller by 2x the current inset space + if self._inset: + # Current inset space = (rect.width - cone_and_person_size) / 2 + current_inset = (self._rect.width - cone_and_person_size) / 2 + # Reduce size by 2x the current inset (1x on each side) + cone_and_person_size = round(cone_and_person_size - current_inset * 2) + + self._dm_person = gui_app.texture("icons_mici/onroad/driver_monitoring/dm_person.png", cone_and_person_size, cone_and_person_size) + self._dm_cone = gui_app.texture("icons_mici/onroad/driver_monitoring/dm_cone.png", cone_and_person_size, cone_and_person_size) + self._dm_background = gui_app.texture("icons_mici/onroad/driver_monitoring/dm_background.png", int(self._rect.width), int(self._rect.height)) + + def set_should_draw(self, should_draw: bool): + self._should_draw = should_draw + + @property + def should_draw(self): + return (self._should_draw and ui_state.sm["selfdriveState"].alertSize == AlertSize.none and + ui_state.sm.recv_frame["driverStateV2"] > ui_state.started_frame) + + def set_force_active(self, force_active: bool): + """Force the dmoji to always appear active (green) regardless of actual state""" + self._force_active = force_active + + @property + def effective_active(self) -> bool: + """Returns True if dmoji should appear active (either actually active or forced)""" + return bool(self._force_active or self._is_active) + + @property + def is_rhd(self) -> bool: + return self._is_rhd + + def _render(self, _): + if DEBUG: + rl.draw_rectangle_lines_ex(self._rect, 1, rl.RED) + + rl.draw_texture_ex(self._dm_background, + rl.Vector2(self._rect.x, self._rect.y), 0.0, 1.0, + rl.Color(255, 255, 255, int(255 * self._fade_filter.x))) + + rl.draw_texture_ex(self._dm_person, + rl.Vector2(self._rect.x + (self._rect.width - self._dm_person.width) / 2, + self._rect.y + (self._rect.height - self._dm_person.height) / 2), 0.0, 1.0, + rl.Color(255, 255, 255, int(255 * 0.9 * self._fade_filter.x))) + + green_amount = self._color_fade_filter.update(0.0 if self._awareness_unfull else 1.0) + if self.effective_active: + source_rect = rl.Rectangle(0, 0, self._dm_cone.width, self._dm_cone.height) + dest_rect = rl.Rectangle( + self._rect.x + self._rect.width / 2, + self._rect.y + self._rect.height / 2, + self._dm_cone.width, + self._dm_cone.height, + ) + + if not self._lines: + r = int(round(CONE_COLOR_GREEN[0] * green_amount + CONE_COLOR_ORANGE[0] * (1 - green_amount))) + g = int(round(CONE_COLOR_GREEN[1] * green_amount + CONE_COLOR_ORANGE[1] * (1 - green_amount))) + b = int(round(CONE_COLOR_GREEN[2] * green_amount + CONE_COLOR_ORANGE[2] * (1 - green_amount))) + rl.draw_texture_pro( + self._dm_cone, + source_rect, + dest_rect, + rl.Vector2(dest_rect.width / 2, dest_rect.height / 2), + self._rotation_filter.x - 90, + rl.Color(r, g, b, int(255 * self._fade_filter.x)), + ) + + else: + # remove old angles + for angle, f in self._head_angles.items(): + dst_from_current = ((angle - self._rotation_filter.x) % 360) - 180 + target = 1.0 if abs(dst_from_current) <= self.LINES_ANGLE_INCREMENT * 5 else 0.0 + if not self._face_detected: + target = 0.0 + + # Reduce all line lengths when looking center + if self._looking_center: + target = np.interp(self._looking_center_filter.x, [0.0, 1.0], [target, 0.45]) + + f.update(target) + self._draw_line(angle, f, self._looking_center) + + def _draw_line(self, angle: int, f: FirstOrderFilter, grey: bool): + line_length = self._rect.width / 6 + line_length = round(np.interp(f.x, [0.0, 1.0], [0, line_length])) + line_offset = self._rect.width / 2 - line_length * 2 # ensure line ends within rect + center_x = self._rect.x + self._rect.width / 2 + center_y = self._rect.y + self._rect.height / 2 + start_x = center_x + (line_offset + line_length) * math.cos(math.radians(angle)) + start_y = center_y + (line_offset + line_length) * math.sin(math.radians(angle)) + end_x = start_x + line_length * math.cos(math.radians(angle)) + end_y = start_y + line_length * math.sin(math.radians(angle)) + color = rl.Color(0, 255, 64, 255) + + if grey: + color = rl.Color(166, 166, 166, 255) + + if f.x > 0.01: + rl.draw_line_ex((start_x, start_y), (end_x, end_y), 12, color) + + def get_driver_data(self): + sm = ui_state.sm + + dm_state = sm["driverMonitoringState"] + self._is_active = dm_state.activePolicy == log.DriverMonitoringState.MonitoringPolicy.vision + self._is_rhd = dm_state.isRHD + self._face_detected = dm_state.visionPolicyState.faceDetected + self._awareness_unfull = self.effective_active and dm_state.visionPolicyState.awarenessPercent < self.AWARENESS_UNFULL_PERCENT + self._face_pitch = dm_state.visionPolicyState.pose.pitch + math.radians(6) # calib or DM pose is not accurate, add a fake upward pitch to bias forward + self._face_yaw = -dm_state.visionPolicyState.pose.yaw # undo sign flip in face_orientation_from_model to match UI convention + + driverstate = sm["driverStateV2"] + driver_data = driverstate.rightDriverData if self._is_rhd else driverstate.leftDriverData + return driver_data + + def _update_state(self): + # Get monitoring state + _ = self.get_driver_data() + pitch = self._pitch_filter.update(self._face_pitch) + yaw = self._yaw_filter.update(self._face_yaw) + + # hysteresis on looking center + if abs(pitch) < LOOKING_CENTER_THRESHOLD_LOWER and abs(yaw) < LOOKING_CENTER_THRESHOLD_LOWER: + self._looking_center = True + elif abs(pitch) > LOOKING_CENTER_THRESHOLD_UPPER or abs(yaw) > LOOKING_CENTER_THRESHOLD_UPPER: + self._looking_center = False + self._looking_center_filter.update(1 if self._looking_center else 0) + + if DEBUG: + pitchd = math.degrees(pitch) + yawd = math.degrees(yaw) + + rl.draw_line_ex((0, 100), (200, 100), 3, rl.RED) + rl.draw_line_ex((0, 120), (200, 120), 3, rl.RED) + rl.draw_line_ex((0, 140), (200, 140), 3, rl.RED) + + pitch_x = 100 + pitchd + yaw_x = 100 + yawd + rl.draw_circle(int(pitch_x), 100, 5, rl.GREEN) + rl.draw_circle(int(yaw_x), 120, 5, rl.GREEN) + + # filter head rotation, handling wrap-around + rotation = math.degrees(math.atan2(pitch * 2, yaw)) # reduce yaw sensitivity + angle_diff = rotation - self._rotation_filter.x + angle_diff = ((angle_diff + 180) % 360) - 180 + self._rotation_filter.update(self._rotation_filter.x + angle_diff) + + if not self.should_draw: + self._fade_filter.update(0.0) + elif not self.effective_active: + self._fade_filter.update(0.35) + else: + self._fade_filter.update(1.0) diff --git a/openpilot/selfdrive/ui/mici/onroad/hud_renderer.py b/openpilot/selfdrive/ui/mici/onroad/hud_renderer.py new file mode 100644 index 0000000000..67f9833021 --- /dev/null +++ b/openpilot/selfdrive/ui/mici/onroad/hud_renderer.py @@ -0,0 +1,278 @@ +import pyray as rl +from dataclasses import dataclass +from openpilot.common.constants import CV +from openpilot.selfdrive.ui.mici.onroad.torque_bar import TorqueBar +from openpilot.selfdrive.ui.ui_state import ui_state, UIStatus +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.widgets import Widget +from openpilot.common.filter_simple import FirstOrderFilter +from openpilot.cereal import log + +EventName = log.OnroadEvent.EventName + +# Constants +SET_SPEED_NA = 255 +KM_TO_MILE = 0.621371 +CRUISE_DISABLED_CHAR = '–' + +SET_SPEED_PERSISTENCE = 2.5 # seconds + + +@dataclass(frozen=True) +class FontSizes: + current_speed: int = 176 + speed_unit: int = 66 + max_speed: int = 36 + set_speed: int = 112 + + +@dataclass(frozen=True) +class Colors: + WHITE = rl.WHITE + WHITE_TRANSLUCENT = rl.Color(255, 255, 255, 200) + + +FONT_SIZES = FontSizes() +COLORS = Colors() + + +class TurnIntent(Widget): + FADE_IN_ANGLE = 30 # degrees + + def __init__(self): + super().__init__() + self._pre = False + self._turn_intent_direction: int = 0 + + self._turn_intent_alpha_filter = FirstOrderFilter(0, 0.05, 1 / gui_app.target_fps) + self._turn_intent_rotation_filter = FirstOrderFilter(0, 0.1, 1 / gui_app.target_fps) + + self._txt_turn_intent_left: rl.Texture = gui_app.texture('icons_mici/turn_intent_left.png', 50, 20) + self._txt_turn_intent_right: rl.Texture = gui_app.texture('icons_mici/turn_intent_left.png', 50, 20, flip_x=True) + + def _render(self, _): + if self._turn_intent_alpha_filter.x > 1e-2: + turn_intent_texture = self._txt_turn_intent_right if self._turn_intent_direction == 1 else self._txt_turn_intent_left + src_rect = rl.Rectangle(0, 0, turn_intent_texture.width, turn_intent_texture.height) + dest_rect = rl.Rectangle(self._rect.x + self._rect.width / 2, self._rect.y + self._rect.height / 2, + turn_intent_texture.width, turn_intent_texture.height) + + origin = (turn_intent_texture.width / 2, self._rect.height / 2) + color = rl.Color(255, 255, 255, int(255 * self._turn_intent_alpha_filter.x)) + rl.draw_texture_pro(turn_intent_texture, src_rect, dest_rect, origin, self._turn_intent_rotation_filter.x, color) + + def _update_state(self) -> None: + sm = ui_state.sm + + left = any(e.name == EventName.preLaneChangeLeft for e in sm['onroadEvents']) + right = any(e.name == EventName.preLaneChangeRight for e in sm['onroadEvents']) + if left or right: + # pre lane change + if not self._pre: + self._turn_intent_rotation_filter.x = self.FADE_IN_ANGLE if left else -self.FADE_IN_ANGLE + + self._pre = True + self._turn_intent_direction = -1 if left else 1 + self._turn_intent_alpha_filter.update(1) + self._turn_intent_rotation_filter.update(0) + elif any(e.name == EventName.laneChange for e in sm['onroadEvents']): + # fade out and rotate away + self._pre = False + self._turn_intent_alpha_filter.update(0) + + if self._turn_intent_direction == 0: + # unknown. missed pre frame? + self._turn_intent_rotation_filter.update(0) + else: + self._turn_intent_rotation_filter.update(self._turn_intent_direction * self.FADE_IN_ANGLE) + else: + # didn't complete lane change, just hide + self._pre = False + self._turn_intent_direction = 0 + self._turn_intent_alpha_filter.update(0) + self._turn_intent_rotation_filter.update(0) + + +class HudRenderer(Widget): + def __init__(self): + super().__init__() + """Initialize the HUD renderer.""" + self.is_cruise_set: bool = False + self.is_cruise_available: bool = True + self.set_speed: float = SET_SPEED_NA + self._set_speed_changed_time: float = 0 + self.speed: float = 0.0 + self.v_ego_cluster_seen: bool = False + self._engaged: bool = False + + self._can_draw_top_icons = True + self._show_wheel_critical = False + + self._font_bold: rl.Font = gui_app.font(FontWeight.BOLD) + self._font_medium: rl.Font = gui_app.font(FontWeight.MEDIUM) + self._font_semi_bold: rl.Font = gui_app.font(FontWeight.SEMI_BOLD) + self._font_display: rl.Font = gui_app.font(FontWeight.DISPLAY) + + self._turn_intent = TurnIntent() + self._torque_bar = TorqueBar() + + self._txt_wheel: rl.Texture = gui_app.texture('icons_mici/wheel.png', 50, 50) + self._txt_wheel_critical: rl.Texture = gui_app.texture('icons_mici/wheel_critical.png', 50, 50) + self._txt_exclamation_point: rl.Texture = gui_app.texture('icons_mici/exclamation_point.png', 9, 44) + + self._wheel_alpha_filter = FirstOrderFilter(0, 0.05, 1 / gui_app.target_fps) + self._wheel_y_filter = FirstOrderFilter(0, 0.1, 1 / gui_app.target_fps) + + self._set_speed_alpha_filter = FirstOrderFilter(0.0, 0.1, 1 / gui_app.target_fps) + + def set_wheel_critical_icon(self, critical: bool): + """Set the wheel icon to critical or normal state.""" + self._show_wheel_critical = critical + + def set_can_draw_top_icons(self, can_draw_top_icons: bool): + """Set whether to draw the top part of the HUD.""" + self._can_draw_top_icons = can_draw_top_icons + + def drawing_top_icons(self) -> bool: + # whether we're drawing any top icons currently + return bool(self._set_speed_alpha_filter.x > 1e-2) + + def _update_state(self) -> None: + """Update HUD state based on car state and controls state.""" + sm = ui_state.sm + if sm.recv_frame["carState"] < ui_state.started_frame: + self.is_cruise_set = False + self.set_speed = SET_SPEED_NA + self.speed = 0.0 + return + + controls_state = sm['controlsState'] + car_state = sm['carState'] + + v_cruise_cluster = car_state.vCruiseCluster + set_speed = ( + controls_state.deprecated.vCruise if v_cruise_cluster == 0.0 else v_cruise_cluster + ) + engaged = sm['selfdriveState'].enabled + if (set_speed != self.set_speed and engaged) or (engaged and not self._engaged): + self._set_speed_changed_time = rl.get_time() + self._engaged = engaged + self.set_speed = set_speed + self.is_cruise_set = 0 < self.set_speed < SET_SPEED_NA + self.is_cruise_available = self.set_speed != -1 + + v_ego_cluster = car_state.vEgoCluster + self.v_ego_cluster_seen = self.v_ego_cluster_seen or v_ego_cluster != 0.0 + v_ego = v_ego_cluster if self.v_ego_cluster_seen else car_state.vEgo + speed_conversion = CV.MS_TO_KPH if ui_state.is_metric else CV.MS_TO_MPH + self.speed = max(0.0, v_ego * speed_conversion) + + def _render(self, rect: rl.Rectangle) -> None: + """Render HUD elements to the screen.""" + + self._torque_bar.render(rect) + + if self.is_cruise_set: + self._draw_set_speed(rect) + + self._draw_steering_wheel(rect) + + def _draw_steering_wheel(self, rect: rl.Rectangle) -> None: + wheel_txt = self._txt_wheel_critical if self._show_wheel_critical else self._txt_wheel + + bsm_detected = self._has_blind_spot_detected() if gui_app.sunnypilot_ui() else False + + if self._show_wheel_critical: + self._wheel_alpha_filter.update(255) + self._wheel_y_filter.update(0) + else: + if ui_state.status == UIStatus.DISENGAGED or bsm_detected: + self._wheel_alpha_filter.update(0) + self._wheel_y_filter.update(wheel_txt.height / 2) + else: + self._wheel_alpha_filter.update(255 * 0.9) + self._wheel_y_filter.update(0) + + # pos + pos_x = int(rect.x + 21 + wheel_txt.width / 2) + pos_y = int(rect.y + rect.height - 14 - wheel_txt.height / 2 + self._wheel_y_filter.x) + rotation = -ui_state.sm['carState'].steeringAngleDeg + + turn_intent_margin = 25 + self._turn_intent.render(rl.Rectangle( + pos_x - wheel_txt.width / 2 - turn_intent_margin, + pos_y - wheel_txt.height / 2 - turn_intent_margin, + wheel_txt.width + turn_intent_margin * 2, + wheel_txt.height + turn_intent_margin * 2, + )) + + src_rect = rl.Rectangle(0, 0, wheel_txt.width, wheel_txt.height) + dest_rect = rl.Rectangle(pos_x, pos_y, wheel_txt.width, wheel_txt.height) + origin = (wheel_txt.width / 2, wheel_txt.height / 2) + + # color and draw + color = rl.Color(255, 255, 255, int(self._wheel_alpha_filter.x)) + rl.draw_texture_pro(wheel_txt, src_rect, dest_rect, origin, rotation, color) + + if self._show_wheel_critical: + # Draw exclamation point icon + EXCLAMATION_POINT_SPACING = 10 + exclamation_pos_x = pos_x - self._txt_exclamation_point.width / 2 + wheel_txt.width / 2 + EXCLAMATION_POINT_SPACING + exclamation_pos_y = pos_y - self._txt_exclamation_point.height / 2 + rl.draw_texture_ex(self._txt_exclamation_point, rl.Vector2(exclamation_pos_x, exclamation_pos_y), 0.0, 1.0, rl.WHITE) + + def _draw_set_speed(self, rect: rl.Rectangle) -> None: + """Draw the MAX speed indicator box.""" + alpha = self._set_speed_alpha_filter.update(0 < rl.get_time() - self._set_speed_changed_time < SET_SPEED_PERSISTENCE and + self._can_draw_top_icons and self._engaged) + if alpha < 1e-2: + return + + x = rect.x + y = rect.y + + # draw drop shadow + circle_radius = 162 // 2 + rl.draw_circle_gradient(rl.Vector2(x + circle_radius, y + circle_radius), circle_radius, + rl.Color(0, 0, 0, int(255 / 2 * alpha)), rl.BLANK) + + set_speed_color = rl.Color(255, 255, 255, int(255 * 0.9 * alpha)) + max_color = rl.Color(255, 255, 255, int(255 * 0.9 * alpha)) + + set_speed = self.set_speed + if self.is_cruise_set and not ui_state.is_metric: + set_speed *= KM_TO_MILE + + set_speed_text = CRUISE_DISABLED_CHAR if not self.is_cruise_set else str(round(set_speed)) + rl.draw_text_ex( + self._font_display, + set_speed_text, + rl.Vector2(x + 13 + 4, y + 3 - 8 - 3 + 4), + FONT_SIZES.set_speed, + 0, + set_speed_color, + ) + + max_text = tr("MAX") + rl.draw_text_ex( + self._font_semi_bold, + max_text, + rl.Vector2(x + 25, y + FONT_SIZES.set_speed - 7 + 4), + FONT_SIZES.max_speed, + 0, + max_color, + ) + + def _draw_current_speed(self, rect: rl.Rectangle) -> None: + """Draw the current vehicle speed and unit.""" + speed_text = str(round(self.speed)) + speed_text_size = measure_text_cached(self._font_bold, speed_text, FONT_SIZES.current_speed) + speed_pos = rl.Vector2(rect.x + rect.width / 2 - speed_text_size.x / 2, 180 - speed_text_size.y / 2) + rl.draw_text_ex(self._font_bold, speed_text, speed_pos, FONT_SIZES.current_speed, 0, COLORS.WHITE) + + unit_text = tr("km/h") if ui_state.is_metric else tr("mph") + unit_text_size = measure_text_cached(self._font_medium, unit_text, FONT_SIZES.speed_unit) + unit_pos = rl.Vector2(rect.x + rect.width / 2 - unit_text_size.x / 2, 290 - unit_text_size.y / 2) + rl.draw_text_ex(self._font_medium, unit_text, unit_pos, FONT_SIZES.speed_unit, 0, COLORS.WHITE_TRANSLUCENT) diff --git a/openpilot/selfdrive/ui/mici/onroad/model_renderer.py b/openpilot/selfdrive/ui/mici/onroad/model_renderer.py new file mode 100644 index 0000000000..3f514b28d2 --- /dev/null +++ b/openpilot/selfdrive/ui/mici/onroad/model_renderer.py @@ -0,0 +1,499 @@ +import colorsys +import numpy as np +import pyray as rl +from openpilot.cereal import messaging +from opendbc.car.structs import car +from dataclasses import dataclass, field +from openpilot.common.params import Params +from openpilot.common.filter_simple import FirstOrderFilter +from openpilot.selfdrive.locationd.calibrationd import HEIGHT_INIT +from openpilot.selfdrive.ui.ui_state import ui_state, UIStatus +from openpilot.selfdrive.ui.mici.onroad import blend_colors +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.lib.shader_polygon import draw_polygon, Gradient +from openpilot.system.ui.widgets import Widget + +from openpilot.selfdrive.ui.sunnypilot.mici.onroad.model_renderer import LANE_LINE_COLORS_SP, ModelRendererSP + +CLIP_MARGIN = 500 +MIN_DRAW_DISTANCE = 10.0 +MAX_DRAW_DISTANCE = 100.0 + +THROTTLE_COLORS = [ + rl.Color(13, 248, 122, 102), # HSLF(148/360, 0.94, 0.51, 0.4) + rl.Color(114, 255, 92, 89), # HSLF(112/360, 1.0, 0.68, 0.35) + rl.Color(114, 255, 92, 0), # HSLF(112/360, 1.0, 0.68, 0.0) +] + +NO_THROTTLE_COLORS = [ + rl.Color(242, 242, 242, 102), # HSLF(148/360, 0.0, 0.95, 0.4) + rl.Color(242, 242, 242, 89), # HSLF(112/360, 0.0, 0.95, 0.35) + rl.Color(242, 242, 242, 0), # HSLF(112/360, 0.0, 0.95, 0.0) +] + +LANE_LINE_COLORS = { + UIStatus.DISENGAGED: rl.Color(200, 200, 200, 255), + UIStatus.OVERRIDE: rl.Color(255, 255, 255, 255), + UIStatus.ENGAGED: rl.Color(0, 255, 64, 255), + **LANE_LINE_COLORS_SP, +} + + +@dataclass +class ModelPoints: + raw_points: np.ndarray = field(default_factory=lambda: np.empty((0, 3), dtype=np.float32)) + projected_points: np.ndarray = field(default_factory=lambda: np.empty((0, 2), dtype=np.float32)) + + +@dataclass +class LeadVehicle: + glow: list[tuple[float, float]] = field(default_factory=list) + chevron: list[tuple[float, float]] = field(default_factory=list) + fill_alpha: int = 0 + + +class ModelRenderer(Widget, ModelRendererSP): + def __init__(self): + Widget.__init__(self) + ModelRendererSP.__init__(self) + self._longitudinal_control = False + self._experimental_mode = False + self._blend_filter = FirstOrderFilter(1.0, 0.25, 1 / gui_app.target_fps) + self._prev_allow_throttle = True + self._lane_line_probs = np.zeros(4, dtype=np.float32) + self._road_edge_stds = np.zeros(2, dtype=np.float32) + self._lead_vehicles = [LeadVehicle(), LeadVehicle()] + self._path_offset_z = HEIGHT_INIT[0] + + # Initialize ModelPoints objects + self._path = ModelPoints() + self._lane_lines = [ModelPoints() for _ in range(4)] + self._road_edges = [ModelPoints() for _ in range(2)] + self._acceleration_x = np.empty((0,), dtype=np.float32) + + self._acceleration_x_filter = FirstOrderFilter(0.0, 0.1, 1 / gui_app.target_fps) + self._acceleration_x_filter2 = FirstOrderFilter(0.0, 1, 1 / gui_app.target_fps) + + self._torque_filter = FirstOrderFilter(0, 0.1, 1 / gui_app.target_fps) + self._ll_color_filter = FirstOrderFilter(0.0, 0.1, 1 / gui_app.target_fps) + + # 3x3 car space -> rect-origin space (draw methods add rect.x/y) + self._car_space_transform = np.zeros((3, 3), dtype=np.float32) + self._transform_dirty = True + self._clip_region = None + + self._counter = -1 + self._camera_offset = ui_state.params.get("CameraOffset", return_default=True) if ui_state.active_bundle else 0.0 + + self._exp_gradient = Gradient( + start=(0.0, 1.0), # Bottom of path + end=(0.0, 0.0), # Top of path + colors=[], + stops=[], + ) + + # Get longitudinal control setting from car parameters + if car_params := Params().get("CarParams"): + cp = messaging.log_from_bytes(car_params, car.CarParams) + self._longitudinal_control = cp.openpilotLongitudinalControl + + def set_transform(self, transform: np.ndarray): + self._car_space_transform = transform.astype(np.float32) + self._transform_dirty = True + + def _render(self, rect: rl.Rectangle): + sm = ui_state.sm + + if self._counter % 180 == 0: # This runs at 60fps, so we query every 3 seconds + self._camera_offset = ui_state.params.get("CameraOffset", return_default=True) if ui_state.active_bundle else 0.0 + self._counter += 1 + + self._torque_filter.update(-ui_state.sm['carOutput'].actuatorsOutput.torque) + + # Check if data is up-to-date + if (sm.recv_frame["liveCalibration"] < ui_state.started_frame or + sm.recv_frame["modelV2"] < ui_state.started_frame): + return + + # Set up clipping region + self._clip_region = rl.Rectangle( + rect.x - CLIP_MARGIN, rect.y - CLIP_MARGIN, rect.width + 2 * CLIP_MARGIN, rect.height + 2 * CLIP_MARGIN + ) + + # Update state + self._experimental_mode = sm['selfdriveState'].experimentalMode + + live_calib = sm['liveCalibration'] + self._path_offset_z = live_calib.height[0] if live_calib.height else HEIGHT_INIT[0] + + if sm.updated['carParams']: + self._longitudinal_control = sm['carParams'].openpilotLongitudinalControl + + model = sm['modelV2'] + radar_state = sm['radarState'] if sm.valid['radarState'] else None + lead_one = radar_state.leadOne if radar_state else None + render_lead_indicator = self._longitudinal_control and radar_state is not None + + # Update model data when needed + model_updated = sm.updated['modelV2'] + if model_updated or sm.updated['radarState'] or self._transform_dirty: + if model_updated: + self._update_raw_points(model) + + path_x_array = self._path.raw_points[:, 0] + if path_x_array.size == 0: + return + + self._update_model(lead_one, path_x_array) + if render_lead_indicator: + self._update_leads(radar_state, path_x_array) + self._transform_dirty = False + + # Draw elements (hide when disengaged) + if ui_state.status != UIStatus.DISENGAGED: + self._draw_lane_lines() + self._draw_path(sm) + + # if render_lead_indicator and radar_state: + # self._draw_lead_indicator() + + def _update_raw_points(self, model): + """Update raw 3D points from model data""" + self._path.raw_points = np.array([model.position.x, np.array(model.position.y) + self._camera_offset, model.position.z], dtype=np.float32).T + + for i, lane_line in enumerate(model.laneLines): + self._lane_lines[i].raw_points = np.array([lane_line.x, np.array(lane_line.y) + self._camera_offset, lane_line.z], dtype=np.float32).T + + for i, road_edge in enumerate(model.roadEdges): + self._road_edges[i].raw_points = np.array([road_edge.x, np.array(road_edge.y) + self._camera_offset, road_edge.z], dtype=np.float32).T + + self._lane_line_probs = np.array(model.laneLineProbs, dtype=np.float32) + self._road_edge_stds = np.array(model.roadEdgeStds, dtype=np.float32) + self._acceleration_x = np.array(model.acceleration.x, dtype=np.float32) + + def _update_leads(self, radar_state, path_x_array): + """Update positions of lead vehicles""" + self._lead_vehicles = [LeadVehicle(), LeadVehicle()] + leads = [radar_state.leadOne, radar_state.leadTwo] + + for i, lead_data in enumerate(leads): + if lead_data and lead_data.present: + d_rel, y_rel, v_rel = lead_data.dRel, lead_data.yRel, lead_data.vRel + idx = self._get_path_length_idx(path_x_array, d_rel) + + # Get z-coordinate from path at the lead vehicle position + z = self._path.raw_points[idx, 2] if idx < len(self._path.raw_points) else 0.0 + point = self._map_to_screen(d_rel, -y_rel + self._camera_offset, z + self._path_offset_z) + if point: + self._lead_vehicles[i] = self._update_lead_vehicle(d_rel, v_rel, point, self._rect) + + def _update_model(self, lead, path_x_array): + """Update model visualization data based on model message""" + max_distance = np.clip(path_x_array[-1], MIN_DRAW_DISTANCE, MAX_DRAW_DISTANCE) + max_idx = self._get_path_length_idx(self._lane_lines[0].raw_points[:, 0], max_distance) + + # Update lane lines using raw points + line_width_factor = 0.12 + for i, lane_line in enumerate(self._lane_lines): + if i in (1, 2): + line_width_factor = 0.16 + lane_line.projected_points = self._map_line_to_polygon( + lane_line.raw_points, line_width_factor * self._lane_line_probs[i], 0.0, max_idx + ) + + # Update road edges using raw points + for road_edge in self._road_edges: + road_edge.projected_points = self._map_line_to_polygon(road_edge.raw_points, line_width_factor, 0.0, max_idx) + + # Update path using raw points + if lead and lead.present: + lead_d = lead.dRel * 2.0 + max_distance = np.clip(lead_d - min(lead_d * 0.35, 10.0), 0.0, max_distance) + + soon_acceleration = self._acceleration_x[len(self._acceleration_x) // 4] if len(self._acceleration_x) > 0 else 0 + self._acceleration_x_filter.update(soon_acceleration) + self._acceleration_x_filter2.update(soon_acceleration) + + # make path width wider/thinner when initially braking/accelerating + if self._experimental_mode and False: + high_pass_acceleration = self._acceleration_x_filter.x - self._acceleration_x_filter2.x + y_off = np.interp(high_pass_acceleration, [-1, 0, 1], [0.9 * 2, 0.9, 0.9 / 2]) + else: + y_off = 0.9 + + max_idx = self._get_path_length_idx(path_x_array, max_distance) + self._path.projected_points = self._map_line_to_polygon( + self._path.raw_points, y_off, self._path_offset_z, max_idx, allow_invert=False + ) + + self._update_experimental_gradient() + + def _update_experimental_gradient(self): + """Pre-calculate experimental mode gradient colors""" + if not self._experimental_mode: + return + + path_pts = self._path.projected_points + np.array([self._rect.x, self._rect.y], dtype=np.float32) + max_len = min(len(path_pts) // 2, len(self._acceleration_x)) + + segment_colors = [] + gradient_stops = [] + + i = 0 + while i < max_len: + # Some points (screen space) are out of frame (rect space) + track_y = path_pts[i][1] + if track_y < self._rect.y or track_y > (self._rect.y + self._rect.height): + i += 1 + continue + + # Calculate color based on acceleration (0 is bottom, 1 is top) + lin_grad_point = 1 - (track_y - self._rect.y) / self._rect.height + + # speed up: 120, slow down: 0 + path_hue = np.clip(60 + self._acceleration_x[i] * 35, 0, 120) + + saturation = min(abs(self._acceleration_x[i] * 1.5), 1) + lightness = np.interp(saturation, [0.0, 1.0], [0.95, 0.62]) + alpha = np.interp(lin_grad_point, [0.75 / 2.0, 0.75], [0.4, 0.0]) + + # Use HSL to RGB conversion + color = self._hsla_to_color(path_hue / 360.0, saturation, lightness, alpha) + + gradient_stops.append(lin_grad_point) + segment_colors.append(color) + + # Skip a point, unless next is last + i += 1 + (1 if (i + 2) < max_len else 0) + + # Store the gradient in the path object + self._exp_gradient.colors = segment_colors + self._exp_gradient.stops = gradient_stops + + def _update_lead_vehicle(self, d_rel, v_rel, point, rect): + speed_buff, lead_buff = 10.0, 40.0 + + # Calculate fill alpha + fill_alpha = 0 + if d_rel < lead_buff: + fill_alpha = 255 * (1.0 - (d_rel / lead_buff)) + if v_rel < 0: + fill_alpha += 255 * (-1 * (v_rel / speed_buff)) + fill_alpha = min(fill_alpha, 255) + + # Calculate size and position + sz = np.clip((25 * 30) / (d_rel / 3 + 30), 15.0, 30.0) * 1 + x = np.clip(point[0], 0.0, rect.width - sz / 2) + y = min(point[1], rect.height - sz * 0.6) + + g_xo = sz / 5 + g_yo = sz / 10 + + glow = [(x + (sz * 1.35) + g_xo, y + sz + g_yo), (x, y - g_yo), (x - (sz * 1.35) - g_xo, y + sz + g_yo)] + chevron = [(x + (sz * 1.25), y + sz), (x, y), (x - (sz * 1.25), y + sz)] + + return LeadVehicle(glow=glow, chevron=chevron, fill_alpha=int(fill_alpha)) + + def _get_ll_color(self, prob: float, adjacent: bool, left: bool): + alpha = np.clip(prob, 0.0, 0.7) + if adjacent: + _base_color = LANE_LINE_COLORS.get(ui_state.status, LANE_LINE_COLORS[UIStatus.DISENGAGED]) + color = rl.Color(_base_color.r, _base_color.g, _base_color.b, int(alpha * 255)) + + # turn adjacent lls orange if torque is high + torque = self._torque_filter.x + high_torque = abs(torque) > 0.6 + if high_torque and (left == (torque > 0)): + color = blend_colors( + color, + rl.Color(255, 115, 0, int(alpha * 255)), # orange + np.interp(abs(torque), [0.6, 0.8], [0.0, 1.0]) + ) + else: + color = rl.Color(255, 255, 255, int(alpha * 255)) + + if ui_state.status == UIStatus.DISENGAGED: + color = rl.Color(0, 0, 0, int(alpha * 255)) + + return color + + def _draw_lane_lines(self): + """Draw lane lines and road edges. Two closest lines should be green (lane line or road edges).""" + offset = np.array([self._rect.x, self._rect.y], dtype=np.float32) + + for i, lane_line in enumerate(self._lane_lines): + if lane_line.projected_points.size == 0: + continue + + color = self._get_ll_color(float(self._lane_line_probs[i]), i in (1, 2), i in (0, 1)) + draw_polygon(self._rect, lane_line.projected_points + offset, color) + + for i, road_edge in enumerate(self._road_edges): + if road_edge.projected_points.size == 0: + continue + + # if closest lane lines are not confident, make road edges green + color = self._get_ll_color(float(1.0 - self._road_edge_stds[i]), float(self._lane_line_probs[i + 1]) < 0.25, i == 0) + draw_polygon(self._rect, road_edge.projected_points + offset, color) + + def _draw_path(self, sm): + """Draw path with dynamic coloring based on mode and throttle state.""" + if not self._path.projected_points.size: + return + + allow_throttle = sm['longitudinalPlan'].allowThrottle or not self._longitudinal_control + self._blend_filter.update(int(allow_throttle)) + + if ui_state.rainbow_path: + self.rainbow_path.draw_rainbow_path(self._rect, self._path) + return + + path_pts = self._path.projected_points + np.array([self._rect.x, self._rect.y], dtype=np.float32) + + if self._experimental_mode: + # Draw with acceleration coloring + if ui_state.status == UIStatus.DISENGAGED: + draw_polygon(self._rect, path_pts, rl.Color(0, 0, 0, 90)) + elif len(self._exp_gradient.colors) > 1: + draw_polygon(self._rect, path_pts, gradient=self._exp_gradient) + else: + draw_polygon(self._rect, path_pts, rl.Color(255, 255, 255, 30)) + else: + # Blend throttle/no throttle colors based on transition + blend_factor = round(self._blend_filter.x * 100) / 100 + blended_colors = self._blend_colors(NO_THROTTLE_COLORS, THROTTLE_COLORS, blend_factor) + gradient = Gradient( + start=(0.0, 1.0), # Bottom of path + end=(0.0, 0.0), # Top of path + colors=blended_colors, + stops=[0.0, 0.5, 1.0], + ) + + if ui_state.status == UIStatus.DISENGAGED: + draw_polygon(self._rect, path_pts, rl.Color(0, 0, 0, 90)) + else: + draw_polygon(self._rect, path_pts, gradient=gradient) + + def _draw_lead_indicator(self): + # Draw lead vehicles if available + for lead in self._lead_vehicles: + if not lead.glow or not lead.chevron: + continue + + rl.draw_triangle_fan(lead.glow, len(lead.glow), rl.Color(218, 202, 37, 255)) + rl.draw_triangle_fan(lead.chevron, len(lead.chevron), rl.Color(201, 34, 49, lead.fill_alpha)) + + @staticmethod + def _get_path_length_idx(pos_x_array: np.ndarray, path_height: float) -> int: + """Get the index corresponding to the given path height""" + if len(pos_x_array) == 0: + return 0 + indices = np.where(pos_x_array <= path_height)[0] + return indices[-1] if indices.size > 0 else 0 + + def _map_to_screen(self, in_x, in_y, in_z): + """Project a point in car space to screen space""" + input_pt = np.array([in_x, in_y, in_z]) + pt = self._car_space_transform @ input_pt + + if abs(pt[2]) < 1e-6: + return None + + x, y = pt[0] / pt[2], pt[1] / pt[2] + + clip = self._clip_region + if not (clip.x <= x <= clip.x + clip.width and clip.y <= y <= clip.y + clip.height): + return None + + return (x, y) + + def _map_line_to_polygon(self, line: np.ndarray, y_off: float, z_off: float, max_idx: int, allow_invert: bool = True) -> np.ndarray: + """Convert 3D line to 2D polygon for rendering.""" + if line.shape[0] == 0: + return np.empty((0, 2), dtype=np.float32) + + # Slice points and filter non-negative x-coordinates + points = line[:max_idx + 1] + points = points[points[:, 0] >= 0] + if points.shape[0] == 0: + return np.empty((0, 2), dtype=np.float32) + + N = points.shape[0] + # Generate left and right 3D points in one array using broadcasting + offsets = np.array([[0, -y_off, z_off], [0, y_off, z_off]], dtype=np.float32) + points_3d = points[None, :, :] + offsets[:, None, :] # Shape: 2xNx3 + points_3d = points_3d.reshape(2 * N, 3) # Shape: (2*N)x3 + + # Transform all points to projected space in one operation + proj = self._car_space_transform @ points_3d.T # Shape: 3x(2*N) + proj = proj.reshape(3, 2, N) + left_proj = proj[:, 0, :] + right_proj = proj[:, 1, :] + + # Filter points where z is sufficiently large + valid_proj = (np.abs(left_proj[2]) >= 1e-6) & (np.abs(right_proj[2]) >= 1e-6) + if not np.any(valid_proj): + return np.empty((0, 2), dtype=np.float32) + + # Compute screen coordinates + left_screen = left_proj[:2, valid_proj] / left_proj[2, valid_proj][None, :] + right_screen = right_proj[:2, valid_proj] / right_proj[2, valid_proj][None, :] + + # Define clip region bounds + clip = self._clip_region + x_min, x_max = clip.x, clip.x + clip.width + y_min, y_max = clip.y, clip.y + clip.height + + # Filter points within clip region + left_in_clip = ( + (left_screen[0] >= x_min) & (left_screen[0] <= x_max) & + (left_screen[1] >= y_min) & (left_screen[1] <= y_max) + ) + right_in_clip = ( + (right_screen[0] >= x_min) & (right_screen[0] <= x_max) & + (right_screen[1] >= y_min) & (right_screen[1] <= y_max) + ) + both_in_clip = left_in_clip & right_in_clip + + if not np.any(both_in_clip): + return np.empty((0, 2), dtype=np.float32) + + # Select valid and clipped points + left_screen = left_screen[:, both_in_clip] + right_screen = right_screen[:, both_in_clip] + + # Handle Y-coordinate inversion on hills + if not allow_invert and left_screen.shape[1] > 1: + y = left_screen[1, :] # y-coordinates + keep = y == np.minimum.accumulate(y) + if not np.any(keep): + return np.empty((0, 2), dtype=np.float32) + left_screen = left_screen[:, keep] + right_screen = right_screen[:, keep] + + return np.vstack((left_screen.T, right_screen[:, ::-1].T)).astype(np.float32) + + @staticmethod + def _hsla_to_color(h, s, l, a): + rgb = colorsys.hls_to_rgb(h, l, s) + return rl.Color( + int(rgb[0] * 255), + int(rgb[1] * 255), + int(rgb[2] * 255), + int(a * 255) + ) + + @staticmethod + def _blend_colors(begin_colors, end_colors, t): + if t >= 1.0: + return end_colors + if t <= 0.0: + return begin_colors + + inv_t = 1.0 - t + return [rl.Color( + int(inv_t * start.r + t * end.r), + int(inv_t * start.g + t * end.g), + int(inv_t * start.b + t * end.b), + int(inv_t * start.a + t * end.a) + ) for start, end in zip(begin_colors, end_colors, strict=True)] diff --git a/openpilot/selfdrive/ui/mici/onroad/torque_bar.py b/openpilot/selfdrive/ui/mici/onroad/torque_bar.py new file mode 100644 index 0000000000..85edd89e98 --- /dev/null +++ b/openpilot/selfdrive/ui/mici/onroad/torque_bar.py @@ -0,0 +1,268 @@ +import math +import time +from functools import wraps +from collections import OrderedDict + +import numpy as np +import pyray as rl +from opendbc.car import ACCELERATION_DUE_TO_GRAVITY +from openpilot.selfdrive.ui.mici.onroad import blend_colors +from openpilot.selfdrive.ui.ui_state import ui_state, UIStatus +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.lib.shader_polygon import draw_polygon, Gradient +from openpilot.system.ui.widgets import Widget +from openpilot.common.filter_simple import FirstOrderFilter + +# TODO: arc_bar_pts doesn't consider rounded end caps part of the angle span +TORQUE_ANGLE_SPAN = 12.7 + +DEBUG = False + + +def quantized_lru_cache(maxsize=128): + def decorator(func): + cache = OrderedDict() + @wraps(func) + def wrapper(r_mid, thickness, a0_deg, a1_deg, **kwargs): + # Quantize inputs: balanced for smoothness vs cache effectiveness + key = (round(r_mid), + round(thickness), # 1px precision for smoother height transitions + round(a0_deg * 10) / 10, # 0.1° precision for smoother angle transitions + round(a1_deg * 10) / 10, + tuple(sorted(kwargs.items()))) + + if key in cache: + cache.move_to_end(key) + else: + if len(cache) >= maxsize: + cache.popitem(last=False) + + result = func(r_mid, thickness, a0_deg, a1_deg, **kwargs) + cache[key] = result + return cache[key] + return wrapper + return decorator + + +@quantized_lru_cache(maxsize=256) +def arc_bar_pts(r_mid: float, thickness: float, + a0_deg: float, a1_deg: float, + *, max_points: int = 100, cap_segs: int = 10, + cap_radius: float = 7, px_per_seg: float = 2.0) -> np.ndarray: + """Return Nx2 np.float32 points for a single closed polygon (rounded thick arc), centered at origin.""" + + def get_cap(left: bool, a_deg: float): + # end cap at a1: center (a1), sweep a1→a1+180 (skip endpoints to avoid dupes) + # quarter arc (outer corner) at a1 with fixed pixel radius cap_radius + + nx, ny = math.cos(math.radians(a_deg)), math.sin(math.radians(a_deg)) # outward normal + tx, ty = -ny, nx # tangent (CCW) + + mx, my = nx * r_mid, ny * r_mid # mid-point at a1 + if DEBUG: + rl.draw_circle(int(mx), int(my), 4, rl.PURPLE) + + ex = mx + nx * (half - cap_radius) + ey = my + ny * (half - cap_radius) + + if DEBUG: + rl.draw_circle(int(ex), int(ey), 2, rl.WHITE) + + # sweep 90° in the local (t,n) frame: from outer edge toward inside + if not left: + alpha = np.deg2rad(np.linspace(90, 0, cap_segs + 2))[1:-1] + else: + alpha = np.deg2rad(np.linspace(180, 90, cap_segs + 2))[1:-1] + cap_end = np.c_[ex + np.cos(alpha) * cap_radius * tx + np.sin(alpha) * cap_radius * nx, + ey + np.cos(alpha) * cap_radius * ty + np.sin(alpha) * cap_radius * ny] + + # bottom quarter (inner corner) at a1 + ex2 = mx + nx * (-half + cap_radius) + ey2 = my + ny * (-half + cap_radius) + if DEBUG: + rl.draw_circle(int(ex2), int(ey2), 2, rl.WHITE) + + if not left: + alpha2 = np.deg2rad(np.linspace(0, -90, cap_segs + 1))[:-1] # include 0 once, exclude -90 + else: + alpha2 = np.deg2rad(np.linspace(90 - 90 - 90, 0 - 90 - 90, cap_segs + 1))[:-1] + cap_end_bot = np.c_[ex2 + np.cos(alpha2) * cap_radius * tx + np.sin(alpha2) * cap_radius * nx, + ey2 + np.cos(alpha2) * cap_radius * ty + np.sin(alpha2) * cap_radius * ny] + + # append to the top quarter + if not left: + cap_end = np.vstack((cap_end, cap_end_bot)) + else: + cap_end = np.vstack((cap_end_bot, cap_end)) + + return cap_end + + if a1_deg < a0_deg: + a0_deg, a1_deg = a1_deg, a0_deg + half = thickness * 0.5 + + cap_radius = min(cap_radius, half) + + span = max(1e-3, a1_deg - a0_deg) + + # pick arc segment count from arc length, clamp to shader points[] budget + arc_len = r_mid * math.radians(span) + arc_segs = max(6, int(arc_len / px_per_seg)) + max_arc = (max_points - (4 * cap_segs + 3)) // 2 + arc_segs = max(6, min(arc_segs, max_arc)) + + # outer arc a0→a1 + ang_o = np.deg2rad(np.linspace(a0_deg, a1_deg, arc_segs + 1)) + outer = np.c_[np.cos(ang_o) * (r_mid + half), + np.sin(ang_o) * (r_mid + half)] + + # end cap at a1 + cap_end = get_cap(False, a1_deg) + + # inner arc a1→a0 + ang_i = np.deg2rad(np.linspace(a1_deg, a0_deg, arc_segs + 1)) + inner = np.c_[np.cos(ang_i) * (r_mid - half), + np.sin(ang_i) * (r_mid - half)] + + # start cap at a0 + cap_start = get_cap(True, a0_deg) + + pts = np.vstack((outer, cap_end, inner, cap_start, outer[:1])).astype(np.float32) + + # Rotate to start from middle of cap for proper triangulation + pts = np.roll(pts, cap_segs, axis=0) + + if DEBUG: + n = len(pts) + idx = int(time.monotonic() * 12) % max(1, n) # speed: 12 pts/sec + for i, (x, y) in enumerate(pts): + j = (i - idx) % n # rotate the gradient + t = j / n + color = rl.Color(255, int(255 * (1 - t)), int(255 * t), 255) + rl.draw_circle(int(x), int(y), 2, color) + + return pts + + +DEFAULT_MAX_LAT_ACCEL = 3.0 # m/s^2 + + +class TorqueBar(Widget): + def __init__(self, demo: bool = False, scale: float = 1.0, always: bool = False): + super().__init__() + self._demo = demo + self._scale = scale + self._always = always + self._torque_filter = FirstOrderFilter(0, 0.1, 1 / gui_app.target_fps) + self._torque_line_alpha_filter = FirstOrderFilter(0.0, 0.1, 1 / gui_app.target_fps) + + def update_filter(self, value: float): + """Update the torque filter value (for demo mode).""" + self._torque_filter.update(value) + + def _update_state(self): + if self._demo: + return + + # torque line + if ui_state.sm['controlsState'].lateralControlState.which() in ('angleState', 'curvatureState'): + controls_state = ui_state.sm['controlsState'] + car_state = ui_state.sm['carState'] + live_parameters = ui_state.sm['liveParameters'] + car_control = ui_state.sm['carControl'] + + # Include lateral accel error in estimated torque utilization + actual_lateral_accel = controls_state.curvature * car_state.vEgo ** 2 + desired_lateral_accel = controls_state.desiredCurvature * car_state.vEgo ** 2 + accel_diff = (desired_lateral_accel - actual_lateral_accel) + + # Include road roll in estimated torque utilization + # Roll is less accurate near standstill, so reduce its effect at low speed + roll_compensation = live_parameters.roll * ACCELERATION_DUE_TO_GRAVITY * np.interp(car_state.vEgo, [5, 15], [0.0, 1.0]) + lateral_acceleration = actual_lateral_accel - roll_compensation + max_lateral_acceleration = ui_state.CP.maxLateralAccel if ui_state.CP else DEFAULT_MAX_LAT_ACCEL + + if not car_control.latActive: + self._torque_filter.update(0.0) + else: + self._torque_filter.update(np.clip((lateral_acceleration + accel_diff) / max_lateral_acceleration, -1, 1)) + else: + self._torque_filter.update(-ui_state.sm['carOutput'].actuatorsOutput.torque) + + def _render(self, rect: rl.Rectangle) -> None: + # adjust y pos with torque + torque_line_offset = np.interp(abs(self._torque_filter.x), [0.5, 1], [22 * self._scale, 26 * self._scale]) + torque_line_height = np.interp(abs(self._torque_filter.x), [0.5, 1], [14 * self._scale, 56 * self._scale]) + + # animate alpha and angle span + if not self._demo: + self._torque_line_alpha_filter.update(ui_state.status not in (UIStatus.DISENGAGED, UIStatus.LONG_ONLY)) + else: + self._torque_line_alpha_filter.update(1.0) + + torque_line_bg_alpha = np.interp(abs(self._torque_filter.x), [0.5, 1.0], [0.25, 0.5]) + torque_line_bg_color = rl.Color(255, 255, 255, int(255 * torque_line_bg_alpha * self._torque_line_alpha_filter.x)) + if ui_state.status not in (UIStatus.ENGAGED, UIStatus.LAT_ONLY) and not self._demo: + torque_line_bg_color = rl.Color(255, 255, 255, int(255 * 0.15 * self._torque_line_alpha_filter.x)) + + # draw curved line polygon torque bar + torque_line_radius = 1200 * self._scale + top_angle = -90 + torque_bg_angle_span = self._torque_line_alpha_filter.x * TORQUE_ANGLE_SPAN + torque_start_angle = top_angle - torque_bg_angle_span / 2 + torque_end_angle = top_angle + torque_bg_angle_span / 2 + # centerline radius & center (you already have these values) + mid_r = torque_line_radius + torque_line_height / 2 + + cx = rect.x + rect.width / 2 + 8 # offset 8px to right of camera feed + cy = rect.y + rect.height + torque_line_radius - torque_line_offset + offset = np.array([cx, cy], dtype=np.float32) + + # draw bg torque indicator line + bg_pts = arc_bar_pts(mid_r, torque_line_height, torque_start_angle, torque_end_angle, cap_radius=7 * self._scale) + offset + draw_polygon(rect, bg_pts, color=torque_line_bg_color) + + # draw torque indicator line + a0s = top_angle + a1s = a0s + torque_bg_angle_span / 2 * self._torque_filter.x + sl_pts = arc_bar_pts(mid_r, torque_line_height, a0s, a1s, cap_radius=7 * self._scale) + offset + + # draw beautiful gradient from center to 65% of the bg torque bar width + start_grad_pt = cx / rect.width + if self._torque_filter.x < 0: + end_grad_pt = (cx * (1 - 0.65) + (min(bg_pts[:, 0]) * 0.65)) / rect.width + else: + end_grad_pt = (cx * (1 - 0.65) + (max(bg_pts[:, 0]) * 0.65)) / rect.width + + # fade to orange as we approach max torque + start_color = blend_colors( + rl.Color(255, 255, 255, int(255 * 0.9 * self._torque_line_alpha_filter.x)), + rl.Color(255, 200, 0, int(255 * self._torque_line_alpha_filter.x)), # yellow + max(0, abs(self._torque_filter.x) - 0.75) * 4, + ) + end_color = blend_colors( + rl.Color(255, 255, 255, int(255 * 0.9 * self._torque_line_alpha_filter.x)), + rl.Color(255, 115, 0, int(255 * self._torque_line_alpha_filter.x)), # orange + max(0, abs(self._torque_filter.x) - 0.75) * 4, + ) + + if ui_state.status not in (UIStatus.ENGAGED, UIStatus.LAT_ONLY) and not self._demo: + start_color = end_color = rl.Color(255, 255, 255, int(255 * 0.35 * self._torque_line_alpha_filter.x)) + + gradient = Gradient( + start=(start_grad_pt, 0), + end=(end_grad_pt, 0), + colors=[ + start_color, + end_color, + ], + stops=[0.0, 1.0], + ) + + draw_polygon(rect, sl_pts, gradient=gradient) + + # draw center torque bar dot + if abs(self._torque_filter.x) < 0.5: + dot_y = self._rect.y + self._rect.height - torque_line_offset - torque_line_height / 2 + rl.draw_circle(int(cx), int(dot_y), (10 // 2 * self._scale), + rl.Color(182, 182, 182, int(255 * 0.9 * self._torque_line_alpha_filter.x))) diff --git a/openpilot/selfdrive/ui/mici/tests/test_widget_leaks.py b/openpilot/selfdrive/ui/mici/tests/test_widget_leaks.py new file mode 100755 index 0000000000..68c61f4ff3 --- /dev/null +++ b/openpilot/selfdrive/ui/mici/tests/test_widget_leaks.py @@ -0,0 +1,121 @@ +import gc +import weakref +import pytest + +# FIXME: known small leaks not worth worrying about at the moment +KNOWN_LEAKS = { + "openpilot.selfdrive.ui.mici.onroad.driver_camera_dialog.DriverCameraView", + "openpilot.selfdrive.ui.mici.layouts.onboarding.TermsPage", + "openpilot.selfdrive.ui.mici.layouts.onboarding.TrainingGuide", + "openpilot.selfdrive.ui.mici.layouts.onboarding.DeclinePage", + "openpilot.selfdrive.ui.mici.layouts.onboarding.OnboardingWindow", + "openpilot.selfdrive.ui.onroad.driver_state.DriverStateRenderer", + "openpilot.selfdrive.ui.onroad.driver_camera_dialog.DriverCameraDialog", + "openpilot.selfdrive.ui.layouts.onboarding.TermsPage", + "openpilot.selfdrive.ui.layouts.onboarding.DeclinePage", + "openpilot.selfdrive.ui.layouts.onboarding.OnboardingWindow", + "openpilot.system.ui.widgets.confirm_dialog.ConfirmDialog", + "openpilot.system.ui.widgets.label.Label", + "openpilot.system.ui.widgets.button.Button", + "openpilot.system.ui.widgets.html_render.HtmlRenderer", + "openpilot.system.ui.widgets.nav_widget.NavBar", + "openpilot.selfdrive.ui.mici.layouts.settings.device.MiciFccModal", + "openpilot.system.ui.widgets.inputbox.InputBox", + "openpilot.system.ui.widgets.scroller_tici.Scroller", + "openpilot.system.ui.widgets.label.UnifiedLabel", + "openpilot.system.ui.widgets.mici_keyboard.MiciKeyboard", + "openpilot.selfdrive.ui.mici.widgets.dialog.BigConfirmationDialog", + "openpilot.system.ui.widgets.keyboard.Keyboard", + "openpilot.system.ui.widgets.slider.BigSlider", + "openpilot.selfdrive.ui.mici.widgets.dialog.BigInputDialog", + "openpilot.system.ui.widgets.option_dialog.MultiOptionDialog", +} + + +def get_child_widgets(widget) -> list: + from openpilot.system.ui.widgets import Widget + children = [] + for val in widget.__dict__.values(): + items = val if isinstance(val, (list, tuple)) else (val,) + children.extend(w for w in items if isinstance(w, Widget)) + return children + + +class TestWidgetLeaks: + @pytest.mark.skip(reason="segfaults") + def test_dialogs_do_not_leak(self): + import pyray as rl + rl.set_config_flags(rl.ConfigFlags.FLAG_WINDOW_HIDDEN) + from openpilot.system.ui.lib.application import gui_app + + # mici dialogs + from openpilot.selfdrive.ui.mici.layouts.onboarding import TrainingGuide as MiciTrainingGuide, OnboardingWindow as MiciOnboardingWindow + from openpilot.selfdrive.ui.mici.onroad.driver_camera_dialog import DriverCameraDialog as MiciDriverCameraDialog + from openpilot.selfdrive.ui.mici.widgets.pairing_dialog import PairingDialog as MiciPairingDialog + from openpilot.selfdrive.ui.mici.widgets.dialog import BigDialog, BigConfirmationDialog, BigInputDialog + from openpilot.selfdrive.ui.mici.layouts.settings.device import MiciFccModal + + # tici dialogs + from openpilot.selfdrive.ui.onroad.driver_camera_dialog import DriverCameraDialog as TiciDriverCameraDialog + from openpilot.selfdrive.ui.layouts.onboarding import OnboardingWindow as TiciOnboardingWindow + from openpilot.selfdrive.ui.widgets.pairing_dialog import PairingDialog as TiciPairingDialog + from openpilot.system.ui.widgets.confirm_dialog import ConfirmDialog + from openpilot.system.ui.widgets.option_dialog import MultiOptionDialog + from openpilot.system.ui.widgets.html_render import HtmlModal + from openpilot.system.ui.widgets.keyboard import Keyboard + + gui_app.init_window("ref-test") + + leaked_widgets = set() + + for ctor in ( + # mici + MiciDriverCameraDialog, MiciPairingDialog, + lambda: MiciTrainingGuide(lambda: None), + lambda: MiciOnboardingWindow(lambda: None), + lambda: BigDialog("test", "test"), + lambda: BigConfirmationDialog("test", gui_app.texture("icons_mici/settings/network/new/trash.png", 54, 64), lambda: None), + lambda: BigInputDialog("test"), + lambda: MiciFccModal(text="test"), + # tici + TiciDriverCameraDialog, TiciOnboardingWindow, TiciPairingDialog, Keyboard, + lambda: ConfirmDialog("test", "ok"), + lambda: MultiOptionDialog("test", ["a", "b"]), + lambda: HtmlModal(text="test"), + ): + widget = ctor() + all_refs = [weakref.ref(w) for w in get_child_widgets(widget) + [widget]] + + del widget + + for ref in all_refs: + if ref() is not None: + obj = ref() + name = f"{type(obj).__module__}.{type(obj).__qualname__}" + leaked_widgets.add(name) + + print(f"\n=== Widget {name} alive after del") + print(" Referrers:") + for r in gc.get_referrers(obj): + if r is obj: + continue + + if hasattr(r, '__self__') and r.__self__ is not obj: + print(f" bound method: {type(r.__self__).__qualname__}.{r.__name__}") + elif hasattr(r, '__func__'): + print(f" method: {r.__name__}") + else: + print(f" {type(r).__module__}.{type(r).__qualname__}") + del obj + + gui_app.close() + + unexpected = leaked_widgets - KNOWN_LEAKS + assert not unexpected, f"New leaked widgets: {unexpected}" + + fixed = KNOWN_LEAKS - leaked_widgets + assert not fixed, f"These leaks are fixed, remove from KNOWN_LEAKS: {fixed}" + + +if __name__ == "__main__": + TestWidgetLeaks().test_dialogs_do_not_leak() diff --git a/openpilot/selfdrive/ui/mici/widgets/button.py b/openpilot/selfdrive/ui/mici/widgets/button.py new file mode 100644 index 0000000000..3dd7ad9a8a --- /dev/null +++ b/openpilot/selfdrive/ui/mici/widgets/button.py @@ -0,0 +1,425 @@ +import math +import pyray as rl +from typing import Union +from enum import Enum +from collections.abc import Callable +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.label import UnifiedLabel +from openpilot.system.ui.widgets.scroller import DO_ZOOM +from openpilot.system.ui.lib.application import gui_app, FontWeight, MousePos +from openpilot.common.filter_simple import BounceFilter + +try: + from openpilot.common.params import Params +except ImportError: + Params = None + +SCROLLING_SPEED_PX_S = 50 +COMPLICATION_SIZE = 36 +LABEL_COLOR = rl.Color(255, 255, 255, int(255 * 0.9)) +COMPLICATION_GREY = rl.Color(0xAA, 0xAA, 0xAA, 255) +PRESSED_SCALE = 1.15 if DO_ZOOM else 1.07 + + +class ScrollState(Enum): + PRE_SCROLL = 0 + SCROLLING = 1 + POST_SCROLL = 2 + + +class BigCircleButton(Widget): + def __init__(self, icon: rl.Texture, red: bool = False, icon_offset: tuple[int, int] = (0, 0)): + super().__init__() + self._red = red + self._icon_offset = icon_offset + + # State + self.set_rect(rl.Rectangle(0, 0, 180, 180)) + self._scale_filter = BounceFilter(1.0, 0.1, 1 / gui_app.target_fps) + self._click_delay = 0.075 + + # Icons + self._txt_icon = icon + self._txt_btn_disabled_bg = gui_app.texture("icons_mici/buttons/button_circle_disabled.png", 180, 180) + + self._txt_btn_bg = gui_app.texture("icons_mici/buttons/button_circle.png", 180, 180) + self._txt_btn_pressed_bg = gui_app.texture("icons_mici/buttons/button_circle_pressed.png", 180, 180) + + self._txt_btn_red_bg = gui_app.texture("icons_mici/buttons/button_circle_red.png", 180, 180) + self._txt_btn_red_pressed_bg = gui_app.texture("icons_mici/buttons/button_circle_red_pressed.png", 180, 180) + + def _draw_content(self, btn_y: float): + # draw icon + icon_color = rl.Color(255, 255, 255, int(255 * 0.9)) if self.enabled else rl.Color(255, 255, 255, int(255 * 0.35)) + rl.draw_texture_ex(self._txt_icon, (self._rect.x + (self._rect.width - self._txt_icon.width) / 2 + self._icon_offset[0], + btn_y + (self._rect.height - self._txt_icon.height) / 2 + self._icon_offset[1]), 0, 1.0, icon_color) + + def _render(self, _): + # draw background + txt_bg = self._txt_btn_bg if not self._red else self._txt_btn_red_bg + if not self.enabled: + txt_bg = self._txt_btn_disabled_bg + elif self.is_pressed: + txt_bg = self._txt_btn_pressed_bg if not self._red else self._txt_btn_red_pressed_bg + + scale = self._scale_filter.update(PRESSED_SCALE if self.is_pressed else 1.0) + btn_x = self._rect.x + (self._rect.width * (1 - scale)) / 2 + btn_y = self._rect.y + (self._rect.height * (1 - scale)) / 2 + rl.draw_texture_ex(txt_bg, (btn_x, btn_y), 0, scale, rl.WHITE) + + self._draw_content(btn_y) + + +class BigCircleToggle(BigCircleButton): + def __init__(self, icon: rl.Texture, toggle_callback: Callable | None = None, icon_offset: tuple[int, int] = (0, 0)): + super().__init__(icon, False, icon_offset=icon_offset) + self._toggle_callback = toggle_callback + + # State + self._checked = False + + # Icons + self._txt_toggle_enabled = gui_app.texture("icons_mici/buttons/toggle_dot_enabled.png", 66, 66) + self._txt_toggle_disabled = gui_app.texture("icons_mici/buttons/toggle_dot_disabled.png", 66, 66) + + def set_checked(self, checked: bool): + self._checked = checked + + def _handle_mouse_release(self, mouse_pos: MousePos): + super()._handle_mouse_release(mouse_pos) + + self._checked = not self._checked + if self._toggle_callback: + self._toggle_callback(self._checked) + + def _draw_content(self, btn_y: float): + super()._draw_content(btn_y) + + # draw status icon + rl.draw_texture_ex(self._txt_toggle_enabled if self._checked else self._txt_toggle_disabled, + (self._rect.x + (self._rect.width - self._txt_toggle_enabled.width) / 2, btn_y + 5), + 0, 1.0, rl.WHITE) + + +class BigButton(Widget): + LABEL_HORIZONTAL_PADDING = 40 + LABEL_VERTICAL_PADDING = 23 # visually matches 30 in figma + + """A lightweight stand-in for the Qt BigButton, drawn & updated each frame.""" + + def __init__(self, text: str, value: str = "", icon: Union[rl.Texture, None] = None, scroll: bool = False): + super().__init__() + self.set_rect(rl.Rectangle(0, 0, 402, 180)) + self.text = text + self.value = value + self._txt_icon = icon + self._scroll = scroll + + self._scale_filter = BounceFilter(1.0, 0.1, 1 / gui_app.target_fps) + self._click_delay = 0.075 + self._shake_start: float | None = None + self._grow_animation_until: float | None = None + + self._rotate_icon_t: float | None = None + + self._label = UnifiedLabel(text, font_size=self._get_label_font_size(), font_weight=FontWeight.BOLD, + text_color=LABEL_COLOR, alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_BOTTOM, scroll=scroll, + line_height=0.9) + self._sub_label = UnifiedLabel(value, font_size=COMPLICATION_SIZE, font_weight=FontWeight.ROMAN, + text_color=COMPLICATION_GREY, alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_BOTTOM) + self._update_label_layout() + + self._load_images() + + def set_icon(self, icon: Union[rl.Texture, None]): + self._txt_icon = icon + + def set_rotate_icon(self, rotate: bool): + if rotate and self._rotate_icon_t is not None: + return + self._rotate_icon_t = rl.get_time() if rotate else None + + def _load_images(self): + self._txt_default_bg = gui_app.texture("icons_mici/buttons/button_rectangle.png", 402, 180) + self._txt_pressed_bg = gui_app.texture("icons_mici/buttons/button_rectangle_pressed.png", 402, 180) + self._txt_disabled_bg = gui_app.texture("icons_mici/buttons/button_rectangle_disabled.png", 402, 180) + + def set_touch_valid_callback(self, touch_callback: Callable[[], bool]) -> None: + super().set_touch_valid_callback(lambda: touch_callback() and self._grow_animation_until is None) + + def _width_hint(self) -> int: + # Single line if scrolling, so hide behind icon if exists + icon_size = self._txt_icon.width if self._txt_icon and self._scroll and self.value else 0 + return int(self._rect.width - self.LABEL_HORIZONTAL_PADDING * 2 - icon_size) + + def _get_label_font_size(self): + if len(self.text) <= 18: + return 48 + else: + return 42 + + def _update_label_layout(self): + self._label.set_font_size(self._get_label_font_size()) + if self.value: + self._label.set_alignment_vertical(rl.GuiTextAlignmentVertical.TEXT_ALIGN_TOP) + else: + self._label.set_alignment_vertical(rl.GuiTextAlignmentVertical.TEXT_ALIGN_BOTTOM) + + def set_text(self, text: str): + self.text = text + self._label.set_text(text) + self._update_label_layout() + + def set_value(self, value: str): + self.value = value + self._sub_label.set_text(value) + self._update_label_layout() + + def get_value(self) -> str: + return self.value + + def get_text(self): + return self.text + + def trigger_shake(self): + self._shake_start = rl.get_time() + + def trigger_grow_animation(self, duration: float = 0.65): + self._grow_animation_until = rl.get_time() + duration + + @property + def _shake_offset(self) -> float: + SHAKE_DURATION = 0.5 + SHAKE_AMPLITUDE = 24.0 + SHAKE_FREQUENCY = 32.0 + if self._shake_start is None: + return 0.0 + t = rl.get_time() - self._shake_start + if t > SHAKE_DURATION: + return 0.0 + decay = 1.0 - t / SHAKE_DURATION + return decay * SHAKE_AMPLITUDE * math.sin(t * SHAKE_FREQUENCY) + + def set_position(self, x: float, y: float) -> None: + super().set_position(x + self._shake_offset, y) + + def _handle_background(self) -> tuple[rl.Texture, float, float, float]: + if self._grow_animation_until is not None: + if rl.get_time() >= self._grow_animation_until: + self._grow_animation_until = None + + # draw _txt_default_bg + txt_bg = self._txt_default_bg + if not self.enabled: + txt_bg = self._txt_disabled_bg + elif self.is_pressed: + txt_bg = self._txt_pressed_bg + + scale = self._scale_filter.update(PRESSED_SCALE if self.is_pressed or self._grow_animation_until is not None else 1.0) + btn_x = self._rect.x + (self._rect.width * (1 - scale)) / 2 + btn_y = self._rect.y + (self._rect.height * (1 - scale)) / 2 + return txt_bg, btn_x, btn_y, scale + + def _draw_content(self, btn_y: float): + # LABEL ------------------------------------------------------------------ + label_x = self._rect.x + self.LABEL_HORIZONTAL_PADDING + + label_color = LABEL_COLOR if self.enabled else rl.Color(255, 255, 255, int(255 * 0.35)) + self._label.set_color(label_color) + label_rect = rl.Rectangle(label_x, btn_y + self.LABEL_VERTICAL_PADDING, self._width_hint(), + self._rect.height - self.LABEL_VERTICAL_PADDING * 2) + self._label.render(label_rect) + + if self.value: + label_y = btn_y + self.LABEL_VERTICAL_PADDING + self._label.get_content_height(self._width_hint()) + sub_label_height = btn_y + self._rect.height - self.LABEL_VERTICAL_PADDING - label_y + sub_label_rect = rl.Rectangle(label_x, label_y, self._width_hint(), sub_label_height) + self._sub_label.render(sub_label_rect) + + # ICON ------------------------------------------------------------------- + if self._txt_icon: + rotation = 0 + if self._rotate_icon_t is not None: + rotation = (rl.get_time() - self._rotate_icon_t) * 180 + + # draw top right with 30px padding + x = self._rect.x + self._rect.width - 30 - self._txt_icon.width / 2 + y = btn_y + 30 + self._txt_icon.height / 2 + source_rec = rl.Rectangle(0, 0, self._txt_icon.width, self._txt_icon.height) + dest_rec = rl.Rectangle(x, y, self._txt_icon.width, self._txt_icon.height) + origin = rl.Vector2(self._txt_icon.width / 2, self._txt_icon.height / 2) + rl.draw_texture_pro(self._txt_icon, source_rec, dest_rec, origin, rotation, rl.Color(255, 255, 255, int(255 * 0.9))) + + def _render(self, _): + txt_bg, btn_x, btn_y, scale = self._handle_background() + + if self._scroll: + # draw black background since images are transparent + scaled_rect = rl.Rectangle(btn_x, btn_y, self._rect.width * scale, self._rect.height * scale) + rl.draw_rectangle_rounded(scaled_rect, 0.4, 7, rl.Color(0, 0, 0, int(255 * 0.5))) + + self._draw_content(btn_y) + rl.draw_texture_ex(txt_bg, (btn_x, btn_y), 0, scale, rl.WHITE) + else: + rl.draw_texture_ex(txt_bg, (btn_x, btn_y), 0, scale, rl.WHITE) + self._draw_content(btn_y) + + +class BigToggle(BigButton): + def __init__(self, text: str, value: str = "", initial_state: bool = False, toggle_callback: Callable | None = None): + super().__init__(text, value, "") + self._checked = initial_state + self._toggle_callback = toggle_callback + + def _load_images(self): + super()._load_images() + self._txt_enabled_toggle = gui_app.texture("icons_mici/buttons/toggle_pill_enabled.png", 84, 66) + self._txt_disabled_toggle = gui_app.texture("icons_mici/buttons/toggle_pill_disabled.png", 84, 66) + + def set_checked(self, checked: bool): + self._checked = checked + + def _handle_mouse_release(self, mouse_pos: MousePos): + super()._handle_mouse_release(mouse_pos) + self._checked = not self._checked + if self._toggle_callback: + self._toggle_callback(self._checked) + + def _draw_pill(self, x: float, y: float, checked: bool): + # draw toggle icon top right + if checked: + rl.draw_texture_ex(self._txt_enabled_toggle, (x, y), 0, 1.0, rl.WHITE) + else: + rl.draw_texture_ex(self._txt_disabled_toggle, (x, y), 0, 1.0, rl.WHITE) + + def _draw_content(self, btn_y: float): + super()._draw_content(btn_y) + + x = self._rect.x + self._rect.width - self._txt_enabled_toggle.width + y = btn_y + self._draw_pill(x, y, self._checked) + + +class BigMultiToggle(BigToggle): + def __init__(self, text: str, options: list[str], toggle_callback: Callable | None = None, + select_callback: Callable | None = None): + super().__init__(text, "", toggle_callback=toggle_callback) + assert len(options) > 0 + self._options = options + self._select_callback = select_callback + + self.set_value(self._options[0]) + + def _width_hint(self) -> int: + return int(self._rect.width - self.LABEL_HORIZONTAL_PADDING * 2 - self._txt_enabled_toggle.width) + + def _handle_mouse_release(self, mouse_pos: MousePos): + super()._handle_mouse_release(mouse_pos) + cur_idx = self._options.index(self.value) + new_idx = (cur_idx + 1) % len(self._options) + self.set_value(self._options[new_idx]) + if self._select_callback: + self._select_callback(self.value) + + def _draw_content(self, btn_y: float): + # don't draw pill from BigToggle + BigButton._draw_content(self, btn_y) + + checked_idx = self._options.index(self.value) + + x = self._rect.x + self._rect.width - self._txt_enabled_toggle.width + y = btn_y + + for i in range(len(self._options)): + self._draw_pill(x, y, checked_idx == i) + y += 35 + + +class GreyBigButton(BigButton): + """Users should manage newlines with this class themselves""" + + LABEL_HORIZONTAL_PADDING = 30 + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.set_touch_valid_callback(lambda: False) + + self._rect.width = 476 + + self._label.set_font_size(36) + self._label.set_font_weight(FontWeight.BOLD) + self._label.set_line_height(1.0) + + self._sub_label.set_font_size(36) + self._sub_label.set_text_color(rl.Color(255, 255, 255, int(255 * 0.9))) + self._sub_label.set_font_weight(FontWeight.DISPLAY_REGULAR) + self._sub_label.set_alignment_vertical(rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE if not self._label.text else + rl.GuiTextAlignmentVertical.TEXT_ALIGN_BOTTOM) + self._sub_label.set_line_height(0.95) + + @property + def LABEL_VERTICAL_PADDING(self): + return BigButton.LABEL_VERTICAL_PADDING if self._label.text else 18 + + def _width_hint(self) -> int: + return int(self._rect.width - self.LABEL_HORIZONTAL_PADDING * 2) + + def _get_label_font_size(self): + return 36 + + def _render(self, _): + rl.draw_rectangle_rounded(self._rect, 0.4, 10, rl.Color(255, 255, 255, int(255 * 0.15))) + self._draw_content(self._rect.y) + + +class BigMultiParamToggle(BigMultiToggle): + def __init__(self, text: str, param: str, options: list[str], toggle_callback: Callable | None = None, + select_callback: Callable | None = None): + assert Params is not None + super().__init__(text, options, toggle_callback, select_callback) + self._param = param + + self._params = Params() + self._load_value() + + def _load_value(self): + self.set_value(self._options[self._params.get(self._param) or 0]) + + def _handle_mouse_release(self, mouse_pos: MousePos): + super()._handle_mouse_release(mouse_pos) + new_idx = self._options.index(self.value) + self._params.put(self._param, new_idx) + + +class BigParamControl(BigToggle): + def __init__(self, text: str, param: str, toggle_callback: Callable | None = None): + assert Params is not None + super().__init__(text, "", toggle_callback=toggle_callback) + self.param = param + self.params = Params() + self.set_checked(self.params.get_bool(self.param, False)) + + def _handle_mouse_release(self, mouse_pos: MousePos): + super()._handle_mouse_release(mouse_pos) + self.params.put_bool(self.param, self._checked, block=True) + + def refresh(self): + self.set_checked(self.params.get_bool(self.param, False)) + + +# TODO: param control base class +class BigCircleParamControl(BigCircleToggle): + def __init__(self, icon: rl.Texture, param: str, toggle_callback: Callable | None = None, + icon_offset: tuple[int, int] = (0, 0)): + assert Params is not None + super().__init__(icon, toggle_callback, icon_offset=icon_offset) + self._param = param + self.params = Params() + self.set_checked(self.params.get_bool(self._param, False)) + + def _handle_mouse_release(self, mouse_pos: MousePos): + super()._handle_mouse_release(mouse_pos) + self.params.put_bool(self._param, self._checked, block=True) + + def refresh(self): + self.set_checked(self.params.get_bool(self._param, False)) diff --git a/openpilot/selfdrive/ui/mici/widgets/dialog.py b/openpilot/selfdrive/ui/mici/widgets/dialog.py new file mode 100644 index 0000000000..ed1466449b --- /dev/null +++ b/openpilot/selfdrive/ui/mici/widgets/dialog.py @@ -0,0 +1,240 @@ +import abc +import math +import pyray as rl +from typing import Union +from collections.abc import Callable +from openpilot.system.ui.widgets.nav_widget import NavWidget +from openpilot.system.ui.widgets.label import UnifiedLabel +from openpilot.system.ui.widgets.mici_keyboard import MiciKeyboard +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.lib.application import gui_app, FontWeight, MousePos +from openpilot.system.ui.widgets.slider import RedBigSlider, BigSlider +from openpilot.common.filter_simple import FirstOrderFilter +from openpilot.selfdrive.ui.mici.widgets.button import BigCircleButton, BigButton, GreyBigButton + +DEBUG = False + +PADDING = 20 + + +class BigDialogBase(NavWidget, abc.ABC): + def __init__(self): + super().__init__() + self.set_rect(rl.Rectangle(0, 0, gui_app.width, gui_app.height)) + + +class BigDialog(BigDialogBase): + def __init__(self, title: str, description: str, icon: Union[rl.Texture, None] = None): + super().__init__() + self._card = GreyBigButton(title, description, icon) + + def _render(self, _): + self._card.render(rl.Rectangle( + self._rect.x + self._rect.width / 2 - self._card.rect.width / 2, + self._rect.y + self._rect.height / 2 - self._card.rect.height / 2, + self._card.rect.width, + self._card.rect.height, + )) + + +class BigConfirmationDialog(BigDialogBase): + def __init__(self, title: str, icon: rl.Texture, confirm_callback: Callable[[], None], + exit_on_confirm: bool = True, red: bool = False): + super().__init__() + self._confirm_callback = confirm_callback + self._exit_on_confirm = exit_on_confirm + + self._slider: BigSlider | RedBigSlider + if red: + self._slider = self._child(RedBigSlider(title, icon, confirm_callback=self._on_confirm)) + else: + self._slider = self._child(BigSlider(title, icon, confirm_callback=self._on_confirm)) + self._slider.set_enabled(lambda: self.enabled and not self.is_dismissing) # for nav stack + NavWidget + + def _on_confirm(self): + if self._exit_on_confirm: + self.dismiss(self._confirm_callback) + elif self._confirm_callback: + self._confirm_callback() + + def _update_state(self): + super()._update_state() + if self.is_dismissing and not self._slider.confirmed: + self._slider.reset() + + def _render(self, _): + self._slider.render(self._rect) + + +class BigInputDialog(BigDialogBase): + BACK_TOUCH_AREA_PERCENTAGE = 0.2 + BACKSPACE_RATE = 25 # hz + TEXT_INPUT_SIZE = 35 + + def __init__(self, + hint: str, + default_text: str = "", + minimum_length: int = 1, + confirm_callback: Callable[[str], None] | None = None, + auto_return_to_letters: str = ""): + super().__init__() + self._hint_label = UnifiedLabel(hint, font_size=35, text_color=rl.Color(255, 255, 255, int(255 * 0.35)), + font_weight=FontWeight.MEDIUM) + self._keyboard = MiciKeyboard(auto_return_to_letters=auto_return_to_letters) + self._keyboard.set_text(default_text) + self._keyboard.set_enabled(lambda: self.enabled and not self.is_dismissing) # for nav stack + NavWidget + self._minimum_length = minimum_length + + self._backspace_held_time: float | None = None + + self._backspace_img = gui_app.texture("icons_mici/settings/keyboard/backspace.png", 42, 36) + self._backspace_img_alpha = FirstOrderFilter(0, 0.05, 1 / gui_app.target_fps) + + self._enter_img = gui_app.texture("icons_mici/settings/keyboard/enter.png", 76, 62) + self._enter_disabled_img = gui_app.texture("icons_mici/settings/keyboard/enter_disabled.png", 76, 62) + self._enter_img_alpha = FirstOrderFilter(0, 0.05, 1 / gui_app.target_fps) + + # rects for top buttons + self._top_left_button_rect = rl.Rectangle(0, 0, 0, 0) + self._top_right_button_rect = rl.Rectangle(0, 0, 0, 0) + + def confirm_callback_wrapper(): + text = self._keyboard.text() + self.dismiss((lambda: confirm_callback(text)) if confirm_callback else None) + self._confirm_callback = confirm_callback_wrapper + + def _update_state(self): + super()._update_state() + + if self.is_dismissing: + self._backspace_held_time = None + return + + last_mouse_event = gui_app.last_mouse_event + if last_mouse_event.left_down and rl.check_collision_point_rec(last_mouse_event.pos, self._top_right_button_rect) and self._backspace_img_alpha.x > 1: + if self._backspace_held_time is None: + self._backspace_held_time = rl.get_time() + + if rl.get_time() - self._backspace_held_time > 0.5: + if gui_app.frame % round(gui_app.target_fps / self.BACKSPACE_RATE) == 0: + self._keyboard.backspace() + + else: + self._backspace_held_time = None + + def _render(self, _): + # draw current text so far below everything. text floats left but always stays in view + text = self._keyboard.text() + candidate_char = self._keyboard.get_candidate_character() + text_size = measure_text_cached(gui_app.font(FontWeight.ROMAN), text + candidate_char or self._hint_label.text, self.TEXT_INPUT_SIZE) + + bg_block_margin = 5 + text_x = PADDING / 2 + self._enter_img.width + PADDING + text_field_rect = rl.Rectangle(text_x, self._rect.y + PADDING - bg_block_margin, + self._rect.width - text_x * 2, + text_size.y) + + # draw text input + # push text left with a gradient on left side if too long + if text_size.x > text_field_rect.width: + text_x -= text_size.x - text_field_rect.width + + rl.begin_scissor_mode(int(text_field_rect.x), int(text_field_rect.y), int(text_field_rect.width), int(text_field_rect.height)) + rl.draw_text_ex(gui_app.font(FontWeight.ROMAN), text, rl.Vector2(text_x, text_field_rect.y), self.TEXT_INPUT_SIZE, 0, rl.WHITE) + + # draw grayed out character user is hovering over + if candidate_char: + candidate_char_size = measure_text_cached(gui_app.font(FontWeight.ROMAN), candidate_char, self.TEXT_INPUT_SIZE) + rl.draw_text_ex(gui_app.font(FontWeight.ROMAN), candidate_char, + rl.Vector2(min(text_x + text_size.x, text_field_rect.x + text_field_rect.width) - candidate_char_size.x, text_field_rect.y), + self.TEXT_INPUT_SIZE, 0, rl.Color(255, 255, 255, 128)) + + rl.end_scissor_mode() + + # draw gradient on left side to indicate more text + if text_size.x > text_field_rect.width: + rl.draw_rectangle_gradient_ex(rl.Rectangle(text_field_rect.x, text_field_rect.y, 80, text_field_rect.height), + rl.BLACK, rl.BLANK, rl.BLANK, rl.BLACK) + + # draw cursor + blink_alpha = (math.sin(rl.get_time() * 6) + 1) / 2 + if text: + cursor_x = min(text_x + text_size.x + 3, text_field_rect.x + text_field_rect.width) + else: + cursor_x = text_field_rect.x - 6 + rl.draw_rectangle_rounded(rl.Rectangle(cursor_x, text_field_rect.y, 4, text_size.y), + 1, 4, rl.Color(255, 255, 255, int(255 * blink_alpha))) + + # draw backspace icon with nice fade + self._backspace_img_alpha.update(255 * bool(text)) + if self._backspace_img_alpha.x > 1: + color = rl.Color(255, 255, 255, int(self._backspace_img_alpha.x)) + rl.draw_texture_ex(self._backspace_img, rl.Vector2(self._rect.width - self._backspace_img.width - 27, self._rect.y + 14), 0.0, 1.0, color) + + if not text and self._hint_label.text and not candidate_char: + # draw description if no text entered yet and not drawing candidate char + hint_rect = rl.Rectangle(text_field_rect.x, text_field_rect.y, + self._rect.width - text_field_rect.x - PADDING, + text_field_rect.height) + self._hint_label.render(hint_rect) + + # TODO: move to update state + # make rect take up entire area so it's easier to click + self._top_left_button_rect = rl.Rectangle(self._rect.x, self._rect.y, text_field_rect.x, self._rect.height - self._keyboard.get_keyboard_height()) + self._top_right_button_rect = rl.Rectangle(text_field_rect.x + text_field_rect.width, self._rect.y, + self._rect.width - (text_field_rect.x + text_field_rect.width), self._top_left_button_rect.height) + + # draw enter button + self._enter_img_alpha.update(255 if len(text) >= self._minimum_length else 0) + color = rl.Color(255, 255, 255, int(self._enter_img_alpha.x)) + rl.draw_texture_ex(self._enter_img, rl.Vector2(self._rect.x + PADDING / 2, self._rect.y), 0.0, 1.0, color) + color = rl.Color(255, 255, 255, 255 - int(self._enter_img_alpha.x)) + rl.draw_texture_ex(self._enter_disabled_img, rl.Vector2(self._rect.x + PADDING / 2, self._rect.y), 0.0, 1.0, color) + + # keyboard goes over everything + self._keyboard.render(self._rect) + + # draw debugging rect bounds + if DEBUG: + rl.draw_rectangle_lines_ex(text_field_rect, 1, rl.Color(100, 100, 100, 255)) + rl.draw_rectangle_lines_ex(self._top_right_button_rect, 1, rl.Color(0, 255, 0, 255)) + rl.draw_rectangle_lines_ex(self._top_left_button_rect, 1, rl.Color(0, 255, 0, 255)) + + def _handle_mouse_press(self, mouse_pos: MousePos): + super()._handle_mouse_press(mouse_pos) + # TODO: need to track where press was so enter and back can activate on release rather than press + # or turn into icon widgets :eyes_open: + + if self.is_dismissing: + return + + # handle backspace icon click + if rl.check_collision_point_rec(mouse_pos, self._top_right_button_rect) and self._backspace_img_alpha.x > 254: + self._keyboard.backspace() + elif rl.check_collision_point_rec(mouse_pos, self._top_left_button_rect) and self._enter_img_alpha.x > 254: + # handle enter icon click + self._confirm_callback() + + +class BigDialogButton(BigButton): + def __init__(self, text: str, value: str = "", icon: Union[str, rl.Texture] = "", description: str = ""): + super().__init__(text, value, icon) + self._description = description + + def _handle_mouse_release(self, mouse_pos: MousePos): + super()._handle_mouse_release(mouse_pos) + + dlg = BigDialog(self.text, self._description) + gui_app.push_widget(dlg) + + +class BigConfirmationCircleButton(BigCircleButton): + def __init__(self, title: str, icon: rl.Texture, confirm_callback: Callable[[], None], exit_on_confirm: bool = True, + red: bool = False, icon_offset: tuple[int, int] = (0, 0)): + super().__init__(icon, red, icon_offset) + + def show_confirm_dialog(): + gui_app.push_widget(BigConfirmationDialog(title, icon, confirm_callback, + exit_on_confirm=exit_on_confirm, red=red)) + + self.set_click_callback(show_confirm_dialog) diff --git a/openpilot/selfdrive/ui/mici/widgets/pairing_dialog.py b/openpilot/selfdrive/ui/mici/widgets/pairing_dialog.py new file mode 100644 index 0000000000..a18b26ec02 --- /dev/null +++ b/openpilot/selfdrive/ui/mici/widgets/pairing_dialog.py @@ -0,0 +1,111 @@ +import pyray as rl +import qrcode +import numpy as np +import time + +from openpilot.common.api import Api +from openpilot.common.swaglog import cloudlog +from openpilot.common.params import Params +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.ui.widgets.nav_widget import NavWidget +from openpilot.system.ui.lib.application import FontWeight, gui_app +from openpilot.system.ui.widgets.label import UnifiedLabel + + +class PairingDialog(NavWidget): + """Dialog for device pairing with QR code.""" + + QR_REFRESH_INTERVAL = 300 # 5 minutes in seconds + + def __init__(self): + super().__init__() + self._params = Params() + self._qr_texture: rl.Texture | None = None + self._last_qr_generation = float("-inf") + + self._txt_pair = gui_app.texture("icons_mici/settings/device/pair.png", 33, 60) + self._pair_label = UnifiedLabel("pair with comma connect", font_size=48, font_weight=FontWeight.BOLD, line_height=0.8) + + def _get_pairing_url(self) -> str: + try: + dongle_id = self._params.get("DongleId") or "" + token = Api(dongle_id).get_token({'pair': True}) + except Exception as e: + cloudlog.warning(f"Failed to get pairing token: {e}") + token = "" + return f"https://connect.comma.ai/?pair={token}" + + def _generate_qr_code(self) -> None: + try: + qr = qrcode.QRCode(version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=0) + qr.add_data(self._get_pairing_url()) + qr.make(fit=True) + + pil_img = qr.make_image(fill_color="white", back_color="black").convert('RGBA') + img_array = np.array(pil_img, dtype=np.uint8) + + if self._qr_texture and self._qr_texture.id != 0: + rl.unload_texture(self._qr_texture) + + rl_image = rl.Image() + rl_image.data = rl.ffi.cast("void *", img_array.ctypes.data) + rl_image.width = pil_img.width + rl_image.height = pil_img.height + rl_image.mipmaps = 1 + rl_image.format = rl.PixelFormat.PIXELFORMAT_UNCOMPRESSED_R8G8B8A8 + + self._qr_texture = rl.load_texture_from_image(rl_image) + except Exception as e: + cloudlog.warning(f"QR code generation failed: {e}") + self._qr_texture = None + + def _check_qr_refresh(self) -> None: + current_time = time.monotonic() + if current_time - self._last_qr_generation >= self.QR_REFRESH_INTERVAL: + self._generate_qr_code() + self._last_qr_generation = current_time + + def _update_state(self): + super()._update_state() + if ui_state.prime_state.is_paired() and not self.is_dismissing: + self.dismiss() + + def _render(self, rect: rl.Rectangle): + self._check_qr_refresh() + + self._render_qr_code() + + label_x = self._rect.x + 8 + self._rect.height + 24 + self._pair_label.set_max_width(int(self._rect.width - label_x)) + self._pair_label.set_position(label_x, self._rect.y + 16) + self._pair_label.render() + + rl.draw_texture_ex(self._txt_pair, rl.Vector2(label_x, self._rect.y + self._rect.height - self._txt_pair.height - 16), + 0.0, 1.0, rl.Color(255, 255, 255, int(255 * 0.35))) + + def _render_qr_code(self) -> None: + if not self._qr_texture: + error_font = gui_app.font(FontWeight.BOLD) + rl.draw_text_ex( + error_font, "QR Code Error", rl.Vector2(self._rect.x + 20, self._rect.y + self._rect.height // 2 - 15), 30, 0.0, rl.RED + ) + return + + scale = self._rect.height / self._qr_texture.height + pos = rl.Vector2(round(self._rect.x + 8), round(self._rect.y)) + rl.draw_texture_ex(self._qr_texture, pos, 0.0, scale, rl.WHITE) + + def __del__(self): + if self._qr_texture and self._qr_texture.id != 0: + rl.unload_texture(self._qr_texture) + + +if __name__ == "__main__": + gui_app.init_window("pairing device") + pairing = PairingDialog() + gui_app.push_widget(pairing) + try: + for _ in gui_app.render(): + pass + finally: + del pairing diff --git a/selfdrive/ui/layouts/__init__.py b/openpilot/selfdrive/ui/onroad/__init__.py similarity index 100% rename from selfdrive/ui/layouts/__init__.py rename to openpilot/selfdrive/ui/onroad/__init__.py diff --git a/openpilot/selfdrive/ui/onroad/alert_renderer.py b/openpilot/selfdrive/ui/onroad/alert_renderer.py new file mode 100644 index 0000000000..b77b1539f4 --- /dev/null +++ b/openpilot/selfdrive/ui/onroad/alert_renderer.py @@ -0,0 +1,182 @@ +import time +import pyray as rl +from dataclasses import dataclass +from openpilot.cereal import messaging, log +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.common.hardware import TICI +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.label import Label + +AlertSize = log.SelfdriveState.AlertSize +AlertStatus = log.SelfdriveState.AlertStatus + +ALERT_MARGIN = 40 +ALERT_PADDING = 60 +ALERT_LINE_SPACING = 45 +ALERT_BORDER_RADIUS = 30 + +ALERT_FONT_SMALL = 66 +ALERT_FONT_MEDIUM = 74 +ALERT_FONT_BIG = 88 + +ALERT_HEIGHTS = { + AlertSize.small: 271, + AlertSize.mid: 420, +} + +SELFDRIVE_STATE_TIMEOUT = 5 # Seconds +SELFDRIVE_UNRESPONSIVE_TIMEOUT = 10 # Seconds + +# Constants +ALERT_COLORS = { + AlertStatus.normal: rl.Color(0x15, 0x15, 0x15, 0xF1), # #151515 with alpha 0xF1 + AlertStatus.userPrompt: rl.Color(0xDA, 0x6F, 0x25, 0xF1), # #DA6F25 with alpha 0xF1 + AlertStatus.critical: rl.Color(0xC9, 0x22, 0x31, 0xF1), # #C92231 with alpha 0xF1 +} + + +@dataclass +class Alert: + text1: str = "" + text2: str = "" + size: int = 0 + status: int = 0 + + +# Pre-defined alert instances +ALERT_STARTUP_PENDING = Alert( + text1=tr("sunnypilot Unavailable"), + text2=tr("Waiting to start"), + size=AlertSize.mid, + status=AlertStatus.normal, +) + +ALERT_CRITICAL_TIMEOUT = Alert( + text1=tr("TAKE CONTROL IMMEDIATELY"), + text2=tr("System Unresponsive"), + size=AlertSize.full, + status=AlertStatus.critical, +) + +ALERT_CRITICAL_REBOOT = Alert( + text1=tr("System Unresponsive"), + text2=tr("Reboot Device"), + size=AlertSize.mid, + status=AlertStatus.normal, +) + + +class AlertRenderer(Widget): + def __init__(self): + super().__init__() + self.font_regular: rl.Font = gui_app.font(FontWeight.NORMAL) + self.font_bold: rl.Font = gui_app.font(FontWeight.BOLD) + + # font size is set dynamically + self._full_text1_label = Label("", font_size=0, font_weight=FontWeight.BOLD, text_alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER, + text_alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_TOP) + self._full_text2_label = Label("", font_size=ALERT_FONT_BIG, text_alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER, + text_alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_TOP) + + def get_alert(self, sm: messaging.SubMaster) -> Alert | None: + """Generate the current alert based on selfdrive state.""" + ss = sm['selfdriveState'] + + # Check if selfdriveState messages have stopped arriving + recv_frame = sm.recv_frame['selfdriveState'] + if not sm.updated['selfdriveState']: + time_since_onroad = time.monotonic() - ui_state.started_time + + # 1. Never received selfdriveState since going onroad + waiting_for_startup = recv_frame < ui_state.started_frame + if waiting_for_startup and time_since_onroad > 5: + return ALERT_STARTUP_PENDING + + # 2. Lost communication with selfdriveState after receiving it + if TICI and not waiting_for_startup: + ss_missing = time.monotonic() - sm.recv_time['selfdriveState'] + if ss_missing > SELFDRIVE_STATE_TIMEOUT: + if ss.enabled and (ss_missing - SELFDRIVE_STATE_TIMEOUT) < SELFDRIVE_UNRESPONSIVE_TIMEOUT: + return ALERT_CRITICAL_TIMEOUT + return ALERT_CRITICAL_REBOOT + + # No alert if size is none + if ss.alertSize == 0: + return None + + # Don't get old alert + if recv_frame < ui_state.started_frame: + return None + + # Return current alert + return Alert(text1=ss.alertText1, text2=ss.alertText2, size=ss.alertSize.raw, status=ss.alertStatus.raw) + + def _render(self, rect: rl.Rectangle): + alert = self.get_alert(ui_state.sm) + + if gui_app.sunnypilot_ui(): + ui_state.onroad_brightness_handle_alerts(ui_state, alert) + + if not alert: + return + + alert_rect = self._get_alert_rect(rect, alert.size) + self._draw_background(alert_rect, alert) + + text_rect = rl.Rectangle( + alert_rect.x + ALERT_PADDING, + alert_rect.y + ALERT_PADDING, + alert_rect.width - 2 * ALERT_PADDING, + alert_rect.height - 2 * ALERT_PADDING + ) + self._draw_text(text_rect, alert) + + def _get_alert_rect(self, rect: rl.Rectangle, size: int) -> rl.Rectangle: + if size == AlertSize.full: + return rect + + h = ALERT_HEIGHTS.get(size, rect.height) + return rl.Rectangle(rect.x + ALERT_MARGIN, rect.y + rect.height - h + ALERT_MARGIN, + rect.width - ALERT_MARGIN * 2, h - ALERT_MARGIN * 2) + + def _draw_background(self, rect: rl.Rectangle, alert: Alert) -> None: + color = ALERT_COLORS.get(alert.status, ALERT_COLORS[AlertStatus.normal]) + + if alert.size != AlertSize.full: + roundness = ALERT_BORDER_RADIUS / (min(rect.width, rect.height) / 2) + rl.draw_rectangle_rounded(rect, roundness, 10, color) + else: + rl.draw_rectangle_rec(rect, color) + + def _draw_text(self, rect: rl.Rectangle, alert: Alert) -> None: + if alert.size == AlertSize.small: + self._draw_centered(alert.text1, rect, self.font_bold, ALERT_FONT_MEDIUM) + + elif alert.size == AlertSize.mid: + self._draw_centered(alert.text1, rect, self.font_bold, ALERT_FONT_BIG, center_y=False) + rect.y += ALERT_FONT_BIG + ALERT_LINE_SPACING + self._draw_centered(alert.text2, rect, self.font_regular, ALERT_FONT_SMALL, center_y=False) + + else: + is_long = len(alert.text1) > 15 + font_size1 = 132 if is_long else 177 + + top_offset = 200 if is_long or '\n' in alert.text1 else 270 + title_rect = rl.Rectangle(rect.x, rect.y + top_offset, rect.width, 600) + self._full_text1_label.set_font_size(font_size1) + self._full_text1_label.set_text(alert.text1) + self._full_text1_label.render(title_rect) + + bottom_offset = 361 if is_long else 420 + subtitle_rect = rl.Rectangle(rect.x, rect.y + rect.height - bottom_offset, rect.width, 300) + self._full_text2_label.set_text(alert.text2) + self._full_text2_label.render(subtitle_rect) + + def _draw_centered(self, text, rect, font, font_size, center_y=True, color=rl.WHITE) -> None: + text_size = measure_text_cached(font, text, font_size) + x = rect.x + (rect.width - text_size.x) / 2 + y = rect.y + ((rect.height - text_size.y) / 2 if center_y else 0) + rl.draw_text_ex(font, text, rl.Vector2(x, y), font_size, 0, color) diff --git a/openpilot/selfdrive/ui/onroad/augmented_road_view.py b/openpilot/selfdrive/ui/onroad/augmented_road_view.py new file mode 100644 index 0000000000..c255804f2d --- /dev/null +++ b/openpilot/selfdrive/ui/onroad/augmented_road_view.py @@ -0,0 +1,245 @@ +import numpy as np +import pyray as rl +from openpilot.cereal import log +from msgq.visionipc import VisionStreamType +from openpilot.selfdrive.ui import UI_BORDER_SIZE +from openpilot.selfdrive.ui.ui_state import ui_state, UIStatus +from openpilot.selfdrive.ui.onroad.alert_renderer import AlertRenderer +from openpilot.selfdrive.ui.onroad.driver_state import DriverStateRenderer +from openpilot.selfdrive.ui.onroad.hud_renderer import HudRenderer +from openpilot.selfdrive.ui.onroad.model_renderer import ModelRenderer +from openpilot.selfdrive.ui.onroad.cameraview import CameraView +from openpilot.system.ui.lib.application import gui_app +from openpilot.common.transformations.camera import DEVICE_CAMERAS, DeviceCameraConfig, view_frame_from_device_frame +from openpilot.common.transformations.orientation import rot_from_euler + +if gui_app.sunnypilot_ui(): + from openpilot.selfdrive.ui.sunnypilot.onroad.alert_renderer import AlertRendererSP as AlertRenderer + from openpilot.selfdrive.ui.sunnypilot.onroad.augmented_road_view import BORDER_COLORS_SP, AugmentedRoadViewSP + from openpilot.selfdrive.ui.sunnypilot.onroad.driver_state import DriverStateRendererSP as DriverStateRenderer + from openpilot.selfdrive.ui.sunnypilot.onroad.hud_renderer import HudRendererSP as HudRenderer + from openpilot.selfdrive.ui.sunnypilot.ui_state import OnroadTimerStatus + +OpState = log.SelfdriveState.OpenpilotState +CALIBRATED = log.LiveCalibrationData.Status.calibrated +ROAD_CAM = VisionStreamType.VISION_STREAM_ROAD +WIDE_CAM = VisionStreamType.VISION_STREAM_WIDE_ROAD +DEFAULT_DEVICE_CAMERA = DEVICE_CAMERAS["tici", "ar0231"] + +BORDER_COLORS = { + UIStatus.DISENGAGED: rl.Color(0x12, 0x28, 0x39, 0xFF), # Blue for disengaged state + UIStatus.OVERRIDE: rl.Color(0x89, 0x92, 0x8D, 0xFF), # Gray for override state + UIStatus.ENGAGED: rl.Color(0x16, 0x7F, 0x40, 0xFF), # Green for engaged state + **BORDER_COLORS_SP, +} + +WIDE_CAM_MAX_SPEED = 10.0 # m/s (22 mph) +ROAD_CAM_MIN_SPEED = 15.0 # m/s (34 mph) +INF_POINT = np.array([1000.0, 0.0, 0.0]) + + +class AugmentedRoadView(CameraView, AugmentedRoadViewSP): + def __init__(self, stream_type: VisionStreamType = VisionStreamType.VISION_STREAM_ROAD): + CameraView.__init__(self, "camerad", stream_type) + AugmentedRoadViewSP.__init__(self) + self._set_placeholder_color(BORDER_COLORS[UIStatus.DISENGAGED]) + + self.device_camera: DeviceCameraConfig | None = None + self.view_from_calib = view_frame_from_device_frame.copy() + self.view_from_wide_calib = view_frame_from_device_frame.copy() + + self._matrix_cache_key = (0, 0.0, 0.0, stream_type) + self._cached_matrix: np.ndarray | None = None + self._content_rect = rl.Rectangle() + + self.model_renderer = ModelRenderer() + self._hud_renderer = HudRenderer() + self.alert_renderer = AlertRenderer() + self.driver_state_renderer = DriverStateRenderer() + + def _render(self, rect): + # Only render when system is started to avoid invalid data access + if not ui_state.started: + return + + self._switch_stream_if_needed(ui_state.sm) + + # Update calibration before rendering + self._update_calibration() + + # Create inner content area with border padding + self._content_rect = rl.Rectangle( + rect.x + UI_BORDER_SIZE, + rect.y + UI_BORDER_SIZE, + rect.width - 2 * UI_BORDER_SIZE, + rect.height - 2 * UI_BORDER_SIZE, + ) + + # Enable scissor mode to clip all rendering within content rectangle boundaries + # This creates a rendering viewport that prevents graphics from drawing outside the border + rl.begin_scissor_mode( + int(self._content_rect.x), + int(self._content_rect.y), + int(self._content_rect.width), + int(self._content_rect.height) + ) + + # Render the base camera view + super()._render(self._content_rect) + + # Draw all UI overlays + self.model_renderer.render(self._content_rect) + AugmentedRoadViewSP.update_fade_out_bottom_overlay(self, self._content_rect) + self._hud_renderer.render(self._content_rect) + self.alert_renderer.render(self._content_rect) + self.driver_state_renderer.render(self._content_rect) + + # Custom UI extension point - add custom overlays here + # Use self._content_rect for positioning within camera bounds + + # End clipping region + rl.end_scissor_mode() + + # Draw colored border based on driving state + self._draw_border(rect) + + def _handle_mouse_press(self, _): + if not self._hud_renderer.user_interacting() and self._click_callback is not None: + self._click_callback() + + def _handle_mouse_release(self, _): + # We only call click callback on press if not interacting with HUD + pass + + def _draw_border(self, rect: rl.Rectangle): + rl.draw_rectangle_lines_ex(rect, UI_BORDER_SIZE, rl.BLACK) + border_roundness = 0.12 + border_color = BORDER_COLORS.get(ui_state.status, BORDER_COLORS[UIStatus.DISENGAGED]) + border_rect = rl.Rectangle(rect.x + UI_BORDER_SIZE, rect.y + UI_BORDER_SIZE, + rect.width - 2 * UI_BORDER_SIZE, rect.height - 2 * UI_BORDER_SIZE) + rl.draw_rectangle_rounded_lines_ex(border_rect, border_roundness, 10, UI_BORDER_SIZE, border_color) + + def _switch_stream_if_needed(self, sm): + if sm['selfdriveState'].experimentalMode and WIDE_CAM in self.available_streams: + v_ego = sm['carState'].vEgo + if v_ego < WIDE_CAM_MAX_SPEED: + target = WIDE_CAM + elif v_ego > ROAD_CAM_MIN_SPEED: + target = ROAD_CAM + else: + # Hysteresis zone - keep current stream + target = self.stream_type + else: + target = ROAD_CAM + + if self.stream_type != target: + self.switch_stream(target) + + def _update_calibration(self): + # Update device camera if not already set + sm = ui_state.sm + if not self.device_camera and sm.seen['roadCameraState'] and sm.seen['deviceState']: + self.device_camera = DEVICE_CAMERAS[(str(sm['deviceState'].deviceType), str(sm['roadCameraState'].sensor))] + + # Check if live calibration data is available and valid + if not (sm.updated["liveCalibration"] and sm.valid['liveCalibration']): + return + + calib = sm['liveCalibration'] + if len(calib.rpyCalib) != 3 or calib.calStatus != CALIBRATED: + return + + # Update view_from_calib matrix + device_from_calib = rot_from_euler(calib.rpyCalib) + self.view_from_calib = view_frame_from_device_frame @ device_from_calib + + # Update wide calibration if available + if hasattr(calib, 'wideFromDeviceEuler') and len(calib.wideFromDeviceEuler) == 3: + wide_from_device = rot_from_euler(calib.wideFromDeviceEuler) + self.view_from_wide_calib = view_frame_from_device_frame @ wide_from_device @ device_from_calib + + def _calc_frame_matrix(self, rect: rl.Rectangle) -> np.ndarray: + # Check if we can use cached matrix + cache_key = ( + ui_state.sm.recv_frame['liveCalibration'], + self._content_rect.width, + self._content_rect.height, + self.stream_type + ) + if cache_key == self._matrix_cache_key and self._cached_matrix is not None: + return self._cached_matrix + + # Get camera configuration + device_camera = self.device_camera or DEFAULT_DEVICE_CAMERA + is_wide_camera = self.stream_type == WIDE_CAM + intrinsic = device_camera.ecam.intrinsics if is_wide_camera else device_camera.fcam.intrinsics + calibration = self.view_from_wide_calib if is_wide_camera else self.view_from_calib + zoom = 2.0 if is_wide_camera else 1.1 + + # Calculate transforms for vanishing point + calib_transform = intrinsic @ calibration + kep = calib_transform @ INF_POINT + + # Calculate center points and dimensions + x, y = self._content_rect.x, self._content_rect.y + w, h = self._content_rect.width, self._content_rect.height + cx, cy = intrinsic[0, 2], intrinsic[1, 2] + + # Ensure zoom views the whole area + zoom = max(zoom, w / (2 * cx), h / (2 * cy)) + + # Calculate max allowed offsets with margins + margin = 5 + max_x_offset = max(0.0, cx * zoom - w / 2 - margin) + max_y_offset = max(0.0, cy * zoom - h / 2 - margin) + + # Calculate and clamp offsets to prevent out-of-bounds issues + try: + if abs(kep[2]) > 1e-6: + x_offset = np.clip((kep[0] / kep[2] - cx) * zoom, -max_x_offset, max_x_offset) + y_offset = np.clip((kep[1] / kep[2] - cy) * zoom, -max_y_offset, max_y_offset) + else: + x_offset, y_offset = 0, 0 + except (ZeroDivisionError, OverflowError): + x_offset, y_offset = 0, 0 + + # Cache the computed transformation matrix to avoid recalculations + self._matrix_cache_key = cache_key + self._cached_matrix = np.array([ + [zoom * 2 * cx / w, 0, -x_offset / w * 2], + [0, zoom * 2 * cy / h, -y_offset / h * 2], + [0, 0, 1.0] + ]) + + video_transform = np.array([ + [zoom, 0.0, (w / 2 + x - x_offset) - (cx * zoom)], + [0.0, zoom, (h / 2 + y - y_offset) - (cy * zoom)], + [0.0, 0.0, 1.0] + ]) + self.model_renderer.set_transform(video_transform @ calib_transform) + + return self._cached_matrix + + def show_event(self): + if gui_app.sunnypilot_ui(): + ui_state.reset_onroad_sleep_timer(OnroadTimerStatus.RESUME) + + def hide_event(self): + if gui_app.sunnypilot_ui(): + ui_state.reset_onroad_sleep_timer(OnroadTimerStatus.PAUSE) + + +if __name__ == "__main__": + gui_app.init_window("OnRoad Camera View") + road_camera_view = AugmentedRoadView(ROAD_CAM) + gui_app.push_widget(road_camera_view) + print("***press space to switch camera view***") + try: + for _ in gui_app.render(): + ui_state.update() + if rl.is_key_released(rl.KeyboardKey.KEY_SPACE): + if WIDE_CAM in road_camera_view.available_streams: + stream = ROAD_CAM if road_camera_view.stream_type == WIDE_CAM else WIDE_CAM + road_camera_view.switch_stream(stream) + finally: + road_camera_view.close() diff --git a/openpilot/selfdrive/ui/onroad/cameraview.py b/openpilot/selfdrive/ui/onroad/cameraview.py new file mode 100644 index 0000000000..846bf20bbc --- /dev/null +++ b/openpilot/selfdrive/ui/onroad/cameraview.py @@ -0,0 +1,366 @@ +import platform +import numpy as np +import pyray as rl + +from msgq.visionipc import VisionIpcClient, VisionStreamType, VisionBuf +from openpilot.common.swaglog import cloudlog +from openpilot.common.hardware import TICI +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.lib.egl import init_egl, create_egl_image, destroy_egl_image, bind_egl_image_to_texture, EGLImage +from openpilot.system.ui.widgets import Widget +from openpilot.selfdrive.ui.ui_state import ui_state + +CONNECTION_RETRY_INTERVAL = 0.2 # seconds between connection attempts + +VERSION = """ +#version 300 es +precision mediump float; +""" +if platform.system() == "Darwin": + VERSION = """ + #version 330 core + """ + + +VERTEX_SHADER = VERSION + """ +in vec3 vertexPosition; +in vec2 vertexTexCoord; +in vec3 vertexNormal; +in vec4 vertexColor; +uniform mat4 mvp; +out vec2 fragTexCoord; +out vec4 fragColor; +void main() { + fragTexCoord = vertexTexCoord; + fragColor = vertexColor; + gl_Position = mvp * vec4(vertexPosition, 1.0); +} +""" + +# Choose fragment shader based on platform capabilities +if TICI: + FRAME_FRAGMENT_SHADER = """ + #version 300 es + #extension GL_OES_EGL_image_external_essl3 : enable + precision mediump float; + in vec2 fragTexCoord; + uniform samplerExternalOES texture0; + out vec4 fragColor; + void main() { + vec4 color = texture(texture0, fragTexCoord); + fragColor = vec4(pow(color.rgb, vec3(1.0/1.28)), color.a); + } + """ +else: + FRAME_FRAGMENT_SHADER = VERSION + """ + in vec2 fragTexCoord; + uniform sampler2D texture0; + uniform sampler2D texture1; + out vec4 fragColor; + void main() { + float y = texture(texture0, fragTexCoord).r; + vec2 uv = texture(texture1, fragTexCoord).ra - 0.5; + fragColor = vec4(y + 1.402*uv.y, y - 0.344*uv.x - 0.714*uv.y, y + 1.772*uv.x, 1.0); + } + """ + + +class CameraView(Widget): + def __init__(self, name: str, stream_type: VisionStreamType): + super().__init__() + self._name = name + # Primary stream + self.client = VisionIpcClient(name, stream_type, conflate=True) + self._stream_type = stream_type + self.available_streams: list[VisionStreamType] = [] + + # Target stream for switching + self._target_client: VisionIpcClient | None = None + self._target_stream_type: VisionStreamType | None = None + self._switching: bool = False + + self._texture_needs_update = True + self.last_connection_attempt: float = 0.0 + self.shader = rl.load_shader_from_memory(VERTEX_SHADER, FRAME_FRAGMENT_SHADER) + self._texture1_loc: int = rl.get_shader_location(self.shader, "texture1") if not TICI else -1 + + self.frame: VisionBuf | None = None + self.texture_y: rl.Texture | None = None + self.texture_uv: rl.Texture | None = None + + # EGL resources + self.egl_images: dict[int, EGLImage] = {} + self.egl_texture: rl.Texture | None = None + + self._placeholder_color: rl.Color | None = None + + # Initialize EGL for zero-copy rendering on TICI + if TICI: + if not init_egl(): + raise RuntimeError("Failed to initialize EGL") + + # Create a 1x1 pixel placeholder texture for EGL image binding + temp_image = rl.gen_image_color(1, 1, rl.BLACK) + self.egl_texture = rl.load_texture_from_image(temp_image) + rl.unload_image(temp_image) + + ui_state.add_offroad_transition_callback(self._offroad_transition) + + def _offroad_transition(self): + # Reconnect if not first time going onroad + if ui_state.is_onroad() and self.frame is not None: + # Prevent old frames from showing when going onroad. Qt has a separate thread + # which drains the VisionIpcClient SubSocket for us. Re-connecting is not enough + # and only clears internal buffers, not the message queue. + self.frame = None + self.available_streams.clear() + if self.client: + del self.client + self.client = VisionIpcClient(self._name, self._stream_type, conflate=True) + + def _set_placeholder_color(self, color: rl.Color): + """Set a placeholder color to be drawn when no frame is available.""" + self._placeholder_color = color + + def switch_stream(self, stream_type: VisionStreamType) -> None: + if self._stream_type == stream_type: + return + + if self._switching and self._target_stream_type == stream_type: + return + + cloudlog.debug(f'Preparing switch from {self._stream_type} to {stream_type}') + + if self._target_client: + del self._target_client + + self._target_stream_type = stream_type + self._target_client = VisionIpcClient(self._name, stream_type, conflate=True) + self._switching = True + + @property + def stream_type(self) -> VisionStreamType: + return self._stream_type + + def close(self) -> None: + self._clear_textures() + + # Clean up EGL texture + if TICI and self.egl_texture: + rl.unload_texture(self.egl_texture) + self.egl_texture = None + + # Clean up shader + if self.shader and self.shader.id: + rl.unload_shader(self.shader) + + self.frame = None + self.available_streams.clear() + self.client = None + + def __del__(self): + self.close() + + def _calc_frame_matrix(self, rect: rl.Rectangle) -> np.ndarray: + if not self.frame: + return np.eye(3) + + # Calculate aspect ratios + widget_aspect_ratio = rect.width / rect.height + frame_aspect_ratio = self.frame.width / self.frame.height + + # Calculate scaling factors to maintain aspect ratio + zx = min(frame_aspect_ratio / widget_aspect_ratio, 1.0) + zy = min(widget_aspect_ratio / frame_aspect_ratio, 1.0) + + return np.array([ + [zx, 0.0, 0.0], + [0.0, zy, 0.0], + [0.0, 0.0, 1.0] + ]) + + def _render(self, rect: rl.Rectangle): + if self._switching: + self._handle_switch() + + if not self._ensure_connection(): + self._draw_placeholder(rect) + return + + # Try to get a new buffer without blocking + buffer = self.client.recv(timeout_ms=0) + if buffer: + self._texture_needs_update = True + self.frame = buffer + elif not self.client.is_connected(): + # ensure we clear the displayed frame when the connection is lost + self.frame = None + + if not self.frame: + self._draw_placeholder(rect) + return + + transform = self._calc_frame_matrix(rect) + src_rect = rl.Rectangle(0, 0, float(self.frame.width), float(self.frame.height)) + # Flip driver camera horizontally + if self._stream_type == VisionStreamType.VISION_STREAM_DRIVER: + src_rect.width = -src_rect.width + + # Calculate scale + scale_x = rect.width * transform[0, 0] # zx + scale_y = rect.height * transform[1, 1] # zy + + # Calculate base position (centered) + x_offset = rect.x + (rect.width - scale_x) / 2 + y_offset = rect.y + (rect.height - scale_y) / 2 + + x_offset += transform[0, 2] * rect.width / 2 + y_offset += transform[1, 2] * rect.height / 2 + + dst_rect = rl.Rectangle(x_offset, y_offset, scale_x, scale_y) + + # Render with appropriate method + if TICI: + self._render_egl(src_rect, dst_rect) + else: + self._render_textures(src_rect, dst_rect) + + def _draw_placeholder(self, rect: rl.Rectangle): + if self._placeholder_color: + rl.draw_rectangle_rec(rect, self._placeholder_color) + + def _render_egl(self, src_rect: rl.Rectangle, dst_rect: rl.Rectangle) -> None: + """Render using EGL for direct buffer access""" + if self.frame is None or self.egl_texture is None: + return + + idx = self.frame.idx + egl_image = self.egl_images.get(idx) + + # Create EGL image if needed + if egl_image is None: + egl_image = create_egl_image(self.frame.width, self.frame.height, self.frame.stride, self.frame.fd, self.frame.uv_offset) + if egl_image: + self.egl_images[idx] = egl_image + else: + return + + # Update texture dimensions to match current frame + self.egl_texture.width = self.frame.width + self.egl_texture.height = self.frame.height + + # Bind the EGL image to our texture + bind_egl_image_to_texture(self.egl_texture.id, egl_image) + + # Render with shader + rl.begin_shader_mode(self.shader) + rl.draw_texture_pro(self.egl_texture, src_rect, dst_rect, rl.Vector2(0, 0), 0.0, rl.WHITE) + rl.end_shader_mode() + + def _render_textures(self, src_rect: rl.Rectangle, dst_rect: rl.Rectangle) -> None: + """Render using texture copies""" + if not self.texture_y or not self.texture_uv or self.frame is None: + return + + # Update textures with new frame data + if self._texture_needs_update: + y_data = self.frame.data[: self.frame.uv_offset] + uv_data = self.frame.data[self.frame.uv_offset:] + + rl.update_texture(self.texture_y, rl.ffi.cast("void *", rl.ffi.from_buffer(y_data))) + rl.update_texture(self.texture_uv, rl.ffi.cast("void *", rl.ffi.from_buffer(uv_data))) + self._texture_needs_update = False + + # Render with shader + rl.begin_shader_mode(self.shader) + rl.set_shader_value_texture(self.shader, self._texture1_loc, self.texture_uv) + rl.draw_texture_pro(self.texture_y, src_rect, dst_rect, rl.Vector2(0, 0), 0.0, rl.WHITE) + rl.end_shader_mode() + + def _ensure_connection(self) -> bool: + if not self.client.is_connected(): + self.frame = None + self.available_streams.clear() + + # Throttle connection attempts + current_time = rl.get_time() + if current_time - self.last_connection_attempt < CONNECTION_RETRY_INTERVAL: + return False + self.last_connection_attempt = current_time + + if not self.client.connect(False) or not self.client.num_buffers: + return False + + cloudlog.debug(f"Connected to {self._name} stream: {self._stream_type}, buffers: {self.client.num_buffers}") + self._initialize_textures() + self.available_streams = self.client.available_streams(self._name, block=False) + + return True + + def _handle_switch(self) -> None: + """Check if target stream is ready and switch immediately.""" + if not self._target_client or not self._switching: + return + + # Try to connect target if needed + if not self._target_client.is_connected(): + if not self._target_client.connect(False) or not self._target_client.num_buffers: + return + + cloudlog.debug(f"Target stream connected: {self._target_stream_type}") + + # Check if target has frames ready + target_frame = self._target_client.recv(timeout_ms=0) + if target_frame: + self.frame = target_frame # Update current frame to target frame + self._complete_switch() + + def _complete_switch(self) -> None: + """Instantly switch to target stream.""" + cloudlog.debug(f"Switching to {self._target_stream_type}") + # Clean up current resources + if self.client: + del self.client + + # Switch to target + self.client = self._target_client + self._stream_type = self._target_stream_type + self._texture_needs_update = True + + # Reset state + self._target_client = None + self._target_stream_type = None + self._switching = False + + # Initialize textures for new stream + self._initialize_textures() + + def _initialize_textures(self): + self._clear_textures() + if not TICI: + self.texture_y = rl.load_texture_from_image(rl.Image(None, int(self.client.stride), + int(self.client.height), 1, rl.PixelFormat.PIXELFORMAT_UNCOMPRESSED_GRAYSCALE)) + self.texture_uv = rl.load_texture_from_image(rl.Image(None, int(self.client.stride // 2), + int(self.client.height // 2), 1, rl.PixelFormat.PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA)) + + def _clear_textures(self): + if self.texture_y and self.texture_y.id: + rl.unload_texture(self.texture_y) + self.texture_y = None + + if self.texture_uv and self.texture_uv.id: + rl.unload_texture(self.texture_uv) + self.texture_uv = None + + # Clean up EGL resources + if TICI: + for data in self.egl_images.values(): + destroy_egl_image(data) + self.egl_images = {} + + +if __name__ == "__main__": + gui_app.init_window("camera view") + road = CameraView("camerad", VisionStreamType.VISION_STREAM_ROAD) + for _ in gui_app.render(): + road.render(rl.Rectangle(0, 0, gui_app.width, gui_app.height)) diff --git a/openpilot/selfdrive/ui/onroad/driver_camera_dialog.py b/openpilot/selfdrive/ui/onroad/driver_camera_dialog.py new file mode 100644 index 0000000000..7e07e44210 --- /dev/null +++ b/openpilot/selfdrive/ui/onroad/driver_camera_dialog.py @@ -0,0 +1,111 @@ +import numpy as np +import pyray as rl +from msgq.visionipc import VisionStreamType +from openpilot.selfdrive.ui.onroad.cameraview import CameraView +from openpilot.selfdrive.ui.onroad.driver_state import DriverStateRenderer +from openpilot.selfdrive.ui.ui_state import ui_state, device +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.widgets.label import gui_label + + +class DriverCameraDialog(CameraView): + def __init__(self): + super().__init__("camerad", VisionStreamType.VISION_STREAM_DRIVER) + self.driver_state_renderer = DriverStateRenderer() + # TODO: this can grow unbounded, should be given some thought + device.add_interactive_timeout_callback(gui_app.pop_widget) + ui_state.params.put_bool("IsDriverViewEnabled", True, block=True) + + def hide_event(self): + super().hide_event() + ui_state.params.put_bool("IsDriverViewEnabled", False, block=True) + self.close() + + def _handle_mouse_release(self, _): + super()._handle_mouse_release(_) + gui_app.pop_widget() + + def __del__(self): + self.close() + + def _render(self, rect): + super()._render(rect) + + if not self.frame: + gui_label( + rect, + tr("camera starting"), + font_size=100, + font_weight=FontWeight.BOLD, + alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER, + ) + return -1 + + self._draw_face_detection(rect) + self.driver_state_renderer.render(rect) + + return -1 + + def _draw_face_detection(self, rect: rl.Rectangle) -> None: + driver_state = ui_state.sm["driverStateV2"] + is_rhd = driver_state.wheelOnRightProb > 0.5 + driver_data = driver_state.rightDriverData if is_rhd else driver_state.leftDriverData + face_detect = driver_data.faceProb > 0.7 + if not face_detect: + return + + # Get face position and orientation + face_x, face_y = driver_data.facePosition + face_std = max(driver_data.faceOrientationStd[0], driver_data.faceOrientationStd[1]) + alpha = 0.7 + if face_std > 0.15: + alpha = max(0.7 - (face_std - 0.15) * 3.5, 0.0) + + # use approx instead of distort_points + # TODO: replace with distort_points + fbox_x = int(1080.0 - 1714.0 * face_x) + fbox_y = int(-135.0 + (504.0 + abs(face_x) * 112.0) + (1205.0 - abs(face_x) * 724.0) * face_y) + box_size = 220 + + line_color = rl.Color(255, 255, 255, int(alpha * 255)) + rl.draw_rectangle_rounded_lines_ex( + rl.Rectangle(fbox_x - box_size / 2, fbox_y - box_size / 2, box_size, box_size), + 35.0 / box_size / 2, + 10, + 10, + line_color, + ) + + def _calc_frame_matrix(self, rect: rl.Rectangle) -> np.ndarray: + driver_view_ratio = 2.0 + + # Get stream dimensions + if self.frame: + stream_width = self.frame.width + stream_height = self.frame.height + else: + # Default values if frame not available + stream_width = 1928 + stream_height = 1208 + + yscale = stream_height * driver_view_ratio / stream_width + xscale = yscale * rect.height / rect.width * stream_width / stream_height + + return np.array([ + [xscale, 0.0, 0.0], + [0.0, yscale, 0.0], + [0.0, 0.0, 1.0] + ]) + + +if __name__ == "__main__": + gui_app.init_window("Driver Camera View") + + driver_camera_view = DriverCameraDialog() + gui_app.push_widget(driver_camera_view) + try: + for _ in gui_app.render(): + ui_state.update() + finally: + driver_camera_view.close() diff --git a/openpilot/selfdrive/ui/onroad/driver_state.py b/openpilot/selfdrive/ui/onroad/driver_state.py new file mode 100644 index 0000000000..6b11f0b10b --- /dev/null +++ b/openpilot/selfdrive/ui/onroad/driver_state.py @@ -0,0 +1,231 @@ +import numpy as np +import pyray as rl +from openpilot.cereal import log +from dataclasses import dataclass +from openpilot.selfdrive.ui import UI_BORDER_SIZE +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.widgets import Widget + +AlertSize = log.SelfdriveState.AlertSize + +# Default 3D coordinates for face keypoints as a NumPy array +DEFAULT_FACE_KPTS_3D = np.array([ + [-5.98, -51.20, 8.00], [-17.64, -49.14, 8.00], [-23.81, -46.40, 8.00], [-29.98, -40.91, 8.00], + [-32.04, -37.49, 8.00], [-34.10, -32.00, 8.00], [-36.16, -21.03, 8.00], [-36.16, 6.40, 8.00], + [-35.47, 10.51, 8.00], [-32.73, 19.43, 8.00], [-29.30, 26.29, 8.00], [-24.50, 33.83, 8.00], + [-19.01, 41.37, 8.00], [-14.21, 46.17, 8.00], [-12.16, 47.54, 8.00], [-4.61, 49.60, 8.00], + [4.99, 49.60, 8.00], [12.53, 47.54, 8.00], [14.59, 46.17, 8.00], [19.39, 41.37, 8.00], + [24.87, 33.83, 8.00], [29.67, 26.29, 8.00], [33.10, 19.43, 8.00], [35.84, 10.51, 8.00], + [36.53, 6.40, 8.00], [36.53, -21.03, 8.00], [34.47, -32.00, 8.00], [32.42, -37.49, 8.00], + [30.36, -40.91, 8.00], [24.19, -46.40, 8.00], [18.02, -49.14, 8.00], [6.36, -51.20, 8.00], + [-5.98, -51.20, 8.00], +], dtype=np.float32) + +# UI constants +BTN_SIZE = 192 +IMG_SIZE = 144 +ARC_LENGTH = 133 +ARC_THICKNESS_DEFAULT = 6.7 +ARC_THICKNESS_EXTEND = 12.0 + +SCALES_POS = np.array([0.9, 0.4, 0.4], dtype=np.float32) +SCALES_NEG = np.array([0.7, 0.4, 0.4], dtype=np.float32) + +ARC_POINT_COUNT = 37 # Number of points in the arc +ARC_ANGLES = np.linspace(0.0, np.pi, ARC_POINT_COUNT, dtype=np.float32) + + +@dataclass +class ArcData: + """Data structure for arc rendering parameters.""" + x: float + y: float + width: float + height: float + thickness: float + + +class DriverStateRenderer(Widget): + def __init__(self): + super().__init__() + # Initial state with NumPy arrays + self.face_kpts_draw = DEFAULT_FACE_KPTS_3D.copy() + self.is_active = False + self.is_rhd = False + self.dm_fade_state = 0.0 + self.driver_pose_vals = np.zeros(3, dtype=np.float32) + self.driver_pose_diff = np.zeros(3, dtype=np.float32) + self.driver_pose_sins = np.zeros(3, dtype=np.float32) + self.driver_pose_coss = np.zeros(3, dtype=np.float32) + self.face_keypoints_transformed = np.zeros((DEFAULT_FACE_KPTS_3D.shape[0], 2), dtype=np.float32) + self.position_x: float = 0.0 + self.position_y: float = 0.0 + self.h_arc_data = None + self.v_arc_data = None + + # Pre-allocate drawing arrays + self.face_lines = [rl.Vector2(0, 0) for _ in range(len(DEFAULT_FACE_KPTS_3D))] + self.h_arc_lines = [rl.Vector2(0, 0) for _ in range(ARC_POINT_COUNT)] + self.v_arc_lines = [rl.Vector2(0, 0) for _ in range(ARC_POINT_COUNT)] + + # Load the driver face icon + self.dm_img = gui_app.texture("icons/driver_face.png", IMG_SIZE, IMG_SIZE) + + # Colors + self.white_color = rl.Color(255, 255, 255, 255) + self.arc_color = rl.Color(26, 242, 66, 255) + self.engaged_color = rl.Color(26, 242, 66, 255) + self.disengaged_color = rl.Color(139, 139, 139, 255) + + self.set_visible(lambda: (ui_state.sm["selfdriveState"].alertSize == AlertSize.none and + ui_state.sm.recv_frame["driverStateV2"] > ui_state.started_frame)) + + def _render(self, rect): + # Set opacity based on active state + opacity = 0.65 if self.is_active else 0.2 + + # Draw background circle + rl.draw_circle(int(self.position_x), int(self.position_y), BTN_SIZE // 2, rl.Color(0, 0, 0, 70)) + + # Draw face icon + icon_pos = rl.Vector2(self.position_x - self.dm_img.width // 2, self.position_y - self.dm_img.height // 2) + rl.draw_texture_v(self.dm_img, icon_pos, rl.Color(255, 255, 255, int(255 * opacity))) + + # Draw face outline + self.white_color.a = int(255 * opacity) + rl.draw_spline_linear(self.face_lines, len(self.face_lines), 5.2, self.white_color) + + # Set arc color based on engaged state + self.arc_color = self.engaged_color if ui_state.engaged else self.disengaged_color + self.arc_color.a = int(0.4 * 255 * (1.0 - self.dm_fade_state)) # Fade out when inactive + + # Draw arcs + if self.h_arc_data: + rl.draw_spline_linear(self.h_arc_lines, len(self.h_arc_lines), self.h_arc_data.thickness, self.arc_color) + if self.v_arc_data: + rl.draw_spline_linear(self.v_arc_lines, len(self.v_arc_lines), self.v_arc_data.thickness, self.arc_color) + + def _update_state(self): + """Update the driver monitoring state based on model data""" + sm = ui_state.sm + if not self.is_visible: + return + + # Get monitoring state + dm_state = sm["driverMonitoringState"] + self.is_active = dm_state.activePolicy == log.DriverMonitoringState.MonitoringPolicy.vision + self.is_rhd = dm_state.isRHD + + # Update fade state (smoother transition between active/inactive) + fade_target = 0.0 if self.is_active else 0.5 + self.dm_fade_state = np.clip(self.dm_fade_state + 0.2 * (fade_target - self.dm_fade_state), 0.0, 1.0) + + # Get driver orientation data from appropriate camera + driverstate = sm["driverStateV2"] + driver_data = driverstate.rightDriverData if self.is_rhd else driverstate.leftDriverData + driver_orient = driver_data.faceOrientation + + # Update pose values with scaling and smoothing + driver_orient = np.array(driver_orient) + scales = np.where(driver_orient < 0, SCALES_NEG, SCALES_POS) + v_this = driver_orient * scales + self.driver_pose_diff = np.abs(self.driver_pose_vals - v_this) + self.driver_pose_vals = 0.8 * v_this + 0.2 * self.driver_pose_vals # Smooth changes + + # Apply fade to rotation and compute sin/cos + rotation_amount = self.driver_pose_vals * (1.0 - self.dm_fade_state) + self.driver_pose_sins = np.sin(rotation_amount) + self.driver_pose_coss = np.cos(rotation_amount) + + # Create rotation matrix for 3D face model + sin_y, sin_x, sin_z = self.driver_pose_sins + cos_y, cos_x, cos_z = self.driver_pose_coss + r_xyz = np.array( + [ + [cos_x * cos_z, cos_x * sin_z, -sin_x], + [-sin_y * sin_x * cos_z - cos_y * sin_z, -sin_y * sin_x * sin_z + cos_y * cos_z, -sin_y * cos_x], + [cos_y * sin_x * cos_z - sin_y * sin_z, cos_y * sin_x * sin_z + sin_y * cos_z, cos_y * cos_x], + ] + ) + + # Transform face keypoints using vectorized matrix multiplication + self.face_kpts_draw = DEFAULT_FACE_KPTS_3D @ r_xyz.T + self.face_kpts_draw[:, 2] = self.face_kpts_draw[:, 2] * (1.0 - self.dm_fade_state) + 8 * self.dm_fade_state + + # Pre-calculate the transformed keypoints + kp_depth = (self.face_kpts_draw[:, 2] - 8) / 120.0 + 1.0 + self.face_keypoints_transformed = self.face_kpts_draw[:, :2] * kp_depth[:, None] + + # Pre-calculate all drawing elements + self._pre_calculate_drawing_elements() + + def _pre_calculate_drawing_elements(self): + """Pre-calculate all drawing elements based on the current rectangle""" + # Calculate icon position (bottom-left or bottom-right) + width, height = self._rect.width, self._rect.height + offset = UI_BORDER_SIZE + BTN_SIZE // 2 + self.position_x = self._rect.x + (width - offset if self.is_rhd else offset) + self.position_y = self._rect.y + height - offset + + # Pre-calculate the face lines positions + positioned_keypoints = self.face_keypoints_transformed + np.array([self.position_x, self.position_y]) + for i in range(len(positioned_keypoints)): + self.face_lines[i].x = positioned_keypoints[i][0] + self.face_lines[i].y = positioned_keypoints[i][1] + + # Calculate arc dimensions based on head rotation + delta_x = -self.driver_pose_sins[1] * ARC_LENGTH / 2.0 # Horizontal movement + delta_y = -self.driver_pose_sins[0] * ARC_LENGTH / 2.0 # Vertical movement + + # Horizontal arc + h_width = abs(delta_x) + self.h_arc_data = self._calculate_arc_data( + delta_x, h_width, self.position_x, self.position_y - ARC_LENGTH / 2, + self.driver_pose_sins[1], self.driver_pose_diff[1], is_horizontal=True + ) + + # Vertical arc + v_height = abs(delta_y) + self.v_arc_data = self._calculate_arc_data( + delta_y, v_height, self.position_x - ARC_LENGTH / 2, self.position_y, + self.driver_pose_sins[0], self.driver_pose_diff[0], is_horizontal=False + ) + + def _calculate_arc_data( + self, delta: float, size: float, x: float, y: float, sin_val: float, diff_val: float, is_horizontal: bool + ): + """Calculate arc data and pre-compute arc points.""" + if size <= 0: + return None + + thickness = ARC_THICKNESS_DEFAULT + ARC_THICKNESS_EXTEND * min(1.0, diff_val * 5.0) + start_angle = (90 if sin_val > 0 else -90) if is_horizontal else (0 if sin_val > 0 else 180) + x = min(x + delta, x) if is_horizontal else x + y = y if is_horizontal else min(y + delta, y) + + arc_data = ArcData( + x=x, + y=y, + width=size if is_horizontal else ARC_LENGTH, + height=ARC_LENGTH if is_horizontal else size, + thickness=thickness, + ) + + # Pre-calculate arc points + angles = ARC_ANGLES + np.deg2rad(start_angle) + + center_x = x + arc_data.width / 2 + center_y = y + arc_data.height / 2 + radius_x = arc_data.width / 2 + radius_y = arc_data.height / 2 + + x_coords = center_x + np.cos(angles) * radius_x + y_coords = center_y - np.sin(angles) * radius_y + + arc_lines = self.h_arc_lines if is_horizontal else self.v_arc_lines + for i, (x_coord, y_coord) in enumerate(zip(x_coords, y_coords, strict=True)): + arc_lines[i].x = x_coord + arc_lines[i].y = y_coord + + return arc_data diff --git a/openpilot/selfdrive/ui/onroad/exp_button.py b/openpilot/selfdrive/ui/onroad/exp_button.py new file mode 100644 index 0000000000..9a92ebc3c3 --- /dev/null +++ b/openpilot/selfdrive/ui/onroad/exp_button.py @@ -0,0 +1,70 @@ +import time +import pyray as rl +from openpilot.common.params import Params +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.widgets import Widget + + +class ExpButton(Widget): + def __init__(self, button_size: int, icon_size: int): + super().__init__() + self._params = Params() + self._experimental_mode: bool = False + self._engageable: bool = False + + # State hold mechanism + self._hold_duration = 2.0 # seconds + self._held_mode: bool | None = None + self._hold_end_time: float | None = None + + self._white_color: rl.Color = rl.Color(255, 255, 255, 255) + self._black_bg: rl.Color = rl.Color(0, 0, 0, 166) + self._txt_wheel: rl.Texture = gui_app.texture('icons/chffr_wheel.png', icon_size, icon_size) + self._txt_exp: rl.Texture = gui_app.texture('icons/experimental.png', icon_size, icon_size) + self._rect = rl.Rectangle(0, 0, button_size, button_size) + + def set_rect(self, rect: rl.Rectangle) -> None: + self._rect.x, self._rect.y = rect.x, rect.y + + def _update_state(self) -> None: + selfdrive_state = ui_state.sm["selfdriveState"] + self._experimental_mode = selfdrive_state.experimentalMode + self._engageable = selfdrive_state.engageable or selfdrive_state.enabled + + def _handle_mouse_release(self, _): + super()._handle_mouse_release(_) + if self._is_toggle_allowed(): + new_mode = not self._experimental_mode + self._params.put_bool("ExperimentalMode", new_mode) + + # Hold new state temporarily + self._held_mode = new_mode + self._hold_end_time = time.monotonic() + self._hold_duration + + def _render(self, rect: rl.Rectangle) -> None: + center_x = int(self._rect.x + self._rect.width // 2) + center_y = int(self._rect.y + self._rect.height // 2) + + self._white_color.a = 180 if self.is_pressed or not self._engageable else 255 + + texture = self._txt_exp if self._held_or_actual_mode() else self._txt_wheel + rl.draw_circle(center_x, center_y, self._rect.width / 2, self._black_bg) + rl.draw_texture_ex(texture, rl.Vector2(center_x - texture.width / 2, center_y - texture.height / 2), 0.0, 1.0, self._white_color) + + def _held_or_actual_mode(self): + now = time.monotonic() + if self._hold_end_time and now < self._hold_end_time: + return self._held_mode + + if self._hold_end_time and now >= self._hold_end_time: + self._hold_end_time = self._held_mode = None + + return self._experimental_mode + + def _is_toggle_allowed(self): + if not self._params.get_bool("ExperimentalModeConfirmed"): + return False + + # Mirror exp mode toggle using persistent car params + return ui_state.has_longitudinal_control diff --git a/openpilot/selfdrive/ui/onroad/hud_renderer.py b/openpilot/selfdrive/ui/onroad/hud_renderer.py new file mode 100644 index 0000000000..73df8b3961 --- /dev/null +++ b/openpilot/selfdrive/ui/onroad/hud_renderer.py @@ -0,0 +1,180 @@ +import pyray as rl +from dataclasses import dataclass +from openpilot.common.constants import CV +from openpilot.selfdrive.ui.onroad.exp_button import ExpButton +from openpilot.selfdrive.ui.ui_state import ui_state, UIStatus +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.widgets import Widget + +# Constants +SET_SPEED_NA = 255 +KM_TO_MILE = 0.621371 +CRUISE_DISABLED_CHAR = '–' + + +@dataclass(frozen=True) +class UIConfig: + header_height: int = 300 + border_size: int = 30 + button_size: int = 192 + set_speed_width_metric: int = 200 + set_speed_width_imperial: int = 172 + set_speed_height: int = 204 + wheel_icon_size: int = 144 + + +@dataclass(frozen=True) +class FontSizes: + current_speed: int = 176 + speed_unit: int = 66 + max_speed: int = 40 + set_speed: int = 90 + + +@dataclass(frozen=True) +class Colors: + WHITE = rl.WHITE + DISENGAGED = rl.Color(145, 155, 149, 255) + OVERRIDE = rl.Color(145, 155, 149, 255) # Added + ENGAGED = rl.Color(128, 216, 166, 255) + DISENGAGED_BG = rl.Color(0, 0, 0, 153) + OVERRIDE_BG = rl.Color(145, 155, 149, 204) + ENGAGED_BG = rl.Color(128, 216, 166, 204) + GREY = rl.Color(166, 166, 166, 255) + DARK_GREY = rl.Color(114, 114, 114, 255) + BLACK_TRANSLUCENT = rl.Color(0, 0, 0, 166) + WHITE_TRANSLUCENT = rl.Color(255, 255, 255, 200) + BORDER_TRANSLUCENT = rl.Color(255, 255, 255, 75) + HEADER_GRADIENT_START = rl.Color(0, 0, 0, 114) + HEADER_GRADIENT_END = rl.BLANK + + +UI_CONFIG = UIConfig() +FONT_SIZES = FontSizes() +COLORS = Colors() + + +class HudRenderer(Widget): + def __init__(self): + super().__init__() + """Initialize the HUD renderer.""" + self.is_cruise_set: bool = False + self.is_cruise_available: bool = True + self.set_speed: float = SET_SPEED_NA + self.speed: float = 0.0 + self.v_ego_cluster_seen: bool = False + + self._font_semi_bold: rl.Font = gui_app.font(FontWeight.SEMI_BOLD) + self._font_bold: rl.Font = gui_app.font(FontWeight.BOLD) + self._font_medium: rl.Font = gui_app.font(FontWeight.MEDIUM) + + self._exp_button: ExpButton = ExpButton(UI_CONFIG.button_size, UI_CONFIG.wheel_icon_size) + + def _update_state(self) -> None: + """Update HUD state based on car state and controls state.""" + sm = ui_state.sm + if sm.recv_frame["carState"] < ui_state.started_frame: + self.is_cruise_set = False + self.set_speed = SET_SPEED_NA + self.speed = 0.0 + return + + controls_state = sm['controlsState'] + car_state = sm['carState'] + + v_cruise_cluster = car_state.vCruiseCluster + self.set_speed = ( + controls_state.deprecated.vCruise if v_cruise_cluster == 0.0 else v_cruise_cluster + ) + self.is_cruise_set = 0 < self.set_speed < SET_SPEED_NA + self.is_cruise_available = self.set_speed != -1 + + if self.is_cruise_set and not ui_state.is_metric: + self.set_speed *= KM_TO_MILE + + v_ego_cluster = car_state.vEgoCluster + self.v_ego_cluster_seen = self.v_ego_cluster_seen or v_ego_cluster != 0.0 + v_ego = v_ego_cluster if self.v_ego_cluster_seen else car_state.vEgo + speed_conversion = CV.MS_TO_KPH if ui_state.is_metric else CV.MS_TO_MPH + self.speed = max(0.0, v_ego * speed_conversion) + + def _render(self, rect: rl.Rectangle) -> None: + """Render HUD elements to the screen.""" + # Draw the header background + rl.draw_rectangle_gradient_v( + int(rect.x), + int(rect.y), + int(rect.width), + UI_CONFIG.header_height, + COLORS.HEADER_GRADIENT_START, + COLORS.HEADER_GRADIENT_END, + ) + + if self.is_cruise_available: + self._draw_set_speed(rect) + + self._draw_current_speed(rect) + + button_x = rect.x + rect.width - UI_CONFIG.border_size - UI_CONFIG.button_size + button_y = rect.y + UI_CONFIG.border_size + self._exp_button.render(rl.Rectangle(button_x, button_y, UI_CONFIG.button_size, UI_CONFIG.button_size)) + + def user_interacting(self) -> bool: + return self._exp_button.is_pressed + + def _draw_set_speed(self, rect: rl.Rectangle) -> None: + """Draw the MAX speed indicator box.""" + set_speed_width = UI_CONFIG.set_speed_width_metric if ui_state.is_metric else UI_CONFIG.set_speed_width_imperial + x = rect.x + 60 + (UI_CONFIG.set_speed_width_imperial - set_speed_width) // 2 + y = rect.y + 45 + + set_speed_rect = rl.Rectangle(x, y, set_speed_width, UI_CONFIG.set_speed_height) + rl.draw_rectangle_rounded(set_speed_rect, 0.35, 10, COLORS.BLACK_TRANSLUCENT) + rl.draw_rectangle_rounded_lines_ex(set_speed_rect, 0.35, 10, 6, COLORS.BORDER_TRANSLUCENT) + + max_color = COLORS.GREY + set_speed_color = COLORS.DARK_GREY + if self.is_cruise_set: + set_speed_color = COLORS.WHITE + if ui_state.status == UIStatus.ENGAGED: + max_color = COLORS.ENGAGED + elif ui_state.status == UIStatus.DISENGAGED: + max_color = COLORS.DISENGAGED + elif ui_state.status == UIStatus.OVERRIDE: + max_color = COLORS.OVERRIDE + + max_text = tr("MAX") + max_text_width = measure_text_cached(self._font_semi_bold, max_text, FONT_SIZES.max_speed).x + rl.draw_text_ex( + self._font_semi_bold, + max_text, + rl.Vector2(x + (set_speed_width - max_text_width) / 2, y + 27), + FONT_SIZES.max_speed, + 0, + max_color, + ) + + set_speed_text = CRUISE_DISABLED_CHAR if not self.is_cruise_set else str(round(self.set_speed)) + speed_text_width = measure_text_cached(self._font_bold, set_speed_text, FONT_SIZES.set_speed).x + rl.draw_text_ex( + self._font_bold, + set_speed_text, + rl.Vector2(x + (set_speed_width - speed_text_width) / 2, y + 77), + FONT_SIZES.set_speed, + 0, + set_speed_color, + ) + + def _draw_current_speed(self, rect: rl.Rectangle) -> None: + """Draw the current vehicle speed and unit.""" + speed_text = str(round(self.speed)) + speed_text_size = measure_text_cached(self._font_bold, speed_text, FONT_SIZES.current_speed) + speed_pos = rl.Vector2(rect.x + rect.width / 2 - speed_text_size.x / 2, 180 - speed_text_size.y / 2) + rl.draw_text_ex(self._font_bold, speed_text, speed_pos, FONT_SIZES.current_speed, 0, COLORS.WHITE) + + unit_text = tr("km/h") if ui_state.is_metric else tr("mph") + unit_text_size = measure_text_cached(self._font_medium, unit_text, FONT_SIZES.speed_unit) + unit_pos = rl.Vector2(rect.x + rect.width / 2 - unit_text_size.x / 2, 290 - unit_text_size.y / 2) + rl.draw_text_ex(self._font_medium, unit_text, unit_pos, FONT_SIZES.speed_unit, 0, COLORS.WHITE_TRANSLUCENT) diff --git a/openpilot/selfdrive/ui/onroad/model_renderer.py b/openpilot/selfdrive/ui/onroad/model_renderer.py new file mode 100644 index 0000000000..a4d9b8b65b --- /dev/null +++ b/openpilot/selfdrive/ui/onroad/model_renderer.py @@ -0,0 +1,450 @@ +import colorsys +import numpy as np +import pyray as rl +from openpilot.cereal import messaging +from opendbc.car.structs import car +from dataclasses import dataclass, field +from openpilot.common.filter_simple import FirstOrderFilter +from openpilot.common.params import Params +from openpilot.selfdrive.locationd.calibrationd import HEIGHT_INIT +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.lib.shader_polygon import draw_polygon, Gradient +from openpilot.system.ui.widgets import Widget + +from openpilot.selfdrive.ui.sunnypilot.onroad.model_renderer import ChevronMetrics, ModelRendererSP + +CLIP_MARGIN = 500 +MIN_DRAW_DISTANCE = 10.0 +MAX_DRAW_DISTANCE = 100.0 + +THROTTLE_COLORS = [ + rl.Color(13, 248, 122, 102), # HSLF(148/360, 0.94, 0.51, 0.4) + rl.Color(114, 255, 92, 89), # HSLF(112/360, 1.0, 0.68, 0.35) + rl.Color(114, 255, 92, 0), # HSLF(112/360, 1.0, 0.68, 0.0) +] + +NO_THROTTLE_COLORS = [ + rl.Color(242, 242, 242, 102), # HSLF(148/360, 0.0, 0.95, 0.4) + rl.Color(242, 242, 242, 89), # HSLF(112/360, 0.0, 0.95, 0.35) + rl.Color(242, 242, 242, 0), # HSLF(112/360, 0.0, 0.95, 0.0) +] + + +@dataclass +class ModelPoints: + raw_points: np.ndarray = field(default_factory=lambda: np.empty((0, 3), dtype=np.float32)) + projected_points: np.ndarray = field(default_factory=lambda: np.empty((0, 2), dtype=np.float32)) + + +@dataclass +class LeadVehicle: + glow: list[tuple[float, float]] = field(default_factory=list) + chevron: list[tuple[float, float]] = field(default_factory=list) + fill_alpha: int = 0 + + +class ModelRenderer(Widget, ChevronMetrics, ModelRendererSP): + def __init__(self): + Widget.__init__(self) + ChevronMetrics.__init__(self) + ModelRendererSP.__init__(self) + self._longitudinal_control = False + self._experimental_mode = False + self._blend_filter = FirstOrderFilter(1.0, 0.25, 1 / gui_app.target_fps) + self._prev_allow_throttle = True + self._lane_line_probs = np.zeros(4, dtype=np.float32) + self._road_edge_stds = np.zeros(2, dtype=np.float32) + self._lead_vehicles = [LeadVehicle(), LeadVehicle()] + self._path_offset_z = HEIGHT_INIT[0] + self._counter = -1 + self._camera_offset = ui_state.params.get("CameraOffset", return_default=True) if ui_state.active_bundle else 0.0 + # Initialize ModelPoints objects + self._path = ModelPoints() + self._lane_lines = [ModelPoints() for _ in range(4)] + self._road_edges = [ModelPoints() for _ in range(2)] + self._acceleration_x = np.empty((0,), dtype=np.float32) + + # Transform matrix (3x3 for car space to screen space) + self._car_space_transform = np.zeros((3, 3), dtype=np.float32) + self._transform_dirty = True + self._clip_region = None + + self._exp_gradient = Gradient( + start=(0.0, 1.0), # Bottom of path + end=(0.0, 0.0), # Top of path + colors=[], + stops=[], + ) + + # Get longitudinal control setting from car parameters + if car_params := Params().get("CarParams"): + cp = messaging.log_from_bytes(car_params, car.CarParams) + self._longitudinal_control = cp.openpilotLongitudinalControl + + def set_transform(self, transform: np.ndarray): + self._car_space_transform = transform.astype(np.float32) + self._transform_dirty = True + + def _render(self, rect: rl.Rectangle): + sm = ui_state.sm + + # Check if data is up-to-date + if (sm.recv_frame["liveCalibration"] < ui_state.started_frame or + sm.recv_frame["modelV2"] < ui_state.started_frame): + return + + # Set up clipping region + self._clip_region = rl.Rectangle( + rect.x - CLIP_MARGIN, rect.y - CLIP_MARGIN, rect.width + 2 * CLIP_MARGIN, rect.height + 2 * CLIP_MARGIN + ) + + # Update state + self._experimental_mode = sm['selfdriveState'].experimentalMode + + live_calib = sm['liveCalibration'] + self._path_offset_z = live_calib.height[0] if live_calib.height else HEIGHT_INIT[0] + + if self._counter % 60 == 0: + self._camera_offset = ui_state.params.get("CameraOffset", return_default=True) if ui_state.active_bundle else 0.0 + self._counter += 1 + + if sm.updated['carParams']: + self._longitudinal_control = sm['carParams'].openpilotLongitudinalControl + + model = sm['modelV2'] + radar_state = sm['radarState'] if sm.valid['radarState'] else None + lead_one = radar_state.leadOne if radar_state else None + render_lead_indicator = self._longitudinal_control and radar_state is not None + + # Update model data when needed + model_updated = sm.updated['modelV2'] + if model_updated or sm.updated['radarState'] or self._transform_dirty: + if model_updated: + self._update_raw_points(model) + + path_x_array = self._path.raw_points[:, 0] + if path_x_array.size == 0: + return + + self._update_model(lead_one, path_x_array) + if render_lead_indicator: + self._update_leads(radar_state, path_x_array) + self._transform_dirty = False + + # Draw elements + self._draw_lane_lines() + self._draw_path(sm) + + if render_lead_indicator and radar_state: + self._draw_lead_indicator() + self.chevron_metrics.draw_lead_status(sm, radar_state, self._rect, self._lead_vehicles) + + def _update_raw_points(self, model): + """Update raw 3D points from model data""" + self._path.raw_points = np.array([model.position.x, np.array(model.position.y) + self._camera_offset, model.position.z], dtype=np.float32).T + + for i, lane_line in enumerate(model.laneLines): + self._lane_lines[i].raw_points = np.array([lane_line.x, np.array(lane_line.y) + self._camera_offset, lane_line.z], dtype=np.float32).T + + for i, road_edge in enumerate(model.roadEdges): + self._road_edges[i].raw_points = np.array([road_edge.x, np.array(road_edge.y) + self._camera_offset, road_edge.z], dtype=np.float32).T + + self._lane_line_probs = np.array(model.laneLineProbs, dtype=np.float32) + self._road_edge_stds = np.array(model.roadEdgeStds, dtype=np.float32) + self._acceleration_x = np.array(model.acceleration.x, dtype=np.float32) + + def _update_leads(self, radar_state, path_x_array): + """Update positions of lead vehicles""" + self._lead_vehicles = [LeadVehicle(), LeadVehicle()] + leads = [radar_state.leadOne, radar_state.leadTwo] + + for i, lead_data in enumerate(leads): + if lead_data and lead_data.present: + d_rel, y_rel, v_rel = lead_data.dRel, lead_data.yRel, lead_data.vRel + idx = self._get_path_length_idx(path_x_array, d_rel) + + # Get z-coordinate from path at the lead vehicle position + z = self._path.raw_points[idx, 2] if idx < len(self._path.raw_points) else 0.0 + point = self._map_to_screen(d_rel, -y_rel + self._camera_offset, z + self._path_offset_z) + if point: + self._lead_vehicles[i] = self._update_lead_vehicle(d_rel, v_rel, point, self._rect) + + def _update_model(self, lead, path_x_array): + """Update model visualization data based on model message""" + max_distance = np.clip(path_x_array[-1], MIN_DRAW_DISTANCE, MAX_DRAW_DISTANCE) + max_idx = self._get_path_length_idx(self._lane_lines[0].raw_points[:, 0], max_distance) + + # Update lane lines using raw points + for i, lane_line in enumerate(self._lane_lines): + lane_line.projected_points = self._map_line_to_polygon( + lane_line.raw_points, 0.025 * self._lane_line_probs[i], 0.0, max_idx, max_distance + ) + + # Update road edges using raw points + for road_edge in self._road_edges: + road_edge.projected_points = self._map_line_to_polygon(road_edge.raw_points, 0.025, 0.0, max_idx, max_distance) + + # Update path using raw points + if lead and lead.present: + lead_d = lead.dRel * 2.0 + max_distance = np.clip(lead_d - min(lead_d * 0.35, 10.0), 0.0, max_distance) + + max_idx = self._get_path_length_idx(path_x_array, max_distance) + self._path.projected_points = self._map_line_to_polygon( + self._path.raw_points, 0.9, self._path_offset_z, max_idx, max_distance, allow_invert=False + ) + + self._update_experimental_gradient() + + def _update_experimental_gradient(self): + """Pre-calculate experimental mode gradient colors""" + if not self._experimental_mode: + return + + max_len = min(len(self._path.projected_points) // 2, len(self._acceleration_x)) + + segment_colors = [] + gradient_stops = [] + + i = 0 + while i < max_len: + # Some points (screen space) are out of frame (rect space) + track_y = self._path.projected_points[i][1] + if track_y < self._rect.y or track_y > (self._rect.y + self._rect.height): + i += 1 + continue + + # Calculate color based on acceleration (0 is bottom, 1 is top) + lin_grad_point = 1 - (track_y - self._rect.y) / self._rect.height + + # speed up: 120, slow down: 0 + path_hue = np.clip(60 + self._acceleration_x[i] * 35, 0, 120) + + saturation = min(abs(self._acceleration_x[i] * 1.5), 1) + lightness = np.interp(saturation, [0.0, 1.0], [0.95, 0.62]) + alpha = np.interp(lin_grad_point, [0.75 / 2.0, 0.75], [0.4, 0.0]) + + # Use HSL to RGB conversion + color = self._hsla_to_color(path_hue / 360.0, saturation, lightness, alpha) + + gradient_stops.append(lin_grad_point) + segment_colors.append(color) + + # Skip a point, unless next is last + i += 1 + (1 if (i + 2) < max_len else 0) + + # Store the gradient in the path object + self._exp_gradient = Gradient( + start=(0.0, 1.0), # Bottom of path + end=(0.0, 0.0), # Top of path + colors=segment_colors, + stops=gradient_stops, + ) + + def _update_lead_vehicle(self, d_rel, v_rel, point, rect): + speed_buff, lead_buff = 10.0, 40.0 + + # Calculate fill alpha + fill_alpha = 0 + if d_rel < lead_buff: + fill_alpha = 255 * (1.0 - (d_rel / lead_buff)) + if v_rel < 0: + fill_alpha += 255 * (-1 * (v_rel / speed_buff)) + fill_alpha = min(fill_alpha, 255) + + # Calculate size and position + sz = np.clip((25 * 30) / (d_rel / 3 + 30), 15.0, 30.0) * 2.35 + x = np.clip(point[0], 0.0, rect.width - sz / 2) + y = min(point[1], rect.height - sz * 0.6) + + g_xo = sz / 5 + g_yo = sz / 10 + + glow = [(x + (sz * 1.35) + g_xo, y + sz + g_yo), (x, y - g_yo), (x - (sz * 1.35) - g_xo, y + sz + g_yo)] + chevron = [(x + (sz * 1.25), y + sz), (x, y), (x - (sz * 1.25), y + sz)] + + return LeadVehicle(glow=glow, chevron=chevron, fill_alpha=int(fill_alpha)) + + def _draw_lane_lines(self): + """Draw lane lines and road edges""" + for i, lane_line in enumerate(self._lane_lines): + if lane_line.projected_points.size == 0: + continue + + alpha = np.clip(self._lane_line_probs[i], 0.0, 0.7) + color = rl.Color(255, 255, 255, int(alpha * 255)) + draw_polygon(self._rect, lane_line.projected_points, color) + + for i, road_edge in enumerate(self._road_edges): + if road_edge.projected_points.size == 0: + continue + + alpha = np.clip(1.0 - self._road_edge_stds[i], 0.0, 1.0) + color = rl.Color(255, 0, 0, int(alpha * 255)) + draw_polygon(self._rect, road_edge.projected_points, color) + + def _draw_path(self, sm): + """Draw path with dynamic coloring based on mode and throttle state.""" + if not self._path.projected_points.size: + return + + allow_throttle = sm['longitudinalPlan'].allowThrottle or not self._longitudinal_control + self._blend_filter.update(int(allow_throttle)) + + if ui_state.rainbow_path: + self.rainbow_path.draw_rainbow_path(self._rect, self._path) + return + + if self._experimental_mode: + # Draw with acceleration coloring + if len(self._exp_gradient.colors) > 1: + draw_polygon(self._rect, self._path.projected_points, gradient=self._exp_gradient) + else: + draw_polygon(self._rect, self._path.projected_points, rl.Color(255, 255, 255, 30)) + else: + # Blend throttle/no throttle colors based on transition + blend_factor = round(self._blend_filter.x * 100) / 100 + blended_colors = self._blend_colors(NO_THROTTLE_COLORS, THROTTLE_COLORS, blend_factor) + gradient = Gradient( + start=(0.0, 1.0), # Bottom of path + end=(0.0, 0.0), # Top of path + colors=blended_colors, + stops=[0.0, 0.5, 1.0], + ) + draw_polygon(self._rect, self._path.projected_points, gradient=gradient) + + def _draw_lead_indicator(self): + # Draw lead vehicles if available + for lead in self._lead_vehicles: + if not lead.glow or not lead.chevron: + continue + + rl.draw_triangle_fan(lead.glow, len(lead.glow), rl.Color(218, 202, 37, 255)) + rl.draw_triangle_fan(lead.chevron, len(lead.chevron), rl.Color(201, 34, 49, lead.fill_alpha)) + + @staticmethod + def _get_path_length_idx(pos_x_array: np.ndarray, path_distance: float) -> int: + """Get the index corresponding to the given path distance""" + if len(pos_x_array) == 0: + return 0 + indices = np.where(pos_x_array <= path_distance)[0] + return indices[-1] if indices.size > 0 else 0 + + def _map_to_screen(self, in_x, in_y, in_z): + """Project a point in car space to screen space""" + input_pt = np.array([in_x, in_y, in_z]) + pt = self._car_space_transform @ input_pt + + if abs(pt[2]) < 1e-6: + return None + + x, y = pt[0] / pt[2], pt[1] / pt[2] + + clip = self._clip_region + if not (clip.x <= x <= clip.x + clip.width and clip.y <= y <= clip.y + clip.height): + return None + + return (x, y) + + def _map_line_to_polygon(self, line: np.ndarray, y_off: float, z_off: float, max_idx: int, max_distance: float, allow_invert: bool = True) -> np.ndarray: + """Convert 3D line to 2D polygon for rendering.""" + if line.shape[0] == 0: + return np.empty((0, 2), dtype=np.float32) + + # Slice points and filter non-negative x-coordinates + points = line[:max_idx + 1] + + # Interpolate around max_idx so path end is smooth (max_distance is always >= p0.x) + if 0 < max_idx < line.shape[0] - 1: + p0 = line[max_idx] + p1 = line[max_idx + 1] + x0, x1 = p0[0], p1[0] + interp_y = np.interp(max_distance, [x0, x1], [p0[1], p1[1]]) + interp_z = np.interp(max_distance, [x0, x1], [p0[2], p1[2]]) + interp_point = np.array([max_distance, interp_y, interp_z], dtype=points.dtype) + points = np.concatenate((points, interp_point[None, :]), axis=0) + + points = points[points[:, 0] >= 0] + if points.shape[0] == 0: + return np.empty((0, 2), dtype=np.float32) + + N = points.shape[0] + # Generate left and right 3D points in one array using broadcasting + offsets = np.array([[0, -y_off, z_off], [0, y_off, z_off]], dtype=np.float32) + points_3d = points[None, :, :] + offsets[:, None, :] # Shape: 2xNx3 + points_3d = points_3d.reshape(2 * N, 3) # Shape: (2*N)x3 + + # Transform all points to projected space in one operation + proj = self._car_space_transform @ points_3d.T # Shape: 3x(2*N) + proj = proj.reshape(3, 2, N) + left_proj = proj[:, 0, :] + right_proj = proj[:, 1, :] + + # Filter points where z is sufficiently large + valid_proj = (np.abs(left_proj[2]) >= 1e-6) & (np.abs(right_proj[2]) >= 1e-6) + if not np.any(valid_proj): + return np.empty((0, 2), dtype=np.float32) + + # Compute screen coordinates + left_screen = left_proj[:2, valid_proj] / left_proj[2, valid_proj][None, :] + right_screen = right_proj[:2, valid_proj] / right_proj[2, valid_proj][None, :] + + # Define clip region bounds + clip = self._clip_region + x_min, x_max = clip.x, clip.x + clip.width + y_min, y_max = clip.y, clip.y + clip.height + + # Filter points within clip region + left_in_clip = ( + (left_screen[0] >= x_min) & (left_screen[0] <= x_max) & + (left_screen[1] >= y_min) & (left_screen[1] <= y_max) + ) + right_in_clip = ( + (right_screen[0] >= x_min) & (right_screen[0] <= x_max) & + (right_screen[1] >= y_min) & (right_screen[1] <= y_max) + ) + both_in_clip = left_in_clip & right_in_clip + + if not np.any(both_in_clip): + return np.empty((0, 2), dtype=np.float32) + + # Select valid and clipped points + left_screen = left_screen[:, both_in_clip] + right_screen = right_screen[:, both_in_clip] + + # Handle Y-coordinate inversion on hills + if not allow_invert and left_screen.shape[1] > 1: + y = left_screen[1, :] # y-coordinates + keep = y == np.minimum.accumulate(y) + if not np.any(keep): + return np.empty((0, 2), dtype=np.float32) + left_screen = left_screen[:, keep] + right_screen = right_screen[:, keep] + + return np.vstack((left_screen.T, right_screen[:, ::-1].T)).astype(np.float32) + + @staticmethod + def _hsla_to_color(h, s, l, a): + rgb = colorsys.hls_to_rgb(h, l, s) + return rl.Color( + int(rgb[0] * 255), + int(rgb[1] * 255), + int(rgb[2] * 255), + int(a * 255) + ) + + @staticmethod + def _blend_colors(begin_colors, end_colors, t): + if t >= 1.0: + return end_colors + if t <= 0.0: + return begin_colors + + inv_t = 1.0 - t + return [rl.Color( + int(inv_t * start.r + t * end.r), + int(inv_t * start.g + t * end.g), + int(inv_t * start.b + t * end.b), + int(inv_t * start.a + t * end.a) + ) for start, end in zip(begin_colors, end_colors, strict=True)] diff --git a/openpilot/selfdrive/ui/soundd.py b/openpilot/selfdrive/ui/soundd.py new file mode 100644 index 0000000000..a0ffbacffe --- /dev/null +++ b/openpilot/selfdrive/ui/soundd.py @@ -0,0 +1,224 @@ +import math +import numpy as np +import time +import wave + + +from openpilot.cereal import log, messaging, custom +from openpilot.common.basedir import BASEDIR +from openpilot.common.filter_simple import FirstOrderFilter +from openpilot.common.realtime import Ratekeeper +from openpilot.common.utils import retry +from openpilot.common.swaglog import cloudlog + +from openpilot.system import micd +from openpilot.common.hardware import HARDWARE + +from openpilot.sunnypilot.selfdrive.ui.quiet_mode import QuietMode + +SAMPLE_RATE = 48000 +SAMPLE_BUFFER = 4096 # (approx 100ms) +MAX_VOLUME = 1.0 +MIN_VOLUME = 0.1 +ALERT_RAMP_TIME = 4 # seconds to ramp to max volume for warningImmediate +SELFDRIVE_STATE_TIMEOUT = 5 # 5 seconds +FILTER_DT = 1. / (micd.SAMPLE_RATE / micd.FFT_SAMPLES) + +AMBIENT_DB = 26 # DB where MIN_VOLUME is applied +DB_SCALE = 30 # AMBIENT_DB + DB_SCALE is where MAX_VOLUME is applied + +VOLUME_BASE = 20 +if HARDWARE.get_device_type() == "tizi": + AMBIENT_DB = 30 + VOLUME_BASE = 10 + +AudibleAlert = log.SelfdriveState.AudibleAlert +AudibleAlertSP = custom.SelfdriveStateSP.AudibleAlert + + +sound_list_sp: dict[int, tuple[str, int | None, float]] = { + # AudibleAlertSP, file name, play count (none for infinite) + AudibleAlertSP.promptSingleLow: ("prompt_single_low.wav", 1, MAX_VOLUME), + AudibleAlertSP.promptSingleHigh: ("prompt_single_high.wav", 1, MAX_VOLUME), +} + +sound_list: dict[int, tuple[str, int | None, float]] = { + # AudibleAlert, file name, play count (none for infinite) + AudibleAlert.engage: ("engage.wav", 1, MAX_VOLUME), + AudibleAlert.disengage: ("disengage.wav", 1, MAX_VOLUME), + AudibleAlert.refuse: ("refuse.wav", 1, MAX_VOLUME), + + AudibleAlert.prompt: ("warning.wav", 1, MAX_VOLUME), + AudibleAlert.promptRepeat: ("warning.wav", None, MAX_VOLUME), + AudibleAlert.promptDistracted: ("dm_warning.wav", None, MAX_VOLUME), + + AudibleAlert.preAlert: ("pre_alert.wav", 1, MAX_VOLUME), + AudibleAlert.complete: ("complete.wav", 1, MAX_VOLUME), + + AudibleAlert.warningSoft: ("critical.wav", None, MAX_VOLUME), + AudibleAlert.warningImmediate: ("dm_critical.wav", None, MAX_VOLUME), + + **sound_list_sp, +} +if HARDWARE.get_device_type() == "tizi": + sound_list.update({ + AudibleAlert.engage: ("engage_tizi.wav", 1, MAX_VOLUME), + AudibleAlert.disengage: ("disengage_tizi.wav", 1, MAX_VOLUME), + }) + +def check_selfdrive_timeout_alert(sm): + ss_missing = time.monotonic() - sm.recv_time['selfdriveState'] + + if ss_missing > SELFDRIVE_STATE_TIMEOUT: + if (sm['selfdriveState'].enabled or sm['selfdriveStateSP'].mads.enabled) and (ss_missing - SELFDRIVE_STATE_TIMEOUT) < 10: + return True + + return False + + +class Soundd(QuietMode): + def __init__(self): + super().__init__() + + self.load_sounds() + + self.current_alert = AudibleAlert.none + self.current_volume = MIN_VOLUME + self.current_sound_frame = 0 + + self.ramp_start_volume = MIN_VOLUME + self.ramp_start_time = 0. + + self.selfdrive_timeout_alert = False + self.pending_stop = False + + self.spl_filter_weighted = FirstOrderFilter(0, 2.5, FILTER_DT, initialized=False) + + def load_sounds(self): + self.loaded_sounds: dict[int, np.ndarray] = {} + + # Load all sounds + for sound in sound_list: + filename, play_count, volume = sound_list[sound] + + with wave.open(BASEDIR + "/openpilot/selfdrive/assets/sounds/" + filename, 'r') as wavefile: + assert wavefile.getnchannels() == 1 + assert wavefile.getsampwidth() == 2 + assert wavefile.getframerate() == SAMPLE_RATE + + length = wavefile.getnframes() + self.loaded_sounds[sound] = np.frombuffer(wavefile.readframes(length), dtype=np.int16).astype(np.float32) / (2**16/2) + + def get_sound_data(self, frames): # get "frames" worth of data from the current alert sound, looping when required + + ret = np.zeros(frames, dtype=np.float32) + + if self.should_play_sound(self.current_alert): + num_loops = sound_list[self.current_alert][1] + sound_data = self.loaded_sounds[self.current_alert] + written_frames = 0 + + current_sound_frame = self.current_sound_frame % len(sound_data) + loops = self.current_sound_frame // len(sound_data) + + while written_frames < frames and (num_loops is None or loops < num_loops): + available_frames = sound_data.shape[0] - current_sound_frame + frames_to_write = min(available_frames, frames - written_frames) + ret[written_frames:written_frames+frames_to_write] = sound_data[current_sound_frame:current_sound_frame+frames_to_write] + written_frames += frames_to_write + self.current_sound_frame += frames_to_write + current_sound_frame = self.current_sound_frame % len(sound_data) + loops = self.current_sound_frame // len(sound_data) + if self.pending_stop and current_sound_frame == 0: + self.current_alert = AudibleAlert.none + self.pending_stop = False + break + + return ret * self.current_volume + + def callback(self, data_out: np.ndarray, frames: int, time, status) -> None: + if status: + cloudlog.warning(f"soundd stream over/underflow: {status}") + data_out[:frames, 0] = self.get_sound_data(frames) + + def update_alert(self, new_alert): + current_alert_played_once = self.current_alert == AudibleAlert.none or self.current_sound_frame >= len(self.loaded_sounds[self.current_alert]) + # let looping sounds finish the current loop instead of cutting off mid tone + if new_alert == AudibleAlert.none and self.current_alert != AudibleAlert.none and sound_list[self.current_alert][1] is None: + if current_alert_played_once: + self.pending_stop = True + else: + self.current_alert = AudibleAlert.none + self.current_sound_frame = 0 + return + self.pending_stop = False + if self.current_alert != new_alert and (new_alert != AudibleAlert.none or current_alert_played_once): + if new_alert == AudibleAlert.warningImmediate: + self.ramp_start_volume = self.current_volume + self.ramp_start_time = time.monotonic() + self.current_alert = new_alert + self.current_sound_frame = 0 + + def get_audible_alert(self, sm): + if sm.updated['selfdriveState']: + new_alert = sm['selfdriveState'].alertSound.raw + self.update_alert(new_alert) + elif check_selfdrive_timeout_alert(sm): + self.update_alert(AudibleAlert.warningImmediate) + self.selfdrive_timeout_alert = True + elif self.selfdrive_timeout_alert: + self.update_alert(AudibleAlert.none) + self.selfdrive_timeout_alert = False + + def calculate_volume(self, weighted_db): + volume = ((weighted_db - AMBIENT_DB) / DB_SCALE) * (MAX_VOLUME - MIN_VOLUME) + MIN_VOLUME + return math.pow(VOLUME_BASE, (np.clip(volume, MIN_VOLUME, MAX_VOLUME) - 1)) + + @retry(attempts=10, delay=3) + def get_stream(self, sd): + # reload sounddevice to reinitialize portaudio + sd._terminate() + sd._initialize() + return sd.OutputStream(channels=1, samplerate=SAMPLE_RATE, callback=self.callback, blocksize=SAMPLE_BUFFER) + + def soundd_thread(self): + # sounddevice must be imported after forking processes + import sounddevice as sd + + sm = messaging.SubMaster(['selfdriveState', 'selfdriveStateSP', 'soundPressure']) + + with self.get_stream(sd) as stream: + rk = Ratekeeper(20) + + cloudlog.info(f"soundd stream started: {stream.samplerate=} {stream.channels=} {stream.dtype=} {stream.device=}, {stream.blocksize=}") + while True: + sm.update(0) + + self.load_param() + + # freeze volume during alerts to avoid mic feedback increasing volume + if sm.updated['soundPressure']: + self.spl_filter_weighted.update(sm["soundPressure"].soundPressureWeightedDb) + if self.current_alert == AudibleAlert.none: + self.current_volume = self.calculate_volume(float(self.spl_filter_weighted.x)) + + self.get_audible_alert(sm) + + # Ramp up immediate warning sound over 4s + if self.current_alert == AudibleAlert.warningImmediate: + elapsed = time.monotonic() - self.ramp_start_time + ramp_vol = float(np.interp(elapsed, [0, ALERT_RAMP_TIME], [self.ramp_start_volume, MAX_VOLUME])) + self.current_volume = max(self.current_volume, ramp_vol) + + rk.keep_time() + + assert stream.active + + +def main(): + s = Soundd() + s.soundd_thread() + + +if __name__ == "__main__": + main() diff --git a/selfdrive/ui/onroad/__init__.py b/openpilot/selfdrive/ui/sunnypilot/__init__.py similarity index 100% rename from selfdrive/ui/onroad/__init__.py rename to openpilot/selfdrive/ui/sunnypilot/__init__.py diff --git a/selfdrive/ui/tests/__init__.py b/openpilot/selfdrive/ui/sunnypilot/layouts/__init__.py similarity index 100% rename from selfdrive/ui/tests/__init__.py rename to openpilot/selfdrive/ui/sunnypilot/layouts/__init__.py diff --git a/openpilot/selfdrive/ui/sunnypilot/layouts/onboarding.py b/openpilot/selfdrive/ui/sunnypilot/layouts/onboarding.py new file mode 100644 index 0000000000..a86677a7b1 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/layouts/onboarding.py @@ -0,0 +1,115 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import pyray as rl +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.ui.lib.application import FontWeight +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.button import Button, ButtonStyle +from openpilot.system.ui.widgets.label import Label +from openpilot.common.version import sunnylink_consent_version, sunnylink_consent_declined + + +class SunnylinkConsentPage(Widget): + def __init__(self, done_callback=None): + super().__init__() + self._done_callback = done_callback + self._step = 0 + + self._title = self._child(Label(tr("sunnylink"), font_size=90, font_weight=FontWeight.BOLD, text_alignment=rl.GuiTextAlignment.TEXT_ALIGN_LEFT)) + + self._content = [ + { + "text": tr("sunnylink enables secured remote access to your comma device from anywhere, " + + "including settings management, remote monitoring, real-time dashboard, etc."), + "primary_btn": tr("Enable"), + "secondary_btn": tr("Disable"), + "highlight_primary": True + }, + { + "text": tr("sunnylink is designed to be enabled as part of sunnypilot's core functionality. " + + "If sunnylink is disabled, features such as settings management, remote monitoring, " + + "real-time dashboards will be unavailable."), + "secondary_btn": tr("Back"), + "danger_btn": tr("Disable"), + "highlight_primary": True + } + ] + + self._primary_btn = self._child(Button("", button_style=ButtonStyle.PRIMARY, click_callback=lambda: self._handle_choice("enable"))) + self._secondary_btn = self._child(Button("", button_style=ButtonStyle.NORMAL, click_callback=lambda: self._handle_choice("secondary"))) + self._danger_btn = self._child(Button("", button_style=ButtonStyle.DANGER, click_callback=lambda: self._handle_choice("disable"))) + self._desc = self._child(Label("", font_size=90, font_weight=FontWeight.MEDIUM, text_alignment=rl.GuiTextAlignment.TEXT_ALIGN_LEFT)) + + def _handle_choice(self, choice): + if choice == "enable": + ui_state.params.put_bool("SunnylinkEnabled", True) + ui_state.params.put("CompletedSunnylinkConsentVersion", sunnylink_consent_version) + if self._done_callback: + self._done_callback() + elif choice == "secondary": + if self._step == 0: + self._step = 1 + elif self._step == 1: + self._step = 0 + elif choice == "disable": + ui_state.params.put_bool("SunnylinkEnabled", False) + ui_state.params.put("CompletedSunnylinkConsentVersion", sunnylink_consent_declined) + if self._done_callback: + self._done_callback() + + def _render(self, _): + step_data = self._content[self._step] + + welcome_x = self._rect.x + 95 + welcome_y = self._rect.y + 165 + welcome_rect = rl.Rectangle(welcome_x, welcome_y, self._rect.width - welcome_x, 90) + self._title.render(welcome_rect) + + desc_x = welcome_x + desc_y = welcome_y + 120 + desc_rect = rl.Rectangle(desc_x, desc_y, self._rect.width - desc_x, self._rect.height - desc_y - 250) + + self._desc.set_text(step_data["text"]) + self._desc.render(desc_rect) + + btn_y = self._rect.y + self._rect.height - 160 - 45 + + if "danger_btn" in step_data: + btn_width = (self._rect.width - 45 * 3) / 2 + + self._secondary_btn.set_text(step_data["secondary_btn"]) + self._secondary_btn.render(rl.Rectangle(self._rect.x + 45, btn_y, btn_width, 160)) + + self._danger_btn.set_text(step_data["danger_btn"]) + self._danger_btn.render(rl.Rectangle(self._rect.x + 45 * 2 + btn_width, btn_y, btn_width, 160)) + + else: + btn_width = (self._rect.width - 45 * 3) / 2 + + self._secondary_btn.set_text(step_data["secondary_btn"]) + self._secondary_btn.render(rl.Rectangle(self._rect.x + 45, btn_y, btn_width, 160)) + + self._primary_btn.set_text(step_data["primary_btn"]) + self._primary_btn.render(rl.Rectangle(self._rect.x + 45 * 2 + btn_width, btn_y, btn_width, 160)) + + +class SunnylinkOnboarding: + def __init__(self): + self.consent_page = SunnylinkConsentPage(done_callback=self._on_done) + self.consent_done: bool = ui_state.params.get("CompletedSunnylinkConsentVersion") in {sunnylink_consent_version, sunnylink_consent_declined} + + @property + def completed(self) -> bool: + return self.consent_done + + def _on_done(self): + self.consent_done = True + + def render(self, rect): + if not self.consent_done: + self.consent_page.render(rect) diff --git a/selfdrive/ui/widgets/__init__.py b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/__init__.py similarity index 100% rename from selfdrive/ui/widgets/__init__.py rename to openpilot/selfdrive/ui/sunnypilot/layouts/settings/__init__.py diff --git a/openpilot/selfdrive/ui/sunnypilot/layouts/settings/cruise.py b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/cruise.py new file mode 100644 index 0000000000..671174ac7a --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/cruise.py @@ -0,0 +1,193 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from enum import IntEnum + +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.cruise_sub_layouts.speed_limit_settings import SpeedLimitSettingsLayout +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.ui.lib.multilang import tr, tr_noop +from openpilot.system.ui.sunnypilot.widgets.list_view import toggle_item_sp, option_item_sp, simple_button_item_sp +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.scroller_tici import Scroller + + +class PanelType(IntEnum): + CRUISE = 0 + SLA = 1 + + +ICBM_DESC = tr_noop("When enabled, sunnypilot will attempt to manage the built-in cruise control buttons " + + "by emulating button presses for limited longitudinal control.") +ICMB_UNAVAILABLE = tr_noop("Intelligent Cruise Button Management is currently unavailable on this platform.") +ICMB_UNAVAILABLE_LONG_AVAILABLE = tr_noop("Disable the sunnypilot Longitudinal Control (alpha) toggle to allow Intelligent Cruise Button Management.") +ICMB_UNAVAILABLE_LONG_UNAVAILABLE = tr_noop("sunnypilot Longitudinal Control is the default longitudinal control for this platform.") + +ACC_ENABLED_DESCRIPTION = tr_noop("Enable custom Short & Long press increments for cruise speed increase/decrease.") +ACC_NOLONG_DESCRIPTION = tr_noop("This feature can only be used with sunnypilot longitudinal control enabled.") +ACC_PCMCRUISE_DISABLED_DESCRIPTION = tr_noop("This feature is not supported on this platform due to vehicle limitations.") +ONROAD_ONLY_DESCRIPTION = tr_noop("Start the vehicle to check vehicle compatibility.") + + +class CruiseLayout(Widget): + def __init__(self): + super().__init__() + self._current_panel = PanelType.CRUISE + self._speed_limit_layout = SpeedLimitSettingsLayout(lambda: self._set_current_panel(PanelType.CRUISE)) + + items = self._initialize_items() + self._scroller = Scroller(items, line_separator=True, spacing=0) + + def _initialize_items(self): + + self.icbm_toggle = toggle_item_sp( + title=tr("Intelligent Cruise Button Management (ICBM) (Alpha)"), + description="", + param="IntelligentCruiseButtonManagement") + + self.scc_v_toggle = toggle_item_sp( + title=tr("Smart Cruise Control - Vision"), + description=tr("Use vision path predictions to estimate the appropriate speed to drive through turns ahead."), + param="SmartCruiseControlVision") + + self.scc_m_toggle = toggle_item_sp( + title=tr("Smart Cruise Control - Map"), + description=tr("Use map data to estimate the appropriate speed to drive through turns ahead."), + param="SmartCruiseControlMap") + + self.custom_acc_toggle = toggle_item_sp( + title=tr("Custom ACC Speed Increments"), + description="", + param="CustomAccIncrementsEnabled", + callback=self._on_custom_acc_toggle) + + self.custom_acc_short_increment = option_item_sp( + title=tr("Short Press Increment"), + param="CustomAccShortPressIncrement", + min_value=1, max_value=10, value_change_step=1, + inline=True) + + self.custom_acc_long_increment = option_item_sp( + title=tr("Long Press Increment"), + param="CustomAccLongPressIncrement", + value_map={1: 1, 2: 5, 3: 10}, + min_value=1, max_value=3, value_change_step=1, + inline=True) + + self.sla_settings_button = simple_button_item_sp( + button_text=lambda: tr("Speed Limit"), + button_width=800, + callback=lambda: self._set_current_panel(PanelType.SLA) + ) + + self.dec_toggle = toggle_item_sp( + title=tr("Enable Dynamic Experimental Control"), + description=tr("Enable toggle to allow the model to determine when to use sunnypilot ACC or sunnypilot End to End Longitudinal."), + param="DynamicExperimentalControl") + + items = [ + self.icbm_toggle, + self.dec_toggle, + self.scc_v_toggle, + self.scc_m_toggle, + self.custom_acc_toggle, + self.custom_acc_short_increment, + self.custom_acc_long_increment, + self.sla_settings_button, + ] + return items + + def _render(self, rect): + if self._current_panel == PanelType.SLA: + self._speed_limit_layout.render(rect) + else: + self._scroller.render(rect) + + def show_event(self): + self._set_current_panel(PanelType.CRUISE) + self._scroller.show_event() + self.icbm_toggle.show_description(True) + self.custom_acc_toggle.show_description(True) + + def _set_current_panel(self, panel: PanelType): + self._current_panel = panel + if panel == PanelType.SLA: + self._speed_limit_layout.show_event() + + def _update_state(self): + super()._update_state() + + if ui_state.CP is not None and ui_state.CP_SP is not None: + has_icbm = ui_state.has_icbm + has_long = ui_state.has_longitudinal_control + + if ui_state.CP_SP.intelligentCruiseButtonManagementAvailable and not has_long: + self.icbm_toggle.action_item.set_enabled(ui_state.is_offroad()) + self.icbm_toggle.set_description(tr(ICBM_DESC)) + else: + ui_state.params.remove("IntelligentCruiseButtonManagement") + self.icbm_toggle.action_item.set_enabled(False) + + long_desc = ICMB_UNAVAILABLE + if has_long: + if ui_state.CP.alphaLongitudinalAvailable: + long_desc += " " + ICMB_UNAVAILABLE_LONG_AVAILABLE + else: + long_desc += " " + ICMB_UNAVAILABLE_LONG_UNAVAILABLE + + new_desc = "" + tr(long_desc) + "\n\n" + tr(ICBM_DESC) + if self.icbm_toggle.description != new_desc: + self.icbm_toggle.set_description(new_desc) + self.icbm_toggle.show_description(True) + + if has_long or has_icbm: + self.custom_acc_toggle.action_item.set_enabled(((has_long and not ui_state.CP.pcmCruise) or has_icbm) and ui_state.is_offroad()) + self.dec_toggle.action_item.set_enabled(has_long) + self.scc_v_toggle.action_item.set_enabled(True) + self.scc_m_toggle.action_item.set_enabled(True) + else: + ui_state.params.remove("CustomAccIncrementsEnabled") + ui_state.params.remove("DynamicExperimentalControl") + ui_state.params.remove("SmartCruiseControlVision") + ui_state.params.remove("SmartCruiseControlMap") + self.custom_acc_toggle.action_item.set_enabled(False) + self.dec_toggle.action_item.set_enabled(False) + self.scc_v_toggle.action_item.set_enabled(False) + self.scc_m_toggle.action_item.set_enabled(False) + + else: + has_icbm = has_long = False + self.icbm_toggle.action_item.set_enabled(False) + self.icbm_toggle.set_description(tr(ONROAD_ONLY_DESCRIPTION)) + + show_custom_acc_desc = False + + if ui_state.is_offroad(): + new_custom_acc_desc = tr(ONROAD_ONLY_DESCRIPTION) + show_custom_acc_desc = True + else: + if has_long or has_icbm: + if has_long and ui_state.CP.pcmCruise: + new_custom_acc_desc = tr(ACC_PCMCRUISE_DISABLED_DESCRIPTION) + show_custom_acc_desc = True + else: + new_custom_acc_desc = tr(ACC_ENABLED_DESCRIPTION) + else: + new_custom_acc_desc = tr(ACC_NOLONG_DESCRIPTION) + show_custom_acc_desc = True + self.custom_acc_toggle.action_item.set_state(False) + + if self.custom_acc_toggle.description != new_custom_acc_desc: + self.custom_acc_toggle.set_description(new_custom_acc_desc) + if show_custom_acc_desc: + self.custom_acc_toggle.show_description(True) + + self._on_custom_acc_toggle(self.custom_acc_toggle.action_item.get_state()) + + def _on_custom_acc_toggle(self, state): + self.custom_acc_short_increment.set_visible(state) + self.custom_acc_long_increment.set_visible(state) + self.custom_acc_short_increment.action_item.set_enabled(self.custom_acc_toggle.action_item.enabled) + self.custom_acc_long_increment.action_item.set_enabled(self.custom_acc_toggle.action_item.enabled) diff --git a/openpilot/selfdrive/ui/sunnypilot/layouts/settings/cruise_sub_layouts/speed_limit_policy.py b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/cruise_sub_layouts/speed_limit_policy.py new file mode 100644 index 0000000000..e6846744a2 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/cruise_sub_layouts/speed_limit_policy.py @@ -0,0 +1,65 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from collections.abc import Callable + +import pyray as rl +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.sunnypilot.widgets.list_view import multiple_button_item_sp +from openpilot.system.ui.widgets.network import NavButton +from openpilot.system.ui.widgets.scroller_tici import Scroller +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.sunnypilot.widgets import get_highlighted_description + +SPEED_LIMIT_POLICY_BUTTONS = [tr("Car Only"), tr("Map Only"), tr("Car First"), tr("Map First"), tr("Combined")] + +SPEED_LIMIT_POLICY_DESCRIPTIONS = [ + tr("Car Only: Use Speed Limit data only from Car"), + tr("Map Only: Use Speed Limit data only from OpenStreetMaps"), + tr("Car First: Use Speed Limit data from Car if available, else use from OpenStreetMaps"), + tr("Map First: Use Speed Limit data from OpenStreetMaps if available, else use from Car"), + tr("Combined: Use combined Speed Limit data from Car & OpenStreetMaps") +] + + +class SpeedLimitPolicyLayout(Widget): + def __init__(self, back_btn_callback: Callable): + super().__init__() + self._back_button = NavButton(tr("Back")) + self._back_button.set_click_callback(back_btn_callback) + + items = self._initialize_items() + self._scroller = Scroller(items, line_separator=False, spacing=0) + + def _initialize_items(self): + self._speed_limit_policy = multiple_button_item_sp( + title=lambda: tr("Speed Limit Source"), + description=self._get_policy_description, + buttons=SPEED_LIMIT_POLICY_BUTTONS, + param="SpeedLimitPolicy", + button_width=250, + ) + + items = [ + self._speed_limit_policy + ] + return items + + @staticmethod + def _get_policy_description(): + return get_highlighted_description(ui_state.params, "SpeedLimitPolicy", SPEED_LIMIT_POLICY_DESCRIPTIONS) + + def _render(self, rect): + self._back_button.set_position(self._rect.x, self._rect.y + 20) + self._back_button.render() + + content_rect = rl.Rectangle(rect.x, rect.y + self._back_button.rect.height + 40, rect.width, rect.height - self._back_button.rect.height - 40) + self._scroller.render(content_rect) + + def show_event(self): + self._scroller.show_event() + self._speed_limit_policy.show_description(True) diff --git a/openpilot/selfdrive/ui/sunnypilot/layouts/settings/cruise_sub_layouts/speed_limit_settings.py b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/cruise_sub_layouts/speed_limit_settings.py new file mode 100644 index 0000000000..c14330d9ac --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/cruise_sub_layouts/speed_limit_settings.py @@ -0,0 +1,178 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from collections.abc import Callable +from enum import IntEnum + +import pyray as rl +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.cruise_sub_layouts.speed_limit_policy import SpeedLimitPolicyLayout +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.sunnypilot.selfdrive.controls.lib.speed_limit.common import Mode as SpeedLimitMode +from openpilot.sunnypilot.selfdrive.controls.lib.speed_limit.common import OffsetType as SpeedLimitOffsetType +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.sunnypilot.widgets import get_highlighted_description +from openpilot.system.ui.sunnypilot.widgets.list_view import multiple_button_item_sp, option_item_sp, simple_button_item_sp, LineSeparatorSP +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.network import NavButton +from openpilot.system.ui.widgets.scroller_tici import Scroller + +SPEED_LIMIT_MODE_BUTTONS = [tr("Off"), tr("Info"), tr("Warning"), tr("Assist")] +SPEED_LIMIT_OFFSET_TYPE_BUTTONS = [tr("None"), tr("Fixed"), tr("%")] + +SPEED_LIMIT_MODE_DESCRIPTIONS = [ + tr("Off: Disables the Speed Limit functions."), + tr("Information: Displays the current road's speed limit."), + tr("Warning: Provides a warning when exceeding the current road's speed limit."), + tr("Assist: Adjusts the vehicle's cruise speed based on the current road's speed limit when operating the +/- buttons."), +] + +SPEED_LIMIT_OFFSET_DESCRIPTIONS = [ + tr("None: No Offset"), + tr("Fixed: Adds a fixed offset [Speed Limit + Offset]"), + tr("Percent: Adds a percent offset [Speed Limit + (Offset % Speed Limit)]"), +] + + +class PanelType(IntEnum): + SETTINGS = 0 + POLICY = 1 + + +class SpeedLimitSettingsLayout(Widget): + def __init__(self, back_btn_callback: Callable): + super().__init__() + self._current_panel = PanelType.SETTINGS + + self._back_button = NavButton(tr("Back")) + self._back_button.set_click_callback(back_btn_callback) + + self._policy_layout = SpeedLimitPolicyLayout(lambda: self._set_current_panel(PanelType.SETTINGS)) + + items = self._initialize_items() + self._scroller = Scroller(items, line_separator=False, spacing=0) + + def _initialize_items(self): + self._speed_limit_mode = multiple_button_item_sp( + title=lambda: tr("Speed Limit"), + description=self._get_mode_description, + buttons=SPEED_LIMIT_MODE_BUTTONS, + param="SpeedLimitMode", + button_width=380, + ) + + self._source_button = simple_button_item_sp( + button_text=lambda: tr("Customize Source"), + button_width=720, + callback=lambda: self._set_current_panel(PanelType.POLICY) + ) + + self._speed_limit_offset_type = multiple_button_item_sp( + title=lambda: tr("Speed Limit Offset"), + description="", + buttons=SPEED_LIMIT_OFFSET_TYPE_BUTTONS, + param="SpeedLimitOffsetType", + button_width=450, + ) + + self._speed_limit_value_offset = option_item_sp( + title="", + param="SpeedLimitValueOffset", + min_value=-30, + max_value=30, + description=self._get_offset_description, + label_callback=self._get_offset_label, + ) + + items = [ + self._speed_limit_mode, + LineSeparatorSP(40), + self._source_button, + LineSeparatorSP(40), + self._speed_limit_offset_type, + self._speed_limit_value_offset + ] + return items + + def _set_current_panel(self, panel: PanelType): + self._current_panel = panel + if panel == PanelType.POLICY: + self._policy_layout.show_event() + + @staticmethod + def _get_mode_description(): + return get_highlighted_description(ui_state.params, "SpeedLimitMode", SPEED_LIMIT_MODE_DESCRIPTIONS) + + @staticmethod + def _get_offset_description(): + return get_highlighted_description(ui_state.params, "SpeedLimitOffsetType", SPEED_LIMIT_OFFSET_DESCRIPTIONS) + + @staticmethod + def _get_offset_label(value): + offset_type = int(ui_state.params.get("SpeedLimitOffsetType", return_default=True)) + unit = tr("km/h") if ui_state.is_metric else tr("mph") + + if offset_type == int(SpeedLimitOffsetType.percentage): + return f"{value}%" + elif offset_type == int(SpeedLimitOffsetType.fixed): + return f"{value} {unit}" + return str(value) + + def _update_state(self): + super()._update_state() + + speed_limit_mode_param = ui_state.params.get("SpeedLimitMode", return_default=True) + if ui_state.CP is not None and ui_state.CP_SP is not None: + brand = ui_state.CP.brand + has_long = ui_state.has_longitudinal_control + has_icbm = ui_state.has_icbm + + """ + Speed Limit Assist is available when: + - has_long or has_icbm, and + - is not a release branch or not a disallowed brand, and + - is not always disallwed + """ + sla_disallow_in_release = brand == "tesla" and ui_state.is_sp_release + sla_always_disallow = brand == "rivian" + sla_available = (has_long or has_icbm) and not sla_disallow_in_release and not sla_always_disallow + + if not sla_available and speed_limit_mode_param == int(SpeedLimitMode.assist): + ui_state.params.put("SpeedLimitMode", int(SpeedLimitMode.warning)) + + else: + sla_available = False + + if not sla_available: + self._speed_limit_mode.action_item.set_enabled_buttons({ + int(SpeedLimitMode.off), + int(SpeedLimitMode.information), + int(SpeedLimitMode.warning), + }) + else: + self._speed_limit_mode.action_item.set_enabled_buttons(None) + + offset_type = ui_state.params.get("SpeedLimitOffsetType", return_default=True) + self._speed_limit_value_offset.set_visible(offset_type != int(SpeedLimitOffsetType.off)) + + def _render(self, rect): + if self._current_panel == PanelType.POLICY: + self._policy_layout.render(rect) + return + + self._back_button.set_position(self._rect.x, self._rect.y + 20) + self._back_button.render() + + content_rect = rl.Rectangle(rect.x, rect.y + self._back_button.rect.height + 40, rect.width, rect.height - self._back_button.rect.height - 40) + self._scroller.render(content_rect) + + def show_event(self): + self._current_panel = PanelType.SETTINGS + self._scroller.show_event() + self._speed_limit_mode.show_description(True) + + def hide_event(self): + self._current_panel = PanelType.SETTINGS + self._scroller.hide_event() diff --git a/openpilot/selfdrive/ui/sunnypilot/layouts/settings/developer.py b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/developer.py new file mode 100644 index 0000000000..a8768af5be --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/developer.py @@ -0,0 +1,106 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import datetime +import os +from pathlib import Path + +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.selfdrive.ui.layouts.settings.developer import DeveloperLayout +from openpilot.common.hardware import PC +from openpilot.common.hardware.hw import Paths +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.widgets import DialogResult +from openpilot.system.ui.widgets.confirm_dialog import ConfirmDialog +from openpilot.system.ui.widgets.list_view import button_item + +from openpilot.system.ui.sunnypilot.widgets.html_render import HtmlModalSP +from openpilot.system.ui.sunnypilot.widgets.list_view import toggle_item_sp + +PREBUILT_PATH = os.path.join(Paths.comma_home(), "prebuilt") if PC else "/data/openpilot/prebuilt" + + +class DeveloperLayoutSP(DeveloperLayout): + def __init__(self): + super().__init__() + self.error_log_path = os.path.join(Paths.crash_log_root(), "error.log") + self._is_release_branch: bool = self._is_release or ui_state.params.get_bool("IsReleaseSpBranch") + self._is_development_branch: bool = ui_state.params.get_bool("IsTestedBranch") or ui_state.params.get_bool("IsDevelopmentBranch") + self._initialize_items() + + for item in self.items: + self._scroller.add_widget(item) + + def _initialize_items(self): + self.show_advanced_controls = toggle_item_sp(tr("Show Advanced Controls"), + tr("Toggle visibility of advanced sunnypilot controls.
This only changes the visibility of the toggles; " + + "it does not change the actual enabled/disabled state."), param="ShowAdvancedControls") + + self.enable_github_runner_toggle = toggle_item_sp(tr("GitHub Runner Service"), tr("Enables or disables the GitHub runner service."), + param="EnableGithubRunner") + + self.enable_copyparty_toggle = toggle_item_sp(tr("copyparty Service"), + tr("copyparty is a very capable file server, you can use it to download your routes, view your logs " + + "and even make some edits on some files from your browser. " + + "Requires you to connect to your comma locally via its IP address."), param="EnableCopyparty") + + self.prebuilt_toggle = toggle_item_sp(tr("Quickboot Mode"), "", param="QuickBootToggle", callback=self._on_prebuilt_toggled) + + self.error_log_btn = button_item(tr("Error Log"), tr("VIEW"), tr("View the error log for sunnypilot crashes."), callback=self._on_error_log_clicked) + + self.items: list = [self.show_advanced_controls, self.enable_github_runner_toggle, self.enable_copyparty_toggle, self.prebuilt_toggle, self.error_log_btn,] + + @staticmethod + def _on_prebuilt_toggled(state): + if state: + Path(PREBUILT_PATH).touch(exist_ok=True) + else: + os.remove(PREBUILT_PATH) + ui_state.params.put_bool("QuickBootToggle", state) + + def _on_delete_confirm(self, result): + if result == DialogResult.CONFIRM: + if os.path.exists(self.error_log_path): + os.remove(self.error_log_path) + + def _on_error_log_closed(self, result, log_exists): + if result == DialogResult.CONFIRM and log_exists: + dialog2 = ConfirmDialog(tr("Would you like to delete this log?"), tr("Yes"), tr("No"), rich=False, callback=self._on_delete_confirm) + gui_app.push_widget(dialog2) + + def _on_error_log_clicked(self): + text = "" + if os.path.exists(self.error_log_path): + text = f"{datetime.datetime.fromtimestamp(os.path.getmtime(self.error_log_path)).strftime('%d-%b-%Y %H:%M:%S').upper()}

" + try: + with open(self.error_log_path) as file: + text += file.read() + except Exception: + pass + dialog = HtmlModalSP(text=text, callback=lambda result: self._on_error_log_closed(result, os.path.exists(self.error_log_path))) + gui_app.push_widget(dialog) + + def _update_state(self): + disable_updates = ui_state.params.get_bool("DisableUpdates") + show_advanced = ui_state.params.get_bool("ShowAdvancedControls") + + if (prebuilt_file := os.path.exists(PREBUILT_PATH)) != ui_state.params.get_bool("QuickBootToggle"): + ui_state.params.put_bool("QuickBootToggle", prebuilt_file) + self.prebuilt_toggle.action_item.set_state(prebuilt_file) + + self.prebuilt_toggle.set_visible(show_advanced and not (self._is_release_branch or self._is_development_branch)) + self.prebuilt_toggle.action_item.set_enabled(disable_updates) + + if disable_updates: + self.prebuilt_toggle.set_description(tr("When toggled on, this creates a prebuilt file to allow accelerated boot times. When toggled off, it " + + "removes the prebuilt file so compilation of locally edited cpp files can be made.")) + else: + self.prebuilt_toggle.set_description(tr("Quickboot mode requires updates to be disabled.
Enable 'Disable Updates' in the Software panel first.")) + + self.enable_copyparty_toggle.set_visible(show_advanced) + self.enable_github_runner_toggle.set_visible(show_advanced and not self._is_release_branch) + self.error_log_btn.set_visible(not self._is_release_branch) diff --git a/openpilot/selfdrive/ui/sunnypilot/layouts/settings/device.py b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/device.py new file mode 100644 index 0000000000..e5c956cd81 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/device.py @@ -0,0 +1,221 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from openpilot.selfdrive.ui.layouts.settings.device import DeviceLayout +from openpilot.selfdrive.ui.onroad.driver_camera_dialog import DriverCameraDialog +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.common.hardware import HARDWARE +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.sunnypilot.widgets.list_view import option_item_sp, multiple_button_item_sp, button_item_sp, \ + dual_button_item_sp, Spacer +from openpilot.system.ui.widgets import DialogResult +from openpilot.system.ui.widgets.button import ButtonStyle +from openpilot.system.ui.widgets.confirm_dialog import alert_dialog, ConfirmDialog +from openpilot.system.ui.widgets.list_view import text_item +from openpilot.system.ui.widgets.scroller_tici import LineSeparator + +offroad_time_options = { + 0: 0, + 1: 5, + 2: 10, + 3: 15, + 4: 30, + 5: 60, + 6: 120, + 7: 180, + 8: 300, + 9: 600, + 10: 1440, + 11: 1800, +} + + +class DeviceLayoutSP(DeviceLayout): + def __init__(self): + DeviceLayout.__init__(self) + self._scroller._line_separator = None + + def _initialize_items(self): + DeviceLayout._initialize_items(self) + + # Using dual button with no right button for better alignment + self._always_offroad_btn = dual_button_item_sp( + left_text=lambda: tr("Enable Always Offroad"), + left_callback=self._handle_always_offroad, + right_text="", + right_callback=None, + ) + self._always_offroad_btn.action_item.right_button.set_visible(False) + + self._max_time_offroad = option_item_sp( + title=lambda: tr("Max Time Offroad"), + description=lambda: tr("Device will automatically shutdown after set time once the engine is turned off.\n(30h is the default)"), + param="MaxTimeOffroad", + min_value=0, + max_value=11, + value_change_step=1, + on_value_changed=None, + enabled=True, + icon="", + value_map=offroad_time_options, + label_width=360, + use_float_scaling=False, + inline=True, + label_callback=self._update_max_time_offroad_label + ) + + self._device_wake_mode = multiple_button_item_sp( + title=lambda: tr("Wake Up Behavior"), + description=self.wake_mode_description, + param="DeviceBootMode", + buttons=[lambda: tr("Default"), lambda: tr("Offroad")], + button_width=364, + callback=None, + inline=True, + ) + + self._quiet_mode_and_dcam = dual_button_item_sp( + left_text=lambda: tr("Quiet Mode"), + right_text=lambda: tr("Driver Camera Preview"), + left_callback=lambda: ui_state.params.put_bool("QuietMode", not ui_state.params.get_bool("QuietMode")), + right_callback=lambda: gui_app.push_widget(DriverCameraDialog()) + ) + self._quiet_mode_and_dcam.action_item.right_button.set_button_style(ButtonStyle.NORMAL) + + self._reg_and_training = dual_button_item_sp( + left_text=lambda: tr("Regulatory"), + left_callback=self._on_regulatory, + right_text=lambda: tr("Training Guide"), + right_callback=self._on_review_training_guide + ) + self._reg_and_training.action_item.right_button.set_button_style(ButtonStyle.NORMAL) + + self._onroad_uploads_and_reset_settings = dual_button_item_sp( + left_text=lambda: tr("Onroad Uploads"), + left_callback=lambda: ui_state.params.put_bool("OnroadUploads", not ui_state.params.get_bool("OnroadUploads")), + right_text=lambda: tr("Reset Settings"), + right_callback=self._reset_settings + ) + + self._power_buttons = dual_button_item_sp( + left_text=lambda: tr("Reboot"), + right_text=lambda: tr("Power Off"), + left_callback=self._reboot_prompt, + right_callback=self._power_off_prompt + ) + + items = [ + text_item(lambda: tr("Dongle ID"), self._params.get("DongleId") or (lambda: tr("N/A"))), + LineSeparator(), + text_item(lambda: tr("Serial"), self._params.get("HardwareSerial") or (lambda: tr("N/A"))), + LineSeparator(), + self._pair_device_btn, + LineSeparator(), + self._reset_calib_btn, + LineSeparator(), + button_item_sp(lambda: tr("Change Language"), lambda: tr("CHANGE"), callback=self._show_language_dialog), + LineSeparator(), + self._device_wake_mode, + LineSeparator(), + self._max_time_offroad, + LineSeparator(height=10), + self._quiet_mode_and_dcam, + self._reg_and_training, + self._onroad_uploads_and_reset_settings, + Spacer(10), + LineSeparator(height=10), + self._power_buttons, + ] + + return items + + def _offroad_transition(self): + self._power_buttons.action_item.right_button.set_visible(ui_state.is_offroad()) + + @staticmethod + def wake_mode_description() -> str: + def_str = tr("Default: Device will boot/wake-up normally & will be ready to engage.") + offrd_str = tr("Offroad: Device will be in Always Offroad mode after boot/wake-up.") + header = tr("Controls state of the device after boot/sleep.") + + return f"{header}\n\n{def_str}\n{offrd_str}" + + @staticmethod + def _reset_settings(): + def _do_reset(result: int): + if result == DialogResult.CONFIRM: + for _key in ui_state.params.all_keys(): + ui_state.params.remove(_key) + HARDWARE.reboot() + + def _second_confirm(result: int): + if result == DialogResult.CONFIRM: + gui_app.push_widget(ConfirmDialog( + text=tr("The reset cannot be undone. You have been warned."), + confirm_text=tr("Confirm"), callback=_do_reset + )) + + gui_app.push_widget(ConfirmDialog( + text=tr("Are you sure you want to reset all sunnypilot settings to default? Once the settings are reset, there is no going back."), + confirm_text=tr("Reset"), callback=_second_confirm + )) + + @staticmethod + def _handle_always_offroad(): + if ui_state.engaged: + gui_app.push_widget(alert_dialog(tr("Disengage to Enter Always Offroad Mode"))) + return + + _offroad_mode_state = ui_state.params.get_bool("OffroadMode") + _offroad_mode_str = tr("Are you sure you want to exit Always Offroad mode?") if _offroad_mode_state else \ + tr("Are you sure you want to enter Always Offroad mode?") + + def _set_always_offroad(result: int): + if result == DialogResult.CONFIRM and not ui_state.engaged: + ui_state.params.put_bool("OffroadMode", not _offroad_mode_state) + + gui_app.push_widget(ConfirmDialog(_offroad_mode_str, tr("Confirm"), callback=lambda result: _set_always_offroad(result))) + + @staticmethod + def _update_max_time_offroad_label(value: int) -> str: + label = tr("Always On") if value == 0 else f"{value}" + tr("m") if value < 60 else f"{value // 60}" + tr("h") + label += tr(" (Default)") if value == 1800 else "" + return label + + def _update_state(self): + super()._update_state() + + # Handle Always Offroad button + always_offroad = ui_state.params.get_bool("OffroadMode") + + # Text & Color + offroad_mode_btn_text = tr("Exit Always Offroad") if always_offroad else tr("Enable Always Offroad") + offroad_mode_btn_style = ButtonStyle.PRIMARY if always_offroad else ButtonStyle.DANGER + self._always_offroad_btn.action_item.left_button.set_text(offroad_mode_btn_text) + self._always_offroad_btn.action_item.left_button.set_button_style(offroad_mode_btn_style) + + # Position + if self._scroller._items.__contains__(self._always_offroad_btn): + self._scroller._items.remove(self._always_offroad_btn) + if ui_state.is_offroad() and not always_offroad: + self._scroller._items.insert(len(self._scroller._items) - 1, self._always_offroad_btn) + else: + self._scroller._items.insert(0, self._always_offroad_btn) + + # Quiet Mode button + self._quiet_mode_and_dcam.action_item.left_button.set_button_style(ButtonStyle.PRIMARY if ui_state.params.get_bool("QuietMode") else ButtonStyle.NORMAL) + + # Onroad Uploads + self._onroad_uploads_and_reset_settings.action_item.left_button.set_button_style( + ButtonStyle.PRIMARY if ui_state.params.get_bool("OnroadUploads") else ButtonStyle.NORMAL + ) + + # Offroad only buttons + self._quiet_mode_and_dcam.action_item.right_button.set_enabled(ui_state.is_offroad()) + self._reg_and_training.action_item.left_button.set_enabled(ui_state.is_offroad()) + self._reg_and_training.action_item.right_button.set_enabled(ui_state.is_offroad()) + self._onroad_uploads_and_reset_settings.action_item.right_button.set_enabled(ui_state.is_offroad()) diff --git a/openpilot/selfdrive/ui/sunnypilot/layouts/settings/display.py b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/display.py new file mode 100644 index 0000000000..8ba5663662 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/display.py @@ -0,0 +1,94 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from enum import IntEnum + +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.widgets.scroller_tici import Scroller +from openpilot.system.ui.sunnypilot.widgets.list_view import option_item_sp +from openpilot.sunnypilot.system.params_migration import ONROAD_BRIGHTNESS_TIMER_VALUES + + +class OnroadBrightness(IntEnum): + AUTO = 0 + AUTO_DARK = 1 + SCREEN_OFF = 2 + + +class DisplayLayout(Widget): + def __init__(self): + super().__init__() + + items = self._initialize_items() + self._scroller = Scroller(items, line_separator=True, spacing=0) + + def _initialize_items(self): + self._onroad_brightness = option_item_sp( + param="OnroadScreenOffBrightness", + title=lambda: tr("Onroad Brightness"), + description="", + min_value=0, + max_value=22, + value_change_step=1, + label_callback=lambda value: self.update_onroad_brightness(value), + inline=True + ) + self._onroad_brightness_timer = option_item_sp( + param="OnroadScreenOffTimer", + title=lambda: tr("Onroad Brightness Delay"), + description="", + min_value=0, + max_value=15, + value_change_step=1, + value_map=ONROAD_BRIGHTNESS_TIMER_VALUES, + label_callback=lambda value: f"{value} s" if value < 60 else f"{int(value/60)} m", + inline=True + ) + self._interactivity_timeout = option_item_sp( + param="InteractivityTimeout", + title=lambda: tr("Interactivity Timeout"), + description=lambda: tr("Apply a custom timeout for settings UI." + + "
This is the time after which settings UI closes automatically " + + "if user is not interacting with the screen."), + min_value=0, + max_value=120, + value_change_step=10, + label_callback=lambda value: (tr("Default") if not value or value == 0 else + f"{value} s" if value < 60 else f"{int(value/60)} m"), + inline=True + ) + items = [ + self._onroad_brightness, + self._onroad_brightness_timer, + self._interactivity_timeout, + ] + return items + + @staticmethod + def update_onroad_brightness(val): + if val == OnroadBrightness.AUTO: + return tr("Auto (Default)") + + if val == OnroadBrightness.AUTO_DARK: + return tr("Auto (Dark)") + + if val == OnroadBrightness.SCREEN_OFF: + return tr("Screen Off") + + return f"{(val - 2) * 5} %" + + def _update_state(self): + super()._update_state() + + brightness_val = self._onroad_brightness.action_item.current_value + self._onroad_brightness_timer.action_item.set_enabled(brightness_val not in (OnroadBrightness.AUTO, OnroadBrightness.AUTO_DARK)) + + def _render(self, rect): + self._scroller.render(rect) + + def show_event(self): + self._scroller.show_event() diff --git a/openpilot/selfdrive/ui/sunnypilot/layouts/settings/models.py b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/models.py new file mode 100644 index 0000000000..e2ea81d1f5 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/models.py @@ -0,0 +1,261 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import os +import re +import time +import pyray as rl + +from openpilot.cereal import custom +from openpilot.sunnypilot.models.default_model import DEFAULT_MODEL +from openpilot.common.constants import CV +from openpilot.selfdrive.ui.ui_state import device, ui_state +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.widgets import DialogResult, Widget +from openpilot.system.ui.widgets.confirm_dialog import alert_dialog, ConfirmDialog +from openpilot.system.ui.widgets.scroller_tici import Scroller +from openpilot.system.ui.widgets.toggle import ON_COLOR + +from openpilot.sunnypilot.models.runners.constants import CUSTOM_MODEL_PATH +from openpilot.system.ui.sunnypilot.lib.styles import style +from openpilot.system.ui.sunnypilot.lib.utils import NoElideButtonAction +from openpilot.system.ui.sunnypilot.widgets.list_view import ListItemSP, toggle_item_sp, option_item_sp +from openpilot.system.ui.sunnypilot.widgets.progress_bar import progress_item +from openpilot.system.ui.sunnypilot.widgets.tree_dialog import TreeOptionDialog, TreeNode, TreeFolder + +if gui_app.sunnypilot_ui(): + from openpilot.system.ui.sunnypilot.widgets.list_view import button_item_sp as button_item + + +class ModelsLayout(Widget): + def __init__(self): + super().__init__() + self.model_manager = None + self.download_status = None + self.prev_download_status = None + self.model_dialog = None + self.last_cache_calc_time = 0 + + self._initialize_items() + + self.clear_cache_item.action_item.set_value(f"{self.calculate_cache_size():.2f} MB") + for ctrl, key in [(self.lane_turn_value_control, "LaneTurnValue"), (self.delay_control, "LagdToggleDelay")]: + ctrl.action_item.set_value(int(float(ui_state.params.get(key, return_default=True)) * 100)) + + self._scroller = Scroller(self.items, line_separator=True, spacing=0) + + def _initialize_items(self): + self.current_model_item = ListItemSP( + title=tr("Current Model"), + description="", + action_item=NoElideButtonAction(tr("SELECT")), + callback=self._handle_current_model_clicked + ) + + self.supercombo_label = progress_item(tr("Driving Model")) + self.vision_label = progress_item(tr("Vision Model")) + self.policy_label = progress_item(tr("Policy Model")) + self.off_policy_label = progress_item(tr("Off-Policy Model")) + self.on_policy_label = progress_item(tr("On-Policy Model")) + + self.refresh_item = button_item(tr("Refresh Model List"), tr("REFRESH"), "", + lambda: (ui_state.params.put("ModelManager_LastSyncTime", 0), + gui_app.push_widget(alert_dialog(tr("Fetching Latest Models"))))) + + self.clear_cache_item = ListItemSP( + title=tr("Clear Model Cache"), + description="", + action_item=NoElideButtonAction(tr("CLEAR")), + callback=self._clear_cache + ) + + self.cancel_download_item = button_item(tr("Cancel Download"), tr("Cancel"), "", lambda: ui_state.params.remove("ModelManager_DownloadIndex")) + + self.lane_turn_value_control = option_item_sp(tr("Adjust Lane Turn Speed"), "LaneTurnValue", 500, 2000, + tr("Set the maximum speed for lane turn desires. Default is 19 mph."), + int(round(100 / CV.MPH_TO_KPH)), None, True, "", style.BUTTON_ACTION_WIDTH, None, True, + lambda v: f"{int(round(v / 100 * (CV.MPH_TO_KPH if ui_state.is_metric else 1)))}" + + f" {'km/h' if ui_state.is_metric else 'mph'}") + + self.lane_turn_desire_toggle = toggle_item_sp(tr("Use Lane Turn Desires"), + tr("If you're driving at 20 mph (32 km/h) or below and have your blinker on," + + " the car will plan a turn in that direction at the nearest drivable path. " + + "This prevents situations (like at red lights) where the car might plan the wrong turn direction."), + param="LaneTurnDesire") + + self.delay_control = option_item_sp(tr("Adjust Software Delay"), "LagdToggleDelay", 5, 50, + tr("Adjust the software delay when Live Learning Steer Delay is toggled off. The default software delay value is 0.2"), + 1, None, True, "", style.BUTTON_ACTION_WIDTH, None, True, lambda v: f"{v / 100:.2f}s") + + self.lagd_toggle = toggle_item_sp(tr("Live Learning Steer Delay"), "", param="LagdToggle") + + self.items = [self.current_model_item, self.cancel_download_item, self.supercombo_label, self.vision_label, + self.policy_label, self.off_policy_label, self.on_policy_label, self.refresh_item, self.clear_cache_item, self.lane_turn_desire_toggle, + self.lane_turn_value_control, self.lagd_toggle, self.delay_control] + + def _update_lagd_description(self, lagd_toggle: bool): + desc = tr("Enable this for the car to learn and adapt its steering response time. Disable to use a fixed steering response time. " + + "Keeping this on provides the stock openpilot experience.") + if lagd_toggle: + desc += f"
{tr('Live Steer Delay:')} {ui_state.sm['liveDelay'].lateralDelay:.3f} s" + elif ui_state.CP is not None: + sw = float(ui_state.params.get("LagdToggleDelay", "0.2")) + cp = ui_state.CP.steerActuatorDelay + desc += f"
{tr('Actuator Delay:')} {cp:.2f} s + {tr('Software Delay:')} {sw:.2f} s = {tr('Total Delay:')} {cp + sw:.2f} s" + self.lagd_toggle.set_description(desc) + + def _is_downloading(self): + return (self.model_manager and self.model_manager.selectedBundle and + self.model_manager.selectedBundle.status == custom.ModelManagerSP.DownloadStatus.downloading) + + @staticmethod + def calculate_cache_size(): + cache_size = 0.0 + if os.path.exists(CUSTOM_MODEL_PATH): + cache_size = sum(os.path.getsize(os.path.join(CUSTOM_MODEL_PATH, file)) for file in os.listdir(CUSTOM_MODEL_PATH)) / (1024**2) + return cache_size + + def _clear_cache(self): + def _callback(response): + if response == DialogResult.CONFIRM: + ui_state.params.put_bool("ModelManager_ClearCache", True) + self.clear_cache_item.action_item.set_value(f"{self.calculate_cache_size():.2f} MB") + + dialog = ConfirmDialog(tr("This will delete ALL downloaded models from the cache except the currently active model. Are you sure?"), + tr("Clear Cache"), callback=_callback) + gui_app.push_widget(dialog) + + def _handle_bundle_download_progress(self): + labels = {custom.ModelManagerSP.Model.Type.supercombo: self.supercombo_label, + custom.ModelManagerSP.Model.Type.vision: self.vision_label, + custom.ModelManagerSP.Model.Type.policy: self.policy_label, + custom.ModelManagerSP.Model.Type.offPolicy: self.off_policy_label, + custom.ModelManagerSP.Model.Type.onPolicy: self.on_policy_label} + for label in labels.values(): + label.set_visible(False) + self.cancel_download_item.set_visible(False) + + if not self.model_manager or (not self.model_manager.selectedBundle and not self.model_manager.activeBundle): + return + + bundle = self.model_manager.selectedBundle if self._is_downloading() or ( + self.model_manager.selectedBundle and self.model_manager.selectedBundle.status == custom.ModelManagerSP.DownloadStatus.failed + ) else self.model_manager.activeBundle + if not bundle: + return + + self.download_status = bundle.status + status_changed = self.prev_download_status != self.download_status + self.prev_download_status = self.download_status + + self.cancel_download_item.set_visible(bool(self.model_manager.selectedBundle) and ui_state.params.get("ModelManager_DownloadIndex") is not None) + + if (current_time := time.monotonic()) - self.last_cache_calc_time > 0.5: + self.last_cache_calc_time = current_time + self.clear_cache_item.action_item.set_value(f"{self.calculate_cache_size():.2f} MB") + + if self.download_status == custom.ModelManagerSP.DownloadStatus.downloading: + device._reset_interactive_timeout() + + for model in bundle.models: + if label := labels.get(getattr(model.type, 'raw', model.type)): + label.set_visible(True) + p = model.artifact.downloadProgress + text, show, color = f"pending - {bundle.displayName}", False, rl.GRAY + if p.status == custom.ModelManagerSP.DownloadStatus.downloading: + text, show = f"{int(p.progress)}% - {bundle.displayName}", True + elif p.status in (custom.ModelManagerSP.DownloadStatus.downloaded, custom.ModelManagerSP.DownloadStatus.cached): + status_text = tr("from cache" if p.status == custom.ModelManagerSP.DownloadStatus.cached else "downloaded") + text, color = f"{bundle.displayName} - {status_text if status_changed else tr('ready')}", ON_COLOR + elif p.status == custom.ModelManagerSP.DownloadStatus.failed: + text, color = f"download failed - {bundle.displayName}", rl.RED + label.action_item.update(p.progress, text, show, color) + + @staticmethod + def _show_reset_params_dialog(): + def _callback(response): + if response == DialogResult.CONFIRM: + ui_state.params.remove("CalibrationParams") + ui_state.params.remove("LiveTorqueParameters") + msg = tr("Model download has started in the background. We suggest resetting calibration. Would you like to do that now?") + dialog = ConfirmDialog(msg, tr("Reset Calibration"), callback=_callback) + gui_app.push_widget(dialog) + + def _on_model_selected(self, result): + if result != DialogResult.CONFIRM: + return + selected_ref = self.model_dialog.selection_ref + if selected_ref == "Default": + ui_state.params.remove("ModelManager_ActiveBundle") + self._show_reset_params_dialog() + elif selected_bundle := next((bundle for bundle in self.model_manager.availableBundles if bundle.ref == selected_ref), None): + ui_state.params.put("ModelManager_DownloadIndex", selected_bundle.index) + if self.model_manager.activeBundle and selected_bundle.generation != self.model_manager.activeBundle.generation: + self._show_reset_params_dialog() + self.model_dialog = None + + @staticmethod + def _bundle_to_node(bundle): + return TreeNode(bundle.ref, {'display_name': bundle.displayName, 'short_name': bundle.internalName}) + + def _get_folders(self, favorites): + bundles = self.model_manager.availableBundles + folders = {} + for bundle in bundles: + folders.setdefault(next((ov_ride.value for ov_ride in bundle.overrides if ov_ride.key == "folder"), ""), []).append(bundle) + + folders_list = [TreeFolder("", [TreeNode("Default", {'display_name': f"{DEFAULT_MODEL} (Default)", 'short_name': "Default"})])] + for folder, folder_bundles in sorted(folders.items(), key=lambda x: max((bundle.index for bundle in x[1]), default=-1), reverse=True): + folder_bundles.sort(key=lambda bundle: bundle.index, reverse=True) + name = folder + (f" - (Updated: {m.group(1)})" if folder_bundles and (m := re.search(r'\(([^)]*)\)[^(]*$', folder_bundles[0].displayName)) else "") + folders_list.append(TreeFolder(name, [self._bundle_to_node(bundle) for bundle in folder_bundles])) + + if favorites and (fav_bundles := [bundle for bundle in bundles if bundle.ref in favorites]): + folders_list.insert(1, TreeFolder("Favorites", [self._bundle_to_node(bundle) for bundle in fav_bundles])) + return folders_list + + def _handle_current_model_clicked(self): + favs = ui_state.params.get("ModelManager_Favs") + favorites = set(favs.split(';')) if favs else set() + folders_list = self._get_folders(favorites) + + active_ref = self.model_manager.activeBundle.ref if self.model_manager.activeBundle else "Default" + self.model_dialog = TreeOptionDialog(tr("Select a Model"), folders_list, active_ref, "ModelManager_Favs", + get_folders_fn=self._get_folders, on_exit=self._on_model_selected) + gui_app.push_widget(self.model_dialog) + + def _update_state(self): + advanced_controls: bool = ui_state.params.get_bool("ShowAdvancedControls") + turn_desire: bool = ui_state.params.get_bool("LaneTurnDesire") + live_delay: bool = ui_state.params.get_bool("LagdToggle") + + self.lane_turn_desire_toggle.action_item.set_state(turn_desire) + self.lane_turn_value_control.set_visible(turn_desire and advanced_controls) + self.lagd_toggle.action_item.set_state(live_delay) + self.delay_control.set_visible(not live_delay and advanced_controls) + new_step = int(round(100 / CV.MPH_TO_KPH)) if ui_state.is_metric else 100 + if self.lane_turn_value_control.action_item is not None and self.lane_turn_value_control.action_item.value_change_step != new_step: + self.lane_turn_value_control.action_item.value_change_step = new_step + + self._update_lagd_description(live_delay) + self.model_manager = ui_state.sm["modelManagerSP"] + self._handle_bundle_download_progress() + active_name = self.model_manager.activeBundle.internalName if self.model_manager and self.model_manager.activeBundle.ref else f"{DEFAULT_MODEL} (Default)" + self.current_model_item.action_item.set_value(active_name) + + if not ui_state.is_offroad(): + self.current_model_item.action_item.set_enabled(False) + self.current_model_item.set_description(tr("Only available when vehicle is off, or always offroad mode is on")) + else: + self.current_model_item.action_item.set_enabled(True) + self.current_model_item.set_description("") + + def _render(self, rect): + self._scroller.render(rect) + + def show_event(self): + self._scroller.show_event() diff --git a/openpilot/selfdrive/ui/sunnypilot/layouts/settings/navigation.py b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/navigation.py new file mode 100644 index 0000000000..1f44775bb3 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/navigation.py @@ -0,0 +1,30 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from openpilot.common.params import Params +from openpilot.system.ui.widgets.scroller_tici import Scroller +from openpilot.system.ui.widgets import Widget + + +class NavigationLayout(Widget): + def __init__(self): + super().__init__() + + self._params = Params() + items = self._initialize_items() + self._scroller = Scroller(items, line_separator=True, spacing=0) + + def _initialize_items(self): + items = [ + + ] + return items + + def _render(self, rect): + self._scroller.render(rect) + + def show_event(self): + self._scroller.show_event() diff --git a/openpilot/selfdrive/ui/sunnypilot/layouts/settings/network.py b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/network.py new file mode 100644 index 0000000000..2663607fc8 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/network.py @@ -0,0 +1,46 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import threading +import time +import pyray as rl + +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.widgets.button import Button, ButtonStyle +from openpilot.system.ui.widgets.network import NetworkUI, PanelType + + +class NetworkUISP(NetworkUI): + def __init__(self, wifi_manager): + super().__init__(wifi_manager) + + self.scan_button = Button(tr("Scan"), self._scan_clicked, button_style=ButtonStyle.NORMAL, font_size=60, border_radius=30) + self.scan_button.set_rect(rl.Rectangle(0, 0, 400, 100)) + + self._scanning = False + self._wifi_manager.add_callbacks(networks_updated=self._on_networks_updated) + + def _scan_clicked(self): + self._scanning = True + self.scan_button.set_text(tr("Scanning...")) + self.scan_button.set_enabled(False) + + threading.Thread(target=self._wifi_manager._update_networks, daemon=True).start() + self._wifi_manager._request_scan() + self._wifi_manager._last_network_update = time.monotonic() + + def _on_networks_updated(self, networks): + if self._scanning: + self._scanning = False + self.scan_button.set_text(tr("Scan")) + self.scan_button.set_enabled(True) + + def _render(self, _): + super()._render(_) + + if self._current_panel == PanelType.WIFI: + self.scan_button.set_position(self._rect.x, self._rect.y + 20) + self.scan_button.render() diff --git a/openpilot/selfdrive/ui/sunnypilot/layouts/settings/osm.py b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/osm.py new file mode 100644 index 0000000000..7b30e880f9 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/osm.py @@ -0,0 +1,232 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import datetime +import os +import platform +import requests +import shutil +import threading +from pathlib import Path +from time import monotonic + +from openpilot.common.params import Params +from openpilot.selfdrive.ui.ui_state import device, ui_state +from openpilot.selfdrive.ui.layouts.settings.software import time_ago +from openpilot.common.hardware.hw import Paths +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.widgets import DialogResult, Widget +from openpilot.system.ui.widgets.confirm_dialog import ConfirmDialog +from openpilot.system.ui.widgets.list_view import text_item +from openpilot.system.ui.widgets.scroller_tici import Scroller + +from openpilot.system.ui.sunnypilot.lib.utils import NoElideButtonAction +from openpilot.system.ui.sunnypilot.widgets.list_view import ListItemSP +from openpilot.system.ui.sunnypilot.widgets.tree_dialog import TreeFolder, TreeNode, TreeOptionDialog +from openpilot.system.ui.sunnypilot.widgets.progress_bar import progress_item + +MAP_PATH = Path(Paths.mapd_root()) / "offline" + + +class OSMLayout(Widget): + def __init__(self): + super().__init__() + self._current_percent = 0 + self._last_map_size_update = 0 + self._mem_params = Params("/dev/shm/params") if platform.system() != "Darwin" else ui_state.params + self._initialize_items() + self._update_map_size() + self._progress.set_visible(False) + self._state_btn.set_visible(False) + self._mapd_version.action_item.set_text(ui_state.params.get("MapdVersion") or "Loading...") + self._scroller = Scroller(self.items, line_separator=True, spacing=0) + + def _initialize_items(self): + self._mapd_version = text_item(tr("Mapd Version"), lambda: ui_state.params.get("MapdVersion") or "Loading...") + self._delete_maps_btn = ListItemSP(tr("Downloaded Maps"), action_item=NoElideButtonAction(tr("DELETE"), enabled=True), callback=self._delete_maps) + self._progress = progress_item(tr("Downloading Map")) + self._update_btn = ListItemSP(tr("Database Update"), action_item=NoElideButtonAction(tr("CHECK"), enabled=True), callback=self._update_db) + self._country_btn = ListItemSP(tr("Country"), action_item=NoElideButtonAction(tr("SELECT"), enabled=True), callback=lambda: self._select_region("Country")) + self._state_btn = ListItemSP(tr("State"), action_item=NoElideButtonAction(tr("SELECT"), enabled=True), callback=lambda: self._select_region("State")) + + self.items = [self._mapd_version, self._delete_maps_btn, self._progress, self._update_btn, self._country_btn, self._state_btn] + + def _show_confirm(self, msg, confirm_text, func): + gui_app.push_widget(ConfirmDialog(msg, confirm_text, callback=lambda res: func() if res == DialogResult.CONFIRM else None)) + + def calculate_size(self): + total_size = 0 + directories_to_scan = [MAP_PATH] if MAP_PATH.exists() else [] + while directories_to_scan: + try: + for entry in os.scandir(directories_to_scan.pop()): + if entry.is_file(): + total_size += entry.stat().st_size + elif entry.is_dir(): + directories_to_scan.append(entry.path) + except OSError: + pass + self._delete_maps_btn.action_item.set_value(f"{total_size / 1024 ** 2:.2f} MB" if total_size < 1024 ** 3 else f"{total_size / 1024 ** 3:.2f} GB") + + def _update_map_size(self): + threading.Thread(target=self.calculate_size, daemon=True).start() + + def _do_delete_maps(self): + if MAP_PATH.exists(): + shutil.rmtree(MAP_PATH) + + for param in ("OsmDownloadedDate", "OsmLocal", "OsmLocationName", "OsmLocationTitle", "OsmStateName", "OsmStateTitle"): + ui_state.params.remove(param) + + self._delete_maps_btn.action_item.set_enabled(True) + self._delete_maps_btn.action_item.set_text(tr("DELETE")) + self._update_map_size() + + def _on_confirm_delete_maps(self): + self._delete_maps_btn.action_item.set_enabled(False) + self._delete_maps_btn.action_item.set_text("DELETING...") + threading.Thread(target=self._do_delete_maps).start() + + def _delete_maps(self): + self._show_confirm(tr("This will delete ALL downloaded maps\n\nAre you sure you want to delete all maps?"), + tr("Yes, delete all maps"), self._on_confirm_delete_maps) + + def _update_db(self): + self._show_confirm(tr("This will start the download process and it might take a while to complete."), tr("Start Download"), + lambda: ui_state.params.put_bool("OsmDbUpdatesCheck", True)) + + def _select_region(self, region_type): + is_country = region_type == "Country" + btn = self._country_btn if is_country else self._state_btn + btn.action_item.set_enabled(False) + btn.action_item.set_text(tr("FETCHING...")) + threading.Thread(target=self._do_select_region, args=(region_type, btn)).start() + + def _handle_region_selection(self, region_type, locations, key, res, ref): + if res != DialogResult.CONFIRM or not ref: + if region_type == "State" and res == DialogResult.CANCEL: + if ui_state.params.get("OsmLocationName") == "US" and not ui_state.params.get("OsmStateName"): + ui_state.params.remove("OsmLocationName") + ui_state.params.remove("OsmLocationTitle") + ui_state.params.remove("OsmLocal") + self._update_labels() + return + + if region_type == "Country": + ui_state.params.put_bool("OsmLocal", True) + ui_state.params.remove("OsmStateName") + ui_state.params.remove("OsmStateTitle") + + ui_state.params.put(f"{key}Name", ref) + name = next((n.data['display_name'] for n in locations if n.ref == ref), ref) + ui_state.params.put(f"{key}Title", name) + + if ref == "US" and region_type == "Country": + self._select_region("State") + else: + self._update_db() + + def _do_select_region(self, region_type, btn): + base_url = "https://raw.githubusercontent.com/pfeiferj/openpilot-mapd/main/" + url = base_url + ("nation_bounding_boxes.json" if region_type == "Country" else "us_states_bounding_boxes.json") + try: + data = requests.get(url, timeout=10).json() + locations = sorted([TreeNode(ref=k, data={'display_name': v['full_name']}) for k, v in data.items()], key=lambda n: n.data['display_name']) + except Exception: + locations = [] + + if region_type == "State": + locations.insert(0, TreeNode(ref="All", data={'display_name': tr("All states (~6.0 GB)")})) + + btn.action_item.set_enabled(True) + btn.action_item.set_text(tr("SELECT")) + + key = "OsmLocation" if region_type == "Country" else "OsmState" + current = ui_state.params.get(f"{key}Name") or "" + + dialog = TreeOptionDialog(tr(f"Select {region_type}"), [TreeFolder(folder="", nodes=locations)], current_ref=current, search_prompt="Perform a search") + dialog.on_exit = lambda res: self._handle_region_selection(region_type, locations, key, res, dialog.selection_ref) + gui_app.push_widget(dialog) + + def _update_labels(self): + downloading = bool(self._mem_params.get("OSMDownloadLocations")) + self._country_btn.set_enabled(not downloading) + self._state_btn.set_enabled(not downloading) + self._state_btn.set_visible(ui_state.params.get("OsmLocationName") == "US") + self._update_btn.set_visible(bool(ui_state.params.get("OsmLocationName"))) + + self._country_btn.action_item.set_value(ui_state.params.get("OsmLocationTitle") or "") + self._state_btn.action_item.set_value(ui_state.params.get("OsmStateTitle") or "") + + pending = ui_state.params.get_bool("OsmDbUpdatesCheck") + if downloading or pending: + if downloading: + device._reset_interactive_timeout() + self._update_map_size() + self._progress.set_visible(True) + progress = ui_state.params.get("OSMDownloadProgress") + total = progress.get('total_files', 0) if progress else 0 + done = progress.get('downloaded_files', 0) if progress else 0 + failed = total > 0 and not downloading and done < total + + if total > 0: + progress_perc = max(0.0, min(100.0, (done / total) * 100.0)) + else: + progress_perc = 0.0 + + if failed: + text = "0% - Downloading Maps" + btn_text = tr("Error: Invalid download. Retry.") + self._current_percent = 0.0 + elif total > 0 and downloading: + self._current_percent = progress_perc + perc_int = int(progress_perc) + text = f"{perc_int}% - Downloading Maps" + btn_text = f"{done}/{total} ({perc_int}%)" + else: + self._current_percent = 0.0 + text = "0% - Downloading Maps" + btn_text = tr("Downloading Maps...") + + self._progress.action_item.update(self._current_percent, text, show_progress=total > 0 and downloading and not failed) + self._update_btn.action_item.set_enabled(not downloading) # TODO-SP: introduce CANCEL database download with mapd + self._update_btn.action_item.set_value(btn_text) + self._country_btn.action_item.set_enabled(not downloading) + self._state_btn.action_item.set_enabled(not downloading) + self._delete_maps_btn.action_item.set_enabled(not downloading) + else: + self._progress.set_visible(False) + self._update_btn.action_item.set_enabled(True) + self._country_btn.action_item.set_enabled(True) + self._state_btn.action_item.set_enabled(True) + self._delete_maps_btn.action_item.set_enabled(True) + + ts = ui_state.params.get("OsmDownloadedDate") + dt: datetime.datetime | None = None + + if ts: + try: + ts_f = float(ts) + if ts_f > 0: + dt = datetime.datetime.fromtimestamp(ts_f, tz=datetime.UTC) + except (ValueError, TypeError): + dt = None + + formatted = time_ago(dt) + self._update_btn.action_item.set_value(tr("Last checked {}").format(formatted)) + + def show_event(self): + self._scroller.show_event() + + def _update_state(self): + now = monotonic() + if now - self._last_map_size_update >= 1.0: + self._last_map_size_update = now + self._update_labels() + + def _render(self, rect): + self._scroller.render(rect) diff --git a/openpilot/selfdrive/ui/sunnypilot/layouts/settings/settings.py b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/settings.py new file mode 100644 index 0000000000..1b85c0923a --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/settings.py @@ -0,0 +1,199 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from dataclasses import dataclass +from enum import IntEnum + +import pyray as rl +from openpilot.selfdrive.ui.layouts.settings import settings as OP +from openpilot.selfdrive.ui.layouts.settings.firehose import FirehoseLayout +from openpilot.selfdrive.ui.layouts.settings.toggles import TogglesLayout +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.cruise import CruiseLayout +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.developer import DeveloperLayoutSP +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.device import DeviceLayoutSP +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.display import DisplayLayout +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.models import ModelsLayout +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.network import NetworkUISP +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.osm import OSMLayout +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.software import SoftwareLayoutSP +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.steering import SteeringLayout +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.sunnylink import SunnylinkLayout +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.trips import TripsLayout +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.vehicle import VehicleLayout +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.visuals import VisualsLayout +from openpilot.system.ui.lib.application import gui_app, MousePos +from openpilot.system.ui.lib.multilang import tr_noop +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.lib.wifi_manager import WifiManager +from openpilot.system.ui.sunnypilot.lib.styles import style +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.scroller_tici import Scroller + +# from openpilot.selfdrive.ui.sunnypilot.layouts.settings.navigation import NavigationLayout + +OP.PANEL_COLOR = rl.Color(10, 10, 10, 255) +ICON_SIZE = 70 + +OP.PanelType = IntEnum( # type: ignore[assignment] # ty: ignore[invalid-assignment] + "PanelType", + [es.name for es in OP.PanelType] + [ + "SUNNYLINK", + "MODELS", + "STEERING", + "CRUISE", + "VISUALS", + "DISPLAY", + "OSM", + "NAVIGATION", + "TRIPS", + "VEHICLE", + ], + start=0, +) + + +@dataclass +class PanelInfo(OP.PanelInfo): + icon: str = "" + + +class NavButton(Widget): + def __init__(self, parent, p_type, p_info): + super().__init__() + self.parent = parent + self.panel_type = p_type + self.panel_info = p_info + + def _render(self, rect): + is_selected = self.panel_type == self.parent._current_panel + text_color = OP.TEXT_SELECTED if is_selected else OP.TEXT_NORMAL + content_x = rect.x + 90 + text_size = measure_text_cached(self.parent._font_medium, self.panel_info.name, 65) + + # Draw background if selected + if is_selected: + self.container_rect = rl.Rectangle( + content_x - 50, rect.y, OP.SIDEBAR_WIDTH - 50, OP.NAV_BTN_HEIGHT + ) + rl.draw_rectangle_rounded(self.container_rect, 0.2, 5, OP.CLOSE_BTN_COLOR) + + if self.panel_info.icon: + icon_texture = gui_app.texture(self.panel_info.icon, ICON_SIZE, ICON_SIZE, keep_aspect_ratio=True) + rl.draw_texture_ex(icon_texture, rl.Vector2(content_x, rect.y + (OP.NAV_BTN_HEIGHT - icon_texture.height) / 2), 0.0, 1.0, rl.WHITE) + content_x += ICON_SIZE + 20 + + # Draw button text (right-aligned) + text_pos = rl.Vector2( + content_x, + rect.y + (OP.NAV_BTN_HEIGHT - text_size.y) / 2 + ) + rl.draw_text_ex(self.parent._font_medium, self.panel_info.name, text_pos, 55, 0, text_color) + + # Store button rect for click detection + self.panel_info.button_rect = rect + + +class SettingsLayoutSP(OP.SettingsLayout): + def __init__(self): + OP.SettingsLayout.__init__(self) + self._nav_items: list[Widget] = [] + + # Create sidebar scroller + self._sidebar_scroller = Scroller([], spacing=0, line_separator=False, pad_end=False) + + # Panel configuration + wifi_manager = WifiManager() + wifi_manager.set_active(False) + + self._panels = { + OP.PanelType.DEVICE: PanelInfo(tr_noop("Device"), DeviceLayoutSP(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_home.png"), + OP.PanelType.NETWORK: PanelInfo(tr_noop("Network"), NetworkUISP(wifi_manager), icon="icons/network.png"), + OP.PanelType.SUNNYLINK: PanelInfo(tr_noop("sunnylink"), SunnylinkLayout(), icon="icons/wifi_strength_full.png"), + OP.PanelType.TOGGLES: PanelInfo(tr_noop("Toggles"), TogglesLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_toggle.png"), + OP.PanelType.SOFTWARE: PanelInfo(tr_noop("Software"), SoftwareLayoutSP(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_software.png"), + OP.PanelType.MODELS: PanelInfo(tr_noop("Models"), ModelsLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_models.png"), + OP.PanelType.STEERING: PanelInfo(tr_noop("Steering"), SteeringLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_lateral.png"), + OP.PanelType.CRUISE: PanelInfo(tr_noop("Cruise"), CruiseLayout(), icon="icons/speed_limit.png"), + OP.PanelType.VISUALS: PanelInfo(tr_noop("Visuals"), VisualsLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_visuals.png"), + OP.PanelType.DISPLAY: PanelInfo(tr_noop("Display"), DisplayLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_display.png"), + OP.PanelType.OSM: PanelInfo(tr_noop("OSM"), OSMLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_map.png"), + # OP.PanelType.NAVIGATION: PanelInfo(tr_noop("Navigation"), NavigationLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_map.png"), + OP.PanelType.TRIPS: PanelInfo(tr_noop("Trips"), TripsLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_trips.png"), + OP.PanelType.VEHICLE: PanelInfo(tr_noop("Vehicle"), VehicleLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_vehicle.png"), + OP.PanelType.FIREHOSE: PanelInfo(tr_noop("Firehose"), FirehoseLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_firehose.png"), + OP.PanelType.DEVELOPER: PanelInfo(tr_noop("Developer"), DeveloperLayoutSP(), icon="icons/shell.png"), + } + + def _draw_sidebar(self, rect: rl.Rectangle): + rl.draw_rectangle_rec(rect, OP.SIDEBAR_COLOR) + + # Close button + close_btn_rect = rl.Rectangle( + rect.x + style.ITEM_PADDING * 3, rect.y + style.ITEM_PADDING * 2, style.CLOSE_BTN_SIZE, style.CLOSE_BTN_SIZE + ) + + pressed = (rl.is_mouse_button_down(rl.MouseButton.MOUSE_BUTTON_LEFT) and + rl.check_collision_point_rec(rl.get_mouse_position(), close_btn_rect)) + close_color = OP.CLOSE_BTN_PRESSED if pressed else OP.CLOSE_BTN_COLOR + rl.draw_rectangle_rounded(close_btn_rect, 1.0, 20, close_color) + + icon_color = rl.Color(255, 255, 255, 255) if not pressed else rl.Color(220, 220, 220, 255) + icon_dest = rl.Rectangle( + close_btn_rect.x + (close_btn_rect.width - self._close_icon.width) / 2, + close_btn_rect.y + (close_btn_rect.height - self._close_icon.height) / 2, + self._close_icon.width, + self._close_icon.height, + ) + rl.draw_texture_pro( + self._close_icon, + rl.Rectangle(0, 0, self._close_icon.width, self._close_icon.height), + icon_dest, + rl.Vector2(0, 0), + 0, + icon_color, + ) + + # Store close button rect for click detection + self._close_btn_rect = close_btn_rect + + # Navigation buttons with scroller + if not self._nav_items: + for panel_type, panel_info in self._panels.items(): + nav_button = NavButton(self, panel_type, panel_info) + nav_button.rect.width = rect.width - 100 # Full width minus padding + nav_button.rect.height = OP.NAV_BTN_HEIGHT + self._nav_items.append(nav_button) + self._sidebar_scroller.add_widget(nav_button) + + # Draw navigation section with scroller + nav_rect = rl.Rectangle( + rect.x, + self._close_btn_rect.height + style.ITEM_PADDING * 4, # Starting Y position for nav items + rect.width, + rect.height - 300 # Remaining height after close button + ) + + if self._nav_items: + self._sidebar_scroller.render(nav_rect) + return + + def _handle_mouse_release(self, mouse_pos: MousePos) -> None: + # Check close button + if rl.check_collision_point_rec(mouse_pos, self._close_btn_rect): + if self._close_callback: + self._close_callback() + return + + # Check navigation buttons + for panel_type, panel_info in self._panels.items(): + if rl.check_collision_point_rec(mouse_pos, panel_info.button_rect) and self._sidebar_scroller.scroll_panel.is_touch_valid(): + self.set_current_panel(panel_type) + return + + def show_event(self): + super().show_event() + self._panels[self._current_panel].instance.show_event() + self._sidebar_scroller.show_event() diff --git a/openpilot/selfdrive/ui/sunnypilot/layouts/settings/software.py b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/software.py new file mode 100644 index 0000000000..d067f1330d --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/software.py @@ -0,0 +1,96 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import subprocess + +from openpilot.selfdrive.ui.layouts.settings.software import SoftwareLayout +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.common.hardware import HARDWARE +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.lib.multilang import tr, tr_noop +from openpilot.system.ui.widgets import DialogResult +from openpilot.system.ui.widgets.confirm_dialog import ConfirmDialog + +from openpilot.system.ui.sunnypilot.widgets.list_view import toggle_item_sp +from openpilot.system.ui.sunnypilot.widgets.tree_dialog import TreeOptionDialog, TreeNode, TreeFolder + + +DESCRIPTIONS = { + 'disable_updates_offroad': tr_noop( + "When enabled, automatic software updates will be off.
This requires a reboot to take effect." + ), + 'disable_updates_onroad': tr_noop( + "Please enable \"Always Offroad\" mode or turn off the vehicle to adjust these toggles." + ) +} + + +class SoftwareLayoutSP(SoftwareLayout): + def __init__(self): + super().__init__() + self.disable_updates_toggle = toggle_item_sp( + lambda: tr("Disable Updates"), + description="", + initial_state=ui_state.params.get_bool("DisableUpdates"), + callback=self._on_disable_updates_toggled, + ) + self._scroller.add_widget(self.disable_updates_toggle) + + def _handle_reboot(self, result): + if result == DialogResult.CONFIRM: + ui_state.params.put_bool("DisableUpdates", self.disable_updates_toggle.action_item.get_state()) + ui_state.params.put_bool("DoReboot", True) + else: + self.disable_updates_toggle.action_item.set_state(ui_state.params.get_bool("DisableUpdates")) + + def _on_disable_updates_toggled(self, enabled): + dialog = ConfirmDialog(tr("System reboot required for changes to take effect. Reboot now?"), tr("Reboot"), callback=self._handle_reboot) + gui_app.push_widget(dialog) + + def _on_select_branch(self): + current_git_branch = ui_state.params.get("GitBranch") or "" + branches_str = ui_state.params.get("UpdaterAvailableBranches") or "" + branches = [b for b in branches_str.split(",") if b] + current_target = ui_state.params.get("UpdaterTargetBranch") or "" + top_level_branches = [current_git_branch, "release-mici", "release-tizi", "staging", "dev", "master"] + + if HARDWARE.get_device_type() == "tici": + top_level_branches = ["release-tici", "staging-tici"] + branches = [b for b in branches if b.endswith("-tici")] + + top_level_nodes = [TreeNode(b, {'display_name': b}) for b in top_level_branches if b in branches] + remaining_branches = [b for b in branches if b not in top_level_branches] + prebuilt_nodes = [TreeNode(b, {'display_name': b}) for b in remaining_branches if b.endswith("-prebuilt")] + non_prebuilt_nodes = [TreeNode(b, {'display_name': b}) for b in remaining_branches if not b.endswith("-prebuilt")] + + folders = [ + TreeFolder("", top_level_nodes), + TreeFolder("Prebuilt Branches", prebuilt_nodes), + TreeFolder("Non-Prebuilt Branches", non_prebuilt_nodes), + ] + + def _on_branch_selected(result): + if result == DialogResult.CONFIRM and self._branch_dialog is not None: + selection = self._branch_dialog.selection_ref + if selection: + ui_state.params.put("UpdaterTargetBranch", selection) + self._branch_btn.action_item.set_value(selection) + subprocess.run(["pkill", "-SIGUSR1", "-f", "openpilot.system.updated.updated"], check=False) + self._branch_dialog = None + + self._branch_dialog = TreeOptionDialog(tr("Select a branch"), folders, current_target, "", + on_exit=_on_branch_selected) + + gui_app.push_widget(self._branch_dialog) + + def _update_state(self): + super()._update_state() + show_advanced = ui_state.params.get_bool("ShowAdvancedControls") + self.disable_updates_toggle.action_item.set_enabled(ui_state.is_offroad()) + self.disable_updates_toggle.set_visible(show_advanced) + + disable_updates_desc = tr(DESCRIPTIONS["disable_updates_offroad"] if ui_state.is_offroad() else DESCRIPTIONS["disable_updates_onroad"]) + self.disable_updates_toggle.set_description(disable_updates_desc) diff --git a/openpilot/selfdrive/ui/sunnypilot/layouts/settings/steering.py b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/steering.py new file mode 100644 index 0000000000..15cb6a15e0 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/steering.py @@ -0,0 +1,158 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from opendbc.car.structs import car +from enum import IntEnum + +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.sunnypilot.widgets.list_view import toggle_item_sp, simple_button_item_sp, option_item_sp, LineSeparatorSP +from openpilot.system.ui.widgets.scroller_tici import Scroller +from openpilot.system.ui.widgets import Widget +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.steering_sub_layouts.lane_change_settings import LaneChangeSettingsLayout +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.steering_sub_layouts.mads_settings import MadsSettingsLayout +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.steering_sub_layouts.torque_settings import TorqueSettingsLayout + + +class PanelType(IntEnum): + STEERING = 0 + MADS = 1 + LANE_CHANGE = 2 + TORQUE_CONTROL = 3 + + +class SteeringLayout(Widget): + def __init__(self): + super().__init__() + + self._current_panel = PanelType.STEERING + self._lane_change_settings_layout = LaneChangeSettingsLayout(lambda: self._set_current_panel(PanelType.STEERING)) + self._mads_settings_layout = MadsSettingsLayout(lambda: self._set_current_panel(PanelType.STEERING)) + self._torque_control_layout = TorqueSettingsLayout(lambda: self._set_current_panel(PanelType.STEERING)) + + items = self._initialize_items() + self._scroller = Scroller(items, line_separator=False, spacing=0) + + def _initialize_items(self): + self._mads_base_desc = tr("Enable the beloved MADS feature. " + + "Disable toggle to revert back to stock sunnypilot engagement/disengagement.") + self._mads_limited_desc = tr("This platform supports limited MADS settings.") + self._mads_full_desc = tr("This platform supports all MADS settings.") + self._mads_check_compat_desc = tr("Start the vehicle to check vehicle compatibility.") + + self._mads_toggle = toggle_item_sp( + param="Mads", + title=lambda: tr("Modular Assistive Driving System (MADS)"), + description=self._mads_base_desc, + ) + self._mads_settings_button = simple_button_item_sp( + button_text=lambda: tr("Customize MADS"), + button_width=800, + callback=lambda: self._set_current_panel(PanelType.MADS) + ) + self._lane_change_settings_button = simple_button_item_sp( + button_text=lambda: tr("Customize Lane Change"), + button_width=800, + callback=lambda: self._set_current_panel(PanelType.LANE_CHANGE) + ) + self._blinker_control_toggle = toggle_item_sp( + param="BlinkerPauseLateralControl", + description=lambda: tr("Pause lateral control with blinker when traveling below the desired speed selected."), + title=lambda: tr("Pause Lateral Control with Blinker"), + ) + self._blinker_control_options = option_item_sp( + param="BlinkerMinLateralControlSpeed", + title=lambda: tr("Minimum Speed to Pause Lateral Control"), + min_value=0, + max_value=255, + value_change_step=5, + description="", + label_callback=lambda speed: f'{speed} {"km/h" if ui_state.is_metric else "mph"}', + ) + self._blinker_reengage_delay = option_item_sp( + param="BlinkerLateralReengageDelay", + title=lambda: tr("Post-Blinker Delay"), + min_value=0, + max_value=10, + value_change_step=1, + description=lambda: tr("Delay before lateral control resumes after the turn signal ends."), + label_callback=lambda delay: f'{delay} {"s"}' + ) + self._torque_control_toggle = toggle_item_sp( + param="EnforceTorqueControl", + title=lambda: tr("Enforce Torque Lateral Control"), + description=lambda: tr("Enable this to enforce sunnypilot to steer with Torque lateral control."), + ) + self._torque_customization_button = simple_button_item_sp( + button_text=lambda: tr("Customize Torque Params"), + button_width=850, + callback=lambda: self._set_current_panel(PanelType.TORQUE_CONTROL) + ) + self._nnlc_toggle = toggle_item_sp( + param="NeuralNetworkLateralControl", + title=lambda: tr("Neural Network Lateral Control (NNLC)"), + description="" + ) + + items = [ + self._mads_toggle, + self._mads_settings_button, + LineSeparatorSP(40), + self._lane_change_settings_button, + LineSeparatorSP(40), + self._blinker_control_toggle, + self._blinker_control_options, + self._blinker_reengage_delay, + LineSeparatorSP(40), + self._torque_control_toggle, + self._torque_customization_button, + LineSeparatorSP(40), + self._nnlc_toggle, + ] + return items + + def _set_current_panel(self, panel: PanelType): + self._current_panel = panel + + def _update_state(self): + super()._update_state() + + torque_allowed = ui_state.CP is not None and ui_state.CP.steerControlType != car.CarParams.SteerControlType.angle + if ui_state.CP is not None: + mads_main_desc = self._mads_limited_desc if self._mads_settings_layout._mads_limited_settings() else self._mads_full_desc + self._mads_toggle.set_description(f"{mads_main_desc}

{self._mads_base_desc}") + else: + self._mads_toggle.set_description(f"{self._mads_check_compat_desc}

{self._mads_base_desc}") + + self._mads_toggle.action_item.set_enabled(ui_state.is_offroad()) + self._mads_settings_button.action_item.set_enabled(ui_state.is_offroad() and self._mads_toggle.action_item.get_state()) + self._blinker_control_options.set_visible(self._blinker_control_toggle.action_item.get_state()) + self._blinker_reengage_delay.set_visible(self._blinker_control_toggle.action_item.get_state()) + + enforce_torque_enabled = self._torque_control_toggle.action_item.get_state() + nnlc_enabled = self._nnlc_toggle.action_item.get_state() + if enforce_torque_enabled and nnlc_enabled: + self._torque_control_toggle.action_item.set_state(False) + self._nnlc_toggle.action_item.set_state(False) + enforce_torque_enabled = False + nnlc_enabled = False + self._nnlc_toggle.action_item.set_enabled(ui_state.is_offroad() and torque_allowed and not enforce_torque_enabled) + self._torque_control_toggle.action_item.set_enabled(ui_state.is_offroad() and torque_allowed and not nnlc_enabled) + self._torque_customization_button.action_item.set_enabled(self._torque_control_toggle.action_item.get_state()) + + def _render(self, rect): + if self._current_panel == PanelType.LANE_CHANGE: + self._lane_change_settings_layout.render(rect) + elif self._current_panel == PanelType.MADS: + self._mads_settings_layout.render(rect) + elif self._current_panel == PanelType.TORQUE_CONTROL: + self._torque_control_layout.render(rect) + else: + self._scroller.render(rect) + + def show_event(self): + self._set_current_panel(PanelType.STEERING) + self._scroller.show_event() diff --git a/openpilot/selfdrive/ui/sunnypilot/layouts/settings/steering_sub_layouts/lane_change_settings.py b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/steering_sub_layouts/lane_change_settings.py new file mode 100644 index 0000000000..fbb9ce7cf7 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/steering_sub_layouts/lane_change_settings.py @@ -0,0 +1,81 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from collections.abc import Callable +import pyray as rl + +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.sunnypilot.widgets.list_view import toggle_item_sp, option_item_sp, LineSeparatorSP +from openpilot.system.ui.widgets.network import NavButton +from openpilot.system.ui.widgets.scroller_tici import Scroller +from openpilot.system.ui.widgets import Widget + +from openpilot.sunnypilot.selfdrive.controls.lib.auto_lane_change import AutoLaneChangeMode + + +class LaneChangeSettingsLayout(Widget): + def __init__(self, back_btn_callback: Callable): + super().__init__() + self._back_button = NavButton(tr("Back")) + self._back_button.set_click_callback(back_btn_callback) + + items = self._initialize_items() + self._scroller = Scroller(items, line_separator=False, spacing=0) + + def _initialize_items(self): + self._lane_change_timer = option_item_sp( + title=lambda: tr("Auto Lane Change by Blinker"), + param="AutoLaneChangeTimer", + description=lambda: tr("Set a timer to delay the auto lane change operation when the blinker is used. " + + "No nudge on the steering wheel is required to auto lane change if a timer is set. Default is Nudge.
" + + "Please use caution when using this feature. Only use the blinker when traffic and road conditions permit."), + min_value=-1, + max_value=5, + value_change_step=1, + label_callback=(lambda x: + tr("Off") if x == -1 else + tr("Nudge") if x == 0 else + tr("Nudgeless") if x == 1 else + f"0.5 {tr('s')}" if x == 2 else + f"1 {tr('s')}" if x == 3 else + f"2 {tr('s')}" if x == 4 else + f"3 {tr('s')}") + ) + self._bsm_delay = toggle_item_sp( + param="AutoLaneChangeBsmDelay", + title=lambda: tr("Auto Lane Change: Delay with Blind Spot"), + description=lambda: tr("Toggle to enable a delay timer for seamless lane changes when blind spot monitoring " + + "(BSM) detects a obstructing vehicle, ensuring safe maneuvering."), + ) + + items = [ + self._lane_change_timer, + LineSeparatorSP(40), + self._bsm_delay, + ] + + return items + + def _update_state(self): + super()._update_state() + self._update_toggles() + + def _render(self, rect): + self._back_button.set_position(self._rect.x, self._rect.y + 20) + self._back_button.render() + # subtract button + content_rect = rl.Rectangle(rect.x, rect.y + self._back_button.rect.height + 40, rect.width, rect.height - self._back_button.rect.height - 40) + self._scroller.render(content_rect) + + def show_event(self): + self._scroller.show_event() + + def _update_toggles(self): + enable_bsm = ui_state.CP is not None and ui_state.CP.enableBsm + if not enable_bsm and ui_state.params.get_bool("AutoLaneChangeBsmDelay"): + ui_state.params.remove("AutoLaneChangeBsmDelay") + self._bsm_delay.action_item.set_enabled(enable_bsm and ui_state.params.get("AutoLaneChangeTimer", return_default=True) > AutoLaneChangeMode.NUDGE) diff --git a/openpilot/selfdrive/ui/sunnypilot/layouts/settings/steering_sub_layouts/mads_settings.py b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/steering_sub_layouts/mads_settings.py new file mode 100644 index 0000000000..098fcf8ce8 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/steering_sub_layouts/mads_settings.py @@ -0,0 +1,137 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from collections.abc import Callable +import pyray as rl + +from opendbc.sunnypilot.car.tesla.values import TeslaFlagsSP +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.sunnypilot.mads.helpers import MadsSteeringModeOnBrake +from openpilot.system.ui.lib.multilang import tr, tr_noop +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.network import NavButton +from openpilot.system.ui.widgets.scroller_tici import Scroller +from openpilot.system.ui.sunnypilot.widgets.list_view import multiple_button_item_sp, toggle_item_sp + +MADS_STEERING_MODE_OPTIONS = [ + (tr("Remain Active"), tr_noop("Remain Active: ALC will remain active when the brake pedal is pressed.")), + (tr("Pause"), tr_noop("Pause: ALC will pause when the brake pedal is pressed.")), + (tr("Disengage"), tr_noop("Disengage: ALC will disengage when the brake pedal is pressed.")), +] + +MADS_MAIN_CRUISE_BASE_DESC = tr("Note: For vehicles without LFA/LKAS button, disabling this will prevent lateral control engagement.") +MADS_UNIFIED_ENGAGEMENT_MODE_BASE_DESC = "{engage}

{note}

".format( + engage=tr("Engage lateral and longitudinal control with cruise control engagement."), + note=tr("Note: Once lateral control is engaged via UEM, it will remain engaged until it is manually disabled via the MADS button or car shut off."), +) + +STATUS_CHECK_COMPATIBILITY = tr("Start the vehicle to check vehicle compatibility.") +DEFAULT_TO_OFF = tr("This feature defaults to OFF, and does not allow selection due to vehicle limitations.") +DEFAULT_TO_ON = tr("This feature defaults to ON, and does not allow selection due to vehicle limitations.") +STATUS_DISENGAGE_ONLY = tr("This platform only supports Disengage mode due to vehicle limitations.") + + +class MadsSettingsLayout(Widget): + def __init__(self, back_btn_callback: Callable): + super().__init__() + self._back_button = NavButton(tr("Back")) + self._back_button.set_click_callback(back_btn_callback) + self._initialize_items() + self._scroller = Scroller(self.items, line_separator=True, spacing=0) + + def _initialize_items(self): + self._main_cruise_toggle = toggle_item_sp( + title=lambda: tr("Toggle with Main Cruise"), + description=MADS_MAIN_CRUISE_BASE_DESC, + param="MadsMainCruiseAllowed", + ) + self._unified_engagement_toggle = toggle_item_sp( + title=lambda: tr("Unified Engagement Mode (UEM)"), + description=MADS_UNIFIED_ENGAGEMENT_MODE_BASE_DESC, + param="MadsUnifiedEngagementMode" + ) + self._steering_mode = multiple_button_item_sp( + param="MadsSteeringMode", + title=lambda: tr("Steering Mode on Brake Pedal"), + description="", + buttons=[opt[0] for opt in MADS_STEERING_MODE_OPTIONS], + inline=False, + button_width=350, + callback=self._update_steering_mode_description, + ) + + self.items = [ + self._main_cruise_toggle, + self._unified_engagement_toggle, + self._steering_mode, + ] + + def _update_state(self): + super()._update_state() + self._update_toggles() + + def _render(self, rect): + self._back_button.set_position(self._rect.x, self._rect.y + 20) + self._back_button.render() + # subtract button + content_rect = rl.Rectangle(rect.x, rect.y + self._back_button.rect.height + 40, rect.width, rect.height - self._back_button.rect.height - 40) + self._scroller.render(content_rect) + + def show_event(self): + self._scroller.show_event() + + @staticmethod + def _mads_limited_settings() -> bool: + brand = "" + if ui_state.is_offroad(): + bundle = ui_state.params.get("CarPlatformBundle") + if bundle: + brand = bundle.get("brand", "") + if not brand: + brand = ui_state.CP.brand if ui_state.CP is not None else "" + + if brand == "rivian": + return True + elif brand == "tesla": + return not (ui_state.CP_SP is not None and ui_state.CP_SP.flags & TeslaFlagsSP.HAS_VEHICLE_BUS) + return False + + def _update_steering_mode_description(self, button_index: int): + base_desc = tr("Choose how Automatic Lane Centering (ALC) behaves after the brake pedal is manually pressed in sunnypilot.") + result = base_desc + "

" + for opt in MADS_STEERING_MODE_OPTIONS: + desc = "" + opt[1] + "" if button_index == MADS_STEERING_MODE_OPTIONS.index(opt) else opt[1] + result += desc + "
" + self._steering_mode.set_description(result) + self._steering_mode.show_description(True) + + def _update_toggles(self): + self._update_steering_mode_description(self._steering_mode.action_item.get_selected_button()) + if self._mads_limited_settings(): + ui_state.params.remove("MadsMainCruiseAllowed") + ui_state.params.put_bool("MadsUnifiedEngagementMode", True) + ui_state.params.put("MadsSteeringMode", MadsSteeringModeOnBrake.DISENGAGE) + + self._main_cruise_toggle.action_item.set_enabled(False) + self._main_cruise_toggle.action_item.set_state(False) + self._main_cruise_toggle.set_description("" + DEFAULT_TO_OFF + "
" + MADS_MAIN_CRUISE_BASE_DESC) + + self._unified_engagement_toggle.action_item.set_enabled(False) + self._unified_engagement_toggle.action_item.set_state(True) + self._unified_engagement_toggle.set_description("" + DEFAULT_TO_ON + "
" + MADS_UNIFIED_ENGAGEMENT_MODE_BASE_DESC) + + self._steering_mode.set_description(STATUS_DISENGAGE_ONLY) + self._steering_mode.action_item.set_selected_button(MadsSteeringModeOnBrake.DISENGAGE) + self._steering_mode.action_item.set_enabled_buttons({MadsSteeringModeOnBrake.DISENGAGE}) + else: + self._main_cruise_toggle.action_item.set_enabled(True) + self._main_cruise_toggle.set_description(MADS_MAIN_CRUISE_BASE_DESC) + + self._unified_engagement_toggle.action_item.set_enabled(True) + self._unified_engagement_toggle.set_description(MADS_UNIFIED_ENGAGEMENT_MODE_BASE_DESC) + + self._steering_mode.action_item.set_enabled(True) + self._steering_mode.action_item.set_enabled_buttons(None) diff --git a/openpilot/selfdrive/ui/sunnypilot/layouts/settings/steering_sub_layouts/torque_settings.py b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/steering_sub_layouts/torque_settings.py new file mode 100644 index 0000000000..f3c4419e45 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/steering_sub_layouts/torque_settings.py @@ -0,0 +1,191 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import json +import math +import os +from collections.abc import Callable +import pyray as rl + +from openpilot.common.basedir import BASEDIR +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.sunnypilot.lib.utils import NoElideButtonAction +from openpilot.system.ui.sunnypilot.widgets.list_view import ListItemSP, toggle_item_sp, option_item_sp +from openpilot.system.ui.sunnypilot.widgets.tree_dialog import TreeOptionDialog, TreeFolder, TreeNode +from openpilot.system.ui.widgets import Widget, DialogResult +from openpilot.system.ui.widgets.network import NavButton +from openpilot.system.ui.widgets.scroller_tici import Scroller + +TORQUE_VERSIONS_PATH = os.path.join(BASEDIR, "openpilot", "sunnypilot", "selfdrive", "controls", "lib", "latcontrol_torque_versions.json") + + +class TorqueSettingsLayout(Widget): + def __init__(self, back_btn_callback: Callable): + super().__init__() + self._back_button = NavButton(tr("Back")) + self._back_button.set_click_callback(back_btn_callback) + self._torque_version_dialog: TreeOptionDialog | None = None + self.cached_torque_versions = {} + self._load_versions() + items = self._initialize_items() + self._scroller = Scroller(items, line_separator=True, spacing=0) + + def _load_versions(self): + with open(TORQUE_VERSIONS_PATH) as f: + self.cached_torque_versions = json.load(f) + + def _initialize_items(self): + self._torque_control_versions = ListItemSP( + title=tr("Torque Control Tune Version"), + description="Select the version of Torque Control Tune to use.", + action_item=NoElideButtonAction(tr("SELECT")), + callback=self._show_torque_version_dialog, + ) + self._self_tune_toggle = toggle_item_sp( + param="LiveTorqueParamsToggle", + title=lambda: tr("Self-Tune"), + description=lambda: tr("Enables self-tune for Torque lateral control for platforms that do not use " + + "Torque lateral control by default."), + ) + self._relaxed_tune_toggle = toggle_item_sp( + param="LiveTorqueParamsRelaxedToggle", + title=lambda: tr("Less Restrict Settings for Self-Tune (Beta)"), + description=lambda: tr("Less strict settings when using Self-Tune. This allows torqued to be more " + + "forgiving when learning values."), + ) + self._custom_tune_toggle = toggle_item_sp( + param="CustomTorqueParams", + title=lambda: tr("Enable Custom Tuning"), + description=lambda: tr("Enables custom tuning for Torque lateral control. " + + "Modifying Lateral Acceleration Factor and Friction below will override the offline values " + + "indicated in the YAML files within \"opendbc/car/torque_data\". " + + "The values will also be used live when \"Manual Real-Time Tuning\" toggle is enabled."), + ) + self._torque_prams_override_toggle = toggle_item_sp( + param="TorqueParamsOverrideEnabled", + title=lambda: tr("Manual Real-Time Tuning"), + description=lambda: tr("Enforces the torque lateral controller to use the fixed values instead of the learned " + + "values from Self-Tune. Enabling this toggle overrides Self-Tune values."), + ) + self._torque_lat_accel_factor = option_item_sp( + title=lambda: tr("Lateral Acceleration Factor"), + param="TorqueParamsOverrideLatAccelFactor", + description="", + min_value=1, + max_value=500, + value_change_step=1, + label_callback=(lambda x: f"{x/100} m/s^2"), + use_float_scaling=True + ) + + self._torque_friction = option_item_sp( + title=lambda: tr("Friction"), + param="TorqueParamsOverrideFriction", + description="", + min_value=1, + max_value=100, + value_change_step=1, + label_callback=(lambda x: f"{x/100}"), + use_float_scaling=True + ) + + items = [ + self._torque_control_versions, + self._self_tune_toggle, + self._relaxed_tune_toggle, + self._custom_tune_toggle, + self._torque_prams_override_toggle, + self._torque_lat_accel_factor, + self._torque_friction, + ] + return items + + def _update_state(self): + super()._update_state() + if not ui_state.params.get_bool("LiveTorqueParamsToggle"): + ui_state.params.remove("LiveTorqueParamsRelaxedToggle") + self._relaxed_tune_toggle.action_item.set_state(False) + self._self_tune_toggle.action_item.set_enabled(ui_state.is_offroad()) + self._relaxed_tune_toggle.action_item.set_enabled(ui_state.is_offroad() and self._self_tune_toggle.action_item.get_state()) + self._custom_tune_toggle.action_item.set_enabled(ui_state.is_offroad()) + custom_tune_enabled = self._custom_tune_toggle.action_item.get_state() + self._torque_prams_override_toggle.set_visible(custom_tune_enabled) + self._torque_lat_accel_factor.set_visible(custom_tune_enabled) + self._torque_friction.set_visible(custom_tune_enabled) + + self._torque_prams_override_toggle.action_item.set_enabled(ui_state.is_offroad()) + sliders_enabled = self._torque_prams_override_toggle.action_item.get_state() or ui_state.is_offroad() + self._torque_lat_accel_factor.action_item.set_enabled(sliders_enabled) + self._torque_friction.action_item.set_enabled(sliders_enabled) + + title_text = tr("Real-Time & Offline") if ui_state.params.get("TorqueParamsOverrideEnabled") else tr("Offline Only") + self._torque_lat_accel_factor.set_title(lambda: tr("Lateral Acceleration Factor") + " (" + title_text + ")") + self._torque_friction.set_title(lambda: tr("Friction") + " (" + title_text + ")") + self._torque_control_versions.action_item.set_value(self._get_current_torque_version_label()) + + def _render(self, rect): + self._back_button.set_position(self._rect.x, self._rect.y + 20) + self._back_button.render() + # subtract button + content_rect = rl.Rectangle(rect.x, rect.y + self._back_button.rect.height + 40, rect.width, rect.height - self._back_button.rect.height - 40) + self._scroller.render(content_rect) + + def show_event(self): + self._scroller.show_event() + + def _get_current_torque_version_label(self): + current_val_bytes = ui_state.params.get("TorqueControlTune") + if current_val_bytes is None: + return tr("Default") + + try: + current_val = float(current_val_bytes) + for label, info in self.cached_torque_versions.items(): + if math.isclose(float(info["version"]), current_val, rel_tol=1e-5): + return label + except (ValueError, KeyError): + pass + + return tr("Default") + + def _show_torque_version_dialog(self): + options_map = {} + for label, info in self.cached_torque_versions.items(): + try: + options_map[label] = float(info["version"]) + except (ValueError, KeyError): + pass + + # Sort options by label in descending order + sorted_labels = sorted(options_map.keys(), key=lambda k: options_map[k], reverse=True) + + nodes = [TreeNode(tr("Default"))] + for label in sorted_labels: + nodes.append(TreeNode(label)) + + folders = [TreeFolder("", nodes)] + + current_label = self._get_current_torque_version_label() + + def handle_selection(result: int): + if result == DialogResult.CONFIRM and self._torque_version_dialog: + selected_ref = self._torque_version_dialog.selection_ref + if selected_ref == tr("Default"): + ui_state.params.remove("TorqueControlTune") + elif selected_ref in options_map: + ui_state.params.put("TorqueControlTune", options_map[selected_ref]) + self._torque_version_dialog = None + + self._torque_version_dialog = TreeOptionDialog( + tr("Select Torque Control Tune Version"), + folders, + current_ref=current_label, + option_font_weight=FontWeight.UNIFONT, + on_exit=handle_selection, + ) + gui_app.push_widget(self._torque_version_dialog) diff --git a/openpilot/selfdrive/ui/sunnypilot/layouts/settings/sunnylink.py b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/sunnylink.py new file mode 100644 index 0000000000..5e75e797cb --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/sunnylink.py @@ -0,0 +1,366 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import pyray as rl +from openpilot.cereal import custom +from openpilot.selfdrive.ui.sunnypilot.layouts.onboarding import SunnylinkConsentPage +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.sunnypilot.sunnylink.api import UNREGISTERED_SUNNYLINK_DONGLE_ID +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.sunnypilot.widgets.list_view import button_item_sp +from openpilot.system.ui.sunnypilot.widgets.list_view import toggle_item_sp +from openpilot.system.ui.sunnypilot.widgets.sunnylink_pairing_dialog import SunnylinkPairingDialog +from openpilot.system.ui.widgets import Widget, DialogResult +from openpilot.system.ui.widgets.button import ButtonStyle, Button +from openpilot.system.ui.widgets.confirm_dialog import alert_dialog, ConfirmDialog +from openpilot.system.ui.widgets.label import UnifiedLabel +from openpilot.system.ui.widgets.list_view import dual_button_item +from openpilot.system.ui.widgets.scroller_tici import Scroller, LineSeparator +from openpilot.common.version import sunnylink_consent_version + + +class SunnylinkHeader(Widget): + def __init__(self): + super().__init__() + + self._title = UnifiedLabel( + text="🚀 sunnylink 🚀", + font_size=90, + font_weight=FontWeight.AUDIOWIDE, + text_color=rl.WHITE, + alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER, + alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_TOP, + wrap_text=False, + elide=False + ) + + self._description = UnifiedLabel( + text=tr("For secure backup, restore, and remote configuration"), + font_size=40, + font_weight=FontWeight.NORMAL, + text_color=rl.Color(0, 255, 0, 255), # Green + alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER, + alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_TOP, + wrap_text=True, + elide=False + ) + + self._sponsor_msg = UnifiedLabel( + text=tr("Sponsorship isn't required for basic backup/restore") + "\n" + + tr("Click the Sponsor button for more details"), + font_size=35, + font_weight=FontWeight.NORMAL, + text_color=rl.Color(255, 165, 0, 255), # Orange + alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER, + alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_TOP, + wrap_text=True, + elide=False + ) + + self._padding = 20 + self._spacing = 10 + + def set_parent_rect(self, parent_rect: rl.Rectangle) -> None: + super().set_parent_rect(parent_rect) + + content_width = int(parent_rect.width - (self._padding * 2)) + + title_height = self._title.get_content_height(content_width) + desc_height = self._description.get_content_height(content_width) + sponsor_height = self._sponsor_msg.get_content_height(content_width) + + total_height = (self._padding + title_height + self._spacing + + desc_height + self._spacing + sponsor_height + self._padding) + + self._rect.width = parent_rect.width + self._rect.height = total_height + + def _render(self, rect: rl.Rectangle): + content_width = rect.width - (self._padding * 2) + current_y = rect.y + self._padding + + # Render title + title_height = self._title.get_content_height(int(content_width)) + title_rect = rl.Rectangle(rect.x + self._padding, current_y, content_width, title_height) + self._title.render(title_rect) + current_y += title_height + self._spacing + + # Render description + desc_height = self._description.get_content_height(int(content_width)) + desc_rect = rl.Rectangle(rect.x + self._padding, current_y, content_width, desc_height) + self._description.render(desc_rect) + current_y += desc_height + self._spacing + + # Render sponsor message + sponsor_height = self._sponsor_msg.get_content_height(int(content_width)) + sponsor_rect = rl.Rectangle(rect.x + self._padding, current_y, content_width, sponsor_height) + self._sponsor_msg.render(sponsor_rect) + + +class SunnylinkDescriptionItem(Widget): + def __init__(self): + super().__init__() + self._description = UnifiedLabel( + text="", + font_size=40, + font_weight=FontWeight.NORMAL, + text_color=rl.WHITE, + alignment=rl.GuiTextAlignment.TEXT_ALIGN_LEFT, + alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_TOP, + wrap_text=True, + elide=False, + ) + self._padding = 20 + + def set_parent_rect(self, parent_rect: rl.Rectangle) -> None: + super().set_parent_rect(parent_rect) + desc_height = self._description.get_content_height(int(parent_rect.width)) + self._padding * 2 + + self._rect.width = parent_rect.width + self._rect.height = desc_height + + def set_text(self, text: str): + self._description.set_text(text) + + def set_color(self, color: rl.Color): + self._description.set_text_color(color) + + def _render(self, rect: rl.Rectangle): + content_width = rect.width - (self._padding * 2) + + desc_height = self._description.get_content_height(int(content_width)) + desc_rect = rl.Rectangle(rect.x + self._padding, rect.y, content_width, desc_height) + self._description.render(desc_rect) + + +class SunnylinkLayout(Widget): + def __init__(self): + super().__init__() + + self._sunnylink_pairing_dialog: SunnylinkPairingDialog | None = None + self._restore_in_progress = False + self._backup_in_progress = False + self._sunnylink_enabled = ui_state.params.get("SunnylinkEnabled") + + items = self._initialize_items() + self._scroller = Scroller(items, line_separator=False, spacing=0) + + def _initialize_items(self): + self._sunnylink_toggle = toggle_item_sp( + title=tr("Enable sunnylink"), + description=tr("This is the master switch, it will allow you to cutoff any sunnylink requests should you want to do that."), + param="SunnylinkEnabled", + callback=self._sunnylink_toggle_callback + ) + + self._sunnylink_description = SunnylinkDescriptionItem() + self._sunnylink_description.set_visible(False) + + self._sponsor_btn = button_item_sp( + title=tr("Sponsor Status"), + button_text=tr("SPONSOR"), + description=tr( + "Become a sponsor of sunnypilot to get early access to sunnylink features when they become available."), + callback=lambda: self._handle_pair_btn(False) + ) + self._pair_btn = button_item_sp( + title=tr("Pair GitHub Account"), + button_text=tr("Not Paired"), + description=tr( + "Pair your GitHub account to grant your device sponsor benefits, including API access on sunnylink."), + callback=lambda: self._handle_pair_btn(True) + ) + self._sunnylink_uploader_toggle = toggle_item_sp( + title=tr("Enable sunnylink uploader (infrastructure test)"), + description=tr("Enable sunnylink uploader to allow sunnypilot to upload your driving data to sunnypilot servers. ") + + tr("(Only for highest tiers, and does NOT bring ANY benefit to you yet. We are just testing data volume.)"), + param="EnableSunnylinkUploader" + ) + self._sunnylink_backup_restore_buttons = dual_button_item( + description="", + left_text=tr("Backup Settings"), + right_text=tr("Restore Settings"), + left_callback=self._handle_backup_btn, + right_callback=self._handle_restore_btn + ) + self._backup_btn: Button = self._sunnylink_backup_restore_buttons.action_item.left_button # store for easy individual access + self._restore_btn: Button = self._sunnylink_backup_restore_buttons.action_item.right_button + self._backup_btn.set_button_style(ButtonStyle.NORMAL) + self._restore_btn.set_button_style(ButtonStyle.PRIMARY) + + items = [ + SunnylinkHeader(), + LineSeparator(), + self._sunnylink_toggle, + self._sunnylink_description, + LineSeparator(), + self._sponsor_btn, + LineSeparator(), + self._pair_btn, + LineSeparator(), + self._sunnylink_uploader_toggle, + LineSeparator(), + self._sunnylink_backup_restore_buttons + ] + return items + + @staticmethod + def _get_sunnylink_dongle_id() -> str: + return ui_state.params.get("SunnylinkDongleId") or tr("N/A") + + def _handle_pair_btn(self, sponsor_pairing: bool = False): + sunnylink_dongle_id = self._get_sunnylink_dongle_id() + if sunnylink_dongle_id == UNREGISTERED_SUNNYLINK_DONGLE_ID: + gui_app.push_widget(alert_dialog(message=tr("sunnylink Dongle ID not found. ") + + tr("This may be due to weak internet connection or sunnylink registration issue. ") + + tr("Please reboot and try again."))) + elif not self._sunnylink_pairing_dialog: + self._sunnylink_pairing_dialog = SunnylinkPairingDialog(sponsor_pairing) + gui_app.push_widget(self._sunnylink_pairing_dialog) + + def _handle_backup_btn(self): + backup_dialog = ConfirmDialog(text=tr("Are you sure you want to backup your current sunnypilot settings?"), confirm_text="Backup", + callback=self._backup_handler) + gui_app.push_widget(backup_dialog) + + def _handle_restore_btn(self): + self._restore_btn.set_enabled(False) + restore_dialog = ConfirmDialog(text=tr("Are you sure you want to restore the last backed up sunnypilot settings?"), + confirm_text="Restore", callback=self._restore_handler) + gui_app.push_widget(restore_dialog) + + def _backup_handler(self, dialog_result: int): + if dialog_result == DialogResult.CONFIRM: + self._backup_in_progress = True + self._backup_btn.set_enabled(False) + ui_state.params.put_bool("BackupManager_CreateBackup", True) + + def _restore_handler(self, dialog_result: int): + if dialog_result == DialogResult.CONFIRM: + self._restore_in_progress = True + self._restore_btn.set_enabled(False) + ui_state.params.put("BackupManager_RestoreVersion", "latest") + + def handle_backup_restore_progress(self): + sunnylink_backup_manager = ui_state.sm["backupManagerSP"] + + backup_status = sunnylink_backup_manager.backupStatus + restore_status = sunnylink_backup_manager.restoreStatus + backup_progress = sunnylink_backup_manager.backupProgress + restore_progress = sunnylink_backup_manager.restoreProgress + + if self._backup_in_progress: + self._restore_btn.set_enabled(False) + self._backup_btn.set_enabled(False) + + if backup_status == custom.BackupManagerSP.Status.inProgress: + self._backup_in_progress = True + text = tr(f"Backing up {backup_progress}%") + self._backup_btn.set_text(text) + + elif backup_status == custom.BackupManagerSP.Status.failed: + self._backup_in_progress = False + self._backup_btn.set_enabled(not ui_state.is_onroad()) + self._backup_btn.set_text(tr("Backup Failed")) + + elif (backup_status == custom.BackupManagerSP.Status.completed or + (backup_status == custom.BackupManagerSP.Status.idle and backup_progress == 100.0)): + self._backup_in_progress = False + dialog = alert_dialog(tr("Settings backup completed.")) + gui_app.push_widget(dialog) + self._backup_btn.set_enabled(not ui_state.is_onroad()) + + elif self._restore_in_progress: + self._restore_btn.set_enabled(False) + self._backup_btn.set_enabled(False) + + if restore_status == custom.BackupManagerSP.Status.inProgress: + self._restore_in_progress = True + text = tr(f"Restoring {restore_progress}%") + self._restore_btn.set_text(text) + + elif restore_status == custom.BackupManagerSP.Status.failed: + self._restore_in_progress = False + self._restore_btn.set_enabled(not ui_state.is_onroad()) + self._restore_btn.set_text(tr("Restore Failed")) + dialog = alert_dialog(tr("Unable to restore the settings, try again later.")) + gui_app.push_widget(dialog) + + elif (restore_status == custom.BackupManagerSP.Status.completed or + (restore_status == custom.BackupManagerSP.Status.idle and restore_progress == 100.0)): + self._restore_in_progress = False + dialog = ConfirmDialog(tr("Settings restored. Confirm to restart the interface."), tr("OK"), cancel_text="", callback=lambda _: gui_app.request_close()) + gui_app.push_widget(dialog) + + else: + can_enable = self._sunnylink_enabled and not ui_state.is_onroad() + self._backup_btn.set_enabled(can_enable) + self._backup_btn.set_text(tr("Backup Settings")) + self._restore_btn.set_enabled(can_enable) + self._restore_btn.set_text(tr("Restore Settings")) + + def _sunnylink_toggle_callback(self, state: bool): + sl_consent: bool = ui_state.params.get("CompletedSunnylinkConsentVersion") == sunnylink_consent_version + sl_enabled: bool = ui_state.params.get_bool("SunnylinkEnabled") + + if state and not sl_consent and not sl_enabled: + def on_consent_done(): + enabled = ui_state.params.get_bool("SunnylinkEnabled") + self._update_description(enabled) + gui_app.pop_widget() + + sl_terms_dlg = SunnylinkConsentPage(done_callback=on_consent_done) + gui_app.push_widget(sl_terms_dlg) + else: + ui_state.params.put_bool("SunnylinkEnabled", state) + self._update_description(state) + + def _update_description(self, state: bool): + if state: + description = tr( + "Welcome back!! We're excited to see you've enabled sunnylink again!") + color = rl.Color(0, 255, 0, 255) # Green + else: + description = ("😢 " + tr("Not going to lie, it's sad to see you disabled sunnylink") + + tr(", but we'll be here when you're ready to come back.")) + color = rl.Color(255, 165, 0, 255) # Orange + self._sunnylink_description.set_text(description) + self._sunnylink_description.set_color(color) + self._sunnylink_description.set_visible(True) + self._sunnylink_toggle.show_description(False) + + def _update_state(self): + super()._update_state() + self._sunnylink_enabled = ui_state.params.get_bool("SunnylinkEnabled") + self._sunnylink_toggle.set_right_value(tr("Dongle ID") + ": " + self._get_sunnylink_dongle_id()) + self._sunnylink_toggle.action_item.set_enabled(not ui_state.is_onroad()) + self._sunnylink_toggle.action_item.set_state(self._sunnylink_enabled) + self._sunnylink_uploader_toggle.action_item.set_enabled(self._sunnylink_enabled) + self.handle_backup_restore_progress() + + sponsor_btn_text = tr("THANKS ♥") if ui_state.sunnylink_state.is_sponsor() else tr("SPONSOR") + tier_name = ui_state.sunnylink_state.get_sponsor_tier().name.capitalize() or tr("Not Sponsor") + self._sponsor_btn.action_item.set_text(sponsor_btn_text) + self._sponsor_btn.action_item.set_value(tier_name, ui_state.sunnylink_state.get_sponsor_tier_color()) + self._sponsor_btn.action_item.set_enabled(self._sunnylink_enabled) + + pair_btn_text = tr("Paired") if ui_state.sunnylink_state.is_paired() else tr("Not Paired") + self._pair_btn.action_item.set_text(pair_btn_text) + self._pair_btn.action_item.set_enabled(self._sunnylink_enabled) + + def _render(self, rect): + self._scroller.render(rect) + + def show_event(self): + super().show_event() + ui_state.sunnylink_state.set_settings_open(True) + self._scroller.show_event() + self._sunnylink_description.set_visible(False) + + def hide_event(self): + super().hide_event() + ui_state.sunnylink_state.set_settings_open(False) diff --git a/openpilot/selfdrive/ui/sunnypilot/layouts/settings/trips.py b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/trips.py new file mode 100644 index 0000000000..066f52507f --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/trips.py @@ -0,0 +1,149 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import requests +import threading +import time +import pyray as rl + +from openpilot.common.api import api_get +from openpilot.common.constants import CV +from openpilot.common.params import Params +from openpilot.common.swaglog import cloudlog +from openpilot.selfdrive.ui.lib.api_helpers import get_token +from openpilot.selfdrive.ui.ui_state import ui_state, device +from openpilot.system.athena.registration import UNREGISTERED_DONGLE_ID +from openpilot.system.ui.lib.application import gui_app, FontWeight, FONT_SCALE +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.widgets import Widget + + +class TripsLayout(Widget): + PARAM_KEY = "ApiCache_DriveStats" + UPDATE_INTERVAL = 30 # seconds + + def __init__(self): + super().__init__() + self._params = Params() + self._session = requests.Session() + self._stats = self._get_stats() + + self._icon_distance = gui_app.texture("icons/road.png", 100, 100, keep_aspect_ratio=True) + self._icon_drives = gui_app.texture("icons_mici/wheel.png", 80, 80, keep_aspect_ratio=True) + self._icon_hours = gui_app.texture("../../sunnypilot/selfdrive/assets/icons/clock.png", 80, 80, keep_aspect_ratio=True) + + self._running = True + self._update_thread = threading.Thread(target=self._update_loop, daemon=True) + self._update_thread.start() + + def __del__(self): + self._running = False + try: + if self._update_thread and self._update_thread.is_alive(): + self._update_thread.join(timeout=1.0) + except Exception: + pass + + def _get_stats(self): + stats = self._params.get(self.PARAM_KEY) + if not stats: + return {} + try: + return stats + except Exception: + cloudlog.exception(f"Failed to decode drive stats: {stats}") + return {} + + def _fetch_drive_stats(self): + try: + dongle_id = self._params.get("DongleId") + if not dongle_id or dongle_id == UNREGISTERED_DONGLE_ID: + return + identity_token = get_token(dongle_id) + response = api_get(f"v1.1/devices/{dongle_id}/stats", access_token=identity_token, session=self._session) + if response.status_code == 200: + data = response.json() + self._stats = data + self._params.put(self.PARAM_KEY, data) + except Exception as e: + cloudlog.error(f"Failed to fetch drive stats: {e}") + + def _update_loop(self): + while self._running: + if not ui_state.started and device._awake: + self._fetch_drive_stats() + time.sleep(self.UPDATE_INTERVAL) + + def _render_stat_group(self, x, y, width, height, title, data, is_metric): + # Card Background + rl.draw_rectangle_rounded(rl.Rectangle(x, y, width, height), 0.05, 10, rl.Color(30, 30, 30, 255)) + + # Title + title_font = gui_app.font(FontWeight.BOLD) + rl.draw_text_ex(title_font, title, rl.Vector2(x + 60, y + 30), 50 * FONT_SCALE, 0, rl.Color(200, 200, 200, 255)) + + # Internal content area + # Center the content block (Icon + Value + Unit) vertically + content_y = y + (height / 2) - (140 * FONT_SCALE) + col_width = width / 3 + + # Values + number_font = gui_app.font(FontWeight.BOLD) + unit_font = gui_app.font(FontWeight.NORMAL) + number_base_size = 92 + unit_base_size = 55 + number_size = number_base_size * FONT_SCALE + unit_size = unit_base_size * FONT_SCALE + color_unit = rl.Color(160, 160, 160, 255) + + routes = int(data.get("routes", 0)) + distance = data.get("distance", 0) + distance_str = str(int(distance * CV.MPH_TO_KPH)) if is_metric else str(int(distance)) + hours = int(data.get("minutes", 0) / 60) + + dist_unit = tr("KM") if is_metric else tr("Miles") + + def draw_col(col_idx, icon, value, unit): + col_x = x + (col_width * col_idx) + center_x = col_x + (col_width / 2) + + # Icon + icon_x = center_x - (icon.width / 2) + icon_y = content_y + 60 + rl.draw_texture_ex(icon, rl.Vector2(icon_x, icon_y), 0.0, 1.0, rl.WHITE) + + # Value + val_size = measure_text_cached(number_font, value, number_base_size) + rl.draw_text_ex(number_font, value, rl.Vector2(center_x - val_size.x / 1.65, content_y + 145 * FONT_SCALE), number_size, 0, rl.WHITE) + + # Unit + unit_size_vec = measure_text_cached(unit_font, unit, unit_base_size) + rl.draw_text_ex(unit_font, unit, rl.Vector2(center_x - unit_size_vec.x / 1.65, content_y + 255 * FONT_SCALE), unit_size, 0, color_unit) + + draw_col(0, self._icon_drives, str(routes), tr("Drives")) + draw_col(1, self._icon_distance, distance_str, dist_unit) + draw_col(2, self._icon_hours, str(hours), tr("Hours")) + + return y + height + + def _render(self, rect: rl.Rectangle): + x = rect.x + y = rect.y + w = rect.width + + spacing = 30 + available_h = rect.height - 30 + card_height = available_h / 2 + + is_metric = self._params.get_bool("IsMetric") + + all_time = self._stats.get("all", {}) + week = self._stats.get("week", {}) + + y = self._render_stat_group(x, y, w, card_height, tr("ALL TIME"), all_time, is_metric) + y += spacing + y = self._render_stat_group(x, y, w, card_height, tr("PAST WEEK"), week, is_metric) diff --git a/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/__init__.py b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/__init__.py new file mode 100644 index 0000000000..d8fdd61e72 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/__init__.py @@ -0,0 +1,67 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.list_view import ButtonAction +from openpilot.system.ui.widgets.scroller_tici import Scroller + +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.vehicle.brands.factory import BrandSettingsFactory +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.vehicle.platform_selector import PlatformSelector, LegendWidget +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.ui.sunnypilot.widgets.list_view import ListItemSP + + +class VehicleLayout(Widget): + def __init__(self): + super().__init__() + self._brand_settings = None + self._brand_items = [] + self._current_brand = None + self._platform_selector = PlatformSelector(self._update_brand_settings) + + self._vehicle_item = ListItemSP(title=self._platform_selector.text, action_item=ButtonAction(text=tr("SELECT")), + callback=self._platform_selector._on_clicked) + self._vehicle_item.title_color = self._platform_selector.color + self._legend_widget = LegendWidget(self._platform_selector) + + self.items = [self._vehicle_item, self._legend_widget] + self._scroller = Scroller(self.items, line_separator=True, spacing=0) + + @staticmethod + def get_brand(): + if bundle := ui_state.params.get("CarPlatformBundle"): + return bundle.get("brand", "") + elif ui_state.CP is not None and ui_state.CP.carFingerprint != "MOCK": + return ui_state.CP.brand + return "" + + def _update_brand_settings(self): + self._vehicle_item._title = self._platform_selector.text + self._vehicle_item.title_color = self._platform_selector.color + vehicle_text = tr("REMOVE") if ui_state.params.get("CarPlatformBundle") else tr("SELECT") + self._vehicle_item.action_item.set_text(vehicle_text) + + brand = self.get_brand() + if brand != self._current_brand: + self._current_brand = brand + self._brand_settings = BrandSettingsFactory.create_brand_settings(brand) + self._brand_items = self._brand_settings.items if self._brand_settings else [] + + self.items = [self._vehicle_item, self._legend_widget] + self._brand_items + self._scroller = Scroller(self.items, line_separator=True, spacing=0) + + def _update_state(self): + self._update_brand_settings() + if self._brand_settings: + self._brand_settings.update_settings() + self._platform_selector.refresh() + + def _render(self, rect): + self._scroller.render(rect) + + def show_event(self): + self._scroller.show_event() diff --git a/sunnypilot/__init__.py b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/__init__.py similarity index 100% rename from sunnypilot/__init__.py rename to openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/__init__.py diff --git a/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/base.py b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/base.py new file mode 100644 index 0000000000..8d83fdf916 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/base.py @@ -0,0 +1,16 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import abc + + +class BrandSettings(abc.ABC): + def __init__(self): + self.items = [] + + @abc.abstractmethod + def update_settings(self) -> None: + """Update the settings based on the current vehicle brand.""" diff --git a/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/body.py b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/body.py new file mode 100644 index 0000000000..d1c9ea5d64 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/body.py @@ -0,0 +1,15 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.vehicle.brands.base import BrandSettings + + +class BodySettings(BrandSettings): + def __init__(self): + super().__init__() + + def update_settings(self): + pass diff --git a/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/chrysler.py b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/chrysler.py new file mode 100644 index 0000000000..ad62dba56f --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/chrysler.py @@ -0,0 +1,15 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.vehicle.brands.base import BrandSettings + + +class ChryslerSettings(BrandSettings): + def __init__(self): + super().__init__() + + def update_settings(self): + pass diff --git a/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/factory.py b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/factory.py new file mode 100644 index 0000000000..678732296f --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/factory.py @@ -0,0 +1,45 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.vehicle.brands.base import BrandSettings +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.vehicle.brands.body import BodySettings +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.vehicle.brands.chrysler import ChryslerSettings +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.vehicle.brands.ford import FordSettings +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.vehicle.brands.gm import GMSettings +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.vehicle.brands.honda import HondaSettings +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.vehicle.brands.hyundai import HyundaiSettings +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.vehicle.brands.mazda import MazdaSettings +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.vehicle.brands.nissan import NissanSettings +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.vehicle.brands.psa import PSASettings +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.vehicle.brands.rivian import RivianSettings +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.vehicle.brands.subaru import SubaruSettings +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.vehicle.brands.tesla import TeslaSettings +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.vehicle.brands.toyota import ToyotaSettings +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.vehicle.brands.volkswagen import VolkswagenSettings + + +class BrandSettingsFactory: + _BRAND_MAP: dict[str, type[BrandSettings]] = { + "body": BodySettings, + "chrysler": ChryslerSettings, + "ford": FordSettings, + "gm": GMSettings, + "honda": HondaSettings, + "hyundai": HyundaiSettings, + "mazda": MazdaSettings, + "nissan": NissanSettings, + "psa": PSASettings, + "rivian": RivianSettings, + "subaru": SubaruSettings, + "tesla": TeslaSettings, + "toyota": ToyotaSettings, + "volkswagen": VolkswagenSettings, + } + + @staticmethod + def create_brand_settings(brand: str) -> BrandSettings | None: + cls = BrandSettingsFactory._BRAND_MAP.get(brand) + return cls() if cls is not None else None diff --git a/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/ford.py b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/ford.py new file mode 100644 index 0000000000..8871087e03 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/ford.py @@ -0,0 +1,15 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.vehicle.brands.base import BrandSettings + + +class FordSettings(BrandSettings): + def __init__(self): + super().__init__() + + def update_settings(self): + pass diff --git a/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/gm.py b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/gm.py new file mode 100644 index 0000000000..edcd17cdb8 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/gm.py @@ -0,0 +1,15 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.vehicle.brands.base import BrandSettings + + +class GMSettings(BrandSettings): + def __init__(self): + super().__init__() + + def update_settings(self): + pass diff --git a/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/honda.py b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/honda.py new file mode 100644 index 0000000000..fec68795a6 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/honda.py @@ -0,0 +1,15 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.vehicle.brands.base import BrandSettings + + +class HondaSettings(BrandSettings): + def __init__(self): + super().__init__() + + def update_settings(self): + pass diff --git a/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/hyundai.py b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/hyundai.py new file mode 100644 index 0000000000..20c9903a63 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/hyundai.py @@ -0,0 +1,59 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.vehicle.brands.base import BrandSettings +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.sunnypilot.widgets.list_view import multiple_button_item_sp +from opendbc.car.hyundai.values import CAR, UNSUPPORTED_LONGITUDINAL_CAR + + +class HyundaiSettings(BrandSettings): + def __init__(self): + super().__init__() + self.alpha_long_available = False + + tuning_texts = [tr("Off"), tr("Dynamic"), tr("Predictive")] + self.longitudinal_tuning_item = multiple_button_item_sp(tr("Custom Longitudinal Tuning"), "", tuning_texts, + button_width=300, callback=self._on_tuning_selected, + param="HyundaiLongitudinalTuning", inline=False) + self.items = [self.longitudinal_tuning_item] + + @staticmethod + def _on_tuning_selected(index): + ui_state.params.put("HyundaiLongitudinalTuning", index) + + def update_settings(self): + self.alpha_long_available = False + bundle = ui_state.params.get("CarPlatformBundle") + if bundle: + platform = bundle.get("platform") + self.alpha_long_available = CAR[platform] not in set().union(*UNSUPPORTED_LONGITUDINAL_CAR.values()) + elif ui_state.CP is not None: + self.alpha_long_available = ui_state.CP.alphaLongitudinalAvailable + + tuning_param = int(ui_state.params.get("HyundaiLongitudinalTuning") or "0") + long_enabled = ui_state.has_longitudinal_control + + long_tuning_descs = [ + tr("Your vehicle will use the Default longitudinal tuning."), + tr("Your vehicle will use the Dynamic longitudinal tuning."), + tr("Your vehicle will use the Predictive longitudinal tuning."), + ] + long_tuning_desc = long_tuning_descs[tuning_param] if tuning_param < len(long_tuning_descs) else long_tuning_descs[0] + + longitudinal_tuning_disabled = not ui_state.is_offroad() or not long_enabled + if longitudinal_tuning_disabled: + if not ui_state.is_offroad(): + long_tuning_desc = tr("This feature is unavailable while the car is onroad.") + elif not long_enabled: + long_tuning_desc = tr("This feature is unavailable because sunnypilot Longitudinal Control (Alpha) is not enabled.") + + self.longitudinal_tuning_item.action_item.set_enabled(not longitudinal_tuning_disabled) + self.longitudinal_tuning_item.set_description(long_tuning_desc) + self.longitudinal_tuning_item.show_description(True) + self.longitudinal_tuning_item.action_item.set_selected_button(tuning_param) + self.longitudinal_tuning_item.set_visible(self.alpha_long_available) diff --git a/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/mazda.py b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/mazda.py new file mode 100644 index 0000000000..d354f0f34b --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/mazda.py @@ -0,0 +1,15 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.vehicle.brands.base import BrandSettings + + +class MazdaSettings(BrandSettings): + def __init__(self): + super().__init__() + + def update_settings(self): + pass diff --git a/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/nissan.py b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/nissan.py new file mode 100644 index 0000000000..7b3446a1a7 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/nissan.py @@ -0,0 +1,15 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.vehicle.brands.base import BrandSettings + + +class NissanSettings(BrandSettings): + def __init__(self): + super().__init__() + + def update_settings(self): + pass diff --git a/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/psa.py b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/psa.py new file mode 100644 index 0000000000..6b767d332a --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/psa.py @@ -0,0 +1,15 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.vehicle.brands.base import BrandSettings + + +class PSASettings(BrandSettings): + def __init__(self): + super().__init__() + + def update_settings(self): + pass diff --git a/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/rivian.py b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/rivian.py new file mode 100644 index 0000000000..876aa2d2ea --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/rivian.py @@ -0,0 +1,15 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.vehicle.brands.base import BrandSettings + + +class RivianSettings(BrandSettings): + def __init__(self): + super().__init__() + + def update_settings(self): + pass diff --git a/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/subaru.py b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/subaru.py new file mode 100644 index 0000000000..5ef53a0e43 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/subaru.py @@ -0,0 +1,54 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.vehicle.brands.base import BrandSettings +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.sunnypilot.widgets.list_view import toggle_item_sp +from opendbc.car.subaru.values import CAR, SubaruFlags + + +class SubaruSettings(BrandSettings): + def __init__(self): + super().__init__() + self.has_stop_and_go = False + + self.stop_and_go_toggle = toggle_item_sp(tr("Stop and Go (Beta)"), "", param="SubaruStopAndGo", callback=self._on_toggle_changed) + + self.stop_and_go_manual_parking_brake_toggle = toggle_item_sp(tr("Stop and Go for Manual Parking Brake (Beta)"), "", + param="SubaruStopAndGoManualParkingBrake", callback=self._on_toggle_changed) + + self.items = [self.stop_and_go_toggle, self.stop_and_go_manual_parking_brake_toggle] + + def _on_toggle_changed(self, _): + self.update_settings() + + def stop_and_go_disabled_msg(self): + if not self.has_stop_and_go: + return tr("This feature is currently not available on this platform.") + elif not ui_state.is_offroad(): + return tr("Enable \"Always Offroad\" in Device panel, or turn vehicle off to toggle.") + return "" + + def update_settings(self): + bundle = ui_state.params.get("CarPlatformBundle") + if bundle: + platform = bundle.get("platform") + config = CAR[platform].config + self.has_stop_and_go = not (config.flags & (SubaruFlags.GLOBAL_GEN2 | SubaruFlags.HYBRID)) + elif ui_state.CP is not None: + self.has_stop_and_go = not (ui_state.CP.flags & (SubaruFlags.GLOBAL_GEN2 | SubaruFlags.HYBRID)) + + disabled_msg = self.stop_and_go_disabled_msg() + descriptions = [ + tr("Experimental feature to enable auto-resume during stop-and-go for certain supported Subaru platforms."), + tr("Experimental feature to enable stop and go for Subaru Global models with manual handbrake. " + + "Models with electric parking brake should keep this disabled. Thanks to martinl for this implementation!") + ] + + for toggle, desc in zip([self.stop_and_go_toggle, self.stop_and_go_manual_parking_brake_toggle], descriptions, strict=True): + toggle.action_item.set_enabled(self.has_stop_and_go and ui_state.is_offroad()) + toggle.set_description(f"{disabled_msg}

{desc}" if disabled_msg else desc) diff --git a/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/tesla.py b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/tesla.py new file mode 100644 index 0000000000..46d536c651 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/tesla.py @@ -0,0 +1,43 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.vehicle.brands.base import BrandSettings +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.sunnypilot.widgets.list_view import toggle_item_sp + +COOP_STEERING_MIN_KMH = 23 +OEM_STEERING_MIN_KMH = 48 +KM_TO_MILE = 0.621371 + + +class TeslaSettings(BrandSettings): + def __init__(self): + super().__init__() + self.coop_steering_toggle = toggle_item_sp(tr("Cooperative Steering (Beta)"), "", param="TeslaCoopSteering") + self.items = [self.coop_steering_toggle] + + def update_settings(self): + is_metric = ui_state.is_metric + unit = "km/h" if is_metric else "mph" + + display_value_coop = COOP_STEERING_MIN_KMH if is_metric else round(COOP_STEERING_MIN_KMH * KM_TO_MILE) + display_value_oem = OEM_STEERING_MIN_KMH if is_metric else round(OEM_STEERING_MIN_KMH * KM_TO_MILE) + + coop_steering_disabled_msg = tr("Enable \"Always Offroad\" in Device panel, or turn vehicle off to toggle.") + coop_steering_warning = tr(f"Warning: May experience steering oscillations below {display_value_oem} {unit} during turns, " + + "recommend disabling this feature if you experience these.") + coop_steering_desc = ( + f"{coop_steering_warning}

" + + f"{tr('Allows the driver to provide limited steering input while openpilot is engaged.')}
" + + f"{tr(f'Only works above {display_value_coop} {unit}.')}" + ) + + if not ui_state.is_offroad(): + coop_steering_desc = f"{coop_steering_disabled_msg}

{coop_steering_desc}" + + self.coop_steering_toggle.set_description(coop_steering_desc) + self.coop_steering_toggle.action_item.set_enabled(ui_state.is_offroad()) diff --git a/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/toyota.py b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/toyota.py new file mode 100644 index 0000000000..5a696466b1 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/toyota.py @@ -0,0 +1,121 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.vehicle.brands.base import BrandSettings +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.lib.multilang import tr, tr_noop +from openpilot.system.ui.widgets import DialogResult +from openpilot.system.ui.widgets.confirm_dialog import ConfirmDialog +from openpilot.system.ui.sunnypilot.widgets.list_view import toggle_item_sp + + +ONROAD_ONLY_DESCRIPTION = tr_noop("Start the vehicle to check vehicle compatibility.") +SNG_HACK_UNAVAILABLE = tr_noop("sunnypilot Longitudinal Control must be available and enabled for your vehicle to use this feature.") + +DESCRIPTIONS = { + 'enforce_stock_longitudinal': tr_noop( + 'sunnypilot will not take over control of gas and brakes. Factory Toyota longitudinal control will be used.' + ), + 'stop_and_go_hack': tr_noop( + 'sunnypilot will allow some Toyota/Lexus cars to auto resume during stop and go traffic. ' + + 'This feature is only applicable to certain models that are able to use longitudinal control. This is an alpha feature. Use at your own risk.' + ) +} + + +class ToyotaSettings(BrandSettings): + def __init__(self): + super().__init__() + + self.enforce_stock_longitudinal = toggle_item_sp( + lambda: tr("Enforce Factory Longitudinal Control"), + description=lambda: tr(DESCRIPTIONS["enforce_stock_longitudinal"]), + initial_state=ui_state.params.get_bool("ToyotaEnforceStockLongitudinal"), + callback=self._on_enable_enforce_stock_longitudinal, + enabled=lambda: not ui_state.engaged, + ) + + self.stop_and_go_hack = toggle_item_sp( + lambda: tr("Stop and Go Hack (Alpha)"), + description=lambda: tr(DESCRIPTIONS["stop_and_go_hack"]), + initial_state=ui_state.params.get_bool("ToyotaStopAndGoHack"), + callback=self._on_enable_stop_and_go_hack, + enabled=lambda: not ui_state.engaged, + ) + + self.items = [ + self.enforce_stock_longitudinal, + self.stop_and_go_hack, + ] + + def _on_enable_enforce_stock_longitudinal(self, state: bool): + if state: + def confirm_callback(result: int): + if result == DialogResult.CONFIRM: + ui_state.params.put_bool("ToyotaEnforceStockLongitudinal", True) + if ui_state.params.get_bool("AlphaLongitudinalEnabled"): + ui_state.params.put_bool("AlphaLongitudinalEnabled", False) + ui_state.params.put_bool("ToyotaStopAndGoHack", False) + self.stop_and_go_hack.action_item.set_state(False) + ui_state.params.put_bool("OnroadCycleRequested", True) + else: + self.enforce_stock_longitudinal.action_item.set_state(False) + + content = (f"

{self.enforce_stock_longitudinal.title}


" + + f"

{self.enforce_stock_longitudinal.description}

") + + dlg = ConfirmDialog(content, tr("Enable"), rich=True, callback=confirm_callback) + gui_app.push_widget(dlg) + + else: + ui_state.params.put_bool("ToyotaEnforceStockLongitudinal", False) + ui_state.params.put_bool("OnroadCycleRequested", True) + + def _on_enable_stop_and_go_hack(self, state: bool): + if state: + def confirm_callback(result: int): + if result == DialogResult.CONFIRM: + ui_state.params.put_bool("ToyotaStopAndGoHack", True) + ui_state.params.put_bool("OnroadCycleRequested", True) + else: + self.stop_and_go_hack.action_item.set_state(False) + + content = (f"

{self.stop_and_go_hack.title}


" + + f"

{self.stop_and_go_hack.description}

") + + dlg = ConfirmDialog(content, tr("Enable"), rich=True, callback=confirm_callback) + gui_app.push_widget(dlg) + + else: + ui_state.params.put_bool("ToyotaStopAndGoHack", False) + ui_state.params.put_bool("OnroadCycleRequested", True) + + def update_settings(self): + if ui_state.CP is not None: + longitudinal = ui_state.CP.openpilotLongitudinalControl + enforce_stock = self.enforce_stock_longitudinal.action_item.get_state() + + if longitudinal and not enforce_stock: + self.stop_and_go_hack.action_item.set_enabled(not ui_state.engaged) + new_desc = tr(DESCRIPTIONS["stop_and_go_hack"]) + show_desc = False + else: + self.stop_and_go_hack.action_item.set_enabled(False) + self.stop_and_go_hack.action_item.set_state(False) + new_desc = "" + tr(SNG_HACK_UNAVAILABLE) + "\n\n" + tr(DESCRIPTIONS["stop_and_go_hack"]) + show_desc = True + + if self.stop_and_go_hack.description != new_desc: + self.stop_and_go_hack.set_description(new_desc) + if show_desc: + self.stop_and_go_hack.show_description(True) + else: + self.stop_and_go_hack.action_item.set_enabled(False) + new_desc = "" + tr(ONROAD_ONLY_DESCRIPTION) + "\n\n" + tr(DESCRIPTIONS["stop_and_go_hack"]) + if self.stop_and_go_hack.description != new_desc: + self.stop_and_go_hack.set_description(new_desc) + self.stop_and_go_hack.show_description(True) diff --git a/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/volkswagen.py b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/volkswagen.py new file mode 100644 index 0000000000..a6d44c5e4d --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/brands/volkswagen.py @@ -0,0 +1,15 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.vehicle.brands.base import BrandSettings + + +class VolkswagenSettings(BrandSettings): + def __init__(self): + super().__init__() + + def update_settings(self): + pass diff --git a/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/platform_selector.py b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/platform_selector.py new file mode 100644 index 0000000000..aab935d4b8 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/vehicle/platform_selector.py @@ -0,0 +1,137 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import json +import os +import pyray as rl +from collections.abc import Callable +from functools import partial + +from openpilot.common.basedir import BASEDIR +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.widgets import DialogResult, Widget +from openpilot.system.ui.widgets.button import Button, ButtonStyle +from openpilot.system.ui.widgets.confirm_dialog import ConfirmDialog + +from openpilot.system.ui.sunnypilot.lib.styles import style +from openpilot.system.ui.sunnypilot.widgets.tree_dialog import TreeOptionDialog, TreeNode, TreeFolder +from openpilot.selfdrive.ui.ui_state import ui_state + +CAR_LIST_JSON_OUT = os.path.join(BASEDIR, "openpilot", "sunnypilot", "selfdrive", "car", "car_list.json") + + +class LegendWidget(Widget): + def __init__(self, platform_selector): + super().__init__() + self.set_rect(rl.Rectangle(0, 0, 0, 350)) + self._platform_selector = platform_selector + self._font = gui_app.font(FontWeight.NORMAL) + self._bold_font = gui_app.font(FontWeight.BOLD) + + def _render(self, rect): + x = rect.x + 20 + y = rect.y + 20 + rl.draw_text_ex(self._font, tr("Select vehicle to force fingerprint manually."), rl.Vector2(x, y), 40, 0, style.ITEM_DESC_TEXT_COLOR) + y += 80 + rl.draw_text_ex(self._font, tr("Colors represent vehicle fingerprint status:"), rl.Vector2(x, y), 40, 0, style.ITEM_DESC_TEXT_COLOR) + y += 80 + + items = [ + (style.GREEN, tr("Fingerprinted automatically")), + (style.BLUE, tr("Manually selected fingerprint")), + (style.YELLOW, tr("Not fingerprinted or manually selected")), + ] + for color, text in items: + p_color = self._platform_selector.color + is_active = p_color.r == color.r and p_color.g == color.g and p_color.b == color.b and p_color.a == color.a + rl.draw_rectangle(int(x), int(y + 5), 30, 30, color) + font = self._bold_font if is_active else self._font + text_color = rl.WHITE if is_active else style.ITEM_DESC_TEXT_COLOR + rl.draw_text_ex(font, f"- {text}", rl.Vector2(x + 50, y - 7), 40, 0, text_color) + y += 50 + + +class PlatformSelector(Button): + def __init__(self, on_platform_change: Callable[[], None] | None = None): + super().__init__(tr("Vehicle"), self._on_clicked, button_style=ButtonStyle.NORMAL) + self.set_rect(rl.Rectangle(0, 0, 0, 120)) + + with open(CAR_LIST_JSON_OUT) as car_list_json: + self._platforms = json.load(car_list_json) + + self._on_platform_change = on_platform_change + self.refresh() + + @property + def text(self): + return self._label._text + + def set_parent_rect(self, parent_rect): + super().set_parent_rect(parent_rect) + self._rect.width = parent_rect.width + + def _on_clicked(self): + if ui_state.params.get("CarPlatformBundle"): + ui_state.params.remove("CarPlatformBundle") + self.refresh() + if self._on_platform_change: + self._on_platform_change() + else: + self._show_platform_dialog() + + def _set_platform(self, platform_name): + if data := self._platforms.get(platform_name): + ui_state.params.put("CarPlatformBundle", {**data, "name": platform_name}) + self.refresh() + if self._on_platform_change: + self._on_platform_change() + + def _on_platform_selected(self, dialog, res): + if res == DialogResult.CONFIRM and dialog.selection_ref: + offroad_msg = tr("This setting will take effect immediately.") if ui_state.is_offroad else \ + tr("This setting will take effect once the device enters offroad state.") + + callback = partial(self._confirm_platform, dialog.selection_ref) + confirm_dialog = ConfirmDialog(offroad_msg, tr("Confirm"), callback=callback) + gui_app.push_widget(confirm_dialog) + + def _confirm_platform(self, platform_name, res): + if res == DialogResult.CONFIRM: + self._set_platform(platform_name) + + def _show_platform_dialog(self): + platforms = sorted(self._platforms.keys()) + makes = sorted({self._platforms[p].get('make') for p in platforms}) + folders = [TreeFolder(make, [TreeNode(p, { + 'display_name': p, + 'search_tags': f"{p} {self._platforms[p].get('make')} {' '.join(map(str, self._platforms[p].get('year', [])))} {self._platforms[p].get('model', p)}" + }) for p in platforms if self._platforms[p].get('make') == make]) for make in makes] + dialog = TreeOptionDialog( + tr("Select a vehicle"), + folders, + search_title=tr("Search your vehicle"), + search_subtitle=tr("Enter model year (e.g., 2021) and model (Toyota Corolla):"), + search_funcs=[lambda node: node.data.get('display_name', ''), lambda node: node.data.get('search_tags', '')] + ) + callback = partial(self._on_platform_selected, dialog) + dialog.on_exit = callback + gui_app.push_widget(dialog) + + def refresh(self): + self.color = style.YELLOW + self._platform = tr("Unrecognized Vehicle") + self.set_text(tr("No vehicle selected")) + + if bundle := ui_state.params.get("CarPlatformBundle"): + self._platform = bundle.get("name", "") + self.set_text(self._platform) + self.color = style.BLUE + elif ui_state.CP is not None and ui_state.CP.carFingerprint != "MOCK": + self._platform = ui_state.CP.carFingerprint + self.set_text(self._platform) + self.color = style.GREEN + self.set_enabled(True) diff --git a/openpilot/selfdrive/ui/sunnypilot/layouts/settings/visuals.py b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/visuals.py new file mode 100644 index 0000000000..84be5a26ab --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/layouts/settings/visuals.py @@ -0,0 +1,154 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from openpilot.common.params import Params +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.ui.lib.multilang import tr, tr_noop +from openpilot.system.ui.sunnypilot.widgets.list_view import toggle_item_sp, multiple_button_item_sp +from openpilot.system.ui.widgets.scroller_tici import Scroller +from openpilot.system.ui.widgets import Widget + +CHEVRON_INFO_DESCRIPTION = { + "enabled": tr_noop("Display useful metrics below the chevron that tracks the lead car " + + "only applicable to cars with sunnypilot longitudinal control."), + "disabled": tr_noop("This feature requires sunnypilot longitudinal control to be available.") +} + + +class VisualsLayout(Widget): + def __init__(self): + super().__init__() + + self._params = Params() + items = self._initialize_items() + self._scroller = Scroller(items, line_separator=True, spacing=0) + + def _initialize_items(self): + self._toggle_defs = { + "BlindSpot": ( + lambda: tr("Show Blind Spot Warnings"), + tr("Enabling this will display warnings when a vehicle is detected in your " + + "blind spot as long as your car has BSM supported."), + None, + ), + "TorqueBar": ( + lambda: tr("Steering Arc"), + tr("Display steering arc on the driving screen when lateral control is enabled."), + None, + ), + "RainbowMode": ( + lambda: tr("Enable Tesla Rainbow Mode"), + tr("A beautiful rainbow effect on the path the model wants to take. " + + "It does not affect driving in any way."), + None, + ), + "StandstillTimer": ( + lambda: tr("Enable Standstill Timer"), + tr("Show a timer on the HUD when the car is at a standstill."), + None, + ), + "RoadNameToggle": ( + lambda: tr("Display Road Name"), + tr("Displays the name of the road the car is traveling on." + + "
The OpenStreetMap database of the location must be downloaded from " + + "the OSM panel to fetch the road name."), + None, + ), + "GreenLightAlert": ( + lambda: tr("Green Traffic Light Alert (Beta)"), + tr("A chime and on-screen alert will play when the traffic light you are waiting for " + + "turns green and you have no vehicle in front of you." + + "
Note: This chime is only designed as a notification. " + + "It is the driver's responsibility to observe their environment and make decisions accordingly."), + None, + ), + "LeadDepartAlert": ( + lambda: tr("Lead Departure Alert (Beta)"), + tr("A chime and on-screen alert will play when you are stopped, and the vehicle in front of you start moving." + + "
Note: This chime is only designed as a notification. " + + "It is the driver's responsibility to observe their environment and make decisions accordingly."), + None, + ), + "TrueVEgoUI": ( + lambda: tr("Speedometer: Always Display True Speed"), + tr("For applicable vehicles, always display the true vehicle current speed from wheel speed sensors."), + None, + ), + "HideVEgoUI": ( + lambda: tr("Speedometer: Hide from Onroad Screen"), + tr("When enabled, the speedometer on the onroad screen is not displayed."), + None, + ), + "ShowTurnSignals": ( + lambda: tr("Display Turn Signals"), + tr("When enabled, visual turn indicators are drawn on the HUD."), + None, + ), + "RocketFuel": ( + lambda: tr("Real-time Acceleration Bar"), + tr("Show an indicator on the left side of the screen to display real-time vehicle acceleration and deceleration. " + + "This displays what the car is currently doing, not what the planner is requesting."), + None, + ), + } + self._toggles = {} + for param, (title, desc, callback) in self._toggle_defs.items(): + toggle = toggle_item_sp( + title=title, + description=desc, + param=param, + initial_state=ui_state.params.get_bool(param), + callback=callback, + ) + self._toggles[param] = toggle + + self._chevron_info = multiple_button_item_sp( + title=lambda: tr("Display Metrics Below Chevron"), + description="", + buttons=[lambda: tr("Off"), lambda: tr("Distance"), lambda: tr("Speed"), lambda: tr("Time"), lambda: tr("All")], + param="ChevronInfo", + inline=False + ) + self._dev_ui_info = multiple_button_item_sp( + title=lambda: tr("Developer UI"), + description=lambda: tr("Display real-time parameters and metrics from various sources."), + buttons=[lambda: tr("Off"), lambda: tr("Bottom"), lambda: tr("Right"), lambda: tr("Right & Bottom")], + param="DevUIInfo", + button_width=350, + inline=False + ) + + items = list(self._toggles.values()) + [ + self._chevron_info, + self._dev_ui_info, + ] + return items + + def _update_state(self): + super()._update_state() + + for param in self._toggle_defs: + self._toggles[param].action_item.set_state(self._params.get_bool(param)) + + self._dev_ui_info.action_item.set_selected_button(ui_state.params.get("DevUIInfo", return_default=True)) + + if ui_state.has_longitudinal_control: + self._chevron_info.set_description(tr(CHEVRON_INFO_DESCRIPTION["enabled"])) + self._chevron_info.action_item.set_selected_button(ui_state.params.get("ChevronInfo", return_default=True)) + self._chevron_info.action_item.set_enabled(True) + else: + self._chevron_info.set_description(tr(CHEVRON_INFO_DESCRIPTION["disabled"])) + self._chevron_info.action_item.set_enabled(False) + ui_state.params.put("ChevronInfo", 0) + + def _render(self, rect): + self._scroller.render(rect) + + def show_event(self): + self._scroller.show_event() + if not ui_state.has_longitudinal_control: + self._chevron_info.set_description(tr(CHEVRON_INFO_DESCRIPTION["disabled"])) + self._chevron_info.show_description(True) diff --git a/openpilot/selfdrive/ui/sunnypilot/layouts/sidebar.py b/openpilot/selfdrive/ui/sunnypilot/layouts/sidebar.py new file mode 100644 index 0000000000..79bb15dbb8 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/layouts/sidebar.py @@ -0,0 +1,87 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import pyray as rl +import time +from dataclasses import dataclass +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.sunnypilot.sunnylink.api import UNREGISTERED_SUNNYLINK_DONGLE_ID +from openpilot.system.ui.lib.multilang import tr_noop + + +PING_TIMEOUT_NS = 80_000_000_000 # 80 seconds in nanoseconds +METRIC_HEIGHT = 126 +METRIC_MARGIN = 30 +METRIC_START_Y = 300 +HOME_BTN = rl.Rectangle(60, 860, 180, 180) + + +# Color scheme +class Colors: + WHITE = rl.WHITE + WHITE_DIM = rl.Color(255, 255, 255, 85) + GRAY = rl.Color(84, 84, 84, 255) + + # Status colors + GOOD = rl.WHITE + WARNING = rl.Color(218, 202, 37, 255) + DANGER = rl.Color(201, 34, 49, 255) + PROGRESS = rl.Color(0, 134, 233, 255) + DISABLED = rl.Color(128, 128, 128, 255) + + # UI elements + METRIC_BORDER = rl.Color(255, 255, 255, 85) + BUTTON_NORMAL = rl.WHITE + BUTTON_PRESSED = rl.Color(255, 255, 255, 166) + + +@dataclass(slots=True) +class MetricData: + label: str + value: str + color: rl.Color + + def update(self, label: str, value: str, color: rl.Color): + self.label = label + self.value = value + self.color = color + + +class SidebarSP: + def __init__(self): + self._sunnylink_status = MetricData(tr_noop("SUNNYLINK"), tr_noop("OFFLINE"), Colors.WARNING) + + def _update_sunnylink_status(self): + if not ui_state.params.get_bool("SunnylinkEnabled"): + self._sunnylink_status.update(tr_noop("SUNNYLINK"), tr_noop("DISABLED"), Colors.DISABLED) + return + + last_ping = ui_state.params.get("LastSunnylinkPingTime") or 0 + dongle_id = ui_state.params.get("SunnylinkDongleId") + + is_online = last_ping and (time.monotonic_ns() - last_ping) < PING_TIMEOUT_NS + is_temp_fault = ui_state.params.get_bool("SunnylinkTempFault") + is_registering = not is_temp_fault and dongle_id in (None, "", UNREGISTERED_SUNNYLINK_DONGLE_ID) + + # Determine status/color pair based on priority + if last_ping: + status, color = (tr_noop("ONLINE"), Colors.GOOD) if is_online else (tr_noop("ERROR"), Colors.DANGER) + elif is_temp_fault: + status, color = (tr_noop("FAULT"), Colors.WARNING) + elif is_registering: + status, color = (tr_noop("REGIST..."), Colors.PROGRESS) + else: + status, color = (tr_noop("OFFLINE"), Colors.DANGER) + + self._sunnylink_status.update(tr_noop("SUNNYLINK"), status, color) + + def _draw_metrics_w_sunnylink(self, rect: rl.Rectangle, _temp, _panda, _connect): + metrics = [_temp, _panda, _connect, self._sunnylink_status] + start_y = int(rect.y) + METRIC_START_Y + available_height = max(0, int(HOME_BTN.y) - METRIC_MARGIN - METRIC_HEIGHT - start_y) + spacing = available_height / max(1, len(metrics) - 1) + + return metrics, start_y, spacing diff --git a/sunnypilot/mapd/__init__.py b/openpilot/selfdrive/ui/sunnypilot/mici/__init__.py similarity index 100% rename from sunnypilot/mapd/__init__.py rename to openpilot/selfdrive/ui/sunnypilot/mici/__init__.py diff --git a/sunnypilot/modeld/__init__.py b/openpilot/selfdrive/ui/sunnypilot/mici/layouts/__init__.py similarity index 100% rename from sunnypilot/modeld/__init__.py rename to openpilot/selfdrive/ui/sunnypilot/mici/layouts/__init__.py diff --git a/openpilot/selfdrive/ui/sunnypilot/mici/layouts/models.py b/openpilot/selfdrive/ui/sunnypilot/mici/layouts/models.py new file mode 100644 index 0000000000..8999281430 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/mici/layouts/models.py @@ -0,0 +1,202 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from collections.abc import Callable +import pyray as rl + +from openpilot.cereal import custom +from openpilot.sunnypilot.models.default_model import DEFAULT_MODEL +from openpilot.selfdrive.ui.mici.widgets.button import BigButton +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.models import ModelsLayout +from openpilot.selfdrive.ui.ui_state import ui_state, device +from openpilot.system.ui.lib.application import FontWeight, gui_app +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.label import UnifiedLabel +from openpilot.system.ui.widgets.scroller import NavScroller + +class CurrentModelInfo(Widget): + def __init__(self): + super().__init__() + + self.set_rect(rl.Rectangle(0, 0, 360, 180)) + + header_color = rl.Color(255, 255, 255, int(255 * 0.9)) + subheader_color = rl.Color(255, 255, 255, int(255 * 0.9 * 0.65)) + max_width = int(self._rect.width - 20) + self.current_model_header = UnifiedLabel(tr("active model"), 48, max_width=max_width, text_color=header_color, font_weight=FontWeight.DISPLAY) + default_text = f"{DEFAULT_MODEL} (Default)".lower() + self.current_model_text = UnifiedLabel(default_text, 32, max_width=max_width, text_color=subheader_color, font_weight=FontWeight.ROMAN, scroll=True) + + self.info_header = UnifiedLabel("cache size", 48, max_width=max_width, text_color=header_color, font_weight=FontWeight.DISPLAY) + self.info_text = UnifiedLabel("0 mb", 32, max_width=max_width, text_color=subheader_color, font_weight=FontWeight.ROMAN) + + def _render(self, _): + self.current_model_header.set_position(self._rect.x + 20, self._rect.y - 10) + self.current_model_header.render() + + self.current_model_text.set_position(self._rect.x + 20, self._rect.y + 68 - 25) + self.current_model_text.render() + + self.info_header.set_position(self._rect.x + 20, self._rect.y + 114 - 30) + self.info_header.render() + + self.info_text.set_position(self._rect.x + 20, self._rect.y + 161 - 25) + self.info_text.render() + +class ModelsLayoutMici(NavScroller): + def __init__(self, back_callback: Callable): + super().__init__() + self.set_back_callback(back_callback) + self.original_back_callback = back_callback + self.focused_widget = None + + self.current_model_info = CurrentModelInfo() + self._download_progress = "." + self._download_frame = 0 + self._was_downloading = False + + self.select_model_btn = BigButton(tr("select model")) + self.select_model_btn.set_click_callback(self._show_folders) + + self.cancel_download_btn = BigButton(tr("cancel download")) + self.cancel_download_btn.set_click_callback(lambda: ui_state.params.remove("ModelManager_DownloadIndex")) + + self.main_items = [self.current_model_info, self.select_model_btn, self.cancel_download_btn] + self._scroller.add_widgets(self.main_items) + + @property + def model_manager(self): + return ui_state.sm["modelManagerSP"] + + def _get_grouped_bundles(self, favorites = None): + bundles = self.model_manager.availableBundles + folders = {} + for bundle in bundles: + folder = next((override.value for override in bundle.overrides if override.key == "folder"), "") + folders.setdefault(folder, []).append(bundle) + + if favorites: + for fav_bundle in [bundle for bundle in bundles if bundle.ref in favorites]: + folders.setdefault("favorites", []).append(fav_bundle) + + return folders + + def _show_selection_view(self, items, back_callback: Callable): + self._scroller._items = items + for item in items: + item.set_touch_valid_callback(lambda: self._scroller.scroll_panel.is_touch_valid() and self._scroller.enabled) + self._scroller.scroll_panel.set_offset(0) + self.set_back_callback(back_callback) + + def _show_folders(self): + self.focused_widget = self.select_model_btn + + favs = ui_state.params.get("ModelManager_Favs") + favorites = set(favs.split(';')) if favs else set() + + folders = self._get_grouped_bundles(favorites) + folder_buttons = [] + default_btn = BigButton(f"{DEFAULT_MODEL} (Default)".lower()) + default_btn.set_click_callback(self._select_default) + folder_buttons.append(default_btn) + + for folder in sorted(folders.keys(), key=lambda f: max((bundle.index for bundle in folders[f]), default=-1), reverse=True): + if folder.lower() in ["release models", "master models", "favorites"]: + btn = BigButton(folder.lower()) + btn.set_click_callback(lambda f=folder: self._select_folder(f)) + if folder.lower() == "favorites": + folder_buttons.insert(0, btn) + else: + folder_buttons.append(btn) + self._show_selection_view(folder_buttons, self._reset_main_view) + + def _select_model(self, bundle): + ui_state.params.put("ModelManager_DownloadIndex", bundle.index) + self._reset_main_view() + + def _select_default(self): + ui_state.params.remove("ModelManager_ActiveBundle") + self._reset_main_view() + + def _select_folder(self, folder_name): + favs = ui_state.params.get("ModelManager_Favs") + favorites = set(favs.split(';')) if favs else set() + + folders = self._get_grouped_bundles(favorites) + bundles = sorted(folders.get(folder_name, []), key=lambda b: b.index, reverse=True) + + btns = [] + for bundle in bundles: + txt = bundle.displayName.lower() + btn = BigButton(txt) + btn.set_click_callback(lambda b=bundle: self._select_model(b)) + btns.append(btn) + self._show_selection_view(btns, self._show_folders) + + def _reset_main_view(self): + self._scroller._items = self.main_items # type: ignore[assignment] # ty: ignore[invalid-assignment] + self.set_back_callback(self.original_back_callback) + self._scroller.scroll_panel.set_offset(0) + self._scroller.scroll_to(0) + + def hide_event(self): + super().hide_event() + if self._was_downloading: + device.set_override_interactive_timeout(None) + self._was_downloading = False + + def _update_state(self): + super()._update_state() + + self.select_model_btn.set_enabled(ui_state.is_offroad()) + self.cancel_download_btn.set_visible(False) + self.current_model_info.current_model_header._shimmer = False + self.current_model_info.info_header._shimmer = False + + manager = self.model_manager + self._download_frame += 1 + should_update = self._download_frame % (gui_app.target_fps / 2) == 0 + if should_update: + self._download_progress = self._download_progress + "." if len(self._download_progress) < 3 else "" + + is_downloading = (manager.selectedBundle + and manager.selectedBundle.status == custom.ModelManagerSP.DownloadStatus.downloading) + if self._was_downloading and not is_downloading: + device.set_override_interactive_timeout(None) + self._was_downloading = is_downloading + + self.current_model_info.current_model_header.set_text(tr("active model")) + model_text = manager.activeBundle.displayName.lower() if manager.activeBundle.ref else f"{DEFAULT_MODEL} (Default)".lower() + self.current_model_info.current_model_text.set_text(model_text) + self.current_model_info.info_header.set_text(tr("cache size")) + self.current_model_info.info_text.set_text(f"{ModelsLayout.calculate_cache_size():.2f} MB") + + if manager.selectedBundle and manager.selectedBundle.status == custom.ModelManagerSP.DownloadStatus.failed: + self.current_model_info.info_header.set_text(tr("error") + self._download_progress) + self.current_model_info.info_text.set_text(tr("download failed")) + + elif manager.selectedBundle and manager.selectedBundle.status == custom.ModelManagerSP.DownloadStatus.downloading: + self.cancel_download_btn.set_visible(True) + device.set_override_interactive_timeout(5) + progress = 0.0 + count = 0 + for model in manager.selectedBundle.models: + count += 1 + p = model.artifact.downloadProgress + if p.status == custom.ModelManagerSP.DownloadStatus.downloading: + progress += p.progress + elif p.status in (custom.ModelManagerSP.DownloadStatus.downloaded, + custom.ModelManagerSP.DownloadStatus.cached): + progress += 100.0 + + self.current_model_info.current_model_header.set_text(tr("downloading")) + self.current_model_info.current_model_header._shimmer = True + self.current_model_info.current_model_text.set_text(f"{manager.selectedBundle.internalName.lower()}") + self.current_model_info.info_header.set_text(tr("progress") + self._download_progress) + self.current_model_info.info_header._shimmer = True + self.current_model_info.info_text.set_text(f"{progress/count:.2f}%") + diff --git a/openpilot/selfdrive/ui/sunnypilot/mici/layouts/onboarding.py b/openpilot/selfdrive/ui/sunnypilot/mici/layouts/onboarding.py new file mode 100644 index 0000000000..5aed8fac38 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/mici/layouts/onboarding.py @@ -0,0 +1,34 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from collections.abc import Callable + +from openpilot.selfdrive.ui.mici.widgets.dialog import BigConfirmationCircleButton +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.mici_setup import GreyBigButton +from openpilot.system.ui.widgets.scroller import NavScroller + + +class SunnylinkConsentPage(NavScroller): + def __init__(self, on_accept: Callable | None = None, on_decline: Callable | None = None): + super().__init__() + + assert on_accept is not None and callable(on_accept) + assert on_decline is not None and callable(on_decline) + + self._accept_button = BigConfirmationCircleButton("enable\nsunnylink", gui_app.texture("icons_mici/setup/driver_monitoring/dm_check.png", 64, 64), + on_accept, exit_on_confirm=False) + + self._decline_button = BigConfirmationCircleButton("disable\nsunnylink", gui_app.texture("icons_mici/setup/cancel.png", 64, 64), + on_decline, red=True, exit_on_confirm=False) + + self._scroller.add_widgets([ + GreyBigButton("sunnylink", "scroll to continue", + gui_app.texture("../../sunnypilot/selfdrive/assets/logo.png", 64, 64)), + GreyBigButton("", "sunnylink enables secured remote access to your comma device from anywhere."), + self._accept_button, + self._decline_button, + ]) diff --git a/openpilot/selfdrive/ui/sunnypilot/mici/layouts/settings.py b/openpilot/selfdrive/ui/sunnypilot/mici/layouts/settings.py new file mode 100644 index 0000000000..96a4c789c1 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/mici/layouts/settings.py @@ -0,0 +1,92 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from openpilot.selfdrive.ui.mici.layouts.settings import settings as OP +from openpilot.selfdrive.ui.mici.layouts.settings.settings import SettingsBigButton +from openpilot.selfdrive.ui.mici.layouts.settings.device import DeviceLayoutMici +from openpilot.selfdrive.ui.mici.widgets.button import BigCircleButton +from openpilot.selfdrive.ui.mici.widgets.dialog import BigConfirmationDialog, BigDialog +from openpilot.selfdrive.ui.sunnypilot.mici.layouts.sunnylink import SunnylinkLayoutMici +from openpilot.selfdrive.ui.sunnypilot.mici.layouts.models import ModelsLayoutMici +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.lib.multilang import tr + +ICON_SIZE = 70 +BIG_ICON_SIZE = 110 + + +class SettingsLayoutSP(OP.SettingsLayout): + def __init__(self): + OP.SettingsLayout.__init__(self) + + device_panel = DeviceLayoutMici() + self._scroller._items[2].set_click_callback(lambda: gui_app.push_widget(device_panel)) + + self.icon_offroad_enable = gui_app.texture("../../sunnypilot/selfdrive/assets/icons_mici/always_offroad.png", BIG_ICON_SIZE, + BIG_ICON_SIZE) + self.icon_offroad_disable = gui_app.texture("../../sunnypilot/selfdrive/assets/icons_mici/disable_offroad.png", BIG_ICON_SIZE, + BIG_ICON_SIZE) + self.icon_offroad_slider = gui_app.texture("icons_mici/settings/device/lkas.png", BIG_ICON_SIZE, BIG_ICON_SIZE) + + sunnylink_panel = SunnylinkLayoutMici(back_callback=gui_app.pop_widget) + sunnylink_btn = SettingsBigButton(tr("sunnylink"), "", gui_app.texture("icons_mici/settings/developer/ssh.png", 55, 55)) + sunnylink_btn.set_click_callback(lambda: gui_app.push_widget(sunnylink_panel)) + + models_panel = ModelsLayoutMici(back_callback=gui_app.pop_widget) + models_btn = SettingsBigButton(tr("models"), "", gui_app.texture("../../sunnypilot/selfdrive/assets/offroad/icon_models.png", ICON_SIZE, ICON_SIZE)) + models_btn.set_click_callback(lambda: gui_app.push_widget(models_panel)) + + # onroad: enable button sits at the front (left of toggles) + self._enable_offroad_btn_onroad = BigCircleButton(self.icon_offroad_enable, red=True) + self._enable_offroad_btn_onroad.set_click_callback(lambda: self._handle_always_offroad(True)) + self._enable_offroad_btn_onroad.set_visible(lambda: ui_state.started and not ui_state.always_offroad) + + # offroad: enable button sits at the end (right of developer) + self._enable_offroad_btn_offroad = BigCircleButton(self.icon_offroad_enable, red=True) + self._enable_offroad_btn_offroad.set_click_callback(lambda: self._handle_always_offroad(True)) + self._enable_offroad_btn_offroad.set_visible(lambda: not ui_state.started and not ui_state.always_offroad) + + self._disable_offroad_btn = BigCircleButton(self.icon_offroad_disable, red=False) + self._disable_offroad_btn.set_click_callback(lambda: self._handle_always_offroad(False)) + self._disable_offroad_btn.set_visible(lambda: ui_state.always_offroad) + + items = self._scroller._items.copy() + + items.insert(1, sunnylink_btn) + items.insert(2, models_btn) + + # front slots (only one ever visible at a time): exit-always-offroad, then enable-onroad + items.insert(0, self._enable_offroad_btn_onroad) + items.insert(0, self._disable_offroad_btn) + # end slot: enable-offroad (right of developer) + items.append(self._enable_offroad_btn_offroad) + + self._scroller._items.clear() + for item in items: + self._scroller.add_widget(item) + + def _update_state(self): + super()._update_state() + + def _handle_always_offroad(self, enable: bool): + + def _set_offroad_status(status: bool): + if not ui_state.engaged: + ui_state.params.put_bool("OffroadMode", status) + ui_state.always_offroad = status + + if not enable: + dlg = BigConfirmationDialog(tr("slide to exit always offroad"), self.icon_offroad_slider, red=False, + confirm_callback=lambda: _set_offroad_status(False)) + else: + if ui_state.engaged: + gui_app.push_widget(BigDialog(tr("disengage to enable always offroad"), "", )) + return + + dlg = BigConfirmationDialog(tr("slide to force offroad"), self.icon_offroad_slider, red=True, + confirm_callback=lambda: _set_offroad_status(True)) + gui_app.push_widget(dlg) diff --git a/openpilot/selfdrive/ui/sunnypilot/mici/layouts/sunnylink.py b/openpilot/selfdrive/ui/sunnypilot/mici/layouts/sunnylink.py new file mode 100644 index 0000000000..e804c78035 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/mici/layouts/sunnylink.py @@ -0,0 +1,256 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import pyray as rl + +from collections.abc import Callable + +from openpilot.cereal import custom +from openpilot.selfdrive.ui.mici.widgets.button import BigButton, BigToggle +from openpilot.selfdrive.ui.mici.widgets.dialog import BigDialog, BigConfirmationDialog +from openpilot.selfdrive.ui.sunnypilot.mici.layouts.onboarding import SunnylinkConsentPage +from openpilot.selfdrive.ui.sunnypilot.mici.widgets.sunnylink_pairing_dialog import SunnylinkPairingDialog +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.sunnypilot.sunnylink.api import UNREGISTERED_SUNNYLINK_DONGLE_ID +from openpilot.system.ui.lib.application import gui_app, MousePos, FontWeight +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.label import UnifiedLabel +from openpilot.system.ui.widgets.scroller import NavScroller +from openpilot.common.version import sunnylink_consent_version, sunnylink_consent_declined + +class SunnylinkInfo(Widget): + def __init__(self): + super().__init__() + + self.set_rect(rl.Rectangle(0, 0, 360, 180)) + + header_color = rl.Color(255, 255, 255, int(255 * 0.9)) + subheader_color = rl.Color(255, 255, 255, int(255 * 0.9 * 0.65)) + max_width = int(self._rect.width - 20) + self.device_id_header = UnifiedLabel(tr("device id"), 48, max_width=max_width, text_color=header_color, + font_weight=FontWeight.DISPLAY, shimmer=True) + self.device_id_text = UnifiedLabel(UNREGISTERED_SUNNYLINK_DONGLE_ID, 32, max_width=max_width, text_color=subheader_color, + font_weight=FontWeight.ROMAN, scroll=True) + + self.sponsor_header = UnifiedLabel(tr("sponsor tier"), 48, max_width=max_width, text_color=header_color, + font_weight=FontWeight.DISPLAY, shimmer=True) + self.sponsor_text = UnifiedLabel("N/A", 32, max_width=max_width, text_color=subheader_color, font_weight=FontWeight.ROMAN) + + def _render(self, _): + self.device_id_header.set_position(self._rect.x + 20, self._rect.y - 10) + self.device_id_header.render() + + self.device_id_text.set_position(self._rect.x + 20, self._rect.y + 68 - 25) + self.device_id_text.render() + + self.sponsor_header.set_position(self._rect.x + 20, self._rect.y + 114 - 30) + self.sponsor_header.render() + + self.sponsor_text.set_position(self._rect.x + 20, self._rect.y + 161 - 25) + self.sponsor_text.render() + +class SunnylinkLayoutMici(NavScroller): + def __init__(self, back_callback: Callable): + super().__init__() + self.set_back_callback(back_callback) + self._restore_in_progress = False + self._backup_in_progress = False + self._sunnylink_enabled = ui_state.params.get("SunnylinkEnabled") + + self._sunnylink_info = SunnylinkInfo() + + self._sunnylink_toggle = BigToggle(text=tr("enable sunnylink"), + initial_state=self._sunnylink_enabled, + toggle_callback=self._sunnylink_toggle_callback) + self._sunnylink_sponsor_button = SunnylinkPairBigButton(sponsor_pairing=False) + self._sunnylink_pair_button = SunnylinkPairBigButton(sponsor_pairing=True) + self._backup_btn = BigButton(tr("backup settings"), "") + self._backup_btn.set_click_callback(lambda: self._handle_backup_restore_btn(restore=False)) + self._restore_btn = BigButton(tr("restore settings"), "") + self._restore_btn.set_click_callback(lambda: self._handle_backup_restore_btn(restore=True)) + self._sunnylink_uploader_toggle = BigToggle(text=tr("sunnylink uploader"), initial_state=False, + toggle_callback=self._sunnylink_uploader_callback) + + self._scroller.add_widgets([ + self._sunnylink_info, + self._sunnylink_toggle, + self._sunnylink_sponsor_button, + self._sunnylink_pair_button, + self._backup_btn, + self._restore_btn, + self._sunnylink_uploader_toggle + ]) + + def _update_state(self): + super()._update_state() + self._sunnylink_enabled = ui_state.params.get("SunnylinkEnabled") + self._sunnylink_toggle.set_checked(self._sunnylink_enabled) + self._sunnylink_pair_button.set_visible(self._sunnylink_enabled) + self._sunnylink_sponsor_button.set_visible(self._sunnylink_enabled) + self._backup_btn.set_visible(self._sunnylink_enabled) + self._restore_btn.set_visible(self._sunnylink_enabled) + self._sunnylink_uploader_toggle.set_visible(self._sunnylink_enabled) + self.handle_backup_restore_progress() + + self._sunnylink_info.device_id_text.set_text(ui_state.params.get("SunnylinkDongleId") or UNREGISTERED_SUNNYLINK_DONGLE_ID) + self._sunnylink_info.sponsor_text.set_text(ui_state.sunnylink_state.get_sponsor_tier().name.lower() or "N/A") + self._sunnylink_info.set_visible(self._sunnylink_enabled) + + if ui_state.sunnylink_state.is_sponsor(): + self._sunnylink_sponsor_button.set_text(tr("thanks")) + self._sunnylink_sponsor_button.set_value(ui_state.sunnylink_state.get_sponsor_tier().name.lower()) + self._sunnylink_sponsor_button.set_enabled(False) + else: + self._sunnylink_sponsor_button.set_text(tr("sponsor")) + self._sunnylink_sponsor_button.set_value("") + + if ui_state.sunnylink_state.is_paired(): + self._sunnylink_pair_button.set_text(tr("paired")) + else: + self._sunnylink_pair_button.set_text(tr("pair")) + + def show_event(self): + super().show_event() + ui_state.update_params() + ui_state.sunnylink_state.set_settings_open(True) + + def hide_event(self): + super().hide_event() + ui_state.sunnylink_state.set_settings_open(False) + + @staticmethod + def _sunnylink_toggle_callback(state: bool): + sl_consent: bool = ui_state.params.get("CompletedSunnylinkConsentVersion") == sunnylink_consent_version + sl_enabled: bool = ui_state.params.get("SunnylinkEnabled") + + def sl_terms_accepted(): + ui_state.params.put("CompletedSunnylinkConsentVersion", sunnylink_consent_version) + ui_state.params.put_bool("SunnylinkEnabled", True) + gui_app.pop_widget() + + def sl_terms_declined(): + ui_state.params.put("CompletedSunnylinkConsentVersion", sunnylink_consent_declined) + ui_state.params.put_bool("SunnylinkEnabled", False) + gui_app.pop_widget() + + if state and not sl_consent and not sl_enabled: + sl_terms_dlg = SunnylinkConsentPage(on_accept=sl_terms_accepted, on_decline=sl_terms_declined) + gui_app.push_widget(sl_terms_dlg) + else: + ui_state.params.put_bool("SunnylinkEnabled", state) + + ui_state.update_params() + + @staticmethod + def _sunnylink_uploader_callback(state: bool): + ui_state.params.put_bool("EnableSunnylinkUploader", state) + + def _handle_backup_restore_btn(self, restore: bool = False): + lbl = tr("slide to restore") if restore else tr("slide to backup") + icon = gui_app.texture("icons_mici/settings/device/update.png", 64, 64) + dlg = BigConfirmationDialog(lbl, icon, confirm_callback=self._restore_handler if restore else self._backup_handler) + gui_app.push_widget(dlg) + + def _backup_handler(self): + self._backup_in_progress = True + self._backup_btn.set_enabled(False) + ui_state.params.put_bool("BackupManager_CreateBackup", True) + + def _restore_handler(self): + self._restore_in_progress = True + self._restore_btn.set_enabled(False) + ui_state.params.put("BackupManager_RestoreVersion", "latest") + + def handle_backup_restore_progress(self): + sunnylink_backup_manager = ui_state.sm["backupManagerSP"] + + backup_status = sunnylink_backup_manager.backupStatus + restore_status = sunnylink_backup_manager.restoreStatus + backup_progress = sunnylink_backup_manager.backupProgress + restore_progress = sunnylink_backup_manager.restoreProgress + + if self._backup_in_progress: + self._restore_btn.set_enabled(False) + self._backup_btn.set_enabled(False) + + if backup_status == custom.BackupManagerSP.Status.inProgress: + self._backup_in_progress = True + self._backup_btn.set_text(tr("backing up")) + text = tr(f"{backup_progress}%") + self._backup_btn.set_value(text) + + elif backup_status == custom.BackupManagerSP.Status.failed: + self._backup_in_progress = False + self._backup_btn.set_enabled(not ui_state.is_onroad()) + self._backup_btn.set_text(tr("backup")) + self._backup_btn.set_value(tr("failed")) + + elif (backup_status == custom.BackupManagerSP.Status.completed or + (backup_status == custom.BackupManagerSP.Status.idle and backup_progress == 100.0)): + self._backup_in_progress = False + gui_app.push_widget(BigDialog(title=tr("settings backed up"), description="")) + self._backup_btn.set_enabled(not ui_state.is_onroad()) + + elif self._restore_in_progress: + self._restore_btn.set_enabled(False) + self._backup_btn.set_enabled(False) + + if restore_status == custom.BackupManagerSP.Status.inProgress: + self._restore_in_progress = True + self._restore_btn.set_text(tr("restoring")) + text = tr(f"{restore_progress}%") + self._restore_btn.set_value(text) + + elif restore_status == custom.BackupManagerSP.Status.failed: + self._restore_in_progress = False + self._restore_btn.set_enabled(not ui_state.is_onroad()) + self._restore_btn.set_text(tr("restore")) + self._restore_btn.set_value(tr("failed")) + gui_app.push_widget(BigDialog(title=tr("unable to restore"), description="try again later.")) + + elif (restore_status == custom.BackupManagerSP.Status.completed or + (restore_status == custom.BackupManagerSP.Status.idle and restore_progress == 100.0)): + self._restore_in_progress = False + gui_app.push_widget(BigConfirmationDialog( + title="slide to restart", icon=gui_app.texture("icons_mici/settings/device/reboot.png", 64, 64), + confirm_callback=lambda: gui_app.request_close())) + + else: + can_enable = self._sunnylink_enabled and not ui_state.is_onroad() + self._backup_btn.set_enabled(can_enable) + self._backup_btn.set_text(tr("backup settings")) + self._backup_btn.set_value("") + self._restore_btn.set_enabled(can_enable) + self._restore_btn.set_text(tr("restore settings")) + self._restore_btn.set_value("") + + +class SunnylinkPairBigButton(BigButton): + def __init__(self, sponsor_pairing: bool = False): + self.sponsor_pairing = sponsor_pairing + super().__init__("") + + def _update_state(self): + super()._update_state() + + def _handle_mouse_release(self, mouse_pos: MousePos): + super()._handle_mouse_release(mouse_pos) + + network_type = ui_state.sm["deviceState"].networkType + + dlg: BigDialog | SunnylinkPairingDialog | None = None + + if network_type == 0: + dlg = BigDialog(tr("no internet"), tr("please connect to WiFi & try again")) + elif UNREGISTERED_SUNNYLINK_DONGLE_ID == (ui_state.params.get("SunnylinkDongleId") or UNREGISTERED_SUNNYLINK_DONGLE_ID): + dlg = BigDialog(tr("sunnylink dongle id not found"), tr("please reboot & try again")) + elif self.sponsor_pairing: + dlg = SunnylinkPairingDialog(sponsor_pairing=True) + elif not self.sponsor_pairing: + dlg = SunnylinkPairingDialog(sponsor_pairing=False) + if dlg: + gui_app.push_widget(dlg) diff --git a/sunnypilot/modeld/models/__init__.py b/openpilot/selfdrive/ui/sunnypilot/mici/onroad/__init__.py similarity index 100% rename from sunnypilot/modeld/models/__init__.py rename to openpilot/selfdrive/ui/sunnypilot/mici/onroad/__init__.py diff --git a/openpilot/selfdrive/ui/sunnypilot/mici/onroad/confidence_ball.py b/openpilot/selfdrive/ui/sunnypilot/mici/onroad/confidence_ball.py new file mode 100644 index 0000000000..4a1aa92241 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/mici/onroad/confidence_ball.py @@ -0,0 +1,26 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from openpilot.selfdrive.ui.onroad.augmented_road_view import BORDER_COLORS +from openpilot.selfdrive.ui.ui_state import ui_state, UIStatus + + +class ConfidenceBallSP: + @staticmethod + def get_animate_status_probs(): + if ui_state.status == UIStatus.LAT_ONLY: + return ui_state.sm['modelV2'].meta.disengagePredictions.steerOverrideProbs + + # UIStatus.LONG_ONLY + return ui_state.sm['modelV2'].meta.disengagePredictions.brakeDisengageProbs + + @staticmethod + def get_lat_long_dot_color(): + if ui_state.status == UIStatus.LAT_ONLY: + return BORDER_COLORS[UIStatus.LAT_ONLY] + + # UIStatus.LONG_ONLY + return BORDER_COLORS[UIStatus.LONG_ONLY] diff --git a/openpilot/selfdrive/ui/sunnypilot/mici/onroad/hud_renderer.py b/openpilot/selfdrive/ui/sunnypilot/mici/onroad/hud_renderer.py new file mode 100644 index 0000000000..9d39d01727 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/mici/onroad/hud_renderer.py @@ -0,0 +1,28 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import pyray as rl + +from openpilot.selfdrive.ui.mici.onroad.hud_renderer import HudRenderer +from openpilot.selfdrive.ui.sunnypilot.onroad.blind_spot_indicators import BlindSpotIndicators + + +class HudRendererSP(HudRenderer): + def __init__(self): + super().__init__() + self.blind_spot_indicators = BlindSpotIndicators() + + def _update_state(self) -> None: + super()._update_state() + self.blind_spot_indicators.update() + + def _render(self, rect: rl.Rectangle) -> None: + super()._render(rect) + self.blind_spot_indicators.render(rect) + + def _has_blind_spot_detected(self) -> bool: + + return self.blind_spot_indicators.detected diff --git a/openpilot/selfdrive/ui/sunnypilot/mici/onroad/model_renderer.py b/openpilot/selfdrive/ui/sunnypilot/mici/onroad/model_renderer.py new file mode 100644 index 0000000000..e3de9401ce --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/mici/onroad/model_renderer.py @@ -0,0 +1,19 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import pyray as rl +from openpilot.selfdrive.ui.ui_state import UIStatus +from openpilot.selfdrive.ui.sunnypilot.onroad.rainbow_path import RainbowPath + +LANE_LINE_COLORS_SP = { + UIStatus.LAT_ONLY: rl.Color(0, 255, 64, 255), + UIStatus.LONG_ONLY: rl.Color(0, 255, 64, 255), +} + + +class ModelRendererSP: + def __init__(self): + self.rainbow_path = RainbowPath() diff --git a/sunnypilot/modeld/thneed/__init__.py b/openpilot/selfdrive/ui/sunnypilot/mici/widgets/__init__.py similarity index 100% rename from sunnypilot/modeld/thneed/__init__.py rename to openpilot/selfdrive/ui/sunnypilot/mici/widgets/__init__.py diff --git a/openpilot/selfdrive/ui/sunnypilot/mici/widgets/sunnylink_pairing_dialog.py b/openpilot/selfdrive/ui/sunnypilot/mici/widgets/sunnylink_pairing_dialog.py new file mode 100644 index 0000000000..c727e4fc1c --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/mici/widgets/sunnylink_pairing_dialog.py @@ -0,0 +1,57 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import base64 + +import pyray as rl +from openpilot.common.swaglog import cloudlog +from openpilot.selfdrive.ui.mici.widgets.pairing_dialog import PairingDialog +from openpilot.sunnypilot.sunnylink.api import SunnylinkApi, UNREGISTERED_SUNNYLINK_DONGLE_ID, API_HOST +from openpilot.system.ui.lib.application import FontWeight, gui_app +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.widgets.nav_widget import NavWidget +from openpilot.system.ui.widgets.label import UnifiedLabel + + +class SunnylinkPairingDialog(PairingDialog): + """Dialog for device pairing with QR code.""" + + def __init__(self, sponsor_pairing: bool = False): + PairingDialog.__init__(self) + self._sponsor_pairing = sponsor_pairing + label_text = tr("pair with sunnylink") if sponsor_pairing else tr("become a sunnypilot sponsor") + self._pair_label = UnifiedLabel(label_text, font_size=48, font_weight=FontWeight.BOLD, + text_color=rl.Color(255, 255, 255, int(255 * 0.9)), line_height=0.8) + + def _get_pairing_url(self) -> str: + qr_string = "https://github.com/sponsors/sunnyhaibin" + + if self._sponsor_pairing: + try: + sl_dongle_id = self._params.get("SunnylinkDongleId") or UNREGISTERED_SUNNYLINK_DONGLE_ID + token = SunnylinkApi(sl_dongle_id).get_token() + inner_string = f"1|{sl_dongle_id}|{token}" + payload_bytes = base64.b64encode(inner_string.encode('utf-8')).decode('utf-8') + qr_string = f"{API_HOST}/sso?state={payload_bytes}" + except Exception: + cloudlog.exception("Failed to get pairing token") + + return qr_string + + def _update_state(self): + NavWidget._update_state(self) + + +if __name__ == "__main__": + gui_app.init_window("pairing device") + pairing = SunnylinkPairingDialog(sponsor_pairing=True) + try: + for _ in gui_app.render(): + result = pairing.render(rl.Rectangle(0, 0, gui_app.width, gui_app.height)) + if result != -1: + break + finally: + del pairing diff --git a/sunnypilot/modeld_v2/models/__init__.py b/openpilot/selfdrive/ui/sunnypilot/onroad/__init__.py similarity index 100% rename from sunnypilot/modeld_v2/models/__init__.py rename to openpilot/selfdrive/ui/sunnypilot/onroad/__init__.py diff --git a/openpilot/selfdrive/ui/sunnypilot/onroad/alert_renderer.py b/openpilot/selfdrive/ui/sunnypilot/onroad/alert_renderer.py new file mode 100644 index 0000000000..9f48287a70 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/onroad/alert_renderer.py @@ -0,0 +1,103 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import pyray as rl +from openpilot.selfdrive.ui.onroad.alert_renderer import AlertRenderer, AlertSize, ALERT_FONT_MEDIUM, ALERT_FONT_BIG, \ + ALERT_FONT_SMALL, ALERT_MARGIN, ALERT_HEIGHTS, ALERT_PADDING, Alert +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.lib.wrap_text import wrap_text + +ALERT_LINE_SPACING = 15 + + +class AlertRendererSP(AlertRenderer): + def __init__(self): + super().__init__() + + def _draw_text(self, rect: rl.Rectangle, alert: Alert) -> None: + if alert.size == AlertSize.small: + self._draw_multiline_centered(alert.text1, rect, self.font_bold, ALERT_FONT_MEDIUM) + + elif alert.size == AlertSize.mid: + wrap_width = int(rect.width) + lines1 = wrap_text(self.font_bold, alert.text1, ALERT_FONT_BIG, wrap_width) + lines2 = wrap_text(self.font_regular, alert.text2, ALERT_FONT_SMALL, wrap_width) if alert.text2 else [] + + total_text_height = len(lines1) * measure_text_cached(self.font_bold, "A", ALERT_FONT_BIG).y + if lines2: + total_text_height += ALERT_LINE_SPACING + len(lines2) * measure_text_cached(self.font_regular, "A", ALERT_FONT_SMALL).y + + curr_y = rect.y + (rect.height - total_text_height) / 2 + + for line in lines1: + line_height = measure_text_cached(self.font_bold, alert.text1, ALERT_FONT_BIG).y + self._draw_line_centered(line, rl.Rectangle(rect.x, curr_y, rect.width, line_height), self.font_bold, ALERT_FONT_BIG) + curr_y += line_height + + if lines2: + curr_y += ALERT_LINE_SPACING + for line in lines2: + line_height = measure_text_cached(self.font_regular, alert.text2, ALERT_FONT_SMALL).y + self._draw_line_centered(line, rl.Rectangle(rect.x, curr_y, rect.width, line_height), self.font_regular, ALERT_FONT_SMALL) + curr_y += line_height + + else: + super()._draw_text(rect, alert) + + def _draw_multiline_centered(self, text, rect, font, font_size, color=rl.WHITE) -> None: + lines = wrap_text(font, text, font_size, rect.width) + line_height = measure_text_cached(font, text, font_size).y + total_height = len(lines) * line_height + curr_y = rect.y + (rect.height - total_height) / 2 + for line in lines: + self._draw_line_centered(line, rl.Rectangle(rect.x, curr_y, rect.width, line_height), font, font_size, color) + curr_y += line_height + + def _draw_line_centered(self, text, rect, font, font_size, color=rl.WHITE) -> None: + text_size = measure_text_cached(font, text, font_size) + x = rect.x + (rect.width - text_size.x) / 2 + y = rect.y + rl.draw_text_ex(font, text, rl.Vector2(x, y), font_size, 0, color) + + def _get_alert_rect(self, rect: rl.Rectangle, size: int) -> rl.Rectangle: + if size == AlertSize.full: + return rect + + dev_ui_info = ui_state.developer_ui + v_adjustment = 40 if dev_ui_info in {2, 3} and size != AlertSize.full else 0 + h_adjustment = 230 if dev_ui_info in {1, 3} and size != AlertSize.full else 0 + + w = int(rect.width - ALERT_MARGIN * 2 - h_adjustment) + h = self._calculate_dynamic_height(size, w) + return rl.Rectangle(rect.x + ALERT_MARGIN, rect.y + rect.height - h + ALERT_MARGIN - v_adjustment, w, + h - ALERT_MARGIN * 2) + + def _calculate_dynamic_height(self, size: int, width: int) -> int: + alert = self.get_alert(ui_state.sm) + if not alert: + return ALERT_HEIGHTS.get(size, 271) + + height = 2 * ALERT_PADDING + wrap_width = width - 2 * ALERT_PADDING + + if size == AlertSize.small: + lines = wrap_text(self.font_bold, alert.text1, ALERT_FONT_MEDIUM, wrap_width) + line_height = measure_text_cached(self.font_bold, alert.text1, ALERT_FONT_MEDIUM).y + height += int(len(lines) * line_height) + elif size == AlertSize.mid: + lines1 = wrap_text(self.font_bold, alert.text1, ALERT_FONT_BIG, wrap_width) + line_height1 = measure_text_cached(self.font_bold, alert.text1, ALERT_FONT_BIG).y + height += int(len(lines1) * line_height1) + + if alert.text2: + lines2 = wrap_text(self.font_regular, alert.text2, ALERT_FONT_SMALL, wrap_width) + line_height2 = measure_text_cached(self.font_regular, alert.text2, ALERT_FONT_SMALL).y + height += int(ALERT_LINE_SPACING + len(lines2) * line_height2) + else: + height = ALERT_HEIGHTS.get(size, 271) + + return int(height) diff --git a/openpilot/selfdrive/ui/sunnypilot/onroad/augmented_road_view.py b/openpilot/selfdrive/ui/sunnypilot/onroad/augmented_road_view.py new file mode 100644 index 0000000000..c7dedee540 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/onroad/augmented_road_view.py @@ -0,0 +1,31 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import pyray as rl +from openpilot.common.filter_simple import FirstOrderFilter +from openpilot.selfdrive.ui.ui_state import UIStatus, ui_state +from openpilot.system.ui.lib.application import gui_app + +BORDER_COLORS_SP = { + UIStatus.LAT_ONLY: rl.Color(0x00, 0xC8, 0xC8, 0xFF), # Cyan for lateral-only state + UIStatus.LONG_ONLY: rl.Color(0x96, 0x1C, 0xA8, 0xFF), # Purple for longitudinal-only state +} + + +class AugmentedRoadViewSP: + def __init__(self): + self._fade_texture = gui_app.texture("icons_mici/onroad/onroad_fade.png") + self._fade_alpha_filter = FirstOrderFilter(0, 0.1, 1 / gui_app.target_fps) + + def update_fade_out_bottom_overlay(self, _content_rect): + # Fade out bottom of overlays for looks (only when engaged) + fade_alpha = self._fade_alpha_filter.update(ui_state.status != UIStatus.DISENGAGED) + if ui_state.torque_bar and fade_alpha > 1e-2: + # Scale the fade texture to the content rect + rl.draw_texture_pro(self._fade_texture, + rl.Rectangle(0, 0, self._fade_texture.width, self._fade_texture.height), + _content_rect, rl.Vector2(0, 0), 0.0, + rl.Color(255, 255, 255, int(255 * fade_alpha))) diff --git a/openpilot/selfdrive/ui/sunnypilot/onroad/blind_spot_indicators.py b/openpilot/selfdrive/ui/sunnypilot/onroad/blind_spot_indicators.py new file mode 100644 index 0000000000..2efda17a2b --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/onroad/blind_spot_indicators.py @@ -0,0 +1,52 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import pyray as rl + +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.ui.lib.application import gui_app +from openpilot.common.filter_simple import FirstOrderFilter + + +class BlindSpotIndicators: + def __init__(self): + self._txt_blind_spot_left: rl.Texture = gui_app.texture('icons_mici/onroad/blind_spot_left.png', 108, 128) + self._txt_blind_spot_right: rl.Texture = gui_app.texture('icons_mici/onroad/blind_spot_left.png', 108, 128, flip_x=True) + + self._blind_spot_left_alpha_filter = FirstOrderFilter(0, 0.15, 1 / gui_app.target_fps) + self._blind_spot_right_alpha_filter = FirstOrderFilter(0, 0.15, 1 / gui_app.target_fps) + + def update(self) -> None: + sm = ui_state.sm + CS = sm['carState'] + + self._blind_spot_left_alpha_filter.update(1.0 if CS.leftBlindspot else 0.0) + self._blind_spot_right_alpha_filter.update(1.0 if CS.rightBlindspot else 0.0) + + @property + def detected(self) -> bool: + return ui_state.blindspot and (self._blind_spot_left_alpha_filter.x > 0.01 or self._blind_spot_right_alpha_filter.x > 0.01) + + def render(self, rect: rl.Rectangle) -> None: + if not ui_state.blindspot: + return + + BLIND_SPOT_MARGIN_X = 20 # Distance from edge of screen + BLIND_SPOT_Y_OFFSET = 100 # Distance from top of screen + + if self._blind_spot_left_alpha_filter.x > 0.01: + pos_x = int(rect.x + BLIND_SPOT_MARGIN_X) + pos_y = int(rect.y + BLIND_SPOT_Y_OFFSET) + alpha = int(255 * self._blind_spot_left_alpha_filter.x) + color = rl.Color(255, 255, 255, alpha) + rl.draw_texture_ex(self._txt_blind_spot_left, rl.Vector2(pos_x, pos_y), 0.0, 1.0, color) + + if self._blind_spot_right_alpha_filter.x > 0.01: + pos_x = int(rect.x + rect.width - BLIND_SPOT_MARGIN_X - self._txt_blind_spot_right.width) + pos_y = int(rect.y + BLIND_SPOT_Y_OFFSET) + alpha = int(255 * self._blind_spot_right_alpha_filter.x) + color = rl.Color(255, 255, 255, alpha) + rl.draw_texture_ex(self._txt_blind_spot_right, rl.Vector2(pos_x, pos_y), 0.0, 1.0, color) diff --git a/openpilot/selfdrive/ui/sunnypilot/onroad/chevron_metrics.py b/openpilot/selfdrive/ui/sunnypilot/onroad/chevron_metrics.py new file mode 100644 index 0000000000..1dded3fc62 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/onroad/chevron_metrics.py @@ -0,0 +1,147 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import numpy as np + +import pyray as rl +from openpilot.common.constants import CV +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.lib.text_measure import measure_text_cached + + +class ChevronOptions: + OFF = 0 + DISTANCE_ONLY = 1 + SPEED_ONLY = 2 + TTC_ONLY = 3 + ALL = 4 + + +class ChevronMetrics: + def __init__(self): + self._lead_status_alpha: float = 0.0 + self._font = gui_app.font(FontWeight.SEMI_BOLD) + + def update_alpha(self, has_lead: bool): + """Update the alpha value for fade in/out animation""" + if not has_lead: + self._lead_status_alpha = max(0.0, self._lead_status_alpha - 0.05) + else: + self._lead_status_alpha = min(1.0, self._lead_status_alpha + 0.1) + + def should_render(self) -> bool: + """Check if dev UI should be rendered""" + return ui_state.chevron_metrics != ChevronOptions.OFF and self._lead_status_alpha > 0.0 + + def _draw_lead(self, lead_data, lead_vehicle, v_ego: float, rect: rl.Rectangle): + """Draw lead vehicle status information (distance, speed, TTC)""" + if not self.should_render(): + return + + d_rel = lead_data.dRel + v_rel = lead_data.vRel + + if not lead_vehicle.chevron or len(lead_vehicle.chevron) < 2: + return + + chevron_x = lead_vehicle.chevron[1][0] + chevron_y = lead_vehicle.chevron[1][1] + sz = np.clip((25 * 30) / (d_rel / 3 + 30), 15.0, 30.0) * 2.35 + + text_lines = self._build_text_lines(d_rel, v_rel, v_ego) + if not text_lines: + return + + self._render_text_lines(text_lines, chevron_x, chevron_y, sz, rect) + + @staticmethod + def _build_text_lines(d_rel: float, v_rel: float, v_ego: float) -> list[str]: + """Build text lines based on chevron info setting""" + text_lines = [] + + # Distance + if ui_state.chevron_metrics == ChevronOptions.DISTANCE_ONLY or ui_state.chevron_metrics == ChevronOptions.ALL: + val = max(0.0, d_rel) + unit = "m" if ui_state.is_metric else "ft" + if not ui_state.is_metric: + val *= 3.28084 + text_lines.append(f"{val:.0f} {unit}") + + # Speed + if ui_state.chevron_metrics == ChevronOptions.SPEED_ONLY or ui_state.chevron_metrics == ChevronOptions.ALL: + multiplier = CV.MS_TO_KPH if ui_state.is_metric else CV.MS_TO_MPH + val = max(0.0, (v_rel + v_ego) * multiplier) + unit = "km/h" if ui_state.is_metric else "mph" + text_lines.append(f"{val:.0f} {unit}") + + # Time to collision + if ui_state.chevron_metrics == ChevronOptions.TTC_ONLY or ui_state.chevron_metrics == ChevronOptions.ALL: + val = (d_rel / v_ego) if (d_rel > 0 and v_ego > 0) else 0.0 + ttc_text = f"{val:.1f} s" if (0 < val < 200) else "---" + text_lines.append(ttc_text) + + return text_lines + + def _render_text_lines(self, text_lines: list[str], chevron_x: float, chevron_y: float, + sz: float, rect: rl.Rectangle): + """Render text lines with proper centering and positioning""" + font_size = 40 + line_height = 50 + margin = 20 + + text_y = chevron_y + sz + 15 + total_height = len(text_lines) * line_height + + # Adjust Y position if text would go off screen + if text_y + total_height > rect.height - margin: + y_max = min(chevron_y, rect.height - margin) + text_y = y_max - 15 - total_height + text_y = max(margin, text_y) + + alpha = int(255 * self._lead_status_alpha) + text_color = rl.Color(255, 255, 255, alpha) + shadow_color = rl.Color(0, 0, 0, int(200 * self._lead_status_alpha)) + + for i, line in enumerate(text_lines): + y = int(text_y + (i * line_height)) + if y + line_height > rect.height - margin: + break + + # Measure actual text width for proper centering + text_size = measure_text_cached(self._font, line, font_size, 0) + text_width = text_size.x + + # Center the text horizontally on the chevron + x = int(chevron_x - text_width / 2) + x = int(np.clip(x, margin, rect.width - text_width - margin)) + + # Draw shadow + rl.draw_text_ex(self._font, line, rl.Vector2(x + 2, y + 2), font_size, 0, shadow_color) + # Draw text + rl.draw_text_ex(self._font, line, rl.Vector2(x, y), font_size, 0, text_color) + + def draw_lead_status(self, sm, radar_state, rect, lead_vehicles): + lead_one = radar_state.leadOne + lead_two = radar_state.leadTwo + + has_lead_one = lead_one.present if lead_one else False + has_lead_two = lead_two.present if lead_two else False + + self.update_alpha(has_lead_one or has_lead_two) + + if not self.should_render(): + return + + v_ego = sm['carState'].vEgo + + if has_lead_one and lead_vehicles[0].chevron: + self._draw_lead(lead_one, lead_vehicles[0], v_ego, rect) + + if has_lead_two and lead_vehicles[1].chevron: + d_rel_diff = abs(lead_one.dRel - lead_two.dRel) if has_lead_one else float('inf') + if d_rel_diff > 3.0: + self._draw_lead(lead_two, lead_vehicles[1], v_ego, rect) diff --git a/openpilot/selfdrive/ui/sunnypilot/onroad/circular_alerts.py b/openpilot/selfdrive/ui/sunnypilot/onroad/circular_alerts.py new file mode 100644 index 0000000000..c44e4455eb --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/onroad/circular_alerts.py @@ -0,0 +1,140 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import pyray as rl + +from openpilot.cereal import log +from openpilot.selfdrive.ui import UI_BORDER_SIZE +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.selfdrive.ui.sunnypilot.onroad.developer_ui import DeveloperUiState +from openpilot.system.ui.lib.application import gui_app, FontWeight, FONT_SCALE +from openpilot.system.ui.lib.text_measure import measure_text_cached + + +class CircularAlertsRenderer: + def __init__(self): + self._green_light_alert_img = gui_app.texture("../../sunnypilot/selfdrive/assets/images/green_light.png", 250, 250) + self._lead_depart_alert_img = gui_app.texture("../../sunnypilot/selfdrive/assets/images/lead_depart.png", 250, 250) + + self._e2e_alert_display_timer = 0 + self._e2e_alert_frame = 0 + self._green_light_alert = False + self._lead_depart_alert = False + self._standstill_elapsed_time = 0.0 + self._is_standstill = False + self._alert_text = "" + self._alert_img = None + self._allow_e2e_alerts = False + + def update(self) -> None: + sm = ui_state.sm + lp_sp = sm['longitudinalPlanSP'] + car_state = sm['carState'] + self._green_light_alert = lp_sp.e2eAlerts.greenLightAlert + self._lead_depart_alert = lp_sp.e2eAlerts.leadDepartAlert + self._is_standstill = car_state.standstill + + if not ui_state.started: + self._standstill_elapsed_time = 0.0 + + self._allow_e2e_alerts = sm['selfdriveState'].alertSize == log.SelfdriveState.AlertSize.none and \ + sm.recv_frame['driverStateV2'] > ui_state.started_frame + + if self._green_light_alert or self._lead_depart_alert: + self._e2e_alert_display_timer = 3 * gui_app.target_fps + # reset onroad sleep timer for e2e alerts + ui_state.reset_onroad_sleep_timer() + + if self._e2e_alert_display_timer > 0: + self._e2e_alert_frame += 1 + self._e2e_alert_display_timer -= 1 + + if self._green_light_alert: + self._alert_text = "GREEN\nLIGHT" + self._alert_img = self._green_light_alert_img + elif self._lead_depart_alert: + self._alert_text = "LEAD VEHICLE\nDEPARTING" + self._alert_img = self._lead_depart_alert_img + + elif ui_state.standstill_timer and self._is_standstill: + self._alert_img = None + self._standstill_elapsed_time += 1.0 / gui_app.target_fps + minute = int(self._standstill_elapsed_time / 60) + second = int(self._standstill_elapsed_time - (minute * 60)) + self._alert_text = f"{minute:01d}:{second:02d}" + self._e2e_alert_frame += 1 + + else: + self._e2e_alert_frame = 0 + if not self._is_standstill: + self._standstill_elapsed_time = 0.0 + + def render(self, rect: rl.Rectangle) -> None: + if not self._allow_e2e_alerts or (self._e2e_alert_display_timer <= 0 and not (ui_state.standstill_timer and self._is_standstill)): + return + + e2e_alert_size = 250 + dev_ui_width_adjustment = 180 if ui_state.developer_ui in (DeveloperUiState.RIGHT, DeveloperUiState.BOTH) else 100 + + x = rect.x + rect.width - e2e_alert_size - dev_ui_width_adjustment - (UI_BORDER_SIZE * 3) + y = rect.y + rect.height / 2 + 20 + + alert_rect = rl.Rectangle(x - e2e_alert_size, y - e2e_alert_size, e2e_alert_size * 2, e2e_alert_size * 2) + center = rl.Vector2(alert_rect.x + alert_rect.width / 2, alert_rect.y + alert_rect.height / 2) + + # Pulse logic + is_pulsing = (self._e2e_alert_frame % gui_app.target_fps) < (gui_app.target_fps / 2.5) + + # Standstill Timer (STOPPED) should be static white + if self._e2e_alert_display_timer == 0 and ui_state.standstill_timer and self._is_standstill: + frame_color = rl.Color(255, 255, 255, 75) + else: + frame_color = rl.Color(255, 255, 255, 75) if is_pulsing else rl.Color(0, 255, 0, 75) + + # Draw Circle + rl.draw_circle_v(center, e2e_alert_size, rl.Color(0, 0, 0, 190)) + # Draw Ring (Border) + rl.draw_ring(center, e2e_alert_size - 7.5, e2e_alert_size + 7.5, 0, 360, 0, frame_color) + + # Draw Image + if self._alert_img and self._e2e_alert_display_timer > 0: + img_x = center.x - self._alert_img.width / 2 + img_y = center.y - self._alert_img.height / 2 + rl.draw_texture_ex(self._alert_img, rl.Vector2(img_x, img_y), 0.0, 1.0, rl.WHITE) + + # Draw Text + txt_color = rl.Color(255, 255, 255, 255) if is_pulsing else rl.Color(0, 255, 0, 190) + font = gui_app.font(FontWeight.BOLD) + text_size = 48 + spacing = 0 + + lines = self._alert_text.split('\n') + + # Position text at bottom of alert circle + bottom_y = (alert_rect.y + alert_rect.height) - (alert_rect.height / 7) + + # Draw lines upwards from bottom + current_y = bottom_y - (len(lines) * text_size * FONT_SCALE) + + if self._e2e_alert_display_timer == 0 and ui_state.standstill_timer and self._is_standstill: + # Standstill Timer Text + alert_alt_text = "STOPPED" + top_text_size = 80 + measure_top = measure_text_cached(font, alert_alt_text, top_text_size, spacing) + top_y = alert_rect.y + alert_rect.height / 3.5 + rl.draw_text_ex(font, alert_alt_text, rl.Vector2(center.x - measure_top.x / 2, top_y), top_text_size, spacing, rl.Color(255, 175, 3, 240)) + + # Timer + timer_text_size = 100 + measure_timer = measure_text_cached(font, self._alert_text, timer_text_size, spacing) + timer_y = (alert_rect.y + alert_rect.height) - (alert_rect.height / 5) - measure_timer.y + rl.draw_text_ex(font, self._alert_text, rl.Vector2(center.x - measure_timer.x / 2, timer_y), timer_text_size, spacing, rl.WHITE) + else: + for line in lines: + measure = measure_text_cached(font, line, text_size, spacing) + line_x = center.x - measure.x / 2 + rl.draw_text_ex(font, line, rl.Vector2(line_x, current_y), text_size, spacing, txt_color) + current_y += text_size * FONT_SCALE diff --git a/openpilot/selfdrive/ui/sunnypilot/onroad/developer_ui/__init__.py b/openpilot/selfdrive/ui/sunnypilot/onroad/developer_ui/__init__.py new file mode 100644 index 0000000000..889e1737ee --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/onroad/developer_ui/__init__.py @@ -0,0 +1,192 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from enum import IntEnum + +import pyray as rl +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.selfdrive.ui.sunnypilot.onroad.developer_ui.elements import ( + UiElement, RelDistElement, RelSpeedElement, SteeringAngleElement, + DesiredLateralAccelElement, ActualLateralAccelElement, DesiredSteeringAngleElement, + AEgoElement, LeadSpeedElement, FrictionCoefficientElement, LatAccelFactorElement, + SteeringTorqueEpsElement, BearingDegElement, AltitudeElement, DesiredSteeringPIDElement +) +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.widgets import Widget + + +def get_bottom_dev_ui_offset(): + if ui_state.developer_ui in (DeveloperUiState.BOTTOM, DeveloperUiState.BOTH): + return 60 + return 0 + + +class DeveloperUiState(IntEnum): + OFF = 0 + BOTTOM = 1 + RIGHT = 2 + BOTH = 3 + + +class DeveloperUiRenderer(Widget): + def __init__(self): + super().__init__() + self._font_bold: rl.Font = gui_app.font(FontWeight.BOLD) + self._font_semi_bold: rl.Font = gui_app.font(FontWeight.SEMI_BOLD) + self.dev_ui_mode = DeveloperUiState.OFF + + self.rel_dist_elem = RelDistElement() + self.rel_speed_elem = RelSpeedElement() + self.steering_angle_elem = SteeringAngleElement() + self.desired_lat_accel_elem = DesiredLateralAccelElement() + self.actual_lat_accel_elem = ActualLateralAccelElement() + self.desired_steer_elem = DesiredSteeringAngleElement() + self.desired_pid_steer_elem = DesiredSteeringPIDElement() + self.a_ego_elem = AEgoElement() + self.lead_speed_elem = LeadSpeedElement() + self.friction_elem = FrictionCoefficientElement() + self.lat_accel_factor_elem = LatAccelFactorElement() + self.steering_torque_elem = SteeringTorqueEpsElement() + self.bearing_elem = BearingDegElement() + self.altitude_elem = AltitudeElement() + + def _update_state(self) -> None: + self.dev_ui_mode = ui_state.developer_ui + + def _render(self, rect: rl.Rectangle) -> None: + if self.dev_ui_mode == DeveloperUiState.OFF: + return + + sm = ui_state.sm + if sm.recv_frame["carState"] < ui_state.started_frame: + return + + if self.dev_ui_mode == DeveloperUiState.BOTTOM: + self._draw_bottom_dev_ui(rect) + elif self.dev_ui_mode == DeveloperUiState.RIGHT: + self._draw_right_dev_ui(rect) + elif self.dev_ui_mode == DeveloperUiState.BOTH: + self._draw_right_dev_ui(rect) + self._draw_bottom_dev_ui(rect) + + def _draw_right_dev_ui(self, rect: rl.Rectangle) -> None: + sm = ui_state.sm + controls_state = sm['controlsState'] + + UI_BORDER_SIZE = 20 + container_width = 184 + x = int(rect.x + rect.width - container_width - UI_BORDER_SIZE * 2) + y = int(rect.y + UI_BORDER_SIZE * 1.5) + + elements = [ + self.rel_dist_elem.update(sm, ui_state.is_metric), + self.rel_speed_elem.update(sm, ui_state.is_metric), + self.steering_angle_elem.update(sm, ui_state.is_metric), + ] + if controls_state.lateralControlState.which() == 'torqueState': + elements.append(self.desired_lat_accel_elem.update(sm, ui_state.is_metric)) + elif controls_state.lateralControlState.which() == 'angleState': + elements.append(self.desired_steer_elem.update(sm, ui_state.is_metric)) + elif controls_state.lateralControlState.which() == 'pidState': + elements.append(self.desired_pid_steer_elem.update(sm, ui_state.is_metric)) + + elements.append(self.actual_lat_accel_elem.update(sm, ui_state.is_metric)) + + current_y = y + for element in elements: + current_y += self._draw_right_dev_ui_element(x, current_y, element) + + def _draw_right_dev_ui_element(self, x: int, y: int, element: UiElement) -> int: + x += 0 + y += 230 + container_width = 184 + label_size = 28 + value_size = 60 + unit_size = 28 + label_width = measure_text_cached(self._font_bold, element.label, label_size, 0).x + centered_label_x = x + (container_width - label_width) / 2 + rl.draw_text_ex(self._font_bold, element.label, rl.Vector2(centered_label_x, y), label_size, 0, rl.WHITE) + + y += 45 + value_width = measure_text_cached(self._font_bold, element.value, value_size, 0).x + centered_value_x = x + (container_width - value_width) / 2 + rl.draw_text_ex(self._font_bold, element.value, rl.Vector2(centered_value_x, y), value_size, 0, element.color) + + if element.unit: + units_height = measure_text_cached(self._font_bold, element.unit, unit_size, 0).x + + units_x = x + container_width + units_y = y + (value_size / 2) + (units_height / 2) + + rl.draw_text_pro(self._font_bold, element.unit, rl.Vector2(units_x, units_y), rl.Vector2(0, 0), -90.0, unit_size, 0, rl.WHITE) + + return 130 + + def _draw_bottom_dev_ui(self, rect: rl.Rectangle) -> None: + sm = ui_state.sm + bar_height = 61 + y = int(rect.y + rect.height - bar_height) + + rl.draw_rectangle(int(rect.x), y, int(rect.width), bar_height, + rl.Color(0, 0, 0, 100)) + + elements = [ + self.a_ego_elem.update(sm, ui_state.is_metric), + self.lead_speed_elem.update(sm, ui_state.is_metric), + ] + + # Add torque-specific elements if using torque control + if sm['controlsState'].lateralControlState.which() == 'torqueState': + override_active = ui_state.enforce_torque_control and ui_state.custom_torque_params and ui_state.torque_override_enabled + if sm.valid['liveTorqueParameters'] or override_active: + elements.extend([ + self.friction_elem.update(sm, ui_state.is_metric), + self.lat_accel_factor_elem.update(sm, ui_state.is_metric), + ]) + else: + # Non-torque: show steering torque and GPS data + elements.append(self.steering_torque_elem.update(sm, ui_state.is_metric)) + + if sm.valid['gpsLocationExternal'] or sm.valid['gpsLocation']: + elements.append(self.bearing_elem.update(sm, ui_state.is_metric)) + + # Add altitude if GPS available + if sm.valid['gpsLocationExternal'] or sm.valid['gpsLocation']: + elements.append(self.altitude_elem.update(sm, ui_state.is_metric)) + + if not elements: + return + + font_size = 38 + element_widths = [] + for element in elements: + element.measure(self._font_bold, font_size) + element_widths.append(element.total_width) + + total_element_width = sum(element_widths) + num_gaps = len(elements) + 1 + available_width = rect.width + gap_width = (available_width - total_element_width) / num_gaps + + center_y = y + bar_height // 2 + current_x = rect.x + gap_width + + for i, element in enumerate(elements): + element_center_x = int(current_x + element_widths[i] / 2) + self._draw_bottom_dev_ui_element(element_center_x, center_y, element) + current_x += element_widths[i] + gap_width + + def _draw_bottom_dev_ui_element(self, center_x: int, y: int, element: UiElement) -> None: + font_size = 38 + start_x = center_x - element.total_width / 2 + + rl.draw_text_ex(self._font_bold, element.label_text, rl.Vector2(start_x, y - font_size // 2), font_size, 0, rl.WHITE) + rl.draw_text_ex(self._font_bold, element.val_text, rl.Vector2(start_x + element.label_width, y - font_size // 2), font_size, 0, element.color) + + if element.unit: + rl.draw_text_ex(self._font_bold, element.unit_text, rl.Vector2(start_x + element.label_width + element.val_width, y - font_size // 2), + font_size, 0, rl.WHITE) diff --git a/openpilot/selfdrive/ui/sunnypilot/onroad/developer_ui/elements.py b/openpilot/selfdrive/ui/sunnypilot/onroad/developer_ui/elements.py new file mode 100644 index 0000000000..4119990f22 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/onroad/developer_ui/elements.py @@ -0,0 +1,348 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import pyray as rl +from dataclasses import dataclass + +from openpilot.common.constants import CV +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.ui.lib.text_measure import measure_text_cached + + +@dataclass +class UiElement: + value: str + label: str + unit: str + color: rl.Color + val_text: str = "" + label_text: str = "" + unit_text: str = "" + val_width: float = 0.0 + label_width: float = 0.0 + unit_width: float = 0.0 + total_width: float = 0.0 + + def measure(self, font, font_size: int): + self.label_text = f"{self.label} " + self.val_text = self.value + self.unit_text = f" {self.unit}" if self.unit else "" + + self.label_width = measure_text_cached(font, self.label_text, font_size, 0).x + self.val_width = measure_text_cached(font, self.val_text, font_size, 0).x + self.unit_width = measure_text_cached(font, self.unit_text, font_size, 0).x if self.unit else 0 + + self.total_width = self.label_width + self.val_width + self.unit_width + + +class LeadInfoElement: + @staticmethod + def get_lead_status(sm): + lead_one = sm['radarState'].leadOne + return lead_one.present, lead_one.dRel, lead_one.vRel + + @staticmethod + def get_lead_color(lead_d_rel: float, lead_v_rel: float = 0.0, use_v_rel: bool = False) -> rl.Color: + if use_v_rel: + if lead_v_rel < -4.4704: + return rl.RED + elif lead_v_rel < 0: + return rl.Color(255, 188, 0, 255) # Orange + else: + if lead_d_rel < 5: + return rl.RED + elif lead_d_rel < 15: + return rl.Color(255, 188, 0, 255) # Orange + return rl.WHITE + + +class LateralControlElement: + @staticmethod + def get_lat_color(lat_active: bool, steer_override: bool, angle_steers: float = 0.0, + check_angle: bool = False) -> rl.Color: + color = rl.WHITE + if lat_active: + color = rl.Color(145, 155, 149, 255) if steer_override else rl.Color(0, 255, 0, 255) + + if check_angle and lat_active: + if abs(angle_steers) > 180: + color = rl.RED + elif abs(angle_steers) > 90: + color = rl.Color(255, 188, 0, 255) + else: + # Keep green/grey from above + pass + elif check_angle and not lat_active: + if abs(angle_steers) > 180: + color = rl.RED + elif abs(angle_steers) > 90: + color = rl.Color(255, 188, 0, 255) + + return color + + +class RelDistElement(LeadInfoElement): + def __init__(self): + self.unit = "m" + + def update(self, sm, is_metric: bool) -> UiElement: + lead_status, lead_d_rel, _ = self.get_lead_status(sm) + value = f"{lead_d_rel:.0f}" if lead_status else "-" + color = self.get_lead_color(lead_d_rel) if lead_status else rl.WHITE + return UiElement(value, "REL DIST", self.unit, color) + + +class RelSpeedElement(LeadInfoElement): + def __init__(self): + self.unit = "km/h" + + def update(self, sm, is_metric: bool) -> UiElement: + lead_status, _, lead_v_rel = self.get_lead_status(sm) + + self.unit = "km/h" if is_metric else "mph" + + conversion = CV.MS_TO_KPH if is_metric else CV.MS_TO_MPH + value = f"{lead_v_rel * conversion:.0f}" if lead_status else "-" + color = self.get_lead_color(0, lead_v_rel, use_v_rel=True) if lead_status else rl.WHITE + + return UiElement(value, "REL SPEED", self.unit, color) + + +class SteeringAngleElement(LateralControlElement): + def __init__(self): + self.unit = "" + + def update(self, sm, is_metric: bool) -> UiElement: + car_state = sm['carState'] + angle_steers = car_state.steeringAngleDeg + lat_active = sm['carControl'].latActive + steer_override = car_state.steeringPressed + + value = f"{angle_steers:.1f}°" + color = self.get_lat_color(lat_active, steer_override, angle_steers, check_angle=True) + + return UiElement(value, "REAL STEER", self.unit, color) + + +class DesiredSteeringAngleElement(LateralControlElement): + def __init__(self): + self.unit = "" + + def update(self, sm, is_metric: bool) -> UiElement: + car_state = sm['carState'] + controls_state = sm['controlsState'] + lat_active = sm['carControl'].latActive + angle_steers = car_state.steeringAngleDeg + steer_angle_desired = controls_state.lateralControlState.angleState.steeringAngleDeg + + value = f"{steer_angle_desired:.1f}°" if lat_active else "-" + + color = rl.WHITE + if lat_active: + if abs(angle_steers) > 180: + color = rl.RED + elif abs(angle_steers) > 90: + color = rl.Color(255, 188, 0, 255) + else: + color = rl.Color(0, 255, 0, 255) + + return UiElement(value, "DESIRED STEER", self.unit, color) + + +class ActualLateralAccelElement(LateralControlElement): + def __init__(self): + self.unit = "m/s^2" + + def update(self, sm, is_metric: bool) -> UiElement: + controls_state = sm['controlsState'] + curvature = controls_state.curvature + v_ego = sm['carState'].vEgo + roll = sm['liveParameters'].roll if sm.valid['liveParameters'] else 0.0 + lat_active = sm['carControl'].latActive + steer_override = sm['carState'].steeringPressed + + actual_lat_accel = (curvature * v_ego ** 2) - (roll * 9.81) + value = f"{actual_lat_accel:.2f}" + color = self.get_lat_color(lat_active, steer_override) + + return UiElement(value, "ACTUAL L.A.", self.unit, color) + + +class DesiredLateralAccelElement(LateralControlElement): + def __init__(self): + self.unit = "m/s^2" + + def update(self, sm, is_metric: bool) -> UiElement: + controls_state = sm['controlsState'] + desired_curvature = controls_state.desiredCurvature + v_ego = sm['carState'].vEgo + roll = sm['liveParameters'].roll if sm.valid['liveParameters'] else 0.0 + lat_active = sm['carControl'].latActive + steer_override = sm['carState'].steeringPressed + + desired_lat_accel = (desired_curvature * v_ego ** 2) - (roll * 9.81) + value = f"{desired_lat_accel:.2f}" if lat_active else "-" + color = self.get_lat_color(lat_active, steer_override) + + return UiElement(value, "DESIRED L.A.", self.unit, color) + + +class DesiredSteeringPIDElement(LateralControlElement): + def __init__(self): + self.unit = "" + + def update(self, sm, is_metric: bool) -> UiElement: + car_state = sm['carState'] + controls_state = sm['controlsState'] + lat_active = sm['carControl'].latActive + angle_steers = car_state.steeringAngleDeg + steer_angle_desired = controls_state.lateralControlState.pidState.steeringAngleDesiredDeg + + value = f"{steer_angle_desired:.1f}°" if lat_active else "-" + + color = rl.WHITE + if lat_active: + if abs(angle_steers) > 180: + color = rl.RED + elif abs(angle_steers) > 90: + color = rl.Color(255, 188, 0, 255) + else: + color = rl.Color(0, 255, 0, 255) + + return UiElement(value, "DESIRED STEER", self.unit, color) + + +class AEgoElement: + def __init__(self): + self.unit = "m/s^2" + + def update(self, sm, is_metric: bool) -> UiElement: + a_ego = sm['carState'].aEgo + value = f"{a_ego:.1f}" + return UiElement(value, "ACC.", self.unit, rl.WHITE) + + +class LeadSpeedElement(LeadInfoElement): + def __init__(self): + self.unit = "km/h" + + def update(self, sm, is_metric: bool) -> UiElement: + lead_status, _, lead_v_rel = self.get_lead_status(sm) + v_ego = sm['carState'].vEgo + + self.unit = "km/h" if is_metric else "mph" + + conversion = CV.MS_TO_KPH if is_metric else CV.MS_TO_MPH + value = f"{(lead_v_rel + v_ego) * conversion:.0f}" if lead_status else "-" + color = self.get_lead_color(0, lead_v_rel, use_v_rel=True) if lead_status else rl.WHITE + + return UiElement(value, "L.S.", self.unit, color) + + +class FrictionCoefficientElement: + def __init__(self): + self.unit = "" + + def update(self, sm, is_metric: bool) -> UiElement: + if ui_state.enforce_torque_control and ui_state.custom_torque_params and ui_state.torque_override_enabled: + return UiElement(f"{ui_state.torque_override_friction:.3f}", "FRIC.", self.unit, rl.WHITE) + + ltp = sm['liveTorqueParameters'] + value = f"{ltp.frictionCoefficientFiltered:.3f}" + color = rl.Color(0, 255, 0, 255) if ltp.liveValid else rl.WHITE + return UiElement(value, "FRIC.", self.unit, color) + + +class LatAccelFactorElement: + def __init__(self): + self.unit = "" + + def update(self, sm, is_metric: bool) -> UiElement: + if ui_state.enforce_torque_control and ui_state.custom_torque_params and ui_state.torque_override_enabled: + return UiElement(f"{ui_state.torque_override_lat_accel_factor:.3f}", "L.A.F.", self.unit, rl.WHITE) + + ltp = sm['liveTorqueParameters'] + value = f"{ltp.latAccelFactorFiltered:.3f}" + color = rl.Color(0, 255, 0, 255) if ltp.liveValid else rl.WHITE + return UiElement(value, "L.A.F.", self.unit, color) + + +class SteeringTorqueEpsElement: + def __init__(self): + self.unit = "N·dm" + + def update(self, sm, is_metric: bool) -> UiElement: + steering_torque_eps = sm['carState'].steeringTorqueEps + value = f"{abs(steering_torque_eps):.1f}" + return UiElement(value, "E.T.", self.unit, rl.WHITE) + + +class GpsInfoElement: + @staticmethod + def get_gps_data(sm): + if sm.valid['gpsLocationExternal']: + return sm['gpsLocationExternal'], True + elif sm.valid['gpsLocation']: + return sm['gpsLocation'], True + return None, False + + +class BearingDegElement(GpsInfoElement): + def __init__(self): + self.unit = "" + + def update(self, sm, is_metric: bool) -> UiElement: + gps_data, valid = self.get_gps_data(sm) + if not valid: + return UiElement("OFF | -", "B.D.", self.unit, rl.WHITE) + + bearing_accuracy_deg = gps_data.bearingAccuracyDeg + bearing_deg = gps_data.bearingDeg + + if bearing_accuracy_deg != 180.0: + value = f"{bearing_deg:.0f}°" + if (337.5 <= bearing_deg <= 360) or (0 <= bearing_deg <= 22.5): + dir_value = "N" + elif 22.5 < bearing_deg < 67.5: + dir_value = "NE" + elif 67.5 <= bearing_deg <= 112.5: + dir_value = "E" + elif 112.5 < bearing_deg < 157.5: + dir_value = "SE" + elif 157.5 <= bearing_deg <= 202.5: + dir_value = "S" + elif 202.5 < bearing_deg < 247.5: + dir_value = "SW" + elif 247.5 <= bearing_deg <= 292.5: + dir_value = "W" + else: # 292.5 < bearing_deg < 337.5 + dir_value = "NW" + else: + value = "-" + dir_value = "OFF" + + return UiElement(f"{dir_value} | {value}", "B.D.", self.unit, rl.WHITE) + + +class AltitudeElement(GpsInfoElement): + def __init__(self): + self.unit = "m" + + def update(self, sm, is_metric: bool) -> UiElement: + gps_data, valid = self.get_gps_data(sm) + + gps_accuracy = 0.0 + altitude = 0.0 + + if valid: + altitude = gps_data.altitude + if sm.valid['gpsLocationExternal']: + gps_accuracy = gps_data.horizontalAccuracy + else: + gps_accuracy = 1.0 # Simulate valid for legacy check + + value = f"{altitude:.1f}" if gps_accuracy != 0.0 else "-" + return UiElement(value, "ALT.", self.unit, rl.WHITE) diff --git a/openpilot/selfdrive/ui/sunnypilot/onroad/driver_state.py b/openpilot/selfdrive/ui/sunnypilot/onroad/driver_state.py new file mode 100644 index 0000000000..d3239b9e3d --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/onroad/driver_state.py @@ -0,0 +1,48 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import numpy as np + +from openpilot.selfdrive.ui import UI_BORDER_SIZE +from openpilot.selfdrive.ui.onroad.driver_state import DriverStateRenderer, BTN_SIZE, ARC_LENGTH +from openpilot.selfdrive.ui.sunnypilot.onroad.developer_ui import get_bottom_dev_ui_offset + + +class DriverStateRendererSP(DriverStateRenderer): + def __init__(self): + super().__init__() + + def _pre_calculate_drawing_elements(self): + """Pre-calculate all drawing elements based on the current rectangle""" + # Calculate icon position (bottom-left or bottom-right) + width, height = self._rect.width, self._rect.height + offset = UI_BORDER_SIZE + BTN_SIZE // 2 + self.position_x = self._rect.x + (width - offset if self.is_rhd else offset) + self.position_y = self._rect.y + height - offset - get_bottom_dev_ui_offset() + + # Pre-calculate the face lines positions + positioned_keypoints = self.face_keypoints_transformed + np.array([self.position_x, self.position_y]) + for i in range(len(positioned_keypoints)): + self.face_lines[i].x = positioned_keypoints[i][0] + self.face_lines[i].y = positioned_keypoints[i][1] + + # Calculate arc dimensions based on head rotation + delta_x = -self.driver_pose_sins[1] * ARC_LENGTH / 2.0 # Horizontal movement + delta_y = -self.driver_pose_sins[0] * ARC_LENGTH / 2.0 # Vertical movement + + # Horizontal arc + h_width = abs(delta_x) + self.h_arc_data = self._calculate_arc_data( + delta_x, h_width, self.position_x, self.position_y - ARC_LENGTH / 2, + self.driver_pose_sins[1], self.driver_pose_diff[1], is_horizontal=True + ) + + # Vertical arc + v_height = abs(delta_y) + self.v_arc_data = self._calculate_arc_data( + delta_y, v_height, self.position_x - ARC_LENGTH / 2, self.position_y, + self.driver_pose_sins[0], self.driver_pose_diff[0], is_horizontal=False + ) diff --git a/openpilot/selfdrive/ui/sunnypilot/onroad/hud_renderer.py b/openpilot/selfdrive/ui/sunnypilot/onroad/hud_renderer.py new file mode 100644 index 0000000000..f8e4257733 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/onroad/hud_renderer.py @@ -0,0 +1,146 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import pyray as rl + +from openpilot.common.constants import CV +from openpilot.selfdrive.ui.mici.onroad.torque_bar import TorqueBar +from openpilot.selfdrive.ui.sunnypilot.onroad.developer_ui import DeveloperUiRenderer, DeveloperUiState, get_bottom_dev_ui_offset +from openpilot.selfdrive.ui.sunnypilot.onroad.road_name import RoadNameRenderer +from openpilot.selfdrive.ui.sunnypilot.onroad.rocket_fuel import RocketFuel +from openpilot.selfdrive.ui.sunnypilot.onroad.speed_limit import SpeedLimitRenderer +from openpilot.selfdrive.ui.sunnypilot.onroad.smart_cruise_control import SmartCruiseControlRenderer +from openpilot.selfdrive.ui.sunnypilot.onroad.turn_signal import TurnSignalController +from openpilot.selfdrive.ui.sunnypilot.onroad.circular_alerts import CircularAlertsRenderer +from openpilot.selfdrive.ui.sunnypilot.onroad.speed_renderer import SpeedRenderer +from openpilot.selfdrive.ui.ui_state import ui_state, UIStatus +from openpilot.selfdrive.ui.onroad.hud_renderer import HudRenderer, UI_CONFIG, FONT_SIZES, COLORS, CRUISE_DISABLED_CHAR +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.lib.text_measure import measure_text_cached + +SLA_ACTIVE_COLOR = rl.Color(0x91, 0x9b, 0x95, 0xff) + + +class HudRendererSP(HudRenderer): + def __init__(self): + super().__init__() + self.developer_ui = DeveloperUiRenderer() + self.road_name_renderer = RoadNameRenderer() + self.rocket_fuel = RocketFuel() + self.speed_limit_renderer = SpeedLimitRenderer() + self.smart_cruise_control_renderer = SmartCruiseControlRenderer() + self.turn_signal_controller = TurnSignalController() + self.circular_alerts_renderer = CircularAlertsRenderer() + self.speed_renderer = SpeedRenderer() + self._torque_bar = TorqueBar(scale=3.0, always=True) + + self.pcm_cruise_speed: bool = True + self.show_icbm_status: bool = False + self.icbm_active_counter: int = 0 + self.speed_cluster: float = 0.0 + self.speed_conv: float = CV.MS_TO_KPH if ui_state.is_metric else CV.MS_TO_MPH + + def _update_state(self) -> None: + if ui_state.sm.recv_frame["carState"] < ui_state.started_frame: + return + + if ui_state.CP_SP is not None: + self.pcm_cruise_speed = ui_state.CP_SP.pcmCruiseSpeed + self.speed_conv = CV.MS_TO_KPH if ui_state.is_metric else CV.MS_TO_MPH + self.speed_cluster = ui_state.sm['carState'].cruiseState.speedCluster * self.speed_conv + + super()._update_state() + self.road_name_renderer.update() + self.speed_limit_renderer.update() + self.smart_cruise_control_renderer.update() + self.turn_signal_controller.update() + self.circular_alerts_renderer.update() + self.speed_renderer.update() + + def _get_icbm_status(self): + if not self.pcm_cruise_speed and ui_state.sm['carControl'].enabled: + if round(self.set_speed) != round(self.speed_cluster): + self.icbm_active_counter = 3 * gui_app.target_fps # 3 seconds usually + elif self.icbm_active_counter > 0: + self.icbm_active_counter -= 1 + else: + self.icbm_active_counter = 0 + + self.show_icbm_status = self.icbm_active_counter > 0 + + def _draw_set_speed(self, rect: rl.Rectangle) -> None: + long_plan_sp = ui_state.sm['longitudinalPlanSP'] + long_override = ui_state.sm['carControl'].cruiseControl.override + self._get_icbm_status() + + set_speed_width = UI_CONFIG.set_speed_width_metric if ui_state.is_metric else UI_CONFIG.set_speed_width_imperial + x = rect.x + 60 + (UI_CONFIG.set_speed_width_imperial - set_speed_width) // 2 + y = rect.y + 45 + + set_speed_rect = rl.Rectangle(x, y, set_speed_width, UI_CONFIG.set_speed_height) + rl.draw_rectangle_rounded(set_speed_rect, 0.35, 10, COLORS.BLACK_TRANSLUCENT) + rl.draw_rectangle_rounded_lines_ex(set_speed_rect, 0.35, 10, 6, COLORS.BORDER_TRANSLUCENT) + + max_color = COLORS.GREY + set_speed_color = COLORS.DARK_GREY + if self.is_cruise_set: + set_speed_color = COLORS.WHITE + if long_plan_sp.speedLimit.assist.active: + set_speed_color = SLA_ACTIVE_COLOR if long_override else rl.Color(0, 0xff, 0, 0xff) + max_color = SLA_ACTIVE_COLOR if long_override else rl.Color(0x80, 0xd8, 0xa6, 0xff) + else: + if ui_state.status == UIStatus.ENGAGED: + max_color = COLORS.ENGAGED + elif ui_state.status == UIStatus.DISENGAGED: + max_color = COLORS.DISENGAGED + elif ui_state.status == UIStatus.OVERRIDE: + max_color = COLORS.OVERRIDE + + max_str_size = 60 if self.show_icbm_status else 40 + max_str_y = 15 if self.show_icbm_status else 27 + + max_text = str(round(self.speed_cluster)) if self.show_icbm_status else tr("MAX") + max_text_width = measure_text_cached(self._font_semi_bold, max_text, max_str_size).x + rl.draw_text_ex( + self._font_semi_bold, + max_text, + rl.Vector2(x + (set_speed_width - max_text_width) / 2, y + max_str_y), + max_str_size, + 0, + max_color, + ) + + set_speed_text = CRUISE_DISABLED_CHAR if not self.is_cruise_set else str(round(self.set_speed)) + speed_text_width = measure_text_cached(self._font_bold, set_speed_text, FONT_SIZES.set_speed).x + rl.draw_text_ex( + self._font_bold, + set_speed_text, + rl.Vector2(x + (set_speed_width - speed_text_width) / 2, y + 77), + FONT_SIZES.set_speed, + 0, + set_speed_color, + ) + + def _draw_current_speed(self, rect: rl.Rectangle) -> None: + self.speed_renderer.render(rect) + + def _render(self, rect: rl.Rectangle) -> None: + super()._render(rect) + + if ui_state.torque_bar: + torque_rect = rect + if ui_state.developer_ui in (DeveloperUiState.BOTTOM, DeveloperUiState.BOTH): + torque_rect = rl.Rectangle(rect.x, rect.y, rect.width, rect.height - get_bottom_dev_ui_offset()) + self._torque_bar.render(torque_rect) + + self.developer_ui.render(rect) + self.road_name_renderer.render(rect) + self.speed_limit_renderer.render(rect) + self.smart_cruise_control_renderer.render(rect) + self.turn_signal_controller.render(rect) + self.circular_alerts_renderer.render(rect) + self.rocket_fuel.render(rect, ui_state.sm) diff --git a/openpilot/selfdrive/ui/sunnypilot/onroad/model_renderer.py b/openpilot/selfdrive/ui/sunnypilot/onroad/model_renderer.py new file mode 100644 index 0000000000..5d78997662 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/onroad/model_renderer.py @@ -0,0 +1,14 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from openpilot.selfdrive.ui.sunnypilot.onroad.chevron_metrics import ChevronMetrics +from openpilot.selfdrive.ui.sunnypilot.onroad.rainbow_path import RainbowPath + + +class ModelRendererSP: + def __init__(self): + self.rainbow_path = RainbowPath() + self.chevron_metrics = ChevronMetrics() diff --git a/openpilot/selfdrive/ui/sunnypilot/onroad/rainbow_path.py b/openpilot/selfdrive/ui/sunnypilot/onroad/rainbow_path.py new file mode 100644 index 0000000000..de383a659d --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/onroad/rainbow_path.py @@ -0,0 +1,79 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import time +import colorsys +import pyray as rl +from openpilot.system.ui.lib.shader_polygon import draw_polygon, Gradient + + +class RainbowPath: + DEFAULT_NUM_SEGMENTS = 8 + DEFAULT_SPEED = 50.0 # degrees per second + DEFAULT_SATURATION = 0.9 + DEFAULT_LIGHTNESS = 0.6 + BASE_ALPHA = 0.8 + ALPHA_FADE = 0.3 # Alpha reduction from bottom to top + + def __init__(self, num_segments: int = DEFAULT_NUM_SEGMENTS, speed: float = DEFAULT_SPEED, + saturation: float = DEFAULT_SATURATION, lightness: float = DEFAULT_LIGHTNESS): + self.num_segments = num_segments + self.speed = speed + self.saturation = saturation + self.lightness = lightness + + def set_speed(self, speed: float): + self.speed = speed + + def set_num_segments(self, num_segments: int): + self.num_segments = num_segments + + def set_saturation(self, saturation: float): + self.saturation = max(0.0, min(1.0, saturation)) + + def set_lightness(self, lightness: float): + self.lightness = max(0.0, min(1.0, lightness)) + + def get_gradient(self) -> Gradient: + time_offset = time.monotonic() + hue_offset = (time_offset * self.speed) % 360.0 + + segment_colors = [] + gradient_stops = [] + + for i in range(self.num_segments): + position = i / (self.num_segments - 1) + hue = (hue_offset + position * 360.0) % 360.0 + alpha = self.BASE_ALPHA * (1.0 - position * self.ALPHA_FADE) + color = self._hsla_to_color( + hue / 360.0, + self.saturation, + self.lightness, + alpha + ) + gradient_stops.append(position) + segment_colors.append(color) + + return Gradient( + start=(0.0, 1.0), # Bottom of path + end=(0.0, 0.0), # Top of path + colors=segment_colors, + stops=gradient_stops, + ) + + @staticmethod + def _hsla_to_color(h: float, s: float, l: float, a: float) -> rl.Color: + rgb = colorsys.hls_to_rgb(h, l, s) + return rl.Color( + int(rgb[0] * 255), + int(rgb[1] * 255), + int(rgb[2] * 255), + int(a * 255) + ) + + def draw_rainbow_path(self, rect, path): + gradient = self.get_gradient() + draw_polygon(rect, path.projected_points, gradient=gradient) diff --git a/openpilot/selfdrive/ui/sunnypilot/onroad/road_name.py b/openpilot/selfdrive/ui/sunnypilot/onroad/road_name.py new file mode 100644 index 0000000000..f85285ef53 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/onroad/road_name.py @@ -0,0 +1,56 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import pyray as rl + +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.widgets import Widget + + +class RoadNameRenderer(Widget): + def __init__(self): + super().__init__() + self.road_name = "" + self.is_metric = False + self.font_demi = gui_app.font(FontWeight.SEMI_BOLD) + + def update(self): + sm = ui_state.sm + if sm.recv_frame["carState"] < ui_state.started_frame: + return + + self.is_metric = ui_state.is_metric + + if sm.updated["liveMapDataSP"]: + lmd = sm["liveMapDataSP"] + self.road_name = lmd.roadName + + def _render(self, rect: rl.Rectangle): + if not self.road_name or not ui_state.road_name_toggle: + return + + text = self.road_name + text_size = measure_text_cached(self.font_demi, text, 46) + + padding = 40 + rect_width = max(200, min(text_size.x + padding, rect.width - 40)) + + road_rect = rl.Rectangle(rect.x + rect.width / 2 - rect_width / 2, rect.y - 4, rect_width, 60) + + rl.draw_rectangle_rounded(road_rect, 0.2, 10, rl.Color(0, 0, 0, 120)) + + max_text_width = road_rect.width - 20 + if text_size.x > max_text_width: + while text_size.x > max_text_width and len(text) > 3: + text = text[:-1] + text_size = measure_text_cached(self.font_demi, text + "...", 46) + text = text + "..." + + sz = measure_text_cached(self.font_demi, text, 46) + origin = rl.Vector2(road_rect.x + road_rect.width / 2 - sz.x / 2, road_rect.y + road_rect.height / 2 - sz.y / 2) + rl.draw_text_ex(self.font_demi, text, origin, 46, 0, rl.Color(255, 255, 255, 200)) diff --git a/openpilot/selfdrive/ui/sunnypilot/onroad/rocket_fuel.py b/openpilot/selfdrive/ui/sunnypilot/onroad/rocket_fuel.py new file mode 100644 index 0000000000..cb1012890e --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/onroad/rocket_fuel.py @@ -0,0 +1,50 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import pyray as rl + +from openpilot.selfdrive.ui.ui_state import ui_state + + +class RocketFuel: + def __init__(self): + self.vc_accel = 0.0 + + def render(self, rect: rl.Rectangle, sm) -> None: + if not ui_state.rocket_fuel: + return + + vc_accel0 = sm['carState'].aEgo + + # Smooth the acceleration + self.vc_accel = self.vc_accel + (vc_accel0 - self.vc_accel) / 5.0 + + hha = 0.0 + color = rl.Color(0, 0, 0, 0) # Transparent by default + + if self.vc_accel > 0: + hha = 0.85 - 0.1 / self.vc_accel # only extend up to 85% + color = rl.Color(0, 245, 0, 200) + elif self.vc_accel < 0: + hha = 0.85 + 0.1 / self.vc_accel # only extend up to 85% + color = rl.Color(245, 0, 0, 200) + + if hha < 0: + hha = 0.0 + + hha = hha * rect.height + wp = 28.0 + + # Draw + rect_h = rect.height + + if self.vc_accel > 0: + ra_y = rect_h / 2.0 - hha / 2.0 + else: + ra_y = rect_h / 2.0 + + if hha > 0: + rl.draw_rectangle(int(rect.x), int(rect.y + ra_y), int(wp), int(hha / 2.0), color) diff --git a/openpilot/selfdrive/ui/sunnypilot/onroad/smart_cruise_control.py b/openpilot/selfdrive/ui/sunnypilot/onroad/smart_cruise_control.py new file mode 100644 index 0000000000..c89bd914be --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/onroad/smart_cruise_control.py @@ -0,0 +1,105 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import pyray as rl + +from openpilot.selfdrive.ui.onroad.hud_renderer import COLORS +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.sunnypilot.lib.utils import AlertFadeAnimator +from openpilot.system.ui.widgets import Widget + + +class SmartCruiseControlRenderer(Widget): + def __init__(self): + super().__init__() + self.vision_enabled = False + self.vision_active = False + self.map_enabled = False + self.map_active = False + self.long_override = False + + self._vision_fade = AlertFadeAnimator(gui_app.target_fps) + self._map_fade = AlertFadeAnimator(gui_app.target_fps) + + self.font = gui_app.font(FontWeight.BOLD) + + def update(self): + sm = ui_state.sm + if sm.updated["longitudinalPlanSP"]: + lp_sp = sm["longitudinalPlanSP"] + vision = lp_sp.smartCruiseControl.vision + map_ = lp_sp.smartCruiseControl.map + + self.vision_enabled = vision.enabled + self.vision_active = vision.active + self.map_enabled = map_.enabled + self.map_active = map_.active + + if sm.updated["carControl"]: + self.long_override = sm["carControl"].cruiseControl.override + + self._vision_fade.update(self.vision_active) + self._map_fade.update(self.map_active) + + def _draw_icon(self, rect_center_x, rect_height, x_offset, y_offset, name, alpha=1.0): + text = name + font_size = 36 + padding_v = 5 + box_width = 160 + + sz = measure_text_cached(self.font, text, font_size) + box_height = int(sz.y + padding_v * 2) + + if self.long_override: + color = COLORS.OVERRIDE + box_color = rl.Color(color.r, color.g, color.b, int(alpha * 255)) + else: + box_color = rl.Color(0, 255, 0, int(alpha * 255)) + + text_color = rl.Color(0, 0, 0, int(alpha * 255)) + + screen_y = rect_height / 4 + y_offset + + box_x = rect_center_x + x_offset - box_width / 2 + box_y = screen_y - box_height / 2 + + # Draw rounded background box + if alpha > 0.01: + rl.draw_rectangle_rounded(rl.Rectangle(box_x, box_y, box_width, box_height), 0.2, 10, box_color) + + # Draw text centered in the box (black color for contrast against bright green/grey) + text_pos_x = box_x + (box_width - sz.x) / 2 + text_pos_y = box_y + (box_height - sz.y) / 2 + + rl.draw_text_ex(self.font, text, rl.Vector2(text_pos_x, text_pos_y), font_size, 0, text_color) + + def _render(self, rect: rl.Rectangle): + x_offset = -260 + y1_offset = -40 + y2_offset = -100 + + orders = [y1_offset, y2_offset] + y_scc_v = 0 + y_scc_m = 0 + idx = 0 + + if self.vision_enabled: + y_scc_v = orders[idx] + idx += 1 + + if self.map_enabled: + y_scc_m = orders[idx] + idx += 1 + + if self.vision_enabled: + alpha = self._vision_fade.alpha if self.vision_active else 1.0 + self._draw_icon(rect.x + rect.width / 2, rect.height, x_offset, y_scc_v, "SCC-V", alpha) + + if self.map_enabled: + alpha = self._map_fade.alpha if self.map_active else 1.0 + self._draw_icon(rect.x + rect.width / 2, rect.height, x_offset, y_scc_m, "SCC-M", alpha) diff --git a/openpilot/selfdrive/ui/sunnypilot/onroad/speed_limit.py b/openpilot/selfdrive/ui/sunnypilot/onroad/speed_limit.py new file mode 100644 index 0000000000..fa8143eb32 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/onroad/speed_limit.py @@ -0,0 +1,328 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" + +from dataclasses import dataclass +from enum import StrEnum +import pyray as rl + +from openpilot.cereal import custom +from openpilot.common.constants import CV +from openpilot.selfdrive.ui.onroad.hud_renderer import UI_CONFIG +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.sunnypilot.selfdrive.controls.lib.speed_limit.common import Mode as SpeedLimitMode +from openpilot.common.hardware import HARDWARE +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.sunnypilot.lib.utils import AlertFadeAnimator +from openpilot.system.ui.widgets import Widget + +METER_TO_FOOT = 3.28084 +METER_TO_MILE = 0.000621371 +AHEAD_THRESHOLD = 5 +SET_SPEED_NA = 255 +KM_TO_MILE = 0.621371 + +AssistState = custom.LongitudinalPlanSP.SpeedLimit.AssistState +SpeedLimitSource = custom.LongitudinalPlanSP.SpeedLimit.Source + + +@dataclass(frozen=True) +class Colors: + WHITE = rl.WHITE + BLACK = rl.BLACK + RED = rl.Color(235, 32, 32, 255) + GREY = rl.Color(145, 155, 149, 255) + DARK_GREY = rl.Color(77, 77, 77, 255) + SUB_BG = rl.Color(0, 0, 0, 180) + MUTCD_LINES = rl.Color(255, 255, 255, 100) + + +class IconSide(StrEnum): + left = 'left' + right = 'right' + + +class SpeedLimitAlertRenderer: + ARROW_SIZE = 90 if HARDWARE.get_device_type() == 'mici' else 200 + + def __init__(self): + self.arrow_up = gui_app.texture("../../sunnypilot/selfdrive/assets/img_plus_arrow_up.png", self.ARROW_SIZE, self.ARROW_SIZE) + self.arrow_down = gui_app.texture("../../sunnypilot/selfdrive/assets/img_minus_arrow_down.png", self.ARROW_SIZE, self.ARROW_SIZE) + + blank_image = rl.gen_image_color(self.ARROW_SIZE, self.ARROW_SIZE, rl.Color(0, 0, 0, 0)) + self.arrow_blank = rl.load_texture_from_image(blank_image) + rl.unload_image(blank_image) + + self._pre_active_fade = AlertFadeAnimator(gui_app.target_fps, duration_on=0.75, rc=0.05) + + def update(self): + assist_state = ui_state.sm['longitudinalPlanSP'].speedLimit.assist.state + self._pre_active_fade.update(assist_state == AssistState.preActive) + + def speed_limit_pre_active_icon_helper(self): + icon_alpha = max(0.0, min(self._pre_active_fade.alpha * 255.0, 255.0)) + txt_icon = self.arrow_blank + icon_margin_x = 10 + icon_margin_y = 18 + + if icon_alpha > 0: + speed_conv = CV.MS_TO_KPH if ui_state.is_metric else CV.MS_TO_MPH + speed_limit_final_last = ui_state.sm['longitudinalPlanSP'].speedLimit.resolver.speedLimitFinalLast + + v_cruise_cluster = ui_state.sm['carState'].vCruiseCluster + set_speed = ui_state.sm['controlsState'].deprecated.vCruise if v_cruise_cluster == 0.0 else v_cruise_cluster + if not ui_state.is_metric: + set_speed *= KM_TO_MILE + + set_speed_round = round(set_speed) + speed_limit_round = round(speed_limit_final_last * speed_conv) + + if set_speed_round < speed_limit_round: + txt_icon = self.arrow_up + elif set_speed_round > speed_limit_round: + txt_icon = self.arrow_down + + return IconSide.right, txt_icon, icon_alpha, icon_margin_x, icon_margin_y + + +class SpeedLimitRenderer(Widget, SpeedLimitAlertRenderer): + def __init__(self): + Widget.__init__(self) + SpeedLimitAlertRenderer.__init__(self) + + self.speed_limit = 0.0 + self.speed_limit_last = 0.0 + self.speed_limit_offset = 0.0 + self.speed_limit_valid = False + self.speed_limit_last_valid = False + self.speed_limit_final_last = 0.0 + self.speed_limit_source = SpeedLimitSource.none + self.speed_limit_assist_state = AssistState.disabled + + self.speed_limit_ahead = 0.0 + self.speed_limit_ahead_dist = 0.0 + self.speed_limit_ahead_dist_prev = 0.0 + self.speed_limit_ahead_valid = False + self.speed_limit_ahead_frame = 0 + + self.is_cruise_set: bool = False + self.is_cruise_available: bool = True + self.set_speed: float = SET_SPEED_NA + self.speed: float = 0.0 + self.v_ego_cluster_seen: bool = False + + self.font_bold = gui_app.font(FontWeight.BOLD) + self.font_demi = gui_app.font(FontWeight.SEMI_BOLD) + self.font_norm = gui_app.font(FontWeight.NORMAL) + + @property + def speed_conv(self): + return CV.MS_TO_KPH if ui_state.is_metric else CV.MS_TO_MPH + + def update(self): + SpeedLimitAlertRenderer.update(self) + sm = ui_state.sm + if sm.recv_frame["carState"] < ui_state.started_frame: + self.set_speed = SET_SPEED_NA + self.speed = 0.0 + return + + if sm.updated["longitudinalPlanSP"]: + lp_sp = sm["longitudinalPlanSP"] + resolver = lp_sp.speedLimit.resolver + assist = lp_sp.speedLimit.assist + + self.speed_limit = resolver.speedLimit * self.speed_conv + self.speed_limit_last = resolver.speedLimitLast * self.speed_conv + self.speed_limit_offset = resolver.speedLimitOffset * self.speed_conv + self.speed_limit_valid = resolver.speedLimitValid + self.speed_limit_last_valid = resolver.speedLimitLastValid + self.speed_limit_final_last = resolver.speedLimitFinalLast * self.speed_conv + self.speed_limit_source = resolver.source + self.speed_limit_assist_state = assist.state + + if sm.updated["liveMapDataSP"]: + lmd = sm["liveMapDataSP"] + self.speed_limit_ahead_valid = lmd.speedLimitAheadValid + self.speed_limit_ahead = lmd.speedLimitAhead * self.speed_conv + self.speed_limit_ahead_dist = lmd.speedLimitAheadDistance + + if self.speed_limit_ahead_dist < self.speed_limit_ahead_dist_prev and self.speed_limit_ahead_frame < AHEAD_THRESHOLD: + self.speed_limit_ahead_frame += 1 + elif self.speed_limit_ahead_dist > self.speed_limit_ahead_dist_prev and self.speed_limit_ahead_frame > 0: + self.speed_limit_ahead_frame -= 1 + + self.speed_limit_ahead_dist_prev = self.speed_limit_ahead_dist + + controls_state = sm['controlsState'] + car_state = sm["carState"] + + v_cruise_cluster = car_state.vCruiseCluster + self.set_speed = ( + controls_state.deprecated.vCruise if v_cruise_cluster == 0.0 else v_cruise_cluster + ) + self.is_cruise_set = 0 < self.set_speed < SET_SPEED_NA + self.is_cruise_available = self.set_speed != -1 + + if self.is_cruise_set and not ui_state.is_metric: + self.set_speed *= KM_TO_MILE + + self.v_ego_cluster_seen = self.v_ego_cluster_seen or car_state.vEgoCluster != 0.0 + v_ego = car_state.vEgoCluster if self.v_ego_cluster_seen else car_state.vEgo + self.speed = max(0.0, v_ego * self.speed_conv) + + @staticmethod + def _draw_text_centered(font, text, size, pos_center, color): + sz = measure_text_cached(font, text, size) + rl.draw_text_ex(font, text, rl.Vector2(pos_center.x - sz.x / 2, pos_center.y - sz.y / 2), size, 0, color) + + def _render(self, rect: rl.Rectangle): + width = UI_CONFIG.set_speed_width_metric if ui_state.is_metric else UI_CONFIG.set_speed_width_imperial + x = rect.x + 60 + width + 30 - 6 + y = rect.y + 45 - 6 + + sign_rect = rl.Rectangle(x, y, width, UI_CONFIG.set_speed_height + 6 * 2) + + alpha = self._pre_active_fade.alpha + + if ui_state.speed_limit_mode != SpeedLimitMode.off: + self._draw_sign_main(sign_rect, alpha) + if self.speed_limit_assist_state == AssistState.preActive: + self._draw_pre_active_arrow(sign_rect) + else: + self._draw_ahead_info(sign_rect) + + def _draw_sign_main(self, rect, alpha=1.0): + speed_limit_warning_enabled = ui_state.speed_limit_mode is not None and ui_state.speed_limit_mode >= SpeedLimitMode.warning + has_limit = self.speed_limit_valid or self.speed_limit_last_valid + is_overspeed = has_limit and round(self.speed_limit_final_last) < round(self.speed) + + limit_str = str(round(self.speed_limit_last)) if has_limit else "---" + sub_text = "" + if self.speed_limit_offset != 0: + sign = "" if self.speed_limit_offset > 0 else "-" + sub_text = f"{sign}{round(abs(self.speed_limit_offset))}" + + txt_color = Colors.BLACK + if speed_limit_warning_enabled and is_overspeed: + txt_color = Colors.RED + elif not self.speed_limit_valid: + txt_color = Colors.GREY + + if ui_state.is_metric: + self._render_vienna(rect, limit_str, sub_text, txt_color, has_limit, alpha) + else: + self._render_mutcd(rect, limit_str, sub_text, txt_color, has_limit, alpha) + + def _draw_pre_active_arrow(self, sign_rect): + _, txt_icon, icon_alpha, _, _ = SpeedLimitAlertRenderer.speed_limit_pre_active_icon_helper(self) + if icon_alpha > 0 and txt_icon != self.arrow_blank: + sign_margin = 12 + arrow_spacing = int(sign_margin * 1.4) + arrow_x = sign_rect.x + sign_rect.width + arrow_spacing + arrow_y = sign_rect.y + (sign_rect.height - txt_icon.height) / 2 + color = rl.Color(255, 255, 255, int(icon_alpha)) + rl.draw_texture_ex(txt_icon, rl.Vector2(arrow_x, arrow_y), 0.0, 1.0, color) + + def _render_vienna(self, rect, val, sub, color, has_limit, alpha=1.0): + center = rl.Vector2(rect.x + rect.width / 2, rect.y + rect.height / 2) + radius = (rect.width + 18) / 2 + + white = rl.color_alpha(Colors.WHITE, alpha) + red = rl.color_alpha(Colors.RED, alpha) + black = rl.color_alpha(Colors.BLACK, alpha) + dark_grey = rl.color_alpha(Colors.DARK_GREY, alpha) + text_color = rl.color_alpha(color, alpha) + + rl.draw_circle_v(center, radius, white) + rl.draw_ring(center, radius * 0.75, radius, 0, 360, 36, red) + + font_size = 70 if len(val) >= 3 else 85 + self._draw_text_centered(self.font_bold, val, font_size, center, text_color) + + if sub and has_limit: + s_radius = radius * 0.4 + s_center = rl.Vector2(rect.x + rect.width - s_radius / 2, rect.y + s_radius / 2) + + rl.draw_circle_v(s_center, s_radius, black) + rl.draw_ring(s_center, s_radius - 3, s_radius, 0, 360, 36, dark_grey) + + font_scale = 0.5 if len(sub) < 3 else 0.45 + self._draw_text_centered(self.font_bold, sub, int(s_radius * 2 * font_scale), s_center, white) + + def _render_mutcd(self, rect, val, sub, color, has_limit, alpha=1.0): + white = rl.color_alpha(Colors.WHITE, alpha) + black = rl.color_alpha(Colors.BLACK, alpha) + dark_grey = rl.color_alpha(Colors.DARK_GREY, alpha) + text_color = rl.color_alpha(color, alpha) + + rl.draw_rectangle_rounded(rect, 0.35, 10, white) + + inner = rl.Rectangle(rect.x + 10, rect.y + 10, rect.width - 20, rect.height - 20) + outer_radius = 0.35 * rect.width / 2.0 + inner_radius = outer_radius - 10.0 + inner_roundness = inner_radius / (inner.width / 2.0) + + rl.draw_rectangle_rounded_lines_ex(inner, inner_roundness, 10, 4, black) + + self._draw_text_centered(self.font_demi, "SPEED", 40, rl.Vector2(rect.x + rect.width / 2, rect.y + 40), black) + self._draw_text_centered(self.font_demi, "LIMIT", 40, rl.Vector2(rect.x + rect.width / 2, rect.y + 80), black) + self._draw_text_centered(self.font_bold, val, 90, rl.Vector2(rect.x + rect.width / 2, rect.y + 150), text_color) + + if sub and has_limit: + box_sz = rect.width * 0.3 + overlap = box_sz * 0.2 + s_rect = rl.Rectangle(rect.x + rect.width - box_sz / 1.5 + overlap, rect.y - box_sz / 1.25 + overlap, box_sz, box_sz) + + rl.draw_rectangle_rounded(s_rect, 0.35, 10, black) + rl.draw_rectangle_rounded_lines_ex(s_rect, 0.35, 10, 6, dark_grey) + + f_scale = 0.6 if len(sub) < 3 else 0.475 + self._draw_text_centered(self.font_bold, sub, int(box_sz * f_scale), rl.Vector2(s_rect.x + box_sz / 2, s_rect.y + box_sz / 2), white) + + def _draw_ahead_info(self, sign_rect): + source_is_map = self.speed_limit_source == SpeedLimitSource.map + valid = self.speed_limit_ahead_valid and self.speed_limit_ahead > 0 and self.speed_limit_ahead != self.speed_limit + + if not (valid and source_is_map): + return + + rect = rl.Rectangle(sign_rect.x + (sign_rect.width - 170) / 2, sign_rect.y + sign_rect.height + 10, 170, 160) + rl.draw_rectangle_rounded(rect, 0.35, 10, Colors.SUB_BG) + rl.draw_rectangle_rounded_lines_ex(rect, 0.35, 10, 3, Colors.MUTCD_LINES) + + mid_x = rect.x + rect.width / 2 + self._draw_text_centered(self.font_demi, "AHEAD", 40, rl.Vector2(mid_x, rect.y + 28), Colors.GREY) + self._draw_text_centered(self.font_bold, str(round(self.speed_limit_ahead)), 70, rl.Vector2(mid_x, rect.y + 82), Colors.WHITE) + self._draw_text_centered(self.font_norm, self._format_dist(self.speed_limit_ahead_dist), 36, rl.Vector2(mid_x, rect.y + 134), Colors.GREY) + + @staticmethod + def _format_dist(d): + # metric + if ui_state.is_metric: + if d < 50: + return tr("Near") + + if d >= 1000: + return f"{d / 1000:.1f} km" + + d_rounded = round(d, -1) if d < 200 else round(d, -2) + return f"{int(d_rounded)} m" + + # imperial + d_ft = d * METER_TO_FOOT + if d_ft < 100: + return tr("Near") + + if d_ft >= 900: + return f"{d * METER_TO_MILE:.1f} mi" + + if d_ft < 500: + return f"{int(round(d_ft / 50) * 50)} ft" + + return f"{int(round(d_ft / 100) * 100)} ft" diff --git a/openpilot/selfdrive/ui/sunnypilot/onroad/speed_renderer.py b/openpilot/selfdrive/ui/sunnypilot/onroad/speed_renderer.py new file mode 100644 index 0000000000..0a017876e1 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/onroad/speed_renderer.py @@ -0,0 +1,46 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import pyray as rl + +from openpilot.common.constants import CV +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.selfdrive.ui.onroad.hud_renderer import FONT_SIZES, COLORS + + +class SpeedRenderer: + def __init__(self): + self.speed: float = 0.0 + self.v_ego_cluster_seen: bool = False + + self._font_bold: rl.Font = gui_app.font(FontWeight.BOLD) + self._font_medium: rl.Font = gui_app.font(FontWeight.MEDIUM) + + def update(self) -> None: + car_state = ui_state.sm['carState'] + v_ego_cluster = car_state.vEgoCluster + self.v_ego_cluster_seen = self.v_ego_cluster_seen or v_ego_cluster != 0.0 + v_ego = v_ego_cluster if self.v_ego_cluster_seen and not ui_state.true_v_ego_ui else car_state.vEgo + speed_conversion = CV.MS_TO_KPH if ui_state.is_metric else CV.MS_TO_MPH + self.speed = max(0.0, v_ego * speed_conversion) + + def render(self, rect: rl.Rectangle) -> None: + if ui_state.hide_v_ego_ui: + return + + # Draw current speed and unit + speed_text = str(round(self.speed)) + speed_text_size = measure_text_cached(self._font_bold, speed_text, FONT_SIZES.current_speed) + speed_pos = rl.Vector2(rect.x + rect.width / 2 - speed_text_size.x / 2, 180 - speed_text_size.y / 2) + rl.draw_text_ex(self._font_bold, speed_text, speed_pos, FONT_SIZES.current_speed, 0, COLORS.WHITE) + + unit_text = tr("km/h") if ui_state.is_metric else tr("mph") + unit_text_size = measure_text_cached(self._font_medium, unit_text, FONT_SIZES.speed_unit) + unit_pos = rl.Vector2(rect.x + rect.width / 2 - unit_text_size.x / 2, 290 - unit_text_size.y / 2) + rl.draw_text_ex(self._font_medium, unit_text, unit_pos, FONT_SIZES.speed_unit, 0, COLORS.WHITE_TRANSLUCENT) diff --git a/openpilot/selfdrive/ui/sunnypilot/onroad/turn_signal.py b/openpilot/selfdrive/ui/sunnypilot/onroad/turn_signal.py new file mode 100644 index 0000000000..fc6f7eb915 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/onroad/turn_signal.py @@ -0,0 +1,119 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import pyray as rl +import time +from dataclasses import dataclass + +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.selfdrive.ui.mici.onroad.alert_renderer import IconSide, TURN_SIGNAL_BLINK_PERIOD +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.widgets import Widget +from openpilot.common.filter_simple import FirstOrderFilter + + +@dataclass(frozen=True) +class TurnSignalConfig: + left_x: int = 80 + left_y: int = 190 + right_x: int = 80 + right_y: int = 190 + size: int = 150 + + +class TurnSignalWidget(Widget): + def __init__(self, direction: IconSide): + super().__init__() + self._direction = direction + self._active = False + self._type = 'signal' + + self._turn_signal_timer = 0.0 + self._turn_signal_alpha_filter = FirstOrderFilter(0.0, 0.3, 1 / gui_app.target_fps) + + self._signal_texture = gui_app.texture('icons_mici/onroad/turn_signal_left.png', 120, 109, flip_x=(direction == IconSide.right)) + self._blind_spot_texture = gui_app.texture('icons_mici/onroad/blind_spot_left.png', 120, 109, flip_x=(direction == IconSide.right)) + self._texture = self._signal_texture + + def _render(self, _): + if not self._active: + return + + if self._type == 'signal': + if time.monotonic() - self._turn_signal_timer > TURN_SIGNAL_BLINK_PERIOD: + self._turn_signal_timer = time.monotonic() + self._turn_signal_alpha_filter.x = 255 * 2 + else: + self._turn_signal_alpha_filter.update(255 * 0.2) + icon_alpha = int(min(self._turn_signal_alpha_filter.x, 255)) + else: + icon_alpha = 255 + + self._texture = self._blind_spot_texture if self._type == 'blind_spot' else self._signal_texture + + if self._texture: + pos_x = self._rect.x + (self._rect.width - self._texture.width) / 2 + pos_y = self._rect.y + (self._rect.height - self._texture.height) / 2 + color = rl.Color(255, 255, 255, icon_alpha) + rl.draw_texture_ex(self._texture, rl.Vector2(pos_x, pos_y), 0.0, 1.0, color) + + def activate(self, _type: str = 'signal'): + if not self._active or self._type != _type: + self._turn_signal_timer = 0.0 + self._active = True + self._type = _type + + def deactivate(self): + self._active = False + self._turn_signal_timer = 0.0 + + +class TurnSignalController: + def __init__(self): + self._config = TurnSignalConfig() + self._left_signal = TurnSignalWidget(direction=IconSide.left) + self._right_signal = TurnSignalWidget(direction=IconSide.right) + + @staticmethod + def _update_signal(signal, blindspot, blinker): + if ui_state.blindspot and blindspot: + signal.activate('blind_spot') + elif ui_state.turn_signals and blinker: + signal.activate('signal') + else: + signal.deactivate() + + def update(self): + CS = ui_state.sm['carState'] + + self._update_signal(self._left_signal, CS.leftBlindspot, CS.leftBlinker) + self._update_signal(self._right_signal, CS.rightBlindspot, CS.rightBlinker) + + def render(self, rect: rl.Rectangle): + if not ui_state.turn_signals and not ui_state.blindspot: + return + + x = rect.x + rect.width / 2 + + left_x = x - self._config.left_x - self._config.size + left_y = rect.y + self._config.left_y + + right_x = x + self._config.right_x + right_y = rect.y + self._config.right_y + + if self._left_signal._active: + self._left_signal.render(rl.Rectangle(left_x, left_y, self._config.size, self._config.size)) + + if self._right_signal._active: + self._right_signal.render(rl.Rectangle(right_x, right_y, self._config.size, self._config.size)) + + @property + def config(self) -> TurnSignalConfig: + return self._config + + @config.setter + def config(self, new_config: TurnSignalConfig): + self._config = new_config diff --git a/openpilot/selfdrive/ui/sunnypilot/ui_state.py b/openpilot/selfdrive/ui/sunnypilot/ui_state.py new file mode 100644 index 0000000000..c2729bbd91 --- /dev/null +++ b/openpilot/selfdrive/ui/sunnypilot/ui_state.py @@ -0,0 +1,265 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from enum import Enum + +from openpilot.cereal import messaging, log, custom +from opendbc.car.structs import car +from openpilot.common.params import Params +from openpilot.selfdrive.ui.sunnypilot.layouts.settings.display import OnroadBrightness +from openpilot.sunnypilot.sunnylink.sunnylink_state import SunnylinkState +from openpilot.system.ui.lib.application import gui_app + +OpenpilotState = log.SelfdriveState.OpenpilotState +MADSState = custom.ModularAssistiveDrivingSystem.ModularAssistiveDrivingSystemState + +ONROAD_BRIGHTNESS_TIMER_PAUSED = -1 + + +class OnroadTimerStatus(Enum): + NONE = 0 + PAUSE = 1 + RESUME = 2 + + +class UIStateSP: + def __init__(self): + self.params = Params() + self.CP_SP: custom.CarParamsSP | None = None + self.has_icbm: bool = False + self.is_sp_release: bool = self.params.get_bool("IsReleaseSpBranch") + self.sm_services_ext = [ + "modelManagerSP", "selfdriveStateSP", "longitudinalPlanSP", "backupManagerSP", + "gpsLocation", "liveTorqueParameters", "carStateSP", "liveMapDataSP", "carParamsSP", "liveDelay" + ] + + self.sunnylink_state = SunnylinkState() + + self.active_bundle = None + self.blindspot: bool = False + self.chevron_metrics = None + self.custom_interactive_timeout: int = 0 + self.developer_ui = None + self.hide_v_ego_ui: bool = False + self.onroad_brightness: int = 0 + self.onroad_brightness_timer: int = 0 + self.onroad_brightness_timer_param: int = 0 + self.rainbow_path: bool = False + self.road_name_toggle: bool = False + self.rocket_fuel: bool = False + self.speed_limit_mode = None + self.standstill_timer: bool = False + self.sunnylink_enabled: bool = False + self.torque_bar: bool = False + self.enforce_torque_control: bool = False + self.custom_torque_params: bool = False + self.torque_override_enabled: bool = False + self._sp_initialized: bool = False + + def update(self) -> None: + if self.sunnylink_enabled: + self.sunnylink_state.start() + else: + self.sunnylink_state.stop() + + def onroad_brightness_handle_alerts(self, _ui_state, alert): + if _ui_state.sm.recv_frame["carState"] < _ui_state.started_frame: + return + + has_alert = _ui_state.started and self.onroad_brightness != OnroadBrightness.AUTO and alert is not None + + self.update_onroad_brightness(has_alert) + if has_alert: + self.reset_onroad_sleep_timer() + + def update_onroad_brightness(self, has_alert: bool) -> None: + if has_alert: + return + + if self.onroad_brightness_timer > 0: + self.onroad_brightness_timer -= 1 + + def reset_onroad_sleep_timer(self, timer_status: OnroadTimerStatus = OnroadTimerStatus.NONE) -> None: + # Toggling from active state to inactive + if timer_status == OnroadTimerStatus.PAUSE and self.onroad_brightness_timer != ONROAD_BRIGHTNESS_TIMER_PAUSED: + self.onroad_brightness_timer = ONROAD_BRIGHTNESS_TIMER_PAUSED + # Toggling from a previously inactive state or resetting an active timer + elif (self.onroad_brightness_timer_param >= 0 and self.onroad_brightness != OnroadBrightness.AUTO and + self.onroad_brightness_timer != ONROAD_BRIGHTNESS_TIMER_PAUSED) or timer_status == OnroadTimerStatus.RESUME: + if self.onroad_brightness == OnroadBrightness.AUTO_DARK: + self.onroad_brightness_timer = 15 * gui_app.target_fps + else: + self.onroad_brightness_timer = self.onroad_brightness_timer_param * gui_app.target_fps + + @property + def onroad_brightness_timer_expired(self) -> bool: + return self.onroad_brightness != OnroadBrightness.AUTO and self.onroad_brightness_timer == 0 + + @property + def auto_onroad_brightness(self) -> bool: + return self.onroad_brightness in (OnroadBrightness.AUTO, OnroadBrightness.AUTO_DARK) + + @staticmethod + def update_status(ss, ss_sp, onroad_evt) -> str: + state = ss.state + mads = ss_sp.mads + mads_state = mads.state + + if state == OpenpilotState.preEnabled: + return "override" + + if state == OpenpilotState.overriding: + if not mads.available: + return "override" + + if any(e.overrideLongitudinal for e in onroad_evt): + return "override" + + if mads_state in (MADSState.paused, MADSState.overriding): + return "override" + + # MADS specific statuses + if not mads.available: + return "engaged" if ss.enabled else "disengaged" + + if not mads.enabled and not ss.enabled: + return "disengaged" + + if mads.enabled and ss.enabled: + return "engaged" + + if mads.enabled: + return "lat_only" + + if ss.enabled: + return "long_only" + + return "disengaged" + + def update_params(self) -> None: + CP_SP_bytes = self.params.get("CarParamsSPPersistent") + if CP_SP_bytes is not None: + self.CP_SP = messaging.log_from_bytes(CP_SP_bytes, custom.CarParamsSP) + self.has_icbm = self.CP_SP.intelligentCruiseButtonManagementAvailable and self.params.get_bool("IntelligentCruiseButtonManagement") + + self._enforce_constraints() + self.active_bundle = self.params.get("ModelManager_ActiveBundle") + self.blindspot = self.params.get_bool("BlindSpot") + self.chevron_metrics = self.params.get("ChevronInfo") + self.custom_interactive_timeout = self.params.get("InteractivityTimeout", return_default=True) + self.developer_ui = self.params.get("DevUIInfo") + self.hide_v_ego_ui = self.params.get_bool("HideVEgoUI") + self.onroad_brightness = int(float(self.params.get("OnroadScreenOffBrightness", return_default=True))) + self.onroad_brightness_timer_param = self.params.get("OnroadScreenOffTimer", return_default=True) + self.rainbow_path = self.params.get_bool("RainbowMode") + self.road_name_toggle = self.params.get_bool("RoadNameToggle") + self.rocket_fuel = self.params.get_bool("RocketFuel") + self.speed_limit_mode = self.params.get("SpeedLimitMode", return_default=True) + self.standstill_timer = self.params.get_bool("StandstillTimer") + self.sunnylink_enabled = self.params.get_bool("SunnylinkEnabled") + self.torque_bar = self.params.get_bool("TorqueBar") + self.enforce_torque_control = self.params.get_bool("EnforceTorqueControl") + self.custom_torque_params = self.params.get_bool("CustomTorqueParams") + self.torque_override_enabled = self.params.get_bool("TorqueParamsOverrideEnabled") + self.torque_override_lat_accel_factor = float(self.params.get("TorqueParamsOverrideLatAccelFactor", return_default=True)) + self.torque_override_friction = float(self.params.get("TorqueParamsOverrideFriction", return_default=True)) + self.true_v_ego_ui = self.params.get_bool("TrueVEgoUI") + self.turn_signals = self.params.get_bool("ShowTurnSignals") + self.boot_offroad_mode = self.params.get("DeviceBootMode", return_default=True) + self.always_offroad = self.params.get_bool("OffroadMode") + + if not self._sp_initialized: + self._sp_initialized = True + self.reset_onroad_sleep_timer() + + def _enforce_constraints(self) -> None: + has_long = self.has_longitudinal_control + CP = self.CP + + if CP is not None: + if self.params.get_bool("EnforceTorqueControl") and self.params.get_bool("NeuralNetworkLateralControl"): + self.params.put_bool("EnforceTorqueControl", False, block=True) + self.params.put_bool("NeuralNetworkLateralControl", False, block=True) + + # Angle steering: no torque-based lateral controls + if CP.steerControlType == car.CarParams.SteerControlType.angle: + self.params.remove("EnforceTorqueControl") + self.params.remove("NeuralNetworkLateralControl") + + # Alpha longitudinal: clear if not available + if not CP.alphaLongitudinalAvailable: + self.params.remove("AlphaLongitudinalEnabled") + + # BSM not available: clear BSM-dependent settings + if not CP.enableBsm: + self.params.remove("AutoLaneChangeBsmDelay") + else: + # No CarParams: clear all car-dependent params as safety default + self.params.remove("EnforceTorqueControl") + self.params.remove("NeuralNetworkLateralControl") + self.params.remove("AlphaLongitudinalEnabled") + + # No longitudinal control: no experimental mode or DEC + if not has_long: + self.params.remove("ExperimentalMode") + self.params.remove("DynamicExperimentalControl") + + # ICBM: clear if not available or if full longitudinal control is active + if self.CP_SP is not None: + if not self.CP_SP.intelligentCruiseButtonManagementAvailable or has_long: + self.params.remove("IntelligentCruiseButtonManagement") + self.has_icbm = False + else: + self.params.remove("IntelligentCruiseButtonManagement") + self.has_icbm = False + + # Cruise features requiring longitudinal or ICBM + if not (has_long or self.has_icbm): + self.params.remove("CustomAccIncrementsEnabled") + self.params.remove("SmartCruiseControlVision") + self.params.remove("SmartCruiseControlMap") + + +class DeviceSP: + def _set_awake(self, on: bool, _ui_state=None): + if _ui_state.boot_offroad_mode == 1 and not on: + _ui_state.params.put_bool("OffroadMode", True) + + @staticmethod + def set_onroad_brightness(_ui_state, awake: bool, cur_brightness: float) -> float: + if not awake or not _ui_state.started: + return cur_brightness + + if _ui_state.onroad_brightness_timer != 0: + if _ui_state.onroad_brightness == OnroadBrightness.AUTO_DARK: + return max(30.0, cur_brightness) + return cur_brightness + + # 0: Auto (Default), 1: Auto (Dark), 2: Screen Off + if _ui_state.onroad_brightness == OnroadBrightness.AUTO: + return cur_brightness + if _ui_state.onroad_brightness == OnroadBrightness.AUTO_DARK: + return cur_brightness + if _ui_state.onroad_brightness == OnroadBrightness.SCREEN_OFF: + return 0.0 + + # 3-22: 5% - 100% + return float((_ui_state.onroad_brightness - 2) * 5) + + @staticmethod + def set_min_onroad_brightness(_ui_state, min_brightness: int) -> int: + if _ui_state.onroad_brightness == OnroadBrightness.AUTO_DARK: + min_brightness = 10 + + return min_brightness + + @staticmethod + def wake_from_dimmed_onroad_brightness(_ui_state, evs) -> None: + if _ui_state.started and (_ui_state.onroad_brightness_timer_expired or _ui_state.onroad_brightness == OnroadBrightness.AUTO_DARK): + if any(ev.left_down for ev in evs): + if _ui_state.onroad_brightness_timer_expired: + gui_app.mouse_events.clear() + _ui_state.reset_onroad_sleep_timer() diff --git a/sunnypilot/modeld_v2/tests/__init__.py b/openpilot/selfdrive/ui/tests/__init__.py similarity index 100% rename from sunnypilot/modeld_v2/tests/__init__.py rename to openpilot/selfdrive/ui/tests/__init__.py diff --git a/openpilot/selfdrive/ui/tests/body.py b/openpilot/selfdrive/ui/tests/body.py new file mode 100755 index 0000000000..b9f5c2d18c --- /dev/null +++ b/openpilot/selfdrive/ui/tests/body.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python3 +import time +import openpilot.cereal.messaging as messaging + +if __name__ == "__main__": + while True: + pm = messaging.PubMaster(['carParams', 'carState']) + batt = 1. + while True: + msg = messaging.new_message('carParams') + msg.carParams.brand = "body" + msg.carParams.notCar = True + pm.send('carParams', msg) + + for b in range(100, 0, -1): + msg = messaging.new_message('carState') + msg.carState.charging = True + msg.carState.fuelGauge = b / 100. + pm.send('carState', msg) + time.sleep(0.1) + + time.sleep(1) diff --git a/openpilot/selfdrive/ui/tests/cycle_offroad_alerts.py b/openpilot/selfdrive/ui/tests/cycle_offroad_alerts.py new file mode 100755 index 0000000000..c2690edf7d --- /dev/null +++ b/openpilot/selfdrive/ui/tests/cycle_offroad_alerts.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python3 +import os +import sys +import time +import json + +from openpilot.common.basedir import BASEDIR +from openpilot.common.params import Params +from openpilot.selfdrive.selfdrived.alertmanager import set_offroad_alert +from openpilot.system.updated.updated import parse_release_notes + +if __name__ == "__main__": + params = Params() + + with open(os.path.join(BASEDIR, "openpilot/selfdrive/selfdrived/alerts_offroad.json")) as f: + offroad_alerts = json.load(f) + + t = 10 if len(sys.argv) < 2 else int(sys.argv[1]) + while True: + print("setting alert update") + params.put_bool("UpdateAvailable", True, block=True) + params.put("UpdaterNewReleaseNotes", parse_release_notes(BASEDIR), block=True) + + time.sleep(t) + params.put_bool("UpdateAvailable", False, block=True) + + # cycle through normal alerts + for a in offroad_alerts: + print("setting alert:", a) + set_offroad_alert(a, True) + time.sleep(t) + set_offroad_alert(a, False) + + print("no alert") + time.sleep(t) diff --git a/openpilot/selfdrive/ui/tests/diff/diff.py b/openpilot/selfdrive/ui/tests/diff/diff.py new file mode 100755 index 0000000000..9dd7c3bc0e --- /dev/null +++ b/openpilot/selfdrive/ui/tests/diff/diff.py @@ -0,0 +1,151 @@ +#!/usr/bin/env python3 +import os +import sys +import subprocess +import webbrowser +import argparse +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +from openpilot.common.basedir import BASEDIR + +DIFF_OUT_DIR = Path(BASEDIR) / "openpilot" / "selfdrive" / "ui" / "tests" / "diff" / "report" +HTML_TEMPLATE_PATH = Path(__file__).with_name("diff_template.html") + + +def extract_framehashes(video_path: Path) -> list[str]: + cmd = ['ffmpeg', '-nostdin', '-i', video_path, '-map', '0:v:0', '-vsync', '0', '-f', 'framehash', '-hash', 'md5', '-'] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + hashes = [] + for line in result.stdout.splitlines(): + if not line or line.startswith('#'): + continue + parts = line.split(',') + if len(parts) < 4: + continue + hashes.append(parts[-1].strip()) + return hashes + + +def get_video_frame_hashes(video1: Path, video2: Path) -> tuple[list[str], list[str]]: + """Hash every frame of both videos in parallel and return the two hash lists.""" + with ThreadPoolExecutor(max_workers=2) as executor: + print("Generating frame hashes for both videos...") + future1 = executor.submit(extract_framehashes, video1) + future2 = executor.submit(extract_framehashes, video2) + hashes1 = future1.result() + hashes2 = future2.result() + return hashes1, hashes2 + + +def create_diff_video(video1: Path, video2: Path, output: Path) -> None: + """Create a diff video of two clips using ffmpeg blend filter with difference mode.""" + cmd = ['ffmpeg', '-nostdin', '-i', video1, '-i', video2, '-filter_complex', 'blend=all_mode=difference', '-vsync', '0', '-y', output] + subprocess.run(cmd, capture_output=True, check=True) + + +def find_frame_differences(hashes1: list[str], hashes2: list[str]) -> list[int]: + """Compare two lists of frame hashes and return the indices of different frames.""" + different_frames = [] + for i, (h1, h2) in enumerate(zip(hashes1, hashes2, strict=False)): + if h1 != h2: + different_frames.append(i) + return different_frames + + +def generate_html_report(videos: tuple[Path, Path], basedir: str, different_frames: list[int], frame_counts: tuple[int, int], diff_video_name: str) -> str: + total_frames = max(frame_counts) + frame_delta = frame_counts[1] - frame_counts[0] + different_total = len(different_frames) + abs(frame_delta) + + result_text = ( + f"✅ Videos are identical! ({total_frames} frames)" + if different_total == 0 + else f"❌ Found {different_total} different frames out of {total_frames} total ({different_total / total_frames * 100:.1f}%)." + + (f" Video {'2' if frame_delta > 0 else '1'} is longer by {abs(frame_delta)} frames." if frame_delta != 0 else "") + ) + print(f" Results: {result_text}") + + # Load HTML template and replace placeholders + html = HTML_TEMPLATE_PATH.read_text() + placeholders = { + "VIDEO1_SRC": os.path.join(basedir, videos[0].name), + "VIDEO2_SRC": os.path.join(basedir, videos[1].name), + "DIFF_SRC": os.path.join(basedir, diff_video_name), + "RESULT_TEXT": result_text, + } + for key, value in placeholders.items(): + html = html.replace(f"${key}", value) + + return html + + +def main(): + parser = argparse.ArgumentParser(description='Compare two videos and generate HTML diff report') + parser.add_argument('video1', help='First video file') + parser.add_argument('video2', help='Second video file') + parser.add_argument('output', nargs='?', default='diff.html', help='Output HTML file (default: diff.html)') + parser.add_argument("--basedir", type=str, help="Base path for files in HTML report", default="") + parser.add_argument('--no-open', action='store_true', help='Do not open HTML report in browser') + + args = parser.parse_args() + + if not args.output.lower().endswith('.html'): + args.output += '.html' + + video1, video2 = Path(args.video1), Path(args.video2) + missing = [str(p) for p in (video1, video2) if not p.is_file()] + if missing: + parser.error(f"Video file(s) not found: {', '.join(missing)}") + + diff_video_name = f"{Path(args.output).stem}.mp4" # diff video name derived from output HTML name + + os.makedirs(DIFF_OUT_DIR, exist_ok=True) + + print("=" * 60) + print("UI VIDEO DIFF - HTML REPORT") + print("=" * 60) + print(f"Video 1: {video1}") + print(f"Video 2: {video2}") + print(f"HTML output: {args.output}") + print(f"Diff video: {diff_video_name}") + print() + + print("[1/4] Starting full video diff generation in background thread...") + diff_executor = ThreadPoolExecutor(max_workers=1) + diff_future = diff_executor.submit(create_diff_video, video1, video2, DIFF_OUT_DIR / diff_video_name) + + print("[2/4] Hashing frames...") + hashes1, hashes2 = get_video_frame_hashes(video1, video2) + frame_counts = (len(hashes1), len(hashes2)) + print(f" Found {frame_counts[0]} frames in video 1 and {frame_counts[1]} frames in video 2.") + + print("[3/4] Finding different frames...") + different_frames = find_frame_differences(hashes1, hashes2) + print(f" Found {len(different_frames)} different frames.") + + print("[4/4] Generating HTML report...") + html = generate_html_report((video1, video2), args.basedir, different_frames, frame_counts, diff_video_name) + + output_path = DIFF_OUT_DIR / args.output + with open(output_path, 'w') as f: + f.write(html) + + print(f" Report generated at: {output_path}") + + # Open in browser by default + if not args.no_open: + print(f"Opening {args.output} in browser...") + webbrowser.open(f'file://{os.path.abspath(output_path)}') + + # Wait for diff video generation to finish before exiting + if not diff_future.done(): + print("Waiting for diff video generation to finish...") + diff_future.result() + diff_executor.shutdown() + + extra_frames = abs(frame_counts[0] - frame_counts[1]) + return 0 if (len(different_frames) + extra_frames) == 0 else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/openpilot/selfdrive/ui/tests/diff/diff_template.html b/openpilot/selfdrive/ui/tests/diff/diff_template.html new file mode 100644 index 0000000000..3f1de10512 --- /dev/null +++ b/openpilot/selfdrive/ui/tests/diff/diff_template.html @@ -0,0 +1,80 @@ + + + + + + UI Diff Report + + + +

UI Diff

+
+
+

Results: $RESULT_TEXT

+ + + diff --git a/openpilot/selfdrive/ui/tests/diff/replay.py b/openpilot/selfdrive/ui/tests/diff/replay.py new file mode 100755 index 0000000000..e378076850 --- /dev/null +++ b/openpilot/selfdrive/ui/tests/diff/replay.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python3 +import os +import argparse +import coverage +import pyray as rl + +from tqdm import tqdm +from typing import Literal +from collections.abc import Callable +from openpilot.cereal.messaging import PubMaster +from openpilot.common.api import Api +from openpilot.common.basedir import BASEDIR +from openpilot.common.params import Params +from openpilot.common.prefix import OpenpilotPrefix +from openpilot.selfdrive.ui.tests.diff.diff import DIFF_OUT_DIR +from openpilot.system.updated.updated import parse_release_notes +from openpilot.common.version import terms_version, training_version, terms_version_sp, sunnylink_consent_version + +LayoutVariant = Literal["mici", "tizi"] + +FPS = 60 +HEADLESS = os.getenv("WINDOWED", "0") != "1" + + +def setup_state(): + params = Params() + params.put("HasAcceptedTerms", terms_version, block=True) + params.put("CompletedTrainingVersion", training_version, block=True) + params.put("DongleId", "test123456789", block=True) + # Combined description for layouts that still use it (BIG home, settings/software) + params.put("UpdaterCurrentDescription", "0.10.1 / test-branch / abc1234 / Nov 30", block=True) + params.put("UpdaterCurrentReleaseNotes", parse_release_notes(BASEDIR), block=True) + params.put("HasAcceptedTermsSP", terms_version_sp, block=True) + params.put("CompletedSunnylinkConsentVersion", sunnylink_consent_version, block=True) + # Params for mici home + params.put("Version", "0.10.1", block=True) + params.put("GitBranch", "test-branch", block=True) + params.put("GitCommit", "abc12340ff9131237ba23a1d0fbd8edf9c80e87", block=True) + params.put("GitCommitDate", "'1732924800 2024-11-30 00:00:00 +0000'", block=True) + + # Patch Api.get_token to return a static token so the pairing QR code is deterministic across runs + Api.get_token = lambda self, payload_extra=None, expiry_hours=0: "test_token" + + +def run_replay(variant: LayoutVariant) -> None: + if HEADLESS: + rl.set_config_flags(rl.ConfigFlags.FLAG_WINDOW_HIDDEN) + os.environ["OFFSCREEN"] = "1" # Run UI without FPS limit (set before importing gui_app) + + setup_state() + os.makedirs(DIFF_OUT_DIR, exist_ok=True) + + from openpilot.selfdrive.ui.ui_state import ui_state, device # Import within OpenpilotPrefix context so param values are setup correctly + from openpilot.system.ui.lib.application import gui_app # Import here for accurate coverage + from openpilot.selfdrive.ui.tests.diff.replay_script import build_script + + gui_app.init_window("ui diff test", fps=FPS) + + # Dynamically import main layout based on variant + if variant == "mici": + from openpilot.selfdrive.ui.mici.layouts.main import MiciMainLayout as MainLayout + else: + from openpilot.selfdrive.ui.layouts.main import MainLayout + main_layout = MainLayout() + + # Disable interactive timeout — replay clicks use left_down=False so they never reset the timer, + # and after 30s of real wall-clock time the settings panel would close automatically. + device.set_override_interactive_timeout(99999) + + pm = PubMaster(["deviceState", "pandaStates", "driverStateV2", "selfdriveState"]) + script = build_script(pm, main_layout, variant) + script_index = 0 + + send_fn: Callable | None = None + frame = 0 + # Override raylib timing functions to return deterministic values based on frame count instead of real time + rl.get_frame_time = lambda: 1.0 / FPS + rl.get_time = lambda: frame / FPS + + # Main loop to replay events and render frames + with tqdm(total=script[-1][0] + 1, desc="Replaying", unit="frame", disable=bool(os.getenv("CI"))) as pbar: + for _ in gui_app.render(): + # Handle all events for the current frame + while script_index < len(script) and script[script_index][0] == frame: + _, event = script[script_index] + # Call setup function, if any + if event.setup: + event.setup() + # Send mouse events to the application + if event.mouse_events: + with gui_app._mouse._lock: + gui_app._mouse._events.extend(event.mouse_events) + # Update persistent send function + if event.send_fn is not None: + send_fn = event.send_fn + # Move to next script event + script_index += 1 + + # Keep sending cereal messages for persistent states (onroad, alerts) + if send_fn: + send_fn() + + ui_state.update() + + frame += 1 + pbar.update(1) + + if script_index >= len(script): + break + + gui_app.close() + + print(f"Total frames: {frame}") + print(f"Video saved to: {os.environ['RECORD_OUTPUT']}") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--big', action='store_true', help='Use big UI layout (tizi/tici) instead of mici layout') + args = parser.parse_args() + + variant: LayoutVariant = 'tizi' if args.big else 'mici' + + if args.big: + os.environ["BIG"] = "1" + os.environ["RECORD"] = "1" + os.environ["RECORD_QUALITY"] = "0" # Use CRF 0 ("lossless" encode) for deterministic output across different machines + os.environ["RECORD_OUTPUT"] = os.path.join(DIFF_OUT_DIR, os.environ.get("RECORD_OUTPUT", f"{variant}_ui_replay.mp4")) + + print(f"Running {variant} UI replay...") + with OpenpilotPrefix(): + sources = ["openpilot.system.ui"] + if variant == "mici": + sources.append("openpilot.selfdrive.ui.mici") + omit = ["**/*tizi*", "**/*tici*"] # exclude files containing "tizi" or "tici" + else: + sources.extend(["openpilot.selfdrive.ui.layouts", "openpilot.selfdrive.ui.onroad", "openpilot.selfdrive.ui.widgets"]) + omit = ["**/*mici*"] # exclude files containing "mici" + cov = coverage.Coverage(source=sources, omit=omit) + with cov.collect(): + run_replay(variant) + cov.save() + cov.report() + directory = os.path.join(DIFF_OUT_DIR, f"htmlcov-{variant}") + cov.html_report(directory=directory) + print(f"HTML report: {directory}/index.html") + + +if __name__ == "__main__": + main() diff --git a/openpilot/selfdrive/ui/tests/diff/replay_script.py b/openpilot/selfdrive/ui/tests/diff/replay_script.py new file mode 100644 index 0000000000..109f32e47a --- /dev/null +++ b/openpilot/selfdrive/ui/tests/diff/replay_script.py @@ -0,0 +1,526 @@ +from __future__ import annotations +from typing import TYPE_CHECKING +from collections.abc import Callable +from dataclasses import dataclass + +import math + +from openpilot.cereal import log, messaging +from opendbc.car.structs import car +from openpilot.cereal.messaging import PubMaster +from openpilot.common.basedir import BASEDIR +from openpilot.common.params import Params +from openpilot.selfdrive.selfdrived.alertmanager import set_offroad_alert +from openpilot.selfdrive.ui.lib.prime_state import PrimeType +from openpilot.selfdrive.ui.tests.diff.replay import FPS, LayoutVariant +from openpilot.system.updated.updated import parse_release_notes + +# Default frames to wait after events +WAIT_LONG = FPS +WAIT_SHORT = FPS // 2 +FAST_CLICK = FPS // 6 + +# Direction vectors for drag gestures +DIR_LEFT = (-1, 0) +DIR_RIGHT = (1, 0) +DIR_UP = (0, -1) +DIR_DOWN = (0, 1) + +AlertSize = log.SelfdriveState.AlertSize +AlertStatus = log.SelfdriveState.AlertStatus + +BRANCH_NAME = "this-is-a-really-super-mega-ultra-max-extreme-ultimate-long-branch-name" + + +@dataclass +class ScriptEvent: + if TYPE_CHECKING: + # Only import for type checking to avoid excluding the application code from coverage + from openpilot.system.ui.lib.application import MouseEvent + + setup: Callable | None = None # Setup function to run prior to adding mouse events + mouse_events: list[MouseEvent] | None = None # Mouse events to send to the application on this event's frame + send_fn: Callable | None = None # When set, the main loop uses this as the new persistent sender + + +ScriptEntry = tuple[int, ScriptEvent] # (frame, event) + + +class Script: + def __init__(self, fps: int) -> None: + self.fps = fps + self.frame = 0 + self.entries: list[ScriptEntry] = [] + + def get_frame_time(self) -> float: + return self.frame / self.fps + + def add(self, event: ScriptEvent, before: int = 0, after: int = 0) -> None: + """Add event to the script, optionally with the given number of frames to wait before or after the event.""" + self.frame += before + self.entries.append((self.frame, event)) + self.frame += after + + def end(self) -> None: + """Add a final empty event to mark the end of the script.""" + self.add(ScriptEvent()) # Without this, it will just end on the last event without waiting for any specified delay after it + + def wait(self, frames: int) -> None: + """Add a delay for the given number of frames followed by an empty event.""" + self.add(ScriptEvent(), before=frames) + + def setup(self, fn: Callable, wait_after: int = WAIT_SHORT) -> None: + """Add a setup function to be called immediately followed by a delay of the given number of frames.""" + self.add(ScriptEvent(setup=fn), after=wait_after) + + def set_send(self, fn: Callable, wait_after: int = WAIT_SHORT) -> None: + """Set a new persistent send function to be called every frame.""" + self.add(ScriptEvent(send_fn=fn), after=wait_after) + + def click(self, x: int, y: int, wait_after: int = WAIT_SHORT, wait_between: int = 2) -> None: + """Add a click event to the script for the given position and specify frames to wait between mouse events or after the click.""" + # NOTE: By default we wait a couple frames between mouse events so pressed states will be rendered + from openpilot.system.ui.lib.application import MouseEvent, MousePos + + mouse_down = MouseEvent(pos=MousePos(x, y), slot=0, left_pressed=True, left_released=False, left_down=False, t=self.get_frame_time()) + self.add(ScriptEvent(mouse_events=[mouse_down]), after=wait_between) + mouse_up = MouseEvent(pos=MousePos(x, y), slot=0, left_pressed=False, left_released=True, left_down=False, t=self.get_frame_time()) + self.add(ScriptEvent(mouse_events=[mouse_up]), after=wait_after) + + def drag(self, start_x: int, start_y: int, direction: tuple[int, int], distance: int, duration_frames: int, wait_after: int = WAIT_LONG) -> None: + """Add a drag gesture to the script from start position in the specified direction by the given distance over the given number of frames.""" + from openpilot.system.ui.lib.application import MouseEvent, MousePos + + # Calculate delta and end position based on direction and distance + delta_x, delta_y = direction[0] * distance, direction[1] * distance + end_x, end_y = start_x + delta_x, start_y + delta_y + + # Mouse down at start + mouse_down = MouseEvent(pos=MousePos(start_x, start_y), slot=0, left_pressed=True, left_released=False, left_down=True, t=self.get_frame_time()) + self.add(ScriptEvent(mouse_events=[mouse_down]), after=1) + + # Interpolate positions over duration_frames + for i in range(1, duration_frames): + t = i / duration_frames + x, y = int(start_x + delta_x * t), int(start_y + delta_y * t) + mouse_move = MouseEvent(pos=MousePos(x, y), slot=0, left_pressed=False, left_released=False, left_down=True, t=self.get_frame_time()) + self.add(ScriptEvent(mouse_events=[mouse_move]), after=1) + + # Mouse up at end + mouse_up = MouseEvent(pos=MousePos(end_x, end_y), slot=0, left_pressed=False, left_released=True, left_down=False, t=self.get_frame_time()) + self.add(ScriptEvent(mouse_events=[mouse_up]), after=wait_after) + + +# --- Setup functions --- + + +def set_prime_state(prime_type: PrimeType) -> None: + from openpilot.selfdrive.ui.ui_state import ui_state + ui_state.prime_state.set_type(prime_type) + + +def setup_offroad_alerts() -> None: + set_offroad_alert("Offroad_TemperatureTooHigh", True, extra_text='99C') + set_offroad_alert("Offroad_ExcessiveActuation", True, extra_text='longitudinal') + + +def setup_update_available(available: bool = True) -> None: + params = Params() + params.put_bool("UpdateAvailable", available, block=True) + params.put("UpdaterAvailableBranches", ",".join(["test-branch", "test-branch-2", BRANCH_NAME]), block=True) + if available: + params.put("UpdaterNewDescription", f"0.10.2 / {BRANCH_NAME} / 0a1b2c3 / Jan 01", block=True) + params.put("UpdaterNewReleaseNotes", parse_release_notes(BASEDIR), block=True) + params.put("UpdaterTargetBranch", BRANCH_NAME, block=True) + else: + params.remove("UpdaterNewDescription") + params.remove("UpdaterNewReleaseNotes") + params.remove("UpdaterTargetBranch") + + +def setup_calibration_params() -> None: + params = Params() + # live calibration + calib = messaging.new_message('liveCalibration') + calib.liveCalibration.calStatus = log.LiveCalibrationData.Status.calibrated + calib.liveCalibration.rpyCalib = [0.0, math.radians(2.5), math.radians(-1.2)] + params.put("CalibrationParams", calib.to_bytes(), block=True) + # live delay + delay = messaging.new_message('liveDelay') + delay.liveDelay.calPerc = 75 + params.put("LiveDelay", delay.to_bytes(), block=True) + # live torque parameters + torque = messaging.new_message('liveTorqueParameters') + torque.liveTorqueParameters.useParams = True + torque.liveTorqueParameters.calPerc = 60 + params.put("LiveTorqueParameters", torque.to_bytes(), block=True) + + +def setup_developer_params() -> None: + CP = car.CarParams() + CP.alphaLongitudinalAvailable = True + Params().put("CarParamsPersistent", CP.to_bytes(), block=True) + + +# --- Send functions --- + +def send_onroad(pm: PubMaster) -> None: + ds = messaging.new_message('deviceState') + ds.deviceState.started = True + ds.deviceState.networkType = log.DeviceState.NetworkType.wifi + + ps = messaging.new_message('pandaStates', 1) + ps.pandaStates[0].pandaType = log.PandaState.PandaType.dos + ps.pandaStates[0].ignitionLine = True + + pm.send('deviceState', ds) + pm.send('pandaStates', ps) + + +def make_network_state_setup(pm: PubMaster, network_type) -> Callable: + def _send() -> None: + ds = messaging.new_message('deviceState') + ds.deviceState.networkType = network_type + pm.send('deviceState', ds) + return _send + + +def make_alert_setup(pm: PubMaster, size, text1, text2, status) -> Callable: + def _send() -> None: + alert = messaging.new_message('selfdriveState') + ss = alert.selfdriveState + ss.alertSize = size + ss.alertText1 = text1 + ss.alertText2 = text2 + ss.alertStatus = status + pm.send('selfdriveState', alert) + return _send + + +def test_onroad_alerts(script: Script, pm: PubMaster) -> None: + """Go through various alert types and sizes and add them to the script to test alert rendering. + Each alert is sent as a separate event with a delay in between.""" + # Small alert (normal) + script.set_send(make_alert_setup(pm, AlertSize.small, "Small Alert", "This is a small alert", AlertStatus.normal)) + # Medium alert (userPrompt) + script.set_send(make_alert_setup(pm, AlertSize.mid, "Medium Alert", "This is a medium alert", AlertStatus.userPrompt)) + # Full alert (critical) + script.set_send(make_alert_setup(pm, AlertSize.full, "DISENGAGE IMMEDIATELY", "Driver Distracted", AlertStatus.critical)) + # Full alert multiline + script.set_send(make_alert_setup(pm, AlertSize.full, "Reverse\nGear", "", AlertStatus.normal)) + # Full alert long text + script.set_send(make_alert_setup(pm, AlertSize.full, "TAKE CONTROL IMMEDIATELY", "Calibration Invalid: Remount Device & Recalibrate", AlertStatus.userPrompt)) + + +# --- Script builders --- + +def build_mici_script(pm: PubMaster, main_layout, script: Script) -> None: + """Build the replay script for the mici layout.""" + from openpilot.system.ui.lib.application import gui_app + + width, height = gui_app.width, gui_app.height + center = (width // 2, height // 2) + right = (width * 4 // 5, height // 2) + left = (width // 5, height // 2) + top = (width // 2, height // 10) + bottom = (width // 2, height * 9 // 10) + + DURATION = 5 + SWIPE_WAIT = FPS * 3 // 4 + + def click(times: int = 1, wait_after: int = WAIT_SHORT) -> None: + """Click at the center of the screen the given number of times with optional delay after.""" + for _ in range(times): + script.click(*center, wait_after=wait_after) + + def press(x: int, y: int, duration_frames: int = DURATION, wait_after: int = WAIT_SHORT) -> None: + """Perform a drag with no movement to simulate a left_down mouse event at the given position for the specified duration and delay after.""" + script.drag(x, y, (0, 0), 0, duration_frames, wait_after=wait_after) + + def swipe_left(distance: int = right[0] - left[0], duration_frames: int = DURATION, wait_after: int = SWIPE_WAIT) -> None: + """Drag from right edge to left (scroll right / slide confirmation).""" + script.drag(*right, DIR_LEFT, distance, duration_frames, wait_after) + + def swipe_right(distance: int = right[0] - left[0], duration_frames: int = DURATION, wait_after: int = SWIPE_WAIT) -> None: + """Drag from left edge to right (scroll left).""" + script.drag(*left, DIR_RIGHT, distance, duration_frames, wait_after) + + def swipe_down(distance: int = bottom[1] - top[1], duration_frames: int = DURATION, wait_after: int = SWIPE_WAIT) -> None: + """Drag from top edge to bottom (scroll up / go back).""" + script.drag(*top, DIR_DOWN, distance, duration_frames, wait_after) + + def swipe_up(distance: int = bottom[1] - top[1], duration_frames: int = DURATION, wait_after: int = SWIPE_WAIT) -> None: + """Drag from bottom edge to top (scroll down).""" + script.drag(*bottom, DIR_UP, distance, duration_frames, wait_after) + + ActionFn = Callable[[], None] | None + Cases = list[ActionFn] + + def run_actions(*actions: ActionFn, after_each: ActionFn = None) -> None: + """Helper function to run a sequence of actions in order for interaction tests, calling after_each callback after each action if provided.""" + for action in actions: + if action is not None: + action() + if after_each is not None: + after_each() + + def explore_setting(*actions: ActionFn) -> None: + """Helper function to open a settings item, run the given actions, and go back.""" + run_actions(click, *actions, swipe_down) # open, interact, go back + + def scroll_through_cases(cases: Cases) -> None: + """Helper function to explore a panel by calling the interaction callbacks for each item/page before swiping to the next one.""" + run_actions(*cases, after_each=lambda: swipe_left(210, 10)) # swipe to roughly the center of the next toggle after each case + + def interact_keyboard() -> None: + """Interact with the keyboard in various ways to test different actions and states. + Assumes it's a password keyboard with 8 characters required. Closes by pressing confirm at the end.""" + KEY = (250, 160) # key in the middle of the keyboard ('G') + SHIFT = (50, 210) + NUMBERS = (480, 210) + SPACE = (500, 160) + BACKSPACE = (490, 30) + CONFIRM = (50, 30) + # Begin interactions + press(*CONFIRM, wait_after=FAST_CLICK) # confirm while disabled should do nothing + swipe_left(duration_frames=FPS // 2) # swipe to type + swipe_up(duration_frames=FPS // 2) # swipe out of keyboard (nothing typed) + # press various keys to test different states: + for key in [ + SHIFT, KEY, KEY, SHIFT, SHIFT, KEY, KEY, # test casing (upper, lower, caps lock) + SPACE, SPACE, BACKSPACE, BACKSPACE, # test multiple space and backspace + NUMBERS, KEY, center, SHIFT, KEY # test numbers and symbols + ]: + press(*key, wait_after=FAST_CLICK) + # press confirm to close + script.wait(WAIT_SHORT) # wait for confirm to enable + press(*CONFIRM) + + toggle_cases: Cases = [ + lambda: click(times=3, wait_after=FAST_CLICK), # first toggle is personality, which has 3 states + None, None, None, None, None, None, # skip other toggles to save time + lambda: click(times=2, wait_after=FAST_CLICK), # test final toggle (enable openpilot) + ] + + network_cases: Cases = [ + explore_setting, # select wifi (just open and close) + None, None, + lambda: run_actions(click, interact_keyboard), # tether password keyboard + ] + + device_cases: Cases = [ + None, + click, # update + explore_setting, # pairing (just open and close) + lambda: explore_setting( + # training guide + lambda: swipe_left(width * 2), click, # first page, click next + lambda: swipe_left(width * 2), swipe_down # second page, go back (TODO: make driver cam preview work) + ), + None, # TODO: preview driver camera; enabling this causes MultiplePublishersError later in onroad alert tests + lambda: explore_setting(swipe_left), # terms & conditions (swipe to view QR code) + lambda: explore_setting(lambda: swipe_up(height * 3), lambda: swipe_down(height * 3)), # regulatory info + lambda: run_actions(click, lambda: swipe_left(width)), # reset calibration confirm (goes back automatically) + lambda: explore_setting(lambda: swipe_left(width)), # uninstall + lambda: run_actions( + lambda: explore_setting(lambda: swipe_left(width)), # reboot + lambda: script.click(430, 120), lambda: swipe_left(width), swipe_down, # shutdown + ), + ] + + developer_cases: Cases = [ + lambda: click(times=2, wait_after=FAST_CLICK), # toggle ssh mode + explore_setting, # SSH keys keyboard (just open and close) + None, # joystick mode + lambda: click(wait_after=FAST_CLICK), # longitudinal maneuver mode (disabled; should do nothing) + lambda: click(times=2, wait_after=FAST_CLICK), # toggle UI debug mode + ] + + settings_cases: Cases = [ + lambda: scroll_through_cases(toggle_cases), + lambda: scroll_through_cases(network_cases), + lambda: scroll_through_cases(device_cases), + lambda: script.wait(WAIT_SHORT), # pairing + lambda: run_actions(lambda: swipe_up(height * 3), lambda: swipe_down(height * 3)), # firehose (scroll down and back up) + lambda: scroll_through_cases(developer_cases), + ] + + # === Homescreen === # + script.wait(WAIT_SHORT) + swipe_left(width, wait_after=WAIT_SHORT) # onroad screen + swipe_right(width, wait_after=WAIT_SHORT) # back to home + + # === Offroad Alerts === + def setup_offroad_alerts_and_refresh() -> None: + """Setup function to trigger offroad alerts and force a refresh on the alerts layout.""" + setup_offroad_alerts() + params = Params() + main_layout._alerts_layout._pending_params = ({"UpdaterNewDescription": params.get("UpdaterNewDescription")} | + {alert_data.key: params.get(alert_data.key) for alert_data in main_layout._alerts_layout.sorted_alerts}) + main_layout._alerts_layout._update_state() + + swipe_right(width, wait_after=WAIT_SHORT) # open alerts + script.setup(setup_offroad_alerts_and_refresh) # show alerts + swipe_up(height) # scroll alerts + swipe_left(width, wait_after=WAIT_SHORT) # close alerts + + # === Settings === # + click() # open settings + scroll_through_cases([lambda case=case: explore_setting(case) for case in settings_cases]) # explore settings + swipe_down() # back to home + + # === Onroad === + script.set_send(lambda: send_onroad(pm)) + swipe_left(width, wait_after=WAIT_SHORT) # onroad screen + test_onroad_alerts(script, pm) + swipe_right(width) # back to home + + script.end() + + +def build_tizi_script(pm: PubMaster, main_layout, script: Script) -> None: + """Build the replay script for the tizi layout.""" + + def make_home_refresh_setup(fn: Callable) -> Callable: + """Return setup function that calls the given function to modify state and forces an immediate refresh on the home layout.""" + from openpilot.selfdrive.ui.layouts.main import MainState + + def setup(): + fn() + main_layout._layouts[MainState.HOME].last_refresh = 0 + + return setup + + def add_prime_state_setup(prime_type: PrimeType) -> None: + script.set_send(lambda: set_prime_state(prime_type)) + + def do_onboarding() -> None: + """Click through the training guide and close.""" + from openpilot.selfdrive.ui.layouts.onboarding import STEP_RECTS + step = 0 + for step_rect in STEP_RECTS: + if step < len(STEP_RECTS) - 1: + script.click(int(step_rect.x), int(step_rect.y), wait_after=FAST_CLICK) + else: + script.click(950, 900) # On the last step, click Finish instead of restart + step += 1 + + def type_keyboard() -> None: + """Types 8 characters using the big keyboard to test different layouts and interactions.""" + KEY = (150, 430) # e.g. 'Q' key + SHIFT = (150, 750) # also symbols key in number mode + NUMBERS = (150, 950) + SPACE = (1060, 950) + BACKSPACE = (2000, 780) + for key in [ + SHIFT, KEY, KEY, SHIFT, SHIFT, KEY, KEY, # test casing (upper, lower, caps lock) + SPACE, SPACE, BACKSPACE, BACKSPACE, # test multiple space and backspace + NUMBERS, KEY, KEY, SHIFT, KEY, KEY # test numbers and symbols + ]: + script.click(*key, wait_after=FAST_CLICK) + + # TODO: Better way of organizing the events + + # === Homescreen === + script.set_send(make_network_state_setup(pm, log.DeviceState.NetworkType.wifi)) + # Go through different prime state layouts + add_prime_state_setup(PrimeType.LITE) + add_prime_state_setup(PrimeType.NONE) + add_prime_state_setup(PrimeType.UNPAIRED) + + # === Update Available (auto-transitions via HomeLayout refresh) === + script.setup(make_home_refresh_setup(setup_update_available)) + + # === Offroad Alerts (auto-transitions via HomeLayout refresh, overrides update) === + script.setup(make_home_refresh_setup(setup_offroad_alerts)) + script.click(620, 950) # close alerts + + # === Settings (click sidebar settings button) === + script.click(150, 90) + + # === Settings - Device === + # pair device + script.click(2000, 450) # pair device + script.click(110, 110) # close pairing dialog + add_prime_state_setup(PrimeType.NONE) # changed from unpaired to hide pair device button + # calibration + script.setup(setup_calibration_params, wait_after=0) + script.click(1000, 620) # expand calibration description + script.click(2000, 620) # reset calibration confirmation + script.click(1500, 750) # confirm reset + script.click(1000, 620) # collapse calibration description + # training guide + script.click(2000, 800) # open training guide + do_onboarding() + # regulatory info + script.click(2000, 970) # regulatory button + script.click(2000, 970) # OK + + # === Settings - Network === + script.click(278, 450) + # TODO: mock networks + script.click(1880, 100) # advanced network settings + + # Keyboard (tethering password) + script.click(2000, 420, wait_after=FAST_CLICK) # open tether password keyboard + script.click(2000, 950, wait_after=FAST_CLICK) # click confirm (disabled, should not close) + script.click(2000, 115) # cancel (close without typing) + script.click(2000, 420, wait_after=FAST_CLICK) # open keyboard again + type_keyboard() # test various keyboard layouts and interactions + script.click(2050, 250, wait_after=FAST_CLICK) # toggle show/hide password + script.click(2000, 950) # confirm (close keyboard) + + script.click(630, 80) # back from advanced network + + # === Settings - Toggles === + script.click(278, 600) + script.click(1200, 280) # expand experimental mode description + + # === Settings - Software === + script.setup(lambda: setup_update_available(False), wait_after=0) # start with no update available + script.click(278, 720) # software + for _ in range(2): + script.click(720, 120) # toggle current release notes + script.setup(setup_update_available) # set update available + for _ in range(2): + script.click(720, 450) # toggle new release notes + script.click(2000, 630) # open select branch dialog + script.click(1000, 300) # select 1st option + script.click(1600, 900) # confirm selection + script.click(2000, 800) # uninstall + script.click(650, 750) # cancel uninstall + + # === Settings - Firehose === + script.click(278, 845) + + # === Settings - Developer (set CarParamsPersistent first) === + script.setup(setup_developer_params, wait_after=0) + script.click(278, 950) + script.click(1930, 470) # SSH keys (keyboard) + script.click(1930, 115) # click cancel on keyboard + script.click(2000, 960) # toggle alpha long + script.click(1500, 875) # confirm + + # === Close settings === + script.click(250, 160) + + # === Onroad === + script.set_send(lambda: send_onroad(pm)) + script.click(1000, 500) # click onroad to toggle sidebar + test_onroad_alerts(script, pm) + + # End + script.end() + + +def build_script(pm: PubMaster, main_layout, variant: LayoutVariant) -> list[ScriptEntry]: + """Build the replay script for the appropriate layout variant and return list of script entries.""" + print(f"Building {variant} replay script...") + + script = Script(FPS) + builder = build_tizi_script if variant == 'tizi' else build_mici_script + builder(pm, main_layout, script) + + print(f"Built replay script with {len(script.entries)} events and {script.frame} frames ({script.get_frame_time():.2f} seconds)") + + return script.entries diff --git a/openpilot/selfdrive/ui/tests/profile_onroad.py b/openpilot/selfdrive/ui/tests/profile_onroad.py new file mode 100755 index 0000000000..ec15e71c35 --- /dev/null +++ b/openpilot/selfdrive/ui/tests/profile_onroad.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +import os +import time +import cProfile +import pyray as rl +import numpy as np + +from msgq.visionipc import VisionIpcServer, VisionStreamType +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.selfdrive.ui.mici.layouts.main import MiciMainLayout +from openpilot.system.ui.lib.application import gui_app +from openpilot.tools.lib.logreader import LogReader + +FPS = 60 + + +def chunk_messages_by_time(messages): + dt_ns = 1e9 / FPS + chunks = [] + current_services = {} + next_time = messages[0].logMonoTime + dt_ns if messages else 0 + + for msg in messages: + if msg.logMonoTime >= next_time: + chunks.append(current_services) + current_services = {} + next_time += dt_ns * ((msg.logMonoTime - next_time) // dt_ns + 1) + current_services[msg.which()] = msg + + if current_services: + chunks.append(current_services) + return chunks + + +def patch_submaster(message_chunks): + def mock_update(timeout=None): + sm = ui_state.sm + sm.updated = dict.fromkeys(sm.services, False) + current_time = time.monotonic() + for service, msg in message_chunks[sm.frame].items(): + if service in sm.data: + sm.seen[service] = True + sm.updated[service] = True + + msg_builder = msg.as_builder() + sm.data[service] = getattr(msg_builder, service) + sm.logMonoTime[service] = msg.logMonoTime + sm.recv_time[service] = current_time + sm.recv_frame[service] = sm.frame + sm.valid[service] = True + sm.frame += 1 + ui_state.sm.update = mock_update # ty: ignore[invalid-assignment] # profiling hook + + +if __name__ == "__main__": + import argparse + parser = argparse.ArgumentParser(description='Profile openpilot UI rendering and state updates') + parser.add_argument('route', type=str, nargs='?', default="302bab07c1511180/00000006--0b9a7005f1/3", + help='Route to use for profiling') + parser.add_argument('--loop', type=int, default=1, + help='Number of times to loop the log (default: 1)') + parser.add_argument('--output', type=str, default='cachegrind.out.ui', + help='Output file prefix (default: cachegrind.out.ui)') + parser.add_argument('--max-seconds', type=float, default=None, + help='Maximum seconds of messages to process (default: all)') + parser.add_argument('--headless', action='store_true', + help='Run in headless mode without GPU (for CI/testing)') + args = parser.parse_args() + + print(f"Loading log from {args.route}...") + lr = LogReader(args.route, sort_by_time=True) + messages = list(lr) * args.loop + + print("Chunking messages...") + message_chunks = chunk_messages_by_time(messages) + if args.max_seconds: + message_chunks = message_chunks[:int(args.max_seconds * FPS)] + + print("Initializing UI with GPU rendering...") + + if args.headless: + os.environ['SDL_VIDEODRIVER'] = 'dummy' + + gui_app.init_window("UI Profiling", fps=600) + main_layout = MiciMainLayout() + + print("Running...") + patch_submaster(message_chunks) + + W, H = 2048, 1216 + vipc = VisionIpcServer("camerad") + vipc.create_buffers(VisionStreamType.VISION_STREAM_ROAD, 5, W, H) + vipc.start_listener() + yuv_buffer_size = W * H + (W // 2) * (H // 2) * 2 + yuv_data = np.random.default_rng().integers(0, 256, yuv_buffer_size, dtype=np.uint8).tobytes() + with cProfile.Profile() as pr: + for _ in gui_app.render(): + if ui_state.sm.frame >= len(message_chunks): + break + if ui_state.sm.frame % 3 == 0: + eof = int((ui_state.sm.frame % 3) * 0.05 * 1e9) + vipc.send(VisionStreamType.VISION_STREAM_ROAD, yuv_data, ui_state.sm.frame % 3, eof, eof) + ui_state.update() + pr.dump_stats(f'{args.output}_deterministic.stats') + + rl.close_window() + print("\nProfiling complete!") + print(f" run: python -m pstats {args.output}_deterministic.stats") diff --git a/openpilot/selfdrive/ui/tests/test_feedbackd.py b/openpilot/selfdrive/ui/tests/test_feedbackd.py new file mode 100644 index 0000000000..72bd499081 --- /dev/null +++ b/openpilot/selfdrive/ui/tests/test_feedbackd.py @@ -0,0 +1,53 @@ +import pytest +import openpilot.cereal.messaging as messaging +from opendbc.car.structs import car +from openpilot.common.params import Params +from openpilot.system.manager.process_config import managed_processes + + +@pytest.mark.skip("tmp disabled") +class TestFeedbackd: + def setup_method(self): + self.pm = messaging.PubMaster(['carState', 'rawAudioData']) + self.sm = messaging.SubMaster(['audioFeedback']) + + def _send_lkas_button(self, pressed: bool): + msg = messaging.new_message('carState') + msg.carState.canValid = True + msg.carState.buttonEvents = [{'type': car.CarState.ButtonEvent.Type.lkas, 'pressed': pressed}] + self.pm.send('carState', msg) + + def _send_audio_data(self, count: int = 5): + for _ in range(count): + audio_msg = messaging.new_message('rawAudioData') + audio_msg.rawAudioData.data = bytes(1600) # 800 samples of int16 + audio_msg.rawAudioData.sampleRate = 16000 + self.pm.send('rawAudioData', audio_msg) + self.sm.update(timeout=100) + + @pytest.mark.parametrize("record_feedback", [False, True]) + def test_audio_feedback(self, record_feedback): + Params().put_bool("RecordAudioFeedback", record_feedback, block=True) + + managed_processes["feedbackd"].start() + assert self.pm.wait_for_readers_to_update('carState', timeout=5) + assert self.pm.wait_for_readers_to_update('rawAudioData', timeout=5) + + self._send_lkas_button(pressed=True) + self._send_audio_data() + self._send_lkas_button(pressed=False) + self._send_audio_data() + + if record_feedback: + assert self.sm.updated['audioFeedback'], "audioFeedback should be published when enabled" + else: + assert not self.sm.updated['audioFeedback'], "audioFeedback should not be published when disabled" + + self._send_lkas_button(pressed=True) + self._send_audio_data() + self._send_lkas_button(pressed=False) + self._send_audio_data() + + assert not self.sm.updated['audioFeedback'], "audioFeedback should not be published after second press" + + managed_processes["feedbackd"].stop() diff --git a/openpilot/selfdrive/ui/tests/test_raylib_ui.py b/openpilot/selfdrive/ui/tests/test_raylib_ui.py new file mode 100644 index 0000000000..d04c940cde --- /dev/null +++ b/openpilot/selfdrive/ui/tests/test_raylib_ui.py @@ -0,0 +1,9 @@ +import time +from openpilot.selfdrive.test.helpers import with_processes + + +class TestRaylibUi: + @with_processes(["ui"]) + def test_raylib_ui(self): + """Test initialization of the UI widgets is successful.""" + time.sleep(1) diff --git a/openpilot/selfdrive/ui/tests/test_soundd.py b/openpilot/selfdrive/ui/tests/test_soundd.py new file mode 100644 index 0000000000..95588a9fba --- /dev/null +++ b/openpilot/selfdrive/ui/tests/test_soundd.py @@ -0,0 +1,60 @@ +from openpilot.cereal import log, messaging +from openpilot.cereal.messaging import SubMaster, PubMaster +from openpilot.selfdrive.ui.soundd import SELFDRIVE_STATE_TIMEOUT, check_selfdrive_timeout_alert + +import time + +AudibleAlert = log.SelfdriveState.AudibleAlert + + +class TestSoundd: + def test_check_selfdrive_timeout_alert(self): + sm = SubMaster(['selfdriveState', 'selfdriveStateSP']) + pm = PubMaster(['selfdriveState', 'selfdriveStateSP']) + + for _ in range(100): + cs = messaging.new_message('selfdriveState') + cs.selfdriveState.enabled = True + + pm.send("selfdriveState", cs) + + time.sleep(0.01) + + sm.update(0) + + assert not check_selfdrive_timeout_alert(sm) + + for _ in range(SELFDRIVE_STATE_TIMEOUT * 110): + sm.update(0) + time.sleep(0.01) + + assert check_selfdrive_timeout_alert(sm) + + def test_check_selfdrive_timeout_alert_mads_lateral_only(self): + sm = SubMaster(['selfdriveState', 'selfdriveStateSP']) + pm = PubMaster(['selfdriveState', 'selfdriveStateSP']) + + for _ in range(100): + cs = messaging.new_message('selfdriveState') + cs.selfdriveState.enabled = False + + ss_sp = messaging.new_message('selfdriveStateSP') + ss_sp.selfdriveStateSP.mads.enabled = True + + pm.send("selfdriveState", cs) + pm.send("selfdriveStateSP", ss_sp) + + time.sleep(0.01) + + sm.update(0) + + assert not check_selfdrive_timeout_alert(sm) + + for _ in range(SELFDRIVE_STATE_TIMEOUT * 110): + sm.update(0) + time.sleep(0.01) + + assert check_selfdrive_timeout_alert(sm) + + # TODO: add test with micd for checking that soundd actually outputs sounds + diff --git a/openpilot/selfdrive/ui/tests/test_translations.py b/openpilot/selfdrive/ui/tests/test_translations.py new file mode 100644 index 0000000000..9eae072f21 --- /dev/null +++ b/openpilot/selfdrive/ui/tests/test_translations.py @@ -0,0 +1,104 @@ +import json +import re +import string +from pathlib import Path + +import pytest + +from openpilot.selfdrive.ui.translations.potools import parse_po +from openpilot.system.ui.lib.multilang import LANGUAGES_FILE, TRANSLATIONS_DIR + +PERCENT_PLACEHOLDER_RE = re.compile(r"%(?:n|\d+)") +BAD_ENTITY_RE = re.compile(r'@(\w+);') +LINE_NUMBER_REF_RE = re.compile(r'^#:\s+.+:\d+(?:\s|$)') +FORMATTER = string.Formatter() +PO_DIR = Path(str(TRANSLATIONS_DIR)) + +with LANGUAGES_FILE.open(encoding='utf-8') as f: + TRANSLATION_LANGUAGES = json.load(f) + + +def extract_placeholders(text: str) -> list[str]: + placeholders = PERCENT_PLACEHOLDER_RE.findall(text) + + try: + parsed = list(FORMATTER.parse(text)) + except ValueError as e: + raise AssertionError(f"invalid brace formatting in {text!r}: {e}") from e + + for _, field_name, format_spec, conversion in parsed: + if field_name is None: + continue + + token = "{" + token += field_name + if conversion: + token += f"!{conversion}" + if format_spec: + token += f":{format_spec}" + token += "}" + placeholders.append(token) + + return sorted(placeholders) + + +def load_po_text(po_path: Path) -> str: + return po_path.read_text(encoding='utf-8') + + +class TestTranslations: + @pytest.mark.parametrize("language_code", sorted(TRANSLATION_LANGUAGES.values())) + def test_translation_file_exists(self, language_code: str): + po_path = PO_DIR / f"app_{language_code}.po" + assert po_path.exists(), f"missing translation file: {po_path}" + + @pytest.mark.parametrize("po_path", sorted(PO_DIR.glob("app_*.po")), ids=lambda p: p.name) + def test_translation_placeholders_are_preserved(self, po_path: Path): + _, entries = parse_po(po_path) + language = po_path.stem.removeprefix("app_") + + for entry in entries: + source_placeholders = extract_placeholders(entry.msgid) + + if entry.is_plural: + plural_placeholders = extract_placeholders(entry.msgid_plural) + message = ( + f"{language}: source plural placeholders do not match singular for " + + f"{entry.msgid!r}: {source_placeholders} vs {plural_placeholders}" + ) + assert plural_placeholders == source_placeholders, message + + for idx, msgstr in sorted(entry.msgstr_plural.items()): + if not msgstr: + continue + + translated_placeholders = extract_placeholders(msgstr) + message = ( + f"{language}: plural form {idx} changes placeholders for {entry.msgid!r}: " + + f"expected {source_placeholders}, got {translated_placeholders}" + ) + assert translated_placeholders == source_placeholders, message + else: + if not entry.msgstr: + continue + + translated_placeholders = extract_placeholders(entry.msgstr) + message = ( + f"{language}: translation changes placeholders for {entry.msgid!r}: " + + f"expected {source_placeholders}, got {translated_placeholders}" + ) + assert translated_placeholders == source_placeholders, message + + @pytest.mark.parametrize("po_path", sorted(PO_DIR.glob("app_*.po")), ids=lambda p: p.name) + def test_translation_refs_do_not_include_line_numbers(self, po_path: Path): + for line in load_po_text(po_path).splitlines(): + assert not LINE_NUMBER_REF_RE.match(line), ( + f"{po_path.name}: line-number source reference found: {line}" + ) + + @pytest.mark.parametrize("po_path", sorted(PO_DIR.glob("app_*.po")), ids=lambda p: p.name) + def test_translation_entities_are_valid(self, po_path: Path): + matches = BAD_ENTITY_RE.findall(load_po_text(po_path)) + assert not matches, ( + f"{po_path.name}: found '@...;' entity typo(s): {', '.join(sorted(set(matches)))}" + ) diff --git a/openpilot/selfdrive/ui/translations/app.pot b/openpilot/selfdrive/ui/translations/app.pot new file mode 100644 index 0000000000..37a80ff223 --- /dev/null +++ b/openpilot/selfdrive/ui/translations/app.pot @@ -0,0 +1,871 @@ +msgid "" +msgstr "" +"Content-Type: text/plain; charset=UTF-8\n" + +#: system/ui/sunnypilot/widgets/tree_dialog.py +msgid "Search" +msgstr "" + +#: system/ui/sunnypilot/widgets/tree_dialog.py +msgid "Enter search query" +msgstr "" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Pair your GitHub account" +msgstr "" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Early Access: Become a sunnypilot Sponsor" +msgstr "" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Scan the QR code to login to your GitHub account" +msgstr "" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Follow the prompts to complete the pairing process" +msgstr "" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Re-enter the \"sunnylink\" panel to verify sponsorship status" +msgstr "" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "If sponsorship status was not updated, please contact a moderator on the community forum at https://community.sunnypilot.ai" +msgstr "" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Scan the QR code to visit sunnyhaibin's GitHub Sponsors page" +msgstr "" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Choose your sponsorship tier and confirm your support" +msgstr "" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Join our Community Forum at https://community.sunnypilot.ai and reach out to a moderator if you have issues" +msgstr "" + +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/keyboard.py +#: system/ui/widgets/network.py +#: system/ui/widgets/option_dialog.py +msgid "Cancel" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Advanced" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +#: system/ui/widgets/network.py +msgid "Back" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Enter APN" +msgstr "" + +#: system/ui/widgets/network.py +msgid "leave blank for automatic configuration" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Enter SSID" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Enter new tethering password" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Enable Tethering" +msgstr "" + +#: system/ui/widgets/network.py +msgid "EDIT" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Tethering Password" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Enable Roaming" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Cellular Metered" +msgstr "" + +#: system/ui/widgets/network.py +msgid "APN Setting" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Wi-Fi Network Metered" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Enter password" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Scanning Wi-Fi networks..." +msgstr "" + +#: system/ui/widgets/network.py +msgid "CONNECTING..." +msgstr "" + +#: system/ui/widgets/network.py +msgid "Forget" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered cellular connection" +msgstr "" + +#: system/ui/widgets/network.py +msgid "default" +msgstr "" + +#: system/ui/widgets/network.py +msgid "metered" +msgstr "" + +#: system/ui/widgets/network.py +msgid "unmetered" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered Wi-Fi connection" +msgstr "" + +#: system/ui/widgets/network.py +msgid "IP Address" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Hidden Network" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/network.py +msgid "CONNECT" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Wrong password" +msgstr "" + +#: system/ui/widgets/network.py +msgid "FORGETTING..." +msgstr "" + +#: system/ui/widgets/network.py +msgid "for \"{}\"" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Forget Wi-Fi Network \"{}\"?" +msgstr "" + +#: system/ui/widgets/list_view.py +msgid "Error" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/html_render.py +msgid "OK" +msgstr "" + +#: system/ui/widgets/option_dialog.py +msgid "Select" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "LOADING" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "ADD" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "REMOVE" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Request timed out" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Enter your GitHub username" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "No SSH keys found for user '{}'" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Close" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Snooze Update" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Acknowledge Excessive Actuation" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Reboot and Update" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "No release notes available." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer." +msgstr "" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Maximize your training data uploads to improve openpilot's driving models." +msgstr "" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Finish Setup" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair device" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Open" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "🔥 Firehose Mode 🔥" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Please connect to Wi-Fi to complete initial pairing" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "EXPERIMENTAL MODE ON" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "CHILL MODE ON" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Upgrade Now" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "PRIME FEATURES:" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote access" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "24/7 LTE connectivity" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "1 year of drive storage" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote snapshots" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "✓ SUBSCRIBED" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "comma prime" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Become a comma prime member at connect.comma.ai" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Pair your device to your comma account" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Go to https://connect.comma.ai on your phone" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Click \"add new device\" and scan the QR code on the right" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Bookmark connect.comma.ai to your home screen to use it like an app" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "QR Code Error" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "UPDATE" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "{} ALERT" +msgid_plural "{} ALERTS" +msgstr[0] "" +msgstr[1] "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "--" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Wi-Fi" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ETH" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "2G" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "3G" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "LTE" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "5G" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "TEMP" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "GOOD" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "VEHICLE" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ONLINE" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "OFFLINE" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Unknown" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "NO" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "PANDA" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "HIGH" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ERROR" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Welcome to sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms of Service to use sunnypilot. Read the latest terms at https://sunnypilot.ai/terms before continuing." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Agree" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms of Service in order to use sunnypilot." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline, uninstall sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Device" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Network" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Toggles" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Software" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Firehose" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Developer" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off)" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "sunnypilot requires the device to be mounted within 4° left or right and within 5° up or 9° down." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review the rules, features, and limitations of sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Select a language" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reset calibration?" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is complete." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reboot?" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reboot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to power off?" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Power Off" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Pair Device" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PAIR" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset Calibration" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "RESET" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Dongle ID" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Serial" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Driver Camera" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PREVIEW" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review Training Guide" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "REVIEW" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Regulatory" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "VIEW" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Change Language" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "CHANGE" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reset Calibration" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is {}% complete." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reboot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Power Off" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "N/A" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is complete." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Your device is pointed {:.1f}° {} and {:.1f}° {}." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "down" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "up" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "left" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "right" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is {}% complete." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable ADB" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable SSH" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "SSH Keys" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Joystick Debug Mode" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Longitudinal Maneuver Mode" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Lateral Maneuver Mode" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "sunnypilot Longitudinal Control (Alpha)" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "UI Debug Mode" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "Firehose Mode" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "{} segment of your driving is in the training dataset so far." +msgid_plural "{} segments of your driving is in the training dataset so far." +msgstr[0] "" +msgstr[1] "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "When enabled, pressing the accelerator pedal will disengage sunnypilot." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable driver monitoring even when sunnypilot is not engaged." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Upload data from the driver facing camera and help improve the driver monitoring algorithm." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Display speed in km/h instead of mph." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and store microphone audio while driving. The audio will be included in the dashcam video in comma connect." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Driving Personality" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Changing this setting will restart sunnypilot if the car is powered on." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental Mode" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Disengage on Accelerator Pedal" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable Lane Departure Warnings" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Always-On Driver Monitoring" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Driver Camera" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Microphone Audio" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Use Metric System" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "sunnypilot longitudinal control may come in a future update." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Aggressive" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Standard" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Relaxed" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable the sunnypilot longitudinal control (alpha) toggle to allow Experimental mode." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "checking..." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "downloading..." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "finalizing update..." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "never" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "now" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "CHECK" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Are you sure you want to uninstall?" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Uninstall" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Select a branch" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} minute ago" +msgid_plural "{} minutes ago" +msgstr[0] "" +msgstr[1] "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} hour ago" +msgid_plural "{} hours ago" +msgstr[0] "" +msgstr[1] "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} day ago" +msgid_plural "{} days ago" +msgstr[0] "" +msgstr[1] "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Updates are only downloaded while the car is off." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Current Version" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Download" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Install Update" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "INSTALL" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Target Branch" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "SELECT" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "failed to check for update" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "UNINSTALL" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "update available" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "DOWNLOAD" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked never" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked {}" +msgstr "" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "sunnypilot Unavailable" +msgstr "" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Waiting to start" +msgstr "" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "TAKE CONTROL IMMEDIATELY" +msgstr "" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "System Unresponsive" +msgstr "" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Reboot Device" +msgstr "" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "MAX" +msgstr "" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "km/h" +msgstr "" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "mph" +msgstr "" + +#: openpilot/selfdrive/ui/onroad/driver_camera_dialog.py +msgid "camera starting" +msgstr "" + diff --git a/openpilot/selfdrive/ui/translations/app_de.po b/openpilot/selfdrive/ui/translations/app_de.po new file mode 100644 index 0000000000..b4af3fcc1d --- /dev/null +++ b/openpilot/selfdrive/ui/translations/app_de.po @@ -0,0 +1,873 @@ +msgid "" +msgstr "" +"Content-Type: text/plain; charset=UTF-8\n" +"Language: de\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is complete." +msgstr " Die Lenkmoment-Reaktionskalibrierung ist abgeschlossen." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is {}% complete." +msgstr " Die Lenkmoment-Reaktionskalibrierung ist zu {}% abgeschlossen." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Your device is pointed {:.1f}° {} and {:.1f}° {}." +msgstr " Ihr Gerät ist um {:.1f}° {} und {:.1f}° {} ausgerichtet." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "--" +msgstr "--" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "1 year of drive storage" +msgstr "1 Jahr Fahrtdatenspeicherung" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "24/7 LTE connectivity" +msgstr "24/7 LTE‑Verbindung" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "2G" +msgstr "2G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "3G" +msgstr "3G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "5G" +msgstr "5G" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is complete." +msgstr "

Kalibrierung der Lenkverzögerung abgeschlossen." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is {}% complete." +msgstr "

Kalibrierung der Lenkverzögerung zu {}% abgeschlossen." + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "ADD" +msgstr "HINZUFÜGEN" + +#: system/ui/widgets/network.py +msgid "APN Setting" +msgstr "APN‑Einstellung" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Acknowledge Excessive Actuation" +msgstr "Übermäßige Betätigung bestätigen" + +#: system/ui/widgets/network.py +msgid "Advanced" +msgstr "Erweitert" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Aggressive" +msgstr "Aggressiv" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Agree" +msgstr "Zustimmen" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Always-On Driver Monitoring" +msgstr "Immer aktive Fahrerüberwachung" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to power off?" +msgstr "Sind Sie sicher, dass Sie ausschalten möchten?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reboot?" +msgstr "Sind Sie sicher, dass Sie neu starten möchten?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reset calibration?" +msgstr "Sind Sie sicher, dass Sie die Kalibrierung zurücksetzen möchten?" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Are you sure you want to uninstall?" +msgstr "Sind Sie sicher, dass Sie deinstallieren möchten?" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +#: system/ui/widgets/network.py +msgid "Back" +msgstr "Zurück" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Become a comma prime member at connect.comma.ai" +msgstr "Werden Sie comma prime Mitglied auf connect.comma.ai" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Bookmark connect.comma.ai to your home screen to use it like an app" +msgstr "Fügen Sie connect.comma.ai Ihrem Startbildschirm hinzu, um es wie eine App zu verwenden" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "CHANGE" +msgstr "ÄNDERN" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "CHECK" +msgstr "PRÜFEN" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "CHILL MODE ON" +msgstr "CHILL‑MODUS AKTIV" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/network.py +msgid "CONNECT" +msgstr "VERBINDUNG" + +#: system/ui/widgets/network.py +msgid "CONNECTING..." +msgstr "VERBINDUNG" + +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/keyboard.py +#: system/ui/widgets/network.py +#: system/ui/widgets/option_dialog.py +msgid "Cancel" +msgstr "Abbrechen" + +#: system/ui/widgets/network.py +msgid "Cellular Metered" +msgstr "Getaktete Mobilfunkverbindung" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Change Language" +msgstr "Sprache ändern" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Changing this setting will restart sunnypilot if the car is powered on." +msgstr "" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Choose your sponsorship tier and confirm your support" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Click \"add new device\" and scan the QR code on the right" +msgstr "Klicken Sie auf \"add new device\" und scannen Sie den QR‑Code rechts" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Close" +msgstr "Schließen" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Current Version" +msgstr "Aktuelle Version" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "DOWNLOAD" +msgstr "HERUNTERLADEN" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline" +msgstr "Ablehnen" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline, uninstall sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Developer" +msgstr "Entwickler" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Device" +msgstr "Gerät" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Disengage on Accelerator Pedal" +msgstr "Beim Gaspedal deaktivieren" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Power Off" +msgstr "Zum Ausschalten deaktivieren" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reboot" +msgstr "Zum Neustart deaktivieren" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reset Calibration" +msgstr "Zum Zurücksetzen der Kalibrierung deaktivieren" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Display speed in km/h instead of mph." +msgstr "Geschwindigkeit in km/h statt mph anzeigen." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Dongle ID" +msgstr "Dongle-ID" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Download" +msgstr "Herunterladen" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Driver Camera" +msgstr "Fahrerkamera" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Driving Personality" +msgstr "Fahrstil" + +#: system/ui/widgets/network.py +msgid "EDIT" +msgstr "BEARBEITEN" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ERROR" +msgstr "FEHLER" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ETH" +msgstr "ETH" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "EXPERIMENTAL MODE ON" +msgstr "EXPERIMENTALMODUS AKTIV" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Early Access: Become a sunnypilot Sponsor" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable" +msgstr "Aktivieren" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable ADB" +msgstr "ADB aktivieren" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable Lane Departure Warnings" +msgstr "Spurverlassenswarnungen aktivieren" + +#: system/ui/widgets/network.py +msgid "Enable Roaming" +msgstr "Roaming aktivieren" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable SSH" +msgstr "SSH aktivieren" + +#: system/ui/widgets/network.py +msgid "Enable Tethering" +msgstr "Tethering aktivieren" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable driver monitoring even when sunnypilot is not engaged." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable the sunnypilot longitudinal control (alpha) toggle to allow Experimental mode." +msgstr "" + +#: system/ui/widgets/network.py +msgid "Enter APN" +msgstr "APN eingeben" + +#: system/ui/widgets/network.py +msgid "Enter SSID" +msgstr "SSID eingeben" + +#: system/ui/widgets/network.py +msgid "Enter new tethering password" +msgstr "Neues Tethering‑Passwort eingeben" + +#: system/ui/widgets/network.py +msgid "Enter password" +msgstr "Passwort eingeben" + +#: system/ui/sunnypilot/widgets/tree_dialog.py +msgid "Enter search query" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Enter your GitHub username" +msgstr "Geben Sie Ihren GitHub‑Benutzernamen ein" + +#: system/ui/widgets/list_view.py +msgid "Error" +msgstr "Fehler" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental Mode" +msgstr "Experimentalmodus" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control." +msgstr "Der Experimentalmodus ist derzeit auf diesem Fahrzeug nicht verfügbar, da der serienmäßige ACC für die Längsregelung verwendet wird." + +#: system/ui/widgets/network.py +msgid "FORGETTING..." +msgstr "WIRD VERGESSEN..." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Finish Setup" +msgstr "Einrichtung abschließen" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Firehose" +msgstr "Datenstrom" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "Firehose Mode" +msgstr "Firehose‑Modus" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Follow the prompts to complete the pairing process" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Forget" +msgstr "Vergessen" + +#: system/ui/widgets/network.py +msgid "Forget Wi-Fi Network \"{}\"?" +msgstr "WLAN‑Netz „{}“ vergessen?" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "GOOD" +msgstr "GUT" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Go to https://connect.comma.ai on your phone" +msgstr "Gehen Sie auf Ihrem Telefon zu https://connect.comma.ai" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "HIGH" +msgstr "HOCH" + +#: system/ui/widgets/network.py +msgid "Hidden Network" +msgstr "Verstecktes Netzwerk" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "INSTALL" +msgstr "INSTALLIEREN" + +#: system/ui/widgets/network.py +msgid "IP Address" +msgstr "IP‑Adresse" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "If sponsorship status was not updated, please contact a moderator on the community forum at https://community.sunnypilot.ai" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Install Update" +msgstr "Update installieren" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Join our Community Forum at https://community.sunnypilot.ai and reach out to a moderator if you have issues" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Joystick Debug Mode" +msgstr "Joystick‑Debugmodus" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "LOADING" +msgstr "LADEN" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "LTE" +msgstr "LTE" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Lateral Maneuver Mode" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Longitudinal Maneuver Mode" +msgstr "Längsmanövermodus" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "MAX" +msgstr "MAX." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Maximize your training data uploads to improve openpilot's driving models." +msgstr "Maximieren Sie Ihre Trainingsdaten‑Uploads, um die Fahrmodelle von openpilot zu verbessern." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "N/A" +msgstr "k. A." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "NO" +msgstr "KEIN" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Network" +msgstr "Netzwerk" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "No SSH keys found for user '{}'" +msgstr "Keine SSH‑Schlüssel für Benutzer '{}' gefunden" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "No release notes available." +msgstr "Keine Versionshinweise verfügbar." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "OFFLINE" +msgstr "GETRENNT" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/html_render.py +msgid "OK" +msgstr "OK" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ONLINE" +msgstr "VERBUNDEN" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Open" +msgstr "Öffnen" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PAIR" +msgstr "KOPPELN" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "PANDA" +msgstr "PANDA" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PREVIEW" +msgstr "VORSCHAU" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "PRIME FEATURES:" +msgstr "PRIME‑FUNKTIONEN:" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Pair Device" +msgstr "Gerät koppeln" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair device" +msgstr "Gerät koppeln" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Pair your GitHub account" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Pair your device to your comma account" +msgstr "Koppeln Sie Ihr Gerät mit Ihrem comma‑Konto" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer." +msgstr "Koppeln Sie Ihr Gerät mit comma connect (connect.comma.ai) und lösen Sie Ihr comma‑prime‑Angebot ein." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Please connect to Wi-Fi to complete initial pairing" +msgstr "Bitte mit WLAN verbinden, um das erste Koppeln abzuschließen" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Power Off" +msgstr "Ausschalten" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered Wi-Fi connection" +msgstr "Verhindern Sie das Hochladen großer Datenmengen bei einer getakteten WLAN-Verbindung" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered cellular connection" +msgstr "Verhindern Sie das Hochladen großer Datenmengen bei einer getakteten Mobilfunkverbindung" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off)" +msgstr "Vorschau der Fahrer‑Kamera, um sicherzustellen, dass die Fahrerüberwachung gute Sicht hat. (Fahrzeug muss ausgeschaltet sein)" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "QR Code Error" +msgstr "QR‑Code‑Fehler" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "REMOVE" +msgstr "ENTFERNEN" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "RESET" +msgstr "ZURÜCKSETZEN" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "REVIEW" +msgstr "ANSEHEN" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Re-enter the \"sunnylink\" panel to verify sponsorship status" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reboot" +msgstr "Neustart" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Reboot Device" +msgstr "Gerät neu starten" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Reboot and Update" +msgstr "Neustarten und aktualisieren" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Driver Camera" +msgstr "Fahrerkamera aufzeichnen und hochladen" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Microphone Audio" +msgstr "Mikrofonton aufzeichnen und hochladen" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and store microphone audio while driving. The audio will be included in the dashcam video in comma connect." +msgstr "Mikrofonton während der Fahrt aufzeichnen und speichern. Die Audiospur wird im Dashcam‑Video in comma connect enthalten sein." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Regulatory" +msgstr "Vorschriften" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Relaxed" +msgstr "Entspannt" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote access" +msgstr "Fernzugriff" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote snapshots" +msgstr "Remote‑Schnappschüsse" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Request timed out" +msgstr "Zeitüberschreitung bei der Anfrage" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset" +msgstr "Zurücksetzen" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset Calibration" +msgstr "Kalibrierung zurücksetzen" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review Training Guide" +msgstr "Trainingsanleitung ansehen" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review the rules, features, and limitations of sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "SELECT" +msgstr "WÄHLEN" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "SSH Keys" +msgstr "SSH‑Schlüssel" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Scan the QR code to login to your GitHub account" +msgstr "" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Scan the QR code to visit sunnyhaibin's GitHub Sponsors page" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Scanning Wi-Fi networks..." +msgstr "WLAN‑Netzwerke werden gesucht..." + +#: system/ui/sunnypilot/widgets/tree_dialog.py +msgid "Search" +msgstr "" + +#: system/ui/widgets/option_dialog.py +msgid "Select" +msgstr "Auswählen" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Select a branch" +msgstr "Zweig auswählen" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Select a language" +msgstr "Sprache auswählen" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Serial" +msgstr "Seriennummer" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Snooze Update" +msgstr "Update verschieben" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Software" +msgstr "Softwarebereich" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Standard" +msgstr "Standardmodus" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "System Unresponsive" +msgstr "System reagiert nicht" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "TAKE CONTROL IMMEDIATELY" +msgstr "SOFORT DIE KONTROLLE ÜBERNEHMEN" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "TEMP" +msgstr "TEMP." + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Target Branch" +msgstr "Zielzweig" + +#: system/ui/widgets/network.py +msgid "Tethering Password" +msgstr "Tethering‑Passwort" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Toggles" +msgstr "Schalter" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "UI Debug Mode" +msgstr "UI-Debug-Modus" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "UNINSTALL" +msgstr "DEINSTALLIEREN" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "UPDATE" +msgstr "AKTUALISIEREN" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Uninstall" +msgstr "Deinstallieren" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Unknown" +msgstr "Unbekannt" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Updates are only downloaded while the car is off." +msgstr "Updates werden nur heruntergeladen, wenn das Auto aus ist." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Upgrade Now" +msgstr "Jetzt abonnieren" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Upload data from the driver facing camera and help improve the driver monitoring algorithm." +msgstr "Daten von der Fahrer‑Kamera hochladen und den Fahrerüberwachungs‑Algorithmus verbessern." + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Use Metric System" +msgstr "Metersystem verwenden" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "VEHICLE" +msgstr "FAHRZEUG" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "VIEW" +msgstr "ANSEHEN" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Waiting to start" +msgstr "Warten auf Start" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Welcome to sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "When enabled, pressing the accelerator pedal will disengage sunnypilot." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Wi-Fi" +msgstr "WLAN" + +#: system/ui/widgets/network.py +msgid "Wi-Fi Network Metered" +msgstr "Getaktetes WLAN‑Netzwerk" + +#: system/ui/widgets/network.py +msgid "Wrong password" +msgstr "Falsches Passwort" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms of Service in order to use sunnypilot." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms of Service to use sunnypilot. Read the latest terms at https://sunnypilot.ai/terms before continuing." +msgstr "" + +#: openpilot/selfdrive/ui/onroad/driver_camera_dialog.py +msgid "camera starting" +msgstr "Kamera startet" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "checking..." +msgstr "Überprüfung..." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "comma prime" +msgstr "comma prime" + +#: system/ui/widgets/network.py +msgid "default" +msgstr "Standard" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "down" +msgstr "unten" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "downloading..." +msgstr "Herunterladen..." + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "failed to check for update" +msgstr "Überprüfung auf Updates fehlgeschlagen" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "finalizing update..." +msgstr "Update wird finalisiert..." + +#: system/ui/widgets/network.py +msgid "for \"{}\"" +msgstr "für „{}“" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "km/h" +msgstr "km/h" + +#: system/ui/widgets/network.py +msgid "leave blank for automatic configuration" +msgstr "für automatische Konfiguration leer lassen" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "left" +msgstr "links" + +#: system/ui/widgets/network.py +msgid "metered" +msgstr "getaktet" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "mph" +msgstr "mph" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "never" +msgstr "nie" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "now" +msgstr "jetzt" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "right" +msgstr "rechts" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "sunnypilot Longitudinal Control (Alpha)" +msgstr "" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "sunnypilot Unavailable" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "sunnypilot longitudinal control may come in a future update." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "sunnypilot requires the device to be mounted within 4° left or right and within 5° up or 9° down." +msgstr "" + +#: system/ui/widgets/network.py +msgid "unmetered" +msgstr "unbegrenzt" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "up" +msgstr "oben" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked never" +msgstr "Aktuell, zuletzt geprüft: nie" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked {}" +msgstr "Aktuell, zuletzt geprüft: {}" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "update available" +msgstr "Update verfügbar" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "{} ALERT" +msgid_plural "{} ALERTS" +msgstr[0] "{} WARNUNG" +msgstr[1] "{} WARNUNGEN" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} day ago" +msgid_plural "{} days ago" +msgstr[0] "vor {} Tag" +msgstr[1] "vor {} Tagen" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} hour ago" +msgid_plural "{} hours ago" +msgstr[0] "vor {} Stunde" +msgstr[1] "vor {} Stunden" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} minute ago" +msgid_plural "{} minutes ago" +msgstr[0] "vor {} Minute" +msgstr[1] "vor {} Minuten" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "{} segment of your driving is in the training dataset so far." +msgid_plural "{} segments of your driving is in the training dataset so far." +msgstr[0] "{} Segment Ihrer Fahrten ist bisher im Trainingsdatensatz." +msgstr[1] "{} Segmente Ihrer Fahrten sind bisher im Trainingsdatensatz." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "✓ SUBSCRIBED" +msgstr "✓ ABONNIERT" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "🔥 Firehose Mode 🔥" +msgstr "🔥 Firehose‑Modus 🔥" + diff --git a/openpilot/selfdrive/ui/translations/app_en.po b/openpilot/selfdrive/ui/translations/app_en.po new file mode 100644 index 0000000000..ad2ed1241f --- /dev/null +++ b/openpilot/selfdrive/ui/translations/app_en.po @@ -0,0 +1,873 @@ +msgid "" +msgstr "" +"Content-Type: text/plain; charset=UTF-8\n" +"Language: en\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is complete." +msgstr " Steering torque response calibration is complete." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is {}% complete." +msgstr " Steering torque response calibration is {}% complete." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Your device is pointed {:.1f}° {} and {:.1f}° {}." +msgstr " Your device is pointed {:.1f}° {} and {:.1f}° {}." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "--" +msgstr "--" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "1 year of drive storage" +msgstr "1 year of drive storage" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "24/7 LTE connectivity" +msgstr "24/7 LTE connectivity" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "2G" +msgstr "2G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "3G" +msgstr "3G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "5G" +msgstr "5G" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is complete." +msgstr "

Steering lag calibration is complete." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is {}% complete." +msgstr "

Steering lag calibration is {}% complete." + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "ADD" +msgstr "ADD" + +#: system/ui/widgets/network.py +msgid "APN Setting" +msgstr "APN Setting" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Acknowledge Excessive Actuation" +msgstr "Acknowledge Excessive Actuation" + +#: system/ui/widgets/network.py +msgid "Advanced" +msgstr "Advanced" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Aggressive" +msgstr "Aggressive" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Agree" +msgstr "Agree" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Always-On Driver Monitoring" +msgstr "Always-On Driver Monitoring" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to power off?" +msgstr "Are you sure you want to power off?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reboot?" +msgstr "Are you sure you want to reboot?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reset calibration?" +msgstr "Are you sure you want to reset calibration?" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Are you sure you want to uninstall?" +msgstr "Are you sure you want to uninstall?" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +#: system/ui/widgets/network.py +msgid "Back" +msgstr "Back" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Become a comma prime member at connect.comma.ai" +msgstr "Become a comma prime member at connect.comma.ai" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Bookmark connect.comma.ai to your home screen to use it like an app" +msgstr "Bookmark connect.comma.ai to your home screen to use it like an app" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "CHANGE" +msgstr "CHANGE" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "CHECK" +msgstr "CHECK" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "CHILL MODE ON" +msgstr "CHILL MODE ON" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/network.py +msgid "CONNECT" +msgstr "CONNECT" + +#: system/ui/widgets/network.py +msgid "CONNECTING..." +msgstr "CONNECTING..." + +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/keyboard.py +#: system/ui/widgets/network.py +#: system/ui/widgets/option_dialog.py +msgid "Cancel" +msgstr "Cancel" + +#: system/ui/widgets/network.py +msgid "Cellular Metered" +msgstr "Cellular Metered" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Change Language" +msgstr "Change Language" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Changing this setting will restart sunnypilot if the car is powered on." +msgstr "" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Choose your sponsorship tier and confirm your support" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Click \"add new device\" and scan the QR code on the right" +msgstr "Click \"add new device\" and scan the QR code on the right" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Close" +msgstr "Close" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Current Version" +msgstr "Current Version" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "DOWNLOAD" +msgstr "DOWNLOAD" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline" +msgstr "Decline" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline, uninstall sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Developer" +msgstr "Developer" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Device" +msgstr "Device" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Disengage on Accelerator Pedal" +msgstr "Disengage on Accelerator Pedal" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Power Off" +msgstr "Disengage to Power Off" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reboot" +msgstr "Disengage to Reboot" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reset Calibration" +msgstr "Disengage to Reset Calibration" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Display speed in km/h instead of mph." +msgstr "Display speed in km/h instead of mph." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Dongle ID" +msgstr "Dongle ID" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Download" +msgstr "Download" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Driver Camera" +msgstr "Driver Camera" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Driving Personality" +msgstr "Driving Personality" + +#: system/ui/widgets/network.py +msgid "EDIT" +msgstr "EDIT" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ERROR" +msgstr "ERROR" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ETH" +msgstr "ETH" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "EXPERIMENTAL MODE ON" +msgstr "EXPERIMENTAL MODE ON" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Early Access: Become a sunnypilot Sponsor" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable" +msgstr "Enable" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable ADB" +msgstr "Enable ADB" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable Lane Departure Warnings" +msgstr "Enable Lane Departure Warnings" + +#: system/ui/widgets/network.py +msgid "Enable Roaming" +msgstr "Enable Roaming" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable SSH" +msgstr "Enable SSH" + +#: system/ui/widgets/network.py +msgid "Enable Tethering" +msgstr "Enable Tethering" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable driver monitoring even when sunnypilot is not engaged." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable the sunnypilot longitudinal control (alpha) toggle to allow Experimental mode." +msgstr "" + +#: system/ui/widgets/network.py +msgid "Enter APN" +msgstr "Enter APN" + +#: system/ui/widgets/network.py +msgid "Enter SSID" +msgstr "Enter SSID" + +#: system/ui/widgets/network.py +msgid "Enter new tethering password" +msgstr "Enter new tethering password" + +#: system/ui/widgets/network.py +msgid "Enter password" +msgstr "Enter password" + +#: system/ui/sunnypilot/widgets/tree_dialog.py +msgid "Enter search query" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Enter your GitHub username" +msgstr "Enter your GitHub username" + +#: system/ui/widgets/list_view.py +msgid "Error" +msgstr "Error" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental Mode" +msgstr "Experimental Mode" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control." +msgstr "Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control." + +#: system/ui/widgets/network.py +msgid "FORGETTING..." +msgstr "FORGETTING..." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Finish Setup" +msgstr "Finish Setup" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Firehose" +msgstr "Firehose" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "Firehose Mode" +msgstr "Firehose Mode" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Follow the prompts to complete the pairing process" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Forget" +msgstr "Forget" + +#: system/ui/widgets/network.py +msgid "Forget Wi-Fi Network \"{}\"?" +msgstr "Forget Wi-Fi Network \"{}\"?" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "GOOD" +msgstr "GOOD" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Go to https://connect.comma.ai on your phone" +msgstr "Go to https://connect.comma.ai on your phone" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "HIGH" +msgstr "HIGH" + +#: system/ui/widgets/network.py +msgid "Hidden Network" +msgstr "Hidden Network" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "INSTALL" +msgstr "INSTALL" + +#: system/ui/widgets/network.py +msgid "IP Address" +msgstr "IP Address" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "If sponsorship status was not updated, please contact a moderator on the community forum at https://community.sunnypilot.ai" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Install Update" +msgstr "Install Update" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Join our Community Forum at https://community.sunnypilot.ai and reach out to a moderator if you have issues" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Joystick Debug Mode" +msgstr "Joystick Debug Mode" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "LOADING" +msgstr "LOADING" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "LTE" +msgstr "LTE" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Lateral Maneuver Mode" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Longitudinal Maneuver Mode" +msgstr "Longitudinal Maneuver Mode" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "MAX" +msgstr "MAX" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Maximize your training data uploads to improve openpilot's driving models." +msgstr "Maximize your training data uploads to improve openpilot's driving models." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "N/A" +msgstr "N/A" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "NO" +msgstr "NO" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Network" +msgstr "Network" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "No SSH keys found for user '{}'" +msgstr "No SSH keys found for user '{}'" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "No release notes available." +msgstr "No release notes available." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "OFFLINE" +msgstr "OFFLINE" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/html_render.py +msgid "OK" +msgstr "OK" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ONLINE" +msgstr "ONLINE" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Open" +msgstr "Open" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PAIR" +msgstr "PAIR" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "PANDA" +msgstr "PANDA" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PREVIEW" +msgstr "PREVIEW" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "PRIME FEATURES:" +msgstr "PRIME FEATURES:" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Pair Device" +msgstr "Pair Device" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair device" +msgstr "Pair device" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Pair your GitHub account" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Pair your device to your comma account" +msgstr "Pair your device to your comma account" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer." +msgstr "Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Please connect to Wi-Fi to complete initial pairing" +msgstr "Please connect to Wi-Fi to complete initial pairing" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Power Off" +msgstr "Power Off" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered Wi-Fi connection" +msgstr "Prevent large data uploads when on a metered Wi-Fi connection" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered cellular connection" +msgstr "Prevent large data uploads when on a metered cellular connection" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off)" +msgstr "Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off)" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "QR Code Error" +msgstr "QR Code Error" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "REMOVE" +msgstr "REMOVE" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "RESET" +msgstr "RESET" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "REVIEW" +msgstr "REVIEW" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Re-enter the \"sunnylink\" panel to verify sponsorship status" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reboot" +msgstr "Reboot" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Reboot Device" +msgstr "Reboot Device" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Reboot and Update" +msgstr "Reboot and Update" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Driver Camera" +msgstr "Record and Upload Driver Camera" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Microphone Audio" +msgstr "Record and Upload Microphone Audio" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and store microphone audio while driving. The audio will be included in the dashcam video in comma connect." +msgstr "Record and store microphone audio while driving. The audio will be included in the dashcam video in comma connect." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Regulatory" +msgstr "Regulatory" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Relaxed" +msgstr "Relaxed" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote access" +msgstr "Remote access" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote snapshots" +msgstr "Remote snapshots" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Request timed out" +msgstr "Request timed out" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset" +msgstr "Reset" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset Calibration" +msgstr "Reset Calibration" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review Training Guide" +msgstr "Review Training Guide" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review the rules, features, and limitations of sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "SELECT" +msgstr "SELECT" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "SSH Keys" +msgstr "SSH Keys" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Scan the QR code to login to your GitHub account" +msgstr "" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Scan the QR code to visit sunnyhaibin's GitHub Sponsors page" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Scanning Wi-Fi networks..." +msgstr "Scanning Wi-Fi networks..." + +#: system/ui/sunnypilot/widgets/tree_dialog.py +msgid "Search" +msgstr "" + +#: system/ui/widgets/option_dialog.py +msgid "Select" +msgstr "Select" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Select a branch" +msgstr "Select a branch" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Select a language" +msgstr "Select a language" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Serial" +msgstr "Serial" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Snooze Update" +msgstr "Snooze Update" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Software" +msgstr "Software" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Standard" +msgstr "Standard" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "System Unresponsive" +msgstr "System Unresponsive" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "TAKE CONTROL IMMEDIATELY" +msgstr "TAKE CONTROL IMMEDIATELY" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "TEMP" +msgstr "TEMP" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Target Branch" +msgstr "Target Branch" + +#: system/ui/widgets/network.py +msgid "Tethering Password" +msgstr "Tethering Password" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Toggles" +msgstr "Toggles" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "UI Debug Mode" +msgstr "UI Debug Mode" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "UNINSTALL" +msgstr "UNINSTALL" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "UPDATE" +msgstr "UPDATE" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Uninstall" +msgstr "Uninstall" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Unknown" +msgstr "Unknown" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Updates are only downloaded while the car is off." +msgstr "Updates are only downloaded while the car is off." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Upgrade Now" +msgstr "Upgrade Now" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Upload data from the driver facing camera and help improve the driver monitoring algorithm." +msgstr "Upload data from the driver facing camera and help improve the driver monitoring algorithm." + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Use Metric System" +msgstr "Use Metric System" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "VEHICLE" +msgstr "VEHICLE" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "VIEW" +msgstr "VIEW" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Waiting to start" +msgstr "Waiting to start" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Welcome to sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "When enabled, pressing the accelerator pedal will disengage sunnypilot." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Wi-Fi" +msgstr "Wi-Fi" + +#: system/ui/widgets/network.py +msgid "Wi-Fi Network Metered" +msgstr "Wi-Fi Network Metered" + +#: system/ui/widgets/network.py +msgid "Wrong password" +msgstr "Wrong password" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms of Service in order to use sunnypilot." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms of Service to use sunnypilot. Read the latest terms at https://sunnypilot.ai/terms before continuing." +msgstr "" + +#: openpilot/selfdrive/ui/onroad/driver_camera_dialog.py +msgid "camera starting" +msgstr "camera starting" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "checking..." +msgstr "checking..." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "comma prime" +msgstr "comma prime" + +#: system/ui/widgets/network.py +msgid "default" +msgstr "default" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "down" +msgstr "down" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "downloading..." +msgstr "downloading..." + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "failed to check for update" +msgstr "failed to check for update" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "finalizing update..." +msgstr "finalizing update..." + +#: system/ui/widgets/network.py +msgid "for \"{}\"" +msgstr "for \"{}\"" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "km/h" +msgstr "km/h" + +#: system/ui/widgets/network.py +msgid "leave blank for automatic configuration" +msgstr "leave blank for automatic configuration" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "left" +msgstr "left" + +#: system/ui/widgets/network.py +msgid "metered" +msgstr "metered" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "mph" +msgstr "mph" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "never" +msgstr "never" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "now" +msgstr "now" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "right" +msgstr "right" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "sunnypilot Longitudinal Control (Alpha)" +msgstr "" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "sunnypilot Unavailable" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "sunnypilot longitudinal control may come in a future update." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "sunnypilot requires the device to be mounted within 4° left or right and within 5° up or 9° down." +msgstr "" + +#: system/ui/widgets/network.py +msgid "unmetered" +msgstr "unmetered" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "up" +msgstr "up" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked never" +msgstr "up to date, last checked never" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked {}" +msgstr "up to date, last checked {}" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "update available" +msgstr "update available" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "{} ALERT" +msgid_plural "{} ALERTS" +msgstr[0] "{} ALERT" +msgstr[1] "{} ALERTS" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} day ago" +msgid_plural "{} days ago" +msgstr[0] "{} day ago" +msgstr[1] "{} days ago" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} hour ago" +msgid_plural "{} hours ago" +msgstr[0] "{} hour ago" +msgstr[1] "{} hours ago" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} minute ago" +msgid_plural "{} minutes ago" +msgstr[0] "{} minute ago" +msgstr[1] "{} minutes ago" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "{} segment of your driving is in the training dataset so far." +msgid_plural "{} segments of your driving is in the training dataset so far." +msgstr[0] "{} segment of your driving is in the training dataset so far." +msgstr[1] "{} segments of your driving is in the training dataset so far." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "✓ SUBSCRIBED" +msgstr "✓ SUBSCRIBED" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "🔥 Firehose Mode 🔥" +msgstr "🔥 Firehose Mode 🔥" + diff --git a/openpilot/selfdrive/ui/translations/app_es.po b/openpilot/selfdrive/ui/translations/app_es.po new file mode 100644 index 0000000000..2298fdb5a1 --- /dev/null +++ b/openpilot/selfdrive/ui/translations/app_es.po @@ -0,0 +1,873 @@ +msgid "" +msgstr "" +"Content-Type: text/plain; charset=UTF-8\n" +"Language: es\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is complete." +msgstr " La calibración de respuesta de par de dirección está completa." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is {}% complete." +msgstr " La calibración de respuesta de par de dirección está {}% completa." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Your device is pointed {:.1f}° {} and {:.1f}° {}." +msgstr " Tu dispositivo está orientado {:.1f}° {} y {:.1f}° {}." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "--" +msgstr "--" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "1 year of drive storage" +msgstr "1 año de almacenamiento de conducción" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "24/7 LTE connectivity" +msgstr "Conectividad LTE 24/7" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "2G" +msgstr "2G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "3G" +msgstr "3G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "5G" +msgstr "5G" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is complete." +msgstr "

La calibración del retraso de dirección está completa." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is {}% complete." +msgstr "

La calibración del retraso de dirección está completa en un {}%." + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "ADD" +msgstr "AÑADIR" + +#: system/ui/widgets/network.py +msgid "APN Setting" +msgstr "Configuración de APN" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Acknowledge Excessive Actuation" +msgstr "Reconocer actuación excesiva" + +#: system/ui/widgets/network.py +msgid "Advanced" +msgstr "Avanzado" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Aggressive" +msgstr "Agresivo" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Agree" +msgstr "Aceptar" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Always-On Driver Monitoring" +msgstr "Supervisión del conductor siempre activa" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to power off?" +msgstr "¿Seguro que quieres apagar?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reboot?" +msgstr "¿Seguro que quieres reiniciar?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reset calibration?" +msgstr "¿Seguro que quieres restablecer la calibración?" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Are you sure you want to uninstall?" +msgstr "¿Seguro que quieres desinstalar?" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +#: system/ui/widgets/network.py +msgid "Back" +msgstr "Atrás" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Become a comma prime member at connect.comma.ai" +msgstr "Hazte miembro de comma prime en connect.comma.ai" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Bookmark connect.comma.ai to your home screen to use it like an app" +msgstr "Añade connect.comma.ai a tu pantalla de inicio para usarlo como una app" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "CHANGE" +msgstr "CAMBIAR" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "CHECK" +msgstr "COMPROBAR" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "CHILL MODE ON" +msgstr "MODO CHILL ACTIVADO" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/network.py +msgid "CONNECT" +msgstr "CONECTAR" + +#: system/ui/widgets/network.py +msgid "CONNECTING..." +msgstr "CONECTAR" + +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/keyboard.py +#: system/ui/widgets/network.py +#: system/ui/widgets/option_dialog.py +msgid "Cancel" +msgstr "Cancelar" + +#: system/ui/widgets/network.py +msgid "Cellular Metered" +msgstr "Medición celular" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Change Language" +msgstr "Cambiar idioma" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Changing this setting will restart sunnypilot if the car is powered on." +msgstr "" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Choose your sponsorship tier and confirm your support" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Click \"add new device\" and scan the QR code on the right" +msgstr "Haz clic en \"añadir nuevo dispositivo\" y escanea el código QR de la derecha" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Close" +msgstr "Cerrar" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Current Version" +msgstr "Versión actual" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "DOWNLOAD" +msgstr "DESCARGAR" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline" +msgstr "Rechazar" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline, uninstall sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Developer" +msgstr "Desarrollador" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Device" +msgstr "Dispositivo" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Disengage on Accelerator Pedal" +msgstr "Desactivar con el pedal del acelerador" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Power Off" +msgstr "Desactivar para apagar" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reboot" +msgstr "Desactivar para reiniciar" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reset Calibration" +msgstr "Desactivar para restablecer la calibración" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Display speed in km/h instead of mph." +msgstr "Mostrar la velocidad en km/h en lugar de mph." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Dongle ID" +msgstr "ID del dongle" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Download" +msgstr "Descargar" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Driver Camera" +msgstr "Cámara del conductor" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Driving Personality" +msgstr "Estilo de conducción" + +#: system/ui/widgets/network.py +msgid "EDIT" +msgstr "EDITAR" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ERROR" +msgstr "FALLO" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ETH" +msgstr "ETH" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "EXPERIMENTAL MODE ON" +msgstr "MODO EXPERIMENTAL ACTIVADO" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Early Access: Become a sunnypilot Sponsor" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable" +msgstr "Activar" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable ADB" +msgstr "Activar ADB" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable Lane Departure Warnings" +msgstr "Activar advertencias de salida de carril" + +#: system/ui/widgets/network.py +msgid "Enable Roaming" +msgstr "Activar roaming" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable SSH" +msgstr "Activar SSH" + +#: system/ui/widgets/network.py +msgid "Enable Tethering" +msgstr "Activar anclaje" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable driver monitoring even when sunnypilot is not engaged." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable the sunnypilot longitudinal control (alpha) toggle to allow Experimental mode." +msgstr "" + +#: system/ui/widgets/network.py +msgid "Enter APN" +msgstr "Introduce APN" + +#: system/ui/widgets/network.py +msgid "Enter SSID" +msgstr "Introduzca SSID" + +#: system/ui/widgets/network.py +msgid "Enter new tethering password" +msgstr "Ingrese una nueva contraseña de anclaje a red" + +#: system/ui/widgets/network.py +msgid "Enter password" +msgstr "Introduce la contraseña" + +#: system/ui/sunnypilot/widgets/tree_dialog.py +msgid "Enter search query" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Enter your GitHub username" +msgstr "Introduce tu nombre de usuario de GitHub" + +#: system/ui/widgets/list_view.py +msgid "Error" +msgstr "Fallo" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental Mode" +msgstr "Modo experimental" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control." +msgstr "El modo experimental no está disponible actualmente en este coche, ya que se usa el ACC de fábrica para el control longitudinal." + +#: system/ui/widgets/network.py +msgid "FORGETTING..." +msgstr "OLVIDAR..." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Finish Setup" +msgstr "Finalizar configuración" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Firehose" +msgstr "Flujo masivo" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "Firehose Mode" +msgstr "Modo Firehose" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Follow the prompts to complete the pairing process" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Forget" +msgstr "Olvidar" + +#: system/ui/widgets/network.py +msgid "Forget Wi-Fi Network \"{}\"?" +msgstr "¿Olvidaste la red Wi-Fi \"{}\"?" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "GOOD" +msgstr "BUENO" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Go to https://connect.comma.ai on your phone" +msgstr "Ve a https://connect.comma.ai en tu teléfono" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "HIGH" +msgstr "ALTO" + +#: system/ui/widgets/network.py +msgid "Hidden Network" +msgstr "Red oculta" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "INSTALL" +msgstr "INSTALAR" + +#: system/ui/widgets/network.py +msgid "IP Address" +msgstr "Dirección IP" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "If sponsorship status was not updated, please contact a moderator on the community forum at https://community.sunnypilot.ai" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Install Update" +msgstr "Instalar actualización" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Join our Community Forum at https://community.sunnypilot.ai and reach out to a moderator if you have issues" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Joystick Debug Mode" +msgstr "Modo de depuración de joystick" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "LOADING" +msgstr "CARGANDO" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "LTE" +msgstr "LTE" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Lateral Maneuver Mode" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Longitudinal Maneuver Mode" +msgstr "Modo de maniobra longitudinal" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "MAX" +msgstr "MÁX" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Maximize your training data uploads to improve openpilot's driving models." +msgstr "Maximiza tus cargas de datos de entrenamiento para mejorar los modelos de conducción de openpilot." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "N/A" +msgstr "N / A" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "NO" +msgstr "SIN" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Network" +msgstr "Red" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "No SSH keys found for user '{}'" +msgstr "No se encontraron claves SSH para el usuario '{}'" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "No release notes available." +msgstr "No hay notas de versión disponibles." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "OFFLINE" +msgstr "SIN CONEXIÓN" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/html_render.py +msgid "OK" +msgstr "OK" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ONLINE" +msgstr "EN LÍNEA" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Open" +msgstr "Abrir" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PAIR" +msgstr "EMPAREJAR" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "PANDA" +msgstr "PANDA" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PREVIEW" +msgstr "VISTA PREVIA" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "PRIME FEATURES:" +msgstr "FUNCIONES PRIME:" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Pair Device" +msgstr "Emparejar dispositivo" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair device" +msgstr "Emparejar dispositivo" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Pair your GitHub account" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Pair your device to your comma account" +msgstr "Empareja tu dispositivo con tu cuenta de comma" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer." +msgstr "Empareja tu dispositivo con comma connect (connect.comma.ai) y reclama tu oferta de comma prime." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Please connect to Wi-Fi to complete initial pairing" +msgstr "Conéctate a Wi‑Fi para completar el emparejamiento inicial" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Power Off" +msgstr "Apagar" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered Wi-Fi connection" +msgstr "Evite grandes cargas de datos cuando esté en una conexión Wi-Fi medida" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered cellular connection" +msgstr "Evite grandes cargas de datos cuando esté en una conexión celular medida" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off)" +msgstr "Previsualiza la cámara hacia el conductor para asegurarte de que la supervisión del conductor tenga buena visibilidad. (el vehículo debe estar apagado)" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "QR Code Error" +msgstr "Error de código QR" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "REMOVE" +msgstr "ELIMINAR" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "RESET" +msgstr "RESTABLECER" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "REVIEW" +msgstr "REVISAR" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Re-enter the \"sunnylink\" panel to verify sponsorship status" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reboot" +msgstr "Reiniciar" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Reboot Device" +msgstr "Reiniciar dispositivo" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Reboot and Update" +msgstr "Reiniciar y actualizar" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Driver Camera" +msgstr "Grabar y subir cámara del conductor" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Microphone Audio" +msgstr "Grabar y subir audio del micrófono" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and store microphone audio while driving. The audio will be included in the dashcam video in comma connect." +msgstr "Grabar y almacenar audio del micrófono mientras conduces. El audio se incluirá en el video de la dashcam en comma connect." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Regulatory" +msgstr "Reglamentario" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Relaxed" +msgstr "Relajado" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote access" +msgstr "Acceso remoto" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote snapshots" +msgstr "Capturas remotas" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Request timed out" +msgstr "Se agotó el tiempo de espera de la solicitud" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset" +msgstr "Restablecer" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset Calibration" +msgstr "Restablecer calibración" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review Training Guide" +msgstr "Revisar guía de entrenamiento" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review the rules, features, and limitations of sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "SELECT" +msgstr "SELECCIONAR" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "SSH Keys" +msgstr "Claves SSH" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Scan the QR code to login to your GitHub account" +msgstr "" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Scan the QR code to visit sunnyhaibin's GitHub Sponsors page" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Scanning Wi-Fi networks..." +msgstr "Escaneando redes Wi-Fi..." + +#: system/ui/sunnypilot/widgets/tree_dialog.py +msgid "Search" +msgstr "" + +#: system/ui/widgets/option_dialog.py +msgid "Select" +msgstr "Seleccionar" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Select a branch" +msgstr "Selecciona una rama" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Select a language" +msgstr "Selecciona un idioma" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Serial" +msgstr "Número de serie" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Snooze Update" +msgstr "Posponer actualización" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Software" +msgstr "Sistema" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Standard" +msgstr "Estándar" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "System Unresponsive" +msgstr "Sistema sin respuesta" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "TAKE CONTROL IMMEDIATELY" +msgstr "TOME EL CONTROL INMEDIATAMENTE" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "TEMP" +msgstr "TEMP." + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Target Branch" +msgstr "Rama objetivo" + +#: system/ui/widgets/network.py +msgid "Tethering Password" +msgstr "Contraseña de anclaje" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Toggles" +msgstr "Interruptores" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "UI Debug Mode" +msgstr "Modo de depuración de la interfaz de usuario" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "UNINSTALL" +msgstr "DESINSTALAR" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "UPDATE" +msgstr "ACTUALIZAR" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Uninstall" +msgstr "Desinstalar" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Unknown" +msgstr "Desconocido" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Updates are only downloaded while the car is off." +msgstr "Las actualizaciones solo se descargan cuando el coche está apagado." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Upgrade Now" +msgstr "Mejorar ahora" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Upload data from the driver facing camera and help improve the driver monitoring algorithm." +msgstr "Sube datos de la cámara orientada al conductor y ayuda a mejorar el algoritmo de supervisión del conductor." + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Use Metric System" +msgstr "Usar sistema métrico" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "VEHICLE" +msgstr "VEHÍCULO" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "VIEW" +msgstr "VER" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Waiting to start" +msgstr "Esperando para iniciar" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Welcome to sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "When enabled, pressing the accelerator pedal will disengage sunnypilot." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Wi-Fi" +msgstr "Wi‑Fi" + +#: system/ui/widgets/network.py +msgid "Wi-Fi Network Metered" +msgstr "Red Wi-Fi medida" + +#: system/ui/widgets/network.py +msgid "Wrong password" +msgstr "Contraseña incorrecta" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms of Service in order to use sunnypilot." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms of Service to use sunnypilot. Read the latest terms at https://sunnypilot.ai/terms before continuing." +msgstr "" + +#: openpilot/selfdrive/ui/onroad/driver_camera_dialog.py +msgid "camera starting" +msgstr "iniciando cámara" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "checking..." +msgstr "de cheques..." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "comma prime" +msgstr "comma prime" + +#: system/ui/widgets/network.py +msgid "default" +msgstr "por defecto" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "down" +msgstr "abajo" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "downloading..." +msgstr "descargando..." + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "failed to check for update" +msgstr "Error al buscar actualizaciones" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "finalizing update..." +msgstr "finalizando actualización..." + +#: system/ui/widgets/network.py +msgid "for \"{}\"" +msgstr "para \"{}\"" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "km/h" +msgstr "km/h" + +#: system/ui/widgets/network.py +msgid "leave blank for automatic configuration" +msgstr "dejar en blanco para configuración automática" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "left" +msgstr "izquierda" + +#: system/ui/widgets/network.py +msgid "metered" +msgstr "medido" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "mph" +msgstr "mph" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "never" +msgstr "nunca" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "now" +msgstr "ahora" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "right" +msgstr "derecha" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "sunnypilot Longitudinal Control (Alpha)" +msgstr "" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "sunnypilot Unavailable" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "sunnypilot longitudinal control may come in a future update." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "sunnypilot requires the device to be mounted within 4° left or right and within 5° up or 9° down." +msgstr "" + +#: system/ui/widgets/network.py +msgid "unmetered" +msgstr "sin medir" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "up" +msgstr "arriba" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked never" +msgstr "actualizado, última comprobación: nunca" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked {}" +msgstr "actualizado, última comprobación: {}" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "update available" +msgstr "actualización disponible" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "{} ALERT" +msgid_plural "{} ALERTS" +msgstr[0] "{} ALERTA" +msgstr[1] "{} ALERTAS" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} day ago" +msgid_plural "{} days ago" +msgstr[0] "hace {} día" +msgstr[1] "hace {} días" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} hour ago" +msgid_plural "{} hours ago" +msgstr[0] "hace {} hora" +msgstr[1] "hace {} horas" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} minute ago" +msgid_plural "{} minutes ago" +msgstr[0] "hace {} minuto" +msgstr[1] "hace {} minutos" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "{} segment of your driving is in the training dataset so far." +msgid_plural "{} segments of your driving is in the training dataset so far." +msgstr[0] "{} segmento de tu conducción está en el conjunto de entrenamiento hasta ahora." +msgstr[1] "{} segmentos de tu conducción están en el conjunto de entrenamiento hasta ahora." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "✓ SUBSCRIBED" +msgstr "✓ SUSCRITO" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "🔥 Firehose Mode 🔥" +msgstr "🔥 Modo Firehose 🔥" + diff --git a/openpilot/selfdrive/ui/translations/app_fr.po b/openpilot/selfdrive/ui/translations/app_fr.po new file mode 100644 index 0000000000..ac5b4deea5 --- /dev/null +++ b/openpilot/selfdrive/ui/translations/app_fr.po @@ -0,0 +1,873 @@ +msgid "" +msgstr "" +"Content-Type: text/plain; charset=UTF-8\n" +"Language: fr\n" +"Plural-Forms: nplurals=2; plural=(n > 1);\n" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is complete." +msgstr " Calibration de la réponse du couple de direction terminée." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is {}% complete." +msgstr " Calibration du couple de direction : {}% effectué." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Your device is pointed {:.1f}° {} and {:.1f}° {}." +msgstr " Votre appareil est orienté {:.1f}° {} et {:.1f}° {}." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "--" +msgstr "--" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "1 year of drive storage" +msgstr "1 an de stockage de trajets" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "24/7 LTE connectivity" +msgstr "Connexion LTE 24/7" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "2G" +msgstr "2G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "3G" +msgstr "3G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "5G" +msgstr "5G" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is complete." +msgstr "

La calibration du délai de direction est terminée." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is {}% complete." +msgstr "

Calibration du délai de direction : {}% effectué." + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "ADD" +msgstr "AJOUTER" + +#: system/ui/widgets/network.py +msgid "APN Setting" +msgstr "Paramètre APN" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Acknowledge Excessive Actuation" +msgstr "Accuser réception d'actionnement excessif" + +#: system/ui/widgets/network.py +msgid "Advanced" +msgstr "Avancé" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Aggressive" +msgstr "Agressif" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Agree" +msgstr "Accepter" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Always-On Driver Monitoring" +msgstr "Surveillance continue du conducteur" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to power off?" +msgstr "Êtes-vous sûr de vouloir éteindre ?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reboot?" +msgstr "Êtes-vous sûr de vouloir redémarrer ?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reset calibration?" +msgstr "Êtes-vous sûr de vouloir réinitialiser la calibration ?" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Are you sure you want to uninstall?" +msgstr "Êtes-vous sûr de vouloir désinstaller ?" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +#: system/ui/widgets/network.py +msgid "Back" +msgstr "Retour" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Become a comma prime member at connect.comma.ai" +msgstr "Devenez membre comma prime sur connect.comma.ai" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Bookmark connect.comma.ai to your home screen to use it like an app" +msgstr "Ajoutez connect.comma.ai à votre écran d'accueil pour l'utiliser comme une application" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "CHANGE" +msgstr "CHANGER" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "CHECK" +msgstr "VÉRIFIER" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "CHILL MODE ON" +msgstr "MODE CHILL ACTIVÉ" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/network.py +msgid "CONNECT" +msgstr "CONNECTER" + +#: system/ui/widgets/network.py +msgid "CONNECTING..." +msgstr "CONNEXION..." + +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/keyboard.py +#: system/ui/widgets/network.py +#: system/ui/widgets/option_dialog.py +msgid "Cancel" +msgstr "Annuler" + +#: system/ui/widgets/network.py +msgid "Cellular Metered" +msgstr "Données cellulaires limitées" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Change Language" +msgstr "Changer la langue" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Changing this setting will restart sunnypilot if the car is powered on." +msgstr "La modification de ce réglage redémarrera sunnypilot si la voiture est sous tension." + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Choose your sponsorship tier and confirm your support" +msgstr "Choisissez votre niveau de parrainage et confirmez votre soutien" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Click \"add new device\" and scan the QR code on the right" +msgstr "Cliquez sur \"add new device\" et scannez le code QR à droite" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Close" +msgstr "Fermer" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Current Version" +msgstr "Version actuelle" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "DOWNLOAD" +msgstr "TÉLÉCHARGER" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline" +msgstr "Refuser" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline, uninstall sunnypilot" +msgstr "Refuser, désinstaller sunnypilot" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Developer" +msgstr "Développeur" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Device" +msgstr "Appareil" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Disengage on Accelerator Pedal" +msgstr "Désengager à l'appui sur l'accélérateur" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Power Off" +msgstr "Désengager pour éteindre" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reboot" +msgstr "Désengager pour redémarrer" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reset Calibration" +msgstr "Désengager pour réinitialiser la calibration" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Display speed in km/h instead of mph." +msgstr "Afficher la vitesse en km/h au lieu de mph." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Dongle ID" +msgstr "ID du dongle" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Download" +msgstr "Télécharger" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Driver Camera" +msgstr "Caméra conducteur" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Driving Personality" +msgstr "Personnalité de conduite" + +#: system/ui/widgets/network.py +msgid "EDIT" +msgstr "MODIFIER" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ERROR" +msgstr "ERREUR" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ETH" +msgstr "ETH" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "EXPERIMENTAL MODE ON" +msgstr "MODE EXPÉRIMENTAL ACTIVÉ" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Early Access: Become a sunnypilot Sponsor" +msgstr "Accès anticipé : Devenez parrain sunnypilot" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable" +msgstr "Activer" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable ADB" +msgstr "Activer ADB" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable Lane Departure Warnings" +msgstr "Activer les alertes de sortie de voie" + +#: system/ui/widgets/network.py +msgid "Enable Roaming" +msgstr "Activer l'itinérance" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable SSH" +msgstr "Activer SSH" + +#: system/ui/widgets/network.py +msgid "Enable Tethering" +msgstr "Activer le partage de connexion" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable driver monitoring even when sunnypilot is not engaged." +msgstr "Activer la surveillance du conducteur même lorsque sunnypilot n'est pas engagé." + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable sunnypilot" +msgstr "Activer sunnypilot" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable the sunnypilot longitudinal control (alpha) toggle to allow Experimental mode." +msgstr "Activez l'option de contrôle longitudinal sunnypilot (alpha) pour autoriser le mode expérimental." + +#: system/ui/widgets/network.py +msgid "Enter APN" +msgstr "Entrez l'APN" + +#: system/ui/widgets/network.py +msgid "Enter SSID" +msgstr "Entrez le SSID" + +#: system/ui/widgets/network.py +msgid "Enter new tethering password" +msgstr "Entrez un nouveau mot de passe de partage" + +#: system/ui/widgets/network.py +msgid "Enter password" +msgstr "Entrez le mot de passe" + +#: system/ui/sunnypilot/widgets/tree_dialog.py +msgid "Enter search query" +msgstr "Entrez votre recherche" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Enter your GitHub username" +msgstr "Entrez votre nom d'utilisateur GitHub" + +#: system/ui/widgets/list_view.py +msgid "Error" +msgstr "Erreur" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental Mode" +msgstr "Mode expérimental" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control." +msgstr "Le mode expérimental est actuellement indisponible sur cette voiture car l'ACC d'origine est utilisé pour le contrôle longitudinal." + +#: system/ui/widgets/network.py +msgid "FORGETTING..." +msgstr "SUPPRESSION..." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Finish Setup" +msgstr "Finir la config." + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Firehose" +msgstr "Firehose" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "Firehose Mode" +msgstr "Mode Firehose" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Follow the prompts to complete the pairing process" +msgstr "Suivez les instructions pour terminer le processus d'association" + +#: system/ui/widgets/network.py +msgid "Forget" +msgstr "Oublier" + +#: system/ui/widgets/network.py +msgid "Forget Wi-Fi Network \"{}\"?" +msgstr "Oublier le réseau Wi‑Fi \"{}\" ?" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "GOOD" +msgstr "BONNE" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Go to https://connect.comma.ai on your phone" +msgstr "Allez sur https://connect.comma.ai sur votre téléphone" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "HIGH" +msgstr "ÉLEVÉ" + +#: system/ui/widgets/network.py +msgid "Hidden Network" +msgstr "Réseau masqué" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "INSTALL" +msgstr "INSTALLER" + +#: system/ui/widgets/network.py +msgid "IP Address" +msgstr "Adresse IP" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "If sponsorship status was not updated, please contact a moderator on the community forum at https://community.sunnypilot.ai" +msgstr "Si le statut de parrainage n'a pas été mis à jour, veuillez contacter un modérateur sur le forum communautaire à https://community.sunnypilot.ai" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Install Update" +msgstr "Installer la mise à jour" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Join our Community Forum at https://community.sunnypilot.ai and reach out to a moderator if you have issues" +msgstr "Rejoignez notre forum communautaire à https://community.sunnypilot.ai et contactez un modérateur si vous avez des problèmes" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Joystick Debug Mode" +msgstr "Mode débogage joystick" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "LOADING" +msgstr "CHARGEMENT" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "LTE" +msgstr "LTE" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Lateral Maneuver Mode" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Longitudinal Maneuver Mode" +msgstr "Mode de manœuvre longitudinale" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "MAX" +msgstr "MAX" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Maximize your training data uploads to improve openpilot's driving models." +msgstr "Maximisez vos envois de données d'entraînement pour améliorer les modèles de conduite d'openpilot." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "N/A" +msgstr "N/A" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "NO" +msgstr "NON" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Network" +msgstr "Réseau" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "No SSH keys found for user '{}'" +msgstr "Aucune clé SSH trouvée pour l'utilisateur '{}'" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "No release notes available." +msgstr "Aucune note de version disponible." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "OFFLINE" +msgstr "HORS LIGNE" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/html_render.py +msgid "OK" +msgstr "OK" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ONLINE" +msgstr "EN LIGNE" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Open" +msgstr "Ouvrir" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PAIR" +msgstr "ASSOCIER" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "PANDA" +msgstr "PANDA" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PREVIEW" +msgstr "APERÇU" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "PRIME FEATURES:" +msgstr "FONCTIONNALITÉS PRIME :" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Pair Device" +msgstr "Associer l'appareil" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair device" +msgstr "Associer l'appareil" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Pair your GitHub account" +msgstr "Associer votre compte GitHub" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Pair your device to your comma account" +msgstr "Associez votre appareil à votre compte comma" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer." +msgstr "Associez votre appareil à comma connect (connect.comma.ai) et réclamez votre offre comma prime." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Please connect to Wi-Fi to complete initial pairing" +msgstr "Veuillez vous connecter au Wi‑Fi pour terminer l'association initiale" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Power Off" +msgstr "Éteindre" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered Wi-Fi connection" +msgstr "Empêcher les téléversements volumineux sur une connexion Wi‑Fi limitée" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered cellular connection" +msgstr "Empêcher les téléversements volumineux sur une connexion cellulaire limitée" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off)" +msgstr "Prévisualisez la caméra orientée conducteur pour vous assurer que la surveillance du conducteur a une bonne visibilité. (le véhicule doit être éteint)" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "QR Code Error" +msgstr "Erreur de code QR" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "REMOVE" +msgstr "SUPPRIMER" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "RESET" +msgstr "RÉINITIALISER" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "REVIEW" +msgstr "CONSULTER" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Re-enter the \"sunnylink\" panel to verify sponsorship status" +msgstr "Retournez dans le panneau \"sunnylink\" pour vérifier le statut de parrainage" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reboot" +msgstr "Redémarrer" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Reboot Device" +msgstr "Redémarrer l'appareil" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Reboot and Update" +msgstr "Redémarrer et mettre à jour" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Driver Camera" +msgstr "Enregistrer et téléverser la caméra conducteur" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Microphone Audio" +msgstr "Enregistrer et téléverser l'audio du microphone" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and store microphone audio while driving. The audio will be included in the dashcam video in comma connect." +msgstr "Enregistrer et stocker l'audio du microphone pendant la conduite. L'audio sera inclus dans la vidéo dashcam dans comma connect." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Regulatory" +msgstr "Réglementaire" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Relaxed" +msgstr "Détendu" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote access" +msgstr "Accès à distance" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote snapshots" +msgstr "Captures à distance" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Request timed out" +msgstr "Délai de la requête dépassé" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset" +msgstr "Réinitialiser" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset Calibration" +msgstr "Réinitialiser la calibration" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review Training Guide" +msgstr "Consulter le guide d'entraînement" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review the rules, features, and limitations of sunnypilot" +msgstr "Consultez les règles, fonctionnalités et limitations de sunnypilot" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "SELECT" +msgstr "CHOISIR" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "SSH Keys" +msgstr "Clés SSH" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Scan the QR code to login to your GitHub account" +msgstr "Scannez le code QR pour vous connecter à votre compte GitHub" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Scan the QR code to visit sunnyhaibin's GitHub Sponsors page" +msgstr "Scannez le code QR pour visiter la page GitHub Sponsors de sunnyhaibin" + +#: system/ui/widgets/network.py +msgid "Scanning Wi-Fi networks..." +msgstr "Recherche des réseaux Wi‑Fi..." + +#: system/ui/sunnypilot/widgets/tree_dialog.py +msgid "Search" +msgstr "Rechercher" + +#: system/ui/widgets/option_dialog.py +msgid "Select" +msgstr "Sélectionner" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Select a branch" +msgstr "Sélectionner une branche" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Select a language" +msgstr "Sélectionner une langue" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Serial" +msgstr "Numéro de série" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Snooze Update" +msgstr "Reporter la mise à jour" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Software" +msgstr "Logiciel" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Standard" +msgstr "Standard" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "System Unresponsive" +msgstr "Système non réactif" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "TAKE CONTROL IMMEDIATELY" +msgstr "REPRENEZ IMMÉDIATEMENT LE CONTRÔLE" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "TEMP" +msgstr "TEMP." + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Target Branch" +msgstr "Branche cible" + +#: system/ui/widgets/network.py +msgid "Tethering Password" +msgstr "Mot de passe de partage" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Toggles" +msgstr "Options" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "UI Debug Mode" +msgstr "Mode débogage UI" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "UNINSTALL" +msgstr "SUPPRIMER" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "UPDATE" +msgstr "METTRE À JOUR" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Uninstall" +msgstr "Désinstaller" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Unknown" +msgstr "Inconnu" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Updates are only downloaded while the car is off." +msgstr "Les mises à jour ne sont téléchargées que lorsque la voiture est éteinte." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Upgrade Now" +msgstr "Mettre à jour" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Upload data from the driver facing camera and help improve the driver monitoring algorithm." +msgstr "Téléverser les données de la caméra orientée conducteur et aider à améliorer l'algorithme de surveillance du conducteur." + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Use Metric System" +msgstr "Utiliser le système métrique" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "VEHICLE" +msgstr "VÉHICULE" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "VIEW" +msgstr "VOIR" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Waiting to start" +msgstr "En attente de démarrage" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Welcome to sunnypilot" +msgstr "Bienvenue sur sunnypilot" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "When enabled, pressing the accelerator pedal will disengage sunnypilot." +msgstr "Lorsqu'activé, appuyer sur la pédale d'accélérateur désengagera sunnypilot." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Wi-Fi" +msgstr "Wi‑Fi" + +#: system/ui/widgets/network.py +msgid "Wi-Fi Network Metered" +msgstr "Réseau Wi‑Fi limité" + +#: system/ui/widgets/network.py +msgid "Wrong password" +msgstr "Mot de passe incorrect" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms of Service in order to use sunnypilot." +msgstr "Vous devez accepter les conditions d'utilisation pour utiliser sunnypilot." + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms of Service to use sunnypilot. Read the latest terms at https://sunnypilot.ai/terms before continuing." +msgstr "Vous devez accepter les conditions d'utilisation pour utiliser sunnypilot. Consultez les dernières conditions sur https://sunnypilot.ai/terms avant de continuer." + +#: openpilot/selfdrive/ui/onroad/driver_camera_dialog.py +msgid "camera starting" +msgstr "démarrage de la caméra" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "checking..." +msgstr "vérification..." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "comma prime" +msgstr "comma prime" + +#: system/ui/widgets/network.py +msgid "default" +msgstr "par défaut" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "down" +msgstr "bas" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "downloading..." +msgstr "téléchargement..." + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "failed to check for update" +msgstr "échec de la vérification de mise à jour" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "finalizing update..." +msgstr "finalisation de la mise à jour..." + +#: system/ui/widgets/network.py +msgid "for \"{}\"" +msgstr "pour \"{}\"" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "km/h" +msgstr "km/h" + +#: system/ui/widgets/network.py +msgid "leave blank for automatic configuration" +msgstr "laisser vide pour configuration automatique" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "left" +msgstr "gauche" + +#: system/ui/widgets/network.py +msgid "metered" +msgstr "limité" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "mph" +msgstr "mph" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "never" +msgstr "jamais" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "now" +msgstr "maintenant" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "right" +msgstr "droite" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "sunnypilot Longitudinal Control (Alpha)" +msgstr "Contrôle longitudinal sunnypilot (Alpha)" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "sunnypilot Unavailable" +msgstr "sunnypilot indisponible" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "sunnypilot longitudinal control may come in a future update." +msgstr "Le contrôle longitudinal sunnypilot pourrait arriver dans une future mise à jour." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "sunnypilot requires the device to be mounted within 4° left or right and within 5° up or 9° down." +msgstr "" + +#: system/ui/widgets/network.py +msgid "unmetered" +msgstr "illimité" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "up" +msgstr "haut" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked never" +msgstr "à jour, dernière vérification jamais" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked {}" +msgstr "à jour, dernière vérification {}" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "update available" +msgstr "mise à jour disponible" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "{} ALERT" +msgid_plural "{} ALERTS" +msgstr[0] "{} ALERTE" +msgstr[1] "{} ALERTES" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} day ago" +msgid_plural "{} days ago" +msgstr[0] "il y a {} jour" +msgstr[1] "il y a {} jours" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} hour ago" +msgid_plural "{} hours ago" +msgstr[0] "il y a {} heure" +msgstr[1] "il y a {} heures" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} minute ago" +msgid_plural "{} minutes ago" +msgstr[0] "il y a {} minute" +msgstr[1] "il y a {} minutes" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "{} segment of your driving is in the training dataset so far." +msgid_plural "{} segments of your driving is in the training dataset so far." +msgstr[0] "{} segment de votre conduite est dans l'ensemble d'entraînement jusqu'à présent." +msgstr[1] "{} segments de votre conduite sont dans l'ensemble d'entraînement jusqu'à présent." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "✓ SUBSCRIBED" +msgstr "✓ ABONNÉ" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "🔥 Firehose Mode 🔥" +msgstr "🔥 Mode Firehose 🔥" + diff --git a/openpilot/selfdrive/ui/translations/app_ja.po b/openpilot/selfdrive/ui/translations/app_ja.po new file mode 100644 index 0000000000..1d701bd8b4 --- /dev/null +++ b/openpilot/selfdrive/ui/translations/app_ja.po @@ -0,0 +1,868 @@ +msgid "" +msgstr "" +"Content-Type: text/plain; charset=UTF-8\n" +"Language: ja\n" +"Plural-Forms: nplurals=1; plural=0;\n" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is complete." +msgstr " ステアリングトルク応答のキャリブレーションが完了しました。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is {}% complete." +msgstr " ステアリングトルク応答のキャリブレーションは{}%完了しました。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Your device is pointed {:.1f}° {} and {:.1f}° {}." +msgstr " デバイスは{:.1f}°{}、{:.1f}°{}の向きです。" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "--" +msgstr "--" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "1 year of drive storage" +msgstr "走行データを1年間保存" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "24/7 LTE connectivity" +msgstr "24時間365日のLTE接続" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "2G" +msgstr "2G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "3G" +msgstr "3G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "5G" +msgstr "5G" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is complete." +msgstr "

ステアリング遅延のキャリブレーションが完了しました。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is {}% complete." +msgstr "

ステアリング遅延のキャリブレーションは{}%完了しました。" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "ADD" +msgstr "追加" + +#: system/ui/widgets/network.py +msgid "APN Setting" +msgstr "APN設定" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Acknowledge Excessive Actuation" +msgstr "過度な作動を承認" + +#: system/ui/widgets/network.py +msgid "Advanced" +msgstr "詳細設定" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Aggressive" +msgstr "アグレッシブ" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Agree" +msgstr "同意する" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Always-On Driver Monitoring" +msgstr "常時ドライバーモニタリング" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to power off?" +msgstr "本当に電源をオフにしますか?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reboot?" +msgstr "本当に再起動しますか?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reset calibration?" +msgstr "本当にキャリブレーションをリセットしますか?" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Are you sure you want to uninstall?" +msgstr "本当にアンインストールしますか?" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +#: system/ui/widgets/network.py +msgid "Back" +msgstr "戻る" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Become a comma prime member at connect.comma.ai" +msgstr "connect.comma.aiで comma prime に加入" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Bookmark connect.comma.ai to your home screen to use it like an app" +msgstr "connect.comma.aiをホーム画面に追加してアプリのように使いましょう" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "CHANGE" +msgstr "変更" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "CHECK" +msgstr "確認" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "CHILL MODE ON" +msgstr "チルモードON" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/network.py +msgid "CONNECT" +msgstr "接続" + +#: system/ui/widgets/network.py +msgid "CONNECTING..." +msgstr "接続中..." + +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/keyboard.py +#: system/ui/widgets/network.py +#: system/ui/widgets/option_dialog.py +msgid "Cancel" +msgstr "キャンセル" + +#: system/ui/widgets/network.py +msgid "Cellular Metered" +msgstr "従量課金の携帯回線" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Change Language" +msgstr "言語を変更" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Changing this setting will restart sunnypilot if the car is powered on." +msgstr "" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Choose your sponsorship tier and confirm your support" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Click \"add new device\" and scan the QR code on the right" +msgstr "\"add new device\"を押して右側のQRコードをスキャン" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Close" +msgstr "閉じる" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Current Version" +msgstr "現在のバージョン" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "DOWNLOAD" +msgstr "ダウンロード" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline" +msgstr "拒否する" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline, uninstall sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Developer" +msgstr "開発者" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Device" +msgstr "デバイス" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Disengage on Accelerator Pedal" +msgstr "アクセルで解除" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Power Off" +msgstr "解除して電源オフ" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reboot" +msgstr "解除して再起動" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reset Calibration" +msgstr "解除してキャリブレーションをリセット" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Display speed in km/h instead of mph." +msgstr "速度をmphではなくkm/hで表示します。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Dongle ID" +msgstr "ドングルID" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Download" +msgstr "ダウンロード" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Driver Camera" +msgstr "ドライバーカメラ" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Driving Personality" +msgstr "走行性格" + +#: system/ui/widgets/network.py +msgid "EDIT" +msgstr "編集" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ERROR" +msgstr "エラー" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ETH" +msgstr "ETH" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "EXPERIMENTAL MODE ON" +msgstr "実験モードON" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Early Access: Become a sunnypilot Sponsor" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable" +msgstr "有効化" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable ADB" +msgstr "ADBを有効化" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable Lane Departure Warnings" +msgstr "車線逸脱警報を有効化" + +#: system/ui/widgets/network.py +msgid "Enable Roaming" +msgstr "ローミングを有効化" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable SSH" +msgstr "SSHを有効化" + +#: system/ui/widgets/network.py +msgid "Enable Tethering" +msgstr "テザリングを有効化" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable driver monitoring even when sunnypilot is not engaged." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable the sunnypilot longitudinal control (alpha) toggle to allow Experimental mode." +msgstr "" + +#: system/ui/widgets/network.py +msgid "Enter APN" +msgstr "APNを入力" + +#: system/ui/widgets/network.py +msgid "Enter SSID" +msgstr "SSIDを入力" + +#: system/ui/widgets/network.py +msgid "Enter new tethering password" +msgstr "新しいテザリングのパスワードを入力" + +#: system/ui/widgets/network.py +msgid "Enter password" +msgstr "パスワードを入力" + +#: system/ui/sunnypilot/widgets/tree_dialog.py +msgid "Enter search query" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Enter your GitHub username" +msgstr "GitHubユーザー名を入力" + +#: system/ui/widgets/list_view.py +msgid "Error" +msgstr "エラー" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental Mode" +msgstr "実験モード" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control." +msgstr "この車では縦制御に純正ACCを使用するため、現在実験モードは利用できません。" + +#: system/ui/widgets/network.py +msgid "FORGETTING..." +msgstr "削除中..." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Finish Setup" +msgstr "セットアップを完了" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Firehose" +msgstr "大量配信" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "Firehose Mode" +msgstr "Firehoseモード" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Follow the prompts to complete the pairing process" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Forget" +msgstr "削除" + +#: system/ui/widgets/network.py +msgid "Forget Wi-Fi Network \"{}\"?" +msgstr "Wi‑Fiネットワーク「{}」を削除しますか?" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "GOOD" +msgstr "良好" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Go to https://connect.comma.ai on your phone" +msgstr "スマートフォンで https://connect.comma.ai にアクセス" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "HIGH" +msgstr "高温" + +#: system/ui/widgets/network.py +msgid "Hidden Network" +msgstr "非公開ネットワーク" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "INSTALL" +msgstr "インストール" + +#: system/ui/widgets/network.py +msgid "IP Address" +msgstr "IPアドレス" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "If sponsorship status was not updated, please contact a moderator on the community forum at https://community.sunnypilot.ai" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Install Update" +msgstr "アップデートをインストール" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Join our Community Forum at https://community.sunnypilot.ai and reach out to a moderator if you have issues" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Joystick Debug Mode" +msgstr "ジョイスティックデバッグモード" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "LOADING" +msgstr "読み込み中" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "LTE" +msgstr "LTE" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Lateral Maneuver Mode" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Longitudinal Maneuver Mode" +msgstr "縦制御マヌーバーモード" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "MAX" +msgstr "最大" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Maximize your training data uploads to improve openpilot's driving models." +msgstr "学習データのアップロードを最大化してopenpilotの運転モデルを改善しましょう。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "N/A" +msgstr "該当なし" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "NO" +msgstr "いいえ" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Network" +msgstr "ネットワーク" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "No SSH keys found for user '{}'" +msgstr "ユーザー'{}'のSSH鍵が見つかりません" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "No release notes available." +msgstr "リリースノートはありません。" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "OFFLINE" +msgstr "オフライン" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/html_render.py +msgid "OK" +msgstr "OK" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ONLINE" +msgstr "オンライン" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Open" +msgstr "開く" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PAIR" +msgstr "ペアリング" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "PANDA" +msgstr "PANDA" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PREVIEW" +msgstr "プレビュー" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "PRIME FEATURES:" +msgstr "prime の特典:" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Pair Device" +msgstr "デバイスをペアリング" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair device" +msgstr "デバイスをペアリング" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Pair your GitHub account" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Pair your device to your comma account" +msgstr "デバイスをあなたの comma アカウントにペアリング" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer." +msgstr "デバイスを comma connect(connect.comma.ai)とペアリングして、comma prime 特典を受け取りましょう。" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Please connect to Wi-Fi to complete initial pairing" +msgstr "初回ペアリングを完了するにはWi‑Fiに接続してください" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Power Off" +msgstr "電源オフ" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered Wi-Fi connection" +msgstr "従量課金のWi‑Fi接続時は大きなデータのアップロードを抑制" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered cellular connection" +msgstr "従量課金の携帯回線接続時は大きなデータのアップロードを抑制" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off)" +msgstr "ドライバー向きカメラのプレビューでモニタリングの視界を確認します。(車両は停止状態である必要があります)" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "QR Code Error" +msgstr "QRコードエラー" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "REMOVE" +msgstr "削除" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "RESET" +msgstr "リセット" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "REVIEW" +msgstr "確認" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Re-enter the \"sunnylink\" panel to verify sponsorship status" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reboot" +msgstr "再起動" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Reboot Device" +msgstr "デバイスを再起動" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Reboot and Update" +msgstr "再起動して更新" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Driver Camera" +msgstr "ドライバーカメラを記録してアップロード" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Microphone Audio" +msgstr "マイク音声を記録してアップロード" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and store microphone audio while driving. The audio will be included in the dashcam video in comma connect." +msgstr "走行中にマイク音声を記録・保存します。音声は comma connect のドライブレコーダー動画に含まれます。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Regulatory" +msgstr "規制情報" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Relaxed" +msgstr "リラックス" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote access" +msgstr "リモートアクセス" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote snapshots" +msgstr "リモートスナップショット" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Request timed out" +msgstr "リクエストがタイムアウトしました" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset" +msgstr "リセット" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset Calibration" +msgstr "キャリブレーションをリセット" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review Training Guide" +msgstr "トレーニングガイドを確認" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review the rules, features, and limitations of sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "SELECT" +msgstr "選択" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "SSH Keys" +msgstr "SSH鍵" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Scan the QR code to login to your GitHub account" +msgstr "" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Scan the QR code to visit sunnyhaibin's GitHub Sponsors page" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Scanning Wi-Fi networks..." +msgstr "Wi‑Fiネットワークを検索中..." + +#: system/ui/sunnypilot/widgets/tree_dialog.py +msgid "Search" +msgstr "" + +#: system/ui/widgets/option_dialog.py +msgid "Select" +msgstr "選択" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Select a branch" +msgstr "ブランチを選択" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Select a language" +msgstr "言語を選択" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Serial" +msgstr "シリアル" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Snooze Update" +msgstr "更新を後で通知" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Software" +msgstr "ソフトウェア" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Standard" +msgstr "スタンダード" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "System Unresponsive" +msgstr "システムが応答しません" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "TAKE CONTROL IMMEDIATELY" +msgstr "すぐに手動介入してください" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "TEMP" +msgstr "温度" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Target Branch" +msgstr "対象ブランチ" + +#: system/ui/widgets/network.py +msgid "Tethering Password" +msgstr "テザリングのパスワード" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Toggles" +msgstr "トグル" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "UI Debug Mode" +msgstr "UIデバッグモード" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "UNINSTALL" +msgstr "アンインストール" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "UPDATE" +msgstr "更新" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Uninstall" +msgstr "アンインストール" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Unknown" +msgstr "不明" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Updates are only downloaded while the car is off." +msgstr "アップデートは車両の電源が切れている間のみダウンロードされます。" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Upgrade Now" +msgstr "今すぐアップグレード" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Upload data from the driver facing camera and help improve the driver monitoring algorithm." +msgstr "ドライバー向きカメラのデータをアップロードしてモニタリングアルゴリズムの改善に協力してください。" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Use Metric System" +msgstr "メートル法を使用" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "VEHICLE" +msgstr "車両" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "VIEW" +msgstr "表示" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Waiting to start" +msgstr "開始待機中" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Welcome to sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "When enabled, pressing the accelerator pedal will disengage sunnypilot." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Wi-Fi" +msgstr "Wi‑Fi" + +#: system/ui/widgets/network.py +msgid "Wi-Fi Network Metered" +msgstr "Wi‑Fiネットワーク(従量課金)" + +#: system/ui/widgets/network.py +msgid "Wrong password" +msgstr "パスワードが違います" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms of Service in order to use sunnypilot." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms of Service to use sunnypilot. Read the latest terms at https://sunnypilot.ai/terms before continuing." +msgstr "" + +#: openpilot/selfdrive/ui/onroad/driver_camera_dialog.py +msgid "camera starting" +msgstr "カメラを起動中" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "checking..." +msgstr "チェック中..." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "comma prime" +msgstr "comma prime" + +#: system/ui/widgets/network.py +msgid "default" +msgstr "既定" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "down" +msgstr "下" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "downloading..." +msgstr "ダウンロード中..." + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "failed to check for update" +msgstr "アップデートの確認に失敗しました" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "finalizing update..." +msgstr "アップデートを終了しています..." + +#: system/ui/widgets/network.py +msgid "for \"{}\"" +msgstr "「{}」向け" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "km/h" +msgstr "km/h" + +#: system/ui/widgets/network.py +msgid "leave blank for automatic configuration" +msgstr "自動設定の場合は空欄のままにしてください" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "left" +msgstr "左" + +#: system/ui/widgets/network.py +msgid "metered" +msgstr "従量" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "mph" +msgstr "mph" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "never" +msgstr "なし" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "now" +msgstr "今" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "right" +msgstr "右" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "sunnypilot Longitudinal Control (Alpha)" +msgstr "" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "sunnypilot Unavailable" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "sunnypilot longitudinal control may come in a future update." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "sunnypilot requires the device to be mounted within 4° left or right and within 5° up or 9° down." +msgstr "" + +#: system/ui/widgets/network.py +msgid "unmetered" +msgstr "非従量" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "up" +msgstr "上" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked never" +msgstr "最新です。最終確認: なし" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked {}" +msgstr "最新です。最終確認: {}" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "update available" +msgstr "更新があります" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "{} ALERT" +msgid_plural "{} ALERTS" +msgstr[0] "{}件のアラート" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} day ago" +msgid_plural "{} days ago" +msgstr[0] "{}日前" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} hour ago" +msgid_plural "{} hours ago" +msgstr[0] "{}時間前" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} minute ago" +msgid_plural "{} minutes ago" +msgstr[0] "{}分前" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "{} segment of your driving is in the training dataset so far." +msgid_plural "{} segments of your driving is in the training dataset so far." +msgstr[0] "これまでにあなたの走行の{}セグメントが学習データセットに含まれています。" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "✓ SUBSCRIBED" +msgstr "✓ 登録済み" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "🔥 Firehose Mode 🔥" +msgstr "🔥 Firehoseモード 🔥" + diff --git a/openpilot/selfdrive/ui/translations/app_ko.po b/openpilot/selfdrive/ui/translations/app_ko.po new file mode 100644 index 0000000000..d5c5eb34a2 --- /dev/null +++ b/openpilot/selfdrive/ui/translations/app_ko.po @@ -0,0 +1,868 @@ +msgid "" +msgstr "" +"Content-Type: text/plain; charset=UTF-8\n" +"Language: ko\n" +"Plural-Forms: nplurals=1; plural=0;\n" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is complete." +msgstr " 스티어링 토크 응답 보정이 완료되었습니다." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is {}% complete." +msgstr " 스티어링 토크 응답 보정이 {}% 완료되었습니다." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Your device is pointed {:.1f}° {} and {:.1f}° {}." +msgstr " 장치는 {:.1f}° {} 및 {:.1f}° {} 방향을 가리키고 있습니다." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "--" +msgstr "--" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "1 year of drive storage" +msgstr "주행 데이터 1년 보관" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "24/7 LTE connectivity" +msgstr "연중무휴 LTE 연결" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "2G" +msgstr "2G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "3G" +msgstr "3G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "5G" +msgstr "5G" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is complete." +msgstr "

스티어링 지연 보정이 완료되었습니다." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is {}% complete." +msgstr "

스티어링 지연 보정이 {}% 완료되었습니다." + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "ADD" +msgstr "추가" + +#: system/ui/widgets/network.py +msgid "APN Setting" +msgstr "APN 설정" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Acknowledge Excessive Actuation" +msgstr "과도한 작동을 확인" + +#: system/ui/widgets/network.py +msgid "Advanced" +msgstr "고급" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Aggressive" +msgstr "공격적" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Agree" +msgstr "동의" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Always-On Driver Monitoring" +msgstr "운전자 모니터링 항상 켜짐" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to power off?" +msgstr "정말 전원을 끄시겠습니까?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reboot?" +msgstr "정말 재시작하시겠습니까?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reset calibration?" +msgstr "정말 보정을 재설정하시겠습니까?" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Are you sure you want to uninstall?" +msgstr "정말 제거하시겠습니까?" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +#: system/ui/widgets/network.py +msgid "Back" +msgstr "뒤로" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Become a comma prime member at connect.comma.ai" +msgstr "connect.comma.ai에서 comma prime 회원이 되세요" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Bookmark connect.comma.ai to your home screen to use it like an app" +msgstr "connect.comma.ai를 홈 화면에 추가하여 앱처럼 사용하세요" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "CHANGE" +msgstr "변경" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "CHECK" +msgstr "확인" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "CHILL MODE ON" +msgstr "안정적 모드 켜짐" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/network.py +msgid "CONNECT" +msgstr "연결" + +#: system/ui/widgets/network.py +msgid "CONNECTING..." +msgstr "연결 중..." + +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/keyboard.py +#: system/ui/widgets/network.py +#: system/ui/widgets/option_dialog.py +msgid "Cancel" +msgstr "취소" + +#: system/ui/widgets/network.py +msgid "Cellular Metered" +msgstr "종량제 셀룰러" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Change Language" +msgstr "언어 변경" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Changing this setting will restart sunnypilot if the car is powered on." +msgstr "" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Choose your sponsorship tier and confirm your support" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Click \"add new device\" and scan the QR code on the right" +msgstr "\"add new device\"를 눌러 오른쪽의 QR 코드를 스캔하세요" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Close" +msgstr "닫기" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Current Version" +msgstr "현재 버전" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "DOWNLOAD" +msgstr "다운로드" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline" +msgstr "거부" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline, uninstall sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Developer" +msgstr "개발자" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Device" +msgstr "장치" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Disengage on Accelerator Pedal" +msgstr "가속 페달로 해제" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Power Off" +msgstr "해제 후 전원 끄기" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reboot" +msgstr "해제 후 재시작" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reset Calibration" +msgstr "해제 후 캘리브레이션 재설정" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Display speed in km/h instead of mph." +msgstr "속도를 mph 대신 km/h로 표시합니다." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Dongle ID" +msgstr "동글 ID" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Download" +msgstr "다운로드" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Driver Camera" +msgstr "운전자 카메라" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Driving Personality" +msgstr "주행 성향" + +#: system/ui/widgets/network.py +msgid "EDIT" +msgstr "편집" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ERROR" +msgstr "오류" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ETH" +msgstr "ETH" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "EXPERIMENTAL MODE ON" +msgstr "실험 모드 켜짐" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Early Access: Become a sunnypilot Sponsor" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable" +msgstr "사용" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable ADB" +msgstr "ADB 사용" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable Lane Departure Warnings" +msgstr "차선 이탈 경고 사용" + +#: system/ui/widgets/network.py +msgid "Enable Roaming" +msgstr "로밍 사용" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable SSH" +msgstr "SSH 사용" + +#: system/ui/widgets/network.py +msgid "Enable Tethering" +msgstr "테더링 사용" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable driver monitoring even when sunnypilot is not engaged." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable the sunnypilot longitudinal control (alpha) toggle to allow Experimental mode." +msgstr "" + +#: system/ui/widgets/network.py +msgid "Enter APN" +msgstr "APN 입력" + +#: system/ui/widgets/network.py +msgid "Enter SSID" +msgstr "SSID 입력" + +#: system/ui/widgets/network.py +msgid "Enter new tethering password" +msgstr "새 테더링 비밀번호 입력" + +#: system/ui/widgets/network.py +msgid "Enter password" +msgstr "비밀번호 입력" + +#: system/ui/sunnypilot/widgets/tree_dialog.py +msgid "Enter search query" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Enter your GitHub username" +msgstr "GitHub 사용자 이름 입력" + +#: system/ui/widgets/list_view.py +msgid "Error" +msgstr "오류" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental Mode" +msgstr "실험 모드" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control." +msgstr "이 차량은 롱컨 제어에 순정 ACC를 사용하므로 현재 실험 모드를 사용할 수 없습니다." + +#: system/ui/widgets/network.py +msgid "FORGETTING..." +msgstr "삭제 중..." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Finish Setup" +msgstr "설정 완료" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Firehose" +msgstr "파이어호스" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "Firehose Mode" +msgstr "파이어호스 모드" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Follow the prompts to complete the pairing process" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Forget" +msgstr "삭제" + +#: system/ui/widgets/network.py +msgid "Forget Wi-Fi Network \"{}\"?" +msgstr "Wi‑Fi 네트워크 \"{}\"를 삭제하시겠습니까?" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "GOOD" +msgstr "양호" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Go to https://connect.comma.ai on your phone" +msgstr "휴대폰에서 https://connect.comma.ai 에 접속하세요" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "HIGH" +msgstr "높음" + +#: system/ui/widgets/network.py +msgid "Hidden Network" +msgstr "숨겨진 네트워크" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "INSTALL" +msgstr "설치" + +#: system/ui/widgets/network.py +msgid "IP Address" +msgstr "IP 주소" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "If sponsorship status was not updated, please contact a moderator on the community forum at https://community.sunnypilot.ai" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Install Update" +msgstr "업데이트 설치" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Join our Community Forum at https://community.sunnypilot.ai and reach out to a moderator if you have issues" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Joystick Debug Mode" +msgstr "조이스틱 디버그 모드" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "LOADING" +msgstr "로딩 중" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "LTE" +msgstr "LTE" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Lateral Maneuver Mode" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Longitudinal Maneuver Mode" +msgstr "롱컨 기동 모드" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "MAX" +msgstr "최대" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Maximize your training data uploads to improve openpilot's driving models." +msgstr "학습 데이터 업로드를 최대화하여 openpilot의 주행 모델을 개선하세요." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "N/A" +msgstr "해당 없음" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "NO" +msgstr "아니오" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Network" +msgstr "네트워크" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "No SSH keys found for user '{}'" +msgstr "사용자 '{}'의 SSH 키를 찾을 수 없습니다" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "No release notes available." +msgstr "릴리스 노트가 없습니다." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "OFFLINE" +msgstr "오프라인" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/html_render.py +msgid "OK" +msgstr "확인" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ONLINE" +msgstr "온라인" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Open" +msgstr "열기" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PAIR" +msgstr "페어링" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "PANDA" +msgstr "PANDA" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PREVIEW" +msgstr "미리보기" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "PRIME FEATURES:" +msgstr "프라임 기능:" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Pair Device" +msgstr "장치 페어링" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair device" +msgstr "장치 페어링" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Pair your GitHub account" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Pair your device to your comma account" +msgstr "장치를 귀하의 comma 계정에 페어링하세요" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer." +msgstr "장치를 comma connect(connect.comma.ai)와 페어링하고 comma 프라임 혜택을 받으세요." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Please connect to Wi-Fi to complete initial pairing" +msgstr "초기 페어링을 완료하려면 Wi‑Fi에 연결하세요" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Power Off" +msgstr "전원 끄기" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered Wi-Fi connection" +msgstr "종량제 Wi‑Fi 연결 시 대용량 업로드 방지" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered cellular connection" +msgstr "종량제 셀룰러 연결 시 대용량 업로드 방지" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off)" +msgstr "운전자 모니터링의 가시성을 확인하기 위해 운전자 카메라를 미리 봅니다. (차량은 꺼져 있어야 합니다)" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "QR Code Error" +msgstr "QR 코드 오류" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "REMOVE" +msgstr "제거" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "RESET" +msgstr "재설정" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "REVIEW" +msgstr "검토" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Re-enter the \"sunnylink\" panel to verify sponsorship status" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reboot" +msgstr "재시작" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Reboot Device" +msgstr "장치 재시작" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Reboot and Update" +msgstr "재시작 및 업데이트" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Driver Camera" +msgstr "운전자 카메라 기록 및 업로드" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Microphone Audio" +msgstr "마이크 오디오 기록 및 업로드" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and store microphone audio while driving. The audio will be included in the dashcam video in comma connect." +msgstr "주행 중 마이크 오디오를 기록하고 저장합니다. 오디오는 comma connect의 대시캠 영상에 포함됩니다." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Regulatory" +msgstr "규제 정보" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Relaxed" +msgstr "편안한" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote access" +msgstr "원격 액세스" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote snapshots" +msgstr "원격 스냅샷" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Request timed out" +msgstr "요청 시간이 초과되었습니다" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset" +msgstr "재설정" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset Calibration" +msgstr "캘리브레이션 재설정" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review Training Guide" +msgstr "학습 가이드 검토" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review the rules, features, and limitations of sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "SELECT" +msgstr "선택" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "SSH Keys" +msgstr "SSH 키" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Scan the QR code to login to your GitHub account" +msgstr "" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Scan the QR code to visit sunnyhaibin's GitHub Sponsors page" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Scanning Wi-Fi networks..." +msgstr "Wi‑Fi 네트워크 검색 중..." + +#: system/ui/sunnypilot/widgets/tree_dialog.py +msgid "Search" +msgstr "" + +#: system/ui/widgets/option_dialog.py +msgid "Select" +msgstr "선택" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Select a branch" +msgstr "브랜치 선택" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Select a language" +msgstr "언어 선택" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Serial" +msgstr "시리얼" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Snooze Update" +msgstr "업데이트 나중에 알림" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Software" +msgstr "소프트웨어" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Standard" +msgstr "표준" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "System Unresponsive" +msgstr "시스템 응답 없음" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "TAKE CONTROL IMMEDIATELY" +msgstr "즉시 수동 조작하세요" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "TEMP" +msgstr "온도" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Target Branch" +msgstr "대상 브랜치" + +#: system/ui/widgets/network.py +msgid "Tethering Password" +msgstr "테더링 비밀번호" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Toggles" +msgstr "토글" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "UI Debug Mode" +msgstr "UI 디버그 모드" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "UNINSTALL" +msgstr "제거" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "UPDATE" +msgstr "업데이트" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Uninstall" +msgstr "제거" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Unknown" +msgstr "알수없음" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Updates are only downloaded while the car is off." +msgstr "업데이트는 차량 전원이 꺼져 있을 때만 다운로드됩니다." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Upgrade Now" +msgstr "지금 업그레이드" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Upload data from the driver facing camera and help improve the driver monitoring algorithm." +msgstr "운전자 방향 카메라 데이터를 업로드하여 운전자 모니터링 알고리즘 개선에 도움을 주세요." + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Use Metric System" +msgstr "미터법 사용" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "VEHICLE" +msgstr "차량" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "VIEW" +msgstr "보기" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Waiting to start" +msgstr "시작 대기 중" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Welcome to sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "When enabled, pressing the accelerator pedal will disengage sunnypilot." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Wi-Fi" +msgstr "Wi‑Fi" + +#: system/ui/widgets/network.py +msgid "Wi-Fi Network Metered" +msgstr "Wi‑Fi 네트워크 종량제" + +#: system/ui/widgets/network.py +msgid "Wrong password" +msgstr "비밀번호가 올바르지 않습니다" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms of Service in order to use sunnypilot." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms of Service to use sunnypilot. Read the latest terms at https://sunnypilot.ai/terms before continuing." +msgstr "" + +#: openpilot/selfdrive/ui/onroad/driver_camera_dialog.py +msgid "camera starting" +msgstr "카메라 시작 중" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "checking..." +msgstr "확인 중..." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "comma prime" +msgstr "comma 프라임" + +#: system/ui/widgets/network.py +msgid "default" +msgstr "기본값" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "down" +msgstr "아래" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "downloading..." +msgstr "다운로드 중..." + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "failed to check for update" +msgstr "업데이트 확인 실패" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "finalizing update..." +msgstr "업데이트 마무리 중..." + +#: system/ui/widgets/network.py +msgid "for \"{}\"" +msgstr "\"{}\"용" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "km/h" +msgstr "km/h" + +#: system/ui/widgets/network.py +msgid "leave blank for automatic configuration" +msgstr "자동 구성을 사용하려면 비워 두세요" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "left" +msgstr "왼쪽" + +#: system/ui/widgets/network.py +msgid "metered" +msgstr "종량제" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "mph" +msgstr "mph" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "never" +msgstr "없음" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "now" +msgstr "지금" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "right" +msgstr "오른쪽" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "sunnypilot Longitudinal Control (Alpha)" +msgstr "" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "sunnypilot Unavailable" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "sunnypilot longitudinal control may come in a future update." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "sunnypilot requires the device to be mounted within 4° left or right and within 5° up or 9° down." +msgstr "" + +#: system/ui/widgets/network.py +msgid "unmetered" +msgstr "비종량제" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "up" +msgstr "위" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked never" +msgstr "최신입니다. 마지막 확인: 없음" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked {}" +msgstr "최신입니다. 마지막 확인: {}" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "update available" +msgstr "업데이트 가능" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "{} ALERT" +msgid_plural "{} ALERTS" +msgstr[0] "{}건의 알림" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} day ago" +msgid_plural "{} days ago" +msgstr[0] "{}일 전" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} hour ago" +msgid_plural "{} hours ago" +msgstr[0] "{}시간 전" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} minute ago" +msgid_plural "{} minutes ago" +msgstr[0] "{}분 전" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "{} segment of your driving is in the training dataset so far." +msgid_plural "{} segments of your driving is in the training dataset so far." +msgstr[0] "현재까지 귀하의 주행 {}구간이 학습 데이터셋에 포함되었습니다." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "✓ SUBSCRIBED" +msgstr "✓ 구독됨" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "🔥 Firehose Mode 🔥" +msgstr "🔥 파이어호스 모드 🔥" + diff --git a/openpilot/selfdrive/ui/translations/app_pt-BR.po b/openpilot/selfdrive/ui/translations/app_pt-BR.po new file mode 100644 index 0000000000..5244d9f63f --- /dev/null +++ b/openpilot/selfdrive/ui/translations/app_pt-BR.po @@ -0,0 +1,873 @@ +msgid "" +msgstr "" +"Content-Type: text/plain; charset=UTF-8\n" +"Language: pt-BR\n" +"Plural-Forms: nplurals=2; plural=(n > 1);\n" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is complete." +msgstr " A calibração da resposta de torque da direção foi concluída." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is {}% complete." +msgstr " A calibração da resposta de torque da direção está {}% concluída." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Your device is pointed {:.1f}° {} and {:.1f}° {}." +msgstr " Seu dispositivo está apontado {:.1f}° {} e {:.1f}° {}." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "--" +msgstr "--" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "1 year of drive storage" +msgstr "1 ano de armazenamento de condução" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "24/7 LTE connectivity" +msgstr "Conectividade LTE 24/7" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "2G" +msgstr "2G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "3G" +msgstr "3G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "5G" +msgstr "5G" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is complete." +msgstr "

A calibração da latência da direção está concluída." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is {}% complete." +msgstr "

A calibração da latência da direção está {}% concluída." + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "ADD" +msgstr "ADICIONAR" + +#: system/ui/widgets/network.py +msgid "APN Setting" +msgstr "Configuração de APN" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Acknowledge Excessive Actuation" +msgstr "Reconhecer Atuação Excessiva" + +#: system/ui/widgets/network.py +msgid "Advanced" +msgstr "Avançado" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Aggressive" +msgstr "Agressivo" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Agree" +msgstr "Concordo" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Always-On Driver Monitoring" +msgstr "Monitoramento de Motorista Sempre Ativo" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to power off?" +msgstr "Tem certeza de que deseja desligar?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reboot?" +msgstr "Tem certeza de que deseja reiniciar?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reset calibration?" +msgstr "Tem certeza de que deseja redefinir a calibração?" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Are you sure you want to uninstall?" +msgstr "Tem certeza de que deseja desinstalar?" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +#: system/ui/widgets/network.py +msgid "Back" +msgstr "Voltar" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Become a comma prime member at connect.comma.ai" +msgstr "Torne-se membro comma prime em connect.comma.ai" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Bookmark connect.comma.ai to your home screen to use it like an app" +msgstr "Adicione connect.comma.ai à tela inicial para usá-lo como um app" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "CHANGE" +msgstr "ALTERAR" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "CHECK" +msgstr "VERIFICAR" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "CHILL MODE ON" +msgstr "MODO CHILL ATIVO" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/network.py +msgid "CONNECT" +msgstr "CONECTAR" + +#: system/ui/widgets/network.py +msgid "CONNECTING..." +msgstr "CONECTANDO..." + +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/keyboard.py +#: system/ui/widgets/network.py +#: system/ui/widgets/option_dialog.py +msgid "Cancel" +msgstr "Cancelar" + +#: system/ui/widgets/network.py +msgid "Cellular Metered" +msgstr "Dados móveis limitados" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Change Language" +msgstr "Alterar Idioma" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Changing this setting will restart sunnypilot if the car is powered on." +msgstr "" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Choose your sponsorship tier and confirm your support" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Click \"add new device\" and scan the QR code on the right" +msgstr "Toque em \"adicionar novo dispositivo\" e escaneie o QR code à direita" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Close" +msgstr "Fechar" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Current Version" +msgstr "Versão Atual" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "DOWNLOAD" +msgstr "BAIXAR" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline" +msgstr "Recusar" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline, uninstall sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Developer" +msgstr "Desenvolv" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Device" +msgstr "Dispositivo" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Disengage on Accelerator Pedal" +msgstr "Desativar ao pressionar o acelerador" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Power Off" +msgstr "Desativar para Desligar" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reboot" +msgstr "Desativar para Reiniciar" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reset Calibration" +msgstr "Desativar para Redefinir Calibração" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Display speed in km/h instead of mph." +msgstr "Exibir velocidade em km/h em vez de mph." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Dongle ID" +msgstr "ID do Dongle" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Download" +msgstr "Baixar" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Driver Camera" +msgstr "Câmera do Motorista" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Driving Personality" +msgstr "Personalidade" + +#: system/ui/widgets/network.py +msgid "EDIT" +msgstr "EDITAR" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ERROR" +msgstr "ERRO" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ETH" +msgstr "ETH" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "EXPERIMENTAL MODE ON" +msgstr "MODO EXPERIMENTAL ATIVO" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Early Access: Become a sunnypilot Sponsor" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable" +msgstr "Ativar" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable ADB" +msgstr "Ativar ADB" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable Lane Departure Warnings" +msgstr "Ativar alertas de saída de faixa" + +#: system/ui/widgets/network.py +msgid "Enable Roaming" +msgstr "Ativar roaming" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable SSH" +msgstr "Ativar SSH" + +#: system/ui/widgets/network.py +msgid "Enable Tethering" +msgstr "Ativar compartilhamento" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable driver monitoring even when sunnypilot is not engaged." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable the sunnypilot longitudinal control (alpha) toggle to allow Experimental mode." +msgstr "" + +#: system/ui/widgets/network.py +msgid "Enter APN" +msgstr "Digite APN" + +#: system/ui/widgets/network.py +msgid "Enter SSID" +msgstr "Digite SSID" + +#: system/ui/widgets/network.py +msgid "Enter new tethering password" +msgstr "Digite nova senha tethering" + +#: system/ui/widgets/network.py +msgid "Enter password" +msgstr "Digite a senha" + +#: system/ui/sunnypilot/widgets/tree_dialog.py +msgid "Enter search query" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Enter your GitHub username" +msgstr "Digite seu nome de usuário do GitHub" + +#: system/ui/widgets/list_view.py +msgid "Error" +msgstr "Erro" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental Mode" +msgstr "Modo Experimental" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control." +msgstr "O Modo Experimental está indisponível neste carro pois o ACC original do carro é usado para controle longitudinal." + +#: system/ui/widgets/network.py +msgid "FORGETTING..." +msgstr "ESQUECENDO..." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Finish Setup" +msgstr "Configure" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Firehose" +msgstr "Fluxo contínuo" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "Firehose Mode" +msgstr "Modo Firehose" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Follow the prompts to complete the pairing process" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Forget" +msgstr "Esquecer" + +#: system/ui/widgets/network.py +msgid "Forget Wi-Fi Network \"{}\"?" +msgstr "Esquecer rede Wi-Fi \"{}\"?" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "GOOD" +msgstr "BOM" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Go to https://connect.comma.ai on your phone" +msgstr "Acesse https://connect.comma.ai no seu telefone" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "HIGH" +msgstr "ALTO" + +#: system/ui/widgets/network.py +msgid "Hidden Network" +msgstr "Rede oculta" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "INSTALL" +msgstr "INSTALAR" + +#: system/ui/widgets/network.py +msgid "IP Address" +msgstr "Endereço IP" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "If sponsorship status was not updated, please contact a moderator on the community forum at https://community.sunnypilot.ai" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Install Update" +msgstr "Instalar Atualização" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Join our Community Forum at https://community.sunnypilot.ai and reach out to a moderator if you have issues" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Joystick Debug Mode" +msgstr "Modo de Depuração do Joystick" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "LOADING" +msgstr "CARREGANDO" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "LTE" +msgstr "LTE" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Lateral Maneuver Mode" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Longitudinal Maneuver Mode" +msgstr "Modo de Manobra Longitudinal" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "MAX" +msgstr "MÁX" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Maximize your training data uploads to improve openpilot's driving models." +msgstr "Maximize seus envios de dados de treinamento para melhorar os modelos de condução do openpilot." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "N/A" +msgstr "Indisp." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "NO" +msgstr "NÃO" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Network" +msgstr "Rede" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "No SSH keys found for user '{}'" +msgstr "Nenhuma chave SSH encontrada para o usuário '{}'" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "No release notes available." +msgstr "Sem notas de versão disponíveis." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "OFFLINE" +msgstr "OFF-LINE" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/html_render.py +msgid "OK" +msgstr "OK" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ONLINE" +msgstr "ON-LINE" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Open" +msgstr "Abrir" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PAIR" +msgstr "EMPARELHAR" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "PANDA" +msgstr "PANDA" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PREVIEW" +msgstr "PRÉVIA" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "PRIME FEATURES:" +msgstr "RECURSOS PRIME:" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Pair Device" +msgstr "Emparelhar Dispositivo" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair device" +msgstr "Emparelhar dispositivo" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Pair your GitHub account" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Pair your device to your comma account" +msgstr "Emparelhe seu dispositivo à sua conta comma" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer." +msgstr "Emparelhe seu dispositivo com o comma connect (connect.comma.ai) e resgate sua oferta comma prime." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Please connect to Wi-Fi to complete initial pairing" +msgstr "Conecte-se ao Wi‑Fi para concluir o emparelhamento inicial" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Power Off" +msgstr "Desligar" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered Wi-Fi connection" +msgstr "Evitar uploads grandes de dados em conexões Wi-Fi limitadas" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered cellular connection" +msgstr "Evitar uploads grandes de dados em conexões móveis limitadas" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off)" +msgstr "Pré-visualize a câmera voltada para o motorista para garantir que o monitoramento do motorista tenha boa visibilidade. (veículo deve estar desligado)" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "QR Code Error" +msgstr "Erro no QR Code" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "REMOVE" +msgstr "REMOVER" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "RESET" +msgstr "REDEFINIR" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "REVIEW" +msgstr "REVISAR" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Re-enter the \"sunnylink\" panel to verify sponsorship status" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reboot" +msgstr "Reiniciar" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Reboot Device" +msgstr "Reiniciar Dispositivo" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Reboot and Update" +msgstr "Reiniciar e Atualizar" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Driver Camera" +msgstr "Gravar e Enviar Câmera do Motorista" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Microphone Audio" +msgstr "Gravar e Enviar Áudio do Microfone" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and store microphone audio while driving. The audio will be included in the dashcam video in comma connect." +msgstr "Grave e armazene o áudio do microfone enquanto dirige. O áudio será incluído no vídeo da dashcam no comma connect." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Regulatory" +msgstr "Regulatório" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Relaxed" +msgstr "Relaxado" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote access" +msgstr "Acesso remoto" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote snapshots" +msgstr "Capturas remotas" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Request timed out" +msgstr "Tempo da solicitação esgotado" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset" +msgstr "Redefinir" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset Calibration" +msgstr "Redefinir Calibração" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review Training Guide" +msgstr "Revisar Guia de Treinamento" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review the rules, features, and limitations of sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "SELECT" +msgstr "SELECIONAR" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "SSH Keys" +msgstr "Chaves SSH" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Scan the QR code to login to your GitHub account" +msgstr "" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Scan the QR code to visit sunnyhaibin's GitHub Sponsors page" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Scanning Wi-Fi networks..." +msgstr "Procurando redes Wi-Fi..." + +#: system/ui/sunnypilot/widgets/tree_dialog.py +msgid "Search" +msgstr "" + +#: system/ui/widgets/option_dialog.py +msgid "Select" +msgstr "Selecione" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Select a branch" +msgstr "Selecione uma ramificação" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Select a language" +msgstr "Selecione um idioma" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Serial" +msgstr "Número de série" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Snooze Update" +msgstr "Adiar Atualização" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Software" +msgstr "Sistema" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Standard" +msgstr "Padrão" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "System Unresponsive" +msgstr "Sistema sem resposta" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "TAKE CONTROL IMMEDIATELY" +msgstr "ASSUMA O CONTROLE IMEDIATAMENTE" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "TEMP" +msgstr "TEMP." + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Target Branch" +msgstr "Branch Alvo" + +#: system/ui/widgets/network.py +msgid "Tethering Password" +msgstr "Senha Tethering" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Toggles" +msgstr "Alternativas" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "UI Debug Mode" +msgstr "Modo de depuração da interface do usuário" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "UNINSTALL" +msgstr "DESINSTALAR" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "UPDATE" +msgstr "ATUALIZAR" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Uninstall" +msgstr "Desinstalar" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Unknown" +msgstr "Desconhecido" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Updates are only downloaded while the car is off." +msgstr "Atualizações são baixadas apenas com o carro desligado." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Upgrade Now" +msgstr "Atualizar Agora" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Upload data from the driver facing camera and help improve the driver monitoring algorithm." +msgstr "Envie dados da câmera voltada para o motorista e ajude a melhorar o algoritmo de monitoramento do motorista." + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Use Metric System" +msgstr "Usar Sistema Métrico" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "VEHICLE" +msgstr "VEÍCULO" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "VIEW" +msgstr "VER" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Waiting to start" +msgstr "Aguardando para iniciar" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Welcome to sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "When enabled, pressing the accelerator pedal will disengage sunnypilot." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Wi-Fi" +msgstr "Wi‑Fi" + +#: system/ui/widgets/network.py +msgid "Wi-Fi Network Metered" +msgstr "Rede Wi-Fi limitada" + +#: system/ui/widgets/network.py +msgid "Wrong password" +msgstr "Senha errada" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms of Service in order to use sunnypilot." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms of Service to use sunnypilot. Read the latest terms at https://sunnypilot.ai/terms before continuing." +msgstr "" + +#: openpilot/selfdrive/ui/onroad/driver_camera_dialog.py +msgid "camera starting" +msgstr "câmera iniciando" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "checking..." +msgstr "verificando..." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "comma prime" +msgstr "comma prime" + +#: system/ui/widgets/network.py +msgid "default" +msgstr "padrão" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "down" +msgstr "para baixo" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "downloading..." +msgstr "baixando..." + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "failed to check for update" +msgstr "falha ao verificar atualização" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "finalizing update..." +msgstr "finalizando atualização..." + +#: system/ui/widgets/network.py +msgid "for \"{}\"" +msgstr "para \"{}\"" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "km/h" +msgstr "km/h" + +#: system/ui/widgets/network.py +msgid "leave blank for automatic configuration" +msgstr "deixe em branco para configuração automática" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "left" +msgstr "à esquerda" + +#: system/ui/widgets/network.py +msgid "metered" +msgstr "limitados" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "mph" +msgstr "mph" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "never" +msgstr "nunca" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "now" +msgstr "agora" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "right" +msgstr "à direita" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "sunnypilot Longitudinal Control (Alpha)" +msgstr "" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "sunnypilot Unavailable" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "sunnypilot longitudinal control may come in a future update." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "sunnypilot requires the device to be mounted within 4° left or right and within 5° up or 9° down." +msgstr "" + +#: system/ui/widgets/network.py +msgid "unmetered" +msgstr "ilimitados" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "up" +msgstr "para cima" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked never" +msgstr "atualizado, última verificação: nunca" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked {}" +msgstr "atualizado, última verificação: {}" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "update available" +msgstr "atualização disponível" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "{} ALERT" +msgid_plural "{} ALERTS" +msgstr[0] "{} ALERTA" +msgstr[1] "{} ALERTAS" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} day ago" +msgid_plural "{} days ago" +msgstr[0] "{} dia atrás" +msgstr[1] "{} dias atrás" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} hour ago" +msgid_plural "{} hours ago" +msgstr[0] "{} hora atrás" +msgstr[1] "{} horas atrás" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} minute ago" +msgid_plural "{} minutes ago" +msgstr[0] "{} minuto atrás" +msgstr[1] "{} minutos atrás" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "{} segment of your driving is in the training dataset so far." +msgid_plural "{} segments of your driving is in the training dataset so far." +msgstr[0] "{} segmento da sua condução está no conjunto de treinamento até agora." +msgstr[1] "{} segmentos da sua condução estão no conjunto de treinamento até agora." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "✓ SUBSCRIBED" +msgstr "✓ ASSINADO" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "🔥 Firehose Mode 🔥" +msgstr "🔥 Modo Firehose 🔥" + diff --git a/openpilot/selfdrive/ui/translations/app_th.po b/openpilot/selfdrive/ui/translations/app_th.po new file mode 100644 index 0000000000..4897809528 --- /dev/null +++ b/openpilot/selfdrive/ui/translations/app_th.po @@ -0,0 +1,868 @@ +msgid "" +msgstr "" +"Content-Type: text/plain; charset=UTF-8\n" +"Language: th\n" +"Plural-Forms: nplurals=1; plural=0;\n" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is complete." +msgstr "การสอบเทียบการตอบสนองแรงบิดของพวงมาลัยเสร็จสมบูรณ์" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is {}% complete." +msgstr "การสอบเทียบการตอบสนองแรงบิดของพวงมาลัยเสร็จสมบูรณ์ {}%" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Your device is pointed {:.1f}° {} and {:.1f}° {}." +msgstr "อุปกรณ์ของคุณชี้ไปที่ {:.1f}° {} และ {:.1f}° {}" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "--" +msgstr "--" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "1 year of drive storage" +msgstr "พื้นที่เก็บข้อมูลไดรฟ์ 1 ปี" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "24/7 LTE connectivity" +msgstr "การเชื่อมต่อ LTE ตลอด 24 ชั่วโมงทุกวัน" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "2G" +msgstr "2จี" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "3G" +msgstr "3จี" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "5G" +msgstr "5จี" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is complete." +msgstr "

การปรับเทียบความล่าช้าของพวงมาลัยเสร็จสมบูรณ์" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is {}% complete." +msgstr "

การปรับเทียบความล่าช้าของพวงมาลัย {}% เสร็จสมบูรณ์" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "ADD" +msgstr "เพิ่ม" + +#: system/ui/widgets/network.py +msgid "APN Setting" +msgstr "การตั้งค่า APN" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Acknowledge Excessive Actuation" +msgstr "รับทราบการดำเนินการที่มากเกินไป" + +#: system/ui/widgets/network.py +msgid "Advanced" +msgstr "ขั้นสูง" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Aggressive" +msgstr "ก้าวร้าว" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Agree" +msgstr "เห็นด้วย" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Always-On Driver Monitoring" +msgstr "การตรวจสอบไดรเวอร์ตลอดเวลา" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to power off?" +msgstr "คุณแน่ใจหรือไม่ว่าต้องการปิดเครื่อง?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reboot?" +msgstr "คุณแน่ใจหรือไม่ว่าต้องการรีบูต?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reset calibration?" +msgstr "คุณแน่ใจหรือไม่ว่าต้องการรีเซ็ตการปรับเทียบ" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Are you sure you want to uninstall?" +msgstr "คุณแน่ใจหรือไม่ว่าต้องการถอนการติดตั้ง?" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +#: system/ui/widgets/network.py +msgid "Back" +msgstr "กลับ" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Become a comma prime member at connect.comma.ai" +msgstr "เป็นสมาชิกจุลภาคไพรม์ที่ Connect.comma.ai" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Bookmark connect.comma.ai to your home screen to use it like an app" +msgstr "คั่นหน้า Connect.comma.ai ไปที่หน้าจอหลักของคุณเพื่อใช้เหมือนแอป" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "CHANGE" +msgstr "เปลี่ยน" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "CHECK" +msgstr "ตรวจสอบ" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "CHILL MODE ON" +msgstr "เปิดโหมด Chill" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/network.py +msgid "CONNECT" +msgstr "เชื่อมต่อ" + +#: system/ui/widgets/network.py +msgid "CONNECTING..." +msgstr "กำลังเชื่อมต่อ..." + +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/keyboard.py +#: system/ui/widgets/network.py +#: system/ui/widgets/option_dialog.py +msgid "Cancel" +msgstr "ยกเลิก" + +#: system/ui/widgets/network.py +msgid "Cellular Metered" +msgstr "เซลล์วัดแสง" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Change Language" +msgstr "เปลี่ยนภาษา" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Changing this setting will restart sunnypilot if the car is powered on." +msgstr "" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Choose your sponsorship tier and confirm your support" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Click \"add new device\" and scan the QR code on the right" +msgstr "คลิก \"เพิ่มอุปกรณ์ใหม่\" และสแกนโค้ด QR ทางด้านขวา" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Close" +msgstr "ปิด" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Current Version" +msgstr "เวอร์ชันปัจจุบัน" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "DOWNLOAD" +msgstr "ดาวน์โหลด" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline" +msgstr "ปฏิเสธ" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline, uninstall sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Developer" +msgstr "นักพัฒนา" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Device" +msgstr "อุปกรณ์" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Disengage on Accelerator Pedal" +msgstr "ปลดเมื่อเหยียบคันเร่ง" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Power Off" +msgstr "ปลดเพื่อปิดเครื่อง" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reboot" +msgstr "ยกเลิกการเชื่อมต่อเพื่อรีบูต" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reset Calibration" +msgstr "ปลดเพื่อรีเซ็ตการปรับเทียบ" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Display speed in km/h instead of mph." +msgstr "แสดงความเร็วเป็น km/h แทน mph" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Dongle ID" +msgstr "รหัสดองเกิล" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Download" +msgstr "ดาวน์โหลด" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Driver Camera" +msgstr "กล้องไดร์เวอร์" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Driving Personality" +msgstr "บุคลิกภาพในการขับขี่" + +#: system/ui/widgets/network.py +msgid "EDIT" +msgstr "แก้ไข" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ERROR" +msgstr "ข้อผิดพลาด" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ETH" +msgstr "ผลประโยชน์ทับซ้อน" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "EXPERIMENTAL MODE ON" +msgstr "โหมดทดลองเปิดอยู่" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Early Access: Become a sunnypilot Sponsor" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable" +msgstr "เปิดใช้งาน" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable ADB" +msgstr "เปิดใช้งาน ADB" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable Lane Departure Warnings" +msgstr "เปิดใช้งานคำเตือนการออกนอกเลน" + +#: system/ui/widgets/network.py +msgid "Enable Roaming" +msgstr "เปิดใช้งานโรมมิ่ง" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable SSH" +msgstr "เปิดใช้งาน SSH" + +#: system/ui/widgets/network.py +msgid "Enable Tethering" +msgstr "เปิดใช้งานการปล่อยสัญญาณ" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable driver monitoring even when sunnypilot is not engaged." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable the sunnypilot longitudinal control (alpha) toggle to allow Experimental mode." +msgstr "" + +#: system/ui/widgets/network.py +msgid "Enter APN" +msgstr "ป้อน APN" + +#: system/ui/widgets/network.py +msgid "Enter SSID" +msgstr "ป้อน SSID" + +#: system/ui/widgets/network.py +msgid "Enter new tethering password" +msgstr "ป้อนรหัสผ่านการปล่อยสัญญาณใหม่" + +#: system/ui/widgets/network.py +msgid "Enter password" +msgstr "ใส่รหัสผ่าน" + +#: system/ui/sunnypilot/widgets/tree_dialog.py +msgid "Enter search query" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Enter your GitHub username" +msgstr "ป้อนชื่อผู้ใช้ GitHub ของคุณ" + +#: system/ui/widgets/list_view.py +msgid "Error" +msgstr "ข้อผิดพลาด" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental Mode" +msgstr "โหมดทดลอง" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control." +msgstr "ขณะนี้โหมดทดลองไม่สามารถใช้งานได้บนรถคันนี้ เนื่องจาก ACC ในสต็อกของรถใช้สำหรับการควบคุมตามยาว" + +#: system/ui/widgets/network.py +msgid "FORGETTING..." +msgstr "กำลังลืม..." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Finish Setup" +msgstr "เสร็จสิ้นการตั้งค่า" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Firehose" +msgstr "สายดับเพลิง" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "Firehose Mode" +msgstr "โหมดสายดับเพลิง" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Follow the prompts to complete the pairing process" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Forget" +msgstr "ลืม" + +#: system/ui/widgets/network.py +msgid "Forget Wi-Fi Network \"{}\"?" +msgstr "ลืมเครือข่าย Wi-Fi \"{}\" หรือไม่" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "GOOD" +msgstr "ดี" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Go to https://connect.comma.ai on your phone" +msgstr "ไปที่ https://connect.comma.ai บนโทรศัพท์ของคุณ" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "HIGH" +msgstr "สูง" + +#: system/ui/widgets/network.py +msgid "Hidden Network" +msgstr "เครือข่ายที่ซ่อนอยู่" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "INSTALL" +msgstr "ติดตั้ง" + +#: system/ui/widgets/network.py +msgid "IP Address" +msgstr "ที่อยู่ IP" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "If sponsorship status was not updated, please contact a moderator on the community forum at https://community.sunnypilot.ai" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Install Update" +msgstr "ติดตั้งอัปเดต" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Join our Community Forum at https://community.sunnypilot.ai and reach out to a moderator if you have issues" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Joystick Debug Mode" +msgstr "โหมดดีบักจอยสติ๊ก" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "LOADING" +msgstr "กำลังโหลด" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "LTE" +msgstr "แอลทีที" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Lateral Maneuver Mode" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Longitudinal Maneuver Mode" +msgstr "โหมดการซ้อมรบตามยาว" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "MAX" +msgstr "สูงสุด" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Maximize your training data uploads to improve openpilot's driving models." +msgstr "เพิ่มการอัปโหลดข้อมูลการฝึกของคุณให้สูงสุดเพื่อปรับปรุงโมเดลการขับขี่ของ Openpilot" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "N/A" +msgstr "ไม่มี" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "NO" +msgstr "เลขที่" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Network" +msgstr "เครือข่าย" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "No SSH keys found for user '{}'" +msgstr "ไม่พบคีย์ SSH สำหรับผู้ใช้ '{}'" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "No release notes available." +msgstr "ไม่มีบันทึกประจำรุ่น" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "OFFLINE" +msgstr "ออฟไลน์" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/html_render.py +msgid "OK" +msgstr "ตกลง" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ONLINE" +msgstr "ออนไลน์" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Open" +msgstr "เปิด" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PAIR" +msgstr "คู่" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "PANDA" +msgstr "แพนด้า" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PREVIEW" +msgstr "ดูตัวอย่าง" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "PRIME FEATURES:" +msgstr "คุณสมบัติเด่น:" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Pair Device" +msgstr "จับคู่อุปกรณ์" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair device" +msgstr "จับคู่อุปกรณ์" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Pair your GitHub account" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Pair your device to your comma account" +msgstr "จับคู่อุปกรณ์ของคุณกับบัญชีลูกน้ำของคุณ" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer." +msgstr "จับคู่อุปกรณ์ของคุณกับการเชื่อมต่อด้วยเครื่องหมายจุลภาค (connect.comma.ai) และรับข้อเสนอจุลภาคเฉพาะของคุณ" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Please connect to Wi-Fi to complete initial pairing" +msgstr "โปรดเชื่อมต่อ Wi-Fi เพื่อทำการจับคู่ครั้งแรกให้เสร็จสิ้น" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Power Off" +msgstr "ปิดเครื่อง" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered Wi-Fi connection" +msgstr "ป้องกันการอัปโหลดข้อมูลขนาดใหญ่เมื่อใช้การเชื่อมต่อ Wi-Fi แบบมิเตอร์" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered cellular connection" +msgstr "ป้องกันการอัพโหลดข้อมูลขนาดใหญ่เมื่อใช้การเชื่อมต่อมือถือแบบคิดค่าบริการตามปริมาณข้อมูล" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off)" +msgstr "ดูตัวอย่างกล้องที่หันหน้าไปทางคนขับเพื่อให้แน่ใจว่าการตรวจสอบผู้ขับขี่มีทัศนวิสัยที่ดี (รถจะต้องถูกปิด)" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "QR Code Error" +msgstr "ข้อผิดพลาดรหัส QR" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "REMOVE" +msgstr "ลบ" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "RESET" +msgstr "รีเซ็ต" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "REVIEW" +msgstr "ทบทวน" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Re-enter the \"sunnylink\" panel to verify sponsorship status" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reboot" +msgstr "รีบูต" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Reboot Device" +msgstr "รีบูตอุปกรณ์" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Reboot and Update" +msgstr "รีบูตและอัปเดต" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Driver Camera" +msgstr "บันทึกและอัพโหลดกล้องไดร์เวอร์" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Microphone Audio" +msgstr "บันทึกและอัปโหลดเสียงไมโครโฟน" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and store microphone audio while driving. The audio will be included in the dashcam video in comma connect." +msgstr "บันทึกและจัดเก็บเสียงไมโครโฟนขณะขับรถ เสียงจะรวมอยู่ในวิดีโอ dashcam ด้วยการเชื่อมต่อด้วยเครื่องหมายจุลภาค" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Regulatory" +msgstr "กฎระเบียบ" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Relaxed" +msgstr "ผ่อนคลาย" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote access" +msgstr "การเข้าถึงระยะไกล" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote snapshots" +msgstr "สแนปชอตระยะไกล" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Request timed out" +msgstr "คำขอหมดเวลา" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset" +msgstr "รีเซ็ต" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset Calibration" +msgstr "รีเซ็ตการปรับเทียบ" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review Training Guide" +msgstr "ทบทวนคู่มือการฝึกอบรม" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review the rules, features, and limitations of sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "SELECT" +msgstr "เลือก" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "SSH Keys" +msgstr "คีย์ SSH" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Scan the QR code to login to your GitHub account" +msgstr "" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Scan the QR code to visit sunnyhaibin's GitHub Sponsors page" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Scanning Wi-Fi networks..." +msgstr "กำลังสแกนเครือข่าย Wi-Fi..." + +#: system/ui/sunnypilot/widgets/tree_dialog.py +msgid "Search" +msgstr "" + +#: system/ui/widgets/option_dialog.py +msgid "Select" +msgstr "เลือก" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Select a branch" +msgstr "เลือกสาขา" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Select a language" +msgstr "เลือกภาษา" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Serial" +msgstr "อนุกรม" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Snooze Update" +msgstr "เลื่อนการอัปเดต" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Software" +msgstr "ซอฟต์แวร์" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Standard" +msgstr "มาตรฐาน" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "System Unresponsive" +msgstr "ระบบไม่ตอบสนอง" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "TAKE CONTROL IMMEDIATELY" +msgstr "เข้าควบคุมทันที" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "TEMP" +msgstr "อุณหภูมิ" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Target Branch" +msgstr "สาขาเป้าหมาย" + +#: system/ui/widgets/network.py +msgid "Tethering Password" +msgstr "รหัสผ่านการแชร์อินเทอร์เน็ต" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Toggles" +msgstr "สลับ" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "UI Debug Mode" +msgstr "โหมดดีบัก UI" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "UNINSTALL" +msgstr "ถอนการติดตั้ง" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "UPDATE" +msgstr "อัปเดต" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Uninstall" +msgstr "ถอนการติดตั้ง" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Unknown" +msgstr "ไม่ทราบ" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Updates are only downloaded while the car is off." +msgstr "การอัพเดตจะถูกดาวน์โหลดในขณะที่รถดับอยู่เท่านั้น" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Upgrade Now" +msgstr "อัพเกรดทันที" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Upload data from the driver facing camera and help improve the driver monitoring algorithm." +msgstr "อัปโหลดข้อมูลจากกล้องที่หันเข้าหาคนขับและช่วยปรับปรุงอัลกอริธึมการตรวจสอบผู้ขับขี่" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Use Metric System" +msgstr "ใช้ระบบเมตริก" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "VEHICLE" +msgstr "ยานพาหนะ" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "VIEW" +msgstr "ดู" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Waiting to start" +msgstr "กำลังรอที่จะเริ่ม" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Welcome to sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "When enabled, pressing the accelerator pedal will disengage sunnypilot." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Wi-Fi" +msgstr "อินเตอร์เน็ตไร้สาย" + +#: system/ui/widgets/network.py +msgid "Wi-Fi Network Metered" +msgstr "เครือข่าย Wi-Fi มีการตรวจวัด" + +#: system/ui/widgets/network.py +msgid "Wrong password" +msgstr "รหัสผ่านผิด" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms of Service in order to use sunnypilot." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms of Service to use sunnypilot. Read the latest terms at https://sunnypilot.ai/terms before continuing." +msgstr "" + +#: openpilot/selfdrive/ui/onroad/driver_camera_dialog.py +msgid "camera starting" +msgstr "กำลังเริ่มกล้อง" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "checking..." +msgstr "กำลังตรวจสอบ..." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "comma prime" +msgstr "เครื่องหมายลูกน้ำเฉพาะ" + +#: system/ui/widgets/network.py +msgid "default" +msgstr "ค่าเริ่มต้น" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "down" +msgstr "ลง" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "downloading..." +msgstr "กำลังดาวน์โหลด..." + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "failed to check for update" +msgstr "ไม่สามารถตรวจสอบการอัปเดตได้" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "finalizing update..." +msgstr "กำลังสรุปการอัปเดต..." + +#: system/ui/widgets/network.py +msgid "for \"{}\"" +msgstr "สำหรับ \"{}\"" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "km/h" +msgstr "กม./ชม" + +#: system/ui/widgets/network.py +msgid "leave blank for automatic configuration" +msgstr "เว้นว่างไว้เพื่อกำหนดค่าอัตโนมัติ" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "left" +msgstr "ซ้าย" + +#: system/ui/widgets/network.py +msgid "metered" +msgstr "คิดค่าบริการตามปริมาณ" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "mph" +msgstr "ไมล์/ชม." + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "never" +msgstr "ไม่เคย" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "now" +msgstr "ตอนนี้" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "right" +msgstr "ขวา" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "sunnypilot Longitudinal Control (Alpha)" +msgstr "" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "sunnypilot Unavailable" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "sunnypilot longitudinal control may come in a future update." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "sunnypilot requires the device to be mounted within 4° left or right and within 5° up or 9° down." +msgstr "" + +#: system/ui/widgets/network.py +msgid "unmetered" +msgstr "ไม่จำกัดปริมาณ" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "up" +msgstr "ขึ้น" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked never" +msgstr "เป็นเวอร์ชันล่าสุด ตรวจสอบครั้งล่าสุด: ไม่เคย" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked {}" +msgstr "เป็นเวอร์ชันล่าสุด ตรวจสอบครั้งล่าสุดเมื่อ {}" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "update available" +msgstr "มีอัปเดตใหม่" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "{} ALERT" +msgid_plural "{} ALERTS" +msgstr[0] "การแจ้งเตือน {} รายการ" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} day ago" +msgid_plural "{} days ago" +msgstr[0] "{} วันที่แล้ว" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} hour ago" +msgid_plural "{} hours ago" +msgstr[0] "{} ชั่วโมงที่แล้ว" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} minute ago" +msgid_plural "{} minutes ago" +msgstr[0] "{} นาทีที่แล้ว" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "{} segment of your driving is in the training dataset so far." +msgid_plural "{} segments of your driving is in the training dataset so far." +msgstr[0] "ขณะนี้มีช่วงการขับขี่ของคุณ {} ช่วงอยู่ในชุดข้อมูลฝึกสอนแล้ว" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "✓ SUBSCRIBED" +msgstr "✓ สมัครแล้ว" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "🔥 Firehose Mode 🔥" +msgstr "🔥 โหมด Firehose 🔥" + diff --git a/openpilot/selfdrive/ui/translations/app_tr.po b/openpilot/selfdrive/ui/translations/app_tr.po new file mode 100644 index 0000000000..a6da586bbd --- /dev/null +++ b/openpilot/selfdrive/ui/translations/app_tr.po @@ -0,0 +1,873 @@ +msgid "" +msgstr "" +"Content-Type: text/plain; charset=UTF-8\n" +"Language: tr\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is complete." +msgstr " Direksiyon tork tepkisi kalibrasyonu tamamlandı." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is {}% complete." +msgstr " Direksiyon tork tepkisi kalibrasyonu {}% tamamlandı." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Your device is pointed {:.1f}° {} and {:.1f}° {}." +msgstr " Cihazınız {:.1f}° {} ve {:.1f}° {} yönünde konumlandırılmış." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "--" +msgstr "--" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "1 year of drive storage" +msgstr "1 yıl sürüş depolaması" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "24/7 LTE connectivity" +msgstr "7/24 LTE bağlantısı" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "2G" +msgstr "2G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "3G" +msgstr "3G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "5G" +msgstr "5G" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is complete." +msgstr "

Direksiyon gecikmesi kalibrasyonu tamamlandı." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is {}% complete." +msgstr "

Direksiyon gecikmesi kalibrasyonu %{} tamamlandı." + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "ADD" +msgstr "EKLE" + +#: system/ui/widgets/network.py +msgid "APN Setting" +msgstr "APN Ayarı" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Acknowledge Excessive Actuation" +msgstr "Aşırı Müdahaleyi Onayla" + +#: system/ui/widgets/network.py +msgid "Advanced" +msgstr "Gelişmiş" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Aggressive" +msgstr "Agresif" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Agree" +msgstr "Kabul et" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Always-On Driver Monitoring" +msgstr "Sürekli Sürücü İzleme" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to power off?" +msgstr "Kapatmak istediğinizden emin misiniz?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reboot?" +msgstr "Yeniden başlatmak istediğinizden emin misiniz?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reset calibration?" +msgstr "Kalibrasyonu sıfırlamak istediğinizden emin misiniz?" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Are you sure you want to uninstall?" +msgstr "Kaldırmak istediğinizden emin misiniz?" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +#: system/ui/widgets/network.py +msgid "Back" +msgstr "Geri" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Become a comma prime member at connect.comma.ai" +msgstr "connect.comma.ai adresinde comma prime üyesi olun" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Bookmark connect.comma.ai to your home screen to use it like an app" +msgstr "connect.comma.ai'yi ana ekranınıza ekleyerek bir uygulama gibi kullanın" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "CHANGE" +msgstr "DEĞİŞTİR" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "CHECK" +msgstr "KONTROL ET" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "CHILL MODE ON" +msgstr "CHILL MODU AÇIK" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/network.py +msgid "CONNECT" +msgstr "BAĞLAN" + +#: system/ui/widgets/network.py +msgid "CONNECTING..." +msgstr "BAĞLAN" + +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/keyboard.py +#: system/ui/widgets/network.py +#: system/ui/widgets/option_dialog.py +msgid "Cancel" +msgstr "İptal" + +#: system/ui/widgets/network.py +msgid "Cellular Metered" +msgstr "Ölçülü Hücresel" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Change Language" +msgstr "Dili Değiştir" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Changing this setting will restart sunnypilot if the car is powered on." +msgstr "" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Choose your sponsorship tier and confirm your support" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Click \"add new device\" and scan the QR code on the right" +msgstr "\"yeni cihaz ekle\"ye tıklayın ve sağdaki QR kodunu tarayın" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Close" +msgstr "Kapat" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Current Version" +msgstr "Geçerli Sürüm" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "DOWNLOAD" +msgstr "İNDİR" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline" +msgstr "Reddet" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline, uninstall sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Developer" +msgstr "Geliştirici" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Device" +msgstr "Cihaz" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Disengage on Accelerator Pedal" +msgstr "Gaz Pedalında Devreden Çık" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Power Off" +msgstr "Kapatmak için Devreden Çıkın" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reboot" +msgstr "Yeniden Başlatmak için Devreden Çıkın" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reset Calibration" +msgstr "Kalibrasyonu Sıfırlamak için Devreden Çıkın" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Display speed in km/h instead of mph." +msgstr "Hızı mph yerine km/h olarak göster." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Dongle ID" +msgstr "Dongle kimliği" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Download" +msgstr "İndir" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Driver Camera" +msgstr "Sürücü Kamerası" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Driving Personality" +msgstr "Sürüş Kişiliği" + +#: system/ui/widgets/network.py +msgid "EDIT" +msgstr "DÜZENLE" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ERROR" +msgstr "HATA" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ETH" +msgstr "ETH" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "EXPERIMENTAL MODE ON" +msgstr "DENEYSEL MOD AÇIK" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Early Access: Become a sunnypilot Sponsor" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable" +msgstr "Etkinleştir" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable ADB" +msgstr "ADB'yi Etkinleştir" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable Lane Departure Warnings" +msgstr "Şerit Terk Uyarılarını Etkinleştir" + +#: system/ui/widgets/network.py +msgid "Enable Roaming" +msgstr "Dolaşımı Etkinleştir" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable SSH" +msgstr "SSH'yi Etkinleştir" + +#: system/ui/widgets/network.py +msgid "Enable Tethering" +msgstr "İnternet Paylaşımını Etkinleştir" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable driver monitoring even when sunnypilot is not engaged." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable the sunnypilot longitudinal control (alpha) toggle to allow Experimental mode." +msgstr "" + +#: system/ui/widgets/network.py +msgid "Enter APN" +msgstr "APN girin" + +#: system/ui/widgets/network.py +msgid "Enter SSID" +msgstr "SSID girin" + +#: system/ui/widgets/network.py +msgid "Enter new tethering password" +msgstr "Yeni internet paylaşımı şifresini girin" + +#: system/ui/widgets/network.py +msgid "Enter password" +msgstr "Şifre girin" + +#: system/ui/sunnypilot/widgets/tree_dialog.py +msgid "Enter search query" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Enter your GitHub username" +msgstr "GitHub kullanıcı adınızı girin" + +#: system/ui/widgets/list_view.py +msgid "Error" +msgstr "Hata" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental Mode" +msgstr "Deneysel Mod" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control." +msgstr "Bu araçta boylamsal kontrol için stok ACC kullanıldığından şu anda Deneysel mod kullanılamıyor." + +#: system/ui/widgets/network.py +msgid "FORGETTING..." +msgstr "UNUTULUYOR..." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Finish Setup" +msgstr "Kurulumu Bitir" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Firehose" +msgstr "Yoğun veri akışı" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "Firehose Mode" +msgstr "Firehose Modu" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Follow the prompts to complete the pairing process" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Forget" +msgstr "Unut" + +#: system/ui/widgets/network.py +msgid "Forget Wi-Fi Network \"{}\"?" +msgstr "\"{}\" Wi‑Fi ağı unutulsun mu?" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "GOOD" +msgstr "İYİ" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Go to https://connect.comma.ai on your phone" +msgstr "Telefonunuzda https://connect.comma.ai adresine gidin" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "HIGH" +msgstr "YÜKSEK" + +#: system/ui/widgets/network.py +msgid "Hidden Network" +msgstr "Gizli Ağ" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "INSTALL" +msgstr "YÜKLE" + +#: system/ui/widgets/network.py +msgid "IP Address" +msgstr "IP Adresi" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "If sponsorship status was not updated, please contact a moderator on the community forum at https://community.sunnypilot.ai" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Install Update" +msgstr "Güncellemeyi Yükle" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Join our Community Forum at https://community.sunnypilot.ai and reach out to a moderator if you have issues" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Joystick Debug Mode" +msgstr "Joystick Hata Ayıklama Modu" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "LOADING" +msgstr "YÜKLENİYOR" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "LTE" +msgstr "LTE" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Lateral Maneuver Mode" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Longitudinal Maneuver Mode" +msgstr "Boylamsal Manevra Modu" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "MAX" +msgstr "MAKS" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Maximize your training data uploads to improve openpilot's driving models." +msgstr "openpilot'un sürüş modellerini iyileştirmek için eğitim veri yüklemelerinizi en üst düzeye çıkarın." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "N/A" +msgstr "Yok" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "NO" +msgstr "HAYIR" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Network" +msgstr "Ağ" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "No SSH keys found for user '{}'" +msgstr "'{}' kullanıcısı için SSH anahtarı bulunamadı" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "No release notes available." +msgstr "Sürüm notu mevcut değil." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "OFFLINE" +msgstr "ÇEVRİMDIŞI" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/html_render.py +msgid "OK" +msgstr "OK" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ONLINE" +msgstr "ÇEVRİMİÇİ" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Open" +msgstr "Aç" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PAIR" +msgstr "EŞLE" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "PANDA" +msgstr "PANDA" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PREVIEW" +msgstr "ÖNİZLEME" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "PRIME FEATURES:" +msgstr "PRIME ÖZELLİKLERİ:" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Pair Device" +msgstr "Cihazı Eşle" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair device" +msgstr "Cihazı eşle" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Pair your GitHub account" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Pair your device to your comma account" +msgstr "Cihazınızı comma hesabınızla eşleştirin" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer." +msgstr "Cihazınızı comma connect (connect.comma.ai) ile eşleştirin ve comma prime teklifinizi alın." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Please connect to Wi-Fi to complete initial pairing" +msgstr "İlk eşleştirmeyi tamamlamak için lütfen Wi‑Fi'a bağlanın" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Power Off" +msgstr "Kapat" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered Wi-Fi connection" +msgstr "Ölçülü bir Wi‑Fi bağlantısındayken büyük veri yüklemelerini engelle" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered cellular connection" +msgstr "Ölçülü bir hücresel bağlantıdayken büyük veri yüklemelerini engelle" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off)" +msgstr "Sürücü izleme görünürlüğünün iyi olduğundan emin olmak için sürücüye bakan kamerayı önizleyin. (araç kapalı olmalıdır)" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "QR Code Error" +msgstr "QR Kod Hatası" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "REMOVE" +msgstr "KALDIR" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "RESET" +msgstr "SIFIRLA" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "REVIEW" +msgstr "GÖZDEN GEÇİR" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Re-enter the \"sunnylink\" panel to verify sponsorship status" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reboot" +msgstr "Yeniden Başlat" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Reboot Device" +msgstr "Cihazı Yeniden Başlat" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Reboot and Update" +msgstr "Yeniden Başlat ve Güncelle" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Driver Camera" +msgstr "Sürücü Kamerasını Kaydet ve Yükle" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Microphone Audio" +msgstr "Mikrofon Sesini Kaydet ve Yükle" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and store microphone audio while driving. The audio will be included in the dashcam video in comma connect." +msgstr "Sürüş sırasında mikrofon sesini kaydedip saklayın. Ses, comma connect'teki ön kamera videosuna dahil edilecektir." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Regulatory" +msgstr "Mevzuat" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Relaxed" +msgstr "Rahat" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote access" +msgstr "Uzaktan erişim" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote snapshots" +msgstr "Uzaktan anlık görüntüler" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Request timed out" +msgstr "İstek zaman aşımına uğradı" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset" +msgstr "Sıfırla" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset Calibration" +msgstr "Kalibrasyonu Sıfırla" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review Training Guide" +msgstr "Eğitim Kılavuzunu İncele" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review the rules, features, and limitations of sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "SELECT" +msgstr "SEÇ" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "SSH Keys" +msgstr "SSH Anahtarları" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Scan the QR code to login to your GitHub account" +msgstr "" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Scan the QR code to visit sunnyhaibin's GitHub Sponsors page" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Scanning Wi-Fi networks..." +msgstr "Wi‑Fi ağları taranıyor..." + +#: system/ui/sunnypilot/widgets/tree_dialog.py +msgid "Search" +msgstr "" + +#: system/ui/widgets/option_dialog.py +msgid "Select" +msgstr "Seç" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Select a branch" +msgstr "Bir dal seçin" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Select a language" +msgstr "Bir dil seçin" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Serial" +msgstr "Seri" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Snooze Update" +msgstr "Güncellemeyi Ertele" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Software" +msgstr "Yazılım" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Standard" +msgstr "Standart" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "System Unresponsive" +msgstr "Sistem Yanıt Vermiyor" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "TAKE CONTROL IMMEDIATELY" +msgstr "HEMEN KONTROLÜ DEVRALIN" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "TEMP" +msgstr "SIC." + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Target Branch" +msgstr "Hedef Dal" + +#: system/ui/widgets/network.py +msgid "Tethering Password" +msgstr "İnternet Paylaşımı Şifresi" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Toggles" +msgstr "Seçenekler" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "UI Debug Mode" +msgstr "Arayüz Hata Ayıklama Modu" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "UNINSTALL" +msgstr "KALDIR" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "UPDATE" +msgstr "GÜNCELLE" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Uninstall" +msgstr "Kaldır" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Unknown" +msgstr "Bilinmiyor" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Updates are only downloaded while the car is off." +msgstr "Güncellemeler yalnızca araç kapalıyken indirilir." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Upgrade Now" +msgstr "Şimdi Yükselt" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Upload data from the driver facing camera and help improve the driver monitoring algorithm." +msgstr "Sürücüye bakan kameradan veri yükleyin ve sürücü izleme algoritmasını geliştirmeye yardımcı olun." + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Use Metric System" +msgstr "Metrik Sistemi Kullan" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "VEHICLE" +msgstr "ARAÇ" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "VIEW" +msgstr "GÖRÜNTÜLE" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Waiting to start" +msgstr "Başlatma bekleniyor" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Welcome to sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "When enabled, pressing the accelerator pedal will disengage sunnypilot." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Wi-Fi" +msgstr "Wi‑Fi" + +#: system/ui/widgets/network.py +msgid "Wi-Fi Network Metered" +msgstr "Ölçülü Wi‑Fi Ağı" + +#: system/ui/widgets/network.py +msgid "Wrong password" +msgstr "Yanlış şifre" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms of Service in order to use sunnypilot." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms of Service to use sunnypilot. Read the latest terms at https://sunnypilot.ai/terms before continuing." +msgstr "" + +#: openpilot/selfdrive/ui/onroad/driver_camera_dialog.py +msgid "camera starting" +msgstr "kamera başlatılıyor" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "checking..." +msgstr "kontrol ediliyor..." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "comma prime" +msgstr "comma prime" + +#: system/ui/widgets/network.py +msgid "default" +msgstr "varsayılan" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "down" +msgstr "aşağı" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "downloading..." +msgstr "indiriliyor..." + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "failed to check for update" +msgstr "güncelleme kontrolü başarısız" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "finalizing update..." +msgstr "güncelleme tamamlanıyor..." + +#: system/ui/widgets/network.py +msgid "for \"{}\"" +msgstr "\"{}\" için" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "km/h" +msgstr "km/h" + +#: system/ui/widgets/network.py +msgid "leave blank for automatic configuration" +msgstr "otomatik yapılandırma için boş bırakın" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "left" +msgstr "sol" + +#: system/ui/widgets/network.py +msgid "metered" +msgstr "ölçülü" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "mph" +msgstr "mph" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "never" +msgstr "asla" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "now" +msgstr "şimdi" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "right" +msgstr "sağ" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "sunnypilot Longitudinal Control (Alpha)" +msgstr "" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "sunnypilot Unavailable" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "sunnypilot longitudinal control may come in a future update." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "sunnypilot requires the device to be mounted within 4° left or right and within 5° up or 9° down." +msgstr "" + +#: system/ui/widgets/network.py +msgid "unmetered" +msgstr "ölçüsüz" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "up" +msgstr "yukarı" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked never" +msgstr "güncel, son kontrol asla" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked {}" +msgstr "güncel, son kontrol {}" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "update available" +msgstr "güncelleme mevcut" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "{} ALERT" +msgid_plural "{} ALERTS" +msgstr[0] "{} UYARI" +msgstr[1] "{} UYARILAR" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} day ago" +msgid_plural "{} days ago" +msgstr[0] "{} gün önce" +msgstr[1] "{} gün önce" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} hour ago" +msgid_plural "{} hours ago" +msgstr[0] "{} saat önce" +msgstr[1] "{} saat önce" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} minute ago" +msgid_plural "{} minutes ago" +msgstr[0] "{} dakika önce" +msgstr[1] "{} dakika önce" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "{} segment of your driving is in the training dataset so far." +msgid_plural "{} segments of your driving is in the training dataset so far." +msgstr[0] "{} segment sürüşünüz eğitim veri setinde." +msgstr[1] "{} segment sürüşünüz eğitim veri setinde." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "✓ SUBSCRIBED" +msgstr "✓ ABONE" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "🔥 Firehose Mode 🔥" +msgstr "🔥 Firehose Modu 🔥" + diff --git a/openpilot/selfdrive/ui/translations/app_uk.po b/openpilot/selfdrive/ui/translations/app_uk.po new file mode 100644 index 0000000000..43d78fad1c --- /dev/null +++ b/openpilot/selfdrive/ui/translations/app_uk.po @@ -0,0 +1,878 @@ +msgid "" +msgstr "" +"Content-Type: text/plain; charset=UTF-8\n" +"Language: uk\n" +"Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<12 || n%100>14) ? 1 : 2);\n" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is complete." +msgstr " Калібрування реакції крутного моменту керма завершено." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is {}% complete." +msgstr "Калібрування реакції крутного моменту керма завершено на {}%." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Your device is pointed {:.1f}° {} and {:.1f}° {}." +msgstr " Ваш пристрій нахилено на {:.1f}° {} та {:.1f}° {}." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "--" +msgstr "--" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "1 year of drive storage" +msgstr "1 рік зберігання поїздок" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "24/7 LTE connectivity" +msgstr "Підключення LTE 24/7" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "2G" +msgstr "2G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "3G" +msgstr "3G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "5G" +msgstr "5G" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is complete." +msgstr "

Калібрування затримки кермування завершено." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is {}% complete." +msgstr "

Калібрування затримки кермування завершено на {}%." + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "ADD" +msgstr "ДОДАТИ" + +#: system/ui/widgets/network.py +msgid "APN Setting" +msgstr "Налаштування APN" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Acknowledge Excessive Actuation" +msgstr "Визнайте надмірне спрацьовування" + +#: system/ui/widgets/network.py +msgid "Advanced" +msgstr "Розширені" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Aggressive" +msgstr "Агресивн." + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Agree" +msgstr "Погодитися" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Always-On Driver Monitoring" +msgstr "Постійний моніторинг водія" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to power off?" +msgstr "Ви впевнені, що хочете вимкнути?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reboot?" +msgstr "Ви впевнені, що хочете перезавантажити?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reset calibration?" +msgstr "Ви впевнені, що хочете скинути калібрування?" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Are you sure you want to uninstall?" +msgstr "Ви впевнені, що хочете видалити?" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +#: system/ui/widgets/network.py +msgid "Back" +msgstr "Назад" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Become a comma prime member at connect.comma.ai" +msgstr "Станьте членом comma prime на connect.comma.ai" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Bookmark connect.comma.ai to your home screen to use it like an app" +msgstr "Додайте connect.comma.ai до головного екрану, щоб використовувати його як додаток." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "CHANGE" +msgstr "ЗМІНИТИ" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "CHECK" +msgstr "ПЕРЕВІРИТИ" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "CHILL MODE ON" +msgstr "СПОКІЙНИЙ РЕЖИМ" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/network.py +msgid "CONNECT" +msgstr "ПІДКЛЮЧИТИ" + +#: system/ui/widgets/network.py +msgid "CONNECTING..." +msgstr "ПІДКЛЮЧА..." + +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/keyboard.py +#: system/ui/widgets/network.py +#: system/ui/widgets/option_dialog.py +msgid "Cancel" +msgstr "Скасувати" + +#: system/ui/widgets/network.py +msgid "Cellular Metered" +msgstr "Лімітне стільникове з'єднання" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Change Language" +msgstr "Змінити мову" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Changing this setting will restart sunnypilot if the car is powered on." +msgstr "" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Choose your sponsorship tier and confirm your support" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Click \"add new device\" and scan the QR code on the right" +msgstr "Натисніть «додати новий пристрій» і відскануйте QR-код праворуч." + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Close" +msgstr "Закрити" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Current Version" +msgstr "Поточна версія" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "DOWNLOAD" +msgstr "ВАНТАЖ" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline" +msgstr "Відхилити" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline, uninstall sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Developer" +msgstr "Розробник" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Device" +msgstr "Пристрій" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Disengage on Accelerator Pedal" +msgstr "Вимкнення при натисканні на педаль газу" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Power Off" +msgstr "Вимкніть openpilot, щоб вимкнути пристрій" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reboot" +msgstr "Вимкніть openpilot, щоб перезавантажити" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reset Calibration" +msgstr "Деактивуйте для скидання калібрування" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Display speed in km/h instead of mph." +msgstr "Відображати швидкість у км/год замість миль/год." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Dongle ID" +msgstr "ID ключа" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Download" +msgstr "Завантажити" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Driver Camera" +msgstr "Камера водія" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Driving Personality" +msgstr "Стиль водіння" + +#: system/ui/widgets/network.py +msgid "EDIT" +msgstr "РЕДАГ." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ERROR" +msgstr "ПОМИЛКА" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ETH" +msgstr "ETH" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "EXPERIMENTAL MODE ON" +msgstr "ЕКСПЕРИМЕНТ. РЕЖИМ" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Early Access: Become a sunnypilot Sponsor" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable" +msgstr "Увімкнути" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable ADB" +msgstr "Увімкнути ADB" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable Lane Departure Warnings" +msgstr "Увімкнути попередження про виїзд зі смуги" + +#: system/ui/widgets/network.py +msgid "Enable Roaming" +msgstr "Увімкнути роумінг" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable SSH" +msgstr "Увімкнути SSH" + +#: system/ui/widgets/network.py +msgid "Enable Tethering" +msgstr "Увімкнути точку доступу" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable driver monitoring even when sunnypilot is not engaged." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable the sunnypilot longitudinal control (alpha) toggle to allow Experimental mode." +msgstr "" + +#: system/ui/widgets/network.py +msgid "Enter APN" +msgstr "Введіть APN" + +#: system/ui/widgets/network.py +msgid "Enter SSID" +msgstr "Введіть SSID" + +#: system/ui/widgets/network.py +msgid "Enter new tethering password" +msgstr "Введіть новий пароль для модему" + +#: system/ui/widgets/network.py +msgid "Enter password" +msgstr "Введіть пароль" + +#: system/ui/sunnypilot/widgets/tree_dialog.py +msgid "Enter search query" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Enter your GitHub username" +msgstr "Введіть ваш логін GitHub" + +#: system/ui/widgets/list_view.py +msgid "Error" +msgstr "Помилка" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental Mode" +msgstr "Експериментальний режим" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control." +msgstr "Експериментальний режим наразі недоступний для цього автомобіля, оскільки для поздовжнього керування використовується штатний адаптивний круїз-контроль (ACC)." + +#: system/ui/widgets/network.py +msgid "FORGETTING..." +msgstr "ЗАБУВАЮ..." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Finish Setup" +msgstr "Завершити налаштування" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Firehose" +msgstr "Злива" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "Firehose Mode" +msgstr "Режим зливи" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Follow the prompts to complete the pairing process" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Forget" +msgstr "Забути" + +#: system/ui/widgets/network.py +msgid "Forget Wi-Fi Network \"{}\"?" +msgstr "Забути мережу Wi-Fi \"{}\"?" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "GOOD" +msgstr "ДОБРА" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Go to https://connect.comma.ai on your phone" +msgstr "Перейдіть на сайт https://connect.comma.ai на своєму телефоні." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "HIGH" +msgstr "ВИСОКА" + +#: system/ui/widgets/network.py +msgid "Hidden Network" +msgstr "Прихована мережа" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "INSTALL" +msgstr "ВСТАНОВ." + +#: system/ui/widgets/network.py +msgid "IP Address" +msgstr "IP-адреса" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "If sponsorship status was not updated, please contact a moderator on the community forum at https://community.sunnypilot.ai" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Install Update" +msgstr "Встановити оновлення" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Join our Community Forum at https://community.sunnypilot.ai and reach out to a moderator if you have issues" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Joystick Debug Mode" +msgstr "Режим зневадження джойстика" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "LOADING" +msgstr "ЗАВАНТАЖЕННЯ" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "LTE" +msgstr "LTE" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Lateral Maneuver Mode" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Longitudinal Maneuver Mode" +msgstr "Режим поздовжнього маневрування" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "MAX" +msgstr "МАКС" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Maximize your training data uploads to improve openpilot's driving models." +msgstr "Максимізуйте завантаження навчальних даних, щоб поліпшити моделі openpilot." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "N/A" +msgstr "Н/Д" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "NO" +msgstr "НЕМАЄ" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Network" +msgstr "Мережа" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "No SSH keys found for user '{}'" +msgstr "Користувач '{}' не має ключів на GitHub" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "No release notes available." +msgstr "Інформація про випуск відсутня." + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "OFFLINE" +msgstr "ОФЛАЙН" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/html_render.py +msgid "OK" +msgstr "OK" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ONLINE" +msgstr "ОНЛАЙН" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Open" +msgstr "ВІДКРИТИ" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PAIR" +msgstr "ПІДКЛЮЧИТИ" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "PANDA" +msgstr "PANDA" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PREVIEW" +msgstr "ПОКАЖИ" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "PRIME FEATURES:" +msgstr "XАРАКТЕРИСТИКИ PRIME:" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Pair Device" +msgstr "Підключити пристрій" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair device" +msgstr "Підключити пристрій" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Pair your GitHub account" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Pair your device to your comma account" +msgstr "Підключіть свій пристрій до обліковки comma connect" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer." +msgstr "Підключіть свій пристрій до comma connect (connect.comma.ai) і отримайте свою пропозицію comma prime." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Please connect to Wi-Fi to complete initial pairing" +msgstr "Будь ласка, підключіться до Wi-Fi, щоб завершити початкове сполучення." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Power Off" +msgstr "Вимкнути" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered Wi-Fi connection" +msgstr "Запобігайте завантаженню великих обсягів даних під час використання Wi-Fi-з'єднання з обмеженим трафіком" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered cellular connection" +msgstr "Запобігати великим завантаженням даних під час лімітного стільникового з'єднання" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off)" +msgstr "Попередньо перегляньте камеру, спрямовану на водія, щоб переконатися, що система моніторингу водія має добру видимість. (автомобіль повинен бути вимкнений)" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "QR Code Error" +msgstr "Помилка QR-коду" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "REMOVE" +msgstr "ВИДАЛИТИ" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "RESET" +msgstr "Скинути" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "REVIEW" +msgstr "ДИВИТИСЬ" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Re-enter the \"sunnylink\" panel to verify sponsorship status" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reboot" +msgstr "Перезавантажити" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Reboot Device" +msgstr "Перезавантажте пристрій" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Reboot and Update" +msgstr "Перезавантажити та оновити" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Driver Camera" +msgstr "Писати та вантажити відео з камери водія" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Microphone Audio" +msgstr "Запис та завантаження аудіо з мікрофона" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and store microphone audio while driving. The audio will be included in the dashcam video in comma connect." +msgstr "Записуйте та зберігайте аудіо з мікрофона під час руху. Аудіо буде включено до відео з відеореєстратора в comma connect." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Regulatory" +msgstr "Нормативні документи" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Relaxed" +msgstr "Спокійний" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote access" +msgstr "Віддалений доступ" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote snapshots" +msgstr "Віддалені знімки" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Request timed out" +msgstr "Час запиту вичерпано" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset" +msgstr "Скинути" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset Calibration" +msgstr "Скинути калібрування" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review Training Guide" +msgstr "Переглянути посібник з навчання" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review the rules, features, and limitations of sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "SELECT" +msgstr "ВИБРАТИ" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "SSH Keys" +msgstr "SSH ключі" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Scan the QR code to login to your GitHub account" +msgstr "" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Scan the QR code to visit sunnyhaibin's GitHub Sponsors page" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Scanning Wi-Fi networks..." +msgstr "Пошук мереж..." + +#: system/ui/sunnypilot/widgets/tree_dialog.py +msgid "Search" +msgstr "" + +#: system/ui/widgets/option_dialog.py +msgid "Select" +msgstr "Вибрати" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Select a branch" +msgstr "Виберіть гілку" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Select a language" +msgstr "Виберіть мову" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Serial" +msgstr "Серійний номер" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Snooze Update" +msgstr "Відкласти оновлення" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Software" +msgstr "Програма" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Standard" +msgstr "Стандарт" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "System Unresponsive" +msgstr "Система не реагує" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "TAKE CONTROL IMMEDIATELY" +msgstr "КЕРМУЙТЕ НЕГАЙНО" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "TEMP" +msgstr "ТЕМП" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Target Branch" +msgstr "Цільова гілка" + +#: system/ui/widgets/network.py +msgid "Tethering Password" +msgstr "Пароль для точки доступу" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Toggles" +msgstr "Перемикачі" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "UI Debug Mode" +msgstr "Режим налагодження інтерфейсу" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "UNINSTALL" +msgstr "ВИДАЛИТИ" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "UPDATE" +msgstr "ОНОВИТИ" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Uninstall" +msgstr "Видалити" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Unknown" +msgstr "Невідомо" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Updates are only downloaded while the car is off." +msgstr "Оновлення завантажуються лише тоді, коли автомобіль вимкнено." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Upgrade Now" +msgstr "Оновити зараз" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Upload data from the driver facing camera and help improve the driver monitoring algorithm." +msgstr "Завантажуйте дані з камери, спрямованої на водія, та допоможіть покращити алгоритм моніторингу водія." + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Use Metric System" +msgstr "Використовувати метричну систему" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "VEHICLE" +msgstr "АВТО" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "VIEW" +msgstr "ДИВИСЬ" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Waiting to start" +msgstr "Очікування початку" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Welcome to sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "When enabled, pressing the accelerator pedal will disengage sunnypilot." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Wi-Fi" +msgstr "Wi-Fi" + +#: system/ui/widgets/network.py +msgid "Wi-Fi Network Metered" +msgstr "Трафік Wi-Fi" + +#: system/ui/widgets/network.py +msgid "Wrong password" +msgstr "Невірний пароль" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms of Service in order to use sunnypilot." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms of Service to use sunnypilot. Read the latest terms at https://sunnypilot.ai/terms before continuing." +msgstr "" + +#: openpilot/selfdrive/ui/onroad/driver_camera_dialog.py +msgid "camera starting" +msgstr "запуск камери" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "checking..." +msgstr "перевіряю..." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "comma prime" +msgstr "comma prime" + +#: system/ui/widgets/network.py +msgid "default" +msgstr "замовч." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "down" +msgstr "вниз" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "downloading..." +msgstr "завантажую..." + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "failed to check for update" +msgstr "не вдалося перевірити оновлення" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "finalizing update..." +msgstr "завершую..." + +#: system/ui/widgets/network.py +msgid "for \"{}\"" +msgstr "для \"{}\"" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "km/h" +msgstr "км/год" + +#: system/ui/widgets/network.py +msgid "leave blank for automatic configuration" +msgstr "залиште порожнім для автоматичного налаштування" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "left" +msgstr "вліво" + +#: system/ui/widgets/network.py +msgid "metered" +msgstr "обмеж." + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "mph" +msgstr "миль/год" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "never" +msgstr "ніколи" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "now" +msgstr "зараз" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "right" +msgstr "вправо" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "sunnypilot Longitudinal Control (Alpha)" +msgstr "" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "sunnypilot Unavailable" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "sunnypilot longitudinal control may come in a future update." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "sunnypilot requires the device to be mounted within 4° left or right and within 5° up or 9° down." +msgstr "" + +#: system/ui/widgets/network.py +msgid "unmetered" +msgstr "необмеж." + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "up" +msgstr "вгору" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked never" +msgstr "оновлено, ніколи не перевірялось" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked {}" +msgstr "оновлено, перевірив {}" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "update available" +msgstr "доступне оновлення" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "{} ALERT" +msgid_plural "{} ALERTS" +msgstr[0] "{} СПОВІЩЕННЯ" +msgstr[1] "{} СПОВІЩЕННЯ" +msgstr[2] "{} СПОВІЩЕНЬ" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} day ago" +msgid_plural "{} days ago" +msgstr[0] "{} день тому" +msgstr[1] "{} дні тому" +msgstr[2] "{} днів тому" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} hour ago" +msgid_plural "{} hours ago" +msgstr[0] "{} година тому" +msgstr[1] "{} години тому" +msgstr[2] "{} годин тому" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} minute ago" +msgid_plural "{} minutes ago" +msgstr[0] "{} хвилина тому" +msgstr[1] "{} хвилини тому" +msgstr[2] "{} хвилин тому" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "{} segment of your driving is in the training dataset so far." +msgid_plural "{} segments of your driving is in the training dataset so far." +msgstr[0] "{} сегмент вашого водіння на даний момент містяться в тренувальному наборі даних." +msgstr[1] "{} сегменти вашого водіння на даний момент містяться в тренувальному наборі даних." +msgstr[2] "{} сегментів вашого водіння на даний момент містяться в тренувальному наборі даних." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "✓ SUBSCRIBED" +msgstr "✓ ПІДПИСАНО" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "🔥 Firehose Mode 🔥" +msgstr "🌧️ Режим зливи 🌧️" + diff --git a/openpilot/selfdrive/ui/translations/app_zh-CHS.po b/openpilot/selfdrive/ui/translations/app_zh-CHS.po new file mode 100644 index 0000000000..b01ba69392 --- /dev/null +++ b/openpilot/selfdrive/ui/translations/app_zh-CHS.po @@ -0,0 +1,873 @@ +msgid "" +msgstr "" +"Content-Type: text/plain; charset=UTF-8\n" +"Language: zh-CHS\n" +"Plural-Forms: nplurals=1; plural=0;\n" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is complete." +msgstr " 转向扭矩响应校准完成。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is {}% complete." +msgstr " 转向扭矩响应校准已完成 {}%。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Your device is pointed {:.1f}° {} and {:.1f}° {}." +msgstr " 您的设备朝向 {:.1f}° {} 与 {:.1f}° {}。" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "--" +msgstr "--" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "1 year of drive storage" +msgstr "1 年行驶数据存储" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "24/7 LTE connectivity" +msgstr "全天候 LTE 连接" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "2G" +msgstr "2G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "3G" +msgstr "3G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "5G" +msgstr "5G" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is complete." +msgstr "

转向延迟校准完成。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is {}% complete." +msgstr "

转向延迟校准已完成 {}%。" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "ADD" +msgstr "添加" + +#: system/ui/widgets/network.py +msgid "APN Setting" +msgstr "APN 设置" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Acknowledge Excessive Actuation" +msgstr "确认过度作动" + +#: system/ui/widgets/network.py +msgid "Advanced" +msgstr "高级" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Aggressive" +msgstr "激进" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Agree" +msgstr "同意" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Always-On Driver Monitoring" +msgstr "始终启用驾驶员监控" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to power off?" +msgstr "确定要关机吗?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reboot?" +msgstr "确定要重启吗?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reset calibration?" +msgstr "确定要重置校准吗?" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Are you sure you want to uninstall?" +msgstr "确定要卸载吗?" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +#: system/ui/widgets/network.py +msgid "Back" +msgstr "返回" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Become a comma prime member at connect.comma.ai" +msgstr "前往 connect.comma.ai 成为 comma prime 会员" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Bookmark connect.comma.ai to your home screen to use it like an app" +msgstr "将 connect.comma.ai 添加到主屏幕,像应用一样使用" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "CHANGE" +msgstr "更改" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "CHECK" +msgstr "检查" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "CHILL MODE ON" +msgstr "安稳模式已开启" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/network.py +msgid "CONNECT" +msgstr "连接" + +#: system/ui/widgets/network.py +msgid "CONNECTING..." +msgstr "连接中..." + +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/keyboard.py +#: system/ui/widgets/network.py +#: system/ui/widgets/option_dialog.py +msgid "Cancel" +msgstr "取消" + +#: system/ui/widgets/network.py +msgid "Cellular Metered" +msgstr "蜂窝计量" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Change Language" +msgstr "更改语言" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Changing this setting will restart sunnypilot if the car is powered on." +msgstr "" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Choose your sponsorship tier and confirm your support" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Click \"add new device\" and scan the QR code on the right" +msgstr "点击“添加新设备”,扫描右侧二维码" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Close" +msgstr "关闭" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Current Version" +msgstr "当前版本" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "DOWNLOAD" +msgstr "下载" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline" +msgstr "拒绝" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline, uninstall sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Developer" +msgstr "开发者" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Device" +msgstr "设备" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Disengage on Accelerator Pedal" +msgstr "踩下加速踏板时脱离" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Power Off" +msgstr "脱离以关机" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reboot" +msgstr "脱离以重启" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reset Calibration" +msgstr "脱离以重置校准" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Display speed in km/h instead of mph." +msgstr "以 km/h 显示速度(非 mph)。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Dongle ID" +msgstr "设备 ID" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Download" +msgstr "下载" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Driver Camera" +msgstr "车内摄像头" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Driving Personality" +msgstr "驾驶风格" + +#: system/ui/widgets/network.py +msgid "EDIT" +msgstr "编辑" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ERROR" +msgstr "错误" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ETH" +msgstr "ETH" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "EXPERIMENTAL MODE ON" +msgstr "实验模式已开启" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Early Access: Become a sunnypilot Sponsor" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable" +msgstr "启用" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable ADB" +msgstr "启用 ADB" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable Lane Departure Warnings" +msgstr "启用车道偏离警示" + +#: system/ui/widgets/network.py +msgid "Enable Roaming" +msgstr "启用漫游" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable SSH" +msgstr "启用 SSH" + +#: system/ui/widgets/network.py +msgid "Enable Tethering" +msgstr "启用网络共享" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable driver monitoring even when sunnypilot is not engaged." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable the sunnypilot longitudinal control (alpha) toggle to allow Experimental mode." +msgstr "" + +#: system/ui/widgets/network.py +msgid "Enter APN" +msgstr "输入 APN" + +#: system/ui/widgets/network.py +msgid "Enter SSID" +msgstr "输入 SSID" + +#: system/ui/widgets/network.py +msgid "Enter new tethering password" +msgstr "输入新的网络共享密码" + +#: system/ui/widgets/network.py +msgid "Enter password" +msgstr "输入密码" + +#: system/ui/sunnypilot/widgets/tree_dialog.py +msgid "Enter search query" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Enter your GitHub username" +msgstr "输入您的 GitHub 用户名" + +#: system/ui/widgets/list_view.py +msgid "Error" +msgstr "错误" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental Mode" +msgstr "实验模式" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control." +msgstr "此车型当前无法使用实验模式,因为纵向控制使用的是原厂 ACC。" + +#: system/ui/widgets/network.py +msgid "FORGETTING..." +msgstr "正在遗忘..." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Finish Setup" +msgstr "完成设置" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Firehose" +msgstr "数据洪流" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "Firehose Mode" +msgstr "Firehose 模式" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Follow the prompts to complete the pairing process" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Forget" +msgstr "忘记" + +#: system/ui/widgets/network.py +msgid "Forget Wi-Fi Network \"{}\"?" +msgstr "要忘记 Wi‑Fi 网络“{}”吗?" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "GOOD" +msgstr "良好" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Go to https://connect.comma.ai on your phone" +msgstr "在手机上前往 https://connect.comma.ai" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "HIGH" +msgstr "高" + +#: system/ui/widgets/network.py +msgid "Hidden Network" +msgstr "隐藏网络" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "INSTALL" +msgstr "安装" + +#: system/ui/widgets/network.py +msgid "IP Address" +msgstr "IP 地址" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "If sponsorship status was not updated, please contact a moderator on the community forum at https://community.sunnypilot.ai" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Install Update" +msgstr "安装更新" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Join our Community Forum at https://community.sunnypilot.ai and reach out to a moderator if you have issues" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Joystick Debug Mode" +msgstr "摇杆调试模式" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "LOADING" +msgstr "加载中" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "LTE" +msgstr "LTE" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Lateral Maneuver Mode" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Longitudinal Maneuver Mode" +msgstr "纵向操作模式" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "MAX" +msgstr "最大" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Maximize your training data uploads to improve openpilot's driving models." +msgstr "最大化上传训练数据,以改进 openpilot 的驾驶模型。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "N/A" +msgstr "无" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "NO" +msgstr "否" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Network" +msgstr "网络" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "No SSH keys found for user '{}'" +msgstr "未找到用户“{}”的 SSH 密钥" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "No release notes available." +msgstr "暂无发行说明。" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "OFFLINE" +msgstr "离线" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/html_render.py +msgid "OK" +msgstr "确定" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ONLINE" +msgstr "在线" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Open" +msgstr "打开" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PAIR" +msgstr "配对" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "PANDA" +msgstr "PANDA" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PREVIEW" +msgstr "预览" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "PRIME FEATURES:" +msgstr "PRIME 功能:" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Pair Device" +msgstr "配对设备" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair device" +msgstr "配对设备" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Pair your GitHub account" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Pair your device to your comma account" +msgstr "将设备配对到您的 comma 账号" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer." +msgstr "将设备与 comma connect(connect.comma.ai)配对,领取您的 comma prime 优惠。" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Please connect to Wi-Fi to complete initial pairing" +msgstr "请连接 Wi‑Fi 以完成初始配对" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Power Off" +msgstr "关机" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered Wi-Fi connection" +msgstr "在计量制 Wi‑Fi 连接时避免大量上传" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered cellular connection" +msgstr "在计量制蜂窝网络时避免大量上传" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off)" +msgstr "预览车内摄像头以确保驾驶员监控视野良好。(车辆必须熄火)" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "QR Code Error" +msgstr "二维码错误" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "REMOVE" +msgstr "移除" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "RESET" +msgstr "重置" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "REVIEW" +msgstr "查看" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Re-enter the \"sunnylink\" panel to verify sponsorship status" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reboot" +msgstr "重启" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Reboot Device" +msgstr "重启设备" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Reboot and Update" +msgstr "重启并更新" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Driver Camera" +msgstr "录制并上传车内摄像头" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Microphone Audio" +msgstr "录制并上传麦克风音频" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and store microphone audio while driving. The audio will be included in the dashcam video in comma connect." +msgstr "行驶时录制并保存麦克风音频。音频将包含在 comma connect 的行车记录视频中。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Regulatory" +msgstr "法规" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Relaxed" +msgstr "从容" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote access" +msgstr "远程访问" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote snapshots" +msgstr "远程快照" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Request timed out" +msgstr "请求超时" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset" +msgstr "重置" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset Calibration" +msgstr "重置校准" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review Training Guide" +msgstr "查看训练指南" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review the rules, features, and limitations of sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "SELECT" +msgstr "选择" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "SSH Keys" +msgstr "SSH 密钥" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Scan the QR code to login to your GitHub account" +msgstr "" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Scan the QR code to visit sunnyhaibin's GitHub Sponsors page" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Scanning Wi-Fi networks..." +msgstr "正在扫描 Wi‑Fi 网络…" + +#: system/ui/sunnypilot/widgets/tree_dialog.py +msgid "Search" +msgstr "" + +#: system/ui/widgets/option_dialog.py +msgid "Select" +msgstr "选择" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Select a branch" +msgstr "选择分支" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Select a language" +msgstr "选择语言" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Serial" +msgstr "序列号" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Snooze Update" +msgstr "延后更新" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Software" +msgstr "软件" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Standard" +msgstr "标准" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "System Unresponsive" +msgstr "系统无响应" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "TAKE CONTROL IMMEDIATELY" +msgstr "请立即接管控制" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "TEMP" +msgstr "温度" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Target Branch" +msgstr "目标分支" + +#: system/ui/widgets/network.py +msgid "Tethering Password" +msgstr "网络共享密码" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Toggles" +msgstr "切换" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "UI Debug Mode" +msgstr "界面调试模式" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "UNINSTALL" +msgstr "卸载" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "UPDATE" +msgstr "更新" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Uninstall" +msgstr "卸载" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Unknown" +msgstr "未知" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Updates are only downloaded while the car is off." +msgstr "仅在车辆熄火时下载更新。" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Upgrade Now" +msgstr "立即升级" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Upload data from the driver facing camera and help improve the driver monitoring algorithm." +msgstr "上传车内摄像头数据,帮助改进驾驶员监控算法。" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Use Metric System" +msgstr "使用公制" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "VEHICLE" +msgstr "车辆" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "VIEW" +msgstr "查看" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Waiting to start" +msgstr "等待开始" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Welcome to sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "When enabled, pressing the accelerator pedal will disengage sunnypilot." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Wi-Fi" +msgstr "Wi‑Fi" + +#: system/ui/widgets/network.py +msgid "Wi-Fi Network Metered" +msgstr "Wi‑Fi 计量网络" + +#: system/ui/widgets/network.py +msgid "Wrong password" +msgstr "密码错误" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms of Service in order to use sunnypilot." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms of Service to use sunnypilot. Read the latest terms at https://sunnypilot.ai/terms before continuing." +msgstr "" + +#: openpilot/selfdrive/ui/onroad/driver_camera_dialog.py +msgid "camera starting" +msgstr "相机启动中" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "checking..." +msgstr "检查中..." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "comma prime" +msgstr "comma prime" + +#: system/ui/widgets/network.py +msgid "default" +msgstr "默认" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "down" +msgstr "下" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "downloading..." +msgstr "下载中..." + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "failed to check for update" +msgstr "检查更新失败" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "finalizing update..." +msgstr "正在完成更新..." + +#: system/ui/widgets/network.py +msgid "for \"{}\"" +msgstr "用于“{}”" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "km/h" +msgstr "km/h" + +#: system/ui/widgets/network.py +msgid "leave blank for automatic configuration" +msgstr "留空以自动配置" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "left" +msgstr "左" + +#: system/ui/widgets/network.py +msgid "metered" +msgstr "计量" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "mph" +msgstr "mph" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "never" +msgstr "从不" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "now" +msgstr "现在" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "right" +msgstr "右" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "sunnypilot Longitudinal Control (Alpha)" +msgstr "" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "sunnypilot Unavailable" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "sunnypilot longitudinal control may come in a future update." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "sunnypilot requires the device to be mounted within 4° left or right and within 5° up or 9° down." +msgstr "" + +#: system/ui/widgets/network.py +msgid "unmetered" +msgstr "不限流量" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "up" +msgstr "上" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked never" +msgstr "已是最新,最后检查:从未" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked {}" +msgstr "已是最新,最后检查:{}" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "update available" +msgstr "有可用更新" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "{} ALERT" +msgid_plural "{} ALERTS" +msgstr[0] "{} 条警报" +msgstr[1] "{} 条警报" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} day ago" +msgid_plural "{} days ago" +msgstr[0] "{} 天前" +msgstr[1] "{} 天前" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} hour ago" +msgid_plural "{} hours ago" +msgstr[0] "{} 小时前" +msgstr[1] "{} 小时前" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} minute ago" +msgid_plural "{} minutes ago" +msgstr[0] "{} 分钟前" +msgstr[1] "{} 分钟前" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "{} segment of your driving is in the training dataset so far." +msgid_plural "{} segments of your driving is in the training dataset so far." +msgstr[0] "目前已有 {} 个您的驾驶片段被纳入训练数据集。" +msgstr[1] "目前已有 {} 个您的驾驶片段被纳入训练数据集。" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "✓ SUBSCRIBED" +msgstr "✓ 已订阅" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "🔥 Firehose Mode 🔥" +msgstr "🔥 Firehose 模式 🔥" + diff --git a/openpilot/selfdrive/ui/translations/app_zh-CHT.po b/openpilot/selfdrive/ui/translations/app_zh-CHT.po new file mode 100644 index 0000000000..3cdcfe4e20 --- /dev/null +++ b/openpilot/selfdrive/ui/translations/app_zh-CHT.po @@ -0,0 +1,873 @@ +msgid "" +msgstr "" +"Content-Type: text/plain; charset=UTF-8\n" +"Language: zh-CHT\n" +"Plural-Forms: nplurals=1; plural=0;\n" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is complete." +msgstr " 轉向扭矩回應校正完成。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Steering torque response calibration is {}% complete." +msgstr " 轉向扭矩回應校正已完成 {}%。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid " Your device is pointed {:.1f}° {} and {:.1f}° {}." +msgstr " 您的裝置朝向 {:.1f}° {} 與 {:.1f}° {}。" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "--" +msgstr "--" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "1 year of drive storage" +msgstr "1 年行駛資料儲存" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "24/7 LTE connectivity" +msgstr "全年無休 LTE 連線" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "2G" +msgstr "2G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "3G" +msgstr "3G" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "5G" +msgstr "5G" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is complete." +msgstr "

轉向延遲校正完成。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "

Steering lag calibration is {}% complete." +msgstr "

轉向延遲校正已完成 {}%。" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "ADD" +msgstr "新增" + +#: system/ui/widgets/network.py +msgid "APN Setting" +msgstr "APN 設定" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Acknowledge Excessive Actuation" +msgstr "確認過度作動" + +#: system/ui/widgets/network.py +msgid "Advanced" +msgstr "進階" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Aggressive" +msgstr "積極" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Agree" +msgstr "同意" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Always-On Driver Monitoring" +msgstr "持續啟用駕駛監控" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to power off?" +msgstr "確定要關機嗎?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reboot?" +msgstr "確定要重新啟動嗎?" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Are you sure you want to reset calibration?" +msgstr "確定要重設校正嗎?" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Are you sure you want to uninstall?" +msgstr "確定要解除安裝嗎?" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +#: system/ui/widgets/network.py +msgid "Back" +msgstr "返回" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Become a comma prime member at connect.comma.ai" +msgstr "前往 connect.comma.ai 成為 comma prime 會員" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Bookmark connect.comma.ai to your home screen to use it like an app" +msgstr "將 connect.comma.ai 加到主畫面,像 App 一樣使用" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "CHANGE" +msgstr "變更" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "CHECK" +msgstr "檢查" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "CHILL MODE ON" +msgstr "安穩模式已開啟" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/network.py +msgid "CONNECT" +msgstr "連線" + +#: system/ui/widgets/network.py +msgid "CONNECTING..." +msgstr "連線中..." + +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/keyboard.py +#: system/ui/widgets/network.py +#: system/ui/widgets/option_dialog.py +msgid "Cancel" +msgstr "取消" + +#: system/ui/widgets/network.py +msgid "Cellular Metered" +msgstr "行動網路計量" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Change Language" +msgstr "變更語言" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Changing this setting will restart sunnypilot if the car is powered on." +msgstr "" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Choose your sponsorship tier and confirm your support" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Click \"add new device\" and scan the QR code on the right" +msgstr "點選「新增裝置」,掃描右側 QR 碼" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Close" +msgstr "關閉" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Current Version" +msgstr "目前版本" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "DOWNLOAD" +msgstr "下載" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline" +msgstr "拒絕" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Decline, uninstall sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Developer" +msgstr "開發人員" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Device" +msgstr "裝置" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Disengage on Accelerator Pedal" +msgstr "踩下加速踏板時脫離" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Power Off" +msgstr "脫離以關機" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reboot" +msgstr "脫離以重新啟動" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Disengage to Reset Calibration" +msgstr "脫離以重設校正" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Display speed in km/h instead of mph." +msgstr "以 km/h 顯示速度(非 mph)。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Dongle ID" +msgstr "裝置 ID" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Download" +msgstr "下載" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Driver Camera" +msgstr "車內鏡頭" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Driving Personality" +msgstr "駕駛風格" + +#: system/ui/widgets/network.py +msgid "EDIT" +msgstr "編輯" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ERROR" +msgstr "錯誤" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ETH" +msgstr "ETH" + +#: openpilot/selfdrive/ui/widgets/exp_mode_button.py +msgid "EXPERIMENTAL MODE ON" +msgstr "實驗模式已開啟" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Early Access: Become a sunnypilot Sponsor" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable" +msgstr "啟用" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable ADB" +msgstr "啟用 ADB" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable Lane Departure Warnings" +msgstr "啟用偏離車道警示" + +#: system/ui/widgets/network.py +msgid "Enable Roaming" +msgstr "啟用漫遊" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Enable SSH" +msgstr "啟用 SSH" + +#: system/ui/widgets/network.py +msgid "Enable Tethering" +msgstr "啟用網路共享" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable driver monitoring even when sunnypilot is not engaged." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Enable the sunnypilot longitudinal control (alpha) toggle to allow Experimental mode." +msgstr "" + +#: system/ui/widgets/network.py +msgid "Enter APN" +msgstr "輸入 APN" + +#: system/ui/widgets/network.py +msgid "Enter SSID" +msgstr "輸入 SSID" + +#: system/ui/widgets/network.py +msgid "Enter new tethering password" +msgstr "輸入新的網路共享密碼" + +#: system/ui/widgets/network.py +msgid "Enter password" +msgstr "輸入密碼" + +#: system/ui/sunnypilot/widgets/tree_dialog.py +msgid "Enter search query" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Enter your GitHub username" +msgstr "輸入您的 GitHub 使用者名稱" + +#: system/ui/widgets/list_view.py +msgid "Error" +msgstr "錯誤" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental Mode" +msgstr "實驗模式" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control." +msgstr "此車款目前無法使用實驗模式,因為縱向控制使用的是原廠 ACC。" + +#: system/ui/widgets/network.py +msgid "FORGETTING..." +msgstr "正在遺忘..." + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Finish Setup" +msgstr "完成設定" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Firehose" +msgstr "資料洪流" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "Firehose Mode" +msgstr "Firehose 模式" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Follow the prompts to complete the pairing process" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Forget" +msgstr "忘記" + +#: system/ui/widgets/network.py +msgid "Forget Wi-Fi Network \"{}\"?" +msgstr "要忘記 Wi‑Fi 網路「{}」嗎?" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "GOOD" +msgstr "良好" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Go to https://connect.comma.ai on your phone" +msgstr "在手機上前往 https://connect.comma.ai" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "HIGH" +msgstr "高" + +#: system/ui/widgets/network.py +msgid "Hidden Network" +msgstr "隱藏網路" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "INSTALL" +msgstr "安裝" + +#: system/ui/widgets/network.py +msgid "IP Address" +msgstr "IP 位址" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "If sponsorship status was not updated, please contact a moderator on the community forum at https://community.sunnypilot.ai" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Install Update" +msgstr "安裝更新" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Join our Community Forum at https://community.sunnypilot.ai and reach out to a moderator if you have issues" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Joystick Debug Mode" +msgstr "搖桿除錯模式" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "LOADING" +msgstr "載入中" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "LTE" +msgstr "LTE" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Lateral Maneuver Mode" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "Longitudinal Maneuver Mode" +msgstr "縱向操作模式" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "MAX" +msgstr "最大" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Maximize your training data uploads to improve openpilot's driving models." +msgstr "最大化上傳訓練資料,以改進 openpilot 的駕駛模型。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "N/A" +msgstr "無" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "NO" +msgstr "否" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Network" +msgstr "網路" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "No SSH keys found for user '{}'" +msgstr "找不到使用者 '{}' 的 SSH 金鑰" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "No release notes available." +msgstr "無可用發行說明。" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "OFFLINE" +msgstr "離線" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +#: system/ui/widgets/confirm_dialog.py +#: system/ui/widgets/html_render.py +msgid "OK" +msgstr "確定" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "ONLINE" +msgstr "線上" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Open" +msgstr "開啟" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PAIR" +msgstr "配對" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "PANDA" +msgstr "PANDA" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "PREVIEW" +msgstr "預覽" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "PRIME FEATURES:" +msgstr "PRIME 功能:" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Pair Device" +msgstr "配對裝置" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair device" +msgstr "配對裝置" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Pair your GitHub account" +msgstr "" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "Pair your device to your comma account" +msgstr "將裝置配對至您的 comma 帳號" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer." +msgstr "將裝置與 comma connect(connect.comma.ai)配對,領取您的 comma prime 優惠。" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "Please connect to Wi-Fi to complete initial pairing" +msgstr "請連線至 Wi‑Fi 以完成初始化配對" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Power Off" +msgstr "關機" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered Wi-Fi connection" +msgstr "在計量制 Wi‑Fi 連線時避免大量上傳" + +#: system/ui/widgets/network.py +msgid "Prevent large data uploads when on a metered cellular connection" +msgstr "在計量制行動網路時避免大量上傳" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off)" +msgstr "預覽車內鏡頭以確保駕駛監控視野良好。(車輛須熄火)" + +#: openpilot/selfdrive/ui/widgets/pairing_dialog.py +msgid "QR Code Error" +msgstr "QR 碼錯誤" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "REMOVE" +msgstr "移除" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "RESET" +msgstr "重設" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "REVIEW" +msgstr "檢視" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Re-enter the \"sunnylink\" panel to verify sponsorship status" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reboot" +msgstr "重新啟動" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Reboot Device" +msgstr "重新啟動裝置" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Reboot and Update" +msgstr "重新啟動並更新" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Driver Camera" +msgstr "錄製並上傳車內鏡頭" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and Upload Microphone Audio" +msgstr "錄製並上傳麥克風音訊" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Record and store microphone audio while driving. The audio will be included in the dashcam video in comma connect." +msgstr "行車時錄製並儲存麥克風音訊。音訊將包含在 comma connect 的行車紀錄影片中。" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Regulatory" +msgstr "法規" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Relaxed" +msgstr "從容" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote access" +msgstr "遠端存取" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Remote snapshots" +msgstr "遠端擷圖" + +#: openpilot/selfdrive/ui/widgets/ssh_key.py +msgid "Request timed out" +msgstr "要求逾時" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset" +msgstr "重設" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Reset Calibration" +msgstr "重設校正" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review Training Guide" +msgstr "檢視訓練指南" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Review the rules, features, and limitations of sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "SELECT" +msgstr "選取" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "SSH Keys" +msgstr "SSH 金鑰" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Scan the QR code to login to your GitHub account" +msgstr "" + +#: system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py +msgid "Scan the QR code to visit sunnyhaibin's GitHub Sponsors page" +msgstr "" + +#: system/ui/widgets/network.py +msgid "Scanning Wi-Fi networks..." +msgstr "正在掃描 Wi‑Fi 網路…" + +#: system/ui/sunnypilot/widgets/tree_dialog.py +msgid "Search" +msgstr "" + +#: system/ui/widgets/option_dialog.py +msgid "Select" +msgstr "選取" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Select a branch" +msgstr "選取分支" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Select a language" +msgstr "選取語言" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "Serial" +msgstr "序號" + +#: openpilot/selfdrive/ui/widgets/offroad_alerts.py +msgid "Snooze Update" +msgstr "延後更新" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Software" +msgstr "軟體" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Standard" +msgstr "標準" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "System Unresponsive" +msgstr "系統無回應" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "TAKE CONTROL IMMEDIATELY" +msgstr "請立刻接手控制" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "TEMP" +msgstr "溫度" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Target Branch" +msgstr "目標分支" + +#: system/ui/widgets/network.py +msgid "Tethering Password" +msgstr "網路共享密碼" + +#: openpilot/selfdrive/ui/layouts/settings/settings.py +msgid "Toggles" +msgstr "切換" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "UI Debug Mode" +msgstr "介面除錯模式" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "UNINSTALL" +msgstr "解除安裝" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "UPDATE" +msgstr "更新" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Uninstall" +msgstr "解除安裝" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Unknown" +msgstr "未知" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "Updates are only downloaded while the car is off." +msgstr "僅在車輛熄火時下載更新。" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "Upgrade Now" +msgstr "立即升級" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Upload data from the driver facing camera and help improve the driver monitoring algorithm." +msgstr "上傳車內鏡頭資料,協助改善駕駛監控演算法。" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "Use Metric System" +msgstr "使用公制" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "VEHICLE" +msgstr "車輛" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "VIEW" +msgstr "檢視" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "Waiting to start" +msgstr "等待開始" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "Welcome to sunnypilot" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "When enabled, pressing the accelerator pedal will disengage sunnypilot." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/sidebar.py +msgid "Wi-Fi" +msgstr "Wi‑Fi" + +#: system/ui/widgets/network.py +msgid "Wi-Fi Network Metered" +msgstr "Wi‑Fi 計量網路" + +#: system/ui/widgets/network.py +msgid "Wrong password" +msgstr "密碼錯誤" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms of Service in order to use sunnypilot." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/onboarding.py +msgid "You must accept the Terms of Service to use sunnypilot. Read the latest terms at https://sunnypilot.ai/terms before continuing." +msgstr "" + +#: openpilot/selfdrive/ui/onroad/driver_camera_dialog.py +msgid "camera starting" +msgstr "相機啟動中" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "checking..." +msgstr "檢查中..." + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "comma prime" +msgstr "comma prime" + +#: system/ui/widgets/network.py +msgid "default" +msgstr "預設" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "down" +msgstr "下" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "downloading..." +msgstr "下載中..." + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "failed to check for update" +msgstr "檢查更新失敗" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "finalizing update..." +msgstr "正在完成更新..." + +#: system/ui/widgets/network.py +msgid "for \"{}\"" +msgstr "適用於「{}」" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "km/h" +msgstr "km/h" + +#: system/ui/widgets/network.py +msgid "leave blank for automatic configuration" +msgstr "留空以自動設定" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "left" +msgstr "左" + +#: system/ui/widgets/network.py +msgid "metered" +msgstr "計量" + +#: openpilot/selfdrive/ui/onroad/hud_renderer.py +msgid "mph" +msgstr "mph" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "never" +msgstr "從不" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "now" +msgstr "現在" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "right" +msgstr "右" + +#: openpilot/selfdrive/ui/layouts/settings/developer.py +msgid "sunnypilot Longitudinal Control (Alpha)" +msgstr "" + +#: openpilot/selfdrive/ui/onroad/alert_renderer.py +msgid "sunnypilot Unavailable" +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/toggles.py +msgid "sunnypilot longitudinal control may come in a future update." +msgstr "" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "sunnypilot requires the device to be mounted within 4° left or right and within 5° up or 9° down." +msgstr "" + +#: system/ui/widgets/network.py +msgid "unmetered" +msgstr "不限流量" + +#: openpilot/selfdrive/ui/layouts/settings/device.py +msgid "up" +msgstr "上" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked never" +msgstr "已為最新,最後檢查:從未" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "up to date, last checked {}" +msgstr "已為最新,最後檢查:{}" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "update available" +msgstr "有可用更新" + +#: openpilot/selfdrive/ui/layouts/home.py +msgid "{} ALERT" +msgid_plural "{} ALERTS" +msgstr[0] "{} 則警示" +msgstr[1] "{} 則警示" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} day ago" +msgid_plural "{} days ago" +msgstr[0] "{} 天前" +msgstr[1] "{} 天前" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} hour ago" +msgid_plural "{} hours ago" +msgstr[0] "{} 小時前" +msgstr[1] "{} 小時前" + +#: openpilot/selfdrive/ui/layouts/settings/software.py +msgid "{} minute ago" +msgid_plural "{} minutes ago" +msgstr[0] "{} 分鐘前" +msgstr[1] "{} 分鐘前" + +#: openpilot/selfdrive/ui/layouts/settings/firehose.py +msgid "{} segment of your driving is in the training dataset so far." +msgid_plural "{} segments of your driving is in the training dataset so far." +msgstr[0] "目前已有 {} 個您的駕駛片段納入訓練資料集。" +msgstr[1] "目前已有 {} 個您的駕駛片段納入訓練資料集。" + +#: openpilot/selfdrive/ui/widgets/prime.py +msgid "✓ SUBSCRIBED" +msgstr "✓ 已訂閱" + +#: openpilot/selfdrive/ui/widgets/setup.py +msgid "🔥 Firehose Mode 🔥" +msgstr "🔥 Firehose 模式 🔥" + diff --git a/openpilot/selfdrive/ui/translations/auto_translate.sh b/openpilot/selfdrive/ui/translations/auto_translate.sh new file mode 100755 index 0000000000..7238426c75 --- /dev/null +++ b/openpilot/selfdrive/ui/translations/auto_translate.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +set -euo pipefail + +DIR="$(cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd)" +ROOT="$DIR/../../../" + +cd $DIR +./update_translations.py + +command -v codex >/dev/null || { + echo "Install codex CLI to continue:" + echo "-> https://developers.openai.com/codex/cli" + echo + exit 1 +} + +codex exec --cd "$ROOT" -c 'model_reasoning_effort="low"' --dangerously-bypass-approvals-and-sandbox "$(cat < bool: + return bool(self.msgid_plural) + + +# ──── PO file parsing ──── + +def _parse_quoted(s: str) -> str: + """Parse a PO-format quoted string, handling escape sequences.""" + s = s.strip() + if not (s.startswith('"') and s.endswith('"')): + raise ValueError(f"Expected quoted string: {s!r}") + s = s[1:-1] + result = [] + i = 0 + while i < len(s): + if s[i] == '\\' and i + 1 < len(s): + c = s[i + 1] + if c == 'n': + result.append('\n') + elif c == 't': + result.append('\t') + elif c == '"': + result.append('"') + elif c == '\\': + result.append('\\') + else: + result.append(s[i:i + 2]) + i += 2 + else: + result.append(s[i]) + i += 1 + return ''.join(result) + + +def parse_po(path: str | Path) -> tuple[POEntry | None, list[POEntry]]: + """Parse a .po/.pot file. Returns (header_entry, entries).""" + with open(path, encoding='utf-8') as f: + lines = f.readlines() + + entries: list[POEntry] = [] + header: POEntry | None = None + cur: POEntry | None = None + cur_field: str | None = None + plural_idx = 0 + + def finish(entry: POEntry | None): + nonlocal header + if entry is None: + return + if entry.msgid == "" and entry.msgstr: + header = entry + elif entry.msgid != "" or entry.is_plural: + entries.append(entry) + + for raw in lines: + line = raw.rstrip('\n') + stripped = line.strip() + + if not stripped: + finish(cur) + cur = None + cur_field = None + continue + + # Skip obsolete entries + if stripped.startswith('#~'): + continue + + if stripped.startswith('#'): + if cur is None: + cur = POEntry() + if stripped.startswith('#:'): + cur.source_refs.append(stripped[2:].strip()) + elif stripped.startswith('#,'): + cur.flags.extend(f.strip() for f in stripped[2:].split(',') if f.strip()) + else: + cur.comments.append(line) + continue + + if stripped.startswith('msgid_plural '): + if cur is None: + cur = POEntry() + cur.msgid_plural = _parse_quoted(stripped[len('msgid_plural '):]) + cur_field = 'msgid_plural' + continue + + if stripped.startswith('msgid '): + if cur is None: + cur = POEntry() + cur.msgid = _parse_quoted(stripped[len('msgid '):]) + cur_field = 'msgid' + continue + + m = re.match(r'msgstr\[(\d+)]\s+(.*)', stripped) + if m: + plural_idx = int(m.group(1)) + cur.msgstr_plural[plural_idx] = _parse_quoted(m.group(2)) + cur_field = 'msgstr_plural' + continue + + if stripped.startswith('msgstr '): + if cur is None: + cur = POEntry() + cur.msgstr = _parse_quoted(stripped[len('msgstr '):]) + cur_field = 'msgstr' + continue + + if stripped.startswith('"'): + val = _parse_quoted(stripped) + if cur_field == 'msgid': + cur.msgid += val + elif cur_field == 'msgid_plural': + cur.msgid_plural += val + elif cur_field == 'msgstr': + cur.msgstr += val + elif cur_field == 'msgstr_plural': + cur.msgstr_plural[plural_idx] += val + + finish(cur) + return header, entries + + +# ──── PO file writing ──── + +def _quote(s: str) -> str: + """Quote a string for .po file output.""" + s = s.replace('\\', '\\\\').replace('"', '\\"').replace('\t', '\\t') + if '\n' in s and s != '\n': + parts = s.split('\n') + lines = ['""'] + for i, part in enumerate(parts): + text = part + ('\\n' if i < len(parts) - 1 else '') + if text: + lines.append(f'"{text}"') + return '\n'.join(lines) + return f'"{s}"'.replace('\n', '\\n') + + +def write_po(path: str | Path, header: POEntry | None, entries: list[POEntry]) -> None: + """Write a .po/.pot file.""" + with open(path, 'w', encoding='utf-8') as f: + if header: + for c in header.comments: + f.write(c + '\n') + f.write(f'msgid {_quote("")}\n') + f.write(f'msgstr {_quote(header.msgstr)}\n\n') + + for entry in entries: + for c in entry.comments: + f.write(c + '\n') + # Keep file-level context for translators, but drop line numbers to + # avoid churning PO diffs on unrelated code edits. + source_files = sorted({ref.rsplit(':', 1)[0] for ref in entry.source_refs}) + for ref in source_files: + f.write(f'#: {ref}\n') + # Runtime loading ignores gettext flags; omit them to reduce noise. + f.write(f'msgid {_quote(entry.msgid)}\n') + if entry.is_plural: + f.write(f'msgid_plural {_quote(entry.msgid_plural)}\n') + for idx in sorted(entry.msgstr_plural): + f.write(f'msgstr[{idx}] {_quote(entry.msgstr_plural[idx])}\n') + else: + f.write(f'msgstr {_quote(entry.msgstr)}\n') + f.write('\n') + + +# ──── String extraction (replaces xgettext) ──── + +def extract_strings(files: list[str], basedir: str) -> list[POEntry]: + """Extract tr/trn/tr_noop calls from Python source files.""" + seen: dict[str, POEntry] = {} + + for filepath in files: + full = os.path.join(basedir, filepath) + with open(full, encoding='utf-8') as f: + source = f.read() + try: + tree = ast.parse(source, filename=filepath) + except SyntaxError: + continue + + for node in ast.walk(tree): + if not isinstance(node, ast.Call): + continue + + func = node.func + if isinstance(func, ast.Name): + name = func.id + elif isinstance(func, ast.Attribute): + name = func.attr + else: + continue + + if name not in ('tr', 'trn', 'tr_noop'): + continue + + ref = f'{filepath}:{node.lineno}' + is_flagged = name in ('tr', 'trn') + + if name in ('tr', 'tr_noop'): + if not node.args or not isinstance(node.args[0], ast.Constant) or not isinstance(node.args[0].value, str): + continue + msgid = node.args[0].value + if msgid in seen: + if ref not in seen[msgid].source_refs: + seen[msgid].source_refs.append(ref) + else: + flags = ['python-format'] if is_flagged else [] + seen[msgid] = POEntry(msgid=msgid, source_refs=[ref], flags=flags) + + elif name == 'trn': + if len(node.args) < 2: + continue + a1, a2 = node.args[0], node.args[1] + if not (isinstance(a1, ast.Constant) and isinstance(a1.value, str)): + continue + if not (isinstance(a2, ast.Constant) and isinstance(a2.value, str)): + continue + msgid, msgid_plural = a1.value, a2.value + if msgid in seen: + if ref not in seen[msgid].source_refs: + seen[msgid].source_refs.append(ref) + else: + flags = ['python-format'] if is_flagged else [] + seen[msgid] = POEntry( + msgid=msgid, msgid_plural=msgid_plural, + source_refs=[ref], flags=flags, + msgstr_plural={0: '', 1: ''}, + ) + + return list(seen.values()) + + +# ──── POT generation ──── + +def _build_pot_header() -> POEntry: + return POEntry( + msgstr='Content-Type: text/plain; charset=UTF-8\n', + ) + + +def _build_po_header(language: str) -> POEntry: + plural_forms = PLURAL_FORMS.get(language, 'nplurals=2; plural=(n != 1);') + return POEntry( + msgstr='Content-Type: text/plain; charset=UTF-8\n' + + f'Language: {language}\n' + + f'Plural-Forms: {plural_forms}\n', + ) + + +def generate_pot(entries: list[POEntry], pot_path: str | Path) -> None: + """Generate a .pot template file from extracted entries.""" + write_po(pot_path, _build_pot_header(), entries) + + +# ──── PO init (replaces msginit) ──── + +PLURAL_FORMS: dict[str, str] = { + 'en': 'nplurals=2; plural=(n != 1);', + 'de': 'nplurals=2; plural=(n != 1);', + 'fr': 'nplurals=2; plural=(n > 1);', + 'es': 'nplurals=2; plural=(n != 1);', + 'pt-BR': 'nplurals=2; plural=(n > 1);', + 'tr': 'nplurals=2; plural=(n != 1);', + 'uk': 'nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<12 || n%100>14) ? 1 : 2);', + 'th': 'nplurals=1; plural=0;', + 'zh-CHT': 'nplurals=1; plural=0;', + 'zh-CHS': 'nplurals=1; plural=0;', + 'ko': 'nplurals=1; plural=0;', + 'ja': 'nplurals=1; plural=0;', +} + + +def init_po(pot_path: str | Path, po_path: str | Path, language: str) -> None: + """Create a new .po file from a .pot template (replaces msginit).""" + _, entries = parse_po(pot_path) + plural_forms = PLURAL_FORMS.get(language, 'nplurals=2; plural=(n != 1);') + + nplurals = int(re.search(r'nplurals=(\d+)', plural_forms).group(1)) + for e in entries: + if e.is_plural: + e.msgstr_plural = dict.fromkeys(range(nplurals), '') + + write_po(po_path, _build_po_header(language), entries) + + +# ──── PO merge (replaces msgmerge) ──── + +def merge_po(po_path: str | Path, pot_path: str | Path) -> None: + """Update a .po file with entries from a .pot template (replaces msgmerge --update).""" + _, po_entries = parse_po(po_path) + _, pot_entries = parse_po(pot_path) + language = Path(po_path).stem.removeprefix("app_") + + existing = {e.msgid: e for e in po_entries} + merged = [] + + for pot_e in pot_entries: + if pot_e.msgid in existing: + old = existing[pot_e.msgid] + old.source_refs = pot_e.source_refs + old.flags = pot_e.flags + old.comments = pot_e.comments + if pot_e.is_plural: + old.msgid_plural = pot_e.msgid_plural + merged.append(old) + else: + merged.append(pot_e) + + merged.sort(key=lambda e: e.msgid) + write_po(po_path, _build_po_header(language), merged) diff --git a/openpilot/selfdrive/ui/translations/update_translations.py b/openpilot/selfdrive/ui/translations/update_translations.py new file mode 100755 index 0000000000..9b0d63ee12 --- /dev/null +++ b/openpilot/selfdrive/ui/translations/update_translations.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python3 +from itertools import chain +import os +from openpilot.common.basedir import BASEDIR +from openpilot.system.ui.lib.multilang import SYSTEM_UI_DIR, UI_DIR, TRANSLATIONS_DIR, multilang +from openpilot.selfdrive.ui.translations.potools import extract_strings, generate_pot, merge_po, init_po + +LANGUAGES_FILE = os.path.join(str(TRANSLATIONS_DIR), "languages.json") +POT_FILE = os.path.join(str(TRANSLATIONS_DIR), "app.pot") + + +def update_translations(): + files = [] + for root, _, filenames in chain(os.walk(SYSTEM_UI_DIR), + os.walk(os.path.join(str(UI_DIR), "widgets")), + os.walk(os.path.join(str(UI_DIR), "layouts")), + os.walk(os.path.join(str(UI_DIR), "onroad"))): + for filename in filenames: + if filename.endswith(".py"): + files.append(os.path.relpath(os.path.join(root, filename), BASEDIR)) + + # Extract translatable strings and generate .pot template + entries = extract_strings(files, BASEDIR) + generate_pot(entries, POT_FILE) + + # Generate/update translation files for each language + for name in multilang.languages.values(): + po_file = os.path.join(str(TRANSLATIONS_DIR), f"app_{name}.po") + if os.path.exists(po_file): + merge_po(po_file, POT_FILE) + else: + init_po(POT_FILE, po_file, name) + + +if __name__ == "__main__": + update_translations() diff --git a/openpilot/selfdrive/ui/ui.py b/openpilot/selfdrive/ui/ui.py new file mode 100755 index 0000000000..ff2bc7d3ce --- /dev/null +++ b/openpilot/selfdrive/ui/ui.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python3 +import os +import time + +from openpilot.cereal import messaging +from openpilot.common.hardware import TICI +from openpilot.common.realtime import Priority, config_realtime_process, set_core_affinity +from openpilot.system.ui.lib.application import gui_app +from openpilot.selfdrive.ui.layouts.main import MainLayout +from openpilot.selfdrive.ui.mici.layouts.main import MiciMainLayout +from openpilot.selfdrive.ui.ui_state import ui_state + +BIG_UI = gui_app.big_ui() + + +def main(): + cores = {5, } + # above plannerd and radard + config_realtime_process(0, Priority.CTRL_HIGH) + + gui_app.init_window("UI") + if BIG_UI: + MainLayout() + else: + MiciMainLayout() + + pm = messaging.PubMaster(['uiDebug']) + for should_render, frame_time, cpu_time in gui_app.render(): + extra_start = time.monotonic() + ui_state.update() + + if should_render: + # reaffine after power save offlines our core + if TICI and os.sched_getaffinity(0) != cores: + try: + set_core_affinity(list(cores)) + except OSError: + pass + + extra_cpu = time.monotonic() - extra_start + msg = messaging.new_message('uiDebug') + msg.uiDebug.cpuTimeMillis = (cpu_time + extra_cpu) * 1000 + msg.uiDebug.frameTimeMillis = frame_time * 1000 + pm.send('uiDebug', msg) + + +if __name__ == "__main__": + main() diff --git a/openpilot/selfdrive/ui/ui_state.py b/openpilot/selfdrive/ui/ui_state.py new file mode 100644 index 0000000000..59742edfed --- /dev/null +++ b/openpilot/selfdrive/ui/ui_state.py @@ -0,0 +1,351 @@ +import numpy as np +import time +import threading +from collections.abc import Callable +from enum import Enum +from openpilot.cereal import messaging, log +from opendbc.car.structs import car +from openpilot.common.filter_simple import FirstOrderFilter +from openpilot.common.params import Params +from openpilot.common.realtime import drop_realtime +from openpilot.common.swaglog import cloudlog +from openpilot.selfdrive.ui.lib.prime_state import PrimeState +from openpilot.system.ui.lib.application import gui_app +from openpilot.common.hardware import HARDWARE, PC + +from openpilot.selfdrive.ui.sunnypilot.ui_state import UIStateSP, DeviceSP + +BACKLIGHT_OFFROAD = 65 if HARDWARE.get_device_type() == "mici" else 50 +PARAM_UPDATE_TIME = 1 / 5.0 + + +class UIStatus(Enum): + DISENGAGED = "disengaged" + ENGAGED = "engaged" + OVERRIDE = "override" + LAT_ONLY = "lat_only" + LONG_ONLY = "long_only" + + +class UIState(UIStateSP): + _instance: 'UIState | None' = None + + def __new__(cls): + if cls._instance is None: + cls._instance = super().__new__(cls) + cls._instance._initialize() + return cls._instance + + def _initialize(self): + UIStateSP.__init__(self) + self.params = Params() + self.sm = messaging.SubMaster( + [ + "modelV2", + "controlsState", + "onroadEvents", + "liveCalibration", + "radarState", + "deviceState", + "pandaStates", + "carParams", + "driverMonitoringState", + "carState", + "driverStateV2", + "roadCameraState", + "wideRoadCameraState", + "managerState", + "selfdriveState", + "longitudinalPlan", + "gpsLocationExternal", + "carOutput", + "carControl", + "liveParameters", + "testJoystick", + "rawAudioData", + ] + self.sm_services_ext + ) + + self.prime_state = PrimeState() + + # UI Status tracking + self.status: UIStatus = UIStatus.DISENGAGED + self.started_frame: int = 0 + self.started_time: float = 0.0 + self._engaged_prev: bool = False + self._started_prev: bool = False + + # Core state variables + self.is_metric: bool = self.params.get_bool("IsMetric") + self.is_release = False # self.params.get_bool("IsReleaseBranch") + self.always_on_dm: bool = self.params.get_bool("AlwaysOnDM") + self.experimental_mode: bool = self.params.get_bool("ExperimentalMode") + self.usbgpu: bool = self.params.get_bool("UsbGpuPresent") + self.usbgpu_compiled: bool = self.params.get_bool("UsbGpuCompiled") + self.started: bool = False + self.ignition: bool = False + self.recording_audio: bool = False + self.panda_type: log.PandaState.PandaType = log.PandaState.PandaType.unknown + self.personality: log.LongitudinalPersonality = log.LongitudinalPersonality.standard + self.has_longitudinal_control: bool = False + self.is_body: bool | None = None + self.CP: car.CarParams | None = None + self.light_sensor: float = -1.0 + + self._params_thread: threading.Thread | None = None + + # Callbacks + self._offroad_transition_callbacks: list[Callable[[], None]] = [] + self._engaged_transition_callbacks: list[Callable[[], None]] = [] + self._on_body_changed_callbacks: list[Callable[[], None]] = [] + + def add_offroad_transition_callback(self, callback: Callable[[], None]): + self._offroad_transition_callbacks.append(callback) + + def add_engaged_transition_callback(self, callback: Callable[[], None]): + self._engaged_transition_callbacks.append(callback) + + def add_on_body_changed_callbacks(self, callback: Callable[[], None]): + self._on_body_changed_callbacks.append(callback) + + @property + def engaged(self) -> bool: + return self.started and (self.sm["selfdriveState"].enabled or self.sm["selfdriveStateSP"].mads.enabled) + + def is_onroad(self) -> bool: + return self.started + + def is_offroad(self) -> bool: + return not self.started + + def update(self) -> None: + self.prime_state.start() # start thread after manager forks ui + if self._params_thread is None: + self._params_thread = threading.Thread(target=self._params_refresh_worker, daemon=True) + self._params_thread.start() + + self.sm.update(0) + self._update_state() + self._update_status() + device.update() + UIStateSP.update(self) + + def _params_refresh_worker(self): + drop_realtime() + while True: + self.update_params() + time.sleep(PARAM_UPDATE_TIME) + + def _update_state(self) -> None: + # Handle panda states updates + if self.sm.updated["pandaStates"]: + panda_states = self.sm["pandaStates"] + + if len(panda_states) > 0: + # Get panda type from first panda + self.panda_type = panda_states[0].pandaType + # Check ignition status across all pandas + if self.panda_type != log.PandaState.PandaType.unknown: + self.ignition = any(state.ignitionLine or state.ignitionCan for state in panda_states) + elif not self.sm.alive["pandaStates"]: + self.panda_type = log.PandaState.PandaType.unknown + + # Handle wide road camera state updates + if self.sm.updated["wideRoadCameraState"]: + cam_state = self.sm["wideRoadCameraState"] + self.light_sensor = max(100.0 - cam_state.exposureValPercent, 0.0) + elif not self.sm.alive["wideRoadCameraState"] or not self.sm.valid["wideRoadCameraState"]: + self.light_sensor = -1 + + # Update started state + self.started = self.sm["deviceState"].started and self.ignition + + # Update body state + if self.CP is not None and self.is_body != self.CP.notCar: + self.is_body = self.CP.notCar + for callback in self._on_body_changed_callbacks: + callback() + + def _update_status(self) -> None: + if self.started and self.sm.updated["selfdriveState"]: + ss = self.sm["selfdriveState"] + state = ss.state + + if state in (log.SelfdriveState.OpenpilotState.preEnabled, log.SelfdriveState.OpenpilotState.overriding): + self.status = UIStatus.OVERRIDE + else: + self.status = UIStatus.ENGAGED if ss.enabled else UIStatus.DISENGAGED + + self.status = UIStatus(UIStateSP.update_status(ss, self.sm["selfdriveStateSP"], self.sm["onroadEvents"])) + + # Check for engagement state changes + if self.engaged != self._engaged_prev: + for callback in self._engaged_transition_callbacks: + callback() + self._engaged_prev = self.engaged + + # Handle onroad/offroad transition + if self.started != self._started_prev or self.sm.frame == 1: + if self.started: + self.status = UIStatus.DISENGAGED + self.started_frame = self.sm.frame + self.started_time = time.monotonic() + + for callback in self._offroad_transition_callbacks: + callback() + + self._started_prev = self.started + + def update_params(self) -> None: + # For slower operations + # Update longitudinal control state + CP_bytes = self.params.get("CarParamsPersistent") + if CP_bytes is not None: + self.CP = messaging.log_from_bytes(CP_bytes, car.CarParams) + if self.CP.alphaLongitudinalAvailable: + self.has_longitudinal_control = self.params.get_bool("AlphaLongitudinalEnabled") + else: + self.has_longitudinal_control = self.CP.openpilotLongitudinalControl + + self.recording_audio = self.params.get_bool("RecordAudio") and self.started + self.is_metric = self.params.get_bool("IsMetric") + self.always_on_dm = self.params.get_bool("AlwaysOnDM") + self.experimental_mode = self.params.get_bool("ExperimentalMode") + self.usbgpu = self.params.get_bool("UsbGpuPresent") + self.usbgpu_compiled = self.params.get_bool("UsbGpuCompiled") + + UIStateSP.update_params(self) + + +class Device(DeviceSP): + def __init__(self): + DeviceSP.__init__(self) + self._ignition = False + self._interaction_time: float = -1 + self._override_interactive_timeout: int | None = None + self._interactive_timeout_callbacks: list[Callable] = [] + self._prev_timed_out = False + self._awake: bool = True + + self._offroad_brightness: int = BACKLIGHT_OFFROAD + self._last_brightness: int = 0 + self._brightness_filter = FirstOrderFilter(BACKLIGHT_OFFROAD, 10.00, 1 / gui_app.target_fps) + self._brightness_thread: threading.Thread | None = None + self._brightness_event = threading.Event() + self._brightness_target: int = 0 + + @property + def awake(self) -> bool: + return self._awake + + def set_override_interactive_timeout(self, timeout: int | None) -> None: + # Override the interactive timeout duration temporarily + self._override_interactive_timeout = timeout + self._reset_interactive_timeout() + + @property + def interactive_timeout(self) -> int: + if self._override_interactive_timeout is not None: + return self._override_interactive_timeout + + if gui_app.sunnypilot_ui() and ui_state.custom_interactive_timeout != 0: + return ui_state.custom_interactive_timeout + + ignition_timeout = 10 if gui_app.big_ui() else 5 + return ignition_timeout if ui_state.ignition else 30 + + def _reset_interactive_timeout(self) -> None: + self._interaction_time = time.monotonic() + self.interactive_timeout + + def add_interactive_timeout_callback(self, callback: Callable): + self._interactive_timeout_callbacks.append(callback) + + def update(self): + self._start_brightness_thread() # start thread after manager forks ui + + # do initial reset + if self._interaction_time <= 0: + self._reset_interactive_timeout() + + self._update_brightness() + self._update_wakefulness() + + def _start_brightness_thread(self): + if self._brightness_thread is None or not self._brightness_thread.is_alive(): + self._brightness_thread = threading.Thread(target=self._brightness_worker, daemon=True) + self._brightness_thread.start() + + def _brightness_worker(self): + drop_realtime() + while True: + self._brightness_event.wait() + self._brightness_event.clear() + HARDWARE.set_screen_brightness(self._brightness_target) + + def set_offroad_brightness(self, brightness: int | None): + if brightness is None: + brightness = BACKLIGHT_OFFROAD + self._offroad_brightness = min(max(brightness, 0), 100) + + def _update_brightness(self): + clipped_brightness = self._offroad_brightness + + if ui_state.started and ui_state.light_sensor >= 0: + clipped_brightness = ui_state.light_sensor + + # CIE 1931 - https://www.photonstophotos.net/GeneralTopics/Exposure/Psychometric_Lightness_and_Gamma.htm + if clipped_brightness <= 8: + clipped_brightness = clipped_brightness / 903.3 + else: + clipped_brightness = ((clipped_brightness + 16.0) / 116.0) ** 3.0 + + min_brightness = 30 + if gui_app.sunnypilot_ui(): + min_brightness = DeviceSP.set_min_onroad_brightness(ui_state, min_brightness) + + clipped_brightness = float(np.interp(clipped_brightness, [0, 1], [min_brightness, 100])) + + brightness = round(self._brightness_filter.update(clipped_brightness)) + + if gui_app.sunnypilot_ui(): + brightness = DeviceSP.set_onroad_brightness(ui_state, self._awake, brightness) + + if not self._awake: + brightness = 0 + + if brightness != self._last_brightness: + self._brightness_target = int(brightness) + self._brightness_event.set() + self._last_brightness = int(brightness) + + def _update_wakefulness(self): + # Handle interactive timeout + ignition_just_turned_off = not ui_state.ignition and self._ignition + self._ignition = ui_state.ignition + + if ignition_just_turned_off or any(ev.left_down for ev in gui_app.mouse_events): + if gui_app.sunnypilot_ui(): + DeviceSP.wake_from_dimmed_onroad_brightness(ui_state, gui_app.mouse_events) + + self._reset_interactive_timeout() + + interaction_timeout = time.monotonic() > self._interaction_time + if interaction_timeout and not self._prev_timed_out: + for callback in self._interactive_timeout_callbacks: + callback() + self._prev_timed_out = interaction_timeout + + self._set_awake(ui_state.ignition or not interaction_timeout or PC) + + def _set_awake(self, on: bool, _ui_state=None): + if on != self._awake: + super()._set_awake(on, _ui_state or ui_state) + self._awake = on + cloudlog.debug(f"setting display power {int(on)}") + HARDWARE.set_display_power(on) + gui_app.set_should_render(on) + + +# Global instance +ui_state = UIState() +device = Device() diff --git a/openpilot/selfdrive/ui/watch3.py b/openpilot/selfdrive/ui/watch3.py new file mode 100755 index 0000000000..bb64cdc4d5 --- /dev/null +++ b/openpilot/selfdrive/ui/watch3.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python3 +import pyray as rl + +from msgq.visionipc import VisionStreamType +from openpilot.system.ui.lib.application import gui_app +from openpilot.selfdrive.ui.onroad.cameraview import CameraView + + +if __name__ == "__main__": + gui_app.init_window("watch3") + road = CameraView("camerad", VisionStreamType.VISION_STREAM_ROAD) + driver = CameraView("camerad", VisionStreamType.VISION_STREAM_DRIVER) + wide = CameraView("camerad", VisionStreamType.VISION_STREAM_WIDE_ROAD) + for _ in gui_app.render(): + road.render(rl.Rectangle(gui_app.width // 4, 0, gui_app.width // 2, gui_app.height // 2)) + driver.render(rl.Rectangle(0, gui_app.height // 2, gui_app.width // 2, gui_app.height // 2)) + wide.render(rl.Rectangle(gui_app.width // 2, gui_app.height // 2, gui_app.width // 2, gui_app.height // 2)) diff --git a/sunnypilot/models/__init__.py b/openpilot/selfdrive/ui/widgets/__init__.py similarity index 100% rename from sunnypilot/models/__init__.py rename to openpilot/selfdrive/ui/widgets/__init__.py diff --git a/openpilot/selfdrive/ui/widgets/exp_mode_button.py b/openpilot/selfdrive/ui/widgets/exp_mode_button.py new file mode 100644 index 0000000000..0b5bff7da4 --- /dev/null +++ b/openpilot/selfdrive/ui/widgets/exp_mode_button.py @@ -0,0 +1,65 @@ +import pyray as rl +from openpilot.common.params import Params +from openpilot.system.ui.lib.application import gui_app, FontWeight, FONT_SCALE +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.widgets import Widget + + +class ExperimentalModeButton(Widget): + def __init__(self): + super().__init__() + + self.img_width = 80 + self.horizontal_padding = 25 + self.button_height = 125 + + self.params = Params() + self.experimental_mode = self.params.get_bool("ExperimentalMode") + + self.chill_pixmap = gui_app.texture("icons/couch.png", self.img_width, self.img_width) + self.experimental_pixmap = gui_app.texture("icons/experimental_grey.png", self.img_width, self.img_width) + + def show_event(self): + super().show_event() + self.experimental_mode = self.params.get_bool("ExperimentalMode") + + def _get_gradient_colors(self): + alpha = 0xCC if self.is_pressed else 0xFF + + if self.experimental_mode: + return rl.Color(255, 155, 63, alpha), rl.Color(219, 56, 34, alpha) + else: + return rl.Color(20, 255, 171, alpha), rl.Color(35, 149, 255, alpha) + + def _draw_gradient_background(self, rect): + start_color, end_color = self._get_gradient_colors() + rl.draw_rectangle_gradient_h(int(rect.x), int(rect.y), int(rect.width), int(rect.height), + start_color, end_color) + + def _render(self, rect): + rl.begin_scissor_mode(int(rect.x), int(rect.y), int(rect.width), int(rect.height)) + self._draw_gradient_background(rect) + rl.draw_rectangle_rounded_lines_ex(self._rect, 0.19, 10, 5, rl.BLACK) + rl.end_scissor_mode() + + # Draw vertical separator line + line_x = rect.x + rect.width - self.img_width - (2 * self.horizontal_padding) + separator_color = rl.Color(0, 0, 0, 77) # 0x4d = 77 + rl.draw_line_ex(rl.Vector2(line_x, rect.y), rl.Vector2(line_x, rect.y + rect.height), 3, separator_color) + + # Draw text label (left aligned) + text = tr("EXPERIMENTAL MODE ON") if self.experimental_mode else tr("CHILL MODE ON") + text_x = rect.x + self.horizontal_padding + text_y = rect.y + rect.height / 2 - 45 * FONT_SCALE // 2 # Center vertically + + rl.draw_text_ex(gui_app.font(FontWeight.NORMAL), text, rl.Vector2(int(text_x), int(text_y)), 45, 0, rl.BLACK) + + # Draw icon (right aligned) + icon_x = rect.x + rect.width - self.horizontal_padding - self.img_width + icon_y = rect.y + (rect.height - self.img_width) / 2 + icon_rect = rl.Rectangle(icon_x, icon_y, self.img_width, self.img_width) + + # Draw current mode icon + current_icon = self.experimental_pixmap if self.experimental_mode else self.chill_pixmap + source_rect = rl.Rectangle(0, 0, current_icon.width, current_icon.height) + rl.draw_texture_pro(current_icon, source_rect, icon_rect, rl.Vector2(0, 0), 0, rl.WHITE) diff --git a/openpilot/selfdrive/ui/widgets/offroad_alerts.py b/openpilot/selfdrive/ui/widgets/offroad_alerts.py new file mode 100644 index 0000000000..88ccc5df7e --- /dev/null +++ b/openpilot/selfdrive/ui/widgets/offroad_alerts.py @@ -0,0 +1,345 @@ +import pyray as rl +from enum import IntEnum +from abc import ABC, abstractmethod +from collections.abc import Callable +from dataclasses import dataclass +from openpilot.common.params import Params +from openpilot.common.hardware import HARDWARE +from openpilot.system.ui.lib.application import gui_app, FontWeight, FONT_SCALE +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.lib.scroll_panel import GuiScrollPanel +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.lib.wrap_text import wrap_text +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.html_render import HtmlRenderer +from openpilot.selfdrive.selfdrived.alertmanager import OFFROAD_ALERTS + + +class AlertColors: + HIGH_SEVERITY = rl.Color(226, 44, 44, 255) + LOW_SEVERITY = rl.Color(41, 41, 41, 255) + BACKGROUND = rl.Color(57, 57, 57, 255) + BUTTON = rl.WHITE + BUTTON_PRESSED = rl.Color(200, 200, 200, 255) + BUTTON_TEXT = rl.BLACK + SNOOZE_BG = rl.Color(79, 79, 79, 255) + SNOOZE_BG_PRESSED = rl.Color(100, 100, 100, 255) + TEXT = rl.WHITE + + +class AlertConstants: + MIN_BUTTON_WIDTH = 400 + BUTTON_HEIGHT = 125 + MARGIN = 50 + SPACING = 30 + FONT_SIZE = 48 + BORDER_RADIUS = 30 * 2 # matches Qt's 30px + ALERT_HEIGHT = 120 + ALERT_SPACING = 10 + ALERT_INSET = 60 + + +@dataclass +class AlertData: + key: str + text: str + severity: int + visible: bool = False + + +class ButtonStyle(IntEnum): + LIGHT = 0 + DARK = 1 + + +class ActionButton(Widget): + def __init__(self, text: str | Callable[[], str], style: ButtonStyle = ButtonStyle.LIGHT, + min_width: int = AlertConstants.MIN_BUTTON_WIDTH): + super().__init__() + self._text = text + self._style = style + self._min_width = min_width + self._font = gui_app.font(FontWeight.MEDIUM) + + @property + def text(self) -> str: + return self._text if isinstance(self._text, str) else self._text() + + def _render(self, _): + text_size = measure_text_cached(gui_app.font(FontWeight.MEDIUM), self.text, AlertConstants.FONT_SIZE) + self._rect.width = max(text_size.x + 60 * 2, self._min_width) + self._rect.height = AlertConstants.BUTTON_HEIGHT + + roundness = AlertConstants.BORDER_RADIUS / self._rect.height + bg_color = AlertColors.BUTTON if self._style == ButtonStyle.LIGHT else AlertColors.SNOOZE_BG + if self.is_pressed: + bg_color = AlertColors.BUTTON_PRESSED if self._style == ButtonStyle.LIGHT else AlertColors.SNOOZE_BG_PRESSED + + rl.draw_rectangle_rounded(self._rect, roundness, 10, bg_color) + + # center text + color = rl.WHITE if self._style == ButtonStyle.DARK else rl.BLACK + text_x = int(self._rect.x + (self._rect.width - text_size.x) // 2) + text_y = int(self._rect.y + (self._rect.height - text_size.y) // 2) + rl.draw_text_ex(self._font, self.text, rl.Vector2(text_x, text_y), AlertConstants.FONT_SIZE, 0, color) + + +class AbstractAlert(Widget, ABC): + def __init__(self, has_reboot_btn: bool = False): + super().__init__() + self.params = Params() + self.has_reboot_btn = has_reboot_btn + self.dismiss_callback: Callable | None = None + + def snooze_callback(): + self.params.put_bool("SnoozeUpdate", True) + if self.dismiss_callback: + self.dismiss_callback() + + def excessive_actuation_callback(): + self.params.remove("Offroad_ExcessiveActuation") + if self.dismiss_callback: + self.dismiss_callback() + + self.dismiss_btn = ActionButton(lambda: tr("Close")) + + self.snooze_btn = ActionButton(lambda: tr("Snooze Update"), style=ButtonStyle.DARK) + self.snooze_btn.set_click_callback(snooze_callback) + + self.excessive_actuation_btn = ActionButton(lambda: tr("Acknowledge Excessive Actuation"), style=ButtonStyle.DARK, min_width=800) + self.excessive_actuation_btn.set_click_callback(excessive_actuation_callback) + + self.reboot_btn = ActionButton(lambda: tr("Reboot and Update"), min_width=600) + self.reboot_btn.set_click_callback(lambda: HARDWARE.reboot()) + + # TODO: just use a Scroller? + self.content_rect = rl.Rectangle(0, 0, 0, 0) + self.scroll_panel_rect = rl.Rectangle(0, 0, 0, 0) + self.scroll_panel = GuiScrollPanel() + + def show_event(self): + super().show_event() + self.scroll_panel.set_offset(0) + + def set_dismiss_callback(self, callback: Callable): + self.dismiss_callback = callback + self.dismiss_btn.set_click_callback(self.dismiss_callback) + + @abstractmethod + def refresh(self) -> bool: + pass + + @abstractmethod + def get_content_height(self) -> float: + pass + + def _render(self, rect: rl.Rectangle): + rl.draw_rectangle_rounded(rect, AlertConstants.BORDER_RADIUS / rect.height, 10, AlertColors.BACKGROUND) + + footer_height = AlertConstants.BUTTON_HEIGHT + AlertConstants.SPACING + content_height = rect.height - 2 * AlertConstants.MARGIN - footer_height + + self.content_rect = rl.Rectangle( + rect.x + AlertConstants.MARGIN, + rect.y + AlertConstants.MARGIN, + rect.width - 2 * AlertConstants.MARGIN, + content_height, + ) + self.scroll_panel_rect = rl.Rectangle( + self.content_rect.x, self.content_rect.y, self.content_rect.width, self.content_rect.height + ) + + self._render_scrollable_content() + self._render_footer(rect) + + def _render_scrollable_content(self): + content_total_height = self.get_content_height() + content_bounds = rl.Rectangle(0, 0, self.scroll_panel_rect.width, content_total_height) + scroll_offset = self.scroll_panel.update(self.scroll_panel_rect, content_bounds) + + rl.begin_scissor_mode( + int(self.scroll_panel_rect.x), + int(self.scroll_panel_rect.y), + int(self.scroll_panel_rect.width), + int(self.scroll_panel_rect.height), + ) + + content_rect_with_scroll = rl.Rectangle( + self.scroll_panel_rect.x, + self.scroll_panel_rect.y + scroll_offset, + self.scroll_panel_rect.width, + content_total_height, + ) + + self._render_content(content_rect_with_scroll) + rl.end_scissor_mode() + + @abstractmethod + def _render_content(self, content_rect: rl.Rectangle): + pass + + def _render_footer(self, rect: rl.Rectangle): + footer_y = rect.y + rect.height - AlertConstants.MARGIN - AlertConstants.BUTTON_HEIGHT + + dismiss_x = rect.x + AlertConstants.MARGIN + self.dismiss_btn.set_position(dismiss_x, footer_y) + self.dismiss_btn.render() + + if self.has_reboot_btn: + reboot_x = rect.x + rect.width - AlertConstants.MARGIN - self.reboot_btn.rect.width + self.reboot_btn.set_position(reboot_x, footer_y) + self.reboot_btn.render() + + elif self.excessive_actuation_btn.is_visible: + actuation_x = rect.x + rect.width - AlertConstants.MARGIN - self.excessive_actuation_btn.rect.width + self.excessive_actuation_btn.set_position(actuation_x, footer_y) + self.excessive_actuation_btn.render() + + elif self.snooze_btn.is_visible: + snooze_x = rect.x + rect.width - AlertConstants.MARGIN - self.snooze_btn.rect.width + self.snooze_btn.set_position(snooze_x, footer_y) + self.snooze_btn.render() + + +class OffroadAlert(AbstractAlert): + def __init__(self): + super().__init__(has_reboot_btn=False) + self.sorted_alerts: list[AlertData] = [] + + def refresh(self): + if not self.sorted_alerts: + self._build_alerts() + + active_count = 0 + connectivity_needed = False + excessive_actuation = False + + for alert_data in self.sorted_alerts: + text = "" + alert_json = self.params.get(alert_data.key) + + if alert_json: + text = alert_json.get("text", "").replace("%1", alert_json.get("extra", "")) + + alert_data.text = text + alert_data.visible = bool(text) + + if alert_data.visible: + active_count += 1 + + if alert_data.key == "Offroad_ConnectivityNeeded" and alert_data.visible: + connectivity_needed = True + + if alert_data.key == "Offroad_ExcessiveActuation" and alert_data.visible: + excessive_actuation = True + + self.excessive_actuation_btn.set_visible(excessive_actuation) + self.snooze_btn.set_visible(connectivity_needed and not excessive_actuation) + return active_count + + def get_content_height(self) -> float: + if not self.sorted_alerts: + return 0 + + total_height = 20 + font = gui_app.font(FontWeight.NORMAL) + + for alert_data in self.sorted_alerts: + if not alert_data.visible: + continue + + text_width = int(self.content_rect.width - (AlertConstants.ALERT_INSET * 2)) + wrapped_lines = wrap_text(font, alert_data.text, AlertConstants.FONT_SIZE, text_width) + line_count = len(wrapped_lines) + text_height = line_count * (AlertConstants.FONT_SIZE * FONT_SCALE) + alert_item_height = max(text_height + (AlertConstants.ALERT_INSET * 2), AlertConstants.ALERT_HEIGHT) + total_height += round(alert_item_height + AlertConstants.ALERT_SPACING) + + if total_height > 20: + total_height = total_height - AlertConstants.ALERT_SPACING + 20 + + return total_height + + def _build_alerts(self): + self.sorted_alerts = [] + for key, config in sorted(OFFROAD_ALERTS.items(), key=lambda x: x[1].get("severity", 0), reverse=True): + severity = config.get("severity", 0) + alert_data = AlertData(key=key, text="", severity=severity) + self.sorted_alerts.append(alert_data) + + def _render_content(self, content_rect: rl.Rectangle): + y_offset = AlertConstants.ALERT_SPACING + font = gui_app.font(FontWeight.NORMAL) + + for alert_data in self.sorted_alerts: + if not alert_data.visible: + continue + + bg_color = AlertColors.HIGH_SEVERITY if alert_data.severity > 0 else AlertColors.LOW_SEVERITY + text_width = int(content_rect.width - (AlertConstants.ALERT_INSET * 2)) + wrapped_lines = wrap_text(font, alert_data.text, AlertConstants.FONT_SIZE, text_width) + line_count = len(wrapped_lines) + text_height = line_count * (AlertConstants.FONT_SIZE * FONT_SCALE) + alert_item_height = max(text_height + (AlertConstants.ALERT_INSET * 2), AlertConstants.ALERT_HEIGHT) + + alert_rect = rl.Rectangle( + content_rect.x + 10, + content_rect.y + y_offset, + content_rect.width - 30, + alert_item_height, + ) + + roundness = AlertConstants.BORDER_RADIUS / min(alert_rect.height, alert_rect.width) + rl.draw_rectangle_rounded(alert_rect, roundness, 10, bg_color) + + text_x = alert_rect.x + AlertConstants.ALERT_INSET + text_y = alert_rect.y + AlertConstants.ALERT_INSET + + for i, line in enumerate(wrapped_lines): + rl.draw_text_ex( + font, + line, + rl.Vector2(text_x, text_y + i * AlertConstants.FONT_SIZE * FONT_SCALE), + AlertConstants.FONT_SIZE, + 0, + AlertColors.TEXT, + ) + + y_offset += round(alert_item_height + AlertConstants.ALERT_SPACING) + + +class UpdateAlert(AbstractAlert): + def __init__(self): + super().__init__(has_reboot_btn=True) + self.release_notes = "" + self._wrapped_release_notes = "" + self._cached_content_height: float = 0.0 + self._html_renderer = HtmlRenderer(text="") + + def refresh(self) -> bool: + update_available: bool = self.params.get_bool("UpdateAvailable") + no_release_notes = "

" + tr("No release notes available.") + "

" + + if update_available: + self.release_notes = (self.params.get("UpdaterNewReleaseNotes") or b"").decode("utf8").strip() + self._html_renderer.parse_html_content(self.release_notes or no_release_notes) + self._cached_content_height = 0 + else: + self._html_renderer.parse_html_content(no_release_notes) + + return update_available + + def get_content_height(self) -> float: + if not self.release_notes: + return 100 + + if self._cached_content_height == 0: + self._wrapped_release_notes = self.release_notes + size = measure_text_cached(gui_app.font(FontWeight.NORMAL), self._wrapped_release_notes, AlertConstants.FONT_SIZE) + self._cached_content_height = max(size.y + 60, 100) + + return self._cached_content_height + + def _render_content(self, content_rect: rl.Rectangle): + notes_rect = rl.Rectangle(content_rect.x + 30, content_rect.y + 30, content_rect.width - 60, content_rect.height - 60) + self._html_renderer.render(notes_rect) diff --git a/openpilot/selfdrive/ui/widgets/pairing_dialog.py b/openpilot/selfdrive/ui/widgets/pairing_dialog.py new file mode 100644 index 0000000000..1ff550e4b6 --- /dev/null +++ b/openpilot/selfdrive/ui/widgets/pairing_dialog.py @@ -0,0 +1,170 @@ +import pyray as rl +import qrcode +import numpy as np +import time + +from openpilot.common.api import Api +from openpilot.common.swaglog import cloudlog +from openpilot.common.params import Params +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.lib.application import FontWeight, gui_app +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.lib.wrap_text import wrap_text +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.widgets.button import IconButton +from openpilot.selfdrive.ui.ui_state import ui_state + + +class PairingDialog(Widget): + """Dialog for device pairing with QR code.""" + + QR_REFRESH_INTERVAL = 300 # 5 minutes in seconds + + def __init__(self): + super().__init__() + self.params = Params() + self.qr_texture: rl.Texture | None = None + self.last_qr_generation = float('-inf') + self._close_btn = IconButton(gui_app.texture("icons/close.png", 80, 80)) + self._close_btn.set_click_callback(gui_app.pop_widget) + + def _get_pairing_url(self) -> str: + try: + dongle_id = self.params.get("DongleId") or "" + token = Api(dongle_id).get_token({'pair': True}) + except Exception: + cloudlog.exception("Failed to get pairing token") + token = "" + return f"https://connect.comma.ai/?pair={token}" + + def _generate_qr_code(self) -> None: + try: + qr = qrcode.QRCode(version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4) + qr.add_data(self._get_pairing_url()) + qr.make(fit=True) + + pil_img = qr.make_image(fill_color="black", back_color="white").convert('RGBA') + img_array = np.array(pil_img, dtype=np.uint8) + + if self.qr_texture and self.qr_texture.id != 0: + rl.unload_texture(self.qr_texture) + + rl_image = rl.Image() + rl_image.data = rl.ffi.cast("void *", img_array.ctypes.data) + rl_image.width = pil_img.width + rl_image.height = pil_img.height + rl_image.mipmaps = 1 + rl_image.format = rl.PixelFormat.PIXELFORMAT_UNCOMPRESSED_R8G8B8A8 + + self.qr_texture = rl.load_texture_from_image(rl_image) + except Exception: + cloudlog.exception("QR code generation failed") + self.qr_texture = None + + def _check_qr_refresh(self) -> None: + current_time = time.monotonic() + if current_time - self.last_qr_generation >= self.QR_REFRESH_INTERVAL: + self._generate_qr_code() + self.last_qr_generation = current_time + + def _update_state(self): + if ui_state.prime_state.is_paired(): + gui_app.pop_widget() + + def _render(self, rect: rl.Rectangle) -> int: + rl.clear_background(rl.Color(224, 224, 224, 255)) + + self._check_qr_refresh() + + margin = 70 + content_rect = rl.Rectangle(rect.x + margin, rect.y + margin, rect.width - 2 * margin, rect.height - 2 * margin) + y = content_rect.y + + # Close button + close_size = 80 + pad = 20 + close_rect = rl.Rectangle(content_rect.x - pad, y - pad, close_size + pad * 2, close_size + pad * 2) + self._close_btn.render(close_rect) + + y += close_size + 40 + + # Title + title = tr("Pair your device to your comma account") + title_font = gui_app.font(FontWeight.NORMAL) + left_width = int(content_rect.width * 0.5 - 15) + + title_wrapped = wrap_text(title_font, title, 75, left_width) + rl.draw_text_ex(title_font, "\n".join(title_wrapped), rl.Vector2(content_rect.x, y), 75, 0.0, rl.BLACK) + y += len(title_wrapped) * 75 + 60 + + # Two columns: instructions and QR code + remaining_height = content_rect.height - (y - content_rect.y) + right_width = content_rect.width // 2 - 20 + + # Instructions + self._render_instructions(rl.Rectangle(content_rect.x, y, left_width, remaining_height)) + + # QR code + qr_size = min(right_width, content_rect.height) - 40 + qr_x = content_rect.x + left_width + 40 + (right_width - qr_size) // 2 + qr_y = content_rect.y + self._render_qr_code(rl.Rectangle(qr_x, qr_y, qr_size, qr_size)) + + return -1 + + def _render_instructions(self, rect: rl.Rectangle) -> None: + instructions = [ + tr("Go to https://connect.comma.ai on your phone"), + tr("Click \"add new device\" and scan the QR code on the right"), + tr("Bookmark connect.comma.ai to your home screen to use it like an app"), + ] + + font = gui_app.font(FontWeight.BOLD) + y = rect.y + + for i, text in enumerate(instructions): + circle_radius = 25 + circle_x = rect.x + circle_radius + 15 + text_x = rect.x + circle_radius * 2 + 40 + text_width = rect.width - (circle_radius * 2 + 40) + + wrapped = wrap_text(font, text, 47, int(text_width)) + text_height = len(wrapped) * 47 + circle_y = y + text_height // 2 + + # Circle and number + rl.draw_circle(int(circle_x), int(circle_y), circle_radius, rl.Color(70, 70, 70, 255)) + number = str(i + 1) + number_size = measure_text_cached(font, number, 30) + rl.draw_text_ex(font, number, (int(circle_x - number_size.x // 2), int(circle_y - number_size.y // 2)), 30, 0, rl.WHITE) + + # Text + rl.draw_text_ex(font, "\n".join(wrapped), rl.Vector2(text_x, y), 47, 0.0, rl.BLACK) + y += text_height + 50 + + def _render_qr_code(self, rect: rl.Rectangle) -> None: + if not self.qr_texture: + rl.draw_rectangle_rounded(rect, 0.1, 20, rl.Color(240, 240, 240, 255)) + error_font = gui_app.font(FontWeight.BOLD) + rl.draw_text_ex( + error_font, tr("QR Code Error"), rl.Vector2(rect.x + 20, rect.y + rect.height // 2 - 15), 30, 0.0, rl.RED + ) + return + + source = rl.Rectangle(0, 0, self.qr_texture.width, self.qr_texture.height) + rl.draw_texture_pro(self.qr_texture, source, rect, rl.Vector2(0, 0), 0, rl.WHITE) + + def __del__(self): + if self.qr_texture and self.qr_texture.id != 0: + rl.unload_texture(self.qr_texture) + + +if __name__ == "__main__": + gui_app.init_window("pairing device") + pairing = PairingDialog() + gui_app.push_widget(pairing) + try: + for _ in gui_app.render(): + pass + finally: + del pairing diff --git a/openpilot/selfdrive/ui/widgets/prime.py b/openpilot/selfdrive/ui/widgets/prime.py new file mode 100644 index 0000000000..e98e4c1e1c --- /dev/null +++ b/openpilot/selfdrive/ui/widgets/prime.py @@ -0,0 +1,63 @@ +import pyray as rl + +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.lib.wrap_text import wrap_text +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.label import gui_label + + +class PrimeWidget(Widget): + """Widget for displaying comma prime subscription status""" + + PRIME_BG_COLOR = rl.Color(51, 51, 51, 255) + + def _render(self, rect): + if ui_state.prime_state.is_prime(): + self._render_for_prime_user(rect) + else: + self._render_for_non_prime_users(rect) + + def _render_for_non_prime_users(self, rect: rl.Rectangle): + """Renders the advertisement for non-Prime users.""" + + rl.draw_rectangle_rounded(rect, 0.025, 10, self.PRIME_BG_COLOR) + + # Layout + x, y = rect.x + 80, rect.y + 90 + w = rect.width - 160 + + # Title + gui_label(rl.Rectangle(x, y, w, 90), tr("Upgrade Now"), 75, font_weight=FontWeight.BOLD) + + # Description with wrapping + desc_y = y + 140 + font = gui_app.font(FontWeight.NORMAL) + wrapped_text = "\n".join(wrap_text(font, tr("Become a comma prime member at connect.comma.ai"), 56, int(w))) + text_size = measure_text_cached(font, wrapped_text, 56) + rl.draw_text_ex(font, wrapped_text, rl.Vector2(x, desc_y), 56, 0, rl.WHITE) + + # Features section + features_y = desc_y + text_size.y + 50 + gui_label(rl.Rectangle(x, features_y, w, 50), tr("PRIME FEATURES:"), 41, font_weight=FontWeight.BOLD) + + # Feature list + features = [tr("Remote access"), tr("24/7 LTE connectivity"), tr("1 year of drive storage"), tr("Remote snapshots")] + for i, feature in enumerate(features): + item_y = features_y + 80 + i * 65 + gui_label(rl.Rectangle(x, item_y, 100, 60), "✓", 50, color=rl.Color(70, 91, 234, 255)) + gui_label(rl.Rectangle(x + 60, item_y, w - 60, 60), feature, 50) + + def _render_for_prime_user(self, rect: rl.Rectangle): + """Renders the prime user widget with subscription status.""" + + rl.draw_rectangle_rounded(rl.Rectangle(rect.x, rect.y, rect.width, 230), 0.1, 10, self.PRIME_BG_COLOR) + + x = rect.x + 56 + y = rect.y + 40 + + font = gui_app.font(FontWeight.BOLD) + rl.draw_text_ex(font, tr("✓ SUBSCRIBED"), rl.Vector2(x, y), 41, 0, rl.Color(134, 255, 78, 255)) + rl.draw_text_ex(font, tr("comma prime"), rl.Vector2(x, y + 61), 75, 0, rl.WHITE) diff --git a/openpilot/selfdrive/ui/widgets/setup.py b/openpilot/selfdrive/ui/widgets/setup.py new file mode 100644 index 0000000000..c9452fc535 --- /dev/null +++ b/openpilot/selfdrive/ui/widgets/setup.py @@ -0,0 +1,95 @@ +import pyray as rl +from openpilot.common.time_helpers import system_time_valid +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.selfdrive.ui.widgets.pairing_dialog import PairingDialog +from openpilot.system.ui.lib.application import gui_app, FontWeight, FONT_SCALE +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.lib.wrap_text import wrap_text +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.confirm_dialog import alert_dialog +from openpilot.system.ui.widgets.button import Button, ButtonStyle +from openpilot.system.ui.widgets.label import Label + + +class SetupWidget(Widget): + def __init__(self): + super().__init__() + self._open_settings_callback = None + self._pair_device_btn = Button(lambda: tr("Pair device"), self._show_pairing, button_style=ButtonStyle.PRIMARY) + self._open_settings_btn = Button(lambda: tr("Open"), lambda: self._open_settings_callback() if self._open_settings_callback else None, + button_style=ButtonStyle.PRIMARY) + self._firehose_label = Label(lambda: tr("🔥 Firehose Mode 🔥"), font_weight=FontWeight.MEDIUM, font_size=64) + + def set_open_settings_callback(self, callback): + self._open_settings_callback = callback + + def _render(self, rect: rl.Rectangle): + if not ui_state.prime_state.is_paired(): + self._render_registration(rect) + else: + self._render_firehose_prompt(rect) + + def _render_registration(self, rect: rl.Rectangle): + """Render registration prompt.""" + + rl.draw_rectangle_rounded(rl.Rectangle(rect.x, rect.y, rect.width, rect.height), 0.03, 20, rl.Color(51, 51, 51, 255)) + + x = rect.x + 64 + y = rect.y + 48 + w = rect.width - 128 + + # Title + font = gui_app.font(FontWeight.BOLD) + rl.draw_text_ex(font, tr("Finish Setup"), rl.Vector2(x, y), 75, 0, rl.WHITE) + y += 113 # 75 + 38 spacing + + # Description + desc = tr("Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer.") + light_font = gui_app.font(FontWeight.NORMAL) + wrapped = wrap_text(light_font, desc, 50, int(w)) + for line in wrapped: + rl.draw_text_ex(light_font, line, rl.Vector2(x, y), 50, 0, rl.WHITE) + y += 50 * FONT_SCALE + + button_rect = rl.Rectangle(x, y + 30, w, 200) + self._pair_device_btn.render(button_rect) + + def _render_firehose_prompt(self, rect: rl.Rectangle): + """Render firehose prompt widget.""" + + rl.draw_rectangle_rounded(rl.Rectangle(rect.x, rect.y, rect.width, 500), 0.04, 20, rl.Color(51, 51, 51, 255)) + + # Content margins (56, 40, 56, 40) + x = rect.x + 56 + y = rect.y + 40 + w = rect.width - 112 + spacing = 42 + + # Title with fire emojis + self._firehose_label.render(rl.Rectangle(rect.x, y, rect.width, 64)) + y += 64 + spacing + + # Description + desc_font = gui_app.font(FontWeight.NORMAL) + desc_text = tr("Maximize your training data uploads to improve openpilot's driving models.") + wrapped_desc = wrap_text(desc_font, desc_text, 40, int(w)) + + for line in wrapped_desc: + rl.draw_text_ex(desc_font, line, rl.Vector2(x, y), 40, 0, rl.WHITE) + y += 40 * FONT_SCALE + + y += spacing + + # Open button + button_height = 48 + 64 # font size + padding + button_rect = rl.Rectangle(x, y, w, button_height) + self._open_settings_btn.render(button_rect) + + @staticmethod + def _show_pairing(): + if not system_time_valid(): + dlg = alert_dialog(tr("Please connect to Wi-Fi to complete initial pairing")) + gui_app.push_widget(dlg) + return + + gui_app.push_widget(PairingDialog()) diff --git a/openpilot/selfdrive/ui/widgets/ssh_key.py b/openpilot/selfdrive/ui/widgets/ssh_key.py new file mode 100644 index 0000000000..aa7cb91b1f --- /dev/null +++ b/openpilot/selfdrive/ui/widgets/ssh_key.py @@ -0,0 +1,158 @@ +import pyray as rl +import requests +import threading +from collections.abc import Callable +from enum import Enum + +from openpilot.common.params import Params +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.lib.multilang import tr, tr_noop +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.widgets import DialogResult +from openpilot.system.ui.widgets.button import Button, ButtonStyle +from openpilot.system.ui.widgets.confirm_dialog import alert_dialog +from openpilot.system.ui.widgets.keyboard import Keyboard +from openpilot.system.ui.widgets.list_view import ( + ItemAction, + ListItem, + BUTTON_HEIGHT, + BUTTON_BORDER_RADIUS, + BUTTON_FONT_SIZE, + BUTTON_WIDTH, +) + +VALUE_FONT_SIZE = 48 + + +class SshKeyFetcher: + HTTP_TIMEOUT = 15 # seconds + + def __init__(self, params: Params): + self._params = params + self._on_response: Callable[[str | None], None] | None = None + self._done: bool = False + self._error: str | None = None + + def fetch(self, username: str, on_response: Callable[[str | None], None]): + self._error = None + self._on_response = on_response + threading.Thread(target=self._fetch_thread, args=(username,), daemon=True).start() + + def update(self): + if not self._done: + return + self._done = False + if self._error is not None: + self.clear() + if self._on_response: + self._on_response(self._error) + + def clear(self): + self._params.remove("GithubUsername") + self._params.remove("GithubSshKeys") + + def _fetch_thread(self, username: str): + try: + response = requests.get(f"https://github.com/{username}.keys", timeout=self.HTTP_TIMEOUT) + response.raise_for_status() + keys = response.text.strip() + if not keys: + raise requests.exceptions.HTTPError("No SSH keys found") + + self._params.put("GithubUsername", username, block=True) + self._params.put("GithubSshKeys", keys, block=True) + except requests.exceptions.Timeout: + self._error = tr("Request timed out") + except Exception: + self._error = tr("No SSH keys found for user '{}'").format(username) + finally: + self._done = True + + +class SshKeyActionState(Enum): + LOADING = tr_noop("LOADING") + ADD = tr_noop("ADD") + REMOVE = tr_noop("REMOVE") + + +class SshKeyAction(ItemAction): + MAX_WIDTH = 500 + + def __init__(self): + super().__init__(self.MAX_WIDTH, True) + + self._keyboard = Keyboard(min_text_size=1) + self._params = Params() + self._fetcher = SshKeyFetcher(self._params) + self._text_font = gui_app.font(FontWeight.NORMAL) + self._button = Button("", click_callback=self._handle_button_click, button_style=ButtonStyle.LIST_ACTION, + border_radius=BUTTON_BORDER_RADIUS, font_size=BUTTON_FONT_SIZE) + + self._refresh_state() + + def set_touch_valid_callback(self, touch_callback: Callable[[], bool]) -> None: + super().set_touch_valid_callback(touch_callback) + self._button.set_touch_valid_callback(touch_callback) + + def _refresh_state(self): + self._username = self._params.get("GithubUsername") + self._state = SshKeyActionState.REMOVE if self._params.get("GithubSshKeys") else SshKeyActionState.ADD + + def _update_state(self): + super()._update_state() + self._fetcher.update() + + def _render(self, rect: rl.Rectangle) -> bool: + # Draw username if exists + if self._username: + text_size = measure_text_cached(self._text_font, self._username, VALUE_FONT_SIZE) + rl.draw_text_ex( + self._text_font, + self._username, + (rect.x + rect.width - BUTTON_WIDTH - text_size.x - 30, rect.y + (rect.height - text_size.y) / 2), + VALUE_FONT_SIZE, + 1.0, + rl.Color(170, 170, 170, 255), + ) + + # Draw button + button_rect = rl.Rectangle(rect.x + rect.width - BUTTON_WIDTH, rect.y + (rect.height - BUTTON_HEIGHT) / 2, BUTTON_WIDTH, BUTTON_HEIGHT) + self._button.set_rect(button_rect) + self._button.set_text(tr(self._state.value)) + self._button.set_enabled(self._state != SshKeyActionState.LOADING) + self._button.render(button_rect) + return False + + def _handle_button_click(self): + if self._state == SshKeyActionState.ADD: + self._keyboard.reset() + self._keyboard.set_title(tr("Enter your GitHub username")) + self._keyboard.set_callback(self._on_username_submit) + gui_app.push_widget(self._keyboard) + elif self._state == SshKeyActionState.REMOVE: + self._fetcher.clear() + self._refresh_state() + + def _on_username_submit(self, result: DialogResult): + if result != DialogResult.CONFIRM: + return + + username = self._keyboard.text.strip() + if not username: + return + + self._state = SshKeyActionState.LOADING + self._fetcher.fetch(username, self._on_fetch_response) + + def _on_fetch_response(self, error: str | None): + if error is None: + self._state = SshKeyActionState.REMOVE + self._username = self._params.get("GithubUsername") + else: + self._state = SshKeyActionState.ADD + self._username = "" + gui_app.push_widget(alert_dialog(error)) + + +def ssh_key_item(title: str | Callable[[], str], description: str | Callable[[], str]) -> ListItem: + return ListItem(title=title, description=description, action_item=SshKeyAction()) diff --git a/openpilot/sunnypilot b/openpilot/sunnypilot deleted file mode 120000 index c4ca692907..0000000000 --- a/openpilot/sunnypilot +++ /dev/null @@ -1 +0,0 @@ -../sunnypilot \ No newline at end of file diff --git a/openpilot/sunnypilot/SConscript b/openpilot/sunnypilot/SConscript new file mode 100644 index 0000000000..09ad39ab43 --- /dev/null +++ b/openpilot/sunnypilot/SConscript @@ -0,0 +1,3 @@ +SConscript(['common/transformations/SConscript']) +SConscript(['modeld_v2/SConscript']) +SConscript(['selfdrive/locationd/SConscript']) diff --git a/openpilot/sunnypilot/__init__.py b/openpilot/sunnypilot/__init__.py new file mode 100644 index 0000000000..59b3600531 --- /dev/null +++ b/openpilot/sunnypilot/__init__.py @@ -0,0 +1,39 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" + +from enum import IntEnum +import hashlib + +PARAMS_UPDATE_PERIOD = 3 # seconds + + +def get_file_hash(path: str) -> str: + sha256_hash = hashlib.sha256() + with open(path, "rb") as f: + for byte_block in iter(lambda: f.read(4096), b""): + sha256_hash.update(byte_block) + return sha256_hash.hexdigest() + + +class IntEnumBase(IntEnum): + @classmethod + def min(cls): + return min(cls) + + @classmethod + def max(cls): + return max(cls) + + +def get_sanitize_int_param(key: str, min_val: int, max_val: int, params) -> int: + val: int = params.get(key, return_default=True) + clipped_val = max(min_val, min(max_val, val)) + + if clipped_val != val: + params.put(key, clipped_val, block=True) + + return clipped_val diff --git a/openpilot/sunnypilot/common/transformations/SConscript b/openpilot/sunnypilot/common/transformations/SConscript new file mode 100644 index 0000000000..ffeaf18012 --- /dev/null +++ b/openpilot/sunnypilot/common/transformations/SConscript @@ -0,0 +1,4 @@ +Import('env') + +transformations = env.Library('transformations', ['orientation.cc', 'coordinates.cc']) +Export('transformations') diff --git a/common/transformations/coordinates.cc b/openpilot/sunnypilot/common/transformations/coordinates.cc similarity index 97% rename from common/transformations/coordinates.cc rename to openpilot/sunnypilot/common/transformations/coordinates.cc index f3f10e547f..776a5529d2 100644 --- a/common/transformations/coordinates.cc +++ b/openpilot/sunnypilot/common/transformations/coordinates.cc @@ -1,6 +1,6 @@ #define _USE_MATH_DEFINES -#include "common/transformations/coordinates.hpp" +#include "sunnypilot/common/transformations/coordinates.hpp" #include #include diff --git a/common/transformations/coordinates.hpp b/openpilot/sunnypilot/common/transformations/coordinates.hpp similarity index 100% rename from common/transformations/coordinates.hpp rename to openpilot/sunnypilot/common/transformations/coordinates.hpp diff --git a/common/transformations/orientation.cc b/openpilot/sunnypilot/common/transformations/orientation.cc similarity index 97% rename from common/transformations/orientation.cc rename to openpilot/sunnypilot/common/transformations/orientation.cc index fb5e47a86a..42c92b68b7 100644 --- a/common/transformations/orientation.cc +++ b/openpilot/sunnypilot/common/transformations/orientation.cc @@ -4,8 +4,8 @@ #include #include -#include "common/transformations/orientation.hpp" -#include "common/transformations/coordinates.hpp" +#include "sunnypilot/common/transformations/orientation.hpp" +#include "sunnypilot/common/transformations/coordinates.hpp" Eigen::Quaterniond ensure_unique(const Eigen::Quaterniond &quat) { if (quat.w() > 0){ @@ -141,4 +141,3 @@ Eigen::Vector3d ned_euler_from_ecef(const ECEF &ecef_init, const Eigen::Vector3d return {phi, theta, psi}; } - diff --git a/common/transformations/orientation.hpp b/openpilot/sunnypilot/common/transformations/orientation.hpp similarity index 92% rename from common/transformations/orientation.hpp rename to openpilot/sunnypilot/common/transformations/orientation.hpp index 0874a0a814..045340901c 100644 --- a/common/transformations/orientation.hpp +++ b/openpilot/sunnypilot/common/transformations/orientation.hpp @@ -1,6 +1,6 @@ #pragma once #include -#include "common/transformations/coordinates.hpp" +#include "sunnypilot/common/transformations/coordinates.hpp" Eigen::Quaterniond ensure_unique(const Eigen::Quaterniond &quat); diff --git a/openpilot/sunnypilot/common/version.h b/openpilot/sunnypilot/common/version.h new file mode 100644 index 0000000000..26151e206f --- /dev/null +++ b/openpilot/sunnypilot/common/version.h @@ -0,0 +1 @@ +#define SUNNYPILOT_VERSION "2026.003.000" diff --git a/sunnypilot/models/tests/__init__.py b/openpilot/sunnypilot/livedelay/__init__.py similarity index 100% rename from sunnypilot/models/tests/__init__.py rename to openpilot/sunnypilot/livedelay/__init__.py diff --git a/openpilot/sunnypilot/livedelay/helpers.py b/openpilot/sunnypilot/livedelay/helpers.py new file mode 100644 index 0000000000..0f7437ceea --- /dev/null +++ b/openpilot/sunnypilot/livedelay/helpers.py @@ -0,0 +1,14 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from openpilot.common.params import Params + + +def get_lat_delay(params: Params, stock_lat_delay: float) -> float: + if params.get_bool("LagdToggle"): + return float(params.get("LagdValueCache", return_default=True)) + + return stock_lat_delay diff --git a/openpilot/sunnypilot/livedelay/lagd_toggle.py b/openpilot/sunnypilot/livedelay/lagd_toggle.py new file mode 100644 index 0000000000..3926cbebf6 --- /dev/null +++ b/openpilot/sunnypilot/livedelay/lagd_toggle.py @@ -0,0 +1,38 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from openpilot.cereal import log + +from opendbc.car import structs +from openpilot.common.params import Params + + +class LagdToggle: + def __init__(self, CP: structs.CarParams): + self.CP = CP + self.params = Params() + self.lag = 0.0 + + self.lagd_toggle = self.params.get_bool("LagdToggle") + self.software_delay = self.params.get("LagdToggleDelay", return_default=True) + + def read_params(self) -> None: + self.lagd_toggle = self.params.get_bool("LagdToggle") + self.software_delay = self.params.get("LagdToggleDelay", return_default=True) + + def update(self, lag_msg: log.LiveDelayData) -> None: + self.read_params() + + if not self.lagd_toggle: + steer_actuator_delay = self.CP.steerActuatorDelay + delay = self.software_delay + self.lag = (steer_actuator_delay + delay) + self.params.put("LagdValueCache", self.lag) + return + + lateral_delay = lag_msg.liveDelay.lateralDelay + self.lag = lateral_delay + self.params.put("LagdValueCache", self.lag) diff --git a/openpilot/sunnypilot/mads/helpers.py b/openpilot/sunnypilot/mads/helpers.py new file mode 100644 index 0000000000..b9efd620f3 --- /dev/null +++ b/openpilot/sunnypilot/mads/helpers.py @@ -0,0 +1,73 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" + +from openpilot.common.params import Params +from opendbc.car import structs +from opendbc.safety import ALTERNATIVE_EXPERIENCE +from opendbc.sunnypilot.car.hyundai.values import HyundaiFlagsSP, HyundaiSafetyFlagsSP +from opendbc.sunnypilot.car.tesla.values import TeslaFlagsSP + + +MADS_NO_ACC_MAIN_BUTTON = ("rivian", "tesla") + + +class MadsSteeringModeOnBrake: + REMAIN_ACTIVE = 0 + PAUSE = 1 + DISENGAGE = 2 + + +def get_mads_limited_brands(CP: structs.CarParams, CP_SP: structs.CarParamsSP) -> bool: + if CP.brand == 'rivian': + return True + if CP.brand == 'tesla': + return not CP_SP.flags & TeslaFlagsSP.HAS_VEHICLE_BUS + + return False + + +def read_steering_mode_param(CP: structs.CarParams, CP_SP: structs.CarParamsSP, params: Params): + if get_mads_limited_brands(CP, CP_SP): + return MadsSteeringModeOnBrake.DISENGAGE + + return params.get("MadsSteeringMode", return_default=True) + + +def set_alternative_experience(CP: structs.CarParams, CP_SP: structs.CarParamsSP, params: Params): + enabled = params.get_bool("Mads") + steering_mode = read_steering_mode_param(CP, CP_SP, params) + + if enabled: + CP.alternativeExperience |= ALTERNATIVE_EXPERIENCE.ENABLE_MADS + + if steering_mode == MadsSteeringModeOnBrake.DISENGAGE: + CP.alternativeExperience |= ALTERNATIVE_EXPERIENCE.MADS_DISENGAGE_LATERAL_ON_BRAKE + elif steering_mode == MadsSteeringModeOnBrake.PAUSE: + CP.alternativeExperience |= ALTERNATIVE_EXPERIENCE.MADS_PAUSE_LATERAL_ON_BRAKE + + +def set_car_specific_params(CP: structs.CarParams, CP_SP: structs.CarParamsSP, params: Params): + if CP.brand == "hyundai": + # TODO-SP: This should be separated from MADS module for future implementations + # Use "HyundaiLongitudinalMainCruiseToggleable" param + hyundai_cruise_main_toggleable = True + if hyundai_cruise_main_toggleable: + CP_SP.flags |= HyundaiFlagsSP.LONGITUDINAL_MAIN_CRUISE_TOGGLEABLE.value + CP_SP.safetyParam |= HyundaiSafetyFlagsSP.LONG_MAIN_CRUISE_TOGGLEABLE + + # MADS Partial Support + # MADS is currently partially supported for these platforms due to lack of consistent states to engage controls + # Only MadsSteeringModeOnBrake.DISENGAGE is supported for these platforms + # TODO-SP: To enable MADS full support for Rivian and most Tesla, identify consistent signals for MADS toggling + mads_partial_support = get_mads_limited_brands(CP, CP_SP) + if mads_partial_support: + params.put("MadsSteeringMode", 2, block=True) + params.put_bool("MadsUnifiedEngagementMode", True, block=True) + + # no ACC MAIN button for these brands + if CP.brand in MADS_NO_ACC_MAIN_BUTTON: + params.remove("MadsMainCruiseAllowed") diff --git a/sunnypilot/mads/mads.py b/openpilot/sunnypilot/mads/mads.py similarity index 81% rename from sunnypilot/mads/mads.py rename to openpilot/sunnypilot/mads/mads.py index f16b688358..4ae3534b57 100644 --- a/sunnypilot/mads/mads.py +++ b/openpilot/sunnypilot/mads/mads.py @@ -5,12 +5,12 @@ This file is part of sunnypilot and is licensed under the MIT License. See the LICENSE.md file in the root directory for more details. """ -from cereal import log, custom +from openpilot.cereal import log, custom from opendbc.car import structs from opendbc.car.hyundai.values import HyundaiFlags from openpilot.common.params import Params -from openpilot.sunnypilot.mads.helpers import MadsSteeringModeOnBrake, read_steering_mode_param, get_mads_limited_brands +from openpilot.sunnypilot.mads.helpers import MadsSteeringModeOnBrake, read_steering_mode_param, MADS_NO_ACC_MAIN_BUTTON from openpilot.sunnypilot.mads.state import StateMachine, GEARS_ALLOW_PAUSED_SILENT State = custom.ModularAssistiveDrivingSystem.ModularAssistiveDrivingSystemState @@ -27,11 +27,13 @@ IGNORED_SAFETY_MODES = (SafetyModel.silent, SafetyModel.noOutput) class ModularAssistiveDrivingSystem: def __init__(self, selfdrive): self.CP = selfdrive.CP + self.CP_SP = selfdrive.CP_SP self.params = selfdrive.params self.enabled = False self.active = False self.available = False + self.lateral_mismatch_counter = 0 self.allow_always = False self.no_main_cruise = False self.selfdrive = selfdrive @@ -43,14 +45,16 @@ class ModularAssistiveDrivingSystem: if self.CP.brand == "hyundai": if self.CP.flags & (HyundaiFlags.HAS_LDA_BUTTON | HyundaiFlags.CANFD): self.allow_always = True + if self.CP.brand == "tesla": + self.allow_always = True - if get_mads_limited_brands(self.CP): + if self.CP.brand in MADS_NO_ACC_MAIN_BUTTON: self.no_main_cruise = True # read params on init self.enabled_toggle = self.params.get_bool("Mads") self.main_enabled_toggle = self.params.get_bool("MadsMainCruiseAllowed") - self.steering_mode_on_brake = read_steering_mode_param(self.CP, self.params) + self.steering_mode_on_brake = read_steering_mode_param(self.CP, self.CP_SP, self.params) self.unified_engagement_mode = self.params.get_bool("MadsUnifiedEngagementMode") def read_params(self): @@ -58,13 +62,14 @@ class ModularAssistiveDrivingSystem: self.unified_engagement_mode = self.params.get_bool("MadsUnifiedEngagementMode") def pedal_pressed_non_gas_pressed(self, CS: structs.CarState) -> bool: + # ignore `pedalPressed` events caused by gas presses if self.events.has(EventName.pedalPressed) and not (CS.gasPressed and not self.selfdrive.CS_prev.gasPressed and self.disengage_on_accelerator): return True return False def should_silent_lkas_enable(self, CS: structs.CarState) -> bool: - if self.steering_mode_on_brake == MadsSteeringModeOnBrake.PAUSE and self.pedal_pressed_non_gas_pressed(CS): + if self.steering_mode_on_brake == MadsSteeringModeOnBrake.PAUSE and (CS.brakePressed or CS.regenBraking or self.pedal_pressed_non_gas_pressed(CS)): return False if self.events_sp.contains_in_list(GEARS_ALLOW_PAUSED_SILENT): @@ -100,14 +105,26 @@ class ModularAssistiveDrivingSystem: self.events.remove(old_event) self.events_sp.add(new_event) + def data_sample(self): + # When the safety and selfdrived do not agree on controls_allowed_lateral + # we want to disengage sunnypilot. However the status from the panda goes through + # another socket other than the CAN messages and one can arrive earlier than the other. + # Therefore we allow a mismatch for two samples, then we trigger the disengagement. + if not self.active or self.selfdrive.enabled: + self.lateral_mismatch_counter = 0 + elif any(not ps.controlsAllowedLateral for ps in self.selfdrive.sm['pandaStates'] + if ps.safetyModel not in IGNORED_SAFETY_MODES): + self.lateral_mismatch_counter += 1 + def update_events(self, CS: structs.CarState): if not self.selfdrive.enabled and self.enabled: - if self.events.has(EventName.doorOpen): - self.replace_event(EventName.doorOpen, EventNameSP.silentDoorOpen) - self.transition_paused_state() - if self.events.has(EventName.seatbeltNotLatched): - self.replace_event(EventName.seatbeltNotLatched, EventNameSP.silentSeatbeltNotLatched) - self.transition_paused_state() + if CS.standstill: + if self.events.has(EventName.doorOpen): + self.replace_event(EventName.doorOpen, EventNameSP.silentDoorOpen) + self.transition_paused_state() + if self.events.has(EventName.seatbeltNotLatched): + self.replace_event(EventName.seatbeltNotLatched, EventNameSP.silentSeatbeltNotLatched) + self.transition_paused_state() if self.events.has(EventName.wrongGear) and (CS.vEgo < 2.5 or CS.gearShifter == GearShifter.reverse): self.replace_event(EventName.wrongGear, EventNameSP.silentWrongGear) self.transition_paused_state() @@ -130,6 +147,7 @@ class ModularAssistiveDrivingSystem: self.events.remove(EventName.speedTooLow) self.events.remove(EventName.cruiseDisabled) self.events.remove(EventName.manualRestart) + self.events.remove(EventName.espActive) selfdrive_enable_events = self.events.has(EventName.pcmEnable) or self.events.has(EventName.buttonEnable) set_speed_btns_enable = any(be.type in SET_SPEED_BUTTONS for be in CS.buttonEvents) @@ -181,6 +199,9 @@ class ModularAssistiveDrivingSystem: if self.state_machine.state == State.paused: self.events_sp.add(EventNameSP.silentLkasEnable) + if self.lateral_mismatch_counter >= 200: + self.events_sp.add(EventNameSP.controlsMismatchLateral) + self.events.remove(EventName.pcmDisable) self.events.remove(EventName.buttonCancel) self.events.remove(EventName.pedalPressed) @@ -190,6 +211,8 @@ class ModularAssistiveDrivingSystem: if not self.enabled_toggle: return + self.data_sample() + self.update_events(CS) if not self.CP.passive and self.selfdrive.initialized: diff --git a/openpilot/sunnypilot/mads/state.py b/openpilot/sunnypilot/mads/state.py new file mode 100644 index 0000000000..a8e5e1892f --- /dev/null +++ b/openpilot/sunnypilot/mads/state.py @@ -0,0 +1,135 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" + +from openpilot.cereal import log, custom +from openpilot.selfdrive.selfdrived.events import ET +from openpilot.selfdrive.selfdrived.state import SOFT_DISABLE_TIME +from openpilot.common.realtime import DT_CTRL + +State = custom.ModularAssistiveDrivingSystem.ModularAssistiveDrivingSystemState +EventName = log.OnroadEvent.EventName +EventNameSP = custom.OnroadEventSP.EventName + +ACTIVE_STATES = (State.enabled, State.softDisabling, State.overriding) +ENABLED_STATES = (State.paused, *ACTIVE_STATES) + +GEARS_ALLOW_PAUSED_SILENT = [EventNameSP.silentWrongGear, EventNameSP.silentReverseGear, EventNameSP.silentBrakeHold, + EventNameSP.silentDoorOpen, EventNameSP.silentSeatbeltNotLatched, EventNameSP.silentParkBrake] +GEARS_ALLOW_PAUSED = [EventName.wrongGear, EventName.reverseGear, EventName.brakeHold, + EventName.doorOpen, EventName.seatbeltNotLatched, EventName.parkBrake] + + +class StateMachine: + def __init__(self, mads): + self.selfdrive = mads.selfdrive + self.ss_state_machine = mads.selfdrive.state_machine + self._events = mads.selfdrive.events + self._events_sp = mads.selfdrive.events_sp + + self.state = State.disabled + + def add_current_alert_types(self, alert_type): + if not self.selfdrive.enabled: + self.ss_state_machine.current_alert_types.append(alert_type) + + def check_contains(self, event_type: str) -> bool: + return bool(self._events.contains(event_type) or self._events_sp.contains(event_type)) + + def check_contains_in_list(self) -> bool: + return bool(self._events.contains_in_list(GEARS_ALLOW_PAUSED) or self._events_sp.contains_in_list(GEARS_ALLOW_PAUSED_SILENT)) + + def update(self): + # soft disable timer and current alert types are from the state machine of openpilot + # decrement the soft disable timer at every step, as it's reset on + # entrance in SOFT_DISABLING state + + # ENABLED, SOFT DISABLING, PAUSED, OVERRIDING + if self.state != State.disabled: + # user and immediate disable always have priority in a non-disabled state + if self.check_contains(ET.USER_DISABLE): + if self._events_sp.has(EventNameSP.silentLkasDisable): + self.state = State.paused + else: + self.state = State.disabled + self.ss_state_machine.current_alert_types.append(ET.USER_DISABLE) + + elif self.check_contains(ET.IMMEDIATE_DISABLE): + self.state = State.disabled + self.add_current_alert_types(ET.IMMEDIATE_DISABLE) + + else: + # ENABLED + if self.state == State.enabled: + if self.check_contains(ET.SOFT_DISABLE): + self.state = State.softDisabling + if not self.selfdrive.enabled: + self.ss_state_machine.soft_disable_timer = int(SOFT_DISABLE_TIME / DT_CTRL) + self.ss_state_machine.current_alert_types.append(ET.SOFT_DISABLE) + + elif self.check_contains(ET.OVERRIDE_LATERAL): + self.state = State.overriding + self.add_current_alert_types(ET.OVERRIDE_LATERAL) + + # SOFT DISABLING + elif self.state == State.softDisabling: + if not self.check_contains(ET.SOFT_DISABLE): + # no more soft disabling condition, so go back to ENABLED + self.state = State.enabled + + elif self.ss_state_machine.soft_disable_timer > 0: + self.add_current_alert_types(ET.SOFT_DISABLE) + + elif self.ss_state_machine.soft_disable_timer <= 0: + self.state = State.disabled + + # PAUSED + elif self.state == State.paused: + if self.check_contains(ET.ENABLE): + if self.check_contains(ET.NO_ENTRY): + self.add_current_alert_types(ET.NO_ENTRY) + + else: + if self.check_contains(ET.OVERRIDE_LATERAL): + self.state = State.overriding + else: + self.state = State.enabled + self.add_current_alert_types(ET.ENABLE) + + # OVERRIDING + elif self.state == State.overriding: + if self.check_contains(ET.SOFT_DISABLE): + self.state = State.softDisabling + if not self.selfdrive.enabled: + self.ss_state_machine.soft_disable_timer = int(SOFT_DISABLE_TIME / DT_CTRL) + self.ss_state_machine.current_alert_types.append(ET.SOFT_DISABLE) + elif not self.check_contains(ET.OVERRIDE_LATERAL): + self.state = State.enabled + else: + self.ss_state_machine.current_alert_types += [ET.OVERRIDE_LATERAL] + + # DISABLED + elif self.state == State.disabled: + if self.check_contains(ET.ENABLE): + if self.check_contains(ET.NO_ENTRY): + if self.check_contains_in_list(): + self.state = State.paused + self.add_current_alert_types(ET.NO_ENTRY) + + else: + if self.check_contains(ET.OVERRIDE_LATERAL): + self.state = State.overriding + else: + self.state = State.enabled + self.add_current_alert_types(ET.ENABLE) + + # check if MADS is engaged and actuators are enabled + enabled = self.state in ENABLED_STATES + active = self.state in ACTIVE_STATES + if active: + self.add_current_alert_types(ET.WARNING) + + return enabled, active diff --git a/sunnypilot/mads/tests/test_mads_state_machine.py b/openpilot/sunnypilot/mads/tests/test_mads_state_machine.py similarity index 97% rename from sunnypilot/mads/tests/test_mads_state_machine.py rename to openpilot/sunnypilot/mads/tests/test_mads_state_machine.py index 7bc556a0fc..14549119fd 100644 --- a/sunnypilot/mads/tests/test_mads_state_machine.py +++ b/openpilot/sunnypilot/mads/tests/test_mads_state_machine.py @@ -8,7 +8,7 @@ See the LICENSE.md file in the root directory for more details. import pytest from pytest_mock import MockerFixture -from cereal import custom +from openpilot.cereal import custom from openpilot.common.realtime import DT_CTRL from openpilot.sunnypilot.mads.state import StateMachine, SOFT_DISABLE_TIME from openpilot.selfdrive.selfdrived.events import ET, NormalPermanentAlert, Events @@ -29,7 +29,7 @@ def make_event(event_types): event = {} for ev in event_types: event[ev] = NormalPermanentAlert("alert") - EVENTS_SP[0] = event + EVENTS_SP[0] = event # type: ignore[assignment] # ty: ignore[invalid-assignment] return 0 diff --git a/openpilot/sunnypilot/mads/tests/test_mads_steering_mode.py b/openpilot/sunnypilot/mads/tests/test_mads_steering_mode.py new file mode 100644 index 0000000000..3b7e27a86f --- /dev/null +++ b/openpilot/sunnypilot/mads/tests/test_mads_steering_mode.py @@ -0,0 +1,242 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" + +import pytest + +from openpilot.cereal import log, custom +from opendbc.car import structs +from openpilot.selfdrive.selfdrived.events import Events +from openpilot.sunnypilot.selfdrive.selfdrived.events import EventsSP +from openpilot.sunnypilot.mads.helpers import MadsSteeringModeOnBrake, read_steering_mode_param +from openpilot.sunnypilot.mads.mads import ModularAssistiveDrivingSystem +from opendbc.sunnypilot.car.tesla.values import TeslaFlagsSP + +State = custom.ModularAssistiveDrivingSystem.ModularAssistiveDrivingSystemState +EventName = log.OnroadEvent.EventName +EventNameSP = custom.OnroadEventSP.EventName +SafetyModel = structs.CarParams.SafetyModel + + +def make_car_state(brake_pressed=False, regen_braking=False, standstill=False, v_ego=0.0): + cs = structs.CarState() + cs.brakePressed = brake_pressed + cs.regenBraking = regen_braking + cs.standstill = standstill + cs.vEgo = v_ego + cs.cruiseState.available = True + return cs + + +def make_panda_state(mocker, controls_allowed_lateral=True): + ps = mocker.MagicMock() + ps.controlsAllowedLateral = controls_allowed_lateral + ps.safetyModel = SafetyModel.hyundai + return ps + + +def make_mads(mocker, steering_mode): + sd = mocker.MagicMock() + sd.CP = structs.CarParams() + sd.CP.brand = "hyundai" + sd.CP_SP = structs.CarParamsSP() + sd.params = mocker.MagicMock() + sd.params.get_bool = mocker.MagicMock(side_effect=lambda k: { + "Mads": True, "MadsMainCruiseAllowed": False, + "DisengageOnAccelerator": True, "MadsUnifiedEngagementMode": False, + }.get(k, False)) + sd.params.get = mocker.MagicMock(return_value=steering_mode) + sd.events = Events() + sd.events_sp = EventsSP() + sd.enabled = False + sd.enabled_prev = False + sd.initialized = True + sd.CS_prev = make_car_state() + sd.sm = {'pandaStates': [make_panda_state(mocker)]} + sd.state_machine = mocker.MagicMock() + + mads = ModularAssistiveDrivingSystem(sd) + mads.enabled_toggle = True + mads.steering_mode_on_brake = steering_mode + return mads, sd + + +def run_frames(mads, sd, cs, n=1): + for _ in range(n): + mads.update(cs) + sd.CS_prev = cs + sd.events.clear() + sd.events_sp.clear() + + +# should_silent_lkas_enable across all modes + +class TestShouldSilentLkasEnable: + @pytest.mark.parametrize("brake,regen", [(True, False), (False, True)]) + def test_pause_blocks_reenable_on_braking_at_standstill(self, mocker, brake, regen): + mads, _ = make_mads(mocker, MadsSteeringModeOnBrake.PAUSE) + cs = make_car_state(brake_pressed=brake, regen_braking=regen, standstill=True) + assert mads.should_silent_lkas_enable(cs) is False + + def test_pause_allows_reenable_on_brake_release(self, mocker): + mads, _ = make_mads(mocker, MadsSteeringModeOnBrake.PAUSE) + cs = make_car_state(standstill=True) + assert mads.should_silent_lkas_enable(cs) is True + + def test_remain_active_ignores_brake(self, mocker): + mads, _ = make_mads(mocker, MadsSteeringModeOnBrake.REMAIN_ACTIVE) + cs = make_car_state(brake_pressed=True, standstill=True) + assert mads.should_silent_lkas_enable(cs) is True + + def test_disengage_ignores_brake_for_silent_enable(self, mocker): + mads, _ = make_mads(mocker, MadsSteeringModeOnBrake.DISENGAGE) + cs = make_car_state(brake_pressed=True, standstill=True) + assert mads.should_silent_lkas_enable(cs) is True + + +# pause + +class TestPauseMode: + def test_stays_paused_at_standstill_brake_held(self, mocker): + mads, sd = make_mads(mocker, MadsSteeringModeOnBrake.PAUSE) + mads.state_machine.state = State.enabled + mads.enabled = True + mads.active = True + + sd.events.add(EventName.pedalPressed) + run_frames(mads, sd, make_car_state(brake_pressed=True, v_ego=15.0)) + assert mads.state_machine.state == State.paused + + sd.sm['pandaStates'] = [make_panda_state(mocker, False)] + run_frames(mads, sd, make_car_state(brake_pressed=True, standstill=True), n=250) + assert mads.state_machine.state == State.paused + + def test_resumes_on_brake_release_at_standstill(self, mocker): + mads, sd = make_mads(mocker, MadsSteeringModeOnBrake.PAUSE) + mads.state_machine.state = State.paused + mads.enabled = True + mads.active = False + + run_frames(mads, sd, make_car_state(standstill=True)) + assert mads.state_machine.state == State.enabled + + def test_full_cycle_moving_to_standstill(self, mocker): + mads, sd = make_mads(mocker, MadsSteeringModeOnBrake.PAUSE) + mads.state_machine.state = State.enabled + mads.enabled = True + mads.active = True + + sd.events.add(EventName.pedalPressed) + run_frames(mads, sd, make_car_state(brake_pressed=True, v_ego=15.0)) + assert mads.state_machine.state == State.paused + + sd.sm['pandaStates'] = [make_panda_state(mocker, False)] + run_frames(mads, sd, make_car_state(brake_pressed=True, standstill=True), n=250) + assert mads.state_machine.state == State.paused + + sd.sm['pandaStates'] = [make_panda_state(mocker, True)] + run_frames(mads, sd, make_car_state(standstill=True)) + assert mads.state_machine.state == State.enabled + + +# disengage + +class TestDisengageMode: + def test_brake_while_enabled_disables(self, mocker): + mads, sd = make_mads(mocker, MadsSteeringModeOnBrake.DISENGAGE) + mads.state_machine.state = State.enabled + mads.enabled = True + mads.active = True + + sd.events.add(EventName.pedalPressed) + run_frames(mads, sd, make_car_state(brake_pressed=True, v_ego=10.0)) + assert mads.state_machine.state == State.disabled + + def test_brake_sends_lkas_disable_when_enabled(self, mocker): + mads, sd = make_mads(mocker, MadsSteeringModeOnBrake.DISENGAGE) + mads.state_machine.state = State.enabled + mads.enabled = True + mads.active = True + + sd.events.add(EventName.pedalPressed) + mads.update_events(make_car_state(brake_pressed=True, v_ego=5.0)) + assert sd.events_sp.has(EventNameSP.lkasDisable) + + +# remain active + +class TestRemainActiveMode: + def test_brake_does_not_pause_or_disable(self, mocker): + mads, sd = make_mads(mocker, MadsSteeringModeOnBrake.REMAIN_ACTIVE) + mads.state_machine.state = State.enabled + mads.enabled = True + mads.active = True + + sd.events.add(EventName.pedalPressed) + run_frames(mads, sd, make_car_state(brake_pressed=True, v_ego=10.0)) + assert mads.state_machine.state == State.enabled + + +# lateral mismatch counter + +class TestLateralMismatchCounter: + def test_no_accumulation_while_paused(self, mocker): + mads, sd = make_mads(mocker, MadsSteeringModeOnBrake.PAUSE) + mads.state_machine.state = State.paused + mads.enabled = True + mads.active = False + sd.sm['pandaStates'] = [make_panda_state(mocker, False)] + + run_frames(mads, sd, make_car_state(brake_pressed=True, standstill=True), n=250) + assert mads.lateral_mismatch_counter == 0 + + def test_accumulates_when_active_and_panda_disagrees(self, mocker): + mads, sd = make_mads(mocker, MadsSteeringModeOnBrake.PAUSE) + mads.enabled = True + mads.active = True + sd.sm['pandaStates'] = [make_panda_state(mocker, False)] + + for _ in range(200): + mads.data_sample() + assert mads.lateral_mismatch_counter == 200 + + +# brand restrictions + +class TestBrandSteeringModeRestrictions: + def test_rivian_forced_to_disengage(self, mocker): + CP = structs.CarParams() + CP.brand = "rivian" + CP_SP = structs.CarParamsSP() + params = mocker.MagicMock() + assert read_steering_mode_param(CP, CP_SP, params) == MadsSteeringModeOnBrake.DISENGAGE + params.get.assert_not_called() + + def test_tesla_without_vehicle_bus_forced_to_disengage(self, mocker): + CP = structs.CarParams() + CP.brand = "tesla" + CP_SP = structs.CarParamsSP() + CP_SP.flags = 0 + params = mocker.MagicMock() + assert read_steering_mode_param(CP, CP_SP, params) == MadsSteeringModeOnBrake.DISENGAGE + + def test_tesla_with_vehicle_bus_uses_param(self, mocker): + CP = structs.CarParams() + CP.brand = "tesla" + CP_SP = structs.CarParamsSP() + CP_SP.flags = TeslaFlagsSP.HAS_VEHICLE_BUS + params = mocker.MagicMock() + params.get = mocker.MagicMock(return_value=MadsSteeringModeOnBrake.REMAIN_ACTIVE) + assert read_steering_mode_param(CP, CP_SP, params) == MadsSteeringModeOnBrake.REMAIN_ACTIVE + + @pytest.mark.parametrize("brand", ["hyundai", "toyota", "honda", "gm"]) + def test_other_brands_use_param(self, mocker, brand): + CP = structs.CarParams() + CP.brand = brand + CP_SP = structs.CarParamsSP() + params = mocker.MagicMock() + params.get = mocker.MagicMock(return_value=MadsSteeringModeOnBrake.REMAIN_ACTIVE) + assert read_steering_mode_param(CP, CP_SP, params) == MadsSteeringModeOnBrake.REMAIN_ACTIVE diff --git a/openpilot/sunnypilot/mapd/__init__.py b/openpilot/sunnypilot/mapd/__init__.py new file mode 100644 index 0000000000..57525254ce --- /dev/null +++ b/openpilot/sunnypilot/mapd/__init__.py @@ -0,0 +1,5 @@ +import os +from openpilot.common.basedir import BASEDIR + +MAPD_BIN_DIR = os.path.join(BASEDIR, 'openpilot', 'third_party/mapd_pfeiferj') +MAPD_PATH = os.path.join(MAPD_BIN_DIR, 'mapd') diff --git a/sunnypilot/mapd/live_map_data/__init__.py b/openpilot/sunnypilot/mapd/live_map_data/__init__.py similarity index 100% rename from sunnypilot/mapd/live_map_data/__init__.py rename to openpilot/sunnypilot/mapd/live_map_data/__init__.py diff --git a/openpilot/sunnypilot/mapd/live_map_data/base_map_data.py b/openpilot/sunnypilot/mapd/live_map_data/base_map_data.py new file mode 100644 index 0000000000..ca79ce1c6b --- /dev/null +++ b/openpilot/sunnypilot/mapd/live_map_data/base_map_data.py @@ -0,0 +1,65 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from abc import abstractmethod, ABC + +import openpilot.cereal.messaging as messaging +from openpilot.common.params import Params +from openpilot.common.constants import CV +from openpilot.selfdrive.car.cruise import V_CRUISE_UNSET +from openpilot.sunnypilot.navd.helpers import coordinate_from_param + +MAX_SPEED_LIMIT = V_CRUISE_UNSET * CV.KPH_TO_MS + + +class BaseMapData(ABC): + def __init__(self): + self.params = Params() + + self.sm = messaging.SubMaster(['liveLocationKalman']) + self.pm = messaging.PubMaster(['liveMapDataSP']) + + self.localizer_valid = False + self.last_bearing = None + self.last_position = coordinate_from_param("LastGPSPositionLLK", self.params) + + @abstractmethod + def update_location(self) -> None: + pass + + @abstractmethod + def get_current_speed_limit(self) -> float: + pass + + @abstractmethod + def get_next_speed_limit_and_distance(self) -> tuple[float, float]: + pass + + @abstractmethod + def get_current_road_name(self) -> str: + pass + + def publish(self) -> None: + speed_limit = self.get_current_speed_limit() + next_speed_limit, next_speed_limit_distance = self.get_next_speed_limit_and_distance() + + mapd_sp_send = messaging.new_message('liveMapDataSP') + mapd_sp_send.valid = self.sm['liveLocationKalman'].gpsOK + live_map_data = mapd_sp_send.liveMapDataSP + + live_map_data.speedLimitValid = bool(MAX_SPEED_LIMIT > speed_limit > 0) + live_map_data.speedLimit = speed_limit + live_map_data.speedLimitAheadValid = bool(MAX_SPEED_LIMIT > next_speed_limit > 0) + live_map_data.speedLimitAhead = next_speed_limit + live_map_data.speedLimitAheadDistance = next_speed_limit_distance + live_map_data.roadName = self.get_current_road_name() + + self.pm.send('liveMapDataSP', mapd_sp_send) + + def tick(self) -> None: + self.sm.update(0) + self.update_location() + self.publish() diff --git a/openpilot/sunnypilot/mapd/live_map_data/debug.py b/openpilot/sunnypilot/mapd/live_map_data/debug.py new file mode 100644 index 0000000000..00783d58df --- /dev/null +++ b/openpilot/sunnypilot/mapd/live_map_data/debug.py @@ -0,0 +1,56 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +# DISCLAIMER: This code is intended principally for development and debugging purposes. +# Although it provides a standalone entry point to the program, users should refer +# to the actual implementations for consumption. Usage outside of development scenarios +# is not advised and could lead to unpredictable results. + +import threading +import traceback + +from openpilot.cereal import messaging +from openpilot.common.gps import get_gps_location_service +from openpilot.common.params import Params +from openpilot.common.realtime import config_realtime_process +from openpilot.sunnypilot.selfdrive.controls.lib.speed_limit.common import Policy +from openpilot.sunnypilot.selfdrive.controls.lib.speed_limit.speed_limit_resolver import SpeedLimitResolver +from openpilot.sunnypilot.mapd.live_map_data import get_debug + + +def excepthook(args): + get_debug(f'MapD: Threading exception:\n{args}') + traceback.print_exception(args.exc_type, args.exc_value, args.exc_traceback) + + +def live_map_data_sp_thread(): + config_realtime_process([0, 1, 2, 3], 5) + + params = Params() + gps_location_service = get_gps_location_service(params) + + while True: + live_map_data_sp_thread_debug(gps_location_service) + + +def live_map_data_sp_thread_debug(gps_location_service): + _sub_master = messaging.SubMaster(['carState', 'livePose', 'liveMapDataSP', 'longitudinalPlanSP', 'carStateSP', gps_location_service]) + _sub_master.update() + + v_ego = _sub_master['carState'].vEgo + _resolver = SpeedLimitResolver() + _resolver.policy = Policy.car_state_priority + _resolver.update(v_ego, _sub_master) + print(_resolver.speed_limit, _resolver.distance, _resolver.source) + + +def main(): + threading.excepthook = excepthook + live_map_data_sp_thread() + + +if __name__ == "__main__": + main() diff --git a/openpilot/sunnypilot/mapd/live_map_data/osm_map_data.py b/openpilot/sunnypilot/mapd/live_map_data/osm_map_data.py new file mode 100644 index 0000000000..e6cbce0674 --- /dev/null +++ b/openpilot/sunnypilot/mapd/live_map_data/osm_map_data.py @@ -0,0 +1,61 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import json +import math +import platform + +from openpilot.cereal import log +from openpilot.common.params import Params +from openpilot.sunnypilot.mapd.live_map_data.base_map_data import BaseMapData +from openpilot.sunnypilot.navd.helpers import Coordinate + + +class OsmMapData(BaseMapData): + def __init__(self): + super().__init__() + self.mem_params = Params("/dev/shm/params") if platform.system() != "Darwin" else self.params + + def update_location(self) -> None: + location = self.sm['liveLocationKalman'] + self.localizer_valid = (location.status == log.LiveLocationKalman.Status.valid) and location.positionGeodetic.valid + + if self.localizer_valid: + self.last_bearing = math.degrees(location.calibratedOrientationNED.value[2]) + self.last_position = Coordinate(location.positionGeodetic.value[0], location.positionGeodetic.value[1]) + + if self.last_position is None: + return + + params = { + "latitude": self.last_position.latitude, + "longitude": self.last_position.longitude, + } + + if self.last_bearing is not None: + params['bearing'] = self.last_bearing + + self.mem_params.put("LastGPSPosition", json.dumps(params), block=True) + + def get_current_speed_limit(self) -> float: + return float(self.mem_params.get("MapSpeedLimit") or 0.0) + + def get_current_road_name(self) -> str: + return str(self.mem_params.get("RoadName") or "") + + def get_next_speed_limit_and_distance(self) -> tuple[float, float]: + next_speed_limit_section_str = self.mem_params.get("NextMapSpeedLimit") + next_speed_limit_section = next_speed_limit_section_str if next_speed_limit_section_str else {} + next_speed_limit = next_speed_limit_section.get('speedlimit', 0.0) + next_speed_limit_latitude = next_speed_limit_section.get('latitude') + next_speed_limit_longitude = next_speed_limit_section.get('longitude') + next_speed_limit_distance = 0.0 + + if next_speed_limit_latitude and next_speed_limit_longitude: + next_speed_limit_coordinates = Coordinate(next_speed_limit_latitude, next_speed_limit_longitude) + next_speed_limit_distance = (self.last_position or Coordinate(0, 0)).distance_to(next_speed_limit_coordinates) + + return next_speed_limit, next_speed_limit_distance diff --git a/sunnypilot/mapd/live_map_data/standalone.py b/openpilot/sunnypilot/mapd/live_map_data/standalone.py similarity index 100% rename from sunnypilot/mapd/live_map_data/standalone.py rename to openpilot/sunnypilot/mapd/live_map_data/standalone.py diff --git a/sunnypilot/mapd/mapd_installer.py b/openpilot/sunnypilot/mapd/mapd_installer.py similarity index 84% rename from sunnypilot/mapd/mapd_installer.py rename to openpilot/sunnypilot/mapd/mapd_installer.py index a151dd4807..9f2e72720a 100755 --- a/sunnypilot/mapd/mapd_installer.py +++ b/openpilot/sunnypilot/mapd/mapd_installer.py @@ -14,34 +14,41 @@ import requests from pathlib import Path from urllib.request import urlopen -from cereal import messaging +from openpilot.cereal import messaging from openpilot.common.params import Params -from openpilot.sunnypilot.mapd.mapd_manager import MAPD_PATH, MAPD_BIN_DIR -from openpilot.system.hardware.hw import Paths +from openpilot.common.hardware.hw import Paths from openpilot.common.spinner import Spinner -from openpilot.system.version import is_prebuilt +from openpilot.common.version import is_prebuilt +from openpilot.sunnypilot.mapd import MAPD_PATH, MAPD_BIN_DIR import openpilot.system.sentry as sentry -VERSION = 'v1.9.0' +VERSION = "v1.12.0" URL = f"https://github.com/pfeiferj/openpilot-mapd/releases/download/{VERSION}/mapd" +def update_installed_version(version: str, params: Params = None) -> None: + if params is None: + params = Params() + + params.put("MapdVersion", version, block=True) + + class MapdInstallManager: def __init__(self, spinner_ref: Spinner): self._spinner = spinner_ref + self._params = Params() def download(self) -> None: self.ensure_directories_exist() self._download_file() - self.update_installed_version(VERSION) + update_installed_version(VERSION, self._params) def check_and_download(self) -> None: if self.download_needed(): self.download() - @staticmethod - def download_needed() -> bool: - return not os.path.exists(MAPD_PATH) or MapdInstallManager.get_installed_version() != VERSION + def download_needed(self) -> bool: + return not os.path.exists(MAPD_PATH) or self.get_installed_version() != VERSION @staticmethod def ensure_directories_exist() -> None: @@ -82,13 +89,8 @@ class MapdInstallManager: temp_file.unlink() logging.error("Failed to download file after all retries") - @staticmethod - def update_installed_version(version: str) -> None: - Params().put("MapdVersion", version) - - @staticmethod - def get_installed_version() -> str: - return Params().get("MapdVersion", encoding="utf-8") or "" + def get_installed_version(self) -> str: + return str(self._params.get("MapdVersion") or "") def wait_for_internet_connection(self, return_on_failure: bool = False) -> bool: max_retries = 10 @@ -122,7 +124,7 @@ class MapdInstallManager: return if self.wait_for_internet_connection(return_on_failure=True): - self._spinner.update(f"Downloading pfeiferj's mapd [{install_manager.get_installed_version()}] => [{VERSION}].") + self._spinner.update(f"Downloading pfeiferj's mapd [{self.get_installed_version()}] => [{VERSION}].") time.sleep(0.1) self.check_and_download() self._spinner.close() @@ -146,7 +148,7 @@ if __name__ == "__main__": if is_prebuilt(): debug_msg = f"[DEBUG] This is prebuilt, no mapd install required. VERSION: [{VERSION}], Param [{install_manager.get_installed_version()}]" spinner.update(debug_msg) - install_manager.update_installed_version(VERSION) + update_installed_version(VERSION) else: spinner.update(f"Checking if mapd is installed and valid. Prebuilt [{is_prebuilt()}]") install_manager.non_prebuilt_install() diff --git a/sunnypilot/mapd/mapd_manager.py b/openpilot/sunnypilot/mapd/mapd_manager.py similarity index 79% rename from sunnypilot/mapd/mapd_manager.py rename to openpilot/sunnypilot/mapd/mapd_manager.py index 342ba3fe7b..2251289bbe 100755 --- a/sunnypilot/mapd/mapd_manager.py +++ b/openpilot/sunnypilot/mapd/mapd_manager.py @@ -6,28 +6,26 @@ This file is part of sunnypilot and is licensed under the MIT License. See the LICENSE.md file in the root directory for more details. """ import json -import time import platform import os import glob import shutil +from datetime import datetime -from openpilot.common.basedir import BASEDIR from openpilot.common.params import Params from openpilot.common.realtime import Ratekeeper, config_realtime_process from openpilot.common.swaglog import cloudlog from openpilot.selfdrive.selfdrived.alertmanager import set_offroad_alert from openpilot.sunnypilot.mapd.live_map_data.osm_map_data import OsmMapData -from openpilot.system.hardware.hw import Paths +from openpilot.common.hardware.hw import Paths +from openpilot.sunnypilot.mapd import MAPD_PATH +from openpilot.sunnypilot.mapd.mapd_installer import VERSION, update_installed_version # PFEIFER - MAPD {{ params = Params() mem_params = Params("/dev/shm/params") if platform.system() != "Darwin" else params # }} PFEIFER - MAPD -MAPD_BIN_DIR = os.path.join(BASEDIR, 'third_party/mapd_pfeiferj') -MAPD_PATH = os.path.join(MAPD_BIN_DIR, 'mapd') - def get_files_for_cleanup() -> list[str]: paths = [ @@ -57,20 +55,20 @@ def cleanup_old_osm_data(files_to_remove: list[str]) -> None: shutil.rmtree(file, ignore_errors=False) -def request_refresh_osm_location_data(nations: list[str], states: list[str] = None) -> None: - params.put("OsmDownloadedDate", str(time.time())) - params.put_bool("OsmDbUpdatesCheck", False) +def request_refresh_osm_location_data(nations: list[str], states: list[str] | None = None) -> None: + params.put("OsmDownloadedDate", str(datetime.now().timestamp()), block=True) + params.put_bool("OsmDbUpdatesCheck", False, block=True) - osm_download_locations = json.dumps({ + osm_download_locations = { "nations": nations, "states": states or [] - }) + } - print(f"Downloading maps for {osm_download_locations}") - mem_params.put("OSMDownloadLocations", osm_download_locations) + print(f"Downloading maps for {json.dumps(osm_download_locations)}") + mem_params.put("OSMDownloadLocations", osm_download_locations, block=True) -def filter_nations_and_states(nations: list[str], states: list[str] = None) -> tuple[list[str], list[str]]: +def filter_nations_and_states(nations: list[str], states: list[str] | None = None) -> tuple[list[str], list[str]]: """Filters and prepares nation and state data for OSM map download. If the nation is 'US' and a specific state is provided, the nation 'US' is removed from the list. @@ -100,23 +98,22 @@ def filter_nations_and_states(nations: list[str], states: list[str] = None) -> t def update_osm_db() -> None: - # last_downloaded_date = float(params.get('OsmDownloadedDate', encoding='utf-8') or 0.0) - # if params.get_bool("OsmDbUpdatesCheck") or time.time() - last_downloaded_date >= 604800: # 7 days * 24 hours/day * 60 if params.get_bool("OsmDbUpdatesCheck"): cleanup_old_osm_data(get_files_for_cleanup()) - country = params.get('OsmLocationName', encoding='utf-8') - state = params.get('OsmStateName', encoding='utf-8') or "All" + country = params.get("OsmLocationName", return_default=True) + state = params.get("OsmStateName", return_default=True) filtered_nations, filtered_states = filter_nations_and_states([country], [state]) request_refresh_osm_location_data(filtered_nations, filtered_states) if not mem_params.get("OSMDownloadBounds"): - mem_params.put("OSMDownloadBounds", "") + mem_params.put("OSMDownloadBounds", "", block=True) if not mem_params.get("LastGPSPosition"): - mem_params.put("LastGPSPosition", "{}") + mem_params.put("LastGPSPosition", "{}", block=True) def main_thread(): + update_installed_version(VERSION, params) config_realtime_process([0, 1, 2, 3], 5) rk = Ratekeeper(1, print_delay_threshold=None) @@ -131,7 +128,7 @@ def main_thread(): cloudlog.exception(f"mapd: failed to make {Paths.mapd_root()}") while True: - show_alert = get_files_for_cleanup() and params.get_bool("OsmLocal") + show_alert = bool(get_files_for_cleanup() and params.get_bool("OsmLocal")) set_offroad_alert("Offroad_OSMUpdateRequired", show_alert, "This alert will be cleared when new maps are downloaded.") update_osm_db() diff --git a/sunnypilot/selfdrive/__init__.py b/openpilot/sunnypilot/mapd/tests/__init__.py similarity index 100% rename from sunnypilot/selfdrive/__init__.py rename to openpilot/sunnypilot/mapd/tests/__init__.py diff --git a/openpilot/sunnypilot/mapd/tests/mapd_hash b/openpilot/sunnypilot/mapd/tests/mapd_hash new file mode 100644 index 0000000000..0322ea97ca --- /dev/null +++ b/openpilot/sunnypilot/mapd/tests/mapd_hash @@ -0,0 +1 @@ +fdb3b49ee19956e6ce09fdc3373cbba557f1263b2180e9f344c1d4053852284b \ No newline at end of file diff --git a/openpilot/sunnypilot/mapd/tests/test_mapd_version.py b/openpilot/sunnypilot/mapd/tests/test_mapd_version.py new file mode 100644 index 0000000000..5619d2ec29 --- /dev/null +++ b/openpilot/sunnypilot/mapd/tests/test_mapd_version.py @@ -0,0 +1,19 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from openpilot.sunnypilot import get_file_hash +from openpilot.sunnypilot.mapd import MAPD_PATH +from openpilot.sunnypilot.mapd.update_version import MAPD_HASH_PATH + + +class TestMapdVersion: + def test_compare_versions(self): + mapd_hash = get_file_hash(MAPD_PATH) + + with open(MAPD_HASH_PATH) as f: + current_hash = f.read().strip() + + assert current_hash == mapd_hash, "Run sunnypilot/mapd/update_version.py to update the current mapd version and hash" diff --git a/openpilot/sunnypilot/mapd/update_version.py b/openpilot/sunnypilot/mapd/update_version.py new file mode 100755 index 0000000000..b6ca2a757f --- /dev/null +++ b/openpilot/sunnypilot/mapd/update_version.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python3 +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import argparse +import os +import re + +from openpilot.sunnypilot import get_file_hash +from openpilot.common.basedir import BASEDIR +from openpilot.sunnypilot.mapd import MAPD_PATH + +MAPD_HASH_PATH = os.path.join(BASEDIR, "openpilot", "sunnypilot", "mapd", "tests", "mapd_hash") +MAPD_VERSION_PATH = os.path.join(BASEDIR, "openpilot", "sunnypilot", "mapd", "mapd_installer.py") + + +def update_mapd_hash(): + mapd_hash = get_file_hash(MAPD_PATH) + + with open(MAPD_HASH_PATH, "w") as f: + f.write(mapd_hash) + + print(f"Generated and updated new mapd hash to {MAPD_HASH_PATH}") + + +def get_current_mapd_version(path: str) -> str: + print("[GET CURRENT MAPD VERSION]") + with open(path) as f: + for line in f: + if line.strip().startswith("VERSION"): + # Match VERSION = 'v1.11.0' or VERSION="v1.11.0" (with optional spaces) + match = re.search(r'VERSION\s*=\s*[\'"]([^\'"]+)[\'"]', line) + if match: + ver = match.group(1) + print(f'Current mapd version: "{ver}"') + return ver + else: + print("[ERROR] VERSION line found but no quoted value detected.") + return "" + print("[ERROR] VERSION not found in file!") + return "" + + +def update_mapd_version(ver: str, path: str): + print("[CHANGE CURRENT MAPD VERSION]") + + with open(path) as f: + lines = f.readlines() + + found = False + new_lines = [] + for line in lines: + if not found and line.startswith("VERSION ="): + new_lines.append(f'VERSION = "{ver}"\n') + found = True + new_lines.extend(lines[lines.index(line) + 1:]) + break + else: + new_lines.append(line) + + if not found: + print("[ERROR] VERSION line not found! Aborting without writing.") + return + + with open(path, "w") as f: + f.writelines(new_lines) + + print(f'New mapd version: "{ver}"') + print("[DONE]") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Update mapd version and hash") + parser.add_argument("--new_ver", type=str, help="New mapd version") + args = parser.parse_args() + + if not args.new_ver: + print("Warning: No new mapd version provided. Use --new_ver to specify") + print("Example:") + print(" python sunnypilot/mapd/update_version.py --new_ver \"v1.12.0\"") + print("Current mapd version and hash will not be updated! (aborted)") + exit(0) + + current_ver = get_current_mapd_version(MAPD_VERSION_PATH) + new_ver = f"{args.new_ver}" + if current_ver == new_ver: + print(f'Proposed mapd version: "{new_ver}"') + confirm = input("Proposed mapd version is the same as the current mapd version. Confirm? (y/n): ").upper().strip() + if confirm != "Y": + print("Current mapd version and hash will not be updated! (aborted)") + exit(0) + + update_mapd_version(new_ver, MAPD_VERSION_PATH) + update_mapd_hash() diff --git a/docs/glossary.toml b/openpilot/sunnypilot/mapd/version.py similarity index 100% rename from docs/glossary.toml rename to openpilot/sunnypilot/mapd/version.py diff --git a/sunnypilot/modeld/.gitignore b/openpilot/sunnypilot/modeld_v2/.gitignore similarity index 100% rename from sunnypilot/modeld/.gitignore rename to openpilot/sunnypilot/modeld_v2/.gitignore diff --git a/openpilot/sunnypilot/modeld_v2/SConscript b/openpilot/sunnypilot/modeld_v2/SConscript new file mode 100644 index 0000000000..81affc625a --- /dev/null +++ b/openpilot/sunnypilot/modeld_v2/SConscript @@ -0,0 +1,99 @@ +import os +import glob + +from openpilot.common.transformations.camera import _ar_ox_fisheye, _os_fisheye +from openpilot.common.transformations.model import MEDMODEL_INPUT_SIZE +from openpilot.common.hardware import HARDWARE, PC + +Import('env', 'arch', 'release') +lenv = env.Clone() +tinygrad_files = ["#"+x for x in glob.glob(env.Dir("#tinygrad_repo").relpath + "/**", recursive=True, root_dir=env.Dir("#").abspath) if 'pycache' not in x] + + +def get_camera_configs(): + DEVICE_RESOLUTIONS = { + "tici": (_ar_ox_fisheye.width, _ar_ox_fisheye.height), + "tizi": (_ar_ox_fisheye.width, _ar_ox_fisheye.height), + "mici": (_os_fisheye.width, _os_fisheye.height), + } + if release or PC or 'CI' in os.environ: + return set(DEVICE_RESOLUTIONS.values()) + return [DEVICE_RESOLUTIONS[HARDWARE.get_device_type()]] + +CAMERA_CONFIGS = get_camera_configs() + +tg_flags = { + 'larch64': 'DEV=QCOM FLOAT16=1 NOLOCALS=1 JIT_BATCH_SIZE=0', + 'Darwin': f'DEV=CPU HOME={os.path.expanduser("~")}', +}.get(arch, 'DEV=CPU:LLVM') + +image_flag = { + 'larch64': 'IMAGE=2', +}.get(arch, 'IMAGE=0') + +model_w, model_h = MEDMODEL_INPUT_SIZE +from openpilot.selfdrive.modeld.constants import ModelConstants +frame_skip = ModelConstants.MODEL_RUN_FREQ // ModelConstants.MODEL_CONTEXT_FREQ +camera_res_args = ' '.join(f'{cw}x{ch}' for cw, ch in CAMERA_CONFIGS) + +pythonpath_string = 'PYTHONPATH="${PYTHONPATH}:' + env.Dir("#tinygrad_repo").abspath + ':' + env.Dir("#").abspath + '"' +compile_modeld_script = File("compile_modeld.py").abspath +upstream_compile_script = File(Dir("#openpilot/selfdrive/modeld").File("compile_modeld.py").abspath) +script_deps = [File("compile_modeld.py"), upstream_compile_script] + +def compile_combined(model_type, onnx_args, output_name): + output_pkl = File(f"models/{output_name}").abspath + cmd = (f'{pythonpath_string} {tg_flags} {image_flag} python3 {compile_modeld_script} ' + f'--model-type {model_type} ' + f'--model-size {model_w}x{model_h} ' + f'--camera-resolutions {camera_res_args} ' + f'{onnx_args} ' + f'--frame-skip {frame_skip} ' + f'--output {output_pkl}') + onnx_files = [f for f in onnx_args.split() if f.endswith('.onnx')] + return lenv.Command(output_pkl, tinygrad_files + script_deps + [File(f) for f in onnx_files if os.path.isfile(f)], cmd) + +# Vision + Policy (stock default model) +vision_onnx = File("models/driving_vision.onnx").abspath +policy_onnx = File("models/driving_policy.onnx").abspath +if os.path.isfile(vision_onnx) and os.path.isfile(policy_onnx): + compile_combined('vision_policy', + f'--vision-onnx {vision_onnx} --policy-onnx {policy_onnx}', + 'driving_combined_tinygrad.pkl') + +# Vision + Off-Policy +off_policy_onnx = File("models/driving_off_policy.onnx").abspath +if os.path.isfile(vision_onnx) and os.path.isfile(off_policy_onnx): + policy_arg = f'--policy-onnx {policy_onnx}' if os.path.isfile(policy_onnx) else '' + compile_combined('vision_multi_policy', + f'--vision-onnx {vision_onnx} {policy_arg} --off-policy-onnx {off_policy_onnx}', + 'driving_combined_multi_tinygrad.pkl') + +# Vision + On-Policy + Off-Policy +on_policy_onnx = File("models/driving_on_policy.onnx").abspath +if os.path.isfile(vision_onnx) and os.path.isfile(on_policy_onnx) and os.path.isfile(off_policy_onnx): + compile_combined('vision_multi_policy', + f'--vision-onnx {vision_onnx} --off-policy-onnx {off_policy_onnx} --on-policy-onnx {on_policy_onnx}', + 'driving_combined_tri_tinygrad.pkl') + +# Supercombo +supercombo_onnx = File("models/supercombo.onnx").abspath +if os.path.isfile(supercombo_onnx): + compile_combined('supercombo', + f'--supercombo-onnx {supercombo_onnx}', + 'driving_combined_supercombo_tinygrad.pkl') + +if PC: + inputs = tinygrad_files + [File(Dir("#openpilot/sunnypilot/modeld_v2").File("install_models_pc.py").abspath)] + outputs = [] + model_dir = Dir("models").abspath + cmd = f'python3 {Dir("#openpilot/sunnypilot/modeld_v2").abspath}/install_models_pc.py {model_dir}' + + for model_name in ['supercombo', 'driving_vision', 'driving_off_policy', 'driving_on_policy', 'driving_policy']: + if File(f"models/{model_name}.onnx").exists(): + inputs.append(File(f"models/{model_name}.onnx")) + inputs.append(File(f"models/{model_name}_tinygrad.pkl")) + outputs.append(File(f"models/{model_name}_metadata.pkl")) + if outputs: + lenv.Command(outputs, inputs, cmd) + diff --git a/sunnypilot/modeld_v2/__init__.py b/openpilot/sunnypilot/modeld_v2/__init__.py similarity index 100% rename from sunnypilot/modeld_v2/__init__.py rename to openpilot/sunnypilot/modeld_v2/__init__.py diff --git a/openpilot/sunnypilot/modeld_v2/camera_offset_helper.py b/openpilot/sunnypilot/modeld_v2/camera_offset_helper.py new file mode 100644 index 0000000000..7502c3eeb0 --- /dev/null +++ b/openpilot/sunnypilot/modeld_v2/camera_offset_helper.py @@ -0,0 +1,39 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import numpy as np + +from openpilot.common.transformations.camera import DEVICE_CAMERAS + + +class CameraOffsetHelper: + def __init__(self): + self.camera_offset = 0.0 + self.actual_camera_offset = 0.0 + + @staticmethod + def apply_camera_offset(model_transform, intrinsics, height, offset_param): + cy = intrinsics[1, 2] + shear = np.eye(3, dtype=np.float32) + shear[0, 1] = offset_param / height + shear[0, 2] = -offset_param / height * cy + model_transform = (shear @ model_transform).astype(np.float32) + return model_transform + + def set_offset(self, offset): + self.camera_offset = offset + + def update(self, model_transform_main, model_transform_extra, sm, main_wide_camera): + self.actual_camera_offset = (0.9 * self.actual_camera_offset) + (0.1 * self.camera_offset) + dc = DEVICE_CAMERAS[(str(sm['deviceState'].deviceType), str(sm['roadCameraState'].sensor))] + height = sm["liveCalibration"].height[0] if sm['liveCalibration'].height else 1.22 + + intrinsics_main = dc.ecam.intrinsics if main_wide_camera else dc.fcam.intrinsics + model_transform_main = self.apply_camera_offset(model_transform_main, intrinsics_main, height, self.actual_camera_offset) + + intrinsics_extra = dc.ecam.intrinsics + model_transform_extra = self.apply_camera_offset(model_transform_extra, intrinsics_extra, height, self.actual_camera_offset) + return model_transform_main, model_transform_extra diff --git a/openpilot/sunnypilot/modeld_v2/compile_modeld.py b/openpilot/sunnypilot/modeld_v2/compile_modeld.py new file mode 100755 index 0000000000..fd58038ceb --- /dev/null +++ b/openpilot/sunnypilot/modeld_v2/compile_modeld.py @@ -0,0 +1,480 @@ +#!/usr/bin/env python3 +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" + +import argparse +import os +import pickle +import time +from functools import partial +from collections import defaultdict + +import numpy as np +from tinygrad.tensor import Tensor +from tinygrad.device import Device +from tinygrad.engine.jit import TinyJit + +from openpilot.selfdrive.modeld.compile_modeld import ( + NV12Frame, make_frame_prepare, + shift_and_sample, sample_skip, sample_desire, +) + +MODEL_TYPES = ('vision_policy', 'supercombo', 'vision_multi_policy') + + +def _detect_desire_key(policy_input_shapes): + for k in policy_input_shapes: + if k.startswith('desire'): + return k + return None + + +def _detect_vision_keys(vision_input_shapes): + img_keys = sorted([k for k in vision_input_shapes if 'img' in k]) + road_key = next((k for k in img_keys if 'big' not in k), None) + wide_key = next((k for k in img_keys if 'big' in k), None) + if road_key is None or wide_key is None: + raise ValueError(f"Cannot determine road/wide image keys from {list(vision_input_shapes.keys())}") + return road_key, wide_key + + +def make_split_input_queues(vision_input_shapes, policy_input_shapes, frame_skip, device): + road_key, _ = _detect_vision_keys(vision_input_shapes) + img = vision_input_shapes[road_key] + n_frames = img[1] // 6 + img_buf_shape = (frame_skip * (n_frames - 1) + 1, 6, img[2], img[3]) + + fb = policy_input_shapes['features_buffer'] + desire_key = _detect_desire_key(policy_input_shapes) + dp = policy_input_shapes[desire_key] + tc = policy_input_shapes.get('traffic_convention', (1, 2)) + + npy = { + 'desire': np.zeros(dp[2], dtype=np.float32), + 'traffic_convention': np.zeros(tc, dtype=np.float32), + 'tfm': np.zeros((3, 3), dtype=np.float32), + 'big_tfm': np.zeros((3, 3), dtype=np.float32), + } + + handled = {'features_buffer', desire_key, 'traffic_convention'} + for key, shape in policy_input_shapes.items(): + if key in handled: + continue + npy[key] = np.zeros(shape, dtype=np.float32) + + input_queues = { + 'img_q': Tensor(np.zeros(img_buf_shape, dtype=np.uint8), device=device).contiguous().realize(), + 'big_img_q': Tensor(np.zeros(img_buf_shape, dtype=np.uint8), device=device).contiguous().realize(), + 'feat_q': Tensor(np.zeros((frame_skip * (fb[1] - 1) + 1, fb[0], fb[2]), dtype=np.float32), device=device).contiguous().realize(), + 'desire_q': Tensor(np.zeros((frame_skip * dp[1], dp[0], dp[2]), dtype=np.float32), device=device).contiguous().realize(), + **{k: Tensor(v, device='NPY').realize() for k, v in npy.items()}, + } + return input_queues, npy + + +def make_run_split_policy(vision_runner, policy_runner, nv12: NV12Frame, model_w, model_h, + vision_features_slice, frame_skip, desire_key, extra_policy_keys, + vision_road_key, vision_wide_key, prepare_only=False): + frame_prepare = make_frame_prepare(nv12, model_w, model_h) + sample_skip_fn = partial(sample_skip, frame_skip=frame_skip) + sample_desire_fn = partial(sample_desire, frame_skip=frame_skip) + + def run_policy(img_q, big_img_q, feat_q, desire_q, desire, traffic_convention, tfm, big_tfm, frame, big_frame, **extra): + npy_tensors = [tfm.to(Device.DEFAULT), big_tfm.to(Device.DEFAULT), + desire.to(Device.DEFAULT), traffic_convention.to(Device.DEFAULT)] + extra_device = {k: extra[k].to(Device.DEFAULT) for k in extra_policy_keys} + Tensor.realize(*npy_tensors, *extra_device.values()) + tfm, big_tfm, desire, traffic_convention = npy_tensors + + img = shift_and_sample(img_q, frame_prepare(frame, tfm).unsqueeze(0), sample_skip_fn) + big_img = shift_and_sample(big_img_q, frame_prepare(big_frame, big_tfm).unsqueeze(0), sample_skip_fn) + + if prepare_only: + return img, big_img + + vision_out = next(iter(vision_runner({vision_road_key: img, vision_wide_key: big_img}).values())).cast('float32') + + new_feat = vision_out[:, vision_features_slice].reshape(1, -1).unsqueeze(0) + feat_buf = shift_and_sample(feat_q, new_feat, sample_skip_fn) + desire_buf = shift_and_sample(desire_q, desire.reshape(1, 1, -1), sample_desire_fn) + + inputs = {'features_buffer': feat_buf, desire_key: desire_buf, 'traffic_convention': traffic_convention, **extra_device} + policy_out = next(iter(policy_runner(inputs).values())).cast('float32') + + return vision_out, policy_out + return run_policy + + +def compile_split_policy(nv12: NV12Frame, model_w, model_h, prepare_only, frame_skip, + vision_runner, policy_runner, vision_metadata, policy_metadata): + print(f"Compiling combined policy JIT for {nv12.width}x{nv12.height} (prepare_only={prepare_only})...") + + vision_features_slice = vision_metadata['output_slices']['hidden_state'] + vision_input_shapes = vision_metadata['input_shapes'] + policy_input_shapes = policy_metadata['input_shapes'] + desire_key = _detect_desire_key(policy_input_shapes) + extra_policy_keys = [k for k in policy_input_shapes if k not in ('features_buffer', desire_key, 'traffic_convention')] + vision_road_key, vision_wide_key = _detect_vision_keys(vision_input_shapes) + + _run = make_run_split_policy(vision_runner, policy_runner, nv12, model_w, model_h, + vision_features_slice, frame_skip, desire_key, extra_policy_keys, + vision_road_key, vision_wide_key, prepare_only) + run_policy_jit = TinyJit(_run, prune=True) + + SEED = 42 + + def random_inputs_run_fn(fn, seed, test_val=None, test_buffers=None, expect_match=True): + input_queues, npy = make_split_input_queues(vision_input_shapes, policy_input_shapes, frame_skip, Device.DEFAULT) + rng = np.random.default_rng(seed) + Tensor.manual_seed(seed) + + testing = test_val is not None or test_buffers is not None + n_runs = 1 if testing else 3 + + for i in range(n_runs): + frame = Tensor.randint(nv12.size, low=0, high=256, dtype='uint8').realize() + big_frame = Tensor.randint(nv12.size, low=0, high=256, dtype='uint8').realize() + for v in npy.values(): + v[:] = rng.standard_normal(v.shape).astype(v.dtype) + Device.default.synchronize() + st = time.perf_counter() + outs = fn(**input_queues, frame=frame, big_frame=big_frame) + mt = time.perf_counter() + Device.default.synchronize() + et = time.perf_counter() + print(f" [{i+1}/{n_runs}] enqueue {(mt-st)*1e3:6.2f} ms -- total {(et-st)*1e3:6.2f} ms") + + if i == 0: + val = [np.copy(v.numpy()) for v in outs] + buffers = [np.copy(v.numpy().copy()) for v in input_queues.values()] + + if test_val is not None: + match = all(np.array_equal(a, b) for a, b in zip(val, test_val, strict=True)) + assert match == expect_match, f"outputs {'differ from' if expect_match else 'match'} baseline (seed={seed})" + if test_buffers is not None: + match = all(np.array_equal(a, b) for a, b in zip(buffers, test_buffers, strict=True)) + assert match == expect_match, f"buffers {'differ from' if expect_match else 'match'} baseline (seed={seed})" + return fn, val, buffers + + print('capture + replay') + run_policy_jit, test_val, test_buffers = random_inputs_run_fn(run_policy_jit, SEED) + + print('pickle round trip') + run_policy_jit = pickle.loads(pickle.dumps(run_policy_jit)) + random_inputs_run_fn(run_policy_jit, SEED, test_val, test_buffers, expect_match=True) + random_inputs_run_fn(run_policy_jit, SEED+1, test_val, test_buffers, expect_match=False) + return run_policy_jit + + +def derive_frame_skip(vision_input_shapes, policy_input_shapes): + fb = policy_input_shapes.get('features_buffer') + if fb is None: + return 1 + fb_history = fb[1] + if fb_history >= 99: + return 1 + return 4 + + +def make_supercombo_input_queues(input_shapes, frame_skip, device): + img_shape = input_shapes.get('img', input_shapes.get('input_imgs')) + if img_shape is None: + raise ValueError("No img input found in model shapes") + + n_frames = img_shape[1] // 6 + img_buf_shape = (frame_skip * (n_frames - 1) + 1, 6, img_shape[2], img_shape[3]) + + numpy_keys = {} + queue_keys = {} + + for key, shape in input_shapes.items(): + if 'img' in key: + continue + if len(shape) == 3 and shape[1] > 1: + if key.startswith('desire'): + numpy_keys[key] = np.zeros(shape[2], dtype=np.float32) + queue_keys[f'{key}_q'] = Tensor( + np.zeros((frame_skip * shape[1], shape[0], shape[2]), dtype=np.float32), + device=device).contiguous().realize() + elif key == 'features_buffer': + queue_keys['feat_q'] = Tensor( + np.zeros((frame_skip * (shape[1] - 1) + 1, shape[0], shape[2]), dtype=np.float32), + device=device).contiguous().realize() + else: + numpy_keys[key] = np.zeros(shape, dtype=np.float32) + elif len(shape) == 2: + numpy_keys[key] = np.zeros(shape, dtype=np.float32) + + if 'traffic_convention' not in numpy_keys: + tc_shape = input_shapes.get('traffic_convention', (1, 2)) + numpy_keys['traffic_convention'] = np.zeros(tc_shape, dtype=np.float32) + + numpy_keys['tfm'] = np.zeros((3, 3), dtype=np.float32) + numpy_keys['big_tfm'] = np.zeros((3, 3), dtype=np.float32) + + input_queues = { + 'img_q': Tensor(np.zeros(img_buf_shape, dtype=np.uint8), device=device).contiguous().realize(), + 'big_img_q': Tensor(np.zeros(img_buf_shape, dtype=np.uint8), device=device).contiguous().realize(), + **queue_keys, + **{k: Tensor(v, device='NPY').realize() for k, v in numpy_keys.items()}, + } + return input_queues, numpy_keys + + +def make_run_supercombo(model_runner, nv12: NV12Frame, model_w, model_h, + features_slice, frame_skip, input_shapes, prepare_only=False): + frame_prepare = make_frame_prepare(nv12, model_w, model_h) + sample_skip_fn = partial(sample_skip, frame_skip=frame_skip) + sample_desire_fn = partial(sample_desire, frame_skip=frame_skip) + + desire_key = _detect_desire_key(input_shapes) + if desire_key is None: + raise ValueError(f"No desire* key found in input_shapes: {list(input_shapes.keys())}") + road_img_key, wide_img_key = _detect_vision_keys(input_shapes) + extra_policy_keys = [k for k in input_shapes + if k not in (desire_key, 'features_buffer', 'traffic_convention') + and 'img' not in k] + + def run_supercombo(img_q, big_img_q, feat_q, desire_q, + frame, big_frame, **kwargs): + desire = kwargs.get(desire_key) + traffic_convention = kwargs.get('traffic_convention') + tfm = kwargs['tfm'] + big_tfm = kwargs['big_tfm'] + + tfm = tfm.to(Device.DEFAULT) + big_tfm = big_tfm.to(Device.DEFAULT) + desire = desire.to(Device.DEFAULT) + traffic_convention = traffic_convention.to(Device.DEFAULT) + Tensor.realize(tfm, big_tfm, desire, traffic_convention) + + img = shift_and_sample(img_q, frame_prepare(frame, tfm).unsqueeze(0), sample_skip_fn) + big_img = shift_and_sample(big_img_q, frame_prepare(big_frame, big_tfm).unsqueeze(0), sample_skip_fn) + + if prepare_only: + return img, big_img + + desire_buf = shift_and_sample(desire_q, desire.reshape(1, 1, -1), sample_desire_fn) + feat_buf = sample_skip_fn(feat_q) + + inputs = {road_img_key: img, wide_img_key: big_img, + desire_key: desire_buf, 'features_buffer': feat_buf, + 'traffic_convention': traffic_convention} + for k in extra_policy_keys: + if k in kwargs: + inputs[k] = kwargs[k].to(Device.DEFAULT) + + model_out = next(iter(model_runner(inputs).values())).cast('float32') + + new_feat = model_out[:, features_slice].reshape(1, -1).unsqueeze(0) + shift_and_sample(feat_q, new_feat, sample_skip_fn) + + return model_out + + return run_supercombo + + +def make_run_vision_multi_policy(vision_runner, policy_runners, nv12: NV12Frame, model_w, model_h, + vision_features_slice, frame_skip, desire_key, extra_policy_keys, + vision_road_key, vision_wide_key, prepare_only=False): + frame_prepare = make_frame_prepare(nv12, model_w, model_h) + sample_skip_fn = partial(sample_skip, frame_skip=frame_skip) + sample_desire_fn = partial(sample_desire, frame_skip=frame_skip) + + def run_multi_policy(img_q, big_img_q, feat_q, desire_q, desire, + traffic_convention, tfm, big_tfm, frame, big_frame, **extra): + npy_tensors = [tfm.to(Device.DEFAULT), big_tfm.to(Device.DEFAULT), + desire.to(Device.DEFAULT), traffic_convention.to(Device.DEFAULT)] + extra_device = {k: extra[k].to(Device.DEFAULT) for k in extra_policy_keys} + Tensor.realize(*npy_tensors, *extra_device.values()) + tfm, big_tfm, desire, traffic_convention = npy_tensors + + img = shift_and_sample(img_q, frame_prepare(frame, tfm).unsqueeze(0), sample_skip_fn) + big_img = shift_and_sample(big_img_q, frame_prepare(big_frame, big_tfm).unsqueeze(0), sample_skip_fn) + + if prepare_only: + return img, big_img + + vision_out = next(iter(vision_runner({vision_road_key: img, vision_wide_key: big_img}).values())).cast('float32') + + new_feat = vision_out[:, vision_features_slice].reshape(1, -1).unsqueeze(0) + feat_buf = shift_and_sample(feat_q, new_feat, sample_skip_fn) + desire_buf = shift_and_sample(desire_q, desire.reshape(1, 1, -1), sample_desire_fn) + + inputs = {'features_buffer': feat_buf, desire_key: desire_buf, 'traffic_convention': traffic_convention, **extra_device} + + policy_outputs = [] + for runner in policy_runners: + policy_out = next(iter(runner(inputs).values())).cast('float32') + policy_outputs.append(policy_out) + + return (vision_out, *policy_outputs) + + return run_multi_policy + + +def _warmup_and_serialize(run_jit, input_queues, npy, nv12): + for i in range(3): + rng = np.random.default_rng(42 + i) + frame = Tensor.randint(nv12.size, low=0, high=256, dtype='uint8').realize() + big_frame = Tensor.randint(nv12.size, low=0, high=256, dtype='uint8').realize() + for v in npy.values(): + v[:] = rng.standard_normal(v.shape).astype(v.dtype) + Device.default.synchronize() + st = time.perf_counter() + run_jit(**input_queues, frame=frame, big_frame=big_frame) + mt = time.perf_counter() + Device.default.synchronize() + et = time.perf_counter() + print(f" [{i + 1}/3] enqueue {(mt - st) * 1e3:6.2f} ms -- total {(et - st) * 1e3:6.2f} ms") + return pickle.loads(pickle.dumps(run_jit)) + + +def compile_supercombo(nv12: NV12Frame, model_w, model_h, prepare_only, frame_skip, + model_runner, metadata): + print(f"Compiling combined supercombo JIT for {nv12.width}x{nv12.height} (prepare_only={prepare_only})...") + + features_slice = metadata['output_slices']['hidden_state'] + input_shapes = metadata['input_shapes'] + + _run = make_run_supercombo(model_runner, nv12, model_w, model_h, + features_slice, frame_skip, input_shapes, prepare_only) + run_jit = TinyJit(_run, prune=True) + + input_queues, npy = make_supercombo_input_queues(input_shapes, frame_skip, Device.DEFAULT) + + run_jit = _warmup_and_serialize(run_jit, input_queues, npy, nv12) + return run_jit + + +def compile_multi_policy(nv12: NV12Frame, model_w, model_h, prepare_only, frame_skip, + vision_runner, policy_runners, vision_metadata, policy_metadata): + print(f"Compiling combined multi-policy JIT for {nv12.width}x{nv12.height} (prepare_only={prepare_only})...") + + vision_features_slice = vision_metadata['output_slices']['hidden_state'] + vision_input_shapes = vision_metadata['input_shapes'] + policy_input_shapes = policy_metadata['input_shapes'] + desire_key = _detect_desire_key(policy_input_shapes) + extra_policy_keys = [k for k in policy_input_shapes if k not in ('features_buffer', desire_key, 'traffic_convention')] + vision_road_key, vision_wide_key = _detect_vision_keys(vision_input_shapes) + + _run = make_run_vision_multi_policy(vision_runner, policy_runners, nv12, model_w, model_h, + vision_features_slice, frame_skip, desire_key, extra_policy_keys, + vision_road_key, vision_wide_key, prepare_only) + run_jit = TinyJit(_run, prune=True) + + input_queues, npy = make_split_input_queues(vision_input_shapes, policy_input_shapes, frame_skip, Device.DEFAULT) + + run_jit = _warmup_and_serialize(run_jit, input_queues, npy, nv12) + return run_jit + + +def _parse_size(s): + w, h = s.lower().split('x') + return int(w), int(h) + + +if __name__ == "__main__": + from tinygrad.nn.onnx import OnnxRunner + from openpilot.system.camerad.cameras.nv12_info import get_nv12_info + from openpilot.selfdrive.modeld.get_model_metadata import make_metadata_dict + + p = argparse.ArgumentParser(description="Compile combined JIT pkl for sunnypilot modeld_v2") + p.add_argument('--model-type', choices=MODEL_TYPES, required=True) + p.add_argument('--model-size', type=_parse_size, required=True, help='model input WxH') + p.add_argument('--camera-resolutions', type=_parse_size, nargs='+', required=True) + p.add_argument('--frame-skip', type=int, default=None, help='frame skip value (auto-derived if not provided)') + p.add_argument('--output', required=True) + + p.add_argument('--vision-onnx', help='vision ONNX (for split models)') + p.add_argument('--policy-onnx', help='policy ONNX (for vision_policy)') + p.add_argument('--off-policy-onnx', help='off-policy ONNX (for vision_multi_policy)') + p.add_argument('--on-policy-onnx', help='on-policy ONNX (for vision_multi_policy)') + p.add_argument('--supercombo-onnx', help='supercombo ONNX (for supercombo)') + + args = p.parse_args() + out = defaultdict(dict) + + if args.model_type == 'vision_policy': + assert args.vision_onnx and args.policy_onnx + vision_runner = OnnxRunner(args.vision_onnx) + policy_runner = OnnxRunner(args.policy_onnx) + out['metadata']['vision'] = make_metadata_dict(args.vision_onnx) + out['metadata']['policy'] = make_metadata_dict(args.policy_onnx) + + frame_skip = args.frame_skip if args.frame_skip is not None else derive_frame_skip(out['metadata']['vision']['input_shapes'], + out['metadata']['policy']['input_shapes']) + + for cam_w, cam_h in args.camera_resolutions: + nv12 = NV12Frame(cam_w, cam_h, *get_nv12_info(cam_w, cam_h)) + model_w, model_h = args.model_size + out[(cam_w, cam_h)] = { + name: compile_split_policy(nv12, model_w, model_h, prepare_only, frame_skip, + vision_runner, policy_runner, + out['metadata']['vision'], out['metadata']['policy']) + for name, prepare_only in [('warp_enqueue', True), ('run_policy', False)] + } + + elif args.model_type == 'supercombo': + assert args.supercombo_onnx + model_runner = OnnxRunner(args.supercombo_onnx) + out['metadata']['model'] = make_metadata_dict(args.supercombo_onnx) + + frame_skip = args.frame_skip if args.frame_skip is not None else derive_frame_skip({}, out['metadata']['model']['input_shapes']) + + for cam_w, cam_h in args.camera_resolutions: + nv12 = NV12Frame(cam_w, cam_h, *get_nv12_info(cam_w, cam_h)) + model_w, model_h = args.model_size + out[(cam_w, cam_h)] = { + name: compile_supercombo(nv12, model_w, model_h, prepare_only, frame_skip, + model_runner, out['metadata']['model']) + for name, prepare_only in [('warp_enqueue', True), ('run_policy', False)] + } + + elif args.model_type == 'vision_multi_policy': + assert args.vision_onnx + vision_runner = OnnxRunner(args.vision_onnx) + out['metadata']['vision'] = make_metadata_dict(args.vision_onnx) + + policy_runners = [] + policy_onnxes = [] + if args.policy_onnx: + policy_onnxes.append(('policy', args.policy_onnx)) + if args.off_policy_onnx: + policy_onnxes.append(('off_policy', args.off_policy_onnx)) + if args.on_policy_onnx: + policy_onnxes.append(('on_policy', args.on_policy_onnx)) + + for name, onnx_path in policy_onnxes: + runner = OnnxRunner(onnx_path) + policy_runners.append(runner) + out['metadata'][name] = make_metadata_dict(onnx_path) + + first_policy_key = policy_onnxes[0][0] + frame_skip = args.frame_skip if args.frame_skip is not None else derive_frame_skip(out['metadata']['vision']['input_shapes'], + out['metadata'][first_policy_key]['input_shapes']) + + for cam_w, cam_h in args.camera_resolutions: + nv12 = NV12Frame(cam_w, cam_h, *get_nv12_info(cam_w, cam_h)) + model_w, model_h = args.model_size + out[(cam_w, cam_h)] = { + name: compile_multi_policy(nv12, model_w, model_h, prepare_only, frame_skip, + vision_runner, policy_runners, + out['metadata']['vision'], out['metadata'][first_policy_key]) + for name, prepare_only in [('warp_enqueue', True), ('run_policy', False)] + } + + with open(args.output, "wb") as f: + pickle.dump(out, f) + pkl_size = os.path.getsize(args.output) + print(f"Saved combined JIT to {args.output} ({pkl_size / 1e6:.2f} MB)") + + from openpilot.common.file_chunker import chunk_file, get_chunk_targets + chunk_targets = get_chunk_targets(args.output, pkl_size) + chunk_file(args.output, chunk_targets) + num_chunks = len(chunk_targets) - 1 + print(f"Chunked into {num_chunks} file(s)") diff --git a/sunnypilot/modeld_v2/constants.py b/openpilot/sunnypilot/modeld_v2/constants.py similarity index 100% rename from sunnypilot/modeld_v2/constants.py rename to openpilot/sunnypilot/modeld_v2/constants.py diff --git a/openpilot/sunnypilot/modeld_v2/fill_model_msg.py b/openpilot/sunnypilot/modeld_v2/fill_model_msg.py new file mode 100644 index 0000000000..7d7854be11 --- /dev/null +++ b/openpilot/sunnypilot/modeld_v2/fill_model_msg.py @@ -0,0 +1,218 @@ +import os +import capnp +import numpy as np +from openpilot.cereal import log +from openpilot.sunnypilot.modeld_v2.constants import ModelConstants, Plan +from openpilot.sunnypilot.models.helpers import plan_x_idxs_helper +from openpilot.selfdrive.controls.lib.drive_helpers import get_curvature_from_plan + +SEND_RAW_PRED = os.getenv('SEND_RAW_PRED') + +ConfidenceClass = log.ModelDataV2.ConfidenceClass + + +def get_curvature_from_output(output, plan, vego, lat_action_t, mlsim): + if not mlsim: + if desired_curv := output.get('desired_curvature'): # If the model outputs the desired curvature, use that directly + return float(desired_curv[0, 0]) + + return float(get_curvature_from_plan(plan[:, Plan.T_FROM_CURRENT_EULER][:, 2], plan[:, Plan.ORIENTATION_RATE][:, 2], + ModelConstants.T_IDXS, vego, lat_action_t)) + + +class PublishState: + def __init__(self): + self.disengage_buffer = np.zeros(ModelConstants.CONFIDENCE_BUFFER_LEN*ModelConstants.DISENGAGE_WIDTH, dtype=np.float32) + self.prev_brake_5ms2_probs = np.zeros(ModelConstants.FCW_5MS2_PROBS_WIDTH, dtype=np.float32) + self.prev_brake_3ms2_probs = np.zeros(ModelConstants.FCW_3MS2_PROBS_WIDTH, dtype=np.float32) + +def fill_xyzt(builder, t, x, y, z, x_std=None, y_std=None, z_std=None): + builder.t = t + builder.x = x.tolist() + builder.y = y.tolist() + builder.z = z.tolist() + if x_std is not None: + builder.xStd = x_std.tolist() + if y_std is not None: + builder.yStd = y_std.tolist() + if z_std is not None: + builder.zStd = z_std.tolist() + +def fill_xyvat(builder, t, x, y, v, a, x_std=None, y_std=None, v_std=None, a_std=None): + builder.t = t + builder.x = x.tolist() + builder.y = y.tolist() + builder.v = v.tolist() + builder.a = a.tolist() + if x_std is not None: + builder.xStd = x_std.tolist() + if y_std is not None: + builder.yStd = y_std.tolist() + if v_std is not None: + builder.vStd = v_std.tolist() + if a_std is not None: + builder.aStd = a_std.tolist() + +def fill_xyz_poly(builder, degree, x, y, z): + xyz = np.stack([x, y, z], axis=1) + coeffs = np.polynomial.polynomial.polyfit(ModelConstants.T_IDXS, xyz, deg=degree) + builder.xCoefficients = coeffs[:, 0].tolist() + builder.yCoefficients = coeffs[:, 1].tolist() + builder.zCoefficients = coeffs[:, 2].tolist() + +def fill_lane_line_meta(builder, lane_lines, lane_line_probs): + builder.leftY = lane_lines[1].y[0] + builder.leftProb = lane_line_probs[1] + builder.rightY = lane_lines[2].y[0] + builder.rightProb = lane_line_probs[2] + +def fill_model_msg(base_msg: capnp._DynamicStructBuilder, extended_msg: capnp._DynamicStructBuilder, + net_output_data: dict[str, np.ndarray], action: log.ModelDataV2.Action, + publish_state: PublishState, vipc_frame_id: int, vipc_frame_id_extra: int, + frame_id: int, frame_drop: float, timestamp_eof: int, model_execution_time: float, + valid: bool, model_meta) -> None: + frame_age = frame_id - vipc_frame_id if frame_id > vipc_frame_id else 0 + frame_drop_perc = frame_drop * 100 + extended_msg.valid = valid + base_msg.valid = valid + + driving_model_data = base_msg.drivingModelData + + driving_model_data.frameId = vipc_frame_id + driving_model_data.frameIdExtra = vipc_frame_id_extra + driving_model_data.frameDropPerc = frame_drop_perc + driving_model_data.modelExecutionTime = model_execution_time + driving_model_data.action = action + + modelV2 = extended_msg.modelV2 + modelV2.frameId = vipc_frame_id + modelV2.frameIdExtra = vipc_frame_id_extra + modelV2.frameAge = frame_age + modelV2.frameDropPerc = frame_drop_perc + modelV2.timestampEof = timestamp_eof + modelV2.modelExecutionTime = model_execution_time + + # plan + fill_xyzt(modelV2.position, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.POSITION].T, *net_output_data['plan_stds'][0,:,Plan.POSITION].T) + fill_xyzt(modelV2.velocity, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.VELOCITY].T) + fill_xyzt(modelV2.acceleration, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.ACCELERATION].T) + fill_xyzt(modelV2.orientation, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.T_FROM_CURRENT_EULER].T) + fill_xyzt(modelV2.orientationRate, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.ORIENTATION_RATE].T) + + # temporal pose + temporal_pose = modelV2.deprecated.temporalPose + if 'sim_pose' in net_output_data: + temporal_pose.trans = net_output_data['sim_pose'][0,:ModelConstants.POSE_WIDTH//2].tolist() + temporal_pose.transStd = net_output_data['sim_pose_stds'][0,:ModelConstants.POSE_WIDTH//2].tolist() + temporal_pose.rot = net_output_data['sim_pose'][0,ModelConstants.POSE_WIDTH//2:].tolist() + temporal_pose.rotStd = net_output_data['sim_pose_stds'][0,ModelConstants.POSE_WIDTH//2:].tolist() + else: + temporal_pose.trans = net_output_data['plan'][0,0,Plan.VELOCITY].tolist() + temporal_pose.transStd = net_output_data['plan_stds'][0,0,Plan.VELOCITY].tolist() + temporal_pose.rot = net_output_data['plan'][0,0,Plan.ORIENTATION_RATE].tolist() + temporal_pose.rotStd = net_output_data['plan_stds'][0,0,Plan.ORIENTATION_RATE].tolist() + + # poly path + fill_xyz_poly(driving_model_data.path, ModelConstants.POLY_PATH_DEGREE, *net_output_data['plan'][0,:,Plan.POSITION].T) + + # action (includes lateral planning now) + modelV2.action = action + + # times at X_IDXS of edges and lines + LINE_T_IDXS: list[float] = plan_x_idxs_helper(ModelConstants, Plan, net_output_data) + + # lane lines + modelV2.init('laneLines', 4) + for i in range(4): + lane_line = modelV2.laneLines[i] + fill_xyzt(lane_line, LINE_T_IDXS, np.array(ModelConstants.X_IDXS), net_output_data['lane_lines'][0,i,:,0], net_output_data['lane_lines'][0,i,:,1]) + modelV2.laneLineStds = net_output_data['lane_lines_stds'][0,:,0,0].tolist() + modelV2.laneLineProbs = net_output_data['lane_lines_prob'][0,1::2].tolist() + + fill_lane_line_meta(driving_model_data.laneLineMeta, modelV2.laneLines, modelV2.laneLineProbs) + + # road edges + modelV2.init('roadEdges', 2) + for i in range(2): + road_edge = modelV2.roadEdges[i] + fill_xyzt(road_edge, LINE_T_IDXS, np.array(ModelConstants.X_IDXS), net_output_data['road_edges'][0,i,:,0], net_output_data['road_edges'][0,i,:,1]) + modelV2.roadEdgeStds = net_output_data['road_edges_stds'][0,:,0,0].tolist() + + # leads + modelV2.init('leadsV3', 3) + for i in range(3): + lead = modelV2.leadsV3[i] + fill_xyvat(lead, ModelConstants.LEAD_T_IDXS, *net_output_data['lead'][0,i].T, *net_output_data['lead_stds'][0,i].T) + lead.prob = net_output_data['lead_prob'][0,i].tolist() + lead.probTime = ModelConstants.LEAD_T_OFFSETS[i] + + # meta + meta = modelV2.meta + meta.desireState = net_output_data['desire_state'][0].reshape(-1).tolist() + meta.desirePrediction = net_output_data['desire_pred'][0].reshape(-1).tolist() + meta.engagedProb = net_output_data['meta'][0,model_meta.ENGAGED].item() + meta.init('disengagePredictions') + disengage_predictions = meta.disengagePredictions + disengage_predictions.t = ModelConstants.META_T_IDXS + disengage_predictions.brakeDisengageProbs = net_output_data['meta'][0,model_meta.BRAKE_DISENGAGE].tolist() + disengage_predictions.gasDisengageProbs = net_output_data['meta'][0,model_meta.GAS_DISENGAGE].tolist() + disengage_predictions.steerOverrideProbs = net_output_data['meta'][0,model_meta.STEER_OVERRIDE].tolist() + disengage_predictions.brake3MetersPerSecondSquaredProbs = net_output_data['meta'][0,model_meta.HARD_BRAKE_3].tolist() + disengage_predictions.brake4MetersPerSecondSquaredProbs = net_output_data['meta'][0,model_meta.HARD_BRAKE_4].tolist() + disengage_predictions.brake5MetersPerSecondSquaredProbs = net_output_data['meta'][0,model_meta.HARD_BRAKE_5].tolist() + + if hasattr(model_meta, 'GAS_PRESS') and hasattr(model_meta, 'BRAKE_PRESS'): + disengage_predictions.gasPressProbs = net_output_data['meta'][0,model_meta.GAS_PRESS].tolist() + disengage_predictions.brakePressProbs = net_output_data['meta'][0,model_meta.BRAKE_PRESS].tolist() + + publish_state.prev_brake_5ms2_probs[:-1] = publish_state.prev_brake_5ms2_probs[1:] + publish_state.prev_brake_5ms2_probs[-1] = net_output_data['meta'][0,model_meta.HARD_BRAKE_5][0] + publish_state.prev_brake_3ms2_probs[:-1] = publish_state.prev_brake_3ms2_probs[1:] + publish_state.prev_brake_3ms2_probs[-1] = net_output_data['meta'][0,model_meta.HARD_BRAKE_3][0] + hard_brake_predicted = (publish_state.prev_brake_5ms2_probs > ModelConstants.FCW_THRESHOLDS_5MS2).all() and \ + (publish_state.prev_brake_3ms2_probs > ModelConstants.FCW_THRESHOLDS_3MS2).all() + meta.hardBrakePredicted = hard_brake_predicted.item() + + # confidence + if vipc_frame_id % (2*ModelConstants.MODEL_FREQ) == 0: + # any disengage prob + brake_disengage_probs = net_output_data['meta'][0,model_meta.BRAKE_DISENGAGE] + gas_disengage_probs = net_output_data['meta'][0,model_meta.GAS_DISENGAGE] + steer_override_probs = net_output_data['meta'][0,model_meta.STEER_OVERRIDE] + any_disengage_probs = 1-((1-brake_disengage_probs)*(1-gas_disengage_probs)*(1-steer_override_probs)) + # independent disengage prob for each 2s slice + ind_disengage_probs = np.r_[any_disengage_probs[0], np.diff(any_disengage_probs) / (1 - any_disengage_probs[:-1])] + # rolling buf for 2, 4, 6, 8, 10s + publish_state.disengage_buffer[:-ModelConstants.DISENGAGE_WIDTH] = publish_state.disengage_buffer[ModelConstants.DISENGAGE_WIDTH:] + publish_state.disengage_buffer[-ModelConstants.DISENGAGE_WIDTH:] = ind_disengage_probs + + score = 0. + for i in range(ModelConstants.DISENGAGE_WIDTH): + score += publish_state.disengage_buffer[i*ModelConstants.DISENGAGE_WIDTH+ModelConstants.DISENGAGE_WIDTH-1-i].item() / ModelConstants.DISENGAGE_WIDTH + if score < ModelConstants.RYG_GREEN: + modelV2.confidence = ConfidenceClass.green + elif score < ModelConstants.RYG_YELLOW: + modelV2.confidence = ConfidenceClass.yellow + else: + modelV2.confidence = ConfidenceClass.red + + # raw prediction if enabled + if SEND_RAW_PRED: + modelV2.rawPredictions = net_output_data['raw_pred'].tobytes() + +def fill_pose_msg(msg: capnp._DynamicStructBuilder, net_output_data: dict[str, np.ndarray], + vipc_frame_id: int, vipc_dropped_frames: int, timestamp_eof: int, live_calib_seen: bool) -> None: + msg.valid = live_calib_seen & (vipc_dropped_frames < 1) + cameraOdometry = msg.cameraOdometry + + cameraOdometry.frameId = vipc_frame_id + cameraOdometry.timestampEof = timestamp_eof + + cameraOdometry.trans = net_output_data['pose'][0,:3].tolist() + cameraOdometry.rot = net_output_data['pose'][0,3:].tolist() + cameraOdometry.wideFromDeviceEuler = net_output_data['wide_from_device_euler'][0,:].tolist() + cameraOdometry.roadTransformTrans = net_output_data['road_transform'][0,:3].tolist() + cameraOdometry.transStd = net_output_data['pose_stds'][0,:3].tolist() + cameraOdometry.rotStd = net_output_data['pose_stds'][0,3:].tolist() + cameraOdometry.wideFromDeviceEulerStd = net_output_data['wide_from_device_euler_stds'][0,:].tolist() + cameraOdometry.roadTransformTransStd = net_output_data['road_transform_stds'][0,:3].tolist() diff --git a/openpilot/sunnypilot/modeld_v2/get_model_metadata.py b/openpilot/sunnypilot/modeld_v2/get_model_metadata.py new file mode 100755 index 0000000000..838b1e9f40 --- /dev/null +++ b/openpilot/sunnypilot/modeld_v2/get_model_metadata.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +import sys +import pathlib +import codecs +import pickle +from typing import Any + +from tinygrad.nn.onnx import OnnxPBParser + + +class MetadataOnnxPBParser(OnnxPBParser): + def _parse_ModelProto(self) -> dict: + obj: dict[str, Any] = {"graph": {"input": [], "output": []}, "metadata_props": []} + for fid, wire_type in self._parse_message(self.reader.len): + match fid: + case 7: + obj["graph"] = self._parse_GraphProto() + case 14: + obj["metadata_props"].append(self._parse_StringStringEntryProto()) + case _: + self.reader.skip_field(wire_type) + return obj + + +def get_name_and_shape(value_info: dict[str, Any]) -> tuple[str, tuple[int, ...]]: + shape = tuple(int(dim) if isinstance(dim, int) else 0 for dim in value_info["parsed_type"].shape) + name = value_info["name"] + return name, shape + + +def get_metadata_value_by_name(model: dict[str, Any], name: str) -> str | Any: + for prop in model["metadata_props"]: + if prop["key"] == name: + return prop["value"] + return None + + +if __name__ == "__main__": + model_path = pathlib.Path(sys.argv[1]) + model = MetadataOnnxPBParser(model_path).parse() + output_slices = get_metadata_value_by_name(model, 'output_slices') + assert output_slices is not None, 'output_slices not found in metadata' + + metadata = { + 'model_checkpoint': get_metadata_value_by_name(model, 'model_checkpoint'), + 'output_slices': pickle.loads(codecs.decode(output_slices.encode(), "base64")), + 'input_shapes': dict(get_name_and_shape(x) for x in model["graph"]["input"]), + 'output_shapes': dict(get_name_and_shape(x) for x in model["graph"]["output"]), + } + + metadata_path = model_path.parent / (model_path.stem + '_metadata.pkl') + with open(metadata_path, 'wb') as f: + pickle.dump(metadata, f) + + print(f'saved metadata to {metadata_path}') diff --git a/openpilot/sunnypilot/modeld_v2/install_models_pc.py b/openpilot/sunnypilot/modeld_v2/install_models_pc.py new file mode 100755 index 0000000000..7bc2f4797c --- /dev/null +++ b/openpilot/sunnypilot/modeld_v2/install_models_pc.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python3 +import sys +import shutil +import pickle +import codecs +from pathlib import Path + +from openpilot.common.hardware.hw import Paths +from openpilot.sunnypilot.modeld_v2.get_model_metadata import MetadataOnnxPBParser, get_name_and_shape, get_metadata_value_by_name + + +def generate_metadata_pkl(model_path, output_path): + try: + model = MetadataOnnxPBParser(model_path).parse() + output_slices = get_metadata_value_by_name(model, 'output_slices') + if not output_slices: + return False + metadata = { + 'model_checkpoint': get_metadata_value_by_name(model, 'model_checkpoint'), + 'output_slices': pickle.loads(codecs.decode(output_slices.encode(), "base64")), + 'input_shapes': dict(get_name_and_shape(x) for x in model["graph"]["input"]), + 'output_shapes': dict(get_name_and_shape(x) for x in model["graph"]["output"]), + } + with open(output_path, 'wb') as f: + pickle.dump(metadata, f) + return True + except Exception: + return False + + +def install_models(model_dir): + model_dir = Path(model_dir) + models = ["driving_off_policy", "driving_on_policy", "driving_vision"] + found_models = [] + + for model in models: + if (model_dir / f"{model}.onnx").exists(): + found_models.append(model) + + if not found_models: + return + + try: + custom_name = input(f"Found models ({', '.join(found_models)}). Enter model short name (e.g. wmiv4): ").strip() + except EOFError: + return + + if not custom_name: + print("No name provided, skipping installation.") + return + + dest_dir = Path(Paths.model_root()) + dest_dir.mkdir(parents=True, exist_ok=True) + + for model in found_models: + onnx_path = model_dir / f"{model}.onnx" + tinygrad_pkl = model_dir / f"{model}_tinygrad.pkl" + metadata_pkl = model_dir / f"{model}_metadata.pkl" + + if not metadata_pkl.exists(): + generate_metadata_pkl(onnx_path, metadata_pkl) + + dest_tinygrad = dest_dir / f"{model}_{custom_name}_tinygrad.pkl" + dest_metadata = dest_dir / f"{model}_{custom_name}_metadata.pkl" + + if tinygrad_pkl.exists(): + shutil.move(str(tinygrad_pkl), str(dest_tinygrad)) + if metadata_pkl.exists(): + shutil.move(str(metadata_pkl), str(dest_metadata)) + +if __name__ == "__main__": + if len(sys.argv) < 2: + print("Usage: install_models_pc.py ") + sys.exit(1) + install_models(sys.argv[1]) diff --git a/sunnypilot/modeld_v2/meta_20hz.py b/openpilot/sunnypilot/modeld_v2/meta_20hz.py similarity index 100% rename from sunnypilot/modeld_v2/meta_20hz.py rename to openpilot/sunnypilot/modeld_v2/meta_20hz.py diff --git a/sunnypilot/modeld_v2/meta_helper.py b/openpilot/sunnypilot/modeld_v2/meta_helper.py similarity index 96% rename from sunnypilot/modeld_v2/meta_helper.py rename to openpilot/sunnypilot/modeld_v2/meta_helper.py index 3fa10b2415..bcf73adc6f 100644 --- a/sunnypilot/modeld_v2/meta_helper.py +++ b/openpilot/sunnypilot/modeld_v2/meta_helper.py @@ -1,5 +1,5 @@ from openpilot.sunnypilot.modeld_v2.constants import Meta -from cereal import custom +from openpilot.cereal import custom from openpilot.sunnypilot.modeld_v2.meta_20hz import Meta20hz from openpilot.sunnypilot.models.helpers import get_active_bundle diff --git a/sunnypilot/modeld_v2/modeld b/openpilot/sunnypilot/modeld_v2/modeld similarity index 100% rename from sunnypilot/modeld_v2/modeld rename to openpilot/sunnypilot/modeld_v2/modeld diff --git a/openpilot/sunnypilot/modeld_v2/modeld.py b/openpilot/sunnypilot/modeld_v2/modeld.py new file mode 100755 index 0000000000..86d5b05868 --- /dev/null +++ b/openpilot/sunnypilot/modeld_v2/modeld.py @@ -0,0 +1,458 @@ +#!/usr/bin/env python3 +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" + +import os +from openpilot.common.hardware import TICI +os.environ['DEV'] = 'QCOM' if TICI else 'CPU' +USBGPU = "USBGPU" in os.environ +if USBGPU: + os.environ['DEV'] = 'AMD' + os.environ['AMD_IFACE'] = 'USB' +import pickle +import time +import numpy as np +import openpilot.cereal.messaging as messaging +from openpilot.cereal import log +from opendbc.car.structs import car +from setproctitle import setproctitle +from openpilot.cereal.messaging import PubMaster, SubMaster +from msgq.visionipc import VisionIpcClient, VisionStreamType, VisionBuf +from opendbc.car.car_helpers import get_demo_car_params +from openpilot.common.swaglog import cloudlog +from openpilot.common.params import Params +from openpilot.common.filter_simple import FirstOrderFilter +from openpilot.common.realtime import config_realtime_process, DT_MDL +from openpilot.common.transformations.camera import DEVICE_CAMERAS +from openpilot.common.transformations.model import get_warp_matrix +from openpilot.system import sentry +from openpilot.selfdrive.controls.lib.desire_helper import DesireHelper +from openpilot.selfdrive.controls.lib.drive_helpers import get_accel_from_plan, smooth_value + +from openpilot.sunnypilot.modeld_v2.fill_model_msg import fill_model_msg, fill_pose_msg, PublishState, get_curvature_from_output +from openpilot.sunnypilot.modeld_v2.constants import Plan +from openpilot.sunnypilot.modeld_v2.meta_helper import load_meta_constants +from openpilot.sunnypilot.modeld_v2.camera_offset_helper import CameraOffsetHelper + +from openpilot.sunnypilot.livedelay.helpers import get_lat_delay +from openpilot.sunnypilot.modeld_v2.modeld_base import ModelStateBase +from openpilot.sunnypilot.models.helpers import get_active_bundle + +PROCESS_NAME = "openpilot.selfdrive.modeld.modeld_tinygrad" + + +def _pkl_exists(path): + from openpilot.common.file_chunker import get_manifest_path + return os.path.exists(path) or os.path.exists(get_manifest_path(path)) + + +def _find_driving_pkl(bundle): + if (override := os.environ.get('COMBINED_MODEL_PKL')) and _pkl_exists(override): + return override + if bundle is None or not bundle.models: + return None + from openpilot.common.hardware.hw import Paths + model_root = Paths.model_root() + + pkl_name = bundle.models[0].artifact.fileName + pkl_path = os.path.join(model_root, pkl_name) + if _pkl_exists(pkl_path): + return pkl_path + + +class FrameMeta: + frame_id: int = 0 + timestamp_sof: int = 0 + timestamp_eof: int = 0 + + def __init__(self, vipc=None): + if vipc is not None: + self.frame_id, self.timestamp_sof, self.timestamp_eof = vipc.frame_id, vipc.timestamp_sof, vipc.timestamp_eof + + +class ModelState(ModelStateBase): + inputs: dict[str, np.ndarray] + prev_desire: np.ndarray + + def __init__(self, cam_w: int, cam_h: int): + ModelStateBase.__init__(self) + + env_pkl = os.environ.get('COMBINED_MODEL_PKL') + if env_pkl and os.path.exists(env_pkl): + model_bundle = None + else: + model_bundle = get_active_bundle() + self.generation = model_bundle.generation if model_bundle is not None else None + overrides = {override.key: override.value for override in model_bundle.overrides} if model_bundle else {} + + self.LAT_SMOOTH_SECONDS = float(overrides.get('lat', ".0")) + self.LONG_SMOOTH_SECONDS = float(overrides.get('long', ".0")) + self.MIN_LAT_CONTROL_SPEED = 0.3 + self.PLANPLUS_CONTROL: float = 1.0 + + pkl_path = _find_driving_pkl(model_bundle) + assert pkl_path is not None, "No driving pkl found — all models must be compiled with compile_modeld.py" + self._init_combined(pkl_path, cam_w, cam_h, model_bundle) + + def _init_combined(self, pkl_path, cam_w, cam_h, bundle): + from tinygrad.tensor import Tensor + from openpilot.system.camerad.cameras.nv12_info import get_nv12_info + from openpilot.sunnypilot.modeld_v2.compile_modeld import derive_frame_skip, make_split_input_queues + from tinygrad.device import Device + + from openpilot.common.file_chunker import open_file_chunked + + cloudlog.warning(f"loading combined pkl: {pkl_path}") + jits = pickle.load(open_file_chunked(pkl_path)) + + self.DEV = Device.DEFAULT + + metadata = jits['metadata'] + if 'model' in metadata: + model_metadata = metadata['model'] + self.vision_output_slices = model_metadata['output_slices'] + self.policy_output_slices = {} + self._policy_slices_list = [] + self._combined_model_type = 'supercombo' + self._vision_input_names = [k for k in model_metadata['input_shapes'] if 'img' in k] + from openpilot.sunnypilot.modeld_v2.compile_modeld import make_supercombo_input_queues + frame_skip = derive_frame_skip({}, model_metadata['input_shapes']) + self.input_queues, self.numpy_inputs = make_supercombo_input_queues(model_metadata['input_shapes'], frame_skip, device=self.DEV) + else: + vision_metadata = metadata['vision'] + policy_keys = [k for k in metadata if k != 'vision'] + if policy_keys == ['policy']: + self._combined_model_type = 'split' + else: + self._combined_model_type = 'multi_policy' + self.vision_output_slices = vision_metadata['output_slices'] + self._policy_keys = policy_keys + self._policy_slices_list = [metadata[k]['output_slices'] for k in policy_keys] + self.policy_output_slices = self._policy_slices_list[0] + self._has_on_policy = any('on' in k.lower() for k in policy_keys) + first_policy_metadata = metadata[policy_keys[0]] + vision_input_shapes = vision_metadata['input_shapes'] + policy_input_shapes = first_policy_metadata['input_shapes'] + self._vision_input_names = [k for k in vision_input_shapes if 'img' in k] + frame_skip = derive_frame_skip(vision_input_shapes, policy_input_shapes) + self.input_queues, self.numpy_inputs = make_split_input_queues(vision_input_shapes, policy_input_shapes, frame_skip, device=self.DEV) + + from openpilot.sunnypilot.modeld_v2.parse_model_outputs_split import Parser as SplitParser + from openpilot.sunnypilot.modeld_v2.parse_model_outputs import Parser as CombinedParser + self.parser = SplitParser() if self._combined_model_type != 'supercombo' else CombinedParser() + + is_20hz = bundle.is20hz if bundle else self._combined_model_type in ('split', 'multi_policy') + if is_20hz: + from openpilot.sunnypilot.models.split_model_constants import SplitModelConstants + self.constants = SplitModelConstants() + else: + from openpilot.sunnypilot.modeld_v2.constants import ModelConstants + self.constants = ModelConstants() + + self.prev_desire = np.zeros(self.constants.DESIRE_LEN, dtype=np.float32) + self.full_frames: dict = {} + self._blob_cache: dict = {} + nv12_info = get_nv12_info(cam_w, cam_h) + self.frame_buf_params = dict.fromkeys(self._vision_input_names, nv12_info) + + self._run_policy = jits[(cam_w, cam_h)]['run_policy'] + self._warp_enqueue = jits[(cam_w, cam_h)]['warp_enqueue'] + road_name = next(k for k in self._vision_input_names if 'big' not in k) + yuv_size = self.frame_buf_params[road_name][3] + self._warp_enqueue( + **self.input_queues, + frame=Tensor(np.zeros(yuv_size, dtype=np.uint8), device=self.DEV).contiguous().realize(), + big_frame=Tensor(np.zeros(yuv_size, dtype=np.uint8), device=self.DEV).contiguous().realize()) + + + @property + def mlsim(self) -> bool: + return bool(self.generation is not None and self.generation >= 11) + + @property + def vision_input_names(self) -> list[str]: + return self._vision_input_names + + @property + def desire_key(self) -> str: + return next(k for k in self.numpy_inputs if k.startswith('desire')) + + def run(self, bufs: dict[str, VisionBuf], transforms: dict[str, np.ndarray], + inputs: dict[str, np.ndarray], prepare_only: bool) -> dict[str, np.ndarray] | None: + from tinygrad.tensor import Tensor + + for key in bufs.keys(): + ptr = np.frombuffer(bufs[key].data, dtype=np.uint8).ctypes.data + yuv_size = self.frame_buf_params[key][3] + cache_key = (key, ptr) + if cache_key not in self._blob_cache: + self._blob_cache[cache_key] = Tensor.from_blob(ptr, (yuv_size,), dtype='uint8', device=self.DEV) + self.full_frames[key] = self._blob_cache[cache_key] + + desire_key = self.desire_key + inputs[desire_key][0] = 0 + self.numpy_inputs[desire_key][:] = np.where(inputs[desire_key] - self.prev_desire > .99, inputs[desire_key], 0) + self.prev_desire[:] = inputs[desire_key] + for key in ('traffic_convention', 'lateral_control_params'): + if key in self.numpy_inputs and key in inputs: + self.numpy_inputs[key][:] = inputs[key] + + road_key = next(n for n in bufs if 'big' not in n) + wide_key = next(n for n in bufs if 'big' in n) + self.numpy_inputs['tfm'][:, :] = transforms[road_key].reshape(3, 3) + self.numpy_inputs['big_tfm'][:, :] = transforms[wide_key].reshape(3, 3) + + if prepare_only: + self._warp_enqueue(**self.input_queues, frame=self.full_frames[road_key], big_frame=self.full_frames[wide_key]) + return None + + raw_outputs = self._run_policy(**self.input_queues, frame=self.full_frames[road_key], big_frame=self.full_frames[wide_key]) + + if self._combined_model_type == 'supercombo': + model_output = raw_outputs.numpy().flatten() + sliced = {k: model_output[np.newaxis, v] for k, v in self.vision_output_slices.items()} + outputs = self.parser.parse_outputs(sliced) + else: + vision_output = raw_outputs[0].numpy().flatten() + vision_sliced = {k: vision_output[np.newaxis, v] for k, v in self.vision_output_slices.items()} + outputs = self.parser.parse_vision_outputs(vision_sliced) + + for i, policy_slices in enumerate(self._policy_slices_list): + policy_output = raw_outputs[i + 1].numpy().flatten() + policy_sliced = {k: policy_output[np.newaxis, v] for k, v in policy_slices.items()} + parsed = self.parser.parse_policy_outputs(policy_sliced) + if 'off' in self._policy_keys[i] and self._has_on_policy: + parsed.pop('plan', None) + outputs.update(parsed) + + if 'planplus' in outputs and 'plan' in outputs: + outputs['plan'] = outputs['plan'] + outputs['planplus'] + + if 'desired_curvature' in outputs and 'prev_desired_curv' in self.numpy_inputs: + buf = self.numpy_inputs['prev_desired_curv'] + buf[0, :-1] = buf[0, 1:] + buf[0, -1, :] = outputs['desired_curvature'][0, :] if not self.mlsim else 0 + + return outputs + + def get_action_from_model(self, model_output: dict[str, np.ndarray], prev_action: log.ModelDataV2.Action, + lat_action_t: float, long_action_t: float, v_ego: float) -> log.ModelDataV2.Action: + plan = model_output['plan'][0] + desired_accel, should_stop = get_accel_from_plan(plan[:, Plan.VELOCITY][:, 0], plan[:, Plan.ACCELERATION][:, 0], self.constants.T_IDXS, + action_t=long_action_t) + desired_accel = smooth_value(desired_accel, prev_action.desiredAcceleration, self.LONG_SMOOTH_SECONDS) + + curvature_plan = plan + (self.PLANPLUS_CONTROL - 1.0) * model_output['planplus'][0] if 'planplus' in model_output and self.PLANPLUS_CONTROL != 1.0 else plan + desired_curvature = get_curvature_from_output(model_output, curvature_plan, v_ego, lat_action_t, self.mlsim) + if self.generation is not None and self.generation >= 10: # smooth curvature for post FOF models + if v_ego > self.MIN_LAT_CONTROL_SPEED: + desired_curvature = smooth_value(desired_curvature, prev_action.desiredCurvature, self.LAT_SMOOTH_SECONDS) + else: + desired_curvature = prev_action.desiredCurvature + + return log.ModelDataV2.Action(desiredCurvature=float(desired_curvature),desiredAcceleration=float(desired_accel), shouldStop=bool(should_stop)) + + +def main(demo=False): + cloudlog.warning("modeld init") + + sentry.set_tag("daemon", PROCESS_NAME) + cloudlog.bind(daemon=PROCESS_NAME) + setproctitle(PROCESS_NAME) + config_realtime_process(7, 54) + + # visionipc clients + while True: + available_streams = VisionIpcClient.available_streams("camerad", block=False) + if available_streams: + use_extra_client = VisionStreamType.VISION_STREAM_WIDE_ROAD in available_streams and VisionStreamType.VISION_STREAM_ROAD in available_streams + main_wide_camera = VisionStreamType.VISION_STREAM_ROAD not in available_streams + break + time.sleep(.1) + + vipc_client_main_stream = VisionStreamType.VISION_STREAM_WIDE_ROAD if main_wide_camera else VisionStreamType.VISION_STREAM_ROAD + vipc_client_main = VisionIpcClient("camerad", vipc_client_main_stream, True) + vipc_client_extra = VisionIpcClient("camerad", VisionStreamType.VISION_STREAM_WIDE_ROAD, False) + cloudlog.warning(f"vision stream set up, main_wide_camera: {main_wide_camera}, use_extra_client: {use_extra_client}") + + while not vipc_client_main.connect(False): + time.sleep(0.1) + while use_extra_client and not vipc_client_extra.connect(False): + time.sleep(0.1) + + cloudlog.warning(f"connected main cam with buffer size: {vipc_client_main.buffer_len} ({vipc_client_main.width} x {vipc_client_main.height})") + if use_extra_client: + cloudlog.warning(f"connected extra cam with buffer size: {vipc_client_extra.buffer_len} ({vipc_client_extra.width} x {vipc_client_extra.height})") + + cloudlog.warning("loading model") + model = ModelState(cam_w=vipc_client_main.width, cam_h=vipc_client_main.height) + cloudlog.warning("models loaded, modeld starting") + + # messaging + pm = PubMaster(["modelV2", "drivingModelData", "cameraOdometry", "modelDataV2SP"]) + sm = SubMaster(["deviceState", "carState", "roadCameraState", "liveCalibration", "driverMonitoringState", "carControl", "liveDelay"]) + + publish_state = PublishState() + params = Params() + + # setup filter to track dropped frames + frame_dropped_filter = FirstOrderFilter(0., 10., 1. / model.constants.MODEL_FREQ) + frame_id = 0 + last_vipc_frame_id = 0 + run_count = 0 + + model_transform_main = np.zeros((3, 3), dtype=np.float32) + model_transform_extra = np.zeros((3, 3), dtype=np.float32) + live_calib_seen = False + buf_main, buf_extra = None, None + meta_main = FrameMeta() + meta_extra = FrameMeta() + camera_offset_helper = CameraOffsetHelper() + + + if demo: + CP = get_demo_car_params() + else: + CP = messaging.log_from_bytes(params.get("CarParams", block=True), car.CarParams) + cloudlog.info("modeld got CarParams: %s", CP.brand) + + # TODO Move smooth seconds to action function + long_delay = CP.longitudinalActuatorDelay + model.LONG_SMOOTH_SECONDS + prev_action = log.ModelDataV2.Action() + + DH = DesireHelper() + meta_constants = load_meta_constants() + + while True: + # Keep receiving frames until we are at least 1 frame ahead of previous extra frame + while meta_main.timestamp_sof < meta_extra.timestamp_sof + 25000000: + buf_main = vipc_client_main.recv() + meta_main = FrameMeta(vipc_client_main) + if buf_main is None: + break + + if buf_main is None: + cloudlog.debug("vipc_client_main no frame") + continue + + if use_extra_client: + # Keep receiving extra frames until frame id matches main camera + while True: + buf_extra = vipc_client_extra.recv() + meta_extra = FrameMeta(vipc_client_extra) + if buf_extra is None or meta_main.timestamp_sof < meta_extra.timestamp_sof + 25000000: + break + + if buf_extra is None: + cloudlog.debug("vipc_client_extra no frame") + continue + + if abs(meta_main.timestamp_sof - meta_extra.timestamp_sof) > 10000000: + cloudlog.error(f"frames out of sync! main: {meta_main.frame_id} ({meta_main.timestamp_sof / 1e9:.5f}),\ + extra: {meta_extra.frame_id} ({meta_extra.timestamp_sof / 1e9:.5f})") + + else: + # Use single camera + buf_extra = buf_main + meta_extra = meta_main + + sm.update(0) + desire = DH.desire + is_rhd = sm["driverMonitoringState"].isRHD + frame_id = sm["roadCameraState"].frameId + v_ego = max(sm["carState"].vEgo, 0.) + if sm.frame % 60 == 0: + model.lat_delay = get_lat_delay(params, sm["liveDelay"].lateralDelay) + model.PLANPLUS_CONTROL = params.get("PlanplusControl", return_default=True) + camera_offset_helper.set_offset(params.get("CameraOffset", return_default=True)) + lat_delay = model.lat_delay + model.LAT_SMOOTH_SECONDS + if sm.updated["liveCalibration"] and sm.seen['roadCameraState'] and sm.seen['deviceState']: + device_from_calib_euler = np.array(sm["liveCalibration"].rpyCalib, dtype=np.float32) + dc = DEVICE_CAMERAS[(str(sm['deviceState'].deviceType), str(sm['roadCameraState'].sensor))] + model_transform_main = get_warp_matrix(device_from_calib_euler, dc.ecam.intrinsics if main_wide_camera else dc.fcam.intrinsics, False).astype(np.float32) + model_transform_extra = get_warp_matrix(device_from_calib_euler, dc.ecam.intrinsics, True).astype(np.float32) + model_transform_main, model_transform_extra = camera_offset_helper.update(model_transform_main, model_transform_extra, sm, main_wide_camera) + live_calib_seen = True + + traffic_convention = np.zeros(2) + traffic_convention[int(is_rhd)] = 1 + + vec_desire = np.zeros(model.constants.DESIRE_LEN, dtype=np.float32) + if desire >= 0 and desire < model.constants.DESIRE_LEN: + vec_desire[desire] = 1 + + # tracked dropped frames + vipc_dropped_frames = max(0, meta_main.frame_id - last_vipc_frame_id - 1) + frames_dropped = frame_dropped_filter.update(min(vipc_dropped_frames, 10)) + if run_count < 10: # let frame drops warm up + frame_dropped_filter.x = 0. + frames_dropped = 0. + run_count = run_count + 1 + + frame_drop_ratio = frames_dropped / (1 + frames_dropped) + prepare_only = vipc_dropped_frames > 0 + if prepare_only: + cloudlog.error(f"skipping model eval. Dropped {vipc_dropped_frames} frames") + + bufs = {name: buf_extra if 'big' in name else buf_main for name in model.vision_input_names} + transforms = {name: model_transform_extra if 'big' in name else model_transform_main for name in model.vision_input_names} + inputs:dict[str, np.ndarray] = { + model.desire_key: vec_desire, + 'traffic_convention': traffic_convention, + } + + if 'lateral_control_params' in model.numpy_inputs: + inputs['lateral_control_params'] = np.array([v_ego, lat_delay], dtype=np.float32) + + mt1 = time.perf_counter() + model_output = model.run(bufs, transforms, inputs, prepare_only) + mt2 = time.perf_counter() + model_execution_time = mt2 - mt1 + + if model_output is not None: + modelv2_send = messaging.new_message('modelV2') + drivingdata_send = messaging.new_message('drivingModelData') + posenet_send = messaging.new_message('cameraOdometry') + mdv2sp_send = messaging.new_message('modelDataV2SP') + + action = model.get_action_from_model(model_output, prev_action, lat_delay + DT_MDL, long_delay + DT_MDL, v_ego) + prev_action = action + fill_model_msg(drivingdata_send, modelv2_send, model_output, action, + publish_state, meta_main.frame_id, meta_extra.frame_id, frame_id, + frame_drop_ratio, meta_main.timestamp_eof, model_execution_time, live_calib_seen, meta_constants) + + desire_state = modelv2_send.modelV2.meta.desireState + l_lane_change_prob = desire_state[log.Desire.laneChangeLeft] + r_lane_change_prob = desire_state[log.Desire.laneChangeRight] + lane_change_prob = l_lane_change_prob + r_lane_change_prob + DH.update(sm['carState'], sm['carControl'].latActive, lane_change_prob) + modelv2_send.modelV2.meta.laneChangeState = DH.lane_change_state + modelv2_send.modelV2.meta.laneChangeDirection = DH.lane_change_direction + mdv2sp_send.modelDataV2SP.laneTurnDirection = DH.lane_turn_direction + drivingdata_send.drivingModelData.meta.laneChangeState = DH.lane_change_state + drivingdata_send.drivingModelData.meta.laneChangeDirection = DH.lane_change_direction + + fill_pose_msg(posenet_send, model_output, meta_main.frame_id, vipc_dropped_frames, meta_main.timestamp_eof, live_calib_seen) + pm.send('modelV2', modelv2_send) + pm.send('drivingModelData', drivingdata_send) + pm.send('cameraOdometry', posenet_send) + pm.send('modelDataV2SP', mdv2sp_send) + last_vipc_frame_id = meta_main.frame_id + + +if __name__ == "__main__": + try: + import argparse + parser = argparse.ArgumentParser() + parser.add_argument('--demo', action='store_true', help='A boolean for demo mode.') + args = parser.parse_args() + main(demo=args.demo) + except KeyboardInterrupt: + cloudlog.warning(f"child {PROCESS_NAME} got SIGINT") + except Exception: + sentry.capture_exception() + raise diff --git a/openpilot/sunnypilot/modeld_v2/modeld_base.py b/openpilot/sunnypilot/modeld_v2/modeld_base.py new file mode 100644 index 0000000000..ba57659b09 --- /dev/null +++ b/openpilot/sunnypilot/modeld_v2/modeld_base.py @@ -0,0 +1,12 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from openpilot.common.params import Params + + +class ModelStateBase: + def __init__(self): + self.lat_delay = Params().get("LagdValueCache", return_default=True) diff --git a/openpilot/sunnypilot/modeld_v2/parse_model_outputs.py b/openpilot/sunnypilot/modeld_v2/parse_model_outputs.py new file mode 100644 index 0000000000..82103283f3 --- /dev/null +++ b/openpilot/sunnypilot/modeld_v2/parse_model_outputs.py @@ -0,0 +1,110 @@ +import numpy as np +from openpilot.sunnypilot.modeld_v2.constants import ModelConstants + +def safe_exp(x, out=None): + # -11 is around 10**14, more causes float16 overflow + return np.exp(np.clip(x, -np.inf, 11), out=out) + +def sigmoid(x): + return 1. / (1. + safe_exp(-x)) + +def softmax(x, axis=-1): + x -= np.max(x, axis=axis, keepdims=True) + if x.dtype == np.float32 or x.dtype == np.float64: + safe_exp(x, out=x) + else: + x = safe_exp(x) + x /= np.sum(x, axis=axis, keepdims=True) + return x + +class Parser: + def __init__(self, ignore_missing=False): + self.ignore_missing = ignore_missing + + def check_missing(self, outs, name): + if name not in outs and not self.ignore_missing: + raise ValueError(f"Missing output {name}") + return name not in outs + + def parse_categorical_crossentropy(self, name, outs, out_shape=None): + if self.check_missing(outs, name): + return + raw = outs[name] + if out_shape is not None: + raw = raw.reshape((raw.shape[0],) + out_shape) + outs[name] = softmax(raw, axis=-1) + + def parse_binary_crossentropy(self, name, outs): + if self.check_missing(outs, name): + return + raw = outs[name] + outs[name] = sigmoid(raw) + + def parse_mdn(self, name, outs, in_N=0, out_N=1, out_shape=None): + if self.check_missing(outs, name): + return + raw = outs[name] + raw = raw.reshape((raw.shape[0], max(in_N, 1), -1)) + + n_values = (raw.shape[2] - out_N)//2 + pred_mu = raw[:,:,:n_values] + pred_std = safe_exp(raw[:,:,n_values: 2*n_values]) + + if in_N > 1: + weights = np.zeros((raw.shape[0], in_N, out_N), dtype=raw.dtype) + for i in range(out_N): + weights[:,:,i - out_N] = softmax(raw[:,:,i - out_N], axis=-1) + + if out_N == 1: + for fidx in range(weights.shape[0]): + idxs = np.argsort(weights[fidx][:,0])[::-1] + weights[fidx] = weights[fidx][idxs] + pred_mu[fidx] = pred_mu[fidx][idxs] + pred_std[fidx] = pred_std[fidx][idxs] + assert out_shape is not None + full_shape = tuple([raw.shape[0], in_N] + list(out_shape)) + outs[name + '_weights'] = weights + outs[name + '_hypotheses'] = pred_mu.reshape(full_shape) + outs[name + '_stds_hypotheses'] = pred_std.reshape(full_shape) + + pred_mu_final = np.zeros((raw.shape[0], out_N, n_values), dtype=raw.dtype) + pred_std_final = np.zeros((raw.shape[0], out_N, n_values), dtype=raw.dtype) + for fidx in range(weights.shape[0]): + for hidx in range(out_N): + idxs = np.argsort(weights[fidx,:,hidx])[::-1] + pred_mu_final[fidx, hidx] = pred_mu[fidx, idxs[0]] + pred_std_final[fidx, hidx] = pred_std[fidx, idxs[0]] + else: + pred_mu_final = pred_mu + pred_std_final = pred_std + + if out_N > 1: + assert out_shape is not None + final_shape = tuple([raw.shape[0], out_N] + list(out_shape)) + else: + assert out_shape is not None + final_shape = tuple([raw.shape[0],] + list(out_shape)) + outs[name] = pred_mu_final.reshape(final_shape) + outs[name + '_stds'] = pred_std_final.reshape(final_shape) + + def parse_outputs(self, outs: dict[str, np.ndarray]) -> dict[str, np.ndarray]: + self.parse_mdn('plan', outs, in_N=ModelConstants.PLAN_MHP_N, out_N=ModelConstants.PLAN_MHP_SELECTION, + out_shape=(ModelConstants.IDX_N,ModelConstants.PLAN_WIDTH)) + self.parse_mdn('lane_lines', outs, in_N=0, out_N=0, out_shape=(ModelConstants.NUM_LANE_LINES,ModelConstants.IDX_N,ModelConstants.LANE_LINES_WIDTH)) + self.parse_mdn('road_edges', outs, in_N=0, out_N=0, out_shape=(ModelConstants.NUM_ROAD_EDGES,ModelConstants.IDX_N,ModelConstants.LANE_LINES_WIDTH)) + self.parse_mdn('pose', outs, in_N=0, out_N=0, out_shape=(ModelConstants.POSE_WIDTH,)) + self.parse_mdn('road_transform', outs, in_N=0, out_N=0, out_shape=(ModelConstants.POSE_WIDTH,)) + if 'sim_pose' in outs: + self.parse_mdn('sim_pose', outs, in_N=0, out_N=0, out_shape=(ModelConstants.POSE_WIDTH,)) + self.parse_mdn('wide_from_device_euler', outs, in_N=0, out_N=0, out_shape=(ModelConstants.WIDE_FROM_DEVICE_WIDTH,)) + self.parse_mdn('lead', outs, in_N=ModelConstants.LEAD_MHP_N, out_N=ModelConstants.LEAD_MHP_SELECTION, + out_shape=(ModelConstants.LEAD_TRAJ_LEN,ModelConstants.LEAD_WIDTH)) + if 'lat_planner_solution' in outs: + self.parse_mdn('lat_planner_solution', outs, in_N=0, out_N=0, out_shape=(ModelConstants.IDX_N,ModelConstants.LAT_PLANNER_SOLUTION_WIDTH)) + if 'desired_curvature' in outs: + self.parse_mdn('desired_curvature', outs, in_N=0, out_N=0, out_shape=(ModelConstants.DESIRED_CURV_WIDTH,)) + for k in ['lead_prob', 'lane_lines_prob', 'meta']: + self.parse_binary_crossentropy(k, outs) + self.parse_categorical_crossentropy('desire_state', outs, out_shape=(ModelConstants.DESIRE_PRED_WIDTH,)) + self.parse_categorical_crossentropy('desire_pred', outs, out_shape=(ModelConstants.DESIRE_PRED_LEN,ModelConstants.DESIRE_PRED_WIDTH)) + return outs diff --git a/openpilot/sunnypilot/modeld_v2/parse_model_outputs_split.py b/openpilot/sunnypilot/modeld_v2/parse_model_outputs_split.py new file mode 100644 index 0000000000..6bd2a70eed --- /dev/null +++ b/openpilot/sunnypilot/modeld_v2/parse_model_outputs_split.py @@ -0,0 +1,157 @@ +import numpy as np +from openpilot.sunnypilot.models.split_model_constants import SplitModelConstants + + +def safe_exp(x, out=None): + # -11 is around 10**14, more causes float16 overflow + return np.exp(np.clip(x, -np.inf, 11), out=out) + + +def sigmoid(x): + return 1. / (1. + safe_exp(-x)) + + +def softmax(x, axis=-1): + x -= np.max(x, axis=axis, keepdims=True) + if x.dtype == np.float32 or x.dtype == np.float64: + safe_exp(x, out=x) + else: + x = safe_exp(x) + x /= np.sum(x, axis=axis, keepdims=True) + return x + + +class Parser: + def __init__(self, ignore_missing=False): + self.ignore_missing = ignore_missing + + def check_missing(self, outs, name): + if name not in outs and not self.ignore_missing: + raise ValueError(f"Missing output {name}") + return name not in outs + + def parse_categorical_crossentropy(self, name, outs, out_shape=None): + if self.check_missing(outs, name): + return + raw = outs[name] + if out_shape is not None: + raw = raw.reshape((raw.shape[0],) + out_shape) + outs[name] = softmax(raw, axis=-1) + + def parse_binary_crossentropy(self, name, outs): + if self.check_missing(outs, name): + return + raw = outs[name] + outs[name] = sigmoid(raw) + + def parse_mdn(self, name, outs, in_N=0, out_N=1, out_shape=None): + if self.check_missing(outs, name): + return + raw = outs[name] + raw = raw.reshape((raw.shape[0], max(in_N, 1), -1)) + + n_values = (raw.shape[2] - out_N)//2 + pred_mu = raw[:,:,:n_values] + pred_std = safe_exp(raw[:,:,n_values: 2*n_values]) + + if in_N > 1: + weights = np.zeros((raw.shape[0], in_N, out_N), dtype=raw.dtype) + for i in range(out_N): + weights[:,:,i - out_N] = softmax(raw[:,:,i - out_N], axis=-1) + + if out_N == 1: + for fidx in range(weights.shape[0]): + idxs = np.argsort(weights[fidx][:,0])[::-1] + weights[fidx] = weights[fidx][idxs] + pred_mu[fidx] = pred_mu[fidx][idxs] + pred_std[fidx] = pred_std[fidx][idxs] + assert out_shape is not None + full_shape = tuple([raw.shape[0], in_N] + list(out_shape)) + outs[name + '_weights'] = weights + outs[name + '_hypotheses'] = pred_mu.reshape(full_shape) + outs[name + '_stds_hypotheses'] = pred_std.reshape(full_shape) + + pred_mu_final = np.zeros((raw.shape[0], out_N, n_values), dtype=raw.dtype) + pred_std_final = np.zeros((raw.shape[0], out_N, n_values), dtype=raw.dtype) + for fidx in range(weights.shape[0]): + for hidx in range(out_N): + idxs = np.argsort(weights[fidx,:,hidx])[::-1] + pred_mu_final[fidx, hidx] = pred_mu[fidx, idxs[0]] + pred_std_final[fidx, hidx] = pred_std[fidx, idxs[0]] + else: + pred_mu_final = pred_mu + pred_std_final = pred_std + + if out_N > 1: + assert out_shape is not None + final_shape = tuple([raw.shape[0], out_N] + list(out_shape)) + else: + assert out_shape is not None + final_shape = tuple([raw.shape[0],] + list(out_shape)) + outs[name] = pred_mu_final.reshape(final_shape) + outs[name + '_stds'] = pred_std_final.reshape(final_shape) + + def is_mhp(self, outs, name, shape): + if self.check_missing(outs, name): + return False + if outs[name].shape[1] == 2 * shape: + return False + return True + + def parse_dynamic_outputs(self, outs: dict[str, np.ndarray]) -> None: + if 'lead' in outs: + lead_mhp = self.is_mhp(outs, 'lead', + SplitModelConstants.LEAD_MHP_SELECTION * SplitModelConstants.LEAD_TRAJ_LEN * SplitModelConstants.LEAD_WIDTH) + lead_in_N, lead_out_N = (SplitModelConstants.LEAD_MHP_N, SplitModelConstants.LEAD_MHP_SELECTION) if lead_mhp else (0, 0) + lead_out_shape = (SplitModelConstants.LEAD_TRAJ_LEN, SplitModelConstants.LEAD_WIDTH) if lead_mhp else \ + (SplitModelConstants.LEAD_MHP_SELECTION, SplitModelConstants.LEAD_TRAJ_LEN, SplitModelConstants.LEAD_WIDTH) + self.parse_mdn('lead', outs, in_N=lead_in_N, out_N=lead_out_N, out_shape=lead_out_shape) + if 'plan' in outs: + plan_mhp = self.is_mhp(outs, 'plan', SplitModelConstants.IDX_N * SplitModelConstants.PLAN_WIDTH) + plan_in_N, plan_out_N = (SplitModelConstants.PLAN_MHP_N, SplitModelConstants.PLAN_MHP_SELECTION) if plan_mhp else (0, 0) + self.parse_mdn('plan', outs, in_N=plan_in_N, out_N=plan_out_N, + out_shape=(SplitModelConstants.IDX_N, SplitModelConstants.PLAN_WIDTH)) + if 'planplus' in outs: + self.parse_mdn('planplus', outs, in_N=0, out_N=0, out_shape=(SplitModelConstants.IDX_N, SplitModelConstants.PLAN_WIDTH)) + + def split_outputs(self, outs: dict[str, np.ndarray]) -> None: + if 'desired_curvature' in outs: + self.parse_mdn('desired_curvature', outs, in_N=0, out_N=0, out_shape=(SplitModelConstants.DESIRED_CURV_WIDTH,)) + if 'desire_pred' in outs: + self.parse_categorical_crossentropy('desire_pred', outs, out_shape=(SplitModelConstants.DESIRE_PRED_LEN,SplitModelConstants.DESIRE_PRED_WIDTH)) + if 'desire_state' in outs: + self.parse_categorical_crossentropy('desire_state', outs, out_shape=(SplitModelConstants.DESIRE_PRED_WIDTH,)) + if 'lane_lines' in outs: + self.parse_mdn('lane_lines', outs, in_N=0, out_N=0, + out_shape=(SplitModelConstants.NUM_LANE_LINES,SplitModelConstants.IDX_N,SplitModelConstants.LANE_LINES_WIDTH)) + if 'lane_lines_prob' in outs: + self.parse_binary_crossentropy('lane_lines_prob', outs) + if 'lead_prob' in outs: + self.parse_binary_crossentropy('lead_prob', outs) + if 'lat_planner_solution' in outs: + self.parse_mdn('lat_planner_solution', outs, in_N=0, out_N=0, out_shape=(SplitModelConstants.IDX_N,SplitModelConstants.LAT_PLANNER_SOLUTION_WIDTH)) + if 'meta' in outs: + self.parse_binary_crossentropy('meta', outs) + if 'road_edges' in outs: + self.parse_mdn('road_edges', outs, in_N=0, out_N=0, + out_shape=(SplitModelConstants.NUM_ROAD_EDGES,SplitModelConstants.IDX_N,SplitModelConstants.LANE_LINES_WIDTH)) + if 'sim_pose' in outs: + self.parse_mdn('sim_pose', outs, in_N=0, out_N=0, out_shape=(SplitModelConstants.POSE_WIDTH,)) + + def parse_vision_outputs(self, outs: dict[str, np.ndarray]) -> dict[str, np.ndarray]: + self.parse_mdn('pose', outs, in_N=0, out_N=0, out_shape=(SplitModelConstants.POSE_WIDTH,)) + self.parse_mdn('wide_from_device_euler', outs, in_N=0, out_N=0, out_shape=(SplitModelConstants.WIDE_FROM_DEVICE_WIDTH,)) + self.parse_mdn('road_transform', outs, in_N=0, out_N=0, out_shape=(SplitModelConstants.POSE_WIDTH,)) + self.parse_dynamic_outputs(outs) + self.split_outputs(outs) + return outs + + def parse_policy_outputs(self, outs: dict[str, np.ndarray]) -> dict[str, np.ndarray]: + self.parse_dynamic_outputs(outs) + self.split_outputs(outs) + return outs + + def parse_outputs(self, outs: dict[str, np.ndarray]) -> dict[str, np.ndarray]: + outs = self.parse_vision_outputs(outs) + outs = self.parse_policy_outputs(outs) + return outs diff --git a/sunnypilot/selfdrive/car/__init__.py b/openpilot/sunnypilot/modeld_v2/tests/__init__.py similarity index 100% rename from sunnypilot/selfdrive/car/__init__.py rename to openpilot/sunnypilot/modeld_v2/tests/__init__.py diff --git a/openpilot/sunnypilot/modeld_v2/tests/conftest.py b/openpilot/sunnypilot/modeld_v2/tests/conftest.py new file mode 100644 index 0000000000..f79cbe10b2 --- /dev/null +++ b/openpilot/sunnypilot/modeld_v2/tests/conftest.py @@ -0,0 +1,204 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" + +import pickle +import pytest + +import openpilot.sunnypilot.models.helpers as helpers +import openpilot.sunnypilot.modeld_v2.modeld as modeld_module +from openpilot.sunnypilot.modeld_v2.constants import ModelConstants +from openpilot.sunnypilot.models.split_model_constants import SplitModelConstants + + +class DummyOverride: + def __init__(self, key, value): + self.key = key + self.value = value + + +class DummyArtifact: + def __init__(self, file_name): + self.fileName = file_name + + +class DummyModelType: + def __init__(self, raw): + self.raw = raw + + +class DummyModel: + def __init__(self, type_str, artifact_file): + self.type = DummyModelType(type_str) + self.artifact = DummyArtifact(artifact_file) + + +class DummyBundle: + def __init__(self, is_20hz=False, models=None, generation=10): + self.overrides = [DummyOverride('lat', '.1'), DummyOverride('long', '.3')] + self.generation = generation + self.is20hz = is_20hz + self.models = models or [] + + +class Archetype: + def __init__(self, name, metadata_structure, model_stubs, is_20hz, + expected_model_type, expected_constants_class, expected_parser_module, + expected_desire_key): + self.name = name + self.metadata_structure = metadata_structure + self.model_stubs = model_stubs + self.is_20hz = is_20hz + self.expected_model_type = expected_model_type + self.expected_constants_class = expected_constants_class + self.expected_parser_module = expected_parser_module + self.expected_desire_key = expected_desire_key + + +def _noop_jit(**kwargs): + pass + + +def _make_vision_policy_metadata(vision_input_shapes, policy_input_shapes, + vision_output_slices, policy_output_slices): + return { + 'vision': {'input_shapes': vision_input_shapes, 'output_slices': vision_output_slices}, + 'policy': {'input_shapes': policy_input_shapes, 'output_slices': policy_output_slices}, + } + + +def _make_multi_policy_metadata(vision_input_shapes, policy_input_shapes, + vision_output_slices, policy_output_slices): + return { + 'vision': {'input_shapes': vision_input_shapes, 'output_slices': vision_output_slices}, + 'offPolicy': {'input_shapes': policy_input_shapes, 'output_slices': policy_output_slices}, + } + + +def _make_tri_policy_metadata(vision_input_shapes, policy_input_shapes, + vision_output_slices, policy_output_slices): + return { + 'vision': {'input_shapes': vision_input_shapes, 'output_slices': vision_output_slices}, + 'onPolicy': {'input_shapes': policy_input_shapes, 'output_slices': policy_output_slices}, + 'offPolicy': {'input_shapes': policy_input_shapes, 'output_slices': policy_output_slices}, + } + + +def _make_supercombo_metadata(input_shapes, output_slices): + return {'model': {'input_shapes': input_shapes, 'output_slices': output_slices}} + + +SPLIT_VISION_INPUT_SHAPES = {'img': (1, 12, 128, 256), 'big_img': (1, 12, 128, 256)} +SPLIT_POLICY_INPUT_SHAPES = {'features_buffer': (1, 25, 512), 'desire_pulse': (1, 25, 8), 'traffic_convention': (1, 2)} +SPLIT_VISION_SLICES = {'hidden_state': slice(0, 512), 'pose': slice(512, 524)} +SPLIT_POLICY_SLICES = {'plan': slice(0, 495), 'meta': slice(495, 550)} + +SUPERCOMBO_INPUT_SHAPES = { + 'img': (1, 12, 128, 256), 'big_img': (1, 12, 128, 256), + 'desire': (1, 100, 8), 'features_buffer': (1, 99, 512), + 'lateral_control_params': (1, 2), 'prev_desired_curv': (1, 100, 1), + 'traffic_convention': (1, 2), +} +SUPERCOMBO_SLICES = {'plan': slice(0, 495), 'hidden_state': slice(495, 1007), 'meta': slice(1007, 1062)} + +CAM_W, CAM_H = 1928, 1208 + +ARCHETYPES = { + 'vision_policy_split': Archetype( + name='vision_policy_split', + metadata_structure=_make_vision_policy_metadata( + SPLIT_VISION_INPUT_SHAPES, SPLIT_POLICY_INPUT_SHAPES, + SPLIT_VISION_SLICES, SPLIT_POLICY_SLICES), + model_stubs=[DummyModel('vision', 'driving_test_tinygrad.pkl'), + DummyModel('policy', 'driving_test_tinygrad.pkl')], + is_20hz=True, + expected_model_type='split', + expected_constants_class=SplitModelConstants, + expected_parser_module='parse_model_outputs_split', + expected_desire_key='desire', + ), + 'vision_multi_policy': Archetype( + name='vision_multi_policy', + metadata_structure=_make_multi_policy_metadata( + SPLIT_VISION_INPUT_SHAPES, SPLIT_POLICY_INPUT_SHAPES, + SPLIT_VISION_SLICES, SPLIT_POLICY_SLICES), + model_stubs=[DummyModel('vision', 'driving_test_tinygrad.pkl'), + DummyModel('offPolicy', 'driving_test_tinygrad.pkl')], + is_20hz=True, + expected_model_type='multi_policy', + expected_constants_class=SplitModelConstants, + expected_parser_module='parse_model_outputs_split', + expected_desire_key='desire', + ), + 'tri_policy': Archetype( + name='tri_policy', + metadata_structure=_make_tri_policy_metadata( + SPLIT_VISION_INPUT_SHAPES, SPLIT_POLICY_INPUT_SHAPES, + SPLIT_VISION_SLICES, SPLIT_POLICY_SLICES), + model_stubs=[DummyModel('vision', 'driving_test_tinygrad.pkl'), + DummyModel('onPolicy', 'driving_test_tinygrad.pkl'), + DummyModel('offPolicy', 'driving_test_tinygrad.pkl')], + is_20hz=True, + expected_model_type='multi_policy', + expected_constants_class=SplitModelConstants, + expected_parser_module='parse_model_outputs_split', + expected_desire_key='desire', + ), + 'supercombo_non20hz': Archetype( + name='supercombo_non20hz', + metadata_structure=_make_supercombo_metadata(SUPERCOMBO_INPUT_SHAPES, SUPERCOMBO_SLICES), + model_stubs=[DummyModel('supercombo', 'driving_test_tinygrad.pkl')], + is_20hz=False, + expected_model_type='supercombo', + expected_constants_class=ModelConstants, + expected_parser_module='parse_model_outputs', + expected_desire_key='desire', + ), +} + + +def make_pkl_data(archetype): + return { + 'metadata': archetype.metadata_structure, + (CAM_W, CAM_H): {'run_policy': _noop_jit, 'warp_enqueue': _noop_jit}, + } + + +def write_pkl(tmp_path, archetype): + pkl_path = tmp_path / 'driving_test_tinygrad.pkl' + with open(pkl_path, 'wb') as f: + pickle.dump(make_pkl_data(archetype), f) + return pkl_path + + +def make_bundle(archetype): + return DummyBundle( + models=archetype.model_stubs, + is_20hz=archetype.is_20hz, + ) + + +@pytest.fixture +def patch_modeld(monkeypatch): + def _patch(bundle): + monkeypatch.setattr(helpers, 'get_active_bundle', lambda params=None: bundle, raising=False) + monkeypatch.setattr(modeld_module, 'get_active_bundle', lambda params=None: bundle, raising=False) + + return _patch + + +@pytest.fixture +def model_state_factory(tmp_path, monkeypatch, patch_modeld): + from openpilot.common.hardware import hw + + def _create(archetype): + write_pkl(tmp_path, archetype) + bundle = make_bundle(archetype) + patch_modeld(bundle) + monkeypatch.setattr(hw.Paths, 'model_root', staticmethod(lambda: str(tmp_path))) + return modeld_module.ModelState(cam_w=CAM_W, cam_h=CAM_H) + + return _create diff --git a/openpilot/sunnypilot/modeld_v2/tests/test_camera_offset_helper.py b/openpilot/sunnypilot/modeld_v2/tests/test_camera_offset_helper.py new file mode 100644 index 0000000000..f25bcd0a35 --- /dev/null +++ b/openpilot/sunnypilot/modeld_v2/tests/test_camera_offset_helper.py @@ -0,0 +1,84 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import numpy as np + +from openpilot.common.transformations.camera import DEVICE_CAMERAS +from openpilot.common.transformations.model import get_warp_matrix +from openpilot.sunnypilot.modeld_v2.camera_offset_helper import CameraOffsetHelper + + +class MockStruct: + def __init__(self, **kwargs): + for k, v in kwargs.items(): + setattr(self, k, v) + + def __getitem__(self, item): + return getattr(self, item) + + +class TestCameraOffset: + def setup_method(self): + self.camera_offset = CameraOffsetHelper() + self.dc = DEVICE_CAMERAS[('mici', 'os04c10')] + + def test_smoothing(self): + self.camera_offset.set_offset(0.2) + + sm = MockStruct( + deviceState=MockStruct(deviceType='mici'), + roadCameraState=MockStruct(sensor='os04c10'), + liveCalibration=MockStruct(rpyCalib=[0.0, 0.0, 0.0], height=[1.22]) + ) + + intrinsics_main = self.dc.fcam.intrinsics + intrinsics_extra = self.dc.ecam.intrinsics + device_from_calib_euler = np.array([0.0, 0.0, 0.0], dtype=np.float32) + main_transform = get_warp_matrix(device_from_calib_euler, intrinsics_main, False).astype(np.float32) + extra_transform = get_warp_matrix(device_from_calib_euler, intrinsics_extra, True).astype(np.float32) + + self.camera_offset.update(main_transform, extra_transform, sm, False) + np.testing.assert_almost_equal(self.camera_offset.actual_camera_offset, 0.02) + self.camera_offset.update(main_transform, extra_transform, sm, False) + np.testing.assert_almost_equal(self.camera_offset.actual_camera_offset, 0.038) + + def test_camera_offset_(self): + intrinsics = self.dc.fcam.intrinsics + transform = np.eye(3, dtype=np.float32) + height = 1.22 + offset = 0.1 + + cy = intrinsics[1, 2] + expected_shear = np.eye(3, dtype=np.float32) + expected_shear[0, 1] = offset / height + expected_shear[0, 2] = -offset / height * cy + + result = CameraOffsetHelper.apply_camera_offset(transform, intrinsics, height, offset) + np.testing.assert_array_almost_equal(result, expected_shear) + + def test_update(self): + sm = MockStruct( + deviceState=MockStruct(deviceType='mici'), + roadCameraState=MockStruct(sensor='os04c10'), + liveCalibration=MockStruct(rpyCalib=[0.0, 0.0, 0.0], height=[1.22]) + ) + intrinsics_main = self.dc.fcam.intrinsics + intrinsics_extra = self.dc.ecam.intrinsics + device_from_calib_euler = np.array([0.0, 0.0, 0.0], dtype=np.float32) + main_transform = get_warp_matrix(device_from_calib_euler, intrinsics_main, False).astype(np.float32) + extra_transform = get_warp_matrix(device_from_calib_euler, intrinsics_extra, True).astype(np.float32) + + self.camera_offset.set_offset(0.0) # test default offset doesn't change transformation + main_out, extra_out = self.camera_offset.update(main_transform, extra_transform, sm, False) + np.testing.assert_array_equal(main_out, main_transform) + np.testing.assert_array_equal(extra_out, extra_transform) + + self.camera_offset.set_offset(0.2) # test valid offset changes transformation + main_out, extra_out = self.camera_offset.update(main_transform, extra_transform, sm, False) + assert not np.array_equal(main_out, main_transform) + assert not np.array_equal(extra_out, extra_transform) + assert main_out[0, 1] != 0.0 + assert main_out[0, 2] != 0.0 diff --git a/openpilot/sunnypilot/modeld_v2/tests/test_combined_pkl_loader.py b/openpilot/sunnypilot/modeld_v2/tests/test_combined_pkl_loader.py new file mode 100644 index 0000000000..b13a7abecf --- /dev/null +++ b/openpilot/sunnypilot/modeld_v2/tests/test_combined_pkl_loader.py @@ -0,0 +1,260 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" + +import pytest + +import openpilot.sunnypilot.models.helpers as helpers +import openpilot.sunnypilot.modeld_v2.modeld as modeld_module +from openpilot.sunnypilot.modeld_v2.modeld import _find_driving_pkl +from openpilot.sunnypilot.modeld_v2.tests.conftest import DummyModel, DummyBundle, ARCHETYPES, CAM_W, CAM_H, \ + SPLIT_VISION_INPUT_SHAPES, SPLIT_POLICY_INPUT_SHAPES + +ModelState = modeld_module.ModelState + + +# Pkl discovery + +class TestFindDrivingPkl: + def test_returns_none_when_no_bundle(self): + assert _find_driving_pkl(None) is None + + def test_returns_none_when_no_models(self): + bundle = DummyBundle(models=[]) + assert _find_driving_pkl(bundle) is None + + def test_returns_none_when_pkl_not_on_disk(self): + bundle = DummyBundle(models=[ + DummyModel('vision', 'driving_fof_tinygrad.pkl'), + DummyModel('policy', 'driving_fof_tinygrad.pkl'), + ]) + assert _find_driving_pkl(bundle) is None + + def test_finds_pkl_by_artifact_name(self, tmp_path, monkeypatch): + (tmp_path / 'driving_fof_tinygrad.pkl').write_bytes(b'fake') + from openpilot.common.hardware import hw + monkeypatch.setattr(hw.Paths, 'model_root', staticmethod(lambda: str(tmp_path))) + + bundle = DummyBundle(models=[ + DummyModel('vision', 'driving_fof_tinygrad.pkl'), + DummyModel('policy', 'driving_fof_tinygrad.pkl'), + ]) + result = _find_driving_pkl(bundle) + assert result is not None + assert 'driving_fof_tinygrad.pkl' in result + + +# Init — assertion guard + +class TestModelStateCombinedInit: + def test_asserts_when_no_pkl(self, monkeypatch): + bundle = DummyBundle(models=[], is_20hz=True) + monkeypatch.setattr(helpers, 'get_active_bundle', lambda params=None: bundle, raising=False) + monkeypatch.setattr(modeld_module, 'get_active_bundle', lambda params=None: bundle, raising=False) + with pytest.raises(AssertionError, match="No driving pkl found"): + ModelState(cam_w=CAM_W, cam_h=CAM_H) + + +class TestStockEquivalence: + + def test_split_queue_keys_match_stock(self, model_state_factory): + from openpilot.selfdrive.modeld.compile_modeld import make_input_queues + from openpilot.sunnypilot.modeld_v2.compile_modeld import derive_frame_skip + + state = model_state_factory(ARCHETYPES['vision_policy_split']) + + frame_skip = derive_frame_skip(SPLIT_VISION_INPUT_SHAPES, SPLIT_POLICY_INPUT_SHAPES) + # action_t is a deep-model prerequisite the SP loader doesn't provide yet; see skip_keys below + stock_shapes = {**SPLIT_VISION_INPUT_SHAPES, **SPLIT_POLICY_INPUT_SHAPES, 'action_t': (1, 2)} + stock_queues, stock_npy = make_input_queues(stock_shapes, frame_skip, device='NPY') + + # TODO-SP: remove action_t skip once SP adds prerequisite for deep models (action_t input queue) + # prev_feat is a stock QCOM corruption workaround handled inside the SP loader's JIT path + skip_keys = {'action_t', 'prev_feat'} + # stock packs the per-key policy inputs into packed_npy_inputs; the npy views carry the individual keys + stock_queue_keys = set(stock_queues.keys()) + if 'packed_npy_inputs' in stock_queue_keys: + stock_queue_keys.remove('packed_npy_inputs') + stock_queue_keys |= set(stock_npy.keys()) + assert set(state.input_queues.keys()) == stock_queue_keys - skip_keys, \ + f"Queue keys differ: v2={set(state.input_queues.keys())}, stock={stock_queue_keys}" + assert set(state.numpy_inputs.keys()) == set(stock_npy.keys()) - skip_keys, \ + f"Npy keys differ: v2={set(state.numpy_inputs.keys())}, stock={set(stock_npy.keys())}" + + def test_split_queue_keys_work_with_desire_key(self, model_state_factory): + from openpilot.sunnypilot.modeld_v2.compile_modeld import derive_frame_skip, make_split_input_queues + + policy_shapes_desire = {'features_buffer': (1, 25, 512), 'desire': (1, 25, 8), 'traffic_convention': (1, 2)} + frame_skip = derive_frame_skip(SPLIT_VISION_INPUT_SHAPES, policy_shapes_desire) + queues, npy = make_split_input_queues(SPLIT_VISION_INPUT_SHAPES, policy_shapes_desire, frame_skip, device='NPY') + + assert 'desire_q' in queues + assert 'desire' in npy + assert 'img_q' in queues + assert 'feat_q' in queues + + def test_split_vision_input_names_match_stock(self, model_state_factory): + state = model_state_factory(ARCHETYPES['vision_policy_split']) + assert state.vision_input_names == ['img', 'big_img'] + + def test_split_output_slices_preserved(self, model_state_factory): + arch = ARCHETYPES['vision_policy_split'] + state = model_state_factory(arch) + assert state.vision_output_slices == arch.metadata_structure['vision']['output_slices'] + assert state.policy_output_slices == arch.metadata_structure['policy']['output_slices'] + + +ARCHETYPE_NAMES = list(ARCHETYPES.keys()) + + +class TestModelTypeDetection: + @pytest.mark.parametrize("archetype_name", ARCHETYPE_NAMES) + def test_combined_model_type(self, archetype_name, model_state_factory): + arch = ARCHETYPES[archetype_name] + state = model_state_factory(arch) + assert state._combined_model_type == arch.expected_model_type, \ + f"{arch.name}: got {state._combined_model_type}, expected {arch.expected_model_type}" + + +class TestConstantsSelection: + @pytest.mark.parametrize("archetype_name", ARCHETYPE_NAMES) + def test_constants_class(self, archetype_name, model_state_factory): + arch = ARCHETYPES[archetype_name] + state = model_state_factory(arch) + assert type(state.constants) is arch.expected_constants_class, \ + f"{arch.name}: got {type(state.constants).__name__}, expected {arch.expected_constants_class.__name__}" + + +class TestParserSelection: + @pytest.mark.parametrize("archetype_name", ARCHETYPE_NAMES) + def test_parser_module(self, archetype_name, model_state_factory): + arch = ARCHETYPES[archetype_name] + state = model_state_factory(arch) + parser_module = type(state.parser).__module__ + assert parser_module.endswith(arch.expected_parser_module), \ + f"{arch.name}: parser from {parser_module}, expected module ending with {arch.expected_parser_module}" + + +class TestDesireKeyDetection: + @pytest.mark.parametrize("archetype_name", ARCHETYPE_NAMES) + def test_desire_key(self, archetype_name, model_state_factory): + arch = ARCHETYPES[archetype_name] + state = model_state_factory(arch) + assert state.desire_key == arch.expected_desire_key, \ + f"{arch.name}: got {state.desire_key}, expected {arch.expected_desire_key}" + + +class TestVisionInputNames: + @pytest.mark.parametrize("archetype_name", ARCHETYPE_NAMES) + def test_vision_names_contain_img(self, archetype_name, model_state_factory): + arch = ARCHETYPES[archetype_name] + state = model_state_factory(arch) + assert len(state.vision_input_names) >= 1 + for name in state.vision_input_names: + assert 'img' in name, f"{arch.name}: vision input name '{name}' missing 'img'" + + +class TestOutputSlices: + @pytest.mark.parametrize("archetype_name", ARCHETYPE_NAMES) + def test_vision_slices_populated(self, archetype_name, model_state_factory): + arch = ARCHETYPES[archetype_name] + state = model_state_factory(arch) + assert len(state.vision_output_slices) > 0, f"{arch.name}: vision_output_slices empty" + + @pytest.mark.parametrize("archetype_name", ARCHETYPE_NAMES) + def test_policy_slices_match_type(self, archetype_name, model_state_factory): + arch = ARCHETYPES[archetype_name] + state = model_state_factory(arch) + if arch.expected_model_type == 'supercombo': + assert state.policy_output_slices == {}, f"{arch.name}: supercombo should have empty policy slices" + else: + assert len(state.policy_output_slices) > 0, f"{arch.name}: split/multi should have policy slices" + + +class TestInputQueueCreation: + @pytest.mark.parametrize("archetype_name", ARCHETYPE_NAMES) + def test_queues_not_empty(self, archetype_name, model_state_factory): + arch = ARCHETYPES[archetype_name] + state = model_state_factory(arch) + assert len(state.input_queues) > 0, f"{arch.name}: input_queues empty" + + @pytest.mark.parametrize("archetype_name", ARCHETYPE_NAMES) + def test_npy_contains_transforms(self, archetype_name, model_state_factory): + arch = ARCHETYPES[archetype_name] + state = model_state_factory(arch) + assert 'tfm' in state.numpy_inputs, f"{arch.name}: 'tfm' missing from npy" + assert 'big_tfm' in state.numpy_inputs, f"{arch.name}: 'big_tfm' missing from npy" + assert state.numpy_inputs['tfm'].shape == (3, 3) + assert state.numpy_inputs['big_tfm'].shape == (3, 3) + + @pytest.mark.parametrize("archetype_name", ARCHETYPE_NAMES) + def test_npy_contains_desire(self, archetype_name, model_state_factory): + arch = ARCHETYPES[archetype_name] + state = model_state_factory(arch) + assert arch.expected_desire_key in state.numpy_inputs, \ + f"{arch.name}: '{arch.expected_desire_key}' missing from npy" + + +class TestFrameBufferParams: + @pytest.mark.parametrize("archetype_name", ARCHETYPE_NAMES) + def test_frame_buf_params_per_vision_input(self, archetype_name, model_state_factory): + arch = ARCHETYPES[archetype_name] + state = model_state_factory(arch) + for name in state.vision_input_names: + assert name in state.frame_buf_params, f"{arch.name}: frame_buf_params missing '{name}'" + nv12_info = state.frame_buf_params[name] + assert len(nv12_info) >= 4, f"{arch.name}: nv12_info for '{name}' too short" + + +class TestBundleOverrides: + @pytest.mark.parametrize("archetype_name", ARCHETYPE_NAMES) + def test_smoothing_params_from_overrides(self, archetype_name, model_state_factory): + arch = ARCHETYPES[archetype_name] + state = model_state_factory(arch) + assert state.LAT_SMOOTH_SECONDS == 0.1 + assert state.LONG_SMOOTH_SECONDS == 0.3 + + @pytest.mark.parametrize("archetype_name", ARCHETYPE_NAMES) + def test_generation_from_bundle(self, archetype_name, model_state_factory): + arch = ARCHETYPES[archetype_name] + state = model_state_factory(arch) + assert state.generation == 10 + + +class TestMlsimProperty: + def test_mlsim_false_for_gen10(self, model_state_factory): + state = model_state_factory(ARCHETYPES['supercombo_non20hz']) + assert state.mlsim is False + + def test_mlsim_true_for_gen11(self, tmp_path, monkeypatch, patch_modeld): + from openpilot.common.hardware import hw + from openpilot.sunnypilot.modeld_v2.tests.conftest import write_pkl, ARCHETYPES as A + + arch = A['supercombo_non20hz'] + write_pkl(tmp_path, arch) + bundle = DummyBundle(models=arch.model_stubs, is_20hz=arch.is_20hz, generation=11) + patch_modeld(bundle) + monkeypatch.setattr(hw.Paths, 'model_root', staticmethod(lambda: str(tmp_path))) + + state = ModelState(cam_w=CAM_W, cam_h=CAM_H) + assert state.mlsim is True + + +class TestCrossArchetypeMismatch: + def test_wrong_is_20hz_changes_constants(self, tmp_path, monkeypatch, patch_modeld): + from openpilot.common.hardware import hw + from openpilot.sunnypilot.modeld_v2.tests.conftest import write_pkl + from openpilot.sunnypilot.modeld_v2.constants import ModelConstants + + arch = ARCHETYPES['vision_policy_split'] + write_pkl(tmp_path, arch) + bundle = DummyBundle(models=arch.model_stubs, is_20hz=False) + patch_modeld(bundle) + monkeypatch.setattr(hw.Paths, 'model_root', staticmethod(lambda: str(tmp_path))) + + state = ModelState(cam_w=CAM_W, cam_h=CAM_H) + assert type(state.constants) is ModelConstants, \ + "Wrong is_20hz should produce wrong constants class" diff --git a/openpilot/sunnypilot/modeld_v2/tests/test_compile_modeld.py b/openpilot/sunnypilot/modeld_v2/tests/test_compile_modeld.py new file mode 100644 index 0000000000..c30dd46e33 --- /dev/null +++ b/openpilot/sunnypilot/modeld_v2/tests/test_compile_modeld.py @@ -0,0 +1,161 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" + +import numpy as np +import pytest + +from openpilot.sunnypilot.modeld_v2.compile_modeld import derive_frame_skip, _detect_desire_key + + +class TestDeriveFrameSkip: + def test_non20hz_supercombo(self): + vision = {} + policy = {'features_buffer': (1, 99, 512), 'desire': (1, 100, 8)} + assert derive_frame_skip(vision, policy) == 1 + + def test_20hz_supercombo(self): + vision = {} + policy = {'features_buffer': (1, 24, 512), 'desire': (1, 25, 8)} + assert derive_frame_skip(vision, policy) == 4 + + def test_split_vision_policy(self): + vision = {'img': (1, 12, 128, 256)} + policy = {'features_buffer': (1, 25, 512), 'desire_pulse': (1, 25, 8)} + assert derive_frame_skip(vision, policy) == 4 + + def test_no_features_buffer(self): + assert derive_frame_skip({}, {}) == 1 + + +class TestFrameSkipBufferLengthEquivalence: + @pytest.mark.parametrize("frame_skip,expected_buffer_length", [ + (1, 2), + (4, 5), + ]) + def test_img_buffer_size_matches_warp_buffer_length(self, frame_skip, expected_buffer_length): + n_frames = 2 + img_buf_dim0 = frame_skip * (n_frames - 1) + 1 + assert img_buf_dim0 == expected_buffer_length, \ + f"frame_skip={frame_skip}: img_buf[0]={img_buf_dim0}, expected {expected_buffer_length}" + + @pytest.mark.parametrize("is_20hz,expected_frame_skip,expected_buffer_length", [ + (False, 1, 2), + (True, 4, 5), + ]) + def test_is_20hz_to_frame_skip_to_buffer_length(self, is_20hz, expected_frame_skip, expected_buffer_length): + if is_20hz: + policy_shapes = {'features_buffer': (1, 24, 512)} + else: + policy_shapes = {'features_buffer': (1, 99, 512)} + frame_skip = derive_frame_skip({}, policy_shapes) + assert frame_skip == expected_frame_skip + + n_frames = 2 + img_buf_dim0 = frame_skip * (n_frames - 1) + 1 + assert img_buf_dim0 == expected_buffer_length + + +class TestTemporalSamplingEquivalence: + def test_non20hz_desire_sampling_identity(self): + buf = np.random.default_rng(0).standard_normal((100, 1, 8)).astype(np.float32) + frame_skip = 1 + sampled = buf[::frame_skip].reshape(-1, 8) + assert sampled.shape == (100, 8) + np.testing.assert_array_equal(sampled, buf[:, 0, :]) + + def test_20hz_desire_sampling_max(self): + buf = np.zeros((100, 1, 8), dtype=np.float32) + buf[99, 0, 3] = 1.0 + frame_skip = 4 + reshaped = buf.reshape(-1, frame_skip, 1, 8).max(axis=1) + sampled = reshaped.reshape(-1, 8) + assert sampled.shape == (25, 8) + assert sampled[24, 3] == 1.0 + assert sampled[23, 3] == 0.0 + + def test_split_features_buffer_sampling_skip(self): + buf = np.arange(100 * 512, dtype=np.float32).reshape(100, 1, 512) + frame_skip = 4 + sampled = buf[::frame_skip].reshape(-1, 512) + assert sampled.shape == (25, 512) + np.testing.assert_array_equal(sampled[0], buf[0, 0]) + np.testing.assert_array_equal(sampled[1], buf[4, 0]) + np.testing.assert_array_equal(sampled[24], buf[96, 0]) + + def test_non20hz_features_buffer_sampling_identity(self): + buf = np.arange(99 * 512, dtype=np.float32).reshape(99, 1, 512) + frame_skip = 1 + sampled = buf[::frame_skip].reshape(-1, 512) + assert sampled.shape == (99, 512) + np.testing.assert_array_equal(sampled, buf[:, 0, :]) + + +class TestTemporalIdxEquivalence: + @pytest.mark.parametrize("mode,desire_shape,fb_shape,frame_skip", [ + ('non20hz', (1, 100, 8), (1, 99, 512), 1), + ('20hz', (1, 25, 8), (1, 24, 512), 4), + ('split', (1, 25, 8), (1, 25, 512), 4), + ]) + def test_features_buffer_idx_equivalence(self, mode, desire_shape, fb_shape, frame_skip): + history = fb_shape[1] + + if mode == 'non20hz': + modelstate_idxs = np.arange(history) + buf_len = history + elif mode == '20hz': + buf_len = (history + 1) * 4 + step = int(-buf_len / history) + modelstate_idxs = np.arange(step, step * (history + 1), step)[::-1] + elif mode == 'split': + buf_len = history * 4 + skip = buf_len // history + modelstate_idxs = np.arange(buf_len)[-1 - (skip * (history - 1))::skip] + + assert len(modelstate_idxs) == fb_shape[1], \ + f"{mode}: ModelState idx count {len(modelstate_idxs)} != input shape {fb_shape[1]}" + + @pytest.mark.parametrize("mode,desire_shape,fb_shape,frame_skip", [ + ('non20hz', (1, 100, 8), (1, 99, 512), 1), + ('20hz', (1, 25, 8), (1, 24, 512), 4), + ('split', (1, 25, 8), (1, 25, 512), 4), + ]) + def test_desire_idx_equivalence(self, mode, desire_shape, fb_shape, frame_skip): + history = desire_shape[1] + + compile_desire_buf_len = frame_skip * history if mode != 'non20hz' else history + compile_sampled_count = compile_desire_buf_len // frame_skip if frame_skip > 1 else compile_desire_buf_len + assert compile_sampled_count == history, \ + f"{mode}: compile desire samples {compile_sampled_count} != model input {history}" + + +class TestDetectDesireKey: + def test_finds_desire(self): + shapes = {'features_buffer': (1, 99, 512), 'desire': (1, 100, 8), 'traffic_convention': (1, 2)} + assert _detect_desire_key(shapes) == 'desire' + + def test_finds_desire_pulse(self): + shapes = {'features_buffer': (1, 25, 512), 'desire_pulse': (1, 25, 8), 'traffic_convention': (1, 2)} + assert _detect_desire_key(shapes) == 'desire_pulse' + + def test_returns_none_when_no_desire(self): + shapes = {'features_buffer': (1, 99, 512), 'traffic_convention': (1, 2)} + assert _detect_desire_key(shapes) is None + + +class TestOutputSlicePreservation: + def test_vision_hidden_state_slice_used_for_features(self): + mock_slices = {'hidden_state': slice(0, 512), 'plan': slice(512, 1024)} + features_slice = mock_slices['hidden_state'] + fake_output = np.random.default_rng(0).standard_normal((1, 1024)).astype(np.float32) + features = fake_output[:, features_slice] + assert features.shape == (1, 512) + + def test_policy_output_slices_independent(self): + vision_slices = {'hidden_state': slice(0, 512)} + policy_slices = {'plan': slice(0, 495), 'meta': slice(495, 550)} + assert set(vision_slices.keys()) & set(policy_slices.keys()) == set(), \ + "vision and policy slices should not overlap in keys" diff --git a/openpilot/sunnypilot/modeld_v2/tests/test_recovery_power.py b/openpilot/sunnypilot/modeld_v2/tests/test_recovery_power.py new file mode 100644 index 0000000000..d7c8563e64 --- /dev/null +++ b/openpilot/sunnypilot/modeld_v2/tests/test_recovery_power.py @@ -0,0 +1,72 @@ +from typing import Any + +import numpy as np + +from openpilot.cereal import log + +from openpilot.sunnypilot.modeld_v2.constants import Plan +from openpilot.sunnypilot.modeld_v2.modeld import ModelState +import openpilot.sunnypilot.modeld_v2.modeld as modeld + + +class MockStruct: + def __init__(self, **kwargs): + for k, v in kwargs.items(): + setattr(self, k, v) + + +def test_recovery_power_scaling(): + state: Any = MockStruct( + PLANPLUS_CONTROL=0.75, + LONG_SMOOTH_SECONDS=0.3, + LAT_SMOOTH_SECONDS=0.1, + MIN_LAT_CONTROL_SPEED=0.3, + mlsim=True, + generation=12, + constants=MockStruct(T_IDXS=np.arange(100), DESIRE_LEN=8) + ) + prev_action = log.ModelDataV2.Action() + recorded_vel: list = [] + recorded_curv_plans: list = [] + + def mock_accel(plan_vel, plan_accel, t_idxs, action_t=0.0): + recorded_vel.append(plan_vel.copy()) + return 0.0, False + + def mock_curvature(output, plan, vego, lat_action_t, mlsim): + recorded_curv_plans.append(plan.copy()) + return 0.0 + + modeld.get_accel_from_plan = mock_accel # ty: ignore[invalid-assignment] + modeld.get_curvature_from_output = mock_curvature # ty: ignore[invalid-assignment] + plan = np.random.default_rng(0).random((1, 100, 15)).astype(np.float32) + planplus = np.random.default_rng(1).random((1, 100, 15)).astype(np.float32) + merged_plan = plan + planplus + + model_output: dict = { + 'plan': merged_plan.copy(), + 'planplus': planplus.copy() + } + + test_cases: list = [ + # (control, v_ego) + (0.55, 20.0), + (1.0, 25.0), + (1.5, 25.1), + (2.0, 20.0), + (0.75, 19.0), + (0.8, 25.1), + ] + + for control, v_ego in test_cases: + state.PLANPLUS_CONTROL = control + recorded_vel.clear() + recorded_curv_plans.clear() + ModelState.get_action_from_model(state, model_output, prev_action, 0.0, 0.0, v_ego) # type: ignore[arg-type] + + expected_accel_plan_vel = plan[0, :, Plan.VELOCITY][:, 0] + planplus[0, :, Plan.VELOCITY][:, 0] + np.testing.assert_allclose(recorded_vel[0], expected_accel_plan_vel, rtol=1e-5, atol=1e-6) + + # For the below, yes, I know this isn't the same slicing as fillmodlmsg. This is to show that the values are only scaled on curv + expected_curv_plan_vel = plan[0, :, Plan.VELOCITY][:, 0] + control * planplus[0, :, Plan.VELOCITY][:, 0] + np.testing.assert_allclose(recorded_curv_plans[0][:, Plan.VELOCITY][:, 0], expected_curv_plan_vel, rtol=1e-5, atol=1e-6) diff --git a/openpilot/sunnypilot/modeld_v2/tests/test_warp.py b/openpilot/sunnypilot/modeld_v2/tests/test_warp.py new file mode 100644 index 0000000000..49dc634a4d --- /dev/null +++ b/openpilot/sunnypilot/modeld_v2/tests/test_warp.py @@ -0,0 +1,103 @@ +import os +os.environ['DEV'] = 'CPU' +import pytest +import numpy as np +from openpilot.system.camerad.cameras.nv12_info import get_nv12_info +from openpilot.sunnypilot.modeld_v2.warp import CAMERA_CONFIGS +from openpilot.sunnypilot.modeld_v2.warp import Warp, MODEL_W, MODEL_H + +VISION_NAME_PAIRS = [ # needed to account for supercombos input_imgs + ('img', 'big_img'), + ('input_imgs', 'big_input_imgs'), +] + + +class MockVisionBuf: + def __init__(self, w, h): + self.width = w + self.height = h + _, _, _, yuv_size = get_nv12_info(w, h) + self.data = np.zeros(yuv_size, dtype=np.uint8) + + +@pytest.mark.parametrize("buffer_length", [2, 5]) +def test_warp_initialization(buffer_length): + warp = Warp(buffer_length) + assert warp.buffer_length == buffer_length + assert warp.img_buffer_shape == (buffer_length * 6, MODEL_H // 2, MODEL_W // 2) + + +@pytest.mark.parametrize("buffer_length", [2, 5]) +@pytest.mark.parametrize("cam_w, cam_h", CAMERA_CONFIGS) +@pytest.mark.parametrize("road, wide", VISION_NAME_PAIRS) +def test_warp_process(buffer_length, cam_w, cam_h, road, wide): + warp = Warp(buffer_length) + mock_buf = MockVisionBuf(cam_w, cam_h) + transform = np.eye(3, dtype=np.float32).flatten() + bufs = {road: mock_buf, wide: mock_buf} + transforms = {road: transform, wide: transform} + + out = warp.process(bufs, transforms) + assert isinstance(out, dict) + assert road in out and wide in out + assert out[road].shape == (1, 12, MODEL_H // 2, MODEL_W // 2) + assert out[wide].shape == (1, 12, MODEL_H // 2, MODEL_W // 2) + + key = (cam_w, cam_h) + assert key in warp.jit_cache + + out2 = warp.process(bufs, transforms) + assert out2[road].shape == out[road].shape + + +@pytest.mark.parametrize("road, wide", VISION_NAME_PAIRS) +def test_warp_buffer_shift(road, wide): + warp = Warp(2) + cam_w, cam_h = CAMERA_CONFIGS[1] + transform = np.eye(3, dtype=np.float32).flatten() + + buf1 = MockVisionBuf(cam_w, cam_h) + buf1.data[0] = 255 + bufs1 = {road: buf1, wide: buf1} + transforms = {road: transform, wide: transform} + out1 = warp.process(bufs1, transforms) + road1 = out1[road].numpy().copy() + + buf2 = MockVisionBuf(cam_w, cam_h) + buf2.data[0] = 128 + bufs2 = {road: buf2, wide: buf2} + out2 = warp.process(bufs2, transforms) + assert not np.array_equal(road1, out2[road].numpy()) + + +@pytest.mark.parametrize("buffer_length", [2, 5]) +@pytest.mark.parametrize("road, wide", VISION_NAME_PAIRS) +def test_warp_buffer_accumulation(buffer_length, road, wide): + warp = Warp(buffer_length) + cam_w, cam_h = CAMERA_CONFIGS[0] + transform = np.eye(3, dtype=np.float32).flatten() + transforms = {road: transform, wide: transform} + outputs = [] + + for i in range(buffer_length + 1): + buf = MockVisionBuf(cam_w, cam_h) + buf.data[:] = i * 10 + out = warp.process({road: buf, wide: buf}, transforms) + outputs.append(out[road].numpy().copy()) + + assert warp.full_buffers['img'].shape == (buffer_length * 6, MODEL_H // 2, MODEL_W // 2) + for i in range(1, len(outputs)): + assert not np.array_equal(outputs[i - 1], outputs[i]) + + +def test_warp_different_cameras_same_instance(): + warp = Warp(2) + transform = np.eye(3, dtype=np.float32).flatten() + + buf1 = MockVisionBuf(*CAMERA_CONFIGS[0]) + warp.process({'img': buf1, 'big_img': buf1}, {'img': transform, 'big_img': transform}) + assert len(warp.jit_cache) == 1 + + buf2 = MockVisionBuf(*CAMERA_CONFIGS[1]) + warp.process({'img': buf2, 'big_img': buf2}, {'img': transform, 'big_img': transform}) + assert len(warp.jit_cache) == 2 diff --git a/openpilot/sunnypilot/modeld_v2/warp.py b/openpilot/sunnypilot/modeld_v2/warp.py new file mode 100644 index 0000000000..29d1925f8e --- /dev/null +++ b/openpilot/sunnypilot/modeld_v2/warp.py @@ -0,0 +1,171 @@ +import pickle +import time +import numpy as np +from pathlib import Path +from tinygrad.tensor import Tensor +from tinygrad.engine.jit import TinyJit +from tinygrad.device import Device + +from openpilot.system.camerad.cameras.nv12_info import get_nv12_info +from openpilot.common.transformations.model import MEDMODEL_INPUT_SIZE +from openpilot.common.transformations.camera import _ar_ox_fisheye, _os_fisheye +from openpilot.selfdrive.modeld.compile_modeld import NV12Frame, make_frame_prepare as _make_frame_prepare + +CAMERA_CONFIGS = [ + (_ar_ox_fisheye.width, _ar_ox_fisheye.height), + (_os_fisheye.width, _os_fisheye.height), +] + + +def make_frame_prepare(cam_w, cam_h, model_w, model_h): + nv12 = NV12Frame(cam_w, cam_h, *get_nv12_info(cam_w, cam_h)) + return _make_frame_prepare(nv12, model_w, model_h) + + +def warp_pkl_path(w, h): + from openpilot.selfdrive.modeld.helpers import MODELS_DIR + return MODELS_DIR / f'warp_{w}x{h}_tinygrad.pkl' + + +def make_update_img_input(frame_prepare, model_w, model_h): + def update_img_input_tinygrad(tensor, frame, M_inv): + M_inv = M_inv.to(Device.DEFAULT) + new_img = frame_prepare(frame, M_inv) + tensor.assign(tensor[6:].cat(new_img, dim=0).contiguous()) + return Tensor.cat(tensor[:6], tensor[-6:], dim=0).contiguous().reshape(1, 12, model_h//2, model_w//2) + return update_img_input_tinygrad + + +def make_update_both_imgs(frame_prepare, model_w, model_h): + update_img = make_update_img_input(frame_prepare, model_w, model_h) + def update_both_imgs_tinygrad(calib_img_buffer, new_img, M_inv, + calib_big_img_buffer, new_big_img, M_inv_big): + calib_img_pair = update_img(calib_img_buffer, new_img, M_inv) + calib_big_img_pair = update_img(calib_big_img_buffer, new_big_img, M_inv_big) + return calib_img_pair, calib_big_img_pair + return update_both_imgs_tinygrad + +MODELS_DIR = Path(__file__).parent / 'models' +MODEL_W, MODEL_H = MEDMODEL_INPUT_SIZE +UPSTREAM_BUFFER_LENGTH = 5 + + +def v2_warp_pkl_path(cam_w, cam_h, buffer_length): + return MODELS_DIR / f'warp_{cam_w}x{cam_h}_b{buffer_length}_tinygrad.pkl' + + +def compile_v2_warp(cam_w, cam_h, buffer_length): + _, _, _, yuv_size = get_nv12_info(cam_w, cam_h) + img_buffer_shape = (buffer_length * 6, MODEL_H // 2, MODEL_W // 2) + + print(f"Compiling v2 warp for {cam_w}x{cam_h} buffer_length={buffer_length}...") + + frame_prepare = make_frame_prepare(cam_w, cam_h, MODEL_W, MODEL_H) + update_both_imgs = make_update_both_imgs(frame_prepare, MODEL_W, MODEL_H) + update_img_jit = TinyJit(update_both_imgs, prune=True) + + full_buffer = Tensor.zeros(img_buffer_shape, dtype='uint8').contiguous().realize() + big_full_buffer = Tensor.zeros(img_buffer_shape, dtype='uint8').contiguous().realize() + new_frame_np = np.random.default_rng(0).integers(0, 256, yuv_size, dtype=np.uint8) + new_big_frame_np = np.random.default_rng(1).integers(0, 256, yuv_size, dtype=np.uint8) + for i in range(10): + img_inputs = [full_buffer, + Tensor.from_blob(new_frame_np.ctypes.data, (yuv_size,), dtype='uint8').realize(), + Tensor(Tensor.randn(3, 3).mul(8).realize().numpy(), device='NPY')] + big_img_inputs = [big_full_buffer, + Tensor.from_blob(new_big_frame_np.ctypes.data, (yuv_size,), dtype='uint8').realize(), + Tensor(Tensor.randn(3, 3).mul(8).realize().numpy(), device='NPY')] + inputs = img_inputs + big_img_inputs + Device.default.synchronize() + + st = time.perf_counter() + _ = update_img_jit(*inputs) + mt = time.perf_counter() + Device.default.synchronize() + et = time.perf_counter() + print(f" [{i+1}/10] enqueue {(mt-st)*1e3:6.2f} ms -- total {(et-st)*1e3:6.2f} ms") + + pkl_path = v2_warp_pkl_path(cam_w, cam_h, buffer_length) + with open(pkl_path, "wb") as f: + pickle.dump(update_img_jit, f) + print(f" Saved to {pkl_path}") + + jit = pickle.load(open(pkl_path, "rb")) + verify_frame = np.random.default_rng(0).integers(0, 256, yuv_size, dtype=np.uint8) + verify_big_frame = np.random.default_rng(1).integers(0, 256, yuv_size, dtype=np.uint8) + fresh_inputs = [ + Tensor.zeros(img_buffer_shape, dtype='uint8').contiguous().realize(), + Tensor.from_blob(verify_frame.ctypes.data, (yuv_size,), dtype='uint8').realize(), + Tensor(Tensor.randn(3, 3).mul(8).realize().numpy(), device='NPY'), + Tensor.zeros(img_buffer_shape, dtype='uint8').contiguous().realize(), + Tensor.from_blob(verify_big_frame.ctypes.data, (yuv_size,), dtype='uint8').realize(), + Tensor(Tensor.randn(3, 3).mul(8).realize().numpy(), device='NPY'), + ] + jit(*fresh_inputs) + + +class Warp: + def __init__(self, buffer_length=2): + self.buffer_length = buffer_length + self.img_buffer_shape = (buffer_length * 6, MODEL_H // 2, MODEL_W // 2) + + self.jit_cache = {} + self.full_buffers = {k: Tensor.zeros(self.img_buffer_shape, dtype='uint8').contiguous().realize() for k in ['img', 'big_img']} + self._blob_cache: dict[int, Tensor] = {} + self._nv12_cache: dict[tuple[int, int], int] = {} + self.transforms_np = {k: np.zeros((3, 3), dtype=np.float32) for k in ['img', 'big_img']} + self.transforms = {k: Tensor(v, device='NPY').realize() for k, v in self.transforms_np.items()} + + def process(self, bufs, transforms): + if not bufs: + return {} + road = next(n for n in bufs if 'big' not in n) + wide = next(n for n in bufs if 'big' in n) + cam_w, cam_h = bufs[road].width, bufs[road].height + key = (cam_w, cam_h) + + if key not in self.jit_cache: + v2_pkl = v2_warp_pkl_path(cam_w, cam_h, self.buffer_length) + if v2_pkl.exists(): + with open(v2_pkl, 'rb') as f: + self.jit_cache[key] = pickle.load(f) + elif self.buffer_length == UPSTREAM_BUFFER_LENGTH: + upstream_pkl = warp_pkl_path(cam_w, cam_h) + if upstream_pkl.exists(): + with open(upstream_pkl, 'rb') as f: + self.jit_cache[key] = pickle.load(f) + if key not in self.jit_cache: + frame_prepare = make_frame_prepare(cam_w, cam_h, MODEL_W, MODEL_H) + update_both_imgs = make_update_both_imgs(frame_prepare, MODEL_W, MODEL_H) + self.jit_cache[key] = TinyJit(update_both_imgs, prune=True) + + if key not in self._nv12_cache: + self._nv12_cache[key] = get_nv12_info(cam_w, cam_h)[3] + yuv_size = self._nv12_cache[key] + + road_ptr = bufs[road].data.ctypes.data + wide_ptr = bufs[wide].data.ctypes.data + if road_ptr not in self._blob_cache: + self._blob_cache[road_ptr] = Tensor.from_blob(road_ptr, (yuv_size,), dtype='uint8') + if wide_ptr not in self._blob_cache: + self._blob_cache[wide_ptr] = Tensor.from_blob(wide_ptr, (yuv_size,), dtype='uint8') + road_blob = self._blob_cache[road_ptr] + wide_blob = self._blob_cache[wide_ptr] if wide_ptr != road_ptr else Tensor.from_blob(wide_ptr, (yuv_size,), dtype='uint8') + np.copyto(self.transforms_np['img'], transforms[road].reshape(3, 3)) + np.copyto(self.transforms_np['big_img'], transforms[wide].reshape(3, 3)) + + Device.default.synchronize() + res = self.jit_cache[key]( + self.full_buffers['img'], road_blob, self.transforms['img'], + self.full_buffers['big_img'], wide_blob, self.transforms['big_img'], + ) + out_road = res[0].realize() + out_wide = res[1].realize() + + return {road: out_road, wide: out_wide} + + +if __name__ == "__main__": + for cam_w, cam_h in CAMERA_CONFIGS: + for bl in [2, 5]: + compile_v2_warp(cam_w, cam_h, bl) diff --git a/openpilot/sunnypilot/models/README.md b/openpilot/sunnypilot/models/README.md new file mode 100644 index 0000000000..bf4fb72a98 --- /dev/null +++ b/openpilot/sunnypilot/models/README.md @@ -0,0 +1,63 @@ +# Model Selector Version Compatibility + +This document explains the version compatibility mechanism used by the Model Selector system, and the rationale behind certain version constraints and JSON file management strategies. + +## Overview + +The Model Selector is responsible for selecting and validating model bundles based on their metadata and version constraints. Each model bundle is distributed via a JSON file and includes a `minimumSelectorVersion` field indicating the minimum selector version required to load it. + +To ensure robust compatibility and prevent mismatches between model expectations and selector capabilities, the selector enforces two version boundaries: + +* **`REQUIRED_MIN_SELECTOR_VERSION`**: the oldest selector version we support. +* **`CURRENT_SELECTOR_VERSION`**: the current version of the selector logic. + +## Version Compatibility Check + +A model bundle is considered compatible if: + +```python +REQUIRED_MIN_SELECTOR_VERSION <= bundle["minimumSelectorVersion"] <= CURRENT_SELECTOR_VERSION +``` + +This ensures: + +* **Old bundles are rejected** if they rely on deprecated selector behavior. +* **Future bundles are ignored** if they expect logic that the current selector doesn't yet implement. + +## Handling Breaking Changes + +When a deep change in selector behavior requires *all* models to be recompiled (e.g., due to a major architectural update), we: + +1. **Create a new JSON file** (e.g., from `models_v4.json` to `models_v5.json`). +2. **Assign updated `minimumSelectorVersion` values** in the new bundles. + +This allows older selector versions to continue using the previous JSON file, while newer versions point to the new one, preventing cross-contamination. + +## Why `REQUIRED_MIN_SELECTOR_VERSION` Still Matters + +Despite using new JSON files to isolate breaking changes, `REQUIRED_MIN_SELECTOR_VERSION` plays a critical role: + +### 1. **Cached Bundle Validation** + +Model bundles are cached locally (e.g., in-memory or on disk). A user might have previously loaded a now-invalid bundle from an older JSON file. + +`REQUIRED_MIN_SELECTOR_VERSION` prevents the selector from reloading or trusting that stale cached bundle, even if the original JSON is gone. + +### 2. **Explicit Deprecation Boundary** + +By raising `REQUIRED_MIN_SELECTOR_VERSION`, we declare older bundles officially unsupported, even if they technically still exist in a legacy JSON file. + +### 3. **Avoiding Race Conditions** + +Some clients may have intermittent access to updated JSONs. The runtime check ensures version compatibility is enforced independently of external file state. + +## Summary + +| Component | Purpose | +| ------------------------------- | --------------------------------------------------------------------- | +| `minimumSelectorVersion` | Declares the minimum selector version required to load a model bundle | +| `REQUIRED_MIN_SELECTOR_VERSION` | Prevents loading bundles that are too old (e.g., from stale cache) | +| `CURRENT_SELECTOR_VERSION` | Prevents loading bundles that are too new or forward-incompatible | +| JSON file renaming | Isolates bundles by selector generation to handle full recompiles | + +This layered strategy ensures safe evolution of the model selection system while maintaining backward compatibility and runtime protection against stale or incompatible bundles. diff --git a/sunnypilot/selfdrive/car/tests/__init__.py b/openpilot/sunnypilot/models/__init__.py similarity index 100% rename from sunnypilot/selfdrive/car/tests/__init__.py rename to openpilot/sunnypilot/models/__init__.py diff --git a/sunnypilot/modeld/constants.py b/openpilot/sunnypilot/models/constants.py similarity index 100% rename from sunnypilot/modeld/constants.py rename to openpilot/sunnypilot/models/constants.py diff --git a/openpilot/sunnypilot/models/default_model.py b/openpilot/sunnypilot/models/default_model.py new file mode 100755 index 0000000000..62b6831402 --- /dev/null +++ b/openpilot/sunnypilot/models/default_model.py @@ -0,0 +1,61 @@ +import argparse +import os +import hashlib + +from openpilot.common.basedir import BASEDIR +from openpilot.sunnypilot import get_file_hash +from openpilot.sunnypilot.models.model_name import DEFAULT_MODEL + +DEFAULT_MODEL_NAME_PATH = os.path.join(BASEDIR, "openpilot", "sunnypilot", "models", "model_name.py") +MODEL_HASH_PATH = os.path.join(BASEDIR, "openpilot", "sunnypilot", "models", "tests", "model_hash") +SUPERCOMBO_ONNX_PATH = os.path.join(BASEDIR, "openpilot", "selfdrive", "modeld", "models", "driving_supercombo.onnx") + + +def update_model_hash(): + supercombo_hash = get_file_hash(SUPERCOMBO_ONNX_PATH) + + combined_hash = hashlib.sha256(supercombo_hash.encode()).hexdigest() + + with open(MODEL_HASH_PATH, "w") as f: + f.write(combined_hash) + + print(f"Generated and updated new combined model hash to {MODEL_HASH_PATH}") + + +def get_current_default_model_name(): + print("[GET DEFAULT MODEL NAME]") + name = DEFAULT_MODEL + print(f'Current default model name: "{name}"') + + return name + + +def update_default_model_name(name: str): + print("[CHANGE DEFAULT MODEL NAME]") + with open(DEFAULT_MODEL_NAME_PATH, "w") as f: + f.write(f'DEFAULT_MODEL = "{name}"\n') + print(f'New default model name: "{name}"') + print("[DONE]") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Update default model name and hash") + parser.add_argument("--new_name", type=str, help="New default model name") + args = parser.parse_args() + + if not args.new_name: + print("Warning: No new default model name provided. Use --new_name to specify") + print("Default model name and hash will not be updated! (aborted)") + exit(0) + + current_name = get_current_default_model_name() + new_name = args.new_name + if current_name == new_name: + print(f'Proposed default model name: "{new_name}"') + confirm = input("Proposed default model name is the same as the current default model name. Confirm? (y/n): ").upper().strip() + if confirm != "Y": + print("Default model name and hash will not be updated! (aborted)") + exit(0) + + update_default_model_name(new_name) + update_model_hash() diff --git a/sunnypilot/models/fetcher.py b/openpilot/sunnypilot/models/fetcher.py similarity index 75% rename from sunnypilot/models/fetcher.py rename to openpilot/sunnypilot/models/fetcher.py index 02ae52d77e..b5197988bb 100644 --- a/sunnypilot/models/fetcher.py +++ b/openpilot/sunnypilot/models/fetcher.py @@ -5,15 +5,15 @@ This file is part of sunnypilot and is licensed under the MIT License. See the LICENSE.md file in the root directory for more details. """ -import json import time import requests +from requests.exceptions import (SSLError, RequestException, HTTPError) from openpilot.common.params import Params from openpilot.common.swaglog import cloudlog -from sunnypilot.models.helpers import is_bundle_version_compatible +from openpilot.sunnypilot.models.helpers import is_bundle_version_compatible -from cereal import custom +from openpilot.cereal import custom class ModelParser: @@ -67,6 +67,7 @@ class ModelParser: model_bundle.is20hz = bundle.get("is_20hz", False) model_bundle.minimumSelectorVersion = int(bundle["minimum_selector_version"]) model_bundle.overrides = ModelParser._parse_overrides(bundle.get("overrides", {})) + model_bundle.ref = bundle.get("ref") return model_bundle @@ -88,8 +89,8 @@ class ModelCache: def _is_expired(self) -> bool: """Checks if the cache has expired""" current_time = int(time.monotonic() * 1e9) - last_sync = int(self.params.get(self._LAST_SYNC_KEY, encoding="utf-8") or 0) - return last_sync == 0 or (current_time - last_sync) >= self.cache_timeout + last_sync = self.params.get(self._LAST_SYNC_KEY) or 0 + return bool(last_sync == 0) or (current_time - last_sync) >= self.cache_timeout def get(self) -> tuple[dict, bool]: """ @@ -98,43 +99,60 @@ class ModelCache: If no cached data exists or on error, returns an empty dict """ try: - cached_data = self.params.get(self._CACHE_KEY, encoding="utf-8") + cached_data = self.params.get(self._CACHE_KEY) if not cached_data: cloudlog.warning("No cached model data available") return {}, True - return json.loads(cached_data), self._is_expired() + return cached_data, self._is_expired() except Exception as e: cloudlog.exception(f"Error retrieving cached model data: {str(e)}") return {}, True def set(self, data: dict) -> None: """Updates the cache with new model data""" - self.params.put(self._CACHE_KEY, json.dumps(data)) - self.params.put(self._LAST_SYNC_KEY, str(int(time.monotonic() * 1e9))) + self.params.put(self._CACHE_KEY, data, block=True) + self.params.put(self._LAST_SYNC_KEY, int(time.monotonic() * 1e9), block=True) class ModelFetcher: """Handles fetching and caching of model data from remote source""" - MODEL_URL = "https://docs.sunnypilot.ai/driving_models_v4.json" + MODEL_URL = "https://raw.githubusercontent.com/sunnypilot/sunnypilot-models/refs/heads/gh-pages/docs/driving_models_v17.json" def __init__(self, params: Params): self.params = params self.model_cache = ModelCache(params) self.model_parser = ModelParser() - def _fetch_and_cache_models(self) -> list[custom.ModelManagerSP.ModelBundle]: - """Fetches fresh model data from remote and updates cache""" + def _fetch_and_cache_models(self) -> list[custom.ModelManagerSP.ModelBundle] | None: + """Fetches fresh model data from remote and updates cache. + Returns None on transport errors. Raises on 404 and other fatal HTTP errors. + """ try: response = requests.get(self.MODEL_URL, timeout=10) - response.raise_for_status() - json_data = response.json() + # Explicitly handle 404 differently + if response.status_code == 404: + cloudlog.error(f"Models URL returned 404 Not Found: {self.MODEL_URL}") + raise HTTPError(f"404 Not Found: {self.MODEL_URL}", response=response) + + # Raise for any other 4xx/5xx + response.raise_for_status() + + json_data = response.json() self.model_cache.set(json_data) cloudlog.debug("Successfully updated models cache") return self.model_parser.parse_models(json_data) - except Exception: - cloudlog.exception("Error fetching models") - raise + + except ConnectionError as e: + cloudlog.warning(f"DNS/connection error while fetching models: {e}") + except SSLError as e: + cloudlog.warning(f"SSL error while fetching models: {e}") + except RequestException as e: + cloudlog.warning(f"Request transport error while fetching models: {e}") + except Exception as e: + cloudlog.exception(f"Unexpected error fetching models: {e}") + + return None def get_available_bundles(self) -> list[custom.ModelManagerSP.ModelBundle]: """Gets the list of available models, with smart cache handling""" @@ -144,12 +162,12 @@ class ModelFetcher: cloudlog.debug("Using valid cached models data") return self.model_parser.parse_models(cached_data) - try: - return self._fetch_and_cache_models() - except Exception: - if not cached_data: - cloudlog.exception("Failed to fetch fresh data and no cache available") - raise + fetched_bundles = self._fetch_and_cache_models() + if fetched_bundles is not None: + return fetched_bundles + + if not cached_data: + cloudlog.warning("Failed to fetch fresh data and no cache available") cloudlog.warning("Failed to fetch fresh data. Using expired cache as fallback") return self.model_parser.parse_models(cached_data) diff --git a/openpilot/sunnypilot/models/helpers.py b/openpilot/sunnypilot/models/helpers.py new file mode 100644 index 0000000000..ad1333d4ed --- /dev/null +++ b/openpilot/sunnypilot/models/helpers.py @@ -0,0 +1,207 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" + +import hashlib +import os +import pickle +from pathlib import Path +import numpy as np + +from openpilot.cereal import custom +from openpilot.common.params import Params +from openpilot.common.swaglog import cloudlog +from openpilot.sunnypilot.models.constants import Meta, MetaSimPose, MetaTombRaider +from openpilot.common.hardware.hw import Paths + +# SET ME TO THE EXACT JSON VERSION WE SET IN SUNNYPILOT_MODELS REPO +REQUIRED_JSON_VERSION = 15 + +CUSTOM_MODEL_PATH = Paths.model_root() +METADATA_PATH = Path(__file__).parent / '../models/supercombo_metadata.pkl' +ModelManager = custom.ModelManagerSP +_LAST_VALIDATED_RAW = None + + +def _compute_hash(file_path: str) -> str | None: + from openpilot.common.file_chunker import open_file_chunked + try: + with open_file_chunked(file_path) as file: + return hashlib.file_digest(file, "sha256").hexdigest().lower() + except FileNotFoundError: + return None + + +async def verify_file(file_path: str, expected_hash: str) -> bool: + file_hash = _compute_hash(file_path) + return file_hash == expected_hash.lower() if file_hash else False + + +def _verify_file(file_path: str, expected_hash: str) -> bool: + file_hash = _compute_hash(file_path) + return file_hash == expected_hash.lower() if file_hash else False + + +def is_bundle_version_compatible(bundle: dict) -> bool: + """ + The bundle parsed from the json specifies a `minimum_selector_version`, which defines the minimum selector version + required to load the model. This function ensures that: + the bundle MUST match the `REQUIRED_JSON_VERSION` set here in helpers. + """ + return bundle.get("minimumSelectorVersion", 0) == REQUIRED_JSON_VERSION + + +def _bundle_artifacts(bundle: custom.ModelManagerSP.ModelBundle) -> list[tuple[str, str]]: + artifacts = [] + for model in getattr(bundle, 'models', []) or []: + for artifact in (getattr(model, 'artifact', None), getattr(model, 'metadata', None)): + if artifact and getattr(artifact, 'fileName', None) and getattr(artifact, 'downloadUri', None): + sha256 = getattr(artifact.downloadUri, 'sha256', None) + if sha256: + artifacts.append((artifact.fileName, sha256)) + return artifacts + + +def _bundle_is_valid_locally(bundle: custom.ModelManagerSP.ModelBundle) -> bool: + model_root = Paths.model_root() + return all(_verify_file(os.path.join(model_root, file_name), expected_hash) + for file_name, expected_hash in _bundle_artifacts(bundle)) + + +def _bundle_needs_reset(active_bundle: custom.ModelManagerSP.ModelBundle, available_bundles: list[custom.ModelManagerSP.ModelBundle] | None) -> bool: + if active_bundle is None: + return False + + if available_bundles is not None: + matching_bundle = None + for bundle in available_bundles: + if getattr(active_bundle, 'ref', None) and getattr(bundle, 'ref', None): + if active_bundle.ref == bundle.ref: + matching_bundle = bundle + break + elif getattr(active_bundle, 'internalName', None) == getattr(bundle, 'internalName', None): + matching_bundle = bundle + break + + if matching_bundle is None: + return True + if active_bundle.minimumSelectorVersion != matching_bundle.minimumSelectorVersion: + return True + + active_runner = getattr(active_bundle, 'runner', None) + matching_runner = getattr(matching_bundle, 'runner', None) + if active_runner is not None and matching_runner is not None: + if getattr(active_runner, 'raw', active_runner) != getattr(matching_runner, 'raw', matching_runner): + return True + if set(_bundle_artifacts(active_bundle)) != set(_bundle_artifacts(matching_bundle)): + return True + + return not _bundle_is_valid_locally(active_bundle) + + +def validate_active_bundle(params: Params, available_bundles: list[custom.ModelManagerSP.ModelBundle] | None = None) -> None: + global _LAST_VALIDATED_RAW + + raw_bundle = params.get("ModelManager_ActiveBundle") + if not raw_bundle: + return + + if raw_bundle == _LAST_VALIDATED_RAW: + return + + active_bundle = get_active_bundle(params, raw_bundle_dict=raw_bundle) + if active_bundle is None or _bundle_needs_reset(active_bundle, available_bundles): + cloudlog.warning("Active model bundle invalid; resetting to default") + params.remove("ModelManager_ActiveBundle") + params.put("ModelRunnerTypeCache", int(custom.ModelManagerSP.Runner.stock), block=True) + _LAST_VALIDATED_RAW = None + else: + _LAST_VALIDATED_RAW = raw_bundle + + +def get_active_bundle(params: Params | None = None, raw_bundle_dict: dict | bytes | None = None) -> "custom.ModelManagerSP.ModelBundle | None": + params = params or Params() + try: + active_bundle_dict = raw_bundle_dict if raw_bundle_dict is not None else (params.get("ModelManager_ActiveBundle") or {}) + if isinstance(active_bundle_dict, dict) and active_bundle_dict and is_bundle_version_compatible(active_bundle_dict): + return custom.ModelManagerSP.ModelBundle(**active_bundle_dict) + except Exception: + pass + return None + + +def get_active_model_runner(params: Params | None = None, force_check: bool = False) -> int: + params = params or Params() + cached_runner_type = params.get("ModelRunnerTypeCache") + if cached_runner_type is not None and not force_check: + return cached_runner_type + runner_type = custom.ModelManagerSP.Runner.stock + if active_bundle := get_active_bundle(params): + runner_type = active_bundle.runner.raw + + if cached_runner_type != runner_type: + params.put("ModelRunnerTypeCache", int(runner_type), block=True) + + return runner_type + + +def _get_model(): + if bundle := get_active_bundle(): + drive_model = next(model for model in bundle.models if model.type == ModelManager.Model.Type.supercombo) + return drive_model + return None + + +def load_metadata(): + model = _get_model() + metadata_path = f"{CUSTOM_MODEL_PATH}/{model.metadata.fileName}" if model else METADATA_PATH + + with open(metadata_path, 'rb') as f: + return pickle.load(f) + + +def prepare_inputs(model_metadata: dict) -> dict[str, np.ndarray]: + return { + key: np.zeros(shape, dtype=np.float32).flatten() + for key, shape in model_metadata['input_shapes'].items() + if 'img' not in key + } + + +def load_meta_constants(model_metadata: dict): + """ Loads the appropriate meta model class based on key shapes""" + if 'sim_pose' in model_metadata['input_shapes']: + return MetaSimPose + + meta_slice = model_metadata['output_slices']['meta'] + if (meta_slice.start, meta_slice.stop, meta_slice.step) == (5868, 5921, None): + return MetaTombRaider + + return Meta + + +# The following method(s) are modeld helper methods +def plan_x_idxs_helper(constants, plan, model_output) -> list[float]: + # times at X_IDXS according to plan. + LINE_T_IDXS = [np.nan] * constants.IDX_N + LINE_T_IDXS[0] = 0.0 + plan_x = model_output['plan'][0, :, plan.POSITION][:, 0].tolist() + for xidx in range(1, constants.IDX_N): + tidx = 0 + # increment tidx until we find an element that's further away than the current xidx + while tidx < constants.IDX_N - 1 and plan_x[tidx + 1] < constants.X_IDXS[xidx]: + tidx += 1 + if tidx == constants.IDX_N - 1: + # if the plan doesn't extend far enough, set plan_t to the max value (10s), then break + LINE_T_IDXS[xidx] = constants.T_IDXS[constants.IDX_N - 1] + break + # interpolate to find `t` for the current xidx + current_x_val = plan_x[tidx] + next_x_val = plan_x[tidx + 1] + p = (constants.X_IDXS[xidx] - current_x_val) / (next_x_val - current_x_val) if abs( + next_x_val - current_x_val) > 1e-9 else float('nan') + LINE_T_IDXS[xidx] = p * constants.T_IDXS[tidx + 1] + (1 - p) * constants.T_IDXS[tidx] + return LINE_T_IDXS diff --git a/openpilot/sunnypilot/models/manager.py b/openpilot/sunnypilot/models/manager.py new file mode 100644 index 0000000000..3338a91711 --- /dev/null +++ b/openpilot/sunnypilot/models/manager.py @@ -0,0 +1,299 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" + +import asyncio +import os +import time + +import aiohttp +from openpilot.common.params import Params +from openpilot.common.realtime import Ratekeeper +from openpilot.common.swaglog import cloudlog +from openpilot.common.hardware.hw import Paths + +from openpilot.cereal import messaging, custom +from openpilot.sunnypilot.models.fetcher import ModelFetcher +from openpilot.sunnypilot.models.helpers import get_active_bundle, validate_active_bundle, verify_file + + +class ModelManagerSP: + """Manages model downloads and status reporting""" + + def __init__(self): + self.params = Params() + self.model_fetcher = ModelFetcher(self.params) + self.pm = messaging.PubMaster(["modelManagerSP"]) + self.available_models: list[custom.ModelManagerSP.ModelBundle] = [] + self.selected_bundle: custom.ModelManagerSP.ModelBundle = None + self.active_bundle: custom.ModelManagerSP.ModelBundle = get_active_bundle(self.params) + self._chunk_size = 128 * 1000 # 128 KB chunks + self._download_start_times: dict[str, float] = {} # Track start time per model + + def _sync_artifact_progress(self, source_artifact) -> None: + """Mirror download progress to all artifacts sharing the same filename in the selected bundle.""" + if not self.selected_bundle: + return + for model in self.selected_bundle.models: + for artifact in (model.artifact, model.metadata): + if artifact is not source_artifact and artifact.fileName == source_artifact.fileName: + artifact.downloadProgress.status = source_artifact.downloadProgress.status + artifact.downloadProgress.progress = source_artifact.downloadProgress.progress + artifact.downloadProgress.eta = source_artifact.downloadProgress.eta + + def _calculate_eta(self, filename: str, progress: float) -> int: + """Calculate ETA based on elapsed time and current progress""" + if filename not in self._download_start_times or progress <= 0: + return 60 # Default ETA for new downloads + + elapsed_time = time.monotonic() - self._download_start_times[filename] + if elapsed_time <= 0: + return 60 + + # If we're at X% after Y seconds, we can estimate total time as (Y / X) * 100 + total_estimated_time = (elapsed_time / progress) * 100 + eta = total_estimated_time - elapsed_time + + return max(1, int(eta)) # Return at least 1 second if download is ongoing + + async def _download_file(self, url: str, path: str, model) -> None: + """Downloads a file with progress tracking""" + self._download_start_times[model.fileName] = time.monotonic() + + async with aiohttp.ClientSession() as session: + async with session.get(url) as response: + response.raise_for_status() + total_size = int(response.headers.get("content-length", 0)) + bytes_downloaded = 0 + + with open(path, 'wb') as f: # noqa: ASYNC230 + async for chunk in response.content.iter_chunked(self._chunk_size): # type: bytes + f.write(chunk) + bytes_downloaded += len(chunk) + + if self.params.get("ModelManager_DownloadIndex") is None: + raise Exception("Download cancelled") + + if total_size > 0: + progress = (bytes_downloaded / total_size) * 100 + model.downloadProgress.status = custom.ModelManagerSP.DownloadStatus.downloading + model.downloadProgress.progress = progress + model.downloadProgress.eta = self._calculate_eta(model.fileName, progress) + self._sync_artifact_progress(model) + self._report_status() + + # Clean up start time after download completes + del self._download_start_times[model.fileName] + + async def _download_chunked(self, base_url: str, base_path: str, artifact) -> None: + from openpilot.common.file_chunker import get_manifest_path, get_chunk_name + manifest_url = get_manifest_path(base_url) + manifest_path = get_manifest_path(base_path) + + async with aiohttp.ClientSession() as session: + async with session.get(manifest_url) as resp: + if resp.status == 404: + raise FileNotFoundError + resp.raise_for_status() + num_chunks = int((await resp.read()).strip()) + + self._download_start_times[artifact.fileName] = time.monotonic() + + for i in range(num_chunks): + chunk_url = get_chunk_name(base_url, i, num_chunks) + chunk_path = get_chunk_name(base_path, i, num_chunks) + chunk_downloaded = 0 + async with aiohttp.ClientSession() as session: + async with session.get(chunk_url) as response: + response.raise_for_status() + chunk_size = int(response.headers.get("content-length", 0)) + with open(chunk_path, 'wb') as f: # noqa: ASYNC230 + async for data in response.content.iter_chunked(self._chunk_size): + f.write(data) + chunk_downloaded += len(data) + if self.params.get("ModelManager_DownloadIndex") is None: + raise Exception("Download cancelled") + intra = chunk_downloaded / max(chunk_size, 1) + progress = min(99, (i + intra) / num_chunks * 100) + artifact.downloadProgress.status = custom.ModelManagerSP.DownloadStatus.downloading + artifact.downloadProgress.progress = progress + artifact.downloadProgress.eta = self._calculate_eta(artifact.fileName, progress) + self._sync_artifact_progress(artifact) + self._report_status() + + with open(manifest_path, 'w') as f: # noqa: ASYNC230 + f.write(str(num_chunks)) + if os.path.isfile(base_path): # noqa: ASYNC240 + os.remove(base_path) + del self._download_start_times[artifact.fileName] + + async def _process_artifact(self, artifact, destination_path: str) -> None: + if not artifact.downloadUri.uri: + return None + + url = artifact.downloadUri.uri + expected_hash = artifact.downloadUri.sha256 + filename = artifact.fileName + full_path = os.path.join(destination_path, filename) + + try: + if await verify_file(full_path, expected_hash): + artifact.downloadProgress.status = custom.ModelManagerSP.DownloadStatus.cached + artifact.downloadProgress.progress = 100 + artifact.downloadProgress.eta = 0 + self._sync_artifact_progress(artifact) + self._report_status() + return + + try: + await self._download_chunked(url, full_path, artifact) + except (FileNotFoundError, aiohttp.ClientResponseError): + await self._download_file(url, full_path, artifact) + + if not await verify_file(full_path, expected_hash): + raise ValueError(f"Hash validation failed for {filename}") + + artifact.downloadProgress.status = custom.ModelManagerSP.DownloadStatus.downloaded + artifact.downloadProgress.progress = 100 + artifact.downloadProgress.eta = 0 + self._sync_artifact_progress(artifact) + self._report_status() + + except Exception as e: + cloudlog.error(f"Error downloading {filename}: {str(e)}") + for f in [full_path] + [p for p in (os.path.join(destination_path, f) for f in os.listdir(destination_path)) if filename in p]: + if os.path.isfile(f): # noqa: ASYNC240 + os.remove(f) + artifact.downloadProgress.status = custom.ModelManagerSP.DownloadStatus.failed + artifact.downloadProgress.eta = 0 + self._sync_artifact_progress(artifact) + self.selected_bundle.status = custom.ModelManagerSP.DownloadStatus.failed + self._report_status() + self._download_start_times.pop(artifact.fileName, None) + raise + + async def _process_model(self, model, destination_path: str) -> None: + """Processes a single model download including verification""" + model_artifact = model.artifact + metadata_artifact = model.metadata + + await self._process_artifact(metadata_artifact, destination_path) + await self._process_artifact(model_artifact, destination_path) + + def _report_status(self) -> None: + """Reports current status through messaging system""" + msg = messaging.new_message('modelManagerSP', valid=True) + model_manager_state = msg.modelManagerSP + if self.selected_bundle: + model_manager_state.selectedBundle = self.selected_bundle + + if self.active_bundle: + model_manager_state.activeBundle = self.active_bundle + + model_manager_state.availableBundles = self.available_models + self.pm.send('modelManagerSP', msg) + + async def _download_bundle(self, model_bundle: custom.ModelManagerSP.ModelBundle, destination_path: str) -> None: + """Downloads all models in a bundle""" + self.selected_bundle = model_bundle + self.selected_bundle.status = custom.ModelManagerSP.DownloadStatus.downloading + os.makedirs(destination_path, exist_ok=True) + + try: + seen_artifacts: set[str] = set() + for model in self.selected_bundle.models: + for artifact in (model.metadata, model.artifact): + if not artifact.fileName: + continue + if artifact.fileName in seen_artifacts: + artifact.downloadProgress.status = custom.ModelManagerSP.DownloadStatus.cached + artifact.downloadProgress.progress = 100 + artifact.downloadProgress.eta = 0 + else: + seen_artifacts.add(artifact.fileName) + await self._process_artifact(artifact, destination_path) + + self.active_bundle = self.selected_bundle + self.active_bundle.status = custom.ModelManagerSP.DownloadStatus.downloaded + self.params.put("ModelManager_ActiveBundle", self.active_bundle.to_dict(), block=True) + self.selected_bundle = None + + except Exception: + if self.selected_bundle is not None: + self.selected_bundle.status = custom.ModelManagerSP.DownloadStatus.failed + raise + + finally: + self._report_status() + + def download(self, model_bundle: custom.ModelManagerSP.ModelBundle, destination_path: str) -> None: + """Main entry point for downloading a model bundle""" + asyncio.run(self._download_bundle(model_bundle, destination_path)) + + def main_thread(self) -> None: + """Main thread for model management""" + rk = Ratekeeper(1, print_delay_threshold=None) + + while True: + try: + self.available_models = self.model_fetcher.get_available_bundles() + validate_active_bundle(self.params, self.available_models) + self.active_bundle = get_active_bundle(self.params) + + if (index_to_download := self.params.get("ModelManager_DownloadIndex")) is not None: + if model_to_download := next((model for model in self.available_models if model.index == index_to_download), None): + try: + self.download(model_to_download, Paths.model_root()) + except Exception as e: + cloudlog.exception(e) + finally: + self.params.remove("ModelManager_DownloadIndex") + self.selected_bundle = None + + if self.params.get("ModelManager_ClearCache"): + self.clear_model_cache() + self.params.remove("ModelManager_ClearCache") + + self._report_status() + rk.keep_time() + + except Exception as e: + cloudlog.exception(f"Error in main thread: {str(e)}") + rk.keep_time() + + def clear_model_cache(self) -> None: + """ + Clears the model cache directory of all files except those in the active model bundle. + """ + + # Get list of files used by active model bundle + active_files = [] + if self.active_bundle is not None: # When the default model is active + for model in self.active_bundle.models: + if hasattr(model, 'artifact') and model.artifact.fileName: + active_files.append(model.artifact.fileName) + if hasattr(model, 'metadata') and model.metadata.fileName: + active_files.append(model.metadata.fileName) + + # Remove all files except active ones (including their chunk files) + model_dir = Paths.model_root() + try: + for filename in os.listdir(model_dir): + base = filename.split('.chunk')[0] if '.chunk' in filename else filename + if base not in active_files and filename not in active_files: + file_path = os.path.join(model_dir, filename) + if os.path.isfile(file_path): + os.remove(file_path) + cloudlog.info("Model cache cleared, keeping active model files") + except Exception as e: + cloudlog.exception(f"Error clearing model cache: {str(e)}") + +def main(): + ModelManagerSP().main_thread() + + +if __name__ == "__main__": + main() diff --git a/openpilot/sunnypilot/models/model_name.py b/openpilot/sunnypilot/models/model_name.py new file mode 100644 index 0000000000..02a6c2bac2 --- /dev/null +++ b/openpilot/sunnypilot/models/model_name.py @@ -0,0 +1 @@ +DEFAULT_MODEL = "CD210" diff --git a/openpilot/sunnypilot/models/runners/constants.py b/openpilot/sunnypilot/models/runners/constants.py new file mode 100644 index 0000000000..344f8f98cc --- /dev/null +++ b/openpilot/sunnypilot/models/runners/constants.py @@ -0,0 +1,15 @@ +import os +import numpy as np +from openpilot.common.hardware.hw import Paths +from openpilot.cereal import custom + +# Type definitions for clarity +NumpyDict = dict[str, np.ndarray] +ShapeDict = dict[str, tuple[int, ...]] +SliceDict = dict[str, slice] + +ModelType = custom.ModelManagerSP.Model.Type +Model = custom.ModelManagerSP.Model + +SEND_RAW_PRED = os.getenv('SEND_RAW_PRED') +CUSTOM_MODEL_PATH = Paths.model_root() diff --git a/openpilot/sunnypilot/models/runners/helpers.py b/openpilot/sunnypilot/models/runners/helpers.py new file mode 100644 index 0000000000..b34a62132b --- /dev/null +++ b/openpilot/sunnypilot/models/runners/helpers.py @@ -0,0 +1,28 @@ +from openpilot.sunnypilot.models.helpers import get_active_bundle +from openpilot.sunnypilot.models.runners.model_runner import ModelRunner +from openpilot.sunnypilot.models.runners.tinygrad.tinygrad_runner import TinygradRunner, TinygradSplitRunner +from openpilot.sunnypilot.models.runners.constants import ModelType + + +def get_model_runner() -> ModelRunner: + """ + Factory function to create and return the appropriate ModelRunner instance. + + Selects TinygradRunner, choosing TinygradSplitRunner if separate vision/policy + models are detected in the active bundle. + + :return: An instance of a ModelRunner subclass (ONNXRunner, TinygradRunner, or TinygradSplitRunner). + """ + bundle = get_active_bundle() + if bundle and bundle.models: + model_types = {m.type.raw for m in bundle.models} + # Check if the bundle uses separate vision and policy models (legacy or new split format) + split_types = {ModelType.vision, ModelType.policy, ModelType.offPolicy, ModelType.onPolicy} + if model_types & split_types: + return TinygradSplitRunner() + # Otherwise, assume a single model (likely supercombo) + if bundle.models: + return TinygradRunner(bundle.models[0].type.raw) + + # Default fallback to TinygradRunner with the supercombo type if bundle info is missing/incomplete + return TinygradRunner(ModelType.supercombo) diff --git a/sunnypilot/models/runners/model_runner.py b/openpilot/sunnypilot/models/runners/model_runner.py similarity index 89% rename from sunnypilot/models/runners/model_runner.py rename to openpilot/sunnypilot/models/runners/model_runner.py index 7124662791..cbf2fc5e20 100644 --- a/sunnypilot/models/runners/model_runner.py +++ b/openpilot/sunnypilot/models/runners/model_runner.py @@ -1,28 +1,14 @@ -import os from abc import abstractmethod, ABC import numpy as np from openpilot.sunnypilot.models.helpers import get_active_bundle -from openpilot.system.hardware import TICI -from openpilot.sunnypilot.models.runners.constants import NumpyDict, ShapeDict, CLMemDict, FrameDict, Model, SliceDict, SEND_RAW_PRED -from openpilot.system.hardware.hw import Paths +from openpilot.sunnypilot.models.runners.constants import NumpyDict, ShapeDict, Model, SliceDict, SEND_RAW_PRED +from openpilot.common.hardware.hw import Paths import pickle CUSTOM_MODEL_PATH = Paths.model_root() -# Set QCOM environment variable for TICI devices, potentially enabling hardware acceleration -USBGPU = "USBGPU" in os.environ -if USBGPU: - os.environ['AMD'] = '1' - os.environ['AMD_IFACE'] = 'USB' -elif TICI: - os.environ['QCOM'] = '1' -else: - os.environ['LLVM'] = '1' - os.environ['JIT'] = '2' # TODO: This may cause issues - - class ModelData: """ Stores metadata and configuration for a specific machine learning model. @@ -147,13 +133,11 @@ class ModelRunner(ModularRunner): raise ValueError("Model data is not available. Ensure the model is loaded correctly.") @abstractmethod - def prepare_inputs(self, imgs_cl: CLMemDict, numpy_inputs: NumpyDict, frames: FrameDict) -> dict: + def prepare_inputs(self, numpy_inputs: NumpyDict) -> dict: """ Abstract method to prepare inputs for model inference. - :param imgs_cl: Dictionary of OpenCL memory objects for image inputs. :param numpy_inputs: Dictionary of numpy arrays for non-image inputs. - :param frames: Dictionary of DrivingModelFrame objects for context. :return: Dictionary of prepared inputs ready for the model. """ raise NotImplementedError diff --git a/openpilot/sunnypilot/models/runners/tinygrad/model_types.py b/openpilot/sunnypilot/models/runners/tinygrad/model_types.py new file mode 100644 index 0000000000..295e75afb5 --- /dev/null +++ b/openpilot/sunnypilot/models/runners/tinygrad/model_types.py @@ -0,0 +1,91 @@ +import os +from abc import ABC + +import numpy as np +from openpilot.sunnypilot.modeld_v2.parse_model_outputs import Parser as CombinedParser +from openpilot.sunnypilot.modeld_v2.parse_model_outputs_split import Parser as SplitParser +from openpilot.sunnypilot.models.runners.constants import ModelType, NumpyDict +from openpilot.sunnypilot.models.runners.model_runner import ModularRunner +from openpilot.common.hardware.hw import Paths + + +SEND_RAW_PRED = os.getenv('SEND_RAW_PRED') +CUSTOM_MODEL_PATH = Paths.model_root() + + +class OffPolicyTinygrad(ModularRunner, ABC): + """ + A TinygradRunner specialized for off-policy models. + + Uses a SplitParser to handle outputs specific to the off-policy part of a split model setup. + """ + def __init__(self): + self._off_policy_parser = SplitParser() + self.parser_method_dict[ModelType.offPolicy] = self._parse_off_policy_outputs + + def _parse_off_policy_outputs(self, model_outputs: np.ndarray) -> NumpyDict: + """Parses off-policy model outputs using SplitParser.""" + result: NumpyDict = self._off_policy_parser.parse_policy_outputs(self._slice_outputs(model_outputs)) + return result + + +class OnPolicyTinygrad(ModularRunner, ABC): + """ + A TinygradRunner specialized for on-policy models. + + Uses a SplitParser to handle outputs specific to the on-policy part of a split model setup. + """ + def __init__(self): + self._on_policy_parser = SplitParser() + self.parser_method_dict[ModelType.onPolicy] = self._parse_on_policy_outputs + + def _parse_on_policy_outputs(self, model_outputs: np.ndarray) -> NumpyDict: + """Parses on-policy model outputs using SplitParser.""" + result: NumpyDict = self._on_policy_parser.parse_policy_outputs(self._slice_outputs(model_outputs)) + return result + + +class PolicyTinygrad(ModularRunner, ABC): + """ + A TinygradRunner specialized for policy-only models. + + Uses a SplitParser to handle outputs specific to the policy part of a split model setup. + """ + def __init__(self): + self._policy_parser = SplitParser() + self.parser_method_dict[ModelType.policy] = self._parse_policy_outputs + + def _parse_policy_outputs(self, model_outputs: np.ndarray) -> NumpyDict: + """Parses policy model outputs using SplitParser.""" + result: NumpyDict = self._policy_parser.parse_policy_outputs(self._slice_outputs(model_outputs)) + return result + +class VisionTinygrad(ModularRunner, ABC): + """ + A TinygradRunner specialized for vision-only models. + + Uses a SplitParser to handle outputs specific to the vision part of a split model setup. + """ + def __init__(self): + self._vision_parser = SplitParser() + self.parser_method_dict[ModelType.vision] = self._parse_vision_outputs + + def _parse_vision_outputs(self, model_outputs: np.ndarray) -> NumpyDict: + """Parses vision model outputs using SplitParser.""" + result: NumpyDict = self._vision_parser.parse_vision_outputs(self._slice_outputs(model_outputs)) + return result + +class SupercomboTinygrad(ModularRunner, ABC): + """ + A TinygradRunner specialized for vision-only models. + + Uses a SplitParser to handle outputs specific to the vision part of a split model setup. + """ + def __init__(self): + self._supercombo_parser = CombinedParser() + self.parser_method_dict[ModelType.supercombo] = self._parse_supercombo_outputs + + def _parse_supercombo_outputs(self, model_outputs: np.ndarray) -> NumpyDict: + """Parses vision model outputs using SplitParser.""" + result: NumpyDict = self._supercombo_parser.parse_outputs(self._slice_outputs(model_outputs)) + return result diff --git a/openpilot/sunnypilot/models/runners/tinygrad/tinygrad_runner.py b/openpilot/sunnypilot/models/runners/tinygrad/tinygrad_runner.py new file mode 100644 index 0000000000..4e17bd5ead --- /dev/null +++ b/openpilot/sunnypilot/models/runners/tinygrad/tinygrad_runner.py @@ -0,0 +1,179 @@ +import pickle + +import numpy as np +from openpilot.sunnypilot.models.runners.constants import NumpyDict, ModelType, ShapeDict, CUSTOM_MODEL_PATH, SliceDict +from openpilot.sunnypilot.models.runners.model_runner import ModelRunner +from openpilot.sunnypilot.models.runners.tinygrad.model_types import PolicyTinygrad, VisionTinygrad, SupercomboTinygrad, OffPolicyTinygrad, OnPolicyTinygrad +from openpilot.sunnypilot.models.split_model_constants import SplitModelConstants +from openpilot.sunnypilot.modeld_v2.constants import ModelConstants + +from tinygrad.tensor import Tensor + + +class TinygradRunner(ModelRunner, SupercomboTinygrad, PolicyTinygrad, VisionTinygrad, OffPolicyTinygrad, OnPolicyTinygrad): + """ + A ModelRunner implementation for executing Tinygrad models. + + Handles loading Tinygrad model artifacts (.pkl), preparing inputs as Tinygrad + Tensors (potentially using QCOM extensions on TICI), running inference, + and parsing the outputs. + + :param model_type: The type of model (e.g., supercombo) to load and run. + """ + def __init__(self, model_type: int = ModelType.supercombo): + ModelRunner.__init__(self) + SupercomboTinygrad.__init__(self) + PolicyTinygrad.__init__(self) + VisionTinygrad.__init__(self) + OffPolicyTinygrad.__init__(self) + OnPolicyTinygrad.__init__(self) + self._constants = ModelConstants + self._model_data = self.models.get(model_type) + if not self._model_data or not self._model_data.model: + raise ValueError(f"Model data for type {model_type} not available.") + + artifact_filename = self._model_data.model.artifact.fileName + assert artifact_filename.endswith('_tinygrad.pkl'), \ + f"Invalid model file {artifact_filename} for TinygradRunner" + + model_pkl_path = f"{CUSTOM_MODEL_PATH}/{artifact_filename}" + with open(model_pkl_path, "rb") as f: + try: + # Load the compiled Tinygrad model runner function + self.model_run = pickle.load(f) + except FileNotFoundError as e: + # Provide a helpful error message if the model was built for a different platform + assert "/dev/kgsl-3d0" not in str(e), "Model was built on C3 or C3X, but is being loaded on PC" + raise + + # Map input names to their required dtype and device from the loaded model + self.input_to_dtype = {} + self.input_to_device = {} + for idx, name in enumerate(self.model_run.captured.expected_names): + info = self.model_run.captured.expected_input_info[idx] + self.input_to_dtype[name] = info[2] # dtype + self.input_to_device[name] = info[3] # device + self._policy_cached = False + + @property + def vision_input_names(self) -> list[str]: + """Returns the list of vision input names from the input shapes.""" + return [name for name in self.input_shapes.keys() if 'img' in name] + + + def prepare_policy_inputs(self, numpy_inputs: NumpyDict): + if not self._policy_cached: + for key, value in numpy_inputs.items(): + self.inputs[key] = Tensor(value, device='NPY').realize() + self._policy_cached = True + + def prepare_inputs(self, numpy_inputs: NumpyDict) -> dict: + """Prepares all vision and policy inputs for the model.""" + self.prepare_policy_inputs(numpy_inputs) + for key in self.vision_input_names: + if key in self.inputs: + self.inputs[key] = self.inputs[key].cast(self.input_to_dtype[key]) + return self.inputs + + def _run_model(self) -> NumpyDict: + """Runs the Tinygrad model inference and parses the outputs.""" + outputs = self.model_run(**self.inputs).contiguous().realize().uop.base.buffer.numpy().flatten() + return self._parse_outputs(outputs) + + def _parse_outputs(self, model_outputs: np.ndarray) -> NumpyDict: + """Parses the raw model outputs using the standard Parser.""" + if self._model_data is None: + raise ValueError("Model data is not available. Ensure the model is loaded correctly.") + + result: NumpyDict = self.parser_method_dict[self._model_data.model.type.raw](model_outputs) + return result + + +class TinygradSplitRunner(ModelRunner): + """ + A ModelRunner that coordinates separate TinygradVisionRunner and TinygradPolicyRunner instances. + + Manages the execution of split vision and policy models, combining their inputs and outputs. + """ + def __init__(self): + super().__init__() + self.is_20hz_3d = True + self.vision_runner = TinygradRunner(ModelType.vision) + self.policy_runner = TinygradRunner(ModelType.policy) if self.models.get(ModelType.policy) else None + self.off_policy_runner = TinygradRunner(ModelType.offPolicy) if self.models.get(ModelType.offPolicy) else None + self.on_policy_runner = TinygradRunner(ModelType.onPolicy) if self.models.get(ModelType.onPolicy) else None + self._constants = SplitModelConstants + + def _run_model(self) -> NumpyDict: + """Runs both vision and policy models and merges their parsed outputs.""" + vision_output = self.vision_runner.run_model() + outputs = {**vision_output} + + if self.policy_runner: + policy_output = self.policy_runner.run_model() + outputs.update(policy_output) + + if self.off_policy_runner: + off_policy_output = self.off_policy_runner.run_model() + if self.on_policy_runner: + off_policy_output.pop('plan', None) + outputs.update(off_policy_output) + + if self.on_policy_runner: + on_policy_output = self.on_policy_runner.run_model() + outputs.update(on_policy_output) + + if 'planplus' in outputs and 'plan' in outputs: + outputs['plan'] = outputs['plan'] + outputs['planplus'] + + return outputs + + @property + def vision_input_names(self) -> list[str]: + """Returns the list of vision input names from the vision runner.""" + return list(self.vision_runner.vision_input_names) + + @property + def input_shapes(self) -> ShapeDict: + """Returns the combined input shapes from both vision and policy models.""" + shapes = {**self.vision_runner.input_shapes} + if self.policy_runner: + shapes.update(self.policy_runner.input_shapes) + if self.off_policy_runner: + shapes.update(self.off_policy_runner.input_shapes) + if self.on_policy_runner: + shapes.update(self.on_policy_runner.input_shapes) + return shapes + + @property + def output_slices(self) -> SliceDict: + """Returns the combined output slices from both vision and policy models.""" + slices = {**self.vision_runner.output_slices} + if self.policy_runner: + slices.update(self.policy_runner.output_slices) + if self.off_policy_runner: + slices.update(self.off_policy_runner.output_slices) + if self.on_policy_runner: + slices.update(self.on_policy_runner.output_slices) + return slices + + def prepare_inputs(self, numpy_inputs: NumpyDict) -> dict: + """Prepares inputs for both vision and policy models.""" + if self.policy_runner: + self.policy_runner.prepare_policy_inputs(numpy_inputs) + + for key in self.vision_input_names: + if key in self.inputs: + self.vision_runner.inputs[key] = self.inputs[key].cast(self.vision_runner.input_to_dtype[key]) + + inputs = {**self.vision_runner.inputs} + if self.policy_runner: + inputs.update(self.policy_runner.inputs) + + if self.off_policy_runner: + self.off_policy_runner.prepare_policy_inputs(numpy_inputs) + inputs.update(self.off_policy_runner.inputs) + if self.on_policy_runner: + self.on_policy_runner.prepare_policy_inputs(numpy_inputs) + inputs.update(self.on_policy_runner.inputs) + return inputs diff --git a/sunnypilot/models/split_model_constants.py b/openpilot/sunnypilot/models/split_model_constants.py similarity index 100% rename from sunnypilot/models/split_model_constants.py rename to openpilot/sunnypilot/models/split_model_constants.py diff --git a/sunnypilot/selfdrive/controls/__init__.py b/openpilot/sunnypilot/models/tests/__init__.py similarity index 100% rename from sunnypilot/selfdrive/controls/__init__.py rename to openpilot/sunnypilot/models/tests/__init__.py diff --git a/openpilot/sunnypilot/models/tests/model_hash b/openpilot/sunnypilot/models/tests/model_hash new file mode 100644 index 0000000000..13a16294ff --- /dev/null +++ b/openpilot/sunnypilot/models/tests/model_hash @@ -0,0 +1 @@ +49133798d9cd9cacf47085c7ef8122bfee88cd9c6192a8314c81bfb1b37f5809 \ No newline at end of file diff --git a/sunnypilot/models/tests/model_manager_audit.py b/openpilot/sunnypilot/models/tests/model_manager_audit.py similarity index 93% rename from sunnypilot/models/tests/model_manager_audit.py rename to openpilot/sunnypilot/models/tests/model_manager_audit.py index 4cd2b7d78e..2fc8bf5f21 100644 --- a/sunnypilot/models/tests/model_manager_audit.py +++ b/openpilot/sunnypilot/models/tests/model_manager_audit.py @@ -5,7 +5,7 @@ This file is part of sunnypilot and is licensed under the MIT License. See the LICENSE.md file in the root directory for more details. """ -from cereal import messaging, custom +from openpilot.cereal import messaging, custom if __name__ == "__main__": sm = messaging.SubMaster(["modelManagerSP"]) diff --git a/openpilot/sunnypilot/models/tests/test_default_model.py b/openpilot/sunnypilot/models/tests/test_default_model.py new file mode 100644 index 0000000000..ab51027442 --- /dev/null +++ b/openpilot/sunnypilot/models/tests/test_default_model.py @@ -0,0 +1,22 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" + +from openpilot.sunnypilot import get_file_hash +from openpilot.sunnypilot.models.default_model import MODEL_HASH_PATH, SUPERCOMBO_ONNX_PATH +import hashlib + + +class TestDefaultModel: + def test_compare_onnx_hashes(self): + supercombo_hash = get_file_hash(SUPERCOMBO_ONNX_PATH) + + combined_hash = hashlib.sha256(supercombo_hash.encode()).hexdigest() + + with open(MODEL_HASH_PATH) as f: + current_hash = f.read().strip() + + assert combined_hash == current_hash, "Run sunnypilot/models/default_model.py to update the default model name and hash" diff --git a/openpilot/sunnypilot/models/tests/test_tinygrad_ref.py b/openpilot/sunnypilot/models/tests/test_tinygrad_ref.py new file mode 100644 index 0000000000..3e60ab5308 --- /dev/null +++ b/openpilot/sunnypilot/models/tests/test_tinygrad_ref.py @@ -0,0 +1,23 @@ +import requests + +from openpilot.sunnypilot.models.tinygrad_ref import get_tinygrad_ref +from openpilot.sunnypilot.models.fetcher import ModelFetcher + + +def fetch_tinygrad_ref(): + response = requests.get(ModelFetcher.MODEL_URL, timeout=10) + response.raise_for_status() + json_data = response.json() + return json_data.get("tinygrad_ref") + + +def test_tinygrad_ref(): + current_ref = get_tinygrad_ref() + remote_ref = fetch_tinygrad_ref() + assert remote_ref == current_ref, ( + f"""tinygrad_repo ref does not match remote tinygrad_ref of current compiled driving models json. + Current: {current_ref} + Remote: {remote_ref} + Please run build-all workflow to update models.""" + ) + print("tinygrad_repo ref matches current compiled driving models json ref.") diff --git a/openpilot/sunnypilot/models/tinygrad_ref.py b/openpilot/sunnypilot/models/tinygrad_ref.py new file mode 100644 index 0000000000..4dd333e323 --- /dev/null +++ b/openpilot/sunnypilot/models/tinygrad_ref.py @@ -0,0 +1,36 @@ +import os + +from openpilot.common.basedir import BASEDIR + + +def get_tinygrad_ref(): + repo_path = os.path.join(BASEDIR, "tinygrad_repo") + git_path = os.path.join(repo_path, ".git") + try: + if os.path.isdir(git_path): + git_dir = git_path + else: + with open(git_path) as f: + line = f.read().strip() + git_dir = os.path.join(repo_path, line[8:]) + with open(os.path.join(git_dir, "HEAD")) as f: + ref = f.read().strip() + if ref.startswith("ref:"): + with open(os.path.join(git_dir, ref.split(" ", 1)[1])) as f: + return f.read().strip() + return ref + except Exception as e: + print(f"Error getting tinygrad_repo ref: {e}") + return None + + +def main(): + current_ref = get_tinygrad_ref() + if current_ref: + print(current_ref) + else: + print("") + + +if __name__ == "__main__": + main() diff --git a/openpilot/sunnypilot/navd/helpers.py b/openpilot/sunnypilot/navd/helpers.py new file mode 100644 index 0000000000..c57706d32a --- /dev/null +++ b/openpilot/sunnypilot/navd/helpers.py @@ -0,0 +1,189 @@ +from __future__ import annotations + +import json +import math +import numpy as np +from typing import Any, cast + +from openpilot.common.constants import CV +from openpilot.common.params import Params + +DIRECTIONS = ('left', 'right', 'straight') +MODIFIABLE_DIRECTIONS = ('left', 'right') + +EARTH_MEAN_RADIUS = 6371007.2 +SPEED_CONVERSIONS = { + 'km/h': CV.KPH_TO_MS, + 'mph': CV.MPH_TO_MS, +} + + +class Coordinate: + def __init__(self, latitude: float, longitude: float) -> None: + self.latitude = latitude + self.longitude = longitude + self.annotations: dict[str, float] = {} + + @classmethod + def from_mapbox_tuple(cls, t: tuple[float, float]) -> Coordinate: + return cls(t[1], t[0]) + + def as_dict(self) -> dict[str, float]: + return {'latitude': self.latitude, 'longitude': self.longitude} + + def __str__(self) -> str: + return f'Coordinate({self.latitude}, {self.longitude})' + + def __repr__(self) -> str: + return self.__str__() + + def __eq__(self, other) -> bool: + if not isinstance(other, Coordinate): + return False + return (self.latitude == other.latitude) and (self.longitude == other.longitude) + + def __sub__(self, other: Coordinate) -> Coordinate: + return Coordinate(self.latitude - other.latitude, self.longitude - other.longitude) + + def __add__(self, other: Coordinate) -> Coordinate: + return Coordinate(self.latitude + other.latitude, self.longitude + other.longitude) + + def __mul__(self, c: float) -> Coordinate: + return Coordinate(self.latitude * c, self.longitude * c) + + def dot(self, other: Coordinate) -> float: + return self.latitude * other.latitude + self.longitude * other.longitude + + def distance_to(self, other: Coordinate) -> float: + # Haversine formula + dlat = math.radians(other.latitude - self.latitude) + dlon = math.radians(other.longitude - self.longitude) + + haversine_dlat = math.sin(dlat / 2.0) + haversine_dlat *= haversine_dlat + haversine_dlon = math.sin(dlon / 2.0) + haversine_dlon *= haversine_dlon + + y = haversine_dlat \ + + math.cos(math.radians(self.latitude)) \ + * math.cos(math.radians(other.latitude)) \ + * haversine_dlon + x = 2 * math.asin(math.sqrt(y)) + return x * EARTH_MEAN_RADIUS + + +def minimum_distance(a: Coordinate, b: Coordinate, p: Coordinate): + if a.distance_to(b) < 0.01: + return a.distance_to(p) + + ap = p - a + ab = b - a + t = np.clip(ap.dot(ab) / ab.dot(ab), 0.0, 1.0) + projection = a + ab * t + return projection.distance_to(p) + + +def distance_along_geometry(geometry: list[Coordinate], pos: Coordinate) -> float: + if len(geometry) <= 2: + return geometry[0].distance_to(pos) + + # 1. Find segment that is closest to current position + # 2. Total distance is sum of distance to start of closest segment + # + all previous segments + total_distance = 0.0 + total_distance_closest = 0.0 + closest_distance = 1e9 + + for i in range(len(geometry) - 1): + d = minimum_distance(geometry[i], geometry[i + 1], pos) + + if d < closest_distance: + closest_distance = d + total_distance_closest = total_distance + geometry[i].distance_to(pos) + + total_distance += geometry[i].distance_to(geometry[i + 1]) + + return total_distance_closest + + +def coordinate_from_param(param: str, params: Params = None) -> Coordinate | None: + if params is None: + params = Params() + + json_str = params.get(param) + if json_str is None: + return None + + pos = json.loads(json_str) + if 'latitude' not in pos or 'longitude' not in pos: + return None + + return Coordinate(pos['latitude'], pos['longitude']) + + +def string_to_direction(direction: str) -> str: + for d in DIRECTIONS: + if d in direction: + if 'slight' in direction and d in MODIFIABLE_DIRECTIONS: + return 'slight' + d.capitalize() + return d + return 'none' + + +def maxspeed_to_ms(maxspeed: dict[str, str | float]) -> float: + unit = cast(str, maxspeed['unit']) + speed = cast(float, maxspeed['speed']) + return float(SPEED_CONVERSIONS[unit] * speed) + + +def field_valid(dat: dict, field: str) -> bool: + return field in dat and dat[field] is not None + + +def parse_banner_instructions(banners: Any, distance_to_maneuver: float = 0.0) -> dict[str, Any] | None: + if not len(banners): + return None + + instruction = {} + + # A segment can contain multiple banners, find one that we need to show now + current_banner = banners[0] + for banner in banners: + if distance_to_maneuver < banner['distanceAlongGeometry']: + current_banner = banner + + # Only show banner when close enough to maneuver + instruction['showFull'] = distance_to_maneuver < current_banner['distanceAlongGeometry'] + + # Primary + p = current_banner['primary'] + if field_valid(p, 'text'): + instruction['maneuverPrimaryText'] = p['text'] + if field_valid(p, 'type'): + instruction['maneuverType'] = p['type'] + if field_valid(p, 'modifier'): + instruction['maneuverModifier'] = p['modifier'] + + # Secondary + if field_valid(current_banner, 'secondary'): + instruction['maneuverSecondaryText'] = current_banner['secondary']['text'] + + # Lane lines + if field_valid(current_banner, 'sub'): + lanes = [] + for component in current_banner['sub']['components']: + if component['type'] != 'lane': + continue + + lane = { + 'active': component['active'], + 'directions': [string_to_direction(d) for d in component['directions']], + } + + if field_valid(component, 'active_direction'): + lane['activeDirection'] = string_to_direction(component['active_direction']) + + lanes.append(lane) + instruction['lanes'] = lanes + + return instruction diff --git a/openpilot/sunnypilot/neural_network_data b/openpilot/sunnypilot/neural_network_data new file mode 160000 index 0000000000..03cac2d30e --- /dev/null +++ b/openpilot/sunnypilot/neural_network_data @@ -0,0 +1 @@ +Subproject commit 03cac2d30e111e0689c0429cb8c1fe6cb5a905af diff --git a/sunnypilot/selfdrive/controls/lib/__init__.py b/openpilot/sunnypilot/selfdrive/__init__.py similarity index 100% rename from sunnypilot/selfdrive/controls/lib/__init__.py rename to openpilot/sunnypilot/selfdrive/__init__.py diff --git a/openpilot/sunnypilot/selfdrive/assets/icons/clock.png b/openpilot/sunnypilot/selfdrive/assets/icons/clock.png new file mode 100644 index 0000000000..e04d1db949 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/assets/icons/clock.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e095cfc4de71788bd4a99699a2e7ab4098cd426277d672b9e43981c5fab8b40f +size 16407 diff --git a/openpilot/sunnypilot/selfdrive/assets/icons/star-empty.png b/openpilot/sunnypilot/selfdrive/assets/icons/star-empty.png new file mode 100644 index 0000000000..bf60dec374 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/assets/icons/star-empty.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3731604f80e83a1fdb7c258baf6530b81190eeec82e6443172e84a35b7a74c02 +size 1088 diff --git a/openpilot/sunnypilot/selfdrive/assets/icons/star-filled.png b/openpilot/sunnypilot/selfdrive/assets/icons/star-filled.png new file mode 100644 index 0000000000..3667231bf0 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/assets/icons/star-filled.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0c2a513b7f2da004f145b7d689654cc65137f1b146d484fbce7ce727a297b62c +size 861 diff --git a/openpilot/sunnypilot/selfdrive/assets/icons_mici/always_offroad.png b/openpilot/sunnypilot/selfdrive/assets/icons_mici/always_offroad.png new file mode 100644 index 0000000000..56f35669c6 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/assets/icons_mici/always_offroad.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e459241d896824f5e8207d568847acab3dedd41caae7af59d4c17e043663b0c9 +size 4035 diff --git a/openpilot/sunnypilot/selfdrive/assets/icons_mici/disable_offroad.png b/openpilot/sunnypilot/selfdrive/assets/icons_mici/disable_offroad.png new file mode 100644 index 0000000000..146734aafa --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/assets/icons_mici/disable_offroad.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:27a0fca872d4586f578d246890b83674cdb7ecb03f58b2b0379b4b64a5816053 +size 3908 diff --git a/openpilot/sunnypilot/selfdrive/assets/images/green_light.png b/openpilot/sunnypilot/selfdrive/assets/images/green_light.png new file mode 100644 index 0000000000..2da2c13a82 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/assets/images/green_light.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3aa5ec9ac1daee6a549e62647d90bcaa66d2485f7df7f386ff902fcfb04c1716 +size 6583 diff --git a/openpilot/sunnypilot/selfdrive/assets/images/lead_depart.png b/openpilot/sunnypilot/selfdrive/assets/images/lead_depart.png new file mode 100644 index 0000000000..6030ee67cf --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/assets/images/lead_depart.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:087db35bd469e85aefe3b45636f11ab3e8b55ceb7bc94ea059cfd9a69c2f338f +size 8914 diff --git a/sunnypilot/selfdrive/assets/images/spinner_sunnypilot.png b/openpilot/sunnypilot/selfdrive/assets/images/spinner_sunnypilot.png similarity index 100% rename from sunnypilot/selfdrive/assets/images/spinner_sunnypilot.png rename to openpilot/sunnypilot/selfdrive/assets/images/spinner_sunnypilot.png diff --git a/openpilot/sunnypilot/selfdrive/assets/img_minus_arrow_down.png b/openpilot/sunnypilot/selfdrive/assets/img_minus_arrow_down.png new file mode 100644 index 0000000000..2dc99789a5 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/assets/img_minus_arrow_down.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ad42ecaeff96a0a6c1a6db67b01e3c0452566906dd3a7f0336a1010ae854d27b +size 60924 diff --git a/openpilot/sunnypilot/selfdrive/assets/img_plus_arrow_up.png b/openpilot/sunnypilot/selfdrive/assets/img_plus_arrow_up.png new file mode 100644 index 0000000000..4247827340 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/assets/img_plus_arrow_up.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1fdea39873f60a0c4b216b75792e826f3633091a72ea2abd05740bd6e4e72089 +size 63058 diff --git a/openpilot/sunnypilot/selfdrive/assets/logo.png b/openpilot/sunnypilot/selfdrive/assets/logo.png new file mode 100644 index 0000000000..690cf7fb70 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/assets/logo.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:66b3aefa108dd0c7f64205a11e424430c318e6fd06de31b5550d0b9d05616e6a +size 19035 diff --git a/openpilot/sunnypilot/selfdrive/assets/offroad/icon_display.png b/openpilot/sunnypilot/selfdrive/assets/offroad/icon_display.png new file mode 100644 index 0000000000..547977f522 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/assets/offroad/icon_display.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:614767308d435d165a9ab78e3eac22ee15697d94066df8200ef32afb33ef8d60 +size 5698 diff --git a/sunnypilot/selfdrive/assets/offroad/icon_exit_offroad.png b/openpilot/sunnypilot/selfdrive/assets/offroad/icon_exit_offroad.png similarity index 100% rename from sunnypilot/selfdrive/assets/offroad/icon_exit_offroad.png rename to openpilot/sunnypilot/selfdrive/assets/offroad/icon_exit_offroad.png diff --git a/openpilot/sunnypilot/selfdrive/assets/offroad/icon_firehose.png b/openpilot/sunnypilot/selfdrive/assets/offroad/icon_firehose.png new file mode 100644 index 0000000000..d579937f3f --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/assets/offroad/icon_firehose.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a258a022f0ab90368327d899ed4fb85b47dd0e35c93508e35851d9c3184528c0 +size 36382 diff --git a/sunnypilot/selfdrive/assets/offroad/icon_firehose.svg b/openpilot/sunnypilot/selfdrive/assets/offroad/icon_firehose.svg similarity index 100% rename from sunnypilot/selfdrive/assets/offroad/icon_firehose.svg rename to openpilot/sunnypilot/selfdrive/assets/offroad/icon_firehose.svg diff --git a/openpilot/sunnypilot/selfdrive/assets/offroad/icon_home.png b/openpilot/sunnypilot/selfdrive/assets/offroad/icon_home.png new file mode 100644 index 0000000000..1229af846d --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/assets/offroad/icon_home.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8623dbc5c7dd043a91d98777cb423cfd116014ed6390af6d7d00c1f8dea3c6e8 +size 1181 diff --git a/sunnypilot/selfdrive/assets/offroad/icon_home.svg b/openpilot/sunnypilot/selfdrive/assets/offroad/icon_home.svg similarity index 100% rename from sunnypilot/selfdrive/assets/offroad/icon_home.svg rename to openpilot/sunnypilot/selfdrive/assets/offroad/icon_home.svg diff --git a/sunnypilot/selfdrive/assets/offroad/icon_lateral.png b/openpilot/sunnypilot/selfdrive/assets/offroad/icon_lateral.png similarity index 100% rename from sunnypilot/selfdrive/assets/offroad/icon_lateral.png rename to openpilot/sunnypilot/selfdrive/assets/offroad/icon_lateral.png diff --git a/sunnypilot/selfdrive/assets/offroad/icon_map.png b/openpilot/sunnypilot/selfdrive/assets/offroad/icon_map.png similarity index 100% rename from sunnypilot/selfdrive/assets/offroad/icon_map.png rename to openpilot/sunnypilot/selfdrive/assets/offroad/icon_map.png diff --git a/sunnypilot/selfdrive/assets/offroad/icon_models.png b/openpilot/sunnypilot/selfdrive/assets/offroad/icon_models.png similarity index 100% rename from sunnypilot/selfdrive/assets/offroad/icon_models.png rename to openpilot/sunnypilot/selfdrive/assets/offroad/icon_models.png diff --git a/sunnypilot/selfdrive/assets/offroad/icon_software.png b/openpilot/sunnypilot/selfdrive/assets/offroad/icon_software.png similarity index 100% rename from sunnypilot/selfdrive/assets/offroad/icon_software.png rename to openpilot/sunnypilot/selfdrive/assets/offroad/icon_software.png diff --git a/sunnypilot/selfdrive/assets/offroad/icon_toggle.png b/openpilot/sunnypilot/selfdrive/assets/offroad/icon_toggle.png similarity index 100% rename from sunnypilot/selfdrive/assets/offroad/icon_toggle.png rename to openpilot/sunnypilot/selfdrive/assets/offroad/icon_toggle.png diff --git a/sunnypilot/selfdrive/assets/offroad/icon_trips.png b/openpilot/sunnypilot/selfdrive/assets/offroad/icon_trips.png similarity index 100% rename from sunnypilot/selfdrive/assets/offroad/icon_trips.png rename to openpilot/sunnypilot/selfdrive/assets/offroad/icon_trips.png diff --git a/sunnypilot/selfdrive/assets/offroad/icon_vehicle.png b/openpilot/sunnypilot/selfdrive/assets/offroad/icon_vehicle.png similarity index 100% rename from sunnypilot/selfdrive/assets/offroad/icon_vehicle.png rename to openpilot/sunnypilot/selfdrive/assets/offroad/icon_vehicle.png diff --git a/sunnypilot/selfdrive/assets/offroad/icon_visuals.png b/openpilot/sunnypilot/selfdrive/assets/offroad/icon_visuals.png similarity index 100% rename from sunnypilot/selfdrive/assets/offroad/icon_visuals.png rename to openpilot/sunnypilot/selfdrive/assets/offroad/icon_visuals.png diff --git a/sunnypilot/selfdrive/controls/lib/dec/__init__.py b/openpilot/sunnypilot/selfdrive/car/__init__.py similarity index 100% rename from sunnypilot/selfdrive/controls/lib/dec/__init__.py rename to openpilot/sunnypilot/selfdrive/car/__init__.py diff --git a/openpilot/sunnypilot/selfdrive/car/car_list.json b/openpilot/sunnypilot/selfdrive/car/car_list.json new file mode 120000 index 0000000000..9bef560d9c --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/car/car_list.json @@ -0,0 +1 @@ +../../../../opendbc_repo/opendbc/sunnypilot/car/car_list.json \ No newline at end of file diff --git a/openpilot/sunnypilot/selfdrive/car/car_specific.py b/openpilot/sunnypilot/selfdrive/car/car_specific.py new file mode 100644 index 0000000000..54fcd34976 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/car/car_specific.py @@ -0,0 +1,51 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" + +from openpilot.cereal import log, custom +from opendbc.car import structs + +from opendbc.car.chrysler.values import RAM_DT +from openpilot.selfdrive.selfdrived.events import Events +from openpilot.sunnypilot.selfdrive.selfdrived.events import EventsSP + +EventName = log.OnroadEvent.EventName +EventNameSP = custom.OnroadEventSP.EventName +GearShifter = structs.CarState.GearShifter + + +class CarSpecificEventsSP: + def __init__(self, CP: structs.CarParams, CP_SP: structs.CarParamsSP): + self.CP = CP + self.CP_SP = CP_SP + + self.low_speed_alert = False + + def update(self, CS: structs.CarState, events: Events): + events_sp = EventsSP() + + if self.CP.brand == 'chrysler': + if self.CP.carFingerprint in RAM_DT: + # remove belowSteerSpeed event from CarSpecificEvents as RAM_DT uses a different logic + if events.has(EventName.belowSteerSpeed): + events.remove(EventName.belowSteerSpeed) + + # TODO-SP: use if/elif to have the gear shifter condition takes precedence over the speed condition + # TODO-SP: add 1 m/s hysteresis + if CS.vEgo >= self.CP.minEnableSpeed: + self.low_speed_alert = False + if self.CP.minEnableSpeed >= 14.5 and CS.gearShifter != GearShifter.drive: + self.low_speed_alert = True + if self.low_speed_alert: + events.add(EventName.belowSteerSpeed) + + elif self.CP.brand == 'toyota': + if self.CP.openpilotLongitudinalControl: + if CS.cruiseState.standstill and not CS.brakePressed and self.CP_SP.enableGasInterceptor: + if events.has(EventName.resumeRequired): + events.remove(EventName.resumeRequired) + + return events_sp diff --git a/openpilot/sunnypilot/selfdrive/car/cruise_ext.py b/openpilot/sunnypilot/selfdrive/car/cruise_ext.py new file mode 100644 index 0000000000..61bec477f2 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/car/cruise_ext.py @@ -0,0 +1,139 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import numpy as np + +from openpilot.cereal import custom +from opendbc.car.structs import car +from opendbc.car import structs +from openpilot.common.constants import CV +from openpilot.common.params import Params +from openpilot.sunnypilot.selfdrive.car.intelligent_cruise_button_management.helpers import get_minimum_set_speed +from openpilot.sunnypilot.selfdrive.controls.lib.speed_limit.speed_limit_assist import ACTIVE_STATES as SLA_ACTIVE_STATES +from openpilot.sunnypilot.selfdrive.controls.lib.speed_limit.helpers import compare_cluster_target + +ButtonType = car.CarState.ButtonEvent.Type +SpeedLimitAssistState = custom.LongitudinalPlanSP.SpeedLimit.AssistState + +CRUISE_BUTTON_TIMER = {ButtonType.decelCruise: 0, ButtonType.accelCruise: 0, + ButtonType.setCruise: 0, ButtonType.resumeCruise: 0, + ButtonType.cancel: 0, ButtonType.mainCruise: 0} + +V_CRUISE_MIN = 8 +V_CRUISE_MAX = 145 +V_CRUISE_UNSET = 255 + + +def update_manual_button_timers(CS: car.CarState, button_timers: dict[car.CarState.ButtonEvent.Type, int]) -> None: + # increment timer for buttons still pressed + for k in button_timers: + if button_timers[k] > 0: + button_timers[k] += 1 + + for b in CS.buttonEvents: + if b.type.raw in button_timers: + # Start/end timer and store current state on change of button pressed + button_timers[b.type.raw] = 1 if b.pressed else 0 + + +class VCruiseHelperSP: + def __init__(self, CP: structs.CarParams, CP_SP: structs.CarParamsSP) -> None: + self.CP = CP + self.CP_SP = CP_SP + self.v_cruise_kph = V_CRUISE_UNSET + self.v_cruise_cluster_kph = V_CRUISE_UNSET + self.params = Params() + self.v_cruise_min = 0 + self.enabled_prev = False + + self.custom_acc_enabled = self.params.get_bool("CustomAccIncrementsEnabled") + self.short_increment = self.params.get("CustomAccShortPressIncrement", return_default=True) + self.long_increment = self.params.get("CustomAccLongPressIncrement", return_default=True) + + self.enable_button_timers = CRUISE_BUTTON_TIMER + + # Speed Limit Assist + self.sla_state = SpeedLimitAssistState.disabled + self.prev_sla_state = SpeedLimitAssistState.disabled + self.has_speed_limit = False + self.speed_limit_final_last = 0. + self.speed_limit_final_last_kph = 0. + self.prev_speed_limit_final_last_kph = 0. + self.req_plus = False + self.req_minus = False + + def read_custom_set_speed_params(self) -> None: + self.custom_acc_enabled = self.params.get_bool("CustomAccIncrementsEnabled") + self.short_increment = self.params.get("CustomAccShortPressIncrement", return_default=True) + self.long_increment = self.params.get("CustomAccLongPressIncrement", return_default=True) + + def update_v_cruise_delta(self, long_press: bool, v_cruise_delta: float) -> tuple[bool, float]: + if not self.custom_acc_enabled: + v_cruise_delta = v_cruise_delta * (5 if long_press else 1) + return long_press, v_cruise_delta + + # Apply user-specified multipliers to the base increment + short_increment = np.clip(self.short_increment, 1, 10) + long_increment = np.clip(self.long_increment, 1, 10) + + actual_increment = long_increment if long_press else short_increment + round_to_nearest = actual_increment in (5, 10) + v_cruise_delta = v_cruise_delta * actual_increment + + return round_to_nearest, v_cruise_delta + + def get_minimum_set_speed(self, is_metric: bool) -> None: + if self.CP_SP.pcmCruiseSpeed: + self.v_cruise_min = V_CRUISE_MIN + return + + self.v_cruise_min = get_minimum_set_speed(is_metric) + + def update_enabled_state(self, CS: car.CarState, enabled: bool) -> bool: + # special enabled state for non pcmCruiseSpeed, unchanged for non pcmCruise + if not self.CP_SP.pcmCruiseSpeed: + update_manual_button_timers(CS, self.enable_button_timers) + button_pressed = any(self.enable_button_timers[k] > 0 for k in self.enable_button_timers) + + if enabled and not self.enabled_prev: + self.enabled_prev = not button_pressed + enabled = False + elif not enabled: + self.enabled_prev = enabled + + return enabled and self.enabled_prev + + return enabled + + def update_speed_limit_assist(self, is_metric, LP_SP: custom.LongitudinalPlanSP) -> None: + resolver = LP_SP.speedLimit.resolver + self.has_speed_limit = resolver.speedLimitValid or resolver.speedLimitLastValid + self.speed_limit_final_last = LP_SP.speedLimit.resolver.speedLimitFinalLast + self.speed_limit_final_last_kph = self.speed_limit_final_last * CV.MS_TO_KPH + self.sla_state = LP_SP.speedLimit.assist.state + self.req_plus, self.req_minus = compare_cluster_target(self.v_cruise_cluster_kph * CV.KPH_TO_MS, + self.speed_limit_final_last, is_metric) + + @property + def update_speed_limit_final_last_changed(self) -> bool: + return self.has_speed_limit and bool(self.speed_limit_final_last_kph != self.prev_speed_limit_final_last_kph) + + def update_speed_limit_assist_pre_active_confirmed(self, button_type: car.CarState.ButtonEvent.Type) -> bool: + if self.sla_state == SpeedLimitAssistState.preActive or self.prev_sla_state == SpeedLimitAssistState.preActive: + if button_type == ButtonType.decelCruise and self.req_minus: + return True + if button_type == ButtonType.accelCruise and self.req_plus: + return True + + return False + + def update_speed_limit_assist_v_cruise_non_pcm(self) -> None: + if self.sla_state in SLA_ACTIVE_STATES and (self.prev_sla_state not in SLA_ACTIVE_STATES or + self.update_speed_limit_final_last_changed): + self.v_cruise_kph = np.clip(round(self.speed_limit_final_last_kph, 1), self.v_cruise_min, V_CRUISE_MAX) + + self.prev_sla_state = self.sla_state + self.prev_speed_limit_final_last_kph = self.speed_limit_final_last_kph diff --git a/sunnypilot/selfdrive/car/cruise_helpers.py b/openpilot/sunnypilot/selfdrive/car/cruise_helpers.py similarity index 92% rename from sunnypilot/selfdrive/car/cruise_helpers.py rename to openpilot/sunnypilot/selfdrive/car/cruise_helpers.py index 1c0026e12f..aa689ec904 100644 --- a/sunnypilot/selfdrive/car/cruise_helpers.py +++ b/openpilot/sunnypilot/selfdrive/car/cruise_helpers.py @@ -5,7 +5,8 @@ This file is part of sunnypilot and is licensed under the MIT License. See the LICENSE.md file in the root directory for more details. """ -from cereal import car, custom +from openpilot.cereal import custom +from opendbc.car.structs import car from opendbc.car import structs from openpilot.common.params import Params @@ -45,6 +46,6 @@ class CruiseHelper: def update_experimental_mode(self, events, experimental_mode) -> None: if self.button_frame_counts[ButtonType.gapAdjustCruise] >= DISTANCE_LONG_PRESS and not self.experimental_mode_switched: self._experimental_mode = not experimental_mode - self.params.put_bool_nonblocking("ExperimentalMode", self._experimental_mode) + self.params.put_bool("ExperimentalMode", self._experimental_mode) events.add(EventNameSP.experimentalModeSwitched) self.experimental_mode_switched = True diff --git a/sunnypilot/selfdrive/controls/lib/dec/tests/__init__.py b/openpilot/sunnypilot/selfdrive/car/intelligent_cruise_button_management/__init__.py similarity index 100% rename from sunnypilot/selfdrive/controls/lib/dec/tests/__init__.py rename to openpilot/sunnypilot/selfdrive/car/intelligent_cruise_button_management/__init__.py diff --git a/openpilot/sunnypilot/selfdrive/car/intelligent_cruise_button_management/controller.py b/openpilot/sunnypilot/selfdrive/car/intelligent_cruise_button_management/controller.py new file mode 100644 index 0000000000..ded2c0ab19 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/car/intelligent_cruise_button_management/controller.py @@ -0,0 +1,128 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from openpilot.cereal import custom +from opendbc.car.structs import car +from opendbc.car import structs, apply_hysteresis +from openpilot.common.constants import CV +from openpilot.common.realtime import DT_CTRL +from openpilot.sunnypilot.selfdrive.car.intelligent_cruise_button_management.helpers import get_minimum_set_speed +from openpilot.sunnypilot.selfdrive.car.cruise_ext import CRUISE_BUTTON_TIMER, update_manual_button_timers + +LongitudinalPlanSource = custom.LongitudinalPlanSP.LongitudinalPlanSource +State = custom.IntelligentCruiseButtonManagement.IntelligentCruiseButtonManagementState +SendButtonState = custom.IntelligentCruiseButtonManagement.SendButtonState + +ALLOWED_SPEED_THRESHOLD = 1.8 # m/s, ~4 MPH +HYST_GAP = 0.0 # currently disabled; TODO-SP: might need to be brand-specific +INACTIVE_TIMER = 0.4 + + +SEND_BUTTONS = { + State.increasing: SendButtonState.increase, + State.decreasing: SendButtonState.decrease, +} + + +class IntelligentCruiseButtonManagement: + def __init__(self, CP: structs.CarParams, CP_SP: structs.CarParamsSP): + self.CP = CP + self.CP_SP = CP_SP + + self.v_target = 0 + self.v_cruise_cluster = 0 + self.v_cruise_min = 0 + self.cruise_button = SendButtonState.none + self.state = State.inactive + self.pre_active_timer = 0 + + self.is_ready = False + self.is_ready_prev = False + self.v_target_ms_last = 0.0 + self.is_metric = False + + self.cruise_button_timers = CRUISE_BUTTON_TIMER + + @property + def v_cruise_equal(self) -> bool: + return self.v_target == self.v_cruise_cluster + + def update_calculations(self, CS: car.CarState, LP_SP: custom.LongitudinalPlanSP) -> None: + speed_conv = CV.MS_TO_KPH if self.is_metric else CV.MS_TO_MPH + ms_conv = CV.KPH_TO_MS if self.is_metric else CV.MPH_TO_MS + + self.v_target_ms_last = apply_hysteresis(LP_SP.vTarget, self.v_target_ms_last, HYST_GAP * ms_conv) + + self.v_target = round(self.v_target_ms_last * speed_conv) + self.v_cruise_min = get_minimum_set_speed(self.is_metric) + self.v_cruise_cluster = round(CS.cruiseState.speedCluster * speed_conv) + + def update_state_machine(self) -> custom.IntelligentCruiseButtonManagement.SendButtonState: + self.pre_active_timer = max(0, self.pre_active_timer - 1) + + # HOLDING, ACCELERATING, DECELERATING, PRE_ACTIVE + if self.state != State.inactive: + if not self.is_ready: + self.state = State.inactive + + else: + # PRE_ACTIVE + if self.state == State.preActive: + if self.pre_active_timer <= 0: + if self.v_cruise_equal: + self.state = State.holding + + elif self.v_target > self.v_cruise_cluster: + self.state = State.increasing + + elif self.v_target < self.v_cruise_cluster and self.v_cruise_cluster > self.v_cruise_min: + self.state = State.decreasing + + # HOLDING + elif self.state == State.holding: + if not self.v_cruise_equal: + self.state = State.preActive + + # ACCELERATING + elif self.state == State.increasing: + if self.v_target <= self.v_cruise_cluster: + self.state = State.holding + + # DECELERATING + elif self.state == State.decreasing: + if self.v_target >= self.v_cruise_cluster or self.v_cruise_cluster <= self.v_cruise_min: + self.state = State.holding + + # INACTIVE + elif self.state == State.inactive: + if self.is_ready and not self.is_ready_prev: + self.pre_active_timer = int(INACTIVE_TIMER / DT_CTRL) + self.state = State.preActive + + send_button = SEND_BUTTONS.get(self.state, SendButtonState.none) + + return send_button + + def update_readiness(self, CS: car.CarState, CC: car.CarControl) -> None: + update_manual_button_timers(CS, self.cruise_button_timers) + + ready = CC.enabled and not CC.cruiseControl.override and not CC.cruiseControl.cancel and not CC.cruiseControl.resume + button_pressed = any(self.cruise_button_timers[k] > 0 for k in self.cruise_button_timers) + + self.is_ready = ready and not button_pressed + + def run(self, CS: car.CarState, CC: car.CarControl, LP_SP: custom.LongitudinalPlanSP, is_metric: bool) -> None: + if self.CP_SP.pcmCruiseSpeed: + return + + self.is_metric = is_metric + + self.update_calculations(CS, LP_SP) + self.update_readiness(CS, CC) + + self.cruise_button = self.update_state_machine() + + self.is_ready_prev = self.is_ready diff --git a/openpilot/sunnypilot/selfdrive/car/intelligent_cruise_button_management/helpers.py b/openpilot/sunnypilot/selfdrive/car/intelligent_cruise_button_management/helpers.py new file mode 100644 index 0000000000..eb4bbdecb5 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/car/intelligent_cruise_button_management/helpers.py @@ -0,0 +1,8 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +def get_minimum_set_speed(is_metric: bool) -> int: + return 30 if is_metric else 20 diff --git a/openpilot/sunnypilot/selfdrive/car/interfaces.py b/openpilot/sunnypilot/selfdrive/car/interfaces.py new file mode 100644 index 0000000000..5be227c262 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/car/interfaces.py @@ -0,0 +1,134 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from typing import Any + +from opendbc.car import structs +from opendbc.car.interfaces import CarInterfaceBase +from openpilot.common.params import Params +from openpilot.common.swaglog import cloudlog +from openpilot.sunnypilot.selfdrive.controls.lib.nnlc.helpers import get_nn_model_path +from openpilot.sunnypilot.selfdrive.controls.lib.speed_limit.helpers import set_speed_limit_assist_availability + +import openpilot.system.sentry as sentry + +from openpilot.sunnypilot.sunnylink.statsd import STATSLOGSP + + +def log_fingerprint(CP: structs.CarParams) -> None: + if CP.carFingerprint == "MOCK": + sentry.capture_fingerprint_mock() + else: + sentry.capture_fingerprint(CP.carFingerprint, CP.brand) + + +def _enforce_torque_lateral_control(CP: structs.CarParams, params: Params = None, enabled: bool = False) -> bool: + if params is None: + params = Params() + + if CP.steerControlType != structs.CarParams.SteerControlType.angle: + enabled = params.get_bool("EnforceTorqueControl") + + return enabled + + +def _initialize_neural_network_lateral_control(CP: structs.CarParams, CP_SP: structs.CarParamsSP, + params: Params = None, enabled: bool = False) -> bool: + if params is None: + params = Params() + + nnlc_model_path, nnlc_model_name, exact_match = get_nn_model_path(CP) + + if nnlc_model_name == "MOCK": + cloudlog.error({"nnlc event": "car doesn't match any Neural Network model"}) + + if nnlc_model_name != "MOCK" and CP.steerControlType != structs.CarParams.SteerControlType.angle: + enabled = params.get_bool("NeuralNetworkLateralControl") + + CP_SP.neuralNetworkLateralControl.model.path = nnlc_model_path + CP_SP.neuralNetworkLateralControl.model.name = nnlc_model_name + CP_SP.neuralNetworkLateralControl.fuzzyFingerprint = not exact_match + + return enabled + + +def _initialize_intelligent_cruise_button_management(CP: structs.CarParams, CP_SP: structs.CarParamsSP, params: Params = None) -> None: + if params is None: + params = Params() + + icbm_enabled = params.get_bool("IntelligentCruiseButtonManagement") + if icbm_enabled and CP_SP.intelligentCruiseButtonManagementAvailable and not CP.openpilotLongitudinalControl: + CP_SP.pcmCruiseSpeed = False + + +def _initialize_torque_lateral_control(CI: CarInterfaceBase, CP: structs.CarParams, enforce_torque: bool, nnlc_enabled: bool) -> None: + if nnlc_enabled or enforce_torque: + CI.configure_torque_tune(CP.carFingerprint, CP.lateralTuning) + + +def _cleanup_unsupported_params(CP: structs.CarParams, CP_SP: structs.CarParamsSP, params: Params = None) -> None: + if params is None: + params = Params() + + if CP.steerControlType == structs.CarParams.SteerControlType.angle: + cloudlog.warning("SteerControlType is angle, cleaning up params") + params.remove("NeuralNetworkLateralControl") + params.remove("EnforceTorqueControl") + + if not CP_SP.intelligentCruiseButtonManagementAvailable or CP.openpilotLongitudinalControl: + cloudlog.warning("ICBM not available or openpilot Longitudinal Control enabled, cleaning up params") + params.remove("IntelligentCruiseButtonManagement") + + if not CP.openpilotLongitudinalControl and CP_SP.pcmCruiseSpeed: + cloudlog.warning("openpilot Longitudinal Control and ICBM not available, cleaning up params") + params.remove("DynamicExperimentalControl") + params.remove("CustomAccIncrementsEnabled") + params.remove("SmartCruiseControlVision") + params.remove("SmartCruiseControlMap") + + set_speed_limit_assist_availability(CP, CP_SP, params) + + +def setup_interfaces(CI: CarInterfaceBase, params: Params = None) -> None: + enforce_torque = _enforce_torque_lateral_control(CI.CP, params) + nnlc_enabled = _initialize_neural_network_lateral_control(CI.CP, CI.CP_SP, params) + _initialize_intelligent_cruise_button_management(CI.CP, CI.CP_SP, params) + _initialize_torque_lateral_control(CI, CI.CP, enforce_torque, nnlc_enabled) + _cleanup_unsupported_params(CI.CP, CI.CP_SP) + + try: + STATSLOGSP.raw('sunnypilot.car_params', CI.CP.to_dict()) + except RuntimeError: + pass # to_dict fails on macOS due to library issues. + # STATSLOGSP.raw('sunnypilot_params.car_params_sp', CP_SP.to_dict()) # https://github.com/sunnypilot/opendbc/pull/361 + + +def initialize_params(params) -> list[dict[str, Any]]: + keys: list = [] + + # hyundai + keys.extend([ + "HyundaiLongitudinalTuning", + ]) + + # subaru + keys.extend([ + "SubaruStopAndGo", + "SubaruStopAndGoManualParkingBrake", + ]) + + # tesla + keys.extend([ + "TeslaCoopSteering", + ]) + + # toyota + keys.extend([ + "ToyotaEnforceStockLongitudinal", + "ToyotaStopAndGoHack", + ]) + + return [{k: params.get(k, return_default=True)} for k in keys] diff --git a/openpilot/sunnypilot/selfdrive/car/sync_sunnylink_params.py b/openpilot/sunnypilot/selfdrive/car/sync_sunnylink_params.py new file mode 100755 index 0000000000..6c964710b0 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/car/sync_sunnylink_params.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import json +import os + +from openpilot.common.basedir import BASEDIR +from openpilot.common.params import Params +from openpilot.common.swaglog import cloudlog + +CAR_LIST_JSON_OUT = os.path.join(BASEDIR, "openpilot", "sunnypilot", "selfdrive", "car", "car_list.json") + + +def update_car_list_param(): + with open(CAR_LIST_JSON_OUT) as f: + current_car_list = json.load(f) + + params = Params() + if params.get("CarList") != current_car_list: + params.put("CarList", current_car_list, block=True) + cloudlog.warning("Updated CarList param with latest platform list") + else: + cloudlog.warning("CarList param is up to date, no need to update") + + +if __name__ == "__main__": + update_car_list_param() diff --git a/sunnypilot/selfdrive/controls/lib/nnlc/__init__.py b/openpilot/sunnypilot/selfdrive/car/tests/__init__.py similarity index 100% rename from sunnypilot/selfdrive/controls/lib/nnlc/__init__.py rename to openpilot/sunnypilot/selfdrive/car/tests/__init__.py diff --git a/sunnypilot/selfdrive/car/tests/test_cruise_mode.py b/openpilot/sunnypilot/selfdrive/car/tests/test_cruise_mode.py similarity index 96% rename from sunnypilot/selfdrive/car/tests/test_cruise_mode.py rename to openpilot/sunnypilot/selfdrive/car/tests/test_cruise_mode.py index 26338319f5..3f3701b3ae 100644 --- a/sunnypilot/selfdrive/car/tests/test_cruise_mode.py +++ b/openpilot/sunnypilot/selfdrive/car/tests/test_cruise_mode.py @@ -1,5 +1,5 @@ -from parameterized import parameterized_class -from cereal import car +from opendbc.car.structs import car +from openpilot.common.parameterized import parameterized_class from openpilot.selfdrive.selfdrived.events import Events from openpilot.sunnypilot.selfdrive.car.cruise_helpers import CruiseHelper, DISTANCE_LONG_PRESS diff --git a/sunnypilot/selfdrive/car/tests/test_custom_cruise.py b/openpilot/sunnypilot/selfdrive/car/tests/test_custom_cruise.py similarity index 89% rename from sunnypilot/selfdrive/car/tests/test_custom_cruise.py rename to openpilot/sunnypilot/selfdrive/car/tests/test_custom_cruise.py index 2f9d976847..ce5d7dc124 100644 --- a/sunnypilot/selfdrive/car/tests/test_custom_cruise.py +++ b/openpilot/sunnypilot/selfdrive/car/tests/test_custom_cruise.py @@ -1,8 +1,8 @@ import pytest -from parameterized import parameterized_class -from cereal import car -from openpilot.common.conversions import Conversions as CV +from opendbc.car.structs import car +from openpilot.common.constants import CV +from openpilot.common.parameterized import parameterized_class from openpilot.common.params import Params from openpilot.selfdrive.car.cruise import V_CRUISE_INITIAL from openpilot.selfdrive.car.tests.test_cruise_speed import TestVCruiseHelper @@ -11,7 +11,8 @@ ButtonEvent = car.CarState.ButtonEvent ButtonType = car.CarState.ButtonEvent.Type -@parameterized_class(('pcm_cruise',), [(False,)]) +# TODO: test pcmCruise and pcmCruiseSpeed +@parameterized_class(('pcm_cruise', 'pcm_cruise_speed'), [(False, True)]) class TestCustomAccIncrements(TestVCruiseHelper): def setup_method(self): TestVCruiseHelper.setup_method(self) @@ -20,9 +21,9 @@ class TestCustomAccIncrements(TestVCruiseHelper): def reset_custom_params(self) -> None: """Reset to default custom ACC parameters""" - self.params.put_bool("CustomAccIncrementsEnabled", False) - self.params.put("CustomAccShortPressIncrement", "1") - self.params.put("CustomAccLongPressIncrement", "5") + self.params.put_bool("CustomAccIncrementsEnabled", False, block=True) + self.params.put("CustomAccShortPressIncrement", 1, block=True) + self.params.put("CustomAccLongPressIncrement", 5, block=True) self.v_cruise_helper.read_custom_set_speed_params() def press_button_short(self, button_type: car.CarState.ButtonEvent.Type) -> None: @@ -50,9 +51,9 @@ class TestCustomAccIncrements(TestVCruiseHelper): def set_custom_increments(self, enabled: bool, short_inc: int, long_inc: int) -> None: """Set custom ACC increment parameters""" - self.params.put_bool("CustomAccIncrementsEnabled", enabled) - self.params.put("CustomAccShortPressIncrement", str(short_inc)) - self.params.put("CustomAccLongPressIncrement", str(long_inc)) + self.params.put_bool("CustomAccIncrementsEnabled", enabled, block=True) + self.params.put("CustomAccShortPressIncrement", short_inc, block=True) + self.params.put("CustomAccLongPressIncrement", long_inc, block=True) self.v_cruise_helper.read_custom_set_speed_params() def test_default_behavior_when_disabled(self): diff --git a/sunnypilot/selfdrive/controls/lib/nnlc/tests/__init__.py b/openpilot/sunnypilot/selfdrive/controls/__init__.py similarity index 100% rename from sunnypilot/selfdrive/controls/lib/nnlc/tests/__init__.py rename to openpilot/sunnypilot/selfdrive/controls/__init__.py diff --git a/openpilot/sunnypilot/selfdrive/controls/controlsd_ext.py b/openpilot/sunnypilot/selfdrive/controls/controlsd_ext.py new file mode 100644 index 0000000000..33cc9e3ad8 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/controls/controlsd_ext.py @@ -0,0 +1,119 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import time + +import openpilot.cereal.messaging as messaging +from openpilot.cereal import log, custom + +from opendbc.car import structs +from openpilot.common.params import Params +from openpilot.common.swaglog import cloudlog +from openpilot.sunnypilot import PARAMS_UPDATE_PERIOD +from openpilot.sunnypilot.livedelay.helpers import get_lat_delay +from openpilot.sunnypilot.modeld_v2.modeld_base import ModelStateBase +from openpilot.sunnypilot.selfdrive.controls.lib.blinker_pause_lateral import BlinkerPauseLateral +from openpilot.sunnypilot.selfdrive.controls.lib.latcontrol_torque_v0 import LatControlTorque as LatControlTorqueV0 + + +class ControlsExt(ModelStateBase): + def __init__(self, CP: structs.CarParams, params: Params): + ModelStateBase.__init__(self) + self.CP = CP + self.params = params + self._param_update_time: float = 0.0 + self.blinker_pause_lateral = BlinkerPauseLateral() + + cloudlog.info("controlsd_ext is waiting for CarParamsSP") + self.CP_SP = messaging.log_from_bytes(params.get("CarParamsSP", block=True), custom.CarParamsSP) + cloudlog.info("controlsd_ext got CarParamsSP") + + self.sm_services_ext = ['radarState', 'selfdriveStateSP'] + self.pm_services_ext = ['carControlSP'] + + def initialize_lateral_control(self, lac, CI, dt): + enforce_torque_control = self.params.get_bool("EnforceTorqueControl") + torque_versions = self.params.get("TorqueControlTune") + if not enforce_torque_control: + if self.CP.lateralTuning.which() == 'torque': + return LatControlTorqueV0(self.CP, self.CP_SP, CI, dt) # FIXME-SP: revert when upstream fixes tuning issues with v1 + return lac + + if torque_versions == 0.0: # v0 + return LatControlTorqueV0(self.CP, self.CP_SP, CI, dt) + else: + return lac + + def get_params_sp(self, sm: messaging.SubMaster) -> None: + if time.monotonic() - self._param_update_time > PARAMS_UPDATE_PERIOD: + self.blinker_pause_lateral.get_params() + + if self.CP.lateralTuning.which() == 'torque': + self.lat_delay = get_lat_delay(self.params, sm["liveDelay"].lateralDelay) + + self._param_update_time = time.monotonic() + + def get_lat_active(self, sm: messaging.SubMaster) -> bool: + if self.blinker_pause_lateral.update(sm['carState']): + return False + + ss_sp = sm['selfdriveStateSP'] + if ss_sp.mads.available: + return bool(ss_sp.mads.active) + + # MADS not available, use stock state to engage + return bool(sm['selfdriveState'].active) + + @staticmethod + def get_lead_data(_lead, src: log.RadarState.LeadData) -> None: + _lead.dRel = src.dRel + _lead.yRel = src.yRel + _lead.vRel = src.vRel + _lead.aRel = src.deprecated.aRel + _lead.vLead = src.vLead + _lead.dPath = src.deprecated.dPath + _lead.vLat = src.deprecated.vLat + _lead.vLeadK = src.vLeadK + _lead.aLeadK = src.aLeadK + _lead.fcw = src.deprecated.fcw + _lead.status = src.present + _lead.aLeadTau = src.aLeadTau + _lead.modelProb = src.modelProb + _lead.radar = src.radar + _lead.radarTrackId = src.radarTrackId + + def state_control_ext(self, sm: messaging.SubMaster) -> custom.CarControlSP: + CC_SP = custom.CarControlSP.new_message() + + self.get_lead_data(CC_SP.leadOne, sm['radarState'].leadOne) + self.get_lead_data(CC_SP.leadTwo, sm['radarState'].leadTwo) + + # MADS state + mads_src = sm['selfdriveStateSP'].mads + CC_SP.mads.state = mads_src.state + CC_SP.mads.enabled = mads_src.enabled + CC_SP.mads.active = mads_src.active + CC_SP.mads.available = mads_src.available + + # ICBM state + icbm_src = sm['selfdriveStateSP'].intelligentCruiseButtonManagement + CC_SP.intelligentCruiseButtonManagement.state = icbm_src.state + CC_SP.intelligentCruiseButtonManagement.sendButton = icbm_src.sendButton + CC_SP.intelligentCruiseButtonManagement.vTarget = icbm_src.vTarget + + return CC_SP + + @staticmethod + def publish_ext(CC_SP: custom.CarControlSP, sm: messaging.SubMaster, pm: messaging.PubMaster) -> None: + cc_sp_send = messaging.new_message('carControlSP') + cc_sp_send.valid = sm['carState'].canValid + cc_sp_send.carControlSP = CC_SP + + pm.send('carControlSP', cc_sp_send) + + def run_ext(self, sm: messaging.SubMaster, pm: messaging.PubMaster) -> None: + CC_SP = self.state_control_ext(sm) + self.publish_ext(CC_SP, sm, pm) diff --git a/sunnypilot/selfdrive/selfdrived/__init__.py b/openpilot/sunnypilot/selfdrive/controls/lib/__init__.py similarity index 100% rename from sunnypilot/selfdrive/selfdrived/__init__.py rename to openpilot/sunnypilot/selfdrive/controls/lib/__init__.py diff --git a/sunnypilot/selfdrive/controls/lib/auto_lane_change.py b/openpilot/sunnypilot/selfdrive/controls/lib/auto_lane_change.py similarity index 92% rename from sunnypilot/selfdrive/controls/lib/auto_lane_change.py rename to openpilot/sunnypilot/selfdrive/controls/lib/auto_lane_change.py index 29056d5ac5..39909ac7b1 100644 --- a/sunnypilot/selfdrive/controls/lib/auto_lane_change.py +++ b/openpilot/sunnypilot/selfdrive/controls/lib/auto_lane_change.py @@ -4,7 +4,7 @@ Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. This file is part of sunnypilot and is licensed under the MIT License. See the LICENSE.md file in the root directory for more details. """ -from cereal import log +from openpilot.cereal import log from openpilot.common.params import Params from openpilot.common.realtime import DT_MDL @@ -42,7 +42,7 @@ class AutoLaneChangeController: self.param_read_counter = 0 self.lane_change_delay = 0.0 - self.lane_change_set_timer = AutoLaneChangeMode.NUDGE + self.lane_change_set_timer = self.params.get("AutoLaneChangeTimer", return_default=True) self.lane_change_bsm_delay = False self.prev_brake_pressed = False @@ -61,10 +61,7 @@ class AutoLaneChangeController: def read_params(self) -> None: self.lane_change_bsm_delay = self.params.get_bool("AutoLaneChangeBsmDelay") - try: - self.lane_change_set_timer = int(self.params.get("AutoLaneChangeTimer", encoding="utf8")) - except (ValueError, TypeError): - self.lane_change_set_timer = AutoLaneChangeMode.NUDGE + self.lane_change_set_timer = self.params.get("AutoLaneChangeTimer", return_default=True) def update_params(self) -> None: if self.param_read_counter % 50 == 0: diff --git a/openpilot/sunnypilot/selfdrive/controls/lib/blinker_pause_lateral.py b/openpilot/sunnypilot/selfdrive/controls/lib/blinker_pause_lateral.py new file mode 100644 index 0000000000..e9a6be595e --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/controls/lib/blinker_pause_lateral.py @@ -0,0 +1,44 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from opendbc.car.structs import car + +from openpilot.common.constants import CV +from openpilot.common.params import Params + + +class BlinkerPauseLateral: + def __init__(self): + self.params = Params() + + self.enabled = self.params.get_bool("BlinkerPauseLateralControl") + self.is_metric = self.params.get_bool("IsMetric") + self.min_speed = 0 + self.reengage_delay = 0 + self.blinker_off_timer = 0.0 + + def get_params(self) -> None: + self.enabled = self.params.get_bool("BlinkerPauseLateralControl") + self.is_metric = self.params.get_bool("IsMetric") + self.min_speed = self.params.get("BlinkerMinLateralControlSpeed", return_default=True) + self.reengage_delay = self.params.get("BlinkerLateralReengageDelay", return_default=True) + + def update(self, CS: car.CarState, DT_CTRL: float = 0.01) -> bool: + if not self.enabled: + return False + + one_blinker = CS.leftBlinker != CS.rightBlinker + speed_factor = CV.KPH_TO_MS if self.is_metric else CV.MPH_TO_MS + min_speed_ms = self.min_speed * speed_factor + + below_speed = CS.vEgo < min_speed_ms + + if one_blinker and below_speed: + self.blinker_off_timer = self.reengage_delay + elif self.blinker_off_timer > 0: + self.blinker_off_timer -= DT_CTRL + + return bool((one_blinker and below_speed) or self.blinker_off_timer > 0) diff --git a/sunnypilot/sunnylink/__init__.py b/openpilot/sunnypilot/selfdrive/controls/lib/dec/__init__.py similarity index 100% rename from sunnypilot/sunnylink/__init__.py rename to openpilot/sunnypilot/selfdrive/controls/lib/dec/__init__.py diff --git a/openpilot/sunnypilot/selfdrive/controls/lib/dec/constants.py b/openpilot/sunnypilot/selfdrive/controls/lib/dec/constants.py new file mode 100644 index 0000000000..4586afbc9f --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/controls/lib/dec/constants.py @@ -0,0 +1,17 @@ +class WMACConstants: + # Lead detection parameters + LEAD_WINDOW_SIZE = 6 # Stable detection window + LEAD_PROB = 0.45 # Balanced threshold for lead detection + + # Slow down detection parameters + SLOW_DOWN_WINDOW_SIZE = 5 # Responsive but stable + SLOW_DOWN_PROB = 0.3 # Balanced threshold for slow down scenarios + + # Optimized slow down distance curve - smooth and progressive + SLOW_DOWN_BP = [0., 10., 20., 30., 40., 50., 55., 60.] + SLOW_DOWN_DIST = [32., 46., 64., 86., 108., 130., 145., 165.] + + # Slowness detection parameters + SLOWNESS_WINDOW_SIZE = 10 # Stable slowness detection + SLOWNESS_PROB = 0.55 # Clear threshold for slowness + SLOWNESS_CRUISE_OFFSET = 1.025 # Conservative cruise speed offset diff --git a/openpilot/sunnypilot/selfdrive/controls/lib/dec/dec.py b/openpilot/sunnypilot/selfdrive/controls/lib/dec/dec.py new file mode 100644 index 0000000000..1ba5ab0618 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/controls/lib/dec/dec.py @@ -0,0 +1,388 @@ +""" +Copyright (c) 2021-, rav4kumar, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +# Version = 2025-6-30 + +from openpilot.cereal import messaging +from opendbc.car import structs +from numpy import interp +from openpilot.common.params import Params +from openpilot.common.realtime import DT_MDL +from openpilot.sunnypilot.selfdrive.controls.lib.dec.constants import WMACConstants +from typing import Literal + +# d-e2e, from modeldata.h +TRAJECTORY_SIZE = 33 +SET_MODE_TIMEOUT = 15 + +# Define the valid mode types +ModeType = Literal['acc', 'blended'] + + +class SmoothKalmanFilter: + """Enhanced Kalman filter with smoothing for stable decision making.""" + + def __init__(self, initial_value=0, measurement_noise=0.1, process_noise=0.01, + alpha=1.0, smoothing_factor=0.85): + self.x = initial_value + self.P = 1.0 + self.R = measurement_noise + self.Q = process_noise + self.alpha = alpha + self.smoothing_factor = smoothing_factor + self.initialized = False + self.history = [] + self.max_history = 10 + self.confidence = 0.0 + + def add_data(self, measurement): + if len(self.history) >= self.max_history: + self.history.pop(0) + self.history.append(measurement) + + if not self.initialized: + self.x = measurement + self.initialized = True + self.confidence = 0.1 + return + + self.P = self.alpha * self.P + self.Q + + K = self.P / (self.P + self.R) + effective_K = K * (1.0 - self.smoothing_factor) + self.smoothing_factor * 0.1 + + innovation = measurement - self.x + self.x = self.x + effective_K * innovation + self.P = (1 - effective_K) * self.P + + if abs(innovation) < 0.1: + self.confidence = min(1.0, self.confidence + 0.05) + else: + self.confidence = max(0.1, self.confidence - 0.02) + + def get_value(self): + return self.x if self.initialized else None + + def get_confidence(self): + return self.confidence + + def reset_data(self): + self.initialized = False + self.history = [] + self.confidence = 0.0 + + +class ModeTransitionManager: + """Manages smooth transitions between driving modes with hysteresis.""" + + def __init__(self): + self.current_mode: ModeType = 'acc' + self.mode_confidence = {'acc': 1.0, 'blended': 0.0} + self.transition_timeout = 0 + self.min_mode_duration = 10 + self.mode_duration = 0 + self.emergency_override = False + + def request_mode(self, mode: ModeType, confidence: float = 1.0, emergency: bool = False): + # Emergency override for critical situations (stops, collisions) + if emergency: + self.emergency_override = True + self.current_mode = mode + self.transition_timeout = SET_MODE_TIMEOUT + self.mode_duration = 0 + return + + self.mode_confidence[mode] = min(1.0, self.mode_confidence[mode] + 0.1 * confidence) + for m in self.mode_confidence: + if m != mode: + self.mode_confidence[m] = max(0.0, self.mode_confidence[m] - 0.05) + + # Require minimum duration in current mode (unless emergency) + if self.mode_duration < self.min_mode_duration and not self.emergency_override: + return + + # Hysteresis: higher threshold for mode changes + confidence_threshold = 0.6 if mode != self.current_mode else 0.3 # Lower threshold for faster response + + if self.mode_confidence[mode] > confidence_threshold: + if mode != self.current_mode and self.transition_timeout == 0: + self.transition_timeout = SET_MODE_TIMEOUT + self.current_mode = mode + self.mode_duration = 0 + + def update(self): + if self.transition_timeout > 0: + self.transition_timeout -= 1 + self.mode_duration += 1 + + # Reset emergency override after some time + if self.emergency_override and self.mode_duration > 20: + self.emergency_override = False + + # Gradual confidence decay + for mode in self.mode_confidence: + self.mode_confidence[mode] *= 0.98 + + def get_mode(self) -> ModeType: + return self.current_mode + + +class DynamicExperimentalController: + def __init__(self, CP: structs.CarParams, mpc, params=None): + self._CP = CP + self._mpc = mpc + self._params = params or Params() + self._enabled: bool = self._params.get_bool("DynamicExperimentalControl") + self._active: bool = False + self._frame: int = 0 + self._urgency = 0.0 + + self._mode_manager = ModeTransitionManager() + + # Smooth filters for stable decision making with faster response for critical scenarios + self._lead_filter = SmoothKalmanFilter( + measurement_noise=0.15, + process_noise=0.05, + alpha=1.02, + smoothing_factor=0.8 + ) + + self._slow_down_filter = SmoothKalmanFilter( + measurement_noise=0.1, + process_noise=0.1, + alpha=1.05, + smoothing_factor=0.7 + ) + + self._slowness_filter = SmoothKalmanFilter( + measurement_noise=0.1, + process_noise=0.06, + alpha=1.015, + smoothing_factor=0.92 + ) + + self._mpc_fcw_filter = SmoothKalmanFilter( + measurement_noise=0.2, + process_noise=0.1, + alpha=1.1, + smoothing_factor=0.5 + ) + self._has_lead_filtered = False + self._has_slow_down = False + self._has_slowness = False + self._has_mpc_fcw = False + self._v_ego_kph = 0.0 + self._v_cruise_kph = 0.0 + self._has_standstill = False + self._mpc_fcw_crash_cnt = 0 + self._standstill_count = 0 + # debug + self._endpoint_x = float('inf') + self._expected_distance = 0.0 + self._trajectory_valid = False + + def _read_params(self) -> None: + if self._frame % int(1. / DT_MDL) == 0: + self._enabled = self._params.get_bool("DynamicExperimentalControl") + + def mode(self) -> str: + return self._mode_manager.get_mode() + + def enabled(self) -> bool: + return self._enabled + + def active(self) -> bool: + return self._active + + def set_mpc_fcw_crash_cnt(self) -> None: + """Set MPC FCW crash count""" + self._mpc_fcw_crash_cnt = self._mpc.crash_cnt + + def _update_calculations(self, sm: messaging.SubMaster) -> None: + car_state = sm['carState'] + lead_one = sm['radarState'].leadOne + md = sm['modelV2'] + + self._v_ego_kph = car_state.vEgo * 3.6 + self._v_cruise_kph = car_state.vCruise + self._has_standstill = car_state.standstill + + # standstill detection + if self._has_standstill: + self._standstill_count = min(20, self._standstill_count + 1) + else: + self._standstill_count = max(0, self._standstill_count - 1) + + # Lead detection + self._lead_filter.add_data(float(lead_one.present)) + lead_value = self._lead_filter.get_value() or 0.0 + self._has_lead_filtered = lead_value > WMACConstants.LEAD_PROB + + # MPC FCW detection + fcw_filtered_value = self._mpc_fcw_filter.get_value() or 0.0 + self._mpc_fcw_filter.add_data(float(self._mpc_fcw_crash_cnt > 0)) + self._has_mpc_fcw = fcw_filtered_value > 0.5 + + # Slow down detection + self._calculate_slow_down(md) + + # Slowness detection + if not (self._standstill_count > 5) and not self._has_slow_down: + current_slowness = float(self._v_ego_kph <= (self._v_cruise_kph * WMACConstants.SLOWNESS_CRUISE_OFFSET)) + self._slowness_filter.add_data(current_slowness) + slowness_value = self._slowness_filter.get_value() or 0.0 + + # Hysteresis for slowness + threshold = WMACConstants.SLOWNESS_PROB * (0.8 if self._has_slowness else 1.1) + self._has_slowness = slowness_value > threshold + + def _calculate_slow_down(self, md): + """Calculate urgency based on trajectory endpoint vs expected distance.""" + + # Reset to safe defaults + urgency = 0.0 + self._endpoint_x = float('inf') + self._trajectory_valid = False + + #Require exact trajectory size + position_valid = len(md.position.x) == TRAJECTORY_SIZE + orientation_valid = len(md.orientation.x) == TRAJECTORY_SIZE + + if not (position_valid and orientation_valid): + # Invalid trajectory - this itself might indicate a stop scenario + # Apply moderate urgency for incomplete trajectories at speed + if self._v_ego_kph > 20.0: + urgency = 0.3 + + self._slow_down_filter.add_data(urgency) + urgency_filtered = self._slow_down_filter.get_value() or 0.0 + self._has_slow_down = urgency_filtered > WMACConstants.SLOW_DOWN_PROB + self._urgency = urgency_filtered + return + + # We have a valid full trajectory + self._trajectory_valid = True + + # Use the exact endpoint (33rd point, index 32) + endpoint_x = md.position.x[TRAJECTORY_SIZE - 1] + self._endpoint_x = endpoint_x + + # Get expected distance based on current speed using tuned constants + expected_distance = interp(self._v_ego_kph, + WMACConstants.SLOW_DOWN_BP, + WMACConstants.SLOW_DOWN_DIST) + self._expected_distance = expected_distance + + # Calculate urgency based on trajectory shortage + if endpoint_x < expected_distance: + shortage = expected_distance - endpoint_x + shortage_ratio = shortage / expected_distance + + # Base urgency on shortage ratio + urgency = min(1.0, shortage_ratio * 2.0) + + # Increase urgency for very short trajectories (imminent stops) + critical_distance = expected_distance * 0.3 + if endpoint_x < critical_distance: + urgency = min(1.0, urgency * 2.0) + + # Speed-based urgency adjustment + if self._v_ego_kph > 25.0: + speed_factor = 1.0 + (self._v_ego_kph - 25.0) / 80.0 + urgency = min(1.0, urgency * speed_factor) + + # Apply filtering but with less smoothing for stops + self._slow_down_filter.add_data(urgency) + urgency_filtered = self._slow_down_filter.get_value() or 0.0 + + # Update state with lower threshold for better stop detection + self._has_slow_down = urgency_filtered > (WMACConstants.SLOW_DOWN_PROB * 0.8) + self._urgency = urgency_filtered + + def _radarless_mode(self) -> None: + """Radarless mode decision logic with emergency handling.""" + + # EMERGENCY: MPC FCW - immediate blended mode + if self._has_mpc_fcw: + self._mode_manager.request_mode('blended', confidence=1.0, emergency=True) + return + + # Standstill: use blended + if self._standstill_count > 3: + self._mode_manager.request_mode('blended', confidence=0.9) + return + + # Slow down scenarios: emergency for high urgency, normal for lower urgency + if self._has_slow_down: + if self._urgency > 0.7: + # Emergency: immediate blended mode for high urgency stops + self._mode_manager.request_mode('blended', confidence=1.0, emergency=True) + else: + # Normal: blended with urgency-based confidence + confidence = min(1.0, self._urgency * 1.5) + self._mode_manager.request_mode('blended', confidence=confidence) + return + + # Driving slow: use ACC (but not if actively slowing down) + if self._has_slowness and not self._has_slow_down: + self._mode_manager.request_mode('acc', confidence=0.8) + return + + # Default: ACC + self._mode_manager.request_mode('acc', confidence=0.7) + + def _radar_mode(self) -> None: + """Radar mode with emergency handling.""" + + # EMERGENCY: MPC FCW - immediate blended mode + if self._has_mpc_fcw: + self._mode_manager.request_mode('blended', confidence=1.0, emergency=True) + return + + # If lead detected and not in standstill: always use ACC + if self._has_lead_filtered and not (self._standstill_count > 3): + self._mode_manager.request_mode('acc', confidence=1.0) + return + + # Slow down scenarios: emergency for high urgency, normal for lower urgency + if self._has_slow_down: + if self._urgency > 0.7: + # Emergency: immediate blended mode for high urgency stops + self._mode_manager.request_mode('blended', confidence=1.0, emergency=True) + else: + # Normal: blended with urgency-based confidence + confidence = min(1.0, self._urgency * 1.3) + self._mode_manager.request_mode('blended', confidence=confidence) + return + + # Standstill: use blended + if self._standstill_count > 3: + self._mode_manager.request_mode('blended', confidence=0.9) + return + + # Driving slow: use ACC (but not if actively slowing down) + if self._has_slowness and not self._has_slow_down: + self._mode_manager.request_mode('acc', confidence=0.8) + return + + # Default: ACC + self._mode_manager.request_mode('acc', confidence=0.7) + + def update(self, sm: messaging.SubMaster) -> None: + self._read_params() + + self.set_mpc_fcw_crash_cnt() + + self._update_calculations(sm) + + if self._CP.radarUnavailable: + self._radarless_mode() + else: + self._radar_mode() + + self._mode_manager.update() + self._active = sm['selfdriveState'].experimentalMode and self._enabled + self._frame += 1 diff --git a/sunnypilot/sunnylink/athena/__init__.py b/openpilot/sunnypilot/selfdrive/controls/lib/dec/tests/__init__.py similarity index 100% rename from sunnypilot/sunnylink/athena/__init__.py rename to openpilot/sunnypilot/selfdrive/controls/lib/dec/tests/__init__.py diff --git a/openpilot/sunnypilot/selfdrive/controls/lib/dec/tests/pytest_dynamic_controller.py b/openpilot/sunnypilot/selfdrive/controls/lib/dec/tests/pytest_dynamic_controller.py new file mode 100644 index 0000000000..407ed0af3a --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/controls/lib/dec/tests/pytest_dynamic_controller.py @@ -0,0 +1,94 @@ +import pytest + +from openpilot.sunnypilot.selfdrive.controls.lib.dec.dec import DynamicExperimentalController + +class MockLeadOne: + def __init__(self, status=0.0): + self.status = status + +class MockRadarState: + def __init__(self, status=0.0): + self.leadOne = MockLeadOne(status=status) + +class MockCarState: + def __init__(self, vEgo=0.0, vCruise=0.0, standstill=False): + self.vEgo = vEgo + self.vCruise = vCruise + self.standstill = standstill + +class MockModelData: + def __init__(self, valid=True): + size = 33 if valid else 10 # incomplete if invalid + self.position = type("Pos", (), {"x": [0.0] * size})() + self.orientation = type("Ori", (), {"x": [0.0] * size})() + +class MockSelfDriveState: + def __init__(self, experimentalMode=False): + self.experimentalMode = experimentalMode + +class MockParams: + def get_bool(self, name): + return True + +@pytest.fixture +def default_sm(): + sm = { + 'carState': MockCarState(vEgo=10.0, vCruise=20.0), + 'radarState': MockRadarState(status=1.0), + 'modelV2': MockModelData(valid=True), + 'selfdriveState': MockSelfDriveState(experimentalMode=True), + } + return sm + +@pytest.fixture +def mock_cp(): + class CP: + radarUnavailable = False + return CP() + +@pytest.fixture +def mock_mpc(): + class MPC: + crash_cnt = 0 + return MPC() + +# Fake Kalman Filter that always returns a given value +class FakeKalman: + def __init__(self, value=1.0): + self.value = value + def add_data(self, v): pass + def get_value(self): return self.value + def get_confidence(self): return 1.0 + def reset_data(self): pass + +def test_initial_mode_is_acc(mock_cp, mock_mpc): + controller = DynamicExperimentalController(mock_cp, mock_mpc, params=MockParams()) + assert controller.mode() == "acc" + +def test_standstill_triggers_blended(mock_cp, mock_mpc, default_sm): + controller = DynamicExperimentalController(mock_cp, mock_mpc, params=MockParams()) + default_sm['carState'].standstill = True + for _ in range(10): + controller.update(default_sm) + assert controller.mode() == "blended" + +def test_emergency_blended_on_fcw(mock_cp, mock_mpc, default_sm): + controller = DynamicExperimentalController(mock_cp, mock_mpc, params=MockParams()) + mock_mpc.crash_cnt = 1 # simulate FCW + for _ in range(2): + controller.update(default_sm) + assert controller.mode() == "blended" + +def test_radarless_slowdown_triggers_blended(mock_cp, mock_mpc, default_sm): + mock_cp.radarUnavailable = True + controller = DynamicExperimentalController(mock_cp, mock_mpc, params=MockParams()) + + # Force conditions to simulate slowdown + controller._slow_down_filter = FakeKalman(value=1.0) # ty: ignore[invalid-assignment] + controller._v_ego_kph = 35.0 + default_sm['modelV2'] = MockModelData(valid=False) # Incomplete trajectory + + for _ in range(3): + controller.update(default_sm) + + assert controller.mode() == "blended" diff --git a/openpilot/sunnypilot/selfdrive/controls/lib/e2e_alerts_helper.py b/openpilot/sunnypilot/selfdrive/controls/lib/e2e_alerts_helper.py new file mode 100644 index 0000000000..b75bae2461 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/controls/lib/e2e_alerts_helper.py @@ -0,0 +1,170 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" + +from openpilot.cereal import messaging, custom + +from openpilot.common.params import Params +from openpilot.common.realtime import DT_MDL +from openpilot.sunnypilot import PARAMS_UPDATE_PERIOD +from openpilot.sunnypilot.selfdrive.selfdrived.events import EventsSP + +GREEN_LIGHT_X_THRESHOLD = 30 +LEAD_DEPART_DIST_THRESHOLD = 1.0 +TRIGGER_TIMER_THRESHOLD = 0.3 + + +class E2EStates: + INACTIVE = 0 + ARMED = 1 + CONSUMED = 2 + + +class E2EAlertsHelper: + def __init__(self): + self._params = Params() + self.frame = -1 + self.green_light_state = E2EStates.INACTIVE + self.prev_green_light_state = E2EStates.INACTIVE + self.lead_depart_state = E2EStates.INACTIVE + self.prev_lead_depart_state = E2EStates.INACTIVE + + self.green_light_alert = False + self.green_light_alert_enabled = self._params.get_bool("GreenLightAlert") + self.lead_depart_alert = False + self.lead_depart_alert_enabled = self._params.get_bool("LeadDepartAlert") + + self.green_light_trigger_timer = 0 + self.lead_depart_trigger_timer = 0 + self.last_lead_distance = -1 + self.last_moving_frame = -1 + + self.allowed = False + self.last_allowed = False + self.has_lead = False + + self.lead_depart_arm_timer = 0 + self.lead_depart_confirmed_lead = False + self.lead_depart_armed = False + + def _read_params(self) -> None: + if self.frame % int(PARAMS_UPDATE_PERIOD / DT_MDL) == 0: + self.green_light_alert_enabled = self._params.get_bool("GreenLightAlert") + self.lead_depart_alert_enabled = self._params.get_bool("LeadDepartAlert") + + def update_alert_trigger(self, sm: messaging.SubMaster): + CS = sm['carState'] + CC = sm['carControl'] + + model_x = sm['modelV2'].position.x + max_idx = len(model_x) - 1 + self.has_lead = sm['radarState'].leadOne.present + lead_dRel = sm['radarState'].leadOne.dRel + + standstill = CS.standstill + moving = not standstill and CS.vEgo > 0.1 + + if moving: + self.last_moving_frame = self.frame + recent_moving = self.last_moving_frame == -1 or (self.frame - self.last_moving_frame) * DT_MDL < 2.0 + + self.allowed = not moving and not CS.gasPressed and not CC.enabled and not recent_moving + + # Green Light Alert + green_light_trigger = False + if self.green_light_state == E2EStates.ARMED: + if model_x[max_idx] > GREEN_LIGHT_X_THRESHOLD: + self.green_light_trigger_timer += 1 + else: + self.green_light_trigger_timer = 0 + + if self.green_light_trigger_timer * DT_MDL > TRIGGER_TIMER_THRESHOLD: + green_light_trigger = True + elif self.green_light_state != E2EStates.ARMED: + self.green_light_trigger_timer = 0 + + # Lead Departure Alert + close_lead_valid = self.has_lead and lead_dRel < 8.0 + if self.allowed and not self.last_allowed and close_lead_valid: + self.lead_depart_confirmed_lead = True + elif not self.allowed: + self.lead_depart_confirmed_lead = False + + if self.allowed and self.lead_depart_confirmed_lead and close_lead_valid: + self.lead_depart_arm_timer += 1 + + if self.lead_depart_arm_timer * DT_MDL >= 1.0: + self.lead_depart_armed = True + else: + self.lead_depart_arm_timer = 0 + self.lead_depart_armed = False + + lead_depart_trigger = False + if self.lead_depart_state == E2EStates.ARMED: + if self.last_lead_distance == -1 or lead_dRel < self.last_lead_distance: + self.last_lead_distance = lead_dRel + + if self.last_lead_distance != -1 and (lead_dRel - self.last_lead_distance > LEAD_DEPART_DIST_THRESHOLD): + self.lead_depart_trigger_timer += 1 + else: + self.lead_depart_trigger_timer = 0 + + if self.lead_depart_trigger_timer * DT_MDL > TRIGGER_TIMER_THRESHOLD: + lead_depart_trigger = True + elif self.lead_depart_state != E2EStates.ARMED: + self.last_lead_distance = -1 + self.lead_depart_trigger_timer = 0 + + self.last_allowed = self.allowed + + return green_light_trigger, lead_depart_trigger + + @staticmethod + def update_state_machine(state: int, enabled: bool, allowed: bool, triggered: bool) -> tuple[int, bool]: + if state != E2EStates.INACTIVE: + if not allowed or not enabled: + state = E2EStates.INACTIVE + + else: + if state == E2EStates.ARMED: + if triggered: + state = E2EStates.CONSUMED + + elif state == E2EStates.CONSUMED: + pass + + elif state == E2EStates.INACTIVE: + if allowed and enabled: + state = E2EStates.ARMED + + return state, triggered + + def update(self, sm: messaging.SubMaster, events_sp: EventsSP) -> None: + self._read_params() + + green_light_trigger, lead_depart_trigger = self.update_alert_trigger(sm) + + self.prev_green_light_state = self.green_light_state + self.prev_lead_depart_state = self.lead_depart_state + + self.green_light_state, self.green_light_alert = self.update_state_machine( + self.green_light_state, + self.green_light_alert_enabled, + self.allowed and not self.has_lead, + green_light_trigger + ) + + self.lead_depart_state, self.lead_depart_alert = self.update_state_machine( + self.lead_depart_state, + self.lead_depart_alert_enabled, + self.allowed and self.lead_depart_armed, + lead_depart_trigger + ) + + if self.green_light_alert or self.lead_depart_alert: + events_sp.add(custom.OnroadEventSP.EventName.e2eChime) + + self.frame += 1 diff --git a/openpilot/sunnypilot/selfdrive/controls/lib/lane_turn_desire.py b/openpilot/sunnypilot/selfdrive/controls/lib/lane_turn_desire.py new file mode 100644 index 0000000000..ad7e80eda0 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/controls/lib/lane_turn_desire.py @@ -0,0 +1,47 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from openpilot.cereal import custom + +from openpilot.common.constants import CV +from openpilot.common.params import Params + +TurnDirection = custom.ModelDataV2SP.TurnDirection + +LANE_CHANGE_SPEED_MIN = 20 * CV.MPH_TO_MS + + +class LaneTurnController: + def __init__(self, desire_helper): + self.DH = desire_helper + self.turn_direction = TurnDirection.none + self.params = Params() + self.lane_turn_value = float(self.params.get("LaneTurnValue", return_default=True)) * CV.MPH_TO_MS + self.param_read_counter = 0 + self.enabled = self.params.get_bool("LaneTurnDesire") + + def read_params(self): + self.enabled = self.params.get_bool("LaneTurnDesire") + value = float(self.params.get("LaneTurnValue", return_default=True)) * CV.MPH_TO_MS + self.lane_turn_value = min(float(LANE_CHANGE_SPEED_MIN), value) + + def update_params(self) -> None: + if self.param_read_counter % 50 == 0: + self.read_params() + self.param_read_counter += 1 + + def update_lane_turn(self, blindspot_left: bool, blindspot_right: bool, left_blinker: bool, right_blinker: bool, v_ego: float) -> None: + if left_blinker and not right_blinker and v_ego < self.lane_turn_value and not blindspot_left: + self.turn_direction = TurnDirection.turnLeft + elif right_blinker and not left_blinker and v_ego < self.lane_turn_value and not blindspot_right: + self.turn_direction = TurnDirection.turnRight + else: + self.turn_direction = TurnDirection.none + + def get_turn_direction(self): + if not self.enabled: + return TurnDirection.none + return self.turn_direction diff --git a/openpilot/sunnypilot/selfdrive/controls/lib/latcontrol_torque_ext.py b/openpilot/sunnypilot/selfdrive/controls/lib/latcontrol_torque_ext.py new file mode 100644 index 0000000000..39525b3b8e --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/controls/lib/latcontrol_torque_ext.py @@ -0,0 +1,38 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" + +from openpilot.sunnypilot.selfdrive.controls.lib.nnlc.nnlc import NeuralNetworkLateralControl +from openpilot.sunnypilot.selfdrive.controls.lib.latcontrol_torque_ext_override import LatControlTorqueExtOverride + + +class LatControlTorqueExt(NeuralNetworkLateralControl, LatControlTorqueExtOverride): + def __init__(self, lac_torque, CP, CP_SP, CI): + NeuralNetworkLateralControl.__init__(self, lac_torque, CP, CP_SP, CI) + LatControlTorqueExtOverride.__init__(self, CP) + + def update(self, CS, VM, pid, params, ff, pid_log, setpoint, measurement, calibrated_pose, roll_compensation, + desired_lateral_accel, actual_lateral_accel, lateral_accel_deadzone, gravity_adjusted_lateral_accel, + desired_curvature, actual_curvature, steer_limited_by_safety, output_torque): + self._ff = ff + self._pid = pid + self._pid_log = pid_log + self._setpoint = setpoint + self._measurement = measurement + self._roll_compensation = roll_compensation + self._lateral_accel_deadzone = lateral_accel_deadzone + self._desired_lateral_accel = desired_lateral_accel + self._actual_lateral_accel = actual_lateral_accel + self._desired_curvature = desired_curvature + self._actual_curvature = actual_curvature + self._gravity_adjusted_lateral_accel = gravity_adjusted_lateral_accel + self._steer_limited_by_safety = steer_limited_by_safety + self._output_torque = output_torque + + self.update_calculations(CS, VM, desired_lateral_accel) + self.update_neural_network_feedforward(CS, params, calibrated_pose) + + return self._pid_log, self._output_torque diff --git a/sunnypilot/selfdrive/controls/lib/latcontrol_torque_ext_base.py b/openpilot/sunnypilot/selfdrive/controls/lib/latcontrol_torque_ext_base.py similarity index 87% rename from sunnypilot/selfdrive/controls/lib/latcontrol_torque_ext_base.py rename to openpilot/sunnypilot/selfdrive/controls/lib/latcontrol_torque_ext_base.py index 8ccd81d8ff..df773889a9 100644 --- a/sunnypilot/selfdrive/controls/lib/latcontrol_torque_ext_base.py +++ b/openpilot/sunnypilot/selfdrive/controls/lib/latcontrol_torque_ext_base.py @@ -7,11 +7,16 @@ See the LICENSE.md file in the root directory for more details. import math import numpy as np +from openpilot.common.pid import PIDController from openpilot.selfdrive.controls.lib.drive_helpers import CONTROL_N from openpilot.selfdrive.modeld.constants import ModelConstants LAT_PLAN_MIN_IDX = 5 -LATERAL_LAG_MOD = 0.0 # seconds, modifies how far in the future we look ahead for the lateral plan +LATERAL_LAG_MOD = 0.0 # seconds, modifies how far in the future we look ahead for the lateral plan + +KP = 1.0 +KI = 0.3 + def get_predicted_lateral_jerk(lat_accels, t_diffs): # compute finite difference between subsequent model_v2.acceleration.y values @@ -42,28 +47,33 @@ def get_lookahead_value(future_vals, current_val): class LatControlTorqueExtBase: - def __init__(self, lac_torque, CP, CP_SP): + def __init__(self, lac_torque, CP, CP_SP, CI): self.model_v2 = None self.model_valid = False - self.use_steering_angle = lac_torque.use_steering_angle + self.lac_torque = lac_torque self.actual_lateral_jerk: float = 0.0 self.lateral_jerk_setpoint: float = 0.0 self.lateral_jerk_measurement: float = 0.0 self.lookahead_lateral_jerk: float = 0.0 - self.torque_from_lateral_accel = lac_torque.torque_from_lateral_accel + self.torque_from_lateral_accel_in_torque_space = CI.torque_from_lateral_accel_in_torque_space() self.torque_params = lac_torque.torque_params self._ff = 0.0 + self._pid = PIDController(KP, KI) self._pid_log = None self._setpoint = 0.0 self._measurement = 0.0 + self._roll_compensation = 0.0 self._lateral_accel_deadzone = 0.0 self._desired_lateral_accel = 0.0 self._actual_lateral_accel = 0.0 self._desired_curvature = 0.0 self._actual_curvature = 0.0 + self._gravity_adjusted_lateral_accel = 0.0 + self._steer_limited_by_safety = False + self._output_torque = 0.0 # twilsonco's Lateral Neural Network Feedforward # Instantaneous lateral jerk changes very rapidly, making it not useful on its own, @@ -106,9 +116,8 @@ class LatControlTorqueExtBase: self.lateral_jerk_measurement = 0.0 self.lookahead_lateral_jerk = 0.0 - if self.use_steering_angle: - actual_curvature_rate = -VM.calc_curvature(math.radians(CS.steeringRateDeg), CS.vEgo, 0.0) - self.actual_lateral_jerk = actual_curvature_rate * CS.vEgo ** 2 + actual_curvature_rate = -VM.calc_curvature(math.radians(CS.steeringRateDeg), CS.vEgo, 0.0) + self.actual_lateral_jerk = actual_curvature_rate * CS.vEgo ** 2 if self.model_valid: # prepare "look-ahead" desired lateral jerk @@ -118,8 +127,7 @@ class LatControlTorqueExtBase: desired_lateral_jerk = (np.interp(self.desired_lat_jerk_time, ModelConstants.T_IDXS, self.model_v2.acceleration.y) - desired_lateral_accel) / self.desired_lat_jerk_time self.lookahead_lateral_jerk = get_lookahead_value(predicted_lateral_jerk[LAT_PLAN_MIN_IDX:friction_upper_idx], desired_lateral_jerk) - if not self.use_steering_angle or self.lookahead_lateral_jerk == 0.0: - self.lookahead_lateral_jerk = 0.0 + if self.lookahead_lateral_jerk == 0.0: self.actual_lateral_jerk = 0.0 self.lat_accel_friction_factor = 1.0 self.lateral_jerk_setpoint = self.lat_jerk_friction_factor * self.lookahead_lateral_jerk diff --git a/openpilot/sunnypilot/selfdrive/controls/lib/latcontrol_torque_ext_override.py b/openpilot/sunnypilot/selfdrive/controls/lib/latcontrol_torque_ext_override.py new file mode 100644 index 0000000000..f07a7292c1 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/controls/lib/latcontrol_torque_ext_override.py @@ -0,0 +1,34 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" + +from openpilot.common.params import Params + + +class LatControlTorqueExtOverride: + def __init__(self, CP): + self.CP = CP + self.params = Params() + self.enforce_torque_control_toggle = self.params.get_bool("EnforceTorqueControl") # only during init + self.torque_override_enabled = self.params.get_bool("TorqueParamsOverrideEnabled") + self.frame = -1 + + def update_override_torque_params(self, torque_params) -> bool: + if not self.enforce_torque_control_toggle: + return False + + self.frame += 1 + if self.frame % 300 == 0: + self.torque_override_enabled = self.params.get_bool("TorqueParamsOverrideEnabled") + + if not self.torque_override_enabled: + return False + + torque_params.latAccelFactor = float(self.params.get("TorqueParamsOverrideLatAccelFactor", return_default=True)) + torque_params.friction = float(self.params.get("TorqueParamsOverrideFriction", return_default=True)) + return True + + return False diff --git a/openpilot/sunnypilot/selfdrive/controls/lib/latcontrol_torque_v0.py b/openpilot/sunnypilot/selfdrive/controls/lib/latcontrol_torque_v0.py new file mode 100644 index 0000000000..4d9e4492f9 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/controls/lib/latcontrol_torque_v0.py @@ -0,0 +1,128 @@ +import math +import numpy as np +from collections import deque + +from openpilot.cereal import log +from opendbc.car.lateral import get_friction +from openpilot.common.constants import ACCELERATION_DUE_TO_GRAVITY +from openpilot.common.filter_simple import FirstOrderFilter +from openpilot.selfdrive.controls.lib.latcontrol import LatControl +from openpilot.common.pid import PIDController + +from openpilot.sunnypilot.selfdrive.controls.lib.latcontrol_torque_ext import LatControlTorqueExt + +# At higher speeds (25+mph) we can assume: +# Lateral acceleration achieved by a specific car correlates to +# torque applied to the steering rack. It does not correlate to +# wheel slip, or to speed. + +# This controller applies torque to achieve desired lateral +# accelerations. To compensate for the low speed effects the +# proportional gain is increased at low speeds by the PID controller. +# Additionally, there is friction in the steering wheel that needs +# to be overcome to move it at all, this is compensated for too. + +KP = 1.0 +KI = 0.3 +KD = 0.0 +INTERP_SPEEDS = [1, 1.5, 2.0, 3.0, 5, 7.5, 10, 15, 30] +KP_INTERP = [250, 120, 65, 30, 11.5, 5.5, 3.5, 2.0, KP] + +LP_FILTER_CUTOFF_HZ = 1.2 +LAT_ACCEL_REQUEST_BUFFER_SECONDS = 1.0 +FRICTION_THRESHOLD = 0.3 +VERSION = 0 + + +class LatControlTorque(LatControl): + def __init__(self, CP, CP_SP, CI, dt): + super().__init__(CP, CP_SP, CI, dt) + self.torque_params = CP.lateralTuning.torque.as_builder() + self.torque_from_lateral_accel = CI.torque_from_lateral_accel() + self.lateral_accel_from_torque = CI.lateral_accel_from_torque() + self.pid = PIDController([INTERP_SPEEDS, KP_INTERP], KI, KD, rate=1/self.dt) + self.update_limits() + self.steering_angle_deadzone_deg = self.torque_params.steeringAngleDeadzoneDeg + self.lat_accel_request_buffer_len = int(LAT_ACCEL_REQUEST_BUFFER_SECONDS / self.dt) + self.lat_accel_request_buffer = deque([0.] * self.lat_accel_request_buffer_len , maxlen=self.lat_accel_request_buffer_len) + self.previous_measurement = 0.0 + self.measurement_rate_filter = FirstOrderFilter(0.0, 1 / (2 * np.pi * LP_FILTER_CUTOFF_HZ), self.dt) + + self.extension = LatControlTorqueExt(self, CP, CP_SP, CI) + + def update_live_torque_params(self, latAccelFactor, latAccelOffset, friction): + self.torque_params.latAccelFactor = latAccelFactor + self.torque_params.latAccelOffset = latAccelOffset + self.torque_params.friction = friction + self.update_limits() + + def update_limits(self): + self.pid.set_limits(self.lateral_accel_from_torque(self.steer_max, self.torque_params), + self.lateral_accel_from_torque(-self.steer_max, self.torque_params)) + + def update(self, active, CS, VM, params, steer_limited_by_safety, desired_curvature, calibrated_pose, curvature_limited, lat_delay): + # Override torque params from extension + if self.extension.update_override_torque_params(self.torque_params): + self.update_limits() + + pid_log = log.ControlsState.LateralTorqueState.new_message() + pid_log.version = VERSION + if not active: + output_torque = 0.0 + pid_log.active = False + else: + measured_curvature = -VM.calc_curvature(math.radians(CS.steeringAngleDeg - params.angleOffsetDeg), CS.vEgo, params.roll) + roll_compensation = params.roll * ACCELERATION_DUE_TO_GRAVITY + curvature_deadzone = abs(VM.calc_curvature(math.radians(self.steering_angle_deadzone_deg), CS.vEgo, 0.0)) + lateral_accel_deadzone = curvature_deadzone * CS.vEgo ** 2 + + delay_frames = int(np.clip(lat_delay / self.dt, 1, self.lat_accel_request_buffer_len)) + expected_lateral_accel = self.lat_accel_request_buffer[-delay_frames] + # TODO factor out lateral jerk from error to later replace it with delay independent alternative + future_desired_lateral_accel = desired_curvature * CS.vEgo ** 2 + self.lat_accel_request_buffer.append(future_desired_lateral_accel) + gravity_adjusted_future_lateral_accel = future_desired_lateral_accel - roll_compensation + desired_lateral_jerk = (future_desired_lateral_accel - expected_lateral_accel) / lat_delay + + measurement = measured_curvature * CS.vEgo ** 2 + measurement_rate = self.measurement_rate_filter.update((measurement - self.previous_measurement) / self.dt) + self.previous_measurement = measurement + + setpoint = lat_delay * desired_lateral_jerk + expected_lateral_accel + error = setpoint - measurement + + # do error correction in lateral acceleration space, convert at end to handle non-linear torque responses correctly + pid_log.error = float(error) + ff = gravity_adjusted_future_lateral_accel + # latAccelOffset corrects roll compensation bias from device roll misalignment relative to car roll + ff -= self.torque_params.latAccelOffset + # TODO jerk is weighted by lat_delay for legacy reasons, but should be made independent of it + ff += get_friction(error, lateral_accel_deadzone, FRICTION_THRESHOLD, self.torque_params) + + freeze_integrator = steer_limited_by_safety or CS.steeringPressed or CS.vEgo < 5 + output_lataccel = self.pid.update(pid_log.error, + -measurement_rate, + feedforward=ff, + speed=CS.vEgo, + freeze_integrator=freeze_integrator) + output_torque = self.torque_from_lateral_accel(output_lataccel, self.torque_params) + + # Lateral acceleration torque controller extension updates + # Overrides pid_log.error and output_torque + pid_log, output_torque = self.extension.update(CS, VM, self.pid, params, ff, pid_log, setpoint, measurement, calibrated_pose, roll_compensation, + future_desired_lateral_accel, measurement, lateral_accel_deadzone, gravity_adjusted_future_lateral_accel, + desired_curvature, measured_curvature, steer_limited_by_safety, output_torque) + + pid_log.active = True + pid_log.p = float(self.pid.p) + pid_log.i = float(self.pid.i) + pid_log.d = float(self.pid.d) + pid_log.f = float(self.pid.f) + pid_log.output = float(-output_torque) # TODO: log lat accel? + pid_log.actualLateralAccel = float(measurement) + pid_log.desiredLateralAccel = float(setpoint) + pid_log.desiredLateralJerk = float(desired_lateral_jerk) + pid_log.saturated = bool(self._check_saturation(self.steer_max - abs(output_torque) < 1e-3, CS, steer_limited_by_safety, curvature_limited)) + + # TODO left is positive in this convention + return -output_torque, 0.0, pid_log diff --git a/openpilot/sunnypilot/selfdrive/controls/lib/latcontrol_torque_versions.json b/openpilot/sunnypilot/selfdrive/controls/lib/latcontrol_torque_versions.json new file mode 100644 index 0000000000..21b5884a01 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/controls/lib/latcontrol_torque_versions.json @@ -0,0 +1,8 @@ +{ + "v1.0": { + "version": "1.0" + }, + "v0.0": { + "version": "0.0" + } +} diff --git a/openpilot/sunnypilot/selfdrive/controls/lib/longitudinal_planner.py b/openpilot/sunnypilot/selfdrive/controls/lib/longitudinal_planner.py new file mode 100644 index 0000000000..f1e0c36416 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/controls/lib/longitudinal_planner.py @@ -0,0 +1,141 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" + +from openpilot.cereal import messaging, custom +from opendbc.car import structs +from openpilot.common.constants import CV +from openpilot.selfdrive.car.cruise import V_CRUISE_MAX +from openpilot.sunnypilot.selfdrive.controls.lib.dec.dec import DynamicExperimentalController +from openpilot.sunnypilot.selfdrive.controls.lib.e2e_alerts_helper import E2EAlertsHelper +from openpilot.sunnypilot.selfdrive.controls.lib.smart_cruise_control.smart_cruise_control import SmartCruiseControl +from openpilot.sunnypilot.selfdrive.controls.lib.speed_limit.speed_limit_assist import SpeedLimitAssist +from openpilot.sunnypilot.selfdrive.controls.lib.speed_limit.speed_limit_resolver import SpeedLimitResolver +from openpilot.sunnypilot.selfdrive.selfdrived.events import EventsSP +from openpilot.sunnypilot.models.helpers import get_active_bundle + +DecState = custom.LongitudinalPlanSP.DynamicExperimentalControl.DynamicExperimentalControlState +LongitudinalPlanSource = custom.LongitudinalPlanSP.LongitudinalPlanSource + + +class LongitudinalPlannerSP: + def __init__(self, CP: structs.CarParams, CP_SP: structs.CarParamsSP, mpc): + self.events_sp = EventsSP() + self.resolver = SpeedLimitResolver() + self.dec = DynamicExperimentalController(CP, mpc) + self.scc = SmartCruiseControl() + self.resolver = SpeedLimitResolver() + self.sla = SpeedLimitAssist(CP, CP_SP) + self.generation = int(model_bundle.generation) if (model_bundle := get_active_bundle()) else None + self.source = LongitudinalPlanSource.cruise + self.e2e_alerts_helper = E2EAlertsHelper() + + self.output_v_target = 0. + self.output_a_target = 0. + + def is_e2e(self, sm: messaging.SubMaster) -> bool: + experimental_mode = sm['selfdriveState'].experimentalMode + if not self.dec.active(): + return experimental_mode + + return experimental_mode and self.dec.mode() == "blended" + + def update_targets(self, sm: messaging.SubMaster, v_ego: float, a_ego: float, v_cruise: float) -> tuple[float, float]: + CS = sm['carState'] + v_cruise_cluster_kph = min(CS.vCruiseCluster, V_CRUISE_MAX) + v_cruise_cluster = v_cruise_cluster_kph * CV.KPH_TO_MS + + long_enabled = sm['carControl'].enabled + long_override = sm['carControl'].cruiseControl.override + + # Smart Cruise Control + self.scc.update(sm, long_enabled, long_override, v_ego, a_ego, v_cruise) + + # Speed Limit Resolver + self.resolver.update(v_ego, sm) + + # Speed Limit Assist + has_speed_limit = self.resolver.speed_limit_valid or self.resolver.speed_limit_last_valid + self.sla.update(long_enabled, long_override, v_ego, a_ego, v_cruise_cluster, self.resolver.speed_limit, + self.resolver.speed_limit_final_last, has_speed_limit, self.resolver.distance, self.events_sp) + + targets = { + LongitudinalPlanSource.cruise: (v_cruise, a_ego), + LongitudinalPlanSource.sccVision: (self.scc.vision.output_v_target, self.scc.vision.output_a_target), + LongitudinalPlanSource.sccMap: (self.scc.map.output_v_target, self.scc.map.output_a_target), + LongitudinalPlanSource.speedLimitAssist: (self.sla.output_v_target, self.sla.output_a_target), + } + + self.source = min(targets, key=lambda k: targets[k][0]) + self.output_v_target, self.output_a_target = targets[self.source] + return self.output_v_target, self.output_a_target + + def update(self, sm: messaging.SubMaster) -> None: + self.events_sp.clear() + self.dec.update(sm) + self.e2e_alerts_helper.update(sm, self.events_sp) + + def publish_longitudinal_plan_sp(self, sm: messaging.SubMaster, pm: messaging.PubMaster) -> None: + plan_sp_send = messaging.new_message('longitudinalPlanSP') + + plan_sp_send.valid = sm.all_checks(service_list=['carState', 'controlsState']) + + longitudinalPlanSP = plan_sp_send.longitudinalPlanSP + longitudinalPlanSP.longitudinalPlanSource = self.source + longitudinalPlanSP.vTarget = float(self.output_v_target) + longitudinalPlanSP.aTarget = float(self.output_a_target) + longitudinalPlanSP.events = self.events_sp.to_msg() + + # Dynamic Experimental Control + dec = longitudinalPlanSP.dec + dec.state = DecState.blended if self.dec.mode() == 'blended' else DecState.acc + dec.enabled = self.dec.enabled() + dec.active = self.dec.active() + + # Smart Cruise Control + smartCruiseControl = longitudinalPlanSP.smartCruiseControl + # Vision Control + sccVision = smartCruiseControl.vision + sccVision.state = self.scc.vision.state + sccVision.vTarget = float(self.scc.vision.output_v_target) + sccVision.aTarget = float(self.scc.vision.output_a_target) + sccVision.currentLateralAccel = float(self.scc.vision.current_lat_acc) + sccVision.maxPredictedLateralAccel = float(self.scc.vision.max_pred_lat_acc) + sccVision.enabled = self.scc.vision.is_enabled + sccVision.active = self.scc.vision.is_active + # Map Control + sccMap = smartCruiseControl.map + sccMap.state = self.scc.map.state + sccMap.vTarget = float(self.scc.map.output_v_target) + sccMap.aTarget = float(self.scc.map.output_a_target) + sccMap.enabled = self.scc.map.is_enabled + sccMap.active = self.scc.map.is_active + + # Speed Limit + speedLimit = longitudinalPlanSP.speedLimit + resolver = speedLimit.resolver + resolver.speedLimit = float(self.resolver.speed_limit) + resolver.speedLimitLast = float(self.resolver.speed_limit_last) + resolver.speedLimitFinal = float(self.resolver.speed_limit_final) + resolver.speedLimitFinalLast = float(self.resolver.speed_limit_final_last) + resolver.speedLimitValid = self.resolver.speed_limit_valid + resolver.speedLimitLastValid = self.resolver.speed_limit_last_valid + resolver.speedLimitOffset = float(self.resolver.speed_limit_offset) + resolver.distToSpeedLimit = float(self.resolver.distance) + resolver.source = self.resolver.source + assist = speedLimit.assist + assist.state = self.sla.state + assist.enabled = self.sla.is_enabled + assist.active = self.sla.is_active + assist.vTarget = float(self.sla.output_v_target) + assist.aTarget = float(self.sla.output_a_target) + + # E2E Alerts + e2eAlerts = longitudinalPlanSP.e2eAlerts + e2eAlerts.greenLightAlert = self.e2e_alerts_helper.green_light_alert + e2eAlerts.leadDepartAlert = self.e2e_alerts_helper.lead_depart_alert + + pm.send('longitudinalPlanSP', plan_sp_send) diff --git a/sunnypilot/sunnylink/backups/__init__.py b/openpilot/sunnypilot/selfdrive/controls/lib/nnlc/__init__.py similarity index 100% rename from sunnypilot/sunnylink/backups/__init__.py rename to openpilot/sunnypilot/selfdrive/controls/lib/nnlc/__init__.py diff --git a/openpilot/sunnypilot/selfdrive/controls/lib/nnlc/helpers.py b/openpilot/sunnypilot/selfdrive/controls/lib/nnlc/helpers.py new file mode 100644 index 0000000000..a5d56b1ff0 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/controls/lib/nnlc/helpers.py @@ -0,0 +1,68 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import os +import tomllib +from difflib import SequenceMatcher + +from opendbc.car import structs +from openpilot.common.basedir import BASEDIR + +TORQUE_NN_MODEL_PATH = os.path.join(BASEDIR, "openpilot", "sunnypilot", "neural_network_data", "neural_network_lateral_control") +TORQUE_NN_MODEL_SUBSTITUTE_PATH = os.path.join(BASEDIR, "opendbc_repo", "opendbc", "car", "torque_data/substitute.toml") +MOCK_MODEL_PATH = os.path.join(TORQUE_NN_MODEL_PATH, "MOCK.json") + + +def similarity(s1: str, s2: str) -> float: + return SequenceMatcher(None, s1, s2).ratio() + + +def get_nn_model_path(CP: structs.CarParams) -> tuple[str, str, bool]: + car_fingerprint = CP.carFingerprint + eps_fw = str(next((fw.fwVersion for fw in CP.carFw if fw.ecu == "eps"), "")) + + def check_nn_path(_nn_candidate): + _model_path = None + _max_similarity = -1.0 + for f in os.listdir(TORQUE_NN_MODEL_PATH): + if f.endswith(".json"): + model = os.path.splitext(f)[0] + similarity_score = similarity(model, _nn_candidate) + if similarity_score > _max_similarity: + _max_similarity = similarity_score + _model_path = os.path.join(TORQUE_NN_MODEL_PATH, f) + return _model_path, _max_similarity + + if len(eps_fw) > 3: + eps_fw = eps_fw.replace("\\", "") + nn_candidate = f"{car_fingerprint} {eps_fw}" + else: + nn_candidate = car_fingerprint + + model_path, max_similarity = check_nn_path(nn_candidate) + exact_match = max_similarity >= 0.99 + + if car_fingerprint not in model_path or 0.0 <= max_similarity < 0.9: + nn_candidate = car_fingerprint + model_path, max_similarity = check_nn_path(nn_candidate) + exact_match = max_similarity >= 0.99 + + if 0.0 <= max_similarity < 0.9: + with open(TORQUE_NN_MODEL_SUBSTITUTE_PATH, 'rb') as f: + sub = tomllib.load(f) + sub_candidate = sub.get(car_fingerprint, car_fingerprint) + + for candidate in [car_fingerprint, sub_candidate]: + model_path, max_similarity = check_nn_path(candidate) + + exact_match = False + + if CP.steerControlType == structs.CarParams.SteerControlType.angle: + model_path = MOCK_MODEL_PATH + + model_name = os.path.splitext(os.path.basename(model_path))[0] + + return model_path, model_name, exact_match diff --git a/sunnypilot/selfdrive/controls/lib/nnlc/model.py b/openpilot/sunnypilot/selfdrive/controls/lib/nnlc/model.py similarity index 100% rename from sunnypilot/selfdrive/controls/lib/nnlc/model.py rename to openpilot/sunnypilot/selfdrive/controls/lib/nnlc/model.py diff --git a/openpilot/sunnypilot/selfdrive/controls/lib/nnlc/nnlc.py b/openpilot/sunnypilot/selfdrive/controls/lib/nnlc/nnlc.py new file mode 100644 index 0000000000..e66072f86f --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/controls/lib/nnlc/nnlc.py @@ -0,0 +1,164 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from collections import deque +import math +import numpy as np + +from opendbc.car.lateral import FRICTION_THRESHOLD, get_friction +from opendbc.sunnypilot.car.interfaces import LatControlInputs +from opendbc.sunnypilot.car.lateral_ext import get_friction as get_friction_in_torque_space +from openpilot.common.filter_simple import FirstOrderFilter +from openpilot.common.params import Params +from openpilot.selfdrive.modeld.constants import ModelConstants +from openpilot.sunnypilot.selfdrive.controls.lib.latcontrol_torque_ext_base import LatControlTorqueExtBase, sign +from openpilot.sunnypilot.selfdrive.controls.lib.nnlc.helpers import MOCK_MODEL_PATH +from openpilot.sunnypilot.selfdrive.controls.lib.nnlc.model import NNTorqueModel + +LOW_SPEED_X = [0, 10, 20, 30] +LOW_SPEED_Y = [12, 3, 1, 0] + + +# At a given roll, if pitch magnitude increases, the +# gravitational acceleration component starts pointing +# in the longitudinal direction, decreasing the lateral +# acceleration component. Here we do the same thing +# to the roll value itself, then passed to nnff. +def roll_pitch_adjust(roll, pitch): + return roll * math.cos(pitch) + + +class NeuralNetworkLateralControl(LatControlTorqueExtBase): + def __init__(self, lac_torque, CP, CP_SP, CI): + super().__init__(lac_torque, CP, CP_SP, CI) + self.params = Params() + self.enabled = self.params.get_bool("NeuralNetworkLateralControl") + self.has_nn_model = CP_SP.neuralNetworkLateralControl.model.path != MOCK_MODEL_PATH + + # NN model takes current v_ego, lateral_accel, lat accel/jerk error, roll, and past/future/planned data + # of lat accel and roll + # Past value is computed using previous desired lat accel and observed roll + self.model = NNTorqueModel(CP_SP.neuralNetworkLateralControl.model.path) + + self.pitch = FirstOrderFilter(0.0, 0.5, 0.01) + self.pitch_last = 0.0 + + # setup future time offsets + self.future_times = [0.3, 0.6, 1.0, 1.5] # seconds in the future + self.nn_future_times = [i + self.desired_lat_jerk_time for i in self.future_times] + + # setup past time offsets + self.past_times = [-0.3, -0.2, -0.1] + history_check_frames = [int(abs(i)*100) for i in self.past_times] + self.history_frame_offsets = [history_check_frames[0] - i for i in history_check_frames] + self.lateral_accel_desired_deque = deque(maxlen=history_check_frames[0]) + self.roll_deque = deque(maxlen=history_check_frames[0]) + self.error_deque = deque(maxlen=history_check_frames[0]) + self.past_future_len = len(self.past_times) + len(self.nn_future_times) + + @property + def _nnlc_enabled(self): + return self.enabled and self.model_valid and self.has_nn_model + + def update_limits(self): + if not self._nnlc_enabled: + return + + self._pid.set_limits(self.lac_torque.steer_max, -self.lac_torque.steer_max) + + def update_lateral_lag(self, lag): + super().update_lateral_lag(lag) + self.nn_future_times = [t + self.desired_lat_jerk_time for t in self.future_times] + + def update_feedforward_torque_space(self, CS): + torque_from_setpoint = self.torque_from_lateral_accel_in_torque_space(LatControlInputs(self._setpoint, self._roll_compensation, CS.vEgo, CS.aEgo), + self.torque_params, gravity_adjusted=False) + torque_from_measurement = self.torque_from_lateral_accel_in_torque_space(LatControlInputs(self._measurement, self._roll_compensation, CS.vEgo, CS.aEgo), + self.torque_params, gravity_adjusted=False) + self._pid_log.error = float(torque_from_setpoint - torque_from_measurement) # ty: ignore[invalid-assignment] + self._ff = self.torque_from_lateral_accel_in_torque_space(LatControlInputs(self._gravity_adjusted_lateral_accel, self._roll_compensation, + CS.vEgo, CS.aEgo), self.torque_params, gravity_adjusted=True) + self._ff += get_friction_in_torque_space(self._desired_lateral_accel - self._actual_lateral_accel, self._lateral_accel_deadzone, + FRICTION_THRESHOLD, self.torque_params) + + def update_output_torque(self, CS): + freeze_integrator = self._steer_limited_by_safety or CS.steeringPressed or CS.vEgo < 5 + self._output_torque = self._pid.update(self._pid_log.error, + feedforward=self._ff, + speed=CS.vEgo, + freeze_integrator=freeze_integrator) + + def update_neural_network_feedforward(self, CS, params, calibrated_pose) -> None: + if not self._nnlc_enabled: + return + + self.update_feedforward_torque_space(CS) + + low_speed_factor = float(np.interp(CS.vEgo, LOW_SPEED_X, LOW_SPEED_Y)) ** 2 + self._setpoint = self._desired_lateral_accel + low_speed_factor * self._desired_curvature + self._measurement = self._actual_lateral_accel + low_speed_factor * self._actual_curvature + + # update past data + roll = params.roll + if calibrated_pose is not None: + pitch = self.pitch.update(calibrated_pose.orientation.pitch) + roll = roll_pitch_adjust(roll, pitch) + self.pitch_last = pitch + self.roll_deque.append(roll) + self.lateral_accel_desired_deque.append(self._desired_lateral_accel) + + # prepare past and future values + # adjust future times to account for longitudinal acceleration + adjusted_future_times = [t + 0.5 * CS.aEgo * (t / max(CS.vEgo, 1.0)) for t in self.nn_future_times] + past_rolls = [self.roll_deque[min(len(self.roll_deque) - 1, i)] for i in self.history_frame_offsets] + future_rolls = [roll_pitch_adjust(np.interp(t, ModelConstants.T_IDXS, self.model_v2.orientation.x) + roll, + np.interp(t, ModelConstants.T_IDXS, self.model_v2.orientation.y) + self.pitch_last) for t in + adjusted_future_times] + past_lateral_accels_desired = [self.lateral_accel_desired_deque[min(len(self.lateral_accel_desired_deque) - 1, i)] + for i in self.history_frame_offsets] + future_planned_lateral_accels = [np.interp(t, ModelConstants.T_IDXS, self.model_v2.acceleration.y) for t in + adjusted_future_times] + + # compute NNFF error response + nnff_setpoint_input = [CS.vEgo, self._setpoint, self.lateral_jerk_setpoint, roll] \ + + [self._setpoint] * self.past_future_len \ + + past_rolls + future_rolls + # past lateral accel error shouldn't count, so use past desired like the setpoint input + nnff_measurement_input = [CS.vEgo, self._measurement, self.lateral_jerk_measurement, roll] \ + + [self._measurement] * self.past_future_len \ + + past_rolls + future_rolls + torque_from_setpoint = self.model.evaluate(nnff_setpoint_input) + torque_from_measurement = self.model.evaluate(nnff_measurement_input) + self._pid_log.error = torque_from_setpoint - torque_from_measurement # ty: ignore[invalid-assignment] + + # The "pure" NNLC error response can be too weak for cars whose models were trained + # with a lack of high-magnitude lateral acceleration data, for which the NNLC model + # torque response flattens out at high lateral accelerations. + # This workaround blends in a guaranteed stronger error response only when the + # desired lateral acceleration is high enough to warrant it, by using the lateral acceleration + # error as the input to the NNLC model. This is not ideal, and potentially degrades the NNLC + # accuracy for cars that don't have this issue, but it's necessary until a better NNLC model + # structure is used that doesn't create this issue when high-magnitude data is missing. + error_blend_factor = float(np.interp(abs(self._desired_lateral_accel), [1.0, 2.0], [0.0, 1.0])) + if error_blend_factor > 0.0: # blend in stronger error response when in high lat accel + # NNFF inputs 5+ are optional, and if left out are replaced with 0.0 inside the NNFF class + nnff_error_input = [CS.vEgo, self._setpoint - self._measurement, self.lateral_jerk_setpoint - self.lateral_jerk_measurement, 0.0] + torque_from_error = self.model.evaluate(nnff_error_input) + if sign(self._pid_log.error) == sign(torque_from_error) and abs(self._pid_log.error) < abs(torque_from_error): + self._pid_log.error = self._pid_log.error * (1.0 - error_blend_factor) + torque_from_error * error_blend_factor # ty: ignore[invalid-assignment] + + # compute feedforward (same as nn setpoint output) + friction_input = self.update_friction_input(self._setpoint, self._measurement) + nn_input = [CS.vEgo, self._desired_lateral_accel, friction_input, roll] \ + + past_lateral_accels_desired + future_planned_lateral_accels \ + + past_rolls + future_rolls + self._ff = self.model.evaluate(nn_input) + + # apply friction override for cars with low NN friction response + if self.model.friction_override: + self._pid_log.error += get_friction(friction_input, self._lateral_accel_deadzone, FRICTION_THRESHOLD, self.torque_params) + + self.update_output_torque(CS) diff --git a/system/__init__.py b/openpilot/sunnypilot/selfdrive/controls/lib/nnlc/tests/__init__.py similarity index 100% rename from system/__init__.py rename to openpilot/sunnypilot/selfdrive/controls/lib/nnlc/tests/__init__.py diff --git a/sunnypilot/selfdrive/controls/lib/nnlc/tests/test_fingerprint.py b/openpilot/sunnypilot/selfdrive/controls/lib/nnlc/tests/test_fingerprint.py similarity index 96% rename from sunnypilot/selfdrive/controls/lib/nnlc/tests/test_fingerprint.py rename to openpilot/sunnypilot/selfdrive/controls/lib/nnlc/tests/test_fingerprint.py index 0f016ccaf0..07e7d2852d 100644 --- a/sunnypilot/selfdrive/controls/lib/nnlc/tests/test_fingerprint.py +++ b/openpilot/sunnypilot/selfdrive/controls/lib/nnlc/tests/test_fingerprint.py @@ -1,11 +1,10 @@ -from parameterized import parameterized - from opendbc.car.car_helpers import interfaces from opendbc.car.honda.values import CAR as HONDA from opendbc.car.hyundai.values import CAR as HYUNDAI from opendbc.car.nissan.values import CAR as NISSAN from opendbc.car.toyota.values import CAR as TOYOTA from opendbc.car.tesla.values import CAR as TESLA +from openpilot.common.parameterized import parameterized from openpilot.common.params import Params from openpilot.sunnypilot.selfdrive.car import interfaces as sunnypilot_interfaces diff --git a/sunnypilot/selfdrive/controls/lib/nnlc/tests/test_load_model.py b/openpilot/sunnypilot/selfdrive/controls/lib/nnlc/tests/test_load_model.py similarity index 84% rename from sunnypilot/selfdrive/controls/lib/nnlc/tests/test_load_model.py rename to openpilot/sunnypilot/selfdrive/controls/lib/nnlc/tests/test_load_model.py index af7077d1c6..2f4e0d6993 100644 --- a/sunnypilot/selfdrive/controls/lib/nnlc/tests/test_load_model.py +++ b/openpilot/sunnypilot/selfdrive/controls/lib/nnlc/tests/test_load_model.py @@ -1,10 +1,10 @@ -from parameterized import parameterized - from opendbc.car.car_helpers import interfaces from opendbc.car.honda.values import CAR as HONDA from opendbc.car.hyundai.values import CAR as HYUNDAI from opendbc.car.toyota.values import CAR as TOYOTA +from openpilot.common.parameterized import parameterized from openpilot.common.params import Params +from openpilot.common.realtime import DT_CTRL from openpilot.selfdrive.car.helpers import convert_to_capnp from openpilot.selfdrive.controls.lib.latcontrol_torque import LatControlTorque from openpilot.sunnypilot.selfdrive.car import interfaces as sunnypilot_interfaces @@ -15,7 +15,7 @@ class TestNNTorqueModel: @parameterized.expand([HONDA.HONDA_CIVIC, TOYOTA.TOYOTA_RAV4, HYUNDAI.HYUNDAI_SANTA_CRUZ_1ST_GEN]) def test_load_model(self, car_name): params = Params() - params.put_bool("NeuralNetworkLateralControl", True) + params.put_bool("NeuralNetworkLateralControl", True, block=True) CarInterface = interfaces[car_name] CP = CarInterface.get_non_essential_params(car_name) @@ -26,6 +26,6 @@ class TestNNTorqueModel: CP_SP = convert_to_capnp(CP_SP) - controller = LatControlTorque(CP.as_reader(), CP_SP.as_reader(), CI) + controller = LatControlTorque(CP.as_reader(), CP_SP.as_reader(), CI, DT_CTRL) assert controller.extension.has_nn_model diff --git a/sunnypilot/selfdrive/controls/lib/nnlc/tests/test_nnlc.py b/openpilot/sunnypilot/selfdrive/controls/lib/nnlc/tests/test_nnlc.py similarity index 76% rename from sunnypilot/selfdrive/controls/lib/nnlc/tests/test_nnlc.py rename to openpilot/sunnypilot/selfdrive/controls/lib/nnlc/tests/test_nnlc.py index 01ddec68ab..56fd2f9ce7 100644 --- a/sunnypilot/selfdrive/controls/lib/nnlc/tests/test_nnlc.py +++ b/openpilot/sunnypilot/selfdrive/controls/lib/nnlc/tests/test_nnlc.py @@ -1,13 +1,16 @@ import numpy as np -from parameterized import parameterized -from cereal import car, log, messaging +from openpilot.cereal import log, messaging +from opendbc.car.structs import car from opendbc.car.car_helpers import interfaces +from opendbc.car.gm.values import CAR as GM from opendbc.car.honda.values import CAR as HONDA from opendbc.car.hyundai.values import CAR as HYUNDAI from opendbc.car.toyota.values import CAR as TOYOTA from opendbc.car.vehicle_model import VehicleModel +from openpilot.common.parameterized import parameterized from openpilot.common.params import Params +from openpilot.common.realtime import DT_CTRL from openpilot.selfdrive.car.helpers import convert_to_capnp from openpilot.selfdrive.controls.lib.latcontrol_torque import LatControlTorque from openpilot.selfdrive.locationd.helpers import Pose @@ -41,10 +44,10 @@ def generate_modelV2(): class TestNeuralNetworkLateralControl: - @parameterized.expand([HONDA.HONDA_CIVIC, TOYOTA.TOYOTA_RAV4, HYUNDAI.HYUNDAI_SANTA_CRUZ_1ST_GEN]) + @parameterized.expand([HONDA.HONDA_CIVIC, TOYOTA.TOYOTA_RAV4, HYUNDAI.HYUNDAI_SANTA_CRUZ_1ST_GEN, GM.CHEVROLET_BOLT_EUV]) def test_saturation(self, car_name): params = Params() - params.put_bool("NeuralNetworkLateralControl", True) + params.put_bool("NeuralNetworkLateralControl", True, block=True) CarInterface = interfaces[car_name] CP = CarInterface.get_non_essential_params(car_name) @@ -56,7 +59,8 @@ class TestNeuralNetworkLateralControl: CP_SP = convert_to_capnp(CP_SP) VM = VehicleModel(CP) - controller = LatControlTorque(CP.as_reader(), CP_SP.as_reader(), CI) + controller = LatControlTorque(CP.as_reader(), CP_SP.as_reader(), CI, DT_CTRL) + torque_params = CP.lateralTuning.torque CS = car.CarState.new_message() CS.vEgo = 30 @@ -77,17 +81,23 @@ class TestNeuralNetworkLateralControl: for _ in range(1000): controller.extension.update_model_v2(model_v2) controller.extension.update_lateral_lag(test_lag) - _, _, lac_log = controller.update(True, CS, VM, params, False, 0, pose, True) + controller.update_live_torque_params(torque_params.latAccelFactor, torque_params.latAccelOffset, torque_params.friction) + controller.extension.update_limits() + _, _, lac_log = controller.update(True, CS, VM, params, False, 0, pose, True, 0.2) assert lac_log.saturated for _ in range(1000): controller.extension.update_model_v2(model_v2) controller.extension.update_lateral_lag(test_lag) - _, _, lac_log = controller.update(True, CS, VM, params, False, 0, pose, False) + controller.update_live_torque_params(torque_params.latAccelFactor, torque_params.latAccelOffset, torque_params.friction) + controller.extension.update_limits() + _, _, lac_log = controller.update(True, CS, VM, params, False, 0, pose, False, 0.2) assert not lac_log.saturated for _ in range(1000): controller.extension.update_model_v2(model_v2) controller.extension.update_lateral_lag(test_lag) - _, _, lac_log = controller.update(True, CS, VM, params, False, 1, pose, False) + controller.update_live_torque_params(torque_params.latAccelFactor, torque_params.latAccelOffset, torque_params.friction) + controller.extension.update_limits() + _, _, lac_log = controller.update(True, CS, VM, params, False, 1, pose, False, 0.2) assert lac_log.saturated diff --git a/openpilot/sunnypilot/selfdrive/controls/lib/smart_cruise_control/__init__.py b/openpilot/sunnypilot/selfdrive/controls/lib/smart_cruise_control/__init__.py new file mode 100644 index 0000000000..271f49dcc2 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/controls/lib/smart_cruise_control/__init__.py @@ -0,0 +1,9 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from openpilot.common.constants import CV + +MIN_V = 20 * CV.KPH_TO_MS # Do not operate under 20 km/h diff --git a/openpilot/sunnypilot/selfdrive/controls/lib/smart_cruise_control/map_controller.py b/openpilot/sunnypilot/selfdrive/controls/lib/smart_cruise_control/map_controller.py new file mode 100644 index 0000000000..65e157bdbc --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/controls/lib/smart_cruise_control/map_controller.py @@ -0,0 +1,261 @@ +import json +import math +import platform + +from openpilot.cereal import custom +from openpilot.common.params import Params +from openpilot.common.realtime import DT_MDL +from openpilot.selfdrive.car.cruise import V_CRUISE_UNSET +from openpilot.sunnypilot import PARAMS_UPDATE_PERIOD +from openpilot.sunnypilot.navd.helpers import coordinate_from_param, Coordinate +from openpilot.sunnypilot.selfdrive.controls.lib.smart_cruise_control import MIN_V + +MapState = VisionState = custom.LongitudinalPlanSP.SmartCruiseControl.MapState + +ACTIVE_STATES = (MapState.turning, ) +ENABLED_STATES = (MapState.enabled, MapState.overriding, *ACTIVE_STATES) + +R = 6373000.0 # approximate radius of earth in meters +TO_RADIANS = math.pi / 180 +TO_DEGREES = 180 / math.pi +TARGET_JERK = -0.6 # m/s^3 There's some jounce limits that are not consistent so we're fudging this some +TARGET_ACCEL = -1.2 # m/s^2 should match up with the long planner limit +TARGET_OFFSET = 1.0 # seconds - This controls how soon before the curve you reach the target velocity. It also helps + # reach the target velocity when inaccuracies in the distance modeling logic would cause overshoot. + # The value is multiplied against the target velocity to determine the additional distance. This is + # done to keep the distance calculations consistent but results in the offset actually being less + # time than specified depending on how much of a speed differential there is between v_ego and the + # target velocity. + + +def velocities_from_param(param: str, params: Params): + if params is None: + params = Params() + + json_str = params.get(param) + if json_str is None: + return None + + velocities = json.loads(json_str) + + return velocities + + +def calculate_accel(t, target_jerk, a_ego): + return a_ego + target_jerk * t + + +def calculate_velocity(t, target_jerk, a_ego, v_ego): + return v_ego + a_ego * t + target_jerk/2 * (t ** 2) + + +def calculate_distance(t, target_jerk, a_ego, v_ego): + return t * v_ego + a_ego/2 * (t ** 2) + target_jerk/6 * (t ** 3) + + +# points should be in radians +# output is meters +def distance_to_point(ax, ay, bx, by): + a = math.sin((bx-ax)/2)*math.sin((bx-ax)/2) + math.cos(ax) * math.cos(bx)*math.sin((by-ay)/2)*math.sin((by-ay)/2) + c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a)) + + return R * c # in meters + + +class SmartCruiseControlMap: + v_target: float = 0 + a_target: float = 0. + v_ego: float = 0. + a_ego: float = 0. + output_v_target: float = V_CRUISE_UNSET + output_a_target: float = 0. + + def __init__(self): + self.params = Params() + self.mem_params = Params("/dev/shm/params") if platform.system() != "Darwin" else self.params + self.enabled = self.params.get_bool("SmartCruiseControlMap") + self.long_enabled = False + self.long_override = False + self.is_enabled = False + self.is_active = False + self.state = MapState.disabled + self.v_cruise = 0 + self.target_lat = 0.0 + self.target_lon = 0.0 + self.frame = -1 + + self.last_position = coordinate_from_param("LastGPSPosition", self.mem_params) or Coordinate(0.0, 0.0) + self.target_velocities = velocities_from_param("MapTargetVelocities", self.mem_params) or [] + + def get_v_target_from_control(self) -> float: + if self.is_active: + return max(self.v_target, MIN_V) + + return V_CRUISE_UNSET + + def get_a_target_from_control(self) -> float: + return self.a_ego + + def update_params(self): + if self.frame % int(PARAMS_UPDATE_PERIOD / DT_MDL) == 0: + self.enabled = self.params.get_bool("SmartCruiseControlMap") + + def update_calculations(self) -> None: + self.last_position = coordinate_from_param("LastGPSPosition", self.mem_params) or Coordinate(0.0, 0.0) + lat = self.last_position.latitude + lon = self.last_position.longitude + + self.target_velocities = velocities_from_param("MapTargetVelocities", self.mem_params) or [] + + if self.last_position is None or self.target_velocities is None: + return + + min_dist = 1000 + min_idx = 0 + distances = [] + + # find our location in the path + for i in range(len(self.target_velocities)): + target_velocity = self.target_velocities[i] + tlat = target_velocity["latitude"] + tlon = target_velocity["longitude"] + d = distance_to_point(lat * TO_RADIANS, lon * TO_RADIANS, tlat * TO_RADIANS, tlon * TO_RADIANS) + distances.append(d) + if d < min_dist: + min_dist = d + min_idx = i + + # only look at values from our current position forward + forward_points = self.target_velocities[min_idx:] + forward_distances = distances[min_idx:] + + # find velocities that we are within the distance we need to adjust for + valid_velocities = [] + for i in range(len(forward_points)): + target_velocity = forward_points[i] + tlat = target_velocity["latitude"] + tlon = target_velocity["longitude"] + tv = target_velocity["velocity"] + if tv > self.v_ego: + continue + + d = forward_distances[i] + + a_diff = (self.a_ego - TARGET_ACCEL) + accel_t = abs(a_diff / TARGET_JERK) + min_accel_v = calculate_velocity(accel_t, TARGET_JERK, self.a_ego, self.v_ego) + + max_d = 0 + if tv > min_accel_v: + # calculate time needed based on target jerk + a = 0.5 * TARGET_JERK + b = self.a_ego + c = self.v_ego - tv + t_a = -1 * ((b**2 - 4 * a * c) ** 0.5 + b) / 2 * a + t_b = ((b**2 - 4 * a * c) ** 0.5 - b) / 2 * a + if not isinstance(t_a, complex) and t_a > 0: + t = t_a + else: + t = t_b + if isinstance(t, complex): + continue + + max_d = max_d + calculate_distance(t, TARGET_JERK, self.a_ego, self.v_ego) + else: + t = accel_t + max_d = calculate_distance(t, TARGET_JERK, self.a_ego, self.v_ego) + + # calculate additional time needed based on target accel + t = abs((min_accel_v - tv) / TARGET_ACCEL) + max_d += calculate_distance(t, 0, TARGET_ACCEL, min_accel_v) + + if d < max_d + tv * TARGET_OFFSET: + valid_velocities.append((float(tv), tlat, tlon)) + + # Find the smallest velocity we need to adjust for + min_v = 100.0 + target_lat = 0.0 + target_lon = 0.0 + for tv, lat, lon in valid_velocities: + if tv < min_v: + min_v = tv + target_lat = lat + target_lon = lon + + if self.v_target < min_v and not (self.target_lat == 0 and self.target_lon == 0): + for i in range(len(forward_points)): + target_velocity = forward_points[i] + tlat = target_velocity["latitude"] + tlon = target_velocity["longitude"] + tv = target_velocity["velocity"] + if tv > self.v_ego: + continue + + if tlat == self.target_lat and tlon == self.target_lon and tv == self.v_target: + return + + # not found so let's reset + self.v_target = 0.0 + self.target_lat = 0.0 + self.target_lon = 0.0 + + self.v_target = min_v + self.target_lat = target_lat + self.target_lon = target_lon + + def _update_state_machine(self) -> tuple[bool, bool]: + # ENABLED, TURNING + if self.state != MapState.disabled: + if not self.long_enabled or not self.enabled: + self.state = MapState.disabled + elif self.long_override: + self.state = MapState.overriding + + else: + # ENABLED + if self.state == MapState.enabled: + if self.v_cruise > self.v_target != 0: + self.state = MapState.turning + + # TURNING + elif self.state == MapState.turning: + if self.v_cruise <= self.v_target or self.v_target == 0: + self.state = MapState.enabled + + # OVERRIDING + elif self.state == MapState.overriding: + if not self.long_override: + if self.v_cruise > self.v_target != 0: + self.state = MapState.turning + else: + self.state = MapState.enabled + + # DISABLED + elif self.state == MapState.disabled: + if self.long_enabled and self.enabled: + if self.long_override: + self.state = MapState.overriding + else: + self.state = MapState.enabled + + enabled = self.state in ENABLED_STATES + active = self.state in ACTIVE_STATES + + return enabled, active + + def update(self, long_enabled: bool, long_override: bool, v_ego, a_ego, v_cruise) -> None: + self.long_enabled = long_enabled + self.long_override = long_override + self.v_ego = v_ego + self.a_ego = a_ego + self.v_cruise = v_cruise + + self.update_params() + self.update_calculations() + + self.is_enabled, self.is_active = self._update_state_machine() + + self.output_v_target = self.get_v_target_from_control() + self.output_a_target = self.get_a_target_from_control() + + self.frame += 1 diff --git a/openpilot/sunnypilot/selfdrive/controls/lib/smart_cruise_control/smart_cruise_control.py b/openpilot/sunnypilot/selfdrive/controls/lib/smart_cruise_control/smart_cruise_control.py new file mode 100644 index 0000000000..ff6c706634 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/controls/lib/smart_cruise_control/smart_cruise_control.py @@ -0,0 +1,19 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import openpilot.cereal.messaging as messaging +from openpilot.sunnypilot.selfdrive.controls.lib.smart_cruise_control.vision_controller import SmartCruiseControlVision +from openpilot.sunnypilot.selfdrive.controls.lib.smart_cruise_control.map_controller import SmartCruiseControlMap + + +class SmartCruiseControl: + def __init__(self): + self.vision = SmartCruiseControlVision() + self.map = SmartCruiseControlMap() + + def update(self, sm: messaging.SubMaster, long_enabled: bool, long_override: bool, v_ego: float, a_ego: float, v_cruise: float) -> None: + self.map.update(long_enabled, long_override, v_ego, a_ego, v_cruise) + self.vision.update(sm, long_enabled, long_override, v_ego, a_ego, v_cruise) diff --git a/openpilot/sunnypilot/selfdrive/controls/lib/smart_cruise_control/tests/test_map_controller.py b/openpilot/sunnypilot/selfdrive/controls/lib/smart_cruise_control/tests/test_map_controller.py new file mode 100644 index 0000000000..3b16c59bb5 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/controls/lib/smart_cruise_control/tests/test_map_controller.py @@ -0,0 +1,58 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import platform + +from openpilot.cereal import custom +from openpilot.common.params import Params +from openpilot.common.realtime import DT_MDL +from openpilot.selfdrive.car.cruise import V_CRUISE_UNSET +from openpilot.sunnypilot.selfdrive.controls.lib.smart_cruise_control.map_controller import SmartCruiseControlMap + +MapState = VisionState = custom.LongitudinalPlanSP.SmartCruiseControl.MapState + + +class TestSmartCruiseControlMap: + + def setup_method(self): + self.params = Params() + self.mem_params = Params("/dev/shm/params") if platform.system() != "Darwin" else self.params + self.reset_params() + self.scc_m = SmartCruiseControlMap() + + def reset_params(self): + self.params.put_bool("SmartCruiseControlMap", True, block=True) + + # TODO-SP: mock data from gpsLocation + self.params.put("LastGPSPosition", "{}", block=True) + self.params.put("MapTargetVelocities", "{}", block=True) + + def test_initial_state(self): + assert self.scc_m.state == VisionState.disabled + assert not self.scc_m.is_active + assert self.scc_m.output_v_target == V_CRUISE_UNSET + assert self.scc_m.output_a_target == 0. + + def test_system_disabled(self): + self.params.put_bool("SmartCruiseControlMap", False, block=True) + self.scc_m.enabled = self.params.get_bool("SmartCruiseControlMap") + + for _ in range(int(10. / DT_MDL)): + self.scc_m.update(True, False, 0., 0., 0.) + assert self.scc_m.state == VisionState.disabled + assert not self.scc_m.is_active + + def test_disabled(self): + for _ in range(int(10. / DT_MDL)): + self.scc_m.update(False, False, 0., 0., 0.) + assert self.scc_m.state == VisionState.disabled + + def test_transition_disabled_to_enabled(self): + for _ in range(int(10. / DT_MDL)): + self.scc_m.update(True, False, 0., 0., 0.) + assert self.scc_m.state == VisionState.enabled + + # TODO-SP: mock data from modelV2 to test other states diff --git a/openpilot/sunnypilot/selfdrive/controls/lib/smart_cruise_control/tests/test_vision_controller.py b/openpilot/sunnypilot/selfdrive/controls/lib/smart_cruise_control/tests/test_vision_controller.py new file mode 100644 index 0000000000..98b3ffc8e7 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/controls/lib/smart_cruise_control/tests/test_vision_controller.py @@ -0,0 +1,216 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from typing import Any + +import numpy as np +import pytest + +import openpilot.cereal.messaging as messaging +from openpilot.cereal import custom, log +from openpilot.common.params import Params +from openpilot.common.realtime import DT_MDL +from openpilot.selfdrive.car.cruise import V_CRUISE_UNSET +from openpilot.selfdrive.modeld.constants import ModelConstants +from openpilot.sunnypilot.selfdrive.controls.lib.smart_cruise_control import MIN_V +from openpilot.sunnypilot.selfdrive.controls.lib.smart_cruise_control.vision_controller import SmartCruiseControlVision, _ENTERING_PRED_LAT_ACC_TH + +VisionState = custom.LongitudinalPlanSP.SmartCruiseControl.VisionState + + +def _th_above_f32(th: float) -> float: + """ + Return the next representable float32 *above* `th`. + This avoids flaky comparisons around thresholds due to float32 rounding. + """ + th32 = np.float32(th) + above32 = np.nextafter(th32, np.float32(np.inf), dtype=np.float32) + return float(above32) + + +def _build_single_spike_filtered(n: int, base: float = 1.0) -> np.ndarray: + """ + Create an array where max() is >= threshold but p97 is < threshold. + This demonstrates the behavior difference vs np.amax(). + + Note: We intentionally construct using float32-representable values to match + the data path through cereal/capnp. + """ + th = float(_ENTERING_PRED_LAT_ACC_TH) + th32 = float(np.float32(th)) + + # numpy percentile default is linear interpolation: idx=(n-1)*p/100 + idx = (n - 1) * 0.97 + w = float(idx - np.floor(idx)) + + base32 = float(np.float32(base)) + + # Choose spike so that p97 = base + w*(spike-base) < th + # -> spike < base + (th-base)/w. Use a margin (0.9) and ensure spike >= th. + if w == 0.0: + spike = th32 + 1.0 + else: + spike = base32 + (th32 - base32) / w * 0.9 + spike = max(spike, th32 + 0.01) + + arr = np.full(n, base32, dtype=np.float32) + arr[-1] = np.float32(spike) + return arr + + +def generate_modelV2(): + model = messaging.new_message('modelV2') + position = log.XYZTData.new_message() + speed = 30 + position.x = [float(x) for x in (speed + 0.5) * np.array(ModelConstants.T_IDXS)] + model.modelV2.position = position + orientation = log.XYZTData.new_message() + curvature = 0.05 + orientation.x = [float(curvature) for _ in ModelConstants.T_IDXS] + orientation.y = [0.0 for _ in ModelConstants.T_IDXS] + model.modelV2.orientation = orientation + orientationRate = log.XYZTData.new_message() + orientationRate.z = [float(z) for z in ModelConstants.T_IDXS] + model.modelV2.orientationRate = orientationRate + velocity = log.XYZTData.new_message() + velocity.x = [float(x) for x in (speed + 0.5) * np.ones_like(ModelConstants.T_IDXS)] + velocity.x[0] = float(speed) # always start at current speed + model.modelV2.velocity = velocity + acceleration = log.XYZTData.new_message() + acceleration.x = [float(x) for x in np.zeros_like(ModelConstants.T_IDXS)] + acceleration.y = [float(y) for y in np.zeros_like(ModelConstants.T_IDXS)] + model.modelV2.acceleration = acceleration + + return model + + +def generate_carState(): + car_state = messaging.new_message('carState') + speed = 30 + v_cruise = 50 + car_state.carState.vEgo = float(speed) + car_state.carState.standstill = False + car_state.carState.vCruise = float(v_cruise * 3.6) + + return car_state + + +def generate_controlsState(): + controls_state = messaging.new_message('controlsState') + controls_state.controlsState.curvature = 0.05 + + return controls_state + + +class TestSmartCruiseControlVision: + + def setup_method(self): + self.params = Params() + self.reset_params() + self.scc_v = SmartCruiseControlVision() + + mdl = generate_modelV2() + cs = generate_carState() + controls_state = generate_controlsState() + self.sm: Any = {'modelV2': mdl.modelV2, 'carState': cs.carState, 'controlsState': controls_state.controlsState} + + def reset_params(self): + self.params.put_bool("SmartCruiseControlVision", True, block=True) + + def test_initial_state(self): + assert self.scc_v.state == VisionState.disabled + assert not self.scc_v.is_active + assert self.scc_v.output_v_target == V_CRUISE_UNSET + assert self.scc_v.output_a_target == 0. + + def test_system_disabled(self): + self.params.put_bool("SmartCruiseControlVision", False, block=True) + self.scc_v.enabled = self.params.get_bool("SmartCruiseControlVision") + + for _ in range(int(10. / DT_MDL)): + self.scc_v.update(self.sm, True, False, 0., 0., 0.) + assert self.scc_v.state == VisionState.disabled + assert not self.scc_v.is_active + + def test_disabled(self): + for _ in range(int(10. / DT_MDL)): + self.scc_v.update(self.sm, False, False, 0., 0., 0.) + assert self.scc_v.state == VisionState.disabled + + def test_transition_disabled_to_enabled(self): + for _ in range(int(10. / DT_MDL)): + self.scc_v.update(self.sm, True, False, 0., 0., 0.) + assert self.scc_v.state == VisionState.enabled + + @pytest.mark.parametrize( + "case, should_enter", + [ + ("p97_just_above_threshold", True), + ("single_spike_filtered", False), + ("persistent_high_values", True), + ], + ids=[ + "p97>threshold_enters", + "single_spike_max_large_but_p97_below_threshold", + "high_values_persist_trigger_entering", + ], + ) + def test_max_pred_lat_acc_uses_p97_and_threshold(self, case, should_enter): + n = len(ModelConstants.T_IDXS) + th = float(_ENTERING_PRED_LAT_ACC_TH) + + if case == "p97_just_above_threshold": + # Use the next representable float32 above threshold to avoid float32 rounding flakiness. + val = _th_above_f32(th) + pred_lat_accels = np.full(n, np.float32(val), dtype=np.float32) + + elif case == "single_spike_filtered": + pred_lat_accels = _build_single_spike_filtered(n, base=1.0) + + elif case == "persistent_high_values": + # Make enough "high" samples so p97 is driven by the persistent trend, not a single outlier. + high_count = max(2, int(np.ceil(n * 0.03)) + 1) + pred_lat_accels = np.full(n, np.float32(1.0), dtype=np.float32) + pred_lat_accels[-high_count:] = np.float32(2.0) + pred_lat_accels[-1] = np.float32(8.0) # keep one big outlier too + + else: + raise AssertionError(f"Unknown case: {case}") + + # Override model predictions so: + # predicted_lat_accels = abs(orientationRate.z) * velocity.x == pred_lat_accels + mdl = generate_modelV2() + mdl.modelV2.velocity.x = [1.0 for _ in range(n)] + mdl.modelV2.orientationRate.z = [float(x) for x in pred_lat_accels] + self.sm["modelV2"] = mdl.modelV2 + + v_ego = float(MIN_V + 5.0) + + # 1st update: disabled -> enabled + self.scc_v.update(self.sm, True, False, v_ego, 0.0, 0.0) + # 2nd update: evaluate entering condition from enabled state + self.scc_v.update(self.sm, True, False, v_ego, 0.0, 0.0) + + # Controller does percentile on numpy float64 arrays (values already quantized by capnp), + # so compute expected in float64 to match behavior and avoid interpolation/rounding deltas. + expected_p97 = float(np.percentile(pred_lat_accels.astype(np.float64), 97)) + + # allow tiny numeric differences due to float conversions/interpolation + assert np.isclose(self.scc_v.max_pred_lat_acc, expected_p97, rtol=1e-6, atol=1e-5) + + if should_enter: + # We assert entering primarily by state (this is the actual intended behavior). + assert self.scc_v.state == VisionState.entering + # Optional sanity: should be >= threshold with some margin (since we used nextafter above threshold). + assert self.scc_v.max_pred_lat_acc > th + + else: + # Difference vs np.amax(): max can be above threshold, but p97 stays below it. + assert float(np.max(pred_lat_accels)) >= th + assert self.scc_v.max_pred_lat_acc < th + assert self.scc_v.state == VisionState.enabled + + # TODO-SP: mock modelV2 data to test other states diff --git a/openpilot/sunnypilot/selfdrive/controls/lib/smart_cruise_control/vision_controller.py b/openpilot/sunnypilot/selfdrive/controls/lib/smart_cruise_control/vision_controller.py new file mode 100644 index 0000000000..fb76f5b546 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/controls/lib/smart_cruise_control/vision_controller.py @@ -0,0 +1,203 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import numpy as np + +import openpilot.cereal.messaging as messaging +from openpilot.cereal import custom +from openpilot.common.params import Params +from openpilot.common.realtime import DT_MDL +from openpilot.selfdrive.car.cruise import V_CRUISE_UNSET +from openpilot.sunnypilot import PARAMS_UPDATE_PERIOD +from openpilot.sunnypilot.selfdrive.controls.lib.smart_cruise_control import MIN_V + +VisionState = custom.LongitudinalPlanSP.SmartCruiseControl.VisionState + +ACTIVE_STATES = (VisionState.entering, VisionState.turning, VisionState.leaving) +ENABLED_STATES = (VisionState.enabled, VisionState.overriding, *ACTIVE_STATES) + +_ENTERING_PRED_LAT_ACC_TH = 1.3 # Predicted Lat Acc threshold to trigger entering turn state. +_ABORT_ENTERING_PRED_LAT_ACC_TH = 1.1 # Predicted Lat Acc threshold to abort entering state if speed drops. + +_TURNING_LAT_ACC_TH = 1.6 # Lat Acc threshold to trigger turning state. + +_LEAVING_LAT_ACC_TH = 1.3 # Lat Acc threshold to trigger leaving turn state. +_FINISH_LAT_ACC_TH = 1.1 # Lat Acc threshold to trigger the end of the turn cycle. + +_A_LAT_REG_MAX = 2. # Maximum lateral acceleration + +_NO_OVERSHOOT_TIME_HORIZON = 4. # s. Time to use for velocity desired based on a_target when not overshooting. + +# Lookup table for the minimum smooth deceleration during the ENTERING state +# depending on the actual maximum absolute lateral acceleration predicted on the turn ahead. +_ENTERING_SMOOTH_DECEL_V = [-0.2, -1.] # min decel value allowed on ENTERING state +_ENTERING_SMOOTH_DECEL_BP = [1.3, 3.] # absolute value of lat acc ahead + +# Lookup table for the acceleration for the TURNING state +# depending on the current lateral acceleration of the vehicle. +_TURNING_ACC_V = [0.5, 0., -0.4] # acc value +_TURNING_ACC_BP = [1.5, 2.3, 3.] # absolute value of current lat acc + +_LEAVING_ACC = 0.5 # Conformable acceleration to regain speed while leaving a turn. + + +class SmartCruiseControlVision: + v_target: float = 0 + a_target: float = 0. + v_ego: float = 0. + a_ego: float = 0. + output_v_target: float = V_CRUISE_UNSET + output_a_target: float = 0. + + def __init__(self): + self.params = Params() + self.frame = -1 + self.long_enabled = False + self.long_override = False + self.is_enabled = False + self.is_active = False + self.enabled = self.params.get_bool("SmartCruiseControlVision") + self.v_cruise_setpoint = 0. + + self.state = VisionState.disabled + self.current_lat_acc = 0. + self.max_pred_lat_acc = 0. + + def get_a_target_from_control(self) -> float: + return self.a_target + + def get_v_target_from_control(self) -> float: + if self.is_active: + return max(self.v_target, MIN_V) + self.a_target * _NO_OVERSHOOT_TIME_HORIZON + + return V_CRUISE_UNSET + + def _update_params(self) -> None: + if self.frame % int(PARAMS_UPDATE_PERIOD / DT_MDL) == 0: + self.enabled = self.params.get_bool("SmartCruiseControlVision") + + def _update_calculations(self, sm: messaging.SubMaster) -> None: + if not self.long_enabled: + return + else: + rate_plan = np.array(np.abs(sm['modelV2'].orientationRate.z)) + vel_plan = np.array(sm['modelV2'].velocity.x) + + self.current_lat_acc = self.v_ego ** 2 * abs(sm['controlsState'].curvature) + + # get the maximum lat accel from the model + predicted_lat_accels = rate_plan * vel_plan + self.max_pred_lat_acc = np.percentile(predicted_lat_accels, 97) + + # get the maximum curve based on the current velocity + v_ego = max(self.v_ego, 0.1) # ensure a value greater than 0 for calculations + max_curve = self.max_pred_lat_acc / (v_ego**2) + + # Get the target velocity for the maximum curve + self.v_target = (_A_LAT_REG_MAX / max_curve) ** 0.5 + + def _update_state_machine(self) -> tuple[bool, bool]: + # ENABLED, ENTERING, TURNING, LEAVING, OVERRIDING + if self.state != VisionState.disabled: + # longitudinal and feature disable always have priority in a non-disabled state + if not self.long_enabled or not self.enabled: + self.state = VisionState.disabled + elif self.long_override: + self.state = VisionState.overriding + + else: + # ENABLED + if self.state == VisionState.enabled: + # Do not enter a turn control cycle if the speed is low. + if self.v_ego <= MIN_V: + pass + # If significant lateral acceleration is predicted ahead, then move to Entering turn state. + elif self.max_pred_lat_acc >= _ENTERING_PRED_LAT_ACC_TH: + self.state = VisionState.entering + + # OVERRIDING + elif self.state == VisionState.overriding: + if not self.long_override: + self.state = VisionState.enabled + + # ENTERING + elif self.state == VisionState.entering: + # Transition to Turning if current lateral acceleration is over the threshold. + if self.current_lat_acc >= _TURNING_LAT_ACC_TH: + self.state = VisionState.turning + # Abort if the predicted lateral acceleration drops + elif self.max_pred_lat_acc < _ABORT_ENTERING_PRED_LAT_ACC_TH: + self.state = VisionState.enabled + + # TURNING + elif self.state == VisionState.turning: + # Transition to Leaving if current lateral acceleration drops below a threshold. + if self.current_lat_acc <= _LEAVING_LAT_ACC_TH: + self.state = VisionState.leaving + + # LEAVING + elif self.state == VisionState.leaving: + # Transition back to Turning if current lateral acceleration goes back over the threshold. + if self.current_lat_acc >= _TURNING_LAT_ACC_TH: + self.state = VisionState.turning + # Finish if current lateral acceleration goes below a threshold. + elif self.current_lat_acc < _FINISH_LAT_ACC_TH: + self.state = VisionState.enabled + + # DISABLED + elif self.state == VisionState.disabled: + if self.long_enabled and self.enabled: + if self.long_override: + self.state = VisionState.overriding + else: + self.state = VisionState.enabled + + enabled = self.state in ENABLED_STATES + active = self.state in ACTIVE_STATES + + return enabled, active + + def _update_solution(self) -> float: + # DISABLED, ENABLED, OVERRIDING + if self.state not in ACTIVE_STATES: + # when not overshooting, calculate v_turn as the speed at the prediction horizon when following + # the smooth deceleration. + a_target = self.a_ego + # ENTERING + elif self.state == VisionState.entering: + # when not overshooting, target a smooth deceleration in preparation for a sharp turn to come. + a_target = np.interp(self.max_pred_lat_acc, _ENTERING_SMOOTH_DECEL_BP, _ENTERING_SMOOTH_DECEL_V) + # TURNING + elif self.state == VisionState.turning: + # When turning, we provide a target acceleration that is comfortable for the lateral acceleration felt. + a_target = np.interp(self.current_lat_acc, _TURNING_ACC_BP, _TURNING_ACC_V) + # LEAVING + elif self.state == VisionState.leaving: + # When leaving, we provide a comfortable acceleration to regain speed. + a_target = _LEAVING_ACC + else: + raise NotImplementedError(f"SCC-V state not supported: {self.state}") + + return a_target + + def update(self, sm: messaging.SubMaster, long_enabled: bool, long_override: bool, v_ego: float, a_ego: float, + v_cruise_setpoint: float) -> None: + self.long_enabled = long_enabled + self.long_override = long_override + self.v_ego = v_ego + self.a_ego = a_ego + self.v_cruise_setpoint = v_cruise_setpoint + + self._update_params() + self._update_calculations(sm) + + self.is_enabled, self.is_active = self._update_state_machine() + self.a_target = self._update_solution() + + self.output_v_target = self.get_v_target_from_control() + self.output_a_target = self.get_a_target_from_control() + + self.frame += 1 diff --git a/openpilot/sunnypilot/selfdrive/controls/lib/speed_limit/__init__.py b/openpilot/sunnypilot/selfdrive/controls/lib/speed_limit/__init__.py new file mode 100644 index 0000000000..22ea75fe19 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/controls/lib/speed_limit/__init__.py @@ -0,0 +1,19 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +LIMIT_ADAPT_ACC = -1. # m/s^2 Ideal acceleration for the adapting (braking) phase when approaching speed limits. +LIMIT_MAX_MAP_DATA_AGE = 10. # s Maximum time to hold to map data, then consider it invalid inside limits controllers. + +# Speed Limit Assist constants +PCM_LONG_REQUIRED_MAX_SET_SPEED = { + True: (33.3333, 36.1111), # km/h, (120, 130) + False: (31.2928, 35.7632), # mph, (70, 80) +} + +CONFIRM_SPEED_THRESHOLD = { + True: 80, # km/h + False: 50, # mph +} diff --git a/openpilot/sunnypilot/selfdrive/controls/lib/speed_limit/common.py b/openpilot/sunnypilot/selfdrive/controls/lib/speed_limit/common.py new file mode 100644 index 0000000000..c46768464e --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/controls/lib/speed_limit/common.py @@ -0,0 +1,29 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" + +from openpilot.sunnypilot import IntEnumBase + + +class Policy(IntEnumBase): + car_state_only = 0 + map_data_only = 1 + car_state_priority = 2 + map_data_priority = 3 + combined = 4 + + +class OffsetType(IntEnumBase): + off = 0 + fixed = 1 + percentage = 2 + + +class Mode(IntEnumBase): + off = 0 + information = 1 + warning = 2 + assist = 3 diff --git a/openpilot/sunnypilot/selfdrive/controls/lib/speed_limit/helpers.py b/openpilot/sunnypilot/selfdrive/controls/lib/speed_limit/helpers.py new file mode 100644 index 0000000000..77d89251e2 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/controls/lib/speed_limit/helpers.py @@ -0,0 +1,45 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" + +from openpilot.cereal import custom +from opendbc.car.structs import car +from openpilot.common.constants import CV +from openpilot.common.params import Params +from openpilot.sunnypilot.selfdrive.controls.lib.speed_limit.common import Mode as SpeedLimitMode + + +def compare_cluster_target(v_cruise_cluster: float, target_set_speed: float, is_metric: bool) -> tuple[bool, bool]: + speed_conv = CV.MS_TO_KPH if is_metric else CV.MS_TO_MPH + v_cruise_cluster_conv = round(v_cruise_cluster * speed_conv) + target_set_speed_conv = round(target_set_speed * speed_conv) + + req_plus = v_cruise_cluster_conv < target_set_speed_conv + req_minus = v_cruise_cluster_conv > target_set_speed_conv + + return req_plus, req_minus + + +def set_speed_limit_assist_availability(CP: car.CarParams, CP_SP: custom.CarParamsSP, params: Params = None) -> bool: + if params is None: + params = Params() + + is_release = params.get_bool("IsReleaseSpBranch") + disallow_in_release = CP.brand == "tesla" and is_release + always_disallow = CP.brand == "rivian" + allowed = True + + if disallow_in_release or always_disallow: + allowed = False + + if not CP.openpilotLongitudinalControl and CP_SP.pcmCruiseSpeed: + allowed = False + + if not allowed: + if params.get("SpeedLimitMode", return_default=True) == SpeedLimitMode.assist: + params.put("SpeedLimitMode", int(SpeedLimitMode.warning), block=True) + + return allowed diff --git a/openpilot/sunnypilot/selfdrive/controls/lib/speed_limit/speed_limit_assist.py b/openpilot/sunnypilot/selfdrive/controls/lib/speed_limit/speed_limit_assist.py new file mode 100644 index 0000000000..1ff541167f --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/controls/lib/speed_limit/speed_limit_assist.py @@ -0,0 +1,415 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import time + +from openpilot.cereal import custom +from opendbc.car.structs import car +from openpilot.common.params import Params +from openpilot.common.constants import CV +from openpilot.common.realtime import DT_MDL +from openpilot.selfdrive.controls.lib.drive_helpers import CONTROL_N +from openpilot.selfdrive.modeld.constants import ModelConstants +from openpilot.sunnypilot import PARAMS_UPDATE_PERIOD +from openpilot.sunnypilot.selfdrive.selfdrived.events import EventsSP +from openpilot.sunnypilot.selfdrive.controls.lib.speed_limit import PCM_LONG_REQUIRED_MAX_SET_SPEED, CONFIRM_SPEED_THRESHOLD +from openpilot.sunnypilot.selfdrive.controls.lib.speed_limit.common import Mode +from openpilot.sunnypilot.selfdrive.controls.lib.speed_limit.helpers import compare_cluster_target, set_speed_limit_assist_availability + +ButtonType = car.CarState.ButtonEvent.Type +EventNameSP = custom.OnroadEventSP.EventName +SpeedLimitAssistState = custom.LongitudinalPlanSP.SpeedLimit.AssistState +SpeedLimitSource = custom.LongitudinalPlanSP.SpeedLimit.Source + +ACTIVE_STATES = (SpeedLimitAssistState.active, SpeedLimitAssistState.adapting) +ENABLED_STATES = (SpeedLimitAssistState.preActive, SpeedLimitAssistState.pending, *ACTIVE_STATES) + +DISABLED_GUARD_PERIOD = 0.5 # secs. +# secs. Time to wait after activation before considering temp deactivation signal. +PRE_ACTIVE_GUARD_PERIOD = { + True: 15, + False: 5, +} +SPEED_LIMIT_CHANGED_HOLD_PERIOD = 1 # secs. Time to wait after speed limit change before switching to preActive. + +LIMIT_MIN_ACC = -1.5 # m/s^2 Maximum deceleration allowed for limit controllers to provide. +LIMIT_MAX_ACC = 1.0 # m/s^2 Maximum acceleration allowed for limit controllers to provide while active. +LIMIT_MIN_SPEED = 8.33 # m/s, Minimum speed limit to provide as solution on limit controllers. +LIMIT_SPEED_OFFSET_TH = -1. # m/s Maximum offset between speed limit and current speed for adapting state. +V_CRUISE_UNSET = 255. + +CRUISE_BUTTONS_PLUS = (ButtonType.accelCruise, ButtonType.resumeCruise) +CRUISE_BUTTONS_MINUS = (ButtonType.decelCruise, ButtonType.setCruise) +CRUISE_BUTTON_CONFIRM_HOLD = 0.5 # secs. + + +class SpeedLimitAssist: + _speed_limit_final_last: float + _distance: float + v_ego: float + a_ego: float + v_offset: float + + def __init__(self, CP: car.CarParams, CP_SP: custom.CarParamsSP): + self.params = Params() + self.CP = CP + self.CP_SP = CP_SP + self.frame = -1 + self.long_engaged_timer = 0 + self.pre_active_timer = 0 + self.is_metric = self.params.get_bool("IsMetric") + set_speed_limit_assist_availability(self.CP, self.CP_SP, self.params) + self.enabled = self.params.get("SpeedLimitMode", return_default=True) == Mode.assist + self.long_enabled = False + self.long_enabled_prev = False + self.is_enabled = False + self.is_active = False + self.output_v_target = V_CRUISE_UNSET + self.output_a_target = 0. + self.v_ego = 0. + self.a_ego = 0. + self.v_offset = 0. + self.target_set_speed_conv = 0 + self.prev_target_set_speed_conv = 0 + self.v_cruise_cluster = 0. + self.v_cruise_cluster_prev = 0. + self.v_cruise_cluster_conv = 0 + self.prev_v_cruise_cluster_conv = 0 + self._has_speed_limit = False + self._speed_limit = 0. + self._speed_limit_final_last = 0. + self.speed_limit_prev = 0. + self.speed_limit_final_last_conv = 0 + self.prev_speed_limit_final_last_conv = 0 + self._distance = 0. + self.state = SpeedLimitAssistState.disabled + self._state_prev = SpeedLimitAssistState.disabled + self.pcm_op_long = CP.openpilotLongitudinalControl and CP.pcmCruise + + self._plus_hold = 0. + self._minus_hold = 0. + self._last_carstate_ts = 0. + + # TODO-SP: SLA's own output_a_target for planner + # Solution functions mapped to respective states + self.acceleration_solutions = { + SpeedLimitAssistState.disabled: self.get_current_acceleration_as_target, + SpeedLimitAssistState.inactive: self.get_current_acceleration_as_target, + SpeedLimitAssistState.preActive: self.get_current_acceleration_as_target, + SpeedLimitAssistState.pending: self.get_current_acceleration_as_target, + SpeedLimitAssistState.adapting: self.get_adapting_state_target_acceleration, + SpeedLimitAssistState.active: self.get_active_state_target_acceleration, + } + + @property + def speed_limit_changed(self) -> bool: + return self._has_speed_limit and bool(self._speed_limit != self.speed_limit_prev) + + @property + def v_cruise_cluster_changed(self) -> bool: + return bool(self.v_cruise_cluster_conv != self.prev_v_cruise_cluster_conv) + + @property + def target_set_speed_confirmed(self) -> bool: + return bool(self.v_cruise_cluster_conv == self.target_set_speed_conv) + + @property + def v_cruise_cluster_below_confirm_speed_threshold(self) -> bool: + return bool(self.v_cruise_cluster_conv < CONFIRM_SPEED_THRESHOLD[self.is_metric]) + + def update_active_event(self, events_sp: EventsSP) -> None: + if self.v_cruise_cluster_below_confirm_speed_threshold: + events_sp.add(EventNameSP.speedLimitChanged) + else: + events_sp.add(EventNameSP.speedLimitActive) + + def get_v_target_from_control(self) -> float: + if self._has_speed_limit: + if self.pcm_op_long and self.is_enabled: + return self._speed_limit_final_last + if not self.pcm_op_long and self.is_active: + return self._speed_limit_final_last + + # Fallback + return V_CRUISE_UNSET + + # TODO-SP: SLA's own output_a_target for planner + def get_a_target_from_control(self) -> float: + return self.a_ego + + def update_params(self) -> None: + if self.frame % int(PARAMS_UPDATE_PERIOD / DT_MDL) == 0: + self.is_metric = self.params.get_bool("IsMetric") + set_speed_limit_assist_availability(self.CP, self.CP_SP, self.params) + self.enabled = self.params.get("SpeedLimitMode", return_default=True) == Mode.assist + + def update_car_state(self, CS: car.CarState) -> None: + now = time.monotonic() + self._last_carstate_ts = now + + for b in CS.buttonEvents: + if not b.pressed: + if b.type in CRUISE_BUTTONS_PLUS: + self._plus_hold = max(self._plus_hold, now + CRUISE_BUTTON_CONFIRM_HOLD) + elif b.type in CRUISE_BUTTONS_MINUS: + self._minus_hold = max(self._minus_hold, now + CRUISE_BUTTON_CONFIRM_HOLD) + + def _get_button_release(self, req_plus: bool, req_minus: bool) -> bool: + now = time.monotonic() + if req_plus and now <= self._plus_hold: + self._plus_hold = 0. + return True + elif req_minus and now <= self._minus_hold: + self._minus_hold = 0. + return True + + # expired + if now > self._plus_hold: + self._plus_hold = 0. + if now > self._minus_hold: + self._minus_hold = 0. + return False + + def update_calculations(self, v_cruise_cluster: float) -> None: + speed_conv = CV.MS_TO_KPH if self.is_metric else CV.MS_TO_MPH + self.v_cruise_cluster = v_cruise_cluster + + # Update current velocity offset (error) + self.v_offset = self._speed_limit_final_last - self.v_ego + + self.speed_limit_final_last_conv = round(self._speed_limit_final_last * speed_conv) + self.v_cruise_cluster_conv = round(self.v_cruise_cluster * speed_conv) + + cst_low, cst_high = PCM_LONG_REQUIRED_MAX_SET_SPEED[self.is_metric] + pcm_long_required_max = cst_low if self._has_speed_limit and self.speed_limit_final_last_conv < CONFIRM_SPEED_THRESHOLD[self.is_metric] else \ + cst_high + pcm_long_required_max_set_speed_conv = round(pcm_long_required_max * speed_conv) + + self.target_set_speed_conv = pcm_long_required_max_set_speed_conv if self.pcm_op_long else self.speed_limit_final_last_conv + + @property + def apply_confirm_speed_threshold(self) -> bool: + # below CST: always require user confirmation + if self.v_cruise_cluster_below_confirm_speed_threshold: + return True + + # at/above CST: + # - new speed limit >= CST: auto change + # - new speed limit < CST: user confirmation required + return bool(self.speed_limit_final_last_conv < CONFIRM_SPEED_THRESHOLD[self.is_metric]) + + def get_current_acceleration_as_target(self) -> float: + return self.a_ego + + def get_adapting_state_target_acceleration(self) -> float: + if self._distance > 0: + return (self._speed_limit_final_last ** 2 - self.v_ego ** 2) / (2. * self._distance) + + return self.v_offset / float(ModelConstants.T_IDXS[CONTROL_N]) + + def get_active_state_target_acceleration(self) -> float: + return self.v_offset / float(ModelConstants.T_IDXS[CONTROL_N]) + + def _update_confirmed_state(self): + if self._has_speed_limit: + if self.v_offset < LIMIT_SPEED_OFFSET_TH: + self.state = SpeedLimitAssistState.adapting + else: + self.state = SpeedLimitAssistState.active + else: + self.state = SpeedLimitAssistState.pending + + def _update_non_pcm_long_confirmed_state(self) -> bool: + if self.target_set_speed_confirmed: + return True + + if self.state != SpeedLimitAssistState.preActive: + return False + + req_plus, req_minus = compare_cluster_target(self.v_cruise_cluster, self._speed_limit_final_last, self.is_metric) + + return self._get_button_release(req_plus, req_minus) + + def update_state_machine_pcm_op_long(self): + self.long_engaged_timer = max(0, self.long_engaged_timer - 1) + self.pre_active_timer = max(0, self.pre_active_timer - 1) + + # ACTIVE, ADAPTING, PENDING, PRE_ACTIVE, INACTIVE + if self.state != SpeedLimitAssistState.disabled: + if not self.long_enabled or not self.enabled: + self.state = SpeedLimitAssistState.disabled + + else: + # ACTIVE + if self.state == SpeedLimitAssistState.active: + if self.v_cruise_cluster_changed: + self.state = SpeedLimitAssistState.inactive + elif self.speed_limit_changed and self.apply_confirm_speed_threshold: + self.state = SpeedLimitAssistState.preActive + self.pre_active_timer = int(PRE_ACTIVE_GUARD_PERIOD[self.pcm_op_long] / DT_MDL) + elif self._has_speed_limit and self.v_offset < LIMIT_SPEED_OFFSET_TH: + self.state = SpeedLimitAssistState.adapting + + # ADAPTING + elif self.state == SpeedLimitAssistState.adapting: + if self.v_cruise_cluster_changed: + self.state = SpeedLimitAssistState.inactive + elif self.speed_limit_changed and self.apply_confirm_speed_threshold: + self.state = SpeedLimitAssistState.preActive + self.pre_active_timer = int(PRE_ACTIVE_GUARD_PERIOD[self.pcm_op_long] / DT_MDL) + elif self.v_offset >= LIMIT_SPEED_OFFSET_TH: + self.state = SpeedLimitAssistState.active + + # PENDING + elif self.state == SpeedLimitAssistState.pending: + if self.target_set_speed_confirmed: + self._update_confirmed_state() + elif self.speed_limit_changed: + self.state = SpeedLimitAssistState.preActive + self.pre_active_timer = int(PRE_ACTIVE_GUARD_PERIOD[self.pcm_op_long] / DT_MDL) + + # PRE_ACTIVE + elif self.state == SpeedLimitAssistState.preActive: + if self.target_set_speed_confirmed: + self._update_confirmed_state() + elif self.pre_active_timer <= 0: + # Timeout - session ended + self.state = SpeedLimitAssistState.inactive + + # INACTIVE + elif self.state == SpeedLimitAssistState.inactive: + pass + + # DISABLED + elif self.state == SpeedLimitAssistState.disabled: + if self.long_enabled and self.enabled: + # start or reset preActive timer if initially enabled or manual set speed change detected + if not self.long_enabled_prev or self.v_cruise_cluster_changed: + self.long_engaged_timer = int(DISABLED_GUARD_PERIOD / DT_MDL) + + elif self.long_engaged_timer <= 0: + if self.target_set_speed_confirmed: + self._update_confirmed_state() + elif self._has_speed_limit: + self.state = SpeedLimitAssistState.preActive + self.pre_active_timer = int(PRE_ACTIVE_GUARD_PERIOD[self.pcm_op_long] / DT_MDL) + else: + self.state = SpeedLimitAssistState.pending + + enabled = self.state in ENABLED_STATES + active = self.state in ACTIVE_STATES + + return enabled, active + + def update_state_machine_non_pcm_long(self): + self.long_engaged_timer = max(0, self.long_engaged_timer - 1) + self.pre_active_timer = max(0, self.pre_active_timer - 1) + + # ACTIVE, ADAPTING, PENDING, PRE_ACTIVE, INACTIVE + if self.state != SpeedLimitAssistState.disabled: + if not self.long_enabled or not self.enabled: + self.state = SpeedLimitAssistState.disabled + + else: + # ACTIVE + if self.state == SpeedLimitAssistState.active: + if self.v_cruise_cluster_changed: + self.state = SpeedLimitAssistState.inactive + + elif self.speed_limit_changed and self.apply_confirm_speed_threshold: + self.state = SpeedLimitAssistState.preActive + self.pre_active_timer = int(PRE_ACTIVE_GUARD_PERIOD[self.pcm_op_long] / DT_MDL) + + # PRE_ACTIVE + elif self.state == SpeedLimitAssistState.preActive: + if self._update_non_pcm_long_confirmed_state(): + self.state = SpeedLimitAssistState.active + elif self.pre_active_timer <= 0: + # Timeout - session ended + self.state = SpeedLimitAssistState.inactive + + # INACTIVE + elif self.state == SpeedLimitAssistState.inactive: + if self.speed_limit_changed: + self.state = SpeedLimitAssistState.preActive + self.pre_active_timer = int(PRE_ACTIVE_GUARD_PERIOD[self.pcm_op_long] / DT_MDL) + elif self._update_non_pcm_long_confirmed_state(): + self.state = SpeedLimitAssistState.active + + # DISABLED + elif self.state == SpeedLimitAssistState.disabled: + if self.long_enabled and self.enabled: + # start or reset preActive timer if initially enabled or manual set speed change detected + if not self.long_enabled_prev or self.v_cruise_cluster_changed: + self.long_engaged_timer = int(DISABLED_GUARD_PERIOD / DT_MDL) + + elif self.long_engaged_timer <= 0: + if self._update_non_pcm_long_confirmed_state(): + self.state = SpeedLimitAssistState.active + elif self._has_speed_limit: + self.state = SpeedLimitAssistState.preActive + self.pre_active_timer = int(PRE_ACTIVE_GUARD_PERIOD[self.pcm_op_long] / DT_MDL) + else: + self.state = SpeedLimitAssistState.inactive + + enabled = self.state in ENABLED_STATES + active = self.state in ACTIVE_STATES + + return enabled, active + + def update_events(self, events_sp: EventsSP) -> None: + if self.state == SpeedLimitAssistState.preActive: + events_sp.add(EventNameSP.speedLimitPreActive) + + if self.state == SpeedLimitAssistState.pending and self._state_prev != SpeedLimitAssistState.pending: + events_sp.add(EventNameSP.speedLimitPending) + + if self.is_active: + if self._state_prev not in ACTIVE_STATES: + self.update_active_event(events_sp) + + # only notify if we acquire a valid speed limit + # do not check has_speed_limit here + elif self._speed_limit != self.speed_limit_prev: + if self.speed_limit_prev <= 0: + self.update_active_event(events_sp) + elif self.speed_limit_prev > 0 and self._speed_limit > 0: + self.update_active_event(events_sp) + + def update(self, long_enabled: bool, long_override: bool, v_ego: float, a_ego: float, v_cruise_cluster: float, speed_limit: float, + speed_limit_final_last: float, has_speed_limit: bool, distance: float, events_sp: EventsSP) -> None: + self.long_enabled = long_enabled + self.v_ego = v_ego + self.a_ego = a_ego + + self._has_speed_limit = has_speed_limit + self._speed_limit = speed_limit + self._speed_limit_final_last = speed_limit_final_last + self._distance = distance + + self.update_params() + self.update_calculations(v_cruise_cluster) + + self._state_prev = self.state + if self.pcm_op_long: + self.is_enabled, self.is_active = self.update_state_machine_pcm_op_long() + else: + self.is_enabled, self.is_active = self.update_state_machine_non_pcm_long() + + self.update_events(events_sp) + + # Update change tracking variables + self.speed_limit_prev = self._speed_limit + self.v_cruise_cluster_prev = self.v_cruise_cluster + self.long_enabled_prev = self.long_enabled + self.prev_target_set_speed_conv = self.target_set_speed_conv + self.prev_v_cruise_cluster_conv = self.v_cruise_cluster_conv + self.prev_speed_limit_final_last_conv = self.speed_limit_final_last_conv + + self.output_v_target = self.get_v_target_from_control() + self.output_a_target = self.get_a_target_from_control() + + self.frame += 1 diff --git a/openpilot/sunnypilot/selfdrive/controls/lib/speed_limit/speed_limit_resolver.py b/openpilot/sunnypilot/selfdrive/controls/lib/speed_limit/speed_limit_resolver.py new file mode 100644 index 0000000000..a226e0d120 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/controls/lib/speed_limit/speed_limit_resolver.py @@ -0,0 +1,190 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import time + +import openpilot.cereal.messaging as messaging +from openpilot.cereal import custom +from openpilot.common.constants import CV +from openpilot.common.gps import get_gps_location_service +from openpilot.common.params import Params +from openpilot.common.realtime import DT_MDL +from openpilot.sunnypilot import PARAMS_UPDATE_PERIOD, get_sanitize_int_param +from openpilot.sunnypilot.selfdrive.controls.lib.speed_limit import LIMIT_MAX_MAP_DATA_AGE, LIMIT_ADAPT_ACC +from openpilot.sunnypilot.selfdrive.controls.lib.speed_limit.common import Policy, OffsetType + +SpeedLimitSource = custom.LongitudinalPlanSP.SpeedLimit.Source + +ALL_SOURCES = tuple(SpeedLimitSource.schema.enumerants.values()) + + +class SpeedLimitResolver: + limit_solutions: dict[custom.LongitudinalPlanSP.SpeedLimit.Source, float] + distance_solutions: dict[custom.LongitudinalPlanSP.SpeedLimit.Source, float] + v_ego: float + speed_limit: float + speed_limit_last: float + speed_limit_final: float + speed_limit_final_last: float + distance: float + source: custom.LongitudinalPlanSP.SpeedLimit.Source + speed_limit_offset: float + + def __init__(self): + self.params = Params() + self.frame = -1 + + self._gps_location_service = get_gps_location_service(self.params) + self.limit_solutions = {} # Store for speed limit solutions from different sources + self.distance_solutions = {} # Store for distance to current speed limit start for different sources + + self.policy = self.params.get("SpeedLimitPolicy", return_default=True) + self.policy = get_sanitize_int_param( + "SpeedLimitPolicy", + Policy.min().value, + Policy.max().value, + self.params + ) + self._policy_to_sources_map = { + Policy.car_state_only: [SpeedLimitSource.car], + Policy.map_data_only: [SpeedLimitSource.map], + Policy.car_state_priority: [SpeedLimitSource.car, SpeedLimitSource.map], + Policy.map_data_priority: [SpeedLimitSource.map, SpeedLimitSource.car], + Policy.combined: [SpeedLimitSource.car, SpeedLimitSource.map], + } + self.source = SpeedLimitSource.none + for source in ALL_SOURCES: + self._reset_limit_sources(source) + + self.is_metric = self.params.get_bool("IsMetric") + self.offset_type = get_sanitize_int_param( + "SpeedLimitOffsetType", + OffsetType.min().value, + OffsetType.max().value, + self.params + ) + self.offset_value = self.params.get("SpeedLimitValueOffset", return_default=True) + + self.speed_limit = 0. + self.speed_limit_last = 0. + self.speed_limit_final = 0. + self.speed_limit_final_last = 0. + self.speed_limit_offset = 0. + + def update_speed_limit_states(self) -> None: + self.speed_limit_final = self.speed_limit + self.speed_limit_offset + + if self.speed_limit > 0.: + self.speed_limit_last = self.speed_limit + self.speed_limit_final_last = self.speed_limit_final + + @property + def speed_limit_valid(self) -> bool: + return self.speed_limit > 0. + + @property + def speed_limit_last_valid(self) -> bool: + return self.speed_limit_last > 0. + + def update_params(self): + if self.frame % int(PARAMS_UPDATE_PERIOD / DT_MDL) == 0: + self.policy = self.params.get("SpeedLimitPolicy", return_default=True) + self.is_metric = self.params.get_bool("IsMetric") + self.offset_type = self.params.get("SpeedLimitOffsetType", return_default=True) + self.offset_value = self.params.get("SpeedLimitValueOffset", return_default=True) + + def _get_speed_limit_offset(self) -> float: + if self.offset_type == OffsetType.off: + return 0 + elif self.offset_type == OffsetType.fixed: + return float(self.offset_value * (CV.KPH_TO_MS if self.is_metric else CV.MPH_TO_MS)) + elif self.offset_type == OffsetType.percentage: + return float(self.offset_value * 0.01 * self.speed_limit) + else: + raise NotImplementedError("Offset not supported") + + def _reset_limit_sources(self, source: custom.LongitudinalPlanSP.SpeedLimit.Source) -> None: + self.limit_solutions[source] = 0. + self.distance_solutions[source] = 0. + + def _get_from_car_state(self, sm: messaging.SubMaster) -> None: + self._reset_limit_sources(SpeedLimitSource.car) + self.limit_solutions[SpeedLimitSource.car] = sm['carStateSP'].speedLimit + self.distance_solutions[SpeedLimitSource.car] = 0. + + def _get_from_map_data(self, sm: messaging.SubMaster) -> None: + self._reset_limit_sources(SpeedLimitSource.map) + self._process_map_data(sm) + + def _process_map_data(self, sm: messaging.SubMaster) -> None: + gps_data = sm[self._gps_location_service] + map_data = sm['liveMapDataSP'] + + gps_fix_age = time.monotonic() - gps_data.unixTimestampMillis * 1e-3 + if gps_fix_age > LIMIT_MAX_MAP_DATA_AGE: + return + + speed_limit = map_data.speedLimit if map_data.speedLimitValid else 0. + next_speed_limit = map_data.speedLimitAhead if map_data.speedLimitAheadValid else 0. + + self._calculate_map_data_limits(sm, speed_limit, next_speed_limit) + + def _calculate_map_data_limits(self, sm: messaging.SubMaster, speed_limit: float, next_speed_limit: float) -> None: + gps_data = sm[self._gps_location_service] + map_data = sm['liveMapDataSP'] + + distance_since_fix = self.v_ego * (time.monotonic() - gps_data.unixTimestampMillis * 1e-3) + distance_to_speed_limit_ahead = max(0., map_data.speedLimitAheadDistance - distance_since_fix) + + self.limit_solutions[SpeedLimitSource.map] = speed_limit + self.distance_solutions[SpeedLimitSource.map] = 0. + + # FIXME-SP: this is not working as expected + if 0. < next_speed_limit < self.v_ego: + adapt_time = (next_speed_limit - self.v_ego) / LIMIT_ADAPT_ACC + adapt_distance = self.v_ego * adapt_time + 0.5 * LIMIT_ADAPT_ACC * adapt_time ** 2 + + if distance_to_speed_limit_ahead <= adapt_distance: + self.limit_solutions[SpeedLimitSource.map] = next_speed_limit + self.distance_solutions[SpeedLimitSource.map] = distance_to_speed_limit_ahead + + def _get_source_solution_according_to_policy(self) -> custom.LongitudinalPlanSP.SpeedLimit.Source: + sources_for_policy = self._policy_to_sources_map[Policy(self.policy)] + + if Policy(self.policy) != Policy.combined: + # They are ordered in the order of preference, so we pick the first that's non-zero + for source in sources_for_policy: + if self.limit_solutions[source] > 0.: + return source + return SpeedLimitSource.none + + sources_with_limits = [(s, limit) for s, limit in [(s, self.limit_solutions[s]) for s in sources_for_policy] if limit > 0.] + if sources_with_limits: + return min(sources_with_limits, key=lambda x: x[1])[0] + + return SpeedLimitSource.none + + def _resolve_limit_sources(self, sm: messaging.SubMaster) -> tuple[float, float, custom.LongitudinalPlanSP.SpeedLimit.Source]: + """Get limit solutions from each data source""" + self._get_from_car_state(sm) + self._get_from_map_data(sm) + + source = self._get_source_solution_according_to_policy() + speed_limit = self.limit_solutions[source] if source else 0. + distance = self.distance_solutions[source] if source else 0. + + return speed_limit, distance, source + + def update(self, v_ego: float, sm: messaging.SubMaster) -> None: + self.v_ego = v_ego + self.update_params() + + self.speed_limit, self.distance, self.source = self._resolve_limit_sources(sm) + self.speed_limit_offset = self._get_speed_limit_offset() + + self.update_speed_limit_states() + + self.frame += 1 diff --git a/system/athena/__init__.py b/openpilot/sunnypilot/selfdrive/controls/lib/speed_limit/tests/__init__.py similarity index 100% rename from system/athena/__init__.py rename to openpilot/sunnypilot/selfdrive/controls/lib/speed_limit/tests/__init__.py diff --git a/openpilot/sunnypilot/selfdrive/controls/lib/speed_limit/tests/test_speed_limit_assist.py b/openpilot/sunnypilot/selfdrive/controls/lib/speed_limit/tests/test_speed_limit_assist.py new file mode 100644 index 0000000000..7cd6fef524 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/controls/lib/speed_limit/tests/test_speed_limit_assist.py @@ -0,0 +1,278 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" + +import pytest + +from openpilot.cereal import custom +from opendbc.car.car_helpers import interfaces +from opendbc.car.rivian.values import CAR as RIVIAN +from opendbc.car.tesla.values import CAR as TESLA +from opendbc.car.toyota.values import CAR as TOYOTA +from openpilot.common.constants import CV +from openpilot.common.params import Params +from openpilot.common.realtime import DT_MDL +from openpilot.selfdrive.car.cruise import V_CRUISE_UNSET +from openpilot.sunnypilot import PARAMS_UPDATE_PERIOD +from openpilot.sunnypilot.selfdrive.car import interfaces as sunnypilot_interfaces +from openpilot.sunnypilot.selfdrive.controls.lib.speed_limit import PCM_LONG_REQUIRED_MAX_SET_SPEED +from openpilot.sunnypilot.selfdrive.controls.lib.speed_limit.common import Mode +from openpilot.sunnypilot.selfdrive.controls.lib.speed_limit.speed_limit_assist import SpeedLimitAssist, \ + PRE_ACTIVE_GUARD_PERIOD, ACTIVE_STATES +from openpilot.sunnypilot.selfdrive.selfdrived.events import EventsSP + +SpeedLimitAssistState = custom.LongitudinalPlanSP.SpeedLimit.AssistState + +ALL_STATES = tuple(SpeedLimitAssistState.schema.enumerants.values()) + +SPEED_LIMITS = { + 'residential': 25 * CV.MPH_TO_MS, # 25 mph + 'city': 35 * CV.MPH_TO_MS, # 35 mph + 'highway': 65 * CV.MPH_TO_MS, # 65 mph + 'freeway': 80 * CV.MPH_TO_MS, # 80 mph +} + +DEFAULT_CAR = TOYOTA.TOYOTA_RAV4_TSS2 + + +@pytest.fixture +def car_name(request): + return getattr(request, "param", DEFAULT_CAR) + + +@pytest.fixture(autouse=True) +def set_car_name_on_instance(request, car_name): + instance = getattr(request, "instance", None) + if instance: + instance.car_name = car_name + + +class TestSpeedLimitAssist: + + def setup_method(self, method): + self.params = Params() + self.reset_custom_params() + self.events_sp = EventsSP() + CI = self._setup_platform(self.car_name) + self.sla = SpeedLimitAssist(CI.CP, CI.CP_SP) + self.sla.pre_active_timer = int(PRE_ACTIVE_GUARD_PERIOD[self.sla.pcm_op_long] / DT_MDL) + self.pcm_long_max_set_speed = PCM_LONG_REQUIRED_MAX_SET_SPEED[self.sla.is_metric][1] # use 80 MPH for now + self.speed_conv = CV.MS_TO_KPH if self.sla.is_metric else CV.MS_TO_MPH + + def teardown_method(self, method): + self.reset_state() + + def _setup_platform(self, car_name): + CarInterface = interfaces[car_name] + CP = CarInterface.get_non_essential_params(car_name) + CP_SP = CarInterface.get_non_essential_params_sp(CP, car_name) + CI = CarInterface(CP, CP_SP) + CI.CP.openpilotLongitudinalControl = True # always assume it's openpilot longitudinal + sunnypilot_interfaces.setup_interfaces(CI, self.params) + return CI + + def reset_custom_params(self): + self.params.put("IsReleaseSpBranch", True, block=True) + self.params.put("SpeedLimitMode", int(Mode.assist), block=True) + self.params.put_bool("IsMetric", False, block=True) + self.params.put("SpeedLimitOffsetType", 0, block=True) + self.params.put("SpeedLimitValueOffset", 0, block=True) + + def reset_state(self): + self.sla.state = SpeedLimitAssistState.disabled + self.sla.frame = -1 + self.sla.last_op_engaged_frame = 0 + self.sla.op_engaged = False + self.sla.op_engaged_prev = False + self.sla._speed_limit = 0. + self.sla.speed_limit_prev = 0. + self.sla.last_valid_speed_limit_offsetted = 0. + self.sla._distance = 0. + self.events_sp.clear() + + def initialize_active_state(self, initialize_v_cruise): + self.sla.state = SpeedLimitAssistState.active + self.sla.v_cruise_cluster = initialize_v_cruise + self.sla.v_cruise_cluster_prev = initialize_v_cruise + self.sla.prev_v_cruise_cluster_conv = round(initialize_v_cruise * self.speed_conv) + + def test_initial_state(self): + assert self.sla.state == SpeedLimitAssistState.disabled + assert not self.sla.is_enabled + assert not self.sla.is_active + assert V_CRUISE_UNSET == self.sla.get_v_target_from_control() + + @pytest.mark.parametrize("car_name", [RIVIAN.RIVIAN_R1, TESLA.TESLA_MODEL_Y], indirect=True) + def test_disallowed_brands(self, car_name): + """ + Speed Limit Assist is disabled for the following brands and conditions: + - All Tesla and is a release branch; + - All Rivian + """ + assert not self.sla.enabled + + # stay disallowed even when the param may have changed from somewhere else + self.params.put("SpeedLimitMode", int(Mode.assist), block=True) + for _ in range(int(PARAMS_UPDATE_PERIOD / DT_MDL)): + self.sla.update(True, False, SPEED_LIMITS['city'], 0, SPEED_LIMITS['highway'], SPEED_LIMITS['city'], + SPEED_LIMITS['city'], True, 0, self.events_sp) + assert not self.sla.enabled + + def test_disabled(self): + self.params.put("SpeedLimitMode", int(Mode.off), block=True) + for _ in range(int(10. / DT_MDL)): + self.sla.update(True, False, SPEED_LIMITS['city'], 0, SPEED_LIMITS['highway'], SPEED_LIMITS['city'], SPEED_LIMITS['city'], True, 0, self.events_sp) + assert self.sla.state == SpeedLimitAssistState.disabled + + def test_transition_disabled_to_preactive(self): + for _ in range(int(3. / DT_MDL)): + self.sla.update(True, False, SPEED_LIMITS['city'], 0, SPEED_LIMITS['highway'], SPEED_LIMITS['city'], SPEED_LIMITS['city'], True, 0, self.events_sp) + assert self.sla.state == SpeedLimitAssistState.preActive + assert self.sla.is_enabled and not self.sla.is_active + + def test_transition_disabled_to_pending_no_speed_limit_not_max_initial_set_speed(self): + for _ in range(int(3. / DT_MDL)): + self.sla.update(True, False, SPEED_LIMITS['highway'], 0, SPEED_LIMITS['city'], 0, 0, False, 0, self.events_sp) + assert self.sla.state == SpeedLimitAssistState.pending + assert self.sla.is_enabled and not self.sla.is_active + + def test_preactive_to_active_with_max_speed_confirmation(self): + self.sla.state = SpeedLimitAssistState.preActive + self.sla.update(True, False, SPEED_LIMITS['city'], 0, self.pcm_long_max_set_speed, SPEED_LIMITS['highway'], + SPEED_LIMITS['highway'], True, 0, self.events_sp) + assert self.sla.state == SpeedLimitAssistState.active + assert self.sla.is_enabled and self.sla.is_active + assert self.sla.output_v_target == SPEED_LIMITS['highway'] + + def test_preactive_timeout_to_inactive(self): + self.sla.state = SpeedLimitAssistState.preActive + self.sla.update(True, False, SPEED_LIMITS['city'], 0, SPEED_LIMITS['highway'], SPEED_LIMITS['city'], SPEED_LIMITS['city'], True, 0, self.events_sp) + + for _ in range(int(PRE_ACTIVE_GUARD_PERIOD[self.sla.pcm_op_long] / DT_MDL)): + self.sla.update(True, False, SPEED_LIMITS['city'], 0, SPEED_LIMITS['highway'], SPEED_LIMITS['city'], SPEED_LIMITS['city'], True, 0, self.events_sp) + assert self.sla.state == SpeedLimitAssistState.inactive + + def test_preactive_to_pending_no_speed_limit(self): + self.sla.state = SpeedLimitAssistState.preActive + self.sla.update(True, False, SPEED_LIMITS['highway'], 0, self.pcm_long_max_set_speed, 0, 0, False, 0, self.events_sp) + assert self.sla.state == SpeedLimitAssistState.pending + assert self.sla.is_enabled and not self.sla.is_active + + def test_pending_to_active_when_speed_limit_available(self): + self.sla.state = SpeedLimitAssistState.pending + self.sla.v_cruise_cluster_prev = self.pcm_long_max_set_speed + self.sla.prev_v_cruise_cluster_conv = round(self.pcm_long_max_set_speed * self.speed_conv) + + self.sla.update(True, False, SPEED_LIMITS['highway'], 0, self.pcm_long_max_set_speed, + SPEED_LIMITS['highway'], SPEED_LIMITS['highway'], True, 0, self.events_sp) + assert self.sla.state == SpeedLimitAssistState.active + + def test_pending_to_adapting_when_below_speed_limit(self): + self.sla.state = SpeedLimitAssistState.pending + self.sla.v_cruise_cluster_prev = self.pcm_long_max_set_speed + self.sla.prev_v_cruise_cluster_conv = round(self.pcm_long_max_set_speed * self.speed_conv) + + self.sla.update(True, False, SPEED_LIMITS['highway'] + 5, 0, self.pcm_long_max_set_speed, + SPEED_LIMITS['highway'], SPEED_LIMITS['highway'], True, 0, self.events_sp) + assert self.sla.state == SpeedLimitAssistState.adapting + assert self.sla.is_enabled and self.sla.is_active + + def test_active_to_adapting_transition(self): + self.initialize_active_state(self.pcm_long_max_set_speed) + + self.sla.update(True, False, SPEED_LIMITS['highway'] + 2, 0, self.pcm_long_max_set_speed, SPEED_LIMITS['highway'], + SPEED_LIMITS['highway'], True, 0, self.events_sp) + assert self.sla.state == SpeedLimitAssistState.adapting + + def test_adapting_to_active_transition(self): + self.sla.state = SpeedLimitAssistState.adapting + self.sla.v_cruise_cluster_prev = self.pcm_long_max_set_speed + self.sla.prev_v_cruise_cluster_conv = round(self.pcm_long_max_set_speed * self.speed_conv) + + self.sla.update(True, False, SPEED_LIMITS['city'], 0, self.pcm_long_max_set_speed, SPEED_LIMITS['highway'], + SPEED_LIMITS['highway'], True, 0, self.events_sp) + assert self.sla.state == SpeedLimitAssistState.active + + def test_manual_cruise_change_detection(self): + self.sla.state = SpeedLimitAssistState.active + expected_cruise = SPEED_LIMITS['highway'] + self.sla.v_cruise_cluster_prev = expected_cruise + + different_cruise = SPEED_LIMITS['highway'] + 5 + self.sla.update(True, False, SPEED_LIMITS['city'], 0, different_cruise, SPEED_LIMITS['city'], SPEED_LIMITS['city'], True, 0, self.events_sp) + assert self.sla.state == SpeedLimitAssistState.inactive + + # TODO-SP: test lower CST cases + def test_rapid_speed_limit_changes(self): + self.initialize_active_state(self.pcm_long_max_set_speed) + speed_limits = [SPEED_LIMITS['highway'], SPEED_LIMITS['freeway']] + + for _, speed_limit in enumerate(speed_limits): + self.sla.update(True, False, speed_limit, 0, self.pcm_long_max_set_speed, speed_limit, speed_limit, True, 0, self.events_sp) + assert self.sla.state in ACTIVE_STATES + + def test_invalid_speed_limits_handling(self): + self.initialize_active_state(self.pcm_long_max_set_speed) + + invalid_limits = [-10, 0, 200 * CV.MPH_TO_MS] + + for invalid_limit in invalid_limits: + self.sla.update(True, False, SPEED_LIMITS['city'], 0, self.pcm_long_max_set_speed, invalid_limit, SPEED_LIMITS['city'], True, 0, self.events_sp) + assert isinstance(self.sla.output_v_target, (int, float)) + assert self.sla.output_v_target == V_CRUISE_UNSET or self.sla.output_v_target > 0 + + def test_stale_data_handling(self): + self.initialize_active_state(self.pcm_long_max_set_speed) + old_speed_limit = SPEED_LIMITS['city'] + + self.sla.update(True, False, SPEED_LIMITS['city'], 0, self.pcm_long_max_set_speed, 0, old_speed_limit, True, 0, self.events_sp) + assert self.sla.state in ACTIVE_STATES + assert self.sla.output_v_target == old_speed_limit + + def test_distance_based_adapting(self): + self.sla.state = SpeedLimitAssistState.adapting + self.sla.v_cruise_cluster_prev = self.pcm_long_max_set_speed + self.sla.prev_v_cruise_cluster_conv = round(self.pcm_long_max_set_speed * self.speed_conv) + + distance = 100.0 + current_speed = SPEED_LIMITS['freeway'] + target_speed = SPEED_LIMITS['highway'] + + self.sla.update(True, False, current_speed, 0, self.pcm_long_max_set_speed, target_speed, target_speed, True, distance, self.events_sp) + assert self.sla.state == SpeedLimitAssistState.adapting + assert self.sla.output_v_target == target_speed # TODO-SP: assert expected accel, need to enable self.acceleration_solutions + + def test_long_disengaged_to_disabled(self): + self.initialize_active_state(self.pcm_long_max_set_speed) + + self.sla.update(False, False, SPEED_LIMITS['city'], 0, self.pcm_long_max_set_speed, SPEED_LIMITS['city'], + SPEED_LIMITS['city'], True, 0, self.events_sp) + assert self.sla.state == SpeedLimitAssistState.disabled + assert self.sla.output_v_target == V_CRUISE_UNSET + + def test_maintain_states_with_no_changes(self): + """Test that states are maintained when no significant changes occur""" + test_states = [ + SpeedLimitAssistState.preActive, + SpeedLimitAssistState.pending, + SpeedLimitAssistState.active, + SpeedLimitAssistState.adapting + ] + + for state in test_states: + self.sla.state = state + self.sla.op_engaged = True + + initial_state = state + + self.sla.update(True, False, SPEED_LIMITS['city'], 0, self.pcm_long_max_set_speed, SPEED_LIMITS['city'], SPEED_LIMITS['city'], True, 0, self.events_sp) + + assert self.sla.state in ALL_STATES # Sanity check + + if initial_state == SpeedLimitAssistState.preActive: + assert self.sla.state in [SpeedLimitAssistState.preActive, SpeedLimitAssistState.active] + elif initial_state in ACTIVE_STATES: + assert self.sla.state in ACTIVE_STATES diff --git a/openpilot/sunnypilot/selfdrive/controls/lib/speed_limit/tests/test_speed_limit_resolver.py b/openpilot/sunnypilot/selfdrive/controls/lib/speed_limit/tests/test_speed_limit_resolver.py new file mode 100644 index 0000000000..a18880c620 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/controls/lib/speed_limit/tests/test_speed_limit_resolver.py @@ -0,0 +1,144 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import random +import time + +import pytest +from pytest_mock import MockerFixture + +from openpilot.cereal import custom +from openpilot.sunnypilot.selfdrive.controls.lib.speed_limit import LIMIT_MAX_MAP_DATA_AGE + +from openpilot.sunnypilot.selfdrive.controls.lib.speed_limit.speed_limit_resolver import SpeedLimitResolver, ALL_SOURCES +from openpilot.sunnypilot.selfdrive.controls.lib.speed_limit.common import Policy + +SpeedLimitSource = custom.LongitudinalPlanSP.SpeedLimit.Source + + +def create_mock(properties, mocker: MockerFixture): + mock = mocker.MagicMock() + for _property, value in properties.items(): + setattr(mock, _property, value) + return mock + + +def setup_sm_mock(mocker: MockerFixture): + cruise_speed_limit = random.uniform(0, 120) + live_map_data_limit = random.uniform(0, 120) + + car_state = create_mock({ + 'gasPressed': False, + 'brakePressed': False, + 'standstill': False, + }, mocker) + car_state_sp = create_mock({ + 'speedLimit': cruise_speed_limit, + }, mocker) + live_map_data = create_mock({ + 'speedLimit': live_map_data_limit, + 'speedLimitValid': True, + 'speedLimitAhead': 0., + 'speedLimitAheadValid': 0., + 'speedLimitAheadDistance': 0., + }, mocker) + gps_data = create_mock({ + 'unixTimestampMillis': time.monotonic() * 1e3, + }, mocker) + sm_mock = mocker.MagicMock() + sm_mock.__getitem__.side_effect = lambda key: { + 'carState': car_state, + 'liveMapDataSP': live_map_data, + 'carStateSP': car_state_sp, + 'gpsLocation': gps_data, + }[key] + return sm_mock + + +parametrized_policies = pytest.mark.parametrize( + "policy, sm_key, function_key", [ + (Policy.car_state_only, 'carStateSP', SpeedLimitSource.car), + (Policy.car_state_priority, 'carStateSP', SpeedLimitSource.car), + (Policy.map_data_only, 'liveMapDataSP', SpeedLimitSource.map), + (Policy.map_data_priority, 'liveMapDataSP', SpeedLimitSource.map), + ], + ids=lambda val: val.name if hasattr(val, 'name') else str(val) +) + + +@pytest.mark.parametrize("resolver_class", [SpeedLimitResolver]) +class TestSpeedLimitResolverValidation: + + @pytest.mark.parametrize("policy", list(Policy), ids=lambda policy: policy.name) + def test_initial_state(self, resolver_class, policy): + resolver = resolver_class() + resolver.policy = policy + for source in ALL_SOURCES: + if source in resolver.limit_solutions: + assert resolver.limit_solutions[source] == 0. + assert resolver.distance_solutions[source] == 0. + + @parametrized_policies + def test_resolver(self, resolver_class, policy, sm_key, function_key, mocker: MockerFixture): + resolver = resolver_class() + resolver.policy = policy + sm_mock = setup_sm_mock(mocker) + source_speed_limit = sm_mock[sm_key].speedLimit + + # Assert the resolver + resolver.update(source_speed_limit, sm_mock) + assert resolver.speed_limit == source_speed_limit + assert resolver.source == ALL_SOURCES[function_key] + + def test_resolver_combined(self, resolver_class, mocker: MockerFixture): + resolver = resolver_class() + resolver.policy = Policy.combined + sm_mock = setup_sm_mock(mocker) + socket_to_source = {'carStateSP': SpeedLimitSource.car, 'liveMapDataSP': SpeedLimitSource.map} + minimum_key, minimum_speed_limit = min( + ((key, sm_mock[key].speedLimit) for key in + socket_to_source.keys()), key=lambda x: x[1]) + + # Assert the resolver + resolver.update(minimum_speed_limit, sm_mock) + assert resolver.speed_limit == minimum_speed_limit + assert resolver.source == socket_to_source[minimum_key] + + @parametrized_policies + def test_parser(self, resolver_class, policy, sm_key, function_key, mocker: MockerFixture): + resolver = resolver_class() + resolver.policy = policy + sm_mock = setup_sm_mock(mocker) + source_speed_limit = sm_mock[sm_key].speedLimit + + # Assert the parsing + resolver.update(source_speed_limit, sm_mock) + assert resolver.limit_solutions[ALL_SOURCES[function_key]] == source_speed_limit + assert resolver.distance_solutions[ALL_SOURCES[function_key]] == 0. + + @pytest.mark.parametrize("policy", list(Policy), ids=lambda policy: policy.name) + def test_resolve_interaction_in_update(self, resolver_class, policy, mocker: MockerFixture): + v_ego = 50 + resolver = resolver_class() + resolver.policy = policy + + sm_mock = setup_sm_mock(mocker) + resolver.update(v_ego, sm_mock) + + # After resolution + assert resolver.speed_limit is not None + assert resolver.distance is not None + assert resolver.source is not None + + @pytest.mark.parametrize("policy", list(Policy), ids=lambda policy: policy.name) + def test_old_map_data_ignored(self, resolver_class, policy, mocker: MockerFixture): + resolver = resolver_class() + resolver.policy = policy + sm_mock = mocker.MagicMock() + sm_mock['gpsLocation'].unixTimestampMillis = (time.monotonic() - 2 * LIMIT_MAX_MAP_DATA_AGE) * 1e3 + resolver._get_from_map_data(sm_mock) + assert resolver.limit_solutions[SpeedLimitSource.map] == 0. + assert resolver.distance_solutions[SpeedLimitSource.map] == 0. diff --git a/sunnypilot/selfdrive/controls/lib/tests/test_auto_lane_change.py b/openpilot/sunnypilot/selfdrive/controls/lib/tests/test_auto_lane_change.py similarity index 99% rename from sunnypilot/selfdrive/controls/lib/tests/test_auto_lane_change.py rename to openpilot/sunnypilot/selfdrive/controls/lib/tests/test_auto_lane_change.py index 5d1fa360ed..b4ec5041c8 100644 --- a/sunnypilot/selfdrive/controls/lib/tests/test_auto_lane_change.py +++ b/openpilot/sunnypilot/selfdrive/controls/lib/tests/test_auto_lane_change.py @@ -4,9 +4,7 @@ Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. This file is part of sunnypilot and is licensed under the MIT License. See the LICENSE.md file in the root directory for more details. """ - -from parameterized import parameterized - +from openpilot.common.parameterized import parameterized from openpilot.common.realtime import DT_MDL from openpilot.selfdrive.controls.lib.desire_helper import DesireHelper, LaneChangeState, LaneChangeDirection from openpilot.sunnypilot.selfdrive.controls.lib.auto_lane_change import AutoLaneChangeController, AutoLaneChangeMode, \ diff --git a/sunnypilot/selfdrive/controls/lib/tests/test_blinker_pause_lateral.py b/openpilot/sunnypilot/selfdrive/controls/lib/tests/test_blinker_pause_lateral.py similarity index 87% rename from sunnypilot/selfdrive/controls/lib/tests/test_blinker_pause_lateral.py rename to openpilot/sunnypilot/selfdrive/controls/lib/tests/test_blinker_pause_lateral.py index 6ba1dcef41..7a72cfa1f2 100644 --- a/sunnypilot/selfdrive/controls/lib/tests/test_blinker_pause_lateral.py +++ b/openpilot/sunnypilot/selfdrive/controls/lib/tests/test_blinker_pause_lateral.py @@ -4,9 +4,9 @@ Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. This file is part of sunnypilot and is licensed under the MIT License. See the LICENSE.md file in the root directory for more details. """ -from cereal import car +from opendbc.car.structs import car -from openpilot.common.conversions import Conversions as CV +from openpilot.common.constants import CV from openpilot.sunnypilot.selfdrive.controls.lib.blinker_pause_lateral import BlinkerPauseLateral @@ -20,6 +20,8 @@ class TestBlinkerPauseLateral: self.blinker_pause_lateral.enabled = True self.blinker_pause_lateral.is_metric = False self.blinker_pause_lateral.min_speed = 20 # MPH + self.blinker_pause_lateral.reengage_delay = 0 + self.blinker_pause_lateral.blinker_off_timer = 0.0 self.CS = car.CarState.new_message() self.CS.vEgo = 0 @@ -46,6 +48,18 @@ class TestBlinkerPauseLateral: } self._test_should_blinker_pause_lateral(expected_results) + def test_reengage_delay(self): + self.blinker_pause_lateral.reengage_delay = 2 # seconds + self.CS.vEgo = 4.5 # ~10 MPH + + expected_results = { + (False, False): True, + (True, False): True, + (False, True): True, + (True, True): False + } + self._test_should_blinker_pause_lateral(expected_results) + def test_above_min_speed_blinker(self): self.CS.vEgo = 13.4 # ~30 MPH diff --git a/openpilot/sunnypilot/selfdrive/controls/lib/tests/test_lane_turn_desire.py b/openpilot/sunnypilot/selfdrive/controls/lib/tests/test_lane_turn_desire.py new file mode 100644 index 0000000000..c3e96fd778 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/controls/lib/tests/test_lane_turn_desire.py @@ -0,0 +1,113 @@ +import pytest +from openpilot.cereal import log, custom +from openpilot.common.params import Params + +from openpilot.selfdrive.controls.lib.desire_helper import DesireHelper +from openpilot.sunnypilot.selfdrive.controls.lib.lane_turn_desire import LaneTurnController, LANE_CHANGE_SPEED_MIN +from openpilot.sunnypilot.selfdrive.controls.lib.auto_lane_change import AutoLaneChangeMode + +TurnDirection = custom.ModelDataV2SP.TurnDirection + + +@pytest.mark.parametrize("left_blinker,right_blinker,v_ego,blindspot_left,blindspot_right,expected", [ + (True, False, 5, False, False, TurnDirection.turnLeft), + (False, True, 6, False, False, TurnDirection.turnRight), + (True, False, 9, False, False, TurnDirection.none), + (True, False, 7, True, False, TurnDirection.none), + (False, True, 6, False, True, TurnDirection.none), + (False, False, 5, False, False, TurnDirection.none), + (True, True, 5, False, False, TurnDirection.none), +]) +def test_lane_turn_desire_conditions(left_blinker, right_blinker, v_ego, blindspot_left, blindspot_right, expected): + dh = DesireHelper() + controller = LaneTurnController(dh) + controller.enabled = True + controller.lane_turn_value = LANE_CHANGE_SPEED_MIN + controller.turn_direction = TurnDirection.none + controller.update_lane_turn(blindspot_left, blindspot_right, left_blinker, right_blinker, v_ego) + assert controller.get_turn_direction() == expected + + +def test_lane_turn_desire_disabled(): + dh = DesireHelper() + controller = LaneTurnController(dh) + controller.enabled = False + controller.lane_turn_value = LANE_CHANGE_SPEED_MIN + controller.turn_direction = TurnDirection.none + controller.update_lane_turn(False, False, True, False, 7) + assert controller.get_turn_direction() == TurnDirection.none + + +def test_lane_turn_overrides_lane_change(): + dh = DesireHelper() + controller = LaneTurnController(dh) + controller.enabled = True + controller.lane_turn_value = LANE_CHANGE_SPEED_MIN + controller.turn_direction = TurnDirection.none + # left turn desire + controller.update_lane_turn(False, False, True, False, 5) + assert controller.get_turn_direction() == TurnDirection.turnLeft + # right turn desire + controller.update_lane_turn(False, False, False, True, 6) + assert controller.get_turn_direction() == TurnDirection.turnRight + # no turn + controller.update_lane_turn(False, False, False, False, 7) + assert controller.get_turn_direction() == TurnDirection.none + + +@pytest.mark.parametrize("v_ego,expected", [ + (8.93, TurnDirection.turnLeft), # just below threshold + (8.96, TurnDirection.none), # above threshold + (8.95, TurnDirection.none), # just above threshold +]) +def test_lane_turn_desire_speed_boundary(v_ego, expected): + dh = DesireHelper() + controller = LaneTurnController(dh) + controller.enabled = True + controller.lane_turn_value = LANE_CHANGE_SPEED_MIN + controller.turn_direction = TurnDirection.none + controller.update_lane_turn(False, True, True, False, v_ego) + assert controller.get_turn_direction() == expected + + +class DummyCarState: + def __init__(self, vEgo=0, leftBlinker=False, rightBlinker=False, leftBlindspot=False, rightBlindspot=False, + steeringPressed=False, steeringTorque=0, brakePressed=False): + self.vEgo = vEgo + self.leftBlinker = leftBlinker + self.rightBlinker = rightBlinker + self.leftBlindspot = leftBlindspot + self.rightBlindspot = rightBlindspot + self.steeringPressed = steeringPressed + self.steeringTorque = steeringTorque + self.brakePressed = brakePressed + + +@pytest.fixture +def set_lane_turn_params(): + params = Params() + params.put("LaneTurnDesire", True) + params.put("LaneTurnValue", 20.0) + + +@pytest.mark.parametrize("carstate, lateral_active, lane_change_prob, expected_desire", [ + # Lane turn desire overrides lane change desire + (DummyCarState(vEgo=5, leftBlinker=True, rightBlinker=False, leftBlindspot=False, rightBlindspot=False), True, 1.0, + log.Desire.turnLeft), + (DummyCarState(vEgo=7, leftBlinker=False, rightBlinker=True, leftBlindspot=False, rightBlindspot=False), True, 1.0, + log.Desire.turnRight), + # Lane change desire only (no turn desires) + (DummyCarState(vEgo=9, leftBlinker=True, rightBlinker=False, leftBlindspot=False, rightBlindspot=False, + steeringPressed=True, steeringTorque=1), True, 1.0, log.Desire.laneChangeLeft), + (DummyCarState(vEgo=9, leftBlinker=False, rightBlinker=True, leftBlindspot=False, rightBlindspot=False, + steeringPressed=True, steeringTorque=-1), True, 1.0, log.Desire.laneChangeRight), + # No desire (inactive) + (DummyCarState(vEgo=9, leftBlinker=False, rightBlinker=False), False, 1.0, log.Desire.none), + (DummyCarState(vEgo=4, leftBlinker=False, rightBlinker=False), True, 1.0, log.Desire.none), # No blinkers? no desire! +]) +def test_desire_helper_integration(carstate, lateral_active, lane_change_prob, expected_desire, set_lane_turn_params): + dh = DesireHelper() + dh.alc.lane_change_set_timer = AutoLaneChangeMode.NUDGE + for _ in range(10): + dh.update(carstate, lateral_active, lane_change_prob) + assert dh.desire == expected_desire # The first four tests were unit tests to test the controller, where this tests the integration in desire helpers diff --git a/openpilot/sunnypilot/selfdrive/locationd/.gitignore b/openpilot/sunnypilot/selfdrive/locationd/.gitignore new file mode 100644 index 0000000000..11b9f127b2 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/locationd/.gitignore @@ -0,0 +1,3 @@ +params_learner +paramsd +locationd diff --git a/openpilot/sunnypilot/selfdrive/locationd/SConscript b/openpilot/sunnypilot/selfdrive/locationd/SConscript new file mode 100644 index 0000000000..3e71f36782 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/locationd/SConscript @@ -0,0 +1,30 @@ +Import('env', 'arch', 'common', 'messaging', 'rednose', 'transformations') + +loc_libs = [messaging, common, 'pthread', 'dl'] + +# build ekf models +rednose_gen_dir = 'models/generated' +rednose_gen_deps = [ + "models/constants.py", +] +live_ekf = env.RednoseCompileFilter( + target='live', + filter_gen_script='models/live_kf.py', + output_dir=rednose_gen_dir, + extra_gen_artifacts=['live_kf_constants.h'], + gen_script_deps=rednose_gen_deps, +) + +# locationd build +locationd_sources = ["locationd.cc", "models/live_kf.cc"] + +lenv = env.Clone() +# ekf filter libraries need to be linked, even if no symbols are used +if arch != "Darwin": + lenv["LINKFLAGS"] += ["-Wl,--no-as-needed"] + +lenv["LIBPATH"].append(Dir(rednose_gen_dir).abspath) +lenv["RPATH"].append(Dir(rednose_gen_dir).abspath) +locationd = lenv.Program("locationd", locationd_sources, LIBS=["live", "ekf_sym"] + loc_libs + transformations) +lenv.Depends(locationd, rednose) +lenv.Depends(locationd, live_ekf) diff --git a/system/athena/tests/__init__.py b/openpilot/sunnypilot/selfdrive/locationd/__init__.py similarity index 100% rename from system/athena/tests/__init__.py rename to openpilot/sunnypilot/selfdrive/locationd/__init__.py diff --git a/openpilot/sunnypilot/selfdrive/locationd/locationd.cc b/openpilot/sunnypilot/selfdrive/locationd/locationd.cc new file mode 100644 index 0000000000..b24daa961b --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/locationd/locationd.cc @@ -0,0 +1,750 @@ +#include "sunnypilot/selfdrive/locationd/locationd.h" + +#include +#include + +#include +#include +#include + +using namespace EKFS; +using namespace Eigen; + +ExitHandler do_exit; +const double ACCEL_SANITY_CHECK = 100.0; // m/s^2 +const double ROTATION_SANITY_CHECK = 10.0; // rad/s +const double TRANS_SANITY_CHECK = 200.0; // m/s +const double CALIB_RPY_SANITY_CHECK = 0.5; // rad (+- 30 deg) +const double ALTITUDE_SANITY_CHECK = 10000; // m +const double MIN_STD_SANITY_CHECK = 1e-5; // m or rad +const double VALID_TIME_SINCE_RESET = 1.0; // s +const double VALID_POS_STD = 50.0; // m +const double MAX_RESET_TRACKER = 5.0; +const double SANE_GPS_UNCERTAINTY = 1500.0; // m +const double INPUT_INVALID_THRESHOLD = 0.5; // same as reset tracker +const double RESET_TRACKER_DECAY = 0.99995; +const double DECAY = 0.9993; // ~10 secs to resume after a bad input +const double MAX_FILTER_REWIND_TIME = 0.8; // s +const double YAWRATE_CROSS_ERR_CHECK_FACTOR = 30; + +// TODO: GPS sensor time offsets are empirically calculated +// They should be replaced with synced time from a real clock +const double GPS_QUECTEL_SENSOR_TIME_OFFSET = 0.630; // s +const double GPS_UBLOX_SENSOR_TIME_OFFSET = 0.095; // s +const float GPS_POS_STD_THRESHOLD = 50.0; +const float GPS_VEL_STD_THRESHOLD = 5.0; +const float GPS_POS_ERROR_RESET_THRESHOLD = 300.0; +const float GPS_POS_STD_RESET_THRESHOLD = 2.0; +const float GPS_VEL_STD_RESET_THRESHOLD = 0.5; +const float GPS_ORIENTATION_ERROR_RESET_THRESHOLD = 1.0; +const int GPS_ORIENTATION_ERROR_RESET_CNT = 3; + +const bool DEBUG = getenv("DEBUG") != nullptr && std::string(getenv("DEBUG")) != "0"; + +static VectorXd floatlist2vector(const capnp::List::Reader& floatlist) { + VectorXd res(floatlist.size()); + for (int i = 0; i < floatlist.size(); i++) { + res[i] = floatlist[i]; + } + return res; +} + +static Vector4d quat2vector(const Quaterniond& quat) { + return Vector4d(quat.w(), quat.x(), quat.y(), quat.z()); +} + +static Quaterniond vector2quat(const VectorXd& vec) { + return Quaterniond(vec(0), vec(1), vec(2), vec(3)); +} + +static void init_measurement(cereal::LiveLocationKalman::Measurement::Builder meas, const VectorXd& val, const VectorXd& std, bool valid) { + meas.setValue(kj::arrayPtr(val.data(), val.size())); + meas.setStd(kj::arrayPtr(std.data(), std.size())); + meas.setValid(valid); +} + + +static MatrixXdr rotate_cov(const MatrixXdr& rot_matrix, const MatrixXdr& cov_in) { + // To rotate a covariance matrix, the cov matrix needs to multiplied left and right by the transform matrix + return ((rot_matrix * cov_in) * rot_matrix.transpose()); +} + +static VectorXd rotate_std(const MatrixXdr& rot_matrix, const VectorXd& std_in) { + // Stds cannot be rotated like values, only covariances can be rotated + return rotate_cov(rot_matrix, std_in.array().square().matrix().asDiagonal()).diagonal().array().sqrt(); +} + +Localizer::Localizer(LocalizerGnssSource gnss_source) { + this->kf = std::make_unique(); + this->reset_kalman(); + + this->calib = Vector3d(0.0, 0.0, 0.0); + this->device_from_calib = MatrixXdr::Identity(3, 3); + this->calib_from_device = MatrixXdr::Identity(3, 3); + + for (int i = 0; i < POSENET_STD_HIST_HALF * 2; i++) { + this->posenet_stds.push_back(10.0); + } + + VectorXd ecef_pos = this->kf->get_x().segment(STATE_ECEF_POS_START); + this->converter = std::make_unique((ECEF) { .x = ecef_pos[0], .y = ecef_pos[1], .z = ecef_pos[2] }); + this->configure_gnss_source(gnss_source); +} + +void Localizer::build_live_location(cereal::LiveLocationKalman::Builder& fix) { + VectorXd predicted_state = this->kf->get_x(); + MatrixXdr predicted_cov = this->kf->get_P(); + VectorXd predicted_std = predicted_cov.diagonal().array().sqrt(); + + VectorXd fix_ecef = predicted_state.segment(STATE_ECEF_POS_START); + ECEF fix_ecef_ecef = { .x = fix_ecef(0), .y = fix_ecef(1), .z = fix_ecef(2) }; + VectorXd fix_ecef_std = predicted_std.segment(STATE_ECEF_POS_ERR_START); + VectorXd vel_ecef = predicted_state.segment(STATE_ECEF_VELOCITY_START); + VectorXd vel_ecef_std = predicted_std.segment(STATE_ECEF_VELOCITY_ERR_START); + VectorXd fix_pos_geo_vec = this->get_position_geodetic(); + VectorXd orientation_ecef = quat2euler(vector2quat(predicted_state.segment(STATE_ECEF_ORIENTATION_START))); + VectorXd orientation_ecef_std = predicted_std.segment(STATE_ECEF_ORIENTATION_ERR_START); + MatrixXdr orientation_ecef_cov = predicted_cov.block(STATE_ECEF_ORIENTATION_ERR_START, STATE_ECEF_ORIENTATION_ERR_START); + MatrixXdr device_from_ecef = euler2rot(orientation_ecef).transpose(); + VectorXd calibrated_orientation_ecef = rot2euler((this->calib_from_device * device_from_ecef).transpose()); + + VectorXd acc_calib = this->calib_from_device * predicted_state.segment(STATE_ACCELERATION_START); + MatrixXdr acc_calib_cov = predicted_cov.block(STATE_ACCELERATION_ERR_START, STATE_ACCELERATION_ERR_START); + VectorXd acc_calib_std = rotate_cov(this->calib_from_device, acc_calib_cov).diagonal().array().sqrt(); + VectorXd ang_vel_calib = this->calib_from_device * predicted_state.segment(STATE_ANGULAR_VELOCITY_START); + + MatrixXdr vel_angular_cov = predicted_cov.block(STATE_ANGULAR_VELOCITY_ERR_START, STATE_ANGULAR_VELOCITY_ERR_START); + VectorXd ang_vel_calib_std = rotate_cov(this->calib_from_device, vel_angular_cov).diagonal().array().sqrt(); + + VectorXd vel_device = device_from_ecef * vel_ecef; + VectorXd device_from_ecef_eul = quat2euler(vector2quat(predicted_state.segment(STATE_ECEF_ORIENTATION_START))).transpose(); + MatrixXdr condensed_cov(STATE_ECEF_ORIENTATION_ERR_LEN + STATE_ECEF_VELOCITY_ERR_LEN, STATE_ECEF_ORIENTATION_ERR_LEN + STATE_ECEF_VELOCITY_ERR_LEN); + condensed_cov.topLeftCorner() = + predicted_cov.block(STATE_ECEF_ORIENTATION_ERR_START, STATE_ECEF_ORIENTATION_ERR_START); + condensed_cov.topRightCorner() = + predicted_cov.block(STATE_ECEF_ORIENTATION_ERR_START, STATE_ECEF_VELOCITY_ERR_START); + condensed_cov.bottomRightCorner() = + predicted_cov.block(STATE_ECEF_VELOCITY_ERR_START, STATE_ECEF_VELOCITY_ERR_START); + condensed_cov.bottomLeftCorner() = + predicted_cov.block(STATE_ECEF_VELOCITY_ERR_START, STATE_ECEF_ORIENTATION_ERR_START); + VectorXd H_input(device_from_ecef_eul.size() + vel_ecef.size()); + H_input << device_from_ecef_eul, vel_ecef; + MatrixXdr HH = this->kf->H(H_input); + MatrixXdr vel_device_cov = (HH * condensed_cov) * HH.transpose(); + VectorXd vel_device_std = vel_device_cov.diagonal().array().sqrt(); + + VectorXd vel_calib = this->calib_from_device * vel_device; + VectorXd vel_calib_std = rotate_cov(this->calib_from_device, vel_device_cov).diagonal().array().sqrt(); + + VectorXd orientation_ned = ned_euler_from_ecef(fix_ecef_ecef, orientation_ecef); + VectorXd orientation_ned_std = rotate_cov(this->converter->ecef2ned_matrix, orientation_ecef_cov).diagonal().array().sqrt(); + VectorXd calibrated_orientation_ned = ned_euler_from_ecef(fix_ecef_ecef, calibrated_orientation_ecef); + VectorXd nextfix_ecef = fix_ecef + vel_ecef; + VectorXd ned_vel = this->converter->ecef2ned((ECEF) { .x = nextfix_ecef(0), .y = nextfix_ecef(1), .z = nextfix_ecef(2) }).to_vector() - converter->ecef2ned(fix_ecef_ecef).to_vector(); + + VectorXd accDevice = predicted_state.segment(STATE_ACCELERATION_START); + VectorXd accDeviceErr = predicted_std.segment(STATE_ACCELERATION_ERR_START); + + VectorXd angVelocityDevice = predicted_state.segment(STATE_ANGULAR_VELOCITY_START); + VectorXd angVelocityDeviceErr = predicted_std.segment(STATE_ANGULAR_VELOCITY_ERR_START); + + Vector3d nans = Vector3d(NAN, NAN, NAN); + + // TODO fill in NED and Calibrated stds + // write measurements to msg + init_measurement(fix.initPositionGeodetic(), fix_pos_geo_vec, nans, this->gps_mode); + init_measurement(fix.initPositionECEF(), fix_ecef, fix_ecef_std, this->gps_mode); + init_measurement(fix.initVelocityECEF(), vel_ecef, vel_ecef_std, this->gps_mode); + init_measurement(fix.initVelocityNED(), ned_vel, nans, this->gps_mode); + init_measurement(fix.initVelocityDevice(), vel_device, vel_device_std, true); + init_measurement(fix.initAccelerationDevice(), accDevice, accDeviceErr, true); + init_measurement(fix.initOrientationECEF(), orientation_ecef, orientation_ecef_std, this->gps_mode); + init_measurement(fix.initCalibratedOrientationECEF(), calibrated_orientation_ecef, nans, this->calibrated && this->gps_mode); + init_measurement(fix.initOrientationNED(), orientation_ned, orientation_ned_std, this->gps_mode); + init_measurement(fix.initCalibratedOrientationNED(), calibrated_orientation_ned, nans, this->calibrated && this->gps_mode); + init_measurement(fix.initAngularVelocityDevice(), angVelocityDevice, angVelocityDeviceErr, true); + init_measurement(fix.initVelocityCalibrated(), vel_calib, vel_calib_std, this->calibrated); + init_measurement(fix.initAngularVelocityCalibrated(), ang_vel_calib, ang_vel_calib_std, this->calibrated); + init_measurement(fix.initAccelerationCalibrated(), acc_calib, acc_calib_std, this->calibrated); + if (DEBUG) { + init_measurement(fix.initFilterState(), predicted_state, predicted_std, true); + } + + double old_mean = 0.0, new_mean = 0.0; + int i = 0; + for (double x : this->posenet_stds) { + if (i < POSENET_STD_HIST_HALF) { + old_mean += x; + } else { + new_mean += x; + } + i++; + } + old_mean /= POSENET_STD_HIST_HALF; + new_mean /= POSENET_STD_HIST_HALF; + // experimentally found these values, no false positives in 20k minutes of driving + bool std_spike = (new_mean / old_mean > 4.0 && new_mean > 7.0); + + fix.setPosenetOK(!(std_spike && this->car_speed > 5.0)); + fix.setDeviceStable(!this->device_fell); + fix.setExcessiveResets(this->reset_tracker > MAX_RESET_TRACKER); + fix.setTimeToFirstFix(std::isnan(this->ttff) ? -1. : this->ttff); + this->device_fell = false; + + //fix.setGpsWeek(this->time.week); + //fix.setGpsTimeOfWeek(this->time.tow); + fix.setUnixTimestampMillis(this->unix_timestamp_millis); + + double time_since_reset = this->kf->get_filter_time() - this->last_reset_time; + fix.setTimeSinceReset(time_since_reset); + if (fix_ecef_std.norm() < VALID_POS_STD && this->calibrated && time_since_reset > VALID_TIME_SINCE_RESET) { + fix.setStatus(cereal::LiveLocationKalman::Status::VALID); + } else if (fix_ecef_std.norm() < VALID_POS_STD && time_since_reset > VALID_TIME_SINCE_RESET) { + fix.setStatus(cereal::LiveLocationKalman::Status::UNCALIBRATED); + } else { + fix.setStatus(cereal::LiveLocationKalman::Status::UNINITIALIZED); + } +} + +VectorXd Localizer::get_position_geodetic() { + VectorXd fix_ecef = this->kf->get_x().segment(STATE_ECEF_POS_START); + ECEF fix_ecef_ecef = { .x = fix_ecef(0), .y = fix_ecef(1), .z = fix_ecef(2) }; + Geodetic fix_pos_geo = ecef2geodetic(fix_ecef_ecef); + return Vector3d(fix_pos_geo.lat, fix_pos_geo.lon, fix_pos_geo.alt); +} + +VectorXd Localizer::get_state() { + return this->kf->get_x(); +} + +VectorXd Localizer::get_stdev() { + return this->kf->get_P().diagonal().array().sqrt(); +} + +bool Localizer::are_inputs_ok() { + return this->critical_services_valid(this->observation_values_invalid) && !this->observation_timings_invalid; +} + +void Localizer::observation_timings_invalid_reset(){ + this->observation_timings_invalid = false; +} + +void Localizer::handle_sensor(double current_time, const cereal::SensorEventData::Reader& log) { + // TODO does not yet account for double sensor readings in the log + + // Ignore empty readings (e.g. in case the magnetometer had no data ready) + if (log.getTimestamp() == 0) { + return; + } + + double sensor_time = 1e-9 * log.getTimestamp(); + + // sensor time and log time should be close + if (std::abs(current_time - sensor_time) > 0.1) { + LOGE("Sensor reading ignored, sensor timestamp more than 100ms off from log time"); + this->observation_timings_invalid = true; + return; + } else if (!this->is_timestamp_valid(sensor_time)) { + this->observation_timings_invalid = true; + return; + } + + // TODO: handle messages from two IMUs at the same time + if (log.getSource() == cereal::SensorEventData::SensorSource::BMX055) { + return; + } + + // Gyro Uncalibrated + if (log.which() == cereal::SensorEventData::GYRO_UNCALIBRATED) { + auto v = log.getGyroUncalibrated().getV(); + auto meas = Vector3d(-v[2], -v[1], -v[0]); + + VectorXd gyro_bias = this->kf->get_x().segment(STATE_GYRO_BIAS_START); + float gyro_camodo_yawrate_err = std::abs((meas[2] - gyro_bias[2]) - this->camodo_yawrate_distribution[0]); + float gyro_camodo_yawrate_err_threshold = YAWRATE_CROSS_ERR_CHECK_FACTOR * this->camodo_yawrate_distribution[1]; + bool gyro_valid = gyro_camodo_yawrate_err < gyro_camodo_yawrate_err_threshold; + + if ((meas.norm() < ROTATION_SANITY_CHECK) && gyro_valid) { + this->kf->predict_and_observe(sensor_time, OBSERVATION_PHONE_GYRO, { meas }); + this->observation_values_invalid["gyroscope"] *= DECAY; + } else { + this->observation_values_invalid["gyroscope"] += 1.0; + } + } + + // Accelerometer + if (log.which() == cereal::SensorEventData::ACCELERATION) { + auto v = log.getAcceleration().getV(); + + // TODO: reduce false positives and re-enable this check + // check if device fell, estimate 10 for g + // 40m/s**2 is a good filter for falling detection, no false positives in 20k minutes of driving + // this->device_fell |= (floatlist2vector(v) - Vector3d(10.0, 0.0, 0.0)).norm() > 40.0; + + auto meas = Vector3d(-v[2], -v[1], -v[0]); + if (meas.norm() < ACCEL_SANITY_CHECK) { + this->kf->predict_and_observe(sensor_time, OBSERVATION_PHONE_ACCEL, { meas }); + this->observation_values_invalid["accelerometer"] *= DECAY; + } else { + this->observation_values_invalid["accelerometer"] += 1.0; + } + } +} + +void Localizer::input_fake_gps_observations(double current_time) { + // This is done to make sure that the error estimate of the position does not blow up + // when the filter is in no-gps mode + // Steps : first predict -> observe current obs with reasonable STD + this->kf->predict(current_time); + + VectorXd current_x = this->kf->get_x(); + VectorXd ecef_pos = current_x.segment(STATE_ECEF_POS_START); + VectorXd ecef_vel = current_x.segment(STATE_ECEF_VELOCITY_START); + const MatrixXdr &ecef_pos_R = this->kf->get_fake_gps_pos_cov(); + const MatrixXdr &ecef_vel_R = this->kf->get_fake_gps_vel_cov(); + + this->kf->predict_and_observe(current_time, OBSERVATION_ECEF_POS, { ecef_pos }, { ecef_pos_R }); + this->kf->predict_and_observe(current_time, OBSERVATION_ECEF_VEL, { ecef_vel }, { ecef_vel_R }); +} + +void Localizer::handle_gps(double current_time, const cereal::GpsLocationData::Reader& log, const double sensor_time_offset) { + bool gps_unreasonable = (Vector2d(log.getHorizontalAccuracy(), log.getVerticalAccuracy()).norm() >= SANE_GPS_UNCERTAINTY); + bool gps_accuracy_insane = ((log.getVerticalAccuracy() <= 0) || (log.getSpeedAccuracy() <= 0) || (log.getBearingAccuracyDeg() <= 0)); + bool gps_lat_lng_alt_insane = ((std::abs(log.getLatitude()) > 90) || (std::abs(log.getLongitude()) > 180) || (std::abs(log.getAltitude()) > ALTITUDE_SANITY_CHECK)); + bool gps_vel_insane = (floatlist2vector(log.getVNED()).norm() > TRANS_SANITY_CHECK); + + if (!log.getHasFix() || gps_unreasonable || gps_accuracy_insane || gps_lat_lng_alt_insane || gps_vel_insane) { + //this->gps_valid = false; + this->determine_gps_mode(current_time); + return; + } + + double sensor_time = current_time - sensor_time_offset; + + // Process message + //this->gps_valid = true; + this->gps_mode = true; + Geodetic geodetic = { log.getLatitude(), log.getLongitude(), log.getAltitude() }; + this->converter = std::make_unique(geodetic); + + VectorXd ecef_pos = this->converter->ned2ecef({ 0.0, 0.0, 0.0 }).to_vector(); + VectorXd ecef_vel = this->converter->ned2ecef({ log.getVNED()[0], log.getVNED()[1], log.getVNED()[2] }).to_vector() - ecef_pos; + float ecef_pos_std = std::sqrt(this->gps_variance_factor * std::pow(log.getHorizontalAccuracy(), 2) + this->gps_vertical_variance_factor * std::pow(log.getVerticalAccuracy(), 2)); + MatrixXdr ecef_pos_R = Vector3d::Constant(std::pow(this->gps_std_factor * ecef_pos_std, 2)).asDiagonal(); + MatrixXdr ecef_vel_R = Vector3d::Constant(std::pow(this->gps_std_factor * log.getSpeedAccuracy(), 2)).asDiagonal(); + + this->unix_timestamp_millis = log.getUnixTimestampMillis(); + double gps_est_error = (this->kf->get_x().segment(STATE_ECEF_POS_START) - ecef_pos).norm(); + + VectorXd orientation_ecef = quat2euler(vector2quat(this->kf->get_x().segment(STATE_ECEF_ORIENTATION_START))); + VectorXd orientation_ned = ned_euler_from_ecef({ ecef_pos(0), ecef_pos(1), ecef_pos(2) }, orientation_ecef); + VectorXd orientation_ned_gps = Vector3d(0.0, 0.0, DEG2RAD(log.getBearingDeg())); + VectorXd orientation_error = (orientation_ned - orientation_ned_gps).array() - M_PI; + for (int i = 0; i < orientation_error.size(); i++) { + orientation_error(i) = std::fmod(orientation_error(i), 2.0 * M_PI); + if (orientation_error(i) < 0.0) { + orientation_error(i) += 2.0 * M_PI; + } + orientation_error(i) -= M_PI; + } + VectorXd initial_pose_ecef_quat = quat2vector(euler2quat(ecef_euler_from_ned({ ecef_pos(0), ecef_pos(1), ecef_pos(2) }, orientation_ned_gps))); + + if (ecef_vel.norm() > 5.0 && orientation_error.norm() > 1.0) { + LOGE("Locationd vs ubloxLocation orientation difference too large, kalman reset"); + this->reset_kalman(NAN, initial_pose_ecef_quat, ecef_pos, ecef_vel, ecef_pos_R, ecef_vel_R); + this->kf->predict_and_observe(sensor_time, OBSERVATION_ECEF_ORIENTATION_FROM_GPS, { initial_pose_ecef_quat }); + } else if (gps_est_error > 100.0) { + LOGE("Locationd vs ubloxLocation position difference too large, kalman reset"); + this->reset_kalman(NAN, initial_pose_ecef_quat, ecef_pos, ecef_vel, ecef_pos_R, ecef_vel_R); + } + + this->last_gps_msg = sensor_time; + this->kf->predict_and_observe(sensor_time, OBSERVATION_ECEF_POS, { ecef_pos }, { ecef_pos_R }); + this->kf->predict_and_observe(sensor_time, OBSERVATION_ECEF_VEL, { ecef_vel }, { ecef_vel_R }); +} + +void Localizer::handle_gnss(double current_time, const cereal::GnssMeasurements::Reader& log) { + + if (!log.getPositionECEF().getValid() || !log.getVelocityECEF().getValid()) { + this->determine_gps_mode(current_time); + return; + } + + double sensor_time = log.getMeasTime() * 1e-9; + sensor_time -= this->gps_time_offset; + + auto ecef_pos_v = log.getPositionECEF().getValue(); + VectorXd ecef_pos = Vector3d(ecef_pos_v[0], ecef_pos_v[1], ecef_pos_v[2]); + + // indexed at 0 cause all std values are the same MAE + auto ecef_pos_std = log.getPositionECEF().getStd()[0]; + MatrixXdr ecef_pos_R = Vector3d::Constant(pow(this->gps_std_factor*ecef_pos_std, 2)).asDiagonal(); + + auto ecef_vel_v = log.getVelocityECEF().getValue(); + VectorXd ecef_vel = Vector3d(ecef_vel_v[0], ecef_vel_v[1], ecef_vel_v[2]); + + // indexed at 0 cause all std values are the same MAE + auto ecef_vel_std = log.getVelocityECEF().getStd()[0]; + MatrixXdr ecef_vel_R = Vector3d::Constant(pow(this->gps_std_factor*ecef_vel_std, 2)).asDiagonal(); + + double gps_est_error = (this->kf->get_x().segment(STATE_ECEF_POS_START) - ecef_pos).norm(); + + VectorXd orientation_ecef = quat2euler(vector2quat(this->kf->get_x().segment(STATE_ECEF_ORIENTATION_START))); + VectorXd orientation_ned = ned_euler_from_ecef({ ecef_pos[0], ecef_pos[1], ecef_pos[2] }, orientation_ecef); + + LocalCoord convs((ECEF){ .x = ecef_pos[0], .y = ecef_pos[1], .z = ecef_pos[2] }); + ECEF next_ecef = {.x = ecef_pos[0] + ecef_vel[0], .y = ecef_pos[1] + ecef_vel[1], .z = ecef_pos[2] + ecef_vel[2]}; + VectorXd ned_vel = convs.ecef2ned(next_ecef).to_vector(); + double bearing_rad = atan2(ned_vel[1], ned_vel[0]); + + VectorXd orientation_ned_gps = Vector3d(0.0, 0.0, bearing_rad); + VectorXd orientation_error = (orientation_ned - orientation_ned_gps).array() - M_PI; + for (int i = 0; i < orientation_error.size(); i++) { + orientation_error(i) = std::fmod(orientation_error(i), 2.0 * M_PI); + if (orientation_error(i) < 0.0) { + orientation_error(i) += 2.0 * M_PI; + } + orientation_error(i) -= M_PI; + } + VectorXd initial_pose_ecef_quat = quat2vector(euler2quat(ecef_euler_from_ned({ ecef_pos(0), ecef_pos(1), ecef_pos(2) }, orientation_ned_gps))); + + if (ecef_pos_std > GPS_POS_STD_THRESHOLD || ecef_vel_std > GPS_VEL_STD_THRESHOLD) { + this->determine_gps_mode(current_time); + return; + } + + // prevent jumping gnss measurements (covered lots, standstill...) + bool orientation_reset = ecef_vel_std < GPS_VEL_STD_RESET_THRESHOLD; + orientation_reset &= orientation_error.norm() > GPS_ORIENTATION_ERROR_RESET_THRESHOLD; + orientation_reset &= !this->standstill; + if (orientation_reset) { + this->orientation_reset_count++; + } else { + this->orientation_reset_count = 0; + } + + if ((gps_est_error > GPS_POS_ERROR_RESET_THRESHOLD && ecef_pos_std < GPS_POS_STD_RESET_THRESHOLD) || this->last_gps_msg == 0) { + // always reset on first gps message and if the location is off but the accuracy is high + LOGE("Locationd vs gnssMeasurement position difference too large, kalman reset"); + this->reset_kalman(NAN, initial_pose_ecef_quat, ecef_pos, ecef_vel, ecef_pos_R, ecef_vel_R); + } else if (orientation_reset_count > GPS_ORIENTATION_ERROR_RESET_CNT) { + LOGE("Locationd vs gnssMeasurement orientation difference too large, kalman reset"); + this->reset_kalman(NAN, initial_pose_ecef_quat, ecef_pos, ecef_vel, ecef_pos_R, ecef_vel_R); + this->kf->predict_and_observe(sensor_time, OBSERVATION_ECEF_ORIENTATION_FROM_GPS, { initial_pose_ecef_quat }); + this->orientation_reset_count = 0; + } + + this->gps_mode = true; + this->last_gps_msg = sensor_time; + this->kf->predict_and_observe(sensor_time, OBSERVATION_ECEF_POS, { ecef_pos }, { ecef_pos_R }); + this->kf->predict_and_observe(sensor_time, OBSERVATION_ECEF_VEL, { ecef_vel }, { ecef_vel_R }); +} + +void Localizer::handle_car_state(double current_time, const cereal::CarState::Reader& log) { + this->car_speed = std::abs(log.getVEgo()); + this->standstill = log.getStandstill(); + if (this->standstill) { + this->kf->predict_and_observe(current_time, OBSERVATION_NO_ROT, { Vector3d(0.0, 0.0, 0.0) }); + this->kf->predict_and_observe(current_time, OBSERVATION_NO_ACCEL, { Vector3d(0.0, 0.0, 0.0) }); + } +} + +void Localizer::handle_cam_odo(double current_time, const cereal::CameraOdometry::Reader& log) { + VectorXd rot_device = this->device_from_calib * floatlist2vector(log.getRot()); + VectorXd trans_device = this->device_from_calib * floatlist2vector(log.getTrans()); + + if (!this->is_timestamp_valid(current_time)) { + this->observation_timings_invalid = true; + return; + } + + if ((rot_device.norm() > ROTATION_SANITY_CHECK) || (trans_device.norm() > TRANS_SANITY_CHECK)) { + this->observation_values_invalid["cameraOdometry"] += 1.0; + return; + } + + VectorXd rot_calib_std = floatlist2vector(log.getRotStd()); + VectorXd trans_calib_std = floatlist2vector(log.getTransStd()); + + if ((rot_calib_std.minCoeff() <= MIN_STD_SANITY_CHECK) || (trans_calib_std.minCoeff() <= MIN_STD_SANITY_CHECK)) { + this->observation_values_invalid["cameraOdometry"] += 1.0; + return; + } + + if ((rot_calib_std.norm() > 10 * ROTATION_SANITY_CHECK) || (trans_calib_std.norm() > 10 * TRANS_SANITY_CHECK)) { + this->observation_values_invalid["cameraOdometry"] += 1.0; + return; + } + + this->posenet_stds.pop_front(); + this->posenet_stds.push_back(trans_calib_std[0]); + + // Multiply by 10 to avoid to high certainty in kalman filter because of temporally correlated noise + trans_calib_std *= 10.0; + rot_calib_std *= 10.0; + MatrixXdr rot_device_cov = rotate_std(this->device_from_calib, rot_calib_std).array().square().matrix().asDiagonal(); + MatrixXdr trans_device_cov = rotate_std(this->device_from_calib, trans_calib_std).array().square().matrix().asDiagonal(); + this->kf->predict_and_observe(current_time, OBSERVATION_CAMERA_ODO_ROTATION, + { rot_device }, { rot_device_cov }); + this->kf->predict_and_observe(current_time, OBSERVATION_CAMERA_ODO_TRANSLATION, + { trans_device }, { trans_device_cov }); + this->observation_values_invalid["cameraOdometry"] *= DECAY; + this->camodo_yawrate_distribution = Vector2d(rot_device[2], rotate_std(this->device_from_calib, rot_calib_std)[2]); +} + +void Localizer::handle_live_calib(double current_time, const cereal::LiveCalibrationData::Reader& log) { + if (!this->is_timestamp_valid(current_time)) { + this->observation_timings_invalid = true; + return; + } + + if (log.getRpyCalib().size() > 0) { + auto live_calib = floatlist2vector(log.getRpyCalib()); + if ((live_calib.minCoeff() < -CALIB_RPY_SANITY_CHECK) || (live_calib.maxCoeff() > CALIB_RPY_SANITY_CHECK)) { + this->observation_values_invalid["liveCalibration"] += 1.0; + return; + } + + this->calib = live_calib; + this->device_from_calib = euler2rot(this->calib); + this->calib_from_device = this->device_from_calib.transpose(); + this->calibrated = log.getCalStatus() == cereal::LiveCalibrationData::Status::CALIBRATED; + this->observation_values_invalid["liveCalibration"] *= DECAY; + } +} + +void Localizer::reset_kalman(double current_time) { + const VectorXd &init_x = this->kf->get_initial_x(); + const MatrixXdr &init_P = this->kf->get_initial_P(); + this->reset_kalman(current_time, init_x, init_P); +} + +void Localizer::finite_check(double current_time) { + bool all_finite = this->kf->get_x().array().isFinite().all() or this->kf->get_P().array().isFinite().all(); + if (!all_finite) { + LOGE("Non-finite values detected, kalman reset"); + this->reset_kalman(current_time); + } +} + +void Localizer::time_check(double current_time) { + if (std::isnan(this->last_reset_time)) { + this->last_reset_time = current_time; + } + if (std::isnan(this->first_valid_log_time)) { + this->first_valid_log_time = current_time; + } + double filter_time = this->kf->get_filter_time(); + bool big_time_gap = !std::isnan(filter_time) && (current_time - filter_time > 10); + if (big_time_gap) { + LOGE("Time gap of over 10s detected, kalman reset"); + this->reset_kalman(current_time); + } +} + +void Localizer::update_reset_tracker() { + // reset tracker is tuned to trigger when over 1reset/10s over 2min period + if (this->is_gps_ok()) { + this->reset_tracker *= RESET_TRACKER_DECAY; + } else { + this->reset_tracker = 0.0; + } +} + +void Localizer::reset_kalman(double current_time, const VectorXd &init_orient, const VectorXd &init_pos, const VectorXd &init_vel, const MatrixXdr &init_pos_R, const MatrixXdr &init_vel_R) { + // too nonlinear to init on completely wrong + VectorXd current_x = this->kf->get_x(); + MatrixXdr current_P = this->kf->get_P(); + MatrixXdr init_P = this->kf->get_initial_P(); + const MatrixXdr &reset_orientation_P = this->kf->get_reset_orientation_P(); + int non_ecef_state_err_len = init_P.rows() - (STATE_ECEF_POS_ERR_LEN + STATE_ECEF_ORIENTATION_ERR_LEN + STATE_ECEF_VELOCITY_ERR_LEN); + + current_x.segment(STATE_ECEF_ORIENTATION_START) = init_orient; + current_x.segment(STATE_ECEF_VELOCITY_START) = init_vel; + current_x.segment(STATE_ECEF_POS_START) = init_pos; + + init_P.block(STATE_ECEF_POS_ERR_START, STATE_ECEF_POS_ERR_START).diagonal() = init_pos_R.diagonal(); + init_P.block(STATE_ECEF_ORIENTATION_ERR_START, STATE_ECEF_ORIENTATION_ERR_START).diagonal() = reset_orientation_P.diagonal(); + init_P.block(STATE_ECEF_VELOCITY_ERR_START, STATE_ECEF_VELOCITY_ERR_START).diagonal() = init_vel_R.diagonal(); + init_P.block(STATE_ANGULAR_VELOCITY_ERR_START, STATE_ANGULAR_VELOCITY_ERR_START, non_ecef_state_err_len, non_ecef_state_err_len).diagonal() = current_P.block(STATE_ANGULAR_VELOCITY_ERR_START, + STATE_ANGULAR_VELOCITY_ERR_START, non_ecef_state_err_len, non_ecef_state_err_len).diagonal(); + + this->reset_kalman(current_time, current_x, init_P); +} + +void Localizer::reset_kalman(double current_time, const VectorXd &init_x, const MatrixXdr &init_P) { + this->kf->init_state(init_x, init_P, current_time); + this->last_reset_time = current_time; + this->reset_tracker += 1.0; +} + +void Localizer::handle_msg_bytes(const char *data, const size_t size) { + AlignedBuffer aligned_buf; + + capnp::FlatArrayMessageReader cmsg(aligned_buf.align(data, size)); + cereal::Event::Reader event = cmsg.getRoot(); + + this->handle_msg(event); +} + +void Localizer::handle_msg(const cereal::Event::Reader& log) { + double t = log.getLogMonoTime() * 1e-9; + this->time_check(t); + if (log.isAccelerometer()) { + this->handle_sensor(t, log.getAccelerometer()); + } else if (log.isGyroscope()) { + this->handle_sensor(t, log.getGyroscope()); + } else if (log.isGpsLocation()) { + this->handle_gps(t, log.getGpsLocation(), GPS_QUECTEL_SENSOR_TIME_OFFSET); + } else if (log.isGpsLocationExternal()) { + this->handle_gps(t, log.getGpsLocationExternal(), GPS_UBLOX_SENSOR_TIME_OFFSET); + //} else if (log.isGnssMeasurements()) { + // this->handle_gnss(t, log.getGnssMeasurements()); + } else if (log.isCarState()) { + this->handle_car_state(t, log.getCarState()); + } else if (log.isCameraOdometry()) { + this->handle_cam_odo(t, log.getCameraOdometry()); + } else if (log.isLiveCalibration()) { + this->handle_live_calib(t, log.getLiveCalibration()); + } + this->finite_check(); + this->update_reset_tracker(); +} + +kj::ArrayPtr Localizer::get_message_bytes(MessageBuilder& msg_builder, bool inputsOK, + bool sensorsOK, bool gpsOK, bool msgValid) { + cereal::Event::Builder evt = msg_builder.initEvent(); + evt.setValid(msgValid); + cereal::LiveLocationKalman::Builder liveLoc = evt.initLiveLocationKalman(); + this->build_live_location(liveLoc); + liveLoc.setSensorsOK(sensorsOK); + liveLoc.setGpsOK(gpsOK); + liveLoc.setInputsOK(inputsOK); + return msg_builder.toBytes(); +} + +bool Localizer::is_gps_ok() { + return (this->kf->get_filter_time() - this->last_gps_msg) < 2.0; +} + +bool Localizer::critical_services_valid(const std::map &critical_services) { + for (auto &kv : critical_services){ + if (kv.second >= INPUT_INVALID_THRESHOLD){ + return false; + } + } + return true; +} + +bool Localizer::is_timestamp_valid(double current_time) { + double filter_time = this->kf->get_filter_time(); + if (!std::isnan(filter_time) && ((filter_time - current_time) > MAX_FILTER_REWIND_TIME)) { + LOGE("Observation timestamp is older than the max rewind threshold of the filter"); + return false; + } + return true; +} + +void Localizer::determine_gps_mode(double current_time) { + // 1. If the pos_std is greater than what's not acceptable and localizer is in gps-mode, reset to no-gps-mode + // 2. If the pos_std is greater than what's not acceptable and localizer is in no-gps-mode, fake obs + // 3. If the pos_std is smaller than what's not acceptable, let gps-mode be whatever it is + VectorXd current_pos_std = this->kf->get_P().block(STATE_ECEF_POS_ERR_START, STATE_ECEF_POS_ERR_START).diagonal().array().sqrt(); + if (current_pos_std.norm() > SANE_GPS_UNCERTAINTY){ + if (this->gps_mode){ + this->gps_mode = false; + this->reset_kalman(current_time); + } else { + this->input_fake_gps_observations(current_time); + } + } +} + +void Localizer::configure_gnss_source(const LocalizerGnssSource &source) { + this->gnss_source = source; + if (source == LocalizerGnssSource::UBLOX) { + this->gps_std_factor = 10.0; + this->gps_variance_factor = 1.0; + this->gps_vertical_variance_factor = 1.0; + this->gps_time_offset = GPS_UBLOX_SENSOR_TIME_OFFSET; + } else { + this->gps_std_factor = 2.0; + this->gps_variance_factor = 0.0; + this->gps_vertical_variance_factor = 3.0; + this->gps_time_offset = GPS_QUECTEL_SENSOR_TIME_OFFSET; + } +} + +int Localizer::locationd_thread() { + Params params; + LocalizerGnssSource source; + const char* gps_location_socket; + if (params.getBool("UbloxAvailable")) { + source = LocalizerGnssSource::UBLOX; + gps_location_socket = "gpsLocationExternal"; + } else { + source = LocalizerGnssSource::QCOM; + gps_location_socket = "gpsLocation"; + } + + this->configure_gnss_source(source); + const std::initializer_list service_list = {gps_location_socket, "cameraOdometry", "liveCalibration", + "carState", "accelerometer", "gyroscope"}; + + SubMaster sm(service_list, {}, nullptr, {gps_location_socket}); + PubMaster pm({"liveLocationKalman"}); + + uint64_t cnt = 0; + bool filterInitialized = false; + const std::vector critical_input_services = {"cameraOdometry", "liveCalibration", "accelerometer", "gyroscope"}; + for (std::string service : critical_input_services) { + this->observation_values_invalid.insert({service, 0.0}); + } + + while (!do_exit) { + sm.update(); + if (filterInitialized){ + this->observation_timings_invalid_reset(); + for (const char* service : service_list) { + if (sm.updated(service) && sm.valid(service)){ + const cereal::Event::Reader log = sm[service]; + this->handle_msg(log); + } + } + } else { + filterInitialized = sm.allAliveAndValid(); + } + + const char* trigger_msg = "cameraOdometry"; + if (sm.updated(trigger_msg)) { + bool inputsOK = sm.allValid() && this->are_inputs_ok(); + bool gpsOK = this->is_gps_ok(); + bool sensorsOK = sm.allAliveAndValid({"accelerometer", "gyroscope"}); + + // Log time to first fix + if (gpsOK && std::isnan(this->ttff) && !std::isnan(this->first_valid_log_time)) { + this->ttff = std::max(1e-3, (sm[trigger_msg].getLogMonoTime() * 1e-9) - this->first_valid_log_time); + } + + MessageBuilder msg_builder; + kj::ArrayPtr bytes = this->get_message_bytes(msg_builder, inputsOK, sensorsOK, gpsOK, filterInitialized); + pm.send("liveLocationKalman", bytes.begin(), bytes.size()); + + if (cnt % 1200 == 0 && gpsOK) { // once a minute + VectorXd posGeo = this->get_position_geodetic(); + std::string lastGPSPosJSON = util::string_format( + "{\"latitude\": %.15f, \"longitude\": %.15f, \"altitude\": %.15f}", posGeo(0), posGeo(1), posGeo(2)); + params.putNonBlocking("LastGPSPositionLLK", lastGPSPosJSON); + } + cnt++; + } + } + return 0; +} + +int main() { + util::set_realtime_priority(5); + + Localizer localizer; + return localizer.locationd_thread(); +} diff --git a/openpilot/sunnypilot/selfdrive/locationd/locationd.h b/openpilot/sunnypilot/selfdrive/locationd/locationd.h new file mode 100644 index 0000000000..a6ce697f30 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/locationd/locationd.h @@ -0,0 +1,100 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "cereal/messaging/messaging.h" +#include "common/params.h" +#include "common/swaglog.h" +#include "common/timing.h" +#include "common/util.h" + +#include "sunnypilot/common/transformations/coordinates.hpp" +#include "sunnypilot/common/transformations/orientation.hpp" +#include "sunnypilot/system/sensord/sensors/constants.h" +#include "sunnypilot/selfdrive/locationd/models/live_kf.h" + +#define VISION_DECIMATION 2 +#define SENSOR_DECIMATION 10 +#define POSENET_STD_HIST_HALF 20 + +enum LocalizerGnssSource { + UBLOX, QCOM +}; + +class Localizer { +public: + Localizer(LocalizerGnssSource gnss_source = LocalizerGnssSource::UBLOX); + + int locationd_thread(); + + void reset_kalman(double current_time = NAN); + void reset_kalman(double current_time, const Eigen::VectorXd &init_orient, const Eigen::VectorXd &init_pos, const Eigen::VectorXd &init_vel, const MatrixXdr &init_pos_R, const MatrixXdr &init_vel_R); + void reset_kalman(double current_time, const Eigen::VectorXd &init_x, const MatrixXdr &init_P); + void finite_check(double current_time = NAN); + void time_check(double current_time = NAN); + void update_reset_tracker(); + bool is_gps_ok(); + bool critical_services_valid(const std::map &critical_services); + bool is_timestamp_valid(double current_time); + void determine_gps_mode(double current_time); + bool are_inputs_ok(); + void observation_timings_invalid_reset(); + + kj::ArrayPtr get_message_bytes(MessageBuilder& msg_builder, + bool inputsOK, bool sensorsOK, bool gpsOK, bool msgValid); + void build_live_location(cereal::LiveLocationKalman::Builder& fix); + + Eigen::VectorXd get_position_geodetic(); + Eigen::VectorXd get_state(); + Eigen::VectorXd get_stdev(); + + void handle_msg_bytes(const char *data, const size_t size); + void handle_msg(const cereal::Event::Reader& log); + void handle_sensor(double current_time, const cereal::SensorEventData::Reader& log); + void handle_gps(double current_time, const cereal::GpsLocationData::Reader& log, const double sensor_time_offset); + void handle_gnss(double current_time, const cereal::GnssMeasurements::Reader& log); + void handle_car_state(double current_time, const cereal::CarState::Reader& log); + void handle_cam_odo(double current_time, const cereal::CameraOdometry::Reader& log); + void handle_live_calib(double current_time, const cereal::LiveCalibrationData::Reader& log); + + void input_fake_gps_observations(double current_time); + +private: + std::unique_ptr kf; + + Eigen::VectorXd calib; + MatrixXdr device_from_calib; + MatrixXdr calib_from_device; + bool calibrated = false; + + double car_speed = 0.0; + double last_reset_time = NAN; + std::deque posenet_stds; + + std::unique_ptr converter; + + int64_t unix_timestamp_millis = 0; + double reset_tracker = 0.0; + bool device_fell = false; + bool gps_mode = false; + double first_valid_log_time = NAN; + double ttff = NAN; + double last_gps_msg = 0; + LocalizerGnssSource gnss_source; + bool observation_timings_invalid = false; + std::map observation_values_invalid; + bool standstill = true; + int32_t orientation_reset_count = 0; + float gps_std_factor; + float gps_variance_factor; + float gps_vertical_variance_factor; + double gps_time_offset; + Eigen::VectorXd camodo_yawrate_distribution = Eigen::Vector2d(0.0, 10.0); // mean, std + + void configure_gnss_source(const LocalizerGnssSource &source); +}; diff --git a/openpilot/sunnypilot/selfdrive/locationd/models/.gitignore b/openpilot/sunnypilot/selfdrive/locationd/models/.gitignore new file mode 100644 index 0000000000..9ab870da89 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/locationd/models/.gitignore @@ -0,0 +1 @@ +generated/ diff --git a/system/camerad/__init__.py b/openpilot/sunnypilot/selfdrive/locationd/models/__init__.py similarity index 100% rename from system/camerad/__init__.py rename to openpilot/sunnypilot/selfdrive/locationd/models/__init__.py diff --git a/openpilot/sunnypilot/selfdrive/locationd/models/car_kf.py b/openpilot/sunnypilot/selfdrive/locationd/models/car_kf.py new file mode 100755 index 0000000000..9964cab973 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/locationd/models/car_kf.py @@ -0,0 +1,180 @@ +#!/usr/bin/env python3 +import math +import sys +from typing import Any + +import numpy as np + +from openpilot.common.constants import ACCELERATION_DUE_TO_GRAVITY +from openpilot.sunnypilot.selfdrive.locationd.models.constants import ObservationKind +from openpilot.common.swaglog import cloudlog + +from rednose.helpers.kalmanfilter import KalmanFilter + +if __name__ == '__main__': # Generating sympy + import sympy as sp + from rednose.helpers.ekf_sym import gen_code +else: + from rednose.helpers.ekf_sym_pyx import EKF_sym_pyx + + +i = 0 + +def _slice(n): + global i + s = slice(i, i + n) + i += n + + return s + + +class States: + # Vehicle model params + STIFFNESS = _slice(1) # [-] + STEER_RATIO = _slice(1) # [-] + ANGLE_OFFSET = _slice(1) # [rad] + ANGLE_OFFSET_FAST = _slice(1) # [rad] + + VELOCITY = _slice(2) # (x, y) [m/s] + YAW_RATE = _slice(1) # [rad/s] + STEER_ANGLE = _slice(1) # [rad] + ROAD_ROLL = _slice(1) # [rad] + + +class CarKalman(KalmanFilter): + name = 'car' + + initial_x = np.array([ + 1.0, + 15.0, + 0.0, + 0.0, + + 10.0, 0.0, + 0.0, + 0.0, + 0.0 + ]) + + # process noise + Q = np.diag([ + (.05 / 100)**2, + .01**2, + math.radians(0.02)**2, + math.radians(0.25)**2, + + .1**2, .01**2, + math.radians(0.1)**2, + math.radians(0.1)**2, + math.radians(1)**2, + ]) + P_initial = Q.copy() + + obs_noise: dict[int, Any] = { + ObservationKind.STEER_ANGLE: np.atleast_2d(math.radians(0.05)**2), + ObservationKind.ANGLE_OFFSET_FAST: np.atleast_2d(math.radians(10.0)**2), + ObservationKind.ROAD_ROLL: np.atleast_2d(math.radians(1.0)**2), + ObservationKind.STEER_RATIO: np.atleast_2d(5.0**2), + ObservationKind.STIFFNESS: np.atleast_2d(0.5**2), + ObservationKind.ROAD_FRAME_X_SPEED: np.atleast_2d(0.1**2), + } + + global_vars = [ + 'mass', + 'rotational_inertia', + 'center_to_front', + 'center_to_rear', + 'stiffness_front', + 'stiffness_rear', + ] + + @staticmethod + def generate_code(generated_dir): + dim_state = CarKalman.initial_x.shape[0] + name = CarKalman.name + + # Linearized single-track lateral dynamics, equations 7.211-7.213 + # Massimo Guiggiani, The Science of Vehicle Dynamics: Handling, Braking, and Ride of Road and Race Cars + # Springer Cham, 2023. doi: https://doi.org/10.1007/978-3-031-06461-6 + + # globals + global_vars = [sp.Symbol(name) for name in CarKalman.global_vars] + m, j, aF, aR, cF_orig, cR_orig = global_vars + + # make functions and jacobians with sympy + # state variables + state_sym = sp.MatrixSymbol('state', dim_state, 1) + state = sp.Matrix(state_sym) + + # Vehicle model constants + sf = state[States.STIFFNESS, :][0, 0] + + cF, cR = sf * cF_orig, sf * cR_orig + angle_offset = state[States.ANGLE_OFFSET, :][0, 0] + angle_offset_fast = state[States.ANGLE_OFFSET_FAST, :][0, 0] + theta = state[States.ROAD_ROLL, :][0, 0] + sa = state[States.STEER_ANGLE, :][0, 0] + + sR = state[States.STEER_RATIO, :][0, 0] + u, v = state[States.VELOCITY, :] + r = state[States.YAW_RATE, :][0, 0] + + A = sp.Matrix(np.zeros((2, 2))) + A[0, 0] = -(cF + cR) / (m * u) + A[0, 1] = -(cF * aF - cR * aR) / (m * u) - u + A[1, 0] = -(cF * aF - cR * aR) / (j * u) + A[1, 1] = -(cF * aF**2 + cR * aR**2) / (j * u) + + B = sp.Matrix(np.zeros((2, 1))) + B[0, 0] = cF / m / sR + B[1, 0] = (cF * aF) / j / sR + + C = sp.Matrix(np.zeros((2, 1))) + C[0, 0] = ACCELERATION_DUE_TO_GRAVITY + C[1, 0] = 0 + + x = sp.Matrix([v, r]) # lateral velocity, yaw rate + x_dot = A * x + B * (sa - angle_offset - angle_offset_fast) - C * theta + + dt = sp.Symbol('dt') + state_dot = sp.Matrix(np.zeros((dim_state, 1))) + state_dot[States.VELOCITY.start + 1, 0] = x_dot[0] + state_dot[States.YAW_RATE.start, 0] = x_dot[1] + + # Basic descretization, 1st order integrator + # Can be pretty bad if dt is big + f_sym = state + dt * state_dot + + # + # Observation functions + # + obs_eqs = [ + [sp.Matrix([r]), ObservationKind.ROAD_FRAME_YAW_RATE, None], + [sp.Matrix([u, v]), ObservationKind.ROAD_FRAME_XY_SPEED, None], + [sp.Matrix([u]), ObservationKind.ROAD_FRAME_X_SPEED, None], + [sp.Matrix([sa]), ObservationKind.STEER_ANGLE, None], + [sp.Matrix([angle_offset_fast]), ObservationKind.ANGLE_OFFSET_FAST, None], + [sp.Matrix([sR]), ObservationKind.STEER_RATIO, None], + [sp.Matrix([sf]), ObservationKind.STIFFNESS, None], + [sp.Matrix([theta]), ObservationKind.ROAD_ROLL, None], + ] + + gen_code(generated_dir, name, f_sym, dt, state_sym, obs_eqs, dim_state, dim_state, global_vars=global_vars) + + def __init__(self, generated_dir): + dim_state, dim_state_err = CarKalman.initial_x.shape[0], CarKalman.P_initial.shape[0] + self.filter = EKF_sym_pyx(generated_dir, CarKalman.name, CarKalman.Q, CarKalman.initial_x, CarKalman.P_initial, + dim_state, dim_state_err, global_vars=CarKalman.global_vars, logger=cloudlog) + + def set_globals(self, mass, rotational_inertia, center_to_front, center_to_rear, stiffness_front, stiffness_rear): + self.filter.set_global("mass", mass) + self.filter.set_global("rotational_inertia", rotational_inertia) + self.filter.set_global("center_to_front", center_to_front) + self.filter.set_global("center_to_rear", center_to_rear) + self.filter.set_global("stiffness_front", stiffness_front) + self.filter.set_global("stiffness_rear", stiffness_rear) + + +if __name__ == "__main__": + generated_dir = sys.argv[2] + CarKalman.generate_code(generated_dir) diff --git a/openpilot/sunnypilot/selfdrive/locationd/models/constants.py b/openpilot/sunnypilot/selfdrive/locationd/models/constants.py new file mode 100644 index 0000000000..6d328ce6f5 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/locationd/models/constants.py @@ -0,0 +1,92 @@ +import os + +GENERATED_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), 'generated')) + +class ObservationKind: + UNKNOWN = 0 + NO_OBSERVATION = 1 + GPS_NED = 2 + ODOMETRIC_SPEED = 3 + PHONE_GYRO = 4 + GPS_VEL = 5 + PSEUDORANGE_GPS = 6 + PSEUDORANGE_RATE_GPS = 7 + SPEED = 8 + NO_ROT = 9 + PHONE_ACCEL = 10 + ORB_POINT = 11 + ECEF_POS = 12 + CAMERA_ODO_TRANSLATION = 13 + CAMERA_ODO_ROTATION = 14 + ORB_FEATURES = 15 + MSCKF_TEST = 16 + FEATURE_TRACK_TEST = 17 + LANE_PT = 18 + IMU_FRAME = 19 + PSEUDORANGE_GLONASS = 20 + PSEUDORANGE_RATE_GLONASS = 21 + PSEUDORANGE = 22 + PSEUDORANGE_RATE = 23 + ECEF_VEL = 35 + ECEF_ORIENTATION_FROM_GPS = 32 + NO_ACCEL = 33 + ORB_FEATURES_WIDE = 34 + + ROAD_FRAME_XY_SPEED = 24 # (x, y) [m/s] + ROAD_FRAME_YAW_RATE = 25 # [rad/s] + STEER_ANGLE = 26 # [rad] + ANGLE_OFFSET_FAST = 27 # [rad] + STIFFNESS = 28 # [-] + STEER_RATIO = 29 # [-] + ROAD_FRAME_X_SPEED = 30 # (x) [m/s] + ROAD_ROLL = 31 # [rad] + + names = [ + 'Unknown', + 'No observation', + 'GPS NED', + 'Odometric speed', + 'Phone gyro', + 'GPS velocity', + 'GPS pseudorange', + 'GPS pseudorange rate', + 'Speed', + 'No rotation', + 'Phone acceleration', + 'ORB point', + 'ECEF pos', + 'camera odometric translation', + 'camera odometric rotation', + 'ORB features', + 'MSCKF test', + 'Feature track test', + 'Lane ecef point', + 'imu frame eulers', + 'GLONASS pseudorange', + 'GLONASS pseudorange rate', + 'pseudorange', + 'pseudorange rate', + + 'Road Frame x,y speed', + 'Road Frame yaw rate', + 'Steer Angle', + 'Fast Angle Offset', + 'Stiffness', + 'Steer Ratio', + 'Road Frame x speed', + 'Road Roll', + 'ECEF orientation from GPS', + 'NO accel', + 'ORB features wide camera', + 'ECEF_VEL', + ] + + @classmethod + def to_string(cls, kind): + return cls.names[kind] + + +SAT_OBS = [ObservationKind.PSEUDORANGE_GPS, + ObservationKind.PSEUDORANGE_RATE_GPS, + ObservationKind.PSEUDORANGE_GLONASS, + ObservationKind.PSEUDORANGE_RATE_GLONASS] diff --git a/openpilot/sunnypilot/selfdrive/locationd/models/live_kf.cc b/openpilot/sunnypilot/selfdrive/locationd/models/live_kf.cc new file mode 100644 index 0000000000..7ef6be638e --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/locationd/models/live_kf.cc @@ -0,0 +1,122 @@ +#include "sunnypilot/selfdrive/locationd/models/live_kf.h" + +using namespace EKFS; +using namespace Eigen; + +Eigen::Map get_mapvec(const Eigen::VectorXd &vec) { + return Eigen::Map((double*)vec.data(), vec.rows(), vec.cols()); +} + +Eigen::Map get_mapmat(const MatrixXdr &mat) { + return Eigen::Map((double*)mat.data(), mat.rows(), mat.cols()); +} + +std::vector> get_vec_mapvec(const std::vector &vec_vec) { + std::vector> res; + for (const Eigen::VectorXd &vec : vec_vec) { + res.push_back(get_mapvec(vec)); + } + return res; +} + +std::vector> get_vec_mapmat(const std::vector &mat_vec) { + std::vector> res; + for (const MatrixXdr &mat : mat_vec) { + res.push_back(get_mapmat(mat)); + } + return res; +} + +LiveKalman::LiveKalman() { + this->dim_state = live_initial_x.rows(); + this->dim_state_err = live_initial_P_diag.rows(); + + this->initial_x = live_initial_x; + this->initial_P = live_initial_P_diag.asDiagonal(); + this->fake_gps_pos_cov = live_fake_gps_pos_cov_diag.asDiagonal(); + this->fake_gps_vel_cov = live_fake_gps_vel_cov_diag.asDiagonal(); + this->reset_orientation_P = live_reset_orientation_diag.asDiagonal(); + this->Q = live_Q_diag.asDiagonal(); + for (auto& pair : live_obs_noise_diag) { + this->obs_noise[pair.first] = pair.second.asDiagonal(); + } + + // init filter + this->filter = std::make_shared(this->name, get_mapmat(this->Q), get_mapvec(this->initial_x), + get_mapmat(initial_P), this->dim_state, this->dim_state_err, 0, 0, 0, std::vector(), + std::vector{3}, std::vector(), 0.8); +} + +void LiveKalman::init_state(const VectorXd &state, const VectorXd &covs_diag, double filter_time) { + MatrixXdr covs = covs_diag.asDiagonal(); + this->filter->init_state(get_mapvec(state), get_mapmat(covs), filter_time); +} + +void LiveKalman::init_state(const VectorXd &state, const MatrixXdr &covs, double filter_time) { + this->filter->init_state(get_mapvec(state), get_mapmat(covs), filter_time); +} + +void LiveKalman::init_state(const VectorXd &state, double filter_time) { + MatrixXdr covs = this->filter->covs(); + this->filter->init_state(get_mapvec(state), get_mapmat(covs), filter_time); +} + +VectorXd LiveKalman::get_x() { + return this->filter->state(); +} + +MatrixXdr LiveKalman::get_P() { + return this->filter->covs(); +} + +double LiveKalman::get_filter_time() { + return this->filter->get_filter_time(); +} + +std::vector LiveKalman::get_R(int kind, int n) { + std::vector R; + for (int i = 0; i < n; i++) { + R.push_back(this->obs_noise[kind]); + } + return R; +} + +std::optional LiveKalman::predict_and_observe(double t, int kind, const std::vector &meas, std::vector R) { + std::optional r; + if (R.size() == 0) { + R = this->get_R(kind, meas.size()); + } + r = this->filter->predict_and_update_batch(t, kind, get_vec_mapvec(meas), get_vec_mapmat(R)); + return r; +} + +void LiveKalman::predict(double t) { + this->filter->predict(t); +} + +const Eigen::VectorXd &LiveKalman::get_initial_x() { + return this->initial_x; +} + +const MatrixXdr &LiveKalman::get_initial_P() { + return this->initial_P; +} + +const MatrixXdr &LiveKalman::get_fake_gps_pos_cov() { + return this->fake_gps_pos_cov; +} + +const MatrixXdr &LiveKalman::get_fake_gps_vel_cov() { + return this->fake_gps_vel_cov; +} + +const MatrixXdr &LiveKalman::get_reset_orientation_P() { + return this->reset_orientation_P; +} + +MatrixXdr LiveKalman::H(const VectorXd &in) { + assert(in.size() == 6); + Matrix res; + this->filter->get_extra_routine("H")((double*)in.data(), res.data()); + return res; +} diff --git a/openpilot/sunnypilot/selfdrive/locationd/models/live_kf.h b/openpilot/sunnypilot/selfdrive/locationd/models/live_kf.h new file mode 100644 index 0000000000..e4b3e326b3 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/locationd/models/live_kf.h @@ -0,0 +1,66 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include + +#include "generated/live_kf_constants.h" +#include "rednose/helpers/ekf_sym.h" + +#define EARTH_GM 3.986005e14 // m^3/s^2 (gravitational constant * mass of earth) + +using namespace EKFS; + +Eigen::Map get_mapvec(const Eigen::VectorXd &vec); +Eigen::Map get_mapmat(const MatrixXdr &mat); +std::vector> get_vec_mapvec(const std::vector &vec_vec); +std::vector> get_vec_mapmat(const std::vector &mat_vec); + +class LiveKalman { +public: + LiveKalman(); + + void init_state(const Eigen::VectorXd &state, const Eigen::VectorXd &covs_diag, double filter_time); + void init_state(const Eigen::VectorXd &state, const MatrixXdr &covs, double filter_time); + void init_state(const Eigen::VectorXd &state, double filter_time); + + Eigen::VectorXd get_x(); + MatrixXdr get_P(); + double get_filter_time(); + std::vector get_R(int kind, int n); + + std::optional predict_and_observe(double t, int kind, const std::vector &meas, std::vector R = {}); + std::optional predict_and_update_odo_speed(std::vector speed, double t, int kind); + std::optional predict_and_update_odo_trans(std::vector trans, double t, int kind); + std::optional predict_and_update_odo_rot(std::vector rot, double t, int kind); + void predict(double t); + + const Eigen::VectorXd &get_initial_x(); + const MatrixXdr &get_initial_P(); + const MatrixXdr &get_fake_gps_pos_cov(); + const MatrixXdr &get_fake_gps_vel_cov(); + const MatrixXdr &get_reset_orientation_P(); + + MatrixXdr H(const Eigen::VectorXd &in); + +private: + std::string name = "live"; + + std::shared_ptr filter; + + int dim_state; + int dim_state_err; + + Eigen::VectorXd initial_x; + MatrixXdr initial_P; + MatrixXdr fake_gps_pos_cov; + MatrixXdr fake_gps_vel_cov; + MatrixXdr reset_orientation_P; + MatrixXdr Q; // process noise + std::unordered_map obs_noise; +}; diff --git a/openpilot/sunnypilot/selfdrive/locationd/models/live_kf.py b/openpilot/sunnypilot/selfdrive/locationd/models/live_kf.py new file mode 100755 index 0000000000..e5626b8f28 --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/locationd/models/live_kf.py @@ -0,0 +1,242 @@ +#!/usr/bin/env python3 + +import sys +import os +import numpy as np + +from openpilot.sunnypilot.selfdrive.locationd.models.constants import ObservationKind + +import sympy as sp +import inspect +from rednose.helpers.sympy_helpers import euler_rotate, quat_matrix_r, quat_rotate +from rednose.helpers.ekf_sym import gen_code + +EARTH_GM = 3.986005e14 # m^3/s^2 (gravitational constant * mass of earth) + + +def numpy2eigenstring(arr): + assert(len(arr.shape) == 1) + arr_str = np.array2string(arr, precision=20, separator=',')[1:-1].replace(' ', '').replace('\n', '') + return f"(Eigen::VectorXd({len(arr)}) << {arr_str}).finished()" + + +class States: + ECEF_POS = slice(0, 3) # x, y and z in ECEF in meters + ECEF_ORIENTATION = slice(3, 7) # quat for pose of phone in ecef + ECEF_VELOCITY = slice(7, 10) # ecef velocity in m/s + ANGULAR_VELOCITY = slice(10, 13) # roll, pitch and yaw rates in device frame in radians/s + GYRO_BIAS = slice(13, 16) # roll, pitch and yaw biases + ACCELERATION = slice(16, 19) # Acceleration in device frame in m/s**2 + ACC_BIAS = slice(19, 22) # Acceletometer bias in m/s**2 + + # Error-state has different slices because it is an ESKF + ECEF_POS_ERR = slice(0, 3) + ECEF_ORIENTATION_ERR = slice(3, 6) # euler angles for orientation error + ECEF_VELOCITY_ERR = slice(6, 9) + ANGULAR_VELOCITY_ERR = slice(9, 12) + GYRO_BIAS_ERR = slice(12, 15) + ACCELERATION_ERR = slice(15, 18) + ACC_BIAS_ERR = slice(18, 21) + + +class LiveKalman: + name = 'live' + + initial_x = np.array([3.88e6, -3.37e6, 3.76e6, + 0.42254641, -0.31238054, -0.83602975, -0.15788347, # NED [0,0,0] -> ECEF Quat + 0, 0, 0, + 0, 0, 0, + 0, 0, 0, + 0, 0, 0, + 0, 0, 0]) + + # state covariance + initial_P_diag = np.array([10**2, 10**2, 10**2, + 0.01**2, 0.01**2, 0.01**2, + 10**2, 10**2, 10**2, + 1**2, 1**2, 1**2, + 1**2, 1**2, 1**2, + 100**2, 100**2, 100**2, + 0.01**2, 0.01**2, 0.01**2]) + + # state covariance when resetting midway in a segment + reset_orientation_diag = np.array([1**2, 1**2, 1**2]) + + # fake observation covariance, to ensure the uncertainty estimate of the filter is under control + fake_gps_pos_cov_diag = np.array([1000**2, 1000**2, 1000**2]) + fake_gps_vel_cov_diag = np.array([10**2, 10**2, 10**2]) + + # process noise + Q_diag = np.array([0.03**2, 0.03**2, 0.03**2, + 0.001**2, 0.001**2, 0.001**2, + 0.01**2, 0.01**2, 0.01**2, + 0.1**2, 0.1**2, 0.1**2, + (0.005 / 100)**2, (0.005 / 100)**2, (0.005 / 100)**2, + 3**2, 3**2, 3**2, + 0.005**2, 0.005**2, 0.005**2]) + + obs_noise_diag = {ObservationKind.PHONE_GYRO: np.array([0.025**2, 0.025**2, 0.025**2]), + ObservationKind.PHONE_ACCEL: np.array([.5**2, .5**2, .5**2]), + ObservationKind.CAMERA_ODO_ROTATION: np.array([0.05**2, 0.05**2, 0.05**2]), + ObservationKind.NO_ROT: np.array([0.005**2, 0.005**2, 0.005**2]), + ObservationKind.NO_ACCEL: np.array([0.05**2, 0.05**2, 0.05**2]), + ObservationKind.ECEF_POS: np.array([5**2, 5**2, 5**2]), + ObservationKind.ECEF_VEL: np.array([.5**2, .5**2, .5**2]), + ObservationKind.ECEF_ORIENTATION_FROM_GPS: np.array([.2**2, .2**2, .2**2, .2**2])} + + @staticmethod + def generate_code(generated_dir): + name = LiveKalman.name + dim_state = LiveKalman.initial_x.shape[0] + dim_state_err = LiveKalman.initial_P_diag.shape[0] + + state_sym = sp.MatrixSymbol('state', dim_state, 1) + state = sp.Matrix(state_sym) + x, y, z = state[States.ECEF_POS, :] + q = state[States.ECEF_ORIENTATION, :] + v = state[States.ECEF_VELOCITY, :] + vx, vy, vz = v + omega = state[States.ANGULAR_VELOCITY, :] + vroll, vpitch, vyaw = omega + roll_bias, pitch_bias, yaw_bias = state[States.GYRO_BIAS, :] + acceleration = state[States.ACCELERATION, :] + acc_bias = state[States.ACC_BIAS, :] + + dt = sp.Symbol('dt') + + # calibration and attitude rotation matrices + quat_rot = quat_rotate(*q) + + # Got the quat predict equations from here + # A New Quaternion-Based Kalman Filter for + # Real-Time Attitude Estimation Using the Two-Step + # Geometrically-Intuitive Correction Algorithm + A = 0.5 * sp.Matrix([[0, -vroll, -vpitch, -vyaw], + [vroll, 0, vyaw, -vpitch], + [vpitch, -vyaw, 0, vroll], + [vyaw, vpitch, -vroll, 0]]) + q_dot = A * q + + # Time derivative of the state as a function of state + state_dot = sp.Matrix(np.zeros((dim_state, 1))) + state_dot[States.ECEF_POS, :] = v + state_dot[States.ECEF_ORIENTATION, :] = q_dot + state_dot[States.ECEF_VELOCITY, 0] = quat_rot * acceleration + + # Basic descretization, 1st order intergrator + # Can be pretty bad if dt is big + f_sym = state + dt * state_dot + + state_err_sym = sp.MatrixSymbol('state_err', dim_state_err, 1) + state_err = sp.Matrix(state_err_sym) + quat_err = state_err[States.ECEF_ORIENTATION_ERR, :] + v_err = state_err[States.ECEF_VELOCITY_ERR, :] + omega_err = state_err[States.ANGULAR_VELOCITY_ERR, :] + acceleration_err = state_err[States.ACCELERATION_ERR, :] + + # Time derivative of the state error as a function of state error and state + quat_err_matrix = euler_rotate(quat_err[0], quat_err[1], quat_err[2]) + q_err_dot = quat_err_matrix * quat_rot * (omega + omega_err) + state_err_dot = sp.Matrix(np.zeros((dim_state_err, 1))) + state_err_dot[States.ECEF_POS_ERR, :] = v_err + state_err_dot[States.ECEF_ORIENTATION_ERR, :] = q_err_dot + state_err_dot[States.ECEF_VELOCITY_ERR, :] = quat_err_matrix * quat_rot * (acceleration + acceleration_err) + f_err_sym = state_err + dt * state_err_dot + + # Observation matrix modifier + H_mod_sym = sp.Matrix(np.zeros((dim_state, dim_state_err))) + H_mod_sym[States.ECEF_POS, States.ECEF_POS_ERR] = np.eye(States.ECEF_POS.stop - States.ECEF_POS.start) + H_mod_sym[States.ECEF_ORIENTATION, States.ECEF_ORIENTATION_ERR] = 0.5 * quat_matrix_r(state[3:7])[:, 1:] + H_mod_sym[States.ECEF_ORIENTATION.stop:, States.ECEF_ORIENTATION_ERR.stop:] = np.eye(dim_state - States.ECEF_ORIENTATION.stop) + + # these error functions are defined so that say there + # is a nominal x and true x: + # true x = err_function(nominal x, delta x) + # delta x = inv_err_function(nominal x, true x) + nom_x = sp.MatrixSymbol('nom_x', dim_state, 1) + true_x = sp.MatrixSymbol('true_x', dim_state, 1) + delta_x = sp.MatrixSymbol('delta_x', dim_state_err, 1) + + err_function_sym = sp.Matrix(np.zeros((dim_state, 1))) + delta_quat = sp.Matrix(np.ones(4)) + delta_quat[1:, :] = sp.Matrix(0.5 * delta_x[States.ECEF_ORIENTATION_ERR, :]) + err_function_sym[States.ECEF_POS, :] = sp.Matrix(nom_x[States.ECEF_POS, :] + delta_x[States.ECEF_POS_ERR, :]) + err_function_sym[States.ECEF_ORIENTATION, 0] = quat_matrix_r(nom_x[States.ECEF_ORIENTATION, 0]) * delta_quat + err_function_sym[States.ECEF_ORIENTATION.stop:, :] = sp.Matrix(nom_x[States.ECEF_ORIENTATION.stop:, :] + delta_x[States.ECEF_ORIENTATION_ERR.stop:, :]) + + inv_err_function_sym = sp.Matrix(np.zeros((dim_state_err, 1))) + inv_err_function_sym[States.ECEF_POS_ERR, 0] = sp.Matrix(-nom_x[States.ECEF_POS, 0] + true_x[States.ECEF_POS, 0]) + delta_quat = quat_matrix_r(nom_x[States.ECEF_ORIENTATION, 0]).T * true_x[States.ECEF_ORIENTATION, 0] + inv_err_function_sym[States.ECEF_ORIENTATION_ERR, 0] = sp.Matrix(2 * delta_quat[1:]) + inv_err_function_sym[States.ECEF_ORIENTATION_ERR.stop:, 0] = sp.Matrix(-nom_x[States.ECEF_ORIENTATION.stop:, 0] + true_x[States.ECEF_ORIENTATION.stop:, 0]) + + eskf_params = [[err_function_sym, nom_x, delta_x], + [inv_err_function_sym, nom_x, true_x], + H_mod_sym, f_err_sym, state_err_sym] + # + # Observation functions + # + h_gyro_sym = sp.Matrix([ + vroll + roll_bias, + vpitch + pitch_bias, + vyaw + yaw_bias]) + + pos = sp.Matrix([x, y, z]) + gravity = quat_rot.T * ((EARTH_GM / ((x**2 + y**2 + z**2)**(3.0 / 2.0))) * pos) + h_acc_sym = (gravity + acceleration + acc_bias) + h_acc_stationary_sym = acceleration + h_phone_rot_sym = sp.Matrix([vroll, vpitch, vyaw]) + h_pos_sym = sp.Matrix([x, y, z]) + h_vel_sym = sp.Matrix([vx, vy, vz]) + h_orientation_sym = q + h_relative_motion = sp.Matrix(quat_rot.T * v) + + obs_eqs = [[h_gyro_sym, ObservationKind.PHONE_GYRO, None], + [h_phone_rot_sym, ObservationKind.NO_ROT, None], + [h_acc_sym, ObservationKind.PHONE_ACCEL, None], + [h_pos_sym, ObservationKind.ECEF_POS, None], + [h_vel_sym, ObservationKind.ECEF_VEL, None], + [h_orientation_sym, ObservationKind.ECEF_ORIENTATION_FROM_GPS, None], + [h_relative_motion, ObservationKind.CAMERA_ODO_TRANSLATION, None], + [h_phone_rot_sym, ObservationKind.CAMERA_ODO_ROTATION, None], + [h_acc_stationary_sym, ObservationKind.NO_ACCEL, None]] + + # this returns a sympy routine for the jacobian of the observation function of the local vel + in_vec = sp.MatrixSymbol('in_vec', 6, 1) # roll, pitch, yaw, vx, vy, vz + h = euler_rotate(in_vec[0], in_vec[1], in_vec[2]).T * (sp.Matrix([in_vec[3], in_vec[4], in_vec[5]])) + extra_routines = [('H', h.jacobian(in_vec), [in_vec])] + + gen_code(generated_dir, name, f_sym, dt, state_sym, obs_eqs, dim_state, dim_state_err, eskf_params, extra_routines=extra_routines) + + # write constants to extra header file for use in cpp + live_kf_header = "#pragma once\n\n" + live_kf_header += "#include \n" + live_kf_header += "#include \n\n" + for state, slc in inspect.getmembers(States, lambda x: isinstance(x, slice)): + assert(slc.step is None) # unsupported + live_kf_header += f'#define STATE_{state}_START {slc.start}\n' + live_kf_header += f'#define STATE_{state}_END {slc.stop}\n' + live_kf_header += f'#define STATE_{state}_LEN {slc.stop - slc.start}\n' + live_kf_header += "\n" + + for kind, val in inspect.getmembers(ObservationKind, lambda x: isinstance(x, int)): + live_kf_header += f'#define OBSERVATION_{kind} {val}\n' + live_kf_header += "\n" + + live_kf_header += f"static const Eigen::VectorXd live_initial_x = {numpy2eigenstring(LiveKalman.initial_x)};\n" + live_kf_header += f"static const Eigen::VectorXd live_initial_P_diag = {numpy2eigenstring(LiveKalman.initial_P_diag)};\n" + live_kf_header += f"static const Eigen::VectorXd live_fake_gps_pos_cov_diag = {numpy2eigenstring(LiveKalman.fake_gps_pos_cov_diag)};\n" + live_kf_header += f"static const Eigen::VectorXd live_fake_gps_vel_cov_diag = {numpy2eigenstring(LiveKalman.fake_gps_vel_cov_diag)};\n" + live_kf_header += f"static const Eigen::VectorXd live_reset_orientation_diag = {numpy2eigenstring(LiveKalman.reset_orientation_diag)};\n" + live_kf_header += f"static const Eigen::VectorXd live_Q_diag = {numpy2eigenstring(LiveKalman.Q_diag)};\n" + live_kf_header += "static const std::unordered_map> live_obs_noise_diag = {\n" + for kind, noise in LiveKalman.obs_noise_diag.items(): + live_kf_header += f" {{ {kind}, {numpy2eigenstring(noise)} }},\n" + live_kf_header += "};\n\n" + + open(os.path.join(generated_dir, "live_kf_constants.h"), 'w').write(live_kf_header) + + +if __name__ == "__main__": + generated_dir = sys.argv[2] + LiveKalman.generate_code(generated_dir) diff --git a/selfdrive/locationd/test/.gitignore b/openpilot/sunnypilot/selfdrive/locationd/tests/.gitignore similarity index 100% rename from selfdrive/locationd/test/.gitignore rename to openpilot/sunnypilot/selfdrive/locationd/tests/.gitignore diff --git a/system/hardware/pc/__init__.py b/openpilot/sunnypilot/selfdrive/locationd/tests/__init__.py similarity index 100% rename from system/hardware/pc/__init__.py rename to openpilot/sunnypilot/selfdrive/locationd/tests/__init__.py diff --git a/openpilot/sunnypilot/selfdrive/locationd/tests/test_locationd.py b/openpilot/sunnypilot/selfdrive/locationd/tests/test_locationd.py new file mode 100644 index 0000000000..f81d1349aa --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/locationd/tests/test_locationd.py @@ -0,0 +1,93 @@ +import pytest +import platform +import json +import random +import time +import capnp + +import openpilot.cereal.messaging as messaging +from openpilot.cereal.services import SERVICE_LIST +from openpilot.common.params import Params +from openpilot.common.transformations.coordinates import ecef2geodetic + +from openpilot.system.manager.process_config import managed_processes + + +if platform.system() == 'Darwin': + pytest.skip("Skipping locationd test on macOS due to unsupported msgq.", allow_module_level=True) + + +class TestLocationdProc: + LLD_MSGS = ['gpsLocationExternal', 'cameraOdometry', 'carState', 'liveCalibration', + 'accelerometer', 'gyroscope'] + + def setup_method(self): + self.pm = messaging.PubMaster(self.LLD_MSGS) + + self.params = Params() + self.params.put_bool("UbloxAvailable", True) + managed_processes['locationd_llk'].start() + + def teardown_method(self): + managed_processes['locationd_llk'].stop() + + def get_msg(self, name, t): + try: + msg = messaging.new_message(name) + except capnp.lib.capnp.KjException: + msg = messaging.new_message(name, 0) + + if name == "gpsLocationExternal": + msg.gpsLocationExternal.flags = 1 + msg.gpsLocationExternal.hasFix = True + msg.gpsLocationExternal.verticalAccuracy = 1.0 + msg.gpsLocationExternal.speedAccuracy = 1.0 + msg.gpsLocationExternal.bearingAccuracyDeg = 1.0 + msg.gpsLocationExternal.vNED = [0.0, 0.0, 0.0] + msg.gpsLocationExternal.latitude = float(self.lat) + msg.gpsLocationExternal.longitude = float(self.lon) + msg.gpsLocationExternal.unixTimestampMillis = t * 1e6 + msg.gpsLocationExternal.altitude = float(self.alt) + #if name == "gnssMeasurements": + # msg.gnssMeasurements.measTime = t + # msg.gnssMeasurements.positionECEF.value = [self.x , self.y, self.z] + # msg.gnssMeasurements.positionECEF.std = [0,0,0] + # msg.gnssMeasurements.positionECEF.valid = True + # msg.gnssMeasurements.velocityECEF.value = [] + # msg.gnssMeasurements.velocityECEF.std = [0,0,0] + # msg.gnssMeasurements.velocityECEF.valid = True + elif name == 'cameraOdometry': + msg.cameraOdometry.rot = [0.0, 0.0, 0.0] + msg.cameraOdometry.rotStd = [0.0, 0.0, 0.0] + msg.cameraOdometry.trans = [0.0, 0.0, 0.0] + msg.cameraOdometry.transStd = [0.0, 0.0, 0.0] + msg.logMonoTime = t + msg.valid = True + return msg + + def test_params_gps(self): + random.seed(123489234) + self.params.remove('LastGPSPositionLLK') + + self.x = -2710700 + (random.random() * 1e5) + self.y = -4280600 + (random.random() * 1e5) + self.z = 3850300 + (random.random() * 1e5) + self.lat, self.lon, self.alt = ecef2geodetic([self.x, self.y, self.z]) + + # get fake messages at the correct frequency, listed in services.py + msgs = [] + for sec in range(65): + for name in self.LLD_MSGS: + for j in range(int(SERVICE_LIST[name].frequency)): + msgs.append(self.get_msg(name, int((sec + j / SERVICE_LIST[name].frequency) * 1e9))) + + for msg in sorted(msgs, key=lambda x: x.logMonoTime): + self.pm.send(msg.which(), msg) + if msg.which() == "cameraOdometry": + self.pm.wait_for_readers_to_update(msg.which(), timeout=1, dt=0.005) + time.sleep(1) # wait for async params write + + lastGPS = json.loads(self.params.get('LastGPSPositionLLK')) + assert lastGPS['latitude'] == pytest.approx(self.lat, abs=0.001) + assert lastGPS['longitude'] == pytest.approx(self.lon, abs=0.001) + assert lastGPS['altitude'] == pytest.approx(self.alt, abs=0.001) diff --git a/openpilot/sunnypilot/selfdrive/locationd/torqued_ext.py b/openpilot/sunnypilot/selfdrive/locationd/torqued_ext.py new file mode 100644 index 0000000000..f1f16f58ee --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/locationd/torqued_ext.py @@ -0,0 +1,65 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import numpy as np + +from opendbc.car.structs import car + +from openpilot.common.params import Params +from openpilot.common.realtime import DT_MDL +from openpilot.sunnypilot import PARAMS_UPDATE_PERIOD + +RELAXED_MIN_BUCKET_POINTS = np.array([1, 200, 300, 500, 500, 300, 200, 1]) + +ALLOWED_CARS = ['toyota', 'hyundai', 'rivian', 'honda'] + + +class TorqueEstimatorExt: + def __init__(self, CP: car.CarParams): + self.CP = CP + self._params = Params() + self.frame = -1 + + self.enforce_torque_control_toggle = self._params.get_bool("EnforceTorqueControl") # only during init + self.use_params = self.CP.brand in ALLOWED_CARS and self.CP.lateralTuning.which() == 'torque' + self.use_live_torque_params = self._params.get_bool("LiveTorqueParamsToggle") + self.custom_torque_params = self._params.get_bool("CustomTorqueParams") + self.torque_override_enabled = self._params.get_bool("TorqueParamsOverrideEnabled") + self.min_bucket_points = RELAXED_MIN_BUCKET_POINTS + self.factor_sanity = 0.0 + self.friction_sanity = 0.0 + self.offline_latAccelFactor = 0.0 + self.offline_friction = 0.0 + + def initialize_custom_params(self, decimated=False): + self.update_use_params() + + if self.enforce_torque_control_toggle: + if self._params.get_bool("LiveTorqueParamsRelaxedToggle"): + self.min_bucket_points = RELAXED_MIN_BUCKET_POINTS / (10 if decimated else 1) + self.factor_sanity = 0.5 if decimated else 1.0 + self.friction_sanity = 0.8 if decimated else 1.0 + + if self._params.get_bool("CustomTorqueParams"): + self.offline_latAccelFactor = float(self._params.get("TorqueParamsOverrideLatAccelFactor", return_default=True)) + self.offline_friction = float(self._params.get("TorqueParamsOverrideFriction", return_default=True)) + + def _update_params(self): + if self.frame % int(PARAMS_UPDATE_PERIOD / DT_MDL) == 0: + self.use_live_torque_params = self._params.get_bool("LiveTorqueParamsToggle") + self.custom_torque_params = self._params.get_bool("CustomTorqueParams") + self.torque_override_enabled = self._params.get_bool("TorqueParamsOverrideEnabled") + + def update_use_params(self): + self._update_params() + + if self.enforce_torque_control_toggle: + if self.custom_torque_params and self.torque_override_enabled: + self.use_params = False + else: + self.use_params = self.use_live_torque_params + + self.frame += 1 diff --git a/system/hardware/tests/__init__.py b/openpilot/sunnypilot/selfdrive/pandad/__init__.py similarity index 100% rename from system/hardware/tests/__init__.py rename to openpilot/sunnypilot/selfdrive/pandad/__init__.py diff --git a/openpilot/sunnypilot/selfdrive/pandad/rivian_long_flasher.py b/openpilot/sunnypilot/selfdrive/pandad/rivian_long_flasher.py new file mode 100755 index 0000000000..3be9fb0e4d --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/pandad/rivian_long_flasher.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python3 +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import os +from itertools import accumulate + +from openpilot.cereal import messaging +from opendbc.car.structs import car +from panda import Panda +from openpilot.common.params import Params +from openpilot.common.swaglog import cloudlog + +FW_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "rivian_long_fw.bin.signed") +SECTOR_SIZES = [0x4000] * 4 + [0x10000] + [0x20000] * 11 + + +def _is_rivian() -> bool: + params = Params() + + # check fixed fingerprint + if bundle := params.get("CarPlatformBundle"): + if bundle.get("brand") == "rivian": + return True + + # check cached fingerprint + CP_bytes = params.get("CarParamsPersistent") + if CP_bytes is not None: + CP = messaging.log_from_bytes(CP_bytes, car.CarParams) + if CP.brand == "rivian": + return True + + return False + + +def _flash_static(handle, code): + assert Panda.flasher_present(handle) + last_sector = next((i + 1 for i, v in enumerate(accumulate(SECTOR_SIZES[1:])) if v > len(code)), -1) + assert 1 <= last_sector < 7, "Invalid firmware size" + + handle.controlWrite(Panda.REQUEST_IN, 0xb1, 0, 0, b'') + for i in range(1, last_sector + 1): + handle.controlWrite(Panda.REQUEST_IN, 0xb2, i, 0, b'') + for i in range(0, len(code), 0x10): + handle.bulkWrite(2, code[i:i + 0x10]) + try: + handle.controlWrite(Panda.REQUEST_IN, 0xd8, 0, 0, b'', expect_disconnect=True) + except Exception: + pass + + +def _flash_panda(panda: Panda) -> None: + expected_sig = Panda.get_signature_from_firmware(FW_PATH) + if not panda.bootstub and panda.get_signature() == expected_sig: + cloudlog.info(f"F4 panda {panda.get_usb_serial()} already up to date") + return + + cloudlog.info(f"Flashing F4 panda {panda.get_usb_serial()}") + with open(FW_PATH, "rb") as f: + code = f.read() + + if not panda.bootstub: + # enter bootstub directly, panda.reset() rejects deprecated hw types + try: + panda._handle.controlWrite(Panda.REQUEST_IN, 0xd1, 1, 0, b'', timeout=15000, expect_disconnect=True) + except Exception: + pass + panda.close() + panda.reconnect() + + _flash_static(panda._handle, code) + panda.reconnect() + cloudlog.info(f"Successfully flashed xnor's Rivian Longitudinal Upgrade Kit: {panda.get_usb_serial()}") + + +def flash_rivian_long(panda_serials: list[str]) -> None: + if not os.path.isfile(FW_PATH): + cloudlog.error(f"Rivian longitudinal upgrade firmware not found at {FW_PATH}") + return + + if not _is_rivian(): + cloudlog.info("Not a Rivian, skipping longitudinal upgrade...") + return + + # only check USB connected pandas, internal panda uses SPI and is never an external panda + usb_serials = set(Panda.usb_list()) + for serial in panda_serials: + if serial not in usb_serials: + continue + panda = Panda(serial) + # only flash external black pandas (HW_TYPE_BLACK = 0x03) + if panda.get_type() == b'\x03' and not panda.is_internal(): + try: + _flash_panda(panda) + except Exception: + cloudlog.exception(f"Failed to flash xnor's Rivian Longitudinal Upgrade Kit: {serial}") + panda.close() + + return + + +if __name__ == '__main__': + flash_rivian_long(Panda.list()) diff --git a/openpilot/sunnypilot/selfdrive/pandad/rivian_long_fw.bin.signed b/openpilot/sunnypilot/selfdrive/pandad/rivian_long_fw.bin.signed new file mode 100644 index 0000000000..bdbd237ba9 Binary files /dev/null and b/openpilot/sunnypilot/selfdrive/pandad/rivian_long_fw.bin.signed differ diff --git a/system/hardware/tici/__init__.py b/openpilot/sunnypilot/selfdrive/selfdrived/__init__.py similarity index 100% rename from system/hardware/tici/__init__.py rename to openpilot/sunnypilot/selfdrive/selfdrived/__init__.py diff --git a/openpilot/sunnypilot/selfdrive/selfdrived/events.py b/openpilot/sunnypilot/selfdrive/selfdrived/events.py new file mode 100644 index 0000000000..2001d0dbee --- /dev/null +++ b/openpilot/sunnypilot/selfdrive/selfdrived/events.py @@ -0,0 +1,247 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import openpilot.cereal.messaging as messaging +from openpilot.cereal import log, custom +from opendbc.car.structs import car +from openpilot.common.constants import CV +from openpilot.sunnypilot.selfdrive.selfdrived.events_base import EventsBase, Priority, ET, Alert, \ + NoEntryAlert, ImmediateDisableAlert, EngagementAlert, NormalPermanentAlert, AlertCallbackType, wrong_car_mode_alert +from openpilot.sunnypilot.selfdrive.controls.lib.speed_limit import PCM_LONG_REQUIRED_MAX_SET_SPEED, CONFIRM_SPEED_THRESHOLD +from openpilot.common.hardware import HARDWARE + +AlertSize = log.SelfdriveState.AlertSize +AlertStatus = log.SelfdriveState.AlertStatus +VisualAlert = car.CarControl.HUDControl.VisualAlert +AudibleAlert = car.CarControl.HUDControl.AudibleAlert +AudibleAlertSP = custom.SelfdriveStateSP.AudibleAlert +EventNameSP = custom.OnroadEventSP.EventName + + +# get event name from enum +EVENT_NAME_SP = {v: k for k, v in EventNameSP.schema.enumerants.items()} + +IS_MICI = HARDWARE.get_device_type() == 'mici' + + +def speed_limit_adjust_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + speedLimit = sm['longitudinalPlanSP'].speedLimit.resolver.speedLimit + speed = round(speedLimit * (CV.MS_TO_KPH if metric else CV.MS_TO_MPH)) + message = f'Adjusting to {speed} {"km/h" if metric else "mph"} speed limit' + return Alert( + message, + "", + AlertStatus.normal, AlertSize.small, + Priority.LOW, VisualAlert.none, AudibleAlert.none, 4.) + + +def speed_limit_pre_active_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: + speed_conv = CV.MS_TO_KPH if metric else CV.MS_TO_MPH + v_cruise_cluster = CS.vCruiseCluster + set_speed = sm['controlsState'].deprecated.vCruise if v_cruise_cluster == 0.0 else v_cruise_cluster + set_speed_conv = round(set_speed * speed_conv) + + speed_limit_final_last = sm['longitudinalPlanSP'].speedLimit.resolver.speedLimitFinalLast + speed_limit_final_last_conv = round(speed_limit_final_last * speed_conv) + alert_1_str = "" + alert_size = AlertSize.small + + if CP.openpilotLongitudinalControl and CP.pcmCruise: + # PCM long + cst_low, cst_high = PCM_LONG_REQUIRED_MAX_SET_SPEED[metric] + pcm_long_required_max = cst_low if speed_limit_final_last_conv < CONFIRM_SPEED_THRESHOLD[metric] else cst_high + pcm_long_required_max_set_speed_conv = round(pcm_long_required_max * speed_conv) + speed_unit = "km/h" if metric else "mph" + + alert_1_str = f"Speed Limit Assist: set to {pcm_long_required_max_set_speed_conv} {speed_unit} to engage" + else: + if IS_MICI: + if set_speed_conv < speed_limit_final_last_conv: + alert_1_str = "Press + to confirm speed limit" + elif set_speed_conv > speed_limit_final_last_conv: + alert_1_str = "Press - to confirm speed limit" + else: + alert_size = AlertSize.none + + return Alert( + alert_1_str, + "", + AlertStatus.normal, alert_size, + Priority.LOW, VisualAlert.none, AudibleAlertSP.promptSingleLow, .1) + + +class EventsSP(EventsBase): + def __init__(self): + super().__init__() + self.event_counters = dict.fromkeys(EVENTS_SP.keys(), 0) + + def get_events_mapping(self) -> dict[int, dict[str, Alert | AlertCallbackType]]: + return EVENTS_SP + + def get_event_name(self, event: int): + return EVENT_NAME_SP[event] + + def get_event_msg_type(self): + return custom.OnroadEventSP.Event + + +EVENTS_SP: dict[int, dict[str, Alert | AlertCallbackType]] = { + # sunnypilot + EventNameSP.lkasEnable: { + ET.ENABLE: EngagementAlert(AudibleAlert.engage), + }, + + EventNameSP.lkasDisable: { + ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), + }, + + EventNameSP.manualSteeringRequired: { + ET.USER_DISABLE: Alert( + "Automatic Lane Centering is OFF", + "Manual Steering Required", + AlertStatus.normal, AlertSize.mid, + Priority.LOW, VisualAlert.none, AudibleAlert.disengage, 1.), + }, + + EventNameSP.manualLongitudinalRequired: { + ET.WARNING: Alert( + "Smart/Adaptive Cruise Control: OFF", + "Manual Speed Control Required", + AlertStatus.normal, AlertSize.mid, + Priority.LOW, VisualAlert.none, AudibleAlert.none, 1.), + }, + + EventNameSP.silentLkasEnable: { + ET.ENABLE: EngagementAlert(AudibleAlert.none), + }, + + EventNameSP.silentLkasDisable: { + ET.USER_DISABLE: EngagementAlert(AudibleAlert.none), + }, + + EventNameSP.silentBrakeHold: { + ET.WARNING: EngagementAlert(AudibleAlert.none), + ET.NO_ENTRY: NoEntryAlert("Brake Hold Active"), + }, + + EventNameSP.silentWrongGear: { + ET.WARNING: Alert( + "", + "", + AlertStatus.normal, AlertSize.none, + Priority.LOWEST, VisualAlert.none, AudibleAlert.none, 0.), + ET.NO_ENTRY: Alert( + "Gear not D", + "openpilot Unavailable", + AlertStatus.normal, AlertSize.mid, + Priority.LOW, VisualAlert.none, AudibleAlert.none, 0.), + }, + + EventNameSP.silentReverseGear: { + ET.PERMANENT: Alert( + "Reverse\nGear", + "", + AlertStatus.normal, AlertSize.full, + Priority.LOWEST, VisualAlert.none, AudibleAlert.none, .2, creation_delay=0.5), + ET.NO_ENTRY: NoEntryAlert("Reverse Gear"), + }, + + EventNameSP.silentDoorOpen: { + ET.WARNING: Alert( + "", + "", + AlertStatus.normal, AlertSize.none, + Priority.LOWEST, VisualAlert.none, AudibleAlert.none, 0.), + ET.NO_ENTRY: NoEntryAlert("Door Open"), + }, + + EventNameSP.silentSeatbeltNotLatched: { + ET.WARNING: Alert( + "", + "", + AlertStatus.normal, AlertSize.none, + Priority.LOWEST, VisualAlert.none, AudibleAlert.none, 0.), + ET.NO_ENTRY: NoEntryAlert("Seatbelt Unlatched"), + }, + + EventNameSP.silentParkBrake: { + ET.WARNING: Alert( + "", + "", + AlertStatus.normal, AlertSize.none, + Priority.LOWEST, VisualAlert.none, AudibleAlert.none, 0.), + ET.NO_ENTRY: NoEntryAlert("Parking Brake Engaged"), + }, + + EventNameSP.controlsMismatchLateral: { + ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("Controls Mismatch: Lateral"), + ET.NO_ENTRY: NoEntryAlert("Controls Mismatch: Lateral"), + }, + + EventNameSP.experimentalModeSwitched: { + ET.WARNING: NormalPermanentAlert("Experimental Mode Switched", duration=1.5) + }, + + EventNameSP.wrongCarModeAlertOnly: { + ET.WARNING: wrong_car_mode_alert, + }, + + EventNameSP.pedalPressedAlertOnly: { + ET.WARNING: NoEntryAlert("Pedal Pressed") + }, + + EventNameSP.laneTurnLeft: { + ET.WARNING: Alert( + "Turning Left", + "", + AlertStatus.normal, AlertSize.small, + Priority.LOW, VisualAlert.none, AudibleAlert.none, 1.), + }, + + EventNameSP.laneTurnRight: { + ET.WARNING: Alert( + "Turning Right", + "", + AlertStatus.normal, AlertSize.small, + Priority.LOW, VisualAlert.none, AudibleAlert.none, 1.), + }, + + EventNameSP.speedLimitActive: { + ET.WARNING: Alert( + "Auto adjusting to speed limit", + "", + AlertStatus.normal, AlertSize.small, + Priority.LOW, VisualAlert.none, AudibleAlertSP.promptSingleHigh, 5.), + }, + + EventNameSP.speedLimitChanged: { + ET.WARNING: Alert( + "Set speed changed", + "", + AlertStatus.normal, AlertSize.small, + Priority.LOW, VisualAlert.none, AudibleAlertSP.promptSingleHigh, 5.), + }, + + EventNameSP.speedLimitPreActive: { + ET.WARNING: speed_limit_pre_active_alert, + }, + + EventNameSP.speedLimitPending: { + ET.WARNING: Alert( + "Auto adjusting to last speed limit", + "", + AlertStatus.normal, AlertSize.small, + Priority.LOW, VisualAlert.none, AudibleAlertSP.promptSingleHigh, 5.), + }, + + EventNameSP.e2eChime: { + ET.PERMANENT: Alert( + "", + "", + AlertStatus.normal, AlertSize.none, + Priority.MID, VisualAlert.none, AudibleAlert.prompt, 3.), + }, +} diff --git a/sunnypilot/selfdrive/selfdrived/events_base.py b/openpilot/sunnypilot/selfdrive/selfdrived/events_base.py similarity index 89% rename from sunnypilot/selfdrive/selfdrived/events_base.py rename to openpilot/sunnypilot/selfdrive/selfdrived/events_base.py index 66396c4968..a392978144 100644 --- a/sunnypilot/selfdrive/selfdrived/events_base.py +++ b/openpilot/sunnypilot/selfdrive/selfdrived/events_base.py @@ -3,14 +3,16 @@ from enum import IntEnum from abc import abstractmethod from collections.abc import Callable -from cereal import log, car -import cereal.messaging as messaging +from openpilot.cereal import log +from opendbc.car.structs import car +import openpilot.cereal.messaging as messaging from openpilot.common.realtime import DT_CTRL +from openpilot.common.hardware import HARDWARE AlertSize = log.SelfdriveState.AlertSize AlertStatus = log.SelfdriveState.AlertStatus VisualAlert = car.CarControl.HUDControl.VisualAlert -AudibleAlert = car.CarControl.HUDControl.AudibleAlert +AudibleAlert = log.SelfdriveState.AudibleAlert # Alert priorities @@ -45,7 +47,7 @@ class Alert: alert_size: log.SelfdriveState.AlertSize, priority: Priority, visual_alert: car.CarControl.HUDControl.VisualAlert, - audible_alert: car.CarControl.HUDControl.AudibleAlert, + audible_alert: log.SelfdriveState.AudibleAlert, duration: float, creation_delay: float = 0.): @@ -76,7 +78,7 @@ class AlertBase(Alert): def __init__(self, alert_text_1: str, alert_text_2: str, alert_status: log.SelfdriveState.AlertStatus, alert_size: log.SelfdriveState.AlertSize, priority: Priority, visual_alert: car.CarControl.HUDControl.VisualAlert, - audible_alert: car.CarControl.HUDControl.AudibleAlert, duration: float): + audible_alert: log.SelfdriveState.AudibleAlert, duration: float): super().__init__(alert_text_1, alert_text_2, alert_status, alert_size, priority, visual_alert, audible_alert, duration) @@ -184,9 +186,12 @@ EmptyAlert = Alert("" , "", AlertStatus.normal, AlertSize.none, Priority.LOWEST, class NoEntryAlert(Alert): def __init__(self, alert_text_2: str, alert_text_1: str = "openpilot Unavailable", - visual_alert: car.CarControl.HUDControl.VisualAlert=VisualAlert.none): + visual_alert: car.CarControl.HUDControl.VisualAlert=VisualAlert.none, + priority: Priority = Priority.LOW): + if HARDWARE.get_device_type() == 'mici': + alert_text_1, alert_text_2 = alert_text_2, alert_text_1 super().__init__(alert_text_1, alert_text_2, AlertStatus.normal, - AlertSize.mid, Priority.LOW, visual_alert, + AlertSize.mid, priority, visual_alert, AudibleAlert.refuse, 3.) @@ -214,7 +219,7 @@ class ImmediateDisableAlert(Alert): class EngagementAlert(Alert): - def __init__(self, audible_alert: car.CarControl.HUDControl.AudibleAlert): + def __init__(self, audible_alert: log.SelfdriveState.AudibleAlert): super().__init__("", "", AlertStatus.normal, AlertSize.none, Priority.MID, VisualAlert.none, @@ -230,6 +235,11 @@ class NormalPermanentAlert(Alert): class StartupAlert(Alert): def __init__(self, alert_text_1: str, alert_text_2: str = "Always keep hands on wheel and eyes on road", alert_status=AlertStatus.normal): + alert_size = AlertSize.mid + if HARDWARE.get_device_type() == 'mici': + if alert_text_2 == "Always keep hands on wheel and eyes on road": + alert_text_2 = "" + alert_size = AlertSize.small super().__init__(alert_text_1, alert_text_2, - alert_status, AlertSize.mid, + alert_status, alert_size, Priority.LOWER, VisualAlert.none, AudibleAlert.none, 5.), diff --git a/selfdrive/ui/sunnypilot/quiet_mode.py b/openpilot/sunnypilot/selfdrive/ui/quiet_mode.py similarity index 96% rename from selfdrive/ui/sunnypilot/quiet_mode.py rename to openpilot/sunnypilot/selfdrive/ui/quiet_mode.py index 893df95033..d4dba74d95 100644 --- a/selfdrive/ui/sunnypilot/quiet_mode.py +++ b/openpilot/sunnypilot/selfdrive/ui/quiet_mode.py @@ -4,7 +4,7 @@ Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. This file is part of sunnypilot and is licensed under the MIT License. See the LICENSE.md file in the root directory for more details. """ -from cereal import car +from opendbc.car.structs import car from openpilot.common.params import Params @@ -17,6 +17,7 @@ ALERTS_ALWAYS_PLAY = { AudibleAlert.promptRepeat, } + class QuietMode: def __init__(self): self.params = Params() diff --git a/system/hardware/tici/tests/__init__.py b/openpilot/sunnypilot/sunnylink/__init__.py similarity index 100% rename from system/hardware/tici/tests/__init__.py rename to openpilot/sunnypilot/sunnylink/__init__.py diff --git a/openpilot/sunnypilot/sunnylink/api.py b/openpilot/sunnypilot/sunnylink/api.py new file mode 100644 index 0000000000..7ca619721b --- /dev/null +++ b/openpilot/sunnypilot/sunnylink/api.py @@ -0,0 +1,151 @@ +import json +import os +import random +import time +import jwt +from typing import cast +from datetime import datetime, timedelta, UTC + +from openpilot.common.api.base import BaseApi +from openpilot.common.params import Params +from openpilot.common.hardware import HARDWARE +from openpilot.common.hardware.hw import Paths + +API_HOST = os.getenv('SUNNYLINK_API_HOST', 'https://stg.api.sunnypilot.ai') +UNREGISTERED_SUNNYLINK_DONGLE_ID = "UnregisteredDevice" +MAX_RETRIES = 6 +CRASH_LOG_DIR = Paths.crash_log_root() + + +class SunnylinkApi(BaseApi): + def __init__(self, dongle_id): + super().__init__(dongle_id, API_HOST) + self.user_agent = "sunnypilot-" + self.spinner = None + self.params = Params() + + def api_get(self, endpoint, method='GET', timeout=10, access_token=None, session=None, json=None, **kwargs): + if not self.params.get_bool("SunnylinkEnabled"): + return None + + return super().api_get(endpoint, method, timeout, access_token, session, json, **kwargs) + + def get_token(self, payload_extra=None, expiry_hours=1): + # Add your additional data here + additional_data = {} + return super()._get_token(payload_extra, expiry_hours, **additional_data) + + def _status_update(self, message): + print(message) + if self.spinner: + self.spinner.update(message) + time.sleep(0.5) + + def _resolve_dongle_ids(self): + sunnylink_dongle_id = self.params.get("SunnylinkDongleId") + comma_dongle_id = self.dongle_id or self.params.get("DongleId") + return sunnylink_dongle_id, comma_dongle_id + + def _resolve_imeis(self): + imei = None + imei_try = 0 + while imei is None and imei_try < MAX_RETRIES: + try: + imei = HARDWARE.get_imei() + except Exception: + self._status_update(f"Error getting imei, trying again... [{imei_try + 1}/{MAX_RETRIES}]") + time.sleep(1) + imei_try += 1 + return imei, "" + + def _resolve_serial(self): + return (self.params.get("HardwareSerial") + or HARDWARE.get_serial()) + + def register_device(self, spinner=None, timeout=60, verbose=False): + self.spinner = spinner + + sunnylink_dongle_id, comma_dongle_id = self._resolve_dongle_ids() + + if comma_dongle_id is None: + self._status_update("Comma dongle ID not found, deferring sunnylink's registration to comma's registration process.") + return None + + imei1, imei2 = self._resolve_imeis() + serial = self._resolve_serial() + + if sunnylink_dongle_id not in (None, UNREGISTERED_SUNNYLINK_DONGLE_ID): + return sunnylink_dongle_id + + jwt_algo, private_key, public_key = BaseApi.get_key_pair() + + start_time = time.monotonic() + successful_registration = False + if not public_key: + sunnylink_dongle_id = UNREGISTERED_SUNNYLINK_DONGLE_ID + self._status_update("Public key not found, setting dongle ID to unregistered.") + else: + Params().put("LastSunnylinkPingTime", 0, block=True) # Reset the last ping time to 0 if we are trying to register + + backoff = 1 + while True: + register_token = jwt.encode({'register': True, 'exp': datetime.now(UTC).replace(tzinfo=None) + timedelta(hours=1)}, + cast(str, private_key), algorithm=jwt_algo) + try: + if verbose or time.monotonic() - start_time < timeout / 2: + self._status_update("Registering device to sunnylink...") + elif time.monotonic() - start_time >= timeout / 2: + self._status_update("Still registering device to sunnylink...") + + resp = self.api_get("v2/pilotauth/", method='POST', timeout=15, imei=imei1, imei2=imei2, serial=serial, + comma_dongle_id=comma_dongle_id, public_key=public_key, register_token=register_token) + + if resp is None: + raise Exception("Unable to register device, request was None") + + if resp.status_code in (409, 412): + timeout = time.monotonic() - start_time # Don't retry if the public key is already in use + key_in_use = "Public key is already in use, is your key unique? Contact your vendor for a new key." + unsafe_key = "Public key is known to not be unique and it's unsafe. Contact your vendor for a new key." + error_message = key_in_use if resp.status_code == 409 else unsafe_key + raise Exception(error_message) + + if resp.status_code != 200: + raise Exception(f"Failed to register with sunnylink. Status code: {resp.status_code}\nData\n:{resp.text}") + + dongleauth = json.loads(resp.text) + sunnylink_dongle_id = dongleauth["device_id"] + if sunnylink_dongle_id: + self._status_update("Device registered successfully.") + successful_registration = True + break + except Exception as e: + if verbose: + self._status_update(f"Waiting {backoff}s before retry, Exception occurred during registration: [{str(e)}]") + + if not os.path.exists(CRASH_LOG_DIR): + os.makedirs(CRASH_LOG_DIR) + + with open(f'{CRASH_LOG_DIR}/error.txt', 'a') as f: + f.write(f"[{datetime.now()}] sunnylink: {str(e)}\n") + + backoff = min(backoff * 2 * (0.5 + random.random()), 60) + time.sleep(backoff) + + if time.monotonic() - start_time > timeout: + self._status_update(f"Giving up on sunnylink's registration after {timeout}s. Will retry on next boot.") + time.sleep(3) + break + + self.params.put("SunnylinkDongleId", sunnylink_dongle_id or UNREGISTERED_SUNNYLINK_DONGLE_ID, block=True) + + # Set the last ping time to the current time since we were just talking to the API + last_ping = int((time.monotonic() if successful_registration else start_time) * 1e9) + Params().put("LastSunnylinkPingTime", last_ping, block=True) + + # Disable sunnylink if registration was not successful + if not successful_registration: + Params().put_bool("SunnylinkEnabled", False, block=True) + + self.spinner = None + return sunnylink_dongle_id diff --git a/system/loggerd/__init__.py b/openpilot/sunnypilot/sunnylink/athena/__init__.py similarity index 100% rename from system/loggerd/__init__.py rename to openpilot/sunnypilot/sunnylink/athena/__init__.py diff --git a/sunnypilot/sunnylink/athena/manage_sunnylinkd.py b/openpilot/sunnypilot/sunnylink/athena/manage_sunnylinkd.py similarity index 76% rename from sunnypilot/sunnylink/athena/manage_sunnylinkd.py rename to openpilot/sunnypilot/sunnylink/athena/manage_sunnylinkd.py index 377b6990f7..d811fa5dbc 100755 --- a/sunnypilot/sunnylink/athena/manage_sunnylinkd.py +++ b/openpilot/sunnypilot/sunnylink/athena/manage_sunnylinkd.py @@ -2,4 +2,4 @@ from openpilot.system.athena.manage_athenad import manage_athenad if __name__ == '__main__': - manage_athenad("SunnylinkDongleId", "SunnylinkdPid", 'sunnylinkd', 'sunnypilot.sunnylink.athena.sunnylinkd') + manage_athenad("SunnylinkDongleId", "SunnylinkdPid", 'sunnylinkd', 'openpilot.sunnypilot.sunnylink.athena.sunnylinkd') diff --git a/openpilot/sunnypilot/sunnylink/athena/sunnylinkd.py b/openpilot/sunnypilot/sunnylink/athena/sunnylinkd.py new file mode 100755 index 0000000000..ac168db7d8 --- /dev/null +++ b/openpilot/sunnypilot/sunnylink/athena/sunnylinkd.py @@ -0,0 +1,331 @@ +#!/usr/bin/env python3 +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from __future__ import annotations + +import base64 +import errno +import gzip +import json +import os +import ssl +import threading +import time + +from functools import partial +from openpilot.system.athena.rpc import dispatcher +from openpilot.common.params import Params, ParamKeyType +from openpilot.common.realtime import set_core_affinity +from openpilot.common.swaglog import cloudlog +from openpilot.common.hardware.hw import Paths +from openpilot.system.athena.athenad import ws_send, jsonrpc_handler, \ + recv_queue, UploadQueueCache, upload_queue, cur_upload_items, backoff, ws_manage, log_handler, start_local_proxy_shim, upload_handler, stat_handler +from websocket import (ABNF, WebSocket, WebSocketException, WebSocketTimeoutException, + create_connection, WebSocketConnectionClosedException) + +import openpilot.cereal.messaging as messaging +from openpilot.sunnypilot.models.default_model import DEFAULT_MODEL +from openpilot.sunnypilot.selfdrive.car.sync_sunnylink_params import update_car_list_param +from openpilot.sunnypilot.sunnylink.api import SunnylinkApi +from openpilot.sunnypilot.sunnylink.utils import sunnylink_need_register, sunnylink_ready, get_param_as_byte, save_param_from_base64_encoded_string +from openpilot.sunnypilot.sunnylink.capabilities import generate_capabilities, CAPABILITY_LABELS +from openpilot.sunnypilot.sunnylink.tools.generate_settings_schema import generate_schema + +SUNNYLINK_ATHENA_HOST = os.getenv('SUNNYLINK_ATHENA_HOST', 'wss://athena.sunnylink.ai') +HANDLER_THREADS = int(os.getenv('HANDLER_THREADS', "4")) +LOCAL_PORT_WHITELIST = {8022} +SUNNYLINK_LOG_ATTR_NAME = "user.sunny.upload" +SUNNYLINK_RECONNECT_TIMEOUT_S = 70 # FYI changing this will also would require a change on sidebar.cc +DISALLOW_LOG_UPLOAD = threading.Event() + +params = Params() + +# Parameters that should never be remotely modified +BLOCKED_PARAMS = { + "AdbEnabled", + "CompletedSunnylinkConsentVersion", + "CompletedTrainingVersion", + "GithubUsername", # Could grant SSH access + "GithubSshKeys", # Direct SSH key injection + "HasAcceptedTerms", + "HasAcceptedTermsSP", + "OnroadCycleRequested", # Prevent remote cycle trigger + "ParamsVersion", # Device-managed version counter +} + + +def handle_long_poll(ws: WebSocket, exit_event: threading.Event | None) -> None: + cloudlog.info("sunnylinkd.handle_long_poll started") + sm = messaging.SubMaster(['deviceState']) + end_event = threading.Event() + comma_prime_cellular_end_event = threading.Event() + + threads = [ + threading.Thread(target=ws_manage, args=(ws, end_event), name='ws_manage'), + threading.Thread(target=ws_recv, args=(ws, end_event), name='ws_recv'), + threading.Thread(target=ws_send, args=(ws, end_event), name='ws_send'), + threading.Thread(target=ws_ping, args=(ws, end_event), name='ws_ping'), + threading.Thread(target=upload_handler, args=(end_event,), name='upload_handler'), + threading.Thread(target=sunny_log_handler, args=(end_event, comma_prime_cellular_end_event), name='log_handler'), + threading.Thread(target=stat_handler, args=(end_event, Paths.stats_sp_root(), True), name='stat_handler'), + ] + [ + threading.Thread(target=jsonrpc_handler, args=(end_event, partial(startLocalProxy, end_event),), name=f'worker_{x}') + for x in range(HANDLER_THREADS) + ] + + for thread in threads: + thread.start() + try: + while not end_event.wait(0.1): + if not sunnylink_ready(params): + cloudlog.warning("Exiting sunnylinkd.handle_long_poll as SunnylinkEnabled is False") + break + + sm.update(0) + if exit_event is not None and exit_event.is_set(): + end_event.set() + comma_prime_cellular_end_event.set() + + prime_type = params.get("PrimeType") or 0 + metered = sm['deviceState'].networkMetered + + if DISALLOW_LOG_UPLOAD.is_set() and not comma_prime_cellular_end_event.is_set(): + cloudlog.debug("sunnylinkd.handle_long_poll: DISALLOW_LOG_UPLOAD, setting comma_prime_cellular_end_event") + comma_prime_cellular_end_event.set() + elif metered and int(prime_type) > 2: + cloudlog.debug(f"sunnylinkd.handle_long_poll: PrimeType({prime_type}) > 2 and networkMetered({metered})") + comma_prime_cellular_end_event.set() + elif comma_prime_cellular_end_event.is_set() and not DISALLOW_LOG_UPLOAD.is_set(): + cloudlog.debug( + f"sunnylinkd.handle_long_poll: comma_prime_cellular_end_event is set and not PrimeType({prime_type}) > 2 or not networkMetered({metered})") + comma_prime_cellular_end_event.clear() + finally: + end_event.set() + comma_prime_cellular_end_event.set() + for thread in threads: + cloudlog.debug(f"sunnylinkd athena.joining {thread.name}") + thread.join() + cloudlog.debug(f"sunnylinkd athena.joined {thread.name}") + + +def ws_recv(ws: WebSocket, end_event: threading.Event) -> None: + last_ping = int(time.monotonic() * 1e9) + while not end_event.is_set(): + try: + opcode, data = ws.recv_data(control_frame=True) + if opcode in (ABNF.OPCODE_TEXT, ABNF.OPCODE_BINARY): + if opcode == ABNF.OPCODE_TEXT: + data = data.decode("utf-8") + recv_queue.put_nowait(data) + cloudlog.debug(f"sunnylinkd.ws_recv.recv {data}") + elif opcode in (ABNF.OPCODE_PING, ABNF.OPCODE_PONG): + cloudlog.debug("sunnylinkd.ws_recv.pong") + last_ping = int(time.monotonic() * 1e9) + Params().put("LastSunnylinkPingTime", last_ping, block=True) + except WebSocketTimeoutException: + ns_since_last_ping = int(time.monotonic() * 1e9) - last_ping + if ns_since_last_ping > SUNNYLINK_RECONNECT_TIMEOUT_S * 1e9: + cloudlog.warning("sunnylinkd.ws_recv.timeout") + end_event.set() + except Exception as e: + if isinstance(e, WebSocketConnectionClosedException): + cloudlog.warning(f"sunnylinkd.ws_recv.{type(e).__name__}") + else: + cloudlog.exception("sunnylinkd.ws_recv.exception") + end_event.set() + + +def ws_ping(ws: WebSocket, end_event: threading.Event) -> None: + ws.ping() # Send the first ping + while not end_event.wait(SUNNYLINK_RECONNECT_TIMEOUT_S * 0.7): # Sleep about 70% before a timeout + try: + ws.ping() + cloudlog.debug("sunnylinkd.ws_recv.ws_ping: Pinging") + except Exception: + cloudlog.exception("sunnylinkd.ws_ping.exception") + end_event.set() + cloudlog.debug("sunnylinkd.ws_ping.end_event is set, exiting ws_ping thread") + + +def sunny_log_handler(end_event: threading.Event, comma_prime_cellular_end_event: threading.Event) -> None: + while not end_event.wait(0.1): + if not comma_prime_cellular_end_event.is_set(): + log_handler(comma_prime_cellular_end_event, SUNNYLINK_LOG_ATTR_NAME) + comma_prime_cellular_end_event.set() + + +@dispatcher.add_method +def toggleLogUpload(enabled: bool): + DISALLOW_LOG_UPLOAD.clear() if enabled and DISALLOW_LOG_UPLOAD.is_set() else DISALLOW_LOG_UPLOAD.set() + + +@dispatcher.add_method +def getParamsAllKeys() -> list[str]: + keys: list[str] = [k.decode('utf-8') for k in Params().all_keys()] + return keys + + +@dispatcher.add_method +def getParamsMetadata() -> str: + """Return settings_ui.json + live capabilities as gzip-compressed, base64-encoded string. + + Reads settings_ui.json, injects live capabilities from CarParams, compresses, + and returns. Single RPC for the frontend to get the complete settings UI and + runtime capabilities. + """ + try: + schema = generate_schema() + schema["capabilities"] = generate_capabilities() + schema["capability_labels"] = CAPABILITY_LABELS + schema["default_model"] = DEFAULT_MODEL + raw = json.dumps(schema, separators=(",", ":")).encode("utf-8") + return base64.b64encode(gzip.compress(raw)).decode("utf-8") + except Exception: + cloudlog.exception("sunnylinkd.getParamsMetadata.exception") + raise + + +@dispatcher.add_method +def getParams(params_keys: list[str], compression: bool = False) -> str | dict[str, str]: + params = Params() + available_keys: list[str] = [k.decode('utf-8') for k in Params().all_keys()] + + try: + zero_values: dict[int, bytes] = { + ParamKeyType.STRING.value: b"", + ParamKeyType.BOOL.value: b"0", + ParamKeyType.INT.value: b"0", + ParamKeyType.FLOAT.value: b"0.0", + ParamKeyType.TIME.value: b"", + ParamKeyType.JSON.value: b"{}", + ParamKeyType.BYTES.value: b"", + } + + param_keys_validated = [key for key in params_keys if key in available_keys] + params_dict: dict[str, list[dict[str, str | bool | int]]] = {"params": []} + for key in param_keys_validated: + value = get_param_as_byte(key) + if value is None: + value = get_param_as_byte(key, get_default=True) + if value is None: + param_type = params.get_type(key) + value = zero_values.get(param_type.value, b"") + + params_dict["params"].append({ + "key": key, + "value": base64.b64encode(gzip.compress(value) if compression else value).decode('utf-8'), + "type": int(params.get_type(key).value), + "is_compressed": compression + }) + + response = {str(param.get('key')): str(param.get('value')) for param in params_dict.get("params", [])} + response |= {"params": json.dumps(params_dict.get("params", []))} # Upcoming for settings v1 + return response + + except Exception as e: + cloudlog.exception("sunnylinkd.getParams.exception", e) + raise + + +@dispatcher.add_method +def saveParams(params_to_update: dict[str, str], compression: bool = False) -> None: + for key, value in params_to_update.items(): + # disallow modifications to blocked parameters + if key in BLOCKED_PARAMS: + cloudlog.warning(f"sunnylinkd.saveParams.blocked: Attempted to modify blocked parameter '{key}'") + continue + + try: + save_param_from_base64_encoded_string(key, value, compression) + except Exception as e: + cloudlog.error(f"sunnylinkd.saveParams.exception {e}") + + # Increment version counter for frontend change detection + try: + current = int(params.get("ParamsVersion") or "0") + params.put("ParamsVersion", str(current + 1), block=True) + except Exception: + pass + + +def startLocalProxy(global_end_event: threading.Event, remote_ws_uri: str, local_port: int) -> dict[str, int]: + sunnylink_dongle_id = params.get("SunnylinkDongleId") + sunnylink_api = SunnylinkApi(sunnylink_dongle_id) + + cloudlog.debug("athena.startLocalProxy.starting") + ws = create_connection( + remote_ws_uri, header={"Authorization": f"Bearer {sunnylink_api.get_token()}"}, enable_multithread=True, sslopt={"cert_reqs": ssl.CERT_NONE} + ) + + return start_local_proxy_shim(global_end_event, local_port, ws) + + +def main(exit_event: threading.Event | None = None): + try: + set_core_affinity([0, 1, 2, 3]) + except Exception: + cloudlog.exception("failed to set core affinity") + + while sunnylink_need_register(params): + cloudlog.info("Waiting for sunnylink registration to complete") + time.sleep(10) + + sunnylink_dongle_id = params.get("SunnylinkDongleId") + sunnylink_api = SunnylinkApi(sunnylink_dongle_id) + UploadQueueCache.initialize(upload_queue) + + update_car_list_param() + + ws_uri = f"{SUNNYLINK_ATHENA_HOST}" + conn_start = None + conn_retries = 0 + while (exit_event is None or not exit_event.is_set()) and sunnylink_ready(params): + try: + if conn_start is None: + conn_start = time.monotonic() + + cloudlog.event("sunnylinkd.main.connecting_ws", ws_uri=ws_uri, retries=conn_retries) + ws = create_connection( + ws_uri, + header={"Authorization": f"Bearer {sunnylink_api.get_token()}"}, + enable_multithread=True, + sslopt={"cert_reqs": ssl.CERT_NONE if "localhost" in ws_uri else ssl.CERT_REQUIRED}, + timeout=SUNNYLINK_RECONNECT_TIMEOUT_S, + ) + cloudlog.event("sunnylinkd.main.connected_ws", ws_uri=ws_uri, retries=conn_retries, + duration=time.monotonic() - conn_start) + conn_start = None + + conn_retries = 0 + cur_upload_items.clear() + + handle_long_poll(ws, exit_event) + except (KeyboardInterrupt, SystemExit): + break + except Exception as e: + conn_retries += 1 + params.remove("LastSunnylinkPingTime") + + if isinstance(e, (ConnectionError, TimeoutError, WebSocketException)): + cloudlog.warning(f"sunnylinkd.main.{type(e).__name__}") + elif isinstance(e, OSError): + name = errno.errorcode.get(e.errno or -1, "UNKNOWN") + msg = f"sunnylinkd.main.OSError.{name} ({e.errno})" + is_expected_error = e.errno in (errno.ENETDOWN, errno.ENETRESET, errno.ENETUNREACH) + cloudlog.warning(msg) if is_expected_error else cloudlog.exception(msg) + else: + cloudlog.exception("sunnylinkd.main.exception") + + time.sleep(backoff(conn_retries)) + + if not sunnylink_ready(params): + cloudlog.debug("Reached end of sunnylinkd.main while sunnylink is not ready. Waiting 60s before retrying") + time.sleep(60) + + +if __name__ == "__main__": + main() diff --git a/openpilot/sunnypilot/sunnylink/athena/tests/test_sunnylinkd.py b/openpilot/sunnypilot/sunnylink/athena/tests/test_sunnylinkd.py new file mode 100644 index 0000000000..7b81da5ad4 --- /dev/null +++ b/openpilot/sunnypilot/sunnylink/athena/tests/test_sunnylinkd.py @@ -0,0 +1,59 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from openpilot.sunnypilot.sunnylink.athena import sunnylinkd + + +class TestSunnylinkdMethods: + def setup_method(self): + self.saved_params = [] + + self.original_save = sunnylinkd.save_param_from_base64_encoded_string + + def mock_save_param(key, value, compression=False): + self.saved_params.append((key, value, compression)) + + sunnylinkd.save_param_from_base64_encoded_string = mock_save_param # ty: ignore[invalid-assignment] + + def teardown_method(self): + sunnylinkd.save_param_from_base64_encoded_string = self.original_save # ty: ignore[invalid-assignment] + + def test_saveParams_blocked(self): + blocked_params = { + "GithubUsername": "attacker", + "GithubSshKeys": "ssh-rsa attacker_key", + } + + sunnylinkd.saveParams(blocked_params) + + assert len(self.saved_params) == 0 + + def test_saveParams_allowed(self): + allowed_params = { + "SpeedLimitOffset": "5", + "MyCustomParam": "123" + } + + sunnylinkd.saveParams(allowed_params) + + # verify content + assert len(self.saved_params) == 2 + keys_saved = [p[0] for p in self.saved_params] + assert "SpeedLimitOffset" in keys_saved + assert "MyCustomParam" in keys_saved + + def test_saveParams_mixed(self): + mixed_params = { + "GithubUsername": "attacker", + "SpeedLimitOffset": "10" + } + + sunnylinkd.saveParams(mixed_params) + + # should save allowed one + assert len(self.saved_params) == 1 + assert self.saved_params[0][0] == "SpeedLimitOffset" + assert self.saved_params[0][1] == "10" diff --git a/sunnypilot/sunnylink/backups/AESCipher.py b/openpilot/sunnypilot/sunnylink/backups/AESCipher.py similarity index 100% rename from sunnypilot/sunnylink/backups/AESCipher.py rename to openpilot/sunnypilot/sunnylink/backups/AESCipher.py diff --git a/system/loggerd/tests/__init__.py b/openpilot/sunnypilot/sunnylink/backups/__init__.py similarity index 100% rename from system/loggerd/tests/__init__.py rename to openpilot/sunnypilot/sunnylink/backups/__init__.py diff --git a/openpilot/sunnypilot/sunnylink/backups/manager.py b/openpilot/sunnypilot/sunnylink/backups/manager.py new file mode 100644 index 0000000000..5ac6b8cabc --- /dev/null +++ b/openpilot/sunnypilot/sunnylink/backups/manager.py @@ -0,0 +1,286 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" + +import base64 +import json +import requests +import time +from enum import Enum +from typing import Any + +from openpilot.common.git import get_branch +from openpilot.common.params import Params, ParamKeyFlag +from openpilot.common.realtime import Ratekeeper +from openpilot.common.swaglog import cloudlog +from openpilot.common.version import get_version + +from openpilot.cereal import messaging, custom +from openpilot.sunnypilot.sunnylink.api import SunnylinkApi +from openpilot.sunnypilot.sunnylink.backups.utils import decrypt_compressed_data, encrypt_compressed_data, SnakeCaseEncoder +from openpilot.sunnypilot.sunnylink.utils import get_param_as_byte, save_param_from_base64_encoded_string + + +class OperationType(Enum): + BACKUP = "backup" + RESTORE = "restore" + + +class BackupManagerSP: + """Manages device configuration backups to/from sunnylink""" + + def __init__(self): + self.params = Params() + self.device_id = self.params.get("SunnylinkDongleId") + self.api = SunnylinkApi(self.device_id) + self.pm = messaging.PubMaster(["backupManagerSP"]) + + # Status tracking + self.backup_status = custom.BackupManagerSP.Status.idle + self.restore_status = custom.BackupManagerSP.Status.idle + + # Unified progress & operation type (only one operation runs at a time) + self.progress = 0.0 + self.operation: OperationType | None = None + + self.last_error = "" + self._session = requests.Session() # reuse session to reduce SSL handshake overhead + + def _report_status(self) -> None: + """Reports current backup manager state through the messaging system.""" + msg = messaging.new_message('backupManagerSP', valid=True) + backup_state = msg.backupManagerSP + + backup_state.backupStatus = self.backup_status + backup_state.restoreStatus = self.restore_status + # Both progress fields use the unified progress value + backup_state.backupProgress = self.progress + backup_state.restoreProgress = self.progress + backup_state.lastError = self.last_error + + # Optionally, add a field for operation type if supported: + # backup_state.operationType = self.operation.value if self.operation else "none" + + self.pm.send('backupManagerSP', msg) + + def _update_progress(self, progress: float, op_type: OperationType) -> None: + """Updates the unified progress and operation type, then reports status.""" + self.progress = progress + self.operation = op_type + self._report_status() + + def _collect_config_data(self) -> dict[str, Any]: + """Collects configuration data to be backed up.""" + config_data = {} + params_to_backup = [k.decode('utf-8') for k in self.params.all_keys(ParamKeyFlag.BACKUP)] + for param in params_to_backup: + value = get_param_as_byte(param) + if value is not None: + config_data[param] = base64.b64encode(value).decode('utf-8') + return config_data + + def _get_metadata_value(self, metadata_list, key, default_value=None): + return next((entry.get("value") for entry in metadata_list if entry.get("key") == key), default_value) + + async def create_backup(self) -> bool: + """Creates and uploads a new backup to sunnylink.""" + try: + self.backup_status = custom.BackupManagerSP.Status.inProgress + self._update_progress(0.0, OperationType.BACKUP) + + # Collect configuration data + config_data = self._collect_config_data() + self._update_progress(25.0, OperationType.BACKUP) + + # Serialize and encrypt config data + config_json = json.dumps(config_data) + encrypted_config = encrypt_compressed_data(config_json, use_aes_256=True) + self._update_progress(50.0, OperationType.BACKUP) + + backup_info = custom.BackupManagerSP.BackupInfo() + backup_info.deviceId = self.device_id + backup_info.config = encrypted_config + backup_info.isEncrypted = True + backup_info.createdAt = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()) + backup_info.updatedAt = backup_info.createdAt + backup_info.sunnypilotVersion = self._get_current_version() + backup_info.backupMetadata = [ + custom.BackupManagerSP.MetadataEntry(key="creator", value="BackupManagerSP"), + custom.BackupManagerSP.MetadataEntry(key="all_values_encoded", value="True"), + custom.BackupManagerSP.MetadataEntry(key="AES", value="256") + ] + + payload = json.loads(json.dumps(backup_info.to_dict(), cls=SnakeCaseEncoder)) + self._update_progress(75.0, OperationType.BACKUP) + + cloudlog.debug(f"Uploading backup with payload: {json.dumps(payload)}") + # Upload to sunnylink + result = self.api.api_get( + f"backup/{self.device_id}", + method='PUT', + access_token=self.api.get_token(), + json=payload, + session=self._session + ) + + if result: + self.backup_status = custom.BackupManagerSP.Status.completed + self._update_progress(100.0, OperationType.BACKUP) + cloudlog.info("Backup successfully created and uploaded") + else: + self.backup_status = custom.BackupManagerSP.Status.failed + self.last_error = "Failed to upload backup" + cloudlog.error(result) + self._report_status() + + return bool(self.backup_status == custom.BackupManagerSP.Status.completed) + + except Exception as e: + cloudlog.exception(f"Error creating backup: {str(e)}") + self.backup_status = custom.BackupManagerSP.Status.failed + self.last_error = str(e) + self._report_status() + return False + + async def restore_backup(self, version: int | None = None) -> bool: + """Restores a backup from sunnylink.""" + try: + self.restore_status = custom.BackupManagerSP.Status.inProgress + self._update_progress(0.0, OperationType.RESTORE) + + # Get backup data from API for the specified version + endpoint = f"backup/{self.device_id}" + f"/{version or ''}" + "?api-version=1" + backup_data = self.api.api_get(endpoint, access_token=self.api.get_token(), session=self._session) + if not backup_data: + raise Exception(f"No backup found for device {self.device_id}") + + self._update_progress(25.0, OperationType.RESTORE) + + data = backup_data.json() + backup_metadata = data.get("backup_metadata", []) + encrypted_config = data.get("config", "") + if not encrypted_config: + raise Exception("Empty backup configuration") + self._update_progress(50.0, OperationType.RESTORE) + + # Decrypt config and load data + use_aes_256 = self._get_metadata_value(backup_metadata, "AES", "128") == "256" + config_json = decrypt_compressed_data(encrypted_config, use_aes_256) + if not config_json: + raise Exception("Failed to decrypt backup configuration") + + config_data = json.loads(config_json) + self._update_progress(75.0, OperationType.RESTORE) + + # Apply configuration + self._apply_config(config_data) + + self.restore_status = custom.BackupManagerSP.Status.completed + self._update_progress(100.0, OperationType.RESTORE) + return True + + except Exception as e: + cloudlog.exception(f"Error restoring backup: {str(e)}") + self.restore_status = custom.BackupManagerSP.Status.failed + self.last_error = str(e) + self._report_status() + return False + + def _apply_config(self, config_data: dict[str, str]) -> None: + """Applies configuration data from a backup, but only for parameters marked as backupable.""" + backupable_params = [k.decode('utf-8') for k in self.params.all_keys(ParamKeyFlag.BACKUP)] + backupable_set_lower = {p.lower() for p in backupable_params} + + restored_count = 0 + skipped_count = 0 + + for param, encoded_value in config_data.items(): + if param.lower() in backupable_set_lower: + # Find real param name (with correct casing) + real_param = next(p for p in backupable_params if p.lower() == param.lower()) + try: + save_param_from_base64_encoded_string(real_param, encoded_value) + restored_count += 1 + except Exception as e: + cloudlog.error(f"Failed to restore param {param}: {str(e)}") + else: + skipped_count += 1 + cloudlog.info(f"Skipped restoring param {param}: not marked for backup in current version") + + cloudlog.info(f"Restore complete: {restored_count} params restored, {skipped_count} params skipped") + + def _get_current_version(self) -> custom.BackupManagerSP.Version: + """Gets current sunnypilot version information.""" + version_obj = custom.BackupManagerSP.Version() + version_str = get_version() + + version_parts = version_str.split('-') # For when version is like "1.2.3-456" + version_nums = version_parts[0].split('.') + + # Extract build number from hyphen format or as 4th version component + build = 0 + if len(version_parts) > 1 and version_parts[1].isdigit(): + build = int(version_parts[1]) + elif len(version_nums) > 3 and version_nums[3].isdigit(): + build = int(version_nums[3]) + + # Set version components with safer defaults + version_obj.major = int(version_nums[0]) if len(version_nums) > 0 and version_nums[0].isdigit() else 0 + version_obj.minor = int(version_nums[1]) if len(version_nums) > 1 and version_nums[1].isdigit() else 0 + version_obj.patch = int(version_nums[2]) if len(version_nums) > 2 and version_nums[2].isdigit() else 0 + version_obj.build = build + version_obj.branch = get_branch() + + return version_obj + + async def main_thread(self) -> None: + """Main thread for backup management.""" + rk = Ratekeeper(1, print_delay_threshold=None) + reset_progress = False + + while True: + try: + if reset_progress: + self.progress = 100.0 + self.operation = None + self.restore_status = custom.BackupManagerSP.Status.idle + self.backup_status = custom.BackupManagerSP.Status.idle + + # Check for backup command + if self.params.get_bool("BackupManager_CreateBackup"): + try: + if await self.create_backup(): + reset_progress = True + finally: + self.params.remove("BackupManager_CreateBackup") + + # Check for restore command + restore_version = self.params.get("BackupManager_RestoreVersion") + if restore_version: + try: + version = int(restore_version) if restore_version.isdigit() else None + await self.restore_backup(version) + reset_progress = True + finally: + self.params.remove("BackupManager_RestoreVersion") + + self._report_status() + rk.keep_time() + + except Exception as e: + cloudlog.exception(f"Error in backup manager main thread: {str(e)}") + self.last_error = str(e) + self._report_status() + rk.keep_time() + + +def main(): + import asyncio + asyncio.run(BackupManagerSP().main_thread()) + + +if __name__ == "__main__": + main() diff --git a/openpilot/sunnypilot/sunnylink/backups/utils.py b/openpilot/sunnypilot/sunnylink/backups/utils.py new file mode 100644 index 0000000000..054a01793f --- /dev/null +++ b/openpilot/sunnypilot/sunnylink/backups/utils.py @@ -0,0 +1,188 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import base64 +import hashlib +import os +import zlib +import re +import json +from pathlib import Path + +from cryptography.hazmat.backends import default_backend +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import rsa, ec + +from openpilot.common.api.base import KEYS +from openpilot.sunnypilot.sunnylink.backups.AESCipher import AESCipher +from openpilot.common.hardware.hw import Paths + + +class KeyDerivation: + @staticmethod + def _load_key(file_path: str) -> bytes: + with open(file_path, 'rb') as f: + return f.read() + + @staticmethod + def derive_aes_key_iv(key_path: str, use_aes_256: bool) -> tuple[bytes, bytes]: + key_pem: bytes = KeyDerivation._load_key(key_path) + key_plain = key_pem.decode(errors="ignore") + + if "private" in key_plain.lower(): + private_key = serialization.load_pem_private_key(key_pem, password=None, backend=default_backend()) + if isinstance(private_key, (rsa.RSAPrivateKey, ec.EllipticCurvePrivateKey)): + public_key = private_key.public_key() + else: + raise ValueError("Invalid key format: Unable to determine if key is public or private.") + elif "public" in key_plain.lower(): + public_key = serialization.load_pem_public_key(key_pem, backend=default_backend()) + if not isinstance(public_key, (rsa.RSAPublicKey, ec.EllipticCurvePublicKey)): + raise ValueError("Invalid key format: Unable to determine if key is public or private.") + else: + raise ValueError("Invalid key format: Unable to determine if key is public or private.") + + if isinstance(public_key, rsa.RSAPublicKey): + der_data = public_key.public_bytes(encoding=serialization.Encoding.DER, format=serialization.PublicFormat.PKCS1) + elif isinstance(public_key, ec.EllipticCurvePublicKey): + der_data = public_key.public_bytes(encoding=serialization.Encoding.DER, format=serialization.PublicFormat.SubjectPublicKeyInfo) + else: + raise ValueError("Unsupported key type.") + + if use_aes_256: + # AES-256-CBC + key = hashlib.sha256(der_data).digest() + iv = hashlib.md5(der_data).digest() + else: + # AES-128-CBC + key = hashlib.md5(der_data).digest() + iv = hashlib.md5(der_data).digest() # Insecure IV reuse, kept for compatibility + + return key, iv + + +def uncompress_dat(data): + """ + Decompress data using zlib. + + Args: + data (bytes): Compressed data + + Returns: + bytes: Decompressed data + """ + data_stripped_4 = data[4:] + return zlib.decompress(data_stripped_4) + + +def compress_dat(data): + """ + Compress data using zlib. + + Args: + data (bytes): Data to compress + + Returns: + bytes: Compressed data + """ + compressed_data = zlib.compress(data, level=9) + return b"ZLIB" + compressed_data + + +def get_key_path(use_aes_256=False) -> str: + key_path = "" + for key in KEYS: + if os.path.isfile(Paths.persist_root() + f'/comma/{key}') and os.path.isfile(Paths.persist_root() + f'/comma/{key}.pub'): + key_path = str(Path(Paths.persist_root() + f'/comma/{key}') if use_aes_256 else Path(Paths.persist_root() + f'/comma/{key}.pub')) + break + + if not key_path: + raise FileNotFoundError("No valid key pair found in persist storage.") + + return key_path + + +def decrypt_compressed_data(encrypted_base64, use_aes_256=False): + """ + Decrypt and decompress data from base64 string. + + Args: + encrypted_base64 (str): Base64 encoded encrypted data + key_path (str, optional): Path to RSA public key + + Returns: + str: Decrypted and decompressed string + """ + try: + # Decode base64 + encrypted_data = base64.b64decode(encrypted_base64) + + # Decrypt + key, iv = KeyDerivation.derive_aes_key_iv(get_key_path(use_aes_256), use_aes_256) + cipher = AESCipher(key, iv) + decrypted_data = cipher.decrypt(encrypted_data) + + # Decompress + decompressed_data = uncompress_dat(decrypted_data) + + # Decode UTF-8 + result = decompressed_data.decode('utf-8') + return result + except Exception as e: + print(f"Decryption and decompression failed: {e}") + return "" + + +def encrypt_compressed_data(text, use_aes_256=True): + """ + Compress and encrypt string data to base64. + + Args: + text (str): Text to compress and encrypt + key_path (str, optional): Path to RSA public key + + Returns: + str: Base64 encoded encrypted data + """ + try: + # Encode to UTF-8 + text_bytes = text.encode('utf-8') + + # Compress + compressed_data = compress_dat(text_bytes) + + # Encrypt + key, iv = KeyDerivation.derive_aes_key_iv(get_key_path(use_aes_256), use_aes_256) + cipher = AESCipher(key, iv) + encrypted_data = cipher.encrypt(compressed_data) + + # Encode to base64 + result = base64.b64encode(encrypted_data).decode('utf-8') + return result + except Exception as e: + print(f"Compression and encryption failed: {e}") + return "" + + +def camel_to_snake(name): + """Convert camelCase to snake_case.""" + name = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) + return re.sub('([a-z0-9])([A-Z])', r'\1_\2', name).lower() + + +def transform_dict(obj): + """Recursively transform dictionary keys from camelCase to snake_case.""" + if isinstance(obj, dict): + return {camel_to_snake(k): transform_dict(v) for k, v in obj.items()} + elif isinstance(obj, list): + return [transform_dict(item) for item in obj] + return obj + + +class SnakeCaseEncoder(json.JSONEncoder): + def encode(self, o): + transformed_obj = transform_dict(o) + return super().encode(transformed_obj) diff --git a/openpilot/sunnypilot/sunnylink/capabilities.py b/openpilot/sunnypilot/sunnylink/capabilities.py new file mode 100644 index 0000000000..1f12b5b001 --- /dev/null +++ b/openpilot/sunnypilot/sunnylink/capabilities.py @@ -0,0 +1,187 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import json + +from openpilot.cereal import custom, messaging +from opendbc.car.structs import car +from opendbc.car.hyundai.values import CAR as HYUNDAI_CAR, UNSUPPORTED_LONGITUDINAL_CAR +from opendbc.car.subaru.values import CAR as SUBARU_CAR, SubaruFlags +from opendbc.sunnypilot.car.tesla.values import TeslaFlagsSP +from openpilot.common.params import Params +from openpilot.common.swaglog import cloudlog +from openpilot.common.hardware import HARDWARE + + +# Wire-protocol version for the capabilities payload. Bump on breaking changes +# only; additive fields are backward-compatible and do not require a bump. +PROTOCOL_VERSION = 1 + +# All capability fields that rules may reference. +# Non-boolean fields must have defaults in CAPABILITY_DEFAULTS. +CAPABILITY_FIELDS = ( + "protocol_version", + "has_longitudinal_control", + "has_icbm", + "icbm_available", + "torque_allowed", + "brand", + "pcm_cruise", + "alpha_long_available", + "steer_control_type", + "enable_bsm", + "is_release", + "is_sp_release", + "is_development", + "tesla_has_vehicle_bus", + "has_stop_and_go", + "stock_longitudinal", + "device_type", + "subaru_has_sng", + "hyundai_alpha_long_available", +) + +CAPABILITY_LABELS: dict[str, str] = { + "protocol_version": "Capabilities protocol version", + "has_longitudinal_control": "sunnypilot longitudinal control", + "has_icbm": "ICBM enabled", + "icbm_available": "ICBM available", + "torque_allowed": "torque steering (not available for angle steering vehicles)", + "brand": "Vehicle brand", + "pcm_cruise": "PCM cruise", + "alpha_long_available": "Alpha Longitudinal available", + "steer_control_type": "Steer control type", + "enable_bsm": "BSM available", + "is_release": "Release branch", + "is_sp_release": "SP release branch", + "is_development": "Development branch", + "tesla_has_vehicle_bus": "Tesla vehicle bus", + "has_stop_and_go": "Stop and Go", + "stock_longitudinal": "stock longitudinal", + "device_type": "Device type", + "subaru_has_sng": "Subaru Stop-and-Go available", + "hyundai_alpha_long_available": "Hyundai Alpha Longitudinal available", +} + +# Explicit defaults for non-boolean capability fields +CAPABILITY_DEFAULTS: dict[str, bool | str | int] = { + "brand": "", + "steer_control_type": "", + "device_type": "", + "protocol_version": PROTOCOL_VERSION, +} + + +def _bundle_field(bundle: dict | None, key: str) -> str: + return bundle.get(key, "") if isinstance(bundle, dict) else "" + + +def _resolve_brand_capabilities(caps: dict, bundle_platform: str, CP) -> None: + """Set brand-specific capabilities from bundle platform or CarParams fallback. + + Bundle (manual car selection) is a pre-fingerprint approximation. + CarParams (auto-fingerprint) is the authoritative post-fingerprint source. + Mirrors the per-brand update_settings() logic in device UI layouts. + """ + brand = caps["brand"] + + if brand == "hyundai": + if bundle_platform: + try: + unsupported = set().union(*UNSUPPORTED_LONGITUDINAL_CAR.values()) + caps["hyundai_alpha_long_available"] = HYUNDAI_CAR[bundle_platform] not in unsupported + except KeyError: + cloudlog.exception(f"capabilities: unknown hyundai platform {bundle_platform!r}") + elif CP is not None: + caps["hyundai_alpha_long_available"] = bool(CP.alphaLongitudinalAvailable) + + elif brand == "subaru": + if bundle_platform: + try: + flags = SUBARU_CAR[bundle_platform].config.flags + caps["subaru_has_sng"] = not bool(flags & (SubaruFlags.GLOBAL_GEN2 | SubaruFlags.HYBRID)) + caps["has_stop_and_go"] = caps["subaru_has_sng"] + except KeyError: + cloudlog.exception(f"capabilities: unknown subaru platform {bundle_platform!r}") + elif CP is not None: + caps["subaru_has_sng"] = not bool(CP.flags & (SubaruFlags.GLOBAL_GEN2 | SubaruFlags.HYBRID)) + caps["has_stop_and_go"] = caps["subaru_has_sng"] + + +def generate_capabilities(params: Params | None = None) -> dict: + """Generate a SettingsCapabilities dict from CarParams + boolean params. + + When CarPlatformBundle is present, brand and platform come from the bundle + (mirrors Raylib). CarParams* deserialization is the fallback before the bundle + is written (early after first pairing). + """ + params = params or Params() + + caps: dict = {field: CAPABILITY_DEFAULTS.get(field, False) for field in CAPABILITY_FIELDS} + + # Wire-protocol version is always set explicitly. + caps["protocol_version"] = PROTOCOL_VERSION + + # Hardware + boolean params (no CarParams dependency) + caps["device_type"] = HARDWARE.get_device_type() + caps["is_release"] = False # params.get_bool("IsReleaseBranch") + caps["is_sp_release"] = params.get_bool("IsReleaseSpBranch") + caps["is_development"] = params.get_bool("IsDevelopmentBranch") + caps["stock_longitudinal"] = params.get_bool("ToyotaEnforceStockLongitudinal") + + bundle = params.get("CarPlatformBundle") + bundle_brand = _bundle_field(bundle, "brand") + bundle_platform = _bundle_field(bundle, "platform") + + # Bundle-first brand resolution; CP is fallback only. + if bundle_brand: + caps["brand"] = bundle_brand + + # CarParams-derived capabilities + CP = None + CP_bytes = params.get("CarParamsPersistent") + if CP_bytes is not None: + try: + CP = messaging.log_from_bytes(CP_bytes, car.CarParams) + caps["alpha_long_available"] = bool(CP.alphaLongitudinalAvailable) + if CP.alphaLongitudinalAvailable: + caps["has_longitudinal_control"] = params.get_bool("AlphaLongitudinalEnabled") + else: + caps["has_longitudinal_control"] = bool(CP.openpilotLongitudinalControl) + # CP.steerControlType is the physical control mode (angle / torque). + # CP.lateralTuning.which() returns the tuning class (pid / torque / indi) + # which is a separate concept and is not interchangeable. + caps["steer_control_type"] = str(CP.steerControlType) + caps["torque_allowed"] = CP.steerControlType != car.CarParams.SteerControlType.angle + if not caps["brand"] and CP.brand: + caps["brand"] = str(CP.brand) + caps["pcm_cruise"] = bool(CP.pcmCruise) + caps["enable_bsm"] = bool(CP.enableBsm) + # Generic SnG fallback. Brand-specific opaque flags below override. + caps["has_stop_and_go"] = bool(CP.openpilotLongitudinalControl) + except Exception: + CP = None + cloudlog.exception("capabilities: failed to deserialize CarParamsPersistent") + + # CarParamsSP-derived capabilities + CP_SP_bytes = params.get("CarParamsSPPersistent") + if CP_SP_bytes is not None: + try: + CP_SP = messaging.log_from_bytes(CP_SP_bytes, custom.CarParamsSP) + caps["icbm_available"] = bool(CP_SP.intelligentCruiseButtonManagementAvailable) + caps["has_icbm"] = bool(CP_SP.intelligentCruiseButtonManagementAvailable) and params.get_bool("IntelligentCruiseButtonManagement") + caps["tesla_has_vehicle_bus"] = bool(CP_SP.flags & TeslaFlagsSP.HAS_VEHICLE_BUS) + except Exception: + cloudlog.exception("capabilities: failed to deserialize CarParamsSPPersistent") + + _resolve_brand_capabilities(caps, bundle_platform, CP) + + return caps + + +def generate_capabilities_json(params: Params | None = None) -> str: + """Generate SettingsCapabilities as a JSON string.""" + return json.dumps(generate_capabilities(params), separators=(",", ":")) diff --git a/openpilot/sunnypilot/sunnylink/docs/README.md b/openpilot/sunnypilot/sunnylink/docs/README.md new file mode 100644 index 0000000000..62d46677e6 --- /dev/null +++ b/openpilot/sunnypilot/sunnylink/docs/README.md @@ -0,0 +1,585 @@ +# sunnylink Settings UI Guide + +> One YAML file per page. Edit, run the compiler, commit. The sunnylink frontend updates automatically. + +## What you edit (and what's generated) + +| File | What | When to edit | +|------|------|-------------| +| `settings_ui_src/pages/.yaml` | One YAML per page (panel). Contains panel metadata + sections + items + sub_panels inline. | Adding/changing/removing a setting. | +| `settings_ui_src/pages/vehicle.yaml` | Per-brand settings page (`kind: vehicle`). Each brand is a section. | Adding/changing a vehicle-specific setting. | +| `settings_ui_src/_macros.yaml` | Named rule fragments referenced via `{$ref: "#/macros/"}`. | Adding a reusable rule (e.g. a new platform gate). | +| **`settings_ui.json`** | **Generated from src tree by `compile_settings_ui.py`. Do not edit by hand.** | Never. Compiler emits it; frontend reads it. | + +Pages today: `steering, cruise, display, visuals, toggles, device, software, developer, models, vehicle` (10). + +Run `python sunnypilot/sunnylink/tools/compile_settings_ui.py` after edits. Add `--check` in CI to fail on out-of-sync `settings_ui.json`. + +Display metadata (titles, descriptions, options, min/max/step/unit) is inline on each item. There is no separate metadata file. + +## Page file shape + +A page YAML contains the whole panel: metadata at the top, then `sections`. Each section has its own `items` and (optionally) `sub_panels`. Sub-panels are nested inside the section they belong to. Items appear in the order written in the file. + +```yaml +# yaml-language-server: $schema=../_schemas/page.schema.json +id: steering +label: Steering +icon: steering_wheel +order: 1 +remote_configurable: true +description: Lateral control, lane changes, and steering behavior + +sections: + - id: mads + title: Modular Assistive Driving System (MADS) + items: + - key: Mads + widget: toggle + title: Enable Modular Assistive Driving System (MADS) + description: | + Enable the beloved MADS feature. Disable toggle to revert back + to stock sunnypilot engagement/disengagement. + enablement: + - {$ref: "#/macros/offroad"} + + sub_panels: + - id: mads_settings + label: MADS Settings + trigger_key: Mads + trigger_condition: {type: param, key: Mads, equals: true} + items: + - key: MadsMainCruiseAllowed + widget: toggle + title: Toggle with Main Cruise + description: | + Note: For vehicles without LFA/LKAS button, disabling this will + prevent lateral control engagement. + enablement: + - {$ref: "#/macros/offroad"} + - {$ref: "#/macros/mads_full_platforms"} +``` + +The vehicle page has the same shape but declares `kind: vehicle`; each section's `id` becomes a brand key under `vehicle_settings` in the compiled JSON. + +## Macros (named rule fragments) + +`_macros.yaml` declares reusable rule lists. Reference them from any rules array via `{$ref: "#/macros/"}`. + +```yaml +macros: + offroad: [{type: offroad_only}] + longitudinal: [{type: capability, field: has_longitudinal_control, equals: true}] + mads_full_platforms: + - type: not + condition: + type: any + conditions: + - {type: capability, field: brand, equals: rivian} + - type: all + conditions: + - {type: capability, field: brand, equals: tesla} + - type: not + condition: {type: capability, field: tesla_has_vehicle_bus, equals: true} +``` + +In an item: + +```yaml +enablement: + - {$ref: "#/macros/offroad"} + - {$ref: "#/macros/mads_full_platforms"} +``` + +The compiler splices a list-context `$ref` into its parent list. Macros may reference other macros up to depth 3; cycles are an error. + +## Compiler workflow + +``` +1. common/params_keys.h — add/remove the C++ param key +2. settings_ui_src/pages/.yaml — add/edit/remove the item in the right section +3. python sunnypilot/sunnylink/tools/compile_settings_ui.py +4. python sunnypilot/sunnylink/tools/validate_settings_ui.py (or: --check on the compiler) +5. uv run python -m pytest sunnypilot/sunnylink/tests/ # run regression + compiler tests +6. commit +``` + +CI runs `compile_settings_ui.py --check` to fail on hand-edited `settings_ui.json`. + +## Compiled output reference (schema contract) + +The tables below describe the **compiled** `settings_ui.json` schema — what the frontend consumes at runtime. JSON snippets show the wire shape; in the src tree you author YAML that compiles to the same shape. Use these as a contract reference for valid fields, their meanings, and rule types. + +## Quick reference: widget types + +| Widget | Use for | Fields needed | +|--------|---------|---------------| +| `toggle` | On/off boolean | `title` | +| `multiple_button` | 2-4 discrete options | `title` + `options` array | +| `option` | Numeric range or dropdown | `title` + `min/max/step` or `options` | +| `info` | Read-only display | `title` | + +## Quick reference: item fields + +| Field | Required | Description | +|-------|----------|-------------| +| `key` | Yes | Param key name (must exist in `params_keys.h`) | +| `widget` | Yes | `toggle`, `option`, `multiple_button`, `button`, `info` | +| `title` | Yes | Display name shown to the user | +| `description` | No | Inline explanatory text below the title. May be empty when only `details` is used. | +| `details` | No | Extended help text shown in a modal when the user taps an "i" button on the row. Independent of `description`: either, both, or neither may be present. | +| `options` | For selectors | Array of `{"value": 0, "label": "Off"}` objects (see per-option enablement below) | +| `min`, `max`, `step` | For sliders | Numeric range constraints | +| `unit` | No | Unit label. Static: `"seconds"`. Dynamic: `{"metric": "km/h", "imperial": "mph"}` (resolved by IsMetric) | +| `visibility` | No | Rules for show/hide. Settings are never hidden, always dimmed with UNAVAILABLE badge when rules fail | +| `enablement` | No | Rules for enabled/disabled (all must pass). Dimmed with badge when rules fail | +| `blocked` | No | `true` for device-only settings that cannot be modified remotely. Frontend shows as read-only | +| `title_param_suffix` | No | Dynamic title suffix. Example: `{"param": "IsMetric", "values": {"0": "mph", "1": "km/h"}}` | +| `sub_items` | No | Nested child items | +| `needs_onroad_cycle` | No | `true` if changing this param triggers a system restart. Frontend shows a "Restart" badge. See [REFERENCE.md - Remote Onroad Cycle](REFERENCE.md#remote-onroad-cycle) | + +## Quick reference: rule types + +| Rule | Example | Use for | +|------|---------|---------| +| `offroad_only` | `{"type": "offroad_only"}` | Grey out while driving | +| `not_engaged` | `{"type": "not_engaged"}` | Grey out only while engaged (started + selfdrive/MADS active) | +| `capability` | `{"type": "capability", "field": "has_longitudinal_control", "equals": true}` | Car-dependent visibility | +| `param` | `{"type": "param", "key": "Mads", "equals": true}` | Show/enable based on another setting | +| `param_compare` | `{"type": "param_compare", "key": "SpeedLimitMode", "op": ">", "value": 0}` | Numeric comparison | +| `not` | `{"type": "not", "condition": {...}}` | Negate a rule | +| `any` | `{"type": "any", "conditions": [...]}` | OR logic | +| `all` | `{"type": "all", "conditions": [...]}` | AND logic (for nesting inside `any`/`not`) | +| `$ref` | `{"$ref": "#/macros/offroad"}` | Reference a named rule fragment in `_macros.yaml` | + +**Visibility design**: Settings are always visible. When visibility rules fail, the setting is dimmed with an UNAVAILABLE badge, so users know it exists but is not applicable. + +**Enablement rules**: Grayed out (disabled) when rules fail. Frontend shows a contextual badge explaining why. + +**Capability fields** (referenced in rules): `has_longitudinal_control`, `has_icbm`, `icbm_available`, `torque_allowed`, `brand`, `pcm_cruise`, `alpha_long_available`, `steer_control_type`, `enable_bsm`, `is_release`, `is_sp_release`, `is_development`, `tesla_has_vehicle_bus`, `has_stop_and_go`, `stock_longitudinal` + +--- + +## How to + +### Pick a writability rule (offroad / not_engaged / param-based) + +| Use this | When | Why | +|---|---|---| +| `offroad_only` | Param can only be safely changed when the car is parked. Most user-facing toggles. | Strictest. Frontend shows "device is driving" badge and disables the row. | +| `not_engaged` | Param can be changed while the car is started but only when sunnypilot/MADS is **not** actively driving. | Less strict than offroad. Matches Raylib `engaged = started AND (selfdriveState.enabled OR mads.enabled)`. Use for items the device must apply mid-drive (e.g. test maneuvers, longitudinal stock-vs-OP toggle). | +| `param`-based | Behavior depends on another setting's value (parent toggle, mode selector, etc.). | Composes with `not`/`any`/`all` for arbitrary logic. | +| `capability`-based | Behavior depends on the connected car or device (brand, longitudinal, hardware). | Resolved on the device from `CarParams` / hardware. See [`capabilities.py`](../capabilities.py) for the full field list. | +| (no rule) | Param is always writable, no gating. | Rare. Prefer at least `offroad_only` unless the param is genuinely safe to flip mid-drive. | + +Default for new toggles: `enablement: [{$ref: "#/macros/offroad"}]`. Drop down to `not_engaged` only if you've confirmed mid-drive write is safe in the controls/UI code path. + +### Use `details` for safety notes / extended help + +Inline `description` shows under the title. For longer caveats, safety notes, or "learn more" content, use `details` — the frontend renders an info button that opens a modal. Either field may be present alone or both together. + +```yaml +- key: AutoLaneChangeTimer + widget: option + title: Auto Lane Change by Blinker + description: |- + Set a timer to delay the auto lane change operation when the blinker is used. + No nudge on the steering wheel is required to auto lane change if a timer is set. + Default is Nudge. + details: |- + Please use caution when using this feature. Only use the blinker when traffic + and road conditions permit. + options: [...] +``` + +For an item that is intentionally minimal inline (no inline body, only the modal): + +```yaml +- key: SomeAdvancedToggle + widget: toggle + title: Some Advanced Feature + details: |- + Long-form rationale, caveats, links, etc. — kept entirely behind the info button. +``` + +### Add a toggle + +1. Register in `common/params_keys.h`: + ```cpp + {"MyToggle", {PERSISTENT | BACKUP, BOOL}}, + ``` + +2. Open `settings_ui_src/pages/.yaml`. Add the item to the right section: + ```yaml + - key: MyToggle + widget: toggle + title: My Feature + description: What this feature does. + enablement: + - {$ref: "#/macros/offroad"} + ``` + + If changing the param requires an onroad cycle to take effect, add `needs_onroad_cycle: true`. + +3. Compile + validate + test: + ``` + python sunnypilot/sunnylink/tools/compile_settings_ui.py + python sunnypilot/sunnylink/tools/validate_settings_ui.py + uv run python -m pytest sunnypilot/sunnylink/tests/ + ``` + +### Add a multi-button option + +```yaml +- key: MySelector + widget: multiple_button + title: Mode + options: + - {value: 0, label: Off} + - {value: 1, label: On} + - {value: 2, label: Auto} +``` + +### Add a slider or range + +```yaml +- key: MyRange + widget: option + title: Follow Distance + description: Time gap to lead vehicle. + min: 0.5 + max: 3.0 + step: 0.1 + unit: seconds +``` + +### Add a slider with metric/imperial units + +```yaml +- key: MinSpeed + widget: option + title: Minimum Speed + min: 0 + max: 100 + step: 5 + unit: {metric: km/h, imperial: mph} +``` + +Frontend resolves the unit string based on the device's `IsMetric` param. Static units (e.g. `seconds`, `m/s²`) stay plain strings. + +### Add a dynamic title suffix + +```yaml +- key: FollowDistance + widget: option + title: Follow Distance + title_param_suffix: + param: IsMetric + values: {'0': mph, '1': km/h} + min: 0.5 + max: 3.0 + step: 0.1 +``` + +Renders as "Follow Distance: mph" / "Follow Distance: km/h". + +### Add a device-only read-only setting + +```yaml +- key: OnroadCyclePendingRemote + widget: info + title: Pending Remote Cycle + blocked: true +``` + +Frontend treats `blocked: true` items as read-only. + +### Add a dropdown option + +```yaml +- key: MyDropdown + widget: option + title: Recording Quality + options: + - {value: 0, label: Low (720p)} + - {value: 1, label: Medium (1080p)} + - {value: 2, label: High (4K)} +``` + +### Per-option enablement rules + +```yaml +- key: MadsSteeringMode + widget: multiple_button + title: Steering Mode on Brake Pedal + options: + - value: 0 + label: Remain Active + enablement: + - {$ref: "#/macros/mads_full_platforms"} + - value: 1 + label: Pause + enablement: + - {$ref: "#/macros/mads_full_platforms"} + - value: 2 + label: Disengage + enablement: + - {$ref: "#/macros/offroad"} +``` + +When an option's enablement fails, that option is grayed out but still visible. + +### Show only when another setting is on + +```yaml +- key: ChildSetting + widget: toggle + title: Child Feature + visibility: + - {type: param, key: ParentToggle, equals: true} +``` + +(With the "dim instead of hide" design, this setting is dimmed, not hidden, when the rule fails.) + +### Show only for specific brands + +```yaml +- key: LongFeature + widget: toggle + title: Longitudinal Feature + visibility: + - {$ref: "#/macros/longitudinal"} +``` + +### Combine multiple conditions + +The `enablement` array is implicit-AND: every entry must pass. Use `any` for OR, `all` for nested AND, `not` for negation. Wrap repeated combinations in a macro so future you doesn't re-derive the logic. + +**AND across two params** (writable only when both Mads is on AND ICBM is enabled): +```yaml +enablement: + - {type: param, key: Mads, equals: true} + - {type: param, key: IntelligentCruiseButtonManagement, equals: true} +``` + +**OR across two params** (writable when either is on): +```yaml +enablement: + - type: any + conditions: + - {type: param, key: ExperimentalMode, equals: true} + - {type: param, key: DynamicExperimentalControl, equals: true} +``` + +**Mixed: capability AND param** (only on longitudinal cars when ShowAdvancedControls is on): +```yaml +enablement: + - {$ref: "#/macros/longitudinal"} + - {$ref: "#/macros/advanced_only"} +``` + +**Three-way: offroad AND torque-allowed AND not-NNLC** (real example: `EnforceTorqueControl`): +```yaml +enablement: + - {$ref: "#/macros/offroad"} + - {type: capability, field: torque_allowed, equals: true} + - {type: param, key: NeuralNetworkLateralControl, equals: false} +``` + +**Negation across multiple platforms** (everything except Rivian + Tesla-no-bus): +```yaml +enablement: + - {$ref: "#/macros/offroad"} + - {$ref: "#/macros/mads_full_platforms"} # macro encapsulates the not(any(rivian, all(tesla, not(bus)))) logic +``` + +If the same multi-condition block appears in 2+ items, **promote it to a macro** in `_macros.yaml`. Re-run `python sunnypilot/sunnylink/tools/apply_macros.py` to substitute existing inlined matches automatically. + +### Mutual exclusion + +```yaml +- key: FeatureAlpha + widget: toggle + title: Feature Alpha + enablement: + - {type: param, key: FeatureBeta, equals: false} + +- key: FeatureBeta + widget: toggle + title: Feature Beta + enablement: + - {type: param, key: FeatureAlpha, equals: false} +``` + +### Add a section + +In the page YAML, add an entry to the `sections` list: +```yaml +sections: + - id: my_section + title: My Section + description: Optional subtitle + enablement: + - {$ref: "#/macros/longitudinal"} + items: + - {key: ..., widget: toggle, title: ...} +``` + +Sections support `visibility`, `enablement`, and `attestation_required`. When section-level rules fail, all items within are dimmed. + +### Add a sub-panel + +Sub-panels nest inside the section they belong to: +```yaml +sections: + - id: parent_section + title: Parent + items: [...] + sub_panels: + - id: my_sub + label: Advanced Settings + trigger_key: ParentParam + trigger_condition: {type: param, key: ParentParam, equals: true} + items: + - {key: ..., widget: toggle, title: ...} +``` + +### Add vehicle-brand settings + +Edit `pages/vehicle.yaml`. Each section is a brand: +```yaml +id: vehicle +kind: vehicle +sections: + - id: rivian + title: Rivian Settings + description: '' + items: + - key: RivianFeature + widget: toggle + title: Rivian One Pedal + enablement: + - {$ref: "#/macros/offroad"} +``` + +`kind: vehicle` tells the compiler to emit this page as `vehicle_settings.` in the wire JSON. + +### Add a feature with toggles, sub-panel, and macro + +Example: "Smart Wipers" with a master toggle, intensity selector, and sub-panel for advanced tuning, gated to torque-steering Hyundais on offroad. + +1. **Param keys** — register all 4 in `common/params_keys.h`. + +2. **Decide on a macro** — if "torque Hyundai" gating is reused, add to `_macros.yaml`: + ```yaml + torque_hyundai: + - {$ref: "#/macros/offroad"} + - {type: capability, field: brand, equals: hyundai} + - {type: capability, field: torque_allowed, equals: true} + ``` + +3. **Edit the relevant page** — `pages/visuals.yaml` (or wherever the feature lives). Add a new section + sub_panel: + ```yaml + sections: + - id: smart_wipers + title: Smart Wipers + description: Camera-driven wiper control (Hyundai/Kia, torque only) + items: + - key: SmartWipersEnabled + widget: toggle + title: Enable Smart Wipers + enablement: + - {$ref: "#/macros/torque_hyundai"} + - key: SmartWipersIntensity + widget: multiple_button + title: Sensitivity + options: + - {value: 0, label: Low} + - {value: 1, label: Medium} + - {value: 2, label: High} + visibility: + - {type: param, key: SmartWipersEnabled, equals: true} + enablement: + - {$ref: "#/macros/torque_hyundai"} + sub_panels: + - id: smart_wipers_tuning + label: Smart Wipers Tuning + trigger_key: SmartWipersEnabled + trigger_condition: {type: param, key: SmartWipersEnabled, equals: true} + items: + - key: SmartWipersHysteresis + widget: option + title: Hysteresis (frames) + min: 1 + max: 30 + step: 1 + enablement: + - {$ref: "#/macros/offroad"} + - {$ref: "#/macros/advanced_only"} + ``` + +4. **Compile / validate / test**: + ``` + python sunnypilot/sunnylink/tools/compile_settings_ui.py + python sunnypilot/sunnylink/tools/validate_settings_ui.py + uv run python -m pytest sunnypilot/sunnylink/tests/ + ``` + + `apply_macros.py` is automatic for newly-added items only if you wrote the rule list inline; for greenfield items, you'd write `$ref` directly. + +### Change a toggle's behavior + +1. Find the item in `pages/.yaml`. +2. Edit `visibility`/`enablement`/`options[].enablement` directly. Use macros where possible. +3. **Add a regression test** in `sunnypilot/sunnylink/tests/test_settings_changes.py` that asserts the new gate exists. Use existing tests (e.g. `TestMadsBrandGates`, `TestNotEngagedReplacement`) as templates: lookup item by key, assert `_references_capability_field(rules, "...")` or `_flatten_rule_types(rules)` contains/excludes a type. This freezes the new behavior so a future edit won't silently revert it. +4. Compile + run the full suite. Per-bug test should pass; structural tests should remain green. + +### Change a widget type or options + +Editing `widget:` from `toggle` to `multiple_button` is a frontend behavior change. Whenever you change widget shape: +- The param's underlying type (bool / int / string) must match what the new widget writes. `toggle` writes bool; `multiple_button`/`option` write int/string. Update `params_keys.h` if the type changes. +- Add an `options:` list when switching to `multiple_button` or `option`. +- Old values stored on devices may not be valid for the new widget. Consider a migration in `sunnypilot/system/updated/` if users have stale values. + +### Deprecate or remove a setting + +1. Remove the item from `pages/.yaml`. +2. Remove the param key from `common/params_keys.h` **only after** confirming nothing in `selfdrive/`, `sunnypilot/`, or any controls code reads it. +3. If the param has been on user devices, drop it via a migration (see `sunnypilot/system/updated/`) so stale values don't linger. +4. Compile + validate + test. The validator's "no duplicate keys" + structural checks will fail if anything still references the removed key. + +### Move a setting to another page + +Cut the item block from one page YAML, paste into the target page's section. Compile + validate. The "no duplicate keys" check catches forgotten copies. + +### Change display text + +Edit `title:` or `description:` in the page YAML and recompile to regenerate `settings_ui.json`. + +### Reorder sections, sub-panels, and items + +Reorder them within their parent list in the YAML. The compiler preserves authored order — no `order:` field required at the section/sub_panel/item level (panel-level `order:` controls which page comes first in the side nav). + +--- + +### Capability labels and tooltips + +The schema response includes `capability_labels`, which map capability field names to descriptions. The frontend uses these to show contextual tooltips when a capability rule prevents a setting from being used. + +The device defines these labels in `capabilities.py:CAPABILITY_LABELS`. Examples: + +- `has_longitudinal_control` → "sunnypilot longitudinal control" +- `torque_allowed` → "torque steering (not available for angle steering vehicles)" +- `brand` → "Vehicle brand" + +### Centralized param enforcement + +The device-side UI enforces capability constraints in `selfdrive/ui/sunnypilot/ui_state.py:_enforce_constraints()`, which removes incompatible params based on car capabilities. This is the single source of truth for such constraints. + +Settings layouts should not duplicate these params.remove() calls. Instead, rely on schema rules and centralized enforcement to prevent duplicate logic and ensure consistency. + +Example constraints in `_enforce_constraints()`: +- Angle steering cars: remove `EnforceTorqueControl` and `NeuralNetworkLateralControl` +- No CarParams: remove all car-dependent params +- No longitudinal: remove `ExperimentalMode` +- No ICBM: remove `IntelligentCruiseButtonManagement` diff --git a/openpilot/sunnypilot/sunnylink/registration_manager.py b/openpilot/sunnypilot/sunnylink/registration_manager.py new file mode 100755 index 0000000000..cc43dcae87 --- /dev/null +++ b/openpilot/sunnypilot/sunnylink/registration_manager.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python3 +import time + +from openpilot.common.params import Params +from openpilot.common.realtime import Ratekeeper +from openpilot.common.swaglog import cloudlog + +from openpilot.cereal import log, messaging +from openpilot.sunnypilot.sunnylink.utils import register_sunnylink + +NetworkType = log.DeviceState.NetworkType + + +def main(): + """The main method is expected to be called by the manager when the device boots up.""" + try: + rk = Ratekeeper(.5) + sm = messaging.SubMaster(['deviceState'], poll='deviceState') + while True: + sm.update(1000) + if sm['deviceState'].networkType != NetworkType.none: + break + + cloudlog.info(f"Waiting to become online... {time.monotonic()}") + rk.keep_time() + + register_sunnylink() + except Exception: + cloudlog.exception("Sunnylink registration failed") + Params().put_bool("SunnylinkTempFault", True, block=True) + raise + + +if __name__ == "__main__": + main() diff --git a/openpilot/sunnypilot/sunnylink/settings_ui.json b/openpilot/sunnypilot/sunnylink/settings_ui.json new file mode 100644 index 0000000000..1745235d96 --- /dev/null +++ b/openpilot/sunnypilot/sunnylink/settings_ui.json @@ -0,0 +1,2208 @@ +{ + "$schema": "./settings_ui.schema.json", + "schema_version": "1.0", + "panels": [ + { + "id": "steering", + "label": "Steering", + "icon": "steering_wheel", + "order": 1, + "remote_configurable": true, + "description": "Lateral control, lane changes, and steering behavior", + "sections": [ + { + "id": "mads", + "title": "Modular Assistive Driving System (MADS)", + "description": "", + "items": [ + { + "key": "Mads", + "widget": "toggle", + "title": "Enable Modular Assistive Driving System (MADS)", + "description": "Enable MADS. Disable toggle to revert back to stock sunnypilot engagement/disengagement.", + "enablement": [ + { + "type": "offroad_only" + } + ] + } + ], + "sub_panels": [ + { + "id": "mads_settings", + "label": "MADS Settings", + "trigger_key": "Mads", + "trigger_condition": { + "type": "param", + "key": "Mads", + "equals": true + }, + "items": [ + { + "key": "MadsMainCruiseAllowed", + "widget": "toggle", + "title": "Toggle with Main Cruise", + "description": "Note: For vehicles without LFA/LKAS button, disabling this will prevent lateral control engagement.", + "enablement": [ + { + "type": "offroad_only" + }, + { + "type": "not", + "condition": { + "type": "any", + "conditions": [ + { + "type": "capability", + "field": "brand", + "equals": "rivian" + }, + { + "type": "all", + "conditions": [ + { + "type": "capability", + "field": "brand", + "equals": "tesla" + }, + { + "type": "not", + "condition": { + "type": "capability", + "field": "tesla_has_vehicle_bus", + "equals": true + } + } + ] + } + ] + } + } + ] + }, + { + "key": "MadsUnifiedEngagementMode", + "widget": "toggle", + "title": "Unified Engagement Mode (UEM)", + "description": "Engage lateral and longitudinal control with cruise control engagement. Note: Once lateral control is engaged via UEM, it will remain engaged until it is manually disabled via the MADS button or car shut off.", + "enablement": [ + { + "type": "offroad_only" + }, + { + "type": "not", + "condition": { + "type": "any", + "conditions": [ + { + "type": "capability", + "field": "brand", + "equals": "rivian" + }, + { + "type": "all", + "conditions": [ + { + "type": "capability", + "field": "brand", + "equals": "tesla" + }, + { + "type": "not", + "condition": { + "type": "capability", + "field": "tesla_has_vehicle_bus", + "equals": true + } + } + ] + } + ] + } + } + ] + }, + { + "key": "MadsSteeringMode", + "widget": "multiple_button", + "title": "Steering Mode on Brake Pedal", + "description": "Choose how Automatic Lane Centering (ALC) behaves after the brake pedal is manually pressed in sunnypilot.", + "options": [ + { + "value": 0, + "label": "Remain Active", + "enablement": [ + { + "type": "not", + "condition": { + "type": "any", + "conditions": [ + { + "type": "capability", + "field": "brand", + "equals": "rivian" + }, + { + "type": "all", + "conditions": [ + { + "type": "capability", + "field": "brand", + "equals": "tesla" + }, + { + "type": "not", + "condition": { + "type": "capability", + "field": "tesla_has_vehicle_bus", + "equals": true + } + } + ] + } + ] + } + } + ] + }, + { + "value": 1, + "label": "Pause", + "enablement": [ + { + "type": "not", + "condition": { + "type": "any", + "conditions": [ + { + "type": "capability", + "field": "brand", + "equals": "rivian" + }, + { + "type": "all", + "conditions": [ + { + "type": "capability", + "field": "brand", + "equals": "tesla" + }, + { + "type": "not", + "condition": { + "type": "capability", + "field": "tesla_has_vehicle_bus", + "equals": true + } + } + ] + } + ] + } + } + ] + }, + { + "value": 2, + "label": "Disengage" + } + ], + "enablement": [ + { + "type": "offroad_only" + } + ] + } + ] + } + ] + }, + { + "id": "blinker", + "title": "Blinker Control", + "description": "Lateral pause behavior during turn signals", + "items": [ + { + "key": "BlinkerPauseLateralControl", + "widget": "toggle", + "title": "Pause Lateral Control with Blinker", + "description": "Pause lateral control with blinker when traveling below the desired speed selected.", + "sub_items": [ + { + "key": "BlinkerMinLateralControlSpeed", + "widget": "option", + "title": "Minimum Speed to Pause Lateral Control", + "min": 0, + "max": 255, + "step": 5, + "unit": { + "metric": "km/h", + "imperial": "mph" + }, + "enablement": [ + { + "type": "param", + "key": "BlinkerPauseLateralControl", + "equals": true + } + ] + }, + { + "key": "BlinkerLateralReengageDelay", + "widget": "option", + "title": "Post-Blinker Delay", + "description": "Delay before lateral control resumes after the turn signal ends.", + "min": 0, + "max": 10, + "step": 1, + "unit": "second", + "enablement": [ + { + "type": "param", + "key": "BlinkerPauseLateralControl", + "equals": true + } + ] + } + ] + } + ] + }, + { + "id": "torque", + "title": "Torque Control", + "description": "Steering torque tuning and lateral control method", + "enablement": [ + { + "type": "capability", + "field": "torque_allowed", + "equals": true + } + ], + "items": [ + { + "key": "EnforceTorqueControl", + "widget": "toggle", + "title": "Enforce Torque Lateral Control", + "description": "Enable this to enforce sunnypilot to steer with Torque lateral control.", + "visibility": [ + { + "type": "not", + "condition": { + "type": "capability", + "field": "steer_control_type", + "equals": "angle" + } + } + ], + "enablement": [ + { + "type": "offroad_only" + }, + { + "type": "capability", + "field": "torque_allowed", + "equals": true + }, + { + "type": "param", + "key": "NeuralNetworkLateralControl", + "equals": false + } + ] + } + ], + "sub_panels": [ + { + "id": "torque_settings", + "label": "Torque Settings", + "trigger_key": "EnforceTorqueControl", + "trigger_condition": { + "type": "param", + "key": "EnforceTorqueControl", + "equals": true + }, + "items": [ + { + "key": "LiveTorqueParamsToggle", + "widget": "toggle", + "title": "Self-Tune", + "description": "Enables self-tune for Torque lateral control for platforms that do not use Torque lateral control by default.", + "enablement": [ + { + "type": "offroad_only" + } + ] + }, + { + "key": "LiveTorqueParamsRelaxedToggle", + "widget": "toggle", + "title": "Less Restrict Settings for Self-Tune (Beta)", + "description": "Less strict settings when using Self-Tune. This allows torqued to be more forgiving when learning values.", + "enablement": [ + { + "type": "offroad_only" + }, + { + "type": "param", + "key": "LiveTorqueParamsToggle", + "equals": true + } + ] + }, + { + "key": "CustomTorqueParams", + "widget": "toggle", + "title": "Enable Custom Tuning", + "description": "Enables custom tuning for Torque lateral control. Modifying Lateral Acceleration Factor and Friction below will override the offline values indicated in the YAML files within \"opendbc/car/torque_data\". The values will also be used live when \"Manual Real-Time Tuning\" toggle is enabled.", + "enablement": [ + { + "type": "offroad_only" + } + ] + }, + { + "key": "TorqueParamsOverrideEnabled", + "widget": "toggle", + "title": "Manual Real-Time Tuning", + "description": "Enforces the torque lateral controller to use the fixed values instead of the learned values from Self-Tune. Enabling this toggle overrides Self-Tune values.", + "enablement": [ + { + "type": "offroad_only" + }, + { + "type": "param", + "key": "CustomTorqueParams", + "equals": true + } + ] + }, + { + "key": "TorqueParamsOverrideLatAccelFactor", + "widget": "option", + "title": "Lateral Acceleration Factor", + "title_param_suffix": { + "param": "TorqueParamsOverrideEnabled", + "values": { + "true": "(Real-Time & Offline)", + "false": "(Offline Only)" + } + }, + "min": 0.1, + "max": 5.0, + "step": 0.1, + "unit": "m/s\u00b2", + "enablement": [ + { + "type": "param", + "key": "CustomTorqueParams", + "equals": true + }, + { + "type": "any", + "conditions": [ + { + "type": "param", + "key": "TorqueParamsOverrideEnabled", + "equals": true + }, + { + "type": "offroad_only" + } + ] + } + ] + }, + { + "key": "TorqueParamsOverrideFriction", + "widget": "option", + "title": "Friction", + "title_param_suffix": { + "param": "TorqueParamsOverrideEnabled", + "values": { + "true": "(Real-Time & Offline)", + "false": "(Offline Only)" + } + }, + "min": 0.0, + "max": 1.0, + "step": 0.01, + "enablement": [ + { + "type": "param", + "key": "CustomTorqueParams", + "equals": true + }, + { + "type": "any", + "conditions": [ + { + "type": "param", + "key": "TorqueParamsOverrideEnabled", + "equals": true + }, + { + "type": "offroad_only" + } + ] + } + ] + }, + { + "key": "TorqueControlTune", + "widget": "multiple_button", + "title": "Torque Control Tune Version", + "description": "Select the version of Torque Control Tune to use.", + "options": [ + { + "value": "", + "label": "Default" + }, + { + "value": 1.0, + "label": "v1.0" + }, + { + "value": 0.0, + "label": "v0.0" + } + ], + "enablement": [ + { + "type": "offroad_only" + } + ] + } + ] + } + ] + }, + { + "id": "lane_change", + "title": "Lane Change", + "description": "Automatic lane change timing and behavior", + "items": [ + { + "key": "AutoLaneChangeTimer", + "widget": "option", + "title": "Auto Lane Change by Blinker", + "description": "Set a timer to delay the auto lane change operation when the blinker is used. No nudge on the steering wheel is required to auto lane change if a timer is set. Default is Nudge.", + "details": "Please use caution when using this feature. Only use the blinker when traffic and road conditions permit.", + "options": [ + { + "value": -1, + "label": "Off" + }, + { + "value": 0, + "label": "Nudge" + }, + { + "value": 1, + "label": "Nudgeless" + }, + { + "value": 2, + "label": "0.5 second" + }, + { + "value": 3, + "label": "1 second" + }, + { + "value": 4, + "label": "2 seconds" + }, + { + "value": 5, + "label": "3 seconds" + } + ] + }, + { + "key": "AutoLaneChangeBsmDelay", + "widget": "toggle", + "title": "Auto Lane Change: Delay with Blind Spot", + "description": "Toggle to enable a delay timer for lane changes when blind spot monitoring (BSM) detects a vehicle in your blind spot.", + "enablement": [ + { + "type": "capability", + "field": "enable_bsm", + "equals": true + }, + { + "type": "param_compare", + "key": "AutoLaneChangeTimer", + "op": ">", + "value": 0 + } + ] + } + ] + } + ] + }, + { + "id": "cruise", + "label": "Cruise", + "icon": "cruise_control", + "order": 2, + "remote_configurable": true, + "description": "Longitudinal control, speed limits, and cruise behavior", + "sections": [ + { + "id": "core_cruise_features", + "title": "", + "description": "", + "items": [ + { + "key": "ExperimentalMode", + "widget": "toggle", + "title": "Experimental Mode", + "enablement": [ + { + "type": "capability", + "field": "has_longitudinal_control", + "equals": true + } + ] + }, + { + "key": "DynamicExperimentalControl", + "widget": "toggle", + "title": "Dynamic Experimental Control", + "description": "Let the model decide when to use sunnypilot ACC or sunnypilot End to End Longitudinal.", + "visibility": [ + { + "type": "capability", + "field": "has_longitudinal_control", + "equals": true + } + ], + "enablement": [ + { + "type": "capability", + "field": "has_longitudinal_control", + "equals": true + } + ] + }, + { + "key": "DisengageOnAccelerator", + "widget": "toggle", + "title": "Disengage Cruise on Accelerator Pedal", + "description": "When enabled, pressing the accelerator pedal will disengage longitudinal control." + }, + { + "key": "LongitudinalPersonality", + "widget": "multiple_button", + "title": "Driving Personality", + "description": "Standard is recommended. In aggressive mode, sunnypilot will follow lead cars closer and be more aggressive with the gas and brake. In relaxed mode sunnypilot will stay further away from lead cars. On supported cars, you can cycle through these personalities with your steering wheel distance button.", + "options": [ + { + "value": 0, + "label": "Aggressive" + }, + { + "value": 1, + "label": "Standard" + }, + { + "value": 2, + "label": "Relaxed" + } + ], + "enablement": [ + { + "type": "capability", + "field": "has_longitudinal_control", + "equals": true + } + ] + }, + { + "key": "IntelligentCruiseButtonManagement", + "widget": "toggle", + "title": "Intelligent Cruise Button Management (ICBM) (Alpha)", + "visibility": [ + { + "type": "capability", + "field": "icbm_available", + "equals": true + } + ], + "enablement": [ + { + "type": "offroad_only" + }, + { + "type": "not", + "condition": { + "type": "capability", + "field": "has_longitudinal_control", + "equals": true + } + } + ] + } + ] + }, + { + "id": "custom_acc_increments", + "title": "Custom ACC Speed Intervals", + "description": "", + "enablement": [ + { + "type": "offroad_only" + }, + { + "type": "any", + "conditions": [ + { + "type": "all", + "conditions": [ + { + "type": "capability", + "field": "has_longitudinal_control", + "equals": true + }, + { + "type": "not", + "condition": { + "type": "capability", + "field": "pcm_cruise", + "equals": true + } + } + ] + }, + { + "type": "capability", + "field": "has_icbm", + "equals": true + } + ] + } + ], + "items": [ + { + "key": "CustomAccIncrementsEnabled", + "widget": "toggle", + "title": "Enable Custom ACC Speed Intervals", + "enablement": [ + { + "type": "offroad_only" + }, + { + "type": "any", + "conditions": [ + { + "type": "all", + "conditions": [ + { + "type": "capability", + "field": "has_longitudinal_control", + "equals": true + }, + { + "type": "not", + "condition": { + "type": "capability", + "field": "pcm_cruise", + "equals": true + } + } + ] + }, + { + "type": "capability", + "field": "has_icbm", + "equals": true + } + ] + } + ] + } + ], + "sub_panels": [ + { + "id": "custom_acc_intervals", + "label": "Custom ACC Speed Intervals Settings", + "trigger_key": "CustomAccIncrementsEnabled", + "trigger_condition": { + "type": "param", + "key": "CustomAccIncrementsEnabled", + "equals": true + }, + "items": [ + { + "key": "CustomAccShortPressIncrement", + "widget": "option", + "title": "Short Press Increment", + "min": 1, + "max": 10, + "step": 1, + "enablement": [ + { + "type": "param", + "key": "CustomAccIncrementsEnabled", + "equals": true + } + ] + }, + { + "key": "CustomAccLongPressIncrement", + "widget": "option", + "title": "Long Press Increment", + "min": 1, + "max": 10, + "step": 1, + "enablement": [ + { + "type": "param", + "key": "CustomAccIncrementsEnabled", + "equals": true + } + ] + } + ] + } + ] + }, + { + "id": "speed_limits", + "title": "Speed Limits", + "description": "Speed limit detection and offset behavior", + "items": [], + "sub_panels": [ + { + "id": "speed_limit_settings", + "label": "Speed Limit Settings", + "trigger_key": "SpeedLimitMode", + "items": [ + { + "key": "SpeedLimitMode", + "widget": "multiple_button", + "title": "Speed Limit Assist Mode", + "options": [ + { + "value": 0, + "label": "Off" + }, + { + "value": 1, + "label": "Information" + }, + { + "value": 2, + "label": "Warning" + }, + { + "value": 3, + "label": "Assist", + "enablement": [ + { + "type": "any", + "conditions": [ + { + "type": "capability", + "field": "has_longitudinal_control", + "equals": true + }, + { + "type": "capability", + "field": "has_icbm", + "equals": true + } + ] + }, + { + "type": "not", + "condition": { + "type": "capability", + "field": "brand", + "equals": "rivian" + } + }, + { + "type": "not", + "condition": { + "type": "all", + "conditions": [ + { + "type": "capability", + "field": "brand", + "equals": "tesla" + }, + { + "type": "capability", + "field": "is_sp_release", + "equals": true + } + ] + } + } + ] + } + ] + }, + { + "key": "SpeedLimitPolicy", + "widget": "multiple_button", + "title": "Speed Limit Source", + "options": [ + { + "value": 0, + "label": "Car State Only" + }, + { + "value": 1, + "label": "Map Data Only" + }, + { + "value": 2, + "label": "Car State Priority" + }, + { + "value": 3, + "label": "Map Data Priority" + }, + { + "value": 4, + "label": "Combined" + } + ] + }, + { + "key": "SpeedLimitOffsetType", + "widget": "multiple_button", + "title": "Speed Limit Offset Type", + "options": [ + { + "value": 0, + "label": "Off" + }, + { + "value": 1, + "label": "Fixed" + }, + { + "value": 2, + "label": "Percentage" + } + ] + }, + { + "key": "SpeedLimitValueOffset", + "widget": "option", + "title": "Speed Limit Offset Value", + "min": -30, + "max": 30, + "step": 1, + "unit": { + "metric": "km/h", + "imperial": "mph" + }, + "visibility": [ + { + "type": "param_compare", + "key": "SpeedLimitOffsetType", + "op": ">", + "value": 0 + } + ] + } + ] + } + ] + }, + { + "id": "smart_cruise", + "title": "Smart Cruise Control", + "description": "", + "enablement": [ + { + "type": "any", + "conditions": [ + { + "type": "capability", + "field": "has_longitudinal_control", + "equals": true + }, + { + "type": "capability", + "field": "has_icbm", + "equals": true + } + ] + } + ], + "items": [ + { + "key": "SmartCruiseControlVision", + "widget": "toggle", + "title": "Vision", + "description": "Use vision path predictions to estimate the appropriate speed to drive through turns ahead.", + "visibility": [ + { + "type": "any", + "conditions": [ + { + "type": "capability", + "field": "has_longitudinal_control", + "equals": true + }, + { + "type": "capability", + "field": "has_icbm", + "equals": true + } + ] + } + ], + "enablement": [ + { + "type": "any", + "conditions": [ + { + "type": "capability", + "field": "has_longitudinal_control", + "equals": true + }, + { + "type": "capability", + "field": "has_icbm", + "equals": true + } + ] + } + ] + }, + { + "key": "SmartCruiseControlMap", + "widget": "toggle", + "title": "Map", + "description": "Use map data to estimate the appropriate speed to drive through turns ahead.", + "visibility": [ + { + "type": "any", + "conditions": [ + { + "type": "capability", + "field": "has_longitudinal_control", + "equals": true + }, + { + "type": "capability", + "field": "has_icbm", + "equals": true + } + ] + } + ], + "enablement": [ + { + "type": "any", + "conditions": [ + { + "type": "capability", + "field": "has_longitudinal_control", + "equals": true + }, + { + "type": "capability", + "field": "has_icbm", + "equals": true + } + ] + } + ] + } + ] + } + ] + }, + { + "id": "display", + "label": "Display", + "icon": "display", + "order": 3, + "remote_configurable": true, + "description": "Screen brightness, timeout, and interactivity settings", + "sections": [ + { + "id": "brightness_timeout", + "title": "Brightness & Timeout", + "description": "Screen dimming and sleep behavior while driving", + "items": [ + { + "key": "OnroadScreenOffBrightness", + "widget": "multiple_button", + "title": "Onroad Brightness", + "options": [ + { + "value": 0, + "label": "Auto (Default)" + }, + { + "value": 1, + "label": "Auto (Dark)" + }, + { + "value": 2, + "label": "Screen Off" + }, + { + "value": 3, + "label": "5 %" + }, + { + "value": 4, + "label": "10 %" + }, + { + "value": 5, + "label": "15 %" + }, + { + "value": 6, + "label": "20 %" + }, + { + "value": 7, + "label": "25 %" + }, + { + "value": 8, + "label": "30 %" + }, + { + "value": 9, + "label": "35 %" + }, + { + "value": 10, + "label": "40 %" + }, + { + "value": 11, + "label": "45 %" + }, + { + "value": 12, + "label": "50 %" + }, + { + "value": 13, + "label": "55 %" + }, + { + "value": 14, + "label": "60 %" + }, + { + "value": 15, + "label": "65 %" + }, + { + "value": 16, + "label": "70 %" + }, + { + "value": 17, + "label": "75 %" + }, + { + "value": 18, + "label": "80 %" + }, + { + "value": 19, + "label": "85 %" + }, + { + "value": 20, + "label": "90 %" + }, + { + "value": 21, + "label": "95 %" + }, + { + "value": 22, + "label": "100 %" + } + ] + }, + { + "key": "OnroadScreenOffTimer", + "widget": "multiple_button", + "title": "Onroad Brightness Delay", + "options": [ + { + "value": 0, + "label": "Always On" + }, + { + "value": 3, + "label": "3s" + }, + { + "value": 5, + "label": "5s" + }, + { + "value": 10, + "label": "10s" + }, + { + "value": 15, + "label": "15s" + }, + { + "value": 30, + "label": "30s" + }, + { + "value": 60, + "label": "1m" + }, + { + "value": 180, + "label": "3m" + }, + { + "value": 300, + "label": "5m" + }, + { + "value": 600, + "label": "10m" + } + ], + "enablement": [ + { + "type": "not", + "condition": { + "type": "any", + "conditions": [ + { + "type": "param", + "key": "OnroadScreenOffBrightness", + "equals": 0 + }, + { + "type": "param", + "key": "OnroadScreenOffBrightness", + "equals": 1 + } + ] + } + } + ] + }, + { + "key": "InteractivityTimeout", + "widget": "multiple_button", + "title": "Interactivity Timeout", + "description": "Apply a custom timeout for settings UI. This is the time after which settings UI closes automatically if user is not interacting with the screen.", + "options": [ + { + "value": 0, + "label": "Default" + }, + { + "value": 10, + "label": "10 s" + }, + { + "value": 20, + "label": "20 s" + }, + { + "value": 30, + "label": "30 s" + }, + { + "value": 40, + "label": "40 s" + }, + { + "value": 50, + "label": "50 s" + }, + { + "value": 60, + "label": "1 m" + }, + { + "value": 70, + "label": "1 m" + }, + { + "value": 80, + "label": "1 m" + }, + { + "value": 90, + "label": "1 m" + }, + { + "value": 100, + "label": "1 m" + }, + { + "value": 110, + "label": "1 m" + }, + { + "value": 120, + "label": "2 m" + } + ] + } + ] + } + ] + }, + { + "id": "visuals", + "label": "Visuals", + "icon": "visuals", + "order": 4, + "remote_configurable": true, + "description": "HUD overlays, alerts, and on-screen display elements", + "sections": [ + { + "id": "hud_elements", + "title": "HUD Elements", + "description": "Overlays shown on the driving screen", + "items": [ + { + "key": "BlindSpot", + "widget": "toggle", + "title": "Show Blind Spot Warnings", + "description": "Enabling this will display warnings when a vehicle is detected in your blind spot as long as your car has BSM supported." + }, + { + "key": "TorqueBar", + "widget": "toggle", + "title": "Steering Arc", + "description": "Display steering arc on the driving screen when lateral control is enabled." + }, + { + "key": "ShowTurnSignals", + "widget": "toggle", + "title": "Display Turn Signals", + "description": "When enabled, visual turn indicators are drawn on the HUD." + }, + { + "key": "RoadNameToggle", + "widget": "toggle", + "title": "Display Road Name", + "description": "Displays the name of the road the car is traveling on. The OpenStreetMap database of the location must be downloaded to fetch the road name.", + "visibility": [ + { + "type": "not", + "condition": { + "type": "capability", + "field": "device_type", + "equals": "mici" + } + } + ] + }, + { + "key": "StandstillTimer", + "widget": "toggle", + "title": "Standstill Timer", + "description": "Show a timer on the HUD when the car is at a standstill.", + "visibility": [ + { + "type": "not", + "condition": { + "type": "capability", + "field": "device_type", + "equals": "mici" + } + } + ] + }, + { + "key": "RocketFuel", + "widget": "toggle", + "title": "Real-time Acceleration Bar", + "description": "Show an indicator on the left side of the screen to display real-time vehicle acceleration and deceleration. This displays what the car is currently doing, not what the planner is requesting.", + "visibility": [ + { + "type": "not", + "condition": { + "type": "capability", + "field": "device_type", + "equals": "mici" + } + } + ] + }, + { + "key": "ChevronInfo", + "widget": "option", + "title": "Display Metrics Below Chevron", + "options": [ + { + "value": 0, + "label": "Off" + }, + { + "value": 1, + "label": "Distance" + }, + { + "value": 2, + "label": "Speed" + }, + { + "value": 3, + "label": "Time" + }, + { + "value": 4, + "label": "All" + } + ], + "visibility": [ + { + "type": "not", + "condition": { + "type": "capability", + "field": "device_type", + "equals": "mici" + } + } + ], + "enablement": [ + { + "type": "capability", + "field": "has_longitudinal_control", + "equals": true + } + ] + } + ] + }, + { + "id": "developer_ui", + "title": "Developer UI Info", + "description": "Speedometer and debug display options", + "visibility": [ + { + "type": "not", + "condition": { + "type": "capability", + "field": "device_type", + "equals": "mici" + } + } + ], + "items": [ + { + "key": "DevUIInfo", + "widget": "option", + "title": "Developer UI", + "description": "Display real-time parameters and metrics from various sources.", + "options": [ + { + "value": 0, + "label": "Off" + }, + { + "value": 1, + "label": "Bottom" + }, + { + "value": 2, + "label": "Right" + }, + { + "value": 3, + "label": "Right & Bottom" + } + ] + }, + { + "key": "TrueVEgoUI", + "widget": "toggle", + "title": "Speedometer: Always Display True Speed", + "description": "For applicable vehicles, always display the true vehicle current speed from wheel speed sensors." + }, + { + "key": "HideVEgoUI", + "widget": "toggle", + "title": "Speedometer: Hide from Onroad Screen", + "description": "When enabled, the speedometer on the onroad screen is not displayed." + } + ] + }, + { + "id": "alerts_extras", + "title": "Alerts & Extras", + "description": "Traffic light alerts and visual flair", + "items": [ + { + "key": "GreenLightAlert", + "widget": "toggle", + "title": "Green Traffic Light Alert (Beta)", + "description": "A chime and on-screen alert will play when the traffic light you are waiting for turns green and you have no vehicle in front of you. On-screen visual alert is only available on comma 3X. Note: This chime is only designed as a notification. It is the driver's responsibility to observe their environment and make decisions accordingly." + }, + { + "key": "LeadDepartAlert", + "widget": "toggle", + "title": "Lead Departure Alert (Beta)", + "description": "A chime and on-screen alert will play when you are stopped, and the vehicle in front of you start moving. On-screen visual alert is only available on comma 3X. Note: This chime is only designed as a notification. It is the driver's responsibility to observe their environment and make decisions accordingly." + }, + { + "key": "RainbowMode", + "widget": "toggle", + "title": "Tesla Rainbow Mode", + "description": "Display a rainbow effect on the path the model wants to take. It does not affect driving in any way." + } + ] + } + ] + }, + { + "id": "toggles", + "label": "Toggles", + "icon": "toggles", + "order": 5, + "remote_configurable": true, + "description": "Core openpilot feature toggles", + "sections": [ + { + "id": "core_toggles", + "title": "", + "description": "", + "items": [ + { + "key": "OpenpilotEnabledToggle", + "widget": "toggle", + "needs_onroad_cycle": true, + "title": "Enable sunnypilot", + "description": "Use the sunnypilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature.", + "enablement": [ + { + "type": "offroad_only" + } + ] + }, + { + "key": "IsLdwEnabled", + "widget": "toggle", + "title": "Enable Lane Departure Warnings", + "description": "Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h)." + }, + { + "key": "AlwaysOnDM", + "widget": "toggle", + "title": "Always-On Driver Monitoring", + "description": "Enable driver monitoring even when sunnypilot is not engaged." + }, + { + "key": "IsMetric", + "widget": "toggle", + "title": "Use Metric System", + "description": "Display speed in km/h instead of mph." + } + ] + }, + { + "id": "recording", + "title": "Recording", + "description": "Camera and audio recording during drives", + "items": [ + { + "key": "RecordFront", + "widget": "toggle", + "needs_onroad_cycle": true, + "title": "Record and Upload Driver Camera", + "description": "Upload data from the driver facing camera and help improve the driver monitoring algorithm." + }, + { + "key": "RecordAudio", + "widget": "toggle", + "needs_onroad_cycle": true, + "title": "Record and Upload Microphone Audio", + "description": "Record and store microphone audio while driving. The audio will be included in the dashcam video in comma connect." + } + ] + } + ] + }, + { + "id": "device", + "label": "Device", + "icon": "device", + "order": 6, + "remote_configurable": true, + "description": "Device behavior, units, and recording settings", + "sections": [ + { + "id": "general", + "title": "General", + "description": "Power, boot, and unit preferences", + "items": [ + { + "key": "OffroadMode", + "widget": "toggle", + "title": "Force Offroad Mode" + }, + { + "key": "DeviceBootMode", + "widget": "option", + "title": "Wake Up Behavior", + "description": "Controls state of the device after boot/sleep. Default: Device will boot/wake-up normally and will be ready to engage. Offroad: Device will be in Always Offroad mode after boot/wake-up.", + "options": [ + { + "value": 0, + "label": "Standard" + }, + { + "value": 1, + "label": "Always Offroad" + } + ] + }, + { + "key": "QuietMode", + "widget": "toggle", + "title": "Quiet Mode" + }, + { + "key": "OnroadUploads", + "widget": "toggle", + "title": "Onroad Uploads" + }, + { + "key": "MaxTimeOffroad", + "widget": "option", + "title": "Max Time Offroad", + "description": "Device will automatically shutdown after set time once the engine is turned off. 30h is the default.", + "options": [ + { + "value": 0, + "label": "Always On" + }, + { + "value": 5, + "label": "5m" + }, + { + "value": 10, + "label": "10m" + }, + { + "value": 15, + "label": "15m" + }, + { + "value": 30, + "label": "30m" + }, + { + "value": 60, + "label": "1h" + }, + { + "value": 120, + "label": "2h" + }, + { + "value": 180, + "label": "3h" + }, + { + "value": 300, + "label": "5h" + }, + { + "value": 600, + "label": "10h" + }, + { + "value": 1440, + "label": "24h" + }, + { + "value": 1800, + "label": "30h (Default)" + } + ] + } + ] + }, + { + "id": "language", + "title": "Language", + "items": [ + { + "key": "LanguageSetting", + "widget": "info", + "title": "Language" + } + ] + } + ] + }, + { + "id": "software", + "label": "Software", + "icon": "software", + "order": 7, + "remote_configurable": true, + "description": "Software update preferences", + "sections": [ + { + "id": "updates", + "title": "Updates", + "description": "Control software updates", + "items": [ + { + "key": "DisableUpdates", + "widget": "toggle", + "title": "Disable Updates", + "description": "When enabled, software updates will be off. This requires a reboot to take effect.", + "enablement": [ + { + "type": "offroad_only" + }, + { + "type": "param", + "key": "ShowAdvancedControls", + "equals": true + } + ] + } + ] + } + ] + }, + { + "id": "developer", + "label": "Developer", + "icon": "developer", + "order": 9, + "remote_configurable": true, + "description": "Debug tools, remote access, and advanced services", + "sections": [ + { + "id": "connectivity", + "title": "Connectivity", + "description": "Remote access and debugging interfaces", + "items": [ + { + "key": "AdbEnabled", + "widget": "toggle", + "blocked": true, + "title": "Enable ADB", + "description": "ADB (Android Debug Bridge) allows connecting to your device over USB or over the network. See https://docs.comma.ai/how-to/connect-to-comma for more info.", + "enablement": [ + { + "type": "offroad_only" + } + ] + }, + { + "key": "SshEnabled", + "widget": "toggle", + "blocked": true, + "title": "Enable SSH" + }, + { + "key": "JoystickDebugMode", + "widget": "toggle", + "title": "Joystick Debug Mode", + "enablement": [ + { + "type": "offroad_only" + } + ] + }, + { + "key": "AlphaLongitudinalEnabled", + "widget": "toggle", + "needs_onroad_cycle": true, + "title": "sunnypilot Longitudinal Control (Alpha)", + "description": "WARNING: sunnypilot longitudinal control is in alpha for this car and will disable Automatic Emergency Braking (AEB). On this car, sunnypilot defaults to the car's built-in ACC instead of sunnypilot's longitudinal control. Enable this to switch to sunnypilot longitudinal control. Enabling Experimental mode is recommended when enabling sunnypilot longitudinal control alpha. Changing this setting will restart sunnypilot if the car is powered on.", + "visibility": [ + { + "type": "all", + "conditions": [ + { + "type": "capability", + "field": "alpha_long_available", + "equals": true + }, + { + "type": "not", + "condition": { + "type": "capability", + "field": "has_icbm", + "equals": true + } + } + ] + } + ], + "enablement": [ + { + "type": "not_engaged" + } + ] + }, + { + "key": "ShowDebugInfo", + "widget": "toggle", + "title": "UI Debug Mode" + } + ] + }, + { + "id": "test_maneuvers", + "title": "Test Maneuvers", + "description": "DANGER: enabling these maneuvers replaces normal driving behavior with deterministic test sequences. Each toggle requires explicit confirmation per write. Use only in a closed environment.", + "visibility": [ + { + "type": "any", + "conditions": [ + { + "type": "capability", + "field": "is_development", + "equals": true + }, + { + "type": "capability", + "field": "is_sp_release", + "equals": true + } + ] + } + ], + "enablement": [ + { + "type": "any", + "conditions": [ + { + "type": "capability", + "field": "is_development", + "equals": true + }, + { + "type": "param", + "key": "ShowAdvancedControls", + "equals": true + } + ] + } + ], + "attestation_required": true, + "items": [ + { + "key": "LateralManeuverMode", + "widget": "toggle", + "title": "[TEST] Lateral Maneuver Mode", + "description": "Replaces normal lateral control with a deterministic test sequence. NOT for road use.", + "enablement": [ + { + "type": "not_engaged" + }, + { + "type": "capability", + "field": "torque_allowed", + "equals": true + } + ] + }, + { + "key": "LongitudinalManeuverMode", + "widget": "toggle", + "title": "[TEST] Longitudinal Maneuver Mode", + "description": "Replaces normal longitudinal control with a deterministic test sequence. NOT for road use.", + "enablement": [ + { + "type": "not_engaged" + }, + { + "type": "capability", + "field": "has_longitudinal_control", + "equals": true + } + ] + } + ] + }, + { + "id": "advanced_services", + "title": "Advanced Settings", + "description": "", + "items": [ + { + "key": "ShowAdvancedControls", + "widget": "toggle", + "title": "Show Advanced Controls", + "description": "Toggle visibility of advanced sunnypilot controls. This only changes the visibility of the toggles; it does not change the actual enabled/disabled state." + }, + { + "key": "EnableGithubRunner", + "widget": "toggle", + "title": "GitHub Runner Service", + "description": "Enables or disables the GitHub runner service.", + "visibility": [ + { + "type": "not", + "condition": { + "type": "capability", + "field": "is_sp_release", + "equals": true + } + } + ], + "enablement": [ + { + "type": "param", + "key": "ShowAdvancedControls", + "equals": true + } + ] + }, + { + "key": "EnableCopyparty", + "widget": "toggle", + "title": "copyparty Service", + "description": "copyparty is a very capable file server, you can use it to download your routes, view your logs and even make some edits on some files from your browser. Requires you to connect to your comma locally via its IP address.", + "enablement": [ + { + "type": "param", + "key": "ShowAdvancedControls", + "equals": true + } + ] + }, + { + "key": "QuickBootToggle", + "widget": "toggle", + "title": "Quickboot Mode", + "visibility": [ + { + "type": "not", + "condition": { + "type": "any", + "conditions": [ + { + "type": "capability", + "field": "is_sp_release", + "equals": true + }, + { + "type": "capability", + "field": "is_development", + "equals": true + } + ] + } + } + ], + "enablement": [ + { + "type": "param", + "key": "DisableUpdates", + "equals": true + }, + { + "type": "param", + "key": "ShowAdvancedControls", + "equals": true + } + ] + } + ] + } + ] + }, + { + "id": "models", + "label": "Models", + "icon": "models", + "order": 10, + "remote_configurable": false, + "description": "Driving model behavior and camera calibration", + "sections": [ + { + "id": "model_behavior", + "title": "Model Behavior", + "description": "Lane desire and lead-vehicle awareness tuning", + "items": [ + { + "key": "LaneTurnDesire", + "widget": "toggle", + "title": "Use Lane Turn Desires", + "description": "If you are driving at 20 mph (32 km/h) or below and have your blinker on, the car will plan a turn in that direction at the nearest drivable path. This prevents situations (like at red lights) where the car might plan the wrong turn direction." + }, + { + "key": "LaneTurnValue", + "widget": "option", + "title": "Adjust Lane Turn Speed", + "description": "Set the maximum speed for lane turn desires.", + "min": 0, + "max": 20, + "step": 1, + "unit": { + "metric": "km/h", + "imperial": "mph" + }, + "enablement": [ + { + "type": "param", + "key": "LaneTurnDesire", + "equals": true + }, + { + "type": "param", + "key": "ShowAdvancedControls", + "equals": true + } + ] + }, + { + "key": "LagdToggle", + "widget": "toggle", + "title": "Live Learning Steer Delay", + "description": "Allow device to learn and adapt car's steering response time" + }, + { + "key": "LagdToggleDelay", + "widget": "option", + "title": "Adjust Software Delay", + "description": "Adjust the software delay when Live Learning Steer Delay is toggled off. The default software delay value is 0.2", + "min": 0.05, + "max": 0.5, + "step": 0.01, + "enablement": [ + { + "type": "not", + "condition": { + "type": "param", + "key": "LagdToggle", + "equals": true + } + }, + { + "type": "param", + "key": "ShowAdvancedControls", + "equals": true + } + ] + } + ] + }, + { + "id": "lateral_control", + "title": "Lateral Control", + "description": "Neural network lateral control for supported models", + "items": [ + { + "key": "NeuralNetworkLateralControl", + "widget": "toggle", + "title": "Neural Network Lateral Control (NNLC)", + "description": "Use a neural network for lateral control instead of the default torque controller.", + "visibility": [ + { + "type": "not", + "condition": { + "type": "capability", + "field": "steer_control_type", + "equals": "angle" + } + } + ], + "enablement": [ + { + "type": "offroad_only" + }, + { + "type": "capability", + "field": "torque_allowed", + "equals": true + }, + { + "type": "param", + "key": "EnforceTorqueControl", + "equals": false + } + ] + } + ] + }, + { + "id": "camera", + "title": "Camera", + "description": "Camera position and calibration", + "items": [ + { + "key": "CameraOffset", + "widget": "option", + "title": "Adjust Camera Offset", + "description": "Virtually shift camera's perspective to move model's center to Left(+ values) or Right (- values)", + "min": -0.35, + "max": 0.35, + "step": 0.01, + "unit": "meters", + "enablement": [ + { + "type": "param", + "key": "ShowAdvancedControls", + "equals": true + } + ] + } + ] + } + ] + } + ], + "vehicle_settings": { + "hyundai": { + "title": "Hyundai / Kia / Genesis Settings", + "description": "", + "items": [ + { + "key": "HyundaiLongitudinalTuning", + "widget": "multiple_button", + "title": "Custom Longitudinal Tuning", + "options": [ + { + "value": 0, + "label": "Off" + }, + { + "value": 1, + "label": "Dynamic" + }, + { + "value": 2, + "label": "Predictive" + } + ], + "visibility": [ + { + "type": "capability", + "field": "hyundai_alpha_long_available", + "equals": true + } + ], + "enablement": [ + { + "type": "offroad_only" + }, + { + "type": "capability", + "field": "has_longitudinal_control", + "equals": true + } + ] + } + ] + }, + "subaru": { + "title": "Subaru Settings", + "description": "", + "items": [ + { + "key": "SubaruStopAndGo", + "widget": "toggle", + "title": "Stop and Go (Beta)", + "enablement": [ + { + "type": "offroad_only" + }, + { + "type": "capability", + "field": "has_stop_and_go", + "equals": true + } + ] + }, + { + "key": "SubaruStopAndGoManualParkingBrake", + "widget": "toggle", + "title": "Stop and Go for Manual Parking Brake (Beta)", + "enablement": [ + { + "type": "offroad_only" + }, + { + "type": "capability", + "field": "has_stop_and_go", + "equals": true + } + ] + } + ] + }, + "tesla": { + "title": "Tesla Settings", + "description": "", + "items": [ + { + "key": "TeslaCoopSteering", + "widget": "toggle", + "title": "Cooperative Steering (Beta)", + "enablement": [ + { + "type": "offroad_only" + } + ] + } + ] + }, + "toyota": { + "title": "Toyota / Lexus Settings", + "description": "", + "items": [ + { + "key": "ToyotaEnforceStockLongitudinal", + "widget": "toggle", + "needs_onroad_cycle": true, + "title": "Enforce Factory Longitudinal Control", + "description": "sunnypilot will not take over control of gas and brakes. Factory Toyota longitudinal control will be used.", + "enablement": [ + { + "type": "not_engaged" + } + ] + }, + { + "key": "ToyotaStopAndGoHack", + "widget": "toggle", + "needs_onroad_cycle": true, + "title": "Stop and Go Hack (Alpha)", + "description": "sunnypilot will allow some Toyota/Lexus cars to auto resume during stop and go traffic. This feature is only applicable to certain models that are able to use longitudinal control. This is an alpha feature. Use at your own risk.", + "enablement": [ + { + "type": "not_engaged" + }, + { + "type": "capability", + "field": "has_longitudinal_control", + "equals": true + }, + { + "type": "param", + "key": "ToyotaEnforceStockLongitudinal", + "equals": false + } + ] + } + ] + } + } +} diff --git a/openpilot/sunnypilot/sunnylink/settings_ui.schema.json b/openpilot/sunnypilot/sunnylink/settings_ui.schema.json new file mode 100644 index 0000000000..38c7d1b5ab --- /dev/null +++ b/openpilot/sunnypilot/sunnylink/settings_ui.schema.json @@ -0,0 +1,516 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://sunnypilot.com/schemas/settings_ui.schema.json", + "title": "sunnypilot Settings UI Schema", + "description": "Defines the structure of the sunnypilot settings UI panels, items, rules, and vehicle-specific settings.", + "type": "object", + "required": ["schema_version", "panels", "vehicle_settings"], + "additionalProperties": false, + "properties": { + "$schema": { + "type": "string", + "description": "JSON Schema reference for editor support." + }, + "schema_version": { + "type": "string", + "description": "Version of the settings UI schema format.", + "examples": ["1.0"] + }, + "panels": { + "type": "array", + "description": "Top-level settings panels displayed in the UI.", + "items": { + "$ref": "#/$defs/Panel" + } + }, + "vehicle_settings": { + "type": "object", + "description": "Brand-keyed vehicle-specific settings. Each key is a car brand (e.g. 'hyundai', 'toyota').", + "additionalProperties": { + "$ref": "#/$defs/VehicleBrandSettings" + } + } + }, + "$defs": { + "Panel": { + "type": "object", + "description": "A top-level settings panel (tab) in the UI.", + "required": ["id", "label", "icon", "order"], + "additionalProperties": false, + "properties": { + "id": { + "type": "string", + "description": "Unique identifier for this panel." + }, + "label": { + "type": "string", + "description": "Display label shown in the UI." + }, + "icon": { + "type": "string", + "description": "Icon identifier for this panel." + }, + "order": { + "type": "integer", + "description": "Sort order for panel display.", + "minimum": 0 + }, + "description": { + "type": "string", + "description": "Optional description shown below the panel label." + }, + "remote_configurable": { + "type": "boolean", + "description": "Whether this panel's settings can be changed remotely via sunnylink.", + "default": false + }, + "sections": { + "type": "array", + "description": "Grouped sections within this panel.", + "items": { + "$ref": "#/$defs/PanelSection" + } + }, + "items": { + "type": "array", + "description": "Settings items directly in this panel (no section grouping).", + "items": { + "$ref": "#/$defs/SchemaItem" + } + }, + "sub_panels": { + "type": "array", + "description": "Nested sub-panels triggered by a setting.", + "items": { + "$ref": "#/$defs/SubPanel" + } + } + } + }, + "PanelSection": { + "type": "object", + "description": "A grouped section within a panel.", + "required": ["id", "title"], + "additionalProperties": false, + "properties": { + "id": { + "type": "string", + "description": "Unique identifier for this section." + }, + "title": { + "type": "string", + "description": "Display title for this section." + }, + "description": { + "type": "string", + "description": "Optional description shown below the section title." + }, + "order": { + "type": "integer", + "description": "Sort order within the parent panel.", + "minimum": 0 + }, + "visibility": { + "type": "array", + "description": "Rules that determine whether this section is visible. All rules must pass.", + "items": { + "$ref": "#/$defs/Rule" + } + }, + "enablement": { + "type": "array", + "description": "Rules that determine whether items in this section are enabled. All rules must pass.", + "items": { + "$ref": "#/$defs/Rule" + } + }, + "attestation_required": { + "type": "boolean", + "description": "When true, the UI must show an attestation modal before any write to items in this section.", + "default": false + }, + "items": { + "type": "array", + "description": "Settings items within this section.", + "items": { + "$ref": "#/$defs/SchemaItem" + } + }, + "sub_panels": { + "type": "array", + "description": "Nested sub-panels within this section.", + "items": { + "$ref": "#/$defs/SubPanel" + } + } + } + }, + "VehicleBrandSettings": { + "type": "object", + "description": "Brand-specific settings group inside vehicle_settings.", + "required": ["items"], + "additionalProperties": false, + "properties": { + "title": { + "type": "string", + "description": "Display title for this brand's settings group." + }, + "description": { + "type": "string", + "description": "Optional description shown below the brand title." + }, + "items": { + "type": "array", + "description": "Settings items for this brand.", + "items": { + "$ref": "#/$defs/SchemaItem" + } + } + } + }, + "SchemaItem": { + "type": "object", + "description": "A single settings item (toggle, option selector, button group, etc.).", + "required": ["key", "widget"], + "additionalProperties": false, + "properties": { + "key": { + "type": "string", + "description": "The param key this item reads/writes." + }, + "widget": { + "type": "string", + "description": "The UI widget type to render.", + "enum": ["toggle", "option", "multiple_button", "button", "info"] + }, + "title": { + "type": "string", + "description": "Override display title (defaults to metadata lookup by key)." + }, + "description": { + "type": "string", + "description": "Override description text. Rendered inline below the title. May be empty when only `details` is used." + }, + "details": { + "type": "string", + "description": "Extended help text shown in a popover/modal when the user taps an info ('i') button on the row. Independent of `description`: either, both, or neither may be present." + }, + "options": { + "type": "array", + "description": "Available options for 'option' or 'multiple_button' widgets.", + "items": { + "$ref": "#/$defs/SchemaOption" + } + }, + "min": { + "type": "number", + "description": "Minimum value for numeric option widgets." + }, + "max": { + "type": "number", + "description": "Maximum value for numeric option widgets." + }, + "step": { + "type": "number", + "description": "Step increment for numeric option widgets." + }, + "unit": { + "oneOf": [ + { + "type": "string", + "description": "Static unit label (e.g. 'seconds', 'm/s²')." + }, + { + "type": "object", + "description": "Dynamic unit that changes based on IsMetric param.", + "required": ["metric", "imperial"], + "additionalProperties": false, + "properties": { + "metric": { + "type": "string", + "description": "Unit label when IsMetric is true (e.g. 'km/h')." + }, + "imperial": { + "type": "string", + "description": "Unit label when IsMetric is false (e.g. 'mph')." + } + } + } + ], + "description": "Unit label for numeric values. Use a string for static units or an object with metric/imperial variants for units that depend on the IsMetric param." + }, + "value_map": { + "type": "object", + "description": "Maps stored values to display labels.", + "additionalProperties": { + "type": "string" + } + }, + "visibility": { + "type": "array", + "description": "Rules that determine whether this item is visible. All rules must pass.", + "items": { + "$ref": "#/$defs/Rule" + } + }, + "enablement": { + "type": "array", + "description": "Rules that determine whether this item is enabled/interactive. All rules must pass.", + "items": { + "$ref": "#/$defs/Rule" + } + }, + "sub_items": { + "type": "array", + "description": "Child items nested under this item (e.g. options revealed by a toggle).", + "items": { + "$ref": "#/$defs/SchemaItem" + } + }, + "action": { + "type": "string", + "description": "Action identifier for button widgets." + }, + "title_param_suffix": { + "type": "object", + "description": "Renders an extra suffix in the item title chosen by the value of another param.", + "required": ["param", "values"], + "additionalProperties": false, + "properties": { + "param": { + "type": "string", + "description": "Param key whose value selects the suffix label." + }, + "values": { + "type": "object", + "description": "Map from stringified param value to suffix label.", + "additionalProperties": { + "type": "string" + } + } + } + }, + "needs_onroad_cycle": { + "type": "boolean", + "description": "When true, the device must cycle onroad/offroad for the new value to take effect.", + "default": false + }, + "blocked": { + "type": "boolean", + "description": "When true, this item is treated as DEVICE_ONLY and the dashboard must not write it remotely.", + "default": false + }, + "requires_attestation": { + "type": "boolean", + "description": "When true, writes to this item require an explicit per-write confirmation modal.", + "default": false + } + } + }, + "SubPanel": { + "type": "object", + "description": "A nested panel that opens when triggered by a parent item.", + "required": ["id", "label", "trigger_key"], + "additionalProperties": false, + "properties": { + "id": { + "type": "string", + "description": "Unique identifier for this sub-panel." + }, + "label": { + "type": "string", + "description": "Display label for the sub-panel header." + }, + "trigger_key": { + "type": "string", + "description": "The param key that triggers opening this sub-panel." + }, + "trigger_condition": { + "$ref": "#/$defs/Rule", + "description": "Optional rule that must evaluate to true for the sub-panel trigger to be active." + }, + "items": { + "type": "array", + "description": "Settings items within this sub-panel.", + "items": { + "$ref": "#/$defs/SchemaItem" + } + } + } + }, + "SchemaOption": { + "type": "object", + "description": "A selectable option for option/multiple_button widgets.", + "required": ["value", "label"], + "additionalProperties": false, + "properties": { + "value": { + "oneOf": [ + { "type": "number" }, + { "type": "string" } + ], + "description": "The stored value when this option is selected." + }, + "label": { + "type": "string", + "description": "The display label for this option." + }, + "enablement": { + "type": "array", + "description": "Rules that determine whether this option is selectable. All rules must pass.", + "items": { + "$ref": "#/$defs/Rule" + } + } + } + }, + "Rule": { + "description": "A visibility or enablement rule. Discriminated union on the 'type' field.", + "oneOf": [ + { "$ref": "#/$defs/RuleOffroadOnly" }, + { "$ref": "#/$defs/RuleNotEngaged" }, + { "$ref": "#/$defs/RuleCapability" }, + { "$ref": "#/$defs/RuleParam" }, + { "$ref": "#/$defs/RuleParamCompare" }, + { "$ref": "#/$defs/RuleNot" }, + { "$ref": "#/$defs/RuleAny" }, + { "$ref": "#/$defs/RuleAll" } + ] + }, + "RuleOffroadOnly": { + "type": "object", + "description": "Rule that passes only when the device is offroad.", + "required": ["type"], + "additionalProperties": false, + "properties": { + "type": { + "const": "offroad_only" + } + } + }, + "RuleNotEngaged": { + "type": "object", + "description": "Rule that passes when the vehicle is not engaged (matches Raylib `engaged = started AND (selfdriveState.enabled OR selfdriveStateSP.mads.enabled)`).", + "required": ["type"], + "additionalProperties": false, + "properties": { + "type": { + "const": "not_engaged" + } + } + }, + "RuleCapability": { + "type": "object", + "description": "Rule that checks a vehicle capability field against an expected value.", + "required": ["type", "field", "equals"], + "additionalProperties": false, + "properties": { + "type": { + "const": "capability" + }, + "field": { + "type": "string", + "description": "The capability field name to check." + }, + "equals": { + "description": "The expected value to match against." + } + } + }, + "RuleParam": { + "type": "object", + "description": "Rule that checks a param value against an expected value.", + "required": ["type", "key", "equals"], + "additionalProperties": false, + "properties": { + "type": { + "const": "param" + }, + "key": { + "type": "string", + "description": "The param key to read." + }, + "equals": { + "description": "The expected value to match against." + } + } + }, + "RuleParamCompare": { + "type": "object", + "description": "Rule that compares a numeric param value using a comparison operator.", + "required": ["type", "key", "op", "value"], + "additionalProperties": false, + "properties": { + "type": { + "const": "param_compare" + }, + "key": { + "type": "string", + "description": "The param key to read." + }, + "op": { + "type": "string", + "description": "Comparison operator.", + "enum": [">", "<", ">=", "<="] + }, + "value": { + "type": "number", + "description": "The numeric value to compare against." + } + } + }, + "RuleNot": { + "type": "object", + "description": "Rule that negates a single child condition.", + "required": ["type", "condition"], + "additionalProperties": false, + "properties": { + "type": { + "const": "not" + }, + "condition": { + "$ref": "#/$defs/Rule", + "description": "The rule to negate." + } + } + }, + "RuleAny": { + "type": "object", + "description": "Rule that passes if ANY of the child conditions pass (logical OR).", + "required": ["type", "conditions"], + "additionalProperties": false, + "properties": { + "type": { + "const": "any" + }, + "conditions": { + "type": "array", + "description": "Child rules; at least one must pass.", + "items": { + "$ref": "#/$defs/Rule" + }, + "minItems": 1 + } + } + }, + "RuleAll": { + "type": "object", + "description": "Rule that passes only if ALL child conditions pass (logical AND).", + "required": ["type", "conditions"], + "additionalProperties": false, + "properties": { + "type": { + "const": "all" + }, + "conditions": { + "type": "array", + "description": "Child rules; all must pass.", + "items": { + "$ref": "#/$defs/Rule" + }, + "minItems": 1 + } + } + } + } +} diff --git a/openpilot/sunnypilot/sunnylink/settings_ui_src/_macros.yaml b/openpilot/sunnypilot/sunnylink/settings_ui_src/_macros.yaml new file mode 100644 index 0000000000..a771720831 --- /dev/null +++ b/openpilot/sunnypilot/sunnylink/settings_ui_src/_macros.yaml @@ -0,0 +1,65 @@ +# Named rule fragments. Reference from items/sections via {$ref: "#/macros/"}. +# Macros may $ref other macros (max depth 3 — see compile_settings_ui.py). No template logic. +# +# Adding a macro: define here once, then reference everywhere. The compiler +# resolves $refs into the canonical settings_ui.json output the frontend reads. + +macros: + # Most-used: only writable when the device is offroad. + offroad: + - {type: offroad_only} + + # Writable while not engaged (started, but selfdrive/MADS not active). + not_engaged: + - {type: not_engaged} + + # sunnypilot longitudinal control is active. + longitudinal: + - {type: capability, field: has_longitudinal_control, equals: true} + + # Longitudinal + ICBM both available. + longitudinal_and_icbm: + - {type: capability, field: has_longitudinal_control, equals: true} + - {type: capability, field: has_icbm, equals: true} + + # Item only meaningful when "Show Advanced Controls" is enabled by the user. + advanced_only: + - {type: param, key: ShowAdvancedControls, equals: true} + + # Hide on MICI hardware (no analog HUD support yet). + hide_on_mici: + - type: not + condition: {type: capability, field: device_type, equals: mici} + + # Mirrors selfdrive/ui/sunnypilot/layouts/.../mads_settings.py:_mads_limited_settings() + # Rivian + Tesla-without-vehicle-bus get the limited MADS UI (3-toggle subset). + # On those platforms these toggles are disabled — full MADS settings are + # only writable on platforms NOT in the limited-set. + mads_full_platforms: + - type: not + condition: + type: any + conditions: + - {type: capability, field: brand, equals: rivian} + - type: all + conditions: + - {type: capability, field: brand, equals: tesla} + - type: not + condition: {type: capability, field: tesla_has_vehicle_bus, equals: true} + + # Inverse of mads_full_platforms: present only on the limited platforms. + # Useful for "show this only on rivian/tesla-no-bus" toggles. + mads_limited_platforms: + - type: any + conditions: + - {type: capability, field: brand, equals: rivian} + - type: all + conditions: + - {type: capability, field: brand, equals: tesla} + - type: not + condition: {type: capability, field: tesla_has_vehicle_bus, equals: true} + + # Hide on sunnypilot release branches (is_release is hardcoded False everywhere; is_sp_release is the active gate). + release_branches_hide: + - type: not + condition: {type: capability, field: is_sp_release, equals: true} diff --git a/openpilot/sunnypilot/sunnylink/settings_ui_src/_schemas/macros.schema.json b/openpilot/sunnypilot/sunnylink/settings_ui_src/_schemas/macros.schema.json new file mode 100644 index 0000000000..57629acecb --- /dev/null +++ b/openpilot/sunnypilot/sunnylink/settings_ui_src/_schemas/macros.schema.json @@ -0,0 +1,23 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://sunnypilot.com/schemas/sdui/macros.schema.json", + "title": "Settings UI macros (named rule fragments)", + "type": "object", + "additionalProperties": false, + "required": ["macros"], + "properties": { + "macros": { + "type": "object", + "description": "Named rule fragments. Each value is either a list of rules (typical) or a single rule object. Reference from items/layout via {$ref: '#/macros/'}.", + "patternProperties": { + "^[A-Za-z_][A-Za-z0-9_]*$": { + "oneOf": [ + {"type": "array", "items": {"$ref": "rule.schema.json"}}, + {"$ref": "rule.schema.json"} + ] + } + }, + "additionalProperties": false + } + } +} diff --git a/openpilot/sunnypilot/sunnylink/settings_ui_src/_schemas/page.schema.json b/openpilot/sunnypilot/sunnylink/settings_ui_src/_schemas/page.schema.json new file mode 100644 index 0000000000..0e312dc745 --- /dev/null +++ b/openpilot/sunnypilot/sunnylink/settings_ui_src/_schemas/page.schema.json @@ -0,0 +1,113 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://sunnypilot.com/schemas/sdui/page.schema.json", + "title": "Settings UI page (panel) YAML", + "description": "Validates pages/.yaml. Each page describes one settings panel (or the vehicle namespace via kind: vehicle).", + "type": "object", + "required": ["id"], + "additionalProperties": false, + "properties": { + "id": {"type": "string"}, + "label": {"type": "string"}, + "icon": {"type": "string"}, + "order": {"type": "integer"}, + "remote_configurable": {"type": "boolean"}, + "description": {"type": "string"}, + "kind": { + "type": "string", + "enum": ["panel", "vehicle"], + "description": "panel (default) or vehicle (compiles to settings_ui.json#vehicle_settings)." + }, + "sections": { + "type": "array", + "items": {"$ref": "#/$defs/Section"} + }, + "items": { + "type": "array", + "items": {"$ref": "#/$defs/Item"} + }, + "sub_panels": { + "type": "array", + "items": {"$ref": "#/$defs/SubPanel"} + } + }, + "$defs": { + "Section": { + "type": "object", + "required": ["id", "title"], + "additionalProperties": false, + "properties": { + "id": {"type": "string"}, + "title": {"type": "string"}, + "description": {"type": "string"}, + "order": {"type": "integer"}, + "attestation_required": {"type": "boolean"}, + "visibility": {"type": "array", "items": {"$ref": "rule.schema.json"}}, + "enablement": {"type": "array", "items": {"$ref": "rule.schema.json"}}, + "items": {"type": "array", "items": {"$ref": "#/$defs/Item"}}, + "sub_panels": {"type": "array", "items": {"$ref": "#/$defs/SubPanel"}} + } + }, + "SubPanel": { + "type": "object", + "required": ["id", "label"], + "additionalProperties": false, + "properties": { + "id": {"type": "string"}, + "label": {"type": "string"}, + "trigger_key": {"type": ["string", "null"]}, + "trigger_condition": {"$ref": "rule.schema.json"}, + "items": {"type": "array", "items": {"$ref": "#/$defs/Item"}} + } + }, + "Item": { + "type": "object", + "required": ["key", "widget"], + "additionalProperties": false, + "properties": { + "key": {"type": "string", "pattern": "^[A-Za-z][A-Za-z0-9_]*$"}, + "widget": {"type": "string", "enum": ["toggle", "option", "multiple_button", "button", "info"]}, + "title": {"type": "string"}, + "description": {"type": "string", "description": "Inline body text under the title. May be omitted when only details is used."}, + "details": {"type": "string", "description": "Extended help shown in a modal when the user taps the info (i) button. Independent of description; either, both, or neither may be present."}, + "title_param_suffix": {"type": "object"}, + "min": {"type": "number"}, + "max": {"type": "number"}, + "step": {"type": "number"}, + "unit": { + "oneOf": [ + {"type": "string"}, + { + "type": "object", + "additionalProperties": false, + "required": ["metric", "imperial"], + "properties": { + "metric": {"type": "string"}, + "imperial": {"type": "string"} + } + } + ] + }, + "needs_onroad_cycle": {"type": "boolean"}, + "requires_attestation": {"type": "boolean"}, + "blocked": {"type": "boolean"}, + "options": { + "type": "array", + "items": { + "type": "object", + "required": ["value", "label"], + "additionalProperties": false, + "properties": { + "value": {}, + "label": {"type": "string"}, + "enablement": {"type": "array", "items": {"$ref": "rule.schema.json"}} + } + } + }, + "visibility": {"type": "array", "items": {"$ref": "rule.schema.json"}}, + "enablement": {"type": "array", "items": {"$ref": "rule.schema.json"}}, + "sub_items": {"type": "array", "items": {"$ref": "#/$defs/Item"}} + } + } + } +} diff --git a/openpilot/sunnypilot/sunnylink/settings_ui_src/_schemas/rule.schema.json b/openpilot/sunnypilot/sunnylink/settings_ui_src/_schemas/rule.schema.json new file mode 100644 index 0000000000..92a7dd307c --- /dev/null +++ b/openpilot/sunnypilot/sunnylink/settings_ui_src/_schemas/rule.schema.json @@ -0,0 +1,101 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://sunnypilot.com/schemas/sdui/rule.schema.json", + "title": "Rule", + "description": "Visibility/enablement rule. Discriminated union on 'type'. Macro reference is also accepted via {$ref: '#/macros/'}.", + "oneOf": [ + {"$ref": "#/$defs/MacroRef"}, + {"$ref": "#/$defs/RuleOffroadOnly"}, + {"$ref": "#/$defs/RuleNotEngaged"}, + {"$ref": "#/$defs/RuleCapability"}, + {"$ref": "#/$defs/RuleParam"}, + {"$ref": "#/$defs/RuleParamCompare"}, + {"$ref": "#/$defs/RuleNot"}, + {"$ref": "#/$defs/RuleAny"}, + {"$ref": "#/$defs/RuleAll"} + ], + "$defs": { + "MacroRef": { + "type": "object", + "required": ["$ref"], + "additionalProperties": false, + "properties": { + "$ref": { + "type": "string", + "pattern": "^#/macros/[A-Za-z_][A-Za-z0-9_]*$", + "description": "Reference to a macro defined in _macros.yaml under #/macros/." + } + } + }, + "RuleOffroadOnly": { + "type": "object", + "required": ["type"], + "additionalProperties": false, + "properties": {"type": {"const": "offroad_only"}} + }, + "RuleNotEngaged": { + "type": "object", + "required": ["type"], + "additionalProperties": false, + "properties": {"type": {"const": "not_engaged"}} + }, + "RuleCapability": { + "type": "object", + "required": ["type", "field", "equals"], + "additionalProperties": false, + "properties": { + "type": {"const": "capability"}, + "field": {"type": "string"}, + "equals": {} + } + }, + "RuleParam": { + "type": "object", + "required": ["type", "key", "equals"], + "additionalProperties": false, + "properties": { + "type": {"const": "param"}, + "key": {"type": "string"}, + "equals": {} + } + }, + "RuleParamCompare": { + "type": "object", + "required": ["type", "key", "op", "value"], + "additionalProperties": false, + "properties": { + "type": {"const": "param_compare"}, + "key": {"type": "string"}, + "op": {"type": "string", "enum": [">", "<", ">=", "<="]}, + "value": {"type": "number"} + } + }, + "RuleNot": { + "type": "object", + "required": ["type", "condition"], + "additionalProperties": false, + "properties": { + "type": {"const": "not"}, + "condition": {"$ref": "#"} + } + }, + "RuleAny": { + "type": "object", + "required": ["type", "conditions"], + "additionalProperties": false, + "properties": { + "type": {"const": "any"}, + "conditions": {"type": "array", "items": {"$ref": "#"}, "minItems": 1} + } + }, + "RuleAll": { + "type": "object", + "required": ["type", "conditions"], + "additionalProperties": false, + "properties": { + "type": {"const": "all"}, + "conditions": {"type": "array", "items": {"$ref": "#"}, "minItems": 1} + } + } + } +} diff --git a/openpilot/sunnypilot/sunnylink/settings_ui_src/pages/cruise.yaml b/openpilot/sunnypilot/sunnylink/settings_ui_src/pages/cruise.yaml new file mode 100644 index 0000000000..3ef73e0fb0 --- /dev/null +++ b/openpilot/sunnypilot/sunnylink/settings_ui_src/pages/cruise.yaml @@ -0,0 +1,269 @@ +# Page: cruise +# Edit this file. Run compile_settings_ui.py to emit settings_ui.json. +id: cruise +label: Cruise +icon: cruise_control +order: 2 +remote_configurable: true +description: Longitudinal control, speed limits, and cruise behavior +sections: +- id: core_cruise_features + title: '' + description: '' + items: + - key: ExperimentalMode + widget: toggle + title: Experimental Mode + enablement: + - $ref: '#/macros/longitudinal' + - key: DynamicExperimentalControl + widget: toggle + title: Dynamic Experimental Control + description: Let the model decide when to use sunnypilot ACC or sunnypilot End to End Longitudinal. + visibility: + - $ref: '#/macros/longitudinal' + enablement: + - $ref: '#/macros/longitudinal' + - key: DisengageOnAccelerator + widget: toggle + title: Disengage Cruise on Accelerator Pedal + description: When enabled, pressing the accelerator pedal will disengage longitudinal control. + - key: LongitudinalPersonality + widget: multiple_button + title: Driving Personality + description: Standard is recommended. In aggressive mode, sunnypilot will follow lead cars closer and be more aggressive + with the gas and brake. In relaxed mode sunnypilot will stay further away from lead cars. On supported cars, you can + cycle through these personalities with your steering wheel distance button. + options: + - value: 0 + label: Aggressive + - value: 1 + label: Standard + - value: 2 + label: Relaxed + enablement: + - $ref: '#/macros/longitudinal' + - key: IntelligentCruiseButtonManagement + widget: toggle + title: Intelligent Cruise Button Management (ICBM) (Alpha) + visibility: + - type: capability + field: icbm_available + equals: true + enablement: + - $ref: '#/macros/offroad' + - type: not + condition: + type: capability + field: has_longitudinal_control + equals: true +- id: custom_acc_increments + title: Custom ACC Speed Intervals + description: '' + enablement: + - $ref: '#/macros/offroad' + - type: any + conditions: + - type: all + conditions: + - type: capability + field: has_longitudinal_control + equals: true + - type: not + condition: + type: capability + field: pcm_cruise + equals: true + - type: capability + field: has_icbm + equals: true + items: + - key: CustomAccIncrementsEnabled + widget: toggle + title: Enable Custom ACC Speed Intervals + enablement: + - $ref: '#/macros/offroad' + - type: any + conditions: + - type: all + conditions: + - type: capability + field: has_longitudinal_control + equals: true + - type: not + condition: + type: capability + field: pcm_cruise + equals: true + - type: capability + field: has_icbm + equals: true + sub_panels: + - id: custom_acc_intervals + label: Custom ACC Speed Intervals Settings + trigger_key: CustomAccIncrementsEnabled + trigger_condition: + type: param + key: CustomAccIncrementsEnabled + equals: true + items: + - key: CustomAccShortPressIncrement + widget: option + title: Short Press Increment + min: 1 + max: 10 + step: 1 + enablement: + - type: param + key: CustomAccIncrementsEnabled + equals: true + - key: CustomAccLongPressIncrement + widget: option + title: Long Press Increment + min: 1 + max: 10 + step: 1 + enablement: + - type: param + key: CustomAccIncrementsEnabled + equals: true +- id: speed_limits + title: Speed Limits + description: Speed limit detection and offset behavior + items: [] + sub_panels: + - id: speed_limit_settings + label: Speed Limit Settings + trigger_key: SpeedLimitMode + items: + - key: SpeedLimitMode + widget: multiple_button + title: Speed Limit Assist Mode + options: + - value: 0 + label: 'Off' + - value: 1 + label: Information + - value: 2 + label: Warning + - value: 3 + label: Assist + enablement: + - type: any + conditions: + - type: capability + field: has_longitudinal_control + equals: true + - type: capability + field: has_icbm + equals: true + - type: not + condition: + type: capability + field: brand + equals: rivian + - type: not + condition: + type: all + conditions: + - type: capability + field: brand + equals: tesla + - type: capability + field: is_sp_release + equals: true + - key: SpeedLimitPolicy + widget: multiple_button + title: Speed Limit Source + options: + - value: 0 + label: Car State Only + - value: 1 + label: Map Data Only + - value: 2 + label: Car State Priority + - value: 3 + label: Map Data Priority + - value: 4 + label: Combined + - key: SpeedLimitOffsetType + widget: multiple_button + title: Speed Limit Offset Type + options: + - value: 0 + label: 'Off' + - value: 1 + label: Fixed + - value: 2 + label: Percentage + - key: SpeedLimitValueOffset + widget: option + title: Speed Limit Offset Value + min: -30 + max: 30 + step: 1 + unit: + metric: km/h + imperial: mph + visibility: + - type: param_compare + key: SpeedLimitOffsetType + op: '>' + value: 0 +- id: smart_cruise + title: Smart Cruise Control + description: '' + enablement: + - type: any + conditions: + - type: capability + field: has_longitudinal_control + equals: true + - type: capability + field: has_icbm + equals: true + items: + - key: SmartCruiseControlVision + widget: toggle + title: Vision + description: Use vision path predictions to estimate the appropriate speed to drive through turns ahead. + visibility: + - type: any + conditions: + - type: capability + field: has_longitudinal_control + equals: true + - type: capability + field: has_icbm + equals: true + enablement: + - type: any + conditions: + - type: capability + field: has_longitudinal_control + equals: true + - type: capability + field: has_icbm + equals: true + - key: SmartCruiseControlMap + widget: toggle + title: Map + description: Use map data to estimate the appropriate speed to drive through turns ahead. + visibility: + - type: any + conditions: + - type: capability + field: has_longitudinal_control + equals: true + - type: capability + field: has_icbm + equals: true + enablement: + - type: any + conditions: + - type: capability + field: has_longitudinal_control + equals: true + - type: capability + field: has_icbm + equals: true diff --git a/openpilot/sunnypilot/sunnylink/settings_ui_src/pages/developer.yaml b/openpilot/sunnypilot/sunnylink/settings_ui_src/pages/developer.yaml new file mode 100644 index 0000000000..b42720b436 --- /dev/null +++ b/openpilot/sunnypilot/sunnylink/settings_ui_src/pages/developer.yaml @@ -0,0 +1,137 @@ +# Page: developer +# Edit this file. Run compile_settings_ui.py to emit settings_ui.json. +id: developer +label: Developer +icon: developer +order: 9 +remote_configurable: true +description: Debug tools, remote access, and advanced services +sections: +- id: connectivity + title: Connectivity + description: Remote access and debugging interfaces + items: + - key: AdbEnabled + widget: toggle + blocked: true + title: Enable ADB + description: ADB (Android Debug Bridge) allows connecting to your device over USB or over the network. See https://docs.comma.ai/how-to/connect-to-comma + for more info. + enablement: + - $ref: '#/macros/offroad' + - key: SshEnabled + widget: toggle + blocked: true + title: Enable SSH + - key: JoystickDebugMode + widget: toggle + title: Joystick Debug Mode + enablement: + - $ref: '#/macros/offroad' + - key: AlphaLongitudinalEnabled + widget: toggle + needs_onroad_cycle: true + title: sunnypilot Longitudinal Control (Alpha) + description: 'WARNING: sunnypilot longitudinal control is in alpha for this car and will disable Automatic Emergency Braking + (AEB). On this car, sunnypilot defaults to the car''s built-in ACC instead of sunnypilot''s longitudinal control. Enable + this to switch to sunnypilot longitudinal control. Enabling Experimental mode is recommended when enabling sunnypilot + longitudinal control alpha. Changing this setting will restart sunnypilot if the car is powered on.' + visibility: + - type: all + conditions: + - type: capability + field: alpha_long_available + equals: true + - type: not + condition: + type: capability + field: has_icbm + equals: true + enablement: + - $ref: '#/macros/not_engaged' + - key: ShowDebugInfo + widget: toggle + title: UI Debug Mode +- id: test_maneuvers + title: Test Maneuvers + description: 'DANGER: enabling these maneuvers replaces normal driving behavior with deterministic test sequences. Each + toggle requires explicit confirmation per write. Use only in a closed environment.' + visibility: + - type: any + conditions: + - type: capability + field: is_development + equals: true + - type: capability + field: is_sp_release + equals: true + enablement: + - type: any + conditions: + - type: capability + field: is_development + equals: true + - type: param + key: ShowAdvancedControls + equals: true + attestation_required: true + items: + - key: LateralManeuverMode + widget: toggle + title: '[TEST] Lateral Maneuver Mode' + description: Replaces normal lateral control with a deterministic test sequence. NOT for road use. + enablement: + - $ref: '#/macros/not_engaged' + - type: capability + field: torque_allowed + equals: true + - key: LongitudinalManeuverMode + widget: toggle + title: '[TEST] Longitudinal Maneuver Mode' + description: Replaces normal longitudinal control with a deterministic test sequence. NOT for road use. + enablement: + - $ref: '#/macros/not_engaged' + - $ref: '#/macros/longitudinal' +- id: advanced_services + title: Advanced Settings + description: '' + items: + - key: ShowAdvancedControls + widget: toggle + title: Show Advanced Controls + description: Toggle visibility of advanced sunnypilot controls. This only changes the visibility of the toggles; it does + not change the actual enabled/disabled state. + - key: EnableGithubRunner + widget: toggle + title: GitHub Runner Service + description: Enables or disables the GitHub runner service. + visibility: + - $ref: '#/macros/release_branches_hide' + enablement: + - $ref: '#/macros/advanced_only' + - key: EnableCopyparty + widget: toggle + title: copyparty Service + description: copyparty is a very capable file server, you can use it to download your routes, view your logs and even + make some edits on some files from your browser. Requires you to connect to your comma locally via its IP address. + enablement: + - $ref: '#/macros/advanced_only' + - key: QuickBootToggle + widget: toggle + title: Quickboot Mode + visibility: + - type: not + condition: + type: any + conditions: + - type: capability + field: is_sp_release + equals: true + - type: capability + field: is_development + equals: true + enablement: + - type: param + key: DisableUpdates + equals: true + - $ref: '#/macros/advanced_only' diff --git a/openpilot/sunnypilot/sunnylink/settings_ui_src/pages/device.yaml b/openpilot/sunnypilot/sunnylink/settings_ui_src/pages/device.yaml new file mode 100644 index 0000000000..bf5f7883ab --- /dev/null +++ b/openpilot/sunnypilot/sunnylink/settings_ui_src/pages/device.yaml @@ -0,0 +1,67 @@ +# Page: device +# Edit this file. Run compile_settings_ui.py to emit settings_ui.json. +id: device +label: Device +icon: device +order: 6 +remote_configurable: true +description: Device behavior, units, and recording settings +sections: +- id: general + title: General + description: Power, boot, and unit preferences + items: + - key: OffroadMode + widget: toggle + title: Force Offroad Mode + - key: DeviceBootMode + widget: option + title: Wake Up Behavior + description: 'Controls state of the device after boot/sleep. Default: Device will boot/wake-up normally and will be ready + to engage. Offroad: Device will be in Always Offroad mode after boot/wake-up.' + options: + - value: 0 + label: Standard + - value: 1 + label: Always Offroad + - key: QuietMode + widget: toggle + title: Quiet Mode + - key: OnroadUploads + widget: toggle + title: Onroad Uploads + - key: MaxTimeOffroad + widget: option + title: Max Time Offroad + description: Device will automatically shutdown after set time once the engine is turned off. 30h is the default. + options: + - value: 0 + label: Always On + - value: 5 + label: 5m + - value: 10 + label: 10m + - value: 15 + label: 15m + - value: 30 + label: 30m + - value: 60 + label: 1h + - value: 120 + label: 2h + - value: 180 + label: 3h + - value: 300 + label: 5h + - value: 600 + label: 10h + - value: 1440 + label: 24h + - value: 1800 + label: 30h (Default) +- id: language + title: Language + items: + - key: LanguageSetting + widget: info + title: Language diff --git a/openpilot/sunnypilot/sunnylink/settings_ui_src/pages/display.yaml b/openpilot/sunnypilot/sunnylink/settings_ui_src/pages/display.yaml new file mode 100644 index 0000000000..39a8cbaf80 --- /dev/null +++ b/openpilot/sunnypilot/sunnylink/settings_ui_src/pages/display.yaml @@ -0,0 +1,130 @@ +# Page: display +# Edit this file. Run compile_settings_ui.py to emit settings_ui.json. +id: display +label: Display +icon: display +order: 3 +remote_configurable: true +description: Screen brightness, timeout, and interactivity settings +sections: +- id: brightness_timeout + title: Brightness & Timeout + description: Screen dimming and sleep behavior while driving + items: + - key: OnroadScreenOffBrightness + widget: multiple_button + title: Onroad Brightness + options: + - value: 0 + label: Auto (Default) + - value: 1 + label: Auto (Dark) + - value: 2 + label: Screen Off + - value: 3 + label: 5 % + - value: 4 + label: 10 % + - value: 5 + label: 15 % + - value: 6 + label: 20 % + - value: 7 + label: 25 % + - value: 8 + label: 30 % + - value: 9 + label: 35 % + - value: 10 + label: 40 % + - value: 11 + label: 45 % + - value: 12 + label: 50 % + - value: 13 + label: 55 % + - value: 14 + label: 60 % + - value: 15 + label: 65 % + - value: 16 + label: 70 % + - value: 17 + label: 75 % + - value: 18 + label: 80 % + - value: 19 + label: 85 % + - value: 20 + label: 90 % + - value: 21 + label: 95 % + - value: 22 + label: 100 % + - key: OnroadScreenOffTimer + widget: multiple_button + title: Onroad Brightness Delay + options: + - value: 0 + label: Always On + - value: 3 + label: 3s + - value: 5 + label: 5s + - value: 10 + label: 10s + - value: 15 + label: 15s + - value: 30 + label: 30s + - value: 60 + label: 1m + - value: 180 + label: 3m + - value: 300 + label: 5m + - value: 600 + label: 10m + enablement: + - type: not + condition: + type: any + conditions: + - type: param + key: OnroadScreenOffBrightness + equals: 0 + - type: param + key: OnroadScreenOffBrightness + equals: 1 + - key: InteractivityTimeout + widget: multiple_button + title: Interactivity Timeout + description: Apply a custom timeout for settings UI. This is the time after which settings UI closes automatically if + user is not interacting with the screen. + options: + - value: 0 + label: Default + - value: 10 + label: 10 s + - value: 20 + label: 20 s + - value: 30 + label: 30 s + - value: 40 + label: 40 s + - value: 50 + label: 50 s + - value: 60 + label: 1 m + - value: 70 + label: 1 m + - value: 80 + label: 1 m + - value: 90 + label: 1 m + - value: 100 + label: 1 m + - value: 110 + label: 1 m + - value: 120 + label: 2 m diff --git a/openpilot/sunnypilot/sunnylink/settings_ui_src/pages/models.yaml b/openpilot/sunnypilot/sunnylink/settings_ui_src/pages/models.yaml new file mode 100644 index 0000000000..4ae1fca88b --- /dev/null +++ b/openpilot/sunnypilot/sunnylink/settings_ui_src/pages/models.yaml @@ -0,0 +1,89 @@ +# Page: models +# Edit this file. Run compile_settings_ui.py to emit settings_ui.json. +id: models +label: Models +icon: models +order: 10 +remote_configurable: false +description: Driving model behavior and camera calibration +sections: +- id: model_behavior + title: Model Behavior + description: Lane desire and lead-vehicle awareness tuning + items: + - key: LaneTurnDesire + widget: toggle + title: Use Lane Turn Desires + description: If you are driving at 20 mph (32 km/h) or below and have your blinker on, the car will plan a turn in that + direction at the nearest drivable path. This prevents situations (like at red lights) where the car might plan the wrong + turn direction. + - key: LaneTurnValue + widget: option + title: Adjust Lane Turn Speed + description: Set the maximum speed for lane turn desires. + min: 0 + max: 20 + step: 1 + unit: + metric: km/h + imperial: mph + enablement: + - type: param + key: LaneTurnDesire + equals: true + - $ref: '#/macros/advanced_only' + - key: LagdToggle + widget: toggle + title: Live Learning Steer Delay + description: Allow device to learn and adapt car's steering response time + - key: LagdToggleDelay + widget: option + title: Adjust Software Delay + description: Adjust the software delay when Live Learning Steer Delay is toggled off. The default software delay value + is 0.2 + min: 0.05 + max: 0.5 + step: 0.01 + enablement: + - type: not + condition: + type: param + key: LagdToggle + equals: true + - $ref: '#/macros/advanced_only' +- id: lateral_control + title: Lateral Control + description: Neural network lateral control for supported models + items: + - key: NeuralNetworkLateralControl + widget: toggle + title: Neural Network Lateral Control (NNLC) + description: Use a neural network for lateral control instead of the default torque controller. + visibility: + - type: not + condition: + type: capability + field: steer_control_type + equals: angle + enablement: + - $ref: '#/macros/offroad' + - type: capability + field: torque_allowed + equals: true + - type: param + key: EnforceTorqueControl + equals: false +- id: camera + title: Camera + description: Camera position and calibration + items: + - key: CameraOffset + widget: option + title: Adjust Camera Offset + description: Virtually shift camera's perspective to move model's center to Left(+ values) or Right (- values) + min: -0.35 + max: 0.35 + step: 0.01 + unit: meters + enablement: + - $ref: '#/macros/advanced_only' diff --git a/openpilot/sunnypilot/sunnylink/settings_ui_src/pages/software.yaml b/openpilot/sunnypilot/sunnylink/settings_ui_src/pages/software.yaml new file mode 100644 index 0000000000..4935d28e0c --- /dev/null +++ b/openpilot/sunnypilot/sunnylink/settings_ui_src/pages/software.yaml @@ -0,0 +1,20 @@ +# Page: software +# Edit this file. Run compile_settings_ui.py to emit settings_ui.json. +id: software +label: Software +icon: software +order: 7 +remote_configurable: true +description: Software update preferences +sections: +- id: updates + title: Updates + description: Control software updates + items: + - key: DisableUpdates + widget: toggle + title: Disable Updates + description: When enabled, software updates will be off. This requires a reboot to take effect. + enablement: + - $ref: '#/macros/offroad' + - $ref: '#/macros/advanced_only' diff --git a/openpilot/sunnypilot/sunnylink/settings_ui_src/pages/steering.yaml b/openpilot/sunnypilot/sunnylink/settings_ui_src/pages/steering.yaml new file mode 100644 index 0000000000..697c5f4f21 --- /dev/null +++ b/openpilot/sunnypilot/sunnylink/settings_ui_src/pages/steering.yaml @@ -0,0 +1,257 @@ +# Page: steering +# Edit this file. Run compile_settings_ui.py to emit settings_ui.json. +id: steering +label: Steering +icon: steering_wheel +order: 1 +remote_configurable: true +description: Lateral control, lane changes, and steering behavior +sections: +- id: mads + title: Modular Assistive Driving System (MADS) + description: '' + items: + - key: Mads + widget: toggle + title: Enable Modular Assistive Driving System (MADS) + description: Enable MADS. Disable toggle to revert back to stock sunnypilot engagement/disengagement. + enablement: + - $ref: '#/macros/offroad' + sub_panels: + - id: mads_settings + label: MADS Settings + trigger_key: Mads + trigger_condition: + type: param + key: Mads + equals: true + items: + - key: MadsMainCruiseAllowed + widget: toggle + title: Toggle with Main Cruise + description: 'Note: For vehicles without LFA/LKAS button, disabling this will prevent lateral control engagement.' + enablement: + - $ref: '#/macros/offroad' + - $ref: '#/macros/mads_full_platforms' + - key: MadsUnifiedEngagementMode + widget: toggle + title: Unified Engagement Mode (UEM) + description: 'Engage lateral and longitudinal control with cruise control engagement. Note: Once lateral control is + engaged via UEM, it will remain engaged until it is manually disabled via the MADS button or car shut off.' + enablement: + - $ref: '#/macros/offroad' + - $ref: '#/macros/mads_full_platforms' + - key: MadsSteeringMode + widget: multiple_button + title: Steering Mode on Brake Pedal + description: Choose how Automatic Lane Centering (ALC) behaves after the brake pedal is manually pressed in sunnypilot. + options: + - value: 0 + label: Remain Active + enablement: + - $ref: '#/macros/mads_full_platforms' + - value: 1 + label: Pause + enablement: + - $ref: '#/macros/mads_full_platforms' + - value: 2 + label: Disengage + enablement: + - $ref: '#/macros/offroad' +- id: blinker + title: Blinker Control + description: Lateral pause behavior during turn signals + items: + - key: BlinkerPauseLateralControl + widget: toggle + title: Pause Lateral Control with Blinker + description: Pause lateral control with blinker when traveling below the desired speed selected. + sub_items: + - key: BlinkerMinLateralControlSpeed + widget: option + title: Minimum Speed to Pause Lateral Control + min: 0 + max: 255 + step: 5 + unit: + metric: km/h + imperial: mph + enablement: + - type: param + key: BlinkerPauseLateralControl + equals: true + - key: BlinkerLateralReengageDelay + widget: option + title: Post-Blinker Delay + description: Delay before lateral control resumes after the turn signal ends. + min: 0 + max: 10 + step: 1 + unit: second + enablement: + - type: param + key: BlinkerPauseLateralControl + equals: true +- id: torque + title: Torque Control + description: Steering torque tuning and lateral control method + enablement: + - type: capability + field: torque_allowed + equals: true + items: + - key: EnforceTorqueControl + widget: toggle + title: Enforce Torque Lateral Control + description: Enable this to enforce sunnypilot to steer with Torque lateral control. + visibility: + - type: not + condition: + type: capability + field: steer_control_type + equals: angle + enablement: + - $ref: '#/macros/offroad' + - type: capability + field: torque_allowed + equals: true + - type: param + key: NeuralNetworkLateralControl + equals: false + sub_panels: + - id: torque_settings + label: Torque Settings + trigger_key: EnforceTorqueControl + trigger_condition: + type: param + key: EnforceTorqueControl + equals: true + items: + - key: LiveTorqueParamsToggle + widget: toggle + title: Self-Tune + description: Enables self-tune for Torque lateral control for platforms that do not use Torque lateral control by default. + enablement: + - $ref: '#/macros/offroad' + - key: LiveTorqueParamsRelaxedToggle + widget: toggle + title: Less Restrict Settings for Self-Tune (Beta) + description: Less strict settings when using Self-Tune. This allows torqued to be more forgiving when learning values. + enablement: + - $ref: '#/macros/offroad' + - type: param + key: LiveTorqueParamsToggle + equals: true + - key: CustomTorqueParams + widget: toggle + title: Enable Custom Tuning + description: Enables custom tuning for Torque lateral control. Modifying Lateral Acceleration Factor and Friction below + will override the offline values indicated in the YAML files within "opendbc/car/torque_data". The values will also + be used live when "Manual Real-Time Tuning" toggle is enabled. + enablement: + - $ref: '#/macros/offroad' + - key: TorqueParamsOverrideEnabled + widget: toggle + title: Manual Real-Time Tuning + description: Enforces the torque lateral controller to use the fixed values instead of the learned values from Self-Tune. + Enabling this toggle overrides Self-Tune values. + enablement: + - $ref: '#/macros/offroad' + - type: param + key: CustomTorqueParams + equals: true + - key: TorqueParamsOverrideLatAccelFactor + widget: option + title: Lateral Acceleration Factor + title_param_suffix: + param: TorqueParamsOverrideEnabled + values: + 'true': (Real-Time & Offline) + 'false': (Offline Only) + min: 0.1 + max: 5.0 + step: 0.1 + unit: m/s² + enablement: + - type: param + key: CustomTorqueParams + equals: true + - type: any + conditions: + - type: param + key: TorqueParamsOverrideEnabled + equals: true + - type: offroad_only + - key: TorqueParamsOverrideFriction + widget: option + title: Friction + title_param_suffix: + param: TorqueParamsOverrideEnabled + values: + 'true': (Real-Time & Offline) + 'false': (Offline Only) + min: 0.0 + max: 1.0 + step: 0.01 + enablement: + - type: param + key: CustomTorqueParams + equals: true + - type: any + conditions: + - type: param + key: TorqueParamsOverrideEnabled + equals: true + - type: offroad_only + - key: TorqueControlTune + widget: multiple_button + title: Torque Control Tune Version + description: Select the version of Torque Control Tune to use. + options: + - value: '' + label: Default + - value: 1.0 + label: v1.0 + - value: 0.0 + label: v0.0 + enablement: + - $ref: '#/macros/offroad' +- id: lane_change + title: Lane Change + description: Automatic lane change timing and behavior + items: + - key: AutoLaneChangeTimer + widget: option + title: Auto Lane Change by Blinker + description: |- + Set a timer to delay the auto lane change operation when the blinker is used. No nudge on the steering wheel is required to auto lane change if a timer is set. Default is Nudge. + details: |- + Please use caution when using this feature. Only use the blinker when traffic and road conditions permit. + options: + - value: -1 + label: 'Off' + - value: 0 + label: Nudge + - value: 1 + label: Nudgeless + - value: 2 + label: 0.5 second + - value: 3 + label: 1 second + - value: 4 + label: 2 seconds + - value: 5 + label: 3 seconds + - key: AutoLaneChangeBsmDelay + widget: toggle + title: 'Auto Lane Change: Delay with Blind Spot' + description: Toggle to enable a delay timer for lane changes when blind spot monitoring (BSM) detects a vehicle in your blind + spot. + enablement: + - type: capability + field: enable_bsm + equals: true + - type: param_compare + key: AutoLaneChangeTimer + op: '>' + value: 0 diff --git a/openpilot/sunnypilot/sunnylink/settings_ui_src/pages/toggles.yaml b/openpilot/sunnypilot/sunnylink/settings_ui_src/pages/toggles.yaml new file mode 100644 index 0000000000..1a4186cf30 --- /dev/null +++ b/openpilot/sunnypilot/sunnylink/settings_ui_src/pages/toggles.yaml @@ -0,0 +1,49 @@ +# Page: toggles +# Edit this file. Run compile_settings_ui.py to emit settings_ui.json. +id: toggles +label: Toggles +icon: toggles +order: 5 +remote_configurable: true +description: Core openpilot feature toggles +sections: +- id: core_toggles + title: '' + description: '' + items: + - key: OpenpilotEnabledToggle + widget: toggle + needs_onroad_cycle: true + title: Enable sunnypilot + description: Use the sunnypilot system for adaptive cruise control and lane keep driver assistance. Your attention is + required at all times to use this feature. + enablement: + - $ref: '#/macros/offroad' + - key: IsLdwEnabled + widget: toggle + title: Enable Lane Departure Warnings + description: Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn + signal activated while driving over 31 mph (50 km/h). + - key: AlwaysOnDM + widget: toggle + title: Always-On Driver Monitoring + description: Enable driver monitoring even when sunnypilot is not engaged. + - key: IsMetric + widget: toggle + title: Use Metric System + description: Display speed in km/h instead of mph. +- id: recording + title: Recording + description: Camera and audio recording during drives + items: + - key: RecordFront + widget: toggle + needs_onroad_cycle: true + title: Record and Upload Driver Camera + description: Upload data from the driver facing camera and help improve the driver monitoring algorithm. + - key: RecordAudio + widget: toggle + needs_onroad_cycle: true + title: Record and Upload Microphone Audio + description: Record and store microphone audio while driving. The audio will be included in the dashcam video in comma + connect. diff --git a/openpilot/sunnypilot/sunnylink/settings_ui_src/pages/vehicle.yaml b/openpilot/sunnypilot/sunnylink/settings_ui_src/pages/vehicle.yaml new file mode 100644 index 0000000000..2f6f20730e --- /dev/null +++ b/openpilot/sunnypilot/sunnylink/settings_ui_src/pages/vehicle.yaml @@ -0,0 +1,81 @@ +# Page: vehicle (per-brand settings) +# Compiles to settings_ui.json#vehicle_settings (brand = section id). +id: vehicle +label: Vehicle +icon: vehicle +order: 99 +kind: vehicle +sections: +- id: hyundai + title: Hyundai / Kia / Genesis Settings + description: '' + items: + - key: HyundaiLongitudinalTuning + widget: multiple_button + title: Custom Longitudinal Tuning + options: + - value: 0 + label: 'Off' + - value: 1 + label: Dynamic + - value: 2 + label: Predictive + visibility: + - type: capability + field: hyundai_alpha_long_available + equals: true + enablement: + - $ref: '#/macros/offroad' + - $ref: '#/macros/longitudinal' +- id: subaru + title: Subaru Settings + description: '' + items: + - key: SubaruStopAndGo + widget: toggle + title: Stop and Go (Beta) + enablement: + - $ref: '#/macros/offroad' + - type: capability + field: has_stop_and_go + equals: true + - key: SubaruStopAndGoManualParkingBrake + widget: toggle + title: Stop and Go for Manual Parking Brake (Beta) + enablement: + - $ref: '#/macros/offroad' + - type: capability + field: has_stop_and_go + equals: true +- id: tesla + title: Tesla Settings + description: '' + items: + - key: TeslaCoopSteering + widget: toggle + title: Cooperative Steering (Beta) + enablement: + - $ref: '#/macros/offroad' +- id: toyota + title: Toyota / Lexus Settings + description: '' + items: + - key: ToyotaEnforceStockLongitudinal + widget: toggle + needs_onroad_cycle: true + title: Enforce Factory Longitudinal Control + description: sunnypilot will not take over control of gas and brakes. Factory Toyota longitudinal control will be used. + enablement: + - $ref: '#/macros/not_engaged' + - key: ToyotaStopAndGoHack + widget: toggle + needs_onroad_cycle: true + title: Stop and Go Hack (Alpha) + description: sunnypilot will allow some Toyota/Lexus cars to auto resume during stop and go traffic. This feature is only + applicable to certain models that are able to use longitudinal control. This is an alpha feature. Use at your own risk. + enablement: + - $ref: '#/macros/not_engaged' + - $ref: '#/macros/longitudinal' + - type: param + key: ToyotaEnforceStockLongitudinal + equals: false diff --git a/openpilot/sunnypilot/sunnylink/settings_ui_src/pages/visuals.yaml b/openpilot/sunnypilot/sunnylink/settings_ui_src/pages/visuals.yaml new file mode 100644 index 0000000000..3170991157 --- /dev/null +++ b/openpilot/sunnypilot/sunnylink/settings_ui_src/pages/visuals.yaml @@ -0,0 +1,111 @@ +# Page: visuals +# Edit this file. Run compile_settings_ui.py to emit settings_ui.json. +id: visuals +label: Visuals +icon: visuals +order: 4 +remote_configurable: true +description: HUD overlays, alerts, and on-screen display elements +sections: +- id: hud_elements + title: HUD Elements + description: Overlays shown on the driving screen + items: + - key: BlindSpot + widget: toggle + title: Show Blind Spot Warnings + description: Enabling this will display warnings when a vehicle is detected in your blind spot as long as your car has + BSM supported. + - key: TorqueBar + widget: toggle + title: Steering Arc + description: Display steering arc on the driving screen when lateral control is enabled. + - key: ShowTurnSignals + widget: toggle + title: Display Turn Signals + description: When enabled, visual turn indicators are drawn on the HUD. + - key: RoadNameToggle + widget: toggle + title: Display Road Name + description: Displays the name of the road the car is traveling on. The OpenStreetMap database of the location must be + downloaded to fetch the road name. + visibility: + - $ref: '#/macros/hide_on_mici' + - key: StandstillTimer + widget: toggle + title: Standstill Timer + description: Show a timer on the HUD when the car is at a standstill. + visibility: + - $ref: '#/macros/hide_on_mici' + - key: RocketFuel + widget: toggle + title: Real-time Acceleration Bar + description: Show an indicator on the left side of the screen to display real-time vehicle acceleration and deceleration. + This displays what the car is currently doing, not what the planner is requesting. + visibility: + - $ref: '#/macros/hide_on_mici' + - key: ChevronInfo + widget: option + title: Display Metrics Below Chevron + options: + - value: 0 + label: 'Off' + - value: 1 + label: Distance + - value: 2 + label: Speed + - value: 3 + label: Time + - value: 4 + label: All + visibility: + - $ref: '#/macros/hide_on_mici' + enablement: + - $ref: '#/macros/longitudinal' +- id: developer_ui + title: Developer UI Info + description: Speedometer and debug display options + visibility: + - $ref: '#/macros/hide_on_mici' + items: + - key: DevUIInfo + widget: option + title: Developer UI + description: Display real-time parameters and metrics from various sources. + options: + - value: 0 + label: 'Off' + - value: 1 + label: Bottom + - value: 2 + label: Right + - value: 3 + label: Right & Bottom + - key: TrueVEgoUI + widget: toggle + title: 'Speedometer: Always Display True Speed' + description: For applicable vehicles, always display the true vehicle current speed from wheel speed sensors. + - key: HideVEgoUI + widget: toggle + title: 'Speedometer: Hide from Onroad Screen' + description: When enabled, the speedometer on the onroad screen is not displayed. +- id: alerts_extras + title: Alerts & Extras + description: Traffic light alerts and visual flair + items: + - key: GreenLightAlert + widget: toggle + title: Green Traffic Light Alert (Beta) + description: 'A chime and on-screen alert will play when the traffic light you are waiting for turns green and you have + no vehicle in front of you. On-screen visual alert is only available on comma 3X. Note: This chime is only designed + as a notification. It is the driver''s responsibility to observe their environment and make decisions accordingly.' + - key: LeadDepartAlert + widget: toggle + title: Lead Departure Alert (Beta) + description: 'A chime and on-screen alert will play when you are stopped, and the vehicle in front of you start moving. + On-screen visual alert is only available on comma 3X. Note: This chime is only designed as a notification. It is the + driver''s responsibility to observe their environment and make decisions accordingly.' + - key: RainbowMode + widget: toggle + title: Tesla Rainbow Mode + description: Display a rainbow effect on the path the model wants to take. It does not affect driving in any way. diff --git a/openpilot/sunnypilot/sunnylink/statsd.py b/openpilot/sunnypilot/sunnylink/statsd.py new file mode 100755 index 0000000000..7e8faf6327 --- /dev/null +++ b/openpilot/sunnypilot/sunnylink/statsd.py @@ -0,0 +1,278 @@ +#!/usr/bin/env python3 +import base64 +import json +import os +import threading +import traceback + +import zmq +import time +import uuid +from pathlib import Path +from collections import defaultdict +from datetime import datetime, UTC + +from openpilot.common.params import Params +from openpilot.cereal.messaging import SubMaster +from openpilot.common.hardware.hw import Paths +from openpilot.common.swaglog import cloudlog +from openpilot.common.hardware import HARDWARE +from openpilot.common.utils import atomic_write +from openpilot.common.version import get_build_metadata +from openpilot.system.loggerd.config import STATS_DIR_FILE_LIMIT, STATS_SOCKET, STATS_FLUSH_TIME_S +from openpilot.sunnypilot.system.statsd import METRIC_TYPE, StatLogSP +from openpilot.common.realtime import Ratekeeper + +STATSLOGSP = StatLogSP(intercept=False) + +def sp_stats(end_event): + """Collect sunnypilot-specific statistics and send as raw metrics.""" + rk = Ratekeeper(.1, print_delay_threshold=None) + statlogsp = STATSLOGSP + params = Params() + + def flatten_dict(d, parent_key='', sep='.'): + items = {} + if isinstance(d, dict): + for k, v in d.items(): + new_key = f"{parent_key}{sep}{k}" if parent_key else k + items.update(flatten_dict(v, new_key, sep=sep)) + elif isinstance(d, (list, tuple)): + for i, v in enumerate(d): + new_key = f"{parent_key}[{i}]" + items.update(flatten_dict(v, new_key, sep=sep)) + else: + items[parent_key] = d + return items + + # Collect sunnypilot parameters + stats_dict = {} + + param_keys = [ + 'SunnylinkEnabled', + 'AutoLaneChangeBsmDelay', + 'AutoLaneChangeTimer', + 'CarPlatformBundle', + 'CurrentRoute', + 'DevUIInfo', + 'EnableCopyparty', + 'IntelligentCruiseButtonManagement', + 'QuietMode', + 'RainbowMode', + 'ShowAdvancedControls', + 'Mads', + 'MadsMainCruiseAllowed', + 'MadsSteeringMode', + 'MadsUnifiedEngagementMode', + 'ModelManager_ActiveBundle', + 'ModelManager_Favs', + 'EnableSunnylinkUploader', + 'SunnylinkEnabled', + 'InstallDate', + 'UptimeOffroad', + 'UptimeOnroad', + ] + + while not end_event.is_set(): + try: + for key in param_keys: + + try: + value = params.get(key) + except Exception as e: + stats_dict[key] = e + continue + + if value is None: + continue + + if isinstance(value, (dict, list, tuple)): + stats_dict.update(flatten_dict(value, key)) + else: + stats_dict[key] = value + + if stats_dict: + statlogsp.raw('sunnypilot.device_params', stats_dict) + except Exception as e: + cloudlog.error(f"Exception {e}") + finally: + rk.keep_time() + + +def stats_main(end_event): + comma_dongle_id = Params().get("DongleId") + sunnylink_dongle_id = Params().get("SunnylinkDongleId") + + def get_influxdb_line(measurement: str, value: float | dict[str, float], timestamp: datetime, tags: dict) -> str: + res = f"{measurement}" + for k, v in tags.items(): + res += f",{k}={str(v)}" + res += " " + + if isinstance(value, float): + value = {'value': value} + + for k, v in value.items(): + res += f"{k}={str(v)}," + + res += f"sunnylink_dongle_id=\"{sunnylink_dongle_id}\",comma_dongle_id=\"{comma_dongle_id}\" {int(timestamp.timestamp() * 1e9)}\n" + return res + + def get_influxdb_line_raw(measurement: str, value: dict, timestamp: datetime, tags: dict) -> str: + res = f"{measurement}" + try: + custom_tags = "" + for k, v in tags.items(): + custom_tags += f",{k}={str(v)}" + res += custom_tags + + fields = "" + for k, v in value.items(): + # Skip complex types - only keep simple scalar values + if isinstance(v, (dict, list, bytes, bytearray)): + continue + + fields += f"{k}={json.dumps(v)}," + + res += f" {fields}" + except Exception as e: + cloudlog.error(f"Unable to get influxdb line for: {value}") + res += f",invalid=1 reason={e}," + + res += f"sunnylink_dongle_id=\"{sunnylink_dongle_id}\",comma_dongle_id=\"{comma_dongle_id}\" {int(timestamp.timestamp() * 1e9)}\n" + return res + + # open statistics socket + ctx = zmq.Context.instance() + sock = ctx.socket(zmq.PULL) + sock.bind(f"{STATS_SOCKET}_sp") + + STATS_DIR = Paths.stats_sp_root() + + # initialize stats directory + Path(STATS_DIR).mkdir(parents=True, exist_ok=True) + + build_metadata = get_build_metadata() + + # initialize tags + tags = { + 'started': False, + 'version': build_metadata.openpilot.version, + 'branch': build_metadata.channel, + 'dirty': build_metadata.openpilot.is_dirty, + 'origin': build_metadata.openpilot.git_normalized_origin, + 'deviceType': HARDWARE.get_device_type(), + } + + # subscribe to deviceState for started state + sm = SubMaster(['deviceState']) + + idx = 0 + boot_uid = str(uuid.uuid4())[:8] + last_flush_time = time.monotonic() + gauges = {} + samples: dict[str, list[float]] = defaultdict(list) + raws: dict = defaultdict() + try: + while not end_event.is_set(): + started_prev = sm['deviceState'].started + sm.update() + + # Update metrics + while True: + try: + metric = sock.recv_string(zmq.NOBLOCK) + try: + metric_type = metric.split('|')[1] + metric_name = metric.split(':')[0] + metric_value_raw = metric.split('|')[0].split(':')[1] + + if metric_type == METRIC_TYPE.GAUGE: + metric_value = float(metric_value_raw) + gauges[metric_name] = metric_value + elif metric_type == METRIC_TYPE.SAMPLE: + metric_value = float(metric_value_raw) + samples[metric_name].append(metric_value) + elif metric_type == METRIC_TYPE.RAW: + raws[metric_name] = metric_value_raw + else: + cloudlog.event("unknown metric type", metric_type=metric_type) + except Exception: + print(traceback.format_exc()) + cloudlog.event("malformed metric", metric=metric) + except zmq.error.Again: + break + + # flush when started state changes or after FLUSH_TIME_S + if (time.monotonic() > last_flush_time + STATS_FLUSH_TIME_S) or (sm['deviceState'].started != started_prev): + result = "" + current_time = datetime.now(UTC) + tags['started'] = sm['deviceState'].started + + for key, value in raws.items(): + decoded_value = json.loads(base64.b64decode(value).decode('utf-8')) + result += get_influxdb_line_raw(key, decoded_value, current_time, tags) + + for key, value in gauges.items(): + result += get_influxdb_line(f"gauge.{key}", value, current_time, tags) + + for key, values in samples.items(): + values.sort() + sample_count = len(values) + sample_sum = sum(values) + + stats = { + 'count': sample_count, + 'min': values[0], + 'max': values[-1], + 'mean': sample_sum / sample_count, + } + for percentile in [0.05, 0.5, 0.95]: + value = values[int(round(percentile * (sample_count - 1)))] + stats[f"p{int(percentile * 100)}"] = value + + result += get_influxdb_line(f"sample.{key}", stats, current_time, tags) + + # clear intermediate data + gauges.clear() + samples.clear() + last_flush_time = time.monotonic() + + # check that we aren't filling up the drive + if len(os.listdir(STATS_DIR)) < STATS_DIR_FILE_LIMIT: + if len(result) > 0: + stats_path = os.path.join(STATS_DIR, f"{boot_uid}_{idx}") + with atomic_write(stats_path) as f: + f.write(result) + idx += 1 + else: + cloudlog.error("stats dir full") + finally: + sock.close() + ctx.term() + + +def main(): + rk = Ratekeeper(1, print_delay_threshold=None) + end_event = threading.Event() + + threads = [ + threading.Thread(target=stats_main, args=(end_event,)), + threading.Thread(target=sp_stats, args=(end_event,)), + ] + + for t in threads: + t.start() + + try: + while all(t.is_alive() for t in threads): + rk.keep_time() + finally: + end_event.set() + + for t in threads: + t.join() + + +if __name__ == "__main__": + main() diff --git a/openpilot/sunnypilot/sunnylink/sunnylink_state.py b/openpilot/sunnypilot/sunnylink/sunnylink_state.py new file mode 100644 index 0000000000..7dc553951e --- /dev/null +++ b/openpilot/sunnypilot/sunnylink/sunnylink_state.py @@ -0,0 +1,235 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from enum import IntEnum +import threading +import requests +import time +import json +import pyray as rl + +from openpilot.cereal import messaging +from openpilot.common.params import Params +from openpilot.common.swaglog import cloudlog +from openpilot.sunnypilot.sunnylink.api import UNREGISTERED_SUNNYLINK_DONGLE_ID, SunnylinkApi +from openpilot.system.ui.sunnypilot.lib.styles import style + + +class RoleType(IntEnum): + READONLY = 0 + SPONSOR = 1 + ADMIN = 2 + + +class SponsorTier(IntEnum): + FREE = 0 + NOVICE = 1 + SUPPORTER = 2 + CONTRIBUTOR = 3 + BENEFACTOR = 4 + GUARDIAN = 5 + + +class User: + device_id: str + user_id: str + created_at: int + updated_at: int + token_hash: str + + def __init__(self, json_data): + self.device_id = json_data.get("device_id") + self.user_id = json_data.get("user_id") + self.created_at = json_data.get("created_at") + self.updated_at = json_data.get("updated_at") + self.token_hash = json_data.get("token_hash") + + +class Role: + role_type: str + role_tier: str + + def __init__(self, json_data): + self.role_type = json_data.get("role_type") + self.role_tier = json_data.get("role_tier") + + +def _parse_roles(roles: str) -> list[Role]: + lst_roles = [] + try: + roles_list = json.loads(roles) + for r in roles_list: + try: + role = Role(r) + lst_roles.append(role) + except Exception as e: + cloudlog.exception(f"Failed to parse role {r}: {e}") + return lst_roles + except Exception as e: + cloudlog.exception(f"Error parsing roles: {e}") + return [] + + +def _parse_users(users: str) -> list[User]: + lst_users = [] + try: + users_list = json.loads(users) + for u in users_list: + try: + user = User(u) + lst_users.append(user) + except Exception as e: + cloudlog.exception(f"Failed to parse user {u}: {e}") + return lst_users + except Exception as e: + cloudlog.exception(f"Error parsing users: {e}") + return [] + + +class SunnylinkState: + FETCH_INTERVAL = 5.0 # seconds between API calls + API_TIMEOUT = 10.0 # seconds for API requests + SLEEP_INTERVAL = 0.5 # seconds to sleep between checks in the worker thread + NOT_PAIRED_USERNAMES = ["unregisteredsponsor", "temporarysponsor"] + + def __init__(self): + self._params = Params() + self._lock = threading.Lock() + self._session = requests.Session() # reuse session to reduce SSL handshake overhead + self._running = False + self._thread = None + self._sm = messaging.SubMaster(['deviceState']) + + self._roles: list[Role] = [] + self._users: list[User] = [] + self.sponsor_tier: SponsorTier = SponsorTier.FREE + self.sunnylink_dongle_id = self._params.get("SunnylinkDongleId") + self._api = SunnylinkApi(self.sunnylink_dongle_id) + + self._panel_open = False + + self._load_initial_state() + + def _load_initial_state(self) -> None: + roles_cache = self._params.get("SunnylinkCache_Roles") + users_cache = self._params.get("SunnylinkCache_Users") + if roles_cache is not None: + self._roles = _parse_roles(roles_cache) + self.sponsor_tier = self._get_highest_tier() + if users_cache is not None: + self._users = _parse_users(users_cache) + + def _get_highest_tier(self) -> SponsorTier: + role_tier = SponsorTier.FREE + for role in self._roles: + try: + if RoleType[role.role_type.upper()] == RoleType.SPONSOR: + role_tier = max(role_tier, SponsorTier[role.role_tier.upper()]) + except Exception as e: + cloudlog.exception(f"Error parsing role {role}: {e} for dongle id {self.sunnylink_dongle_id}") + return role_tier + + def _fetch_roles(self) -> None: + if not self.sunnylink_dongle_id or self.sunnylink_dongle_id == UNREGISTERED_SUNNYLINK_DONGLE_ID: + return + + try: + token = self._api.get_token() + response = self._api.api_get(f"device/{self.sunnylink_dongle_id}/roles", method='GET', access_token=token, session=self._session) + if response.status_code == 200: + roles = response.text + self._params.put("SunnylinkCache_Roles", roles, block=True) + with self._lock: + self._roles = _parse_roles(roles) + sponsor_tier = self._get_highest_tier() + if sponsor_tier != self.sponsor_tier: + self.sponsor_tier = sponsor_tier + cloudlog.info(f"Sunnylink sponsor tier updated to {sponsor_tier.name}") + except Exception as e: + cloudlog.exception(f"Failed to fetch sunnylink roles: {e} for dongle id {self.sunnylink_dongle_id}") + + def _fetch_users(self) -> None: + if not self.sunnylink_dongle_id or self.sunnylink_dongle_id == UNREGISTERED_SUNNYLINK_DONGLE_ID: + return + + try: + token = self._api.get_token() + response = self._api.api_get(f"device/{self.sunnylink_dongle_id}/users", method='GET', access_token=token, session=self._session) + if response.status_code == 200: + users = response.text + self._params.put("SunnylinkCache_Users", users, block=True) + with self._lock: + self._users = _parse_users(users) + except Exception as e: + cloudlog.exception(f"Failed to fetch sunnylink users: {e} for dongle id {self.sunnylink_dongle_id}") + + def _worker_thread(self) -> None: + while self._running: + with self._lock: + panel_open = self._panel_open + + if panel_open: + self._sm.update() + if self.is_connected(): + self._fetch_roles() + self._fetch_users() + + for _ in range(int(self.FETCH_INTERVAL / self.SLEEP_INTERVAL)): + if not self._running: + break + time.sleep(self.SLEEP_INTERVAL) + + def start(self) -> None: + if self._thread and self._thread.is_alive(): + return + self._running = True + self._thread = threading.Thread(target=self._worker_thread, daemon=True) + self._thread.start() + + def stop(self) -> None: + self._running = False + if self._thread and self._thread.is_alive(): + self._thread.join(timeout=1.0) + + def get_sponsor_tier(self) -> SponsorTier: + with self._lock: + return self.sponsor_tier + + def is_sponsor(self) -> bool: + with self._lock: + is_sponsor = any(role.role_type.upper() == RoleType.SPONSOR.name and role.role_tier.upper() != SponsorTier.FREE.name + for role in self._roles) + return is_sponsor + + def is_paired(self) -> bool: + with self._lock: + is_paired = any(user.user_id not in self.NOT_PAIRED_USERNAMES for user in self._users) + return is_paired + + def is_connected(self) -> bool: + network_type = self._sm["deviceState"].networkType + return bool(network_type != 0) + + def get_sponsor_tier_color(self) -> rl.Color: + tier = self.get_sponsor_tier() + + if tier == SponsorTier.GUARDIAN: + return rl.Color(255, 215, 0, 255) + elif tier == SponsorTier.BENEFACTOR: + return rl.Color(60, 179, 113, 255) + elif tier == SponsorTier.CONTRIBUTOR: + return rl.Color(70, 130, 180, 255) + elif tier == SponsorTier.SUPPORTER: + return rl.Color(147, 112, 219, 255) + else: + return style.ITEM_TEXT_VALUE_COLOR + + def set_settings_open(self, _open: bool) -> None: + with self._lock: + self._panel_open = _open + + def __del__(self): + self.stop() diff --git a/openpilot/sunnypilot/sunnylink/tests/test_capabilities.py b/openpilot/sunnypilot/sunnylink/tests/test_capabilities.py new file mode 100644 index 0000000000..4af1462479 --- /dev/null +++ b/openpilot/sunnypilot/sunnylink/tests/test_capabilities.py @@ -0,0 +1,92 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. + +Sentinel tests for the capabilities payload contract. PROTOCOL_VERSION is the +wire-protocol version observable by the dashboard; bumping it is a breaking +change and must be intentional. KNOWN_PROTOCOL_VERSIONS pins the set we +explicitly support — when the constant is bumped, this list must be edited in +the same commit so the bump shows up in code review. +""" +from __future__ import annotations + +import pytest + +from openpilot.sunnypilot.sunnylink.capabilities import ( + CAPABILITY_DEFAULTS, + CAPABILITY_FIELDS, + CAPABILITY_LABELS, + PROTOCOL_VERSION, + generate_capabilities, +) + + +KNOWN_PROTOCOL_VERSIONS = (1,) +LATEST_KNOWN = max(KNOWN_PROTOCOL_VERSIONS) + + +@pytest.fixture(scope="module") +def caps(): + return generate_capabilities() + + +class TestProtocolVersion: + def test_protocol_version_in_capability_fields(self): + assert "protocol_version" in CAPABILITY_FIELDS + + def test_protocol_version_has_label(self): + assert "protocol_version" in CAPABILITY_LABELS + + def test_protocol_version_default_is_set(self): + assert CAPABILITY_DEFAULTS.get("protocol_version") == PROTOCOL_VERSION + + def test_protocol_version_emitted(self, caps): + assert "protocol_version" in caps + assert isinstance(caps["protocol_version"], int) + assert caps["protocol_version"] >= 1 + + def test_protocol_version_matches_constant(self, caps): + assert caps["protocol_version"] == PROTOCOL_VERSION + + def test_protocol_version_is_known(self): + """Sentinel against accidental bumps. Edit KNOWN_PROTOCOL_VERSIONS if intentional.""" + assert PROTOCOL_VERSION in KNOWN_PROTOCOL_VERSIONS, ( + f"PROTOCOL_VERSION={PROTOCOL_VERSION} is not in KNOWN_PROTOCOL_VERSIONS={KNOWN_PROTOCOL_VERSIONS}. " + + "If this bump is intentional, add it to KNOWN_PROTOCOL_VERSIONS." + ) + + def test_protocol_version_matches_latest_known(self): + assert PROTOCOL_VERSION == LATEST_KNOWN, ( + "Test invariant: PROTOCOL_VERSION must equal max(KNOWN_PROTOCOL_VERSIONS)." + ) + + +class TestOpaquePerBrandFlags: + def test_subaru_has_sng_field_present(self): + assert "subaru_has_sng" in CAPABILITY_FIELDS + + def test_hyundai_alpha_long_available_field_present(self): + assert "hyundai_alpha_long_available" in CAPABILITY_FIELDS + + def test_subaru_has_sng_default_false(self, caps): + assert caps["subaru_has_sng"] is False + + def test_hyundai_alpha_long_available_default_false(self, caps): + assert caps["hyundai_alpha_long_available"] is False + + +class TestCapabilitiesShape: + def test_all_fields_present(self, caps): + for field in CAPABILITY_FIELDS: + assert field in caps, f"capabilities missing {field}" + + def test_all_fields_have_labels(self): + for field in CAPABILITY_FIELDS: + assert field in CAPABILITY_LABELS, f"CAPABILITY_LABELS missing {field}" + + def test_string_defaults_are_strings(self, caps): + assert isinstance(caps["brand"], str) + assert isinstance(caps["steer_control_type"], str) + assert isinstance(caps["device_type"], str) diff --git a/openpilot/sunnypilot/sunnylink/tests/test_compile_settings_ui.py b/openpilot/sunnypilot/sunnylink/tests/test_compile_settings_ui.py new file mode 100644 index 0000000000..2fcd889ec3 --- /dev/null +++ b/openpilot/sunnypilot/sunnylink/tests/test_compile_settings_ui.py @@ -0,0 +1,194 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. + +Tests for the settings_ui_src/ -> settings_ui.json compiler. Covers: + - Roundtrip: compiled output matches the checked-in settings_ui.json + - $ref macro resolution semantics (list-splice, scalar-substitute, depth, cycles) + - Per-page tree integrity (every page has id; vehicle page emits to vehicle_settings) + +Does not cover device-side generator (test_settings_schema.py) or per-bug +regression (test_settings_changes.py); those continue to validate the +compiled output once the compiler has produced it. +""" +from __future__ import annotations + +import difflib +import json +import os + +import pytest +import yaml + +from openpilot.sunnypilot.sunnylink.tools.compile_settings_ui import ( + CompileError, + DEFAULT_OUT, + DEFAULT_SRC, + _resolve_refs, + compile_schema, +) + + +@pytest.fixture(scope="module") +def compiled() -> dict: + return compile_schema(DEFAULT_SRC) + + +@pytest.fixture(scope="module") +def committed() -> dict: + with open(DEFAULT_OUT) as f: + return json.load(f) + + +class TestRoundtrip: + def test_compiled_matches_committed(self, compiled, committed): + """Compiled output must match the checked-in JSON.""" + if compiled == committed: + return + diff = "\n".join(difflib.unified_diff( + json.dumps(committed, indent=2).splitlines(), + json.dumps(compiled, indent=2).splitlines(), + fromfile="settings_ui.json (committed)", + tofile="settings_ui.json (freshly compiled)", + lineterm="", + )) + pytest.fail(f"settings_ui.json schema mismatch — run compile_settings_ui.py\n\n{diff}") + + def test_committed_file_is_canonical(self): + """Compiled output must byte-match the checked-in file (including trailing newline). + Drift means someone edited settings_ui.json by hand instead of editing settings_ui_src/.""" + schema = compile_schema(DEFAULT_SRC) + rendered = json.dumps(schema, indent=2) + "\n" + with open(DEFAULT_OUT) as f: + current = f.read() + if current == rendered: + return + diff = "\n".join(difflib.unified_diff( + current.splitlines(), + rendered.splitlines(), + fromfile="settings_ui.json (on disk)", + tofile="settings_ui.json (freshly compiled)", + lineterm="", + )) + pytest.fail(f"settings_ui.json out of sync — run compile_settings_ui.py\n\n{diff}") + + +class TestRefResolution: + def test_list_context_splices(self): + macros = {"a": [{"type": "offroad_only"}], "b": [{"type": "not_engaged"}]} + out = _resolve_refs([{"$ref": "#/macros/a"}, {"$ref": "#/macros/b"}], macros) + assert out == [{"type": "offroad_only"}, {"type": "not_engaged"}] + + def test_scalar_context_substitutes(self): + macros = {"x": {"type": "capability", "field": "brand", "equals": "tesla"}} + out = _resolve_refs({"condition": {"$ref": "#/macros/x"}}, macros) + assert out == {"condition": {"type": "capability", "field": "brand", "equals": "tesla"}} + + def test_chained_ref_resolves(self): + macros = { + "leaf": [{"type": "offroad_only"}], + "middle": [{"$ref": "#/macros/leaf"}], + } + out = _resolve_refs([{"$ref": "#/macros/middle"}], macros) + assert out == [{"type": "offroad_only"}] + + def test_unknown_macro_raises(self): + with pytest.raises(CompileError, match="unknown macro"): + _resolve_refs([{"$ref": "#/macros/missing"}], {}) + + def test_cycle_raises(self): + macros = {"a": [{"$ref": "#/macros/b"}], "b": [{"$ref": "#/macros/a"}]} + with pytest.raises(CompileError, match="cycle"): + _resolve_refs([{"$ref": "#/macros/a"}], macros) + + def test_depth_limit(self): + # Depth 4 chain should fail (limit is 3). + macros = { + "l1": [{"$ref": "#/macros/l2"}], + "l2": [{"$ref": "#/macros/l3"}], + "l3": [{"$ref": "#/macros/l4"}], + "l4": [{"type": "offroad_only"}], + } + with pytest.raises(CompileError, match="depth"): + _resolve_refs([{"$ref": "#/macros/l1"}], macros) + + def test_invalid_ref_scheme(self): + with pytest.raises(CompileError, match="unsupported"): + _resolve_refs([{"$ref": "https://example.com/x"}], {}) + + def test_scalar_macro_in_list_context_raises(self): + macros = {"x": {"type": "offroad_only"}} # macro is a single rule (dict), not a list + with pytest.raises(CompileError, match="must resolve to a list"): + _resolve_refs([{"$ref": "#/macros/x"}], macros) + + +class TestCompiledShape: + def test_panels_present(self, compiled): + assert isinstance(compiled["panels"], list) + assert len(compiled["panels"]) == 9 + panel_ids = {p["id"] for p in compiled["panels"]} + assert {"steering", "cruise", "display", "visuals", "toggles", + "device", "software", "developer", "models"} <= panel_ids + + def test_vehicle_settings_consistent_shape(self, compiled): + """Each brand in vehicle_settings must have {title, description, items}.""" + for brand, data in compiled["vehicle_settings"].items(): + assert isinstance(data, dict), f"{brand}: expected object, got {type(data).__name__}" + assert "title" in data, f"{brand}: missing title" + assert "description" in data, f"{brand}: missing description" + assert "items" in data, f"{brand}: missing items" + + def test_no_dangling_refs_after_compile(self, compiled): + """All $ref objects must be resolved during compilation.""" + def walk(node): + if isinstance(node, dict): + if "$ref" in node: + pytest.fail(f"unresolved $ref: {node}") + for v in node.values(): + walk(v) + elif isinstance(node, list): + for x in node: + walk(x) + walk(compiled) + + +class TestSourceTreeIntegrity: + def test_macros_yaml_well_formed(self): + with open(os.path.join(DEFAULT_SRC, "_macros.yaml")) as f: + doc = yaml.safe_load(f) + assert "macros" in doc + for name, body in doc["macros"].items(): + assert name.replace("_", "").isalnum(), f"macro name '{name}' must be alphanumeric_" + assert body, f"macro '{name}' empty" + + def test_pages_dir_well_formed(self): + pages_dir = os.path.join(DEFAULT_SRC, "pages") + assert os.path.isdir(pages_dir), "pages/ directory missing" + page_files = sorted(fn for fn in os.listdir(pages_dir) if fn.endswith(".yaml")) + # 9 panels + 1 vehicle = 10 + assert len(page_files) == 10, f"expected 10 pages, found {len(page_files)}: {page_files}" + + def test_every_page_has_id(self): + pages_dir = os.path.join(DEFAULT_SRC, "pages") + for fn in sorted(os.listdir(pages_dir)): + if not fn.endswith(".yaml"): + continue + path = os.path.join(pages_dir, fn) + with open(path) as f: + doc = yaml.safe_load(f) + assert isinstance(doc, dict), f"{path}: top-level must be a mapping" + assert "id" in doc, f"{path}: page missing 'id'" + # File basename should match page id (modulo .yaml extension). + expected_id = os.path.splitext(fn)[0] + assert doc["id"] == expected_id, ( + f"{path}: page id '{doc['id']}' must match filename '{expected_id}'" + ) + + def test_vehicle_page_kind(self): + """vehicle.yaml must declare kind: vehicle so it routes to vehicle_settings.""" + path = os.path.join(DEFAULT_SRC, "pages", "vehicle.yaml") + with open(path) as f: + doc = yaml.safe_load(f) + assert doc.get("kind") == "vehicle", "vehicle.yaml must declare kind: vehicle" diff --git a/openpilot/sunnypilot/sunnylink/tests/test_settings_changes.py b/openpilot/sunnypilot/sunnylink/tests/test_settings_changes.py new file mode 100644 index 0000000000..07b05d4ac4 --- /dev/null +++ b/openpilot/sunnypilot/sunnylink/tests/test_settings_changes.py @@ -0,0 +1,219 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. + +Per-bug regression tests for the Raylib-vs-schema parity audit. Each test +isolates one of the gating bugs that the design-overhaul branch fixes so a +future regression is loud and obvious. These tests are intentionally narrow +and additive — they do not replace the broader test_settings_schema.py. +""" +from __future__ import annotations + +import json +import os +from typing import Any + +import pytest + +from openpilot.sunnypilot.sunnylink.tools.generate_settings_schema import ( + DEFINITION_PATH, + TORQUE_VERSIONS_PATH, + _build_torque_options, + _load_torque_versions, + generate_schema, +) + + +SCHEMA_VALIDATOR_PATH = os.path.join(os.path.dirname(DEFINITION_PATH), "settings_ui.schema.json") + + +def _walk_items(schema: dict[str, Any]): + """Yield every item dict from the schema.""" + def _yield(item: dict[str, Any]): + yield item + for sub in item.get("sub_items", []): + yield from _yield(sub) + + for panel in schema.get("panels", []): + for section in panel.get("sections", []): + for item in section.get("items", []): + yield from _yield(item) + for sp in section.get("sub_panels", []): + for item in sp.get("items", []): + yield from _yield(item) + for item in panel.get("items", []): + yield from _yield(item) + for sp in panel.get("sub_panels", []): + for item in sp.get("items", []): + yield from _yield(item) + for brand in schema.get("vehicle_settings", {}).values(): + items = brand.get("items", []) if isinstance(brand, dict) else brand + for item in items: + yield from _yield(item) + + +def _find_item(schema: dict[str, Any], key: str) -> dict[str, Any] | None: + for item in _walk_items(schema): + if item.get("key") == key: + return item + return None + + +def _find_section(schema: dict[str, Any], panel_id: str, section_id: str) -> dict[str, Any] | None: + for panel in schema.get("panels", []): + if panel.get("id") != panel_id: + continue + for section in panel.get("sections", []): + if section.get("id") == section_id: + return section + return None + + +def _flatten_rule_types(rules: list[dict[str, Any]] | None) -> set[str]: + out: set[str] = set() + + def _walk(rule: dict[str, Any]) -> None: + out.add(rule.get("type", "")) + if rule.get("type") == "not" and "condition" in rule: + _walk(rule["condition"]) + elif rule.get("type") in ("any", "all"): + for c in rule.get("conditions", []): + _walk(c) + + for rule in rules or []: + _walk(rule) + return out + + +def _references_capability_field(rules: list[dict[str, Any]] | None, field: str) -> bool: + found = False + + def _walk(rule: dict[str, Any]) -> None: + nonlocal found + if rule.get("type") == "capability" and rule.get("field") == field: + found = True + elif rule.get("type") == "not" and "condition" in rule: + _walk(rule["condition"]) + elif rule.get("type") in ("any", "all"): + for c in rule.get("conditions", []): + _walk(c) + + for rule in rules or []: + _walk(rule) + return found + + +@pytest.fixture(scope="module") +def schema(): + return generate_schema() + + +class TestMadsBrandGates: + def test_mads_main_cruise_has_brand_gate(self, schema): + """MadsMainCruiseAllowed must gate on brand and tesla_has_vehicle_bus.""" + item = _find_item(schema, "MadsMainCruiseAllowed") + assert item is not None + assert _references_capability_field(item.get("enablement"), "brand") + assert _references_capability_field(item.get("enablement"), "tesla_has_vehicle_bus") + + def test_mads_unified_engagement_has_brand_gate(self, schema): + """MadsUnifiedEngagementMode must mirror MadsMainCruiseAllowed brand-gate.""" + item = _find_item(schema, "MadsUnifiedEngagementMode") + assert item is not None + assert _references_capability_field(item.get("enablement"), "brand") + assert _references_capability_field(item.get("enablement"), "tesla_has_vehicle_bus") + + +class TestTestManeuversSection: + def test_lateral_maneuver_mode_in_test_maneuvers(self, schema): + section = _find_section(schema, "developer", "test_maneuvers") + assert section is not None, "developer.test_maneuvers section missing" + keys = {item["key"] for item in section.get("items", [])} + assert "LateralManeuverMode" in keys + assert "LongitudinalManeuverMode" in keys + + def test_test_maneuvers_section_requires_attestation(self, schema): + section = _find_section(schema, "developer", "test_maneuvers") + assert section is not None + assert section.get("attestation_required") is True + + def test_test_maneuvers_section_visibility_gate(self, schema): + section = _find_section(schema, "developer", "test_maneuvers") + assert section is not None + visibility = section.get("visibility") + assert visibility, "test_maneuvers must have visibility gate" + vis_refs = json.dumps(visibility) + assert "is_development" in vis_refs + assert "is_sp_release" in vis_refs + enablement = section.get("enablement") or [] + enable_refs = json.dumps(enablement) + assert "ShowAdvancedControls" in enable_refs, \ + "test_maneuvers must gate ShowAdvancedControls via enablement" + + +class TestValidator: + def test_validator_accepts_real_json(self): + """settings_ui.json validates against settings_ui.schema.json.""" + jsonschema = pytest.importorskip("jsonschema") + with open(DEFINITION_PATH) as f: + data = json.load(f) + with open(SCHEMA_VALIDATOR_PATH) as f: + validator = json.load(f) + jsonschema.validate(instance=data, schema=validator) + + +class TestTorqueOptionGeneration: + def test_torque_versions_match_generated_options(self, schema): + versions = _load_torque_versions() + assert versions, "latcontrol_torque_versions.json must have at least one version" + expected = _build_torque_options(versions) + item = _find_item(schema, "TorqueControlTune") + assert item is not None, "TorqueControlTune item must be present" + assert item.get("options") == expected + + def test_torque_versions_path_resolves(self): + assert os.path.exists(TORQUE_VERSIONS_PATH), ( + f"latcontrol_torque_versions.json not found at {TORQUE_VERSIONS_PATH}" + ) + + +class TestReleaseBranchGates: + @pytest.mark.parametrize("key", [ + "EnableGithubRunner", + "QuickBootToggle", + ]) + def test_sp_dev_items_gate_on_is_sp_release(self, schema, key): + """sunnypilot dev items must hide on sunnypilot release branches (is_sp_release gate).""" + item = _find_item(schema, key) + assert item is not None, f"{key} not found in schema" + rules = (item.get("visibility") or []) + (item.get("enablement") or []) + assert _references_capability_field(rules, "is_sp_release"), f"{key} missing is_sp_release gate" + + +class TestSpuriousOffroadGatesDropped: + def test_disengage_on_accelerator_has_no_offroad_only(self, schema): + item = _find_item(schema, "DisengageOnAccelerator") + assert item is not None + assert "offroad_only" not in _flatten_rule_types(item.get("enablement")) + + def test_dynamic_experimental_has_no_offroad_only(self, schema): + item = _find_item(schema, "DynamicExperimentalControl") + assert item is not None + assert "offroad_only" not in _flatten_rule_types(item.get("enablement")) + + +class TestNotEngagedReplacement: + @pytest.mark.parametrize("key", [ + "AlphaLongitudinalEnabled", + "ToyotaEnforceStockLongitudinal", + "ToyotaStopAndGoHack", + ]) + def test_offroad_only_replaced_with_not_engaged(self, schema, key): + """These items should use not_engaged, not offroad_only.""" + item = _find_item(schema, key) + assert item is not None, f"{key} not found" + rule_types = _flatten_rule_types(item.get("enablement")) + assert "offroad_only" not in rule_types, f"{key} still uses offroad_only" + assert "not_engaged" in rule_types, f"{key} missing not_engaged" diff --git a/openpilot/sunnypilot/sunnylink/tests/test_settings_schema.py b/openpilot/sunnypilot/sunnylink/tests/test_settings_schema.py new file mode 100644 index 0000000000..61cc0131cf --- /dev/null +++ b/openpilot/sunnypilot/sunnylink/tests/test_settings_schema.py @@ -0,0 +1,353 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import json +import pytest + +from openpilot.common.params import Params +from openpilot.sunnypilot.sunnylink.tools.generate_settings_schema import ( + SCHEMA_VERSION, + generate_schema, + generate_schema_json, + collect_all_keys, + collect_capability_refs, +) +from openpilot.sunnypilot.sunnylink.capabilities import CAPABILITY_FIELDS + + +VALID_WIDGET_TYPES = {"toggle", "option", "multiple_button", "button", "info"} +VALID_RULE_TYPES = {"offroad_only", "not_engaged", "capability", "param", "param_compare", "not", "any", "all"} +VALID_COMPARE_OPS = {">", "<", ">=", "<="} +MAX_ALLOWED_MISSING_TITLES = 0 # All items must have titles (metadata is inline in settings_ui.json) + + +def _iter_panel_items(panel: dict): + """Yield top-level items from a panel (non-recursive).""" + for item in panel.get("items", []): + yield item + for sp in panel.get("sub_panels", []): + for item in sp.get("items", []): + yield item + for section in panel.get("sections", []): + for item in section.get("items", []): + yield item + for sp in section.get("sub_panels", []): + for item in sp.get("items", []): + yield item + + +def _iter_all_sub_panels(panel: dict): + """Yield all sub_panels from a panel and its sections.""" + yield from panel.get("sub_panels", []) + for section in panel.get("sections", []): + yield from section.get("sub_panels", []) + + +def _brand_items(brand_data) -> list[dict]: + """Extract items from vehicle_settings[brand] (handles dict or list).""" + if isinstance(brand_data, dict): + return brand_data.get("items", []) + if isinstance(brand_data, list): + return brand_data + return [] + + +@pytest.fixture(scope="module") +def schema(): + return generate_schema() + + +@pytest.fixture(scope="module") +def all_param_keys(): + """All keys registered in the device param store.""" + return {k.decode("utf-8") for k in Params().all_keys()} + + +class TestSchemaStructure: + def test_schema_is_valid_json(self): + """Schema serializes to valid JSON.""" + raw = generate_schema_json() + parsed = json.loads(raw) + assert isinstance(parsed, dict) + + def test_has_required_top_level_fields(self, schema): + assert "schema_version" in schema + assert schema["schema_version"] == SCHEMA_VERSION + assert "generated_at" in schema + assert "panels" in schema + assert "vehicle_settings" in schema + assert "capability_fields" in schema + + def test_panels_are_list(self, schema): + assert isinstance(schema["panels"], list) + assert len(schema["panels"]) > 0 + + def test_all_panels_have_required_fields(self, schema): + for panel in schema["panels"]: + assert "id" in panel, f"Panel missing 'id': {panel}" + assert "label" in panel, f"Panel {panel.get('id')} missing 'label'" + assert "order" in panel, f"Panel {panel.get('id')} missing 'order'" + has_sections = "sections" in panel + has_items = "items" in panel + assert has_sections or has_items, \ + f"Panel {panel['id']} must have 'sections' or 'items'" + if has_sections: + assert isinstance(panel["sections"], list) + for sec in panel["sections"]: + assert "id" in sec, f"Section in panel {panel['id']} missing 'id'" + assert "items" in sec, f"Section {panel['id']}.{sec.get('id')} missing 'items'" + assert isinstance(sec["items"], list) + if has_items: + assert isinstance(panel["items"], list) + + def test_all_items_have_key_and_widget(self, schema): + for panel in schema["panels"]: + for item in _iter_panel_items(panel): + assert "key" in item, f"Item in panel {panel['id']} missing 'key'" + assert "widget" in item, f"Item {item.get('key')} missing 'widget'" + assert item["widget"] in VALID_WIDGET_TYPES, \ + f"Item {item['key']} has invalid widget type: {item['widget']}" + + def test_sub_panel_items_have_key_and_widget(self, schema): + for panel in schema["panels"]: + for sp in _iter_all_sub_panels(panel): + assert "id" in sp + assert "items" in sp + for item in sp["items"]: + assert "key" in item + assert "widget" in item + assert item["widget"] in VALID_WIDGET_TYPES + + def test_vehicle_settings_structure(self, schema): + vs = schema["vehicle_settings"] + assert isinstance(vs, dict) + for brand, data in vs.items(): + assert isinstance(brand, str) + assert isinstance(data, dict), \ + f"vehicle_settings[{brand}] must be a dict {{title, items, ...}}" + assert "items" in data, f"vehicle_settings[{brand}] missing 'items'" + assert isinstance(data["items"], list) + for item in data["items"]: + assert "key" in item, f"Vehicle item for {brand} missing 'key'" + assert "widget" in item, f"Vehicle item {item.get('key')} missing 'widget'" + + def test_no_duplicate_keys_across_panels(self, schema): + """Param keys should appear in at most one panel.""" + seen: dict[str, str] = {} # key -> panel_id + for panel in schema["panels"]: + for item in _iter_panel_items(panel): + key = item["key"] + if key in seen: + pytest.fail(f"Key '{key}' appears in both panel '{seen[key]}' and '{panel['id']}'") + seen[key] = panel["id"] + for sub in item.get("sub_items", []): + sub_key = sub["key"] + if sub_key in seen: + pytest.fail(f"Sub-item key '{sub_key}' appears in both '{seen[sub_key]}' and '{panel['id']}'") + seen[sub_key] = panel["id"] + + +class TestSchemaCoverage: + def test_all_schema_keys_exist_in_params(self, schema, all_param_keys): + """Schema keys must exist in Params().all_keys().""" + schema_keys = collect_all_keys(schema) + missing = schema_keys - all_param_keys + assert not missing, f"Schema references keys not in Params: {missing}" + + def test_all_capability_fields_are_declared(self, schema): + """Capability fields used in rules must be declared.""" + declared = set(schema["capability_fields"]) + referenced = collect_capability_refs(schema) + undeclared = referenced - declared + assert not undeclared, f"Rules reference undeclared capability fields: {undeclared}" + + def test_capability_fields_match_constant(self, schema): + """Schema capability_fields must match CAPABILITY_FIELDS constant.""" + assert set(schema["capability_fields"]) == set(CAPABILITY_FIELDS) + + +class TestRuleWellFormedness: + def _validate_rule(self, rule: dict, context: str = ""): + """Recursively validate a single rule dict.""" + assert "type" in rule, f"Rule missing 'type' in {context}" + rtype = rule["type"] + assert rtype in VALID_RULE_TYPES, f"Invalid rule type '{rtype}' in {context}" + + if rtype == "capability": + assert "field" in rule, f"Capability rule missing 'field' in {context}" + assert "equals" in rule, f"Capability rule missing 'equals' in {context}" + elif rtype == "param": + assert "key" in rule, f"Param rule missing 'key' in {context}" + assert "equals" in rule, f"Param rule missing 'equals' in {context}" + elif rtype == "param_compare": + assert "key" in rule, f"Param compare rule missing 'key' in {context}" + assert "op" in rule, f"Param compare rule missing 'op' in {context}" + assert rule["op"] in VALID_COMPARE_OPS, f"Invalid op '{rule['op']}' in {context}" + assert "value" in rule, f"Param compare rule missing 'value' in {context}" + elif rtype == "not": + assert "condition" in rule, f"Not rule missing 'condition' in {context}" + self._validate_rule(rule["condition"], context=f"{context} > not") + elif rtype in ("any", "all"): + assert "conditions" in rule, f"{rtype} rule missing 'conditions' in {context}" + assert isinstance(rule["conditions"], list) + for c in rule["conditions"]: + self._validate_rule(c, context=f"{context} > {rtype}") + + def _validate_items(self, items: list[dict], context: str): + for item in items: + key = item.get("key", "unknown") + for rules_field in ("visibility", "enablement"): + rules = item.get(rules_field) + if rules: + assert isinstance(rules, list), f"{key}.{rules_field} must be a list" + for rule in rules: + self._validate_rule(rule, context=f"{context}.{key}.{rules_field}") + for sub in item.get("sub_items", []): + self._validate_items([sub], context=f"{context}.{key}") + + def _validate_section_rules(self, section: dict, context: str): + for rules_field in ("visibility", "enablement"): + rules = section.get(rules_field) or [] + for rule in rules: + self._validate_rule(rule, context=f"{context}.{rules_field}") + + def test_all_panel_rules_well_formed(self, schema): + for panel in schema["panels"]: + self._validate_items(list(_iter_panel_items(panel)), context=f"panel:{panel['id']}") + for sp in _iter_all_sub_panels(panel): + self._validate_items(sp["items"], context=f"subpanel:{sp['id']}") + for section in panel.get("sections", []): + self._validate_section_rules(section, context=f"section:{panel['id']}.{section['id']}") + + def test_all_vehicle_rules_well_formed(self, schema): + for brand, data in schema["vehicle_settings"].items(): + self._validate_items(_brand_items(data), context=f"vehicle:{brand}") + + def test_no_self_referencing_visibility(self, schema): + """An item's visibility/enablement rules should not depend on its own key.""" + def _check_self_ref(item: dict, rules_field: str): + key = item.get("key") + for rule in item.get(rules_field, []): + if rule.get("type") == "param" and rule.get("key") == key: + pytest.fail(f"Item {key} has self-referencing {rules_field} rule") + + for panel in schema["panels"]: + for item in _iter_panel_items(panel): + _check_self_ref(item, "visibility") + _check_self_ref(item, "enablement") + + for brand_data in schema.get("vehicle_settings", {}).values(): + for item in _brand_items(brand_data): + _check_self_ref(item, "visibility") + _check_self_ref(item, "enablement") + + +class TestKnownPanels: + def test_expected_panels_exist(self, schema): + panel_ids = {p["id"] for p in schema["panels"]} + expected = {"steering", "cruise", "display", "visuals", "device", "software", "developer"} + assert expected.issubset(panel_ids), f"Missing panels: {expected - panel_ids}" + + def test_mads_sub_panel_exists(self, schema): + steering = next(p for p in schema["panels"] if p["id"] == "steering") + sub_ids = {sp["id"] for sp in _iter_all_sub_panels(steering)} + assert "mads_settings" in sub_ids + + def test_mutual_exclusion_torque_nnlc(self, schema): + """EnforceTorqueControl and NNLC must reference each other in enablement.""" + torque = nnlc = None + for panel in schema["panels"]: + for item in _iter_panel_items(panel): + if item["key"] == "EnforceTorqueControl": + torque = item + elif item["key"] == "NeuralNetworkLateralControl": + nnlc = item + assert torque is not None, "EnforceTorqueControl item missing" + assert nnlc is not None, "NeuralNetworkLateralControl item missing" + torque_enable_keys = {r.get("key") for r in torque.get("enablement", []) if r.get("type") == "param"} + assert "NeuralNetworkLateralControl" in torque_enable_keys + nnlc_enable_keys = {r.get("key") for r in nnlc.get("enablement", []) if r.get("type") == "param"} + assert "EnforceTorqueControl" in nnlc_enable_keys + + +class TestKnownVehicleSettings: + def test_hyundai_has_longitudinal_tuning(self, schema): + keys = {i["key"] for i in _brand_items(schema["vehicle_settings"].get("hyundai"))} + assert "HyundaiLongitudinalTuning" in keys + + def test_toyota_has_enforce_stock_and_stop_go(self, schema): + keys = {i["key"] for i in _brand_items(schema["vehicle_settings"].get("toyota"))} + assert "ToyotaEnforceStockLongitudinal" in keys + assert "ToyotaStopAndGoHack" in keys + + def test_tesla_has_coop_steering(self, schema): + keys = {i["key"] for i in _brand_items(schema["vehicle_settings"].get("tesla"))} + assert "TeslaCoopSteering" in keys + + def test_subaru_has_stop_and_go(self, schema): + keys = {i["key"] for i in _brand_items(schema["vehicle_settings"].get("subaru"))} + assert "SubaruStopAndGo" in keys + assert "SubaruStopAndGoManualParkingBrake" in keys + + +class TestItemCompleteness: + def _collect_all_items(self, schema): + """Collect all items and sub_items from panels and vehicle_settings.""" + items = [] + for panel in schema["panels"]: + for item in _iter_panel_items(panel): + items.append(item) + for sub in item.get("sub_items", []): + items.append(sub) + for brand_data in schema.get("vehicle_settings", {}).values(): + for item in _brand_items(brand_data): + items.append(item) + for sub in item.get("sub_items", []): + items.append(sub) + return items + + def test_all_items_have_titles(self, schema): + """All items must have titles.""" + missing = [i["key"] for i in self._collect_all_items(schema) if "title" not in i] + if len(missing) > MAX_ALLOWED_MISSING_TITLES: + pytest.fail(f"Items without titles ({len(missing)}): {missing[:10]}") + + def test_no_default_titles(self, schema): + """Item titles must differ from keys.""" + defaults = [i["key"] for i in self._collect_all_items(schema) if i.get("title") == i["key"]] + assert not defaults, f"Items with default titles (title == key): {defaults}" + + def test_options_structure(self, schema): + """Options must be a list of {value, label} dicts.""" + for item in self._collect_all_items(schema): + opts = item.get("options") + if opts is None: + continue + assert isinstance(opts, list), f"{item['key']}: options must be a list" + for opt in opts: + assert isinstance(opt, dict), f"{item['key']}: each option must be a dict" + assert "value" in opt, f"{item['key']}: option missing 'value': {opt}" + assert "label" in opt, f"{item['key']}: option missing 'label': {opt}" + + def test_numeric_constraints(self, schema): + """If any of min/max/step is present, all three must be, and min < max.""" + for item in self._collect_all_items(schema): + has_min = "min" in item + has_max = "max" in item + has_step = "step" in item + if has_min or has_max or has_step: + assert has_min and has_max and has_step, \ + f"{item['key']}: must have all of min/max/step or none" + assert item["min"] < item["max"], \ + f"{item['key']}: min ({item['min']}) must be < max ({item['max']})" + + def test_known_param_has_options(self, schema): + """LongitudinalPersonality should have 3 options.""" + cruise = next(p for p in schema["panels"] if p["id"] == "cruise") + lp = next((i for i in _iter_panel_items(cruise) if i["key"] == "LongitudinalPersonality"), None) + assert lp is not None + assert "options" in lp + assert len(lp["options"]) == 3 diff --git a/openpilot/sunnypilot/sunnylink/tools/apply_macros.py b/openpilot/sunnypilot/sunnylink/tools/apply_macros.py new file mode 100755 index 0000000000..a6b56122ad --- /dev/null +++ b/openpilot/sunnypilot/sunnylink/tools/apply_macros.py @@ -0,0 +1,211 @@ +#!/usr/bin/env python3 +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. + +Scans all per-page YAML files in settings_ui_src/pages/ and replaces inlined +rule blocks that exactly match a macro definition in _macros.yaml with $ref +references. + +Match policy: + - Whole-list match (exact): replace the entire list with [{$ref}]. + - Single-rule match: any individual rule whose canonical form equals macro[0] + (when macro is exactly one rule) is replaced with {$ref}. + +Re-run is idempotent (already-substituted $refs are skipped). + +Usage: + python apply_macros.py [--src DIR] [--dry-run] +""" +from __future__ import annotations + +import argparse +import json +import os +import sys + +import yaml + +DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +DEFAULT_SRC = os.path.join(DIR, "settings_ui_src") + + +class _BlockDumper(yaml.SafeDumper): + pass + + +def _represent_dict(dumper, data): + return dumper.represent_mapping("tag:yaml.org,2002:map", data.items(), flow_style=False) + + +def _represent_list(dumper, data): + flow = all(not isinstance(x, (dict, list)) for x in data) and len(data) <= 8 + return dumper.represent_sequence("tag:yaml.org,2002:seq", data, flow_style=flow) + + +_BlockDumper.add_representer(dict, _represent_dict) +_BlockDumper.add_representer(list, _represent_list) + + +def _dump_yaml(data) -> str: + return yaml.dump(data, Dumper=_BlockDumper, sort_keys=False, allow_unicode=True, width=120) + + +def _canon(node) -> str: + return json.dumps(node, sort_keys=True, separators=(",", ":")) + + +def _is_ref(node) -> bool: + return isinstance(node, dict) and len(node) == 1 and "$ref" in node + + +def _make_ref(name: str) -> dict: + return {"$ref": f"#/macros/{name}"} + + +def _substitute_rules(rules: list, whole_list: dict, single_rule: dict) -> list: + if not isinstance(rules, list) or not rules: + return rules + full_canon = _canon(rules) + if full_canon in whole_list: + return [_make_ref(whole_list[full_canon])] + out = [] + for r in rules: + if _is_ref(r): + out.append(r) + continue + rc = _canon(r) + if rc in single_rule: + out.append(_make_ref(single_rule[rc])) + else: + out.append(r) + return out + + +def _walk_item(item: dict, whole_list: dict, single_rule: dict) -> bool: + changed = False + for ctx in ("visibility", "enablement"): + if ctx in item: + new = _substitute_rules(item[ctx], whole_list, single_rule) + if new != item[ctx]: + item[ctx] = new + changed = True + if "options" in item: + for opt in item["options"]: + if not isinstance(opt, dict): + continue + for ctx in ("visibility", "enablement"): + if ctx in opt: + new = _substitute_rules(opt[ctx], whole_list, single_rule) + if new != opt[ctx]: + opt[ctx] = new + changed = True + if "sub_items" in item: + for sub in item["sub_items"]: + if _walk_item(sub, whole_list, single_rule): + changed = True + return changed + + +def _walk_page(page: dict, whole_list: dict, single_rule: dict) -> bool: + changed = False + for sec in page.get("sections", []) or []: + for ctx in ("visibility", "enablement"): + if ctx in sec: + new = _substitute_rules(sec[ctx], whole_list, single_rule) + if new != sec[ctx]: + sec[ctx] = new + changed = True + for it in sec.get("items", []) or []: + if _walk_item(it, whole_list, single_rule): + changed = True + for sp in sec.get("sub_panels", []) or []: + for it in sp.get("items", []) or []: + if _walk_item(it, whole_list, single_rule): + changed = True + for it in page.get("items", []) or []: + if _walk_item(it, whole_list, single_rule): + changed = True + for sp in page.get("sub_panels", []) or []: + for it in sp.get("items", []) or []: + if _walk_item(it, whole_list, single_rule): + changed = True + return changed + + +def _build_macro_indices(macros: dict) -> tuple[dict, dict]: + whole_list = {} + single_rule = {} + for name, body in macros.items(): + if isinstance(body, list): + whole_list[_canon(body)] = name + if len(body) == 1 and isinstance(body[0], dict): + single_rule[_canon(body[0])] = name + elif isinstance(body, dict): + single_rule[_canon(body)] = name + return whole_list, single_rule + + +def _read_yaml_with_header(path: str) -> tuple[list[str], dict]: + with open(path) as f: + text = f.read() + header_lines = [] + for line in text.splitlines(keepends=True): + if line.startswith("#"): + header_lines.append(line) + elif line.strip() == "": + header_lines.append(line) + else: + break + doc = yaml.safe_load(text) or {} + return header_lines, doc + + +def _write_yaml_with_header(path: str, header: list[str], doc: dict) -> None: + with open(path, "w") as f: + if header: + # Keep at most one trailing blank line in header + while len(header) > 1 and header[-1].strip() == "" and header[-2].strip() == "": + header.pop() + for line in header: + f.write(line) + f.write(_dump_yaml(doc)) + + +def apply(src_dir: str, dry_run: bool) -> int: + with open(os.path.join(src_dir, "_macros.yaml")) as f: + macros_doc = yaml.safe_load(f) or {} + macros = (macros_doc.get("macros") or {}) if isinstance(macros_doc, dict) else {} + whole_list, single_rule = _build_macro_indices(macros) + + changed_files = 0 + pages_dir = os.path.join(src_dir, "pages") + if os.path.isdir(pages_dir): + for fn in sorted(os.listdir(pages_dir)): + if not fn.endswith((".yaml", ".yml")) or fn.startswith("_"): + continue + path = os.path.join(pages_dir, fn) + header, doc = _read_yaml_with_header(path) + if _walk_page(doc, whole_list, single_rule): + changed_files += 1 + if not dry_run: + _write_yaml_with_header(path, header, doc) + else: + print(f"would-rewrite: {path}") + + print(f"{'Would rewrite' if dry_run else 'Rewrote'} {changed_files} files") + return 0 + + +def _main() -> int: + parser = argparse.ArgumentParser(description="Substitute inlined rule blocks with $ref macros across pages/.") + parser.add_argument("--src", default=DEFAULT_SRC) + parser.add_argument("--dry-run", action="store_true") + args = parser.parse_args() + return apply(args.src, args.dry_run) + + +if __name__ == "__main__": + sys.exit(_main()) diff --git a/openpilot/sunnypilot/sunnylink/tools/compile_settings_ui.py b/openpilot/sunnypilot/sunnylink/tools/compile_settings_ui.py new file mode 100755 index 0000000000..c13ecd63a0 --- /dev/null +++ b/openpilot/sunnypilot/sunnylink/tools/compile_settings_ui.py @@ -0,0 +1,300 @@ +#!/usr/bin/env python3 +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. + +Reads settings_ui_src/ (the dev-friendly authoring tree) and emits the +canonical settings_ui.json that the device generator + frontend consume. + +Source layout: + _macros.yaml # named rule fragments + pages/.yaml # one file per panel/page + pages/vehicle.yaml # special: emits vehicle_settings + +Each page.yaml contains the full panel: metadata + sections + items + sub_panels +inline. Sub-panels are nested inside the section they belong to. Items appear +in the order written in the file. + +Macro references use JSON-Schema-style $ref pointers: + enablement: + - {$ref: "#/macros/offroad"} + - {$ref: "#/macros/mads_full_platforms"} + +Macros may reference other macros (max depth 3). Cycles raise an error. + +Usage: + python compile_settings_ui.py [--src DIR] [--out PATH] [--check] +""" +from __future__ import annotations + +import argparse +import copy +import json +import os +import sys + +import yaml + +DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +DEFAULT_SRC = os.path.join(DIR, "settings_ui_src") +DEFAULT_OUT = os.path.join(DIR, "settings_ui.json") + +SCHEMA_VERSION = "1.0" +MAX_MACRO_DEPTH = 3 + + +class CompileError(Exception): + pass + + +def _load_yaml(path: str): + with open(path) as f: + return yaml.safe_load(f) or {} + + +def _is_ref(node) -> bool: + return isinstance(node, dict) and len(node) == 1 and "$ref" in node + + +def _ref_name(node: dict) -> str: + ref = node["$ref"] + if not isinstance(ref, str) or not ref.startswith("#/macros/"): + raise CompileError(f"unsupported $ref: {ref!r} (must start with '#/macros/')") + return ref[len("#/macros/"):] + + +def _resolve_refs(node, macros: dict, visiting: tuple[str, ...] = ()): + """Resolve $ref nodes against macros. Recursive; depth-limited; cycle-safe. + + - $ref in list-context: macro's list spliced into parent list. + - $ref in scalar-context (object value): macro's value substitutes. + - Non-list macro values may not be referenced from list contexts. + """ + if _is_ref(node): + name = _ref_name(node) + if name in visiting: + raise CompileError(f"$ref cycle: {' -> '.join(visiting + (name,))}") + if len(visiting) >= MAX_MACRO_DEPTH: + raise CompileError(f"$ref nesting exceeds depth {MAX_MACRO_DEPTH}: {' -> '.join(visiting + (name,))}") + if name not in macros: + raise CompileError(f"unknown macro: {name}") + return _resolve_refs(copy.deepcopy(macros[name]), macros, visiting + (name,)) + + if isinstance(node, dict): + return {k: _resolve_refs(v, macros, visiting) for k, v in node.items()} + + if isinstance(node, list): + out = [] + for item in node: + if _is_ref(item): + resolved = _resolve_refs(item, macros, visiting) + if not isinstance(resolved, list): + raise CompileError( + f"macro '{_ref_name(item)}' must resolve to a list when used in a list context" + ) + out.extend(resolved) + else: + out.append(_resolve_refs(item, macros, visiting)) + return out + + return node + + +# Output JSON key order. Mirrors the conventions in the original hand-written +# settings_ui.json so structural diffs after extraction are minimal. +_ITEM_KEY_ORDER = [ + "key", + "widget", + "needs_onroad_cycle", + "requires_attestation", + "blocked", + "title", + "description", + "details", + "title_param_suffix", + "min", + "max", + "step", + "unit", + "options", + "visibility", + "enablement", + "sub_items", +] + + +def _canon_item(item: dict, macros: dict) -> dict: + resolved = dict(item) + for ctx in ("visibility", "enablement"): + if ctx in resolved: + resolved[ctx] = _resolve_refs(resolved[ctx], macros) + if "options" in resolved: + new_opts = [] + for opt in resolved["options"]: + if isinstance(opt, dict): + opt = dict(opt) + for ctx in ("visibility", "enablement"): + if ctx in opt: + opt[ctx] = _resolve_refs(opt[ctx], macros) + new_opts.append(opt) + resolved["options"] = new_opts + if "sub_items" in resolved: + resolved["sub_items"] = [_canon_item(s, macros) for s in resolved["sub_items"]] + + out: dict = {} + for k in _ITEM_KEY_ORDER: + if k in resolved: + out[k] = resolved[k] + for k, v in resolved.items(): + if k not in out: + out[k] = v + return out + + +def _canon_section(section: dict, macros: dict) -> dict: + out: dict = {"id": section["id"], "title": section["title"]} + if "description" in section: + out["description"] = section["description"] + for k in ("visibility", "enablement"): + if k in section: + out[k] = _resolve_refs(section[k], macros) + if "attestation_required" in section: + out["attestation_required"] = section["attestation_required"] + out["items"] = [_canon_item(i, macros) for i in section.get("items", [])] + if "sub_panels" in section and section["sub_panels"]: + out["sub_panels"] = [_canon_sub_panel(sp, macros) for sp in section["sub_panels"]] + for k, v in section.items(): + if k not in out and k != "order": + out[k] = v + return out + + +def _canon_sub_panel(sp: dict, macros: dict) -> dict: + out: dict = {"id": sp["id"], "label": sp["label"], "trigger_key": sp["trigger_key"]} + if "trigger_condition" in sp: + out["trigger_condition"] = _resolve_refs(sp["trigger_condition"], macros) + out["items"] = [_canon_item(i, macros) for i in sp.get("items", [])] + for k, v in sp.items(): + if k not in out: + out[k] = v + return out + + +def _canon_panel(page: dict, macros: dict) -> dict: + out: dict = { + "id": page["id"], + "label": page["label"], + "icon": page["icon"], + "order": page["order"], + } + if "remote_configurable" in page: + out["remote_configurable"] = page["remote_configurable"] + if "description" in page: + out["description"] = page["description"] + if "sections" in page and page["sections"]: + out["sections"] = [_canon_section(s, macros) for s in page["sections"]] + if "items" in page and page["items"]: + out["items"] = [_canon_item(i, macros) for i in page["items"]] + if "sub_panels" in page and page["sub_panels"]: + out["sub_panels"] = [_canon_sub_panel(sp, macros) for sp in page["sub_panels"]] + return out + + +def _canon_vehicle(page: dict, macros: dict) -> dict: + """Convert page-shape vehicle.yaml to wire-format vehicle_settings dict.""" + out: dict = {} + for sec in page.get("sections", []): + brand = sec["id"] + brand_out: dict = {"title": sec.get("title", "")} + if "description" in sec: + brand_out["description"] = sec["description"] + brand_out["items"] = [_canon_item(i, macros) for i in sec.get("items", [])] + out[brand] = brand_out + return out + + +def _load_pages(src: str) -> list[dict]: + pages_dir = os.path.join(src, "pages") + if not os.path.isdir(pages_dir): + return [] + pages = [] + for fn in sorted(os.listdir(pages_dir)): + if not fn.endswith((".yaml", ".yml")): + continue + if fn.startswith("_"): + continue + path = os.path.join(pages_dir, fn) + page = _load_yaml(path) + if not isinstance(page, dict): + raise CompileError(f"{path}: page YAML must be an object") + if "id" not in page: + raise CompileError(f"{path}: page missing 'id'") + page["__source"] = path + pages.append(page) + return pages + + +def compile_schema(src: str) -> dict: + macros_doc = _load_yaml(os.path.join(src, "_macros.yaml")) + macros = (macros_doc.get("macros") or {}) if isinstance(macros_doc, dict) else {} + + pages = _load_pages(src) + + panels_out = [] + vehicle_out: dict = {} + + # Order panels by `order` field (falling back to file position). + panel_pages = [p for p in pages if p.get("kind") != "vehicle"] + panel_pages.sort(key=lambda p: (p.get("order", 999), p["id"])) + + for page in panel_pages: + panels_out.append(_canon_panel(page, macros)) + + for page in pages: + if page.get("kind") == "vehicle": + vehicle_out = _canon_vehicle(page, macros) + + return { + "$schema": "./settings_ui.schema.json", + "schema_version": SCHEMA_VERSION, + "panels": panels_out, + "vehicle_settings": vehicle_out, + } + + +def _main() -> int: + parser = argparse.ArgumentParser(description="Compile settings_ui_src/ -> settings_ui.json") + parser.add_argument("--src", default=DEFAULT_SRC) + parser.add_argument("--out", default=DEFAULT_OUT) + parser.add_argument("--check", action="store_true", + help="Compile and diff against existing settings_ui.json; exit non-zero on diff.") + args = parser.parse_args() + + schema = compile_schema(args.src) + rendered = json.dumps(schema, indent=2) + "\n" + + if args.check: + if not os.path.exists(args.out): + print(f"--check: {args.out} does not exist", file=sys.stderr) + return 1 + with open(args.out) as f: + current = f.read() + if current.strip() == rendered.strip(): + print(f"--check: {args.out} matches compiled output") + return 0 + print(f"--check: {args.out} differs from compiled output", file=sys.stderr) + cur_obj = json.loads(current) + if cur_obj == schema: + print("(structurally equal; only formatting differs)", file=sys.stderr) + return 1 + + with open(args.out, "w") as f: + f.write(rendered) + print(f"Wrote {args.out}") + return 0 + + +if __name__ == "__main__": + sys.exit(_main()) diff --git a/openpilot/sunnypilot/sunnylink/tools/extract_settings_ui.py b/openpilot/sunnypilot/sunnylink/tools/extract_settings_ui.py new file mode 100755 index 0000000000..4b3283f770 --- /dev/null +++ b/openpilot/sunnypilot/sunnylink/tools/extract_settings_ui.py @@ -0,0 +1,214 @@ +#!/usr/bin/env python3 +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. + +One-shot extractor: settings_ui.json -> settings_ui_src/pages/*.yaml. + +Reads the existing monolithic settings_ui.json and produces one YAML file per +page (panel) plus pages/vehicle.yaml for the per-brand settings. Macros remain +unwritten by extract; populate _macros.yaml separately. + +Usage: + python extract_settings_ui.py [--src DIR] [--definition PATH] +""" +from __future__ import annotations + +import argparse +import json +import os +import shutil +import sys + +import yaml + +DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +DEFAULT_DEFINITION = os.path.join(DIR, "settings_ui.json") +DEFAULT_SRC = os.path.join(DIR, "settings_ui_src") + + +class _BlockDumper(yaml.SafeDumper): + pass + + +def _represent_dict(dumper, data): + return dumper.represent_mapping("tag:yaml.org,2002:map", data.items(), flow_style=False) + + +def _represent_list(dumper, data): + flow = all(not isinstance(x, (dict, list)) for x in data) and len(data) <= 8 + return dumper.represent_sequence("tag:yaml.org,2002:seq", data, flow_style=flow) + + +_BlockDumper.add_representer(dict, _represent_dict) +_BlockDumper.add_representer(list, _represent_list) + + +def _dump_yaml(data) -> str: + return yaml.dump(data, Dumper=_BlockDumper, sort_keys=False, allow_unicode=True, width=120) + + +# Item field order in per-page YAML (mirrors settings_ui.json conventions). +_ITEM_ORDER = [ + "key", + "widget", + "needs_onroad_cycle", + "requires_attestation", + "blocked", + "title", + "description", + "details", + "title_param_suffix", + "min", + "max", + "step", + "unit", + "options", + "visibility", + "enablement", + "sub_items", +] + + +def _ordered_item(item: dict) -> dict: + out: dict = {} + for k in _ITEM_ORDER: + if k in item: + v = item[k] + if k == "sub_items": + v = [_ordered_item(s) for s in v] + out[k] = v + for k, v in item.items(): + if k not in out: + out[k] = v + return out + + +def _ordered_section(section: dict) -> dict: + out: dict = {"id": section["id"], "title": section["title"]} + for f in ("description", "order", "visibility", "enablement", "attestation_required"): + if f in section: + out[f] = section[f] + if "items" in section: + out["items"] = [_ordered_item(i) for i in section["items"]] + if "sub_panels" in section and section["sub_panels"]: + out["sub_panels"] = [_ordered_sub_panel(sp) for sp in section["sub_panels"]] + for k, v in section.items(): + if k not in out: + out[k] = v + return out + + +def _ordered_sub_panel(sp: dict) -> dict: + out: dict = {"id": sp["id"], "label": sp["label"], "trigger_key": sp["trigger_key"]} + if "trigger_condition" in sp: + out["trigger_condition"] = sp["trigger_condition"] + if "items" in sp: + out["items"] = [_ordered_item(i) for i in sp["items"]] + for k, v in sp.items(): + if k not in out: + out[k] = v + return out + + +def _ordered_page(panel: dict) -> dict: + out: dict = { + "id": panel["id"], + "label": panel["label"], + "icon": panel["icon"], + "order": panel["order"], + } + for f in ("remote_configurable", "description"): + if f in panel: + out[f] = panel[f] + if "sections" in panel and panel["sections"]: + out["sections"] = [_ordered_section(s) for s in panel["sections"]] + if "items" in panel and panel["items"]: + out["items"] = [_ordered_item(i) for i in panel["items"]] + if "sub_panels" in panel and panel["sub_panels"]: + out["sub_panels"] = [_ordered_sub_panel(sp) for sp in panel["sub_panels"]] + for k, v in panel.items(): + if k not in out: + out[k] = v + return out + + +def _ordered_vehicle_page(vehicle_settings: dict) -> dict: + """Convert wire-format vehicle_settings dict into a page-shape YAML. + + Brand becomes a section id. Each brand's items become section items. + """ + sections = [] + for brand in sorted(vehicle_settings.keys()): + bd = vehicle_settings[brand] + items = bd.get("items", []) if isinstance(bd, dict) else bd + sec: dict = { + "id": brand, + "title": bd.get("title", "") if isinstance(bd, dict) else "", + } + if isinstance(bd, dict) and "description" in bd: + sec["description"] = bd["description"] + sec["items"] = [_ordered_item(i) for i in items] + sections.append(sec) + return { + "id": "vehicle", + "label": "Vehicle", + "icon": "vehicle", + "order": 99, + "kind": "vehicle", # signals to compiler: emit as vehicle_settings, not panels + "sections": sections, + } + + +def extract(definition_path: str, src_dir: str) -> None: + with open(definition_path) as f: + data = json.load(f) + + pages_dir = os.path.join(src_dir, "pages") + if os.path.isdir(pages_dir): + shutil.rmtree(pages_dir) + os.makedirs(pages_dir) + + count = 0 + for panel in data.get("panels", []): + page = _ordered_page(panel) + path = os.path.join(pages_dir, f"{panel['id']}.yaml") + with open(path, "w") as f: + f.write(f"# Page: {panel['id']}\n") + f.write("# Edit this file. Run compile_settings_ui.py to emit settings_ui.json.\n") + f.write(_dump_yaml(page)) + count += 1 + + vehicle_settings = data.get("vehicle_settings", {}) + if vehicle_settings: + vehicle_page = _ordered_vehicle_page(vehicle_settings) + path = os.path.join(pages_dir, "vehicle.yaml") + with open(path, "w") as f: + f.write("# Page: vehicle (per-brand settings)\n") + f.write("# Compiles to settings_ui.json#vehicle_settings (brand = section id).\n") + f.write(_dump_yaml(vehicle_page)) + count += 1 + + # Ensure _macros.yaml exists + macros_path = os.path.join(src_dir, "_macros.yaml") + if not os.path.exists(macros_path): + with open(macros_path, "w") as f: + f.write("# Named rule fragments. Reference from pages via {$ref: \"#/macros/\"}.\n") + f.write(_dump_yaml({"macros": {}})) + + print(f"Extracted: {count} pages -> {pages_dir}") + + +def _main() -> int: + parser = argparse.ArgumentParser(description="Extract settings_ui.json into per-page YAML files.") + parser.add_argument("--definition", default=DEFAULT_DEFINITION, help="path to settings_ui.json") + parser.add_argument("--src", default=DEFAULT_SRC, help="path to settings_ui_src/ output dir") + args = parser.parse_args() + extract(args.definition, args.src) + return 0 + + +if __name__ == "__main__": + sys.exit(_main()) diff --git a/openpilot/sunnypilot/sunnylink/tools/generate_settings_schema.py b/openpilot/sunnypilot/sunnylink/tools/generate_settings_schema.py new file mode 100755 index 0000000000..5ace2a8087 --- /dev/null +++ b/openpilot/sunnypilot/sunnylink/tools/generate_settings_schema.py @@ -0,0 +1,194 @@ +#!/usr/bin/env python3 +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from __future__ import annotations + +import base64 +import datetime +import gzip +import json +import os +from collections.abc import Callable + +from openpilot.sunnypilot.sunnylink.capabilities import CAPABILITY_FIELDS, CAPABILITY_LABELS + +SCHEMA_VERSION = "1.0" +_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +DEFINITION_PATH = os.path.join(_DIR, "settings_ui.json") +TORQUE_VERSIONS_PATH = os.path.normpath( + os.path.join(_DIR, "..", "selfdrive", "controls", "lib", "latcontrol_torque_versions.json") +) + + +def _load_torque_versions() -> dict: + """Load latcontrol_torque_versions.json so TorqueControlTune options stay in sync.""" + try: + with open(TORQUE_VERSIONS_PATH) as f: + return json.load(f) + except (FileNotFoundError, json.JSONDecodeError): + return {} + + +def _build_torque_options(versions: dict) -> list[dict]: + options: list[dict] = [{"value": "", "label": "Default"}] + parsed: list[tuple[float, str]] = [] + for label, info in versions.items(): + try: + parsed.append((float(info["version"]), label)) + except (KeyError, TypeError, ValueError): + continue + for version, label in sorted(parsed, key=lambda kv: kv[0], reverse=True): + options.append({"value": version, "label": label}) + return options + + +def _inject_dynamic_options(schema: dict) -> None: + versions = _load_torque_versions() + if not versions: + return + options = _build_torque_options(versions) + + def visitor(item: dict) -> None: + if item.get("key") == "TorqueControlTune": + item["options"] = options + + _walk_all_items(schema, visitor) + + +def _load_definition() -> dict: + """Load settings_ui.json and inject dynamic options sourced from runtime data files.""" + with open(DEFINITION_PATH) as f: + schema = json.load(f) + _inject_dynamic_options(schema) + return schema + + +# Public API +def generate_schema() -> dict: + """Return the settings_ui.json content augmented with runtime metadata. + + Adds three top-level fields the frontend consumes: + - generated_at: ISO timestamp (drives schema-cache freshness checks) + - capability_fields: declared CAPABILITY_FIELDS, used for rule validation + - capability_labels: human-readable labels for capability_fields + """ + schema = _load_definition() + schema["generated_at"] = datetime.datetime.now(datetime.UTC).isoformat() + schema["capability_fields"] = list(CAPABILITY_FIELDS) + schema["capability_labels"] = dict(CAPABILITY_LABELS) + return schema + + +def generate_schema_json() -> str: + """Generate SettingsSchema as a compact JSON string.""" + return json.dumps(generate_schema(), separators=(",", ":")) + + +def generate_schema_compressed() -> str: + """Generate SettingsSchema as gzip-compressed, base64-encoded string. + + Compression pipeline: + 1. JSON serialize (compact, no whitespace) + 2. UTF-8 encode + 3. gzip compress + 4. base64 encode + """ + raw = json.dumps(generate_schema(), separators=(",", ":")).encode("utf-8") + return base64.b64encode(gzip.compress(raw)).decode("utf-8") + + +# Schema introspection utilities +def _walk_rules(rules: list[dict] | None, visitor: Callable[[dict], None]) -> None: + """Recursively walk all rules, calling visitor on each leaf rule.""" + if not rules: + return + for rule in rules: + visitor(rule) + if rule.get("type") == "not" and "condition" in rule: + _walk_rules([rule["condition"]], visitor) + elif rule.get("type") in ("any", "all") and "conditions" in rule: + _walk_rules(rule["conditions"], visitor) + + +def _walk_all_items(schema: dict, visitor: Callable[[dict], None]) -> None: + """Walk every item in the schema (panels, sections, sub_panels, sub_items, vehicle_settings).""" + def _visit_item(item: dict) -> None: + visitor(item) + for sub in item.get("sub_items", []): + _visit_item(sub) + + for panel in schema.get("panels", []): + # Walk section items (V2) + for section in panel.get("sections", []): + for item in section.get("items", []): + _visit_item(item) + for sp in section.get("sub_panels", []): + for item in sp.get("items", []): + _visit_item(item) + + # Walk flat items (V1) + for item in panel.get("items", []): + _visit_item(item) + for sp in panel.get("sub_panels", []): + for item in sp.get("items", []): + _visit_item(item) + + for brand_data in schema.get("vehicle_settings", {}).values(): + items = brand_data.get("items", []) if isinstance(brand_data, dict) else brand_data + for item in items: + _visit_item(item) + + +def collect_all_keys(schema: dict) -> set[str]: + """Collect all param keys referenced in the schema (items + rules).""" + keys: set[str] = set() + + def _visit_rule(rule: dict) -> None: + if rule.get("type") in ("param", "param_compare") and "key" in rule: + keys.add(rule["key"]) + + def _visit_item(item: dict) -> None: + if "key" in item: + keys.add(item["key"]) + _walk_rules(item.get("visibility"), _visit_rule) + _walk_rules(item.get("enablement"), _visit_rule) + + _walk_all_items(schema, _visit_item) + return keys + + +def collect_capability_refs(schema: dict) -> set[str]: + """Collect all capability field names referenced in rules.""" + refs: set[str] = set() + + def _visit_rule(rule: dict) -> None: + if rule.get("type") == "capability" and "field" in rule: + refs.add(rule["field"]) + + def _visit_item(item: dict) -> None: + _walk_rules(item.get("visibility"), _visit_rule) + _walk_rules(item.get("enablement"), _visit_rule) + + _walk_all_items(schema, _visit_item) + return refs + + +if __name__ == "__main__": + # CLI: print schema for inspection + schema = generate_schema() + print(json.dumps(schema, indent=2)) + print(f"\nTotal panels: {len(schema.get('panels', []))}") + print(f"Total vehicle brands: {len(schema.get('vehicle_settings', {}))}") + keys = collect_all_keys(schema) + print(f"Total unique param keys: {len(keys)}") + + # Show compression stats + raw_json = json.dumps(schema, separators=(",", ":")).encode("utf-8") + compressed = gzip.compress(raw_json) + print(f"\nRaw JSON size: {len(raw_json):,} bytes") + print(f"Compressed size: {len(compressed):,} bytes") + print(f"Compression ratio: {len(compressed)/len(raw_json):.1%}") diff --git a/openpilot/sunnypilot/sunnylink/tools/validate_settings_ui.py b/openpilot/sunnypilot/sunnylink/tools/validate_settings_ui.py new file mode 100755 index 0000000000..a7bfe7cf67 --- /dev/null +++ b/openpilot/sunnypilot/sunnylink/tools/validate_settings_ui.py @@ -0,0 +1,530 @@ +#!/usr/bin/env python3 +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. + +Validates settings_ui.json against structural, semantic, and referential integrity constraints. + +Usage: + python validate_settings_ui.py + python validate_settings_ui.py /path/to/settings_ui.json +""" +from __future__ import annotations + +import json +import os +import sys + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', '..')) + +from openpilot.sunnypilot.sunnylink.capabilities import CAPABILITY_FIELDS + +VALID_WIDGETS = {"toggle", "option", "multiple_button", "button", "info"} +VALID_COMPARE_OPS = {">", "<", ">=", "<="} + +DEFAULT_PATH = os.path.join( + os.path.dirname(os.path.dirname(os.path.abspath(__file__))), + "settings_ui.json", +) + + +class ValidationResult: + """Tracks pass/fail for each named check.""" + + def __init__(self) -> None: + self.passed: list[str] = [] + self.failed: list[tuple[str, str]] = [] + self.warnings: list[str] = [] + + def ok(self, name: str) -> None: + self.passed.append(name) + print(f"OK: {name}") + + def error(self, name: str, details: str) -> None: + self.failed.append((name, details)) + print(f"ERROR: {name}: {details}") + + def warn(self, msg: str) -> None: + self.warnings.append(msg) + print(f"WARNING: {msg}") + + @property + def success(self) -> bool: + return len(self.failed) == 0 + + def summary(self) -> None: + total_passed = len(self.passed) + total_failed = len(self.failed) + print(f"\n{'='*60}") + print(f"Summary: {total_passed} checks passed, {total_failed} checks failed") + if self.warnings: + print(f" {len(self.warnings)} warnings") + if self.success: + print("Result: PASS") + else: + print("Result: FAIL") + + +def validate_rule(rule: dict, path: str, result: ValidationResult, + capability_fields: tuple[str, ...]) -> bool: + """Validate a single rule dict. Returns True if valid.""" + if not isinstance(rule, dict): + result.error("rule well-formedness", f"{path}: rule is not a dict: {rule!r}") + return False + + rule_type = rule.get("type") + if rule_type is None: + result.error("rule well-formedness", f"{path}: rule missing 'type' field") + return False + + if rule_type in ("offroad_only", "not_engaged"): + # Only type required + return True + + if rule_type == "capability": + valid = True + if "field" not in rule or not isinstance(rule["field"], str): + result.error("rule well-formedness", f"{path}: capability rule missing/invalid 'field'") + valid = False + if "equals" not in rule: + result.error("rule well-formedness", f"{path}: capability rule missing 'equals'") + valid = False + return valid + + if rule_type == "param": + valid = True + if "key" not in rule or not isinstance(rule["key"], str): + result.error("rule well-formedness", f"{path}: param rule missing/invalid 'key'") + valid = False + if "equals" not in rule: + result.error("rule well-formedness", f"{path}: param rule missing 'equals'") + valid = False + return valid + + if rule_type == "param_compare": + valid = True + if "key" not in rule or not isinstance(rule["key"], str): + result.error("rule well-formedness", f"{path}: param_compare rule missing/invalid 'key'") + valid = False + if "op" not in rule or rule["op"] not in VALID_COMPARE_OPS: + result.error("rule well-formedness", + f"{path}: param_compare rule missing/invalid 'op' (must be one of {VALID_COMPARE_OPS})") + valid = False + if "value" not in rule or not isinstance(rule["value"], (int, float)): + result.error("rule well-formedness", f"{path}: param_compare rule missing/invalid 'value' (must be number)") + valid = False + return valid + + if rule_type == "not": + if "condition" not in rule or not isinstance(rule["condition"], dict): + result.error("rule well-formedness", f"{path}: 'not' rule missing/invalid 'condition'") + return False + return validate_rule(rule["condition"], f"{path}.not", result, capability_fields) + + if rule_type in ("any", "all"): + if "conditions" not in rule or not isinstance(rule["conditions"], list): + result.error("rule well-formedness", f"{path}: '{rule_type}' rule missing/invalid 'conditions' array") + return False + valid = True + for i, cond in enumerate(rule["conditions"]): + if not isinstance(cond, dict): + result.error("rule well-formedness", f"{path}.{rule_type}[{i}]: condition must be a dict") + valid = False + continue + if not validate_rule(cond, f"{path}.{rule_type}[{i}]", result, capability_fields): + valid = False + return valid + + result.error("rule well-formedness", f"{path}: unknown rule type '{rule_type}'") + return False + + +def collect_rules_from_item(item: dict) -> list[tuple[str, list[dict]]]: + """Return list of (context, rules_list) for an item's visibility + enablement.""" + result = [] + key = item.get("key", "?") + if "visibility" in item: + result.append((f"item '{key}' visibility", item["visibility"])) + if "enablement" in item: + result.append((f"item '{key}' enablement", item["enablement"])) + return result + + +def walk_rules_flat(rules: list[dict]) -> list[dict]: + """Flatten all rules recursively into a single list.""" + flat: list[dict] = [] + for rule in rules: + flat.append(rule) + if rule.get("type") == "not" and "condition" in rule: + flat.extend(walk_rules_flat([rule["condition"]])) + elif rule.get("type") in ("any", "all") and "conditions" in rule: + flat.extend(walk_rules_flat(rule["conditions"])) + return flat + + +def collect_all_items(data: dict) -> list[tuple[str, dict]]: + """Collect all items with their location path from the schema. + + Returns (path, item_dict) tuples. Traverses sections, sub_panels, sub_items, + and vehicle_settings. + """ + items: list[tuple[str, dict]] = [] + + for panel in data.get("panels", []): + pid = panel.get("id", "?") + + # Flat items on panel + for item in panel.get("items", []): + _collect_item(f"panel '{pid}'", item, items) + + # Sections + for section in panel.get("sections", []): + sid = section.get("id", "?") + for item in section.get("items", []): + _collect_item(f"panel '{pid}' > section '{sid}'", item, items) + for sp in section.get("sub_panels", []): + spid = sp.get("id", "?") + for item in sp.get("items", []): + _collect_item(f"panel '{pid}' > section '{sid}' > sub_panel '{spid}'", item, items) + + # Top-level sub_panels on panel (no section) + for sp in panel.get("sub_panels", []): + spid = sp.get("id", "?") + for item in sp.get("items", []): + _collect_item(f"panel '{pid}' > sub_panel '{spid}'", item, items) + + # Vehicle settings (supports both flat list and { title, items } structure) + for brand, brand_data in data.get("vehicle_settings", {}).items(): + brand_items = brand_data.get("items", []) if isinstance(brand_data, dict) else brand_data + for item in brand_items: + _collect_item(f"vehicle_settings '{brand}'", item, items) + + return items + + +def _collect_item(path: str, item: dict, items: list[tuple[str, dict]]) -> None: + """Recursively collect an item and its sub_items.""" + items.append((path, item)) + for sub in item.get("sub_items", []): + _collect_item(f"{path} > sub_item", sub, items) + + +def collect_panel_keys(panel: dict) -> set[str]: + """Collect all item keys within a single panel (sections, sub_panels, sub_items).""" + keys: set[str] = set() + + def _add(item: dict) -> None: + if "key" in item: + keys.add(item["key"]) + for sub in item.get("sub_items", []): + _add(sub) + + for item in panel.get("items", []): + _add(item) + for section in panel.get("sections", []): + for item in section.get("items", []): + _add(item) + for sp in section.get("sub_panels", []): + for item in sp.get("items", []): + _add(item) + for sp in panel.get("sub_panels", []): + for item in sp.get("items", []): + _add(item) + + return keys + + +def check_json_parseable(path: str, result: ValidationResult) -> dict | None: + """Check 1: JSON parseable.""" + try: + with open(path) as f: + data = json.load(f) + result.ok("JSON parseable") + return data + except json.JSONDecodeError as e: + result.error("JSON parseable", str(e)) + return None + except FileNotFoundError: + result.error("JSON parseable", f"file not found: {path}") + return None + + +def check_structural(data: dict, result: ValidationResult) -> None: + """Check 2: Required fields on panels, sections, items, sub_panels.""" + errors: list[str] = [] + + for i, panel in enumerate(data.get("panels", [])): + for field in ("id", "label", "icon", "order"): + if field not in panel: + errors.append(f"panels[{i}]: missing required field '{field}'") + + for j, section in enumerate(panel.get("sections", [])): + for field in ("id", "title"): + if field not in section: + errors.append(f"panels[{i}].sections[{j}]: missing required field '{field}'") + + for k, sp in enumerate(section.get("sub_panels", [])): + for field in ("id", "label", "trigger_key"): + if field not in sp: + errors.append(f"panels[{i}].sections[{j}].sub_panels[{k}]: missing required field '{field}'") + + for k, sp in enumerate(panel.get("sub_panels", [])): + for field in ("id", "label", "trigger_key"): + if field not in sp: + errors.append(f"panels[{i}].sub_panels[{k}]: missing required field '{field}'") + + # Validate items + all_items = collect_all_items(data) + for path, item in all_items: + if "key" not in item: + errors.append(f"{path}: item missing required field 'key'") + if "widget" not in item: + errors.append(f"{path}: item missing required field 'widget'") + elif item["widget"] not in VALID_WIDGETS: + errors.append( + f"{path}: item '{item.get('key', '?')}' has invalid widget '{item['widget']}'" + + f" (must be one of {VALID_WIDGETS})" + ) + + if errors: + result.error("structural", "; ".join(errors)) + else: + result.ok("structural") + + +def check_item_completeness(data: dict, result: ValidationResult) -> None: + """Check 3: All items have required metadata (title, options for dropdowns).""" + all_items = collect_all_items(data) + issues: list[str] = [] + + for _path, item in all_items: + key = item.get("key", "unknown") + if "title" not in item: + issues.append(f"{key}: missing 'title'") + elif item["title"] == key: + issues.append(f"{key}: title must not equal key (use a human-readable title)") + widget = item.get("widget") + if widget in ("multiple_button", "option") and "options" in item: + opts = item["options"] + if not isinstance(opts, list): + issues.append(f"{key}: options must be a list") + else: + for opt in opts: + if not isinstance(opt, dict) or "value" not in opt or "label" not in opt: + issues.append(f"{key}: each option must have 'value' and 'label'") + break + + if issues: + for issue in issues: + result.error("item completeness", issue) + else: + result.ok("item completeness") + + +def check_no_duplicate_keys(data: dict, result: ValidationResult) -> None: + """Check 4: No param key appears in more than one panel.""" + panel_keys: dict[str, list[str]] = {} # key -> list of panel ids + + for panel in data.get("panels", []): + pid = panel.get("id", "?") + keys = collect_panel_keys(panel) + for key in keys: + panel_keys.setdefault(key, []).append(pid) + + # Also check vehicle_settings keys don't collide with panel keys + for brand, brand_data in data.get("vehicle_settings", {}).items(): + brand_items = brand_data.get("items", []) if isinstance(brand_data, dict) else brand_data + for item in brand_items: + key = item.get("key") + if key: + panel_keys.setdefault(key, []).append(f"vehicle_settings.{brand}") + + duplicates = {k: v for k, v in panel_keys.items() if len(v) > 1} + if duplicates: + details = "; ".join(f"'{k}' in [{', '.join(v)}]" for k, v in duplicates.items()) + result.error("no duplicate keys", details) + else: + result.ok("no duplicate keys") + + +def check_rule_wellformedness(data: dict, result: ValidationResult) -> None: + """Check 5: All rules have valid structure.""" + all_items = collect_all_items(data) + + # Save current error count to detect new errors + error_count_before = len(result.failed) + + for path, item in all_items: + for ctx, rules in collect_rules_from_item(item): + for i, rule in enumerate(rules): + validate_rule(rule, f"{path} > {ctx}[{i}]", result, CAPABILITY_FIELDS) + + # Also validate trigger_condition rules on sub_panels + for panel in data.get("panels", []): + pid = panel.get("id", "?") + for section in panel.get("sections", []): + for sp in section.get("sub_panels", []): + if "trigger_condition" in sp: + validate_rule(sp["trigger_condition"], f"panel '{pid}' > sub_panel '{sp.get('id', '?')}' trigger_condition", + result, CAPABILITY_FIELDS) + + if len(result.failed) == error_count_before: + result.ok("rule well-formedness") + + +def check_capability_refs(data: dict, result: ValidationResult) -> None: + """Check 6: All capability rule field values are in CAPABILITY_FIELDS.""" + all_items = collect_all_items(data) + invalid_refs: list[str] = [] + cap_set = set(CAPABILITY_FIELDS) + + for _path, item in all_items: + for _ctx, rules in collect_rules_from_item(item): + for rule in walk_rules_flat(rules): + if rule.get("type") == "capability": + field = rule.get("field") + if field and field not in cap_set: + invalid_refs.append(f"'{field}' in item '{item.get('key', '?')}'") + + # Also check trigger_conditions + for panel in data.get("panels", []): + for section in panel.get("sections", []): + for sp in section.get("sub_panels", []): + if "trigger_condition" in sp: + for rule in walk_rules_flat([sp["trigger_condition"]]): + if rule.get("type") == "capability": + field = rule.get("field") + if field and field not in cap_set: + invalid_refs.append(f"'{field}' in sub_panel '{sp.get('id', '?')}' trigger_condition") + + if invalid_refs: + result.error("capability refs", f"unknown capability fields: {', '.join(invalid_refs)}") + else: + result.ok("capability refs") + + +def check_no_self_reference(data: dict, result: ValidationResult) -> None: + """Check 7: Item's rules must not reference the item's own key.""" + all_items = collect_all_items(data) + self_refs: list[str] = [] + + for path, item in all_items: + key = item.get("key") + if not key: + continue + for _ctx, rules in collect_rules_from_item(item): + for rule in walk_rules_flat(rules): + if rule.get("type") in ("param", "param_compare") and rule.get("key") == key: + self_refs.append(f"'{key}' at {path}") + + if self_refs: + result.error("no self-reference", f"items reference their own key: {', '.join(self_refs)}") + else: + result.ok("no self-reference") + + +def check_sub_panel_triggers(data: dict, result: ValidationResult) -> None: + """Check 8: Sub-panel trigger_key must reference a key in the same panel.""" + errors: list[str] = [] + + for panel in data.get("panels", []): + pid = panel.get("id", "?") + panel_keys = collect_panel_keys(panel) + + # Check sub_panels at section level + for section in panel.get("sections", []): + for sp in section.get("sub_panels", []): + trigger = sp.get("trigger_key") + if trigger and trigger not in panel_keys: + errors.append( + f"sub_panel '{sp.get('id', '?')}' trigger_key '{trigger}'" + + f" not found in panel '{pid}'" + ) + + # Check top-level sub_panels + for sp in panel.get("sub_panels", []): + trigger = sp.get("trigger_key") + if trigger and trigger not in panel_keys: + errors.append( + f"sub_panel '{sp.get('id', '?')}' trigger_key '{trigger}'" + + f" not found in panel '{pid}'" + ) + + if errors: + result.error("sub-panel triggers", "; ".join(errors)) + else: + result.ok("sub-panel triggers") + + +def check_ordering(data: dict, result: ValidationResult) -> None: + """Check 9: Panel order values must be unique.""" + orders: dict[int, list[str]] = {} + for panel in data.get("panels", []): + order = panel.get("order") + if order is not None: + orders.setdefault(order, []).append(panel.get("id", "?")) + + duplicates = {o: ids for o, ids in orders.items() if len(ids) > 1} + if duplicates: + details = "; ".join(f"order {o}: [{', '.join(ids)}]" for o, ids in duplicates.items()) + result.error("ordering", f"duplicate order values: {details}") + else: + result.ok("ordering") + + +def check_vehicle_brands(data: dict, result: ValidationResult) -> None: + """Check 10: Vehicle settings keys lowercase + each brand has consistent {title, description, items} shape.""" + vehicle = data.get("vehicle_settings", {}) + errors: list[str] = [] + + for brand, brand_data in vehicle.items(): + if not isinstance(brand, str) or brand != brand.lower(): + errors.append(f"non-lowercase brand key: '{brand}'") + if not isinstance(brand_data, dict): + errors.append(f"brand '{brand}': expected object with {{title, description, items}}, got bare list") + continue + if "items" not in brand_data: + errors.append(f"brand '{brand}': missing 'items'") + if "title" not in brand_data: + errors.append(f"brand '{brand}': missing 'title' (use empty string for none)") + + if errors: + result.error("vehicle brands", "; ".join(errors)) + else: + result.ok("vehicle brands") + + +def validate(path: str) -> bool: + """Run all validation checks on the given settings_ui.json file. + + Returns True if all checks pass. + """ + result = ValidationResult() + + # Check 1: JSON parseable + data = check_json_parseable(path, result) + if data is None: + result.summary() + return False + + # Checks 2-10 + check_structural(data, result) + check_item_completeness(data, result) + check_no_duplicate_keys(data, result) + check_rule_wellformedness(data, result) + check_capability_refs(data, result) + check_no_self_reference(data, result) + check_sub_panel_triggers(data, result) + check_ordering(data, result) + check_vehicle_brands(data, result) + + result.summary() + return result.success + + +if __name__ == "__main__": + target = sys.argv[1] if len(sys.argv) > 1 else DEFAULT_PATH + success = validate(target) + sys.exit(0 if success else 1) diff --git a/openpilot/sunnypilot/sunnylink/uploader.py b/openpilot/sunnypilot/sunnylink/uploader.py new file mode 100755 index 0000000000..358e3a88e7 --- /dev/null +++ b/openpilot/sunnypilot/sunnylink/uploader.py @@ -0,0 +1,282 @@ +#!/usr/bin/env python3 +import json +import os +import random +import requests +import threading +import time +import traceback +import datetime +from collections.abc import Iterator + +from openpilot.cereal import log +import openpilot.cereal.messaging as messaging +from openpilot.sunnypilot.sunnylink.api import SunnylinkApi +from openpilot.common.utils import get_upload_stream +from openpilot.common.params import Params +from openpilot.common.realtime import set_core_affinity +from openpilot.common.hardware.hw import Paths +from openpilot.system.loggerd.xattr_cache import getxattr, setxattr +from openpilot.common.swaglog import cloudlog + +NetworkType = log.DeviceState.NetworkType +UPLOAD_ATTR_NAME = 'user.sunny.upload' +UPLOAD_ATTR_VALUE = b'1' + +MAX_UPLOAD_SIZES = { + "qlog": 25*1e6, # can't be too restrictive here since we use qlogs to find + # bugs, including ones that can cause massive log sizes + "qcam": 5*1e6, +} + +allow_sleep = bool(os.getenv("UPLOADER_SLEEP", "1")) +force_wifi = os.getenv("FORCEWIFI") is not None +fake_upload = os.getenv("FAKEUPLOAD") is not None + + +class FakeRequest: + def __init__(self): + self.headers = {"Content-Length": "0"} + + +class FakeResponse: + def __init__(self): + self.status_code = 200 + self.request = FakeRequest() + + +def get_directory_sort(d: str) -> list[str]: + # ensure old format is sorted sooner + o = ["0", ] if d.startswith("2024-") else ["1", ] + return o + [s.rjust(10, '0') for s in d.rsplit('--', 1)] + +def listdir_by_creation(d: str) -> list[str]: + if not os.path.isdir(d): + return [] + + try: + paths = [f for f in os.listdir(d) if os.path.isdir(os.path.join(d, f))] + paths = sorted(paths, key=get_directory_sort) + return paths + except OSError: + cloudlog.exception("listdir_by_creation failed") + return [] + +def clear_locks(root: str) -> None: + for logdir in os.listdir(root): + path = os.path.join(root, logdir) + try: + for fname in os.listdir(path): + if fname.endswith(".lock"): + os.unlink(os.path.join(path, fname)) + except OSError: + cloudlog.exception("clear_locks failed") + + +class Uploader: + def __init__(self, dongle_id: str, root: str): + self.dongle_id = dongle_id + self.api = SunnylinkApi(dongle_id) + self.root = root + + self.params = Params() + + # stats for last successfully uploaded file + self.last_filename = "" + + self.immediate_folders = ["crash/", "boot/"] + self.immediate_priority = {"qlog": 0, "qlog.zst": 0, "qcamera.ts": 1} + + def list_upload_files(self, metered: bool) -> Iterator[tuple[str, str, str]]: + r = self.params.get("AthenadRecentlyViewedRoutes") + requested_routes = [] if r is None else [route for route in r.split(",") if route] + + for logdir in listdir_by_creation(self.root): + path = os.path.join(self.root, logdir) + try: + names = os.listdir(path) + except OSError: + continue + + if any(name.endswith(".lock") for name in names): + continue + + for name in sorted(names, key=lambda n: self.immediate_priority.get(n, 1000)): + key = os.path.join(logdir, name) + fn = os.path.join(path, name) + # skip files already uploaded + try: + ctime = os.path.getctime(fn) + is_uploaded = getxattr(fn, UPLOAD_ATTR_NAME) == UPLOAD_ATTR_VALUE + except OSError: + cloudlog.event("uploader_getxattr_failed", key=key, fn=fn) + # deleter could have deleted, so skip + continue + if is_uploaded: + continue + + # limit uploading on metered connections + if metered: + dt = datetime.timedelta(hours=12) + if logdir in self.immediate_folders and (datetime.datetime.now() - datetime.datetime.fromtimestamp(ctime)) < dt: + continue + + if name == "qcamera.ts" and not any(logdir.startswith(r.split('|')[-1]) for r in requested_routes): + continue + + yield name, key, fn + + def next_file_to_upload(self, metered: bool) -> tuple[str, str, str] | None: + upload_files = list(self.list_upload_files(metered)) + + for name, key, fn in upload_files: + if any(f in fn for f in self.immediate_folders): + return name, key, fn + + for name, key, fn in upload_files: + if name in self.immediate_priority: + return name, key, fn + + return None + + def do_upload(self, key: str, fn: str): + url_resp = self.api.get( + f"device/{self.dongle_id}/upload_url/", + timeout=10, + path=key, + access_token=self.api.get_token(), + ) + if url_resp.status_code == 412: + return url_resp + + url_resp_json = json.loads(url_resp.text) + url = url_resp_json['url'] + headers = url_resp_json['headers'] + cloudlog.debug("sunnylink upload_url %s | Headers: %s", url, headers) + + if fake_upload: + return FakeResponse() + + stream = None + try: + compress = key.endswith('.zst') and not fn.endswith('.zst') + stream, _ = get_upload_stream(fn, compress) + response = requests.put(url, data=stream, headers=headers, timeout=10) + return response + finally: + if stream: + stream.close() + + def upload(self, name: str, key: str, fn: str, network_type: int, metered: bool) -> bool: + try: + sz = os.path.getsize(fn) + except OSError: + cloudlog.exception("upload: getsize failed") + return False + + cloudlog.event("upload_start", key=key, fn=fn, sz=sz, network_type=network_type, metered=metered) + + if sz == 0: + # tag files of 0 size as uploaded + success = True + elif name in MAX_UPLOAD_SIZES and sz > MAX_UPLOAD_SIZES[name]: + cloudlog.event("uploader_too_large", key=key, fn=fn, sz=sz) + success = True + else: + start_time = time.monotonic() + + stat = None + last_exc = None + try: + stat = self.do_upload(key, fn) + except Exception as e: + last_exc = (e, traceback.format_exc()) + + if stat is not None and stat.status_code in (200, 201, 412): + self.last_filename = fn + dt = time.monotonic() - start_time + if stat.status_code == 412: + cloudlog.event("upload_ignored", key=key, fn=fn, sz=sz, network_type=network_type, metered=metered) + else: + content_length = int(stat.request.headers.get("Content-Length", 0)) + speed = (content_length / 1e6) / dt + cloudlog.event("upload_success", key=key, fn=fn, sz=sz, content_length=content_length, + network_type=network_type, metered=metered, speed=speed) + success = True + elif stat is not None: # 401, 403... Not sure why they were up to begin with + success = False + cloudlog.event("upload_failed with content", stat=stat, exc=last_exc, key=key, fn=fn, sz=sz, network_type=network_type, metered=metered, + error=stat.content.decode("utf-8")) + else: + success = False + cloudlog.event("upload_failed", stat=stat, exc=last_exc, key=key, fn=fn, sz=sz, network_type=network_type, metered=metered) + + if success: + # tag file as uploaded + try: + setxattr(fn, UPLOAD_ATTR_NAME, UPLOAD_ATTR_VALUE) + except OSError: + cloudlog.event("uploader_setxattr_failed", exc=last_exc, key=key, fn=fn, sz=sz) + + return success + + + def step(self, network_type: int, metered: bool) -> bool | None: + d = self.next_file_to_upload(metered) + if d is None: + return None + + name, key, fn = d + + # qlogs and bootlogs need to be compressed before uploading + if key.endswith(('qlog', 'rlog')) or (key.startswith('boot/') and not key.endswith('.zst')): + key += ".zst" + + return self.upload(name, key, fn, network_type, metered) + + +def main(exit_event: threading.Event | None = None) -> None: + if exit_event is None: + exit_event = threading.Event() + + try: + set_core_affinity([0, 1, 2, 3]) + except Exception: + cloudlog.exception("failed to set core affinity") + + clear_locks(Paths.log_root()) + + params = Params() + dongle_id = params.get("SunnylinkDongleId") + + if dongle_id is None: + cloudlog.info("uploader missing dongle_id") + raise Exception("uploader can't start without dongle id") + + sm = messaging.SubMaster(['deviceState']) + uploader = Uploader(dongle_id, Paths.log_root()) + + backoff = 0.1 + while not exit_event.is_set(): + sm.update(0) + offroad = params.get_bool("IsOffroad") + network_type = sm['deviceState'].networkType if not force_wifi else NetworkType.wifi + if network_type == NetworkType.none: + if allow_sleep: + time.sleep(60 if offroad else 5) + continue + + success = uploader.step(sm['deviceState'].networkType.raw, sm['deviceState'].networkMetered) + if success is None: + backoff = 60 if offroad else 5 + elif success: + backoff = 0.1 + else: + cloudlog.info("upload backoff %r", backoff) + backoff = min(backoff*2, 120) + if allow_sleep: + time.sleep(backoff + random.uniform(0, backoff)) + + +if __name__ == "__main__": + main() diff --git a/openpilot/sunnypilot/sunnylink/utils.py b/openpilot/sunnypilot/sunnylink/utils.py new file mode 100644 index 0000000000..59b2d15c12 --- /dev/null +++ b/openpilot/sunnypilot/sunnylink/utils.py @@ -0,0 +1,129 @@ +import base64 +import gzip +import json +from openpilot.sunnypilot.sunnylink.api import SunnylinkApi, UNREGISTERED_SUNNYLINK_DONGLE_ID +from openpilot.common.params import Params, ParamKeyType +from openpilot.common.version import is_prebuilt + + +def get_sunnylink_status(params=None) -> tuple[bool, bool, bool]: + """Get the status of Sunnylink on the device. Returns a tuple of (is_sunnylink_enabled, is_registered).""" + params = params or Params() + is_sunnylink_enabled = params.get_bool("SunnylinkEnabled") + is_registered = params.get("SunnylinkDongleId") not in (None, UNREGISTERED_SUNNYLINK_DONGLE_ID) + is_on_temporary_fault = params.get_bool("SunnylinkTempFault") + return is_sunnylink_enabled, is_registered, is_on_temporary_fault + + +def sunnylink_ready(params=None) -> bool: + """Check if the device is ready to communicate with Sunnylink. That means it is enabled and registered.""" + params = params or Params() + is_sunnylink_enabled, is_registered, is_on_temporary_fault = get_sunnylink_status(params) + return is_sunnylink_enabled and is_registered and not is_on_temporary_fault + + +def use_sunnylink_uploader(params) -> bool: + """Check if the device is ready to use Sunnylink and the uploader is enabled.""" + return not params.get_bool("NetworkMetered") and sunnylink_ready(params) and params.get_bool("EnableSunnylinkUploader") + + +def sunnylink_need_register(params=None) -> bool: + """Check if the device needs to be registered with Sunnylink.""" + params = params or Params() + is_sunnylink_enabled, is_registered, is_on_temporary_fault = get_sunnylink_status(params) + return is_sunnylink_enabled and not is_registered and not is_on_temporary_fault + + +def register_sunnylink(): + """Register the device with Sunnylink if it is enabled.""" + extra_args = {} + + if not Params().get_bool("SunnylinkEnabled"): + print("Sunnylink is not enabled. Exiting.") + exit(0) + + if not is_prebuilt(): + extra_args = { + "verbose": True, + "timeout": 60 + } + + try: + sunnylink_id = SunnylinkApi(None).register_device(None, **extra_args) + print(f"SunnyLinkId: {sunnylink_id}") + except Exception: + Params().put_bool("SunnylinkTempFault", True, block=True) + raise + + +def get_api_token(): + """Get the API token for the device.""" + params = Params() + sunnylink_dongle_id = params.get("SunnylinkDongleId") + sunnylink_api = SunnylinkApi(sunnylink_dongle_id) + token = sunnylink_api.get_token() + print(f"API Token: {token}") + + +def get_param_as_byte(param_name: str, params=None, get_default=False) -> bytes | None: + """Get a parameter as bytes. Returns None if the parameter does not exist.""" + params = params or Params() + param = params.get(param_name) if not get_default else params.get_default_value(param_name) + + if param is None: + return None + + param_type = params.get_type(param_name) + return _to_bytes(param, param_type) + + +def _to_bytes(param: bytes, param_type: ParamKeyType) -> bytes | None: + """Convert a parameter value to bytes based on its type.""" + if param_type == ParamKeyType.BYTES: + return bytes(param) + elif param_type == ParamKeyType.JSON: + return json.dumps(param).encode('utf-8') + return str(param).encode('utf-8') + + +def save_param_from_base64_encoded_string(param_name: str, base64_encoded_data: str, is_compressed=False) -> None: + """Save a parameter from bytes. Overwrites the parameter if it already exists.""" + params = Params() + # Find real param name (with correct casing) + param_type = params.get_type(param_name) + value = base64.b64decode(base64_encoded_data) + + if is_compressed: + value = gzip.decompress(value) + + # We convert to string anything that isn't bytes first. We later transform further. + param_value = _convert_param_to_type(value, param_type) + params.put(param_name, param_value, block=True) + + +def _convert_param_to_type(value: bytes, param_type: ParamKeyType) -> bytes | str | int | float | bool | dict | None: + """ + Convert a byte value to the specified param type. Used internally when getting a Param to convert it to the right type. + If this method looks familiar, it's because on SP we have a similar one in openpilot/sunnypilot/car/__init__.py. + """ + + # We convert to string anything that isn't bytes first. We later transform further. + if param_type == ParamKeyType.BYTES: + return value + + decoded = value.decode('utf-8') + + if param_type == ParamKeyType.STRING: + return decoded + elif param_type == ParamKeyType.BOOL: + return decoded.lower() in ('true', '1', 'yes') + elif param_type == ParamKeyType.INT: + return int(decoded) + elif param_type == ParamKeyType.FLOAT: + return float(decoded) + elif param_type == ParamKeyType.TIME: + return str(decoded) + elif param_type == ParamKeyType.JSON: + return json.loads(decoded) + + return decoded diff --git a/system/manager/__init__.py b/openpilot/sunnypilot/system/__init__.py similarity index 100% rename from system/manager/__init__.py rename to openpilot/sunnypilot/system/__init__.py diff --git a/openpilot/sunnypilot/system/params_migration.py b/openpilot/sunnypilot/system/params_migration.py new file mode 100644 index 0000000000..f9d7d1bc43 --- /dev/null +++ b/openpilot/sunnypilot/system/params_migration.py @@ -0,0 +1,82 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import json + +from openpilot.common.swaglog import cloudlog +from openpilot.sunnypilot.selfdrive.car.sync_sunnylink_params import CAR_LIST_JSON_OUT + +ONROAD_BRIGHTNESS_MIGRATION_VERSION: str = "1.0" +ONROAD_BRIGHTNESS_TIMER_MIGRATION_VERSION: str = "1.0" + +# index → seconds mapping for OnroadScreenOffTimer (SSoT) +ONROAD_BRIGHTNESS_TIMER_VALUES = {0: 3, 1: 5, 2: 7, 3: 10, 4: 15, 5: 30, **{i: (i - 5) * 60 for i in range(6, 16)}} +VALID_TIMER_VALUES = set(ONROAD_BRIGHTNESS_TIMER_VALUES.values()) + + +def _migrate_car_platform_bundle(_params): + bundle = _params.get("CarPlatformBundle") + if bundle is None: + return + + old_platform = bundle.get("platform") + if not old_platform: + return + + from opendbc.car.fingerprints import MIGRATION # lazy: avoids heavy import at module level + if old_platform not in MIGRATION: + return + + new_platform = str(MIGRATION[old_platform]) + + with open(CAR_LIST_JSON_OUT) as f: + car_list = json.load(f) + + candidates = [(k, v) for k, v in car_list.items() if v.get("platform") == new_platform] + if candidates: + old_model = bundle.get("model") + key, data = next(((k, v) for k, v in candidates if v.get("model") == old_model), candidates[0]) + bundle = {**data, "name": key} + else: + bundle["platform"] = new_platform + + _params.put("CarPlatformBundle", bundle, block=True) + cloudlog.info(f"params_migration: CarPlatformBundle migrated {old_platform!r} -> {new_platform!r}") + + +def run_migration(_params): + # migrate OnroadScreenOffBrightness + if _params.get("OnroadScreenOffBrightnessMigrated") != ONROAD_BRIGHTNESS_MIGRATION_VERSION: + try: + val = _params.get("OnroadScreenOffBrightness", return_default=True) + if val >= 2: # old: 5%, new: Screen Off + new_val = val + 1 + _params.put("OnroadScreenOffBrightness", new_val, block=True) + log_str = f"Successfully migrated OnroadScreenOffBrightness from {val} to {new_val}." + else: + log_str = "Migration not required for OnroadScreenOffBrightness." + + _params.put("OnroadScreenOffBrightnessMigrated", ONROAD_BRIGHTNESS_MIGRATION_VERSION, block=True) + cloudlog.info(log_str + f" Setting OnroadScreenOffBrightnessMigrated to {ONROAD_BRIGHTNESS_MIGRATION_VERSION}") + except Exception as e: + cloudlog.exception(f"Error migrating OnroadScreenOffBrightness: {e}") + + # migrate OnroadScreenOffTimer + if _params.get("OnroadScreenOffTimerMigrated") != ONROAD_BRIGHTNESS_TIMER_MIGRATION_VERSION: + try: + val = _params.get("OnroadScreenOffTimer", return_default=True) + if val not in VALID_TIMER_VALUES: + _params.put("OnroadScreenOffTimer", 15, block=True) + log_str = f"Successfully migrated OnroadScreenOffTimer from {val} to 15 (default)." + else: + log_str = "Migration not required for OnroadScreenOffTimer." + + _params.put("OnroadScreenOffTimerMigrated", ONROAD_BRIGHTNESS_TIMER_MIGRATION_VERSION, block=True) + cloudlog.info(log_str + f" Setting OnroadScreenOffTimerMigrated to {ONROAD_BRIGHTNESS_TIMER_MIGRATION_VERSION}") + except Exception as e: + cloudlog.exception(f"Error migrating OnroadScreenOffTimer: {e}") + + _migrate_car_platform_bundle(_params) diff --git a/openpilot/sunnypilot/system/sensord/.gitignore b/openpilot/sunnypilot/system/sensord/.gitignore new file mode 100644 index 0000000000..e17675e254 --- /dev/null +++ b/openpilot/sunnypilot/system/sensord/.gitignore @@ -0,0 +1 @@ +sensord diff --git a/openpilot/sunnypilot/system/sensord/SConscript b/openpilot/sunnypilot/system/sensord/SConscript new file mode 100644 index 0000000000..1222f0bfcd --- /dev/null +++ b/openpilot/sunnypilot/system/sensord/SConscript @@ -0,0 +1,13 @@ +Import('env', 'arch', 'common', 'messaging') + +sensors = [ + 'sensors/i2c_sensor.cc', + 'sensors/lsm6ds3_accel.cc', + 'sensors/lsm6ds3_gyro.cc', + 'sensors/lsm6ds3_temp.cc', + 'sensors/mmc5603nj_magn.cc', +] +libs = [common, messaging, 'pthread'] +if arch == "larch64": + libs.append('i2c') +env.Program('sensord', ['sensors_qcom2.cc'] + sensors, LIBS=libs) diff --git a/openpilot/sunnypilot/system/sensord/sensors/bmx055_accel.cc b/openpilot/sunnypilot/system/sensord/sensors/bmx055_accel.cc new file mode 100644 index 0000000000..5db10c3b5b --- /dev/null +++ b/openpilot/sunnypilot/system/sensord/sensors/bmx055_accel.cc @@ -0,0 +1,85 @@ +#include "sunnypilot/system/sensord/sensors/bmx055_accel.h" + +#include + +#include "common/swaglog.h" +#include "common/timing.h" +#include "common/util.h" + +BMX055_Accel::BMX055_Accel(I2CBus *bus) : I2CSensor(bus) {} + +int BMX055_Accel::init() { + int ret = verify_chip_id(BMX055_ACCEL_I2C_REG_ID, {BMX055_ACCEL_CHIP_ID}); + if (ret == -1) { + goto fail; + } + + ret = set_register(BMX055_ACCEL_I2C_REG_PMU, BMX055_ACCEL_NORMAL_MODE); + if (ret < 0) { + goto fail; + } + + // bmx055 accel has a 1.3ms wakeup time from deep suspend mode + util::sleep_for(10); + + // High bandwidth + // ret = set_register(BMX055_ACCEL_I2C_REG_HBW, BMX055_ACCEL_HBW_ENABLE); + // if (ret < 0) { + // goto fail; + // } + + // Low bandwidth + ret = set_register(BMX055_ACCEL_I2C_REG_HBW, BMX055_ACCEL_HBW_DISABLE); + if (ret < 0) { + goto fail; + } + + ret = set_register(BMX055_ACCEL_I2C_REG_BW, BMX055_ACCEL_BW_125HZ); + if (ret < 0) { + goto fail; + } + + enabled = true; + +fail: + return ret; +} + +int BMX055_Accel::shutdown() { + if (!enabled) return 0; + + // enter deep suspend mode (lowest power mode) + int ret = set_register(BMX055_ACCEL_I2C_REG_PMU, BMX055_ACCEL_DEEP_SUSPEND); + if (ret < 0) { + LOGE("Could not move BMX055 ACCEL in deep suspend mode!"); + } + + return ret; +} + +bool BMX055_Accel::get_event(MessageBuilder &msg, uint64_t ts) { + uint64_t start_time = nanos_since_boot(); + uint8_t buffer[6]; + int len = read_register(BMX055_ACCEL_I2C_REG_X_LSB, buffer, sizeof(buffer)); + assert(len == 6); + + // 12 bit = +-2g + float scale = 9.81 * 2.0f / (1 << 11); + float x = -read_12_bit(buffer[0], buffer[1]) * scale; + float y = -read_12_bit(buffer[2], buffer[3]) * scale; + float z = read_12_bit(buffer[4], buffer[5]) * scale; + + auto event = msg.initEvent().initAccelerometer2(); + event.setSource(cereal::SensorEventData::SensorSource::BMX055); + event.setVersion(1); + event.setSensor(SENSOR_ACCELEROMETER); + event.setType(SENSOR_TYPE_ACCELEROMETER); + event.setTimestamp(start_time); + + float xyz[] = {x, y, z}; + auto svec = event.initAcceleration(); + svec.setV(xyz); + svec.setStatus(true); + + return true; +} diff --git a/openpilot/sunnypilot/system/sensord/sensors/bmx055_accel.h b/openpilot/sunnypilot/system/sensord/sensors/bmx055_accel.h new file mode 100644 index 0000000000..4aea163c8b --- /dev/null +++ b/openpilot/sunnypilot/system/sensord/sensors/bmx055_accel.h @@ -0,0 +1,41 @@ +#pragma once + +#include "sunnypilot/system/sensord/sensors/i2c_sensor.h" + +// Address of the chip on the bus +#define BMX055_ACCEL_I2C_ADDR 0x18 + +// Registers of the chip +#define BMX055_ACCEL_I2C_REG_ID 0x00 +#define BMX055_ACCEL_I2C_REG_X_LSB 0x02 +#define BMX055_ACCEL_I2C_REG_TEMP 0x08 +#define BMX055_ACCEL_I2C_REG_BW 0x10 +#define BMX055_ACCEL_I2C_REG_PMU 0x11 +#define BMX055_ACCEL_I2C_REG_HBW 0x13 +#define BMX055_ACCEL_I2C_REG_FIFO 0x3F + +// Constants +#define BMX055_ACCEL_CHIP_ID 0xFA + +#define BMX055_ACCEL_HBW_ENABLE 0b10000000 +#define BMX055_ACCEL_HBW_DISABLE 0b00000000 +#define BMX055_ACCEL_DEEP_SUSPEND 0b00100000 +#define BMX055_ACCEL_NORMAL_MODE 0b00000000 + +#define BMX055_ACCEL_BW_7_81HZ 0b01000 +#define BMX055_ACCEL_BW_15_63HZ 0b01001 +#define BMX055_ACCEL_BW_31_25HZ 0b01010 +#define BMX055_ACCEL_BW_62_5HZ 0b01011 +#define BMX055_ACCEL_BW_125HZ 0b01100 +#define BMX055_ACCEL_BW_250HZ 0b01101 +#define BMX055_ACCEL_BW_500HZ 0b01110 +#define BMX055_ACCEL_BW_1000HZ 0b01111 + +class BMX055_Accel : public I2CSensor { + uint8_t get_device_address() {return BMX055_ACCEL_I2C_ADDR;} +public: + BMX055_Accel(I2CBus *bus); + int init(); + bool get_event(MessageBuilder &msg, uint64_t ts = 0); + int shutdown(); +}; diff --git a/openpilot/sunnypilot/system/sensord/sensors/bmx055_gyro.cc b/openpilot/sunnypilot/system/sensord/sensors/bmx055_gyro.cc new file mode 100644 index 0000000000..4701c70d71 --- /dev/null +++ b/openpilot/sunnypilot/system/sensord/sensors/bmx055_gyro.cc @@ -0,0 +1,92 @@ +#include "sunnypilot/system/sensord/sensors/bmx055_gyro.h" + +#include +#include + +#include "common/swaglog.h" +#include "common/util.h" + +#define DEG2RAD(x) ((x) * M_PI / 180.0) + + +BMX055_Gyro::BMX055_Gyro(I2CBus *bus) : I2CSensor(bus) {} + +int BMX055_Gyro::init() { + int ret = verify_chip_id(BMX055_GYRO_I2C_REG_ID, {BMX055_GYRO_CHIP_ID}); + if (ret == -1) return -1; + + ret = set_register(BMX055_GYRO_I2C_REG_LPM1, BMX055_GYRO_NORMAL_MODE); + if (ret < 0) { + goto fail; + } + // bmx055 gyro has a 30ms wakeup time from deep suspend mode + util::sleep_for(50); + + // High bandwidth + // ret = set_register(BMX055_GYRO_I2C_REG_HBW, BMX055_GYRO_HBW_ENABLE); + // if (ret < 0) { + // goto fail; + // } + + // Low bandwidth + ret = set_register(BMX055_GYRO_I2C_REG_HBW, BMX055_GYRO_HBW_DISABLE); + if (ret < 0) { + goto fail; + } + + // 116 Hz filter + ret = set_register(BMX055_GYRO_I2C_REG_BW, BMX055_GYRO_BW_116HZ); + if (ret < 0) { + goto fail; + } + + // +- 125 deg/s range + ret = set_register(BMX055_GYRO_I2C_REG_RANGE, BMX055_GYRO_RANGE_125); + if (ret < 0) { + goto fail; + } + + enabled = true; + +fail: + return ret; +} + +int BMX055_Gyro::shutdown() { + if (!enabled) return 0; + + // enter deep suspend mode (lowest power mode) + int ret = set_register(BMX055_GYRO_I2C_REG_LPM1, BMX055_GYRO_DEEP_SUSPEND); + if (ret < 0) { + LOGE("Could not move BMX055 GYRO in deep suspend mode!"); + } + + return ret; +} + +bool BMX055_Gyro::get_event(MessageBuilder &msg, uint64_t ts) { + uint64_t start_time = nanos_since_boot(); + uint8_t buffer[6]; + int len = read_register(BMX055_GYRO_I2C_REG_RATE_X_LSB, buffer, sizeof(buffer)); + assert(len == 6); + + // 16 bit = +- 125 deg/s + float scale = 125.0f / (1 << 15); + float x = -DEG2RAD(read_16_bit(buffer[0], buffer[1]) * scale); + float y = -DEG2RAD(read_16_bit(buffer[2], buffer[3]) * scale); + float z = DEG2RAD(read_16_bit(buffer[4], buffer[5]) * scale); + + auto event = msg.initEvent().initGyroscope2(); + event.setSource(cereal::SensorEventData::SensorSource::BMX055); + event.setVersion(1); + event.setSensor(SENSOR_GYRO_UNCALIBRATED); + event.setType(SENSOR_TYPE_GYROSCOPE_UNCALIBRATED); + event.setTimestamp(start_time); + + float xyz[] = {x, y, z}; + auto svec = event.initGyroUncalibrated(); + svec.setV(xyz); + svec.setStatus(true); + + return true; +} diff --git a/openpilot/sunnypilot/system/sensord/sensors/bmx055_gyro.h b/openpilot/sunnypilot/system/sensord/sensors/bmx055_gyro.h new file mode 100644 index 0000000000..489184bb18 --- /dev/null +++ b/openpilot/sunnypilot/system/sensord/sensors/bmx055_gyro.h @@ -0,0 +1,41 @@ +#pragma once + +#include "sunnypilot/system/sensord/sensors/i2c_sensor.h" + +// Address of the chip on the bus +#define BMX055_GYRO_I2C_ADDR 0x68 + +// Registers of the chip +#define BMX055_GYRO_I2C_REG_ID 0x00 +#define BMX055_GYRO_I2C_REG_RATE_X_LSB 0x02 +#define BMX055_GYRO_I2C_REG_RANGE 0x0F +#define BMX055_GYRO_I2C_REG_BW 0x10 +#define BMX055_GYRO_I2C_REG_LPM1 0x11 +#define BMX055_GYRO_I2C_REG_HBW 0x13 +#define BMX055_GYRO_I2C_REG_FIFO 0x3F + +// Constants +#define BMX055_GYRO_CHIP_ID 0x0F + +#define BMX055_GYRO_HBW_ENABLE 0b10000000 +#define BMX055_GYRO_HBW_DISABLE 0b00000000 +#define BMX055_GYRO_DEEP_SUSPEND 0b00100000 +#define BMX055_GYRO_NORMAL_MODE 0b00000000 + +#define BMX055_GYRO_RANGE_2000 0b000 +#define BMX055_GYRO_RANGE_1000 0b001 +#define BMX055_GYRO_RANGE_500 0b010 +#define BMX055_GYRO_RANGE_250 0b011 +#define BMX055_GYRO_RANGE_125 0b100 + +#define BMX055_GYRO_BW_116HZ 0b0010 + + +class BMX055_Gyro : public I2CSensor { + uint8_t get_device_address() {return BMX055_GYRO_I2C_ADDR;} +public: + BMX055_Gyro(I2CBus *bus); + int init(); + bool get_event(MessageBuilder &msg, uint64_t ts = 0); + int shutdown(); +}; diff --git a/openpilot/sunnypilot/system/sensord/sensors/bmx055_magn.cc b/openpilot/sunnypilot/system/sensord/sensors/bmx055_magn.cc new file mode 100644 index 0000000000..00b35aa136 --- /dev/null +++ b/openpilot/sunnypilot/system/sensord/sensors/bmx055_magn.cc @@ -0,0 +1,258 @@ +#include "sunnypilot/system/sensord/sensors/bmx055_magn.h" + +#include + +#include +#include +#include + +#include "common/swaglog.h" +#include "common/util.h" + +static int16_t compensate_x(trim_data_t trim_data, int16_t mag_data_x, uint16_t data_rhall) { + uint16_t process_comp_x0 = data_rhall; + int32_t process_comp_x1 = ((int32_t)trim_data.dig_xyz1) * 16384; + uint16_t process_comp_x2 = ((uint16_t)(process_comp_x1 / process_comp_x0)) - ((uint16_t)0x4000); + int16_t retval = ((int16_t)process_comp_x2); + int32_t process_comp_x3 = (((int32_t)retval) * ((int32_t)retval)); + int32_t process_comp_x4 = (((int32_t)trim_data.dig_xy2) * (process_comp_x3 / 128)); + int32_t process_comp_x5 = (int32_t)(((int16_t)trim_data.dig_xy1) * 128); + int32_t process_comp_x6 = ((int32_t)retval) * process_comp_x5; + int32_t process_comp_x7 = (((process_comp_x4 + process_comp_x6) / 512) + ((int32_t)0x100000)); + int32_t process_comp_x8 = ((int32_t)(((int16_t)trim_data.dig_x2) + ((int16_t)0xA0))); + int32_t process_comp_x9 = ((process_comp_x7 * process_comp_x8) / 4096); + int32_t process_comp_x10 = ((int32_t)mag_data_x) * process_comp_x9; + retval = ((int16_t)(process_comp_x10 / 8192)); + retval = (retval + (((int16_t)trim_data.dig_x1) * 8)) / 16; + + return retval; +} + +static int16_t compensate_y(trim_data_t trim_data, int16_t mag_data_y, uint16_t data_rhall) { + uint16_t process_comp_y0 = trim_data.dig_xyz1; + int32_t process_comp_y1 = (((int32_t)trim_data.dig_xyz1) * 16384) / process_comp_y0; + uint16_t process_comp_y2 = ((uint16_t)process_comp_y1) - ((uint16_t)0x4000); + int16_t retval = ((int16_t)process_comp_y2); + int32_t process_comp_y3 = ((int32_t) retval) * ((int32_t)retval); + int32_t process_comp_y4 = ((int32_t)trim_data.dig_xy2) * (process_comp_y3 / 128); + int32_t process_comp_y5 = ((int32_t)(((int16_t)trim_data.dig_xy1) * 128)); + int32_t process_comp_y6 = ((process_comp_y4 + (((int32_t)retval) * process_comp_y5)) / 512); + int32_t process_comp_y7 = ((int32_t)(((int16_t)trim_data.dig_y2) + ((int16_t)0xA0))); + int32_t process_comp_y8 = (((process_comp_y6 + ((int32_t)0x100000)) * process_comp_y7) / 4096); + int32_t process_comp_y9 = (((int32_t)mag_data_y) * process_comp_y8); + retval = (int16_t)(process_comp_y9 / 8192); + retval = (retval + (((int16_t)trim_data.dig_y1) * 8)) / 16; + + return retval; +} + +static int16_t compensate_z(trim_data_t trim_data, int16_t mag_data_z, uint16_t data_rhall) { + int16_t process_comp_z0 = ((int16_t)data_rhall) - ((int16_t) trim_data.dig_xyz1); + int32_t process_comp_z1 = (((int32_t)trim_data.dig_z3) * ((int32_t)(process_comp_z0))) / 4; + int32_t process_comp_z2 = (((int32_t)(mag_data_z - trim_data.dig_z4)) * 32768); + int32_t process_comp_z3 = ((int32_t)trim_data.dig_z1) * (((int16_t)data_rhall) * 2); + int16_t process_comp_z4 = (int16_t)((process_comp_z3 + (32768)) / 65536); + int32_t retval = ((process_comp_z2 - process_comp_z1) / (trim_data.dig_z2 + process_comp_z4)); + + /* saturate result to +/- 2 micro-tesla */ + retval = std::clamp(retval, -32767, 32767); + + /* Conversion of LSB to micro-tesla*/ + retval = retval / 16; + + return (int16_t)retval; +} + +BMX055_Magn::BMX055_Magn(I2CBus *bus) : I2CSensor(bus) {} + +int BMX055_Magn::init() { + uint8_t trim_x1y1[2] = {0}; + uint8_t trim_x2y2[2] = {0}; + uint8_t trim_xy1xy2[2] = {0}; + uint8_t trim_z1[2] = {0}; + uint8_t trim_z2[2] = {0}; + uint8_t trim_z3[2] = {0}; + uint8_t trim_z4[2] = {0}; + uint8_t trim_xyz1[2] = {0}; + + // suspend -> sleep + int ret = set_register(BMX055_MAGN_I2C_REG_PWR_0, 0x01); + if (ret < 0) { + LOGD("Enabling power failed: %d", ret); + goto fail; + } + util::sleep_for(5); // wait until the chip is powered on + + ret = verify_chip_id(BMX055_MAGN_I2C_REG_ID, {BMX055_MAGN_CHIP_ID}); + if (ret == -1) { + goto fail; + } + + // Load magnetometer trim + ret = read_register(BMX055_MAGN_I2C_REG_DIG_X1, trim_x1y1, 2); + if (ret < 0) goto fail; + ret = read_register(BMX055_MAGN_I2C_REG_DIG_X2, trim_x2y2, 2); + if (ret < 0) goto fail; + ret = read_register(BMX055_MAGN_I2C_REG_DIG_XY2, trim_xy1xy2, 2); + if (ret < 0) goto fail; + ret = read_register(BMX055_MAGN_I2C_REG_DIG_Z1_LSB, trim_z1, 2); + if (ret < 0) goto fail; + ret = read_register(BMX055_MAGN_I2C_REG_DIG_Z2_LSB, trim_z2, 2); + if (ret < 0) goto fail; + ret = read_register(BMX055_MAGN_I2C_REG_DIG_Z3_LSB, trim_z3, 2); + if (ret < 0) goto fail; + ret = read_register(BMX055_MAGN_I2C_REG_DIG_Z4_LSB, trim_z4, 2); + if (ret < 0) goto fail; + ret = read_register(BMX055_MAGN_I2C_REG_DIG_XYZ1_LSB, trim_xyz1, 2); + if (ret < 0) goto fail; + + // Read trim data + trim_data.dig_x1 = trim_x1y1[0]; + trim_data.dig_y1 = trim_x1y1[1]; + + trim_data.dig_x2 = trim_x2y2[0]; + trim_data.dig_y2 = trim_x2y2[1]; + + trim_data.dig_xy1 = trim_xy1xy2[1]; // NB: MSB/LSB swapped + trim_data.dig_xy2 = trim_xy1xy2[0]; + + trim_data.dig_z1 = read_16_bit(trim_z1[0], trim_z1[1]); + trim_data.dig_z2 = read_16_bit(trim_z2[0], trim_z2[1]); + trim_data.dig_z3 = read_16_bit(trim_z3[0], trim_z3[1]); + trim_data.dig_z4 = read_16_bit(trim_z4[0], trim_z4[1]); + + trim_data.dig_xyz1 = read_16_bit(trim_xyz1[0], trim_xyz1[1] & 0x7f); + assert(trim_data.dig_xyz1 != 0); + + perform_self_test(); + + // f_max = 1 / (145us * nXY + 500us * NZ + 980us) + // Chose NXY = 7, NZ = 12, which gives 125 Hz, + // and has the same ratio as the high accuracy preset + ret = set_register(BMX055_MAGN_I2C_REG_REPXY, (7 - 1) / 2); + if (ret < 0) { + goto fail; + } + + ret = set_register(BMX055_MAGN_I2C_REG_REPZ, 12 - 1); + if (ret < 0) { + goto fail; + } + + enabled = true; + return 0; + + fail: + return ret; +} + +int BMX055_Magn::shutdown() { + if (!enabled) return 0; + + // move to suspend mode + int ret = set_register(BMX055_MAGN_I2C_REG_PWR_0, 0); + if (ret < 0) { + LOGE("Could not move BMX055 MAGN in suspend mode!"); + } + + return ret; +} + +bool BMX055_Magn::perform_self_test() { + uint8_t buffer[8]; + int16_t x, y; + int16_t neg_z, pos_z; + + // Increase z reps for less false positives (~30 Hz ODR) + set_register(BMX055_MAGN_I2C_REG_REPXY, 1); + set_register(BMX055_MAGN_I2C_REG_REPZ, 64 - 1); + + // Clean existing measurement + read_register(BMX055_MAGN_I2C_REG_DATAX_LSB, buffer, sizeof(buffer)); + + uint8_t forced = BMX055_MAGN_FORCED; + + // Negative current + set_register(BMX055_MAGN_I2C_REG_MAG, forced | (uint8_t(0b10) << 6)); + util::sleep_for(100); + + read_register(BMX055_MAGN_I2C_REG_DATAX_LSB, buffer, sizeof(buffer)); + parse_xyz(buffer, &x, &y, &neg_z); + + // Positive current + set_register(BMX055_MAGN_I2C_REG_MAG, forced | (uint8_t(0b11) << 6)); + util::sleep_for(100); + + read_register(BMX055_MAGN_I2C_REG_DATAX_LSB, buffer, sizeof(buffer)); + parse_xyz(buffer, &x, &y, &pos_z); + + // Put back in normal mode + set_register(BMX055_MAGN_I2C_REG_MAG, 0); + + int16_t diff = pos_z - neg_z; + bool passed = (diff > 180) && (diff < 240); + + if (!passed) { + LOGE("self test failed: neg %d pos %d diff %d", neg_z, pos_z, diff); + } + + return passed; +} + +bool BMX055_Magn::parse_xyz(uint8_t buffer[8], int16_t *x, int16_t *y, int16_t *z) { + bool ready = buffer[6] & 0x1; + if (ready) { + int16_t mdata_x = (int16_t) (((int16_t)buffer[1] << 8) | buffer[0]) >> 3; + int16_t mdata_y = (int16_t) (((int16_t)buffer[3] << 8) | buffer[2]) >> 3; + int16_t mdata_z = (int16_t) (((int16_t)buffer[5] << 8) | buffer[4]) >> 1; + uint16_t data_r = (uint16_t) (((uint16_t)buffer[7] << 8) | buffer[6]) >> 2; + assert(data_r != 0); + + *x = compensate_x(trim_data, mdata_x, data_r); + *y = compensate_y(trim_data, mdata_y, data_r); + *z = compensate_z(trim_data, mdata_z, data_r); + } + return ready; +} + + +bool BMX055_Magn::get_event(MessageBuilder &msg, uint64_t ts) { + uint64_t start_time = nanos_since_boot(); + uint8_t buffer[8]; + int16_t _x, _y, x, y, z; + + int len = read_register(BMX055_MAGN_I2C_REG_DATAX_LSB, buffer, sizeof(buffer)); + assert(len == sizeof(buffer)); + + bool parsed = parse_xyz(buffer, &_x, &_y, &z); + if (parsed) { + + auto event = msg.initEvent().initMagnetometer(); + event.setSource(cereal::SensorEventData::SensorSource::BMX055); + event.setVersion(2); + event.setSensor(SENSOR_MAGNETOMETER_UNCALIBRATED); + event.setType(SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED); + event.setTimestamp(start_time); + + // Move magnetometer into same reference frame as accel/gryo + x = -_y; + y = _x; + + // Axis convention + x = -x; + y = -y; + + float xyz[] = {(float)x, (float)y, (float)z}; + auto svec = event.initMagneticUncalibrated(); + svec.setV(xyz); + svec.setStatus(true); + } + + // The BMX055 Magnetometer has no FIFO mode. Self running mode only goes + // up to 30 Hz. Therefore we put in forced mode, and request measurements + // at a 100 Hz. When reading the registers we have to check the ready bit + // To verify the measurement was completed this cycle. + set_register(BMX055_MAGN_I2C_REG_MAG, BMX055_MAGN_FORCED); + + return parsed; +} diff --git a/openpilot/sunnypilot/system/sensord/sensors/bmx055_magn.h b/openpilot/sunnypilot/system/sensord/sensors/bmx055_magn.h new file mode 100644 index 0000000000..7b1f7853d0 --- /dev/null +++ b/openpilot/sunnypilot/system/sensord/sensors/bmx055_magn.h @@ -0,0 +1,64 @@ +#pragma once +#include + +#include "sunnypilot/system/sensord/sensors/i2c_sensor.h" + +// Address of the chip on the bus +#define BMX055_MAGN_I2C_ADDR 0x10 + +// Registers of the chip +#define BMX055_MAGN_I2C_REG_ID 0x40 +#define BMX055_MAGN_I2C_REG_PWR_0 0x4B +#define BMX055_MAGN_I2C_REG_MAG 0x4C +#define BMX055_MAGN_I2C_REG_DATAX_LSB 0x42 +#define BMX055_MAGN_I2C_REG_RHALL_LSB 0x48 +#define BMX055_MAGN_I2C_REG_REPXY 0x51 +#define BMX055_MAGN_I2C_REG_REPZ 0x52 + +#define BMX055_MAGN_I2C_REG_DIG_X1 0x5D +#define BMX055_MAGN_I2C_REG_DIG_Y1 0x5E +#define BMX055_MAGN_I2C_REG_DIG_Z4_LSB 0x62 +#define BMX055_MAGN_I2C_REG_DIG_Z4_MSB 0x63 +#define BMX055_MAGN_I2C_REG_DIG_X2 0x64 +#define BMX055_MAGN_I2C_REG_DIG_Y2 0x65 +#define BMX055_MAGN_I2C_REG_DIG_Z2_LSB 0x68 +#define BMX055_MAGN_I2C_REG_DIG_Z2_MSB 0x69 +#define BMX055_MAGN_I2C_REG_DIG_Z1_LSB 0x6A +#define BMX055_MAGN_I2C_REG_DIG_Z1_MSB 0x6B +#define BMX055_MAGN_I2C_REG_DIG_XYZ1_LSB 0x6C +#define BMX055_MAGN_I2C_REG_DIG_XYZ1_MSB 0x6D +#define BMX055_MAGN_I2C_REG_DIG_Z3_LSB 0x6E +#define BMX055_MAGN_I2C_REG_DIG_Z3_MSB 0x6F +#define BMX055_MAGN_I2C_REG_DIG_XY2 0x70 +#define BMX055_MAGN_I2C_REG_DIG_XY1 0x71 + +// Constants +#define BMX055_MAGN_CHIP_ID 0x32 +#define BMX055_MAGN_FORCED (0b01 << 1) + +struct trim_data_t { + int8_t dig_x1; + int8_t dig_y1; + int8_t dig_x2; + int8_t dig_y2; + uint16_t dig_z1; + int16_t dig_z2; + int16_t dig_z3; + int16_t dig_z4; + uint8_t dig_xy1; + int8_t dig_xy2; + uint16_t dig_xyz1; +}; + + +class BMX055_Magn : public I2CSensor{ + uint8_t get_device_address() {return BMX055_MAGN_I2C_ADDR;} + trim_data_t trim_data = {0}; + bool perform_self_test(); + bool parse_xyz(uint8_t buffer[8], int16_t *x, int16_t *y, int16_t *z); +public: + BMX055_Magn(I2CBus *bus); + int init(); + bool get_event(MessageBuilder &msg, uint64_t ts = 0); + int shutdown(); +}; diff --git a/openpilot/sunnypilot/system/sensord/sensors/bmx055_temp.cc b/openpilot/sunnypilot/system/sensord/sensors/bmx055_temp.cc new file mode 100644 index 0000000000..3932c66fa6 --- /dev/null +++ b/openpilot/sunnypilot/system/sensord/sensors/bmx055_temp.cc @@ -0,0 +1,31 @@ +#include "sunnypilot/system/sensord/sensors/bmx055_temp.h" + +#include + +#include "sunnypilot/system/sensord/sensors/bmx055_accel.h" +#include "common/swaglog.h" +#include "common/timing.h" + +BMX055_Temp::BMX055_Temp(I2CBus *bus) : I2CSensor(bus) {} + +int BMX055_Temp::init() { + return verify_chip_id(BMX055_ACCEL_I2C_REG_ID, {BMX055_ACCEL_CHIP_ID}) == -1 ? -1 : 0; +} + +bool BMX055_Temp::get_event(MessageBuilder &msg, uint64_t ts) { + uint64_t start_time = nanos_since_boot(); + uint8_t buffer[1]; + int len = read_register(BMX055_ACCEL_I2C_REG_TEMP, buffer, sizeof(buffer)); + assert(len == sizeof(buffer)); + + float temp = 23.0f + int8_t(buffer[0]) / 2.0f; + + auto event = msg.initEvent().initTemperatureSensor(); + event.setSource(cereal::SensorEventData::SensorSource::BMX055); + event.setVersion(1); + event.setType(SENSOR_TYPE_AMBIENT_TEMPERATURE); + event.setTimestamp(start_time); + event.setTemperature(temp); + + return true; +} diff --git a/openpilot/sunnypilot/system/sensord/sensors/bmx055_temp.h b/openpilot/sunnypilot/system/sensord/sensors/bmx055_temp.h new file mode 100644 index 0000000000..02c48dc92c --- /dev/null +++ b/openpilot/sunnypilot/system/sensord/sensors/bmx055_temp.h @@ -0,0 +1,13 @@ +#pragma once + +#include "sunnypilot/system/sensord/sensors/bmx055_accel.h" +#include "sunnypilot/system/sensord/sensors/i2c_sensor.h" + +class BMX055_Temp : public I2CSensor { + uint8_t get_device_address() {return BMX055_ACCEL_I2C_ADDR;} +public: + BMX055_Temp(I2CBus *bus); + int init(); + bool get_event(MessageBuilder &msg, uint64_t ts = 0); + int shutdown() { return 0; } +}; diff --git a/openpilot/sunnypilot/system/sensord/sensors/constants.h b/openpilot/sunnypilot/system/sensord/sensors/constants.h new file mode 100644 index 0000000000..c216f838a5 --- /dev/null +++ b/openpilot/sunnypilot/system/sensord/sensors/constants.h @@ -0,0 +1,18 @@ +#pragma once + + +#define SENSOR_ACCELEROMETER 1 +#define SENSOR_MAGNETOMETER 2 +#define SENSOR_MAGNETOMETER_UNCALIBRATED 3 +#define SENSOR_GYRO 4 +#define SENSOR_GYRO_UNCALIBRATED 5 +#define SENSOR_LIGHT 7 + +#define SENSOR_TYPE_ACCELEROMETER 1 +#define SENSOR_TYPE_GEOMAGNETIC_FIELD 2 +#define SENSOR_TYPE_GYROSCOPE 4 +#define SENSOR_TYPE_LIGHT 5 +#define SENSOR_TYPE_AMBIENT_TEMPERATURE 13 +#define SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED 14 +#define SENSOR_TYPE_MAGNETIC_FIELD SENSOR_TYPE_GEOMAGNETIC_FIELD +#define SENSOR_TYPE_GYROSCOPE_UNCALIBRATED 16 diff --git a/openpilot/sunnypilot/system/sensord/sensors/i2c_sensor.cc b/openpilot/sunnypilot/system/sensord/sensors/i2c_sensor.cc new file mode 100644 index 0000000000..e29f98c721 --- /dev/null +++ b/openpilot/sunnypilot/system/sensord/sensors/i2c_sensor.cc @@ -0,0 +1,50 @@ +#include "sunnypilot/system/sensord/sensors/i2c_sensor.h" + +int16_t read_12_bit(uint8_t lsb, uint8_t msb) { + uint16_t combined = (uint16_t(msb) << 8) | uint16_t(lsb & 0xF0); + return int16_t(combined) / (1 << 4); +} + +int16_t read_16_bit(uint8_t lsb, uint8_t msb) { + uint16_t combined = (uint16_t(msb) << 8) | uint16_t(lsb); + return int16_t(combined); +} + +int32_t read_20_bit(uint8_t b2, uint8_t b1, uint8_t b0) { + uint32_t combined = (uint32_t(b0) << 16) | (uint32_t(b1) << 8) | uint32_t(b2); + return int32_t(combined) / (1 << 4); +} + +I2CSensor::I2CSensor(I2CBus *bus, int gpio_nr, bool shared_gpio) : + bus(bus), gpio_nr(gpio_nr), shared_gpio(shared_gpio) {} + +I2CSensor::~I2CSensor() { + if (gpio_fd != -1) { + close(gpio_fd); + } +} + +int I2CSensor::read_register(uint register_address, uint8_t *buffer, uint8_t len) { + return bus->read_register(get_device_address(), register_address, buffer, len); +} + +int I2CSensor::set_register(uint register_address, uint8_t data) { + return bus->set_register(get_device_address(), register_address, data); +} + +int I2CSensor::init_gpio() { + if (shared_gpio || gpio_nr == 0) { + return 0; + } + + gpio_fd = gpiochip_get_ro_value_fd("sensord", GPIOCHIP_INT, gpio_nr); + if (gpio_fd < 0) { + return -1; + } + + return 0; +} + +bool I2CSensor::has_interrupt_enabled() { + return gpio_nr != 0; +} diff --git a/openpilot/sunnypilot/system/sensord/sensors/i2c_sensor.h b/openpilot/sunnypilot/system/sensord/sensors/i2c_sensor.h new file mode 100644 index 0000000000..6513db7934 --- /dev/null +++ b/openpilot/sunnypilot/system/sensord/sensors/i2c_sensor.h @@ -0,0 +1,51 @@ +#pragma once + +#include +#include +#include +#include "cereal/gen/cpp/log.capnp.h" + +#include "common/i2c.h" +#include "common/gpio.h" + +#include "common/swaglog.h" +#include "sunnypilot/system/sensord/sensors/constants.h" +#include "sunnypilot/system/sensord/sensors/sensor.h" + +int16_t read_12_bit(uint8_t lsb, uint8_t msb); +int16_t read_16_bit(uint8_t lsb, uint8_t msb); +int32_t read_20_bit(uint8_t b2, uint8_t b1, uint8_t b0); + + +class I2CSensor : public Sensor { +private: + I2CBus *bus; + int gpio_nr; + bool shared_gpio; + virtual uint8_t get_device_address() = 0; + +public: + I2CSensor(I2CBus *bus, int gpio_nr = 0, bool shared_gpio = false); + ~I2CSensor(); + int read_register(uint register_address, uint8_t *buffer, uint8_t len); + int set_register(uint register_address, uint8_t data); + int init_gpio(); + bool has_interrupt_enabled(); + virtual int init() = 0; + virtual bool get_event(MessageBuilder &msg, uint64_t ts = 0) = 0; + virtual int shutdown() = 0; + + int verify_chip_id(uint8_t address, const std::vector &expected_ids) { + uint8_t chip_id = 0; + int ret = read_register(address, &chip_id, 1); + if (ret < 0) { + LOGD("Reading chip ID failed: %d", ret); + return -1; + } + for (int i = 0; i < expected_ids.size(); ++i) { + if (chip_id == expected_ids[i]) return chip_id; + } + LOGE("Chip ID wrong. Got: %d, Expected %d", chip_id, expected_ids[0]); + return -1; + } +}; diff --git a/openpilot/sunnypilot/system/sensord/sensors/lsm6ds3_accel.cc b/openpilot/sunnypilot/system/sensord/sensors/lsm6ds3_accel.cc new file mode 100644 index 0000000000..2857106944 --- /dev/null +++ b/openpilot/sunnypilot/system/sensord/sensors/lsm6ds3_accel.cc @@ -0,0 +1,250 @@ +#include "sunnypilot/system/sensord/sensors/lsm6ds3_accel.h" + +#include +#include +#include + +#include "common/swaglog.h" +#include "common/timing.h" +#include "common/util.h" + +LSM6DS3_Accel::LSM6DS3_Accel(I2CBus *bus, int gpio_nr, bool shared_gpio) : + I2CSensor(bus, gpio_nr, shared_gpio) {} + +void LSM6DS3_Accel::wait_for_data_ready() { + uint8_t drdy = 0; + uint8_t buffer[6]; + + do { + read_register(LSM6DS3_ACCEL_I2C_REG_STAT_REG, &drdy, sizeof(drdy)); + drdy &= LSM6DS3_ACCEL_DRDY_XLDA; + } while (drdy == 0); + + read_register(LSM6DS3_ACCEL_I2C_REG_OUTX_L_XL, buffer, sizeof(buffer)); +} + +void LSM6DS3_Accel::read_and_avg_data(float* out_buf) { + uint8_t drdy = 0; + uint8_t buffer[6]; + + float scaling = 0.061f; + if (source == cereal::SensorEventData::SensorSource::LSM6DS3TRC) { + scaling = 0.122f; + } + + for (int i = 0; i < 5; i++) { + do { + read_register(LSM6DS3_ACCEL_I2C_REG_STAT_REG, &drdy, sizeof(drdy)); + drdy &= LSM6DS3_ACCEL_DRDY_XLDA; + } while (drdy == 0); + + int len = read_register(LSM6DS3_ACCEL_I2C_REG_OUTX_L_XL, buffer, sizeof(buffer)); + assert(len == sizeof(buffer)); + + for (int j = 0; j < 3; j++) { + out_buf[j] += (float)read_16_bit(buffer[j*2], buffer[j*2+1]) * scaling; + } + } + + for (int i = 0; i < 3; i++) { + out_buf[i] /= 5.0f; + } +} + +int LSM6DS3_Accel::self_test(int test_type) { + float val_st_off[3] = {0}; + float val_st_on[3] = {0}; + float test_val[3] = {0}; + uint8_t ODR_FS_MO = LSM6DS3_ACCEL_ODR_52HZ; // full scale: +-2g, ODR: 52Hz + + // prepare sensor for self-test + + // enable block data update and automatic increment + int ret = set_register(LSM6DS3_ACCEL_I2C_REG_CTRL3_C, LSM6DS3_ACCEL_IF_INC_BDU); + if (ret < 0) { + return ret; + } + + if (source == cereal::SensorEventData::SensorSource::LSM6DS3TRC) { + ODR_FS_MO = LSM6DS3_ACCEL_FS_4G | LSM6DS3_ACCEL_ODR_52HZ; + } + ret = set_register(LSM6DS3_ACCEL_I2C_REG_CTRL1_XL, ODR_FS_MO); + if (ret < 0) { + return ret; + } + + // wait for stable output, and discard first values + util::sleep_for(100); + wait_for_data_ready(); + read_and_avg_data(val_st_off); + + // enable Self Test positive (or negative) + ret = set_register(LSM6DS3_ACCEL_I2C_REG_CTRL5_C, test_type); + if (ret < 0) { + return ret; + } + + // wait for stable output, and discard first values + util::sleep_for(100); + wait_for_data_ready(); + read_and_avg_data(val_st_on); + + // disable sensor + ret = set_register(LSM6DS3_ACCEL_I2C_REG_CTRL1_XL, 0); + if (ret < 0) { + return ret; + } + + // disable self test + ret = set_register(LSM6DS3_ACCEL_I2C_REG_CTRL5_C, 0); + if (ret < 0) { + return ret; + } + + // calculate the mg values for self test + for (int i = 0; i < 3; i++) { + test_val[i] = fabs(val_st_on[i] - val_st_off[i]); + } + + // verify test result + for (int i = 0; i < 3; i++) { + if ((LSM6DS3_ACCEL_MIN_ST_LIMIT_mg > test_val[i]) || + (test_val[i] > LSM6DS3_ACCEL_MAX_ST_LIMIT_mg)) { + return -1; + } + } + + return ret; +} + +int LSM6DS3_Accel::init() { + uint8_t value = 0; + bool do_self_test = false; + + const char* env_lsm_selftest = std::getenv("LSM_SELF_TEST"); + if (env_lsm_selftest != nullptr && strncmp(env_lsm_selftest, "1", 1) == 0) { + do_self_test = true; + } + + int ret = verify_chip_id(LSM6DS3_ACCEL_I2C_REG_ID, {LSM6DS3_ACCEL_CHIP_ID, LSM6DS3TRC_ACCEL_CHIP_ID}); + if (ret == -1) return -1; + + if (ret == LSM6DS3TRC_ACCEL_CHIP_ID) { + source = cereal::SensorEventData::SensorSource::LSM6DS3TRC; + } + + ret = self_test(LSM6DS3_ACCEL_POSITIVE_TEST); + if (ret < 0) { + LOGE("LSM6DS3 accel positive self-test failed!"); + if (do_self_test) goto fail; + } + + ret = self_test(LSM6DS3_ACCEL_NEGATIVE_TEST); + if (ret < 0) { + LOGE("LSM6DS3 accel negative self-test failed!"); + if (do_self_test) goto fail; + } + + ret = init_gpio(); + if (ret < 0) { + goto fail; + } + + // enable continuous update, and automatic increase + ret = set_register(LSM6DS3_ACCEL_I2C_REG_CTRL3_C, LSM6DS3_ACCEL_IF_INC); + if (ret < 0) { + goto fail; + } + + // TODO: set scale and bandwidth. Default is +- 2G, 50 Hz + ret = set_register(LSM6DS3_ACCEL_I2C_REG_CTRL1_XL, LSM6DS3_ACCEL_ODR_104HZ); + if (ret < 0) { + goto fail; + } + + ret = set_register(LSM6DS3_ACCEL_I2C_REG_DRDY_CFG, LSM6DS3_ACCEL_DRDY_PULSE_MODE); + if (ret < 0) { + goto fail; + } + + // enable data ready interrupt for accel on INT1 + // (without resetting existing interrupts) + ret = read_register(LSM6DS3_ACCEL_I2C_REG_INT1_CTRL, &value, 1); + if (ret < 0) { + goto fail; + } + + value |= LSM6DS3_ACCEL_INT1_DRDY_XL; + ret = set_register(LSM6DS3_ACCEL_I2C_REG_INT1_CTRL, value); + +fail: + return ret; +} + +int LSM6DS3_Accel::shutdown() { + int ret = 0; + + // disable data ready interrupt for accel on INT1 + uint8_t value = 0; + ret = read_register(LSM6DS3_ACCEL_I2C_REG_INT1_CTRL, &value, 1); + if (ret < 0) { + goto fail; + } + + value &= ~(LSM6DS3_ACCEL_INT1_DRDY_XL); + ret = set_register(LSM6DS3_ACCEL_I2C_REG_INT1_CTRL, value); + if (ret < 0) { + LOGE("Could not disable lsm6ds3 acceleration interrupt!"); + goto fail; + } + + // enable power-down mode + value = 0; + ret = read_register(LSM6DS3_ACCEL_I2C_REG_CTRL1_XL, &value, 1); + if (ret < 0) { + goto fail; + } + + value &= 0x0F; + ret = set_register(LSM6DS3_ACCEL_I2C_REG_CTRL1_XL, value); + if (ret < 0) { + LOGE("Could not power-down lsm6ds3 accelerometer!"); + goto fail; + } + +fail: + return ret; +} + +bool LSM6DS3_Accel::get_event(MessageBuilder &msg, uint64_t ts) { + + // INT1 shared with gyro, check STATUS_REG who triggered + uint8_t status_reg = 0; + read_register(LSM6DS3_ACCEL_I2C_REG_STAT_REG, &status_reg, sizeof(status_reg)); + if ((status_reg & LSM6DS3_ACCEL_DRDY_XLDA) == 0) { + return false; + } + + uint8_t buffer[6]; + int len = read_register(LSM6DS3_ACCEL_I2C_REG_OUTX_L_XL, buffer, sizeof(buffer)); + assert(len == sizeof(buffer)); + + float scale = 9.81 * 2.0f / (1 << 15); + float x = read_16_bit(buffer[0], buffer[1]) * scale; + float y = read_16_bit(buffer[2], buffer[3]) * scale; + float z = read_16_bit(buffer[4], buffer[5]) * scale; + + auto event = msg.initEvent().initAccelerometer(); + event.setSource(source); + event.setVersion(1); + event.setSensor(SENSOR_ACCELEROMETER); + event.setType(SENSOR_TYPE_ACCELEROMETER); + event.setTimestamp(ts); + + float xyz[] = {y, -x, z}; + auto svec = event.initAcceleration(); + svec.setV(xyz); + svec.setStatus(true); + + return true; +} diff --git a/openpilot/sunnypilot/system/sensord/sensors/lsm6ds3_accel.h b/openpilot/sunnypilot/system/sensord/sensors/lsm6ds3_accel.h new file mode 100644 index 0000000000..2ac61c5a0f --- /dev/null +++ b/openpilot/sunnypilot/system/sensord/sensors/lsm6ds3_accel.h @@ -0,0 +1,49 @@ +#pragma once + +#include "sunnypilot/system/sensord/sensors/i2c_sensor.h" + +// Address of the chip on the bus +#define LSM6DS3_ACCEL_I2C_ADDR 0x6A + +// Registers of the chip +#define LSM6DS3_ACCEL_I2C_REG_DRDY_CFG 0x0B +#define LSM6DS3_ACCEL_I2C_REG_ID 0x0F +#define LSM6DS3_ACCEL_I2C_REG_INT1_CTRL 0x0D +#define LSM6DS3_ACCEL_I2C_REG_CTRL1_XL 0x10 +#define LSM6DS3_ACCEL_I2C_REG_CTRL3_C 0x12 +#define LSM6DS3_ACCEL_I2C_REG_CTRL5_C 0x14 +#define LSM6DS3_ACCEL_I2C_REG_CTR9_XL 0x18 +#define LSM6DS3_ACCEL_I2C_REG_STAT_REG 0x1E +#define LSM6DS3_ACCEL_I2C_REG_OUTX_L_XL 0x28 + +// Constants +#define LSM6DS3_ACCEL_CHIP_ID 0x69 +#define LSM6DS3TRC_ACCEL_CHIP_ID 0x6A +#define LSM6DS3_ACCEL_FS_4G (0b10 << 2) +#define LSM6DS3_ACCEL_ODR_52HZ (0b0011 << 4) +#define LSM6DS3_ACCEL_ODR_104HZ (0b0100 << 4) +#define LSM6DS3_ACCEL_INT1_DRDY_XL 0b1 +#define LSM6DS3_ACCEL_DRDY_XLDA 0b1 +#define LSM6DS3_ACCEL_DRDY_PULSE_MODE (1 << 7) +#define LSM6DS3_ACCEL_IF_INC 0b00000100 +#define LSM6DS3_ACCEL_IF_INC_BDU 0b01000100 +#define LSM6DS3_ACCEL_XYZ_DEN 0b11100000 +#define LSM6DS3_ACCEL_POSITIVE_TEST 0b01 +#define LSM6DS3_ACCEL_NEGATIVE_TEST 0b10 +#define LSM6DS3_ACCEL_MIN_ST_LIMIT_mg 90.0f +#define LSM6DS3_ACCEL_MAX_ST_LIMIT_mg 1700.0f + +class LSM6DS3_Accel : public I2CSensor { + uint8_t get_device_address() {return LSM6DS3_ACCEL_I2C_ADDR;} + cereal::SensorEventData::SensorSource source = cereal::SensorEventData::SensorSource::LSM6DS3; + + // self test functions + int self_test(int test_type); + void wait_for_data_ready(); + void read_and_avg_data(float* val_st_off); +public: + LSM6DS3_Accel(I2CBus *bus, int gpio_nr = 0, bool shared_gpio = false); + int init(); + bool get_event(MessageBuilder &msg, uint64_t ts = 0); + int shutdown(); +}; diff --git a/openpilot/sunnypilot/system/sensord/sensors/lsm6ds3_gyro.cc b/openpilot/sunnypilot/system/sensord/sensors/lsm6ds3_gyro.cc new file mode 100644 index 0000000000..e881f3942a --- /dev/null +++ b/openpilot/sunnypilot/system/sensord/sensors/lsm6ds3_gyro.cc @@ -0,0 +1,233 @@ +#include "sunnypilot/system/sensord/sensors/lsm6ds3_gyro.h" + +#include +#include +#include + +#include "common/swaglog.h" +#include "common/timing.h" +#include "common/util.h" + +#define DEG2RAD(x) ((x) * M_PI / 180.0) + +LSM6DS3_Gyro::LSM6DS3_Gyro(I2CBus *bus, int gpio_nr, bool shared_gpio) : + I2CSensor(bus, gpio_nr, shared_gpio) {} + +void LSM6DS3_Gyro::wait_for_data_ready() { + uint8_t drdy = 0; + uint8_t buffer[6]; + + do { + read_register(LSM6DS3_GYRO_I2C_REG_STAT_REG, &drdy, sizeof(drdy)); + drdy &= LSM6DS3_GYRO_DRDY_GDA; + } while (drdy == 0); + + read_register(LSM6DS3_GYRO_I2C_REG_OUTX_L_G, buffer, sizeof(buffer)); +} + +void LSM6DS3_Gyro::read_and_avg_data(float* out_buf) { + uint8_t drdy = 0; + uint8_t buffer[6]; + + for (int i = 0; i < 5; i++) { + do { + read_register(LSM6DS3_GYRO_I2C_REG_STAT_REG, &drdy, sizeof(drdy)); + drdy &= LSM6DS3_GYRO_DRDY_GDA; + } while (drdy == 0); + + int len = read_register(LSM6DS3_GYRO_I2C_REG_OUTX_L_G, buffer, sizeof(buffer)); + assert(len == sizeof(buffer)); + + for (int j = 0; j < 3; j++) { + out_buf[j] += (float)read_16_bit(buffer[j*2], buffer[j*2+1]) * 70.0f; + } + } + + // calculate the mg average values + for (int i = 0; i < 3; i++) { + out_buf[i] /= 5.0f; + } +} + +int LSM6DS3_Gyro::self_test(int test_type) { + float val_st_off[3] = {0}; + float val_st_on[3] = {0}; + float test_val[3] = {0}; + + // prepare sensor for self-test + + // full scale: 2000dps, ODR: 208Hz + int ret = set_register(LSM6DS3_GYRO_I2C_REG_CTRL2_G, LSM6DS3_GYRO_ODR_208HZ | LSM6DS3_GYRO_FS_2000dps); + if (ret < 0) { + return ret; + } + + // wait for stable output, and discard first values + util::sleep_for(150); + wait_for_data_ready(); + read_and_avg_data(val_st_off); + + // enable Self Test positive (or negative) + ret = set_register(LSM6DS3_GYRO_I2C_REG_CTRL5_C, test_type); + if (ret < 0) { + return ret; + } + + // wait for stable output, and discard first values + util::sleep_for(50); + wait_for_data_ready(); + read_and_avg_data(val_st_on); + + // disable sensor + ret = set_register(LSM6DS3_GYRO_I2C_REG_CTRL2_G, 0); + if (ret < 0) { + return ret; + } + + // disable self test + ret = set_register(LSM6DS3_GYRO_I2C_REG_CTRL5_C, 0); + if (ret < 0) { + return ret; + } + + // calculate the mg values for self test + for (int i = 0; i < 3; i++) { + test_val[i] = fabs(val_st_on[i] - val_st_off[i]); + } + + // verify test result + for (int i = 0; i < 3; i++) { + if ((LSM6DS3_GYRO_MIN_ST_LIMIT_mdps > test_val[i]) || + (test_val[i] > LSM6DS3_GYRO_MAX_ST_LIMIT_mdps)) { + return -1; + } + } + + return ret; +} + +int LSM6DS3_Gyro::init() { + uint8_t value = 0; + bool do_self_test = false; + + const char* env_lsm_selftest = std::getenv("LSM_SELF_TEST"); + if (env_lsm_selftest != nullptr && strncmp(env_lsm_selftest, "1", 1) == 0) { + do_self_test = true; + } + + int ret = verify_chip_id(LSM6DS3_GYRO_I2C_REG_ID, {LSM6DS3_GYRO_CHIP_ID, LSM6DS3TRC_GYRO_CHIP_ID}); + if (ret == -1) return -1; + + if (ret == LSM6DS3TRC_GYRO_CHIP_ID) { + source = cereal::SensorEventData::SensorSource::LSM6DS3TRC; + } + + ret = init_gpio(); + if (ret < 0) { + goto fail; + } + + ret = self_test(LSM6DS3_GYRO_POSITIVE_TEST); + if (ret < 0) { + LOGE("LSM6DS3 gyro positive self-test failed!"); + if (do_self_test) goto fail; + } + + ret = self_test(LSM6DS3_GYRO_NEGATIVE_TEST); + if (ret < 0) { + LOGE("LSM6DS3 gyro negative self-test failed!"); + if (do_self_test) goto fail; + } + + // TODO: set scale. Default is +- 250 deg/s + ret = set_register(LSM6DS3_GYRO_I2C_REG_CTRL2_G, LSM6DS3_GYRO_ODR_104HZ); + if (ret < 0) { + goto fail; + } + + ret = set_register(LSM6DS3_GYRO_I2C_REG_DRDY_CFG, LSM6DS3_GYRO_DRDY_PULSE_MODE); + if (ret < 0) { + goto fail; + } + + // enable data ready interrupt for gyro on INT1 + // (without resetting existing interrupts) + ret = read_register(LSM6DS3_GYRO_I2C_REG_INT1_CTRL, &value, 1); + if (ret < 0) { + goto fail; + } + + value |= LSM6DS3_GYRO_INT1_DRDY_G; + ret = set_register(LSM6DS3_GYRO_I2C_REG_INT1_CTRL, value); + +fail: + return ret; +} + +int LSM6DS3_Gyro::shutdown() { + int ret = 0; + + // disable data ready interrupt for gyro on INT1 + uint8_t value = 0; + ret = read_register(LSM6DS3_GYRO_I2C_REG_INT1_CTRL, &value, 1); + if (ret < 0) { + goto fail; + } + + value &= ~(LSM6DS3_GYRO_INT1_DRDY_G); + ret = set_register(LSM6DS3_GYRO_I2C_REG_INT1_CTRL, value); + if (ret < 0) { + LOGE("Could not disable lsm6ds3 gyroscope interrupt!"); + goto fail; + } + + // enable power-down mode + value = 0; + ret = read_register(LSM6DS3_GYRO_I2C_REG_CTRL2_G, &value, 1); + if (ret < 0) { + goto fail; + } + + value &= 0x0F; + ret = set_register(LSM6DS3_GYRO_I2C_REG_CTRL2_G, value); + if (ret < 0) { + LOGE("Could not power-down lsm6ds3 gyroscope!"); + goto fail; + } + +fail: + return ret; +} + +bool LSM6DS3_Gyro::get_event(MessageBuilder &msg, uint64_t ts) { + + // INT1 shared with accel, check STATUS_REG who triggered + uint8_t status_reg = 0; + read_register(LSM6DS3_GYRO_I2C_REG_STAT_REG, &status_reg, sizeof(status_reg)); + if ((status_reg & LSM6DS3_GYRO_DRDY_GDA) == 0) { + return false; + } + + uint8_t buffer[6]; + int len = read_register(LSM6DS3_GYRO_I2C_REG_OUTX_L_G, buffer, sizeof(buffer)); + assert(len == sizeof(buffer)); + + float scale = 8.75 / 1000.0; + float x = DEG2RAD(read_16_bit(buffer[0], buffer[1]) * scale); + float y = DEG2RAD(read_16_bit(buffer[2], buffer[3]) * scale); + float z = DEG2RAD(read_16_bit(buffer[4], buffer[5]) * scale); + + auto event = msg.initEvent().initGyroscope(); + event.setSource(source); + event.setVersion(2); + event.setSensor(SENSOR_GYRO_UNCALIBRATED); + event.setType(SENSOR_TYPE_GYROSCOPE_UNCALIBRATED); + event.setTimestamp(ts); + + float xyz[] = {y, -x, z}; + auto svec = event.initGyroUncalibrated(); + svec.setV(xyz); + svec.setStatus(true); + + return true; +} diff --git a/openpilot/sunnypilot/system/sensord/sensors/lsm6ds3_gyro.h b/openpilot/sunnypilot/system/sensord/sensors/lsm6ds3_gyro.h new file mode 100644 index 0000000000..686a6a7169 --- /dev/null +++ b/openpilot/sunnypilot/system/sensord/sensors/lsm6ds3_gyro.h @@ -0,0 +1,45 @@ +#pragma once + +#include "sunnypilot/system/sensord/sensors/i2c_sensor.h" + +// Address of the chip on the bus +#define LSM6DS3_GYRO_I2C_ADDR 0x6A + +// Registers of the chip +#define LSM6DS3_GYRO_I2C_REG_DRDY_CFG 0x0B +#define LSM6DS3_GYRO_I2C_REG_ID 0x0F +#define LSM6DS3_GYRO_I2C_REG_INT1_CTRL 0x0D +#define LSM6DS3_GYRO_I2C_REG_CTRL2_G 0x11 +#define LSM6DS3_GYRO_I2C_REG_CTRL5_C 0x14 +#define LSM6DS3_GYRO_I2C_REG_STAT_REG 0x1E +#define LSM6DS3_GYRO_I2C_REG_OUTX_L_G 0x22 +#define LSM6DS3_GYRO_POSITIVE_TEST (0b01 << 2) +#define LSM6DS3_GYRO_NEGATIVE_TEST (0b11 << 2) + +// Constants +#define LSM6DS3_GYRO_CHIP_ID 0x69 +#define LSM6DS3TRC_GYRO_CHIP_ID 0x6A +#define LSM6DS3_GYRO_FS_2000dps (0b11 << 2) +#define LSM6DS3_GYRO_ODR_104HZ (0b0100 << 4) +#define LSM6DS3_GYRO_ODR_208HZ (0b0101 << 4) +#define LSM6DS3_GYRO_INT1_DRDY_G 0b10 +#define LSM6DS3_GYRO_DRDY_GDA 0b10 +#define LSM6DS3_GYRO_DRDY_PULSE_MODE (1 << 7) +#define LSM6DS3_GYRO_MIN_ST_LIMIT_mdps 150000.0f +#define LSM6DS3_GYRO_MAX_ST_LIMIT_mdps 700000.0f + + +class LSM6DS3_Gyro : public I2CSensor { + uint8_t get_device_address() {return LSM6DS3_GYRO_I2C_ADDR;} + cereal::SensorEventData::SensorSource source = cereal::SensorEventData::SensorSource::LSM6DS3; + + // self test functions + int self_test(int test_type); + void wait_for_data_ready(); + void read_and_avg_data(float* val_st_off); +public: + LSM6DS3_Gyro(I2CBus *bus, int gpio_nr = 0, bool shared_gpio = false); + int init(); + bool get_event(MessageBuilder &msg, uint64_t ts = 0); + int shutdown(); +}; diff --git a/openpilot/sunnypilot/system/sensord/sensors/lsm6ds3_temp.cc b/openpilot/sunnypilot/system/sensord/sensors/lsm6ds3_temp.cc new file mode 100644 index 0000000000..390f192a2d --- /dev/null +++ b/openpilot/sunnypilot/system/sensord/sensors/lsm6ds3_temp.cc @@ -0,0 +1,37 @@ +#include "sunnypilot/system/sensord/sensors/lsm6ds3_temp.h" + +#include + +#include "common/swaglog.h" +#include "common/timing.h" + +LSM6DS3_Temp::LSM6DS3_Temp(I2CBus *bus) : I2CSensor(bus) {} + +int LSM6DS3_Temp::init() { + int ret = verify_chip_id(LSM6DS3_TEMP_I2C_REG_ID, {LSM6DS3_TEMP_CHIP_ID, LSM6DS3TRC_TEMP_CHIP_ID}); + if (ret == -1) return -1; + + if (ret == LSM6DS3TRC_TEMP_CHIP_ID) { + source = cereal::SensorEventData::SensorSource::LSM6DS3TRC; + } + return 0; +} + +bool LSM6DS3_Temp::get_event(MessageBuilder &msg, uint64_t ts) { + uint64_t start_time = nanos_since_boot(); + uint8_t buffer[2]; + int len = read_register(LSM6DS3_TEMP_I2C_REG_OUT_TEMP_L, buffer, sizeof(buffer)); + assert(len == sizeof(buffer)); + + float scale = (source == cereal::SensorEventData::SensorSource::LSM6DS3TRC) ? 256.0f : 16.0f; + float temp = 25.0f + read_16_bit(buffer[0], buffer[1]) / scale; + + auto event = msg.initEvent().initTemperatureSensor(); + event.setSource(source); + event.setVersion(1); + event.setType(SENSOR_TYPE_AMBIENT_TEMPERATURE); + event.setTimestamp(start_time); + event.setTemperature(temp); + + return true; +} diff --git a/openpilot/sunnypilot/system/sensord/sensors/lsm6ds3_temp.h b/openpilot/sunnypilot/system/sensord/sensors/lsm6ds3_temp.h new file mode 100644 index 0000000000..c314d456e8 --- /dev/null +++ b/openpilot/sunnypilot/system/sensord/sensors/lsm6ds3_temp.h @@ -0,0 +1,26 @@ +#pragma once + +#include "sunnypilot/system/sensord/sensors/i2c_sensor.h" + +// Address of the chip on the bus +#define LSM6DS3_TEMP_I2C_ADDR 0x6A + +// Registers of the chip +#define LSM6DS3_TEMP_I2C_REG_ID 0x0F +#define LSM6DS3_TEMP_I2C_REG_OUT_TEMP_L 0x20 + +// Constants +#define LSM6DS3_TEMP_CHIP_ID 0x69 +#define LSM6DS3TRC_TEMP_CHIP_ID 0x6A + + +class LSM6DS3_Temp : public I2CSensor { + uint8_t get_device_address() {return LSM6DS3_TEMP_I2C_ADDR;} + cereal::SensorEventData::SensorSource source = cereal::SensorEventData::SensorSource::LSM6DS3; + +public: + LSM6DS3_Temp(I2CBus *bus); + int init(); + bool get_event(MessageBuilder &msg, uint64_t ts = 0); + int shutdown() { return 0; } +}; diff --git a/openpilot/sunnypilot/system/sensord/sensors/mmc5603nj_magn.cc b/openpilot/sunnypilot/system/sensord/sensors/mmc5603nj_magn.cc new file mode 100644 index 0000000000..12d438ebd1 --- /dev/null +++ b/openpilot/sunnypilot/system/sensord/sensors/mmc5603nj_magn.cc @@ -0,0 +1,108 @@ +#include "sunnypilot/system/sensord/sensors/mmc5603nj_magn.h" + +#include +#include +#include + +#include "common/swaglog.h" +#include "common/timing.h" +#include "common/util.h" + +MMC5603NJ_Magn::MMC5603NJ_Magn(I2CBus *bus) : I2CSensor(bus) {} + +int MMC5603NJ_Magn::init() { + int ret = verify_chip_id(MMC5603NJ_I2C_REG_ID, {MMC5603NJ_CHIP_ID}); + if (ret == -1) return -1; + + // Set ODR to 0 + ret = set_register(MMC5603NJ_I2C_REG_ODR, 0); + if (ret < 0) { + goto fail; + } + + // Set BW to 0b01 for 1-150 Hz operation + ret = set_register(MMC5603NJ_I2C_REG_INTERNAL_1, 0b01); + if (ret < 0) { + goto fail; + } + +fail: + return ret; +} + +int MMC5603NJ_Magn::shutdown() { + int ret = 0; + + // disable auto reset of measurements + uint8_t value = 0; + ret = read_register(MMC5603NJ_I2C_REG_INTERNAL_0, &value, 1); + if (ret < 0) { + goto fail; + } + + value &= ~(MMC5603NJ_CMM_FREQ_EN | MMC5603NJ_AUTO_SR_EN); + ret = set_register(MMC5603NJ_I2C_REG_INTERNAL_0, value); + if (ret < 0) { + goto fail; + } + + // set ODR to 0 to leave continuous mode + ret = set_register(MMC5603NJ_I2C_REG_ODR, 0); + if (ret < 0) { + goto fail; + } + return ret; + +fail: + LOGE("Could not disable mmc5603nj auto set reset"); + return ret; +} + +void MMC5603NJ_Magn::start_measurement() { + set_register(MMC5603NJ_I2C_REG_INTERNAL_0, 0b01); + util::sleep_for(5); +} + +std::vector MMC5603NJ_Magn::read_measurement() { + int len; + uint8_t buffer[9]; + len = read_register(MMC5603NJ_I2C_REG_XOUT0, buffer, sizeof(buffer)); + assert(len == sizeof(buffer)); + float scale = 1.0 / 16384.0; + float x = (read_20_bit(buffer[6], buffer[1], buffer[0]) * scale) - 32.0; + float y = (read_20_bit(buffer[7], buffer[3], buffer[2]) * scale) - 32.0; + float z = (read_20_bit(buffer[8], buffer[5], buffer[4]) * scale) - 32.0; + std::vector xyz = {x, y, z}; + return xyz; +} + +bool MMC5603NJ_Magn::get_event(MessageBuilder &msg, uint64_t ts) { + uint64_t start_time = nanos_since_boot(); + // SET - RESET cycle + set_register(MMC5603NJ_I2C_REG_INTERNAL_0, MMC5603NJ_SET); + util::sleep_for(5); + MMC5603NJ_Magn::start_measurement(); + std::vector xyz = MMC5603NJ_Magn::read_measurement(); + + set_register(MMC5603NJ_I2C_REG_INTERNAL_0, MMC5603NJ_RESET); + util::sleep_for(5); + MMC5603NJ_Magn::start_measurement(); + std::vector reset_xyz = MMC5603NJ_Magn::read_measurement(); + + auto event = msg.initEvent().initMagnetometer(); + event.setSource(cereal::SensorEventData::SensorSource::MMC5603NJ); + event.setVersion(1); + event.setSensor(SENSOR_MAGNETOMETER_UNCALIBRATED); + event.setType(SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED); + event.setTimestamp(start_time); + + float vals[] = {xyz[0], xyz[1], xyz[2], reset_xyz[0], reset_xyz[1], reset_xyz[2]}; + bool valid = true; + if (std::any_of(std::begin(vals), std::end(vals), [](float val) { return val == -32.0; })) { + valid = false; + } + auto svec = event.initMagneticUncalibrated(); + svec.setV(vals); + svec.setStatus(valid); + return true; +} diff --git a/openpilot/sunnypilot/system/sensord/sensors/mmc5603nj_magn.h b/openpilot/sunnypilot/system/sensord/sensors/mmc5603nj_magn.h new file mode 100644 index 0000000000..9311631c06 --- /dev/null +++ b/openpilot/sunnypilot/system/sensord/sensors/mmc5603nj_magn.h @@ -0,0 +1,37 @@ +#pragma once + +#include + +#include "sunnypilot/system/sensord/sensors/i2c_sensor.h" + +// Address of the chip on the bus +#define MMC5603NJ_I2C_ADDR 0x30 + +// Registers of the chip +#define MMC5603NJ_I2C_REG_XOUT0 0x00 +#define MMC5603NJ_I2C_REG_ODR 0x1A +#define MMC5603NJ_I2C_REG_INTERNAL_0 0x1B +#define MMC5603NJ_I2C_REG_INTERNAL_1 0x1C +#define MMC5603NJ_I2C_REG_INTERNAL_2 0x1D +#define MMC5603NJ_I2C_REG_ID 0x39 + +// Constants +#define MMC5603NJ_CHIP_ID 0x10 +#define MMC5603NJ_CMM_FREQ_EN (1 << 7) +#define MMC5603NJ_AUTO_SR_EN (1 << 5) +#define MMC5603NJ_CMM_EN (1 << 4) +#define MMC5603NJ_EN_PRD_SET (1 << 3) +#define MMC5603NJ_SET (1 << 3) +#define MMC5603NJ_RESET (1 << 4) + +class MMC5603NJ_Magn : public I2CSensor { +private: + uint8_t get_device_address() {return MMC5603NJ_I2C_ADDR;} + void start_measurement(); + std::vector read_measurement(); +public: + MMC5603NJ_Magn(I2CBus *bus); + int init(); + bool get_event(MessageBuilder &msg, uint64_t ts = 0); + int shutdown(); +}; diff --git a/openpilot/sunnypilot/system/sensord/sensors/sensor.h b/openpilot/sunnypilot/system/sensord/sensors/sensor.h new file mode 100644 index 0000000000..ccf998d161 --- /dev/null +++ b/openpilot/sunnypilot/system/sensord/sensors/sensor.h @@ -0,0 +1,24 @@ +#pragma once + +#include "cereal/messaging/messaging.h" + +class Sensor { +public: + int gpio_fd = -1; + bool enabled = false; + uint64_t start_ts = 0; + uint64_t init_delay = 500e6; // default dealy 500ms + + virtual ~Sensor() {} + virtual int init() = 0; + virtual bool get_event(MessageBuilder &msg, uint64_t ts = 0) = 0; + virtual bool has_interrupt_enabled() = 0; + virtual int shutdown() = 0; + + virtual bool is_data_valid(uint64_t current_ts) { + if (start_ts == 0) { + start_ts = current_ts; + } + return (current_ts - start_ts) > init_delay; + } +}; diff --git a/openpilot/sunnypilot/system/sensord/sensors_qcom2.cc b/openpilot/sunnypilot/system/sensord/sensors_qcom2.cc new file mode 100644 index 0000000000..f4ecc7fc21 --- /dev/null +++ b/openpilot/sunnypilot/system/sensord/sensors_qcom2.cc @@ -0,0 +1,179 @@ +#include + +#include +#include +#include +#include +#include +#include + +#include "cereal/services.h" +#include "cereal/messaging/messaging.h" +#include "common/i2c.h" +#include "common/ratekeeper.h" +#include "common/swaglog.h" +#include "common/timing.h" +#include "common/util.h" +#include "sunnypilot/system/sensord/sensors/bmx055_accel.h" +#include "sunnypilot/system/sensord/sensors/bmx055_gyro.h" +#include "sunnypilot/system/sensord/sensors/bmx055_magn.h" +#include "sunnypilot/system/sensord/sensors/bmx055_temp.h" +#include "sunnypilot/system/sensord/sensors/constants.h" +#include "sunnypilot/system/sensord/sensors/lsm6ds3_accel.h" +#include "sunnypilot/system/sensord/sensors/lsm6ds3_gyro.h" +#include "sunnypilot/system/sensord/sensors/lsm6ds3_temp.h" +#include "sunnypilot/system/sensord/sensors/mmc5603nj_magn.h" + +#define I2C_BUS_IMU 1 + +ExitHandler do_exit; + +void interrupt_loop(std::vector> sensors) { + PubMaster pm({"gyroscope", "accelerometer"}); + + int fd = -1; + for (auto &[sensor, msg_name] : sensors) { + if (sensor->has_interrupt_enabled()) { + fd = sensor->gpio_fd; + break; + } + } + + uint64_t offset = nanos_since_epoch() - nanos_since_boot(); + struct pollfd fd_list[1] = {0}; + fd_list[0].fd = fd; + fd_list[0].events = POLLIN | POLLPRI; + + while (!do_exit) { + int err = poll(fd_list, 1, 100); + if (err == -1) { + if (errno == EINTR) { + continue; + } + return; + } else if (err == 0) { + LOGE("poll timed out"); + continue; + } + + if ((fd_list[0].revents & (POLLIN | POLLPRI)) == 0) { + LOGE("no poll events set"); + continue; + } + + // Read all events + struct gpioevent_data evdata[16]; + err = HANDLE_EINTR(read(fd, evdata, sizeof(evdata))); + if (err < 0 || err % sizeof(*evdata) != 0) { + LOGE("error reading event data %d", err); + continue; + } + + uint64_t cur_offset = nanos_since_epoch() - nanos_since_boot(); + uint64_t diff = cur_offset > offset ? cur_offset - offset : offset - cur_offset; + if (diff > 10*1e6) { // 10ms + LOGW("time jumped: %lu %lu", cur_offset, offset); + offset = cur_offset; + + // we don't have a valid timestamp since the + // time jumped, so throw out this measurement. + continue; + } + + int num_events = err / sizeof(*evdata); + uint64_t ts = evdata[num_events - 1].timestamp - cur_offset; + + for (auto &[sensor, msg_name] : sensors) { + if (!sensor->has_interrupt_enabled()) { + continue; + } + + MessageBuilder msg; + if (!sensor->get_event(msg, ts)) { + continue; + } + + if (!sensor->is_data_valid(ts)) { + continue; + } + + pm.send(msg_name.c_str(), msg); + } + } +} + +void polling_loop(Sensor *sensor, std::string msg_name) { + PubMaster pm({msg_name.c_str()}); + RateKeeper rk(msg_name, services.at(msg_name).frequency); + while (!do_exit) { + MessageBuilder msg; + if (sensor->get_event(msg) && sensor->is_data_valid(nanos_since_boot())) { + pm.send(msg_name.c_str(), msg); + } + rk.keepTime(); + } +} + +int sensor_loop(I2CBus *i2c_bus_imu) { + // Sensor init + std::vector> sensors_init = { + {new BMX055_Accel(i2c_bus_imu), "accelerometer2"}, + {new BMX055_Gyro(i2c_bus_imu), "gyroscope2"}, + {new BMX055_Magn(i2c_bus_imu), "magnetometer"}, + {new BMX055_Temp(i2c_bus_imu), "temperatureSensor2"}, + + {new LSM6DS3_Accel(i2c_bus_imu, GPIO_LSM_INT), "accelerometer"}, + {new LSM6DS3_Gyro(i2c_bus_imu, GPIO_LSM_INT, true), "gyroscope"}, + {new LSM6DS3_Temp(i2c_bus_imu), "temperatureSensor"}, + + {new MMC5603NJ_Magn(i2c_bus_imu), "magnetometer"}, + }; + + // Initialize sensors + std::vector threads; + for (auto &[sensor, msg_name] : sensors_init) { + int err = sensor->init(); + if (err < 0) { + continue; + } + + if (!sensor->has_interrupt_enabled()) { + threads.emplace_back(polling_loop, sensor, msg_name); + } + } + + // increase interrupt quality by pinning interrupt and process to core 1 + setpriority(PRIO_PROCESS, 0, -18); + util::set_core_affinity({1}); + + // TODO: get the IRQ number from gpiochip + std::string irq_path = "/proc/irq/336/smp_affinity_list"; + if (!util::file_exists(irq_path)) { + irq_path = "/proc/irq/335/smp_affinity_list"; + } + std::system(util::string_format("sudo su -c 'echo 1 > %s'", irq_path.c_str()).c_str()); + + // thread for reading events via interrupts + threads.emplace_back(&interrupt_loop, std::ref(sensors_init)); + + // wait for all threads to finish + for (auto &t : threads) { + t.join(); + } + + for (auto &[sensor, msg_name] : sensors_init) { + sensor->shutdown(); + delete sensor; + } + return 0; +} + +int main(int argc, char *argv[]) { + try { + auto i2c_bus_imu = std::make_unique(I2C_BUS_IMU); + return sensor_loop(i2c_bus_imu.get()); + } catch (std::exception &e) { + LOGE("I2CBus init failed"); + return -1; + } +} diff --git a/openpilot/sunnypilot/system/sensord/tests/test_sensord.py b/openpilot/sunnypilot/system/sensord/tests/test_sensord.py new file mode 100644 index 0000000000..53f5d27219 --- /dev/null +++ b/openpilot/sunnypilot/system/sensord/tests/test_sensord.py @@ -0,0 +1,252 @@ +import os +import subprocess +import pytest +import time +import numpy as np +from collections import namedtuple, defaultdict + +import openpilot.cereal.messaging as messaging +from openpilot.cereal import log +from openpilot.cereal.services import SERVICE_LIST +from openpilot.common.gpio import get_irqs_for_action +from openpilot.common.timeout import Timeout +from openpilot.common.hardware import HARDWARE +from openpilot.system.manager.process_config import managed_processes + +BMX = { + ('bmx055', 'acceleration'), + ('bmx055', 'gyroUncalibrated'), + ('bmx055', 'magneticUncalibrated'), + ('bmx055', 'temperature'), +} + +LSM = { + ('lsm6ds3', 'acceleration'), + ('lsm6ds3', 'gyroUncalibrated'), + ('lsm6ds3', 'temperature'), +} +LSM_C = {(x[0]+'trc', x[1]) for x in LSM} + +MMC = { + ('mmc5603nj', 'magneticUncalibrated'), +} + +SENSOR_CONFIGURATIONS: list[set] = [ + BMX | LSM, + MMC | LSM, + BMX | LSM_C, + MMC| LSM_C, +] +if HARDWARE.get_device_type() == "mici": + SENSOR_CONFIGURATIONS = [ + LSM, + LSM_C, + ] + +Sensor = log.SensorEventData.SensorSource +SensorConfig = namedtuple('SensorConfig', ['type', 'sanity_min', 'sanity_max']) +ALL_SENSORS = { + Sensor.lsm6ds3: { + SensorConfig("acceleration", 5, 15), + SensorConfig("gyroUncalibrated", 0, .2), + SensorConfig("temperature", 0, 60), + }, + + Sensor.lsm6ds3trc: { + SensorConfig("acceleration", 5, 15), + SensorConfig("gyroUncalibrated", 0, .2), + SensorConfig("temperature", 0, 60), + }, + + Sensor.bmx055: { + SensorConfig("acceleration", 5, 15), + SensorConfig("gyroUncalibrated", 0, .2), + SensorConfig("magneticUncalibrated", 0, 300), + SensorConfig("temperature", 0, 60), + }, + + Sensor.mmc5603nj: { + SensorConfig("magneticUncalibrated", 0, 300), + } +} + + +def get_irq_count(irq: str): + with open(f"/sys/kernel/irq/{irq}/per_cpu_count") as f: + per_cpu = map(int, f.read().split(",")) + return sum(per_cpu) + +def read_sensor_events(duration_sec): + sensor_types = ['accelerometer', 'gyroscope', 'magnetometer', 'accelerometer2', + 'gyroscope2', 'temperatureSensor', 'temperatureSensor2'] + socks = {} + poller = messaging.Poller() + events = defaultdict(list) + for stype in sensor_types: + socks[stype] = messaging.sub_sock(stype, poller=poller, timeout=100) + + # wait for sensors to come up + with Timeout(int(os.environ.get("SENSOR_WAIT", "5")), "sensors didn't come up"): + while len(poller.poll(250)) == 0: + pass + time.sleep(1) + for s in socks.values(): + messaging.drain_sock_raw(s) + + st = time.monotonic() + while time.monotonic() - st < duration_sec: + for s in socks: + events[s] += messaging.drain_sock(socks[s]) + time.sleep(0.1) + + assert sum(map(len, events.values())) != 0, "No sensor events collected!" + + return {k: v for k, v in events.items() if len(v) > 0} + +@pytest.mark.tici +class TestSensord: + @classmethod + def setup_class(cls): + # enable LSM self test + os.environ["LSM_SELF_TEST"] = "1" + + # read initial sensor values every test case can use + subprocess.run(["pkill", "-f", r"\\./sensord"], check=False) + try: + managed_processes["sensord"].start() + cls.sample_secs = int(os.getenv("SAMPLE_SECS", "10")) + cls.events = read_sensor_events(cls.sample_secs) + + # determine sensord's irq + cls.sensord_irq = get_irqs_for_action("sensord")[0] + finally: + # teardown won't run if this doesn't succeed + managed_processes["sensord"].stop() + + @classmethod + def teardown_class(cls): + managed_processes["sensord"].stop() + + def teardown_method(self): + managed_processes["sensord"].stop() + + def test_sensors_present(self): + # verify correct sensors configuration + seen = set() + for etype in self.events: + for measurement in self.events[etype]: + m = getattr(measurement, measurement.which()) + seen.add((str(m.source), m.which())) + + assert seen in SENSOR_CONFIGURATIONS + + def test_lsm6ds3_timing(self, subtests): + # verify measurements are sampled and published at 104Hz + + sensor_t = { + 1: [], # accel + 5: [], # gyro + } + + for measurement in self.events['accelerometer']: + m = getattr(measurement, measurement.which()) + sensor_t[m.sensor].append(m.timestamp) + + for measurement in self.events['gyroscope']: + m = getattr(measurement, measurement.which()) + sensor_t[m.sensor].append(m.timestamp) + + for s, vals in sensor_t.items(): + with subtests.test(sensor=s): + assert len(vals) > 0 + tdiffs = np.diff(vals) / 1e6 # millis + + high_delay_diffs = list(filter(lambda d: d >= 20., tdiffs)) + assert len(high_delay_diffs) < 15, f"Too many large diffs: {high_delay_diffs}" + + avg_diff = sum(tdiffs)/len(tdiffs) + avg_freq = 1. / (avg_diff * 1e-3) + assert 92. < avg_freq < 114., f"avg freq {avg_freq}Hz wrong, expected 104Hz" + + stddev = np.std(tdiffs) + assert stddev < 2.0, f"Standard-dev to big {stddev}" + + def test_sensor_frequency(self, subtests): + for s, msgs in self.events.items(): + with subtests.test(sensor=s): + freq = len(msgs) / self.sample_secs + ef = SERVICE_LIST[s].frequency + assert ef*0.85 <= freq <= ef*1.15 + + def test_logmonottime_timestamp_diff(self): + # ensure diff between the message logMonotime and sample timestamp is small + + tdiffs = [] + for etype in self.events: + for measurement in self.events[etype]: + m = getattr(measurement, measurement.which()) + + # check if gyro and accel timestamps are before logMonoTime + if str(m.source).startswith("lsm6ds3") and m.which() != 'temperature': + err_msg = f"Timestamp after logMonoTime: {m.timestamp} > {measurement.logMonoTime}" + assert m.timestamp < measurement.logMonoTime, err_msg + + # negative values might occur, as non interrupt packages created + # before the sensor is read + tdiffs.append(abs(measurement.logMonoTime - m.timestamp) / 1e6) + + # some sensors have a read procedure that will introduce an expected diff on the order of 20ms + high_delay_diffs = set(filter(lambda d: d >= 25., tdiffs)) + assert len(high_delay_diffs) < 20, f"Too many measurements published: {high_delay_diffs}" + + avg_diff = round(sum(tdiffs)/len(tdiffs), 4) + assert avg_diff < 4, f"Avg packet diff: {avg_diff:.1f}ms" + + def test_sensor_values(self): + sensor_values = {} + for etype in self.events: + for measurement in self.events[etype]: + m = getattr(measurement, measurement.which()) + key = (m.source.raw, m.which()) + values = getattr(m, m.which()) + + if hasattr(values, 'v'): + values = values.v + values = np.atleast_1d(values) + + if key in sensor_values: + sensor_values[key].append(values) + else: + sensor_values[key] = [values] + + # Sanity check sensor values + for sensor, stype in sensor_values: + for s in ALL_SENSORS[sensor]: + if s.type != stype: + continue + + key = (sensor, s.type) + mean_norm = np.mean(np.linalg.norm(sensor_values[key], axis=1)) + err_msg = f"Sensor '{sensor} {s.type}' failed sanity checks {mean_norm} is not between {s.sanity_min} and {s.sanity_max}" + assert s.sanity_min <= mean_norm <= s.sanity_max, err_msg + + def test_sensor_verify_no_interrupts_after_stop(self): + managed_processes["sensord"].start() + time.sleep(3) + + # read /proc/interrupts to verify interrupts are received + state_one = get_irq_count(self.sensord_irq) + time.sleep(1) + state_two = get_irq_count(self.sensord_irq) + + error_msg = f"no interrupts received after sensord start!\n{state_one} {state_two}" + assert state_one != state_two, error_msg + + managed_processes["sensord"].stop() + time.sleep(1) + + # read /proc/interrupts to verify no more interrupts are received + state_one = get_irq_count(self.sensord_irq) + time.sleep(1) + state_two = get_irq_count(self.sensord_irq) + assert state_one == state_two, "Interrupts received after sensord stop!" diff --git a/openpilot/sunnypilot/system/sensord/tests/ttff_test.py b/openpilot/sunnypilot/system/sensord/tests/ttff_test.py new file mode 100755 index 0000000000..cc8408055c --- /dev/null +++ b/openpilot/sunnypilot/system/sensord/tests/ttff_test.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python3 + +import time +import atexit + +from openpilot.cereal import messaging +from openpilot.system.manager.process_config import managed_processes + +TIMEOUT = 10*60 + +def kill(): + for proc in ['ubloxd', 'pigeond']: + managed_processes[proc].stop(retry=True, block=True) + +if __name__ == "__main__": + # start ubloxd + managed_processes['ubloxd'].start() + atexit.register(kill) + + sm = messaging.SubMaster(['ubloxGnss']) + + times = [] + for i in range(20): + # start pigeond + st = time.monotonic() + managed_processes['pigeond'].start() + + # wait for a >4 satellite fix + while True: + sm.update(0) + msg = sm['ubloxGnss'] + if msg.which() == 'measurementReport' and sm.updated["ubloxGnss"]: + report = msg.measurementReport + if report.numMeas > 4: + times.append(time.monotonic() - st) + print(f"\033[94m{i}: Got a fix in {round(times[-1], 2)} seconds\033[0m") + break + + if time.monotonic() - st > TIMEOUT: + raise TimeoutError("\033[91mFailed to get a fix in {TIMEOUT} seconds!\033[0m") + + time.sleep(0.1) + + # stop pigeond + managed_processes['pigeond'].stop(retry=True, block=True) + time.sleep(20) + + print(f"\033[92mAverage TTFF: {round(sum(times) / len(times), 2)}s\033[0m") diff --git a/openpilot/sunnypilot/system/statsd.py b/openpilot/sunnypilot/system/statsd.py new file mode 100755 index 0000000000..ff77a5a57f --- /dev/null +++ b/openpilot/sunnypilot/system/statsd.py @@ -0,0 +1,234 @@ +#!/usr/bin/env python3 +import base64 +import json +import os +from decimal import Decimal + +import zmq +import time +import uuid +from pathlib import Path +from collections import defaultdict +from datetime import datetime, UTC, date +from typing import NoReturn + +from openpilot.common.params import Params +from openpilot.cereal.messaging import SubMaster +from openpilot.common.hardware.hw import Paths +from openpilot.common.swaglog import cloudlog +from openpilot.common.hardware import HARDWARE +from openpilot.common.utils import atomic_write +from openpilot.common.version import get_build_metadata +from openpilot.system.loggerd.config import STATS_DIR_FILE_LIMIT, STATS_SOCKET, STATS_FLUSH_TIME_S + + +class METRIC_TYPE: + GAUGE = 'g' + SAMPLE = 'sa' + RAW = 'r' + + +class StatLog: + def __init__(self): + self.pid = None + self.zctx = None + self.sock = None + self.stats_socket = STATS_SOCKET + + def connect(self) -> None: + self.zctx = zmq.Context.instance() or zmq.Context() + self.sock = self.zctx.socket(zmq.PUSH) + self.sock.setsockopt(zmq.LINGER, 10) + self.sock.connect(self.stats_socket) + self.pid = os.getpid() + + def __del__(self): + if self.sock is not None: + self.sock.close() + if self.zctx is not None: + self.zctx.term() + + def _send(self, metric: str) -> None: + if os.getpid() != self.pid: + self.connect() + + try: + self.sock.send_string(metric, zmq.NOBLOCK) + except zmq.error.Again: + # drop :/ + pass + + def gauge(self, name: str, value: float) -> None: + self._send(f"{name}:{value}|{METRIC_TYPE.GAUGE}") + + # Samples will be recorded in a buffer and at aggregation time, + # statistical properties will be logged (mean, count, percentiles, ...) + def sample(self, name: str, value: float): + self._send(f"{name}:{value}|{METRIC_TYPE.SAMPLE}") + + +class StatLogSP(StatLog): + def __init__(self, intercept=True): + """ + Initializes the class instance with an optional parameter to determine + if statistical logging should be configured or not. + + :param intercept: A boolean flag that indicates whether to initialize + the `comma_statlog`. If True, the `comma_statlog` attribute is + instantiated as a `StatLog` object. Defaults to True. + """ + super().__init__() + self.comma_statlog = StatLog() if intercept else None + self.stats_socket = f"{STATS_SOCKET}_sp" + + def connect(self) -> None: + super().connect() + if self.comma_statlog: + self.comma_statlog.connect() + + def __del__(self): + super().__del__() + if self.comma_statlog: + self.comma_statlog.__del__() + + def _send(self, metric: str) -> None: + super()._send(metric) + if self.comma_statlog: + self.comma_statlog._send(metric) + + @staticmethod + def default_converter(obj): + if isinstance(obj, (datetime, date)): + return obj.isoformat() + if isinstance(obj, set): + return list(obj) + if isinstance(obj, Decimal): + return float(obj) + return str(obj) # fallback for unknown types + + def raw(self, name: str, value: dict) -> None: + encoded_dict = base64.b64encode(json.dumps(value, default=self.default_converter).encode("utf-8")).decode("utf-8") + self._send(f"{name}:{encoded_dict}|{METRIC_TYPE.RAW}") + + +def main() -> NoReturn: + dongle_id = Params().get("DongleId") + def get_influxdb_line(measurement: str, value: float | dict[str, float], timestamp: datetime, tags: dict) -> str: + res = f"{measurement}" + for k, v in tags.items(): + res += f",{k}={str(v)}" + res += " " + + if isinstance(value, float): + value = {'value': value} + + for k, v in value.items(): + res += f"{k}={v}," + + res += f"dongle_id=\"{dongle_id}\" {int(timestamp.timestamp() * 1e9)}\n" + return res + + # open statistics socket + ctx = zmq.Context.instance() + sock = ctx.socket(zmq.PULL) + sock.bind(STATS_SOCKET) + + STATS_DIR = Paths.stats_root() + + # initialize stats directory + Path(STATS_DIR).mkdir(parents=True, exist_ok=True) + + build_metadata = get_build_metadata() + + # initialize tags + tags = { + 'started': False, + 'version': build_metadata.openpilot.version, + 'branch': build_metadata.channel, + 'dirty': build_metadata.openpilot.is_dirty, + 'origin': build_metadata.openpilot.git_normalized_origin, + 'deviceType': HARDWARE.get_device_type(), + } + + # subscribe to deviceState for started state + sm = SubMaster(['deviceState']) + + idx = 0 + boot_uid = str(uuid.uuid4())[:8] + last_flush_time = time.monotonic() + gauges = {} + samples: dict[str, list[float]] = defaultdict(list) + try: + while True: + started_prev = sm['deviceState'].started + sm.update() + + # Update metrics + while True: + try: + metric = sock.recv_string(zmq.NOBLOCK) + try: + metric_type = metric.split('|')[1] + metric_name = metric.split(':')[0] + metric_value = float(metric.split('|')[0].split(':')[1]) + + if metric_type == METRIC_TYPE.GAUGE: + gauges[metric_name] = metric_value + elif metric_type == METRIC_TYPE.SAMPLE: + samples[metric_name].append(metric_value) + else: + cloudlog.event("unknown metric type", metric_type=metric_type) + except Exception: + cloudlog.event("malformed metric", metric=metric) + except zmq.error.Again: + break + + # flush when started state changes or after FLUSH_TIME_S + if (time.monotonic() > last_flush_time + STATS_FLUSH_TIME_S) or (sm['deviceState'].started != started_prev): + result = "" + current_time = datetime.now(UTC) + tags['started'] = sm['deviceState'].started + + for key, value in gauges.items(): + result += get_influxdb_line(f"gauge.{key}", value, current_time, tags) + + for key, values in samples.items(): + values.sort() + sample_count = len(values) + sample_sum = sum(values) + + stats = { + 'count': sample_count, + 'min': values[0], + 'max': values[-1], + 'mean': sample_sum / sample_count, + } + for percentile in [0.05, 0.5, 0.95]: + value = values[int(round(percentile * (sample_count - 1)))] + stats[f"p{int(percentile * 100)}"] = value + + result += get_influxdb_line(f"sample.{key}", stats, current_time, tags) + + # clear intermediate data + gauges.clear() + samples.clear() + last_flush_time = time.monotonic() + + # check that we aren't filling up the drive + if len(os.listdir(STATS_DIR)) < STATS_DIR_FILE_LIMIT: + if len(result) > 0: + stats_path = os.path.join(STATS_DIR, f"{boot_uid}_{idx}") + with atomic_write(stats_path) as f: + f.write(result) + idx += 1 + else: + cloudlog.error("stats dir full") + finally: + sock.close() + ctx.term() + + +if __name__ == "__main__": + main() +else: + statlog = StatLogSP(intercept=True) diff --git a/openpilot/sunnypilot/system/updated/tests/test_sp_branch_migrations.py b/openpilot/sunnypilot/system/updated/tests/test_sp_branch_migrations.py new file mode 100644 index 0000000000..b2742841a0 --- /dev/null +++ b/openpilot/sunnypilot/system/updated/tests/test_sp_branch_migrations.py @@ -0,0 +1,73 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import pytest + +from openpilot.common.params import Params +from openpilot.system.updated.updated import Updater + + +@pytest.mark.parametrize(("device_type", "branch", "expected"), [ + ("tici", "staging-c3-new", "staging-tici"), + ("tici", "dev-c3-new", "staging-tici"), + ("tici", "master", "master-tici"), + ("tici", "master-dev-c3-new", "master-tici"), + ("tizi", "staging-c3-new", "staging"), + ("tizi", "dev-c3-new", "dev"), + ("tizi", "master-dev-c3-new", "master-dev"), + ("tizi", "release3", "release-tizi"), + ("tizi", "release3-staging", "release-tizi-staging"), + ("mici", "release3", "release-mici"), + ("mici", "release3-staging", "release-mici-staging"), +]) +def test_sp_branch_migrations_from_current_branch(mocker, device_type, branch, expected): + params = Params() + params.remove("UpdaterTargetBranch") + + mocker.patch("openpilot.system.updated.updated.HARDWARE.get_device_type", return_value=device_type) + mocker.patch.object(Updater, "get_branch", return_value=branch) + + assert Updater().target_branch == expected + + +@pytest.mark.parametrize(("device_type", "branch", "expected"), [ + ("tici", "staging-c3-new", "staging-tici"), + ("tici", "dev-c3-new", "staging-tici"), + ("tici", "master", "master-tici"), + ("tici", "master-dev-c3-new", "master-tici"), + ("tizi", "staging-c3-new", "staging"), + ("tizi", "dev-c3-new", "dev"), + ("tizi", "master-dev-c3-new", "master-dev"), + ("tizi", "release3", "release-tizi"), + ("tizi", "release3-staging", "release-tizi-staging"), + ("mici", "release3", "release-mici"), + ("mici", "release3-staging", "release-mici-staging"), +]) +def test_sp_branch_migrations_from_param(mocker, device_type, branch, expected): + params = Params() + params.put("UpdaterTargetBranch", branch, block=True) + + mocker.patch("openpilot.system.updated.updated.HARDWARE.get_device_type", return_value=device_type) + + try: + assert Updater().target_branch == expected + finally: + params.remove("UpdaterTargetBranch") + + +@pytest.mark.parametrize(("device_type", "branch"), [ + ("tici", "unknown"), + ("tizi", "unknown"), + ("mici", "unknown"), +]) +def test_sp_branch_migrations_passthrough(mocker, device_type, branch): + params = Params() + params.remove("UpdaterTargetBranch") + + mocker.patch("openpilot.system.updated.updated.HARDWARE.get_device_type", return_value=device_type) + mocker.patch.object(Updater, "get_branch", return_value=branch) + + assert Updater().target_branch == branch diff --git a/system/manager/test/__init__.py b/openpilot/sunnypilot/tools/__init__.py similarity index 100% rename from system/manager/test/__init__.py rename to openpilot/sunnypilot/tools/__init__.py diff --git a/system/sensord/__init__.py b/openpilot/sunnypilot/tools/memory_profiler/__init__.py similarity index 100% rename from system/sensord/__init__.py rename to openpilot/sunnypilot/tools/memory_profiler/__init__.py diff --git a/openpilot/sunnypilot/tools/memory_profiler/mem_usage.py b/openpilot/sunnypilot/tools/memory_profiler/mem_usage.py new file mode 100644 index 0000000000..20b4bb2d0f --- /dev/null +++ b/openpilot/sunnypilot/tools/memory_profiler/mem_usage.py @@ -0,0 +1,164 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import matplotlib.pyplot as plt +import os +import sys +import argparse +import numpy as np +import base64 +import io + +from openpilot.tools.lib.logreader import LogReader, ReadMode + + +def extract_mem_cpu_data(lr): + times, mems, cpus = [], [], [] + start_time = None + + for msg in lr: + if msg.which() == 'procLog': + if start_time is None: + start_time = msg.logMonoTime + mem = msg.procLog.mem + mem_usage = (mem.total - mem.available) / mem.total * 100 + cpu_usages = [(total - cpu.idle) / total * 100 for cpu in msg.procLog.cpuTimes + if (total := cpu.idle + cpu.user + cpu.system + cpu.nice + cpu.iowait + cpu.irq + cpu.softirq) > 0] + avg_cpu = sum(cpu_usages) / len(cpu_usages) if cpu_usages else 0 + times.append((msg.logMonoTime - start_time) / 1e9) + mems.append(mem_usage) + cpus.append(avg_cpu) + return times, mems, cpus + + +def process_segment(lr): + return [extract_mem_cpu_data(lr)] + + +def calculate_r_squared(y_true, y_pred): + ss_res = np.sum((y_true - y_pred) ** 2) + ss_tot = np.sum((y_true - np.mean(y_true)) ** 2) + return 1 - (ss_res / ss_tot) if ss_tot != 0 else 0 + + +def plot_results(segments, segment_data, route_name): + valid_data = [d for d in segment_data if d and d[0]] + if not valid_data: + print("No valid data to plot") + return + + avg_mems = [np.mean(d[1]) for d in valid_data] + avg_cpus = [np.mean(d[2]) for d in valid_data] + valid_segments = [segments[i] for i, d in enumerate(segment_data) if d and d[0]] + + height = max(10, 5 + len(valid_segments) * 0.4) + fig1, ax1 = plt.subplots(1, 1, figsize=(12, height), dpi=150) + + y_pos = range(len(valid_segments)) + ax1.barh([y - 0.2 for y in y_pos], avg_mems, height=0.4, color="dodgerblue", alpha=0.8, label="Avg Mem %") + ax1.barh([y + 0.2 for y in y_pos], avg_cpus, height=0.4, color="green", alpha=0.8, label="Avg CPU %") + + for i, (mem, cpu) in enumerate(zip(avg_mems, avg_cpus, strict=True)): + ax1.text(mem, i - 0.2, f"{mem:.1f}%", va="center", fontsize=8, color="#005a9e", fontweight="bold") + ax1.text(cpu, i + 0.2, f"{cpu:.1f}%", va="center", fontsize=8, color="#005a9e", fontweight="bold") + + ax1.set_yticks(y_pos) + ax1.set_yticklabels([f"Seg {s}" for s in valid_segments]) + ax1.set_xlabel("Usage (%)") + ax1.set_title("Average Memory and CPU Usage by Segment") + ax1.legend() + ax1.grid(axis="x", linestyle="--", alpha=0.5) + ax1.invert_yaxis() + + fig2, ax2 = plt.subplots(1, 1, figsize=(12, 8), dpi=150) + combined_times, combined_mems, combined_cpus = [], [], [] + time_offset = 0.0 + for times, mems, cpus in valid_data: + if times: + combined_times.extend([t + time_offset for t in times]) + combined_mems.extend(mems) + combined_cpus.extend(cpus) + time_offset += max(times) + + ax2.plot(combined_times, combined_mems, color="red", label="Memory Usage", alpha=0.6) + ax2.plot(combined_times, combined_cpus, color="blue", label="CPU Usage", alpha=0.6) + + warmup_sec = 60 + if len(combined_times) > 1 and combined_times[-1] > warmup_sec: + mask = np.array(combined_times) > warmup_sec + x_reg = np.array(combined_times)[mask] + + y_mem_reg = np.array(combined_mems)[mask] + slope_mem, intercept_mem = np.polyfit(x_reg, y_mem_reg, 1) + trend_mem = slope_mem * x_reg + intercept_mem + r2_mem = calculate_r_squared(y_mem_reg, trend_mem) + ax2.plot(x_reg, trend_mem, color="darkred", linestyle="--", linewidth=2.5, + label=f"Mem Trend (Slope: {slope_mem:.4f} %/s, R²: {r2_mem:.2f})") + + y_cpu_reg = np.array(combined_cpus)[mask] + slope_cpu, intercept_cpu = np.polyfit(x_reg, y_cpu_reg, 1) + trend_cpu = slope_cpu * x_reg + intercept_cpu + r2_cpu = calculate_r_squared(y_cpu_reg, trend_cpu) + ax2.plot(x_reg, trend_cpu, color="navy", linestyle="--", linewidth=2.5, + label=f"CPU Trend (Slope: {slope_cpu:.4f} %/s, R²: {r2_cpu:.2f})") + + ax2.set_xlabel("Time (s)") + ax2.set_ylabel("Usage (%)") + ax2.set_title("Memory and CPU Usage Over Time") + ax2.legend(loc='lower left', fontsize='small', framealpha=0.9) + ax2.grid(True, linestyle="--", alpha=0.5) + + buffer1 = io.BytesIO() + fig1.savefig(buffer1, format='webp', bbox_inches='tight', pad_inches=1.0) + buffer1.seek(0) + img1 = base64.b64encode(buffer1.getvalue()).decode() + + buffer2 = io.BytesIO() + fig2.savefig(buffer2, format='webp', bbox_inches='tight', pad_inches=1.0) + buffer2.seek(0) + img2 = base64.b64encode(buffer2.getvalue()).decode() + + filename = f"memory_usage_{route_name}.html" + save_path = os.path.join(os.path.dirname(__file__), "plots", filename) + os.makedirs(os.path.dirname(save_path), exist_ok=True) + + html_template = ( + "" + + f"

Memory Profile Report

Route: {route_name.replace('_', '/')}

" + + f"" + + f"" + ) + + plt.close(fig1) + plt.close(fig2) + + with open(save_path, "w") as f: + f.write(html_template) + + print(f"Report saved to {save_path}") + + +def main(): + parser = argparse.ArgumentParser(description='Extract memory usage from route logs.') + parser.add_argument('route_or_segment_name', help='Route or segment name from comma connect') + args = parser.parse_args() + + try: + print(f"Fetching logs for {args.route_or_segment_name}") + lr = LogReader(args.route_or_segment_name, default_mode=ReadMode.QLOG) + segment_data = lr.run_across_segments(24, process_segment) + segments = list(range(len(segment_data))) + route_name = args.route_or_segment_name.replace('/', '_') + plot_results(segments, segment_data, route_name) + except Exception as e: + print(f"Error: {e}") + sys.exit(1) + + +if __name__ == "__main__": + main() diff --git a/openpilot/sunnypilot/tools/pull_footage.py b/openpilot/sunnypilot/tools/pull_footage.py new file mode 100755 index 0000000000..9964ef5769 --- /dev/null +++ b/openpilot/sunnypilot/tools/pull_footage.py @@ -0,0 +1,136 @@ +#!/usr/bin/env python3 +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import argparse +import os +import shutil +import subprocess +import sys +import requests +from openpilot.tools.lib.route import Route + + +def get_segments(source, route_id, camera, seg_range): + if "@" in source or "comma-" in source or "sunny-" in source: # SSH + if not route_id: + raise ValueError("route_id required for SSH") + cmd = ["ssh", source, f"ls -d /data/media/0/realdata/{route_id.split('--')[0]}--*"] + output = subprocess.check_output(cmd, stderr=subprocess.DEVNULL).decode("utf-8").strip() + return [{ + "type": "ssh", + "host": source, + "src": os.path.join(path, camera), + "num": int(path.split("--")[-1]) + } for path in sorted(output.split("\n"), key=lambda x: int(x.split("--")[-1])) if path] + else: # URL + route = Route(route_id) + cameras = [camera] + if camera == "fcamera.hevc": + cameras.extend([c for c in ["ecamera.hevc", "qcamera.ts"] if c != camera]) + + for cam in cameras: + attr_name = "camera_paths" if cam == "fcamera.hevc" else f"{cam.split('.')[0]}_paths" + paths = getattr(route, attr_name)() + if any(paths): + return [{"type": "url", "src": url, "num": idx, "cam": cam} for idx, url in enumerate(paths) if url] + + raise ValueError(f"No footage found for {route_id}") + + +def download(job, out_dir): + destination = os.path.join(out_dir, f"{job['num']}_{os.path.basename(job.get('cam', job.get('src')))}") + if os.path.exists(destination) and os.path.getsize(destination) > 0: + return destination + + print(f"Downloading segment {job['num']}") + if job["type"] == "ssh": + subprocess.check_call(["scp", f"{job['host']}:{job['src']}", destination]) + else: + with requests.get(job["src"], stream=True) as r: + r.raise_for_status() + with open(destination, 'wb') as f: + shutil.copyfileobj(r.raw, f) + return destination + + +def mux(files, output_file, codec): + list_filename = f"{output_file}.list.txt" + with open(list_filename, 'w') as f: + f.write('\n'.join([f"file '{os.path.abspath(name)}'" for name in files])) + + try: + cmd = [ + "ffmpeg", "-y", "-probesize", "100M", "-analyzeduration", "100M", "-f", "concat", + "-safe", "0", "-r", "20", "-i", list_filename, "-c", "copy", "-tag:v", codec, output_file + ] + subprocess.check_call(cmd) + print(f"Saved: {output_file} ({os.path.getsize(output_file) / 1048576:.2f} MB)") + if sys.platform == "darwin": + subprocess.run(["open", "-R", output_file]) + finally: + if os.path.exists(list_filename): + os.remove(list_filename) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("source") + parser.add_argument("route_id", nargs='?') + parser.add_argument("--output", "-o", default="output.mp4") + parser.add_argument("--camera", "-c", default="fcamera.hevc") + parser.add_argument("--keep-segments", action="store_true") + args = parser.parse_args() + + try: + route_id_str = args.route_id or args.source + segment_range = None + if "/" in route_id_str: + route_id_str, range_str = route_id_str.rsplit("/", 1) + if ":" in range_str or range_str.isdigit(): + segment_range = range_str + + is_ssh = "@" in args.source or "comma-" in args.source or "sunny-" in args.source + if not is_ssh and len(route_id_str.split("--")) > 2: + route_id_str = "--".join(route_id_str.split("--")[:2]) + + segments = get_segments(args.source, route_id_str, args.camera, segment_range) + if segment_range: + if ":" in segment_range: + parts = segment_range.split(":") + start_idx = int(parts[0]) if parts[0] else None + end_idx = int(parts[1]) if parts[1] else None + else: + start_idx = int(segment_range) + end_idx = start_idx + 1 + + segments = [ + segment for segment in segments + if (start_idx is None or segment['num'] >= start_idx) and (end_idx is None or segment['num'] < end_idx) + ] + + download_dir = f"{route_id_str}_segments" + os.makedirs(download_dir, exist_ok=True) + + downloaded_files = sorted( + [download(segment, download_dir) for segment in segments], + key=lambda x: int(os.path.basename(x).split("_")[0]) + ) + + camera_name = segments[0].get('cam', args.camera) + codec = "hvc1" if camera_name.endswith("hevc") else "avc1" + mux(downloaded_files, f"{route_id_str}--{args.output}", codec) + + if not args.keep_segments: + shutil.rmtree(download_dir) + + except Exception as e: + print(f"Error: {e}") + sys.exit(1) + + +if __name__ == "__main__": + main() diff --git a/openpilot/system b/openpilot/system deleted file mode 120000 index 16f8cc2b23..0000000000 --- a/openpilot/system +++ /dev/null @@ -1 +0,0 @@ -../system/ \ No newline at end of file diff --git a/system/sensord/sensors/__init__.py b/openpilot/system/__init__.py similarity index 100% rename from system/sensord/sensors/__init__.py rename to openpilot/system/__init__.py diff --git a/system/sensord/tests/__init__.py b/openpilot/system/athena/__init__.py similarity index 100% rename from system/sensord/tests/__init__.py rename to openpilot/system/athena/__init__.py diff --git a/system/athena/athenad.py b/openpilot/system/athena/athenad.py similarity index 80% rename from system/athena/athenad.py rename to openpilot/system/athena/athenad.py index 018fa0a0b5..1f59c8d271 100755 --- a/system/athena/athenad.py +++ b/openpilot/system/athena/athenad.py @@ -3,7 +3,7 @@ from __future__ import annotations import base64 import hashlib -import io +import itertools import json import os import queue @@ -23,22 +23,24 @@ from typing import cast from collections.abc import Callable import requests -from jsonrpc import JSONRPCResponseManager, dispatcher +from requests.adapters import HTTPAdapter, DEFAULT_POOLBLOCK from websocket import (ABNF, WebSocket, WebSocketException, WebSocketTimeoutException, create_connection) -import cereal.messaging as messaging -from cereal import log -from cereal.services import SERVICE_LIST -from openpilot.common.api import Api -from openpilot.common.file_helpers import CallbackReader, get_upload_stream +import openpilot.cereal.messaging as messaging +from openpilot.cereal import log +from opendbc.car.structs import car +from openpilot.cereal.services import SERVICE_LIST +from openpilot.common.api import Api, get_key_pair +from openpilot.common.utils import CallbackReader, get_upload_stream from openpilot.common.params import Params from openpilot.common.realtime import set_core_affinity -from openpilot.system.hardware import HARDWARE, PC +from openpilot.common.hardware import HARDWARE, PC from openpilot.system.loggerd.xattr_cache import getxattr, setxattr from openpilot.common.swaglog import cloudlog -from openpilot.system.version import get_build_metadata -from openpilot.system.hardware.hw import Paths +from openpilot.common.version import get_build_metadata +from openpilot.common.hardware.hw import Paths +from openpilot.system.athena.rpc import dispatcher, handle, is_call, is_response, loads ATHENA_HOST = os.getenv('ATHENA_HOST', 'wss://athena.comma.ai') @@ -56,6 +58,14 @@ WS_FRAME_SIZE = 4096 DEVICE_STATE_UPDATE_INTERVAL = 1.0 # in seconds DEFAULT_UPLOAD_PRIORITY = 99 # higher number = lower priority +SEND_PRIORITY_HIGH = 0 +SEND_PRIORITY_LOW = 1 + +# https://bytesolutions.com/dscp-tos-cos-precedence-conversion-chart, +# https://en.wikipedia.org/wiki/Differentiated_services +UPLOAD_TOS = 0x20 # CS1, low priority background traffic +SSH_TOS = 0x90 # AF42, DSCP of 36/HDD_LINUX_AC_VI with the minimum delay flag + NetworkType = log.DeviceState.NetworkType UploadFileDict = dict[str, str | int | float | bool] @@ -64,6 +74,17 @@ UploadItemDict = dict[str, str | bool | int | float | dict[str, str]] UploadFilesToUrlResponse = dict[str, int | list[UploadItemDict] | list[str]] +class UploadTOSAdapter(HTTPAdapter): + def init_poolmanager(self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs): + pool_kwargs["socket_options"] = [(socket.IPPROTO_IP, socket.IP_TOS, UPLOAD_TOS)] + super().init_poolmanager(connections, maxsize, block, **pool_kwargs) + + +UPLOAD_SESS = requests.Session() +UPLOAD_SESS.mount("http://", UploadTOSAdapter()) +UPLOAD_SESS.mount("https://", UploadTOSAdapter()) + + @dataclass class UploadFile: fn: str @@ -109,14 +130,18 @@ class UploadItem: dispatcher["echo"] = lambda s: s recv_queue: Queue[str] = queue.Queue() -send_queue: Queue[str] = queue.Queue() +send_queue: Queue[tuple[int, int, str]] = queue.PriorityQueue() upload_queue: Queue[UploadItem] = queue.PriorityQueue() -low_priority_send_queue: Queue[str] = queue.Queue() log_recv_queue: Queue[str] = queue.Queue() cancelled_uploads: set[str] = set() cur_upload_items: dict[int, UploadItem | None] = {} +send_seq = itertools.count() +def send_queue_push(data: str, priority: int) -> None: + assert priority is not None, "send queue priority must be specified" + send_queue.put_nowait((priority, next(send_seq), data)) # tie-break with a monotonic counter + # TODO-SP: adapt zst for sunnylink def strip_zst_extension(fn: str) -> str: @@ -136,7 +161,7 @@ class UploadQueueCache: try: upload_queue_json = Params().get("AthenadUploadQueue") if upload_queue_json is not None: - for item in json.loads(upload_queue_json): + for item in upload_queue_json: upload_queue.put(UploadItem.from_dict(item)) except Exception: cloudlog.exception("athena.UploadQueueCache.initialize.exception") @@ -146,7 +171,7 @@ class UploadQueueCache: try: queue: list[UploadItem | None] = list(upload_queue.queue) items = [asdict(i) for i in queue if i is not None and (i.id not in cancelled_uploads)] - Params().put("AthenadUploadQueue", json.dumps(items)) + Params().put("AthenadUploadQueue", items, block=True) except Exception: cloudlog.exception("athena.UploadQueueCache.cache.exception") @@ -189,11 +214,11 @@ def jsonrpc_handler(end_event: threading.Event, localProxyHandler = None) -> Non while not end_event.is_set(): try: data = recv_queue.get(timeout=1) - if "method" in data: + msg = loads(data) + if is_call(msg): cloudlog.event("athena.jsonrpc_handler.call_method", data=data) - response = JSONRPCResponseManager.handle(data, dispatcher) - send_queue.put_nowait(response.json) - elif "id" in data and ("result" in data or "error" in data): + send_queue_push(handle(msg, dispatcher), SEND_PRIORITY_HIGH) + elif is_response(msg): log_recv_queue.put_nowait(data) else: raise Exception("not a valid request or response") @@ -201,7 +226,7 @@ def jsonrpc_handler(end_event: threading.Event, localProxyHandler = None) -> Non pass except Exception as e: cloudlog.exception("athena jsonrpc handler failed") - send_queue.put_nowait(json.dumps({"error": str(e)})) + send_queue_push(json.dumps({"error": str(e)}), SEND_PRIORITY_HIGH) def retry_upload(tid: int, end_event: threading.Event, increase_count: bool = True) -> None: @@ -299,7 +324,7 @@ def upload_handler(end_event: threading.Event) -> None: cloudlog.exception("athena.upload_handler.exception") -def _do_upload(upload_item: UploadItem, callback: Callable = None) -> requests.Response: +def _do_upload(upload_item: UploadItem, callback: Callable | None = None) -> requests.Response: path = upload_item.path compress = False @@ -311,10 +336,10 @@ def _do_upload(upload_item: UploadItem, callback: Callable = None) -> requests.R stream = None try: stream, content_length = get_upload_stream(path, compress) - response = requests.put(upload_item.url, - data=CallbackReader(stream, callback, content_length) if callback else stream, - headers={**upload_item.headers, 'Content-Length': str(content_length)}, - timeout=30) + response = UPLOAD_SESS.put(upload_item.url, + data=CallbackReader(stream, callback, content_length) if callback else stream, + headers={**upload_item.headers, 'Content-Length': str(content_length)}, + timeout=30) return response finally: if stream: @@ -352,7 +377,7 @@ def getVersion() -> dict[str, str]: @dispatcher.add_method -def setNavDestination(latitude: int = 0, longitude: int = 0, place_name: str = None, place_details: str = None) -> dict[str, int]: +def setNavDestination(latitude: int = 0, longitude: int = 0, place_name: str | None = None, place_details: str | None = None) -> dict[str, int]: destination = { "latitude": latitude, "longitude": longitude, @@ -364,20 +389,22 @@ def setNavDestination(latitude: int = 0, longitude: int = 0, place_name: str = N return {"success": 1} -def scan_dir(path: str, prefix: str) -> list[str]: +def scan_dir(path: str, prefix: str, base: str | None = None) -> list[str]: + if base is None: + base = path files = [] # only walk directories that match the prefix # (glob and friends traverse entire dir tree) with os.scandir(path) as i: for e in i: - rel_path = os.path.relpath(e.path, Paths.log_root()) + rel_path = os.path.relpath(e.path, base) if e.is_dir(follow_symlinks=False): # add trailing slash rel_path = os.path.join(rel_path, '') # if prefix is a partial dir name, current dir will start with prefix # if prefix is a partial file name, prefix with start with dir name if rel_path.startswith(prefix) or prefix.startswith(rel_path): - files.extend(scan_dir(e.path, prefix)) + files.extend(scan_dir(e.path, prefix, base)) else: if rel_path.startswith(prefix): files.append(rel_path) @@ -385,7 +412,12 @@ def scan_dir(path: str, prefix: str) -> list[str]: @dispatcher.add_method def listDataDirectory(prefix='') -> list[str]: - return scan_dir(Paths.log_root(), prefix) + internal_files = scan_dir(Paths.log_root(), prefix, Paths.log_root()) + try: + external_files = scan_dir(Paths.log_root_external(), prefix, Paths.log_root_external()) + except FileNotFoundError: + external_files = [] + return sorted(set(internal_files + external_files)) @dispatcher.add_method @@ -410,8 +442,13 @@ def uploadFilesToUrls(files_data: list[UploadFileDict]) -> UploadFilesToUrlRespo failed.append(file.fn) continue - path = os.path.join(Paths.log_root(), file.fn) - if not os.path.exists(path) and not os.path.exists(strip_zst_extension(path)): + path_internal = os.path.join(Paths.log_root(), file.fn) + path_external = os.path.join(Paths.log_root_external(), file.fn) + if os.path.exists(path_internal) or os.path.exists(strip_zst_extension(path_internal)): + path = path_internal + elif os.path.exists(path_external) or os.path.exists(strip_zst_extension(path_external)): + path = path_external + else: failed.append(file.fn) continue @@ -424,7 +461,7 @@ def uploadFilesToUrls(files_data: list[UploadFileDict]) -> UploadFilesToUrlRespo path=path, url=file.url, headers=file.headers, - created_at=int(time.time() * 1000), + created_at=int(time.time() * 1000), # noqa: TID251 id=None, allow_cellular=file.allow_cellular, priority=file.priority, @@ -468,20 +505,20 @@ def setRouteViewed(route: str) -> dict[str, int | str]: # maintain a list of the last 10 routes viewed in connect params = Params() - r = params.get("AthenadRecentlyViewedRoutes", encoding="utf8") + r = params.get("AthenadRecentlyViewedRoutes") routes = [] if r is None else r.split(",") routes.append(route) # remove duplicates routes = list(dict.fromkeys(routes)) - params.put("AthenadRecentlyViewedRoutes", ",".join(routes[-10:])) + params.put("AthenadRecentlyViewedRoutes", ",".join(routes[-10:]), block=True) return {"success": 1} def startLocalProxy(global_end_event: threading.Event, remote_ws_uri: str, local_port: int) -> dict[str, int]: cloudlog.debug("athena.startLocalProxy.starting") - dongle_id = Params().get("DongleId").decode('utf8') + dongle_id = Params().get("DongleId") identity_token = Api(dongle_id).get_token() ws = create_connection(remote_ws_uri, cookie="jwt=" + identity_token, enable_multithread=True) @@ -501,8 +538,7 @@ def start_local_proxy_shim(global_end_event: threading.Event, local_port: int, w raise Exception("Requested local port not whitelisted") # Set TOS to keep connection responsive while under load. - # DSCP of 36/HDD_LINUX_AC_VI with the minimum delay flag - ws.sock.setsockopt(socket.IPPROTO_IP, socket.IP_TOS, 0x90) + ws.sock.setsockopt(socket.IPPROTO_IP, socket.IP_TOS, SSH_TOS) ssock, csock = socket.socketpair() local_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) @@ -526,21 +562,28 @@ def start_local_proxy_shim(global_end_event: threading.Event, local_port: int, w @dispatcher.add_method def getPublicKey() -> str | None: - if not os.path.isfile(Paths.persist_root() + '/comma/id_rsa.pub'): - return None - - with open(Paths.persist_root() + '/comma/id_rsa.pub') as f: - return f.read() + _, _, public_key = get_key_pair() + return public_key @dispatcher.add_method def getSshAuthorizedKeys() -> str: - return Params().get("GithubSshKeys", encoding='utf8') or '' + return cast(str, Params().get("GithubSshKeys") or "") @dispatcher.add_method def getGithubUsername() -> str: - return Params().get("GithubUsername", encoding='utf8') or '' + return cast(str, Params().get("GithubUsername") or "") + + +@dispatcher.add_method +def getNotCar() -> bool: + cp_bytes = Params().get("CarParamsPersistent") + if cp_bytes is not None: + with car.CarParams.from_bytes(cp_bytes) as CP: + return CP.notCar + return False + @dispatcher.add_method def getSimInfo(): @@ -559,31 +602,33 @@ def getNetworkMetered() -> bool: @dispatcher.add_method -def getNetworks(): - return HARDWARE.get_networks() +def startStream(sdp: str, enabled: bool) -> dict: + from openpilot.system.webrtc.helpers import StreamRequestBody, post_stream_request, wait_for_webrtcd + params = Params() + bridge_services_in = [] - -@dispatcher.add_method -def takeSnapshot() -> str | dict[str, str] | None: - from openpilot.system.camerad.snapshot import jpeg_write, snapshot - ret = snapshot() - if ret is not None: - def b64jpeg(x): - if x is not None: - f = io.BytesIO() - jpeg_write(f, x) - return base64.b64encode(f.getvalue()).decode("utf-8") - else: - return None - return {'jpegBack': b64jpeg(ret[0]), - 'jpegFront': b64jpeg(ret[1])} + # stale car params case taken care of by webrtcd being shut off on ignition + cp_bytes = Params().get("CarParamsPersistent") + if cp_bytes is not None: + with car.CarParams.from_bytes(cp_bytes) as CP: + if CP.notCar: + bridge_services_in.append("testJoystick") else: - raise Exception("not available while camerad is started") + raise Exception("failed to get CarParamsPersistent") + + if params.get_bool("IsOffroad"): + # manager owns camerad/stream_encoderd/webrtcd; flip the param and let it bring them up. + # webrtcd clears IsLiveStreaming when the session ends + params.put_bool("IsLiveStreaming", True) + # wait for webrtcd end points to wake up + wait_for_webrtcd() + + return post_stream_request(StreamRequestBody(sdp, "wideRoad", enabled, bridge_services_in, ["carState", "deviceState"])) def get_logs_to_send_sorted(log_attr_name=LOG_ATTR_NAME) -> list[str]: # TODO: scan once then use inotify to detect file creation/deletion - curr_time = int(time.time()) + curr_time = int(time.time()) # noqa: TID251 logs = [] for log_entry in os.listdir(Paths.swaglog_root()): log_path = os.path.join(Paths.swaglog_root(), log_entry) @@ -634,29 +679,28 @@ def add_log_to_queue(log_path, log_id, is_sunnylink=False): f"after compression: {compressed_size} bytes, " + f"after encoding: {encoded_size} bytes") - jsonrpc = { + params: dict[str, str | bool] = {"logs": payload} + if is_sunnylink and is_compressed: + params["compressed"] = is_compressed + + jsonrpc: dict = { "method": "forwardLogs", - "params": { - "logs": payload - }, + "params": params, "jsonrpc": "2.0", "id": log_id } - if is_sunnylink and is_compressed: - jsonrpc["params"]["compressed"] = is_compressed - jsonrpc_str = json.dumps(jsonrpc) size_in_bytes = len(jsonrpc_str.encode('utf-8')) if is_sunnylink and size_in_bytes <= MAX_SIZE_BYTES: cloudlog.debug(f"Target is sunnylink and log file {log_path} is small enough to send in one request ({size_in_bytes} bytes).") - low_priority_send_queue.put_nowait(jsonrpc_str) + send_queue_push(jsonrpc_str, SEND_PRIORITY_LOW) elif is_sunnylink: cloudlog.warning(f"Target is sunnylink and log file {log_path} is too large to send in one request.") else: cloudlog.debug(f"Target is not sunnylink, proceeding to send log file {log_path} in one request ({size_in_bytes} bytes).") - low_priority_send_queue.put_nowait(jsonrpc_str) + send_queue_push(jsonrpc_str, SEND_PRIORITY_LOW) def log_handler(end_event: threading.Event, log_attr_name=LOG_ATTR_NAME) -> None: @@ -681,7 +725,7 @@ def log_handler(end_event: threading.Event, log_attr_name=LOG_ATTR_NAME) -> None log_entry = log_files.pop() # newest log file cloudlog.debug(f"athena.log_handler.forward_request {log_entry}") try: - curr_time = int(time.time()) + curr_time = int(time.time()) # noqa: TID251 log_path = os.path.join(Paths.swaglog_root(), log_entry) setxattr(log_path, log_attr_name, int.to_bytes(curr_time, 4, sys.byteorder)) @@ -716,27 +760,40 @@ def log_handler(end_event: threading.Event, log_attr_name=LOG_ATTR_NAME) -> None cloudlog.exception("athena.log_handler.exception") -def stat_handler(end_event: threading.Event) -> None: - STATS_DIR = Paths.stats_root() +def stat_handler(end_event: threading.Event, stats_dir=None, is_sunnylink=False) -> None: + stats_dir = stats_dir or Paths.stats_root() last_scan = 0.0 while not end_event.is_set(): curr_scan = time.monotonic() try: if curr_scan - last_scan > 10: - stat_filenames = list(filter(lambda name: not name.startswith(tempfile.gettempprefix()), os.listdir(STATS_DIR))) + stat_filenames = list(filter(lambda name: not name.startswith(tempfile.gettempprefix()), os.listdir(stats_dir))) if len(stat_filenames) > 0: - stat_path = os.path.join(STATS_DIR, stat_filenames[0]) + stat_path = os.path.join(stats_dir, stat_filenames[0]) with open(stat_path) as f: - jsonrpc = { + payload = f.read() + is_compressed = False + + # Log the current size of the file + if is_sunnylink: + # Compress and encode the data if it exceeds the maximum size + compressed_data = gzip.compress(payload.encode()) + payload = base64.b64encode(compressed_data).decode() + is_compressed = True + + params: dict[str, str | bool] = {"stats": payload} + if is_sunnylink and is_compressed: + params["compressed"] = is_compressed + + jsonrpc: dict = { "method": "storeStats", - "params": { - "stats": f.read() - }, + "params": params, "jsonrpc": "2.0", "id": stat_filenames[0] } - low_priority_send_queue.put_nowait(json.dumps(jsonrpc)) + + send_queue_push(json.dumps(jsonrpc), SEND_PRIORITY_LOW) os.remove(stat_path) last_scan = curr_scan except Exception: @@ -747,7 +804,10 @@ def stat_handler(end_event: threading.Event) -> None: def ws_proxy_recv(ws: WebSocket, local_sock: socket.socket, ssock: socket.socket, end_event: threading.Event, global_end_event: threading.Event) -> None: while not (end_event.is_set() or global_end_event.is_set()): try: - r = select.select((ws.sock,), (), (), 30) + sock = ws.sock + if sock is None: + return + r = select.select((sock,), (), (), 30) if r[0]: data = ws.recv() if isinstance(data, str): @@ -804,7 +864,7 @@ def ws_recv(ws: WebSocket, end_event: threading.Event) -> None: recv_queue.put_nowait(data) elif opcode == ABNF.OPCODE_PING: last_ping = int(time.monotonic() * 1e9) - Params().put("LastAthenaPingTime", str(last_ping)) + Params().put("LastAthenaPingTime", last_ping, block=True) except WebSocketTimeoutException: ns_since_last_ping = int(time.monotonic() * 1e9) - last_ping if ns_since_last_ping > RECONNECT_TIMEOUT_S * 1e9: @@ -818,10 +878,7 @@ def ws_recv(ws: WebSocket, end_event: threading.Event) -> None: def ws_send(ws: WebSocket, end_event: threading.Event) -> None: while not end_event.is_set(): try: - try: - data = send_queue.get_nowait() - except queue.Empty: - data = low_priority_send_queue.get(timeout=1) + _, _, data = send_queue.get(timeout=1) for i in range(0, len(data), WS_FRAME_SIZE): frame = data[i:i+WS_FRAME_SIZE] last = i + WS_FRAME_SIZE >= len(data) @@ -840,7 +897,7 @@ def ws_manage(ws: WebSocket, end_event: threading.Event) -> None: sock = ws.sock while not end_event.wait(5): - onroad = params.get_bool("IsOnroad") + onroad = not params.get_bool("IsOffroad") if onroad != onroad_prev: onroad_prev = onroad @@ -862,14 +919,14 @@ def backoff(retries: int) -> int: return random.randrange(0, min(128, int(2 ** retries))) -def main(exit_event: threading.Event = None): +def main(exit_event: threading.Event | None = None): try: set_core_affinity([0, 1, 2, 3]) except Exception: cloudlog.exception("failed to set core affinity") params = Params() - dongle_id = params.get("DongleId", encoding='utf-8') + dongle_id = params.get("DongleId") UploadQueueCache.initialize(upload_queue) ws_uri = ATHENA_HOST + "/ws/v2/" + dongle_id diff --git a/system/athena/manage_athenad.py b/openpilot/system/athena/manage_athenad.py similarity index 83% rename from system/athena/manage_athenad.py rename to openpilot/system/athena/manage_athenad.py index 7158cd9220..3f0d6adcd3 100755 --- a/system/athena/manage_athenad.py +++ b/openpilot/system/athena/manage_athenad.py @@ -6,19 +6,19 @@ from multiprocessing import Process from openpilot.common.params import Params from openpilot.system.manager.process import launcher from openpilot.common.swaglog import cloudlog -from openpilot.system.hardware import HARDWARE -from openpilot.system.version import get_build_metadata +from openpilot.common.hardware import HARDWARE +from openpilot.common.version import get_build_metadata ATHENA_MGR_PID_PARAM = "AthenadPid" def main(): - manage_athenad("DongleId", ATHENA_MGR_PID_PARAM, 'athenad', 'system.athena.athenad') + manage_athenad("DongleId", ATHENA_MGR_PID_PARAM, 'athenad', 'openpilot.system.athena.athenad') def manage_athenad(dongle_id_param, pid_param, process_name, target): params = Params() - dongle_id = params.get(dongle_id_param, encoding='utf-8') + dongle_id = params.get(dongle_id_param) build_metadata = get_build_metadata() cloudlog.bind_global(dongle_id=dongle_id, diff --git a/openpilot/system/athena/registration.py b/openpilot/system/athena/registration.py new file mode 100755 index 0000000000..5e80fe5598 --- /dev/null +++ b/openpilot/system/athena/registration.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +import time +import json +import jwt +from typing import cast +from pathlib import Path + +from datetime import datetime, timedelta, UTC +from openpilot.common.api import api_get, get_key_pair +from openpilot.common.params import Params +from openpilot.common.spinner import Spinner +from openpilot.selfdrive.selfdrived.alertmanager import set_offroad_alert +from openpilot.common.hardware import HARDWARE, PC +from openpilot.common.hardware.hw import Paths +from openpilot.common.swaglog import cloudlog + + +UNREGISTERED_DONGLE_ID = "UnregisteredDevice" + +def is_registered_device() -> bool: + dongle = Params().get("DongleId") + return dongle not in (None, UNREGISTERED_DONGLE_ID) + + +def register(show_spinner=False) -> str | None: + """ + All devices built since March 2024 come with all + info stored in /persist/. This is kept around + only for devices built before then. + + With a backend update to take serial number instead + of dongle ID to some endpoints, this can be removed + entirely. + """ + params = Params() + + dongle_id: str | None = params.get("DongleId") + if dongle_id is None and Path(Paths.persist_root()+"/comma/dongle_id").is_file(): + # not all devices will have this; added early in comma 3X production (2/28/24) + with open(Paths.persist_root()+"/comma/dongle_id") as f: + dongle_id = f.read().strip() + + # Create registration token, in the future, this key will make JWTs directly + jwt_algo, private_key, public_key = get_key_pair() + + if not public_key: + dongle_id = UNREGISTERED_DONGLE_ID + cloudlog.warning("missing public key") + elif dongle_id is None: + if show_spinner: + spinner = Spinner() + spinner.update("registering device") + + # Block until we get the imei + serial = HARDWARE.get_serial() + start_time = time.monotonic() + imei: str | None = None + while imei is None: + try: + imei = HARDWARE.get_imei() + except Exception: + cloudlog.exception("Error getting imei, trying again...") + time.sleep(1) + + if time.monotonic() - start_time > 60 and show_spinner: + spinner.update(f"registering device - serial: {serial}, IMEI: {imei}") + + backoff = 0 + start_time = time.monotonic() + while True: + try: + register_token = jwt.encode({'register': True, 'exp': datetime.now(UTC).replace(tzinfo=None) + timedelta(hours=1)}, + cast(str, private_key), algorithm=jwt_algo) + cloudlog.info("getting pilotauth") + cloudlog.info("getting pilotauth") + resp = api_get("v2/pilotauth/", method='POST', timeout=15, + imei=imei, imei2="", serial=serial, public_key=public_key, register_token=register_token) + + if resp.status_code in (402, 403): + cloudlog.info(f"Unable to register device, got {resp.status_code}") + dongle_id = UNREGISTERED_DONGLE_ID + else: + dongleauth = json.loads(resp.text) + dongle_id = dongleauth["dongle_id"] + break + except NotImplementedError: + # dependency issues with PyJWT will hang the registration test in backoff loop otherwise + raise + except Exception: + cloudlog.exception("failed to authenticate") + backoff = min(backoff + 1, 15) + time.sleep(backoff) + + if time.monotonic() - start_time > 60 and show_spinner: + spinner.update(f"registering device - serial: {serial}, IMEI: {imei}") + return UNREGISTERED_DONGLE_ID # hotfix to prevent an infinite wait for registration + + if show_spinner: + spinner.close() + + if dongle_id: + params.put("DongleId", dongle_id, block=True) + set_offroad_alert("Offroad_UnregisteredHardware", (dongle_id == UNREGISTERED_DONGLE_ID) and not PC) + return dongle_id + + +if __name__ == "__main__": + print(register()) diff --git a/openpilot/system/athena/rpc.py b/openpilot/system/athena/rpc.py new file mode 100644 index 0000000000..aaf7f41fc3 --- /dev/null +++ b/openpilot/system/athena/rpc.py @@ -0,0 +1,116 @@ +import json +from collections.abc import Callable, Mapping +from typing import Any + +# a minimal implementation of json-rpc 2.0 https://www.jsonrpc.org/specification + +JSONRPC_VERSION = "2.0" + +# JSON-RPC 2.0 reserved / application error codes +PARSE_ERROR = -32700 +INVALID_REQUEST = -32600 +METHOD_NOT_FOUND = -32601 +INVALID_PARAMS = -32602 +SERVER_ERROR = -32000 + +JsonDict = dict[str, Any] +MethodMap = Mapping[str, Callable[..., Any]] + + +class Dispatcher(dict[str, Callable[..., Any]]): + def add_method(self, f: Callable[..., Any] | None = None, *, name: str | None = None): + def decorator(fn: Callable[..., Any]) -> Callable[..., Any]: + self[name or fn.__name__] = fn + return fn + return decorator(f) if f is not None else decorator + + +dispatcher = Dispatcher() + + +def dumps_call(method: str, params: Any = None, request_id: Any = None) -> str: + msg: JsonDict = {"jsonrpc": JSONRPC_VERSION, "method": method, "id": request_id} + if params is not None: + msg["params"] = params + return json.dumps(msg) + + +def dumps_result(request_id: Any, result: Any) -> str: + return json.dumps({"jsonrpc": JSONRPC_VERSION, "id": request_id, "result": result}) + + +def dumps_error(request_id: Any, message: str, code: int = SERVER_ERROR) -> str: + return json.dumps({ + "jsonrpc": JSONRPC_VERSION, + "id": request_id, + "error": {"code": code, "message": message}, + }) + + +def loads(raw: str | bytes) -> JsonDict: + if isinstance(raw, bytes): + raw = raw.decode() + data = json.loads(raw) + if not isinstance(data, dict): + raise ValueError("message must be a JSON object") + return data + + +def is_call(msg: JsonDict) -> bool: + return "method" in msg + + +def is_response(msg: JsonDict) -> bool: + return "id" in msg and ("result" in msg or "error" in msg) + + +def error_message(err: Any) -> str: + """Normalize JSON-RPC object errors and plain-string errors.""" + if isinstance(err, str): + return err + if isinstance(err, dict): + data = err.get("data") + if isinstance(data, dict) and data.get("message"): + return str(data["message"]) + if err.get("message") is not None: + return str(err["message"]) + return str(err) + + +def _invoke(fn: Callable[..., Any], params: Any) -> Any: + if params is None: + return fn() + if isinstance(params, dict): + return fn(**params) + if isinstance(params, (list, tuple)): + return fn(*params) + raise TypeError("params must be a list, object, or omitted") + + +def handle(raw: str | bytes | JsonDict, methods: MethodMap | None = None) -> str: + methods = dispatcher if methods is None else methods + + try: + msg = raw if isinstance(raw, dict) else loads(raw) + except (TypeError, ValueError, UnicodeDecodeError): + return dumps_error(None, "parse error", PARSE_ERROR) + + if not is_call(msg): + raise ValueError("not a call") + + req_id = msg.get("id") + name = msg.get("method") + if not isinstance(name, str): + return dumps_error(req_id, "invalid request", INVALID_REQUEST) + + try: + fn = methods[name] + except KeyError: + return dumps_error(req_id, f"method not found: {name}", METHOD_NOT_FOUND) + + try: + return dumps_result(req_id, _invoke(fn, msg.get("params"))) + except TypeError as e: + return dumps_error(req_id, str(e), INVALID_PARAMS) + except Exception as e: + return dumps_error(req_id, str(e), SERVER_ERROR) diff --git a/system/tests/__init__.py b/openpilot/system/athena/tests/__init__.py similarity index 100% rename from system/tests/__init__.py rename to openpilot/system/athena/tests/__init__.py diff --git a/system/athena/tests/helpers.py b/openpilot/system/athena/tests/helpers.py similarity index 100% rename from system/athena/tests/helpers.py rename to openpilot/system/athena/tests/helpers.py diff --git a/system/athena/tests/test_athenad.py b/openpilot/system/athena/tests/test_athenad.py similarity index 87% rename from system/athena/tests/test_athenad.py rename to openpilot/system/athena/tests/test_athenad.py index dd82325815..8c090b93af 100644 --- a/system/athena/tests/test_athenad.py +++ b/openpilot/system/athena/tests/test_athenad.py @@ -14,22 +14,22 @@ from datetime import datetime, timedelta from websocket import ABNF from websocket._exceptions import WebSocketConnectionClosedException -from cereal import messaging +from openpilot.cereal import messaging from openpilot.common.params import Params from openpilot.common.timeout import Timeout from openpilot.system.athena import athenad -from openpilot.system.athena.athenad import MAX_RETRY_COUNT, dispatcher +from openpilot.system.athena.athenad import MAX_RETRY_COUNT, UPLOAD_SESS, dispatcher from openpilot.system.athena.tests.helpers import HTTPRequestHandler, MockWebsocket, MockApi, EchoSocket from openpilot.selfdrive.test.helpers import http_server_context -from openpilot.system.hardware.hw import Paths +from openpilot.common.hardware.hw import Paths def seed_athena_server(host, port): with Timeout(2, 'HTTP Server seeding failed'): while True: try: - requests.put(f'http://{host}:{port}/qlog.zst', data='', timeout=10) + UPLOAD_SESS.put(f'http://{host}:{port}/qlog.zst', data='', timeout=10) break except requests.exceptions.ConnectionError: time.sleep(0.1) @@ -60,21 +60,21 @@ class TestAthenadMethods: @classmethod def setup_class(cls): cls.SOCKET_PORT = 45454 - athenad.Api = MockApi + athenad.Api = MockApi # ty: ignore[invalid-assignment] # test double athenad.LOCAL_PORT_WHITELIST = {cls.SOCKET_PORT} def setup_method(self): self.default_params = { "DongleId": "0000000000000000", - "GithubSshKeys": b"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC307aE+nuHzTAgaJhzSf5v7ZZQW9gaperjhCmyPyl4PzY7T1mDGenTlVTN7yoVFZ9UfO9oMQqo0n1OwDIiqbIFxqnhrHU0cYfj88rI85m5BEKlNu5RdaVTj1tcbaPpQc5kZEolaI1nDDjzV0lwS7jo5VYDHseiJHlik3HH1SgtdtsuamGR2T80q1SyW+5rHoMOJG73IH2553NnWuikKiuikGHUYBd00K1ilVAK2xSiMWJp55tQfZ0ecr9QjEsJ+J/efL4HqGNXhffxvypCXvbUYAFSddOwXUPo5BTKevpxMtH+2YrkpSjocWA04VnTYFiPG6U4ItKmbLOTFZtPzoez private", # noqa: E501 - "GithubUsername": b"commaci", - "AthenadUploadQueue": '[]', + "GithubSshKeys": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC307aE+nuHzTAgaJhzSf5v7ZZQW9gaperjhCmyPyl4PzY7T1mDGenTlVTN7yoVFZ9UfO9oMQqo0n1OwDIiqbIFxqnhrHU0cYfj88rI85m5BEKlNu5RdaVTj1tcbaPpQc5kZEolaI1nDDjzV0lwS7jo5VYDHseiJHlik3HH1SgtdtsuamGR2T80q1SyW+5rHoMOJG73IH2553NnWuikKiuikGHUYBd00K1ilVAK2xSiMWJp55tQfZ0ecr9QjEsJ+J/efL4HqGNXhffxvypCXvbUYAFSddOwXUPo5BTKevpxMtH+2YrkpSjocWA04VnTYFiPG6U4ItKmbLOTFZtPzoez private", # noqa: E501 + "GithubUsername": "commaci", + "AthenadUploadQueue": [], } self.params = Params() for k, v in self.default_params.items(): - self.params.put(k, v) - self.params.put_bool("GsmMetered", True) + self.params.put(k, v, block=True) + self.params.put_bool("GsmMetered", True, block=True) athenad.upload_queue = queue.PriorityQueue() athenad.cur_upload_items.clear() @@ -91,13 +91,13 @@ class TestAthenadMethods: @staticmethod def _wait_for_upload(): - now = time.time() - while time.time() - now < 5: + now = time.monotonic() + while time.monotonic() - now < 5: if athenad.upload_queue.qsize() == 0: break @staticmethod - def _create_file(file: str, parent: str = None, data: bytes = b'') -> str: + def _create_file(file: str, parent: str | None = None, data: bytes = b'') -> str: fn = os.path.join(Paths.log_root() if parent is None else parent, file) os.makedirs(os.path.dirname(fn), exist_ok=True) with open(fn, 'wb') as f: @@ -190,11 +190,11 @@ class TestAthenadMethods: fn = self._create_file('qlog', data=os.urandom(10000 * 1024)) upload_fn = fn + ('.zst' if compress else '') - item = athenad.UploadItem(path=upload_fn, url="http://localhost:1238", headers={}, created_at=int(time.time()*1000), id='') + item = athenad.UploadItem(path=upload_fn, url="http://localhost:1238", headers={}, created_at=int(time.time()*1000), id='') # noqa: TID251 with pytest.raises(requests.exceptions.ConnectionError): athenad._do_upload(item) - item = athenad.UploadItem(path=upload_fn, url=f"{host}/qlog.zst", headers={}, created_at=int(time.time()*1000), id='') + item = athenad.UploadItem(path=upload_fn, url=f"{host}/qlog.zst", headers={}, created_at=int(time.time()*1000), id='') # noqa: TID251 resp = athenad._do_upload(item) assert resp.status_code == 201 @@ -226,7 +226,7 @@ class TestAthenadMethods: @with_upload_handler def test_upload_handler(self, host): fn = self._create_file('qlog.zst') - item = athenad.UploadItem(path=fn, url=f"{host}/qlog.zst", headers={}, created_at=int(time.time()*1000), id='', allow_cellular=True) + item = athenad.UploadItem(path=fn, url=f"{host}/qlog.zst", headers={}, created_at=int(time.time()*1000), id='', allow_cellular=True) # noqa: TID251 athenad.upload_queue.put_nowait(item) self._wait_for_upload() @@ -239,10 +239,10 @@ class TestAthenadMethods: @pytest.mark.parametrize("status,retry", [(500,True), (412,False)]) @with_upload_handler def test_upload_handler_retry(self, mocker, host, status, retry): - mock_put = mocker.patch('requests.put') + mock_put = mocker.patch('openpilot.system.athena.athenad.UPLOAD_SESS.put') mock_put.return_value.__enter__.return_value.status_code = status fn = self._create_file('qlog.zst') - item = athenad.UploadItem(path=fn, url=f"{host}/qlog.zst", headers={}, created_at=int(time.time()*1000), id='', allow_cellular=True) + item = athenad.UploadItem(path=fn, url=f"{host}/qlog.zst", headers={}, created_at=int(time.time()*1000), id='', allow_cellular=True) # noqa: TID251 athenad.upload_queue.put_nowait(item) self._wait_for_upload() @@ -257,7 +257,7 @@ class TestAthenadMethods: def test_upload_handler_timeout(self): """When an upload times out or fails to connect it should be placed back in the queue""" fn = self._create_file('qlog.zst') - item = athenad.UploadItem(path=fn, url="http://localhost:44444/qlog.zst", headers={}, created_at=int(time.time()*1000), id='', allow_cellular=True) + item = athenad.UploadItem(path=fn, url="http://localhost:44444/qlog.zst", headers={}, created_at=int(time.time()*1000), id='', allow_cellular=True) # noqa: TID251 item_no_retry = replace(item, retry_count=MAX_RETRY_COUNT) athenad.upload_queue.put_nowait(item_no_retry) @@ -278,7 +278,7 @@ class TestAthenadMethods: @with_upload_handler def test_cancel_upload(self): item = athenad.UploadItem(path="qlog.zst", url="http://localhost:44444/qlog.zst", headers={}, - created_at=int(time.time()*1000), id='id', allow_cellular=True) + created_at=int(time.time()*1000), id='id', allow_cellular=True) # noqa: TID251 athenad.upload_queue.put_nowait(item) dispatcher["cancelUpload"](item.id) @@ -312,7 +312,7 @@ class TestAthenadMethods: @with_upload_handler def test_list_upload_queue_current(self, host: str): fn = self._create_file('qlog.zst') - item = athenad.UploadItem(path=fn, url=f"{host}/qlog.zst", headers={}, created_at=int(time.time()*1000), id='', allow_cellular=True) + item = athenad.UploadItem(path=fn, url=f"{host}/qlog.zst", headers={}, created_at=int(time.time()*1000), id='', allow_cellular=True) # noqa: TID251 athenad.upload_queue.put_nowait(item) self._wait_for_upload() @@ -331,7 +331,7 @@ class TestAthenadMethods: path=fp, url=f"http://localhost:44444/{fn}", headers={}, - created_at=int(time.time()*1000), + created_at=int(time.time()*1000), # noqa: TID251 id='', allow_cellular=True, priority=i @@ -343,7 +343,7 @@ class TestAthenadMethods: def test_list_upload_queue(self): item = athenad.UploadItem(path="qlog.zst", url="http://localhost:44444/qlog.zst", headers={}, - created_at=int(time.time()*1000), id='id', allow_cellular=True) + created_at=int(time.time()*1000), id='id', allow_cellular=True) # noqa: TID251 athenad.upload_queue.put_nowait(item) items = dispatcher["listUploadQueue"]() @@ -351,18 +351,20 @@ class TestAthenadMethods: assert items[0] == asdict(item) assert not items[0]['current'] + assert item.id is not None athenad.cancelled_uploads.add(item.id) items = dispatcher["listUploadQueue"]() assert len(items) == 0 def test_upload_queue_persistence(self): - item1 = athenad.UploadItem(path="_", url="_", headers={}, created_at=int(time.time()), id='id1') - item2 = athenad.UploadItem(path="_", url="_", headers={}, created_at=int(time.time()), id='id2') + item1 = athenad.UploadItem(path="_", url="_", headers={}, created_at=int(time.time()), id='id1') # noqa: TID251 + item2 = athenad.UploadItem(path="_", url="_", headers={}, created_at=int(time.time()), id='id2') # noqa: TID251 athenad.upload_queue.put_nowait(item1) athenad.upload_queue.put_nowait(item2) # Ensure canceled items are not persisted + assert item2.id is not None athenad.cancelled_uploads.add(item2.id) # serialize item @@ -400,11 +402,11 @@ class TestAthenadMethods: def test_get_ssh_authorized_keys(self): keys = dispatcher["getSshAuthorizedKeys"]() - assert keys == self.default_params["GithubSshKeys"].decode('utf-8') + assert keys == self.default_params["GithubSshKeys"] def test_get_github_username(self): keys = dispatcher["getGithubUsername"]() - assert keys == self.default_params["GithubUsername"].decode('utf-8') + assert keys == self.default_params["GithubUsername"] def test_get_version(self): resp = dispatcher["getVersion"]() @@ -422,11 +424,11 @@ class TestAthenadMethods: try: # with params athenad.recv_queue.put_nowait(json.dumps({"method": "echo", "params": ["hello"], "jsonrpc": "2.0", "id": 0})) - resp = athenad.send_queue.get(timeout=3) + _, _, resp = athenad.send_queue.get(timeout=3) assert json.loads(resp) == {'result': 'hello', 'id': 0, 'jsonrpc': '2.0'} # without params athenad.recv_queue.put_nowait(json.dumps({"method": "getNetworkType", "jsonrpc": "2.0", "id": 0})) - resp = athenad.send_queue.get(timeout=3) + _, _, resp = athenad.send_queue.get(timeout=3) assert json.loads(resp) == {'result': 1, 'id': 0, 'jsonrpc': '2.0'} # log forwarding athenad.recv_queue.put_nowait(json.dumps({'result': {'success': 1}, 'id': 0, 'jsonrpc': '2.0'})) @@ -437,7 +439,7 @@ class TestAthenadMethods: thread.join() def test_get_logs_to_send_sorted(self): - fl = list() + fl = [] for i in range(10): file = f'swaglog.{i:010}' self._create_file(file, Paths.swaglog_root()) diff --git a/system/athena/tests/test_athenad_ping.py b/openpilot/system/athena/tests/test_athenad_ping.py similarity index 91% rename from system/athena/tests/test_athenad_ping.py rename to openpilot/system/athena/tests/test_athenad_ping.py index 025df7d614..44a6b8a56b 100644 --- a/system/athena/tests/test_athenad_ping.py +++ b/openpilot/system/athena/tests/test_athenad_ping.py @@ -7,8 +7,7 @@ from typing import cast from openpilot.common.params import Params from openpilot.common.timeout import Timeout from openpilot.system.athena import athenad -from openpilot.system.manager.helpers import write_onroad_params -from openpilot.system.hardware import TICI +from openpilot.common.hardware import TICI TIMEOUT_TOLERANCE = 20 # seconds @@ -28,7 +27,7 @@ class TestAthenadPing: exit_event: threading.Event def _get_ping_time(self) -> str | None: - return cast(str | None, self.params.get("LastAthenaPingTime", encoding="utf-8")) + return cast(str | None, self.params.get("LastAthenaPingTime")) def _clear_ping_time(self) -> None: self.params.remove("LastAthenaPingTime") @@ -42,7 +41,7 @@ class TestAthenadPing: def setup_method(self) -> None: self.params = Params() - self.dongle_id = self.params.get("DongleId", encoding="utf-8") + self.dongle_id = self.params.get("DongleId") wifi_radio(True) self._clear_ping_time() @@ -93,10 +92,10 @@ class TestAthenadPing: @pytest.mark.skipif(not TICI, reason="only run on desk") def test_offroad(self, subtests, mocker) -> None: - write_onroad_params(False, self.params) + self.params.put_bool("IsOffroad", True, block=True) self.assertTimeout(60 + TIMEOUT_TOLERANCE, subtests, mocker) # based using TCP keepalive settings @pytest.mark.skipif(not TICI, reason="only run on desk") def test_onroad(self, subtests, mocker) -> None: - write_onroad_params(True, self.params) + self.params.put_bool("IsOffroad", False, block=True) self.assertTimeout(21 + TIMEOUT_TOLERANCE, subtests, mocker) diff --git a/system/athena/tests/test_registration.py b/openpilot/system/athena/tests/test_registration.py similarity index 88% rename from system/athena/tests/test_registration.py rename to openpilot/system/athena/tests/test_registration.py index c1dabb78ec..bb1523de80 100644 --- a/system/athena/tests/test_registration.py +++ b/openpilot/system/athena/tests/test_registration.py @@ -5,7 +5,7 @@ from pathlib import Path from openpilot.common.params import Params from openpilot.system.athena.registration import register, UNREGISTERED_DONGLE_ID from openpilot.system.athena.tests.helpers import MockResponse -from openpilot.system.hardware.hw import Paths +from openpilot.common.hardware.hw import Paths class TestRegistration: @@ -37,7 +37,7 @@ class TestRegistration: dongle = "DONGLE_ID_123" m = mocker.patch("openpilot.system.athena.registration.api_get", autospec=True) for persist, params in [(True, True), (True, False), (False, True)]: - self.params.put("DongleId", dongle if params else "") + self.params.put("DongleId", dongle if params else "", block=True) with open(self.dongle_id, "w") as f: f.write(dongle if persist else "") assert register() == dongle @@ -49,7 +49,7 @@ class TestRegistration: dongle = register() assert m.call_count == 0 assert dongle == UNREGISTERED_DONGLE_ID - assert self.params.get("DongleId", encoding='utf-8') == dongle + assert self.params.get("DongleId") == dongle def test_missing_cache(self, mocker): # keys exist but no dongle id @@ -63,7 +63,7 @@ class TestRegistration: # call again, shouldn't hit the API this time assert register() == dongle assert m.call_count == 1 - assert self.params.get("DongleId", encoding='utf-8') == dongle + assert self.params.get("DongleId") == dongle def test_unregistered(self, mocker): # keys exist, but unregistered @@ -73,4 +73,4 @@ class TestRegistration: dongle = register() assert m.call_count == 1 assert dongle == UNREGISTERED_DONGLE_ID - assert self.params.get("DongleId", encoding='utf-8') == dongle + assert self.params.get("DongleId") == dongle diff --git a/openpilot/system/camerad/SConscript b/openpilot/system/camerad/SConscript new file mode 100644 index 0000000000..c28330b32c --- /dev/null +++ b/openpilot/system/camerad/SConscript @@ -0,0 +1,11 @@ +Import('env', 'arch', 'messaging', 'common', 'visionipc') + +libs = [common, messaging, visionipc] + +if arch != "Darwin": + camera_obj = env.Object(['cameras/camera_qcom2.cc', 'cameras/camera_common.cc', 'cameras/spectra.cc', + 'cameras/cdm.cc', 'sensors/ox03c10.cc', 'sensors/os04c10.cc']) + env.Program('camerad', ['main.cc', camera_obj], LIBS=libs) + +if GetOption("extras") and arch == "x86_64": + env.Program('test/test_ae_gray', ['test/test_ae_gray.cc', camera_obj], LIBS=libs) diff --git a/system/ui/lib/__init__.py b/openpilot/system/camerad/__init__.py similarity index 100% rename from system/ui/lib/__init__.py rename to openpilot/system/camerad/__init__.py diff --git a/openpilot/system/camerad/cameras/bps_blobs.h b/openpilot/system/camerad/cameras/bps_blobs.h new file mode 100644 index 0000000000..ee31698e7f --- /dev/null +++ b/openpilot/system/camerad/cameras/bps_blobs.h @@ -0,0 +1,30 @@ +#include +#include + + +/* ********************************************************** + THIS FILE IS AUTO-GENERATED, DO NOT EDIT DIRECTLY! + ********************************************************** */ + + +unsigned char bps_cfg[4][768] = { +{ /* placeholder */ }, +{ /* placeholder */ }, + {0x3, 0x0, 0x0, 0x0, 0x88, 0x7, 0x0, 0x0, 0xB8, 0x4, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x50, 0xB, 0x0, 0x0, 0xB8, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x14, 0x0, 0x0, 0x0, 0x88, 0x7, 0x0, 0x0, 0xB8, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8, 0x0, 0x0, 0xC0, 0x4, 0x0, 0x0, 0x0, 0x8, 0x0, 0x0, 0x60, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, + {0x3, 0x0, 0x0, 0x0, 0x80, 0xA, 0x0, 0x0, 0xF0, 0x5, 0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC0, 0xF, 0x0, 0x0, 0xF0, 0x5, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x14, 0x0, 0x0, 0x0, 0x80, 0xA, 0x0, 0x0, 0xF0, 0x5, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x80, 0xA, 0x0, 0x0, 0x0, 0x6, 0x0, 0x0, 0x80, 0xA, 0x0, 0x0, 0x0, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x14, 0x0, 0x0, 0x0, 0x40, 0x5, 0x0, 0x0, 0xF8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x80, 0x5, 0x0, 0x0, 0x0, 0x3, 0x0, 0x0, 0x80, 0x5, 0x0, 0x0, 0x80, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, +}; + +unsigned char bps_striping_output[4][0xc58] = { +{ /* placeholder */ }, +{ /* placeholder */ }, + {0x5, 0x0, 0x6, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x4, 0x0, 0x0, 0xFF, 0xFF, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x4, 0x0, 0x0, 0xB7, 0x4, 0x0, 0x0, 0xB7, 0x4, 0x0, 0x0, 0x5B, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x4, 0x0, 0x0, 0x5B, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0xB8, 0x4, 0x5C, 0x2, 0x0, 0x0, 0x3, 0x0, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x5, 0x0, 0x0, 0x0, 0x70, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC0, 0x89, 0x23, 0x0, 0x1, 0x0, 0x0, 0x0, 0xCC, 0x5, 0x87, 0x7, 0x0, 0x0, 0x0, 0x0, 0xD0, 0x5, 0x87, 0x7, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0xB, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0xB8, 0x1, 0xDC, 0x0, 0x0, 0x0, 0x3, 0x0, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8, 0x2, 0xA4, 0xFD, 0x50, 0xB1, 0x9, 0x0, 0x8, 0x0, 0x33, 0x0, 0x8, 0x2, 0xA4, 0xFD, 0x50, 0xB1, 0x9, 0x0, 0x8, 0x0, 0x33, 0x0, 0x0, 0x0, 0x0, 0x0, 0x6, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xE, 0x2, 0xA6, 0xFD, 0x68, 0xC0, 0x9, 0x0, 0x8, 0x0, 0x34, 0x0, 0xD0, 0x5, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x1C, 0x8, 0x0, 0x14, 0x4, 0xD3, 0x5, 0x0, 0x0, 0x0, 0x0, 0x18, 0x4, 0xCF, 0x5, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0xB, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0xB8, 0x1, 0xDC, 0x0, 0x0, 0x0, 0x3, 0x0, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x50, 0x0, 0xA4, 0xFD, 0x10, 0xAA, 0x5, 0x0, 0x8, 0x0, 0x33, 0x0, 0x50, 0x0, 0xA4, 0xFD, 0x10, 0xAA, 0x5, 0x0, 0x8, 0x0, 0x33, 0x0, 0x0, 0x0, 0x0, 0x0, 0xA, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x56, 0x0, 0xA6, 0xFD, 0x88, 0xA4, 0x5, 0x0, 0x8, 0x0, 0x34, 0x0, 0x18, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x1C, 0x8, 0x0, 0x5C, 0x2, 0x1B, 0x4, 0x0, 0x0, 0x0, 0x0, 0x60, 0x2, 0x17, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0xB, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0xB8, 0x1, 0xDC, 0x0, 0x0, 0x0, 0x3, 0x0, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x98, 0xFE, 0xA4, 0xFD, 0x50, 0x8B, 0x7, 0x0, 0x8, 0x0, 0x33, 0x0, 0x98, 0xFE, 0xA4, 0xFD, 0x50, 0x8B, 0x7, 0x0, 0x8, 0x0, 0x33, 0x0, 0x0, 0x0, 0x0, 0x0, 0xE, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x9E, 0xFE, 0xA6, 0xFD, 0x28, 0x71, 0x7, 0x0, 0x8, 0x0, 0x34, 0x0, 0x60, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x1C, 0x8, 0x0, 0xC0, 0x0, 0x63, 0x2, 0x0, 0x0, 0x0, 0x0, 0xC4, 0x0, 0x5F, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0xB, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x9B, 0x1, 0x0, 0x0, 0x9B, 0x1, 0x0, 0x0, 0x9B, 0x1, 0x0, 0x0, 0x9B, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x9B, 0x1, 0x0, 0x0, 0x9B, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0x9C, 0x1, 0xCE, 0x0, 0x0, 0x0, 0x3, 0x0, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFC, 0xFC, 0xA4, 0xFD, 0x20, 0xA9, 0xE, 0x0, 0x8, 0x0, 0x33, 0x0, 0xFC, 0xFC, 0xA4, 0xFD, 0x20, 0xA9, 0xE, 0x0, 0x8, 0x0, 0x33, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2, 0xFD, 0xA6, 0xFD, 0xA8, 0x7B, 0xE, 0x0, 0x8, 0x0, 0x34, 0x0, 0xC4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x20, 0x98, 0x7, 0x0, 0x0, 0x0, 0xC7, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0xB, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC3, 0x0, 0x0, 0x0, 0xC3, 0x0, 0x0, 0x0, 0xC3, 0x0, 0x0, 0x0, 0xC3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC3, 0x0, 0x0, 0x0, 0xC3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0xC4, 0x0, 0x62, 0x0, 0x0, 0x0, 0x3, 0x0, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x3C, 0xFC, 0xA4, 0xFD, 0x20, 0xBF, 0x13, 0x0, 0x8, 0x0, 0x33, 0x0, 0x3C, 0xFC, 0xA4, 0xFD, 0x20, 0xBF, 0x13, 0x0, 0x8, 0x0, 0x33, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x3E, 0xFC, 0xA6, 0xFD, 0xA8, 0xA6, 0x13, 0x0, 0x8, 0x0, 0x34, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xE0, 0x9C, 0x3, 0x0, 0xEC, 0x3, 0x1, 0x0, 0x5D, 0x59, 0xAB, 0x0, 0xC8, 0xFC, 0xFB, 0x40, 0x3, 0x0, 0x0, 0x0, 0x0, 0xFC, 0x7F, 0x40, 0xAC, 0x1F, 0x84, 0x40, 0x0, 0x20, 0x4E, 0x0, 0xAB, 0xAA, 0xAA, 0xAA, 0x40, 0xD9, 0xFB, 0x40, 0x0, 0x0, 0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC8, 0xED, 0x80, 0x40, 0x11, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x9F, 0x9, 0x0, 0x0, 0xB8, 0x2B, 0x6B, 0x15, 0xC0, 0x2A, 0x84, 0x40, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFC, 0x7F, 0x40, 0x0, 0x5, 0x1, 0x0, 0x8, 0xFC, 0x7F, 0x40, 0x74, 0xFC, 0x7F, 0x40, 0x5C, 0xFC, 0x7F, 0x40, 0xCC, 0xA8, 0x81, 0x40, 0x8, 0xFC, 0x7F, 0x40, 0x64, 0x2A, 0x84, 0x40, 0x3, 0x0, 0x0, 0x0, 0x30, 0xEE, 0x80, 0x40, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x8, 0x29, 0x84, 0x40, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC0, 0x2A, 0x84, 0x40, 0x8, 0x29, 0x84, 0x40, 0xFF, 0xFF, 0xFF, 0xFF, 0xA0, 0x9, 0x0, 0x0, 0xF8, 0x22, 0xFC, 0x40, 0xB8, 0x16, 0x80, 0x40, 0xD0, 0x34, 0x84, 0x40, 0x1, 0xB0, 0xAB, 0x40, 0xAC, 0x7, 0x80, 0x40, 0xD0, 0x1D, 0x3, 0x41, 0x30, 0x40, 0x1, 0x0, 0xD0, 0x34, 0x84, 0x40, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x1, 0x0, 0xA4, 0xFC, 0x7F, 0x40, 0x0, 0x0, 0x0, 0x0, 0xC, 0x40, 0x1, 0x0, 0xD0, 0x34, 0x84, 0x40, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x1, 0x0, 0x8C, 0xB, 0x80, 0x34, 0x31, 0x32, 0x31, 0x36, 0x30, 0xEE, 0x80, 0x40, 0xA8, 0xFC, 0x7F, 0x40, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x1, 0x0, 0x58, 0x7, 0x80, 0x40, 0x4C, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x1, 0x0, 0x8C, 0xB, 0x80, 0x40, 0xC0, 0x4C, 0x0, 0x41, 0x4C, 0x0, 0x0, 0x0, 0x9C, 0xFC, 0x7F, 0x40, 0x78, 0x22, 0x1, 0x0, 0xC4, 0x15, 0x1, 0x0, 0xC0, 0x22, 0x1, 0x0, 0x0, 0xA1, 0x0, 0x0, 0x0, 0xA1, 0x0, 0x0, 0xC0, 0x22, 0x1, 0x0, 0xB4, 0x7, 0x80, 0x40, 0xAC, 0x7, 0x80, 0x40, 0xB0, 0x7, 0x80, 0x40, 0x0, 0x0, 0x0, 0x0}, + {0x7, 0x0, 0x8, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0xEF, 0x5, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xEF, 0x5, 0x0, 0x0, 0xFF, 0xFF, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0xF7, 0x2, 0x0, 0x0, 0xEF, 0x5, 0x0, 0x0, 0xEF, 0x5, 0x0, 0x0, 0xEF, 0x5, 0x0, 0x0, 0xF7, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xEF, 0x5, 0x0, 0x0, 0xF7, 0x2, 0x0, 0x0, 0xEF, 0x5, 0x0, 0x0, 0xF7, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xF7, 0x2, 0x0, 0x0, 0x7B, 0x1, 0x0, 0x0, 0xEF, 0x5, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0xF0, 0x5, 0xF8, 0x2, 0x0, 0x0, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0xF8, 0x2, 0x7C, 0x1, 0x0, 0x0, 0x3, 0x0, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0xF0, 0x5, 0xF8, 0x2, 0x0, 0x0, 0x3, 0x0, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x7, 0x0, 0x0, 0x0, 0x70, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x3, 0x0, 0x88, 0x7, 0xB8, 0x4, 0x14, 0x0, 0x88, 0x7, 0xB8, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x74, 0x16, 0x80, 0x40, 0x52, 0x5, 0x1, 0x0, 0x1A, 0x3, 0x0, 0x0, 0xC4, 0xED, 0x80, 0x40, 0x98, 0x1, 0x0, 0x0, 0x11, 0x7B, 0x9C, 0x7C, 0x11, 0x7B, 0x9C, 0x7C, 0x14, 0x69, 0x69, 0xD, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xE8, 0x8A, 0xFC, 0x40, 0xB2, 0x4, 0x1, 0x0, 0x11, 0x7B, 0x9C, 0x7C, 0xBC, 0x3, 0x1, 0x0, 0xD8, 0xE3, 0xE4, 0x3, 0xC8, 0xFC, 0xFB, 0x40, 0x3, 0x0, 0x0, 0x0, 0x60, 0xF2, 0x7F, 0x40, 0x0, 0x58, 0x3E, 0x0, 0x1, 0x20, 0x4E, 0x0, 0xC4, 0x8, 0x7F, 0xA, 0x0, 0x0, 0x0, 0x0, 0xC8, 0x8, 0x7F, 0xA, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0xB, 0x64, 0x4, 0x3F, 0x5, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xDB, 0x0, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xDB, 0x0, 0x0, 0x0, 0x6D, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0xB8, 0x1, 0xDC, 0x0, 0x0, 0x0, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0xDC, 0x0, 0x6E, 0x0, 0x0, 0x0, 0x3, 0x0, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0xB8, 0x1, 0xDC, 0x0, 0x0, 0x0, 0x3, 0x0, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x84, 0x3, 0x8, 0xFD, 0x50, 0x2C, 0x15, 0x0, 0x9, 0x0, 0x38, 0x0, 0x84, 0x3, 0x8, 0xFD, 0x50, 0x2C, 0x15, 0x0, 0x9, 0x0, 0x38, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8A, 0x3, 0xA, 0xFD, 0xC8, 0x4A, 0x15, 0x0, 0x9, 0x0, 0x38, 0x0, 0xC8, 0x8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x80, 0x34, 0xA, 0x0, 0xC, 0x7, 0xCB, 0x8, 0x0, 0x0, 0x0, 0x0, 0x10, 0x7, 0xC7, 0x8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0xB, 0x88, 0x3, 0x63, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xDB, 0x0, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xDB, 0x0, 0x0, 0x0, 0x6D, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0xB8, 0x1, 0xDC, 0x0, 0x0, 0x0, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0xDC, 0x0, 0x6E, 0x0, 0x0, 0x0, 0x3, 0x0, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0xB8, 0x1, 0xDC, 0x0, 0x0, 0x0, 0x3, 0x0, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xCC, 0x1, 0x8, 0xFD, 0xD0, 0xA, 0xC, 0x0, 0x9, 0x0, 0x38, 0x0, 0xCC, 0x1, 0x8, 0xFD, 0xD0, 0xA, 0xC, 0x0, 0x9, 0x0, 0x38, 0x0, 0x0, 0x0, 0x0, 0x0, 0x6, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xD2, 0x1, 0xA, 0xFD, 0xA8, 0x14, 0xC, 0x0, 0x9, 0x0, 0x38, 0x0, 0x10, 0x7, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x80, 0x34, 0xA, 0x0, 0x54, 0x5, 0x13, 0x7, 0x0, 0x0, 0x0, 0x0, 0x58, 0x5, 0xF, 0x7, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0xB, 0xAC, 0x2, 0x87, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xDB, 0x0, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xDB, 0x0, 0x0, 0x0, 0x6D, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0xB8, 0x1, 0xDC, 0x0, 0x0, 0x0, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0xDC, 0x0, 0x6E, 0x0, 0x0, 0x0, 0x3, 0x0, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0xB8, 0x1, 0xDC, 0x0, 0x0, 0x0, 0x3, 0x0, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x14, 0x0, 0x8, 0xFD, 0xD0, 0xD1, 0x8, 0x0, 0x9, 0x0, 0x38, 0x0, 0x14, 0x0, 0x8, 0xFD, 0xD0, 0xD1, 0x8, 0x0, 0x9, 0x0, 0x38, 0x0, 0x0, 0x0, 0x0, 0x0, 0xA, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1A, 0x0, 0xA, 0xFD, 0x8, 0xC7, 0x8, 0x0, 0x9, 0x0, 0x38, 0x0, 0x58, 0x5, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x80, 0x34, 0xA, 0x0, 0x9C, 0x3, 0x5B, 0x5, 0x0, 0x0, 0x0, 0x0, 0xA0, 0x3, 0x57, 0x5, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0xB, 0xD0, 0x1, 0xAB, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xDB, 0x0, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xDB, 0x0, 0x0, 0x0, 0x6D, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0xB8, 0x1, 0xDC, 0x0, 0x0, 0x0, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0xDC, 0x0, 0x6E, 0x0, 0x0, 0x0, 0x3, 0x0, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0xB8, 0x1, 0xDC, 0x0, 0x0, 0x0, 0x3, 0x0, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x1, 0x1, 0x0, 0x40, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x5C, 0xFE, 0x8, 0xFD, 0x50, 0x81, 0xB, 0x0, 0x9, 0x0, 0x38, 0x0, 0x5C, 0xFE, 0x8, 0xFD, 0x50, 0x81, 0xB, 0x0, 0x9, 0x0, 0x38, 0x0, 0x0, 0x0, 0x0, 0x0, 0xE, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x62, 0xFE, 0xA, 0xFD, 0xE8, 0x61, 0xB, 0x0, 0x9, 0x0, 0x38, 0x0, 0xA0, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x80, 0x34, 0xA, 0x0, 0xE4, 0x1, 0xA3, 0x3, 0x0, 0x0, 0x0, 0x0, 0xE8, 0x1, 0x9F, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0xB, 0xF4, 0x0, 0xCF, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xDB, 0x0, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xDB, 0x0, 0x0, 0x0, 0x6D, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0xB8, 0x1, 0xDC, 0x0, 0x0, 0x0, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0xDC, 0x0, 0x6E, 0x0, 0x0, 0x0, 0x3, 0x0, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0xB8, 0x1, 0xDC, 0x0, 0x0, 0x0, 0x3, 0x0, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xA4, 0xFC, 0x8, 0xFD, 0x50, 0x19, 0x14, 0x0, 0x9, 0x0, 0x38, 0x0, 0xA4, 0xFC, 0x8, 0xFD, 0x50, 0x19, 0x14, 0x0, 0x9, 0x0, 0x38, 0x0, 0x0, 0x0, 0x0, 0x0, 0x12, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xAA, 0xFC, 0xA, 0xFD, 0x48, 0xE5, 0x13, 0x0, 0x9, 0x0, 0x38, 0x0, 0xE8, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x80, 0x34, 0xA, 0x0, 0xC0, 0x0, 0xEB, 0x1, 0x0, 0x0, 0x0, 0x0, 0xC4, 0x0, 0xE7, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0xB, 0x62, 0x0, 0xF3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x23, 0x1, 0x0, 0x0, 0x23, 0x1, 0x0, 0x0, 0x23, 0x1, 0x0, 0x0, 0x23, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x23, 0x1, 0x0, 0x0, 0x91, 0x0, 0x0, 0x0, 0x23, 0x1, 0x0, 0x0, 0x23, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x91, 0x0, 0x0, 0x0, 0x48, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0x24, 0x1, 0x92, 0x0, 0x0, 0x0, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0x92, 0x0, 0x49, 0x0, 0x0, 0x0, 0x3, 0x0, 0x1, 0x0, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0x24, 0x1, 0x92, 0x0, 0x0, 0x0, 0x3, 0x0, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x80, 0xFB, 0x8, 0xFD, 0x40, 0x10, 0x1D, 0x0, 0x9, 0x0, 0x38, 0x0, 0x80, 0xFB, 0x8, 0xFD, 0x40, 0x10, 0x1D, 0x0, 0x9, 0x0, 0x38, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x86, 0xFB, 0xA, 0xFD, 0x88, 0xCE, 0x1C, 0x0, 0x9, 0x0, 0x38, 0x0, 0xC4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC0, 0xC5, 0x6, 0x0, 0x0, 0x0, 0xC7, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0xB, 0x0, 0x0, 0x61, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC3, 0x0, 0x0, 0x0, 0xC3, 0x0, 0x0, 0x0, 0xC3, 0x0, 0x0, 0x0, 0xC3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC3, 0x0, 0x0, 0x0, 0x61, 0x0, 0x0, 0x0, 0xC3, 0x0, 0x0, 0x0, 0xC3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x61, 0x0, 0x0, 0x0, 0x30, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0xC4, 0x0, 0x62, 0x0, 0x0, 0x0, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0x62, 0x0, 0x31, 0x0, 0x0, 0x0, 0x3, 0x0, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0xC4, 0x0, 0x62, 0x0, 0x0, 0x0, 0x3, 0x0, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x1, 0x1, 0x0, 0x40, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC0, 0xFA, 0x8, 0xFD, 0x40, 0x60, 0x24, 0x0, 0x9, 0x0, 0x38, 0x0, 0xC0, 0xFA, 0x8, 0xFD, 0x40, 0x60, 0x24, 0x0, 0x9, 0x0, 0x38, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC2, 0xFA, 0xA, 0xFD, 0x68, 0x3F, 0x24, 0x0, 0x9, 0x0, 0x38, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC0, 0x8B, 0x4, 0x0, 0xEC, 0x3, 0x1, 0x0, 0x58, 0xC, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x6, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8, 0x50, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x7, 0x0, 0x0, 0x0, 0xFC, 0xC7, 0x10, 0x41, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC0, 0x10, 0x41, 0x0, 0x0, 0x0, 0x0, 0x57, 0xC, 0x0, 0x0, 0x69, 0x0, 0x0, 0x0, 0x61, 0x0, 0x0, 0x0, 0x6E, 0x0, 0x0, 0x0, 0x77, 0x0, 0x0, 0x0, 0x7C, 0x0, 0x0, 0x0, 0x8C, 0x1, 0x0, 0x0, 0x31, 0x0, 0x0, 0x0, 0xA4, 0x51, 0x1, 0x0, 0x58, 0x3, 0x0, 0x0, 0x8, 0xFC, 0x7F, 0x40, 0x64, 0x2A, 0x84, 0x40, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC0, 0x10, 0x41, 0x57, 0xC, 0x0, 0x0, 0x58, 0xC, 0x0, 0x0, 0xFC, 0xC7, 0x10, 0x41, 0x8A, 0x1, 0x0, 0x0, 0xD0, 0x34, 0x84, 0x40, 0x1, 0xB0, 0xAB, 0x40, 0xAC, 0x7, 0x80, 0x40, 0xD0, 0x1D, 0x3, 0x41, 0x30, 0x40, 0x1, 0x0, 0xD0, 0x34, 0x84, 0x40, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x1, 0x0, 0xA4, 0xFC, 0x7F, 0x40, 0x0, 0x0, 0x0, 0x0, 0x40, 0x5, 0x0, 0x0, 0x4C, 0x17, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC0, 0x0, 0x0, 0x0, 0x8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x35, 0x33, 0x32, 0x31, 0x36, 0x68, 0x8, 0x80, 0x40, 0xA8, 0xFC, 0x7F, 0x40, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x1, 0x0, 0x58, 0x7, 0x80, 0x40, 0xA0, 0x9, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x1, 0x0, 0x8C, 0xB, 0x80, 0x40, 0xC0, 0x4C, 0x0, 0x41, 0x0, 0x0, 0x0, 0x0, 0x9C, 0xFC, 0x7F, 0x40, 0x58, 0x7, 0x80, 0x40, 0xC4, 0x15, 0x1, 0x0, 0xC0, 0x22, 0x1, 0x0, 0xE0, 0xCF, 0x0, 0x0, 0xE0, 0xCF, 0x0, 0x0, 0xC0, 0x22, 0x1, 0x0, 0xB4, 0x7, 0x80, 0x40, 0xAC, 0x7, 0x80, 0x40, 0xB0, 0x7, 0x80, 0x40, 0x0, 0x0, 0x0, 0x0}, +}; + +unsigned char bps_settings[4][684] = { +{ /* placeholder */ }, +{ /* placeholder */ }, + {0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, + {0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, +}; + diff --git a/system/camerad/cameras/camera_common.cc b/openpilot/system/camerad/cameras/camera_common.cc similarity index 83% rename from system/camerad/cameras/camera_common.cc rename to openpilot/system/camerad/cameras/camera_common.cc index 1f6ad9b4be..329192b63a 100644 --- a/system/camerad/cameras/camera_common.cc +++ b/openpilot/system/camerad/cameras/camera_common.cc @@ -7,7 +7,7 @@ #include "system/camerad/cameras/spectra.h" -void CameraBuf::init(cl_device_id device_id, cl_context context, SpectraCamera *cam, VisionIpcServer * v, int frame_cnt, VisionStreamType type) { +void CameraBuf::init(SpectraCamera *cam, VisionIpcServer * v, int frame_cnt, VisionStreamType type) { vipc_server = v; stream_type = type; frame_buf_count = frame_cnt; @@ -21,16 +21,11 @@ void CameraBuf::init(cl_device_id device_id, cl_context context, SpectraCamera * const int raw_frame_size = (sensor->frame_height + sensor->extra_height) * sensor->frame_stride; for (int i = 0; i < frame_buf_count; i++) { camera_bufs_raw[i].allocate(raw_frame_size); - camera_bufs_raw[i].init_cl(device_id, context); } - LOGD("allocated %d CL buffers", frame_buf_count); + LOGD("allocated %d buffers", frame_buf_count); } - // the encoder HW tells us the size it wants after setting it up. - // TODO: VENUS_BUFFER_SIZE should give the size, but it's too small. dependent on encoder settings? - size_t nv12_size = (out_img_width <= 1344 ? 2900 : 2346)*cam->stride; - - vipc_server->create_buffers_with_sizes(stream_type, VIPC_BUFFER_COUNT, out_img_width, out_img_height, nv12_size, cam->stride, cam->uv_offset); + vipc_server->create_buffers_with_sizes(stream_type, VIPC_BUFFER_COUNT, out_img_width, out_img_height, cam->yuv_size, cam->stride, cam->uv_offset); LOGD("created %d YUV vipc buffers with size %dx%d", VIPC_BUFFER_COUNT, cam->stride, cam->y_height); } diff --git a/system/camerad/cameras/camera_common.h b/openpilot/system/camerad/cameras/camera_common.h similarity index 84% rename from system/camerad/cameras/camera_common.h rename to openpilot/system/camerad/cameras/camera_common.h index c26859cbc4..24f70dbcf3 100644 --- a/system/camerad/cameras/camera_common.h +++ b/openpilot/system/camerad/cameras/camera_common.h @@ -2,7 +2,7 @@ #include -#include "cereal/messaging/messaging.h" +#include "openpilot/cereal/messaging/messaging.h" #include "msgq/visionipc/visionipc_server.h" #include "common/util.h" @@ -36,7 +36,7 @@ public: CameraBuf() = default; ~CameraBuf(); - void init(cl_device_id device_id, cl_context context, SpectraCamera *cam, VisionIpcServer * v, int frame_cnt, VisionStreamType type); + void init(SpectraCamera *cam, VisionIpcServer * v, int frame_cnt, VisionStreamType type); void sendFrameToVipc(); }; diff --git a/system/camerad/cameras/camera_qcom2.cc b/openpilot/system/camerad/cameras/camera_qcom2.cc similarity index 92% rename from system/camerad/cameras/camera_qcom2.cc rename to openpilot/system/camerad/cameras/camera_qcom2.cc index 8c4602bb31..63640920db 100644 --- a/system/camerad/cameras/camera_qcom2.cc +++ b/openpilot/system/camerad/cameras/camera_qcom2.cc @@ -12,16 +12,6 @@ #include #include -#ifdef QCOM2 -#include "CL/cl_ext_qcom.h" -#else -#define CL_PRIORITY_HINT_HIGH_QCOM NULL -#define CL_CONTEXT_PRIORITY_HINT_QCOM NULL -#endif - -#include "media/cam_sensor_cmn_header.h" - -#include "common/clutil.h" #include "common/params.h" #include "common/swaglog.h" @@ -50,14 +40,14 @@ public: Rect ae_xywh = {}; float measured_grey_fraction = 0; - float target_grey_fraction = 0.3; + float target_grey_fraction = 0.125; float fl_pix = 0; std::unique_ptr pm; CameraState(SpectraMaster *master, const CameraConfig &config) : camera(master, config) {}; ~CameraState(); - void init(VisionIpcServer *v, cl_device_id device_id, cl_context ctx); + void init(VisionIpcServer *v); void update_exposure_score(float desired_ev, int exp_t, int exp_g_idx, float exp_gain); void set_camera_exposure(float grey_frac); void set_exposure_rect(); @@ -68,8 +58,8 @@ public: } }; -void CameraState::init(VisionIpcServer *v, cl_device_id device_id, cl_context ctx) { - camera.camera_open(v, device_id, ctx); +void CameraState::init(VisionIpcServer *v) { + camera.camera_open(v); if (!camera.enabled) return; @@ -89,7 +79,7 @@ void CameraState::set_exposure_rect() { // set areas for each camera, shouldn't be changed std::vector> ae_targets = { // (Rect, F) - std::make_pair((Rect){96, 250, 1734, 524}, 567.0), // wide + std::make_pair((Rect){96, 400, 1734, 524}, 567.0), // wide std::make_pair((Rect){96, 160, 1734, 986}, 2648.0), // road std::make_pair((Rect){96, 242, 1736, 906}, 567.0) // driver }; @@ -257,11 +247,7 @@ void CameraState::sendState() { void camerad_thread() { // TODO: centralize enabled handling - cl_device_id device_id = cl_get_device_id(CL_DEVICE_TYPE_DEFAULT); - const cl_context_properties props[] = {CL_CONTEXT_PRIORITY_HINT_QCOM, CL_PRIORITY_HINT_HIGH_QCOM, 0}; - cl_context ctx = CL_CHECK_ERR(clCreateContext(props, 1, &device_id, NULL, NULL, &err)); - - VisionIpcServer v("camerad", device_id, ctx); + VisionIpcServer v("camerad"); // *** initial ISP init *** SpectraMaster m; @@ -271,7 +257,7 @@ void camerad_thread() { std::vector> cams; for (const auto &config : ALL_CAMERA_CONFIGS) { auto cam = std::make_unique(&m, config); - cam->init(&v, device_id, ctx); + cam->init(&v); cams.emplace_back(std::move(cam)); } diff --git a/system/camerad/cameras/cdm.cc b/openpilot/system/camerad/cameras/cdm.cc similarity index 95% rename from system/camerad/cameras/cdm.cc rename to openpilot/system/camerad/cameras/cdm.cc index d4ef20c48c..8a070fa3aa 100644 --- a/system/camerad/cameras/cdm.cc +++ b/openpilot/system/camerad/cameras/cdm.cc @@ -1,9 +1,9 @@ #include "cdm.h" #include "stddef.h" -int write_dmi(uint8_t *dst, uint64_t *addr, uint32_t length, uint32_t dmi_addr, uint8_t sel) { +int write_dmi(uint8_t *dst, uint64_t *addr, uint32_t length, uint32_t dmi_addr, uint8_t sel, uint8_t opcode) { struct cdm_dmi_cmd *cmd = (struct cdm_dmi_cmd*)dst; - cmd->cmd = CAM_CDM_CMD_DMI_32; + cmd->cmd = opcode; cmd->length = length - 1; cmd->reserved = 0; cmd->addr = 0; // gets patched in diff --git a/system/camerad/cameras/cdm.h b/openpilot/system/camerad/cameras/cdm.h similarity index 97% rename from system/camerad/cameras/cdm.h rename to openpilot/system/camerad/cameras/cdm.h index adda600400..d9640cee3e 100644 --- a/system/camerad/cameras/cdm.h +++ b/openpilot/system/camerad/cameras/cdm.h @@ -6,11 +6,6 @@ #include #include -// our helpers -int write_random(uint8_t *dst, const std::vector &vals); -int write_cont(uint8_t *dst, uint32_t reg, const std::vector &vals); -int write_dmi(uint8_t *dst, uint64_t *addr, uint32_t length, uint32_t dmi_addr, uint8_t sel); - // from drivers/media/platform/msm/camera/cam_cdm/cam_cdm_util.{c,h} enum cam_cdm_command { @@ -32,6 +27,11 @@ enum cam_cdm_command { CAM_CDM_CMD_PRIVATE_BASE_MAX = 0x7F }; +// our helpers +int write_random(uint8_t *dst, const std::vector &vals); +int write_cont(uint8_t *dst, uint32_t reg, const std::vector &vals); +int write_dmi(uint8_t *dst, uint64_t *addr, uint32_t length, uint32_t dmi_addr, uint8_t sel, uint8_t opcode = CAM_CDM_CMD_DMI_32); + /** * struct cdm_regrandom_cmd - Definition for CDM random register command. * @count: Number of register writes diff --git a/openpilot/system/camerad/cameras/hw.h b/openpilot/system/camerad/cameras/hw.h new file mode 100644 index 0000000000..be0bea872d --- /dev/null +++ b/openpilot/system/camerad/cameras/hw.h @@ -0,0 +1,72 @@ +#pragma once + +#include "common/util.h" +#include "openpilot/cereal/gen/cpp/log.capnp.h" +#include "msgq/visionipc/visionipc_server.h" + +#include "media/cam_isp_ife.h" + + +typedef enum { + ISP_RAW_OUTPUT, // raw frame from sensor + ISP_IFE_PROCESSED, // fully processed image through the IFE + ISP_BPS_PROCESSED, // fully processed image through the BPS +} SpectraOutputType; + +// For the comma 3X three camera platform + +struct CameraConfig { + int camera_num; + VisionStreamType stream_type; + float focal_len; // millimeters + const char *publish_name; + cereal::FrameData::Builder (cereal::Event::Builder::*init_camera_state)(); + bool enabled; + uint32_t phy; + bool vignetting_correction; + SpectraOutputType output_type; + bool staggered_sof; // SOF is staggered (half-period offset) from other cameras +}; + +// NOTE: to be able to disable road and wide road, we still have to configure the sensor over i2c +// If you don't do this, the strobe GPIO is an output (even in reset it seems!) +const CameraConfig WIDE_ROAD_CAMERA_CONFIG = { + .camera_num = 0, + .stream_type = VISION_STREAM_WIDE_ROAD, + .focal_len = 1.71, + .publish_name = "wideRoadCameraState", + .init_camera_state = &cereal::Event::Builder::initWideRoadCameraState, + .enabled = !getenv("DISABLE_WIDE_ROAD"), + .phy = CAM_ISP_IFE_IN_RES_PHY_0, + .vignetting_correction = false, + .output_type = ISP_IFE_PROCESSED, + .staggered_sof = false, +}; + +const CameraConfig ROAD_CAMERA_CONFIG = { + .camera_num = 1, + .stream_type = VISION_STREAM_ROAD, + .focal_len = 8.0, + .publish_name = "roadCameraState", + .init_camera_state = &cereal::Event::Builder::initRoadCameraState, + .enabled = !getenv("DISABLE_ROAD"), + .phy = CAM_ISP_IFE_IN_RES_PHY_1, + .vignetting_correction = true, + .output_type = ISP_IFE_PROCESSED, + .staggered_sof = false, +}; + +const CameraConfig DRIVER_CAMERA_CONFIG = { + .camera_num = 2, + .stream_type = VISION_STREAM_DRIVER, + .focal_len = 1.71, + .publish_name = "driverCameraState", + .init_camera_state = &cereal::Event::Builder::initDriverCameraState, + .enabled = !getenv("DISABLE_DRIVER"), + .phy = CAM_ISP_IFE_IN_RES_PHY_2, + .vignetting_correction = false, + .output_type = ISP_BPS_PROCESSED, + .staggered_sof = true, +}; + +const CameraConfig ALL_CAMERA_CONFIGS[] = {WIDE_ROAD_CAMERA_CONFIG, ROAD_CAMERA_CONFIG, DRIVER_CAMERA_CONFIG}; diff --git a/system/camerad/cameras/ife.h b/openpilot/system/camerad/cameras/ife.h similarity index 100% rename from system/camerad/cameras/ife.h rename to openpilot/system/camerad/cameras/ife.h diff --git a/openpilot/system/camerad/cameras/nv12_info.h b/openpilot/system/camerad/cameras/nv12_info.h new file mode 100644 index 0000000000..c0460caee3 --- /dev/null +++ b/openpilot/system/camerad/cameras/nv12_info.h @@ -0,0 +1,130 @@ +#pragma once + +#include +#include +#include + +// NV12 subset copied from media/msm_media_info.h. +#ifndef MSM_MEDIA_ALIGN +#define MSM_MEDIA_ALIGN(__sz, __align) (((__align) & ((__align) - 1)) ? \ + ((((__sz) + (__align) - 1) / (__align)) * (__align)) : \ + (((__sz) + (__align) - 1) & (~((__align) - 1)))) +#endif + +#ifndef MSM_MEDIA_MAX +#define MSM_MEDIA_MAX(__a, __b) ((__a) > (__b) ? (__a) : (__b)) +#endif + +enum color_fmts { + COLOR_FMT_NV12, +}; + +static inline unsigned int VENUS_EXTRADATA_SIZE(int width, int height) { + (void)height; + (void)width; + return 16 * 1024; +} + +static inline unsigned int VENUS_Y_STRIDE(int color_fmt, int width) { + unsigned int stride = 0; + if (!width) goto invalid_input; + + switch (color_fmt) { + case COLOR_FMT_NV12: + stride = MSM_MEDIA_ALIGN(width, 128); + break; + default: + break; + } +invalid_input: + return stride; +} + +static inline unsigned int VENUS_UV_STRIDE(int color_fmt, int width) { + unsigned int stride = 0; + if (!width) goto invalid_input; + + switch (color_fmt) { + case COLOR_FMT_NV12: + stride = MSM_MEDIA_ALIGN(width, 128); + break; + default: + break; + } +invalid_input: + return stride; +} + +static inline unsigned int VENUS_Y_SCANLINES(int color_fmt, int height) { + unsigned int sclines = 0; + if (!height) goto invalid_input; + + switch (color_fmt) { + case COLOR_FMT_NV12: + sclines = MSM_MEDIA_ALIGN(height, 32); + break; + default: + break; + } +invalid_input: + return sclines; +} + +static inline unsigned int VENUS_UV_SCANLINES(int color_fmt, int height) { + unsigned int sclines = 0; + if (!height) goto invalid_input; + + switch (color_fmt) { + case COLOR_FMT_NV12: + sclines = MSM_MEDIA_ALIGN((height + 1) >> 1, 16); + break; + default: + break; + } +invalid_input: + return sclines; +} + +static inline unsigned int VENUS_BUFFER_SIZE(int color_fmt, int width, int height) { + const unsigned int extra_size = VENUS_EXTRADATA_SIZE(width, height); + unsigned int size = 0; + unsigned int y_stride = 0, uv_stride = 0, y_sclines = 0, uv_sclines = 0; + + if (!width || !height) goto invalid_input; + + y_stride = VENUS_Y_STRIDE(color_fmt, width); + uv_stride = VENUS_UV_STRIDE(color_fmt, width); + y_sclines = VENUS_Y_SCANLINES(color_fmt, height); + uv_sclines = VENUS_UV_SCANLINES(color_fmt, height); + + switch (color_fmt) { + case COLOR_FMT_NV12: { + const unsigned int y_plane = y_stride * y_sclines; + const unsigned int uv_plane = uv_stride * uv_sclines + 4096; + size = y_plane + uv_plane + MSM_MEDIA_MAX(extra_size, 8 * y_stride); + size = MSM_MEDIA_ALIGN(size, 4096); + size += MSM_MEDIA_ALIGN(width, 512) * 512; + size = MSM_MEDIA_ALIGN(size, 4096); + break; + } + default: + break; + } +invalid_input: + return size; +} + +// Returns NV12 aligned (stride, y_height, uv_height, buffer_size) for the given frame dimensions. +inline std::tuple get_nv12_info(int width, int height) { + const uint32_t stride = VENUS_Y_STRIDE(COLOR_FMT_NV12, width); + const uint32_t y_height = VENUS_Y_SCANLINES(COLOR_FMT_NV12, height); + const uint32_t uv_height = VENUS_UV_SCANLINES(COLOR_FMT_NV12, height); + const uint32_t size = VENUS_BUFFER_SIZE(COLOR_FMT_NV12, width, height); + + // Sanity checks for NV12 format assumptions + assert(stride == VENUS_UV_STRIDE(COLOR_FMT_NV12, width)); + assert(y_height / 2 == uv_height); + assert((stride * y_height) % 0x1000 == 0); // uv_offset must be page-aligned + + return {stride, y_height, uv_height, size}; +} diff --git a/openpilot/system/camerad/cameras/nv12_info.py b/openpilot/system/camerad/cameras/nv12_info.py new file mode 100644 index 0000000000..abd734ba50 --- /dev/null +++ b/openpilot/system/camerad/cameras/nv12_info.py @@ -0,0 +1,21 @@ +# Python version of openpilot/system/camerad/cameras/nv12_info.h +# Calculations from media/msm_media_info.h (VENUS_BUFFER_SIZE) + +def align(val: int, alignment: int) -> int: + return ((val + alignment - 1) // alignment) * alignment + +def get_nv12_info(width: int, height: int) -> tuple[int, int, int, int]: + """Returns (stride, y_height, uv_height, buffer_size) for NV12 frame dimensions.""" + stride = align(width, 128) + y_height = align(height, 32) + uv_height = align(height // 2, 16) + + # VENUS_BUFFER_SIZE for NV12 + y_plane = stride * y_height + uv_plane = stride * uv_height + 4096 + size = y_plane + uv_plane + max(16 * 1024, 8 * stride) + size = align(size, 4096) + size += align(width, 512) * 512 # kernel padding for non-aligned frames + size = align(size, 4096) + + return stride, y_height, uv_height, size diff --git a/system/camerad/cameras/spectra.cc b/openpilot/system/camerad/cameras/spectra.cc similarity index 89% rename from system/camerad/cameras/spectra.cc rename to openpilot/system/camerad/cameras/spectra.cc index 47ae9061f4..0b5f5327f5 100644 --- a/system/camerad/cameras/spectra.cc +++ b/openpilot/system/camerad/cameras/spectra.cc @@ -10,13 +10,12 @@ #include "media/cam_isp.h" #include "media/cam_icp.h" #include "media/cam_isp_ife.h" -#include "media/cam_sensor_cmn_header.h" #include "media/cam_sync.h" -#include "third_party/linux/include/msm_media_info.h" #include "common/util.h" #include "common/swaglog.h" #include "system/camerad/cameras/ife.h" +#include "system/camerad/cameras/nv12_info.h" #include "system/camerad/cameras/spectra.h" #include "system/camerad/cameras/bps_blobs.h" @@ -274,7 +273,7 @@ int SpectraCamera::clear_req_queue() { return ret; } -void SpectraCamera::camera_open(VisionIpcServer *v, cl_device_id device_id, cl_context ctx) { +void SpectraCamera::camera_open(VisionIpcServer *v) { if (!openSensor()) { return; } @@ -286,17 +285,8 @@ void SpectraCamera::camera_open(VisionIpcServer *v, cl_device_id device_id, cl_c // size is driven by all the HW that handles frames, // the video encoder has certain alignment requirements in this case - stride = VENUS_Y_STRIDE(COLOR_FMT_NV12, buf.out_img_width); - y_height = VENUS_Y_SCANLINES(COLOR_FMT_NV12, buf.out_img_height); - uv_height = VENUS_UV_SCANLINES(COLOR_FMT_NV12, buf.out_img_height); - uv_offset = stride*y_height; - yuv_size = uv_offset + stride*uv_height; - if (cc.output_type != ISP_RAW_OUTPUT) { - uv_offset = ALIGNED_SIZE(uv_offset, 0x1000); - yuv_size = uv_offset + ALIGNED_SIZE(stride*uv_height, 0x1000); - } - assert(stride == VENUS_UV_STRIDE(COLOR_FMT_NV12, buf.out_img_width)); - assert(y_height/2 == uv_height); + std::tie(stride, y_height, uv_height, yuv_size) = get_nv12_info(buf.out_img_width, buf.out_img_height); + uv_offset = stride * y_height; open = true; configISP(); @@ -305,7 +295,7 @@ void SpectraCamera::camera_open(VisionIpcServer *v, cl_device_id device_id, cl_c linkDevices(); LOGD("camera init %d", cc.camera_num); - buf.init(device_id, ctx, this, v, ife_buf_depth, cc.stream_type); + buf.init(this, v, ife_buf_depth, cc.stream_type); camera_map_bufs(); clearAndRequeue(1); } @@ -475,8 +465,11 @@ void SpectraCamera::config_bps(int idx, int request_id) { * BPS = Bayer Processing Segment */ - int size = sizeof(struct cam_packet) + sizeof(struct cam_cmd_buf_desc)*2 + sizeof(struct cam_buf_io_cfg)*2; - size += sizeof(struct cam_patch_desc)*9; + bool needs_downscale = sensor->out_scale > 1; + int num_io_cfgs = needs_downscale ? 3 : 2; + int num_patches = needs_downscale ? 14 : 12; + int size = sizeof(struct cam_packet) + sizeof(struct cam_cmd_buf_desc)*2 + sizeof(struct cam_buf_io_cfg)*num_io_cfgs; + size += sizeof(struct cam_patch_desc)*num_patches; uint32_t cam_packet_handle = 0; auto pkt = m->mem_mgr.alloc(size, &cam_packet_handle); @@ -554,8 +547,15 @@ void SpectraCamera::config_bps(int idx, int request_id) { int cdm_len = 0; if (bps_lin_reg.size() == 0) { + // set first knee pt to do BLC + uint32_t new_knee[8]; + new_knee[0] = sensor->black_level << (14 - sensor->bits_per_pixel); + for (int i = 0; i < 7; i++) { + uint32_t pts = sensor->linearization_pts[i / 2]; + new_knee[i + 1] = (i % 2 == 0) ? (pts >> 16) : (pts & 0xffff); + } for (int i = 0; i < 4; i++) { - bps_lin_reg.push_back(((sensor->linearization_pts[i] & 0xffff) << 0x10) | (sensor->linearization_pts[i] >> 0x10)); + bps_lin_reg.push_back((new_knee[2*i + 1] << 16) | new_knee[2*i]); } } @@ -578,20 +578,24 @@ void SpectraCamera::config_bps(int idx, int request_id) { 0x00000080, 0x00800066, }); - // linearization, EN=0 + // linearization cdm_len += write_cont((unsigned char *)bps_cdm_program_array.ptr + cdm_len, 0x1868, bps_lin_reg); cdm_len += write_cont((unsigned char *)bps_cdm_program_array.ptr + cdm_len, 0x1878, bps_lin_reg); cdm_len += write_cont((unsigned char *)bps_cdm_program_array.ptr + cdm_len, 0x1888, bps_lin_reg); cdm_len += write_cont((unsigned char *)bps_cdm_program_array.ptr + cdm_len, 0x1898, bps_lin_reg); - /* - uint8_t *start = (unsigned char *)bps_cdm_program_array.ptr + cdm_len; uint64_t addr; - cdm_len += write_dmi((unsigned char *)bps_cdm_program_array.ptr + cdm_len, &addr, sensor->linearization_lut.size()*sizeof(uint32_t), 0x1808, 1); - patches.push_back(addr - (uint64_t)start); - */ + cdm_len += write_dmi((unsigned char *)bps_cdm_program_array.ptr + cdm_len, &addr, sensor->linearization_lut.size()*sizeof(uint32_t), 0x1808, 1, CAM_CDM_CMD_DMI); + patches.push_back(addr - (uint64_t)bps_cdm_program_array.ptr); + // color correction cdm_len += write_cont((unsigned char *)bps_cdm_program_array.ptr + cdm_len, 0x2e68, bps_ccm_reg); + // gamma + for (uint8_t ch = 1; ch <= 3; ch++) { + cdm_len += write_dmi((unsigned char *)bps_cdm_program_array.ptr + cdm_len, &addr, sensor->gamma_lut_rgb.size()*sizeof(uint32_t), 0x3208, ch, CAM_CDM_CMD_DMI); + patches.push_back(addr - (uint64_t)bps_cdm_program_array.ptr); + } + cdm_len += build_common_ife_bps((unsigned char *)bps_cdm_program_array.ptr + cdm_len, cc, sensor.get(), patches, false); pa->length = cdm_len - 1; @@ -605,7 +609,7 @@ void SpectraCamera::config_bps(int idx, int request_id) { tmp.header = CAM_ICP_CMD_GENERIC_BLOB_CLK; tmp.header |= (sizeof(cam_icp_clk_bw_request)) << 8; tmp.clk.budget_ns = 0x1fca058; - tmp.clk.frame_cycles = 2329024; // comes from the striping lib + tmp.clk.frame_cycles = sensor->frame_width * sensor->frame_height; // matches striping lib pixelCount tmp.clk.rt_flag = 0x0; tmp.clk.uncompressed_bw = 0x38512180; tmp.clk.compressed_bw = 0x38512180; @@ -620,7 +624,7 @@ void SpectraCamera::config_bps(int idx, int request_id) { } // *** io config *** - pkt->num_io_configs = 2; + pkt->num_io_configs = num_io_cfgs; pkt->io_configs_offset = sizeof(struct cam_cmd_buf_desc)*pkt->num_cmd_buf; struct cam_buf_io_cfg *io_cfg = (struct cam_buf_io_cfg *)((char*)&pkt->payload + pkt->io_configs_offset); { @@ -664,28 +668,69 @@ void SpectraCamera::config_bps(int idx, int request_id) { io_cfg[1].format = CAM_FORMAT_NV12; // TODO: why is this 21 in the dump? should be 12 io_cfg[1].color_space = CAM_COLOR_SPACE_BT601_FULL; - io_cfg[1].resource_type = CAM_ICP_BPS_OUTPUT_IMAGE_FULL; + io_cfg[1].resource_type = needs_downscale ? CAM_ICP_BPS_OUTPUT_IMAGE_REG1 : CAM_ICP_BPS_OUTPUT_IMAGE_FULL; io_cfg[1].fence = sync_objs_bps[idx]; io_cfg[1].direction = CAM_BUF_OUTPUT; io_cfg[1].subsample_pattern = 0x1; io_cfg[1].framedrop_pattern = 0x1; + + if (needs_downscale) { + // downscaling needs a full res placeholder + uint32_t full_stride, full_y_h, full_uv_h, full_yuv_size; + std::tie(full_stride, full_y_h, full_uv_h, full_yuv_size) = get_nv12_info(sensor->frame_width, sensor->frame_height); + io_cfg[2].mem_handle[0] = bps_fullres_dummy.handle; + io_cfg[2].mem_handle[1] = bps_fullres_dummy.handle; + io_cfg[2].planes[0] = (struct cam_plane_cfg){ + .width = sensor->frame_width, + .height = sensor->frame_height, + .plane_stride = full_stride, + .slice_height = full_y_h, + }; + io_cfg[2].planes[1] = (struct cam_plane_cfg){ + .width = sensor->frame_width, + .height = sensor->frame_height / 2, + .plane_stride = full_stride, + .slice_height = full_uv_h, + }; + io_cfg[2].offsets[1] = ALIGNED_SIZE(full_stride * full_y_h, 0x1000); + io_cfg[2].format = CAM_FORMAT_NV12; + io_cfg[2].color_space = CAM_COLOR_SPACE_BT601_FULL; + io_cfg[2].resource_type = CAM_ICP_BPS_OUTPUT_IMAGE_FULL; + io_cfg[2].fence = sync_objs_bps[idx]; + io_cfg[2].direction = CAM_BUF_OUTPUT; + io_cfg[2].subsample_pattern = 0x1; + io_cfg[2].framedrop_pattern = 0x1; + } } // *** patches *** { - assert(patches.size() == 0 | patches.size() == 1); + assert(patches.size() == 0 || patches.size() == 4); pkt->patch_offset = sizeof(struct cam_cmd_buf_desc)*pkt->num_cmd_buf + sizeof(struct cam_buf_io_cfg)*pkt->num_io_configs; if (patches.size() > 0) { - add_patch(pkt.get(), bps_cmd.handle, patches[0], bps_linearization_lut.handle, 0); + // linearization LUT + add_patch(pkt.get(), bps_cdm_program_array.handle, patches[0], bps_linearization_lut.handle, 0); + // gamma LUTs + for (int i = 0; i < 3; i++) { + add_patch(pkt.get(), bps_cdm_program_array.handle, patches[i+1], bps_gamma_lut.handle, 0); + } } // input frame add_patch(pkt.get(), bps_cmd.handle, buf_desc[0].offset + offsetof(bps_tmp, frames[0].ptr[0]), buf_handle_raw[idx], 0); - // output frame - add_patch(pkt.get(), bps_cmd.handle, buf_desc[0].offset + offsetof(bps_tmp, frames[1].ptr[0]), buf_handle_yuv[idx], 0); - add_patch(pkt.get(), bps_cmd.handle, buf_desc[0].offset + offsetof(bps_tmp, frames[1].ptr[1]), buf_handle_yuv[idx], io_cfg[1].offsets[1]); + if (needs_downscale) { + add_patch(pkt.get(), bps_cmd.handle, buf_desc[0].offset + offsetof(bps_tmp, frames[1].ptr[0]), bps_fullres_dummy.handle, 0); + add_patch(pkt.get(), bps_cmd.handle, buf_desc[0].offset + offsetof(bps_tmp, frames[1].ptr[1]), bps_fullres_dummy.handle, io_cfg[2].offsets[1]); + // output frame at REG1 + add_patch(pkt.get(), bps_cmd.handle, buf_desc[0].offset + offsetof(bps_tmp, frames[7].ptr[0]), buf_handle_yuv[idx], 0); + add_patch(pkt.get(), bps_cmd.handle, buf_desc[0].offset + offsetof(bps_tmp, frames[7].ptr[1]), buf_handle_yuv[idx], io_cfg[1].offsets[1]); + } else { + // output frame at FULL + add_patch(pkt.get(), bps_cmd.handle, buf_desc[0].offset + offsetof(bps_tmp, frames[1].ptr[0]), buf_handle_yuv[idx], 0); + add_patch(pkt.get(), bps_cmd.handle, buf_desc[0].offset + offsetof(bps_tmp, frames[1].ptr[1]), buf_handle_yuv[idx], io_cfg[1].offsets[1]); + } // rest of buffers add_patch(pkt.get(), bps_cmd.handle, buf_desc[0].offset + offsetof(bps_tmp, settings_addr), bps_iq.handle, 0); @@ -996,17 +1041,13 @@ bool SpectraCamera::openSensor() { LOGD("-- Probing sensor %d", cc.camera_num); auto init_sensor_lambda = [this](SensorInfo *s) { - if (s->image_sensor == cereal::FrameData::ImageSensor::OS04C10 && cc.output_type == ISP_IFE_PROCESSED) { - ((OS04C10*)s)->ife_downscale_configure(); - } sensor.reset(s); return (sensors_init() == 0); }; // Figure out which sensor we have - if (!init_sensor_lambda(new AR0231) && - !init_sensor_lambda(new OX03C10) && - !init_sensor_lambda(new OS04C10)) { + if (!init_sensor_lambda(new OS04C10) && + !init_sensor_lambda(new OX03C10)) { LOGE("** sensor %d FAILED bringup, disabling", cc.camera_num); enabled = false; return false; @@ -1177,13 +1218,39 @@ void SpectraCamera::configICP() { // used internally by the BPS, we just allocate it. // size comes from the BPSStripingLib - bps_cdm_striping_bl.init(m, 0xa100, 0x20, true, m->icp_device_iommu); + bps_cdm_striping_bl.init(m, 0xcfe0, 0x20, true, m->icp_device_iommu); + + if (sensor->out_scale > 1) { + uint32_t full_stride, full_y_h, full_uv_h, full_yuv_size; + std::tie(full_stride, full_y_h, full_uv_h, full_yuv_size) = get_nv12_info(sensor->frame_width, sensor->frame_height); + bps_fullres_dummy.init(m, full_yuv_size, 0x1000, true, m->icp_device_iommu); + } // LUTs - /* + assert(sensor->linearization_lut.size() == 36); bps_linearization_lut.init(m, sensor->linearization_lut.size()*sizeof(uint32_t), 0x20, true, m->icp_device_iommu); - memcpy(bps_linearization_lut.ptr, sensor->linearization_lut.data(), bps_linearization_lut.size); - */ + + // bit shift linearization_lut to bps specs, also compensate for black level here + uint32_t bl = sensor->black_level << (14 - sensor->bits_per_pixel); + uint32_t* bps_lut = (uint32_t*)bps_linearization_lut.ptr; + for (size_t i = 0; i < sensor->linearization_lut.size(); i++) { + size_t seg = i / 4; + size_t ch = i % 4; + if (seg == 0) { + bps_lut[i] = 0; + continue; + } + uint32_t e = sensor->linearization_lut[(seg - 1) * 4 + ch]; + uint32_t base = e & 0x3fff; + uint32_t slope_q11 = (e >> 14) & 0x3fff; + uint32_t slope_q12 = std::min(slope_q11 << 1, 0x3fff); + base = (base > bl) ? (base - bl) : 0; + bps_lut[i] = base | (slope_q12 << 14); + } + + assert(sensor->gamma_lut_rgb.size() == 64); + bps_gamma_lut.init(m, sensor->gamma_lut_rgb.size()*sizeof(uint32_t), 0x20, true, m->icp_device_iommu); + memcpy(bps_gamma_lut.ptr, sensor->gamma_lut_rgb.data(), bps_gamma_lut.size); } void SpectraCamera::configCSIPHY() { @@ -1446,7 +1513,7 @@ bool SpectraCamera::waitForFrameReady(uint64_t request_id) { } bool SpectraCamera::processFrame(int buf_idx, uint64_t request_id, uint64_t frame_id_raw, uint64_t timestamp) { - if (!syncFirstFrame(cc.camera_num, request_id, frame_id_raw, timestamp)) { + if (!syncFirstFrame(cc.camera_num, request_id, frame_id_raw, timestamp, cc.staggered_sof)) { return false; } @@ -1465,23 +1532,31 @@ bool SpectraCamera::processFrame(int buf_idx, uint64_t request_id, uint64_t fram return true; } -bool SpectraCamera::syncFirstFrame(int camera_id, uint64_t request_id, uint64_t raw_id, uint64_t timestamp) { +bool SpectraCamera::syncFirstFrame(int camera_id, uint64_t request_id, uint64_t raw_id, uint64_t timestamp, bool staggered) { if (first_frame_synced) return true; // Store the frame data for this camera - camera_sync_data[camera_id] = SyncData{timestamp, raw_id + 1}; + camera_sync_data[camera_id] = SyncData{timestamp, raw_id + 1, staggered}; // Ensure all cameras are up int enabled_camera_count = std::count_if(std::begin(ALL_CAMERA_CONFIGS), std::end(ALL_CAMERA_CONFIGS), [](const auto &config) { return config.enabled; }); bool all_cams_up = camera_sync_data.size() == enabled_camera_count; - // Wait until the timestamps line up + // Check that camera timestamps are properly aligned: + // - non-staggered cameras should be within 0.2ms of each other + // - staggered cameras should be within 0.2ms of a 25ms offset from non-staggered cameras + const uint64_t half_period_ns = 25 * 1000000ULL; // 25ms + const uint64_t tolerance_ns = 200000ULL; // 0.2ms bool all_cams_synced = true; - for (const auto &[_, sync_data] : camera_sync_data) { + for (const auto &[cam, sync_data] : camera_sync_data) { + if (cam == camera_id) continue; uint64_t diff = std::max(timestamp, sync_data.timestamp) - std::min(timestamp, sync_data.timestamp); - if (diff > 0.2*1e6) { // milliseconds + bool pair_staggered = staggered != sync_data.staggered; + uint64_t expected_offset = pair_staggered ? half_period_ns : 0; + uint64_t error = (diff > expected_offset) ? diff - expected_offset : expected_offset - diff; + if (error > tolerance_ns) { all_cams_synced = false; } } diff --git a/system/camerad/cameras/spectra.h b/openpilot/system/camerad/cameras/spectra.h similarity index 86% rename from system/camerad/cameras/spectra.h rename to openpilot/system/camerad/cameras/spectra.h index 13cb13f98f..eb6d95af1c 100644 --- a/system/camerad/cameras/spectra.h +++ b/openpilot/system/camerad/cameras/spectra.h @@ -30,6 +30,29 @@ const int MIPI_SETTLE_CNT = 33; // Calculated by camera_freqs.py #define OpcodesIFEInitialConfig 0x0 #define OpcodesIFEUpdate 0x1 +// Sensor command values from the SDM845 kernel's private camera header: +// drivers/media/platform/msm/camera/cam_sensor_module/cam_sensor_utils/cam_sensor_cmn_header.h +// These are userspace-visible ioctl payload values, but Qualcomm did not export them through UAPI. +enum { + CAMERA_SENSOR_CMD_TYPE_PROBE = 1, + CAMERA_SENSOR_CMD_TYPE_PWR_UP = 2, + CAMERA_SENSOR_CMD_TYPE_PWR_DOWN = 3, + CAMERA_SENSOR_CMD_TYPE_I2C_INFO = 4, + CAMERA_SENSOR_CMD_TYPE_I2C_RNDM_WR = 5, + CAMERA_SENSOR_CMD_TYPE_WAIT = 9, + + CAMERA_SENSOR_WAIT_OP_SW_UCND = 3, + + CAMERA_SENSOR_I2C_TYPE_BYTE = 1, + CAMERA_SENSOR_I2C_TYPE_WORD = 2, + + I2C_FAST_MODE = 1, + + CAM_SENSOR_PACKET_OPCODE_SENSOR_PROBE = 3, + CAM_SENSOR_PACKET_OPCODE_SENSOR_CONFIG = 4, + CAM_SENSOR_PACKET_OPCODE_SENSOR_NOP = 127, +}; + std::optional device_acquire(int fd, int32_t session_handle, void *data, uint32_t num_resources=1); int device_config(int fd, int32_t session_handle, int32_t dev_handle, uint64_t packet_handle); int device_control(int fd, int op_code, int session_handle, int dev_handle); @@ -113,7 +136,7 @@ public: SpectraCamera(SpectraMaster *master, const CameraConfig &config); ~SpectraCamera(); - void camera_open(VisionIpcServer *v, cl_device_id device_id, cl_context ctx); + void camera_open(VisionIpcServer *v); bool handle_camera_event(const cam_req_mgr_message *event_data); void camera_close(); void camera_map_bufs(); @@ -173,6 +196,8 @@ public: SpectraBuf bps_iq; SpectraBuf bps_striping; SpectraBuf bps_linearization_lut; + SpectraBuf bps_gamma_lut; + SpectraBuf bps_fullres_dummy; std::vector bps_lin_reg; std::vector bps_ccm_reg; @@ -194,10 +219,11 @@ private: bool validateEvent(uint64_t request_id, uint64_t frame_id_raw); bool waitForFrameReady(uint64_t request_id); bool processFrame(int buf_idx, uint64_t request_id, uint64_t frame_id_raw, uint64_t timestamp); - static bool syncFirstFrame(int camera_id, uint64_t request_id, uint64_t raw_id, uint64_t timestamp); + static bool syncFirstFrame(int camera_id, uint64_t request_id, uint64_t raw_id, uint64_t timestamp, bool staggered); struct SyncData { uint64_t timestamp; uint64_t frame_id_offset = 0; + bool staggered = false; }; inline static std::map camera_sync_data; inline static bool first_frame_synced = false; diff --git a/system/camerad/main.cc b/openpilot/system/camerad/main.cc similarity index 100% rename from system/camerad/main.cc rename to openpilot/system/camerad/main.cc diff --git a/system/camerad/sensors/os04c10.cc b/openpilot/system/camerad/sensors/os04c10.cc similarity index 94% rename from system/camerad/sensors/os04c10.cc rename to openpilot/system/camerad/sensors/os04c10.cc index 38be4ecca4..d14c288b91 100644 --- a/system/camerad/sensors/os04c10.cc +++ b/openpilot/system/camerad/sensors/os04c10.cc @@ -1,6 +1,7 @@ #include #include "system/camerad/sensors/sensor.h" +#include namespace { @@ -20,27 +21,16 @@ const uint32_t os04c10_analog_gains_reg[] = { } // namespace -void OS04C10::ife_downscale_configure() { - out_scale = 2; - - pixel_size_mm = 0.002; - frame_width = 2688; - frame_height = 1520; - exposure_time_max = 2352; - - init_reg_array.insert(init_reg_array.end(), std::begin(ife_downscale_override_array_os04c10), std::end(ife_downscale_override_array_os04c10)); -} - OS04C10::OS04C10() { image_sensor = cereal::FrameData::ImageSensor::OS04C10; bayer_pattern = CAM_ISP_PATTERN_BAYER_BGBGBG; - pixel_size_mm = 0.004; + pixel_size_mm = 0.002; data_word = false; - // hdr_offset = 64 * 2 + 8; // stagger - frame_width = 1344; - frame_height = 760; //760 * 2 + hdr_offset; - frame_stride = (frame_width * 12 / 8); // no alignment + out_scale = 2; + frame_width = 2688; + frame_height = 1520; + frame_stride = frame_width * 12 / 8; extra_height = 0; frame_offset = 0; @@ -51,7 +41,7 @@ OS04C10::OS04C10() { probe_expected_data = 0x5304; bits_per_pixel = 12; mipi_format = CAM_FORMAT_MIPI_RAW_12; - frame_data_type = 0x2c; + frame_data_type = CSI_RAW12; mclk_frequency = 24000000; // Hz // TODO: this was set from logs. actually calculate it out @@ -64,7 +54,7 @@ OS04C10::OS04C10() { dc_gain_on_grey = 0.9; dc_gain_off_grey = 1.0; exposure_time_min = 2; - exposure_time_max = 1684; + exposure_time_max = 2352; analog_gain_min_idx = 0x0; analog_gain_rec_idx = 0x0; // 1x analog_gain_max_idx = 0x28; diff --git a/system/camerad/sensors/os04c10_registers.h b/openpilot/system/camerad/sensors/os04c10_registers.h similarity index 89% rename from system/camerad/sensors/os04c10_registers.h rename to openpilot/system/camerad/sensors/os04c10_registers.h index 7cd9e97be5..45512851bc 100644 --- a/system/camerad/sensors/os04c10_registers.h +++ b/openpilot/system/camerad/sensors/os04c10_registers.h @@ -4,10 +4,10 @@ const struct i2c_random_wr_payload start_reg_array_os04c10[] = {{0x100, 1}}; const struct i2c_random_wr_payload stop_reg_array_os04c10[] = {{0x100, 0}}; const struct i2c_random_wr_payload init_array_os04c10[] = { - // DP_2688X1520_NEWSTG_MIPI0776Mbps_30FPS_10BIT_FOURLANE - {0x0103, 0x01}, + // OS04C10_AA_00_02_17_wAO_2688x1524_MIPI728Mbps_Linear12bit_20FPS_4Lane_MCLK24MHz + {0x0103, 0x01}, // software reset - // PLL + // PLL + clocks {0x0301, 0xe4}, {0x0303, 0x01}, {0x0305, 0xb6}, @@ -24,7 +24,7 @@ const struct i2c_random_wr_payload init_array_os04c10[] = { {0x3106, 0x21}, {0x3107, 0xa1}, - // ? + // Analog/timing fine-tuning block {0x3624, 0x00}, {0x3625, 0x4c}, {0x3660, 0x04}, @@ -93,7 +93,7 @@ const struct i2c_random_wr_payload init_array_os04c10[] = { {0x388b, 0x00}, {0x3c80, 0x10}, {0x3c86, 0x00}, - {0x3c8c, 0x20}, + {0x3c8c, 0x40}, {0x3c9f, 0x01}, {0x3d85, 0x1b}, {0x3d8c, 0x71}, @@ -101,7 +101,7 @@ const struct i2c_random_wr_payload init_array_os04c10[] = { {0x3f00, 0x0b}, {0x3f06, 0x04}, - // BLC + // BLC - black level correction {0x400a, 0x01}, {0x400b, 0x50}, {0x400e, 0x08}, @@ -157,7 +157,7 @@ const struct i2c_random_wr_payload init_array_os04c10[] = { {0x5180, 0x70}, {0x5181, 0x10}, - // DPC + // DPC - defective pixel correction {0x520a, 0x03}, {0x520b, 0x06}, {0x520c, 0x0c}, @@ -197,7 +197,7 @@ const struct i2c_random_wr_payload init_array_os04c10[] = { {0x370b, 0x48}, {0x370c, 0x01}, {0x370f, 0x00}, - {0x3714, 0x28}, + {0x3714, 0x24}, {0x3716, 0x04}, {0x3719, 0x11}, {0x371a, 0x1e}, @@ -229,7 +229,7 @@ const struct i2c_random_wr_payload init_array_os04c10[] = { {0x37bd, 0x01}, {0x37bf, 0x26}, {0x37c0, 0x11}, - {0x37c2, 0x14}, + {0x37c2, 0x04}, {0x37cd, 0x19}, {0x37e0, 0x08}, {0x37e6, 0x04}, @@ -239,16 +239,16 @@ const struct i2c_random_wr_payload init_array_os04c10[] = { {0x37d8, 0x02}, {0x37e2, 0x10}, {0x3739, 0x10}, - {0x3662, 0x08}, + {0x3662, 0x10}, {0x37e4, 0x20}, {0x37e3, 0x08}, - {0x37d9, 0x04}, + {0x37d9, 0x08}, {0x4040, 0x00}, - {0x4041, 0x03}, - {0x4008, 0x01}, - {0x4009, 0x06}, + {0x4041, 0x07}, + {0x4008, 0x02}, + {0x4009, 0x0d}, - // FSIN + // FSIN - frame sync {0x3002, 0x22}, {0x3663, 0x22}, {0x368a, 0x04}, @@ -267,20 +267,20 @@ const struct i2c_random_wr_payload init_array_os04c10[] = { {0x3802, 0x00}, {0x3803, 0x00}, {0x3804, 0x0a}, {0x3805, 0x8f}, {0x3806, 0x05}, {0x3807, 0xff}, - {0x3808, 0x05}, {0x3809, 0x40}, - {0x380a, 0x02}, {0x380b, 0xf8}, + {0x3808, 0x0a}, {0x3809, 0x80}, + {0x380a, 0x05}, {0x380b, 0xf0}, {0x3811, 0x08}, {0x3813, 0x08}, - {0x3814, 0x03}, + {0x3814, 0x01}, {0x3815, 0x01}, - {0x3816, 0x03}, + {0x3816, 0x01}, {0x3817, 0x01}, - {0x380c, 0x0b}, {0x380d, 0xac}, // HTS - {0x380e, 0x06}, {0x380f, 0x9c}, // VTS + {0x380c, 0x08}, {0x380d, 0x5c}, // HTS (line length) + {0x380e, 0x09}, {0x380f, 0x38}, // VTS (frame length) - {0x3820, 0xb3}, - {0x3821, 0x01}, + {0x3820, 0xb0}, + {0x3821, 0x00}, {0x3880, 0x00}, {0x3882, 0x20}, {0x3c91, 0x0b}, @@ -309,17 +309,17 @@ const struct i2c_random_wr_payload init_array_os04c10[] = { // initialize exposure {0x3503, 0x88}, - // long + // long exposure {0x3500, 0x00}, {0x3501, 0x00}, {0x3502, 0x10}, {0x3508, 0x00}, {0x3509, 0x80}, {0x350a, 0x04}, {0x350b, 0x00}, - // short + // short exposure {0x3510, 0x00}, {0x3511, 0x00}, {0x3512, 0x40}, {0x350c, 0x00}, {0x350d, 0x80}, {0x350e, 0x04}, {0x350f, 0x00}, - // wb + // white balance // b {0x5100, 0x06}, {0x5101, 0x7e}, {0x5140, 0x06}, {0x5141, 0x7e}, @@ -330,23 +330,3 @@ const struct i2c_random_wr_payload init_array_os04c10[] = { {0x5104, 0x08}, {0x5105, 0xd6}, {0x5144, 0x08}, {0x5145, 0xd6}, }; - -const struct i2c_random_wr_payload ife_downscale_override_array_os04c10[] = { - // OS04C10_AA_00_02_17_wAO_2688x1524_MIPI728Mbps_Linear12bit_20FPS_4Lane_MCLK24MHz - {0x3c8c, 0x40}, - {0x3714, 0x24}, - {0x37c2, 0x04}, - {0x3662, 0x10}, - {0x37d9, 0x08}, - {0x4041, 0x07}, - {0x4008, 0x02}, - {0x4009, 0x0d}, - {0x3808, 0x0a}, {0x3809, 0x80}, - {0x380a, 0x05}, {0x380b, 0xf0}, - {0x3814, 0x01}, - {0x3816, 0x01}, - {0x380c, 0x08}, {0x380d, 0x5c}, // HTS - {0x380e, 0x09}, {0x380f, 0x38}, // VTS - {0x3820, 0xb0}, - {0x3821, 0x00}, -}; diff --git a/system/camerad/sensors/ox03c10.cc b/openpilot/system/camerad/sensors/ox03c10.cc similarity index 98% rename from system/camerad/sensors/ox03c10.cc rename to openpilot/system/camerad/sensors/ox03c10.cc index 6f7e658f48..e0e0dec2ff 100644 --- a/system/camerad/sensors/ox03c10.cc +++ b/openpilot/system/camerad/sensors/ox03c10.cc @@ -1,6 +1,7 @@ #include #include "system/camerad/sensors/sensor.h" +#include namespace { @@ -40,8 +41,8 @@ OX03C10::OX03C10() { probe_expected_data = 0x5803; bits_per_pixel = 12; mipi_format = CAM_FORMAT_MIPI_RAW_12; - frame_data_type = 0x2c; // one is 0x2a, two are 0x2b - mclk_frequency = 24000000; //Hz + frame_data_type = CSI_RAW12; + mclk_frequency = 24000000; // Hz readout_time_ns = 14697000; diff --git a/system/camerad/sensors/ox03c10_registers.h b/openpilot/system/camerad/sensors/ox03c10_registers.h similarity index 100% rename from system/camerad/sensors/ox03c10_registers.h rename to openpilot/system/camerad/sensors/ox03c10_registers.h diff --git a/openpilot/system/camerad/sensors/sensor.h b/openpilot/system/camerad/sensors/sensor.h new file mode 100644 index 0000000000..251f5d64b4 --- /dev/null +++ b/openpilot/system/camerad/sensors/sensor.h @@ -0,0 +1,104 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include "media/cam_isp.h" +#include "media/cam_sensor.h" + +#include "openpilot/cereal/gen/cpp/log.capnp.h" +#include "system/camerad/sensors/ox03c10_registers.h" +#include "system/camerad/sensors/os04c10_registers.h" + +#define ANALOG_GAIN_MAX_CNT 55 + +class SensorInfo { +public: + SensorInfo() = default; + virtual std::vector getExposureRegisters(int exposure_time, int new_exp_g, bool dc_gain_enabled) const { return {}; } + virtual float getExposureScore(float desired_ev, int exp_t, int exp_g_idx, float exp_gain, int gain_idx) const {return 0; } + virtual int getSlaveAddress(int port) const { assert(0); } + + cereal::FrameData::ImageSensor image_sensor = cereal::FrameData::ImageSensor::UNKNOWN; + float pixel_size_mm; + uint32_t frame_width, frame_height; + uint32_t frame_stride; + uint32_t frame_offset = 0; + uint32_t extra_height = 0; + int out_scale = 1; + int registers_offset = -1; + int stats_offset = -1; + int hdr_offset = -1; + + int exposure_time_min; + int exposure_time_max; + + float dc_gain_factor; + int dc_gain_min_weight; + int dc_gain_max_weight; + float dc_gain_on_grey; + float dc_gain_off_grey; + + float ev_scale = 1.0; + float sensor_analog_gains[ANALOG_GAIN_MAX_CNT]; + int analog_gain_min_idx; + int analog_gain_max_idx; + int analog_gain_rec_idx; + int analog_gain_cost_delta; + float analog_gain_cost_low; + float analog_gain_cost_high; + float target_grey_factor; + float min_ev; + float max_ev; + + bool data_word; + uint32_t probe_reg_addr; + uint32_t probe_expected_data; + std::vector start_reg_array; + std::vector init_reg_array; + + uint32_t bits_per_pixel; + uint32_t bayer_pattern; + uint32_t mipi_format; + uint32_t mclk_frequency; + uint32_t frame_data_type; + + uint32_t readout_time_ns; // used to recover EOF from SOF + + // ISP image processing params + uint32_t black_level; + std::vector color_correct_matrix; // 3x3 + std::vector gamma_lut_rgb; // gamma LUTs are length 64 * sizeof(uint32_t); same for r/g/b here + void prepare_gamma_lut() { + for (int i = 0; i < 64; i++) { + gamma_lut_rgb[i] |= ((uint32_t)(gamma_lut_rgb[i+1] - gamma_lut_rgb[i]) << 10); + } + gamma_lut_rgb.pop_back(); + } + std::vector linearization_lut; // length 36 + std::vector linearization_pts; // length 4 + std::vector vignetting_lut; // length 221 + + const int num() const { + return static_cast(image_sensor); + }; +}; + +class OX03C10 : public SensorInfo { +public: + OX03C10(); + std::vector getExposureRegisters(int exposure_time, int new_exp_g, bool dc_gain_enabled) const override; + float getExposureScore(float desired_ev, int exp_t, int exp_g_idx, float exp_gain, int gain_idx) const override; + int getSlaveAddress(int port) const override; +}; + +class OS04C10 : public SensorInfo { +public: + OS04C10(); + std::vector getExposureRegisters(int exposure_time, int new_exp_g, bool dc_gain_enabled) const override; + float getExposureScore(float desired_ev, int exp_t, int exp_g_idx, float exp_gain, int gain_idx) const override; + int getSlaveAddress(int port) const override; +}; diff --git a/openpilot/system/camerad/snapshot.py b/openpilot/system/camerad/snapshot.py new file mode 100755 index 0000000000..8383865fce --- /dev/null +++ b/openpilot/system/camerad/snapshot.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python3 + +import numpy as np + +import openpilot.cereal.messaging as messaging +from msgq.visionipc import VisionIpcClient, VisionStreamType +from openpilot.common.realtime import DT_MDL + + +VISION_STREAMS = { + "roadCameraState": VisionStreamType.VISION_STREAM_ROAD, + "driverCameraState": VisionStreamType.VISION_STREAM_DRIVER, + "wideRoadCameraState": VisionStreamType.VISION_STREAM_WIDE_ROAD, +} + + +def yuv_to_rgb(y, u, v): + ul = np.repeat(np.repeat(u, 2).reshape(u.shape[0], y.shape[1]), 2, axis=0).reshape(y.shape) + vl = np.repeat(np.repeat(v, 2).reshape(v.shape[0], y.shape[1]), 2, axis=0).reshape(y.shape) + + yuv = np.dstack((y, ul, vl)).astype(np.int16) + yuv[:, :, 1:] -= 128 + + m = np.array([ + [1.00000, 1.00000, 1.00000], + [0.00000, -0.39465, 2.03211], + [1.13983, -0.58060, 0.00000], + ]) + rgb = np.dot(yuv, m).clip(0, 255) + return rgb.astype(np.uint8) + + +def extract_image(buf): + # NV12 format: Y plane followed by interleaved UV plane + # UV plane size is stride * uv_height, where uv_height = align(height/2, 16) + uv_height = ((buf.height // 2) + 15) // 16 * 16 + uv_plane_size = buf.stride * uv_height + + y = np.array(buf.data[:buf.uv_offset], dtype=np.uint8).reshape((-1, buf.stride))[:buf.height, :buf.width] + uv_data = buf.data[buf.uv_offset:buf.uv_offset + uv_plane_size] + u = np.array(uv_data[::2], dtype=np.uint8).reshape((-1, buf.stride//2))[:buf.height//2, :buf.width//2] + v = np.array(uv_data[1::2], dtype=np.uint8).reshape((-1, buf.stride//2))[:buf.height//2, :buf.width//2] + + return yuv_to_rgb(y, u, v) + + +def get_snapshots(frame="roadCameraState", front_frame="driverCameraState"): + sockets = [s for s in (frame, front_frame) if s is not None] + sm = messaging.SubMaster(sockets) + vipc_clients = {s: VisionIpcClient("camerad", VISION_STREAMS[s], True) for s in sockets} + + # wait 4 sec from camerad startup for focus and exposure + while sm[sockets[0]].frameId < int(4. / DT_MDL): + sm.update() + + for client in vipc_clients.values(): + client.connect(True) + + # grab images + rear, front = None, None + if frame is not None: + c = vipc_clients[frame] + rear = extract_image(c.recv()) + if front_frame is not None: + c = vipc_clients[front_frame] + front = extract_image(c.recv()) + return rear, front diff --git a/system/camerad/test/.gitignore b/openpilot/system/camerad/test/.gitignore similarity index 100% rename from system/camerad/test/.gitignore rename to openpilot/system/camerad/test/.gitignore diff --git a/system/camerad/test/debug.sh b/openpilot/system/camerad/test/debug.sh similarity index 94% rename from system/camerad/test/debug.sh rename to openpilot/system/camerad/test/debug.sh index a031be6923..eba167ce6a 100755 --- a/system/camerad/test/debug.sh +++ b/openpilot/system/camerad/test/debug.sh @@ -8,7 +8,7 @@ echo 0xfffdbfff | sudo tee /sys/module/cam_debug_util/parameters/debug_mdl #echo 0 | sudo tee /sys/module/cam_debug_util/parameters/debug_mdl sudo dmesg -C -scons -u -j8 --minimal . +scons -u --minimal . export DEBUG_FRAMES=1 export DISABLE_ROAD=1 DISABLE_WIDE_ROAD=1 #export DISABLE_DRIVER=1 diff --git a/system/camerad/test/icp_debug.sh b/openpilot/system/camerad/test/icp_debug.sh similarity index 100% rename from system/camerad/test/icp_debug.sh rename to openpilot/system/camerad/test/icp_debug.sh diff --git a/system/camerad/test/intercept.sh b/openpilot/system/camerad/test/intercept.sh similarity index 100% rename from system/camerad/test/intercept.sh rename to openpilot/system/camerad/test/intercept.sh diff --git a/system/camerad/test/stress_restart.sh b/openpilot/system/camerad/test/stress_restart.sh similarity index 100% rename from system/camerad/test/stress_restart.sh rename to openpilot/system/camerad/test/stress_restart.sh diff --git a/system/camerad/test/test_ae_gray.cc b/openpilot/system/camerad/test/test_ae_gray.cc similarity index 100% rename from system/camerad/test/test_ae_gray.cc rename to openpilot/system/camerad/test/test_ae_gray.cc diff --git a/openpilot/system/camerad/test/test_camerad.py b/openpilot/system/camerad/test/test_camerad.py new file mode 100644 index 0000000000..afc49c02bf --- /dev/null +++ b/openpilot/system/camerad/test/test_camerad.py @@ -0,0 +1,162 @@ +import os +import time +import pytest +import numpy as np + +from openpilot.cereal.services import SERVICE_LIST +from openpilot.tools.lib.log_time_series import msgs_to_time_series +from openpilot.system.camerad.snapshot import get_snapshots +from openpilot.selfdrive.test.helpers import collect_logs, log_collector, processes_context + +TEST_TIMESPAN = 10 +CAMERAS = ('roadCameraState', 'driverCameraState', 'wideRoadCameraState') +EXPOSURE_STABLE_COUNT = 3 +EXPOSURE_RANGE = (0.15, 0.35) +MAX_TEST_TIME = 25 + + +def _numpy_rgb2gray(im): + return np.clip(im[:,:,2] * 0.114 + im[:,:,1] * 0.587 + im[:,:,0] * 0.299, 0, 255).astype(np.uint8) + +def _exposure_stats(im): + h, w = im.shape[:2] + gray = _numpy_rgb2gray(im[h//10:9*h//10, w//10:9*w//10]) + return float(np.median(gray) / 255.), float(np.mean(gray) / 255.) + +def _in_range(median, mean): + lo, hi = EXPOSURE_RANGE + return lo < median < hi and lo < mean < hi + +def _exposure_stable(results): + return all( + len(v) >= EXPOSURE_STABLE_COUNT and all(_in_range(*s) for s in v[-EXPOSURE_STABLE_COUNT:]) + for v in results.values() + ) + + +def run_and_log(procs, services, duration): + with processes_context(procs): + return collect_logs(services, duration) + +@pytest.fixture(scope="module") +def _camera_session(): + """Single camerad session that collects logs and exposure data. + Runs until exposure stabilizes (min TEST_TIMESPAN seconds for enough log data).""" + with processes_context(["camerad"]), log_collector(CAMERAS) as (raw_logs, lock): + exposure = {cam: [] for cam in CAMERAS} + start = time.monotonic() + while time.monotonic() - start < MAX_TEST_TIME: + rpic, dpic = get_snapshots(frame="roadCameraState", front_frame="driverCameraState") + wpic, _ = get_snapshots(frame="wideRoadCameraState") + for cam, img in zip(CAMERAS, [rpic, dpic, wpic], strict=True): + exposure[cam].append(_exposure_stats(img)) + + if time.monotonic() - start >= TEST_TIMESPAN and _exposure_stable(exposure): + break + + elapsed = time.monotonic() - start + + with lock: + ts = msgs_to_time_series(raw_logs) + + for cam in CAMERAS: + expected_frames = SERVICE_LIST[cam].frequency * elapsed + cnt = len(ts[cam]['t']) + assert expected_frames*0.8 < cnt < expected_frames*1.2, f"unexpected frame count {cam}: {expected_frames=}, got {cnt}" + + dts = np.abs(np.diff([ts[cam]['timestampSof']/1e6]) - 1000/SERVICE_LIST[cam].frequency) + assert (dts < 1.0).all(), f"{cam} dts(ms) out of spec: max diff {dts.max()}, 99 percentile {np.percentile(dts, 99)}" + + return ts, exposure + +@pytest.fixture(scope="module") +def logs(_camera_session): + return _camera_session[0] + +@pytest.fixture(scope="module") +def exposure_data(_camera_session): + return _camera_session[1] + +@pytest.mark.tici +class TestCamerad: + @pytest.mark.parametrize("cam", CAMERAS) + def test_camera_exposure(self, exposure_data, cam): + lo, hi = EXPOSURE_RANGE + checks = exposure_data[cam] + assert len(checks) >= EXPOSURE_STABLE_COUNT, f"{cam}: only got {len(checks)} samples" + + # check that exposure converges into the valid range + passed = sum(_in_range(med, mean) for med, mean in checks) + assert passed >= EXPOSURE_STABLE_COUNT, \ + f"{cam}: only {passed}/{len(checks)} checks in range. " + \ + " | ".join(f"#{i+1}: med={m:.4f} mean={u:.4f}" for i, (m, u) in enumerate(checks)) + + # check that exposure is stable once converged (no regressions) + in_range = False + for i, (median, mean) in enumerate(checks): + ok = _in_range(median, mean) + if in_range and not ok: + pytest.fail(f"{cam}: exposure regressed on sample {i+1} " + + f"(median={median:.4f}, mean={mean:.4f}, expected: ({lo}, {hi}))") + in_range = ok + + def test_frame_skips(self, logs): + for c in CAMERAS: + assert set(np.diff(logs[c]['frameId'])) == {1, }, f"{c} has frame skips" + + def test_frame_sync(self, logs): + SYNCED_CAMS = ('roadCameraState', 'wideRoadCameraState') + n = range(len(logs['roadCameraState']['t'][:-10])) + + frame_ids = {i: [logs[cam]['frameId'][i] for cam in CAMERAS] for i in n} + assert all(len(set(v)) == 1 for v in frame_ids.values()), "frame IDs not aligned" + + # road and wide cameras should be synced within 1.1ms + synced_times = {i: [logs[cam]['timestampSof'][i] for cam in SYNCED_CAMS] for i in n} + diffs = {i: (max(ts) - min(ts))/1e6 for i, ts in synced_times.items()} + laggy_frames = {k: v for k, v in diffs.items() if v > 1.1} + assert len(laggy_frames) == 0, f"Frames not synced properly: {laggy_frames=}" + + # driver camera should be staggered ~25ms from road camera + for i in n: + offset_ms = abs(logs['driverCameraState']['timestampSof'][i] - logs['roadCameraState']['timestampSof'][i]) / 1e6 + assert 20 < offset_ms < 30, f"driver camera stagger out of range at frame {i}: {offset_ms:.1f}ms (expected ~25ms)" + + def test_sanity_checks(self, logs): + self._sanity_checks(logs) + + def _sanity_checks(self, ts): + for c in CAMERAS: + assert c in ts + assert len(ts[c]['t']) > 20 + + # not a valid request id + assert 0 not in ts[c]['requestId'] + + # should monotonically increase + assert np.all(np.diff(ts[c]['frameId']) >= 1) + assert np.all(np.diff(ts[c]['requestId']) >= 1) + + # EOF > SOF + assert np.all((ts[c]['timestampEof'] - ts[c]['timestampSof']) > 0) + + # logMonoTime > SOF + assert np.all((ts[c]['t'] - ts[c]['timestampSof']/1e9) > 1e-7) + + # logMonoTime > EOF, needs some tolerance since EOF is (SOF + readout time) but there is noise in the SOF timestamping (done via IRQ) + assert np.mean((ts[c]['t'] - ts[c]['timestampEof']/1e9) > 1e-7) > 0.7 # should be mostly logMonoTime > EOF + assert np.all((ts[c]['t'] - ts[c]['timestampEof']/1e9) > -0.10) # when EOF > logMonoTime, it should never be more than two frames + + def test_stress_test(self): + os.environ['SPECTRA_ERROR_PROB'] = '0.008' + try: + logs = run_and_log(["camerad", ], CAMERAS, 10) + finally: + del os.environ['SPECTRA_ERROR_PROB'] + ts = msgs_to_time_series(logs) + + # we should see some jumps from introduced errors + assert np.max([ np.max(np.diff(ts[c]['frameId'])) for c in CAMERAS ]) > 1 + assert np.max([ np.max(np.diff(ts[c]['requestId'])) for c in CAMERAS ]) > 1 + + self._sanity_checks(ts) diff --git a/openpilot/system/camerad/webcam/README.md b/openpilot/system/camerad/webcam/README.md new file mode 100644 index 0000000000..17d7ee6d80 --- /dev/null +++ b/openpilot/system/camerad/webcam/README.md @@ -0,0 +1,24 @@ +# Run openpilot with webcam on PC + +## Setup openpilot +- Follow [this readme](../README.md) to install and build the requirements + +## Connect the hardware +- Connect the camera first +- Connect your computer to panda + +## GO + +``` +USE_WEBCAM=1 openpilot/system/manager/manager.py +``` +- Start the car, then the UI should show the road webcam's view +- Adjust and secure the webcam +- Finish calibration and engage! + +## Specify Cameras + +Use the `ROAD_CAM` (default 0) and optional `DRIVER_CAM`, `WIDE_CAM` environment variables to specify which camera is which (ie. `ROAD_CAM=1` uses `/dev/video1`, on Ubuntu, for the road camera): +``` +USE_WEBCAM=1 ROAD_CAM=1 openpilot/system/manager/manager.py +``` diff --git a/openpilot/system/camerad/webcam/camera.py b/openpilot/system/camerad/webcam/camera.py new file mode 100644 index 0000000000..7926766c6f --- /dev/null +++ b/openpilot/system/camerad/webcam/camera.py @@ -0,0 +1,39 @@ +import av +import cv2 as cv + +class Camera: + def __init__(self, cam_type_state, stream_type, camera_id): + try: + camera_id = int(camera_id) + except ValueError: # allow strings, ex: /dev/video0 + pass + self.cam_type_state = cam_type_state + self.stream_type = stream_type + self.cur_frame_id = 0 + + print(f"Opening {cam_type_state} at {camera_id}") + + self.cap = cv.VideoCapture(camera_id) + + self.cap.set(cv.CAP_PROP_FRAME_WIDTH, 1280.0) + self.cap.set(cv.CAP_PROP_FRAME_HEIGHT, 720.0) + self.cap.set(cv.CAP_PROP_FPS, 25.0) + + self.W = self.cap.get(cv.CAP_PROP_FRAME_WIDTH) + self.H = self.cap.get(cv.CAP_PROP_FRAME_HEIGHT) + + @classmethod + def bgr2nv12(self, bgr): + frame = av.VideoFrame.from_ndarray(bgr, format='bgr24') + return frame.reformat(format='nv12').to_ndarray() + + def read_frames(self): + while True: + ret, frame = self.cap.read() + if not ret: + break + # Rotate the frame 180 degrees (flip both axes) + frame = cv.flip(frame, -1) + yuv = Camera.bgr2nv12(frame) + yield yuv.data.tobytes() + self.cap.release() diff --git a/openpilot/system/camerad/webcam/camerad.py b/openpilot/system/camerad/webcam/camerad.py new file mode 100755 index 0000000000..c46482360d --- /dev/null +++ b/openpilot/system/camerad/webcam/camerad.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +import threading +import os +import platform +from collections import namedtuple + +from msgq.visionipc import VisionIpcServer, VisionStreamType +from openpilot.cereal import messaging + +from openpilot.system.camerad.webcam.camera import Camera +from openpilot.common.realtime import Ratekeeper + +ROAD_CAM = os.getenv("ROAD_CAM", "0") +WIDE_CAM = os.getenv("WIDE_CAM") +DRIVER_CAM = os.getenv("DRIVER_CAM") + +CameraType = namedtuple("CameraType", ["msg_name", "stream_type", "cam_id"]) + +CAMERAS = [ + CameraType("roadCameraState", VisionStreamType.VISION_STREAM_ROAD, ROAD_CAM) +] +if WIDE_CAM: + CAMERAS.append(CameraType("wideRoadCameraState", VisionStreamType.VISION_STREAM_WIDE_ROAD, WIDE_CAM)) +if DRIVER_CAM: + CAMERAS.append(CameraType("driverCameraState", VisionStreamType.VISION_STREAM_DRIVER, DRIVER_CAM)) + +class Camerad: + def __init__(self): + self.pm = messaging.PubMaster([c.msg_name for c in CAMERAS]) + self.vipc_server = VisionIpcServer("camerad") + + self.cameras = [] + for c in CAMERAS: + cam_device = f"/dev/video{c.cam_id}" if platform.system() != "Darwin" else c.cam_id + cam = Camera(c.msg_name, c.stream_type, cam_device) + self.cameras.append(cam) + self.vipc_server.create_buffers(c.stream_type, 20, cam.W, cam.H) + + self.vipc_server.start_listener() + + def _send_yuv(self, yuv, frame_id, pub_type, yuv_type): + eof = int(frame_id * 0.05 * 1e9) + self.vipc_server.send(yuv_type, yuv, frame_id, eof, eof) + dat = messaging.new_message(pub_type, valid=True) + msg = { + "frameId": frame_id, + "transform": [1.0, 0.0, 0.0, + 0.0, 1.0, 0.0, + 0.0, 0.0, 1.0] + } + setattr(dat, pub_type, msg) + self.pm.send(pub_type, dat) + + def camera_runner(self, cam): + rk = Ratekeeper(20, None) + for yuv in cam.read_frames(): + self._send_yuv(yuv, cam.cur_frame_id, cam.cam_type_state, cam.stream_type) + cam.cur_frame_id += 1 + rk.keep_time() + + def run(self): + threads = [] + for cam in self.cameras: + cam_thread = threading.Thread(target=self.camera_runner, args=(cam,)) + cam_thread.start() + threads.append(cam_thread) + + for t in threads: + t.join() + + +def main(): + camerad = Camerad() + camerad.run() + + +if __name__ == "__main__": + main() diff --git a/openpilot/system/hardware/fan_controller.py b/openpilot/system/hardware/fan_controller.py new file mode 100755 index 0000000000..869fe19c3d --- /dev/null +++ b/openpilot/system/hardware/fan_controller.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python3 +import numpy as np + +from openpilot.common.pid import PIDController +from openpilot.common.hardware import HARDWARE + +# raise fan setpoint on tici/tizi to reduce noise +# after raising LMH threshold in AGNOS 18.1 to prevent CPU throttling +OFFSET = 0 if HARDWARE.get_device_type() == "mici" else 5 + + +class FanController: + def __init__(self, rate: int) -> None: + self.last_ignition = False + self.controller = PIDController(k_p=0, k_i=4e-3, rate=rate) + + def update(self, cur_temp: float, ignition: bool) -> int: + self.controller.pos_limit = 100 if ignition else 30 + self.controller.neg_limit = 30 if ignition else 0 + + if ignition != self.last_ignition: + self.controller.reset() + self.last_ignition = ignition + + return int(self.controller.update( + error=(cur_temp - (75 + OFFSET)), # temperature setpoint in C + feedforward=np.interp(cur_temp, [60.0 + OFFSET, 100.0 + OFFSET], [0, 100]) + )) diff --git a/system/hardware/hardwared.py b/openpilot/system/hardware/hardwared.py similarity index 78% rename from system/hardware/hardwared.py rename to openpilot/system/hardware/hardwared.py index 223faeaafd..e5b3d8020c 100755 --- a/system/hardware/hardwared.py +++ b/openpilot/system/hardware/hardwared.py @@ -1,31 +1,30 @@ #!/usr/bin/env python3 import fcntl import os -import json import queue import struct import threading import time from collections import OrderedDict, namedtuple -from pathlib import Path -import psutil - -import cereal.messaging as messaging -from cereal import log -from cereal.services import SERVICE_LIST -from openpilot.common.dict_helpers import strip_deprecated_keys +import openpilot.cereal.messaging as messaging +from openpilot.cereal import log +from openpilot.cereal.services import SERVICE_LIST +from openpilot.common.utils import strip_deprecated_keys from openpilot.common.filter_simple import FirstOrderFilter from openpilot.common.params import Params from openpilot.common.realtime import DT_HW from openpilot.selfdrive.selfdrived.alertmanager import set_offroad_alert -from openpilot.system.hardware import HARDWARE, TICI, AGNOS +from openpilot.common.hardware import HARDWARE, TICI +from openpilot.common.hardware.usb import get_usb_state, set_usb_state +from openpilot.common.linux import LinuxSystemStats from openpilot.system.loggerd.config import get_available_percent -from openpilot.system.statsd import statlog from openpilot.common.swaglog import cloudlog +from openpilot.sunnypilot.system.statsd import statlog from openpilot.system.hardware.power_monitoring import PowerMonitoring -from openpilot.system.hardware.fan_controller import TiciFanController -from openpilot.system.version import terms_version, training_version +from openpilot.system.hardware.fan_controller import FanController +from openpilot.common.version import terms_version, training_version, get_build_metadata, terms_version_sp + ThermalStatus = log.DeviceState.ThermalStatus NetworkType = log.DeviceState.NetworkType @@ -38,19 +37,25 @@ ONROAD_CYCLE_TIME = 1 # seconds to wait offroad after requesting an onroad cycl ThermalBand = namedtuple("ThermalBand", ['min_temp', 'max_temp']) HardwareState = namedtuple("HardwareState", ['network_type', 'network_info', 'network_strength', 'network_stats', - 'network_metered', 'nvme_temps', 'modem_temps']) + 'network_metered', 'modem_temps', 'usb_state']) # List of thermal bands. We will stay within this region as long as we are within the bounds. # When exiting the bounds, we'll jump to the lower or higher band. Bands are ordered in the dict. -THERMAL_BANDS = OrderedDict({ - ThermalStatus.green: ThermalBand(None, 80.0), - ThermalStatus.yellow: ThermalBand(75.0, 96.0), - ThermalStatus.red: ThermalBand(88.0, 107.), - ThermalStatus.danger: ThermalBand(94.0, None), -}) +if HARDWARE.get_device_type() == "mici": + THERMAL_BANDS = OrderedDict({ + ThermalStatus.ok: ThermalBand(None, 100.0), + ThermalStatus.overheated: ThermalBand(92.0, 107.), + ThermalStatus.critical: ThermalBand(98.0, None), + }) +else: + THERMAL_BANDS = OrderedDict({ + ThermalStatus.ok: ThermalBand(None, 96.0), + ThermalStatus.overheated: ThermalBand(88.0, 107.), + ThermalStatus.critical: ThermalBand(94.0, None), + }) # Override to highest thermal band when offroad and above this temp -OFFROAD_DANGER_TEMP = 75 +OFFROAD_DANGER_TEMP = 85 if HARDWARE.get_device_type() == "mici" else 75 prev_offroad_states: dict[str, tuple[bool, str | None]] = {} @@ -102,11 +107,6 @@ def hw_state_thread(end_event, hw_queue): count = 0 prev_hw_state = None - modem_version = None - modem_configured = False - modem_restarted = False - modem_missing_count = 0 - while not end_event.is_set(): # these are expensive calls. update every 10s if (count % int(10. / DT_HW)) == 0: @@ -116,23 +116,6 @@ def hw_state_thread(end_event, hw_queue): if len(modem_temps) == 0 and prev_hw_state is not None: modem_temps = prev_hw_state.modem_temps - # Log modem version once - if AGNOS and (modem_version is None): - modem_version = HARDWARE.get_modem_version() - - if modem_version is not None: - cloudlog.event("modem version", version=modem_version) - else: - if not modem_restarted: - # TODO: we may be able to remove this with a MM update - # ModemManager's probing on startup can fail - # rarely, restart the service to probe again. - modem_missing_count += 1 - if modem_missing_count > 3: - modem_restarted = True - cloudlog.event("restarting ModemManager") - os.system("sudo systemctl restart --no-block ModemManager") - tx, rx = HARDWARE.get_modem_data_usage() hw_state = HardwareState( @@ -141,8 +124,8 @@ def hw_state_thread(end_event, hw_queue): network_strength=HARDWARE.get_network_strength(network_type), network_stats={'wwanTx': tx, 'wwanRx': rx}, network_metered=HARDWARE.get_network_metered(network_type), - nvme_temps=HARDWARE.get_nvme_temperatures(), modem_temps=modem_temps, + usb_state=get_usb_state(), ) try: @@ -150,11 +133,6 @@ def hw_state_thread(end_event, hw_queue): except queue.Full: pass - if not modem_configured and HARDWARE.get_modem_version() is not None: - cloudlog.warning("configuring modem") - HARDWARE.configure_modem() - modem_configured = True - prev_hw_state = hw_state except Exception: cloudlog.exception("Error getting hardware state") @@ -164,6 +142,7 @@ def hw_state_thread(end_event, hw_queue): def hardware_thread(end_event, hw_queue) -> None: + system_stats = LinuxSystemStats() pm = messaging.PubMaster(['deviceState']) sm = messaging.SubMaster(["peripheralState", "gpsLocationExternal", "selfdriveState", "pandaStates"], poll="pandaStates") @@ -172,6 +151,7 @@ def hardware_thread(end_event, hw_queue) -> None: onroad_conditions: dict[str, bool] = { "ignition": False, "not_onroad_cycle": True, + "device_temp_good": True, } startup_conditions: dict[str, bool] = {} startup_conditions_prev: dict[str, bool] = {} @@ -180,7 +160,7 @@ def hardware_thread(end_event, hw_queue) -> None: started_ts: float | None = None started_seen = False startup_blocked_ts: float | None = None - thermal_status = ThermalStatus.yellow + thermal_status = ThermalStatus.ok last_hw_state = HardwareState( network_type=NetworkType.none, @@ -188,8 +168,8 @@ def hardware_thread(end_event, hw_queue) -> None: network_metered=False, network_strength=NetworkStrength.unknown, network_stats={'wwanTx': -1, 'wwanRx': -1}, - nvme_temps=[], modem_temps=[], + usb_state=[], ) all_temp_filter = FirstOrderFilter(0., TEMP_TAU, DT_HW, initialized=False) @@ -197,26 +177,30 @@ def hardware_thread(end_event, hw_queue) -> None: should_start_prev = False in_car = False engaged_prev = False + pwrsave = False offroad_cycle_count = 0 params = Params() power_monitor = PowerMonitoring() + uptime_offroad: float = params.get("UptimeOffroad", return_default=True) + uptime_onroad: float = params.get("UptimeOnroad", return_default=True) + last_uptime_ts: float = time.monotonic() + HARDWARE.initialize_hardware() thermal_config = HARDWARE.get_thermal_config() - fan_controller = None + fan_controller = FanController(int(1./DT_HW)) while not end_event.is_set(): sm.update(PANDA_STATES_TIMEOUT) pandaStates = sm['pandaStates'] peripheralState = sm['peripheralState'] - peripheral_panda_present = peripheralState.pandaType != log.PandaState.PandaType.unknown # handle requests to cycle system started state if params.get_bool("OnroadCycleRequested"): - params.put_bool("OnroadCycleRequested", False) + params.put_bool("OnroadCycleRequested", False, block=True) offroad_cycle_count = sm.frame onroad_conditions["not_onroad_cycle"] = (sm.frame - offroad_cycle_count) >= ONROAD_CYCLE_TIME * SERVICE_LIST['pandaStates'].frequency @@ -229,11 +213,6 @@ def hardware_thread(end_event, hw_queue) -> None: in_car = pandaState.harnessStatus != log.PandaState.HarnessStatus.notConnected - # Setup fan handler on first connect to panda - if fan_controller is None and peripheral_panda_present: - if TICI: - fan_controller = TiciFanController() - elif (time.monotonic() - sm.recv_time['pandaStates']) > DISCONNECT_TIMEOUT: if onroad_conditions["ignition"]: onroad_conditions["ignition"] = False @@ -254,9 +233,9 @@ def hardware_thread(end_event, hw_queue) -> None: pass msg.deviceState.freeSpacePercent = get_available_percent(default=100.0) - msg.deviceState.memoryUsagePercent = int(round(psutil.virtual_memory().percent)) + msg.deviceState.memoryUsagePercent = int(round(system_stats.memory_usage_percent())) msg.deviceState.gpuUsagePercent = int(round(HARDWARE.get_gpu_usage_percent())) - online_cpu_usage = [int(round(n)) for n in psutil.cpu_percent(percpu=True)] + online_cpu_usage = [int(round(n)) for n in system_stats.cpu_usage_percent()] offline_cpu_usage = [0., ] * (len(msg.deviceState.cpuTempC) - len(online_cpu_usage)) msg.deviceState.cpuUsagePercent = online_cpu_usage + offline_cpu_usage @@ -267,11 +246,12 @@ def hardware_thread(end_event, hw_queue) -> None: if last_hw_state.network_info is not None: msg.deviceState.networkInfo = last_hw_state.network_info - msg.deviceState.nvmeTempC = last_hw_state.nvme_temps msg.deviceState.modemTempC = last_hw_state.modem_temps msg.deviceState.screenBrightnessPercent = HARDWARE.get_screen_brightness() + set_usb_state(msg.deviceState, last_hw_state.usb_state) + # this subset is only used for offroad temp_sources = [ msg.deviceState.memoryTempC, @@ -285,14 +265,13 @@ def hardware_thread(end_event, hw_queue) -> None: all_comp_temp = all_temp_filter.update(max(temp_sources)) msg.deviceState.maxTempC = all_comp_temp - if fan_controller is not None: - msg.deviceState.fanSpeedPercentDesired = fan_controller.update(all_comp_temp, onroad_conditions["ignition"]) + msg.deviceState.fanSpeedPercentDesired = fan_controller.update(all_comp_temp, onroad_conditions["ignition"]) is_offroad_for_5_min = (started_ts is None) and ((not started_seen) or (off_ts is None) or (time.monotonic() - off_ts > 60 * 5)) if is_offroad_for_5_min and offroad_comp_temp > OFFROAD_DANGER_TEMP: # if device is offroad and already hot without the extra onroad load, # we want to cool down first before increasing load - thermal_status = ThermalStatus.danger + thermal_status = ThermalStatus.critical else: current_band = THERMAL_BANDS[thermal_status] band_idx = list(THERMAL_BANDS.keys()).index(thermal_status) @@ -304,17 +283,18 @@ def hardware_thread(end_event, hw_queue) -> None: # **** starting logic **** startup_conditions["up_to_date"] = params.get("Offroad_ConnectivityNeeded") is None or params.get_bool("DisableUpdates") or params.get_bool("SnoozeUpdate") + startup_conditions["no_excessive_actuation"] = params.get("Offroad_ExcessiveActuation") is None startup_conditions["not_uninstalling"] = not params.get_bool("DoUninstall") startup_conditions["accepted_terms"] = params.get("HasAcceptedTerms") == terms_version + startup_conditions["accepted_terms_sp"] = params.get("HasAcceptedTermsSP") == terms_version_sp # with 2% left, we killall, otherwise the phone will take a long time to boot startup_conditions["free_space"] = msg.deviceState.freeSpacePercent > 2 startup_conditions["completed_training"] = params.get("CompletedTrainingVersion") == training_version startup_conditions["not_driver_view"] = not params.get_bool("IsDriverViewEnabled") - startup_conditions["not_taking_snapshot"] = not params.get_bool("IsTakingSnapshot") # must be at an engageable thermal band to go onroad - startup_conditions["device_temp_engageable"] = thermal_status < ThermalStatus.red + startup_conditions["device_temp_engageable"] = thermal_status < ThermalStatus.overheated # ensure device is fully booted startup_conditions["device_booted"] = startup_conditions.get("device_booted", False) or HARDWARE.booted() @@ -324,27 +304,24 @@ def hardware_thread(end_event, hw_queue) -> None: startup_conditions["not_always_offroad"] = not offroad_mode onroad_conditions["not_always_offroad"] = not offroad_mode + # if an unsupported device and branch is detected, going onroad is blocked + # only allow going onroad when: + # - TIZI, or + # - TICI and channel_type is "tici" + build_metadata = get_build_metadata() + is_unsupported_combo = TICI and HARDWARE.get_device_type() == "tici" and build_metadata.channel_type != "tici" + startup_conditions["not_tici"] = not is_unsupported_combo + onroad_conditions["not_tici"] = not is_unsupported_combo + set_offroad_alert("Offroad_TiciSupport", is_unsupported_combo, extra_text=build_metadata.channel) + # if the temperature enters the danger zone, go offroad to cool down - onroad_conditions["device_temp_good"] = thermal_status < ThermalStatus.danger + onroad_conditions["device_temp_good"] = thermal_status < ThermalStatus.critical extra_text = f"{offroad_comp_temp:.1f}C" show_alert = (not onroad_conditions["device_temp_good"] or not startup_conditions["device_temp_engageable"]) and onroad_conditions["ignition"] set_offroad_alert_if_changed("Offroad_TemperatureTooHigh", show_alert, extra_text=extra_text) - # TODO: this should move to TICI.initialize_hardware, but we currently can't import params there - if TICI and HARDWARE.get_device_type() == "tici": - if not os.path.isfile("/persist/comma/living-in-the-moment"): - if not Path("/data/media").is_mount(): - set_offroad_alert_if_changed("Offroad_StorageMissing", True) - else: - # check for bad NVMe - try: - with open("/sys/block/nvme0n1/device/model") as f: - model = f.read().strip() - if not model.startswith("Samsung SSD 980") and params.get("Offroad_BadNvme") is None: - set_offroad_alert_if_changed("Offroad_BadNvme", True) - cloudlog.event("Unsupported NVMe", model=model, error=True) - except Exception: - pass + if show_alert: + msg.deviceState.fanSpeedPercentDesired = 100 # Handle offroad/onroad transition should_start = all(onroad_conditions.values()) @@ -352,14 +329,13 @@ def hardware_thread(end_event, hw_queue) -> None: should_start = should_start and all(startup_conditions.values()) if should_start != should_start_prev or (count == 0): - params.put_bool("IsEngaged", False) + params.put_bool("IsEngaged", False, block=True) engaged_prev = False - HARDWARE.set_power_save(not should_start) if sm.updated['selfdriveState']: engaged = sm['selfdriveState'].enabled if engaged != engaged_prev: - params.put_bool("IsEngaged", engaged) + params.put_bool("IsEngaged", engaged, block=True) engaged_prev = engaged try: @@ -368,6 +344,11 @@ def hardware_thread(end_event, hw_queue) -> None: except Exception: pass + should_pwrsave = not onroad_conditions["ignition"] and msg.deviceState.screenBrightnessPercent < 1e-3 + if should_pwrsave != pwrsave or (count == 0): + HARDWARE.set_power_save(should_pwrsave) + pwrsave = should_pwrsave + if should_start: off_ts = None if started_ts is None: @@ -390,6 +371,11 @@ def hardware_thread(end_event, hw_queue) -> None: # Offroad power monitoring voltage = None if peripheralState.pandaType == log.PandaState.PandaType.unknown else peripheralState.voltage + + # GitHub runner auto off: 9V is used as the threshold because most desktop runners + # will rarely exceed 5V so 9V is set as our buffer between desk use and car use. + params.put_bool("GithubRunnerSufficientVoltage", ((voltage or 0) and voltage > 9000)) + power_monitor.calculate(voltage, onroad_conditions["ignition"]) msg.deviceState.offroadPowerUsageUwh = power_monitor.get_power_used() msg.deviceState.carBatteryCapacityUwh = max(0, power_monitor.get_car_battery_capacity()) @@ -404,19 +390,18 @@ def hardware_thread(end_event, hw_queue) -> None: # Check if we need to shut down if power_monitor.should_shutdown(onroad_conditions["ignition"], in_car, off_ts, started_seen): cloudlog.warning(f"shutting device down, offroad since {off_ts}") - params.put_bool("DoShutdown", True) + params.put_bool("DoShutdown", True, block=True) msg.deviceState.started = started_ts is not None and not offroad_mode msg.deviceState.startedMonoTime = int(1e9*(started_ts or 0)) last_ping = params.get("LastAthenaPingTime") if last_ping is not None: - msg.deviceState.lastAthenaPingTime = int(last_ping) + msg.deviceState.lastAthenaPingTime = last_ping msg.deviceState.thermalStatus = thermal_status pm.send("deviceState", msg) - # Log to statsd statlog.gauge("free_space_percent", msg.deviceState.freeSpacePercent) statlog.gauge("gpu_usage_percent", msg.deviceState.gpuUsagePercent) statlog.gauge("memory_usage_percent", msg.deviceState.memoryUsagePercent) @@ -429,16 +414,15 @@ def hardware_thread(end_event, hw_queue) -> None: statlog.gauge("memory_temperature", msg.deviceState.memoryTempC) for i, temp in enumerate(msg.deviceState.pmicTempC): statlog.gauge(f"pmic{i}_temperature", temp) - for i, temp in enumerate(last_hw_state.nvme_temps): - statlog.gauge(f"nvme_temperature{i}", temp) for i, temp in enumerate(last_hw_state.modem_temps): statlog.gauge(f"modem_temperature{i}", temp) statlog.gauge("fan_speed_percent_desired", msg.deviceState.fanSpeedPercentDesired) statlog.gauge("screen_brightness_percent", msg.deviceState.screenBrightnessPercent) - # report to server once every 10 minutes + # report to server once every 10 minutes, or every 1s when thermally blocked rising_edge_started = should_start and not should_start_prev - if rising_edge_started or (count % int(600. / DT_HW)) == 0: + status_packet_interval = 1. if show_alert else 600. + if rising_edge_started or (count % int(status_packet_interval / DT_HW)) == 0: dat = { 'count': count, 'pandaStates': [strip_deprecated_keys(p.to_dict()) for p in pandaStates], @@ -451,11 +435,22 @@ def hardware_thread(end_event, hw_queue) -> None: # save last one before going onroad if rising_edge_started: try: - params.put("LastOffroadStatusPacket", json.dumps(dat)) + params.put("LastOffroadStatusPacket", dat, block=True) except Exception: cloudlog.exception("failed to save offroad status") - params.put_bool_nonblocking("NetworkMetered", msg.deviceState.networkMetered) + params.put_bool("NetworkMetered", msg.deviceState.networkMetered) + + now_ts = time.monotonic() + if off_ts: + uptime_offroad += now_ts - max(last_uptime_ts, off_ts) + elif started_ts: + uptime_onroad += now_ts - max(last_uptime_ts, started_ts) + last_uptime_ts = now_ts + + if (count % int(60. / DT_HW)) == 0: + params.put("UptimeOffroad", uptime_offroad, block=True) + params.put("UptimeOnroad", uptime_onroad, block=True) count += 1 should_start_prev = should_start diff --git a/system/hardware/power_monitoring.py b/openpilot/system/hardware/power_monitoring.py similarity index 89% rename from system/hardware/power_monitoring.py rename to openpilot/system/hardware/power_monitoring.py index 952aebd9d7..bd9c334d04 100644 --- a/system/hardware/power_monitoring.py +++ b/openpilot/system/hardware/power_monitoring.py @@ -2,9 +2,9 @@ import time import threading from openpilot.common.params import Params -from openpilot.system.hardware import HARDWARE +from openpilot.common.hardware import HARDWARE from openpilot.common.swaglog import cloudlog -from openpilot.system.statsd import statlog +from openpilot.sunnypilot.system.statsd import statlog CAR_VOLTAGE_LOW_PASS_K = 0.011 # LPF gain for 45s tau (dt/tau / (dt/tau + 1)) @@ -29,15 +29,13 @@ class PowerMonitoring: self.car_voltage_instant_mV = 12e3 # Last value of peripheralState voltage self.integration_lock = threading.Lock() - car_battery_capacity_uWh = self.params.get("CarBatteryCapacity") - if car_battery_capacity_uWh is None: - car_battery_capacity_uWh = 0 + car_battery_capacity_uWh = self.params.get("CarBatteryCapacity") or 0 # Reset capacity if it's low - self.car_battery_capacity_uWh = max((CAR_BATTERY_CAPACITY_uWh / 10), int(car_battery_capacity_uWh)) + self.car_battery_capacity_uWh = max((CAR_BATTERY_CAPACITY_uWh / 10), car_battery_capacity_uWh) # Calculation tick - def calculate(self, voltage: int | None, ignition: bool): + def calculate(self, voltage: float | None, ignition: bool): try: now = time.monotonic() @@ -58,7 +56,7 @@ class PowerMonitoring: self.car_battery_capacity_uWh = max(self.car_battery_capacity_uWh, 0) self.car_battery_capacity_uWh = min(self.car_battery_capacity_uWh, CAR_BATTERY_CAPACITY_uWh) if now - self.last_save_time >= 10: - self.params.put_nonblocking("CarBatteryCapacity", str(int(self.car_battery_capacity_uWh))) + self.params.put("CarBatteryCapacity", int(self.car_battery_capacity_uWh)) self.last_save_time = now # First measurement, set integration time @@ -114,15 +112,14 @@ class PowerMonitoring: :return: True if the max time offroad has been exceeded, False otherwise """ try: - param = self.params.get("MaxTimeOffroad", encoding="utf8") - sp_max_time_val_s = int(param) * 60 if param is not None and int(param) >= 0 else MAX_TIME_OFFROAD_S + param = self.params.get("MaxTimeOffroad") + sp_max_time_val_s = param * 60 if param is not None and param >= 0 else MAX_TIME_OFFROAD_S except Exception: sp_max_time_val_s = MAX_TIME_OFFROAD_S - return sp_max_time_val_s > 0 and offroad_time >= sp_max_time_val_s + return 0 < sp_max_time_val_s <= offroad_time - -# See if we need to shutdown + # See if we need to shutdown def should_shutdown(self, ignition: bool, in_car: bool, offroad_timestamp: float | None, started_seen: bool): if offroad_timestamp is None: return False diff --git a/system/webrtc/__init__.py b/openpilot/system/hardware/tests/__init__.py similarity index 100% rename from system/webrtc/__init__.py rename to openpilot/system/hardware/tests/__init__.py diff --git a/openpilot/system/hardware/tests/test_fan_controller.py b/openpilot/system/hardware/tests/test_fan_controller.py new file mode 100644 index 0000000000..e1aceeb081 --- /dev/null +++ b/openpilot/system/hardware/tests/test_fan_controller.py @@ -0,0 +1,46 @@ +import pytest + +from openpilot.system.hardware.fan_controller import FanController + +ALL_CONTROLLERS = [FanController] + +class TestFanController: + def wind_up(self, controller, ignition=True): + for _ in range(1000): + controller.update(100, ignition) + + def wind_down(self, controller, ignition=False): + for _ in range(1000): + controller.update(10, ignition) + + @pytest.mark.parametrize("controller_class", ALL_CONTROLLERS) + def test_hot_onroad(self, controller_class): + controller = controller_class(2) + self.wind_up(controller) + assert controller.update(100, True) >= 70 + + @pytest.mark.parametrize("controller_class", ALL_CONTROLLERS) + def test_offroad_limits(self, controller_class): + controller = controller_class(2) + self.wind_up(controller) + assert controller.update(100, False) <= 30 + + @pytest.mark.parametrize("controller_class", ALL_CONTROLLERS) + def test_no_fan_wear(self, controller_class): + controller = controller_class(2) + self.wind_down(controller) + assert controller.update(10, False) == 0 + + @pytest.mark.parametrize("controller_class", ALL_CONTROLLERS) + def test_limited(self, controller_class): + controller = controller_class(2) + self.wind_up(controller, True) + assert controller.update(100, True) == 100 + + @pytest.mark.parametrize("controller_class", ALL_CONTROLLERS) + def test_windup_speed(self, controller_class): + controller = controller_class(2) + self.wind_down(controller, True) + for _ in range(10): + controller.update(90, True) + assert controller.update(90, True) >= 60 diff --git a/system/hardware/tests/test_power_monitoring.py b/openpilot/system/hardware/tests/test_power_monitoring.py similarity index 94% rename from system/hardware/tests/test_power_monitoring.py rename to openpilot/system/hardware/tests/test_power_monitoring.py index 3eec13dc4c..12057ab837 100644 --- a/system/hardware/tests/test_power_monitoring.py +++ b/openpilot/system/hardware/tests/test_power_monitoring.py @@ -35,7 +35,7 @@ class TestPowerMonitoring: def test_panda_state_present(self): pm = PowerMonitoring() for _ in range(10): - pm.calculate(None, None) + pm.calculate(None, False) assert pm.get_power_used() == 0 assert pm.get_car_battery_capacity() == (CAR_BATTERY_CAPACITY_uWh / 10) @@ -139,7 +139,7 @@ class TestPowerMonitoring: def test_disable_power_down(self, mocker): POWER_DRAW = 0 # To stop shutting down for other reasons TEST_TIME = 100 - self.params.put_bool("DisablePowerDown", True) + self.params.put_bool("DisablePowerDown", True, block=True) pm_patch(mocker, "HARDWARE.get_current_power_draw", POWER_DRAW) pm = PowerMonitoring() pm.car_battery_capacity_uWh = CAR_BATTERY_CAPACITY_uWh @@ -206,24 +206,24 @@ class TestPowerMonitoring: (None, MAX_TIME_OFFROAD_S + 1, True), # exceeds 30h (1800+ mins) # Valid max time values (in minutes) - ("60", 59, False), # under limit - ("60", 120, True), # over limit - ("10", 8, False), # under limit - ("10", 11, True), # over limit + (60, 59, False), # under limit + (60, 120, True), # over limit + (10, 8, False), # under limit + (10, 11, True), # over limit # Edge case: max time is zero → no limit enforced - ("0", 0, False), - ("0", 400, False), + (0, 0, False), + (0, 400, False), # Invalid max time formats or negative values → fallback to 30 hours - ("invalid", 100, False), # should fallback to 30h - ("-1", MAX_TIME_OFFROAD_S + 1, True), # should fallback to 30h, and exceed it + (-100, 100, False), # should fallback to 30h + (-1, MAX_TIME_OFFROAD_S + 1, True), # should fallback to 30h, and exceed it ] ) def test_max_time_offroad_exceeded(self, max_time_offroad, offroad_time_min, expected_result): # Set the parameter if provided if max_time_offroad is not None: - self.params.put("MaxTimeOffroad", max_time_offroad) + self.params.put("MaxTimeOffroad", max_time_offroad, block=True) # Convert offroad time from minutes to seconds offroad_time_s = offroad_time_min * 60 diff --git a/openpilot/system/hardware/tici/agnos.json b/openpilot/system/hardware/tici/agnos.json new file mode 120000 index 0000000000..ffee992f25 --- /dev/null +++ b/openpilot/system/hardware/tici/agnos.json @@ -0,0 +1 @@ +../../../common/hardware/tici/agnos.json \ No newline at end of file diff --git a/openpilot/system/journald.py b/openpilot/system/journald.py new file mode 100755 index 0000000000..091494b652 --- /dev/null +++ b/openpilot/system/journald.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 +import json +import subprocess + +import openpilot.cereal.messaging as messaging +from openpilot.common.swaglog import cloudlog + + +def main(): + pm = messaging.PubMaster(['operatingSystemLog']) + cmd = ['journalctl', '-f', '-o', 'json'] + proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, text=True) + assert proc.stdout is not None + try: + for line in proc.stdout: + line = line.strip() + if not line: + continue + try: + kv = json.loads(line) + except json.JSONDecodeError: + cloudlog.exception("failed to parse journalctl output") + continue + + msg = messaging.new_message('operatingSystemLog') + entry = msg.operatingSystemLog + entry.ts = int(kv.get('__REALTIME_TIMESTAMP', 0)) + entry.message = json.dumps(kv) + if '_PID' in kv: + entry.pid = int(kv['_PID']) + if 'PRIORITY' in kv: + entry.priority = int(kv['PRIORITY']) + if 'SYSLOG_IDENTIFIER' in kv: + entry.tag = kv['SYSLOG_IDENTIFIER'] + + pm.send('operatingSystemLog', msg) + finally: + proc.terminate() + proc.wait() + + +if __name__ == '__main__': + main() diff --git a/system/loggerd/.gitignore b/openpilot/system/loggerd/.gitignore similarity index 100% rename from system/loggerd/.gitignore rename to openpilot/system/loggerd/.gitignore diff --git a/openpilot/system/loggerd/SConscript b/openpilot/system/loggerd/SConscript new file mode 100644 index 0000000000..7f6d4faf0c --- /dev/null +++ b/openpilot/system/loggerd/SConscript @@ -0,0 +1,22 @@ +Import('env', 'arch', 'messaging', 'common', 'visionipc', 'ffmpeg_libs') + +libs = [common, messaging, visionipc] + ffmpeg_libs + ['pthread', 'm', 'zstd'] +frameworks = [] + +src = ['logger.cc', 'zstd_writer.cc', 'video_writer.cc', 'encoder/encoder.cc', 'encoder/jpeg_encoder.cc'] +if arch == "larch64": + src += ['encoder/v4l_encoder.cc'] +else: + src += ['encoder/ffmpeg_encoder.cc'] + if arch == "Darwin": + frameworks += ['VideoToolbox', 'CoreMedia', 'CoreFoundation', 'CoreVideo'] + +logger_lib = env.Library('logger', src) +libs.insert(0, logger_lib) + +env.Program('loggerd', ['loggerd.cc'], LIBS=libs, FRAMEWORKS=frameworks) +env.Program('encoderd', ['encoderd.cc'], LIBS=libs, FRAMEWORKS=frameworks) +env.Program('bootlog.cc', LIBS=libs, FRAMEWORKS=frameworks) + +if GetOption('extras'): + env.Program('tests/test_logger', ['tests/test_runner.cc', 'tests/test_logger.cc', 'tests/test_zstd_writer.cc'], LIBS=libs) diff --git a/third_party/acados/acados_template/gnsf/__init__.py b/openpilot/system/loggerd/__init__.py similarity index 100% rename from third_party/acados/acados_template/gnsf/__init__.py rename to openpilot/system/loggerd/__init__.py diff --git a/system/loggerd/bootlog.cc b/openpilot/system/loggerd/bootlog.cc similarity index 88% rename from system/loggerd/bootlog.cc rename to openpilot/system/loggerd/bootlog.cc index a7b1ae8244..b2e3abfcf1 100644 --- a/system/loggerd/bootlog.cc +++ b/openpilot/system/loggerd/bootlog.cc @@ -1,7 +1,7 @@ #include #include -#include "cereal/messaging/messaging.h" +#include "openpilot/cereal/messaging/messaging.h" #include "common/params.h" #include "common/swaglog.h" #include "system/loggerd/logger.h" @@ -28,12 +28,9 @@ static kj::Array build_boot_log() { // Gather output of commands std::vector bootlog_commands = { - "[ -x \"$(command -v journalctl)\" ] && journalctl -o short-monotonic", + "[ -x \"$(command -v journalctl)\" ] && journalctl -b -n 2000 -o short-monotonic --no-pager", }; - if (Hardware::TICI()) { - bootlog_commands.push_back("[ -e /dev/nvme0 ] && sudo nvme smart-log --output-format=json /dev/nvme0"); - } auto commands = boot.initCommands().initEntries(bootlog_commands.size()); for (int j = 0; j < bootlog_commands.size(); j++) { diff --git a/openpilot/system/loggerd/config.py b/openpilot/system/loggerd/config.py new file mode 100644 index 0000000000..e6bd97b99d --- /dev/null +++ b/openpilot/system/loggerd/config.py @@ -0,0 +1,34 @@ +import os +from openpilot.common.hardware.hw import Paths + + +CAMERA_FPS = 20 +SEGMENT_LENGTH = 60 + +STATS_DIR_FILE_LIMIT = 10000 +STATS_SOCKET = "ipc:///tmp/stats" +STATS_FLUSH_TIME_S = 60 + +PATH_DICT = { + "internal": Paths.log_root(), + "external": Paths.log_root_external() +} + +def get_available_percent(default: float, path_type="internal") -> float: + try: + statvfs = os.statvfs(PATH_DICT[path_type]) + available_percent = 100.0 * statvfs.f_bavail / statvfs.f_blocks + except (OSError, KeyError): + available_percent = default + + return available_percent + + +def get_available_bytes(default: int, path_type="internal") -> int: + try: + statvfs = os.statvfs(PATH_DICT[path_type]) + available_bytes = statvfs.f_bavail * statvfs.f_frsize + except (OSError, KeyError): + available_bytes = default + + return available_bytes diff --git a/openpilot/system/loggerd/deleter.py b/openpilot/system/loggerd/deleter.py new file mode 100755 index 0000000000..d5c12474f8 --- /dev/null +++ b/openpilot/system/loggerd/deleter.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python3 +import os +import time +import shutil +import threading +from pathlib import Path +from openpilot.common.hardware.hw import Paths +from openpilot.common.swaglog import cloudlog +from openpilot.system.loggerd.config import get_available_bytes, get_available_percent +from openpilot.system.loggerd.uploader import listdir_by_creation +from openpilot.system.loggerd.xattr_cache import getxattr + +MIN_BYTES = 5 * 1024 * 1024 * 1024 +MIN_PERCENT = 10 + +DELETE_LAST = ['boot', 'crash'] + +PRESERVE_ATTR_NAME = 'user.preserve' +PRESERVE_ATTR_VALUE = b'1' +PRESERVE_COUNT = 5 + + +def has_preserve_xattr(d: str) -> bool: + return getxattr(os.path.join(Paths.log_root(), d), PRESERVE_ATTR_NAME) == PRESERVE_ATTR_VALUE + + +def get_preserved_segments(dirs_by_creation: list[str]) -> set[str]: + # skip deleting most recent N preserved segments (and their prior segment) + preserved = set() + for n, d in enumerate(filter(has_preserve_xattr, reversed(dirs_by_creation))): + if n == PRESERVE_COUNT: + break + date_str, _, seg_str = d.rpartition("--") + + # ignore non-segment directories + if not date_str: + continue + try: + seg_num = int(seg_str) + except ValueError: + continue + + # preserve segment and two prior + for _seg_num in range(max(0, seg_num - 2), seg_num + 1): + preserved.add(f"{date_str}--{_seg_num}") + + return preserved + + +def deleter_thread(exit_event: threading.Event): + while not exit_event.is_set(): + out_of_bytes = get_available_bytes(default=MIN_BYTES + 1) < MIN_BYTES + out_of_percent = get_available_percent(default=MIN_PERCENT + 1) < MIN_PERCENT + + if out_of_percent or out_of_bytes: + dirs = listdir_by_creation(Paths.log_root()) + preserved_dirs = get_preserved_segments(dirs) + + # remove the earliest directory we can + for delete_dir in sorted(dirs, key=lambda d: (d in DELETE_LAST, d in preserved_dirs)): + delete_path = os.path.join(Paths.log_root(), delete_dir) + + if any(name.endswith(".lock") for name in os.listdir(delete_path)): + continue + + if Path(Paths.log_root_external()).is_mount(): + out_of_bytes_external = get_available_bytes(default=MIN_BYTES + 1, path_type="external") < MIN_BYTES + out_of_percent_external = get_available_percent(default=MIN_PERCENT + 1, path_type="external") < MIN_PERCENT + + if out_of_percent_external or out_of_bytes_external: + dirs_external = listdir_by_creation(Paths.log_root_external()) + + # remove the earliest external directory we can + for delete_dir_external in sorted(dirs_external): + delete_path_external = os.path.join(Paths.log_root_external(), delete_dir_external) + try: + cloudlog.warning(f"deleting {delete_path_external}") + shutil.rmtree(delete_path_external) + break + except OSError: + cloudlog.exception(f"issue deleting {delete_path_external}") + + # move directory from internal to external + path_external = os.path.join(Paths.log_root_external(), delete_dir) + try: + cloudlog.warning(f"moving {delete_path} to {path_external}") + start = time.monotonic() + shutil.move(delete_path, path_external) + cloudlog.warning(f"moved {delete_path} to {path_external} in {time.monotonic() - start:.2f}s") + break + except Exception: + cloudlog.error(f"issue moving {delete_path} to {path_external}") + try: + cloudlog.warning(f"deleting {delete_path}") + shutil.rmtree(delete_path) + break + except OSError: + cloudlog.exception(f"issue deleting {delete_path}") + continue + + try: + cloudlog.info(f"deleting {delete_path}") + shutil.rmtree(delete_path) + break + except OSError: + cloudlog.exception(f"issue deleting {delete_path}") + exit_event.wait(.1) + else: + exit_event.wait(30) + + +def main(): + deleter_thread(threading.Event()) + + +if __name__ == "__main__": + main() diff --git a/system/loggerd/encoder/encoder.cc b/openpilot/system/loggerd/encoder/encoder.cc similarity index 96% rename from system/loggerd/encoder/encoder.cc rename to openpilot/system/loggerd/encoder/encoder.cc index b8f2f274d2..06922b0cd0 100644 --- a/system/loggerd/encoder/encoder.cc +++ b/openpilot/system/loggerd/encoder/encoder.cc @@ -21,7 +21,7 @@ void VideoEncoder::publisher_publish(int segment_num, uint32_t idx, VisionIpcBuf edata.setFrameId(extra.frame_id); edata.setTimestampSof(extra.timestamp_sof); edata.setTimestampEof(extra.timestamp_eof); - edata.setType(encoder_info.encode_type); + edata.setType(encoder_info.get_settings(in_width).encode_type); edata.setEncodeId(cnt++); edata.setSegmentNum(segment_num); edata.setSegmentId(idx); diff --git a/system/loggerd/encoder/encoder.h b/openpilot/system/loggerd/encoder/encoder.h similarity index 85% rename from system/loggerd/encoder/encoder.h rename to openpilot/system/loggerd/encoder/encoder.h index 57146fafc3..d333351cb4 100644 --- a/system/loggerd/encoder/encoder.h +++ b/openpilot/system/loggerd/encoder/encoder.h @@ -2,7 +2,7 @@ // has to be in this order #ifdef __linux__ -#include "third_party/linux/include/v4l2-controls.h" +#include #include #else #define V4L2_BUF_FLAG_KEYFRAME 8 @@ -14,7 +14,7 @@ #include #include -#include "cereal/messaging/messaging.h" +#include "openpilot/cereal/messaging/messaging.h" #include "msgq/visionipc/visionipc.h" #include "common/queue.h" #include "system/loggerd/loggerd.h" @@ -26,6 +26,8 @@ public: virtual int encode_frame(VisionBuf* buf, VisionIpcBufExtra *extra) = 0; virtual void encoder_open() = 0; virtual void encoder_close() = 0; + virtual void set_bitrate(int bitrate) = 0; + virtual void request_keyframe() = 0; void publisher_publish(int segment_num, uint32_t idx, VisionIpcBufExtra &extra, unsigned int flags, kj::ArrayPtr header, kj::ArrayPtr dat); diff --git a/system/loggerd/encoder/ffmpeg_encoder.cc b/openpilot/system/loggerd/encoder/ffmpeg_encoder.cc similarity index 78% rename from system/loggerd/encoder/ffmpeg_encoder.cc rename to openpilot/system/loggerd/encoder/ffmpeg_encoder.cc index 4e6946363f..451445e5a0 100644 --- a/system/loggerd/encoder/ffmpeg_encoder.cc +++ b/openpilot/system/loggerd/encoder/ffmpeg_encoder.cc @@ -1,5 +1,3 @@ -#pragma clang diagnostic ignored "-Wdeprecated-declarations" - #include "system/loggerd/encoder/ffmpeg_encoder.h" #include @@ -11,8 +9,6 @@ #define __STDC_CONSTANT_MACROS -#include "third_party/libyuv/include/libyuv.h" - extern "C" { #include #include @@ -21,6 +17,7 @@ extern "C" { #include "common/swaglog.h" #include "common/util.h" +#include "common/yuv.h" const int env_debug_encoder = (getenv("DEBUG_ENCODER") != NULL) ? atoi(getenv("DEBUG_ENCODER")) : 0; @@ -48,7 +45,7 @@ FfmpegEncoder::~FfmpegEncoder() { } void FfmpegEncoder::encoder_open() { - auto codec_id = encoder_info.encode_type == cereal::EncodeIndex::Type::QCAMERA_H264 + auto codec_id = encoder_info.get_settings(in_width).encode_type == cereal::EncodeIndex::Type::QCAMERA_H264 ? AV_CODEC_ID_H264 : AV_CODEC_ID_FFVHUFF; const AVCodec *codec = avcodec_find_encoder(codec_id); @@ -74,6 +71,14 @@ void FfmpegEncoder::encoder_close() { is_open = false; } +void FfmpegEncoder::set_bitrate(int bitrate) { + LOGE("adaptive bitrate is not supported for ffmpeg encoder %s", encoder_info.publish_name); +} + +void FfmpegEncoder::request_keyframe() { + LOGE("keyframe request is not supported for ffmpeg encoder %s", encoder_info.publish_name); +} + int FfmpegEncoder::encode_frame(VisionBuf* buf, VisionIpcBufExtra *extra) { assert(buf->width == this->in_width); assert(buf->height == this->in_height); @@ -81,26 +86,25 @@ int FfmpegEncoder::encode_frame(VisionBuf* buf, VisionIpcBufExtra *extra) { uint8_t *cy = convert_buf.data(); uint8_t *cu = cy + in_width * in_height; uint8_t *cv = cu + (in_width / 2) * (in_height / 2); - libyuv::NV12ToI420(buf->y, buf->stride, - buf->uv, buf->stride, - cy, in_width, - cu, in_width/2, - cv, in_width/2, - in_width, in_height); + yuv::nv12_to_i420(buf->y, buf->stride, + buf->uv, buf->stride, + cy, in_width, + cu, in_width/2, + cv, in_width/2, + in_width, in_height); if (downscale_buf.size() > 0) { uint8_t *out_y = downscale_buf.data(); uint8_t *out_u = out_y + frame->width * frame->height; uint8_t *out_v = out_u + (frame->width / 2) * (frame->height / 2); - libyuv::I420Scale(cy, in_width, - cu, in_width/2, - cv, in_width/2, - in_width, in_height, - out_y, frame->width, - out_u, frame->width/2, - out_v, frame->width/2, - frame->width, frame->height, - libyuv::kFilterNone); + yuv::i420_scale(cy, in_width, + cu, in_width/2, + cv, in_width/2, + in_width, in_height, + out_y, frame->width, + out_u, frame->width/2, + out_v, frame->width/2, + frame->width, frame->height); frame->data[0] = out_y; frame->data[1] = out_u; frame->data[2] = out_v; @@ -119,8 +123,7 @@ int FfmpegEncoder::encode_frame(VisionBuf* buf, VisionIpcBufExtra *extra) { ret = -1; } - AVPacket pkt; - av_init_packet(&pkt); + AVPacket pkt = {}; pkt.data = NULL; pkt.size = 0; while (ret >= 0) { diff --git a/system/loggerd/encoder/ffmpeg_encoder.h b/openpilot/system/loggerd/encoder/ffmpeg_encoder.h similarity index 92% rename from system/loggerd/encoder/ffmpeg_encoder.h rename to openpilot/system/loggerd/encoder/ffmpeg_encoder.h index cd5ac1e13a..3f7c674db3 100644 --- a/system/loggerd/encoder/ffmpeg_encoder.h +++ b/openpilot/system/loggerd/encoder/ffmpeg_encoder.h @@ -21,6 +21,8 @@ public: int encode_frame(VisionBuf* buf, VisionIpcBufExtra *extra); void encoder_open(); void encoder_close(); + void set_bitrate(int bitrate); + void request_keyframe(); private: int segment_num = -1; diff --git a/openpilot/system/loggerd/encoder/jpeg_encoder.cc b/openpilot/system/loggerd/encoder/jpeg_encoder.cc new file mode 100644 index 0000000000..6258e8144d --- /dev/null +++ b/openpilot/system/loggerd/encoder/jpeg_encoder.cc @@ -0,0 +1,115 @@ +#include "system/loggerd/encoder/jpeg_encoder.h" + +#include +#include + +#include "common/swaglog.h" + +// Lower qscale = higher quality / bigger files for MJPEG. +constexpr int MJPEG_QSCALE = 7; + +JpegEncoder::JpegEncoder(const std::string &publish_name, int width, int height) + : publish_name(publish_name), thumbnail_width(width), thumbnail_height(height) { + yuv_buffer.resize((thumbnail_width * thumbnail_height * 3) / 2); + pm = std::make_unique(std::vector{publish_name.c_str()}); + + const AVCodec *codec = avcodec_find_encoder(AV_CODEC_ID_MJPEG); + assert(codec); + + codec_ctx = avcodec_alloc_context3(codec); + assert(codec_ctx); + codec_ctx->width = thumbnail_width; + codec_ctx->height = thumbnail_height; + codec_ctx->pix_fmt = AV_PIX_FMT_YUV420P; + codec_ctx->time_base = (AVRational){1, 1}; + codec_ctx->color_range = AVCOL_RANGE_JPEG; + codec_ctx->flags |= AV_CODEC_FLAG_QSCALE; + codec_ctx->global_quality = FF_QP2LAMBDA * MJPEG_QSCALE; + + int err = avcodec_open2(codec_ctx, codec, NULL); + assert(err >= 0); + + frame = av_frame_alloc(); + assert(frame); + frame->format = codec_ctx->pix_fmt; + frame->width = thumbnail_width; + frame->height = thumbnail_height; + frame->linesize[0] = thumbnail_width; + frame->linesize[1] = thumbnail_width / 2; + frame->linesize[2] = thumbnail_width / 2; + frame->color_range = AVCOL_RANGE_JPEG; + + pkt = av_packet_alloc(); + assert(pkt); +} + +JpegEncoder::~JpegEncoder() { + av_packet_free(&pkt); + av_frame_free(&frame); + avcodec_free_context(&codec_ctx); +} + +void JpegEncoder::pushThumbnail(VisionBuf *buf, const VisionIpcBufExtra &extra) { + generateThumbnail(buf->y, buf->uv, buf->width, buf->height, buf->stride); + + MessageBuilder msg; + auto thumbnaild = msg.initEvent().initThumbnail(); + thumbnaild.setFrameId(extra.frame_id); + thumbnaild.setTimestampEof(extra.timestamp_eof); + thumbnaild.setThumbnail({out_buffer.data(), out_buffer.size()}); + + pm->send(publish_name.c_str(), msg); +} + +void JpegEncoder::generateThumbnail(const uint8_t *y_addr, const uint8_t *uv_addr, int width, int height, int stride) { + int downscale = width / thumbnail_width; + assert(downscale * thumbnail_height == height); + + uint8_t *y_plane = yuv_buffer.data(); + uint8_t *u_plane = y_plane + thumbnail_width * thumbnail_height; + uint8_t *v_plane = u_plane + (thumbnail_width * thumbnail_height) / 4; + { + // subsampled conversion from nv12 to yuv420p + for (int hy = 0; hy < thumbnail_height / 2; hy++) { + for (int hx = 0; hx < thumbnail_width / 2; hx++) { + int ix = hx * downscale + (downscale - 1) / 2; + int iy = hy * downscale + (downscale - 1) / 2; + y_plane[(hy * 2 + 0) * thumbnail_width + (hx * 2 + 0)] = y_addr[(iy * 2 + 0) * stride + ix * 2 + 0]; + y_plane[(hy * 2 + 0) * thumbnail_width + (hx * 2 + 1)] = y_addr[(iy * 2 + 0) * stride + ix * 2 + 1]; + y_plane[(hy * 2 + 1) * thumbnail_width + (hx * 2 + 0)] = y_addr[(iy * 2 + 1) * stride + ix * 2 + 0]; + y_plane[(hy * 2 + 1) * thumbnail_width + (hx * 2 + 1)] = y_addr[(iy * 2 + 1) * stride + ix * 2 + 1]; + u_plane[hy * thumbnail_width / 2 + hx] = uv_addr[iy * stride + ix * 2 + 0]; + v_plane[hy * thumbnail_width / 2 + hx] = uv_addr[iy * stride + ix * 2 + 1]; + } + } + } + + compressToJpeg(y_plane, u_plane, v_plane); +} + +void JpegEncoder::compressToJpeg(uint8_t *y_plane, uint8_t *u_plane, uint8_t *v_plane) { + frame->data[0] = y_plane; + frame->data[1] = u_plane; + frame->data[2] = v_plane; + // Required for MJPEG qscale to take effect (global_quality alone is not enough). + frame->quality = FF_QP2LAMBDA * MJPEG_QSCALE; + frame->pts = AV_NOPTS_VALUE; + + int err = avcodec_send_frame(codec_ctx, frame); + if (err < 0) { + LOGE("thumbnail avcodec_send_frame error %d", err); + out_buffer.clear(); + return; + } + + av_packet_unref(pkt); + err = avcodec_receive_packet(codec_ctx, pkt); + if (err < 0) { + LOGE("thumbnail avcodec_receive_packet error %d", err); + out_buffer.clear(); + return; + } + + out_buffer.assign(pkt->data, pkt->data + pkt->size); + av_packet_unref(pkt); +} diff --git a/openpilot/system/loggerd/encoder/jpeg_encoder.h b/openpilot/system/loggerd/encoder/jpeg_encoder.h new file mode 100644 index 0000000000..10cec52657 --- /dev/null +++ b/openpilot/system/loggerd/encoder/jpeg_encoder.h @@ -0,0 +1,35 @@ +#pragma once + +#include +#include +#include +#include + +#include "openpilot/cereal/messaging/messaging.h" +#include "msgq/visionipc/visionbuf.h" + +extern "C" { +#include +} + +class JpegEncoder { +public: + JpegEncoder(const std::string &publish_name, int width, int height); + ~JpegEncoder(); + void pushThumbnail(VisionBuf *buf, const VisionIpcBufExtra &extra); + +private: + void generateThumbnail(const uint8_t *y, const uint8_t *uv, int width, int height, int stride); + void compressToJpeg(uint8_t *y_plane, uint8_t *u_plane, uint8_t *v_plane); + + int thumbnail_width; + int thumbnail_height; + std::string publish_name; + std::vector yuv_buffer; + std::vector out_buffer; + std::unique_ptr pm; + + AVCodecContext *codec_ctx = nullptr; + AVFrame *frame = nullptr; + AVPacket *pkt = nullptr; +}; diff --git a/system/loggerd/encoder/v4l_encoder.cc b/openpilot/system/loggerd/encoder/v4l_encoder.cc similarity index 79% rename from system/loggerd/encoder/v4l_encoder.cc rename to openpilot/system/loggerd/encoder/v4l_encoder.cc index ac1da09693..1b4d976b93 100644 --- a/system/loggerd/encoder/v4l_encoder.cc +++ b/openpilot/system/loggerd/encoder/v4l_encoder.cc @@ -7,11 +7,10 @@ #include "common/util.h" #include "common/timing.h" -#include "third_party/libyuv/include/libyuv.h" -#include "third_party/linux/include/msm_media_info.h" +#include // has to be in this order -#include "third_party/linux/include/v4l2-controls.h" +#include #include #define V4L2_QCOM_BUF_FLAG_CODECCONFIG 0x00020000 #define V4L2_QCOM_BUF_FLAG_EOS 0x02000000 @@ -24,14 +23,6 @@ */ const int env_debug_encoder = (getenv("DEBUG_ENCODER") != NULL) ? atoi(getenv("DEBUG_ENCODER")) : 0; -static void checked_ioctl(int fd, unsigned long request, void *argp) { - int ret = util::safe_ioctl(fd, request, argp); - if (ret != 0) { - LOGE("checked_ioctl failed with error %d (%d %lx %p)", errno, fd, request, argp); - assert(0); - } -} - static void dequeue_buffer(int fd, v4l2_buf_type buf_type, unsigned int *index=NULL, unsigned int *bytesused=NULL, unsigned int *flags=NULL, struct timeval *timestamp=NULL) { v4l2_plane plane = {0}; v4l2_buffer v4l_buf = { @@ -40,7 +31,7 @@ static void dequeue_buffer(int fd, v4l2_buf_type buf_type, unsigned int *index=N .m = { .planes = &plane, }, .length = 1, }; - checked_ioctl(fd, VIDIOC_DQBUF, &v4l_buf); + util::safe_ioctl(fd, VIDIOC_DQBUF, &v4l_buf, "VIDIOC_DQBUF failed"); if (index) *index = v4l_buf.index; if (bytesused) *bytesused = v4l_buf.m.planes[0].bytesused; @@ -51,32 +42,31 @@ static void dequeue_buffer(int fd, v4l2_buf_type buf_type, unsigned int *index=N static void queue_buffer(int fd, v4l2_buf_type buf_type, unsigned int index, VisionBuf *buf, struct timeval timestamp={}) { v4l2_plane plane = { + .bytesused = (uint32_t)buf->len, .length = (unsigned int)buf->len, .m = { .userptr = (unsigned long)buf->addr, }, - .bytesused = (uint32_t)buf->len, .reserved = {(unsigned int)buf->fd} }; v4l2_buffer v4l_buf = { - .type = buf_type, .index = index, + .type = buf_type, + .flags = V4L2_BUF_FLAG_TIMESTAMP_COPY, + .timestamp = timestamp, .memory = V4L2_MEMORY_USERPTR, .m = { .planes = &plane, }, .length = 1, - .flags = V4L2_BUF_FLAG_TIMESTAMP_COPY, - .timestamp = timestamp }; - - checked_ioctl(fd, VIDIOC_QBUF, &v4l_buf); + util::safe_ioctl(fd, VIDIOC_QBUF, &v4l_buf, "VIDIOC_QBUF failed"); } static void request_buffers(int fd, v4l2_buf_type buf_type, unsigned int count) { struct v4l2_requestbuffers reqbuf = { + .count = count, .type = buf_type, .memory = V4L2_MEMORY_USERPTR, - .count = count }; - checked_ioctl(fd, VIDIOC_REQBUFS, &reqbuf); + util::safe_ioctl(fd, VIDIOC_REQBUFS, &reqbuf, "VIDIOC_REQBUFS failed"); } void V4LEncoder::dequeue_handler(V4LEncoder *e) { @@ -159,11 +149,15 @@ V4LEncoder::V4LEncoder(const EncoderInfo &encoder_info, int in_width, int in_hei assert(fd >= 0); struct v4l2_capability cap; - checked_ioctl(fd, VIDIOC_QUERYCAP, &cap); + util::safe_ioctl(fd, VIDIOC_QUERYCAP, &cap, "VIDIOC_QUERYCAP failed"); LOGD("opened encoder device %s %s = %d", cap.driver, cap.card, fd); assert(strcmp((const char *)cap.driver, "msm_vidc_driver") == 0); assert(strcmp((const char *)cap.card, "msm_vidc_venc") == 0); + EncoderSettings encoder_settings = encoder_info.get_settings(in_width); + current_bitrate = encoder_settings.bitrate; + bool is_h265 = encoder_settings.encode_type == cereal::EncodeIndex::Type::FULL_H_E_V_C; + struct v4l2_format fmt_out = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE, .fmt = { @@ -171,13 +165,13 @@ V4LEncoder::V4LEncoder(const EncoderInfo &encoder_info, int in_width, int in_hei // downscales are free with v4l .width = (unsigned int)(out_width), .height = (unsigned int)(out_height), - .pixelformat = (encoder_info.encode_type == cereal::EncodeIndex::Type::FULL_H_E_V_C) ? V4L2_PIX_FMT_HEVC : V4L2_PIX_FMT_H264, + .pixelformat = is_h265 ? V4L2_PIX_FMT_HEVC : V4L2_PIX_FMT_H264, .field = V4L2_FIELD_ANY, .colorspace = V4L2_COLORSPACE_DEFAULT, } } }; - checked_ioctl(fd, VIDIOC_S_FMT, &fmt_out); + util::safe_ioctl(fd, VIDIOC_S_FMT, &fmt_out, "VIDIOC_S_FMT failed"); v4l2_streamparm streamparm = { .type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE, @@ -191,7 +185,7 @@ V4LEncoder::V4LEncoder(const EncoderInfo &encoder_info, int in_width, int in_hei } } }; - checked_ioctl(fd, VIDIOC_S_PARM, &streamparm); + util::safe_ioctl(fd, VIDIOC_S_PARM, &streamparm, "VIDIOC_S_PARM failed"); struct v4l2_format fmt_in = { .type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE, @@ -205,7 +199,7 @@ V4LEncoder::V4LEncoder(const EncoderInfo &encoder_info, int in_width, int in_hei } } }; - checked_ioctl(fd, VIDIOC_S_FMT, &fmt_in); + util::safe_ioctl(fd, VIDIOC_S_FMT, &fmt_in, "VIDIOC_S_FMT failed"); LOGD("in buffer size %d, out buffer size %d", fmt_in.fmt.pix_mp.plane_fmt[0].sizeimage, @@ -214,34 +208,32 @@ V4LEncoder::V4LEncoder(const EncoderInfo &encoder_info, int in_width, int in_hei // shared ctrls { struct v4l2_control ctrls[] = { + { .id = V4L2_CID_MPEG_VIDEO_BITRATE, .value = encoder_settings.bitrate}, + { .id = V4L2_CID_MPEG_VIDC_VIDEO_NUM_P_FRAMES, .value = encoder_settings.gop_size - encoder_settings.b_frames - 1}, + { .id = V4L2_CID_MPEG_VIDC_VIDEO_NUM_B_FRAMES, .value = encoder_settings.b_frames}, { .id = V4L2_CID_MPEG_VIDEO_HEADER_MODE, .value = V4L2_MPEG_VIDEO_HEADER_MODE_SEPARATE}, - { .id = V4L2_CID_MPEG_VIDEO_BITRATE, .value = encoder_info.bitrate}, { .id = V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL, .value = V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_VBR_CFR}, { .id = V4L2_CID_MPEG_VIDC_VIDEO_PRIORITY, .value = V4L2_MPEG_VIDC_VIDEO_PRIORITY_REALTIME_DISABLE}, { .id = V4L2_CID_MPEG_VIDC_VIDEO_IDR_PERIOD, .value = 1}, }; for (auto ctrl : ctrls) { - checked_ioctl(fd, VIDIOC_S_CTRL, &ctrl); + util::safe_ioctl(fd, VIDIOC_S_CTRL, &ctrl, "VIDIOC_S_CTRL failed"); } } - if (encoder_info.encode_type == cereal::EncodeIndex::Type::FULL_H_E_V_C) { + if (is_h265) { struct v4l2_control ctrls[] = { { .id = V4L2_CID_MPEG_VIDC_VIDEO_HEVC_PROFILE, .value = V4L2_MPEG_VIDC_VIDEO_HEVC_PROFILE_MAIN}, { .id = V4L2_CID_MPEG_VIDC_VIDEO_HEVC_TIER_LEVEL, .value = V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_5}, { .id = V4L2_CID_MPEG_VIDC_VIDEO_VUI_TIMING_INFO, .value = V4L2_MPEG_VIDC_VIDEO_VUI_TIMING_INFO_ENABLED}, - { .id = V4L2_CID_MPEG_VIDC_VIDEO_NUM_P_FRAMES, .value = 29}, - { .id = V4L2_CID_MPEG_VIDC_VIDEO_NUM_B_FRAMES, .value = 0}, }; for (auto ctrl : ctrls) { - checked_ioctl(fd, VIDIOC_S_CTRL, &ctrl); + util::safe_ioctl(fd, VIDIOC_S_CTRL, &ctrl, "VIDIOC_S_CTRL failed"); } } else { struct v4l2_control ctrls[] = { { .id = V4L2_CID_MPEG_VIDEO_H264_PROFILE, .value = V4L2_MPEG_VIDEO_H264_PROFILE_HIGH}, { .id = V4L2_CID_MPEG_VIDEO_H264_LEVEL, .value = V4L2_MPEG_VIDEO_H264_LEVEL_UNKNOWN}, - { .id = V4L2_CID_MPEG_VIDC_VIDEO_NUM_P_FRAMES, .value = 14}, - { .id = V4L2_CID_MPEG_VIDC_VIDEO_NUM_B_FRAMES, .value = 0}, { .id = V4L2_CID_MPEG_VIDEO_H264_ENTROPY_MODE, .value = V4L2_MPEG_VIDEO_H264_ENTROPY_MODE_CABAC}, { .id = V4L2_CID_MPEG_VIDC_VIDEO_H264_CABAC_MODEL, .value = V4L2_CID_MPEG_VIDC_VIDEO_H264_CABAC_MODEL_0}, { .id = V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_MODE, .value = 0}, @@ -250,7 +242,7 @@ V4LEncoder::V4LEncoder(const EncoderInfo &encoder_info, int in_width, int in_hei { .id = V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MODE, .value = 0}, }; for (auto ctrl : ctrls) { - checked_ioctl(fd, VIDIOC_S_CTRL, &ctrl); + util::safe_ioctl(fd, VIDIOC_S_CTRL, &ctrl, "VIDIOC_S_CTRL failed"); } } @@ -260,9 +252,9 @@ V4LEncoder::V4LEncoder(const EncoderInfo &encoder_info, int in_width, int in_hei // start encoder v4l2_buf_type buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; - checked_ioctl(fd, VIDIOC_STREAMON, &buf_type); + util::safe_ioctl(fd, VIDIOC_STREAMON, &buf_type, "VIDIOC_STREAMON failed"); buf_type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; - checked_ioctl(fd, VIDIOC_STREAMON, &buf_type); + util::safe_ioctl(fd, VIDIOC_STREAMON, &buf_type, "VIDIOC_STREAMON failed"); // queue up output buffers for (unsigned int i = 0; i < BUF_OUT_COUNT; i++) { @@ -305,7 +297,7 @@ void V4LEncoder::encoder_close() { for (int i = 0; i < BUF_IN_COUNT; i++) free_buf_in.push(i); // no frames, stop the encoder struct v4l2_encoder_cmd encoder_cmd = { .cmd = V4L2_ENC_CMD_STOP }; - checked_ioctl(fd, VIDIOC_ENCODER_CMD, &encoder_cmd); + util::safe_ioctl(fd, VIDIOC_ENCODER_CMD, &encoder_cmd, "VIDIOC_ENCODER_CMD failed"); // join waits for V4L2_QCOM_BUF_FLAG_EOS dequeue_handler_thread.join(); assert(extras.empty()); @@ -313,13 +305,43 @@ void V4LEncoder::encoder_close() { this->is_open = false; } +void V4LEncoder::set_bitrate(int bitrate) { + if (bitrate == current_bitrate) return; + if (bitrate <= 0) { + LOGE("invalid livestream encoder bitrate %d", bitrate); + return; + } + + struct v4l2_control ctrl = { + .id = V4L2_CID_MPEG_VIDEO_BITRATE, + .value = bitrate, + }; + + if (util::safe_ioctl(fd, VIDIOC_S_CTRL, &ctrl) == -1) { + LOGE("failed to update %s bitrate to %d", encoder_info.publish_name, bitrate); + return; + } + current_bitrate = bitrate; +} + +void V4LEncoder::request_keyframe() { + struct v4l2_control ctrl = { + .id = V4L2_CID_MPEG_VIDC_VIDEO_REQUEST_IFRAME, + .value = 1, + }; + + if (util::safe_ioctl(fd, VIDIOC_S_CTRL, &ctrl) == -1) { + LOGE("failed to request keyframe for %s", encoder_info.publish_name); + } +} + V4LEncoder::~V4LEncoder() { encoder_close(); v4l2_buf_type buf_type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; - checked_ioctl(fd, VIDIOC_STREAMOFF, &buf_type); + util::safe_ioctl(fd, VIDIOC_STREAMOFF, &buf_type, "VIDIOC_STREAMOFF failed"); request_buffers(fd, V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE, 0); buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; - checked_ioctl(fd, VIDIOC_STREAMOFF, &buf_type); + util::safe_ioctl(fd, VIDIOC_STREAMOFF, &buf_type, "VIDIOC_STREAMOFF failed"); request_buffers(fd, V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE, 0); close(fd); diff --git a/system/loggerd/encoder/v4l_encoder.h b/openpilot/system/loggerd/encoder/v4l_encoder.h similarity index 88% rename from system/loggerd/encoder/v4l_encoder.h rename to openpilot/system/loggerd/encoder/v4l_encoder.h index 58011d60e1..b1a84e654f 100644 --- a/system/loggerd/encoder/v4l_encoder.h +++ b/openpilot/system/loggerd/encoder/v4l_encoder.h @@ -13,6 +13,8 @@ public: int encode_frame(VisionBuf* buf, VisionIpcBufExtra *extra); void encoder_open(); void encoder_close(); + void set_bitrate(int bitrate); + void request_keyframe(); private: int fd; @@ -20,6 +22,7 @@ private: bool is_open = false; int segment_num = -1; int counter = 0; + int current_bitrate = -1; SafeQueue extras; diff --git a/system/loggerd/encoderd.cc b/openpilot/system/loggerd/encoderd.cc similarity index 90% rename from system/loggerd/encoderd.cc rename to openpilot/system/loggerd/encoderd.cc index 3237d13074..11db07671d 100644 --- a/system/loggerd/encoderd.cc +++ b/openpilot/system/loggerd/encoderd.cc @@ -3,7 +3,7 @@ #include "system/loggerd/loggerd.h" #include "system/loggerd/encoder/jpeg_encoder.h" -#ifdef QCOM2 +#ifdef __TICI__ #include "system/loggerd/encoder/v4l_encoder.h" #define Encoder V4LEncoder #else @@ -44,11 +44,25 @@ bool sync_encoders(EncoderdState *s, VisionStreamType cam_type, uint32_t frame_i } } +void encoder_set_bitrate(std::unique_ptr &e) { + static Params params; + std::string val = params.get("LivestreamEncoderBitrate"); + if (val.empty()) return; + int bitrate = std::stoi(val); + e->set_bitrate(bitrate); +} + +void encoder_request_keyframe(std::unique_ptr &e) { + static Params params; + if (!params.getBool("LivestreamRequestKeyframe")) return; + e->request_keyframe(); +} void encoder_thread(EncoderdState *s, const LogCameraInfo &cam_info) { util::set_thread_name(cam_info.thread_name); std::vector> encoders; + VisionIpcClient vipc_client = VisionIpcClient("camerad", cam_info.stream_type, false); std::unique_ptr jpeg_encoder; @@ -110,6 +124,11 @@ void encoder_thread(EncoderdState *s, const LogCameraInfo &cam_info) { // encode a frame for (int i = 0; i < encoders.size(); ++i) { + if (cam_info.encoder_infos[i].is_live) { + encoder_set_bitrate(encoders[i]); + encoder_request_keyframe(encoders[i]); + } + int out_id = encoders[i]->encode_frame(buf, &extra); if (out_id == -1) { diff --git a/system/loggerd/logger.cc b/openpilot/system/loggerd/logger.cc similarity index 97% rename from system/loggerd/logger.cc rename to openpilot/system/loggerd/logger.cc index f07aee1596..e8aeb96d02 100644 --- a/system/loggerd/logger.cc +++ b/openpilot/system/loggerd/logger.cc @@ -11,6 +11,8 @@ #include "common/swaglog.h" #include "common/version.h" +#include "sunnypilot/common/version.h" + // ***** log metadata ***** kj::Array logger_build_init_data() { uint64_t wall_time = nanos_since_epoch(); @@ -19,7 +21,7 @@ kj::Array logger_build_init_data() { auto init = msg.initEvent().initInitData(); init.setWallTimeNanos(wall_time); - init.setVersion(COMMA_VERSION); + init.setVersion(SUNNYPILOT_VERSION); init.setDirty(!getenv("CLEAN")); init.setDeviceType(Hardware::get_device_type()); @@ -59,7 +61,7 @@ kj::Array logger_build_init_data() { for (auto& [key, value] : params_map) { auto lentry = lparams[j]; lentry.setKey(key); - if ( !(params.getKeyType(key) & DONT_LOG) ) { + if ( !(params.getKeyFlag(key) & DONT_LOG) ) { lentry.setValue(capnp::Data::Reader((const kj::byte*)value.data(), value.size())); } j++; diff --git a/system/loggerd/logger.h b/openpilot/system/loggerd/logger.h similarity index 93% rename from system/loggerd/logger.h rename to openpilot/system/loggerd/logger.h index 18d07b5f38..419becfe5d 100644 --- a/system/loggerd/logger.h +++ b/openpilot/system/loggerd/logger.h @@ -4,9 +4,9 @@ #include #include -#include "cereal/messaging/messaging.h" +#include "openpilot/cereal/messaging/messaging.h" #include "common/util.h" -#include "system/hardware/hw.h" +#include "common/hardware/hw.h" #include "system/loggerd/zstd_writer.h" constexpr int LOG_COMPRESSION_LEVEL = 10; diff --git a/system/loggerd/loggerd.cc b/openpilot/system/loggerd/loggerd.cc similarity index 81% rename from system/loggerd/loggerd.cc rename to openpilot/system/loggerd/loggerd.cc index 2d2d4640ed..3755929619 100644 --- a/system/loggerd/loggerd.cc +++ b/openpilot/system/loggerd/loggerd.cc @@ -62,6 +62,7 @@ struct RemoteEncoder { bool recording = false; bool marked_ready_to_rotate = false; bool seen_first_packet = false; + bool audio_initialized = false; }; size_t write_encode_data(LoggerdState *s, cereal::Event::Reader event, RemoteEncoder &re, const EncoderInfo &encoder_info) { @@ -78,12 +79,7 @@ size_t write_encode_data(LoggerdState *s, cereal::Event::Reader event, RemoteEnc LOGW("%s: dropped %d non iframe packets before init", encoder_info.publish_name, re.dropped_frames); re.dropped_frames = 0; } - // if we aren't actually recording, don't create the writer if (encoder_info.record) { - assert(encoder_info.filename != NULL); - re.writer.reset(new VideoWriter(s->logger.segmentPath().c_str(), - encoder_info.filename, idx.getType() != cereal::EncodeIndex::Type::FULL_H_E_V_C, - edata.getWidth(), edata.getHeight(), encoder_info.fps, idx.getType())); // write the header auto header = edata.getHeader(); re.writer->write((uint8_t *)header.begin(), header.size(), idx.getTimestampEof() / 1000, true, false); @@ -138,12 +134,19 @@ int handle_encoder_msg(LoggerdState *s, Message *msg, std::string &name, struct // if this is a new segment, we close any possible old segments, move to the new, and process any queued packets if (re.current_segment != s->logger.segment()) { - if (re.recording) { - re.writer.reset(); + // if we aren't actually recording, don't create the writer + if (encoder_info.record) { + assert(encoder_info.filename != NULL); + re.writer.reset(new VideoWriter(s->logger.segmentPath().c_str(), + encoder_info.filename, idx.getType() != cereal::EncodeIndex::Type::FULL_H_E_V_C, + edata.getWidth(), edata.getHeight(), encoder_info.fps, idx.getType())); re.recording = false; + re.audio_initialized = false; } re.current_segment = s->logger.segment(); re.marked_ready_to_rotate = false; + } + if (re.audio_initialized || !encoder_info.include_audio) { // we are in this segment now, process any queued messages before this one if (!re.q.empty()) { for (auto qmsg : re.q) { @@ -153,9 +156,14 @@ int handle_encoder_msg(LoggerdState *s, Message *msg, std::string &name, struct } re.q.clear(); } + bytes_count += write_encode_data(s, event, re, encoder_info); + delete msg; + } else if (re.q.size() > MAIN_FPS*10) { + LOGE_100("%s: dropping frame waiting for audio initialization, queue is too large", name.c_str()); + delete msg; + } else { + re.q.push_back(msg); // queue up all the new segment messages, they go in after audio is initialized } - bytes_count += write_encode_data(s, event, re, encoder_info); - delete msg; } else if (offset_segment_num > s->logger.segment()) { // encoderd packet has a newer segment, this means encoderd has rolled over if (!re.marked_ready_to_rotate) { @@ -186,7 +194,7 @@ int handle_encoder_msg(LoggerdState *s, Message *msg, std::string &name, struct return bytes_count; } -void handle_user_flag(LoggerdState *s) { +void handle_preserve_segment(LoggerdState *s) { static int prev_segment = -1; if (s->logger.segment() == prev_segment) return; @@ -211,11 +219,11 @@ void handle_user_flag(LoggerdState *s) { void loggerd_thread() { // setup messaging - typedef struct ServiceState { + struct ServiceState { std::string name; int counter, freq; - bool encoder, user_flag; - } ServiceState; + bool encoder, preserve_segment, record_audio; + }; std::unordered_map service_state; std::unordered_map remote_encoders; @@ -226,19 +234,22 @@ void loggerd_thread() { for (const auto& [_, it] : services) { const bool encoder = util::ends_with(it.name, "EncodeData"); const bool livestream_encoder = util::starts_with(it.name, "livestream"); - if (!it.should_log && (!encoder || livestream_encoder)) continue; - LOGD("logging %s", it.name.c_str()); + const bool record_audio = (it.name == "rawAudioData") && Params().getBool("RecordAudio"); + if (it.should_log || (encoder && !livestream_encoder) || record_audio) { + LOGD("logging %s", it.name.c_str()); - SubSocket * sock = SubSocket::create(ctx.get(), it.name); - assert(sock != NULL); - poller->registerSocket(sock); - service_state[sock] = { - .name = it.name, - .counter = 0, - .freq = it.decimation, - .encoder = encoder, - .user_flag = it.name == "userFlag", - }; + SubSocket * sock = SubSocket::create(ctx.get(), it.name, "127.0.0.1", false, true, it.queue_size); + assert(sock != NULL); + poller->registerSocket(sock); + service_state[sock] = { + .name = it.name, + .counter = 0, + .freq = it.decimation, + .encoder = encoder, + .preserve_segment = (it.name == "userBookmark") || (it.name == "audioFeedback"), + .record_audio = record_audio, + }; + } } LoggerdState s; @@ -247,6 +258,7 @@ void loggerd_thread() { Params().put("CurrentRoute", s.logger.routeName()); std::map encoder_infos_dict; + std::vector encoders_with_audio; for (const auto &cam : cameras_logged) { for (const auto &encoder_info : cam.encoder_infos) { encoder_infos_dict[encoder_info.publish_name] = encoder_info; @@ -254,6 +266,13 @@ void loggerd_thread() { } } + for (auto &[sock, service] : service_state) { + auto it = encoder_infos_dict.find(service.name); + if (it != encoder_infos_dict.end() && it->second.include_audio) { + encoders_with_audio.push_back(&remote_encoders[sock]); + } + } + uint64_t msg_count = 0, bytes_count = 0; double start_ts = millis_since_boot(); while (!do_exit) { @@ -262,8 +281,8 @@ void loggerd_thread() { if (do_exit) break; ServiceState &service = service_state[sock]; - if (service.user_flag) { - handle_user_flag(&s); + if (service.preserve_segment) { + handle_preserve_segment(&s); } // drain socket @@ -271,6 +290,20 @@ void loggerd_thread() { Message *msg = nullptr; while (!do_exit && (msg = sock->receive(true))) { const bool in_qlog = service.freq != -1 && (service.counter++ % service.freq == 0); + + if (service.record_audio) { + capnp::FlatArrayMessageReader cmsg(kj::ArrayPtr((capnp::word *)msg->getData(), msg->getSize() / sizeof(capnp::word))); + auto event = cmsg.getRoot(); + auto audio_data = event.getRawAudioData().getData(); + auto sample_rate = event.getRawAudioData().getSampleRate(); + for (auto* encoder : encoders_with_audio) { + if (encoder && encoder->writer) { + encoder->writer->write_audio((uint8_t*)audio_data.begin(), audio_data.size(), event.getLogMonoTime() / 1000, sample_rate); + encoder->audio_initialized = true; + } + } + } + if (service.encoder) { s.last_camera_seen_tms = millis_since_boot(); bytes_count += handle_encoder_msg(&s, msg, service.name, remote_encoders[sock], encoder_infos_dict[service.name]); diff --git a/openpilot/system/loggerd/loggerd.h b/openpilot/system/loggerd/loggerd.h new file mode 100644 index 0000000000..110dbe4fd2 --- /dev/null +++ b/openpilot/system/loggerd/loggerd.h @@ -0,0 +1,176 @@ +#pragma once + +#include +#include + +#include "openpilot/cereal/messaging/messaging.h" +#include "openpilot/cereal/services.h" +#include "msgq/visionipc/visionipc_client.h" +#include "common/hardware/hw.h" +#include "common/params.h" +#include "common/swaglog.h" +#include "common/util.h" + +#include "system/loggerd/logger.h" + +constexpr int MAIN_FPS = 20; +const auto MAIN_ENCODE_TYPE = Hardware::PC() ? cereal::EncodeIndex::Type::BIG_BOX_LOSSLESS : cereal::EncodeIndex::Type::FULL_H_E_V_C; +#define NO_CAMERA_PATIENCE 500 // fall back to time-based rotation if all cameras are dead + +#define INIT_ENCODE_FUNCTIONS(encode_type) \ + .get_encode_data_func = &cereal::Event::Reader::get##encode_type##Data, \ + .set_encode_idx_func = &cereal::Event::Builder::set##encode_type##Idx, \ + .init_encode_data_func = &cereal::Event::Builder::init##encode_type##Data + +const bool LOGGERD_TEST = getenv("LOGGERD_TEST"); +const int SEGMENT_LENGTH = LOGGERD_TEST ? atoi(getenv("LOGGERD_SEGMENT_LENGTH")) : 60; + +constexpr char PRESERVE_ATTR_NAME[] = "user.preserve"; +constexpr char PRESERVE_ATTR_VALUE = '1'; + +struct EncoderSettings { + cereal::EncodeIndex::Type encode_type; + int bitrate; + int gop_size; + int b_frames = 0; // we don't use b frames + + static EncoderSettings MainEncoderSettings(int in_width) { + if (in_width <= 1344) { + return EncoderSettings{.encode_type = MAIN_ENCODE_TYPE, .bitrate = 5'000'000, .gop_size = 20}; + } else { + return EncoderSettings{.encode_type = MAIN_ENCODE_TYPE, .bitrate = 10'000'000, .gop_size = 30}; + } + } + + static EncoderSettings QcamEncoderSettings() { + return EncoderSettings{.encode_type = cereal::EncodeIndex::Type::QCAMERA_H264, .bitrate = 256'000, .gop_size = 15}; + } + + static EncoderSettings StreamEncoderSettings() { + int _stream_bitrate = getenv("STREAM_BITRATE") ? atoi(getenv("STREAM_BITRATE")) : 5'000'000; + return EncoderSettings{.encode_type = cereal::EncodeIndex::Type::QCAMERA_H264, .bitrate = _stream_bitrate , .gop_size = 5}; + } +}; + +class EncoderInfo { +public: + const char *publish_name; + const char *thumbnail_name = NULL; + const char *filename = NULL; + bool record = true; + bool include_audio = false; + bool is_live = false; + int frame_width = -1; + int frame_height = -1; + int fps = MAIN_FPS; + std::function get_settings; + + ::cereal::EncodeData::Reader (cereal::Event::Reader::*get_encode_data_func)() const; + void (cereal::Event::Builder::*set_encode_idx_func)(::cereal::EncodeIndex::Reader); + cereal::EncodeData::Builder (cereal::Event::Builder::*init_encode_data_func)(); +}; + +class LogCameraInfo { +public: + const char *thread_name; + int fps = MAIN_FPS; + VisionStreamType stream_type; + std::vector encoder_infos; +}; + +const EncoderInfo main_road_encoder_info = { + .publish_name = "roadEncodeData", + .thumbnail_name = "thumbnail", + .filename = "fcamera.hevc", + .get_settings = [](int in_width){return EncoderSettings::MainEncoderSettings(in_width);}, + INIT_ENCODE_FUNCTIONS(RoadEncode), +}; + +const EncoderInfo main_wide_road_encoder_info = { + .publish_name = "wideRoadEncodeData", + .filename = "ecamera.hevc", + .get_settings = [](int in_width){return EncoderSettings::MainEncoderSettings(in_width);}, + INIT_ENCODE_FUNCTIONS(WideRoadEncode), +}; + +const EncoderInfo main_driver_encoder_info = { + .publish_name = "driverEncodeData", + .filename = "dcamera.hevc", + .record = Params().getBool("RecordFront"), + .get_settings = [](int in_width){return EncoderSettings::MainEncoderSettings(in_width);}, + INIT_ENCODE_FUNCTIONS(DriverEncode), +}; + +const EncoderInfo stream_road_encoder_info = { + .publish_name = "livestreamRoadEncodeData", + //.thumbnail_name = "thumbnail", + .record = false, + .is_live = true, + .get_settings = [](int){return EncoderSettings::StreamEncoderSettings();}, + INIT_ENCODE_FUNCTIONS(LivestreamRoadEncode), +}; + +const EncoderInfo stream_wide_road_encoder_info = { + .publish_name = "livestreamWideRoadEncodeData", + .record = false, + .is_live = true, + .get_settings = [](int){return EncoderSettings::StreamEncoderSettings();}, + INIT_ENCODE_FUNCTIONS(LivestreamWideRoadEncode), +}; + +const EncoderInfo stream_driver_encoder_info = { + .publish_name = "livestreamDriverEncodeData", + .record = false, + .is_live = true, + .get_settings = [](int){return EncoderSettings::StreamEncoderSettings();}, + INIT_ENCODE_FUNCTIONS(LivestreamDriverEncode), +}; + +const EncoderInfo qcam_encoder_info = { + .publish_name = "qRoadEncodeData", + .filename = "qcamera.ts", + .include_audio = Params().getBool("RecordAudio"), + .frame_width = 526, + .frame_height = 330, + .get_settings = [](int){return EncoderSettings::QcamEncoderSettings();}, + INIT_ENCODE_FUNCTIONS(QRoadEncode), +}; + +const LogCameraInfo road_camera_info{ + .thread_name = "road_cam_encoder", + .stream_type = VISION_STREAM_ROAD, + .encoder_infos = {main_road_encoder_info, qcam_encoder_info} +}; + +const LogCameraInfo wide_road_camera_info{ + .thread_name = "wide_road_cam_encoder", + .stream_type = VISION_STREAM_WIDE_ROAD, + .encoder_infos = {main_wide_road_encoder_info} +}; + +const LogCameraInfo driver_camera_info{ + .thread_name = "driver_cam_encoder", + .stream_type = VISION_STREAM_DRIVER, + .encoder_infos = {main_driver_encoder_info} +}; + +const LogCameraInfo stream_road_camera_info{ + .thread_name = "road_cam_encoder", + .stream_type = VISION_STREAM_ROAD, + .encoder_infos = {stream_road_encoder_info}, +}; + +const LogCameraInfo stream_wide_road_camera_info{ + .thread_name = "wide_road_cam_encoder", + .stream_type = VISION_STREAM_WIDE_ROAD, + .encoder_infos = {stream_wide_road_encoder_info}, +}; + +const LogCameraInfo stream_driver_camera_info{ + .thread_name = "driver_cam_encoder", + .stream_type = VISION_STREAM_DRIVER, + .encoder_infos = {stream_driver_encoder_info}, +}; + +const LogCameraInfo cameras_logged[] = {road_camera_info, wide_road_camera_info, driver_camera_info}; +const LogCameraInfo stream_cameras_logged[] = {stream_road_camera_info, stream_wide_road_camera_info, stream_driver_camera_info}; diff --git a/tools/__init__.py b/openpilot/system/loggerd/tests/__init__.py similarity index 100% rename from tools/__init__.py rename to openpilot/system/loggerd/tests/__init__.py diff --git a/system/loggerd/tests/loggerd_tests_common.py b/openpilot/system/loggerd/tests/loggerd_tests_common.py similarity index 81% rename from system/loggerd/tests/loggerd_tests_common.py rename to openpilot/system/loggerd/tests/loggerd_tests_common.py index 15fd997eb8..55f5fbb816 100644 --- a/system/loggerd/tests/loggerd_tests_common.py +++ b/openpilot/system/loggerd/tests/loggerd_tests_common.py @@ -6,11 +6,11 @@ from pathlib import Path import openpilot.system.loggerd.deleter as deleter import openpilot.system.loggerd.uploader as uploader from openpilot.common.params import Params -from openpilot.system.hardware.hw import Paths +from openpilot.common.hardware.hw import Paths from openpilot.system.loggerd.xattr_cache import setxattr -def create_random_file(file_path: Path, size_mb: float, lock: bool = False, upload_xattr: bytes = None) -> None: +def create_random_file(file_path: Path, size_mb: float, lock: bool = False, upload_xattr: bytes | None = None) -> None: file_path.parent.mkdir(parents=True, exist_ok=True) if lock: @@ -63,10 +63,10 @@ class UploaderTestCase: seg_dir: str def set_ignore(self): - uploader.Api = MockApiIgnore + uploader.Api = MockApiIgnore # ty: ignore[invalid-assignment] # test double def setup_method(self): - uploader.Api = MockApi + uploader.Api = MockApi # ty: ignore[invalid-assignment] # test double uploader.fake_upload = True uploader.force_wifi = True uploader.allow_sleep = False @@ -76,11 +76,11 @@ class UploaderTestCase: self.seg_dir = self.seg_format.format(self.seg_num) self.params = Params() - self.params.put("IsOffroad", "1") - self.params.put("DongleId", "0000000000000000") + self.params.put("IsOffroad", True, block=True) + self.params.put("DongleId", "0000000000000000", block=True) def make_file_with_data(self, f_dir: str, fn: str, size_mb: float = .1, lock: bool = False, - upload_xattr: bytes = None, preserve_xattr: bytes = None) -> Path: + upload_xattr: bytes | None = None, preserve_xattr: bytes | None = None) -> Path: file_path = Path(Paths.log_root()) / f_dir / fn create_random_file(file_path, size_mb, lock, upload_xattr) diff --git a/system/loggerd/tests/test_deleter.py b/openpilot/system/loggerd/tests/test_deleter.py similarity index 97% rename from system/loggerd/tests/test_deleter.py rename to openpilot/system/loggerd/tests/test_deleter.py index 6222ea253b..8f18c8ceee 100644 --- a/system/loggerd/tests/test_deleter.py +++ b/openpilot/system/loggerd/tests/test_deleter.py @@ -19,7 +19,7 @@ class TestDeleter(UploaderTestCase): self.f_type = "fcamera.hevc" super().setup_method() self.fake_stats = Stats(f_bavail=0, f_blocks=10, f_frsize=4096) - deleter.os.statvfs = self.fake_statvfs + deleter.os.statvfs = self.fake_statvfs # ty: ignore[invalid-assignment] # test double def start_thread(self): self.end_event = threading.Event() diff --git a/system/loggerd/tests/test_encoder.py b/openpilot/system/loggerd/tests/test_encoder.py similarity index 81% rename from system/loggerd/tests/test_encoder.py rename to openpilot/system/loggerd/tests/test_encoder.py index b24bfbe168..05bc211cbe 100644 --- a/system/loggerd/tests/test_encoder.py +++ b/openpilot/system/loggerd/tests/test_encoder.py @@ -1,29 +1,28 @@ import math import os import pytest -import random import shutil import subprocess import time from pathlib import Path -from parameterized import parameterized from tqdm import trange from openpilot.common.params import Params from openpilot.common.timeout import Timeout -from openpilot.system.hardware import TICI +from openpilot.common.hardware import TICI from openpilot.system.manager.process_config import managed_processes from openpilot.tools.lib.logreader import LogReader -from openpilot.system.hardware.hw import Paths +from openpilot.common.hardware.hw import Paths SEGMENT_LENGTH = 2 FULL_SIZE = 2507572 +def hevc_size(w): return FULL_SIZE // 2 if w <= 1344 else FULL_SIZE CAMERAS = [ - ("fcamera.hevc", 20, FULL_SIZE, "roadEncodeIdx"), - ("dcamera.hevc", 20, FULL_SIZE, "driverEncodeIdx"), - ("ecamera.hevc", 20, FULL_SIZE, "wideRoadEncodeIdx"), - ("qcamera.ts", 20, 130000, None), + ("fcamera.hevc", 20, hevc_size, "roadEncodeIdx"), + ("dcamera.hevc", 20, hevc_size, "driverEncodeIdx"), + ("ecamera.hevc", 20, hevc_size, "wideRoadEncodeIdx"), + ("qcamera.ts", 20, lambda x: 130000, None), ] # we check frame count, so we don't have to be too strict on size @@ -50,9 +49,8 @@ class TestEncoder: return os.path.join(Paths.log_root(), last_route) # TODO: this should run faster than real time - @parameterized.expand([(True, ), (False, )]) - def test_log_rotation(self, record_front): - Params().put_bool("RecordFront", record_front) + def test_log_rotation(self): + Params().put_bool("RecordFront", True, block=True) managed_processes['sensord'].start() managed_processes['loggerd'].start() @@ -61,7 +59,7 @@ class TestEncoder: time.sleep(1.0) managed_processes['camerad'].start() - num_segments = int(os.getenv("SEGMENTS", random.randint(2, 8))) + num_segments = 3 # wait for loggerd to make the dir for first segment route_prefix_path = None @@ -76,24 +74,21 @@ class TestEncoder: # check each camera file size counts = [] first_frames = [] - for camera, fps, size, encode_idx_name in CAMERAS: - if not record_front and "dcamera" in camera: - continue - + for camera, fps, size_lambda, encode_idx_name in CAMERAS: file_path = f"{route_prefix_path}--{i}/{camera}" # check file exists assert os.path.exists(file_path), f"segment #{i}: '{file_path}' missing" # TODO: this ffprobe call is really slow - # check frame count - cmd = f"ffprobe -v error -select_streams v:0 -count_packets -show_entries stream=nb_read_packets -of csv=p=0 {file_path}" + # get width and check frame count + cmd = f"ffprobe -v error -select_streams v:0 -count_packets -show_entries stream=nb_read_packets,width -of csv=p=0 {file_path}" if TICI: cmd = "LD_LIBRARY_PATH=/usr/local/lib " + cmd expected_frames = fps * SEGMENT_LENGTH - probe = subprocess.check_output(cmd, shell=True, encoding='utf8') - frame_count = int(probe.split('\n')[0].strip()) + probe = subprocess.check_output(cmd, shell=True, encoding='utf8').split('\n')[0].strip().split(',') + frame_width, frame_count = int(probe[0]), int(probe[1]) counts.append(frame_count) assert frame_count == expected_frames, \ @@ -101,8 +96,9 @@ class TestEncoder: # sanity check file size file_size = os.path.getsize(file_path) - assert math.isclose(file_size, size, rel_tol=FILE_SIZE_TOLERANCE), \ - f"{file_path} size {file_size} isn't close to target size {size}" + target_size = size_lambda(frame_width) + assert math.isclose(file_size, target_size, rel_tol=FILE_SIZE_TOLERANCE), \ + f"{file_path} size {file_size} isn't close to target size {target_size}" # Check encodeIdx if encode_idx_name is not None: diff --git a/system/loggerd/tests/test_logger.cc b/openpilot/system/loggerd/tests/test_logger.cc similarity index 97% rename from system/loggerd/tests/test_logger.cc rename to openpilot/system/loggerd/tests/test_logger.cc index 40a45a68d5..61509c256c 100644 --- a/system/loggerd/tests/test_logger.cc +++ b/openpilot/system/loggerd/tests/test_logger.cc @@ -56,7 +56,7 @@ void write_msg(LoggerState *logger) { TEST_CASE("logger") { const int segment_cnt = 100; const std::string log_root = "/tmp/test_logger"; - system(("rm " + log_root + " -rf").c_str()); + REQUIRE(system(("rm " + log_root + " -rf").c_str()) == 0); std::string route_name; { LoggerState logger(log_root); diff --git a/openpilot/system/loggerd/tests/test_loggerd.py b/openpilot/system/loggerd/tests/test_loggerd.py new file mode 100644 index 0000000000..3678ca95be --- /dev/null +++ b/openpilot/system/loggerd/tests/test_loggerd.py @@ -0,0 +1,342 @@ +import numpy as np +import os +import re +import random +import string +import subprocess +import time +from collections.abc import Collection +from collections import defaultdict +from pathlib import Path +import pytest + +import openpilot.cereal.messaging as messaging +from openpilot.cereal import log +from openpilot.cereal.services import SERVICE_LIST +from openpilot.common.basedir import BASEDIR +from openpilot.common.params import Params +from openpilot.common.timeout import Timeout +from openpilot.common.hardware.hw import Paths +from openpilot.common.hardware import TICI +from openpilot.system.loggerd.xattr_cache import getxattr +from openpilot.system.loggerd.deleter import PRESERVE_ATTR_NAME, PRESERVE_ATTR_VALUE +from openpilot.system.manager.process_config import managed_processes +from openpilot.common.version import get_version +from openpilot.tools.lib.helpers import RE +from openpilot.tools.lib.logreader import LogReader +from msgq.visionipc import VisionIpcServer, VisionStreamType + +SentinelType = log.Sentinel.SentinelType + +CEREAL_SERVICES = [f for f in log.Event.schema.union_fields if f in SERVICE_LIST + and SERVICE_LIST[f].should_log and "encode" not in f.lower()] + + +class TestLoggerd: + def _get_latest_log_dir(self): + log_dirs = sorted(Path(Paths.log_root()).iterdir(), key=lambda f: f.stat().st_mtime) + return log_dirs[-1] + + def _get_log_dir(self, x): + for l in x.splitlines(): + for p in l.split(' '): + path = Path(p.strip()) + if path.is_dir(): + return path + return None + + def _get_log_fn(self, x): + for l in x.splitlines(): + for p in l.split(' '): + path = Path(p.strip()) + if path.is_file(): + return path + return None + + def _gen_bootlog(self): + with Timeout(5): + out = subprocess.check_output("./bootlog", cwd=os.path.join(BASEDIR, "openpilot/system/loggerd"), encoding='utf-8') + + log_fn = self._get_log_fn(out) + + # check existence + assert log_fn is not None + + return log_fn + + def _check_init_data(self, msgs): + msg = msgs[0] + assert msg.which() == 'initData' + + def _check_sentinel(self, msgs, route): + start_type = SentinelType.startOfRoute if route else SentinelType.startOfSegment + assert msgs[1].sentinel.type == start_type + + end_type = SentinelType.endOfRoute if route else SentinelType.endOfSegment + assert msgs[-1].sentinel.type == end_type + + def _publish_random_messages(self, services: Collection[str]) -> dict[str, list]: + pm = messaging.PubMaster(list(services)) + + managed_processes["loggerd"].start() + for s in services: + assert pm.wait_for_readers_to_update(s, timeout=5) + + sent_msgs = defaultdict(list) + for i in range(random.randint(2, 10) * 100): + for s in services: + try: + m = messaging.new_message(s) + except Exception: + m = messaging.new_message(s, random.randint(2, 10)) + pm.send(s, m) + sent_msgs[s].append(m) + + # Keep msgq's finite per-service queues from wrapping; this test asserts + # that loggerd logged every message we sent. + if (i + 1) % 100 == 0: + for s in services: + assert pm.wait_for_readers_to_update(s, timeout=5) + + for s in services: + assert pm.wait_for_readers_to_update(s, timeout=5) + managed_processes["loggerd"].stop() + + return sent_msgs + + def _publish_camera_and_audio_messages(self, num_segs=1, segment_length=5): + # Use small frame sizes for testing (width, height, size, stride, uv_offset) + # NV12 format: size = stride * height * 1.5, uv_offset = stride * height + w, h = 320, 240 + frame_spec = (w, h, w * h * 3 // 2, w, w * h) + streams = [ + (VisionStreamType.VISION_STREAM_ROAD, frame_spec, "roadCameraState"), + (VisionStreamType.VISION_STREAM_DRIVER, frame_spec, "driverCameraState"), + (VisionStreamType.VISION_STREAM_WIDE_ROAD, frame_spec, "wideRoadCameraState"), + ] + + sm = messaging.SubMaster(["roadEncodeData"]) + pm = messaging.PubMaster([s for _, _, s in streams] + ["rawAudioData"]) + vipc_server = VisionIpcServer("camerad") + for stream_type, frame_spec, _ in streams: + vipc_server.create_buffers_with_sizes(stream_type, 40, *(frame_spec)) + vipc_server.start_listener() + + os.environ["LOGGERD_TEST"] = "1" + os.environ["LOGGERD_SEGMENT_LENGTH"] = str(segment_length) + managed_processes["loggerd"].start() + managed_processes["encoderd"].start() + assert pm.wait_for_readers_to_update("roadCameraState", timeout=5) + + fps = 20 + for n in range(1, int(num_segs * segment_length * fps) + 1): + # send video + for stream_type, frame_spec, state in streams: + dat = np.empty(frame_spec[2], dtype=np.uint8) + vipc_server.send(stream_type, dat[:].flatten().tobytes(), n, n / fps, n / fps) + + camera_state = messaging.new_message(state) + frame = getattr(camera_state, state) + frame.frameId = n + pm.send(state, camera_state) + + # send audio + msg = messaging.new_message('rawAudioData') + msg.rawAudioData.data = bytes(800 * 2) # 800 samples of int16 + msg.rawAudioData.sampleRate = 16000 + pm.send('rawAudioData', msg) + + for _, _, state in streams: + assert pm.wait_for_readers_to_update(state, timeout=5, dt=0.001) + + sm.update(100) # wait for encode data publish + + managed_processes["loggerd"].stop() + managed_processes["encoderd"].stop() + + def test_init_data_values(self): + os.environ["CLEAN"] = random.choice(["0", "1"]) + + dongle = ''.join(random.choice(string.printable) for n in range(random.randint(1, 100))) + fake_params = [ + # param, initData field, value + ("DongleId", "dongleId", dongle), + ("GitCommit", "gitCommit", "commit"), + ("GitCommitDate", "gitCommitDate", "date"), + ("GitBranch", "gitBranch", "branch"), + ("GitRemote", "gitRemote", "remote"), + ] + params = Params() + for k, _, v in fake_params: + params.put(k, v, block=True) + params.put("AccessToken", "abc", block=True) + + lr = list(LogReader(str(self._gen_bootlog()))) + initData = lr[0].initData + + assert initData.dirty != bool(os.environ["CLEAN"]) + assert initData.version == get_version() + + if os.path.isfile("/proc/cmdline"): + with open("/proc/cmdline") as f: + assert list(initData.kernelArgs) == f.read().strip().split(" ") + + with open("/proc/version") as f: + assert initData.kernelVersion == f.read() + + # check params + logged_params = {entry.key: entry.value for entry in initData.params.entries} + expected_params = {k for k, _, __ in fake_params} | {'AccessToken', 'BootCount'} + assert set(logged_params.keys()) == expected_params, set(logged_params.keys()) ^ expected_params + assert logged_params['AccessToken'] == b'', f"DONT_LOG param value was logged: {repr(logged_params['AccessToken'])}" + for param_key, initData_key, v in fake_params: + assert getattr(initData, initData_key) == v + assert logged_params[param_key].decode() == v + + @pytest.mark.xdist_group("camera_encoder_tests") # setting xdist group ensures tests are run in same worker, prevents encoderd from crashing + def test_rotation(self): + Params().put("RecordFront", True, block=True) + + expected_files = {"rlog.zst", "qlog.zst", "qcamera.ts", "fcamera.hevc", "dcamera.hevc", "ecamera.hevc"} + + num_segs = random.randint(2, 3) + length = random.randint(4, 5) # H264 encoder uses 40 lookahead frames and does B-frame reordering, so minimum 3 seconds before qcam output + + self._publish_camera_and_audio_messages(num_segs=num_segs, segment_length=length) + + route_path = str(self._get_latest_log_dir()).rsplit("--", 1)[0] + for n in range(num_segs): + p = Path(f"{route_path}--{n}") + logged = {f.name for f in p.iterdir() if f.is_file()} + diff = logged ^ expected_files + assert len(diff) == 0, f"didn't get all expected files. seg={n} {route_path=}, {diff=}\n{logged=} {expected_files=}" + + def test_bootlog(self): + # generate bootlog with fake launch log + launch_log = ''.join(str(random.choice(string.printable)) for _ in range(100)) + with open("/tmp/launch_log", "w") as f: + f.write(launch_log) + + bootlog_path = self._gen_bootlog() + lr = list(LogReader(str(bootlog_path))) + + # check length + assert len(lr) == 2 # boot + initData + + self._check_init_data(lr) + + # check msgs + bootlog_msgs = [m for m in lr if m.which() == 'boot'] + assert len(bootlog_msgs) == 1 + + # sanity check values + boot = bootlog_msgs.pop().boot + assert abs(boot.wallTimeNanos - time.time_ns()) < 5*1e9 # within 5s + assert boot.launchLog == launch_log + + if TICI: + for fn in ["console-ramoops", "pmsg-ramoops-0"]: + path = Path(os.path.join("/sys/fs/pstore/", fn)) + if path.is_file(): + with open(path, "rb") as f: + expected_val = f.read() + bootlog_val = [e.value for e in boot.pstore.entries if e.key == fn][0] + assert expected_val == bootlog_val + else: + assert len(boot.pstore.entries) == 0 + + # next one should increment by one + bl1 = re.match(RE.LOG_ID_V2, bootlog_path.name) + bl2 = re.match(RE.LOG_ID_V2, self._gen_bootlog().name) + assert bl1.group('uid') != bl2.group('uid') + assert int(bl1.group('count')) == 0 and int(bl2.group('count')) == 1 + + def test_qlog(self): + qlog_services = [s for s in CEREAL_SERVICES if SERVICE_LIST[s].decimation is not None] + no_qlog_services = [s for s in CEREAL_SERVICES if SERVICE_LIST[s].decimation is None] + + services = random.sample(qlog_services, random.randint(2, min(10, len(qlog_services)))) + \ + random.sample(no_qlog_services, random.randint(2, min(10, len(no_qlog_services)))) + sent_msgs = self._publish_random_messages(services) + + qlog_path = os.path.join(self._get_latest_log_dir(), "qlog.zst") + lr = list(LogReader(qlog_path)) + + # check initData and sentinel + self._check_init_data(lr) + self._check_sentinel(lr, True) + + recv_msgs = defaultdict(list) + for m in lr: + recv_msgs[m.which()].append(m) + + for s, msgs in sent_msgs.items(): + recv_cnt = len(recv_msgs[s]) + + if s in no_qlog_services: + # check services with no specific decimation aren't in qlog + assert recv_cnt == 0, f"got {recv_cnt} {s} msgs in qlog" + else: + # check logged message count matches decimation + decimation = SERVICE_LIST[s].decimation + assert decimation is not None + expected_cnt = (len(msgs) - 1) // decimation + 1 + assert recv_cnt == expected_cnt, f"expected {expected_cnt} msgs for {s}, got {recv_cnt}" + + def test_rlog(self): + services = random.sample(CEREAL_SERVICES, random.randint(5, 10)) + sent_msgs = self._publish_random_messages(services) + + lr = list(LogReader(os.path.join(self._get_latest_log_dir(), "rlog.zst"))) + + # check initData and sentinel + self._check_init_data(lr) + self._check_sentinel(lr, True) + + # check all messages were logged and in order + lr = lr[2:-1] # slice off initData and both sentinels + for m in lr: + sent = sent_msgs[m.which()].pop(0) + sent.clear_write_flag() + assert sent.to_bytes() == m.as_builder().to_bytes() + + def test_preserving_bookmarked_segments(self): + services = set(random.sample(CEREAL_SERVICES, random.randint(5, 10))) | {"userBookmark"} + self._publish_random_messages(services) + + segment_dir = self._get_latest_log_dir() + assert getxattr(segment_dir, PRESERVE_ATTR_NAME) == PRESERVE_ATTR_VALUE + + def test_not_preserving_nonbookmarked_segments(self): + services = set(random.sample(CEREAL_SERVICES, random.randint(5, 10))) - {"userBookmark", "audioFeedback"} + self._publish_random_messages(services) + + segment_dir = self._get_latest_log_dir() + assert getxattr(segment_dir, PRESERVE_ATTR_NAME) is None + + @pytest.mark.xdist_group("camera_encoder_tests") # setting xdist group ensures tests are run in same worker, prevents encoderd from crashing + @pytest.mark.parametrize("record_front", [True, False]) + def test_record_front(self, record_front): + params = Params() + params.put_bool("RecordFront", record_front, block=True) + + self._publish_camera_and_audio_messages() + + dcamera_hevc_exists = os.path.exists(os.path.join(self._get_latest_log_dir(), 'dcamera.hevc')) + assert dcamera_hevc_exists == record_front + + @pytest.mark.xdist_group("camera_encoder_tests") # setting xdist group ensures tests are run in same worker, prevents encoderd from crashing + @pytest.mark.parametrize("record_audio", [True, False]) + def test_record_audio(self, record_audio): + params = Params() + params.put_bool("RecordAudio", record_audio, block=True) + + self._publish_camera_and_audio_messages() + + qcamera_ts_path = os.path.join(self._get_latest_log_dir(), 'qcamera.ts') + ffprobe_cmd = f"ffprobe -i {qcamera_ts_path} -show_streams -select_streams a -loglevel error" + has_audio_stream = subprocess.run(ffprobe_cmd, shell=True, capture_output=True).stdout.strip() != b'' + assert has_audio_stream == record_audio + + raw_audio_in_rlog = any(m.which() == 'rawAudioData' for m in LogReader(os.path.join(self._get_latest_log_dir(), 'rlog.zst'))) + assert raw_audio_in_rlog == record_audio diff --git a/system/loggerd/tests/test_runner.cc b/openpilot/system/loggerd/tests/test_runner.cc similarity index 100% rename from system/loggerd/tests/test_runner.cc rename to openpilot/system/loggerd/tests/test_runner.cc diff --git a/system/loggerd/tests/test_uploader.py b/openpilot/system/loggerd/tests/test_uploader.py similarity index 97% rename from system/loggerd/tests/test_uploader.py rename to openpilot/system/loggerd/tests/test_uploader.py index 961a8aa36f..3af78e2c37 100644 --- a/system/loggerd/tests/test_uploader.py +++ b/openpilot/system/loggerd/tests/test_uploader.py @@ -4,7 +4,7 @@ import threading import logging import json from pathlib import Path -from openpilot.system.hardware.hw import Paths +from openpilot.common.hardware.hw import Paths from openpilot.common.swaglog import cloudlog from openpilot.system.loggerd.uploader import main, UPLOAD_ATTR_NAME, UPLOAD_ATTR_VALUE @@ -18,8 +18,8 @@ class FakeLogHandler(logging.Handler): self.reset() def reset(self): - self.upload_order = list() - self.upload_ignored = list() + self.upload_order = [] + self.upload_ignored = [] def emit(self, record): try: @@ -50,7 +50,7 @@ class TestUploader(UploaderTestCase): self.end_event.set() self.up_thread.join() - def gen_files(self, lock=False, xattr: bytes = None, boot=True) -> list[Path]: + def gen_files(self, lock=False, xattr: bytes | None = None, boot=True) -> list[Path]: f_paths = [] for t in ["qlog", "rlog", "dcamera.hevc", "fcamera.hevc"]: f_paths.append(self.make_file_with_data(self.seg_dir, t, 1, lock=lock, upload_xattr=xattr)) diff --git a/system/loggerd/tests/test_zstd_writer.cc b/openpilot/system/loggerd/tests/test_zstd_writer.cc similarity index 100% rename from system/loggerd/tests/test_zstd_writer.cc rename to openpilot/system/loggerd/tests/test_zstd_writer.cc diff --git a/openpilot/system/loggerd/tests/vidc_debug.sh b/openpilot/system/loggerd/tests/vidc_debug.sh new file mode 100755 index 0000000000..7471f2ab08 --- /dev/null +++ b/openpilot/system/loggerd/tests/vidc_debug.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -e + +cd /sys/kernel/debug/tracing +echo "" > trace +echo 1 > tracing_on +echo 1 > /sys/kernel/debug/tracing/events/msm_vidc/enable + +echo 0xff > /sys/module/videobuf2_core/parameters/debug +echo 0x7fffffff > /sys/kernel/debug/msm_vidc/debug_level +echo 0xff > /sys/devices/platform/soc/aa00000.qcom,vidc/video4linux/video33/dev_debug + +cat /sys/kernel/debug/tracing/trace_pipe diff --git a/openpilot/system/loggerd/uploader.py b/openpilot/system/loggerd/uploader.py new file mode 100755 index 0000000000..81f8ed1ba3 --- /dev/null +++ b/openpilot/system/loggerd/uploader.py @@ -0,0 +1,271 @@ +#!/usr/bin/env python3 +import json +import os +import random +import requests +import threading +import time +import traceback +import datetime +from collections.abc import Iterator + +from openpilot.cereal import log +import openpilot.cereal.messaging as messaging +from openpilot.common.api import Api +from openpilot.common.utils import get_upload_stream +from openpilot.common.params import Params +from openpilot.common.realtime import set_core_affinity +from openpilot.common.hardware.hw import Paths +from openpilot.system.loggerd.xattr_cache import getxattr, setxattr +from openpilot.common.swaglog import cloudlog + +NetworkType = log.DeviceState.NetworkType +UPLOAD_ATTR_NAME = 'user.upload' +UPLOAD_ATTR_VALUE = b'1' + +MAX_UPLOAD_SIZES = { + "qlog": 25*1e6, # can't be too restrictive here since we use qlogs to find + # bugs, including ones that can cause massive log sizes + "qcam": 5*1e6, +} + +allow_sleep = bool(int(os.getenv("UPLOADER_SLEEP", "1"))) +force_wifi = os.getenv("FORCEWIFI") is not None +fake_upload = os.getenv("FAKEUPLOAD") is not None + + +class FakeRequest: + def __init__(self): + self.headers = {"Content-Length": "0"} + + +class FakeResponse: + def __init__(self): + self.status_code = 200 + self.request = FakeRequest() + + +def get_directory_sort(d: str) -> list[str]: + return [s.rjust(10, '0') for s in d.rsplit('--', 1)] + +def listdir_by_creation(d: str) -> list[str]: + if not os.path.isdir(d): + return [] + + try: + paths = [f for f in os.listdir(d) if os.path.isdir(os.path.join(d, f))] + paths = sorted(paths, key=get_directory_sort) + return paths + except OSError: + cloudlog.exception("listdir_by_creation failed") + return [] + +def clear_locks(root: str) -> None: + for logdir in os.listdir(root): + path = os.path.join(root, logdir) + try: + for fname in os.listdir(path): + if fname.endswith(".lock"): + os.unlink(os.path.join(path, fname)) + except OSError: + cloudlog.exception("clear_locks failed") + + +class Uploader: + def __init__(self, dongle_id: str, root: str): + self.dongle_id = dongle_id + self.api = Api(dongle_id) + self.root = root + + self.params = Params() + + # stats for last successfully uploaded file + self.last_filename = "" + + self.immediate_folders = ["crash/", "boot/"] + self.immediate_priority = {"qlog": 0, "qlog.zst": 0, "qcamera.ts": 1} + + def list_upload_files(self, metered: bool) -> Iterator[tuple[str, str, str]]: + r = self.params.get("AthenadRecentlyViewedRoutes") + requested_routes = [] if r is None else [route for route in r.split(",") if route] + + for logdir in listdir_by_creation(self.root): + path = os.path.join(self.root, logdir) + try: + names = os.listdir(path) + except OSError: + continue + + if any(name.endswith(".lock") for name in names): + continue + + for name in sorted(names, key=lambda n: self.immediate_priority.get(n, 1000)): + key = os.path.join(logdir, name) + fn = os.path.join(path, name) + # skip files already uploaded + try: + ctime = os.path.getctime(fn) + is_uploaded = getxattr(fn, UPLOAD_ATTR_NAME) == UPLOAD_ATTR_VALUE + except OSError: + cloudlog.event("uploader_getxattr_failed", key=key, fn=fn) + # deleter could have deleted, so skip + continue + if is_uploaded: + continue + + # limit uploading on metered connections + if metered: + dt = datetime.timedelta(hours=12) + if logdir in self.immediate_folders and (datetime.datetime.now() - datetime.datetime.fromtimestamp(ctime)) < dt: + continue + + if name == "qcamera.ts" and not any(logdir.startswith(r.split('|')[-1]) for r in requested_routes): + continue + + yield name, key, fn + + def next_file_to_upload(self, metered: bool) -> tuple[str, str, str] | None: + upload_files = list(self.list_upload_files(metered)) + + for name, key, fn in upload_files: + if any(f in fn for f in self.immediate_folders): + return name, key, fn + + for name, key, fn in upload_files: + if name in self.immediate_priority: + return name, key, fn + + return None + + def do_upload(self, key: str, fn: str): + url_resp = self.api.get("v1.4/" + self.dongle_id + "/upload_url/", timeout=10, path=key, access_token=self.api.get_token()) + if url_resp.status_code == 412: + return url_resp + + url_resp_json = json.loads(url_resp.text) + url = url_resp_json['url'] + headers = url_resp_json['headers'] + cloudlog.debug("upload_url v1.4 %s %s", url, str(headers)) + + if fake_upload: + return FakeResponse() + + stream = None + try: + compress = key.endswith('.zst') and not fn.endswith('.zst') + stream, _ = get_upload_stream(fn, compress) + response = requests.put(url, data=stream, headers=headers, timeout=10) + return response + finally: + if stream: + stream.close() + + def upload(self, name: str, key: str, fn: str, network_type: int, metered: bool) -> bool: + try: + sz = os.path.getsize(fn) + except OSError: + cloudlog.exception("upload: getsize failed") + return False + + cloudlog.event("upload_start", key=key, fn=fn, sz=sz, network_type=network_type, metered=metered) + + if sz == 0: + # tag files of 0 size as uploaded + success = True + elif name in MAX_UPLOAD_SIZES and sz > MAX_UPLOAD_SIZES[name]: + cloudlog.event("uploader_too_large", key=key, fn=fn, sz=sz) + success = True + else: + start_time = time.monotonic() + + stat = None + last_exc = None + try: + stat = self.do_upload(key, fn) + except Exception as e: + last_exc = (e, traceback.format_exc()) + + if stat is not None and stat.status_code in (200, 201, 401, 403, 412): + self.last_filename = fn + dt = time.monotonic() - start_time + if stat.status_code == 412: + cloudlog.event("upload_ignored", key=key, fn=fn, sz=sz, network_type=network_type, metered=metered) + else: + content_length = int(stat.request.headers.get("Content-Length", 0)) + speed = (content_length / 1e6) / dt + cloudlog.event("upload_success", key=key, fn=fn, sz=sz, content_length=content_length, + network_type=network_type, metered=metered, speed=speed) + success = True + else: + success = False + cloudlog.event("upload_failed", stat=stat, exc=last_exc, key=key, fn=fn, sz=sz, network_type=network_type, metered=metered) + + if success: + # tag file as uploaded + try: + setxattr(fn, UPLOAD_ATTR_NAME, UPLOAD_ATTR_VALUE) + except OSError: + cloudlog.event("uploader_setxattr_failed", exc=last_exc, key=key, fn=fn, sz=sz) + + return success + + + def step(self, network_type: int, metered: bool) -> bool | None: + d = self.next_file_to_upload(metered) + if d is None: + return None + + name, key, fn = d + + # qlogs and bootlogs need to be compressed before uploading + if key.endswith(('qlog', 'rlog')) or (key.startswith('boot/') and not key.endswith('.zst')): + key += ".zst" + + return self.upload(name, key, fn, network_type, metered) + + +def main(exit_event: threading.Event | None = None) -> None: + if exit_event is None: + exit_event = threading.Event() + + try: + set_core_affinity([0, 1, 2, 3]) + except Exception: + cloudlog.exception("failed to set core affinity") + + clear_locks(Paths.log_root()) + + params = Params() + dongle_id = params.get("DongleId") + + if dongle_id is None: + cloudlog.info("uploader missing dongle_id") + raise Exception("uploader can't start without dongle id") + + sm = messaging.SubMaster(['deviceState']) + uploader = Uploader(dongle_id, Paths.log_root()) + + backoff = 0.1 + while not exit_event.is_set(): + sm.update(0) + offroad = params.get_bool("IsOffroad") + network_type = sm['deviceState'].networkType if not force_wifi else NetworkType.wifi + if network_type == NetworkType.none: + if allow_sleep: + time.sleep(60 if offroad else 5) + continue + + success = uploader.step(sm['deviceState'].networkType.raw, sm['deviceState'].networkMetered) + if success is None: + backoff = 60 if offroad else 5 + elif success: + backoff = 0.1 + else: + cloudlog.info("upload backoff %r", backoff) + backoff = min(backoff*2, 120) + if allow_sleep: + time.sleep(backoff + random.uniform(0, backoff)) + + +if __name__ == "__main__": + main() diff --git a/openpilot/system/loggerd/video_writer.cc b/openpilot/system/loggerd/video_writer.cc new file mode 100644 index 0000000000..1b47a8fceb --- /dev/null +++ b/openpilot/system/loggerd/video_writer.cc @@ -0,0 +1,234 @@ +#include + +#include "system/loggerd/video_writer.h" +#include "common/swaglog.h" +#include "common/util.h" + +VideoWriter::VideoWriter(const char *path, const char *filename, bool remuxing, int width, int height, int fps, cereal::EncodeIndex::Type codec) + : remuxing(remuxing) { + vid_path = util::string_format("%s/%s", path, filename); + lock_path = util::string_format("%s/%s.lock", path, filename); + + int lock_fd = HANDLE_EINTR(open(lock_path.c_str(), O_RDWR | O_CREAT, 0664)); + assert(lock_fd >= 0); + close(lock_fd); + + LOGD("encoder_open %s remuxing:%d", this->vid_path.c_str(), this->remuxing); + if (this->remuxing) { + bool raw = (codec == cereal::EncodeIndex::Type::BIG_BOX_LOSSLESS); + avformat_alloc_output_context2(&this->ofmt_ctx, NULL, raw ? "matroska" : NULL, this->vid_path.c_str()); + assert(this->ofmt_ctx); + + // set codec correctly. needed? + assert(codec != cereal::EncodeIndex::Type::FULL_H_E_V_C); + const AVCodec *avcodec = avcodec_find_encoder(raw ? AV_CODEC_ID_FFVHUFF : AV_CODEC_ID_H264); + assert(avcodec); + + this->codec_ctx = avcodec_alloc_context3(avcodec); + assert(this->codec_ctx); + this->codec_ctx->width = width; + this->codec_ctx->height = height; + this->codec_ctx->pix_fmt = AV_PIX_FMT_YUV420P; + this->codec_ctx->time_base = (AVRational){ 1, fps }; + + if (codec == cereal::EncodeIndex::Type::BIG_BOX_LOSSLESS) { + // without this, there's just noise + int err = avcodec_open2(this->codec_ctx, avcodec, NULL); + assert(err >= 0); + } + + this->out_stream = avformat_new_stream(this->ofmt_ctx, raw ? avcodec : NULL); + assert(this->out_stream); + + int err = avio_open(&this->ofmt_ctx->pb, this->vid_path.c_str(), AVIO_FLAG_WRITE); + assert(err >= 0); + + } else { + this->of = util::safe_fopen(this->vid_path.c_str(), "wb"); + assert(this->of); + } +} + +void VideoWriter::initialize_audio(int sample_rate) { + assert(this->ofmt_ctx->oformat->audio_codec != AV_CODEC_ID_NONE); // check output format supports audio streams + const AVCodec *audio_avcodec = avcodec_find_encoder(AV_CODEC_ID_AAC); + assert(audio_avcodec); + this->audio_codec_ctx = avcodec_alloc_context3(audio_avcodec); + assert(this->audio_codec_ctx); + this->audio_codec_ctx->sample_fmt = AV_SAMPLE_FMT_FLTP; + this->audio_codec_ctx->sample_rate = sample_rate; + #if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(57, 28, 100) // FFmpeg 5.1+ + av_channel_layout_default(&this->audio_codec_ctx->ch_layout, 1); + #else + this->audio_codec_ctx->channel_layout = AV_CH_LAYOUT_MONO; + #endif + this->audio_codec_ctx->bit_rate = 32000; + this->audio_codec_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; + this->audio_codec_ctx->time_base = (AVRational){1, audio_codec_ctx->sample_rate}; + int err = avcodec_open2(this->audio_codec_ctx, audio_avcodec, NULL); + assert(err >= 0); + av_log_set_level(AV_LOG_WARNING); // hide "QAvg" info msgs at the end of every segment + + this->audio_stream = avformat_new_stream(this->ofmt_ctx, NULL); + assert(this->audio_stream); + err = avcodec_parameters_from_context(this->audio_stream->codecpar, this->audio_codec_ctx); + assert(err >= 0); + + this->audio_frame = av_frame_alloc(); + assert(this->audio_frame); + this->audio_frame->format = this->audio_codec_ctx->sample_fmt; + #if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(57, 28, 100) // FFmpeg 5.1+ + av_channel_layout_copy(&this->audio_frame->ch_layout, &this->audio_codec_ctx->ch_layout); + #else + this->audio_frame->channel_layout = this->audio_codec_ctx->channel_layout; + #endif + this->audio_frame->sample_rate = this->audio_codec_ctx->sample_rate; + this->audio_frame->nb_samples = this->audio_codec_ctx->frame_size; + err = av_frame_get_buffer(this->audio_frame, 0); + assert(err >= 0); +} + +void VideoWriter::write(uint8_t *data, int len, long long timestamp, bool codecconfig, bool keyframe) { + if (of && data) { + size_t written = util::safe_fwrite(data, 1, len, of); + if (written != len) { + LOGE("failed to write file.errno=%d", errno); + } + } + + if (remuxing) { + if (codecconfig) { + if (len > 0) { + codec_ctx->extradata = (uint8_t*)av_mallocz(len + AV_INPUT_BUFFER_PADDING_SIZE); + codec_ctx->extradata_size = len; + memcpy(codec_ctx->extradata, data, len); + } + int err = avcodec_parameters_from_context(out_stream->codecpar, codec_ctx); + assert(err >= 0); + // if there is an audio stream, it must be initialized before this point + err = avformat_write_header(ofmt_ctx, NULL); + assert(err >= 0); + header_written = true; + } else { + // input timestamps are in microseconds + AVRational in_timebase = {1, 1000000}; + + AVPacket pkt = {}; + pkt.data = data; + pkt.size = len; + pkt.stream_index = this->out_stream->index; + + enum AVRounding rnd = static_cast(AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX); + pkt.pts = pkt.dts = av_rescale_q_rnd(timestamp, in_timebase, ofmt_ctx->streams[0]->time_base, rnd); + pkt.duration = av_rescale_q(50*1000, in_timebase, ofmt_ctx->streams[0]->time_base); + + if (keyframe) { + pkt.flags |= AV_PKT_FLAG_KEY; + } + + // TODO: can use av_write_frame for non raw? + int err = av_interleaved_write_frame(ofmt_ctx, &pkt); + if (err < 0) { LOGW("ts encoder write issue len: %d ts: %lld", len, timestamp); } + + av_packet_unref(&pkt); + } + } +} + +void VideoWriter::write_audio(uint8_t *data, int len, long long timestamp, int sample_rate) { + if (!remuxing) return; + if (!audio_initialized) { + initialize_audio(sample_rate); + audio_initialized = true; + } + if (!audio_codec_ctx) return; + // sync logMonoTime of first audio packet with the timestampEof of first video packet + if (audio_pts == 0) { + audio_pts = (timestamp * audio_codec_ctx->sample_rate) / 1000000ULL; + } + + // convert s16le samples to fltp and add to buffer + const int16_t *raw_samples = reinterpret_cast(data); + int sample_count = len / sizeof(int16_t); + constexpr float normalizer = 1.0f / 32768.0f; + + const size_t max_buffer_size = sample_rate * 10; // 10 seconds + if (audio_buffer.size() + sample_count > max_buffer_size) { + size_t samples_to_drop = (audio_buffer.size() + sample_count) - max_buffer_size; + LOGE("Audio buffer overflow, dropping %zu oldest samples", samples_to_drop); + audio_buffer.erase(audio_buffer.begin(), audio_buffer.begin() + samples_to_drop); + audio_pts += samples_to_drop; + } + + // Add new samples to the buffer + const size_t original_size = audio_buffer.size(); + audio_buffer.resize(original_size + sample_count); + std::transform(raw_samples, raw_samples + sample_count, audio_buffer.begin() + original_size, + [](int16_t sample) { return sample * normalizer; }); + + if (!header_written) return; // header not written yet, process audio frame after header is written + while (audio_buffer.size() >= audio_codec_ctx->frame_size) { + audio_frame->pts = audio_pts; + float *f_samples = reinterpret_cast(audio_frame->data[0]); + std::copy(audio_buffer.begin(), audio_buffer.begin() + audio_codec_ctx->frame_size, f_samples); + audio_buffer.erase(audio_buffer.begin(), audio_buffer.begin() + audio_codec_ctx->frame_size); + encode_and_write_audio_frame(audio_frame); + } +} + +void VideoWriter::encode_and_write_audio_frame(AVFrame* frame) { + if (!remuxing || !audio_codec_ctx) return; + int send_result = avcodec_send_frame(audio_codec_ctx, frame); // encode frame + if (send_result >= 0) { + AVPacket *pkt = av_packet_alloc(); + while (avcodec_receive_packet(audio_codec_ctx, pkt) == 0) { + av_packet_rescale_ts(pkt, audio_codec_ctx->time_base, audio_stream->time_base); + pkt->stream_index = audio_stream->index; + + int err = av_interleaved_write_frame(ofmt_ctx, pkt); // write encoded frame + if (err < 0) { + LOGW("AUDIO: Write frame failed - error: %d", err); + } + av_packet_unref(pkt); + } + av_packet_free(&pkt); + } else { + LOGW("AUDIO: Failed to send audio frame to encoder: %d", send_result); + } + audio_pts += audio_codec_ctx->frame_size; +} + +void VideoWriter::process_remaining_audio() { + // Process remaining audio samples by padding with silence + if (audio_buffer.size() > 0 && audio_buffer.size() < audio_codec_ctx->frame_size) { + audio_buffer.resize(audio_codec_ctx->frame_size, 0.0f); + + // Encode final frame + audio_frame->pts = audio_pts; + float *f_samples = reinterpret_cast(audio_frame->data[0]); + std::copy(audio_buffer.begin(), audio_buffer.end(), f_samples); + encode_and_write_audio_frame(audio_frame); + } +} + +VideoWriter::~VideoWriter() { + if (this->remuxing) { + if (this->audio_codec_ctx) { + process_remaining_audio(); + encode_and_write_audio_frame(NULL); // flush encoder + avcodec_free_context(&this->audio_codec_ctx); + } + int err = av_write_trailer(this->ofmt_ctx); + if (err != 0) LOGE("av_write_trailer failed %d", err); + avcodec_free_context(&this->codec_ctx); + if (this->audio_frame) av_frame_free(&this->audio_frame); + err = avio_closep(&this->ofmt_ctx->pb); + if (err != 0) LOGE("avio_closep failed %d", err); + avformat_free_context(this->ofmt_ctx); + } else { + util::safe_fflush(this->of); + fclose(this->of); + this->of = nullptr; + } + unlink(this->lock_path.c_str()); +} diff --git a/openpilot/system/loggerd/video_writer.h b/openpilot/system/loggerd/video_writer.h new file mode 100644 index 0000000000..fdec606058 --- /dev/null +++ b/openpilot/system/loggerd/video_writer.h @@ -0,0 +1,42 @@ +#pragma once + +#include +#include + +extern "C" { +#include +#include +} + +#include "openpilot/cereal/messaging/messaging.h" + +class VideoWriter { +public: + VideoWriter(const char *path, const char *filename, bool remuxing, int width, int height, int fps, cereal::EncodeIndex::Type codec); + void write(uint8_t *data, int len, long long timestamp, bool codecconfig, bool keyframe); + void write_audio(uint8_t *data, int len, long long timestamp, int sample_rate); + + ~VideoWriter(); + +private: + void initialize_audio(int sample_rate); + void encode_and_write_audio_frame(AVFrame* frame); + void process_remaining_audio(); + + std::string vid_path, lock_path; + FILE *of = nullptr; + + AVCodecContext *codec_ctx; + AVFormatContext *ofmt_ctx; + AVStream *out_stream; + + bool audio_initialized = false; + bool header_written = false; + AVStream *audio_stream = nullptr; + AVCodecContext *audio_codec_ctx = nullptr; + AVFrame *audio_frame = nullptr; + uint64_t audio_pts = 0; + std::deque audio_buffer; + + bool remuxing; +}; diff --git a/openpilot/system/loggerd/xattr_cache.py b/openpilot/system/loggerd/xattr_cache.py new file mode 100644 index 0000000000..e0f6ba9588 --- /dev/null +++ b/openpilot/system/loggerd/xattr_cache.py @@ -0,0 +1,70 @@ +import ctypes +import errno +import os +import sys + + +if sys.platform == "darwin": + _libc = ctypes.CDLL(None, use_errno=True) + _libc.getxattr.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_uint32, ctypes.c_int] + _libc.getxattr.restype = ctypes.c_ssize_t + _libc.setxattr.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_uint32, ctypes.c_int] + _libc.setxattr.restype = ctypes.c_int + + +def _raise_os_error(path: str) -> None: + error = ctypes.get_errno() + raise OSError(error, os.strerror(error), path) + + +def _getxattr(path: str, attr_name: str) -> bytes: + if sys.platform != "darwin": + return os.getxattr(path, attr_name) + + encoded_path = os.fsencode(path) + encoded_attr_name = os.fsencode(attr_name) + while True: + size = _libc.getxattr(encoded_path, encoded_attr_name, None, 0, 0, 0) + if size == -1: + _raise_os_error(path) + if size == 0: + return b"" + + value = ctypes.create_string_buffer(size) + result = _libc.getxattr(encoded_path, encoded_attr_name, value, size, 0, 0) + if result != -1: + return value.raw[:result] + if ctypes.get_errno() != errno.ERANGE: + _raise_os_error(path) + + +def _setxattr(path: str, attr_name: str, attr_value: bytes) -> None: + if sys.platform != "darwin": + os.setxattr(path, attr_name, attr_value) + return + + encoded_path = os.fsencode(path) + encoded_attr_name = os.fsencode(attr_name) + value = ctypes.create_string_buffer(attr_value) + if _libc.setxattr(encoded_path, encoded_attr_name, value, len(attr_value), 0, 0) == -1: + _raise_os_error(path) + +_cached_attributes: dict[tuple, bytes | None] = {} + +def getxattr(path: str, attr_name: str) -> bytes | None: + key = (path, attr_name) + if key not in _cached_attributes: + try: + response = _getxattr(path, attr_name) + except OSError as e: + # ENODATA (Linux) or ENOATTR (macOS) means attribute hasn't been set + if e.errno == errno.ENODATA or (hasattr(errno, 'ENOATTR') and e.errno == errno.ENOATTR): + response = None + else: + raise + _cached_attributes[key] = response + return _cached_attributes[key] + +def setxattr(path: str, attr_name: str, attr_value: bytes) -> None: + _cached_attributes.pop((path, attr_name), None) + _setxattr(path, attr_name, attr_value) diff --git a/system/loggerd/zstd_writer.cc b/openpilot/system/loggerd/zstd_writer.cc similarity index 100% rename from system/loggerd/zstd_writer.cc rename to openpilot/system/loggerd/zstd_writer.cc diff --git a/system/loggerd/zstd_writer.h b/openpilot/system/loggerd/zstd_writer.h similarity index 100% rename from system/loggerd/zstd_writer.h rename to openpilot/system/loggerd/zstd_writer.h diff --git a/system/logmessaged.py b/openpilot/system/logmessaged.py similarity index 93% rename from system/logmessaged.py rename to openpilot/system/logmessaged.py index c095c26192..937a0741d0 100755 --- a/system/logmessaged.py +++ b/openpilot/system/logmessaged.py @@ -2,9 +2,9 @@ import zmq from typing import NoReturn -import cereal.messaging as messaging +import openpilot.cereal.messaging as messaging from openpilot.common.logging_extra import SwagLogFileFormatter -from openpilot.system.hardware.hw import Paths +from openpilot.common.hardware.hw import Paths from openpilot.common.swaglog import get_file_handler diff --git a/tools/lib/__init__.py b/openpilot/system/manager/__init__.py similarity index 100% rename from tools/lib/__init__.py rename to openpilot/system/manager/__init__.py diff --git a/openpilot/system/manager/build.py b/openpilot/system/manager/build.py new file mode 100755 index 0000000000..75a7dc63eb --- /dev/null +++ b/openpilot/system/manager/build.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python3 +import os +import subprocess + +# NOTE: Do NOT import anything here that needs be built (e.g. params) +from openpilot.common.basedir import BASEDIR +from openpilot.common.spinner import Spinner +from openpilot.common.text_window import TextWindow +from openpilot.common.hardware import HARDWARE, AGNOS + +def build() -> None: + spinner = Spinner() + spinner.update_progress(0, 100) + + HARDWARE.set_power_save(False) + if AGNOS: + os.sched_setaffinity(0, range(8)) # ensure we can use the isolcpus cores + + # building with all cores can result in using too much memory, so retry serially + compile_output: list[bytes] = [] + for parallelism in ([], ["-j4"], ["-j1"]): + compile_output.clear() + with subprocess.Popen(["scons", *parallelism], cwd=BASEDIR, env={**os.environ, "PWD": BASEDIR}, stderr=subprocess.PIPE) as scons: + assert scons.stderr is not None + + # Read progress from stderr and update spinner + while scons.poll() is None: + try: + line = scons.stderr.readline() + if line is None: + continue + line = line.rstrip() + + prefix = b'progress: ' + if line.startswith(prefix): + progress = float(line[len(prefix):]) + spinner.update_progress(100 * min(1., progress / 100.), 100.) + elif len(line): + compile_output.append(line) + print(line.decode('utf8', 'replace')) + except Exception: + pass + + # Drain and close the pipe before retrying or returning. + for line in scons.stderr.read().split(b'\n'): + line = line.rstrip() + if len(line): + compile_output.append(line) + + if scons.returncode == 0: + break + + if scons.returncode != 0: + # Build failed log errors + error_s = b"\n".join(compile_output).decode('utf8', 'replace') + + # Show TextWindow + spinner.close() + if not os.getenv("CI"): + with TextWindow("openpilot failed to build\n \n" + error_s) as t: + t.wait_for_exit() + exit(1) + +if __name__ == "__main__": + build() diff --git a/system/manager/github_runner.sh b/openpilot/system/manager/github_runner.sh similarity index 100% rename from system/manager/github_runner.sh rename to openpilot/system/manager/github_runner.sh diff --git a/openpilot/system/manager/helpers.py b/openpilot/system/manager/helpers.py new file mode 100644 index 0000000000..453e13184d --- /dev/null +++ b/openpilot/system/manager/helpers.py @@ -0,0 +1,61 @@ +import errno +import fcntl +import os +import sys +import pathlib +import shutil +import signal +import subprocess +import tempfile +import threading + +from openpilot.common.basedir import BASEDIR +from openpilot.common.params import Params + +def unblock_stdout() -> None: + # get a non-blocking stdout + child_pid, child_pty = os.forkpty() + if child_pid != 0: # parent + + # child is in its own process group, manually pass kill signals + signal.signal(signal.SIGINT, lambda signum, frame: os.kill(child_pid, signal.SIGINT)) + signal.signal(signal.SIGTERM, lambda signum, frame: os.kill(child_pid, signal.SIGTERM)) + + fcntl.fcntl(sys.stdout, fcntl.F_SETFL, fcntl.fcntl(sys.stdout, fcntl.F_GETFL) | os.O_NONBLOCK) + + while True: + try: + dat = os.read(child_pty, 4096) + except OSError as e: + if e.errno == errno.EIO: + break + continue + + if not dat: + break + + try: + sys.stdout.write(dat.decode('utf8')) + except (OSError, UnicodeDecodeError): + pass + + # os.wait() returns a tuple with the pid and a 16 bit value + # whose low byte is the signal number and whose high byte is the exit status + exit_status = os.wait()[1] >> 8 + os._exit(exit_status) + +def save_bootlog(): + # copy current params + tmp = tempfile.mkdtemp() + params_dirname = pathlib.Path(Params().get_param_path()).name + params_dir = os.path.join(tmp, params_dirname) + shutil.copytree(Params().get_param_path(), params_dir, dirs_exist_ok=True) + + def fn(tmpdir): + env = os.environ.copy() + env['PARAMS_COPY_PATH'] = tmpdir + subprocess.call("./bootlog", cwd=os.path.join(BASEDIR, "openpilot/system/loggerd"), env=env) + shutil.rmtree(tmpdir) + t = threading.Thread(target=fn, args=(tmp, )) + t.daemon = True + t.start() diff --git a/openpilot/system/manager/manager.py b/openpilot/system/manager/manager.py new file mode 100755 index 0000000000..7befb7f4ae --- /dev/null +++ b/openpilot/system/manager/manager.py @@ -0,0 +1,248 @@ +#!/usr/bin/env python3 +import datetime +import os +import signal +import sys +import time +import traceback + +from openpilot.cereal import log +import openpilot.cereal.messaging as messaging +import openpilot.system.sentry as sentry +from openpilot.common.utils import atomic_write +from openpilot.common.params import Params, ParamKeyFlag +from openpilot.common.text_window import TextWindow +from openpilot.common.hardware import HARDWARE, PC +from openpilot.system.manager.helpers import unblock_stdout, save_bootlog +from openpilot.system.manager.process import ensure_running +from openpilot.system.manager.process_config import managed_processes +from openpilot.system.athena.registration import register, UNREGISTERED_DONGLE_ID +from openpilot.common.swaglog import cloudlog, add_file_handler +from openpilot.common.version import get_build_metadata +from openpilot.common.hardware.hw import Paths + +from openpilot.sunnypilot.system.params_migration import run_migration + + +def manager_init() -> None: + save_bootlog() + + build_metadata = get_build_metadata() + + params = Params() + params.clear_all(ParamKeyFlag.CLEAR_ON_MANAGER_START) + params.clear_all(ParamKeyFlag.CLEAR_ON_ONROAD_TRANSITION) + params.clear_all(ParamKeyFlag.CLEAR_ON_OFFROAD_TRANSITION) + params.clear_all(ParamKeyFlag.CLEAR_ON_IGNITION_ON) + # if build_metadata.release_channel: + # params.clear_all(ParamKeyFlag.DEVELOPMENT_ONLY) + + # device boot mode + if params.get("DeviceBootMode") == 1: # start in Always Offroad mode + params.put_bool("OffroadMode", True, block=True) + + # quick boot + if params.get_bool("QuickBootToggle") and not PC: + prebuilt_path = "/data/openpilot/prebuilt" + if not os.path.exists(prebuilt_path): + open(prebuilt_path, 'x').close() + + if params.get_bool("RecordFrontLock"): + params.put_bool("RecordFront", True, block=True) + + if not PC: + run_migration(params) + + # set unset params to their default value + for k in params.all_keys(): + default_value = params.get_default_value(k) + if default_value is not None and params.get(k) is None: + params.put(k, default_value, block=True) + + # Create folders needed for msgq + try: + os.mkdir(Paths.shm_path()) + except FileExistsError: + pass + except PermissionError: + print(f"WARNING: failed to make {Paths.shm_path()}") + + # set params + serial = HARDWARE.get_serial() + params.put("Version", build_metadata.openpilot.version, block=True) + params.put("GitCommit", build_metadata.openpilot.git_commit, block=True) + params.put("GitCommitDate", build_metadata.openpilot.git_commit_date, block=True) + params.put("GitBranch", build_metadata.channel, block=True) + params.put("GitRemote", build_metadata.openpilot.git_origin, block=True) + params.put_bool("IsDevelopmentBranch", build_metadata.development_channel, block=True) + params.put_bool("IsTestedBranch", build_metadata.tested_channel, block=True) + params.put_bool("IsReleaseBranch", build_metadata.release_channel, block=True) + params.put_bool("IsReleaseSpBranch", build_metadata.release_sp_channel, block=True) + params.put("HardwareSerial", serial, block=True) + + # set dongle id + reg_res = register(show_spinner=True) + if reg_res: + dongle_id = reg_res + else: + raise Exception(f"Registration failed for device {serial}") + os.environ['DONGLE_ID'] = dongle_id # Needed for swaglog + os.environ['GIT_ORIGIN'] = build_metadata.openpilot.git_normalized_origin # Needed for swaglog + os.environ['GIT_BRANCH'] = build_metadata.channel # Needed for swaglog + os.environ['GIT_COMMIT'] = build_metadata.openpilot.git_commit # Needed for swaglog + + if not build_metadata.openpilot.is_dirty: + os.environ['CLEAN'] = '1' + + # init logging + sentry.init(sentry.SentryProject.SELFDRIVE) + cloudlog.bind_global(dongle_id=dongle_id, + version=build_metadata.openpilot.version, + origin=build_metadata.openpilot.git_normalized_origin, + branch=build_metadata.channel, + commit=build_metadata.openpilot.git_commit, + dirty=build_metadata.openpilot.is_dirty, + device=HARDWARE.get_device_type()) + +def manager_cleanup() -> None: + # send signals to kill all procs + for p in managed_processes.values(): + p.stop(block=False) + + # ensure all are killed + for p in managed_processes.values(): + p.stop(block=True) + + cloudlog.info("everything is dead") + + +def manager_thread() -> None: + cloudlog.bind(daemon="manager") + cloudlog.info("manager start") + cloudlog.info({"environ": os.environ}) + + params = Params() + + ignore: list[str] = [] + if params.get("DongleId") in (None, UNREGISTERED_DONGLE_ID): + ignore += ["manage_athenad", "uploader"] + if os.getenv("NOBOARD") is not None: + ignore.append("pandad") + ignore += [x for x in os.getenv("BLOCK", "").split(",") if len(x) > 0] + + sm = messaging.SubMaster(['deviceState', 'carParams', 'pandaStates'], poll='deviceState') + pm = messaging.PubMaster(['managerState']) + + params.put_bool("IsOffroad", True, block=True) + ensure_running(managed_processes.values(), False, params=params, CP=sm['carParams'], not_run=ignore) + + started_prev = False + ignition_prev = False + + while True: + sm.update(1000) + + started = sm['deviceState'].started + + if started and not started_prev: + params.clear_all(ParamKeyFlag.CLEAR_ON_ONROAD_TRANSITION) + elif not started and started_prev: + params.clear_all(ParamKeyFlag.CLEAR_ON_OFFROAD_TRANSITION) + + ignition = any(ps.ignitionLine or ps.ignitionCan for ps in sm['pandaStates'] if ps.pandaType != log.PandaState.PandaType.unknown) + if ignition and not ignition_prev: + params.clear_all(ParamKeyFlag.CLEAR_ON_IGNITION_ON) + + # update offroad state for services that don't subscribe to deviceState + if started != started_prev: + params.put_bool("IsOffroad", not started, block=True) + + started_prev = started + ignition_prev = ignition + + ensure_running(managed_processes.values(), started, params=params, CP=sm['carParams'], not_run=ignore) + + running = ' '.join("{}{}\u001b[0m".format("\u001b[32m" if p.proc.is_alive() else "\u001b[31m", p.name) + for p in managed_processes.values() if p.proc) + print(running) + cloudlog.debug(running) + + # send managerState + msg = messaging.new_message('managerState', valid=True) + msg.managerState.processes = [p.get_process_state_msg() for p in managed_processes.values()] + pm.send('managerState', msg) + + # kick AGNOS power monitoring watchdog + try: + if sm.all_checks(['deviceState']): + with atomic_write("/var/tmp/power_watchdog", "w", overwrite=True) as f: + f.write(str(time.monotonic())) + except Exception: + pass + + # Exit main loop when uninstall/shutdown/reboot is needed + shutdown = False + for param in ("DoUninstall", "DoShutdown", "DoReboot"): + if params.get_bool(param): + shutdown = True + params.put("LastManagerExitReason", f"{param} {datetime.datetime.now()}", block=True) + cloudlog.warning(f"Shutting down manager - {param} set") + + if shutdown: + break + + +def main() -> None: + manager_init() + if os.getenv("PREPAREONLY") is not None: + return + + # SystemExit on sigterm + signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit(1)) + + try: + manager_thread() + except Exception: + traceback.print_exc() + sentry.capture_exception() + finally: + manager_cleanup() + + params = Params() + if params.get_bool("DoUninstall"): + cloudlog.warning("uninstalling") + HARDWARE.uninstall() + elif params.get_bool("DoReboot"): + cloudlog.warning("reboot") + HARDWARE.reboot() + elif params.get_bool("DoShutdown"): + cloudlog.warning("shutdown") + HARDWARE.shutdown() + + +if __name__ == "__main__": + unblock_stdout() + + try: + main() + except KeyboardInterrupt: + print("got CTRL-C, exiting") + except Exception: + add_file_handler(cloudlog) + cloudlog.exception("Manager failed to start") + + try: + managed_processes['ui'].stop() + except Exception: + pass + + # Show last 3 lines of traceback + error = traceback.format_exc(-3) + error = "Manager failed to start\n\n" + error + with TextWindow(error) as t: + t.wait_for_exit() + + raise + + # manual exit because we are forked + sys.exit(0) diff --git a/openpilot/system/manager/process.py b/openpilot/system/manager/process.py new file mode 100644 index 0000000000..7f7eabd7be --- /dev/null +++ b/openpilot/system/manager/process.py @@ -0,0 +1,249 @@ +import importlib +import os +import signal +import time +import subprocess +from collections.abc import Callable, ValuesView +from abc import ABC, abstractmethod +from multiprocessing import Process + +from setproctitle import setproctitle + +from openpilot.cereal import log +from opendbc.car.structs import car +import openpilot.cereal.messaging as messaging +import openpilot.system.sentry as sentry +from openpilot.common.basedir import BASEDIR +from openpilot.common.params import Params +from openpilot.common.swaglog import cloudlog + + +def launcher(proc: str, name: str) -> None: + try: + # import the process + mod = importlib.import_module(proc) + + # rename the process + setproctitle(proc) + + # create new context since we forked + messaging.reset_context() + + # add daemon name tag to logs + cloudlog.bind(daemon=name) + sentry.set_tag("daemon", name) + + # exec the process + mod.main() + except KeyboardInterrupt: + cloudlog.warning(f"child {proc} got SIGINT") + except Exception: + # can't install the crash handler because sys.excepthook doesn't play nice + # with threads, so catch it here. + sentry.capture_exception() + raise + + +def nativelauncher(pargs: list[str], cwd: str, name: str) -> None: + os.environ['MANAGER_DAEMON'] = name + + # exec the process + os.chdir(cwd) + os.execvp(pargs[0], pargs) + + +def join_process(process: Process, timeout: float) -> None: + # Process().join(timeout) will hang due to a python 3 bug: https://bugs.python.org/issue28382 + # We have to poll the exitcode instead + t = time.monotonic() + while time.monotonic() - t < timeout and process.exitcode is None: + time.sleep(0.001) + + +class ManagerProcess(ABC): + daemon = False + sigkill = False + should_run: Callable[[bool, Params, car.CarParams], bool] + proc: Process | None = None + enabled = True + name = "" + shutting_down = False + restart_if_crash = False + + @abstractmethod + def start(self) -> None: + pass + + def restart(self) -> None: + self.stop(sig=signal.SIGKILL) + self.start() + + def stop(self, retry: bool = True, block: bool = True, sig: signal.Signals | None = None) -> int | None: + if self.proc is None: + return None + + if self.proc.exitcode is None: + if not self.shutting_down: + cloudlog.info(f"killing {self.name}") + if sig is None: + sig = signal.SIGKILL if self.sigkill else signal.SIGINT + self.signal(sig) + self.shutting_down = True + + if not block: + return None + + join_process(self.proc, 5) + + # If process failed to die send SIGKILL + if self.proc.exitcode is None and retry: + cloudlog.info(f"killing {self.name} with SIGKILL") + self.signal(signal.SIGKILL) + self.proc.join() + + ret = self.proc.exitcode + cloudlog.info(f"{self.name} is dead with {ret}") + + if self.proc.exitcode is not None: + self.shutting_down = False + self.proc = None + + return ret + + def signal(self, sig: int) -> None: + if self.proc is None: + return + + # Don't signal if already exited + if self.proc.exitcode is not None and self.proc.pid is not None: + return + + # Can't signal if we don't have a pid + if self.proc.pid is None: + return + + cloudlog.info(f"sending signal {sig} to {self.name}") + os.kill(self.proc.pid, sig) + + def get_process_state_msg(self): + state = log.ManagerState.ProcessState.new_message() + state.name = self.name + if self.proc: + state.running = self.proc.is_alive() + state.shouldBeRunning = self.proc is not None and not self.shutting_down + state.pid = self.proc.pid or 0 + state.exitCode = self.proc.exitcode or 0 + return state + + +class NativeProcess(ManagerProcess): + def __init__(self, name, cwd, cmdline, should_run, enabled=True, sigkill=False): + self.name = name + self.cwd = cwd + self.cmdline = cmdline + self.should_run = should_run + self.enabled = enabled + self.sigkill = sigkill + self.launcher = nativelauncher + + def start(self) -> None: + # In case we only tried a non blocking stop we need to stop it before restarting + if self.shutting_down: + self.stop() + + if self.proc is not None: + return + + cwd = os.path.join(BASEDIR, self.cwd) + cloudlog.info(f"starting process {self.name}") + self.proc = Process(name=self.name, target=self.launcher, args=(self.cmdline, cwd, self.name)) + self.proc.start() + self.shutting_down = False + + +class PythonProcess(ManagerProcess): + def __init__(self, name, module, should_run, enabled=True, sigkill=False, restart_if_crash=False): + self.name = name + self.module = module + self.should_run = should_run + self.enabled = enabled + self.sigkill = sigkill + self.launcher = launcher + self.restart_if_crash = restart_if_crash + + def start(self) -> None: + # In case we only tried a non blocking stop we need to stop it before restarting + if self.shutting_down: + self.stop() + + if self.proc is not None: + return + + cloudlog.info(f"starting python {self.module}") + self.proc = Process(name=self.name, target=self.launcher, args=(self.module, self.name)) + self.proc.start() + self.shutting_down = False + + +class DaemonProcess(ManagerProcess): + """Python process that has to stay running across manager restart. + This is used for athena so you don't lose SSH access when restarting manager.""" + def __init__(self, name, module, param_name, enabled=True): + self.name = name + self.module = module + self.param_name = param_name + self.enabled = enabled + self.params = None + + @staticmethod + def should_run(started, params, CP): + return True + + def start(self) -> None: + if self.params is None: + self.params = Params() + + pid = self.params.get(self.param_name) + if pid is not None: + try: + os.kill(int(pid), 0) + with open(f'/proc/{pid}/cmdline') as f: + if self.module in f.read(): + # daemon is running + return + except (OSError, FileNotFoundError): + # process is dead + pass + + cloudlog.info(f"starting daemon {self.name}") + proc = subprocess.Popen(['python', '-m', self.module], + stdin=open('/dev/null'), + stdout=open('/dev/null', 'w'), + stderr=open('/dev/null', 'w'), + preexec_fn=os.setpgrp) + + self.params.put(self.param_name, proc.pid, block=True) + + def stop(self, retry=True, block=True, sig=None) -> None: + pass + + +def ensure_running(procs: ValuesView[ManagerProcess], started: bool, params=None, CP: car.CarParams=None, + not_run: list[str] | None=None) -> list[ManagerProcess]: + if not_run is None: + not_run = [] + + running = [] + for p in procs: + if p.enabled and p.name not in not_run and p.should_run(started, params, CP): + if p.restart_if_crash and p.proc is not None and not p.proc.is_alive(): + cloudlog.error(f'Restarting {p.name} (exitcode {p.proc.exitcode})') + p.restart() + running.append(p) + else: + p.stop(block=False) + + for p in running: + p.start() + + return running diff --git a/openpilot/system/manager/process_config.py b/openpilot/system/manager/process_config.py new file mode 100644 index 0000000000..a72675385d --- /dev/null +++ b/openpilot/system/manager/process_config.py @@ -0,0 +1,211 @@ +import os +import operator +import platform + +from opendbc.car.structs import car +from openpilot.cereal import custom +from openpilot.common.params import Params +from openpilot.common.hardware import PC, TICI +from openpilot.system.manager.process import PythonProcess, NativeProcess, DaemonProcess +from openpilot.common.hardware.hw import Paths + +from openpilot.sunnypilot.mapd.mapd_manager import MAPD_PATH + +from openpilot.sunnypilot.models.helpers import get_active_model_runner +from openpilot.sunnypilot.sunnylink.utils import sunnylink_need_register, sunnylink_ready, use_sunnylink_uploader + +WEBCAM = os.getenv("USE_WEBCAM") is not None + +def driverview(started: bool, params: Params, CP: car.CarParams) -> bool: + return started or params.get_bool("IsDriverViewEnabled") + +def notcar(started: bool, params: Params, CP: car.CarParams) -> bool: + return started and CP.notCar + +def iscar(started: bool, params: Params, CP: car.CarParams) -> bool: + return started and not CP.notCar + +def logging(started: bool, params: Params, CP: car.CarParams) -> bool: + run = (not CP.notCar) or not params.get_bool("DisableLogging") + return started and run + +def ublox_available() -> bool: + return os.path.exists('/dev/ttyHS0') and not os.path.exists('/persist/comma/use-quectel-gps') + +def ublox(started: bool, params: Params, CP: car.CarParams) -> bool: + use_ublox = ublox_available() + if use_ublox != params.get_bool("UbloxAvailable"): + params.put_bool("UbloxAvailable", use_ublox, block=True) + return started and use_ublox + +def joystick(started: bool, params: Params, CP: car.CarParams) -> bool: + return started and params.get_bool("JoystickDebugMode") + +def not_joystick(started: bool, params: Params, CP: car.CarParams) -> bool: + return started and not params.get_bool("JoystickDebugMode") + +def long_maneuver(started: bool, params: Params, CP: car.CarParams) -> bool: + return started and params.get_bool("LongitudinalManeuverMode") + +def lat_maneuver(started: bool, params: Params, CP: car.CarParams) -> bool: + return started and params.get_bool("LateralManeuverMode") + +def not_long_maneuver(started: bool, params: Params, CP: car.CarParams) -> bool: + return started and not params.get_bool("LongitudinalManeuverMode") + +def qcomgps(started: bool, params: Params, CP: car.CarParams) -> bool: + return started and not ublox_available() + +def always_run(started: bool, params: Params, CP: car.CarParams) -> bool: + return True + +def only_onroad(started: bool, params: Params, CP: car.CarParams) -> bool: + return started + +def only_offroad(started: bool, params: Params, CP: car.CarParams) -> bool: + return not started + +def livestream(started: bool, params: Params, CP: car.CarParams) -> bool: + return params.get_bool("IsLiveStreaming") + +def use_github_runner(started, params, CP: car.CarParams) -> bool: + return not PC and params.get_bool("EnableGithubRunner") and ( + not params.get_bool("NetworkMetered") and not params.get_bool("GithubRunnerSufficientVoltage")) + +def use_copyparty(started, params, CP: car.CarParams) -> bool: + return bool(params.get_bool("EnableCopyparty")) + +def sunnylink_ready_shim(started, params, CP: car.CarParams) -> bool: + """Shim for sunnylink_ready to match the process manager signature.""" + return sunnylink_ready(params) + +def sunnylink_need_register_shim(started, params, CP: car.CarParams) -> bool: + """Shim for sunnylink_need_register to match the process manager signature.""" + return sunnylink_need_register(params) + +def use_sunnylink_uploader_shim(started, params, CP: car.CarParams) -> bool: + """Shim for use_sunnylink_uploader to match the process manager signature.""" + return use_sunnylink_uploader(params) + +def is_tinygrad_model(started, params, CP: car.CarParams) -> bool: + """Check if the active model runner is SNPE.""" + return bool(get_active_model_runner(params, not started) == custom.ModelManagerSP.Runner.tinygrad) + +def is_stock_model(started, params, CP: car.CarParams) -> bool: + """Check if the active model runner is stock.""" + return bool(get_active_model_runner(params, not started) == custom.ModelManagerSP.Runner.stock) + +def mapd_ready(started: bool, params: Params, CP: car.CarParams) -> bool: + return bool(os.path.exists(Paths.mapd_root())) + +def uploader_ready(started: bool, params: Params, CP: car.CarParams) -> bool: + if not params.get_bool("OnroadUploads"): + return only_offroad(started, params, CP) + + return always_run(started, params, CP) + +def or_(*fns): + return lambda *args: operator.or_(*(fn(*args) for fn in fns)) + +def and_(*fns): + return lambda *args: operator.and_(*(fn(*args) for fn in fns)) + +def not_(*fns): + return lambda *args: operator.not_(*(fn(*args) for fn in fns)) + +procs = [ + DaemonProcess("manage_athenad", "openpilot.system.athena.manage_athenad", "AthenadPid"), + + NativeProcess("loggerd", "openpilot/system/loggerd", ["./loggerd"], logging), + NativeProcess("encoderd", "openpilot/system/loggerd", ["./encoderd"], only_onroad), + NativeProcess("stream_encoderd", "openpilot/system/loggerd", ["./encoderd", "--stream"], or_(and_(livestream, not_(iscar)), notcar)), + PythonProcess("logmessaged", "openpilot.system.logmessaged", always_run), + + NativeProcess("camerad", "openpilot/system/camerad", ["./camerad"], or_(driverview, livestream), enabled=not WEBCAM), + PythonProcess("webcamerad", "openpilot.system.camerad.webcam.camerad", driverview, enabled=WEBCAM), + PythonProcess("proclogd", "openpilot.system.proclogd", only_onroad, enabled=platform.system() != "Darwin"), + PythonProcess("journald", "openpilot.system.journald", only_onroad, platform.system() != "Darwin"), + PythonProcess("micd", "openpilot.system.micd", iscar), + PythonProcess("timed", "openpilot.system.timed", always_run, enabled=not PC), + + PythonProcess("modeld", "openpilot.selfdrive.modeld.modeld", and_(only_onroad, is_stock_model)), + PythonProcess("dmonitoringmodeld", "openpilot.selfdrive.modeld.dmonitoringmodeld", driverview, enabled=(WEBCAM or not PC)), + + PythonProcess("sensord", "openpilot.system.sensord.sensord", only_onroad, enabled=not PC), + PythonProcess("ui", "openpilot.selfdrive.ui.ui", always_run, restart_if_crash=True), + PythonProcess("soundd", "openpilot.selfdrive.ui.soundd", driverview), + PythonProcess("locationd", "openpilot.selfdrive.locationd.locationd", only_onroad), + NativeProcess("_pandad", "openpilot/selfdrive/pandad", ["./pandad"], always_run, enabled=False), + PythonProcess("calibrationd", "openpilot.selfdrive.locationd.calibrationd", only_onroad), + PythonProcess("torqued", "openpilot.selfdrive.locationd.torqued", only_onroad), + PythonProcess("controlsd", "openpilot.selfdrive.controls.controlsd", and_(not_joystick, iscar)), + PythonProcess("joystickd", "openpilot.tools.joystick.joystickd", or_(joystick, notcar)), + PythonProcess("selfdrived", "openpilot.selfdrive.selfdrived.selfdrived", only_onroad), + PythonProcess("card", "openpilot.selfdrive.car.card", only_onroad), + PythonProcess("deleter", "openpilot.system.loggerd.deleter", always_run), + PythonProcess("dmonitoringd", "openpilot.selfdrive.monitoring.dmonitoringd", driverview, enabled=(WEBCAM or not PC)), + PythonProcess("qcomgpsd", "openpilot.system.qcomgpsd.qcomgpsd", qcomgps, enabled=TICI), + PythonProcess("pandad", "openpilot.selfdrive.pandad.pandad", always_run), + PythonProcess("paramsd", "openpilot.selfdrive.locationd.paramsd", only_onroad), + PythonProcess("lagd", "openpilot.selfdrive.locationd.lagd", only_onroad), + PythonProcess("ubloxd", "openpilot.system.ubloxd.ubloxd", ublox, enabled=TICI), + PythonProcess("pigeond", "openpilot.system.ubloxd.pigeond", ublox, enabled=TICI), + PythonProcess("plannerd", "openpilot.selfdrive.controls.plannerd", not_long_maneuver), + PythonProcess("maneuversd", "openpilot.tools.longitudinal_maneuvers.maneuversd", long_maneuver), + PythonProcess("lateral_maneuversd", "openpilot.tools.lateral_maneuvers.lateral_maneuversd", lat_maneuver), + PythonProcess("radard", "openpilot.selfdrive.controls.radard", only_onroad), + PythonProcess("hardwared", "openpilot.system.hardware.hardwared", always_run), + PythonProcess("modem", "openpilot.common.hardware.tici.modem", always_run, enabled=TICI), + PythonProcess("tombstoned", "openpilot.system.tombstoned", always_run, enabled=not PC), + PythonProcess("updated", "openpilot.system.updated.updated", only_offroad, enabled=not PC), + PythonProcess("uploader", "openpilot.system.loggerd.uploader", uploader_ready), + PythonProcess("statsd", "openpilot.sunnypilot.system.statsd", always_run), + PythonProcess("feedbackd", "openpilot.selfdrive.ui.feedback.feedbackd", only_onroad), + + # debug procs + NativeProcess("bridge", "openpilot/cereal/messaging", ["./bridge"], notcar), + PythonProcess("webrtcd", "openpilot.system.webrtc.webrtcd", or_(and_(livestream, not_(iscar)), notcar)), + PythonProcess("joystick", "openpilot.tools.joystick.joystick_control", and_(joystick, iscar)), + + # sunnylink <3 + DaemonProcess("manage_sunnylinkd", "openpilot.sunnypilot.sunnylink.athena.manage_sunnylinkd", "SunnylinkdPid"), + PythonProcess("sunnylink_registration_manager", "openpilot.sunnypilot.sunnylink.registration_manager", sunnylink_need_register_shim), + PythonProcess("statsd_sp", "openpilot.sunnypilot.sunnylink.statsd", and_(always_run, sunnylink_ready_shim)), +] + +# sunnypilot +procs += [ + # Models + PythonProcess("models_manager", "openpilot.sunnypilot.models.manager", only_offroad), + NativeProcess("modeld_tinygrad", "openpilot/sunnypilot/modeld_v2", ["./modeld"], and_(only_onroad, is_tinygrad_model)), + + # Backup + PythonProcess("backup_manager", "openpilot.sunnypilot.sunnylink.backups.manager", and_(only_offroad, sunnylink_ready_shim)), + + # mapd + NativeProcess("mapd", Paths.mapd_root(), ["bash", "-c", f"{MAPD_PATH} > /dev/null 2>&1"], mapd_ready), + PythonProcess("mapd_manager", "openpilot.sunnypilot.mapd.mapd_manager", always_run), + + # locationd + NativeProcess("locationd_llk", "openpilot/sunnypilot/selfdrive/locationd", ["./locationd"], only_onroad), +] + +if os.path.exists("./github_runner.sh"): + procs += [NativeProcess("github_runner_start", "openpilot/system/manager", + ["./github_runner.sh", "start"], and_(only_offroad, use_github_runner), sigkill=False)] + +if os.path.exists("../../sunnypilot/sunnylink/uploader.py"): + procs += [PythonProcess("sunnylink_uploader", "openpilot.sunnypilot.sunnylink.uploader", use_sunnylink_uploader_shim)] + +if os.path.exists("../../third_party/copyparty/copyparty-sfx.py"): + sunnypilot_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")) + copyparty_args = [f"-v{Paths.crash_log_root()}:/swaglogs:r"] + copyparty_args += [f"-v{Paths.log_root()}:/routes:r"] + copyparty_args += [f"-v{Paths.model_root()}:/models:rw"] + copyparty_args += [f"-v{sunnypilot_root}:/sunnypilot:rw"] + copyparty_args += ["-p8080"] + copyparty_args += ["-z"] + copyparty_args += ["-q"] + procs += [NativeProcess("copyparty-sfx", "openpilot/third_party/copyparty", ["./copyparty-sfx.py", *copyparty_args], and_(only_offroad, use_copyparty))] + +managed_processes = {p.name: p for p in procs} diff --git a/tools/lib/tests/__init__.py b/openpilot/system/manager/test/__init__.py similarity index 100% rename from tools/lib/tests/__init__.py rename to openpilot/system/manager/test/__init__.py diff --git a/system/manager/test/test_manager.py b/openpilot/system/manager/test/test_manager.py similarity index 82% rename from system/manager/test/test_manager.py rename to openpilot/system/manager/test/test_manager.py index 9c0b664006..a3808bf29f 100644 --- a/system/manager/test/test_manager.py +++ b/openpilot/system/manager/test/test_manager.py @@ -3,12 +3,12 @@ import pytest import signal import time -from cereal import car +from opendbc.car.structs import car from openpilot.common.params import Params import openpilot.system.manager.manager as manager from openpilot.system.manager.process import ensure_running from openpilot.system.manager.process_config import managed_processes, procs -from openpilot.system.hardware import HARDWARE +from openpilot.common.hardware import HARDWARE os.environ['FAKEUPLOAD'] = "1" @@ -27,10 +27,6 @@ class TestManager: def teardown_method(self): manager.manager_cleanup() - def test_manager_prepare(self): - os.environ['PREPAREONLY'] = '1' - manager.main() - def test_duplicate_procs(self): assert len(procs) == len(managed_processes), "Duplicate process names" @@ -38,6 +34,19 @@ class TestManager: # TODO: ensure there are blacklisted procs until we have a dedicated test assert len(BLACKLIST_PROCS), "No blacklisted procs to test not_run" + def test_set_params_with_default_value(self): + params = Params() + params.clear_all() + + os.environ['PREPAREONLY'] = '1' + manager.main() + for k in params.all_keys(): + default_value = params.get_default_value(k) + if default_value is not None: + assert params.get(k) == default_value + assert params.get("OpenpilotEnabledToggle") + assert params.get("RouteCount") == 0 + @pytest.mark.skip("this test is flaky the way it's currently written, should be moved to test_onroad") def test_clean_exit(self, subtests): """ diff --git a/system/micd.py b/openpilot/system/micd.py similarity index 79% rename from system/micd.py rename to openpilot/system/micd.py index 38f3225f55..a3a93c8c1a 100755 --- a/system/micd.py +++ b/openpilot/system/micd.py @@ -3,16 +3,16 @@ import numpy as np from functools import cache import threading -from cereal import messaging +from openpilot.cereal import messaging from openpilot.common.realtime import Ratekeeper -from openpilot.common.retry import retry +from openpilot.common.utils import retry from openpilot.common.swaglog import cloudlog RATE = 10 -FFT_SAMPLES = 4096 +FFT_SAMPLES = 1600 # 100ms REFERENCE_SPL = 2e-5 # newtons/m^2 -SAMPLE_RATE = 44100 -SAMPLE_BUFFER = 4096 # approx 100ms +SAMPLE_RATE = 16000 +SAMPLE_BUFFER = 800 # 50ms @cache @@ -45,7 +45,7 @@ def apply_a_weighting(measurements: np.ndarray) -> np.ndarray: class Mic: def __init__(self): self.rk = Ratekeeper(RATE) - self.pm = messaging.PubMaster(['microphone']) + self.pm = messaging.PubMaster(['soundPressure', 'rawAudioData']) self.measurements = np.empty(0) @@ -61,12 +61,12 @@ class Mic: sound_pressure_weighted = self.sound_pressure_weighted sound_pressure_level_weighted = self.sound_pressure_level_weighted - msg = messaging.new_message('microphone', valid=True) - msg.microphone.soundPressure = float(sound_pressure) - msg.microphone.soundPressureWeighted = float(sound_pressure_weighted) - msg.microphone.soundPressureWeightedDb = float(sound_pressure_level_weighted) + msg = messaging.new_message('soundPressure', valid=True) + msg.soundPressure.soundPressure = float(sound_pressure) + msg.soundPressure.soundPressureWeighted = float(sound_pressure_weighted) + msg.soundPressure.soundPressureWeightedDb = float(sound_pressure_level_weighted) - self.pm.send('microphone', msg) + self.pm.send('soundPressure', msg) self.rk.keep_time() def callback(self, indata, frames, time, status): @@ -76,6 +76,12 @@ class Mic: Logged A-weighted equivalents are rough approximations of the human-perceived loudness. """ + msg = messaging.new_message('rawAudioData', valid=True) + audio_data_int_16 = (indata[:, 0] * 32767).astype(np.int16) + msg.rawAudioData.data = audio_data_int_16.tobytes() + msg.rawAudioData.sampleRate = SAMPLE_RATE + self.pm.send('rawAudioData', msg) + with self.lock: self.measurements = np.concatenate((self.measurements, indata[:, 0])) @@ -88,7 +94,7 @@ class Mic: self.measurements = self.measurements[FFT_SAMPLES:] - @retry(attempts=7, delay=3) + @retry(attempts=10, delay=3) def get_stream(self, sd): # reload sounddevice to reinitialize portaudio sd._terminate() diff --git a/openpilot/system/proclogd.py b/openpilot/system/proclogd.py new file mode 100755 index 0000000000..9979b3a401 --- /dev/null +++ b/openpilot/system/proclogd.py @@ -0,0 +1,286 @@ +#!/usr/bin/env python3 +import os +from typing import NoReturn, TypedDict + +from openpilot.cereal import messaging +from openpilot.common.realtime import Ratekeeper +from openpilot.common.swaglog import cloudlog + +JIFFY = os.sysconf(os.sysconf_names['SC_CLK_TCK']) +PAGE_SIZE = os.sysconf(os.sysconf_names['SC_PAGE_SIZE']) + + +def _cpu_times() -> list[dict[str, float]]: + cpu_times: list[dict[str, float]] = [] + try: + with open('/proc/stat') as f: + lines = f.readlines()[1:] + for line in lines: + if not line.startswith('cpu') or len(line) < 4 or not line[3].isdigit(): + break + parts = line.split() + cpu_times.append({ + 'cpuNum': int(parts[0][3:]), + 'user': float(parts[1]) / JIFFY, + 'nice': float(parts[2]) / JIFFY, + 'system': float(parts[3]) / JIFFY, + 'idle': float(parts[4]) / JIFFY, + 'iowait': float(parts[5]) / JIFFY, + 'irq': float(parts[6]) / JIFFY, + 'softirq': float(parts[7]) / JIFFY, + }) + except Exception: + cloudlog.exception("failed to read /proc/stat") + return cpu_times + + +def _mem_info() -> dict[str, int]: + keys = ["MemTotal:", "MemFree:", "MemAvailable:", "Buffers:", "Cached:", "Active:", "Inactive:", "Shmem:"] + info: dict[str, int] = dict.fromkeys(keys, 0) + try: + with open('/proc/meminfo') as f: + for line in f: + parts = line.split() + if parts and parts[0] in info: + info[parts[0]] = int(parts[1]) * 1024 + except Exception: + cloudlog.exception("failed to read /proc/meminfo") + return info + + +_STAT_POS = { + 'pid': 1, + 'state': 3, + 'ppid': 4, + 'utime': 14, + 'stime': 15, + 'cutime': 16, + 'cstime': 17, + 'priority': 18, + 'nice': 19, + 'num_threads': 20, + 'starttime': 22, + 'vsize': 23, + 'rss': 24, + 'processor': 39, +} + +class ProcStat(TypedDict): + name: str + pid: int + state: str + ppid: int + utime: int + stime: int + cutime: int + cstime: int + priority: int + nice: int + num_threads: int + starttime: int + vms: int + rss: int + processor: int + + +def _parse_proc_stat(stat: str) -> ProcStat | None: + open_paren = stat.find('(') + close_paren = stat.rfind(')') + if open_paren == -1 or close_paren == -1 or open_paren > close_paren: + return None + name = stat[open_paren + 1:close_paren] + stat = stat[:open_paren] + stat[open_paren:close_paren].replace(' ', '_') + stat[close_paren:] + parts = stat.split() + if len(parts) < 52: + return None + try: + return { + 'name': name, + 'pid': int(parts[_STAT_POS['pid'] - 1]), + 'state': parts[_STAT_POS['state'] - 1][0], + 'ppid': int(parts[_STAT_POS['ppid'] - 1]), + 'utime': int(parts[_STAT_POS['utime'] - 1]), + 'stime': int(parts[_STAT_POS['stime'] - 1]), + 'cutime': int(parts[_STAT_POS['cutime'] - 1]), + 'cstime': int(parts[_STAT_POS['cstime'] - 1]), + 'priority': int(parts[_STAT_POS['priority'] - 1]), + 'nice': int(parts[_STAT_POS['nice'] - 1]), + 'num_threads': int(parts[_STAT_POS['num_threads'] - 1]), + 'starttime': int(parts[_STAT_POS['starttime'] - 1]), + 'vms': int(parts[_STAT_POS['vsize'] - 1]), + 'rss': int(parts[_STAT_POS['rss'] - 1]), + 'processor': int(parts[_STAT_POS['processor'] - 1]), + } + except Exception: + cloudlog.exception("failed to parse /proc//stat") + return None + +class SmapsData(TypedDict): + pss: int # bytes + pss_anon: int # bytes + pss_shmem: int # bytes + + +_SMAPS_KEYS = {b'Pss:', b'Pss_Anon:', b'Pss_Shmem:'} + +# smaps_rollup (kernel 4.14+) is ideal but missing on some BSP kernels; +# fall back to per-VMA smaps (any kernel). Pss_Anon/Pss_Shmem only in 5.x+. +_smaps_path: str | None = None # auto-detected on first call + +# per-VMA smaps is expensive (kernel walks page tables for every VMA). +# cache results and only refresh every N cycles to keep CPU low. +_smaps_cache: dict[int, SmapsData] = {} +_smaps_cycle = 0 +_SMAPS_EVERY = 20 # refresh every 20th cycle (40s at 0.5Hz) + + +def _read_smaps(pid: int) -> SmapsData: + global _smaps_path + try: + if _smaps_path is None: + _smaps_path = 'smaps_rollup' if os.path.exists(f'/proc/{pid}/smaps_rollup') else 'smaps' + + result: SmapsData = {'pss': 0, 'pss_anon': 0, 'pss_shmem': 0} + with open(f'/proc/{pid}/{_smaps_path}', 'rb') as f: + for line in f: + parts = line.split() + if len(parts) >= 2 and parts[0] in _SMAPS_KEYS: + val = int(parts[1]) * 1024 # kB -> bytes + if parts[0] == b'Pss:': + result['pss'] += val + elif parts[0] == b'Pss_Anon:': + result['pss_anon'] += val + elif parts[0] == b'Pss_Shmem:': + result['pss_shmem'] += val + return result + except (FileNotFoundError, PermissionError, ProcessLookupError, OSError): + return {'pss': 0, 'pss_anon': 0, 'pss_shmem': 0} + + +def _get_smaps_cached(pid: int) -> SmapsData: + """Return cached smaps data, refreshing every _SMAPS_EVERY cycles.""" + if _smaps_cycle == 0 or pid not in _smaps_cache: + _smaps_cache[pid] = _read_smaps(pid) + return _smaps_cache.get(pid, {'pss': 0, 'pss_anon': 0, 'pss_shmem': 0}) + + +class ProcExtra(TypedDict): + pid: int + name: str + exe: str + cmdline: list[str] + + +_proc_cache: dict[int, ProcExtra] = {} + + +def _get_proc_extra(pid: int, name: str) -> ProcExtra: + cache: ProcExtra | None = _proc_cache.get(pid) + if cache is None or cache.get('name') != name: + exe = '' + cmdline: list[str] = [] + try: + exe = os.readlink(f'/proc/{pid}/exe') + except OSError: + pass + try: + with open(f'/proc/{pid}/cmdline', 'rb') as f: + cmdline = [c.decode('utf-8', errors='replace') for c in f.read().split(b'\0') if c] + except OSError: + pass + cache = {'pid': pid, 'name': name, 'exe': exe, 'cmdline': cmdline} + _proc_cache[pid] = cache + return cache + + +def _procs() -> list[ProcStat]: + stats: list[ProcStat] = [] + for pid_str in os.listdir('/proc'): + if not pid_str.isdigit(): + continue + try: + with open(f'/proc/{pid_str}/stat') as f: + stat = f.read() + parsed = _parse_proc_stat(stat) + if parsed is not None: + stats.append(parsed) + except OSError: + continue + return stats + + +def build_proc_log_message(msg) -> None: + pl = msg.procLog + + procs = _procs() + l = pl.init('procs', len(procs)) + for i, r in enumerate(procs): + proc = l[i] + proc.pid = r['pid'] + proc.state = ord(r['state'][0]) + proc.ppid = r['ppid'] + proc.cpuUser = r['utime'] / JIFFY + proc.cpuSystem = r['stime'] / JIFFY + proc.cpuChildrenUser = r['cutime'] / JIFFY + proc.cpuChildrenSystem = r['cstime'] / JIFFY + proc.priority = r['priority'] + proc.nice = r['nice'] + proc.numThreads = r['num_threads'] + proc.startTime = r['starttime'] / JIFFY + proc.memVms = r['vms'] + proc.memRss = r['rss'] * PAGE_SIZE + proc.processor = r['processor'] + proc.name = r['name'] + + extra = _get_proc_extra(r['pid'], r['name']) + proc.exe = extra['exe'] + cmdline = proc.init('cmdline', len(extra['cmdline'])) + for j, arg in enumerate(extra['cmdline']): + cmdline[j] = arg + + # smaps is expensive (kernel walks page tables); skip small processes, use cache + if r['rss'] * PAGE_SIZE > 5 * 1024 * 1024: + smaps = _get_smaps_cached(r['pid']) + proc.memPss = smaps['pss'] + proc.memPssAnon = smaps['pss_anon'] + proc.memPssShmem = smaps['pss_shmem'] + + cpu_times = _cpu_times() + cpu_list = pl.init('cpuTimes', len(cpu_times)) + for i, ct in enumerate(cpu_times): + cpu = cpu_list[i] + cpu.cpuNum = ct['cpuNum'] + cpu.user = ct['user'] + cpu.nice = ct['nice'] + cpu.system = ct['system'] + cpu.idle = ct['idle'] + cpu.iowait = ct['iowait'] + cpu.irq = ct['irq'] + cpu.softirq = ct['softirq'] + + mem_info = _mem_info() + pl.mem.total = mem_info["MemTotal:"] + pl.mem.free = mem_info["MemFree:"] + pl.mem.available = mem_info["MemAvailable:"] + pl.mem.buffers = mem_info["Buffers:"] + pl.mem.cached = mem_info["Cached:"] + pl.mem.active = mem_info["Active:"] + pl.mem.inactive = mem_info["Inactive:"] + pl.mem.shared = mem_info["Shmem:"] + + global _smaps_cycle + _smaps_cycle = (_smaps_cycle + 1) % _SMAPS_EVERY + + +def main() -> NoReturn: + pm = messaging.PubMaster(['procLog']) + rk = Ratekeeper(0.5) + while True: + msg = messaging.new_message('procLog', valid=True) + build_proc_log_message(msg) + pm.send('procLog', msg) + rk.keep_time() + + +if __name__ == '__main__': + main() diff --git a/system/qcomgpsd/modemdiag.py b/openpilot/system/qcomgpsd/modemdiag.py similarity index 80% rename from system/qcomgpsd/modemdiag.py rename to openpilot/system/qcomgpsd/modemdiag.py index 5d72aeba9e..313563a314 100644 --- a/system/qcomgpsd/modemdiag.py +++ b/openpilot/system/qcomgpsd/modemdiag.py @@ -1,8 +1,31 @@ import select -from serial import Serial -from crcmod import mkCrcFun from struct import pack, unpack_from, calcsize +from openpilot.common.serial import Serial + + +def _gen_crc16_reflected_table(poly: int) -> list[int]: + # poly is the reflected form (e.g. 0x8408 for CRC-16 poly 0x1021) + table = [] + for i in range(256): + crc = i + for _ in range(8): + if crc & 1: + crc = (crc >> 1) ^ poly + else: + crc >>= 1 + table.append(crc) + return table + +# CRC-16/IBM-SDLC (aka X-25 / ISO-HDLC): poly 0x1021, refin/refout, init/xor 0xFFFF +_CRC16_X25_TABLE = _gen_crc16_reflected_table(0x8408) + +def crc16_x25(data: bytes) -> int: + crc = 0xFFFF + for b in data: + crc = _CRC16_X25_TABLE[(crc ^ b) & 0xFF] ^ (crc >> 8) + return crc ^ 0xFFFF + class ModemDiag: def __init__(self): self.serial = self.open_serial() @@ -15,12 +38,11 @@ class ModemDiag: serial.reset_output_buffer() return serial - ccitt_crc16 = mkCrcFun(0x11021, initCrc=0, xorOut=0xffff) ESCAPE_CHAR = b'\x7d' TRAILER_CHAR = b'\x7e' def hdlc_encapsulate(self, payload): - payload += pack(' 'GnssClockNmeaPort': + ints = [int(value) if value else None for value in values[:5]] + floats = [float(value) if value else None for value in values[5:9]] + return cls(*ints, *floats) + +@dataclass +class GnssMeasNmeaPort: + messageCount: int | None + messageNum: int | None + svCount: int | None + # constellation enum: + # 1 = GPS + # 2 = SBAS + # 3 = GLONASS + # 4 = QZSS + # 5 = BEIDOU + # 6 = GALILEO + constellation: int | None + svId: int | None + flags: int | None # always zero + time_offset_ns: int | None + # state bit mask: + # 0x0001 = CODE LOCK + # 0x0002 = BIT SYNC + # 0x0004 = SUBFRAME SYNC + # 0x0008 = TIME OF WEEK DECODED + # 0x0010 = MSEC AMBIGUOUS + # 0x0020 = SYMBOL SYNC + # 0x0040 = GLONASS STRING SYNC + # 0x0080 = GLONASS TIME OF DAY DECODED + # 0x0100 = BEIDOU D2 BIT SYNC + # 0x0200 = BEIDOU D2 SUBFRAME SYNC + # 0x0400 = GALILEO E1BC CODE LOCK + # 0x0800 = GALILEO E1C 2ND CODE LOCK + # 0x1000 = GALILEO E1B PAGE SYNC + # 0x2000 = GALILEO E1B PAGE SYNC + state: int | None + time_of_week_ns: int | None + time_of_week_uncertainty_ns: int | None # 1-sigma + carrier_to_noise_ratio: float | None + pseudorange_rate: float | None + pseudorange_rate_uncertainty: float | None # 1-sigma + + @classmethod + def from_fields(cls, values: list[str]) -> 'GnssMeasNmeaPort': + ints = [int(value) if value else None for value in values[:10]] + floats = [float(value) if value else None for value in values[10:13]] + return cls(*ints, *floats) + +def nmea_checksum_ok(s): + checksum = 0 + for i, c in enumerate(s[1:]): + if c == "*": + if i != len(s) - 4: # should be 3rd to last character + print("ERROR: NMEA string does not have checksum delimiter in correct location:", s) + return False + break + checksum ^= ord(c) + else: + print("ERROR: NMEA string does not have checksum delimiter:", s) + return False + + return True + +def process_nmea_port_messages(device:str="/dev/ttyUSB1") -> NoReturn: + while True: + try: + with open(device) as nmeaport: + for line in nmeaport: + line = line.strip() + if DEBUG: + print(line) + if not line.startswith("$"): # all NMEA messages start with $ + continue + if not nmea_checksum_ok(line): + continue + + fields = line.split(",") + match fields[0]: + case "$GNCLK": + # fields at end are reserved (not used) + gnss_clock = GnssClockNmeaPort.from_fields(fields[1:10]) + print(gnss_clock) + case "$GNMEAS": + # fields at end are reserved (not used) + gnss_meas = GnssMeasNmeaPort.from_fields(fields[1:14]) + print(gnss_meas) + except Exception as e: + print(e) + sleep(1) + +def main() -> NoReturn: + from openpilot.common.gpio import gpio_init, gpio_set + from openpilot.common.hardware.tici.pins import GPIO + from openpilot.system.qcomgpsd.qcomgpsd import at_cmd + + try: + check_output(["pidof", "qcomgpsd"]) + print("qcomgpsd is running, please kill openpilot before running this script! (aborted)") + sys.exit(1) + except CalledProcessError as e: + if e.returncode != 1: # 1 == no process found (pandad not running) + raise e + + print("power up antenna ...") + gpio_init(GPIO.GNSS_PWR_EN, True) + gpio_set(GPIO.GNSS_PWR_EN, True) + + if b"+QGPS: 0" not in (at_cmd("AT+QGPS?") or b""): + print("stop location tracking ...") + at_cmd("AT+QGPSEND") + + if b'+QGPSCFG: "outport",usbnmea' not in (at_cmd('AT+QGPSCFG="outport"') or b""): + print("configure outport ...") + at_cmd('AT+QGPSCFG="outport","usbnmea"') # usbnmea = /dev/ttyUSB1 + + if b'+QGPSCFG: "gnssrawdata",3,0' not in (at_cmd('AT+QGPSCFG="gnssrawdata"') or b""): + print("configure gnssrawdata ...") + # AT+QGPSCFG="gnssrawdata",,' + # values: + # 0x01 = GPS + # 0x02 = GLONASS + # 0x04 = BEIDOU + # 0x08 = GALILEO + # 0x10 = QZSS + # values: + # 0 = NMEA port + # 1 = AT port + at_cmd('AT+QGPSCFG="gnssrawdata",3,0') # enable all constellations, output data to NMEA port + print("rebooting ...") + at_cmd('AT+CFUN=1,1') + print("re-run this script when it is back up") + sys.exit(2) + + print("starting location tracking ...") + at_cmd("AT+QGPS=1") + + process_nmea_port_messages() + +if __name__ == "__main__": + main() diff --git a/system/qcomgpsd/qcomgpsd.py b/openpilot/system/qcomgpsd/qcomgpsd.py similarity index 81% rename from system/qcomgpsd/qcomgpsd.py rename to openpilot/system/qcomgpsd/qcomgpsd.py index 3a9e3585ba..4e52154419 100755 --- a/system/qcomgpsd/qcomgpsd.py +++ b/openpilot/system/qcomgpsd/qcomgpsd.py @@ -1,24 +1,22 @@ #!/usr/bin/env python3 +import fcntl import os import sys import signal import itertools import math import time -import requests -import shutil -import subprocess import datetime -from multiprocessing import Process, Event from typing import NoReturn from struct import unpack_from, calcsize, pack -from cereal import log -import cereal.messaging as messaging +from openpilot.cereal import log +import openpilot.cereal.messaging as messaging from openpilot.common.gpio import gpio_init, gpio_set -from openpilot.common.retry import retry +from openpilot.common.utils import retry from openpilot.common.time_helpers import system_time_valid -from openpilot.system.hardware.tici.pins import GPIO +from openpilot.common.hardware.tici.pins import GPIO +from openpilot.common.serial import Serial from openpilot.common.swaglog import cloudlog from openpilot.system.qcomgpsd.modemdiag import ModemDiag, DIAG_LOG_F, setup_logs, send_recv from openpilot.system.qcomgpsd.structs import (dict_unpacker, position_report, relist, @@ -30,9 +28,6 @@ from openpilot.system.qcomgpsd.structs import (dict_unpacker, position_report, r LOG_GNSS_OEMDRE_SVPOLY_REPORT) DEBUG = int(os.getenv("DEBUG", "0"))==1 -ASSIST_DATA_FILE = '/tmp/xtra3grc.bin' -ASSIST_DATA_FILE_DOWNLOAD = ASSIST_DATA_FILE + '.download' -ASSISTANCE_URL = 'http://xtrapath3.izatcloud.net/xtra3grc.bin' LOG_TYPES = [ LOG_GNSS_GPS_MEASUREMENT_REPORT, @@ -90,55 +85,33 @@ measurementStatusGlonassFields = { def try_setup_logs(diag, logs): return setup_logs(diag, logs) -@retry(attempts=3, delay=1.0) -def at_cmd(cmd: str) -> str | None: - return subprocess.check_output(f"mmcli -m any --timeout 30 --command='{cmd}'", shell=True, encoding='utf8') +AT_PORT = "/dev/modem_at0" +AT_LOCK = "/dev/shm/modem.lock" # shared with modem.py and LPA + +@retry(attempts=5, delay=1.0) +def at_cmd(cmd: str) -> str: + with os.fdopen(os.open(AT_LOCK, os.O_CREAT | os.O_RDWR, 0o666), "r+") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + with Serial(AT_PORT, baudrate=115200, timeout=5) as ser: + ser.reset_input_buffer() + ser.write(f"{cmd}\r".encode()) + lines = [] + while True: + line = ser.readline() + if not line: + raise RuntimeError(f"AT command timeout: {cmd}") + line = line.decode('utf-8', errors='replace').strip() + if line in ("OK", "ERROR") or line.startswith("+CME ERROR"): + break + if line and line != cmd: + lines.append(line) + return '\n'.join(lines) def gps_enabled() -> bool: return "QGPS: 1" in at_cmd("AT+QGPS?") -def download_assistance(): - try: - response = requests.get(ASSISTANCE_URL, timeout=5, stream=True) - - with open(ASSIST_DATA_FILE_DOWNLOAD, 'wb') as fp: - for chunk in response.iter_content(chunk_size=8192): - fp.write(chunk) - if fp.tell() > 1e5: - cloudlog.error("Qcom assistance data larger than expected") - return - - os.rename(ASSIST_DATA_FILE_DOWNLOAD, ASSIST_DATA_FILE) - - except requests.exceptions.RequestException: - cloudlog.exception("Failed to download assistance file") - return - -def downloader_loop(event): - if os.path.exists(ASSIST_DATA_FILE): - os.remove(ASSIST_DATA_FILE) - - alt_path = os.getenv("QCOM_ALT_ASSISTANCE_PATH", None) - if alt_path is not None and os.path.exists(alt_path): - shutil.copyfile(alt_path, ASSIST_DATA_FILE) - - try: - while not os.path.exists(ASSIST_DATA_FILE) and not event.is_set(): - download_assistance() - event.wait(timeout=10) - except KeyboardInterrupt: - pass - -@retry(attempts=5, delay=0.2, ignore_failure=True) -def inject_assistance(): - cmd = f"mmcli -m any --timeout 30 --location-inject-assistance-data={ASSIST_DATA_FILE}" - subprocess.check_output(cmd, stderr=subprocess.PIPE, shell=True) - cloudlog.info("successfully loaded assistance data") - @retry(attempts=5, delay=1.0) -def setup_quectel(diag: ModemDiag) -> bool: - ret = False - +def setup_quectel(diag: ModemDiag): # enable OEMDRE in the NV # TODO: it has to reboot for this to take effect DIAG_NV_READ_F = 38 @@ -152,26 +125,11 @@ def setup_quectel(diag: ModemDiag) -> bool: if gps_enabled(): at_cmd("AT+QGPSEND") - if "GPS_COLD_START" in os.environ: - # deletes all assistance - at_cmd("AT+QGPSDEL=0") - else: - # allow module to perform hot start - at_cmd("AT+QGPSDEL=1") - # disable DPO power savings for more accuracy at_cmd("AT+QGPSCFG=\"dpoenable\",0") # don't automatically turn on GNSS on powerup at_cmd("AT+QGPSCFG=\"autogps\",0") - # Do internet assistance - at_cmd("AT+QGPSXTRA=1") - at_cmd("AT+QGPSSUPLURL=\"NULL\"") - if os.path.exists(ASSIST_DATA_FILE): - ret = True - inject_assistance() - os.remove(ASSIST_DATA_FILE) - #at_cmd("AT+QGPSXTRADATA?") if system_time_valid(): time_str = datetime.datetime.now(datetime.UTC).replace(tzinfo=None).strftime("%Y/%m/%d,%H:%M:%S") at_cmd(f"AT+QGPSXTRATIME=0,\"{time_str}\",1,1,1000") @@ -198,7 +156,6 @@ def setup_quectel(diag: ModemDiag) -> bool: 0,0 )) - return ret def teardown_quectel(diag): at_cmd("AT+QGPSCFG=\"outport\",\"none\"") @@ -207,13 +164,19 @@ def teardown_quectel(diag): try_setup_logs(diag, []) -def wait_for_modem(cmd="AT+QGPS?"): +def wait_for_modem(): cloudlog.warning("waiting for modem to come up") + while not os.path.exists(AT_PORT): + time.sleep(0.5) + # wait until the modem GNSS subsystem responds while True: - ret = subprocess.call(f"mmcli -m any --timeout 10 --command=\"{cmd}\"", stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, shell=True) - if ret == 0: - return - time.sleep(0.1) + try: + resp = at_cmd("AT+QGPS?") + if "+QGPS:" in resp: + return + except Exception: + pass + time.sleep(0.5) def main() -> NoReturn: @@ -233,9 +196,6 @@ def main() -> NoReturn: wait_for_modem() - stop_download_event = Event() - assist_fetch_proc = Process(target=downloader_loop, args=(stop_download_event,)) - assist_fetch_proc.start() def cleanup(sig, frame): cloudlog.warning("caught sig disabling quectel gps") @@ -246,18 +206,13 @@ def main() -> NoReturn: except NameError: cloudlog.warning('quectel not yet setup') - stop_download_event.set() - assist_fetch_proc.kill() - assist_fetch_proc.join() - sys.exit(0) signal.signal(signal.SIGINT, cleanup) signal.signal(signal.SIGTERM, cleanup) # connect to modem diag = ModemDiag() - r = setup_quectel(diag) - want_assistance = not r + setup_quectel(diag) cloudlog.warning("quectel setup done") gpio_init(GPIO.GNSS_PWR_EN, True) gpio_set(GPIO.GNSS_PWR_EN, True) @@ -265,10 +220,6 @@ def main() -> NoReturn: pm = messaging.PubMaster(['qcomGnss', 'gpsLocation']) while 1: - if os.path.exists(ASSIST_DATA_FILE) and want_assistance: - setup_quectel(diag) - want_assistance = False - opcode, payload = diag.recv() if opcode != DIAG_LOG_F: cloudlog.error(f"Unhandled opcode: {opcode}") @@ -286,7 +237,7 @@ def main() -> NoReturn: continue if DEBUG: - print(f"{time.time():.4f}: got log: {log_type} len {len(log_payload)}") + print(f"{time.time():.4f}: got log: {log_type} len {len(log_payload)}") # noqa: TID251 if log_type == LOG_GNSS_OEMDRE_MEASUREMENT_REPORT: msg = messaging.new_message('qcomGnss', valid=True) @@ -335,6 +286,9 @@ def main() -> NoReturn: report = unpack_position(log_payload) if report["u_PosSource"] != 2: continue + # uint16_t max is an invalid sentinel value from the modem + if report['w_GpsWeekNumber'] >= 0xFFFF: + continue vNED = [report["q_FltVelEnuMps[1]"], report["q_FltVelEnuMps[0]"], -report["q_FltVelEnuMps[2]"]] vNEDsigma = [report["q_FltVelSigmaMps[1]"], report["q_FltVelSigmaMps[0]"], -report["q_FltVelSigmaMps[2]"]] @@ -358,9 +312,6 @@ def main() -> NoReturn: gps.speedAccuracy = math.sqrt(sum([x**2 for x in vNEDsigma])) # quectel gps verticalAccuracy is clipped to 500, set invalid if so gps.hasFix = gps.verticalAccuracy != 500 - if gps.hasFix: - want_assistance = False - stop_download_event.set() pm.send('gpsLocation', msg) elif log_type == LOG_GNSS_OEMDRE_SVPOLY_REPORT: diff --git a/system/qcomgpsd/structs.py b/openpilot/system/qcomgpsd/structs.py similarity index 100% rename from system/qcomgpsd/structs.py rename to openpilot/system/qcomgpsd/structs.py diff --git a/tools/replay/__init__.py b/openpilot/system/sensord/__init__.py similarity index 100% rename from tools/replay/__init__.py rename to openpilot/system/sensord/__init__.py diff --git a/system/sensord/sensord.py b/openpilot/system/sensord/sensord.py similarity index 88% rename from system/sensord/sensord.py rename to openpilot/system/sensord/sensord.py index ed9d0ed415..6942b284df 100755 --- a/system/sensord/sensord.py +++ b/openpilot/system/sensord/sensord.py @@ -5,9 +5,9 @@ import ctypes import select import threading -import cereal.messaging as messaging -from cereal.services import SERVICE_LIST -from openpilot.common.util import sudo_write +import openpilot.cereal.messaging as messaging +from openpilot.cereal.services import SERVICE_LIST +from openpilot.common.utils import sudo_write from openpilot.common.realtime import config_realtime_process, Ratekeeper from openpilot.common.swaglog import cloudlog from openpilot.common.gpio import gpiochip_get_ro_value_fd, gpioevent_data @@ -16,13 +16,16 @@ from openpilot.system.sensord.sensors.i2c_sensor import Sensor from openpilot.system.sensord.sensors.lsm6ds3_accel import LSM6DS3_Accel from openpilot.system.sensord.sensors.lsm6ds3_gyro import LSM6DS3_Gyro from openpilot.system.sensord.sensors.lsm6ds3_temp import LSM6DS3_Temp -from openpilot.system.sensord.sensors.mmc5603nj_magn import MMC5603NJ_Magn I2C_BUS_IMU = 1 def interrupt_loop(sensors: list[tuple[Sensor, str, bool]], event) -> None: pm = messaging.PubMaster([service for sensor, service, interrupt in sensors if interrupt]) + # NOTE: the gyro and accelerometer share an IRQ due to the comma three + # routing only one GPIO from the LSM to the SOC, but comma 3X and four + # have two. if we want better timestamps in the future, we can use both. + # Requesting both edges as the data ready pulse from the lsm6ds sensor is # very short (75us) and is mostly detected as falling edge instead of rising. # So if it is detected as rising the following falling edge is skipped. @@ -95,9 +98,15 @@ def main() -> None: (LSM6DS3_Accel(I2C_BUS_IMU), "accelerometer", True), (LSM6DS3_Gyro(I2C_BUS_IMU), "gyroscope", True), (LSM6DS3_Temp(I2C_BUS_IMU), "temperatureSensor", False), - (MMC5603NJ_Magn(I2C_BUS_IMU), "magnetometer", False), ] + # Reset sensors + for sensor, _, _ in sensors_cfg: + try: + sensor.reset() + except Exception: + cloudlog.exception(f"Error initializing {sensor} sensor") + # Initialize sensors exit_event = threading.Event() threads = [ diff --git a/tools/replay/lib/__init__.py b/openpilot/system/sensord/sensors/__init__.py similarity index 100% rename from tools/replay/lib/__init__.py rename to openpilot/system/sensord/sensors/__init__.py diff --git a/system/sensord/sensors/i2c_sensor.py b/openpilot/system/sensord/sensors/i2c_sensor.py similarity index 90% rename from system/sensord/sensors/i2c_sensor.py rename to openpilot/system/sensord/sensors/i2c_sensor.py index 0e15a6622b..e0e8087258 100644 --- a/system/sensord/sensors/i2c_sensor.py +++ b/openpilot/system/sensord/sensors/i2c_sensor.py @@ -1,9 +1,10 @@ import time -import smbus2 import ctypes from collections.abc import Iterable -from cereal import log +from openpilot.cereal import log +from openpilot.common.i2c import SMBus + class Sensor: class SensorException(Exception): @@ -13,7 +14,7 @@ class Sensor: pass def __init__(self, bus: int) -> None: - self.bus = smbus2.SMBus(bus) + self.bus = SMBus(bus) self.source = log.SensorEventData.SensorSource.velodyne # unknown self.start_ts = 0. @@ -40,6 +41,11 @@ class Sensor: def device_address(self) -> int: raise NotImplementedError + def reset(self) -> None: + # optional. + # not part of init due to shared registers + pass + def init(self) -> None: raise NotImplementedError diff --git a/system/sensord/sensors/lsm6ds3_accel.py b/openpilot/system/sensord/sensors/lsm6ds3_accel.py similarity index 97% rename from system/sensord/sensors/lsm6ds3_accel.py rename to openpilot/system/sensord/sensors/lsm6ds3_accel.py index 2d788fcbe2..e47db15250 100644 --- a/system/sensord/sensors/lsm6ds3_accel.py +++ b/openpilot/system/sensord/sensors/lsm6ds3_accel.py @@ -1,7 +1,7 @@ import os import time -from cereal import log +from openpilot.cereal import log from openpilot.system.sensord.sensors.i2c_sensor import Sensor class LSM6DS3_Accel(Sensor): @@ -31,6 +31,10 @@ class LSM6DS3_Accel(Sensor): def device_address(self) -> int: return 0x6A + def reset(self): + self.write(0x12, 0x1) + time.sleep(0.1) + def init(self): chip_id = self.verify_chip_id(0x0F, [0x69, 0x6A]) if chip_id == 0x6A: @@ -73,13 +77,9 @@ class LSM6DS3_Accel(Sensor): event = log.SensorEventData.new_message() event.timestamp = ts - event.version = 1 - event.sensor = 1 # SENSOR_ACCELEROMETER - event.type = 1 # SENSOR_TYPE_ACCELEROMETER event.source = self.source a = event.init('acceleration') a.v = [y, -x, z] - a.status = 1 return event def shutdown(self) -> None: diff --git a/system/sensord/sensors/lsm6ds3_gyro.py b/openpilot/system/sensord/sensors/lsm6ds3_gyro.py similarity index 96% rename from system/sensord/sensors/lsm6ds3_gyro.py rename to openpilot/system/sensord/sensors/lsm6ds3_gyro.py index 68fd267df2..a82827ccb4 100644 --- a/system/sensord/sensors/lsm6ds3_gyro.py +++ b/openpilot/system/sensord/sensors/lsm6ds3_gyro.py @@ -2,7 +2,7 @@ import os import math import time -from cereal import log +from openpilot.cereal import log from openpilot.system.sensord.sensors.i2c_sensor import Sensor class LSM6DS3_Gyro(Sensor): @@ -29,6 +29,10 @@ class LSM6DS3_Gyro(Sensor): def device_address(self) -> int: return 0x6A + def reset(self): + self.write(0x12, 0x1) + time.sleep(0.1) + def init(self): chip_id = self.verify_chip_id(0x0F, [0x69, 0x6A]) if chip_id == 0x6A: @@ -69,13 +73,9 @@ class LSM6DS3_Gyro(Sensor): event = log.SensorEventData.new_message() event.timestamp = ts - event.version = 2 - event.sensor = 5 # SENSOR_GYRO_UNCALIBRATED - event.type = 16 # SENSOR_TYPE_GYROSCOPE_UNCALIBRATED event.source = self.source g = event.init('gyroUncalibrated') g.v = xyz - g.status = 1 return event def shutdown(self) -> None: diff --git a/system/sensord/sensors/lsm6ds3_temp.py b/openpilot/system/sensord/sensors/lsm6ds3_temp.py similarity index 84% rename from system/sensord/sensors/lsm6ds3_temp.py rename to openpilot/system/sensord/sensors/lsm6ds3_temp.py index 7d7b1c2ce1..0a5e85a2b9 100644 --- a/system/sensord/sensors/lsm6ds3_temp.py +++ b/openpilot/system/sensord/sensors/lsm6ds3_temp.py @@ -1,16 +1,16 @@ import time -from cereal import log +from openpilot.cereal import log from openpilot.system.sensord.sensors.i2c_sensor import Sensor # https://content.arduino.cc/assets/st_imu_lsm6ds3_datasheet.pdf class LSM6DS3_Temp(Sensor): @property def device_address(self) -> int: - return 0x6A # Default I2C address for LSM6DS3 + return 0x6A def _read_temperature(self) -> float: - scale = 16.0 if log.SensorEventData.SensorSource.lsm6ds3 else 256.0 + scale = 16.0 if self.source == log.SensorEventData.SensorSource.lsm6ds3 else 256.0 data = self.read(0x20, 2) return 25 + (self.parse_16bit(data[0], data[1]) / scale) @@ -23,7 +23,6 @@ class LSM6DS3_Temp(Sensor): def get_event(self, ts: int | None = None) -> log.SensorEventData: event = log.SensorEventData.new_message() - event.version = 1 event.timestamp = int(time.monotonic() * 1e9) event.source = self.source event.temperature = self._read_temperature() diff --git a/tools/sim/__init__.py b/openpilot/system/sensord/tests/__init__.py similarity index 100% rename from tools/sim/__init__.py rename to openpilot/system/sensord/tests/__init__.py diff --git a/openpilot/system/sensord/tests/test_sensord.py b/openpilot/system/sensord/tests/test_sensord.py new file mode 100644 index 0000000000..dc96886e4a --- /dev/null +++ b/openpilot/system/sensord/tests/test_sensord.py @@ -0,0 +1,185 @@ +import os +import subprocess +import pytest +import time +import numpy as np +from collections import namedtuple, defaultdict + +import openpilot.cereal.messaging as messaging +from openpilot.cereal.services import SERVICE_LIST +from openpilot.common.gpio import get_irqs_for_action +from openpilot.common.timeout import Timeout +from openpilot.system.manager.process_config import managed_processes + +SensorConfig = namedtuple('SensorConfig', ['service', 'measurement', 'sanity_min', 'sanity_max', 'std_max']) + +SENSOR_CONFIGS = ( + SensorConfig("accelerometer", "acceleration", 5, 15, 5), + SensorConfig("gyroscope", "gyroUncalibrated", 0, .3, 0.5), + SensorConfig("temperatureSensor", "temperature", 10, 60, 0.5), # looser for device density +) +SENSOR_CONFIGS_BY_MEASUREMENT = {config.measurement: config for config in SENSOR_CONFIGS} + +def get_irq_count(irq: str): + with open(f"/sys/kernel/irq/{irq}/per_cpu_count") as f: + per_cpu = map(int, f.read().split(",")) + return sum(per_cpu) + +def read_sensor_events(duration_sec): + socks = {} + poller = messaging.Poller() + events = defaultdict(list) + for config in SENSOR_CONFIGS: + socks[config.service] = messaging.sub_sock(config.service, poller=poller, timeout=100) + + # wait for sensors to come up + with Timeout(int(os.environ.get("SENSOR_WAIT", "5")), "sensors didn't come up"): + while len(poller.poll(250)) == 0: + pass + time.sleep(1) + for s in socks.values(): + messaging.drain_sock_raw(s) + + st = time.monotonic() + while time.monotonic() - st < duration_sec: + for s in socks: + events[s] += messaging.drain_sock(socks[s]) + time.sleep(0.1) + assert sum(map(len, events.values())) != 0, "No sensor events collected!" + + return {k: v for k, v in events.items() if len(v) > 0} + +def iter_measurements(events): + for msgs in events.values(): + for measurement in msgs: + yield measurement, getattr(measurement, measurement.which()) + +@pytest.mark.tici +class TestSensord: + @classmethod + def setup_class(cls): + # enable LSM self test + os.environ["LSM_SELF_TEST"] = "1" + + # read initial sensor values every test case can use + subprocess.run("pkill -f \\\\./sensord", shell=True) + try: + managed_processes["sensord"].start() + cls.sample_secs = int(os.getenv("SAMPLE_SECS", "10")) + cls.events = read_sensor_events(cls.sample_secs) + + # determine sensord's irq + cls.sensord_irq = get_irqs_for_action("sensord")[0] + finally: + # teardown won't run if this doesn't succeed + managed_processes["sensord"].stop() + + @classmethod + def teardown_class(cls): + managed_processes["sensord"].stop() + + def teardown_method(self): + managed_processes["sensord"].stop() + + def test_all_sensors_present(self): + missing = [config.service for config in SENSOR_CONFIGS if config.service not in self.events] + assert len(missing) == 0, f"missing sensors: {missing}" + + def test_lsm6ds3_timing(self, subtests): + # verify measurements are sampled and published at 104Hz + + sensor_t = {service: [] for service in ('accelerometer', 'gyroscope')} + + for service in sensor_t: + for measurement in self.events.get(service, []): + m = getattr(measurement, measurement.which()) + sensor_t[service].append(m.timestamp) + + for s, vals in sensor_t.items(): + with subtests.test(sensor=s): + assert len(vals) > 0 + tdiffs = np.diff(vals) / 1e6 # millis + + high_delay_diffs = list(filter(lambda d: d >= 20., tdiffs)) + assert len(high_delay_diffs) < 15, f"Too many large diffs: {high_delay_diffs}" + + avg_diff = sum(tdiffs)/len(tdiffs) + avg_freq = 1. / (avg_diff * 1e-3) + assert 92. < avg_freq < 114., f"avg freq {avg_freq}Hz wrong, expected 104Hz" + + stddev = np.std(tdiffs) + assert stddev < 2.0, f"Standard-dev to big {stddev}" + + def test_sensor_frequency(self, subtests): + for s, msgs in self.events.items(): + with subtests.test(sensor=s): + freq = len(msgs) / self.sample_secs + ef = SERVICE_LIST[s].frequency + assert ef*0.85 <= freq <= ef*1.15 + + def test_logmonottime_timestamp_diff(self): + # ensure diff between the message logMonotime and sample timestamp is small + + tdiffs = [] + for measurement, m in iter_measurements(self.events): + # check if gyro and accel timestamps are before logMonoTime + if str(m.source).startswith("lsm6ds3") and m.which() != 'temperature': + err_msg = f"Timestamp after logMonoTime: {m.timestamp} > {measurement.logMonoTime}" + assert m.timestamp < measurement.logMonoTime, err_msg + + # negative values might occur, as non interrupt packages created + # before the sensor is read + tdiffs.append(abs(measurement.logMonoTime - m.timestamp) / 1e6) + + # some sensors have a read procedure that will introduce an expected diff on the order of 20ms + high_delay_diffs = set(filter(lambda d: d >= 25., tdiffs)) + assert len(high_delay_diffs) < 20, f"Too many measurements published: {high_delay_diffs}" + + avg_diff = round(sum(tdiffs)/len(tdiffs), 4) + assert avg_diff < 4, f"Avg packet diff: {avg_diff:.1f}ms" + + def test_sensor_values(self): + sensor_values = defaultdict(list) + for _, m in iter_measurements(self.events): + key = (m.source.raw, m.which()) + values = getattr(m, m.which()) + + if hasattr(values, 'v'): + values = values.v + sensor_values[key].append(np.atleast_1d(values)) + + # Sanity check sensor values + for (sensor, stype), values in sensor_values.items(): + config = SENSOR_CONFIGS_BY_MEASUREMENT[stype] + + if config.measurement == 'temperature': + measurement_stat = np.mean(values) + else: + measurement_stat = np.mean(np.linalg.norm(values, axis=1)) + err_msg = f"Sensor '{sensor} {config.measurement}' failed sanity checks {measurement_stat} is not between {config.sanity_min} and {config.sanity_max}" + assert config.sanity_min <= measurement_stat <= config.sanity_max, err_msg + + std_dev = np.std(values, axis=0) + err_msg = f"Sensor '{sensor} {config.measurement}' failed std dev test {std_dev} is not under {config.std_max}" + assert np.all(std_dev <= config.std_max), err_msg + + def test_sensor_verify_no_interrupts_after_stop(self): + managed_processes["sensord"].start() + time.sleep(3) + + # read /proc/interrupts to verify interrupts are received + state_one = get_irq_count(self.sensord_irq) + time.sleep(1) + state_two = get_irq_count(self.sensord_irq) + + error_msg = f"no interrupts received after sensord start!\n{state_one} {state_two}" + assert state_one != state_two, error_msg + + managed_processes["sensord"].stop() + time.sleep(1) + + # read /proc/interrupts to verify no more interrupts are received + state_one = get_irq_count(self.sensord_irq) + time.sleep(1) + state_two = get_irq_count(self.sensord_irq) + assert state_one == state_two, "Interrupts received after sensord stop!" diff --git a/system/sentry.py b/openpilot/system/sentry.py similarity index 88% rename from system/sentry.py rename to openpilot/system/sentry.py index 2f918ebc49..dc078eb532 100644 --- a/system/sentry.py +++ b/openpilot/system/sentry.py @@ -8,10 +8,10 @@ from sentry_sdk.integrations.threading import ThreadingIntegration from openpilot.common.params import Params from openpilot.system.athena.registration import UNREGISTERED_DONGLE_ID -from openpilot.system.hardware import HARDWARE -from openpilot.system.hardware.hw import Paths +from openpilot.common.hardware import HARDWARE +from openpilot.common.hardware.hw import Paths from openpilot.common.swaglog import cloudlog -from openpilot.system.version import get_build_metadata, get_version +from openpilot.common.version import get_build_metadata, get_version from openpilot.sunnypilot.sunnylink.api import UNREGISTERED_SUNNYLINK_DONGLE_ID @@ -106,10 +106,10 @@ def set_user() -> None: def get_properties() -> tuple[str, str, str]: params = Params() - hardware_serial: str = params.get("HardwareSerial", encoding='utf-8') or "" - git_username: str = params.get("GithubUsername", encoding='utf-8') or "" - dongle_id: str = params.get("DongleId", encoding='utf-8') or f"{UNREGISTERED_DONGLE_ID}-{hardware_serial}" - sunnylink_dongle_id: str = params.get("SunnylinkDongleId", encoding='utf-8') or UNREGISTERED_SUNNYLINK_DONGLE_ID + hardware_serial: str = params.get("HardwareSerial") or "" + git_username: str = params.get("GithubUsername") or "" + dongle_id: str = params.get("DongleId") or f"{UNREGISTERED_DONGLE_ID}-{hardware_serial}" + sunnylink_dongle_id: str = params.get("SunnylinkDongleId") or UNREGISTERED_SUNNYLINK_DONGLE_ID return dongle_id, git_username, sunnylink_dongle_id diff --git a/tools/sim/bridge/__init__.py b/openpilot/system/tests/__init__.py similarity index 100% rename from tools/sim/bridge/__init__.py rename to openpilot/system/tests/__init__.py diff --git a/system/tests/test_logmessaged.py b/openpilot/system/tests/test_logmessaged.py similarity index 94% rename from system/tests/test_logmessaged.py rename to openpilot/system/tests/test_logmessaged.py index 9ccc8ef53b..e2637fb0e6 100644 --- a/system/tests/test_logmessaged.py +++ b/openpilot/system/tests/test_logmessaged.py @@ -2,9 +2,9 @@ import glob import os import time -import cereal.messaging as messaging +import openpilot.cereal.messaging as messaging from openpilot.system.manager.process_config import managed_processes -from openpilot.system.hardware.hw import Paths +from openpilot.common.hardware.hw import Paths from openpilot.common.swaglog import cloudlog, ipchandler diff --git a/system/timed.py b/openpilot/system/timed.py similarity index 89% rename from system/timed.py rename to openpilot/system/timed.py index b7131b04c0..0413f645e3 100755 --- a/system/timed.py +++ b/openpilot/system/timed.py @@ -4,8 +4,8 @@ import subprocess import time from typing import NoReturn -import cereal.messaging as messaging -from openpilot.common.time_helpers import min_date, system_time_valid +import openpilot.cereal.messaging as messaging +from openpilot.common.time_helpers import min_date, MAX_DATE, system_time_valid from openpilot.common.swaglog import cloudlog from openpilot.common.params import Params from openpilot.common.gps import get_gps_location_service @@ -52,7 +52,7 @@ def main() -> NoReturn: continue if not gps.hasFix: continue - if gps_time < min_date(): + if gps_time < min_date() or gps_time > MAX_DATE: continue set_time(gps_time) diff --git a/system/tombstoned.py b/openpilot/system/tombstoned.py similarity index 96% rename from system/tombstoned.py rename to openpilot/system/tombstoned.py index 5bcced2666..7741a923cd 100755 --- a/system/tombstoned.py +++ b/openpilot/system/tombstoned.py @@ -10,9 +10,9 @@ import glob from typing import NoReturn import openpilot.system.sentry as sentry -from openpilot.system.hardware.hw import Paths +from openpilot.common.hardware.hw import Paths from openpilot.common.swaglog import cloudlog -from openpilot.system.version import get_build_metadata +from openpilot.common.version import get_build_metadata MAX_SIZE = 1_000_000 * 100 # allow up to 100M MAX_TOMBSTONE_FN_LEN = 62 # 85 - 23 ("/crash/") @@ -104,7 +104,7 @@ def report_tombstone_apport(fn): # Try to find first entry in openpilot, fall back to first line for line in stacktrace_s: - if "at selfdrive/" in line: + if "at openpilot/selfdrive/" in line or "at selfdrive/" in line: crash_function = line found = True break diff --git a/openpilot/system/ubloxd/binary_struct.py b/openpilot/system/ubloxd/binary_struct.py new file mode 100644 index 0000000000..5bc05094f3 --- /dev/null +++ b/openpilot/system/ubloxd/binary_struct.py @@ -0,0 +1,280 @@ +""" +Binary struct parsing DSL. + +Defines a declarative schema for binary messages using dataclasses +and type annotations. +""" + +import struct +from enum import Enum +from dataclasses import dataclass, is_dataclass +from typing import Annotated, Any, TypeVar, get_args, get_origin + + +class FieldType: + """Base class for field type descriptors.""" + + +@dataclass(frozen=True) +class IntType(FieldType): + bits: int + signed: bool + big_endian: bool = False + +@dataclass(frozen=True) +class FloatType(FieldType): + bits: int + +@dataclass(frozen=True) +class BitsType(FieldType): + bits: int + +@dataclass(frozen=True) +class BytesType(FieldType): + size: int + +@dataclass(frozen=True) +class ArrayType(FieldType): + element_type: Any + count_field: str + +@dataclass(frozen=True) +class SwitchType(FieldType): + selector: str + cases: dict[Any, Any] + default: Any = None + +@dataclass(frozen=True) +class EnumType(FieldType): + base_type: FieldType + enum_cls: type[Enum] + +@dataclass(frozen=True) +class ConstType(FieldType): + base_type: FieldType + expected: Any + +@dataclass(frozen=True) +class SubstreamType(FieldType): + length_field: str + element_type: Any + +# Common types - little endian +u8 = IntType(8, False) +u16 = IntType(16, False) +u32 = IntType(32, False) +s8 = IntType(8, True) +s16 = IntType(16, True) +s32 = IntType(32, True) +f32 = FloatType(32) +f64 = FloatType(64) +# Big endian variants +u16be = IntType(16, False, big_endian=True) +u32be = IntType(32, False, big_endian=True) +s16be = IntType(16, True, big_endian=True) +s32be = IntType(32, True, big_endian=True) + + +def bits(n: int) -> BitsType: + """Create a bit-level field type.""" + return BitsType(n) + +def bytes_field(size: int) -> BytesType: + """Create a fixed-size bytes field.""" + return BytesType(size) + +def array(element_type: Any, count_field: str) -> ArrayType: + """Create an array/repeated field.""" + return ArrayType(element_type, count_field) + +def switch(selector: str, cases: dict[Any, Any], default: Any = None) -> SwitchType: + """Create a switch-on field.""" + return SwitchType(selector, cases, default) + +def enum(base_type: Any, enum_cls: type[Enum]) -> EnumType: + """Create an enum-wrapped field.""" + field_type = _field_type_from_spec(base_type) + if field_type is None: + raise TypeError(f"Unsupported field type: {base_type!r}") + return EnumType(field_type, enum_cls) + +def const(base_type: Any, expected: Any) -> ConstType: + """Create a constant-value field.""" + field_type = _field_type_from_spec(base_type) + if field_type is None: + raise TypeError(f"Unsupported field type: {base_type!r}") + return ConstType(field_type, expected) + +def substream(length_field: str, element_type: Any) -> SubstreamType: + """Parse a fixed-length substream using an inner schema.""" + return SubstreamType(length_field, element_type) + + +class BinaryReader: + def __init__(self, data: bytes): + self.data = data + self.pos = 0 + self.bit_pos = 0 # 0-7, position within current byte + + def _require(self, n: int) -> None: + if self.pos + n > len(self.data): + raise EOFError("Unexpected end of data") + + def _read_struct(self, fmt: str): + self._align_to_byte() + size = struct.calcsize(fmt) + self._require(size) + value = struct.unpack_from(fmt, self.data, self.pos)[0] + self.pos += size + return value + + def read_bytes(self, n: int) -> bytes: + self._align_to_byte() + self._require(n) + result = self.data[self.pos : self.pos + n] + self.pos += n + return result + + def read_bits_int_be(self, n: int) -> int: + result = 0 + bits_remaining = n + while bits_remaining > 0: + if self.pos >= len(self.data): + raise EOFError("Unexpected end of data while reading bits") + bits_in_byte = 8 - self.bit_pos + bits_to_read = min(bits_remaining, bits_in_byte) + byte_val = self.data[self.pos] + shift = bits_in_byte - bits_to_read + mask = (1 << bits_to_read) - 1 + extracted = (byte_val >> shift) & mask + result = (result << bits_to_read) | extracted + self.bit_pos += bits_to_read + bits_remaining -= bits_to_read + if self.bit_pos >= 8: + self.bit_pos = 0 + self.pos += 1 + return result + + def _align_to_byte(self) -> None: + if self.bit_pos > 0: + self.bit_pos = 0 + self.pos += 1 + + +T = TypeVar('T', bound='BinaryStruct') + + +class BinaryStruct: + """Base class for binary struct definitions.""" + + def __init_subclass__(cls, **kwargs) -> None: + super().__init_subclass__(**kwargs) + if cls is BinaryStruct: + return + if not is_dataclass(cls): + dataclass(init=False)(cls) + fields = list(getattr(cls, '__annotations__', {}).items()) + cls.__binary_fields__ = fields + + @classmethod + def _read(inner_cls, reader: BinaryReader): + obj = inner_cls.__new__(inner_cls) + for name, spec in inner_cls.__binary_fields__: + value = _parse_field(spec, reader, obj) + setattr(obj, name, value) + return obj + + cls._read = _read # ty: ignore[invalid-assignment] # installed dynamically for each subclass + + @classmethod + def from_bytes(cls: type[T], data: bytes) -> T: + """Parse struct from bytes.""" + reader = BinaryReader(data) + return cls._read(reader) + + @classmethod + def _read(cls: type[T], reader: BinaryReader) -> T: + """Override in subclasses to implement parsing.""" + raise NotImplementedError + + +def _resolve_path(obj: Any, path: str) -> Any: + cur = obj + for part in path.split('.'): + cur = getattr(cur, part) + return cur + +def _unwrap_annotated(spec: Any) -> tuple[Any, ...]: + if get_origin(spec) is Annotated: + return get_args(spec)[1:] + return () + +def _field_type_from_spec(spec: Any) -> FieldType | None: + if isinstance(spec, FieldType): + return spec + for item in _unwrap_annotated(spec): + if isinstance(item, FieldType): + return item + return None + + +def _int_format(field_type: IntType) -> str: + if field_type.bits == 8: + return 'b' if field_type.signed else 'B' + endian = '>' if field_type.big_endian else '<' + if field_type.bits == 16: + code = 'h' if field_type.signed else 'H' + elif field_type.bits == 32: + code = 'i' if field_type.signed else 'I' + else: + raise ValueError(f"Unsupported integer size: {field_type.bits}") + return f"{endian}{code}" + +def _float_format(field_type: FloatType) -> str: + if field_type.bits == 32: + return ' Any: + field_type = _field_type_from_spec(spec) + if field_type is not None: + spec = field_type + if isinstance(spec, ConstType): + value = _parse_field(spec.base_type, reader, obj) + if value != spec.expected: + raise ValueError(f"Invalid constant: expected {spec.expected!r}, got {value!r}") + return value + if isinstance(spec, EnumType): + raw = _parse_field(spec.base_type, reader, obj) + try: + return spec.enum_cls(raw) + except ValueError: + return raw + if isinstance(spec, SwitchType): + key = _resolve_path(obj, spec.selector) + target = spec.cases.get(key, spec.default) + if target is None: + return None + return _parse_field(target, reader, obj) + if isinstance(spec, ArrayType): + count = _resolve_path(obj, spec.count_field) + return [_parse_field(spec.element_type, reader, obj) for _ in range(int(count))] + if isinstance(spec, SubstreamType): + length = _resolve_path(obj, spec.length_field) + data = reader.read_bytes(int(length)) + sub_reader = BinaryReader(data) + return _parse_field(spec.element_type, sub_reader, obj) + if isinstance(spec, IntType): + return reader._read_struct(_int_format(spec)) + if isinstance(spec, FloatType): + return reader._read_struct(_float_format(spec)) + if isinstance(spec, BitsType): + value = reader.read_bits_int_be(spec.bits) + return bool(value) if spec.bits == 1 else value + if isinstance(spec, BytesType): + return reader.read_bytes(spec.size) + if isinstance(spec, type) and issubclass(spec, BinaryStruct): + return spec._read(reader) + raise TypeError(f"Unsupported field spec: {spec!r}") diff --git a/openpilot/system/ubloxd/glonass.py b/openpilot/system/ubloxd/glonass.py new file mode 100644 index 0000000000..144ccdde6e --- /dev/null +++ b/openpilot/system/ubloxd/glonass.py @@ -0,0 +1,156 @@ +""" +Parses GLONASS navigation strings per GLONASS ICD specification. +http://gauss.gge.unb.ca/GLONASS.ICD.pdf +https://www.unavco.org/help/glossary/docs/ICD_GLONASS_4.0_(1998)_en.pdf +""" + +from typing import Annotated + +from openpilot.system.ubloxd import binary_struct as bs + + +class Glonass(bs.BinaryStruct): + class String1(bs.BinaryStruct): + not_used: Annotated[int, bs.bits(2)] + p1: Annotated[int, bs.bits(2)] + t_k: Annotated[int, bs.bits(12)] + x_vel_sign: Annotated[bool, bs.bits(1)] + x_vel_value: Annotated[int, bs.bits(23)] + x_accel_sign: Annotated[bool, bs.bits(1)] + x_accel_value: Annotated[int, bs.bits(4)] + x_sign: Annotated[bool, bs.bits(1)] + x_value: Annotated[int, bs.bits(26)] + + @property + def x_vel(self) -> int: + """Computed x_vel from sign-magnitude representation.""" + return (self.x_vel_value * -1) if self.x_vel_sign else self.x_vel_value + + @property + def x_accel(self) -> int: + """Computed x_accel from sign-magnitude representation.""" + return (self.x_accel_value * -1) if self.x_accel_sign else self.x_accel_value + + @property + def x(self) -> int: + """Computed x from sign-magnitude representation.""" + return (self.x_value * -1) if self.x_sign else self.x_value + + class String2(bs.BinaryStruct): + b_n: Annotated[int, bs.bits(3)] + p2: Annotated[bool, bs.bits(1)] + t_b: Annotated[int, bs.bits(7)] + not_used: Annotated[int, bs.bits(5)] + y_vel_sign: Annotated[bool, bs.bits(1)] + y_vel_value: Annotated[int, bs.bits(23)] + y_accel_sign: Annotated[bool, bs.bits(1)] + y_accel_value: Annotated[int, bs.bits(4)] + y_sign: Annotated[bool, bs.bits(1)] + y_value: Annotated[int, bs.bits(26)] + + @property + def y_vel(self) -> int: + """Computed y_vel from sign-magnitude representation.""" + return (self.y_vel_value * -1) if self.y_vel_sign else self.y_vel_value + + @property + def y_accel(self) -> int: + """Computed y_accel from sign-magnitude representation.""" + return (self.y_accel_value * -1) if self.y_accel_sign else self.y_accel_value + + @property + def y(self) -> int: + """Computed y from sign-magnitude representation.""" + return (self.y_value * -1) if self.y_sign else self.y_value + + class String3(bs.BinaryStruct): + p3: Annotated[bool, bs.bits(1)] + gamma_n_sign: Annotated[bool, bs.bits(1)] + gamma_n_value: Annotated[int, bs.bits(10)] + not_used: Annotated[bool, bs.bits(1)] + p: Annotated[int, bs.bits(2)] + l_n: Annotated[bool, bs.bits(1)] + z_vel_sign: Annotated[bool, bs.bits(1)] + z_vel_value: Annotated[int, bs.bits(23)] + z_accel_sign: Annotated[bool, bs.bits(1)] + z_accel_value: Annotated[int, bs.bits(4)] + z_sign: Annotated[bool, bs.bits(1)] + z_value: Annotated[int, bs.bits(26)] + + @property + def gamma_n(self) -> int: + """Computed gamma_n from sign-magnitude representation.""" + return (self.gamma_n_value * -1) if self.gamma_n_sign else self.gamma_n_value + + @property + def z_vel(self) -> int: + """Computed z_vel from sign-magnitude representation.""" + return (self.z_vel_value * -1) if self.z_vel_sign else self.z_vel_value + + @property + def z_accel(self) -> int: + """Computed z_accel from sign-magnitude representation.""" + return (self.z_accel_value * -1) if self.z_accel_sign else self.z_accel_value + + @property + def z(self) -> int: + """Computed z from sign-magnitude representation.""" + return (self.z_value * -1) if self.z_sign else self.z_value + + class String4(bs.BinaryStruct): + tau_n_sign: Annotated[bool, bs.bits(1)] + tau_n_value: Annotated[int, bs.bits(21)] + delta_tau_n_sign: Annotated[bool, bs.bits(1)] + delta_tau_n_value: Annotated[int, bs.bits(4)] + e_n: Annotated[int, bs.bits(5)] + not_used_1: Annotated[int, bs.bits(14)] + p4: Annotated[bool, bs.bits(1)] + f_t: Annotated[int, bs.bits(4)] + not_used_2: Annotated[int, bs.bits(3)] + n_t: Annotated[int, bs.bits(11)] + n: Annotated[int, bs.bits(5)] + m: Annotated[int, bs.bits(2)] + + @property + def tau_n(self) -> int: + """Computed tau_n from sign-magnitude representation.""" + return (self.tau_n_value * -1) if self.tau_n_sign else self.tau_n_value + + @property + def delta_tau_n(self) -> int: + """Computed delta_tau_n from sign-magnitude representation.""" + return (self.delta_tau_n_value * -1) if self.delta_tau_n_sign else self.delta_tau_n_value + + class String5(bs.BinaryStruct): + n_a: Annotated[int, bs.bits(11)] + tau_c: Annotated[int, bs.bits(32)] + not_used: Annotated[bool, bs.bits(1)] + n_4: Annotated[int, bs.bits(5)] + tau_gps: Annotated[int, bs.bits(22)] + l_n: Annotated[bool, bs.bits(1)] + + class StringNonImmediate(bs.BinaryStruct): + data_1: Annotated[int, bs.bits(64)] + data_2: Annotated[int, bs.bits(8)] + + idle_chip: Annotated[bool, bs.bits(1)] + string_number: Annotated[int, bs.bits(4)] + data: Annotated[ + object, + bs.switch( + 'string_number', + { + 1: String1, + 2: String2, + 3: String3, + 4: String4, + 5: String5, + }, + default=StringNonImmediate, + ), + ] + hamming_code: Annotated[int, bs.bits(8)] + pad_1: Annotated[int, bs.bits(11)] + superframe_number: Annotated[int, bs.bits(16)] + pad_2: Annotated[int, bs.bits(8)] + frame_number: Annotated[int, bs.bits(8)] diff --git a/openpilot/system/ubloxd/gps.py b/openpilot/system/ubloxd/gps.py new file mode 100644 index 0000000000..1c0833bd92 --- /dev/null +++ b/openpilot/system/ubloxd/gps.py @@ -0,0 +1,116 @@ +""" +Parses GPS navigation subframes per IS-GPS-200E specification. +https://www.gps.gov/technical/icwg/IS-GPS-200E.pdf +""" + +from typing import Annotated + +from openpilot.system.ubloxd import binary_struct as bs + + +class Gps(bs.BinaryStruct): + class Tlm(bs.BinaryStruct): + preamble: Annotated[bytes, bs.const(bs.bytes_field(1), b"\x8b")] + tlm: Annotated[int, bs.bits(14)] + integrity_status: Annotated[bool, bs.bits(1)] + reserved: Annotated[bool, bs.bits(1)] + + class How(bs.BinaryStruct): + tow_count: Annotated[int, bs.bits(17)] + alert: Annotated[bool, bs.bits(1)] + anti_spoof: Annotated[bool, bs.bits(1)] + subframe_id: Annotated[int, bs.bits(3)] + reserved: Annotated[int, bs.bits(2)] + + class Subframe1(bs.BinaryStruct): + week_no: Annotated[int, bs.bits(10)] + code: Annotated[int, bs.bits(2)] + sv_accuracy: Annotated[int, bs.bits(4)] + sv_health: Annotated[int, bs.bits(6)] + iodc_msb: Annotated[int, bs.bits(2)] + l2_p_data_flag: Annotated[bool, bs.bits(1)] + reserved1: Annotated[int, bs.bits(23)] + reserved2: Annotated[int, bs.bits(24)] + reserved3: Annotated[int, bs.bits(24)] + reserved4: Annotated[int, bs.bits(16)] + t_gd: Annotated[int, bs.s8] + iodc_lsb: Annotated[int, bs.u8] + t_oc: Annotated[int, bs.u16be] + af_2: Annotated[int, bs.s8] + af_1: Annotated[int, bs.s16be] + af_0_sign: Annotated[bool, bs.bits(1)] + af_0_value: Annotated[int, bs.bits(21)] + reserved5: Annotated[int, bs.bits(2)] + + @property + def af_0(self) -> int: + """Computed af_0 from sign-magnitude representation.""" + return (self.af_0_value - (1 << 21)) if self.af_0_sign else self.af_0_value + + class Subframe2(bs.BinaryStruct): + iode: Annotated[int, bs.u8] + c_rs: Annotated[int, bs.s16be] + delta_n: Annotated[int, bs.s16be] + m_0: Annotated[int, bs.s32be] + c_uc: Annotated[int, bs.s16be] + e: Annotated[int, bs.s32be] + c_us: Annotated[int, bs.s16be] + sqrt_a: Annotated[int, bs.u32be] + t_oe: Annotated[int, bs.u16be] + fit_interval_flag: Annotated[bool, bs.bits(1)] + aoda: Annotated[int, bs.bits(5)] + reserved: Annotated[int, bs.bits(2)] + + class Subframe3(bs.BinaryStruct): + c_ic: Annotated[int, bs.s16be] + omega_0: Annotated[int, bs.s32be] + c_is: Annotated[int, bs.s16be] + i_0: Annotated[int, bs.s32be] + c_rc: Annotated[int, bs.s16be] + omega: Annotated[int, bs.s32be] + omega_dot_sign: Annotated[bool, bs.bits(1)] + omega_dot_value: Annotated[int, bs.bits(23)] + iode: Annotated[int, bs.u8] + idot_sign: Annotated[bool, bs.bits(1)] + idot_value: Annotated[int, bs.bits(13)] + reserved: Annotated[int, bs.bits(2)] + + @property + def omega_dot(self) -> int: + """Computed omega_dot from sign-magnitude representation.""" + return (self.omega_dot_value - (1 << 23)) if self.omega_dot_sign else self.omega_dot_value + + @property + def idot(self) -> int: + """Computed idot from sign-magnitude representation.""" + return (self.idot_value - (1 << 13)) if self.idot_sign else self.idot_value + + class Subframe4(bs.BinaryStruct): + class IonosphereData(bs.BinaryStruct): + a0: Annotated[int, bs.s8] + a1: Annotated[int, bs.s8] + a2: Annotated[int, bs.s8] + a3: Annotated[int, bs.s8] + b0: Annotated[int, bs.s8] + b1: Annotated[int, bs.s8] + b2: Annotated[int, bs.s8] + b3: Annotated[int, bs.s8] + + data_id: Annotated[int, bs.bits(2)] + page_id: Annotated[int, bs.bits(6)] + body: Annotated[object, bs.switch('page_id', {56: IonosphereData})] + + tlm: Tlm + how: How + body: Annotated[ + object, + bs.switch( + 'how.subframe_id', + { + 1: Subframe1, + 2: Subframe2, + 3: Subframe3, + 4: Subframe4, + }, + ), + ] diff --git a/system/ubloxd/pigeond.py b/openpilot/system/ubloxd/pigeond.py similarity index 89% rename from system/ubloxd/pigeond.py rename to openpilot/system/ubloxd/pigeond.py index 2194a4b9d2..9891285465 100755 --- a/system/ubloxd/pigeond.py +++ b/openpilot/system/ubloxd/pigeond.py @@ -2,19 +2,19 @@ import sys import time import signal -import serial import struct import requests import urllib.parse from datetime import datetime, UTC -from cereal import messaging +from openpilot.cereal import messaging from openpilot.common.time_helpers import system_time_valid from openpilot.common.params import Params +from openpilot.common.serial import Serial from openpilot.common.swaglog import cloudlog -from openpilot.system.hardware import TICI +from openpilot.common.hardware import TICI from openpilot.common.gpio import gpio_init, gpio_set -from openpilot.system.hardware.tici.pins import GPIO +from openpilot.common.hardware.tici.pins import GPIO UBLOX_TTY = "/dev/ttyHS0" @@ -41,7 +41,7 @@ def add_ubx_checksum(msg: bytes) -> bytes: B = (B + A) % 256 return msg + bytes([A, B]) -def get_assistnow_messages(token: bytes) -> list[bytes]: +def get_assistnow_messages(token: str) -> list[bytes]: # make request # TODO: implement adding the last known location r = requests.get("https://online-live2.services.u-blox.com/GetOnlineData.ashx", params=urllib.parse.urlencode({ @@ -64,7 +64,7 @@ def get_assistnow_messages(token: bytes) -> list[bytes]: class TTYPigeon: def __init__(self): - self.tty = serial.VTIMESerial(UBLOX_TTY, baudrate=9600, timeout=0) + self.tty = Serial(UBLOX_TTY, baudrate=9600, timeout=0) def send(self, dat: bytes) -> None: self.tty.write(dat) @@ -136,6 +136,17 @@ class TTYPigeon: return True return False +def save_almanac(pigeon: TTYPigeon) -> None: + # store almanac in flash + pigeon.send(b"\xB5\x62\x09\x14\x04\x00\x00\x00\x00\x00\x21\xEC") + try: + if pigeon.wait_for_ack(ack=UBLOX_SOS_ACK, nack=UBLOX_SOS_NACK): + cloudlog.info("Done storing almanac") + else: + cloudlog.error("Error storing almanac") + except TimeoutError: + pass + def init_baudrate(pigeon: TTYPigeon): # ublox default setting on startup is 9600 baudrate pigeon.set_baud(9600) @@ -146,7 +157,7 @@ def init_baudrate(pigeon: TTYPigeon): pigeon.set_baud(460800) -def initialize_pigeon(pigeon: TTYPigeon) -> bool: +def init_pigeon(pigeon: TTYPigeon) -> bool: # try initializing a few times for _ in range(10): try: @@ -239,32 +250,17 @@ def initialize_pigeon(pigeon: TTYPigeon) -> bool: return True def deinitialize_and_exit(pigeon: TTYPigeon | None): - cloudlog.warning("Storing almanac in ublox flash") - if pigeon is not None: # controlled GNSS stop pigeon.send(b"\xB5\x62\x06\x04\x04\x00\x00\x00\x08\x00\x16\x74") - # store almanac in flash - pigeon.send(b"\xB5\x62\x09\x14\x04\x00\x00\x00\x00\x00\x21\xEC") - try: - if pigeon.wait_for_ack(ack=UBLOX_SOS_ACK, nack=UBLOX_SOS_NACK): - cloudlog.warning("Done storing almanac") - else: - cloudlog.error("Error storing almanac") - except TimeoutError: - pass - # turn off power and exit cleanly set_power(False) sys.exit(0) -def create_pigeon() -> tuple[TTYPigeon, messaging.PubMaster]: - pigeon = None - +def init(pigeon: TTYPigeon) -> None: # register exit handler signal.signal(signal.SIGINT, lambda sig, frame: deinitialize_and_exit(pigeon)) - pm = messaging.PubMaster(['ubloxRaw']) # power cycle ublox set_power(False) @@ -272,28 +268,34 @@ def create_pigeon() -> tuple[TTYPigeon, messaging.PubMaster]: set_power(True) time.sleep(0.5) - pigeon = TTYPigeon() - return pigeon, pm + init_baudrate(pigeon) + init_pigeon(pigeon) -def run_receiving(pigeon: TTYPigeon, pm: messaging.PubMaster, duration: int = 0): +def run_receiving(duration: int = 0): + pm = messaging.PubMaster(['ubloxRaw']) + + pigeon = TTYPigeon() + init(pigeon) start_time = time.monotonic() - def end_condition(): - return True if duration == 0 else time.monotonic() - start_time < duration - - while end_condition(): + last_almanac_save = time.monotonic() + while (duration == 0) or (time.monotonic() - start_time < duration): dat = pigeon.receive() if len(dat) > 0: if dat[0] == 0x00: cloudlog.warning("received invalid data from ublox, re-initing!") - init_baudrate(pigeon) - initialize_pigeon(pigeon) + init(pigeon) continue # send out to socket msg = messaging.new_message('ubloxRaw', len(dat), valid=True) msg.ubloxRaw = dat[:] pm.send('ubloxRaw', msg) + + # save almanac every 5 minutes + if (time.monotonic() - last_almanac_save) > 60*5: + save_almanac(pigeon) + last_almanac_save = time.monotonic() else: # prevent locking up a CPU core if ublox disconnects time.sleep(0.001) @@ -301,13 +303,7 @@ def run_receiving(pigeon: TTYPigeon, pm: messaging.PubMaster, duration: int = 0) def main(): assert TICI, "unsupported hardware for pigeond" - - pigeon, pm = create_pigeon() - init_baudrate(pigeon) - initialize_pigeon(pigeon) - - # start receiving data - run_receiving(pigeon, pm) + run_receiving() if __name__ == "__main__": main() diff --git a/system/ubloxd/tests/test_pigeond.py b/openpilot/system/ubloxd/tests/test_pigeond.py similarity index 90% rename from system/ubloxd/tests/test_pigeond.py rename to openpilot/system/ubloxd/tests/test_pigeond.py index 202820e412..b894ed718b 100644 --- a/system/ubloxd/tests/test_pigeond.py +++ b/openpilot/system/ubloxd/tests/test_pigeond.py @@ -1,12 +1,12 @@ import pytest import time -import cereal.messaging as messaging -from cereal.services import SERVICE_LIST +import openpilot.cereal.messaging as messaging +from openpilot.cereal.services import SERVICE_LIST from openpilot.common.gpio import gpio_read from openpilot.selfdrive.test.helpers import with_processes from openpilot.system.manager.process_config import managed_processes -from openpilot.system.hardware.tici.pins import GPIO +from openpilot.common.hardware.tici.pins import GPIO # TODO: test TTFF when we have good A-GNSS diff --git a/openpilot/system/ubloxd/ubloxd.py b/openpilot/system/ubloxd/ubloxd.py new file mode 100755 index 0000000000..3b32f70657 --- /dev/null +++ b/openpilot/system/ubloxd/ubloxd.py @@ -0,0 +1,534 @@ +#!/usr/bin/env python3 +import math +import capnp +import calendar +import numpy as np +from collections import defaultdict +from dataclasses import dataclass + +from openpilot.cereal import log +from openpilot.cereal import messaging +from openpilot.system.ubloxd.ubx import Ubx +from openpilot.system.ubloxd.gps import Gps +from openpilot.system.ubloxd.glonass import Glonass + + +SECS_IN_MIN = 60 +SECS_IN_HR = 60 * SECS_IN_MIN +SECS_IN_DAY = 24 * SECS_IN_HR +SECS_IN_WEEK = 7 * SECS_IN_DAY + + +class UbxFramer: + PREAMBLE1 = 0xB5 + PREAMBLE2 = 0x62 + HEADER_SIZE = 6 + CHECKSUM_SIZE = 2 + + def __init__(self) -> None: + self.buf = bytearray() + self.last_log_time = 0.0 + + def reset(self) -> None: + self.buf.clear() + + @staticmethod + def _checksum_ok(frame: bytes) -> bool: + ck_a = 0 + ck_b = 0 + for b in frame[2:-2]: + ck_a = (ck_a + b) & 0xFF + ck_b = (ck_b + ck_a) & 0xFF + return ck_a == frame[-2] and ck_b == frame[-1] + + def add_data(self, log_time: float, incoming: bytes) -> list[bytes]: + self.last_log_time = log_time + out: list[bytes] = [] + if not incoming: + return out + self.buf += incoming + + while True: + # find preamble + if len(self.buf) < 2: + break + start = self.buf.find(b"\xb5\x62") + if start < 0: + # no preamble in buffer + self.buf.clear() + break + if start > 0: + # drop garbage before preamble + self.buf = self.buf[start:] + + if len(self.buf) < self.HEADER_SIZE: + break + + length_le = int.from_bytes(self.buf[4:6], 'little', signed=False) + total_len = self.HEADER_SIZE + length_le + self.CHECKSUM_SIZE + if len(self.buf) < total_len: + break + + candidate = bytes(self.buf[:total_len]) + if self._checksum_ok(candidate): + out.append(candidate) + # consume this frame + self.buf = self.buf[total_len:] + else: + # drop first byte and retry + self.buf = self.buf[1:] + + return out + + +def _bit(b: int, shift: int) -> bool: + return (b & (1 << shift)) != 0 + + +@dataclass +class EphemerisCaches: + gps_subframes: defaultdict[int, dict[int, bytes]] + glonass_strings: defaultdict[int, dict[int, bytes]] + glonass_string_times: defaultdict[int, dict[int, float]] + glonass_string_superframes: defaultdict[int, dict[int, int]] + + +class UbloxMsgParser: + gpsPi = 3.1415926535898 + + # user range accuracy in meters + glonass_URA_lookup: dict[int, float] = { + 0: 1, + 1: 2, + 2: 2.5, + 3: 4, + 4: 5, + 5: 7, + 6: 10, + 7: 12, + 8: 14, + 9: 16, + 10: 32, + 11: 64, + 12: 128, + 13: 256, + 14: 512, + 15: 1024, + } + + def __init__(self) -> None: + self.framer = UbxFramer() + self.caches = EphemerisCaches( + gps_subframes=defaultdict(dict), + glonass_strings=defaultdict(dict), + glonass_string_times=defaultdict(dict), + glonass_string_superframes=defaultdict(dict), + ) + + # Message generation entry point + def parse_frame(self, frame: bytes) -> tuple[str, capnp.lib.capnp._DynamicStructBuilder] | None: + # Quick header parse + msg_type = int.from_bytes(frame[2:4], 'big') + payload = frame[6:-2] + if msg_type == 0x0107: + body = Ubx.NavPvt.from_bytes(payload) + return self._gen_nav_pvt(body) + if msg_type == 0x0213: + # Manually parse RXM-SFRBX to avoid EOF on some frames + if len(payload) < 8: + return None + gnss_id = payload[0] + sv_id = payload[1] + freq_id = payload[3] + num_words = payload[4] + exp = 8 + 4 * num_words + if exp != len(payload): + return None + words: list[int] = [] + off = 8 + for _ in range(num_words): + words.append(int.from_bytes(payload[off : off + 4], 'little')) + off += 4 + + class _SfrbxView: + def __init__(self, gid: int, sid: int, fid: int, body: list[int]): + self.gnss_id = Ubx.GnssType(gid) + self.sv_id = sid + self.freq_id = fid + self.body = body + + view = _SfrbxView(gnss_id, sv_id, freq_id, words) + return self._gen_rxm_sfrbx(view) + if msg_type == 0x0215: + body = Ubx.RxmRawx.from_bytes(payload) + return self._gen_rxm_rawx(body) + if msg_type == 0x0A09: + body = Ubx.MonHw.from_bytes(payload) + return self._gen_mon_hw(body) + if msg_type == 0x0A0B: + body = Ubx.MonHw2.from_bytes(payload) + return self._gen_mon_hw2(body) + if msg_type == 0x0135: + body = Ubx.NavSat.from_bytes(payload) + return self._gen_nav_sat(body) + return None + + # NAV-PVT -> gpsLocationExternal + def _gen_nav_pvt(self, msg: Ubx.NavPvt) -> tuple[str, capnp.lib.capnp._DynamicStructBuilder]: + dat = messaging.new_message('gpsLocationExternal', valid=True) + gps = dat.gpsLocationExternal + gps.source = log.GpsLocationData.SensorSource.ublox + gps.flags = msg.flags + gps.hasFix = (msg.flags % 2) == 1 + gps.latitude = msg.lat * 1e-07 + gps.longitude = msg.lon * 1e-07 + gps.altitude = msg.height * 1e-03 + gps.speed = msg.g_speed * 1e-03 + gps.bearingDeg = msg.head_mot * 1e-5 + gps.horizontalAccuracy = msg.h_acc * 1e-03 + gps.satelliteCount = msg.num_sv + + # build UTC timestamp millis (NAV-PVT is in UTC) + # tolerate invalid or unset date values like C++ timegm + try: + utc_tt = calendar.timegm((msg.year, msg.month, msg.day, msg.hour, msg.min, msg.sec, 0, 0, 0)) + except Exception: + utc_tt = 0 + gps.unixTimestampMillis = int(utc_tt * 1e3 + (msg.nano * 1e-6)) + + # match C++ float32 rounding semantics exactly + gps.vNED = [ + float(np.float32(msg.vel_n) * np.float32(1e-03)), + float(np.float32(msg.vel_e) * np.float32(1e-03)), + float(np.float32(msg.vel_d) * np.float32(1e-03)), + ] + gps.verticalAccuracy = msg.v_acc * 1e-03 + gps.speedAccuracy = msg.s_acc * 1e-03 + gps.bearingAccuracyDeg = msg.head_acc * 1e-05 + return ('gpsLocationExternal', dat) + + # RXM-SFRBX dispatch to GPS or GLONASS ephemeris + def _gen_rxm_sfrbx(self, msg) -> tuple[str, capnp.lib.capnp._DynamicStructBuilder] | None: + if msg.gnss_id == Ubx.GnssType.gps: + return self._parse_gps_ephemeris(msg) + if msg.gnss_id == Ubx.GnssType.glonass: + return self._parse_glonass_ephemeris(msg) + return None + + def _parse_gps_ephemeris(self, msg: Ubx.RxmSfrbx) -> tuple[str, capnp.lib.capnp._DynamicStructBuilder] | None: + # body is list of 10 words; convert to 30-byte subframe (strip parity/padding) + body = msg.body + if len(body) != 10: + return None + subframe_data = bytearray() + for word in body: + word >>= 6 + subframe_data.append((word >> 16) & 0xFF) + subframe_data.append((word >> 8) & 0xFF) + subframe_data.append(word & 0xFF) + + sf = Gps.from_bytes(bytes(subframe_data)) + subframe_id = sf.how.subframe_id + if subframe_id < 1 or subframe_id > 3: + return None + self.caches.gps_subframes[msg.sv_id][subframe_id] = bytes(subframe_data) + + if len(self.caches.gps_subframes[msg.sv_id]) != 3: + return None + + dat = messaging.new_message('ubloxGnss', valid=True) + eph = dat.ubloxGnss.init('ephemeris') + eph.svId = msg.sv_id + + iode_s2 = 0 + iode_s3 = 0 + iodc_lsb = 0 + week = 0 + + # Subframe 1 + sf1 = Gps.from_bytes(self.caches.gps_subframes[msg.sv_id][1]) + s1 = sf1.body + assert isinstance(s1, Gps.Subframe1) + week = s1.week_no + week += 1024 + if week < 1877: + week += 1024 + eph.tgd = s1.t_gd * math.pow(2, -31) + eph.toc = s1.t_oc * math.pow(2, 4) + eph.af2 = s1.af_2 * math.pow(2, -55) + eph.af1 = s1.af_1 * math.pow(2, -43) + eph.af0 = s1.af_0 * math.pow(2, -31) + eph.svHealth = s1.sv_health + eph.towCount = sf1.how.tow_count + iodc_lsb = s1.iodc_lsb + + # Subframe 2 + sf2 = Gps.from_bytes(self.caches.gps_subframes[msg.sv_id][2]) + s2 = sf2.body + assert isinstance(s2, Gps.Subframe2) + if s2.t_oe == 0 and sf2.how.tow_count * 6 >= (SECS_IN_WEEK - 2 * SECS_IN_HR): + week += 1 + eph.crs = s2.c_rs * math.pow(2, -5) + eph.deltaN = s2.delta_n * math.pow(2, -43) * self.gpsPi + eph.m0 = s2.m_0 * math.pow(2, -31) * self.gpsPi + eph.cuc = s2.c_uc * math.pow(2, -29) + eph.ecc = s2.e * math.pow(2, -33) + eph.cus = s2.c_us * math.pow(2, -29) + eph.a = math.pow(s2.sqrt_a * math.pow(2, -19), 2.0) + eph.toe = s2.t_oe * math.pow(2, 4) + iode_s2 = s2.iode + + # Subframe 3 + sf3 = Gps.from_bytes(self.caches.gps_subframes[msg.sv_id][3]) + s3 = sf3.body + assert isinstance(s3, Gps.Subframe3) + eph.cic = s3.c_ic * math.pow(2, -29) + eph.omega0 = s3.omega_0 * math.pow(2, -31) * self.gpsPi + eph.cis = s3.c_is * math.pow(2, -29) + eph.i0 = s3.i_0 * math.pow(2, -31) * self.gpsPi + eph.crc = s3.c_rc * math.pow(2, -5) + eph.omega = s3.omega * math.pow(2, -31) * self.gpsPi + eph.omegaDot = s3.omega_dot * math.pow(2, -43) * self.gpsPi + eph.iode = s3.iode + eph.iDot = s3.idot * math.pow(2, -43) * self.gpsPi + iode_s3 = s3.iode + + eph.toeWeek = week + eph.tocWeek = week + + # clear cache for this SV + self.caches.gps_subframes[msg.sv_id].clear() + if not (iodc_lsb == iode_s2 == iode_s3): + return None + return ('ubloxGnss', dat) + + def _parse_glonass_ephemeris(self, msg: Ubx.RxmSfrbx) -> tuple[str, capnp.lib.capnp._DynamicStructBuilder] | None: + # words are 4 bytes each; Glonass parser expects 16 bytes (string) + body = msg.body + if len(body) != 4: + return None + string_bytes = bytearray() + for word in body: + for i in (3, 2, 1, 0): + string_bytes.append((word >> (8 * i)) & 0xFF) + + gl = Glonass.from_bytes(bytes(string_bytes)) + string_number = gl.string_number + if string_number < 1 or string_number > 5 or gl.idle_chip: + return None + + # correlate by superframe and timing, similar to C++ logic + freq_id = msg.freq_id + superframe_unknown = False + needs_clear = False + for i in range(1, 6): + if i not in self.caches.glonass_strings[freq_id]: + continue + sf_prev = self.caches.glonass_string_superframes[freq_id].get(i, 0) + if sf_prev == 0 or gl.superframe_number == 0: + superframe_unknown = True + elif sf_prev != gl.superframe_number: + needs_clear = True + if superframe_unknown: + prev_time = self.caches.glonass_string_times[freq_id].get(i, 0.0) + if abs((prev_time - 2.0 * i) - (self.framer.last_log_time - 2.0 * string_number)) > 10: + needs_clear = True + + if needs_clear: + self.caches.glonass_strings[freq_id].clear() + self.caches.glonass_string_superframes[freq_id].clear() + self.caches.glonass_string_times[freq_id].clear() + + self.caches.glonass_strings[freq_id][string_number] = bytes(string_bytes) + self.caches.glonass_string_superframes[freq_id][string_number] = gl.superframe_number + self.caches.glonass_string_times[freq_id][string_number] = self.framer.last_log_time + + if msg.sv_id == 255: + # unknown SV id + return None + if len(self.caches.glonass_strings[freq_id]) != 5: + return None + + dat = messaging.new_message('ubloxGnss', valid=True) + eph = dat.ubloxGnss.init('glonassEphemeris') + eph.svId = msg.sv_id + eph.freqNum = msg.freq_id - 7 + + current_day = 0 + tk = 0 + + # string 1 + try: + s1 = Glonass.from_bytes(self.caches.glonass_strings[freq_id][1]).data + except Exception: + return None + assert isinstance(s1, Glonass.String1) + eph.p1 = int(s1.p1) + tk = int(s1.t_k) + eph.deprecated.tk = tk + eph.xVel = float(s1.x_vel) * math.pow(2, -20) + eph.xAccel = float(s1.x_accel) * math.pow(2, -30) + eph.x = float(s1.x) * math.pow(2, -11) + + # string 2 + try: + s2 = Glonass.from_bytes(self.caches.glonass_strings[freq_id][2]).data + except Exception: + return None + assert isinstance(s2, Glonass.String2) + eph.svHealth = int(s2.b_n >> 2) + eph.p2 = int(s2.p2) + eph.tb = int(s2.t_b) + eph.yVel = float(s2.y_vel) * math.pow(2, -20) + eph.yAccel = float(s2.y_accel) * math.pow(2, -30) + eph.y = float(s2.y) * math.pow(2, -11) + + # string 3 + try: + s3 = Glonass.from_bytes(self.caches.glonass_strings[freq_id][3]).data + except Exception: + return None + assert isinstance(s3, Glonass.String3) + eph.p3 = int(s3.p3) + eph.gammaN = float(s3.gamma_n) * math.pow(2, -40) + eph.svHealth = int(eph.svHealth | (1 if s3.l_n else 0)) + eph.zVel = float(s3.z_vel) * math.pow(2, -20) + eph.zAccel = float(s3.z_accel) * math.pow(2, -30) + eph.z = float(s3.z) * math.pow(2, -11) + + # string 4 + try: + s4 = Glonass.from_bytes(self.caches.glonass_strings[freq_id][4]).data + except Exception: + return None + assert isinstance(s4, Glonass.String4) + current_day = int(s4.n_t) + eph.nt = current_day + eph.tauN = float(s4.tau_n) * math.pow(2, -30) + eph.deltaTauN = float(s4.delta_tau_n) * math.pow(2, -30) + eph.age = int(s4.e_n) + eph.p4 = int(s4.p4) + eph.svURA = float(self.glonass_URA_lookup.get(int(s4.f_t), 0.0)) + # consistency check: SV slot number + # if it doesn't match, keep going but note mismatch (no logging here) + eph.svType = int(s4.m) + + # string 5 + try: + s5 = Glonass.from_bytes(self.caches.glonass_strings[freq_id][5]).data + except Exception: + return None + assert isinstance(s5, Glonass.String5) + eph.n4 = int(s5.n_4) + tk_seconds = int(SECS_IN_HR * ((tk >> 7) & 0x1F) + SECS_IN_MIN * ((tk >> 1) & 0x3F) + (tk & 0x1) * 30) + eph.tkSeconds = tk_seconds + + self.caches.glonass_strings[freq_id].clear() + return ('ubloxGnss', dat) + + def _gen_rxm_rawx(self, msg: Ubx.RxmRawx) -> tuple[str, capnp.lib.capnp._DynamicStructBuilder]: + dat = messaging.new_message('ubloxGnss', valid=True) + mr = dat.ubloxGnss.init('measurementReport') + mr.rcvTow = msg.rcv_tow + mr.gpsWeek = msg.week + mr.leapSeconds = msg.leap_s + + mb = mr.init('measurements', msg.num_meas) + for i, m in enumerate(msg.meas): + mb[i].svId = m.sv_id + mb[i].pseudorange = m.pr_mes + mb[i].carrierCycles = m.cp_mes + mb[i].doppler = m.do_mes + mb[i].gnssId = int(m.gnss_id.value) + mb[i].glonassFrequencyIndex = m.freq_id + mb[i].locktime = m.lock_time + mb[i].cno = m.cno + mb[i].pseudorangeStdev = 0.01 * (math.pow(2, (m.pr_stdev & 15))) + mb[i].carrierPhaseStdev = 0.004 * (m.cp_stdev & 15) + mb[i].dopplerStdev = 0.002 * (math.pow(2, (m.do_stdev & 15))) + + ts = mb[i].init('trackingStatus') + trk = m.trk_stat + ts.pseudorangeValid = _bit(trk, 0) + ts.carrierPhaseValid = _bit(trk, 1) + ts.halfCycleValid = _bit(trk, 2) + ts.halfCycleSubtracted = _bit(trk, 3) + + mr.numMeas = msg.num_meas + rs = mr.init('receiverStatus') + rs.leapSecValid = _bit(msg.rec_stat, 0) + rs.clkReset = _bit(msg.rec_stat, 2) + return ('ubloxGnss', dat) + + def _gen_nav_sat(self, msg: Ubx.NavSat) -> tuple[str, capnp.lib.capnp._DynamicStructBuilder]: + dat = messaging.new_message('ubloxGnss', valid=True) + sr = dat.ubloxGnss.init('satReport') + sr.iTow = msg.itow + svs = sr.init('svs', msg.num_svs) + for i, s in enumerate(msg.svs): + svs[i].svId = s.sv_id + svs[i].gnssId = int(s.gnss_id.value) + svs[i].flagsBitfield = s.flags + svs[i].cno = s.cno + svs[i].elevationDeg = s.elev + svs[i].azimuthDeg = s.azim + svs[i].pseudorangeResidual = s.pr_res * 0.1 + return ('ubloxGnss', dat) + + def _gen_mon_hw(self, msg: Ubx.MonHw) -> tuple[str, capnp.lib.capnp._DynamicStructBuilder]: + dat = messaging.new_message('ubloxGnss', valid=True) + hw = dat.ubloxGnss.init('hwStatus') + hw.noisePerMS = msg.noise_per_ms + hw.flags = msg.flags + hw.agcCnt = msg.agc_cnt + hw.aStatus = int(msg.a_status.value) + hw.aPower = int(msg.a_power.value) + hw.jamInd = msg.jam_ind + return ('ubloxGnss', dat) + + def _gen_mon_hw2(self, msg: Ubx.MonHw2) -> tuple[str, capnp.lib.capnp._DynamicStructBuilder]: + dat = messaging.new_message('ubloxGnss', valid=True) + hw = dat.ubloxGnss.init('hwStatus2') + hw.ofsI = msg.ofs_i + hw.magI = msg.mag_i + hw.ofsQ = msg.ofs_q + hw.magQ = msg.mag_q + # Map Ubx enum to cereal enum {undefined=0, rom=1, otp=2, configpins=3, flash=4} + cfg_map = { + Ubx.MonHw2.ConfigSource.rom: 1, + Ubx.MonHw2.ConfigSource.otp: 2, + Ubx.MonHw2.ConfigSource.config_pins: 3, + Ubx.MonHw2.ConfigSource.flash: 4, + } + hw.cfgSource = cfg_map.get(msg.cfg_source, 0) + hw.lowLevCfg = msg.low_lev_cfg + hw.postStatus = msg.post_status + return ('ubloxGnss', dat) + + +def main(): + parser = UbloxMsgParser() + pm = messaging.PubMaster(['ubloxGnss', 'gpsLocationExternal']) + sock = messaging.sub_sock('ubloxRaw', timeout=100, conflate=False) + + while True: + msg = messaging.recv_one(sock) + if msg is None: + continue + + data = bytes(msg.ubloxRaw) + log_time = msg.logMonoTime * 1e-9 + frames = parser.framer.add_data(log_time, data) + for frame in frames: + try: + res = parser.parse_frame(frame) + except Exception: + continue + if not res: + continue + service, dat = res + pm.send(service, dat) + + +if __name__ == '__main__': + main() diff --git a/openpilot/system/ubloxd/ubx.py b/openpilot/system/ubloxd/ubx.py new file mode 100644 index 0000000000..857498ebf1 --- /dev/null +++ b/openpilot/system/ubloxd/ubx.py @@ -0,0 +1,180 @@ +""" +UBX protocol parser +""" + +from enum import IntEnum +from typing import Annotated + +from openpilot.system.ubloxd import binary_struct as bs + + +class GnssType(IntEnum): + gps = 0 + sbas = 1 + galileo = 2 + beidou = 3 + imes = 4 + qzss = 5 + glonass = 6 + + +class Ubx(bs.BinaryStruct): + GnssType = GnssType + + class RxmRawx(bs.BinaryStruct): + class Measurement(bs.BinaryStruct): + pr_mes: Annotated[float, bs.f64] + cp_mes: Annotated[float, bs.f64] + do_mes: Annotated[float, bs.f32] + gnss_id: Annotated[GnssType | int, bs.enum(bs.u8, GnssType)] + sv_id: Annotated[int, bs.u8] + reserved2: Annotated[bytes, bs.bytes_field(1)] + freq_id: Annotated[int, bs.u8] + lock_time: Annotated[int, bs.u16] + cno: Annotated[int, bs.u8] + pr_stdev: Annotated[int, bs.u8] + cp_stdev: Annotated[int, bs.u8] + do_stdev: Annotated[int, bs.u8] + trk_stat: Annotated[int, bs.u8] + reserved3: Annotated[bytes, bs.bytes_field(1)] + + rcv_tow: Annotated[float, bs.f64] + week: Annotated[int, bs.u16] + leap_s: Annotated[int, bs.s8] + num_meas: Annotated[int, bs.u8] + rec_stat: Annotated[int, bs.u8] + reserved1: Annotated[bytes, bs.bytes_field(3)] + meas: Annotated[list[Measurement], bs.array(Measurement, count_field='num_meas')] + + class RxmSfrbx(bs.BinaryStruct): + gnss_id: Annotated[GnssType | int, bs.enum(bs.u8, GnssType)] + sv_id: Annotated[int, bs.u8] + reserved1: Annotated[bytes, bs.bytes_field(1)] + freq_id: Annotated[int, bs.u8] + num_words: Annotated[int, bs.u8] + reserved2: Annotated[bytes, bs.bytes_field(1)] + version: Annotated[int, bs.u8] + reserved3: Annotated[bytes, bs.bytes_field(1)] + body: Annotated[list[int], bs.array(bs.u32, count_field='num_words')] + + class NavSat(bs.BinaryStruct): + class Nav(bs.BinaryStruct): + gnss_id: Annotated[GnssType | int, bs.enum(bs.u8, GnssType)] + sv_id: Annotated[int, bs.u8] + cno: Annotated[int, bs.u8] + elev: Annotated[int, bs.s8] + azim: Annotated[int, bs.s16] + pr_res: Annotated[int, bs.s16] + flags: Annotated[int, bs.u32] + + itow: Annotated[int, bs.u32] + version: Annotated[int, bs.u8] + num_svs: Annotated[int, bs.u8] + reserved: Annotated[bytes, bs.bytes_field(2)] + svs: Annotated[list[Nav], bs.array(Nav, count_field='num_svs')] + + class NavPvt(bs.BinaryStruct): + i_tow: Annotated[int, bs.u32] + year: Annotated[int, bs.u16] + month: Annotated[int, bs.u8] + day: Annotated[int, bs.u8] + hour: Annotated[int, bs.u8] + min: Annotated[int, bs.u8] + sec: Annotated[int, bs.u8] + valid: Annotated[int, bs.u8] + t_acc: Annotated[int, bs.u32] + nano: Annotated[int, bs.s32] + fix_type: Annotated[int, bs.u8] + flags: Annotated[int, bs.u8] + flags2: Annotated[int, bs.u8] + num_sv: Annotated[int, bs.u8] + lon: Annotated[int, bs.s32] + lat: Annotated[int, bs.s32] + height: Annotated[int, bs.s32] + h_msl: Annotated[int, bs.s32] + h_acc: Annotated[int, bs.u32] + v_acc: Annotated[int, bs.u32] + vel_n: Annotated[int, bs.s32] + vel_e: Annotated[int, bs.s32] + vel_d: Annotated[int, bs.s32] + g_speed: Annotated[int, bs.s32] + head_mot: Annotated[int, bs.s32] + s_acc: Annotated[int, bs.s32] + head_acc: Annotated[int, bs.u32] + p_dop: Annotated[int, bs.u16] + flags3: Annotated[int, bs.u8] + reserved1: Annotated[bytes, bs.bytes_field(5)] + head_veh: Annotated[int, bs.s32] + mag_dec: Annotated[int, bs.s16] + mag_acc: Annotated[int, bs.u16] + + class MonHw2(bs.BinaryStruct): + class ConfigSource(IntEnum): + flash = 102 + otp = 111 + config_pins = 112 + rom = 113 + + ofs_i: Annotated[int, bs.s8] + mag_i: Annotated[int, bs.u8] + ofs_q: Annotated[int, bs.s8] + mag_q: Annotated[int, bs.u8] + cfg_source: Annotated[ConfigSource | int, bs.enum(bs.u8, ConfigSource)] + reserved1: Annotated[bytes, bs.bytes_field(3)] + low_lev_cfg: Annotated[int, bs.u32] + reserved2: Annotated[bytes, bs.bytes_field(8)] + post_status: Annotated[int, bs.u32] + reserved3: Annotated[bytes, bs.bytes_field(4)] + + class MonHw(bs.BinaryStruct): + class AntennaStatus(IntEnum): + init = 0 + dontknow = 1 + ok = 2 + short = 3 + open = 4 + + class AntennaPower(IntEnum): + false = 0 + true = 1 + dontknow = 2 + + pin_sel: Annotated[int, bs.u32] + pin_bank: Annotated[int, bs.u32] + pin_dir: Annotated[int, bs.u32] + pin_val: Annotated[int, bs.u32] + noise_per_ms: Annotated[int, bs.u16] + agc_cnt: Annotated[int, bs.u16] + a_status: Annotated[AntennaStatus | int, bs.enum(bs.u8, AntennaStatus)] + a_power: Annotated[AntennaPower | int, bs.enum(bs.u8, AntennaPower)] + flags: Annotated[int, bs.u8] + reserved1: Annotated[bytes, bs.bytes_field(1)] + used_mask: Annotated[int, bs.u32] + vp: Annotated[bytes, bs.bytes_field(17)] + jam_ind: Annotated[int, bs.u8] + reserved2: Annotated[bytes, bs.bytes_field(2)] + pin_irq: Annotated[int, bs.u32] + pull_h: Annotated[int, bs.u32] + pull_l: Annotated[int, bs.u32] + + magic: Annotated[bytes, bs.const(bs.bytes_field(2), b"\xb5\x62")] + msg_type: Annotated[int, bs.u16be] + length: Annotated[int, bs.u16] + body: Annotated[ + object, + bs.substream( + 'length', + bs.switch( + 'msg_type', + { + 0x0107: NavPvt, + 0x0213: RxmSfrbx, + 0x0215: RxmRawx, + 0x0A09: MonHw, + 0x0A0B: MonHw2, + 0x0135: NavSat, + }, + ), + ), + ] + checksum: Annotated[int, bs.u16] diff --git a/openpilot/system/ui/README.md b/openpilot/system/ui/README.md new file mode 100644 index 0000000000..7c9713b39e --- /dev/null +++ b/openpilot/system/ui/README.md @@ -0,0 +1,21 @@ +# ui + +The user interfaces here are built with [raylib](https://www.raylib.com/). + +Quick start: +* set `BIG=1` to run the comma 3X UI (comma four UI runs by default) +* set `SHOW_FPS=1` to show the FPS +* set `STRICT_MODE=1` to kill the app if it drops too much below 60fps +* set `SCALE=1.5` to scale the entire UI by 1.5x +* set `BURN_IN=1` to get a burn-in heatmap version of the UI +* set `GRID=50` to show a 50-pixel alignment grid overlay +* set `MAGIC_DEBUG=1` to show every dropped frames (only on device) +* set `RECORD=1` to record the screen, output defaults to `output.mp4` but can be set with `RECORD_OUTPUT` +* set `SUNNYPILOT_UI=0` to run the stock UI instead of the sunnypilot UI +* https://www.raylib.com/cheatsheet/cheatsheet.html +* https://electronstudio.github.io/raylib-python-cffi/README.html#quickstart + +Style guide: +* All graphical elements should subclass [`Widget`](/openpilot/system/ui/widgets/__init__.py). + * Prefer a stateful widget over a function for easy migration from QT +* All internal class variables and functions should be prefixed with `_` diff --git a/tools/sim/lib/__init__.py b/openpilot/system/ui/lib/__init__.py similarity index 100% rename from tools/sim/lib/__init__.py rename to openpilot/system/ui/lib/__init__.py diff --git a/openpilot/system/ui/lib/application.py b/openpilot/system/ui/lib/application.py new file mode 100644 index 0000000000..58fcc15a22 --- /dev/null +++ b/openpilot/system/ui/lib/application.py @@ -0,0 +1,874 @@ +import atexit +import cffi +import math +import os +import queue +import time +import signal +import sys +import pyray as rl +import threading +import platform +import subprocess +from contextlib import contextmanager +from collections.abc import Callable +from collections import deque +from enum import StrEnum +from pathlib import Path +from typing import NamedTuple +from importlib.resources import as_file, files +from openpilot.common.swaglog import cloudlog +from openpilot.common.hardware import HARDWARE, PC +from openpilot.system.ui.lib.multilang import multilang +from openpilot.common.realtime import Ratekeeper + +from openpilot.system.ui.sunnypilot.lib.application import GuiApplicationExt + +_DEFAULT_FPS = int(os.getenv("FPS", {'tizi': 20}.get(HARDWARE.get_device_type(), 60))) +FPS_LOG_INTERVAL = 5 # Seconds between logging FPS drops +FPS_DROP_THRESHOLD = 0.9 # FPS drop threshold for triggering a warning +FPS_CRITICAL_THRESHOLD = 0.5 # Critical threshold for triggering strict actions +MOUSE_THREAD_RATE = 140 # touch controller runs at 140Hz +MAX_TOUCH_SLOTS = 2 +TOUCH_HISTORY_TIMEOUT = 3.0 # Seconds before touch points fade out + +BIG_UI = os.getenv("BIG", "0") == "1" +ENABLE_VSYNC = os.getenv("ENABLE_VSYNC", "0") == "1" +SHOW_FPS = os.getenv("SHOW_FPS") == "1" +SHOW_TOUCHES = os.getenv("SHOW_TOUCHES") == "1" +STRICT_MODE = os.getenv("STRICT_MODE") == "1" +SCALE = float(os.getenv("SCALE", "1.0")) +GRID_SIZE = int(os.getenv("GRID", "0")) +PROFILE_RENDER = int(os.getenv("PROFILE_RENDER", "0")) +PROFILE_STATS = int(os.getenv("PROFILE_STATS", "100")) # Number of functions to show in profile output +RECORD = os.getenv("RECORD") == "1" +RECORD_OUTPUT = str(Path(os.getenv("RECORD_OUTPUT", "output")).with_suffix(".mp4")) +RECORD_QUALITY = int(os.getenv("RECORD_QUALITY", "23")) # Dynamic bitrate quality level (CRF); 0 is lossless (bigger size), max is 51, default is 23 for x264 +RECORD_BITRATE = os.getenv("RECORD_BITRATE", "") # Target bitrate e.g. "2000k" (overrides RECORD_QUALITY when set) +RECORD_SPEED = int(os.getenv("RECORD_SPEED", "1")) # Speed multiplier +OFFSCREEN = os.getenv("OFFSCREEN") == "1" # Disable FPS limiting for fast offline rendering + +GL_VERSION = """ +#version 300 es +precision highp float; +""" +if platform.system() == "Darwin": + GL_VERSION = """ + #version 330 core + """ + +BURN_IN_MODE = "BURN_IN" in os.environ +BURN_IN_VERTEX_SHADER = GL_VERSION + """ +in vec3 vertexPosition; +in vec2 vertexTexCoord; +uniform mat4 mvp; +out vec2 fragTexCoord; +void main() { + fragTexCoord = vertexTexCoord; + gl_Position = mvp * vec4(vertexPosition, 1.0); +} +""" +BURN_IN_FRAGMENT_SHADER = GL_VERSION + """ +in vec2 fragTexCoord; +uniform sampler2D texture0; +out vec4 fragColor; +void main() { + vec4 sampled = texture(texture0, fragTexCoord); + float intensity = sampled.b; + // Map blue intensity to green -> yellow -> red to highlight burn-in risk. + vec3 start = vec3(0.0, 1.0, 0.0); + vec3 middle = vec3(1.0, 1.0, 0.0); + vec3 end = vec3(1.0, 0.0, 0.0); + vec3 gradient = mix(start, middle, clamp(intensity * 2.0, 0.0, 1.0)); + gradient = mix(gradient, end, clamp((intensity - 0.5) * 2.0, 0.0, 1.0)); + fragColor = vec4(gradient, sampled.a); +} +""" + +DEFAULT_TEXT_SIZE = 60 +DEFAULT_TEXT_COLOR = rl.Color(255, 255, 255, int(255 * 0.9)) + +# Qt draws fonts accounting for ascent/descent differently, so compensate to match old styles +# The real scales for the fonts below range from 1.212 to 1.266 +FONT_SCALE = 1.242 if BIG_UI else 1.16 + +ASSETS_DIR = files("openpilot.selfdrive").joinpath("assets") +FONT_DIR = ASSETS_DIR.joinpath("fonts") + + +class FontWeight(StrEnum): + NORMAL = "Inter-Regular.fnt" if BIG_UI else "Inter-Medium.fnt" + MEDIUM = "Inter-Medium.fnt" + BOLD = "Inter-Bold.fnt" + SEMI_BOLD = "Inter-SemiBold.fnt" + UNIFONT = "unifont.fnt" + AUDIOWIDE = "Audiowide-Regular.fnt" + + # Small UI fonts + DISPLAY_REGULAR = "Inter-Regular.fnt" + ROMAN = "Inter-Regular.fnt" + DISPLAY = "Inter-Bold.fnt" + + +def font_fallback(font: rl.Font) -> rl.Font: + """Fall back to unifont for languages that require it.""" + if multilang.requires_unifont(): + return gui_app.font(FontWeight.UNIFONT) + return font + + +class MousePos(NamedTuple): + x: float + y: float + + +class MousePosWithTime(NamedTuple): + x: float + y: float + t: float + + +class MouseEvent(NamedTuple): + pos: MousePos + slot: int + left_pressed: bool + left_released: bool + left_down: bool + t: float + + +class MouseState: + def __init__(self, scale: float = 1.0): + self._scale = scale + self._events: deque[MouseEvent] = deque(maxlen=MOUSE_THREAD_RATE) # bound event list + self._prev_mouse_event: list[MouseEvent | None] = [None] * MAX_TOUCH_SLOTS + + self._rk = Ratekeeper(MOUSE_THREAD_RATE, print_delay_threshold=None) + self._lock = threading.Lock() + self._exit_event = threading.Event() + self._thread = None + + def get_events(self) -> list[MouseEvent]: + with self._lock: + events = list(self._events) + self._events.clear() + return events + + def start(self): + self._exit_event.clear() + if self._thread is None or not self._thread.is_alive(): + self._thread = threading.Thread(target=self._run_thread, daemon=True) + self._thread.start() + + def stop(self): + self._exit_event.set() + if self._thread is not None and self._thread.is_alive(): + self._thread.join() + + def _run_thread(self): + while not self._exit_event.is_set(): + rl.poll_input_events() + self._handle_mouse_event() + self._rk.keep_time() + + def _handle_mouse_event(self): + # TODO: read touch events from evdev directly to get real kernel timestamps. + # Polling at 140Hz with time.monotonic() causes timing jitter that makes scroll + # velocity oscillate (alternating high/low). Real timestamps would also let us + # detect swipe-stop-lift via event gaps instead of the fragile decel heuristic. + for slot in range(MAX_TOUCH_SLOTS): + mouse_pos = rl.get_touch_position(slot) + x = mouse_pos.x / self._scale if self._scale != 1.0 else mouse_pos.x + y = mouse_pos.y / self._scale if self._scale != 1.0 else mouse_pos.y + ev = MouseEvent( + MousePos(x, y), + slot, + rl.is_mouse_button_pressed(slot), # noqa: TID251 + rl.is_mouse_button_released(slot), # noqa: TID251 + rl.is_mouse_button_down(slot), + time.monotonic(), + ) + # Only add changes + prev = self._prev_mouse_event[slot] + if prev is None or ev[:-1] != prev[:-1]: + with self._lock: + self._events.append(ev) + self._prev_mouse_event[slot] = ev + + +class GuiApplication(GuiApplicationExt): + def __init__(self, width: int | None = None, height: int | None = None): + self._set_log_callback() + + self._fonts: dict[FontWeight, rl.Font] = {} + self._width = width if width is not None else GuiApplication._default_width() + self._height = height if height is not None else GuiApplication._default_height() + + if PC and os.getenv("SCALE") is None: + self._scale = self._calculate_auto_scale() + else: + self._scale = SCALE + + # Scale, then ensure dimensions are even + self._scaled_width = int(self._width * self._scale) + self._scaled_height = int(self._height * self._scale) + self._scaled_width += self._scaled_width % 2 + self._scaled_height += self._scaled_height % 2 + + self._render_texture: rl.RenderTexture | None = None + self._burn_in_shader: rl.Shader | None = None + self._ffmpeg_proc: subprocess.Popen | None = None + self._ffmpeg_queue: queue.Queue | None = None + self._ffmpeg_thread: threading.Thread | None = None + self._ffmpeg_stop_event: threading.Event | None = None + self._textures: dict[str, rl.Texture] = {} + self._target_fps: int = _DEFAULT_FPS + self._last_fps_log_time: float = time.monotonic() + self._frame = 0 + self._window_close_requested = False + self._nav_stack: list[object] = [] + self._nav_stack_ticks: list[Callable[[], None]] = [] + self._nav_stack_widgets_to_render = 1 if self.big_ui() else 2 + + self._mouse = MouseState(self._scale) + self._mouse_events: list[MouseEvent] = [] + self._last_mouse_event: MouseEvent = MouseEvent(MousePos(0, 0), 0, False, False, False, 0.0) + + self._should_render = True + + # Debug variables + self._mouse_history: deque[MousePosWithTime] = deque(maxlen=MOUSE_THREAD_RATE) + self._show_touches = SHOW_TOUCHES + self._show_fps = SHOW_FPS + self._grid_size = GRID_SIZE + self._profile_render_frames = PROFILE_RENDER + self._render_profiler = None + self._render_profile_start_time = None + + GuiApplicationExt.__init__(self) + + @property + def frame(self): + return self._frame + + def set_show_touches(self, show: bool): + self._show_touches = show + + def set_show_fps(self, show: bool): + self._show_fps = show + + @property + def show_touches(self) -> bool: + return self._show_touches + + @property + def target_fps(self): + return self._target_fps + + def request_close(self): + self._window_close_requested = True + + def init_window(self, title: str, fps: int = _DEFAULT_FPS): + with self._startup_profile_context(): + def _close(sig, frame): + self.close() + sys.exit(0) + signal.signal(signal.SIGINT, _close) + atexit.register(self.close) + + flags = rl.ConfigFlags.FLAG_MSAA_4X_HINT + if ENABLE_VSYNC: + flags |= rl.ConfigFlags.FLAG_VSYNC_HINT + rl.set_config_flags(flags) + + rl.init_window(self._scaled_width, self._scaled_height, title) + + needs_render_texture = self._scale != 1.0 or BURN_IN_MODE or RECORD + if self._scale != 1.0: + rl.set_mouse_scale(1 / self._scale, 1 / self._scale) + if needs_render_texture: + self._render_texture = rl.load_render_texture(self._scaled_width, self._scaled_height) + rl.set_texture_filter(self._render_texture.texture, rl.TextureFilter.TEXTURE_FILTER_BILINEAR) + + if RECORD: + output_fps = fps * RECORD_SPEED + ffmpeg_args = [ + 'ffmpeg', + '-v', 'warning', # Reduce ffmpeg log spam + '-nostats', # Suppress encoding progress + '-f', 'rawvideo', # Input format + '-pix_fmt', 'rgba', # Input pixel format + '-s', f'{self._scaled_width}x{self._scaled_height}', # Input resolution + '-r', str(fps), # Input frame rate + '-i', 'pipe:0', # Input from stdin + '-vf', 'vflip,format=yuv420p', # Flip vertically and convert to yuv420p + '-r', str(output_fps), # Output frame rate (for speed multiplier) + '-c:v', 'libx264', + '-preset', 'veryfast', + '-crf', str(RECORD_QUALITY) + ] + if RECORD_BITRATE: + # NOTE: custom bitrate overrides crf setting + ffmpeg_args += ['-b:v', RECORD_BITRATE, '-maxrate', RECORD_BITRATE, '-bufsize', RECORD_BITRATE] + ffmpeg_args += [ + '-y', # Overwrite existing file + '-f', 'mp4', # Output format + RECORD_OUTPUT, # Output file path + ] + self._ffmpeg_proc = subprocess.Popen(ffmpeg_args, stdin=subprocess.PIPE) + self._ffmpeg_queue = queue.Queue(maxsize=60) # Buffer up to 60 frames + self._ffmpeg_stop_event = threading.Event() + self._ffmpeg_thread = threading.Thread(target=self._ffmpeg_writer_thread, daemon=True) + self._ffmpeg_thread.start() + + # four display runs slightly faster than 60 FPS, let it dictate rate so we don't drift and drop frames + vblank_control = HARDWARE.get_device_type() == 'mici' + rl.set_target_fps(0 if OFFSCREEN or vblank_control else fps) + + self._target_fps = fps + self._set_styles() + self._load_fonts() + self._patch_text_functions() + self._patch_scissor_mode() + if BURN_IN_MODE and self._burn_in_shader is None: + self._burn_in_shader = rl.load_shader_from_memory(BURN_IN_VERTEX_SHADER, BURN_IN_FRAGMENT_SHADER) + + if not PC: + self._mouse.start() + + @contextmanager + def _startup_profile_context(self): + if "PROFILE_STARTUP" not in os.environ: + yield + return + + import cProfile + import io + import pstats + + profiler = cProfile.Profile() + start_time = time.monotonic() + profiler.enable() + + # do the init + yield + + profiler.disable() + elapsed_ms = (time.monotonic() - start_time) * 1e3 + + stats_stream = io.StringIO() + pstats.Stats(profiler, stream=stats_stream).sort_stats("cumtime").print_stats(25) + print("\n=== Startup profile ===") + print(stats_stream.getvalue().rstrip()) + + green = "\033[92m" + reset = "\033[0m" + print(f"{green}UI window ready in {elapsed_ms:.1f} ms{reset}") + sys.exit(0) + + def _ffmpeg_writer_thread(self): + """Background thread that writes frames to ffmpeg.""" + while True: + try: + data = self._ffmpeg_queue.get(timeout=1.0) + if data is None: # Sentinel to stop + break + self._ffmpeg_proc.stdin.write(data) + except queue.Empty: + if self._ffmpeg_stop_event.is_set(): + break + continue + except Exception: + break + + def push_widget(self, widget: object): + if widget in self._nav_stack: + cloudlog.warning("Widget already in stack, cannot push again!") + return + + # disable previous widget to prevent input processing + if len(self._nav_stack) > 0: + prev_widget = self._nav_stack[-1] + # TODO: change these to touch_valid + prev_widget.set_enabled(False) + + self._nav_stack.append(widget) + widget.show_event() + widget.set_enabled(True) + + def pop_widget(self, idx: int | None = None): + # Pops widget instantly without animation + if len(self._nav_stack) < 2: + cloudlog.warning("At least one widget should remain on the stack, ignoring pop!") + return + + idx_to_pop = len(self._nav_stack) - 1 if idx is None else idx + if idx_to_pop <= 0 or idx_to_pop >= len(self._nav_stack): + cloudlog.warning(f"Invalid index {idx_to_pop} to pop, ignoring!") + return + + # only re-enable previous widget if popping top widget + if idx_to_pop == len(self._nav_stack) - 1: + prev_widget = self._nav_stack[idx_to_pop - 1] + prev_widget.set_enabled(True) + + widget = self._nav_stack.pop(idx_to_pop) + widget.hide_event() + + def pop_widgets_to(self, widget: object, callback: Callable[[], None] | None = None, instant: bool = False): + # Pops middle widgets instantly without animation then dismisses top, animated out if NavWidget + if widget not in self._nav_stack: + cloudlog.warning("Widget not in stack, cannot pop to it!") + return + + # Nothing to pop, ensure we still run callback + top_widget = self._nav_stack[-1] + if top_widget == widget: + if callback: + callback() + return + + # instantly pop widgets in between, then dismiss top widget for animation + while len(self._nav_stack) > 1 and self._nav_stack[-2] != widget: + self.pop_widget(len(self._nav_stack) - 2) + + if not instant: + top_widget.dismiss(callback) + else: + self.pop_widget() + + def get_active_widget(self): + if len(self._nav_stack) > 0: + return self._nav_stack[-1] + return None + + def widget_in_stack(self, widget: object) -> bool: + return widget in self._nav_stack + + def add_nav_stack_tick(self, tick_function: Callable[[], None]): + if tick_function not in self._nav_stack_ticks: + self._nav_stack_ticks.append(tick_function) + + def remove_nav_stack_tick(self, tick_function: Callable[[], None]): + if tick_function in self._nav_stack_ticks: + self._nav_stack_ticks.remove(tick_function) + + def set_should_render(self, should_render: bool): + self._should_render = should_render + + def texture(self, asset_path: str, width: int | None = None, height: int | None = None, + alpha_premultiply=False, keep_aspect_ratio=True, flip_x: bool = False) -> rl.Texture: + if width is not None: + width = round(width) + if height is not None: + height = round(height) + + cache_key = f"{asset_path}_{width}_{height}_{alpha_premultiply}_{keep_aspect_ratio}_{flip_x}" + if cache_key in self._textures: + return self._textures[cache_key] + + with as_file(ASSETS_DIR.joinpath(asset_path)) as fspath: + image_obj = self._load_image_from_path(fspath.as_posix(), width, height, alpha_premultiply, keep_aspect_ratio, flip_x) + texture_obj = self._load_texture_from_image(image_obj) + + # Set logical size so widget layout math stays at 1x coordinates + if self._scale != 1.0 and width is not None and height is not None: + texture_obj.width = width + texture_obj.height = height + + self._textures[cache_key] = texture_obj + return texture_obj + + def _load_image_from_path(self, image_path: str, width: int | None = None, height: int | None = None, + alpha_premultiply: bool = False, keep_aspect_ratio: bool = True, flip_x: bool = False) -> rl.Image: + """Load and resize an image, storing it for later automatic unloading.""" + image = rl.load_image(image_path) + + if alpha_premultiply: + rl.image_alpha_premultiply(image) + + # Scale up load size for sharper rendering, capped at source resolution + if self._scale != 1.0 and width is not None and height is not None: + width = min(int(width * self._scale), image.width) + height = min(int(height * self._scale), image.height) + + if width is not None and height is not None: + same_dimensions = image.width == width and image.height == height + + # Resize with aspect ratio preservation if requested + if not same_dimensions: + if keep_aspect_ratio: + orig_width = image.width + orig_height = image.height + + scale_width = width / orig_width + scale_height = height / orig_height + + # Calculate new dimensions + scale = min(scale_width, scale_height) + new_width = int(orig_width * scale) + new_height = int(orig_height * scale) + + rl.image_resize(image, new_width, new_height) + else: + rl.image_resize(image, width, height) + else: + assert keep_aspect_ratio, "Cannot resize without specifying width and height" + + if flip_x: + rl.image_flip_horizontal(image) + + return image + + def _load_texture_from_image(self, image: rl.Image) -> rl.Texture: + """Send image to GPU and unload original image.""" + texture = rl.load_texture_from_image(image) + # Set texture filtering to smooth the result + rl.set_texture_filter(texture, rl.TextureFilter.TEXTURE_FILTER_BILINEAR) + # prevent artifacts from wrapping coordinates + rl.set_texture_wrap(texture, rl.TextureWrap.TEXTURE_WRAP_CLAMP) + + rl.unload_image(image) + return texture + + def close_ffmpeg(self): + if self._ffmpeg_thread is not None: + # Signal thread to stop, send sentinel, then wait for it to drain + self._ffmpeg_stop_event.set() + self._ffmpeg_queue.put(None) + self._ffmpeg_thread.join(timeout=30) + + if self._ffmpeg_proc is not None: + self._ffmpeg_proc.stdin.flush() + self._ffmpeg_proc.stdin.close() + try: + self._ffmpeg_proc.wait(timeout=30) + except subprocess.TimeoutExpired: + self._ffmpeg_proc.terminate() + self._ffmpeg_proc.wait() + + def close(self): + if not rl.is_window_ready(): + return + + for texture in self._textures.values(): + rl.unload_texture(texture) + self._textures = {} + + for font in self._fonts.values(): + rl.unload_font(font) + self._fonts = {} + + if self._render_texture is not None: + rl.unload_render_texture(self._render_texture) + self._render_texture = None + + if self._burn_in_shader: + rl.unload_shader(self._burn_in_shader) + self._burn_in_shader = None + + if not PC: + self._mouse.stop() + + self.close_ffmpeg() + + rl.close_window() + + @property + def mouse_events(self) -> list[MouseEvent]: + return self._mouse_events + + @property + def last_mouse_event(self) -> MouseEvent: + return self._last_mouse_event + + def render(self): + try: + if self._profile_render_frames > 0: + import cProfile + self._render_profiler = cProfile.Profile() + self._render_profile_start_time = time.monotonic() + self._render_profiler.enable() + + while not (self._window_close_requested or rl.window_should_close()): + frame_start = time.monotonic() + + if PC: + # Thread is not used on PC, need to manually add mouse events + self._mouse._handle_mouse_event() + + # Store all mouse events for the current frame + self._mouse_events = self._mouse.get_events() + if len(self._mouse_events) > 0: + self._last_mouse_event = self._mouse_events[-1] + + # Skip rendering when screen is off + if not self._should_render: + if PC: + rl.poll_input_events() + time.sleep(1 / self._target_fps) + yield False, 0.0, 0.0 + continue + + if self._render_texture: + rl.begin_texture_mode(self._render_texture) + rl.clear_background(rl.BLACK) + else: + rl.begin_drawing() + rl.clear_background(rl.BLACK) + + if self._scale != 1.0: + rl.rl_push_matrix() + rl.rl_scalef(self._scale, self._scale, 1.0) + + # Allow a Widget to still run a function regardless of the stack depth + for tick in self._nav_stack_ticks: + tick() + + # Only render top widgets + for widget in self._nav_stack[-self._nav_stack_widgets_to_render:]: + widget.render(rl.Rectangle(0, 0, self.width, self.height)) + + frame_time = rl.get_frame_time() + cpu_time = time.monotonic() - frame_start + yield True, frame_time, cpu_time + + if self._scale != 1.0: + rl.rl_pop_matrix() + + if self._render_texture: + rl.end_texture_mode() + rl.begin_drawing() + rl.clear_background(rl.BLACK) + src_rect = rl.Rectangle(0, 0, float(self._scaled_width), -float(self._scaled_height)) + dst_rect = rl.Rectangle(0, 0, float(self._scaled_width), float(self._scaled_height)) + texture = self._render_texture.texture + if texture: + if BURN_IN_MODE and self._burn_in_shader: + rl.begin_shader_mode(self._burn_in_shader) + rl.draw_texture_pro(texture, src_rect, dst_rect, rl.Vector2(0, 0), 0.0, rl.WHITE) + rl.end_shader_mode() + else: + rl.draw_texture_pro(texture, src_rect, dst_rect, rl.Vector2(0, 0), 0.0, rl.WHITE) + + if self._show_fps: + rl.draw_fps(10, 10) + + if self._show_touches: + self._draw_touch_points() + + if self._show_mouse_coords: + self._draw_mouse_coordinates(gui_app.font(FontWeight.SEMI_BOLD)) + + if self._grid_size > 0: + self._draw_grid() + + rl.end_drawing() + + if RECORD: + image = rl.load_image_from_texture(self._render_texture.texture) + data_size = image.width * image.height * 4 + data = bytes(rl.ffi.buffer(image.data, data_size)) + self._ffmpeg_queue.put(data) # Async write via background thread + rl.unload_image(image) + + self._monitor_fps() + self._frame += 1 + + if self._profile_render_frames > 0 and self._frame >= self._profile_render_frames: + self._output_render_profile() + except KeyboardInterrupt: + pass + + def font(self, font_weight: FontWeight = FontWeight.NORMAL) -> rl.Font: + return self._fonts[font_weight] + + @property + def width(self): + return self._width + + @property + def height(self): + return self._height + + def _load_fonts(self): + for font_weight_file in FontWeight: + with as_file(FONT_DIR) as fspath: + fnt_path = fspath / font_weight_file + font = rl.load_font(fnt_path.as_posix()) + if font_weight_file != FontWeight.UNIFONT: + rl.gen_texture_mipmaps(font.texture) + rl.set_texture_filter(font.texture, rl.TextureFilter.TEXTURE_FILTER_TRILINEAR) + self._fonts[font_weight_file] = font + rl.gui_set_font(self._fonts[FontWeight.NORMAL]) + + def _set_styles(self): + rl.gui_set_style(rl.GuiControl.DEFAULT, rl.GuiControlProperty.BORDER_WIDTH, 0) + rl.gui_set_style(rl.GuiControl.DEFAULT, rl.GuiDefaultProperty.TEXT_SIZE, DEFAULT_TEXT_SIZE) + rl.gui_set_style(rl.GuiControl.DEFAULT, rl.GuiDefaultProperty.BACKGROUND_COLOR, rl.color_to_int(rl.BLACK)) + rl.gui_set_style(rl.GuiControl.DEFAULT, rl.GuiControlProperty.TEXT_COLOR_NORMAL, rl.color_to_int(DEFAULT_TEXT_COLOR)) + rl.gui_set_style(rl.GuiControl.DEFAULT, rl.GuiControlProperty.BASE_COLOR_NORMAL, rl.color_to_int(rl.Color(50, 50, 50, 255))) + + def _patch_text_functions(self): + # Wrap pyray text APIs to apply a global text size scale so our px sizes match Qt + if not hasattr(rl, "_orig_draw_text_ex"): + rl._orig_draw_text_ex = rl.draw_text_ex + + def _draw_text_ex_scaled(font, text, position, font_size, spacing, tint): + font = font_fallback(font) + return rl._orig_draw_text_ex(font, text, position, font_size * FONT_SCALE, spacing, tint) + + rl.draw_text_ex = _draw_text_ex_scaled + + def _patch_scissor_mode(self): + if self._scale == 1.0: + return + + if not hasattr(rl, "_orig_begin_scissor_mode"): + rl._orig_begin_scissor_mode = rl.begin_scissor_mode + + def _begin_scissor_mode_scaled(x, y, width, height): + return rl._orig_begin_scissor_mode( + int(x * self._scale), int(y * self._scale), + int(math.ceil(width * self._scale)), int(math.ceil(height * self._scale))) + + rl.begin_scissor_mode = _begin_scissor_mode_scaled + + def _set_log_callback(self): + ffi_libc = cffi.FFI() + ffi_libc.cdef(""" + int vasprintf(char **strp, const char *fmt, void *ap); + void free(void *ptr); + """) + libc = ffi_libc.dlopen(None) + + @rl.ffi.callback("void(int, char *, void *)") + def trace_log_callback(log_level, text, args): + try: + text_addr = int(rl.ffi.cast("uintptr_t", text)) + args_addr = int(rl.ffi.cast("uintptr_t", args)) + text_libc = ffi_libc.cast("char *", text_addr) + args_libc = ffi_libc.cast("void *", args_addr) + + out = ffi_libc.new("char **") + if libc.vasprintf(out, text_libc, args_libc) >= 0 and out[0] != ffi_libc.NULL: + text_str = ffi_libc.string(out[0]).decode("utf-8", "replace") + libc.free(out[0]) + else: + text_str = rl.ffi.string(text).decode("utf-8", "replace") + except Exception as e: + text_str = f"[Log decode error: {e}]" + + if log_level == rl.TraceLogLevel.LOG_ERROR: + cloudlog.error(f"raylib: {text_str}") + elif log_level == rl.TraceLogLevel.LOG_WARNING: + cloudlog.warning(f"raylib: {text_str}") + elif log_level == rl.TraceLogLevel.LOG_INFO: + cloudlog.info(f"raylib: {text_str}") + elif log_level == rl.TraceLogLevel.LOG_DEBUG: + cloudlog.debug(f"raylib: {text_str}") + else: + cloudlog.error(f"raylib: Unknown level {log_level}: {text_str}") + + # ensure we get all the logs forwarded to us + rl.set_trace_log_level(rl.TraceLogLevel.LOG_DEBUG) + + # Store callback reference + self._trace_log_callback = trace_log_callback + rl.set_trace_log_callback(self._trace_log_callback) + + def _monitor_fps(self): + fps = rl.get_fps() + + # Log FPS drop below threshold at regular intervals + if fps < self._target_fps * FPS_DROP_THRESHOLD: + current_time = time.monotonic() + if current_time - self._last_fps_log_time >= FPS_LOG_INTERVAL: + cloudlog.warning(f"FPS dropped below {self._target_fps}: {fps}") + self._last_fps_log_time = current_time + + # Strict mode: terminate UI if FPS drops too much + if STRICT_MODE and fps < self._target_fps * FPS_CRITICAL_THRESHOLD: + cloudlog.error(f"FPS dropped critically below {fps}. Shutting down UI.") + self.close_ffmpeg() + os._exit(1) + + def _draw_touch_points(self): + current_time = time.monotonic() + + for mouse_event in self._mouse_events: + if mouse_event.left_pressed: + self._mouse_history.clear() + self._mouse_history.append(MousePosWithTime(mouse_event.pos.x * self._scale, mouse_event.pos.y * self._scale, current_time)) + + # Remove old touch points that exceed the timeout + while self._mouse_history and (current_time - self._mouse_history[0].t) > TOUCH_HISTORY_TIMEOUT: + self._mouse_history.popleft() + + if self._mouse_history: + mouse_pos = self._mouse_history[-1] + rl.draw_circle(int(mouse_pos.x), int(mouse_pos.y), 15, rl.RED) + for idx, mouse_pos in enumerate(self._mouse_history): + perc = idx / len(self._mouse_history) + color = rl.Color(min(int(255 * (1.5 - perc)), 255), int(min(255 * (perc + 0.5), 255)), 50, 255) + rl.draw_circle(int(mouse_pos.x), int(mouse_pos.y), 5, color) + + def _draw_grid(self): + grid_color = rl.Color(60, 60, 60, 255) + # Draw vertical lines + x = 0 + while x <= self._scaled_width: + rl.draw_line(x, 0, x, self._scaled_height, grid_color) + x += self._grid_size + # Draw horizontal lines + y = 0 + while y <= self._scaled_height: + rl.draw_line(0, y, self._scaled_width, y, grid_color) + y += self._grid_size + + def _output_render_profile(self): + import io + import pstats + + self._render_profiler.disable() + assert self._render_profile_start_time is not None + elapsed_ms = (time.monotonic() - self._render_profile_start_time) * 1e3 + avg_frame_time = elapsed_ms / self._frame if self._frame > 0 else 0 + + stats_stream = io.StringIO() + pstats.Stats(self._render_profiler, stream=stats_stream).sort_stats("cumtime").print_stats(PROFILE_STATS) + print("\n=== Render loop profile ===") + print(stats_stream.getvalue().rstrip()) + + green = "\033[92m" + reset = "\033[0m" + print(f"\n{green}Rendered {self._frame} frames in {elapsed_ms:.1f} ms{reset}") + print(f"{green}Average frame time: {avg_frame_time:.2f} ms ({1000/avg_frame_time:.1f} FPS){reset}") + sys.exit(0) + + def _calculate_auto_scale(self) -> float: + # Create temporary window to query monitor info + rl.init_window(1, 1, "") + w, h = rl.get_monitor_width(0), rl.get_monitor_height(0) + rl.close_window() + + if w == 0 or h == 0 or (w >= self._width and h >= self._height): + return 1.0 + + # Apply 0.95 factor for window decorations/taskbar margin + return max(0.3, min(w / self._width, h / self._height) * 0.95) + + @staticmethod + def _default_width() -> int: + return 2160 if GuiApplication.big_ui() else 536 + + @staticmethod + def _default_height() -> int: + return 1080 if GuiApplication.big_ui() else 240 + + @staticmethod + def big_ui() -> bool: + return HARDWARE.get_device_type() in ('tici', 'tizi') or BIG_UI + + +gui_app = GuiApplication() diff --git a/system/ui/lib/egl.py b/openpilot/system/ui/lib/egl.py similarity index 96% rename from system/ui/lib/egl.py rename to openpilot/system/ui/lib/egl.py index d119a8a832..69236482b0 100644 --- a/system/ui/lib/egl.py +++ b/openpilot/system/ui/lib/egl.py @@ -128,8 +128,12 @@ def init_egl() -> bool: def create_egl_image(width: int, height: int, stride: int, fd: int, uv_offset: int) -> EGLImage | None: assert _egl.initialized, "EGL not initialized" - # Duplicate fd since EGL needs it - dup_fd = os.dup(fd) + try: + # Duplicate fd since EGL needs it + dup_fd = os.dup(fd) + except OSError as e: + cloudlog.exception(f"Failed to duplicate frame fd when creating EGL image: {e}") + return None # Create image attributes for EGL img_attrs = [ diff --git a/openpilot/system/ui/lib/emoji.py b/openpilot/system/ui/lib/emoji.py new file mode 100644 index 0000000000..ad4c272c8d --- /dev/null +++ b/openpilot/system/ui/lib/emoji.py @@ -0,0 +1,55 @@ +import io +import re +import functools +from importlib.resources import as_file + +from PIL import Image, ImageDraw, ImageFont +import pyray as rl + +from openpilot.system.ui.lib.application import FONT_DIR + +_cache: dict[str, rl.Texture] = {} + +EMOJI_REGEX = re.compile( +"""[\U0001F600-\U0001F64F +\U0001F300-\U0001F5FF +\U0001F680-\U0001F6FF +\U0001F1E0-\U0001F1FF +\U00002700-\U000027BF +\U0001F900-\U0001F9FF +\U00002600-\U000026FF +\U00002300-\U000023FF +\U00002B00-\U00002BFF +\U0001FA70-\U0001FAFF +\U0001F700-\U0001F77F +\u2640-\u2642 +\u2600-\u2B55 +\u200d +\u23cf +\u23e9 +\u231a +\ufe0f +\u3030 +]+""".replace("\n", ""), + flags=re.UNICODE +) + +@functools.cache +def _load_emoji_font() -> ImageFont.FreeTypeFont: + with as_file(FONT_DIR.joinpath("NotoColorEmoji.ttf")) as font_path: + return ImageFont.truetype(io.BytesIO(font_path.read_bytes()), 109) + +def find_emoji(text): + return [(m.start(), m.end(), m.group()) for m in EMOJI_REGEX.finditer(text)] + +def emoji_tex(emoji): + if emoji not in _cache: + img = Image.new("RGBA", (128, 128), (0, 0, 0, 0)) + draw = ImageDraw.Draw(img) + draw.text((0, 0), emoji, font=_load_emoji_font(), embedded_color=True) + with io.BytesIO() as buffer: + img.save(buffer, format="PNG") + l = buffer.tell() + buffer.seek(0) + _cache[emoji] = rl.load_texture_from_image(rl.load_image_from_memory(".png", buffer.getvalue(), l)) + return _cache[emoji] diff --git a/openpilot/system/ui/lib/multilang.py b/openpilot/system/ui/lib/multilang.py new file mode 100644 index 0000000000..8d79ec3eea --- /dev/null +++ b/openpilot/system/ui/lib/multilang.py @@ -0,0 +1,214 @@ +from importlib.resources import files +import json +import os +import re +from openpilot.common.basedir import BASEDIR +from openpilot.common.swaglog import cloudlog + +try: + from openpilot.common.params import Params +except ImportError: + Params = None + +SYSTEM_UI_DIR = os.path.join(BASEDIR, "openpilot/system", "ui") +UI_DIR = files("openpilot.selfdrive.ui") +TRANSLATIONS_DIR = UI_DIR.joinpath("translations") +LANGUAGES_FILE = TRANSLATIONS_DIR.joinpath("languages.json") + +UNIFONT_LANGUAGES = [ + "th", + "zh-CHT", + "zh-CHS", + "ko", + "ja", +] + +# Plural form selectors for supported languages +PLURAL_SELECTORS = { + 'en': lambda n: 0 if n == 1 else 1, + 'de': lambda n: 0 if n == 1 else 1, + 'fr': lambda n: 0 if n <= 1 else 1, + 'pt-BR': lambda n: 0 if n <= 1 else 1, + 'es': lambda n: 0 if n == 1 else 1, + 'tr': lambda n: 0 if n == 1 else 1, + 'uk': lambda n: 0 if n % 10 == 1 and n % 100 != 11 else (1 if 2 <= n % 10 <= 4 and not 12 <= n % 100 <= 14 else 2), + 'th': lambda n: 0, + 'zh-CHT': lambda n: 0, + 'zh-CHS': lambda n: 0, + 'ko': lambda n: 0, + 'ja': lambda n: 0, +} + + +def _parse_quoted(s: str) -> str: + """Parse a PO-format quoted string.""" + s = s.strip() + if not (s.startswith('"') and s.endswith('"')): + raise ValueError(f"Expected quoted string: {s!r}") + s = s[1:-1] + result: list[str] = [] + i = 0 + while i < len(s): + if s[i] == '\\' and i + 1 < len(s): + c = s[i + 1] + if c == 'n': + result.append('\n') + elif c == 't': + result.append('\t') + elif c == '"': + result.append('"') + elif c == '\\': + result.append('\\') + else: + result.append(s[i:i + 2]) + i += 2 + else: + result.append(s[i]) + i += 1 + return ''.join(result) + + +def load_translations(path) -> tuple[dict[str, str], dict[str, list[str]]]: + """Parse a .po file and return (translations, plurals) dicts. + + translations: msgid -> msgstr + plurals: msgid -> [msgstr[0], msgstr[1], ...] + """ + with path.open(encoding='utf-8') as f: + lines = f.readlines() + + translations: dict[str, str] = {} + plurals: dict[str, list[str]] = {} + + # Parser state + msgid = msgid_plural = msgstr = "" + msgstr_plurals: dict[int, str] = {} + field: str | None = None + plural_idx = 0 + + def finish(): + nonlocal msgid, msgid_plural, msgstr, msgstr_plurals, field + if msgid: # skip header (empty msgid) + if msgid_plural: + max_idx = max(msgstr_plurals.keys()) if msgstr_plurals else 0 + plurals[msgid] = [msgstr_plurals.get(i, '') for i in range(max_idx + 1)] + else: + if msgstr: + translations[msgid] = msgstr + msgid = msgid_plural = msgstr = "" + msgstr_plurals = {} + field = None + + for raw in lines: + line = raw.strip() + + if not line: + finish() + continue + + if line.startswith('#'): + continue + + if line.startswith('msgid_plural '): + msgid_plural = _parse_quoted(line[len('msgid_plural '):]) + field = 'msgid_plural' + continue + + if line.startswith('msgid '): + msgid = _parse_quoted(line[len('msgid '):]) + field = 'msgid' + continue + + m = re.match(r'msgstr\[(\d+)]\s+(.*)', line) + if m: + plural_idx = int(m.group(1)) + msgstr_plurals[plural_idx] = _parse_quoted(m.group(2)) + field = 'msgstr_plural' + continue + + if line.startswith('msgstr '): + msgstr = _parse_quoted(line[len('msgstr '):]) + field = 'msgstr' + continue + + if line.startswith('"'): + val = _parse_quoted(line) + if field == 'msgid': + msgid += val + elif field == 'msgid_plural': + msgid_plural += val + elif field == 'msgstr': + msgstr += val + elif field == 'msgstr_plural': + msgstr_plurals[plural_idx] += val + + finish() + return translations, plurals + + +class Multilang: + def __init__(self): + self._params = Params() if Params is not None else None + self._language: str = "en" + self.languages: dict[str, str] = {} + self.codes: dict[str, str] = {} + self._translations: dict[str, str] = {} + self._plurals: dict[str, list[str]] = {} + self._plural_selector = PLURAL_SELECTORS.get('en', lambda n: 0) + self._load_languages() + + @property + def language(self) -> str: + return self._language + + def requires_unifont(self) -> bool: + """Certain languages require unifont to render their glyphs.""" + return self._language in UNIFONT_LANGUAGES + + def setup(self): + try: + po_path = TRANSLATIONS_DIR.joinpath(f'app_{self._language}.po') + self._translations, self._plurals = load_translations(po_path) + self._plural_selector = PLURAL_SELECTORS.get(self._language, lambda n: 0) + cloudlog.debug(f"Loaded translations for language: {self._language}") + except FileNotFoundError: + cloudlog.error(f"No translation file found for language: {self._language}, using default.") + self._translations = {} + self._plurals = {} + + def change_language(self, language_code: str) -> None: + self._params.put("LanguageSetting", language_code, block=True) + self._language = language_code + self.setup() + + def tr(self, text: str) -> str: + return self._translations.get(text, text) or text + + def trn(self, singular: str, plural: str, n: int) -> str: + if singular in self._plurals: + idx = self._plural_selector(n) + forms = self._plurals[singular] + if idx < len(forms) and forms[idx]: + return forms[idx] + return singular if n == 1 else plural + + def _load_languages(self): + with LANGUAGES_FILE.open(encoding='utf-8') as f: + self.languages = json.load(f) + self.codes = {v: k for k, v in self.languages.items()} + + if self._params is not None: + lang = str(self._params.get("LanguageSetting")).removeprefix("main_") + if lang in self.codes: + self._language = lang + + +multilang = Multilang() +multilang.setup() + +tr, trn = multilang.tr, multilang.trn + + +# no-op marker for static strings translated later +def tr_noop(s: str) -> str: + return s diff --git a/openpilot/system/ui/lib/networkmanager.py b/openpilot/system/ui/lib/networkmanager.py new file mode 100644 index 0000000000..d2d6b30b10 --- /dev/null +++ b/openpilot/system/ui/lib/networkmanager.py @@ -0,0 +1,64 @@ +from enum import IntEnum + + +# NetworkManager device states +class NMDeviceState(IntEnum): + # https://networkmanager.dev/docs/api/1.46/nm-dbus-types.html#NMDeviceState + UNKNOWN = 0 + UNMANAGED = 10 + UNAVAILABLE = 20 + DISCONNECTED = 30 + PREPARE = 40 + CONFIG = 50 + NEED_AUTH = 60 + IP_CONFIG = 70 + IP_CHECK = 80 + SECONDARIES = 90 + ACTIVATED = 100 + DEACTIVATING = 110 + FAILED = 120 + + +class NMDeviceStateReason(IntEnum): + # https://networkmanager.dev/docs/api/1.46/nm-dbus-types.html#NMDeviceStateReason + NONE = 0 + UNKNOWN = 1 + IP_CONFIG_UNAVAILABLE = 5 + NO_SECRETS = 7 + SUPPLICANT_DISCONNECT = 8 + SUPPLICANT_TIMEOUT = 11 + CONNECTION_REMOVED = 38 + USER_REQUESTED = 39 + SSID_NOT_FOUND = 53 + NEW_ACTIVATION = 60 + + +# NetworkManager constants +NM = "org.freedesktop.NetworkManager" +NM_PATH = '/org/freedesktop/NetworkManager' +NM_IFACE = 'org.freedesktop.NetworkManager' +NM_ACCESS_POINT_IFACE = 'org.freedesktop.NetworkManager.AccessPoint' +NM_SETTINGS_PATH = '/org/freedesktop/NetworkManager/Settings' +NM_SETTINGS_IFACE = 'org.freedesktop.NetworkManager.Settings' +NM_CONNECTION_IFACE = 'org.freedesktop.NetworkManager.Settings.Connection' +NM_ACTIVE_CONNECTION_IFACE = 'org.freedesktop.NetworkManager.Connection.Active' +NM_WIRELESS_IFACE = 'org.freedesktop.NetworkManager.Device.Wireless' +NM_PROPERTIES_IFACE = 'org.freedesktop.DBus.Properties' +NM_DEVICE_IFACE = 'org.freedesktop.NetworkManager.Device' +NM_IP4_CONFIG_IFACE = 'org.freedesktop.NetworkManager.IP4Config' + +NM_DEVICE_TYPE_WIFI = 2 +NM_DEVICE_TYPE_MODEM = 8 + +# https://developer.gnome.org/NetworkManager/1.26/nm-dbus-types.html#NM80211ApFlags +NM_802_11_AP_FLAGS_NONE = 0x0 +NM_802_11_AP_FLAGS_PRIVACY = 0x1 +NM_802_11_AP_FLAGS_WPS = 0x2 + +# https://developer.gnome.org/NetworkManager/1.26/nm-dbus-types.html#NM80211ApSecurityFlags +NM_802_11_AP_SEC_PAIR_WEP40 = 0x00000001 +NM_802_11_AP_SEC_PAIR_WEP104 = 0x00000002 +NM_802_11_AP_SEC_GROUP_WEP40 = 0x00000010 +NM_802_11_AP_SEC_GROUP_WEP104 = 0x00000020 +NM_802_11_AP_SEC_KEY_MGMT_PSK = 0x00000100 +NM_802_11_AP_SEC_KEY_MGMT_802_1X = 0x00000200 diff --git a/openpilot/system/ui/lib/scroll_panel.py b/openpilot/system/ui/lib/scroll_panel.py new file mode 100644 index 0000000000..6dd9ceaadc --- /dev/null +++ b/openpilot/system/ui/lib/scroll_panel.py @@ -0,0 +1,138 @@ +import math +import pyray as rl +from enum import IntEnum +from openpilot.system.ui.lib.application import gui_app, MouseEvent +from openpilot.common.filter_simple import FirstOrderFilter + +# Scroll constants for smooth scrolling behavior +MOUSE_WHEEL_SCROLL_SPEED = 50 +BOUNCE_RETURN_RATE = 5 # ~0.92 at 60fps +MIN_VELOCITY = 2 # px/s, changes from auto scroll to steady state +MIN_VELOCITY_FOR_CLICKING = 2 * 60 # px/s, accepts clicks while auto scrolling below this velocity +DRAG_THRESHOLD = 12 # pixels of movement to consider it a drag, not a click + +DEBUG = False + + +class ScrollState(IntEnum): + IDLE = 0 # Not dragging, content may be bouncing or scrolling with inertia + DRAGGING_CONTENT = 1 # User is actively dragging the content + + +class GuiScrollPanel: + def __init__(self): + self._scroll_state: ScrollState = ScrollState.IDLE + self._last_mouse_y: float = 0.0 + self._start_mouse_y: float = 0.0 # Track the initial mouse position for drag detection + self._offset_filter_y = FirstOrderFilter(0.0, 0.1, 1 / gui_app.target_fps) + self._velocity_filter_y = FirstOrderFilter(0.0, 0.05, 1 / gui_app.target_fps) + self._last_drag_time: float = 0.0 + + def update(self, bounds: rl.Rectangle, content: rl.Rectangle) -> float: + for mouse_event in gui_app.mouse_events: + if mouse_event.slot == 0: + self._handle_mouse_event(mouse_event, bounds, content) + + self._update_state(bounds, content) + + return float(self._offset_filter_y.x) + + def _update_state(self, bounds: rl.Rectangle, content: rl.Rectangle): + if DEBUG: + rl.draw_rectangle_lines(0, 0, abs(int(self._velocity_filter_y.x)), 10, rl.RED) + + # Handle mouse wheel only when the mouse cursor is over this panel + mouse_wheel = rl.get_mouse_wheel_move() + if mouse_wheel != 0: + mouse_pos = rl.get_mouse_position() + if rl.check_collision_point_rec(mouse_pos, bounds): + self._offset_filter_y.x += mouse_wheel * MOUSE_WHEEL_SCROLL_SPEED + + max_scroll_distance = max(0, content.height - bounds.height) + if self._scroll_state == ScrollState.IDLE: + above_bounds, below_bounds = self._check_bounds(bounds, content) + + # Decay velocity when idle + if abs(self._velocity_filter_y.x) > MIN_VELOCITY: + # Faster decay if bouncing back from out of bounds + friction = math.exp(-BOUNCE_RETURN_RATE * 1 / gui_app.target_fps) + self._velocity_filter_y.x *= friction ** 2 if (above_bounds or below_bounds) else friction + else: + self._velocity_filter_y.x = 0.0 + + if above_bounds or below_bounds: + if above_bounds: + self._offset_filter_y.update(0) + else: + self._offset_filter_y.update(-max_scroll_distance) + + self._offset_filter_y.x += self._velocity_filter_y.x / gui_app.target_fps + + elif self._scroll_state == ScrollState.DRAGGING_CONTENT: + # Mouse not moving, decay velocity + if not len(gui_app.mouse_events): + self._velocity_filter_y.update(0.0) + + # Settle to exact bounds + if abs(self._offset_filter_y.x) < 1e-2: + self._offset_filter_y.x = 0.0 + elif abs(self._offset_filter_y.x + max_scroll_distance) < 1e-2: + self._offset_filter_y.x = -max_scroll_distance + + def _handle_mouse_event(self, mouse_event: MouseEvent, bounds: rl.Rectangle, content: rl.Rectangle): + if self._scroll_state == ScrollState.IDLE: + if rl.check_collision_point_rec(mouse_event.pos, bounds): + if mouse_event.left_pressed: + self._start_mouse_y = mouse_event.pos.y + # Interrupt scrolling with new drag + # TODO: stop scrolling with any tap, need to fix is_touch_valid + if abs(self._velocity_filter_y.x) > MIN_VELOCITY_FOR_CLICKING: + self._scroll_state = ScrollState.DRAGGING_CONTENT + # Start velocity at initial measurement for more immediate response + self._velocity_filter_y.initialized = False + + if mouse_event.left_down: + if abs(mouse_event.pos.y - self._start_mouse_y) > DRAG_THRESHOLD: + self._scroll_state = ScrollState.DRAGGING_CONTENT + # Start velocity at initial measurement for more immediate response + self._velocity_filter_y.initialized = False + + elif self._scroll_state == ScrollState.DRAGGING_CONTENT: + if mouse_event.left_released: + self._scroll_state = ScrollState.IDLE + else: + delta_y = mouse_event.pos.y - self._last_mouse_y + above_bounds, below_bounds = self._check_bounds(bounds, content) + # Rubber banding effect when out of bands + if above_bounds or below_bounds: + delta_y /= 3 + + self._offset_filter_y.x += delta_y + + # Track velocity for inertia + dt = mouse_event.t - self._last_drag_time + if dt > 0: + drag_velocity = delta_y / dt + self._velocity_filter_y.update(drag_velocity) + + # TODO: just store last mouse event! + self._last_drag_time = mouse_event.t + self._last_mouse_y = mouse_event.pos.y + + def _check_bounds(self, bounds: rl.Rectangle, content: rl.Rectangle) -> tuple[bool, bool]: + max_scroll_distance = max(0, content.height - bounds.height) + above_bounds = self._offset_filter_y.x > 0 + below_bounds = self._offset_filter_y.x < -max_scroll_distance + return above_bounds, below_bounds + + def is_touch_valid(self): + return self._scroll_state == ScrollState.IDLE and abs(self._velocity_filter_y.x) < MIN_VELOCITY_FOR_CLICKING + + def set_offset(self, position: float) -> None: + self._offset_filter_y.x = position + self._velocity_filter_y.x = 0.0 + self._scroll_state = ScrollState.IDLE + + @property + def offset(self) -> float: + return float(self._offset_filter_y.x) diff --git a/openpilot/system/ui/lib/scroll_panel2.py b/openpilot/system/ui/lib/scroll_panel2.py new file mode 100644 index 0000000000..b6193672c4 --- /dev/null +++ b/openpilot/system/ui/lib/scroll_panel2.py @@ -0,0 +1,268 @@ +import os +import math +import pyray as rl +from collections.abc import Callable +from enum import Enum +from typing import cast +from openpilot.system.ui.lib.application import gui_app, MouseEvent +from openpilot.common.hardware import TICI +from collections import deque + +MIN_VELOCITY = 10 # px/s, changes from auto scroll to steady state +MIN_VELOCITY_FOR_CLICKING = 2 * 60 # px/s, accepts clicks while auto scrolling below this velocity +MIN_DRAG_PIXELS = 12 +AUTO_SCROLL_TC_SNAP = 0.025 +AUTO_SCROLL_TC = 0.18 +BOUNCE_RETURN_RATE = 10.0 +SNAP_RATE = 6.3 # matches previous Scroller snapping. exp rate of approach to snap target, 1/s +REJECT_DECELERATION_FACTOR = 3 +MAX_SPEED = 10000.0 # px/s + +DEBUG = os.getenv("DEBUG_SCROLL", "0") == "1" + + +# Weights older (steadier) velocity samples more heavily on release. +# Finger-lift samples are noisy; trusting earlier samples gives consistent fling velocity. +# Reverse-engineered from iOS UIScrollView (tuned at 120Hz touch) by Flutter team: +# https://github.com/flutter/flutter/pull/60501 +# 3 samples ≈ 25ms at 120Hz (iOS) / ~21ms at 140Hz (comma). Scale if touch rate changes. +def weighted_velocity(buffer: deque) -> float: + if len(buffer) >= 3: + return buffer[-3] * 0.6 + buffer[-2] * 0.35 + buffer[-1] * 0.05 + elif len(buffer) == 2: + return buffer[-2] * 0.7 + buffer[-1] * 0.3 + elif len(buffer) == 1: + return buffer[-1] + return 0.0 + + +# from https://ariya.io/2011/10/flick-list-with-its-momentum-scrolling-and-deceleration +class ScrollState(Enum): + STEADY = 0 + PRESSED = 1 + MANUAL_SCROLL = 2 + AUTO_SCROLL = 3 + + +class GuiScrollPanel2: + def __init__(self, horizontal: bool = True) -> None: + self._horizontal = horizontal + self._state = ScrollState.STEADY + self._offset: rl.Vector2 = rl.Vector2(0, 0) + self._initial_click_event: MouseEvent | None = None + self._previous_mouse_event: MouseEvent | None = None + self._velocity = 0.0 # pixels per second + self._velocity_buffer: deque[float] = deque(maxlen=12 if TICI else 6) + self._enabled: bool | Callable[[], bool] = True + + def set_enabled(self, enabled: bool | Callable[[], bool]) -> None: + self._enabled = enabled + + @property + def enabled(self) -> bool: + return self._enabled() if callable(self._enabled) else self._enabled + + def update(self, bounds: rl.Rectangle, content_size: float, snap_target: float | None = None) -> float: + if DEBUG: + print('Old state:', self._state) + + bounds_size = bounds.width if self._horizontal else bounds.height + + for mouse_event in gui_app.mouse_events: + self._handle_mouse_event(mouse_event, bounds, bounds_size, content_size) + self._previous_mouse_event = mouse_event + + self._update_state(bounds_size, content_size, snap_target) + + if DEBUG: + print('Velocity:', self._velocity) + print('Offset X:', self._offset.x, 'Y:', self._offset.y) + print('New state:', self._state) + print() + return self.get_offset() + + def _get_offset_bounds(self, bounds_size: float, content_size: float) -> tuple[float, float]: + """Returns (max_offset, min_offset) for the given bounds and content size.""" + return 0.0, min(0.0, bounds_size - content_size) + + def _update_state(self, bounds_size: float, content_size: float, snap_target: float | None) -> None: + """Runs per render frame, independent of mouse events. Updates auto-scrolling state and velocity.""" + max_offset, min_offset = self._get_offset_bounds(bounds_size, content_size) + + if self._state == ScrollState.STEADY: + # if we find ourselves out of bounds, scroll back in (from external layout dimension changes, etc.) + if self.get_offset() > max_offset or self.get_offset() < min_offset: + self._state = ScrollState.AUTO_SCROLL + + elif self._state == ScrollState.AUTO_SCROLL: + # simple exponential return if out of bounds + # out of bounds is handled by snapping, so skip if set + out_of_bounds = self.get_offset() > max_offset or self.get_offset() < min_offset + if out_of_bounds and snap_target is None: + target = max_offset if self.get_offset() > max_offset else min_offset + + dt = rl.get_frame_time() or 1e-6 + factor = 1.0 - math.exp(-BOUNCE_RETURN_RATE * dt) + + dist = target - self.get_offset() + self.set_offset(self.get_offset() + dist * factor) # ease toward the edge + self._velocity *= (1.0 - factor) # damp any leftover fling + + # Steady once we are close enough to the target + if abs(dist) < 1 and abs(self._velocity) < MIN_VELOCITY: + self.set_offset(target) + self._velocity = 0.0 + self._state = ScrollState.STEADY + + elif abs(self._velocity) < MIN_VELOCITY: + self._velocity = 0.0 + self._state = ScrollState.STEADY + + # Update the offset based on the current velocity + dt = rl.get_frame_time() + self.set_offset(self.get_offset() + self._velocity * dt) # Adjust the offset based on velocity + # fast decay in snap mode so velocity yields to the snap pull instead of fighting it + auto_scroll_tc = AUTO_SCROLL_TC_SNAP if snap_target is not None else AUTO_SCROLL_TC + alpha = 1 - (dt / (auto_scroll_tc + dt)) + self._velocity *= alpha + + # Ease toward snap target when not in user control. Composes with velocity coast above: + # high velocity dominates initially, snap dominates as velocity decays. + if snap_target is not None and self._state not in (ScrollState.PRESSED, ScrollState.MANUAL_SCROLL): + snap_target = max(min_offset, min(max_offset, snap_target)) + dist = snap_target - self.get_offset() + if abs(dist) < 1: # finished snap + self.set_offset(snap_target) + else: + dt = rl.get_frame_time() or 1e-6 + factor = 1.0 - math.exp(-SNAP_RATE * dt) + self.set_offset(self.get_offset() + dist * factor) + + def _handle_mouse_event(self, mouse_event: MouseEvent, bounds: rl.Rectangle, bounds_size: float, + content_size: float) -> None: + max_offset, min_offset = self._get_offset_bounds(bounds_size, content_size) + # simple exponential return if out of bounds + out_of_bounds = self.get_offset() > max_offset or self.get_offset() < min_offset + if DEBUG: + print('Mouse event:', mouse_event) + + mouse_pos = self._get_mouse_pos(mouse_event) + + if not self.enabled: + # Reset state if not enabled + self._state = ScrollState.STEADY + self._velocity = 0.0 + self._velocity_buffer.clear() + + elif self._state == ScrollState.STEADY: + if rl.check_collision_point_rec(mouse_event.pos, bounds): + if mouse_event.left_pressed: + self._state = ScrollState.PRESSED + self._initial_click_event = mouse_event + + elif self._state == ScrollState.PRESSED: + initial_click_pos = self._get_mouse_pos(cast(MouseEvent, self._initial_click_event)) + diff = abs(mouse_pos - initial_click_pos) + if mouse_event.left_released: + # Special handling for down and up clicks across two frames + # TODO: not sure what that means or if it's accurate anymore + if out_of_bounds: + self._state = ScrollState.AUTO_SCROLL + elif diff <= MIN_DRAG_PIXELS: + self._state = ScrollState.STEADY + else: + self._state = ScrollState.MANUAL_SCROLL + elif diff > MIN_DRAG_PIXELS: + self._state = ScrollState.MANUAL_SCROLL + + elif self._state == ScrollState.MANUAL_SCROLL: + if mouse_event.left_released: + # Touch rejection: when releasing finger after swiping and stopping, panel + # reports a few erroneous touch events with high velocity, try to ignore. + + # If velocity decelerates very quickly, assume user doesn't intend to auto scroll. + # Catches two cases: 1) swipe, stop finger, then lift (stale high velocity in buffer) + # 2) dirty finger lift where finger rotates/slides producing spurious velocity spike. + # TODO: this heuristic false-positives on fast swipes because 140Hz touch polling + # jitter causes velocity to oscillate (not real deceleration). Better approaches: + # - Use evdev kernel timestamps to eliminate velocity oscillation at the source + # - Replace with a time-since-last-event check (40ms timeout) for swipe-stop-lift + high_decel = False + if len(self._velocity_buffer) > 2: + # We limit max to first half since final few velocities can surpass first few + abs_velocity_buffer = [(abs(v), i) for i, v in enumerate(self._velocity_buffer)] + max_idx = max(abs_velocity_buffer[:len(abs_velocity_buffer) // 2])[1] + min_idx = min(abs_velocity_buffer)[1] + if DEBUG: + print('min_idx:', min_idx, 'max_idx:', max_idx, 'velocity buffer:', self._velocity_buffer) + if (abs(self._velocity_buffer[min_idx]) * REJECT_DECELERATION_FACTOR < abs(self._velocity_buffer[max_idx]) and + max_idx < min_idx): + if DEBUG: + print('deceleration too high, going to STEADY') + high_decel = True + + self._velocity = weighted_velocity(self._velocity_buffer) + + # If final velocity is below some threshold, switch to steady state too + low_speed = abs(self._velocity) <= MIN_VELOCITY_FOR_CLICKING * 1.5 # plus some margin + + if out_of_bounds or not (high_decel or low_speed): + self._state = ScrollState.AUTO_SCROLL + else: + # TODO: we should just set velocity and let autoscroll go back to steady. delays one frame but who cares + self._velocity = 0.0 + self._state = ScrollState.STEADY + self._velocity_buffer.clear() + else: + # Update velocity for when we release the mouse button. + # Do not update velocity on the same frame the mouse was released + previous_mouse_pos = self._get_mouse_pos(cast(MouseEvent, self._previous_mouse_event)) + delta_x = mouse_pos - previous_mouse_pos + delta_t = max((mouse_event.t - cast(MouseEvent, self._previous_mouse_event).t), 1e-6) + self._velocity = delta_x / delta_t + self._velocity = max(-MAX_SPEED, min(MAX_SPEED, self._velocity)) + self._velocity_buffer.append(self._velocity) + + # rubber-banding: reduce dragging when out of bounds + # TODO: this drifts when dragging quickly + if out_of_bounds: + delta_x *= 0.25 + + # Update the offset based on the mouse movement + # Use internal _offset directly to preserve precision (don't round via get_offset()) + # TODO: make get_offset return float + current_offset = self._offset.x if self._horizontal else self._offset.y + self.set_offset(current_offset + delta_x) + + elif self._state == ScrollState.AUTO_SCROLL: + if mouse_event.left_pressed: + # Decide whether to click or scroll (block click if moving too fast) + if abs(self._velocity) <= MIN_VELOCITY_FOR_CLICKING: + # Traveling slow enough, click + self._state = ScrollState.PRESSED + self._initial_click_event = mouse_event + else: + # Go straight into manual scrolling to block erroneous input + self._state = ScrollState.MANUAL_SCROLL + # Reset velocity for touch down and up events that happen in back-to-back frames + self._velocity = 0.0 + + def _get_mouse_pos(self, mouse_event: MouseEvent) -> float: + return mouse_event.pos.x if self._horizontal else mouse_event.pos.y + + def get_offset(self) -> float: + return self._offset.x if self._horizontal else self._offset.y + + def set_offset(self, value: float) -> None: + if self._horizontal: + self._offset.x = value + else: + self._offset.y = value + + @property + def state(self) -> ScrollState: + return self._state + + def is_touch_valid(self) -> bool: + # MIN_VELOCITY_FOR_CLICKING is checked in auto-scroll state + return bool(self._state != ScrollState.MANUAL_SCROLL) diff --git a/openpilot/system/ui/lib/shader_polygon.py b/openpilot/system/ui/lib/shader_polygon.py new file mode 100644 index 0000000000..de729d6aae --- /dev/null +++ b/openpilot/system/ui/lib/shader_polygon.py @@ -0,0 +1,238 @@ +import pyray as rl +import numpy as np +from dataclasses import dataclass +from typing import Any, Optional, cast +from openpilot.system.ui.lib.application import gui_app, GL_VERSION + +MAX_GRADIENT_COLORS = 20 # includes stops as well + + +@dataclass +class Gradient: + start: tuple[float, float] + end: tuple[float, float] + colors: list[rl.Color] + stops: list[float] + + def __post_init__(self): + if len(self.colors) > MAX_GRADIENT_COLORS: + self.colors = self.colors[:MAX_GRADIENT_COLORS] + print(f"Warning: Gradient colors truncated to {MAX_GRADIENT_COLORS} entries") + + if len(self.stops) > MAX_GRADIENT_COLORS: + self.stops = self.stops[:MAX_GRADIENT_COLORS] + print(f"Warning: Gradient stops truncated to {MAX_GRADIENT_COLORS} entries") + + if not len(self.stops): + color_count = min(len(self.colors), MAX_GRADIENT_COLORS) + self.stops = [i / max(1, color_count - 1) for i in range(color_count)] + + +FRAGMENT_SHADER = GL_VERSION + """ +in vec2 fragTexCoord; +out vec4 finalColor; + +uniform vec4 fillColor; + +// Gradient line defined in *screen pixels* +uniform int useGradient; +uniform vec2 gradientStart; // e.g. vec2(0, 0) +uniform vec2 gradientEnd; // e.g. vec2(0, screenHeight) +uniform vec4 gradientColors[20]; +uniform float gradientStops[20]; +uniform int gradientColorCount; + +vec4 getGradientColor(vec2 p) { + // Compute t from screen-space position + vec2 d = gradientStart - gradientEnd; + float len2 = max(dot(d, d), 1e-6); + float t = clamp(dot(p - gradientEnd, d) / len2, 0.0, 1.0); + + // Clamp to range + float t0 = gradientStops[0]; + float tn = gradientStops[gradientColorCount-1]; + if (t <= t0) return gradientColors[0]; + if (t >= tn) return gradientColors[gradientColorCount-1]; + + for (int i = 0; i < gradientColorCount - 1; i++) { + float a = gradientStops[i]; + float b = gradientStops[i+1]; + if (t >= a && t <= b) { + float k = (t - a) / max(b - a, 1e-6); + return mix(gradientColors[i], gradientColors[i+1], k); + } + } + + return gradientColors[gradientColorCount-1]; +} + +void main() { + // TODO: do proper antialiasing + finalColor = useGradient == 1 ? getGradientColor(gl_FragCoord.xy) : fillColor; +} +""" + +# Default vertex shader +VERTEX_SHADER = GL_VERSION + """ +in vec3 vertexPosition; +in vec2 vertexTexCoord; +out vec2 fragTexCoord; +uniform mat4 mvp; + +void main() { + fragTexCoord = vertexTexCoord; + gl_Position = mvp * vec4(vertexPosition, 1.0); +} +""" + +UNIFORM_INT = rl.ShaderUniformDataType.SHADER_UNIFORM_INT +UNIFORM_FLOAT = rl.ShaderUniformDataType.SHADER_UNIFORM_FLOAT +UNIFORM_VEC2 = rl.ShaderUniformDataType.SHADER_UNIFORM_VEC2 +UNIFORM_VEC4 = rl.ShaderUniformDataType.SHADER_UNIFORM_VEC4 + + +class ShaderState: + _instance: Any = None + + @classmethod + def get_instance(cls): + if cls._instance is None: + cls._instance = cls() + return cls._instance + + def __init__(self): + if ShaderState._instance is not None: + raise Exception("This class is a singleton. Use get_instance() instead.") + + self.initialized = False + self.shader = None + + # Shader uniform locations + self.locations = { + 'fillColor': None, + 'useGradient': None, + 'gradientStart': None, + 'gradientEnd': None, + 'gradientColors': None, + 'gradientStops': None, + 'gradientColorCount': None, + 'mvp': None, + } + + # Pre-allocated FFI objects + self.fill_color_ptr = rl.ffi.new("float[]", [0.0, 0.0, 0.0, 0.0]) + self.use_gradient_ptr = rl.ffi.new("int[]", [0]) + self.color_count_ptr = rl.ffi.new("int[]", [0]) + self.gradient_colors_ptr = rl.ffi.new("float[]", MAX_GRADIENT_COLORS * 4) + self.gradient_stops_ptr = rl.ffi.new("float[]", MAX_GRADIENT_COLORS) + + def initialize(self): + if self.initialized: + return + + self.shader = rl.load_shader_from_memory(VERTEX_SHADER, FRAGMENT_SHADER) + + # Cache all uniform locations + for uniform in self.locations.keys(): + self.locations[uniform] = rl.get_shader_location(self.shader, uniform) + + # Orthographic MVP (origin top-left) + proj = rl.matrix_ortho(0, gui_app.width, gui_app.height, 0, -1, 1) + rl.set_shader_value_matrix(self.shader, self.locations['mvp'], proj) + + self.initialized = True + + def cleanup(self): + if not self.initialized: + return + if self.shader: + rl.unload_shader(self.shader) + self.shader = None + + self.initialized = False + + +def _configure_shader_color(state: ShaderState, color: Optional[rl.Color], # noqa: UP045 # rl.Color is a function, so `rl.Color | None` fails + gradient: Gradient | None, origin_rect: rl.Rectangle): + assert (color is not None) != (gradient is not None), "Either color or gradient must be provided" + + use_gradient = 1 if (gradient is not None and len(gradient.colors) >= 1) else 0 + state.use_gradient_ptr[0] = use_gradient + rl.set_shader_value(state.shader, state.locations['useGradient'], state.use_gradient_ptr, UNIFORM_INT) + + if use_gradient: + gradient = cast(Gradient, gradient) + state.color_count_ptr[0] = len(gradient.colors) + for i in range(len(gradient.colors)): + c = gradient.colors[i] + base = i * 4 + state.gradient_colors_ptr[base:base + 4] = [c.r / 255.0, c.g / 255.0, c.b / 255.0, c.a / 255.0] + rl.set_shader_value_v(state.shader, state.locations['gradientColors'], state.gradient_colors_ptr, UNIFORM_VEC4, len(gradient.colors)) + + for i in range(len(gradient.stops)): + s = float(gradient.stops[i]) + state.gradient_stops_ptr[i] = 0.0 if s < 0.0 else 1.0 if s > 1.0 else s + rl.set_shader_value_v(state.shader, state.locations['gradientStops'], state.gradient_stops_ptr, UNIFORM_FLOAT, len(gradient.stops)) + rl.set_shader_value(state.shader, state.locations['gradientColorCount'], state.color_count_ptr, UNIFORM_INT) + + # Map normalized start/end to screen pixels + start_vec = rl.Vector2(origin_rect.x + gradient.start[0] * origin_rect.width, origin_rect.y + gradient.start[1] * origin_rect.height) + end_vec = rl.Vector2(origin_rect.x + gradient.end[0] * origin_rect.width, origin_rect.y + gradient.end[1] * origin_rect.height) + rl.set_shader_value(state.shader, state.locations['gradientStart'], start_vec, UNIFORM_VEC2) + rl.set_shader_value(state.shader, state.locations['gradientEnd'], end_vec, UNIFORM_VEC2) + else: + color = color or rl.WHITE + state.fill_color_ptr[0:4] = [color.r / 255.0, color.g / 255.0, color.b / 255.0, color.a / 255.0] + rl.set_shader_value(state.shader, state.locations['fillColor'], state.fill_color_ptr, UNIFORM_VEC4) + + +def triangulate(pts: np.ndarray) -> list[tuple[float, float]]: + """Only supports simple polygons with two chains (ribbon).""" + + # TODO: consider deduping close screenspace points + # interleave points to produce a triangle strip + # assert len(pts) % 2 == 0, "Interleaving expects even number of points" + if len(pts) % 2 != 0: + pts = pts[:-1] + + tri_strip = [] + for i in range(len(pts) // 2): + tri_strip.append(pts[i]) + tri_strip.append(pts[-i - 1]) + + return cast(list, np.array(tri_strip).tolist()) + + +def draw_polygon(origin_rect: rl.Rectangle, points: np.ndarray, + color: Optional[rl.Color] = None, gradient: Gradient | None = None): # noqa: UP045 # rl.Color is a function, so `rl.Color | None` fails + + """ + Draw a ribbon polygon (two chains) with a triangle strip and gradient. + - Input must be [L0..Lk-1, Rk-1..R0], even count, no crossings/holes. + """ + if len(points) < 3: + return + + # Initialize shader on-demand + state = ShaderState.get_instance() + state.initialize() + + # Ensure (N,2) float32 contiguous array + pts = np.ascontiguousarray(points, dtype=np.float32) + assert pts.ndim == 2 and pts.shape[1] == 2, "points must be (N,2)" + + # Configure gradient shader + _configure_shader_color(state, color, gradient, origin_rect) + + # Triangulate via interleaving + tri_strip = triangulate(pts) + + # Draw strip, color here doesn't matter + rl.begin_shader_mode(state.shader) + rl.draw_triangle_strip(tri_strip, len(tri_strip), rl.WHITE) + rl.end_shader_mode() + + +def cleanup_shader_resources(): + state = ShaderState.get_instance() + state.cleanup() diff --git a/openpilot/system/ui/lib/tests/test_handle_state_change.py b/openpilot/system/ui/lib/tests/test_handle_state_change.py new file mode 100644 index 0000000000..69aae6fdf3 --- /dev/null +++ b/openpilot/system/ui/lib/tests/test_handle_state_change.py @@ -0,0 +1,906 @@ +"""Tests for WifiManager._handle_state_change. + +Tests the state machine in isolation by constructing a WifiManager with mocked +DBus, then calling _handle_state_change directly with NM state transitions. +""" +import pytest +from jeepney.low_level import MessageType +from pytest_mock import MockerFixture + +from openpilot.system.ui.lib.networkmanager import NMDeviceState, NMDeviceStateReason +from openpilot.system.ui.lib.wifi_manager import WifiManager, WifiState, ConnectStatus + + +def _make_wm(mocker: MockerFixture, connections=None): + """Create a WifiManager with only the fields _handle_state_change touches.""" + mocker.patch.object(WifiManager, '_initialize') + wm = WifiManager.__new__(WifiManager) + wm._exit = True # prevent stop() from doing anything in __del__ + wm._conn_monitor = mocker.MagicMock() + wm._connections = dict(connections or {}) + wm._wifi_state = WifiState() + wm._user_epoch = 0 + wm._callback_queue = [] + wm._need_auth = [] + wm._activated = [] + wm._update_networks = mocker.MagicMock() + wm._update_active_connection_info = mocker.MagicMock() + wm._get_active_wifi_connection = mocker.MagicMock(return_value=(None, None)) + return wm + + +def fire(wm: WifiManager, new_state: int, prev_state: int = NMDeviceState.UNKNOWN, + reason: int = NMDeviceStateReason.NONE) -> None: + """Feed a state change into the handler.""" + wm._handle_state_change(new_state, prev_state, reason) + + +def fire_wpa_connect(wm: WifiManager) -> None: + """WPA handshake then IP negotiation through ACTIVATED, as seen on device.""" + fire(wm, NMDeviceState.NEED_AUTH) + fire(wm, NMDeviceState.PREPARE, prev_state=NMDeviceState.NEED_AUTH) + fire(wm, NMDeviceState.CONFIG) + fire(wm, NMDeviceState.IP_CONFIG) + fire(wm, NMDeviceState.IP_CHECK) + fire(wm, NMDeviceState.SECONDARIES) + fire(wm, NMDeviceState.ACTIVATED) + + +# --------------------------------------------------------------------------- +# Basic transitions +# --------------------------------------------------------------------------- + +class TestDisconnected: + def test_generic_disconnect_clears_state(self, mocker): + wm = _make_wm(mocker) + wm._wifi_state = WifiState(ssid="Net", status=ConnectStatus.CONNECTED) + + fire(wm, NMDeviceState.DISCONNECTED, reason=NMDeviceStateReason.UNKNOWN) + + assert wm._wifi_state.ssid is None + assert wm._wifi_state.status == ConnectStatus.DISCONNECTED + wm._update_networks.assert_not_called() + + def test_new_activation_is_noop(self, mocker): + """NEW_ACTIVATION means NM is about to connect to another network — don't clear.""" + wm = _make_wm(mocker) + wm._wifi_state = WifiState(ssid="OldNet", status=ConnectStatus.CONNECTED) + + fire(wm, NMDeviceState.DISCONNECTED, reason=NMDeviceStateReason.NEW_ACTIVATION) + + assert wm._wifi_state.ssid == "OldNet" + assert wm._wifi_state.status == ConnectStatus.CONNECTED + + def test_connection_removed_keeps_other_connecting(self, mocker): + """Forget A while connecting to B: CONNECTION_REMOVED for A must not clear B.""" + wm = _make_wm(mocker, connections={"B": "/path/B"}) + wm._set_connecting("B") + + fire(wm, NMDeviceState.DISCONNECTED, reason=NMDeviceStateReason.CONNECTION_REMOVED) + + assert wm._wifi_state.ssid == "B" + assert wm._wifi_state.status == ConnectStatus.CONNECTING + + def test_connection_removed_clears_when_forgotten(self, mocker): + """Forget A: A is no longer in _connections, so state should clear.""" + wm = _make_wm(mocker, connections={}) + wm._wifi_state = WifiState(ssid="A", status=ConnectStatus.CONNECTED) + + fire(wm, NMDeviceState.DISCONNECTED, reason=NMDeviceStateReason.CONNECTION_REMOVED) + + assert wm._wifi_state.ssid is None + assert wm._wifi_state.status == ConnectStatus.DISCONNECTED + + +class TestDeactivating: + def test_deactivating_noop_for_non_connection_removed(self, mocker): + """DEACTIVATING with non-CONNECTION_REMOVED reason is a no-op.""" + wm = _make_wm(mocker) + wm._wifi_state = WifiState(ssid="Net", status=ConnectStatus.CONNECTED) + + fire(wm, NMDeviceState.DEACTIVATING, reason=NMDeviceStateReason.USER_REQUESTED) + + assert wm._wifi_state.ssid == "Net" + assert wm._wifi_state.status == ConnectStatus.CONNECTED + + @pytest.mark.parametrize("status, expected_clears", [ + (ConnectStatus.CONNECTED, True), + (ConnectStatus.CONNECTING, False), + ]) + def test_deactivating_connection_removed(self, mocker, status, expected_clears): + """DEACTIVATING(CONNECTION_REMOVED) clears CONNECTED but preserves CONNECTING. + + CONNECTED: forgetting the current network. The forgotten callback fires between + DEACTIVATING and DISCONNECTED — must clear here so the UI doesn't flash "connected" + after the eager _network_forgetting flag resets. + + CONNECTING: forget A while connecting to B. DEACTIVATING fires for A's removal, + but B's CONNECTING state must be preserved. + """ + wm = _make_wm(mocker, connections={"B": "/path/B"}) + wm._wifi_state = WifiState(ssid="B" if status == ConnectStatus.CONNECTING else "A", status=status) + + fire(wm, NMDeviceState.DEACTIVATING, reason=NMDeviceStateReason.CONNECTION_REMOVED) + + if expected_clears: + assert wm._wifi_state.ssid is None + assert wm._wifi_state.status == ConnectStatus.DISCONNECTED + else: + assert wm._wifi_state.ssid == "B" + assert wm._wifi_state.status == ConnectStatus.CONNECTING + + +class TestPrepareConfig: + def test_user_initiated_skips_dbus_lookup(self, mocker): + """User called _set_connecting('B') — PREPARE must not overwrite via DBus. + + Reproduced on device: rapidly tap A then B. PREPARE's DBus lookup returns A's + stale conn_path, overwriting ssid to A for 1-2 frames. UI shows the "connecting" + indicator briefly jump to the wrong network row then back. + """ + wm = _make_wm(mocker, connections={"A": "/path/A", "B": "/path/B"}) + wm._set_connecting("B") + wm._get_active_wifi_connection.return_value = ("/path/A", {}) + + fire(wm, NMDeviceState.PREPARE) + + assert wm._wifi_state.ssid == "B" + assert wm._wifi_state.status == ConnectStatus.CONNECTING + wm._get_active_wifi_connection.assert_not_called() + + @pytest.mark.parametrize("state", [NMDeviceState.PREPARE, NMDeviceState.CONFIG]) + def test_auto_connect_looks_up_ssid(self, mocker, state): + """Auto-connection (ssid=None): PREPARE and CONFIG must look up ssid from NM.""" + wm = _make_wm(mocker, connections={"AutoNet": "/path/auto"}) + wm._get_active_wifi_connection.return_value = ("/path/auto", {}) + + fire(wm, state) + + assert wm._wifi_state.ssid == "AutoNet" + assert wm._wifi_state.status == ConnectStatus.CONNECTING + + def test_auto_connect_dbus_fails(self, mocker): + """Auto-connection but DBus returns None: ssid stays None, status CONNECTING.""" + wm = _make_wm(mocker) + + fire(wm, NMDeviceState.PREPARE) + + assert wm._wifi_state.ssid is None + assert wm._wifi_state.status == ConnectStatus.CONNECTING + + def test_auto_connect_conn_path_not_in_connections(self, mocker): + """DBus returns a conn_path that doesn't match any known connection.""" + wm = _make_wm(mocker, connections={"Other": "/path/other"}) + wm._get_active_wifi_connection.return_value = ("/path/unknown", {}) + + fire(wm, NMDeviceState.PREPARE) + + assert wm._wifi_state.ssid is None + assert wm._wifi_state.status == ConnectStatus.CONNECTING + + +class TestNeedAuth: + def test_wrong_password_fires_callback(self, mocker): + """NEED_AUTH+SUPPLICANT_DISCONNECT from CONFIG = real wrong password.""" + wm = _make_wm(mocker) + cb = mocker.MagicMock() + wm.add_callbacks(need_auth=cb) + wm._set_connecting("SecNet") + + fire(wm, NMDeviceState.NEED_AUTH, prev_state=NMDeviceState.CONFIG, + reason=NMDeviceStateReason.SUPPLICANT_DISCONNECT) + + assert wm._wifi_state.status == ConnectStatus.DISCONNECTED + assert len(wm._callback_queue) == 1 + wm.process_callbacks() + cb.assert_called_once_with("SecNet") + + def test_failed_no_secrets_fires_callback(self, mocker): + """FAILED+NO_SECRETS = wrong password (weak/gone network). + + Confirmed on device: also fires when a hotspot turns off during connection. + NM can't complete the WPA handshake (AP vanished) and reports NO_SECRETS + rather than SSID_NOT_FOUND. The need_auth callback fires, so the UI shows + "wrong password" — a false positive, but same signal path. + + Real device sequence (new connection, hotspot turned off immediately): + PREPARE → CONFIG → NEED_AUTH(CONFIG, NONE) → PREPARE(NEED_AUTH) → CONFIG + → NEED_AUTH(CONFIG, NONE) → FAILED(NEED_AUTH, NO_SECRETS) → DISCONNECTED(FAILED, NONE) + """ + wm = _make_wm(mocker) + cb = mocker.MagicMock() + wm.add_callbacks(need_auth=cb) + wm._set_connecting("WeakNet") + + fire(wm, NMDeviceState.FAILED, reason=NMDeviceStateReason.NO_SECRETS) + + assert wm._wifi_state.status == ConnectStatus.DISCONNECTED + assert len(wm._callback_queue) == 1 + wm.process_callbacks() + cb.assert_called_once_with("WeakNet") + + def test_need_auth_then_failed_no_double_fire(self, mocker): + """Real device sends NEED_AUTH(SUPPLICANT_DISCONNECT) then FAILED(NO_SECRETS) back-to-back. + + The first clears ssid, so the second must not fire a duplicate callback. + Real device sequence: NEED_AUTH(CONFIG, SUPPLICANT_DISCONNECT) → FAILED(NEED_AUTH, NO_SECRETS) + """ + wm = _make_wm(mocker) + cb = mocker.MagicMock() + wm.add_callbacks(need_auth=cb) + wm._set_connecting("BadPass") + + fire(wm, NMDeviceState.NEED_AUTH, prev_state=NMDeviceState.CONFIG, + reason=NMDeviceStateReason.SUPPLICANT_DISCONNECT) + assert len(wm._callback_queue) == 1 + + fire(wm, NMDeviceState.FAILED, prev_state=NMDeviceState.NEED_AUTH, + reason=NMDeviceStateReason.NO_SECRETS) + assert len(wm._callback_queue) == 1 # no duplicate + + wm.process_callbacks() + cb.assert_called_once_with("BadPass") + + def test_no_ssid_no_callback(self, mocker): + """If ssid is None when NEED_AUTH fires, no callback enqueued.""" + wm = _make_wm(mocker) + cb = mocker.MagicMock() + wm.add_callbacks(need_auth=cb) + + fire(wm, NMDeviceState.NEED_AUTH, reason=NMDeviceStateReason.SUPPLICANT_DISCONNECT) + + assert len(wm._callback_queue) == 0 + + def test_interrupted_auth_ignored(self, mocker): + """Switching A->B: NEED_AUTH from A (prev=DISCONNECTED) must not fire callback. + + Reproduced on device: rapidly switching between two saved networks can trigger a + rare false "wrong password" dialog for the previous network, even though both have + correct passwords. The stale NEED_AUTH has prev_state=DISCONNECTED (not CONFIG). + """ + wm = _make_wm(mocker) + cb = mocker.MagicMock() + wm.add_callbacks(need_auth=cb) + wm._set_connecting("A") + wm._set_connecting("B") + + fire(wm, NMDeviceState.NEED_AUTH, prev_state=NMDeviceState.DISCONNECTED, + reason=NMDeviceStateReason.SUPPLICANT_DISCONNECT) + + assert wm._wifi_state.ssid == "B" + assert wm._wifi_state.status == ConnectStatus.CONNECTING + assert len(wm._callback_queue) == 0 + + +class TestPassthroughStates: + """NEED_AUTH (generic), IP_CONFIG, IP_CHECK, SECONDARIES, FAILED (generic) are no-ops.""" + + @pytest.mark.parametrize("state", [ + NMDeviceState.NEED_AUTH, + NMDeviceState.IP_CONFIG, + NMDeviceState.IP_CHECK, + NMDeviceState.SECONDARIES, + NMDeviceState.FAILED, + ]) + def test_passthrough_is_noop(self, mocker, state): + wm = _make_wm(mocker) + wm._set_connecting("Net") + + fire(wm, state, reason=NMDeviceStateReason.NONE) + + assert wm._wifi_state.ssid == "Net" + assert wm._wifi_state.status == ConnectStatus.CONNECTING + assert len(wm._callback_queue) == 0 + + +class TestActivated: + def test_sets_connected(self, mocker): + """ACTIVATED sets status to CONNECTED and fires callback.""" + wm = _make_wm(mocker, connections={"MyNet": "/path/mynet"}) + cb = mocker.MagicMock() + wm.add_callbacks(activated=cb) + wm._set_connecting("MyNet") + wm._get_active_wifi_connection.return_value = ("/path/mynet", {}) + + fire(wm, NMDeviceState.ACTIVATED) + + assert wm._wifi_state.status == ConnectStatus.CONNECTED + assert wm._wifi_state.ssid == "MyNet" + assert len(wm._callback_queue) == 1 + wm.process_callbacks() + cb.assert_called_once() + + def test_conn_path_none_still_connected(self, mocker): + """ACTIVATED but DBus returns None: status CONNECTED, ssid unchanged.""" + wm = _make_wm(mocker) + wm._set_connecting("MyNet") + + fire(wm, NMDeviceState.ACTIVATED) + + assert wm._wifi_state.status == ConnectStatus.CONNECTED + assert wm._wifi_state.ssid == "MyNet" + + def test_activated_side_effects(self, mocker): + """ACTIVATED persists the volatile connection to disk and updates active connection info.""" + wm = _make_wm(mocker, connections={"Net": "/path/net"}) + wm._set_connecting("Net") + wm._get_active_wifi_connection.return_value = ("/path/net", {}) + + fire(wm, NMDeviceState.ACTIVATED) + + wm._conn_monitor.send_and_get_reply.assert_called_once() + wm._update_active_connection_info.assert_called_once() + wm._update_networks.assert_not_called() + + +# --------------------------------------------------------------------------- +# Thread races: _set_connecting on main thread vs _handle_state_change on monitor thread. +# Uses side_effect on the DBus mock to simulate _set_connecting running mid-handler. +# The epoch counter detects that a user action occurred during the slow DBus call +# and discards the stale update. +# --------------------------------------------------------------------------- +# The deterministic fixes (skip DBus lookup when ssid already set, prev_state guard +# on NEED_AUTH, DEACTIVATING clears CONNECTED on CONNECTION_REMOVED, CONNECTION_REMOVED +# guard) shrink these race windows significantly. The epoch counter closes the +# remaining gaps. + +class TestThreadRaces: + def test_prepare_race_user_tap_during_dbus(self, mocker): + """User taps B while PREPARE's DBus call is in flight for auto-connect. + + Monitor thread reads wifi_state (ssid=None), starts DBus call. + Main thread: _set_connecting("B"). Monitor thread writes back stale ssid from DBus. + """ + wm = _make_wm(mocker, connections={"A": "/path/A", "B": "/path/B"}) + + def user_taps_b_during_dbus(*args, **kwargs): + wm._set_connecting("B") + return ("/path/A", {}) + + wm._get_active_wifi_connection.side_effect = user_taps_b_during_dbus + + fire(wm, NMDeviceState.PREPARE) + + assert wm._wifi_state.ssid == "B" + assert wm._wifi_state.status == ConnectStatus.CONNECTING + + def test_activated_race_user_tap_during_dbus(self, mocker): + """User taps B right as A finishes connecting (ACTIVATED handler running). + + Monitor thread reads wifi_state (A, CONNECTING), starts DBus call. + Main thread: _set_connecting("B"). Monitor thread writes (A, CONNECTED), losing B. + """ + wm = _make_wm(mocker, connections={"A": "/path/A", "B": "/path/B"}) + wm._set_connecting("A") + + def user_taps_b_during_dbus(*args, **kwargs): + wm._set_connecting("B") + return ("/path/A", {}) + + wm._get_active_wifi_connection.side_effect = user_taps_b_during_dbus + + fire(wm, NMDeviceState.ACTIVATED) + + assert wm._wifi_state.ssid == "B" + assert wm._wifi_state.status == ConnectStatus.CONNECTING + + def test_init_wifi_state_race_user_tap_during_dbus(self, mocker): + """User taps B while _init_wifi_state's DBus calls are in flight. + + _init_wifi_state runs from set_active(True) or worker error paths. It does + 2 DBus calls (device State property + _get_active_wifi_connection) then + unconditionally writes _wifi_state. If the user taps a network during those + calls, _set_connecting("B") is overwritten with stale NM ground truth. + """ + wm = _make_wm(mocker, connections={"A": "/path/A", "B": "/path/B"}) + wm._wifi_device = "/dev/wifi0" + wm._router_main = mocker.MagicMock() + + state_reply = mocker.MagicMock() + state_reply.body = [('u', NMDeviceState.ACTIVATED)] + wm._router_main.send_and_get_reply.return_value = state_reply + + def user_taps_b_during_dbus(*args, **kwargs): + wm._set_connecting("B") + return ("/path/A", {}) + + wm._get_active_wifi_connection.side_effect = user_taps_b_during_dbus + + wm._init_wifi_state() + + assert wm._wifi_state.ssid == "B" + assert wm._wifi_state.status == ConnectStatus.CONNECTING + + +# --------------------------------------------------------------------------- +# Full sequences (NM signal order from real devices) +# --------------------------------------------------------------------------- + +class TestFullSequences: + def test_normal_connect(self, mocker): + """User connects to saved network: full happy path. + + Real device sequence (switching from another connected network): + DEACTIVATING(ACTIVATED, NEW_ACTIVATION) → DISCONNECTED(DEACTIVATING, NEW_ACTIVATION) + PREPARE → CONFIG → NEED_AUTH(CONFIG, NONE) → PREPARE(NEED_AUTH, NONE) → CONFIG + → IP_CONFIG → IP_CHECK → SECONDARIES → ACTIVATED + """ + wm = _make_wm(mocker, connections={"Home": "/path/home"}) + wm._get_active_wifi_connection.return_value = ("/path/home", {}) + + wm._set_connecting("Home") + fire(wm, NMDeviceState.PREPARE) + fire(wm, NMDeviceState.CONFIG) + fire(wm, NMDeviceState.NEED_AUTH) # WPA handshake (reason=NONE) + fire(wm, NMDeviceState.PREPARE, prev_state=NMDeviceState.NEED_AUTH) + fire(wm, NMDeviceState.CONFIG) + assert wm._wifi_state.status == ConnectStatus.CONNECTING + + fire(wm, NMDeviceState.IP_CONFIG) + fire(wm, NMDeviceState.IP_CHECK) + fire(wm, NMDeviceState.SECONDARIES) + fire(wm, NMDeviceState.ACTIVATED) + + assert wm._wifi_state.status == ConnectStatus.CONNECTED + assert wm._wifi_state.ssid == "Home" + + def test_wrong_password_then_retry(self, mocker): + """Wrong password → NEED_AUTH → FAILED → NM auto-reconnects to saved network. + + Confirmed on device: wrong password for Shane's iPhone, NM auto-connected to unifi. + + Real device sequence (switching from a connected network): + DEACTIVATING(ACTIVATED, NEW_ACTIVATION) → DISCONNECTED(DEACTIVATING, NEW_ACTIVATION) + → PREPARE → CONFIG → NEED_AUTH(CONFIG, NONE) ← WPA handshake + → PREPARE(NEED_AUTH, NONE) → CONFIG + → NEED_AUTH(CONFIG, SUPPLICANT_DISCONNECT) ← wrong password + → FAILED(NEED_AUTH, NO_SECRETS) ← NM gives up + → DISCONNECTED(FAILED, NONE) + → PREPARE → CONFIG → NEED_AUTH(CONFIG, NONE) → PREPARE(NEED_AUTH) → CONFIG + → IP_CONFIG → IP_CHECK → SECONDARIES → ACTIVATED ← auto-reconnect to other saved network + """ + wm = _make_wm(mocker, connections={"Sec": "/path/sec"}) + cb = mocker.MagicMock() + wm.add_callbacks(need_auth=cb) + + wm._set_connecting("Sec") + fire(wm, NMDeviceState.PREPARE) + fire(wm, NMDeviceState.CONFIG) + fire(wm, NMDeviceState.NEED_AUTH) # WPA handshake (reason=NONE) + fire(wm, NMDeviceState.PREPARE, prev_state=NMDeviceState.NEED_AUTH) + fire(wm, NMDeviceState.CONFIG) + + fire(wm, NMDeviceState.NEED_AUTH, prev_state=NMDeviceState.CONFIG, + reason=NMDeviceStateReason.SUPPLICANT_DISCONNECT) + assert wm._wifi_state.status == ConnectStatus.DISCONNECTED + assert len(wm._callback_queue) == 1 + + # FAILED(NO_SECRETS) follows but ssid is already cleared — no double-fire + fire(wm, NMDeviceState.FAILED, reason=NMDeviceStateReason.NO_SECRETS) + assert len(wm._callback_queue) == 1 + + fire(wm, NMDeviceState.DISCONNECTED, prev_state=NMDeviceState.FAILED) + + # Retry + wm._callback_queue.clear() + wm._set_connecting("Sec") + wm._get_active_wifi_connection.return_value = ("/path/sec", {}) + fire(wm, NMDeviceState.PREPARE) + fire(wm, NMDeviceState.CONFIG) + fire_wpa_connect(wm) + assert wm._wifi_state.status == ConnectStatus.CONNECTED + + def test_switch_saved_networks(self, mocker): + """Switch from A to B (both saved): NM signal sequence from real device. + + Real device sequence: + DEACTIVATING(ACTIVATED, NEW_ACTIVATION) → DISCONNECTED(DEACTIVATING, NEW_ACTIVATION) + → PREPARE → CONFIG → NEED_AUTH(CONFIG, NONE) → PREPARE(NEED_AUTH, NONE) → CONFIG + → IP_CONFIG → IP_CHECK → SECONDARIES → ACTIVATED + """ + wm = _make_wm(mocker, connections={"A": "/path/A", "B": "/path/B"}) + wm._wifi_state = WifiState(ssid="A", status=ConnectStatus.CONNECTED) + wm._get_active_wifi_connection.return_value = ("/path/B", {}) + + wm._set_connecting("B") + + fire(wm, NMDeviceState.DEACTIVATING, prev_state=NMDeviceState.ACTIVATED, + reason=NMDeviceStateReason.NEW_ACTIVATION) + fire(wm, NMDeviceState.DISCONNECTED, prev_state=NMDeviceState.DEACTIVATING, + reason=NMDeviceStateReason.NEW_ACTIVATION) + assert wm._wifi_state.ssid == "B" + assert wm._wifi_state.status == ConnectStatus.CONNECTING + + fire(wm, NMDeviceState.PREPARE) + fire(wm, NMDeviceState.CONFIG) + fire_wpa_connect(wm) + assert wm._wifi_state.status == ConnectStatus.CONNECTED + assert wm._wifi_state.ssid == "B" + + def test_rapid_switch_no_false_wrong_password(self, mocker): + """Switch A→B quickly: A's interrupted NEED_AUTH must NOT show wrong password. + + NOTE: The late NEED_AUTH(DISCONNECTED, SUPPLICANT_DISCONNECT) is common when rapidly + switching between networks with wrong/new passwords. Less common when switching between + saved networks with correct passwords. Not guaranteed — some switches skip it and go + straight from DISCONNECTED to PREPARE. The prev_state is consistently DISCONNECTED + for stale signals, so the prev_state guard reliably distinguishes them. + + Worst-case signal sequence this protects against: + DEACTIVATING(NEW_ACTIVATION) → DISCONNECTED(NEW_ACTIVATION) + → NEED_AUTH(DISCONNECTED, SUPPLICANT_DISCONNECT) ← A's stale auth failure + → PREPARE → CONFIG → ... → ACTIVATED ← B connects + """ + wm = _make_wm(mocker, connections={"A": "/path/A", "B": "/path/B"}) + cb = mocker.MagicMock() + wm.add_callbacks(need_auth=cb) + wm._wifi_state = WifiState(ssid="A", status=ConnectStatus.CONNECTED) + wm._get_active_wifi_connection.return_value = ("/path/B", {}) + + wm._set_connecting("B") + + fire(wm, NMDeviceState.DEACTIVATING, prev_state=NMDeviceState.ACTIVATED, + reason=NMDeviceStateReason.NEW_ACTIVATION) + fire(wm, NMDeviceState.DISCONNECTED, prev_state=NMDeviceState.DEACTIVATING, + reason=NMDeviceStateReason.NEW_ACTIVATION) + fire(wm, NMDeviceState.NEED_AUTH, prev_state=NMDeviceState.DISCONNECTED, + reason=NMDeviceStateReason.SUPPLICANT_DISCONNECT) + + assert wm._wifi_state.ssid == "B" + assert wm._wifi_state.status == ConnectStatus.CONNECTING + assert len(wm._callback_queue) == 0 + + fire(wm, NMDeviceState.PREPARE) + fire(wm, NMDeviceState.CONFIG) + fire_wpa_connect(wm) + assert wm._wifi_state.status == ConnectStatus.CONNECTED + + def test_forget_while_connecting(self, mocker): + """Forget the network we're currently connecting to (not yet ACTIVATED). + + Confirmed on device: connected to unifi, tapped Shane's iPhone, then forgot + Shane's iPhone while at CONFIG. NM auto-connected to unifi afterward. + + Real device sequence (switching then forgetting mid-connection): + DEACTIVATING(ACTIVATED, NEW_ACTIVATION) → DISCONNECTED(DEACTIVATING, NEW_ACTIVATION) + → PREPARE → CONFIG → NEED_AUTH(CONFIG, NONE) → PREPARE(NEED_AUTH) → CONFIG + → DEACTIVATING(CONFIG, CONNECTION_REMOVED) ← forget at CONFIG + → DISCONNECTED(DEACTIVATING, CONNECTION_REMOVED) + → PREPARE → CONFIG → ... → ACTIVATED ← NM auto-connects to other saved network + + Note: DEACTIVATING fires from CONFIG (not ACTIVATED). wifi_state.status is + CONNECTING, so the DEACTIVATING handler is a no-op. DISCONNECTED clears state + (ssid removed from _connections by ConnectionRemoved), then PREPARE recovers + via DBus lookup for the auto-connect. + """ + wm = _make_wm(mocker, connections={"A": "/path/A", "Other": "/path/other"}) + wm._get_active_wifi_connection.return_value = ("/path/other", {}) + + wm._set_connecting("A") + + fire(wm, NMDeviceState.PREPARE) + fire(wm, NMDeviceState.CONFIG) + assert wm._wifi_state.ssid == "A" + assert wm._wifi_state.status == ConnectStatus.CONNECTING + + # User forgets A: ConnectionRemoved processed first, then state changes + del wm._connections["A"] + + fire(wm, NMDeviceState.DEACTIVATING, prev_state=NMDeviceState.CONFIG, + reason=NMDeviceStateReason.CONNECTION_REMOVED) + assert wm._wifi_state.ssid == "A" + assert wm._wifi_state.status == ConnectStatus.CONNECTING # DEACTIVATING preserves CONNECTING + + fire(wm, NMDeviceState.DISCONNECTED, prev_state=NMDeviceState.DEACTIVATING, + reason=NMDeviceStateReason.CONNECTION_REMOVED) + assert wm._wifi_state.ssid is None + assert wm._wifi_state.status == ConnectStatus.DISCONNECTED + + # NM auto-connects to another saved network + fire(wm, NMDeviceState.PREPARE) + assert wm._wifi_state.ssid == "Other" + assert wm._wifi_state.status == ConnectStatus.CONNECTING + + fire(wm, NMDeviceState.CONFIG) + fire_wpa_connect(wm) + assert wm._wifi_state.status == ConnectStatus.CONNECTED + assert wm._wifi_state.ssid == "Other" + + def test_forget_connected_network(self, mocker): + """Forget the currently connected network (not switching to another). + + Real device sequence: + DEACTIVATING(ACTIVATED, CONNECTION_REMOVED) → DISCONNECTED(DEACTIVATING, CONNECTION_REMOVED) + + ConnectionRemoved signal may or may not have been processed before state changes. + Either way, state must clear — we're forgetting what we're connected to, not switching. + """ + wm = _make_wm(mocker, connections={"A": "/path/A"}) + wm._wifi_state = WifiState(ssid="A", status=ConnectStatus.CONNECTED) + + fire(wm, NMDeviceState.DEACTIVATING, prev_state=NMDeviceState.ACTIVATED, + reason=NMDeviceStateReason.CONNECTION_REMOVED) + assert wm._wifi_state.ssid is None + assert wm._wifi_state.status == ConnectStatus.DISCONNECTED + + # DISCONNECTED follows — harmless since state is already cleared + fire(wm, NMDeviceState.DISCONNECTED, prev_state=NMDeviceState.DEACTIVATING, + reason=NMDeviceStateReason.CONNECTION_REMOVED) + assert wm._wifi_state.ssid is None + assert wm._wifi_state.status == ConnectStatus.DISCONNECTED + + def test_forget_A_connect_B(self, mocker): + """Forget A while connecting to B: full signal sequence. + + Real device sequence: + DEACTIVATING(ACTIVATED, CONNECTION_REMOVED) → DISCONNECTED(DEACTIVATING, CONNECTION_REMOVED) + → PREPARE → CONFIG → NEED_AUTH(CONFIG, NONE) → PREPARE(NEED_AUTH, NONE) → CONFIG + → IP_CONFIG → IP_CHECK → SECONDARIES → ACTIVATED + + Signal order: + 1. User: _set_connecting("B"), forget("A") removes A from _connections + 2. NewConnection for B arrives → _connections["B"] = ... + 3. DEACTIVATING(CONNECTION_REMOVED) — no-op + 4. DISCONNECTED(CONNECTION_REMOVED) — B is in _connections, must not clear + 5. PREPARE → CONFIG → NEED_AUTH → PREPARE → CONFIG → ... → ACTIVATED + """ + wm = _make_wm(mocker, connections={"A": "/path/A"}) + wm._wifi_state = WifiState(ssid="A", status=ConnectStatus.CONNECTED) + + wm._set_connecting("B") + del wm._connections["A"] + wm._connections["B"] = "/path/B" + + fire(wm, NMDeviceState.DEACTIVATING, prev_state=NMDeviceState.ACTIVATED, + reason=NMDeviceStateReason.CONNECTION_REMOVED) + assert wm._wifi_state.ssid == "B" + assert wm._wifi_state.status == ConnectStatus.CONNECTING + + fire(wm, NMDeviceState.DISCONNECTED, prev_state=NMDeviceState.DEACTIVATING, + reason=NMDeviceStateReason.CONNECTION_REMOVED) + assert wm._wifi_state.ssid == "B" + assert wm._wifi_state.status == ConnectStatus.CONNECTING + + wm._get_active_wifi_connection.return_value = ("/path/B", {}) + fire(wm, NMDeviceState.PREPARE) + fire(wm, NMDeviceState.CONFIG) + fire_wpa_connect(wm) + assert wm._wifi_state.status == ConnectStatus.CONNECTED + assert wm._wifi_state.ssid == "B" + + def test_forget_A_connect_B_late_new_connection(self, mocker): + """Forget A, connect B: NewConnection for B arrives AFTER DISCONNECTED. + + This is the worst-case race: B isn't in _connections when DISCONNECTED fires, + so the guard can't protect it and state clears. PREPARE must recover by doing + the DBus lookup (ssid is None at that point). + + Signal order: + 1. User: _set_connecting("B"), forget("A") removes A from _connections + 2. DEACTIVATING(CONNECTION_REMOVED) — B NOT in _connections, should be no-op + 3. DISCONNECTED(CONNECTION_REMOVED) — B STILL NOT in _connections, clears state + 4. NewConnection for B arrives late → _connections["B"] = ... + 5. PREPARE (ssid=None, so DBus lookup recovers) → CONFIG → ACTIVATED + """ + wm = _make_wm(mocker, connections={"A": "/path/A"}) + wm._wifi_state = WifiState(ssid="A", status=ConnectStatus.CONNECTED) + + wm._set_connecting("B") + del wm._connections["A"] + + fire(wm, NMDeviceState.DEACTIVATING, prev_state=NMDeviceState.ACTIVATED, + reason=NMDeviceStateReason.CONNECTION_REMOVED) + assert wm._wifi_state.ssid == "B" + assert wm._wifi_state.status == ConnectStatus.CONNECTING + + fire(wm, NMDeviceState.DISCONNECTED, prev_state=NMDeviceState.DEACTIVATING, + reason=NMDeviceStateReason.CONNECTION_REMOVED) + # B not in _connections yet, so state clears — this is the known edge case + assert wm._wifi_state.ssid is None + assert wm._wifi_state.status == ConnectStatus.DISCONNECTED + + # NewConnection arrives late + wm._connections["B"] = "/path/B" + wm._get_active_wifi_connection.return_value = ("/path/B", {}) + + # PREPARE recovers: ssid is None so it looks up from DBus + fire(wm, NMDeviceState.PREPARE) + assert wm._wifi_state.ssid == "B" + assert wm._wifi_state.status == ConnectStatus.CONNECTING + + fire(wm, NMDeviceState.CONFIG) + fire_wpa_connect(wm) + assert wm._wifi_state.status == ConnectStatus.CONNECTED + assert wm._wifi_state.ssid == "B" + + def test_auto_connect(self, mocker): + """NM auto-connects (no user action, ssid starts None).""" + wm = _make_wm(mocker, connections={"AutoNet": "/path/auto"}) + wm._get_active_wifi_connection.return_value = ("/path/auto", {}) + + fire(wm, NMDeviceState.PREPARE) + assert wm._wifi_state.ssid == "AutoNet" + assert wm._wifi_state.status == ConnectStatus.CONNECTING + + fire(wm, NMDeviceState.CONFIG) + fire_wpa_connect(wm) + assert wm._wifi_state.status == ConnectStatus.CONNECTED + assert wm._wifi_state.ssid == "AutoNet" + + def test_network_lost_during_connection(self, mocker): + """Hotspot turned off while connecting (before ACTIVATED). + + Confirmed on device: started new connection to Shane's iPhone, immediately + turned off the hotspot. NM can't complete WPA handshake and reports + FAILED(NO_SECRETS) — same signal as wrong password (false positive). + + Real device sequence: + PREPARE → CONFIG → NEED_AUTH(CONFIG, NONE) → PREPARE(NEED_AUTH) → CONFIG + → NEED_AUTH(CONFIG, NONE) → FAILED(NEED_AUTH, NO_SECRETS) → DISCONNECTED(FAILED, NONE) + + Note: no DEACTIVATING, no SUPPLICANT_DISCONNECT. The NEED_AUTH(CONFIG, NONE) is the + normal WPA handshake (not an error). NM gives up with NO_SECRETS because the AP + vanished mid-handshake. + """ + wm = _make_wm(mocker, connections={"Hotspot": "/path/hs"}) + cb = mocker.MagicMock() + wm.add_callbacks(need_auth=cb) + + wm._set_connecting("Hotspot") + fire(wm, NMDeviceState.PREPARE) + fire(wm, NMDeviceState.CONFIG) + fire(wm, NMDeviceState.NEED_AUTH) # WPA handshake (reason=NONE) + fire(wm, NMDeviceState.PREPARE, prev_state=NMDeviceState.NEED_AUTH) + fire(wm, NMDeviceState.CONFIG) + assert wm._wifi_state.status == ConnectStatus.CONNECTING + + # Second NEED_AUTH(CONFIG, NONE) — NM retries handshake, AP vanishing + fire(wm, NMDeviceState.NEED_AUTH) + assert wm._wifi_state.status == ConnectStatus.CONNECTING + + # NM gives up — reports NO_SECRETS (same as wrong password) + fire(wm, NMDeviceState.FAILED, prev_state=NMDeviceState.NEED_AUTH, + reason=NMDeviceStateReason.NO_SECRETS) + assert wm._wifi_state.status == ConnectStatus.DISCONNECTED + assert len(wm._callback_queue) == 1 + + fire(wm, NMDeviceState.DISCONNECTED, prev_state=NMDeviceState.FAILED) + assert wm._wifi_state.ssid is None + assert wm._wifi_state.status == ConnectStatus.DISCONNECTED + + wm.process_callbacks() + cb.assert_called_once_with("Hotspot") + + @pytest.mark.xfail(reason="TODO: FAILED(SSID_NOT_FOUND) should emit error for UI") + def test_ssid_not_found(self, mocker): + """Network drops off while connected — hotspot turned off. + + NM docs: SSID_NOT_FOUND (53) = "The WiFi network could not be found" + + Confirmed on device: connected to Shane's iPhone, then turned off the hotspot. + No DEACTIVATING fires — NM goes straight from ACTIVATED to FAILED(SSID_NOT_FOUND). + NM retries connecting (PREPARE → CONFIG → ... → FAILED(CONFIG, SSID_NOT_FOUND)) + before finally giving up with DISCONNECTED. + + NOTE: turning off a hotspot during initial connection (before ACTIVATED) typically + produces FAILED(NO_SECRETS) instead of SSID_NOT_FOUND (see test_failed_no_secrets). + + Real device sequence (hotspot turned off while connected): + FAILED(ACTIVATED, SSID_NOT_FOUND) → DISCONNECTED(FAILED, NONE) + → PREPARE → CONFIG → NEED_AUTH(CONFIG, NONE) → PREPARE(NEED_AUTH) → CONFIG + → NEED_AUTH(CONFIG, NONE) → PREPARE(NEED_AUTH) → CONFIG + → FAILED(CONFIG, SSID_NOT_FOUND) → DISCONNECTED(FAILED, NONE) + + The UI error callback mechanism is intentionally deferred — for now just clear state. + """ + wm = _make_wm(mocker, connections={"GoneNet": "/path/gone"}) + cb = mocker.MagicMock() + wm.add_callbacks(need_auth=cb) + + wm._set_connecting("GoneNet") + fire(wm, NMDeviceState.PREPARE) + fire(wm, NMDeviceState.CONFIG) + fire(wm, NMDeviceState.FAILED, reason=NMDeviceStateReason.SSID_NOT_FOUND) + + assert wm._wifi_state.status == ConnectStatus.DISCONNECTED + assert wm._wifi_state.ssid is None + + def test_failed_then_disconnected_clears_state(self, mocker): + """After FAILED, NM always transitions to DISCONNECTED to clean up. + + NM docs: FAILED (120) = "failed to connect, cleaning up the connection request" + Full sequence: ... → FAILED(reason) → DISCONNECTED(NONE) + """ + wm = _make_wm(mocker) + wm._set_connecting("Net") + + fire(wm, NMDeviceState.FAILED, reason=NMDeviceStateReason.NONE) + assert wm._wifi_state.status == ConnectStatus.CONNECTING # FAILED(NONE) is a no-op + + fire(wm, NMDeviceState.DISCONNECTED, reason=NMDeviceStateReason.NONE) + assert wm._wifi_state.ssid is None + assert wm._wifi_state.status == ConnectStatus.DISCONNECTED + + def test_user_requested_disconnect(self, mocker): + """User explicitly disconnects from the network. + + NM docs: USER_REQUESTED (39) = "Device disconnected by user or client" + Expected sequence: DEACTIVATING(USER_REQUESTED) → DISCONNECTED(USER_REQUESTED) + """ + wm = _make_wm(mocker) + wm._wifi_state = WifiState(ssid="MyNet", status=ConnectStatus.CONNECTED) + + fire(wm, NMDeviceState.DEACTIVATING, reason=NMDeviceStateReason.USER_REQUESTED) + fire(wm, NMDeviceState.DISCONNECTED, reason=NMDeviceStateReason.USER_REQUESTED) + + assert wm._wifi_state.ssid is None + assert wm._wifi_state.status == ConnectStatus.DISCONNECTED + + +# --------------------------------------------------------------------------- +# Worker error recovery: DBus errors in activate/connect re-sync with NM +# --------------------------------------------------------------------------- +# Verified on device: when ActivateConnection returns UnknownConnection error, +# NM emits no state signals. The worker error path is the only recovery point. + +class TestWorkerErrorRecovery: + """Worker threads re-sync with NM via _init_wifi_state on DBus errors, + preserving actual NM state instead of blindly clearing to DISCONNECTED.""" + + def _mock_init_restores(self, wm, mocker, ssid, status): + """Replace _init_wifi_state with a mock that simulates NM reporting the given state.""" + mock = mocker.MagicMock( + side_effect=lambda: setattr(wm, '_wifi_state', WifiState(ssid=ssid, status=status)) + ) + wm._init_wifi_state = mock + return mock + + def test_activate_dbus_error_resyncs(self, mocker): + """ActivateConnection returns DBus error while A is connected. + NM rejects the request — no state signals emitted. Worker must re-read NM + state to discover A is still connected, not clear to DISCONNECTED. + """ + wm = _make_wm(mocker, connections={"A": "/path/A", "B": "/path/B"}) + wm._wifi_device = "/dev/wifi0" + wm._nm = mocker.MagicMock() + wm._wifi_state = WifiState(ssid="A", status=ConnectStatus.CONNECTED) + wm._router_main = mocker.MagicMock() + + error_reply = mocker.MagicMock() + error_reply.header.message_type = MessageType.error + wm._router_main.send_and_get_reply.return_value = error_reply + + mock_init = self._mock_init_restores(wm, mocker, "A", ConnectStatus.CONNECTED) + + wm.activate_connection("B", block=True) + + mock_init.assert_called_once() + assert wm._wifi_state.ssid == "A" + assert wm._wifi_state.status == ConnectStatus.CONNECTED + + def test_connect_to_network_dbus_error_resyncs(self, mocker): + """AddAndActivateConnection2 returns DBus error while A is connected.""" + wm = _make_wm(mocker, connections={"A": "/path/A"}) + wm._wifi_device = "/dev/wifi0" + wm._nm = mocker.MagicMock() + wm._wifi_state = WifiState(ssid="A", status=ConnectStatus.CONNECTED) + wm._router_main = mocker.MagicMock() + wm._forgotten = [] + + error_reply = mocker.MagicMock() + error_reply.header.message_type = MessageType.error + wm._router_main.send_and_get_reply.return_value = error_reply + + mock_init = self._mock_init_restores(wm, mocker, "A", ConnectStatus.CONNECTED) + + # Run worker thread synchronously + workers = [] + mocker.patch('openpilot.system.ui.lib.wifi_manager.threading.Thread', + side_effect=lambda target, **kw: type('T', (), {'start': lambda self: workers.append(target)})()) + + wm.connect_to_network("B", "password123") + workers[-1]() + + mock_init.assert_called_once() + assert wm._wifi_state.ssid == "A" + assert wm._wifi_state.status == ConnectStatus.CONNECTED diff --git a/openpilot/system/ui/lib/text_measure.py b/openpilot/system/ui/lib/text_measure.py new file mode 100644 index 0000000000..dee4b419ff --- /dev/null +++ b/openpilot/system/ui/lib/text_measure.py @@ -0,0 +1,36 @@ +import pyray as rl +from openpilot.system.ui.lib.application import FONT_SCALE, font_fallback +from openpilot.system.ui.lib.emoji import find_emoji + +_cache: dict[int, rl.Vector2] = {} + + +def measure_text_cached(font: rl.Font, text: str, font_size: int, spacing: float = 0) -> rl.Vector2: + """Caches text measurements to avoid redundant calculations.""" + font = font_fallback(font) + spacing = round(spacing, 4) + key = hash((font.texture.id, text, font_size, spacing)) + if key in _cache: + return _cache[key] + + # Measure normal characters without emojis, then add standard width for each found emoji + emoji = find_emoji(text) + if emoji: + non_emoji_text = "" + last_index = 0 + for start, end, _ in emoji: + non_emoji_text += text[last_index:start] + last_index = end + non_emoji_text += text[last_index:] + else: + non_emoji_text = text + + result = rl.measure_text_ex(font, non_emoji_text, font_size * FONT_SCALE, spacing) # noqa: TID251 + if emoji: + result.x += len(emoji) * font_size * FONT_SCALE + # If just emoji assume a single line height + if result.y == 0: + result.y = font_size * FONT_SCALE + + _cache[key] = result + return result diff --git a/openpilot/system/ui/lib/utils.py b/openpilot/system/ui/lib/utils.py new file mode 100644 index 0000000000..e97b3ba9d9 --- /dev/null +++ b/openpilot/system/ui/lib/utils.py @@ -0,0 +1,19 @@ +import pyray as rl +from collections.abc import Sequence + + +class GuiStyleContext: + def __init__(self, styles: Sequence[tuple[int, int, int]]): + """styles is a list of tuples (control, prop, new_value)""" + self.styles = styles + self.prev_styles: list[tuple[int, int, int]] = [] + + def __enter__(self): + for control, prop, new_value in self.styles: + prev_value = rl.gui_get_style(control, prop) + self.prev_styles.append((control, prop, prev_value)) + rl.gui_set_style(control, prop, new_value) + + def __exit__(self, exc_type, exc_value, traceback): + for control, prop, prev_value in self.prev_styles: + rl.gui_set_style(control, prop, prev_value) diff --git a/openpilot/system/ui/lib/wifi_manager.py b/openpilot/system/ui/lib/wifi_manager.py new file mode 100644 index 0000000000..dedb341cd0 --- /dev/null +++ b/openpilot/system/ui/lib/wifi_manager.py @@ -0,0 +1,946 @@ +import atexit +import threading +import time +import uuid +import subprocess +from collections.abc import Callable +from dataclasses import dataclass, replace +from enum import IntEnum +from typing import Any + +from jeepney import DBusAddress, new_method_call +from jeepney.bus_messages import MatchRule, message_bus +from jeepney.io.blocking import DBusConnection, open_dbus_connection as open_dbus_connection_blocking +from jeepney.io.threading import DBusRouter, open_dbus_connection as open_dbus_connection_threading +from jeepney.low_level import MessageType +from jeepney.wrappers import Properties + +from openpilot.common.swaglog import cloudlog +from openpilot.system.ui.lib.networkmanager import (NM, NM_WIRELESS_IFACE, NM_802_11_AP_SEC_PAIR_WEP40, + NM_802_11_AP_SEC_PAIR_WEP104, NM_802_11_AP_SEC_GROUP_WEP40, + NM_802_11_AP_SEC_GROUP_WEP104, NM_802_11_AP_SEC_KEY_MGMT_PSK, + NM_802_11_AP_SEC_KEY_MGMT_802_1X, NM_802_11_AP_FLAGS_NONE, + NM_802_11_AP_FLAGS_PRIVACY, NM_802_11_AP_FLAGS_WPS, + NM_PATH, NM_IFACE, NM_ACCESS_POINT_IFACE, NM_SETTINGS_PATH, + NM_SETTINGS_IFACE, NM_CONNECTION_IFACE, NM_DEVICE_IFACE, + NM_DEVICE_TYPE_WIFI, NM_ACTIVE_CONNECTION_IFACE, + NM_IP4_CONFIG_IFACE, NM_PROPERTIES_IFACE, NMDeviceState, NMDeviceStateReason) + +try: + from openpilot.common.params import Params +except Exception: + Params = None + +TETHERING_IP_ADDRESS = "192.168.43.1" +DEFAULT_TETHERING_PASSWORD = "swagswagcomma" +SIGNAL_QUEUE_SIZE = 10 +SCAN_PERIOD_SECONDS = 5 + +DEBUG = False +_dbus_call_idx = 0 + + +def normalize_ssid(ssid: str) -> str: + return ssid.replace("’", "'") # for iPhone hotspots + + +def _wrap_router(router): + def _wrap(orig): + def wrapper(msg, **kw): + global _dbus_call_idx + _dbus_call_idx += 1 + if DEBUG: + h = msg.header.fields + print(f"[DBUS #{_dbus_call_idx}] {h.get(6, '?')} {h.get(3, '?')} {msg.body}") + return orig(msg, **kw) + return wrapper + router.send_and_get_reply = _wrap(router.send_and_get_reply) + router.send = _wrap(router.send) + + +class SecurityType(IntEnum): + OPEN = 0 + WPA = 1 + WPA2 = 2 + WPA3 = 3 + UNSUPPORTED = 4 + + +class MeteredType(IntEnum): + UNKNOWN = 0 + YES = 1 + NO = 2 + + +def get_security_type(flags: int, wpa_flags: int, rsn_flags: int) -> SecurityType: + wpa_props = wpa_flags | rsn_flags + + # obtained by looking at flags of networks in the office as reported by an Android phone + supports_wpa = (NM_802_11_AP_SEC_PAIR_WEP40 | NM_802_11_AP_SEC_PAIR_WEP104 | NM_802_11_AP_SEC_GROUP_WEP40 | + NM_802_11_AP_SEC_GROUP_WEP104 | NM_802_11_AP_SEC_KEY_MGMT_PSK) + + if (flags == NM_802_11_AP_FLAGS_NONE) or ((flags & NM_802_11_AP_FLAGS_WPS) and not (wpa_props & supports_wpa)): + return SecurityType.OPEN + elif (flags & NM_802_11_AP_FLAGS_PRIVACY) and (wpa_props & supports_wpa) and not (wpa_props & NM_802_11_AP_SEC_KEY_MGMT_802_1X): + return SecurityType.WPA + else: + cloudlog.warning(f"Unsupported network! flags: {flags}, wpa_flags: {wpa_flags}, rsn_flags: {rsn_flags}") + return SecurityType.UNSUPPORTED + + +@dataclass(frozen=True) +class Network: + ssid: str + strength: int + security_type: SecurityType + is_tethering: bool + + @classmethod + def from_dbus(cls, ssid: str, aps: list["AccessPoint"], is_tethering: bool) -> "Network": + # we only want to show the strongest AP for each Network/SSID + strongest_ap = max(aps, key=lambda ap: ap.strength) + security_type = get_security_type(strongest_ap.flags, strongest_ap.wpa_flags, strongest_ap.rsn_flags) + + return cls( + ssid=ssid, + strength=100 if is_tethering else strongest_ap.strength, + security_type=security_type, + is_tethering=is_tethering, + ) + + +@dataclass(frozen=True) +class AccessPoint: + ssid: str + bssid: str + strength: int + flags: int + wpa_flags: int + rsn_flags: int + ap_path: str + + @classmethod + def from_dbus(cls, ap_props: dict[str, tuple[str, Any]], ap_path: str) -> "AccessPoint": + ssid = bytes(ap_props['Ssid'][1]).decode("utf-8", "replace") + bssid = str(ap_props['HwAddress'][1]) + strength = int(ap_props['Strength'][1]) + flags = int(ap_props['Flags'][1]) + wpa_flags = int(ap_props['WpaFlags'][1]) + rsn_flags = int(ap_props['RsnFlags'][1]) + + return cls( + ssid=ssid, + bssid=bssid, + strength=strength, + flags=flags, + wpa_flags=wpa_flags, + rsn_flags=rsn_flags, + ap_path=ap_path, + ) + + +class ConnectStatus(IntEnum): + DISCONNECTED = 0 + CONNECTING = 1 + CONNECTED = 2 + + +@dataclass(frozen=True) +class WifiState: + ssid: str | None = None + status: ConnectStatus = ConnectStatus.DISCONNECTED + + +class WifiManager: + def __init__(self): + self._networks: list[Network] = [] # an unsorted list of available Networks. a Network can be comprised of multiple APs + self._active = True # used to not run when not in settings + self._exit = False + + # DBus connections + try: + self._router_main = DBusRouter(open_dbus_connection_threading(bus="SYSTEM")) # used by scanner / general method calls + _wrap_router(self._router_main) + self._conn_monitor = open_dbus_connection_blocking(bus="SYSTEM") # used by state monitor thread + self._nm = DBusAddress(NM_PATH, bus_name=NM, interface=NM_IFACE) + except FileNotFoundError: + cloudlog.exception("Failed to connect to system D-Bus") + self._router_main = None + self._conn_monitor = None + self._exit = True + + # Store wifi device path + self._wifi_device: str | None = None + + # State + self._connections: dict[str, str] = {} # ssid -> connection path, updated via NM signals + self._wifi_state: WifiState = WifiState() + self._user_epoch: int = 0 + self._ipv4_address: str = "" + self._current_network_metered: MeteredType = MeteredType.UNKNOWN + self._tethering_password: str = "" + self._ipv4_forward = False + + self._last_network_scan: float = 0.0 + self._callback_queue: list[Callable] = [] + + self._tethering_ssid = "weedle" + if Params is not None: + dongle_id = Params().get("DongleId") + if dongle_id: + self._tethering_ssid += "-" + dongle_id[:4] + + # Callbacks + self._need_auth: list[Callable[[str], None]] = [] + self._activated: list[Callable[[], None]] = [] + self._forgotten: list[Callable[[str | None], None]] = [] + self._networks_updated: list[Callable[[list[Network]], None]] = [] + self._disconnected: list[Callable[[], None]] = [] + + self._scan_lock = threading.Lock() + self._scan_thread = threading.Thread(target=self._network_scanner, daemon=True) + self._state_thread = threading.Thread(target=self._monitor_state, daemon=True) + self._initialize() + atexit.register(self.stop) + + def _initialize(self): + def worker(): + self._wait_for_wifi_device() + + # TODO: wait for state thread to start before adding tethering connection, tiny race currently + self._scan_thread.start() + self._state_thread.start() + + self._init_connections() + if Params is not None and self._tethering_ssid not in self._connections: + self._add_tethering_connection() + + self._init_wifi_state() + + self._tethering_password = self._get_tethering_password() + cloudlog.debug("WifiManager initialized") + + threading.Thread(target=worker, daemon=True).start() + + def _init_wifi_state(self, block: bool = True): + def worker(): + if self._wifi_device is None: + cloudlog.warning("No WiFi device found") + return + + epoch = self._user_epoch + + dev_addr = DBusAddress(self._wifi_device, bus_name=NM, interface=NM_DEVICE_IFACE) + dev_state = self._router_main.send_and_get_reply(Properties(dev_addr).get('State')).body[0][1] + + ssid: str | None = None + status = ConnectStatus.DISCONNECTED + if NMDeviceState.PREPARE <= dev_state <= NMDeviceState.SECONDARIES and dev_state != NMDeviceState.NEED_AUTH: + status = ConnectStatus.CONNECTING + elif dev_state == NMDeviceState.ACTIVATED: + status = ConnectStatus.CONNECTED + + conn_path, _ = self._get_active_wifi_connection() + if conn_path: + ssid = next((s for s, p in self._connections.items() if p == conn_path), None) + + # Discard if user acted during DBus calls + if self._user_epoch != epoch: + return + + self._wifi_state = WifiState(ssid=ssid, status=status) + + if block: + worker() + else: + threading.Thread(target=worker, daemon=True).start() + + def add_callbacks(self, need_auth: Callable[[str], None] | None = None, + activated: Callable[[], None] | None = None, + forgotten: Callable[[str | None], None] | None = None, + networks_updated: Callable[[list[Network]], None] | None = None, + disconnected: Callable[[], None] | None = None): + if need_auth is not None: + self._need_auth.append(need_auth) + if activated is not None: + self._activated.append(activated) + if forgotten is not None: + self._forgotten.append(forgotten) + if networks_updated is not None: + self._networks_updated.append(networks_updated) + if disconnected is not None: + self._disconnected.append(disconnected) + + @property + def networks(self) -> list[Network]: + # Sort by connected/connecting, then known, then strength, then alphabetically. This is a pure UI ordering and should not affect underlying state. + return sorted(self._networks, key=lambda n: (n.ssid != self._wifi_state.ssid, not self.is_connection_saved(n.ssid), -n.strength, n.ssid.lower())) + + @property + def wifi_state(self) -> WifiState: + return self._wifi_state + + @property + def ipv4_address(self) -> str: + return self._ipv4_address + + @property + def current_network_metered(self) -> MeteredType: + return self._current_network_metered + + @property + def connecting_to_ssid(self) -> str | None: + wifi_state = self._wifi_state + return wifi_state.ssid if wifi_state.status == ConnectStatus.CONNECTING else None + + @property + def connected_ssid(self) -> str | None: + wifi_state = self._wifi_state + return wifi_state.ssid if wifi_state.status == ConnectStatus.CONNECTED else None + + @property + def tethering_password(self) -> str: + return self._tethering_password + + def _set_connecting(self, ssid: str | None): + # Called by user action, or sequentially from state change handler + self._user_epoch += 1 + self._wifi_state = WifiState(ssid=ssid, status=ConnectStatus.DISCONNECTED if ssid is None else ConnectStatus.CONNECTING) + + def _enqueue_callbacks(self, cbs: list[Callable], *args): + for cb in cbs: + self._callback_queue.append(lambda _cb=cb: _cb(*args)) + + def process_callbacks(self): + # Call from UI thread to run any pending callbacks + to_run, self._callback_queue = self._callback_queue, [] + for cb in to_run: + cb() + + def set_active(self, active: bool): + self._active = active + + # Update networks and WiFi state (to self-heal) immediately when activating for UI + if active: + self._init_wifi_state(block=False) + self._update_networks(block=False) + + def _monitor_state(self): + # Filter for signals + rules = ( + MatchRule( + type="signal", + interface=NM_DEVICE_IFACE, + member="StateChanged", + path=self._wifi_device, + ), + MatchRule( + type="signal", + interface=NM_SETTINGS_IFACE, + member="NewConnection", + path=NM_SETTINGS_PATH, + ), + MatchRule( + type="signal", + interface=NM_SETTINGS_IFACE, + member="ConnectionRemoved", + path=NM_SETTINGS_PATH, + ), + MatchRule( + type="signal", + interface=NM_PROPERTIES_IFACE, + member="PropertiesChanged", + path=self._wifi_device, + ), + ) + + for rule in rules: + self._conn_monitor.send_and_get_reply(message_bus.AddMatch(rule)) + + with (self._conn_monitor.filter(rules[0], bufsize=SIGNAL_QUEUE_SIZE) as state_q, + self._conn_monitor.filter(rules[1], bufsize=SIGNAL_QUEUE_SIZE) as new_conn_q, + self._conn_monitor.filter(rules[2], bufsize=SIGNAL_QUEUE_SIZE) as removed_conn_q, + self._conn_monitor.filter(rules[3], bufsize=SIGNAL_QUEUE_SIZE) as props_q): + while not self._exit: + try: + self._conn_monitor.recv_messages(timeout=1) + except TimeoutError: + continue + + # Connection added/removed + while len(removed_conn_q): + conn_path = removed_conn_q.popleft().body[0] + self._connection_removed(conn_path) + while len(new_conn_q): + conn_path = new_conn_q.popleft().body[0] + self._new_connection(conn_path) + + # PropertiesChanged on wifi device (LastScan = scan complete) + while len(props_q): + iface, changed, _ = props_q.popleft().body + if iface == NM_WIRELESS_IFACE and 'LastScan' in changed: + self._update_networks() + + # Device state changes + while len(state_q): + new_state, previous_state, change_reason = state_q.popleft().body + + self._handle_state_change(new_state, previous_state, change_reason) + + def _handle_state_change(self, new_state: int, prev_state: int, change_reason: int): + # Thread safety: _wifi_state is read/written by both the monitor thread (this handler) + # and the main thread (_set_connecting via connect/activate). PREPARE/CONFIG and ACTIVATED + # have a read-then-write pattern with a slow DBus call in between — if _set_connecting + # runs mid-call, the handler would overwrite the user's newer state with stale data. + # + # The _user_epoch counter solves this without locks. _set_connecting increments the epoch + # on every user action. Handlers snapshot the epoch before their DBus call and compare + # after: if it changed, a user action occurred during the call and the stale result is + # discarded. Combined with deterministic fixes (skip DBus lookup when ssid already set, + # DEACTIVATING clears CONNECTED on CONNECTION_REMOVED, CONNECTION_REMOVED guard), + # all known race windows are closed. + + # TODO: Handle (FAILED, SSID_NOT_FOUND) and emit for UI to show error + # Happens when network drops off after starting connection + + if new_state == NMDeviceState.DISCONNECTED: + if change_reason == NMDeviceStateReason.NEW_ACTIVATION: + return + + # Guard: forget A while connecting to B fires CONNECTION_REMOVED. Don't clear B's state + # if B is still a known connection. If B hasn't arrived in _connections yet (late + # NewConnection), state clears here but PREPARE recovers via DBus lookup. + if (change_reason == NMDeviceStateReason.CONNECTION_REMOVED and self._wifi_state.ssid and + self._wifi_state.ssid in self._connections): + return + + self._set_connecting(None) + + elif new_state in (NMDeviceState.PREPARE, NMDeviceState.CONFIG): + epoch = self._user_epoch + + if self._wifi_state.ssid is not None: + self._wifi_state = replace(self._wifi_state, status=ConnectStatus.CONNECTING) + return + + # Auto-connection when NetworkManager connects to known networks on its own (ssid=None): look up ssid from NM + wifi_state = replace(self._wifi_state, status=ConnectStatus.CONNECTING) + + conn_path, _ = self._get_active_wifi_connection(self._conn_monitor) + + # Discard if user acted during DBus call + if self._user_epoch != epoch: + return + + if conn_path is None: + cloudlog.warning("Failed to get active wifi connection during PREPARE/CONFIG state") + else: + wifi_state = replace(wifi_state, ssid=next((s for s, p in self._connections.items() if p == conn_path), None)) + + self._wifi_state = wifi_state + + # BAD PASSWORD + # - strong network rejects with NEED_AUTH+SUPPLICANT_DISCONNECT + # - weak/gone network fails with FAILED+NO_SECRETS + # TODO: sometimes on PC it's observed no future signals are fired if mouse is held down blocking wrong password dialog + elif ((new_state == NMDeviceState.NEED_AUTH and change_reason == NMDeviceStateReason.SUPPLICANT_DISCONNECT + and prev_state == NMDeviceState.CONFIG) or + (new_state == NMDeviceState.FAILED and change_reason == NMDeviceStateReason.NO_SECRETS)): + + # prev_state guard: real auth failures come from CONFIG (supplicant handshake). + # Stale NEED_AUTH from a prior connection during network switching arrives with + # prev_state=DISCONNECTED and must be ignored to avoid a false wrong-password callback. + if self._wifi_state.ssid: + self._enqueue_callbacks(self._need_auth, self._wifi_state.ssid) + self._set_connecting(None) + + elif new_state in (NMDeviceState.NEED_AUTH, NMDeviceState.IP_CONFIG, NMDeviceState.IP_CHECK, + NMDeviceState.SECONDARIES, NMDeviceState.FAILED): + pass + + elif new_state == NMDeviceState.ACTIVATED: + # Note that IP address from Ip4Config may not be propagated immediately and could take until the next scan results + epoch = self._user_epoch + wifi_state = replace(self._wifi_state, status=ConnectStatus.CONNECTED) + + conn_path, _ = self._get_active_wifi_connection(self._conn_monitor) + + # Discard if user acted during DBus call + if self._user_epoch != epoch: + return + + if conn_path is None: + cloudlog.warning("Failed to get active wifi connection during ACTIVATED state") + else: + wifi_state = replace(wifi_state, ssid=next((s for s, p in self._connections.items() if p == conn_path), None)) + + self._wifi_state = wifi_state + self._enqueue_callbacks(self._activated) + self._update_active_connection_info() + + # Persist volatile connections (created by AddAndActivateConnection2) to disk + if conn_path is not None: + conn_addr = DBusAddress(conn_path, bus_name=NM, interface=NM_CONNECTION_IFACE) + save_reply = self._conn_monitor.send_and_get_reply(new_method_call(conn_addr, 'Save')) + if save_reply.header.message_type == MessageType.error: + cloudlog.warning(f"Failed to persist connection to disk: {save_reply}") + + elif new_state == NMDeviceState.DEACTIVATING: + # Must clear state when forgetting the currently connected network so the UI + # doesn't flash "connected" after the eager "forgetting..." state resets + # (the forgotten callback fires between DEACTIVATING and DISCONNECTED). + # Only clear CONNECTED — CONNECTING must be preserved for forget-A-connect-B. + if change_reason == NMDeviceStateReason.CONNECTION_REMOVED and self._wifi_state.status == ConnectStatus.CONNECTED: + self._set_connecting(None) + + def _network_scanner(self): + while not self._exit: + if self._active: + if time.monotonic() - self._last_network_scan > SCAN_PERIOD_SECONDS: + self._request_scan() + self._last_network_scan = time.monotonic() + time.sleep(1 / 2.) + + def _wait_for_wifi_device(self): + while not self._exit: + device_path = self._get_adapter(NM_DEVICE_TYPE_WIFI) + if device_path is not None: + self._wifi_device = device_path + break + time.sleep(1) + + def _get_adapter(self, adapter_type: int) -> str | None: + # Return the first NetworkManager device path matching adapter_type + try: + device_paths = self._router_main.send_and_get_reply(new_method_call(self._nm, 'GetDevices')).body[0] + for device_path in device_paths: + dev_addr = DBusAddress(device_path, bus_name=NM, interface=NM_DEVICE_IFACE) + dev_type = self._router_main.send_and_get_reply(Properties(dev_addr).get('DeviceType')).body[0][1] + if dev_type == adapter_type: + return str(device_path) + except Exception as e: + cloudlog.exception(f"Error getting adapter type {adapter_type}: {e}") + return None + + def _init_connections(self) -> None: + settings_addr = DBusAddress(NM_SETTINGS_PATH, bus_name=NM, interface=NM_SETTINGS_IFACE) + known_connections = self._router_main.send_and_get_reply(new_method_call(settings_addr, 'ListConnections')).body[0] + + conns: dict[str, str] = {} + for conn_path in known_connections: + settings = self._get_connection_settings(conn_path) + + if len(settings) == 0: + cloudlog.warning(f'Failed to get connection settings for {conn_path}') + continue + + if "802-11-wireless" in settings: + ssid = settings['802-11-wireless']['ssid'][1].decode("utf-8", "replace") + if ssid != "": + conns[ssid] = conn_path + self._connections = conns + + def _new_connection(self, conn_path: str): + settings = self._get_connection_settings(conn_path) + + if "802-11-wireless" in settings: + ssid = settings['802-11-wireless']['ssid'][1].decode("utf-8", "replace") + if ssid != "": + self._connections[ssid] = conn_path + + def _connection_removed(self, conn_path: str): + self._connections = {ssid: path for ssid, path in self._connections.items() if path != conn_path} + + def _get_active_connections(self, router: DBusConnection | DBusRouter | None = None): + # Returns list of ActiveConnection + if router is None: + router = self._router_main + + return router.send_and_get_reply(Properties(self._nm).get('ActiveConnections')).body[0][1] + + def _get_active_wifi_connection(self, router: DBusConnection | DBusRouter | None = None) -> tuple[str | None, dict | None]: + # Returns first Connection settings path and ActiveConnection props from ActiveConnections with Type 802-11-wireless + if router is None: + router = self._router_main + + for active_conn in self._get_active_connections(router): + conn_addr = DBusAddress(active_conn, bus_name=NM, interface=NM_ACTIVE_CONNECTION_IFACE) + reply = router.send_and_get_reply(Properties(conn_addr).get_all()) + + if reply.header.message_type == MessageType.error: + cloudlog.warning(f"Failed to get active connection properties for {active_conn}: {reply}") + continue + + props = reply.body[0] + + conn_path = props.get('Connection', ('o', '/'))[1] + if props.get('Type', ('s', ''))[1] == '802-11-wireless' and conn_path != '/': + return conn_path, props + + return None, None + + def _get_connection_settings(self, conn_path: str) -> dict: + conn_addr = DBusAddress(conn_path, bus_name=NM, interface=NM_CONNECTION_IFACE) + reply = self._router_main.send_and_get_reply(new_method_call(conn_addr, 'GetSettings')) + if reply.header.message_type == MessageType.error: + cloudlog.warning(f'Failed to get connection settings: {reply}') + return {} + return dict(reply.body[0]) + + def _add_tethering_connection(self): + connection = { + 'connection': { + 'type': ('s', '802-11-wireless'), + 'uuid': ('s', str(uuid.uuid4())), + 'id': ('s', 'Hotspot'), + 'autoconnect-retries': ('i', 0), + 'interface-name': ('s', 'wlan0'), + 'autoconnect': ('b', False), + }, + '802-11-wireless': { + 'band': ('s', 'bg'), + 'mode': ('s', 'ap'), + 'ssid': ('ay', self._tethering_ssid.encode("utf-8")), + }, + '802-11-wireless-security': { + 'group': ('as', ['ccmp']), + 'key-mgmt': ('s', 'wpa-psk'), + 'pairwise': ('as', ['ccmp']), + 'proto': ('as', ['rsn']), + 'psk': ('s', DEFAULT_TETHERING_PASSWORD), + }, + 'ipv4': { + 'method': ('s', 'shared'), + 'address-data': ('aa{sv}', [[ + ('address', ('s', TETHERING_IP_ADDRESS)), + ('prefix', ('u', 24)), + ]]), + 'gateway': ('s', TETHERING_IP_ADDRESS), + 'never-default': ('b', True), + }, + 'ipv6': {'method': ('s', 'ignore')}, + } + + settings_addr = DBusAddress(NM_SETTINGS_PATH, bus_name=NM, interface=NM_SETTINGS_IFACE) + self._router_main.send_and_get_reply(new_method_call(settings_addr, 'AddConnection', 'a{sa{sv}}', (connection,))) + + def connect_to_network(self, ssid: str, password: str, hidden: bool = False): + self._set_connecting(ssid) + + def worker(): + # Clear all connections that may already exist to the network we are connecting to + self.forget_connection(ssid, block=True) + + connection = { + 'connection': { + 'type': ('s', '802-11-wireless'), + 'uuid': ('s', str(uuid.uuid4())), + 'id': ('s', f'sunnypilot connection {ssid}'), + 'autoconnect-retries': ('i', 0), + }, + '802-11-wireless': { + 'ssid': ('ay', ssid.encode("utf-8")), + 'hidden': ('b', hidden), + 'mode': ('s', 'infrastructure'), + }, + 'ipv4': { + 'method': ('s', 'auto'), + 'dns-priority': ('i', 600), + }, + 'ipv6': {'method': ('s', 'ignore')}, + } + + if password: + connection['802-11-wireless-security'] = { + 'key-mgmt': ('s', 'wpa-psk'), + 'auth-alg': ('s', 'open'), + 'psk': ('s', password), + } + + # Volatile connection auto-deletes on disconnect (wrong password, user switches networks) + # Persisted to disk on ACTIVATED via Save() + if self._wifi_device is None: + cloudlog.warning("No WiFi device found") + # TODO: expose a failed connection state in the UI + self._init_wifi_state() + return + + reply = self._router_main.send_and_get_reply(new_method_call(self._nm, 'AddAndActivateConnection2', 'a{sa{sv}}ooa{sv}', + (connection, self._wifi_device, "/", {'persist': ('s', 'volatile')}))) + + if reply.header.message_type == MessageType.error: + cloudlog.warning(f"Failed to add and activate connection for {ssid}: {reply}") + # TODO: expose a failed connection state in the UI + self._init_wifi_state() + + threading.Thread(target=worker, daemon=True).start() + + def forget_connection(self, ssid: str, block: bool = False): + def worker(): + conn_path = self._connections.get(ssid, None) + if conn_path is None: + cloudlog.warning(f"Trying to forget unknown connection: {ssid}") + else: + conn_addr = DBusAddress(conn_path, bus_name=NM, interface=NM_CONNECTION_IFACE) + self._router_main.send_and_get_reply(new_method_call(conn_addr, 'Delete')) + + self._enqueue_callbacks(self._forgotten, ssid) + + if block: + worker() + else: + threading.Thread(target=worker, daemon=True).start() + + def activate_connection(self, ssid: str, block: bool = False): + self._set_connecting(ssid) + + def worker(): + conn_path = self._connections.get(ssid, None) + if conn_path is None or self._wifi_device is None: + cloudlog.warning(f"Failed to activate connection for {ssid}: conn_path={conn_path}, wifi_device={self._wifi_device}") + # TODO: expose a failed connection state in the UI + self._init_wifi_state() + return + + reply = self._router_main.send_and_get_reply(new_method_call(self._nm, 'ActivateConnection', 'ooo', + (conn_path, self._wifi_device, "/"))) + + if reply.header.message_type == MessageType.error: + cloudlog.warning(f"Failed to activate connection for {ssid}: {reply}") + # TODO: expose a failed connection state in the UI + self._init_wifi_state() + + if block: + worker() + else: + threading.Thread(target=worker, daemon=True).start() + + def _deactivate_connection(self, ssid: str): + for active_conn in self._get_active_connections(): + conn_addr = DBusAddress(active_conn, bus_name=NM, interface=NM_ACTIVE_CONNECTION_IFACE) + reply = self._router_main.send_and_get_reply(Properties(conn_addr).get('SpecificObject')) + if reply.header.message_type == MessageType.error: + continue # object gone (e.g. rapid connect/disconnect) + + specific_obj_path = reply.body[0][1] + + if specific_obj_path != "/": + ap_addr = DBusAddress(specific_obj_path, bus_name=NM, interface=NM_ACCESS_POINT_IFACE) + ap_reply = self._router_main.send_and_get_reply(Properties(ap_addr).get('Ssid')) + if ap_reply.header.message_type == MessageType.error: + continue # AP gone (e.g. mode switch) + + ap_ssid = bytes(ap_reply.body[0][1]).decode("utf-8", "replace") + + if ap_ssid == ssid: + self._router_main.send_and_get_reply(new_method_call(self._nm, 'DeactivateConnection', 'o', (active_conn,))) + return + + def is_tethering_active(self) -> bool: + # Check ssid, not connected_ssid, to also catch connecting state + return self._wifi_state.ssid == self._tethering_ssid + + def is_connection_saved(self, ssid: str) -> bool: + return ssid in self._connections + + def set_tethering_password(self, password: str): + def worker(): + conn_path = self._connections.get(self._tethering_ssid, None) + if conn_path is None: + cloudlog.warning('No tethering connection found') + return + + settings = self._get_connection_settings(conn_path) + if len(settings) == 0: + cloudlog.warning(f'Failed to get tethering settings for {conn_path}') + return + + settings['802-11-wireless-security']['psk'] = ('s', password) + + conn_addr = DBusAddress(conn_path, bus_name=NM, interface=NM_CONNECTION_IFACE) + reply = self._router_main.send_and_get_reply(new_method_call(conn_addr, 'Update', 'a{sa{sv}}', (settings,))) + if reply.header.message_type == MessageType.error: + cloudlog.warning(f'Failed to update tethering settings: {reply}') + return + + self._tethering_password = password + if self.is_tethering_active(): + self.activate_connection(self._tethering_ssid, block=True) + + threading.Thread(target=worker, daemon=True).start() + + def _get_tethering_password(self) -> str: + conn_path = self._connections.get(self._tethering_ssid, None) + if conn_path is None: + cloudlog.warning('No tethering connection found') + return '' + + reply = self._router_main.send_and_get_reply(new_method_call( + DBusAddress(conn_path, bus_name=NM, interface=NM_CONNECTION_IFACE), + 'GetSecrets', 's', ('802-11-wireless-security',) + )) + + if reply.header.message_type == MessageType.error: + cloudlog.warning(f'Failed to get tethering password: {reply}') + return '' + + secrets = reply.body[0] + if '802-11-wireless-security' not in secrets: + return '' + + return str(secrets['802-11-wireless-security'].get('psk', ('s', ''))[1]) + + def set_ipv4_forward(self, enabled: bool): + self._ipv4_forward = enabled + + def set_tethering_active(self, active: bool): + def worker(): + if active: + self.activate_connection(self._tethering_ssid, block=True) + + if not self._ipv4_forward: + time.sleep(5) + cloudlog.warning("net.ipv4.ip_forward = 0") + subprocess.run(["sudo", "sysctl", "net.ipv4.ip_forward=0"], check=False) + else: + self._deactivate_connection(self._tethering_ssid) + + threading.Thread(target=worker, daemon=True).start() + + def set_current_network_metered(self, metered: MeteredType): + def worker(): + if self.is_tethering_active(): + return + + conn_path, _ = self._get_active_wifi_connection() + if conn_path is None: + cloudlog.warning('No active WiFi connection found') + return + + settings = self._get_connection_settings(conn_path) + + if len(settings) == 0: + cloudlog.warning(f'Failed to get connection settings for {conn_path}') + return + + settings['connection']['metered'] = ('i', int(metered)) + + conn_addr = DBusAddress(conn_path, bus_name=NM, interface=NM_CONNECTION_IFACE) + reply = self._router_main.send_and_get_reply(new_method_call(conn_addr, 'Update', 'a{sa{sv}}', (settings,))) + if reply.header.message_type == MessageType.error: + cloudlog.warning(f'Failed to update metered settings: {reply}') + + threading.Thread(target=worker, daemon=True).start() + + def _request_scan(self): + if self._wifi_device is None: + cloudlog.warning("No WiFi device found") + return + + wifi_addr = DBusAddress(self._wifi_device, bus_name=NM, interface=NM_WIRELESS_IFACE) + reply = self._router_main.send_and_get_reply(new_method_call(wifi_addr, 'RequestScan', 'a{sv}', ({},))) + + if reply.header.message_type == MessageType.error: + cloudlog.warning(f"Failed to request scan: {reply}") + + def _update_networks(self, block: bool = True): + if not self._active: + return + + def worker(): + with self._scan_lock: + if self._wifi_device is None: + cloudlog.warning("No WiFi device found") + return + + # NOTE: AccessPoints property may exclude hidden APs (use GetAllAccessPoints method if needed) + wifi_addr = DBusAddress(self._wifi_device, NM, interface=NM_WIRELESS_IFACE) + wifi_props_reply = self._router_main.send_and_get_reply(Properties(wifi_addr).get_all()) + if wifi_props_reply.header.message_type == MessageType.error: + cloudlog.warning(f"Failed to get WiFi properties: {wifi_props_reply}") + return + + ap_paths = wifi_props_reply.body[0].get('AccessPoints', ('ao', []))[1] + + aps: dict[str, list[AccessPoint]] = {} + + for ap_path in ap_paths: + ap_addr = DBusAddress(ap_path, NM, interface=NM_ACCESS_POINT_IFACE) + ap_props = self._router_main.send_and_get_reply(Properties(ap_addr).get_all()) + + # some APs have been seen dropping off during iteration + if ap_props.header.message_type == MessageType.error: + cloudlog.warning(f"Failed to get AP properties for {ap_path}") + continue + + try: + ap = AccessPoint.from_dbus(ap_props.body[0], ap_path) + if ap.ssid == "": + continue + + if ap.ssid not in aps: + aps[ap.ssid] = [] + + aps[ap.ssid].append(ap) + except Exception: + # catch all for parsing errors + cloudlog.exception(f"Failed to parse AP properties for {ap_path}") + + self._networks = [Network.from_dbus(ssid, ap_list, ssid == self._tethering_ssid) for ssid, ap_list in aps.items()] + self._update_active_connection_info() + self._enqueue_callbacks(self._networks_updated, self.networks) # sorted + + if block: + worker() + else: + threading.Thread(target=worker, daemon=True).start() + + def _update_active_connection_info(self): + ipv4_address = "" + metered = MeteredType.UNKNOWN + + conn_path, props = self._get_active_wifi_connection() + + if conn_path is not None and props is not None: + # IPv4 address + ip4config_path = props.get('Ip4Config', ('o', '/'))[1] + + if ip4config_path != "/": + ip4config_addr = DBusAddress(ip4config_path, bus_name=NM, interface=NM_IP4_CONFIG_IFACE) + address_data = self._router_main.send_and_get_reply(Properties(ip4config_addr).get('AddressData')).body[0][1] + + for entry in address_data: + if 'address' in entry: + ipv4_address = entry['address'][1] + break + + # Metered status + settings = self._get_connection_settings(conn_path) + + if len(settings) > 0: + metered_prop = settings['connection'].get('metered', ('i', 0))[1] + + if metered_prop == MeteredType.YES: + metered = MeteredType.YES + elif metered_prop == MeteredType.NO: + metered = MeteredType.NO + + self._ipv4_address = ipv4_address + self._current_network_metered = metered + + def __del__(self): + self.stop() + + def stop(self): + if not self._exit: + self._exit = True + if self._scan_thread.is_alive(): + self._scan_thread.join() + if self._state_thread.is_alive(): + self._state_thread.join() + + if self._router_main is not None: + self._router_main.close() + self._router_main.conn.close() + if self._conn_monitor is not None: + self._conn_monitor.close() diff --git a/openpilot/system/ui/lib/wrap_text.py b/openpilot/system/ui/lib/wrap_text.py new file mode 100644 index 0000000000..3fabfbb66b --- /dev/null +++ b/openpilot/system/ui/lib/wrap_text.py @@ -0,0 +1,107 @@ +import pyray as rl +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.lib.application import font_fallback + + +def _break_long_word(font: rl.Font, word: str, font_size: int, max_width: int, spacing: float = 0) -> list[str]: + if not word: + return [] + + parts = [] + remaining = word + + while remaining: + if measure_text_cached(font, remaining, font_size, spacing).x <= max_width: + parts.append(remaining) + break + + # Binary search for the longest substring that fits + left, right = 1, len(remaining) + best_fit = 1 + + while left <= right: + mid = (left + right) // 2 + substring = remaining[:mid] + width = measure_text_cached(font, substring, font_size, spacing).x + + if width <= max_width: + best_fit = mid + left = mid + 1 + else: + right = mid - 1 + + # Add the part that fits + parts.append(remaining[:best_fit]) + remaining = remaining[best_fit:] + + return parts + + +_cache: dict[int, list[str]] = {} + + +def wrap_text(font: rl.Font, text: str, font_size: int, max_width: int, spacing: float = 0) -> list[str]: + font = font_fallback(font) + spacing = round(spacing, 4) + key = hash((font.texture.id, text, font_size, max_width, spacing)) + if key in _cache: + return _cache[key] + + if not text or max_width <= 0: + return [] + + # Split text by newlines first to preserve explicit line breaks + paragraphs = text.split('\n') + all_lines: list[str] = [] + + for paragraph in paragraphs: + # Handle empty paragraphs (preserve empty lines) + if not paragraph.strip(): + all_lines.append("") + continue + + # Process each paragraph separately + words = paragraph.split() + if not words: + all_lines.append("") + continue + + lines: list[str] = [] + current_line: list[str] = [] + + for word in words: + word_width = measure_text_cached(font, word, font_size, spacing).x + + # Check if word alone exceeds max width (need to break the word) + if word_width > max_width: + # Finish current line if it has content + if current_line: + lines.append(" ".join(current_line)) + current_line = [] + + # Break the long word into parts + lines.extend(_break_long_word(font, word, font_size, max_width, spacing)) + continue + + # Measure the actual joined string to get accurate width (accounts for kerning, etc.) + test_line = " ".join(current_line + [word]) if current_line else word + test_width = measure_text_cached(font, test_line, font_size, spacing).x + + # Check if word fits on current line + if test_width <= max_width: + current_line.append(word) + else: + # Start new line with this word + if current_line: + lines.append(" ".join(current_line)) + current_line = [word] + + # Add remaining words + if current_line: + lines.append(" ".join(current_line)) + + # Add all lines from this paragraph + all_lines.extend(lines) + + _cache[key] = all_lines + return all_lines diff --git a/openpilot/system/ui/mici_reset.py b/openpilot/system/ui/mici_reset.py new file mode 100755 index 0000000000..97ecaf7024 --- /dev/null +++ b/openpilot/system/ui/mici_reset.py @@ -0,0 +1,154 @@ +#!/usr/bin/env python3 +import subprocess +import sys +import time +import threading +from enum import IntEnum + +import pyray as rl + +from openpilot.common.hardware import HARDWARE, PC +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.widgets.scroller import Scroller +from openpilot.system.ui.mici_setup import GreyBigButton, FailedPage +from openpilot.selfdrive.ui.mici.widgets.dialog import BigDialog, BigConfirmationCircleButton + +USERDATA = "/dev/disk/by-partlabel/userdata" +TIMEOUT = 3*60 + + +class ResetMode(IntEnum): + USER_RESET = 0 # user initiated a factory reset from openpilot + RECOVER = 1 # userdata is corrupt for some reason, give a chance to recover + TAP_RESET = 2 # user initiated a factory reset by tapping the screen during boot + + +class ResetFailedPage(FailedPage): + def __init__(self): + super().__init__(None, "reset failed", "reboot to try again", icon="icons_mici/setup/reset_failed.png") + + def show_event(self): + super().show_event() + self._nav_bar._alpha = 0.0 # not dismissable + + def _back_enabled(self) -> bool: + return False + + +class ResettingPage(BigDialog): + DOT_STEP = 0.6 + + def __init__(self): + super().__init__("resetting device", "this may take up to\na minute...", + gui_app.texture("icons_mici/setup/factory_reset.png", 64, 64)) + self._show_time = 0.0 + + def show_event(self): + super().show_event() + self._nav_bar._alpha = 0.0 # not dismissable + self._show_time = rl.get_time() + + def _back_enabled(self) -> bool: + return False + + def _render(self, _): + t = (rl.get_time() - self._show_time) % (self.DOT_STEP * 2) + dots = "." * min(int(t / (self.DOT_STEP / 4)), 3) + self._card.set_value(f"this may take up to\na minute{dots}") + super()._render(_) + + +class Reset(Scroller): + def __init__(self, mode): + super().__init__() + self._mode = mode + self._previous_active_widget = None + self._reset_failed = False + self._timeout_st = time.monotonic() + + self._resetting_page = ResettingPage() + self._reset_failed_page = ResetFailedPage() + + self._reset_button = BigConfirmationCircleButton("reset &\nerase", gui_app.texture("icons_mici/settings/device/uninstall.png", 70, 70), + self._start_reset, exit_on_confirm=False, red=True) + self._cancel_button = BigConfirmationCircleButton("cancel", gui_app.texture("icons_mici/setup/cancel.png", 64, 64), + gui_app.request_close, exit_on_confirm=False) + self._reboot_button = BigConfirmationCircleButton("reboot\ndevice", gui_app.texture("icons_mici/settings/device/reboot.png", 64, 70), + HARDWARE.reboot, exit_on_confirm=False) + + # show reboot button if in recover mode + self._cancel_button.set_visible(mode != ResetMode.RECOVER) + self._reboot_button.set_visible(mode == ResetMode.RECOVER) + + main_card = GreyBigButton("factory reset", "resetting erases\nall user content & data", + gui_app.texture("icons_mici/setup/factory_reset.png", 64, 64)) + self._scroller.add_widget(main_card) + + if mode != ResetMode.USER_RESET: + self._scroller.add_widget(GreyBigButton("", "Resetting erases all user content & data.")) + if mode == ResetMode.RECOVER: + main_card.set_value("user data partition\ncould not be mounted") + elif mode == ResetMode.TAP_RESET: + main_card.set_value("reset triggered by\ntapping the screen") + + self._scroller.add_widgets([ + GreyBigButton("", "For a deeper reset, go to\nhttps://flash.comma.ai"), + self._cancel_button, + self._reboot_button, + self._reset_button, + ]) + + gui_app.add_nav_stack_tick(self._nav_stack_tick) + + def _do_erase(self): + if PC: + return + + # Removing data and formatting + rm = subprocess.run("sudo rm -rf /data/*", shell=True).returncode + subprocess.run(f"sudo umount {USERDATA}", shell=True) + fmt = subprocess.run(f"yes | sudo mkfs.ext4 {USERDATA}", shell=True).returncode + + if rm == 0 or fmt == 0: + subprocess.run("sudo reboot", shell=True) + else: + self._reset_failed = True + + def _start_reset(self): + def do_erase_thread(): + threading.Thread(target=self._do_erase, daemon=True).start() + + self._resetting_page.set_shown_callback(do_erase_thread) + gui_app.push_widget(self._resetting_page) + + def _nav_stack_tick(self): + if self._reset_failed: + self._reset_failed = False + gui_app.pop_widgets_to(self, lambda: gui_app.push_widget(self._reset_failed_page)) + + active_widget = gui_app.get_active_widget() + if active_widget != self._previous_active_widget: + self._previous_active_widget = active_widget + self._timeout_st = time.monotonic() + elif self._mode != ResetMode.RECOVER and active_widget != self._resetting_page and (time.monotonic() - self._timeout_st) > TIMEOUT: + exit(0) + + +def main(): + mode = ResetMode.USER_RESET + if len(sys.argv) > 1: + if sys.argv[1] == '--recover': + mode = ResetMode.RECOVER + elif sys.argv[1] == '--tap-reset': + mode = ResetMode.TAP_RESET + + gui_app.init_window("System Reset") + reset = Reset(mode) + gui_app.push_widget(reset) + + for _ in gui_app.render(): + pass + + +if __name__ == "__main__": + main() diff --git a/openpilot/system/ui/mici_setup.py b/openpilot/system/ui/mici_setup.py new file mode 100755 index 0000000000..e446697cfe --- /dev/null +++ b/openpilot/system/ui/mici_setup.py @@ -0,0 +1,593 @@ +#!/usr/bin/env python3 +import os +import re +import ssl +import threading +import time +import urllib.request +import urllib.error +from urllib.parse import urlparse +from collections.abc import Callable + +import pyray as rl + +from openpilot.cereal import log +from openpilot.common.filter_simple import BounceFilter +from openpilot.common.hardware import HARDWARE, TICI +from openpilot.common.realtime import config_realtime_process, set_core_affinity +from openpilot.common.swaglog import cloudlog +from openpilot.common.time_helpers import system_time_valid +from openpilot.common.utils import run_cmd +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.lib.wifi_manager import WifiManager, ConnectStatus +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.nav_widget import NavWidget +from openpilot.system.ui.widgets.label import UnifiedLabel +from openpilot.system.ui.widgets.scroller import Scroller, NavScroller, ITEM_SPACING +from openpilot.system.ui.widgets.slider import LargerSlider +from openpilot.selfdrive.ui.mici.layouts.settings.network import WifiNetworkButton +from openpilot.selfdrive.ui.mici.layouts.settings.network.wifi_ui import WifiUIMici +from openpilot.selfdrive.ui.mici.widgets.dialog import BigInputDialog, BigConfirmationCircleButton +from openpilot.selfdrive.ui.mici.widgets.button import BigButton, GreyBigButton + +NetworkType = log.DeviceState.NetworkType + +OPENPILOT_URL = "https://openpilot.comma.ai" +USER_AGENT = f"AGNOSSetup-{HARDWARE.get_os_version()}" + +INSTALLER_DESTINATION_PATH = "/tmp/installer" +INSTALLER_URL_PATH = "/tmp/installer_url" + + +class NetworkConnectivityMonitor: + def __init__(self, should_check: Callable[[], bool] | None = None): + self.network_connected = threading.Event() + self.wifi_connected = threading.Event() + self.recheck_event = threading.Event() + self._should_check = should_check or (lambda: True) + self._stop_event = threading.Event() + self._last_timesyncd_restart = 0.0 + self._thread: threading.Thread | None = None + + def start(self): + self._stop_event.clear() + if self._thread is None or not self._thread.is_alive(): + self._thread = threading.Thread(target=self._run, daemon=True) + self._thread.start() + + def stop(self): + if self._thread is not None: + self._stop_event.set() + self._thread.join() + self._thread = None + + def reset(self): + self.network_connected.clear() + self.wifi_connected.clear() + + def invalidate(self): + self.recheck_event.set() + self.reset() + + def _run(self): + while not self._stop_event.is_set(): + if self._should_check(): + try: + request = urllib.request.Request(OPENPILOT_URL, method="HEAD") + urllib.request.urlopen(request, timeout=2.0) + + # Discard stale result if invalidated during request + if self.recheck_event.is_set(): + self.recheck_event.clear() + continue + + self.network_connected.set() + if HARDWARE.get_network_type() == NetworkType.wifi: + self.wifi_connected.set() + except urllib.error.URLError as e: + if (isinstance(e.reason, ssl.SSLCertVerificationError) and + not system_time_valid() and + time.monotonic() - self._last_timesyncd_restart > 5): + self._last_timesyncd_restart = time.monotonic() + run_cmd(["sudo", "systemctl", "restart", "systemd-timesyncd"]) + self.reset() + except Exception: + self.reset() + else: + self.reset() + + if self._stop_event.wait(timeout=1.0): + break + + +class StartPage(Widget): + def __init__(self): + super().__init__() + + self._title = UnifiedLabel("start", 64, text_color=rl.Color(255, 255, 255, int(255 * 0.9)), + font_weight=FontWeight.DISPLAY, alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER, + alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE) + + self._start_bg_txt = gui_app.texture("icons_mici/setup/start_button.png", 500, 224, keep_aspect_ratio=False) + self._start_bg_pressed_txt = gui_app.texture("icons_mici/setup/start_button_pressed.png", 500, 224, keep_aspect_ratio=False) + self._scale_filter = BounceFilter(1.0, 0.1, 1 / gui_app.target_fps) + self._click_delay = 0.075 + + def _render(self, rect: rl.Rectangle): + scale = self._scale_filter.update(1.07 if self.is_pressed else 1.0) + base_draw_x = rect.x + (rect.width - self._start_bg_txt.width) / 2 + base_draw_y = rect.y + (rect.height - self._start_bg_txt.height) / 2 + draw_x = base_draw_x + (self._start_bg_txt.width * (1 - scale)) / 2 + draw_y = base_draw_y + (self._start_bg_txt.height * (1 - scale)) / 2 + texture = self._start_bg_pressed_txt if self.is_pressed else self._start_bg_txt + rl.draw_texture_ex(texture, (draw_x, draw_y), 0, scale, rl.WHITE) + + self._title.render(rl.Rectangle(rect.x, rect.y + (draw_y - base_draw_y), rect.width, rect.height)) + + +class SoftwareSelectionPage(NavWidget): + def __init__(self, use_openpilot_callback: Callable, + use_custom_software_callback: Callable): + super().__init__() + + self._openpilot_slider = self._child(LargerSlider("slide to install\nopenpilot", use_openpilot_callback)) + self._openpilot_slider.set_enabled(lambda: self.enabled and not self.is_dismissing) + self._custom_software_slider = self._child(LargerSlider("slide to install\ncustom software", use_custom_software_callback, green=False, shimmer_offset=0.4)) + self._custom_software_slider.set_enabled(lambda: self.enabled and not self.is_dismissing) + + def show_event(self): + super().show_event() + self._nav_bar._alpha = 0.0 + + def _update_state(self): + super()._update_state() + if self.is_dismissing: + self.reset() + + def reset(self): + self._openpilot_slider.reset() + self._custom_software_slider.reset() + + def _render(self, rect: rl.Rectangle): + self._openpilot_slider.set_opacity(1.0 - self._custom_software_slider.slider_percentage) + self._custom_software_slider.set_opacity(1.0 - self._openpilot_slider.slider_percentage) + + openpilot_rect = rl.Rectangle( + rect.x + (rect.width - self._openpilot_slider.rect.width) / 2, + rect.y, + self._openpilot_slider.rect.width, + rect.height / 2, + ) + self._openpilot_slider.render(openpilot_rect) + + custom_software_rect = rl.Rectangle( + rect.x + (rect.width - self._custom_software_slider.rect.width) / 2, + rect.y + rect.height / 2, + self._custom_software_slider.rect.width, + rect.height / 2, + ) + self._custom_software_slider.render(custom_software_rect) + + +class CustomSoftwareWarningPage(NavScroller): + def __init__(self, continue_callback: Callable, back_callback: Callable): + super().__init__() + self.set_back_callback(back_callback) + + self._continue_button = BigPillButton("next") + self._continue_button.set_click_callback(continue_callback) + + self._scroller.add_widgets([ + GreyBigButton("caution: installing\n3rd party software", "swipe down to go back", + gui_app.texture("icons_mici/setup/warning.png", 64, 58)), + GreyBigButton("", "• It has not been tested by comma."), + GreyBigButton("", "• It may not comply with safety standards."), + GreyBigButton("", "• It may damage your device and/or vehicle."), + GreyBigButton("how to restore to a\nfactory state later", "https://flash.comma.ai", + gui_app.texture("icons_mici/setup/restore.png", 64, 64)), + self._continue_button, + ]) + + +# TODO: unifi with updater's progress page +class DownloadingPage(NavWidget): + def __init__(self): + super().__init__() + + self._title_label = UnifiedLabel("downloading...", 64, text_color=rl.Color(255, 255, 255, int(255 * 0.9)), + font_weight=FontWeight.DISPLAY) + self._progress_label = UnifiedLabel("", 132, text_color=rl.Color(255, 255, 255, int(255 * 0.9 * 0.65)), + font_weight=FontWeight.ROMAN, alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_BOTTOM) + self._progress = 0 + + def _back_enabled(self) -> bool: + return False + + def show_event(self): + super().show_event() + self._nav_bar._alpha = 0.0 # not dismissable + self.set_progress(0) + + def set_progress(self, progress: int): + self._progress = progress + self._progress_label.set_text(f"{progress}%") + + def _render(self, rect: rl.Rectangle): + rl.draw_rectangle_rec(rect, rl.BLACK) + self._title_label.render(rl.Rectangle( + rect.x + 12, + rect.y + 2, + rect.width, + 64, + )) + + self._progress_label.render(rl.Rectangle( + rect.x + 12, + rect.y + 18, + rect.width, + rect.height, + )) + + +class FailedPage(NavScroller): + def __init__(self, retry_callback: Callable | None, title: str = "download failed", + description: str | None = None, icon: str = "icons_mici/setup/warning.png"): + super().__init__() + self.set_back_callback(retry_callback) + + self._reason_card = GreyBigButton("", "") + self._reason_card.set_visible(False) + + self._scroller.add_widgets([ + GreyBigButton(title, description or "swipe down to go\nback and try again", + gui_app.texture(icon, 64, 58)), + self._reason_card, + BigConfirmationCircleButton("reboot\ndevice", gui_app.texture("icons_mici/settings/device/reboot.png", 64, 70), + HARDWARE.reboot, exit_on_confirm=False), + ]) + + def set_reason(self, reason: str): + if reason: + self._reason_card.set_value(reason) + self._reason_card.set_visible(True) + else: + self._reason_card.set_visible(False) + + +class BigPillButton(BigButton): + def __init__(self, *args, green: bool = False, disabled_background: bool = False, **kwargs): + self._green = green + self._disabled_background = disabled_background + super().__init__(*args, **kwargs) + + self._label.set_font_size(48) + self._label.set_alignment(rl.GuiTextAlignment.TEXT_ALIGN_CENTER) + self._label.set_alignment_vertical(rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE) + + def _load_images(self): + if self._green: + self._txt_default_bg = gui_app.texture("icons_mici/setup/start_button.png", 402, 180) + self._txt_pressed_bg = gui_app.texture("icons_mici/setup/start_button_pressed.png", 402, 180) + else: + self._txt_default_bg = gui_app.texture("icons_mici/setup/continue.png", 402, 180) + self._txt_pressed_bg = gui_app.texture("icons_mici/setup/continue_pressed.png", 402, 180) + self._txt_disabled_bg = gui_app.texture("icons_mici/setup/continue_disabled.png", 402, 180) + + def set_green(self, green: bool): + if self._green != green: + self._green = green + self._load_images() + + def _update_label_layout(self): + # Don't change label text size + pass + + def _handle_background(self) -> tuple[rl.Texture, float, float, float]: + txt_bg, btn_x, btn_y, scale = super()._handle_background() + + if self._disabled_background: + txt_bg = self._txt_disabled_bg + return txt_bg, btn_x, btn_y, scale + + +class NetworkSetupPageBase(Scroller): + def __init__(self, network_monitor: NetworkConnectivityMonitor, continue_callback: Callable[[bool], None], + disable_connect_hint: bool = False): + super().__init__() + + self._wifi_manager = WifiManager() + self._wifi_manager.set_active(True) + self._network_monitor = network_monitor + self._custom_software = False + self._wifi_ui = WifiUIMici(self._wifi_manager) + + self._connect_button = GreyBigButton("connect to\ninternet", "swipe down to go back", + gui_app.texture("icons_mici/setup/small_slider/slider_arrow.png", 64, 56, flip_x=True)) + self._connect_button.set_visible(not disable_connect_hint) + + self._wifi_button = WifiNetworkButton(self._wifi_manager) + self._wifi_button.set_click_callback(lambda: gui_app.push_widget(self._wifi_ui)) + + self._prev_has_internet = False + self._prev_wifi_connected = False + self._pending_has_internet_scroll: float | None = None # stores time to use as delay + self._pending_continue_grow_animation = False + self._pending_wifi_grow_animation = False + + def on_waiting_click(): + offset = (self._wifi_button.rect.x + self._wifi_button.rect.width / 2) - (self._rect.x + self._rect.width / 2) + self._scroller.scroll_to(offset, smooth=True, block_interrupt=True, block_widget_interaction=True) + # trigger grow when wifi button in view + self._pending_wifi_grow_animation = True + + self._waiting_button = BigPillButton("connect to\ncontinue", disabled_background=True) + self._waiting_button.set_click_callback(on_waiting_click) + self._continue_button = BigPillButton("install openpilot", green=True) + self._continue_button.set_click_callback(lambda: continue_callback(self._custom_software)) + + self._scroller.add_widgets([ + self._connect_button, + self._wifi_button, + self._continue_button, + self._waiting_button, + ]) + + gui_app.add_nav_stack_tick(self._nav_stack_tick) + + def show_event(self): + super().show_event() + # make sure we populate strength and ip immediately if already have wifi + self._wifi_manager.set_active(True) + self._prev_has_internet = self._has_internet + self._prev_wifi_connected = self._wifi_manager.wifi_state.status == ConnectStatus.CONNECTED + self._pending_has_internet_scroll = None + self._pending_continue_grow_animation = False + self._pending_wifi_grow_animation = False + + if self._prev_has_internet or self._prev_wifi_connected: + self.set_shown_callback(lambda: self._scroll_to_end_and_grow()) + + @property + def _has_internet(self) -> bool: + network_changing = self._wifi_ui.any_network_forgetting or self._wifi_manager.wifi_state.status == ConnectStatus.CONNECTING + if network_changing: + self._network_monitor.invalidate() + + has_internet = (self._network_monitor.network_connected.is_set() and + not network_changing and + not self._network_monitor.recheck_event.is_set()) + return has_internet + + def _nav_stack_tick(self): + # Only run tick when this page or its WiFi UI is on the stack + if gui_app.get_active_widget() is not self and not gui_app.widget_in_stack(self._wifi_ui): + self._wifi_manager.process_callbacks() + return + + # Check network state before processing callbacks so forgetting flag + # is still set on the frame the forgotten callback fires + has_internet = self._has_internet + wifi_connected = self._wifi_manager.wifi_state.status == ConnectStatus.CONNECTED + + self._continue_button.set_visible(has_internet) + self._waiting_button.set_visible(not has_internet) + + # TODO: fire show/hide events on visibility changes + if not has_internet: + self._pending_continue_grow_animation = False + self._waiting_button.set_text("waiting for\ninternet..." if wifi_connected else "connect to\ncontinue") + + self._wifi_manager.process_callbacks() + + # Dismiss WiFi UI and scroll on WiFi connect or internet gain + if (has_internet and not self._prev_has_internet) or (wifi_connected and not self._prev_wifi_connected): + # TODO: cancel if connect is transient + self._pending_has_internet_scroll = rl.get_time() + + self._prev_has_internet = has_internet + self._prev_wifi_connected = wifi_connected + + if self._pending_has_internet_scroll is not None: + # Scrolls over to continue button, then grows once in view + elapsed = rl.get_time() - self._pending_has_internet_scroll + if elapsed > 0.7 or gui_app.get_active_widget() is self: # instant scroll + grow if not popping + # Animate WifiUi down first before scroll + self._pending_has_internet_scroll = None + gui_app.pop_widgets_to(self, self._scroll_to_end_and_grow) + + def _scroll_to_end_and_grow(self): + self._scroller._layout() + end_offset = -(self._scroller.content_size - self._rect.width) + remaining = self._scroller.scroll_panel.get_offset() - end_offset + self._scroller.scroll_to(remaining, smooth=True, block_interrupt=True, block_widget_interaction=True) + self._pending_continue_grow_animation = True + + def set_custom_software(self, custom_software: bool): + self._custom_software = custom_software + self._continue_button.set_text("install openpilot" if not custom_software else "choose software") + self._continue_button.set_green(not custom_software) + + def _update_state(self): + super()._update_state() + + if self._pending_continue_grow_animation: + btn_right = self._continue_button.rect.x + self._continue_button.rect.width + visible_right = self._rect.x + self._rect.width + if btn_right < visible_right + 50: + self._pending_continue_grow_animation = False + self._continue_button.trigger_grow_animation() + + if self._pending_wifi_grow_animation and abs(self._wifi_button.rect.x - ITEM_SPACING) < 50: + self._pending_wifi_grow_animation = False + self._wifi_button.trigger_grow_animation() + + +class NetworkSetupPage(NetworkSetupPageBase, NavScroller): + def __init__(self, network_monitor: NetworkConnectivityMonitor, continue_callback: Callable[[bool], None], + back_callback: Callable[[], None] | None): + super().__init__(network_monitor, continue_callback) + self.set_back_callback(back_callback) + + +class Setup(Widget): + def __init__(self): + super().__init__() + self.download_url = "" + self.download_progress = 0 + self.download_thread = None + self._download_failed_reason: str | None = None + + self._network_monitor = NetworkConnectivityMonitor() + self._network_monitor.start() + + def getting_started_button_callback(): + gui_app.push_widget(self._software_selection_page) + + self._start_page = StartPage() + self._start_page.set_click_callback(getting_started_button_callback) + self._start_page.set_enabled(lambda: self.enabled) # for nav stack + + self._network_setup_page = NetworkSetupPage(self._network_monitor, self._network_setup_continue_callback, self._pop_to_software_selection) + + self._software_selection_page = SoftwareSelectionPage(self._push_network_setup, lambda: gui_app.push_widget(self._custom_software_warning_page)) + + self._download_failed_page = FailedPage(self._pop_to_software_selection, icon="icons_mici/setup/red_warning.png") + + self._custom_software_warning_page = CustomSoftwareWarningPage(lambda: self._push_network_setup(True), self._pop_to_software_selection) + + self._downloading_page = DownloadingPage() + + gui_app.add_nav_stack_tick(self._nav_stack_tick) + + def _nav_stack_tick(self): + self._downloading_page.set_progress(self.download_progress) + + if self._download_failed_reason is not None: + reason = self._download_failed_reason + self._download_failed_reason = None + self._download_failed_page.set_reason(reason) + gui_app.pop_widgets_to(self._software_selection_page, lambda: gui_app.push_widget(self._download_failed_page)) + + def _render(self, rect: rl.Rectangle): + self._start_page.render(rect) + + def close(self): + self._network_monitor.stop() + + def _pop_to_software_selection(self): + # reset sliders after dismiss completes + gui_app.pop_widgets_to(self._software_selection_page, self._software_selection_page.reset) + + def _push_network_setup(self, custom_software: bool = False): + # to fire the correct continue callback later + self._network_setup_page.set_custom_software(custom_software) + gui_app.push_widget(self._network_setup_page) + + def _network_setup_continue_callback(self, custom_software: bool): + if not custom_software: + self._download(OPENPILOT_URL) + else: + def handle_keyboard_result(text): + url = text.strip() + if url: + self._download(url) + + keyboard = BigInputDialog("custom software URL...", confirm_callback=handle_keyboard_result, auto_return_to_letters="./") + gui_app.push_widget(keyboard) + + def _download(self, url: str): + # autocomplete incomplete URLs + if re.match("^([^/.]+)/([^/]+)$", url): + url = f"https://installer.comma.ai/{url}" + + parsed = urlparse(url, scheme='https') + self.download_url = (urlparse(f"https://{url}") if not parsed.netloc else parsed).geturl() + self.download_progress = 0 + + def start_download(): + self.download_thread = threading.Thread(target=self._download_thread, daemon=True) + self.download_thread.start() + + self._downloading_page.set_shown_callback(start_download) + gui_app.push_widget(self._downloading_page) + + def _download_thread(self): + try: + import tempfile + + fd, tmpfile = tempfile.mkstemp(prefix="installer_") + + headers = {"User-Agent": USER_AGENT, + "X-openpilot-serial": HARDWARE.get_serial(), + "X-openpilot-device-type": HARDWARE.get_device_type()} + req = urllib.request.Request(self.download_url, headers=headers) + + with open(tmpfile, 'wb') as f, urllib.request.urlopen(req, timeout=30) as response: + total_size = int(response.headers.get('content-length', 0)) + downloaded = 0 + block_size = 8192 + + while True: + buffer = response.read(block_size) + if not buffer: + break + + downloaded += len(buffer) + f.write(buffer) + + if total_size: + self.download_progress = int(downloaded * 100 / total_size) + + is_elf = False + with open(tmpfile, 'rb') as f: + header = f.read(4) + is_elf = header == b'\x7fELF' + + if not is_elf: + self._download_failed_reason = "No custom software found at this URL: " + self.download_url.replace("https://", "", 1) + return + + # NOTE: currently unused, for future logging + with open(INSTALLER_URL_PATH, "w") as f: + f.write(self.download_url) + + # AGNOS might try to execute the installer before this process exits. + # Therefore, important to close the fd before renaming the installer. + os.close(fd) + os.rename(tmpfile, INSTALLER_DESTINATION_PATH) + + # give time for installer UI to take over + time.sleep(0.1) + gui_app.request_close() + + except urllib.error.HTTPError as e: + if e.code == 409: + self._download_failed_reason = "Incompatible sunnypilot version." + except Exception: + self._download_failed_reason = "Invalid URL: " + self.download_url.replace("https://", "", 1) + + +def main(): + config_realtime_process(0, 51) + # attempt to affine. AGNOS will start setup with all cores, should only fail when manually launching with screen off + if TICI: + try: + set_core_affinity([5]) + except OSError: + cloudlog.exception("Failed to set core affinity for setup process") + + try: + gui_app.init_window("Setup") + setup = Setup() + gui_app.push_widget(setup) + for _ in gui_app.render(): + pass + setup.close() + except Exception as e: + print(f"Setup error: {e}") + finally: + gui_app.close() + + +if __name__ == "__main__": + main() diff --git a/openpilot/system/ui/mici_updater.py b/openpilot/system/ui/mici_updater.py new file mode 100755 index 0000000000..a072354cf0 --- /dev/null +++ b/openpilot/system/ui/mici_updater.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python3 +import sys +import subprocess +import threading +import pyray as rl + +from openpilot.common.realtime import config_realtime_process, set_core_affinity +from openpilot.common.hardware import HARDWARE, TICI +from openpilot.common.swaglog import cloudlog +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.widgets.nav_widget import NavWidget +from openpilot.system.ui.widgets.scroller import Scroller +from openpilot.system.ui.widgets.label import UnifiedLabel +from openpilot.system.ui.mici_setup import (NetworkSetupPage, FailedPage, NetworkConnectivityMonitor, + GreyBigButton, BigPillButton) + + +class UpdaterNetworkSetupPage(NetworkSetupPage): + def __init__(self, network_monitor, continue_callback): + super().__init__(network_monitor, continue_callback, back_callback=None) + self._continue_button.set_text("download\n& install") + self._continue_button.set_green(False) + + +class ProgressPage(NavWidget): + def __init__(self): + super().__init__() + + self._progress_title_label = UnifiedLabel("", 64, text_color=rl.Color(255, 255, 255, int(255 * 0.9)), + font_weight=FontWeight.DISPLAY, line_height=0.8) + self._progress_percent_label = UnifiedLabel("", 132, text_color=rl.Color(255, 255, 255, int(255 * 0.9 * 0.65)), + font_weight=FontWeight.ROMAN, + alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_BOTTOM) + + def _back_enabled(self) -> bool: + return False + + def set_progress(self, text: str, value: int): + self._progress_title_label.set_text(text.replace("_", "_\n") + "...") + self._progress_percent_label.set_text(f"{value}%") + + def show_event(self): + super().show_event() + self._nav_bar._alpha = 0.0 # not dismissable + self.set_progress("downloading", 0) + + def _render(self, rect: rl.Rectangle): + rl.draw_rectangle_rec(rect, rl.BLACK) + self._progress_title_label.render(rl.Rectangle( + rect.x + 12, + rect.y + 2, + rect.width, + self._progress_title_label.get_content_height(int(rect.width - 20)), + )) + + self._progress_percent_label.render(rl.Rectangle( + rect.x + 12, + rect.y + 18, + rect.width, + rect.height, + )) + + +class Updater(Scroller): + def __init__(self, updater_path, manifest_path): + super().__init__() + self.updater = updater_path + self.manifest = manifest_path + + self.progress_value = 0 + self.progress_text = "loading" + self.process = None + self.update_thread = None + self._update_failed = False + + self._network_monitor = NetworkConnectivityMonitor() + self._network_monitor.start() + + self._network_setup_page = UpdaterNetworkSetupPage(self._network_monitor, self._network_setup_continue_callback) + + self._progress_page = ProgressPage() + + self._failed_page = FailedPage(self._retry, title="update failed") + + self._continue_button = BigPillButton("next") + self._continue_button.set_click_callback(lambda: gui_app.push_widget(self._network_setup_page)) + + self._scroller.add_widgets([ + GreyBigButton("update required", "the download size\nis approximately 1 GB", + gui_app.texture("icons_mici/offroad_alerts/green_wheel.png", 64, 64)), + self._continue_button, + ]) + + gui_app.add_nav_stack_tick(self._nav_stack_tick) + + def _network_setup_continue_callback(self, _): + self.install_update() + + def _retry(self): + gui_app.pop_widgets_to(self) + + def _nav_stack_tick(self): + self._progress_page.set_progress(self.progress_text, self.progress_value) + + if self._update_failed: + self._update_failed = False + self.show_event() + gui_app.pop_widgets_to(self, lambda: gui_app.push_widget(self._failed_page)) + + def install_update(self): + self.progress_value = 0 + self.progress_text = "downloading" + + def start_update(): + self.update_thread = threading.Thread(target=self._run_update_process, daemon=True) + self.update_thread.start() + + # Start the update process in a separate thread *after* show animation completes + self._progress_page.set_shown_callback(start_update) + gui_app.push_widget(self._progress_page) + + def _run_update_process(self): + # TODO: just import it and run in a thread without a subprocess + try: + cmd = [self.updater, "--swap", self.manifest] + self.process = subprocess.Popen(cmd, stdout=subprocess.PIPE, + text=True, bufsize=1, universal_newlines=True) + except Exception: + self._update_failed = True + return + + if self.process.stdout is not None: + for line in self.process.stdout: + parts = line.strip().split(":") + if len(parts) == 2: + self.progress_text = parts[0].lower() + try: + self.progress_value = int(float(parts[1])) + except ValueError: + pass + + exit_code = self.process.wait() + if exit_code == 0: + HARDWARE.reboot() + else: + self._update_failed = True + + def close(self): + self._network_monitor.stop() + + +def main(): + config_realtime_process(0, 51) + # attempt to affine. AGNOS will start setup with all cores, should only fail when manually launching with screen off + if TICI: + try: + set_core_affinity([5]) + except OSError: + cloudlog.exception("Failed to set core affinity for updater process") + + if len(sys.argv) < 3: + print("Usage: updater.py ") + sys.exit(1) + + updater_path = sys.argv[1] + manifest_path = sys.argv[2] + + try: + gui_app.init_window("System Update") + updater = Updater(updater_path, manifest_path) + gui_app.push_widget(updater) + for _ in gui_app.render(): + pass + updater.close() + except Exception as e: + print(f"Updater error: {e}") + finally: + gui_app.close() + + +if __name__ == "__main__": + main() diff --git a/openpilot/system/ui/reset.py b/openpilot/system/ui/reset.py new file mode 100755 index 0000000000..c32504a5b8 --- /dev/null +++ b/openpilot/system/ui/reset.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python3 +from openpilot.system.ui.lib.application import gui_app +import openpilot.system.ui.tici_reset as tici_reset +import openpilot.system.ui.mici_reset as mici_reset + + +def main(): + if gui_app.big_ui(): + tici_reset.main() + else: + mici_reset.main() + + +if __name__ == "__main__": + main() diff --git a/openpilot/system/ui/setup.py b/openpilot/system/ui/setup.py new file mode 100755 index 0000000000..23ffc26aa2 --- /dev/null +++ b/openpilot/system/ui/setup.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python3 +from openpilot.system.ui.lib.application import gui_app +import openpilot.system.ui.tici_setup as tici_setup +import openpilot.system.ui.mici_setup as mici_setup + + +def main(): + if gui_app.big_ui(): + tici_setup.main() + else: + mici_setup.main() + + +if __name__ == "__main__": + main() diff --git a/openpilot/system/ui/spinner.py b/openpilot/system/ui/spinner.py new file mode 100755 index 0000000000..33f4543c3e --- /dev/null +++ b/openpilot/system/ui/spinner.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python3 +import pyray as rl +import select +import sys + +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.text import wrap_text +from openpilot.system.ui.widgets import Widget + +# Constants +if gui_app.big_ui(): + PROGRESS_BAR_WIDTH = 1000 + PROGRESS_BAR_HEIGHT = 20 + TEXTURE_SIZE = 360 + WRAPPED_SPACING = 50 + CENTERED_SPACING = 150 +else: + PROGRESS_BAR_WIDTH = 268 + PROGRESS_BAR_HEIGHT = 10 + TEXTURE_SIZE = 140 + WRAPPED_SPACING = 10 + CENTERED_SPACING = 20 +DEGREES_PER_SECOND = 360.0 # one full rotation per second +MARGIN_H = 100 +FONT_SIZE = 96 +LINE_HEIGHT = 104 +DARKGRAY = (55, 55, 55, 255) + + +def clamp(value, min_value, max_value): + return max(min(value, max_value), min_value) + + +class Spinner(Widget): + def __init__(self): + super().__init__() + self._comma_texture = gui_app.texture("../../sunnypilot/selfdrive/assets/images/spinner_sunnypilot.png", TEXTURE_SIZE, TEXTURE_SIZE) + self._spinner_texture = gui_app.texture("images/spinner_track.png", TEXTURE_SIZE, TEXTURE_SIZE, alpha_premultiply=True) + self._rotation = 0.0 + self._progress: int | None = None + self._wrapped_lines: list[str] = [] + + def set_text(self, text: str) -> None: + if text.isdigit(): + self._progress = clamp(int(text), 0, 100) + self._wrapped_lines = [] + else: + self._progress = None + self._wrapped_lines = wrap_text(text, FONT_SIZE, gui_app.width - MARGIN_H) + + def _render(self, rect: rl.Rectangle): + if self._wrapped_lines: + # Calculate total height required for spinner and text + spacing = WRAPPED_SPACING + total_height = TEXTURE_SIZE + spacing + len(self._wrapped_lines) * LINE_HEIGHT + center_y = (rect.height - total_height) / 2.0 + TEXTURE_SIZE / 2.0 + else: + # Center spinner vertically + spacing = CENTERED_SPACING + center_y = rect.height / 2.0 + y_pos = center_y + TEXTURE_SIZE / 2.0 + spacing + + center = rl.Vector2(rect.width / 2.0, center_y) + spinner_origin = rl.Vector2(TEXTURE_SIZE / 2.0, TEXTURE_SIZE / 2.0) + comma_position = rl.Vector2(center.x - TEXTURE_SIZE / 2.0, center.y - TEXTURE_SIZE / 2.0) + + delta_time = rl.get_frame_time() + self._rotation = (self._rotation + DEGREES_PER_SECOND * delta_time) % 360.0 + + # Draw rotating spinner and static comma logo + rl.draw_texture_pro(self._spinner_texture, rl.Rectangle(0, 0, TEXTURE_SIZE, TEXTURE_SIZE), + rl.Rectangle(center.x, center.y, TEXTURE_SIZE, TEXTURE_SIZE), + spinner_origin, self._rotation, rl.WHITE) + rl.draw_texture_v(self._comma_texture, comma_position, rl.WHITE) + + # Display the progress bar or text based on user input + if self._progress is not None: + bar = rl.Rectangle(center.x - PROGRESS_BAR_WIDTH / 2.0, y_pos, PROGRESS_BAR_WIDTH, PROGRESS_BAR_HEIGHT) + rl.draw_rectangle_rounded(bar, 1, 10, DARKGRAY) + + bar.width *= self._progress / 100.0 + rl.draw_rectangle_rounded(bar, 1, 10, rl.WHITE) + elif self._wrapped_lines: + for i, line in enumerate(self._wrapped_lines): + text_size = measure_text_cached(gui_app.font(), line, FONT_SIZE) + rl.draw_text_ex(gui_app.font(), line, rl.Vector2(center.x - text_size.x / 2, y_pos + i * LINE_HEIGHT), + FONT_SIZE, 0.0, rl.WHITE) + + +def _read_stdin(): + """Non-blocking read of available lines from stdin.""" + lines = [] + while True: + rlist, _, _ = select.select([sys.stdin], [], [], 0.0) + if not rlist: + break + line = sys.stdin.readline().strip() + if line == "": + break + lines.append(line) + return lines + + +def main(): + gui_app.init_window("Spinner") + spinner = Spinner() + for _ in gui_app.render(): + text_list = _read_stdin() + if text_list: + spinner.set_text(text_list[-1]) + + spinner.render(rl.Rectangle(0, 0, gui_app.width, gui_app.height)) + + +if __name__ == "__main__": + main() diff --git a/openpilot/system/ui/sunnypilot/lib/application.py b/openpilot/system/ui/sunnypilot/lib/application.py new file mode 100644 index 0000000000..481886e37a --- /dev/null +++ b/openpilot/system/ui/sunnypilot/lib/application.py @@ -0,0 +1,40 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import os + +import pyray as rl + +SHOW_MOUSE_COORDS = os.getenv("SHOW_MOUSE_COORDS") == "1" +SUNNYPILOT_UI = os.getenv("SUNNYPILOT_UI", "1") == "1" + + +class GuiApplicationExt: + def __init__(self): + self._show_mouse_coords = SHOW_MOUSE_COORDS + + @staticmethod + def sunnypilot_ui() -> bool: + return SUNNYPILOT_UI + + def _draw_mouse_coordinates(self, font): + coords_text = f"X:{int(rl.get_mouse_x())}, Y:{int(rl.get_mouse_y())}" + + green_color = rl.Color(0, 159, 47, 255) # Match the green color of FPS counter + + # Calculate text width to position it at the right edge; estimate width based on text length + # Each character is approximately 10-12 pixels wide at font size 20 + estimated_text_width = len(coords_text) * 11 + + # Position text at the top right corner, 10px from the top + screen_width = self._scaled_width if self._scale != 1.0 else self._width + text_pos = rl.Vector2(screen_width - estimated_text_width - 10, 6) + + # Draw the text + rl.draw_text_ex(font, coords_text, text_pos, 20, 0, green_color) + + def set_show_mouse_coords(self, show: bool): + self._show_mouse_coords = show diff --git a/openpilot/system/ui/sunnypilot/lib/styles.py b/openpilot/system/ui/sunnypilot/lib/styles.py new file mode 100644 index 0000000000..7a29b5bb13 --- /dev/null +++ b/openpilot/system/ui/sunnypilot/lib/styles.py @@ -0,0 +1,95 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from dataclasses import dataclass + +import pyray as rl + + +@dataclass +class Base: + # Widget/Control Base Dimensions + ITEM_BASE_HEIGHT = 170 + ITEM_PADDING = 20 + ITEM_TEXT_FONT_SIZE = 50 + ITEM_DESC_FONT_SIZE = 40 + ITEM_DESC_V_OFFSET = 150 + ITEM_TEXT_VALUE_COLOR = rl.Color(170, 170, 170, 255) + CLOSE_BTN_SIZE = 160 + + TEXT_PADDING = 20 + + # Toggle Control + TOGGLE_HEIGHT = 120 + TOGGLE_WIDTH = int(TOGGLE_HEIGHT * 1.75) + TOGGLE_BG_HEIGHT = TOGGLE_HEIGHT - 20 + + # Button Control + BUTTON_ACTION_WIDTH = 300 + BUTTON_HEIGHT = 120 + + # Simple Button Control + SIMPLE_BUTTON_WIDTH = 800 + SIMPLE_BUTTON_HEIGHT = 150 + + +@dataclass +class DefaultStyleSP(Base): + # Base Colors + BASE_BG_COLOR = rl.Color(57, 57, 57, 255) # Grey + ON_BG_COLOR = rl.Color(28, 101, 186, 255) # Blue + OFF_BG_COLOR = BASE_BG_COLOR + ON_HOVER_BG_COLOR = rl.Color(17, 78, 150, 255) # Dark Blue + OFF_HOVER_BG_COLOR = rl.Color(21, 21, 21, 255) # Dark gray + DISABLED_ON_BG_COLOR = rl.Color(37, 70, 107, 255) # Dull Blue + DISABLED_OFF_BG_COLOR = rl.Color(39, 39, 39, 255) # Grey + ITEM_TEXT_COLOR = rl.WHITE + ITEM_DISABLED_TEXT_COLOR = rl.Color(88, 88, 88, 255) + ITEM_DESC_TEXT_COLOR = rl.Color(128, 128, 128, 255) + + # Toggle Control + TOGGLE_ON_COLOR = ON_BG_COLOR + TOGGLE_OFF_COLOR = OFF_BG_COLOR + TOGGLE_KNOB_COLOR = rl.WHITE + TOGGLE_DISABLED_ON_COLOR = DISABLED_ON_BG_COLOR + TOGGLE_DISABLED_OFF_COLOR = DISABLED_OFF_BG_COLOR + TOGGLE_DISABLED_KNOB_COLOR = rl.Color(88, 88, 88, 255) # Lighter Grey + + # Multi Button Control + MBC_TRANSPARENT = rl.Color(255, 255, 255, 0) + MBC_BG_CHECKED_ENABLED = rl.Color(0x69, 0x68, 0x68, 0xFF) + MBC_DISABLED = rl.Color(0xFF, 0xFF, 0xFF, 0x33) + + # Option Control + OPTION_CONTROL_CONTAINER_BG = OFF_BG_COLOR + OPTION_CONTROL_BTN_ENABLED = rl.Color(88, 88, 88, 255) + OPTION_CONTROL_BTN_PRESSED = rl.Color(0x69, 0x68, 0x68, 0xFF) + OPTION_CONTROL_BTN_DISABLED = DISABLED_OFF_BG_COLOR + OPTION_CONTROL_TEXT_ENABLED = rl.WHITE + OPTION_CONTROL_TEXT_PRESSED = rl.WHITE + OPTION_CONTROL_TEXT_DISABLED = ITEM_DISABLED_TEXT_COLOR + + # Tree Button Colors + BUTTON_PRIMARY_COLOR = rl.Color(70, 91, 234, 255) # Royal Blue + BUTTON_NEUTRAL_GRAY = rl.Color(51, 51, 51, 255) + BUTTON_DISABLED_BG_COLOR = rl.Color(30, 30, 30, 255) # Very Dark Grey + TREE_DIALOG_TRANSPARENT = rl.Color(0, 0, 0, 0) + TREE_DIALOG_SEARCH_BUTTON_PRESSED = rl.Color(0x69, 0x68, 0x68, 0xFF) + TREE_DIALOG_SEARCH_BUTTON_BORDER = rl.Color(150, 150, 150, 200) + + # Vehicle Description Colors + GREEN = rl.Color(0, 241, 0, 255) + BLUE = rl.Color(0, 134, 233, 255) + YELLOW = rl.Color(255, 213, 0, 255) + + # Button Colors + BUTTON_ENABLED_OFF = rl.Color(0x39, 0x39, 0x39, 0xFF) + BUTTON_OFF_PRESSED = rl.Color(0x4A, 0x4A, 0x4A, 0xFF) + BUTTON_DISABLED = rl.Color(0x12, 0x12, 0x12, 0xFF) + BUTTON_TEXT_DISABLED = rl.Color(0x5C, 0x5C, 0x5C, 0xFF) + + +style = DefaultStyleSP diff --git a/openpilot/system/ui/sunnypilot/lib/utils.py b/openpilot/system/ui/sunnypilot/lib/utils.py new file mode 100644 index 0000000000..ecaba86f4b --- /dev/null +++ b/openpilot/system/ui/sunnypilot/lib/utils.py @@ -0,0 +1,36 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from openpilot.system.ui.sunnypilot.widgets.list_view import ButtonActionSP + + +class NoElideButtonAction(ButtonActionSP): + def get_width_hint(self): + return super().get_width_hint() + 1 + + +class AlertFadeAnimator: + def __init__(self, target_fps: int, duration_on: float = 0.75, rc: float = 0.05): + from openpilot.common.filter_simple import FirstOrderFilter + self._filter = FirstOrderFilter(1.0, rc, 1 / target_fps) + self._frame = 0 + self._target_fps = target_fps + self._duration_on = duration_on + + def update(self, active: bool): + if active: + self._frame += 1 + if (self._frame % self._target_fps) < (self._target_fps * self._duration_on): + self._filter.x = 1.0 + else: + self._filter.update(0.0) + else: + self._frame = 0 + self._filter.update(1.0) + + @property + def alpha(self) -> float: + return self._filter.x diff --git a/openpilot/system/ui/sunnypilot/widgets/__init__.py b/openpilot/system/ui/sunnypilot/widgets/__init__.py new file mode 100644 index 0000000000..96865e6042 --- /dev/null +++ b/openpilot/system/ui/sunnypilot/widgets/__init__.py @@ -0,0 +1,18 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" + + +def get_highlighted_description(params, param_name: str, descriptions: list[str]) -> str: + index = int(params.get(param_name, return_default=True)) + lines = [] + for i, desc in enumerate(descriptions): + if i == index: + lines.append(f"{desc}") + else: + lines.append(f"{desc}") + + return "
".join(lines) diff --git a/tools/sim/tests/__init__.py b/openpilot/system/ui/sunnypilot/widgets/helpers/__init__.py similarity index 100% rename from tools/sim/tests/__init__.py rename to openpilot/system/ui/sunnypilot/widgets/helpers/__init__.py diff --git a/openpilot/system/ui/sunnypilot/widgets/helpers/fuzzy_search.py b/openpilot/system/ui/sunnypilot/widgets/helpers/fuzzy_search.py new file mode 100644 index 0000000000..8d0f6bd59b --- /dev/null +++ b/openpilot/system/ui/sunnypilot/widgets/helpers/fuzzy_search.py @@ -0,0 +1,40 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import re +import unicodedata + + +def normalize(text: str) -> str: + return unicodedata.normalize('NFKD', text).encode('ascii', 'ignore').decode('utf-8').lower() + + +def search_from_list(query: str, items: list[str]) -> list[str]: + if not query: + return items + + normalized_query = normalize(query) + search_terms = [re.sub(r'[^a-z0-9]', '', term) for term in normalized_query.split() if term.strip()] + + results = [] + for item in items: + normalized_item = normalize(item) + item_with_spaces = re.sub(r'[^a-z0-9\s]', ' ', normalized_item) + item_stripped = re.sub(r'[^a-z0-9]', '', normalized_item) + + all_terms_match = True + for term in search_terms: + if not term: + continue + + if term not in item_with_spaces and term not in item_stripped: + all_terms_match = False + break + + if all_terms_match: + results.append(item) + + return results diff --git a/openpilot/system/ui/sunnypilot/widgets/helpers/star_icon.py b/openpilot/system/ui/sunnypilot/widgets/helpers/star_icon.py new file mode 100644 index 0000000000..14666d49b6 --- /dev/null +++ b/openpilot/system/ui/sunnypilot/widgets/helpers/star_icon.py @@ -0,0 +1,26 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import math + +import pyray as rl + + +def draw_star(center_x, center_y, radius, is_filled, color): + center = rl.Vector2(center_x, center_y) + points = [] + + for i in range(10): + angle = -(i * 36 + 18) * math.pi / 180 + r = radius if i % 2 == 0 else radius / 2 + x = center_x + r * math.cos(angle) + y = center_y + r * math.sin(angle) + points.append(rl.Vector2(x, y)) + + for i in range(10): + if is_filled: + rl.draw_triangle(center, points[i], points[(i + 1) % 10], color) + rl.draw_line_ex(points[i], points[(i + 1) % 10], 2, color) diff --git a/openpilot/system/ui/sunnypilot/widgets/html_render.py b/openpilot/system/ui/sunnypilot/widgets/html_render.py new file mode 100644 index 0000000000..a0018f5be7 --- /dev/null +++ b/openpilot/system/ui/sunnypilot/widgets/html_render.py @@ -0,0 +1,27 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.widgets import DialogResult +from openpilot.system.ui.widgets.html_render import HtmlModal + + +class HtmlModalSP(HtmlModal): + def __init__(self, file_path=None, text=None, callback=None): + super().__init__(file_path=file_path, text=text) + self._callback = callback + self._dialog_result = DialogResult.NO_ACTION + self._ok_button._click_callback = self._on_ok_clicked + + def _on_ok_clicked(self): + self._dialog_result = DialogResult.CONFIRM + gui_app.pop_widget() + + if self._callback: + self._callback(self._dialog_result) + + def reset(self): + self._dialog_result = DialogResult.NO_ACTION diff --git a/openpilot/system/ui/sunnypilot/widgets/input_dialog.py b/openpilot/system/ui/sunnypilot/widgets/input_dialog.py new file mode 100644 index 0000000000..83b7edacf2 --- /dev/null +++ b/openpilot/system/ui/sunnypilot/widgets/input_dialog.py @@ -0,0 +1,43 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from collections.abc import Callable + +from openpilot.common.params import Params +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.widgets import DialogResult +from openpilot.system.ui.widgets.keyboard import Keyboard + + +class InputDialogSP: + def __init__(self, title: str, sub_title: str | None = None, current_text: str = "", param: str | None = None, + callback: Callable[[DialogResult, str], None] | None = None, + min_text_size: int = 0, password_mode: bool = False): + self.callback = callback + self.current_text = current_text + self.keyboard = Keyboard(max_text_size=255, min_text_size=min_text_size, password_mode=password_mode) + self.param = param + self._params = Params() + self.sub_title = sub_title + self.title = title + + def show(self): + self.keyboard.reset(min_text_size=self.keyboard._min_text_size) + if self.sub_title: + self.keyboard.set_title(self.title, self.sub_title) + else: + self.keyboard.set_title(self.title) + self.keyboard.set_text(self.current_text) + + def internal_callback(result: DialogResult): + text = self.keyboard.text if result == DialogResult.CONFIRM else "" + if result == DialogResult.CONFIRM and self.param: + self._params.put(self.param, text) + if self.callback: + self.callback(result, text) + + self.keyboard.set_callback(internal_callback) + gui_app.push_widget(self.keyboard) diff --git a/openpilot/system/ui/sunnypilot/widgets/list_view.py b/openpilot/system/ui/sunnypilot/widgets/list_view.py new file mode 100644 index 0000000000..ff4b8c13dd --- /dev/null +++ b/openpilot/system/ui/sunnypilot/widgets/list_view.py @@ -0,0 +1,411 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from collections.abc import Callable, Sequence + +import pyray as rl +from openpilot.common.params import Params +from openpilot.system.ui.lib.application import gui_app, MousePos, FontWeight +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.sunnypilot.widgets.toggle import ToggleSP +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.button import Button, ButtonStyle +from openpilot.system.ui.widgets.label import gui_label +from openpilot.system.ui.widgets.list_view import ListItem, ToggleAction, ItemAction, MultipleButtonAction, ButtonAction, \ + _resolve_value, BUTTON_WIDTH, BUTTON_HEIGHT, TEXT_PADDING, DualButtonAction +from openpilot.system.ui.widgets.scroller_tici import LineSeparator, LINE_COLOR, LINE_PADDING +from openpilot.system.ui.sunnypilot.lib.styles import style +from openpilot.system.ui.sunnypilot.widgets.option_control import OptionControlSP, LABEL_WIDTH + + +class Spacer(Widget): + def __init__(self, height: int = 1): + super().__init__() + self._rect = rl.Rectangle(0, 0, 0, height) + + def set_parent_rect(self, parent_rect: rl.Rectangle) -> None: + super().set_parent_rect(parent_rect) + self._rect.width = parent_rect.width + + def _render(self, _): + rl.draw_rectangle(int(self._rect.x), int(self._rect.y), int(self._rect.x + self._rect.width), int(self._rect.y), rl.Color(0,0,0,0)) + + +class ToggleActionSP(ToggleAction): + def __init__(self, initial_state: bool = False, width: int = style.TOGGLE_WIDTH, enabled: bool | Callable[[], bool] = True, + callback: Callable[[bool], None] | None = None, param: str | None = None): + ToggleAction.__init__(self, initial_state, width, enabled, callback) + self.toggle = ToggleSP(initial_state=initial_state, callback=callback, param=param) + + +class ButtonSP(Button): + def _update_state(self): + super()._update_state() + if self.enabled: + if self.is_pressed: + self._background_color = style.BUTTON_OFF_PRESSED + else: + self._background_color = style.BUTTON_ENABLED_OFF + else: + self._background_color = style.BUTTON_DISABLED + self._label.set_text_color(style.BUTTON_TEXT_DISABLED) + + +class SimpleButtonActionSP(ItemAction): + def __init__(self, button_text: str | Callable[[], str], callback: Callable | None = None, + enabled: bool | Callable[[], bool] = True, button_width: int = style.SIMPLE_BUTTON_WIDTH): + super().__init__(width=button_width, enabled=enabled) + self.button_action = ButtonSP(button_text, click_callback=callback, button_style=ButtonStyle.NORMAL, + border_radius=20) + + def set_touch_valid_callback(self, touch_callback: Callable[[], bool]) -> None: + super().set_touch_valid_callback(touch_callback) + self.button_action.set_touch_valid_callback(touch_callback) + + def _render(self, rect: rl.Rectangle) -> bool | int | None: + self.button_action.set_enabled(self.enabled) + return self.button_action.render(rect) + + +class ButtonActionSP(ButtonAction): + def __init__(self, text: str | Callable[[], str], width: int = style.BUTTON_ACTION_WIDTH, enabled: bool | Callable[[], bool] = True): + super().__init__(text=text, width=width, enabled=enabled) + self._value_color: rl.Color = style.ITEM_TEXT_VALUE_COLOR + + def set_value(self, value: str | Callable[[], str], color: rl.Color = style.ITEM_TEXT_VALUE_COLOR): + self._value_source = value + self._value_color = color + + def _render(self, rect: rl.Rectangle) -> bool: + """Duplicate of ButtonAction._render, with additional value rendering""" + self._button.set_text(self.text) + self._button.set_enabled(_resolve_value(self.enabled)) + button_rect = rl.Rectangle(rect.x + rect.width - BUTTON_WIDTH, rect.y + (rect.height - BUTTON_HEIGHT) / 2, BUTTON_WIDTH, BUTTON_HEIGHT) + self._button.render(button_rect) + + value_text = self.value + if value_text: + value_rect = rl.Rectangle(rect.x, rect.y, rect.width - BUTTON_WIDTH - TEXT_PADDING, rect.height) + gui_label(value_rect, value_text, font_size=style.ITEM_TEXT_FONT_SIZE, color=self._value_color, + font_weight=FontWeight.NORMAL, alignment=rl.GuiTextAlignment.TEXT_ALIGN_LEFT, + alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE) + + pressed = self._pressed + self._pressed = False + return pressed + + +class DualButtonActionSP(DualButtonAction): + def __init__(self, left_text: str | Callable[[], str], right_text: str | Callable[[], str], left_callback: Callable | None = None, + right_callback: Callable | None = None, enabled: bool | Callable[[], bool] = True, border_radius: int = 15): + DualButtonAction.__init__(self, left_text, right_text, left_callback, right_callback, enabled) + self.left_button._border_radius = self.right_button._border_radius = border_radius + + def _render(self, rect: rl.Rectangle): + button_spacing = 20 + button_height = 150 + button_width = (rect.width - button_spacing) / 2 + button_y = rect.y + (rect.height - button_height) / 2 + + left_rect = rl.Rectangle(rect.x, button_y, button_width, button_height) + right_rect = rl.Rectangle(rect.x + button_width + button_spacing, button_y, button_width, button_height) + + # expand one to full width if other is not visible + if not self.left_button.is_visible: + right_rect.x = rect.x + right_rect.width = rect.width + elif not self.right_button.is_visible: + left_rect.width = rect.width + + # Render buttons + self.left_button.render(left_rect) + self.right_button.render(right_rect) + + +class MultipleButtonActionSP(MultipleButtonAction): + def __init__(self, buttons: Sequence[str | Callable[[], str]], button_width: int, selected_index: int = 0, callback: Callable | None = None, + param: str | None = None): + MultipleButtonAction.__init__(self, buttons, button_width, selected_index, callback) + self.param_key = param + self.params = Params() + if self.param_key: + self.selected_button = int(self.params.get(self.param_key, return_default=True)) + self._anim_x: float | None = None + self.enabled_buttons: set[int] | None = None + + def set_enabled_buttons(self, indices: set[int] | None): + self.enabled_buttons = indices + + def _render(self, rect: rl.Rectangle): + + button_y = rect.y + (rect.height - style.BUTTON_HEIGHT) / 2 + + total_width = len(self.buttons) * self.button_width + track_rect = rl.Rectangle(rect.x, button_y, total_width, style.BUTTON_HEIGHT) + + bg_color = style.MBC_TRANSPARENT + text_color = style.ITEM_TEXT_COLOR if self.enabled else style.MBC_DISABLED + highlight_color = style.MBC_BG_CHECKED_ENABLED if self.enabled else style.MBC_DISABLED + + # background + rl.draw_rectangle_rounded(track_rect, 0.2, 20, bg_color) + + # border + border_color = style.MBC_BG_CHECKED_ENABLED if self.enabled else style.MBC_DISABLED + rl.draw_rectangle_rounded_lines_ex(track_rect, 0.2, 20, 2, border_color) + + # highlight with animation + target_x = rect.x + self.selected_button * self.button_width + if not self._anim_x: + self._anim_x = target_x + self._anim_x += (target_x - self._anim_x) * 0.2 + + highlight_rect = rl.Rectangle(self._anim_x, button_y, self.button_width, style.BUTTON_HEIGHT) + rl.draw_rectangle_rounded(highlight_rect, 0.2, 20, highlight_color) + + # text + for i, _text in enumerate(self.buttons): + button_x = rect.x + i * self.button_width + + text = _resolve_value(_text, "") + text_size = measure_text_cached(self._font, text, 40) + text_x = button_x + (self.button_width - text_size.x) / 2 + text_y = button_y + (style.BUTTON_HEIGHT - text_size.y) / 2 + + # Check individual button enabled state + is_button_enabled = self.enabled and (self.enabled_buttons is None or i in self.enabled_buttons) + current_text_color = text_color if is_button_enabled else style.MBC_DISABLED + + rl.draw_text_ex(self._font, text, rl.Vector2(text_x, text_y), 40, 0, current_text_color) + + def _handle_mouse_release(self, mouse_pos: MousePos): + # Override parent method to check individual button enabled state + if not self.enabled: + return + + button_y = self._rect.y + (self._rect.height - style.BUTTON_HEIGHT) / 2 + for i, _ in enumerate(self.buttons): + button_x = self._rect.x + i * self.button_width + button_rect = rl.Rectangle(button_x, button_y, self.button_width, style.BUTTON_HEIGHT) + + if rl.check_collision_point_rec(mouse_pos, button_rect): + # Check if this specific button is enabled + if self.enabled_buttons is not None and i not in self.enabled_buttons: + return + + self.selected_button = i + if self.callback: + self.callback(i) + + if self.param_key: + self.params.put(self.param_key, self.selected_button) + + +class ListItemSP(ListItem): + def __init__(self, title: str | Callable[[], str] = "", icon: str | None = None, description: str | Callable[[], str] | None = None, + description_visible: bool = False, callback: Callable | None = None, + action_item: ItemAction | None = None, inline: bool = True, title_color: rl.Color = style.ITEM_TEXT_COLOR): + ListItem.__init__(self, title, icon, description, description_visible, callback, action_item) + self.title_color = title_color + self.inline = inline + if not self.inline: + self._rect.height += style.ITEM_BASE_HEIGHT/1.75 + self._right_value_source: str | Callable[[], str] | None = None + self._right_value_font = gui_app.font(FontWeight.NORMAL) + self._right_value_color: rl.Color = style.ITEM_TEXT_VALUE_COLOR + + def set_title(self, title: str | Callable[[], str] = ""): + self._title = title + + def set_right_value(self, value: str | Callable[[], str], color: rl.Color = style.ITEM_TEXT_VALUE_COLOR): + self._right_value_source = value + self._right_value_color = color + + @property + def right_value(self) -> str: + if self._right_value_source is None: + return "" + return str(_resolve_value(self._right_value_source, "")) + + def _update_state(self): + prev_desc = self._prev_description + super()._update_state() + if self.description_visible and self._prev_description != prev_desc: + content_width = int(self._rect.width - style.ITEM_PADDING * 2) + self._rect.height = self.get_item_height(self._font, content_width) + + def set_parent_rect(self, parent_rect: rl.Rectangle) -> None: + super().set_parent_rect(parent_rect) + if self.description_visible: + content_width = int(self._rect.width - style.ITEM_PADDING * 2) + self._rect.height = self.get_item_height(self._font, content_width) + + def get_item_height(self, font: rl.Font, max_width: int) -> float: + height = super().get_item_height(font, max_width) + + if self.description_visible: + height += style.ITEM_PADDING * 1.5 + + if not self.inline: + height += style.ITEM_BASE_HEIGHT / 1.75 + + return height + + def show_description(self, show: bool): + self._set_description_visible(show) + + def get_right_item_rect(self, item_rect: rl.Rectangle) -> rl.Rectangle: + if not self.action_item: + return rl.Rectangle(0, 0, 0, 0) + + if not self.inline: + text_size = measure_text_cached(self._font, self.title, style.ITEM_TEXT_FONT_SIZE) + action_y = item_rect.y + text_size.y + style.ITEM_PADDING * 3 + return rl.Rectangle(item_rect.x + style.ITEM_PADDING, action_y, item_rect.width - (style.ITEM_PADDING * 2), style.BUTTON_HEIGHT) + + right_width = self.action_item.get_width_hint() + if right_width == 0: + return rl.Rectangle(item_rect.x + style.ITEM_PADDING, item_rect.y, item_rect.width - (style.ITEM_PADDING * 2), style.ITEM_BASE_HEIGHT) + + content_width = item_rect.width - (style.ITEM_PADDING * 2) + title_width = measure_text_cached(self._font, self.title, style.ITEM_TEXT_FONT_SIZE).x + right_width = min(content_width - title_width, right_width) + if isinstance(self.action_item, ToggleAction) or isinstance(self.action_item, SimpleButtonActionSP): + action_x = item_rect.x + else: + action_x = item_rect.x + item_rect.width - right_width + action_y = item_rect.y + return rl.Rectangle(action_x, action_y, right_width, style.ITEM_BASE_HEIGHT) + + def _render(self, _): + if not self.is_visible: + return + + # Don't draw items that are not in parent's viewport + if (self._rect.y + self.rect.height) <= self._parent_rect.y or self._rect.y >= (self._parent_rect.y + self._parent_rect.height): + return + + content_x = self._rect.x + style.ITEM_PADDING + text_x = content_x + left_action_item = isinstance(self.action_item, ToggleAction) or isinstance(self.action_item, SimpleButtonActionSP) + + if left_action_item: + item_height = style.SIMPLE_BUTTON_HEIGHT if isinstance(self.action_item, SimpleButtonActionSP) else style.TOGGLE_HEIGHT + left_rect = rl.Rectangle( + content_x, + self._rect.y + (style.ITEM_BASE_HEIGHT - item_height) // 2, + self.action_item.rect.width, + item_height + ) + text_x = left_rect.x + left_rect.width + style.ITEM_PADDING * 1.5 + + # Draw title + if self.title: + self._text_size = measure_text_cached(self._font, self.title, style.ITEM_TEXT_FONT_SIZE) + item_y = self._rect.y + (style.ITEM_BASE_HEIGHT - self._text_size.y) // 2 + rl.draw_text_ex(self._font, self.title, rl.Vector2(text_x, item_y), style.ITEM_TEXT_FONT_SIZE, 0, self.title_color) + + value_text = self.right_value + if value_text: + # area from after the title to the right edge of the row + value_rect = rl.Rectangle( + text_x, # start at the beginning of the text area + self._rect.y, + self._rect.width - (text_x - self._rect.x) - style.ITEM_PADDING, + style.ITEM_BASE_HEIGHT, + ) + if value_rect.width > 0: + gui_label(value_rect, value_text, font_size=style.ITEM_TEXT_FONT_SIZE, color=self._right_value_color, font_weight=FontWeight.NORMAL, + alignment=rl.GuiTextAlignment.TEXT_ALIGN_RIGHT, alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE) + + # Render toggle and handle callback + if self.action_item.render(left_rect) and self.action_item.enabled: + if self.callback: + self.callback() + + else: + if self.title: + # Draw main text + self._text_size = measure_text_cached(self._font, self.title, style.ITEM_TEXT_FONT_SIZE) + item_y = self._rect.y + (style.ITEM_BASE_HEIGHT - self._text_size.y) // 2 if self.inline else self._rect.y + style.ITEM_PADDING * 1.5 + rl.draw_text_ex(self._font, self.title, rl.Vector2(text_x, item_y), style.ITEM_TEXT_FONT_SIZE, 0, self.title_color) + + # Draw right item if present + if self.action_item: + right_rect = self.get_right_item_rect(self._rect) + if self.action_item.render(right_rect) and self.action_item.enabled: + # Right item was clicked/activated + if self.callback: + self.callback() + + # Draw description if visible + if self.description_visible: + content_width = int(self._rect.width - style.ITEM_PADDING * 2) + description_height = self._html_renderer.get_total_height(content_width) + + desc_y = self._rect.y + style.ITEM_DESC_V_OFFSET + if not self.inline and self.action_item: + desc_y = self.action_item.rect.y + style.ITEM_DESC_V_OFFSET - style.ITEM_PADDING * 0.5 + + description_rect = rl.Rectangle(self._rect.x + style.ITEM_PADDING, desc_y, content_width, description_height) + self._html_renderer.render(description_rect) + + +def simple_button_item_sp(button_text: str | Callable[[], str], callback: Callable | None = None, + enabled: bool | Callable[[], bool] = True, button_width: int = style.SIMPLE_BUTTON_WIDTH) -> ListItemSP: + action = SimpleButtonActionSP(button_text=button_text, enabled=enabled, callback=callback, button_width=button_width) + return ListItemSP(title="", callback=callback, description="", action_item=action) + + +def toggle_item_sp(title: str | Callable[[], str], description: str | Callable[[], str] | None = None, initial_state: bool = False, + callback: Callable | None = None, icon: str = "", enabled: bool | Callable[[], bool] = True, param: str | None = None) -> ListItemSP: + action = ToggleActionSP(initial_state=initial_state, enabled=enabled, callback=callback, param=param) + return ListItemSP(title=title, description=description, action_item=action, icon=icon) + + +def multiple_button_item_sp(title: str | Callable[[], str], description: str | Callable[[], str], buttons: Sequence[str | Callable[[], str]], + selected_index: int = 0, button_width: int = style.BUTTON_ACTION_WIDTH, callback: Callable | None = None, + icon: str = "", param: str | None = None, inline: bool = False) -> ListItemSP: + action = MultipleButtonActionSP(buttons, button_width, selected_index, callback=callback, param=param) + return ListItemSP(title=title, description=description, icon=icon, action_item=action, inline=inline) + + +def option_item_sp(title: str | Callable[[], str], param: str, + min_value: int, max_value: int, description: str | Callable[[], str] | None = None, + value_change_step: int = 1, on_value_changed: Callable[[int], None] | None = None, + enabled: bool | Callable[[], bool] = True, + icon: str = "", label_width: int = LABEL_WIDTH, value_map: dict[int, int] | None = None, + use_float_scaling: bool = False, label_callback: Callable[[int], str] | None = None, inline: bool = False) -> ListItemSP: + action = OptionControlSP( + param, min_value, max_value, value_change_step, + enabled, on_value_changed, value_map, label_width, use_float_scaling, label_callback + ) + return ListItemSP(title=title, description=description, action_item=action, icon=icon, inline=inline) + + +def button_item_sp(title: str | Callable[[], str], button_text: str | Callable[[], str], description: str | Callable[[], str] | None = None, + callback: Callable | None = None, enabled: bool | Callable[[], bool] = True) -> ListItemSP: + action = ButtonActionSP(text=button_text, enabled=enabled) + return ListItemSP(title=title, description=description, action_item=action, callback=callback) + + +def dual_button_item_sp(left_text: str | Callable[[], str], right_text: str | Callable[[], str], left_callback: Callable | None = None, + right_callback: Callable | None = None, description: str | Callable[[], str] | None = None, + enabled: bool | Callable[[], bool] = True, border_radius: int = 15) -> ListItemSP: + action = DualButtonActionSP(left_text, right_text, left_callback, right_callback, enabled, border_radius) + return ListItemSP(title="", description=description, action_item=action) + + +class LineSeparatorSP(LineSeparator): + def __init__(self, height: int = 1): + super().__init__() + self._rect = rl.Rectangle(0, 0, 0, height) + + def _render(self, _): + line_y = int(self._rect.y + self._rect.height // 2) + rl.draw_line(int(self._rect.x) + LINE_PADDING, line_y, + int(self._rect.x + self._rect.width) - LINE_PADDING, line_y, + LINE_COLOR) diff --git a/openpilot/system/ui/sunnypilot/widgets/option_control.py b/openpilot/system/ui/sunnypilot/widgets/option_control.py new file mode 100644 index 0000000000..82126417d5 --- /dev/null +++ b/openpilot/system/ui/sunnypilot/widgets/option_control.py @@ -0,0 +1,168 @@ +import pyray as rl +from collections.abc import Callable +from openpilot.common.params import Params +from openpilot.system.ui.lib.application import gui_app, FontWeight, MousePos +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.sunnypilot.lib.styles import style +from openpilot.system.ui.widgets.list_view import ItemAction + +# Dimensions and styling constants +BUTTON_WIDTH = 150 +BUTTON_HEIGHT = 150 +LABEL_WIDTH = 350 +BUTTON_SPACING = 25 +VALUE_FONT_SIZE = 50 +BUTTON_FONT_SIZE = 60 +CONTAINER_PADDING = 20 + + +class OptionControlSP(ItemAction): + def __init__(self, param: str, min_value: int, max_value: int, + value_change_step: int = 1, enabled: bool | Callable[[], bool] = True, + on_value_changed: Callable[[int], None] | None = None, + value_map: dict[int, int] | None = None, + label_width: int = LABEL_WIDTH, + use_float_scaling: bool = False, label_callback: Callable[[int], str] | None = None): + + super().__init__(enabled=enabled) + self.params = Params() + self.param_key = param + self.min_value = min_value + self.max_value = max_value + self.value_change_step = value_change_step + self._minus_enabled = enabled + self._plus_enabled = enabled + self.on_value_changed = on_value_changed + self.value_map = value_map + self.label_width = label_width + self.use_float_scaling = use_float_scaling + self.current_value = min_value + self.label_callback = label_callback + if self.value_map: + for key in self.value_map: + if self.value_map[key] == self.params.get(self.param_key, return_default=True): + self.current_value = int(key) + break + else: + value = self.params.get(self.param_key, return_default=True) + self.current_value = int(float(value) * 100.0) if self.use_float_scaling else int(value) + + # Initialize font and button styles + self._font = gui_app.font(FontWeight.MEDIUM) + + # Layout rectangles for components + self.minus_btn_rect = rl.Rectangle(0, 0, 0, 0) + self.plus_btn_rect = rl.Rectangle(0, 0, 0, 0) + + def get_value(self) -> int: + """Get the current value of the control""" + return self.current_value + + def set_value(self, value: int): + """Set the control to a specific value""" + if not (self.min_value <= value <= self.max_value): + return + if value == self.current_value: + return + self.current_value = value + if self.value_map: + self.params.put(self.param_key, self.value_map[value]) + elif self.use_float_scaling: + self.params.put(self.param_key, value / 100.0) + else: + self.params.put(self.param_key, value) + if self.on_value_changed: + self.on_value_changed(value) + + def get_displayed_value(self) -> str: + """Get the displayed value, handling value mapping if present""" + value = self.current_value + + if callable(self.label_callback): + if self.value_map: + return self.label_callback(self.value_map[value]) + else: + return self.label_callback(value) + + if self.value_map: + # Use the value map to get the display string + if value in self.value_map: + return str(self.value_map[value]) # Return the display string + + # If using float scaling, format as float + if self.use_float_scaling: + return f"{value / 100.0:.2f}" + + return str(value) + + def _render(self, rect: rl.Rectangle): + if self._rect.width == 0 or self._rect.height == 0 or not self.is_visible: + return + + control_width = (BUTTON_WIDTH * 2) + self.label_width + (BUTTON_SPACING * 2) + total_width = control_width + (CONTAINER_PADDING * 2) + self._rect.width = total_width + + start_x = self._rect.x + self._rect.width - control_width - (CONTAINER_PADDING * 2) + component_y = rect.y + (rect.height - BUTTON_HEIGHT) / 2 + self.container_rect = rl.Rectangle(start_x, component_y, total_width, BUTTON_HEIGHT) + + # background + rl.draw_rectangle_rounded(self.container_rect, 0.2, 20, style.OPTION_CONTROL_CONTAINER_BG) + + # minus button + self.minus_btn_rect = rl.Rectangle(self.container_rect.x, component_y, BUTTON_WIDTH + CONTAINER_PADDING, + BUTTON_HEIGHT) + + # label + label_x = self.container_rect.x + CONTAINER_PADDING + BUTTON_WIDTH + BUTTON_SPACING + self.label_rect = rl.Rectangle(label_x, component_y, self.label_width, BUTTON_HEIGHT) + + # plus button + plus_x = label_x + self.label_width + BUTTON_SPACING + self.plus_btn_rect = rl.Rectangle(plus_x, component_y, BUTTON_WIDTH + CONTAINER_PADDING, BUTTON_HEIGHT) + + self._minus_enabled = self.enabled and self.current_value > self.min_value + self._plus_enabled = self.enabled and self.current_value < self.max_value + + self._render_button(self.minus_btn_rect, "-", self._minus_enabled) + self._render_value_label() + self._render_button(self.plus_btn_rect, "+", self._plus_enabled) + + def _render_button(self, rect: rl.Rectangle, text: str, enabled: bool): + mouse_pos = rl.get_mouse_position() + is_pressed = (rl.check_collision_point_rec(mouse_pos, rect) and + self._touch_valid() and rl.is_mouse_button_down(rl.MouseButton.MOUSE_BUTTON_LEFT)) + + text_color = style.ITEM_TEXT_COLOR if enabled else style.ITEM_DISABLED_TEXT_COLOR + + # highlight + if enabled and is_pressed: + rl.draw_rectangle_rounded(rect, 0.2, 20, style.OPTION_CONTROL_BTN_PRESSED) + + # button text + text_size = measure_text_cached(self._font, text, BUTTON_FONT_SIZE) + text_x = rect.x + (rect.width - text_size.x) / 2 + text_y = rect.y + (rect.height - text_size.y) / 2 + rl.draw_text_ex(self._font, text, rl.Vector2(text_x, text_y), BUTTON_FONT_SIZE, 0, text_color) + + def _render_value_label(self): + """Render the current value label""" + text = self.get_displayed_value() + text_color = style.ITEM_TEXT_COLOR if self.enabled else style.ITEM_DISABLED_TEXT_COLOR + + text_size = measure_text_cached(self._font, text, VALUE_FONT_SIZE) + text_x = self.label_rect.x + (self.label_rect.width - text_size.x) / 2 + text_y = self.label_rect.y + (self.label_rect.height - text_size.y) / 2 + + rl.draw_text_ex(self._font, text, rl.Vector2(text_x, text_y), VALUE_FONT_SIZE, 0, text_color) + + def _handle_mouse_release(self, mouse_pos: MousePos): + if self._minus_enabled and rl.check_collision_point_rec(mouse_pos, self.minus_btn_rect): + new_value = self.current_value - self.value_change_step + new_value = max(self.min_value, new_value) + self.set_value(new_value) + elif self._plus_enabled and rl.check_collision_point_rec(mouse_pos, self.plus_btn_rect): + new_value = self.current_value + self.value_change_step + new_value = min(self.max_value, new_value) + self.set_value(new_value) diff --git a/openpilot/system/ui/sunnypilot/widgets/progress_bar.py b/openpilot/system/ui/sunnypilot/widgets/progress_bar.py new file mode 100644 index 0000000000..76f4243411 --- /dev/null +++ b/openpilot/system/ui/sunnypilot/widgets/progress_bar.py @@ -0,0 +1,57 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import pyray as rl +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.widgets.list_view import ListItem, ItemAction + + +class ProgressBarAction(ItemAction): + def __init__(self, width=600): + super().__init__(width=width) + self.progress = 0.0 + self.text = "" + self.show_progress = False + self.text_color = rl.GRAY + self._font = gui_app.font(FontWeight.NORMAL) + + def update(self, progress, text, show_progress=False, text_color=rl.GRAY): + self.progress = progress + self.text = text + self.show_progress = show_progress + self.text_color = text_color + + def _render(self, rect: rl.Rectangle): + font_size = 40 + text_size = measure_text_cached(self._font, self.text, font_size) + padding = 30 + bar_width = text_size.x + 2 * padding + text_x = (bar_width - text_size.x) / 2 + + if self.show_progress and len(parts := self.text.split(' - ', 1)) == 2: + prefix = parts[0] + max_prefix_w = measure_text_cached(self._font, "100%", font_size).x + current_prefix_w = measure_text_cached(self._font, prefix, font_size).x + + bar_width = (text_size.x - current_prefix_w + max_prefix_w) + 2 * padding + text_x = padding + (max_prefix_w - current_prefix_w) + + bar_height = 60 + bar_rect = rl.Rectangle(rect.x + rect.width - bar_width, rect.y + (rect.height - bar_height) / 2, bar_width, bar_height) + + if self.show_progress: + inner_rect = rl.Rectangle(bar_rect.x + 4, bar_rect.y + 4, bar_rect.width - 8, bar_rect.height - 8) + if inner_rect.width > 0: + fill_width = max(0, min(inner_rect.width, inner_rect.width * (self.progress / 100.0))) + rl.draw_rectangle_rounded(rl.Rectangle(inner_rect.x, inner_rect.y, fill_width, inner_rect.height), 0.2, 10, rl.Color(30, 121, 232, 255)) + + rl.draw_text_ex(self._font, self.text, rl.Vector2(bar_rect.x + text_x, bar_rect.y + (bar_height - text_size.y) / 2), font_size, 0, self.text_color) + + +def progress_item(title): + action = ProgressBarAction() + return ListItem(title=title, action_item=action) diff --git a/openpilot/system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py b/openpilot/system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py new file mode 100644 index 0000000000..77e8b5fd2c --- /dev/null +++ b/openpilot/system/ui/sunnypilot/widgets/sunnylink_pairing_dialog.py @@ -0,0 +1,139 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +import base64 + +import pyray as rl +from openpilot.common.swaglog import cloudlog +from openpilot.selfdrive.ui.ui_state import ui_state +from openpilot.selfdrive.ui.widgets.pairing_dialog import PairingDialog +from openpilot.sunnypilot.sunnylink.api import SunnylinkApi, UNREGISTERED_SUNNYLINK_DONGLE_ID, API_HOST +from openpilot.system.ui.lib.application import FontWeight, gui_app +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.lib.wrap_text import wrap_text +from openpilot.system.ui.lib.text_measure import measure_text_cached + + +class SunnylinkPairingDialog(PairingDialog): + """Dialog for device pairing with QR code.""" + + QR_REFRESH_INTERVAL = 300 # 5 minutes in seconds + + def __init__(self, sponsor_pairing: bool = False): + PairingDialog.__init__(self) + self._sponsor_pairing = sponsor_pairing + self._is_paired_prev = ui_state.sunnylink_state.is_paired() + + def _get_pairing_url(self) -> str: + qr_string = "https://github.com/sponsors/sunnyhaibin" + + if self._sponsor_pairing: + try: + sl_dongle_id = self.params.get("SunnylinkDongleId") or UNREGISTERED_SUNNYLINK_DONGLE_ID + token = SunnylinkApi(sl_dongle_id).get_token() + inner_string = f"1|{sl_dongle_id}|{token}" + payload_bytes = base64.b64encode(inner_string.encode('utf-8')).decode('utf-8') + qr_string = f"{API_HOST}/sso?state={payload_bytes}" + except Exception: + cloudlog.exception("Failed to get pairing token") + + return qr_string + + def _update_state(self): + is_paired = ui_state.sunnylink_state.is_paired() + if not self._is_paired_prev and is_paired: + gui_app.pop_widget() + + def _render(self, rect: rl.Rectangle) -> int: + rl.clear_background(rl.Color(224, 224, 224, 255)) + + self._check_qr_refresh() + + margin = 70 + content_rect = rl.Rectangle(rect.x + margin, rect.y + margin, rect.width - 2 * margin, rect.height - 2 * margin) + y = content_rect.y + + # Close button + close_size = 80 + pad = 20 + close_rect = rl.Rectangle(content_rect.x - pad, y - pad, close_size + pad * 2, close_size + pad * 2) + self._close_btn.render(close_rect) + + y += close_size + 40 + + # Title + title = tr("Pair your GitHub account") if self._sponsor_pairing else tr("Early Access: Become a sunnypilot Sponsor") + title_font = gui_app.font(FontWeight.NORMAL) + left_width = int(content_rect.width * 0.5 - 15) + + title_wrapped = wrap_text(title_font, title, 75, left_width) + rl.draw_text_ex(title_font, "\n".join(title_wrapped), rl.Vector2(content_rect.x, y), 75, 0.0, rl.BLACK) + y += len(title_wrapped) * 75 + 60 + + # Two columns: instructions and QR code + remaining_height = content_rect.height - (y - content_rect.y) + right_width = content_rect.width // 2 - 20 + + # Instructions + self._render_instructions(rl.Rectangle(content_rect.x, y, left_width, remaining_height)) + + # QR code + qr_size = min(right_width, content_rect.height) - 40 + qr_x = content_rect.x + left_width + 40 + (right_width - qr_size) // 2 + qr_y = content_rect.y + self._render_qr_code(rl.Rectangle(qr_x, qr_y, qr_size, qr_size)) + + return -1 + + def _render_instructions(self, rect: rl.Rectangle) -> None: + if self._sponsor_pairing: + instructions = [ + tr("Scan the QR code to login to your GitHub account"), + tr("Follow the prompts to complete the pairing process"), + tr("Re-enter the \"sunnylink\" panel to verify sponsorship status"), + tr("If sponsorship status was not updated, please contact a moderator on the community forum at https://community.sunnypilot.ai") + ] + else: + instructions = [ + tr("Scan the QR code to visit sunnyhaibin's GitHub Sponsors page"), + tr("Choose your sponsorship tier and confirm your support"), + tr("Join our Community Forum at https://community.sunnypilot.ai and reach out to a moderator if you have issues") + ] + + font = gui_app.font(FontWeight.BOLD) + y = rect.y + + for i, text in enumerate(instructions): + circle_radius = 25 + circle_x = rect.x + circle_radius + 15 + text_x = rect.x + circle_radius * 2 + 40 + text_width = rect.width - (circle_radius * 2 + 40) + + wrapped = wrap_text(font, text, 47, int(text_width)) + text_height = len(wrapped) * 47 + circle_y = y + text_height // 2 + + # Circle and number + rl.draw_circle(int(circle_x), int(circle_y), circle_radius, rl.Color(70, 70, 70, 255)) + number = str(i + 1) + number_size = measure_text_cached(font, number, 30) + rl.draw_text_ex(font, number, (int(circle_x - number_size.x // 2), int(circle_y - number_size.y // 2)), 30, 0, rl.WHITE) + + # Text + rl.draw_text_ex(font, "\n".join(wrapped), rl.Vector2(text_x, y), 47, 0.0, rl.BLACK) + y += text_height + 50 + + +if __name__ == "__main__": + gui_app.init_window("pairing device") + pairing = SunnylinkPairingDialog(sponsor_pairing=True) + try: + for _ in gui_app.render(): + result = pairing.render(rl.Rectangle(0, 0, gui_app.width, gui_app.height)) + if result != -1: + break + finally: + del pairing diff --git a/openpilot/system/ui/sunnypilot/widgets/toggle.py b/openpilot/system/ui/sunnypilot/widgets/toggle.py new file mode 100644 index 0000000000..fbb2ba40ac --- /dev/null +++ b/openpilot/system/ui/sunnypilot/widgets/toggle.py @@ -0,0 +1,63 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from collections.abc import Callable + +import pyray as rl +from openpilot.common.params import Params +from openpilot.system.ui.lib.application import MousePos +from openpilot.system.ui.widgets.toggle import Toggle +from openpilot.system.ui.sunnypilot.lib.styles import style + +KNOB_PADDING = 5 +KNOB_RADIUS = style.TOGGLE_BG_HEIGHT / 2 - KNOB_PADDING + + +class ToggleSP(Toggle): + def __init__(self, initial_state=False, callback: Callable[[bool], None] | None = None, param: str | None = None): + self.param_key = param + self.params = Params() + if self.param_key: + initial_state = self.params.get_bool(self.param_key) + Toggle.__init__(self, initial_state, callback) + + def set_rect(self, rect: rl.Rectangle): + self._rect = rl.Rectangle(rect.x, rect.y, style.TOGGLE_WIDTH, style.TOGGLE_HEIGHT) + + def _handle_mouse_release(self, mouse_pos: MousePos): + super()._handle_mouse_release(mouse_pos) + if self._enabled and self.param_key: + self.params.put_bool(self.param_key, self._state) + + def _render(self, rect: rl.Rectangle): + self.update() + self._rect.y -= style.ITEM_PADDING / 2 + if self._enabled: + bg_color = self._blend_color(style.TOGGLE_OFF_COLOR, style.TOGGLE_ON_COLOR, self._progress) + knob_color = style.TOGGLE_KNOB_COLOR + else: + bg_color = self._blend_color(style.TOGGLE_DISABLED_OFF_COLOR, style.TOGGLE_DISABLED_ON_COLOR, self._progress) + knob_color = style.TOGGLE_DISABLED_KNOB_COLOR + + # Draw background + bg_rect = rl.Rectangle(self._rect.x, self._rect.y, style.TOGGLE_WIDTH, style.TOGGLE_BG_HEIGHT) + + # Draw actual background + rl.draw_rectangle_rounded(bg_rect, 1.0, 10, bg_color) + + left_edge = bg_rect.x + KNOB_PADDING + right_edge = bg_rect.x + bg_rect.width - KNOB_PADDING + + knob_travel_distance = right_edge - left_edge - 2 * KNOB_RADIUS + min_knob_x = left_edge + KNOB_RADIUS + knob_x = min_knob_x + knob_travel_distance * self._progress + knob_y = self._rect.y + style.TOGGLE_BG_HEIGHT / 2 + + rl.draw_circle(int(knob_x), int(knob_y), KNOB_RADIUS, knob_color) + + clicked = self._clicked + self._clicked = False + return clicked diff --git a/openpilot/system/ui/sunnypilot/widgets/tree_dialog.py b/openpilot/system/ui/sunnypilot/widgets/tree_dialog.py new file mode 100644 index 0000000000..97150e1028 --- /dev/null +++ b/openpilot/system/ui/sunnypilot/widgets/tree_dialog.py @@ -0,0 +1,296 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" +from dataclasses import dataclass, field + +import pyray as rl +from openpilot.common.params import Params +from openpilot.system.ui.lib.application import FontWeight +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.widgets import DialogResult +from openpilot.system.ui.widgets.button import Button, ButtonStyle, BUTTON_PRESSED_BACKGROUND_COLORS +from openpilot.system.ui.widgets.label import gui_label +from openpilot.system.ui.widgets.option_dialog import MultiOptionDialog + +from openpilot.system.ui.sunnypilot.lib.styles import style +from openpilot.system.ui.sunnypilot.widgets.helpers.fuzzy_search import search_from_list +from openpilot.system.ui.sunnypilot.widgets.helpers.star_icon import draw_star +from openpilot.system.ui.sunnypilot.widgets.input_dialog import InputDialogSP + + +@dataclass +class TreeNode: + ref: str + data: dict = field(default_factory=dict) + + +@dataclass +class TreeFolder: + folder: str + nodes: list + + +class TreeItemWidget(Button): + def __init__(self, text, ref, is_folder=False, indent_level=0, click_callback=None, favorite_callback=None, is_favorite=False, is_expanded=False): + super().__init__(text, click_callback, button_style=ButtonStyle.NORMAL, text_alignment=rl.GuiTextAlignment.TEXT_ALIGN_LEFT, + text_padding=20 + indent_level * 30, elide_right=True) + self.text = text + self.ref = ref + self.is_folder = is_folder + self.indent_level = indent_level + self.is_favorite = is_favorite + self.selected = False + self._favorite_callback = favorite_callback + self.text_padding = 20 + indent_level * 30 + self.border_radius = 10 + self.is_expanded = is_expanded + + def _render(self, _): + indent = 60 * self.indent_level + self._rect = rl.Rectangle(_.x + indent, _.y, _.width - indent, _.height) + if self.is_pressed: + color = BUTTON_PRESSED_BACKGROUND_COLORS[self._button_style] + elif self.selected and self.ref != "search_bar": + color = style.BUTTON_PRIMARY_COLOR + else: + color = style.BUTTON_DISABLED_BG_COLOR + roundness = self.border_radius / (min(self._rect.width, self._rect.height) / 2) + rl.draw_rectangle_rounded(self._rect, roundness, 10, color) + text_offset = self.text_padding + 20 - 15 if self.is_expanded and not self.is_folder and self.indent_level > 0 else self.text_padding + 20 + text_rect = rl.Rectangle(self._rect.x + text_offset, self._rect.y, self._rect.width - self.text_padding - 20 - 90, self._rect.height) + self._label.render(text_rect) + + if not self.is_folder and self._favorite_callback: + draw_star(self._rect.x + self._rect.width - 90, self._rect.y + self._rect.height / 2, 40, self.is_favorite, + style.ON_BG_COLOR if self.is_favorite else rl.GRAY) + + def _handle_mouse_release(self, mouse_pos): + star_rect = rl.Rectangle(self._rect.x + self._rect.width - 90 - 40, self._rect.y + self._rect.height / 2 - 40, 80, 80) + if not self.is_folder and self._favorite_callback and rl.check_collision_point_rec(mouse_pos, star_rect): + self._favorite_callback() + return True + return super()._handle_mouse_release(mouse_pos) + + +class TreeOptionDialog(MultiOptionDialog): + @property + def on_exit(self): + return self._callback + + @on_exit.setter + def on_exit(self, value): + self._callback = value + + def __init__(self, title, folders, current_ref="", fav_param="", option_font_weight=FontWeight.MEDIUM, search_prompt=None, + get_folders_fn=None, on_exit=None, display_func=None, search_funcs=None, search_title=None, search_subtitle=None): + super().__init__(title, [], current_ref, option_font_weight) + self.folders = folders + self.selection_ref = current_ref + self.fav_param = fav_param + self.expanded = set() + self.params = Params() + val = self.params.get(fav_param) if fav_param else None + self.favorites = set(val.split(';')) if val else set() + self.query = "" + self.search_prompt = search_prompt or tr("Search") + self.get_folders_fn = get_folders_fn + self.on_exit = on_exit + self.display_func = display_func or (lambda node: node.data.get('display_name', node.ref)) + self.search_funcs = search_funcs or [lambda node: node.data.get('display_name', ''), lambda node: node.data.get('short_name', '')] + self._search_rect = None + self._search_width = 0.475 + + # Default title & overridable subtitle for InputDialogSP + self.search_title = search_title or tr("Enter search query") + self.search_subtitle = search_subtitle + self.search_dialog = None + self._search_pressed = False + + self.selection_node = None + # Try to match by ref, by display text, or fall back to "Default" when no ref is set + for folder in self.folders: + for node in folder.nodes: + display = self.display_func(node) + if ( + node.ref == current_ref or + display == current_ref or + (not current_ref and node.ref == "Default") + ): + self.selection = display + self.current = display + self.selection_node = node + break + if self.selection_node is not None: + break + + self._build_visible_items() + + def _on_search_confirm(self, result, text): + if result == DialogResult.CONFIRM: + self.query = text + self._build_visible_items() + + def _on_search_clicked(self): + self.search_dialog = InputDialogSP( + self.search_title, + self.search_subtitle, + current_text=self.query, + callback=self._on_search_confirm, + ) + self.search_dialog.show() + + def _toggle_folder(self, folder): + if folder.folder: + if folder.folder in self.expanded: + self.expanded.remove(folder.folder) + else: + self.expanded.add(folder.folder) + if folder == self.folders[-1] and folder.folder in self.expanded: + self.scroller.scroll_panel.set_offset(self.scroller.scroll_panel.offset - 200) + self._build_visible_items(reset_scroll=False) + + def _select_node(self, node): + self.selection = self.display_func(node) + self.selection_ref = node.ref + + def _toggle_favorite(self, node): + self.favorites.remove(node.ref) if node.ref in self.favorites else self.favorites.add(node.ref) + if self.fav_param: + self.params.put(self.fav_param, ';'.join(self.favorites)) + if self.get_folders_fn: + self.folders = self.get_folders_fn(self.favorites) + self._build_visible_items(reset_scroll=False) + + def _build_visible_items(self, reset_scroll=True): + self.visible_items = [] + + # Pinned selected item at the very top (if any) + if getattr(self, "selection_node", None) is not None: + node = self.selection_node + display = self.display_func(node) + self.selection = self.current = display + favorite_cb = (lambda node_ref=node: self._toggle_favorite(node_ref)) if self.fav_param and node.ref != "Default" else None + self.visible_items.append(TreeItemWidget(self.display_func(node), node.ref, False, 0, + lambda node_ref=node: self._select_node(node_ref), + favorite_cb, node.ref in self.favorites, is_expanded=True)) + + for folder in self.folders: + nodes = [node for node in folder.nodes if not self.query or search_from_list(self.query, [search_func(node) for search_func in self.search_funcs])] + if not nodes and self.query: + continue + expanded = folder.folder in self.expanded or not folder.folder or bool(self.query) + if folder.folder: + self.visible_items.append(TreeItemWidget(f"{'-' if expanded else '+'} {folder.folder}", "", True, 0, + lambda folder_ref=folder: self._toggle_folder(folder_ref))) + if expanded: + for node in nodes: + # Skip duplicate root-level item for the selected node + if self.selection_node is not None and node.ref == self.selection_node.ref and not folder.folder: + continue + + favorite_cb = (lambda node_ref=node: self._toggle_favorite(node_ref)) if self.fav_param and node.ref != "Default" else None + self.visible_items.append(TreeItemWidget(self.display_func(node), node.ref, False, 1 if folder.folder else 0, + lambda node_ref=node: self._select_node(node_ref), + favorite_cb, node.ref in self.favorites, is_expanded=expanded)) + + self.option_buttons = self.visible_items + self.options = [item.text for item in self.visible_items] + # Rebuild scroller items to ensure proper setup of touch callbacks + self.scroller._items.clear() + for item in self.option_buttons: + self.scroller.add_widget(item) + if reset_scroll: + self.scroller.scroll_panel.set_offset(0) + + def _render(self, rect): + dialog_content_rect = rl.Rectangle(rect.x + 50, rect.y + 50, rect.width - 100, rect.height - 100) + rl.draw_rectangle_rounded(dialog_content_rect, 0.02, 20, rl.BLACK) + + # Title on the left + title_rect = rl.Rectangle(dialog_content_rect.x + 50, dialog_content_rect.y + 50, dialog_content_rect.width * 0.5, 70) + gui_label(title_rect, self.title, 70, font_weight=FontWeight.BOLD) + + # Search bar on the top right + search_width = dialog_content_rect.width * self._search_width + search_height = 110 + search_x = dialog_content_rect.x + dialog_content_rect.width - 50 - search_width + search_y = dialog_content_rect.y + 40 # align roughly with title + + self._search_rect = rl.Rectangle(search_x, search_y, search_width, search_height) + + # Draw search field + inset = 4 + roundness = 0.3 + input_rect = rl.Rectangle(self._search_rect.x + inset, self._search_rect.y + inset, + self._search_rect.width - inset * 2, self._search_rect.height - inset * 2) + + # Transparent fill (unpressed), white fill (pressed), border + fill_color = style.TREE_DIALOG_SEARCH_BUTTON_PRESSED if self._search_pressed else style.TREE_DIALOG_TRANSPARENT + rl.draw_rectangle_rounded(input_rect, roundness, 10, fill_color) + rl.draw_rectangle_rounded_lines_ex(input_rect, roundness, 10, 3, style.TREE_DIALOG_SEARCH_BUTTON_BORDER) + + # Magnifying glass icon + icon_color = rl.Color(180, 180, 180, 240) + cx = input_rect.x + 60 + cy = input_rect.y + input_rect.height / 2 - 5 + radius = min(input_rect.height * 0.28, 26) + + circle_thickness = 4 + for i in range(circle_thickness): + rl.draw_circle_lines(int(cx), int(cy), radius - i, icon_color) + + handle_thickness = 5 + inner_x = cx + radius * 0.65 + inner_y = cy + radius * 0.65 + outer_x = cx + radius * 1.45 + outer_y = cy + radius * 1.45 + + rl.draw_line_ex(rl.Vector2(inner_x, inner_y), rl.Vector2(outer_x, outer_y), handle_thickness, icon_color) + + # User text (query), placed after the icon if present + if self.query: + text_start_x = outer_x + 45 + text_rect = rl.Rectangle(text_start_x, input_rect.y, input_rect.x + input_rect.width - text_start_x - 10, input_rect.height) + gui_label(text_rect, self.query, 70, font_weight=FontWeight.MEDIUM) + + options_top = self._search_rect.y + self._search_rect.height + 40 + options_area_rect = rl.Rectangle(dialog_content_rect.x + 50, options_top, dialog_content_rect.width - 100, + dialog_content_rect.height - (options_top - dialog_content_rect.y) - 210) + + for index, option_text in enumerate(self.options): + self.option_buttons[index].selected = (option_text == self.selection) + self.option_buttons[index].set_button_style(ButtonStyle.PRIMARY if option_text == self.selection else ButtonStyle.NORMAL) + self.option_buttons[index].set_rect(rl.Rectangle(0, 0, options_area_rect.width, 135)) + self.scroller.render(options_area_rect) + + button_width = (dialog_content_rect.width - 150) / 2 + button_y_position = dialog_content_rect.y + dialog_content_rect.height - 160 + + cancel_rect = rl.Rectangle(dialog_content_rect.x + 50, button_y_position, button_width, 160) + self.cancel_button.render(cancel_rect) + + select_rect = rl.Rectangle(dialog_content_rect.x + 100 + button_width, button_y_position, button_width, 160) + self.select_button.set_enabled(self.selection != self.current) + self.select_button.render(select_rect) + + def _handle_mouse_press(self, mouse_pos): + if self._search_rect and rl.check_collision_point_rec(mouse_pos, self._search_rect): + self._search_pressed = True + return True + return super()._handle_mouse_press(mouse_pos) + + def _handle_mouse_release(self, mouse_pos): + clicked_search = False + if self._search_rect and rl.check_collision_point_rec(mouse_pos, self._search_rect): + clicked_search = self._search_pressed + + self._search_pressed = False + + if clicked_search: + self._on_search_clicked() + return True + + return super()._handle_mouse_release(mouse_pos) diff --git a/openpilot/system/ui/text.py b/openpilot/system/ui/text.py new file mode 100755 index 0000000000..f6bcf4eddf --- /dev/null +++ b/openpilot/system/ui/text.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python3 +import re +import sys +import pyray as rl +from openpilot.common.hardware import HARDWARE, PC +from openpilot.system.ui.lib.application import BIG_UI, gui_app +from openpilot.system.ui.lib.scroll_panel import GuiScrollPanel +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.button import Button, ButtonStyle + +if BIG_UI: + MARGIN = 50 + SPACING = 40 + FONT_SIZE = 72 + LINE_HEIGHT = 80 + BUTTON_SIZE = rl.Vector2(310, 160) +else: + MARGIN = 20 + SPACING = 30 + FONT_SIZE = 25 + LINE_HEIGHT = 25 + BUTTON_SIZE = rl.Vector2(150, 80) + +DEMO_TEXT = """This is a sample text that will be wrapped and scrolled if necessary. + The text is long enough to demonstrate scrolling and word wrapping.""" * 30 + + +def wrap_text(text, font_size, max_width): + lines = [] + font = gui_app.font() + + for paragraph in text.split("\n"): + if not paragraph.strip(): + # Don't add empty lines first, ensuring wrap_text("") returns [] + if lines: + lines.append("") + continue + indent = re.match(r"^\s*", paragraph).group() + current_line = indent + words = re.split(r"(\s+|-)", paragraph[len(indent):]) + while len(words): + word = words.pop(0) + test_line = current_line + word + (words.pop(0) if words else "") + if measure_text_cached(font, test_line, font_size).x <= max_width: + current_line = test_line + else: + lines.append(current_line) + current_line = word + " " + current_line = current_line.rstrip() + if current_line: + lines.append(current_line) + + return lines + + +class TextWindow(Widget): + def __init__(self, text: str): + super().__init__() + self._textarea_rect = rl.Rectangle(MARGIN, MARGIN, gui_app.width - MARGIN * 2, gui_app.height - MARGIN * 2) + self._wrapped_lines = wrap_text(text, FONT_SIZE, self._textarea_rect.width - 20) + self._content_rect = rl.Rectangle(0, 0, self._textarea_rect.width - 20, len(self._wrapped_lines) * LINE_HEIGHT) + self._scroll_panel = GuiScrollPanel() + self._scroll_panel._offset_filter_y.x = -max(self._content_rect.height - self._textarea_rect.height, 0) + + button_text = "Exit" if PC else "Reboot" + self._button = Button(button_text, click_callback=self._on_button_clicked, button_style=ButtonStyle.TRANSPARENT_WHITE_BORDER, font_size=FONT_SIZE) + + @staticmethod + def _on_button_clicked(): + gui_app.request_close() + if not PC: + HARDWARE.reboot() + + def _render(self, rect: rl.Rectangle): + scroll = self._scroll_panel.update(self._textarea_rect, self._content_rect) + rl.begin_scissor_mode(int(self._textarea_rect.x), int(self._textarea_rect.y), int(self._textarea_rect.width), int(self._textarea_rect.height)) + for i, line in enumerate(self._wrapped_lines): + position = rl.Vector2(self._textarea_rect.x, self._textarea_rect.y + scroll + i * LINE_HEIGHT) + if position.y + LINE_HEIGHT < self._textarea_rect.y or position.y > self._textarea_rect.y + self._textarea_rect.height: + continue + rl.draw_text_ex(gui_app.font(), line, position, FONT_SIZE, 0, rl.WHITE) + rl.end_scissor_mode() + + button_bounds = rl.Rectangle(rect.width - MARGIN - BUTTON_SIZE.x - SPACING, rect.height - MARGIN - BUTTON_SIZE.y, BUTTON_SIZE.x, BUTTON_SIZE.y) + self._button.render(button_bounds) + + +if __name__ == "__main__": + text = sys.argv[1] if len(sys.argv) > 1 else DEMO_TEXT + gui_app.init_window("Text Viewer") + text_window = TextWindow(text) + for _ in gui_app.render(): + text_window.render(rl.Rectangle(0, 0, gui_app.width, gui_app.height)) diff --git a/openpilot/system/ui/tici_reset.py b/openpilot/system/ui/tici_reset.py new file mode 100755 index 0000000000..5c175dbfa6 --- /dev/null +++ b/openpilot/system/ui/tici_reset.py @@ -0,0 +1,130 @@ +#!/usr/bin/env python3 +import subprocess +import sys +import threading +import time +from enum import IntEnum + +import pyray as rl + +from openpilot.common.hardware import PC +from openpilot.system.ui.lib.application import gui_app, FontWeight, FONT_SCALE +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.button import Button, ButtonStyle +from openpilot.system.ui.widgets.label import gui_label, gui_text_box + +USERDATA = "/dev/disk/by-partlabel/userdata" +TIMEOUT = 3*60 + + +class ResetMode(IntEnum): + USER_RESET = 0 # user initiated a factory reset from openpilot + RECOVER = 1 # userdata is corrupt for some reason, give a chance to recover + + +class ResetState(IntEnum): + NONE = 0 + CONFIRM = 1 + RESETTING = 2 + FAILED = 3 + + +class Reset(Widget): + def __init__(self, mode): + super().__init__() + self._mode = mode + self._previous_reset_state = None + self._reset_state = ResetState.NONE + self._cancel_button = Button("Cancel", gui_app.request_close) + self._confirm_button = Button("Confirm", self._confirm, button_style=ButtonStyle.PRIMARY) + self._reboot_button = Button("Reboot", self._reboot) + + @staticmethod + def _reboot() -> None: + subprocess.run("sudo reboot", shell=True) + + def _do_erase(self): + if PC: + return + + # Removing data and formatting + rm = subprocess.run("sudo rm -rf /data/*", shell=True).returncode + subprocess.run(f"sudo umount {USERDATA}", shell=True) + fmt = subprocess.run(f"yes | sudo mkfs.ext4 {USERDATA}", shell=True).returncode + + if rm == 0 or fmt == 0: + subprocess.run("sudo reboot", shell=True) + else: + self._reset_state = ResetState.FAILED + + def _start_reset(self): + self._reset_state = ResetState.RESETTING + threading.Timer(0.1, self._do_erase).start() + + def _update_state(self): + if self._reset_state != self._previous_reset_state: + self._previous_reset_state = self._reset_state + self._timeout_st = time.monotonic() + elif self._reset_state != ResetState.RESETTING and (time.monotonic() - self._timeout_st) > TIMEOUT: + exit(0) + + def _render(self, _): + content_rect = rl.Rectangle(45, 200, self._rect.width - 90, self._rect.height - 245) + + label_rect = rl.Rectangle(content_rect.x + 140, content_rect.y, content_rect.width - 280, 100 * FONT_SCALE) + gui_label(label_rect, "System Reset", 100, font_weight=FontWeight.BOLD) + + text_rect = rl.Rectangle(content_rect.x + 140, content_rect.y + 140, content_rect.width - 280, content_rect.height - 90 - 100 * FONT_SCALE) + gui_text_box(text_rect, self._get_body_text(), 90) + + button_height = 160 + button_spacing = 50 + button_top = content_rect.y + content_rect.height - button_height + button_width = (content_rect.width - button_spacing) / 2.0 + + if self._reset_state != ResetState.RESETTING: + if self._mode == ResetMode.RECOVER: + self._reboot_button.render(rl.Rectangle(content_rect.x, button_top, button_width, button_height)) + elif self._mode == ResetMode.USER_RESET: + self._cancel_button.render(rl.Rectangle(content_rect.x, button_top, button_width, button_height)) + + if self._reset_state != ResetState.FAILED: + self._confirm_button.render(rl.Rectangle(content_rect.x + button_width + 50, button_top, button_width, button_height)) + else: + self._reboot_button.render(rl.Rectangle(content_rect.x, button_top, content_rect.width, button_height)) + + def _confirm(self): + if self._reset_state == ResetState.CONFIRM: + self._start_reset() + else: + self._reset_state = ResetState.CONFIRM + + def _get_body_text(self): + if self._reset_state == ResetState.CONFIRM: + return "Are you sure you want to reset your device?" + if self._reset_state == ResetState.RESETTING: + return "Resetting device...\nThis may take up to a minute." + if self._reset_state == ResetState.FAILED: + return "Reset failed. Reboot to try again." + if self._mode == ResetMode.RECOVER: + return "Unable to mount data partition. Partition may be corrupted. Press confirm to erase and reset your device." + return "System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot." + + +def main(): + mode = ResetMode.USER_RESET + if len(sys.argv) > 1: + if sys.argv[1] == '--recover': + mode = ResetMode.RECOVER + + gui_app.init_window("System Reset", 20) + reset = Reset(mode) + + gui_app.push_widget(reset) + + for _ in gui_app.render(): + pass + + +if __name__ == "__main__": + main() diff --git a/openpilot/system/ui/tici_setup.py b/openpilot/system/ui/tici_setup.py new file mode 100755 index 0000000000..2b2c1c39f8 --- /dev/null +++ b/openpilot/system/ui/tici_setup.py @@ -0,0 +1,424 @@ +#!/usr/bin/env python3 +import os +import re +import threading +import time +import urllib.request +import urllib.error +from urllib.parse import urlparse +from enum import IntEnum + +import pyray as rl + +from openpilot.cereal import log +from openpilot.common.hardware import HARDWARE +from openpilot.system.ui.lib.scroll_panel import GuiScrollPanel +from openpilot.system.ui.lib.application import gui_app, FontWeight, FONT_SCALE +from openpilot.system.ui.widgets import DialogResult, Widget +from openpilot.system.ui.widgets.button import Button, ButtonStyle, ButtonRadio +from openpilot.system.ui.widgets.keyboard import Keyboard +from openpilot.system.ui.widgets.label import Label +from openpilot.system.ui.widgets.network import WifiManagerUI, WifiManager + +NetworkType = log.DeviceState.NetworkType + +MARGIN = 50 +TITLE_FONT_SIZE = 90 +TITLE_FONT_WEIGHT = FontWeight.MEDIUM +NEXT_BUTTON_WIDTH = 310 +BODY_FONT_SIZE = 80 +BUTTON_HEIGHT = 160 +BUTTON_SPACING = 50 + +OPENPILOT_URL = "https://openpilot.comma.ai" +USER_AGENT = f"AGNOSSetup-{HARDWARE.get_os_version()}" + +INSTALLER_DESTINATION_PATH = "/tmp/installer" +INSTALLER_URL_PATH = "/tmp/installer_url" + + +class SetupState(IntEnum): + LOW_VOLTAGE = 0 + GETTING_STARTED = 1 + NETWORK_SETUP = 2 + SOFTWARE_SELECTION = 3 + CUSTOM_SOFTWARE = 4 + DOWNLOADING = 5 + DOWNLOAD_FAILED = 6 + CUSTOM_SOFTWARE_WARNING = 7 + + +class Setup(Widget): + def __init__(self): + super().__init__() + self.state = SetupState.GETTING_STARTED + self.network_check_thread = None + self.network_connected = threading.Event() + self.wifi_connected = threading.Event() + self.stop_network_check_thread = threading.Event() + self.failed_url = "" + self.failed_reason = "" + self.download_url = "" + self.download_progress = 0 + self.download_thread = None + self.wifi_ui = WifiManagerUI(WifiManager()) + self.keyboard = Keyboard() + self.selected_radio = None + self.warning = gui_app.texture("icons/warning.png", 150, 150) + self.checkmark = gui_app.texture("icons/circled_check.png", 100, 100) + + self._low_voltage_title_label = Label("WARNING: Low Voltage", TITLE_FONT_SIZE, FontWeight.MEDIUM, rl.GuiTextAlignment.TEXT_ALIGN_LEFT, + text_color=rl.Color(255, 89, 79, 255), text_padding=20) + self._low_voltage_body_label = Label("Power your device in a car with a harness or proceed at your own risk.", BODY_FONT_SIZE, + text_alignment=rl.GuiTextAlignment.TEXT_ALIGN_LEFT, text_padding=20) + self._low_voltage_continue_button = Button("Continue", self._low_voltage_continue_button_callback) + self._low_voltage_poweroff_button = Button("Power Off", HARDWARE.shutdown) + + self._getting_started_button = Button("", self._getting_started_button_callback, button_style=ButtonStyle.PRIMARY, border_radius=0) + self._getting_started_title_label = Label("Getting Started", TITLE_FONT_SIZE, FontWeight.BOLD, rl.GuiTextAlignment.TEXT_ALIGN_LEFT, text_padding=20) + self._getting_started_body_label = Label("Before we get on the road, let's finish installation and cover some details.", + BODY_FONT_SIZE, text_alignment=rl.GuiTextAlignment.TEXT_ALIGN_LEFT, text_padding=20) + + self._software_selection_openpilot_button = ButtonRadio("openpilot", self.checkmark, font_size=BODY_FONT_SIZE, text_padding=80) + self._software_selection_custom_software_button = ButtonRadio("Custom Software", self.checkmark, font_size=BODY_FONT_SIZE, text_padding=80) + self._software_selection_continue_button = Button("Continue", self._software_selection_continue_button_callback, + button_style=ButtonStyle.PRIMARY) + self._software_selection_continue_button.set_enabled(False) + self._software_selection_back_button = Button("Back", self._software_selection_back_button_callback) + self._software_selection_title_label = Label("Choose Software to Use", TITLE_FONT_SIZE, FontWeight.BOLD, rl.GuiTextAlignment.TEXT_ALIGN_LEFT, + text_padding=20) + + self._download_failed_reboot_button = Button("Reboot device", HARDWARE.reboot) + self._download_failed_startover_button = Button("Start over", self._download_failed_startover_button_callback, button_style=ButtonStyle.PRIMARY) + self._download_failed_title_label = Label("Download Failed", TITLE_FONT_SIZE, FontWeight.BOLD, rl.GuiTextAlignment.TEXT_ALIGN_LEFT, text_padding=20) + self._download_failed_url_label = Label("", 52, FontWeight.NORMAL, rl.GuiTextAlignment.TEXT_ALIGN_LEFT, text_padding=20) + self._download_failed_body_label = Label("", BODY_FONT_SIZE, text_alignment=rl.GuiTextAlignment.TEXT_ALIGN_LEFT, text_padding=20) + + self._network_setup_back_button = Button("Back", self._network_setup_back_button_callback) + self._network_setup_continue_button = Button("Waiting for internet", self._network_setup_continue_button_callback, + button_style=ButtonStyle.PRIMARY) + self._network_setup_continue_button.set_enabled(False) + self._network_setup_title_label = Label("Connect to Wi-Fi", TITLE_FONT_SIZE, FontWeight.BOLD, rl.GuiTextAlignment.TEXT_ALIGN_LEFT, text_padding=20) + + self._custom_software_warning_continue_button = Button("Scroll to continue", self._custom_software_warning_continue_button_callback, + button_style=ButtonStyle.PRIMARY) + self._custom_software_warning_continue_button.set_enabled(False) + self._custom_software_warning_back_button = Button("Back", self._custom_software_warning_back_button_callback) + self._custom_software_warning_title_label = Label("WARNING: Custom Software", 81, FontWeight.BOLD, rl.GuiTextAlignment.TEXT_ALIGN_LEFT, + text_color=rl.Color(255, 89, 79, 255), + text_padding=60) + self._custom_software_warning_body_label = Label("Use caution when installing third-party software.\n\n" + + "⚠️ It has not been tested by comma.\n\n" + + "⚠️ It may not comply with relevant safety standards.\n\n" + + "⚠️ It may cause damage to your device and/or vehicle.\n\n" + + "If you'd like to proceed, use https://flash.comma.ai " + + "to restore your device to a factory state later.", + 68, text_alignment=rl.GuiTextAlignment.TEXT_ALIGN_LEFT, text_padding=60) + self._custom_software_warning_body_scroll_panel = GuiScrollPanel() + + self._downloading_body_label = Label("Downloading...", TITLE_FONT_SIZE, FontWeight.MEDIUM, text_padding=20) + + try: + with open("/sys/class/hwmon/hwmon1/in1_input") as f: + voltage = float(f.read().strip()) / 1000.0 + if voltage < 7: + self.state = SetupState.LOW_VOLTAGE + except (FileNotFoundError, ValueError): + self.state = SetupState.LOW_VOLTAGE + + def _render(self, rect: rl.Rectangle): + if self.state == SetupState.LOW_VOLTAGE: + self.render_low_voltage(rect) + elif self.state == SetupState.GETTING_STARTED: + self.render_getting_started(rect) + elif self.state == SetupState.NETWORK_SETUP: + self.render_network_setup(rect) + elif self.state == SetupState.SOFTWARE_SELECTION: + self.render_software_selection(rect) + elif self.state == SetupState.CUSTOM_SOFTWARE_WARNING: + self.render_custom_software_warning(rect) + elif self.state == SetupState.CUSTOM_SOFTWARE: + self.render_custom_software() + elif self.state == SetupState.DOWNLOADING: + self.render_downloading(rect) + elif self.state == SetupState.DOWNLOAD_FAILED: + self.render_download_failed(rect) + + def _low_voltage_continue_button_callback(self): + self.state = SetupState.GETTING_STARTED + + def _custom_software_warning_back_button_callback(self): + self.state = SetupState.SOFTWARE_SELECTION + + def _custom_software_warning_continue_button_callback(self): + self.state = SetupState.NETWORK_SETUP + self.stop_network_check_thread.clear() + self.start_network_check() + + def _getting_started_button_callback(self): + self.state = SetupState.SOFTWARE_SELECTION + + def _software_selection_back_button_callback(self): + self.state = SetupState.GETTING_STARTED + + def _software_selection_continue_button_callback(self): + if self._software_selection_openpilot_button.selected: + self.state = SetupState.NETWORK_SETUP + self.stop_network_check_thread.clear() + self.start_network_check() + else: + self.state = SetupState.CUSTOM_SOFTWARE_WARNING + + def _download_failed_startover_button_callback(self): + self.state = SetupState.GETTING_STARTED + + def _network_setup_back_button_callback(self): + self.state = SetupState.SOFTWARE_SELECTION + + def _network_setup_continue_button_callback(self): + self.stop_network_check_thread.set() + if self._software_selection_openpilot_button.selected: + self.download(OPENPILOT_URL) + else: + self.state = SetupState.CUSTOM_SOFTWARE + + def render_low_voltage(self, rect: rl.Rectangle): + rl.draw_texture_ex(self.warning, rl.Vector2(rect.x + 150, rect.y + 110), 0.0, 1.0, rl.WHITE) + + self._low_voltage_title_label.render(rl.Rectangle(rect.x + 150, rect.y + 110 + 150 + 100, rect.width - 500 - 150, TITLE_FONT_SIZE * FONT_SCALE)) + self._low_voltage_body_label.render(rl.Rectangle(rect.x + 150, rect.y + 110 + 150 + 150, rect.width - 500, BODY_FONT_SIZE * FONT_SCALE * 3)) + + button_width = (rect.width - MARGIN * 3) / 2 + button_y = rect.height - MARGIN - BUTTON_HEIGHT + self._low_voltage_poweroff_button.render(rl.Rectangle(rect.x + MARGIN, button_y, button_width, BUTTON_HEIGHT)) + self._low_voltage_continue_button.render(rl.Rectangle(rect.x + MARGIN * 2 + button_width, button_y, button_width, BUTTON_HEIGHT)) + + def render_getting_started(self, rect: rl.Rectangle): + self._getting_started_title_label.render(rl.Rectangle(rect.x + 165, rect.y + 280, rect.width - 265, TITLE_FONT_SIZE * FONT_SCALE)) + self._getting_started_body_label.render(rl.Rectangle(rect.x + 165, rect.y + 280 + TITLE_FONT_SIZE * FONT_SCALE, rect.width - 500, + BODY_FONT_SIZE * FONT_SCALE * 3)) + + btn_rect = rl.Rectangle(rect.width - NEXT_BUTTON_WIDTH, 0, NEXT_BUTTON_WIDTH, rect.height) + self._getting_started_button.render(btn_rect) + triangle = gui_app.texture("images/button_continue_triangle.png", 54, int(btn_rect.height)) + rl.draw_texture_v(triangle, rl.Vector2(btn_rect.x + btn_rect.width / 2 - triangle.width / 2, btn_rect.height / 2 - triangle.height / 2), rl.WHITE) + + def check_network_connectivity(self): + while not self.stop_network_check_thread.is_set(): + if self.state == SetupState.NETWORK_SETUP: + try: + urllib.request.urlopen(OPENPILOT_URL, timeout=2.0) + self.network_connected.set() + if HARDWARE.get_network_type() == NetworkType.wifi: + self.wifi_connected.set() + else: + self.wifi_connected.clear() + except Exception: + self.network_connected.clear() + time.sleep(1.0) + + def start_network_check(self): + if self.network_check_thread is None or not self.network_check_thread.is_alive(): + self.network_check_thread = threading.Thread(target=self.check_network_connectivity, daemon=True) + self.network_check_thread.start() + + def close(self): + if self.network_check_thread is not None: + self.stop_network_check_thread.set() + self.network_check_thread.join() + + def render_network_setup(self, rect: rl.Rectangle): + self._network_setup_title_label.render(rl.Rectangle(rect.x + MARGIN, rect.y + MARGIN, rect.width - MARGIN * 2, TITLE_FONT_SIZE * FONT_SCALE)) + + wifi_rect = rl.Rectangle(rect.x + MARGIN, rect.y + TITLE_FONT_SIZE * FONT_SCALE + MARGIN + 25, rect.width - MARGIN * 2, + rect.height - TITLE_FONT_SIZE * FONT_SCALE - 25 - BUTTON_HEIGHT - MARGIN * 3) + rl.draw_rectangle_rounded(wifi_rect, 0.05, 10, rl.Color(51, 51, 51, 255)) + wifi_content_rect = rl.Rectangle(wifi_rect.x + MARGIN, wifi_rect.y, wifi_rect.width - MARGIN * 2, wifi_rect.height) + self.wifi_ui.render(wifi_content_rect) + + button_width = (rect.width - BUTTON_SPACING - MARGIN * 2) / 2 + button_y = rect.height - BUTTON_HEIGHT - MARGIN + + self._network_setup_back_button.render(rl.Rectangle(rect.x + MARGIN, button_y, button_width, BUTTON_HEIGHT)) + + # Check network connectivity status + continue_enabled = self.network_connected.is_set() + self._network_setup_continue_button.set_enabled(continue_enabled) + continue_text = ("Continue" if self.wifi_connected.is_set() else "Continue without Wi-Fi") if continue_enabled else "Waiting for internet" + self._network_setup_continue_button.set_text(continue_text) + self._network_setup_continue_button.render(rl.Rectangle(rect.x + MARGIN + button_width + BUTTON_SPACING, button_y, button_width, BUTTON_HEIGHT)) + + def render_software_selection(self, rect: rl.Rectangle): + self._software_selection_title_label.render(rl.Rectangle(rect.x + MARGIN, rect.y + MARGIN, rect.width - MARGIN * 2, TITLE_FONT_SIZE * FONT_SCALE)) + + radio_height = 230 + radio_spacing = 30 + + self._software_selection_continue_button.set_enabled(False) + + openpilot_rect = rl.Rectangle(rect.x + MARGIN, rect.y + TITLE_FONT_SIZE * FONT_SCALE + MARGIN * 2, rect.width - MARGIN * 2, radio_height) + self._software_selection_openpilot_button.render(openpilot_rect) + + if self._software_selection_openpilot_button.selected: + self._software_selection_continue_button.set_enabled(True) + self._software_selection_custom_software_button.selected = False + + custom_rect = rl.Rectangle(rect.x + MARGIN, rect.y + TITLE_FONT_SIZE * FONT_SCALE + MARGIN * 2 + radio_height + radio_spacing, rect.width - MARGIN * 2, + radio_height) + self._software_selection_custom_software_button.render(custom_rect) + + if self._software_selection_custom_software_button.selected: + self._software_selection_continue_button.set_enabled(True) + self._software_selection_openpilot_button.selected = False + + button_width = (rect.width - BUTTON_SPACING - MARGIN * 2) / 2 + button_y = rect.height - BUTTON_HEIGHT - MARGIN + + self._software_selection_back_button.render(rl.Rectangle(rect.x + MARGIN, button_y, button_width, BUTTON_HEIGHT)) + self._software_selection_continue_button.render(rl.Rectangle(rect.x + MARGIN + button_width + BUTTON_SPACING, button_y, button_width, BUTTON_HEIGHT)) + + def render_downloading(self, rect: rl.Rectangle): + self._downloading_body_label.render(rl.Rectangle(rect.x, rect.y + rect.height / 2 - TITLE_FONT_SIZE * FONT_SCALE / 2, rect.width, + TITLE_FONT_SIZE * FONT_SCALE)) + + def render_download_failed(self, rect: rl.Rectangle): + self._download_failed_title_label.render(rl.Rectangle(rect.x + 117, rect.y + 185, rect.width - 117, TITLE_FONT_SIZE * FONT_SCALE)) + self._download_failed_url_label.set_text(self.failed_url) + self._download_failed_url_label.render(rl.Rectangle(rect.x + 117, rect.y + 185 + TITLE_FONT_SIZE * FONT_SCALE + 67, rect.width - 117 - 100, 64)) + + self._download_failed_body_label.set_text(self.failed_reason) + self._download_failed_body_label.render(rl.Rectangle(rect.x + 117, rect.y, rect.width - 117 - 100, rect.height)) + + button_width = (rect.width - BUTTON_SPACING - MARGIN * 2) / 2 + button_y = rect.height - BUTTON_HEIGHT - MARGIN + self._download_failed_reboot_button.render(rl.Rectangle(rect.x + MARGIN, button_y, button_width, BUTTON_HEIGHT)) + self._download_failed_startover_button.render(rl.Rectangle(rect.x + MARGIN + button_width + BUTTON_SPACING, button_y, button_width, BUTTON_HEIGHT)) + + def render_custom_software_warning(self, rect: rl.Rectangle): + warn_rect = rl.Rectangle(rect.x, rect.y, rect.width, 1500) + offset = self._custom_software_warning_body_scroll_panel.update(rect, warn_rect) + + button_width = (rect.width - MARGIN * 3) / 2 + button_y = rect.height - MARGIN - BUTTON_HEIGHT + + rl.begin_scissor_mode(int(rect.x), int(rect.y), int(rect.width), int(button_y - BODY_FONT_SIZE * FONT_SCALE)) + y_offset = rect.y + offset + self._custom_software_warning_title_label.render(rl.Rectangle(rect.x + 50, y_offset + 150, rect.width - 265, TITLE_FONT_SIZE * FONT_SCALE)) + self._custom_software_warning_body_label.render(rl.Rectangle(rect.x + 50, y_offset + 400, rect.width - 50, BODY_FONT_SIZE * FONT_SCALE * 3)) + rl.end_scissor_mode() + + self._custom_software_warning_back_button.render(rl.Rectangle(rect.x + MARGIN, button_y, button_width, BUTTON_HEIGHT)) + self._custom_software_warning_continue_button.render(rl.Rectangle(rect.x + MARGIN * 2 + button_width, button_y, button_width, BUTTON_HEIGHT)) + if offset < (rect.height - warn_rect.height): + self._custom_software_warning_continue_button.set_enabled(True) + self._custom_software_warning_continue_button.set_text("Continue") + + def render_custom_software(self): + def handle_keyboard_result(result): + # Enter pressed + if result == DialogResult.CONFIRM: + url = self.keyboard.text + self.keyboard.clear() + if url: + self.download(url) + + # Cancel pressed + elif result == DialogResult.CANCEL: + self.state = SetupState.SOFTWARE_SELECTION + + self.keyboard.reset(min_text_size=1) + self.keyboard.set_title("Enter URL", "for Custom Software") + self.keyboard.set_callback(handle_keyboard_result) + gui_app.push_widget(self.keyboard) + + def download(self, url: str): + # autocomplete incomplete URLs + if re.match("^([^/.]+)/([^/]+)$", url): + url = f"https://installer.comma.ai/{url}" + + parsed = urlparse(url, scheme='https') + self.download_url = (urlparse(f"https://{url}") if not parsed.netloc else parsed).geturl() + + self.state = SetupState.DOWNLOADING + + self.download_thread = threading.Thread(target=self._download_thread, daemon=True) + self.download_thread.start() + + def _download_thread(self): + try: + import tempfile + + fd, tmpfile = tempfile.mkstemp(prefix="installer_") + + headers = {"User-Agent": USER_AGENT, + "X-openpilot-serial": HARDWARE.get_serial(), + "X-openpilot-device-type": HARDWARE.get_device_type()} + req = urllib.request.Request(self.download_url, headers=headers) + + with open(tmpfile, 'wb') as f, urllib.request.urlopen(req, timeout=30) as response: + total_size = int(response.headers.get('content-length', 0)) + downloaded = 0 + block_size = 8192 + + while True: + buffer = response.read(block_size) + if not buffer: + break + + downloaded += len(buffer) + f.write(buffer) + + if total_size: + self.download_progress = int(downloaded * 100 / total_size) + + is_elf = False + with open(tmpfile, 'rb') as f: + header = f.read(4) + is_elf = header == b'\x7fELF' + + if not is_elf: + self.download_failed(self.download_url, "No custom software found at this URL.") + return + + # AGNOS might try to execute the installer before this process exits. + # Therefore, important to close the fd before renaming the installer. + os.close(fd) + os.rename(tmpfile, INSTALLER_DESTINATION_PATH) + + with open(INSTALLER_URL_PATH, "w") as f: + f.write(self.download_url) + + # give time for installer UI to take over + time.sleep(0.1) + gui_app.request_close() + + except urllib.error.HTTPError as e: + if e.code == 409: + error_msg = e.read().decode("utf-8") + self.download_failed(self.download_url, error_msg) + except Exception: + error_msg = "Ensure the entered URL is valid, and the device's internet connection is good." + self.download_failed(self.download_url, error_msg) + + def download_failed(self, url: str, reason: str): + self.failed_url = url + self.failed_reason = reason + self.state = SetupState.DOWNLOAD_FAILED + + +def main(): + try: + gui_app.init_window("Setup", 20) + setup = Setup() + gui_app.push_widget(setup) + for _ in gui_app.render(): + pass + setup.close() + except Exception as e: + print(f"Setup error: {e}") + finally: + gui_app.close() + + +if __name__ == "__main__": + main() diff --git a/openpilot/system/ui/tici_updater.py b/openpilot/system/ui/tici_updater.py new file mode 100755 index 0000000000..27cf6579a8 --- /dev/null +++ b/openpilot/system/ui/tici_updater.py @@ -0,0 +1,178 @@ +#!/usr/bin/env python3 +import sys +import subprocess +import threading +import pyray as rl +from enum import IntEnum + +from openpilot.common.hardware import HARDWARE +from openpilot.system.ui.lib.application import gui_app, FontWeight, FONT_SCALE +from openpilot.system.ui.lib.wifi_manager import WifiManager +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.button import Button, ButtonStyle +from openpilot.system.ui.widgets.label import gui_text_box, gui_label +from openpilot.system.ui.widgets.network import WifiManagerUI + +# Constants +MARGIN = 50 +BUTTON_HEIGHT = 160 +BUTTON_WIDTH = 400 +PROGRESS_BAR_HEIGHT = 72 +TITLE_FONT_SIZE = 80 +BODY_FONT_SIZE = 65 +BACKGROUND_COLOR = rl.BLACK +PROGRESS_BG_COLOR = rl.Color(41, 41, 41, 255) +PROGRESS_COLOR = rl.Color(54, 77, 239, 255) + + +class Screen(IntEnum): + PROMPT = 0 + WIFI = 1 + PROGRESS = 2 + + +class Updater(Widget): + def __init__(self, updater_path, manifest_path): + super().__init__() + self.updater = updater_path + self.manifest = manifest_path + self.current_screen = Screen.PROMPT + + self.progress_value = 0 + self.progress_text = "Loading..." + self.show_reboot_button = False + self.process = None + self.update_thread = None + self.wifi_manager_ui = WifiManagerUI(WifiManager()) + + # Buttons + self._wifi_button = Button("Connect to Wi-Fi", click_callback=lambda: self.set_current_screen(Screen.WIFI)) + self._install_button = Button("Install", click_callback=self.install_update, button_style=ButtonStyle.PRIMARY) + self._back_button = Button("Back", click_callback=lambda: self.set_current_screen(Screen.PROMPT)) + self._reboot_button = Button("Reboot", click_callback=lambda: HARDWARE.reboot()) + + def set_current_screen(self, screen: Screen): + self.current_screen = screen + + def install_update(self): + self.set_current_screen(Screen.PROGRESS) + self.progress_value = 0 + self.progress_text = "Downloading..." + self.show_reboot_button = False + + # Start the update process in a separate thread + self.update_thread = threading.Thread(target=self._run_update_process) + self.update_thread.daemon = True + self.update_thread.start() + + def _run_update_process(self): + # TODO: just import it and run in a thread without a subprocess + try: + cmd = [self.updater, "--swap", self.manifest] + self.process = subprocess.Popen(cmd, stdout=subprocess.PIPE, + text=True, bufsize=1, universal_newlines=True) + except Exception: + self.progress_text = "Update failed" + self.show_reboot_button = True + return + + if self.process.stdout is not None: + for line in self.process.stdout: + parts = line.strip().split(":") + if len(parts) == 2: + self.progress_text = parts[0] + try: + self.progress_value = int(float(parts[1])) + except ValueError: + pass + + exit_code = self.process.wait() + if exit_code == 0: + HARDWARE.reboot() + else: + self.progress_text = "Update failed" + self.show_reboot_button = True + + def render_prompt_screen(self, rect: rl.Rectangle): + # Title + title_rect = rl.Rectangle(MARGIN + 50, 250, rect.width - MARGIN * 2 - 100, TITLE_FONT_SIZE * FONT_SCALE) + gui_label(title_rect, "Update Required", TITLE_FONT_SIZE, font_weight=FontWeight.BOLD) + + # Description + desc_text = ("An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. " + + "The download size is approximately 1GB.") + + desc_rect = rl.Rectangle(MARGIN + 50, 250 + TITLE_FONT_SIZE * FONT_SCALE + 75, rect.width - MARGIN * 2 - 100, BODY_FONT_SIZE * FONT_SCALE * 4) + gui_text_box(desc_rect, desc_text, BODY_FONT_SIZE) + + # Buttons at the bottom + button_y = rect.height - MARGIN - BUTTON_HEIGHT + button_width = (rect.width - MARGIN * 3) // 2 + + # WiFi button + wifi_button_rect = rl.Rectangle(MARGIN, button_y, button_width, BUTTON_HEIGHT) + self._wifi_button.render(wifi_button_rect) + + # Install button + install_button_rect = rl.Rectangle(MARGIN * 2 + button_width, button_y, button_width, BUTTON_HEIGHT) + self._install_button.render(install_button_rect) + + def render_wifi_screen(self, rect: rl.Rectangle): + # Draw the Wi-Fi manager UI + wifi_rect = rl.Rectangle(rect.x + MARGIN, rect.y + MARGIN, rect.width - MARGIN * 2, + rect.height - BUTTON_HEIGHT - MARGIN * 3) + rl.draw_rectangle_rounded(wifi_rect, 0.035, 10, rl.Color(51, 51, 51, 255)) + wifi_content_rect = rl.Rectangle(wifi_rect.x + 50, wifi_rect.y, wifi_rect.width - 100, wifi_rect.height) + self.wifi_manager_ui.render(wifi_content_rect) + + back_button_rect = rl.Rectangle(MARGIN, rect.height - MARGIN - BUTTON_HEIGHT, BUTTON_WIDTH, BUTTON_HEIGHT) + self._back_button.render(back_button_rect) + + def render_progress_screen(self, rect: rl.Rectangle): + title_rect = rl.Rectangle(MARGIN + 100, 330, rect.width - MARGIN * 2 - 200, 100) + gui_label(title_rect, self.progress_text, 90, font_weight=FontWeight.SEMI_BOLD) + + # Progress bar + bar_rect = rl.Rectangle(MARGIN + 100, 330 + 100 + 100, rect.width - MARGIN * 2 - 200, PROGRESS_BAR_HEIGHT) + rl.draw_rectangle_rounded(bar_rect, 0.5, 10, PROGRESS_BG_COLOR) + + # Calculate the width of the progress chunk + progress_width = (bar_rect.width * self.progress_value) / 100 + if progress_width > 0: + progress_rect = rl.Rectangle(bar_rect.x, bar_rect.y, progress_width, bar_rect.height) + rl.draw_rectangle_rounded(progress_rect, 0.5, 10, PROGRESS_COLOR) + + # Show reboot button if needed + if self.show_reboot_button: + reboot_rect = rl.Rectangle(MARGIN + 100, rect.height - MARGIN - BUTTON_HEIGHT, BUTTON_WIDTH, BUTTON_HEIGHT) + self._reboot_button.render(reboot_rect) + + def _render(self, rect: rl.Rectangle): + if self.current_screen == Screen.PROMPT: + self.render_prompt_screen(rect) + elif self.current_screen == Screen.WIFI: + self.render_wifi_screen(rect) + elif self.current_screen == Screen.PROGRESS: + self.render_progress_screen(rect) + + +def main(): + if len(sys.argv) < 3: + print("Usage: updater.py ") + sys.exit(1) + + updater_path = sys.argv[1] + manifest_path = sys.argv[2] + + try: + gui_app.init_window("System Update") + gui_app.push_widget(Updater(updater_path, manifest_path)) + for _ in gui_app.render(): + pass + finally: + # Make sure we clean up even if there's an error + gui_app.close() + + +if __name__ == "__main__": + main() diff --git a/openpilot/system/ui/updater.py b/openpilot/system/ui/updater.py new file mode 100755 index 0000000000..42d12d9090 --- /dev/null +++ b/openpilot/system/ui/updater.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python3 +from openpilot.system.ui.lib.application import gui_app +import openpilot.system.ui.tici_updater as tici_updater +import openpilot.system.ui.mici_updater as mici_updater + + +def main(): + if gui_app.big_ui(): + tici_updater.main() + else: + mici_updater.main() + + +if __name__ == "__main__": + main() diff --git a/openpilot/system/ui/widgets/__init__.py b/openpilot/system/ui/widgets/__init__.py new file mode 100644 index 0000000000..f8cb04d8a7 --- /dev/null +++ b/openpilot/system/ui/widgets/__init__.py @@ -0,0 +1,253 @@ +from __future__ import annotations + +import abc +import pyray as rl +from enum import IntEnum +from typing import Protocol, TypeVar +from collections.abc import Callable +from openpilot.system.ui.lib.application import gui_app, MousePos, MAX_TOUCH_SLOTS, MouseEvent + +class DeviceLike(Protocol): + awake: bool + + +def _get_device() -> DeviceLike: + try: + from openpilot.selfdrive.ui.ui_state import device + return device + except ImportError: + class Device: + awake = True + return Device() + + +device = _get_device() + +W = TypeVar('W', bound='Widget') + +DEBUG = False + + +class DialogResult(IntEnum): + CANCEL = 0 + CONFIRM = 1 + NO_ACTION = -1 + + +class Widget(abc.ABC): + def __init__(self): + self._rect: rl.Rectangle = rl.Rectangle(0, 0, 0, 0) + self._parent_rect: rl.Rectangle | None = None + self._children: list[Widget] = [] + + self._enabled: bool | Callable[[], bool] = True + self._is_visible: bool | Callable[[], bool] = True + + self.__is_pressed = [False] * MAX_TOUCH_SLOTS + # if current mouse/touch down started within the widget's rectangle + self.__tracking_is_pressed = [False] * MAX_TOUCH_SLOTS + self._touch_valid_callback: Callable[[], bool] | None = None + self._click_delay: float | None = None # seconds to hold is_pressed after release + self._click_release_time: float | None = None + self._click_callback: Callable[[], None] | None = None + self._multi_touch = False + self.__was_awake = True + + @property + def rect(self) -> rl.Rectangle: + return self._rect + + def set_rect(self, rect: rl.Rectangle) -> None: + changed = (self._rect.x != rect.x or self._rect.y != rect.y or + self._rect.width != rect.width or self._rect.height != rect.height) + self._rect = rect + if changed: + self._update_layout_rects() + + def set_parent_rect(self, parent_rect: rl.Rectangle) -> None: + """Can be used like size hint in QT""" + self._parent_rect = parent_rect + + @property + def is_pressed(self) -> bool: + # if actually pressed or holding after release + return any(self.__is_pressed) or self._click_release_time is not None + + @property + def enabled(self) -> bool: + return self._enabled() if callable(self._enabled) else self._enabled + + def set_enabled(self, enabled: bool | Callable[[], bool]) -> None: + self._enabled = enabled + + @property + def is_visible(self) -> bool: + return self._is_visible() if callable(self._is_visible) else self._is_visible + + def set_visible(self, visible: bool | Callable[[], bool]) -> None: + self._is_visible = visible + + def set_click_callback(self, click_callback: Callable[[], None] | None) -> None: + """Set a callback to be called when the widget is clicked.""" + self._click_callback = click_callback + + def set_touch_valid_callback(self, touch_callback: Callable[[], bool]) -> None: + """Set a callback to determine if the widget can be clicked.""" + self._touch_valid_callback = touch_callback + + def _touch_valid(self) -> bool: + """Check if the widget can be touched.""" + return self._touch_valid_callback() if self._touch_valid_callback else True + + def set_position(self, x: float, y: float) -> None: + changed = (self._rect.x != x or self._rect.y != y) + self._rect = rl.Rectangle(x, y, self._rect.width, self._rect.height) + if changed: + self._update_layout_rects() + + @property + def _hit_rect(self) -> rl.Rectangle: + # restrict touches to within parent rect if set, useful inside Scroller + if self._parent_rect is None: + return self._rect + return rl.get_collision_rec(self._rect, self._parent_rect) + + def render(self, rect: rl.Rectangle | None = None) -> bool | int | None: + if rect is not None: + self.set_rect(rect) + + self._update_state() + + if self._click_release_time is not None and rl.get_time() >= self._click_release_time: + self._click_release_time = None + + if not self.is_visible: + return None + + self._layout() + ret = self._render(self._rect) + + if gui_app.show_touches: + self._draw_debug_rect() + + # Keep track of whether mouse down started within the widget's rectangle + if self.enabled and self.__was_awake: + self._process_mouse_events() + else: + # TODO: ideally we emit release events when going disabled + self.__is_pressed = [False] * MAX_TOUCH_SLOTS + self.__tracking_is_pressed = [False] * MAX_TOUCH_SLOTS + + self.__was_awake = device.awake + + return ret + + def _draw_debug_rect(self) -> None: + rl.draw_rectangle_lines(int(self._rect.x), int(self._rect.y), + max(int(self._rect.width), 1), max(int(self._rect.height), 1), rl.RED) + + def _process_mouse_events(self) -> None: + hit_rect = self._hit_rect + touch_valid = self._touch_valid() + + for mouse_event in gui_app.mouse_events: + if not self._multi_touch and mouse_event.slot != 0: + continue + + mouse_in_rect = rl.check_collision_point_rec(mouse_event.pos, hit_rect) + # Ignores touches/presses that start outside our rect + # Allows touch to leave the rect and come back in focus if mouse did not release + if mouse_event.left_pressed and touch_valid: + if mouse_in_rect: + self._handle_mouse_press(mouse_event.pos) + self.__is_pressed[mouse_event.slot] = True + self.__tracking_is_pressed[mouse_event.slot] = True + self._handle_mouse_event(mouse_event) + + # Callback such as scroll panel signifies user is scrolling + elif not touch_valid: + self.__is_pressed[mouse_event.slot] = False + self.__tracking_is_pressed[mouse_event.slot] = False + + elif mouse_event.left_released: + self._handle_mouse_event(mouse_event) + if self.__is_pressed[mouse_event.slot] and mouse_in_rect: + self._handle_mouse_release(mouse_event.pos) + self.__is_pressed[mouse_event.slot] = False + self.__tracking_is_pressed[mouse_event.slot] = False + + # Mouse/touch is still within our rect + elif mouse_in_rect: + if self.__tracking_is_pressed[mouse_event.slot]: + self.__is_pressed[mouse_event.slot] = True + self._handle_mouse_event(mouse_event) + + # Mouse/touch left our rect but may come back into focus later + elif not mouse_in_rect: + self.__is_pressed[mouse_event.slot] = False + self._handle_mouse_event(mouse_event) + + def _layout(self) -> None: + """Optionally lay out child widgets separately. This is called before rendering.""" + + def _update_state(self): + """Optionally update the widget's non-layout state. This is called before rendering.""" + + @abc.abstractmethod + def _render(self, rect: rl.Rectangle, /) -> bool | int | None: + """Render the widget within the given rectangle.""" + + def _update_layout_rects(self) -> None: + """Optionally update any layout rects on Widget rect change.""" + + def _handle_mouse_press(self, mouse_pos: MousePos, /) -> None: + """Optionally handle mouse press events.""" + + def _handle_mouse_release(self, mouse_pos: MousePos, /) -> None: + """Optionally handle mouse release events.""" + if self._click_delay is not None: + self._click_release_time = rl.get_time() + self._click_delay + if self._click_callback: + self._click_callback() + + def _handle_mouse_event(self, mouse_event: MouseEvent) -> None: + """Optionally handle mouse events. This is called before rendering.""" + # Default implementation does nothing, can be overridden by subclasses + + def _child(self, widget: W) -> W: + """ + Register a widget as a child. Lifecycle events (show/hide) propagate to registered children. + - If the widget is pushed onto the nav stack, do NOT register it (gui_app manages its lifecycle). + - If the widget is rendered inline in _render(), register it. + """ + assert widget not in self._children, f"{type(widget).__name__} already a child of {type(self).__name__}" + self._children.append(widget) + return widget + + _show_hide_depth = 0 + + def show_event(self): + """Called when widget becomes visible. Propagates to registered children.""" + if DEBUG: + print(f"{' ' * Widget._show_hide_depth}show_event: {type(self).__name__}") + Widget._show_hide_depth += 1 + for child in self._children: + child.show_event() + if DEBUG: + Widget._show_hide_depth -= 1 + + def hide_event(self): + """Called when widget is hidden. Propagates to registered children.""" + if DEBUG: + print(f"{' ' * Widget._show_hide_depth}hide_event: {type(self).__name__}") + Widget._show_hide_depth += 1 + for child in self._children: + child.hide_event() + if DEBUG: + Widget._show_hide_depth -= 1 + + def dismiss(self, callback: Callable[[], None] | None = None): + """Immediately dismiss the widget, firing the callback after.""" + gui_app.pop_widget() + if callback: + callback() diff --git a/openpilot/system/ui/widgets/button.py b/openpilot/system/ui/widgets/button.py new file mode 100644 index 0000000000..36ef3bedab --- /dev/null +++ b/openpilot/system/ui/widgets/button.py @@ -0,0 +1,225 @@ +from collections.abc import Callable +from enum import IntEnum + +import pyray as rl + +from openpilot.system.ui.lib.application import gui_app, FontWeight, MousePos +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.label import Label +from openpilot.common.filter_simple import FirstOrderFilter + + +class ButtonStyle(IntEnum): + NORMAL = 0 # Most common, neutral buttons + PRIMARY = 1 # For main actions + DANGER = 2 # For critical actions, like reboot or delete + TRANSPARENT = 3 # For buttons with transparent background and border + TRANSPARENT_WHITE_TEXT = 9 # For buttons with transparent background and border and white text + TRANSPARENT_WHITE_BORDER = 10 # For buttons with transparent background and white border and text + ACTION = 4 + LIST_ACTION = 5 # For list items with action buttons + NO_EFFECT = 6 + KEYBOARD = 7 + FORGET_WIFI = 8 + + +ICON_PADDING = 15 +DEFAULT_BUTTON_FONT_SIZE = 60 +ACTION_BUTTON_FONT_SIZE = 48 + +BUTTON_TEXT_COLOR = { + ButtonStyle.NORMAL: rl.Color(228, 228, 228, 255), + ButtonStyle.PRIMARY: rl.Color(228, 228, 228, 255), + ButtonStyle.DANGER: rl.Color(228, 228, 228, 255), + ButtonStyle.TRANSPARENT: rl.BLACK, + ButtonStyle.TRANSPARENT_WHITE_TEXT: rl.WHITE, + ButtonStyle.TRANSPARENT_WHITE_BORDER: rl.Color(228, 228, 228, 255), + ButtonStyle.ACTION: rl.BLACK, + ButtonStyle.LIST_ACTION: rl.Color(228, 228, 228, 255), + ButtonStyle.NO_EFFECT: rl.Color(228, 228, 228, 255), + ButtonStyle.KEYBOARD: rl.Color(221, 221, 221, 255), + ButtonStyle.FORGET_WIFI: rl.Color(51, 51, 51, 255), +} + +BUTTON_DISABLED_TEXT_COLORS = { + ButtonStyle.TRANSPARENT_WHITE_TEXT: rl.WHITE, +} + +BUTTON_BACKGROUND_COLORS = { + ButtonStyle.NORMAL: rl.Color(51, 51, 51, 255), + ButtonStyle.PRIMARY: rl.Color(70, 91, 234, 255), + ButtonStyle.DANGER: rl.Color(226, 44, 44, 255), + ButtonStyle.TRANSPARENT: rl.BLACK, + ButtonStyle.TRANSPARENT_WHITE_TEXT: rl.BLANK, + ButtonStyle.TRANSPARENT_WHITE_BORDER: rl.BLACK, + ButtonStyle.ACTION: rl.Color(189, 189, 189, 255), + ButtonStyle.LIST_ACTION: rl.Color(57, 57, 57, 255), + ButtonStyle.NO_EFFECT: rl.Color(51, 51, 51, 255), + ButtonStyle.KEYBOARD: rl.Color(68, 68, 68, 255), + ButtonStyle.FORGET_WIFI: rl.Color(189, 189, 189, 255), +} + +BUTTON_PRESSED_BACKGROUND_COLORS = { + ButtonStyle.NORMAL: rl.Color(74, 74, 74, 255), + ButtonStyle.PRIMARY: rl.Color(48, 73, 244, 255), + ButtonStyle.DANGER: rl.Color(255, 36, 36, 255), + ButtonStyle.TRANSPARENT: rl.BLACK, + ButtonStyle.TRANSPARENT_WHITE_TEXT: rl.BLANK, + ButtonStyle.TRANSPARENT_WHITE_BORDER: rl.BLANK, + ButtonStyle.ACTION: rl.Color(130, 130, 130, 255), + ButtonStyle.LIST_ACTION: rl.Color(74, 74, 74, 74), + ButtonStyle.NO_EFFECT: rl.Color(51, 51, 51, 255), + ButtonStyle.KEYBOARD: rl.Color(51, 51, 51, 255), + ButtonStyle.FORGET_WIFI: rl.Color(130, 130, 130, 255), +} + +BUTTON_DISABLED_BACKGROUND_COLORS = { + ButtonStyle.TRANSPARENT_WHITE_TEXT: rl.BLANK, +} + + +class Button(Widget): + def __init__(self, + text: str | Callable[[], str], + click_callback: Callable[[], None] | None = None, + font_size: int = DEFAULT_BUTTON_FONT_SIZE, + font_weight: FontWeight = FontWeight.MEDIUM, + button_style: ButtonStyle = ButtonStyle.NORMAL, + border_radius: int = 10, + text_alignment: int = rl.GuiTextAlignment.TEXT_ALIGN_CENTER, + text_padding: int = 20, + icon=None, + elide_right: bool = False, + multi_touch: bool = False, + ): + + super().__init__() + self._button_style = button_style + self._border_radius = border_radius + self._background_color = BUTTON_BACKGROUND_COLORS[self._button_style] + + self._label = Label(text, font_size, font_weight, text_alignment, text_padding=text_padding, + text_color=BUTTON_TEXT_COLOR[self._button_style], icon=icon, elide_right=elide_right) + + self._click_callback = click_callback + self._multi_touch = multi_touch + + def set_text(self, text): + self._label.set_text(text) + + def set_button_style(self, button_style: ButtonStyle): + self._button_style = button_style + self._background_color = BUTTON_BACKGROUND_COLORS[self._button_style] + self._label.set_text_color(BUTTON_TEXT_COLOR[self._button_style]) + + def _update_state(self): + if self.enabled: + self._label.set_text_color(BUTTON_TEXT_COLOR[self._button_style]) + if self.is_pressed: + self._background_color = BUTTON_PRESSED_BACKGROUND_COLORS[self._button_style] + else: + self._background_color = BUTTON_BACKGROUND_COLORS[self._button_style] + elif self._button_style != ButtonStyle.NO_EFFECT: + self._background_color = BUTTON_DISABLED_BACKGROUND_COLORS.get(self._button_style, rl.Color(51, 51, 51, 255)) + self._label.set_text_color(BUTTON_DISABLED_TEXT_COLORS.get(self._button_style, rl.Color(228, 228, 228, 51))) + + def _render(self, _): + roundness = self._border_radius / (min(self._rect.width, self._rect.height) / 2) + if self._button_style == ButtonStyle.TRANSPARENT_WHITE_BORDER: + rl.draw_rectangle_rounded(self._rect, roundness, 10, rl.BLACK) + rl.draw_rectangle_rounded_lines_ex(self._rect, roundness, 10, 2, rl.WHITE) + else: + rl.draw_rectangle_rounded(self._rect, roundness, 10, self._background_color) + self._label.render(self._rect) + + +class ButtonRadio(Button): + def __init__(self, + text: str, + icon, + click_callback: Callable[[], None] | None = None, + font_size: int = DEFAULT_BUTTON_FONT_SIZE, + text_alignment: int = rl.GuiTextAlignment.TEXT_ALIGN_LEFT, + border_radius: int = 10, + text_padding: int = 20, + ): + + super().__init__(text, click_callback=click_callback, font_size=font_size, + border_radius=border_radius, text_padding=text_padding, + text_alignment=text_alignment) + self._text_padding = text_padding + self._icon = icon + self.selected = False + + def _handle_mouse_release(self, mouse_pos: MousePos): + super()._handle_mouse_release(mouse_pos) + self.selected = not self.selected + + def _update_state(self): + if self.selected: + self._background_color = BUTTON_BACKGROUND_COLORS[ButtonStyle.PRIMARY] + else: + self._background_color = BUTTON_BACKGROUND_COLORS[ButtonStyle.NORMAL] + + def _render(self, _): + roundness = self._border_radius / (min(self._rect.width, self._rect.height) / 2) + rl.draw_rectangle_rounded(self._rect, roundness, 10, self._background_color) + self._label.render(self._rect) + + if self._icon and self.selected: + icon_y = self._rect.y + (self._rect.height - self._icon.height) / 2 + icon_x = self._rect.x + self._rect.width - self._icon.width - self._text_padding - ICON_PADDING + rl.draw_texture_v(self._icon, rl.Vector2(icon_x, icon_y), rl.WHITE if self.enabled else rl.Color(255, 255, 255, 100)) + + +class IconButton(Widget): + def __init__(self, texture: rl.Texture): + super().__init__() + self._texture = texture + self._opacity_filter = FirstOrderFilter(1.0, 0.1, 1 / gui_app.target_fps) + self.set_rect(rl.Rectangle(0, 0, self._texture.width, self._texture.height)) + + def set_opacity(self, opacity: float, smooth: bool = False): + if smooth: + self._opacity_filter.update(opacity) + else: + self._opacity_filter.x = opacity + + def _render(self, rect: rl.Rectangle): + color = rl.Color(180, 180, 180, int(150 * self._opacity_filter.x)) if self.is_pressed else rl.WHITE + if not self.enabled: + color = rl.Color(255, 255, 255, int(255 * 0.9 * 0.35 * self._opacity_filter.x)) + draw_x = rect.x + (rect.width - self._texture.width) / 2 + draw_y = rect.y + (rect.height - self._texture.height) / 2 + rl.draw_texture_ex(self._texture, rl.Vector2(draw_x, draw_y), 0.0, 1.0, color) + + +class SmallCircleIconButton(Widget): + def __init__(self, icon_txt: rl.Texture): + super().__init__() + self.set_rect(rl.Rectangle(0, 0, 100, 100)) + self._opacity_filter = FirstOrderFilter(1.0, 0.1, 1 / gui_app.target_fps) + self._icon_bg_txt = gui_app.texture("icons_mici/setup/small_button.png", 100, 100) + self._icon_bg_pressed_txt = gui_app.texture("icons_mici/setup/small_button_pressed.png", 100, 100) + self._icon_bg_disabled_txt = gui_app.texture("icons_mici/setup/small_button_disabled.png", 100, 100) + self._icon_txt = icon_txt + + def set_opacity(self, opacity: float, smooth: bool = False): + if smooth: + self._opacity_filter.update(opacity) + else: + self._opacity_filter.x = opacity + + def _render(self, _): + white = rl.Color(255, 255, 255, int(255 * self._opacity_filter.x)) + if not self.enabled: + bg_txt = self._icon_bg_disabled_txt + icon_white = rl.Color(255, 255, 255, int(white.a * 0.35)) + else: + bg_txt = self._icon_bg_pressed_txt if self.is_pressed else self._icon_bg_txt + icon_white = white + + rl.draw_texture_ex(bg_txt, rl.Vector2(self.rect.x, self.rect.y), 0.0, 1.0, white) + icon_x = self.rect.x + (self.rect.width - self._icon_txt.width) / 2 + icon_y = self.rect.y + (self.rect.height - self._icon_txt.height) / 2 + rl.draw_texture_ex(self._icon_txt, rl.Vector2(icon_x, icon_y), 0.0, 1.0, icon_white) diff --git a/openpilot/system/ui/widgets/confirm_dialog.py b/openpilot/system/ui/widgets/confirm_dialog.py new file mode 100644 index 0000000000..3544836761 --- /dev/null +++ b/openpilot/system/ui/widgets/confirm_dialog.py @@ -0,0 +1,94 @@ +import pyray as rl +from collections.abc import Callable +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.widgets import DialogResult +from openpilot.system.ui.widgets.button import ButtonStyle, Button +from openpilot.system.ui.widgets.label import Label +from openpilot.system.ui.widgets.html_render import HtmlRenderer, ElementType +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.scroller_tici import Scroller + +OUTER_MARGIN = 200 +RICH_OUTER_MARGIN = 100 +BUTTON_HEIGHT = 160 +MARGIN = 50 +TEXT_PADDING = 10 +BACKGROUND_COLOR = rl.Color(27, 27, 27, 255) + + +class ConfirmDialog(Widget): + def __init__(self, text: str, confirm_text: str, cancel_text: str | None = None, rich: bool = False, callback: Callable[[DialogResult], None] | None = None): + super().__init__() + if cancel_text is None: + cancel_text = tr("Cancel") + self._label = Label(text, 70, FontWeight.BOLD, text_color=rl.Color(201, 201, 201, 255)) + self._html_renderer = HtmlRenderer(text=text, text_size={ElementType.P: 50}, center_text=True) + self._cancel_button = Button(cancel_text, self._cancel_button_callback) + self._confirm_button = Button(confirm_text, self._confirm_button_callback, button_style=ButtonStyle.PRIMARY) + self._rich = rich + self._callback = callback + self._cancel_text = cancel_text + self._scroller = Scroller([self._html_renderer], line_separator=False, spacing=0) + + def set_text(self, text): + if not self._rich: + self._label.set_text(text) + else: + self._html_renderer.parse_html_content(text) + + def _cancel_button_callback(self): + gui_app.pop_widget() + if self._callback: + self._callback(DialogResult.CANCEL) + + def _confirm_button_callback(self): + gui_app.pop_widget() + if self._callback: + self._callback(DialogResult.CONFIRM) + + def _render(self, rect: rl.Rectangle): + dialog_x = OUTER_MARGIN if not self._rich else RICH_OUTER_MARGIN + dialog_y = OUTER_MARGIN if not self._rich else RICH_OUTER_MARGIN + dialog_width = gui_app.width - 2 * dialog_x + dialog_height = gui_app.height - 2 * dialog_y + dialog_rect = rl.Rectangle(dialog_x, dialog_y, dialog_width, dialog_height) + + bottom = dialog_rect.y + dialog_rect.height + button_width = (dialog_rect.width - 3 * MARGIN) // 2 + cancel_button_x = dialog_rect.x + MARGIN + confirm_button_x = dialog_rect.x + dialog_rect.width - button_width - MARGIN + button_y = bottom - BUTTON_HEIGHT - MARGIN + cancel_button = rl.Rectangle(cancel_button_x, button_y, button_width, BUTTON_HEIGHT) + confirm_button = rl.Rectangle(confirm_button_x, button_y, button_width, BUTTON_HEIGHT) + + rl.draw_rectangle_rec(dialog_rect, BACKGROUND_COLOR) + + text_rect = rl.Rectangle(dialog_rect.x + MARGIN, dialog_rect.y + TEXT_PADDING, + dialog_rect.width - 2 * MARGIN, dialog_rect.height - BUTTON_HEIGHT - MARGIN - TEXT_PADDING * 2) + if not self._rich: + self._label.render(text_rect) + else: + html_rect = rl.Rectangle(text_rect.x, text_rect.y, text_rect.width, + self._html_renderer.get_total_height(int(text_rect.width))) + self._html_renderer.set_rect(html_rect) + self._scroller.render(text_rect) + + if rl.is_key_pressed(rl.KeyboardKey.KEY_ENTER): + self._confirm_button_callback() + elif rl.is_key_pressed(rl.KeyboardKey.KEY_ESCAPE): + self._cancel_button_callback() + + if self._cancel_text: + self._confirm_button.render(confirm_button) + self._cancel_button.render(cancel_button) + else: + full_button_width = dialog_rect.width - 2 * MARGIN + full_confirm_button = rl.Rectangle(dialog_rect.x + MARGIN, button_y, full_button_width, BUTTON_HEIGHT) + self._confirm_button.render(full_confirm_button) + + +def alert_dialog(message: str, button_text: str | None = None): + if button_text is None: + button_text = tr("OK") + return ConfirmDialog(message, button_text, cancel_text="") diff --git a/openpilot/system/ui/widgets/html_render.py b/openpilot/system/ui/widgets/html_render.py new file mode 100644 index 0000000000..77fca9fe34 --- /dev/null +++ b/openpilot/system/ui/widgets/html_render.py @@ -0,0 +1,290 @@ +import re +import pyray as rl +from dataclasses import dataclass +from enum import Enum +from typing import Any +from openpilot.system.ui.lib.application import gui_app, FontWeight, FONT_SCALE +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.lib.scroll_panel import GuiScrollPanel +from openpilot.system.ui.lib.wrap_text import wrap_text +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.button import Button, ButtonStyle +from openpilot.system.ui.lib.text_measure import measure_text_cached + +LIST_INDENT_PX = 40 + + +class ElementType(Enum): + H1 = "h1" + H2 = "h2" + H3 = "h3" + H4 = "h4" + H5 = "h5" + H6 = "h6" + P = "p" + B = "b" + UL = "ul" + LI = "li" + BR = "br" + + +TAG_NAMES = '|'.join([t.value for t in ElementType]) +START_TAG_RE = re.compile(f'<({TAG_NAMES})>') +END_TAG_RE = re.compile(f'') +COMMENT_RE = re.compile(r'', flags=re.DOTALL) +DOCTYPE_RE = re.compile(r']*>') +HTML_BODY_TAGS_RE = re.compile(r']*>') +TOKEN_RE = re.compile(r']+>|<[^>]+>|[^<\s]+') + + +def is_tag(token: str) -> tuple[bool, bool, ElementType | None]: + supported_tag = bool(START_TAG_RE.fullmatch(token)) + supported_end_tag = bool(END_TAG_RE.fullmatch(token)) + tag = ElementType(token[1:-1].strip('/')) if supported_tag or supported_end_tag else None + return supported_tag, supported_end_tag, tag + + +@dataclass +class HtmlElement: + type: ElementType + content: str + font_size: int + font_weight: FontWeight + margin_top: int + margin_bottom: int + line_height: float = 0.9 # matches Qt visually, unsure why not default 1.2 + indent_level: int = 0 + + +class HtmlRenderer(Widget): + def __init__(self, file_path: str | None = None, text: str | None = None, + text_size: dict | None = None, text_color: rl.Color = rl.WHITE, center_text: bool = False): + super().__init__() + self._text_color = text_color + self._center_text = center_text + self._normal_font = gui_app.font(FontWeight.NORMAL) + self._bold_font = gui_app.font(FontWeight.BOLD) + self._indent_level = 0 + + if text_size is None: + text_size = {} + + self._cached_height: float | None = None + self._cached_width: int = -1 + + # Base paragraph size (Qt stylesheet default is 48px in offroad alerts) + base_p_size = int(text_size.get(ElementType.P, 48)) + + # Untagged text defaults to

+ self.styles: dict[ElementType, dict[str, Any]] = { + ElementType.H1: {"size": round(base_p_size * 2), "weight": FontWeight.BOLD, "margin_top": 20, "margin_bottom": 16}, + ElementType.H2: {"size": round(base_p_size * 1.50), "weight": FontWeight.BOLD, "margin_top": 24, "margin_bottom": 12}, + ElementType.H3: {"size": round(base_p_size * 1.17), "weight": FontWeight.BOLD, "margin_top": 20, "margin_bottom": 10}, + ElementType.H4: {"size": round(base_p_size * 1.00), "weight": FontWeight.BOLD, "margin_top": 16, "margin_bottom": 8}, + ElementType.H5: {"size": round(base_p_size * 0.83), "weight": FontWeight.BOLD, "margin_top": 12, "margin_bottom": 6}, + ElementType.H6: {"size": round(base_p_size * 0.67), "weight": FontWeight.BOLD, "margin_top": 10, "margin_bottom": 4}, + ElementType.P: {"size": base_p_size, "weight": FontWeight.NORMAL, "margin_top": 8, "margin_bottom": 12}, + ElementType.B: {"size": base_p_size, "weight": FontWeight.BOLD, "margin_top": 8, "margin_bottom": 12}, + ElementType.LI: {"size": base_p_size, "weight": FontWeight.NORMAL, "color": rl.Color(40, 40, 40, 255), "margin_top": 6, "margin_bottom": 6}, + ElementType.BR: {"size": 0, "weight": FontWeight.NORMAL, "margin_top": 0, "margin_bottom": 12}, + } + + self.elements: list[HtmlElement] = [] + if file_path is not None: + self.parse_html_file(file_path) + elif text is not None: + self.parse_html_content(text) + else: + raise ValueError("Either file_path or text must be provided") + + def parse_html_file(self, file_path: str) -> None: + with open(file_path, encoding='utf-8') as file: + content = file.read() + self.parse_html_content(content) + + def parse_html_content(self, html_content: str) -> None: + self.elements.clear() + self._cached_height = None + self._cached_width = -1 + + # Remove HTML comments + html_content = COMMENT_RE.sub('', html_content) + + # Remove DOCTYPE, html, head, body tags but keep their content + html_content = DOCTYPE_RE.sub('', html_content) + html_content = HTML_BODY_TAGS_RE.sub('', html_content) + + # Parse HTML + tokens = TOKEN_RE.findall(html_content) + + def close_tag(): + nonlocal current_content + nonlocal current_tag + + # If no tag is set, default to paragraph so we don't lose text + if current_tag is None: + current_tag = ElementType.P + + text = ' '.join(current_content).strip() + current_content = [] + if text: + if current_tag == ElementType.LI: + text = '• ' + text + self._add_element(current_tag, text) + + current_content: list[str] = [] + current_tag: ElementType | None = None + for token in tokens: + is_start_tag, is_end_tag, tag = is_tag(token) + if tag is not None: + if tag == ElementType.BR: + # Close current tag and add a line break + close_tag() + self._add_element(ElementType.BR, "") + + elif is_start_tag or is_end_tag: + # Always add content regardless of opening or closing tag + close_tag() + + if is_start_tag: + current_tag = tag + else: + current_tag = None + + # increment after we add the content for the current tag + if tag == ElementType.UL: + self._indent_level = self._indent_level + 1 if is_start_tag else max(0, self._indent_level - 1) + + else: + current_content.append(token) + + if current_content: + close_tag() + + def _add_element(self, element_type: ElementType, content: str) -> None: + style = self.styles[element_type] + + element = HtmlElement( + type=element_type, + content=content, + font_size=style["size"], + font_weight=style["weight"], + margin_top=style["margin_top"], + margin_bottom=style["margin_bottom"], + indent_level=self._indent_level, + ) + + self.elements.append(element) + + def _render(self, rect: rl.Rectangle): + # TODO: speed up by removing duplicate calculations across renders + current_y = rect.y + padding = 20 + content_width = rect.width - (padding * 2) + + for element in self.elements: + if element.type == ElementType.BR: + current_y += element.margin_bottom + continue + + current_y += element.margin_top + if current_y > rect.y + rect.height: + break + + if element.content: + font = self._get_font(element.font_weight) + wrapped_lines = wrap_text(font, element.content, element.font_size, int(content_width)) + + for line in wrapped_lines: + # Use FONT_SCALE from wrapped raylib text functions to match what is drawn + if current_y < rect.y - element.font_size * FONT_SCALE: + current_y += element.font_size * FONT_SCALE * element.line_height + continue + + if current_y > rect.y + rect.height: + break + + if self._center_text: + text_width = measure_text_cached(font, line, element.font_size).x + text_x = rect.x + (rect.width - text_width) / 2 + else: # left align + text_x = rect.x + (max(element.indent_level - 1, 0) * LIST_INDENT_PX) + + rl.draw_text_ex(font, line, rl.Vector2(text_x + padding, current_y), element.font_size, 0, self._text_color) + + current_y += element.font_size * FONT_SCALE * element.line_height + + # Apply bottom margin + current_y += element.margin_bottom + + return current_y - rect.y + + def get_total_height(self, content_width: int) -> float: + if self._cached_height is not None and self._cached_width == content_width: + return self._cached_height + + total_height = 0.0 + padding = 20 + usable_width = content_width - (padding * 2) + + for element in self.elements: + if element.type == ElementType.BR: + total_height += element.margin_bottom + continue + + total_height += element.margin_top + + if element.content: + font = self._get_font(element.font_weight) + wrapped_lines = wrap_text(font, element.content, element.font_size, int(usable_width)) + + for _ in wrapped_lines: + total_height += element.font_size * FONT_SCALE * element.line_height + + total_height += element.margin_bottom + + # Store result in cache + self._cached_height = total_height + self._cached_width = content_width + + return total_height + + def _get_font(self, weight: FontWeight): + if weight == FontWeight.BOLD: + return self._bold_font + return self._normal_font + + +class HtmlModal(Widget): + def __init__(self, file_path: str | None = None, text: str | None = None): + super().__init__() + self._content = HtmlRenderer(file_path=file_path, text=text) + self._scroll_panel = GuiScrollPanel() + self._ok_button = Button(tr("OK"), click_callback=gui_app.pop_widget, button_style=ButtonStyle.PRIMARY) + + def _render(self, rect: rl.Rectangle): + margin = 50 + content_rect = rl.Rectangle(rect.x + margin, rect.y + margin, rect.width - (margin * 2), rect.height - (margin * 2)) + + button_height = 160 + button_spacing = 20 + scrollable_height = content_rect.height - button_height - button_spacing + + scrollable_rect = rl.Rectangle(content_rect.x, content_rect.y, content_rect.width, scrollable_height) + + total_height = self._content.get_total_height(int(scrollable_rect.width)) + scroll_content_rect = rl.Rectangle(scrollable_rect.x, scrollable_rect.y, scrollable_rect.width, total_height) + scroll_offset = self._scroll_panel.update(scrollable_rect, scroll_content_rect) + scroll_content_rect.y += scroll_offset + + rl.begin_scissor_mode(int(scrollable_rect.x), int(scrollable_rect.y), int(scrollable_rect.width), int(scrollable_rect.height)) + self._content.render(scroll_content_rect) + rl.end_scissor_mode() + + button_width = (rect.width - 3 * 50) // 3 + button_x = content_rect.x + content_rect.width - button_width + button_y = content_rect.y + content_rect.height - button_height + button_rect = rl.Rectangle(button_x, button_y, button_width, button_height) + self._ok_button.render(button_rect) + + return -1 diff --git a/openpilot/system/ui/widgets/icon_widget.py b/openpilot/system/ui/widgets/icon_widget.py new file mode 100644 index 0000000000..bf7790b937 --- /dev/null +++ b/openpilot/system/ui/widgets/icon_widget.py @@ -0,0 +1,16 @@ +import pyray as rl +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.widgets import Widget + + +class IconWidget(Widget): + def __init__(self, image_path: str, size: tuple[int, int], opacity: float = 1.0): + super().__init__() + self._texture = gui_app.texture(image_path, size[0], size[1]) + self._opacity = opacity + self.set_rect(rl.Rectangle(0, 0, float(size[0]), float(size[1]))) + self.set_enabled(False) + + def _render(self, _) -> None: + color = rl.Color(255, 255, 255, int(self._opacity * 255)) + rl.draw_texture_ex(self._texture, rl.Vector2(self._rect.x, self._rect.y), 0.0, 1.0, color) diff --git a/system/ui/lib/inputbox.py b/openpilot/system/ui/widgets/inputbox.py similarity index 84% rename from system/ui/lib/inputbox.py rename to openpilot/system/ui/widgets/inputbox.py index ccf718ba56..f53e3f0ebb 100644 --- a/system/ui/lib/inputbox.py +++ b/openpilot/system/ui/widgets/inputbox.py @@ -1,8 +1,8 @@ import pyray as rl import time -from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.lib.application import gui_app, MousePos, FONT_SCALE from openpilot.system.ui.lib.text_measure import measure_text_cached -from openpilot.system.ui.lib.widget import Widget +from openpilot.system.ui.widgets import Widget PASSWORD_MASK_CHAR = "•" PASSWORD_MASK_DELAY = 1.5 # Seconds to show character before masking @@ -107,9 +107,6 @@ class InputBox(Widget): self._visible_width = rect.width self._font_size = font_size - # Handle mouse input - self._handle_mouse_input(rect, font_size) - # Draw input box rl.draw_rectangle_rec(rect, color) @@ -133,7 +130,7 @@ class InputBox(Widget): rl.draw_text_ex( font, display_text, - rl.Vector2(int(rect.x + padding - self._text_offset), int(rect.y + rect.height / 2 - font_size / 2)), + rl.Vector2(int(rect.x + padding - self._text_offset), int(rect.y + rect.height / 2 - font_size * FONT_SCALE / 2)), font_size, 0, text_color, @@ -148,7 +145,7 @@ class InputBox(Widget): # Apply text offset to cursor position cursor_x -= self._text_offset - cursor_height = font_size + 4 + cursor_height = font_size * FONT_SCALE + 4 cursor_y = rect.y + rect.height / 2 - cursor_height / 2 rl.draw_line(int(cursor_x), int(cursor_y), int(cursor_x), int(cursor_y + cursor_height), rl.WHITE) @@ -169,30 +166,27 @@ class InputBox(Widget): return masked_text - def _handle_mouse_input(self, rect, font_size): - """Handle mouse clicks to position cursor.""" - mouse_pos = rl.get_mouse_position() - if rl.is_mouse_button_pressed(rl.MouseButton.MOUSE_BUTTON_LEFT) and rl.check_collision_point_rec(mouse_pos, rect): - # Calculate cursor position from click - if len(self._input_text) > 0: - font = gui_app.font() - display_text = self._get_display_text() + def _handle_mouse_release(self, mouse_pos: MousePos): + # Calculate cursor position from click + if len(self._input_text) > 0: + font = gui_app.font() + display_text = self._get_display_text() - # Find the closest character position to the click - relative_x = mouse_pos.x - (rect.x + 10) + self._text_offset - best_pos = 0 - min_distance = float('inf') + # Find the closest character position to the click + relative_x = mouse_pos.x - (self._rect.x + 10) + self._text_offset + best_pos = 0 + min_distance = float('inf') - for i in range(len(self._input_text) + 1): - char_width = measure_text_cached(font, display_text[:i], font_size).x - distance = abs(relative_x - char_width) - if distance < min_distance: - min_distance = distance - best_pos = i + for i in range(len(self._input_text) + 1): + char_width = measure_text_cached(font, display_text[:i], self._font_size).x + distance = abs(relative_x - char_width) + if distance < min_distance: + min_distance = distance + best_pos = i - self.set_cursor_position(best_pos) - else: - self.set_cursor_position(0) + self.set_cursor_position(best_pos) + else: + self.set_cursor_position(0) def _handle_keyboard_input(self): # Handle navigation keys diff --git a/openpilot/system/ui/widgets/keyboard.py b/openpilot/system/ui/widgets/keyboard.py new file mode 100644 index 0000000000..49c59a431f --- /dev/null +++ b/openpilot/system/ui/widgets/keyboard.py @@ -0,0 +1,282 @@ +from functools import partial +import time +from typing import Literal +from collections.abc import Callable + +import pyray as rl + +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.widgets import DialogResult, Widget +from openpilot.system.ui.widgets.button import ButtonStyle, Button +from openpilot.system.ui.widgets.inputbox import InputBox +from openpilot.system.ui.widgets.label import Label + +KEY_FONT_SIZE = 96 +DOUBLE_CLICK_THRESHOLD = 0.5 # seconds +DELETE_REPEAT_DELAY = 0.5 +DELETE_REPEAT_INTERVAL = 0.07 + +# Constants for special keys +CONTENT_MARGIN = 50 +BACKSPACE_KEY = "<-" +ENTER_KEY = "->" +SPACE_KEY = " " +SHIFT_INACTIVE_KEY = "SHIFT_OFF" +SHIFT_ACTIVE_KEY = "SHIFT_ON" +CAPS_LOCK_KEY = "CAPS" +NUMERIC_KEY = "123" +SYMBOL_KEY = "#+=" +ABC_KEY = "ABC" + +# Define keyboard layouts as a dictionary for easier access +KEYBOARD_LAYOUTS = { + "lowercase": [ + ["q", "w", "e", "r", "t", "y", "u", "i", "o", "p"], + ["a", "s", "d", "f", "g", "h", "j", "k", "l"], + [SHIFT_INACTIVE_KEY, "z", "x", "c", "v", "b", "n", "m", BACKSPACE_KEY], + [NUMERIC_KEY, "/", "-", SPACE_KEY, ".", ENTER_KEY], + ], + "uppercase": [ + ["Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P"], + ["A", "S", "D", "F", "G", "H", "J", "K", "L"], + [SHIFT_ACTIVE_KEY, "Z", "X", "C", "V", "B", "N", "M", BACKSPACE_KEY], + [NUMERIC_KEY, "/", "-", SPACE_KEY, ".", ENTER_KEY], + ], + "numbers": [ + ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"], + ["-", "/", ":", ";", "(", ")", "$", "&", "@", "\""], + [SYMBOL_KEY, "_", ",", "?", "!", "`", BACKSPACE_KEY], + [ABC_KEY, SPACE_KEY, ".", ENTER_KEY], + ], + "specials": [ + ["[", "]", "{", "}", "#", "%", "^", "*", "+", "="], + ["_", "\\", "|", "~", "<", ">", "€", "£", "¥", "•"], + [NUMERIC_KEY, "-", ",", "?", "!", "'", BACKSPACE_KEY], + [ABC_KEY, SPACE_KEY, ".", ENTER_KEY], + ], +} + + +class Keyboard(Widget): + def __init__(self, max_text_size: int = 255, min_text_size: int = 0, password_mode: bool = False, show_password_toggle: bool = False, + callback: Callable[[DialogResult], None] | None = None): + super().__init__() + self._layout_name: Literal["lowercase", "uppercase", "numbers", "specials"] = "lowercase" + self._caps_lock = False + self._last_shift_press_time = 0 + self._title = Label("", 90, FontWeight.BOLD, rl.GuiTextAlignment.TEXT_ALIGN_LEFT, text_padding=20) + self._sub_title = Label("", 55, FontWeight.NORMAL, rl.GuiTextAlignment.TEXT_ALIGN_LEFT, text_padding=20) + + self._max_text_size = max_text_size + self._min_text_size = min_text_size + self._input_box = InputBox(max_text_size) + self._password_mode = password_mode + self._show_password_toggle = show_password_toggle + self._callback = callback + + # Backspace key repeat tracking + self._backspace_pressed: bool = False + self._backspace_press_time: float = 0.0 + self._backspace_last_repeat: float = 0.0 + + self._cancel_button = Button(lambda: tr("Cancel"), self._cancel_button_callback) + + self._eye_button = Button("", self._eye_button_callback, button_style=ButtonStyle.TRANSPARENT) + + self._eye_open_texture = gui_app.texture("icons/eye_open.png", 81, 54) + self._eye_closed_texture = gui_app.texture("icons/eye_closed.png", 81, 54) + self._key_icons = { + BACKSPACE_KEY: gui_app.texture("icons/backspace.png", 80, 80), + SHIFT_INACTIVE_KEY: gui_app.texture("icons/shift.png", 80, 80), + SHIFT_ACTIVE_KEY: gui_app.texture("icons/shift-fill.png", 80, 80), + CAPS_LOCK_KEY: gui_app.texture("icons/capslock-fill.png", 80, 80), + ENTER_KEY: gui_app.texture("icons/arrow-right.png", 80, 80), + } + + self._all_keys = {} + for l in KEYBOARD_LAYOUTS: + for _, keys in enumerate(KEYBOARD_LAYOUTS[l]): + for _, key in enumerate(keys): + if key in self._key_icons: + texture = self._key_icons[key] + self._all_keys[key] = Button("", partial(self._key_callback, key), icon=texture, + button_style=ButtonStyle.PRIMARY if key == ENTER_KEY else ButtonStyle.KEYBOARD, multi_touch=True) + else: + self._all_keys[key] = Button(key, partial(self._key_callback, key), button_style=ButtonStyle.KEYBOARD, font_size=85, multi_touch=True) + self._all_keys[CAPS_LOCK_KEY] = Button("", partial(self._key_callback, CAPS_LOCK_KEY), icon=self._key_icons[CAPS_LOCK_KEY], + button_style=ButtonStyle.KEYBOARD, multi_touch=True) + + def set_text(self, text: str): + self._input_box.text = text + + @property + def text(self): + return self._input_box.text + + def clear(self): + self._layout_name = "lowercase" + self._caps_lock = False + self._input_box.clear() + self._backspace_pressed = False + + def set_title(self, title: str, sub_title: str = ""): + self._title.set_text(title) + self._sub_title.set_text(sub_title) + + def set_callback(self, callback: Callable[[DialogResult], None] | None): + self._callback = callback + + def _eye_button_callback(self): + self._password_mode = not self._password_mode + + def _cancel_button_callback(self): + self.clear() + gui_app.pop_widget() + if self._callback: + self._callback(DialogResult.CANCEL) + + def _key_callback(self, k): + if k == ENTER_KEY: + gui_app.pop_widget() + if self._callback: + self._callback(DialogResult.CONFIRM) + else: + self.handle_key_press(k) + + def _render(self, rect: rl.Rectangle): + rect = rl.Rectangle(rect.x + CONTENT_MARGIN, rect.y + CONTENT_MARGIN, rect.width - 2 * CONTENT_MARGIN, rect.height - 2 * CONTENT_MARGIN) + self._title.render(rl.Rectangle(rect.x, rect.y, rect.width, 95)) + self._sub_title.render(rl.Rectangle(rect.x, rect.y + 95, rect.width, 60)) + self._cancel_button.render(rl.Rectangle(rect.x + rect.width - 386, rect.y, 386, 125)) + + # Draw input box and password toggle + input_margin = 25 + input_box_rect = rl.Rectangle(rect.x + input_margin, rect.y + 160, rect.width - input_margin, 100) + self._render_input_area(input_box_rect) + + # Process backspace key repeat if it's held down + if not self._all_keys[BACKSPACE_KEY].is_pressed: + self._backspace_pressed = False + + if self._backspace_pressed: + current_time = time.monotonic() + time_since_press = current_time - self._backspace_press_time + + # After initial delay, start repeating with shorter intervals + if time_since_press > DELETE_REPEAT_DELAY: + time_since_last_repeat = current_time - self._backspace_last_repeat + if time_since_last_repeat > DELETE_REPEAT_INTERVAL: + self._input_box.delete_char_before_cursor() + self._backspace_last_repeat = current_time + + layout = KEYBOARD_LAYOUTS[self._layout_name] + + h_space, v_space = 15, 15 + row_y_start = rect.y + 300 # Starting Y position for the first row + key_height = (rect.height - 300 - 3 * v_space) / 4 + key_max_width = (rect.width - (len(layout[2]) - 1) * h_space) / len(layout[2]) + + # Iterate over the rows of keys in the current layout + for row, keys in enumerate(layout): + key_width = min((rect.width - (180 if row == 1 else 0) - h_space * (len(keys) - 1)) / len(keys), key_max_width) + start_x = rect.x + (90 if row == 1 else 0) + + for i, key in enumerate(keys): + if i > 0: + start_x += h_space + + new_width = (key_width * 3 + h_space * 2) if key == SPACE_KEY else (key_width * 2 + h_space if key == ENTER_KEY else key_width) + key_rect = rl.Rectangle(start_x, row_y_start + row * (key_height + v_space), new_width, key_height) + start_x += new_width + + is_enabled = key != ENTER_KEY or len(self._input_box.text) >= self._min_text_size + + if key == BACKSPACE_KEY and self._all_keys[BACKSPACE_KEY].is_pressed and not self._backspace_pressed: + self._backspace_pressed = True + self._backspace_press_time = time.monotonic() + self._backspace_last_repeat = time.monotonic() + + if key in self._key_icons: + if key == SHIFT_ACTIVE_KEY and self._caps_lock: + key = CAPS_LOCK_KEY + self._all_keys[key].set_enabled(is_enabled) + self._all_keys[key].render(key_rect) + else: + self._all_keys[key].set_enabled(is_enabled) + self._all_keys[key].render(key_rect) + + def _render_input_area(self, input_rect: rl.Rectangle): + if self._show_password_toggle: + self._input_box.set_password_mode(self._password_mode) + self._input_box.render(rl.Rectangle(input_rect.x, input_rect.y, input_rect.width - 100, input_rect.height)) + + # render eye icon + eye_texture = self._eye_closed_texture if self._password_mode else self._eye_open_texture + + eye_rect = rl.Rectangle(input_rect.x + input_rect.width - 90, input_rect.y, 80, input_rect.height) + self._eye_button.render(eye_rect) + + eye_x = eye_rect.x + (eye_rect.width - eye_texture.width) / 2 + eye_y = eye_rect.y + (eye_rect.height - eye_texture.height) / 2 + + rl.draw_texture_v(eye_texture, rl.Vector2(eye_x, eye_y), rl.WHITE) + else: + self._input_box.render(input_rect) + + rl.draw_line_ex( + rl.Vector2(input_rect.x, input_rect.y + input_rect.height - 2), + rl.Vector2(input_rect.x + input_rect.width, input_rect.y + input_rect.height - 2), + 3.0, # 3 pixel thickness + rl.Color(189, 189, 189, 255), + ) + + def handle_key_press(self, key): + if key in (CAPS_LOCK_KEY, ABC_KEY): + self._caps_lock = False + self._layout_name = "lowercase" + elif key == SHIFT_INACTIVE_KEY: + self._last_shift_press_time = time.monotonic() + self._layout_name = "uppercase" + elif key == SHIFT_ACTIVE_KEY: + if time.monotonic() - self._last_shift_press_time < DOUBLE_CLICK_THRESHOLD: + self._caps_lock = True + else: + self._layout_name = "lowercase" + elif key == NUMERIC_KEY: + self._layout_name = "numbers" + elif key == SYMBOL_KEY: + self._layout_name = "specials" + elif key == BACKSPACE_KEY: + self._input_box.delete_char_before_cursor() + else: + self._input_box.add_char_at_cursor(key) + if not self._caps_lock and self._layout_name == "uppercase": + self._layout_name = "lowercase" + + def reset(self, min_text_size: int | None = None): + if min_text_size is not None: + self._min_text_size = min_text_size + self._last_shift_press_time = 0 + self._backspace_pressed = False + self._backspace_press_time = 0.0 + self._backspace_last_repeat = 0.0 + self.clear() + + +if __name__ == "__main__": + def callback(result: DialogResult): + if result == DialogResult.CONFIRM: + print(f"You typed: {keyboard.text}") + elif result == DialogResult.CANCEL: + print("Canceled") + gui_app.request_close() + + gui_app.init_window("Keyboard") + keyboard = Keyboard(min_text_size=8, show_password_toggle=True, callback=callback) + keyboard.set_title("Keyboard Input", "Type your text below") + + gui_app.push_widget(keyboard) + for _ in gui_app.render(): + pass + gui_app.close() diff --git a/openpilot/system/ui/widgets/label.py b/openpilot/system/ui/widgets/label.py new file mode 100644 index 0000000000..fdaf6f3148 --- /dev/null +++ b/openpilot/system/ui/widgets/label.py @@ -0,0 +1,724 @@ +import math +from enum import IntEnum +from collections.abc import Callable +from typing import Union +import pyray as rl + +from openpilot.system.ui.lib.application import gui_app, FontWeight, DEFAULT_TEXT_SIZE, DEFAULT_TEXT_COLOR, FONT_SCALE +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.lib.utils import GuiStyleContext +from openpilot.system.ui.lib.emoji import find_emoji, emoji_tex +from openpilot.system.ui.lib.wrap_text import wrap_text + +ICON_PADDING = 15 + + +# TODO: make this common +def _resolve_value(value, default=""): + if callable(value): + return value() + return value if value is not None else default + + +class ScrollState(IntEnum): + STARTING = 0 + SCROLLING = 1 + + +# TODO: This should be a Widget class +def gui_label( + rect: rl.Rectangle, + text: str, + font_size: int = DEFAULT_TEXT_SIZE, + color: rl.Color = DEFAULT_TEXT_COLOR, + font_weight: FontWeight = FontWeight.NORMAL, + alignment: int = rl.GuiTextAlignment.TEXT_ALIGN_LEFT, + alignment_vertical: int = rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE, + elide_right: bool = True +): + font = gui_app.font(font_weight) + text_size = measure_text_cached(font, text, font_size) + display_text = text + + # Elide text to fit within the rectangle + if elide_right and text_size.x > rect.width: + _ellipsis = "..." + left, right = 0, len(text) + while left < right: + mid = (left + right) // 2 + candidate = text[:mid] + _ellipsis + candidate_size = measure_text_cached(font, candidate, font_size) + if candidate_size.x <= rect.width: + left = mid + 1 + else: + right = mid + display_text = text[: left - 1] + _ellipsis if left > 0 else _ellipsis + text_size = measure_text_cached(font, display_text, font_size) + + # Calculate horizontal position based on alignment + text_x = rect.x + { + rl.GuiTextAlignment.TEXT_ALIGN_LEFT: 0, + rl.GuiTextAlignment.TEXT_ALIGN_CENTER: (rect.width - text_size.x) / 2, + rl.GuiTextAlignment.TEXT_ALIGN_RIGHT: rect.width - text_size.x, + }.get(alignment, 0) + + # Calculate vertical position based on alignment + text_y = rect.y + { + rl.GuiTextAlignmentVertical.TEXT_ALIGN_TOP: 0, + rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE: (rect.height - text_size.y) / 2, + rl.GuiTextAlignmentVertical.TEXT_ALIGN_BOTTOM: rect.height - text_size.y, + }.get(alignment_vertical, 0) + + # Draw the text in the specified rectangle + # TODO: add wrapping and proper centering for multiline text + rl.draw_text_ex(font, display_text, rl.Vector2(text_x, text_y), font_size, 0, color) + + +def gui_text_box( + rect: rl.Rectangle, + text: str, + font_size: int = DEFAULT_TEXT_SIZE, + color: rl.Color = DEFAULT_TEXT_COLOR, + alignment: int = rl.GuiTextAlignment.TEXT_ALIGN_LEFT, + alignment_vertical: int = rl.GuiTextAlignmentVertical.TEXT_ALIGN_TOP, + font_weight: FontWeight = FontWeight.NORMAL, + line_scale: float = 1.0, +): + styles = [ + (rl.GuiControl.DEFAULT, rl.GuiControlProperty.TEXT_COLOR_NORMAL, rl.color_to_int(color)), + (rl.GuiControl.DEFAULT, rl.GuiDefaultProperty.TEXT_SIZE, round(font_size * FONT_SCALE)), + (rl.GuiControl.DEFAULT, rl.GuiDefaultProperty.TEXT_LINE_SPACING, round(font_size * FONT_SCALE * line_scale)), + (rl.GuiControl.DEFAULT, rl.GuiControlProperty.TEXT_ALIGNMENT, alignment), + (rl.GuiControl.DEFAULT, rl.GuiDefaultProperty.TEXT_ALIGNMENT_VERTICAL, alignment_vertical), + (rl.GuiControl.DEFAULT, rl.GuiDefaultProperty.TEXT_WRAP_MODE, rl.GuiTextWrapMode.TEXT_WRAP_WORD) + ] + if font_weight != FontWeight.NORMAL: + rl.gui_set_font(gui_app.font(font_weight)) + + with GuiStyleContext(styles): + rl.gui_label(rect, text) + + if font_weight != FontWeight.NORMAL: + rl.gui_set_font(gui_app.font(FontWeight.NORMAL)) + + +# Non-interactive text area. Can render emojis and an optional specified icon. +class Label(Widget): + def __init__(self, + text: str | Callable[[], str], + font_size: int = DEFAULT_TEXT_SIZE, + font_weight: FontWeight = FontWeight.NORMAL, + text_alignment: int = rl.GuiTextAlignment.TEXT_ALIGN_CENTER, + text_alignment_vertical: int = rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE, + text_padding: int = 0, + text_color: rl.Color = DEFAULT_TEXT_COLOR, + icon: Union[rl.Texture, None] = None, + elide_right: bool = False, + line_scale=1.0, + ): + + super().__init__() + self._font_weight = font_weight + self._font = gui_app.font(self._font_weight) + self._font_size = font_size + self._text_alignment = text_alignment + self._text_alignment_vertical = text_alignment_vertical + self._text_padding = text_padding + self._text_color = text_color + self._icon = icon + self._elide_right = elide_right + self._line_scale = line_scale + + self._text = text + self.set_text(text) + + def set_text(self, text): + self._text = text + self._update_text(self._text) + + def set_text_color(self, color): + self._text_color = color + + def set_font_size(self, size): + self._font_size = size + self._update_text(self._text) + + def _update_text(self, text): + self._emojis = [] + self._text_size = [] + text = _resolve_value(text) + + if self._elide_right: + display_text = text + + # Elide text to fit within the rectangle + text_size = measure_text_cached(self._font, text, self._font_size) + content_width = self._rect.width - self._text_padding * 2 + if self._icon: + content_width -= self._icon.width + ICON_PADDING + if text_size.x > content_width: + _ellipsis = "..." + left, right = 0, len(text) + while left < right: + mid = (left + right) // 2 + candidate = text[:mid] + _ellipsis + candidate_size = measure_text_cached(self._font, candidate, self._font_size) + if candidate_size.x <= content_width: + left = mid + 1 + else: + right = mid + display_text = text[: left - 1] + _ellipsis if left > 0 else _ellipsis + + self._text_wrapped = [display_text] + else: + self._text_wrapped = wrap_text(self._font, text, self._font_size, round(self._rect.width - (self._text_padding * 2))) + + for t in self._text_wrapped: + self._emojis.append(find_emoji(t)) + self._text_size.append(measure_text_cached(self._font, t, self._font_size)) + + def _render(self, _): + # Text can be a callable + # TODO: cache until text changed + self._update_text(self._text) + + text_size = self._text_size[0] if self._text_size else rl.Vector2(0.0, 0.0) + if self._text_alignment_vertical == rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE: + total_text_height = sum(ts.y for ts in self._text_size) or self._font_size * FONT_SCALE + text_pos = rl.Vector2(self._rect.x, (self._rect.y + (self._rect.height - total_text_height) // 2)) + elif self._text_alignment_vertical == rl.GuiTextAlignmentVertical.TEXT_ALIGN_BOTTOM: + total_text_height = sum(ts.y for ts in self._text_size) or self._font_size * FONT_SCALE + text_pos = rl.Vector2(self._rect.x, self._rect.y + self._rect.height - total_text_height) + else: + text_pos = rl.Vector2(self._rect.x, self._rect.y) + + if self._icon: + icon_y = self._rect.y + (self._rect.height - self._icon.height) / 2 + if len(self._text_wrapped) > 0: + if self._text_alignment == rl.GuiTextAlignment.TEXT_ALIGN_LEFT: + icon_x = self._rect.x + self._text_padding + text_pos.x = self._rect.x + self._icon.width + ICON_PADDING + elif self._text_alignment == rl.GuiTextAlignment.TEXT_ALIGN_CENTER: + total_width = self._icon.width + ICON_PADDING + text_size.x + icon_x = self._rect.x + (self._rect.width - total_width) / 2 + text_pos.x = self._rect.x + self._icon.width + ICON_PADDING + else: + icon_x = (self._rect.x + self._rect.width - text_size.x - self._text_padding) - ICON_PADDING - self._icon.width + else: + icon_x = self._rect.x + (self._rect.width - self._icon.width) / 2 + rl.draw_texture_v(self._icon, rl.Vector2(icon_x, icon_y), rl.WHITE) + + for text, text_size, emojis in zip(self._text_wrapped, self._text_size, self._emojis, strict=True): + line_pos = rl.Vector2(text_pos.x, text_pos.y) + if self._text_alignment == rl.GuiTextAlignment.TEXT_ALIGN_LEFT: + line_pos.x += self._text_padding + elif self._text_alignment == rl.GuiTextAlignment.TEXT_ALIGN_CENTER: + line_pos.x += (self._rect.width - text_size.x) // 2 + elif self._text_alignment == rl.GuiTextAlignment.TEXT_ALIGN_RIGHT: + line_pos.x += self._rect.width - text_size.x - self._text_padding + + prev_index = 0 + for start, end, emoji in emojis: + text_before = text[prev_index:start] + width_before = measure_text_cached(self._font, text_before, self._font_size) + rl.draw_text_ex(self._font, text_before, line_pos, self._font_size, 0, self._text_color) + line_pos.x += width_before.x + + tex = emoji_tex(emoji) + rl.draw_texture_ex(tex, line_pos, 0.0, self._font_size / tex.height * FONT_SCALE, self._text_color) + line_pos.x += self._font_size * FONT_SCALE + prev_index = end + rl.draw_text_ex(self._font, text[prev_index:], line_pos, self._font_size, 0, self._text_color) + text_pos.y += (text_size.y or self._font_size * FONT_SCALE) * self._line_scale + + +class UnifiedLabel(Widget): + """ + Unified label widget that combines functionality from gui_label, gui_text_box, and Label. + + Supports: + - Emoji rendering + - Text wrapping + - Automatic eliding (single-line or multiline) + - Proper multiline vertical alignment + - Height calculation for layout purposes + """ + # Shimmer constants + SHIMMER_BAND_WIDTH = 0.3 # shimmer width as fraction of text width + SHIMMER_BLUR_RADIUS = 0.12 # gaussian blur as fraction of text width + SHIMMER_CYCLE_PERIOD = 2.5 # seconds per full shimmer cycle + SHIMMER_SWEEP_FRACTION = 0.9 # fraction of cycle spent sweeping (rest is pause) + SHIMMER_LOW_OPACITY = 0.65 # text opacity at rest, shimmer brings to 1.0 + + def __init__(self, + text: str | Callable[[], str], + font_size: int = DEFAULT_TEXT_SIZE, + font_weight: FontWeight = FontWeight.NORMAL, + text_color: rl.Color = DEFAULT_TEXT_COLOR, + alignment: int = rl.GuiTextAlignment.TEXT_ALIGN_LEFT, + alignment_vertical: int = rl.GuiTextAlignmentVertical.TEXT_ALIGN_TOP, + text_padding: int = 0, + max_width: int | None = None, + elide: bool = True, + wrap_text: bool = True, + scroll: bool = False, + line_height: float = 1.0, + letter_spacing: float = 0.0, + shimmer: bool = False): + super().__init__() + self._text = text + self._font_size = font_size + self._font_weight = font_weight + self._font = gui_app.font(self._font_weight) + self._text_color = text_color + self._alignment = alignment + self._alignment_vertical = alignment_vertical + self._text_padding = text_padding + self._max_width = max_width + self._elide = elide + self._wrap_text = wrap_text + self._scroll = scroll + self._line_height = line_height * 0.9 + self._letter_spacing = letter_spacing # 0.1 = 10% + self._spacing_pixels = font_size * letter_spacing + + # Shimmer state + self._shimmer = shimmer + self._shimmer_start_time = 0.0 + + # Scroll state + self._scroll = scroll + self._needs_scroll = False + self._scroll_offset = 0 + self._scroll_pause_t: float | None = None + self._scroll_state: ScrollState = ScrollState.STARTING + + # Scroll mode does not support eliding or multiline wrapping + if self._scroll: + self._elide = False + self._wrap_text = False + + # Cached data + self._cached_text: str | None = None + self._cached_wrapped_lines: list[str] = [] + self._cached_line_sizes: list[rl.Vector2] = [] + self._cached_line_emojis: list[list[tuple[int, int, str]]] = [] + self._cached_total_height: float | None = None + self._cached_width: int = -1 + + # If max_width is set, initialize rect size for Scroller support + if max_width is not None: + self._rect.width = max_width + self._rect.height = self.get_content_height(max_width) + + def set_text(self, text: str | Callable[[], str]): + """Update the text content.""" + self._text = text + # No need to update cache here, will be done on next render if needed + + @property + def text(self) -> str: + """Get the current text content.""" + return str(_resolve_value(self._text)) + + @property + def font_size(self) -> int: + return self._font_size + + @property + def text_width(self) -> float: + return max((s.x for s in self._cached_line_sizes), default=0.0) + + def set_text_color(self, color: rl.Color): + """Update the text color.""" + self._text_color = color + + def set_color(self, color: rl.Color): + """Update the text color (alias for set_text_color).""" + self.set_text_color(color) + + def set_font_size(self, size: int): + """Update the font size.""" + if self._font_size != size: + self._font_size = size + self._spacing_pixels = size * self._letter_spacing # Recalculate spacing + self._cached_text = None # Invalidate cache + + def set_letter_spacing(self, letter_spacing: float): + """Update letter spacing (as percentage, e.g., 0.1 = 10%).""" + if self._letter_spacing != letter_spacing: + self._letter_spacing = letter_spacing + self._spacing_pixels = self._font_size * letter_spacing + self._cached_text = None # Invalidate cache + + def set_line_height(self, line_height: float): + """Update line height (multiplier, e.g., 1.0 = default).""" + new_line_height = line_height * 0.9 + if self._line_height != new_line_height: + self._line_height = new_line_height + self._cached_text = None # Invalidate cache (affects total height) + + def set_font_weight(self, font_weight: FontWeight): + """Update the font weight.""" + if self._font_weight != font_weight: + self._font_weight = font_weight + self._font = gui_app.font(self._font_weight) + self._cached_text = None # Invalidate cache + + def set_alignment(self, alignment: int): + """Update the horizontal text alignment.""" + self._alignment = alignment + + def set_alignment_vertical(self, alignment_vertical: int): + """Update the vertical text alignment.""" + self._alignment_vertical = alignment_vertical + + def reset_scroll(self): + """Reset scroll state to initial position.""" + self._scroll_offset = 0 + self._scroll_pause_t = None + self._scroll_state = ScrollState.STARTING + + def show_event(self): + super().show_event() + if self._shimmer: + self.reset_shimmer() + + def reset_shimmer(self, offset: float = 0.0): + """Reset shimmer animation timing.""" + self._shimmer_start_time = rl.get_time() + offset + + def set_max_width(self, max_width: int | None): + """Set the maximum width constraint for wrapping/eliding.""" + if self._max_width != max_width: + self._max_width = max_width + self._cached_text = None # Invalidate cache + # Update rect size for Scroller support + if max_width is not None: + self._rect.width = max_width + self._rect.height = self.get_content_height(max_width) + + def _update_text_cache(self, available_width: int): + """Update cached text processing data.""" + text = self.text + + # Check if cache is still valid + if (self._cached_text == text and + self._cached_width == available_width and + self._cached_wrapped_lines): + return + + self._cached_text = text + self._cached_width = available_width + + # Determine wrapping width + content_width = available_width - (self._text_padding * 2) + if content_width <= 0: + content_width = 1 + + # Wrap text if enabled + if self._wrap_text: + self._cached_wrapped_lines = wrap_text(self._font, text, self._font_size, content_width, self._spacing_pixels) + else: + # Split by newlines but don't wrap + self._cached_wrapped_lines = text.split('\n') if text else [""] + + # Elide lines if needed (for width constraint) + self._cached_wrapped_lines = [self._elide_line(line, content_width) for line in self._cached_wrapped_lines] + + if self._scroll: + self._cached_wrapped_lines = self._cached_wrapped_lines[:1] # Only first line for scrolling + + # Process each line: measure and find emojis + self._cached_line_sizes = [] + self._cached_line_emojis = [] + + for line in self._cached_wrapped_lines: + emojis = find_emoji(line) + self._cached_line_emojis.append(emojis) + # Empty lines should still have height (use font size as line height) + if not line: + size = rl.Vector2(0, self._font_size * FONT_SCALE) + else: + size = measure_text_cached(self._font, line, self._font_size, self._spacing_pixels) + + # This is the only line + if self._scroll: + self._needs_scroll = size.x > content_width + + self._cached_line_sizes.append(size) + + # Calculate total height + # Each line contributes its measured height * line_height (matching Label's behavior) + # This includes spacing to the next line + if self._cached_line_sizes: + # Match the rendering logic: first line doesn't get line_height scaling + total_height = 0.0 + for idx, size in enumerate(self._cached_line_sizes): + if idx == 0: + total_height += size.y + else: + total_height += size.y * self._line_height + self._cached_total_height = total_height + else: + self._cached_total_height = 0.0 + + def _elide_line(self, line: str, max_width: int, force: bool = False) -> str: + """Elide a single line if it exceeds max_width. If force is True, always elide even if it fits.""" + if not self._elide and not force: + return line + + text_size = measure_text_cached(self._font, line, self._font_size, self._spacing_pixels) + if text_size.x <= max_width and not force: + return line + + ellipsis = "..." + # If force=True and line fits, just append ellipsis without truncating + if force and text_size.x <= max_width: + ellipsis_size = measure_text_cached(self._font, ellipsis, self._font_size, self._spacing_pixels) + if text_size.x + ellipsis_size.x <= max_width: + return line + ellipsis + # If line + ellipsis doesn't fit, need to truncate + # Fall through to binary search below + + left, right = 0, len(line) + while left < right: + mid = (left + right) // 2 + candidate = line[:mid] + ellipsis + candidate_size = measure_text_cached(self._font, candidate, self._font_size, self._spacing_pixels) + if candidate_size.x <= max_width: + left = mid + 1 + else: + right = mid + return line[:left - 1] + ellipsis if left > 0 else ellipsis + + def get_content_height(self, max_width: int) -> float: + """ + Returns the height needed for text at given max_width. + Similar to HtmlRenderer.get_total_height(). + """ + # Use max_width if provided, otherwise use self._max_width or a default + width = max_width if max_width > 0 else (self._max_width if self._max_width else 1000) + self._update_text_cache(width) + + if self._cached_total_height is not None: + return self._cached_total_height + return 0.0 + + def _render(self, _): + """Render the label.""" + if self._rect.width <= 0 or self._rect.height <= 0: + return + + # Determine available width + available_width = self._rect.width + if self._max_width is not None: + available_width = min(available_width, self._max_width) + + # Update text cache + self._update_text_cache(int(available_width)) + + if not self._cached_wrapped_lines: + return + + # Calculate which lines fit in the available height + visible_lines: list[str] = [] + visible_sizes: list[rl.Vector2] = [] + visible_emojis: list[list[tuple[int, int, str]]] = [] + + current_height = 0.0 + broke_early = False + for line, size, emojis in zip( + self._cached_wrapped_lines, + self._cached_line_sizes, + self._cached_line_emojis, + strict=True): + + # Calculate height needed for this line + # Each line contributes its height * line_height (matching Label's behavior) + line_height_needed = size.y * self._line_height + + # Check if this line fits + if current_height + line_height_needed > self._rect.height: + # This line doesn't fit + if len(visible_lines) == 0: + # First line doesn't fit by height - still show it (will be clipped by scissor if needed) + # Continue to add this line below + pass + else: + # We have visible lines and this one doesn't fit - mark that we broke early + broke_early = True + break + + visible_lines.append(line) + visible_sizes.append(size) + visible_emojis.append(emojis) + + current_height += line_height_needed + + # If we broke early (there are more lines that don't fit) and elide is enabled, elide the last visible line + if broke_early and len(visible_lines) > 0 and self._elide: + content_width = int(available_width - (self._text_padding * 2)) + if content_width <= 0: + content_width = 1 + + last_line_idx = len(visible_lines) - 1 + last_line = visible_lines[last_line_idx] + # Force elide the last line to show "..." even if it fits in width (to indicate more content) + elided = self._elide_line(last_line, content_width, force=True) + visible_lines[last_line_idx] = elided + visible_sizes[last_line_idx] = measure_text_cached(self._font, elided, self._font_size, self._spacing_pixels) + + if not visible_lines: + return + + # Calculate total visible text block height + # First line is not changed by line_height scaling + total_visible_height = 0.0 + for idx, size in enumerate(visible_sizes): + if idx == 0: + total_visible_height += size.y + else: + total_visible_height += size.y * self._line_height + + # Calculate vertical alignment offset + if self._alignment_vertical == rl.GuiTextAlignmentVertical.TEXT_ALIGN_TOP: + start_y = self._rect.y + elif self._alignment_vertical == rl.GuiTextAlignmentVertical.TEXT_ALIGN_BOTTOM: + start_y = self._rect.y + self._rect.height - total_visible_height + else: # TEXT_ALIGN_MIDDLE + start_y = self._rect.y + (self._rect.height - total_visible_height) / 2 + + # Only scissor when we know there is a single scrolling line + # Pad a little since descenders like g or j may overflow below rect from font_scale + if self._needs_scroll: + rl.begin_scissor_mode(int(self._rect.x), int(self._rect.y - self._font_size / 2), int(self._rect.width), int(self._rect.height + self._font_size)) + + # Render each line + current_y = start_y + for idx, (line, size, emojis) in enumerate(zip(visible_lines, visible_sizes, visible_emojis, strict=True)): + if self._needs_scroll: + if self._scroll_state == ScrollState.STARTING: + if self._scroll_pause_t is None: + self._scroll_pause_t = rl.get_time() + 2.0 + if rl.get_time() >= self._scroll_pause_t: + self._scroll_state = ScrollState.SCROLLING + self._scroll_pause_t = None + + elif self._scroll_state == ScrollState.SCROLLING: + self._scroll_offset -= 0.8 / 60. * gui_app.target_fps + # don't fully hide + if self._scroll_offset <= -size.x - self._rect.width / 3: + self._scroll_offset = 0 + self._scroll_state = ScrollState.STARTING + self._scroll_pause_t = None + else: + self.reset_scroll() + + self._render_line(line, size, emojis, current_y) + + # Draw 2nd instance for scrolling + if self._needs_scroll and self._scroll_state != ScrollState.STARTING: + text2_scroll_offset = size.x + self._rect.width / 3 + self._render_line(line, size, emojis, current_y, text2_scroll_offset) + + # Move to next line (if not last line) + if idx < len(visible_lines) - 1: + # Use current line's height * line_height for spacing to next line + current_y += size.y * self._line_height + + if self._needs_scroll: + # draw black fade on left and right + fade_width = 20 + rl.draw_rectangle_gradient_h(int(self._rect.x + self._rect.width - fade_width), int(self._rect.y), fade_width, int(self._rect.height), rl.BLANK, rl.BLACK) + + # stop drawing left fade once text scrolls past + text_width = visible_sizes[0].x if visible_sizes else 0 + first_copy_in_view = self._scroll_offset + text_width > 0 + draw_left_fade = self._scroll_state != ScrollState.STARTING and first_copy_in_view + if draw_left_fade: + rl.draw_rectangle_gradient_h(int(self._rect.x), int(self._rect.y), fade_width, int(self._rect.height), rl.BLACK, rl.BLANK) + + rl.end_scissor_mode() + + def _shimmer_alpha(self, char_x: float, shimmer_left: float, shimmer_width: float) -> float: + """Compute shimmer opacity multiplier for a character at the given x position.""" + sigma = shimmer_width * self.SHIMMER_BLUR_RADIUS + if sigma <= 0: + return self.SHIMMER_LOW_OPACITY + + elapsed = rl.get_time() - self._shimmer_start_time + t_raw = (elapsed % self.SHIMMER_CYCLE_PERIOD) / self.SHIMMER_CYCLE_PERIOD + t_clamped = max(0.0, min(t_raw / self.SHIMMER_SWEEP_FRACTION, 1.0)) + t = t_clamped * t_clamped * (3.0 - 2.0 * t_clamped) # smoothstep + + margin = shimmer_width * self.SHIMMER_BAND_WIDTH + center = shimmer_left + shimmer_width + margin - t * (shimmer_width + 2.0 * margin) + + d = char_x - center + shimmer = math.exp(-0.5 * d * d / (sigma * sigma)) + return self.SHIMMER_LOW_OPACITY + (1.0 - self.SHIMMER_LOW_OPACITY) * shimmer + + def _render_line(self, line, size, emojis, current_y, x_offset=0.0): + # Calculate horizontal position + if self._alignment == rl.GuiTextAlignment.TEXT_ALIGN_LEFT: + line_x = self._rect.x + self._text_padding + elif self._alignment == rl.GuiTextAlignment.TEXT_ALIGN_CENTER: + line_x = self._rect.x + (self._rect.width - size.x) / 2 + elif self._alignment == rl.GuiTextAlignment.TEXT_ALIGN_RIGHT: + line_x = self._rect.x + self._rect.width - size.x - self._text_padding + else: + line_x = self._rect.x + self._text_padding + line_x += self._scroll_offset + x_offset + + if self._shimmer: + self._render_line_shimmer(line, line_x, current_y) + else: + # Render line with emojis + self._render_line_normal(line, emojis, line_x, current_y) + + def _render_line_normal(self, line, emojis, line_x, current_y): + line_pos = rl.Vector2(line_x, current_y) + prev_index = 0 + + for start, end, emoji in emojis: + # Draw text before emoji + text_before = line[prev_index:start] + if text_before: + rl.draw_text_ex(self._font, text_before, line_pos, self._font_size, self._spacing_pixels, self._text_color) + width_before = measure_text_cached(self._font, text_before, self._font_size, self._spacing_pixels) + line_pos.x += width_before.x + + # Draw emoji + tex = emoji_tex(emoji) + emoji_scale = self._font_size / tex.height * FONT_SCALE + rl.draw_texture_ex(tex, line_pos, 0.0, emoji_scale, self._text_color) + # Emoji width is font_size * FONT_SCALE (as per measure_text_cached) + line_pos.x += self._font_size * FONT_SCALE + prev_index = end + + # Draw remaining text after last emoji + text_after = line[prev_index:] + if text_after: + rl.draw_text_ex(self._font, text_after, line_pos, self._font_size, self._spacing_pixels, self._text_color) + + def _render_line_shimmer(self, line, line_x, current_y): + # Shimmer range based on widest line so sweep is even across all lines + max_width = self.text_width + if self._alignment == rl.GuiTextAlignment.TEXT_ALIGN_RIGHT: + shimmer_left = self._rect.x + self._rect.width - self._text_padding - max_width + elif self._alignment == rl.GuiTextAlignment.TEXT_ALIGN_CENTER: + shimmer_left = self._rect.x + (self._rect.width - max_width) / 2 + else: + shimmer_left = self._rect.x + self._text_padding + + base_a = self._text_color.a / 255.0 + cursor_x = line_x + for ch in line: + char_width = measure_text_cached(self._font, ch, self._font_size, self._spacing_pixels).x + char_center_x = cursor_x + char_width / 2.0 + alpha = int(255 * self._shimmer_alpha(char_center_x, shimmer_left, max_width) * base_a) + color = rl.Color(self._text_color.r, self._text_color.g, self._text_color.b, alpha) + rl.draw_text_ex(self._font, ch, rl.Vector2(cursor_x, current_y), self._font_size, 0, color) + cursor_x += char_width + self._spacing_pixels diff --git a/openpilot/system/ui/widgets/layouts.py b/openpilot/system/ui/widgets/layouts.py new file mode 100644 index 0000000000..6bbc49e927 --- /dev/null +++ b/openpilot/system/ui/widgets/layouts.py @@ -0,0 +1,59 @@ +from enum import IntFlag +from openpilot.system.ui.widgets import Widget + + +class Alignment(IntFlag): + LEFT = 0 + # TODO: implement + # H_CENTER = 2 + # RIGHT = 4 + + TOP = 8 + V_CENTER = 16 + BOTTOM = 32 + + +class HBoxLayout(Widget): + """ + A Widget that lays out child Widgets horizontally. + """ + + def __init__(self, widgets: list[Widget] | None = None, spacing: int = 0, + alignment: Alignment = Alignment.LEFT | Alignment.V_CENTER): + super().__init__() + self._spacing = spacing + self._alignment = alignment + + if widgets is not None: + for widget in widgets: + self.add_widget(widget) + + @property + def widgets(self) -> list[Widget]: + return self._children + + def add_widget(self, widget: Widget) -> None: + self._child(widget) + + def _render(self, _): + visible_widgets = [w for w in self._children if w.is_visible] + + cur_offset_x = 0 + + for idx, widget in enumerate(visible_widgets): + spacing = self._spacing if (idx > 0) else 0 + + x = self._rect.x + cur_offset_x + spacing + cur_offset_x += widget.rect.width + spacing + + if self._alignment & Alignment.TOP: + y = self._rect.y + elif self._alignment & Alignment.BOTTOM: + y = self._rect.y + self._rect.height - widget.rect.height + else: # center + y = self._rect.y + (self._rect.height - widget.rect.height) / 2 + + # Update widget position and render + widget.set_position(x, y) + widget.set_parent_rect(self._rect) + widget.render() diff --git a/openpilot/system/ui/widgets/list_view.py b/openpilot/system/ui/widgets/list_view.py new file mode 100644 index 0000000000..08c65208a4 --- /dev/null +++ b/openpilot/system/ui/widgets/list_view.py @@ -0,0 +1,468 @@ +import os +import pyray as rl +from collections.abc import Callable, Sequence +from abc import ABC +from openpilot.system.ui.lib.application import gui_app, FontWeight, MousePos +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.button import Button, ButtonStyle +from openpilot.system.ui.widgets.toggle import Toggle, WIDTH as TOGGLE_WIDTH, HEIGHT as TOGGLE_HEIGHT +from openpilot.system.ui.widgets.label import gui_label +from openpilot.system.ui.widgets.html_render import HtmlRenderer, ElementType + +ITEM_BASE_WIDTH = 600 +ITEM_BASE_HEIGHT = 170 +ITEM_PADDING = 20 +ITEM_TEXT_FONT_SIZE = 50 +ITEM_TEXT_COLOR = rl.WHITE +ITEM_TEXT_VALUE_COLOR = rl.Color(170, 170, 170, 255) +ITEM_DESC_TEXT_COLOR = rl.Color(128, 128, 128, 255) +ITEM_DESC_FONT_SIZE = 40 +ITEM_DESC_V_OFFSET = 140 +RIGHT_ITEM_PADDING = 20 +ICON_SIZE = 80 +BUTTON_WIDTH = 250 +BUTTON_HEIGHT = 100 +BUTTON_BORDER_RADIUS = 50 +BUTTON_FONT_SIZE = 35 +BUTTON_FONT_WEIGHT = FontWeight.MEDIUM + +TEXT_PADDING = 20 + + +def _resolve_value(value, default=""): + if callable(value): + return value() + return value if value is not None else default + + +# Abstract base class for right-side items +class ItemAction(Widget, ABC): + def __init__(self, width: int = BUTTON_HEIGHT, enabled: bool | Callable[[], bool] = True): + super().__init__() + self.set_rect(rl.Rectangle(0, 0, width, 0)) + self._enabled_source = enabled + + def get_width_hint(self) -> float: + # Return's action ideal width, 0 means use full width + return self._rect.width + + def set_enabled(self, enabled: bool | Callable[[], bool]): + self._enabled_source = enabled + + @property + def enabled(self): + return _resolve_value(self._enabled_source, False) + + +class ToggleAction(ItemAction): + def __init__(self, initial_state: bool = False, width: int = TOGGLE_WIDTH, enabled: bool | Callable[[], bool] = True, + callback: Callable[[bool], None] | None = None): + super().__init__(width, enabled) + self.toggle = Toggle(initial_state=initial_state, callback=callback) + + def set_touch_valid_callback(self, touch_callback: Callable[[], bool]) -> None: + super().set_touch_valid_callback(touch_callback) + self.toggle.set_touch_valid_callback(touch_callback) + + def _render(self, rect: rl.Rectangle) -> bool: + self.toggle.set_enabled(self.enabled) + clicked = self.toggle.render(rl.Rectangle(rect.x, rect.y + (rect.height - TOGGLE_HEIGHT) / 2, self._rect.width, TOGGLE_HEIGHT)) + return bool(clicked) + + def set_state(self, state: bool): + self.toggle.set_state(state) + + def get_state(self) -> bool: + return self.toggle.get_state() + + +class ButtonAction(ItemAction): + def __init__(self, text: str | Callable[[], str], width: int = BUTTON_WIDTH, enabled: bool | Callable[[], bool] = True): + super().__init__(width, enabled) + self._text_source = text + self._value_source: str | Callable[[], str] | None = None + self._pressed = False + self._font = gui_app.font(FontWeight.NORMAL) + + def pressed(): + self._pressed = True + + self._button = Button( + self.text, + font_size=BUTTON_FONT_SIZE, + font_weight=BUTTON_FONT_WEIGHT, + button_style=ButtonStyle.LIST_ACTION, + border_radius=BUTTON_BORDER_RADIUS, + click_callback=pressed, + text_padding=0, + ) + self.set_enabled(enabled) + + def get_width_hint(self) -> float: + value_text = self.value + if value_text: + text_width = measure_text_cached(self._font, value_text, ITEM_TEXT_FONT_SIZE).x + return text_width + BUTTON_WIDTH + TEXT_PADDING + else: + return BUTTON_WIDTH + + def set_touch_valid_callback(self, touch_callback: Callable[[], bool]) -> None: + super().set_touch_valid_callback(touch_callback) + self._button.set_touch_valid_callback(touch_callback) + + def set_text(self, text: str | Callable[[], str]): + self._text_source = text + + def set_value(self, value: str | Callable[[], str]): + self._value_source = value + + @property + def text(self): + return _resolve_value(self._text_source, tr("Error")) + + @property + def value(self): + return _resolve_value(self._value_source, "") + + def _render(self, rect: rl.Rectangle) -> bool: + self._button.set_text(self.text) + self._button.set_enabled(_resolve_value(self.enabled)) + button_rect = rl.Rectangle(rect.x + rect.width - BUTTON_WIDTH, rect.y + (rect.height - BUTTON_HEIGHT) / 2, BUTTON_WIDTH, BUTTON_HEIGHT) + self._button.render(button_rect) + + value_text = self.value + if value_text: + value_rect = rl.Rectangle(rect.x, rect.y, rect.width - BUTTON_WIDTH - TEXT_PADDING, rect.height) + gui_label(value_rect, value_text, font_size=ITEM_TEXT_FONT_SIZE, color=ITEM_TEXT_VALUE_COLOR, + font_weight=FontWeight.NORMAL, alignment=rl.GuiTextAlignment.TEXT_ALIGN_LEFT, + alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE) + + # TODO: just use the generic Widget click callbacks everywhere, no returning from render + pressed = self._pressed + self._pressed = False + return pressed + + +class TextAction(ItemAction): + def __init__(self, text: str | Callable[[], str], color: rl.Color = ITEM_TEXT_COLOR, enabled: bool | Callable[[], bool] = True): + self._text_source = text + self.color = color + + self._font = gui_app.font(FontWeight.NORMAL) + initial_text = _resolve_value(text, "") + text_width = measure_text_cached(self._font, initial_text, ITEM_TEXT_FONT_SIZE).x + super().__init__(int(text_width + TEXT_PADDING), enabled) + + @property + def text(self): + return _resolve_value(self._text_source, tr("Error")) + + def get_width_hint(self) -> float: + text_width = measure_text_cached(self._font, self.text, ITEM_TEXT_FONT_SIZE).x + return text_width + TEXT_PADDING + + def _render(self, rect: rl.Rectangle) -> bool: + gui_label(self._rect, self.text, font_size=ITEM_TEXT_FONT_SIZE, color=self.color, + font_weight=FontWeight.NORMAL, alignment=rl.GuiTextAlignment.TEXT_ALIGN_RIGHT, + alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE) + return False + + def set_text(self, text: str | Callable[[], str]): + self._text_source = text + + +class DualButtonAction(ItemAction): + def __init__(self, left_text: str | Callable[[], str], right_text: str | Callable[[], str], left_callback: Callable | None = None, + right_callback: Callable | None = None, enabled: bool | Callable[[], bool] = True): + super().__init__(width=0, enabled=enabled) # Width 0 means use full width + self.left_button = Button(left_text, click_callback=left_callback, button_style=ButtonStyle.NORMAL, text_padding=0) + self.right_button = Button(right_text, click_callback=right_callback, button_style=ButtonStyle.DANGER, text_padding=0) + + def set_touch_valid_callback(self, touch_callback: Callable[[], bool]) -> None: + super().set_touch_valid_callback(touch_callback) + self.left_button.set_touch_valid_callback(touch_callback) + self.right_button.set_touch_valid_callback(touch_callback) + + def _render(self, rect: rl.Rectangle): + button_spacing = 30 + button_height = 120 + button_width = (rect.width - button_spacing) / 2 + button_y = rect.y + (rect.height - button_height) / 2 + + left_rect = rl.Rectangle(rect.x, button_y, button_width, button_height) + right_rect = rl.Rectangle(rect.x + button_width + button_spacing, button_y, button_width, button_height) + + # expand one to full width if other is not visible + if not self.left_button.is_visible: + right_rect.x = rect.x + right_rect.width = rect.width + elif not self.right_button.is_visible: + left_rect.width = rect.width + + # Render buttons + self.left_button.render(left_rect) + self.right_button.render(right_rect) + + +class MultipleButtonAction(ItemAction): + def __init__(self, buttons: Sequence[str | Callable[[], str]], button_width: int, selected_index: int = 0, callback: Callable | None = None): + super().__init__(width=len(buttons) * button_width + (len(buttons) - 1) * RIGHT_ITEM_PADDING, enabled=True) + self.buttons = buttons + self.button_width = button_width + self.selected_button = selected_index + self.callback = callback + self._font = gui_app.font(FontWeight.MEDIUM) + + def set_selected_button(self, index: int): + if 0 <= index < len(self.buttons): + self.selected_button = index + + def get_selected_button(self) -> int: + return self.selected_button + + def _render(self, rect: rl.Rectangle): + spacing = RIGHT_ITEM_PADDING + button_y = rect.y + (rect.height - BUTTON_HEIGHT) / 2 + + for i, _text in enumerate(self.buttons): + button_x = rect.x + i * (self.button_width + spacing) + button_rect = rl.Rectangle(button_x, button_y, self.button_width, BUTTON_HEIGHT) + + # Check button state + mouse_pos = rl.get_mouse_position() + is_pressed = rl.check_collision_point_rec(mouse_pos, button_rect) and self.enabled and self.is_pressed + is_selected = i == self.selected_button + + # Button colors + if is_selected: + bg_color = rl.Color(51, 171, 76, 255) # Green + elif is_pressed: + bg_color = rl.Color(74, 74, 74, 255) # Dark gray + else: + bg_color = rl.Color(57, 57, 57, 255) # Gray + + if not self.enabled: + bg_color = rl.Color(bg_color.r, bg_color.g, bg_color.b, 150) # Dim + + # Draw button + rl.draw_rectangle_rounded(button_rect, 1.0, 20, bg_color) + + # Draw text + text = _resolve_value(_text, "") + text_size = measure_text_cached(self._font, text, 40) + text_x = button_x + (self.button_width - text_size.x) / 2 + text_y = button_y + (BUTTON_HEIGHT - text_size.y) / 2 + text_color = rl.Color(228, 228, 228, 255) if self.enabled else rl.Color(150, 150, 150, 255) + rl.draw_text_ex(self._font, text, rl.Vector2(text_x, text_y), 40, 0, text_color) + + def _handle_mouse_release(self, mouse_pos: MousePos): + spacing = RIGHT_ITEM_PADDING + button_y = self._rect.y + (self._rect.height - BUTTON_HEIGHT) / 2 + for i, _ in enumerate(self.buttons): + button_x = self._rect.x + i * (self.button_width + spacing) + button_rect = rl.Rectangle(button_x, button_y, self.button_width, BUTTON_HEIGHT) + if rl.check_collision_point_rec(mouse_pos, button_rect): + self.selected_button = i + if self.callback: + self.callback(i) + + +class ListItem(Widget): + def __init__(self, title: str | Callable[[], str] = "", icon: str | None = None, description: str | Callable[[], str] | None = None, + description_visible: bool = False, callback: Callable | None = None, + action_item: ItemAction | None = None): + super().__init__() + self._title = title + self.set_icon(icon) + self._description = description + self.description_visible = description_visible + self.callback = callback + self.description_opened_callback: Callable | None = None + self.action_item = action_item + + self.set_rect(rl.Rectangle(0, 0, ITEM_BASE_WIDTH, ITEM_BASE_HEIGHT)) + self._font = gui_app.font(FontWeight.NORMAL) + + self._html_renderer = HtmlRenderer(text="", text_size={ElementType.P: ITEM_DESC_FONT_SIZE}, + text_color=ITEM_DESC_TEXT_COLOR) + self._parse_description(self.description) + + # Cached properties for performance + self._prev_description: str | None = self.description + + def show_event(self): + super().show_event() + self._set_description_visible(False) + + def set_description_opened_callback(self, callback: Callable) -> None: + self.description_opened_callback = callback + + def set_touch_valid_callback(self, touch_callback: Callable[[], bool]) -> None: + super().set_touch_valid_callback(touch_callback) + if self.action_item: + self.action_item.set_touch_valid_callback(touch_callback) + + def set_parent_rect(self, parent_rect: rl.Rectangle): + super().set_parent_rect(parent_rect) + self._rect.width = parent_rect.width + + def _handle_mouse_release(self, mouse_pos: MousePos): + if not self.is_visible: + return + + # Check not in action rect + if self.action_item: + action_rect = self.get_right_item_rect(self._rect) + if rl.check_collision_point_rec(mouse_pos, action_rect): + # Click was on right item, don't toggle description + return + + self._set_description_visible(not self.description_visible) + + def _set_description_visible(self, visible: bool): + if self.description and self.description_visible != visible: + self.description_visible = visible + # do callback first in case receiver changes description + if self.description_visible and self.description_opened_callback is not None: + self.description_opened_callback() + # Call _update_state to catch any description changes + self._update_state() + + content_width = int(self._rect.width - ITEM_PADDING * 2) + self._rect.height = self.get_item_height(self._font, content_width) + + def _update_state(self): + # Detect changes if description is callback + new_description = self.description + if new_description != self._prev_description: + self._parse_description(new_description) + + def _render(self, _): + if not self.is_visible: + return + + # Don't draw items that are not in parent's viewport + if ((self._rect.y + self.rect.height) <= self._parent_rect.y or + self._rect.y >= (self._parent_rect.y + self._parent_rect.height)): + return + + content_x = self._rect.x + ITEM_PADDING + text_x = content_x + + # Only draw title and icon for items that have them + if self.title: + # Draw icon if present + if self.icon: + rl.draw_texture_ex(self._icon_texture, rl.Vector2(content_x, self._rect.y + (ITEM_BASE_HEIGHT - self._icon_texture.height) / 2), 0.0, 1.0, rl.WHITE) + text_x += ICON_SIZE + ITEM_PADDING + + # Draw main text + text_size = measure_text_cached(self._font, self.title, ITEM_TEXT_FONT_SIZE) + item_y = self._rect.y + (ITEM_BASE_HEIGHT - text_size.y) // 2 + rl.draw_text_ex(self._font, self.title, rl.Vector2(text_x, item_y), ITEM_TEXT_FONT_SIZE, 0, ITEM_TEXT_COLOR) + + # Draw description if visible + if self.description_visible: + content_width = int(self._rect.width - ITEM_PADDING * 2) + description_height = self._html_renderer.get_total_height(content_width) + description_rect = rl.Rectangle( + self._rect.x + ITEM_PADDING, + self._rect.y + ITEM_DESC_V_OFFSET, + content_width, + description_height + ) + self._html_renderer.render(description_rect) + + # Draw right item if present + if self.action_item: + right_rect = self.get_right_item_rect(self._rect) + right_rect.y = self._rect.y + if self.action_item.render(right_rect) and self.action_item.enabled: + # Right item was clicked/activated + if self.callback: + self.callback() + + def set_icon(self, icon: str | None): + self.icon = icon + self._icon_texture = gui_app.texture(os.path.join("icons", self.icon), ICON_SIZE, ICON_SIZE) if self.icon else None + + def set_description(self, description: str | Callable[[], str] | None): + self._description = description + + def _parse_description(self, new_desc): + self._html_renderer.parse_html_content(new_desc) + self._prev_description = new_desc + + @property + def title(self): + return _resolve_value(self._title, "") + + @property + def description(self): + return _resolve_value(self._description, "") + + def get_item_height(self, font: rl.Font, max_width: int) -> float: + if not self.is_visible: + return 0 + + height = float(ITEM_BASE_HEIGHT) + if self.description_visible: + description_height = self._html_renderer.get_total_height(max_width) + height += description_height - (ITEM_BASE_HEIGHT - ITEM_DESC_V_OFFSET) + ITEM_PADDING + return height + + def get_right_item_rect(self, item_rect: rl.Rectangle) -> rl.Rectangle: + if not self.action_item: + return rl.Rectangle(0, 0, 0, 0) + + right_width = self.action_item.get_width_hint() + if right_width == 0: # Full width action (like DualButtonAction) + return rl.Rectangle(item_rect.x + ITEM_PADDING, item_rect.y, + item_rect.width - (ITEM_PADDING * 2), ITEM_BASE_HEIGHT) + + # Clip width to available space, never overlapping this Item's title + content_width = item_rect.width - (ITEM_PADDING * 2) + title_width = measure_text_cached(self._font, self.title, ITEM_TEXT_FONT_SIZE).x + right_width = min(content_width - title_width, right_width) + + right_x = item_rect.x + item_rect.width - right_width + right_y = item_rect.y + return rl.Rectangle(right_x, right_y, right_width, ITEM_BASE_HEIGHT) + + +# Factory functions +def simple_item(title: str | Callable[[], str], callback: Callable | None = None) -> ListItem: + return ListItem(title=title, callback=callback) + + +def toggle_item(title: str | Callable[[], str], description: str | Callable[[], str] | None = None, initial_state: bool = False, + callback: Callable | None = None, icon: str = "", enabled: bool | Callable[[], bool] = True) -> ListItem: + action = ToggleAction(initial_state=initial_state, enabled=enabled, callback=callback) + return ListItem(title=title, description=description, action_item=action, icon=icon) + + +def button_item(title: str | Callable[[], str], button_text: str | Callable[[], str], description: str | Callable[[], str] | None = None, + callback: Callable | None = None, enabled: bool | Callable[[], bool] = True) -> ListItem: + action = ButtonAction(text=button_text, enabled=enabled) + return ListItem(title=title, description=description, action_item=action, callback=callback) + + +def text_item(title: str | Callable[[], str], value: str | Callable[[], str], description: str | Callable[[], str] | None = None, + callback: Callable | None = None, enabled: bool | Callable[[], bool] = True) -> ListItem: + action = TextAction(text=value, color=ITEM_TEXT_VALUE_COLOR, enabled=enabled) + return ListItem(title=title, description=description, action_item=action, callback=callback) + + +def dual_button_item(left_text: str | Callable[[], str], right_text: str | Callable[[], str], + left_callback: Callable | None = None, right_callback: Callable | None = None, + description: str | Callable[[], str] | None = None, enabled: bool | Callable[[], bool] = True) -> ListItem: + action = DualButtonAction(left_text, right_text, left_callback, right_callback, enabled) + return ListItem(title="", description=description, action_item=action) + + +def multiple_button_item(title: str | Callable[[], str], description: str | Callable[[], str], buttons: list[str | Callable[[], str]], selected_index: int, + button_width: int = BUTTON_WIDTH, callback: Callable | None = None, icon: str = ""): + action = MultipleButtonAction(buttons, button_width, selected_index, callback=callback) + return ListItem(title=title, description=description, icon=icon, action_item=action) diff --git a/openpilot/system/ui/widgets/mici_keyboard.py b/openpilot/system/ui/widgets/mici_keyboard.py new file mode 100644 index 0000000000..bc3041aa3c --- /dev/null +++ b/openpilot/system/ui/widgets/mici_keyboard.py @@ -0,0 +1,405 @@ +from enum import IntEnum +import pyray as rl +import numpy as np +from openpilot.system.ui.lib.application import gui_app, FontWeight, MousePos, MouseEvent +from openpilot.system.ui.lib.text_measure import measure_text_cached +from openpilot.system.ui.widgets import Widget +from openpilot.common.filter_simple import BounceFilter, FirstOrderFilter + +CHAR_FONT_SIZE = 42 +CHAR_NEAR_FONT_SIZE = CHAR_FONT_SIZE * 2 +SELECTED_CHAR_FONT_SIZE = 128 +CHAR_CAPS_FONT_SIZE = 38 # TODO: implement this +NUMBER_LAYER_SWITCH_FONT_SIZE = 24 +KEYBOARD_COLUMN_PADDING = 33 +KEYBOARD_ROW_PADDING = {0: 44, 1: 33, 2: 44} # TODO: 2 should be 116 with extra control keys added in + +KEY_TOUCH_AREA_OFFSET = 10 # px +KEY_DRAG_HYSTERESIS = 5 # px +KEY_MIN_ANIMATION_TIME = 0.075 # s + +DEBUG = False +ANIMATION_SCALE = 0.65 + + +def zip_repeat(a, b): + la, lb = len(a), len(b) + for i in range(max(la, lb)): + yield (a[i] if i < la else a[-1], + b[i] if i < lb else b[-1]) + + +def fast_euclidean_distance(dx, dy): + # https://en.wikibooks.org/wiki/Algorithms/Distance_approximations + max_d, min_d = abs(dx), abs(dy) + if max_d < min_d: + max_d, min_d = min_d, max_d + return 0.941246 * max_d + 0.41 * min_d + + +class Key(Widget): + def __init__(self, char: str, font_weight: FontWeight = FontWeight.SEMI_BOLD): + super().__init__() + self.char = char + self._font = gui_app.font(font_weight) + self._x_filter = BounceFilter(0.0, 0.1 * ANIMATION_SCALE, 1 / gui_app.target_fps) + self._y_filter = BounceFilter(0.0, 0.1 * ANIMATION_SCALE, 1 / gui_app.target_fps) + self._size_filter = BounceFilter(CHAR_FONT_SIZE, 0.1 * ANIMATION_SCALE, 1 / gui_app.target_fps) + self._alpha_filter = BounceFilter(1.0, 0.075 * ANIMATION_SCALE, 1 / gui_app.target_fps) + + self._color = rl.Color(255, 255, 255, 255) + + self._position_initialized = False + self.original_position = rl.Vector2(0, 0) + + def set_position(self, x: float, y: float, smooth: bool = True): + # Smooth keys within parent rect + base_y = self._parent_rect.y if self._parent_rect else 0.0 + local_y = y - base_y + + if not self._position_initialized: + self._x_filter.x = x + self._y_filter.x = local_y + # keep track of original position so dragging around feels consistent. also move touch area down a bit + self.original_position = rl.Vector2(x, local_y + KEY_TOUCH_AREA_OFFSET) + self._position_initialized = True + + if not smooth: + self._x_filter.x = x + self._y_filter.x = local_y + + self._rect.x = self._x_filter.update(x) + self._rect.y = base_y + self._y_filter.update(local_y) + + def set_alpha(self, alpha: float): + self._alpha_filter.update(alpha) + + def get_position(self) -> tuple[float, float]: + return self._rect.x, self._rect.y + + def _update_state(self): + self._color.a = min(int(255 * self._alpha_filter.x), 255) + + def _render(self, _): + # center char at rect position + text_size = measure_text_cached(self._font, self.char, self._get_font_size()) + x = self._rect.x + self._rect.width / 2 - text_size.x / 2 + y = self._rect.y + self._rect.height / 2 - text_size.y / 2 + rl.draw_text_ex(self._font, self.char, (x, y), self._get_font_size(), 0, self._color) + + if DEBUG: + rl.draw_circle(int(self._rect.x), int(self._rect.y), 5, rl.RED) # Debug: draw circle around key + rl.draw_rectangle_lines_ex(self._rect, 2, rl.RED) + + def set_font_size(self, size: float): + self._size_filter.update(size) + + def _get_font_size(self) -> int: + return round(self._size_filter.x) + + +class SmallKey(Key): + def __init__(self, chars: str): + super().__init__(chars, FontWeight.BOLD) + self._size_filter.x = NUMBER_LAYER_SWITCH_FONT_SIZE + + def set_font_size(self, size: float): + self._size_filter.update(size * (NUMBER_LAYER_SWITCH_FONT_SIZE / CHAR_FONT_SIZE)) + + +class IconKey(Key): + def __init__(self, icon: str, vertical_align: str = "center", char: str = "", icon_size: tuple[int, int] = (38, 38)): + super().__init__(char) + self._icon_size = icon_size + self._icon = gui_app.texture(icon, *icon_size) + self._vertical_align = vertical_align + + def set_icon(self, icon: str, icon_size: tuple[int, int] | None = None): + size = icon_size if icon_size is not None else self._icon_size + self._icon = gui_app.texture(icon, *size) + + def _render(self, _): + scale = np.interp(self._size_filter.x, [CHAR_FONT_SIZE, CHAR_NEAR_FONT_SIZE], [1, 1.5]) + + if self._vertical_align == "center": + dest_rec = rl.Rectangle(self._rect.x + (self._rect.width - self._icon.width * scale) / 2, + self._rect.y + (self._rect.height - self._icon.height * scale) / 2, + self._icon.width * scale, self._icon.height * scale) + src_rec = rl.Rectangle(0, 0, self._icon.width, self._icon.height) + rl.draw_texture_pro(self._icon, src_rec, dest_rec, rl.Vector2(0, 0), 0, self._color) + + elif self._vertical_align == "bottom": + dest_rec = rl.Rectangle(self._rect.x + (self._rect.width - self._icon.width * scale) / 2, self._rect.y, + self._icon.width * scale, self._icon.height * scale) + src_rec = rl.Rectangle(0, 0, self._icon.width, self._icon.height) + rl.draw_texture_pro(self._icon, src_rec, dest_rec, rl.Vector2(0, 0), 0, self._color) + + if DEBUG: + rl.draw_circle(int(self._rect.x), int(self._rect.y), 5, rl.RED) # Debug: draw circle around key + rl.draw_rectangle_lines_ex(self._rect, 2, rl.RED) + + +class CapsState(IntEnum): + LOWER = 0 + UPPER = 1 + LOCK = 2 + + +class MiciKeyboard(Widget): + def __init__(self, auto_return_to_letters: str = ""): + super().__init__() + self._auto_return_to_letters = auto_return_to_letters + + lower_chars = [ + "qwertyuiop", + "asdfghjkl", + "zxcvbnm", + ] + upper_chars = ["".join([char.upper() for char in row]) for row in lower_chars] + special_chars = [ + "1234567890", + "-/:;()$&@\"", + "~.,?!'#%", + ] + super_special_chars = [ + "1234567890", + "`[]{}^*+=_", + "\\|<>¥€£•", + ] + + self._lower_keys = [[Key(char) for char in row] for row in lower_chars] + self._upper_keys = [[Key(char) for char in row] for row in upper_chars] + self._special_keys = [[Key(char) for char in row] for row in special_chars] + self._super_special_keys = [[Key(char) for char in row] for row in super_special_chars] + + # control keys + self._space_key = IconKey("icons_mici/settings/keyboard/space.png", char=" ", vertical_align="bottom", icon_size=(43, 14)) + self._caps_key = IconKey("icons_mici/settings/keyboard/caps_lower.png", icon_size=(38, 33)) + # these two are in different places on some layouts + self._123_key, self._123_key2 = SmallKey("123"), SmallKey("123") + self._abc_key = SmallKey("abc") + self._super_special_key = SmallKey("#+=") + + # insert control keys + for keys in (self._lower_keys, self._upper_keys): + keys[2].insert(0, self._caps_key) + keys[2].append(self._123_key) + + for keys in (self._lower_keys, self._upper_keys, self._special_keys, self._super_special_keys): + keys[1].append(self._space_key) + + for keys in (self._special_keys, self._super_special_keys): + keys[2].append(self._abc_key) + + self._special_keys[2].insert(0, self._super_special_key) + self._super_special_keys[2].insert(0, self._123_key2) + + # set initial keys + self._current_keys: list[list[Key]] = [] + self._set_keys(self._lower_keys) + self._caps_state = CapsState.LOWER + self._initialized = False + + self._load_images() + + self._closest_key: tuple[Key | None, float] = None, float('inf') + self._selected_key_t: float | None = None # time key was initially selected + self._unselect_key_t: float | None = None # time to unselect key after release + self._dragging_on_keyboard = False + + self._text: str = "" + + self._bg_scale_filter = BounceFilter(1.0, 0.1 * ANIMATION_SCALE, 1 / gui_app.target_fps) + self._selected_key_filter = FirstOrderFilter(0.0, 0.075 * ANIMATION_SCALE, 1 / gui_app.target_fps) + + def get_candidate_character(self) -> str: + # return str of character about to be added to text + key = self._closest_key[0] + return key.char if key is not None and key.__class__ is Key and self._dragging_on_keyboard else "" + + def get_keyboard_height(self) -> int: + return int(self._txt_bg.height) + + def _load_images(self): + self._txt_bg = gui_app.texture("icons_mici/settings/keyboard/keyboard_background.png", 520, 170, keep_aspect_ratio=False) + + def _set_keys(self, keys: list[list[Key]]): + # inherit previous keys' positions to fix switching animation + for current_row, row in zip(self._current_keys, keys, strict=False): + # not all layouts have the same number of keys + for current_key, key in zip_repeat(current_row, row): + # reset parent rect for new keys + key.set_parent_rect(self._rect) + current_pos = current_key.get_position() + key.set_position(current_pos[0], current_pos[1], smooth=False) + + self._current_keys = keys + + def set_text(self, text: str): + self._text = text + + def text(self) -> str: + return self._text + + def _handle_mouse_event(self, mouse_event: MouseEvent) -> None: + keyboard_pos_y = self._rect.y + self._rect.height - self._txt_bg.height + if mouse_event.left_pressed: + if mouse_event.pos.y > keyboard_pos_y: + self._dragging_on_keyboard = True + elif mouse_event.left_released: + self._dragging_on_keyboard = False + + if mouse_event.left_down and self._dragging_on_keyboard: + self._closest_key = self._get_closest_key() + if self._selected_key_t is None: + self._selected_key_t = rl.get_time() + + # unselect key temporarily if mouse goes above keyboard + if mouse_event.pos.y <= keyboard_pos_y: + self._closest_key = (None, float('inf')) + + if DEBUG: + print('HANDLE MOUSE EVENT', mouse_event, self._closest_key[0].char if self._closest_key[0] else 'None') + + def _get_closest_key(self) -> tuple[Key | None, float]: + closest_key: tuple[Key | None, float] = (None, float('inf')) + for row in self._current_keys: + for key in row: + mouse_pos = gui_app.last_mouse_event.pos + # approximate distance for comparison is accurate enough + # use local y coords so parent widget offset (e.g. during NavWidget animate-in) doesn't affect hit testing + dist = abs(key.original_position.x - mouse_pos.x) + abs(key.original_position.y - (mouse_pos.y - self._rect.y)) + if dist < closest_key[1]: + if self._closest_key[0] is None or key is self._closest_key[0] or dist < self._closest_key[1] - KEY_DRAG_HYSTERESIS: + closest_key = (key, dist) + return closest_key + + def _set_uppercase(self, cycle: bool): + self._set_keys(self._upper_keys if cycle else self._lower_keys) + if not cycle: + self._caps_state = CapsState.LOWER + self._caps_key.set_icon("icons_mici/settings/keyboard/caps_lower.png", icon_size=(38, 33)) + else: + if self._caps_state == CapsState.LOWER: + self._caps_state = CapsState.UPPER + self._caps_key.set_icon("icons_mici/settings/keyboard/caps_upper.png", icon_size=(38, 33)) + elif self._caps_state == CapsState.UPPER: + self._caps_state = CapsState.LOCK + self._caps_key.set_icon("icons_mici/settings/keyboard/caps_lock.png", icon_size=(39, 38)) + else: + self._set_uppercase(False) + + def _handle_mouse_release(self, mouse_pos: MousePos): + if self._closest_key[0] is not None: + if self._closest_key[0] == self._caps_key: + self._set_uppercase(True) + elif self._closest_key[0] in (self._123_key, self._123_key2): + self._set_keys(self._special_keys) + elif self._closest_key[0] == self._abc_key: + self._set_uppercase(False) + elif self._closest_key[0] == self._super_special_key: + self._set_keys(self._super_special_keys) + else: + self._text += self._closest_key[0].char + + # Reset caps state + if self._caps_state == CapsState.UPPER: + self._set_uppercase(False) + + # Switch back to letters after common URL delimiters + if self._closest_key[0].char in self._auto_return_to_letters and self._current_keys in (self._special_keys, self._super_special_keys): + self._set_uppercase(False) + + # ensure minimum selected animation time + key_selected_dt = rl.get_time() - (self._selected_key_t or 0) + cur_t = rl.get_time() + self._unselect_key_t = cur_t + KEY_MIN_ANIMATION_TIME if (key_selected_dt < KEY_MIN_ANIMATION_TIME) else cur_t + + def backspace(self): + if self._text: + self._text = self._text[:-1] + + def space(self): + self._text += ' ' + + def _update_state(self): + # update selected key filter + self._selected_key_filter.update(self._closest_key[0] is not None) + + # unselect key after animation plays + if (self._unselect_key_t is not None and rl.get_time() > self._unselect_key_t) or not self.enabled: + self._closest_key = (None, float('inf')) + self._unselect_key_t = None + self._selected_key_t = None + + def _lay_out_keys(self, bg_x, bg_y, keys: list[list[Key]]): + key_rect = rl.Rectangle(bg_x, bg_y, self._txt_bg.width, self._txt_bg.height) + for row_idx, row in enumerate(keys): + padding = KEYBOARD_ROW_PADDING[row_idx] + step_y = (key_rect.height - 2 * KEYBOARD_COLUMN_PADDING) / (len(keys) - 1) + for key_idx, key in enumerate(row): + key_x = key_rect.x + padding + key_idx * ((key_rect.width - 2 * padding) / (len(row) - 1)) + key_y = key_rect.y + KEYBOARD_COLUMN_PADDING + row_idx * step_y + + if self._closest_key[0] is None: + key.set_alpha(1.0) + key.set_font_size(CHAR_FONT_SIZE) + elif key == self._closest_key[0]: + # push key up with a max and inward so user can see key easier + key_y = max(key_y - 120, 40) + key_x += np.interp(key_x, [self._rect.x, self._rect.x + self._rect.width], [100, -100]) + key.set_alpha(1.0) + key.set_font_size(SELECTED_CHAR_FONT_SIZE) + + # draw black circle behind selected key + circle_alpha = int(self._selected_key_filter.x * 225) + rl.draw_circle_gradient(rl.Vector2(key_x + key.rect.width / 2, key_y + key.rect.height / 2), + SELECTED_CHAR_FONT_SIZE, rl.Color(0, 0, 0, circle_alpha), rl.BLANK) + else: + # move other keys away from selected key a bit + dx = key.original_position.x - self._closest_key[0].original_position.x + dy = key.original_position.y - self._closest_key[0].original_position.y + distance_from_selected_key = fast_euclidean_distance(dx, dy) + + inv = 1 / (distance_from_selected_key or 1.0) + ux = dx * inv + uy = dy * inv + + # NOTE: hardcode to 20 to get entire keyboard to move + push_pixels = np.interp(distance_from_selected_key, [0, 250], [20, 0]) + key_x += ux * push_pixels + key_y += uy * push_pixels + + # TODO: slow enough to use an approximation or nah? also caching might work + font_size = np.interp(distance_from_selected_key, [0, 150], [CHAR_NEAR_FONT_SIZE, CHAR_FONT_SIZE]) + + key_alpha = np.interp(distance_from_selected_key, [0, 100], [1.0, 0.35]) + key.set_alpha(key_alpha) + key.set_font_size(font_size) + + # TODO: I like the push amount, so we should clip the pos inside the keyboard rect + key.set_parent_rect(self._rect) + key.set_position(key_x, key_y) + + def _render(self, _): + # draw bg + bg_x = self._rect.x + (self._rect.width - self._txt_bg.width) / 2 + bg_y = self._rect.y + self._rect.height - self._txt_bg.height + + scale = self._bg_scale_filter.update(1.0307692307692307 if self._closest_key[0] is not None else 1.0) + src_rec = rl.Rectangle(0, 0, self._txt_bg.width, self._txt_bg.height) + dest_rec = rl.Rectangle(self._rect.x + self._rect.width / 2 - self._txt_bg.width * scale / 2, bg_y, + self._txt_bg.width * scale, self._txt_bg.height) + + rl.draw_texture_pro(self._txt_bg, src_rec, dest_rec, rl.Vector2(0, 0), 0.0, rl.WHITE) + + # draw keys + if not self._initialized: + for keys in (self._lower_keys, self._upper_keys, self._special_keys, self._super_special_keys): + self._lay_out_keys(bg_x, bg_y, keys) + self._initialized = True + + self._lay_out_keys(bg_x, bg_y, self._current_keys) + for row in self._current_keys: + for key in row: + key.render() diff --git a/openpilot/system/ui/widgets/nav_widget.py b/openpilot/system/ui/widgets/nav_widget.py new file mode 100644 index 0000000000..58ff8123bb --- /dev/null +++ b/openpilot/system/ui/widgets/nav_widget.py @@ -0,0 +1,229 @@ +from __future__ import annotations + +import abc +import pyray as rl +from collections.abc import Callable +from openpilot.system.ui.widgets import Widget +from openpilot.common.filter_simple import BounceFilter, FirstOrderFilter +from openpilot.system.ui.lib.application import gui_app, MousePos, MouseEvent + +SWIPE_AWAY_THRESHOLD = 80 # px to dismiss after releasing +START_DISMISSING_THRESHOLD = 40 # px to start dismissing while dragging +BLOCK_SWIPE_AWAY_THRESHOLD = 60 # px horizontal movement to block swipe away + +NAV_BAR_MARGIN = 6 +NAV_BAR_WIDTH = 205 +NAV_BAR_HEIGHT = 8 + +DISMISS_PUSH_OFFSET = NAV_BAR_MARGIN + NAV_BAR_HEIGHT + 50 # px extra to push down when dismissing +DISMISS_ANIMATION_RC = 0.2 # slightly slower for non-user triggered dismiss animation + + +class NavBar(Widget): + FADE_AFTER_SECONDS = 2.0 + + def __init__(self): + super().__init__() + self.set_rect(rl.Rectangle(0, 0, NAV_BAR_WIDTH, NAV_BAR_HEIGHT)) + self._alpha = 1.0 + self._alpha_filter = FirstOrderFilter(1.0, 0.1, 1 / gui_app.target_fps) + self._fade_time = 0.0 + + def set_alpha(self, alpha: float) -> None: + self._alpha = alpha + self._fade_time = rl.get_time() + + def show_event(self): + super().show_event() + self._alpha = 1.0 + self._alpha_filter.x = 1.0 + self._fade_time = rl.get_time() + + def _render(self, _): + if rl.get_time() - self._fade_time > self.FADE_AFTER_SECONDS: + self._alpha = 0.0 + alpha = self._alpha_filter.update(self._alpha) + + # white bar with black border + rl.draw_rectangle_rounded(self._rect, 1.0, 6, rl.Color(255, 255, 255, int(255 * 0.9 * alpha))) + rl.draw_rectangle_rounded_lines_ex(self._rect, 1.0, 6, 2, rl.Color(0, 0, 0, int(255 * 0.3 * alpha))) + + +class NavWidget(Widget, abc.ABC): + """ + A full screen widget that supports back navigation by swiping down from the top. + """ + BACK_TOUCH_AREA_PERCENTAGE = 0.65 + + def __init__(self): + super().__init__() + # State + self._drag_start_pos: MousePos | None = None # cleared after certain amount of horizontal movement + self._dragging_down = False # swiped down enough to trigger dismissing on release + self._playing_dismiss_animation = False # released and animating away + self._y_pos_filter = BounceFilter(0.0, 0.1, 1 / gui_app.target_fps, bounce=1) + + self._back_callback: Callable[[], None] | None = None # persistent callback for user-initiated back navigation + self._dismiss_callback: Callable[[], None] | None = None # transient callback for programmatic dismiss + # TODO: add this functionality to push_widget + self._shown_callback: Callable[[], None] | None = None # transient callback fired after show animation completes + + # TODO: move this state into NavBar + self._nav_bar = self._child(NavBar()) + self._nav_bar_show_time = 0.0 + self._nav_bar_y_filter = FirstOrderFilter(0.0, 0.1, 1 / gui_app.target_fps) + + def _back_enabled(self) -> bool: + # Children can override this to block swipe away, like when not at + # the top of a vertical scroll panel to prevent erroneous swipes + return True + + def set_back_callback(self, callback: Callable[[], None] | None) -> None: + self._back_callback = callback + + def set_shown_callback(self, callback: Callable[[], None] | None) -> None: + self._shown_callback = callback + + def _handle_mouse_event(self, mouse_event: MouseEvent) -> None: + super()._handle_mouse_event(mouse_event) + + # Don't let touch events change filter state during dismiss animation + if self._playing_dismiss_animation: + return + + if mouse_event.left_pressed: + # user is able to swipe away if starting near top of screen + self._y_pos_filter.update_alpha(0.04) + in_dismiss_area = mouse_event.pos.y < self._rect.height * self.BACK_TOUCH_AREA_PERCENTAGE + + if in_dismiss_area and self._back_enabled(): + self._drag_start_pos = mouse_event.pos + + elif mouse_event.left_down: + if self._drag_start_pos is not None: + # block swiping away if too much horizontal or upward movement + # block (lock-in) threshold is higher than start dismissing + horizontal_movement = abs(mouse_event.pos.x - self._drag_start_pos.x) > BLOCK_SWIPE_AWAY_THRESHOLD + upward_movement = mouse_event.pos.y - self._drag_start_pos.y < -BLOCK_SWIPE_AWAY_THRESHOLD + + if not (horizontal_movement or upward_movement): + # no blocking movement, check if we should start dismissing + if mouse_event.pos.y - self._drag_start_pos.y > START_DISMISSING_THRESHOLD: + self._dragging_down = True + else: + if not self._dragging_down: + self._drag_start_pos = None + + elif mouse_event.left_released: + # reset rc for either slide up or down animation + self._y_pos_filter.update_alpha(0.1) + + # if far enough, trigger back navigation callback + if self._drag_start_pos is not None: + if mouse_event.pos.y - self._drag_start_pos.y > SWIPE_AWAY_THRESHOLD: + self._playing_dismiss_animation = True + + self._drag_start_pos = None + self._dragging_down = False + + def _update_state(self): + super()._update_state() + + new_y = 0.0 + + if self._dragging_down: + self._nav_bar.set_alpha(1.0) + + # FIXME: disabling this widget on new push_widget still causes this widget to track mouse events without mouse down + if not self.enabled: + self._drag_start_pos = None + + if self._drag_start_pos is not None: + last_mouse_event = gui_app.last_mouse_event + # push entire widget as user drags it away + new_y = max(last_mouse_event.pos.y - self._drag_start_pos.y, 0) + if new_y < SWIPE_AWAY_THRESHOLD: + new_y /= 2 # resistance until mouse release would dismiss widget + + if self._playing_dismiss_animation: + new_y = self._rect.height + DISMISS_PUSH_OFFSET + + new_y = self._y_pos_filter.update(new_y) + if abs(new_y) < 1 and abs(self._y_pos_filter.velocity.x) < 0.5: + new_y = self._y_pos_filter.x = 0.0 + self._y_pos_filter.velocity.x = 0.0 + + if self._shown_callback is not None: + self._shown_callback() + self._shown_callback = None + + if new_y > self._rect.height + DISMISS_PUSH_OFFSET - 10: + gui_app.pop_widget() + + # Only one callback should ever be fired + if self._dismiss_callback is not None: + self._dismiss_callback() + self._dismiss_callback = None + elif self._back_callback is not None: + self._back_callback() + + self._playing_dismiss_animation = False + self._drag_start_pos = None + self._dragging_down = False + + self.set_position(self._rect.x, new_y) + + def _layout(self): + # Dim whatever is behind this widget, fading with position (runs after _update_state so position is correct) + overlay_alpha = int(200 * max(0.0, min(1.0, 1.0 - self._rect.y / self._rect.height))) if self._rect.height > 0 else 0 + rl.draw_rectangle_rec(rl.Rectangle(0, 0, self._rect.width, self._rect.height), rl.Color(0, 0, 0, overlay_alpha)) + + bounce_height = 20 + rl.draw_rectangle_rec(rl.Rectangle(self._rect.x, self._rect.y, self._rect.width, self._rect.height + bounce_height), rl.BLACK) + + def render(self, rect: rl.Rectangle | None = None) -> bool | int | None: + ret = super().render(rect) + + bar_x = self._rect.x + (self._rect.width - self._nav_bar.rect.width) / 2 + nav_bar_delayed = rl.get_time() - self._nav_bar_show_time < 0.4 + # User dragging or dismissing, nav bar follows NavWidget + if self._drag_start_pos is not None or self._playing_dismiss_animation: + self._nav_bar_y_filter.x = NAV_BAR_MARGIN + self._y_pos_filter.x + # Waiting to show + elif nav_bar_delayed: + self._nav_bar_y_filter.x = -NAV_BAR_MARGIN - NAV_BAR_HEIGHT + # Animate back to top + else: + self._nav_bar_y_filter.update(NAV_BAR_MARGIN) + + self._nav_bar.set_position(bar_x, self._nav_bar_y_filter.x) + self._nav_bar.render() + + return ret + + @property + def is_dismissing(self) -> bool: + return self._dragging_down or self._playing_dismiss_animation + + def dismiss(self, callback: Callable[[], None] | None = None): + """Programmatically trigger the dismiss animation. Calls pop_widget when done, then callback.""" + if not self._playing_dismiss_animation: + self._playing_dismiss_animation = True + self._y_pos_filter.update_alpha(DISMISS_ANIMATION_RC) + self._dismiss_callback = callback + + def show_event(self): + super().show_event() + + # Reset state + self._drag_start_pos = None + self._dragging_down = False + self._playing_dismiss_animation = False + self._dismiss_callback = None + # Start NavWidget off-screen, no matter how tall it is + self._y_pos_filter.update_alpha(0.1) + self._y_pos_filter.x = gui_app.height + self._y_pos_filter.velocity.x = 0.0 + + self._nav_bar_y_filter.x = -NAV_BAR_MARGIN - NAV_BAR_HEIGHT + self._nav_bar_show_time = rl.get_time() diff --git a/openpilot/system/ui/widgets/network.py b/openpilot/system/ui/widgets/network.py new file mode 100644 index 0000000000..fb999c0441 --- /dev/null +++ b/openpilot/system/ui/widgets/network.py @@ -0,0 +1,495 @@ +from enum import IntEnum +from functools import partial +from typing import Any, cast + +import pyray as rl +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.lib.scroll_panel import GuiScrollPanel +from openpilot.system.ui.lib.wifi_manager import WifiManager, SecurityType, Network, MeteredType, normalize_ssid +from openpilot.system.ui.widgets import DialogResult, Widget +from openpilot.system.ui.widgets.button import ButtonStyle, Button +from openpilot.system.ui.widgets.confirm_dialog import ConfirmDialog +from openpilot.system.ui.widgets.keyboard import Keyboard +from openpilot.system.ui.widgets.label import gui_label +from openpilot.system.ui.widgets.scroller_tici import Scroller +from openpilot.system.ui.widgets.list_view import ButtonAction, ListItem, MultipleButtonAction, ToggleAction, button_item, text_item + +if gui_app.sunnypilot_ui(): + from openpilot.system.ui.sunnypilot.widgets.list_view import button_item_sp as button_item + from openpilot.system.ui.sunnypilot.widgets.list_view import ListItemSP as ListItem + from openpilot.system.ui.sunnypilot.widgets.list_view import ToggleActionSP as ToggleAction + from openpilot.system.ui.sunnypilot.widgets.list_view import MultipleButtonActionSP as MultipleButtonAction + +# These are only used for AdvancedNetworkSettings, standalone apps just need WifiManagerUI +try: + from openpilot.common.params import Params + from openpilot.selfdrive.ui.ui_state import ui_state + from openpilot.selfdrive.ui.lib.prime_state import PrimeType +except Exception: + Params: Any = None + ui_state: Any = None + PrimeType: Any = None + +NM_DEVICE_STATE_NEED_AUTH = 60 +MIN_PASSWORD_LENGTH = 8 +MAX_PASSWORD_LENGTH = 64 +ITEM_HEIGHT = 160 +ICON_SIZE = 50 + +STRENGTH_ICONS = [ + "icons/wifi_strength_low.png", + "icons/wifi_strength_medium.png", + "icons/wifi_strength_high.png", + "icons/wifi_strength_full.png", +] + + +class PanelType(IntEnum): + WIFI = 0 + ADVANCED = 1 + + +class UIState(IntEnum): + IDLE = 0 + CONNECTING = 1 + NEEDS_AUTH = 2 + SHOW_FORGET_CONFIRM = 3 + FORGETTING = 4 + + +class NavButton(Widget): + def __init__(self, text: str): + super().__init__() + self.text = text + self.set_rect(rl.Rectangle(0, 0, 400, 100)) + + def _render(self, _): + color = rl.Color(74, 74, 74, 255) if self.is_pressed else rl.Color(57, 57, 57, 255) + rl.draw_rectangle_rounded(self._rect, 0.6, 10, color) + gui_label(self.rect, self.text, font_size=60, alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER) + + +class NetworkUI(Widget): + def __init__(self, wifi_manager: WifiManager): + super().__init__() + self._wifi_manager = wifi_manager + self._current_panel: PanelType = PanelType.WIFI + self._wifi_panel = self._child(WifiManagerUI(wifi_manager)) + self._advanced_panel = self._child(AdvancedNetworkSettings(wifi_manager)) + self._nav_button = self._child(NavButton(tr("Advanced"))) + self._nav_button.set_click_callback(self._cycle_panel) + + def show_event(self): + super().show_event() + self._set_current_panel(PanelType.WIFI) + + def _cycle_panel(self): + if self._current_panel == PanelType.WIFI: + self._set_current_panel(PanelType.ADVANCED) + else: + self._set_current_panel(PanelType.WIFI) + + def _render(self, _): + # subtract button + content_rect = rl.Rectangle(self._rect.x, self._rect.y + self._nav_button.rect.height + 40, + self._rect.width, self._rect.height - self._nav_button.rect.height - 40) + if self._current_panel == PanelType.WIFI: + self._nav_button.text = tr("Advanced") + self._nav_button.set_position(self._rect.x + self._rect.width - self._nav_button.rect.width, self._rect.y + 20) + self._wifi_panel.render(content_rect) + else: + self._nav_button.text = tr("Back") + self._nav_button.set_position(self._rect.x, self._rect.y + 20) + self._advanced_panel.render(content_rect) + + self._nav_button.render() + + def _set_current_panel(self, panel: PanelType): + self._current_panel = panel + + +class AdvancedNetworkSettings(Widget): + def __init__(self, wifi_manager: WifiManager): + # AdvancedNetworkSettings needs the full openpilot environment, standalone apps just use WifiManagerUI + from openpilot.common.params import Params + from openpilot.selfdrive.ui.ui_state import ui_state + from openpilot.selfdrive.ui.lib.prime_state import PrimeType + super().__init__() + self._wifi_manager = wifi_manager + self._wifi_manager.add_callbacks(networks_updated=self._on_network_updated) + self._params = Params() + self._prime_state = ui_state.prime_state + self._cell_prime_types = (PrimeType.NONE, PrimeType.LITE) + + self._keyboard = Keyboard(max_text_size=MAX_PASSWORD_LENGTH, min_text_size=MIN_PASSWORD_LENGTH, show_password_toggle=True) + + # Tethering + self._tethering_action = ToggleAction(initial_state=False) + tethering_btn = ListItem(lambda: tr("Enable Tethering"), action_item=self._tethering_action, callback=self._toggle_tethering) + + # Edit tethering password + self._tethering_password_action = ButtonAction(lambda: tr("EDIT")) + tethering_password_btn = ListItem(lambda: tr("Tethering Password"), action_item=self._tethering_password_action, callback=self._edit_tethering_password) + + # Roaming toggle + roaming_enabled = self._params.get_bool("GsmRoaming") + self._roaming_action = ToggleAction(initial_state=roaming_enabled) + self._roaming_btn = ListItem(lambda: tr("Enable Roaming"), action_item=self._roaming_action, callback=self._toggle_roaming) + + # Cellular metered toggle + cellular_metered = self._params.get_bool("GsmMetered") + self._cellular_metered_action = ToggleAction(initial_state=cellular_metered) + self._cellular_metered_btn = ListItem(lambda: tr("Cellular Metered"), + description=lambda: tr("Prevent large data uploads when on a metered cellular connection"), + action_item=self._cellular_metered_action, callback=self._toggle_cellular_metered) + + # APN setting + self._apn_btn = button_item(lambda: tr("APN Setting"), lambda: tr("EDIT"), callback=self._edit_apn) + + # Wi-Fi metered toggle + self._wifi_metered_action = MultipleButtonAction([lambda: tr("default"), lambda: tr("metered"), lambda: tr("unmetered")], 255, 0, + callback=self._toggle_wifi_metered) + wifi_metered_btn = ListItem(lambda: tr("Wi-Fi Network Metered"), description=lambda: tr("Prevent large data uploads when on a metered Wi-Fi connection"), + action_item=self._wifi_metered_action) + + items: list[Widget] = [ + tethering_btn, + tethering_password_btn, + text_item(lambda: tr("IP Address"), lambda: self._wifi_manager.ipv4_address), + self._roaming_btn, + self._apn_btn, + self._cellular_metered_btn, + wifi_metered_btn, + button_item(lambda: tr("Hidden Network"), lambda: tr("CONNECT"), callback=self._connect_to_hidden_network), + ] + + self._scroller = Scroller(items, line_separator=True, spacing=0) + + def _on_network_updated(self, networks: list[Network]): + self._tethering_action.set_enabled(True) + self._tethering_action.set_state(self._wifi_manager.is_tethering_active()) + self._tethering_password_action.set_enabled(True) + + if self._wifi_manager.is_tethering_active() or self._wifi_manager.ipv4_address == "": + self._wifi_metered_action.set_enabled(False) + self._wifi_metered_action.selected_button = 0 + elif self._wifi_manager.ipv4_address != "": + metered = self._wifi_manager.current_network_metered + self._wifi_metered_action.set_enabled(True) + self._wifi_metered_action.selected_button = int(metered) if metered in (MeteredType.UNKNOWN, MeteredType.YES, MeteredType.NO) else 0 + + def _toggle_tethering(self): + checked = self._tethering_action.get_state() + self._tethering_action.set_enabled(False) + if checked: + self._wifi_metered_action.set_enabled(False) + self._wifi_manager.set_tethering_active(checked) + + def _toggle_roaming(self): + self._params.put_bool("GsmRoaming", self._roaming_action.get_state(), block=True) + + def _edit_apn(self): + def update_apn(result: DialogResult): + if result != DialogResult.CONFIRM: + return + + apn = self._keyboard.text.strip() + if apn == "": + self._params.remove("GsmApn") + else: + self._params.put("GsmApn", apn, block=True) + + current_apn = self._params.get("GsmApn") or "" + self._keyboard.reset(min_text_size=0) + self._keyboard.set_title(tr("Enter APN"), tr("leave blank for automatic configuration")) + self._keyboard.set_text(current_apn) + self._keyboard.set_callback(update_apn) + gui_app.push_widget(self._keyboard) + + def _toggle_cellular_metered(self): + self._params.put_bool("GsmMetered", self._cellular_metered_action.get_state(), block=True) + + def _toggle_wifi_metered(self, metered): + metered_type = {0: MeteredType.UNKNOWN, 1: MeteredType.YES, 2: MeteredType.NO}.get(metered, MeteredType.UNKNOWN) + self._wifi_metered_action.set_enabled(False) + self._wifi_manager.set_current_network_metered(metered_type) + + def _connect_to_hidden_network(self): + def connect_hidden(result: DialogResult): + if result != DialogResult.CONFIRM: + return + + ssid = self._keyboard.text + if not ssid: + return + + def enter_password(result: DialogResult): + if result != DialogResult.CONFIRM: + return + + password = self._keyboard.text + if password == "": + # connect without password + self._wifi_manager.connect_to_network(ssid, "", hidden=True) + return + + self._wifi_manager.connect_to_network(ssid, password, hidden=True) + + self._keyboard.reset(min_text_size=0) + self._keyboard.set_title(tr("Enter password"), tr("for \"{}\"").format(ssid)) + self._keyboard.set_callback(enter_password) + gui_app.push_widget(self._keyboard) + + self._keyboard.reset(min_text_size=1) + self._keyboard.set_title(tr("Enter SSID"), "") + self._keyboard.set_callback(connect_hidden) + gui_app.push_widget(self._keyboard) + + def _edit_tethering_password(self): + def update_password(result: DialogResult): + if result != DialogResult.CONFIRM: + return + + password = self._keyboard.text + self._wifi_manager.set_tethering_password(password) + self._tethering_password_action.set_enabled(False) + + self._keyboard.reset(min_text_size=MIN_PASSWORD_LENGTH) + self._keyboard.set_title(tr("Enter new tethering password"), "") + self._keyboard.set_text(self._wifi_manager.tethering_password) + self._keyboard.set_callback(update_password) + gui_app.push_widget(self._keyboard) + + def _update_state(self): + self._wifi_manager.process_callbacks() + + # If not using prime SIM, show GSM settings and enable IPv4 forwarding + show_cell_settings = self._prime_state.get_type() in self._cell_prime_types + self._wifi_manager.set_ipv4_forward(show_cell_settings) + self._roaming_btn.set_visible(show_cell_settings) + self._apn_btn.set_visible(show_cell_settings) + self._cellular_metered_btn.set_visible(show_cell_settings) + + def _render(self, _): + self._scroller.render(self._rect) + + +class WifiManagerUI(Widget): + def __init__(self, wifi_manager: WifiManager): + super().__init__() + self._wifi_manager = wifi_manager + self.state: UIState = UIState.IDLE + self._state_network: Network | None = None # for CONNECTING / NEEDS_AUTH / SHOW_FORGET_CONFIRM / FORGETTING + self._password_retry: bool = False # for NEEDS_AUTH + self.btn_width: int = 200 + self.scroll_panel = GuiScrollPanel() + self.keyboard = Keyboard(max_text_size=MAX_PASSWORD_LENGTH, min_text_size=MIN_PASSWORD_LENGTH, show_password_toggle=True) + self._load_icons() + + self._networks: list[Network] = [] + self._networks_buttons: dict[str, Button] = {} + self._forget_networks_buttons: dict[str, Button] = {} + + self._wifi_manager.add_callbacks(need_auth=self._on_need_auth, + activated=self._on_activated, + forgotten=self._on_forgotten, + networks_updated=self._on_network_updated, + disconnected=self._on_disconnected) + + def show_event(self): + super().show_event() + # start/stop scanning when widget is visible + self._wifi_manager.set_active(True) + + def hide_event(self): + super().hide_event() + self._wifi_manager.set_active(False) + + def _load_icons(self): + for icon in STRENGTH_ICONS + ["icons/checkmark.png", "icons/circled_slash.png", "icons/lock_closed.png"]: + gui_app.texture(icon, ICON_SIZE, ICON_SIZE) + + def _update_state(self): + self._wifi_manager.process_callbacks() + + def _render(self, rect: rl.Rectangle): + if not self._networks: + gui_label(rect, tr("Scanning Wi-Fi networks..."), 72, alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER) + return + + if self.state == UIState.NEEDS_AUTH and self._state_network: + self.keyboard.set_title(tr("Wrong password") if self._password_retry else tr("Enter password"), + tr("for \"{}\"").format(normalize_ssid(self._state_network.ssid))) + self.keyboard.reset(min_text_size=MIN_PASSWORD_LENGTH) + self.keyboard.set_callback(lambda result: self._on_password_entered(cast(Network, self._state_network), result)) + gui_app.push_widget(self.keyboard) + elif self.state == UIState.SHOW_FORGET_CONFIRM and self._state_network: + confirm_dialog = ConfirmDialog("", tr("Forget"), tr("Cancel"), callback=lambda result: self.on_forgot_confirm_finished(self._state_network, result)) + confirm_dialog.set_text(tr("Forget Wi-Fi Network \"{}\"?").format(normalize_ssid(self._state_network.ssid))) + gui_app.push_widget(confirm_dialog) + else: + self._draw_network_list(rect) + + def _on_password_entered(self, network: Network, result: DialogResult): + if result == DialogResult.CONFIRM: + password = self.keyboard.text + self.keyboard.clear() + + if len(password) >= MIN_PASSWORD_LENGTH: + self.connect_to_network(network, password) + elif result == DialogResult.CANCEL: + self.state = UIState.IDLE + + def on_forgot_confirm_finished(self, network, result: DialogResult): + if result == DialogResult.CONFIRM: + self.forget_network(network) + elif result == DialogResult.CANCEL: + self.state = UIState.IDLE + + def _draw_network_list(self, rect: rl.Rectangle): + content_rect = rl.Rectangle(rect.x, rect.y, rect.width, len(self._networks) * ITEM_HEIGHT) + offset = self.scroll_panel.update(rect, content_rect) + + rl.begin_scissor_mode(int(rect.x), int(rect.y), int(rect.width), int(rect.height)) + for i, network in enumerate(self._networks): + y_offset = rect.y + i * ITEM_HEIGHT + offset + item_rect = rl.Rectangle(rect.x, y_offset, rect.width, ITEM_HEIGHT) + if not rl.check_collision_recs(item_rect, rect): + continue + + self._draw_network_item(item_rect, network) + if i < len(self._networks) - 1: + line_y = int(item_rect.y + item_rect.height - 1) + rl.draw_line(int(item_rect.x), int(line_y), int(item_rect.x + item_rect.width), line_y, rl.LIGHTGRAY) + + rl.end_scissor_mode() + + def _draw_network_item(self, rect, network: Network): + spacing = 50 + ssid_rect = rl.Rectangle(rect.x, rect.y, rect.width - self.btn_width * 2, ITEM_HEIGHT) + signal_icon_rect = rl.Rectangle(rect.x + rect.width - ICON_SIZE, rect.y + (ITEM_HEIGHT - ICON_SIZE) / 2, ICON_SIZE, ICON_SIZE) + security_icon_rect = rl.Rectangle(signal_icon_rect.x - spacing - ICON_SIZE, rect.y + (ITEM_HEIGHT - ICON_SIZE) / 2, ICON_SIZE, ICON_SIZE) + + status_text = "" + if self.state == UIState.CONNECTING and self._state_network: + if self._state_network.ssid == network.ssid: + self._networks_buttons[network.ssid].set_enabled(False) + status_text = tr("CONNECTING...") + elif self.state == UIState.FORGETTING and self._state_network: + if self._state_network.ssid == network.ssid: + self._networks_buttons[network.ssid].set_enabled(False) + status_text = tr("FORGETTING...") + elif network.security_type == SecurityType.UNSUPPORTED: + self._networks_buttons[network.ssid].set_enabled(False) + else: + self._networks_buttons[network.ssid].set_enabled(True) + + self._networks_buttons[network.ssid].render(ssid_rect) + + if status_text: + status_text_rect = rl.Rectangle(security_icon_rect.x - 410, rect.y, 410, ITEM_HEIGHT) + gui_label(status_text_rect, status_text, font_size=48, alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER) + else: + # If the network is saved, show the "Forget" button + if self._wifi_manager.is_connection_saved(network.ssid): + forget_btn_rect = rl.Rectangle( + security_icon_rect.x - self.btn_width - spacing, + rect.y + (ITEM_HEIGHT - 80) / 2, + self.btn_width, + 80, + ) + self._forget_networks_buttons[network.ssid].render(forget_btn_rect) + + self._draw_status_icon(security_icon_rect, network) + self._draw_signal_strength_icon(signal_icon_rect, network) + + def _networks_buttons_callback(self, network): + if not self._wifi_manager.is_connection_saved(network.ssid) and network.security_type != SecurityType.OPEN: + self.state = UIState.NEEDS_AUTH + self._state_network = network + self._password_retry = False + elif self._wifi_manager.wifi_state.ssid != network.ssid: + self.connect_to_network(network) + + def _forget_networks_buttons_callback(self, network): + self.state = UIState.SHOW_FORGET_CONFIRM + self._state_network = network + + def _draw_status_icon(self, rect, network: Network): + """Draw the status icon based on network's connection state""" + icon_file = None + if self._wifi_manager.connected_ssid == network.ssid and self.state != UIState.CONNECTING: + icon_file = "icons/checkmark.png" + elif network.security_type == SecurityType.UNSUPPORTED: + icon_file = "icons/circled_slash.png" + elif network.security_type != SecurityType.OPEN: + icon_file = "icons/lock_closed.png" + + if not icon_file: + return + + texture = gui_app.texture(icon_file, ICON_SIZE, ICON_SIZE) + icon_rect = rl.Vector2(rect.x, rect.y + (ICON_SIZE - texture.height) / 2) + rl.draw_texture_v(texture, icon_rect, rl.WHITE) + + def _draw_signal_strength_icon(self, rect: rl.Rectangle, network: Network): + """Draw the Wi-Fi signal strength icon based on network's signal strength""" + strength_level = max(0, min(3, round(network.strength / 33.0))) + rl.draw_texture_v(gui_app.texture(STRENGTH_ICONS[strength_level], ICON_SIZE, ICON_SIZE), rl.Vector2(rect.x, rect.y), rl.WHITE) + + def connect_to_network(self, network: Network, password=''): + self.state = UIState.CONNECTING + self._state_network = network + if self._wifi_manager.is_connection_saved(network.ssid) and not password: + self._wifi_manager.activate_connection(network.ssid) + else: + self._wifi_manager.connect_to_network(network.ssid, password) + + def forget_network(self, network: Network): + self.state = UIState.FORGETTING + self._state_network = network + self._wifi_manager.forget_connection(network.ssid) + + def _on_network_updated(self, networks: list[Network]): + self._networks = networks + for n in self._networks: + self._networks_buttons[n.ssid] = Button(normalize_ssid(n.ssid), partial(self._networks_buttons_callback, n), font_size=55, + text_alignment=rl.GuiTextAlignment.TEXT_ALIGN_LEFT, button_style=ButtonStyle.TRANSPARENT_WHITE_TEXT) + self._networks_buttons[n.ssid].set_touch_valid_callback(lambda: self.scroll_panel.is_touch_valid()) + self._forget_networks_buttons[n.ssid] = Button(tr("Forget"), partial(self._forget_networks_buttons_callback, n), button_style=ButtonStyle.FORGET_WIFI, + font_size=45) + self._forget_networks_buttons[n.ssid].set_touch_valid_callback(lambda: self.scroll_panel.is_touch_valid()) + + def _on_need_auth(self, ssid): + network = next((n for n in self._networks if n.ssid == ssid), None) + if network: + self.state = UIState.NEEDS_AUTH + self._state_network = network + self._password_retry = True + + def _on_activated(self): + if self.state == UIState.CONNECTING: + self.state = UIState.IDLE + + def _on_forgotten(self, _): + if self.state == UIState.FORGETTING: + self.state = UIState.IDLE + + def _on_disconnected(self): + if self.state == UIState.CONNECTING: + self.state = UIState.IDLE + + +def main(): + gui_app.init_window("Wi-Fi Manager") + gui_app.push_widget(WifiManagerUI(WifiManager())) + + for _ in gui_app.render(): + pass + + gui_app.close() + + +if __name__ == "__main__": + main() diff --git a/openpilot/system/ui/widgets/option_dialog.py b/openpilot/system/ui/widgets/option_dialog.py new file mode 100644 index 0000000000..206400a74f --- /dev/null +++ b/openpilot/system/ui/widgets/option_dialog.py @@ -0,0 +1,79 @@ +import pyray as rl +from collections.abc import Callable +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.lib.multilang import tr +from openpilot.system.ui.widgets import Widget, DialogResult +from openpilot.system.ui.widgets.button import Button, ButtonStyle +from openpilot.system.ui.widgets.label import gui_label +from openpilot.system.ui.widgets.scroller_tici import Scroller + +# Constants +MARGIN = 50 +TITLE_FONT_SIZE = 70 +ITEM_HEIGHT = 135 +BUTTON_SPACING = 50 +BUTTON_HEIGHT = 160 +ITEM_SPACING = 50 +LIST_ITEM_SPACING = 25 + + +class MultiOptionDialog(Widget): + def __init__(self, title, options, current="", option_font_weight=FontWeight.MEDIUM, callback: Callable[[DialogResult], None] | None = None): + super().__init__() + self.title = title + self.options = options + self.current = current + self.selection = current + self._callback = callback + + # Create scroller with option buttons + self.option_buttons = [Button(option, click_callback=lambda opt=option: self._on_option_clicked(opt), + font_weight=option_font_weight, + text_alignment=rl.GuiTextAlignment.TEXT_ALIGN_LEFT, button_style=ButtonStyle.NORMAL, + text_padding=50, elide_right=True) for option in options] + self.scroller = Scroller(self.option_buttons, spacing=LIST_ITEM_SPACING) + + self.cancel_button = Button(lambda: tr("Cancel"), click_callback=lambda: self._set_result(DialogResult.CANCEL)) + self.select_button = Button(lambda: tr("Select"), click_callback=lambda: self._set_result(DialogResult.CONFIRM), button_style=ButtonStyle.PRIMARY) + + def _set_result(self, result: DialogResult): + gui_app.pop_widget() + if self._callback: + self._callback(result) + + def _on_option_clicked(self, option): + self.selection = option + + def _render(self, rect): + dialog_rect = rl.Rectangle(rect.x + MARGIN, rect.y + MARGIN, rect.width - 2 * MARGIN, rect.height - 2 * MARGIN) + rl.draw_rectangle_rounded(dialog_rect, 0.02, 20, rl.Color(30, 30, 30, 255)) + + content_rect = rl.Rectangle(dialog_rect.x + MARGIN, dialog_rect.y + MARGIN, + dialog_rect.width - 2 * MARGIN, dialog_rect.height - 2 * MARGIN) + + gui_label(rl.Rectangle(content_rect.x, content_rect.y, content_rect.width, TITLE_FONT_SIZE), self.title, 70, font_weight=FontWeight.BOLD) + + # Options area + options_y = content_rect.y + TITLE_FONT_SIZE + ITEM_SPACING + options_h = content_rect.height - TITLE_FONT_SIZE - BUTTON_HEIGHT - 2 * ITEM_SPACING + options_rect = rl.Rectangle(content_rect.x, options_y, content_rect.width, options_h) + + # Update button styles and set width based on selection + for i, option in enumerate(self.options): + selected = option == self.selection + button = self.option_buttons[i] + button.set_button_style(ButtonStyle.PRIMARY if selected else ButtonStyle.NORMAL) + button.set_rect(rl.Rectangle(0, 0, options_rect.width, ITEM_HEIGHT)) + + self.scroller.render(options_rect) + + # Buttons + button_y = content_rect.y + content_rect.height - BUTTON_HEIGHT + button_w = (content_rect.width - BUTTON_SPACING) / 2 + + cancel_rect = rl.Rectangle(content_rect.x, button_y, button_w, BUTTON_HEIGHT) + self.cancel_button.render(cancel_rect) + + select_rect = rl.Rectangle(content_rect.x + button_w + BUTTON_SPACING, button_y, button_w, BUTTON_HEIGHT) + self.select_button.set_enabled(self.selection != self.current) + self.select_button.render(select_rect) diff --git a/openpilot/system/ui/widgets/scroller.py b/openpilot/system/ui/widgets/scroller.py new file mode 100644 index 0000000000..55195b30fb --- /dev/null +++ b/openpilot/system/ui/widgets/scroller.py @@ -0,0 +1,432 @@ +import pyray as rl +import numpy as np +from collections.abc import Callable, Sequence + +from openpilot.common.filter_simple import FirstOrderFilter, BounceFilter +from openpilot.common.swaglog import cloudlog +from openpilot.system.ui.lib.application import gui_app +from openpilot.system.ui.lib.scroll_panel2 import GuiScrollPanel2, ScrollState +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.nav_widget import NavWidget + +ITEM_SPACING = 20 +LINE_COLOR = rl.GRAY +LINE_PADDING = 40 +ANIMATION_SCALE = 0.6 + +MOVE_LIFT = 20 +MOVE_OVERLAY_ALPHA = 0.65 +SCROLL_RC = 0.15 + +EDGE_SHADOW_WIDTH = 20 + +MIN_ZOOM_ANIMATION_TIME = 0.075 # seconds +DO_ZOOM = False +DO_JELLO = False + + +class ScrollIndicator(Widget): + HORIZONTAL_MARGIN = 4 + + def __init__(self): + super().__init__() + self._txt_scroll_indicator = gui_app.texture("icons_mici/settings/horizontal_scroll_indicator.png", 96, 48) + self._scroll_offset: float = 0.0 + self._content_size: float = 0.0 + self._viewport: rl.Rectangle = rl.Rectangle(0, 0, 0, 0) + + def update(self, scroll_offset: float, content_size: float, viewport: rl.Rectangle) -> None: + self._scroll_offset = scroll_offset + self._content_size = content_size + self._viewport = viewport + + def _render(self, _, /): + # scale indicator width based on content size + indicator_w = float(np.interp(self._content_size, [1000, 3000], [300, 100])) + + # position based on scroll ratio + slide_range = self._viewport.width - indicator_w + max_scroll = self._content_size - self._viewport.width + scroll_ratio = (-self._scroll_offset / abs(max_scroll)) if abs(max_scroll) > 1e-3 else 0.0 + x = self._viewport.x + scroll_ratio * slide_range + # don't bounce up when NavWidget shows + y = max(self._viewport.y, 0) + self._viewport.height - self._txt_scroll_indicator.height / 2 + + # squeeze when overscrolling past edges + dest_left = max(x, self._viewport.x) + dest_right = min(x + indicator_w, self._viewport.x + self._viewport.width) + dest_w = max(indicator_w / 2, dest_right - dest_left) + + # keep within viewport after applying minimum width + dest_left = min(dest_left, self._viewport.x + self._viewport.width - dest_w) + dest_left = max(dest_left, self._viewport.x) + + src_rec = rl.Rectangle(0, 0, self._txt_scroll_indicator.width, self._txt_scroll_indicator.height) + dest_rec = rl.Rectangle(dest_left, y, dest_w, self._txt_scroll_indicator.height) + rl.draw_texture_pro(self._txt_scroll_indicator, src_rec, dest_rec, rl.Vector2(0, 0), 0.0, + rl.Color(255, 255, 255, int(255 * 0.45))) + + +class _Scroller(Widget): + """Should use wrapper below to reduce boilerplate""" + def __init__(self, items: Sequence[Widget], horizontal: bool = True, snap_items: bool = False, spacing: int = ITEM_SPACING, + pad: int = ITEM_SPACING, scroll_indicator: bool = True, edge_shadows: bool = True): + super().__init__() + self._items: list[Widget] = [] + self._horizontal = horizontal + self._snap_items = snap_items + assert not self._snap_items or self._horizontal, "Snapping is only supported for horizontal scrolling" + self._spacing = spacing + self._pad = pad + + self._reset_scroll_at_show = True + + self._scrolling_to: tuple[float | None, bool, bool] = (None, False, False) # target offset, block_interrupt, block_widget_interaction + self._scrolling_to_filter = FirstOrderFilter(0.0, SCROLL_RC, 1 / gui_app.target_fps) + self._zoom_filter = FirstOrderFilter(1.0, 0.2, 1 / gui_app.target_fps) + self._zoom_out_t: float = 0.0 + + # layout state + self._visible_items: list[Widget] = [] + self._content_size: float = 0.0 + self._scroll_offset: float = 0.0 + + self._item_pos_filter = BounceFilter(0.0, 0.05, 1 / gui_app.target_fps) + + self.scroll_panel = GuiScrollPanel2(self._horizontal) + self._scroll_enabled: bool | Callable[[], bool] = True + + self._show_scroll_indicator = scroll_indicator and self._horizontal + self._scroll_indicator = ScrollIndicator() + self._edge_shadows = edge_shadows and self._horizontal + + # move animation state + # on move; lift src widget -> wait -> move all -> wait -> drop src widget + self._overlay_filter = FirstOrderFilter(0.0, 0.05, 1 / gui_app.target_fps) + self._move_animations: dict[Widget, FirstOrderFilter] = {} + self._move_lift: dict[Widget, FirstOrderFilter] = {} + # these are used to wait before moving/dropping, also to move onto next part of the animation earlier for timing + self._pending_lift: set[Widget] = set() + self._pending_move: set[Widget] = set() + + self.add_widgets(items) + + def set_reset_scroll_at_show(self, scroll: bool): + self._reset_scroll_at_show = scroll + + def scroll_to(self, pos: float, smooth: bool = False, block_interrupt: bool = False, block_widget_interaction: bool = False): + assert smooth or (not block_interrupt and not block_widget_interaction), "Instant scroll cannot block interaction" + + # already there + if abs(pos) < 1: + return + + # FIXME: the padding correction doesn't seem correct + scroll_offset = self.scroll_panel.get_offset() - pos + if smooth: + self._scrolling_to_filter.x = self.scroll_panel.get_offset() + self._scrolling_to = scroll_offset, block_interrupt, block_widget_interaction + else: + self.scroll_panel.set_offset(scroll_offset) + + @property + def is_auto_scrolling(self) -> bool: + return self._scrolling_to[0] is not None + + @property + def items(self) -> list[Widget]: + return self._items + + @property + def content_size(self) -> float: + return self._content_size + + def add_widget(self, item: Widget) -> None: + self._items.append(item) + + # preserve original touch valid callback + original_touch_valid_callback = item._touch_valid_callback + item.set_touch_valid_callback(lambda: self.scroll_panel.is_touch_valid() and self.enabled and not self._scrolling_to[2] + and not self.moving_items and (original_touch_valid_callback() if + original_touch_valid_callback else True)) + + def add_widgets(self, items: Sequence[Widget]) -> None: + for item in items: + self.add_widget(item) + + def set_scrolling_enabled(self, enabled: bool | Callable[[], bool]) -> None: + """Set whether scrolling is enabled (does not affect widget enabled state).""" + self._scroll_enabled = enabled + + def _update_state(self): + if DO_ZOOM: + if self._scrolling_to[0] is not None or self.scroll_panel.state != ScrollState.STEADY: + self._zoom_out_t = rl.get_time() + MIN_ZOOM_ANIMATION_TIME + self._zoom_filter.update(0.85) + else: + if self._zoom_out_t is not None: + if rl.get_time() > self._zoom_out_t: + self._zoom_filter.update(1.0) + else: + self._zoom_filter.update(0.85) + + # Cancel auto-scroll if user starts manually scrolling (unless block_interaction) + if (self.scroll_panel.state in (ScrollState.PRESSED, ScrollState.MANUAL_SCROLL) and + self._scrolling_to[0] is not None and not self._scrolling_to[1]): + self._scrolling_to = None, False, False + + if self._scrolling_to[0] is not None and len(self._pending_lift) == 0: + self._scrolling_to_filter.update(self._scrolling_to[0]) + self.scroll_panel.set_offset(self._scrolling_to_filter.x) + + if abs(self._scrolling_to_filter.x - self._scrolling_to[0]) < 1: # finished scroll + self.scroll_panel.set_offset(self._scrolling_to[0]) + self._scrolling_to = None, False, False + + def _get_scroll(self, visible_items: list[Widget], content_size: float) -> float: + scroll_enabled = self._scroll_enabled() if callable(self._scroll_enabled) else self._scroll_enabled + self.scroll_panel.set_enabled(scroll_enabled and self.enabled and not self._scrolling_to[1]) + + # Snap closest item to center. Skipped while scroll_to() is animating + snap_target: float | None = None + if self._snap_items and visible_items and self._scrolling_to[0] is None: + # TODO: this doesn't handle two small buttons at the edges well + center_pos = self._rect.x + self._rect.width / 2 + closest_delta_pos = min((((item.rect.x + item.rect.width / 2) - center_pos) for item in visible_items), key=abs) + snap_target = self.scroll_panel.get_offset() - closest_delta_pos + + return self.scroll_panel.update(self._rect, content_size, snap_target=snap_target) + + @property + def moving_items(self) -> bool: + return len(self._move_animations) > 0 or len(self._move_lift) > 0 + + def move_item(self, from_idx: int, to_idx: int): + assert self._horizontal + if from_idx == to_idx: + return + + if self.moving_items: + cloudlog.warning(f"Already moving items, cannot move from {from_idx} to {to_idx}") + return + + item = self._items.pop(from_idx) + self._items.insert(to_idx, item) + + # store original position in content space of all affected widgets to animate from + for idx in range(min(from_idx, to_idx), max(from_idx, to_idx) + 1): + affected_item = self._items[idx] + self._move_animations[affected_item] = FirstOrderFilter(affected_item.rect.x - self._scroll_offset, SCROLL_RC, 1 / gui_app.target_fps) + self._pending_move.add(affected_item) + + # lift only src widget to make it more clear which one is moving + self._move_lift[item] = FirstOrderFilter(0.0, SCROLL_RC, 1 / gui_app.target_fps) + self._pending_lift.add(item) + + def _do_move_animation(self, item: Widget, target_x: float, target_y: float) -> tuple[float, float]: + # wait a frame before moving so we match potential pending scroll animation + can_start_move = len(self._pending_lift) == 0 + + if item in self._move_lift: + lift_filter = self._move_lift[item] + + # Animate lift + if len(self._pending_move) > 0: + lift_filter.update(MOVE_LIFT) + # start moving when almost lifted + if abs(lift_filter.x - MOVE_LIFT) < 2: + self._pending_lift.discard(item) + else: + # if done moving, animate down + lift_filter.update(0) + if abs(lift_filter.x) < 1: + del self._move_lift[item] + target_y -= lift_filter.x + + # Animate move + if item in self._move_animations: + move_filter = self._move_animations[item] + + # compare/update in content space to match filter + content_x = target_x - self._scroll_offset + if can_start_move: + move_filter.update(content_x) + + # drop when close to target + if abs(move_filter.x - content_x) < 10: + self._pending_move.discard(item) + + # finished moving + if abs(move_filter.x - content_x) < 1: + del self._move_animations[item] + target_x = move_filter.x + self._scroll_offset + + return target_x, target_y + + def _layout(self): + self._visible_items = [item for item in self._items if item.is_visible] + + self._content_size = sum(item.rect.width if self._horizontal else item.rect.height for item in self._visible_items) + self._content_size += self._spacing * (len(self._visible_items) - 1) + self._content_size += self._pad * 2 + + self._scroll_offset = self._get_scroll(self._visible_items, self._content_size) + + self._item_pos_filter.update(self._scroll_offset) + + cur_pos = 0 + for idx, item in enumerate(self._visible_items): + spacing = self._spacing if (idx > 0) else self._pad + # Nicely lay out items horizontally/vertically + if self._horizontal: + x = self._rect.x + cur_pos + spacing + y = self._rect.y + (self._rect.height - item.rect.height) / 2 + cur_pos += item.rect.width + spacing + else: + x = self._rect.x + (self._rect.width - item.rect.width) / 2 + y = self._rect.y + cur_pos + spacing + cur_pos += item.rect.height + spacing + + # Consider scroll + if self._horizontal: + x += self._scroll_offset + else: + y += self._scroll_offset + + # Add some jello effect when scrolling + if DO_JELLO: + if self._horizontal: + cx = self._rect.x + self._rect.width / 2 + jello_offset = self._scroll_offset - np.interp(x + item.rect.width / 2, + [self._rect.x, cx, self._rect.x + self._rect.width], + [self._item_pos_filter.x, self._scroll_offset, self._item_pos_filter.x]) + x -= np.clip(jello_offset, -20, 20) + else: + cy = self._rect.y + self._rect.height / 2 + jello_offset = self._scroll_offset - np.interp(y + item.rect.height / 2, + [self._rect.y, cy, self._rect.y + self._rect.height], + [self._item_pos_filter.x, self._scroll_offset, self._item_pos_filter.x]) + y -= np.clip(jello_offset, -20, 20) + + # Animate moves if needed + x, y = self._do_move_animation(item, x, y) + + # Update item state + item.set_position(x, y) + item.set_parent_rect(self._rect) + + def _render_item(self, item: Widget): + # Skip rendering if not in viewport + if not rl.check_collision_recs(item.rect, self._rect): + return + + # Scale each element around its own origin when scrolling + scale = self._zoom_filter.x + if scale != 1.0: + rl.rl_push_matrix() + rl.rl_scalef(scale, scale, 1.0) + rl.rl_translatef((1 - scale) * (item.rect.x + item.rect.width / 2) / scale, + (1 - scale) * (item.rect.y + item.rect.height / 2) / scale, 0) + item.render() + rl.rl_pop_matrix() + else: + item.render() + + def _render(self, _, /): + rl.begin_scissor_mode(int(self._rect.x), int(self._rect.y), + int(self._rect.width), int(self._rect.height)) + + for item in reversed(self._visible_items): + if item in self._move_lift: + continue + self._render_item(item) + + # Dim background if moving items, lifted items are above + self._overlay_filter.update(MOVE_OVERLAY_ALPHA if len(self._pending_move) else 0.0) + if self._overlay_filter.x > 0.01: + rl.draw_rectangle_rec(self._rect, rl.Color(0, 0, 0, int(255 * self._overlay_filter.x))) + + for item in self._move_lift: + self._render_item(item) + + rl.end_scissor_mode() + + # Draw edge shadows on top of scroller content + if self._edge_shadows: + rl.draw_rectangle_gradient_h(int(self._rect.x), int(self._rect.y), + EDGE_SHADOW_WIDTH, int(self._rect.height), + rl.Color(0, 0, 0, 204), rl.BLANK) + + right_x = int(self._rect.x + self._rect.width - EDGE_SHADOW_WIDTH) + rl.draw_rectangle_gradient_h(right_x, int(self._rect.y), + EDGE_SHADOW_WIDTH, int(self._rect.height), + rl.BLANK, rl.Color(0, 0, 0, 204)) + + # Draw scroll indicator on top of edge shadows + if self._show_scroll_indicator and len(self._visible_items) > 0: + self._scroll_indicator.update(self._scroll_offset, self._content_size, self._rect) + self._scroll_indicator.render() + + def show_event(self): + super().show_event() + for item in self._items: + item.show_event() + + if self._reset_scroll_at_show: + self.scroll_panel.set_offset(0.0) + + self._overlay_filter.x = 0.0 + self._move_animations.clear() + self._move_lift.clear() + self._pending_lift.clear() + self._pending_move.clear() + self._scrolling_to = None, False, False + self._scrolling_to_filter.x = 0.0 + + def hide_event(self): + super().hide_event() + for item in self._items: + item.hide_event() + + +class Scroller(Widget): + """Wrapper for _Scroller so that children do not need to call events or pass down enabled for nav stack.""" + def __init__(self, **kwargs): + super().__init__() + self._scroller = self._child(_Scroller([], **kwargs)) + # pass down enabled to child widget for nav stack + self._scroller.set_enabled(lambda: self.enabled) + + def _render(self, _, /): + self._scroller.render(self._rect) + + +class NavScroller(NavWidget, Scroller): + """Full screen Scroller that properly supports nav stack w/ animations""" + def __init__(self, **kwargs): + super().__init__(**kwargs) + # pass down enabled to child widget for nav stack + disable while swiping away NavWidget + self._scroller.set_enabled(lambda: self.enabled and not self.is_dismissing) + + def _back_enabled(self) -> bool: + # Vertical scrollers need to be at the top to swipe away to prevent erroneous swipes + # TODO: only used for offroad alerts, remove when horizontal + return self._scroller._horizontal or self._scroller.scroll_panel.get_offset() >= -20 # some tolerance + + +# TODO: only used for a few vertical scrollers, remove when horizontal +class NavRawScrollPanel(NavWidget): + # can swipe anywhere, only when at top + BACK_TOUCH_AREA_PERCENTAGE = 1.0 + + def __init__(self): + super().__init__() + self._scroll_panel = GuiScrollPanel2(horizontal=False) + self._scroll_panel.set_enabled(lambda: self.enabled and not self.is_dismissing) + + def show_event(self): + super().show_event() + self._scroll_panel.set_offset(0) + + def _back_enabled(self) -> bool: + return self._scroll_panel.get_offset() >= -20 diff --git a/openpilot/system/ui/widgets/scroller_tici.py b/openpilot/system/ui/widgets/scroller_tici.py new file mode 100644 index 0000000000..fc81e1b079 --- /dev/null +++ b/openpilot/system/ui/widgets/scroller_tici.py @@ -0,0 +1,91 @@ +import pyray as rl +from collections.abc import Sequence +from openpilot.system.ui.lib.scroll_panel import GuiScrollPanel +from openpilot.system.ui.widgets import Widget + +ITEM_SPACING = 40 +LINE_COLOR = rl.GRAY +LINE_PADDING = 40 + + +class LineSeparator(Widget): + def __init__(self, height: int = 1): + super().__init__() + self._rect = rl.Rectangle(0, 0, 0, height) + + def set_parent_rect(self, parent_rect: rl.Rectangle) -> None: + super().set_parent_rect(parent_rect) + self._rect.width = parent_rect.width + + def _render(self, _): + rl.draw_line(int(self._rect.x) + LINE_PADDING, int(self._rect.y), + int(self._rect.x + self._rect.width) - LINE_PADDING, int(self._rect.y), + LINE_COLOR) + + +class Scroller(Widget): + def __init__(self, items: Sequence[Widget], spacing: int = ITEM_SPACING, line_separator: bool = False, pad_end: bool = True): + super().__init__() + self._items: list[Widget] = [] + self._spacing = spacing + self._line_separator = LineSeparator() if line_separator else None + self._pad_end = pad_end + + self.scroll_panel = GuiScrollPanel() + + for item in items: + self.add_widget(item) + + def add_widget(self, item: Widget) -> None: + self._items.append(item) + item.set_touch_valid_callback(self.scroll_panel.is_touch_valid) + + def _render(self, _): + # TODO: don't draw items that are not in the viewport + visible_items = [item for item in self._items if item.is_visible] + + # Add line separator between items + if self._line_separator is not None: + l = len(visible_items) + for i in range(1, len(visible_items)): + visible_items.insert(l - i, self._line_separator) + + content_height = sum(item.rect.height for item in visible_items) + self._spacing * (len(visible_items)) + if not self._pad_end: + content_height -= self._spacing + scroll = self.scroll_panel.update(self._rect, rl.Rectangle(0, 0, self._rect.width, content_height)) + + rl.begin_scissor_mode(int(self._rect.x), int(self._rect.y), + int(self._rect.width), int(self._rect.height)) + + cur_height = 0 + for idx, item in enumerate(visible_items): + if not item.is_visible: + continue + + # Nicely lay out items vertically + x = self._rect.x + y = self._rect.y + cur_height + self._spacing * (idx != 0) + cur_height += item.rect.height + self._spacing * (idx != 0) + + # Consider scroll + y += scroll + + # Update item state + item.set_position(x, y) + item.set_parent_rect(self._rect) + item.render() + + rl.end_scissor_mode() + + def show_event(self): + super().show_event() + # Reset to top + self.scroll_panel.set_offset(0) + for item in self._items: + item.show_event() + + def hide_event(self): + super().hide_event() + for item in self._items: + item.hide_event() diff --git a/openpilot/system/ui/widgets/slider.py b/openpilot/system/ui/widgets/slider.py new file mode 100644 index 0000000000..bf965954f2 --- /dev/null +++ b/openpilot/system/ui/widgets/slider.py @@ -0,0 +1,204 @@ +import abc +from collections.abc import Callable + +import pyray as rl + +from openpilot.system.ui.lib.application import gui_app, FontWeight +from openpilot.system.ui.widgets import Widget +from openpilot.system.ui.widgets.label import UnifiedLabel +from openpilot.common.filter_simple import FirstOrderFilter, BounceFilter + + +class SliderBase(Widget, abc.ABC): + HORIZONTAL_PADDING = 8 + CONFIRM_DELAY = 0.2 + PRESSED_SCALE = 1.07 + + _bg_txt: rl.Texture + _circle_bg_txt: rl.Texture + _circle_bg_pressed_txt: rl.Texture + _circle_arrow_txt: rl.Texture + + def __init__(self, title: str, confirm_callback: Callable | None = None, shimmer_offset: float = 0.0): + super().__init__() + self._confirm_callback = confirm_callback + self._shimmer_offset = shimmer_offset + + self._load_assets() + + self._drag_threshold = -self._rect.width // 2 + + # State + self._opacity_filter = FirstOrderFilter(1.0, 0.1, 1 / gui_app.target_fps) + self._confirmed_time = 0.0 + self._confirm_callback_called = False # we keep dialog open by default, only call once + self._start_x_circle = 0.0 + self._scroll_x_circle = 0.0 + self._scroll_x_circle_filter = FirstOrderFilter(0, 0.05, 1 / gui_app.target_fps) + self._circle_scale_filter = BounceFilter(1.0, 0.1, 1 / gui_app.target_fps) + self._circle_press_time: float | None = None + + self._is_dragging_circle = False + + self._label = self._child(UnifiedLabel(title, font_size=36, font_weight=FontWeight.SEMI_BOLD, text_color=rl.WHITE, + alignment=rl.GuiTextAlignment.TEXT_ALIGN_RIGHT, + alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE, line_height=0.9, shimmer=True)) + + @abc.abstractmethod + def _load_assets(self): + ... + + @property + def confirmed(self) -> bool: + return self._confirmed_time > 0.0 + + def show_event(self): + super().show_event() + self.reset() + + def reset(self): + # reset all slider state + self._is_dragging_circle = False + self._circle_press_time = None + self._confirmed_time = 0.0 + self._confirm_callback_called = False + self._label.reset_shimmer(self._shimmer_offset) + + def set_opacity(self, opacity: float, smooth: bool = False): + if smooth: + self._opacity_filter.update(opacity) + else: + self._opacity_filter.x = opacity + + @property + def slider_percentage(self): + activated_pos = -self._bg_txt.width + self._circle_bg_txt.width + return min(max(-self._scroll_x_circle_filter.x / abs(activated_pos), 0.0), 1.0) + + def _on_confirm(self): + if self._confirm_callback: + self._confirm_callback() + + def _handle_mouse_event(self, mouse_event): + super()._handle_mouse_event(mouse_event) + + if mouse_event.left_pressed: + # touch rect goes to the padding + circle_button_rect = rl.Rectangle( + self._rect.x + (self._rect.width - self._circle_bg_txt.width) + self._scroll_x_circle_filter.x - self.HORIZONTAL_PADDING * 2, + self._rect.y, + self._circle_bg_txt.width + self.HORIZONTAL_PADDING * 2, + self._rect.height, + ) + if rl.check_collision_point_rec(mouse_event.pos, circle_button_rect): + self._start_x_circle = mouse_event.pos.x + self._is_dragging_circle = True + self._circle_press_time = rl.get_time() + + elif mouse_event.left_released: + # swiped to left + if self._scroll_x_circle_filter.x < self._drag_threshold: + self._confirmed_time = rl.get_time() + + self._is_dragging_circle = False + + if self._is_dragging_circle: + self._scroll_x_circle = mouse_event.pos.x - self._start_x_circle + + def _update_state(self): + super()._update_state() + # TODO: this math can probably be cleaned up to remove duplicate stuff + activated_pos = int(-self._bg_txt.width + self._circle_bg_txt.width) + self._scroll_x_circle = max(min(self._scroll_x_circle, 0), activated_pos) + + if self.confirmed: + # swiped left to confirm + self._scroll_x_circle_filter.update(activated_pos) + + # activate once animation completes, small threshold for small floats + if self._scroll_x_circle_filter.x < (activated_pos + 1): + if not self._confirm_callback_called and (rl.get_time() - self._confirmed_time) >= self.CONFIRM_DELAY: + self._confirm_callback_called = True + self._on_confirm() + + elif not self._is_dragging_circle: + # reset back to right + self._scroll_x_circle_filter.update(0) + else: + # not activated yet, keep movement 1:1 + self._scroll_x_circle_filter.x = self._scroll_x_circle + + def _render(self, _): + white = rl.Color(255, 255, 255, int(255 * self._opacity_filter.x)) + + bg_txt_x = self._rect.x + (self._rect.width - self._bg_txt.width) / 2 + bg_txt_y = self._rect.y + (self._rect.height - self._bg_txt.height) / 2 + rl.draw_texture_ex(self._bg_txt, rl.Vector2(bg_txt_x, bg_txt_y), 0.0, 1.0, white) + + btn_x = bg_txt_x + self._bg_txt.width - self._circle_bg_txt.width + self._scroll_x_circle_filter.x + btn_y = self._rect.y + (self._rect.height - self._circle_bg_txt.height) / 2 + + label_alpha = int(255 * (1.0 - self.slider_percentage) * self._opacity_filter.x) + if label_alpha > 0: + self._label.set_text_color(rl.Color(255, 255, 255, label_alpha)) + label_rect = rl.Rectangle( + self._rect.x + 20, + self._rect.y, + self._rect.width - self._circle_bg_txt.width - 20 * 2.5, + self._rect.height, + ) + self._label.render(label_rect) + + # circle and arrow with grow animation + circle_pressed = self._is_dragging_circle or self.confirmed or (self._circle_press_time is not None and rl.get_time() - self._circle_press_time < 0.075) + circle_bg_txt = self._circle_bg_pressed_txt if circle_pressed else self._circle_bg_txt + scale = self._circle_scale_filter.update(self.PRESSED_SCALE if circle_pressed else 1.0) + scaled_btn_x = btn_x + (self._circle_bg_txt.width * (1 - scale)) / 2 + scaled_btn_y = btn_y + (self._circle_bg_txt.height * (1 - scale)) / 2 + rl.draw_texture_ex(circle_bg_txt, rl.Vector2(scaled_btn_x, scaled_btn_y), 0.0, scale, white) + + arrow_x = btn_x + (self._circle_bg_txt.width - self._circle_arrow_txt.width) / 2 + arrow_y = scaled_btn_y + (self._circle_bg_txt.height - self._circle_arrow_txt.height) / 2 + rl.draw_texture_ex(self._circle_arrow_txt, rl.Vector2(arrow_x, arrow_y), 0.0, 1.0, white) + + +class LargerSlider(SliderBase): + def __init__(self, title: str, confirm_callback: Callable | None = None, green: bool = True, shimmer_offset: float = 0.0): + self._green = green + super().__init__(title, confirm_callback=confirm_callback, shimmer_offset=shimmer_offset) + + def _load_assets(self): + self.set_rect(rl.Rectangle(0, 0, 520 + self.HORIZONTAL_PADDING * 2, 115)) + + self._bg_txt = gui_app.texture("icons_mici/setup/small_slider/slider_bg_larger.png", 520, 115) + circle_fn = "slider_green_rounded_rectangle" if self._green else "slider_black_rounded_rectangle" + self._circle_bg_txt = gui_app.texture(f"icons_mici/setup/small_slider/{circle_fn}.png", 180, 115) + self._circle_bg_pressed_txt = gui_app.texture(f"icons_mici/setup/small_slider/{circle_fn}_pressed.png", 180, 115) + self._circle_arrow_txt = gui_app.texture("icons_mici/setup/small_slider/slider_arrow.png", 64, 55) + + +class BigSlider(SliderBase): + def __init__(self, title: str, icon: rl.Texture, confirm_callback: Callable | None = None): + self._icon = icon + super().__init__(title, confirm_callback=confirm_callback) + self._label.set_font_size(48) + self._label.set_font_weight(FontWeight.DISPLAY) + self._label.set_line_height(0.875) + + def _load_assets(self): + self.set_rect(rl.Rectangle(0, 0, 520 + self.HORIZONTAL_PADDING * 2, 180)) + + self._bg_txt = gui_app.texture("icons_mici/buttons/slider_bg.png", 520, 180) + self._circle_bg_txt = gui_app.texture("icons_mici/buttons/button_circle.png", 180, 180) + self._circle_bg_pressed_txt = gui_app.texture("icons_mici/buttons/button_circle_pressed.png", 180, 180) + self._circle_arrow_txt = self._icon + + +class RedBigSlider(BigSlider): + def _load_assets(self): + self.set_rect(rl.Rectangle(0, 0, 520 + self.HORIZONTAL_PADDING * 2, 180)) + + self._bg_txt = gui_app.texture("icons_mici/buttons/slider_bg.png", 520, 180) + self._circle_bg_txt = gui_app.texture("icons_mici/buttons/button_circle_red.png", 180, 180) + self._circle_bg_pressed_txt = gui_app.texture("icons_mici/buttons/button_circle_red_pressed.png", 180, 180) + self._circle_arrow_txt = self._icon diff --git a/openpilot/system/ui/widgets/toggle.py b/openpilot/system/ui/widgets/toggle.py new file mode 100644 index 0000000000..0fbf3c844a --- /dev/null +++ b/openpilot/system/ui/widgets/toggle.py @@ -0,0 +1,81 @@ +import pyray as rl +from collections.abc import Callable +from openpilot.system.ui.lib.application import MousePos +from openpilot.system.ui.widgets import Widget + +ON_COLOR = rl.Color(51, 171, 76, 255) +OFF_COLOR = rl.Color(0x39, 0x39, 0x39, 255) +KNOB_COLOR = rl.WHITE +DISABLED_ON_COLOR = rl.Color(0x22, 0x77, 0x22, 255) # Dark green when disabled + on +DISABLED_OFF_COLOR = rl.Color(0x39, 0x39, 0x39, 255) +DISABLED_KNOB_COLOR = rl.Color(0x88, 0x88, 0x88, 255) +WIDTH, HEIGHT = 160, 80 +BG_HEIGHT = 60 +ANIMATION_SPEED = 8.0 + + +class Toggle(Widget): + def __init__(self, initial_state: bool = False, callback: Callable[[bool], None] | None = None): + super().__init__() + self._state = initial_state + self._callback = callback + self._enabled = True + self._progress = 1.0 if initial_state else 0.0 + self._target = self._progress + self._clicked = False + + def set_rect(self, rect: rl.Rectangle): + self._rect = rl.Rectangle(rect.x, rect.y, WIDTH, HEIGHT) + + def _handle_mouse_release(self, mouse_pos: MousePos): + if not self._enabled: + return + + self._clicked = True + self._state = not self._state + self._target = 1.0 if self._state else 0.0 + if self._callback: + self._callback(self._state) + + def get_state(self) -> bool: + return self._state + + def set_state(self, state: bool): + self._state = state + self._target = 1.0 if state else 0.0 + + def is_enabled(self): + return self._enabled + + def update(self): + if abs(self._progress - self._target) > 0.01: + delta = rl.get_frame_time() * ANIMATION_SPEED + self._progress += delta if self._progress < self._target else -delta + self._progress = max(0.0, min(1.0, self._progress)) + + def _render(self, rect: rl.Rectangle): + self.update() + + if self._enabled: + bg_color = self._blend_color(OFF_COLOR, ON_COLOR, self._progress) + knob_color = KNOB_COLOR + else: + bg_color = self._blend_color(DISABLED_OFF_COLOR, DISABLED_ON_COLOR, self._progress) + knob_color = DISABLED_KNOB_COLOR + + # Draw background + bg_rect = rl.Rectangle(self._rect.x + 5, self._rect.y + 10, WIDTH - 10, BG_HEIGHT) + rl.draw_rectangle_rounded(bg_rect, 1.0, 10, bg_color) + + # Draw knob + knob_x = self._rect.x + HEIGHT / 2 + (WIDTH - HEIGHT) * self._progress + knob_y = self._rect.y + HEIGHT / 2 + rl.draw_circle(int(knob_x), int(knob_y), HEIGHT / 2, knob_color) + + # TODO: use click callback + clicked = self._clicked + self._clicked = False + return clicked + + def _blend_color(self, c1, c2, t): + return rl.Color(int(c1.r + (c2.r - c1.r) * t), int(c1.g + (c2.g - c1.g) * t), int(c1.b + (c2.b - c1.b) * t), 255) diff --git a/system/updated/common.py b/openpilot/system/updated/common.py similarity index 100% rename from system/updated/common.py rename to openpilot/system/updated/common.py diff --git a/system/updated/updated.py b/openpilot/system/updated/updated.py similarity index 82% rename from system/updated/updated.py rename to openpilot/system/updated/updated.py index 0759c0a7aa..99696292f1 100755 --- a/system/updated/updated.py +++ b/openpilot/system/updated/updated.py @@ -3,11 +3,9 @@ import os import re import datetime import subprocess -import psutil import shutil import signal import fcntl -import time import threading from collections import defaultdict from pathlib import Path @@ -18,8 +16,8 @@ from openpilot.common.time_helpers import system_time_valid from openpilot.common.markdown import parse_markdown from openpilot.common.swaglog import cloudlog from openpilot.selfdrive.selfdrived.alertmanager import set_offroad_alert -from openpilot.system.hardware import AGNOS, HARDWARE -from openpilot.system.version import get_build_metadata +from openpilot.common.hardware import AGNOS, HARDWARE +from openpilot.common.version import get_build_metadata, SP_BRANCH_MIGRATIONS LOCK_FILE = os.getenv("UPDATER_LOCK_FILE", "/tmp/safe_staging_overlay.lock") STAGING_ROOT = os.getenv("UPDATER_STAGING_ROOT", "/data/safe_staging") @@ -31,8 +29,13 @@ FINALIZED = os.path.join(STAGING_ROOT, "finalized") OVERLAY_INIT = Path(os.path.join(BASEDIR, ".overlay_init")) -DAYS_NO_CONNECTIVITY_MAX = 14 # do not allow to engage after this many days -DAYS_NO_CONNECTIVITY_PROMPT = 10 # send an offroad prompt after this many days +# do not allow to engage after this many hours onroad and this many routes +HOURS_NO_CONNECTIVITY_MAX = 27 +ROUTES_NO_CONNECTIVITY_MAX = 84 +# send an offroad prompt after this many hours onroad and this many routes +HOURS_NO_CONNECTIVITY_PROMPT = 23 +ROUTES_NO_CONNECTIVITY_PROMPT = 80 + class UserRequest: NONE = 0 @@ -61,17 +64,9 @@ class WaitTimeHelper: def write_time_to_param(params, param) -> None: t = datetime.datetime.now(datetime.UTC).replace(tzinfo=None) - params.put(param, t.isoformat().encode('utf8')) + params.put(param, t, block=True) -def read_time_from_param(params, param) -> datetime.datetime | None: - t = params.get(param, encoding='utf8') - try: - return datetime.datetime.fromisoformat(t) - except (TypeError, ValueError): - pass - return None - -def run(cmd: list[str], cwd: str = None) -> str: +def run(cmd: list[str], cwd: str | None = None) -> str: return subprocess.check_output(cmd, cwd=cwd, stderr=subprocess.STDOUT, encoding='utf8') @@ -86,7 +81,7 @@ def set_consistent_flag(consistent: bool) -> None: def parse_release_notes(basedir: str) -> bytes: try: - with open(os.path.join(basedir, "RELEASES.md"), "rb") as f: + with open(os.path.join(basedir, "CHANGELOG.md"), "rb") as f: r = f.read().split(b'\n\n', 1)[0] # Slice latest release notes try: return bytes(parse_markdown(r.decode("utf-8")), encoding="utf-8") @@ -142,7 +137,7 @@ def init_overlay() -> None: cloudlog.info("preparing new safe staging area") params = Params() - params.put_bool("UpdateAvailable", False) + params.put_bool("UpdateAvailable", False, block=True) set_consistent_flag(False) dismount_overlay() run(["sudo", "rm", "-rf", STAGING_ROOT]) @@ -173,7 +168,7 @@ def init_overlay() -> None: run(["sudo", "chmod", "755", os.path.join(OVERLAY_METADATA, "work")]) git_diff = run(["git", "diff", "--submodule=diff"], OVERLAY_MERGED) - params.put("GitDiff", git_diff) + params.put("GitDiff", git_diff, block=True) cloudlog.info(f"git diff output:\n{git_diff}") @@ -193,21 +188,12 @@ def finalize_update() -> None: run(["git", "reset", "--hard"], FINALIZED) run(["git", "submodule", "foreach", "--recursive", "git", "reset", "--hard"], FINALIZED) - cloudlog.info("Starting git cleanup in finalized update") - t = time.monotonic() - try: - run(["git", "gc"], FINALIZED) - run(["git", "lfs", "prune"], FINALIZED) - cloudlog.event("Done git cleanup", duration=time.monotonic() - t) - except subprocess.CalledProcessError: - cloudlog.exception(f"Failed git cleanup, took {time.monotonic() - t:.3f} s") - set_consistent_flag(True) cloudlog.info("done finalizing overlay") def handle_agnos_update() -> None: - from openpilot.system.hardware.tici.agnos import flash_agnos_update, get_target_slot_number + from openpilot.common.hardware.tici.agnos import flash_agnos_update, get_target_slot_number cur_version = HARDWARE.get_os_version() updated_version = run(["bash", "-c", r"unset AGNOS_VERSION && source launch_env.sh && \ @@ -223,7 +209,7 @@ def handle_agnos_update() -> None: cloudlog.info(f"Beginning background installation for AGNOS {updated_version}") set_offroad_alert("Offroad_NeosUpdate", True) - manifest_path = os.path.join(OVERLAY_MERGED, "system/hardware/tici/agnos.json") + manifest_path = os.path.join(OVERLAY_MERGED, "openpilot/system/hardware/tici/agnos.json") target_slot_number = get_target_slot_number() flash_agnos_update(manifest_path, target_slot_number, cloudlog) set_offroad_alert("Offroad_NeosUpdate", False) @@ -242,9 +228,10 @@ class Updater: @property def target_branch(self) -> str: - b: str | None = self.params.get("UpdaterTargetBranch", encoding='utf-8') + b: str | None = self.params.get("UpdaterTargetBranch") if b is None: b = self.get_branch(BASEDIR) + b = SP_BRANCH_MIGRATIONS.get((HARDWARE.get_device_type(), b), b) return b @property @@ -272,25 +259,27 @@ class Updater: return run(["git", "rev-parse", "HEAD"], path).rstrip() def set_params(self, update_success: bool, failed_count: int, exception: str | None) -> None: - self.params.put("UpdateFailedCount", str(failed_count)) - self.params.put("UpdaterTargetBranch", self.target_branch) + self.params.put("UpdateFailedCount", failed_count, block=True) + self.params.put("UpdaterTargetBranch", self.target_branch, block=True) - self.params.put_bool("UpdaterFetchAvailable", self.update_available) + self.params.put_bool("UpdaterFetchAvailable", self.update_available, block=True) if len(self.branches): - self.params.put("UpdaterAvailableBranches", ','.join(self.branches.keys())) + self.params.put("UpdaterAvailableBranches", ','.join(self.branches.keys()), block=True) - last_update = datetime.datetime.now(datetime.UTC).replace(tzinfo=None) + last_uptime_onroad = self.params.get("UptimeOnroad", return_default=True) + last_route_count = self.params.get("RouteCount", return_default=True) if update_success: - write_time_to_param(self.params, "LastUpdateTime") + self.params.put("LastUpdateTime", datetime.datetime.now(datetime.UTC).replace(tzinfo=None), block=True) + self.params.put("LastUpdateUptimeOnroad", last_uptime_onroad, block=True) + self.params.put("LastUpdateRouteCount", last_route_count, block=True) else: - t = read_time_from_param(self.params, "LastUpdateTime") - if t is not None: - last_update = t + last_uptime_onroad = self.params.get("LastUpdateUptimeOnroad", return_default=True) + last_route_count = self.params.get("LastUpdateRouteCount", return_default=True) if exception is None: self.params.remove("LastUpdateException") else: - self.params.put("LastUpdateException", exception) + self.params.put("LastUpdateException", exception, block=True) # Write out current and new version info def get_description(basedir: str) -> str: @@ -304,7 +293,7 @@ class Updater: try: branch = self.get_branch(basedir) commit = self.get_commit_hash(basedir)[:7] - with open(os.path.join(basedir, "common", "version.h")) as f: + with open(os.path.join(basedir, "openpilot", "sunnypilot", "common", "version.h")) as f: version = f.read().split('"')[1] commit_unix_ts = run(["git", "show", "-s", "--format=%ct", "HEAD"], basedir).rstrip() @@ -313,18 +302,18 @@ class Updater: except Exception: cloudlog.exception("updater.get_description") return f"{version} / {branch} / {commit} / {commit_date}" - self.params.put("UpdaterCurrentDescription", get_description(BASEDIR)) - self.params.put("UpdaterCurrentReleaseNotes", parse_release_notes(BASEDIR)) - self.params.put("UpdaterNewDescription", get_description(FINALIZED)) - self.params.put("UpdaterNewReleaseNotes", parse_release_notes(FINALIZED)) - self.params.put_bool("UpdateAvailable", self.update_ready) + self.params.put("UpdaterCurrentDescription", get_description(BASEDIR), block=True) + self.params.put("UpdaterCurrentReleaseNotes", parse_release_notes(BASEDIR), block=True) + self.params.put("UpdaterNewDescription", get_description(FINALIZED), block=True) + self.params.put("UpdaterNewReleaseNotes", parse_release_notes(FINALIZED), block=True) + self.params.put_bool("UpdateAvailable", self.update_ready, block=True) # Handle user prompt for alert in ("Offroad_UpdateFailed", "Offroad_ConnectivityNeeded", "Offroad_ConnectivityNeededPrompt"): set_offroad_alert(alert, False) - now = datetime.datetime.now(datetime.UTC).replace(tzinfo=None) - dt = now - last_update + dt_uptime_onroad = (self.params.get("UptimeOnroad", return_default=True) - last_uptime_onroad) / (60*60) + dt_route_count = self.params.get("RouteCount", return_default=True) - last_route_count build_metadata = get_build_metadata() if failed_count > 15 and exception is not None and self.has_internet: if build_metadata.tested_channel: @@ -333,11 +322,11 @@ class Updater: extra_text = exception set_offroad_alert("Offroad_UpdateFailed", True, extra_text=extra_text) elif failed_count > 0: - if dt.days > DAYS_NO_CONNECTIVITY_MAX: + if dt_uptime_onroad > HOURS_NO_CONNECTIVITY_MAX and dt_route_count > ROUTES_NO_CONNECTIVITY_MAX: set_offroad_alert("Offroad_ConnectivityNeeded", True) - elif dt.days > DAYS_NO_CONNECTIVITY_PROMPT: - remaining = max(DAYS_NO_CONNECTIVITY_MAX - dt.days, 1) - set_offroad_alert("Offroad_ConnectivityNeededPrompt", True, extra_text=f"{remaining} day{'' if remaining == 1 else 's'}.") + elif dt_uptime_onroad > HOURS_NO_CONNECTIVITY_PROMPT and dt_route_count > ROUTES_NO_CONNECTIVITY_PROMPT: + remaining = max(HOURS_NO_CONNECTIVITY_MAX - dt_uptime_onroad, 1) + set_offroad_alert("Offroad_ConnectivityNeededPrompt", True, extra_text=f"{remaining} hour{'' if remaining == 1 else 's'}.") def check_for_update(self) -> None: cloudlog.info("checking for updates") @@ -353,7 +342,7 @@ class Updater: setup_git_options(OVERLAY_MERGED) output = run(["git", "ls-remote", "--heads"], OVERLAY_MERGED) - self.branches = defaultdict(lambda: None) + self.branches.clear() for line in output.split('\n'): ls_remotes_re = r'(?P\b[0-9a-f]{5,40}\b)(\s+)(refs\/heads\/)(?P.*$)' x = re.fullmatch(ls_remotes_re, line.strip()) @@ -372,14 +361,16 @@ class Updater: def fetch_update(self) -> None: cloudlog.info("attempting git fetch inside staging overlay") - self.params.put("UpdaterState", "downloading...") + self.params.put("UpdaterState", "downloading...", block=True) # TODO: cleanly interrupt this and invalidate old update set_consistent_flag(False) - self.params.put_bool("UpdateAvailable", False) + self.params.put_bool("UpdateAvailable", False, block=True) setup_git_options(OVERLAY_MERGED) + run(["git", "config", "--replace-all", "remote.origin.fetch", "+refs/heads/*:refs/remotes/origin/*"], OVERLAY_MERGED) + branch = self.target_branch git_fetch_output = run(["git", "fetch", "origin", branch], OVERLAY_MERGED) cloudlog.info("git fetch success: %s", git_fetch_output) @@ -387,6 +378,7 @@ class Updater: cloudlog.info("git reset in progress") cmds = [ ["git", "checkout", "--force", "--no-recurse-submodules", "-B", branch, "FETCH_HEAD"], + ["git", "branch", "--set-upstream-to", f"origin/{branch}"], ["git", "reset", "--hard"], ["git", "clean", "-xdff"], ["git", "submodule", "sync"], @@ -401,7 +393,7 @@ class Updater: handle_agnos_update() # Create the finalized, ready-to-swap update - self.params.put("UpdaterState", "finalizing update...") + self.params.put("UpdaterState", "finalizing update...", block=True) finalize_update() cloudlog.info("finalize success!") @@ -419,18 +411,13 @@ def main() -> None: except OSError as e: raise RuntimeError("couldn't get overlay lock; is another instance running?") from e - # Set low io priority - proc = psutil.Process() - if psutil.LINUX: - proc.ionice(psutil.IOPRIO_CLASS_BE, value=7) - # Check if we just performed an update if Path(os.path.join(STAGING_ROOT, "old_openpilot")).is_dir(): cloudlog.event("update installed") if not params.get("InstallDate"): - t = datetime.datetime.now(datetime.UTC).replace(tzinfo=None).isoformat() - params.put("InstallDate", t.encode('utf8')) + t = datetime.datetime.now(datetime.UTC).replace(tzinfo=None) + params.put("InstallDate", t, block=True) updater = Updater() update_failed_count = 0 # TODO: Load from param? @@ -440,7 +427,7 @@ def main() -> None: set_consistent_flag(False) # set initial state - params.put("UpdaterState", "idle") + params.put("UpdaterState", "idle", block=True) # Run the update loop first_run = True @@ -464,11 +451,11 @@ def main() -> None: update_failed_count += 1 # check for update - params.put("UpdaterState", "checking...") + params.put("UpdaterState", "checking...", block=True) updater.check_for_update() # download update - last_fetch = read_time_from_param(params, "UpdaterLastFetchTime") + last_fetch = params.get("UpdaterLastFetchTime") timed_out = last_fetch is None or (datetime.datetime.now(datetime.UTC).replace(tzinfo=None) - last_fetch > datetime.timedelta(days=3)) user_requested_fetch = wait_helper.user_request == UserRequest.FETCH if params.get_bool("NetworkMetered") and not timed_out and not user_requested_fetch: @@ -494,7 +481,7 @@ def main() -> None: OVERLAY_INIT.unlink(missing_ok=True) try: - params.put("UpdaterState", "idle") + params.put("UpdaterState", "idle", block=True) update_successful = (update_failed_count == 0) updater.set_params(update_successful, update_failed_count, exception) except Exception: diff --git a/openpilot/system/webrtc/__init__.py b/openpilot/system/webrtc/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/openpilot/system/webrtc/device/video.py b/openpilot/system/webrtc/device/video.py new file mode 100644 index 0000000000..c300f76485 --- /dev/null +++ b/openpilot/system/webrtc/device/video.py @@ -0,0 +1,101 @@ +import asyncio +from dataclasses import dataclass +import struct +import time + +from teleoprtc.tracks import TiciVideoStreamTrack + +from openpilot.cereal import messaging +from openpilot.common.realtime import DT_MDL +from openpilot.common.params import Params + + +# v4l2 buffer flag marking an encoded keyframe (linux/videodev2.h) +V4L2_BUF_FLAG_KEYFRAME = 0x8 + +# arbitrary 16-byte UUID identifying openpilot frame-timing SEI messages +TIMING_SEI_UUID = bytes([ + 0xa5, 0xe0, 0xc4, 0xa4, 0x5b, 0x6e, 0x4e, 0x1e, + 0x9c, 0x7e, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, +]) +_SEI_PREFIX = b'\x00\x00\x00\x01\x06\x05\x30' + TIMING_SEI_UUID + + +@dataclass(frozen=True) +class EncodedVideoFrame: + data: bytes + pts: int + + def __bytes__(self) -> bytes: + return self.data + + +class LiveStreamVideoStreamTrack(TiciVideoStreamTrack): + camera_to_sock_mapping = { + "driver": "livestreamDriverEncodeData", + "wideRoad": "livestreamWideRoadEncodeData", + "road": "livestreamRoadEncodeData", + } + + def __init__(self, camera_type: str, video_enabled: bool = True): + super().__init__(camera_type, DT_MDL) + + self._sock = self._make_sock(camera_type) + self._pts = 0 + self._t0_ns = time.monotonic_ns() + self.timing_sei_enabled = False + self.params = Params() + self._seen_keyframe = False + self.video_enabled = video_enabled + + def stop(self) -> None: + super().stop() + self._sock = None + + def _make_sock(self, camera_type: str) -> messaging.SubSocket: + return messaging.sub_sock(self.camera_to_sock_mapping[camera_type], conflate=True) + + def switch_camera(self, camera_type: str) -> None: + self._sock = self._make_sock(camera_type) + + def enable(self, enabled: bool): + self.video_enabled = enabled + if not enabled: + self._seen_keyframe = False + + def request_keyframe(self) -> None: + self.params.put("LivestreamRequestKeyframe", True, block=False) + + def _build_frame_data(self, msg) -> bytes: + encode_data = getattr(msg, msg.which()) + if not self.timing_sei_enabled: + return encode_data.header + encode_data.data + + idx = encode_data.idx + sei_nal = _SEI_PREFIX + struct.pack('>4d', + (idx.timestampEof - idx.timestampSof) / 1e6, + (msg.logMonoTime - idx.timestampEof) / 1e6, + (time.monotonic_ns() - msg.logMonoTime) / 1e6, + time.time() * 1000, # noqa: TID251 + ) + b'\x80' + return encode_data.header + sei_nal + encode_data.data + + async def recv(self): + while True: + # while video is disabled, pause here without returning + if not self.video_enabled: + await asyncio.sleep(0.005) + continue + + msg = messaging.recv_one_or_none(self._sock) + if msg is not None: + if not self._seen_keyframe and (getattr(msg, msg.which()).idx.flags & V4L2_BUF_FLAG_KEYFRAME): + self._seen_keyframe = True + self.params.put("LivestreamRequestKeyframe", False, block=False) + break + await asyncio.sleep(0.005) + + self._pts = ((time.monotonic_ns() - self._t0_ns) * self._clock_rate) // 1_000_000_000 + self.log_debug("track sending frame %d", self._pts) + + return EncodedVideoFrame(self._build_frame_data(msg), self._pts) diff --git a/openpilot/system/webrtc/helpers.py b/openpilot/system/webrtc/helpers.py new file mode 100644 index 0000000000..776b64573e --- /dev/null +++ b/openpilot/system/webrtc/helpers.py @@ -0,0 +1,40 @@ +import time +import requests +from dataclasses import asdict, dataclass, field + + +WEBRTCD_PORT = 5001 + +@dataclass +class StreamRequestBody: + sdp: str + init_camera: str + enabled: bool + bridge_services_in: list[str] = field(default_factory=list) + bridge_services_out: list[str] = field(default_factory=list) + + +def post_stream_request(body: StreamRequestBody) -> dict: + t_start = time.monotonic() + try: + resp = requests.post(f"http://localhost:{WEBRTCD_PORT}/stream", json=asdict(body), timeout=10) + t_end = time.monotonic() + ret = resp.json() + ret["time"] = (t_end - t_start) * 1000 + return ret + except requests.ConnectTimeout as e: + raise Exception("webrtc took too long to respond.") from e + except requests.ConnectionError as e: + raise Exception("webrtc server on device is not running.") from e + + +def wait_for_webrtcd(max_retries: float = 10) -> None: + attempts = 0 + while attempts < max_retries: + try: + if requests.get(f"http://localhost:{WEBRTCD_PORT}/schema", timeout=1).ok: + return + except requests.ConnectionError: + attempts += 1 + time.sleep(0.5) + raise TimeoutError("webrtcd did not initialize in time.") diff --git a/system/webrtc/schema.py b/openpilot/system/webrtc/schema.py similarity index 93% rename from system/webrtc/schema.py rename to openpilot/system/webrtc/schema.py index d80986ebf2..4876198eb0 100644 --- a/system/webrtc/schema.py +++ b/openpilot/system/webrtc/schema.py @@ -16,7 +16,7 @@ def generate_type(type_walker, schema_walker) -> str | list[Any] | dict[str, Any def generate_struct(schema: capnp.lib.capnp._StructSchema) -> dict[str, Any]: - return {field: generate_field(schema.fields[field]) for field in schema.fields if not field.endswith("DEPRECATED")} + return {field: generate_field(schema.fields[field]) for field in schema.fields if not field.endswith("DEPRECATED") and field != "deprecated"} def generate_field(field: capnp.lib.capnp._StructSchemaField) -> str | list[Any] | dict[str, Any]: diff --git a/openpilot/system/webrtc/tests/test_stream_session.py b/openpilot/system/webrtc/tests/test_stream_session.py new file mode 100644 index 0000000000..1f7bd5747a --- /dev/null +++ b/openpilot/system/webrtc/tests/test_stream_session.py @@ -0,0 +1,81 @@ +import asyncio +import json +import time + +import capnp +from openpilot.cereal import messaging, log +from teleoprtc.tracks import VIDEO_CLOCK_RATE + +from openpilot.system.webrtc.webrtcd import CerealOutgoingMessageProxy, CerealIncomingMessageProxy +from openpilot.system.webrtc.device.video import LiveStreamVideoStreamTrack + + +class TestStreamSession: + def setup_method(self): + self.loop = asyncio.new_event_loop() + + def teardown_method(self): + self.loop.stop() + self.loop.close() + + def test_outgoing_proxy(self, mocker): + test_msg = log.Event.new_message() + test_msg.logMonoTime = 123 + test_msg.valid = True + test_msg.customReservedRawData0 = b"test" + expected_dict = {"type": "customReservedRawData0", "logMonoTime": 123, "valid": True, "data": "test"} + expected_json = json.dumps(expected_dict).encode() + + channel = mocker.Mock() + channel.is_open.return_value = True + proxy = CerealOutgoingMessageProxy(["customReservedRawData0"]) + def mocked_update(t): + proxy.sm.update_msgs(0, [test_msg]) + + mocker.patch.object(messaging.SubMaster, "update", side_effect=mocked_update) + proxy.add_channel(channel) + + proxy.update() + + channel.send.assert_called_once_with(expected_json) + + def test_incoming_proxy(self, mocker): + tested_msgs = [ + {"type": "customReservedRawData0", "data": "test"}, # primitive + {"type": "can", "data": [{"address": 0, "dat": "", "src": 0}]}, # list + {"type": "testJoystick", "data": {"axes": [0, 0], "buttons": [False]}}, # dict + ] + + mocked_pubmaster = mocker.MagicMock(spec=messaging.PubMaster) + + proxy = CerealIncomingMessageProxy(mocked_pubmaster) + + for msg in tested_msgs: + proxy.send(json.dumps(msg).encode()) + + mocked_pubmaster.send.assert_called_once() + mt, md = mocked_pubmaster.send.call_args.args + msg_type = msg["type"] + assert isinstance(msg_type, str) + assert mt == msg_type + assert isinstance(md, capnp._DynamicStructBuilder) + assert hasattr(md, msg_type) + + mocked_pubmaster.reset_mock() + + def test_livestream_track(self, mocker): + fake_msg = messaging.new_message("livestreamDriverEncodeData") + + config = {"receive.return_value": fake_msg.to_bytes()} + mocker.patch("msgq.SubSocket", spec=True, **config) + track = LiveStreamVideoStreamTrack("driver") + + assert track.id.startswith("driver") + + for i in range(5): + packet = self.loop.run_until_complete(track.recv()) + if i == 0: + start_ns = time.monotonic_ns() + start_pts = packet.pts + assert abs(i + packet.pts - (start_pts + (((time.monotonic_ns() - start_ns) * VIDEO_CLOCK_RATE) // 1_000_000_000))) < 450 #5ms + assert bytes(packet) == b"" diff --git a/openpilot/system/webrtc/webrtcd.py b/openpilot/system/webrtc/webrtcd.py new file mode 100755 index 0000000000..7901f9847f --- /dev/null +++ b/openpilot/system/webrtc/webrtcd.py @@ -0,0 +1,599 @@ +#!/usr/bin/env python3 + +from abc import abstractmethod +from collections.abc import Callable +import os +import socket +import time +import capnp +import argparse +import asyncio +import contextlib +import json +import uuid +import logging +import signal +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from urllib.parse import urlparse, parse_qs +from typing import Any + +from openpilot.system.webrtc.helpers import StreamRequestBody +from openpilot.system.webrtc.schema import generate_field +from openpilot.common.params import Params +from openpilot.cereal import messaging, log + + +# socket trick: route lookup for 8.8.8.8 (nothing is sent or actually connected to) +# return the source interfaces IP which is the default interface of the device +def _default_route_ip() -> str | None: + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + try: + s.connect(("8.8.8.8", 53)) # selects a route, sends nothing + return s.getsockname()[0] + except OSError: + return None + finally: + s.close() + +class AsyncTaskRunner: + def __init__(self): + self.task = None + self.logger = logging.getLogger("webrtcd") + + def start(self): + assert self.task is None + self.task = asyncio.create_task(self.run()) + + async def stop(self): + if self.task is None: + return + task = self.task + self.task = None + if task.done(): + return + task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await task + + @abstractmethod + async def run(self): + pass + + +class CerealOutgoingMessageProxy(AsyncTaskRunner): + def __init__(self, services: list[str], enabled: bool = True): + super().__init__() + self.services = list(services) + self.sm = messaging.SubMaster(self.services) + self.channels = [] + self._enabled = enabled + + def add_channel(self, channel): + self.channels.append(channel) + + def enable(self, enable: bool): + self._enabled = enable + + def to_json(self, msg_content: Any): + if isinstance(msg_content, capnp._DynamicStructReader): + msg_dict = msg_content.to_dict() + elif isinstance(msg_content, capnp._DynamicListReader): + msg_dict = [self.to_json(msg) for msg in msg_content] + elif isinstance(msg_content, bytes): + msg_dict = msg_content.decode() + else: + msg_dict = msg_content + + return msg_dict + + def update(self): + # this is blocking in async context... + self.sm.update(0) + for service, updated in self.sm.updated.items(): + if not updated: + continue + msg_dict = self.to_json(self.sm[service]) + mono_time, valid = self.sm.logMonoTime[service], self.sm.valid[service] + outgoing_msg = {"type": service, "logMonoTime": mono_time, "valid": valid, "data": msg_dict} + encoded_msg = json.dumps(outgoing_msg).encode() + for channel in self.channels: + if not channel.is_open(): + continue + channel.send(encoded_msg) + + async def run(self): + while True: + if not self._enabled: + await asyncio.sleep(0.01) + continue + try: + self.update() + except Exception: + self.logger.exception("Cereal outgoing proxy failure") + await asyncio.sleep(0.01) + + +class CerealIncomingMessageProxy: + def __init__(self, pm: messaging.PubMaster): + self.pm = pm + + def send(self, message: bytes): + msg_json = json.loads(message) + msg_type, msg_data = msg_json["type"], msg_json["data"] + size = None + if not isinstance(msg_data, dict): + size = len(msg_data) + + msg = messaging.new_message(msg_type, size=size) + setattr(msg, msg_type, msg_data) + self.pm.send(msg_type, msg) + + +class DynamicPubMaster(messaging.PubMaster): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.lock = asyncio.Lock() + + async def add_services_if_needed(self, services): + async with self.lock: + for service in services: + if service not in self.sock: + self.sock[service] = messaging.pub_sock(service) + + +class LivestreamBitrateController(AsyncTaskRunner): + bitrates = [500_000, 1_500_000, int(os.environ.get("STREAM_BITRATE", 5_000_000))] + label_to_bitrate = { "high": bitrates[2], "med": bitrates[1], "low": bitrates[0]} + sample_interval = 0.2 + high_level = 0.1 # drop immediately + med_level = 0.05 # drop after # of samples + low_level = 0 # raise after # of samples + down_samples = 5 + param_name = "LivestreamEncoderBitrate" + + def __init__(self, get_stats: Callable[[], dict[str, Any]], params: Params, enabled: bool = True): + super().__init__() + self.get_stats = get_stats + self.params = params + + self.level = 2 + self._publish(self.bitrates[self.level]) + self.prev_stats: tuple[Any, ...] | None = None + self.counter = 0 + self.up_samples = 5 # 1s + self._auto = True + self._enabled = enabled + + def enable(self, enable: bool): + self._enabled = enable + + async def run(self): + while True: + await asyncio.sleep(self.sample_interval) + if not self._enabled: + continue + if not self._auto: + continue + + loss_rate = self._sample() + if loss_rate is None: + continue + if loss_rate >= self.med_level and self.level > 0: + self.counter += 1 + if self.counter >= self.down_samples or loss_rate >= self.high_level: + self.level -= 1 + self.up_samples *= 2 # exponential backoff before raising again + self.counter = 0 + self._publish(self.bitrates[self.level]) + elif loss_rate <= self.low_level and self.level < len(self.bitrates) - 1: + self.counter -= 1 + if -self.counter >= self.up_samples: + self.level += 1 + self.counter = 0 + self._publish(self.bitrates[self.level]) + + def _sample(self) -> float | None: + report = next(iter(self.get_stats().values()), None) + if report is None: + return None + + current = (report.ssrc, report.fraction_lost, report.packets_lost, report.highest_seq_no, report.jitter, report.lsr, report.dlsr) + if self.prev_stats == current: + return None + self.prev_stats = current + + loss_rate = report.fraction_lost / 256 + return loss_rate + + def _publish(self, bitrate: float): + self.params.put(self.param_name, bitrate) + + def set_quality(self, quality): + if quality in self.label_to_bitrate: + self._publish(self.label_to_bitrate[quality]) + self._auto = False + elif quality == "auto": + self._auto = True + + +class StreamSession: + shared_pub_master = DynamicPubMaster([]) + + def __init__(self, body: StreamRequestBody, debug_mode: bool = False): + from openpilot.system.webrtc.device.video import LiveStreamVideoStreamTrack + from teleoprtc.builder import WebRTCAnswerBuilder + + self.identifier = str(uuid.uuid4()) + self.params = Params() + builder = WebRTCAnswerBuilder(body.sdp, bind_address=_default_route_ip()) + + self.enabled = body.enabled + self.video_track = LiveStreamVideoStreamTrack(body.init_camera, self.enabled) + builder.add_video_stream(body.init_camera, self.video_track) + self.stream = builder.stream() + + self.incoming_bridge: CerealIncomingMessageProxy | None = None + self.incoming_bridge_services = body.bridge_services_in + self.outgoing_bridge: CerealOutgoingMessageProxy | None = None + self.bitrate_controller: LivestreamBitrateController | None = None + if len(body.bridge_services_in) > 0: + self.incoming_bridge = CerealIncomingMessageProxy(self.shared_pub_master) + if len(body.bridge_services_out) > 0: + self.outgoing_bridge = CerealOutgoingMessageProxy(body.bridge_services_out, self.enabled) + self.bitrate_controller = LivestreamBitrateController(self.stream.get_receiver_report_stats, self.params, self.enabled) + + self.run_task: asyncio.Task | None = None + self._cleanup_lock = asyncio.Lock() + self._cleanup_done = False + self.logger = logging.getLogger("webrtcd") + self.logger.info( + "New stream session (%s), init camera %s, video enabled %s, incoming services %s, outgoing services %s", + self.identifier, body.init_camera, body.enabled, body.bridge_services_in, body.bridge_services_out, + ) + + def start(self): + self.run_task = asyncio.create_task(self.run()) + + async def stop(self): + if self.run_task is not None and not self.run_task.done() and self.run_task is not asyncio.current_task(): + self.run_task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await self.run_task + self.run_task = None + await self.post_run_cleanup() + + async def get_answer(self): + return await self.stream.start() + + def message_handler(self, message: bytes): + try: + payload = json.loads(message) if isinstance(message, (bytes, str)) else None + if isinstance(payload, dict): + msg_type = payload.get("type") + + match msg_type: + case "livestreamCameraSwitch": + self.video_track.switch_camera(payload["data"]["camera"]) + case "livestreamSettings": + if self.bitrate_controller is not None: + self.bitrate_controller.set_quality(payload["data"]["quality"]) + case "livestreamVideoEnable": + enabled = payload["data"]["enabled"] + self.enabled = enabled + self.video_track.enable(enabled) + if self.outgoing_bridge is not None: + self.outgoing_bridge.enable(enabled) + if self.bitrate_controller is not None: + self.bitrate_controller.enable(enabled) + if not enabled: + self.params.put("LivestreamRequestKeyframe", True) + case "clockSync": + pong = json.dumps({"type": "clockSync", "data": { + "action": "pong", "browserSendTime": payload["data"]["browserSendTime"], "deviceTime": time.time() * 1000, # noqa: TID251 + }}) + self.stream.get_messaging_channel().send(pong) + case "enableTimingSei": + if hasattr(self.video_track, 'timing_sei_enabled'): + self.video_track.timing_sei_enabled = bool(payload["data"]["enabled"]) + case _: + if payload.get("type") not in self.incoming_bridge_services: + return + if self.incoming_bridge is not None: + self.incoming_bridge.send(message) + except Exception: + self.logger.exception("Cereal incoming proxy failure") + + async def run(self): + try: + self.params.put("LivestreamRequestKeyframe", True) + await asyncio.wait_for(self.stream.wait_for_connection(), timeout=15) + if self.stream.has_messaging_channel(): + self.stream.set_message_handler(self.message_handler) + if self.incoming_bridge is not None: + await self.shared_pub_master.add_services_if_needed(self.incoming_bridge_services) + if self.outgoing_bridge is not None: + channel = self.stream.get_messaging_channel() + self.outgoing_bridge.add_channel(channel) + self.outgoing_bridge.start() + if self.bitrate_controller is not None: + self.bitrate_controller.start() + + self.logger.info("Stream session (%s) connected", self.identifier) + await self.stream.wait_for_disconnection() + self.logger.info("Stream session (%s) ended", self.identifier) + except Exception: + self.logger.exception("Stream session failure") + finally: + await self.post_run_cleanup() + + async def post_run_cleanup(self): + async with self._cleanup_lock: + if self._cleanup_done: + return + self._cleanup_done = True + self.params.put("LivestreamRequestKeyframe", False) + if self.bitrate_controller is not None: + await self.bitrate_controller.stop() + if self.outgoing_bridge is not None: + await self.outgoing_bridge.stop() + if self.video_track is not None: + self.video_track.stop() + self.video_track = None + await self.stream.stop() + + +class ServerState: + def __init__(self, debug: bool): + self.streams: dict[str, StreamSession] = {} + self.stream_lock = asyncio.Lock() + self.debug = debug + self.teardown: asyncio.TimerHandle | None = None + + +# if nothing connects for 5 seconds, tear down livestreaming processes +def schedule_teardown(state: ServerState): + if state.teardown is not None: + state.teardown.cancel() + + def clear(): + if not state.streams: + Params().put_bool("IsLiveStreaming", False) + + state.teardown = asyncio.get_running_loop().call_later(5.0, clear) + + +def _json_response(obj: Any, status: int = 200) -> tuple[int, bytes, str]: + return (status, json.dumps(obj).encode(), "application/json; charset=utf-8") + + +def _text_response(text: str, status: int = 200) -> tuple[int, bytes, str]: + return (status, text.encode(), "text/plain; charset=utf-8") + + +async def handle_get_stream(state: ServerState, raw_body: bytes) -> tuple[int, bytes, str]: + stream_dict, debug_mode = state.streams, state.debug + body = StreamRequestBody(**json.loads(raw_body)) + + async with state.stream_lock: + # don't remove existing connection on prewarm request + enabled = any(s.run_task and not s.run_task.done() and s.enabled for s in stream_dict.values()) + if enabled and not body.enabled: + return _json_response({"error": "busy", "message": "someone else is connected."}) + + for sid, s in list(stream_dict.items()): + if s.run_task and not s.run_task.done(): + try: + ch = s.stream.get_messaging_channel() + ch.send(json.dumps({"type": "disconnect", "data": "Another device has connected, closing this session."})) + except Exception: + pass + await s.stop() + stream_dict.pop(sid, None) + + session = StreamSession(body, debug_mode) + stream_dict[session.identifier] = session + try: + answer = await asyncio.wait_for(session.get_answer(), timeout=30) + except TimeoutError: + await session.stop() + stream_dict.pop(session.identifier, None) + logging.getLogger("webrtcd").exception("Timed out creating stream answer") + raise + except Exception: + await session.stop() + stream_dict.pop(session.identifier, None) + logging.getLogger("webrtcd").exception("Failed to create stream answer") + raise + session.start() + + def remove_finished_session(_: asyncio.Task) -> None: + stream_dict.pop(session.identifier, None) + schedule_teardown(state) + + session.run_task.add_done_callback(remove_finished_session) + + return _json_response({"sdp": answer.sdp, "type": answer.type}) + + +async def handle_get_schema(state: ServerState, services_param: str) -> tuple[int, bytes, str]: + services = services_param.split(",") + services = [s for s in services if s] + assert all(s in log.Event.schema.fields and not s.endswith("DEPRECATED") for s in services), "Invalid service name" + schema_dict = {s: generate_field(log.Event.schema.fields[s]) for s in services} + return _json_response(schema_dict) + + +async def handle_post_notify(state: ServerState, payload: Any) -> tuple[int, bytes, str]: + for session in list(state.streams.values()): + try: + ch = session.stream.get_messaging_channel() + ch.send(json.dumps(payload)) + except Exception: + continue + + return _text_response("OK") + + +async def on_shutdown(state: ServerState): + for session in list(state.streams.values()): + try: + ch = session.stream.get_messaging_channel() + ch.send(json.dumps({"type": "disconnect", "data": "device streaming has been stopped."})) + except Exception: + pass + await session.stop() + state.streams.clear() + + +class WebrtcdHandler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + # path -> allowed methods (aiohttp registered POST /stream, POST /notify, GET /schema + its auto HEAD) + _routes = { + "/schema": ("GET", "HEAD"), + "/stream": ("POST",), + "/notify": ("POST",), + } + + def _send(self, status: int, body: bytes, content_type: str) -> None: + self.send_response(status) + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + if self.command != "HEAD": + self.wfile.write(body) + + def _read_body(self) -> bytes: + length = int(self.headers.get("Content-Length", 0)) + return self.rfile.read(length) if length else b"" + + def _run(self, coro) -> tuple[int, bytes, str]: + return asyncio.run_coroutine_threadsafe(coro, self.server.loop).result() + + def _dispatch_request(self) -> None: + parsed = urlparse(self.path) + allowed = self._routes.get(parsed.path) + + try: + if allowed is None: + result = _json_response({"error": "not found"}, status=404) + elif self.command not in allowed: + result = _json_response({"error": "method not allowed"}, status=405) + elif parsed.path == "/schema": + services = parse_qs(parsed.query).get("services", [""])[0] + result = self._run(handle_get_schema(self.server.state, services)) + elif parsed.path == "/stream": + result = self._run(handle_get_stream(self.server.state, self._read_body())) + else: # /notify + try: + payload = json.loads(self._read_body()) + except Exception: + result = _json_response({"error": "bad request"}, status=400) + else: + result = self._run(handle_post_notify(self.server.state, payload)) + except Exception as e: + logging.getLogger("webrtcd").exception("Unhandled error handling %s", self.path) + result = _json_response({"error": "exception", "message": f"{type(e).__name__}: {e}"}, status=500) + + self._send(*result) + + def do_GET(self) -> None: + self._dispatch_request() + + def do_HEAD(self) -> None: + self._dispatch_request() + + def do_POST(self) -> None: + self._dispatch_request() + + def do_PUT(self) -> None: + self._dispatch_request() + + def do_DELETE(self) -> None: + self._dispatch_request() + + def do_PATCH(self) -> None: + self._dispatch_request() + + def do_OPTIONS(self) -> None: + self._dispatch_request() + + def log_message(self, format: str, *args: object) -> None: # noqa: A002 # stdlib override + # silence default access logging; errors are logged explicitly in _dispatch_request + pass + + +class WebrtcdHTTPServer(ThreadingHTTPServer): + daemon_threads = True + allow_reuse_address = True + state: ServerState + loop: asyncio.AbstractEventLoop + + +async def _shutdown(server: WebrtcdHTTPServer, state: ServerState, loop: asyncio.AbstractEventLoop) -> None: + # stop accepting new HTTP connections (blocks until serve_forever returns, so + # run it off the loop) then tear down active stream sessions. + await loop.run_in_executor(None, server.shutdown) + await on_shutdown(state) + loop.stop() + + +def prewarm_stream_session_imports(debug_mode: bool = False) -> None: + from openpilot.system.webrtc.device.video import LiveStreamVideoStreamTrack + from teleoprtc.builder import WebRTCAnswerBuilder + assert LiveStreamVideoStreamTrack + assert WebRTCAnswerBuilder + + +def webrtcd_thread(host: str, port: int, debug: bool): + logging.basicConfig(level=logging.CRITICAL, handlers=[logging.StreamHandler()]) + prewarm_start = time.monotonic() + prewarm_stream_session_imports(debug) + prewarm_end = time.monotonic() + logging.getLogger("webrtcd").info(f"webrtc prewarm finished in {(prewarm_end - prewarm_start) * 1000} ms") + + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + state = ServerState(debug) + + server = WebrtcdHTTPServer((host, port), WebrtcdHandler) + server.state = state + server.loop = loop + + # serve HTTP on a daemon thread so the asyncio loop can own the main thread + http_thread = threading.Thread(target=server.serve_forever, name="webrtcd-http", daemon=True) + http_thread.start() + + shutting_down = False + shutdown_task = None + + def request_shutdown() -> None: + nonlocal shutting_down, shutdown_task + if shutting_down: + return + shutting_down = True + shutdown_task = loop.create_task(_shutdown(server, state, loop)) + + for sig in (signal.SIGINT, signal.SIGTERM): + loop.add_signal_handler(sig, request_shutdown) + + try: + loop.run_forever() + finally: + server.server_close() + loop.close() + + +def main(): + parser = argparse.ArgumentParser(description="WebRTC daemon") + parser.add_argument("--host", type=str, default="0.0.0.0", help="Host to listen on") + parser.add_argument("--port", type=int, default=5001, help="Port to listen on") + parser.add_argument("--debug", action="store_true", help="Enable debug mode") + args = parser.parse_args() + + webrtcd_thread(args.host, args.port, args.debug) + + +if __name__=="__main__": + main() diff --git a/openpilot/third_party b/openpilot/third_party deleted file mode 120000 index d838c05a86..0000000000 --- a/openpilot/third_party +++ /dev/null @@ -1 +0,0 @@ -../third_party \ No newline at end of file diff --git a/openpilot/third_party/copyparty/copyparty-sfx.py b/openpilot/third_party/copyparty/copyparty-sfx.py new file mode 100755 index 0000000000..2506c39a93 --- /dev/null +++ b/openpilot/third_party/copyparty/copyparty-sfx.py @@ -0,0 +1,512 @@ +#!/usr/bin/env python3 +# coding: latin-1 +from __future__ import print_function, unicode_literals +import re, os, sys, time, shutil, signal, tarfile, hashlib, platform, tempfile, traceback +import subprocess as sp + + +""" +to edit this file, use HxD or "vim -b" + (there is compressed stuff at the end) + +run me with python 2.7 or 3.3+ to unpack and run copyparty + +there's zero binaries! just plaintext python scripts all the way down + so you can easily unpack the archive and inspect it for shady stuff + +the archive data is attached after the b"\n# eof\n" archive marker, + b"?0" decodes to b"\x00" + b"?n" decodes to b"\n" + b"?r" decodes to b"\r" + b"??" decodes to b"?" +""" + + +# set by make-sfx.sh +VER = "1.18.9" +SIZE = 846007 +CKSUM = "53f9b019dbba5e9acb44f1e5" +STAMP = 1754082544 + +PY2 = sys.version_info < (3,) +PY37 = sys.version_info > (3, 7) +WINDOWS = sys.platform in ["win32", "msys"] +sys.dont_write_bytecode = True +me = os.path.abspath(os.path.realpath(__file__)) + + +def eprint(*a, **ka): + ka["file"] = sys.stderr + print(*a, **ka) + + +def msg(*a, **ka): + if a: + a = ["[SFX]", a[0]] + list(a[1:]) + + eprint(*a, **ka) + + +def u8(gen): + try: + for s in gen: + yield s.decode("utf-8", "ignore") + except: + yield s + for s in gen: + yield s + + +def yieldfile(fn): + s = 64 * 1024 + with open(fn, "rb", s * 4) as f: + for block in iter(lambda: f.read(s), b""): + yield block + + +def hashfile(fn): + h = hashlib.sha1() + for block in yieldfile(fn): + h.update(block) + + return h.hexdigest()[:24] + + +def unpack(): + """unpacks the tar yielded by `data`""" + name = "pe-copyparty" + try: + name += "." + str(os.geteuid()) + except: + pass + + tag = "v" + str(STAMP) + top = tempfile.gettempdir() + opj = os.path.join + ofe = os.path.exists + final = opj(top, name) + san = opj(final, "copyparty/up2k.py") + for suf in range(0, 9001): + withpid = "%s.%d.%s" % (name, os.getpid(), suf) + mine = opj(top, withpid) + if not ofe(mine): + break + + tar = opj(mine, "tar") + + try: + if tag in os.listdir(final) and ofe(san): + msg("found early") + return final + except: + pass + + sz = 0 + os.mkdir(mine) + with open(tar, "wb") as f: + for buf in get_payload(): + sz += len(buf) + f.write(buf) + + ck = hashfile(tar) + if ck != CKSUM: + t = "\n\nexpected %s (%d byte)\nobtained %s (%d byte)\nsfx corrupt" + raise Exception(t % (CKSUM, SIZE, ck, sz)) + + with tarfile.open(tar, "r:gz") as tf: + # this is safe against traversal + try: + tf.extractall(mine, filter="tar") + except TypeError: + tf.extractall(mine) + + os.remove(tar) + + with open(opj(mine, tag), "wb") as f: + f.write(b"h\n") + + try: + if tag in os.listdir(final) and ofe(san): + msg("found late") + return final + except: + pass + + try: + if os.path.islink(final): + os.remove(final) + else: + shutil.rmtree(final) + except: + pass + + for fn in u8(os.listdir(top)): + if fn.startswith(name) and fn != withpid: + try: + old = opj(top, fn) + if time.time() - os.path.getmtime(old) > 86400: + shutil.rmtree(old) + except: + pass + + try: + os.symlink(mine, final) + except: + try: + os.rename(mine, final) + return final + except: + msg("reloc fail,", mine) + + return mine + + +def get_payload(): + """yields the binary data attached to script""" + with open(me, "rb") as f: + buf = f.read().rstrip(b"\r\n") + + ptn = b"\n# eof\n#" + a = buf.find(ptn) + if a < 0: + raise Exception("could not find archive marker") + + esc = {b"??": b"?", b"?r": b"\r", b"?n": b"\n", b"?0": b"\x00"} + buf = buf[a + len(ptn) :].replace(b"\n#", b"") + p = 0 + while buf: + a = buf.find(b"?", p) + if a < 0: + yield buf[p:] + break + elif a == p: + yield esc[buf[p : p + 2]] + p += 2 + else: + yield buf[p:a] + p = a + + +def confirm(rv): + msg() + msg("retcode", rv if rv else traceback.format_exc()) + if WINDOWS: + msg("*** hit enter to exit ***") + try: + raw_input() if PY2 else input() + except: + pass + + sys.exit(rv or 1) + + +def run(tmp, j2, ftp): + msg("jinja2:", j2 or "bundled") + msg("pyftpd:", ftp or "bundled") + msg("sfxdir:", tmp) + msg() + + sys.argv.append("--sfx-tpoke=" + tmp) + + ld = (("", ""), (j2, "j2"), (ftp, "ftp"), (not PY2, "py2"), (PY37, "py37")) + ld = [os.path.join(tmp, b) for a, b in ld if not a] + + if any([re.match(r"^-.*j[0-9]", x) for x in sys.argv]): + run_s(ld) + else: + run_i(ld) + + +def run_i(ld): + for x in ld: + sys.path.insert(0, x) + + e = os.environ + e["PRTY_NO_IMPRESO"] = "1" + + from copyparty.__main__ import main as p + + p() + + +def run_s(ld): + c = "import sys,runpy;" + "".join(['sys.path.insert(0,r"' + x.replace("\\", "/") + '");' for x in ld]) + 'runpy.run_module("copyparty",run_name="__main__")' + c = [str(x) for x in [sys.executable, "-c", c] + list(sys.argv[1:])] + msg("\n", c, "\n") + p = sp.Popen(c) + + def bye(*a): + p.send_signal(signal.SIGINT) + + signal.signal(signal.SIGTERM, bye) + p.wait() + + raise SystemExit(p.returncode) + + +def main(): + sysver = str(sys.version).replace("\n", "\n" + " " * 18) + pktime = time.strftime("%Y-%m-%d, %H:%M:%S", time.gmtime(STAMP)) + msg() + msg(" this is: copyparty", VER) + msg(" packed at:", pktime, "UTC,", STAMP) + msg("archive is:", me) + msg("python bin:", sys.executable) + msg("python ver:", platform.python_implementation(), sysver) + msg() + + arg = "" + try: + arg = sys.argv[1] + except: + pass + + tmp = os.path.realpath(unpack()) + + try: + from jinja2 import __version__ as j2 + except: + j2 = None + + try: + from pyftpdlib.__init__ import __ver__ as ftp + except: + ftp = None + + try: + run(tmp, j2, ftp) + except SystemExit as ex: + c = ex.code + if c not in [0, -15]: + confirm(ex.code) + except KeyboardInterrupt: + pass + except: + confirm(0) + + +if __name__ == "__main__": + main() + + +# eof +#,ht.7?0U8 ZV<*:DkXF6ʻ-`;?r2%dmX01O%dހA"vu5ʚAfR[8Tfj7h MIeXW|q/v=Ovjʎ❹MɯuF>;F'7W% y`}mv`JCr+޿~kÓT0(~??wܢ5%:M`Irߎ%_(6ڠ8?ruY0n-Bsi-g6)aY7q,՞x1HV͵35qw>s}2ͱVFȋ.t8 jOߋ@ F?rM_4q|?nU'ww~'(+X5A"ʑ:ǂ*6p$$~g[%Tۏa2SJ7??>Bޒ+h?ny>PYRLȌΎ=>;@+,^??9Ixw.u&%*۝I\D|}{:\}+֑;KIkȷ^03hǓa|hOfa( _' ##a`?ng86\Uo4w*O䞓U92kKYG<;bso8#n\S??k-j8tsny;.a`OG t&onhb`hdlT, G(G0̙"?0Ȁ̐R?0$}N>5ov7ވ1 y6Q:ӛ۞k)2J[ɉ.\3??RYc}>L2<Piy7xyVwzЫ<__kţjN;*&8~b'==¼0r֩vOBS+[y*S<ҚE*-tU4eO\G|D3??((͡W7442S`7722?0f?0E?0{߽߸4wNT,y{Ҟ;iliZ%H {os{EW9?0H -ۻ&GN f0(W}2i:y,;hy$aLd*ltΈ~ /_MT Ӟ׿n'U8OR =@Kiz4b UE~i(TDiz_4ٓ(\ }ֈ<%k1"v^kHl?0<<8)vy>VmfF)҈>3>]]G2~/SqĈ`o{КnNh?rF1^6yRJ⓽Ã)>iO?0nB;Vj0c;- 2?0_:u}txH|_v'W%%+Y!(?ri!MLK|[]bv\[}ISZC<~1gR~ň)yd>g$x<='[;gog8-:DLS=ql !R®9=S46mFiG0BlqA.Kd cRjZ?nƓdѬtsvVǝE%[^Pg՛`axEHZ??]YZ¢&olx =l`O74aqGz_n\.?r ]W#׭Wk,k%U&?rd-FcezQ??$b| ҩQ*(`2 SVi. ƒ!c" #[ʲp\h&X\\!T Ȑc)qlv@Xf8ciwbejmZ0Qm+PRQ8':'bbQ3iJ?? Res<[zHXxC_-Sx¥ )1Ή?0zJ8t 1J4LDD@JggC?n0TJ6 LR^5:@^sK5SC +#-Jc$|}}0涔={3tNB8c~ff]T0Zz,f?nclaWVc%i(1C&)=AL|c"}d|у<Q#T 񵆰#bl0gmG@C,JЮ1_7րD??UK$t3qRiFQ3-鶈YhD aK뚎$y@E@ 4&j?n.Ö/3B9????9o6_};C>a R)sK% y93ܗ??黽;FMՔr.a??֦#==ig5p#RO.cݝÃ@&@\1/82bՌcFmRԅ`rw?0iwi")?r }}9/rv_B+0~<DfgA2@(-kr6,dtj)(ʸc,X-H v]jwTAخױ; type??n8&^Pg{=XZٶ?0B?r"!ّ5u<u,ϡ5Hg?0CإMK!׵K){Kfqe2lv=8go߭SE^${o-i?rY#`1S֯V4O @=XDi{,% x=ퟰfy٬>]\8ȡ4(E.dY$X}YXA@'&?rdhP::*#~^nξ:/]UkT?r;Lz:3+fMoɱ@Yq,rab͕?ns{M\۹(׋г?0԰#`4TL9M{{}&.A4쿦bB?0hbn\nFx\fD'C5{?nvL_Glesk3:v7-`<??<|Px]~rySTd4f;hN4E|VUVAš/{g4U,(!e7q+taKb>?0??kW.sHw*zy-ںP!'b. uS#e?nrT/XLhSDrSndL.֏׏Ruv92cciwa:|]1EQPuu6h) ۲T ;;UP&uܤt]?0<w{xh3m֫hzq`,t {eb +F#=7a??:aW/j?n*v(+k۷"'o7dl(@'-iBO6ǦMXc*ULyA2<$\?0l.?0M+ E% gApޢ\@Ur]2eQT?nʟdo)R)yP<)ɾszBt]&ZqmåWO y]ev;?n=T&j{g+;T)J߁c+ ZWn``N3gDjZ1,kAI?0 v6CϜʚW~cUtXjD1/!|zW{Re/AݔEе{@^(3g,X@,Kʽ=ǡG[zl{պ\@9@1qF:km -4KQ_O:=g\/m3eFo nV6/O.4*ܒNɾ_2OzKbGR;du {~.KU<:`VTmw .)d hq4-Q$}.An,cPD:𼙀b# MxJؔ9諯 ?0{6Az"y̽=O#&I(xBFL)(Lܞ̱k"aαErANXb~ILh,9OD$xMX??le:rju^D)_Q_[I9*?rJm@jVl(I3SCk/<^B*_Vs:˹d;) 1 B|IJqE;զp)YDvHΕ9VccKDi~z!|B?n<}ԁ/24Ndqy!Yƨ <-5]sP"(!{[lX^FCg&,3'Pޯڀ\@B}=[(!^^X)*H ! ?n?nA/Ůt}tLN|=4n@::gc rK]?n]GZ*yږFuvjKۗ`4^Uj {*! b >?0XspKd<-_ǟ})0xen7Y"sA$/00|B0St=U~?0b2lG:*E F`aK@%Fʫ}9XB&40JBSq̩bƀQgM)V5mBӐ$?nBރ?rWrDֱv{q>lA+ڿƩ=h}A@ "R5 (@?? j,Z +#&;JbmzM6F8úC,hgd *!vp&f3M}U([8?0a?nAxX0 ).?? c`k??qH3[lƞD-wQzڌBGЃֈ6$[O&0.ڴmpR߱aMKT#iF3G ^WHՙ_}W7vJAQ+s{`o̥-\qe0?r11.쒹vY;єsܲ!DŲ/}-^.6SZ5we$/WbcH͊'HjlȅIb>l+:jO;VAj$3ks[o[}Lܡ|Q#=]yDuBZ4ڞ%|`W9aUUtfe1wp#"˗P`\kn-\k^I{"r|5Q;oQR9vYQw'^T^wy/4}t{O[Y:A!^$MAΉĻ w-' ԃД?0{*F\FݣS{v &Q* c,?0\cγz {`3,$OmZ5iliu.$0??g$(>4!1EXmG?rD?0\jVnJ^ 8emNw??.gNO&yRscˮu8q߅13.:rOs{"c\V|VaW8$1:0=Pnnrr(gE|^EAAi$P+\gFok.ͻ~fJf`*W:m̫=}}0Mtg8ErH1W\߽v{}عwIպu`uw]R*6Uw"Ypq`Ai@?0l-Iz^|j tЍPPo6`"H¦"h=?0órJ4_ti3mUbЮ3yKQHNd|W6֪4MZ|M s8+?nb&eӘxvpCqVn)(ѧ^A'ss+B7s?nEsԳ'l L7[q\feh+mtKMHCz(,6`?nrPcno([͗lL/ftAiilR7??Fܞ؉m<{!|#i>M{\ v'^0,!`hb+Tn<S4{c@:yy?0 i)uu4%{qpn}-rAdrԦV (ȺWGo[ɰ-R-4 `6l@ }VhH"-5zT[ yyM>EvPɳ.A2J밚 ?0sK!z?r߽T?n`f{7?rctFv5Ms-DZONCkD==;q(>e)Żs.Q+:Q?rR)ë95SB>u&@ kVu=DҢ&?rz #%EetP9ը'F\Bnx4(uk5t[UzLHo_hntY¤rmTBUujCY=on3/־znshH=.TH?0r*) ]];~T?r~8 Er~XʺKj|&qX,Zj#7X~Ŗ=v(xMKJ8fNi3o2 NqcԜiCxh0b_!_#߲8 ?n<ᏜM(@P* }l'fD/7vM#Ucf&6شJ?rPK?0 ap^ͼİ4} Ch5-?nUp!&"=@y\h䁚μ!m`8eDLI^{W~Y< J}zqmpoaϨpmբ~ šfo3{PxCP7ʩukօ|gY5Ģ>[3??OB]%݉+v/`ztWz{Nxrp0FLs#694 D7:UEu~@=ۮw??ë!R?rv *B[\njPa&+,TWr[*ၬ v 9\-aj.kp!׈+""ӁFCk`݂.뵓XtH<8{ѻ@䀾ṧSbYg<ЫXX6??-o񷓶ϐ4+iڰAv O?n-Y7Ax\'bW4}̸Cz?0Uy{9:<>r#Gz)!u??W04b*l=B9~0^(;rw 0A'W356622505C?0{׹8?n*]|A?raUj*[)u2}UwGPV~ӿU_ HB3ov@h"_j 6[CBBWuS?0!XVu]$L)h"xWa3Vb,?n%W;D޸u"'怨W3&X)zuڅC)Bϳ%m 얖ujrWשku+Y^g}œdյܩ:"[3PZݬf}_'Qɿ(%wVy+mp Vqy2*C>cD8+P 'j䊫_sm/g`` _?nm7mk]3`EXS+ψ&Y`+?r@ CBwG0'qh@Kp:T+ۆU)9N(<$[^f-X?rJiF#l"+:aJB,O!RuY]m`gl/|϶҇¢Ag.84S Nߴx8yX8c|WpZċ3p?n1??G.>˜'Fe>Sc ueeV*puz̫)Oy|$\֭H@<=VnVyeE5U*.JȞn\,o 3=&X[#ܚte6_)]~hY\r/6޷"n.jY8oCůvl<穖`}GqF^fKb1pylտ_n3q_޶}?nˍPEnN'9˗_^!G&(>K+#LP,HYbB6ɆagpsrVD4ԫj{ƫUDIp9I\“JJzM*agP_VǗ@Kawia8g9Ԁk~?n}{ ?rloiѳ1&ڕ-Ҧqg:=%~&쟲q2!XUؤ,|x{0h$5ϋCi.7x(٥Ͳm}'դoV˗㋧KgfXUnxje # J H{>?r-dI~L_6g)=J <B~w]/0\ϣB7YE?ryL!0>MB@ Džd2%AQpSl̢j ?nEf'X/Ëw_@zUpTZ<(T_F4W^ ν 6_̘D`Ɲ9Q?0ElQ1cf4ud5BmawlX/wiFw,3(Pr?r6q.bΉХ6_i說+SQ"zWjoCK6A6;BMkF6O{fͦ6ַ>׊$hOlɿAHlˣvd4"eiC".?r??3Tw`P?0u)|{7,@|NpˬhIMld-?0)[ッ+@s̢b oo0(a*oB X,x??z>}%??|w|77:?0m1^]D~qp????}ç{{^hn#S,3* =ݺ&N@}t!ܴ0'Ѱds/WA[lFp5עe#$?nwV{q?n:NHC??k `?n4ol492Y!Pщ,:/1; , uwhߺMX&^quʰJ*{ΦZ]E׸iavΦԅd#غimC{զ/o ~kó.DQqXl&6M]e8W]+ؼ Ni^6J -qk9<̲+v=C#泈h?r̫?rj+z?rgث]Ar\T5Ҥ./b߸+R-Mڡ\ v?r2ŕFLw,!E0{[teuO*%{M̊\c?na?nvi1Qr߳}&4R:QJ v&]ܡ{wM!x80iwZkINŻhif*WT閁kxBguo|&K\! EozE}??g ed<&V챹D PKpkZa.Ӑ-\?0\f?0#.ƝIKx%UY/_${v,ph +#4Q>@ :VHU($)@*4b'q0J4.7]Q̝9([2KGϞ\؜AtXojѼ֓?0Vq8#S.oBvb)wq7{ $8* 8 3pe6kZ2K%'|W_efSfʜ-&:󷄌6M6;&"2S!}V4y@johl=FZ ^]~2œoߝB-qskt 咕@lP7/U%!ΥƱ!-q\ A xqK?0B<:Ie#Z[?rNo.\ϰ瘚P-J@g7>̵Qo?0B{:;wcbmEYx5AXM 퍇XGT5"N[WTV5=3*T!* =r UD7'(1D:)~pjld;QFUm7D*K報?0!Z8_ՉhQ\Y8s-1`%57/.bѤWzox;)t Kȳ29dB|0B^  am0ʧ/cQUc;@Tܜ??_}UOB?rh0 {Lx#]F@1O(=mؾy?rbr$Cեq8v7y"RjFR ` L5OjXi .Zq[#dYENݶ?r '6ڒyÃu(zPλXؔw%7~qyAe>2t4t?r1-ljey>.[*0_\v,Z{hRsC[-nx 7 ׯ @ Zm 'cW6tK`*Kɩ8cnvE>J_t6kt-&7Ns#ͺ"Ix+?nG߻OEm} F8X.'s{^Il,# 􅦖9uư?0ja3?ndcK짢WgG$N`E0YS A!zeʯ^كT;qTd1Ǵˑ=G^~zmO??O??}"1z`zκ[ucG ]7^{oLk`z?ncX.Mn#MBOրF6 MskLwnqQd'c?n CX#PiN9ccýMc*4^eضӪ??%%eQ"|J;fguԧm֤$J¯Z$()wsYdB4w~|+??˸f 90󽌣eKj ·3\?rC?ng EM nԞj5pLdt?r??0pXQ4sxI˼Li^5ԱRYj%)G~>/oWOFO#UޚfAGL<}dA?0z@d[z5>]>♇?0n75-*Ztzu^kUlG!4"2.>X2`WkZe\Ќ䥐Y3ly|/M??0J4>ӔKߨqT_tJ ?n>ӹOtzqI[ !81~xUc7k #O<MS~xw*!꺐?n"1Juh?rgFW{/G{^h;Z kv+4:ѹgi* z_$}$'j%92Z?r<zT!1QPi*b|ťƪ`>n2i )I7 B3_I "SfN=](iolH[ JڮSW:׳]Y~=!;f)crڬ,DSeUBNQ#,X059=uSthƆ& u~uNqjѰ?n%c.]0 ׁ36뵌Zj[ۗ)U??tᲖTqʇ4j83&b=ܶ6qb8K?rIt?0oVp5ITßyS R?ru=a`M?0X6<#Z٪ beI(p?r1 Ϙ ÀA{.Vh! s\?0g1Мǜ\nP*c0sЫ]DGu1iN`xIj`2?rqσ݌܅??i?r č-^`xtV5?rbB e?0FÄ.[k+\tCg}h2 FLځ8w>sNxþ2=W?r!N8v Y򈦽)V?na>hJ`@89o5q:1IJ?0aVPf;\T.'3,ݢ4`y 7"uQ)Fv4LEXrLtC;բq+ #ɌjG&yuj46.GJSV%]?0??pmq"-NYH3m}4e's@99vp <,0b;Du7_vpgbIS^cl Mȍ||; {>~.ΙlX\Y  xfH!-'w߼De.&]2<;S{M+䉡azt&߲$ې&#['xgN*\,J3Α#Ary5pHm#9 x}2%9xPjnDŽts5w6T<{RE+g0aHWb\>-ղ ?nl ɛ7H|s).?0\i =_ǚIm4{[ab歧l[ADf6llKkrUuդ^y^ej}tBz)V&Qc|&CTWݴewDC!YeJ]$ku;r]ajB#m IP_r/(|n4o3б,MD7ߝukԦ/T/$ȸ2]3|!McL70կ=??IY=?0Ljj`3D+FDk'{q"z @6Wdm_'h&&"=fn=-68К6W{V*A6rɓ`!i A[g.?0q8}-33??,9:zx}5=!5E`U GwqHTYLIkԉ~>$3OI=!GGGG=pw7ϖb2h*4FHy'EtFc#ZdeCSrX3p1 ?r'd'(ڇ %ZoYGs?nG^d*i_pÃ~QNTN2FW!?nCexP+@j(jFcA= ȓ٭rPeQ1êA(es+m'6M*FGB]:4/t Z$%cY@ڒM<]^ІMWkv&_m(K͹s?nh 9=vWg*h?nvޯt4/SΐW2P |kIU qPP =tI&U)qC%<ɰv&X)Eo?rE%r DTa_>ٱk0 MVxܟmg`:v7Ǡks ǟQy︶[w_94[?0pߙ~?0>R?n5xcp_Znܪ5vʰn^L9{moElcZwVUۊ߂6P栵A[Up):tj|fTHM_-r sFk?rn>?rTl(mK0V4D}5Qe [92]D0Ƕl#~jT;jx$5?0Rȧs!§!)%Cؗe?nmL㧏$u@4oǵA0Xt^!ۡlx;h&C|O^0=EX%ƛa2A"9=齏{g/eyݛi~_7hB ~ׄ%OLeɓ=LNjH?nzEJ)UィO'$^0=G!+4"Rkj +#[d8ё{҈xJ^eebTp 3V}uT(OWf0`eG1o1mFX\$%;8M9"s N{7LRƓݨs_6U2QdϯM̵G%R;!$;=??|$[*:4Ȥ}I$D?0?nB KU?0\13`/pe=X4vu4A[l>$n$Z<9R菦ɛ|!9?rH/A(&./q]w#, h[`u*5We1 GӬ~Cő&^o-=P&*7g\r]u뙈JegZ0/P4Và*@YS~BJ5;J5U!_GɃ7O.??+_ޓIƱa}g޾Ҿ+l0隿~>q䣎-a^b̻BBxe/16xױ6M'THx??.t9C^??˻??5qF=??s,2cˏ<%mf|cy]8:#FMٓW/\*u&zvvG#y>EeX&U` CHoM.D`#]v 9$]M_ā`=|UϿ;Ow/Q@]G1)qك1Uu6EPeTr9'T{4B'j< 5ucY;`Pqg',BmUſFq6x˓W^t/uTCEVH2ggznaO T$WɰG-sh!_hMQxfx`P:s Yhܚ+MSqcCؖ:n[ḻLZ,?r5)ΌzN%8K*Z>lM=zZ:_Kk6>_nU&kٍ< <䐀gIhKPjj/_j{&ACcY|g%@jiAz"7>V|*&9~L?0v@AG!lSUN[Gơ?nw=|p4̩yg4:TwwP J+Sľ ЩQETE~~WreP^'ߎIgxTby{-(u0>oYr&L3MY(sIKs5:pC]c%xm;&u7w܅WCk įOvRϗrɤdoj,}:~P qr\N707l$iH] eGx>D^חړ6+'Fv듋X6uBNM4CːZqhGA֥@;CG)֛`(^n rB2ci)N69QF?rybZ3z,bDdZfϨNCG2s넜rC^.B?0V*9cmJ3O_-+)|!dL}Z7oo ;eɑV&7d\MT}ھ;N*MLk^D*$eVlKNA};a.i:+gqt>{T??I_jk"Y3H"70w #HGIf+ePTìjC.Z5۔Ag4 \YӈV) z1 .)'oUGFѵh$1jgu@ѳ4z<@bt_9Yqe!\u0KHtAo*v۳??]?0ժP?r Auk<%g~3VOݾc왿o؛_uP24h~rd;G[z??<Lf׊دIٶ$Qc<$Q$m"7>?n>Uf2UPNs\Jm6VP,MP"\ockmgw.}dL022o@ ¬`i8U!;j;AHLJ/,hɮ8o=+"vށ*t?n{Ffzv\z*GEс%Go^['lNFQE]2m3XCY>E:VWxKbruH;0 7yw1Atf$#wPp N2k!?nVT7'2.j4ۤŹ =kdLCqWqG#ƥ'؀z?n% τիKjZ8kx`<bJ'~ปUʁnV??.4H%\8b~6~鑝=Z8✤Ȇp6ԋgLJ/AZۢݵ?06~}ʅF?rEDbϷ{<*+Z)".?rCuRM.HN09[GѦhfSB8״N8/BnuXۺ2-LcNcѼύ?r[A˄uG ƫ`dr(N>F ɢ73ѶFK;R,O]VB??e1'>@7bL3kTY4,3ĐR Ʃ1Eiߞ5HKͨ$[O&Ne5V%xvbYA' ?0YU$vvcS!d%1b-GKF Lcv,P}$w9ix"Ѹzݽ"Q%lo9V3n#a]!#=vzǒ:tB))]כ\(J(ilր{2=XzUqf[%-6V[ܚh@6}f?r;uO|N흇[1+i9]8 )`\(M@F}p}%J%Mȝ.{Խ!!L6UaL؇t,q\aX [Mz?n-ī-*9bWLߺ$g68는qQڀڱ&J2K??jEg܏ f}YNb>լn'^7"3;#\8NL217ƵF=/]ѣ< 1y<M釩5 x$fEsĶ=n%.\1uPvLsK>?rk2I,#>y>8$F%>}E$cWXnBu 8*R,l/Lg Kl7!kf&uLV^=yO/,XP29$i&B6X֢*gT"}h"Ѐ%=l;*h'rtg#|y @,p@oׇ;K"_vjf _VTaoYbQGЎ\B?0Vᄃ hz烛Z (>g^r6VKe!օsZchî,o[]L<5ۚM"M io(G94p\ty7pu*k7 *IN2v}Brfv`hb񋋗˗=&X\Agy;nVJN?? g?r`z?07=egv?niHD??LݍۙӋˎ:B+25ġtZ\Ys9yD'Yn֥1.-#F:[(3)6?n=^5"'H(>T2A$Ťj]=NK'xwP7^w&n 9S+_=|Mu M\DsOx s-Yy>7],[f u| 5?0n*yT yV?nnRw7?r|=L$uQ}!74Pm<آnnVc)$HLm=6K”?n[S6տnkkBf5V9û`~T @D>ZENH拶M8FNWsr??YG?nOnPR]Ø^D'VFi5z# #64;k]F>h͓:qſH$5ifp|I)-OT?nE炫mT|h[3hR}u(A~¨4j?01j:3Nt|E"'W&i y}ڿnh^%ϙ_+:NvR%%()]krY#ՏxJ–Y?na&V]ᤆvw qY ??5d0*^x3Q)??RoNJq $lKDr2 {);{}(#&m&Ύ)Ԭ>.iF%DL7R>1ac6}7wh0ܸaupPx#A !J?0>x{1>*l6㏜=fRK%8iwo&;*$(aYKc rpxHbz[Oæ$e.׭s .r9%O`rU2t$T~J-4(X%Y'ޥ ro*._$Uӽ`oʪcT-Mj~{ wMǕAi^Ȇ?nwB1VGuri[m7ۓM$??7iw-4dyV`?0^fbA:S?r?n͠R%#XGEt brdD5h!~u)"TLGF(Εr'c@H3??7miJ?nlWa튑ݮdpdFu7m*`*9)s39_gϽBk.bԯ2&Fm§))P ??"p+N]պtfq!1T_VZfI{* ս3j2(rcqtt4~E/̥Eq|ˍnֹuQ l]Ϥ&>-}2/dT+ևP%$ܹI?r$RUS.]yZ4{'3*{ՙ '4\[K9v8eR)j9YZ Ϝ nSvAP|?n_ǬT~h$,,=?ng&[FcP;}?r/|,EڏSe_ '"H}AqE%?nr C,Q҅,!'ێ;w༝kX.~uTvVW25*ä,(T,k_W\%0b??7Q8w#Di&.Ӑ_??| P'xc4rc X5;u+K5??*oIUby!m(jFR%9d~pCoTHYɠ1!Q<^26?rr6º3}$??_l"s;w3-WF:ed~i~c(i`?ra&?0UmrwuS_??U7xFuS/CM#Ǒ _I4eɯ_O?rxUhr޳EfB?0L+T?njH?n\#?0Vf5U6 _qbJ$,u?0V^̈́oO͔o/+IZufMOA]}A={it) zP[k\|>[g>:N#'DKq  +#0H!O7Sm_- I2\I#f(4jsqA59=גeГCRoONPOrQ&KL%SbXPCQȳ3ꡢt3ZC 7oI=;y{q)y2;$0k͖sdC(Y5WnXDt*m&(l?rmnͭ$?n vGRbtSlq;|EH%qx~Ihlؼvvz||j_.m` J"yO;&nPw(Z}-BQ8$$??63']$r7~u|ŻDnܾo'ky!失Mk!mI3yDN=n#)'G%GH{ĿtTf":qd zv|ϴ93̊XW5_6]C7]Gs/=rƋY2O=|ѐd{U \G:`Y".bzj +#dx"_{?r"*֭,"n]ǯ^>AEy ?rAÍ^tw:(O4g$`R??|W?rO WãAKzk 5&gƒP}|MWPg{1nD9Z0(\!:L*![_y*9y#LT+޽&# ް~5UCD<S_J' kRPеzI\ SA!zk XlEm??iMk^іx?n ,F)?n9p7{V٭[W'w6'51#_/2+??~!J%?r.ۤ!]p/H;T}(,٬BmDMoo݌g&6֜zh0x+Ix֮ͮW$֟MB0GzGj~‚1W;K>)k@?n>ܵrV)ټ_,sC3pVIU$} f`@w_Xr2/،el9CFomln?nf7y11_h??lƙ1e??}Jav1x2*ɣf?ru-N?0JP)Jn-SN;s?n k NiIn9\-KWQTtv][\b>`kWU6VaßV3Z?nuD,?n;gunEoF?nȸ}"/}&"#-RmՐ#6w]lFL;>1VB,ր3FA"P)?n}#sUq}@xhcs[zߞzVq8,XoQߴug!}B*}!jl(om~K-?n--Pğ]T6/8ᒺXgx7G䥨@33ϊxoeŲD6g)Eʊ^Q?0 t2y1<x%֢)H~7wF͡{$?0MBWb RHJ"/Gi?n̍3aS-P>p9z_n:PƂ^v8p`P7Cep gPqTr3RoCSq ^Q'}G'l~?ns$(^~Z0?nps4~fG?nF^(F4\PQu)Keq@x_eqԀ* d[јl~$zxp'eT6\Z]J"SNڼjPůKT%߃.L-La}G0,FesHHjb3j"1mZ{x*BP.ld-(]9vY` umBy/D.dY[Km!2fEӳ8?0}Y^nEQl76YQ*^OJR(Rh#T|Bsfi<{1YƚxGzVspħ/ZЌ$f6 %h\AlfG!BGt?r曞]HѪ^+:yYA%m{3,+z0}F^m4w<3I +"ԧ>.ټGcrբ:$F?rm@g|x0σ7R??͛绛7ݼyꭺ??_~'}G\׿??HDK i?r>4$1[o挸 y$`9,wr8cFֿeA;eyee?rC8^hKv;6fi:Fz7پȃvezW&S)o3|<*Az-`wDz䘉lx4eu~# +#x'Jf.E.O/xܣ]zFe\wK4"Dyά;fcgq1R ٫׳NFGU*/TCc"?0Uo`i!Sekɳ'qީִN|,Q=tK*E?n*b,ȋz*bT ;"vz-"nb# X之2e߬sXrMmtK}iGo)8k/xgK L#C i=ZkF¼7ck+Vl2 H|QA5=!mp x2V1Fw|_ϸRT$uE3j,o&f%yk Զ%/L !9>cXl?? ;,Hs\s=}Ic?0Oڢ?0^}ɯ+}Hǐ&^ !2թ{Od۴c APW`8-L؜m.t 8z)R6adV6+dͻ/uK\w?0쾬3E4&?0 jo#}&Iܿ$'`?neP[R]LJFL;[i_4d'xic ?na`_Cqxh8T"mTY^(u*YD7 F?nh7$e)mͮݚreE۲|`ns~C@NAEW}|ƙ;GXqL\p^i^0Dݙɣ7@qF!z3-3kPv12Cj}g߾x^<;6g.F?0ٜgiќ35'<->4nD;s~`g7x}-.d/Rٌ"ycXHtpmQs&WqgN~.SY9\iYln-d2V4?0uhen>]RR3>!TA{{|^6T&ŋק&#g$zb 9"==f?rby?0)e8e|cS廼X:-Bd(>P Gx# @3qGYRŐ??}#EP ,{:8X3W^JEza,:~f??W 2T[%Ȑ%:TZΧ??C5קzo;)#=%iZMZ k?r8et0eQ~?r۪'\Cřa7=oP5fnC{{qH9~~Y<>(eka /fB$Ja'qsL:l?nDOwY;nP|82LdRɯ:/o7oԗw'g [ ePMͪ PM,{ݥ@D)Ceax#\nדऎ)} ~ d*n,Gdp7o騠e9˪@rڠh 𜣚&TblƓaףO?nx<ɹqɛqi2$I"t[/e.?0 miu: :WLRmhYf@ȝYFu73U8+X&ѫggG=y?n8}qz}owUKRa/}n;DvχF} y_:5*\rH]:[ e! dYu.VRV?njf@9Ҳfs}TH0P)?ri|-e ?0lrㅌ gb@P@4m??x"!S\=lv,<tfrK;@S[1_؋.yЦx0;PJ/61K73쥝aQSkZڥY^/fkPVԓu I=jm>J\GW.Xۅ>}=i ğ͚ V=(A:Z+vy5!z??F1S2qʟW >C7JܒBm95Jji'D]ȋ_̨&.;5-VIJE?n6%TNjs>lfpd/aSH_6HLLȂz?0Gf^!Y3cM8ˆ4񌶉*%,wXrيiέ;M9OFtv)gZtޜ$~uUduMQ_9Mr61nF7>5hgs^EK oQ?nݶk(,_L*:0ၐ63 P쿈8&y1Ё4Bn?r TʐƏBiK% Lq((ף^InEqY+#[3??Mr~8}Gʏ"Ggq~%YCK7FQqsM~\ϧz7o~d.b_OeK{z}C_)٭?0sIfWPzb-Z\}Z)׹SY=|YUb_f)huҶ,m12jex+a!~],-|㯜";Y~nԏiǥVZ[#\}V~ľ29O*Ũ/*T)L}qԔW//S?n+z/KG.RKՍt_'??*q*??8ڨu]lÆ?rn1B,9LThYpLmb>)c@Ovw7ZTs SyEQQ_tVȁ??oMzP=TƹA/@@*]mPmmJ.h &( qRa\={{dwڱyN /|{Rs׷R5'h^n1(nRSPfi1$;[|}OF&rJ{l6Hya3"9o}KN??N}~9L٪MyP3*pYnncðGۣ}LYS{]~5ZIM_$}$XcjQH;ڀMXɋa5VZbT??!gCP?rw[(G.J7ȑni?rZC`cBk:@Nb?r(؎/y?0]"^=RɆja)B?0 ]ܨN@>QjI?0GX]΢aZaI4yjrbg6kwC[ȡȯNPr.&(a%u"=5٬wdUl?r"?rc?r* gٖK"xH b0%$T A؎$fkr??@KёxpE.|:K9=Hݸ~oh|} #$]407:H.t҅ź/8^fi8Qt$/&_o -m{tӋ3ק B!$n:vKYQgFZ+g v< 1RE]{̯[eβ8D?02_6 }-,^c +# 12&FԯOֶ-'-^wfvJ"cT?rôiS]bpK/4gZj fj5=DلoJkz!x*b,$5+sDˠ?nwB~xUVI,7&hYp"!N0Y i!.'aI{tCMiKE\JwH?0*Fl?0_̸6ݽm&vWFrWa6"Z(h]l2A%\Q˛N[:PʆImckmN.s9e']$04QE xܿWzK??'[!/(q_d 7\q SyLԟ< rj^s1-C YN4TᤉFT7p :xnJ1~A?r^J?r y2i~ 0$*A}+--jiZ4)D4ᲣV_bEfek!d'ҳdXaQgAAV;ĉ*h6jży pJ>6XzejZ-*\8_Hw81/zRZa<̪ fTԫ۴| h>ԨRި>0,p4\)\_ B^($=3lHnfBɔGgN{ڳ"b^Zy6"_A{f:Zn2{1C`[ i HH1{Y_hYâٰ*.Nӈ >gH"i^q*?nZu̹aςO{ަgNaQsTƄşqV!i<~TGE,{Uۨb3}@͔??Kq)`Þ]ӫ%TCվ??4b1k02Z..Zd״赦ETq9c,\MM jyE +s2vQ F"̶b`Bp:eDa``r9SL A-91fr3U(/ZS2ȤsVM h6QcQ`C0i }V1e ??6lH bT +V]tho?r0lJ?0TmUuуOahpwn&fepjp&tPMR UQEkEYAF[$F=VMk$?ndtJtkR>zцy3߀@QޛC⽙A!:_.H CDk^W p#\ix4>h~~[?nN𼆂?nmC(isfn?? K) qW7_67e)Q ai&C $X|}Lׇ?n;$ڀO#$Ib9ߡE;r?0uރ6G dͶȉ]jk4''D??HAzF㶺Rq=)$r1bE d"?nS\JhG0f܅Pz̊PP?0f%NfBLƪɃۖTKTj]^Bj/dpyѦ܍(%\ΪI{#/F&d*F$̐rZyGbwgw{WxseUe$꿍(mCyOJ"%z")~2V` SasUC f@/ol<+^'GɴJ̮l hon>(ceU*0tMI8hDY}wuITZT 8jn>$ ZZRuhf) ;NlK?02vvv{ӱn+~8\N'\;Ucigޑl;8M48EP\Cͣň8* 54_yo3zYnDi1yUk{`}:['/ҏ}\#-2D&ynAKd5?r#}ƀnMVL_aX'orULQ+[vy†J@V&='̪\cVY6y#Y9/=ao/JVTW/O,]8ԫۜ!G *rMLh?rx uRNY ?0t:X{2xN_>{Tߞ|FYOJm1k=Fh:2j{=U4V?nF?rӄJf6XO_N#I^?rvSՉh Q\|PTF-]}=^&/#6|PNV4Auew=<\a_P},y 2αuHb.}BEӐū@?nJ_ybwm?0knqeESǒ@M6lM2jsU <#Y?0٧0]eҝHt ΡEh0|K#E>-og8+harhYNjQo4!Q@q1:.?n9n3k׌;꟝_\)!ZJ#iI{ !1MS?rvojm{6E΃Y_?0/3f?0N"rMBQUOUvLbZ.dcG`]?rYEH4LaO;1zNߟȓ\b)u rՀ{>n" a=P,-OOƧ^/W_ךwT^L'jsyBѸt犴Wq{;4tXMSR84@ӳjp MlFdlϚ{TDA؜J+MCM)#aO 2bF :#ax ÒA.0IN?n#m]FpɇN%7b UuzPʲB(S^ Yj14lI8(v)ҍ٢@{JKMoដDBUEY6?n^^}U?rx/æ iXG~*^ԗx#,'tN.:0=zVBt`F . Ha/t859'TiyDX BYWwp~=:&d}$ԗ?r扂-bKN*$@']|!S!9`$"p6*t6qM/=URgTapdQrJw 3۾O'+%vnoӻ;E_??#!-ɴD\]5-78@JBX2?r+h۔~K#|v^nzm?rC4jg.Qw79cT C utqPe>henVH3g{7#:׍6EPìE0KEf% 7K3#.Uer6B ??Fd?r2WIe3>8؏_mø)V9j"KH-U&y^, SKg؁lcdFqo56Ǯ~-zUI$E0TMw?rgrԳGu??y?n9<x^þ "<#,)Da8SkϗX ?n??l}$O.V勃8$;W'YPN&+V??؉TpzyQ1U*'Y|N??|~f=v7݇ed;kE߃_w??w矏 !tׯW~[4QXDctQ\N!!ȭS?0l"WHuo?r#g?rzuU'Sj+bIbHY}!0Pc-5Vm??$Υ,`Azē6GedtzH%S&FÌx~?rY.U"ēKMw6EvBi]O@"rabsեMa1q'llwXO}zUj&%9+M0J1GUZbZ[?nV،hTP7,4sG.D] ILu6dOI)y/zQZIVXēi~'u`T Օ"}A#lcFGSh~Y.lzbܶjO+p>+?0|)*sjObrt[]$%+"MQRrғRRbQJ;RCgf];)r_~Gzqtah6ϚыgAo0}/X-7vyT7la5^EJ"G[$j-f0M#tJ'{Ѱa>\?nF?rqõW[}u y߷^77??0RxaNtL6PVs}&@cXknYEh[EWK9^-aH^QуQ3 !Ŧ,W؏kߎ؇>f ݹbWۍ2,9>7k&!%\̂Y &}ʷock#_iy:?0kTȰX^Pg#va,Q+/gVɌego<5Zz l_S`2ok)god4t823VifmNj`/D/Rev}dBl|$|jjP2guqtIId&k 4։"X]^?rj[`BŠ4-|ׄ] i:*vQPv6!$g?n|I#t\&4z?rѯ~DJSW`$W=@%\D@B2??2fRjw@$ά`}??|k?r| B{~?ny1:ޣ'Mޗ70oye&1r +lCq;$7qդ[g5آUʨ'鬊LmxuY,sFZTDwcNFg)[$L0dgދa8{~Ad/knf*; 'h7?01XEE݅]įޚZxbƮZ+C+8`^1+ AΧ7Pq)t5_g陞}-9Ė}%ٕϹ1O=ŏ0,?n%Wb" H zJ)#nە??^x+\܂j4r"TQEz K7\2BUg5w??i,uimFXK9ODojӚCM??)o{B?n !}XKJ@cOZ(?0_Ga_a&'PUd,2"Vl>D;,SfkS96Xey |x-+Q+v#v<8x|,n/%m=)>0J ?0.n?r<_Rn3WNg}] _WA?nPXDDh'`zĵ33g7'sLm,?n 8,N +z-UX= GJڴ3K~Ɩ] j{ A˟5"FA,THͫ)`y $^%ld_1s'=z"?0*wFBb3s^ƶ}R^QMħ'%A*\!}HE&0㕚xڍNMEA9_Em]?0k!R'??$NzcgpV[jߵ9J]Hc Mm]k:dM|%I8äKX2tbfQN<N@\*XD w' sf 9-xL/m0zeVۿ\mIN-_ذV·(ޕ/ 0=4_K&¾Oݵ$]Hgk|T^3DB-;ar_s[dbZP+-VvB9/e1?rSiCĢtGV84qab#^Wj${f&aGN.=73aӚ:;wl6??eir ΁kؐؐF?r^82m"V??v;9-J+i"H7p&&X6tČT'4 de($^24LQ?rÓĜ&@(h7I!o58ee[v1{tzh޵C7<sWtT_$mRW4^!s=e?n*QS ς ;?r:6뛓\urA{:lnEj8ꮫB@~=_?rG"E{i*[[šeş?r!:N"8MV!@|AtHqVɻ'w5w6 &kh0Cd??+T0>n&:E-n;j#e^pKxrPb 'mڒ2?r=S"ɾ7q]sj! H-BA9d??/ũ{Vy|~???nW(&?ry:VQ9Z+~"/ṪA#x`㩗XdҶ1 xDx'7/j2Ղ#zEH7**!oZ8TcC1@^ !^ʏyh|XidY>_&`s9E)b}ZN˗&s3ľwKg"Xૈp9q5]$J9CԩiN#x+4/0F05HD8.3?rKRe?0Ѯ?nk?0| #(re0z P{E0/T@#5ѩEN$Y.+yAIWC}1ZddZ(n_M?n 'ESQV aO7Nʪ{E:U߫09W]N Θɋ["6Z$H9у6")8Rͭ)i+Z`QSw4]8ʮ|6I=9K?r{ކ+m?nkoE4r5f= w_ykb-0VkVk6TyU{F+Qcl,=pN4J<ˆG2#skSfDtR+V!@*uP Fg8K{.. D&"LoH莘Hȣ&:ǁ;* Gr^ʴy^a54?n=2@ a}m,!JʫtWz,NA ~??s- %po^F^ڧk Z<ӫ憊hVz$&ԗ[:bL?rZE,Bnr_7c<1Sol7Eqs<Zk>d]RXg»4ۅ͍b'UպguzwcH lK5tHtsu}F44ww +#?0x]#١+D(T3{m\>  7aiIF]tm}juJ5ifZ:F}F =d0!7,Cyn/8??W?0G?n%c<44Fc9"Eky~-zAX݅1Ŝ~!cۭuPiЮ'vV}+9Vc10;R=yj:b;vR!E~V 25ඹ'_$ecQ{p<^_yO< |f} JMws@i;W't&]9Z& W"7P(82SA>Yj]]<#ptpM#zYs\ǶGc.JHJez5;YRG|T/3٬H[g2+=}˖z+v)PV̩Wo+A{k_0UEմrJ= a&,# M+?n&!f?0HixQ֨m,ha*Mb[+F(*Kr??)??/b+?n]E:j¡=ܥ37A#pd4z||||]0#0%]W6M%rloTIQkXsoKNsErdɦ'ʴ<}Lէ??Eٷ mjWW!D=P}+ʇ{,DwXg/N5ؗ8rv.@mZ?nM ?rTm?n߁Eblf?n 5S5C?r+ގ4cwEA&y-AptWvRo`ӌ~[t'?0ZXɦE^?r]8О{Bt??ZkV~ :o*l?n(?0 &p|cmb>)0_?r)s3@f#Ndz)پH|H!5g9m=E^<Q  8m &3cgwmtbE\`X.+3Wo.1/ʣ¶ $Qʶ3v\J,V\]AvU.45b,OqV6.*V:3*Wi8R{?n?0$jqIuSo=|so)`_g4w!+eTkGfg@o??eGCĺw1(ChJ2'p"=G*(fBOuAM?0UkU#mgiUZ_iJ tO~p9O!C}6G>2#f'ftj^$eA{z $3fMqnާAz??̌!K$%˖Ët 7R6aHܖfng/4!E̽VIWD"]yT}Fm*VL_nǸ5c_8?0 vyZ*ĻruQO~* kud?r F'Vc?r3e7`7z<"Luqϯ<+;wB-QAc:7ی"*iud{~3jsC;z-ͿŮ>?n)3Q]h]-Vj9oУ+0܊gCf*e]c[6EZeo77t"^CY<0w2NEn$ݟKI#+kE`,P4my>i7U@T P>.PGjᑌ\*VE8! }r^;ª^thER^V"w<ZnX!}*I;hP~F|N@'ѩlJ??Ya,EvE,kd~A#,< wK7N2w 'j~͘{E5ߝ[9t />>zQcKo|"v+v@ۅr֯OڿjG0GJ~dR)& \wUiY]֡(-Q=5OJMWHN"HV'Nd͊Խv맭t뷡sæNg Nvؓb??r .989WQyltu(=ז2Emꀖ'6JQC?nD˗Z?nRI>5'I.]?rw9'5Bꞇ˩ Q,= ?0"F@lL?0f ::,$cwݴY= "wQF{[hgƍb zI-2wv}Y&l'DX^2G'P(-Ië7Y(1ςgsC!EYO XBc`r)+?nnRW[,3v/IM8}tȚTB_҃|i#-X^ɝחɛ+Tߕ1#J&VC U^b\#,R *Dַr vǡ@7BCc_d>=0I[邅l`T+M\%Ԣn}b)%߁$ݙ]IҨkl/qmvV852KcA)JJxF2k$Z)t:tG}K/V~//V#.TQ|Sj}!yR˝uo+ljMU>?0ݹ> >.+W7H6rxbA_S/G1fKSۦ4׿ـjBbhq* ?0 I8u .l}x(?n~;2xBp԰%SER7#G6Cewv'X6Gwʛm?r;o$ |'RrsXuP)0!2V̝8DnL4e$nN?0TvZFb&7 t$5X#XDFonop|InuSLP&)Q?rwIYсOn&F+uz:ukH\EFcy_lN Y-puBh/&rxe?r5S|!IԶ)r=IFJRh-i8Qvx=kvokDە;Oa(frةŴ???r)[<%nv\n OCto?r.̪t >2ý V`}8}roZmF?n,\<r^Usغ@Y%;OfTjTr.Zjn]{m\/;:FW' C CnjEO~ݐ`;Z ??H<%}5??}=;g;92?n %gqPEF%}Bh>fX#dL?n>R'CۣEuHb}7]ZDRНf׹=B[g-)҃!N 󌔫??e?rvր>m(nu@ۮshm7ݔ -W=9J/dm%9g% @X}ʘw_C`:BvYtY*c+%OXm`½TOOCyN~.fPQ9Qs[7ךҝ`R"eWZtC@dۄwtbӽZ 6 .(ۣс[AqӠ[߇rlwqҢey!WMKb\ s+ߧ(?rWVWbS%„}eu%+H[\??[]ٺ"ڵqyn +#ɛ>'[dYڦ'hx1 |tM}P>)'P]}1zބrtm;a퉂|L_Z!,qήVj͌p!7hH*]aTDuEcX%61wu8_+!T@4EZwR?ne]`;+Mb".psu ܰ1H2nt j>>N(g-&CeNyS ThByD@^ㇴˊcU45ʘ?05(Uk$!\}9>5ʉ 1C6ۛOeu?rniqһ'[8S;V?r+QĀ9'M1|?0ޫ2Ʌ $@mNḾlUu!o4TWҼf)! >Т`|958TϽ@iou 0xl}XG?r_c{=c1`h{JG1oY ^e,9G!Y0,H6K\e28Ua.>6?r??xtM?0mڅ$$ҝqZb1$ 1N'ػY3@\IXGa\XO.w>\~Wdm#f4??2VUpD].l?r lu[J?n/hVjQ?r]1wջ4]ZHyBs^Me mN|C(':x[Es,y6DB/B] &-@do{g XJ[?rξeUתL쭒EwX_E$ SK 4"|>tPӸtV=4>mc|MAY')鵮B\rmaQ?0JpM[uT][ ֓>.C*Q*yP⭶?n;Gpd"uV{m"+ty9u5M,eWzl]/X.F9&@HkΣں-uK,8Rʐ쵴/şjnY^g{79YKT"v"h̲AdӬb.??aUly nKc !*?08. i`.ݮ[\`-mR|&?0K.9v?n9EA#k09r&\V UxZ'= pچ0_ky.ֻa H탵n,Xf.GvR%+XJ'c]Um?r[}ˋs??Rr=9w۔LsUyGT3 bz??}]f5>zl7P:6[l#AߛKiDo>+d??!zGv0Hc\(r.H?0uqx_њOj:|#x,݆uyh\bpGVzcRh{)_{F@| j)/F?ntk޵J!փr )s1JFE5tܦaUՉdb/N5$ E BO9GZ.e -H۸ Յ9X?0~?nY(VM,P^0|"1KEoz"IԶ j~ɧW=~JN&ml'}BzhQ??_RN ]Ndt_P ƮV@ͼ\$4Yܽ!y??s#òoɹ(w3G#Ў3Gc6DG`͈8$@U04a D??m_ctsLaY?n첤6DȄްx*7#u6 I92ek(f7/(Wnv@^?0ue@ 6[b<$i]zG=&?r IMk+G4$UUR%e USduNw!hKM{\SOzг3F] |>gsGsAfLh=si"aWCB*U]?nu&@)U#\&oTBcկ(Fg'_?0 ~ԗc*PJE$yUOzU.8M10# iM*=@ڎ!W"~9=oיSۚjnt^ǨǠF7eHo_xc(u3VY;lKF]}&^sPmz"noiAX4nɌ\X@E7fd`a{}Mb!QEf&??W^-P;?rÚ NF?r?0I(˹Y% ϗPHN`6dAԩM2%}H/$KE$ bBPBH˾_bC.e8zA߇_ oGHnټ.ջ5uW/m[ڇ0s&hիE`*Bנ3f[}Dw#e^4gVX5=8Vtj.4J?n?r}OEX5o7Ku`Ʀď]`5_*𨹁DPqjXΖ(ʇ0:fΓ۩&1??AW~XXWPD<-A!?0w%m2˪1uk1/RlNb~KpN^Ɂ H|?nw/F4>^vMAxl9I*'J(@??>Uݦ5Ϯ-yNΨ)e—t<g:!O^gC.?0V+0hnH%Tr)"ztq?0RaT ZŶn 3SW'vq>h<愜V>uשw|q3?nxgȷY1KlxOQ{^ᇪrJF{4F˦Բ?n#{ X?0P>޻ǎBB@+8nST\qJti jF8Ub*|q.Xۈ3w??5C>GЫGLU4h:;O?0Fc76{i@+پ?n.??G0x, ^o:0bb&G=ۇ۰qc<N3RNI2PZa9M32q"Ӝd?n02׉N9N LkXUYӰb3zUR^"ᘤJ|N{2J]ZY ?0d lbj?0 Ppâ(C"36 ??0e1B\c%*5BD[8C x޵͢.Ͷ"$I7dxlAQcD[瘖m:Ji6aaw3mĩ+ZO͘days*0?ni̪=|W1}%OȅeUlMƨM)b۶%yjfvP5턺[8 G7Dv^T?r)Y XWt?n~IdQPaּOU,O?0O???rQtnep^@Q/jܚчÚSpk+OghH:#S?0Pv:Ґj<2OF` N),{7E;nJ|p  C.Tu 3j}99vL6_1??384uIK7FC(QwY(.ʹ)VVstagC(ULvuq\(gmp*F??İq%`mXZ,npRܨd*$+M8 .d;qoZd8Z߀IQ#< aD4CMdI{ѧL~OMR??KM5$-"K>YƆm2AY9d3m&]?0?0}۶??W'H;i۱7NҜV%QJLR]pq'==͊$0  #-W niA։vߕf\^5a9I6T6||q#f`ζ(#[cpKG9H]~͍PKi?0??NY;ukO0LO]oBB(޶,.Bc&@?rBvWvTl_[f('%UTp?06N& F tV<qJ9zlp9 z GW^D˱{61Q)G∠Bt24Zޠt+LK:X. n(U 2z??A=J9Nsvuw=RˢZB{::PJ}!DF'Ї'xݡCᨈUwrE3 09;#mWm))`ʜ{JSs`#!t Ibne-lhʪQ4h+@baY?0y?nt3Z@?0 !}xZ7WhkE_XeIEO/fsOY}$?r32WlL-rf2o7xv,H MAi`GK7RAkpc}'*2M#8n^"J}(j[P|YSBQ-K]6*6O!!ɤM??|h/ʺ. +EK osGȽeT~b?r LwM?0CҌ]SS?n[7{/}Be~ɷ52`*qHh{1X^*R>i$V\2 ?rxd|dxZF},]zVFJβ2v +#Lٝ@֦`[Q:"{UH>,}{C!?nV#Q>?rWQ?n?0晫r}Y(Ï>Aβ ĔZ~yh<)fAEf ?r h)Y2QRYp[Ɣ^9W}%@4H>֏;Sm,P@?nPm3?0X@X'mL?noYg doePy`!LRTu[;lBT:p1LKՆ}0@iM$bwu%b.Ι&ߩQ }g)2d`r(?0SS??hz?0%ľghE6<'7b'X鄅dKj ?0݀2]yu3~m9B'h#m댇IF79J޼yx[.\ҰJRj1& mn9K_WI(Y4[I$hm*s*rc"ݽ"]Y2ccL?n꾩t[OK?0On lŒK ]f]nc!'`&?rbeq-4JwCܺ<&??LsAėqL&zŮ<85yY)vg2L&ܰ7ܽGch_zt&/Oruܲl 4ȟ3N/.G =+S^@[6&TڼDhŒ"N#ZFYt?rG+".p8 X"Fn2=Ӥ d4[2.si~Fʼnϗއރ܄ʻ[\Gԫ2W!A# n2Cy5~?? +#:JQ߸HerشO(s)AN߼1{p"劆:]a?r"oEk>*[84=5`c0/\teKjOf9݁‚[k??7@[2w(6$ƢDn@fDvigJ傷Gr.Q>^K氢b=v_ףFѵ]EJ q<ၠ:K"Ӝp.?rګu1[<4!d/q(CUQUlJN/*}?n*6'AhĈauGN"?0a)A?nw1e??1 avгHK܇ޫ=x裏i`P.q)/7qaq[vLRpaY>q'D*_ Yt2[H^:*MO (;iÆR-Nr"?0t1î /D84߲OO=275֘Y4EqlFNR(8ޯ c!҄gh6r@Yfh&j@ߓt\ lspY}+N/c!-E\}FD=)6\!/6<ⴀc=yJ:]j}/MQnhx%-H+bO}_@wQ~ڟR%t{΢??n,pj~$2j, q cҚւۧ1$ZWqGiRkө=C$"\Nf!$?r5iP?r"@fis ŗt~!X+355E76?0Z.[֥!EQ*OKk`*jSdT[si:}A~nrewЫ"k'HP&6hhU}ˈ#k5w @]@nsz'hр֌RS"}{%=DГSCVX.)u^BkvoY:oVgN^Rɴ&QN (Y?n?r5?nmi:'*EiJHrϢR?0w(YsRrtޕUҠ!SrR!TT S&l!OJ-ꚃ>`87cVp|1M`Gs4Z5-QYlF- !~/M-\CWϋ/T:Y73hy-#wwMmd6䊅ˌ壺.dw5WɆr7hɃo?n@enm ӜM Ii]5ITq]z3hÌbe\b-^N1rBgohrj'g&_pe K?0(K89W]"VL|kq\&xeṕϬ` A}q˼Uu.˩e{N& aѣ1>{:ȋ_Jgne?ngO?0EZ_UpGA鎰[XJ¥]I^F/iKsI SC-߆쏳u~`ġJjm{;AahhӤ*w;0YN5sn!rP*ɼOs*UAbuEzMDY?rrϣ#q\~kLN.?rXkMT(bT6ĤazV^%(\c'r4{d%88DH E~KQWz̉)VWNgL]Jފ*Xfɷ` h{$,뵸nw(Z7feAElYD7EntkP?04^??opwǂ]h u=U¼DZQJgv#Ǹ*`8]zc Ե?0Cs d7G+""p$?rjIT/YDsEj##!͢oBBc31k-N_0&ab6+KϿU*k"'Ⱥn&]^񘓝恬E]C%hZMn#715`dv8j̹Ԥ]ObAi/J233 Z^XzՍ׽!oZGRg-0=@OPVDi_XLDr$"(1KQ]F+="lu,NDpݽnқ .sWEe.vݼDP FtlHe?rDx?nxE P2aWUـ:vˑ'y~uyn' zoMN@^6(}<]Ędηsm&ՃGϾ~1^=u7F EGI^Q,7ӝ?0p??<~}2:ݘxH3Q/hWfr\Hr2f)phtqs09?0iOOq??y^?0 i?r4"r/}kjku_g|WtUl4#ގϗq-CJj(ę)pb<ƠٙMNjA%|qy3%Ryz{@\_W97&[tYtDYmP7'C1k`ˇgiz?ry8m/LBs(P);2V?0¶,1gM&us`һB3mgt~;tWKx8#n:ZXԥvsm5\Mb??pŐ@+?rTWK>V*x.~E M<@S_x'vڈG?rў7*%tkHnƺ9_FEO1ӓ]=#!-Bڙטj?nM:EdxcKtCC7u yJ_!y+5CjfS+zpT}LH!e@S%'-0϶?rxזP?n,ѨLoE-$j(1P?0ҫtV3zȴ6ˏby3]W =/ޘ@c:câr}zxVCxZږBEve٬DojrG nEhC#|;?0sgrglH(sUo;N;u?nw4~EJͨYO *FcV=(@A?n8I}6??B㛀c3R6 !5Kɻ0#h` g|I:-YT^?nMQTx_SrӎXUE?r)??x;7]"V e &lgh_IdV V+87 {+jxn};ɼx`D8?? 8Ke܆A9:!&x}2X\]ެN $s?r 8g9sʥ1oA-l{5uR ' qC3yZKFvվ}?nhfyĤiH&U~⒖K??~ƓګղX~yZ# i,NAI{slZI-̵ u0?0W2??هI0ɡnż Ju(z5nz<ꃋ6͕N??}}=(_?rZ??_)䇵py^5Q-;wj!PTE,@oE{{ɣ>??NS։㖚bGha)s,ͳٱP@3t 9ZmO6G|Vcd(j!V NF@0D7<5??9\JDY8fTm6?nR:g*9?n=oXGdŪ[5W覬v`SnNVօ1K+ !Z@]q~,F7?0ď:v@DJjoqmrV-uVClLB*+͵%8WSgH\KrbZh&U]L$Mz (@ 8mD[Jw|5B$lݡ?nF_Į9lZI?0}p`f0^YHl%K؅q;Q??ŐCP}*|G+[P;,f9,NUL.HNtaiؓl[fjj/i1Dc.sMBzb?n?r|=sJyfLYx|XM N|t q9M{E?rJg1{vAb|{+H?0Q14\o3JϗG"6 A{kyh͍[nǘ̓?0b&^ LrKk݋BT]gKRciD'4t8B5: *[Mӡ^R 't?r??l,8cϝfPrm*Mᴴ  t:??V|fʏRxwSW??q)(AE4Ĭ> Bݺgyv?n "sE?r?nm-?nndubiqN[2Z4~Nf)b]c8OtV%̏KNu滐f+ ?n_Y˖"tY c$ػ+ֹ,b"Sİsz JI\){W?02*< 3R )%$%M}"]DD(dT2'HFlD/Ě'BDaxCU_Fpi%O6)&6C|穆]״e>7D:OЅ)ˮs`3,փL63Yd3eQ\٪ĸɰRwyad??-c3MȊ&Ou)T|z`۩&rX~)J 0!ʉc|3hSiֲ,\BF3 ;dB3)Tf#ytƲ9+B l?rە`Brhۋ#4*Ϲ"^?npZvY#:Q W8P??taЃOJ%Ln_^/71;t$nOZ*Pb:=>K:,|?rZ!3fq(?0 O+nQ'E +#[Gϸr|j/ѤvQ汐h?r9qEw՚HWMRZ 0=0#.F:4:o޲zØjN`ع==q'i??Åx<\|:O_~vpgã????@damtOo;h==kxJV&,b*' ̘ң1x!_5:'Y>iQc07{{O{4g?n^,v)}ns{/xPR g,>@*s##6^πԙ~xE˔9Qop`[:JLu2)L+!??ƈHy(muG&ٱJoʻPTMXF?rʾQ 9WLsn'pzv#Y1D(>|dۓߑuTuKW4ond??Q-'ՂhN/W02fzldoo{"KQh~VK}Dp=0=T??V&ğ?r^?0֫(I8O0ܶFS%VjT6M{<]ѴT΀37Q3$L㞛"lԮpQȒI:lDc/hi㎠r|j9K3x&iZlj?rdŃVu~Azu'EB97&.>WGc- /iiqgȞSZ}*nZ~21\4i*!&}:PNg)-ZU_??dE*i8Dkh>P~V?0J?n`J7 }M??yV 8ЌPaS:J]*[J?0$([DL-Wgm??fUvDu4q?n)*][H"??J^3#觗&q[!iJ`Y"t#S1BGſr͛(,Q%hu^Xx:FgbYlJq]⽽o@ ׯ^=F;J6q&fm_|sX6"?0l7N`x(\`8~KI ?ng:N_E"ǻa@}Z٣)"U6aS+ZvN W0~ 622l̓:_8թmbل,<VTgtNP?0lS W1Ec+E 턒5L:^/=FH {^xߝ4+j|k9[D.+Lh9)PRA79e@ݣ??C@XL??;p%@RXF&7+E-eiBldj}i0Fs]4}u,Y ??|Sʗt^oB}X*P0h=p|x7T 1vi/gtGlQfl +#\= a+ ]<Jc.7%]1ga顔7JY:??JĂѺ8DZa`1u02xoW}#T0Cy-K*[:0 FV4\M,wrT&i+|G ~,y_UJ?nBUDy]ݹ[r}Wx\?r?n4^c 20?0dW&^Im"?0åm47Hg !^BEv< EڝVQi4`ۿ4C+_V;r4"h:{?0JEbi-{$E,o6 ZN` 6"C!1$ϼ/.T(niVLJqj?nN3+1պL^ЮM]۫09-+uS:/Y+yZ$rV.9s]䜟2!ay,%ܖ: Oc, JC5lI!(C|+w8\H*d@B]+$8JH}MGD"P+}?n=޺R^3Xe uuu3UO#|d1;1l|P~& Km.|w!}Auۧ) bʒLC>e`R6c74Y-I!\Jk ̖J+KR8ZN"sVeF7 ADτt+X/HL( =t-6"eR꬏\eOEM,2!\x^|{[6I7hQt$6G;7??ٟ~eaI>͟/72+Y{e]Xf޲ oId%S/g߅PJr孼^mw;$y!HWm2D,)cD.DV(OYj 㷖t}KݽuMh?0HƧ3A'NfP5ҽ?0I&Ηbhႈp?0_䋓't(_HvdGUm̢|ZR>5ڷq~ݨ_բe[pK:?rh:J0> o|ηiH3g?0gCNjXx[*G5|'OySʹۨSPV/ǗRHpYC^Ouf"'35s_$L:s_3ՅC*ʖ}88'31fQfGI]Ek1zze{I?0swK&U_.svBxaa $0.XG„Z7{(+5;G??Ch5.Mc)GI\6Nl˞,q5Fn]?0rRt{?0*MQ?0ġdV>< ?0RЀ#ݕagq2#*!BEܗ +D=0z q8@C"1<Ѐ`?n!aQs}۰rn?0f2 ),xj(Dmq|j-M㜺iDKB<&Z1Yy)IҠj#&A:/ƒ*)'E|yJ;tъbo`_̑ep#DI<Ɗ_cbszclH{#G??A$Hed_2?rC)wy}9?n]}??||:ejYO5Xl 8LAWݕIۛS`*DQP $TJΥ?nUEcdR>v*=5C,2_/E@g$+0 ?0rSwڒ^r$c,I$ִ\eOt.噭Ve]a;kҎEh쏽w}@˛A??qzDZw^J>~FK1דy-t}ّ9m\eB4hq{6% ?0)҂z@5 ʞX2w)-wRe4CV)؏LδڬWG[LPZ,.5?n?01lO 3i!]8t/`?n. k3u`d_ FP FK4vףgpwӭw0JRp̂Fk[ܰ,EZ蘎E??]T?r`AG۹i̚$&.0+m[Y<-]j0?n^.-ldQ\EQB*O㯜b^9T=ϢȃĂg혳iaV7I" @45NOZOq%ÃYz mFҧ˖2yQB&#scqK-5рOP 3Xa]YC7[ (?r;[!&Y?r/ V*h,#s6>8,K5́JZ4fm7S ЄY0{7Pޡ/izdžU񎋐/}'!X$iH\Se5-+2Q6]FEhGލE/CsZ6+[V-,2Jյ3?0g iTo*Ȁv77ԏ?0[Ńi_ J^Xd Ai: ͧi5?r,EEQ >ՖfH`Z??!6?0<:QvceJϜҠ4:t׊;8tbeë?r?0]sr\8 ]P%0Ӵ@mH/ʅgLz{lcF4w~.ݤ P4XEl0[g$^q54ϛ'r|R=ݾ!916Jf,u&/e8תQ)"gĢc?0De"[/Gr$ZyRv8d5q x'aEѵ+ܱJũY9$/Y7;)/<65H?r?0a2OZ7|Ycp, y4yl@ddy|'γpI$,@|3v?nW^;`easr=D}?rp8Ǭp;r J'/O9j3z('t dŃn%Q|hڈ0A|4߼^Q+?nS*L?nJ>d)aEt?nlhifYA,-Jn"s%TuZTxq3^H5`݃wN?r?0N9mᣅRVzqմM3g=mlGa-t , UۚuK?0ѥz?r )$uNa6 F5OA.@%hs3rvWR;"HGJ~ WNQ/"4k6a{?rr(* 4( Nx_A`o}A-o (~?0,[A $P;ȇ??]u8~ynܥWҭA?0Iox7Ho!?0bB 'urNs9sl莹!GTd{t/U3$X0ᓼ.M PEJz>D+(,׭d-E545솩c&p8G!8>gxNu*5$1zeop_rh{L6#|KF MۺiR1v4>?0ݲ%_7/۫,"fiʽ~a5 s;gu Y>B4%^̼΂R{-jp;:YX˅V,Jja4X JS)s~>,qQ?nÑG#ܱf#ɮ/uHUX.G-ET(t1qde%(?0Eʞ>Fd1 gaf*Ip?r!E5{"CvVטCa.`Өު|_"Qxe|Na{?nNf*H6oxŮxLKfc d=w?r!әM/ 5OˤPև@d=2?nPtu8#Qk;-;^u0x.?rEĜIB*+`ӛ27qt%t[ Q" uxvna>E)/.c b?n pʣԄ0im`6 ȟ=NA:8ȐQ)jұy"^ƅ%p1i阂YPr!À &QbW??4T2??'HAfKڭ X\ػ5V[]MQgj8jZ&X% =Qi1+BL+YT*kX~o/\~vmJ %1mX ?rR)0.%}'zW??wtOo/'Jo1(,"G[׻ɿh#${?08??yReR+ju#^?00Bۇŧ ;M8ؘyq;^/`ŝ1ȕr0irVFٳ,f4[bPL^)o?riϮw?0B{#ԻRFpgLKC:v<6{?nW{gJ 9lm{ۧC?0b­@KZXYO+ԋ bTGo㜯^ gm+o=JEŷ|'>I?n2Ǹ=h55My9heo0џO.CuYkB2>fЩ#BgZiհ,eЍ*`hL{ua?n*)yP$MiQvAe &E_>z!Wy3t/[ǯB'.'@k˽/ە/e߼3(НO^<|`?0h??*ͭ}V0R/zap0zG[?0), ގ~|}yI> k]>?0΁X^ϴ'qtWo0JI+Ip;jr)C4!J?nZ^I:3ܗYU 5Z% d?nʔ:2%*͢-NL e֡x.eb޿⬖s6Fr湄~??;Wt{G7^Tu>xՎ{:IsIG%]1CI=Ah,-DFS"?nZo2/x#s,f'@I+2"DX@Ziy6Epn4$??gC g6K;w+QWK,sfjK|==Lka3ہWۍ/,~@u$?0')aIj[BSfX޳F8GVpT1qvgq@oqqƷka7u?nxLdBz;N=tcϔS d:׳e=$D%%<}m ԖKqS8g`1@l,q,eVrZkGB̕ kTD+L>>DmTF>Y#,{o6HRyLy`39ϒzx*cQ aI28E1hT~mX܍;6懨Ka_" ?rZWzTVmm0lo l> 9;4''Y60(Y{?0-QfFTA>{cu_A:4̩%>_",-%Ko?rDo!p-Lq!W&]9=D" ~:?n77z%6$Y%d= Q]p .py$}p" t` CAIzXiOఘCGaDy-dg%??DS C72[עdV~clJ9N,ZhQ}G"-2.tX;,ʄ&Fp7o>2OyRp3F@LL9څEri\?0 ~ 7x3kZƮ?nT^#/I馪A<7 NMX&Ɓ6*ݨAZ`NTB V0)o0'+DK.jL9]) *l|t"[8vmoL+Лv{蛤"B &Nr}$sS2=,*!UhNS( Aw'O{ٿ>wHx9?rbV7p'N?rLf+۞I"8ݭ|ISm4^yE1. 'ZIycaC:V x`cDo#i{m#J?n4!5RK;ke3P@qFchҷg^Ë!??ޙv.NܑI??++^a>.?rZ>Kq>>'KR@]G!s&C6ְw^լNEl')1w3(^kPPvN0-WKcT},Rde@i@{yLnӑwH9~-l25^pv/e7=wp l01r;jK S:&=Mv?0J߆Ak T?nP-p6_^=} HN`H*6h„'N 7_[{U[Yj29\BNU1;M}fu؏Ưx%p8n~ۿW??Kmn7;4!x#S?rX/)Lld 6GaĬu=v|[*fonosU>n Q4(9{=zF+q+~}_}fglDDqOD E;Y!&F&vo,??Z`A EWh=J/W#}VS>jIGume#oidm65.|Gٍ`FE~?0#t֍18#mjգ/{]F5@w,#8qzi`jtK)Ji;͆+IӠ$]1'BG#ei`WuiTE ucj,!"W%G*+u7K|4՝hZuLDs-\s;+)Ӻ"??MDX=źkr`Ԫf?n.ie:;k/.MsȝQQ5iYlC8>!vzS?rkջ,WK4}l[/GDi:MEw宝m`,Jb1}F6jb**\nF$uєjܕS..:\ %'H'*zQelRV:cVzAcW?n12‘y<{Nw[hR"`\__D0.c'??{Uaڱh6̮8k%k#kq^zY/i2Z ;6@gS /TOG8-z씍*qb"E_u'\>Ygzikj??PI#H4{r .QB"֔4 ?r߮ɼ‘ЀC/uW?nV4^ r J } NE :!t'??2B6!"{HP9|?0pu2*Fb9 +}Fj(BƂqu Vq} :xr3^DzVГnbBmJy[qǎ4Y{d­uZ9eqqe{l(!yG5QlTmg;8T.-%5Uu?r EDG.&f0Zm{?0$=#AB?rl+Q0;0ׁ#D:e?0#1+t;UjN{GL^J%2wA$UL#[!?n>l?0^Fw Q4^0̅#%$ c?r2߮#RbFQ |qb-O~P<)K=)i4pcϫ2mVXx?r%??.~_?0.D-{vrA<$I{0Akd>4+rXEo *!szeڜSJD1*oFF8Hk[ףK{gna.VA8nJG{3eⱌC> ႇ/f2棕#΂x*+Rzл?n"{??p[D]?0-|Tqt??~R}`W 8E.rs&a*eӥpB)2\q4lyMg| E0!܌8v$N~8{iq|,*첲A4QBfCiZ/_4~|俞>nЈ$x Wev-UͿH;I6/BߎR{5ϟnIyn??*??=yKP߿~߄,,3Eŀ y>ɢ#4/nrMb0QVxZ6|~o:m(aù 9Ilj| =㔔qY9_ʗ52^JF div> +#30bϢ>i*_ |+??akz_pNJg+J2|町HN/YH~1]"yl5^&mU>0n|i͚ dN-UVXC9:X]ŵ|^׌e%O돋\,C0ҮB%bd0#MJT HlkޒrG ө['91M[zH( nˡ_ol 7 'D.ՔG^<ĉΣ<<ӵ8f/XAe\,{_qP?r:xȺ''`o>$><~wO^Awyjv}!7]37Km 5(֑q%A 8#u3z;6ON|p1?0X30!YG~}Igߝxp.V KއOj{cM7d%lЄp!>Gv/Oٝ/_Q>g/eާZ濟3&m-o_6r9{z83ֳO ??,&~僧1D,z8QdZ٘`̀{~e{(g|hy?0 {m>cQX?0JǏ>ZLW7O.y{Mܔx%)2IGϫfQJؠxRMɠsaT鱆AW&d ^GBrMEP[i:G$7sdW7/c~u WY">e]%^DQ5?r68>lIE~?rv??.xڑi)CwX$W\?rxDohvH'I}NBh6]<vjOZXn= &#:Z^k)8);Z" cԉq^hCGZՕ:$iJo*!??j)ͽ}qViVj^pz|tV)>;ˀrG-t`3ӑ̜s9੆~ *&$ |K-7myqDظ}??n)4H]m/. uDtє|k;{S>>}t>HrWVe?rAF*w2b蒥2HU^Yw%B>9Jcy+{ʧ4] C[yt 3N͇iMf6A}Wd A|g9˾Vapu9ב)a Xf7.b+|A_wbډV^{<.x)8d$LÅ{n0 Y`zJ073 uY n*74/ `ga !!6`\]9`& wi>??>zZ8A hE$i Jjv}VZ%S6Qb*I(tD=:ZL<윘J@ZuGҏ-@%NJ9x`MV}Tt,t}/^,sb$6>὏0Qn!*&pa҃#!5&RmpNMd0>( nB}J}[,nGCD+?0̅.אpC5UN53%eϝ<kx-YDɣL2!]bPL96כL%'fAf.$t Ej.KmБY6ߞ}ww.M/ED* $V?0VK݊u,ww?r` P:co#lN+:r.["#UJRV??(U4,zzWfq(Y.,BfQi#oZV1fmF+ 5-AQQ{gXj⭾4|^8x?nQK: ;'Y+˶d}~8-{~@}ukt:@z?rAj}EgU se Cco%,| z6zX{WX@WˈTTqXWSTs)mj{?nS5/nU5eL]fmkL*F-*Bke' ?0 YxeuT E"4H_+,3bXJP?0Dm!ՈĽ[d&~-ȯtQ#zC>;ҬVД/FA nx9;<۪|~ ݤ1MJ]~}J@\NPRvB/CEᥚz>6"?0nA?nܪŤF"K)?r.,%eT?0&t8xΣj|1^5>6'J)@\<[Q#n:J 5~h,RvPgݭgT ?0F/?n,ꘈAxfh^oɍc>åHbDd{vhjY>ID~UWWSY5bPHu-lo KMWey??B&d3?nj~n"EpkGuFix\5]4ѳUNKRL*,S9)2A;.ξcDE3 c!e"Ԋ)]戁=fMV~dK!e-oX,`\a>|_=~}*ȯRQ?rˬC[řKzЎz0]:5¤N{L [窵1Ұw*Y^iyscIFgI_ nDUM᝖!L+jeu ]x%^`W(ZN]|K}??dzjGos>fKb`cgG!i1Wxrk.qM@Dn,fpys ~y,7,>]59{„.<670:ܴt_0XTseo9FuIB??]Yw?rioʙФ"|??"yRh1u⊂+F??F.rڱrLO>8?rh=#AjYv;A1It/vHy`.-nWf -%XzFO#kYƏgc0Kj0п~!M̋tE_*_Nj~QSߟ:y_<_^CZb7~Qc|SX;EM:⋛޼?nke~A*}$NΛ_5L-痞&@tepE烛㛉i|xr^:&bwjeKD1CxVU??8~t2eb7w(?nPJb퓣5cv-1h8ۇ*#ExZ)֟N̠o p{%+>z={Q`AlZۜnuGxv2|?nmW.~fޭnz{D YzB9blY[ƿ7Bb,UMڏR&4jqFձ`cԄU$6xT\$!?r3봬gk=`^d4#|!e{%N2J) YL})}ifyW%O_$$FM-lH׈\obהW*A?rέ<vx"JtA9)53gxcW]9n߳T0޲a|ETVpY!1?r{mx7(G}w++d(b\.ŘR̮҈S?n24Ͻ?rUɾ.2rfAk.*rTE/1^؈U5#*¥3\vZh]%C%PH.ԑ tO$fa??OXIS [Kr`,ʕ 8/j?nr9S"/b?0\ZѺA9?rht׺[ T?r#*J).,3O騽܃<竑-XCb`RQ6<]T `8>,gkB))?n9ד6h6R+Krv/-`whIM [;!*k;Q!;ys"ڽ͆>j&jk?0(HT?rmjan/huyTߵ0Uq*#?r}7HSj vXZd{蓫QCw&(rEj @ owP e^eR?rFUw%CD9a{QITL,S ?0uj/w0 %n?0(p_`>6S\d1dPzNT,ꢻ|sd%[ڴڤ:^DD!T`33ņ7͠moGI~]|KCB1RB??o%DǴuIC_'sT - sECl5M4RmvÎAu[ +{%9!9XZw'KHQl'g&cUhS`%*B͎ϝD+|2))f%glAwۘܗoXiy K%-??@nWEUj7P?r&CWjc6@2iTi͈2kaTe=R6qIˈy5mLn%=pmmB,Po@iy?n&]A5NAʲ9iDtBĪ^ H`1R4zϒ:5u1*FIذ bڸo ?r}c(Wƅ=p@=5rcrU{B?r??If"@3AεxgNKJaIMJ΀sI(Yyq2%6(iVm ,RL}"?? LԆuVZ*Pm+?0( .6d* `Xȶ\ joqFpM•;8Υ :Zh;GRȶ)Hr%F1ɣ#ϽzHF,F\]JLcIφݟǔ$??>BF:/ajRǐW pIK/4HCc׾3*NPvcCUU> =e +#?0??!/RP?r玓wIAtVTIF]PX*:_EZխ3@qqNMˠ҅iI] CJ}icު\"UlEuz~"!ǀRhӘpґOIEMmuO9+2"$/_??[̘[[n~B~.$PN/(N%h.k]κ#w]7Q :MtUGZHvi,k/wXW M4SfTࢅfԘ%wDwt濺КƁkUwA߹VV+J"kJXWFE?0'PM˜^K8μo)(frI??ٙ@LX͑.Ɯe@0Td4p!=Hv6 =csQ{S 0a6T_+??5?nj߉w^ @p̎S֗<>vj Q3۞W@v?nb>M>Z-O7_ǚbSP2KE1^nݠ(=Uĺp`t0%c̄;xLSϗ֙EY^K*a"ݶD\Vim+8r^^T%ػa%! cx?rsT`򂐬*OB€G1mx~SF3RHD "< u*۽pΤ:C>>m% VRs2,Rus\;NgN^SӘ.ڇS۲`L1?nF*??|`DpB36Glmn6t쩠[y"qH)Z-n[҈㥄eJMd4pո!>oz{ʏ*$r l8[R9Z|4^g1&dAlCHX_ؗ/RrpnD/xOn2Ff"V=F?ny7EV1m0E.ḨW3֫!p|N9!E n1]L~l9c%" 14YCc4^c?0VCɽYΤs$?r?0s)7?0KqYzĒkp@qc>v7ڳv8J|ln: Jɖck"Nj12S}N@r&;Hp|@@Oh?rJ9[O*ƹjxKz0LS\V0,5^zugXUSU)y^֡CVݡQ֩[jl5/ 4(0xfN=zKWVZu%]Ԕ*h 2icطi1YzIj[_;F>EQ>qdH]][/d#( !`_H=2'(Q=hZ+4e24[ CJS'n} YEoDk.ykuMKbJY}]O}sT>ʋxByq$M*x4!q' &Bs=w[Yd=/8\CC@7VhiO΃ݽ g]eԜ/??^[:1θfpLMb$!t9C6F;rU'k*w=4̹!M, >_#ؤ25^!ZB?r!-&lNҢ./= "{!c`R?0:iE)tۦl{?rf@_P/WbUY^1MwaUVVah\j1hFrRyy`HP*5܀yKUd[0qgmn bouȭJlO2N~Q+8_¾}gqܙҰ# nq$vq5 #A=d_@w&Pʰzj^OV{RpZ"mS_0bGâR'Ԭm.iMԧ}*O5 _gs;B??{fX6FwkG%y%M"+?0!Gwg3'OU??ۯhT2_Y Vپ}7ƸUC??i3!Bdy4Fd0gxq63ZxVc9s 继`)_'~25tx!{?0Q2HIgEQP@f㨵T-`C8(m|y~"$`Β-?nݭPWǮc4·j<'mAH,hbjF˽Ԙq0CQP7Xk:t.V$Hz غzM^Uq p nuaP2ogՁǺְ<4o+.)T?09op+Lilcx  g0Qx!8\6NU :@_,722$}IL#?n25pO@8?0`??c}:[,g`wyG,/tHpFo}Efyqk84q*jmum,s=*97UAwxC@;tE*J=kWtj?n r:d-ƆrxBWD-$-ƚPfHalg9;??I/+۳M#R[:y1nMrHCcf-X6P?0f1^*;V ހ"0; nD(7]?rFp wDɍxWC:“p2$@_Ps[,jl29S??6dy'Р̗Ć%LqP%}+cHڪcykjSEG濤/H?0ʉ2ƣPU#ϔpI{#^O4AwlNQ7i1N BV&u%~?r`8.f!p]W^& xwtT}g@πhIӀ"i%]#TK5b_G 0^87ˇ??0,]3Y>If*܄q$A>o"{O%}Ta*\??,~*;<tɫpy,CD,;(> .~cWcz6)5uP 06XA?n%//^{-)_9[_aabL.^nX#Rr* R=U{2&F:gqszML劸!fp,n?0 ={:/CKM}TƵfFN1N<у7hI$}pHotHQ:^'U7J$;MF}.A߰K 7._T;9m*&Y<Ǖd<8KlX͠ Ŷ[Ƕt$I}8unz`GݽJ46!ªw`2OM]6a +#ߦ3͸?0[9->Q݃??}AT>j*g2.IT |4$4vN׵dPRoӍkQ&3}KIE]3{KVZ!Pmlzlx R1ZPROim<3OZ1 n,  9h%Ҭp'?ry[-\^r"ѐ?0jseC[!aQ S6=Gh8~$HwD3BYm@`d^BVDقJH]Az^`kQ_Iw~9<ޯ5۵nүaSZ6-)VoWӬé}I3~r6^8 v5VNQP_BB)6u٬na45ĭ&"ԇR0H~E54 %ћ1.(|@224j @زmo@>}O3BP94#TbeaKzIMLATK?r!վsKy$vT8VEz' O jcЄ;mBgg$MR3]g Hj:e{O ~??yK#;}z* ?nh|ڟã??Fߐj@kƅY=k(Q$+>dԘ=ħӍnLIAZ7&d,M=@\|bR^|7]"no 7U~cҤG*0Ay3uqڰ|A>wљ:lN[c߂whvufʑWn&^xd֦1xҍ4gWݩ#O)}{#̫Gfȿ\bȭ0 p_z"=JaIeczrLb nr[2z9QD](oW?0ͤ"0*f䡎<{MƇ{b@jn6/HTɻ[%kRCbogO#c>1_au&\2ѣÃZĘS} I+.8#ZСj[r{OQI$e ӓ6Fu0p)Bn~cAՈCC+ZG6jմ?0TL93)aYlF7w]?n5(JA%;ok8L'3@M=ezBV̕;=6޶S?rj]~ cAs> &?ne޴GL)}c{5Rr\]5 ^5@-սDz/ۊ{hN#clAid^il 3'{CyGk?rAY詮KEeʟ[r-SD{ݣ8۟KS*掮Y4MHJ?n?nMXIHHI 9zH8?0py18m??H)8F"и;y:}-)2M+y7`C\a"q+r.NT%uXBĥ?n\&?n&-7=R@ 1+wpK_#rob=.^W9OZtP$Mihr[oY1+"vOjz]?nf%[@'Q@UWR*j΀?0oEb[uq-&:/rJc[@Pcuz"_I)g>e$׫ ʋOu/!+r% ]+t>NUʝJ OʎP8W-",[gd+f??dt4K`&)+:A>%#'9tq3^end8j??5lXpyӀiYrHڻw$sM SJ*b _*j1N#eega f`5`+Φh]8%"̙Io<]X#-rd|r⹝m,?nq\!3ۜP?rwc0Юh a擖q#R)[/`k<Ë2~ժbn1yv??ʫ3'}4'dﻢ'?r myxbr[H *!*­{\o/\3L?n`??T_\_%ʸφ|hGe`?rT(7mNTT3Sz5䌿P/٬ Byyg}GdhGT]^0җ@9'a{+Xցi?0P;*[ČQh*LH6QLΜRMERUӅ ˆ?r(-: /PSClӟ]$cL(prA_$מ~h|Hĉz-{XO=:jETz`ִ -{{O&72o z [B8gPsh#'OlPE}Ĩ P(Kt:vMǶZ?r-)@h6 /*U|9{ݛ-}EwGqvXfIjVZh Ogsf:r(MUQkOK?n.1 BnqL^yތ!p.Us{4PDQw9`?0~AOrI1!AQnĺ?0@=Sb0{CApz-.LD0?r7᭡ɈT:_U w&eļkǙ}тSpz.hFGK7)#& rq]w8\g]6z飑Je$ǖ_Bt;P9 QFLYE0eѩá_{K>%WC?r(6xS,꽹5(_wQR-wQ\TsQČEkյC&NQo.=o +#vftrZ/DRR|j5 Dlyq ^?n%ԓ7MƎ; $%at8imE^U}]x ?n#|MHo~}ww'%6H(''$TȎ-`Y8܂ ?rْz?0uˉ5V1J7|m/09O?nm C+@c*?n׃_HIA״+r^v*6-Q/Tm?nwtK*hQݼO@~zIv@mV˭?0 2&Qs?0Rb'M֦fʊ4řZo8zᔸH?0ؿ#*ќwh l`5.:J\1bg%ԬU!'0'I{g>kzbZ߯9?0&qXJ*"}lw(TC=%G( ?0X^rCpwo  ׽"-J\g4𾢏KKGZ.uɝlF`U3k?n\`KGbc]쁏7w[H?0vR!??Tr V^7`L\(Ni6?0JCt5b0Gkk„.-Yz:t_sg%>#$}L[krO??lS3МGJ %$ue.=#P]c\#G[TwT# r*]I7L1T'8SԷۢ>MT'RQ!9{ȁ'G[3G{&PBSB??pvWű/1,tcXm?0tmbW GR՛GTجu]fz .y1*6 [Q6tݡeG#' >5?0V.:9SؠZGD}H!{ޛ% 4)R4?0n h*8ƑA?nhE?nOߪ?0T$A?0F"w]+'ޥ{????h:@>=Bx^ naD˅Zi9?0e\:F&|SÐ48<6JY )LMd?n?nBȶ"?0+*n^rz_8e=\y?rzL, P?r=ckiӭ=dn^?0ADGg[ӽU;(>*OU~!8 5^,qb`cÀ ??Av/Q5%NGZ?0iV,O\]'`wo^ǾTB8Bxk?0OcAK'%ڒ7mNchpX8;(T]J$Eu5cj?nkLtO"Lǻ+39E%vUaCckw??4>HI$!3UWjVP6?r})l6eL-^&B8/+#!޾iJ:VdUqJ1kq{Uݟ}wa8൝,-t?rA$NeC٣R:׍_^KTY%C1moq[ū\p$ɽ{lZ?n/{'/䝪೭.ϳԈFF\bh+8߽WѺ"g 0oB|Ea#!IswŤw]nuj7%19CSR89S1mS[:vHær?0>dHKбΆh1OL]"QP]}`I9il<Q@\GvE2!8Cht>m;w< ?rbǨT&>+J0pP,ֺzeZ ]RLjpPvap:v7X=;*x1,U~@.Gna+?? W????yB /3"~\b~=x4`??@K2؂u?0pݛeC*Mܟ?nWLu]q߁A;\#"jz/?r(աMrkL;q??RKjb,:ρ2;R6K/-{1>2`.1"1vmuSF @3&tޒKʹ(ƍ$yaMn?0-ƻGJm2/tE͝RG;gK|ᛐ.Ws:ϒ-ދf#`!h9QLvFC0j,@oIEq^B&FPcS/Tް\i:\|Щ_?rHעeFRB*=63u?0FOwG^ZD߲,vi p:EbFD?rאg%qm)"("3⼴p`.55X52hؘ~Oj/5rNߍ@Ž?nAbO<oyc7xߛ(}X7z a!5qHaC^(vA^W&:2Jw=˴q[,b[MMy/5??HkKT9PՂoxv4"miS=7 4S?r:2.ќ!:#Eq_)q鬒0p!C"tN@'pl~pzoAzF`EIQnoۮ<5?rSR|}|QdHob<'Xf#?0XX7fTp?r yWmNwz>e2BTR;t=T|BI1_ n13-F|J D_#xꕳI0{M *3+lSlOB'`|@$Jz#yASq8AvAoDLBSvdT| +#ɨU 4İ;DۺnG}Xϳ2'_ЌXQ;3LF *7oDKy&?0MF/Yfqh4NVY=qoqԚi&U&Y$V>rg`a*S]!cjyPI;`wD(?rΝ[̾ڳqB2u ??FE5 Oy4I@n1؝cjyۤ9?r=XO^/f&J;o[i5┚j?rU3_ZL$=*tgn.H?0:jaAZ9J+C00B6^ -ѕ42'%}Z5>~wP*oDxfnԒ`k,ESS_N{mݨ`פ団2XFͲ\)9yޯ/rTN7N6q%ؽnP??S??eu,>ũv( +/!ٗz7X4?nv7rg5#DO71VVٟY?rU@=T.LT~|M~1RkJȧzbV9??'s 1`%y"SF$N7R0lrZyQ:M`{C go.[]X>l191rI?0A!'`l yoD;K??7??lN+2~E\:vIo??+f$jIh=-+>6Mt1iIrK=Kл8(e?n*05٤U|ҁexjjgly^>+kp†IZhЇij>MhW#S??D0~x*Yobult|_m{o~rrtN8V 8aJi=x6P}لRRfTp<|&NIcc;6[q PFAx~wBђ^/kp B?rJ{ZޭCbH5wֲޔ|kO`dTFUጚ??f;n)R,|:&KN7NTO8 {SY< lqkC?0dh:5Zw[Sn4zo7= 6$65̀5z\ i 5ґ VmP|y!_eOY1Z?0K?ruK^b8?rq]I۫IO.'q-ViyBJ~9@cIif/K_Y, .4ܓcQ,sQ|NVSҲӰוWi7m5pgeDM9jpj@Wgw?nk)?0tR{u)_.鸏KdS0`NcCneP ]0g\F;ΊN +#DˮU?n$\c[%z\rƬg}DI&[s6b)VizX[}5-b#w6.V偅X|y94yƠeb4"t6Uvⶸq !IaTIj۷oƶ*͖g+1&#J|@J7#O1.s9\?rf\Dlz+dFCQMe[ȱ4J?0r)پ-y^MO)0u[G97!/<-&7 xC |M/j??JsgToD3;$ІjhhыcDHQO䂈la7\n^]DlAq"5^Ͱ+xN-7瑃\?0RH߉ǹ?0Zҭ?r9hV#w5gN{>뷲vd-2 cvh51v:W!wr5 ъ1rC!p~AYLCdAoiZ_?r[[ekG~SQ}5ϧxG'[R냪:r;2upy:^!26ogkḡvÙg ӢI-,XrGȓ^y]nP·iP@+fN;O`}1B"zڲ9=ukv!;ψK+FfԂ'8[GeZE3m6nTs@?r-ضf5ae:+2uE_Rqb=b3Hv;͟R4=.:rCU5O;c־MV\R__=fN:#rTjf̵o˴iNMp>m$??Ouxa(6-^*:%|7QGf;Ha IsGY/"~|7x O F*C??EܫW6"=8ْH6Di84b(K'&oA۫G杦J?rƁ۠ K!WC8E:jm~sWg0(;(,e23~DWmSO.Oә};oS:]w垙n ګ[eތ. ]ZDSavM,H^FOv!x+HwGQhf]_ݢZVtM649xisZ)QN8lPOYIM?ni\=V :)Ld|ԁ^Ċ2nƖxCD?0<[RFmU[O{G;eg`<=6_O;?0[QLhPbBg?0?r?n͆Sjya;uqg{}s*eCl>+ Ru??~Z0db(G\c+V^{S(Y.qk|텫X m7 4rU_[YdZ-^[U؛!֦5^G<LH-Yte7k!.9(V7 {hvyN:0'$Ű w?nA64e^_Qk\:7bH߈y aM6*:lPQ!jSLM-Ѻ_SHMQS{RD>Vj2kkI&{A#s8m 6v:Ʃ߾yi`G$m bl:^P56_oj-o[xۯݕnsT6(=7V2 8F$mj4NVHW֚gn:隗q?0R^Mw 3@˶If:M]{?0v_??;۶}0QH{AS:3\YtSq:EbKIiޢ6 ث:s=J(M$Gm: ?n":ؔJAKE&?n P_y1D2߽ᤎTz?nNFj4#+m׵GN,%?r}p5:7?0dѤ+?05?0tx6h*YX9}#:ZjF;2 1G40Wyo$/ C!\­*GTq7XaBܸ[X[a.4ƺ&L)#4X1ڄɭ~|] uyIYlUJ@tOTA-?0^B#11a]*OTпXEBrk长?rB@u#??)y-2\`CA&н70ı&?n\dQ1/E2.R׫QƳyb;h{YuO?r0t_^J&ilJgi0|0&Oqtͯ18_#OcT\@6선[U%*Lg&} SWiJE;Qm_Qsj;iOm3T˨(OoMk[XDyO+/  \ss\‘-j;;Wn Ԋ'7] !b(In»?r0 ۑjZ d06B6?r8Hk@^:V b~{Dfa(0c;0rFg>,2HLӊ*Q3w# t؍BNk>*Y{bC޿=;NT\~ݦKs +#JiN5(n.`hkBҙ,-cAq݆2C1Ӵ7ѣGs ?nI?n`olJ̙484jCT7pd'%d‡sBļe_eOZy&WY+sĞcu5YS+⹑?0KԱgUE%Y!! h_R_b,s`REǽlTNQMFXfҁj[ND$gehkXb\-6L a4|EM]|5-:t63FH4gF`%WNd@ Xݕ+j7x6M|"ǟ~_?rbroꑬ7XH-Gy,NK>tu8Wip3ŞH"a )Mci@?r D(ZߠNN֋QT$KfrBtójO08Q^ljSQzz ]c]ul?0%Ƚ?nҝw<:/?0Bpdk WV0#jT{kgQuow^tdxq/nb(\Q#qU}}P^QgDZaq$z^&2цP~<'yc4lcVn6lg&mz zdztn?0=ZFBmAvS>mR0Am6uǯ*& V֏hz=FuO?0t c;.Kw9]IҺcM{Hj][KVa1u?0*_K#~vHjpUp:X~hwo%[i;%NZa`7}ӦZ>?0OrvPS<5#j?rHx?r:0c{%nkW4aJ6EQD!SSKOw' 1 1$ԀZJ}X(?rAE՚lRwfn3r@X 3][aτZ"~<|tjbqMqO2w̬P?n@;Mu_C^D Bܙ$V:8K1hëPz; hr򨆧uӮz\OnKÕ-Bw΄'v;&b%&g}u|nl[ntXxB+D6TW슂YitA) (> aDX-g.7|Cd:$T69ә1XUX&*}; G]{H;Ϧ =O$Hyܙ??A}ޠINAMK 㛐>??ݖgx 4vt˹6;M3[??%;8v&ȊT2eb2-eRoz\:+oe>ֳe\O)=\J%!E®6?nq#gU7HE7"?nhP?0[-x]qwn6:*lLL9??|ϺDuj*ug&rʶŪ?nCwgh!|4HfW.I4XЈn+,_jvKώg .PO)q?n\4Ԇ'˿[1A|B|@[o͠%͠1+R+iYhbC?riYP쩋X rmDž1[6 02[鲒?n'u3??>Hgk{uDgaiwq-(E=O3;3<:8w}Q m(㪅CE?06??OB9PrROd4*$c;VwKQVo^g;/b"DlV9yË$wF Sij2N[(cF{|Y hp%&F^`qⓃԗRQ*?rzf{fb/*<5]qO2?rKiiy5=k{5_'Rq k?nd:^dj?0հ iUqXjp ?r2Rp;c&ٺohNe]IWyِm"ټhJڈDRL}5=8?? 5$U]QFs0!?nHBo)1^/U'8|PqPtMI8z]4!*#rf&>5?0?0۞F78z?n4X(VKݴ(jYn׶> UE`*?0U%pyۻ}y&?0 hv̌??WL~*) WAԸF(0h+MھZ7 iWӍk~$K%bsbH:k%/!=S\+׫Z< uT^32)(4+0*p0 cBwM!e驇oU l!RaͶ(DՂ RN!۲I.B|yOaQ$}Q۶pE?rvK4m'VwT1 ]99ǵ 3EU=W0"jZ-p) %??:cdK᠁63Mv&ߍW\XërG}/Q9ăfE)r"t(;.աSݚ{W_Gy=RtG3,\PR,֫22-=1XEos)I9*=%Ɵ6jtA~ ݻ:?0R?r-5*g68%l35yzČtN +#^Clk{??[- X?rrʶaGFuy 3ӣZOвn_"̯'e<\;o,,{6,mAcVܶS55{R4ĺ2?ruK)?n>F{&_)w6#חRXQ\ A50"yݓTTw+>=Qw.+w┉XxŀŽ1v,KYct p?03ٓS%urtnL~GAG#^Fbjhr["bS:KQ>U)\/(xicXü9u8zRc-]"ů0v67V\T.KfmM2 R|FHnqi*!^oº[VJfql. ?n[f&S[L_HS!uŻ7ZgQg(ЊKCs(B–ȎVtAwHܥݿfVA=<1y*z$JVz./#$OTC_??hg"U|`X] WR[(b[z+G,:ieU1ܪM37J\%Μܖ*p?0 m[:)~P[eZDA&_iou8 ?n'D=W.;D͚MnQ)+LcK>;z~k{=Z}=_L حhyuiVlBSW6H%:m ̐2:"tGBi'Tu{'##ej1\rԅNga>t0Ӫ p͏a0xgU"3U#xi()Ǐ5Fd5 n%DJ*JUwçŎA `5:#4ue\ӆRd|UDAXJpB$IP?r.Nn,.ZTVRҶ?nxpGmSeHj*P̲|RQ,lS3= Fۑ `DNp Nim@o?nfr5$$Z#*xz 2G|ObQدszZ;Ih[%JG7ABUv᪚O;c#bF>L2n:ei \UՌpM"hO5]?0RcUq2d#~81uP\_~w@J ?0bGa.?0M7P f0Ȉ,%ҩH֍V3ڞűb>rz]` ?0472???0J%VͽtE! k ?0BRczbeZA2 Э_М0|=yA7phP\Kק- Me+nG HQ\?nHwQbu;UŽ$N7_Ji@}/n0r4]FyLa6ذN`B(qc{Bc|cs!}  MCپ!i:Cq@@8ZeX]/ npttL[6Ml qa &*;n]'4xY?r#@r߬"L,LF-!65lɺÏ R~Z!߼B9.hpC]ڻv7J㒭E2ܢӣ/t<^?0Dt6NB=tF_kمB%Ns(9Vu0GKHGZ(AYh!p3;w䮊tGnpvY\` h.?05G??֌yy`$1z +XizWFKs(fT)a]كd h|CX( YWn"/MxH=ˊ7OR-%o)]:l r~ZAf+Ob*I.g|?0c̓1]N*)'^^?nobӻ?0OBt LjFe1eb]4Ɩ@>Uì‚кO?rTP C:YB?nJsµ2 =w/%z3U}ސO=+w78m.dsI+":hRB]Šq |%D;$8Wu#u=wI{`bg+/?n0]͠i?rT<Î&l?r5RM˛Qb"r/BK7THYp9Zų;]S?n>mFl}??R{x߮}qݶrtj(T{k2y9Oio+/*n{TgӞq1i4*z7pVV}uŐ^Ga:Cѐͣ￟>??~EKһh-ϪTC|D{SFotbi٨5~_35|΃űc;Ry-m|_ǿ??ǿ/@b??T/zB {įP έ ܢ8IY8rૅ<$T??8>8Li (IդIH-SN9= {??yc??\ᇷ[TYUfY0\v 4 O??$xH?rB<CP'U47s^ڶf٬O^@ ɛ0 O)חkxbbb2:9ГBXr-;gA?nKETg-H>e?rB.-SZ9??ѺXj8lZ@O=|cMYjۦ'gm Uȼ_e ܵW[ZK3 ΌW?rp?0?n>grv/-ϖs?nq4t?rp|4/h%yrC^}yU\72y$xHrJDž//ӅQ>KVT:H?nɍHAU0vj??H!9Kƽ(p=/C+0lUr}*,X}[utK[ZEvc4U0?r8{)ݾáލXs<i`?0x}hFJymxN?rM/ @@nEQ+Ai hpNSܶwEy!=wt="q} '5Ny[F Ӡq+]??_!i . [hY?r%Kp#8dةmeLH.6(Ta(2NВnWn]>XKRɜMJTp| P>AmۻTPyR~']U`㓘&!=/r|,I[9nbqj" MZ<.sBS hO&+ynڐ LIgM)82opHS1F8.q:װ{nsL+i2YcbWB@@ڜcÒ;QI0<Փ6+L5?nX8j(1/߽Y(xJ)Wm|1=䉪'A8BJv)laڀ,-FiҤ [/fm"Čݡ~BЬWWԒ3/a]%i9I+$A-15u+?nƙ'z'n???0k?nIm)O>.E?r\˱۸ry'Zjg#W)gWvEݗ] fU|N(LZuҮ;WZwƆ#6еƵr?0?0v?0Wxm'[wP\]ۉ(HJCMˬÁ毩Gu!fCWµ?0Xc7+ӜhS*i*`=ZHiFBQK]F2(/IsqW;vbS"U=Cޱ;6^;4")rOLؓT=S.־̔.Ѩl!Fa$P$Y>vlTʤj\שa\BCJm;o~EP"Ғmv??QHOp($|RNX%4ɋAx_{[sp9 gFݪvpkBcC(4")ijE9?nh/Uߪ\ &u_?0 6rFye>'l.?ryNIő$7sZXUTL8hX>='3黯7=V/=(?0Xzhu4h_W;??QGvz^޼ox?n^񦖗VeFC-y@G%!s),Zi7?n{,{K\?r?n:xĈ umEw1QjebNڡ?n8UJ+4x]:DF9 *`NuHC!7 7Xo{2V׫FC4fV͛wɲFY[fckT~rMrK?r(QfQ` ǂ?nγdEb߅ZI_#)WTE=pAl9XY*yU>.XFl Uot\ѩ:C7b˅1??&6=qJ/FbTQ*3U#{gu'}ՑWeWg 5ģH|fbb:-}ܰ}~Ah:W2O]S8RYmOui^ph%Oxatf'14wǬ[%&#㖪[B~ ўexF 5(s"ܶ/gثʮ2 ?rh:st.6ý{>tseMw9ySRf "=i3>ۦ†O"O x@>Ù6[yDGyX5)oKɠL鵝$ (mQ@y\poэnZ#U0BwRL&ڍ4o6(Y&,7?r/8"O?r}}#J?n9PmqBD9Jd;3yD8z$꒴'xKǁXh{J6ٜlUU:XQ>mc؇̉ cY>XvC$_OzGѐ/ f?r#7eIk5Y6T(R;_2??mX(DGqSfׂ0F@[o{wh Oc2^7K^AtA⢢Q-g7nB3!h""jEk -lȇ/ŮkӰ[Vc(ݖ*V9GBʪEB˰K??/eu<!&'SϕsN;}Xhdny]y?nem^=DIyظiw4D0n ͶfR)`\,TV@Gqj(ƶZ"u0մ&cCAmaXg%.P: [녷mjM?rek?n``r!5FTs|a1LD0Hll#6^խx;ݬ奢wnq~+HT.YEMiҏ#?0Zq됡:b؍1)5c-u k^à5?0*H@@L~d (alo_rT jpֵ @sL)EbHy܏5AǶEDU} sj`z Qcm[Uk?nxjJ-9iGU 5\5W+af;ӃSKU\Ʋ?rx-ṿTNi#N'??5_'V_B;K;OR YnI;M%)h+rݒ#_¨^ bk~?0biruJ=ZڨElvB@?n0-89;092OQ)<]B??ia3\hGLCG:W)%LӤӝ5tԠńj#H 9??Tf;P!=a9^* +#3s1">?0@IqԩI,g9&@Ah;?0C-w]?0k?0MՒ)UogzylWXjwk L* 6&u_uhfUԝmv5`WFAw`^?0,3AI郎D~B?n=Gk ߶$_gi??J6ZӮrw:t|Ek\da|DP/o^q t7;(f)a?rh4HS0lG<|QQ%{EPF?num:+G -bXt`ף.,zDhLfpr4hC["5jo&xk;PsS y0vOuO NF懓 J_"oϊ_m{RvKm?rxh8N;edD.&[be-Mo`,"A]Ż^Pzl8Dr8BʻuP颊JgWfTha 1d뫖WQ^J??G??{cVVTobVzzՈI.{EJя/ F{A#݄6Ԛ_lYuZnn%G. ݁w\Oۗ B*Lo%E]rK@5DuJG,/hYfTVc!6$6t@Qцr(ɀL@΃vXR)`7䪬YX3z?n=k--i??Nrb&nI*. AR,7CRt^`~7x`@u.X^gXTihȵB:c JAmwR6[qd.͎F=k d>lWMwڋ(/aLk[wu%bTO#nt*uwn;TFagh-E3ZsA0MQEl~N9ԮddJM}aPZdu~:xK&w^+rH/OߺGy}ÄSϧtg:5MᴵL r9m)??.7)S$a%3"lST,CʭY0o9ӧAn\$dힷq WBԧEګPOA"1I(XZV+?rK0KA,G}A\R›|fQ1Te)4X5?n&D5-- pp)v׸Ʋ[C$K 2??̱^ 9K)0,hRm@yGshgվ^PSp?ngC# ??>: E?0pBCJe{-̉7_vjv'λ+ViZ7}[Lz\TfmTjp[$(}t/8}4,mHq\:3ϔ"β01};P*BcV 8{܉N Դ4UNo؃|}rk2v.ǧ ?ncxj_2q??})mxxɩA>9{1b.(?nJP@;O&ʼnѝ\P_͛$Ų$?r+•1tdz^;(\;%wiP5?nL9E^^F6ڀ|SC{ON_7YA%wuh>t_l/D6fQ]셖mn,nM?rw çP?rzl?0Hmtkk(~bot6lۤ.!7[-kWz)H өvw:8X\o!pV9,(_F5v {f5r?04TLC;㤯HSՃt+{ gy9tp{]T[ԣ0]ș_nqcLQ}+-c׋?n4$)W_&PF[+7|sѢ09x?nWxYb oqaXiYN@lҟkgOt^A|. fx$`ùx`3oc]/@/z`b+܍g؃yF4t7oOS#g?ny@3Wá\e7SyهѬv7'uE6=6f\rz5 h}[]nXkfL{D7GKi\Ԑ}״ks=5>5** +#cY_-ZXnmnnA u )?nո{#L.-0/9GG9l"v 8]${j,{?r5>Hhn7+b3|-h(,rJ* j%\0д0eQZ ?n{_UQ޶7??Ӆ'MM>4?nN+I٫lͧ-cerU>۝}@Y8_]{u5 uH ,_gS`xډd[>dvѽw;nwZo,X⨔u}ƈ'#s[_m;kc ëwPLm|1Z\mN։wgϻ*w9ũ=H~o4W_,|d)*[8P*{SidT,gB ڪd:`|>?n2OW.RQe^2X@q_$1Hf&_=l#PմaqB@b cEқix֏bѩ`INHСDR䇳̿\շpnغ_-0/Nu'2בSVUK{A&ݬ+%o3U\cO|]|_;VL7??(:>޳>MʗŘ|S9\Pp;T8"_<%)IW}78JX/ȴtwP5Xn3dMWI˭W1?nَ?rX~EWC?n=,72\su8P,fEgzp.SZskfC.(M,h=x]4ڻm^ǭWftә??[Dgb=>~y1sMP;XݿC-VK( E͇8ET0xQȼ Rڣɞw(goўKЀF!I1y<}S=#?n{?0+.CE3=)=wWwAt?n6AV`/-?nD]XXHehg0ejg{DTG+3VU*#lP4ss=i#|'&= a"~̓wSDT5b#;y4wɠMO_+??F)7S]Tש&^hFGY_QҞhaw0??+oǶlj); u(A%l,LI#92޲;ܨst$N5/_A?0a],?0ܑ,Gp8bk){^Qٗs ջfQ,Tݫw_ߟ޵^^y4!炚3n M.PKrtrj4 o|S??ecc`)5"v|~CchݓRa|=uMTNjS5s)~bnFx[;^0!{9ݲv\Dx<x4כdOh۩OKM??rG{<'|~4ώ }6??YGDYĢt-ek:>Z*M(~Jg=kG`?0%q_/INK'9˶i9Xd ъ}%O;˿N8} ̎VTַduLI?0՗?? .%L~2k:⨨z_=>??~E4ϠKp]٦TKpq2*39YR&38=I?rK>dB??}E B1O .??9)/bZhUtOtȭ[^>~3-ΒU-a;yOv v\q0'9{ɻU\T- ]mfѧ!q:M"1NG3TMcUa3US>n5sCuiVKG30Hz"?nn.Տf6\RWu㗨y?0ll2Rْ׫uTV,?r.-iFkǭ)|pβ3y8Or̈́L`>YLREfQ 0#'?rLdܯ'|\Ix@gxsjGޒ _f (׮*`u[ňROW(??Fk1}y2j`\!tGSǣJQԩ1,S0\\Z< jUq*6EaA۳[4eH&?0ƹb>{rr>xSL EEY躥H0VrX2yY?nB2:;_.mm,+1%?nD^UEu??Εzkv*Gi'E=b$^_#ϕ@;06=s3rL5<+żxE G뢴{ȉdbQ9c!V;Xgd 7Z\$^6rKvje/HumMeǯY3??FDjBΆk6<9|2)&^Yi&'ᆂ>??[o?nwV(/,:cH!:K<<'O_N[ׄIMgaF~$$2bfPM?r;6aO9~;f1qo[~⨳Wz]Fھy_lKǏR#XmIl%v{:SDݣ?0rZ/3??mHyWZOa}I:UwhA&!3٭G.V!aN<3::-w??nE[S#M`?n9t??~]Mev{6u>uUHJדшlAKkF{]%(ٍWe?r$&|b$yD=vj)~N/x2IJAt&h[o{??($aWW~fg*ƉIc7=~|㟟*8!qݰ˙|ab,%5~Uf{q |͓:c&,kcVj$,3?0bVgH)gCRK7HSW+^Uolj^>_px9et??.n~_=BA|9z??yA70yY??'NH2| +#୞ ;Eʮp0YMYL-2l[)d""5BSzI򩧠ON?0;[$P@'~i(7ӂKƧ)Jt tp̪9fA x)v`P?n2Z-+U{˶L7?r^=*2HDg{u\Wjp>Bsù}Vi_DD~O@_%%Ĺå[ lW߀x`xƽqI3,hs>H}G-.~c1^Yp:퇫$gUg37ם:Z|+NY2$:%Jc7]t]7elWM;iyA@"~rw^;??}󢖩/J"AA/^|,C࿺̏q>R_tCIRD§<,u;*p L}<>i#\Fp.#Y0rL䜵 >DJ-#Y^ AH@BT܁hunL!2+Fo֡8Pg̓p{˙RhBhq%5'񬇽pwDiL5۔,.9MC7lEVGF+O03.V[~i)˸&8G9Y.HjhwnnHuN []6%qfYWbg"t`n1g!VSn6 ?nCg`c&w9ϚױTkW!=cP2%?nR?n)a+)??I:EJSSbjnfuH1Q^Up^9ޒ1N13,.a*kڣnG(gsm0a6ފLÌ m&ek]Yg ӞᚍD1l]T\L??~|KWQ_ˬ57dJo{J˳G/k}??Z??=U??ߓ&_~tK&cߊΓDÌuPQ o4yBz??̝{͂x/\'򱫉},sEa݁y]9߸l8SԢ!`- >Z1wF6Z;Y~+opW@2 S79??-KvO eӤ+)Ep6쀘d["f5trw/Lu3q0mv.?0MZjP0^F?0kc@!iM:K_Ek2cL!ؒ_xd4{,\!n9ۭE1QmNY IKj'M??I4_??ɱ)^=~OqH*3VOZU9x>5?r;?rAQz09:W˰C2 @BנsPp;τhY%KWǃ#6\)lYeV*>?rp@j ㈺iKxZj7Oxs@3[yN1?rXҐ9X6ieSyQ9 }5Xieq›z6Q*yZqVrȆЁǞO]Jk9 nA`rL}uk4?n4aX^kEJ^4M*rOש5Ͼ=mbB?r.G,uƲ\e#[2I<vLJu&rwZ*uG + Bmahpl^PgGuY?r~shY-IKQb{Tu}Hc!ZoF+Df%.2tzpӬGς RG+zP+.X wփvh?rCy%Aŕu5OhY??jw}3Y$rsr~ 4A]X0TF"]C#<{P7FR2!je.0C?0Xx) o^86"nwj6ূ'eW>|@3Rmf?0>HX0HN(2]BP(?n2}À~RR7k d$ fǟ@E5?r7礛՘(XzSZ??un+"و>fJ^qe 6;@C!09RK2LYS(+-:yεKhNFwyG"Fgj,>~>bp2 Cr#?n??8gD("6q> ?nԄ$?00/ES_^9)cT*'d p;wGk$5ZYEV4JO+uhXFG$^='ϵ0Kp>߽_װfJ'[ vOvqhdBܛŒfSLZFz߽dCO~w:??>SRҎҨh+ή`\*t<-Q0 ҳeÇa:^ e09ORrxP)B'GO`6(f%3_dqoG7ܵF\_F(+*$Oˢi?0S;pβ0 xohD?rX7KHx6sg1Lƍk|ov0z+WQ9"B)=LX&v65^?r ?0V')mLz:<]Al,=5=lo??ho@7g*?njN.oLh veqSo`?0zcwtxGnP ʩVYG1qMGqSG/[LIȏJ 8ID[0m,x;>l/%R2{iC+`ƇGa/bEn8CCpӝi>o#>)5dɫPsN`mdcJp=Ԫ`*{u^ueuA-?0"=1Ȧ= |mzNHÕ>H5CxVImW`}6_`r!v~)ˆ8P+tP~R/D3Wzw~wj|"?0pcu5Hnu6R]\Sf(H?0?r$uT1za_I;.=2#MMH?rQmK,X;kӀzJ>s7 " L{\Qt q$LX2/ڐ,YN0ʙsW=x`SeKN*&?reo;1X^cݗ1Ͽ"=&RRs{ &HJ>'Sj'']UÂͦx!% +#??翁%2e]^|*'PJݏ>^+'?rf h+!f;}-/8C1Jj,5l50l85n5$\q7Kp0't2ݫs)G$zJճc,ʹH$|vpD|gÛC/@v˗,+Y2!^YRj*kv u֔E>LG+ujfQ]^å& x??w"Cy6du&Qmޙ/\K^pݦFQ2aTP>6By̿l9lmg@S-To)ffJK 0c\558t=i. ߳wm?0izA ",rLaѤ 5fT ppC^@B'shs{q">d! ,<|^ٳOvws G͸RK1b8W O [:Ԓ%?? L)r-Xˌ 0F5-$V 'K*V[D 3ΥIۋUdmѾ[.ZOu{IߺYYMý[Z-MئWhZ\??Ğz"5cD}da߆"dq>V7У t9$$. gpMeo"*9+P8ע>CFz؏_Fq8WQ,CIƉuN뵚3*ĉ/1Dݽ䘼^ҏe@p??{Շ˯v?nhuh, ` @S"bV,.=L<-<(q9$T(Ƭ+:?0"'] $]M1/>ўu\03,*z Nq#WA{tr|OO#=[81B]wV Rgym=v~/?07WzYD3??/dP@`Ak@KN /P׏w9ڣ'sg//ˤKoC8$j4Nxl!1h[ ݣTuFi6E݊ f֭{I0?r??;U}GCzpfo78z| *œ_qPq_QZ F?rZ4˴&J8XYsM#`Hg!4:ʋҎ ȎkF̢+ŕ;?rntCEv- F"S;=8 ޮ]\M:&ؽ?n쾡[]_ߕAgUN)[UP橊)Jg'ޖxt6&t {E=$(>ĨKb:6??w͒5KGlIϨ3F)K3;Rs]Jo#zd,֯73%˚aF4f+>7t%>xʯ7A?rَ$겑)Yz?nSd ?ngrxt*;XyfTk`HI,"͏ΰ:hi(߮~opu6v {d}qq7QO ޽>x$a+2277gOM ??飺m6ةANrskZ?0:c(c&VÌjuv?0ep!??o*:**a[y7:*;Ј.DS f?rv,R=:wjZ5}}DyjM$"ɍX-E҈nn i.)oF*T%7z!?0YxEf?r{EJ:V# }™dj)Q<RDʐG9l51XSf\;9tCր|+T]@yS{F쀜eSu ?0v|3G}s9&žw-\>ES-?rWRfoHaLm:#:"̐~S?nk:[#*vS]U1ͦO??3]xUrCyi8g4pZ@Ҟ<F`y.ܯ?r/ ,|{UݍShYHqȃ<Lvh _a`R]{n0HhY!%)awzSÉ'ML*q7 ޹5?0h}¡i|"|e}:A7#f5pq.jp O.f.\#k\G)^&wRCk>xi?0%,O^?r?0^Azq7N_?rZ$?rnQP䊝OllRЭi=#jO8߽LAꩂI96u,J8V2]PiF?no)yh?roD1V|ǥ[}ɻL h7IeccGod7֡4-Y` ^< u6.$Fƻm&xևS~6@WIyOw씞a~.-,)wbx4e3%~ɯ2?rb`IZ!_qbih/_cR\ <:w9v ~*Ͼ^zoz `칚8&YXYXԲw&)o]Y mء&N0z#Bp\~s??F̰5V2}ͨǯmj⍘a?0>lOquHҎWuΪj&cgrI=`!I:З20^1^Y=*0??u$Ld?0I #uxLֳ@$'~^\Ϗ??w'Ϻ:KBOʱZx9c7A?r/h]qilxj,eٮjݠ$>uB[_r5jJ2/))?rZ?n\W-P|[mN[ڡ,_9x!\H5I#y9-%;kMΒlsv?0 GG!g&s, H{GU}Hz[C~Eޞ= \;D)xN]siIoU4mPKOb^ _?0YJq`fxH<`CƁ\X%RKPP*:G>HsH:6-U2&p(s,D".EvݷuߑylY.ɅsѨNb_@.N4޲q)u<넣#XvLbZW~N%2!p7@)E{w*7)|P O͒mb]kYszXhQx5/UZ1"_?rԣYٶMǙ.`RŒ'jnܚP.Tô?r/D?nzӯAQ.5Թ;2I PJ⁀kDLheyl[0?0a`$C^Z:*·@6ޅaZf[-RYfPrjIx<]z|җc?0\,kmPW>-!dllV׽˟(r(0KYgjjW)-Jz;V[lN# +#V{*xvu)Sv[6$<T1ϰ|rV+t*~??U?0E*?n":|~`iRd Fls;X3`tG` 4*\{*N <孩E4J8-iןl𦱘{>fv$"Rk\wcl &CM-Pt«YoXM2MiFnpz؁pÌ@BD:5B@ي.ܩE[y|6C3D ,N5ݿ2KK.%Sr{ :ZyiK{p&%\dNY컟×<ٍ&L=xHh$\i&*4()'g@*Dh.}0 kdnFI[xKŵL{F1, Z}Xq,rt)^Z4dן$#5 VfR5nυ>Gx2 W{^{2g}%?0UH$c0v%Wm鱄]?nώz =ub?reJX3U$K8W7(TXo /+u" 3n_ Vۯ.aKXJaS=rW%eG{i :M.iFTCb˂A踷IyJ'a{ `w^?ncD[DY1ܵ>{%1)=}/Z"GA^[o{܊~?rܥh "Uj?r`?r~oIe)&c5ڢuw_~Ȣ\??mã{?nZDV+}" _eH(&QAZR8??Tݥw!%.fuꐴ!yh#uKG g/bѤ3b;zy (>-/̡$Җ+S?0Zc  T虃5(0 OU'j܌ȴ^şX>nT۾H?nI??l)Rl%U*iUƅ[}b6EPR7"|?r.v6B)ri~zKnGm*m>syئQ1f,T+H}N4[B ${ b==˘#*#;VG0_BuWѸH2hSZ1a]WJs'oUuRCJ?r+zdrxG:晴rD*o:?rPz-#R.9= ۝C.Rԭ&ZRe9+NZ{霶p%aFЅcᅒa uIMo+(FI5͝+q%J Lu~mHNs[98X )Nw(UvkEkAe;?r_S??~?rP?? $xEgR A Cğr?n1P_RrAxE'^F(,ke:jw) \Eiq ](8t?n. T, N񈡢-F-9ui h#fw T 7zHj^??,Qu៿iՋDYPNAK\G1\ +m#?r4IDxЅ KM俋@EjiQχ(PNJoB:D28ˈK!n#0z"γָԔ8= γX͸!+\i*Lo:3I}bjW}@h??2@81k#f>`NkkxLTAiilՙ D#i㋻HācN+XHZ$NYݳj1%11)-tcaL'=1qeOxFm:ex[M7,d?rB^hGZʼ4z֚%͗yVKs?nSN ىIdkd}„;^dr$ug7+H٬o?nخNUrZJ*&JN})zsg(.x $1C[Iv?0z_D:gzsȥ=8fhZYNaf~ G88Ul%«p.BknʖR121Rߘyc~|0fD~r,Zr:wQUK?n8J(_lB׸bY{b?rr־REM2+p~O\JKSuGHWŁ Mk]jgpY|B@G}E-H zcE6-?r=>h5#¥޸V~*-qP4);q~.12$,|I֏Or~(`/&a'?r9g?ryoKmi@J~tj4 :@/q"KkbI\wB( o 5Ċ*c-w*6W?0?0~8/ Up!;"Ɏ;ޓۙr{%*Xcg&s>\u%O?0@qzd-,?n@P(?nO7-g6)[|x<+r,ƩݿF8ugGȋ/؟Φ9'ңpO3w5={`ޫLqU \|?0$k'>E??n҉zd_cBB7KZϵd).1lZg3p7%)u -wOy'q?r:Dj swb[:9pGSG Yd.*A.}QPx&?ne@ʒk^}bf)ʨ_0ʡֵ@85{0[c|c(ßrYo "RlxnXI 4FmߋCS/f^:ܧ&}Rm_xwPm@K~'t<ÌVK cW~vf kոѻqX.M(3[5nAk&iY G6pہZ% ;O)h/OQbu$]R5 AP6&hMIH nE}6F?nۄ6Mpr3[f2,n2zƢuӺxsI@ ͯfi@q=w?rӹv˞ #?nfu?n ZVKQ"B=m6t.;s^mܫH0+nC +#bCпq3%w"?nm+)ulP-v:e!̋ X<|\X}ˁ\hD@F JϦ3:.sl8ʝ6f<ѥ~ʦ ?0눂hbYB΁{rk\mdPr-FGaT͇Bϊ,{r?n܅PeVR)X-VvN|?rEM??@NSߢ27^t t:vژ R˟i9eqBsJ?rǺuOt2yM wE3ߚa~x~ܪ}YgRVş*Uémhn7QpwũMM7?rkگC'g/|X=<`"Si?r~p6q642jÌ.9 U:_ho+0<Z3݈:ۙ&^tq 'rnQquTc3/8Dt#_y:D/D!ymzvI|soȁk6=G(ugHzaQq`xo??ZpQ^d& X.`'4*nBuk ap(y{ԣ(Ng3ͷp=ǣ5/V?rfW(0C ̨(*ІۯAeH`V( xtv9&KID_.[et;i<2::gŷh|LA[mdh78S&g%dR䯻MU|:KDly:%h)RICKOn퍎*;\yin8Vޮg4h|T#d {1Q43z Di=J^4df?nk?0uk W3 k%Mgbow`NfNJD6VLK${cɍ4z/~d8d&ϑN6#xF,U{l6|?nX:ɵK8Xi~վLe9?0NSAtx_yx%?0 Z2?r":6T`wGxy,??sMWdR' :?n`RHB.u2Ck1h dZk?nsР@!=[Y 3zkR@!,[?n??ƃ6%=|v[hQGuVceK,KIo"0B" zȈf{O,̃.@wg$sN?rg&>?rQEǖJuICN$+E)SQ?nQ*TׅG?nAǺz"0FhQX9f6*0`BҋQ/ ˜`Ă[d]Q4Q-P$|Z{$)U2@矑.Us6('/›6?0}L&N<9vt kLbKX[rRue{?nza(E 4n>sh|ԩ$Lw17rK=yϘ  OK㣔jv1NZ2mt-x\5uww]8yXz3&3cp?rmH,1c{|D⦧81$rv_1b'fժ^T!zEB8XU?0?rl nle?nmRLؼaW?rӀ> 5. Y7@F" ]]Ί.^J2lxTEF8fH/h 8D3a4WNBU;^Gc Kfp ;nPTOkΉ\Ptn*?r-B PT{^?0J?0W,7?0qP)|P_-Y+PU6'38l15B}v9+inmyFW[|J?r?0ljU!Smjc[ /ivHؔ6V{t(Zy1NT L zLYEz/*ͯgr.ԭIzsKomrJ\0A^</7^rkBֿd`f[jPxk( du'C  Oo B,yB?0?n`Vil ޗ??^mbrR^an*2_$Mw%0yo~qGmXNڴ/+"K>(~,TuA[9uA?0գ#GߋktD$RKtKYi>n +#??#~`~'׷"WD EmGEŷN³?r}Ht>N2RA{ʉUI_7?nu %EyKZ?nYL1T؍eR`ҋlXש rEJ%wJ^![?rF_Nh4exiQƪO:!x6ÙKGCʫ*?r^n !Ljh'AȻqo_-+y\m!ې֢bӽсmWcOTյm,oi2aM*?n)Ķ-8ke1;5\51 E^??M }09ڽsY9;FcUJ^A6h[x!Sαٗ.z"n(s lCPGllhITuZqE^mxKD/~{S*,5:v6Fo ),y'FZacaKJmW_95 A6t+g)?r1F^kai jLlgThn0T&E-Op~7%IuTӆ7 mJ ?r^(\㽧Gǽgw?ny:Ŏ,G6"՞w|0cBV.*y6JEav2(Kߗ) GI2 ͎BOI Kt] mQ2#?nS>(x΀Iݜ;OwKWU8t2'g#t-09ܧãB[~"ٻLXmxb[7o#@bK[UC[tDhpm)84⸟δȒL/(*ePbqkq:=Sޥdf‹ay嶱zOng z+1tPz/78k_/˳ "{Z?nހ"V-iϝjI/ qF5 _ԛ;/0 RIӣb)%owz ]S{dZ,ɩFY,KQ!Fd%^vy hxlbVns=AVZBaIY|oeS7 #F陸^\~N3.Hp]s}N[Tj:p g%ŷZxn?n??mgjq9xVudFygC=ţE DD1N'2Bb:Q(??. Stm?rB_݊?nǣ6xg0fȴB7Þ"qѭ{?nYI?rWq~u2RWlf6Eh.GîR.'lNZEiA5P, 1Ia(u̐8!<4Slz[l+QQzaQ?n34lW.f)wF,U&dѬqSө7N^RuS*~L%~BQ }>BN+^s#QW#t S3,n{XoSa,s6$;b}?0 yx67?nb dqJn4,f]4b qpwS†5*vCm>3p^mC(@&Z?0QsKo~Dg[fhw4?0=fj@3z8%lMdTsq2F(E+Y\_yq7JYmR/*˓~!{ WܜyY ͹4&[*{TȢܣB^=4$1"ɓc&אZi].*}隑n)6n47`1fZe E>?rҮ̍: kDlC??t`9d/&"I5{sRty+Gd3Rԥۣt3eeL[6 ;M,ƹ%*yjQR_C.hFuz⡩e+Kcߡꞧso ;??E(zq?r*T.zn쒦t[8iwhOqtďnѥIU;[v:?0oF!_Fle??g߿HSIz[ 2gdK%emFtoԖsI6B AOw \*{/yye,<Ϯ.Ov??>Bhl(c T#E݋=|:Y#8>}H|mܚc>>Avi;qBPE2pxV&ыWA%Z9>*FU?r(紺NqeUB?ra"׷~J0CX;?? S)Օ61guÅf.g`Pa(ĵ svu(R&b?rlɄ2_.mN1^Fc(v}2ǻ O2 EUK"SC&ACpj & 8V(dppK6[o'wD?r$tuUh~Yhwj>xV";k5Ӆ <"~UG"*9Va6Ԝ [(21[@%?rAotLR42$b?r~-A`F[|KFyK ^7nӳ= 3?n Eug=`p` H)A9zwg)ǗzqOQr$5;JJ q:bp"&S?0no7N)0jE!L*'mS<ن B ?r_[gS`3A}ʀi??Tz4`GYta2fw&&)Ig)ASn^r{Z%,>yP;kwA#,i+ׁhaN@M/gh~k'#Ϟ)JL%]mq&})蜊 m§0OF7l6DRu4??K-_ ?rR +#feEvNuV"^W('d.@)Ay%dKDKu~5TG ^5LxNߊ'??ZksdFNyzc48 `^w7=J$z-Ku?nJc),c;_QQ<ԷH a*S\ x^:+r;PU1P瓢.|^Ş4}yԆS%HtiQ@'v"X8*hFA͊2.4QWU?0dy??RN L'R1cy%,??80ʱ{2f:9E'Bܻ jUl_.,?r36=LŏuW|3뎹??R)hڧo$ɣ[-1J$7h`QT??EښqanPl16S50/A~ư:⦏4ȧ=Bt}??RJ\ޅRF_/Z2wҳ\2Cc5E|* 4T}!&M}/Wv??֋rcmqXR-K3%9GcYM?0W~%6d=ux4#y;;1oglQߊ鼜Fy&hG!a?n~]L¢vn#q:~iv8MIQt /??zN_Ltvxt< QЃ{9JƈVJ*I*F\kPN0$dFDW1UofPefjБ+{{zx%oTt\W\Dr`91ůssbLԙ>zˡχlo;/f/VY~0 Y`$St@UP.&lDsކ[TW513&Zm͇ViUUOYDiXY쬊jhXٚzZ#sFf??2*rA\ ] M ƅBn 2J\8}]'e8\J5/g ,LD]EOj%f#o %?n+mRvrusر (dкJ|hq+SBeզuXT*?n0~X&9H$fTqq\v9W}/?0k;LjgPOَy\#X<&C#4"0dsn u??,h W:jJ {kpP┡s&ƧDitfPIey5s,[g* QDTd?rή;.\,K_z@J=0w!oV)gex\BvRLV.dmNOoKPܘKw.K%7Z/1r;h.xI8_qfVNc 4W+\†??l5n] /* B?0Vc`AӠUDX|lvJD 怢YbeoHR)%5բ꡹γ󩾚yp'8b˺#:)sDK˾h:4|Q7bɲ_N5#&򢛑"xu<&SBp2jHМ [d??RvvQ7>#CeJ×0#xFv pz'r$Mj4Pq?rE>73ZWݏ_@t[Lt?r\D4+rZNlpch+&i3??yW1pv9Tq˽{)9![UO%ֿ %Ec"KW7"$ Eްdu=?r21hN֕KЈ$L슞/֎vLbۂ(OK里9?n\^!x Rck*?r v4Iq}ZO"t-RIDl}K +#q7vrxtxo喇??VmZw[Vcmoy~YX 5?0ZydmGTvWj.j:zv^4in5~*%?rWEЌj;pg OdTL*G%ox!LN4xw??aC =^fʬJS3r50Y|Ij/>kW,XjbZ./m]&xi#nQvu[ލ=gI<*f y$9YdfCO|E(ܐ7T'=S{7UԦr,qFd05g@ SAl`d*],]kD| hi]V[Lx[Ǥ.zNǸoMkpzu&??'\p|U;ӹd$#Ub?nSd??ErV`<?nC6jIq޳v{)gue???r Y'޵־??4E?0kH)Tx/uګ;$ 6ęGURM-r{\Q_ 2-:5'n7Dx8GV&8ۃ'.hOh68b>㭜|;^?0?0W)u&'??pYQQP\@mb{۫t?nvm8Ս#G4֞hJJ3&4<>Bvd Ƽ)|S> J}="=r-RIRaJ=s$De#bBqn gX6Kh@.\6yܑ2P:yC?rj88QԻ0?r !J֌S?ns7I>J|_xi}aQn2;n<%s/致nykyė#N_d1Op4ϒAIH(=25I__K:~g8q/ ;M9;E] Cۏ$,f ));ՙlfBCnYzv9OT10'??X(>OM0ȲbqJp\d WZ`diiϻ픇HͻJY(LũtTCrĕRy\؋?n?0v\Ĥ0y C/fb?0g?0 ?rh/X9-(Ic3hxۛG-0FtrB#\_P6 .ƩՀh ef*nWY twaP/EVד9f/{!}_k8(y{<"Nq8dn.8Pt*MghXGa"'Q?n'ODSvWr/.CQkL]jp -76ֿ8里.s+^K.mIWgY|0,Qd8NᲫX41>oz~ڮED5%s\r:jhR1^ɀ^N}hAH-*RqO?nZBbɠŻ_`cǮM*hDEyr]s̘MʎS7vmnpIB5s7"QR7fFQvu?n1.gf>^i"NlAǩW.uRnۖ=|jKF,éUGJ/*DC7~??q!h QNe#iWK4U|!a76TT68ΧQι4_Faq4g^]D aԈg03(>K#?r9>isq}_R-(;؈fL%_0wAYHAߵzh.TPGm0$7 Ki#rjkXFʴTR)Ho=3tB"?nsŧa"8u 'Z֩J֩#(q[aUZ?0mwxczeQi"—}.P_ҭTN<{n%_v_lSL-yq`%>T4??{uc/J><<=RdW??hU/:KtE5+4p$H˺)m{3"- YMYU4-]=D#uC`~X\%.Iq2??,]pǵu:li+f?njyznB4R16e2M_HZJ5Q7O.ؕcV^Ec6g0VwlU>x?0<'Px|6->+a&<`F~恆~Vi?raYQCdPWg?nW'|Vc/(??t7nEjL#Sy5xIn6??~:u%4D\|x~P")ZKbb?n O~VRio#Y+jl_Xp߱jU\-(-]W:͘/OGRU e-GL6`R??= Zu9 \;g=3N,)'_s4?n*7o +?r:ÎQ8uU:AUlP+\者zǵW׫mL13sJfq~(t"2H]BF?nk"ntɼ)Hg4CW㓵ЩUդ%UF/+qT!hDdd߼/(&QQ8܉ǂbd_6g(AR|7x$)H`|?n`.(\No?n}$]aw7r/H`|``.d(3wӭe6%UbdJsyu ʫȦxySƑ+1 W҆X7\f?0nT/k6_w_;]AAoZ?n7/Qb𾤌MrjL#r&R7q*kB}&&$PC74Ee?0iʀFgRrքmN&M'9[kSg>o?n1%k(, m pI)?rHAst9sxX/JfWXLCt\|GәpZG 52ĹٞhMR8>P`z,ӝE’߈!αWSBpVH/P|J+,qP=Z-Q3Kf,QBzt[EMԲeȖ,34~'fjPe{Q)yVz'U?rN >/S[ߵh"ԟu"*-U%q-_މa٧7fkrt/jkx??ӹpsˆ[ŒS??:[hb-wW`U)dzEY!p/PPHwM.+/ZL殺`/SA[j```B띈0D->41i=(S[/ej2?0?nQd'7 u?nx38V4}ͧSo4cu:?nšD.$+fQ#2!Y% yi+O?0},m-aP8W}oz#t_f|Uk,rJ'sMI3+un?01w?ryHAW?rҸeMBP/]mqSJ>SeFV7rߝ ҫt6 qoaR0b*l?ntpN ڛޚL{XsfZMw袞:.hd87GTRڿ̲dp~qRUTBOSy9B۶7p R2.RZJJ{CC @Б%yD?rU;' eW[D{`rUA1xW4xAQ4A?0G59<ŁУ&][48~8]Y f[dڛ_uiƖw_R,bO_nkEuYIUcIYaj߲X%(*m?n[q D[mVԣkMm??V8jM+"R??[SBQ34fY:B0M '\|M"O^d3QAB%:N5!>3;QwyQs]ǎ\bWסb`[Ϗe?0fȭ;~iRf+,MjxZ#NUrRvpL??h Z W?n CG텛ϼY<ŒT+-|ՙ|^cMO&3g?rj_:ihor( SOhpae0EV%TNa;T:й>2WSD^E|g ~+ >xL?rϩ#/1)Ԯډwj/Z RaDH2j׵N'[~?0 FEwtމ>"6YR1i+U&e3D|r\ǧ??<?nA_m)h]rա]PL1^I&LI7],\)oAxNI(*{ژ*WBԝsxO T:zGGo_vb/rSZip߷YQ)kXW눫$]}8nխ'F 0\DwU*E:/^g[D;w[-Vnۍ!H^Gr:*fq2RL0F;2|Z_&O=Fny4=b._{渉 Yv9Cm?06TZ GI_}&1X=eᝓ{oEM/'?nfݹ7S-UOro$/IUڻ7~{N$9j@wH2tt"20n)#?n;##VS?0ϡnuiV<3 =*Js=ܖQ1Xg}sͅA/ς"x3<>irگj'v$Cv 83~yNVSU7Aϭj>Ijs)cd8 !?0f@W)Mɱ$4ݥM 9Xהr?nK?retkIܳu53l9??iNd,?nc 3zJQW{uUQ?0u;Knԟ+jVyXy8nDѐx??DƱqȢ2,/& K_=G,?0F'o*UIN-֙!yk8gFg@ D/`rقG5s1ꟻݺs9V|EF3߁ ɱ|o*ayxvݵ6?nw:NJQeEp0{}$g3y.Fe?rj`kIهW_%vh7hSנaBF/ܝ??R????lm>Zo<*¹u+q4>cFdk8W:uf$y??%=:Q_|+]mN-J(w+8c3}v< Et=xLp:C,9ai'?njˆ!U%4t2B@6Rrf!»"???rbKRhKJya!(u'0V%EI%)Z\}u%dt&܉Ծ2Sr;#_gޡ<8he$[-}0Ϝ2(?r@A+7ٽFrL5U[K/sdJI2QLb;i }y#[d6ĉ+zGҮ"tӤj!ߚ c3qBP4/x(^II{@ ʞ+IEٞ BWM d\1??7K߆%g_ot:kc﫬xa@\&:pɹY/g{d/x01gڝ%D7+w}z#]>Yoy??u֞KZoC\bd0xOދ˄4Y|>[&yyA6]t(+YNbKKn(ȜLRZ=9ColzWC_k?0=jUL@;6嬳i^s$gnHx913dߟᰰ?npϓ1,&Ea3f?0Rӯ+_dڔ7$7/n~ʧ8zȞ}IL?08[Zk>΃tN#BT7^W$-3??<= LaYpLY De\R w<]&?n?0d>Zhf#ٯ??a:&םS[ZD.'G~qyKl2b7p[;'a'Ku]U?r(SA6-0 u+&Kn6y~S?nL0£+_ 풓 |!b#j??$Tٝ??uz,(HqQvO!jRKd`'Fƒ;IຟPaOUz&2BX7pu(G~b?0ocbXx;9tuo:ٻ[դvJ؂3i|4Y F2R:~ط(?n&71lxuQiҭԐa 5'Qp[^EԜ?r@ %ST,eJ,@RhWA(AKI?r2!b,~L)u95:,b TV`$?r6Vj=@lTvk je2 a h1 O9#;d R-?rUh]9qƧ=&CYP'a$<ldQrg7]p>|l!to]_;^jQ??M e?nw7(Z=D?0~;\BK^BWiTDbTFek`Ԋbv?rrTK'YSUA<̀jH<zeA\qyB.8M¢pEo;H!n#{wtLKs=*A 2D@sy{qez[ܴM^fVaǥJ?0w}@Zz?n%6S EPۇYL6se7?rE;qF6]a>2$¦* SGgϥq 8ׂŁP ?r UJUI'=LVE\pB mH[ C ^¯wUZ??7~ӲJ}$IV~`C T_)kVY?0MnW!%[Nt|FpYo4]mi??灍l>m8 &lYZoPb\ʩL?0ہ~ k9Y[;RCl~`CHt1B {dD)ItW#hQhR MoM8{)E$q"t5q2g0:8kGQ6۵(}l;}l43 {z??zlgL_v_z; D>C!_vq 8GGqDGOAZfvJAq*'??A){?n6mR2rpŨ?n{O$U]ļz&3z۟wҹ^M;/Zt@ NM*ݏ.vV Q`,Kj>OZ6)VwW,x ^HLdr;sMT<\{J(4{p6=zA2yMA?r0K{TFQ%r󩧖|J9EI$JDYC-)PmIӕAH&fY(ąGW78xG63S hA(@ץ?rGE5" z^zQ$#jxny{??\$\??fGk0BٱŅT䵊fvvF{??UfAB. X" IC!YUrQưsj} py$Zq[ĸl/Q=~S?rwsKxA_Ė%UjRG"Wb!P+8Lps(-pPOmû_dw[nBlGB`GeIS@Y皛dYcD(MC#A1M8ak"qeH[k#MT<@yvF1.Y}YO7p`P$DI g4#v>]"\??t%5pLD3Fֆ݀wj6,/D򋖲&5ܒ[4Eq=!FmR#5 #h$/uYdUp2(cʷT4-k/ oɽƅ+%AUfY<ш( SRpzV?r[ snҍd\o-=O՜-ҫyFJB??ևq~"pv\Xf;5Ŷһ'#?rp,=3 .HD(;&AQook,FInbX-|UGiʾa*Ո.b(Gtf4H?rr@?r<$-)X(KgMU'IaW{R]FYRH$FO}lTbch;׭Ųt:#FiPc̨ +# 2ż/pyׁ&0 1Z??Z]_/(Mk+aamkVU1L:+N 7%krrsJ,,L2?rvr}?nhD|^C:HR??ruQ=J,<+ZmL˶V?n*,D??wV+'K78CiHQ('-y27HP 6#/](2m9eC?n qd=g&5oy.e(}=!4J2\}25KBVȋb D#%R;x.b>{QT$[GwWL!-ggVRX^npѵU8h?r1r 'I64y!퐬ޠ??eQ#S7^+eJei9 vݑ7?0]cՒ?0eP?n:Y-eݬRG>re}V#jޠArMnkǵTҪݻTХz??.z'jNچrv0m=?n:04E|=+_[26/!]զ^F ,Ӻ_/kf Xe]뚧#ǍoK[]Y\򬂹vׄk9aCø%ډ/@cfz?r#%8gy0&\=܄5'ZΫwjkKUYRWRm.NLvEh8sӞR,8`D2mL$f7λ#X }$#CqwAD*ni?0?0"c`sDYwMFI=Ws YPnhq[kӥ[U^ PIYKD7ר,qL*<2EW=`2"[jZX?rފ{)77_kg?0b8/g_{rLK$;N{68O&IlǫCIͶDIJ<\S??!,RT^Im(?nP(?n{77p5EiP;44o;mCm4[ciCBbZxڤ[}NmF&Yoc6y RZrzPIZ &Vq_d][g'O֋{3jH^?rvVdwvXK:<ECKvWnuWCrXE?0M{h~ ^$g6b4$p?r[=윆78$r G}rxPiTX7E{ eu!N??w窱`kI??a~e(<8<< ZY*m{uTj?r'Ҧ+&s3]meOQfx W޵q0tʝJԕA#hs%DQ #g&⤟?0jd~]PrDoQ4J?nYa/rfE4}_0h-,ZFL,?nTh2Yz-MN=I™m14}ha4v?nR- ^??xWaic#XY?0~~0*ObszY&??v=ޡˀqiu+77qy>.:~5rr!0DML(+)j+m#NlnhăTmYd?0^d(rM3 fT\m"~ Ϳ?r/i>66Q'mWveY8;a;I-6!gH@Y!0f\O%?np?01D+oi]75s;7{D{žat2pl`ʈb-?r|-lTP-a2?0S)e)RV+n3s6{ 6gUIrZ{f<2DS()mPvP;Æ\)k:MZ +#9*/_]$O$Lr&+PtxBNP'o`_dZ')Gm. IS_&HwAgϣ"]'1!O2eEx͈n#y6 8~_,'A??'U"p{roVo4 Rg{x1oo^gaۗtn<++G(?nBn'?0STNc'dyBStseSY.f'@^F&k)6Mv\e@_Do?r-uix^qՍ\0 g.j$\UP4JUEE?rIqRfǪ?r1_rbv*+QՓzQae/[/fԼa@Q&}Jd(LqJoĘDx?r"bcQY 'SP2C{av]3"tDj&Ru?rXUAN Vj#0:}@rfUvs>vL hH8-]L༊lre_$[M٩^gJKɠ⦃ȸڄ(aJ r;s!Ɩ&Yttyvx;L9f3hj)`=S oH?rHy;]*7>y/,MؘjFƮI[?r >KL> Jc+6']Z>t62S4>51uqPM?? I,Y@7S%XCF(9H':5??Z߶ZT.??*F1+2ϧ?0ԮU.b>Otxlxإ=񟔍RO ?rن;==~N&IHq&"u:G9=} a.^^yIw~*JDXrZd^a*M0wG*'F"_s%"W-0Z)X>Ob]o2;}OY8oY4 $`-x?n"?0a#<$Dkװ]pk2d̷ownwqgI]Ɏ*7uht/(ηa Q|ɣ~sхN4ɱF2Wm?n6Ͷ}2NFb< Gf58eLp;Y>)VՃ 3>~ΗW$SX6G+_Na'UA0HF}<6?0Se4y9Ox6S/#osQ:]3p 2C:pzջi1!nLůD! t3v~@l4ܕZ"KPLJSzesz.{Y>{^Wng夌piONH7L.%jLZ5U?ngA"G+uxtڦ;0?nΒ=~Uje@k%B*|frwfffWܱ?0uruX ɪj:%g))/MU)(qe-'qtud_^绉xYDgRGya 'n$Myԍi>5?097*uYӓ'N3b!eRu4M6]-j$ي@*PU=*;187wŀ,q;z-/ *OMLDt+m?r:QS~wZ[lEN^|Q2^ͨTҳn:f?0k`?rUZSBX穪"MYw(]mckoAj?r(stq??`hډq>ݚnuQGַn9T}ojd|¥#?0r`ߠťƹFhk̺UpicߚB_zۮJů}bi=>elR?r-LuSFƒR"nӖF*S&SR(uErH9ooF,wcf\ 5؊(XMĹ?n!V??z9Z[ny~ѥ<]e<2sbto8s~~ v_Esv}D!8~+ۙjL.WFG刜zzD,Ф]|GDtl?rik졒6U@!A.ODMKԴU;[191trQ8>~ÕQӳjCAƆhhJ)&NYhksg])[6Uъ9?095˸5Vn en@`;K;ڹQ?? .Q'!&'p6CuP6m?r~Xϓj_Kf xPhȶXqŚ(m\w^MǞKP_/Qҁ:[F8KiDnB4PE8:;=*]SC?rd_D^q-oo-a@ $?0 C,??+X9ai5f^aϑl?nOu0(y0~1)̠1a^Zrc8RE'(??f,K h?0B2I6ŇcP7YC®Vu^\dv+o8٫]gM%My1i1uc-%e4R4fGGӭK}W0]bVKJ=CW7RWo?n|LĊuxXmZTua0˜9/hh66%C!R=,fG]G _f}妼Իf`%󉷱0fF!g|hgP]c8V#_)'?0{M)9?riC9eSmm6ZmW\Af475?niGARd,'XoR"z #s0?ri-c ?r:>'g|Q?rcWiiZ5Gc@MS3-^GDz:KYmPL&rNuv;zpu?0kut ϱ8 +#{zqx,>.tYFK'aV)U@2ߤf~^:s[*ې9+Dx?rI&TtWwD3\ZC@㵖t$9/'M9[ 㤫2xC˒4Nڡ[,ivg։{ܩU ?rZ;t՗VI\X,$??z??/^c4P,iHM.o+L꧷3c$}$1.A\kyyv9(JսrdO6UW4502)b(/ÆjwLyJ|zB:~+ڤG2&%QC1GoLBB \\S/?ri"[.0/yP%1nIv%8??nD]"fq.הW;x8Q0%YNc9TSӂ;Yzvc Ш?rzK5t!`v`^6nsjmᅋ`nlk?r??ح?n.L9 MJ4mbL9/NDi"nrӅT1ZOQLl$ ްέ2_ls:8:m݀>_ܰפeMD]e2{pq]P˾PfdV62Sf2FPoKvZV+9;'n]єG^>%F (O:SL9.H0'<9?n]"m4}x #9)w%/vf8,V?r"9-M<~a%Qneu"0.4j*9Kkj??px`Q؂ldZ*ׯKYp㹓q%\ jᰍj'W'??b"ێR5pi Uqm8<Ӆ%SW+^\O̯~|wu,7`4?0p{7|+[}0š­]0>%rs_T&??rkq0yNI¦28I"*iJ]fC2ĺα}??I ZH,K!cFL7OPW{ÎIw?0M}ms!Q*ER?n͠իM7*;O@;K"2W{Ԏ:YLmc!P|mU?r]O.`.P4>L*H#_`pVʅ27De5%}EA?nH()8ۍlE1ٷ+nG.YDڦ簬U-ZO?rNKR"LO.-˩aT5Xcz,`-RAUywO‰nJaTG:e_?0>e173S@7.DE?0vQC_Ǹe қP^ãx&!!W nԑw,8ڀНYݺڪ$\-LQ)BPjLoȈw^Td>[U]YYp7htreColH-@??f˚`ybTƘwå7`) -ml?nG:U3q[:dK|i +#;;^ly/^1to{Yj'ɣlj0֨>8J6m/d--$%2# p~[sU"?rE??ns;7ѿu+}#\aT=ӣLYذ62kdgW@yIµjxө5dAbc кXpVX ݆ʅvhUUN"ҔF\RO[ɛ֒)cƱ#9pWJ=u?r{6f݁ ?0.!zDGԟ_VaNIjw;$3Rs\@47ϛbIZH*,P?0Lo5* 7kz?03ܶ-|Wj0qxsAw~&d{PYE0&M9}WH!"c'ٯ/4LBw6ye\9XͦlB?nxLӥDxj4aS׳??]8oӝVmzȝ,R-K EdۭRk}kd`R4M "XT#YC}H9|Q}9>?n8śU@i2ϕ.:r`Kܣ>(ؚĞE??mdpfܿ:i[VH"O!ڔEv=.)%ݝKp&5 Xa-bK/=XdY`+ !bguuZ\+Z5EsN}GlhBS Elcm"71Urr cRLdj@>??u^'?0NwB0xxtr1"ܭc#Lx?0hͰ9M(F>WA6I4φglNpYXN !GYWt ~_|vDžE??R5v(?r T; rl {n;hZnR5Тt65w>ދu{?rd{?r7b-mʑ5mj5 [[ZXi$]+c>I m{b9/`}la;ǥ+H%60?n3(欢"e5>+0ZA?rP4(W% UExPEXT]}v`,N|B?r9";EE#[W5]܁?n=v#ËB5@e{g??~?nE1j|qp~] Jaw^f)p4SuREGL툉ИiXfy>qs_Λ~}+AyF+"{<¤Aid.x&Z!5 @x[΃WD[};?0 Z2p]&SEQϞTVT[qcT\Tጒd.pwC3\F`L7+gB7Qm^1h8҇=Dkҋ'?0tfc|Ee % TMm5kii,vՋjhDpi4,bDцqGkM>AKUo=?0h8G0|~GVjʟ:L\tT%T(KI2E}pC7Ɩ0;^KuoBqp_ӟ^WH?rI9z3q&Uw.ufTNL簋@*bJ xSg_=/?0ъAo:I2/??XZpjڻ'}SG33"sKxt5, a`aLiTҋQ&g"Y̘JhFRR̽?ncY> Bv]Ew韭;CU/yo1UM_?rI8!F8̆?n^)=Z-ҭ@??M.ԛ_0#O;@Խ%g$t!cRs?0w[%yhi)ھh}&euiT^FTb9}\ZmOQo}0|y.#n^U-n:}bv}Bn#|ypcr!??+l="=hzZGVG?0:C 8+ g}ŦA6 dqD@ k\U m"Χ_[$3wGmN<{Y/zcLڛd훁m ,??ѩ;dlzmb5:)ŴD$?0I?ro(Xafjg$Π0a<#|TnHph@;gLO#/| ~m9V%eUQ1]B°ģ[Fdf9kAաE[dٙpKi3Hfv7:b>׌y/52:s a&^I:tҊ uLXnPę'uvɪI9{$?rO* &Fetaڤ#jrI>qY U$ḼRK&Å Fs,ir8?r9a[耢 _ myND>UyiHX8=zH?n2K׎=Ջ^9??9y7nUM;+V ??ƚjnV\l$N:] |o79!eC޽IZoTC%zpCkOU4siQ.U[5I薨Fd"d;QweB}k/|<Ib*4"_BWD,SG%\I[nL7ruQd}j)KKO 1bM2i:hǽΩ_fE o]hT@1Zpk2???0u98=ϸgsⳑQF)Z~9i3^6t!('yc+FJ'#,N`LW)Swb (Fلˬi3GRs9Ek%!8To`zʢnƢ>LbjSiL<0\H3 4js3졍c5v:q{(.lM Xhm۬3p^ꐘz7avho(e@D_ˉ&iس4DGk^+2_ HQCzZzC:[V"8Q-;69ݛ&??}nEw+Gd1$XJ|m"??>r`AvƇAza`uݜ&adܱ7$f?0zmmfeİw.hthC4@Mθs\pN'(Is"s\}uŹqX)2uKh藞˞ _[h&Zzڧ-Q:b86L_!| ̄1 -F?n7gl5-h2P W_q*PcAf?nA&!F!Fd}GnݨsA??o??YD/T;MCdHRv-"&Q^髷z7G-X=N^??{}ȝ)d7]hW'0-vЯۗS:0FSv6XWWc-"FIţǯn$.$sUCg =.rxjm.IBo4 ҉pIjUbDB2eIb~82h5M2;D|??ouDqHx$6O4O/Nz!^USN}/F Q~_Xp Y-/3xD6P|Q??t2TQձ`7+c6MV?n[kA^RZSMҖ*V @ƈn(${4~2( i[VN?0,Z~цLDYƳK]D)<3HʒPDI U7?0-v2?0Tl3&/7 0?r$=!m# 9X)0#6w4% TAF+$S..X`wLF?nӡg<7QoN>bi^lq.I]+٨ZBAFLB??oryBaB7[}kI-C(R Y?0EѱBv2,Pe&0p^1PhYrL1@㷞 ??Kxŗ?0X'ņf8{]%~JCN?nnC¦D>Oq^2$'??<])ȉ u.x/N4%i??]|??>yߞ7iso¼>t9B#gw$:s雓|"IB7oG&Kb$Jp#eOQep̼{¼ѐro0gNMlʱ??Hu)o3i(cJ?n֤RtLɥ)ʨђR??y! ё[n2CpKܳZ)$YV|YB;n1D-mlZ\/&08!rB:-(|4)ۗ#o.F0v#kעD]etUh=E{͈Im6o1piQW8?nY~F[k5gk瓌{c??Ǣ[ZE^IvJ,d 3F2&o9?r7Y@zV<<`xO{TmƻY. $k??2Et5p!uxGnK-)^j&0W gvlL%P1GmQ0QN<{VXy䬙zb [5k.cNB9\%Rį-i`˒IgC4Z?0uI.!,̈[ӎtѲ[HКtHOm|}99tW2ĵ15ḡ} HL3d- +.^mZ`E{$6F{J-&9(JG#:wع1sAjuoT'fM~<:Cab~ʼno`;LIjvhnR$w-?n?0&"mod\4q s,Di6Z)lCw,"~Wmܢu;?rU};w}??\ތP`!53LJ2:{7vT_+fvfd}a\d*{/[ASq6[g]l%g5Av7?n7,]&.HՓ7o^9r ?0QtLcژA$9 Plhu_?rBB<5$??tuM$HoH; ' T47/Giw?? vw'?0&c(KDqIu;[LX1?rZjH.Lz8)x}m?rtc/~-KlP Y?n?n[۩8wNdj.f܎K+???rD)&"MCF;˗SoKzگSd2#n-)*$1%\w: +#~!{N0 rŷlJee,zK0\4"nh`K6$]6] 3 U^: \ z@ńZ$fԦ߈*<'&{uK۷NS[OlJ>?nPf0ULBi@7uIulk\։tGFB~S,{p>%wLO:?n fGTëOf: pb|"~wTAi 3d&y$ŀz˵bŀYX8ޗb xsF+C|n h40B,2ҰzOl(ۛE:wzz}SI7Ӵѣ6qXM.6:D:>Z~#m^%|WIlN$ %[~>0Tx0tilf^xsͻ3OrsFb! VpuVF_Nj:}3W8??O2DnV&w :"@V}a;M+/2.p FB6R"X  2: òZk2PD *'XXu=?rg>O* 9GrZ%dPFOhDIRqOn@Lt2p,[ecY=tP絸4rM8ှn1ܯ{t5j;<hOϚ?0@8vYxƕƆU]H%I2[ގ~}V(5in(Cũ&xbJ-ʔo??uBT7/)%?0Me0Я HKt{/;戎^< @zo 1@) hRU)ϴzc!bu0_#5Jw; mg\֣&?r93WzPAU3n7@͉|X>dZ?nXGy!\#߷sD19ESR>?0m|H%Glh=rev3&].5جD6JtXlPvQ?? vl+ui"&ɢ$D 9lOQ7DEU??FD;Uбt<_ldWd`~=`sCq"Ö]a$w4y-p$W7_j`>3扃Ã>8߆nU>a~g.ӥb e~vc rNVKo>ۗ偵_v?n"_D+ ɟfAf2QUw|8fE (3:}JPDL|WP<?rp53X~o;DPO7??wWo3* 2tw$]==)"?rbikv6N\uhWwBztB\pNU-dup?nbJo9:%o8a6ɀS;,;8sZd͗(}L$~~f0*; ]lO]i8f)dɿk/OnMFe|rt&wW$)_=4aBDXE$__`\D)#??a,)C/-o~+ 艁AY$Yt`>p/R0/F2w:D9}z.[a2pM"on".H,9?n/XDd(^iUXEo,=$8nBy's\K@P] BHl(Mh:TM JLFm<8 $DzJRwSFDnj??XG'D/ù;~^ŽW˧Mk?n%X,\kKگ}MāL{3pT/%*$X'˹G2w4j??leLj 5W0g;;,va>5{>cV>F{,7ϭxHnαx_qXocɵ5??\)ՓW qS=kUY3 | t$n wNO3&cBqpϱ 8WZ-2[%Zl9o;NEʯ???rio??;j??daL/:aZ)4O _VnjlQcΡw 0eTn2Th%1>T|O?n36^=x%&b?ra5L?r[&4`[WV;t}y]~ (?07+o?0Ղ8T<6iLZΌ/>&Xq .G Oeh*-Lo'Ya ]bۧ2xu&wI mr@:@ǵo44Ql]ơjhqisLAlm% ~Wn.keZ個lل_%85P}HyhCgB<:o7qWAprq \'s?nr"o5ju;l+to:8}EUއ(i"YQ^Y?n^Wf4x̣u(x8![ dsg{0 do ٽ/q҈F|<>VۥykDI->),s/{;jn=H,;1:l-?n#R=ݚr?rh%1OpI47Agw;^E$?nN&XQZ7v:R0%\N]t>bD*N?0ڇ[pL?0{(Zey ͩ^ *K/8*ec[}9{x:M&fQ)jr޿^r?nE?r:M14&uz)]  ݑ=xV7հW03 ;Hm>P쎈sږZrK*^`"-gR"$Qqъ6X6d:{cb+QmGmzhn,Q=iP_uVglǞ:;.gBH4biz|[cЉ o,M\UŮ̫ X*[83-m1ggV"l1?0wCrV8^[ǰl\]Rl?07_ٴ.cV!xez Cy ft`^?rJ??dz"\-kO3`w]%36gN1bif[iVȿ:3-wi)JEc4iLHV[В>YH:T&8)b8@eT ߓ;43ժ_WG@Gon]w̖,Ou1tӤF]ugjUwpG6q +#rsTnk?r}.RI*0l _j2Ƭtח$_DioŠB 3-ńsDKc.-̫)( Ǐ]#ݏG~Y['h_Qvm6?rX:;[*o2̕(P \q4p@>Tc *k1W??q߁םbqz?nH4fE WVrJ 2daf7?nn;..9r`P?raKiEQp'+,.t}t>b#^T$A_M|rx)A҆L41Xo\uo>twwH~y~{~[??߀€L9Tv9ҝbGkŵt`@(m(f$(7h?0eB`0\y6 - Z am)5Je-(_mj.d+_(z[ 68uUԭЧ%oc/**UDȬ/Rxbbo+ ?rˋ??1;ZT?0;_|oN~f]:yVۢA%\FNqo*4!j{4hvA6X r=vl f3?nw$\^Zxm,Z liia!IgnvX:^,/wrj?nն*庻UP6B5[%߯*EYJf1䴦Kن"b`A.828fޑjl,`~ŀ%MLG1i'CnIXs,'m[@-%@"oKr3[?0=_[mhm[?0`:Jv곛vjp+MYC,,čX-p]`aZl4Za0S@z_c}>3d|Nxp??N:w18?0=7??*hU* ڰƲ/U7$u1#Tc)N/)2As/][7%(!ќ593TCW:/ԍ3$]o`4  ˕MY<%bN- 4Yf?ri|JxjҢ:8z:wZpQ;𨷒څP +6ui,ӂO%9NBemyMY^ghljױ5ep3hObe0YTSZ*$߯??d%"FrQ7P^>JײaKbb}^:C4bO̓bO-bKqd|~Kw iQC0/wwM6!yBndK3V- T ~~ws>-?r/ead1gLsLrX!X%",Z4 DwD}$΋W:4i NSM\ @ ` <Je5 Mbq‹ϤVuϥWxC\B`zhGx)>q̽Rk5H7a440u6 @4]Z;f~zb^O`s{:b&>α0(G?nj(#ܡ!25ã3̤ǽeF\\gV"U?0a>J)^*<;Ss+5DNeh&4+&fk3xFf?0UY)}_fvn]"_1L,?r ?ny|ȸ"m{\ݢ?0؍&cUvc]֬V1@Ii8m>DJ8kYڅ-Fj>gKDL'{/n#"!]Y0YT$^kq*1/0EH?nTRIXi?0"?r0`h"Yȋg吃_~Oԯm-R)$H̗e⡹l5b!-\@Uu(9c,.aTuf€=alh+iO</!5*T+mB3SH%3?r7$cYBX??v#d`h@'$LkF ^ogZF˻pmџNXkmk ˑP / , E0i,lf>:Lֿӓѽ~V fiV U?0޽+!m\TfY`p*V vpȴO{u?r"#>_@Hq7xz^evW@A1ӿt9WU'Y=lΖ R/#ߪm +dE3 +#mZ+rS֎2#MtAWčDf( ¨!A%:ڴ5 AX̨=/}^hƴ2]h,KDBˣH0wXy儡Ry%kƤ:ZKq>ZKGc*JTydi6?0B$N ^X  'AqNqay.&P_>b)@{Cjy DCq79??F??8o *ǥ*]Bӥ(S>68ؓ(;"-yZe쩿Zxk+CDtfL f2??ȆHiEeXQ-0'1btk5Jhѻ:%kE??U65c*( 7>??IKpW[&f<6 _xz9ku곱sFPڦ4Ѹs+yfc)sY?0R3_T5`l$5?nx cFi_v=S.}2YOn?n??]}b׸+kpәݵu\9={nS*v%f<үRn=f^>_n9{xؗ]G=mٸVw nUp1ųDߡ3$HM7ˏW;=H|ܧ{OYY!]tigK\DSU#l7DQ{DWԳ.m&R摒^.e=ތhHvY>3#_/?rlhz8tqH]7J҈ˮ⍏RhInx ;?rNY`F](.2'k,,|uMF]`NXoAv*qLX°ċhAE?rntu#*VDi`5(&T+3yiR Ae:q {f_(k?n?r$VQur<ݪ9>Gs=ۙ>Ѻܒ,)+14G*&(mIJ@U9½A}@+;)dfKV'&!2 3j{14U\S []@H]ж$-Ot?rŢg~=h&$??dZǤo_<1=Dr1#P}G{Pņj~D|f٬u~J_rt*y,ܰu*m|;[M7r0é^~~aLwoU9"E(WYS: ((ZP[0KkJ2?rÄ/kCY(i+"D>sdʃw/2K5"fܩ{\Ϩ9eؐ#9%}.!W>\:znk^ !NS<U|3Br1eFS??5Ԁ?nQgwGY1Op̓X[0??;>?r??|v3U_cc\}3/| G##'Jf0'ts.hҟCrl1/(t$+ Q\n?0Ru⪸&d IԤhLKXY#&Aŗ߈]Y,#}Wk_7W|?? 2R?0Zȼk'MB뀤LMOf;9p#9_#f+~&e,4xf_ۺɧ sp-ۮ?r{,dW,}#UZn*H=)'Rg0KT-b1En2FYZtd4t,֩1\H_9?0_A*ߗ=O)IicV@ 1~R "@ԏ0 cYMpN~"T&Dӆ D Pf',>M0fc?n&f]#dmQOLZNYp(.mj@Fy?0w?n>a.b$RĦToeF)Koޗ1yT?r_??}Nz, m7~x_]^;G/ɣߛ COSzR aI?04Ō IT89J y^g_D'E~Z0VprgcZ&`ԱbBMxlvJX\7W +#bOwU??szbz`~9߿?n1?0 <:BLWiՍDf2Y& .{Cĕ'`LX{ZDXrD88HLqC@-3".uq;aYWͦl o;;C$jBRjFA?r$o])ף\)8T 4085N]|LjŎi.O/W['&Is9.M3_LpN?0} ~FB*??o(-a!>MAz/dvETN1ݍzތCyo0o_köPTK&w<гk!ijRQw{#1 ֓^lQ3:?0V?n7#~Q% z I`%5ʟp %I WlȆH Bc892[ۘYC"1M>]?rě?0.DH6 g)?n;R;ю:44JIiD%/*  ޿=>TN|!Yr~$(zcdu~ @,O]r(,7GEϋIvO(fg'3܍lXٜ3LwnbS8;,\??x_:7??4y1??Z=wrj*x7hU%|~Ջ̒YC(͏ qf1yz` n\.뜛?rɨGHO)4nK|Ys5O=?0Wp??@ߜ~۩?0(odВ:^rv%=Ɓf()yDQ6+x9\櫙?n mRґE+81^F2dru5ލ}uM+DȚ݌ܗjP!f(`KLd+UFt6FsDOuཛྷ1??_/aO2, ĘJ}}D'MS^MPW}hZnA#OOO~'d*Ya $X^< 8^s&Τҙ"rMx׹nGpM#1)^zGjx]MciVMтmdjQJ|}ŷx]v@)9O׌W^?07)AvҰsݿ*S9O{쬣#겴^&V߱yJ&D!]{zUwk ;_{o&$Slܥ>Ë鰡tgX89$|X&]_H8Jr??Ѩ7*[.WQyӴg:8 Mɼ+2V-kRmVĠ%**d$"<1䰫L&BBٴ;1>NT^\Ok Do57m`yp `G[0^4)t6Ǔ:\qu+O VsV!>U`*''x>_%ד\CE2??4t_>=I//$Ꝟ|WgO藯_[uE+Yʄ%5v+[MITT8e.[b|`tPWBB?r,);%E}۠f{b ?nS xaN??^+G}Nz]T|ry rip*#RAvZu1}Z??yvKQB2Ux+ ?rŨHi60Υ$n^ڲz.`oj?? v߽\39>k)#lMETM^Cwe1HܺB8ڷk #6jK3+eeC??I}/3.?0탧1$]}_it21h26V[ŏstqeާ=Jl}FYobjH6e>0s|Uf)BJwɋqF)D>_77Պ~ډmrw^7œȵ&lT|h?nW1AƜ?rEV`nNѴYH=Dձ)enF?0#Av]Dn!@:)ThM1@ň;?rWaH#_iS>8E~yEZ QR,w𒖘8b^6ey_c%5?n?rMX1:bk2+[%ټ ʔB|V:?nX97pӀjq,5edP0M7W?r*E[r;Pm#hLNcmsy}flf(H\d??yZLxsaNEi{W]^?r?r`WzrEF &DȒ֯Dr[H??V:t}.aƳE<ȚЭy<FTw6LݩvG0zY:bbQ??zWo'ӷ%w}K??oJ=Z6;W~)EIe b~W/M.*o'rA1-??aqQ $wpd$'5T5%ؕ>X-?nx~Lֿi}d5Khƅ='wϞa߃:35Se]y2we=ة0 01^9vϭ瀉fI#=*"ڠ1vtVۺ{ŤY>޳_el>3h5g96wƗg`8llsKL* 3+?0J?rƐ[@ D1vM TIs&7B~A^֥B瞋p+c9q42w`^ Q&9Iy;dy=p7͘zva.3,su1Ӽ5ќP語Dl{pl=G?nmاs7f`VUQ/ԇƵzX)z3MGE/_#ao!%7$`Q`O&k{^M.M+7S'-j\qǤ?noRP5nv:yxXYmp*9E8ta"6,V|pcʢˤ-;H=u<ջ,WFZ)BR5]ceç m?n%nҴ ?r׋b MFd WԃnF??kxl4]2Ge??L8/G2v+FaFI_7ۿ9֘yk].FL/2grqg݉D:[#^Z@XVWN!QltrH2.[~3Z\??Erq5M];4"6?0]-Y ΨQ?n@C5pƘ2AȒܜAW?nZOHF- *WM/?n.fs 6dK?ne~kwcX~> ݲh_ȘM$1ZxXb,U[X@Az O/p?nʯ&{|}jV9?0:ȣ&&ؒf1)*.88@@A%C,m2t]]}?r&RO@V$%^Y9itRMI¬gQVc:o!`x3S!>!QOyl$N:+6h"\b{>VZ╈3EiXJyBxXPJ.F/?0?n{C{.LInڨ*$#";????lGG{P?rɃ?nv8\C\$'?rЮ"Q0aFrS@f(L=Ҽ+@C 6{^k`{H}#~vӨjZ?r9F*A\ry#Mpw|t bmH%姻z\6Qi$5?0Q lj Շ#Lrm,)S4L~`?rUɶG8C1#sa1sRKcdLlq4-4xZ ƧolG/z{Z[z0ԤaflGgODž]&Ty3%&/IEW0k G$W=8b)@8zPU*wc XXN[S'#Tٜ66v֎?r$_=<'n 2&dpd] ?0}W slezO3`b ?07Bz9 >$[kc6G|f4z9Y>5hiMI,L'HK)-%Cgq|j)lW7INF%z89.(Ǻq1~)='A8k4_wd:= :Y?r{*S<=E1~$'DYĪ&Z7;Gi8Ld0T10&%S`>d>s:w847uWɫR6}V#deSX=}ҽ Dk5g.M@58ҳDT,k1l63W!}h?0fV(1omۮ %b?ryRDT.F&moz kӸS*Vlt!@unֽ]Pvț;ʷa_[T~ pä<޼|:E4"mh!σ1?r/N#7؋R, n4 dFoxoSPlbz|nlZEUSĺG hbF_F,u:IBMߵ&{pl|IM{I3Ұ,vdV5JX ?nT)4jj؂z#LuG7l2epcbo5X"#}± c?0_=Ndt?rKEx3NVEM^㑆r)S:҉,bhgjckqxۑ?r`3+s[!5we mW$L?r2#^^3R%aބ% +#}h??e;2ךq*$پ#A?0` &]4p\/5F!`fR$[^D{yM/{u$ƓC+¡!׊|XZRHXq*h&?rMD5iQ?0Ggs.'&>^)u`ܬt* m(l|=ed76ǐrv 3̾$~x2'Rq4+3xSaXGtQ:SUdYNFQo@we>N?nj Uq%}/#c"3I$792z`8Y?r7?rf{hYsU|u5>{;/glgS17ㄐ=OQ` f(=/RUsex#bkqC/Yxald0[0_PehK,a`+bX;m/z{ۆݮŹ㮇gDOO!8A^3e0Yf$- m%?n׉ M0k.Y|T1}4??<<ۦUKYP0Ǘ|l™BsJ3׊c?r*/ksh)'FA|Oؤ[ãrSlR`@jOMV/ :y:%GTlܓlֳ.VF?0j`˳@~gA!--Kl1(\VXb=@;ϚVp4LYBET5Jz{.qU'Q;6㠇ibhdz XTË0"ÇotQy776-#x7GXFaD!qY_+RX[fKJ??l@V%X5äG![~8sBb!N^HtᒆҀ[Rֹkg4[a90??8!?rFBpgdĂ9rcS=**hra,8@iFNUh5<"$5-"+U2eB ;Q/#!rKDж2Tw0wHnMYxvaUb؈ƚlhw.Ws*WQ!H~E1YtYOAE͙r@R>DM7>72g[6+Or(|VUB%Sj?rA%uO??>h\zu̗K7vԑ~]Jh`B_bW=??@bwAEKbXr1uûiPYƋ@TcMkӫ3mObFMY?nbqC?rlxy{ |Ж*>ctCټ&V;Vx(֭-N8m{16F=De\yX I[ЏHbgO6<]&+*?rl٭zgJz"+K?ru)jat?nџuKjAM#CgnVmmltgOY;0!)jHIKcp2v4Qu1$p$;x,ۃ;PGvhϯyP!9Z0 P4(q`̓`rQDx t6cuC@??&]Y=\yl˝ZZZ4ل^cߦ]NT%Yմ4"֤VP=B]$@cÀ]J-fAÉ2T]#%rEFlq9;368" o{k#?rT&݋Üg.pos?rP_?naj`FRwĘY]C$m!o;;+B#??ҩSiFOݓ~Xpd^Y=Cu[0|8g:5zLpdlӎo+}7Q nNۉZUJhA=bò +#5?nx-Fx̮gy6JU0="≩y=' P~j9Si}C Zo&n9CBH9IMqc!ViԇqHHJׇOί?0wu3'j?rkv:M/kQEų߻;KƐ˥ۢfu (~+H9֜zT.܏r_ S?nxTR)ٓO6@O &96??|W??}; jS\Qc.E2Q; $NpF|RL!`E53Dr&H3YRY\;ti^g%Cφ?n[~QXrR۷o_|^??Y. 1.W5Dop |-GuZLB,ȮD(l8-Ο??zֲa5Lumpq1]6.WK??&;ib6(uoq^sPbɱF9X9or[IQ]hπPsz+tү9ځb[wN;s??F6-Qm.jא;Q.B,0uu(j6n(jm^]BԾ#hdcxGc vpc/??ܸ(6=??4R&{lʏ`%z8agtj)A$ 3P?06M3meƞ?0 ,IChA{ZOr?ru9<Ыޝ܃vqr" b:hL: )̘;Ƞ^Rxo(H+ƑE; #R.?nTةݮIpE[vP֬E xa+Nb?03pk0w!#!vF s}Ͱp/;D]6 GMq FϷEarO”0LIQva9wU9vRح '\&JvWn~O64__ߜG]GwSﵗ12 oKٰvEcx\qm_ف+?rKlGPQ sD ;wXUӵ2]n5^z ~ޢ77?rcQ1粒@A xﲅ<(r/׳.9FSnٍ&7'ZЧ\%b%#~R??GE,=mS-+t3z#]™??Fxcv7۹&s{JiJ3yz:}M24f(·o*K%їK6mM #Y?0'M%2as79*Z<pl7Fi'p??oW*Yv셽B`J!X-/??=}xmRh; J96ë!xq[Iפn.datq3zeb?0JEµXav>iH*s`;0F2;e XN*eHN1舆=?rHkE`J7eXزs!ome wkh5WX&Gboͷ`iv$9cQ unm+YΑ%,k?n??{2@G7|ь8!$š$À0{σCKJ"v'PmR 9֥S`Bpu^7^QgO.A٘1vA@6x^-n?rW$YRXW"9@$b9\pYɸsIT{Bq)-9Xt :|$"eN}[Ž?rN`QoYڬ і%Y|LS ]ZyzֹO֒RL-Kd94×]åf ) ڀ,]/4}] =?n ث礦_fq?ny5x5إ3#c,L׮n0,[[ox+Ge2BDcQp [~&.侘djCM?r0xi66<?0FjIf<|W`B z1KprӟeݵX5+Q$Q⃂@'JeD4AW-X#"nE Ww+z~ HkItnT詝7=/&(0- z?n Xee45R l:C.)6~XLQCw?0/ 5`\GSrǟ̯UGV|>~ÖƠ͜OYDϒ1(??66ms,,'Vyʭ4QQ?0Qɯ?0)+:[v_1 q"'كM"zLRh|e9Į#--jqAYK#7L9-k@s!BwR= ir?r2n*8;?0#?0 oi^T4R?rT{(?0?nXe_~!Q4??kU gmbQ5C `4r&nCW>PeJ 3f;dD#8Bܐz+D2̷ns 0oF 1Ye8ܢ]=C) |<3??9;ז9[I|ok& ¶[&GI=2!ݣtZ:g5IУm[݊x]J|aYD7?r[~"mwas??h:#L?0~*K1G\oKRth. TmR%@ ;),@I&̓E׋cGCqtu8l;&~ +#דif,>jLE=;iఞI7;=h_-ya?0n-h> PTY-jNN'k4(2"s֐Y(fOx??{v*>0h:aYtKa?0b S]Ap*AF+ZbN"oTIt/0Sܠh6A֨$X#P_!š`}S2#?0d5.;NZ=O/9#yF餪Zc#ç:Vo{w8X|KOQM vo﫰??NBQQ]kF*|{)w-К//V>|䆗??6?n[2"h>M"Y61Ś}ZxBl!5[e$󔴖 m[`dWv9n<$[1wM*~=8cm:"41E'_[?0>Po[́n+D,6\=`6! BQZ^rVFӵljt??]HA656vw;U?rf6ިoOw?0a,}vd-tNo+ 1(N?r/T#*nC=2gd\Iu["4;fAVlۣT!{mOwtr,CF5omG!هDb6OMQ>YX^<D7ie]GSljI/h[U18=EbuMlBh]:#-XI՗Mq!ǰ:oֆ;e~SOkJO1_/K!4j}r"U;!4?nW"ݝe]>`g (sî~4%0y{L3MƮpgl.sbMjx<]Lvlbx4+4i'Ze5sP9^Y9,0V~F 1$~-niTn-+fIq0vNKh9DxPzV zy)VJm^32DνA{>?nD%p}75O_#46h+ԮZIx#[}PPKuKI G7 w+鑲B,)6E16byy#Wfp]*w sŪnK{5i-Z%/yzhu$ (bYNhM^Za-j>voafZ&?0ڦ)oʳ~R`z̓P,N?nZqŔ8+6=;#fvAlF҇ٺv=B42)Ȧ2RB`x Ҫ%Q˥Dq)hS&M/qp????M3:pV߆y<¬zE?nSs(jU_{ *0F\͔0tҸl8" y)ةԺ'Գ!z"v%LԼ8-l@T\^ \$Ο[QޚKIK C& a%JGp׳sI$/?? rEz]xUKw$Fѐ/n5JnH>@~V-_bf);:*Y!~i d,м!4$RXQ>8=vzdW+h詐%9p(r18i ͼ??ǻO)"fJ,/6eaITD~Ň5΢urqld2{ic/q(ŷ9#`W*3??LQO7|6ݚ!gh;l&+V@eiXj9g>**:?0O/!7G+sp;$m.W|! I9vqr% G/$5Ike@ɒĮ$ISsU(H\(:vedHb"o_gҏKgqta{Rec~4-#{|MeEKS:فtAJ0 ͇ EG g& ̥ TIJz?0C r8Z,??(cٻJܣM04zlў5J$a1UXJ%|}?n>FA l#g2=}^4wgxM6pR<oo<sBJL¾ 1|?rA1`:ʭXipPoFX+AB??jWIV]-g͡kk B#8+#b2kDZ^Pٖ?re/G|@:ŗntmM7BPJǦ~ +#?nd_1_|Cn dVuA*x?0.m㾊c{A[&)4QM<_\>?n-CY0:ټWכf-ҡ(TZ -[< 1(E3Z+@`A9ҷOPlnU_òa0l{=ilaʪZ;Z>)5ͻshK {dL1:dQM&]Jvۉ`{)/?n{UJ&z92?rn3E߱KfWBԺvnR?rE7 J?rC.DJ)wܠZ'ݨLŐ:ASc!xlw>??<??U??piS] .դ -ÂcsEu>CjR?n«T?n餠5ETͦ9 fydS&@ے*q;^X5qZ%qwMzepӣU۲&$^"aJ:nAVF8/Q.:^0ZRbHua`[f-YY̍0)ƃsF &WsBFr@ HA??c-"V?0<M#~p6&a"QnAΆ:uuh\`rV0D?n71~LS1C'?r?0(|k*. X7BJOqG9E̠]BR4ܣNڒDLB?rQ^"GUf2_?0z>o(boqISۘ`D0\b)Pj??@AnY <:BX;2h*Q?n,۲>X>kN{??9a_blk/{%Wȑ :TBwEh*A.bT:N}uk%;JwmxFuKk.GEA3> i6iEY.tDOΐ@祓a$+ceShn*T P`foH|S!"9]*DLIJ(ޜp2F{ 8 ٱEբ@ճYDNiyje#=æB<&n`GAUձ%# kgL_]Nvx͟g.}ODܡVHEO?0>(U{R[OFO Ǵv$CpL$>ow(ywDK% ՖbFO?05ْ`PîQѠU3 ѱT =B?n-|l 9]꘸Jpaet/ӣ}4xrQO@{㊯7҈pۻKs;j79G6nY眶,`\-m@?0R)٣{m$ܶmy N|KYM???rNӽۨ&>N"FslŸ/|r$N-?n\`q!Sx> k)<Ȧ[ J>zL?n^Iѫpѥ]E∩ )+4Bya,6vM?0/??u1 *-.=,iP]7rfjS}k{r_|:O}1%sNLfѫ΋rFTjUdٙފN^3@ y^ڎvxkf>/r6Ye&8ꍚs ,-Eo8ç/H%os?nizh0&4kc]fTKդz]v;Z,-Rx<㎜&㰆UQu3U,I  TԤ:88h$Y?r;Mv˜UR;xu1)`i栭C5oWz_"6PMl[þR=YjGvҼg8]WZ=`bm zDCS~~5>=|F/__'u~>q8.hW?rOuM6a̰*/#aH`?0ѼCLWr7> K=|2'pEq+BbQ57)c7#[mɬi*&L5wِzυrvD'?n~e4r01UtxuZ7t7+vKy&?n褣4t@֨4%(UJ *q}jl2L&_O=?n'vl~?nJjY??*VlP:XZԣ;jLf$i -(PB$#S ?rKQ!C"W8%.FZ(x ɗ[>΂y0H ddžL8II1Xŧ?n7),LԱe/O73?nvyq^EU CdW],H(zdv]&6[p^I{^E1A~i`A LQg':NO{,ֆoT-tzdMV#yĄm̻QKᇗye P7ͨ9R:^=u&?r?n3+}AkK9@T۠5Kz@ث,ŘS\f,g[., Qvu.aE.dĊMBn](In_9ze†ۖ?nwP7:JL4/)fs983Ck>za#zt2=:޻jDz8aߓ̐nI{z|tfPQ3 Isls$@?0C>"]K *&mVyPSâ7??a;CL򆊧]nZQ:qU7ҍyo+/sBms4Rq7xsɆiNUlL>87%"}A^4wB'ퟅ ĩ??)d"ٻSv1f% ɲPHܷntc.t؀Z#ngP^+ta]&d$WB#jqBrjZlʄ>>[ƁhowX-?nLfha?0>j6r ,l[?? g7K?0g-^}/_5f63=tƅVN-;[hJ26\BN7px#& ?0q66N7Q& u ??}H@ւʎOJG4GZxD???nr"O9=տeTCpЅ?0 M@l/ +#?na?r #i.~+zM8??{ǰ(B1E=WJ*Px6+4T*j?n?0*6U9r[j\RΆ=X8JDe3.?n>T_3}oZc]Lbծ8JOͧ-K4/K Wh"eF%REX(\R#PA½v[E+,fu>aH|;C(Xk1.BF8xPhJNKjm`j07WV<1-r8 euq1H>Ɯ&>b5ݣe7raH7<7RHm֡l^?nBOo~+>մaʗ+ǧYB_8elu{[࢜-V,Uݧi?0 {8dXn8Rsс>hn(ppk\B?0qH\4B24PoyO|OpVO1`ql/J,\VP ~ec'9߈bpb"AiAA9?rKiA>0@Ja|h1n*.?n( L*o_`{y^g>?0gvj>c0,x۸a[ƪ[b_ٕ=qKB* ^?0wPop*,Z쨰^pcqV)`=E+va- ?r{?rV  Z+FwW +ݺ-e0RXL^bQ?r8 w% ??Z8;Ixd EQ_Z)8vQ>1?rolGQu*<aNzjw@QNap9 ^'('#÷Wq8B>\ËyW9p*dr?n|HV\a6PK0nPג4xhp)6G&L~l2C0DG;^>T4n{N.guQzbB-Jq81:2AY?rYF&aK"$E 旜m6H>-IBHQ_OuTF|{VٶZhHވ[TސJDH}q`گ?r__ּFb`34qa4VfWfgaF5$ ‚y%,ڽEc??*MDD?n ۱i&iTRaEL_䷃V"6pnw`_91(2laUvq Y1C͏mis@źsȋG}hW2z.& ||]'/HC_P_?r-OJ)GVhZ*g͏x2gj]GUi%Y۠%&1ph$E?0SR9d9\piI:u!>X@}uId/Eͺ޻<5-@{ah,(5#]zENMR/aqꘘijbV˴ZrHvY@Mn}hQh:`?rKu@_FV) M֫:8iK- %\T>&qL8:52u)_c,WCX20SUֱJǣE^31S$ԕ_a.7C5萾6tQj(Pq 4rTmوyd+11n&s)GuMI˚7 .ĎztJJ,R,l(8&gek9sMWӐELnWoxULk#K ox_C^Nң@GCWxO{m][wrshz$?0# tƬ?0?r)‘<].ICehD ^<0kDp(Z}ZȄ8@["K. oYᅢqM4jzQaQaQ;ލr4v+FgZ`d-6^`葤8Dۮ?rݖws"?nב.$ό ͦx1hK zi8HMeoI]玥Jh똚ٹy"?r~w Vk!C).(XG@ëH ??\eFp3>HNEC!ZOZɅb?r(S[R9r0̱$[94:Q=I1{nдٵwG0TJ}̏(pb$/w)(@xf@og"}#y5paû?nl3),%cB8@y\re$T'5L3ٙ+7U Bh}r! ?rEgE].GPnpțjϳ".9U34N .+NU}G#ezX50optB蚷ͺw?? /-0k|IdR8Ԗ˹]9@8wԫ} fJ i؛shyؒöڞi`@){|m]Fmh0MhL?nN$x3UC ߚ-0eVO9͊a/-Szc|y$O.19=?? ';b{hq,F0?nrEPψ y2/a+Tc{UjKjS`ae84??d޻T?r;ZT#+ }JI.+'yt`DӅKǼ4!?rAuUi2hN(#/R߶yڍ(_MF%l.+9?0ܒ ơ#0ȋ@߿›a'ʹxȂ::p]{~lzL~<>ǩNDc{-`D 2khǷ/#7ecj[% GA:$7JݭGW` '15j"gQO=26G3tbZ7#IU<8`z饓kHϟK/A!.z94uGW x!8 jukx{@?0?n\%(JD6jDnȬS?r Φ^w OKg[V,#.6ᠴJe#LG,3»Y]k1"ރ9A-gʉ1/݁vZ??2pܲ ?rlܶ%v9\IX<$[Jrue,[4<:|ޤτ{ʷS1}F[m%Be&h},XlJzV=(S<;BftMC꒛7zMwG64R@4(e@O?0\dωd}{/"#Z7ٸQVG%*yl8o_}c!#<0u@^Ɔb9&F,@TH:y%&qΈ|5s62K.j6N[܎ش梵z>jn[7j\rRtu]Mm6]?r P7 z V>pۢ hQ#HjZT1Z _q& DI ׈;?ny!X5c]m^kTw|l+p|~haOvpOۭ\ayQqΚ0 _ 9j*BӰ1h y{(=63{@/(4Kud y&`??9ј*@hP62k<=/BE-WAN?rמjł nK~o^p,өiveTZ?rP0`=%]FE(*jaK7zgABFp$/vpp!%Mh=ϜHQ3j\sh6aл~UL-i(aZA F-xSy.PF+ %Y-??byVM SףwH6 47ɝo{޸]Yi5?r5|BX+?n4 yQbYP)LA?rѳq9:.@\~IFR%„j^v%wܮ΃ dn|hGG-DOe`_}ʣ?n@鿘?nw/F`LJW(]Qf,h@"j%ğf|ߊS;NOH?n{'f/Em|S6mfj5iT2K4S\)KwZr9rt Nߦڐ|O@Z 7ӑ]cϭr4#[(|ɥg?r$ýЙc7 &w)nu +q?r ERHb)r?0 ֟&?n҅[C>N?0)ayǘQM;0$F4G/ȼ IܝS'q"}OsVՅxńELh[q=ŘM@2t/^W\ՉT?0ֹU/6Pw1N0ե" ;8EW>lzAъ\Λi)]v镍%I`ۛU=MI| ??-ȝ}gd&tP?rߩ?0wH?04~D9#>{~ڹ&)6۬CvAv(??Ïgkm-߷eb|w&s!kHk}6DP,B*d)2$LP"I˔H=:FP%QŒZS$J$pPjN7]{c!`۟'Q{ GIlsfYGǫpu6E깖Tev}OJenIW8hi[VOn䔃h>i'Nd,/t[b%]]\hA~lf9ꗗSWJi)4s:&]unZI[^@*/GBUJ6q1Lc v5i[/6,/8>?0VF6m#Ymj| m#Zme2xUXeJ'XyCs}FE’+CIj\de9j9T5YD[64[YP;mol|=]6˾ F??ox_GgF~M9]u=_{Y/x????///gZOp?0!;>p۸Mk'wa$U4yщጼ[vƘ'<#s21,C&>zE }??|ty.2T,qCG_1\: DErGH?r~tѼdکLx'nttхgԬg/|G姙nvOg׏]m?n[+Juc0L8>'$t}P7} ĴѽI`'.&>=ngo.ţboS=9aQ: ./+m=o7 I`4(WtvVNsd c08۟Wq\ۢCUC6>vUNڜQZBv[,4:?ns]kr|!pHQ YCW@   k r`?n4RE+vEPM-ꦺiEp`RT^^f~,BVbb;Uуt)S`p+n\cKKZ-?0R"jevA\̆J+:{G{%}W׮M+0gu(RG?0װB;#@u_:њ  m("2W`r&:~d (s&L睐??uhpdhqKI!~J"yyYibOPa D߀H`Az"{ 3S_驠ה$il5MYr!^fª=8c^NB?ntDiVIz* rI8ʰtUZhN /(Ѭ'Tp@z(5bdm7i҉.7ުUH"W?0':"b -{o GQY!U8r JXoD9tfz)HkJ7JcrBy_Dp")?00d Olz|@lۣ:)5>^j$M\S<k5Ab+~08OˈPIZL=kBSVɶ͂u:fX(%~) ] ,Iii.Шvuv۾6Vd3À ];md`~g@[~Q/YudYe$ Ecttk*.Dz[eSe%K1C!D=R FA2[{Ǥ ??ki˚"/Vz\$G83Ac&oIC1̅mUݜI`C奍4قe?n$8y!y۬ {,{kwl};T'뭾'x?n./??Gmқ/..O'}9mWݬn[t?rgTu"''iT ?rUA9hCGPfT}Ȓi/(I"&.]6@e؛KҤKi Х!~XdσH7jxLr>CӼ}:g /%rJGv6G7T/ؐ&yU5V=+-\,غQTma%'XF_1jil]3.~0ΨZ?0ޠaZ݄c`9jWhoVpsT@q??4(Ç(0馅W[%5p^U"*^NDM$:r#pS=1gsS?r0*YO04?r4_н~QY*_=i;09MSJ<03R_+n2"=DW>Z嗟cRhf*&aҮf8 =QlCk,y;~?n7Kaau ۠1еksW2  1  o9S?nvđwv@pwmgB5EMjϱÇijXRΒ\nCmùŜwSl[Ⅸr|'??Vm^/9(O^E_Ң_R֣/s9r#^0X/V1N[V%dqCv³3E0(0W=kYQl #HXnhii.%c?r?nqn[7F1T%brD??en˥ޒpA"/'c"/O4秸 Hcぜ5E\^)Ys~%AJwWIBD?rUܖ]rY;6kٴ=l?r#i xfE7x;:@wp?ni??^ȕK^}POa|_[U/r&5ɡga xNTڸ.EUĂgb??MV.a?0C/+򙃆csg/_gp­ӝydŌh}0 fS7-cߝ4XN:YfkrRW%v&_PjlT_@<וeLMWJq?r*[-?0Qc[ց1VxGб;9d8O`pg[vqC4C/8I[,hF_vR;q/GaŲC>D $1.(vں1N_ji2RxW9#P@@U }2Y'̏wƀ??ƶ9?rXqx-6q|qb 9{ $>?n%SC?rEWuc-shoY jtXXQ"=R[&u{[6`iאF 5*(W5@(^B*D`s.,'ܓFY_/Y%_ ,??17>,ۮb]CZd1{?nO=ʾBghY y@ѢK)W:ZPp ӷs$q#U&N`dɃ?0}OH^ Tԋ gLcDl 938A׌0t*]\?r8p̓+fF,R:zd$)Yr`E<:t![ͨ?r۫Υ"W!8*Yڸ`A-a1&?rmy=$K~:?0qPm.RLMni1Q}X΀6cI?ni ?0 8xY4IW5|ƊǁF4+P??W-NcgUqdݴXG,cQOS~/Xk$G= ~ͷQ=g[,eeN??lHς3H9A)Zu5O1D7+x RT-z_;B[ghKp˷,I^l<.1:|_6qjXr?n+?r .:$e;w2mI׷4])ZPZ Nek}{=PY?0zRtH W/<$8FF"[N8a/]M>gv|7TLBès:JR <3p)8#Xa^k(Fd@v;xS)VGbi/"SnH׀#pZjnu??Wng$Sw27n;[,ѶnFrrHe^ɱ &-k@ 3BWKLntvˏ\Qrpr[?nﶁNl/Wc%qp*Mi( 9iVI1`ߪ-E{~?nN%A좰"sq*C2 LG]'QUR~WqSNs%-P:qdGa|O9A19jЀd˃Tc}CMmoª?nݒ7-$8U?0S -[5x??_FC m8-mE:! x2jݿpYWb1MsvFD47hM,$9r:r9 ]eU<p;Rrh.f X15*cGҋ=56b{d̵?njdWd -D0,{1xO25-XrX!e1VZXK"ؿ]eGsXwKlRPp ٽ_{-@G}:6"?n(0XƋnɇไH l,Ȫ4'2Fcd6^RTv#yղ0ͨ,S˲0W4:4c$2]M4w~^2--ݸ[VKvx= YڒS7UJ9J1//=<5q K(/fE-{V*Or9mIG+aBQ&UvYmyb`ޅ磥z}]RkNƷ,"~=_hDqfjc }ƆC~ aC$??*+G6 6}?nUI'QX,}7r{jd_2VQ唍fgS3l0":z|a{`Eu9wհ<֯fET!\)^ qR@JF9dPṚA}} :LTCIqdlt9S{񔒉5YBj\ʫ??'4\ ^^Y2oonPџ-셅}dD\FڒLKj#] ?0EӥmM!4)5jLgb~9=F<L &??G??B8g:8hڷAڇ1h%2+xsH[P(VKD??q!Xb@UcqXBatPĉn,rD$yBl'l0POPz]J [1z'Nch2%jG\hy?0;Q5tՑEce;@&!:>Ž#,D! գ^I|͓?nО5}l> *r| @ȝ@݅($S%<")<>DXQ:??cC(p}KS?nwvcv9=(sŶs?r\4jb~1cU2ͼBKc٘>h,p?nx>*B -p.4=s6QD]}>?rσꕧM麀}7q[YK*7N¬0q.͠+;.F{zTn+IJԥzD>< CA`NP?r'ͯNqi=]kgtMWaX6a;g;C+qiq#[?0 'I6" ?rPoMRw%oNJ>gj!?0At.HmC ?0ق7_JB![?06g?r8.xYpJ05vGcT0n5'r<|H |m@e8xI( G&1Չ-lEW,7UcюTR^>%@.!Hߠa.hv׽9>;>{*'N?n8x] dF v?0H*Խ1ޅGnP r_jC:d~ĸ^J\gE^?r?0$fx7Ai4鱨H;LlǏ??W_ M$R??~Ӡ)~>?n3M\vv,f"'v=@F?n?0'9o$0O($7]`ml K?nۙ7K܀J[G81GB[?nkYp7yRh-<ᇹ$?0o`N\<~]|3pE./>4?n"nӅRI?nC ?n?0x#B#mh?0*ԝ'p Qp+ r8kDʇJ?nnu(;*gy\pg B/dgb,v7x%irX бKS1 ჱyR-TuF_ckћߗhU??m~MçSZC0 B#K{ؒ?rlbi?nu0X_НM??;_3 I Ufˏg>v tL"_?0 5ߍ=4џdI,wG~̱7eWӾ旑f"?0鳳v*32"223/2Ho+2FMͬGC(AS%?r?0h}f"h'bW :MXFqGŲ*l/Jpmk_ъ]HJREXK }CC:뢵L7Q|n{cY?r(w7)!;{>]p[ )6{++0AOH9}nnGEndkCRie o??az1qZ#~RW4Ы?0}keXwͳ?0~9IV쮟nY˺Yum@va0Ugc. `|M޿_QW-Cb|?0Sn>,M 3DIWy{ R$>HnEb2#9 sY j_jempنftAJO?n}Vnl:6܆jp%Э3i, Y-f?n <Oi'Ue`߾Nf~x?0< k:??Gьm(8??'p0&KU84%NyE;,~c`f>Q/ǿW|6BnU-lu??yq?0{9xy&\)K9>5<*{+FV2.W0<]y6܊`LAW=??նZMy'P76O2 hp$w7n(|Dη''z_D f}*2Uc_G7_{sI0)ST*K侧f"ZTIJ2_'R{4qOW+oh/$./"ZQD75qZ慏z7:.ҒHU9G&xo W'IVyAROP>1t's_/~L`ĸgWAwGG`O_~+^DUn nR,{֝)x%kKe?nT*XM(Q+?rv2R!Z'RhS+tSZEWIr:idIA.H']kᜪm`6 h rUaka*\;7JRp8),SK4>߿*Bk??.Uz`"".q0/T~p6Z|="V28lZ?n%i]CGeɒkBV%b9YK޽W?0eЅYNYe^{9U?0$SOPjdǮ'PZj2f LSIy?r%m]qF$fy6?ncɂX*ɶ;IM౉WM= igxf$K}y58ǩ΋2!nK08:* SpO??\ȵ<<G4֮ =P(XѼy`o>q,8*~SBZLi6XsGO\huq?? Õ^R+0U??mEN$^Y,:z$??UE{q_?0_FwIȦ-e! Qu;OԎ!.)$j,3zyj5|{h=tm:iGzQkmP?0Q7\ꞛ@IQ]$ʞ[e??8zaavq!j`6)ptWN>ӧA'ˤE%jaaNp##2H=DBl4rKʡ,n[nY}!7b#)y"/)Bv2uo~zUpv7!gXlѿ_״'7n??|MU:DOΤMw{^meLTY_l'VH9FuA&$R'?n< :R 7-ja8WCn=#2?? jh ??yC7HlPKaF1a`8jJkXI^'B_ʫlQ??'1ƲH?n-.OrFۿUU캏\zwAt}vɩ|!nKwp2s@ؓ0 G?nݝ?rIHܦ= (yɵW!e o8j??]7JXTj$)Hn#/t9q M{D'ZNt`ueZwFzKw^1/%7L)?0ѸM+ג*rC,pVq$WԚ)+> :Tǥ0nb!ShNLp1 !ַ<Μǩ#LAbÿ[(#ñ5.?neC"*{VylK[nV5h95w$F+agPb4*}輥AX@k.[Rq2Jﻫ"@hOoPe `?0~ Z,yϵ ۷ Jy8BtyX{xh RYAv$LY&āH,[ԢxFa9T_#-Niiy1mlptlU̒ ns8mkCVmV{f4֏a$m `%aAUsx[Vj,QE8I)|GF?0UOH?r_k-B IT, T_" ;zUJ^9ﶪ̸ cDVmc.+"??OPYؓpWչ?r-5?nqc Moa^kZrߧɝáѽS IjȆ4m5E&vw<[0f++S'6*=LN(g\WR9dX]u_H*֣.Lfq0͸rJⵋ`m\iPp--޶DUaǻquFਣˈuyve??0#wVrGv6Q74T&כU't|2:C8gm!#7f}fv3G%'֧?nE({TCnVYӣ|qXÙ?0q{fev-/#cL>!&N??N>y_&_EHIE,fz]V z*CC!,Es??i*ޤ5(/{ZiƮ5܌oQ$`r;wS??JSFpu>j_bU}*uҋRz}4Wf BDh* G c]tEG֟_]hdVkp6l>J!#6m[pZ[0=jwݯ~yW9E]zTt*TZ喾fc{_\njL {㒾/tR:Ps݋лKFrtj5WỚiƒ`zw?n[.Oߘ{KM?njA-5Lw `p?0 _=#(] f$,}6lU(MtPQR}ejnlɬNduRDU&(Tj. jrV??ưR\#W#@E<ŸDD>F:Hfn?nc/͸6wDm:79ӢG?rAS//?rq#._p;hevLAă **k6"B6d_?rufzoQ UC;=Am囧c5?nu+=Ճ?nnzex?n=>ȋn ZXi Lύ u~^}̃{R$՜A,Y o!B|P]9)=;oٍ=q9>=;#?0۝<0<zmG7M*sTJvYo.&͢fJDY}X2! hi$XqջO&VlFQ?09ȤdNW)"N|v{%:peft򗛤@6?0ͧ̍*G?0kwj˶Us@Ũ!!`tĨ݌N[⡯;K]A}YK:"ZyFO"}"ఠ.x'`ˁSUz|a*a+>F0YؙvujϘNE|рid7ͽݑ봬u.x?r|42_,1pUACq9B,5`x\ӊKAG)pdHh<^dFđEiNђ% ֺ2f3XBo](DQYU+r> {?nVZZMJaRYn/ њ_Ԓ7`<^%ΒGK8R8H42Fzn4??׋itQ8/N.w~𝎬S=\n|&r7??>}/_|Ǎk7??6>ހ^`hS.lR;??@;epeZuBBvk^49^L0 Ȼ!#%ᣞyYΰrkSakg4Q'S!ts1OߎK<1Ee]U)^amS}_bf:\uQxG?nLTL75Ci>[}/J?0D7?0Oj)?r-ٳOx J\6,'{dcSav?rI/et7R ӎt_[D-nr?nC.-_uYw];:}kdI*_EAzӰ3W1'jgRE^,n?r#~V.2oGw0!={x?n8<.W*ۡ+6ueV'\%jЛ+f89È=L콪Zg QS_u$R:/L#KPҠM= qc r9/;?0p6L +&xz.6}"(`&SirMlŸ7DmB;; Q^1:>ԟ#/=lI~Z5??DQʃ@IUAsZI3_:s]~t"ki9- rܨ)Ewc|?n(6yY¸]>C$s/Kk7znSMr'K. =I?n(o5MD>Ĺ5Dl/3g! R5NO;ҭOVϮR҃"I&(Κ%yL?0m??n}1Dݾyɱ\=[Gm۶h%t?ngLz#c__DED!hv ?ns$'KuUZ&NyFU:92-l'owW EUW^BG*)Ht7G_UXf_I/+>(ov\f1ki?nCEXf5-P~f\bFWr&v{rAaeU{<{wwe#_XwI5 _Rh׀r; 0QqE rV>tWFh޶\DݼQL_~=o]95~y`X@"N<0uX`{yӨ8чb3(v_ӷBL -_)`v=)r|V)wQ$625.Šf Ý=6?0s?0#=0@|m*??wwk0<}xq; Ǽ??EoOBbk?rZ U)Ͽ{o9y8T3gˆsA@G%#޷`V\x*?rNK W-˵7Uy`?n<'Tݐ:^s$󣃽KnmbR%+ºRqEZ eL{czcC?r^{Ca蠳(MwwbNiԸ&?rYTxlD)N}%pF(2>aUu?nVeJ5jC%kgu/Z= C&nvKvOn)PpolpҰ aQ&DFRb#2ZUhhG/_̐#'jxFs5BϠ#2KS__ren@Py)3{,BT.6ڂ^'oɲ\S >#/}OETͰdJ+{,G6,P5x̑f% n +'4~fX[6fCIoG{˯I[ƽdY"0QK:Vg纽:0OX6ꚶy6y<|n;m]tV -T7@@1}qx=[ݿb=~6::' V-Xűzϊ;*|fb ~|Q=K-T})o}}'R8;Iأxш4VbNc}-E/wp8C/=c'/l绵⎪3@$BcN׹w(y=U7{\Nˇ+գ&wz R񿇪JToKXS&{nY6_??|6YlG!MA R =ב?0M(CfjH??H_P}ӏ߼8/Og??xٛ(wg?n?r6K~q>u2~ze"Տ + &ڠZ)O,j!њ !uO§* @S]yykzH 9Hv_us~ʍ͖D[e-ovyx;(eaV\Gs??ÿ9)ʜ1w Yo2UAֿˬ_unaTɜ[_׹??A#`+c"\s[PĦп5~eS;؄o?rN)Soj'^~f8\BNu?rg;m~av\<&oNp?r aiDjqy5(68z{}JËS~X)?r].TZ_L߾~7!и]|MCԻޝeWL2NGMfkN<\a﶑}ݍ8Լ.~-ꯔ'Jk/H|K'+؇T?r]mdmOř߰7t=c_zyjGFʄ?n%(n}^oSxV${3 ?r15po> xE"6@z4ŸxlG!v!U~r"[OኼDMKW_9g&SCwK;|Gr=G2("'Q Ukjěw;/"_U[t„6LEidX[]H]T^.j\ ZXo~avy$6,ǣS??be+)$e.mVF +#w6NNtF??o7EUՒ[ EMN]UNcueB/PØ?0q|k xfD-݇=|?nDQI͵BVs-9KSkͥZd$9 mnI32dm͈TK.<epI%'ۤNQ("t͢f;3rULT(I0F:n4pP2<:ݡvi=M0HFf[*z.}hMN݈*t{"Yt2Pp$`v/z.nw֥«`ۯȘ?rpc+nI kHWp:@Xtj[\pH^ 9 -J0V"??`$qJ>?nz㮦u'+&LLFzapKhH?rCA@Qst}=jqd藭U!>f26[cՊK_]V {[/Ѱf@zAfZP–d[Il6ow{Ul(|ŷ/<ilx?0Ru8ҵa-5 _+fG{a1ue!&A?n:?rYj0[L??e㤿l-0?nIz]f =k'-h}"EM:LŶJ罷(%RIlG0 h!E׸`9eD9%X}$Ebw{8\f{g Fz!)p'Exi^wy\Oe UycJ_%P8J3yX^t\S`:Q^ߟV ?n.(fF&_*Cu׻_&18s_iAXkjjk[?r,*]v72JWpS?r2aO~TYCxZ>O 'gKEbGyUȦ zage/Mc>ᓗ#rkd+z[Yy|*zWzV9&w@ofyֻY|NTj {R襬oUB|Sf-PD!ʤAXҊnimU]"<(V0GW4P+ S ="ffKώwL_"(|KW&U0J #P~rd %Y?rP_Y]".iSc4EǥxExE?rJ7К?r~ѽyJ]6ͧA:.'fHb ֪u=&+ވ҇V{[nMS?n;Z_uLrrP 5KКz=sEz+!=N&{O_.]Z2!-X$[[Ikxx6T禟=RL1)&@qVjwIJ?0uTAcnYJ汎j ]8!84q^{@O6?rY|mUYLJeȩȟ;! fli5dž?0Iښ\{WL3eSwp*wrwPC~xQAzp1; Ky[]%ހ8{+(̆x9س)YnvO]\GbT^J8-pͣs|vňOm?ndž3&>?nyb?0(:e`ը?rl Sopڀ*Z0P>jxY;~TOb|??K(=lgn t:"1x?0|?0k]C($_:}vR$5.gB{EMXAA?rqE=_'׶u[!??~sL<(ḁ"VCUZ oSuDo_CX~[[YBǛԑQA!:+qRS|c7A!q (84 ⵀˤ2 1z3@6"G=[ДTAtwOh+ +;D{?r2Oskcm4j{eZr& ?0ߦ1Th3X𤤒bV5??+3??=??!ޥF`¯,ϐ|tۢᨥ`ބz [:fs물Tx˚n3".WQ,ZtU }*)SJ6p\۪KltwGGó{l ?0@ ^2Vާ ͽW_ބ&4gxF_TLΖ~-?0cG7~*G&!l'Ɩ[Iqlln?0YD<[)补8Yտ_YSeMsӧAUfi>Q~@eQeIƴJ5ʉTGYM|,ڌK#F\7Ǘ hהß=bz.*k`!22{wn& +#?r)߲:,cb#w\f/:5K^H3mZJL&r/g^6Vx7$.NoY[VhQ28݇Ij?0_??Ot+dRNr+{D,ѝF˕2!\5]..!hgoMyیE7otS1Mus42ZEu]̕+KXJ.P^Ӕ5YJTdRڕE0lH/M3Itގs29~5XX\*-[U_Uae2tPl nZhnK6GK.7W`) KEpWUТR!yLER??sl5܏~x~&$;?rCEBUpZX)kh "<`FdOkd9-Kk1M?0n{AOw ,EF?r~$f*Ҽw>?nCyȅzKf%f0jCK Xhf!IIa(\jllb0pcr#P6Ja^\4qTK3V`3:Zf(,>,:??†I7??=??bB)68t`)3J)Јxlͅ:\o،2ЙCFcy;{[g/#}ڵ*&#sDwH 屆W26/g4>tg&WLJTg-?0 N (,a܇U?n館R@3YʹH:t%siZw 8’QvIz9 m ˡjSkKW*%;+eTP>iDfrJ@mQGض^^Sj4PDԨ;a;9Wi*5>AG?00tzK]n-QH3-3V\n-xK5}%E< Km=QNf86?0NvC:M32u \`Y#;r7_"ޮ>?n:ru"8 rLN5Aқ?r"d/kKS` bJm3|oY?r[2`LJsbW`zp1۔9JYobnM GfTi=d[ p(r5\Pnt|s˅cBbDKܳrR86H4"ȈA=Q;fs.sڅ ]/?ru3GlbyYRuX8/&(D#Lf;9G2Eeg-g<Mv"F_~*>-∵C+AdC\U~ʓĈ*` `<y/yd9—vbOshC 2[ָy@$hft+ H)kܠʽk6C9nV+/}LbUWuNs!*;U3FٺsVicB@pFV\fXhRbn$f"woR=_,l7xy;_tfG?nR"9xËK?n u3})?rc3Nh,*wКl&sm8"QBW̿C&4! T??y^F%~T¾s(r1)<"i^m}ˌ"8Pv}?r*7Xr$~%0%?nHvZF8`J)P9??|N$EEy:gy(^ (`O!?rO7Gwi$iv=|瑻]4_. ˯Pt4kU.w=自?n TQzU 4l EIԴFa T!)jQlЉa'w.Byv xyзDٶfEx/ZCXP)rUruUrK tZad=$68̯xJl1q(KER?rVGROz=i\{7 hv;;Ұ3?rį&7QuT"؆x!>Ma"԰\""n?r1.[/$P¹j*7E 1?nMa0Hj'e ٌ7:_>;!CWř_Wֿ#lS1ߴ$o߶ejNߡY_lHpT>affbTk8jםῖaGo1J%t y[Icw`.[ė^tiG>ńMsI/[7w҄-u60f3!t|0E[Ntu[!2b(dxgPqBoYӈ!w݇NߨC?r_rlXvdw+?0c)ݗ,u+d1yu'j@JJL>R`cnQeȎ\j)?r(!yD~sĻb@sfb0f3hrIQz"9qMxHʝ#RZgl1􁡿4o?rar{q1Y'>-NI'P:_"2'|??n8c?n HePmX/#^ܔ׿&q@C"اsQIQ(UFlO>EBxM%nJJ;q) nQ\뫖&ZZ)B|a-h6%)xD^w̺&W,g٥e28ƨk0u@ZDzi'q@hYk鳣{W䇿/[a+զ׽>BWB=??l%xm?0>cyDf>giTR*OP0Isbu_'iC,Iƛ)S:h-oZr4DFyoozmo+@?0eR)YzfȪ ϋDP0}@ $?r{'_9+ OZ͊~i~ᢶ޲ $JEf,e_'qS쫳"itӭ'??~>ij~Zz\v?0apScqԔ&#Ge3!H~ FUmu*d7pA+uDLm-7=]D>.xc?0??>bdw?08i©Cg??msXK#u~{Y;v6@v}х}C* G(-4H2??$a(GdK2dZEHnF$u)e[[RNjo&˖֞kkiFWM79dZ@QrCFL$n??}_'D:ǏՅ֗-ڀsLu5.5/5 b_r0ۯi{BI3Y%^mN,r’# sk)|fs+HBhPp?nVQ~kZ+K?nIvߟ9zr|ct˿IKһ}D *qm&YOݶq(ǐJ*3o<Szv??N!yI(=(.:õ,ޫ'&JL?naRUnX|G& brQ(O^@^<?nSR8<,(7"Lk_{/_}ÀZRvXf6F^\=}ɋ@3q4(H#8L84yj_9:~fW?0̩o%b?05$Gh|j|?0TTZOۙXӹio{R"+PZ=c̩ RBU6)m*:H]Rs&+?rMZѺ\(]K"VvZrmu%4]@Fv5)T~?r9 8?0;*ǥ/PWO]W4&LLp_0R%pj4p1@g=/*#h҈E֧';**ተΠ?0.00IpA?rg̅g@(͍AF9Y$ q6Ќ)Ⴅn?r5/ya1!Vsbה9$ishh~{rgG]`??MKU6V𽜁jQyͣ 1?0@bR4f&KqZ 3rGV}Mv*ߍ&4T&!:3\W#|$CoIegVm}izH42?0h8Dudn!%=cb₸0*>??^}Wt__VḪ~7O_'?rO^??~??ysB)唴qq~؝ yx{AtGT$ O@IQ]i9]/^D^ɼwE߽Z}u`.C}z߃+ܮ&ld'`{*{(}p;5^^̦ZO0Q -Qϳ1HFKj?? !#0.?0RT}\[2iX=Fc2>~%J7[ |zN\mv[ɭXc]pF~??D\o/'0-5. AT}k)O% $*8%Ǣ(w}M/)c*Z[δHfj)5A%,OxZ"J359Ï&W#z,EYjtP3ËJ??Q<)J)ofWQvmh;tL cO4wZ`8yb=#RC|aTOfd5Ƴ="蓺O??M SDl9?nMjθj⌠}~TU~1$GW~rw9+%W"|F&jQk-??R_lݔcqʊ!S7&% 0&g b9B~IEHݩݕ7\)ZDx?r{񰤐E*ED_K)B[\?nA5CY0KN8ĺ\[| {d(@bh~xû_>pgx>v?rR( >KgT49'WצcTvyVwrGȼ#v%!{_J!{.H$\NVN}={KGKRuе2~xRWqY[%;^zg2P{ (Ǟ9?rAul{GW#儕?rJog!|Q??zFSuB+TT:s8ڎG£Z7$43! ˽+'FpZ$-ΟWsOEOqI9E)~My:7y/|CsV xG~F'hF,7APPT(d+AIpW\w_ Ɣk}Aܦ2_ %|YAڽ|ͧV5-~N;g#S4-Iۙh,UK 9(.iJS1_̭qQ~LwW[ 6eL=UOz\cE2{;W|zxt5[[֩JR*t5(L4P?06G7}|B7N^wqt(~i8?n,Ȕϙ&<_ctqIL&9M4-:e޼| *‡?rdo?n8BeMH-> l^xk=W10t.E9Ŷ tD``&S6==ţ(cPe 5J?nQM'ӭh8[ЊOӑ??B]t,g!xcSOl.jDA*Haйp/F4@WR͂^@ X 8IVƀo# ˘^nzmRVnmv`/-P>MQg?rvcT;|;Ԁm?r?r>Xx5R1DXsF<]X$BLtsc-Fn.#{PQM|)w`pFKhVCV*BQw;96l7{s.h+2EӖXMU%\\)*HI1lW9"÷iq&RG:GW?nJH؟z2Ζߜpg0Qjmw^⁷mXb`*1àⅵ~s:o_<ōu{}2`N{'ïI6??yV$mQt"aɋW/OHBў`(79b2VLպ'8&dzLt9\hTxSJs?rO<XK"niw]3y~){ۡ}@twC_&NP=B݄iV 1(@ kxI,x&`A4݄ɩ(rH'0N: M0!xBN.Z~rҠ~xq!Kj2 W6*u\9ɷqgM67{Ͽ~o:[{e`}3<8+w&V+śmlsqHrʄ^"}?nwg_8| [rϫ)=3 rT3ȻgKt Nz0?0t<pV/|j"Qnk5a=D#!,ٻ*S#ǦecbOA.aކeː0>#`w!GynڡZ7L C0y[mu#.>+X]jC O:pRǁ[Ƕ9ިǂ}:1}ʌخE+gS5,֟].eBJpY6SȖZVY??s9CoUo1heɔJ^/ߪ{Ip'WA«9_z؄^i-h0H60- JzHgg肤(4̛I6ܫRv„+8j|ʬ:4+)?n60N-J J4r-??%8E ZBD@?0ml\C^@أ~[y??RT]5yוPl`"a1?rDi$b3cKql9/[(@}NLg)pHj/6%D>ϥC ft2HXN9 'u'.yΌnn[XO4i]*W $2'_U?nX4ioIaR6COS*Kߌn#Q-$PZ*݄?nߦ)]oq~GCÁ#װ2lHjRw#<fʹ?rSJ2ASB__jҊ"B} Y\E6a'3KttӤvٺW[PʩB$k/=D- ]RF4'DrUx:-$$n5e}6LL 08Ug9sL ,zl($<ږZFԊw IHz-dQv`atABqOE4a2<ީB*?0C[eFzXa1, "8$C*O~NQim{P3N Uʊ0Ji:(zg~%T`c}H(?nFY)*o]Ct Զ_d)(<v?nP/o3&g/1Jy(KWa(QtU[VQI7e>c0?r_r5fvP\kdnߎ膑1d$??M[O%??S>xax?02AnǙ]&5V@ *uٛk(G06:Gpu*=||Y+0~qUǂS ش^'%<>??*QBxXTp(0'j< f2"ɖTS_;MN7ŝd#ȆR#zPB3/yvUʶN$bVT"S`?r6V>?n;iP 9W 3Y;,KAdr +#l:j2(,[1q0۸^[ v3TYʵh&YL#mkD akЬV|R1'`SQA?r üyS`e{&jMw$uxe9"#rf/cTI#9d+h3nn7 Fy9OV@=cOhO{8.~I_U޲tj6bA??yCwm/w1ػQZ㒡1YІa~-Ɵٍ7oyˤ׍3>f,Е#YH?06?nT (xZf :It&OI ?n#R.nbv~ѶF"@Hdy Y??`j%\R`?r[WP{a]{9*U~_1}5lCrX$=ZcsY,0LxܰGl7^K??uI3Od3î"sJ'ǔ?? U=6\۪;k?n1^ms ʃ}ۉYӶݤhl%sj~.ƣeuVo!g| {vs۱ͦ?n.l$4Núr(-7J=ᆐN T?nb@:b?nJ:|+pwiAg3{Tnl )ծ[bb@͸6!%=TNcAQ'x$|FKAn6Z ;-Dq?0 8wZ|)8Ǿ 0j?r,ﰼHM52w.rN3!E0[_ܔJgIUxē`836T/}LaA5DǓj :?noxorB`?0$,?????? ƢKQYz7,,[ׯoY%#?riO;%m:a;vy ƅZ˪Gl"%"")7N9ÍI}%ϰ焪yէi69.[dX5eo{*PFx::9Ԛ|hQ•iEI??I4j={ƽUCِggΗ|:om$,Oj|L bd3W]α5k>؇XYsnB~Zs(s?nդ/VA4}69sAd=vMdfBk%mOZd~uX*<̮m$tQ_QxeV%4?0NeaHq(4WjSVRHF¤K9r3t2bHKoYs,kC#I.R١GЉ8ST._Lk`Ƃr_r2+^i܋j9 ;X_.Qcx,??&~3ǹրy4n%⎮+V8(NC^/n<8=@HE|y32?0.)n2~7prP5(pkvPD]G Wcov]0Y&ZZ'Q}`RgA{{_ܯUX^Hc[R)AP$?0Pi7=1XٹtiLA<?ry{9#eGj>Ķ,ޙXZ=0nJC|(ΐ~Q4_$nM|D?0?0bbD.Ik4rHNHc&)CWZ<&ϳĈt~6Z(L|'#䒳@`(u7~V,L ZniLWVd6I؛@BIh5V4HS-ip '(p (M;t8vE_|ax\۩rR7/CYb>$R񑷻n5; x2aQKmW\Frv\M?r?0&@Ȅ!Ft佑ZYZH1Mi#g<Alf`ꇀ,'S)Jkongt f '`|3PeXψb?rŶ9BA^X Qlm!mcA~< S/d{ZaʠX5g|"q\˙ȝ=J$_L .[՜)2튌 |Eu; 6SC2Ȯn6m*$Ç )NSN#y0*Ew@S ?nV՚1!ܥ;u)iVv0P>]?n~ Tz^ҮWge󸩍mzt@AnnŁA <6?0?n@7EHK93t3c?n_tb(m*\yŤ}ݰPz(^|6@(*Z@e1HY@vXB2%)c"icZz'P}@5 Gp辌9e=5> D:D_B"P3$P,fi@??zlVz44?n].NaE_9F]2nV_e?rޘ<{]l??PLe_˴ NJkk=l%ngZm;&05]v[,<`&*ڌziYzI4>,an1yQQҶ9Fm????eQ?06]>6=E! .{PEչ11Դ|SR?rӚoLat+=g7>]B/MrLsT +#hr[ snqd85A{*MrNFbjLS9?n~qG {[?r3ю4[l~sX*VޘF{EN(2*U"t؛YU߁k@3adNv !$;5R=UHx*C1y'0KLm߁*b'Ty33jIυ4??hu@<5MX8 Pq!:h-!_i3aCٕLz#KV2$/!ɪhbA2s{0N<ѫϮЍ ƠFzЖUvdB*SF9_H]A= Q$sRv=#Q >%$878a˗nB@r;ǴKH1f~a}Pw\uQ먲FzJt˗Cz/FW̽6ܶ?nݯzRLZ+ 3?0,dn-?n+4-[uf??I]* (y'aRXC b8 /8C r$bVҗbƤpwkLr|0]NB`9YnM4Wyvg=?n0(͓篞2??IťFm#, J!f~²Cw>ZpkR_<{_Ia·fA3bwL9`%!&dW/Sn#$bf{!˞F+]OGB5?r~ u=Ho cZQ[`P~2i^(ȝ7i;/;ir??;DSw9tL%?r?rλdXPZ4t襖m;Tx2Ƀ*Z޺*U&eV8K Ӥ_[Jb;5gFGsvnH\)55_x >=D.`壜߼iX¦׉@fk m'0 k?n.y/`[0V6fUoU&n{JRa;]NB|`}Rd,JM2!!Ey87|67ٝ@@5Y%s4C-Uu婶z-$C;?0op(rLkeFg<#/uJTo.&~v۶J-~zcObU܋wMdY4 ՟efŭ ؒ?0?n"XPw9T lviWOm>͕?0/->rwW{/) REPp]bT)CjǼ{|msSv'/^ǭ)fk~E5j'a2MN-}?0~P"9Q'xfQ**?r(1bm>`nCar%+a2tCyAS9͎#'),&I&h]Dt(f?n!P^zH{YX&$ 9K<t¡tlӢ+P"Wݦ,PBB2$UEJ*eBoE$~ؑ*bGN="b, rT@Q,!;]@Å mL %!h`5|Z xGۣa}ū  x43W2J"7*|4̘Bd<,,wSTf3ϝgg*̂ \/u::Cpy@v9tދU<\ssk Ց`oOڱU7x:LC2gspB*UlfnA$p\ڰ)1<9ű?n*kIi'8썒,&^JzrAy0H v- ~,؆7((h??&#\o`ǡznЎPj\2>^ٕZ?ni^dgYl#?r#YK&󢿌`lZ$[YFءϖ!<6,~g<\:SC VmA~yir4.ĭAOk4E)nW21yoH*??ɖxc{r b+*6!zx3d`XB; 2u5B-(BaVoQm]|U~4]6mZ &4&̪_o~r`bjpks,\5č;W]Ȋ¹?r+j??GثEyD!^GN$biMӍ2@]][y:FyH,A򞧉NДϩxx!^^h ,ET?rGaÒg|Q#nsec?nc=4)$f?n!W!@nJ=j> Ao4fV۬^UJo&&)a!v =??&mrA| T!_Ś&sv4eħC;3#Xͻ:R~' /Z?rc??M5??C聈 2tF˘ް?nΆI m=wmN}T<)rHSC tp2`JEH1=KL1Xg݁0+߯y>x?n7Mec>\bŏ 0&zyy w-{`~?ns0AVQ$\̭6'GXO\?r/s-\8,iض#zV tCȽ\f,nnmv}5kX+}dec+"t"(2nnyH`| XK}ٍ 2 10V[n5bf4("-v[-* 90ώ?nZ\ 2(?n;(ž/ELgy~7V@AV$;ؿ0gyNrۧ[OW6i/!Wla4rܼ??Y;7#wMgVd-fZԹܦ~̈́?n(j ԃzU x!heԀv??{CmxvJ_E9FL"@cHvg7^?r43c-n(ݎ2!含`7Xsކ.n=NüAwmJΗDf8d5x0%1ú`]X֊#Ɛw"Ï?rt??{ bdȎEJ(%8Rp??'1#[1kO*qnTpr+C/!+T&bS XC Pt73K?r:۾alR?rk1$ԊEJϋMPiEUԫaC{<2PL)\URBZmPE\yLVsWM_L꺑 g%>1K3'[??S[A~&Z"t]:Sm&f%~S].$^nt*؋d"h7{/to[[2C??vkf匂^މ oi Czz9:M"EGɍ`+=#·Ξ;9﯆ӟw8Ά?0mM7ǁsTtck 0lR!!Ui??ԭ*s?n(O^=!kĎ׮ѭs*:R!㞔)X^6zVf݅(??: S/un\F$@a(,?nWk޵л/{|0ϔ^л cs Ej;;,>h65=sE-LZGI\R [\;k eV~=)ܕYA\;nZ5R.j,$u?rT8K2٪eYq ?nR!8H!naYW{_бdH)բ˸_WTsJtFuSu{?0M(.{P'?0@~_5F?n?n:3$ltOhظ%渐Bn-YIAJM署f `E*I?0s2Q+*&^O^3N-'uL$'=V!uG:%bȅ}p~x*@gnnɭ^-#}IEm*a|WE.Bv Rv5&5 nZ`ͩw>v[|rP-FlYݸހR:XKO Pzh-$2sia.a諦^=?rK?? p; QF~zQ;ux[,wÕj$Hx{5O"ź9x^&hFAD.S5_U!P>a6Gq䆌Uߎ?r>F LͼyQ#/旼H"4:sBߝ!W^,=/ҙh j}EV{qlƚMz67r"@b])wOMGz?rz#]c]^_Q ; 7]|SC%>0L}SJ>H\6N +?0(v[b8n-D nOvu??,y5,eb?0ר'igh9??,G|C$QuAr&c*S:??4J?0jZaHva?0XLnbf!"dZՑ85bs9/Oy- hK7|61Y+!(XZ./Ry,q6E9;XVwմ!p}a?rnA930$o,Dy)/B$%+*??Ugv" nV+:Va~D')??@b HKiNTVɱ > lwvr+ H6|CocnPD$FZkFʷJ|F?? -l(pWNG*-()̑?0bPV{͍p-p/v@1?0;M5H՜?r??Rdr@%#[-d̢0r ?n?rX}$4)+ŋqf-%#Pp?r4ZFLS?nWR ðfSW>/}aHHMr6 8M?n????]zi=Hel,IQÜÜ*hOU#hD>1\nGx00+$TѱE?neilmOIO1M)bCtMۓ ik?r vBV(G(~nϿk/"byr|[ys* ZڂMe={lHW^ ~<]k74Ir咄k_2j[%/2o??J}שx%K!HzQR*t/AF&zv\W(N%]?nW+{Zv6Q,~+3aZ/6c = ._$bǗqNǸ[Slૼx̋W 6}w4 7!S8@wFN^̛zkgEc'GG^W??uEKI-7hDù5>?0"o],?0S]Y$Z rk~>PӡtqU;{Cu}^'SzbBiw<>?r紷;E 23qotDŽ?r/.GCyί&g@q1~8ο0|e]TB&3b[] ѝw)3g)h!1ԛc |%.ƃ7O?0 ՝gDsr5υ4ac0H.xd&NB2޳+9Ydi`*K\k(}HJesx0$I%%|1LΆEa$|Z;QxSܔV\OhȄ$fȂn*3gxr V{y: GȬ)mѝvوHI@ǂFx 83ޙ4?? >C`OULf-?0Wc_/=<+H"A9OJ0Y(a+pJ'hh|ϓVWP`|/-~&Gj^8.EqN??zL+`d=!k;_.GloUG+d9l+ac#)~yU<0rHryьF̨-}w!>Ⰿ3<UDJaawI9jym*E$,Wh3J)._.Ju#@n;-U+lB4e0`44 :R.w嬽zQ]??~w&i^8Z+_ì Gv(ۢ{-ì^VsnZF:1OV˞_V{s5Ҹ{RX#vk%[ٹke_goWP3t_5ABQf??ȏfPXn4cx޹;?r??Zdи1kʼfoV)p?r/dN/8os@P%Um޷&bc4H?rU᳻dY|O{nosṄm Jg Um'i% .°4"<mHaso^Vcrjp +#q?nWuUeuCF??qk6w %>xX&!n-1+m.)ʙ;q?nX՝(9N6/V1 Ei_S}xSrL#|lz!#\N'6ugQV ˟xpn[GEuz?r]~VktbyU C}N bY'z7L(??R.fC7cqu=-lDnzb!|Uw.wֱL?0!D #H`\B`qB۰տ9oSDt(oǦ\ќXCk84H xX}fc[y2a3_GIsMGmm|ێ$Qcٔ"GPp^&!v`7KTl/l>0_E>Ite .ݚ_y!γ?0"zi+\.VGYt|b/:3S?nPq&H}:V1 J< ͗+6n>62$nEs~qL307{-wQ+KJ5$RYK,@*UY??njs_C@ α #WwM_TR+EG{g[V:>6j4>Gtl{A.p?rsDf\r y{hr?0,P“g<D\tw:'2:eRTi1U/Z;]M ´R ৚:M#2ev=׏6BuyíY.n;{fO. ̜agc[*JRTYA?nӒ3y?0.&3\mn__?n)~k2Ez5"_p` {Ge* +,oX4-qp?no0ȋsܼdyTKt-~҄4k+%F4&A\a'B3g?rFL0LhضZem,bC?nLHۼ$-YbkyX% D?0Ÿh\y= ?n"̟{i90p3Zm3iބp"PgUb^BWl>g\يW6:zfW4IP\k<[^te+ѓb+[Wy倶rSnбWA>%xVpꡃSmr?rH S kt!WĄgci_NFۑ7L4\Y 1/{^mٹd1卅cGa=k fY:sUY}Y \bse-ŏ/kVf̙eTA8|)?n63\eF&Yo@)7]vk$=h.=.Tͳ9l T7Jඳpľon*uw" y(,Ӊf}54h{xl^Ix;3W𢽂N?nͬVc>Z#ƕ(lYeX_\ Skj!3!J Nԛ?0JW⧱N$??@?0D,) tãE?r}|H[O(+hţZ~m-耚Of0\Rb,'P3[@R2IN ?n2Iőb~oW1,K.?0{J稤;XgP+ʓ0lvܵp#AЌR?ng#[R-?nl=Cg3p~a6`3T#Ҟ*P B4)ml߅Wؚ!C/C&h%켦S#NFFԉ*hns-I.s0 8|i*+{ j#MPEc sRbF0YD?rLBo`>}:35y4??ܙ}A~{ϟog[[[6H$Eѫn6AV}azڛ&??臫~+srd֩/;kR3M80#}aWf"~tq=85إQ6)Beo]?0MjћWNӒv*zg-I $fgG9n6mZ7a>f;O^P 7_ 7oWRX<|b4mnn|mNu~Szut??;,qmvWߵq':]G*ch,pT"]:'0]=ӃWFf(t0׸Hu'dx2Kq-NEAV6w03f9ߟ':hw$b{ًd1}?r2m{񰍟l +#iF2?n-w*c()ĦH?rkjj4P>&e^N6ϘIrvÓ{^ڥƵfb76bqa!L1?n6PƇ9 «ܷ P8ϯv΅qY/3S7ї]eKf7\4xs7O3Z 8@??10KЌa#F'X^rc?n<[gN`Gͦtu_ ȲKOUo|r%NKkP& ?n{YԢ#V?0,EgYKn>3Q+00BQnX]?n.mpx+JLWWQc??~ެa+<1*]3>o>9lF}91O|C٨ḟV530_eDT?n}c??ŪߕXMN??%d:Kۤ7O`=R[jx~]r=%뉺+Tf=ҨQzFQbf*[ctIKԼM_c=]iI'm>zY:TnMs0A˖`=fS֝RVwqVraV>`+G/m-"!=덯F{Ym{M_NKac@~gkk8:V`/dIrPԃOj bՋ{j.RRc)M?r؞[Mn>??VZGP)c I+ǛlĢzq^eM?nEa0B*q+-Pф6+Kَm.t?0^$ (&*21Jso=+¢2Z,!,Trx04\2QMIQ3]~xjZ'&otw7ʕEkP6"1k!G*((+\?0|8Mp#Fԣȵ^C`t 4{.U9 A|????zy/I[|qoWhOO7{??9|׊Cb5M `g&=:w^D6mq]}Y2:W4}nhymsԎM`4zhp0*.3Ml?n4&*EY#Zwr˔`_ӻ%sSp1{'ɘ?nryU0;ަU~26p*ܥ55߮q`?0iWm 1v:-ܻ4??ysKrC9|`>0LӃWqgK.=aܺ@QAIr5, :5-OSnb4FgC x"IN.W#}rSOvm?nF@3e alKP <=\Y&jB?n{`wwF3dTD-/dSqtwof-IC)uu lWGVѳğ>:d٭/:f *@%]F} (CNL"UZB%#HnGɔ[Q.Nc9nGHY2" SWvFNͶauS+8o$ ?0@a_jv'\~M*}X,ec-g~F);ƓY&WQXwL ψUĻRH80I?0"(gPbR1A\WTɈAz8g;?01O{1995׷}FW;1 $KB4tcO87<3^Z_hIrH'w%Bf)>+95hMs]&A/??1cYw'Wjh\!KQ%SN"/s=;`:>c(|0Fv1x؍˔&:LI??I& *MZBA!24:ג7tO5fdQGXڼ669]gr{nd.Q[哑?nA`2x%dLP~u{?r[( 9ꔯ\&ԛLYVSl-2,]2l(\CUuQΑvÙW*o%_??IwU0L*bSz'Z1k3+?nEdx=2xAp){J ~f,#pH".B$WѼn-g?rfm\\UKpl,ˡMd- K0.iT[fwUWdsiN4?0Ch҇zP1Q7*B`41e`٭T?ntU41>iG̿(ֽmrgĮȅ`We0oZOݺ6[}H%W1kYF /Wn7'݄,3Z9I..bk4#_)>$ uJl܎_ȃ1FPm4SkioȣJ, kE~#{ϱ%<x[8zsAptbg̝+'?? g??$L)RTⴧr$M٨xeg;6g͹BY\jo2tB',+·y17V(yK[i+ "V[˶εHYM F{J>|!i*$?rzhf^ʉfЯbH)xTkjYu!Kubleoۮ,~c??;Յ\n={LmdQwK d ?0@?r4?n=Bv>??s}v$]} eb1J5f$#%a8)u*ZݶE"}|6XV]<?n?06؉V ~ u/h{nYkWF׏r_7m??/~}[gJE!XgT¥0fG\2%+??${ji0&y3v.c*`,*Z)H^g 3) 6??TΥ lMX~1]d5Qڲ#?r2w5$4WSkb?n܋VsR-`9RYԡ`>;Hѓg 2ţh!'UDCJ=OU-???rg1m(=k3w~G ?0$V_78D_w+ф"jիvNj4N7;n4aw@fo]o:/»(0*3ngi28$/8UM>c{FxeCSYQNԐPN|8zjifO7_lGg,ur1[ÑwbӪێ,1v?r>t7wPÊ,3f(iedK-ZL&&ŧ=A2a?0)g)IQL!C¹E>AX֖CcL7)7+.W>]x1t4 3m<??7Ό`gy $K"x(:xEyllFyMnOd:e;Iڏ.qt[3:$W?nJazRJIAHGsJkv::$aչxf<l&8D(T5EH%[?nIak1ݪfgU>7?00kخ/Y{:wab)8liƲ?r-˦F^P്,5JkXz#k|oޞ6d[e 1f?r֢{)ilʷq,n&ɇ5I*q:U+7ubλL&4Y̵#'ueT(Ϣs!T6`A(&m&Y+Q7(fIͻafmx.~lAhA`MØLGJǚ/m9۶q3><;6+r83"K|Lwްb]Ɯ˘W??b=g9Σ.^H=Z,Jfn:<(G\|_Y"XV.b6?rN v}Yfq7;X¸??,A0~䍙qZ]y1?0c2N Z=ԧ{0r<玲U< #H( [>ԨeiМv¨|lq= @H{??#WpE3!<`j-NtfӐ,ӧ*t\,ϋD=;AZdƊ܀?nՆK*Pa)~n3??r0Au)Zj^X0Y6CBPV.?0]˅KPRjh?rUve7fïb; [WE&%MuCO;6gdS1>^~2chTc)]5QF$'miMGykYv ԲBl8V 9?r Nn/So--D%h-)ԢB4IqoRjDѢODrށo~Y??Km~ vϿ_:3ndtr+c8Q(|?rzYH>eF2PPyga6Uo@)45mK\f|,^OoL-uzA_o{3|ǀ濶;P9-_'~mn'y79{WamtmƮ??5{/Au6!++ [J|fQ׫e~+PõiFLOȽ dގ.R!#ke;f4n^y?nEy  l;u6)K`?0GL5@AXrURp?nWGIcX 84B}ȷٙU%pQHG(4oھl]1,ƭT&h?r }ڡIQi?0?ndӳ->+@mLVELC0ʀL?n5Ⱦ|?nZB~"U*$qܹne%0TASoVcce?0lL01g?0d"znཐDbpR@(X{"M4O#j&fxijJcG7ĺR4)l ӄ gs?0!34{SN)e"1T&ǻ#,|fLjM+K".Q??&ϔ#Ů7ׂt{5QNh06yFL-)kyyI9}{;ҜߘjrAmJNS?roԫ?n?0ٓK(a dْ[<٩?nyѴI?0L$??>oz8mϮ0p@G>yff,e`(m}<"IGh~I֎bZ;(["skWD$2H%?rKƄj??8???n*Y"- #*)灅{Aq'#/cHDl??2]c'4>?0B?n\nn&wbO 曦[ק?0&ᅄ@éq:k0kǠj6YL_of?0PJJ`-4N ,> 'vgHYE*)???rd.:?n&\(*kb??Bg< 7;bye۪q1گ+h4Q.99{O'<ӆxņ)/[}%kq&ko1$\b*Yzu*Ѹe{Q{)nf925&i1 Ϲ??a?nݹaҏ>}&p[G)CVirx_͚!"c7gR9L,5@vA+1Ƿ"WT\jv[\Ôg?rAVQy6;hص&zy.x??uazr#-k^]Yܖ0V ƴQ%^|߬q?rEH{vs~eʈALUU_qp;/5I6QUbӞS>3cjV>jM!2cV,Z!op a:&i~ ME%lQv[g3c ^h; +#!)6wǽM|*ppm71mIO<xO?nV|5cr_V3]>Lnۊc|bG|֕5gM(ܷrzf4x~bW^b-1rA7V;GAmoC߭-n!F0BPB'u??8N,ʉqҹo\ZT~(νu YyDJ׻!%`j E免}XU^R>E-G C%pt?0eyb*n&3\ 맣tV#3@;Z~#W_1 He$i'[4?0ϒa_# L#ip?0$ЏM4H{F=lu6~s?nI?0e3 I?rgj#ωEfd;}Pr ;QzU%Қ4osYt]VL%Gg"^L'"fpVAoNYTMG# z4?0cT?06a1o%]{a,Tn0dfga[I_zz!b?0Jǽ{d)Co.):<%<[m:?0d$ё ٧{@2º?rh"^f5\Iz5$i:=|?0~-gTvrp HlGZ6OhZª-4N3v/sZ'֪Ooj0m޶+hg5B֮HUXbIj-Ё?0홋V13%6,Ζ?njd(8=?r*hyhldbq'wً(0%*h;~H3@n/H%|)_N?0p'7u@$Z3cnkt@F5+yXJ-A0iNf;R|Ѽ?0mLl韣@?? H[!T0chbޮ<ʺ2fZޟOz\)8J%2༷P&K&$.;tΠuBi!jB˾?r*l*V0R)%>ա=nS'a/gCd6X[ۿ,C%ZpvmQ ,/f'+oDSnۛI``SzEm?r?r t1< =]tFC?n֩Qhv IpN]?rM @??q;E?n=kAeH& ] 7Jr}@^,~ [?n/e/iuazJO%;X9Mh9j0:H0GDI2Y95Et7 *,0$z"# #0\|mD5Zv3SJlaAQk$%詿!iiny,eyA,hlY6- qu'ҺQ. ]3G-**¢C#_(llVea%S8duKl`O>1+ON]֌Sdk'=UK/×ӓ"2e=?0aΥu+IA??/gD]B(]{T볬ZLUtKȢhUo>>6Y#&P3k= 5L()Σ>$cm#֗t*0xnRcKolzh%c8RMe%ʑdS),bEi5o^ZkV;zڕkgJwjrmTW muIHDqǦϐvw5=%VULdlw9xY~5?0:%u?ryg??f"J-3 ſ-a=.9ߍRБמ\_;h7??[٥[&j: \cN??&ш^$kq.FC38D.6ϐjbk"ܨqxXp}]1No 5'LlSVU-55)3ދ^j??F[x=$+_?rZIk R1x)oHt%% {ڑGWc?0[A4_jN.L[n}atZj!jdt[wo ?0漨[ggVĬښTF??[$뇊[M$wd47#YʵE˼r/ %wFDRM(ҁ[4K?n ??JUĕ^xac[Zr!Rm%`筦uID@'QDt]A*xSvi;=&U?rI.TVA-%UT{;" Me!g]t6f6|_mm[Զ,FlTw}A毾;+Ťy˷lֻ+ofج%* #}s.1 sSf?n&r/9hm<[=-SsZ&9z]?0IJg΋2iC]+} ߼waWy#m-}KKHJyDV|mI'{T7dqKI@4uHx9??u}f lt198?0L~n|2;r/ePsE4/^eK,7)¹,r㔩; Lʗ&xr\~ԝQFw?n??6vei,caU?09SXٸ_ as-bWy]K8?0?r77FCC?nI:K2&=C0{& jh}FA|)P<+'aa5/X6jIh24MgOig<$ocO]GˬKMw8Q.thKm?r l"ß?rA\Mjk~QO`޽1f+ʂ<eמ,bUg2K٢&=rEmR/ś`k6 {^nᏞpXbVYYB/B }ixFvO}>6Sh@˒xŒeE`YH܏HܶL)G7lXR4K6 01:꩏??iQ[<d`p5AzOVKP|@A*?r!zb?rI;rOc2?n9>):k qxfYl /,~f> 4=?nؽi'cEa>[eWUo̙Ymkkn0)6l?n?0z?rX52Nx##t21ȟu^*Yomc^??uݢdj=+r: +#8OW+ 9`Wm>L[x*EC6'`6;ir@&vr2.~tHIq\A<`mk+u+x>5>4wLS#C%|𧘔xA?0\?ne7iYlkGM-JFi+H,;N졈~yY`Vwb]ܙ~ɦG1RB:kR3BŀtTX@FL{'=ddQ?n-yy;eU Z6Mihrao]?r/UcVL[1u.`Ax9ew9=sֶm9ՁG1Yrp??pLjϘ.§p 46?rSlt! >??toOإߺ.%{w,~IJ`MBn[┋~–mϢd<{s#,p 19ˆ4WP3EY4Ù#ӅnngD^uJUS0nv>\I?rEA+pxq@i 13XixzL<818f:5՗0EW]-C.#J$C'8Eٳg筪{ʒ@5ma鉆皒7Ϭ&3y`.}X)ѭbG5Dq!fdi^p乨wơj>TA2XٔI6kӒ$諦v)*Hв)md:BDAJ7:"I|)ԍ6 0p)PU?r/_lTc%^"WG,?nKzQvI'N +ipE[/Z(??47$Ž\7U:&KN'VWʙn5CЏ'{6y>z\?nv/U|c%8AQ+b0r?nIX.xI'#dWW#ޔ'FKm 3l26`MEɑ{?rJBoIU&Lфf?0jvp&'/ \+82U}Ë,Inw6gpҝgڿ t =mӎۍ$I>ܜ֏ppՃfTK\\~}q_?n~\~sq]*l9DP?n\ʛ ^neഘ<9^`e婀ʁ=qVǐ042aM~yAAϱ-cwsNQC(\|xIQ}lgP!]V×,5FI_m" 20 }Fqpil%ȑޡ0aD]Ww~.< .=xohiԻA ۰Ltf<ߡ24=7 W|?ns(|TDac%R2^6*t@/H_`-un o'#ӎ^sf!gW澽pW^; 4jjCKДaUqa90??n0E50*m>+28ڠ]W%!q '2j$8\eIi(ˌ&5PVS&#A]3לjG?0D%?nRק|W+Ln2.(?0m*zT:i,}rCTЅVz=BKnǶ_Vcw$,5V#Gmv/Fwxz! NbUJG3or!R9uPrM~w{kj!aŬL#cNnʊ>9]j~w([\~X=9)mRU^@} 3Ĵ2E`x!<*;]R8ǟIʁ?n#k?nt-'MۓF_uc3xe6k,P${A'2ۣ?r8vO%1.ΒЫ] F2EF?0KAVaŻvEt*J̞hX͠IVtIy+vdM,u??um{tjvb.(d;Xk~o]50V:)`~"x^W??.܂?nV8BX̓?r~:ۥj?r?n5RߪYjZ!!CCϩ|6+[X*ƀ,ClJ;Sm#4gB7??dB9흆?r{d=lyWl2PSRba7#w+.$wWk"8 l ҘmR!nQ:1FC bBk&SgPvuPp{Vt `~Pf/e i20nK OCXyKG%d7B_ʑ4@I#{?0Q+?nf~|',aNc:ho/F!M"y:?0x)bIZՕ6.v; Ⱥ&3!F?n%$J mS&˾aJ9QܼmUD%z6#Ė 7??RQNcj#ZpK)~tbcҧarӨʟ]k:?r=է*]7iͳg&Z>Gw$<0{%bjVՑޣYi8Yd23xecP}25 (jc+ӑR%dwCzL\j+Vi^-sY6XA(srF[)d>q4~Acu%r<]1kаKɽ$(.x%0?0V &\ù//Aӣ(FJ5[6hkj05S?rD*8֠H;#ҏDX6LΖ?rHѶ&S wi ×YH]{'_Ќ\>fojK0cC-"%Q^G5|er@Z<Kr8ýM;ehEVV}j+g \7Ex)KP_V&=NoQ)0_`P{(^Rb0˙Q?0?0qw67SpWThciug؏ۛ#KtYԒTbm#nX?0 g[jn~Cܺ?n"k  ׫v<ֺ9Mh24m7zwnҥ%zR:ݢҒ!yWV}AyYxq8{+}CocVrfS0ϰ;gX ZAMdnq(ΒNWd͉̾T'(_SRo??(ώ@.̓;^Ǖc`eB``__㏻LRܲ&N*!>#N`L_KqzktyhA?nՇ,8vN+dPt6ɱ.w?0!:+tu|}Myw΄q֍D1.,U|=;8xٳ.l K2ߚ0n"w]=#sä,E8k@?081g½lLwfwtlT UnH V4˜?0Jjj>yAY??}[B RΔh,lԮ>7j9ꮹ\,'~RϺ͞;?nA_WYּ$r"vw߿Qbv{׆Ok`0߈0Nkz'0SjI?0^Jl$yD_.⦙;m>?rL:?r" ^c8-vi"|YAk^-\–W3(UX0M3kGe\;8#L6LiV/~<==lv"N~-P#xD{hoګ/ݿoeM2-N(Ԫ>U~lf?nOE_݉BUbZ9?nz,?ri8{3c~lC铕wm $?nЩ~ ӝS3<r Ǎx?n|NL_O ,B9>9mkmf!e^U@*Ì;|C.1}Ь_6Ez?0DT&iቨOW1xCQ;07ج}}#OE|Do4:'͍&`.ŗ$.KVzvVOIuZzXo`ʉo1C5 ՛l.;`?n++O;ּ,p@QPLw՜1Ƞ@x9 vW0OwMMngU ԨȳjJ ,8d?ng;fK\|5+2nu ׫?nZKUY'o֑&DugwPtsĺsMʗwhT]Eޝ7NyFe??w^Rܪe~Vv)"^ ʓý5]C,ttP \u.rA/?n@4nA})""$jkrũ;q3 AoZim(]0B^^S;}QꁵZf}pYohT2Y0u,V%O,XEif'r[p-hI1KCh{:]Xy*7}sŖZ] |Stxn^1S'˳*EEXYof5!t~}g$ǼӕuVS9zA 3COQF`Q4*w0D?0z2IUFdא/ݰh`08VJ٩BHu/2cv?0ַƬ?0z(4Ā J[!UcjrqONN=3N59'8լd3??qJ/ÚwH&Nɇcc64Qi3eEO,R= E5B+:w_᫗7dy#gmxz"(PyUeQgfe5dtSkCScF7!נBݿT앭6ֽNet;ьIIeY:-..b L6?r\%NЧJ}-VS'MC%m9D??_uؙ?0b  őzhyLD6(/DsպW* 'ΐ5&r}a\e??xи?0-l')H_+0})??}̐*zB?n!b L/Y98֒( KY~8?0)!{?rtN(;{2"dcq툄χ^~;mC('tSڇmz6_N`o,]rSD}r狷M.Ysְ($-]n%4N[ׁ{7(ٲaڅ%aChA Y#mީhBcQuSD?n@X.öE_kktXvGc`ΌrBY}ysh?0Gm0ݴ2K$hض2Sh,3?0SISl)޼'-gNq1! ҩriMUE9#0=X$Ya! WzHLe(KWQU٘f0Ϭ$IAkbx̏j㔚R}C_9w0ꃖp_<6%lSی1XgQvܪqR#GB'XP8$ U7\%??N»ͮ?r&´2-g9,0AK5'?rVT/K6q 2^媄g{9>?n?0C֦SHhj˺I )_B??SUN8٩@ubUYqx-<!9T#t6gw%TZBCVI-%H}^"Sn0eQvzTNQq0S.y\A!#nzpMT!8KT0'Q=璵jU5G/gڂ^9'3??Fw:cNu~v{ɄԨR_rb!jZK',Igu1M%C".Y~g~"ԣ[ E_eqQ$,_\f{镊`[bS33 ݹGbsm#>LmzP%Жó'j4cr{,CGJvioG9"Aq' HUYlh)\2t߽dR~?nm%o$s2*ŊPgKY |fn.g<];JYjg5=Ы:x疜_]4טԥqڄ0rM{⬑U ':VQViO?r +#Ȅ({l kdgP*?nOVD}x??}qqpe\t*k5+Mm IG3E#Bq׊$f%o}y??}eD>NCa]nDVY>ɰR~cunuނ(ٍUx\>hx w@̹m\lHa AabO$,7z9㜋f^>Ř00{Q/wj!lTwvUU\@9|{)T%gY5PuүA L +v?n6ѽ{2hUNR½-ǠgR9w?rdbg?r Ѻ1ۧg'vj3̷#IH$c&K5d 4C?0{B<Ӓ(ׄͿw;gOOZ5Ԟ%ɩyY'򠥄X4Լ????:y~D,jܶE@р3ʭE &%(݆]Bt^\<dT "@?0ܔD= jvZ ovP|w~ s!Cg34b aЛ9}|1\-ĕA8_Eb,*NL[kJjN_-|r@?0/??PM?0^3ЕY??F6^~ 9?0c#i?0vʱL]^q9.D*9p_??]M:&b]9:) @Kx\%X)5U-o%@b)4۸Fc,hqb]k6˒w.bt*MWp&YQ\ 4²|> a)&oO-* 6P>%V !nsX{EOk/=-PSGU_/uNjήvˆW"88׾w;0Mֵ%+7>'w]+ImWwHpA6IKX7`Ӎ?0 k;Z&'HA* S#>ε_Ѷa+PEw]TV>:?r??vn(?n9.9ii^w٨>t6ez.j%MظU,W[;QlQG9h[6tNl?rva:36b-ʈx_k`]ɈO7XO46;ۖqɛ}HӮkOeXU@|̴??$.npW_77m<1QGW!MO1|f7Ew3 gC3tN~kKyo QxAγd_25#6xvta(R! 2[2Cx>????5'טWt4ofh!Xe0~ZL eiaHMQ\׿hipRt ^ϯox0̝z8ʅʻIW?rge=yUD,oe0z\c}7 bhG>f1{k!14@ɵ5 FٹNNQG!(??c}n* vmm [#EO_ tiTjHQt+;;yC1J}??KgNj@lbRsol/f?0{#=КL nW%,b8[]5n {(X]|w2HmnR&Wj֯ ]YWHp8y\??K!mbSAY-tZL־~MԆiƽ,RFwſk4<';|<<-|?0U" ?0y۱r0` c?006$̼|rDqBq%FHѕ]n+L¶Ȭen9=1K"Ţ"lj:QuJH0{π-;~AX=?0jȑ+ZK.rw*m:j ؽ]/l.XQSHu7ݑXUH,WcZ?n[`)>R 8x[,֟n:vvXo381ۼWITq1aHXG;5ͥ٭D06nƽz9H:y_cE]l.DUc:?r\b&S޼re wū*3J#T.LjnFr1/^tu@eSh3WWwQylHAz+{jɋitsF&W[jÛnf0 ?rɹp_}ǁ{J4EmIФ;նr+^/]\F9+o=_3\J̗Wc?rF-2UɔNh}e**ǜaNia{|+OW`!T?n3fUBќ?0?nKx"4ۋ,N/l_c]՚%޲T\;w& +BPq?n|'F5!jpƯtS^g`??K3sB(/: ݑauew1혢EofI$9!v;mPB;UOJDVez5UwMnpqcxzkws_6"1NHh7a\,h??ḮgfRp4M[jYjeZJu'wV4˙zM_6=|ř=DUOL:P(hwc@Ghjd:fó^6a`_SLutlAˆߪ f6rTJ1ϹU  hڊ'+JmDa??؂PJ-RH+չ:!/z??=QҤB/a﮼2E(I#;.*y)No|W\Lp`%?0DV&}(+\NK!q5vȥ>7㘃R"+mǔQsu?nI vaڃFNɆͧjӖG_?r~eskEVܬ_vV¸U*IݞzUE郤DB UN 1`q4&\z, 4X5L17;k?n^??l6!??mV*؏CJU(?rqe=k]wۊ>!}!ǧ,WqIvd6ff<q@r帱`J%;J*P)n>j?0&a&i*?no6ΨɎ>Q2KݕR *ON^/8zFr]X1*p$'+h [p +#6$yQ`Aܲ Rꦀz?n{x~~z]udGHn:P_4?rK%><{_qHxj?0<Y)ȵ-_F\agw|vpL ;??8*|އ~Ѣq_Gՠ8l 1J?rΔsPW˕ip@nFxb|8X+G&1^k=[ږkWS >??g7vR0YA( 5&hoE[`BU>iag1 gZY^,ʨq:I3h6qX{?nD _oUk,![RHE(C<¶%&owGfQʛR%_VcGϟNäv^n#'vl|.:%d̄{֖??1کcZ=99{wM֏m[vۼI5q.͍Y?r+7x~8?nG癵009Q?r7mׄQ=!tGa^da۠^yeV]ä 9 Qh "뻪qc/??fN%_uz:2^\;as??iCG}ȶ]d5\??+bPO^YAdu+'if+D:8p~<32 p]ch5MH~M>}A[J qDxJcXsy=7`tڒye$M}P?ncE%ʳH.!n 맔N'rTekKE?n(UE3sQ_`Fv89X(??ǘ4SnNIhoc9x_|-??{C~'ÉfWxסsDC)v.k#.yMeC\.J,!c]E*_hFoqhiA!P|nv_81t؅o]NV4n; nM\H5bǒG4{+0fտ/:p1Z1Jƴ{fJ%Bl7 @V~ՒEV(CY > zMJoZ'ڌ (Z{&j1HCm x]8Iӑ $3ˠěN኶beeٺ9@@ 0>ML= rTlX:U54"wJ;z/ 4}???rU9/ekvĮkbttK(vac]Wx=uc>߻b#cJ:u娷e5?n7e}Ba.5ݦy&͒7Tݚ-Vityl`kt5A&Xɍm6˙sG\[1|:I"uLbh nf?nvVE% lMt^4YݾN=rV0)F Ls?rZi"?rt2vNVY]5Ϗ(u5fZˬ?r@ D(Wd?rQ]t) ɕ?r*c7zҙF4ͬ!V`;aWfZbK6cz^RuR??J9B;(IndVTmh5?rbu7 2Voo\\YP➉;%+J=$=`n/legŀ*6h̷t譣dCyC1qKe2+7 `ћܻ,.KfpK2V惷 bZMʣ~t||&|T@d?0DWh2zݢV3W h-`xe:y< %j`Q=p9xE 1Y+?rZV`"՘ 'opu??6 aэC|3?n %&S)|}]UqQdp6&o>8}q/һ].fo|xp7>)|*B0a t_Q,s ȱ|=(cMx{i^zXўNj/FCws(?n9D:H`añE&Oi\^+S{VɈ c$$S\ZA;큹%aϋ,2{^$S&0Fћ8%$4?rLt[F|c?rEJS qM ;^eჯ??nfOXn0M5l-$e߰n 2WR1.s;&Gϖ' ڳmTdin;."()ndx}97MxC{&\ɐ}!j= +#\tN,`(3sPWwmb8#O: *$帰ߵ?n 2%f%u."ΏNzm {>сӂ&֐^`ť8hqVEl4..sȲ?0L7U)/Hת ~}MH??J\|GHw1$LF40)4D6?0x~m(}Cq1M_嗩j\pJV?rqCm 8b @NC|tj8̴rx2,87Ga7 9-j-ȫ4HSG@ V_/QBŶ[6imȴ+s./ Nu|?0hW/3(r'yઙ0Hx(VGS8\n v0.$-\C";quUq1+f<ΥeB,ٛ[Fb/LXo?0P̀"@M}@)bav!agiwOB4d\g޿iGȎ.!W \d5C]?rQۺ`x9jAR@qweq#EEQ;8g)0?0@BqJ?nB]"t[d~,p;c&kKIHJ죾E7cjf?0o?r}/Oz>.>Ýy ??_o????Zq17qƸZ>-oFSWOqe愡Σm&Feb.ΥM1tvNͩvz6|j؋0^ww: 6<;`{g{Mw??~%X:4{}:)SÐkIcNh8?r$O`K>5}OIV:þ]ڭOn ==߯ ~T?0 ]?0[?0$S6s?riAIPlmϵ3x) f*@ZeF8i9e瀎"fxJ,"b:ٖmqNOQ!{%F?rnx2M]f ӖP]91{t(Jez3^,6 îֽt1/7w)a^@u#d4CE%TH8?0?nSFl|Y?0w[/V9?nyI$)*QnV#tKً1䠠,=}X8.jrW>_<ڇS2fM,EHhJT$۩R {mvZkQqM)Ka?r!Ry<\ ޮrxR:4Y3ͲVz_Mҡ3JԽRCw}BC{f2T[Aa5`"o?0k"4HRs(cFO+OAЃ+۠F"< ڛf}~4mr1$Y'/Y1bC3e\,F3oŽ6·͠eY|"G&5ݴrجzpD#\cP?0f.T?nKS_HS3xk.efwХ3/jX?0㿱/\vut&P[p@؉U1X뙴<#TI#H4H?n_z-c(QBMh??jS'PX|,Ṳx=u dJ9aB hDה5fS(dIJP^AmapJd0 h$"}OBGˍ]zXQ|)=mF Fe~i.dz`_Dv6o j6Sѓpœ6zTuW6uns9?0?0n_ύI M w r+FA1`uQڎ`u q F-]CX_B1?n1Ge&"Em.0us"a?0|-eL6."*t_Z@ƶe_mEV8Bp/!ܖCˍ?07Qŧ:)2@`cB%3L!U-J4җj*A{z[:E+j W39X^W,`-2v3)a[h4 ?0U8U=iigMEx~Cz?r~rBcP_z??x!##=d%M{0;hoűRE%bryUe{N_㥥h{.b*(4:Qp\n48DP:8rxjkΩoS%N[0{Aly*hL}n U 4#Ƴ]m??oﱹv(,+|E̙}xUAhXk<^]xNGul#ʂ]p,ITSҫHC`mn(k}.ɲU0XGD+46Hu EZc(r3ocaF~R^WE·wv#nVJr\`3:qٷ`4`"<(RVkn2??dn41@[Wqc8pdL":dsN9=.M AXX_sq0%nGahWȫe75dKğ9aC)(iap1aۮlCIuSnj1^m*#19wtwlv#B?0[Bк0#rR (M'ï?0ɣ޶5w/??ݼ}r1.&BEp@Jۡ}3GG7 <ц]n"C6c;5]*)G$'?r}D*vVKGœOR2u%ΘvLD?n.Cew25OR?nD -2_W_5a9yӌ.SRu?rRExNɖpiipRl ?n0ba0]"2_֨[)~#oQ-1fqɿds?n3,.ep4R/K^h7k0tɂ+Ih&sIKmp Xe!9?n-J"d;OKoUT+|b~Ök6r>8R4$Rsf qؕxMH_{gzh|GZe"x$t2EC!o?n*`D7 9hCῙ=|m ,֔EDF-ȖH~Y XI秴Zn7\.ҹ5.٤x[l՚<ױk[-3)۹ XL'&4N'Rbu.$^gziE|eT&k"Nԛ+s<1Sc3}E$aFr0]`zlV㽪T=TU?n#t8l`Y̬'o4u^m\H':m#6*ocZx+2wp~j=?n?rj+OO??EXfe(??!t?niEkkOР'{\??I/g7ڜ)1-C~ZV(\Y0ĕijKERţ~??^N&ʵ9qRXiΨI\K, uK7MG޻4}*ykzK\\AD+LJjVњ%=tUEl&ZK?r[a F!-a„U#TSX4`-?nht~%;Qdgґ˒4v{>ۅl~aT^ɖ ui\ j+.NW\#%q=?rNn1yMڧb #3I77t~FKeTrbKeo**"^W/3NjdMΉskwmt"SsnRD'ʋi%/??ncʹ qS`t8c̺6f;m{C.v[LM+Z9 7ٍPY?n e(K l:QfؼI%%޹x":5OFFa Q8GAJ)\բKfAWvQYWA*‹FnSЈi?ns:`SKe<0YImږ{2WRY*aeBi3ĈZFz}Y7)p\#@öz`$N@ 6P_eP/~UDㆍϣk~[A1A~e_^D2{;FI!c'-2qU?rC{3Ǝa^m:#L_B/{ mlsXk'䦱I/˾^ta`4XC~5W6?rx|Lܨ[J n]f'_cp|)k^*oyK+'޷^ؙM UՊ҉d۴JH@Dţ|Dbo{A ?0B жG_{O4Ĵ8󝤨`o/"XhqRj\!_OX"Phxʣ5Y@I?0Ӯ2V^@%$i4[;LSyB[KS:*/YېվRS??cLr_DPKXGNJ"t"T3`&fp0d )??n??-?n_hi:Oy?n??6&סE#T}ͧ-/UB^-#5bSCz>|J-9`yCSXp2PP3lZa7btԐ1m3Jt`Kõ?n2jd?nn5+*,4d ]nGp_B>!üzzFcy;S@P)اPfbR,*rB)jrKU_i%]z0Jp|[K顩B~k#XQ C/COiTTXZQBҸAqPcGEH{;p囤ĪW,"%?0aZjrF}D6R fio U^xR`Ф`L64:i}܈},\[|:O&&Zy[^F`oF*~Ͻ8 ǀ[T@$%+f)䛿X??[&T*ԼA][Qt'o#XL??M ֪azy>GSGorcR{W%]bQ??Icիm]]uB床€'bVOc#s$zOo^PY]fLGJ2ɲڈ}KT)Մ\T >%U/id: 12L0|ݟ/)JBK2*Nl?r34~w׻Q_:ߠfh-8St?rMhC{L ϱM0q;/z<+w4ox(d Q֮Lw6$mJ>jZ;r>a˹{-ܬ]:??uǵz c?0۾@WlҗEk6fY]}iǧm[+k2#rV +#i+mڟ@-uo??r:\t XK?0:mJ$Kfk_ 6KC)?0=-7ė++# 3\>?nL7[ۍ?0$'iVwC??`~3TicKK6eOOkܘŇv@,TXD'R;<>5fӅX Smjjee ?nYАN;n*=B(҉f*4sۍ>w]ҙZd~64 S3ޖB~S>w&_K?rCvRb2ykaWMvW_MM˔S֑;0#RdrmR?r??®Bz6*-` 7}sPI@m?rP: ]*C1uFDp[K=iԪN FZܗyxV IyƊQ4|U`$ [d"1T[S:,фqζjD "]bEm/B??_tu1 '#\?nxoYmSN?n/7Jq?n߁HY-{2%Y`\1E쮸Aj$<@]AF??eT ga2ai)0&RQ+Tc=,^9#lއ?nJIi2ܨ׈J=ne/lmY?n,I~2:#sy??&6'Sp8GkRJeKjGeI+s+pXR9$SR~F BTqZgW-?n\YDCCT.FQT*JE2M‹;b)áxmMf٬B_??a}1L"~%A$OۺQ?0?0n0φ[QB>/ϪZ=^b}/f[~Kk}6TU= 6=*hWHdÔ=Xs5qP-?rUP~ 9O &y]>Gqy?n"ؐ/&#I_ ??DC?r\@DT3M<'Gl 5U?r~S57Sܷ\<@J??R7":1*p1n# iuJPSzKpD_/z-']5u6I?r4m֥~0{1!k?r8>x!d!LA( ,wocߐ;j#4q[ezŇ_Z>_܍F,R2E@Fk$ˌ2,n"oeRP,&+Tf]IShu˻];}????{wӻw??ߙû.o$ B$??mj^Q??>/׃f/];>l#7?0lnv4x"QG km3f8c7ј TebwP)V5})ᦆu 81ser0TO??|CeRH%#mfІɻ3eޟSh9ëg!.x۴0IY/kT@XꚳʦXNi6"eخv^\}e?ntUD&3+b=D,TI\WZv-(ԝ g cPLGok `2bDiz4Էpҗ$@z_ud??:Eձ*Aï)n9(Wۡف!)'X<OWF%A/O+TlE*~#oƥ3 'ڧRޓ?nH?rsO 1?0PYr&7a5z?nPWs,:9GHtBHTڰ2"o*T|՛9D"i3eϓ#Lh!X(H??InqPK^][ѧ>y]kne(X$U'ޚq*QfOn{ĽDKg)K#U!Ѵ .ve<ݫ`SU:VJFzG'J4>S5O:Aam3?n[ ŷH0_=ڄ|U5^9GOx>go}o??Ɓ_??:GQ2O??zbo%[c[ҋ# ѷU^6pu!}a|AH??թ?n9_??=~pd2e9ųMwE:8yl<z(sdbB3ӧm4>/J}ȩ ?r埄O=|蹰+iΗˢ@涱^3jsu]o*ik0Ƌmyi2??gz=]l/6m?nAU?0ddgL[ضgw~vZlǚ]۩ǛzB??֭s+??V:wS6ݲ\?r6b;KDz$ܖgg%c$ TNupA YUiu^0$e-h0;IةvD @<1Uk}?n9[0^rbpMCu'71&l`?0Fo?nlMO?rݷv*/lnǒUa ޹+|QFuQ}91k?nS|1Z/ +#+j9?ne*T0sP1#"yU¤]zWzΦn&EQ??q5p??u!'?rd ;džȉ4o+B:k80idLdLWemT-?0?r0o*Qm@TMNޫ0ԗ@W/s/Ңg`+c_b ?0GL 6|]2{?rZȃ{{+j)>"?0Cw/]b}Pa!:h0Wǻ5)Nw+;mEĮb*LŊ~GNptc{=e$7lN^ b^:-,rGE5! wUnH"53GlJ+i#=E6Fa'?0crtіk#pOmz%SeVB=L(H]C8?riI2m%UR&L.??ԄD?n׾ z ӯ23hPfzK;"4J("E0Bw4fO?n i.I#@Umg¡V7 LZuUm`\ayg :rIGg.3l7[Nt(!KdyI%QvcQٝ;>E`@եWkH{:27X5IA!RQT8x*95Rpl`z?0 Nh83Ηƣ;?0ǜI>Bh+N3]>FoD> B"޾̴je?0"wJ g)_?nj n7=:(;oʅSw]X??iv}MvKTƢysg Ԫ2ջM5xudWe+A%~0\!"8X^TP!J=Z酀NLe]&IgLe]ΑiYVInIT??0"z3yhR{g8N!ɤ%MZ5u@\6-\T(4TkRIQl?0PN!u|spp0nUg|s@ߢyPFCeE(KP3Rԍi&5osLOi 1MFh{="h%nlw1I|xUzl=]~MWxhh`duۢik*/Ne^niu}Sώ-x ՋpDk3M$+磺67#GC#TLL@Jp~E:>d%ՀLv~iF??q0ʥ?nقm,nf!.)2+<%Ld_$"8QJƷpφkѹHh$%F|fb shVj=F.Bj:6%fHś,.'G*\}ÀF# \_W\?nW*4!c\Cu5X>BW<>,S x'9**΅>-v6b?n!. i2ƙ1\mCyhk Gj=7݁:$pX?rj޽HOIiג1GJ^]?rtyj`!# eS*U51{+;w~{ xa=jjF[??jꖸW~U_w]vsTPzbP*>l#0gAdbG9k:>̳*8>:*AM\K3."Tƨ9t_;kتtAM& ';/%+B:O/",d|bDɸ}`D FO?nٔoFw ,^-epTYŒeu?0ǯD*??C3zX'Kޯ2ld_i!msxieh4@o!ޕ(%WWz!B^/R?r?01dmJ\Cs1,96~A{˂?0\-h)W=26%Nc^u0#ĉ?nD!BޘB@kTsI/\RuS_攞km3g⤦+Z]L3ЊD6?rdn0)7ؑjŸP~p# 1?nnۄ+Hi␜(c DZ!jCPwѩM+CV/]! uQmЪyhVPn??䢪?r1my^ͶfIs;͵:FҮIlZd;MqcX/*R7Z#RR Y7\z-$x&)ϟ?0 "s?0LNXy3\@WQ|' Rp-<]O|g@:lrr!;"u֢ɪ@C?n$yrw5Sw5"PR""5DGqIfS.?0nSq?n bې#I۲oE^D^rLc/Gto\Ie@\= aZ£BT LGh %:KK#Fpl2VoO*yS2ǩJT&B8Zl%'34mvlEս2HOʓvՋ\T3u<ڞtvzrbH;+*Q0W⟪?rZ^lMmd&H"$#\jbINn%δXK`UѡG8&'ɇcA@iv)̀9p<_4fd%\lzWrBj}SS??'VU@?nx՝hhgկ0kaQ^S`%CQg7VbݿuiU}u5GڇZ (:*briD;r{jg˅T VSrJd hMfێѢPC\q1Q'0bW]h$?? *'txC9lq-{6)y:5ދ_j8_~vpY0z01իb%CLI:vWi)\_xs1??sۜ%13ٺaV@u'qM]9e)N_$#^;F=XyCc;򣛀mOM6_J6M<+ +#"rr8uIKf*;Op53$'y~ψX]:!bj 6f`.z֘!0??nLҷlؔ:'kNH+M-N1*7qhM(9bBu- SȘ4oSP kZ 6ǓL-=)?r?0?n3|NdlՏ*48KaU⟁&XwoW }A*Gbދ$Sl tUbNյVU6 uƙ]\\^苝pu3 Ba De2-w~/d+gπYh¨-ܵipqǑI?0ynqm?n;ϗoujpex 5?rn=>l\¤P?resV]dLB FyеW'|5r(?r?0Ȍ'U\`3p0V; {XAlG??RT3jST%]????·J[hFoa0k5L˾ ZCZY/>9v upcW,n''3C3\7zBVa7JS:FYOQ#hΰJ/.ZםOow EH~a1Q2eУ^#{X8d?0jB־Ƚ;k\q????>U[_K,5}C5.0FJ;T*Y^=loa#EYGX?nJ CT6j;zL??xcG1\o\oۢ &}|6G'Ϫ)2 mوbswZU[p'\2wֈEr鸅T]ddqú]yNO9;V3izxPu<@x=G?r掐gGQKd2q?0vZK?r0?n??qq?rv}(:XoyYȆfvnSͻ,j)r[LGe;9ԉ6Ny6[#`D{Iv[6+?rN$^&?r$Џzrg1lpwݓY}:I> u9˨sӽ4{2wxb\5贄۾幛gvǾZmw;-sHۂsD%wK_1;Z7NS=vחn+QV-}jɟB^B[aQĨQ$ ?rJ-tCOUC T%=}9z] ;p~/c̲ytSFaeB턙rE߳Fp ,#<(|vw;XfNgЁUL p?r[LmՅo~\~>=_oe7zQ_] 2P[6CnE W[)^Wǫr;ornfPn[ulzH,Oq{뿼㡫A.tmץhz]-ZO¡,66+5/KYJ'HO9{|^)~پ^'rEN^L^5~k?nq;tg$BA?nuh2I \ {ĺC;\|i} o{pZ kۘBH?n#tN{/#\s=2(1S.#VN.,UZqY@ Ln/^.Wˡ+؎7c$=KLR-w =4c.,.:MC%M cY'cd?r-8A$7vB??{LtޙCX&3[}׀)h*2L-%T*x n6..pI}Z˥}Y~7]幑^rH?09xI_E]v9y]^%Wav"ݶK 3YFkIFQ?r)`\,Pٝ1?n+Iɇ-FkOz9(%m$Tğ0 dɃawyNae#v?0j1C3hk^UQ0YrщL*qn |ʌI*8@0??з,|P7 Ja,}0WxXJV8;F0+lvuvN}᭜*wJ6vy 8.Y.V?n-~8 f6M~b ?0Xf8?n` "T #5R't9׈LÞ+"&K: -;yl ݲ[?rHuW构)E)Nv"2b;??Ż76^Oq8-MO/gt·7@\YXM.@@"|Vas2AM@"IpQ t6SNj#T؁s>MOR~64 Flǭ@}wRU??tl{bS1L{??j7j/0ͅad<J-Dq[Ѫ)$K3+f<.hZ.v x89>S\,ƗM?r4 :MA<[6mva46̅%;힮f:)ϛܾ!$0ږMM>Kz\ꀳc4LL[#:_4ɎI@[ܚ8Z,e)|Y֫\m?08y%)0T*WW|P&_!eNCH4OW>E-rڼDا'EL%}c(4#=9OѢ]@`%P,+:\cщy&H,䀷ց?n=y~oU9҅rVra u6bg#L +*FV-)-kY,/e+^Us+3=TiUFi[3]š_yeqΈl<\"ժw4;d>]2t^'U9e`O1QqxgIݘ払]Yt9fFtzuO03 +#01w0/0Sy: s0G002 ;^&l+IV&_ܔ } %(Aӱ\PkZkInLGU pzxZڌ(9sWE!@,f^9./5F7Kvڴ뭏TbXru}VF]mLT+z٥8ԫ|iGZh3Z`'D0{]P㓝qjeOk)g9SljwR&3=Q%qT}6ϒ=r8i2(9g5U"쌍qlBNQ*ׯ)??-v c^*ġIR1j䓼a{J}:p9Tm׻@NLӉMe#GbϷ1Ww%'rȤeMj'%t9NX%:Po6֌a`d%:g&R)iM躃^cfMvPmfRP7aITGDGKU81ȊlӦOR㕈Pgd0)7فV??4З}YEop EV>\z]ܼ _8 4)Q?nTZ/k4Iѕ<`Ema}wo0o:a?0MwNš/oSS=Cli顾ݝVȉuH)g |ʑbTװ4͛J81n!i=ok8Ũ>^G݀Zjj0TK.ןt !uo"%dpS4%uefqvú?rۨqبH7*K&`Kզ/lś=pವZPBo5g_Ek(&HĆSŦj- ^$(?rN&YZmypxD~LԌ:3>Rc6-:s)<@wIfhc[{EJ[|50M0"9e7ŒEƮ!QDueChW3Stj(OH7-/p?rf;FQFʼnu-Or*1Su???0vȀNR-WkI3-=mM& Ha$R_6z[[5#?nΥ[|;Wx^Hq@({pe k#S<=R'>:s|V?r?n[zSy{/AAsB)tQmDZU{}e/YC:A;|b#?n'q+37gw>)%&VÜ,Ҁ[i$C+*zwa@E.jyzq>M;NuQم*s5Rԁ"G̍q'(HȜ/mpG^b{vMMN+Fbos$.-f==U`?nQf/ȇ=Q"*3wݓ7Sމ^T%$707]3H[Gq `Hd]&5K6)T65DʶGRdK^G}liM|1z6rˇʰEg%T5?nDJޅ6Tben)%;لlH!jVZ.y鴄eHȔmhwjW.~G/=MS47xHOAJ??dyFy?0H27g@ڻ>eAPT̢͉bG_ ~ȮNlZON^Ռfr3%A@D^C9eoΐTN=,W*ʼnV1uj[?n\{d,`h~pm~1Ի>(~dJ3 e7/β΢΂>[GhS2AfՒO&(6)lL{Yy|'c'go/-7}IJ''7(?rPQ͆??6QSwӊmOnѐ\|fʣfNLC'??W\k#77;??m77v?rg??6C()=M f&8gGϟ<#d ,7&Ho!Λh{yqZZrmTS]I2T7iWo'̃L]}X Y?0\]ʚ SAq/11dHҕ -og?rK4wʕ1AE;?n~fSX??)ru+M5#~|{VR؂Jajᅢ{VHWōEJ),NfD֩v< O}L<p}zyN!xt("(,)YܼipNJYe7*?0&0Y"Ԅ/%=L Lёt.IǺ&GG1|U˫I.Z?0>k v;q#Mg,v-lR6c0[|=6Ď7fzU_۴<}9o\)Psv_ћrG^p_ ~.׶ozqM'e#̚.]h.(WE5Ri<=yS56Goo+*Zgg)H?r r󐝘IP??.B**Qp?0"J_ ;VCV N:??@A Zi|3)#- IE[omǔ++j]5˹^?0ŢI's5;?n^zo0RD]BL-9y1ZDD?rXm;\EVx01n[s8??I[|ޢɀbct-8Z8H!ߥlh\Q{ypˉo\SY)1(Y>KλӁ@?0W=Ƈf!?0A ECך&_\b6XG>MZ:|ɱcgv6ML2m(`[:/ zC؉h<\?0L襙SdN@0 +# Q<'5V!Ûѫm ]?0b+P&C]۟t^3tÕ9~ґ4hήxb~Uj#|ŝu/~-??l~a'Ǖw1qwA[o X ٓ"p?n[ -Pp?0&{7[rE֞=\w%L?r7|ATv&NB[Ty//yӢ$;O^<˗#&'IMvf}vbYy~}ϫ&V47X!FR??~7/ymn_GP&S %dhCi|<]]&El-8ASlzUp??N6Ƿ^>W&ޱk#zB_Eդ)%D~q3'1)xw˯8ӣg_NdS'y=j-d7eEah??{d(!0Lg/4-0ء=?rh2l>JcG򭗿*ŅԼ(<戱Be,]cKbH9ahp'Eٕhx}wrzYd[gx,2[d:M(6xiG'DoayO4U'HO=F'g~Fg'&bh7y6CzVi#i+$'͜R NI?0r"o&p!T^ωb3ѧON%~`Sr<_*l'[KsǼN:.?0wRڢ7~;nqE胝98-G%6ȵ?ry*zZ]ll~U*S$H)Egj*93X @QV%!k[,?n"P=&%>Lr[h|ɺ}<szojAZ1k*mSWcfLUۖpjgcp?nenYmen]F]]kՒ QWi].3 =o꾸oM7}:x#Gkh˙["yFb9O9ql8h~Z)K LzC`>zӢ0; 0q*tk{U\_5>SU\!ULB5ǾYrtJcF3I\B|..0ݡka3~j-(5vW?rW}~ĥ|۸/|!ƪV.{yl?ntH%"n^\5[Ga?nhm_UdFWݬᏟA"?0Ԣ Syc&pxjIG S@) dfB, [#1^USەlJU ŨAH(HyFB?nb<ԫEcO%@>YAJu'JY?rp=+&8#T1(`|c ##*(ӍJhсPjStf`'lM]wvA't-??0Ɂ˗??RxŃ~6eDi[54@#("2jiB=(a4ܜ??o[䘡[V6ha?01%we/wf_h_MlK7Z/W]HW%#ɣ'[;Ffg\@&˵wpCе3IҺOp?0gH1c#??H7Q||K_ky~B1ɴőMhdn·c%/ʯUnYX)ԕ$#<ݒ=eewpͽ|M]>hǿzq;^{l^38F )޿W-ן[?nꏷjNITu#nN R1n%'}:NwB<,1f,0RW_U'GFtݭFM i<2!.l6xm?0fpBZV" w{CDi%(UE2i*м+E)\arݓ$<}|߼j#1Eƣ8[YGA6>S뛞lUѩ_XB??B='?r?0qYak4/">_Ke+/%oX?r”\ueRThz)F.6vn>??>DT|{JTz\Da3UپxVEE}|}8<<&xn*TnMGBa(n#=/]F7cC=θr!b(z*]E"҂R{UhNOIRe+IZhH'"hL>pf0S,_6t`̜TE W$B bӦ*_?nx ]"P!X 1]63c{9cQx9?0%Э$ Jй8#NTK0wZNUC vM"*O?0RCWmcaæ:c[#"O/d $6u ꖄcV"⧺0p>v!zT)UOsHŔ~%(ؘChaHY8Ia s+]{wOӹ;}>W ?r鱁ciN˓{'S +#`-(=C %!VKl+9ؘ2oqp=(86 Y`T͒VV6Xo/}kFޜd{᝷hP.0b5hstK1w]MF*>F-ם,eK# 9F&tVbą /e93= a?rՖ(' ̸Ɖ@E0%/YAR߈l7hs:ԭġwOi%K8b 'cJO8 ㋛.T\,bɍ pW]*M2kM?rGoh}V6u*O>`)wWFsn&qfPeV & *<Ҝܵ#2v@#(͆[ AjH?r5l}#͡l~/׽?nﶰJߏkz1n ۨWio;12^vOD3+W(LǐC-}~mGu¥Mm2єჰ &{?n{?nuG8Vz2؞i4WJ{b_o\TM?0;~%_|kҦ:#wjy0ث2qpK^IPg-H^l2^z^h|\<_o5[]????-PԻͲW\`aׇ4cO}{W3m?r0- /,D?0| Rٌ7eX6;<SP+]I#`~A>U;b]+s(X{uV0?r<҃_?rfkY7uɈ{E1TzM?npo*j%>XL@ZGwX"1Lr$W65kAZ~c*Qy#NWڎU}ZژUiO?03 ^r&VӮvՈ;nGu_QeWQz8 nlᔰWǴ{Ч\&[JU]*76S31X0xhVڂH<,, b/@^l??P$NS痭)d0c?0Z>KZ":jUCHuC k!l/p~$oqU+A?0k|7>نEi Oi|]}:{&RGo52NmT~c%3ɴgփ)n4miS9gKCgtB1^E0e ɣOP@!ؤ!'b-Nt7dh5 hv+KrX,\;W&L~VC?ni,p)TFcP)hƈ"2ژ'YT2O"V&+SlM> 6(FZ:߻KJymAʼn=A=-z/2^- ??#+lkҷaw.UX#Ar3,Q r5u_$[ەsW3??4[_满tYS^0vNWNMisB٢pXp%[5Q6{BmD3٫TaZ8RVAaa"QjxjF?rTgU ى+S0d"~@v;=zU$OP)k=_m}G?02^[VU1/`VT-?r*S<[4?n,\,>iX۾!9bR~#Aև*Ƽg˦Qtf*;'Wusi??rM|m~NΠ/U_]uU(C@^vmm;+8_&C?0xO Iy~(tmw9Ɍqiwn);*Kvuj4d't1/F?ni܇qߔ];jmW&iT?nע|A/a~AA?rgzʜz+a4"aIGOH֋Ͳ9WG7u`ۆ '1BzW"( E"v@Ir7gmX5n)uhv:Gm go̵\Hf}u۲.EQn]w[-%AbQ䳽^r LgU0&##˔S2j3?013Rݑ[z2Йh͖P/Hr=y?r^lT)%-n6n!.Z(2jJ%Q|DO,gdU% WAen@#p'6%;ElZiUEqh#<ۏ/Q.t{17T Jo:V@HwZwAѥdYu!BNF4 7blz~ /գkh??j,Oܧ1ޑgŖM1i뢴UPqYk>ilL<jdQcNOfCcRڱ}\/NwʛI$PI}SpOkcс!qƘPv*(Zes5TϑmHc3;_V=TUEg),S촋3#l,89U;Gd2Jb؞1YFi[?0HZIѼbC4ԫ|Y)Om.xOOxeay?0+!z<'jʲzٮx??_YV07NcK)-|u4|g>g-cǵu! $p8qg1exQ2k]tz#>LZw iɵX5s>jPCɡܜgܶǶɮ6,,x=-MF?n!QGջD[H?rY%Iͽ)UHuc&0L?rV_FoxF@UpnVU?0H2N'|P]~s2{wudghPmY$`6T4QP+5#ts%b̿)ѭwA\тZkM%hޡRMUv&c?0r=$.ޣ*X@<3$Gy{u #;$<*hY?0o]]tj.GZ*h/[mʋ~E?0Czt`pҴQ<.5_2 俫:l??{F6^BfgϨP`(]]Iw4CX^g.(ޥљO񾾲}qWooX:зDlV$gzc??wm#Զ8/j{y9jq:azX%5,Szx ܼWp?0՛lk.ՓzpVTpg}^|m_Ƕ/xxv/~oFs{DR垱SaհWM j[Dա&ofU^ _"aVl;Gū"D+6v9++3,$-zN8m(zrb?nv"fnad1b}w6+;;Vqlw}^iVGDwd˕L q3='HAA`o2G~=w8uCYf6Ŷ]F5a.?r(:?r0 ??B#G>@lО X.s G s~b4es1+*4'B#}7܌TT@4ׯC n9]2.?n?0??&m~??O˻_6އ0qc <^>V:?nkZz+~C9):KSm[ա;zHg\_pEM@gM5s6pīnn@VO@~; B{1&iT~! ao_L/1M]c?0@Xҳ^~5DlCa*R8\7CCdM?n9dp+^bD#C۴я0??iTs??qތ‡A?r(ϰk(v2;̽yKJR.j%w9+S:`?r?nCbfy$;O<^zc8 v,ʿp\ė8R)iŘ-WP!jfF{uؘ.W#@H]s-~V82vM!^l-(Jj<`$8.=352?0)Q ;'_?nF4c?0]!u{xMRWprSp4$?rc([WD[m'-0haS"Gt۱Y/CY Ȏ''5xS8-[lKΤi.:mj_'hTv0ZBDž)Mle\L"|'1 DC"`gՆh[޵DK-ܻ]S}\4d @@z]>P)\b.W!HjM9rHu!pM87aQ7dY1j~xӻfIwNF[C( kG A0??[0 (`Z` ]#iz YhW?0.:8(lVE"'$4iv~Ɔ!h*3Vb#E(D y'pZ0{9?rtdH k,l7J+K05j4\2.)N_o 8~q]EE5Ua(\SG"Ґʖ%?0ƙTID4hNaY ]! r1 ]T 7lv!m4CH Dl(k) gq70e|"dz153-{Wk1H7Xվc+yGpTYWS+ʄY"PaC͘W!N}|Dj|x"?nN2ZX1:"zK''D\af`_ pܢIa(y?0C&nfX>gb?0wyA'$n=w=??xY ?rhƥc6ʰ^fy|p}W^v 1͍86t`!|it&U;WO\q14,?0Di-< 6?njMW. hS ^Bs?nĞw8[1I 2yX-E,#TzD Ϧ^@^f?0%^cqZ06wbxsDbţ8dQG<5d^Kr q> a@ӃZ;8Kv4ikUY (4jUކք3gFx}6{}"b/v6ʼ%G `E6&JC?0LNh}UU@:9H{p±4s!m@Gs&:3bR7O7:bPS0ůmGn 2EJBŢ*3#."!ǡ??85w7Ez +#X׶`o'`Fwǜ| oWؐ46otpY{`-ENYYG b`ē(y]mG8s^LiyGaQf'd}Y8<;%1f@}Pb @G!T?r viڗHW擁eY' z%酥g2Eb8")!=j+xk(uWV!Rp-FxV{y/=idnbdPAWi'G9w9لvͰCtܗ-+2.Dҳ)OEz񸐻Xw:s [Ƿ0*?rJMR*óXS޶zo4xm&* y/cǚ1E1]~84|P\($7Y??`z=B)1X}m6B1ߤNB~C&v͒C *6:NdSnLrCtiT7wdhߏﵹ  hpI Ak;LRoTTWH7l2qU"*?nyݼε=D1t4pȁܭu x2Sj]v/d7",ڽFܩ#{X@.?r6N9>֓M|1ygd#NP˧ⅆ5e-iņ6݌\٣Z"f\BF#`FQc$L@ $s{U-Ym_#%6y.Պm;tc(֧˳߯4ήF nM#/??#?0:RY0W\DXcΈ:?rbpxpϻM1Kh5cqdG<{9M6<{H÷5qmoRg~ؗ?roKmYe9[&Қ&,5<) H`a!xU=ȇmcp$4Hh<:T.zlm$ukУ>x5 |ސWF3bUAm)GA ]dϸDQhN"#J(klI 5I0&cMZXI._ш}]"BEYO̴Tq6ӳQ(29U߁xr`_bK #nwGgCcX"YbUE;2+?r %Y{^Yo䫾Ӡ txTF6.$?r/$0+cث ojl#fІcfOhk;z73F=< w<eCVlvAF"0??2CL^ln8Ry=D!F%JfG|)OA:l!$-EN턺.rM?0}xyK: 5~]Q?0}O:zN޽Row(LWՎ"̃%}Hw愹yߵZrhRܶ^w~[.a~\OK9?ncewaHc\??3?nE!g=n„}U߮ʈ/}RzyU+̬ex(O=,e"FDB>w62~Z5jTa"y^szE_'O(8,mǔ??twJE ?0~d!cz<(%=ӆi~x64quyNܕ?nO1OS D# #-C\t?rnS,tZ3͆Zm0v$@d}өr侹^wĦ?rbQv/ os+EVNUU_ N8N0uaE?0vhM7=Up?n{Ap#t/2=4ckn7$ȯ\#׈nwp-}cyw.S& )J;sv C6 ƍ&z?rX,ҧr\sL??Q?n6?0SgIR'xϞɓs]h@LÊEt~4u_ң͛eKFˢU`E(kKCDϐQxں667>в?0yoS# !*9vj" 4a2F%e?n7XtJ]˻2ouvARC\ >rO]P/<׹ ~i24U(RS,ل4N>>utW{)+g)˖tp=`ˀ'iy]Y2U/* X) a?rGhN <mԀi7`?03Vm]ogDk,4zihÖo% HkQ%$=yUccTt">콩??ۮc@AjZZ^m2@%jY[z?r9"DtJ5M/geL p22I:3$3|s@DsbZ:j#^mVpD?r ErI^ ꮉQtԷx9GDs-륑Try2@!?0@XaRHflIy,_Yk89޲*(!WMFU7T=yxA쟄n[Ra0]dݰD\Z e%QUQV>?rPD`FdI6Eoh1+l2˥~iԜ*[ݥdF3L4vI;e,<`M3U% Wv?riQgs7|a.;?rk+"#w>TI, H9SFTMY|Ɠ~ O -hT2tc9?rx4JUw^ ȋFކ'_*.*??> ^Uw!UefunUxsdq" z6UbBWiS*yµz0H-Ԍ|OY.7ƞf, lI\`'G ^,Ds(x'Tf0(GSQ#XdZ Hwo H??hE] )"eЭ8"!I(3MEgk?rŢ̩>G>p˦8]6= \oykQAɗ9VQ?r,8/w|i0/E;TwRy+ɶbNsȎ y75g67??p=0xp =tbppyINTrqD3H~X626il7 °?rG#ji<4N-ˢ"RIu RMvZRNR$sbu ev,Q?n9@e0??MPso5s/1]#[+w#$Y z@u"ژ,DXب-T(:l?r >S sn\7??cW>3@ЫJ| cg#U7Q^;+HzOBzx IcU CZC?r?r_cU5w?0<^d6HJF,X6HT w+uML:`TZ* K3h*`zG>Wf]Lǫo960I)xt32a5 ̎2E q%a[|l2b0Ll ,5bu|l"I0)P(bU#v axӟMiʅA?rWĺMu߀7dtr-|kvL?0[=<}DG.__^?rIs޴"ԦD:]{oDz{xgCL^o+䐠!]FK,WX O-By-A༐r'yv.^嫌hc7O|~z$+,7EEyx F|^?0~*be04eMg_|z\;44[z7?ng|/Lv"??`6KQ'NI0m鸼C3xB ?0A~$6`!SrT mt)]㒊:?n\??WD>?rqT5wV)z_1qg^Xh CbAmb!݃9w123Gu3ܰ1%}F{5??P??acujMC{d !s#gDUX3KatQ*]?0i&_',ϔDT?nd)oLύ3I`jP3 F|P|P?n> SϢHgӐlIlqNQ&~`k4|~ZVIN"p~ 4??`a@lU0s7 '7 OpbC`gnj5.?rf~`j('4y??t6u{ݿ~׭_tփ{4Ԓ_$FkƾP`|5p?r?r3QRf.2Tש^WePF+:Zq/;TGo?rkG-&??t%MUl.WEr{fd"␳R:HXp,&d s0bfNƻ>2]{:zAW??Sֈ?? x<.3?0%d1nc&$( bkH?0j{ίnmKH*U4X^v$&;%U͝)V[ VQ?rEhdg('1Vg4&zXX%XG+zЫ7Y`vWT%|:C»]iF?0Hk} rsMEfcoM)yNcG=p=j\ݖmN?0]QLy޺kz=/[(11l6A^=4-?r;cgTUkv O9)y\.S:]Kiʭ@-2= G??X{oFQ\ߞ;-p6E +#F5u(,vwwGF.̘g#~5phHBqA#D/??c1鑿aaMI^_]~Y83LuL3qv%0?0f KD:ͽ4~*11 #lH5,9;G 2DAa$ɸ2$`@nBGתXAАժ2UBW)>)d ge~Jhu;,F:̯zކD?02m~ߧbnU ?nnh&a{gErݨxV3{~A9^A3??dIrCizh0 W便=3OtzvLdo߿??xOd'~m3uK2Zˋd}cLա4.$c_o_,g,KmPk{ZJ`>; i "FWIr8 `{0)Y)CH,BC?n7} s_`~1pT|˲odRz@8?0YѬREMk'p %̮Rk0851nqS( =ȗ&XFM[L7آ\233F]@`!Y_' taN9^E.p`ȃ)oS|Y"C5n,s@.Q $!w'\DTL{;tYp'nω'X/6"- X;QD qz+߳h8>_cWRϟ^@x"?rS<7'x8C0s3OkGEqC?0z|g c⹉V`??&9^`cu=hzd7h*_dsw8Cc(g6D+P΁ٸ??vƖ &F5@/0K)ᇷ|j1dOeUAtI?nBT<{R^>1xш`w{kkҼ(T  -tƠXpoO/LB;]tQ F 3yUxϔ?nW`rG ;;=Bc؉g&y̢Bq5J1ʐ\ 5r_ҏ!s4Btc_CPz}Kಚ??Ve3lTَn,?? l9?rBR`#Sqeʩ5 }"{#??9pA>w@T'aȧ=% =t3 9o%b]?nkh2AŴrVq,?n!=x1= zh9B[ ń=gYk Q9Iy?0[h,x}Wۇtxv=yV3 ;oՊ2cKbN!:,%+@OZ0"U392"LSj?n5[rDۓ1?n;;РlԴs(k<#։6idT 0MpbLUjV{]"iv6$RLy!7ミ(sz[T luGB4" "St[^'qaqlQp-(Dxϙ"9?0U/M'v`Lo2-Ž(݇4Eoi]V7zSE%Lߚc_z:l,n S;hra^h@+@g??{lϞ}>lew(??~Ezhi|0LXj{o8uE?n?rYv);R (%)(*t@ kH{XSX܍3 1_!#;Gdfs9HN7UnEjŌ&?rr8)}8nR輙[Q wǕ_MG B55Eu Y9Ph8q\|cXUP|PPLxCu9x>iOcs1WH D;w!&'^>(҃W5域]̒OЎ~0pf==5OYp/n??:Cs$8B9 ާI*Tgi7w ||MhVhDT:4td9֨BK9|iMTr:˦0a0=ϣ)aM$ tf$z|kW9|r:<%zL/Ccgv3)2q! qZ9IHO?0d6HˮPnX2?nap ۾>p d-U5?0*:Viq-+-As]VU:z9 9bfc]++꤇V?0n+yPɌ`CW2?rN6ĀZUD.2j>?r{y~he8{^ۆ!Me~JZ-u I:_9i&i%-lX|7=$Ę@&3LGuw)/ s][pՋ?0G;[*;HUac?r>u]T??5Ae݊%4>a v.S,A k/_ee>$Pf}9Ur @%9HL&O\0Uyr]1&3<5mI~<)*!w"7c 8\ rYAZɤZw-;K֌?n8| z,b2-Ģ【ԑJJZ{xocxæ0 +#?0EŕD`&Q1`ؙyi0T 1( jWꀫ 'P HN^Frt4mPj@č~p%?0.PC?02?0a?nPb?np8$/XT!q';/BL?0?0z244B_olhf>0U?0?0Xo?0|Aݙ{m)f"YՏ?raϋ>dwM*|\{" :ۙAʝ h\/&Y[6.1bX'̟mTBA5R @>LsGX]+aLwh Җw2ʺrDuN6AM->Q=jX  D?rD"?n4ϴEGj_?0Mj K|_sC4 mzgA;*??^s\xo:)Hϙbahw͒W"|<e'ƽ|~"b@e%P&*ׁ??Cd uICk@z}Gѩ,S:{ qv][Rı־Ю5ɬ(Ǭ,?r b}8e?0VƑ;9VP?nGrD,QVv?0zƏh߷(yA2 }ٮ5=8tҭt F|ߞGG?ri:vaᄮ.-A{F,b??+reD~qJiC:ȹ;@|)PqY6lySj(+lͬ`/Xe1 ,5Fqy@dX@EnYytЩbṜLNtuP.D ڏMbD~{nqދ\gAAz<2D3qw -h{=Qt?0s Ԃ%VoTk?nm* 6%0N5[i!WTFqSPEϲŒ嘻 ioL#tJb-dq6/TMEn8$J@P/RHpV/2 ?r ur1@꯷PA4Ac-ЊWb nI(܂4??).h2@y"2B`-]_`rgI"<+?r4}0u nӵCo y~ 2J-|VXpdF{VOr H2BPA??>\(& Ìʛ~uEہ?rk{bhcZ{ Ua۸_cBђL+)zFD[}sQweXp%yQMN#v.W߮ťG^,>/v q؀Ի{m3Ccv:ɔVjtxhCv}??Ż(Ɔq?nɶ.,ἀGje?n%vO:@—dw:Ym_Y?n?rJJbI\l;FO0*Y-l><[݅5I????qn {d_@L]$lևᴣҬ??>24_4};a>57#@?0ٿG _~/+D :e?01U?rE^o[|VC!<'W?0p#փmOëP, 5s)Et>UۄUW'٣v!??A2XVXC'G??tDOR{VToߝyA3!y㳣?r.9s׽2NAk~J M;?n_&C|Ѵ 2;ԭ8לg_nUME{s z8r5j沁d"8)GE:91e1v_QA6k'nJw~UnVS}B]O >GURmqDpI ׈ U٩"6g0Q+^@e@{٫dOqѮ}`ղZm&"G.?r &:4 l?r-Q(oO5ejD ,?0B?r4Q@Ppԣ'{b"M٬c|M*qJc4ui<vLRl8@?r0 :L,Eѣqvdt3fIh2SEG]GXB?0s Հu/F U5ɕ?ruT̂G,ԕO PW!s0Y%,C`8FJ2ݘ]2Sꇄ3.ߤ7wwT'1@Êƪ#!OO;H!A.19|2iy]e*V<)F%|??4?ruP?rl{J; 3,gֆӄ rX\6)yu@n3Bz&6BnD.VR=Nxz՝`+HΛ:%(Dښu,蓾`)G!8)#Y죰2L.`H8/ ,љc^0Ԥ[?r?rjw?r|??/̥48ӔαD:ΫٚM }d u̵}<ՑEqd1#d~Z^`Mk+`7l+A7KƤ?n6gۥA`F$1ˊ yLl62^u!j+qs^ &(bQ['lŅ_0 hR][$*yn.R+?rNϕ?r9Q1HuE-;_A m_H$t{??ߕ p\=D1&BĤFh8vlBv?nıB+d!??'Wk8&>/midmƷNnlYaj"n4,r`U u lB; yKrC+-Z;~J䳿}stv6JAzsJ=???0n)=\EKD?0F~6RerKvOz8;KคuQ?n'6J"!brJQzv='o7?rY????=y{m(^pn%j"[[;:>8:5V?0?0߿ẼCuc )omGի}8 qqPy|ϚByمxpeqG}AnIe%-o>.)AdG]0 |Z=7W>[y,to"@kL$*?0ՎL6盪4ÙDy؛ӎj-~N"ԘbaKb+`fSZszg>1 %mG[shu??+d҂W R\Gl˔qfOЌRLTȦzTPSm?0ǮSq^MV7o\ai"8̪ʍHȪTj߸$P&8>j?ng1-+֚1EqpUk_\{SJ>~Oӛ ?0G05F~??+Ev~"$G'lO}Yi~:F'Ju_t1n\fUFP3TN_Ĝ*DJl t)ys}C Du MaQ1%,YDDh -nQIPTΖBT1X*dgAlv`!C\צwDOqRYgقQϺ;p_z~\K^YW @8R<;J'iji7UYЧ9峬j{:BF_L_i9j[WQa{=OdG=B,lO^HZyfcwX?0Vnt;1@:O3?0uR!LuM B3]?0192C@TiV%R+jq62@I!ޖ8?nJ}j<Ȳvz-f%!Ix=k|fXjJ3I\ '}= ڃXNvn*nK &?0ը"T>f&\,om=0&[| PY$|gGߝuT6UhFI zf=pGEqNJ[|ѰʇYJ2."i?na0Dd("OH?r0nz~Y^9D!`k?0W5R~&6[4=b?r仗iU&up,NqW$K''DLd|ң^2 r05Jgp%1??Eg'֪n7&DH@~. :[?reS4@ᚍJ|6$U7P<-ɧV{??Q?ră l6 ܒY(B&LB0\Wan1 :vJzlPa|)U+uռ"QP/wjs1^HtB"y$wYj*?n@IAX3MC-̟/զ!Z3h *Ĕ2$4&t]`dlk,ԴN Q]@8GA ]z촶)LbBCTh{W۰H3ӏ]jCBYz ԯ@ 5'"֟(ֆPOcO׉ʟMײyV['l@H8)q=ƱH@ov&aR]?rn/BdUTtY/Z!:!Q4s??g܏&4Yx:.4P>z\ud*BCжA=}>wQiRw!L&SGz$E&!LxFѱWZ 7h@?na_&Xš!԰ kagk/o dMDQ:R! =t$~ Y4K?0^Ms~ΠӨKIH,U@g)4/C)Cbv֥ЏaICh!.E$ΒBkR!8ޯ>36 pb\6 .y?n/o%YuQ\_\(m3k@p?0`9'oj8r`3\ӬɱB"DzW([4 ڢĝlF%U92Lbk&0rKjS!l$VTk=R?0rr?06PARٙľb)48%a۟*n3JfJs%wdܵj뺍+CͶy`%&RTL$`eTfP6?r^'v|R T%q@m?nV;FiQOjG͐(Y_YVi㺌'?0j?nI̘^maKJY/`3/E>/* zY ^(rWBau7_qpvnX^Jm83IڼB_bfJIͨGtlxFԏUkKB.޳ RO-sώ#'^u;l􉦨#xAD,D=\o?0lot??knіǷt]k=ik-6Ioh/r[[SwEZ%k9,c>fA_f d^$V"߭l31/j-ߙEޠ;tOr=8^Ãx!?nz?r3cȩ XQ:n9Tü^l{yeͲI7&EhBu,P$0lr}f7Uz:7!ǹooϯ~/zk~+C>)tvx??ס/|9<(З>T_Kȡ>e'1l~B'g$pW?r|C?ri0B٨ҳd ??r??w. ViiO´e;w8IT%ucu qY(*.*#֙#?0xѣg1$1N??X l,??w{;ubO?0ةϣs@4>^&L??u:U;jeUZW҃X'"??}mItކۯk\=׺.cpŧвd}WM䶄h.)k%;cn(A?0]'rssEFR:z%$nܗm"=V¾ZaDDjs?nRp-Yݚ 1KOuɺxy1)/W9=8bcp9i+dB O{vlk-mRαj# \8QV%;oNTӎIr[d.!K33N{5Pyɬ=lUɠ>.78U/#VO&pMA[[y ̲]0wl ȸuHTT$rb>u:??Öǖ4|??H\wbѼ[Eڠjv6>Jq 1*D1;0Ҭ"2;&#Phb 2(&@Zk!.RvLh%_^v?0#VH(kUVQ?0]1\Pǁa)d%Fƒ*gf8Ub; +#>a~mE]%nyڋvq^ھh w¢'ͮE[EɳW6t,Fx$mY ?0yh8|Ԭ4ݲSIwdWl^F?rI`ً3F;¦!:ڀ*?n5+ۜVMޣG|5eZ15H˫%[n׳.)BY/&YXliҥ.,hU$GFP/V}cXN9#+Lfaf|%y^D3Jdwh?0ڄ0EDXH#xN?n2&46Ol3f?rz EUclP&q5yljql7eRnǀ b,F䗮}rk'8AliK'qҹgݦkY{:Aªʫh܎)chڹPO?rXQ[9joXY8qC{R`:cqn?06Cшz(J NR!vg_~64oO*؅'D6*ސɻ()ᰥdzC]-+I9ԴV:<&G/Y$z[^T*Ľ<F?0h|LsW?r.K&ZsMNy&* I_F[tR\vD8{7vr6V2)jo?rgYrWiTOYo??ҊԬeJ6 Tx\G???0)N⤥}P?0 ֭SuChuWUt8obk:[:[\NBWze=IC/&KnLXfg))d`XtbZӣWi3tzlH6z?r IA}%ߊc--ʇ\o?nQ|` z~$YWo( ~ϧ^6IOTzet`-WԣLwj~ 46O<.khyp:saRM%Oy(,]5@5J E}qw6q%5"ɎYޛ6floO^C[tkY4޽>?0Q?0CAaD `0TiqZ+V?r` Wtĵ d ??YUfane:rТ<=(sw_s??wYIi|B_Ր"M|o^揶~yo/X4U%n.VnPM؎7B˫JÊhQ= FĮ84쐫K__ nFHnUf*ZڨS??~J(QN,kmpa"n&Ж{+XX^m)fJx[tn0~՛Ϛݸq??Rn_gJ̈E v'{gu;~jKJQ_!UEʆ??{ˆ-=ߪd:!؍b!Q%NB,^5TdB7Vĕrŋ +*Y,.oAurzmOqYhm")#1tf'he јMhQ6!yj ^\'@H h>)Th$M?n5?rs"|y7yx (P(0hA2;[Ҵ{/萐U:s#wg}0s,n*tw-V??y|FFy=Ռd!7ҙ3=ۧvˍ<#R׹/idrccʡDSt,1-ʫDNᑳFUvPWQ2ۚ'T?nL$'XZוW?rR]y#A.!Wn??L$!-BĔOazi48F"$,K0y@f:{'YeƘά0??V>;ISܩzIy~-W_(l 䟵Wp2tǔUnB rhcd?nݸE8y/6ZTp]ﯥbRK!m1r!y e٠k&ag=V#[ąv';nLU$+-:nbl}!0JJǵ¹(KgZB5iP ßIS5źV?rYDEuUם%2-pDnSRͩ?r6&!?0<1LKLSVXdvRIf{hFdGfm./bx ( $oc)"跿=|uo40'U)ё9]XvC2eP@rh~h,x Sv?n6@tT熒.N^tț^lU&&2 i~+0Y.Эk.mLMH??SF'yZy<4[}HYVA~_؟ƺY@ҫɑ_]g>J9WRzvq")[ݐ×1)A˧9&E$"7Vd0)w?0AyD%WH4F&86~4T9N.x}fn=M?0x^P|[G m,Y@*iCݱ4`wIz]ip&9EGAn`:x /*=#EF(v6-(.uU3FGk&$Z@&'iO蘐 b1טsYV+|*s'AU1wd26z79W yr?rɪi.׷+s:Q buCk?0u®X+)v4BɬBQȅnnXzRVmI2ŷ4!O|n,?0ܟf0eq̬J n('N.:Np^&o=r*A5כֿmO"Ϡۧoi/=^M"v53c +#%* 2[y%4,kHsRL/5,@ْ5`|_|GZB̲ ×Z4A@??RG^zo|Q%鞍 :u)5ҺCaMчMvPY de2ayiͩxOleehD^ItJdbUD%y~c̼iIa|l1/u,tej =DW[3&sc.k8L %pbj~ryS#*NO6Cg~I&3m[-":a ˢpIvi7m#fq=8+0@?0]JcopQp]m7ptc^j5[pfר#h[[9]i!=t\D*\ 28- qzO OS5 tW&v¨nm|F?r8#ʋ@DbN?rS1˰w *i]M=%#("xaڄF2`n̨djU?0-:vbH8H 53E:3:bH-b'J!j* - KeUm3Bnȁs9bʁТ//ŀPo<А.+?n9MJ0;q&DEdU}kgQV5)(V~Q H/ThP`fNLjR̤*=YшdW'VL?nˢ'Y{Bђ y)4le{M @\ʆ?0Yd덵ӣ8!\(]OVWtVgCM M%e<;5eC6t߫"Y9?n=+/Ȍb[$2SvJ!j,=RH?r݇n}..]E8>$6.S2epTu;?0LFPʩ^4YseAe#T 0?rը]/v ej,̠:`O4Ntu_^)DhV7\ksu頢w܁&j2|tܕvj$42]@+,8,XIZFətOz_6eVԜsA ɢ4P0< YzM 3R59vޛifJձ'O;??nWkh3QD۫R4A ^ t1.Oj^\FN--`nH (@* ?nŎv5I2G)GcUXҞ!K8o [{ t?0ݞ=x˅W?0pjDžfAK},| I97S~VQ+ŬH?ni,ݷK??TgoWW7?0_6n_݈;g=7a:K"p΁J{3U{]Ubdw]y92mpF,z_4կe?0pntk*&j@ GQuj2=7?rȇqx#Ղf9O8fwMjVmeZd,K &<$967?0 gL.wۓN8!̸0@GuiLSoa?r.8%Q??h'WwF\Dh,OA}tu#0WtqCulTע@a{cu?n7X{3 gS$1 V`k#8;Ss^ LWkNh0?naTҤ?rnt{4!&&ot~sww??HqgOOaw`_vo:]EI2tt9ɿkp|n(W^qBaxXc]hO????Nd@ou, [%'s[Ic~tճ<Ϳ\$"Y??˛$|ǎOJwGt~H_,հiNO+zų^$0ZHQE/ El|zvMi:@gBnK??'tT"]9#-BvV2jܰ<~P04>j,` ?ndl|aS09~2)NNeAuJ?? ]h>m}MN;qQi]5ai&axTO[@/`+"l鳫6̉ }^q}1Qs?0t7ȧJ[:Sqxw=D,%#fԘ(/)'KrDU~P}V7XQW ?n_CZL>CIKY?r\.ǬpIoKS~8ރ&aw ^Kx^C0wwHV=L2Rv9iixNOzH{cb$wϤWq1ti`S%6ܣff٫h?rzF.IRs:ګox:QɊȵ72XLL&ÿ%a<Φ23kRFJo$LubMq䚷d˸–JRC^~Bs.o*›{!=[>Ko+{* %esD?r/1mv`;A>5ӎ??PƩ!oŌ~b7??P+PW_3M/r}q"M2G|;tЉjm9}mqc!Z-Mqk]&(xYI 8ʯh[U-dnk-NED~Y^35 ^K T-_YAfB7N76\ìvorEیܲ#rhϫA2ɭv/?ryԻ#v[5 vAPrس;ԝm*QYϧ42Xs:3IGYn=vdH]hz4ؿ.] yh:Y6zFO5?nhؗהii^|mMoT:(Ofg?r ]9Of-vrGmS¼#M.0ډxn?r7/{j"͂b[4b'::mvcc$G1y7kq<VsAT*YjrH_Eu_?r:0Xv}u-;MidpFo_(=&s:JwDNiwؼ!MzA$#d+67UGLr5ڣEl`ӚŻDQGih{賗}l6W#W7>:Yϡ8?rQXZyQ3j$_H+Spg]3[je \;/Z}-j:fέ0hW4KLxD>R:+P4$<{6~u)f˕NyV8J^|*]QUL$GbPD<9?rTN"M<(P2 EwQ=yYrS+Q̎$bXި?0m&#e:V=f?0~~"&gĸ4G;wf2eV]-X9Z?0='yk̝q/d^ZxxnD??}Qzcgi֎\CB4= %s??& mE@ @rl+uiy"#0H=6rčT-4CsJ'N1{ZQ ۺ%+SL5a||'sDI#{̠ȵ ~7d 4b]$́vŹnx_E?rtoN≔}EZq%!BJ!Ԏѥ"EL$S](ד,`??Ckgg"EU6ϒ$h+N,R1">$S,bt}Pbg]jeig( h;?0IU,u!;?nӅ U:yꫝ뭛#gUՃ-n6JHÚCO=QꋑXC|KujL@(a6knqq6O0eMVÝWnGgoTUTeW3B#PEâd +#tylɷκe!Qٶ^G(tN =Ngw LM(ܦMC[T̅MUfy]\jt:?r=uiO@JәL"L[ w{L%zm0[`mS u8e<=-X7Yܾ`6p]ZpGp섍w(6~PsWYmm׮O$9???rȕ}:"uYd$EX1U]??@cC${ 7i,YUhY@o\v>WD<*G@&bPbX^q/,"ULar\AYyEA6x6=8p9:48 {AHXܚL<3HBWPق;e!\8L$}Vv+p- y (4v;ws\DblR>eN3~>K?rE+nF6&zLHvÞ 0e HCv6^m:-D'C鬧vbשreu࣍[r!EZz@-a 3ڮϴ{;U!#1 ._"Bw5Sh\ &306@V4]nM @ EUCrH>D˸?0zUizD<#5`g]քs\0]g5'M?n !Vwga7}{4B8^B& *^ֈ+ʞ/ƳGF̌w6ҳe̼ov7=~6Z?? ;?0o$mT:] tA]h^T饵[gsuԪ:e7N&k% .)%s)F^HPuMfx[ҧhe^vG=A-VibJ+r6ܘ9`teKvH kN++rODM]#gU%,s;NoںZ1~BPͱ[??0imq6??!3o~qUgmWϫh&dpk!Vlq+uv+xTWiT"ZDa%32z{:E#ZW?0T~W/Lh iG9 Xn!O c))f o&]EZLX-ll{AuiUrY䌐/".d_ǚ4|3Z(EWn$K?rJ`wTʳа 2U6iگ6&^A "Go4Z" ,%EyԒ'#x%#p@yH<+ߝ+l5-qtOGb?nPXa{lA9&ghR*lO?raP?0V]ш5邁lhl$`?r,a?r-b)EQ_zQm|kEIJ;ƶ~p[G`?n_??eY^ϧ!݊Z;A=@?0RP",Q*?nf%V=|کFkCoĐ)1.n]KaQ04)VG Ap"#Z_vl7 Tm$Z,A$FRǦdjB]4oͻBM矘"pNH5*]މ*\@mg?rl|e'k.njO3¯?0Fh8V??e?0*/DNHTmZݐ)Ƶxfw??tԖXDjbgN9GjI,X*7+զ'v?nbƗz38[hYo,7K"pղgUz 9cSF=9\MsKMj$]w֠A I8kPt??*`e.gpx;FʹҠC,~-MA>m_:= +#u&r Þ%?nJ$HܫUݐ`2](tGĜKLkxj;\lT1e4X4' Ju,xAy;N(nM?n uԊׁ?nGtZH^zVg捺}wVUwG26M[=I(%;Lnڮu!zj۪x) GĎj_FRI<{DkB5ݵb벷1A9??wrX&N:P$c6b4V :P~[B~0h5ca <'FA o&`&&DL+A\svbM$!fTa ^+OriE+V+K:saE9ta"VЊ0,]9O\_h:Q ˪>{+-5lAGҾ珀EiRP$pE5(1;$"_3nQA@r$:f4Ǥ\ald:$Au& ɷE)ɏE~bD?0-1n.P 6o?rv]zv{~ğ_1'6 8X0عy,??lRӦ7ZmNԆ@$$!&.@ZѾ>¾ "eV+qC!Wo^}1P=BVT%I̾_<;qUFٿvqrP&;,#3?rȍrN߱͘} Q!Kn35O64)HZ#rW(gѵ1.)xK%ݏ(|"v3נ[K`YnH$8c]V}%++mV6^V+cu_]o?r;vp;㘱(h}??++e:Q(ziG )U4wc4qȱh݂q vOQw-󸤮~j\O24ikBrf-lHVB5EF˕T9^;Jdǚ^d?rDe*+] ]nPi٭7ݒA`AB??1?nP$ݺov}-ڹ- &aH2Y¸BH[q(t)]p@]7q! .]Zqc??pQ.kV YGXtHoi`GU"r2oUdq|.Up.`:C%E89A.#}1YTWVZ3ufg>G;ۂe7O< n첛r-"5{L0???r0_$lAoӛ"*&o5Jd{绁bz0Ϳd??śׯT??xy_ zĜǨ)#Y-UMYǃj<zxP7%9M??",= 'SLAz-dn)jQ?r3Zi̜t:;WY2HKdWn蝢~?nvbWxڡ5K dR1_H='4/$YE^tEꁎD2=֋.0@;0/_ O6ed'2qɂ;>uʔL0EK?n\I??.n8)z=s??9Gb|o8FTpޗmۆ<'HE.=+RuA@ZvE)WW%ILR y\\j>Xuʒ]ȏ@&R[qdBBWqEI<Rȯj؎vK6> Ύۅ[¾Q| |f䧹rS*FqݡTUFaIVXKoH\?0x<a$DI&wTNExI~6i*gZV*a= ePWq:6.dv9&NRi3(}c8$H0څ[ Gb#NH9kw 8[ZQHLF|`G NHYnAj-NAIeRBZ>ir?niF%vrff mMO(f^r c}ss4 Ff#L?nd-RHʵF&Z1he(364~nd~@^UJJfxR !3q$_,[t?r 葆7 hKyHO!!UlMu&`ٯSІ;?n՛b_HZnAu@p{ޏdޅ`Dŏ_<>\\n(` /[x$l,"d> ?rn8Mg!+]*t Fa ^ãŗ Sy B}E8DY`V#;x ??U?rXpcW r=2b*p|kR"C{`"M?rAG聗b>Qc@.p" 4R0Ԥ#H7qP2?n1ȊI y7m?0~`a?n"ĢYrAՎHńs#֎FP;bo?0a^aarVx'M\;[I^i:LIHBM]"}dK2s /pьmYdLΰl?rp~%&S{`hơpt@@c7:qtkfnTh{>v!`;ui0#?0gKɌ_?04QHHO75C|s/" W?0'd<1Z[ 4"P40xD <a}`L"nk ] .j2mLqx(A1j_:d1LOfѻvsBhm!^p:*O#i7n0w#Lyj+O*?rw4]2B-ThH.KFlT{ [Ab{8LIaΈzM??gToCXLa/G??|~f=m0j]hV,DY& eY{eBQ=DԞQkM8V+h0Є Pb08N@xWzjqPZ^ޔCnx1H7TjyB}\07iϐ6XxfAqmS'/c΁NAdO ~Af02,gO.lyl@΂?r::?r hβi|KVjCQ\ȇ46=4u"eHfTh7r 飼EY`7SMmxU+fNuG@?nqT2m,EwAnNu5ng@`Vp" ''b X19gFI}zvmS}e`\VNdA`>j.hF[tJ$W2uNh4e(yAkJxgK[ ȌA-tX0<?rk+H?n$]>?nZN&#UkCBɵy%" pYcm@<&a:rc}:VQ(C&)DAGwإS:_V_?nή9V4kd"}:8in@Y,[YnPZ=sfh`4خT0^37.>%h"%X>ݦʩ)FS@\ZPD?r&Y 4ڸ|@*峪goQ9`Uip![d iiô-9z/;6Mk;jKӐiy-usJmN;Μ˜98C`0?nb4Θ-r6ذ#2?0fPs6^s#J{Jfl+ rNmҵ x@wfLGFbbj1!q1s$%W,۵W-5{՞f8L}[)z?02Qze'/Kk?r;OМlG%l0-#??zY '5V 즃q},TWGa^`6u@*njBru~/mrBr.xoE[Z1כW???0w<{7m۶m۶m۶mƹ;ߧi;;ji$B߿ʪ<8+;l53#Zzg - X-ɧϏڜ2:>p39:߸#^C9*דF{Crùtȍ1|%Kҕ!#?r7LG kca+|-ugkuPV4`ԱťdE6Ҽb9q]>iB`>-7{R4:UrtR]lZz_>&TI~L({ZzCe#YZPgvH8Z)'MydtOwm٦7?n?0p03C4Փ?0FӀ=)?0?0@?0 I J`g MPPJs0Z07ap9?0X$\?0MlD[&de8 ?0.#"Q?0s\І91(9] ~?0?0x\w???06>J9P0`@ X??&F{?rqk(`xvN !fb=1HXt*=l`Bb(hXK 8څɃi9pʳ}w6xۅ{ "ѡv;#Mc##5F_C?0?r?0J rdŀĀ{Yd74 CWYm??kYCg9?0wT\ȹTY~/2H5 MnSShNvF0~E@z;inwR` k<јeBT?0X)sL?0??$u?0?0->_??O, +N9'c ,c7cdc??"?0ҿ??}!?00D=,rlD p=$T#$܍>+0 H?0L?0?0?0,H?0V;J8$ED~GA`[_?n'X ("z A1V(;Ҽ+n_^N4vw>>Mu9vB飹!"(}j?r@E㓖Sy[ͳvK7H?rG5AJsU]YSִϳ`!IdN_)eqxTʲ1T3!an?0P[3jnvv{ٱT^O 91??*c m[x‹){۾HGN\lP`dD`x@(IE:BEΧ;vg9q& +#5g &"=->v}\ę%heD{CNBx&??i:&iF??)F"|(-1vIʺWYEe[?0A=}ŗo

G_??^xE 1#2r̼4wUYր=!`~jt(RݟoƴPSnpL+޵e!2(8(Jv$T2a $Hd{gZZKxifT-?n8K4X?nCo0-RD#vY):Hf̮kĮ׫%莋,~9?0aud~ T7PPk9\%beY w"v=ɯlXk@H(*~^ [L $ D_rD˩=NESd'Y8=?rN &ey8n:N qUú΃m?n+EyKb1 bź(e}՚ș5{U|[Uz(KY*7 !q?r%1`RjGqIKR- )X,:YВG BH,V})ndΈQQ:+ptØxF9 v;sdw5aw„ Oe"zTs{KMbky/-@e'[VZ.!CṘx:Dø(Bv 4oƿ~}GD_^6 +Y(g2@k6+\fEAPeJïnjCT~!T6~Lu䓆2z1i:)dxEYL-uI!ge,p b}\,?r4+4TJ7kAЮ̀6&]2 ՕOhh5Mm27F j5I~7;̉yb8%!\_LU?0ʽ'Uʻ $|D8UaDڙ6P>W3ZjwwHGYa)Cʕqލm*5ץOffʽQ96V D0C%]>7Ф#ikYԈqMeoKkI?rAҙwz ov?0 n+$t-M !0I[`p8/;ӱcBΑER8ط%" 8Y{SӺ Iw%N8jK\!G{6u~Z@\{iKȵӯcsA>nyi}iUʖAAqQCTGy93%ǧÉEBY4?rK2êJ(Q@~$|Qe?0cqo,gAe[6fV:ܻtYށt5oywlyفq:Dp*'뚊v=i-S麉noLHCoL{0C}^!I:ȃ\dz(L4KgadLm'/r)} #Xa-=DɒVMi|F`z6dwd'_MuQfbt??hdgBܫ011(ADH@yp >SU׀aJ`q\E[]E3KbZy~Dc+b%~#̔_ߴ|oӨzY 9lP`?nV73/r]aFauQ:݄y%ܫ e:R((?nt$$jWM} t s.)_?r>@jJ:+{n0d⓸ֵz6XP# vd*u??=7 #j4oU]{.JbOKiɪLHN/N*&Kk'W&'I,䋐2 HuRh^Ӕ ڌ,d_??&75r$Wyo??ɗY6VXpz.F}#ƒI6ɼ8 Qc.T5|-$fBV !" fUb&k}R&)0fJ es4Z J"})7씮Sb`Xޞ!1DH^V9}GBl1>4iٵ+1%4ju{ u@,!q! +#ǹ a^ l'jڍ"8cDz YA{2GC#g8i[]ptv~?ra2)|jpnlY}+:ѣ퇅2L>[GWWR_yOLJ?n+)[]Y]oBvFby:FѾ]XOQi@\^lY7)'Y??1MFI;]Ճu.=s]ᗘ ԁ6Ҙ5jj?r\&׳S ku??og ??p?rq\LcB0hZ2v^ӥ5|~lh [8ogQ.,|.j?naLsi}yiHrb`(D.U0lZ!Z:ϫ5)??,X2N42}gW>wíFiLoNRrΖ:iJLs9X&P)T8g??L|,:`ܨ2GkZXbQl֧5dlJKhlS£(iUcXCN:+OM%FwѳҥlVJz);f\3%ݬ[2xfӿj=<;"(ΜPc)lyv<5i˓Y&_D0Eغ7'aW3s5JNI@nB0Tǜ`JdPrXiL$Wr)먄SwtV2B5b⸢315sʜ0V]E&(BB)GЭ*?nl !-tbA5210,d#,@թ?nɦ^O_܈cP冑q15",M3|ؖqމB$}KozjPM$v}Х,(i# oTt8BEv'??ޔӜm-~ezXaT-2;.Oz\ ,o=ޜTDXQ';Sж؟$>z7KySYs֮МHGvHU'4|"TcgMHmW !Kȥ#'?0{M5dK%ĥ !(ۭ'Tš+hOQ7O}j%~ZZ}jV$t|OzI_Iߥ8@tT t7 ?n- ?rpC瘯??]Sb͗\?0ՄN[b‹\ZND5mBWAܗ.))6dz_0i(t(;dVи?06&.&6gB#BG]?r?r '.?r:bj<o?n36퓰Hbev@#l@7#QΣq&v,੉\7H̀Gj"9z9롟!EPF'- NvKj=ɄF /΋'+FY==K/|%S\K7e@9@ýv*?n˕Nd:o=55-eX@9Bc [K& %:>$.D ol;^ eI@^[&T(L?n#ef !x?rѝ ILrv??9H~A!;oN>Y#:Amx??IR?0"鈝G#!'*Tx@fh}Rc)x*&W[4??pz\`bbaoiUPdBC {"ɽѪDĈ:`0c9U0 +r1 'GWƞ C6&4d+I+M^x?00hZZZWg7¯s^hWg#$2f[}HH,dNcT5O>܀7>0%DaCb0@ZVYKY^̿ɫ,IV; lܒŚ*% :@LWVD17F0^< +d-{;r>]>ANJkRj!ߚ8]>0mS_cexfv9< 8`<2(qC|nQHPyyս>?nP^pܞc;R^~ƭ[&W?n3 ؁2?0ꗕX}fG}?n8zk%!U%2@A̵giMǜw<Ghw?0بlY_e)W<Q<5a?0Bu!kN#់ݎac&“ G8>qtRu($koA7&YRl9Sxswy{ Lbi_*IqIxB`^bd嬭4!.)+3>hme#5o2LW60Mo ɛc/bIߜ-Kл<_]N2Ǖ (~6j|oBℍvLM*뭃g"ĥFO?nN5؇8PgJg{z1a#&$'/q)!@??}dX]ꀼ~Tд_?0|ClgF`{??wρD"X3TB W ČIEŦACWk-4%6Fe'?nQ qFZ5F6*??wϟrt-X.q4%R*&s7ye-'3ۂ)c3;-uט,?0pY 7r6J;IGFGdž,#*qjVnd~3.*Ҿ}lg73=sJ|9I"sEcvg02?0.b(???rS`t?rG8q$YV2QQج5Mij??2ra +#(: ??NˈfdQt2q1Q56ᒸpVC0v`dcfsHк(C9|k!H֚p9>[ Ͻ{p+T1;w?rIńh?rybw??)889Z8Қz8 #J,=( ie `ӄCrҳv$,[G0Lr4uk^ma^|冟pb1'_-q5ԾP;#ޙ/XW UQlX@b8캆%qwAAu%u# 8玜dAtt,1z> ۍkX?0,yOb{ɓ,Mtm|;!}GTq m??+ ?0ecڈؙ@-\*~kUn97zN)qq%C. nYai>Se2!>Gl駺Ǹ:Нඏ`KRHh#11|ִcږ 0<-lsx]Y6١$r%citF?rtfMÊ>u=Qٍ &v_ j4{FI~ 06??.,Lo7Su}i3kVpVJwk9 MJ)lv`-Ŋc&>*1]T%[%?r@!5PJ[pCLxa˷13{/zFv:{$;_ܬ~????0Z`גS6Jz{IJHX]?nm/:M]S xV!i!_)^'k^7Y}^p+Y"bP|O$(``fj Ygx4.HF!"ZN?n KS22bGpMw e)a!4?0y1@.)Pzjq6%2??'RqޒAiK.'-[9H-efW[q!7mш0ԓFO-?0dXӿVV?0vq=oocB$8ŨsCOX΄.??]oʍ.A%x)ɳR,K 7E wSfqՓ??pH?rOr2kR%+8qD`tJ+nd_8?n[+Ò__kw}v>+\ 3_,y+6?r>~~:K*-ݿE;ްEFVTd֗4t@SA1A }??ҜaOɚwHНkPFTK Pauc8Z`-Tg(_= `+H_J%L<"W19*A$`ICgJ*ŬHN3e*lA_q*h*l Ah;p"g/Sg>ay9BjZ +{>i$8?? 뛋yĥL3?0v*Dʞޛlb@̼)LP-؏ńnG :حU`宦}Ǵx0۔/5@c4}?ryz*Pn/9ZX9^478E#lzuɠdB+od 4w Gvݎac0: HfHJ:<+"o)#I93mxG[if&9PDР7`?rSxao 5o r@ !W;??>;gB(Hd. z6C8:^[c#G,oF08N`ߴr l˞+"2C_noÄҲz,:@ڈ %g_#LVW~!=}맻ё͘^+mj]QӜ>rb{V$5DBQw 5Tgy4SY1sO0=d}8ѸyV/u5:.5t3yPmyиY?r9'o_dLouc>џ1cycgO_ޯsfY7h l\ BfO?na9QOlb f6n/ U+yh0¼ *ENE=FeIhM?0]_n\l{]Rťh̔?nGU2+Y1ˣ%VپCfgͿK1?n\ D$f+5D^.cORԲHMtlfh~;pgT$˞iXGo/\z#t0c@FrAYer1T0AG ,VM-OcjㄷQi@A+9L!$w~M!w9~T306Z?0czgjm!jH1l8\/ X{Tnڿaی<|:oQØcmG'F"YZ ,Z{.sjRkGu:2P zMVOfdx7V,,N̾T,Ը=uk.ή:KC_}GK&AVIU)Iտx0VQn.|ϸ޳uږK]Kh91W[дy{Sx +#4֘ ;}4M}]rzYO#/AJ+??&Sԍ!2OY3N'b)uG8\?n7k8}ІDVѴΙ]u{-1JO]EmM}T[H+JM2ymi[:%Ǚṽ@2c|eO }^{BQuQY-NTG{sgAY6\w>iaڕEH{kr^OCs_G:!??Ő53>N,Σo2AO=%zrvf31I#&A"Gêz%kIx =]~(h ]hn/uG":0טY2qT%4_dOomu8c9{>,*"ˆwU1Z%ɧ?nmN8SwIqg0qnk[]wΗa(h"K^O|r$m7Lfd?nfʷ/s??Fy??s<0Bww19h?r??cr[u70,/YkUՍIU#m2a*d.P#[??ZOmBH@x")h?0c7(rρJEKq?n< <'\='e!^:Z1F7rdI>ƄjрUR*@Qo;b;!F -2"p=_/=MtFS?0??-X]qjCUW-n1c^(# a[|G@7I‚ǯZ@0\'"u~Cr`]>ouII?n{iQINj~X@˼F۠5ٲ3]9V/jP9*Hʬ0$Z ??uut]ϼ |]g郴`O"2QsT)ߤ}7 ^[l9Ԯ86ɺ75ej`Z?rN=.4v?rft[A*ߑ*׍h֭ݼ6@JN\pTK.|s(a7Ev8UN*Pn*gn|UPrtՊյA<x:r_xŬ;jMni%a[_ܼcyxu; C}rՔڊ2;|TUG??Vrw+^A:7ve.5Txy/() t~k]i^:bC >p,]N3 橡F̪" 4_Ea[=[3{-̀9g`* DogԇALP^^i8r=u" p--;VebA, V-sGp(?rkD6gOΓ}_dh˖y!Sc^VwJIx3B"=Jw!}Ivr?rnzK>$(;hiqe"2Rrb.ѮRSd.1x91YKz<%n73g 2ce4%ҲV |(R#9Q^?rk eG!ȭFkJFb_߸aėZN}o[ԙ.``J𚋆Yo/][+Sg%y~m2L`Ֆ&ɹ`yY"0?n2f%Π=i <6Шn 5GdX&N0H㌲Kl4;!݊<LJ$@uK>"1Pd`|n ?0cKfOΉ_F;hASEkChf/0>i jK}dx뙶/ bt9 W`+a_5~RVDY ]y+S3!{znnw!/~r,X'rYb_(!,)tECv݈eð~bItE4q͹/uXx??ꨌo/ 1S[E e LL|d6ξx\VV1veh+2k],nү"$O,;?n陃kp??9f.ѓMP`3+/S3uSކ%=t?nwduW1=-P䱐 )Ba,#zIǒDYz8J7pd+iU;}~aDZJtX^LyFϮ~s?0@׻2?00u:Oc*N4'[`>M?0*'8+7)/M8/ VYm"9+.~ikX`?? 3?rZZ.E"Aof~e^}}sƛݯPhTIwT?r;gv)QFFMC0$p݆3*6nv:О'vF7hʝxS5;LݔfP y f#raSI1q5gXmRqr.I~PW,hԁm?n3eVk^M4v;uOucU + pOZr0@ʁtI)rlf!󂠿\ZFIj--ɠfcZ=!lK߂)1YWr????v?rzETy3=w4OY;*6UWPPwg֠a}yߘ֯ʣ?r 7Ū/g<zOC m5]=y~4i7z ?r86\??f=t__58jMo7:Dk?rӣELdd*&CA$bfS3%xFK&(tj~ _/I ~n9 r:dM{6~`t%$II^?n>RkN7~9bJ%,fE?0O}a9YIpv\Ʊ>0x,Elq9\M<{%,ĩǀ #*v-Ƶ0Fgd>o-o/=V0IҌw +#x%_U5:A}h{bYA1eD@nV@&h65Ӵ%`ْ?n4T%Cc0Uz?nw)TT:,U;N>޸}npOD(RP3+$ImԸf[?rL S$(4lvaWůuBô?02v?rHgǫ_o%CI8/@1ۥ[=)S{?0*qUd2Q&iYNm"eXC\LՙjXI&;KYkhr#&F8[_2vY2[/ US\4sowUpr?npE"i+3)>p/j[e^yz?n8`yf5&%aAxqZLpBN,` }4|Rw咹?neԺ+}?rtd1u8rx3l_{(W+V*Rw}@fY~wd[;!ѣPyĒ3;e5\F^Pp8?nrM;2+`h #7d_jhW7y̸~.I+y5va:Fd9P5Dk'=Z\ ޒԫrhI18,On`[dL8dbF~:oVdS0"ńşdfg܉xЙX9L\Q)(M~TߊZyuSK*[hLDn@4qJD/1)h^{!1_C"kD WQY͈=kTi!StWn[Wp]~R?ry/A?nPew$rW*#X Yk|s@@mb$R,q1?rel/!}G=:uPx<3v0ɠ}r\o@x*cZihbyFتFX8[JD3t5"^͏(oVRHmc83g9Ө¼ۃM0'W΅b'V445bpSR(X`?rd;hQQcPOmyŴ[kAN/?n)PΐDbf\7 Cn=:mqUV?n}kbi\3?0x%*f%:GTPr<-ԏ u\mq>ɕmW51w= -?n>vCZ= ?nl  y箑&&*8/ҶI#MH[[#H\0" gybCQ!d 0>u؀3:x1.w×D։2D*R˱.5++ynHr$HC>TK qSQƔM4tvA}s+ݲa [Ctʪ|+1҇2J7;36H P'fVkz y);ʾkzߖ%N)8;qRJ<,F([Fp=)3ypڃ)TQMq҈+??8C8 oç]l@-cuNK-9[c-xDuQxeoT>nlCCip?n'?r?r˿eFr]MlX@I_ ;G8N|4ꅿXv nn6k)䷒Y?nv#iԠLt0Uߍ]_JR9``Pӈ01O9;_㿎4E??0f7[3*\"O5?ncbdpK܌^2`ꮼJF!|ے[0SmB<"a2ua<}ҏ#D{l&Ĺm>̒H@7QZ9K`CiRdw *)!_~of>74#^??!JϡLYڽȶ/PIq -bܐ(3:{2>/1??nJU1(( ޴1Š2{u0~>$aät( K4 jd2 ??,|W1\C;'ilaX1u܊z2Bm94)rM]$Ϡ__~ksvsnP*":eӤ,5.Bȝ+S@8hM5SBP 1рcOX{r10?rBEc/x?r:#??HxW ֻj%t_q?rn`Z k2[똴L9eYkȔQuy??*\Z?re !G̕ĝ3C^Bɾ0[Cq6sm~'lypF{Y15_(GQ iհGKj}8 NyxHs.uV0F Tb2x%I:TAmNW^0uhK&D<\R\JZe#D@BJqJKL, Tw*7N%E{Ԃx-]PG:W{'\M pC8vSs\tKUJ4xܔM_j]lurC@VV[0*# .NNRPT?r"5 y?0W򅇹l8~Mz?r1/??<]'{bFM?0DOLdJn9u'tlyy&=nu?rMӱKKwZz)Kǹf.?0hj̓ 00Jg߱`&4PSa?0iš?rrї=/Y44&2grƌG!h=j?n7ŕxf zjhOhiCLSWtij Lb +# %V%IR ,hzo< O?n\4X*^bGTq1Ae]`YIN 5=i_YՐ|K\ 1B?0JZ^>??l\hf_Vkp?rɮoJ 7p|xo҃RLz1X}u嵉s]b85-(c?ny??Y <E0N "ncDAۇ&s`zmo D+wV)q$?rt~;xG{wiz<]>PM;CWKbU?r{38o5~=oHjNF;?0Kd$z]W]|LBo꤇g~km?05:@:vk{?n](7a??9;Z!?0cY@L#8/AUVs*{sK.1>to6 ֪hd|6Kb,UJ E/܂/(uw:Cw>DH"A~r-atL?0gU!A?0R&a%4f2xJ¤+2<3E9; d#pb]8+A':[}pJ'eWd|ʝD+8B ҨWkm2 4d.?r(~f!C+?nԡu9"dwaҟ?nmwnj8X1;O{c3v?ru(td}g&\<U!jqv83 Rm8F1AҫչiHv).t1xX-$'VҤwe?0?nLb},{N=x*B(/5ԇln5Qj [;߂P̗'xf?rV7<MA^|s:BkvCCQ"N?nA8?r]⿨ҍ2[WKNxo/6Fz1W ~ v?rue[3tn匇 )8#2p^H*|u?nca}"msZ[5X1aE[!o$n^61z:m|ѹ)??>\ʿJ CMRf9Yrq mZ6Dnuzg6Jꆥբi_eDęg (#y s9}?rc(D-WU$k27O??s̟.⃏AZ6)UC414{_COkm6Ks ??zC ̌ {7+gh{(RQ8bc}v-m/3Df%6St}tD㈒KB6B!.uF3=~Fߠ]]B^8ey';E5O#PF!6m GcP%v`g.M݊\conX$iWy^΃Xd\QF(؄VFD\B6TG=GڌY@%pDS]O:5(qa gpbh876^p-cmc ?0<[]a9r:tA}R͌U/Z-O+쇊?rQBjX A1QTShƔ2("TtR+xڪ׊Ǧ,fgE̳^?03'6#ȱ_HY$!W!ZIeƳ+M+es.@}ziHM+QPYMT#@Z?no0H p3U犠wC1?0ֶm۶m۶m۶m۶8gIsΈz) ޢ jW9?n}֩@v%؝ -pC=#`[1ma˹vs^J6Ee\>8CW]Vyy/jx2QӳP B@./2u1t3??lߙzN2bvq-!UȅJq"h{byj`&z3堲VI?09ѩz WtbUEOzk|zm42¼?nĨu;yc8J\}ZToK'Rvk7J[&bv?nHx9P/'Ođ}Q??˲L6nt&E&))֢B9u`VWPj7B¥V`]^و 5+%?n8 p&OJcsڗ|о^V?03uȯJJf9Vc!! =2,b{탤G+=dM.Q.3ɘԻF5PG8}b jCu\$lN(chA+UO''cgA@ TxBߏ‹(5bU _,6Fg6dt0 }")urO 4YKPM$ 7eܐ{Eͼ`?nlB8Fi)0Y=fyu /9mFr#{P D]c=W|PŻNnV=^h(슧QJuk s,I$F"U2^p.Gbf7%L^;I]/iMo?nm3Bә]/\U?nXtHsVy1Xg=m.^V#L7V;Q\*ʗNߖ_eA>?neî5.&X߆hHf,D$ )TI(FdvR.x]ēp" onጓͼ$|&=pk,l4!To?? e1 Ci8#B'WePz#ID50o0wT?nIF5WD9eL^/(ƈ_ʧ(ծB' Vp{[Gk[f iYK-x=A0pG?r<D!x$a4q?nǞitΑBDRh91PŦcoe=gg@ T-a,twC(Dz~~\xvʩt+O.Sat Y?nVlDP% 0 ;\'9BchP{C?nɐ> ĩi-n`kվpSƤiF/"ۆSxk#)T0!ng ߱%Q!2j "Ws산!g?nxp(K-l/+ KrQh\"1P?rϭ\Tu 싿a`vkaw @ICj۟}}28F.(uUV2P_z'tll/#a*>F:W؀q/~{aWU@c2.dP5Ӄ!m ,qHQ?02YP<4`'EiNy9Nhw }I6yx"@3,mU CO&,ADCf"Ndb'|h%FSk1gDÆv=H8??(|Y3]rxxH@~DE$T-N'h[Oe?0K/QC LMc|Lx R=dwo\H^v}`זϨwP+ /Sq{E4Xju5fs#QJUL"5}p+1X*gSn'1{0AX-"S ŊvSl58r??c"y V-hݚh|h/jk.Q+\JfXS+kg"ny[R 0xՖvX4-d޳3[)&%Re|/iBIum_ˡ_xůޔoTR?nzji1fꕩC)I%PFtA?rb@ v@(dROP,eܦ6\M&V8 +=b7׹Q/e?nㄙ8.޲9?nMȾw,ѤM"mDGȨ9uIN/@ϑ+CKmT-mTlVRk5r'T«2qF&1;1z/а0~ϘsIQx1l_e!Q0L>|="#D\Ú>YK{W5"+?r|4>9#\1N3 +#)dzŐM'ޮTX-ΛGB` L*J?n&q%.[@Ӻ)q{Ic?0SBQ9Tf F*GA:}yqUS0qKXNrY: uǝA"-U`x$DK.&+&1],1="=Ojsia$MGJ0d -hN?rx52/ Y UEOmz??A ^f?rKJw<)R൭QiI])),NGKkדlͶyC0g0qߛZ=IbcFغly8Yl9i?07ߋ1&f='ZjcO_ 6;D4,ݔ)x51؟Ԡ>mRt@яi.sftQhOT~ⱂoFE>؏??j͆M{͖W?n3{LJu#E,?rKlQ[ ([nv#k:jmYr/ӵ~ANd*Q/@1ǂ_^J8##oYyX3:97{I߬W??\K0W=qļ\_:FqHpx _8*[ek`brjHKr$ 6T&$HxIq ?nA.RYzlL$f!M_ ΁(d#?0iL`Q_ < ijW K:ϸA=$DʅдNVB9͑<<'CAK굒IBR==jQL %O?nyVLwk?rJa}1R8AfcZ)yrYޟA_foq}kT%G1ƃ$]zS#~$w_j^KYٝ\??g^xa[}L2$iI[jbb! ۞pQsl8Y?re27PD?r#[Nr8-&+n$)C#Pt?nbNxnSNDE8GȎ|G= /%t?0P4qݷDĢ,1Bn[VHh?nH{Dqim2A@;¿ )҇W*`LulOf)kv~)kaafl 4 \=" F"E4yt|EBg68'XGM6n=_[g"X%oE:е:\9cܪy9Py?n g??lD#!??竨UꙐ^,EǻwqB??Btt!Ob]?n{NJay}W)wR|adsv)t]9GAZ{;C2 u7@4l7,Xr/at }k/b?r2r&8q AX;8YA?r"XsD?0o?0/FVYO;bW-?0U<|eeRݦn-@bIv SCEAxRߴ.{{|_GOcBxLM??M<*h`;s&߰L*p+mBJZfDXwZh:r;<0bWj:hwV$H?nD [?0𫟁ŒVŏuŠWN6d?nҠ}FȆAMO%fuqb7FgPz>0rE$.cBEfRx%R:wBMQD)(|GDHd1:Z'/=Zb^?n%OSlx;r-@zc%/$%6ƞYbmI("[0k`̀Ӧ0|TdlnzldX3h-Q)疒_ٻ%We`pezUI„$DG"jC!X5Re鎊(͖]GVlWPRʡ6kY*pf JnRM$<-̞4D]ܔMGW.jRHJ1011=?ru=)/+Jh4 BVQ>9"@ij|\D_|?rҬ li _G_X[j d;xV.1ya'"q*nbW;X#?0[7xs҅䵏).$XO{BTTQ }~)` ]+w+n|(ISENe3Q O (}ZlVɸ᠟Ad_lUa?nה'nLjޑ2vJMvfPF0ث.|u9??dv??hpE 0FjA\S)2E2/k6dI{ZL']qy-v|9b:>@ƫC5XGiESm(goX׋_%r2fDqkY榁4O͗E?0.9zhceS*?0N0z7hrE=[txPK!.צcV_a-OsZxօ]`-Ccr/Fs\^ہ\Q8 F,ե+PlAhx*V@\~#{,*8y ???0'qilI1]SOsU3r?n;xY(lJ`1-6&񥘝v>X?nӣsXJ+ǜ^{Df3̌8Bu"s:McFYF`޷3?rzUE^\d:Җ??/8a>ɮ;Y׺yJcyt ZfE-g'@ڦH[$bض`mE?ny^yv=\ zNu򻳼IKD+'fdd93|;:?rЮFOdgdd\"\Ls"xl΃?nРxO1.?n"9G?0gHXڝ cI衁v'?rV?rn~> +#gsOҀꆄB?n<{%,io=ыYEޛڕq+kV6vɮH~RJ#VgGX~V^'Ȥ)Z!w!mhԠy-S}:pGaN7IQLJ j{E`,E&.@; )&Gʅ_s"|~OyU :Z5sK»2nJM?rR'?r!}N(Px4??^+>}o߮fMZIѷKT*Phs_fQ#KNwUSūcſ(wVWK@}-<ɳH{2' {}o@{A6GyG*5VVdpo`5Ӱd2es {~>}ޒͅ#؈YФ ZO"1eo??)$=OK*֝[f0Qެ aݜ[OqP{ >z`-(V˶o>>I(A`ƴr\#aw0<7YU`wCj9/1bJLus@}D3u=N?0jRжf׍N0ƹ?nLi?rsa_]h %3,1&rGDR,C5z)8>"B5n2T~sK'wj7s*,([3?rXf02Kٰț @rhq* 5Q}gDm1'gLo Hl#o$ـW(6œ(7֒62|g*1S٢tTl>??8=ghc?nIID#e+9MBp0??&{FŘw>P, ;9Ѓ5>﷔^`VϜ׺`fIswTOE=3Nb*4x^2+I??CDa"9#UOh?nZI:瘝Q! qQ᩷/fͥaCN_bkR?rXivbLTiXgR?rc9i 5Z3 T*۶}]ĂRi<؏*?nQt2g!x!\Bږc5_/juN1c>Rq]/d PL{vG/SF3>$.] ҖSkWGtG~\\WCo4jn??俛F'Tr\B/?nLE7M@3I&̡R1%??+MYL(GMrB/h:!W8N Ӄ\[+fZ&aD1plkvΊ-&3;rSz> 7wĜ>:R??2?0uf4}`/GlSq.BePzm^??U<?0e`% TJ8eʔ]T&XUֺMJ'RO.ULgr~F*;0f߳Bڔ +@\LTkVvLTwvֲm WX&Mh:H@5CSX7xm)y`+b_v% xK'[TvB6I'1lPt&XQSEVf7磆s &LΞa~_?0F!J] ώ=Lu;I?0EoIgT-8ՑEsmjU\fudy uJ:F7CgH8,MgEj= ozEtq~kM=2X܊ì9?r?0-J{8XDڲɹwϝkq3_b8@oO61u_TSmLxs;a@a~:!؃fFdvd".~(G;>?r/H@ >}5!iC2ukN({@-zy"Q,ցM'[J\:'SMtlSP}6V%~'sSV}9x9IF%4)s-@1.qDx& Wm䗜Z+#14??Y??ſӸM#,㴸@|JmaQk8x c?rv(?0n1ia}?r}˭&葯KlF;U [?nwOvbIR52;??@Û_ǿ{xb̈́mG<WQ%;F/?r^/mE(ğeQ*[m 8dZ ߇90:Cw񑦸QM)VK~r74??6 mhGRKM_OMl!"(??uPw?nP:,JnUnW?rj}L7d)K'&ͷ3~(emK ^1 9Z uʋqtl<4*q'S܃e;)[4BL.Z.soyE)MݒZ*{w)N&|Y]??T9 +6[k,ֆLQTZLnr??]U^6!9t??RτFx]kepH2\Vs^88)o![|Wf%GuGO$PzN[JU ZE??0]H)"Q$ɀ[蕟X+4OFQ8sYMyS@8er%@D +#[uNb@lKuF\gܦ5Ic|VN -ڢ2]OX>?n??״V@:g&e0b6C zS$yU;(B>X%Alj?nhdMKIICZ??9"@N2FۈJ]^Y1"4t?0d:dNsTU?nѦ[g`Ú.-Bg_VqGβ{]r= Lap^,ϫd:f&Ud :;AE#{OsMnx۳Db$t"țRn7f+D8RC7N 4!olY sZN:3Ep `6X>oO+@F8+2nc$$#?0 a*li7'V1ʻUUTMs!vO=WxDѠG8BE_BFQi1\!?0ɒe?nyGlM+CKGrnFx6m-ޮGclN?ng*Ȭmтih4q]QZbNV Mm,'F0OTOʁ9Znd8C7.&WU(&M\E-M<_9ߒm¶=[?0a,C.@Cܺ ,콺Єִ-ՒTF??/TҶo~rs8u=[@?n|*>BŤ?0/ x7n~??Xʍ3O|{aȯp?rꮕ*!O]Z!U;#?n8mtvqu5Բ%<-Cxhd&?n^"(,MҼP$с,.{- [??%5Kb ٓ+ΘycpLZRbџNEuAj8\{ဟ9څfM!'ICOIHq˟hl(ݩ0Gج?? f"{Zɜ/_76hd;SJRqei8B+!9d??NH2(/*TvK=H0beq.t/N?0X,k&D*Q0ѺpZ 9kpL75wG6eGkI#N 㪿l,Aǁ `2"[&軴z7 P1b*/#/5?nᠪc쩈:>LQ/Oqa㑩)u0?r[`ab%zLC#}*KQzhpRq:퀚i<6\kRk&6uf")%''E??t:#<E81a-Oh%w38AأoFf!s`utqkb~[H憚L嘍{a'jX>{0sF]H;Σڀ>tqOK[7kn2մ qgSg3[0-|guW6e ^\a-ܕ '6@68H1d>o;f@#xJTo(@A>e~{;IWjkA<;דn#ۂSꖡ543Fk",X +;*w* + Zc._!J$9* /Ol7xF2T,UΚpRϏ3#F@cXWeJA[aN+#@M>\wLQBvam"jhRŹ#A0ఃqX%lHț Y-Wq"L)k,;>Oz޺˅>(C??p/G,a-5.B]A2S7 n69e4q4Hj=27Eݳ!?rnbA3ӒO;G2l*1 ~:|?r`?0?09d|bpQ+nS}*[k'?ngAh>Oϖ +ΞGASSkJX;%]<ᨵ)5J5LPallT^6S[w7k܄15)m(Vsc,* B/ۘ!Za\cev_6s:p @e4v&y7u$}Y)utS/M?ria y}rÍ)%^R>@~tO7u#|6F?r$!Y`?nVawf$ZT ?nև,0?r?0YFyqYI$jӀBˉ˔lB0XES_4=&q/8Ch#W3_G\ q/{ː|An(k{k9,uu,v]c1kUsaޗVI5Ow-rh 0 FU~1Е*y.=6-%{յd ХeIBg7S^gT(js WF7@CF&lOLV^@)K*5dPn4㧋Ѥ%zQJyL~?n`_ye8w?n&)U#ԕ[4,Q׽Y?r&Gd*|W8/)!Y%cLj?0J.[>4.*#rm1pYSjC%R1R_?nF<Ř5QRLiҸẳ3w"HnPwKvs??!Cr±$_پ?nB!myŕO.??#rGƃJzUYQ\Ls^`>-?rB{T=ʙ|+P=$4Yܐ?n/pa4M~l!D. tZl2/9 2Mi5Wu~?0؁HoR`ۓt?r-Ch&x7m^+&񟗽GQ$>Ƌ)e!W!/?nJ??&;860ͧ-[0O<@̾wHr#1Im=|+{v0Q ΤIS|^ ?0`>ΈNї0/Wy*;o|+ms6vձA[3,?n''ԃW!Fͣ&e-:.R}(WaŜM6l{0ZW$V67R5ӽRYd_?rtȔ}[D<_?rwPp,=y5DcOjk/Zj+ЏzxuKߕGLvq۵G(mT$(M\obvT>x?r˸g"'J]CF<5?0k2عġNV#=>??w~ڎ??l1\k-IQjng.?rHK(@*4}k?? Tlx:|f>l Y +#[CY|TOy-*[8D|%E^HݷIО{1yvhu+[})~n`n\wQc̼OR?nMc?? D@Epֻ{{t|ZNn??*E 4k+Bh6 3|(Yd7?rQ_*׭6N\='OhX*nTkw'tvcQ/ dj $xqr㨲??{K}ᓈP d>i0kƱkծz>Ĭzg)9Gu^<cv .l<~Ԇ6XW,Qa.|f(_q.[PmnΗb[ HppW/BXhGR@&>{;}~%=?rllBqo?nZ??d=S4fEKPa٫p\yi5&RƦҞҝS?nOs?r*y$u;//Fڹ6B4I'ַ/* }X7 v)Ruv \9ۦő_D22w!>d#IpngL[qnD3UiU2\pNVVI0Mr$/?rl=NfQFO],p)=:L>^btzK\;L]BlbBx2.ňz6Y\d?nDG`ubbH3QhTғ$⽑;~pw'Uب*9uSz)(tG5 &AX2 V-?0xGǧ%w?nq=JZbzk1tAqic.-r:-ac*زOAeĆ4> Z` u۽&9^T#-CCĈɍ~ٕm5=&ƠOһщNsӥaQwHk!_51|iNK.We?nAY_ŧ =cqmJzBبK?0jfRܼ)tv} Qmh]Bzpԝ?0MN4bf@HC&v ,'ڝ214w|z/i: ZA&#kŚ[!O%/Oiw(yqL{$dv7j^(ov,Ai~ iè]l^Q&S\vp/'C1Tҩ19Y 3(B 8wSQ -J?0(F * I=+Uw?n"g´v DW˽\)9[J3#ܺbc;ƩP!P/?0?0<́@IHc?nqCv khq:2͍c,0hfal=n?r$=?n;,0 5UN?nV?rd_MSI(l)\BOK?nL ]( g?0j!SSR#bypbSݤawOֆߍBc~X4|LoD|={ݑ}= `){FqMc* Uλ0eu@Z ]Z"kdeĂ1^c9/hf]Dsel,x??ldB/r2y@??JOqdADžpw|߂8$9= /N珂XZ= Q {k[o+.r*6U6md.X[tmء @VbsRqV.f\v[l?0Y n$/\z*J*9rF 9?rr!X1~~R'6?0]`E],@ӹӑd}?r>)2sL+ق_dJ7ڕFnt9D#I }j}gi\Yeoh:n4\}DɗyuV?rS#\2 +8B.zN 8g4tgxՔNp=AW;R@輦Q1$)Ww,ـW.rf,S&u}n0CmMn@D+ڮ_R_Y/QNZ P磈B{z1?na1as??Bi.ہC/9OoN!9mh!UMj9?0Dا w3gScͺήHlfN}“m*$Pv<-:W[uERJ/ ӶTW0*-ZKAO`5Tk뛛摵yc.9$jJ[` 5nnʄ3sBʐΔ@;Ѵaay@ѷ dL,X_gm)$;c|jJOE>cP%Md"?0'țh!Dә5&F_,WOiP#-pFAyo{Ex966`8-fߢA2?rPoN)H:ž?0mZI7wjm/v)0-)BOm ?r>ov1OY,8'GmOO?rXpl!Zv˵ :X?r}lw0?nnV6i_SxenCw]~$?0뵀#,Xz$h n;3vr0)ν:7ᛀGyȿ7;0sd#;??TWNFӖ MS)8bZ"P+y:,緱;L>];wHŠ%gT.///|,߹<2kHH%rr~W;Ԍ'F't]meC)R#G{?0瘟{F?nk5յ4uSܗ8ūc B?nI"|8}}mF57hTAydksA{= Q<3U>vSW6knq01pxp :1^_7][\~??vk??&>,|,D~涴 +#`ꍍ3y<^nJ4F0ل˷ڤ*4cZ fWv|tչ+m~?nr8R~OT#BT&0:$_sά2 P>MU}&bؖ@E!nD m`Frf!D9LR5{_'t;xN/"g:<~vUpqgе67Oo6?r5?r sGSܳ4OZ3Yj֖rA>g?0}vHgSB0{25x4>릲,}pP"PY91dBL0kUp$֦h@L54˸*ba7d7H27oܲʩ}8?0+дo0]DVPB5SB.A3 ƯTӅ80mD2-NWZSs%VUL_@5#F^,|fh\AC "+ $|cm=5A_ ֏h̓$/ M[_5ZA-I?raL&2ڟ7qɌGU'E-"8-:̡32`{8ynX+!jZC_6mʧ\T⋲>8Aev.n0`ژR w/֙UIPp%?rǗrzBl67͏????u C^&\;*\ t ނ/` ޭ{1UX3¹ckW(9#seHL;:gL\-;@ְmW{TH2?r+h$m"C0y4uTHтAߍn.=ފE5[pwZMٯj7|옱DrIX!fAC&J2mM?0w"ZX֤4~0ˬ?rT.-#ڹMy[=;1;f rke?n,v?r7rpƮ7  C?r-?0r?r?0̕fVyaƾ%.Iy)&`l-jw0I tuX  P>f/s'ҖeQ'/7Hb*Uoh+blydX}8(T56'oD_:TUƬDkt/QĄcn>AmV㴥rNrQ(cr5e̠Vj<է v:a=6mk$~(:]~wWqc??A'$:#.aiҁn<~Vͅ7{?rP???nvxb6P>5y,Ex'?0:|NJë)13#!lB)ny>3[z/iV{.;#?r$=?0mGm>ĐU\-&@F -uywg%[:f?r P j]yvWrUu.-1`?r$4EIfYvxEIݱlL8V;/M??tr]#Fqaq"o!CP Sf)5+1L"&W$⦔\UBw~m<8ii|${dI;0L83Ogi8$m^q;%<;][Ud$#PcD퉆UyR욂DF XFH=C5C$MC}^TI%UsKgIJ6%kJ9e+gDj V($Q; ??t>WDcrLjGΫ6-_??5ߓ# K"$ܜ2kN7Y>W?r<#xBQo!̇귙 K&4$h=tF,DS_W= jSmcG`myUH??J J+9j-/n4TQ< 7Q4?nBL5[?0Rv #Qe-Q<38&0J"륫ISq$rg((.6F#Y^?0pu ߕ :22Ͼ?n֙4lȩn `2Qk~gڎ??p2}.`x'LDK??@U,W*~2:SZ&&) 9ʎuWEuPl'GEDױ??ߵXUՖ?r8?nezT+:U$k4vѦu?rʔLDSHGYU@pqQ&whJ?n:(՛MkCu$HW".Z??I_24EUq.T.":VJΠi Hr?nPUTD5#S:i=*7M:FTB6ͽK>imiF$28Mékt,4M\T]> <!2h\s'{ot:@-_9~\',,NYgSW@TM{N+*Ra GܛnF>`)7XAi$:V(BC84Ky[K,~W:(\!(\jd-lE:<>*>LqQ?ryWM[iEe s%~i݇}`?na/H*??Q`S܍㍿u(Ɣ#CQuwH.6 +#u2J¬4L< ɑ|C—ʉ^u9<2?n4IXLtV:㴱1Kc/-.bëhFԛ\WB\(05 VTkFr*FP9[lɆvB݉N8hY#d$4&8# _&97^Y<<ⴰ#4%"38]4t+Ύ)?nqK5Ù8A5b5pVחjNpi%+=??8uw#P?rѩVdX?rL7wT|!U?nޢJ}Hsu,?nĂ(%sYBྉeì]&P{0殲B?0\@IZ~KJ Q{4F&Td> :pآzLk##!z4wIEvKRX(^IJ2DҙVȐS݄쪭?nww!f"մ ^Kyho]cDz܌t,gqH02_{yQ6-9ttTEhPqY0nKnq*%o! fcR)qr6(sQ<'??8RŘCZulSt2 |F,'6LKϩ?rҡm,Db~lPCBMSjNviO.nbIJD\w0{#>V׏5‘DΜ*fUD('5GlHp9SR&aPB +#;>th4Ho32ROf"!iH|S?r ͑lіNGR]'|C\~BNVj?r_|?n?nVE;'(7nrSG^#Ts&$?0pDZa|vcpR T@;ՂC/?rnٓlq'=@;/FڏE$5JM}JvB'>DEkKȊNAZHgվf?0&Z)P՛??e$'+f|.Ab+ ҭ .u L?0rB6FoH [`.!JM_mCHvPs}?rrf,7ۺm4g[Ob{jV7澷O)ՔP|XOjbtU^??:^jaY$I֙9\]L7IŦѮ˖UțYNF9vmeM4TEA=A &I4l=n0R0r(*NJ,2{'W&?0@T5͔`.D R*pP8b X. NcSRZ_)O6j ح5.Rۺ]8{s~:):"PDOބa^~b|y:F4,Zu ַQƃGjh+d5C-[0߅򷢀*({{B{+(U8>x7Q -~V]IᬄmM_|9Ago z]1D3Kj)&|HD8?r"#S)lLڮ^fZ~IU[0Tr3sc-Ny2i4)?n-kpK47Av;uUEIF命H??|98}SÉAF?0㈘!XK5,|}oSL ^oObmMk=֡PgZ1A.91E݌7YяFUkWWuGXLlI:64^uѾNBH[uɈe1S.DMY_)ٝ1;0Cb3CjDwQA'%P\0\s~H#SXRy?rbGѯTT}'ZʸMbs ;( w*= a>FJE%.pM*b*Sb[KO ʕ2@{ '7}RO?0?nw(!G_8;@OEsW%bǘhN3J*2U6Uf 6ScSu&|]^}g~ϔ+t4;o˝7HopVѭm|M_J?n\+l9pe[gZTm28dF1H|EmD-WjQ'?n0ibQڦk5:l1NHWzE%H(*]σ_,(|k9kξDw)emG]C;j=~?0IlݼsV]+Uif3Q,݂Zۡ)0M9!,V?ri&hPt{j?nbAǞ3@i YFQ|E\Áz=6" ۩uvHvY;rOvy 9's9|~zu zLQ+e+^6zSͧoQB;%3Ndߖbs*Se?rFӿ-̻~?n)R|؞w烹߉]X$xa JOdzREs)ma+:Ұ /**_ؿGi$`i.`rے$v|?r\q?r??wkbCS>Nb#??'9r \%S]7BK*,~άj:?0bDO*þS?r!b~:K_/<ҚGGRruAQf-_ؒLہO8I\P:rAQ*[rJn OdRWD(m=sEE&\iJER}t)}HeGOѰͬ7Bh=a[#*yzd<>3Z"._GQ72*5ϥHZ2qN֔W.7,RJl^n1Wn}Ȭpy@&Wy``\?0ź:?ni\??nȞ虗ُF_<'\a ^^nQB/;3i{<|w^ċn0wz fG(eۋ(oThNXǙݽSfMb*V m@٥PxZE$*f?n>ڎfCd-΅\|G晦CqǝIɣ%).ɘޖ?03bAjM"?0ǿ5eQ/<8Atqb6k%{sj4Vt*ϳI-θj|ޤ׏R@(@<%;WW<P"74q3q)‰Q|RGJFY?rAGMkC??̡pBLBov߼p8FRi!.JG@ä&:ThҶxƒEU\Մ# w77 K??}]ᶄ\5VZ7":E4ITB.B[@k?rŹxS]\ciVp`X$[tHHABFp_qS]"eĉV{]IZM]pڈQ51'1??t5>d4lpuCWuclb,;TZb!gd|8fχtaR\ ST3Οm0_^[|=.>|u\e HPO;7?rfj913p@Xlp.(^aٮ"9QobE:;nLQ[4*H!jSD316Uhė蝑ōby??>_G.>qpL=. Fx?rSorȪTV3]! Ikc")m4̏.6:mj \!'M@FW02pVįG¸ł09??i`ٹúfP "j`r!wu~8-|؝GTѵWk铑wWE3AtXosa)0j7T-4 l|k50ॖ)c>rRgYGngZ#k`E6UxQgTy8i7`ֶ:Ҩ5?02q|Q?02iTzX5.6DPW@Lrw88L@3uS+DP(+/Jt!`j!XRRɓ+he}6eL@&wx46QQZr{9cw *"D .^D/kR(?r-̋Znoy"FgduV?0q5nH-#Hj 2QnoBgElU:%t.Ǐorꤲdr??JkHn"{o,ks vw+??oSpxDJVMjceO??/憛եO6S ~u8G`Pg%wNg-"ee{ K?rqEetURF\}p8lJ|%&xՐWj1bMڍ~`ͣ9ogy/{[gAUDGWS%6:nB,IBX(v9)i-#n#t{ɘEJ?n>Z$s#*4Jjz8UzphI+rPFoaGRO*wGLD$AW~b9?0 acy|6Hؽ7GIGDW͓eDu4ognY/N%_??`qE;>%U̬s0|x??j&0_>4jYM~NzZv6|15|֯vC$ó !s|)u_f,H|~Y*̘#i]j_0edzq㐦4:׻v,P$%YrcfKm<}pĄD"vWP cFwgbƎmqv3w[=&W&,?n?0e8Ŋe:~VQISSIDIwWlpؗ"""}0VH}$QGUHu}6/Pz]GtH?r' A.$}ɯ:9P:t:nCGw`F(hS iBF3;Okk5fRӉQ +#0_4R`/(jvM/_IB!!{',͓Iqs[DdW\/'- Γ'rL!!@?n4|RS@n:,6ql[Mn2k*8IϾ wY2p`Axnɨj7G7n`0R߁\ڙZ}-'A[Oil3G`sZ;G惹@Z/faIJ\ )}}{=>`P@uEgLQٕ0JqZ i<QV^a;~Z_xq ]ngMI'q@d־O'f'c3$3mvt>\N#\R9BG݃ސz1.^il5fγ8Q!!!صᅝGf{բB4_nRa{}ugOO"2kCݑέ,Nv 7AP#=HX5?n(sA0Gj9]ݠVk;m?r-0 4{Ԟo)qj0B ̨ϔoX?0Zy;`.ʑ |H ??F\b#6-??+>?n1"rn׵>k??l&_PFeSj^OxjyՠfZ-3M߭EE:ǯ}pZv=pJ?0䀻H?n9֛Ta(5PC@[;$y&ۿZ\jӂ/BZU*|<62j?noͣ?r++Π3Z}{|' z?n\ ZIPE #SЋRK;,QE@qRlֻ5I{V &*!cWScPE+ZM &J]rـZs}k?r2=WV}i bnBw3ӱQROƳW U{Q#xj;eЬP$6Y]͗"7Ak氫} t!E'b=lzAv0S|=uT`Swj<,Q ?nxD*[ށ9 If[?rզ̃9rHm(8 \ʛDI800G,Eb._^X?0! `c!"fb4Ft'#t#ӵz,QU-sJ(75-{߻{Arȇ?nm>voQU͌)qNV #Tіj_=t| ^,Lju])?n^x!ĊgpjB;š':H)J?rb\AT:wU9BX)5/<0L`|GX.$Tc0!CZ!L!QmmBc񴔡UOGb|8#{Kr0N(kWW,[v?0PwW W?0. U('(?0۴|VG 5JX'neQ0G-V'z;n?nYj?0Y;މPjBؔ̕L rbyU ??/cxTuYm݆){?0 6!oF)^FYvSD0cܺ&.O (uTkYgj#2vaM4Do3h'aK&T2X))f4V{#7>V,]%@0lg"Ly;P:G|!:Fr)4\i?nw[ᱍ??(6!Ŀ&-_KHS}^HUkXΐStWEẂ3@HkEBcrxhx7Sn~ڻ#ݦ#)J;HK'狦f8?0c@]#P޼?0,QUO8Wݪ~~hG|ܻP1mmZsp\>NRZ}ޯf]~:0\)/rn\4^K3@=NRvrn"9~ L@ڳda,zN u6?rQӮ bd#y9iñZcAtMg/nܶrՕ W^.lEKDU!/Bw|r$h rÔ" :e X=p{$F}4p+-a).븾&&FsNm`'U1.˦AMbӀ#ۭh+nOgA@,ML5oAl1l9Џv*lқܐ]xN*,{v[Fy*2FvW''DEon7ڛ4 {|w78˃';`˕??rX\\?rњ2)( 6upMQLr"`6 Y7?0v$ A@??-ƥK)|+F:plIH|dt`$,ѝ_2u[+`N_/i7Ma:0s[톧ҧƜH64l: DsC 8s?08IsIQ5=ɗA ^^K%=x@_ C%yu|nIL-^8QE_DWP}kW* o7 vK"R[t rrZ,qeH6O%`)㜞s'?r$dD$H3"Do,þvZԣ!?0c'NW{o6_VH0L]s"NH4t=A{"??@Xl$RrGȐ8ɍV1Xウр?0&gbe-3 G :ޣtYW̬}gj?n##??$VWij}\=(+PZi#]SˠF@~XsWw"@RiOY~0 =Fٽs9T'R'kܚ$??ȃo؜???0Otlw'ם8,'s޳A#`:܏ynސB +#Ʒ1?r??^VSc4g5,Oly<(d="MTMÈ~v8a@҄ ]vfΚO=y":??6F9mȋ"(?n:VXRyj(r:?n^T#ўBPVf_ߠxٶ3e`Fx[\ahj}jx% a!b0A?nݗ% }>>4{C^˾\*!R,jTH-ܪPxăױk~d|x67Q ?0[6(UM/~gC&;:qUa?rܚ[8ksX.7UeM*n(=mb0xP c@0أIMmhW29)c8NϺ@Sg^Wȧp!1I!?rQ Z"p޽"2?n!H,2`f?0H'ؚ$T~=.j)Z:5҄r^챈 m$v}I[@Ye3/7ݐF*)b 3wn "8,s`.3&s%ã496U밮SL] M݌̥(op4=(9)$aNL4 hs d=W0p"?0!x8ȧgoHy3lĢm$E" _7K!8v={*f3 fȉ?? yS3"La+Z>nad,~U<eA`8JL')t@KXOڟc W/A ?0k"dv1dPH~7A9FQ)p)n??hA13?nGIZXe+TKlTg:a3?rJ(xh5凷L8InE' D.󥾯 t-a_$m[|?n\ܬޟ?0|*7gf??^@Zrhmѵv-d0?nőG_(j9Cy$1qXEĜ³`O.%φ꓀Ϻ',{R~}u3b??Hҙg)UdT߿y{e_;]R?n2Pb?nb`jN5t[FqrNDXXgq"{ph"ΑHvs6~FXw2Zgp7ղ!f->iKy,pyCAv?0F^=6&~$`>!۷8&ʫfEYyՁ??[_OŚY2'iRf:lGm~!3ړC27WoKfv Zy|y̑td6??9NqDV'[!ϡ=dlܞ֚jJBW ?0&(2 Tq(Sq^z*m:su+3uQlryI(~3ZCV+j[t??Ĉ,< XB.V;kkdqp`\erP_ 36(Pb?01C$vY#6ېP ]MJ^T{r7F듦7,䤱zA!d\Pt ֕[Fk̗y DW˞j?rU<;%Zl!>[ѲO|RP CC-?n|8˕2АOhDёԘ-;:-]eRuT2y,$nVd{HRXۺi8G(vcOsnUQjr*Pĥ/x؝ nTuj"dCsI2 -qp5a'l&?rA (1~ w:BorP&7?0ZU6{;Q?0,:?rnE%^Kf"ѬЧN3VG??BRG:;i"]Zc<2@g*:f~eVTf2>w\. \nrOP 1SDrmpcC^Z8|s)y??ׁ!y}?0U'?04=@'??0ߗAc]PWGxNʆAY+Ri경ÞDHKрc9Z9;g 4WZ^b,z:vNb)M`8a0?0Xa> A뎝 P`k[șqm)SV4Yd[8kzw򘄠M[_??Hr|g/ p=5Pp}6ZtHEfMݷ]#E^̄?r@[/A/p}SDUjp( ѢgpZ78D[ѣAU%1T altJ;TI-n+ Q"eR]-|ZXbv"p%b΋Ԋ'q_Ƨ?r?nQs[@1C*,M&9?riot5|G79?r}:t%N5_!VĤz\TӚ^7_w}ijF~!2b^&DĴ4qC 8P9ϤRJ&Lm Ѐ"jL"w4'saH)ɠQ?rK,ƣ,*C!E'I{UHQ n EN|-k[ J$isє$>רFz4x[ʈKAkgwG'??a?rocbN~S>gV#{r(?0-yֽ_ 7“o^V"C[A0r=5>nAUi]W-a끽Xwべ2FH)>hf*bܮ.ctƠUuV 2LT*|/EQwPWZ3dųQ=Z^#5 4YwSud#8*WغBo~Mӱh~v~et0^SPHZmaUV7S6H&>6LvK0hDk,MȊvY?nv:FRN]* ?0\x*eVoxcv`:6t|TksUhz<}bvl 'S *bJ*4Ҋ3q${lqp?06 ݺdq|+96%pED/.E^EtxAh)J?0gOl FI1'Mr^; B%Nu4O.wU?r8NͶ!O(؀1V*_X*x[В.B>Xm?rH,*D 8j'TUH1_Gdw2{VF+Ί(,ۧ ??R+ɩ` ?n.nk?0 +JZ{F,BO7]Hi6]g`eZ%f.;͟JA.W0o|Ĝ"iZ!'vv~S5* Ţ{YAPf?r0_W ]݂x????,LLv~e???nQ#*64??c^'!`Qk?r rT@qlXЖqjt;gaD_"F#[+k2??Qʴ6^A̜>;iQXRĜ$lY[a嶂UDz>t3BISdDmG'JJWauRW=2]P\Ak!YtDQ hn&n\?rҌLN1 txV,YC뻱*x-_[X^F75Lr)ſRr&Wu8m)L$8)QN*͋8pGÊ,5pV؃Ub` 3B@.;^?? u%81f\]!BUdz9[Y:?nl3/7#HqoKWt2f+plUrSWR҈EDx9dGS^ˬ\SQ1)FP҇#xط:HuPeo=+IB R*t2<.8w $2$hT]ä,ڵQCit vCZBy>O%~0zVΤAfWm *Y)8# ç6|,%.€Ad?n^=1תhJˣӕx ?nx'jXA#,"zbNnK~5mxnA `Jwo*Dg|bJhT!4MniRcuuʆ(/e}v ̽qG̗fG̭2*e!&[tr;d%9q$oMm{(EO{J+, Ԋ2Ed=Vq}#Yq"[ΜJLT\J?n8Z/nx?0bw 3-Xc뼄ھ??ړ1K3wR9Sl5 -"UD׽mg5uhĵfwp$شUt{x)xm/к#,۪5]'NRwph]{ V8!\5zYJ@!:j`SG}u;y|v]"j~(.gh+`A-%{&`NgZBL݊˾ƀ6o,).XW3\-Yʦ",^]S+,@j e u?r*-KSİ 8P(-0\8E={@hc]]u;T& ~S*n|B6&`0@͔i9Mf_wEx`7I\T >|ج6!jR߃1Factd%T_h:l$btP"֑*ݮ,*kTys3(J22mF-FjX;y] ^V/nw7=Z|v&1yRC_fNJ勓7Z %hSX8 &Ofv\SetlNY??LH;AS[bL?n@n<I?n}fOupG-~4cVtFx$ XnQꑾR)tҟqlѠ>Z{4Le@}S+kQ,Z[WȤ}8H[sݷ4?nN)绥%M@fbӄi'c?n)pjІ +#0g YeiW.'#@CSyIS-mn,##A|mK \Ѽti{уІKMBih>[e'@>biU*G !&KKOg>/?nI3?0[J*SRrZRi[ ESs x?r$e1TmC!!QqO^|MȳN?r7ܥ$=.Oiuj.M9^3G Vk'|AkRU?nfLũ֍8 H*Sd<4[WSR4fZ$a#KLM?0Wa6'#BYr{=?n;xIfb$FRa%OFP??}s5Z\㓸uZl]y]z;x[J^h/ b~uGsrZ#w'׮xrdQ|D?rSO"%peq%gLv&ng9n(jydA5yg&ŗ7Aqlj{M̵k8#e HO\ǣ/ &S-I[D?0Tw 2GK\]səGDŽOdG[?nKKz#E¿C}F71[7L+ڼjn??K C~;m'C5`?nimSYu4yνf=W&~4_U@S@k$NlҦ|kR&c3ׁvƺ\HuֲyaTG6[ ??!JXp.GN3JJN?r?0g-jo$Qصu2(̩bT4tws~+nvIEi#d1rx1ze!Vi^%`O|0v8|؍VʆU u1kyȪY1(]=??Lޕ1iPQ%{'xL6DlP kd\nMLcn}|6GWb8}/haW8-)"X@WBFSeDu}-Tu.CSy-gT`=d?n&Ep^pY[l@ ^>c\5fVdO0-?0+j8`/FQo?rD1;xR=X!aI-%,0'؋y{Zz6,ͺ аFȋgN[c$ښ?0[aj6}G(@=%`C0F\BsU?0*I*]Tv=맷;wXGXm[.BeR0(j$FTg?n])r :֕/7;?04!̪U<^pGA% uj{H9$\;>i*Ѳk[wPb$&x,ֈ :mBy\zuJTQqJ^0w x ]mY< v\YGvz]YÆPwSFdY`rp5w[-?rvA!r\iC'U??4{&XEaMx}*mm?nJ6~ܻ^NaWuywYDɛqG_@ Pd 9'SAtwĠR-_ ބ-.R^FF[?nڂFK7y2^[GrSE+ >dȞxxu{lxUˏ]:W1<2`\z5j>?0f&N{2}Ւ$!/u0TY ??M!B"];0$$e%YT\13G誄#/w}H٦wM!l]-;dD*oMʐ3_\4tslk"}oaaZۍ_ly6*Hw{w.qi~jNb]BQi L~͡07V!4E=', mnQ6g\Iu73I{?04 8QpO?0dZ0^|Mb'17I=ّߟֵۼ|i 8ӌumT&?0UL!Tu7*0ϒݓ9#cj1 h4$hwzz Z8cBDB"0ȉqR??#B,µSq??ks4UcI[(?rhh$}<]cB??*!\Ll?r{@ےvCѾa5 1b]N{ETܝq. v&Il3*Nc8T`\cr?r_crknjۄd-Qp̍5aAOd??Pl]L$u_ʗhuן::N^;Ï44$볏[>P4 F/1; Ե $7aPnBHҀ'02]GvmnG5BjꔀݕS~I.>k#9\#*sK?n+ 6<Pf}aE?0cf7 Ċm*:n08Dzt^+??^rz$lߜ-K{+ +#Jg t~ۢ1.6t2:\q-`P_{8ZrԀӕB&ždYRі_j|6 1w{J.bEgҎpJC>yJwAP !+o8(hvq=QScM?rcc|A=+B]RaáZMa(ܖʠt-40tZi}&HLM#L?r&sՈIG!O}òw kڮ]~?nNjf:=1밑qB& U Dfb1؏Ã] pu_h)IQxeKr3Ru%&!;XCTr9x^yLẰ7,ȡ%57zFN3涏sP*q I9o5v4 ?nҠaڢϩ6CH"Tv1??(C,f4dUT vs\M)~SRӁ4#Ĉ%.7JzD=0b)L%gG*$lm!BP5M=e𷜾ߖY 7X0a$FN=͈d\Lo*!g;؁Fj:œQ~Dpi.>䃫V]鐢nvh vP^`J5cU>2}hּ{PE:'apRژ-TJ,0Y??*hQrKÏHR`mǗF+\"bZp$:?r=Jg] :K1)6^ ,][t2TfuIאfB58D +ztl{ ?05F)aa*vylP!4~AhY0Cl4&y!I+'f??-aǷ/TI a-K?0vSc"9uWeU^D)?nev5-]K_YhWSTB3OxJg8EM"R"\";D3JV8?rJr+CJtH/ROQ~ΙM?n8JԢ̪Pȳzf\??b[JJFRꪂ?r=ңT roW%U#: G_ܸ`afLfu Qɠ4h?0 kϬb??&Hhm@,{9M:Ӑ?0W@qkrBxjp, G(Ɓ9UAY56iNܱ ???0%Հ1^Iyߓ^0ɝe5t8lDb"QC?njmERj|.qry=}DcЯ׵^7Y#!R+uBm5#qEJip`wRd0'A&Zw.NÂUYF찥$ϙ/B}C lŬv +"ĥVуopJ4./zĦ[fpߠBg?raa' ["Y~/UmݡcHyMYccN|??Q-pzP'fBws0@;yY ht*}Cot<fؼpdu?rKߧ3ee=3Bnb2!VX/ǡEPQuAŮޟMp {!|%"G{Lf Opw5Y|?0k ؄!yOzIaս2coT.-cmj9+AU{Fn+bzM\n,= x`^7ӔǞ}ux$ +#i`pov,Y URP(<m}Ҕ u 5dX\dgN4{9ߨ6U'%|Sg??א>DKPʁLA>o?0}/<YBZh'K"3w2$ZZB \+k^VO@`Aq-/ ,yFߥy{??K?r뢃: NP'wV'V/AՋ],R~(%7 ɂF2|]s{ keㅂ?nQI??׋ 4LΊ%@2,r^k9U7,&G2?n)i (OӚݒ-ZܳShL}NN0??px7M{̨g/6Xj6]?n%MCc=oDPX{u~%&MS!;pRC?0m,;!{EKb/ p,]oyx;??r^Ba7tl=G:zPS):~d(M ٷx/n`ǩArVU[f/E&8!l٘1RLK,Mhn}m*u ;iT dbdErV\ʔcC[m8ž6փSnedh~$?nxev?npt3KչtL4T 0"\ k (B\(\ԔΟ$.'~4A-Կ;lG?nKF~C}DD*X3 !cHcvXi2k'"!?r::w(lO'|!>HoFqfEh`46%&179-5%=[fItEi%at1fjZSZғ%Xdh~lѭNuX?0Iդ(Xeo US./V_X1< ݶ?n}[l6HV/V*NIo_AxK'l_T\9׷/ZulDGOYkZFqE)VLLksT&&rPO@䱡߃se DRB>h|GWx5pgU="=+G^o}JŒkP ub5w?0D- #ZCvtwKbn|~o 55d^6ЉTtT>1P|,';fj&TSy߰['Mu\q< H4HUJDpM*ae#Q{_kRTKXoIF#YKB4n6װŨԄ,YrZel$2p J?nMI4E6NT?rM傆+'Z_[>fZX ǩ-!E9pK'D{K !z #XxHNx4SLQĬ0z%^WWw3:0 ~U3VT79A9VB-8_(9w3}ζ٩h_X[Rk4+B#&g Ӧ-AnRkk29%?nd#OvoQXnvr!L>}^q`8mB!b!c]57gb97ϼ9aY0$Ŋ>^2[JR|˻TQ0?n(gL7KQOD"UM>͇3F9T7%N[529lC.UOBܙ`Y|2Y]q(B,OG*2??x- Ï]+??ɰ=#/S׵[?0JaE0ړNlWƙ,4rSNpZ %]B?0ctH&F7?rDQv;<V_!%\&ٓF[M_J뺋kEl+D"ʼ 覂.'d߷BT}\??FHAf߁;'[+h6l]l84e+M??RySTA ҋ ?r`9+yqϔlRGih>T ?rMl p&UigSVvm'X܆ˍjцS5?0~toHOgQhʌP??|H1?reF>sOd\Y&:h*MalI^jgE}<#٥({U^M{ Cvh3>?n??ܦo*kYu ESœO=H{??RǦ;XcĝE@\.&Z8ݵE*?0vz?nq ,`MqͳrIXi qt¢;qR+I1ɸFζL||$*؍{n̤3 I9 ]?ru䤋~$cEᎲG^Io|џCڳZX>esޞ/U?0c]kGjd -=4"U2DõKZ71##u^)L?r^zgFgf??c,&ʅ@yw><;H3|Y(0s)5%t'Z)IWZs ??=6]81 *D$B?nbgw]+rs#TG"/s?nr(*|5|?nZ%Gv?r%"L(lle m`.Mpa8m:?0-MS (P{$7Ŏʪ>wbfVt)Ih9`??K-eŚ?rbgr&(Wex6c}#BHϡs%֙jc鐏̒*\Is}NUMCTxȅ؎v=58,azw&I(f2hm*&rKSb$#L+t,59'tM.QrBs]T=ł\Su7f"lF+#s??0Gg{F_q#_?n]IuO3%4߇*d}^Vu+6G VW$ lgy\ʨ7&0Yҗ+ b*DgƼnht2d#{"ؔ>+5k-P6,_8B?rV"c}Mcg&U\ߜv7xڸԵNܢ'@-8lޣѽSz 3:%4h5NI"<6I8Sѡf3`.ݳy{:c$qFx%mVzQ%q/]?nԶ#W*<>BNКflOmn;n.Z[qs_C;7ʆB@-75ow2MCL_ݽk?n(MY„;d[tΙS~!D0w>~>rxIuu|Xo P"ެƒCzho{ҏwFPy¼p-l.7i87t^(7rr۷X"J {b@ «5XQ6<+ض+l5f5<8JNi.M?rVZ]V4̐5"ҠPZ .5$Kn ԟ.2υ_9`&H>ܨT=w*e?0psĚxo0*dV{γ??_J^,W(j{Kȫ@?0wkȢd3"}+Xl`g98MZtb=~J&T3{;5aVpDkLg m͹0Xm.?n8 x_2\Iyi74,]..:O#`hɀc??H[O`ْ]}45#;Bgl%pvUeb!S}?nR^aʙOH]*,kP˹4vvN@[}MU"2QcQml[ c<-;zj#~*?nD͍*IcrH/U;!KJ}cs/C^iPvT.8?rU[/c[c7mX/)K5;﷡dTIRx57A7T>??1+ՠUۿռiVMsV*uƗe4GS6?0"M+){kh"2[H?0D9uJ7_\j20{"LND\89Sʧd:z26/]Ĵ lA!~ PrW<>ϣإS0jsN| X6=Ф4:xSZbOǼc:q>G-[Ư Kw,)^8Iʕ˱:\?rA{vW%]=;7$(Js.~Fg;TO~5۽ڪHѬd?n5λZ{7% *]~n쌴ب&MHv@1??}?n8ণ^)Jg~Ч$QvdpC9lo仠2)$EĨԫ M^䶟 u3Ѭaiirddz:dA5&67ѪV]} HSEwbXwio{O*?0;S+J3Cei???n&v@1B!YQ']V+ e|]0Y7R?r:A?n'ÂN_{&Hĕr??OU?0 ?nҠ\?rхcht=Js-Hҹ͆^ tJ'sиwwo*qpQU=04#')U#kGN̮/1c/>7VRbfrB Z[ZU*^c#XU~87k8]Dm\?n%}% :ݮs]ϬEizɭÞydƞ8[Rn?n|p?n+6uu^s,*uS7g'AX!6s%F D+e +;G@+mg-ѹt|cmp<7TeكO&:/fc??W?0QRgR}t瑅T28-/#rgwztpA^?r튤Sj|2ɋI]mNפsF8ħB{%|ŞRSኁLXbVr3nɸ+@_p!-њK?rҙXiFw?ny&׵??9)~䦋[)r!V|f?r9-_ƹ-%k}/Ԩ\&LJ߀z@55rU ө.?0'_kX۳ mH+0P˸N~EpJMO-ULy=5TJmĘ5J ǷG(?0dsQ9?nAO`60x(˔NDSZ='BKI+A&K@ 0'}L 5/VFheUΥb##¾عSW05iɴr??IL )?0rJ/Rii~%ezoR{9gfƩ|KN]#)DKs┬4-{Լ.z=%ʦҐhG2*RxS/Z?0Bq9,a ]39Sk]oFL1dm42cƪ> +#/v3ܙ|zR#*2I2{d‘G3N]Zgġ15ۢ~0^?n7j'Ju=< :h|D(/#4SuY/9I9xi9FI9gŏmd2I?r̶IQ\jڱTXr%O{uq6SE#SA7r@Rd;ғ骲6tR F̎9Lpct~e"$a+봠`yjNS8l[&xtW$ tz@nILo3im:tLF 7c彣x$W!Roׁ quϐ% +dZ|>WM?0 (NyOuȧv)K6_C򠟜_kJ+J'gZ?rBv!-jUî5䩐w17zMT:)?rB B+ Y0y.lVaR^:[bPamc 5Ntc'~IxPomYK4b6vAOj l췇tdebL yoh@:&0_@:B/zM):O:c՟Y=(g0??V%د{(I4eRZZ1(غS~(dUo`Z"\?ry1m\2|Վ:7ZZ{ paq#pF|}-?nbAl}n]B0dBAK?r]Mj8jǧ}X%?nc;r{óڢ??;<\#8s9^-ei99*MB^gv,ӥC]88{r嫝P3O`Ay*[sb d0g~uWKl낉.4Xy*| [v[fY?0刻CdQ?0Ot#pߩor6Hj_huWx@|.]1͊E?0&Yp\IJ2G>boxWҹv,5v,#pRȊvq]'g+dȲ '=o/, ANqvET8sƻvҳ|Enf ;d@mD$0xtOePGBq ynaw=`bD>Y??x+&a\_C&߃ٯ ^չ7Xv:I-4D*Y[^G9(׬}oܶ³EZ`[Ofܝϫ??(~@'KBǑSh(4:q5 d);햂?ne"61_X|4Y*ōH1Cy5+ɼ DCkXPx]ٔY=M uàE6$]]]6­+ɩڍA c=JB#8QΨ%Kay[??C rg-@%׋<?0|hiM\fSSP1aqkCh!)!ׄ?rfSF"y!7 ˲eh n&MoΡ/Đ0ex*=aK b3.i߫b*.qdL1(cj;Ŕ$眅EeafUlжMO؀R`fI(lbS`-hh??Aq\?rT 2.{5i$)P/LąhP+M ZJB,x j[Kl8k=ӁF;?r@?np L(**%{PPh݃#լʡ-~TLj$?n hl&n%ɇZ}ȁu5蜶OPw|Z|iUj9HE+ׁBL4_Nie7p?n%hxM00/SotjeHH*yJ?rivqՖ-wm:mƽ&iB~.pЮ4HQfEI UaR2r%0"3ZbA`?0_:Co?rfVz WuЁn+8<٭۝ް؈/ U>??TnJl|#j ASiva2>Fu)3*%/nttsɪ$G?r^9R;Nc̊M b2:=5e*̃,8Qfy2|ˆ@]?n8\˜s2,L?nT?? 玡W~?rjv>(ޏ7{$PC.*R^.VHK`m5.O6v* YєiJpo'M\??Z\̼A~.|%Da[9o$„FLJ{"L2) 2 A?0wGZo^hop-\Ϡ6XUNc߭$&>.ye2GJv`q@'B?nu svҏ{QkwfvqHծ/c;^!#Qu?0ώ\2h>z$v _gVB޷\Sj/Q<>tVQ??᠆?? XPUqigvC*m:f/ǯJϊRmcek?0v5*nl<lmRtf cpo$Y@a/K)v?0kexTY9|5H{KL_ wћsJp܊vyŘĐSWBΛm3%9x$6ųzEE,S2k-Z+CaL+, ܘ?0F6?r"N*3*3~?0Dپ(OV{ks;`%v`&K4^'fM]ϑQTM_3o,o>-WЃ?0ag.\\a^ @jQΫ_:p `-,|o/_).{9=t'mTu˓DQL0kxE3vI':x5ĭiD\~X ???0Et濑طV-pey%?0er9?r,,h/u??XFa;hf^Oj8DkVr&msEx\g6+Be5UJbйq?0<1?n2pS3 D).B8@$<(p%^ο'b)Ϭ5uMSLж/_7nQl'ZAK'C5ᖽǴeo.~'?rS乖l-):$OJJ!rvÿM_1e ie;`RW 05T289 Ƌ$=@-YR\8?r/{]&y;??z-eRv.!&??pt/mIxzSw$壆jTC!)O{bDϪap?nlیJ1ķ_禍[p:oLSN fGK?nGưo$m$Pa.,ƈV9d[|ɜ\>a Қۙ+R6zQ]]bg9I}+teGS4oV̰m,-ĉ@N@F 6f6˓9t-ENJBnl/N0Mon&؂)vvD;=Kɰ]ڧˀdv?rK3W # SHbitBe*ktCjl펨Q̟D?n N}$̈??X~XF'XGF`?0uDZ7&`R(V??{42^y"OPEQL'0??sګZD /x?0! o|'Ő̙,k}#w~;|Da \D."!FbxXx]% D[09I+eRZ??s6aI#+}J=Ϧ4X@}K NoUszC^-??G?0ݟdt[@G15Myhhektq ß%g0.Qv|#_jВ ٕ6<>BSHEmosrD/c`qF?0wa{'om,6L(`tZLV`$d*Qct=5G ߚN678+-ߦ1n8?r1_20O:QW'UQ|eC֕0KA?rQ*?0dX&U>U6G>;!郛FGiYp!jrsR!QBp09ZY=|r{?r"*XXhoeYHFWгpbPlk!mO1LIZՒQw1kͩa=&jkbѺT8 >W3 _TDk?0yb@[co dv$Ʌb&?n=R2GPA~+gZߘ +#YvZ`p9!ROx4/禑*vE1c64&_xxiWij|),.>~:?nr %S ˔6ohX)?rAa](SZ '+&~O鶨,ld%&mI#)QBO ?r.o!??ni-Y!Z wז3t.CѠ^IeOo&5x8^Kx⧷I)L5^r-J=+;),=5٬tvFif^YNs0++b/m?0FiOKl6 p?r\áD)N9-|wc???n(ngBL?nRfK}h`?r7Q!!8ҞaPTFk3etqj"]KMw#6yV=]ʹω1WbLyIxQrhnj52HS0A_~̦C^%*NB>TT*>uoWvKTk{ L鞹s+"{gq8~X6X܉bO~F'0Ey1e^~L~"p?0BV.dll@N0pH10o"噶%UL"Z?rPf/X3r3{@;Nn1d w]EIqZ2=jP2M/?n?r"^5.?r--Pc0Tf='\$ȿ-OLuQK3:<:?n eWP3?n-#l.D` ]_̈́H&V4+'T|ŕVOaRM7}6_qbi~ddZ8]Iτ ?rdMMKD"V p*ߴ$.zvTP"}ѝyPeVpzWS#K?nj(B)q g5(ZZvz&YMƢ¥gb{hk%bQNpyTr22Jcgmԩ0N.]r?nIJˁ㳗*K?0PBqzc{oD>⊯QFc5{_mo h?06~P$(vOx?re??̐p~Etx}aPZJ(SN1:T`{n$0{ήt9G~.??Ĭ׮}V`3ep36&#g%|@&!ܓپL3|_=`ڻ jUiQcƴ#2J2Snxy|vGO?r?nЙ*HXvJ!8W3-eyh 2‚*r??(HL!EX_n18U$klPt@3?rB-`mFJ((Cob]) Ĥ#̈́ƺmqNZفK|0?nDޓ9w}vgSo=Hq4NS,[ 9B8q%ϡT3WO6 /0_^unuIj>v{xTpݟە|CY2/r>(6v녫ݭE| ȍ2ۤJ??ALdd(mp)ES9(t{#q|7X}'Q[H: ><@;Mo?rC$;IYoAlPđer]\;b\FT̛zW^(he+%5vؒF??aTn(V=0sCq?0{=LU!z*3K*Ajy^ʐYSS%aKR vI&DI[JHn1Hu3pZ ‡WfaK!f9"${R kr#'(/j;w G&1DwjҞ?r"Ayd2>ij}m6# aE[FB24Ęi79p?0Щ#7 :FdS#l 4 >(HfcȭR1";@2ٚF3?rfg9.>@7>oWQQ&uE~Tg%T'.;EWzq?r'%8`"! X?n6ʎ}s{`=Ʌ*U +@HI`݄MTiֺܹuOr ]9 wY=ہmDCuau†Qa!c~Yµ^Ct6OpQG2 nPF7#G.VC/Lv?n9b`;<]:3jdO{XWkddf??oGqkL??Q|RYj$j4?0/ aHW}~`6 t$=m(䦬vi%4ZmiūqZ<}-o ZrLi$_AoPmm=z]sr8v!N||X\'}[Wo .S|؂nc']_\Nga7pNc].]C6S 4Y٤Z^?ncJVOgR_)[5dl&9K:QϑlT<'K8vI@\/:Lh>02LHGQnZ~;2uVGiv6qpjB(?n]pj_2 y?nl<'տ~~vO^sy{Bع;T<uoEoig>[|BgIx~P"K0Gg'M^&aޝ&BL%YuIX7'H3gzJ=zS?nb|]S??[ղ߉ed_1z]DdHV$@_&-w.DajBm76z}:0p)s|UʫT2Le|@I1TDW*\W\ߣRJvƣ?r+iKVw5{MPyX{AV߹Ew]Kgnk#\2Qh5Y̑hc1B}դ 1ۯ!z-y+rҮ՜+-p"Kz?ruH`A41] *+OeͥB>=I98}pAsut!Pge bl_4t1~?0ё!#b;op?0]{$1;&=C|O0l~#e/٨գ23"%Yؓ2ZX,gg4VMЗ,؂oBR44TYPe 9=DX6$?0I "uSa+fTf2s*v4vI(HG!O" 4G!?n7K|?0XGp8RsZ^刺0dۮۜx_ J-^*bfzzx5?0ɬ("xG%Gf͗Jdb?nZr%.x-J=mH̾.±@RLcML$R~2Gŧ:v́2˝ i}mQ 9bdXڻ^m$O~@}W`\ gjBƃӁXE%+:NJ2Kns%]|l.Οai,Х:th^ %D]<+gsdؖV Ճ ts(p/ځ wIF)Nh=kOnH3q"n_1bDWET5]3b!QbGh2.0FݵI.Ά[C!3gr0'XK(+f@d'3r160+=3|/;??T51BGw#FE?nh5Q73223222,B.(uTڳJE), w`b(8kԃ&<hJ03z0Kpb)ki[yz9 ,ltE.̓M[6myI򫗁q:|9ZՅaфqbm$MDֳR}Y o(2:y}؇wiBMlAq'c,81}WhZī=~kv'>O@@ @f [| +F)Nw{~sa:۫{.$qn?04zyTv#V`WXfSڤZDtY?0oe Z~c6& `p?0D1s??#j.ѬV8Lx1x)gR)b锘}N3좠),)Qh&aDqX71*u>L' ) Q`o?nQJDk?0jNBbL(_,$ umȍCX Oߑ(?r| >w=L7Y:wL&&M*^h  d0-t?r-ʨX#7r 0 @Ư0`UW1 ljsnPgx^[H[J??9oy4OI {:݂!04jBU +#Qkb?r2C?rt1[P(E?0r1*lc06hЅR7=T2tn(x?r M_Sۉi'K!ntKCpZPMIYxqpȢ!!sǼCfE&<$Ӧ뀾=FʡI+~Q g܄j[hw[π,ǜu:iC+QzU1!'MJͲf s"1x:4(sBvL,Ԝ,NZJqŽ?n޻Ž75')EDɁROq"oG,Uj E^sc<G1Xr]GRJl@|>At=lK??;y8kifqPthM0"TzGEi9.6PBZ١߅+z??GCpKp?0'|ۂ??u&=zsZg۲`Akb] U8jkdBB#k??"X ~CYhe랥c~[]f$j%7C[ZmUNvРD4Dq^t.54er8(wu-(4pr)n=uGkx,Dd+*t?0H;,-yxd޶jR[joLi:`^Bl n?0I|Ÿ8&۽??6;dR}8B,??ɤ.9Un>&-$fR3􎯧AVZ)Ƿ7dNVM?0Jz|(}B\~ol3iQ0RÐlI&f?ndc gVe-6-m*;Z7@c.o(%`/r8Ux,;UA$=/(9D d鼄 :}s ~P 7xX^ɳiYkwh_O8n&O̍ fLluPPO?nLz}4kB,(R* G[?n`ogW@LB)qLy@?0ʳ_Gpn\.p;\yW??O|&'hۃg*Mwvha&qJ2sOML5O<'-F~aXi0G$zdJo4f82W>}{-?n|.p>~ 3БvNn1)q9_Tz3ŀ.?rلj $!1dgp^Po%݋ [%(gU4U9E?rbQߧ??kG SU%AQ&L~UfFMK%~ t15ieJj{|{WzϿn@U3'5ДpΓ?01!K4 Zl渼hW?0&ev#< GS~L:@ϙq?r!$ۮ!|6?ndΥqZ-F4 A9yu&]ˢB7gZҕP\0DxCp*ӦS_sjT,pX9u&In<4̹4nWM],,a5'k2ϖIo1q5\ 3XKAzkR3r;Y!?0M??FTw?n;KLFV'Ek l: xWt՞SPKbԵ259LQedDƈ6j3j7ZgN1dWd*A˟Sy)nk*~Vym2УT7É"סx"+zA=hK@e󠷾f mf$}RB2q?r;\Ŏ` #SҏdT 'aJ?n?r,s=x ??pf8?0&縂a[yl??j\װ$-,]ůNKKx$Pd?0d-?0Uo.}?nEͶIC?n~P/䃤?r!sWLL{2 :9>^la}Pۘ.)p p;"QS .= spw*삱"<غ?n5B'Jt߽aM|xQRrۼ!f{&{^?rѻo73\cMskzq` C)ϮbwB|d\pgI\i f, o'7%뢛3!NԳKwN,0_:[P@@ofYW]yD]`??]Z3pPe^bF?njMqw4<"]KׅJ?r[T__ӫ qF5gDI|ly,(08/u9Š9K|םWѦo .V?0tǀ.XzIeMBVg<YeT}cHiwBŖ>fb݌ dH!,DŽ)@ctz ""O-?0%; QD^X7<8cv$ ,`;ҫmƸ\{b?0EmPLK3̶5HjVp3PW덓=67֖: -ԨHx{V~F¬ڧM?rnU65f.mԳ]ӏa>= JAùS;h_#h7_/.2(vled`VPɛKcHS+q~.X*퉿I<66!ثy&L>,0܁I5o,[˩R.*ԤoXz8t!ڧτfR/%?rTMŋ5n %pі#p9xY1 ["\09!4F@Qf}Uڿ??1S;R[X2o\g}"3 >Q/KR%?rf1Au#! .T$`Hir6wʎPc5˒@ozP;Sl5?rp)ͨ1mC̘%e;`h?0}??$FCI`TV;;[^7^??2pkB%6)<Đ1)U U-%P-m.3f H̋)].?0ʻ,&ӃH0hg5lt??2 XGo?nSLҸh&k NW޲Tj+tmK??(>og;5i t!8nnOC?0ߥ}_6CR |"ghv6PXr!cJ*5e.MB8?r١3S”htX"lۦX9~*&5S9Xgx??>CCIݚ)(@ҎH IqkTdw|bCX[&)sG??Z"CRn(x,)Ð?rǠX.G>,%=I8 uT[jzzkl4wTX3?n )DmOFC+O`?r9L@;~{Ӛ?0#4ՠ UpY F1Qxpم(muj&HZ_XX/ꉁF[qG22,zAҕfcQHǖFwio[;-=&=z"S7q馲Ua9L+ywZ2Ґ=!0SXEWNv(WGj'!HY++;ӓqHWhZD"??4Yuw\!P6RSs\-Dq?0㥶kc8U!!Fu)'θJb~uimuuᴲ']ܸ[-iԭ"tn{V›M=R0>J5Ы1O1;N w8xk; 2j-r4wr`VGܽWUb$tWgV+;4H%\Z]~?0\-$8nӠE*!*2`,GT5&oV|wS'I0|VzX[0ըFmGt9!bAQa@8P<4YG~M%ߩe/Vˑ*Ip&Wh??mГ$l3H>0YH.C!:<@՗~CjI:?rm0#"h\x|Ą8,??"rA|dt"tF8f?nC <,AR;V gǧ"ې#)r7/ Te|(\;r'`YRo&Ż4#5 ?nqt7(y<%8$0ݭ\U4qd@} ;I>ZxG&Kfd26q?r#MZ sQC FW|Uѭat7vgtJ=|L.罛zfsU/>g;Y?rs؍,-T<)ZyMڼQ[mtC5/zA"DZ3ݧ19--;@/vTs/ʢ3fJL<t=A Pez)kOv nF}hvwLc2Ӑ$|ݺ?r!O G&S;ɑkKRwA74q8}q1-6BͯIUT#MJ?rZe_9.2ipxse1d)u`Ujh\ncv19{RSMTX$"0z?rEAxv Y\:֥~I?nO:d,LCe5-W]_;b2x!PZ *f:"oG]\)\Tt:,8 FT,i.fYTU-hX;1?0+y\zPi;>YS 0+%tp3xl"# m .aznP|d6~ hN\f(17 '`)_{o+ԣ"QR>}ßH0uzvҠ^_(Q#᝺;͹Ȑa[d^&K;&架a ʤBNW+XCqY9v.39Ν;nJ2տe$$I7j$M+ nįZVXӎ7߲ߛ9)Gpt@N3f G?n6t>;Hq@sQmb>=Ne'@~4t^D*kS߆%nTb,1;O,3`ȪIC1m'X.1GxXZ:(9!mhpơлҲ\}*r@q9>t/JڧVفV">/?nF P]vgFm51PX!h*2,c9ryer Eu9"M%xd?r3-3@OJ_'8alcqds(HSe!y^Rc1bfM{WKX^,Z 8rK=<^]6Iޑ-;a<ƙsgSzV?n7-C7G¯ OӋY6Xy(]L\&#Z"?rl -*h 4:k1Ңn_Ŗ-^ v{ Z"&V\!?r`ՠC4?0LK?030$j|ČkW حriOAfEG6Ht "Y7uq<`PV??@gU݃E'*:|c -'xAyqq-|_wH[Fwe=b|6Sw)8$3"vm??P>+T|F\K=CW0.{!UZ˔!K^|}&}Iw"nњvW=N/W;n2pS)HcvJx\S)ӷ ez))q(=^HlNj4;PP>M?0M[pj_wHǖn~4.X c䃥4wD?rFoJ8pT=I-?rTX']TM9]S[Dj$'jN@}lbŘNV,8EE%Qx6$Xe!ROQEqbyokX/Gck*ma[6f@ ꞙ=m:2Z8 *^1蓞Lސ_e!gQ sLNᕓ{ЈHZӂprs&#}aY݃ҷw\hkip?rxL*(6bb+BJ6o"?0}-YhF@[g?n$a뭩jyK5JM5|b1 KZԝ z2Y?rqCة)O/T]#!t.҄@1J喐)2:`":9Ky0Q<¼N&5!ßk/+x$wnL<3:0ѴDD,.Pe Q2)-KҌ}P<ћYgFz-p%TZ00BBpAs;^=P[IUƺ1h?rAz-8?r;<-Z|'KXʩάWVͨ]E{ijǍvҹ< 7]>O/uX٣ݜ6z9%>W\(+tS*9j~ut(%b+Qq6zU*ID|7[K6JK >)}Is}WAs`Q reKE]\Tͻ8Vu:z~2ԑxf4fp~ػ簟-}ܰ: PE<zss\+QND)fUC1n:fRJ(g͑2L$>u&%{F/u S>|17t)12i3ߕ&Ckp UnL&^(?npѓYG5e:}ÃYRmM V_辮2Llơz,?rX?rS> -xRwNk7+hWwUQ`l-]Mq182m|\#XLO&u|KGyIUAV֞xhS-t?n=;BxA5]=2Y& uaIu&# Է?r׈=Y6}c*!s^ܰAv;Z4{σ[mJqI??[K wTZ!>Lsˇ-zKϡ95BKOW d|(?r7*;SɯcUX1;&oAUh<<;/">j@:Fc.yjڔ\;\_𓜩dy*$KCpBKV7sPԠBHt],ol矞[8sa/?r̷h$g犔\(rJy$l2Q|ȵ*Q$̳5Dh:s5e$f-Zb.xZ.y,(5O!6\&y{??g[>K8tYFe@\ܪ$1o`7jb{&av_|GX' BԌ2Ju}1P{TZ}\?rۂm}??1v6:]3<#06Q(d??ẕ7׽[ q^ rT!dX$.ԴjQ.ȉ5@Z[@BWyky-Yhea]P"e"-[-}|1??3sXwbykʊqónK6kSL>FAchztƔhgۍ37h6]F5W+]<`J*ɊAI uh|0lH*W̑L+-)~њyӹLq?0ً?n АY4at5d8O}Fz\Mv/wmdz3ލq#q!Kb d p+6RM7˗j}Nޕܥ'Dق_kZJX 1h]?0ؿT'S"3IO)O/U(.)IV??>3sp%Lu=Q!&T² r[7A?05 (%ܻB*xkKT?0] {o4E]J88*jѕ>}|vllĨXW`[$_۝¢{bUr??}͢=v[ݮҊޫ T??!2$7E|>ty|ړ2[>`R8mD0tDv96P ?reP|sĈ'ϺCvt#v{ü~<(?rIx-b&?rȿg h[EbӝmTEױAIGM)"KR%C FM!p&"@[Sj05Ѩf vac5J$qHP&#`L7bf9;y1J/Ժ[*zW^c@?nWL#l?nWB}ΝM !,rV 6w}>S'K\~[bioQvIKYVQ;Zq-+rb?n͡ڗy[E pR D$%??kэP׻ks#m\lqPN1꼗$u$IΙGV£YZB=,O?nȆmv/<۹sld..lӞ\x9wUaYUBLrըzt?r蛜Q3ƞ9Y9{vA܃eӃ%4c|YGν0fа"_j.>fTU{^+`ڰ?rڳy|I]FMU¶ScIٟ4n,^py-TfDŝU?rn}'Nr\v;&iy,];V5b7Z+VH*27FbW{޳bbIeRY4i Nk0C !&. +(O.u.\FnA=tM),`i_NBaHRpز]}+uԙ2Jon G?rOzn,tHoQxzҢ+]m(䭓+%ΰ(?r5feMz׼5;BE8H&=ӭU&T{?rӄ*#:bIUAi9h)/5JU ?0CZ3㓝J)zOyTXʅ*lUUMwʦg]ec]{bu)i,?rsEPlÎĘ^XZZ6؍$/_0eĠ«hkRFͅU?r񸚳uw;_NnY?nHR +#D :J$4`~jᓄC%;I=*?rkfB bl"n2G+?? +dqx:D7-\59n9"CmۄGMq4s0o|7~H,ƣ%6lYl6@tҸ(Qor#gzKp8=a594,qޖ,fApɱQq`ۺoЧ XY\&>L^`cCx_*؛Ʀ`ԟ +#V cw9Έȃqd>1}jzcփ3nu᧐T! ?rzxҗX`$-?r\ܫ&B~ɺ\I3%0AkH[Kʄ86]5=dF??t$R`d?rpNv`@>A@EG㦳jr/d7?0i<) U**h(ʦֶ݁5?n>{<7}rb]cڞ,%CHY?n7KEx(MvަkrtL$/AB쌘O\n}Y!!CkYpJŬlWby~逈zN*FxH#,zRzMy8a՘0aOu5Jj6RRn~fcc ew'Q3\oh\Ez]һ~m-SK fw@dl7oJ< BϢ"{Xlyapg *Ѵ'y=W܇MyHinB6Ŀ|pC6Fd ;|;G>T sjBHytK)kPcA km@!|sG;, xKץN$g2uF9%?0L)}ܙ?r To?07aCTn,vgdIԈ81LJ0vd\xs/}-;z{}@T[_Z^x(:j&/ٿK.PJ-$Qܡ77 ~$//VwvKtҦv"o |p}I?r\Qӟ!OIG߼m$1,M ?r6]"${X̱j9đ!-ys9so2}_URt<^@?n]7i6f|CF఩hD£AH{< @۱toQ-)|Ogȱ6keP6`ِBH߅Fr0ic&:IJ{bI:RtзlnPR: ':\)΋&i홢ڀUhV25??2dtvcal-B`:9{lu@{]2?r6 ݊5irD=[MK],ꘐ;@ v޳BO;eG雈7_ӛ'ӗZ뢗=F4%3<-ɱj6'_B<@aF041bAr|-2 ò]нsA/smh]xު7"%H?rKWUDZp7MTxNDԋsz?n?nDڣ]gOؙ;~lm_Pk]t~W[ӣG5=yT.^Te,/Bt8Tg\?nI""ȹ)LG>jxԂFoE{W_AxLj=eQ9ԮbS[Ǵft<={M2- j{CuԒ10bv?n*L>vy/z*h!-ܽ,**U]Ķ i-0B5$jCuNhC)K4;(GF#nH'g `sV: 4pT+ML]Y,?r~/g_W$Ƶ!Tx??>hL,$Q58= y`ӣt`=l͸u0W<2u*_R[9:WcT2 7N_k$:CQIK);BGm={6"nƭ9+P?rtH^ŰkOrt)?rêپ ?rDVbV+f!)Dc*۩Nݠwm.}z[(`Py\YPvB\ʧpt֝wwVSJbI(BLؖ|Ȫԯ@2Y?n s֮*-Bf(1<"?r킾cWtB'~.ԀuTc(L Ł`nS8Ɣ:硬!?n)i(g'j!&+U?0;}g1稠?r@ !X>0 ؤU8EW뢉L8Z4=G6^UgqVܸW?rĘ?rv?0ӰitS@a& _1@cUxmY`XFV}O[x82}ϘZ`rC|3uR+^f?n@11L72\lTl[pa`sWSx ׊UtOH^l`ZIhp-4[E-!EQ?0$˹A` D`B"ѡ,fO͞;`r`[7e.vY~}j+trAΥk֭YuPCbK[?rBo+]tĄO0#9#"ywwؑ9H9վzS&}-ᄠ&?nIqG7.{!^*cU>?r*4V.-IvǼ_?r8,c oy U|%nE!7BvN?ntcʼnU۬.Ek3 ^{:6Qr [?r1?0y($(;۱+]uҝEzeG{??5rRqRccUԨe\ūXo,VWJͥ<м`VZ] .LiɇTe}U5Vn8f]IKd%Xӑ\?rM`/ +#uҾvժī j(K9; 2'(~zlB7>;ŅԨVwVl/2P_s#gK-51)5J?0 F1&,^m^%]s,LI??]KDŽe*T6 Q!ˆmVj76:7Z0C&/9Ρ|Jz|NBFYUUb@U$eɺAX$l3rA;?rcuZZ.a%i\`7Esmel)^Sѣ &́N\/O M+\#r?09/3/* hcx<2tg͑.!K'97Ll(Cd?0 &̴@3L?r -aD`(e?nXرcj]X coѥ>Z|B:s.JM[`ZomIǎ>6ax dS"Bאh RC],0/gA7w#U9IqQNƵ:,ݱhLB4iʋH9*| +>+hn|2˦$kmVrl@{?n* S^[$֤*҂9E(d`ԏ%>ӧ,@[v^YhO- ܘ̌}[x-/ H?0Qa-3'+lc@U}%u܃pSRWОA0qTs4V_-sJКm%!RP)n*$ (웺jmX(pe?r7Cl(ƒ"hv~/'Z?nR~CJ<"sѺmٮ" ?r0 2/͋LG2iQ:fL$Lg55j(?00 iyXO]:J\vUE2 5Xp>R}gzwYM=O@`x>1PD>Wשd[FP?nSU?rŎXZ)b*%g_X[33%r `ٿib3"5;mՓi3X@[nesܡ^1 PAF|l0łg;yD8,;,f37(t|mj>꤃o#æ U^T΢?n5?0Q30_8lJ|"3}" ",??hKJ "̦xzb9')DkZi+C|E$KZ2?n ldtIAD^9C`f?n}h3\x^)??_x35/+kP-Whh=wX}⬃Kۇ,mF:d-O] `կ `ހN.y p nmD쳝EFm[ZOv&I*3}L`ThZ(2{Ȅ/KBFDFqqHv 8j͉Q(0n ^s7DGV,f?n[qhˢl$j_cjy bALhْbsI@[aZf 6n]5=$;Xq\F9QVCaDMSbSWCtK͋'"n3y0t?nƇ;ק&{ZvРuxtl_|"Kz,^e??dh*d?0EjKoWu.O]~*49r|a%Őq^>oK5wb{KjFHd|uh pX+eڝv-]>/'9O@?nqu;KB|h",oxOyttۯ@_yGH_!i7 '3?0BݎTe0Zdos-݋-7l"̐-R|1F/ fH|΄tiY??X*,iUCiܻy{l"e\C<^`PV Nf.^Wܿ1cf3ܴ~$֣˺˒h]MX5g<\m2Mz "Z9Ҩڮ0 * 5>]I"Zfi'$z?nc:,DVP=Obfclb3t?r6tϢIn޲t`]xCU_DIƘQqbj,1wx7oj3v\/EH 85Lyzz??dh)_\Keh[m$Rl}+Հ ;y\OMܑ m5s`ǚB:|~rp|r?n|־p"'\FM3HZ `;[m ?0GMEIq?nb(_p2-]lܰ r=/ݪg;:FK|]@kZ5}ӢKm"r`D4$nB=妓wȜڌL}X^"(k-Y6YQE 8:zj">?r5<8lJKWqeפЃQWDEMTH'$C!iDHz񭣧nɒR?n"ݾݕ"*J[9ˑxO-󟙚+0A^ᛓjWc Z"r],{P疣a7x׆hL?n5M_6vl;!U2 tJ|`,M,[r1Y&o`r`1oIdzm&2Wᨫmmm.??MMׇuy=4G̻fl9WMOIpS>k]zZ>n?06C}Wi?nDž3uR??F8-I:j?0;)#3wVm":.ʓ8rS??`~lHeW8^D1i9{~ġ=-EJ*[r~a!3{?rp ?ra (\C\1}xև۶'=-Rޮ4M{Zp$pYcijLM)??#_xA`jtqf`p#P??[|%ÄIZ;?0m?0}—q{$>уnydNnP!*>[RJJՌ{j ?n͟0Eś! /͌lzWм ?r[M<{;n]z>sꝷ?0sk Kf`!C#&h)/kh$8D]/V!gL#֕olS`d5FUӖz*ل6X$&elۚF;^>^˯u\ 0ǃTW*Z@e[ *?0y" +#l;11V}; : phi7X"A`L7n:+67zk:U%.ʬC.۷>*/R,$K;(?r"ktR65eݙXNǫPvUlhk^N2-BG0ywz Moh8X]ླJ /]Y?rXWvkFϲi*jb tBe1=U-[x>f'2)bx7У5uϱThSeԡ&k ]ְMJv|Gb?r fsW:҉9/O&}jmq0\o :/6Ukj}s3|mj8BT&4.8!]o_9-C]^FlF^A领vST؛x ɂ3儲l =e-*qh^k39H,{4}O\ϹS(ҵ,90TTvo6%ߡh?r_[s` m>/ߤZXi4??)C&:x7N.0cR~[3S-zt ܴl>"+v?n^+PK/^XtjA2?0g?0m?0\gvjQa; ۲@kTRS6/Bs9c.Pu$VUK-*uC{ͳ3n꘱.iu{*񸖊=S&$LQչdSTo?0a w8YJ!nEycpŮZfC!?nm>vL!e?nYF;LzYUBIk%֖L!]kOֺ9+~kP$K"QVtrž?r,@܆pAK4sW2(h3e??1vyZ^#q#*ؤqgӁ/wZ`Z3f6ֵ???n _v{e+dHzL#l,(?0?rrf??rr($ӷJO_$|2;,}ƫM{ZIIq~h\?0(rOIk9N>@xk\.(#p}}kM?0$0uZѝ;KwF?0\Zdp7O;ZB8l$OJ@?05Rl"?0UM AǴ,e5JԘ춴1M]#K.bNKk{tfQ_PcZ_X\3h/^FA9Ԭ[96;m)__۵$䟨ʺ;aixt];9LѴfiQ{R%`kV*vtγ:+|~p2z_;'.u>OtCuge&/??_r 3嚃ò%OJS9 sw&OZ!|N05;??uqb'f_\#|VP_!4-Aa&?n!ӊDzť:0{g!RM.ۚ_w2V7+|Y郐i%ٱ&Xс(Ve1Wsaxv5`VJyDFr0kYCnL$7"eiM>C¬3p1?rAQRP–VO3dЩoԡ{L(rLp34V?rYBI6T]\˸TV>9lh zR+j] l遾'ICǘ!N% WJV[4RK~4m\?n6I3]}SU-PKZZ$<O8H[}eMҚZ,.6 3}:_7f]cś$vΞOjl~\Քc0ҦfK+`.@KJjYa?0Wåx6nߣ(.[M]6MdABlԄ`ڎa+KxN6l^9W`$e=Bu@7^^F4o6PowzygDcnN;T`??mQ6s|>wHQ֗NgAהF3=zhFNFX!UR[ܪVԹxn=-} ŷ_e7}OA)xs]&`ǔ,mu'u[ `ݔb/>QٔrrF/EԹۺ֡TC~ST?0 gBP|6q8I{$ ) 37 ݉~?0V4kc&/Ts=\PC(ҮxHf?n>*\+z71??ẖݰ"08ɔ4Dу{OME,)<'[Zl@ /p̏~M } Ct%#d*I@phpKkèŀ9W{ݒW p,#sw^ ŧݓL5UvVA?r.f'??-o싫O<R! b$cCH,0??F [I}diD0vt\Kdd6+n,1jiv#*.e Z̥! >e}5SS?r+q3ԥ1D*pR3}6~]qF@r?rJ n&ٰ޺H*1<;Xܡ;ZW LMTB0<Ƴxk*ZKM]oF8OCRR2OoZ_]̧tHz> ?r۲჉C|kݭ@]qfȌlD)}OFy˦I# sąOPO]%|`A1 t"KZ4q/ƗUy#T3T܏Ͳ@pKj<;$FM$vcmo6-eڥ/<("rz)T'?r;'N5/K9?rS/~6/nRv+G׻eEk??|YєH& :B@R{eyY;ÿMUе6¯wRNAqy~6G-y6rj?nh994gW;ƥ 3᭫S!YmZ}ŊkBaO+M?r\|7s'kĤ0QڎK3_mpٍ[??vɣYMH˸v*<1a bSpYEY1(GQJd"??uf'V>7~~̜W0X,??N_I\ftY(+Zj޾ͤڎIZTbejkc+s5~.))j|gN27?r-=)V!U#NZrhTc"6G_t֊܆LvVe?n&w#DMUfTe 5e#rZFĿ/ӄEHЏ??\#lY~i?rj1ɉ]Ȑ=~{˚kwJ{HW}3H|{G>!)ݍKt/zlONR/??*`~ 07d W\JUr ?0$h$7$@-\w#.Yt2?0)V9l-tsh`@ܧ\ҩdAlN&Nn E ~5p&SWLҀ*<2)?n'3(0z?nZ|OLLRS?? '$[%}Xҗ'@h?r5)8Pv`)D'FA?no|^9>T}C{%?n&s?nӡnN)g>ŐFFk ~$[*id(λpd/#IӛpGA+[#jغìB넖S\}jU+Ps|&W,,o;??P?r {r ?nis7Yf?0,#_eVq,JìE +Hjg´b%{vN X犔Xb)'ȄcTB#0iX&)ԙECZ$K?rfQ[ՌLw:_͗svϹ84^T't??l3*&UEѥ!JQMڙ??؃#"J%9kerh]?nK5K5i-Nś@S>ẙAm2h!zqE=uJQůRY7<6FO{\(^-+(q9?nbT\*~[o?0^xL7vt6g (# 1=G_qAj0xBz`{Bp-Ѫq޿CNE7rHɻ6o &ˬ^QDLpbA?rP\"tϢB: LSjP \$2esFp]\O?rOFDp`* 8C]ԤEw23Fb7rfȱr^ihsl$mzE/fN59owo-f8Owq$iJ c?0cdЀ';FޜFw#L/tVʬP^\o΂4"<;pWQQU?rps(+MdfddkA>yX62˵^AөPgEM?r4;ec|)4ƙ##7A›x} oY!t\;4r8T2Ia=ܙ,+''?0S.OG׹"S'5zm6d7@dZɎ'@ 3HJP^??+piF?0tmچK?rp*0d&RMtvIy~<27?n] S7Κ\H(?n581hE',9Cz7T)J{A"xFIGx!}HSV+S&UT%)Nr:eZ3LAA&C jwq۫Ɵ"yZ )Д2Δ-R?0d}8?n=Ű;"J_VC"GרKNètyQ>3@#^??l?rW 8#"9tl JQD??:Džo}z[}>??oijsD6aV }ʋ6ǟ_SHNkkcHmT!Bq%#6kxpj74p7#J wWŨқ7& r7廦 /%Qz0tuO('̷7gxAW)n~e0tDH!l{vI_?rG;zuVgi&?rOLN=sv?0^,`FTU5|"=?n&Cxv5$VUhķdv?0ĚAt;!k XС )Jg&?rT"a(+?0Ⱦ@7|md2lۨ C-_B0x?0űMd鶵ͷ?rѡٙ\ -9-t$L͸vpp;YMtt5l~$bيTq` _3AGpPN!59??Ǯ$`͚GhtwwPUuVp[??B~&` ;eq^ۣz Bգ!?n#~ůb׀ldP '=<%#Fz~k@SPtϜ7#_"M!zOSשVs2;Apsp/%y`/?0< `z澤PĻw&O_5k4۶IE&PDDb?0.d?n/>0OQ]u?rz@UEeLH2o`Nt?ra06/ksw{ &&g$n1rv#<#so&-0ټp48vE;緓J N.@I0@|H\//9'Sfj ) 0oScsR۵)Ha*";؅q+ĂkO/w{+є->\Ɓ$D=LX8C-D`77J^ѤA(-L))eHPH.M0SjcaRX\́ݍNP^OGqRP?0~ kWTypBXT:ewt¢%LD4OG;Xi)傹^Q$u 6 xb$|Ң#fWf|~kpiJjbrcSvMi?r%3Be?0b0@vLud%U$'6 \W8uTqqD4PcN9?0 E`?n@gtb/Ifc}iK/hcd!5>޵_U;|(pa8#Fhh' T?0>!JOl+>%x&,3sCJp~:C|cCQ T:Ѫ{$~$8rx2ЊԴD/5{gGI֦(??P敵< M<1'?r?n9oo|&ov6((2 hҼ?nY ɗVcP;Y}y??ZYM޶ce?0 a$_J%Fc?r #?r! PSf٘KHeD,}s@Gт^zw))ބ|,t^4|q |L¦TKR5Uɇ>cѬ*nG2w#R"%`\}uk%a+2(tQ:9?r/^) ;Ŏd$w mɳf52H6BP֟GyP祧)rg+h>YgϦH6^zJC7TNX.?npoȊj=7=&\Dg(fTb?0mqҩ@2JqjzfQ]ՅHK;zUGh88SM~2i֭}jq sۜΜZ㛕ڞsE,"-8JAO3c??ϔ@#Ab ;p301YCq$]"ssfl?nG+0}/Tjk* y?n:p)=T#[J|wÙQ4V Ӝhq/Ngg?0p&DZ6 ]I }:|dw_yYzNK=LDe"a&E=&Lul?0 lq(@0yvxT>q??Q)r MCGAֈl2ҢXS?? ?rGGW+iJ<͓Ǟv [~ݹHUX+`.`4SY0tj\ں[L7[`SÒ95[f8mFTX(K?roş#u'DbyM8׌*v8ȹz-,x&n6)W8#zCQ2??*3}fxQ,S'0n*hgGG6ҿz7bI2h3m)eTr8(n҃0 >ƘG]Et6Y&t4bϩ +#ՋfI6kʹ= d{j⭲rMϤMvfӦL֍uV>D\BMM`/ &0RWǢ4Q(H?rF=,>y@9.Ɠ" - 8?0tofp?0gS55ѱ5TnWħӶNH3 eBP/gfUzX\ztQ;adg0$̑QL22C X h B :8hVi1n7@63oNny4 b#.GI*i >J؍wQo_q_̨f0kwI,%H Lrme۹|ҌPjG,2U@ s41|/i?rf n UyˢuJ+S@Uez.jEd8?? ܚٯŮ(+pϺ$*ՓLܥiLN.5nnł??InralwcUwxZB^T$mT:L27Y]:ƹ.+N2OjkԠEڳhXB?rh)k-oN2R c.84f:)QF"^Ѽd+4QOCK|?nfMharZ\)U?0)M~G1ES0<x*e^@LPsp{2tV˯?0@snp"TDt-w{>܏zaհRZ䩼εQ2"??!ARCTf|ВxXe!K{m1o; ڞq(S6}4xrB4ӵO8wn??C>ǟ t e)|W.e$ddB?repɩn! 2/Tqϳ؊ḁ4X6SX)l7Or0j=@TX1?r{0w<2U@CHwd] wLݷ=šse2 &ܨ45#\uG(9f=1c!*Y5z?n^`SFʄH5T*f?0\K0 4yA8rZ|)kA_-H-qp?rJ?0LSr6CK>p-?rKHMɏߌ)[:e FA"c2?0gPy)Y0tRMjEXX0lUV0k&n3Qz#?nMgg2rv{fԧxcTDL*}1ZܑXnjAu4bH{O[_j fŵ\Jd?r"= tUb!|=rP68CHf|T<chs4\ͺwmijwFS=tlc*1SJ K`M%}. ow݃0_5׭L~  VŁa}R%_Ő+0cċ8ƹ[iyT4;*aQ 3r] j nq>mוZ*0Wơ>6*_ʹ?0՜v:RE}u-[|ߨ#_%S#+4|}0S ?ng-3a00uu OE~4F[,9(`rAիZ?n`Ȣ_ǼԆr#OsK$6>Au4%иs||O\5,:U0;WScz+\>.ޖcީ,6b38=u}׬/Za;ȹ,3/wĆRxAb4p'Nf)DOGSЗ lBrxJLtWx WHbM驎?ni55;Vgjj7=4AF2z JaD%Ͷi_SHU^V5pP[+chH.i2.&SիfNqeސNhsh7Q]ؚ28i`ڲlW,%_qˎ];g LQn!pJac4[DI4%ypQS(51`0֠J3ɏ{RsAtd5 ~>៧(hn9F?r>{,z5479ou)-NT *W?rS7:ӧ('?? #s{%BwD ?n@$v[%tF<3o'.A£GBE6Ghz^]qfAU:f??lz/+kqi".sAHuz] PkybzR7Fw&`ڰΔٖ}7hn΢odgB5?rMjZE:16mGΗf?0{4[m1:M&e'jp)5hW+vB`*7z붻˜yP)3I LLS¯,/6׈/>`0-pYQG N(v$UcN?r#=k;x·́ O6L_Fm8xƊ;n4z-pᆋV[SeJU,n;nkҀZ6?rk @?nkb'Vjm2NR'?nJ"*%txMP{_{a\2Vj.i};k??3@v{sgܼ??Y)0C>')sb0h:;?r9*.cgϱ떟Gw~KcĚ"8hi˧}#dLifvC"3TC6{E(|P6.sdv;R@6??|y`Z??lקoKj(?nkJ p?0}Eyҳ%Oo>n9?00;IfnҺtmQMQ=L%JE!E?0Tko˺!\u'fV4X&|ȃem;eSUmex)SD49QNoF^JD'SI''no(Mj"bQ n.D{ LʾzkH2n!-bs|F5ƟxʼnnIN p0CGrJls7ĉv m?0|Ι: yWVQ!\J X).uΗ}-١a;aZsWr>%s#x?rX??ov[1x1(_Xh,Ch/MAk?r,z\A]6Q}+!kT9Zz1rJ'vDieD9J+y1ߔyN7 #dz.I@>&.Qd,+1N4v0vGi7DblZ軻:H%n3,ԡzСH-M܋ˆ(u%Hu6Ewr@D}Z[tJ#e},,{yľI:4G30g=L7-eJTbs"㋥+ܞabhmy_~3.zõU'R#ƫ1Pb諠L?0W上춿NuKQK?np/$0?rˏ?? F zU*Uti^K LӤDd=A?r~Hnx2бnj&T z".~%q^nJ-'"lׄ.e˘ !/YN›=D=ILa9Pp4?05= W$h6>͈ 2 hlTg*h.r=A$~USAtAmf^WjД4e7HWfVCC{l 4@ Pn@CxhލˀP;{ MPҿOW lJ46ǝxtÈ6,`dMq*輴>$sEU#F„) GJVĊ[hWY-h\6a9#Oh3Xl^??fˮ0dyx`[M.bf1ٜ#:Ek${ *_hy_߯_t?nL^3e :% >CQ`&4mm,)~)_r[EUJ,s1VZ¸_]VtKD4rj!|a9&HI+_o@7"*Zz. qdT!uD6M$*֢ߏ9|͝ᘨ-_+>IO~A*6d/qOiGk x)zb b63WO1C^2CK݀͘{?rRˬbt|xKnPS>mmi)Vո1jaC8P`Gq1߆Ф!ȉ5?0:Q~ynjDOpit uԋ6Ym]ZXK5{ƩC[n=~!M3@ gk5Wۓ5G 2ؓ8Ư%ߓ}mpƨzrzbm??4L̏m$Ɯw/Ws}X䌅} mM-.%]JpR!Zv]ѕA3\۝!Ϻ Nn;q#:K,u[hގ +xZ|:+?n|h?ru^VsOp@EN64b{C'Ԥ<6U.Wl0)i&EY`^ux"$FlY}K,}5Kc$ #f7gʭ v[8QX.Z* őŨe%ȷq:*XF3Yȉwi17ʼu;[]ɘKVAku[T(3@@Y-mMFUА!D{IJDe[@3h+[=w2j]2/K0zl c6y¡}\?n0N(LmsoharY<"6# S͘U f??ěJ9ŴŁrh]dum6-4M*;8ucQZة2qe9X@2:c.DyKsAڱDe 4LFmbHGS0ȟ #s-o&?r[(|ф)_v5]`*1ӕܛEhH?0Ǹxn/RO\g?0 ]\W{n(>= R+#1.vyxo˗V{ OOd0ZuҟB<ৡ?r<5?0*??.fK@G@{2)e,Ӭ7cwz]@hRTv2ʩ1󐘒͞/586k#4R P()rxrô#Nsc tʆ?r,yO+rE+Fo+" Iw9H7u(B5M#'S D}⒪D|9d Z'-;Ǣl88V3Mt<nzoxOĵIkfW#)z[dnj|)u[<])t*\&ho`PGm!+nL|bO MYv [~Ҫ,*$k;bnRR KX6`^ligZ"pY\\=*jV!!Zqk }awcwQ,خ#4>x'HAV*;*\ 2!i9M!&H*ǝ}1?0qqӫ΅Pਘ"Ҿ6ۃ.s!nKKn/9WB#/jH"Rq>n^oxIB?nΪQ4j{@iPtd??~ޔZt=9@4jE/ @\X7T,']?rOJǎx)/n)MMi&\Q\*,sRR]މT`삋L1,,ō]?r{KübHr-ؕ3':f&0sGYg=Og<``h]X^M+DOKhZqSLTTv.tʤrSVlǔ????YV7ѻ}`^o|Qၢ)O6g;~>m??Y(WV@GW3/[Uժr'ҹe]Abv +#.u}5]\p$n.`wB߿o "u._єXbV?nnn_?rH_)AD%ƐxVemhbCXBԶ~S ’WL9^g+}DJ%BiMaS{(CN+_PoV@v*m?0N-ՇbFtΚT `3;I!Y[rK~81D>C d~B?????n2?n ??y1bL쩚aˀY9) ?nMba4K8}F4i&ܸ[׏A%,S(9)>?0(44^s6e,Nef{lqz{{bm;8q 1T[m7\gMLtKKw@uĴ09Bg.,F&fgg 4p1 pJYL,W aWe]3,S۲^&Dc+"SVl|j;a͈몼bJ6:acwOr҇~D??CjG["U8FjRܬe4y[&"(Ôo G&\ gbXiF/f æ?r;Aigs̥6R%I)J6VԪ8C_8FCjOIu7@c3x{/?nLob8oԸs8ڧ'#!=%nX{S3Eqz͹N3ޤiM&l9sku5?nEs$Uuuuuh(WI{*??F xz?r_ѓnZFT=.xжd<y?0*a uT; ^STÍb.6'zMye3hDeg(gU}˟zMC7H_2WWG)U2WZ] Ϗ8NyǏܕ??"yVx>)dNbfgD;:#~yynQ1wQ}5GE%h it0Ȼ@ǏDP銊讨]OjG9#Ne{3:&֯fL.җB.Ya+ˬz1(I JQ ${t|q.Υ9Ź&ѣ K,֓8[^eD|9[%?rm^gے>),U\c[C#b]F*|$z!W5xehlSŢ֚Z[3K]SV\Ǿŕ?n3ӡIeL,Y^G(Mup2񣍷f^Pu꒦<&{3(T+/҃*-}:G 6͂-?nY1R5V!7&I-x:t01l"Q*?r\wGTtXZ%;DmI8;rBR.ZpocEn0?nZ`y?r6y[7ܷ`AP{g/<"=Xy6v0Z;?rHj0~qFqc…6[ڻ`]lYEy ߒPbr:r2땙E_XTu'ՇU贃Egֿ*UHm$8??( 2Q?0t՟a <~7R^vU"1#9Bjor֑,h SX?nc"ˢ !D麃.&;nwI;x'Nƻ.ͣ"ZZ!ZfM .ɪOmJRA rTV?0 գ?0??j_Eh QQ;!w;sȎHİ^]!n3S$oϭR U$EJתd=,N>h-uXؓ0붜3UYy'l5t^7JBO??q\JZtjNɢ*aҝÚ"spUt; ~kUӉ)?r1Yp9m[ykjD9lVr5K"ѥY7WqϠhAQX;94?r݅U?r6#s??L؋QdW9tC(1V.Xr]U^ϚYb5ӱGEkԍmEAL_~<24 ~3L֫0U$"?n:N:?nC[Gd_ ̮v䎂 uOvϮ'ܽ GG3Kü[:L:?r;x}1cY{JQl@*gOxgdxkf:&vipH}tUTHʿ %8)`QKojfjv9LpGQ맃KOzNb Mm*3ؚ#8sfTuSl_X8BqK[W{ዽ.^-8᜿ܥCzvT*²vV+S]c@17Zj㤋.N`EpuMkv$i?n '}{ZRQSE-Ge-jU)U_&حߝī&Wt+/&W/:l0fY1Q [W8Z,x2uEDǁ*yr$/??*3RM'iCban tey4U_SfՐד\:5_fx v (aa?r(SܱYx em *'+=n#A錔nh;1jXZ$u^&n1xNАPji(5Q4h,r!O>ŶS 堅e(zrl'o[RK[FxmT1!)u ˞%]j3f*8LZnm>Rfo胱_fju `Ѣ?r\vw:*)\tDٗOѸ- "&[7M{A@v 1|nTTB8~^l-K aUǞYŭ4' 7&l=hAGM\1+6A<7f+53TlI̟f4^d +#;Ll9r>162o,h,d_m^^=ʮnytN<""=0q',Wa 1Ϣeh9G ytzD"ܖ~?n\[Yr8i?0eT!?0 p?n8T7 ɵpvÏf;ȩD"+E7*j$בt]rW9?rG,s;ӗ\L(GዕQ-dNMGljf߱39Wc?n폘"1(;}0%N/iYy}pYT4)2uFALJO>}S<4?rXr~as@5?0T(vɣ5b &*k/dbmn8-c|?rMFm4۝cpZtW osQyI>vOP]5rV(xpRYRן}o?n[/p駯^5Y3jOΏ.\?rK'NO~Ϙ>^yxq; nt:D'AY6_)C9Q~}gKMdYg&Ob=7GÝ1F4*?nI$%@w?0\2lZ4! )rd xp@aM4z/%7K ?r;&* cGU+=C BPkyޡőZJWgZhD#si}T.$'\tA?r[o8Y(b0>U ,2 O#lg3U{eO~7~wϏ/??{O??~O6pթ.MVaՖʙ-_}&5Q?n*Ku+؉1Mv䦻wZfݖU]ʓO(H_ra.pTRgkf7SVi)=(+mCyyw>W_ 灟(k;rdr4VI^HFCcJ"z,^!Mfђȇ~|pu[n* ;?r]/˱b:O]G%68Xub= /TUwxDS.Iad)xo??K. i"AtUS!<|?nUF<# ~lFȇw`8?r{VI~(2PJ hwg*E6o,?0g ]GhFR{efyte}sH]IفuH߅=]Hik9Vll'={fM'V}b[v7/5?r` JnY5L4  J?n1G"I;|7uևct1D$wi]GfP`RHb q&Cx DvVuh?n-JSȒ7t3':cę_` 5VxIhܘm1"Nĺ?nQW?r&ffm M`v!0+B]#^?rth묩5yL'??x2=|h5rԪ??at}񑰦H`-SRy fY?0pPP馓bH2݌C'qh<@O*[^&"se}Ź@8mkḝHD|X,;#Ed.r؍\xZd b0lnhCk,̶Dv:M,{??BIu+Z-2Ϸq+1\PSY9P\e'VrӦҪx%:[QL52GMmv`"CĻP??k}Gu:`U,6ۅD8Z$Ū\N+ rbg](?0?rr?09pNń@nQx0@W>x2|T] .)?n2\s=i|ؐ;ȯX}{ٱ=k$`qT/|P'kʏ)+H)fgz_R>d˳g?0&=gP {³oau" ღ8"|KU7',Y??;S|l,{dDgBb吂`)=Jp??.F4.yy;14>lTANM`k5y/>\W8LSxjʊKerXgT\T "?noF[2؄M~na>N~>cVђ텳 )*oW [,:hCޕ?0ҙ$k\@% ʇcy3NѮ蟸S ddףܽ?r/Uƺni6=sAV{qX;DFİZ?0{*x bNR??89)KޯCޤeTHi`ã@q[1??ETrne-ïݣI<vrD%H,jӳI^[FMz-3{Cvr11s;Cn 7&VؾJ!S&=RlW-Υ؄6D +#C6!MtG{x'n[!Uj]U5w*Zgn+JH+cPC:?n[FDzFu:"Xc[Vm؞P"5WhgjUi>nURܪ\ߪm8ϯД (>qòB$5>??{B!ip-??&+ȐB\.Hn' P7F]nm ^%j}{1^'"U%dkҋ/??= qb??MI_ }2MB"u6DkA̵F`4^+rTi#yrJRw^5Z?rq\09]a­9Dzd#TN%`|{ռ r_'G=v_,~r퀧9)dϣ#<:1ŎMX2O޼V/UglC7{&bYYYe_h<%HFbو̲u;W+<5&?nGn9^J#vK='Kt*7<5^E??ï7W4rR?rA̦ÿᙌ۫:YU2:+m#@?0?n!;ihe C2ܟQ ?nJ?rONwFs6x/kG_pD]῵ORd?0^w,KNUdsj7eu.?0JY*)!D%b7G˶r\awZJY_os-zbgYK>KWɌjF&'Y;mrFݞ\Qzp%u":7vrMqm9[`'HxO(n!MPwWďaTpvc#]"kqL!/UmmK )?r48O_~=SCnW&X,`#|HxpKY4~2YSQ{-#Aa9b=n7Tib0sg; Hl~YS׾WEˏ @tYc3thG0B]gKmjUH tr}1wc`5"v,Zecu8A{Ŗ&ji5`Ȍ0{/ᏧؒK{H.K^{pd&XZt4aFK>FB~|8^(cJȱԩ_ZWg)~E>ۺvͳE/6QBhGI`,rDSy1thă-a9&8^,qr[=ryFRc&ga$i\"0 ]@qQ)6~|R=U\l͡ y]'u٘TYNE@ǾKA;0??FlݞqsM%66Z١P.ErުhFw;gH>ttݟL>26iUif[V6 \N#=+Ht xc9{d`9SAS!DZ?n'A^:/c8~%p~aQ^o)Cp)L͙ɋ,\nQ oF̳8&U*'w5Zu<29 zRI̲󎆉y5΅6\X֗4BD<ՂH5ى-}3 WܜjA?rG]>ϮtB#5vVŞzFD[xSNQV\g;3Pbr,쵪}k?0[v 3&?0_ҿhWݐ-;䐁mha_MK(-ߺN>~IJy?0{?n[bSptd7=*YҊk?rQ(BZET!4a#gNx6Lh7ǒZ9r?nHsw8ΗSr?nLqS{ݥ7jBLU:l~FMJ0Xoafߞc3%oG?0k@&OzAo^A'WMЕXCNkFG[L6(ٕ=ef@pV\xno;H&->&5`Mզ,kzI.̿s!VvH ?0j%%YuRYgX|?0 &D"}lfg.?r%k[,<" H={Vw777ͬP)],#^g:fCHOwvrS9h"NMk5BÔיŻ.uυo"E7uW]BTomuzޜ認v}@%䷨1GZXF̠XVUi`;:N9,z>+|@pPҫ<)?rY7;_(WU!T[&H]]d\0L: ?0W *.!=ܢd#Τ?r1rJDV$*B,>wl??UԷT3z?0UZ?0xPJU"??ʛf|{1jˇ;R|Bp[o0&r;!@mqϚ>K+6A/w*h.U<Սhr?0i/J +Th KJ..`[=,9ޗ̿Guüpt??LFeYG XPd'VA?r` Q ?nĄ&%}D(Znlm## #.?r03k+-J^w>b+`Kd51jژ*SdrC?nwtrbS-EYjI;XNrAO0F+fk\Bb:"Z}.3L@jq,<,D0'C+0à|HpQ'   r?nI?n A:ZO?rCUz?r?nkaud'}Kd(ƾ'bFƌ^$Rܫu1mJT[R%]q9,=7(/DV .7NЀ2J=G,Ne|7$mI+ߨ3EkVRuxT]cӍi2ƣo!`،S5 7#nG] @*XmRK@0-}5j Q?0;hd3/I:ڪWhG&e; ϧTFI.<4hfެVke@Yj`.ֺ@;ѻ_Hz9>ϟ a*??Uǫ|tUM ,Bʓm#KMWqGj??g?r[1J?rf˃&rWVh)<҉^j^ ]Ό|G7ZEZ$??en|gqQ6#2KeţYFXU=Q&_bPsHVYp;idː5)T(2oK+̡ȧwEe g58IJpo??`.'x*`y%5y=Ez>t ^%rP8fڏkp㆝024ӛ( nywP,KϞ)XR3RLmQQ Qy煮J}1|3!4w?n}= "{2>@,~Xv8Gmx,ݺ>6oiE;vq(l-9"2I7c &$AH 5eu?r~|I(SBNQIVg?0 (PfQfn>- 7-"J4%BzghIpbF(eBKJPʜ&˭o@f0e$n$4`u?0ñ^n`?0?0%EyY0]E?n)hrz0feWU HGw0 dv{L2 oTP D;N$65/dҭd!׆-Ǿ. q?0i, xZ+oY%$m,* Ndy9<fS˜mJ7nFir,zѬUg+ 1J19mʓĕ4?0t@"!OIq5$?nA#:TѨ%(ܲGJ4)-wf_hsg-K[۫;JBJ֖_iu3kVqs2 d9Om?r{M!?rFT?07,[LJPPgl:X5ݎs-A2ևTp^<39Ze7S Qi{|A?0?r/^F9Rį*ݞږ¯IBoß??v`1_SfÎ{(Fa% ƒN}70@Ҿ87uZ7R1o9,(QrRL63 g 9@:%[ Hc|jYvX_Fi9pua;Sz! #e^QntVDа@TWW%h7McߞӺ%-k%4M2rHGN`y}p)e[??O5%bb9F%/!g/6#rᆭ !"rm]GnTa3rɦZ=%ZI(E" iX\w7Zk>Ç"cIxcl\`.Fԕ:*ۋrk8*/9A[o9(YZJ;Q^^N#[^*8@(?nO6jM|-KZK([Evd74?nq/Tϸ$=O?n??E-&|Yz]6o?0Kw LRE^WEn.-n]J`/p0ej`ے~=?0<]Djge}lMc߯w<2Pd5 &\=>{xx8ϑoT,J;&=.oОf}Ėځ[G~$ }LԡPDY}kgqy.fHRXPwhVUQh,7YN|zhQm @`pը/oHsP"Pǔ•^TIb<+ظaF3߲Rlðbyh/]uă[Ja&נgΣǑ5KaYEZwR5LZ F3^L"4쁯GZD2}͚YV.])bNz^U'FY5+oME@>)h*hs|@'S45Xªnb,#OOAX@s!r>ӕoҞ&f&_}#5Puǧn @]=XOk>4Gn7we9_FTT|J'?0Ww>??\p[ӣDX!e=!NZM4ގ{3{pW N9;{~k?r|xA>0 ~Ή?nHq1yNĭ@V?0 W?0 h"@ Aw׋H~;G??fx6,u3LpR/fIG pPg}pʁ>4C"hŬM_ﱥ,G8Pf;`/ hJ")f$ʄ[(C(SW1rܻ"BҌt!_`!Vr0 M8b\Y\btȮ./1  (2,I25U5=Y~XDR]~';}^cx5}5@XVPWfӶxz;%X{:d|3=Hiɰe8JWXFMҴr k@b%S{VA:Or/O -9F*x8Q 7|W7֑%iW`LDʙ5yOx?nK= +UKuF@=??ϟ(tdd5/rE71XQMrXa-Ҳv*"{c:HEK;OH_aqX~xh?0>Q@WYde5 WEVF狇dm5[f<^b,ٕ@ kKb&G +# CQ0ϐy]F@v(ɇhHBiٰZovF8|k6jzyfmtDF)o]ͬ]6TTiU,c/t ,6<]Pdꧪ)I^#(qM@^?nxǎI|leW=([K!* ^){?0"oJ0vX]Xz0~XܵABqnw搘'#kmY@X2ΚyՏ3N*?roۉ;pݱᒽ;`a?0lNApeKMzHN~8n8k[е\F+4:DG @-}/U2)e} V;1Xܒ $H҇{L3r1%^]`t%G pP$[xR,>"laY)_\-er.tAjh.hК'@+gDI9 RWuRlGEA~ +@07;Tc1?nf?nZ]@7þWŮעK$)_ٺbo}=c=Q%?0gW݊mm9oS,7GO1Oi2?01Tba)&Epm_^ C;ĐQV4"HRczMQNjDI帰t`H^M?n(┞x|Zm){5F|ʤFw?0ff8AJBs|z < jK9be7F y)ŜQ??((BkE!v@$ <ߞHÚ}fmxMxZKƯo} H5sFY[uGnie .ro辜8!-%صgKV: gIYA _@2Nؘz]}lsnݷooe+F41{dce!gV'9p\w4[?0WZl|ף{cƑP?n-9ӾI=NR?nIx5kUYX??)9m7,ℜ/2Q8}oҪxh/ͩHxqcvu$[wG<9s3uRFgq"9&`:L'wZN`[!E %ba"ے$j?nmou;??0>W9AP?n |S 2 rWPߗ z NhP"C ?r)R;zRY=ϗ{x" MǵN҂{IT'1?rG7Eى181|/{2VC¡>yvy ^OkNƉ=\o'UBq06?nJ &rv?nЋW?0n.?0?0ѓhG30+./nqjяFFMo?rl_1:@Tg@WB! s/' ~UݏPDDRa;??IMD?rV.ܙ+JUO*λTD”7??"ˀv=٬%C-:pfzbVYY|B,Ҍpd~Iy1燦\p >Hށn5QnJχ#6 QD8l^p(??5<+={_/6ʜXY(T"dK9w??5%?0ŏvZ+Ӊ.b,,_<}5kb'Wp)_=O518?rgق;MP6OS:)K'|r5@]tUū=U:l"f@oMJ't>kPfm9/tfٵCPh }fTP1*w0Pl5Kdn:\5S72>>d ,£}kʲVmΈ%4Xy+F+7{=%eTQ"ǣoY#P/YNY=ϑ.67_Y?0{z8񪧀-:8Oޕ|/g#vwObʄQ~e^ٜ"(e!063Sк?04V`Xhlx.ctD&%V:=9 M:-k+m{A!;>(lA HoԫۼZA}':,=m9u'|Vjsf3^F!7'+g(Tr>L5Isfؗ"\:x4Pak>I#6U&+"`_םv@?r <,85=1=iY0~f)E;)'|nۉ&݇VgpK`>h^ԛH[]oxY0"EasS6tIaTH"ҝMݔ)-Jn C!~.Nj~Ï??}F`a8G|OdZL30D^GE…Ǹ~ӥ7yt1=0}bu+oDu$pMTf|`Kl^\,4S}`W65·b ͷ_ͷ>8^??tC3Ҷi7˿??귚o^i>NA.LAA{ٰz VJ:2ʺzjxB8YV͂A9yXlU,)tE,,~#_{?rVj1/mX0^Afܣ#÷emf&=xIuX[Q Q?r,(`#??-yٚ!@wÏ9O鄯urs$_ ¡~\YG?0eBo&UC塶)fKBtGu݉kK>0?0Rci;+]ǯn_o`7o7,8 .͛ݹuف:N7:[4{pCԣl^zgM9'_fPn7 "hw)VxDx%ϻh{d6hBZCk& ՈuG#!"M0zyˊa4nQN}nP?n^a!ΎV|Ǭ.?0m[Qğ~ǫVs|p9x??l_^ 5δէt@,TwcI]>){9)d??<o[gW_(s(nds"MK&r1^OIdiĤXn¥œQ?rp`?0лU.zp^Pr{OIt*fwpuN KD%!9Pqbpg޳4B=)R_¢tdU -I961Qc儖?0"%ϯ`m* W$S`Z_shDw?0r\ŝ8)kN`~Pp&YOLetz:_x᭙)"s,{Xze(P2Aƹη+ܟ?r.1sɎǼ1obQgu0Xok!Z:`W7 ˻6D1]z^KC[z!G#cu4;<9)kh??1D@oml+ė??nWo_)/\0g>_ S^n&9ݬf_>ZJ'6왵t^{Wɾܥa88WYXZݮ竃lyp4{L:}'^,ᫎa$U y&Zп ʫ +#?nM {dLG7#ThG4ZzF&EZvηt5nHOַP?r:?r{fD s3lf8G#Rx8t1xW|!ܼ//!XW%*߉{l8v@wnJ-W?0LJC3K8Mme:Ocߌe4"{+`sX)l]A9jr>h||\r3|,J5?rj\t#CC}a"Dˀ=D;t\Ѽ?0Ԇ}aEʔLZ?r,+R"@+[%5tH#B-B5_8~!9Z~ZE.ζ7T{fu`ix֋{ru!s&{(۽iWIOsȇTԿnC,p =zR_bKmn"Yל-w\1(W󞆋O@~$nnv??iJl{ 5>DZ>5߅ޞcv׃=c߉my@Zd/} y9>X*S ?rdش UIÚc],ߏ8??W?r$-34Th*s66"R+cYXwi'HZƟ"lJ*$j?0OT8Y9w @[p(ݜT2ѦY4hХ%_} #܍NS˕uZq<nNQz8Yz *?rAɂVWI`Pҙ|RW?niԍ,^Nu{[Vd&?r}[E.J0:DP0¬姝-[|B[,^>k|?r& ȝk,9^]'{ř#II.-̓q=YR1㹸y]`8A(=ܗF*Uq5E%fWP&rc/ ?0$6O4 rFT9h7㴎'skgǙ\ZLY/vl'Ydij"oCs m(AZhkו$@oZ4F)4]R -,Q"" : ?nᖒ&3İlf䋲c=1z-?nϥW u )㚖??9ŗ̎n2vسlqa}Oa=mܭK;^??l >>?? ‘Ѱ} +ٕ٪??+K)sp4qVk/'RE>j3$|=`p)ˊϡ?0]~dOVmȡY/P\62ˆo!j&R6y%b+BYD^15&YU[ 4#TJFw3r&Fvgp7X|kMfcWo]X|kl:Y[,Clˊ4n_ȷUޚF<6&]%5V0{DQOȃ aj҆#$RD5?nL29e!"??NXS #S*Z*[|$YKchzWR5#ا>#BOjX%|9P̃?n &EG4>b[f(n ;*5*u?n,#Ԁhde`[8&{C?0 `4Z-=R7]'D,?r7i4 ݤ!4|*uih<*)0HTQiUdZ"B%Z,KDxްDA]?0QI7Xڛmno848cCE';:URA3ᙥ`)tv;6#^?0b%g oqmkvUfU4`"3YFj6vOMrX$}›}/pQx)N9NSI!?r21 U%R]f: '/Ϻ?0)`dq09˭Ÿ7tKË~~xΡuᣑ?rG^01āA(5DPݛL! O~0EUQ;_RㄙPXz*f~/;lQ"R[74!5Z QgE2^ke{(k4ay`n5ܘZ|76%#PƄǪ'^AlU@AG65^;QXH\.g(?no: yDc'lC?0ɵK;䢰eZVeuYG䓣M1E^GFRA>B˽$1+4(),uGnW6ýaz7ܭx@?0;x, 0EwZy^$?nEnp"0Ma1?ra?rU^,GwndSIsԞ3֤ZZoM|9h4>QؕLb,DmS?0oN??Yp|j5?0^zf16adkWKZh!haͲT?r[2RCP1]B??)O,~Xw^kbLzK6Wmqg<+Zo#Cv#bJⵏ{d0"cV@MLbXhcSjSī !숤!FHEo!Xm@mҩ&?0@{Ph8h)^gmS$`?r9v'tl2wh`n#zM"\hBe??[N~@iN5Rv f7kC hWY[eڮ R.η%ߤ8%mFu}Si+ҕy} cSZم4kmoؠ21Ʈe,k*daKn1}cq!Jhdu0s5$hCt/5XZ9yy->wrwt?nM4*>]ǒK?0lE<ܿ%HK E8|0_ZT7n?rf  u9/?nPhB$)Fb1Ce*+ZwT"~^k??s҄'c}'LtQЮo`}j3@y/0[I?nO.ZL'R\^Bӯ/`65E}=?04< ZBNW?nRyy)Hs2MW!Vu'gy_{%{?rWE~þAlaIgx=1vj !?ru=Aw|<=s Km=q~]!֭*!虛?nnvr<; 5el~x?? ;|y T??4 G3MwМybr@WBskh@LMi˖۸K$||"oM+?0:As,:X_??XSǡh}$fksˆ,?n;l'wG#kĝ&EvU%#0LކUP i$[#;T#S?rQuzf@ !??rYo8̼4\F!qk1;w +#??\x:Dw??y `xv}.,??2zy܃א. cC&1"<[L3rq@-?r F8g0.#Qu)bXCw{a9KuUXZ``ȸ)*n9<;-bdX_ά/K)9uB]f Q.jp`4L|w&um|?rgc[f@ȵq)sִaf"Q|9yްlPc ƷuTe"* z4LdElj[ʄB$&!8`g?0!C_?0b,UFSAQ?nQڦ!|=X:cކiGSsQ >c59:#,DPD1˟=H' I;0t]{7ϝ: QŞNȶ_zc=V M,UUYZM _G!aJkizNAA=ſ\.4XP@]qT%iL<+ I\私OjhtTn%3cpp R[/W,@7d9F-Pt\n#ġ;mz= CsnoPE*J,@?nVn3n*VkΚz*ϱ nz_IHZAƈKk&B#=܌`+u56Gܘ`f,lNmcOsr2#.TS$?ngdTɨVKpA5Q0<0x6vP =b?0IE\ME4/-e>h]|c6.Yr??1`{d*@b"{0(^8n%)5?n;3U-;?nZ'wNm1;z2s+9Cf ɭ'o[u`XM!x7s<>E6T4ה|??& mְxFazZ U͂7.>i.`Ț;<Ƽ泚[UabTWhͨvBEYSY@HIE$z+3@%W;(Fq6hՈ71fп?r]ơU>_[0kWvOToW.A˧ݽ>??Blmn5MjkSsc}c%{GfNaaDӖ# %+K?0qFwFiaOjmR=6g#:L:`/nkNPAʳ!SGouJ[^~??Hgb#DaoH"Ur}ek\;/La5-0~N_?0l~2Jb膂 ~Zh+תvgaj)W|SO]0R+(2SWˏl t2]Ʈw6OvS]µ699t"PI3l,ǔ3PQ?r_{ҙ"U<ߌdRÌ˛A?n;9 ]amhF|ޓS%_G(6k.}09?rgu;krT?rgJck]P}ޯ̉M\fGVnlu70wma񈏪غ%08ǝb)B2LXDtӤlx.#S9s ZoL??+W{ FSŲ>m z䂝W?0qklQ?rM]-"!OXlr1fFPl~ByIXY"2&V7b%UK ܯ$kP k2V18 {'WPt_p(?0L:Yb),vh?nk3YuBf#Qj]'D;͔,V,TbE?n.LWHMqg*0o { faQiC9jOnP|)u[dHi2FA[l`xen%h D(Fc ֑e?0e\dΞp8P`(dmd/ܶv|f=L_R̋|-66hk`?0Q{7t[r޺u2UwQEjylꮦxIEj Tǥ'ĊY>Hʕ2~:Bs??\d,/Z?nWK w7mo˴D(듮Z?rnגGXlm[t/wzyNBdEwEkLm3Tܸ36S8JÐK_XўF{J:+ٷ=Uz l"?ncFuzWnOLGN`sPc;?nKIg.kMi(h{#86QI0>$e??U|1ည}`ʭ̰syVe,Q2?rK&~`XCQ._*vOQēNA?n%;:du&2%_-M*Q41HM"46j($,o/j)EElU@b?n#/D#,ѫC 4qh;{;x)9TX8۵x55a5[}CM3Q"kը˻;DRF njĈ?0n7^$j4jBy?0%?nw%1x*&^9Y./ +#\®&XI qv%f%?0h6yMŒѣuf7.F3qĦ&$vey #F)QeQ+N`svo>&nP\#b!cBnpף <$h(`1)72"Et Z??39$1iH&B)A$8]L_..4!5Hf#de!!3`>?0|~N#JaY^%;?0A-Q"NCJ-r:bSb6l-5,`W?r"yg~}~yAI~M#\tq֛x) ={FM̛'zl:E.WBuI(?rXOӹ#hL%kI>>Fo8 pMP}ib&5_YLTgÖZyP[~J,^H9Q^Qk̟n\,/VҊMtVc4vѨn5$?0M*RbvpJ™po ^ *;>O0#GoM`믺2\3D?n)0&=`^U\XH?nsDfGxx94x\=upԬ}Nj6r r@Ѭ?0^?rX> .j }`I!ƜL؂}eͤd<O?nM=ߧ=#i??Per*ayXu׋.u!dC^wսYmJVY]`~f/*#,c8_ ZҫVn+q[1L1~-ǁ0҅P /?r??[T8?0@vsmY3(PFX>O_a&;eȏ8y6NSψѠtk?0w@tX֒{76MKi,>5Z,Ě^ x?0K#^-[?nCC+m@u`(QAbF??RJmHZjYF=}5q??c<ٸ+å1v] m?n2e&fq#JS=.FD-R>V^"nS:F, @E#"(7 y\-,oۓ0xs^Q&1N0%X*;,byKgEhXAW@j=Wȡ_yBuϿF -Rqɷd=1Pzh׎֏}+tmg꫽Ot,紻^\/p2U)ter4Fl$9uYD Vhm"筒yQ^b>~?n?ry񺇩c6?ryI2@LQь^\y6ݨk_V2?rs!h09JmaToa3Mf1ш!"l*E3U\HS>14<YAښ:뿿K4KH7M,Z5/ip:fV9gf&jע,9m4?ra.Wn]gD`f\Mxc!oJF3!2~|>Ʀȯ@'v$صWMee?rdHXDuE(W0pJ??,]F?r.D?0 z8|s9S'tO>u :Dkl|Tӯ ^Bn7MރOV`$ijQ0?nӰ,vyNtI64R.LBIuEM|Ȩ2)3:sXO :#!i h#j[Drd1g\VL{Wr7:`YRBx~Q39`q3!)l$W1#w͵bp&sڬN'I++q`UF46@߭KbCƖyԭKaMnsxsEGnRQرd寒'2njIJ1ƍ?np\A%ZK#Klj\!AJri2.YA8Iy#ia uVYc54)] 6ʦ*Ĕf.ѯKhK:52dx=>J=tϟ&gzO$/y>%?r??N%1=<&O=}GG#ƣ/w 0ҵ5I<}In>m=K+e&ɸ>;J,vjl@@d??5[6 +ftXGc%%{Ó,$Y S|W^S.UL.ӳW@K'  <,'NYðZvvR4{E9;1e)"_:`iF_@G6?08ŀ7ϟv"< -a8C?rTDG?r1˺W6`9VJG8@6߉bJ&㐳s12> ۙ y.2yL/RZz:/# B"]\<Ƽ9xG1ٱ$VQ߇͝LQzPinzIYljusͦjATƿ[b42q)V 2YTCFx=?0rk7|+]kw5̠=J )Akưuu2^W|8'~,יEvlyòыIaJK GvJ_SϠޅbP.|GE.ը~FyeFCP,t-7v=MHK6+?0`w??Z,kL_X8*Q?n<ΐ?r8?nAĶ@Dyd?0>HutP=J#Sv?rnbEvz+]jDW#jh|zd~Q!=*Ȟ\9nQK8Q<S^C!ǻ} .Dco33!ef??]v2U> X$,0D*H'\,A'aQ!aFwē`\:c\ȰL^ r$she`/ [Vh>\ڃȫ2xyh4/#- {lڜw.>5_跕?0[Ou&Ǻʫ/jK:N(?nXW~kV˩_1?0⫯$eݹj%Uno-C+K6±!hNseI@=gdYߛyu@b)o ?0@"B[;sdgM:juרr5:wDJg}!]Yzʭ4X+sƼm/ Wb*D9>dwD}]Fτ~ q˽n''|}>VvD5x;}(D^NH qv%뎄l%SDԒ g഍Ȓw@gҏ@cgp%Sp+Cm{L5t!+mfT3gAaɖaE<Šmg ,G?0?0;MSh9`yY!ZJ~US=忯N~ɳik6{W'0iom΢Ed?0g +#7?roh3),;f GѨ6<v:52Hym2Ͼ"K"?nw`dG=n5769?n=N&͖wNս]\V5Uyi?0U,v VmL*$\IeUVzBWoKѢNk5σL֐4)WV)Ey3a_mKŔY}+!g;\械#)# BZlίmYy?n){(KaGlvnSݧ֭M=<MXȗ]TXiԒn(+SϽ 9?nIW6K}2D{]G7H]?0B%Zb̛Y5Sl!^Dny[v Fs1;Ϯ39y ~o2 a[6y~ {UeV3P]IM$v}l*6r_2}eZ5B8Oy#w CM9o&`4°1K8lg"#*A"S $B C3`L?nπ,]VRxŅޱ(&P(NyoG?r:ƌߵLIѲm\0H6t FU+B&q=1#C(ѽ簭i@˅7]tbE-TxK&@glٰh.;B?0Ɂ,?rq ?rC,ddzuV ykGog)M(;&fOg?ryͧ3U?0j̪Eil}nAExq1n8(b0[4 _d٣WK&D&Y%?0k\}h:z97?rSP7JX1_M|&6"???0,P^ڲF`ќ)dµV][tTfEoFY6N5cҹZwŦLSl76K?0Hekۭ*m_##*3wYTĭW3Q$T* +y6}m:Zdٌђm7mү@wI\"Ksaˍ>jGx8v߸zǣt@|1 LeQ\OʢՖkR}0Fx-ax*9)H˭kPM[ JK(y8ው:_8C}/F-RاSJZ%hY&qI6 F7AdTJ?nE`(\\X3b$3DZVJRbh;!šRW'ȟuX(Ebhr3n:">7SM"h7dgfoh""))),Fqa&(_#.4q?rXv"Jἀ&E "&] ?nmmD+?rVL;z{]c;Ty??yBZ U;׹yĬ_FbIِ??HUxUݱi#??GU,8f##}C?r 'ofи]#іi{3P;[=${-72h e'Сg'-x?n^?r18JԌT---ل%BwWl.Kڿ*?rQƥH!??9+tdQ "sM63lpGȏrlU9 }*]+ybE9xjЗmj=Z*E}0Uw*(3^IjF%r(T|y)7{!m]1($6^앞ط%?r6/J\uV1m3k\Ѽ(Z/QXd9̒J(*7MP|?0(eK83gѢNK׻OҚp?0Ԭl\7"\G0?0E{G1XۣkO[>m:lPN`}^e4(XЪ< Yh99xlO¼A\F83̬LMZ8b|[>hbFR"2e9b塭LSD]sM,Wˠ~^ 3l_-0*W(Z7uIwUqe-ߖIM2EK'L/騀umj$"Xº`9zz&O7BzzE583y8c#dIZb1ya0(??KS.L:4PsQ҄kFwN?0?n\~&-khg"^s.S ?0Pnc"8X~Pax'3i?r~ₔ3Y/֘!L?n#01#DA9VBmYntyF-g%s"EA+n|8M(s:S8Ox;CGy9_S1CsR#}6MΙeaUO4ٰXVYn=jYRf9-EC=]. [:FXsYjf*Y",CyAJN"!MGݮdrS?0V($',:ebPeDK9F "S=[&1biWxB8QI 坤.t#~&vڜv,_9aL}rfK L$}E32Żkѭ$%QiNVtXO~HJY\; +#/`t;77{l6f9DH cks}O+Feh^9Wy ;vSOT,mݢXp"G[ۓA)&CR=4Là?rbI"?nH?0<`P.>%l K6lhܩ֧ƲtUt/<؇et4TcX2sD6~hkף&ɘ[dזF.KJJ%սa(Cq[Y+s}]gmzؔo\'}S167V"́{&0'N#ᕎFL?0JZVPma?032|ft??.g-UwX\??7hWd70??8%a76[{#Gmqkӝ%f[%UIw?rYn߹M?rnг @$*{m$,qYQNjH\y;WˎgQv,g_|v1ɮC۞Ϣk5½ 2e0ٻ'1>ʾO|5 Q3SD&ߺ\aX@Z&|UÍ_m.J:2]8NΝ?rb??zguwQv8D,$2E%h!GGAgRwnȤlo??.b$~nr]sp?0#140"n>x??t;-S2^ש(w=bCiRQGbC&Ap<|ԫ5^(.Y1$2mK2Ȟ5;0?0/64]L?0lr=}*Ie7I'+0݄NrumA79UL9@`vMXy?nzgQFoh\VzR!O [ix;]Nr|U¹?nqu-`!,kr}Fּ3S)~?0vU?0I_fa"7]µMW?0$hy+R?nNX)& ;x{3Z+ܾE ޼Mh~zpfW|@o"]?0|T&) I#.F](pnˡaT1NS=<%Fc-f?rVN"ax??wkG؋xCЈ'vU\*c?0o kL}ff!N[WTq|yFƛ?nn4l5Zfkmw{ͻU?rr,D[wަQFš!CweCxfrX|2??&"ޘF9 n~ʧ\XͯCA/ P:4L{CKPZٳaRǘ.ZV7߼B??+\TZɰ(8S+lţj*7o)G#`cBJn?rZ֒;F+|??UyMt׀F;׼3jYaY4U|ULqN^,Fc=7g/8u(_t$Y%\,s{>Bh6\7!E1O{?rB0a??+F0fd]fSh#vAaW~֑271轪&.jAɏ1i;fI2Ɨ?rk4NJ|"J D=HjDXtKtg f:WuQ[xG\+or`iOӶ31~#8򯤰Fɏ#)?r?rp?0tCAS:G(gQۛY~E9v;S6w_=6;y+NgIp(=N Ca)S׌똗;>rB$1D![??t21KD7Uen`mʔ6tmKk?0,:FV B,c-=y?nYܜ-Iղ#>bv?r a=ٶKHSVJˉ-{P"?n\ii%[gD3GZ'[Uc 52) 0FuM䝥Sc,dz6(?r?rdKsf/-|VmŦj=8ML˔qr+cSyu0epevUcb?0>I4&m`hqMY-I9k:-y6~vs $[l=lA 3Lhd0{)GZ#3kyߝ Iၘb{ }P^8nE\㲖έnD"~5b},pO9FR@L'Sä+A?rvjmn4C }bΛ9G(U#vo:C|ŸPW,^OH/4&&C?nS_+6:2CN_f&evATeЋ3wx?nK7")\?n;Zndw#F01_?n`V{YnxnP&&IÆDT(29 9GCt.cȏ} @]rŪ h׌2hUU4%yQ~2K\;6-Kaʇu6扽$W;mBĵ.Lܕ#ObRέ%wArSE18(Wz&F"/YSni;[6mh6]<'+#ֺ?r`fÇBbŚM9G{Zzx9vl*;ۈZo(Ͷi.1=%q@ /KV5Sorw=N/0vאYPg!Z,f׮c)*KFcV&&ڍ0~{ʗQu@G??혂6/"*LcQO4_׿JP??PH&믱vx͘k }bp#֌ZX+MS^R$kplu6t%DְltZLJת3wٽMdka?rP(N?n??KuśŞ.WJsy;J؃B{f CdDLRbUͨ_e ??[Iwx[t?0[+keIh 64sb킽?0{NZwAY=\uK-%e{;u0aN?0a:HVm𿴷p~C@y qV,", 4br]iJ Kֲ*QZJϴpik-|ڛCy9@T++[Il/ʩRvq2;7 Ѐx8R7s\"Le{ (ʟJ\բrՋfX{:I)#{|dX,ɑ܏2m쵹0)G,oV~;_Ez??jA)qpϜiF'֭(Y?roCH?0X??d.м[vjlٵ Up7fe7?r|olmSpMw,r|^KK64Q/eeiz2"2KdĶZ$h??1Jʧ%'RGd??i_` rӜLhu9r#U2gyɪȂ'BXV*٥LpMyYCThDJ*{vN_hl2<;`un~hmpNe&GZ(<u~d#+Ok8GMz^hols9]Y?0QA9*YhRH>נ)1R6fPཪ='I"HK)ЋRvNL$iU/ Q{[Cy8iP1 ǽPۄB BZYb_m?nl4Jt`cqNňLM\cTBjWKX(=Oi1^%Dy@ ,W?rz,ZV02ɍh/.69칒;-.\U^0[v u}`Hv@|u\$لF,ֽ+q4fCUK)'u??soY??`0*|煞r~7oom=ԿMM ĊHXzpdHa["9)DJR>|`Y 4œDW6+}p]g0IQwD Ͻo,|-خs0yaz~eҒӍ[o('^zlq8""x\-")irXl#T=2|&U`JJ1v9E7KZK,K g@Jnc;P4D&ڟK?r$Řpw{?0tWXdrP ݟ}c^`xʖGk?rX*} sqo]+e$x#APB,_+8)^5ߌc-:ZBf_SXQOljrC[''Wv Y6ϒ81`  l,՜8 _ʹvB`^U;hC%v.ͮ06ضm۶m۶m۶mw:ɃTw%TҪt5$1pcCގ$+l?npSLiɝaY x~w=X✛Z*_MPu0?nf8F{*"~73w^IJb:.ln.'k9J=WK'i)ߥP+S7LQ64ECSt7 RK z%,_Lk[ˀ3MpiHO'iƠ 3~m60QI[PcwـJβH_0R7%$;#'Ms8P?rtnGqNSFk8ġS$a\Ff??HOLR??2P{9l|Bj?nTYl߭@R,f-S[@ O/. ioFҹbsDؘCleAmE0;Df9oc홴,gҲ??U.2Vg_>hP_?04W:?066?0*~FYfEr_!?retSkIifo@j8tn&jae>G|ih"meO>PV3o^?0ܱV&{n \z#V -]{y#F2Ӕi&4Ρ*JN;Pm}R^z?0erafu&W\T|Gŗa2jAiy,eŠqѓ?rNaZmAb?0v3R0Glf?n̂ȼY 2,D֌#Y IuA(!ɴ9cZo]SF4%EHL3 9[=+ywL7emmk /fU_`XFN=C5?055$n,8<10=FLwzT*D"eD(En/!ax ʸcF;ӟCO (J/N/c裙AFѡw>"lZ̹Txj1QcU2˱"$G*(;S,1k% pdR!ly0\<8@yY cM~RPHKBtF5hFؓ7g?0A8~]㕝Ǻ.]3/5㵉e02QAk'*̰xTykϴ]&5oun1)mN:R }kHtQT?0&VC"ӾM`#ʒ.-H|jj7oBMScr3%s67 ?n֟W,+A協0ם2_/˳!py %LJI+'V`J?0|T% +#{̥ݎLdHZЫ5+z̧냿[J"jh;Fڡi_v<7FBo(5izW0^?0*RbZga-K5??ֺ&C AEhųGTM}=b0]N68`.\ RRJĈ$NI@Jy+1Uxl\V daK4\- cښ(1x+D="O养pKs58s܁?nQyW:ҿ|;"-5Z?07p(3lۥϣTGqprT)Y!C??:nE9QCf!,F˳74] QXнzj&QGje_ 9]SK'%ޫf!e&Pʍw?rN?0(G''y! [ThOLmڲ`R rß,pP¿STގY#fe6-El ;Pxnm\UvpVrzɮ#juQMҺơdbLxZh/>Bϰf^5??jX# c f%B}hV PaUWѕiµhZ+#Ĝk,eӰ8+TZɴdF??ƘcNpaJi`tmՎhXUj(4?rJg=9D.@*sJų:ڭhl{j?0T8qw8o#IE82 csb!lN p@ #zj?nH{BQ(|DYx; -FeF:0%eGRjU.Nڨ0C'Rl%txS_t\bF͸MzǦףF?nY*%Mm%,,El|ڋ 2`?nMׇZvQI,~Bp~?0 6bCЙ&,ҁ=BU?0ZE]R{|-.C*?r^Q?? iNKfp}4~dyƾM ˾37J<]ӛKt@kjDPlg]AefVx_`n<?0FZ|M>~qI^A jCҺDkdGVsrj+&hC]EPDWd. `_k~/v?r+By~+DP2X _ a l 7s%?nJ-mE暵BC[j qL"ۭ|1_{6,cgIQAѱ2A} PI(P~Qe5քGoXR~@@uíZ=xOf9Cp"޺kQ8?rяn8T%XȊ`5?0e%Qʹ3V%Ba~x3Y)SU݃zgLn?0^4q8ABN!ާ0$SA"0!?0n-j~Nm?r}vO?rMH1$C#!K2??٬53~L`hl6ي'vl*H~ijyEf?0?r[S> Z9k%2 z~T:r,$L'c!:h1wd/[/f4dUYחNcۭYۖ4[V6w>Iӟ?0N h-z2&%]i}M<- l?n$?0reort%6YM^e DX"qc7)E ƈ6af 0`p?nohO@Cl{!Wӫd^_#u-m.T P-'^?r1;삟GhLor+?r83?r$Ң8?0s!3@#B<34MSk\ť.7b|ԭSȦ9. 8oշSڪjXm1XƒpWC*Z#EUtFt?rF8ӒsMc??8mGh:Q#qնqTR-?nI3r>nݧS &Qְ2] ?ns&]?ri<+铸~XFxY}kj.}s5gϋ!2W\'[`6jk aSu}"W@ѽ"rC z 2 Weaΰ(RPX9> ep!8'+zd0Ti̻hRy-^oWg/9G13 s?n3bHֈn4(uxEdSIZSrzӥ??TRhlZHeȍ\?0;GZ9.#dFr5[ԞZ!!7wp'i =QnCR`2t WiRKAa~MDlXXy̎bxu|2?n`I"\U~l *pM-\(VdpQFt鞕*IŚ rP>-~"6 TK-y_ctXܧl(bG;K3nU?0u?0G};(]`3ςGX[%(Cmj\7xm]AGijcF ]R&{ c l/ެ??p@;f)QKbߴ{qu0ĽT1ڥ.=<3l`e۵ (9=}Yw?0xdT>CLVZ>;M)4Oe,h~ߺE8, >*3q覷ƬbA\-.74,ӑ'z|Е|YV 5j8z'˽gӽ{όٹ{fK+b;K[/2z9?0eȲfVaSQ,WTۛ F)|8~??j?nTUN@{3Q_נ9?rps79l#E]_&T l3ƘɯV?0 ,B$+5&FUÜ?r{aZBi]yެ?ng`R)@=49(?0eX2>΢ v6)3,q Ziz +#9p]Jk2%{zy5E8wEg/hBx%@|??7Eܾ)=d6O yd"?rz*n?rl#ɳ gBRZ!;|mV=ަΚk4Afc9O?0fZOɺ*X^@=qUiMhhwQ)[Y7Y}6Ǣs=qԅCXn-$49@IJnc;m5%Սz0Oɯ1,t崆hS>3~&>D,!^rn\Tl&q^H̓jȊ1u= ,= E9v CgW#^_@m@n5Wc3}I͑k㰃rVDd_+"ȉW.Ed<Oprm?0>$9̅6/2o4ego%}嫫vSޙobTmk賂N ^u?n]%0t;(.-Q)b&Zgy8op9⮽+"m7gzJd6lkTkM,]zO~Y,fy\OYԔKChl7"p9>Kj%+:~;Er>Vs\ `ۦ/|nwtd(Vj0>u8G/u`iB,Q7vcs+7i{:rK?rp 2F`iUGFU)Aעsk`E˝SU% !BNIq%x֡VaK Y#AOg@+0X\JC`8-1cxyXyKxEkqeO?nҡ3>"0]%jw]584kBÀ46S:gQ\^ZmF|h /԰4*1c@k@b8 UŖSU2zSγ`joc c'?n"CV> ??drx6ϼd& q!4??$PF[D/pM>LJG,k(Â!L:twJhk}b4tf'etJƏT=L%q®>bi3cr?n!HHXq'e}[9:@8#^uL0xy֢?rmX4*y3O.'+2:P+򎓎Du9:΀8ɰo[NA_v2-Usܵ|ŏ+13=` K1> #3`ͭfẽ/ | u~T'W19ݾh.E?0FֳjJr!D;35s.ւmq∊֔i~XqE,\$tuY)j!IuhɿF>7m9;\6s!$_hT?n Ҥ},s)DaE&Ӎb:d9qfJQH??xē-]k+Qd圻JB]ao+#[te&?ry1?0\X\aI'Q9܌؍yq)k(,,l9 Uvۍ?nɎeΏ=aBotU0/rr:]xikgI\RވD?r>{V(CDKDT' :P v;z?no`{L`}/:/4,a|/0OāV?n$)`JW@1'??UeoDYnCM??eϨqzAF+VM)>X??y<#y\OQȗ?r#7iV?0>?rM3mDo(??#OGHasذx"Qz[IZ,Zqtɠ zIG;)[kK$ +#!S6iQy) Mq2"ln}cc'@ƥK{1ʍuhk<~[7ۙãq]*p8TC^DBϛBfEŇ5@hxd_𺲺Z{/<n?0'8RRD}qx8|g 猺B[ivT·d=ɟ\C_Kvz8;'r'F]%ҹꖴnRxZ le𹀨rm{c((1ih$,)f =YaES:N_q"׍Lcu݄;OE,̓@O(lequk٘2n~2gn(y/A d&ɥ{ByDj@j=6d4߫ghyfrc aDd?0YJLyM?nT>#H5W$D "ACDTj?ntܐ3@VtJT%w+J}CO_"rϱ:~yx3%xsz r6!foֻJ_FV:KݏKYi-z/x4' 2QgC!i'obnEOi{+֫Vj@v ׏LK5:Q0Tat Axhvq{@ mqEgc*B1U: T,JIBxx>͛3XQ<?0,cG?rj)вD(>17jޫ]q9A< BN+aAU_ٕQE@_XnB;K$cB(uW?0_ S>}_OM1WDG鵫V??;a -F zEoѶeN0%>[תn6SI`VT&;cP.;_V,>Fg|HcŤ4*Py"a,lX]޽?n}7?rp7ui2p D{??t:6#??>A.f1D/1vsPiY̫)OA }L~k*:sлuK??1'a.JÜhmٱ(oK\sv`ܴ$Ֆu[\7 j]H#ˁЇ&ýF0t;O~Uiu7@?rUrgJCj,S6 #iv{.;]˓?nJxإe&#Cu>UDW{k;L:g}4޿"k  6/-?nMqմ#do{[lwN0v7LSb!E`87_#'a xo5CvH?r^ءEф^bN<Y?nq(,2V WQ2s۔>9\> cv,YY?0 $GwK y?0`RoB=mv,.[D??$ [Ȳb+x^XH@aJg^젳НXlIA:&S78Rͅ9WlrSeFr??׾Ţ'??ix7= i{^:\U3&3u|*w\?rDg?0,eLfҢF,>TtA׮߾yUf3.i̞3n)1tͿ eSZOV1|GƐk^|s3w^ aTY6hN@l@ӕZ5x.S'4Hg]7Q%t@20WZ?r~^ZDP\nRJ7Ej;~rwUˉDO-Jb8$|^ Ǝ?01-_EQЎQW)r "3P{M(`>TnpdeWʹ'q]Nz.7'Vw.9%}3D_,r_kHƎ4913$1X˫E]SG*JFNxex&G̨ERs6ڙrbS"Q$,]e)[~5h/@٤>??PJ;\a&_jV3Onnz^R U~J:u'[S}9(#ނ^3(耡&4$묓hp?nެmEUzmT%t|$nC??VFz?rM(1B'zVm!x+cvrZvđ=kjԘֶO2Ϊ)?0 $^ڴQGFaWd(: # +#lb?0CPG?0S3.nIښ9crmB{-Wr?? lK B mZ^?nKcdDx㣦7 Ӳtk5`!޴??BթJ[bEWLAJye5SL^4 թ-=RQ܁F6o@iغcɚ!)Bx*|,O]*p@ 鰧.;??(%i¡vYDjĶ@A^Hg%,?n6*L]ch}9pկ~!PϷ(J@1\ކm?0f*L0$N9qf(xFPΪo𦯮^ܚIvB1+F܌U<kBlw {{qͽQ~dT%P؋;i*TSt +0h/L?n!x ?0C[;w;}'wZWcZG3}cGCGGSg??zVf?0+ +?0=+??+11?03202IO/H=i!>OچXFg`692caT.Kt'LQ蛌c!x>3??hV]nnqQ=x+J"Hh9 M#-DjX iJ,Q_7?nw.%+$q Zш{[aLqIlߔT'N5UαAm$??ѨBbd3BtC29\+vU١ S Qt\}fWҞ֩4C ʭ1-˛fK?njO?? lV$3wMXV=;Þa[ $FKޠHMh"T¬T%E0QIj[\?rMحHFTNM8d\X>vQ'",9Ee!KjvU$tP7\捛von+ήwQ}5!IR J?rPTrw P/>/Pw|<%cT f =??\K\y>P.`՜Y1Q??UC ROf6l`:8=sG5GƕCФ4;??sOrf\5G̩6E3cڥn"hV~NO8"QalM>Z$p.ܡ$"L}Dd3WѣC_ KJ*a|.0:\$8R\D7 X o20C3"4^XlRSE Z.(^~g{.fJ`sC_7 >S8!.wZ&5odLܬ mb8S0R.a}y2t|?rCoF{z a;BշٿW"nRq-?n۱G52U8s*'C|a cZ?rhy,Da[c,+(Ѹi-L1'}Yim{7l?red 1+???0 1V&*`_@aL`D4j燆fifYiFhbJ2߽D:%ܽ/I1o.bd˟F7etQdyPi>k?n4ؐ}w#.7/܌AURg'v߮/k˭+%KzϺ~aec&̤n]GbHͤۗN?rxNۧe2Fi];}ԞgrDQ7Wv=~t?r*GQO7}f}77`OKQ|M@RIK6DN}zeC:o N.I0,M???n&4jVQ.YFv$]`GmX4B_$:(P,( oh8 *QdP\&j]XT>4|m"{s8ue~~ڔ urjqU3Nx罖~D8=`Vzk/ )4*OaMie1\cҿ$-9I?0^vqPj\8F|Saƀ!Y b[Z= |à%zP.&3&*1Ԉ??IjR-5yuT??I&3*;A;\=='bX'Uaڙ(UWg' 1[?rLQe,׈gﺊ!['m?0}NQ6#`:Ӷ⅐K")!NrYo%C DOUPaZ^ss.Pf :a!x֋J>RN?re?0pЌ5T)"yb`~;YEA[6K46( PI  &O0SŅP"a\РiiH@+ǐ5?n *̰ٻr)r''p<C5^F'È,- d&&9ٕ-"4|[?n\ aejqD,コsBg?r:[HCHшR2E~^[1(I5jʹ:+7c>mcm}??F=v$,"68ɘd\X!j{~6?r`]o$/$}V{ *aM:ŬZ!_IFܞKb?nn&wJ[v$6da =HmF:XgY@?r6׹OUqbo4Kv k[3 eg̵u?r ?r&f%[njPө+7[mҪdjD}Z{c&\E&`(888*_q$(Ј ]Z~ٸh 4Po??ݳǞPPydC s L*fB`i|EO׬ }3Ypve"}DwRL`]! G{??4|N]~}NDWi݉+km[wQJ>gd]Q[]*.x`0 &;fD?n;Orb_TiCa7aYޒYȈ^E#jmN1S{.$"3Of` f!rۡϿ=":V ;5'v؎*8#]1CȉcYjSYE4}yOƺT[gֲT*@@FV_B2q&:UDU-8B5LVdY̧+!~>nv_(.+{8.|6`?r@A~>?0SR[_?0W- 2aB5{c\{ĩôB)CP5K]8xoh&R嫫s59Uj{}meOk,jvHYQ?rM R1>~~DP~Y .ֈ ,KQWӎgonx;Oou5X %  }Ʒ2*Vo/TodH2s@%XB janO'I1EdBzYw[,Vw+?0|g=6_@>|?0 <Syۜ޷ Y[&;)F=?0Z:l ~Riӽ0\0@(Y!a4oqTD$F$ ]໿nȆ>Sy!DF??c燯tH.0DT,H3@D&/nΖ>Y:gXVDuί N#K"^|CBWna4.?0Oخ gCb(Uf̉pa$#4;j.]DϢx-j%KlC??u n rfg=vN0Oھ\s]Zd6p _??m;T,Ė鴸z)k+2Xb\I9tҿߟ*Wl??heo:a*:aPG>?n۲Ǽ7*m(# HZ(h4[l{면\7Ɯo&ԛHe怡?rĚ4lћrz9ߤnFٗ23Y6 pHh,%pX;?rjy"JO ~Wy/??}0@ =wO"!xƒ]!3@5?r:7R!}?rzO/}N2h oz8myAs^n3T^,f~Or9 2_y(b|q*h5J@iCY*M.k֟0*qߙt㏞'??}ke{mLT,m kס??*92-Ƞh\ɕɴt_׿M:`lݝr T',GS?0Xơm6F;إҏY}@0!TR5Kk_ +ASWΡ"_VHAH?n*"[LS X,-Vݵы%ђ*cuSQ^??&* kGVY.Ơ,ژXq@41xen(f ɐS ]$!D9}O)-??[] 5JR?rތ}}jd #mKC9f=#b ԕmsqM,NEyպ$em%[S ?ron;5M""XXiLjARƄ7W*cU$25K+a"Ŏ$Wүʸœu +# m8Cdŝhjͻ2fƊ:]3Rl$h&#~3͘qdK}9c0]?0WK٧Z9(PΥ1_oW3v 0G@Map\?nNuQ<q&sH$˸]oe9P:5"A~?0\n"j?nE}*]uE0rglq?r?rYW U-nIDe{-3g?0:5vϻ1'\Bggں6AZ5s?rÔήՌ-.>;E.UA ȫ0%]keĝsw40ԩOY%]"|CGx9 ;Cf`cmXÚ?n[ \dev\au{Rq{~}ASʧH/9??<Qc@^f0NM0R@ Ux avY:@apă;DM*8L,+i.q?0k S*.P|N>]2yխ8pඎQS8VNNqՖ?0ڦpLyq'-X(?n#gZE[лTR߾!`_(cHEʖk"MX3!N7}&]V3e^xh%=Ǎ{(Y, d9ڀH#4j~vjXKI ?0I|= f?rMu<0 Dm؍۠i }_/?np"-Y^kfe&G%dD˲x?0VfH&Wj7kfVٯ n??-YbKA5A;, `aKZX|D58 DR)ܜ*??lS!ʅB˺-lUS i=}3c@h=~g5 H#ytSp?n-m JUwM9}g.pF3 "[mpqC#j.[I?0vJԲk|M} x||UVH΁KYCq#QܬP,}}C:]>hE5rtfߕD;࿝φwoGgowɒNSd}CT]ޙ~ekҿ-FmkOZ+ȋ"3vi -hf{tOep"1bEBb|R~zRfmnhn7~Y[ۻ!>AؽP'r@,im,Vu0W9`<)c}A#)lM#V/2V%]zlwʷzl_~Pn6?r/-A?0c]R!)]6EAĂ~~,\Y3;1TG3C_,['h#~irG.\Uh8Bm:ȭZۃu  3KAz(ɭ Y |GE8b9B8M#A_rܩtR,I/şN㱛te_,_<6Vc)}7*iTC?0MezcǃB_yٿHsǡyU@grRT[-(.<p#}UʸYވ~dÆ9bp GuIc *`?0E(pLj!,o 6+R3c&Yܿo܁3c/4Kł '6SZnV[tᛥX8z ,)@Y?n.UmHC4I%l:З.0ީkpnVck$IasBSv `#K$B-қ]z_"ӶGevbܮ7l?nzd.n'|12V ۄk! eV6-(E_y뢕k(BY7 dpU!V?r0ǬkJ1;??3eϴ>A@-'??}͹0R^^XA4u!0GFe??IJ>¨qFl'DL)κPJe??:-#H "` -0d6:wutWNd^V=lBYH>!Ն U]" EYPuK[%LMKL#(/;`'챊kE9PV`d:F&GP6غ cx4,Ѧ!o-"/;|8NVoJ??R%tisQD^ڕLt ?0t:̽lXQR_hHVApu{NkF?0GؿmI i:*eTYHƍ|Z=:ڇXt@s|s`N޴YNS*}#扄nlV?r*Cf~ M*h"mY85uf$myIнC6eYj)==̠:?0Gb?r 5}[Nw:kI78kƭB.O@|}sk„N?r'b^T!A#?rR[ t-$>tvC]yU^@N[4Xz{\RN>ycpeŌ 턳OtcY?n'Ɓl"g حbm?0`ՕWW RdD'KGU?r2kiyU@sAjvN.O]J3?rӸ΁`R?0?n=,?0C!?nPLn{zdY^$/s~JREN5(7ޱI;~a5e\ɢ h?n{/wp>1d_ sr0ت9npZVƔGsOLBƙ€N3ڃa3*=hQz#<+q+u%X%`B&Rrv9psJU܄&{8āͪ;`Zac/b\ \N&vZ7dނVZU~eM2y_N9WH$ +#e?0{zHr> !( K"㟩0XU)ِ^LI! ;,0}[J+2t~3h?nj\T& ;+iu>y$`($} 0#t]bM0$', ٪`?0-n5n:þIPnYf} W©ǝ\[ZIpCD9_4Z,a X,ӃRB8=K??q$4AWdmtz]RѽF&6<*Bw-F?n A ..Xz^=.[=́p4֝1,?r=Cl G1??A2YͲ(˶ɾ8x*cR.3⁝IyD~c[s`gOĽYF@PzP[-?n3NpefaT{]B`AzmYt pu=Í]G(SRb{7d^LjŞnd78RxjGcw&A92|9I$ F+ۈ|U7ONןVV9yF^piZ5?rޣW?r9j?nrÆ ~Ż14ݧPh;t甿QpՋ5/xB*e[1BPb\Q~:jȰ5F?0;C *TǔSf=h.i{۸E,Ȗٵi)?0#qƵXC=gP\%)htYvM[Ͼ.Wweԫ8ܩΨz 4}4 Ӯ# 4F0a|k4 7J$_@VD A/U?nfJ ExϞ*tzDP|q˾Rr?n mAA Z"O)ry7cdzNR =xDb;c9f^Ev_)^(J> =€OAgfi+!!#|GE tN\.) ,-.n k]?rZH<~Q^;D?ns QFg+r+Ra6z/$w?0)Hʜg;j#VK#t_PVAqXU ŝ馽g_1O".SwH+.5a@Ӊg}~t@N#<^ d "]9 3wkPasƝ^GI}MS3)REHr jDA=*,1izõ$[GrNrn&;;Qxꍾ>&ܸ{I5B-tVǂ/LWiF|9a̠L#Gk?n&npkN`sZ~?0j)1ʾm,]ia/^^Pg,Nr (|u٣e!<u%Ҟvw.2 .'~]-~Q^M؎fE>ƩиPtÑklD*RjX_OŲȠ???0O7 $SD 04tchC?0?0H>mr~H7{Pm"uBO]#%'XP~^^T4)wiP c;f%B0H96Q&[mINwnϤ,;-~*gN_]0k(*v0]\Gc?0ḳh,++tqՔG t#=hDm/T%fN5vQD+?0Nљ?07 ?00Ѥy` 5"5(_1իi:& (PFES]}ǐ8zc??c \y,[~u?0wjCNSZ?nфayeM=0:jۖǗM=ƈMS{)>PźYX\ZWaIft瑝 ul^J??-?nJ2[M7kK XU*"m0;}ܚz:)@Ft8Ա^zUSE _=^ ȶĭc%"b-9؇|i"i]`G()7`͆/fG#OU|nl'z<{[qjEL43O k?rffU8W8a]ưtd=k?0??גǯPIJo[X??m'tM7ˈ7~)26+?r$ٜ4Î;VqHo?r(P1/Kbcg‚m72w5BPj!NS.Gwˠi Y+r\U3T_S]DۏKq͋eH2Aajqe/51gD7?0Mgs@|K|*R oa?0Hd2nS[1zUolqs]?0q_\FK⡫!JX)3(EV{.)eGFQBM{??`z!f%~Pƭ*D Naۥ]ݦvIۇXP޵N߯_߄aa?0g?r:CYXC7SR?rtk5*/"o nMc/]~Hu:| Nh u{J0@̼ZbT!YawEY7;^46+ƧD<~NÓB]y"׮\?0/X4#_?n=ջ{it/nW%&[[H\ƨ&ΥV˖47Z$Ιܠ'/8?nd cl3buǺ @h6Щ5̤'Ǭ| Hyzcpl3fd;fٞd??v@"f|`uY1$4_d*??cJI,DF?03!Mceר3,(q=6c/?0dM~ QNF:iO8C@IoͿysy y<c-2`GV_P3hNlgz~_)P?r_@JlhXK97vdDD7E?n$C"ZU+Z!j??y+d s]r:!505VOi`h!"S$k?02z#gs~po\P Ld33eidLIpد6 ?n ]55{@'\H/{t6r;l"NSl3cCߟ#6пId2E@?02{{[VZB$^"Dwf*%:wXg^?r)Ȕ(?rб3%.뙄gq-o/[fРM/'|o1gٕ$bpy̳X*Ң]*VG#Ġ1K?0?r&cg7?0_??=33+=?0==#?????0tLt[ # (EC??]O?r!&!'ɯLIoX??o?n{$^l%NߙߚOXʾmDݚpZN z+V>$MWpǟVѯ-٫1n8vxX򤌐3ZAq3?nUblPE8~oU{ep];k /Wz}>նfCvV/?n[xN4ᑽE>Y* }zm3q: OqmSHp6$ryge%2۸Q0eW{[H:9AMY_jhpbY5<W*r&ߟn';[V7jXAl4`]AοHʪR????՟ aֿJ0韚梨%%AU?rdyNFk@ lqDo6s| +ǂy9Gڶ@blT|ſC<ϴSe7=LCA@?0??ȵkQ5-ezGC HL~-Kn>$^m/8:??ݎ;J-V-ދ,4VNj&.p-?rӁ9Vzu?? ``MӍ6 ,AV, VHM?0B?nA1Fu63-I-W[f:-v$6=1=lGglCܺ7vA?0[@?0}mߥ;E`!h3LSoվ1(Ǿ1*t@忸eo}a䯥֓oZ{r*Ao\gpDε]zQ# Eil,[#Z\u%&:d󬂍'쓨";ڻ8xIѨ[Gm6?0N\-X&U7m+D^e{'[a"2e7] +#rv> zRGCf<$ H)2r.ĸۺo_5#-Ɉq_I9wJmwNm :ƣuUBħs{R|R"fI{ƫ]Qz~P"\Snq?n*n?rP5sO^2xvE.zD4XCjPJBѫtG .0WMH:dw??YqDI]oNiB!颭Pmuu?r9 b7%Yw1|qC)~4%_9$$I")4NDyVa @> َ̩ .N烨cd=Ĺet!?nt[Dg?n?ruη#{g-RLyx8?n,6W|!?0Ed"ձ5Z=jR,5h?0& xc}C .@,yL'WEGOHu./9HJ Ao("7ik?r_Gc?r?r@ G1J8KNp2)c=1~.)ks^g R.??U`WŮ8no/M`V@DYZۯF_G߳R`V;`Vs}g1Q~_xQtk1dV4b5_LT<H|^dCr*KH_Nx>r 5ϣ}C-JܣG\*8YT;ɉRvHփD1yiy]1UB6"_j]Yd^*,d^9,|G^RInSy&K?0!J=C&k@h??" '3[ BX>.86m#RJ?0V_t^??hsz\p'"?noU@,ǸKDhhxl0OU ,qa3ɶ4kw6?rZ{_ڪ|GYrEDN\]!^{QkfEETQ#K< ~Bǿ]Ft$!Y?nw/4l#6[ǽ/T HuʇD1*35=jyC8*fʛ)??.9*w)E)qҡ~Q`b4~/lu.F|w[1 O-D}:\Eή;~%yr 2@T{,7Ǎj1ٌf{h)!_rؔ`aZ/(Q68:~xs F8?ruzǑC%#q_jͩ(8{..|Q$??dF $DxPΖ??x&txQygg|uu\3X݈xW<2.d5PgI/3@ ϋ=рEijeэ&ҋMѠFG0D+3!vG0DO.??# _@dK)pB!KcfBƧT#3H/bX$N_xM"S)*4EA S1O]GğiAF&O] 6gk8gV^c??6+dC1^{NĬ" (_b~*¬˸ql嵚?0t‘f?n9=*e~u ʕR,?nwP7O% %[4Aj*ZKC[5A$0U )+A63úLK׺dgvUh15` 훣8v\ RM]ESѿ҆@j)wԘm%S׵9~1ۛK&*ʩh??DÞ;e"HY??8X?0r7[D~# ??^ܮ??0Ҽ/E~--F$Һdl&ŰârE/?ndZ$?nPk@Y>[Z+J\aٓh!Oߓ%-<UuͻW˭A_??3= K^w<d 8߯ga' bo95u}^_L ؾ0huaW?nEcCd08 ϢCf0:%Ch0: "J ~H|p u<8?0N̐qT?0Bs`)q3dCQJbBAF !]$0WRj@kƁSW?0%7,1%МeP'-SM}pV־!IaU??wPh 57nh?n@;ȇBSnYWtUQK_Iv{5 6AkslNxC۹UR0K3SZJ?0.h غLnޘ{g4X.ؑ9Ëӣu_AX-ˮu$g XόQO?0mY$Qs$ LtuGH*l u{'a9b;?r4OfU"V*LBzu 7A"K++*Ե5!7pY[BS?nSśߊlIo=X=YA27y`C7oiDbkzlhdc?0fSqu+-C/&UZIr-Q)-OVN;vO/xҽopCkB;CumRzͱXK9-T +#NWao v~=)!??5/xx`?riM}7'gS09#rҲϝ|{?nvjOZ0R,=K.Ǭ [VQ uIg>5|̈́竬Wk/wQ10tT:8{K$1U2UlrIbFm-NKv sZ8)StKg~3&Ari 2me&\ZQJ ~W,?0Ѭm9/1VlKӾf :l}x q%?rF9??8soJUA~qĚ_cryGT ^>F:ˎFLrq{pQzRڶgZ!]dhYso\D[z5nL,HHށ$Ys:;Igq>zP?nPT)7ʅYݭ.`(A*?rL;Vϣ\A(D0lY?r-7]isXť̌,L^l?? [U?rSI(oe:QT)l> Rtm8#K΂ 8z$ j&U 9C͟WBW>C'hـwȣZЖTJLKϣk!m7Hs~]?ru9X-C8ZKEm}U6DsTzNOl1fu:6q@X6입*F*NV?nXQ;!:%ol2ـ!|vdDÓpJP 5AN_Yb0qts'?ņSb^{P朋?0ps|6d?rqPBx?n?n/*p%3( xỲQ'ɆwϛC5KK2ɤ9Y4ϐ +P7;c6jLz1??B(lha d,֑O@ixomH??8&,16,w#u?rqOJD3?n*qU׳}eaDoU'AiҶ!u:^('P$& ?nFc9?n˨3 Bkz j&cwM7J{Ʀ\ 1c-F NE :G$ -D*+bEtsUxH !?rF[bnZd*H[o`ueln,_sFGt[OVƓ.KRfs_M*$v}?0lXs\Pv}J m{ġ*bec)N%+I# tԝ)\Y/'U/K,&vAĠ$^3i']w+ˆ|*< A_֫y w3OIUS;zfD+]C*b݅&UܗW챿3'b3*wX8*FH?0Ġ|ݕ[]y`1's2#>_ #2uNgb ³!KJyCg8Ϸ5|6d릅3[y)dE]1jtR3&fG4- ^>s{K:E"b>|6vb0Ԉߐ);ؕ?0UYFG.E{^?0~Jzc&Kk*1wWCVClD=?nhRp 87RÃutcږRkĞ΁ 0oH>:ҵ*f(\0^dfC2w:_1$+F"?0]V寇!TqQˆvcDDC±aH㧙:L#2QlG-YSѫ~ui _L&W٠NoilLaCJ hEëevpwy0|@^/Y/kf$&YMQ`'k}S 8N,s|2l8au=ĭCR ¨\?ro=dLu_W;Ca0]r{~)|PgĪkIT}-1IC݄`FRsmR-BBΖҤ1(\ݻG$.~_Οe:hj7еs^D2{JI/pCu~! טkw/=L̿X㛁 CwR-:u?0< %uƒ"]449Qԋ#~;hgg ;дn/Ȇ\UWw{gDjMv5\%~5>sF??ڸkDL tL??׸Lf?rq>ۀ^0;PwַfM*$.hD-MZ3w %RUx(\z*:n#1w%@[89X$SjlEsvO˜P&?nYɺ_00GY3`HjX7rdJji@ࡷe`\8A>\?0$( 5kJ?r(ي'}&QFIXLչw//),,oRo>????Q Pd) t&ɭ$6b&i-&§=`w=Iㄖ8 d?0;e&?0ĩw/M4TiMȜ֕Scq:-G.;vj(7G [5p,JP0ڋܙ1;k;v=m;C֑jF..[CR-C甋ϖ`f+{va-ܤ֠l 7lfmc+UWCM<^Α#[OBG1hjef&u4~4L;10.9Ҟ)1Aށ>?0ל5:&c/g៞!>173Y>e2mYw?n}{Ư2' 87+K?rAo_,RAFaye[3Λ7d^fYBE߽#PQbCnMb<v+bzJ~FԶVs`v&wn<>< kp,/QɌ9#p??¾TӒ)BY#BڻWQ.i.QW6U>Or^B.kBo.^MVd$>ֿd?rU|=u(I'zMG!S(E/1tM!u< GkA*+%_?0[˿˽cTO4O<[%n!y=i|'RQYyS|jVzqhlMK(dgd^Db˒.8}\2Td(誝bˤ>P&KO]U_>z$Oc^~I??|9|~(s>|6.S+s2eڊXbNeh=p&P,8&hO( ȸQRq<>Uv|Jo:ޚe mcjF`{媌gsCʄ휋'ʴgP͗m 73%foe:nGeEֳ}o5ϻ2q7:;l5]on{lwk/c.ʾGy?nmwqss 7lVb̎ ]S?riL S/gow$ؤT9ҧJ9YTb>b%mKMZ&\;)MgE\:N finfχO:mwκ3?n}@A#`לRjŕQprO??v|png'喝eAekq o3\Ě6xa)gR%.ljI_6E{M6pR?0:[cۧwed**inJ%$P,Wǽw)gofBE7>.:(?n^{?n1)2->ajiaLಧ"ssrj+S1[r*{'>78<æO4O(y^ޞ7D0t;UhVB CH;P?nBVW*h{Om>c%ş=k&g6h[5bp~??UgJ9 ͕`z'OJ2:pc>6e[*??TA>WfNlnyA_Ke7_5=cKv7w vTUڃBװ.jn8fno64+7~> A5ƈ| w>QU!DY8Tt=0f=ekKP;mk0R .uyS^JOyiAV"fSkŽpf,!R3yt<7hWT1=;~Bx{ Rd,A\ijU8 PӁX9NϘiryE¬ttF7k<<"GZ zEߔbNO,h~ ۉo?r+ĜBrAĦiJj?r-2bo[#??d6U2^mnt5i>jC0fV߮{oOʆU>eebC5$7#Y:6qնcj $PuZ璯 =о[ ү(]P&OX{7*ԾZKH{CvcDKhIJߚ.A$\X?rZ6N@5Z%jO?nRkD׺ߖЗ2+9>6#[ʒ }PY7A3ÞvvXJs6MشaSBJe?ra<=bl C@6;B}t7_j@|uh=RF+V܅; ނ,&)_a wziε/~c "ݩɜ~*_K\(,;dЧ^Ė+ER[>渽ib;g]R=2L¯z-R)tS𶶿u޾NR^fkc|u?rZ^{Pv?r/0f8:p٥w[T&cc9 Pa1Pu*||lN?0/;|/+cْ|ဝ{0+iC!ﵵ|9_gE!x??|p#*}xkzyL'ɬӖaZs*-c#HF &SKc?nV#J3Hf=b%3+oJgqf?rS'B֧F{1Zoiq~}XlmA$sdb:籬7-bjt5y!?0;p??8LOĀ??PXd|H ԙHPlja|cYOv.M$:[e#-l[XK8bvNBڸ@G]ShȮ Ay{;#_f*^)E(]tHV;Q'sJ]c[?0ʟɔeLeDY—!y)> f}?r1}^fL?nUN+:ޮ=AZi<*1،%8vuK{:Kmpx=kDqɽ\-dVT_-pxz'YIrq֤ n|5x:_??^ k??!=)h*N7}+ػ2.b=%8i?n5˲MȆ2S7bZfI?0XJdR͆5A[??FB2~ ?nnӱ?r܃x_JՆȢiZӄ=B$J +#a|IgyIfmQem3(-M2휫؛v 2qqlQUT]nΩxV!fyHg?? {e/b↙ z%6%`UcwmںB3e(&B/T)eVx'9$5i_8wu*cP`@.omL`N(qI4^Cghgq7 P YR6U_>4imvK0;4)*쟖?n*1T^6fc\`Ǵ~+L#ݗLb6C)?nfq?r*gQcXj4 ۪R,^Rʾ1ؐלUg9{xĻ5zyČWOhh:yȳqhOMk$ˆT0 {J![Yp)9Ie??sH{RJJ%-ƄAJ?r1N\9ltf~tCy Zz˰R0v50`f%jPVC@203 I9}^ ?? ÖYYi9?rm 4A;2H|' ljjj"=ֈ=%''X9p90 Dw\xVr_'=Bf6F]#ȉ~!&?n&(:mȂ)#eG , o&Rqc:x´㮣?r=!iݭBS?0=À1$!O:{EHvWWA&^gGexlz0 e/S5Z??~׮{vB^]f.ˢ-9i]>к1⵫mvh6N%д.~$?n8v\p[^+M{oT/ؚ,%[ŻV>iL5K}hsUu7lgtvBQ?nhDIdf5?nbR%C1EgtW´KpB%qGwFC)~2fs@$IoI1t5F6 E;q:P$as7e2?rC߸@Dʯ|^"gcKȎk}uyzzz)E?0517$ѡkc޲1m:V,2?r[3Y,mBHOB47QwrT642&%ZI??s6ۀJo?rCԁ% 2%F:zFdSgepZ'yܚ[?r[=A{Χ @1p<prȷOg@3]$?0i(-ܥWޮb)IT|%V@NTp8)wkŸpx>??A 1/AO^:I(j"%Œxd_wk\E@ ,pwY@k?0TFCQ gTab.f%ڛy?nIȦXn P/Dz$>GII(UbރU4big }HC!94Z˟V9c"%Cy5L aͦ-4#!~,I 1:0?r@WK8}I5R'3Sd}??qLv.GpYrK[ge}ʯ8/dN6(`3_SuldIuKamڧ3?04&+?0ѝ9ȺN;i KjO"/=0ۂăꍌ1`?n.y2JYߑDEP\wPcti#wZ>?0BB^6(6'?r}%]!jKc-Y,@ck_G]b:ZP'i@#qb558(5UKicۖsCKˆ { Ԥ9}5eS'nzjJZlA??U?r\wB3?0?0"&$@ř69]l.nrO OSR\?n5L1B|X9E*ZJ;ߩOIєA(xh|f韖堔h[dMyV%'-|T?r0]g['e^@)gFcՄJOԊQ⾹\L:<6Q*W֋wirSTR2n?0Zh-<{ f lF22(&?0lwЖԧD3232` -WѐUM1d̼\-5G6):tV֊|V?r~RtKm$dX@5֮Xn92'?0@ u3kR l;0n0ڒ! ' .WʚJ?nÐ9bʔ` :L.emK8Lc0Ohch??h" f't9:UMnugz|/X>`ض[0b4 9Bh*;^1Z{!T9qոܧ욟!Nf7\QÔv˝?0BO6A2Jn,R~U5' :REq9韰'$\>j?nXsus8Ǘ)g T|HbSI<-ZS@﹜A??oMOdt:fve;;o$3ӳ{73 = F??j_0w,xPP ??$?n~Ȅ?rZz%eynָK`p+nj LaBW?n ~ܲ#o7˾:nGtb׸mb%OowH6*baԪiq+w(nP/N]+g\L|G4&?0b#{.t˼5l8?0H?0iÏ}.Zet"#nKP@[ȜEiFZ0+a?rO#U܃ņVF !]#ؠ?rlD:;D+J&__q;𨯻w>yWoUGHWN?nf<;aq:&֛ÈpsRՉD xnNE@X"H̵:dX8<_1 x:Tͱ")7$xݔ*^dv94'(KK??BIưE|V .;XBs! }~?0pn'JeAj1  a8A!K "bN;b0zb̢YehhڍZ̬8?nF˾qm*t~?rwNrj5 {P`3I?n}Xp?0CGS\i)#-㉴4. $ ZՋTjBLqxWz˸qWJ?rwh1=oaY3݋roo,cn)Ow3f+&C :uw%%7SAwm>bNDž_YhyI M9tԙN?n,a{fKV[yOsFJB7#C6??>']11.DD4# E:+[3?ruƢc5n&_bv7<=/\Nroy4R+hv%pϮ0?n"-z-)spSs-ZL, ۬P~~enX4DR)7q;RM4˿E)|qσyR;񱛞,aPF-$=-<aSA{Yn??!H(ڠlt?0HVS['(54Uw0P[]p?0pC_xkJ?r"AirE1˝nϵrk]J'8娣*4$|HgTyk'*Ʌf}Pazbyzy1P86G4©1x 68]?rl?0^@Brei0Yļi=zӮ}M)q*`oe6rd-̂o23Yb+C':NyƱUNR>+eCSq sD1Ug`RnE?nJ@JX_DV,~z%S06f#po2b?n~JɉzOpQTǃb]+9TXJjvU*.Y6G2P*""xL??6kF5zP)gDk?n?00}3#GJ?r}#ϣM)ߧ؁?n@,(;|pF0a\d#Ⳕ|\?0shɈ|pl+(f-Cúm-Ч9 L)%sSX/eK}r(v9@w'sBkq})\v9% 3{sv]L??\V),(vSYZ׿79Ns|ЄGoEx!ivJn.P瓏3b^g<>Kߍ};#CXL}ڲvp/C2QOe{0WZ@T?n.@%/ #2 ????οpu=hC awo6kBfFðOE4|n'l?01K_aR04ʥ,ew?0~J?nSs?0͸{(P@˶IEc%K2y[ԍxs+UіDT FLW}wI);z; xøEn ߆??i?rpޚ䔞ڭ!z*㇫iFԦ||ЖPY j#BISM|J|XR?0C8`8PJ۸)lS-H:K>CBLY?0߬Yx校H=Mq\$!k.޲>OR7ٸMހ@ߝ52sf;bl{j%E@p~ ` pkXd[[wrAb,ʾ?0E$7GJ:.T>GҍO$5#r^!`lr??!#>> +#fX?rVE?0ͰQZ![5 ]sA`6-%XƃVw`9\jmeԏ\?0+;_x#1Xv`J?r()#(c"ȦRY7=<{o/Ooztѻ?rC5 m=HAqp3[JO?n6zWd?r6ryW(809s?rOP a,@S{~~b;jU {%]g|㛥zߟ}?neGo.ɑ7R({%TX+`pT4m058{Vhz.{nm-z^:##LdoO]\d8d+*!^Px afK]iӌҐčTU(HN.Hm tzFE_NOY#iΔѥEbۉkūWj:Ҵkkަu9^]?0%n$8rPlRp GSlxc`&U2icP [V?0]??m Q&JXUroh5Mm Mn$R.L@a jMֿwE2$,2@B::2I')}y!PjB:`}47+cLU4kd;#H[eà./0贿'6HT(nZąڲ88:eBWhcr"*pn[oՏ({w+m μe5-f+7l٪EI1LX{YΨԧA6e.`60Z_"}:'%(M!a>Q ?0x su_νv0$-w*tV<zl=:hנ`(h[&#y%즤s=VYީOp(l?nӭ[^u%!sK H?0ThY f~vS+%'ߤ{NaC,d_Lc'7П_(|&UFc+CFvUZ.=4`b-T>VroyhjG ?nR5W0F ]3e ̙^m- /f vƞBú$Ր{!8d@fxZzCٞY?03TOOy<>^/8Fd??E׀;tDяx񵷋L@Jb ! 㪔 2jtSc+9xkά\:1*E?0r}Gmʉ Y)2@ˏ.=ǥis9sa ?n_JF)}&bRY~#|N9G`vOp|녃c{z_z?r?0?rMBu@ݙwsae_PռB ˼sP>1O.ziryַ7 7WS.gwW??cOG?nZ;\vͿQW- ~OOcG=z.9ti?0n8B֯:؇R-dn=$}/AGgǣCH3`(=frLV_-.[?r.񮟖V^#4z{̜?rOtlFk\Yns+̵n07tus)-w8͎ >v'Gz?n1F9:uq5gz]\xfctu]gƲ'25n,BC dJEy9m*T<6gPCS h-dO?0nM>w(qV;[Pg|9e?00SGV-QAsG^~C{Oyrn+Ce-[`^bf(gvv?r)wѴU쯝h8)P%:=2NJPF+aRטc??'HqMQ:Q_1P%eӘ$@ ݀09~v ㎀D:ћUp[pG;\NL 'awjB8CPjwzd\Z[7zDܷ`k13kڰ6??7ɖ_e'RiڔV@ƚw): :up0GFlӮfKxZO63dSKL QPIx?0dԀ)n)Ǧͯ?0ف>kEIXYKx;g6|KS$3kϠ?r~]6?nM˨'ޒ;}AXq'V'1SӶcw Ƿ`ڔ?0C>Ih<ڧ1] yd ayzq;4g+ns{?nfRW p̢iCt4X ?n4_a9ӰR4"Nq]8 3v)T݃S,v)hUIskmInD6ӹ0tҟ-x- %Dݼ 2>BêEcpdl (o%͵?0O(s>{G]V^8ZL[ڐAt V $K'+ftMQlg.O_/_17D_Y_ s_F{0<]ӎ/)u$3;:jJ՗hwѠy5ݣ՟òϕK3 0V=O_^SǪY^z-F7].,P-TY[Fl εZ?nBsSP1ZWKvWګ#??"r C?0?0cX+W# ʃ6Ѓ|t>nQbV$ZW܋=l8*ʀTD( Gn9mk'QB?0DGU_cnjktロVYu@f73R-dXf;DWɅ~ g9\K#L?rF>-%i2udks.*04!qև/epPA?04.$>t )e~#%И b$NPM+45VӤb!)j7tv%Eh/M+ۭ.t$2Cm -)$bs:^/:=-fbdZ"JRz~R$\ d\jbj ZJu)J~sѹ' CjafWPC*$,6"3CfF;R+iZ0YHGOщc1cY t~!iXvq2bKc8]Q?nI6Yn9~c%[l;c%ٟ, I T͵ىx?0J?n!ze(6nlqs l/2mEYNh /E5q`AZԋ2.X5`.#Ifim)u6:V'lC6秙.Af'eI_l){$]%'1Ci?rQw|NXuMP\$?0 Jշ`iP f?0Zhz$SH7]ү9,gf?nvZ}妦3^WȈ+/U7gkSed_m"@3Ћ嚧6&~Q#j(,(Iv2eEGL?n5[ԍ S%4 UOȡ??ӊGP22\hQ'h,ћ3GF BXYV$ͮW*#8g{:b4:Y%g[y8&tbOMȴMWC>^|3J>z5*7Z,h Y/z_Tsz_y{ODpT25u_U.11k͘'=W^eIgsHJ;^hm98)0 =V^"(gxZNϱ>KgJbUa6b]:~O^tFLb|]]5[ =?rl6b4z%likBE[ȶl[at _7_ݤ{`?nwGh\֩>NRK/cV@3 7݅{F'WkKQH-_4'@Sfe9xm!E{r=d+ۤ`+B}v)iu>SnBGG/c_D>Yd!eǀ;yȤXm#ٞP-ʆ$eH[@8;1#'*-:u<{_aw6r 0?r]ps\>`#ɟni[IGkʺVg?r׺J֊zAO[-|pA!KqHǜ=%T(j;/^D0}^}`9R gzTaB-audp]<&.h)MtwNF"jGkf LOeAZ۠@0'u?nW7 r 3JFILiT:}ܝ?n??F%Ѧ-@BW,mZU~'4Ma5Q tu6poI2K?n#bRg_vq32ruZo{_`G8]uۋhWo"2}i/ӂC[=V""JūOь0I" !"?r2nS +9)A\NS@$Ki'sځ}DOȲىl>?rU =qKjC3ti)=)fu[_jcIayl$?0\XS#&o^C<ۯQ]WSL5*s6j?n,-T;ۇ$BpQ$bQ֭?n(ˣGkc{Ɔ@?0L7pyń;ٚ`BeŸ(^('gQ \0JIc@ ϟ)ʊO6viWºpٸ;m .8oԥL:Ԍvu5V9?0<]1s0Ⱥ}Crl(isȐjڟ˝qvZ6d=Y61|d EcS.ɰښ=Yȝ5z\^ NNҼA(Xd0 ?0weLZcR +# $ER>tO吵 -'cNjdtF=V_0=6ME;X{???rcloK~j?0\W*5!-jNyֽcFL~+?r<TWa]#ʈ6_ц29 T S3:lMe҅COT)A@)!p.gm/R#bHU'M&+&,WR|&2ċk*J^ȹEڀ(2)&s@#"L8QDZ ˧ #.$v@%]p{wl .j7?rgҞ$ 2X}@IF?niZWtE#i&T㦢b[j:ygASi3dX٩,Ay j>\VH{:eσBah9XRg,HP^H8{"r?0{^WnB<M NHé|C+ECSk^coUfET^N~!8gPH3 ډ-;B{ .y҈P{ c+ ܈ҿ&XkGpv&>Wdf3 +yGá皩7k@ps>Cן_&.9O3:}^P-1q Clzj둻bTfwfH7eA6K;- V`swEX~p2rɯ!o3q3$<h)Ow]Dl7BV@H^_>E=O`iBewh4G 6 >CO[)K2",&3{&  Ȩ(#:pje`"ty@$ L(????tKs+!6s@BJv|OdLdjm,;ddu+)EC$iPHWG6*MK`*8o&Qw0+a} Z]P=:?rl~3ٕ)QWCU ]aGڪ/-/&pQG'ݩgm_Ê~g^dF1`/??D n6;bۦtƺ+S)u)ƺ=5|(@|@fYS\3`Bn:,a׾Yhe)Lt9G#BdӝKduBReK~ ?nO8l=wRy;pugL骢3"#ER5Vd-u&IAarA %Am%?02Z6}! ڌ15ay9DB{=?r|ዄO??,Ao]YsrX"trJZC#r}D-X|O>%dڶ[qbȠC#CMU$G??2)l&oN?0v=z{opӟC3StkղT>bA#٪!r =1Z'M?rB!E$!5)립AK9EV`}徳=;Ow*pYʞ %(h[鶼K?0MtY72VjFU[ӿ2fϢ?n?r8WcG?n'di^U~qiKO<*2Eu1D\2;g=L//u|A_N/3;%WܺY=e=4|Zlak%͐]Tn(M'M+{ Sh1Axȗh'3s3\<LaA?r셧787,4H,X{J+!AZf{=NnA|~xr?nO֕pɠ]*$oRd6 bAn[Hgi~n&KmpX(Lj2,Pf@Q)m \??кt2)8ÎAvh(HZJ$CTQ0(*,^?n]>_ ?0 ]5YYBjY[?0M8F⸆S%7ݭ??Z4?row@V?ny#&_z}D5qz|,Nž 5+ˇWݢw%UF]|~ix1~;O1[Fy?nzlSX.w/NNTE _'K:x;K1 .Q8ͼӹ:@Gz,&<.$By)`?rq.t["Iz>ÄF*F?0Bʤ/a`WDo 3;(Ji GT*4[W[3)J~M5V]-2e}ϏA@EQI(fM(F?n=zZND55G֑>"(_ڣ?nBYO jmKJ}"qNlBmJfp4g1g%M <u;?0ЋIh^a"?0AD.d)ؘsbEDvpz5U!A#1J\3&eq/%^[QG9b {ak'ͽ^{zךP ?rN8ΡZ#3gd;qCz1uHoS@R%Y3Eef!M[D=@,(  ,a 2aah$ԷKry~,:>CEGFjj)x{yOp @SSQ_q<\c[Bh8PavZS#gydrn|0Ny8q{NȥSGKg_bs C?nRA D??CKf oC-%q XO1Hu@0ڕgnZֳ9$W|\<Š]3 qRDvLlFB~HZ}xO?r6~m;$!P)mOY`z?rnh135WQ~gR;A`zzC|u?0nEX'ҾɔUng׺"?nɥἤ ??ؑbd:g4|^u&-BQ"&?0qW?n*2@ֆYRM32=HD h|sl\U$c"+zo'{&yPv~N/12oˎrm `%n3W16"M¹y??b>HY2=ݮL`)cΖ͉4N|"<61\Q#E[$NY1GN1"qAplMgVq_d`gA,۱>VnI;K]nqM7ezC.L 8.xRhF>A MYȬ~?0}E..y^~@t?rL]_#Y)@.<5JʇMIh3?0=(S>I{[!D_7꫃YCm?rD@mœW??ڎ}h6MJR: O/%^тV+W &XX].P0QgG2;& ]B??FP)RM@0*{"sVV'J9Vx'@|~_ LW#5LYFM!ES9ŁK"*O˫(_Ѧsb ӤUwÆcVá%ڤy8Gh:1z??XBc´P[Bl#V8+r_T}8PzWjFAfaJv;ovҕp??|:olF:}Mj˛u,'_發+9%´q}yegr&,0r0"c ⶥwlM>mh?nKOůHՈmXw7]ftdqAz,I?nƋ4bUΛcutʈAbmLrh K.O]yR4E]u^{X7zU'VvGsszf*Q6fq.so#ZeyO$aU2A6u/>ZnmONe>3a6-͵Ne.W+{4Gj!Q!6k>U輵Х^6Ț~~0ی3,A+[a=z;UB~ev.o|ousBO?nGc,Gw'շkkd[o9~ FeILذj/f)/ynYzgKcRyWL&sO["e`h2 D?0l*dgϖ,=v=!@wznF%3w]LdMF*߻QB"SsOKZ9lF#C ي˄;=Q-B 5v}UEGMn׍x?r;@i j&բU~ S)8z(æ]xkӲ3]EӼbe7iux`wu}f4{U.Ny#Qo+ϯG%udɨD7I`[˧|`ߵ=_ORRYtYR\s͔ޛhjƪ&`?0!+Irp ʢđa!M~?0e"7-ws&OwiDҸH;ݲx˭B&Xmi?n龜X;[=cp:H1m|vEl<=M,drmAVNCE8ԇ;r4x"J>(h2xex9n?0 Md?0SL{o8 |L)S3M{Nm[N/.Agݤ ae`~VUٕqsqDg֭u[e);thY2M?ng]Sr0- 83ղ2I+^Dׁ] -k8k+`wZ@A4Dyѽz㵊۠iuM)!K&"%re??f&#,wcBYMҎީ3+V$0pnt;vdQh(=ی*t(j#\ DHUMkQBt]GʉM?nLUL7(cplH .JF&8PVe Kf@wAsmstInD?n9)SQ*w -/]/zM\y\gF|k<ƗbavVXr_%]Ryg7_.̓tꌫ3U3e?n7@Nb6r$tpl%&S_H٥|}jQIPw]vB/+ L>Y뇥g#ke@E??4a:or?09>??ڱ%. riͰ;H[Oۗ?rbQnr#}?r.ӎ"DqXvjZ6gvbJ|P_[L' a:mGVKSzAݸbtjGZ'?n/0#j8-oxvB@C,hn;2ޘE??֏x:kDD%\^e]R>NI,?n{cȬݵ)4X O{?n4#`)^ˍMV܁KeU=^OSsGpֹ'g%k3nZ߷cnW|}ƓxykdUfpİӡvQrK,#W^/]`9YBf~ѲPjH3W!Pe[JszBb-Wc{Q!O"K;)IR\&(0:l67,[=y\KPTzUCdoNnSa a{$aq`\oG+EiVWUwQ*U4ѫrxg G ϽiA3L#Da^QGt??P6/ľi|7cJlNp'Dy ugH-RY`+8_AGr7uǮ3Q:7sx(>`\$]}٥?r⽲ι"1euU9wx=3Z)m`0' 쁯N05/M܈+Ry3$ ھ@$5{ ZM=?0{>J7AOMX$$ qU/Ք!JmQԣǴ@/l/srvvn D!?r@M_GQU/ ??lsOЅQ&*HK//͢;- '_&6^~ g5݉ŧ,w??G0u:O?0o$gvNF mUӹfW@Roa2bP?ni3HMY8#`d! x]dk=?rs;7Y&\ LȬK[[a9GRv4g~^=ӕ(= .,;]6]??̒Aso߻B^tyQׄZRmK;OjvBm,\*{ÍOV7?0vKaJ%wUcG'k:.0rW??E)znnLc#Ȋ[fkAWMܶ@=\w oUIk&s<M-q/X??njn/߷i]SǽprL 0t&[ԅ"L2g(*1G $hQlpro??/QH-A92\DCSL1 Ht\h<72Lһ/FCSDUl;o2v#)z\@0ׯ֎Krʝ*'l//i&ڎ'_-im{MXN3')ɞQsTyнuعGp[d7rI+ę͉O0NǙW('ꚥ|7B^>;] MŘ"WvUҥn߀$ċ 7rvX܂+ :zA t u|ro=Ԁ >??K?0F񓁌M/FxH7S-]%JPt1EOlk7S5.vLC6?nd +gg-zON HL~Oe|dHjj0hFt):Jv|7litdԒf^i-L>ɳoSsu{?r4%ȉ[.iZwbVnrF\{J:;h6 LY_ /tIVhٝЭAFUQ0HqscBFhV[CV0{v2'knhg_?r:*j,glp"B0€/5L_F.=aV"-|1+вIrTܱYBn?ryW.]j!B)^'vhjW%%UGq;FHf#?rߥtSΆ;at?r)GQvL?rA^U&|\ >Ҋy7)6~&.]&WB??"DhTKv6H{ꌄqFLO9k$"(ך"EHrY"  >=WAGZT t +#U=(tVjFf;u0lfҎ[a)q39?0,~m۔)9?01?n $1e?0p $/_\̺?rNsԋȑ+fG[)O98&b?0eZVNr2| 'EC"?n'遳iZ$Ѡ$I$^6Q9Xۢ5|L}se=8jS`𾘾p6'{581gFAh0] 2\")իH??鉶eq!MB'x<T#N%03<9_ɥxL Lr_Ǽ->!*b>hkUuUy< 5Vӎ.ƙU==Ҍ?? f 2+uWЂZ2dgFe.!< ذ vWz+M1J,W9<AW('T%FXyX>yy8|CQY!Ӌ??`Ӆ!idPZҦ=M)T!7fBc:f줈p)=euF[ְ?n#?0Z*.~Gu~;|kg">/ g#w4!}pBSgH*_`!ʦP <ӔN-[ѢY / >ŧI{mP??^(kI1?0tC=ɴL_BQ??H[7)Ln%QP^4^ 8e/QZgaF2_ֽOU14#hGm%/ǭJSݡx`LT9CG2?r?rЦP^"=[RlD=3:%ێ)QS??Mi(;J4KN 䨋A5@<.}ʁ,Mx_k 67=??յN?0G|?0kE}P>dXƺTkF tЊ8CVdsb4B:S;:q??A0_ނ, ;ׂva''̝[?0amdLcot #7*/0/,m!;'G5' f}zHRGS)*wYV]ko1a̺g6>:;R901tܡS g*gr@lMCMF̙"Yz+v"(??옡V-! aQ1Yܡ6v-Њ~ڊ(X2u(xwo|DYxz}dƹyuoǎ|WaŠ#qNe 5E3E|CRc땑D>fu>0fQUFޛ2[ o#fd#6ڮ^|)VKß$F%P!I'@Es?0#^y aaz:#$)0*,TIU#XfУ^4.k{u9UL,jߏ$z?r ?rbqdأ)yK#{APnKh΀B_3f,dtL+ƿ<}^}8HUO$X)l4 GYutO߮)a0ś+愘vW \y:?r;$1lX%,t}6B$k-S[F`{P&v-#jU,lllj]N?0n2\6ܨ ְxit|+?n0wВ7mJ|[>KJL[.Mv)<_hN]_z8tPȣF*J|q@Rۦ!o?08G@^(]qw|_[-Ȼ?0?nehr;*a$Q:嶛L=Yn[ԷV3OU.1\$.iVMyYȸl4Jvh5LHΏe?n6@>}oc_{nK,fW\%AÙ9?0Gb>~1ݨ1ݼMU=Q?n OY d.iH&+(}sCuVZus}?0I^??J48Mr|y UTQȞ#]??}Vkv7z9j)Qgc}E)fW=fzoV{??FF҉4`wF},m[,{x=Ğ_"&#f˦T0=U0iy4҂_ ԠTTCh<' b p'7k*kR-2(ITitSPɁu\F+::ùcX¾qQ@Y/(ږYpQwyI5hQ`Z.ߋUuvX ~$ޥ:ohnO갳_J7U7^B~&')S??>i:OIca $?n/V'>+,zcqgp?r]̮גt_ZM-+W${a `a%g`lê5,baKJhm[ȈzYJ#\D1"Q֗/̉nJ2| +#¹r"@?nz:DȄZ'(,^ߟ+$Bbv[`͵-> fΈm^=nyN U;?r5{>PZ`a]~j??Oʀ͞>2l#i<| nּ͢IoɋA٧-?rͅ}URw^,|2,tڃ%kGљ{rSzJҟ ~}RQƹ_0!rA3?n&}d?0eiK_$aej!nL90b<mp(` ۱J??{?nB yt$H>)+~I^\z{ErkS-|UTk¿Nd&?rVfH_WU\k_2,HuF0:ItV7߉<{+Gw}L.Ad' gr^qXr&a ~(?nl`il_f&c``de`gWgV>O??fR2udtaX<~JhJCzы`s?0iB,??=;;Nt(YM,5sknV,9#++++;vg׼`t>zYk案S%V‡ygCM]+A)M@+lXUMAAi9P*1/x{؈rK0{q"mB?r`X38rS3b?rEͲ@-(PH??_灻uWfBBX5N9f+USFMc꽌AJ[ޔ4?r&&kݐ=bUMfC*v`!u/' r`I%r?r??.o2&xeeLueP1>𭮮3Iٺx]Lrz=tX-/wNi 9e&`@KA_f?rm 藑%sv__8*P۝ѝ̿F8":Yr{t96??ǙWK^QZ^!xJINg?0BrKu껋 '}*E\]'#/&Plg??w)yW>s E06RNp$A<ʝk+':??7?0:DJQ]Vy{݉|]sA#1vl H}@x`x=N/EIJ·96RJs*B)*49"o'֊C5c?n8-7*$E5B9hw& DJuCsCne9v"jB3B(L-k./ZHmsWX/0vj7=Pyݝχ9x5'5–;\]C^Y6\u&R31f?0DC378?0{e^NBP9/vBD+*:Q|G0cc%œ%gN 4n)9%ֲFR,$%ףH춿vl4XΎL5&C$I8)ULdBzej(WZ6e=2jP?nX?0oTKyWOⷦγl?n7stÆɴ@n9Zf[ {j'iEa kk6/›*pJ#D1drigMP/AWINiW ҮDҼ[h֣GJp?rlʽ*ٽt9e_y4]ANhu@#g]L!0oMQʑB-Ho)5vթI?n$D%Yfr #"RLҹ^C/??*+Sxw:4!6 $0oejpi??cV, ~?rh{DӨ9h>\R&.+.K5NVݱQ??eOT4r5ǾRYDžYy"{}b޶ikz]L͘λΚq%`,U_a_(iȦ5]c??2:rndNݼeE*rLX/ aBD$u?rpʿe4 M*gM^(m#9a#7k{G6aHfiLԹca)uRDcٵ!^FUGzp v[ԗW8I^d2ōO[ Y N<nﱹȠygH%b*Iq(#+N~R,-R["oi\FO8ou(v/GS,$Ԟ'e 18ѐq%i?n;.%lgyP݈xa,c4d)%@KNЫtt83kja?0ɾ)\WX<q]?0R^{O-6^?nKu\{Md>>>nQ|TPM)/I{\%%%?nnpg)-nܪn_y_!n"Aҋ#`s+Ye[ ٍK+(r!a0BRJtΫOF TyTh1 ɂNR'Dw$y_u)-??+jުp`4קDO0qOuY?r ZR4˯ǝ<֭Fpokab6Lӹm>ʯɑ7€C=\`Z85.3^ 4)Vӯ :t\2zB qӴ>#ګ^:h=l9$kv lq{}f@0~8(q)2r,.+n;DoQhbIZlՌUed]5Ym8VpU9QP9"'ퟶ_ĵXk`(s2x7}z8g]Uy?ra tz}UpzQmp.V !|Ԡ,np@BZ??Htk9(2=m}įTPYv&#t3iq'4Vjꄖ.Qx1d;mw,d_]=m1oyp&aa: _fYY2I+cpjVrޮ.!ps1j\O,ȍnKϤ|C>-ygOV$vWT^#ȴ?0i%l E5ɳ95rd:6zݠx߾V4Z׻،?nc w ӊ6 V,iؓ&% 8uN329P\`rY;jd?0Z Q[{-)r vHO{8??1SaP ̎JSU52_2kN4%QHia~:*e+Nw\dn^e:-{bJ[7ăLX?0u6KB+WdcjKeޭ?rt#7%9c?nZ4Y7kG`X Vϭ0dS?0RRŸr6PYdRgʡL0-L¿ &?nXeEn2t`Iqi@5z:É0h6ζwQSrmھeW blZ׃)W/Ub*"t*u 8LGR>V9vYZ3>??6%r2sƀ!w"E[ޖRgG܏uX~HzeXݏ:tɚu+Z( +# cJ>8٨%]~Q+QKƘe?nJOnm4??NZ[ Xۊ\S2V:ۀ-EEd?n_$'/لN㤍^?rZF}A"v8vVy:iJ[9Dk "iH #XgIء1z~:y2srW?n -iONb6ЀGl@̧Ld?rLلA_0>:ܶ^ek[s XBgB75̛CbnȫVqX],~Ʊ#J' m!v+RTFM?n` V$~a8l=< 3UiɩExV%"L??ZpaZmN:% aV8*%,2mFldCQ]uQMIڷ&(୘8 0MM?n-gy% ؂@`Xtܠz۔Ue6VeglTa0?nzQĦ/?0c~֮K1unrMy_bU?ra_Mq׬`I?0]0=xW'!wn?n ձ7V߿;ij}Q8Zf~4͋@1_t轢-A`4ÂAuSȼb(n?0͋O [im|?r5f?rfs Nj9ރ?n0( p3Rz3O8|Z "?nUc(ͤ ۝}DHذ2}٬?0xwWPOqo ϔsd[ڣ޷tjG{܃1 DVmDև-i#~fRn1.uAlti]ZJ%MYn@ v'f!,mx\[@ :KN z?08&Ǎ+4zJ%eJM+=˗|rFDقJhN+>{?nk]A (*{QR_hXHPHCE}X<>k$:#/AҰ(ntdFjeU_8o*?r8ۭ2sVmAA$)|guEHߴ)(M8:SfDBMSh}}=Ą:2&W]Vz݁ Ԕ!{˟`>x!9݄r.Sh~F*C oA^0b,\і0,:D lAXPV{JWBBzT_N:1dR'Ҹ(2F9n; nK ?rS9veebUfL!7FDHS er=#(7EgRN.O^;,7åZNݰmGB?rSsr(??g`[K:Z% ŭ7pA$??E??ZN0”5uGw}oT.f u.A4 s=Y.(wih•;0g=t^r)?r .zFS縚a:MbZzBF'3۸|s°!;?r؁spe!`ڽ%b?n P7ܺս'Sp'~쏞{fq??ce0(1'?n4=QQ#Dd:r*$2s}% a<ZrOJDqT,dڲ;0j!P`O]Ѝ7 e??=HE9-ܿkc@TWOuJ.Gb"]l&E{CVH≯RK]XJB5LړcYskp'm0&D>u?05TT\O |+ ?0?0x4P-?0ƶm۶m۶m۶m۶yomjNvVέ B@̴RmM]g@l9Y.hq<1S??EdO UlZgD Z'mx↲/wm@toQ/7ZPr'c0m8`DZ:Clpk$6oH-1v`厺όf4 ]ЪG(B:Cd7IctDĉ8= 6ʍДzYo>\@vD6c9-dD'ÿy(#c~l,B́QPe*1??&Qge)r~4#/iA!ӋݱD4&!6ǞdowJ~?rW*h!wfϡ-ŹuYyO>8?n=q?0Ѭw\hxDl8YN{`V˾U8N뿦Pr ;aD: 8?n?r`]dtЊX3bYUH~l??mUlp=R^˱̈??N}x2%?r2:5$f[ߣ8n+?r8\DfzǦGl}uEdޫUk/;FQ!KOG~p#,UoNW|V9"9}:^Φj.^?rk";"/q9nag옮q{:7zl2\#??"z+4VUv]5"WpOid;]?0H3N8.SQ  Db[)|D"lι\}.9sc&TطIB]D>G+ޥ8U}@??ɾPf k*E֔1l4-%N.٬w??i+??Ȧ`H@&?0=`^h??u֯]Bs7uHjeiq?ri4DꀅcxiWDA183ͦo\bW^ z<l9)VX -,Oc??4@GSH?nZ%?0?nTP6 J^v}K x<s?n?nţb#N>'?n$(8}ũ3РU+^<Z9A2m Ze RJZ9bM )f@}*05R0*|姑ivJz{BDm$+|5ٍ/]O+& Q=A^!ȿ#STϮihY@wZ^)=`\ɷS+;ttvӍS[)AiN(P%0byl.U::ZʷS8 9˷v/%}SĘ $Mc+ꚙ"E#unm`$@&Z[\ruCPEMa20GC YBNʗ9[s7Ա߇Z"d̹.x{Ư9 FI1g[E7Qc c?r]ŠoFT>!˭ 7̢)?nr?r&]A-??7v F7M2OK̖(37š^dP$?0jP:?rR?0 ^X% rb`ӻn6?n-23?n U'_f;6g-uia>)of?rv逥.ow ?0,Z w)uʬ?0re1J^;1|r7Jf^D[:ԣÝd!I%,kJ[\e{֟x_Zfv|o!# Qub??tZӵ3j?07bx JtVn,Fe qB6O ?nX^쟨uBGnQ x ' ۩|38J{7 \†x7q?r4@D| #Z?0$i%\ oc#lAfU??@HZĖ8~ewLMl |aJ܀ $ShbAfف. Sfቿ(a@+a$P6ť1hISl|X4rjTJ$gIN6(mzl{C]zl*ٍs?r|=@ckJMšd=bЦ"?0E?rM.&eTC3C#;bv)Z0;Wp{69$3nC0(MSr8+0AEZaǥ+vD,xars[V9x6?0Q$׭GF9G??)`蠬M`z㙌Q*1˱n!>\M(.(onY>A|*l5\!75AtKwWt3Bqysy:u_RQK!Ӷ@)[?0n p`B=;L70ȿ[-{UNJdhqud擑DRmQU%:yS4pu.j ._ZB'kw?0Ō\žUҬgC/6`:,Ik'"Q3yìOKQpeN\gGRJ%mvؒ?nz|'Ezy `?rJt0?rwu/xs5 {D(3,/*R央'Dį)I@|Y:i@?n>5α{{^"`L ^ֆ^.[\U3k_! ܈sůɴB͏'g+9%XK_9=Zgͅ+FKrZh$N`?r1ǝ?r1.ƽ]\RBKyvs?nl#@Ӑ5R?n L0CdSataYQ 2T(M9:ΛH恉2XCMɇcebӍ@O8/S\V۞H>9 II!^eWRTC?nXpbP {r`=L_[na0vڝ#|ol-mK˾'K^Jݢ/9ʗ9=ҟE2?nJи^|GzgJ|I$H觰KsIo֡ 둂d;'1^ z%A8?ra0_ƼCbtaJTw$|YwԖm$mNuZs?r+I[5ԴB)mؗ81TufUEJuF{ղej2(@O=s\GeJo@o)kjSμ?r1̔<>w]X%ep1_4WkjBʾ}??n}:ne&W 공¶9T&}Guy[6眧ni_vnPs7""BJXa$;GՉF?0PҼyEe ) 38?0DzJV??p㈟"#WOʤ*=Iv%qK#2!?rR,Fx* ;'W~ce@I~Q{jL|3ƴ' a|lkZkzΊr?? 𯃡\c}%ݨ2" eÝ"r+w >*t5|d#1:^jEjXGbo*>Z S#b\]цGid v\:0땚r7JSl0p!P2}H8_+B(vP7eݹkZe\sA8j%6?0My#8P=<t榯dמUeDY+D*N5 ?r}{:wmZ6^~V=s![i סwf()@Wc8XIF *[מݱFQ{oi_ q}?0 QkZIC9gW?0`[O ahᚕ\D +#$1xa:BkX-gsG1"s/ٸo\Ul3^+|Qu%yCW:V$n|?n݀N+3:aNf?rӟ??|>5.{%ФZ=VҴ?r!it;f̯RXv_RIhsLvŐW}[W|?n8?? &#rZɹWÎlr7*1Ъ.^<ъʩ4+eϼۧ/l ax4t.b| }P -԰;}O#M=2yAE@ł56+b98R8R6}oF@Vij47Z?n&<;fAc$"",Q2!1C[sWǎrk+3|=?02#O8VVdzOd[C0y0(%M;Eh`.ɍKk 9h|S7XnKBwp6¨ٗ o*I)fR#?? d319/F404cJߏ??l(е<Aj:c??[2MZmNߧ:g}Wp=m { zzY%nfknw`@;|hޑ0??5<.nT_Kij{־S('HoWI~*³4=7YyF~D@Lf=q?n#S]L<>.,Ɍes61.]=wX/B<61; 9p|4BZ\%S,u&1* ]6} "o '?nrzZ:>׎BOqҩOVMsGa%oX_' 1=fN5+;-!iL4ѳң&4XTwx@w_õ$dQr+8ϊRfFarЬ&}lW=9F|ˎ??g??nbq(?0&?0 <!"{- Jhh wRGlg5-Dcj$_F?n!@O*{ 1??qO)l ]LQ.?04#u!D_Bʕ a??v-khm=>i{P>+%M;rk1eVJʆ{`Щ^ũCpy?? P+1#nܐ?04V'9+4uw[QIEe8f5~3IC!s9R[R~kɈ F]{gghj2܈QDD(CE{||(',Q㿿A̬1EZJC3 t{!?ro5sPk'T??V7ظVcVY;0;mʊ7Vunq'duU$LfQ A+Q4`|Ck.)m:<2 Cki;?nO :[NYkYzaYkWXAYl̩v}H`V@hGdu\OfDȶX?n%ޏNri)錻?n|CB̅,?0ǢCR*R6Ao>L95 I")7Rj%VR̗Ux5θϛl4 ?nPstnLU &2f}$ei>WO,;܎?rco?n3?0{?r-9e^vҴ#j~j@ˊ?0q=~pRjb?03h,bT  oXLVZW_f4Iq9KR'"`ħJ)Y˟(?n`#LcdkŊn/@AcsQfNDzdL_@Hѕ4k/|«eSPޑHgu)+,IR$KE5ףiϛhG1 `ȲcW4! (K >%¦T`rErH)yFB V\lN81"WU?rg:[2]cH?n1|[2PacҔKhf[W@EзE=d/mة 8a`j}V]+l@!%e]t7KBsy; ߯??:;ЬJ:}bzjݍsv60ҋ$=&gy$`.vSd֟3dZEJSyN??bBkxTĚr?nbQ Cj(ո&"UؚbJ;j4Co3Ho ?0߭sQ6%WҐ'r;-_PPhK lR ܻ>Z\dX)Uͩ'nGc˪er(ͳqd>--:;:"Ly91\PShsFCdNo7&t$R;m92??vZ~:5a)7wauP{Qv8?0 KXXL<8x:xfynq??0T0:6EF~$QTv_ơ 3,ۦ1qUa"5݆[?r)T),/k&q@%szoaЊ8"u_\0m7{h$1["UTk2rqYֿ֗YlyְLcAuAIi2*CDIn܅i~"J= ]j*=h7BHX[ P|8P TI>'&2-T2P8Fm Leq2y03}- :(dCj0d*g(q*{ vQc1V%2 @ ^>A%w$l?r?01B5tKqȈX#ֹҳ]r;}h~GwK"G}.}RF;cUn7+~OeYp`B&V9wӐk};{h}N7Ili:_Bg3wz߾(9% 3]Rekoc:ŋ p,r_!R?0OzfLǨX?rAG!y`wSbM47YX[causrr{z9Ct{i?rL[ izaܮNRQ@lXIJ=$Pa%T3nSˠ pL]fɭS8b֮7Hg}qR??(Ϊ?ryڒ]Hw{ɤiM1Iz&BjObvO1Q]ao5rwx?0eNNu%u?0{?0֏aʑ%#D?n6NSlJhށ1|ԁZͼ(V&<`kWO=8c?n+ o>|\_(m6??yPTJvQMW-[uHG״o=$yG8*ea !i5ò`w<™~l S,z9/myQijWyyQb)a~LB7`z8G8qnW*T\,AG׍ A_j˛~?0kp>&!@"#G`s%>t?0{CQ͵wgBe6t-ĽfJ:Cv[F1T(fRt+5|?neOtUEtނDncg& SLg93)= P#>Rg}߮RMBJ-qvX;᎐OV% C*tmk]ߡF/ `~TTj0iRi]w,ӥ0)|mqbe75<??(6&N??[H%M3[ O>K ̝ەEԂG3zEHB1zBNU0yQm(ԎLZ>=[,]kc^ xhmFG|X]&#%La5[êi nuF'Zƻ?rmw7{um6@FA4DRM7@_wĝ4]6r??s?r|w$bmZcP(ޡoG9U`¿?r^pVȗ>(.=ľ^:gTRqfj|\չտgS7>-:_-aխOr>I>riꓗ4-7?? dn[lYYipZt_VxvS9yO-N:)d`,YITY_'.27akpupӨg/@vɋ.?01 %i*.<э2"Z *l}L1?0 n!^Ԫs3#Y@2L3F`Z5-6 ?r yCUCkF wQE^A+?nc?0W}݅ZcKctО"ѠȕIg#g_W&??KoL .5*KϽn8qtR:$;̏YQhuE?rC&xHwǂP={)EZ2gK%Z$ J3I;dž%&bc막{~~0g);=\@Jb|ݞe`̕ie .ߔH#ٚ%:R+B1ñ !'G>ў  E`G!,<$ڣs,?n+:}pW&7l5/\Sn%fJݎ03FU{y{?0???r$*1,Ԋe;#y9'nB!@ODLK״=fCF't}Wz Kϡn+A]s_0h]bhE)ZBjxç0A&Q'q pinXg$Ʀ͇?r$3=EVG.4Fz;?r,xC(5e#n[j0"{1料pJ|v=@ǟ[HN{}hr6~20w-X/$)-?0ǁ'8DhC.Lu֦f}"F}Fc|IFA|ۿr`.2bt-\+BD;eIzx:hRuuE1tBjSұ??y)FϿO8Fwme9d7W;5h\<>._!??ݞZy߉K#E?rlw^04<`^AV`XԐ[wJ?0" 7yS&<HZB[\VҦ$3o*,h{9.;]vga]g;?0?0PP&Orӑ??npP :|;=ݓ_RmYՇ0(s+C}[Jaѷڝ݁Wty#7dfzR&M454d>DXX E4"C.5 ze l)0@X~i@l!ݠ!(E?rI>6äΫ|DLU~\ GH4UqHo;LQn?0S"*J"`<7BxN']S{|r^~=OVhaNӻ.€w!>KRHc>C:?n ]X9fif؈&ڵ2FsSˌ$p?n;?r6w1$Ys4㸝 W2c.7(npy#v<5$dKaĦ2U,oSXm)ⶵ 7uaYTpLʰ??p 8?nPF~_!N_4zgKZjwjSh@W bnqe\!qJd`к5f|QGA>b6v¾M'%%}{f#?n)݂*eC(TUeaV/jlΩBW4LUw#E拚h8/ɿ%(w@ B,O|wʉSZsh6%VS')iyK:U 񧿋Jhv!c0!U.J)Ka5A9?r&UQqޣo bx)!4pok#IԽ:EIt ?n`)E̗e4i@_tZ"d-FQ!LB S;E˜:p/SEM sV?rkнhI۵cV<£tdOo??2]l>.= ~XzŤ_VMinn+*<pa:4,GFX_8FLz<|CL9^jK.HA\ˁHRZ ŧGey\Q*OlHH":@>WKeImW1cɢ%s+(k0cx砩3{kBzݒW2V] u($Yy??oЗtA-f9bIR+,r?0Ǒx\ګhy蠹^cā s"iC\w3& ^!nJ\.ʠ,xf|c+7UȈ?0yIWIrM?0y0.õ>dh"?0cƻϚr[+2Z|`a T0H>o$8b?nP[ۻlsӍKTh?rzyqPG0I3{'#)WxKzI-/IF⬢ 5I{LDmD g]fScO&D9&_Ƅ eC?nV@~0,e %sK5N&H%G侸\U?no\AY(F݃i)0ҷ Vl^?n׳S*-T&m,6Kw XdٗR3EԮԏl$hz$A UnjhJ~j=(A*4qabgeubͶ0X 72] d)NOzUa89cӥ OE5M(Tާ)O{s5JVd0k)[$u4{`~|l_8??010032V&_{4=@ʊԀ]??R|͂G gV;E?rn-)J6PdwXz0&?r"2$vbܛm9P;Al Ǖaٹ= E9P5[-CY#zI>h>sXS??`(lkWUdqVZ9tMf#&AnOC??OP ;RUDsfR$$M??ł}$(fXW0`jVC{?n]n}"TBTL.?rPUvp|5??TeRũy5N"VTa5q8E͂IrJ5 1;9\YYz?nKIZEeM0FdO??eW6ٷ(S%ֈ@_o0<԰IW4ZBfF&ozfAH?n?rza2iѰ[uo-h??q??6PgL,˚+O~)P`33ڦ.6Fow7qBvy9|whhnN^E.PO$n%Fj+̽n "+e g U7k"wS؛>_곷ً”kYҚi,X9;P)SӻvOɕKIu~?005ta`CzS Օc6߽: ֚LΜ}m??8Te* +#/,Ê軞^^Y1U[=]~݉gn6j'щ }?0+\3P*rA?r3u̡\vjbosM}EJW6́!ԦM2^$/)L-qCfi@qDqj,y@$iJ"VJ-/,2dt k?r v_ڒJrF؇?nsjRe \lvQ|͝{8]zqy"??PIٹ?rpa,XXt|·p.\s3}ʁn?0%IX,0}濜Ft#"JX@aqp?0N32~ h'Eɤrs||[/R&ZG?r4}% 0ӑI. Ă?rhpR-í{w $=tEt5c{s_縔c X\KE1 \!6MepRWط _țf$L$VNx@JVValZ’?r8xqjnd2=hCQԐ<ҩ4tN'#$ =J]c?n^jn6Y:>hl'~@+{{ܨ77pE]Zrfୡ5TvL⏍">I^Oq'7GV5RTIGER;"DF]][גkY'^q<7v2 y?nh15͡&941J+lRۯ SׯUz`??q|J.aȜsj --rhɄ\w'??C bi5|~0ȷ[:!۠U0@؊Tm1Ú1ᕃ2Ikc6QMwֻp/lE^¿"ɲ&8$kM^XXzQIdwro.jΎ]P?0&?rܿ?n,A ȳ8KNbopY E]FJȘz-T9@~K?nBŮ˻gػ5ta竐,lB#&oBE^D?rQ?nʸEgXr毁R'E៨.b\t/b;RIU$D]77*WH( mHe=eNaLZPNm؛<{Jij<36>{w[wB?n"^`I'䊗'.ύ8ٓ^Q &kyD1L2LPZh?r|JdfD—ܔUg6[T.ᢳk%??'r(cX8.vPXYv~ZFnuynRK}A=ʰUG^XڹC܏ۥH2@?n%J4ܪoQuI5 {ö?0]]U m!6EYb??]hJVۣ]ۻP8e?0ܷ?r ϛF9OƘ.H9<̳ACFT[*P.%^+)C͒4~CFO6̳ N)Jq5p%Iq4s6Yq5 y~AiV1|pv#3G3h`zbΨm:Sإf2N,e*3D6i 4ZXQVKа>KG!_yJoXv_+^{tMD>_ Um>Oz 8@BNFW+QZDX5} ,/q>w4p޾9o zu3K.2JvG"g"tg`]'$񟑡??&F1????vB~@(hL9jNN88'5\w'J&17?riLJ8D[1|m/`BԂZ`U,JU^Cau?nIO~6sJڄB1Cx_w};e3Ir%Vvjfd>Q@ݒva潳cbS3k]F8gLGa홂t<Is~??;f;^BWk?0U?n">3l+VFkb^DCp75ٔ Cl`JSVv֥PgŘWH%oTZ]FAg?nUOԆ?rqoBw211iŞm+ܡ?rl-,Z R觯Y$V,^hJۭnfRu=S4ܳWǛǗVjmQyPO#'OK[VOoFEeY*F^?r-e+gk^?rM7)r)4X)^?nshV1gVdw/ݚ[ލ.Վe )^0/)-O&xVOd&h2!2u*S==㓫vP2?0!n~?rJSFߊ ¡*ibjltM+UQr%>Nj7|jfN}xOʂ(nLpɕ-(Ӥi`7DsWLa;P?0\_`??VF ,F1Đ&7x-8=q!(JЫH9X&h I/,vJbfHӞ??hkQ8fߦkZwԃɆKm0TNJ)%P@p>]soxJp3p>M:8O_Ï*X ux%k-Ĥ(Xl<&k('Z?0ǘ!:)1l:NX?r5aLfAxANVb+8)SScVɼ6fr|/42GΠX!2WJ2b mc@% )'Wpy@Pg=e?rL]l7EbPlf$묖+0+!n`nnN{A`VNZAƤ͙#w$qL_~D?r?r+`:HpK}E??[m9VJf'JD#qdJesS@@L>6ПPh`-?r4څol1vAN . TKaZAy82sCLK.ԹjЩ??(prv8 WqA`F@?r9?nԱ2ZY2v'jZTIY3+$N&a #T8A'y܎g'.\ y??SkmK`W\=[njbOeQi?0&WdPZUq&;?0<(~2x?rd!L??+~DG0YvMph>=|YܤmM: @âIOnʟmI<9.6LdB ~sg?0'h7.Bx/ۀO,dc]y˼xLK F +т0-yoLsFGm;͓U\U;j6/ ?n|>8sK{ &z_8n]p&ջj;???rcBFg/rq[2pW dNƭf??oFU}]LjdX1)ǎ&<Cn=3E?08-p`{gPDqHQ[JM~\꿖%(SDj.Ʊ c`46aiYM?ne)mgpୃlB`e -q1 xzq׍jL0?n?r}UthVf5 ??IƼKFSMqIzIZG$0R=f?nh k|H.PY`kP@#fIŤć^waNdF4^8cn ^8@=Z-K`Y`^Ss,-; "wwmhU^VN??DJ:DKw(?0*?rO,?0uϞ%캚V i6Poeua{j~8^RK:rnS$hR'ĵT???0?r{`,I^p,Hlߙ~Bm#Y88?nx} ƾ9hyF?rZeXӟcWwX{rnu(̳7nR&a7q/"b-6=N^זwL[1B)HloY9*򺻹]mZVҮz>h8faa Ug494yC/2h:#t.4zW_$o|U*&y "dFw;MtXxo"@!k. E,+=̳SVzD(j0^֮B2Nc*:Muߢ6ekݣ/ +Z9UN?nAV*>2'472-1PA{A ??9$R^x'd㥁ondxBإyw]8C*;v1!ܭ}??.ixqqIsu,"<6]f4Mn1 -TA.|Af7 e$u1_GF,`cyd$h9̡ `߼:NA͏0n't4uyt뙲殶N:AʞcH:}}. 8/uzA^DS3ՄWV ֡˅kޛG$uc_4dYr%lbGhQ?0+WRŤg4_;?nmg#qm1GeveߚX~(+/L3cO%(a!&W@OD+"U !m0B^??7T=$$dk(6 x6UbqK,%YaP%:j${47ٌ?ruvh,YDیS8n^g29uwUEf~t!_{kǘԒzs=ڭu??f4zu;SBu.{^$@T hEio,Th~v * !Q]ayo1(!M[?n1=>xNu`E py!&$jEGѹq] Ecъ<֥'M44 Ԩ7ӳN edT뵗ܪWSϨ)Ħv w9ScG,Si]޸6ɓ z#$[ =*cTZ%Z_GfF]vdb)P^uk[qx- ;+D:gOnKSqvf^ŏH<@rh!)*[!IJ!z>PEIn:WOv5++.D`f2!K9V~q+u-e få{W8չ5])\k{v=> to4ئځTaש4+rUR`9%dw&uHM̟n~#ϦǴ)>JY5H0P??W&Й'P6}ta/һoݴn\6Рѽ?n??D7#|m{sfYPnژJϳ{':jy?rH]xn멇OadQ"/ 0-k}JgkC??'K@{e\F_`C?rE2vaS?0pV;%?r羄@>h]>amAZDum?rn9)^Q젻,W[Ƶ$$KgK|_WtD|Xz.*P3??XMŁ??HRQmRyDž%?nT??#i-gV{{w(0=QNoܞJQƟ:|ÅIIΎȹfӦ?n??DLMޝRo8f?rƵY&Iw>Q."B%R.`eeuUr[a#)B E{G@]j?091}VMXu2Pwm,z*·e;C4g_7|U u^-eU"SeJ(." d٦+CvWH W`'L??"Iƭ/tBX)]%^ava On'!*}5WܲdN7>????t!"!Ötwrr9픽MԘ}Ɉtvlz\"?r<}XV㾥yu tgvO؞JAޥ=0Rܣp矀\Aگ t`}o_M40צ.Y4r0cTJ(a'jk=s] Mt\8I8wÜDޤ>)Īo%7@Q}a/!+ؠddQ?0>`K?n-ѐ_r\вctOpM3ݙMkrםM!B~nW?nω2̢nbV`;Dž{(afĄaTӳyg4'?rAL1_,dxFf mJ5L&vG.dO _Ā7i0;y?rX7\&y|+[g2'h~.hb 8x#?n/sR6??s+{TaLnx; )XA,Šs?rqdu4@9sM?rjC^ GѢ?0 1213?000231120??ht@+hDv`vH'TvRQ陖?01]W'/ҫw/L??jÉPϦL44 e>k "0@T! ?rYU/@qr$xH?rߦOgi)뗴 jt!* aMѵ4AsִRqCzC͗C7{F$ ~f- ,LY>GoYg^/W QpI7CND~@el*֚w:gNL??սd'lPu6@HVȓKb1ɜseS+ۜq 1Fh];̳ W0x!!ЬL5LQڅ$g"H +#3"#2gTł-m(Ȣx (+AVR5%*Y9YATN:sh2-rj!5HLiqZY%)+Y6CHĐ8T-B^J0(m*Fk2B(xFvi'J'öx7?rg?0!d$79Zk8E%BG3sQYItY`v?rLč+?rFǾG7cPi25= yASK_ e%Ѐr%xZ$ U񎺢HYVhXMe 4֌Vs3#+ܰ@-zz%I@|vp0?rwֱ~?0k{m6ymh[xD+QiMgzz9xC@&7³74?r5ʂpEҢibW-r3=m{)Bk3'y^})Ɔ_v%/?0;<ȺF&Gz=k׌:<\8j)jD[$?0v#?0iTx5n®O$X!a$JߩRt/M9ڑ]<}`]*1B&4H&<6 Hݨ̼b&V1/+-0tWdZ˞Qu~^"h2m誷xN`iM1}Q8ʽe?nHwkI`bJoIk!,y4/}:S 2HGCˊ~wߧs$?nD{Md.lRs4j?rd@2wT0߈獏x),˱=5SNceeeL "v({i}Yqj'cFdbʦBUsw&Ee14Z<ԅG?nȣ|G~E/LV^/W*͘jʼn)5ЂGsA&=fMSQp85_k_iE|0?nyV-@ȳmc6,Q=^??! %\Aӓ9uwWޥ́DTi-}AtPcPNB1yͤEqoNYa=!w_kU׾P ^j"츘+ې.tVאۇRANuk;vz]< UЯ;/D=9U?0cJZ.e 0>G>,=Y-E3њKd=7dsvc Ob9ǝ=3ZDZ>mה`㎲wRxeoE7OgH%yW^νw ??;Sr =5+?n ++F bOws?n!+tDbxOS/ g~:IARS&SoښR?078b֓,UM^Eb~??8-ԶASvĎR.|LuЍԥN.+w?n ()cyKBnl$$1,gig`+ȁbInÖ}3wζ!K;)a@o}ϲ7rSe!o$1LQgJzwH65 m'(3)xЪ[IjnXG^7FԉM)ۍ"e>=)Ԏ0sV^^y?r/ S_/󼕱gUX|My>ENU%sK hƃEFL!!SUfEﳨW$1##RkBhZW]^|OOR6æz~pI]򮐜y9Gt8?ryª8dOp?n JZn  FY-?0$)_&޴=!9#I2YٳltQT'Rjr`Љ8 5-^L5(]@DŽBkyHbhQB2C8nVVUsuunlLk7g }f*MBGnׁ9}PR'@1'V(o9ZjȽk Pz|j8hr eAUySX֠f9v3Qvi=,?n018,6٤>/HwfzyՔ&n\Szv?009LQ\d??FچAU/OX^xu6*ȍWEP&g~6s*?rR-P4)Pzyn Ɉ6lnA-dw)"DvCo)?0,n~H◘2mp%Ӟ+)SR~z*XQUX.kϥēx.+y;;Š.~TĢ,>wONr$"?nf|)KbD;&Ȟ͙Ĺudgeê7_-jUHN??&c[Soف]&Q^N'^ڴfG oנ_+ 2)HlI%UmI]YQ KTkt%e_>vjY1kmZK?rw'Smy_Xd p TE%:XmG׿`@.nWwrock6KqLۦ?n|8k:( X2qRnUVDon\Uv"[̈zV.O ƻ6vXFoUGQI]`g;Lxf3k +#qd?nhck4Ln}5@n/9T=V8{TIDS= tip24B-XfXzfIl$yO쀡[7^[3ZZɔ> zYemmvkKA ^WDU2Z%dBl$IV,GɌx,Wz&{ؿL'֭)lC#"ͣgTYqZTKlqG+g}Ggz/'q?r`!laL)5??"?nV&<{ s_z:^ дQ꯷ovN??QA2 6R.a`c̬`ZnO/  AزX\6y3ӫ5)e@BۛAW}S31ץ;?0=aY%?nOuQg ֺtN9*etoh{xןJjJ)i}J+PY>mԦ^X7SlUSHt֏V}#s![5V?n0eޚm0M$YcC"z':OXXF_|/#>џGG>7"X4AC Wz_] rt|2ETP^}>>cs(', _J(# r??B}D}>z&{\(0ݻuk첡D/heTV :PJ!&RTC&|c Cb숺xO)yV,ɣ(M=]復OMSIV-LBoxҡlgaBkT6"i* :͎!?n77'&AYF_WW@Noz^vz Ύ؁#=#-#_(~.@4@\T ).u8dUYѹ@=s@@.?0j> UCѫ2q8Ҙ'/NqcTz ?0wYEAe!_rnC|~N,CXg!a)sP}ŏ<%B6,?0UJ%)XBe&-^W+V 6C?n47 M̮n3/@Н+{8SѢ{gms?nA֢ Cfev6|G΢:"??b.Q 1??NVWxH=RShQ'w!B¬BO|&kGOk_վ??j~߿rBoү1Q/Ф+X,[!b;ӆafѼs׻U~sAk' K'eK-f?nm=1k'p(e]Q|D0oK[I|-.#ͺȃB^Wy?nK?0!ϰ\?n1ZTz??1FY GC2- ' SjS! g$cW??0??f2RG\??BFKOg=}l˝G7Ĭ!`Y :~8+qk%Fp¯"Cp.)lJZmAV E\/T uśNJL{N~:|$eeog"Um.x6xwWc|9?n7T#qkA1O2:2=+Rv\{֣'Wj!ָp/cw!C^*jO8.ߴC}0R<ڻR& ;??K5ly!77_I"Ӳ(e rڸm$nZ@u Uzndz=Tr6Sˤ=e{b[=ȇz hrOA $ȝ1!":ios "ľ{|Y?nNW]ΆRs1b6]F!DS<Gݡ"͈V0 'b0)̰6qt[Z>&?n'P~!b;h9 |ޜЭ!$Ҵm93q???r*UC\%b`юP)81%p#eXpaT9<)]A@.v[??!w}#'9yWA BXl˓+EmbI sVhB4\G](9Nǟ|Z8i|u$"7=G%*^ZYlR>y~5Hŋ5zn43&.OG`ͻQ}n4t08Da6VchmmѲ\Lj>J̄j{g??}:5jĔXsafb*1s'H2}z0[K PmQ+z*\9M|Ҹ䇻g Z@I??E:wJZD́3;|9U#`iV˜H%V5H#,fK`+Yb3 =I&gy`7cmIZHCx= G[k-0ٮOQSMg gP(2j#;JfVas N[)}dfVI5؞F||r%P&@CRJ#Vz7odg{R[<9dA+M?nT[|2}qJ K)W'ֺS(ks~mY~RS?r\Tf4o+h)D3AߟN[P.vuMڽ8J;C~S6E[]?0&XIhF؜$89H("3c!{QiQ/j*#_I*& `=bhMCUX.'i9{dibԝt{ˏ+۾Y5͝sHH|Ӷ,J~zT?r-bHQw˛FdSLkCnN挭ѼJ8.?r{|$EudIKoK ˡB{ٴvWA7oCWug6-ns%mz/m>}Nr 4ڝ[ xG 4ڝ^??;M??g<E-BN&GR JH \74}D9Se;b| [B,TE)9V3/uY?n0.:cp!]6qQC'LE[ >و%xݖpC H=Ln;j)Eߧ?rTO +#ʙ5o)'XTbQSJEllMQ@FjbxI+ͪGRGk9'@%M"Ъ_L9fT{ޣf?nENJ7lZiU e>h"m/7oKh0[hl#ZI^eOPV-7?0DA|}d |[^4\>ū2ۤY4FGǂ}-Xf T62,Ѭ!aB*'>W0 Zn["򒻜»Z(#,]޺žkUل6J]큁g1Ќ?0^Cr?0}??h?np |MrJh{\LlH񟠁'Sˆҳ\e,$97lNg¯c GF^wD4nDRC2< a!2GIsDU59KHD*-q??Z +#Ɓg1>)gh8Z~Jy_Z35FS]cUv:Z&B3JX2}V[#sbl'ģDhLO&.'üLdlFhbLfܗ%%W}%ee( ?n0P?0\]9lYȊS??;6XƃJfVv%ivDaK(`ȒQb骉shD l^ N_A|@^𼣱{:\A3S5xW3F?0,ЪR>j!\bTC[74sN(Z<6$@`z}ҟ/#8巃ĠB٥4YxP?rv6a[z7G仴?0}\;(0뢩Q?0qڶ ǖi-?0LOy4Tzkζ=R>@ Qɒ 4U~ie{01lvWQgH?0O"3 ;WW~t>T(uGG7թ۠oBN`Z}?0u6%Gj䑿^G1x8+Ns+(&ˢj%Hh?0漮o͟7OG﷽?0YFs}l':Le^ݛ\p?0(@Cr ,dL܎ A/E fA %dZ.kQ??c:wjbڨ$aASѽ(T?nlc]QcFAdL??Dݪa\Ã[ka}R$9,;Cm?r8(&.;c;'7=+_óucPw~=8È8|㏬HF\gKBw=5\q3c -Id[hM2Rs)Ca9Գ=/[yynZqV1St?rt=Oh(G\]?nQXl/hLBQ& #;fQF!YZk**eoiȦ*`euB2tĢtiDMKczd%;dMGf-Nv%( omY??_VSHЏa0"S[2|2R=xCqOO9?0Fj;<ڎTå:6tf/E8l;(Y"oL20>|v,ǒt'LDCsWG5 )("1rӇY{@.!w:p.Bo7{ngT,{Ehp_pyO'~D]8wRD'x6,+3ܶڥy:fh.G_xN|p>CUNwxQI~Ugq]G`ss{f-_BKz۬ovNѝґn6{+uuO?0RAՂ\}1WA#{8F SR?rߊ?r~崅v`zυ;p?0{No}Kp?ncРCdQ*F=MňFjK~IWqspZN?rV8d6\;%^{Jв|O$T1M@^l535%N~<ہVP*wk{;6eKao,I??kǧDZVX٧' i1KcC(nʴ:/c:~ tbu;g??|f?r`m>%F~.xYKJ}'@@|wTG<}#]͵KZh2(rY1, 8QwhjX4W3`z9K٠?rG"ru8תYԺMԖ7eQʕI̙oЭާ.Ҧ(*"G˼a: f&A]-N??wy+vS>IDx%/".3':6ú2Cܔ>J2G{Aԑ_mfW݊qHIq/SS6];c8e-3c0eV66-[s村WBn?n5'C- ۙs?rSCX\??̹yso;m9-N_k6 ?n׼_?nW$ݶcՙǸp}C??|OPO2FS3biN^ve_+trS~{w@ MRDw~M/8‰Q{80e;нSxY6ڏ Z&.?0&M=BM F0X\$v[O#ō,<;dTN2Jo\@ ' -C+KiĊw?0xaȆA|U}#M't;d~ =쒙{"уm9P?r舓߄@e!M0Lk?rKa2ANԼ8^iZzFE~sGR,u[;S/en-s{B޲G?njf>^U34%gAH+xIwvEԶ"}jw6jzk x3fvuS(3De'q|(Ҟ=kYm^O8vg%KirSHVf-"o* =%7#@nUw/v8ƭa S(|x6?rg,8{w>554%s$%O}JQ3[!ȏw5f}bKBREo\7\vw N%x$0V?n?n?0A?n@?01?rB{Dy2w&;R nwǴ?r<+4NlX,i)N#x*QZ{7Ln"`!T^͐{KQ ^+SO?nŘAK/i%B(z9*Rq!p 0v'r,LZcr2s`G.'bhOCơWSFOp5r24cY-V@b 1M_p pyñ]sb($Ç=b4R,qJ㿭c52GDd1=$.'ޞr/F'.c*A??b?0:s9^1ko?r8Wa˨aLsn7  U??h bM$n{23|:~B$چ<%8 hǸ?noA1Z#̸(B?n b 1e7r ]lD0(_"3941TOd-׎$A%ƍ`ll[X*?0l)?0ZPwɱq̵Jr3Ƚgcљ~Ef3<]p4p}_e1c9}|rxqK?rK@E(p;>x%ԄF_U\F~ #ˋ@7(0]SÎY=xtԎ?n@MfG W,?0OlNS ?0$G?rwUHMVa{ 2";[~jSL??n:UP_݉{ªZ򢃷N JY}O`з8DK'a(w$_!֏?n^Av:S W?nSE}Kc0Ж>>'*`$Fo6 ^ % &c]+Fwy*'n=RQ?01K0kBibxm}Tp~}xyꖚN1R)M925|&c̍{PoNgF= ȍܒ~nGrv3>Ew WU?0W$F2$2L-4֑ց,lwr[?nW?0Gc7es((ٓ{ x f嵀'/sF]Oɝ5G@|r4RysO}"yAN`U=x+dԔ;'.JĪL'Z/?0:iˤV Iz76ܪ&ݴe??1Y%NT*˶mW%iKqmjVV"D;`ƣ~I~Ag'da\#8^!\KC3Hl`?r[¨)* (8o9*~a?ngvlC^+T!y09RZJ7P̀`tmD!wI @Ѿ.넖e(Ul׆m%6M);DcЛ %_!ߺv}eֺ969JMByޏTߍi~|͸=})߷ll[++(FҦ1sNbXðSЕ']B7N"DQ?0`=VAeRO PR*E޼qR/777.GY{r+7.hxE/bǩr嘆q.bѸ}R?r)z}vZS4e0P?rH?0$ݒ8GڄhGDxȂ2͗`f8QJW'_IVhE$SkXR[(a`W[:F#Viz]޲IGLFW='z -%K?0J<{8;U--Ȋ,,/3^i ˫]Sw91p\4ё1{u̒?n[D)c_t!/B^%y*JnCa op*KlK<{??=0^8ڿx捨ʴGDDKtVଖC~ju2bϹݏנS Ұ7B;a,21#L'Ʀ?0U~HA؊,S`w-\ jeSw3G?nh}CFEnʖVt13dDFEFVnH^ fFx1L"}Ga5bG2'{V.Ewj-JJ?r.4aR `?rf )Ҧ,a }|1͓¹" X*VxQ[?n*۲lfXkEz^{bCiN(z,1'??UY 0xk,&x|O@v w(ekg|5e[Өv΅>Zc1{UbZW3/ԘWL/gW}??'V?r`V!$MJ{wi== VF6@'p`pL ^m} `M=ϤyfJ??ڥhǑǓa F0=$I/#@ .%U%#k,VR<-ai?ns`d#>i-D_wԟYLyɹ+J!nI|5,nd\M$[PQu(, Щ2xJAzCHC<5T,5,f tT%)?0.,"ۢT{*eO:sTybOy'F x5Mr΂qTƛ?n,J?nyΊz +#9)Ň hɑ-?r+F;8#>*al%ïRl)??F{bY >9ob>LUةeՅAx| xHP3SNP[j]_K {??UOPEp޵N,ȯH?ruUTf5 9O$0jQ!4:xe1?rJ?0C4c` F=pVq>ch,d??+6Ob7L7)C#{ .Ժb{FG`#J/H!U]hO68ּXk$6F!`Һ\}l"yGHk@:4Y־{SKuU {ʕ T͊J_2 ;}`l*&fɣ2Pk ?np/$EBKcېS ׆Z\^J}6I|J!M?0';Ζ2հ>,7g 1:S-$*G=oa^ij+3#1L~4ro{w>-⧯#ky$&2 N&nWn@4^Ov=|-}!GX8߄Yn wa@j2 Da7L|!8ohĭYri ''Q9х8'@\70?nE^Wdj=Lxj4.lSW$i "qM+|EcZOiu+/=;K4CWCqG\^7M[IƷS ꑊ Of?n| Wu b̸yMz}{LXVP-*`w. k??weYhvc?nnSMȲ ~8rЂLp` 9$Ic|?0p?r8>1þHk;xZ-A,o}+^Mz}co?nq4Ͼ8A`Zi/Uk3)j&O4i>$6 8Ӳ8)?n&S5l՘=eJ)w%ܾ{-%U Cʚ1w +oWN*JmG[o/x眚Ucl5^I "$ekxR3SȭF7Y{}[1ΩօCGhBny1G??D3#UgO;A)hPO($g$@X8OJF)P8eBh,m#x1>ϼEI.oXGרE_ֲ|⃘q2>??3{y5oVxQPS~;]pf\CS "k@;>#H졡8j:a!|W롾N8SI!j܃DZMVbma,qOyZfcD5[rlbI?r^ ~f$0u盶ߘ3$׀> q-]ay%\S'Ja׺fPE K-F4ڽbA65hSヺOdPVp߁l#29@v'dIF-Z,(>{3UxcT2B y_ xgsLPo3;:bMq4>ߌYaE]"xv{ށF¾CS{{n;=4`W<>SsG"A C@">Nvl%:?r7l+sS%~z6ΖR/>a"@8 ::F+QQf+Jm?00at KZnO1~NROL%Op,?nк V!g!??k^#+;॓ ?0sY!'Ŕ*)XpH worL3!E]>X[c|RL\%.2hZh`u|[stHy0.eih7Y;[j, e n!Km:bkcI:ιdW*y~+7 -G[aW{[}` TD?nV_v.;;vPq-H'ņT[`½PXsö-Su A+!>[6ɜgf,M~>@ya?nxlQ*]ӂK/ojf}{9?0W?rlYa+Hk?r6\G.!9U^DT?nhBEjQ]%g4+m Xנ+w7ԔW7\?0,kV 1-5NL pZ.ѫ隣uYg%<6N̎f9;CieÛ|S `/StQJiͱ) 8PYFz2~Y .o#0S} yDh7D p"I#_4c13vPG['yr;vF [uot2Vxs/H???r(ς>cb|F:ʥ~eFb4wu=?0dECͭ,r#zTo_ >o^_óX;+aZ8WAx>zv>DZWᏠH\jLC[iL5?nKCڈg%5C[!C!O;i0 /[iؽ[>+Q??([ *vMmZM9|ᖵ5t%Eui^ԪhY+2yŻr0c<b}?r*r.}rDS%^Le?rI/^2X-O`M^;<:x=pT9Egg8p[tc4ȓ3[ҕJ=ҩ>VrYޒfmn7)??"18-@0;D$01kM]n6r ?r4)&r 9I8m87+O`DiWG]NWbUd?rW?r2^?r?rޖO0CW?r\nc?rZLK3wbJ%cXE?0;GgZXq%.ΟެMs@iٯ?r.8g>!m_v_z͐wp&~r r.uHc?rPjc??P?r7,qݽGs :i[Q9jUp?0DtǙ e~)4?0Z"(}/!4Q.FM3+kYMNBGZHy.UX\e͑*_r#SO>a9O%=Z5iJֱ~~R7^tX2AWտ*F)MMsjgmHl3z8B\n=τБM?rIV}!Qڏ#Kmtc,xhli +#[}iǘctvr;=5­*|vGsO/fθ&|M=?0>v/gPH#œJPB?n?080?0}3?n4sՄ9!` )g6O]VW4Wi㱑O~?rIնx|v ޮ#9%5XKOi4S3ɃҽMNOw d#,K^_@"cN: Bg]L"1:#]8Ď&&\9.[RD.vl!bPl&PwVp?0H&+peI0R.0rÜe`,Y4"!$Laկ8u\>,oe*jQ`Dbv Z҇Yf?0[YACq'|p֨L3g3‘5ZIDO(;?0И`/ѽ ՎnVc.*<+b?07;u݊ |сjp6`~4 cKi+ve|Ϙw?rRzqR\/6E4/?nL腄 ^(/c13wx̞;c|yTd#*M$BVѢإo[&oK.?r5?0zw@\F^&?0 iv&v2Ta/wC++}LB[:?rW0'쁰xvp-}tfΪ~nkʹV-׳ܘYL AW2/5O&s:sA㺚۠*K-8^pF5?reUL|!og؋smg\PQ-vu5ah~ק>H|QZNe<,jV@X6O5hVˎGR, m4PO(j_q%* A0Wg,pͭۑ➶Wh̟6=DhiʹX$xI?r{ܓpM{s-1ϫ6^),y}Ԏf>Emn0ྥx2Ջ$2"|B1%4#YN! E87H b 95"w|vTWv\{& qǫ?n)ݿּ[==tKȫ 3Zw#6I3~`=nX| Toኧ?rQ@ftPc-Uh8W2,R\yڨOYXz0NE!<'TNq=GYSN2rnjL5ݜu}M VTɒAy0pU*>iC`,LMD&Cп48àL#Ngx쳩z5~~ ?n 7C яc_É/s>VJ5O+ޅA&z?nBL½1ȶa'ΗY_ n_Yfѻ'񖮰iЉN{???rq?0otyi9 '8Ve%y%j@ҹ( <2D #bW /yIaAxc&`n'?0q;,g2Sq/ɖ_XęWw6woP'> AWĠ}dk>oT*Lr#ui.};M֞pnc죲_?rTGpc CQ,%=*p|!K`MR2hds4f[?n9ث+ӷEsL(Qo]qVB݈A!~eA}g>D}Ժ6͉գtm^] :`7p!>uJae9I2=LRmDӾNR NqwV.F\U)PiqzܑHk Y]uǟ?0q)<hxu*%yekҠmBW "H??LʋO8v@PA(>c› ~€3c]%J6n=P=wMi3/;"j0d,w.K??(FUyYIqx73Ԫ?r[ڰzxfH:]XSR$AKꇦ`dΪ:PykR-eWNjS_29R m LS-P40l'c{i$Jqm.э?r_ 凎"dcO/66)Cs 8SO'8g[R\N?nl Ll|+ :PVK .[fsEt^M$m&'[QTUx!yokPʾ/w?nh!,>ltqvKLŧbTGvc??3il-l8bI@kD~i";-r?ru􉕆[Nne曏7??R;̙1+}U[st\&Ct}ؘe0++}İBQQV5-" xCm6bᆠ|֓$pVYڃz,?0pIS6`2M`r]%D8X~2nt_ uGe<9x!SPBu3W=Elc8F6^_]){ҝ8g窰o+yˠ@iDV N"Zh!@/L}ڼ ɡTA#S8ꊬ%Z&Cײ4#jնodF- Єut똥;/n6:\0Y&WLz*HA4TA٪A2}h ,4 I-mp('&)bqw1Toݢ??8 >DJÝx?nZ LN\?ny|@5|?nvibU|3nl&Or早g$$ֈ әwzBtU??늖?nWޥ+FFO㎊U*nWKc`p0ހnϋ{,,P*v3LgWH=sJ7px7FO<5;qƟEW?n/*D/"n @|ۙ;u?rh*YmKglمUF1V}{[eĕ#??5}c^P&(kRSD^Y=/Pv07o֚)Ff֙?? j*zϼӧ#3?r:G鹢v8ӷ+bdfS &mRT\IqЩ)pj&b潥JyC\`l?n |WsĪC c +#4}G@ 4r7*U fu??gj.؄ 7kXwn>Bn1>viugMgdI+&ɦt TQ{Pmi4ciߑs'`U@cY?nj_/fOnPY HZ4n@033HtN";ǏPhZ}.ᤶPXىoLm㐔dEHM?rg}o4k\M,W$14?rzǼ ѩc}knE2N f44#ꗻº R\.rՅiQ‰p[cui, ,)"H4?nЖ0l2v?09 ^>c)(MitEo 6&եxuؓ/f:qZrҐov5atEA= r\go{̑]Y?rc Rϭqe-@Tw.mG-q`wx}E34b5.ցZKuk:5P.z 5t/znVԨ[Lz/-gAVO8kO?rKh(+NfBnKY 0$<7m4l_$!@?0<73 Cq?rX@Iv6AnP%2׈W&fa?rJo']" 9H%S!HJZARVN6uA;ZR6#6Odֲ Xj!N Fqt~܏$`V}gEGe=-+# -0H2ጛj6È s96Kv"1V[]_= 8͛roRA=0I"^¤b?rN뻓??/aҡ*R5gB|G'C&iפV%p0wEhp4`WϊB&i_M!" g9 5W5#ڇ0G &^ȁ3놛*~w\;tz??SEuQ?n#`"1(BL!fb=ʧq/)"(ڏ|t4gژq'=+{!\h6b=?n'*:EӒ x?rsQMF<`]M.x?0-b_k{??=+1 1 25+$ 5u~b_ CGqEE,|_g)(??\S0ϑ!O߿L]HO!}tbNYt@v"0X2YshPt*!_IqQM%\#9\Y 1y*Op=C}j.ֺDH #H s!5*DO)(G*ܲ(6@&ƠH~A(?nn"??ÆU{'@+U ru񌀶H'?nz]_8uR.b(da?r :rE3`N1tF3mBbK1Y~!; YJ=rG%]n`čxz%޳,,7^E}< IN1_6VLJSxq bE8Za{} M :6 2?n Ea/UJF؇3sn&*;+-cq{dcK6q.ń>y3 ΝUҟ!e]!CI5֘@bܘWظorM̑$ kOM>[~y:P?r"??86x8V[>?0 k??`ib8'?nPkt=e5?nOC>ɳaЅoԣ Y#F | h}uhTttzJM?0D86$hjԬI\!f$Ja4̍X?n%M4_Ƅ;yTK=isCzZFq$)~>cG&8& ؙ*c%*NbucɄ^vTqҬ@q??EP6 VΘ3il<+)O} ȥƬFֿ`N#:x }^ś]Aw`*|cuA,h.4E ^IOw 0>웡{F CM)z/37Λ9;h`aە??m~{ ,4IAab_W|q-_z^X.kJߚ7?0덲y"nMK-`KT㟾$#*/a$x=30Q[ι :nJ| B͕0ö]ɖp`ZzUc yz3UrR̳m\m'fI~-hA&A2?0e ?rKh:.TH|lF||/??8~7 K_2%n ?rNʴ qͳjX8ې7{F%H Kb?n.8v)ﭜF)P+䨳Qe'o8v ~Do|9QZ3ciJ>hޫYo*b 7j?rnݨ%=mл#^jdN#mlʬpW QbFi @+?n?n,.wk,??w9_YV}tƋT(T@[DҪiY:98 t?nsr߇3iA^Ro\jo-ƴ󍩠~b5ox[E+̰m.)J [ay>g@&byxw2ƒls`"-wd7%;"Q頽TS5??YaAnnx׍c'z,`My}r-!ֆt} wiQwY+HJ2gFJU*vgBc^b~d%rY/kW8e pq񝷔e]>}ru :opN_C BY6mHP8v}YInQ?0|݊:4 _5}| IڑD *h. (ڷӺTn!(쪩,I|PQ;gfwHۉfCܦj^ߊz;"ywoar շqb9w]j9C= 3pQ`[{pV^ YXL˱L734Y|IBވ=4ØX19/V2dr.OMhc;mV(XdfuYa^+!-7.<>l?n}U|'d8ha-KRWxR+0 BE)Ghh¨})b(=RLw}A26e+Y2k&;',V_J |2g:R9 + l)abizd렋'*?r/yOQ5E\Xcڬ(aE/hܥS#PZ BF֘Zk:ؔi-\q! ,g4onz)t*m$$w&&c)*(}:9VTGiM X݈1䝂j]rݞEpܕfuc??z 8OWy??H?0y'vZ+_}z^#8g9J?n ӍFs$G<vغyEc@2D:dZ{ܨa.eACA#vC10 4qdU53 5eޣKm>bk0nӝCYwjJ$DHecSt)?r#^XԨf$-gXmIݶxB= 첱FeS=:fJ?nɐ{t&CZ|=>_p}Z(:Kp[?ruR:,CF&z)Ś۵¼0/Qq{r?r ^H??2E/'P00PDv3J{+ ΋^͆uԣKW*Ob=#'靮}Jidk:I G=2o (&8>XIr7׻ϱry"W[[=_!pĚwvfv>9+y& ^T+YVyԏm\0sn B]85ߛz襑~;??{ӉYkrwutKЎRXqSDzd $Au>TղrͣoATXP *@3v/}}/z)-P}bS8Lbfvtr펷$ЮiN]Q}$(oJj5pq2`(WSl.Q:(va:~HJ)V.Dԃ6)/??n87;nK~$(zƇLp~[AvAP#oM f?n`c?nlsM޼cYWltdCq\9iX_1dFdkE2ƾ1$QeoZ_ǵ~QiafJrZ݆uonöTdd *P Zcs?rrrIc`^ck\?0=FLn zFyDI??rj{&?0c9Ul4XSqzsèqA`xp;I˝$GJq.")F nGu0" kR/@@ŶXe"x`$vJow0BnMz??vuVLUVB}??pg?0 FFѕעP?0MF0!W,x{i^Ie&͌|γ7Y+a$o*ʭؽ3ܥ@IriPjbmX4BY03vMDnC9ü-3׬u##tSKM&AHd/tp!0h.krYFNr ????*j d$[]?rnX7F/^VӁȏ)<Qi}%ަV! q O. B氏6%%#rtD:j40S8GJAI|KAP5ϓ-*JRHRӘȁ+w#ݖ}j}gMy IBH+&?rGz3Pܝ5㧎O<]5\9}Em2??\۔]=au>uimIjQf*#yG'6+(~f.]4>^TеG?0F??USag 9A+I'f¤GX5-m8q@_bU8g--@zW;Lnf?nT??WAe$K4:v9BJ<%łnt%F5Q"|tO^n^'uB&0kiX:FI|4,>adm2#e< ڞ\bc)e$DەEH :Sߤ8$VwB#t3_za+(gdUML:XAfţߠK㯂W֙ne6Km"JIDh bz>w0S[5Hg`X6!~QR*Y?0uyeV3״&-Gql?n_wB±\#`19ۡyVdJ3TQL"z?r^-SXMp+<ީ?n˶\xz??q`. /jVoOqU/?0pzԈMlq"Y (d~GI!JB+?npqj+Oe!b+Vthj Y"b5GQ%d+n DžT9H,,wRK@_hR%Mժ\CV h!CEKPFMB۹و@,n{¹':Ȇb(w??[:H=yN:/*[(A*ʺpXiڧWm> |ŝ-W-DaˮsТ1E){I㹦x=?0LkjtK?0%Բ(X$A+[X0U35 !w"6obv"y h wӘ:SS_\Y>8A^_1i.B5וJUnFߺ3n.ãVP}=OM4&г*??)eѕШLoWýGҴɣ"jmGwwѱPl@'qFY|hs4ԭsDōK_K*$4,4'j]YkFةN>25(Y; .PbhT͑|5/`  X3l<??h|Yb6H.]Ph8!?0p,[{; ?r-?nAe+Nǀ!W=7wR#U@R5140?nga??S1y'h?02}D |u%owAg#Bz)hvJau|1Ss,SDi\.!?0PXf(r~!t bBHHxIâX!BhsY6mضKmC,"Y`sJba& n=`^ ?0,'3|?0p{QwuJ0hʣsl&a?09(rxک?0Cٝȹx`=tu????B+m7Q`xxۨ7\BY'umzڂx[fCZ "TM/+Q9U~*w{??\*d'?rOsΗD> )<)O t e0.ԬMZTG=xlt~FV(??Qs[2=C^qLp|7VՓuuÛ)8[!ixKՑ;};B:?r3; |Wp+[/D?rdTMв#t rFWǼ8 Ҭ?0k?0͍n&.E (I5,I)\yzaօy;G"l/ُJ!5dl4{eGYY%`R ͺОk I먤6 LTt⫂ph+L=1R@:3f3?00^Onc?06Tyw"KV]_Gbޓ!gAUP Dϝǚ ޾P7yE݋ӞheQaʯoP׬/RNH\k$~{w&#ݿ{Ll~8$͹lbx?r/p}ti Q)??yZz`sUi2fN"ܓ0ʡԧ?rx+35H%TVu$sϙzT e&>#W-mS=rX-HSzOt*}r'ޤZg_\?r{ە??0l??Յ+$dM'_@,Bz7ֆC5b |DECyKne=?raPNhFT^#މn}zT-?rgb)c??{T_8WQq})E@S9|<[\z m=J!/b?r&˂Ze>|\k{~zEz@؍~+mwWGuYGE7p&?0h}tmfN?rBeDDyV%%6pǂ=qsi{<+pS#=@VI`/k Ãƭoao przX-?0"}՜&RdBcrj&Pz^;c~#\o|nȡo M-@ύAB,^1pQf,ɆvFB0M1׸JA9hYbw`$K2v(uS"%ώdsKK8ClR+i] &~(r514wz/kzj~?07m5BܓqEdCCm4vp +#??.[vcIIOW6i. iki'&8x bn3+գWQ($nKn?0thp9/%b8C LI͚>ߡǛY(CmIU8e4لdL21e7`]"6Qt ԜAxL9y3b*R}P Y˚+]O,(..ąk${XvZ[]<@yJp2 u^Yтo_E>N+k>m-~?n^Tk锢R dTe??9wJ:b4 !2MZlN|vY7Nv?r:,!5H|NOk??|~OzRCNoŭӀvM틵O67)h2"6汙pX4?rz֞n=feCq\'ᨋ7&R)) UҹxQD;yn_מbe}=𬌢1d"9pnIn> }v7]8%&+&Ugwf!g5@.14?n*;hpiQڞBnn6/?0mP{;uf3VRT0jx)mML=3\\yp8ӾTcX{P™$ÌR=M~{k;2이+c??=s:LjJ7\?ryC;‹%|m:SM9Fd{6nIDmYq&eMX:RڞB?0#JOLR="ِM){ROho,jR'z׬ɿ{$)GӮnxNԦ6vAs+??A,2fxSTgvt`Ӫ kD ~I^ .B_I'[}IJ VxaZX> Ee~LN}:FXGA{Q&s'E-/wTsܛ?r*6Q<(LNKGO2Q{}Q\wk7<̆[+Zo/[蛮vQyuɏXC=-v`^[=%~pȎLF87|Cjm_GC^Ŭ`\BSj\șI&.P)ѕ.U硷cxfb\9MrgNM3S=_k@J&2v {BR:y(:d"1z&4zJAwb.I u9?n3sPiW^_X(7ӾYT'0 [J2Y6[ltIi_U|2"YPsu_3PWFM|M>zK׳hg6Y_)^O ҫl`D7JaU_ClEMfGA|6FzRo.Ӄɸ|_};C{8^@ ]l.I]hjDwQqjŴ=~%[9dBJ5µ ꖓG$B`ο=>R[=yn-9d?0L +#U?0q0QJr?0FϋT:[&pz.1vF K?rIn*b hu  bCSGpj=2dlqoh ;Qao2kh(o/dWyU?nG!3#c^/e1C>;bO=J5 dXJWQu>IeElہ~jTYst$Y?0F vE"JInL{ؖ1n,vY??]R??/.=??PArSGn*;Dǧ!YAq6*pHv(i@OUG;T[y:৬J?npjˎVHF+52l'@›1fAP<|yOk$M&aivu??rWGwe8i&MQ~9)i3#y񛹒K7?nVv?nB,Ke?nUwfiF_-R< r%yi:q?0Pke ?rg<*u1Ht wRq³1֨~6"ȴq/GI]5KC~9ZB-5Xsw变t]^x*X4W-WwO`M?n8aO`veXyA`QqkfʣPh \D_'=(zJt?nZJ Mw/|yO #ee#~> g^l~}`vC]??K{J.P]g,s'j/[%~,͊M+jʿl`('>ڞ>=-gCsUdUJNkᏫob4zkrrJhdt4t")}má:3( K ЃnaBUkw$}T'+Ͳ<YTPol#~Kx??\^A]Dٜm83dZxZ`d3@H?n6`7{i ?reŵSN1J/֗"U0h+#,^S]d1*?nS?na+Zr"iBOHҴz"jx0ʯWd_}$͏PJC)8Jsͬ*#Z]?rMViʥܫTSlLOŃ<M?nP)/E-,qnhMиY%mNJj.l+~6 BbVL5f[w5JTR}JVƜd5b;rM?0x~ @Vњj7-Ztyoň lC&y|޹ެ@nteh8&ЄBW)DvLHj#; Y7lAI[?rF 0\ȾN{jIGܕ6xG]yB0q K {- 7(}"Y]7M X/){s{[)b:ʩɓhpWZVh(ܰ|MɱzHU:_X;%gyFyb2ZưTJ\ӊݬ?n8ݧՆ29U[L9ryen'9$/]'!Cw~ >Ry7?r2_8̀Ii,Ea}>q?0{]ΐ,!|PE;0Ω-;`&L2Q?r`-y:?n=ZϨɱ7J,(BXٝ?0hgFhD={\ 51N?nBFX49-QJVz;/$d='Zse쫭RNJ\gHM5.z8Q5@daJTn[2r @4@FPy.Ρo`x,!2.rHtff0A[ ?n7!^^eHOҦfuAIn_N{o/#(J<"gӌ/ +#`CKo;nuQ2dv#*r4fu ZZioڈl% e!D]nض(b(Nq?n媑 pq@9FgY &vvjtJ~҂Ua ri˸Ub"*p+<osy 8-7Br?n_ĉ.!Y5g4y>Fq\%EIIԬ ;s>pi":o&oy y#R}'.Ѯa׷?r5lˬk/kyWqt տU6mge5)`7gmc_ޫgq2rP6PQG ٰ*Qtmvu\Lqx#O] ͝O&-b&՘˪3*DYQF7\3à N]%BRe [t#  ɲv5FP>g{V jQK7"f]kR߮?00L l~]&~E8~DnuNq[HZnE%fqd{NO0w&ˑrӐ,K'߸z??I^9ձ?n=D Iɤ9@lP+e4MD0o(YC)?rǮfGK<j $q?0qM>3;dU<;MO>fތ ` u{"w<@|ZB W{˫^9Qlb6A6#???0KYدY8ƀ4YW;{7O{??$JŏΩPzdG)-&|Xoo}@6??m<0FnA8J\w52-Q7{i1})-&fױp%)(dn) 6P㟹79nąVTK~Vʰ^(q`&XGJ^ܹpA|I{ͻ"|b a_7Z(}W]͊GEߦЖNn[Ԏ??-$>$%vmOcD8Fg8|}1.?r&w/iVxk8x0?03js1+O?0M([J+`y-ҚGjqo:?nLsTp p?rϷ݌p,HeDF9 5C@ ;a3u1G]t@;g?n:}M+H$O㳾.hKy4{D!0ԡ_A?0_Pe`af߯{?0Wմa9jjNYcH{aw1]*)1"c?0L?06ϵP!$wIvb#hQ2(:ld?rYdZ$HFzƾ\f o7xZQ7^]+ccc Wle؇??h/?rcS?n⽬;O~UkkkA%U8,B?0KJixek b/3aw^l7W2F??\ xÉ!`#9XȔ*=8Jh4W&A|  ʤ؜J zzzzk4 GRu0hѵTOP1Q%?r:qҔ69WFZf_VnV~Vx]c.},gh:/ Vs^8%1x3I%_G# Hr0'Xg%6,PhELQ>?07JTRQ?r\eAf(.˺+b_GqV)8N?n=l3:pYOpaU1 NvW"H5UODcM_NB=wQBn{ϮXteԥft2:v2:tʠU֥(x8a,`fQ| &K]|a:ܳ9 )Vck?rw0IF.n#n~!@Q򀳵|zrj/y_I Oko=i2LM=G^~徺6~U_~.?0?rTAV4mD]+"`IÖdR??'c6edDgŠ.EҚ. [jbbؽf_z7W!ےk*|ESG%<.#W+.^7{A3M Oa%0B7QQ^t~:1~i,S-ߤL;A?0X UNA.egeij/R4%"Npte뛕cawƒgcoEz>'Y9L¹v#છ?r/wi6W]f#\=E!4i1o#&O.aĄ|(*⫒ɞn19 ?0NI;k?n0B,oSv*m8eI\?rxW\T:d7낂8X.S<Rr$vZ֊{|ł$f|@҈gTvh`J}w-nߺu΅=M3Ek39q^E_to >K$5oO Ur[k_06!*jT_iQ()8 ioяٺ!ޏ~Ȃ V7N[?nۙ/*0wCnysK:{4> `Wi떼=C&|?0µ|ԾD4 '‡afq^h-ƄܩJn??cKOFnԪP+F[5)U@MQvZwJb}?r(t%PӢ3ڲOPMթ7T-_?0edǺđhavhyQSYMI#5YFxĺz@b^?0 ̺ i_k ١!)z jM6?n19' &A՝ܨ1N7ջӠ@z:#a:Hx8[g杶1tCHNZJ}T "!ov/6(z0$H5jn??$ގ??ژ`PGUw5L7*Hzp0]!{|_VNs#[h*18$_w_M05h[4W6ˊy8*R???rBYm%©lʀ5xyge/J&q:*ސ<(F:C=e|!vY?r*w\=X.CZGo,!4Z>1_7Ç{=RgFeY±uǮ{iH<楚%?0 "屗F{,ʔ88?rVdK@¸q7dt=_{6![mY!m'2A>j#cf髊C0.P6C -ujxp;/cRњM b9b2Xv %G#=uS٬0"첢b2YwL(?rn~hߟW??/wHz_@":3Wo*?n9gbzc~`U \=NЊPrgzTiQAѴ0L`_xp{z"v fޚfO %g=Lԓ'z=1yjD[Q*"@D4b0lW!{?r" 18>?nb)mLHA&#O;oB9$xJшCyp:8r.Iu’q  ?nx=cRLf5t߈LS=ğSZۣ]6k3m- %spK??tm^ ڶeIb|6Ѐ#\ gQys6]q<`z[[oh|@`KUpOJ84?0饁HwRDц?n߬} ]^Qmn-F)Kl'&Ǧ|ں*$ݦR?n?r G UjOR' 2+tK(b5IۓuJ ̛Ww:^c@UCwѨOc+(NT92ȷmG[rAG70AtAI_YdϿdl$k wrW46iyj[3(s =[-qTTD=UْF^dV=s+# C|1(WF8s2;Ռ?0P*^ҵqAp!?0=&4lzW݇S?rM޽K-I,$b?rh/W&ȩVUTծ"Q*oՑo5H:k\9Pk'Qp-JNcH$ȭJvo"'cN&Լt46f>M|Yu>꜃>*r9~}??Ue(=JȜO{b2>N-O1"E3)D[v 8z?0JSF\ża".m5D8d0}Hlkȫǩ]u ?0ţhL*ݒ)C߂ z3')ARiXӢ"s _6A5y` Yˢ2+`?rM]4ʱj/hFc|[paPSSB܁Pq,{0:#.y@)h|-"9пPV΃'bɅ|4怸Ld[5Bg|uA yh\Ԋ?ne5QgANOcbn9w#dPMFᗐkb-<˷~`TQ7;me*ND|y,|dRG0@Fw6v8SKsYblM%S-G]QY_IU"WrD S1!AP?0~p1s +#4C(&;r\%Q6cN d@6bAXe-Z,PuبG1*eR|i¨ ; 7luRyu?? nX9ɈZw6/y 4<ͭҧ'Tt:yePXP6n3ԗJ[6G;ه?r8,n??|&y}P#f~zظigk&N?nߴQ{ˁB6*@x֓,}R??Ԇ;,GbT@v_J5J m?0?0UUJ`SLeQd:R`yR/\5xD)kRx:ʟWq}4G^f<˦I?nǚ4pd">J!zmgޯ6mjn)yHӡx^ w¦ޖl]?rt1L\J{ȯpѳ/:čQnyJX'?0G 6/@ IRS])LL[B7Wyh͢׺xBu6{2WD,bQP UhUCN%'iHX1&܌eӏF>LTeLNvѐer&#LɖϤ jQ.~//ɃYp3Nj<%?n1u??1z)L&W7Y$ H"倹!~"w3=^?r\8dv6ּXv~龪Fɒ5Mt|t>z2foOuY<ޘŀ ??^]Oˑ=)OIeұ9xiejv C=Q[RҘlOG1??_bt9c׾Eb{ʊ??2Zqno^ełѾm>D_v_egtBtNz~!>wݔt+XGdt+ =jޡ??BbnVɜ+?nmӬ>1&6ťt>3I"\dwz?08l}Ϋ{&:^>ytؘP&k^zz&"#s'/'C𴍓_m+y@/|51W[߃{N<|@X5!hOK=-vkۄq>~mcs A?nFFm~A#kW)Tt%H7^kuCfUZ%~'[2ݓ~MLl5eJ#3N"z^~ze[n8qd>?nMϡ9K?nѻx(SȦ_h Y~Z^Q~oc~,H,ʉǕs<6ɏ Jjhyl'j]O99B`݇|JC^,v[R w]1(jnWM41+T L?n|2t$I']N_@5z}"o?n?r}nW:IE,EP=] Ax!i㒁&#?0]kHqA>>b>x=VPy7tڂa퍋_ng㑙 ˒1rUr5 '`?n͸/?nZ[\Z4s;%MU4*ʁc -o['b':PpQ*BoE_>k*?nٮD `eeηYbԨD"vrOm@%5 2h1n;^zyG(pUNRdU,[*[*X>妄vw1nL0'L0b(|_NY_%e`^ԉЁ"М.-7ޫYf>iw;O_3LA.N_DJJh??WSоϽtrr ZzLRJW{ŐNؒ6gp9J 2=|??! [b/&vf_12?0002101??NY[_4_*f@wZ NRrOlmipO izKiypJQ[ br#~m{bTy!lQ'Ȉ1ZD* n/LߐZjo3y?r>[ vѵjzb=;U?rʀ 5hgy@KGMJI?0ׂKp(!wM'Ǥ^%ćU?0L" -D5i8ebW2與!tޢGybk\"*E7N>DaR;??Oy]?r]e#dz?n)58f 'c tp+-+P񉈃QxeWɲp'a,$K®F*j??[/6i+Il 23|f09"\MB@7N{o?r??(lhw&1y7o%)Q9z?0ڌ͇ aIHRwh(յLd.}<5q=iu=Pqbl?rmjH8`N"çyykBk֢r_\<(OC8G cRJ , MFۙSvjOtDd~*l*6(tohzz/;z`<n\\ f[T d?r¥D7UUK"¤\8q40L"?nF$WCĥai1hb¸+]s״#/%tM*ѫnC>WSϡI®cKS?nAO??[,"?ntOCꨆAN'L0- =?0I1`KW6BJt6$V!oE=*to7^ۃu.?n4m&ɝTa酞fr~˓!sȷԟߏəQdR 6Mxn8A573ౡ?nr8UP^fWطL*vDzۗ)ON*W`yC5v\k"RXGdIVpQpxO??=7~O/En^ΐwvZoz43r|YYƹ7,;V\]ݎМM8uJkؗ/l >FQ4cYv&Ғ˕Yϲ$!:祉'˞K?0h u4PN7:/ǤA[ʇeh鰰Qs[-g_p0ʓyf(MG#?0$^~~)q%?0u9!Q0?0Ƃ?r'Ő?r%$<@7qx^?r@njVu}g(}kUovTn+F?nK-YO?rо+yjStmedC*(\l?rz "UB5?n''n^EkQ؀ĆL??Vm;Gjy9GQ#E9?0$٣kPeB[ky2MIe%ݝ8O??`ʂkp#?0T?r~?npX8V#.7]d!0a`8(8Gd&[SUȷ2u#Bs˂è]6L0<T?n-wFtaKz CSᘣ6 #4f*"3^= ' rx{?r'@GT3~LyEJ?np> Nf??g(52N{K \(i?0; +|ӱcC|ĉ\zL9ʇgjbW2V???rJB?0XC2r1$><\=]>INwբrEB˔\b[|ct?rklRD83nyh2X?nzHb 5+VymW`9k`ſg_ɘ$Tet˖H?0 +v;x/1}iϳ̗`Ӿ%k^% %֘0 :J\w4HI~|yE=*oZ|=7anoH¸*&EJ~{Ypi[Țh7s~a}1`l.ӟf~ŝ@ɅhWhK؀xVe~]%3U?r5?n;}.tik B x˾?0#'?r|Hɚ[߀sz1n("i,5貆?r.+1j 9We8Iu0Bo&ێڡ8:Y ?rfnwO#4Z98Y(K2i?0 2`f+twll +?0޽G䜁^y+ӓd2&}0{?0w}'EOh?r~ $ֿ3Εage{?0v>/SubChKt??_Vtl.j=unK|+Vyy͹馡9l8#,"̞*i("ǞC/C^EfFXw:9k>-] `m_*ZP̤"AnUS;@"PwTeOlؼ4>$>E2v1ih!TB7LJS:Z''a0PaԤ%ܘ |#eWP |LW@d/M!)?0O臀+uɷ8,<؇T:^j[R3 +uQs=m?n;j7}Xе??4O;$;,UU7s3刕T_瑰rChl҈RH?rn$N_gNr:aLtCIsSk@$,鸂&s>œ_-tZZ眊&싅_rv̓ƙ׳a:6#|Mx$GKf3VT@ۢQ@YTd\Z Ne5i=af*pu!Ԩ0p(t;4M/BEi?rq{f^M \I+61ߗ>cP-*cyNfkȜyT9_O,M}FC:^)UQݲ-[ն&F8Y\R¬M+Imuu:7l{'gЛVdշ&Y6T_0&L-(Z`mU*ryvg kes%Pvٹhu:??,=':R;;NOtW3{*~v6>kתѧ{ܣ~{d ЄN\ٴB^ sg V__zS2ZyO֔=+Ԧ]խ?r:_Y:;V$Vz69n9OͯIn.ou՞??F y3f|+??tq#2qӭHak5Yz1)փt'``Nw!7?rdFg幜+M5˒I'T́Kr ]`P3beuF ?rBGdƧ^)"li幄?r??I5?n0V-t$Noض+0cȀX"^-]ђ$9بi0 3G4]d#_ocXԻ?rn*Ih8nBÛPl~j=>Pwf}2sWc 5?0A F|`?0)PG9" Buf%[v ,}?0\~lpѦ7܆{;J> -C+{("BHj<mlU{H4Xif^y59?r<2q9n*gJ&/laK阸*v2HK6rI+eVTYLcHQ^yphq^'m??v8U xb&V^A+Ґi Td7U4kf1?ri5 k+Z(.JoRρ#Wqgx~R\?n-&?r*hՏ#?nY}U `ϚUW=nkd{c-PRFYw;ⓓxDI&Y7|9=1qm=7.i2d6:F00Ic<7:/ tc>?0To`E+`8A=h)t&QaU OC~0+OpxraG <gPxE+#]Z?rm~?nB:pF̀`e%_8xz Pg'"D:0&AQ1yҨs@5鶮}&SfuNEKO٤<~G y?0Ny\gD| ry^6Ǭz⫖Xֱ?0hl. fȚ8V;f na +#RDmT)ݮo}ov;Da?r>LI꜔TcZKs!&hb<({\|3qRb]"bғ `DZE!hs s|*T| L4vNxcXxogV͂E+:7`y5X%Xd8 w7ec#??$Nr\&tLof,̣bJ6t&I$1{̗,eI$!h$7|C|V8/?n `ƺODL1g|OHE}؎3݈UfNL??]qi rag@k[-F/^|?0]f7Z@j1˯O-hCiDL흴??]+3&`^5C??W$VPuSF???n \ E?n??}Y]9O:9I kWxCK6zݖ|ku[+A,z=`(o~Y3ad[ѥ..0|{V_:H/6= x Q2y4pwIBxwˁ]gLz$!R\4M/ć9} Mb{_cwr粈X65.!bmO=]S9H1PQ8!`zwGYٶ⸧J%duD/p ESdIp~AҐ$??Kd엀r .͟kTkߤC0;+KFA`;!0!!)^ʟ5.4],{a=V@9!QW7?0?r?0bJ;]1~ S-8_Jx&hxPxya"v3بQt3IlN,KXy(006?0ۈ  f< f|o%#`б3,~id־KnU8B 5zL!9ާTYF62yd:ɝ0`lɍdYzewyq v3r=%ݔX.b|9R32q1"c5q9n$d޲$#H-0ˑxNF?ny!%a`ǁȑ5ʑ0r'#;<$Ƌ,H#k.[`#r;wfdȑb-0˵;#O&o`~|eIF?nYlY~򄑂?r ,ȕ+a12q{9/?r2W8eOFn`.8kKQ8d0q^YN4=)rVlx䔹~ϞH90j`=0ՍNSN0~9Ív2N#K?r+c`5eF6~n$\%d[,c0Rq|ئ?r0;?nu{w???? ??i7ƞ#ͮ|ky <?n52 á6'bЁq3^$bnC\JxA/hhb-T 07E=G?04I;v\[E36J^i|HZdK:?r,k׳SK4HsxY=_hzo^-]ÔW?0asHD9uOit JtL0T|HrV/1y@QI\ܾ֫+aW%7;ǀ;?0だ4tp_PnX7@a?n;Ğ`nf1\$P8O8Ĺg??ylcz;:&Lx"U{?n?rPm귃RӸ|;e?0U^.<\MUs(C\va"X!x8Q;{9+ F@30???06Rm錩9n4}a_?n"lrjpd?0eFݤ%mƁ_;-*GO:У)M?0l\z*ߔҨH@AWdG ``DYpew8pgYm7*Vg,'./tn6psݸ8$?nC,s;c+в?n,߅hȠ eW7t}N\IMiy^{;98D|wې]<+bi(|11m m43,yy3Ziy9gez‰`1 qM?n 8jsQ_5xb!'Ptwzġ$Q8blrv߽ڱ25ピfYү9| |+N\IFF:"% #qDhTwUOX]ۡqEBI7hAv+ ̦i??@A,eBԃ⃝`AM5*f9w(UM,I7c|l[AqGo`hh8һ-i"޽}['ħe?r RAhl]ؿn̔J]*Dh]o;#AUxؒG C@t6=S⛕zQdvkmi!cv}hRXXJT?nDo$$ӏecs:#AP)~8q=WP$ySEs/< EV 䘸PU2\k,G";H/@=tk‡m 8X<9I34!\(k*/%M??&:@?rlv?0K}Sq?0T  Q_z>,, \U0mB ޗun$J*<.??ȏ|/0nN\^nZ̏XM(NҶe;}ۃ64jϺl[Vhe !?n+`T)[Eg񴊢@e(|[OO,P 92, ծqs^}1*+6,nECp,ܛ s?r z,7\ zཌྷ)1U-Z?r;ݶs O_>Sb.|,&?rޏ307HM (3NPJToY*)cu(=JTe??!}^@=90km[?rUx0/#Eq4p԰.ڔ{W_JAw?0eJӋ\ǁ$1R:ߧ?rŋ^]ɳD׻B#eS1Qaޛ5ʴwm^SL9ېĐ8|oD6X󙗶17XQ(d3BYt)PWhA௰[XS7>C?0/`JVRY D&˓"Uuxi#wޘ%cWaml>K} tC^0ep]ŭuOٶukmdVřnK9ӝfYJQ),.mh.+'e3C >ms~~q@8&V h^RiBTfuw??DmXN 캰s(]??P\ǣ>RD?nSA)E\9f?? p+$?r/k?rЧ?rɴ'Ex`[b_(wɕW?nXU(?0f 볥C8a:MNm0LNT mo4{ͮcQW1&L-x ?n;6y: +d`Z}wf_6S7Đjw譬C^?0{!@rh…|n?n]t֢^H?rھ]5Z%P/þrm8*?rhQeLWr(/Nf&Y?r4^Fc x(Sjak.!V;M?nmFWP 8V[clK8_c?rToX,Q֊4xb{Q#f^3NZ'9u?riARCMb#Tfdw &m[zOOE*f>^aby?0jz?0awHlQѹX:4}Ȋs.ؕ<#[w6??x &}eӡwkٜu8?n{^?0k :>lerlnhDɭnb0ٍ4=qP??321/[Nw+@F!2FR|>X8I[LB5ǒ??۰M.D4c-ra&gx/C/DBxtW?0-|e _[3Fn/^kx:jBھ⩩Ķסs PpT??:,Y(kvϡ?0/yE_0|??ڐ<%Pvx?r,)f]'??߲3Nbc0ӭ?n,+eAI?0TpPo(ÿ@qե`+?nW0``l>&Gx_xremC%I"Hf:b}U#_ߢmwGr| FCG$~]QO4??BamNnXy`dK50R$U ??*f[c\7BG˗lu`^tuBߐ_R.Qٔ.Zm?0@~?0}ہ*s#PAC彐 nK}~Z*[zM2uAѣ+Q{~3pbJbŚUA+Wsݦg*<ѢӢ6RMẻ?nf(hGeۥCԽpɺ,wp~J~2٠?0z.f5d֪Z8J`#Y&J.N2_Cԉn6zF.>O1| 7ῑ[!M(߼90P#3v3-+:-%>=:??@VF[ۙ +#3z w,slȤ&͈HL0̤Mlv>*3QHJ}*#>>lDk<6{[7!|4)zn"?nq#3;Ňf,]x*8j[to9@$܇으mW@JAv^֍Ki_mf<^֔ncYH%gF)df{ ߿U-;A&`I^)O${/"}?n΀KMqt .7s{\m@^ߴeuHhHkG^_]t[T?0N֟Β)2~0PzjHeݵ쳕pEV_a6{B<8T$=UqO4ug,4OuQb%w?n6qcE T0ב'YVcžGCݬ,b'hanvt!(o\-q"M%O%) (f=8$ZЊak>Fd8Ľ`dO8E=0joK^S~Y nu~Z!={[V`@Ww/8'?ngT5h_=5tHo7Rf4*Lm?0L2wD% cI`/-+2.өM%z )^"ۉFz!6?0g?0sj^*M`m\Uņ_ ȬyL(1G7OesWU90P7""y^PĈU;^؋J 9rl]kXyyml7gKNmfIE`#ue[Fp_!xn_n R@Uk^̎s0+C +2hf#$xs.{egsUX/,IG/b /R#[,6ڕ=?nP?0+KE`ʂNp㾰+XkkHN]fxp;N3`yG/t8IoS?04~0;NkD?nq`";ښfJvh^Y ݪpՠ^1rJ=?rl+')]5~qA\?nԂ??>7oiRn]V%SN#U_f;{W̋\ݶr_19Td!-8Y 5jxc #`Vb???raJs}??ϳaQ/??ݚË8ƶ5(w*2bR8 @BY=jD$??w-|K@&FD???nX.ZP?r,4(%w ϿҵXfG.S_rv?r?rL'~'ً[g7s؃lw$=8/ڇ^ ˀebWdXT뤅 "^%+da;ڟula.oOI-u>up?rUS5Xpp~GfSwg:`(;"HGrj,rWƖ2Dd+MUz~+TM8xc7F_t/`i&t(luJ90HLs̛~C lSRmh@Q=|+\γDNI=D3$qmDXxk H?r!-`) P俽ǰsA7ߟ޽[H\l$}_ٰ彷5G&r,?0C>yi. K?n``QX#NU1s4#󞴅fD7g>@j\C~CP^)[at"1 w0XMD$mq#m&6zxElt3B?0n?0{Q׮XlmG !^Ck.U ,ߞ6C8RrqɊ8Ѐ??AC@UZ2g+ Q,Ͳ?rl"bN0aaVZ(=lgNٻzhc"68O+.9!.J| ߹:S?ng`cm]g5mqV0j&iCFDW%P>j53N(mYC7b!gVLsʝ75˒ezXM,uPI%O.ACѭ vj|U |^KzTnWn5.`rG܄ؕE߹gjlk}DcbuuA-e-=_>k8>R?0g.ӊ$PJVn(PXAƂ2\ԠIq?r.56kT˳V\@ģ?0COFy&cv* WV쒸vMmN6wRbc"i*ɻ1ڻ OXrȉ״_#=r'+_[mrbJIz0XfnNe31w+a4VV#.Iq6lҳf^k*U_Щ.튆Auy: M K=F\JqB~$ svU[Sh8woصd+Rs=P\`|4óBGIYj/%X3_u6`;muزi`[[_(#8$}6soٌ/d=ڤqzagx??UIP=42r,,+j+d~Eq C[{??;Nڎfz$Z!\5/1`sS\BW@/]8?r~>';c6\O۷b6 Tn͝B{m⫾a?0(ȍ ܴ59D1]/-W-`\>aXH%ψ+"kV?0Vpd剠ݛ72lG3V_P C}kA+Jz[BpW3񓷚GTÀp%ic6u,??T3u(+TJupˇHC+e 8nSndd&,Yբ?n$?0Ѓ=*p=mXծNuvPo,NVӰ-z2󇿏**yd$wپR;8\;!ɭn\Jm;b;ώ%yHRb3/qufwvRz띺A y,SΗ{${wPe}W3!_ne^wĤ@7Uo+|J ݤgX E* p_p7.SSRp֮E1HvL~k'; m_h:H^s7!%??!0ӹ}sLlݫ6 ^Zf׏,FAuE*$5nH#ٙ2q cogi/8s4º\^hJs|h~e ; n;bRf5n/wć.KխiSW @FEͼmfzN^V m*tg 6Έ𳛯 %G6mxg"$GIhoD{[ٝN7sz–sZStM-0.+Κ()6=.3sjZ訆23 &WwcgI?n*u 8vӋx泐8ova,4L5qU`?r3xhsF7YR5db9^HtEj??€\ iGQ栄鸙iV$N ,SӲ_lgB[/\A8˗/E}pvC1mmT[r -v9u޾Xw.jo[-A>%U8J tmMAVڛ[6(/1#7'Ѳ.- > 覥#W'G??4:?n%wc@`'n?rlyۯw^[ $A[3%x rp{n+-FᆧwT~M(Yy6JF^‡-[T%QRh2» +#h(*rALaKhU4oYoh(w{?n6m c|wV.>LwF\σl !?rrM[z'(_I6qXThqƑD%*AJz>+MW )(>8ETTr7L5BI6)?r}h*WR˶j(hb>vspUǕ?n;\nhXj?n??-fǶ|nV?nO(QGt ( 7?rf{J/+ӣgP?0#vPbDTi \كڷwGo<]9Z!EQV@ o-Tpd??KyV3?nAiathԾEUpT,^U䑽ϰc\c bp!A~oI6t3ܮrB`ǘ:^֘"]Ť` kdj;t:B~FCn?nA9}LH:)/K sGLj턈JEhC9L"2!'7-GT5;.??Yg1 ahxFպX+lnVB4Ugߨm6Ѩ\L~^8c;(mcM4n"Z1wc롊dCPӧDz(RAO>u[L¥b9R?0m{Vib`??f0 l2?n#jw(),]m㠰=f+<:jiPl3Z#"P+5JB*VlT--r??`'3rܥÅ_jlPQSWzIKDko'z %e^bqtAU'_s$"_chw7oS63,2@aSȟ,-QG1h(9IF߁lL?n}&yҡMFmT/YUh(.:Ż?rOe %?r3GGn˔qw?0/m|kX#F7QwPǴ_.փ~of~p 'Ý??AlK??Y|w7 ^CA =\$?n{H8 r`ݥC3XAc???n??|8U?rw15Xw?rD)^pbaƾk4vvXh0Ѫ} ǥ,H{fN-Vᲆ}/˫PClm_ÐC&I\I{kȏCQ(2$O4Gd(0~/{Do7K6=[ 6"y&2#?0????#)a>Oᢉ|lJEs$.KJM;h]c<,0(5Bgsj r=k;&n*؃+N+@?0?n0E.Ou2JM?nX߽p?rCŌeGтf1$3n.fH``ҩ3Ƕ|]h\-mY-vpz5IԪۏЩZKO%4Ł??5٣s??os!kf??O"ʥn@YK'kM,yj7hUij"talxlߞIHELvϤMgZ1?reSېMaEuF9e#~0Bhp@+dµHNCMx;$;c#.V >ё:%~NYur'Y@JЗV^׭.5h^ĄY;P2hI@IҍeuO_t,.O1}Kzc Fmj_?r* f,?0DS!1o4^ڈ ??uPstdz,H3#Q X \Ȣ{ ٶ~{A8PFS\ ;X@B[V{vYt:4s>GvlWr?nv{^p])u^y,A+Ltj&N ɱ}jKrREdU mi?0?rȤ 'e|gLMu??O2)JJ8N2yuX *D.D 3i6v^T:)x.-Yj #U]09n9$XB2%/???r \-_=c "zbl)s!Rڊ+2Χ8_ў^vvor+5*OvXGI۝I}]*ħ3MxS]mw ш??q+?0pR~/;es9삄>80y(տ)Lخh#*8i70]gD|6QSط,kokyr ,6_3``df}wO<ǧQ&?nbFe#UP"dd \oh+^Ot??l=PO`Hփ͆ ^jb=1Se9¯1S;"^jj#W>gYlc1,Zt-K??{l1>??a@Kݎ@l׉ⰷڜ=#ƾMۿHCׂ(EtJH_m[ג5t }loN?0{\2K5tzRW.X-Y CTh@Ccլ%"nFd}ѯ??$V*(U;gߧ=|%~jNoj/OR>/7DmZE .5k"Cϝd\~tS+ u= ̎\o֬)?n-#>=YZ9YTW8o+Gnf,5Btw [08o.TM$q{`FS]٠yU`8s͂#o,A΋!?nؐaC166b@ ֩`l~i޶ *.a26ο[Y?nc(v n;?ro&%bGbNҿ!RF2ѩpC,JĮ҂[Dd ?nY:NQMOD_Pɩ~7ԿI.XGO*"IFm!Ž_1aq-¡ X-dgd?n7x=@CX*%0f/Ch Zvv[㹪~C8Ҽ$x`FY>P mL߿)@1?0Fu`QtЍ6A(('cУzi0[*JXygZ&aT??` ٝp lm='Nid gPl4s4}liHyfk4&[$ VlF߀o$Lxmتя.~_bw@KU C2,{V(9ߠ@+_kPEXA)ᄋQ͗w'RJ^oI:+/] ^EfNE,a@vŏN~o?r|QmxUm믞>~ ??]ʉx??gCe-r=2+5B,^ޭPe|UpMMskѫ)E\R,E 7ۨ!??z5ߩ6;Hoг:Htk jI?rYh>2iF6zuP]bq#H6 o]U.6Jښ2kI_e݆;[\K(2 X[/Nz2Hީ\^MjUb]*/jY@ ~d&?0F_a,l`(uА}50^^64[0~T^n:Fv'*Zտ% IBV,{,Pȴ9GZP`o1O1Gty[^)Q?0??.G ߗtq"Z|Wl[%[ӄ~NAIGqa;| '{.6LĘ)n{6!Z!"-ZzVt`}ɞb}KX{+g-^3??~f`nó"r{zoeg.ٕ?0cڵXҹo$aC enk>o}sg^)mQL˜1 ̂.kJ1y*k~_4/:̊W`[O9+HlAi UIڎŁkdԹ3T>8ΪِCi&vnahR2W߀q n5W毐/ϢS^7;dzDҰmyӹ3µNE|4 ̹+/exװ [fWʈN7O.?0Mk@co Qȼ^96vuD,aS]͒-& 5t8u2;?0pFwgG8h^H:6[& ]zsr+ 񵾏t{iFZ'_Y04 !ZqeM'&w"?n/7N\n𺸽_a,>+Aް?r6s1Gs%3!>^46W|\x!y?0\iKR{eѿrduc:} EOjՉg{5:~3 3b5XQ'x|zQy(ʏ??(J$%ToJeU'e8I,-\$4Jv0MɏU}mY|79mYiR2;g-./a)K%aEޭc(+B 62 lQy}-'}9|.ZVk|6v9#_m9WCzT}eٴA{V @2񋥷Y ;g??kSu6STk(/6cNVeߥ-XO8PV?rs%Q$N7eզm?0R>D$eN?nߋ~pXPe׵9 ]4KqT$_.jv)ݫԚO_i413+Z)4hK5v?nԲ";eg.Ns%ƚ 3kxpAD+_W.#+GFUZ/GQ1yδɱg7"k7ái_lK!pN|[Ҥ vZ;`A~R藾.ENg,ɦy$P?nNpa)([#"U?0OwlUF߭.I,'i?0$#g 1ձ.Z*Nژ>RmP+FL"*n7ѹXf͹s?r d3)L$???0B۳FN].?rѫ0*֖`P\XtOth7U&y#$@m8 MTbf?n v9IRn ۮb5$MW !kx-n{y߸Ji@??N$}r9~Jn[ dȾr\-XDFra6u&Sq*kNp:`8Q8}82J5fSʮ;F6t'0fEvIXAW'G!{[ň1,&?n"p.Ł\," S!N(dC&( 2s,$U>וo\.wn&]t,9C=?rutIt\Il^B\#k$~NXz,/3]$I\7ZUE''L?0G??alj1o}*RZNX^W3EkPYsC>^ﳦ|ɪJݿeZ j'%Ÿ׾1"-[\ P?rlò 7l=[ɎHu$lhx!Gͦ0?0I^dU60!:ITekR.ؘ(ݣyĤL=^Өbƥ#ۑz{e?rt%D{7o0I O6;;W[=˵S%3,5BQ?rSlj\4ESUYm4֢XjlZ,*2UD#ŦfC}wi[55#7$9%.Ϧgv}0 H^+8(& ??I hWmD P QW_mP%lr-Z_ ʋk2M;-z;xg8BSFݸ)ʛQ۵l~7Am:/$\E}v0e\NZcIDy1lFz=m.>d%1]6 :z|5 ai7^tU1H,\`kۓ,cOתoNTH*W'!bf+G>vBIWEAF^[)_C+NQhHc???n,F`d:x1\lbf̋cU#(]Q/:tol&.tпy^wnMꈢyh]&B?n_J6XZ=KJ.<PGl t2p,[-|V*&+`OPm P4DI>iTO?r$!B "KנF_995A`ѵvy4<cYV5.*؀qBY`ʶe,hnmquCAs̸85hƁ'(3 0f ??GtN;??<;W^]".ioz0N_aR0dOe,^:H#[#Wi󸘈&+v "za6?nnpg;Lq83-],:*x1C@)kJ`BvYU0'OzfȟlMuBLުt ΝY1 L)y x9oc{@| je]<}f^R=q>LT75u|.@8|?n$U8#WF@Ե[fm,\]ָ3̠%lTHE"E}fSӕ' >b?07,OJ񟙫r$+S0P&D:uM.fr3cB6 .`}Gu8jB\%>٩ЉJUAa. Iy?r͆Ȓ{(`>ych{mYu;3ռek@vJZ5<`pR 65UKgUȻGwNۨ֯!*{ΞvBykQY,0-|;_kyK+m0VL~F|~1^~uʺqD3ع&MfrnٟoT,B-E*]cp?0R!e 4Mn>YKN!pYdc\3el *ouu2+vWgjUO[th5(VSɚF-2_?r:& %4u&1hʸkn^c?rhY~"g]mA0+,P}kM記WYy4ɧ-l3јh'ذ?rFݢÂ??aXt7DWMExЍtSDOZlhB=C"??4YޤG?r#e䖔tl:_'&DlS} ]Eh`>|xpipvC0?0f-Q6Y}a>=b?0ֵ`TMfrfaOqzsq/O#ģyd\Q[D|*LWTT[$+sqjS MTY̖{rToޤӓx '6s@=-k$GƊ6Բ%L-dhZ|/4Coԑƶ45?0v{/9n4[!\!?nu,x"P2gKgɢdulϕ k۠Uˤ1o!PW)?0XR򄐔|oSi9UlZ/P""?0[4_*-it`u2)C??1DTAZZb0lXV?r-'qGEJ#n5yۧjfFm"xUF5+uɬr.x??e*9K ⭿AULTk QlK?r.;#C`Os[jo_s{dX^m W5LܤϛV԰BmA/f1?n !5?rUb*6yJ 2U"m#dΏ3?r@Z4.N^o/ݶroheݴ弤]*9]k?rC02?0ϼQ%yԳ7F*S2CϨ.Mj= r y7X?0(dHU8+Y6Y kc(w"x 9XTs =uaL;r)˘Q |?r'??x(NAR6 mGޫ.<OJIIđ&zeق3uB,}O^i)J -\LNA!^CUxqNEt_*Z/}ح:"__ku51-V7=\ 6_y[@-,U̚1V?roȡnƀ?0?n&"OBIN=Y,̚x&Xh9;JUe;CU'#UQqS +#b'vCz-߫-ZEܧ藯?nX:|RygW }Xds|gLF2kw(߿0hq3@z7۾()05:|fS'lƚ;?0;jS!9H`g^iG{"-X/&"9R7dC?reHBIcyV^i@WCWŦ ?n??h$ƮP-3թt`丝=Pڭ9Jmkr_,;ipGv|݄sdD+Z6HCU|I˫tPXn4,?0V/GZc>Z0@sbS焹Fcm`G+Lֆ"iDHCe7rs =ǩ*<ԩV?n%{zpNHEf=Hm\?n'~V>QXF\RapX\5y-낀S~/Eq7-mmpK1*!xlp_|àNuPIhR~K6Z;1y3t oGZe`ZOU`ERɇGE~>z?rdp?rچULxmԠ+ЄtmN6j'C6]uBܒyd2d%`e6f=ud`+?nGk>MeZ8ouȊ\n1{*t:hѴf;*&8*FDfyㆲ%gvOc:CPe:z??^]ݏn:e7gDAS??I 8S8XZQ(RPzĒ_2grn4g"9qEOWO-0kO7rvӇ?r?r}R?rheg|=\x-kM*l?rZ?nVM?rMV0yc+??!<~ϻI~^B\eLvڸ#;lg*CktQ<朱hPNWA \+h?0Ϧ3jJ)alcl.ЫjR~hPI-"b%3RȯbǦ-s}5H·=G y"??c,|é]`b ??ls SQz8g`Wt<9Szz|}@iPdQ8M=EER*GWGNڿb&VYzZ5O@]CŨ?0+ޡ?r`a&) ܐ> tVGSZ{|ʆG!Sض\7;3&!n9nbO|1vqJVpY+ߵ*!s#&-;`FzBujͫeu(ni?01 żSH~ CT~ދ}kΉ ~魾qmx!_e֠( v f7ؐhYauҷ8bU??N?0'lA֮|bܭݚ[SNڏ{&AAb \N?0P?? Nb9hBmwnX J[J:)>dWÒ6 ]n H?r׾l'W\ZͿZ8bf'‰zǴV׬&pXJGe̋N3KNH"Z/@(A N3P"K»ԌSXT{uu~ ٱd刞?n*0V:I01S#I0S"*\['{DckRŨ'J0~GJ.xMYɳ띄1h%*BD/d^iqvbȂaK^\Iy$qzla5 zY8thԀBu9FAIzE f8]S0̱klAɰQɇv1GeL _fim>kG.ʨ[?0l|JvKJx.-]?n%s]!#C1B4#sR(O?rY?0,?r6x}!ݸ k#]?0ƵlgrU1Zƃ`bY`Ǚ6^AffB@Z))d.N|af| u(L|<oQ#& հߡIT~{|jCyxuؒپ\K[=wU-3zm#Y*džeXm?nZ6"kFɀQlhc` G?0vq:P&f65CkkKUCp#qgGBUϘhKGO&O2stfhmSsZqv\sEoХSFJrrleam2%S׍1w!yOS'l)&{s|XpJB W>6 =Dп1i%0o&-l%ֹ??d |AN; 8cetq89CB1E/`n8"٬X`QXU#@[c[oH?0]J2]=ܘ)4|0ĄʫYESz 0sHQFgvY뭸}?r_]uoBo 72"~%y3vk?nZwUQغFOmd}ͽ^k{Z},7t+8](OpA2B[$#mWY^ƨSCW=@eC^um=a{\:EImCxY(q\%T8ad/ez?rhl0VR h|fpyQD7k6\ڀBNBUu_}@%1!$lDӢ?n_ګ+>y3Ո>Agn R U6Co{'x* d9hI%G.[zPzƽ`%=CB")_9[T|ĭ7I}?nܘ_aA;]WK:ݾZ oJea!2+jCV{+rQ^'Ӊ&*y}&hP*Gs=%nQ\㢞??8q'"v MS\i~voރw #2 _+٧N.5ӽMOeML.KμDu+a՟#-.>&/bx:WXhx??tQžRmJf?0.\'̘+T\>*Xl qڶ 65!wـ vĕeMPQ?rЬ#?nU\{?0㟛b~6 GIqt?0(a[KMQ?0I6-y6,zݤ%:zbװ)F1Jv~~ut4 / -|?r00ɻƐ?r &]VQ¡tmq xk ( o7a᚝ϲ?rG$+fj0>EdA\ž)6BoØ%l,WKMdЛ{Ee5wuuUw`^"tj.$~BsmC@㜭E9j{=`I%Wl0Jh/^i7x0@|jƎv_mxS'.3ޅQ͊L{ +#+<F: '?r4KO=W>5"PEE:T'(Y]\kH 6\I'Ik>hAWܔ|}#|M>O?? IpjOS{ |C >Ov_P"A.}Ѭ/(v5܇ jD~Լׇ>5?0x;/h@[`5pڪ Ɵ?0]`=p[C??SÄ???rC_h_9{%JӀ9p???r?0 ݷ7?0K?0?0!*/?n<ÿP??>U ~`aO4`egl⃣9cß9'dƞ}t_5.jN_We:?0+Uq}/3ǟ4gnt!.3 xE󃬽`r;>®9kWג$G4;RwLCO=b֪Blxf'Xʮm]Aͯd2>Z=8˵F?n@^>PHlyK{BVCA#Ǝ{λ_&,7zDTHl9hi6q n㓧H6Q/SfB?nSA<lBs%Fxd'ퟭHRΣ{ώz^ǀjĜ!,xN0ԷQENWïR3Z ?0߽~tw.|?n=m~Vbok]*`ԜZ[4I^xgJ6%Vbk* w#{dѼ?rw\Wor<޾/vЏs.umʽc"A2Tɪpoˢ????y,+ߓǂD}6??f_G_?rom@W?n <VTIk4uNPI]]Zҵ.-r\CnY9f4:+bBB[~;NTt??SPY5*00:jj5o$ ]kO4#DV-Z&W}#A F;oI(J@zާk~B@8K6\*ҭ5Uu:Nv,QM[ɼ1L'x6]@oQB[_ߪب^coN`7g>sٖvז4?rUH?n?n5,Զ/kN6tj`iDx@A%n߰  ԓ*dH?0ܶ7x+}x Z"'!7%Xe??f0-i2wWCļ$>V  BU+Ġ7WC"/?0 qgp8BfdLŌrϦ|9Xt':vLAp`qx&"!5I/I'Z he$-J&a!Zɫ]왉EgFl7Of퀳0iI4^NUcD'A04QMYT}jW??&/W؞TNN>}‚0r0Y@JNP}Y;E&M+jPjEɡu |?rL?nkjDr¥|j<5 zamugy"áȅ>/n5?r آ{i-uؾuI/Y$ßb_wCqxqk,w=uWQ Cusyn< 5b*Q{)-E6)뜲01??]h-pYp8MMhhlr*d/ϋ!>BY駻ojU{|eu0òvSɳ=LV}/!AbJC??[ѤYjqfofuah%Q?nKn?raqWhE="1*_g}ǣ+??d+ q5apb"NMd5)'Ww՝}uӼPt~ "jD$1?0@K AXH6ZL2 VT$1ʁVN,.pmwYbISpܮjXCgWAX09;qNV˙r9YM*˂W\tH~羁B.[],/g'~7>`N؊mZw eع(HksGgP_xF3U;mبddl]{(|lI*hΑZ. _{ko]%VY2ow.#NICxmlc%nƴBkjRVjh}E l6BHEnE[*v2P.ƴ!ك۳o~) T~TkkK>Uj!>gEr>?n{>h9 G ?n3;u/WhؙŕNCDUZ›?0miݑPZ `KO[6?reEЧzI<'xoue3:F @cIHUipx[/:fEZ?r'tjmaM!o:Ϻ+?nXu-M@ =PtnsDa6A3xqGTf5yטrp̀Ѥ\haqN??{V)S^dΞ՝[Ws*RwhRN駧H™]!OGL)nx!>`uXA(ܔ@?n٭vK^O| )]L ;o+gj%&.luYщV?rpbtĒcqZ?08?nAb=r]5MtƏzwBT Ǚ{hr+I0v"Z?nBRy nfmg}=VY/2;>twsA?rBFtxyE?rrLd8ݴ>i<(`X k1=C-9SKHnnZǽqx?n]M `v:6t*{(\ uK ʘJ=)gʗSHUKLJNյiK3P7E:{Tz4Һiyuҿ??Ϟ??(5׸k&:c1~a;v\4aI-砡3q, _?nNQT!77??X5?n5h9etdx>??#R/8/]s?07#8/R,D(᱃6&CktAبxo[&??yrzz\dmk?rΞi%?0ÙԟN`97pK8<*6iYT)xi O>$'Ųv'O,)y*uyөm.E|Ѡ&zRGnk2Gˊ2?0{+kѪGJ)5:C]T[Lh*.FߚWjK9$ŅQ?0F/9 M҃~$;t%i%5#/WW1_Df{g;D_*D#7|qa|?r@:O1sSȟ ISw׀͢`(5?narmB9@D۩8k)vCfkqvr:V鋂VJ[MrF#4@L3ے-xZ ??j,8/?nl8?nەiOsLȬF*仦y"Os1HNДyJ}|yIZIɝ"IM &U#"ǹ:%'??%ר |R(ŬAe!U):q@B\b* a_7Ԍ3Y]ċ/H[(r^HC;WZV *ςZОf*zm̕ɼYn/L\1IBf{s@k6⽡zkPT"y87Nc}hid9`M¬eOzPH&C &ƴ/kۓƁE9eB6bi%MBFAmSm"65ry4;'PO|[SQtG<;r}קd1;8?0,H =ZDžD@=IB+ZّkM[T9ĨC:\^u~4&iz8RZ'0|oJ;Q=Ê|n4Dx^Êd` *U8bVn,w#Jd0|??^^S$-R}k?0. t~BSAd?n;qUԟ%!䬶U.=sY]&J'w){p씱# ,e 'vc&ɽLNςWڣm wQAT?r~ <{5k8u铹l91z]&TGW-m9]yr(7~ۯTZdtH Xrb䙠]Ӕ(Hd#rg[N[}d5јoX2MF\R3\DҨ 3OpE`K! I?rYjid.8*zb;:'SeT:l,92<3z?rž/OI!hϮd)V~nyt7_j|@TzaƦ.jFAlњ:{ȃ<~|ȒF}WAxqG(?r#5O*7UDpCif=V??uFypV5Md>ћ&d m\f+@N2p6kUQ72`tHt`6_tL+u4$LO<`(^"M‹a~p2Q6Ke"46ܿ6KtRo*vB+eSeCC;CwCD|..{G`TR}D^]>Xuj5jVs&RYVғsMp~F[,3#%-ln\@W6umгشBStFQ؉LT m%nEł+Ty -d?nByuPCTƜK?n_LYV?ndڡfJqh[e`ΚQ-:" 3'ֈxao'Bt(/B4qy(UӦVxJ|,s!o)5ntGz٩[)I:tC*?nʡrR8IV_aIwsyKJ`m7#]2yL\KV:sR/ѓxo[Ye(П4oTJo/v+J^ 춊T?rB?n6ba?n2U;t3鰐lJH%??W ͦ&V6\Tѧ>G{P%?0d.*264SN_?n-?r3B݂??0 Rqޜo1^33VV\R; Mb,=* vd[mD7:5?nag5حblC+ 9s`?rlݕf1 c@ƐɈ'gQId@θ^>6::/u`i9ojXOO>nvUӺYN5ƭ1?nWFr^2g(0!h1yB[>hFQ>39B_ls)%W9mv,>zq`UC~x!ZѵÉ߲#`6*k 7QﴊL}*0Q:quR?0%l b?0`$N a59NJ?n"n(F6; 8gh K $[\p?rğ=?0{ߖM>\J.137^??PbZx{L2؋0x"?r)uJ:ށS.o唉!Ȣ[}]!AC÷C]zm#8hd>u(%cv'x;2rUcCj\?0W?0 &Im qliSt 9R%ĢvuTnɜZDF NJ?nUClğXp 'Z?r)ɧ\1n3d g%%Z9M6m8ɞ aʭ0% ׎iRі_Nj7BX֠3ݽT[Jţt7)zo-WJoD;lLcUZCs>im `&wZ̫%:M7aJn^kT,Qs)qF;j`>GBqr{UW|^.£M)8mc_>nh yv(IUx_ޜiVkO O|?r)<8;??e8~|ϑzOhxԙU/sFf&;NyϻM9Ԑcy<3IVB$?rfPo7?rʡaD/_@?0ݝҿBVy2gc!m;#m6ܚv&dx=B芿4kN:?? \O/]A[?n:а-z+p/Rfӿ&1vl&Kzr)u1??k7(>Etnh4;kXK$>W^Lȍqoѳ_\bx>v1DxI]ɰ"h8/* [/.UXe|ļ0W@M.^ΑD;EW>wG7ԭrAS-KDINZkl#C&Õ] 40t0J/.vA?rY՟xD ||FDLMc|k*xM_^¹tYoB;ZE؆)-T/8h5{,3UV yT˃f}T89e:awq^R$H3bx/l}?nAhɑdP\ Aʗ^lqӽnPNMM,6ʻ5([m@E 7qU@"ΡXAvvI}`!evzr_??ink(=rM\4^P&@0nq\cIFnbw轏\hqwWNEiף\PQCe.|}jnJ?n<47]}?0Szd}Q@9,axLǸ s8x!pQVrĖYO1[5Բ??TWæ}֚' /lH@D6f1w֏Z9۝'>oƴQ O@P.C)'HKd7lgv>Jv٭>,V˽]?n>,RmpyT|Qla"-\#-8x+𛦆S@#??yX$6GZDںv4=۽:D>YpłHܚ??p4Ezi͡)Ij"hgꉓD?rSZ7߭8gQ[ \`7_o5=/Q??0AX4vc3{Jž/BƶqQ-,/ 9apie k૨ 0"1G:^.Ѣ:y(ZL??b|E/3ߪmel_Z|coQ|}Gm@G"o^wls3Rm}XLdezV}T۳<1CM{CA%3e>YoI4[fױ9-^!yRTWnT=v)/JF7>YjwklcA?0q&uǶlx$\]K3 ??tnyX:qIٲgor??):q/Z8L?0͞%"hd#j'5c-..Whx1"6 n`0*kSxï||_hjPccx]_:E??Bۋ&8oUS+J!PL?n|VM\vuI4VE.5'"I6+KpA_Q"P0$CliK+}Bڀ*,t@!u2r*s?rsCl\7_ŔE>xyЩOmzSGBmjA7שC;x׺9epEb{~Wf\EMCd΍̲`51+jH>mX@#+vZkg37|L=Pnս)lp 4[97ß5~//~8Y-WW GK_zMg-!~ bm]ljq;B)Wx?r5ʱn U1 5?nq~c7,V>tab1QK=iIpiGZ)_Ń#GEыSJ`EQkGT50tvr"w o{ջ<5T/(.S%~m_#/e˫J??jadPN'qxq@ "k-2"-6|y枠{N7OH'و@rŸ6fǔ i@uٵ3}]Q~NSImLǖ0ڏs7 [|[/}Xi9:Oet.q~yռ!Reb3U;+jf,vAb0,!=CyٔB+ryCX#IoWHA RST1G及Upcm|X9Sk@7e͍}#%Իp2ߔ4??VNUS;/qpT=w)_!4KZWؚ"Ng1s))peAUϦ8\Ya PC՛1_m\n6@'#Ίr;{Q^"qiP5Gdְ(1!SScsշG>r,|pfٞy7`>dL{xp'=uL[҄C:U,2?rI\!Ds2`|(h}5aX"l_\SVKr-DFiT&?r 1E{I+ﯚ}JÉĠsw?n깘,4MiiۄX(.65q%EK~Ի*(|^êp*n*<><0'w>8|Wԋ>{'<[ %(FG?0SIGq~/p?0?0믻U"N|ZX?0<1Okxamlh˰"znY;{≭8I%HKآʎ9_)ǀI)]-BV$vQJP9Sn^Ǡ6t 8]#^{??&1HmtY0AW~Za߅a3{.i'I3ec0Nc2˛h29Ux+:Ƽh);?rU6Wo\`ݰjw4PﭛFiDH}acA_=ysΤ93[C??ƐkrRYf/ yd8A51\W59V}I r8ЙP'#%}pJgҊ?nki?rq!P:UDm.A5`H݃X/hdZ9޸Ml ,^^h `ο%o8E}a8C7[{1Q؆Eeyw5]eVIγuYM۬ʫ"1ߚ$P?0$ q~{M՜mYg[S÷7l*i|?nVr*WςƄCT<9|nՖ ̽Em\$-@ʤŧSƚBZ[￘vz`#-vLҚi4 ZudTƋFwXxڬm4Э'Ɯ7^+?0D~se,O3M 07=. +#G?nh1 Y(X9qKՠ9w@͊+@iaAd8iC}??)6#y*p܇A'_\wm1[)/p>S1$'fU'MuD ᩹S~~wE[_.U1"\ZTJvxM[-n*t-ѣk҄SJZb9u3qB#%g. $㧋,hFa|k{ ( ӧY^S#o泐K y|mbfA=sҢvQ?07dJs!K5OjUx׭Ln-66t6i;SK|J`'u҃&t`DƐ"ԇ2id.H\06{$H]¥[c??|(>Mܥh-"XV4=K3XꗆD,wFNiN{yߍ=d֫Y؛怙7XI5e?n?0NCp$$߹F?n='NݩQ:a Jҗ>sAԟdɗyτ1 {S :W-pKZ^5ss*ͼaKY^y^y ަZlI O9ߐ/-]'!p"a+Y4"??IGiCQΘˍMlaѨ BA mUTyc!XjN o2rR9{S ?rI-sRZ<7d@q*dg%vZV@ 66u/W vg3M[_!;3??8D??t$ZZzqGB.YrgxM U6=eD&MDCI8>.٬H^Ӵl>i0WM }.x}6\D(O\st6aI@+Rrc$${)l6Ux?rh._B+C$*19ooA 38Eǐ?nX06R5*k\|5wf\΄=FM-d?n*r3t<#czݤ뵡U㊤>:fOe}WsgAy%L5^??O_X鱝K7m#[d(")LpcluBֆ5&b(9.N𕊷p?0!@ڠ??;*:lx-w`Їѵ?0m똔>??1x^‚}}6Иp0tVY9-)G0ݽ58e~Tg i??)ӟ̉c!묛hhWr_ǭթt(|#!#Ǝ`*=?r~[ 4'8ZY\rBnn"ɠUf}aS 7ؤJ{E/loCB[9lv{pZ[K"_7X q oO#.&MMLym6ֈx2TϵTٳ|tF ??uL\Llx#Rw[w[NgbIE@[lʎҘ??vgcDC4:ϥao{H'ͣj^jh|!lpYVCKHVꚽti򗹚#68#"~YLl+]c"a_GE.ȿre. _j~""3撝p'eM]t-2GՋ>?nI:N]Zu.,ӯ="pA 0 !SMïv^-~ w$\YݥI#ݻraYsP aEx _ލ?ry8j*벽kb@>EiU{a/V_Ii0}P.] `@5 >૰lβrpQyTq²+jJ?0mbu.ܵ~ L+8]|he^YhJ۪/uE֬TM]xQK Wjq>!)J9ã} =ٳ/e5z6~VZBuv??~UAl̮vk6!q~3o 2??EN罿oUm^: UNf?r ngCuO"7ڗ>ZD-%#8ܶachQ^[[QKJ+Z L& ?0nz~?0"(=(Fbf)N?0ϙx)ͣ!'8sժF#7VbD.J/d>=]A 92kȚx)$LEv8TmNèViE^prt &y\]\r6Li*=q]e|q|1]E Z72;9??wjBoN}:S3N 7e??S^TD@+aI6yГ #k+LL6uMkggbq qK`_v+9OV,dYo2)m:fx5Kok꡴\\\̛⣣U?nO>,X^jȂ&.x'AaT, r/g*&Qa9|%ڥ˷]Y(V9v-\*U0'Lhɰ.v@{As=/^~?nW/X!{`?r+Kढ़K6]xУ/NAnuE$+L.r t;6e?0+_4;{AI6M=?n !E7!@ZXMEycs ƴ hQ3Ҩh$袱@ˤ1vȖXAvT`W!9s7SOL%/t{Cw$w33"Ô'Odiᔘ+;TQ=2,0NgÃJ®ߔk??r.j7?nG Ō?0?nCFW'OYk +nnAR`8:Y<taK@4"Ki790??j^.ܮiHy U!'I%Bnn*dEm -=Wl-B!Bb`uWzhR!?r$4#ܓ£BzxG4Dfe(+CM_dy\|n!dƆkx5!Α%2GxB>4vuDfe(ȪIH!f.u/bmz0/OHwG/BC mYx=IBnxpZhn~hK*dYꇅ%8pvMU#´py ha +#xտ=WUڴof v& s?naTHs-O!)P8iBn7|l8HQ!9kx7n*!7\w8CDnw_IB27Q?n)iZhúޟgCn:D'JqW.1fwn96cfy{nǎěnn??A\s#HA@׿:S@- 61诩)g3[]M06 lMY G2˗QS24)"oV[_(NV q 9űvw5:n:(F"c4ya^f??PtUfǂ>F1}l})!a& 8E?rQO M?r{?0iiIe;\*{MFuE~Fv5*K21J/y!B?nt֏ͽ˸5=;cΎ?r_v_??¾^-5XTۏ?n4UEfoџuB8Bnqvz4ĕ99)f^teQ.RFSg^d$bÙD8AYmHré.R~K)W7/W)SQRQ?ni80rED 體ܵ Lle>=vMkՕwiK^Cx5;"Y\U""xR\vgo)M)?0xk绣 7Rm&e-Y,J$ґ??#hE<*OI&l'wCƨ,RH5xh&[:-gt=1ֻ8Gi4A@x߉өU.(+#\t"+n55%I^۩V?nȨ|ĩ?0vY#sCg2~\U~x(",؈|y\U7_d4~;ĬO{>ȏ.5QH Vg.5& e'o~D({*4\s2qnpĂ~M$xPq?r~ž6pp~ RE>cF Q%\OpG-?r6} zt3*u{`J9q^E@í-?0-X\?rh)U^T4h!Uh"`}TK؜X-`VXj*]+D=\hnTӍgTͅ?nZ=eC`rnśBGڦ h_ʁщsLK݄'?rGV k4Pē?nqr0Z`iTU[ew_ųyL3%SVdb].PtYmp[" %~uXN'o2z%16T^%8ڨcMXh u&QHɫ$|":ߒ zJK1VKp2 aEJi:0cR?0^im5p'Pz,w|xAJK$q{m2,I7?0e,'YVKaZ&{tkଏ$Ԏ$̥I:pESQ9$98۔A{JVu'??IjTظ|o>xB{k#̝ u%)p`'&bNÀ4e?0~H.I'U`?0`?0!o`m/1KқuvL]esu:5a]HW#CcV#|8ˢDr"(eh"ܦ?r2g2LR/8; M>edIpn\uN@|HSo.MuvJize`v6'hDzq OL?0}=񭈊V&tgE18Ah`0gp(-?n4w*J#.O5EꏃۑYk\u<`zqHťIxoEb rݍưQ/)d!XnEu&v6 +L݃t8??~~l=24Rv+b'[y;ML]4o%Ԇv5(*2xppRp??d$BΚ`{e4lr@fw5_y>g'Na9y_Mu??T!#޺^/2ft)]&[},F bv86Q="qıVUۼg/sb'Z?n `B@.e CLVw%6UE\\xdt壪B%}KCR *$h[f*^:OI"%?0?0%C:3&~=*Xd.@WU@YKb"qěc}AapF9Az$W>" 餀X{=hN= tUSNĠIV?nł]qe <8ʚ4g 5hYmٳZЂ&n}Մ??qq*$jIw(Zv[v{z/߲l)g\s(iOI6b\?n=f??Y>x&T]d)>MĩnJ/gŌYw8VtVf}jOKD#&l0~eFM})'$xrƝ)??O^)7A4brCRYd_??L慅k LX?rҁqU5H7=1f w7w&C^DEI!9d,x^343ԙ37=x8ѳ6D{5gšdS??wĶCHf 2& $i(m>Ud괗l̸߄uC󃐍VLuņ ˠ?n;|5llŬ"!ivJU3.*=PgYtR-4@w .,(u?nXE }ExrWɐ^9oZqzopLcl+nIk@D9[:c7.t?r}&t5gY5)Ux ?na`pT/``( (*= 9p ]nEgX˕O6^R3#YsL$;r2?nw/FlEp҃dx;Ѣhᝠe-`PGЬ٬Sdl--0-??&W?08?rz '$gKe+?rHՒre1Պ"YQ)GR4zp({K+1dg$LJ4,ަibO3mISvZfIjNw~$5.\.*x6!AkoERj w@%SYU"}5^hO&'wɒt_}^Qef-fgt di{xKBUẁowgkwQ R)kXl' 'ݛexVe2ia$/pXځ0R|Ku&s9Q5A-,n$SX?nf/KU%t0?0jcyaش#zFiVf#҈n̸B觤}+ŖTl=)^]Kd2ɹ?0Lx88LkhUӈM4ÖZ?r ?0?n>C{VE̿K2$egSIޡgq$lL&a#I؈a_&<O܄447/tX<aLq%Ex:bjSOr??a\BcuN?nko@텕ƘpBH?0p;,H8-ܯ4-ނei EmߨQs}<:JР:v?nJX'{r9a4,\DO9kL87 NOYO'N(9??A:o=OG1WeEΊ)k: "?numSֳZb߅^ `|uVYT9Kڅ(5vФ߶"y 7|IAMatvh,!#9B ~1SeOw(K}}AP5 ލ&.PIF)xD>p)!m#=芠Co]ƸITbM8CLޒ&ikR=a??hEJ_W%֘d)Q1")31':C=[q&<[?r;"H4zpׯe<-an̈́]/2?0:j7g6Sbo íF`$82(XpOK"ݜK7!;} Cj|7猆`5ݴ+Ymu*h늩nA\^Sfs[n'/^BTU 뎙u:Nn,qt݃?0Eq_wO;jks׬.H F\KQb|yܩ:]Z}bv <|9#Df٫tncM V=R8[{bU_L6?rfc}+.MjZ;ʝi#N!R6!Aՙ IQ 7.VY)K!SaCӁ&w#'.~{9^s9K^ePY l{m!Qx QC^UaHL$.L6c.?n?ni4?rUJ^Mt9m5oEU-rD2Jy>*DiWVBli1&QhQlr^RZJq7+>'&a{?rR](?0-C12b`\?nKҡ}$P+(Bu^_beRҶrގBU l"g8C~0 &=BqNpSxr㺏`fz;x.3enAkNz?nxd ;ɂN\<}1Ƹ})b\Et9XQ:Y?n'3hίo6:??-4.UyԽqгf6r1??,`Q^NeV+&|ݖ|m= VJ߬D9-]+Шk";Ž}Rl(Hc*UhYvmֶ((~'ڪ$۹Be ~3ϕ??M~tg8ͩp]dV (3Es嫨iԭdbr˫уlj\F3Q?03?n̯Ɍ~zZIy</^=yXϬu{F>,N6`-=v!?r9U-Q=̜l+d/^P4y&em*mMnQ:)CFR9 eLˤ0IT#-S&DRh[u_p*%3ژS6Nk ;"w[LRq;ZXwS^(WCrJqyL[֊bVe d~Zm%[QػQ/Q6Sx 5VpÅErܞf=>)trK^+eߖbW펅n+ۛ!rV(+?r_83m L L L L ̥\;yK:ϻ+q4|ȏxNR޽p_6% IN"BA*I=0?0L]8\8g1N6Ѳo7aq7iq7eqS7mq7cq3`OV 1QOGs!1Syi?0/?ns?na{B8&̞8ZHـhXA4*^bD\$SC!:3]VʘOmVK%H67f3O!лBj.C@|C??)=6'_6A;)7[<[%D8{9.X[+.w&{[doٖ[bv =\;Uӣpdk?nӢGʋ?nbLs ??}Ԍl??>K0165`ԍbSwbpn\TԳaDv߮k.8{Ðqj>Zyr\kejSPPZPJȲrb H3$?n*匞xnIJ@%ibDlP0#UU_-z+iSwb Qŋ( /GI1cO'NY5Uk%A^ea0`V0 4b`h;H8C9"/D<]a_(/_?rB5lMCj m`80M0H0w9$ N]SHQXN"EE"Q4~*€=(6]IQ@W$ݡSZT|c>3V?rM 7nh=AV`/vChh3)c0nZb|r'+@;?rV Xj#䇒~??54WׂZHHɑ:?n%x{\C`,L@'xyʈ-֊d#sS棑Ј]/m!BhZ"(7l|l_(pxGG8lTE6°)p[4qR0/廛] fmb`̐?ne%bv??J*pvߡù;zN)ƌ;R+{W>c~bU]"$7#f[u1\Ye jrb)[aCmS??":\I(`$QYrE "NZmHX"3T]c)`=z9eDPluG6{ʂ'_QXIc}]t5܂ͮ|Z\Na95+؜*Ʋzla^PSegX^qW3n"dI֗'sYZlvӤxbO//OU"̱ߤ;Q(PG47 =IV(8!Mkb@@! LR7.?0# _Y* r.7T.Q"b|s8s9@n 3ϜQXFkGriBN21=y S@29̣ +DF :6LLIQ4Yq6.@g$V|-b;Di*,TAQIџe0..܃˫-1EoM +#*~ɴf՚9ڬtꚪ\M_?nOZ5Y28 C>$p]1 J"BX6Cʐ cp^ Pʸ3Ye)nc@ҤY[YM6 v^HKEkm1樜#Keې5vݥعPְ#S|4$% C^YBsjBQ~3oDgREmQϙjࢡ檔߂h xflv 0,.ޯmx$⢝6xR#i7ډэvծF=FA{؍3R-L } y^Ds].t鐤C)(6z8Xq6Y!!ΐpC{!8<`jXee"^u+%B'<ܕ$7TVͽ^,\D)t7$n-f)IP@Max0˘!ZLr xo_1NUKf}iQ:)b"QQNs3r7D/]UN7?n??l_:QWw؋IM3v⌸kå>SF*>}Xpߛ{&(Rj!$O[" QY_c"`pSi;L_KYwflfmL8+^jO@&uyW4Z{lI-&,m^K^G"}wx^s.&M?r߇:9+~F\M!9-8Bͪ-:R,&EJ^~\jsaȶhk>?nً! xGjxn |+$<$6Y?r~< ceBty3siJ??G&5gd{9T;7xudǎwн~~Lwix} x 1>O2g?rq-Rf0x^H**hf2|@/HD]V?nռBat~yޘ޽ZRK3 r.@ 7Y??k⼹aږ䤵CIyu%(?nay``\%?0X}Դ}ZCQ̅U, $ a1$dRB$_Ik9r?nԎ[  |,ZH1V^9 #f~Gh#i>SP[*GZ??SU9mCO?03wH-gzl>b hG?rff?0Ye"6+JbXkF4I}<Yd?r#H-ΥoEϓlݕ=:Z2Xo?nQgN7 Ѯk:%ݳ~Y=W#*A.s4??R'4hKK3#Сȋ:/oJ\G;4AXNf%g6)Z*&?ncJ Ka_7Q'Q>w}ѰC+ŤK*MN[C6MKoy?rx?r88/k1cLcnc~)vK#`:&tTGd;P%?0+ ^{5杇3q<Í!ttBGYJIS#HPqgۇlOZƃ+^@  3,`zfN B-',NfM'KЗVo6S$2&-zs,}O*`n~Ȝ.3z~q䕤՝;-l`+wj3nnOlb)<c{mD[QNEYE{+}я%R"iDQ~@xPH<-a=CH[4Q O O`ЖH/NasJ~Pc aD]X f'|m\Q\0)쯔b)ĔVVox byc:jVR@b ?0p7x1|r3ÿFs}|`y}1??{wQ +#|zyp{C<룩Tm6ҷr|2=ȣ1rWAL_4kd1GD??~П2-Á5s ݒUP(b??aUTNܞԈ6)_nMx64#vb<1~ v ?n hYњ0(0:w#lvoa0Uu#?0(?0 _'6U VҸC6 I;E;Qb?rlE<琹Ñ-TY/ۨ(|0Q OX3O?? 1JO<"Q"< Մ=B&"=|bc&}pNz2]{9Ŧb6%۳5@u\lNl3ŲZV϶ۘc701mx i??xi)JG xc&2M\7e[TQ=Emך[k^OszJ!nf朓 3zg|#G@o`ta]p |^xQu?05l&01?nԾQ\2DZ|z&ń]gm|:U9A?rtL+U7inLЇ;v5mjc`]^8VU!j^Y~< ߹6FYӽ;_$YKa!uJ[}~N߳6|(?nԥe>|0,<0/"kG«!5;qQ:K_Zmc.k/jmJ؂{Rr_G*4ӟӛc:F~ ΀?? zs}0[dp6*-@p^y kN1ْ"0#Sǟ.u>'E|Bٽ,`}'ed|O{y9dddaYz:,pn.|dޑ૰(sgWyγ0_ Bq'iZFP'TWf=ӋdD*1=,Hb8$d\7 (#({_ ?n5R?nR؞E^@H~Aci.lݻZeX??8P,d疇l?03zs\ AHM<$to0Ǟ?nSYփn/,rs?n2! ԏ?r"dӮ ?nZ}3R +P8旒/,?rrn6hGӲO`x!* ƲH4Yʬ )̞^FQY(YI]J̓?r]ж<g_ i3M3qTBck7 S%RÉ,o }'XD9zbG&/- 7@?r|.Bg<PiR+̍Cџ`4P `VBPD?nOA4?n BY?0mSGEF[pF9,r 3 ?nC}E$?07w?rom, 1px xj]1AUy,#̍ĢT82??b;E5nH[)|-,?nSca sD9YX-6͙C]ǞaUӌ݅[FE??T^tnHl/m!6HVsܐ*i-mkwUa hM2ʇtcZЊU7gFK]_`@:݆A~Zf8߬f_rbH:2?nDq޹QE]?0w͜lmxDUaB;_\M8ߜx#tHU'#^6}se++@?rYD^Rjw%v(b;MZǧIw7m!(cT?0rی祐+!i]KL??#%]o#9"%~C5t{8taPG-5:nO|>d-ZLѦ]Fos'?rYe8/MtoTr9 fN~>r5:rީTwqX6>`U?r2?rkF7h :v"w\?0tcz@LdE;I"NJ*. #E-,Mv+X18'm :ڲ?nJnI=g$->eJWQҩN p^'Vq\~>??]v훌N糇0H}q׷:5=6b);CŮ- cNA2p݊f]9F4}eD^?0[B2Ud?rPP<,ƙ9 Dˠu]3<>Ygf5)W!!6ww".eѣtmF̴6>XRd([?nx"?rQE⍞g}"?0Bqgs ɉNU(Iho#Z`uMFhׅp`^pӼwXvũ<7??KJ㦗G-ls<8r]- 7ĀmFӒ-.`v}xl)qŖ u)\hESwsrsGGT???nr`5`o \zo (U:9'[''cZ0JIŝ9̺z?rEJ7??H+?rLϝl e :Wqn%c(Rf._zf3ӧZ]?0( ?0 t̅94Qb?r#kר%h^v߅+IAv8hh@F4|x?nð5CalS>وl35s?0I㸖S&7%旼Jk?r?r3ptA&W&%p7ݠY) u]?nЛ:]`7kh .?n*>Un0'3VU_Vݚ9T3XIuغpөxBڮ!!4TH % 3ƀ>SA?0/V!^GP1lP +#]ޯ :X-[2LVzlS"SeHīoв]f0?r/>],!LyNȜ+ 0(+2zkQNZW![^jI r=$D~uRSSĜzt'kylU8yAZn>*փĘ#>-C,3|&&Q_V>صLޝ=>$Q<t~m:/"ne.PҸlP&/PA[:֏9?r+סW4#x"fݨKY%p&#zs3z]!d-LAFDϏ`TL?n[ IRmbN wVā%㥢qB {y M Ⱥ`P}1Hf#%K?rһE\[|Lfda1it=K BȣR:giUfKVޡ0&+:}?n4DJ&@T.D%A~fN:2e1Җ #T.T^IZHD4tIN?rB??P㘖6}h&Dss\{](xHs7CQv`AeDn%v&$䍆N1use Q-;]j4xUXT_BH#`YJ|qFgTCR֑Βݲ?0O;ɜrp^1tNxR!npaUƇE\&zb󸼆cCNnb׫NUEyx n?ndWr*hWAbw+n92M.!O?n;܄lU.VA,'BKy+js5-7 7FvFQU76NUOԾlHWYV?r)BlꈞF9΅,}UAb"lxn w.A7ǀt<(?0.ިE瑺a/D9qkb4FǬTuVtPc12fV?r=1max!7H") + sys.exit(1) + + log_path = sys.argv[1] + lr = LogReader(log_path, default_mode=ReadMode.AUTO, sort_by_time=True) + print("\n".join(lr.logreader_identifiers)) + + +if __name__ == "__main__": + main() diff --git a/openpilot/tools/cabana/.gitignore b/openpilot/tools/cabana/.gitignore new file mode 100644 index 0000000000..7f9ac0fde0 --- /dev/null +++ b/openpilot/tools/cabana/.gitignore @@ -0,0 +1,11 @@ +moc_* +*.moc +*.generated.qrc + +assets.cc +bootstrap_icons.cc + +_cabana +dbc/car_fingerprint_to_dbc.json +tests/test_cabana +tests/test_dbc_core diff --git a/openpilot/tools/cabana/README.md b/openpilot/tools/cabana/README.md new file mode 100644 index 0000000000..b30c29640e --- /dev/null +++ b/openpilot/tools/cabana/README.md @@ -0,0 +1,100 @@ +# Cabana + +Cabana is a tool developed to view raw CAN data. One use for this is creating and editing [CAN Dictionaries](http://socialledge.com/sjsu/index.php/DBC_Format) (DBC files), and the tool provides direct integration with [commaai/opendbc](https://github.com/commaai/opendbc) (a collection of DBC files), allowing you to load the DBC files direct from source, and save to your fork. In addition, you can load routes from [comma connect](https://connect.comma.ai). + +## Usage Instructions + +```bash +$ ./cabana -h +Usage: ./cabana [options] route + +Options: + -h, --help Displays help on commandline options. + --help-all Displays help including Qt specific options. + --demo use a demo route instead of providing your own + --auto Auto load the route from the best available source (no video): + internal, openpilotci, comma_api, car_segments, testing_closet + --qcam load qcamera + --ecam load wide road camera + --msgq read can messages from msgq + --panda read can messages from panda + --panda-serial read can messages from panda with given serial + --socketcan read can messages from given SocketCAN device + --zmq read can messages from zmq at the specified ip-address + messages + --data_dir local directory with routes + --no-vipc do not output video + --dbc dbc file to open + +Arguments: + route the drive to replay. find your drives at + connect.comma.ai +``` + +## Examples + +### Running Cabana in Demo Mode +To run Cabana using a built-in demo route, use the following command: + +```shell +cabana --demo +``` + +### Loading a Specific Route + +To load a specific route for replay, provide the route as an argument: + +```shell +cabana "5beb9b58bd12b691/0000010a--a51155e496" +``` + +Replace "5beb9b58bd12b691/0000010a--a51155e496" with your desired route identifier. + + +### Running Cabana with multiple cameras +To run Cabana with multiple cameras, use the following command: + +```shell +cabana "5beb9b58bd12b691/0000010a--a51155e496" --dcam --ecam +``` + +### Streaming CAN Messages from a comma Device + +[SSH into your device](https://github.com/commaai/openpilot/wiki/SSH) and start the bridge with the following command: + +```shell +cd /data/openpilot +./openpilot/cereal/messaging/bridge & +``` + +Then Run Cabana with the device's IP address: + +```shell +cabana --zmq +``` + +Replace <ipaddress> with your comma device's IP address. + +While streaming from the device, Cabana will log the CAN messages to a local directory. By default, this directory is ~/cabana_live_stream/. You can change the log directory in Cabana by navigating to menu -> tools -> settings. + +After disconnecting from the device, you can replay the logged CAN messages from the stream selector dialog -> browse local route. + +### Streaming CAN Messages from Panda + +To read CAN messages from a connected Panda, use the following command: + +```shell +cabana --panda +``` + +### Using the Stream Selector Dialog + +If you run Cabana without any arguments, a stream selector dialog will pop up, allowing you to choose the stream. + +```shell +cabana +``` + +## Additional Information + +For more information, see the [openpilot wiki](https://github.com/commaai/openpilot/wiki/Cabana) diff --git a/openpilot/tools/cabana/SConscript b/openpilot/tools/cabana/SConscript new file mode 100644 index 0000000000..fcaa3b7930 --- /dev/null +++ b/openpilot/tools/cabana/SConscript @@ -0,0 +1,132 @@ +import subprocess +import os +import shutil + +import bootstrap_icons +import libusb + +Import('env', 'arch', 'common', 'messaging', 'visionipc', 'cereal', 'replay_lib', 'ffmpeg_libs') + +# Detect Qt - skip build if not available +if arch == "Darwin": + try: + brew_prefix = subprocess.check_output(['brew', '--prefix'], encoding='utf8').strip() + has_qt = os.path.isdir(os.path.join(brew_prefix, "opt/qt@5")) + except (FileNotFoundError, subprocess.CalledProcessError): + has_qt = False +else: + has_qt = shutil.which('qmake') is not None +if not has_qt: + Return() + +qt_env = env.Clone() +qt_modules = ["Widgets", "Gui", "Core"] + +qt_libs = [] +if arch == "Darwin": + qt_env['QTDIR'] = f"{brew_prefix}/opt/qt@5" + qt_dirs = [ + os.path.join(qt_env['QTDIR'], "include"), + ] + qt_dirs += [f"{qt_env['QTDIR']}/include/Qt{m}" for m in qt_modules] + qt_env["LINKFLAGS"] += ["-F" + os.path.join(qt_env['QTDIR'], "lib")] + qt_env["FRAMEWORKS"] += [f"Qt{m}" for m in qt_modules] + qt_env.AppendENVPath('PATH', os.path.join(qt_env['QTDIR'], "bin")) +else: + qt_install_prefix = subprocess.check_output(['qmake', '-query', 'QT_INSTALL_PREFIX'], encoding='utf8').strip() + qt_install_headers = subprocess.check_output(['qmake', '-query', 'QT_INSTALL_HEADERS'], encoding='utf8').strip() + + qt_env['QTDIR'] = qt_install_prefix + qt_dirs = [ + f"{qt_install_headers}", + ] + + qt_gui_path = os.path.join(qt_install_headers, "QtGui") + qt_gui_dirs = [d for d in os.listdir(qt_gui_path) if os.path.isdir(os.path.join(qt_gui_path, d))] + qt_dirs += [f"{qt_install_headers}/QtGui/{qt_gui_dirs[0]}/QtGui", ] if qt_gui_dirs else [] + qt_dirs += [f"{qt_install_headers}/Qt{m}" for m in qt_modules] + + qt_libs = [f"Qt5{m}" for m in qt_modules] +qt_env['QT3DIR'] = qt_env['QTDIR'] +qt_env.Tool('qt3') + +qt_env['CPPPATH'] += qt_dirs +qt_flags = [ + "-D_REENTRANT", + "-DQT_NO_DEBUG", + "-DQT_WIDGETS_LIB", + "-DQT_GUI_LIB", + "-DQT_CORE_LIB", + "-DQT_MESSAGELOGCONTEXT", +] +qt_env['CXXFLAGS'] += qt_flags +qt_env['LIBPATH'] += ['#openpilot/selfdrive/ui', ] +qt_env['LIBS'] = qt_libs + +base_frameworks = qt_env['FRAMEWORKS'] +base_libs = [common, messaging, cereal, visionipc, 'm', 'pthread'] + qt_env["LIBS"] + +if arch == "Darwin": + base_frameworks += ['CoreFoundation', 'CoreVideo', 'CoreMedia', 'IOKit', 'Security', 'VideoToolbox'] + +cabana_env = qt_env.Clone() +cabana_env['CPPPATH'] += [libusb.INCLUDE_DIR] +cabana_env['LIBPATH'] += [libusb.LIB_DIR] + +cabana_libs = [cereal, messaging, visionipc, replay_lib] + ffmpeg_libs + ['bz2', 'zstd', 'usb-1.0'] + base_libs +opendbc_path = '-DOPENDBC_FILE_PATH=\'"%s"\'' % (cabana_env.Dir("../../../opendbc_repo/opendbc/dbc").abspath) +cabana_env['CXXFLAGS'] += [opendbc_path] + +# embed the bootstrap icons SVG into the binary +def build_bootstrap_icons_src(target, source, env): + data = open(str(source[0]), 'rb').read() + with open(str(target[0]), 'w') as f: + f.write('#include \n') + f.write('extern const unsigned char bootstrap_icons_svg[];\n') + f.write('extern const size_t bootstrap_icons_svg_len;\n') + f.write('const unsigned char bootstrap_icons_svg[] = {\n') + for i in range(0, len(data), 32): + f.write(','.join(str(b) for b in data[i:i+32]) + ',\n') + f.write('};\n') + f.write('const size_t bootstrap_icons_svg_len = sizeof(bootstrap_icons_svg);\n') + return None + +bootstrap_icons_src = cabana_env.Command('assets/bootstrap_icons.cc', str(bootstrap_icons.SVG_PATH), build_bootstrap_icons_src) + +# build assets +assets = "assets/assets.cc" +cabana_env.Command(assets, "assets/assets.qrc", f"rcc $SOURCES -o $TARGET") +cabana_env.Depends(assets, Glob('/assets/*', exclude=[assets, "assets/assets.o"])) + +cabana_srcs = ['mainwin.cc', 'streams/pandastream.cc', 'streams/devicestream.cc', 'streams/livestream.cc', 'streams/abstractstream.cc', 'streams/replaystream.cc', 'binaryview.cc', 'historylog.cc', 'videowidget.cc', 'signalview.cc', + 'streams/routes.cc', 'dbc/dbc.cc', 'dbc/dbcfile.cc', 'dbc/dbcmanager.cc', 'dbc/dbcqt.cc', + 'utils/export.cc', 'utils/util.cc', 'utils/elidedlabel.cc', + 'chart/chartswidget.cc', 'chart/chart.cc', 'chart/signalselector.cc', 'chart/tiplabel.cc', 'chart/sparkline.cc', + 'commands.cc', 'messageswidget.cc', 'streamselector.cc', 'settings.cc', 'panda.cc', + 'cameraview.cc', 'detailwidget.cc', 'tools/findsimilarbits.cc', 'tools/findsignal.cc', 'tools/routeinfo.cc'] +if arch != "Darwin": + cabana_srcs += ['streams/socketcanstream.cc'] +cabana_lib = cabana_env.Library("cabana_lib", cabana_srcs + [bootstrap_icons_src], LIBS=cabana_libs, FRAMEWORKS=base_frameworks) +cabana_env.Program('_cabana', ['cabana.cc', cabana_lib, assets], LIBS=cabana_libs, FRAMEWORKS=base_frameworks) + +if GetOption('extras'): + cabana_env.Program('tests/test_cabana', ['tests/test_runner.cc', 'tests/test_cabana.cc', cabana_lib], LIBS=[cabana_libs]) + + # This target deliberately uses the base environment and links no Qt libraries. + # It prevents Qt dependencies from creeping back into the DBC core. + dbc_core_test_env = env.Clone() + dbc_core_test_env['CXXFLAGS'] += [opendbc_path] + dbc_core_test_objects = [ + dbc_core_test_env.Object('tests/dbc_core_test_runner', 'tests/test_runner.cc'), + dbc_core_test_env.Object('tests/dbc_core_tests', 'tests/test_cabana.cc'), + dbc_core_test_env.Object('tests/dbc_core_model', 'dbc/dbc.cc'), + dbc_core_test_env.Object('tests/dbc_core_file', 'dbc/dbcfile.cc'), + dbc_core_test_env.Object('tests/dbc_core_manager', 'dbc/dbcmanager.cc'), + ] + dbc_core_test_env.Program('tests/test_dbc_core', dbc_core_test_objects) + +output_json_file = 'openpilot/tools/cabana/dbc/car_fingerprint_to_dbc.json' +generate_dbc = cabana_env.Command('#' + output_json_file, + ['dbc/generate_dbc_json.py'], + "python3 openpilot/tools/cabana/dbc/generate_dbc_json.py --out " + output_json_file) +cabana_env.Depends(generate_dbc, ["#openpilot/common", '#opendbc_repo', "#openpilot/cereal", "#msgq_repo"]) diff --git a/openpilot/tools/cabana/assets/assets.qrc b/openpilot/tools/cabana/assets/assets.qrc new file mode 100644 index 0000000000..009d63f008 --- /dev/null +++ b/openpilot/tools/cabana/assets/assets.qrc @@ -0,0 +1,5 @@ + + + cabana-icon.png + + diff --git a/tools/cabana/assets/cabana-icon.png b/openpilot/tools/cabana/assets/cabana-icon.png similarity index 100% rename from tools/cabana/assets/cabana-icon.png rename to openpilot/tools/cabana/assets/cabana-icon.png diff --git a/tools/cabana/binaryview.cc b/openpilot/tools/cabana/binaryview.cc similarity index 88% rename from tools/cabana/binaryview.cc rename to openpilot/tools/cabana/binaryview.cc index eb0af5b64a..5e919dc6a3 100644 --- a/tools/cabana/binaryview.cc +++ b/openpilot/tools/cabana/binaryview.cc @@ -1,8 +1,10 @@ #include "tools/cabana/binaryview.h" +#include "tools/cabana/dbc/dbcqt.h" #include -#include +#include + #include #include #include @@ -34,20 +36,20 @@ BinaryView::BinaryView(QWidget *parent) : QTableView(parent) { setMouseTracking(true); setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - QObject::connect(dbc(), &DBCManager::DBCFileChanged, this, &BinaryView::refresh); - QObject::connect(UndoStack::instance(), &QUndoStack::indexChanged, this, &BinaryView::refresh); + QObject::connect(dbcNotifier(), &QtDBCNotifier::DBCFileChanged, this, &BinaryView::refresh); + QObject::connect(undoNotifier(), &QtUndoNotifier::indexChanged, this, &BinaryView::refresh); addShortcuts(); setWhatsThis(R"( Binary View
- + Shortcuts
Delete Signal:  x ,  Backspace ,  Delete 
Change endianness:  e 
- Change singedness:  s 
+ Change signedness:  s 
Open chart:  c ,  p , @@ -64,7 +66,7 @@ void BinaryView::addShortcuts() { QObject::connect(shortcut_delete_backspace, &QShortcut::activated, shortcut_delete_x, &QShortcut::activated); QObject::connect(shortcut_delete_x, &QShortcut::activated, [=]{ if (hovered_sig != nullptr) { - UndoStack::push(new RemoveSigCommand(model->msg_id, hovered_sig)); + UndoStack::instance()->push(new RemoveSigCommand(model->msg_id, hovered_sig)); hovered_sig = nullptr; } }); @@ -111,7 +113,8 @@ void BinaryView::highlight(const cabana::Signal *sig) { if (sig != hovered_sig) { for (int i = 0; i < model->items.size(); ++i) { auto &item_sigs = model->items[i].sigs; - if ((sig && item_sigs.contains(sig)) || (hovered_sig && item_sigs.contains(hovered_sig))) { + auto has = [](const auto &v, auto p) { return std::find(v.begin(), v.end(), p) != v.end(); }; + if ((sig && has(item_sigs, sig)) || (hovered_sig && has(item_sigs, hovered_sig))) { auto index = model->index(i / model->columnCount(), i % model->columnCount()); emit model->dataChanged(index, index, {Qt::DisplayRole}); } @@ -123,7 +126,7 @@ void BinaryView::highlight(const cabana::Signal *sig) { } void BinaryView::setSelection(const QRect &rect, QItemSelectionModel::SelectionFlags flags) { - auto index = indexAt(viewport()->mapFromGlobal(QCursor::pos())); + auto index = indexAt(last_mouse_pos); if (!anchor_index.isValid() || !index.isValid()) return; @@ -138,7 +141,7 @@ void BinaryView::setSelection(const QRect &rect, QItemSelectionModel::SelectionF void BinaryView::mousePressEvent(QMouseEvent *event) { resize_sig = nullptr; - if (auto index = indexAt(event->pos()); index.isValid() && index.column() != 8) { + if (auto index = indexAt(last_mouse_pos = event->pos()); index.isValid() && index.column() != 8) { anchor_index = index; auto item = (const BinaryViewModel::Item *)anchor_index.internalPointer(); int bit_pos = get_bit_pos(anchor_index); @@ -155,15 +158,15 @@ void BinaryView::mousePressEvent(QMouseEvent *event) { } void BinaryView::highlightPosition(const QPoint &pos) { - if (auto index = indexAt(viewport()->mapFromGlobal(pos)); index.isValid()) { + if (auto index = indexAt(pos); index.isValid()) { auto item = (BinaryViewModel::Item *)index.internalPointer(); - const cabana::Signal *sig = item->sigs.isEmpty() ? nullptr : item->sigs.back(); + const cabana::Signal *sig = item->sigs.empty() ? nullptr : item->sigs.back(); highlight(sig); } } void BinaryView::mouseMoveEvent(QMouseEvent *event) { - highlightPosition(event->globalPos()); + highlightPosition(last_mouse_pos = event->pos()); QTableView::mouseMoveEvent(event); } @@ -176,7 +179,7 @@ void BinaryView::mouseReleaseEvent(QMouseEvent *event) { auto sig = resize_sig ? *resize_sig : cabana::Signal{}; std::tie(sig.start_bit, sig.size, sig.is_little_endian) = getSelection(release_index); resize_sig ? emit editSignal(resize_sig, sig) - : UndoStack::push(new AddSigCommand(model->msg_id, sig)); + : UndoStack::instance()->push(new AddSigCommand(model->msg_id, sig)); } else { auto item = (const BinaryViewModel::Item *)anchor_index.internalPointer(); if (item && item->sigs.size() > 0) @@ -205,15 +208,15 @@ void BinaryView::refresh() { resize_sig = nullptr; hovered_sig = nullptr; model->refresh(); - highlightPosition(QCursor::pos()); + if (underMouse()) highlightPosition(last_mouse_pos); } -QSet BinaryView::getOverlappingSignals() const { - QSet overlapping; +std::set BinaryView::getOverlappingSignals() const { + std::set overlapping; for (const auto &item : model->items) { if (item.sigs.size() > 1) { for (auto s : item.sigs) { - if (s->type == cabana::Signal::Type::Normal) overlapping += s; + if (s->type == cabana::Signal::Type::Normal) overlapping.insert(s); } } } @@ -258,7 +261,8 @@ void BinaryViewModel::refresh() { int pos = sig->is_little_endian ? flipBitPos(sig->start_bit + j) : flipBitPos(sig->start_bit) + j; int idx = column_count * (pos / 8) + pos % 8; if (idx >= items.size()) { - qWarning() << "signal " << sig->name << "out of bounds.start_bit:" << sig->start_bit << "size:" << sig->size; + fprintf(stderr, "signal %s out of bounds.start_bit: %d size: %d\n", + sig->name.c_str(), sig->start_bit, sig->size); break; } if (j == 0) sig->is_little_endian ? items[idx].is_lsb = true : items[idx].is_msb = true; @@ -275,16 +279,13 @@ void BinaryViewModel::refresh() { row_count = can->lastMessage(msg_id).dat.size(); items.resize(row_count * column_count); } - int valid_rows = std::min(can->lastMessage(msg_id).dat.size(), row_count); - for (int i = 0; i < valid_rows * column_count; ++i) { - items[i].valid = true; - } endResetModel(); updateState(); } void BinaryViewModel::updateItem(int row, int col, uint8_t val, const QColor &color) { auto &item = items[row * column_count + col]; + item.valid = true; if (item.val != val || item.bg_color != color) { item.val = val; item.bg_color = color; @@ -336,7 +337,7 @@ void BinaryViewModel::updateState() { color.setAlpha(alpha); updateItem(i, j, bit_val, color); } - updateItem(i, 8, binary[i], last_msg.colors[i]); + updateItem(i, 8, binary[i], toQColor(last_msg.colors[i])); } } @@ -407,7 +408,9 @@ bool BinaryItemDelegate::hasSignal(const QModelIndex &index, int dx, int dy, con if (!index.isValid()) return false; auto model = (const BinaryViewModel*)(index.model()); int idx = (index.row() + dy) * model->columnCount() + index.column() + dx; - return (idx >=0 && idx < model->items.size()) ? model->items[idx].sigs.contains(sig) : false; + if (idx < 0 || idx >= (int)model->items.size()) return false; + auto &s = model->items[idx].sigs; + return std::find(s.begin(), s.end(), sig) != s.end(); } void BinaryItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { @@ -421,14 +424,14 @@ void BinaryItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &op painter->fillRect(option.rect, item->bg_color); } } else if (option.state & QStyle::State_Selected) { - auto color = bin_view->resize_sig ? bin_view->resize_sig->color : option.palette.color(QPalette::Active, QPalette::Highlight); + auto color = bin_view->resize_sig ? toQColor(bin_view->resize_sig->color) : option.palette.color(QPalette::Active, QPalette::Highlight); painter->fillRect(option.rect, color); painter->setPen(option.palette.color(QPalette::BrightText)); - } else if (!bin_view->selectionModel()->hasSelection() || !item->sigs.contains(bin_view->resize_sig)) { // not resizing + } else if (!bin_view->selectionModel()->hasSelection() || std::find(item->sigs.begin(), item->sigs.end(), bin_view->resize_sig) == item->sigs.end()) { // not resizing if (item->sigs.size() > 0) { for (auto &s : item->sigs) { if (s == bin_view->hovered_sig) { - painter->fillRect(option.rect, s->color.darker(125)); // 4/5x brightness + painter->fillRect(option.rect, toQColor(s->color.darker(125))); // 4/5x brightness } else { drawSignalCell(painter, option, index, s); } @@ -436,7 +439,7 @@ void BinaryItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &op } else if (item->valid && item->bg_color.alpha() > 0) { painter->fillRect(option.rect, item->bg_color); } - auto color_role = item->sigs.contains(bin_view->hovered_sig) ? QPalette::BrightText : QPalette::Text; + auto color_role = (std::find(item->sigs.begin(), item->sigs.end(), bin_view->hovered_sig) != item->sigs.end()) ? QPalette::BrightText : QPalette::Text; painter->setPen(option.palette.color(bin_view->is_message_active ? QPalette::Normal : QPalette::Disabled, color_role)); } @@ -483,14 +486,14 @@ void BinaryItemDelegate::drawSignalCell(QPainter *painter, const QStyleOptionVie painter->setClipRegion(QRegion(rc).subtracted(subtract)); auto item = (const BinaryViewModel::Item *)index.internalPointer(); - QColor color = sig->color; + QColor color = toQColor(sig->color); color.setAlpha(item->bg_color.alpha()); // Mixing the signal color with the Base background color to fade it painter->fillRect(rc, option.palette.color(QPalette::Base)); painter->fillRect(rc, color); // Draw edges - color = sig->color.darker(125); + color = toQColor(sig->color.darker(125)); painter->setPen(QPen(color, 1)); if (draw_left) painter->drawLine(rc.topLeft(), rc.bottomLeft()); if (draw_right) painter->drawLine(rc.topRight(), rc.bottomRight()); diff --git a/tools/cabana/binaryview.h b/openpilot/tools/cabana/binaryview.h similarity index 95% rename from tools/cabana/binaryview.h rename to openpilot/tools/cabana/binaryview.h index 920deb0018..c49067a1a2 100644 --- a/tools/cabana/binaryview.h +++ b/openpilot/tools/cabana/binaryview.h @@ -1,10 +1,9 @@ #pragma once +#include #include #include -#include -#include #include #include @@ -51,7 +50,7 @@ public: bool is_msb = false; bool is_lsb = false; uint8_t val; - QList sigs; + std::vector sigs; bool valid = false; }; std::vector items; @@ -68,7 +67,7 @@ public: BinaryView(QWidget *parent = nullptr); void setMessage(const MessageId &message_id); void highlight(const cabana::Signal *sig); - QSet getOverlappingSignals() const; + std::set getOverlappingSignals() const; void updateState() { model->updateState(); } void paintEvent(QPaintEvent *event) override { is_message_active = can->isMessageActive(model->msg_id); @@ -95,6 +94,7 @@ private: void highlightPosition(const QPoint &pt); QModelIndex anchor_index; + QPoint last_mouse_pos{-1, -1}; BinaryViewModel *model; BinaryItemDelegate *delegate; bool is_message_active = false; diff --git a/openpilot/tools/cabana/cabana b/openpilot/tools/cabana/cabana new file mode 100755 index 0000000000..db613b5391 --- /dev/null +++ b/openpilot/tools/cabana/cabana @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +set -e + +DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )" +ROOT="$(cd "$DIR/../../../" && pwd)" + +install_qt() { + if [[ "$(uname)" == "Darwin" ]]; then + brew install qt@5 + brew link qt@5 || true + else + SUDO="" + if [[ ! $(id -u) -eq 0 ]]; then + SUDO="sudo" + fi + $SUDO apt-get install -y --no-install-recommends \ + qtbase5-dev \ + qtbase5-dev-tools \ + qttools5-dev-tools \ + libqt5charts5-dev \ + libqt5svg5-dev \ + libqt5serialbus5-dev \ + libqt5x11extras5-dev \ + libqt5opengl5-dev + fi +} + +# Install Qt if not found +if ! command -v qmake &> /dev/null; then + echo "Qt not found, installing dependencies..." + install_qt +fi + +# Build _cabana +cd "$ROOT" +scons -u openpilot/tools/cabana/_cabana openpilot/cereal/messaging/bridge + +exec "$DIR/_cabana" "$@" diff --git a/openpilot/tools/cabana/cabana.cc b/openpilot/tools/cabana/cabana.cc new file mode 100644 index 0000000000..d8e21815dc --- /dev/null +++ b/openpilot/tools/cabana/cabana.cc @@ -0,0 +1,187 @@ +#include +#include +#include +#include + +#include + +#include "tools/cabana/mainwin.h" +#include "tools/cabana/streams/devicestream.h" +#include "tools/cabana/streams/pandastream.h" +#include "tools/cabana/streams/replaystream.h" +#ifdef __linux__ +#include "tools/cabana/streams/socketcanstream.h" +#endif + +namespace { + +struct CabanaArgs { + bool demo = false; + bool auto_source = false; + bool qcam = false; + bool ecam = false; + bool dcam = false; + bool msgq = false; + bool panda = false; + bool no_vipc = false; + std::string panda_serial; + std::string socketcan; + std::string zmq; + std::string data_dir; + std::string dbc; + std::string route; +}; + +void printUsage(const char *argv0) { + fprintf(stderr, + "Usage: %s [options] [route]\n" + "\n" + " route the drive to replay. find your drives at connect.comma.ai\n" + "\n" + "Options:\n" + " --help show this help\n" + " --demo use a demo route instead of providing your own\n" + " --auto Auto load the route from the best available source (no video):\n" + " internal, openpilotci, comma_api, car_segments, testing_closet\n" + " --qcam load qcamera\n" + " --ecam load wide road camera\n" + " --dcam load driver camera\n" + " --msgq read can messages from the msgq\n" + " --panda read can messages from panda\n" + " --panda-serial read can messages from panda with given serial\n" +#ifdef __linux__ + " --socketcan read can messages from given SocketCAN device\n" +#endif + " --zmq read can messages from zmq at the specified ip-address\n" + " --data_dir

local directory with routes\n" + " --no-vipc do not output video\n" + " --dbc dbc file to open\n", + argv0); +} + +// Returns true if value was consumed from argv[i+1]. +bool takeValue(int argc, char *argv[], int &i, std::string &out) { + if (i + 1 >= argc) { + fprintf(stderr, "error: %s requires a value\n", argv[i]); + return false; + } + out = argv[++i]; + return true; +} + +// Returns 0 to continue, or a process exit code (0 for --help, 1 for errors). +int parseArgs(int argc, char *argv[], CabanaArgs &args, bool &ok) { + ok = false; + for (int i = 1; i < argc; ++i) { + const char *a = argv[i]; + if (std::strcmp(a, "--help") == 0 || std::strcmp(a, "-h") == 0) { + printUsage(argv[0]); + return 0; + } else if (std::strcmp(a, "--demo") == 0) { + args.demo = true; + } else if (std::strcmp(a, "--auto") == 0) { + args.auto_source = true; + } else if (std::strcmp(a, "--qcam") == 0) { + args.qcam = true; + } else if (std::strcmp(a, "--ecam") == 0) { + args.ecam = true; + } else if (std::strcmp(a, "--dcam") == 0) { + args.dcam = true; + } else if (std::strcmp(a, "--msgq") == 0) { + args.msgq = true; + } else if (std::strcmp(a, "--panda") == 0) { + args.panda = true; + } else if (std::strcmp(a, "--panda-serial") == 0) { + if (!takeValue(argc, argv, i, args.panda_serial)) return 1; + args.panda = true; + } else if (std::strcmp(a, "--socketcan") == 0) { + if (!takeValue(argc, argv, i, args.socketcan)) return 1; +#ifdef __linux__ +#else + fprintf(stderr, "error: --socketcan is only supported on Linux\n"); + return 1; +#endif + } else if (std::strcmp(a, "--zmq") == 0) { + if (!takeValue(argc, argv, i, args.zmq)) return 1; + } else if (std::strcmp(a, "--data_dir") == 0) { + if (!takeValue(argc, argv, i, args.data_dir)) return 1; + } else if (std::strcmp(a, "--no-vipc") == 0) { + args.no_vipc = true; + } else if (std::strcmp(a, "--dbc") == 0) { + if (!takeValue(argc, argv, i, args.dbc)) return 1; + } else if (a[0] == '-') { + fprintf(stderr, "error: unknown option %s\n", a); + printUsage(argv[0]); + return 1; + } else if (args.route.empty()) { + args.route = a; + } else { + fprintf(stderr, "error: unexpected argument %s\n", a); + printUsage(argv[0]); + return 1; + } + } + ok = true; + return 0; +} + +} // namespace + +int main(int argc, char *argv[]) { + QCoreApplication::setApplicationName("Cabana"); + initApp(argc, argv, false); + QApplication app(argc, argv); + app.setApplicationDisplayName("Cabana"); + //app.setWindowIcon(QIcon(":cabana-icon.png")); // TODO: do this in imgui + + UnixSignalHandler signalHandler; + utils::setTheme(settings.theme); + + CabanaArgs args; + bool args_ok = false; + if (const int code = parseArgs(argc, argv, args, args_ok); !args_ok) { + return code; + } + + AbstractStream *stream = nullptr; + + if (args.msgq) { + stream = new DeviceStream(&app); + } else if (!args.zmq.empty()) { + stream = new DeviceStream(&app, QString::fromStdString(args.zmq)); + } else if (args.panda || !args.panda_serial.empty()) { + try { + stream = new PandaStream(&app, {.serial = args.panda_serial}); + } catch (std::exception &e) { + fprintf(stderr, "%s\n", e.what()); + return 0; + } +#ifdef __linux__ + } else if (SocketCanStream::available() && !args.socketcan.empty()) { + stream = new SocketCanStream(&app, {.device = args.socketcan}); +#endif + } else { + uint32_t replay_flags = REPLAY_FLAG_NONE; + if (args.ecam) replay_flags |= REPLAY_FLAG_ECAM; + if (args.qcam) replay_flags |= REPLAY_FLAG_QCAMERA; + if (args.dcam) replay_flags |= REPLAY_FLAG_DCAM; + if (args.no_vipc) replay_flags |= REPLAY_FLAG_NO_VIPC; + + QString route; + if (!args.route.empty()) { + route = QString::fromStdString(args.route); + } else if (args.demo) { + route = DEMO_ROUTE; + } + if (!route.isEmpty()) { + auto replay_stream = std::make_unique(&app); + if (!replay_stream->loadRoute(route.toStdString(), args.data_dir, replay_flags, args.auto_source)) { + return 0; + } + stream = replay_stream.release(); + } + } + + MainWindow w(stream, QString::fromStdString(args.dbc)); + return app.exec(); +} diff --git a/openpilot/tools/cabana/cameraview.cc b/openpilot/tools/cabana/cameraview.cc new file mode 100644 index 0000000000..a8df373dc4 --- /dev/null +++ b/openpilot/tools/cabana/cameraview.cc @@ -0,0 +1,125 @@ +#include "tools/cabana/cameraview.h" + +#include +#include +#include +#include + +#include +#include + +#include "common/yuv.h" + +CameraWidget::CameraWidget(std::string stream_name, VisionStreamType type, QWidget* parent) : + stream_name(stream_name), active_stream_type(type), requested_stream_type(type), QWidget(parent) { + setAttribute(Qt::WA_OpaquePaintEvent); + qRegisterMetaType>("availableStreams"); + QObject::connect(this, &CameraWidget::vipcThreadFrameReceived, this, &CameraWidget::vipcFrameReceived, Qt::QueuedConnection); + QObject::connect(this, &CameraWidget::vipcAvailableStreamsUpdated, this, &CameraWidget::availableStreamsUpdated, Qt::QueuedConnection); + QObject::connect(QApplication::instance(), &QCoreApplication::aboutToQuit, this, &CameraWidget::stopVipcThread); +} + +CameraWidget::~CameraWidget() { + stopVipcThread(); +} + +void CameraWidget::showEvent(QShowEvent *event) { + if (!vipc_thread.joinable()) { + clearFrames(); + vipc_exit = false; + vipc_thread = std::thread(&CameraWidget::vipcThread, this); + } +} + +void CameraWidget::stopVipcThread() { + vipc_exit = true; + if (vipc_thread.joinable()) { + vipc_thread.join(); + } +} + +void CameraWidget::availableStreamsUpdated(std::set streams) { + available_streams = streams; +} + +void CameraWidget::paintEvent(QPaintEvent *event) { + QPainter p(this); + p.fillRect(rect(), bg); + + std::lock_guard lk(frame_lock); + if (rgb_frame.isNull()) return; + + // Scale for aspect ratio + float widget_ratio = (float)width() / height(); + float frame_ratio = (float)rgb_frame.width() / rgb_frame.height(); + int w = std::lround(width() * std::min(frame_ratio / widget_ratio, 1.0f)); + int h = std::lround(height() * std::min(widget_ratio / frame_ratio, 1.0f)); + QRect video_rect((width() - w) / 2, (height() - h) / 2, w, h); + + p.setRenderHint(QPainter::SmoothPixmapTransform); + if (active_stream_type == VISION_STREAM_DRIVER) { + // mirror driver camera horizontally + const qreal cx = video_rect.x() + video_rect.width() / 2.0; + p.translate(cx, 0); + p.scale(-1, 1); + p.translate(-cx, 0); + } + p.drawImage(video_rect, rgb_frame); +} + +void CameraWidget::vipcFrameReceived() { + update(); +} + +void CameraWidget::vipcThread() { + VisionStreamType cur_stream = requested_stream_type; + std::unique_ptr vipc_client; + VisionIpcBufExtra frame_meta = {}; + + while (!vipc_exit) { + if (!vipc_client || cur_stream != requested_stream_type) { + clearFrames(); + fprintf(stderr, "connecting to stream %d, was connected to %d\n", + (int)requested_stream_type, (int)cur_stream); + cur_stream = requested_stream_type; + vipc_client.reset(new VisionIpcClient(stream_name, cur_stream, false)); + } + active_stream_type = cur_stream; + + if (!vipc_client->connected) { + clearFrames(); + auto streams = VisionIpcClient::getAvailableStreams(stream_name, false); + if (streams.empty()) { + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + continue; + } + emit vipcAvailableStreamsUpdated(streams); + + if (!vipc_client->connect(false)) { + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + continue; + } + } + + if (VisionBuf *buf = vipc_client->recv(&frame_meta, 100)) { + // NV12 -> RGBA once per frame on the receive thread; paint just draws the image + if (rgb_back.width() != (int)buf->width || rgb_back.height() != (int)buf->height) { + rgb_back = QImage(buf->width, buf->height, QImage::Format_RGBA8888); + } + yuv::nv12_to_rgba(buf->y, buf->stride, buf->uv, buf->stride, + rgb_back.bits(), rgb_back.bytesPerLine(), buf->width, buf->height); + { + std::lock_guard lk(frame_lock); + rgb_frame.swap(rgb_back); + } + emit vipcThreadFrameReceived(); + } + } +} + +void CameraWidget::clearFrames() { + std::lock_guard lk(frame_lock); + rgb_frame = QImage(); + rgb_back = QImage(); + available_streams.clear(); +} diff --git a/openpilot/tools/cabana/cameraview.h b/openpilot/tools/cabana/cameraview.h new file mode 100644 index 0000000000..40d3776005 --- /dev/null +++ b/openpilot/tools/cabana/cameraview.h @@ -0,0 +1,55 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "msgq/visionipc/visionipc_client.h" + +class CameraWidget : public QWidget { + Q_OBJECT + +public: + explicit CameraWidget(std::string stream_name, VisionStreamType stream_type, QWidget* parent = nullptr); + ~CameraWidget(); + void setStreamType(VisionStreamType type) { requested_stream_type = type; } + VisionStreamType getStreamType() { return active_stream_type; } + void stopVipcThread(); + +signals: + void clicked(); + void vipcThreadFrameReceived(); + void vipcAvailableStreamsUpdated(std::set); + +protected: + void paintEvent(QPaintEvent *event) override; + void showEvent(QShowEvent *event) override; + void hideEvent(QHideEvent *event) override { stopVipcThread(); } + void mouseReleaseEvent(QMouseEvent *event) override { emit clicked(); } + void vipcThread(); + void clearFrames(); + + QColor bg = Qt::black; + QImage rgb_frame; // written by vipc thread, drawn by GUI thread; guarded by frame_lock + QImage rgb_back; // vipc thread only + + std::string stream_name; + std::atomic active_stream_type; + std::atomic requested_stream_type; + std::set available_streams; + std::thread vipc_thread; + std::atomic vipc_exit = false; + std::mutex frame_lock; + +protected slots: + void vipcFrameReceived(); + void availableStreamsUpdated(std::set streams); +}; + +Q_DECLARE_METATYPE(std::set); diff --git a/openpilot/tools/cabana/chart/chart.cc b/openpilot/tools/cabana/chart/chart.cc new file mode 100644 index 0000000000..8496c26994 --- /dev/null +++ b/openpilot/tools/cabana/chart/chart.cc @@ -0,0 +1,770 @@ +#include "tools/cabana/chart/chart.h" +#include "tools/cabana/dbc/dbcqt.h" + +#include +#include +#include + +#include +#include +#include +#include + +#include "tools/cabana/chart/chartswidget.h" + +const int AXIS_X_TOP_MARGIN = 4; +const int X_TICK_COUNT = 5; +const double MIN_ZOOM_SECONDS = 0.01; // 10ms +// Define a small value of epsilon to compare double values +const float EPSILON = 0.000001; +static inline bool xLessThan(const QPointF &p, float x) { return p.x() < (x - EPSILON); } + +static QMargins layoutMargins(const QStyle *style) { + return { + style->pixelMetric(QStyle::PM_LayoutLeftMargin), + style->pixelMetric(QStyle::PM_LayoutTopMargin), + style->pixelMetric(QStyle::PM_LayoutRightMargin), + style->pixelMetric(QStyle::PM_LayoutBottomMargin), + }; +} + +ChartView::ChartView(const std::pair &x_range, ChartsWidget *parent) + : x_min(x_range.first), x_max(x_range.second), charts_widget(parent), QWidget(parent) { + series_type = (SeriesType)settings.chart_series_type; + align_to = 50; + setMouseTracking(true); + tip_label = new TipLabel(this); + createToolButtons(); + signal_value_font.setPointSize(9); + + QObject::connect(dbcNotifier(), &QtDBCNotifier::signalRemoved, this, &ChartView::signalRemoved); + QObject::connect(dbcNotifier(), &QtDBCNotifier::signalUpdated, this, &ChartView::signalUpdated); + QObject::connect(dbcNotifier(), &QtDBCNotifier::msgRemoved, this, &ChartView::msgRemoved); + QObject::connect(dbcNotifier(), &QtDBCNotifier::msgUpdated, this, &ChartView::msgUpdated); +} + +void ChartView::createToolButtons() { + close_btn = new ToolButton("x", tr("Remove Chart"), this); + + menu = new QMenu(this); + // series types + auto change_series_group = new QActionGroup(menu); + change_series_group->setExclusive(true); + QStringList types{tr("Line"), tr("Step Line"), tr("Scatter")}; + for (int i = 0; i < types.size(); ++i) { + QAction *act = new QAction(types[i], change_series_group); + act->setData(i); + act->setCheckable(true); + act->setChecked(i == (int)series_type); + menu->addAction(act); + } + menu->addSeparator(); + menu->addAction(tr("Manage Signals"), this, &ChartView::manageSignals); + split_chart_act = menu->addAction(tr("Split Chart"), [this]() { charts_widget->splitChart(this); }); + + manage_btn = new ToolButton("list", "", this); + manage_btn->setMenu(menu); + manage_btn->setPopupMode(QToolButton::InstantPopup); + manage_btn->setStyleSheet("QToolButton::menu-indicator { image: none; }"); + + close_act = new QAction(tr("Close"), this); + QObject::connect(close_act, &QAction::triggered, [this] () { charts_widget->removeChart(this); }); + QObject::connect(close_btn, &QToolButton::clicked, close_act, &QAction::triggered); + QObject::connect(change_series_group, &QActionGroup::triggered, [this](QAction *action) { + setSeriesType((SeriesType)action->data().toInt()); + }); +} + +QSize ChartView::sizeHint() const { + return {CHART_MIN_WIDTH, settings.chart_height}; +} + +void ChartView::addSignal(const MessageId &msg_id, const cabana::Signal *sig) { + if (hasSignal(msg_id, sig)) return; + + sigs.push_back({.msg_id = msg_id, .sig = sig, .color = uniqueColor(toQColor(sig->color))}); + updateSeries(sig); + updateTitle(); + emit charts_widget->seriesChanged(); +} + +bool ChartView::hasSignal(const MessageId &msg_id, const cabana::Signal *sig) const { + return std::any_of(sigs.cbegin(), sigs.cend(), [&](auto &s) { return s.msg_id == msg_id && s.sig == sig; }); +} + +void ChartView::removeIf(std::function predicate) { + int prev_size = sigs.size(); + sigs.erase(std::remove_if(sigs.begin(), sigs.end(), predicate), sigs.end()); + if (sigs.empty()) { + charts_widget->removeChart(this); + } else if (sigs.size() != prev_size) { + emit charts_widget->seriesChanged(); + updateAxisY(); + updateTitle(); + } +} + +void ChartView::signalUpdated(const cabana::Signal *sig) { + auto it = std::find_if(sigs.begin(), sigs.end(), [sig](auto &s) { return s.sig == sig; }); + if (it != sigs.end()) { + if (it->color != toQColor(sig->color)) { + it->color = uniqueColor(toQColor(sig->color), sig); + } + updateTitle(); + updateSeries(sig); + } +} + +void ChartView::msgUpdated(MessageId id) { + if (std::any_of(sigs.cbegin(), sigs.cend(), [=](auto &s) { return s.msg_id.address == id.address; })) { + updateTitle(); + } +} + +void ChartView::manageSignals() { + SignalSelector dlg(tr("Manage Chart"), this); + for (auto &s : sigs) { + dlg.addSelected(s.msg_id, s.sig); + } + if (dlg.exec() == QDialog::Accepted) { + auto items = dlg.seletedItems(); + for (auto s : items) { + addSignal(s->msg_id, s->sig); + } + removeIf([&](auto &s) { + return std::none_of(items.cbegin(), items.cend(), [&](auto &it) { return s.msg_id == it->msg_id && s.sig == it->sig; }); + }); + } +} + +void ChartView::resizeEvent(QResizeEvent *event) { + QWidget::resizeEvent(event); + const auto margins = layoutMargins(style()); + QPixmap grip = utils::icon("grip-horizontal"); + move_icon_rect = QRect(QPoint(margins.left(), margins.top()), grip.size() / grip.devicePixelRatio()); + close_btn->resize(close_btn->sizeHint()); + manage_btn->resize(manage_btn->sizeHint()); + close_btn->move(rect().right() - margins.right() - close_btn->width(), margins.top()); + manage_btn->move(close_btn->x() - manage_btn->width() - style()->pixelMetric(QStyle::PM_LayoutHorizontalSpacing), margins.top()); + updatePlotArea(align_to, true); +} + +void ChartView::updatePlotArea(int left_pos, bool force) { + if (align_to != left_pos || force) { + align_to = left_pos; + + const auto margins = layoutMargins(style()); + QFont bold_font = font(); + bold_font.setBold(true); + QFontMetrics fm(font()), bfm(bold_font); + const int marker_size = fm.height() - 4; + const int row_height = std::max(marker_size, fm.height()) + QFontMetrics(signal_value_font).height() + 3; + const int legend_left = move_icon_rect.right() + margins.left(); + const int legend_right = std::max(manage_btn->x() - margins.right(), legend_left + 10); + + // layout legend entries left-to-right, wrapping between the move icon and the buttons + legend_rects.clear(); + int x = legend_left, y = margins.top(); + for (auto &s : sigs) { + int w = marker_size + 5 + bfm.horizontalAdvance(QString::fromStdString(s.sig->name)) + + fm.horizontalAdvance(QString::fromStdString(" " + msgName(s.msg_id) + " " + s.msg_id.toString())); + w = std::min(w, legend_right - legend_left); // keep oversized entries clear of the header buttons + if (x + w > legend_right && x > legend_left) { + x = legend_left; + y += row_height; + } + legend_rects.emplace_back(x, y, w, std::max(marker_size, fm.height())); + x += w + 12; + } + + // add top space for the legend and signal values + int adjust_top = (y + row_height) - margins.top(); + adjust_top = std::max(adjust_top, manage_btn->geometry().bottom() + style()->pixelMetric(QStyle::PM_LayoutTopMargin)); + // add right space for x-axis label + QSizeF x_label_size = fm.size(Qt::TextSingleLine, QString::number(x_max, 'f', xAxisPrecision())) + QSizeF{5, 5}; + plot_area = rect().adjusted(align_to + margins.left(), adjust_top + margins.top(), + -x_label_size.width() / 2 - margins.right(), + -x_label_size.height() - margins.bottom()); + resetChartCache(); + } +} + +void ChartView::updateTitle() { + split_chart_act->setEnabled(sigs.size() > 1); + updatePlotArea(align_to, true); +} + +void ChartView::updatePlot(double cur, double min, double max) { + cur_sec = cur; + if (min != x_min || max != x_max) { + x_min = min; + x_max = max; + updateAxisY(); + // update tooltip + if (tooltip_x >= 0) { + showTip(secondsAtPoint({tooltip_x, 0})); + } + resetChartCache(); + } + update(); +} + +void ChartView::appendCanEvents(const cabana::Signal *sig, const std::vector &events, + std::vector &vals, std::vector &step_vals) { + vals.reserve(vals.size() + events.capacity()); + step_vals.reserve(step_vals.size() + events.capacity() * 2); + + double value = 0; + for (const CanEvent *e : events) { + if (sig->getValue(e->dat, e->size, &value)) { + const double ts = can->toSeconds(e->mono_time); + vals.emplace_back(ts, value); + if (!step_vals.empty()) + step_vals.emplace_back(ts, step_vals.back().y()); + step_vals.emplace_back(ts, value); + } + } +} + +void ChartView::updateSeries(const cabana::Signal *sig, const MessageEventsMap *msg_new_events) { + for (auto &s : sigs) { + if (!sig || s.sig == sig) { + if (!msg_new_events) { + s.vals.clear(); + s.step_vals.clear(); + } + auto events = msg_new_events ? msg_new_events : &can->eventsMap(); + auto it = events->find(s.msg_id); + if (it == events->end() || it->second.empty()) continue; + + if (s.vals.empty() || can->toSeconds(it->second.back()->mono_time) > s.vals.back().x()) { + appendCanEvents(s.sig, it->second, s.vals, s.step_vals); + } else { + std::vector vals, step_vals; + appendCanEvents(s.sig, it->second, vals, step_vals); + s.vals.insert(std::lower_bound(s.vals.begin(), s.vals.end(), vals.front().x(), xLessThan), + vals.begin(), vals.end()); + s.step_vals.insert(std::lower_bound(s.step_vals.begin(), s.step_vals.end(), step_vals.front().x(), xLessThan), + step_vals.begin(), step_vals.end()); + } + + if (!can->liveStreaming()) { + s.segment_tree.build(s.vals); + } + } + } + updateAxisY(); + // invoke resetChartCache in ui thread + QMetaObject::invokeMethod(this, &ChartView::resetChartCache, Qt::QueuedConnection); +} + +// auto zoom on yaxis +void ChartView::updateAxisY() { + if (sigs.empty()) return; + + double min = std::numeric_limits::max(); + double max = std::numeric_limits::lowest(); + QString unit = QString::fromStdString(sigs[0].sig->unit); + + for (auto &s : sigs) { + if (!s.visible) continue; + + // Only show unit when all signals have the same unit + if (unit != QString::fromStdString(s.sig->unit)) { + unit.clear(); + } + + auto first = std::lower_bound(s.vals.cbegin(), s.vals.cend(), x_min, xLessThan); + auto last = std::lower_bound(first, s.vals.cend(), x_max, xLessThan); + s.min = std::numeric_limits::max(); + s.max = std::numeric_limits::lowest(); + if (can->liveStreaming()) { + for (auto it = first; it != last; ++it) { + if (it->y() < s.min) s.min = it->y(); + if (it->y() > s.max) s.max = it->y(); + } + } else { + std::tie(s.min, s.max) = s.segment_tree.minmax(std::distance(s.vals.cbegin(), first), std::distance(s.vals.cbegin(), last)); + } + min = std::min(min, s.min); + max = std::max(max, s.max); + } + if (min == std::numeric_limits::max()) min = 0; + if (max == std::numeric_limits::lowest()) max = 0; + + if (y_unit != unit) { + y_unit = unit; + y_label_width = 0; // recalc width + } + + double delta = std::abs(max - min) < 1e-3 ? 1 : (max - min) * 0.05; + auto [min_y, max_y, tick_count] = getNiceAxisNumbers(min - delta, max + delta, 3); + if (min_y != y_min || max_y != y_max || y_label_width == 0) { + y_min = min_y; + y_max = max_y; + y_tick_count = tick_count; + y_precision = std::max(int(-std::floor(std::log10((max_y - min_y) / (tick_count - 1)))), 0); + + QFontMetrics fm(font()); + int max_label_width = 0; + for (int i = 0; i < tick_count; i++) { + qreal value = min_y + (i * (max_y - min_y) / (tick_count - 1)); + max_label_width = std::max(max_label_width, fm.horizontalAdvance(QString::number(value, 'f', y_precision))); + } + + int title_spacing = y_unit.isEmpty() ? 0 : fm.size(Qt::TextSingleLine, y_unit).height(); + y_label_width = title_spacing + max_label_width + 15; + emit axisYLabelWidthChanged(y_label_width); + } +} + +std::tuple ChartView::getNiceAxisNumbers(qreal min, qreal max, int tick_count) { + qreal range = niceNumber((max - min), true); // range with ceiling + qreal step = niceNumber(range / (tick_count - 1), false); + min = std::floor(min / step); + max = std::ceil(max / step); + tick_count = int(max - min) + 1; + return {min * step, max * step, tick_count}; +} + +int ChartView::xAxisPrecision() const { + return std::max(int(-std::floor(std::log10((x_max - x_min) / (X_TICK_COUNT - 1)))), 2); +} + +// nice numbers can be expressed as form of 1*10^n, 2* 10^n or 5*10^n +qreal ChartView::niceNumber(qreal x, bool ceiling) { + qreal z = std::pow(10, std::floor(std::log10(x))); //find corresponding number of the form of 10^n than is smaller than x + qreal q = x / z; //q<10 && q>=1; + if (ceiling) { + if (q <= 1.0) q = 1; + else if (q <= 2.0) q = 2; + else if (q <= 5.0) q = 5; + else q = 10; + } else { + if (q < 1.5) q = 1; + else if (q < 3.0) q = 2; + else if (q < 7.0) q = 5; + else q = 10; + } + return q * z; +} + +void ChartView::contextMenuEvent(QContextMenuEvent *event) { + QMenu context_menu(this); + context_menu.addActions(menu->actions()); + context_menu.addSeparator(); + context_menu.addAction(charts_widget->undo_zoom_action); + context_menu.addAction(charts_widget->redo_zoom_action); + context_menu.addSeparator(); + context_menu.addAction(close_act); + context_menu.exec(event->globalPos()); +} + +void ChartView::mousePressEvent(QMouseEvent *event) { + press_pos = event->pos(); + if (event->button() == Qt::LeftButton && move_icon_rect.contains(event->pos())) { + charts_widget->startChartDrag(this, event->globalPos()); + } else if (event->button() == Qt::LeftButton && event->modifiers().testFlag(Qt::ShiftModifier)) { + // Save current playback state when scrubbing + resume_after_scrub = !can->isPaused(); + if (resume_after_scrub) { + can->pause(true); + } + mouse_mode = MouseMode::Scrub; + } else if (event->button() == Qt::LeftButton && plot_area.contains(event->pos())) { + mouse_mode = MouseMode::Rubber; + rubber_rect = QRect(); + } else { + QWidget::mousePressEvent(event); + } +} + +void ChartView::mouseMoveEvent(QMouseEvent *ev) { + // Scrubbing + if (mouse_mode == MouseMode::Scrub && ev->modifiers().testFlag(Qt::ShiftModifier)) { + if (plot_area.contains(ev->pos())) { + can->seekTo(std::clamp(secondsAtPoint(ev->pos()), can->minSeconds(), can->maxSeconds())); + } + } + + if (mouse_mode == MouseMode::Rubber) { + // horizontal selection, clamped to the plot area + int left = std::clamp(std::min(press_pos.x(), ev->pos().x()), plot_area.left(), plot_area.right()); + int right = std::clamp(std::max(press_pos.x(), ev->pos().x()), plot_area.left(), plot_area.right()); + rubber_rect = QRect(left, plot_area.top(), right - left, plot_area.height()); + update(); + } + + clearTrackPoints(); + if (mouse_mode != MouseMode::Rubber && plot_area.contains(ev->pos()) && isActiveWindow()) { + charts_widget->showValueTip(secondsAtPoint(ev->pos())); + } else if (tip_label->isVisible()) { + charts_widget->showValueTip(-1); + } + QWidget::mouseMoveEvent(ev); +} + +void ChartView::mouseReleaseEvent(QMouseEvent *event) { + if (event->button() == Qt::LeftButton && mouse_mode == MouseMode::Rubber) { + mouse_mode = MouseMode::None; + // Prevent zooming/seeking past the end of the route + double min = std::clamp(secondsAtPoint(rubber_rect.topLeft()), can->minSeconds(), can->maxSeconds()); + double max = std::clamp(secondsAtPoint(rubber_rect.bottomRight()), can->minSeconds(), can->maxSeconds()); + if (rubber_rect.width() <= 0) { + // no rubber dragged, seek to mouse position + can->seekTo(std::clamp(secondsAtPoint(press_pos), can->minSeconds(), can->maxSeconds())); + } else if (rubber_rect.width() > 10 && (max - min) > MIN_ZOOM_SECONDS) { + charts_widget->zoom_undo_stack.push(new ZoomCommand({min, max})); + } + rubber_rect = QRect(); + update(); + } else if (event->button() == Qt::LeftButton && mouse_mode == MouseMode::None && sigs.size() > 1) { + // toggle series visibility by clicking its legend entry + for (int i = 0; i < sigs.size() && i < legend_rects.size(); ++i) { + if (legend_rects[i].contains(press_pos) && legend_rects[i].contains(event->pos())) { + sigs[i].visible = !sigs[i].visible; + updateAxisY(); + updateTitle(); + break; + } + } + } else if (event->button() == Qt::RightButton) { + charts_widget->zoom_undo_stack.undo(); + } else { + QWidget::mouseReleaseEvent(event); + } + + // Resume playback if we were scrubbing + if (mouse_mode == MouseMode::Scrub) { + mouse_mode = MouseMode::None; + if (resume_after_scrub) { + can->pause(false); + resume_after_scrub = false; + } + } +} + +void ChartView::takeSignalsFrom(ChartView *source) { + for (auto &s : source->sigs) { + sigs.push_back(std::move(s)); + sigs.back().color = uniqueColor(sigs.back().color, sigs.back().sig); + } + source->sigs.clear(); + updateAxisY(); + updateTitle(); + charts_widget->removeChart(source); +} + +void ChartView::showTip(double sec) { + QRect tip_area(0, plot_area.top(), rect().width(), plot_area.height()); + QRect visible_rect = charts_widget->chartVisibleRect(this).intersected(tip_area); + if (visible_rect.isEmpty()) { + tip_label->hide(); + return; + } + + tooltip_x = xPos(sec); + qreal x = -1; + QStringList text_list; + for (auto &s : sigs) { + if (s.visible) { + QString value = "--"; + // use reverse iterator to find last item <= sec. + auto it = std::lower_bound(s.vals.crbegin(), s.vals.crend(), sec, [](auto &p, double v) { return p.x() > v; }); + if (it != s.vals.crend() && it->x() >= x_min) { + value = QString::fromStdString(s.sig->formatValue(it->y(), false)); + s.track_pt = *it; + x = std::max(x, xPos(it->x())); + } + QString name = sigs.size() > 1 ? QString::fromStdString(s.sig->name) + ": " : ""; + QString min = s.min == std::numeric_limits::max() ? "--" : QString::number(s.min); + QString max = s.max == std::numeric_limits::lowest() ? "--" : QString::number(s.max); + text_list << QString("%2%3 (%4, %5)") + .arg(s.color.name(), name, value, min, max); + } + } + if (x < 0) { + x = tooltip_x; + } + QPoint pt(x, plot_area.top()); + text_list.push_front(QString::number(secondsAtPoint({x, 0}), 'f', 3)); + QString text = "

" % text_list.join("
") % "

"; + tip_label->showText(pt, text, this, visible_rect); + update(); +} + +void ChartView::hideTip() { + clearTrackPoints(); + tooltip_x = -1; + tip_label->hide(); + update(); +} + +void ChartView::resetChartCache() { + chart_pixmap = QPixmap(); + update(); +} + +void ChartView::paintEvent(QPaintEvent *event) { + QPainter painter(this); + painter.setRenderHints(QPainter::Antialiasing); + + // the static layer is invalidated on x-range change and data merge, so cache it in live mode too + const qreal dpr = devicePixelRatioF(); + if (chart_pixmap.isNull() || chart_pixmap.size() != size() * dpr) { + chart_pixmap = QPixmap(size() * dpr); + chart_pixmap.setDevicePixelRatio(dpr); + QPainter p(&chart_pixmap); + p.setRenderHints(QPainter::Antialiasing); + p.setFont(font()); + drawStaticLayer(&p); + } + painter.drawPixmap(QPoint(), chart_pixmap); + + if (can_drop) { + painter.setPen(QPen(palette().color(QPalette::Highlight), 4)); + painter.drawRect(rect()); + } + drawForeground(&painter); +} + +void ChartView::drawStaticLayer(QPainter *painter) { + painter->fillRect(rect(), palette().color(QPalette::Base)); + painter->drawPixmap(move_icon_rect.topLeft(), utils::icon("grip-horizontal")); + drawAxes(painter); + drawLegend(painter); + drawSeries(painter); +} + +void ChartView::drawAxes(QPainter *painter) { + const QColor text_color = palette().color(QPalette::Text); + QColor grid_color = text_color; + grid_color.setAlpha(50); + QFontMetrics fm(font()); + painter->setFont(font()); + + // y grid lines and tick labels + for (int i = 0; i < y_tick_count; ++i) { + double value = y_min + i * (y_max - y_min) / (y_tick_count - 1); + qreal y = yPos(value); + painter->setPen(grid_color); + painter->drawLine(QPointF(plot_area.left(), y), QPointF(plot_area.right(), y)); + painter->setPen(text_color); + QRectF label_rect(0, y - fm.height() / 2.0, plot_area.left() - 6, fm.height()); + painter->drawText(label_rect, Qt::AlignRight | Qt::AlignVCenter, QString::number(value, 'f', y_precision)); + } + + // rotated y axis title (unit) + if (!y_unit.isEmpty()) { + painter->save(); + painter->translate(plot_area.left() - y_label_width + fm.height() / 2.0, plot_area.center().y()); + painter->rotate(-90); + painter->drawText(QRectF(-plot_area.height() / 2.0, -fm.height() / 2.0, plot_area.height(), fm.height()), + Qt::AlignCenter, y_unit); + painter->restore(); + } + + // x grid lines and tick labels + const int x_precision = xAxisPrecision(); + for (int i = 0; i < X_TICK_COUNT; ++i) { + double sec = x_min + i * (x_max - x_min) / (X_TICK_COUNT - 1); + qreal x = xPos(sec); + painter->setPen(grid_color); + painter->drawLine(QPointF(x, plot_area.top()), QPointF(x, plot_area.bottom())); + painter->setPen(text_color); + QString label = QString::number(sec, 'f', x_precision); + QRectF label_rect(x - 100, plot_area.bottom() + AXIS_X_TOP_MARGIN, 200, fm.height()); + painter->drawText(label_rect, Qt::AlignHCenter | Qt::AlignTop, label); + } +} + +void ChartView::drawLegend(QPainter *painter) { + QColor title_color = palette().color(QPalette::WindowText); + // Draw message details in similar color, but slightly fade it to the background + QColor msg_color = title_color; + msg_color.setAlpha(180); + QFont bold_font = font(); + bold_font.setBold(true); + const int marker_size = QFontMetrics(font()).height() - 4; + + for (int i = 0; i < sigs.size() && i < legend_rects.size(); ++i) { + const auto &s = sigs[i]; + const QRect &r = legend_rects[i]; + painter->setPen(Qt::NoPen); + painter->setBrush(s.color); + QRectF marker_rect(r.left(), r.center().y() - marker_size / 2.0, marker_size, marker_size); + series_type == SeriesType::Scatter ? painter->drawEllipse(marker_rect) : painter->drawRect(marker_rect); + + bold_font.setStrikeOut(!s.visible); + QFont normal_font = font(); + normal_font.setStrikeOut(!s.visible); + + qreal x = r.left() + marker_size + 5; + painter->setFont(bold_font); + painter->setPen(title_color); + QString name = QFontMetrics(bold_font).elidedText(QString::fromStdString(s.sig->name), Qt::ElideRight, r.right() - x); + painter->drawText(QRectF(x, r.top(), r.right() - x, r.height()), Qt::AlignLeft | Qt::AlignVCenter, name); + x += QFontMetrics(bold_font).horizontalAdvance(name); + painter->setFont(normal_font); + painter->setPen(msg_color); + QString msg = QFontMetrics(normal_font).elidedText(QString::fromStdString(" " + msgName(s.msg_id) + " " + s.msg_id.toString()), + Qt::ElideRight, r.right() - x); + painter->drawText(QRectF(x, r.top(), r.right() - x, r.height()), Qt::AlignLeft | Qt::AlignVCenter, msg); + } +} + +void ChartView::drawSeries(QPainter *painter) { + painter->save(); + painter->setClipRect(plot_area); + for (auto &s : sigs) { + if (!s.visible) continue; + + // visible points in vals to compute point density + auto first = std::lower_bound(s.vals.cbegin(), s.vals.cend(), x_min, xLessThan); + auto last = std::lower_bound(first, s.vals.cend(), x_max, xLessThan); + int num_points = std::max(last - first, 1); + double pixels_per_point = 0; + if (first != last) { + const QPointF &right_pt = last == s.vals.cend() ? s.vals.back() : *last; + pixels_per_point = (xPos(right_pt.x()) - xPos(first->x())) / num_points; + } + + if (series_type == SeriesType::Scatter) { + qreal radius = std::clamp(pixels_per_point / 2.0, 2.0, 8.0) / 2.0; + painter->setPen(Qt::NoPen); + painter->setBrush(s.color); + for (auto it = first; it != last; ++it) { + painter->drawEllipse(QPointF(xPos(it->x()), yPos(it->y())), radius, radius); + } + } else { + const auto &points = series_type == SeriesType::StepLine ? s.step_vals : s.vals; + auto begin = std::lower_bound(points.cbegin(), points.cend(), x_min, xLessThan); + if (begin != points.cbegin()) --begin; + auto end = std::lower_bound(begin, points.cend(), x_max, xLessThan); + if (end != points.cend()) ++end; + if (begin == end) continue; + + std::vector polyline; + polyline.reserve(end - begin); + for (auto it = begin; it != end; ++it) { + polyline.emplace_back(xPos(it->x()), yPos(it->y())); + } + painter->setPen(QPen(s.color, 2)); + painter->setBrush(Qt::NoBrush); + painter->drawPolyline(polyline.data(), polyline.size()); + + // show points when zoomed in enough + if (num_points == 1 || pixels_per_point > 20) { + painter->setPen(Qt::NoPen); + painter->setBrush(s.color); + for (auto it = first; it != last; ++it) { + painter->drawEllipse(QPointF(xPos(it->x()), yPos(it->y())), 4, 4); + } + } + } + } + painter->restore(); +} + +void ChartView::drawForeground(QPainter *painter) { + drawTimeline(painter); + drawSignalValue(painter); + // draw track points + painter->setPen(Qt::NoPen); + qreal track_line_x = -1; + for (auto &s : sigs) { + if (!s.track_pt.isNull() && s.visible) { + painter->setBrush(s.color.darker(125)); + QPointF pos(xPos(s.track_pt.x()), yPos(s.track_pt.y())); + painter->drawEllipse(pos, 5.5, 5.5); + track_line_x = std::max(track_line_x, pos.x()); + } + } + if (track_line_x > 0) { + painter->setPen(QPen(Qt::darkGray, 1, Qt::DashLine)); + painter->drawLine(QPointF{track_line_x, (qreal)plot_area.top()}, QPointF{track_line_x, (qreal)plot_area.bottom()}); + } + + drawRubberBandTimeRange(painter); +} + +void ChartView::drawRubberBandTimeRange(QPainter *painter) { + if (rubber_rect.width() <= 1) return; + + // selection rect + QColor highlight = palette().color(QPalette::Highlight); + QColor fill = highlight; + fill.setAlpha(50); + painter->fillRect(rubber_rect, fill); + painter->setPen(highlight); + painter->setBrush(Qt::NoBrush); + painter->drawRect(rubber_rect); + + // time labels at the bottom corners + painter->setPen(Qt::white); + painter->setFont(font()); + for (const auto &pt : {rubber_rect.bottomLeft(), rubber_rect.bottomRight()}) { + QString sec = QString::number(secondsAtPoint(pt), 'f', 2); + auto r = painter->fontMetrics().boundingRect(sec).adjusted(-6, -AXIS_X_TOP_MARGIN, 6, AXIS_X_TOP_MARGIN); + pt == rubber_rect.bottomLeft() ? r.moveTopRight(pt + QPoint{0, 2}) : r.moveTopLeft(pt + QPoint{0, 2}); + painter->fillRect(r, Qt::gray); + painter->drawText(r, Qt::AlignCenter, sec); + } +} + +void ChartView::drawTimeline(QPainter *painter) { + // draw vertical time line + qreal x = std::clamp(xPos(cur_sec), (qreal)plot_area.left(), (qreal)plot_area.right()); + painter->setPen(QPen(palette().color(QPalette::Text), 1)); + painter->drawLine(QPointF{x, plot_area.top() - 1.0}, QPointF{x, plot_area.bottom() + 1.0}); + + // draw current time under the axis-x + QString time_str = QString::number(cur_sec, 'f', 2); + QSize time_str_size = QFontMetrics(font()).size(Qt::TextSingleLine, time_str) + QSize(8, 2); + QRectF time_str_rect(QPointF(x - time_str_size.width() / 2.0, plot_area.bottom() + AXIS_X_TOP_MARGIN), time_str_size); + QPainterPath path; + path.addRoundedRect(time_str_rect, 3, 3); + painter->fillPath(path, utils::isDarkTheme() ? Qt::darkGray : Qt::gray); + painter->setPen(palette().color(QPalette::BrightText)); + painter->setFont(font()); + painter->drawText(time_str_rect, Qt::AlignCenter, time_str); +} + +void ChartView::drawSignalValue(QPainter *painter) { + painter->setFont(signal_value_font); + painter->setPen(palette().color(QPalette::Text)); + for (int i = 0; i < sigs.size() && i < legend_rects.size(); ++i) { + const auto &s = sigs[i]; + auto it = std::lower_bound(s.vals.crbegin(), s.vals.crend(), cur_sec, + [](auto &p, double x) { return p.x() > x + EPSILON; }); + QString value = (it != s.vals.crend() && it->x() >= x_min) ? QString::fromStdString(s.sig->formatValue(it->y())) : "--"; + QRectF value_rect(legend_rects[i].bottomLeft() - QPoint(0, 1), legend_rects[i].size()); + QString elided_val = painter->fontMetrics().elidedText(value, Qt::ElideRight, value_rect.width()); + painter->drawText(value_rect, Qt::AlignHCenter | Qt::AlignTop, elided_val); + } +} + +QColor ChartView::uniqueColor(QColor color, const cabana::Signal *exclude) const { + for (auto &s : sigs) { + if (s.sig != exclude && std::abs(color.hueF() - s.color.hueF()) < 0.1) { + // use different color to distinguish it from others. + auto last_color = sigs.back().color; + static thread_local std::mt19937 rng{std::random_device{}()}; + std::uniform_int_distribution sat(35, 99); + std::uniform_int_distribution val(85, 99); + color.setHsvF(std::fmod(last_color.hueF() + 60 / 360.0, 1.0), + sat(rng) / 100.0, + val(rng) / 100.0); + break; + } + } + return color; +} + +void ChartView::setSeriesType(SeriesType type) { + if (type != series_type) { + series_type = type; + menu->actions()[(int)type]->setChecked(true); + updateTitle(); + } +} diff --git a/openpilot/tools/cabana/chart/chart.h b/openpilot/tools/cabana/chart/chart.h new file mode 100644 index 0000000000..b03623475a --- /dev/null +++ b/openpilot/tools/cabana/chart/chart.h @@ -0,0 +1,130 @@ +#pragma once + +#include +#include +#include +#include + +#include + +#include "tools/cabana/chart/tiplabel.h" +#include "tools/cabana/dbc/dbcmanager.h" +#include "tools/cabana/streams/abstractstream.h" + +enum class SeriesType { + Line = 0, + StepLine, + Scatter +}; + +class ChartsWidget; +class ChartView : public QWidget { + Q_OBJECT + +public: + ChartView(const std::pair &x_range, ChartsWidget *parent = nullptr); + void addSignal(const MessageId &msg_id, const cabana::Signal *sig); + bool hasSignal(const MessageId &msg_id, const cabana::Signal *sig) const; + void updateSeries(const cabana::Signal *sig = nullptr, const MessageEventsMap *msg_new_events = nullptr); + void updatePlot(double cur, double min, double max); + void setSeriesType(SeriesType type); + void updatePlotArea(int left, bool force = false); + void showTip(double sec); + void hideTip(); + double secondsAtPoint(const QPointF &pt) const { + return x_min + (pt.x() - plot_area.left()) * (x_max - x_min) / std::max(plot_area.width(), 1); + } + + struct SigItem { + MessageId msg_id; + const cabana::Signal *sig = nullptr; + QColor color; + bool visible = true; + std::vector vals; + std::vector step_vals; + QPointF track_pt{}; + SegmentTree segment_tree; + double min = 0; + double max = 0; + }; + +signals: + void axisYLabelWidthChanged(int w); + +private slots: + void signalUpdated(const cabana::Signal *sig); + void manageSignals(); + void msgUpdated(MessageId id); + void msgRemoved(MessageId id) { removeIf([=](auto &s) { return s.msg_id.address == id.address && !dbc()->msg(id); }); } + void signalRemoved(const cabana::Signal *sig) { removeIf([=](auto &s) { return s.sig == sig; }); } + +private: + void appendCanEvents(const cabana::Signal *sig, const std::vector &events, + std::vector &vals, std::vector &step_vals); + void createToolButtons(); + void contextMenuEvent(QContextMenuEvent *event) override; + void mousePressEvent(QMouseEvent *event) override; + void mouseMoveEvent(QMouseEvent *event) override; + void mouseReleaseEvent(QMouseEvent *event) override; + void resizeEvent(QResizeEvent *event) override; + QSize sizeHint() const override; + void updateAxisY(); + void updateTitle(); + void resetChartCache(); + void paintEvent(QPaintEvent *event) override; + void drawStaticLayer(QPainter *painter); + void drawAxes(QPainter *painter); + void drawLegend(QPainter *painter); + void drawSeries(QPainter *painter); + void drawForeground(QPainter *painter); + void drawSignalValue(QPainter *painter); + void drawTimeline(QPainter *painter); + void drawRubberBandTimeRange(QPainter *painter); + int xAxisPrecision() const; + std::tuple getNiceAxisNumbers(qreal min, qreal max, int tick_count); + qreal niceNumber(qreal x, bool ceiling); + QColor uniqueColor(QColor color, const cabana::Signal *exclude = nullptr) const; + void removeIf(std::function predicate); + void takeSignalsFrom(ChartView *source); + void setDropHighlight(bool highlight) { if (std::exchange(can_drop, highlight) != highlight) update(); } + inline void clearTrackPoints() { for (auto &s : sigs) s.track_pt = {}; } + inline qreal xPos(double sec) const { return plot_area.left() + (sec - x_min) / (x_max - x_min) * plot_area.width(); } + inline qreal yPos(double val) const { return plot_area.bottom() - (val - y_min) / (y_max - y_min) * plot_area.height(); } + + // layout + QRect plot_area; + QRect move_icon_rect; + std::vector legend_rects; + // axes + double x_min; + double x_max; + double y_min = 0; + double y_max = 1; + int y_tick_count = 3; + int y_precision = 0; + QString y_unit; + int y_label_width = 0; + int align_to = 0; + // interaction + enum class MouseMode { None, Rubber, Scrub }; + MouseMode mouse_mode = MouseMode::None; + QPoint press_pos; + QRect rubber_rect; + bool resume_after_scrub = false; + + QMenu *menu; + QAction *split_chart_act; + QAction *close_act; + ToolButton *manage_btn; + ToolButton *close_btn; + TipLabel *tip_label; + std::vector sigs; + double cur_sec = 0; + SeriesType series_type = SeriesType::Line; + QPixmap chart_pixmap; + bool can_drop = false; + double tooltip_x = -1; + QFont signal_value_font; + ChartsWidget *charts_widget; + friend class ChartsWidget; +}; diff --git a/openpilot/tools/cabana/chart/chartswidget.cc b/openpilot/tools/cabana/chart/chartswidget.cc new file mode 100644 index 0000000000..3144c5132d --- /dev/null +++ b/openpilot/tools/cabana/chart/chartswidget.cc @@ -0,0 +1,661 @@ +#include "tools/cabana/chart/chartswidget.h" +#include "tools/cabana/dbc/dbcqt.h" + +#include +#include + +#include +#include +#include +#include +#include + +#include "tools/cabana/chart/chart.h" + +const int MAX_COLUMN_COUNT = 4; +const int CHART_SPACING = 4; + +ChartsWidget::ChartsWidget(QWidget *parent) : QFrame(parent) { + align_timer = new QTimer(this); + auto_scroll_timer = new QTimer(this); + setFrameStyle(QFrame::StyledPanel | QFrame::Plain); + QVBoxLayout *main_layout = new QVBoxLayout(this); + main_layout->setContentsMargins(0, 0, 0, 0); + main_layout->setSpacing(0); + + // toolbar + toolbar = new QToolBar(tr("Charts"), this); + int icon_size = style()->pixelMetric(QStyle::PM_SmallIconSize); + toolbar->setIconSize({icon_size, icon_size}); + + auto new_plot_btn = new ToolButton("file-plus", tr("New Chart")); + auto new_tab_btn = new ToolButton("window-stack", tr("New Tab")); + toolbar->addWidget(new_plot_btn); + toolbar->addWidget(new_tab_btn); + toolbar->addWidget(title_label = new QLabel()); + title_label->setContentsMargins(0, 0, style()->pixelMetric(QStyle::PM_LayoutHorizontalSpacing), 0); + + auto chart_type_action = toolbar->addAction(""); + QMenu *chart_type_menu = new QMenu(this); + auto types = std::array{tr("Line"), tr("Step"), tr("Scatter")}; + for (int i = 0; i < types.size(); ++i) { + QString type_text = types[i]; + chart_type_menu->addAction(type_text, this, [=]() { + settings.chart_series_type = i; + chart_type_action->setText("Type: " + type_text); + settingChanged(); + }); + } + chart_type_action->setText("Type: " + types[settings.chart_series_type]); + chart_type_action->setMenu(chart_type_menu); + qobject_cast(toolbar->widgetForAction(chart_type_action))->setPopupMode(QToolButton::InstantPopup); + + QMenu *menu = new QMenu(this); + for (int i = 0; i < MAX_COLUMN_COUNT; ++i) { + menu->addAction(tr("%1").arg(i + 1), [=]() { setColumnCount(i + 1); }); + } + columns_action = toolbar->addAction(""); + columns_action->setMenu(menu); + qobject_cast(toolbar->widgetForAction(columns_action))->setPopupMode(QToolButton::InstantPopup); + + QWidget *spacer = new QWidget(this); + spacer->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred); + toolbar->addWidget(spacer); + + range_lb_action = toolbar->addWidget(range_lb = new QLabel(this)); + range_slider = new LogSlider(1000, Qt::Horizontal, this); + range_slider->setFixedWidth(150 * qApp->devicePixelRatio()); + range_slider->setToolTip(tr("Set the chart range")); + range_slider->setRange(1, settings.max_cached_minutes * 60); + range_slider->setSingleStep(1); + range_slider->setPageStep(60); // 1 min + range_slider_action = toolbar->addWidget(range_slider); + + // zoom controls + undo_zoom_action = toolbar->addAction(utils::icon("arrow-counterclockwise"), tr("Undo Zoom"), [this]() { zoom_undo_stack.undo(); }); + redo_zoom_action = toolbar->addAction(utils::icon("arrow-clockwise"), tr("Redo Zoom"), [this]() { zoom_undo_stack.redo(); }); + undo_zoom_action->setEnabled(false); + redo_zoom_action->setEnabled(false); + zoom_undo_stack.setCallbacks({.index_changed = [this]() { + undo_zoom_action->setEnabled(zoom_undo_stack.canUndo()); + redo_zoom_action->setEnabled(zoom_undo_stack.canRedo()); + }}); + reset_zoom_action = toolbar->addWidget(reset_zoom_btn = new ToolButton("zoom-out", tr("Reset Zoom"))); + reset_zoom_btn->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); + + toolbar->addWidget(remove_all_btn = new ToolButton("x-square", tr("Remove all charts"))); + toolbar->addWidget(dock_btn = new ToolButton("")); + main_layout->addWidget(toolbar); + + // tabbar + tabbar = new TabBar(this); + tabbar->setAutoHide(true); + tabbar->setExpanding(false); + tabbar->setDrawBase(true); + tabbar->setUsesScrollButtons(true); + main_layout->addWidget(tabbar); + + // charts + charts_container = new ChartsContainer(this); + charts_container->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); + charts_scroll = new QScrollArea(this); + charts_scroll->viewport()->setBackgroundRole(QPalette::Base); + charts_scroll->setFrameStyle(QFrame::NoFrame); + charts_scroll->setWidgetResizable(true); + charts_scroll->setWidget(charts_container); + charts_scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + main_layout->addWidget(charts_scroll); + + // chart drag preview + drag_preview = new QLabel(this); + drag_preview->setAttribute(Qt::WA_TransparentForMouseEvents); + drag_preview->hide(); + + // init settings + current_theme = settings.theme; + column_count = std::clamp(settings.chart_column_count, 1, MAX_COLUMN_COUNT); + max_chart_range = std::clamp(settings.chart_range, 1, settings.max_cached_minutes * 60); + display_range = std::make_pair(can->minSeconds(), can->minSeconds() + max_chart_range); + range_slider->setValue(max_chart_range); + updateToolBar(); + + align_timer->setSingleShot(true); + QObject::connect(align_timer, &QTimer::timeout, this, &ChartsWidget::alignCharts); + QObject::connect(auto_scroll_timer, &QTimer::timeout, this, &ChartsWidget::doAutoScroll); + QObject::connect(dbcNotifier(), &QtDBCNotifier::DBCFileChanged, this, &ChartsWidget::removeAll); + QObject::connect(can, &AbstractStream::eventsMerged, this, &ChartsWidget::eventsMerged); + QObject::connect(can, &AbstractStream::msgsReceived, this, &ChartsWidget::updateState); + QObject::connect(can, &AbstractStream::seeking, this, &ChartsWidget::updateState); + QObject::connect(can, &AbstractStream::timeRangeChanged, this, &ChartsWidget::timeRangeChanged); + QObject::connect(range_slider, &QSlider::valueChanged, this, &ChartsWidget::setMaxChartRange); + QObject::connect(new_plot_btn, &QToolButton::clicked, this, &ChartsWidget::newChart); + QObject::connect(remove_all_btn, &QToolButton::clicked, this, &ChartsWidget::removeAll); + QObject::connect(reset_zoom_btn, &QToolButton::clicked, this, &ChartsWidget::zoomReset); + QObject::connect(&settings, &Settings::changed, this, &ChartsWidget::settingChanged); + QObject::connect(new_tab_btn, &QToolButton::clicked, this, &ChartsWidget::newTab); + QObject::connect(this, &ChartsWidget::seriesChanged, this, &ChartsWidget::updateTabBar); + QObject::connect(tabbar, &QTabBar::tabCloseRequested, this, &ChartsWidget::removeTab); + QObject::connect(tabbar, &QTabBar::currentChanged, [this](int index) { + if (index != -1) updateLayout(true); + }); + QObject::connect(dock_btn, &QToolButton::clicked, this, &ChartsWidget::toggleChartsDocking); + + setIsDocked(true); + newTab(); + qApp->installEventFilter(this); + setWhatsThis(tr(R"( + Chart View
+ Click: Click to seek to a corresponding time.
+ Drag: Zoom into the chart.
+ Shift + Drag: Scrub through the chart to view values.
+ Right Mouse: Open the context menu.
+ )")); +} + +void ChartsWidget::newTab() { + static int tab_unique_id = 0; + int idx = tabbar->addTab(""); + tabbar->setTabData(idx, tab_unique_id++); + tabbar->setCurrentIndex(idx); + updateTabBar(); +} + +void ChartsWidget::removeTab(int index) { + int id = tabbar->tabData(index).toInt(); + for (auto &c : tab_charts[id]) { + removeChart(c); + } + tab_charts.erase(id); + tabbar->removeTab(index); + updateTabBar(); +} + +void ChartsWidget::updateTabBar() { + for (int i = 0; i < tabbar->count(); ++i) { + const auto &charts_in_tab = tab_charts[tabbar->tabData(i).toInt()]; + tabbar->setTabText(i, QString("Tab %1 (%2)").arg(i + 1).arg((int)charts_in_tab.size())); + } +} + +void ChartsWidget::eventsMerged(const MessageEventsMap &new_events) { + std::vector> futures; + for (auto c : charts) { + futures.push_back(std::async(std::launch::async, &ChartView::updateSeries, c, nullptr, &new_events)); + } + for (auto &f : futures) f.get(); +} + +void ChartsWidget::timeRangeChanged(const std::optional> &time_range) { + updateToolBar(); + updateState(); +} + +void ChartsWidget::zoomReset() { + can->setTimeRange(std::nullopt); + zoom_undo_stack.clear(); +} + +QRect ChartsWidget::chartVisibleRect(ChartView *chart) { + const QRect visible_rect(-charts_container->pos(), charts_scroll->viewport()->size()); + return chart->rect().intersected(QRect(chart->mapFrom(charts_container, visible_rect.topLeft()), visible_rect.size())); +} + +void ChartsWidget::showValueTip(double sec) { + emit showTip(sec); + if (sec < 0 && !value_tip_visible_) return; + + value_tip_visible_ = sec >= 0; + for (auto c : currentCharts()) { + value_tip_visible_ ? c->showTip(sec) : c->hideTip(); + } +} + +void ChartsWidget::updateState() { + if (charts.empty()) return; + + const auto &time_range = can->timeRange(); + const double cur_sec = can->currentSec(); + if (!time_range.has_value()) { + double pos = (cur_sec - display_range.first) / std::max(1.0, max_chart_range); + if (pos < 0 || pos > 0.8) { + display_range.first = std::max(can->minSeconds(), cur_sec - max_chart_range * 0.1); + } + double max_sec = std::min(display_range.first + max_chart_range, can->maxSeconds()); + display_range.first = std::max(can->minSeconds(), max_sec - max_chart_range); + display_range.second = display_range.first + max_chart_range; + } + + const auto &range = time_range ? *time_range : display_range; + for (auto c : charts) { + c->updatePlot(cur_sec, range.first, range.second); + } +} + +void ChartsWidget::setMaxChartRange(int value) { + max_chart_range = settings.chart_range = range_slider->value(); + updateToolBar(); + updateState(); +} + +void ChartsWidget::setIsDocked(bool docked) { + is_docked = docked; + dock_btn->setIcon(is_docked ? "arrow-up-right-square" : "arrow-down-left-square"); + dock_btn->setToolTip(is_docked ? tr("Float the charts window") : tr("Dock the charts window")); +} + +void ChartsWidget::updateToolBar() { + title_label->setText(tr("Charts: %1").arg(charts.size())); + columns_action->setText(tr("Columns: %1").arg(column_count)); + range_lb->setText(utils::formatSeconds(max_chart_range)); + + bool is_zoomed = can->timeRange().has_value(); + range_lb_action->setVisible(!is_zoomed); + range_slider_action->setVisible(!is_zoomed); + undo_zoom_action->setVisible(is_zoomed); + redo_zoom_action->setVisible(is_zoomed); + reset_zoom_action->setVisible(is_zoomed); + reset_zoom_btn->setText(is_zoomed ? tr("%1-%2").arg(can->timeRange()->first, 0, 'f', 2).arg(can->timeRange()->second, 0, 'f', 2) : ""); + remove_all_btn->setEnabled(!charts.empty()); +} + +void ChartsWidget::settingChanged() { + if (std::exchange(current_theme, settings.theme) != current_theme) { + undo_zoom_action->setIcon(utils::icon("arrow-counterclockwise")); + redo_zoom_action->setIcon(utils::icon("arrow-clockwise")); + } + if (range_slider->maximum() != settings.max_cached_minutes * 60) { + range_slider->setRange(1, settings.max_cached_minutes * 60); + } + for (auto c : charts) { + c->setFixedHeight(settings.chart_height); + c->setSeriesType((SeriesType)settings.chart_series_type); + c->resetChartCache(); + } +} + +ChartView *ChartsWidget::findChart(const MessageId &id, const cabana::Signal *sig) { + for (auto c : charts) + if (c->hasSignal(id, sig)) return c; + return nullptr; +} + +ChartView *ChartsWidget::createChart(int pos) { + auto chart = new ChartView(can->timeRange().value_or(display_range), this); + chart->setFixedHeight(settings.chart_height); + chart->setMinimumWidth(CHART_MIN_WIDTH); + chart->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed); + QObject::connect(chart, &ChartView::axisYLabelWidthChanged, align_timer, qOverload<>(&QTimer::start)); + pos = std::clamp(pos, 0, (int)charts.size()); + charts.insert(charts.begin() + pos, chart); + currentCharts().insert(currentCharts().begin() + pos, chart); + updateLayout(true); + updateToolBar(); + return chart; +} + +void ChartsWidget::showChart(const MessageId &id, const cabana::Signal *sig, bool show, bool merge) { + ChartView *chart = findChart(id, sig); + if (show && !chart) { + chart = merge && currentCharts().size() > 0 ? currentCharts().front() : createChart(); + chart->addSignal(id, sig); + updateState(); + } else if (!show && chart) { + chart->removeIf([&](auto &s) { return s.msg_id == id && s.sig == sig; }); + } +} + +void ChartsWidget::splitChart(ChartView *src_chart) { + if (src_chart->sigs.size() > 1) { + int pos = std::find(charts.begin(), charts.end(), src_chart) - charts.begin() + 1; + for (auto it = src_chart->sigs.begin() + 1; it != src_chart->sigs.end(); /**/) { + auto c = createChart(pos); + // Restore to the original color + it->color = toQColor(it->sig->color); + c->sigs.emplace_back(std::move(*it)); + c->updateAxisY(); + c->updateTitle(); + it = src_chart->sigs.erase(it); + } + src_chart->updateAxisY(); + src_chart->updateTitle(); + updateState(); + QTimer::singleShot(0, src_chart, &ChartView::resetChartCache); + } +} + +QStringList ChartsWidget::serializeChartIds() const { + QStringList chart_ids; + for (auto c : charts) { + QStringList ids; + for (const auto& s : c->sigs) + ids += QString("%1|%2").arg(QString::fromStdString(s.msg_id.toString()), QString::fromStdString(s.sig->name)); + chart_ids += ids.join(','); + } + std::reverse(chart_ids.begin(), chart_ids.end()); + return chart_ids; +} + +void ChartsWidget::restoreChartsFromIds(const QStringList& chart_ids) { + for (const auto& chart_id : chart_ids) { + int index = 0; + for (const auto& part : chart_id.split(',')) { + const auto sig_parts = part.split('|'); + if (sig_parts.size() != 2) continue; + MessageId msg_id = MessageId::fromString(sig_parts[0].toStdString()); + if (auto* msg = dbc()->msg(msg_id)) + if (auto* sig = msg->sig(sig_parts[1].toStdString())) + showChart(msg_id, sig, true, index++ > 0); + } + } +} + +void ChartsWidget::setColumnCount(int n) { + n = std::clamp(n, 1, MAX_COLUMN_COUNT); + if (column_count != n) { + column_count = settings.chart_column_count = n; + updateToolBar(); + updateLayout(); + } +} + +void ChartsWidget::updateLayout(bool force) { + auto charts_layout = charts_container->charts_layout; + int n = MAX_COLUMN_COUNT; + for (; n > 1; --n) { + if ((n * CHART_MIN_WIDTH + (n - 1) * charts_layout->horizontalSpacing()) < charts_layout->geometry().width()) break; + } + + bool show_column_cb = n > 1; + columns_action->setVisible(show_column_cb); + + n = std::min(column_count, n); + auto ¤t_charts = currentCharts(); + if ((current_charts.size() != charts_layout->count() || n != current_column_count) || force) { + current_column_count = n; + charts_container->setUpdatesEnabled(false); + for (auto c : charts) { + c->setVisible(false); + } + for (int i = 0; i < current_charts.size(); ++i) { + charts_layout->addWidget(current_charts[i], i / n, i % n); + if (current_charts[i]->sigs.empty()) { + // the chart will be resized after add signal. delay setVisible to reduce flicker. + QTimer::singleShot(0, current_charts[i], [c = current_charts[i]]() { c->setVisible(true); }); + } else { + current_charts[i]->setVisible(true); + } + } + charts_container->setUpdatesEnabled(true); + } +} + +void ChartsWidget::startChartDrag(ChartView *chart, const QPoint &global_pos) { + stopAutoScroll(); + drag = {.source = chart, .press_pos = global_pos}; + QPixmap px = chart->grab().scaledToWidth(CHART_MIN_WIDTH * chart->devicePixelRatio(), Qt::SmoothTransformation); + drag_preview->setPixmap(px); + drag_preview->resize(px.size() / px.devicePixelRatio()); +} + +void ChartsWidget::dragChartMove(const QPoint &global_pos) { + if (!drag.active) { + if ((global_pos - drag.press_pos).manhattanLength() < QApplication::startDragDistance()) return; + drag.active = true; + drag_preview->show(); + drag_preview->raise(); + } + drag_preview->move(mapFromGlobal(global_pos) + QPoint(5, 5)); + + // hovering a tab switches to it so the chart can be dropped into another tab + int tab = tabbar->tabAt(tabbar->mapFromGlobal(global_pos)); + if (tab >= 0 && tab != tabbar->currentIndex()) { + tabbar->setCurrentIndex(tab); + } + + const QPoint container_pos = charts_container->mapFromGlobal(global_pos); + ChartView *target = nullptr; + for (auto c : currentCharts()) { + if (c != drag.source && c->isVisible() && c->geometry().contains(container_pos)) { + target = c; + break; + } + } + if (std::exchange(drop_target, target) != target) { + for (auto c : charts) c->setDropHighlight(c == target); + } + bool in_viewport = charts_scroll->viewport()->rect().contains(charts_scroll->viewport()->mapFromGlobal(global_pos)); + bool on_background = !target && in_viewport && !charts_container->childAt(container_pos); + charts_container->drawDropIndicator(on_background ? container_pos : QPoint()); + + if (in_viewport) { + startAutoScroll(global_pos); + } +} + +void ChartsWidget::cancelChartDrag() { + drag = {}; + stopAutoScroll(); + drag_preview->hide(); + charts_container->drawDropIndicator({}); + if (auto target = std::exchange(drop_target, nullptr)) target->setDropHighlight(false); +} + +void ChartsWidget::dragChartRelease(const QPoint &global_pos) { + ChartView *source = drag.source; + bool active = drag.active; + ChartView *target = drop_target; + cancelChartDrag(); + if (!active) return; + + const QPoint container_pos = charts_container->mapFromGlobal(global_pos); + bool in_viewport = charts_scroll->viewport()->rect().contains(charts_scroll->viewport()->mapFromGlobal(global_pos)); + if (target) { + // merge source into target + target->takeSignalsFrom(source); + } else if (in_viewport && !charts_container->childAt(container_pos)) { + // reorder within the current tab + auto w = charts_container->getDropAfter(container_pos); + if (w != source) { + for (auto &[_, list] : tab_charts) { + list.erase(std::remove(list.begin(), list.end(), source), list.end()); + } + auto &cur = currentCharts(); + int to = w ? std::find(cur.begin(), cur.end(), w) - cur.begin() + 1 : 0; + cur.insert(cur.begin() + to, source); + updateLayout(true); + updateTabBar(); + } + } +} + +void ChartsWidget::startAutoScroll(const QPoint &global_pos) { + auto_scroll_pos = global_pos; + auto_scroll_timer->start(50); +} + +void ChartsWidget::stopAutoScroll() { + auto_scroll_timer->stop(); + auto_scroll_count = 0; +} + +void ChartsWidget::doAutoScroll() { + QScrollBar *scroll = charts_scroll->verticalScrollBar(); + if (auto_scroll_count < scroll->pageStep()) { + ++auto_scroll_count; + } + + int value = scroll->value(); + QPoint pos = charts_scroll->viewport()->mapFromGlobal(auto_scroll_pos); + QRect area = charts_scroll->viewport()->rect(); + + if (pos.y() - area.top() < settings.chart_height / 2) { + scroll->setValue(value - auto_scroll_count); + } else if (area.bottom() - pos.y() < settings.chart_height / 2) { + scroll->setValue(value + auto_scroll_count); + } + if (value == scroll->value()) { + stopAutoScroll(); + } else if (chartDragActive()) { + // refresh the drop indicator/target at the new scroll position + dragChartMove(auto_scroll_pos); + } +} + +QSize ChartsWidget::minimumSizeHint() const { + return QSize(CHART_MIN_WIDTH * 1.5, QWidget::minimumSizeHint().height()); +} + +void ChartsWidget::newChart() { + SignalSelector dlg(tr("New Chart"), this); + if (dlg.exec() == QDialog::Accepted) { + auto items = dlg.seletedItems(); + if (!items.empty()) { + auto c = createChart(); + for (auto it : items) { + c->addSignal(it->msg_id, it->sig); + } + updateState(); + } + } +} + +void ChartsWidget::removeChart(ChartView *chart) { + if (drag.source == chart) cancelChartDrag(); + if (drop_target == chart) drop_target = nullptr; + charts.erase(std::remove(charts.begin(), charts.end(), chart), charts.end()); + chart->deleteLater(); + for (auto &[_, list] : tab_charts) { + list.erase(std::remove(list.begin(), list.end(), chart), list.end()); + } + updateToolBar(); + updateLayout(true); + alignCharts(); + emit seriesChanged(); +} + +void ChartsWidget::removeAll() { + while (tabbar->count() > 1) { + tabbar->removeTab(1); + } + tab_charts.clear(); + + if (!charts.empty()) { + for (auto c : charts) { + delete c; + } + charts.clear(); + emit seriesChanged(); + } + zoomReset(); +} + +void ChartsWidget::alignCharts() { + int plot_left = 0; + for (auto c : charts) { + plot_left = std::max(plot_left, c->y_label_width); + } + plot_left = std::max((plot_left / 10) * 10 + 10, 50); + for (auto c : charts) { + c->updatePlotArea(plot_left); + } +} + +bool ChartsWidget::eventFilter(QObject *o, QEvent *e) { + // route all mouse events to the chart drag, even when the source chart is hidden by a tab switch + if (chartDragActive()) { + if (e->type() == QEvent::MouseMove) { + dragChartMove(static_cast(e)->globalPos()); + return true; + } else if (e->type() == QEvent::MouseButtonRelease && static_cast(e)->button() == Qt::LeftButton) { + dragChartRelease(static_cast(e)->globalPos()); + return false; // let the release through so Qt clears the implicit mouse grab + } else if (e->type() == QEvent::MouseButtonPress || e->type() == QEvent::MouseButtonRelease) { + return true; // swallow other buttons during the drag + } + } + + if (!value_tip_visible_) return false; + + if (e->type() == QEvent::MouseMove) { + bool on_tip = qobject_cast(o) != nullptr; + auto global_pos = static_cast(e)->globalPos(); + + for (const auto &c : charts) { + auto local_pos = c->mapFromGlobal(global_pos); + if (c->plot_area.contains(local_pos)) { + if (on_tip) { + showValueTip(c->secondsAtPoint(local_pos)); + } + return false; + } + } + + showValueTip(-1); + } else if (e->type() == QEvent::Wheel) { + if (auto tip = qobject_cast(o)) { + // Forward the event to the parent widget + QCoreApplication::sendEvent(tip->parentWidget(), e); + } + } + return false; +} + +bool ChartsWidget::event(QEvent *event) { + bool back_button = false; + switch (event->type()) { + case QEvent::Resize: + updateLayout(); + break; + case QEvent::MouseButtonPress: + back_button = static_cast(event)->button() == Qt::BackButton; + break; + case QEvent::NativeGesture: + back_button = (static_cast(event)->value() == 180); + break; + case QEvent::WindowDeactivate: + case QEvent::FocusOut: + if (chartDragActive()) cancelChartDrag(); + showValueTip(-1); + default: + break; + } + + if (back_button) { + zoom_undo_stack.undo(); + return true; // Return true since the event has been handled + } + return QFrame::event(event); +} + +// ChartsContainer + +ChartsContainer::ChartsContainer(ChartsWidget *parent) : charts_widget(parent), QWidget(parent) { + setBackgroundRole(QPalette::Window); + QVBoxLayout *charts_main_layout = new QVBoxLayout(this); + charts_main_layout->setContentsMargins(0, CHART_SPACING, 0, CHART_SPACING); + charts_layout = new QGridLayout(); + charts_layout->setSpacing(CHART_SPACING); + charts_main_layout->addLayout(charts_layout); + charts_main_layout->addStretch(0); +} + +void ChartsContainer::paintEvent(QPaintEvent *ev) { + if (!drop_indictor_pos.isNull() && !childAt(drop_indictor_pos)) { + QRect r = geometry(); + r.setHeight(CHART_SPACING); + if (auto insert_after = getDropAfter(drop_indictor_pos)) { + r.moveTop(insert_after->geometry().bottom()); + } + + QPainter p(this); + p.fillRect(r, palette().highlight()); + } +} + +ChartView *ChartsContainer::getDropAfter(const QPoint &pos) const { + auto it = std::find_if(charts_widget->currentCharts().crbegin(), charts_widget->currentCharts().crend(), [&pos](auto c) { + auto area = c->geometry(); + return pos.x() >= area.left() && pos.x() <= area.right() && pos.y() >= area.bottom(); + }); + return it == charts_widget->currentCharts().crend() ? nullptr : *it; +} diff --git a/tools/cabana/chart/chartswidget.h b/openpilot/tools/cabana/chart/chartswidget.h similarity index 75% rename from tools/cabana/chart/chartswidget.h rename to openpilot/tools/cabana/chart/chartswidget.h index 46e7f546b0..8b3003dcd6 100644 --- a/tools/cabana/chart/chartswidget.h +++ b/openpilot/tools/cabana/chart/chartswidget.h @@ -8,15 +8,13 @@ #include #include #include -#include -#include #include "tools/cabana/chart/signalselector.h" +#include "tools/cabana/commands.h" #include "tools/cabana/dbc/dbcmanager.h" #include "tools/cabana/streams/abstractstream.h" const int CHART_MIN_WIDTH = 300; -const QString CHART_MIME_TYPE = "application/x-cabanachartview"; class ChartView; class ChartsWidget; @@ -24,9 +22,6 @@ class ChartsWidget; class ChartsContainer : public QWidget { public: ChartsContainer(ChartsWidget *parent); - void dragEnterEvent(QDragEnterEvent *event) override; - void dropEvent(QDropEvent *event) override; - void dragLeaveEvent(QDragLeaveEvent *event) override { drawDropIndicator({}); } void drawDropIndicator(const QPoint &pt) { drop_indictor_pos = pt; update(); } void paintEvent(QPaintEvent *ev) override; ChartView *getDropAfter(const QPoint &pos) const; @@ -43,6 +38,8 @@ public: ChartsWidget(QWidget *parent = nullptr); void showChart(const MessageId &id, const cabana::Signal *sig, bool show, bool merge); inline bool hasSignal(const MessageId &id, const cabana::Signal *sig) { return findChart(id, sig) != nullptr; } + QStringList serializeChartIds() const; + void restoreChartsFromIds(const QStringList &chart_ids); public slots: void setColumnCount(int n); @@ -67,7 +64,12 @@ private: void eventsMerged(const MessageEventsMap &new_events); void updateState(); void zoomReset(); - void startAutoScroll(); + void startChartDrag(ChartView *chart, const QPoint &global_pos); + void dragChartMove(const QPoint &global_pos); + void dragChartRelease(const QPoint &global_pos); + void cancelChartDrag(); + bool chartDragActive() const { return drag.source != nullptr; } + void startAutoScroll(const QPoint &global_pos); void stopAutoScroll(); void doAutoScroll(); void updateToolBar(); @@ -79,7 +81,7 @@ private: bool eventFilter(QObject *obj, QEvent *event) override; void newTab(); void removeTab(int index); - inline QList ¤tCharts() { return tab_charts[tabbar->tabData(tabbar->currentIndex()).toInt()]; } + inline std::vector ¤tCharts() { return tab_charts[tabbar->tabData(tabbar->currentIndex()).toInt()]; } ChartView *findChart(const MessageId &id, const cabana::Signal *sig); QLabel *title_label; @@ -95,11 +97,11 @@ private: QAction *redo_zoom_action; QAction *reset_zoom_action; ToolButton *reset_zoom_btn; - QUndoStack *zoom_undo_stack; + UndoStack zoom_undo_stack; ToolButton *remove_all_btn; - QList charts; - std::unordered_map> tab_charts; + std::vector charts; + std::unordered_map> tab_charts; TabBar *tabbar; ChartsContainer *charts_container; QScrollArea *charts_scroll; @@ -108,7 +110,15 @@ private: QAction *columns_action; int column_count = 1; int current_column_count = 0; + struct ChartDrag { + ChartView *source = nullptr; + QPoint press_pos; // global + bool active = false; + } drag; + QLabel *drag_preview; + ChartView *drop_target = nullptr; int auto_scroll_count = 0; + QPoint auto_scroll_pos; QTimer *auto_scroll_timer; QTimer *align_timer; int current_theme = 0; @@ -117,11 +127,10 @@ private: friend class ChartsContainer; }; -class ZoomCommand : public QUndoCommand { +class ZoomCommand : public UndoCommand { public: - ZoomCommand(std::pair range) : range(range), QUndoCommand() { + ZoomCommand(std::pair range) : range(range) { prev_range = can->timeRange(); - setText(QObject::tr("Zoom to %1-%2").arg(range.first, 0, 'f', 2).arg(range.second, 0, 'f', 2)); } void undo() override { can->setTimeRange(prev_range); } void redo() override { can->setTimeRange(range); } diff --git a/tools/cabana/chart/signalselector.cc b/openpilot/tools/cabana/chart/signalselector.cc similarity index 89% rename from tools/cabana/chart/signalselector.cc rename to openpilot/tools/cabana/chart/signalselector.cc index 63f3a7d575..85832e796b 100644 --- a/tools/cabana/chart/signalselector.cc +++ b/openpilot/tools/cabana/chart/signalselector.cc @@ -1,6 +1,6 @@ #include "tools/cabana/chart/signalselector.h" +#include "tools/cabana/dbc/dbcqt.h" -#include #include #include #include @@ -20,8 +20,6 @@ SignalSelector::SignalSelector(QString title, QWidget *parent) : QDialog(parent) msgs_combo->setEditable(true); msgs_combo->lineEdit()->setPlaceholderText(tr("Select a msg...")); msgs_combo->setInsertPolicy(QComboBox::NoInsert); - msgs_combo->completer()->setCompletionMode(QCompleter::PopupCompletion); - msgs_combo->completer()->setFilterMode(Qt::MatchContains); main_layout->addWidget(available_list = new QListWidget(this), 2, 0); @@ -46,7 +44,7 @@ SignalSelector::SignalSelector(QString title, QWidget *parent) : QDialog(parent) for (const auto &[id, _] : can->lastMessages()) { if (auto m = dbc()->msg(id)) { - msgs_combo->addItem(QString("%1 (%2)").arg(m->name).arg(id.toString()), QVariant::fromValue(id)); + msgs_combo->addItem(QString("%1 (%2)").arg(QString::fromStdString(m->name)).arg(QString::fromStdString(id.toString())), QVariant::fromValue(id)); } } msgs_combo->model()->sort(0); @@ -92,8 +90,8 @@ void SignalSelector::updateAvailableList(int index) { } void SignalSelector::addItemToList(QListWidget *parent, const MessageId id, const cabana::Signal *sig, bool show_msg_name) { - QString text = QString(" %1").arg(sig->color.name(), sig->name); - if (show_msg_name) text += QString(" %0 %1").arg(msgName(id), id.toString()); + QString text = QString(" %1").arg(toQColor(sig->color).name(), QString::fromStdString(sig->name)); + if (show_msg_name) text += QString(" %0 %1").arg(QString::fromStdString(msgName(id)), QString::fromStdString(id.toString())); QLabel *label = new QLabel(text); label->setContentsMargins(5, 0, 5, 0); @@ -102,8 +100,8 @@ void SignalSelector::addItemToList(QListWidget *parent, const MessageId id, cons parent->setItemWidget(new_item, label); } -QList SignalSelector::seletedItems() { - QList ret; +std::vector SignalSelector::seletedItems() { + std::vector ret; for (int i = 0; i < selected_list->count(); ++i) ret.push_back((ListItem *)selected_list->item(i)); return ret; } diff --git a/tools/cabana/chart/signalselector.h b/openpilot/tools/cabana/chart/signalselector.h similarity index 95% rename from tools/cabana/chart/signalselector.h rename to openpilot/tools/cabana/chart/signalselector.h index f46779f044..5b6e37e56a 100644 --- a/tools/cabana/chart/signalselector.h +++ b/openpilot/tools/cabana/chart/signalselector.h @@ -15,7 +15,7 @@ public: }; SignalSelector(QString title, QWidget *parent); - QList seletedItems(); + std::vector seletedItems(); inline void addSelected(const MessageId &id, const cabana::Signal *sig) { addItemToList(selected_list, id, sig, true); } private: diff --git a/openpilot/tools/cabana/chart/sparkline.cc b/openpilot/tools/cabana/chart/sparkline.cc new file mode 100644 index 0000000000..f5bef0fc2e --- /dev/null +++ b/openpilot/tools/cabana/chart/sparkline.cc @@ -0,0 +1,100 @@ +#include "tools/cabana/chart/sparkline.h" + +#include +#include +#include + +void Sparkline::update(const cabana::Signal *sig, CanEventIter first, CanEventIter last, int range, QSize size) { + if (first == last || size.isEmpty()) { + pixmap = QPixmap(); + return; + } + + points_.clear(); + min_val = std::numeric_limits::max(); + max_val = std::numeric_limits::lowest(); + points_.reserve(std::distance(first, last)); + + uint64_t start_time = (*first)->mono_time; + double value = 0.0; + for (auto it = first; it != last; ++it) { + if (sig->getValue((*it)->dat, (*it)->size, &value)) { + min_val = std::min(min_val, value); + max_val = std::max(max_val, value); + points_.emplace_back(((*it)->mono_time - start_time) / 1e9, value); + } + } + + if (points_.empty()) { + pixmap = QPixmap(); + return; + } + + freq_ = points_.size() / std::max(points_.back().x() - points_.front().x(), 1.0); + render(toQColor(sig->color), range, size); +} + +void Sparkline::render(const QColor &color, int range, QSize size) { + // Adjust for flat lines + bool is_flat_line = min_val == max_val; + if (is_flat_line) { + min_val -= 1.0; + max_val += 1.0; + } + + // Calculate scaling + const double xscale = (size.width() - 1) / (double)range; + const double yscale = (size.height() - 3) / (max_val - min_val); + bool draw_individual_points = (points_.back().x() * xscale / points_.size()) > 8.0; + + // Transform or downsample points + render_points_.reserve(points_.size()); + render_points_.clear(); + if (draw_individual_points) { + for (const auto &p : points_) { + render_points_.emplace_back(p.x() * xscale, 1.0 + (max_val - p.y()) * yscale); + } + } else if (is_flat_line) { + double y = size.height() / 2.0; + render_points_.emplace_back(0.0, y); + render_points_.emplace_back(points_.back().x() * xscale, y); + } else { + double prev_y = points_.front().y(); + render_points_.emplace_back(points_.front().x() * xscale, 1.0 + (max_val - prev_y) * yscale); + bool in_flat = false; + + for (size_t i = 1; i < points_.size(); ++i) { + const auto &p = points_[i]; + double y = p.y(); + if (std::abs(y - prev_y) < 1e-6) { + in_flat = true; + } else { + if (in_flat) render_points_.emplace_back(points_[i - 1].x() * xscale, 1.0 + (max_val - prev_y) * yscale); + render_points_.emplace_back(p.x() * xscale, 1.0 + (max_val - y) * yscale); + in_flat = false; + } + prev_y = y; + } + if (in_flat) render_points_.emplace_back(points_.back().x() * xscale, 1.0 + (max_val - prev_y) * yscale); + } + + // Render to pixmap + qreal dpr = qApp->devicePixelRatio(); + const QSize pixmap_size = size * dpr; + if (pixmap.size() != pixmap_size) { + pixmap = QPixmap(pixmap_size); + } + pixmap.setDevicePixelRatio(dpr); + pixmap.fill(Qt::transparent); + QPainter painter(&pixmap); + painter.setRenderHint(QPainter::Antialiasing, render_points_.size() <= 500); + painter.setPen(color); + painter.drawPolyline(render_points_.data(), render_points_.size()); + + painter.setPen(QPen(color, 3)); + if (draw_individual_points) { + painter.drawPoints(render_points_.data(), render_points_.size()); + } else { + painter.drawPoint(render_points_.back()); + } +} diff --git a/openpilot/tools/cabana/chart/sparkline.h b/openpilot/tools/cabana/chart/sparkline.h new file mode 100644 index 0000000000..7f30047d0d --- /dev/null +++ b/openpilot/tools/cabana/chart/sparkline.h @@ -0,0 +1,26 @@ +#pragma once + +#include +#include +#include + +#include "tools/cabana/dbc/dbc.h" +#include "tools/cabana/streams/abstractstream.h" + +class Sparkline { +public: + void update(const cabana::Signal *sig, CanEventIter first, CanEventIter last, int range, QSize size); + inline double freq() const { return freq_; } + bool isEmpty() const { return pixmap.isNull(); } + + QPixmap pixmap; + double min_val = 0; + double max_val = 0; + +private: + void render(const QColor &color, int range, QSize size); + + std::vector points_; + std::vector render_points_; + double freq_ = 0; +}; diff --git a/tools/cabana/chart/tiplabel.cc b/openpilot/tools/cabana/chart/tiplabel.cc similarity index 95% rename from tools/cabana/chart/tiplabel.cc rename to openpilot/tools/cabana/chart/tiplabel.cc index be71602838..233fa80373 100644 --- a/tools/cabana/chart/tiplabel.cc +++ b/openpilot/tools/cabana/chart/tiplabel.cc @@ -7,6 +7,7 @@ #include #include "tools/cabana/settings.h" +#include "tools/cabana/utils/util.h" TipLabel::TipLabel(QWidget *parent) : QLabel(parent, Qt::ToolTip | Qt::FramelessWindowHint) { setAttribute(Qt::WA_ShowWithoutActivating); @@ -19,7 +20,7 @@ TipLabel::TipLabel(QWidget *parent) : QLabel(parent, Qt::ToolTip | Qt::Frameless font.setPointSizeF(8.34563465); setFont(font); auto palette = QToolTip::palette(); - if (settings.theme != DARK_THEME) { + if (!utils::isDarkTheme()) { palette.setColor(QPalette::ToolTipBase, QApplication::palette().color(QPalette::Base)); palette.setColor(QPalette::ToolTipText, QRgb(0x404044)); // same color as chart label brush } diff --git a/tools/cabana/chart/tiplabel.h b/openpilot/tools/cabana/chart/tiplabel.h similarity index 100% rename from tools/cabana/chart/tiplabel.h rename to openpilot/tools/cabana/chart/tiplabel.h diff --git a/openpilot/tools/cabana/commands.cc b/openpilot/tools/cabana/commands.cc new file mode 100644 index 0000000000..b47bf90b0c --- /dev/null +++ b/openpilot/tools/cabana/commands.cc @@ -0,0 +1,175 @@ +#include "tools/cabana/commands.h" + +#include + +// UndoStack + +void UndoStack::push(UndoCommand *cmd) { + commands_.resize(index_); // drop any redoable commands + if (clean_index_ > index_) clean_index_ = -1; + commands_.emplace_back(cmd); + cmd->redo(); + setIndex(index_ + 1); +} + +void UndoStack::undo() { + if (!canUndo()) return; + commands_[index_ - 1]->undo(); + setIndex(index_ - 1); +} + +void UndoStack::redo() { + if (!canRedo()) return; + commands_[index_]->redo(); + setIndex(index_ + 1); +} + +void UndoStack::clear() { + bool was_clean = isClean(); + commands_.clear(); + index_ = clean_index_ = 0; + if (callbacks_.index_changed) callbacks_.index_changed(); + if (!was_clean && callbacks_.clean_changed) callbacks_.clean_changed(true); +} + +void UndoStack::setClean() { + if (!isClean()) { + clean_index_ = index_; + if (callbacks_.clean_changed) callbacks_.clean_changed(true); + } +} + +void UndoStack::setIndex(int index) { + bool was_clean = isClean(); + index_ = index; + if (callbacks_.index_changed) callbacks_.index_changed(); + if (isClean() != was_clean && callbacks_.clean_changed) callbacks_.clean_changed(isClean()); +} + +UndoStack *UndoStack::instance() { + static UndoStack undo_stack; + return &undo_stack; +} + +QtUndoNotifier::QtUndoNotifier(QObject *parent) : QObject(parent) { + UndoStack::instance()->setCallbacks({ + .index_changed = [this]() { emit indexChanged(); }, + .clean_changed = [this](bool clean) { emit cleanChanged(clean); }, + }); +} + +QtUndoNotifier *undoNotifier() { + static QtUndoNotifier notifier; + return ¬ifier; +} + +// EditMsgCommand + +EditMsgCommand::EditMsgCommand(const MessageId &id, const std::string &name, int size, + const std::string &node, const std::string &comment) + : id(id), new_name(name), new_size(size), new_node(node), new_comment(comment) { + if (auto msg = dbc()->msg(id)) { + old_name = msg->name; + old_size = msg->size; + old_node = msg->transmitter; + old_comment = msg->comment; + text = "edit message " + name + ":" + std::to_string(id.address); + } else { + text = "new message " + name + ":" + std::to_string(id.address); + } +} + +void EditMsgCommand::undo() { + if (old_name.empty()) + dbc()->removeMsg(id); + else + dbc()->updateMsg(id, old_name, old_size, old_node, old_comment); +} + +void EditMsgCommand::redo() { + dbc()->updateMsg(id, new_name, new_size, new_node, new_comment); +} + +// RemoveMsgCommand + +RemoveMsgCommand::RemoveMsgCommand(const MessageId &id) : id(id) { + if (auto msg = dbc()->msg(id)) { + message = *msg; + text = "remove message " + message.name + ":" + std::to_string(id.address); + } +} + +void RemoveMsgCommand::undo() { + if (!message.name.empty()) { + dbc()->updateMsg(id, message.name, message.size, message.transmitter, message.comment); + for (auto s : message.getSignals()) + dbc()->addSignal(id, *s); + } +} + +void RemoveMsgCommand::redo() { + if (!message.name.empty()) + dbc()->removeMsg(id); +} + +// AddSigCommand + +AddSigCommand::AddSigCommand(const MessageId &id, const cabana::Signal &sig) + : id(id), signal(sig) { + text = "add signal " + sig.name + " to " + msgName(id) + ":" + std::to_string(id.address); +} + +void AddSigCommand::undo() { + dbc()->removeSignal(id, signal.name); + if (msg_created) dbc()->removeMsg(id); +} + +void AddSigCommand::redo() { + if (auto msg = dbc()->msg(id); !msg) { + msg_created = true; + dbc()->updateMsg(id, dbc()->newMsgName(id), can->lastMessage(id).dat.size(), "", ""); + } + signal.name = dbc()->newSignalName(id); + signal.max = std::pow(2, signal.size) - 1; + dbc()->addSignal(id, signal); +} + +// RemoveSigCommand + +RemoveSigCommand::RemoveSigCommand(const MessageId &id, const cabana::Signal *sig) : id(id) { + sigs.push_back(*sig); + if (sig->type == cabana::Signal::Type::Multiplexor) { + for (const auto &s : dbc()->msg(id)->sigs) { + if (s->type == cabana::Signal::Type::Multiplexed) { + sigs.push_back(*s); + } + } + } + text = "remove signal " + sig->name + " from " + msgName(id) + ":" + std::to_string(id.address); +} + +void RemoveSigCommand::undo() { for (const auto &s : sigs) dbc()->addSignal(id, s); } +void RemoveSigCommand::redo() { for (const auto &s : sigs) dbc()->removeSignal(id, s.name); } + +// EditSignalCommand + +EditSignalCommand::EditSignalCommand(const MessageId &id, const cabana::Signal *sig, const cabana::Signal &new_sig) + : id(id) { + sigs.push_back({*sig, new_sig}); + if (sig->type == cabana::Signal::Type::Multiplexor && new_sig.type == cabana::Signal::Type::Normal) { + // convert all multiplexed signals to normal signals + auto msg = dbc()->msg(id); + assert(msg); + for (const auto &s : msg->sigs) { + if (s->type == cabana::Signal::Type::Multiplexed) { + auto new_s = *s; + new_s.type = cabana::Signal::Type::Normal; + sigs.push_back({*s, new_s}); + } + } + } + text = "edit signal " + sig->name + " in " + msgName(id) + ":" + std::to_string(id.address); +} + +void EditSignalCommand::undo() { for (const auto &s : sigs) dbc()->updateSignal(id, s.second.name, s.first); } +void EditSignalCommand::redo() { for (const auto &s : sigs) dbc()->updateSignal(id, s.first.name, s.second); } diff --git a/openpilot/tools/cabana/commands.h b/openpilot/tools/cabana/commands.h new file mode 100644 index 0000000000..200a4f2f5b --- /dev/null +++ b/openpilot/tools/cabana/commands.h @@ -0,0 +1,120 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include + +#include "tools/cabana/dbc/dbcmanager.h" +#include "tools/cabana/streams/abstractstream.h" + +class UndoCommand { +public: + virtual ~UndoCommand() = default; + virtual void undo() = 0; + virtual void redo() = 0; + std::string text; +}; + +class UndoStack { +public: + struct Callbacks { + std::function index_changed; + std::function clean_changed; + }; + + void push(UndoCommand *cmd); // takes ownership and calls redo() + void undo(); + void redo(); + void clear(); + void setClean(); + bool isClean() const { return clean_index_ == index_; } + bool canUndo() const { return index_ > 0; } + bool canRedo() const { return index_ < (int)commands_.size(); } + std::string undoText() const { return canUndo() ? commands_[index_ - 1]->text : ""; } + std::string redoText() const { return canRedo() ? commands_[index_]->text : ""; } + void setCallbacks(Callbacks callbacks) { callbacks_ = std::move(callbacks); } + static UndoStack *instance(); + +private: + void setIndex(int index); + std::vector> commands_; + int index_ = 0; + int clean_index_ = 0; + Callbacks callbacks_; +}; + +// emits Qt signals for the global undo stack +class QtUndoNotifier : public QObject { + Q_OBJECT + +public: + explicit QtUndoNotifier(QObject *parent = nullptr); + +signals: + void indexChanged(); + void cleanChanged(bool clean); +}; + +QtUndoNotifier *undoNotifier(); + +class EditMsgCommand : public UndoCommand { +public: + EditMsgCommand(const MessageId &id, const std::string &name, int size, const std::string &node, + const std::string &comment); + void undo() override; + void redo() override; + +private: + const MessageId id; + std::string old_name, new_name, old_comment, new_comment, old_node, new_node; + int old_size = 0, new_size = 0; +}; + +class RemoveMsgCommand : public UndoCommand { +public: + RemoveMsgCommand(const MessageId &id); + void undo() override; + void redo() override; + +private: + const MessageId id; + cabana::Msg message; +}; + +class AddSigCommand : public UndoCommand { +public: + AddSigCommand(const MessageId &id, const cabana::Signal &sig); + void undo() override; + void redo() override; + +private: + const MessageId id; + bool msg_created = false; + cabana::Signal signal = {}; +}; + +class RemoveSigCommand : public UndoCommand { +public: + RemoveSigCommand(const MessageId &id, const cabana::Signal *sig); + void undo() override; + void redo() override; + +private: + const MessageId id; + std::vector sigs; +}; + +class EditSignalCommand : public UndoCommand { +public: + EditSignalCommand(const MessageId &id, const cabana::Signal *sig, const cabana::Signal &new_sig); + void undo() override; + void redo() override; + +private: + const MessageId id; + std::vector> sigs; // {old_sig, new_sig} +}; diff --git a/openpilot/tools/cabana/core/can_data.h b/openpilot/tools/cabana/core/can_data.h new file mode 100644 index 0000000000..38141b1890 --- /dev/null +++ b/openpilot/tools/cabana/core/can_data.h @@ -0,0 +1,46 @@ +#pragma once + +#include +#include +#include +#include + +#include "tools/cabana/core/color.h" +#include "tools/cabana/core/message_id.h" + +struct CanData { + void compute(const MessageId &msg_id, const uint8_t *data, int size, double current_sec, + double playback_speed, const std::vector &mask, double frequency = 0); + + double ts = 0.; + uint32_t count = 0; + double freq = 0; + std::vector dat; + std::vector colors; + + struct ByteLastChange { + double ts = 0; + int delta = 0; + int same_delta_counter = 0; + bool suppressed = false; + }; + std::vector last_changes; + std::vector> bit_flip_counts; + double last_freq_update_ts = 0; +}; + +struct CanEvent { + uint8_t src; + uint32_t address; + uint64_t mono_time; + uint8_t size; + uint8_t dat[]; +}; + +struct CompareCanEvent { + constexpr bool operator()(const CanEvent *const event, uint64_t ts) const { return event->mono_time < ts; } + constexpr bool operator()(uint64_t ts, const CanEvent *const event) const { return ts < event->mono_time; } +}; + +using MessageEventsMap = std::unordered_map>; +using CanEventIter = std::vector::const_iterator; diff --git a/openpilot/tools/cabana/core/color.h b/openpilot/tools/cabana/core/color.h new file mode 100644 index 0000000000..c29704dd44 --- /dev/null +++ b/openpilot/tools/cabana/core/color.h @@ -0,0 +1,79 @@ +#pragma once + +#include +#include +#include + +struct CabanaColor { + uint8_t r = 0; + uint8_t g = 0; + uint8_t b = 0; + uint8_t a = 255; + + constexpr CabanaColor() = default; + constexpr CabanaColor(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha = 255) + : r(red), g(green), b(blue), a(alpha) {} + + static CabanaColor fromHsv(float hue, float saturation, float value, float alpha = 1.0f) { + const float h = hue - std::floor(hue); + const float c = value * saturation; + const float x = c * (1.0f - std::fabs(std::fmod(h * 6.0f, 2.0f) - 1.0f)); + const float m = value - c; + float red = 0, green = 0, blue = 0; + switch (static_cast(h * 6.0f) % 6) { + case 0: red = c; green = x; break; + case 1: red = x; green = c; break; + case 2: green = c; blue = x; break; + case 3: green = x; blue = c; break; + case 4: red = x; blue = c; break; + default: red = c; blue = x; break; + } + auto channel = [m](float v) { return static_cast(std::clamp((v + m) * 255.0f, 0.0f, 255.0f) + 0.5f); }; + return {channel(red), channel(green), channel(blue), + static_cast(std::clamp(alpha * 255.0f, 0.0f, 255.0f) + 0.5f)}; + } + + CabanaColor darker(int factor = 200) const { + if (factor <= 0) return *this; + if (factor < 100) return lighter(10000 / factor); + auto [hue, saturation, value] = hsv(); + return fromHsv(hue, saturation, value * 100.0f / factor, a / 255.0f); + } + + CabanaColor lighter(int factor = 150) const { + if (factor <= 0) return *this; + if (factor < 100) return darker(10000 / factor); + auto [hue, saturation, value] = hsv(); + const float scaled_value = value * factor / 100.0f; + if (scaled_value > 1.0f) saturation = std::max(0.0f, saturation - (scaled_value - 1.0f)); + return fromHsv(hue, saturation, std::min(1.0f, scaled_value), a / 255.0f); + } + + constexpr int red() const { return r; } + constexpr int green() const { return g; } + constexpr int blue() const { return b; } + constexpr int alpha() const { return a; } + float alphaF() const { return a / 255.0f; } + void setAlphaF(float alpha) { a = static_cast(std::clamp(alpha * 255.0f, 0.0f, 255.0f) + 0.5f); } + + constexpr bool operator==(const CabanaColor &other) const { + return r == other.r && g == other.g && b == other.b && a == other.a; + } + +private: + struct Hsv { float hue; float saturation; float value; }; + Hsv hsv() const { + const float red = r / 255.0f, green = g / 255.0f, blue = b / 255.0f; + const float maximum = std::max({red, green, blue}); + const float minimum = std::min({red, green, blue}); + const float delta = maximum - minimum; + float hue = 0; + if (delta > 0) { + if (maximum == red) hue = std::fmod((green - blue) / delta, 6.0f) / 6.0f; + else if (maximum == green) hue = ((blue - red) / delta + 2.0f) / 6.0f; + else hue = ((red - green) / delta + 4.0f) / 6.0f; + if (hue < 0) hue += 1.0f; + } + return {hue, maximum == 0 ? 0 : delta / maximum, maximum}; + } +}; diff --git a/openpilot/tools/cabana/core/message_id.h b/openpilot/tools/cabana/core/message_id.h new file mode 100644 index 0000000000..ecac279631 --- /dev/null +++ b/openpilot/tools/cabana/core/message_id.h @@ -0,0 +1,27 @@ +#pragma once +#include +#include +#include +#include +#include + +constexpr int INVALID_SOURCE = 0xff; + +struct MessageId { + uint8_t source = 0; + uint32_t address = 0; + std::string toString() const { char b[64]; snprintf(b, sizeof(b), "%u:%X", source, address); return b; } + static MessageId fromString(const std::string &s) { + const auto p = s.find(':'); + if (p == std::string::npos) return {}; + return {.source = static_cast(std::stoul(s.substr(0, p))), .address = static_cast(std::stoul(s.substr(p + 1), nullptr, 16))}; + } + bool operator==(const MessageId &o) const { return source == o.source && address == o.address; } + bool operator!=(const MessageId &o) const { return !(*this == o); } + bool operator<(const MessageId &o) const { return std::tie(source, address) < std::tie(o.source, o.address); } + bool operator>(const MessageId &o) const { return o < *this; } +}; + +template <> struct std::hash { + size_t operator()(const MessageId &id) const noexcept { return std::hash{}(id.source) ^ (std::hash{}(id.address) << 1); } +}; diff --git a/openpilot/tools/cabana/core/settings.h b/openpilot/tools/cabana/core/settings.h new file mode 100644 index 0000000000..cad152de92 --- /dev/null +++ b/openpilot/tools/cabana/core/settings.h @@ -0,0 +1,34 @@ +#pragma once + +#include +#include + +constexpr int LIGHT_THEME = 1; +constexpr int DARK_THEME = 2; + +struct CabanaSettingsState { + enum DragDirection { MsbFirst, LsbFirst, AlwaysLE, AlwaysBE }; + + bool absolute_time = false; + int fps = 10; + int max_cached_minutes = 30; + int chart_height = 200; + int chart_column_count = 1; + int chart_range = 3 * 60; + int chart_series_type = 0; + int theme = 0; + int sparkline_range = 15; + bool multiple_lines_hex = false; + bool log_livestream = true; + bool suppress_defined_signals = false; + std::string log_path; + std::string last_dir; + std::string last_route_dir; + std::vector recent_files; + DragDirection drag_direction = MsbFirst; + + std::string recent_dbc_file; + std::string active_msg_id; + std::vector selected_msg_ids; + std::vector active_charts; +}; diff --git a/tools/cabana/dbc/dbc.cc b/openpilot/tools/cabana/dbc/dbc.cc similarity index 83% rename from tools/cabana/dbc/dbc.cc rename to openpilot/tools/cabana/dbc/dbc.cc index e9c869fce7..c8a794c73f 100644 --- a/tools/cabana/dbc/dbc.cc +++ b/openpilot/tools/cabana/dbc/dbc.cc @@ -1,11 +1,17 @@ #include "tools/cabana/dbc/dbc.h" #include +#include -#include "tools/cabana/utils/util.h" - -uint qHash(const MessageId &item) { - return qHash(item.source) ^ qHash(item.address); +namespace { +int numDecimals(double value) { + int decimals = 0; + while (decimals < 6 && std::fabs(value - std::round(value)) > 1e-9) { + value *= 10.0; + ++decimals; + } + return decimals; +} } // cabana::Msg @@ -22,7 +28,7 @@ cabana::Signal *cabana::Msg::addSignal(const cabana::Signal &sig) { return s; } -cabana::Signal *cabana::Msg::updateSignal(const QString &sig_name, const cabana::Signal &new_sig) { +cabana::Signal *cabana::Msg::updateSignal(const std::string &sig_name, const cabana::Signal &new_sig) { auto s = sig(sig_name); if (s) { *s = new_sig; @@ -31,7 +37,7 @@ cabana::Signal *cabana::Msg::updateSignal(const QString &sig_name, const cabana: return s; } -void cabana::Msg::removeSignal(const QString &sig_name) { +void cabana::Msg::removeSignal(const std::string &sig_name) { auto it = std::find_if(sigs.begin(), sigs.end(), [&](auto &s) { return s->name == sig_name; }); if (it != sigs.end()) { delete *it; @@ -57,7 +63,7 @@ cabana::Msg &cabana::Msg::operator=(const cabana::Msg &other) { return *this; } -cabana::Signal *cabana::Msg::sig(const QString &sig_name) const { +cabana::Signal *cabana::Msg::sig(const std::string &sig_name) const { auto it = std::find_if(sigs.begin(), sigs.end(), [&](auto &s) { return s->name == sig_name; }); return it != sigs.end() ? *it : nullptr; } @@ -69,17 +75,17 @@ int cabana::Msg::indexOf(const cabana::Signal *sig) const { return -1; } -QString cabana::Msg::newSignalName() { - QString new_name; +std::string cabana::Msg::newSignalName() { + std::string new_name; for (int i = 1; /**/; ++i) { - new_name = QString("NEW_SIGNAL_%1").arg(i); + new_name = "NEW_SIGNAL_" + std::to_string(i); if (sig(new_name) == nullptr) break; } return new_name; } void cabana::Msg::update() { - if (transmitter.isEmpty()) { + if (transmitter.empty()) { transmitter = DEFAULT_NODE_NAME; } mask.assign(size, 0x00); @@ -109,7 +115,7 @@ void cabana::Msg::update() { mask[i] |= ((1ULL << sz) - 1) << shift; - bits -= size; + bits -= sz; i = sig->is_little_endian ? i - 1 : i + 1; } } @@ -129,21 +135,21 @@ void cabana::Msg::update() { void cabana::Signal::update() { updateMsbLsb(*this); - if (receiver_name.isEmpty()) { + if (receiver_name.empty()) { receiver_name = DEFAULT_NODE_NAME; } float h = 19 * (float)lsb / 64.0; h = fmod(h, 1.0); - size_t hash = qHash(name); + size_t hash = std::hash{}(name); float s = 0.25 + 0.25 * (float)(hash & 0xff) / 255.0; float v = 0.75 + 0.25 * (float)((hash >> 8) & 0xff) / 255.0; - color = QColor::fromHsvF(h, s, v); - precision = std::max(num_decimals(factor), num_decimals(offset)); + color = CabanaColor::fromHsv(h, s, v); + precision = std::max(numDecimals(factor), numDecimals(offset)); } -QString cabana::Signal::formatValue(double value, bool with_unit) const { +std::string cabana::Signal::formatValue(double value, bool with_unit) const { // Show enum string int64_t raw_value = round((value - offset) / factor); for (const auto &[val, desc] : val_desc) { @@ -152,8 +158,10 @@ QString cabana::Signal::formatValue(double value, bool with_unit) const { } } - QString val_str = QString::number(value, 'f', precision); - if (with_unit && !unit.isEmpty()) { + char buf[64]; + snprintf(buf, sizeof(buf), "%.*f", precision, value); + std::string val_str(buf); + if (with_unit && !unit.empty()) { val_str += " " + unit; } return val_str; diff --git a/openpilot/tools/cabana/dbc/dbc.h b/openpilot/tools/cabana/dbc/dbc.h new file mode 100644 index 0000000000..585325d391 --- /dev/null +++ b/openpilot/tools/cabana/dbc/dbc.h @@ -0,0 +1,94 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include "tools/cabana/core/color.h" +#include "tools/cabana/core/message_id.h" + +const std::string UNTITLED = "untitled"; +const std::string DEFAULT_NODE_NAME = "XXX"; +constexpr int CAN_MAX_DATA_BYTES = 64; + +typedef std::vector> ValueDescription; + +namespace cabana { + +class Signal { +public: + Signal() = default; + Signal(const Signal &other) = default; + void update(); + bool getValue(const uint8_t *data, size_t data_size, double *val) const; + std::string formatValue(double value, bool with_unit = true) const; + bool operator==(const cabana::Signal &other) const; + inline bool operator!=(const cabana::Signal &other) const { return !(*this == other); } + + enum class Type { + Normal = 0, + Multiplexed, + Multiplexor + }; + + Type type = Type::Normal; + std::string name; + int start_bit, msb, lsb, size; + double factor = 1.0; + double offset = 0; + bool is_signed; + bool is_little_endian; + double min, max; + std::string unit; + std::string comment; + std::string receiver_name; + ValueDescription val_desc; + int precision = 0; + CabanaColor color; + + // Multiplexed + int multiplex_value = 0; + Signal *multiplexor = nullptr; +}; + +class Msg { +public: + Msg() = default; + Msg(const Msg &other) { *this = other; } + ~Msg(); + cabana::Signal *addSignal(const cabana::Signal &sig); + cabana::Signal *updateSignal(const std::string &sig_name, const cabana::Signal &sig); + void removeSignal(const std::string &sig_name); + Msg &operator=(const Msg &other); + int indexOf(const cabana::Signal *sig) const; + cabana::Signal *sig(const std::string &sig_name) const; + std::string newSignalName(); + void update(); + inline const std::vector &getSignals() const { return sigs; } + + uint32_t address; + std::string name; + uint32_t size; + std::string comment; + std::string transmitter; + std::vector sigs; + + std::vector mask; + cabana::Signal *multiplexor = nullptr; +}; + +} // namespace cabana + +// Helper functions +double get_raw_value(const uint8_t *data, size_t data_size, const cabana::Signal &sig); +void updateMsbLsb(cabana::Signal &s); +inline int flipBitPos(int start_bit) { return 8 * (start_bit / 8) + 7 - start_bit % 8; } +inline std::string doubleToString(double value) { + char buf[64]; + snprintf(buf, sizeof(buf), "%.*g", std::numeric_limits::digits10, value); + return buf; +} diff --git a/openpilot/tools/cabana/dbc/dbcfile.cc b/openpilot/tools/cabana/dbc/dbcfile.cc new file mode 100644 index 0000000000..99a5b71822 --- /dev/null +++ b/openpilot/tools/cabana/dbc/dbcfile.cc @@ -0,0 +1,271 @@ +#include "tools/cabana/dbc/dbcfile.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +std::string trim(const std::string &value) { + const auto first = value.find_first_not_of(" \t\r\n"); + if (first == std::string::npos) return {}; + return value.substr(first, value.find_last_not_of(" \t\r\n") - first + 1); +} + +bool startsWith(const std::string &value, const char *prefix) { + return value.rfind(prefix, 0) == 0; +} + +std::string unescapeComment(std::string value) { + for (size_t pos = 0; (pos = value.find("\\\"", pos)) != std::string::npos; ++pos) { + value.replace(pos, 2, "\""); + } + return trim(value); +} + +bool commentComplete(const std::string &line) { + bool escaped = false; + for (size_t i = 0; i < line.size(); ++i) { + if (line[i] == '\\' && !escaped) { + escaped = true; + continue; + } + if (line[i] == '"' && !escaped) { + size_t next = line.find_first_not_of(" \t\r\n", i + 1); + if (next != std::string::npos && line[next] == ';') return true; + } + escaped = false; + } + return false; +} + +} // namespace + +DBCFile::DBCFile(const std::string &dbc_file_name) { + std::ifstream file(dbc_file_name, std::ios::binary); + if (!file) throw std::runtime_error("Failed to open file."); + filename = dbc_file_name; + name_ = std::filesystem::path(dbc_file_name).stem().string(); + parse(std::string(std::istreambuf_iterator(file), std::istreambuf_iterator())); +} + +DBCFile::DBCFile(const std::string &name, const std::string &content) : name_(name) { + parse(content); +} + +bool DBCFile::save() { + assert(!filename.empty()); + return writeContents(filename); +} + +bool DBCFile::saveAs(const std::string &new_filename) { + filename = new_filename; + return save(); +} + +bool DBCFile::writeContents(const std::string &fn) { + std::ofstream file(fn, std::ios::binary | std::ios::trunc); + if (!file) return false; + file << generateDBC(); + return file.good(); +} + +void DBCFile::updateMsg(const MessageId &id, const std::string &name, uint32_t size, + const std::string &node, const std::string &comment) { + auto &m = msgs[id.address]; + m.address = id.address; + m.name = name; + m.size = size; + m.transmitter = node.empty() ? DEFAULT_NODE_NAME : node; + m.comment = comment; +} + +cabana::Msg *DBCFile::msg(uint32_t address) { + auto it = msgs.find(address); + return it != msgs.end() ? &it->second : nullptr; +} + +cabana::Msg *DBCFile::msg(const std::string &name) { + auto it = std::find_if(msgs.begin(), msgs.end(), [&name](auto &m) { return m.second.name == name; }); + return it != msgs.end() ? &it->second : nullptr; +} + +cabana::Signal *DBCFile::signal(uint32_t address, const std::string &name) { + auto m = msg(address); + return m ? m->sig(name) : nullptr; +} + +void DBCFile::parse(const std::string &content) { + msgs.clear(); + header.clear(); + std::istringstream input(content); + std::string raw_line; + cabana::Msg *current_msg = nullptr; + int multiplexor_cnt = 0; + int line_num = 0; + bool seen_first = false; + + while (std::getline(input, raw_line)) { + ++line_num; + const size_t first_nonspace = raw_line.find_first_not_of(" \t\r"); + std::string line = first_nonspace == std::string::npos ? std::string() : raw_line.substr(first_nonspace); + const int statement_line = line_num; + if ((startsWith(line, "CM_ BO_") || startsWith(line, "CM_ SG_ ")) && !commentComplete(line)) { + std::string continuation; + while (std::getline(input, continuation)) { + ++line_num; + line += "\n" + continuation; + if (commentComplete(line)) break; + } + } + + bool seen = true; + try { + if (startsWith(line, "BO_ ")) { + multiplexor_cnt = 0; + current_msg = parseBO(line); + } else if (startsWith(line, "SG_ ")) { + parseSG(line, current_msg, multiplexor_cnt); + } else if (startsWith(line, "VAL_ ")) { + parseVAL(line); + } else if (startsWith(line, "CM_ BO_")) { + parseCM_BO(line); + } else if (startsWith(line, "CM_ SG_ ")) { + parseCM_SG(line); + } else { + seen = false; + } + } catch (const std::exception &e) { + throw std::runtime_error("[" + filename + ":" + std::to_string(statement_line) + "]" + e.what() + ": " + line); + } + if (seen) seen_first = true; + else if (!seen_first) header += raw_line + "\n"; + } + for (auto &[_, message] : msgs) message.update(); +} + +cabana::Msg *DBCFile::parseBO(const std::string &line) { + static const std::regex pattern(R"(^BO_ ([[:alnum:]_]+) ([[:alnum:]_]+) *: ([[:alnum:]_]+) ([[:alnum:]_]+))"); + std::smatch match; + if (!std::regex_search(line, match, pattern)) throw std::runtime_error("Invalid BO_ line format"); + const uint32_t address = std::stoul(match[1].str()); + if (msgs.count(address)) throw std::runtime_error("Duplicate message address: " + std::to_string(address)); + auto &message = msgs[address]; + message.address = address; + message.name = match[2].str(); + message.size = std::stoul(match[3].str()); + message.transmitter = trim(match[4].str()); + return &message; +} + +void DBCFile::parseSG(const std::string &line, cabana::Msg *current_msg, int &multiplexor_cnt) { + static const std::regex pattern(R"dbc(^SG_ ([[:alnum:]_]+)(?: +([[:alnum:]_]+))? *: ([0-9]+)\|([0-9]+)@([0-9]+)([+-]) \(([0-9.+\-eE]+),([0-9.+\-eE]+)\) \[([0-9.+\-eE]+)\|([0-9.+\-eE]+)\] "(.*)" (.*))dbc"); + if (!current_msg) throw std::runtime_error("No Message"); + std::smatch match; + if (!std::regex_search(line, match, pattern)) throw std::runtime_error("Invalid SG_ line format"); + if (current_msg->sig(match[1].str())) throw std::runtime_error("Duplicate signal name"); + + cabana::Signal signal{}; + const std::string indicator = match[2].str(); + if (!indicator.empty()) { + if (indicator == "M") { + if (++multiplexor_cnt >= 2) throw std::runtime_error("Multiple multiplexor"); + signal.type = cabana::Signal::Type::Multiplexor; + } else { + signal.type = cabana::Signal::Type::Multiplexed; + signal.multiplex_value = indicator.size() > 1 ? std::stoi(indicator.substr(1)) : 0; + } + } + signal.name = match[1].str(); + signal.start_bit = std::stoi(match[3].str()); + signal.size = std::stoi(match[4].str()); + signal.is_little_endian = match[5].str() == "1"; + signal.is_signed = match[6].str() == "-"; + signal.factor = std::stod(match[7].str()); + signal.offset = std::stod(match[8].str()); + signal.min = std::stod(match[9].str()); + signal.max = std::stod(match[10].str()); + signal.unit = match[11].str(); + signal.receiver_name = trim(match[12].str()); + current_msg->sigs.push_back(new cabana::Signal(signal)); +} + +void DBCFile::parseCM_BO(const std::string &line) { + std::istringstream prefix(line.substr(7)); + uint32_t address = 0; + prefix >> address; + const size_t first_quote = line.find('"'); + const size_t last_quote = line.rfind('"'); + if (!prefix || first_quote == std::string::npos || last_quote <= first_quote) { + throw std::runtime_error("Invalid message comment format"); + } + if (auto message = msg(address)) message->comment = unescapeComment(line.substr(first_quote + 1, last_quote - first_quote - 1)); +} + +void DBCFile::parseCM_SG(const std::string &line) { + std::istringstream prefix(line.substr(7)); + uint32_t address = 0; + std::string name; + prefix >> address >> name; + const size_t first_quote = line.find('"'); + const size_t last_quote = line.rfind('"'); + if (!prefix || name.empty() || first_quote == std::string::npos || last_quote <= first_quote) { + throw std::runtime_error("Invalid CM_ SG_ line format"); + } + if (auto sig = signal(address, name)) sig->comment = unescapeComment(line.substr(first_quote + 1, last_quote - first_quote - 1)); +} + +void DBCFile::parseVAL(const std::string &line) { + static const std::regex header_pattern(R"(^VAL_ ([[:alnum:]_]+) ([[:alnum:]_]+) (.*))"); + static const std::regex entry_pattern(R"dbc(([+-]?[0-9]+(?:\.[0-9]+)?)\s+"([^"]*)")dbc"); + std::smatch match; + if (!std::regex_search(line, match, header_pattern)) throw std::runtime_error("invalid VAL_ line format"); + if (auto sig = signal(std::stoul(match[1].str()), match[2].str())) { + const std::string entries = match[3].str(); + for (std::sregex_iterator it(entries.begin(), entries.end(), entry_pattern), end; it != end; ++it) { + sig->val_desc.emplace_back(std::stod((*it)[1].str()), trim((*it)[2].str())); + } + } +} + +std::string DBCFile::generateDBC() { + std::string dbc_string, comment, val_desc; + for (const auto &[address, m] : msgs) { + const std::string &transmitter = m.transmitter.empty() ? DEFAULT_NODE_NAME : m.transmitter; + dbc_string += "BO_ " + std::to_string(address) + " " + m.name + ": " + std::to_string(m.size) + " " + transmitter + "\n"; + if (!m.comment.empty()) { + std::string escaped = m.comment; + for (size_t pos = 0; (pos = escaped.find('"', pos)) != std::string::npos; pos += 2) escaped.replace(pos, 1, "\\\""); + comment += "CM_ BO_ " + std::to_string(address) + " \"" + escaped + "\";\n"; + } + for (auto sig : m.getSignals()) { + std::string mux; + if (sig->type == cabana::Signal::Type::Multiplexor) mux = "M "; + else if (sig->type == cabana::Signal::Type::Multiplexed) mux = "m" + std::to_string(sig->multiplex_value) + " "; + const std::string &receiver = sig->receiver_name.empty() ? DEFAULT_NODE_NAME : sig->receiver_name; + dbc_string += " SG_ " + sig->name + " " + mux + ": " + std::to_string(sig->start_bit) + "|" + std::to_string(sig->size) + "@" + + (sig->is_little_endian ? "1" : "0") + (sig->is_signed ? "-" : "+") + + " (" + doubleToString(sig->factor) + "," + doubleToString(sig->offset) + ")" + + " [" + doubleToString(sig->min) + "|" + doubleToString(sig->max) + "] \"" + sig->unit + "\" " + receiver + "\n"; + if (!sig->comment.empty()) { + std::string escaped = sig->comment; + for (size_t pos = 0; (pos = escaped.find('"', pos)) != std::string::npos; pos += 2) escaped.replace(pos, 1, "\\\""); + comment += "CM_ SG_ " + std::to_string(address) + " " + sig->name + " \"" + escaped + "\";\n"; + } + if (!sig->val_desc.empty()) { + std::string text; + for (const auto &[value, description] : sig->val_desc) { + if (!text.empty()) text += " "; + text += doubleToString(value) + " \"" + description + "\""; + } + val_desc += "VAL_ " + std::to_string(address) + " " + sig->name + " " + text + ";\n"; + } + } + dbc_string += "\n"; + } + return header + dbc_string + comment + val_desc; +} diff --git a/openpilot/tools/cabana/dbc/dbcfile.h b/openpilot/tools/cabana/dbc/dbcfile.h new file mode 100644 index 0000000000..13841a94fa --- /dev/null +++ b/openpilot/tools/cabana/dbc/dbcfile.h @@ -0,0 +1,44 @@ +#pragma once + +#include +#include + +#include "tools/cabana/dbc/dbc.h" + +class DBCFile { +public: + DBCFile(const std::string &dbc_file_name); + DBCFile(const std::string &name, const std::string &content); + ~DBCFile() {} + + bool save(); + bool saveAs(const std::string &new_filename); + bool writeContents(const std::string &fn); + std::string generateDBC(); + + void updateMsg(const MessageId &id, const std::string &name, uint32_t size, const std::string &node, const std::string &comment); + inline void removeMsg(const MessageId &id) { msgs.erase(id.address); } + + inline const std::map &getMessages() const { return msgs; } + cabana::Msg *msg(uint32_t address); + cabana::Msg *msg(const std::string &name); + inline cabana::Msg *msg(const MessageId &id) { return msg(id.address); } + cabana::Signal *signal(uint32_t address, const std::string &name); + + inline std::string name() const { return name_.empty() ? "untitled" : name_; } + inline bool isEmpty() const { return msgs.empty() && name_.empty(); } + + std::string filename; + +private: + void parse(const std::string &content); + cabana::Msg *parseBO(const std::string &line); + void parseSG(const std::string &line, cabana::Msg *current_msg, int &multiplexor_cnt); + void parseCM_BO(const std::string &line); + void parseCM_SG(const std::string &line); + void parseVAL(const std::string &line); + + std::string header; + std::map msgs; + std::string name_; +}; diff --git a/openpilot/tools/cabana/dbc/dbcmanager.cc b/openpilot/tools/cabana/dbc/dbcmanager.cc new file mode 100644 index 0000000000..7a95a4f809 --- /dev/null +++ b/openpilot/tools/cabana/dbc/dbcmanager.cc @@ -0,0 +1,182 @@ +#include "tools/cabana/dbc/dbcmanager.h" + +#include +#include +#include + +bool DBCManager::open(const SourceSet &sources, const std::string &dbc_file_name, std::string *error) { + try { + auto it = std::find_if(dbc_files.begin(), dbc_files.end(), + [&](auto &f) { return f.second && f.second->filename == dbc_file_name; }); + auto file = (it != dbc_files.end()) ? it->second : std::make_shared(dbc_file_name); + for (auto s : sources) { + dbc_files[s] = file; + } + } catch (std::exception &e) { + if (error) *error = e.what(); + return false; + } + + if (callbacks_.file_changed) callbacks_.file_changed(); + return true; +} + +bool DBCManager::open(const SourceSet &sources, const std::string &name, const std::string &content, std::string *error) { + try { + auto file = std::make_shared(name, content); + for (auto s : sources) { + dbc_files[s] = file; + } + } catch (std::exception &e) { + if (error) *error = e.what(); + return false; + } + + if (callbacks_.file_changed) callbacks_.file_changed(); + return true; +} + +void DBCManager::close(const SourceSet &sources) { + for (auto s : sources) { + dbc_files[s] = nullptr; + } + if (callbacks_.file_changed) callbacks_.file_changed(); +} + +void DBCManager::close(DBCFile *dbc_file) { + for (auto &[_, f] : dbc_files) { + if (f.get() == dbc_file) f = nullptr; + } + if (callbacks_.file_changed) callbacks_.file_changed(); +} + +void DBCManager::closeAll() { + dbc_files.clear(); + if (callbacks_.file_changed) callbacks_.file_changed(); +} + +void DBCManager::addSignal(const MessageId &id, const cabana::Signal &sig) { + if (auto m = msg(id)) { + if (auto s = m->addSignal(sig)) { + if (callbacks_.signal_added) callbacks_.signal_added(id, s); + if (callbacks_.mask_updated) callbacks_.mask_updated(); + } + } +} + +void DBCManager::updateSignal(const MessageId &id, const std::string &sig_name, const cabana::Signal &sig) { + if (auto m = msg(id)) { + if (auto s = m->updateSignal(sig_name, sig)) { + if (callbacks_.signal_updated) callbacks_.signal_updated(s); + if (callbacks_.mask_updated) callbacks_.mask_updated(); + } + } +} + +void DBCManager::removeSignal(const MessageId &id, const std::string &sig_name) { + if (auto m = msg(id)) { + if (auto s = m->sig(sig_name)) { + if (callbacks_.signal_removed) callbacks_.signal_removed(s); + m->removeSignal(sig_name); + if (callbacks_.mask_updated) callbacks_.mask_updated(); + } + } +} + +void DBCManager::updateMsg(const MessageId &id, const std::string &name, uint32_t size, const std::string &node, const std::string &comment) { + auto dbc_file = findDBCFile(id); + assert(dbc_file); // This should be impossible + dbc_file->updateMsg(id, name, size, node, comment); + if (callbacks_.msg_updated) callbacks_.msg_updated(id); +} + +void DBCManager::removeMsg(const MessageId &id) { + auto dbc_file = findDBCFile(id); + assert(dbc_file); // This should be impossible + dbc_file->removeMsg(id); + if (callbacks_.msg_removed) callbacks_.msg_removed(id); + if (callbacks_.mask_updated) callbacks_.mask_updated(); +} + +std::string DBCManager::newMsgName(const MessageId &id) { + char buf[64]; + snprintf(buf, sizeof(buf), "NEW_MSG_%X", id.address); + return buf; +} + +std::string DBCManager::newSignalName(const MessageId &id) { + auto m = msg(id); + return m ? m->newSignalName() : ""; +} + +const std::map &DBCManager::getMessages(uint8_t source) { + static std::map empty_msgs; + auto dbc_file = findDBCFile(source); + return dbc_file ? dbc_file->getMessages() : empty_msgs; +} + +cabana::Msg *DBCManager::msg(const MessageId &id) { + auto dbc_file = findDBCFile(id); + return dbc_file ? dbc_file->msg(id) : nullptr; +} + +cabana::Msg *DBCManager::msg(uint8_t source, const std::string &name) { + auto dbc_file = findDBCFile(source); + return dbc_file ? dbc_file->msg(name) : nullptr; +} + +std::vector DBCManager::signalNames() { + // Used for autocompletion + std::set names; + for (auto &f : allDBCFiles()) { + for (auto &[_, m] : f->getMessages()) { + for (auto sig : m.getSignals()) { + names.insert(sig->name); + } + } + } + std::vector ret(names.begin(), names.end()); + std::sort(ret.begin(), ret.end()); + return ret; +} + +int DBCManager::nonEmptyDBCCount() { + auto files = allDBCFiles(); + return std::count_if(files.cbegin(), files.cend(), [](auto &f) { return !f->isEmpty(); }); +} + +DBCFile *DBCManager::findDBCFile(const uint8_t source) { + // Find DBC file that matches id.source, fall back to SOURCE_ALL if no specific DBC is found + auto it = dbc_files.count(source) ? dbc_files.find(source) : dbc_files.find(-1); + return it != dbc_files.end() ? it->second.get() : nullptr; +} + +std::set DBCManager::allDBCFiles() { + std::set files; + for (const auto &[_, f] : dbc_files) { + if (f) files.insert(f.get()); + } + return files; +} + +const SourceSet DBCManager::sources(const DBCFile *dbc_file) const { + SourceSet sources; + for (auto &[s, f] : dbc_files) { + if (f.get() == dbc_file) sources.insert(s); + } + return sources; +} + +std::string toString(const SourceSet &ss) { + std::string result; + for (int source : ss) { + if (!result.empty()) result += ", "; + result += (source == -1) ? "all" : std::to_string(source); + } + return result; +} + +DBCManager *dbc() { + static DBCManager dbc_manager; + return &dbc_manager; +} diff --git a/openpilot/tools/cabana/dbc/dbcmanager.h b/openpilot/tools/cabana/dbc/dbcmanager.h new file mode 100644 index 0000000000..5a09fae03d --- /dev/null +++ b/openpilot/tools/cabana/dbc/dbcmanager.h @@ -0,0 +1,70 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "tools/cabana/dbc/dbcfile.h" + +typedef std::set SourceSet; +const SourceSet SOURCE_ALL = {-1}; +inline bool operator<(const std::shared_ptr &l, const std::shared_ptr &r) { return l.get() < r.get(); } + +class DBCManager { +public: + struct Callbacks { + std::function signal_added; + std::function signal_removed; + std::function signal_updated; + std::function msg_updated; + std::function msg_removed; + std::function file_changed; + std::function mask_updated; + }; + + DBCManager() = default; + bool open(const SourceSet &sources, const std::string &dbc_file_name, std::string *error = nullptr); + bool open(const SourceSet &sources, const std::string &name, const std::string &content, std::string *error = nullptr); + void close(const SourceSet &sources); + void close(DBCFile *dbc_file); + void closeAll(); + + void addSignal(const MessageId &id, const cabana::Signal &sig); + void updateSignal(const MessageId &id, const std::string &sig_name, const cabana::Signal &sig); + void removeSignal(const MessageId &id, const std::string &sig_name); + + void updateMsg(const MessageId &id, const std::string &name, uint32_t size, const std::string &node, const std::string &comment); + void removeMsg(const MessageId &id); + + std::string newMsgName(const MessageId &id); + std::string newSignalName(const MessageId &id); + + const std::map &getMessages(uint8_t source); + cabana::Msg *msg(const MessageId &id); + cabana::Msg* msg(uint8_t source, const std::string &name); + + std::vector signalNames(); + inline int dbcCount() { return allDBCFiles().size(); } + int nonEmptyDBCCount(); + + const SourceSet sources(const DBCFile *dbc_file) const; + DBCFile *findDBCFile(const uint8_t source); + inline DBCFile *findDBCFile(const MessageId &id) { return findDBCFile(id.source); } + std::set allDBCFiles(); + void setCallbacks(Callbacks callbacks) { callbacks_ = std::move(callbacks); } + +private: + std::map> dbc_files; + Callbacks callbacks_; +}; + +DBCManager *dbc(); + +std::string toString(const SourceSet &ss); +inline std::string msgName(const MessageId &id) { + auto msg = dbc()->msg(id); + return msg ? msg->name : UNTITLED; +} diff --git a/openpilot/tools/cabana/dbc/dbcqt.cc b/openpilot/tools/cabana/dbc/dbcqt.cc new file mode 100644 index 0000000000..4354caf3f5 --- /dev/null +++ b/openpilot/tools/cabana/dbc/dbcqt.cc @@ -0,0 +1,18 @@ +#include "tools/cabana/dbc/dbcqt.h" + +QtDBCNotifier::QtDBCNotifier(QObject *parent) : QObject(parent) { + dbc()->setCallbacks({ + .signal_added = [this](MessageId id, const cabana::Signal *sig) { emit signalAdded(id, sig); }, + .signal_removed = [this](const cabana::Signal *sig) { emit signalRemoved(sig); }, + .signal_updated = [this](const cabana::Signal *sig) { emit signalUpdated(sig); }, + .msg_updated = [this](MessageId id) { emit msgUpdated(id); }, + .msg_removed = [this](MessageId id) { emit msgRemoved(id); }, + .file_changed = [this]() { emit DBCFileChanged(); }, + .mask_updated = [this]() { emit maskUpdated(); }, + }); +} + +QtDBCNotifier *dbcNotifier() { + static QtDBCNotifier notifier; + return ¬ifier; +} diff --git a/openpilot/tools/cabana/dbc/dbcqt.h b/openpilot/tools/cabana/dbc/dbcqt.h new file mode 100644 index 0000000000..b889f854ed --- /dev/null +++ b/openpilot/tools/cabana/dbc/dbcqt.h @@ -0,0 +1,27 @@ +#pragma once + +#include +#include + +#include "tools/cabana/dbc/dbcmanager.h" + +Q_DECLARE_METATYPE(MessageId) +Q_DECLARE_METATYPE(ValueDescription) + +class QtDBCNotifier : public QObject { + Q_OBJECT + +public: + explicit QtDBCNotifier(QObject *parent = nullptr); + +signals: + void signalAdded(MessageId id, const cabana::Signal *sig); + void signalRemoved(const cabana::Signal *sig); + void signalUpdated(const cabana::Signal *sig); + void msgUpdated(MessageId id); + void msgRemoved(MessageId id); + void DBCFileChanged(); + void maskUpdated(); +}; + +QtDBCNotifier *dbcNotifier(); diff --git a/tools/cabana/dbc/generate_dbc_json.py b/openpilot/tools/cabana/dbc/generate_dbc_json.py similarity index 99% rename from tools/cabana/dbc/generate_dbc_json.py rename to openpilot/tools/cabana/dbc/generate_dbc_json.py index d002a50ef8..13b6799ffb 100755 --- a/tools/cabana/dbc/generate_dbc_json.py +++ b/openpilot/tools/cabana/dbc/generate_dbc_json.py @@ -1,7 +1,6 @@ #!/usr/bin/env python3 import argparse import json - from opendbc.car import Bus from opendbc.car.fingerprints import MIGRATION from opendbc.car.values import PLATFORMS diff --git a/openpilot/tools/cabana/deqt.md b/openpilot/tools/cabana/deqt.md new file mode 100644 index 0000000000..3bef2d7ab0 --- /dev/null +++ b/openpilot/tools/cabana/deqt.md @@ -0,0 +1,53 @@ +we're migrating cabana away from Qt and to eventually entirely use imgui + +we are doing it incrementally, in small pieces that are easy to execute and verify. +we will repeat this until we're all done. + +# Cabana Qt API inventory + +these are all still in cabana. we remove them from this list once they're gone. +each bullet is an atomic unit of work. + +our workflow is: +- pick the easiest of the bulleted items from below +- implement it and make] sure it builds +- spin up reviewer agents to review the code in a clean context and a separate one to click around in xvfb as a gui test +- then implement the fixes from the above reviewer agents + +some rules +- do not add more Qt usage ever + +- `QObject`, `QMetaObject`, `QMetaType` +- `QApplication`, `QCoreApplication`, `QGuiApplication` +- `QString`, `QStringList`, `QStringBuilder`, `QChar`, `QLatin1Char` +- `QVariant` +- `QTimer` +- `QWidget`, `QMainWindow`, `QWindow` +- `QDialog`, `QDialogButtonBox`, `QMessageBox`, `QProgressDialog` +- `QFileDialog` +- `QMenu`, `QMenuBar`, `QAction`, `QActionGroup`, `QWidgetAction` +- `QToolBar`, `QToolButton`, `QPushButton` +- `QCheckBox`, `QRadioButton`, `QButtonGroup`, `QAbstractButton` +- `QComboBox`, `QLineEdit`, `QTextEdit`, `QSpinBox`, `QSlider` +- `QLabel`, `QGroupBox`, `QFrame` +- `QTabBar`, `QTabWidget`, `QSplitter`, `QScrollArea`, `QScrollBar` +- `QDockWidget`, `QStatusBar`, `QProgressBar` +- `QFormLayout`, `QGridLayout`, `QHBoxLayout`, `QVBoxLayout` +- `QSizePolicy` +- `QAbstractItemModel`, `QAbstractTableModel`, `QModelIndex` +- `QAbstractItemView`, `QTableView`, `QTreeView` +- `QTableWidget`, `QTableWidgetItem`, `QListWidget`, `QListWidgetItem` +- `QItemSelection`, `QItemSelectionModel`, `QItemSelectionRange` +- `QHeaderView`, `QStyledItemDelegate`, `QStyleOptionViewItem` +- `QValidator`, `QIntValidator` +- `QColor`, `QRgb`, `QPalette` +- `QBrush`, `QPen` +- `QPainter`, `QPainterPath`, `QStylePainter` +- `QImage`, `QPixmap`, `QPixmapCache`, `QStaticText` +- `QFont`, `QFontDatabase`, `QFontMetrics`, `QTextDocument` +- `QStyle`, `QStyleOption`, `QStyleOptionFrame`, `QStyleOptionSlider` +- `QPoint`, `QPointF`, `QRect`, `QRectF`, `QRegion` +- `QSize`, `QSizeF` +- `QEvent`, `QPaintEvent`, `QResizeEvent`, `QShowEvent`, `QCloseEvent` +- `QMouseEvent`, `QWheelEvent`, `QNativeGestureEvent`, `QContextMenuEvent` +- `QKeySequence`, `QShortcut`, `QToolTip` diff --git a/tools/cabana/detailwidget.cc b/openpilot/tools/cabana/detailwidget.cc similarity index 81% rename from tools/cabana/detailwidget.cc rename to openpilot/tools/cabana/detailwidget.cc index 2e213988bc..6b62f54959 100644 --- a/tools/cabana/detailwidget.cc +++ b/openpilot/tools/cabana/detailwidget.cc @@ -1,8 +1,10 @@ #include "tools/cabana/detailwidget.h" +#include "tools/cabana/dbc/dbcqt.h" #include #include #include +#include #include #include "tools/cabana/commands.h" @@ -55,8 +57,8 @@ DetailWidget::DetailWidget(ChartsWidget *charts, QWidget *parent) : charts(chart QObject::connect(signal_view, &SignalView::highlight, binary_view, &BinaryView::highlight); QObject::connect(tab_widget, &QTabWidget::currentChanged, [this]() { updateState(); }); QObject::connect(can, &AbstractStream::msgsReceived, this, &DetailWidget::updateState); - QObject::connect(dbc(), &DBCManager::DBCFileChanged, this, &DetailWidget::refresh); - QObject::connect(UndoStack::instance(), &QUndoStack::indexChanged, this, &DetailWidget::refresh); + QObject::connect(dbcNotifier(), &QtDBCNotifier::DBCFileChanged, this, &DetailWidget::refresh); + QObject::connect(undoNotifier(), &QtUndoNotifier::indexChanged, this, &DetailWidget::refresh); QObject::connect(tabbar, &QTabBar::customContextMenuRequested, this, &DetailWidget::showTabBarContextMenu); QObject::connect(tabbar, &QTabBar::currentChanged, [this](int index) { if (index != -1) { @@ -117,19 +119,24 @@ void DetailWidget::showTabBarContextMenu(const QPoint &pt) { } } -void DetailWidget::setMessage(const MessageId &message_id) { - if (std::exchange(msg_id, message_id) == message_id) return; - - tabbar->blockSignals(true); +int DetailWidget::findOrAddTab(const MessageId& message_id) { int index = tabbar->count() - 1; for (/**/; index >= 0; --index) { if (tabbar->tabData(index).value() == message_id) break; } if (index == -1) { - index = tabbar->addTab(message_id.toString()); + index = tabbar->addTab(QString::fromStdString(message_id.toString())); tabbar->setTabData(index, QVariant::fromValue(message_id)); - tabbar->setTabToolTip(index, msgName(message_id)); + tabbar->setTabToolTip(index, QString::fromStdString(msgName(message_id))); } + return index; +} + +void DetailWidget::setMessage(const MessageId &message_id) { + if (std::exchange(msg_id, message_id) == message_id) return; + + tabbar->blockSignals(true); + int index = findOrAddTab(message_id); tabbar->setCurrentIndex(index); tabbar->blockSignals(false); @@ -141,6 +148,29 @@ void DetailWidget::setMessage(const MessageId &message_id) { setUpdatesEnabled(true); } +std::pair DetailWidget::serializeMessageIds() const { + QStringList msgs; + for (int i = 0; i < tabbar->count(); ++i) { + MessageId id = tabbar->tabData(i).value(); + msgs.append(QString::fromStdString(id.toString())); + } + return std::make_pair(QString::fromStdString(msg_id.toString()), msgs); +} + +void DetailWidget::restoreTabs(const QString active_msg_id, const QStringList& msg_ids) { + tabbar->blockSignals(true); + for (const auto& str_id : msg_ids) { + MessageId id = MessageId::fromString(str_id.toStdString()); + if (dbc()->msg(id) != nullptr) + findOrAddTab(id); + } + tabbar->blockSignals(false); + + auto active_id = MessageId::fromString(active_msg_id.toStdString()); + if (dbc()->msg(active_id) != nullptr) + setMessage(active_id); +} + void DetailWidget::refresh() { QStringList warnings; auto msg = dbc()->msg(msg_id); @@ -151,10 +181,10 @@ void DetailWidget::refresh() { warnings.push_back(tr("Message size (%1) is incorrect.").arg(msg->size)); } for (auto s : binary_view->getOverlappingSignals()) { - warnings.push_back(tr("%1 has overlapping bits.").arg(s->name)); + warnings.push_back(tr("%1 has overlapping bits.").arg(QString::fromStdString(s->name))); } } - QString msg_name = msg ? QString("%1 (%2)").arg(msg->name, msg->transmitter) : msgName(msg_id); + QString msg_name = msg ? QString("%1 (%2)").arg(QString::fromStdString(msg->name), QString::fromStdString(msg->transmitter)) : QString::fromStdString(msgName(msg_id)); name_label->setText(msg_name); name_label->setToolTip(msg_name); action_remove_msg->setEnabled(msg != nullptr); @@ -179,22 +209,22 @@ void DetailWidget::updateState(const std::set *msgs) { void DetailWidget::editMsg() { auto msg = dbc()->msg(msg_id); int size = msg ? msg->size : can->lastMessage(msg_id).dat.size(); - EditMessageDialog dlg(msg_id, msgName(msg_id), size, this); + EditMessageDialog dlg(msg_id, QString::fromStdString(msgName(msg_id)), size, this); if (dlg.exec()) { - UndoStack::push(new EditMsgCommand(msg_id, dlg.name_edit->text().trimmed(), dlg.size_spin->value(), - dlg.node->text().trimmed(), dlg.comment_edit->toPlainText().trimmed())); + UndoStack::instance()->push(new EditMsgCommand(msg_id, dlg.name_edit->text().trimmed().toStdString(), dlg.size_spin->value(), + dlg.node->text().trimmed().toStdString(), dlg.comment_edit->toPlainText().trimmed().toStdString())); } } void DetailWidget::removeMsg() { - UndoStack::push(new RemoveMsgCommand(msg_id)); + UndoStack::instance()->push(new RemoveMsgCommand(msg_id)); } // EditMessageDialog EditMessageDialog::EditMessageDialog(const MessageId &msg_id, const QString &title, int size, QWidget *parent) : original_name(title), msg_id(msg_id), QDialog(parent) { - setWindowTitle(tr("Edit message: %1").arg(msg_id.toString())); + setWindowTitle(tr("Edit message: %1").arg(QString::fromStdString(msg_id.toString()))); QFormLayout *form_layout = new QFormLayout(this); form_layout->addRow("", error_label = new QLabel); @@ -212,8 +242,8 @@ EditMessageDialog::EditMessageDialog(const MessageId &msg_id, const QString &tit form_layout->addRow(btn_box = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel)); if (auto msg = dbc()->msg(msg_id)) { - node->setText(msg->transmitter); - comment_edit->setText(msg->comment); + node->setText(QString::fromStdString(msg->transmitter)); + comment_edit->setText(QString::fromStdString(msg->comment)); } validateName(name_edit->text()); setFixedWidth(parent->width() * 0.9); @@ -223,10 +253,10 @@ EditMessageDialog::EditMessageDialog(const MessageId &msg_id, const QString &tit } void EditMessageDialog::validateName(const QString &text) { - bool valid = text.compare(UNTITLED, Qt::CaseInsensitive) != 0; + bool valid = text.compare(QString::fromStdString(UNTITLED), Qt::CaseInsensitive) != 0; error_label->setVisible(false); if (!text.isEmpty() && valid && text != original_name) { - valid = dbc()->msg(msg_id.source, text) == nullptr; + valid = dbc()->msg(msg_id.source, text.toStdString()) == nullptr; if (!valid) { error_label->setText(tr("Name already exists")); error_label->setVisible(true); @@ -243,13 +273,13 @@ CenterWidget::CenterWidget(QWidget *parent) : QWidget(parent) { main_layout->addWidget(welcome_widget = createWelcomeWidget()); } -void CenterWidget::setMessage(const MessageId &msg_id) { +DetailWidget* CenterWidget::ensureDetailWidget() { if (!detail_widget) { delete welcome_widget; welcome_widget = nullptr; layout()->addWidget(detail_widget = new DetailWidget(((MainWindow*)parentWidget())->charts_widget, this)); } - detail_widget->setMessage(msg_id); + return detail_widget; } void CenterWidget::clear() { diff --git a/tools/cabana/detailwidget.h b/openpilot/tools/cabana/detailwidget.h similarity index 78% rename from tools/cabana/detailwidget.h rename to openpilot/tools/cabana/detailwidget.h index 47304fbdc5..0fe1535c7a 100644 --- a/tools/cabana/detailwidget.h +++ b/openpilot/tools/cabana/detailwidget.h @@ -6,11 +6,11 @@ #include #include -#include "selfdrive/ui/qt/widgets/controls.h" #include "tools/cabana/binaryview.h" #include "tools/cabana/chart/chartswidget.h" #include "tools/cabana/historylog.h" #include "tools/cabana/signalview.h" +#include "tools/cabana/utils/elidedlabel.h" class EditMessageDialog : public QDialog { public: @@ -34,9 +34,12 @@ public: DetailWidget(ChartsWidget *charts, QWidget *parent); void setMessage(const MessageId &message_id); void refresh(); + std::pair serializeMessageIds() const; + void restoreTabs(const QString active_msg_id, const QStringList &msg_ids); private: void createToolBar(); + int findOrAddTab(const MessageId& message_id); void showTabBarContextMenu(const QPoint &pt); void editMsg(); void removeMsg(); @@ -60,7 +63,9 @@ class CenterWidget : public QWidget { Q_OBJECT public: CenterWidget(QWidget *parent); - void setMessage(const MessageId &msg_id); + void setMessage(const MessageId &message_id) { ensureDetailWidget()->setMessage(message_id); } + DetailWidget* getDetailWidget() { return detail_widget; } + DetailWidget* ensureDetailWidget(); void clear(); private: diff --git a/tools/cabana/historylog.cc b/openpilot/tools/cabana/historylog.cc similarity index 89% rename from tools/cabana/historylog.cc rename to openpilot/tools/cabana/historylog.cc index 7e73da55f0..3fd569c648 100644 --- a/tools/cabana/historylog.cc +++ b/openpilot/tools/cabana/historylog.cc @@ -1,4 +1,5 @@ #include "tools/cabana/historylog.h" +#include "tools/cabana/dbc/dbcqt.h" #include @@ -14,7 +15,7 @@ QVariant HistoryLogModel::data(const QModelIndex &index, int role) const { const int col = index.column(); if (role == Qt::DisplayRole) { if (col == 0) return QString::number(can->toSeconds(m.mono_time), 'f', 3); - if (!isHexMode()) return sigs[col - 1]->formatValue(m.sig_values[col - 1], false); + if (!isHexMode()) return QString::fromStdString(sigs[col - 1]->formatValue(m.sig_values[col - 1], false)); } else if (role == Qt::TextAlignmentRole) { return (uint32_t)(Qt::AlignRight | Qt::AlignVCenter); } @@ -49,12 +50,12 @@ QVariant HistoryLogModel::headerData(int section, Qt::Orientation orientation, i if (section == 0) return "Time"; if (isHexMode()) return "Data"; - QString name = sigs[section - 1]->name; - QString unit = sigs[section - 1]->unit; + QString name = QString::fromStdString(sigs[section - 1]->name); + QString unit = QString::fromStdString(sigs[section - 1]->unit); return unit.isEmpty() ? name : QString("%1 (%2)").arg(name, unit); } else if (role == Qt::BackgroundRole && section > 0 && !isHexMode()) { // Alpha-blend the signal color with the background to ensure contrast - QColor sigColor = sigs[section - 1]->color; + QColor sigColor = toQColor(sigs[section - 1]->color); sigColor.setAlpha(128); return QBrush(sigColor); } @@ -153,7 +154,7 @@ void HeaderView::paintSection(QPainter *painter, const QRect &rect, int logicalI painter->fillRect(rect, bg_role.value()); } QString text = model()->headerData(logicalIndex, Qt::Horizontal, Qt::DisplayRole).toString(); - painter->setPen(palette().color(settings.theme == DARK_THEME ? QPalette::BrightText : QPalette::Text)); + painter->setPen(palette().color(utils::isDarkTheme() ? QPalette::BrightText : QPalette::Text)); painter->drawText(rect.adjusted(5, 3, -5, -3), defaultAlignment(), text.replace(QChar('_'), ' ')); } @@ -207,8 +208,8 @@ LogsWidget::LogsWidget(QWidget *parent) : QFrame(parent) { QObject::connect(value_edit, &QLineEdit::textEdited, this, &LogsWidget::filterChanged); QObject::connect(export_btn, &QToolButton::clicked, this, &LogsWidget::exportToCSV); QObject::connect(can, &AbstractStream::seekedTo, model, &HistoryLogModel::reset); - QObject::connect(dbc(), &DBCManager::DBCFileChanged, model, &HistoryLogModel::reset); - QObject::connect(UndoStack::instance(), &QUndoStack::indexChanged, model, &HistoryLogModel::reset); + QObject::connect(dbcNotifier(), &QtDBCNotifier::DBCFileChanged, model, &HistoryLogModel::reset); + QObject::connect(undoNotifier(), &QtUndoNotifier::indexChanged, model, &HistoryLogModel::reset); QObject::connect(model, &HistoryLogModel::modelReset, this, &LogsWidget::modelReset); QObject::connect(model, &HistoryLogModel::rowsInserted, [this]() { export_btn->setEnabled(true); }); } @@ -216,7 +217,7 @@ LogsWidget::LogsWidget(QWidget *parent) : QFrame(parent) { void LogsWidget::modelReset() { signals_cb->clear(); for (auto s : model->sigs) { - signals_cb->addItem(s->name); + signals_cb->addItem(QString::fromStdString(s->name)); } export_btn->setEnabled(false); value_edit->clear(); @@ -238,11 +239,11 @@ void LogsWidget::filterChanged() { } void LogsWidget::exportToCSV() { - QString dir = QString("%1/%2_%3.csv").arg(settings.last_dir).arg(can->routeName()).arg(msgName(model->msg_id)); - QString fn = QFileDialog::getSaveFileName(this, QString("Export %1 to CSV file").arg(msgName(model->msg_id)), + QString dir = QString("%1/%2_%3.csv").arg(QString::fromStdString(settings.last_dir)).arg(QString::fromStdString(can->routeName())).arg(QString::fromStdString(msgName(model->msg_id))); + QString fn = QFileDialog::getSaveFileName(this, QString("Export %1 to CSV file").arg(QString::fromStdString(msgName(model->msg_id))), dir, tr("csv (*.csv)")); if (!fn.isEmpty()) { - model->isHexMode() ? utils::exportToCSV(fn, model->msg_id) - : utils::exportSignalsToCSV(fn, model->msg_id); + model->isHexMode() ? utils::exportToCSV(fn.toStdString(), model->msg_id) + : utils::exportSignalsToCSV(fn.toStdString(), model->msg_id); } } diff --git a/tools/cabana/historylog.h b/openpilot/tools/cabana/historylog.h similarity index 98% rename from tools/cabana/historylog.h rename to openpilot/tools/cabana/historylog.h index 1ac6e5bbad..1d3200b200 100644 --- a/tools/cabana/historylog.h +++ b/openpilot/tools/cabana/historylog.h @@ -40,7 +40,7 @@ public: uint64_t mono_time = 0; std::vector sig_values; std::vector data; - std::vector colors; + std::vector colors; }; void fetchData(std::deque::iterator insert_pos, uint64_t from_time, uint64_t min_time); diff --git a/openpilot/tools/cabana/mainwin.cc b/openpilot/tools/cabana/mainwin.cc new file mode 100644 index 0000000000..953f573a0b --- /dev/null +++ b/openpilot/tools/cabana/mainwin.cc @@ -0,0 +1,740 @@ +#include "tools/cabana/mainwin.h" +#include "tools/cabana/dbc/dbcqt.h" + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "json11/json11.hpp" +#include "tools/cabana/commands.h" +#include "tools/cabana/streamselector.h" +#include "tools/cabana/tools/findsignal.h" +#include "tools/cabana/utils/export.h" +#include "tools/replay/py_downloader.h" +#include "tools/replay/util.h" + +MainWindow::MainWindow(AbstractStream *stream, const QString &dbc_file) : QMainWindow() { + loadFingerprints(); + createDockWindows(); + setCentralWidget(center_widget = new CenterWidget(this)); + createActions(); + createStatusBar(); + createShortcuts(); + + // save default window state to allow resetting it + default_state = utils::toBytes(saveState()); + + // restore states; restoreGeometry() itself corrects stale off-screen geometry + restoreGeometry(utils::qbytes(settings.geometry)); + restoreState(utils::qbytes(settings.window_state)); + + // install handlers + static auto static_main_win = this; + qRegisterMetaType("uint64_t"); + qRegisterMetaType("SourceSet"); + installDownloadProgressHandler([](uint64_t cur, uint64_t total, bool success) { + emit static_main_win->updateProgressBar(cur, total, success); + }); + installMessageHandler([](ReplyMsgType type, const std::string msg) { + emit static_main_win->showMessage(QString::fromStdString(msg), 2000); + }); + + setStyleSheet(QString(R"(QMainWindow::separator { + width: %1px; /* when vertical */ + height: %1px; /* when horizontal */ + })").arg(style()->pixelMetric(QStyle::PM_SplitterWidth))); + + QObject::connect(this, &MainWindow::showMessage, statusBar(), &QStatusBar::showMessage); + QObject::connect(this, &MainWindow::updateProgressBar, this, &MainWindow::updateDownloadProgress); + QObject::connect(dbcNotifier(), &QtDBCNotifier::DBCFileChanged, this, &MainWindow::DBCFileChanged); + QObject::connect(undoNotifier(), &QtUndoNotifier::cleanChanged, this, &MainWindow::undoStackCleanChanged); + QObject::connect(&settings, &Settings::changed, this, &MainWindow::updateStatus); + + QTimer::singleShot(0, this, [=]() { stream ? openStream(stream, dbc_file) : selectAndOpenStream(); }); + show(); +} + +void MainWindow::loadFingerprints() { + std::ifstream json_file((QApplication::applicationDirPath() + "/dbc/car_fingerprint_to_dbc.json").toStdString()); + if (!json_file) return; + const std::string contents{std::istreambuf_iterator(json_file), std::istreambuf_iterator()}; + std::string err; + auto doc = json11::Json::parse(contents, err); + if (!err.empty() || !doc.is_object()) return; + fingerprint_to_dbc.clear(); + for (const auto &kv : doc.object_items()) { + if (kv.second.is_string()) { + fingerprint_to_dbc.emplace(kv.first, kv.second.string_value()); + } + } +} + +void MainWindow::createActions() { + // File menu + QMenu *file_menu = menuBar()->addMenu(tr("&File")); + file_menu->addAction(tr("Open Stream..."), this, &MainWindow::selectAndOpenStream); + close_stream_act = file_menu->addAction(tr("Close stream"), this, &MainWindow::closeStream); + export_to_csv_act = file_menu->addAction(tr("Export to CSV..."), this, &MainWindow::exportToCSV); + close_stream_act->setEnabled(false); + export_to_csv_act->setEnabled(false); + file_menu->addSeparator(); + + file_menu->addAction(tr("New DBC File"), [this]() { newFile(); }, QKeySequence::New); + file_menu->addAction(tr("Open DBC File..."), [this]() { openFile(); }, QKeySequence::Open); + + manage_dbcs_menu = file_menu->addMenu(tr("Manage &DBC Files")); + QObject::connect(manage_dbcs_menu, &QMenu::aboutToShow, this, &MainWindow::updateLoadSaveMenus); + + open_recent_menu = file_menu->addMenu(tr("Open &Recent")); + QObject::connect(open_recent_menu, &QMenu::aboutToShow, this, &MainWindow::updateRecentFileMenu); + + file_menu->addSeparator(); + QMenu *load_opendbc_menu = file_menu->addMenu(tr("Load DBC from commaai/opendbc")); + // load_opendbc_menu->setStyleSheet("QMenu { menu-scrollable: true; }"); + std::vector dbc_names; + std::error_code ec; + for (const auto &entry : std::filesystem::directory_iterator(OPENDBC_FILE_PATH, ec)) { + if (entry.is_regular_file() && entry.path().extension() == ".dbc") { + dbc_names.push_back(entry.path().filename().string()); + } + } + std::sort(dbc_names.begin(), dbc_names.end()); + for (const auto &dbc_name : dbc_names) { + QString name = QString::fromStdString(dbc_name); + load_opendbc_menu->addAction(name, [this, name]() { loadDBCFromOpendbc(name); }); + } + + file_menu->addAction(tr("Load DBC From Clipboard"), [=]() { loadFromClipboard(); }); + + file_menu->addSeparator(); + save_dbc = file_menu->addAction(tr("Save DBC..."), this, &MainWindow::save, QKeySequence::Save); + save_dbc_as = file_menu->addAction(tr("Save DBC As..."), this, &MainWindow::saveAs, QKeySequence::SaveAs); + copy_dbc_to_clipboard = file_menu->addAction(tr("Copy DBC To Clipboard"), this, &MainWindow::saveToClipboard); + + file_menu->addSeparator(); + file_menu->addAction(tr("Settings..."), this, &MainWindow::setOption, QKeySequence::Preferences); + + file_menu->addSeparator(); + file_menu->addAction(tr("E&xit"), qApp, &QApplication::closeAllWindows, QKeySequence::Quit); + + // Edit Menu + QMenu *edit_menu = menuBar()->addMenu(tr("&Edit")); + undo_act = edit_menu->addAction(tr("&Undo"), []() { UndoStack::instance()->undo(); }); + undo_act->setShortcuts(QKeySequence::Undo); + redo_act = edit_menu->addAction(tr("&Redo"), []() { UndoStack::instance()->redo(); }); + redo_act->setShortcuts(QKeySequence::Redo); + QObject::connect(undoNotifier(), &QtUndoNotifier::indexChanged, this, &MainWindow::updateUndoRedoActions); + updateUndoRedoActions(); + + // View Menu + QMenu *view_menu = menuBar()->addMenu(tr("&View")); + auto act = view_menu->addAction(tr("Full Screen"), this, &MainWindow::toggleFullScreen, QKeySequence::FullScreen); + addAction(act); + view_menu->addSeparator(); + view_menu->addAction(messages_dock->toggleViewAction()); + view_menu->addAction(video_dock->toggleViewAction()); + view_menu->addSeparator(); + view_menu->addAction(tr("Reset Window Layout"), [this]() { restoreState(utils::qbytes(default_state)); }); + + // Tools Menu + tools_menu = menuBar()->addMenu(tr("&Tools")); + tools_menu->addAction(tr("Find &Similar Bits"), this, &MainWindow::findSimilarBits); + tools_menu->addAction(tr("&Find Signal"), this, &MainWindow::findSignal); + + // Help Menu + QMenu *help_menu = menuBar()->addMenu(tr("&Help")); + help_menu->addAction(tr("Help"), this, &MainWindow::onlineHelp, QKeySequence::HelpContents); + help_menu->addAction(tr("About &Qt"), qApp, &QApplication::aboutQt); +} + +void MainWindow::createDockWindows() { + messages_dock = new QDockWidget(tr("MESSAGES"), this); + messages_dock->setObjectName("MessagesPanel"); + messages_dock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::TopDockWidgetArea | Qt::BottomDockWidgetArea); + messages_dock->setFeatures(QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetClosable); + addDockWidget(Qt::LeftDockWidgetArea, messages_dock); + + video_dock = new QDockWidget("", this); + video_dock->setObjectName(tr("VideoPanel")); + video_dock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea); + video_dock->setFeatures(QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetClosable); + addDockWidget(Qt::RightDockWidgetArea, video_dock); +} + +void MainWindow::createDockWidgets() { + messages_widget = new MessagesWidget(this); + messages_dock->setWidget(messages_widget); + QObject::connect(messages_widget, &MessagesWidget::titleChanged, messages_dock, &QDockWidget::setWindowTitle); + QObject::connect(messages_widget, &MessagesWidget::msgSelectionChanged, center_widget, &CenterWidget::setMessage); + + // right panel + charts_widget = new ChartsWidget(this); + QWidget *charts_container = new QWidget(this); + charts_layout = new QVBoxLayout(charts_container); + charts_layout->setContentsMargins(0, 0, 0, 0); + charts_layout->addWidget(charts_widget); + + // splitter between video and charts + video_splitter = new QSplitter(Qt::Vertical, this); + video_widget = new VideoWidget(this); + video_splitter->addWidget(video_widget); + + video_splitter->addWidget(charts_container); + video_splitter->setStretchFactor(1, 1); + video_splitter->restoreState(utils::qbytes(settings.video_splitter_state)); + video_splitter->handle(1)->setEnabled(!can->liveStreaming()); + video_dock->setWidget(video_splitter); + QObject::connect(charts_widget, &ChartsWidget::toggleChartsDocking, this, &MainWindow::toggleChartsDocking); + QObject::connect(charts_widget, &ChartsWidget::showTip, video_widget, &VideoWidget::showThumbnail); +} + +void MainWindow::createStatusBar() { + progress_bar = new QProgressBar(); + progress_bar->setRange(0, 100); + progress_bar->setTextVisible(true); + progress_bar->setFixedSize({300, 16}); + progress_bar->setVisible(false); + statusBar()->addWidget(new QLabel(tr("For Help, Press F1"))); + statusBar()->addPermanentWidget(progress_bar); + statusBar()->addPermanentWidget(status_label = new QLabel(this)); + updateStatus(); +} + +void MainWindow::createShortcuts() { + auto shortcut = new QShortcut(QKeySequence(Qt::Key_Space), this, nullptr, nullptr, Qt::ApplicationShortcut); + QObject::connect(shortcut, &QShortcut::activated, this, []() { + if (can) can->pause(!can->isPaused()); + }); + // TODO: add more shortcuts here. +} + +void MainWindow::undoStackCleanChanged(bool clean) { + setWindowModified(!clean); +} + +void MainWindow::updateUndoRedoActions() { + auto stack = UndoStack::instance(); + undo_act->setEnabled(stack->canUndo()); + undo_act->setText(stack->canUndo() ? tr("&Undo %1").arg(QString::fromStdString(stack->undoText())) : tr("&Undo")); + redo_act->setEnabled(stack->canRedo()); + redo_act->setText(stack->canRedo() ? tr("&Redo %1").arg(QString::fromStdString(stack->redoText())) : tr("&Redo")); +} + +void MainWindow::DBCFileChanged() { + UndoStack::instance()->clear(); + + // Update file menu + int cnt = dbc()->nonEmptyDBCCount(); + save_dbc->setText(cnt > 1 ? tr("Save %1 DBCs...").arg(cnt) : tr("Save DBC...")); + save_dbc->setEnabled(cnt > 0); + save_dbc_as->setEnabled(cnt == 1); + // TODO: Support clipboard for multiple files + copy_dbc_to_clipboard->setEnabled(cnt == 1); + manage_dbcs_menu->setEnabled(dynamic_cast(can) == nullptr); + + QStringList title; + for (auto f : dbc()->allDBCFiles()) { + title.push_back(tr("(%1) %2").arg(QString::fromStdString(toString(dbc()->sources(f))), QString::fromStdString(f->name()))); + } + setWindowFilePath(title.join(" | ")); + + QTimer::singleShot(0, this, &::MainWindow::restoreSessionState); +} + +void MainWindow::selectAndOpenStream() { + StreamSelector dlg(this); + if (dlg.exec()) { + openStream(dlg.stream(), dlg.dbcFile()); + } else if (!can) { + openStream(new DummyStream(this)); + } +} + +void MainWindow::closeStream() { + openStream(new DummyStream(this)); + if (dbc()->nonEmptyDBCCount() > 0) { + emit dbcNotifier()->DBCFileChanged(); + } + statusBar()->showMessage(tr("stream closed")); +} + +void MainWindow::exportToCSV() { + QString dir = QString("%1/%2.csv").arg(QString::fromStdString(settings.last_dir)).arg(QString::fromStdString(can->routeName())); + QString fn = QFileDialog::getSaveFileName(this, "Export stream to CSV file", dir, tr("csv (*.csv)")); + if (!fn.isEmpty()) { + utils::exportToCSV(fn.toStdString()); + } +} + +void MainWindow::newFile(SourceSet s) { + closeFile(s); + dbc()->open(s, std::string(""), std::string("")); +} + +void MainWindow::openFile(SourceSet s) { + remindSaveChanges(); + QString fn = QFileDialog::getOpenFileName(this, tr("Open File"), QString::fromStdString(settings.last_dir), "DBC (*.dbc)"); + if (!fn.isEmpty()) { + loadFile(fn, s); + } +} + +void MainWindow::loadFile(const QString &fn, SourceSet s) { + if (!fn.isEmpty()) { + closeFile(s); + + std::string error; + if (dbc()->open(s, fn.toStdString(), &error)) { + updateRecentFiles(fn); + statusBar()->showMessage(tr("DBC File %1 loaded").arg(fn), 2000); + } else { + QMessageBox msg_box(QMessageBox::Warning, tr("Failed to load DBC file"), tr("Failed to parse DBC file %1").arg(fn)); + msg_box.setDetailedText(QString::fromStdString(error)); + msg_box.exec(); + } + } +} + +void MainWindow::loadDBCFromOpendbc(const QString &name) { + loadFile(QString("%1/%2").arg(OPENDBC_FILE_PATH, name)); +} + +void MainWindow::loadFromClipboard(SourceSet s, bool close_all) { + std::string text; + if (!utils::getClipboardText(&text)) { + QMessageBox::warning(this, tr("Load From Clipboard"), tr("No clipboard tool found. Install xclip (X11) or wl-clipboard (Wayland).")); + return; + } + if (text.empty()) { + QMessageBox::warning(this, tr("Load From Clipboard"), tr("Clipboard is empty.")); + return; + } + + closeFile(s); + + std::string error; + bool ret = dbc()->open(s, std::string(""), text, &error); + if (ret && dbc()->nonEmptyDBCCount() > 0) { + QMessageBox::information(this, tr("Load From Clipboard"), tr("DBC Successfully Loaded!")); + } else { + QMessageBox msg_box(QMessageBox::Warning, tr("Failed to load DBC from clipboard"), tr("Make sure that you paste the text with correct format.")); + msg_box.setDetailedText(QString::fromStdString(error)); + msg_box.exec(); + } +} + +void MainWindow::openStream(AbstractStream *stream, const QString &dbc_file) { + if (can) { + QObject::connect(can, &QObject::destroyed, this, [=]() { startStream(stream, dbc_file); }); + can->deleteLater(); + } else { + startStream(stream, dbc_file); + } +} + +void MainWindow::startStream(AbstractStream *stream, QString dbc_file) { + center_widget->clear(); + delete messages_widget; + delete video_splitter; + + can = stream; + can->setParent(this); // take ownership + can->start(); + + loadFile(dbc_file); + statusBar()->showMessage(tr("Stream [%1] started").arg(QString::fromStdString(can->routeName())), 2000); + + bool has_stream = dynamic_cast(can) == nullptr; + close_stream_act->setEnabled(has_stream); + export_to_csv_act->setEnabled(has_stream); + tools_menu->setEnabled(has_stream); + createDockWidgets(); + + video_dock->setWindowTitle(QString::fromStdString(can->routeName())); + if (can->liveStreaming() || video_splitter->sizes()[0] == 0) { + // display video at minimum size. + video_splitter->setSizes({1, 1}); + } + // Don't overwrite already loaded DBC + if (!dbc()->nonEmptyDBCCount()) { + newFile(); + } + + QObject::connect(can, &AbstractStream::eventsMerged, this, &MainWindow::eventsMerged); + + if (has_stream) { + auto wait_dlg = new QProgressDialog( + can->liveStreaming() ? tr("Waiting for the live stream to start...") : tr("Loading segment data..."), + tr("&Abort"), 0, 100, this); + wait_dlg->setWindowModality(Qt::WindowModal); + wait_dlg->setFixedSize(400, wait_dlg->sizeHint().height()); + QObject::connect(wait_dlg, &QProgressDialog::canceled, this, &MainWindow::close); + QObject::connect(can, &AbstractStream::eventsMerged, wait_dlg, &QProgressDialog::deleteLater); + QObject::connect(this, &MainWindow::updateProgressBar, wait_dlg, [=](uint64_t cur, uint64_t total, bool success) { + wait_dlg->setValue((int)((cur / (double)total) * 100)); + }); + } +} + +void MainWindow::eventsMerged() { + if (!can->liveStreaming() && std::exchange(car_fingerprint, QString::fromStdString(can->carFingerprint())) != car_fingerprint) { + video_dock->setWindowTitle(tr("ROUTE: %1 FINGERPRINT: %2") + .arg(QString::fromStdString(can->routeName())) + .arg(car_fingerprint.isEmpty() ? tr("Unknown Car") : car_fingerprint)); + // Don't overwrite already loaded DBC + auto it = fingerprint_to_dbc.find(car_fingerprint.toStdString()); + if (!dbc()->nonEmptyDBCCount() && it != fingerprint_to_dbc.end()) { + QTimer::singleShot(0, this, [this, dbc_name = QString::fromStdString(it->second)]() { + loadDBCFromOpendbc(dbc_name + ".dbc"); + }); + } + } +} + +void MainWindow::save() { + // Save all open DBC files + for (auto dbc_file : dbc()->allDBCFiles()) { + if (dbc_file->isEmpty()) continue; + saveFile(dbc_file); + } +} + +void MainWindow::saveAs() { + // Save as all open DBC files. Should not be called with more than 1 file open + for (auto dbc_file : dbc()->allDBCFiles()) { + if (dbc_file->isEmpty()) continue; + saveFileAs(dbc_file); + } +} + +void MainWindow::closeFile(SourceSet s) { + remindSaveChanges(); + if (s == SOURCE_ALL) { + dbc()->closeAll(); + } else { + dbc()->close(s); + } +} + +void MainWindow::closeFile(DBCFile *dbc_file) { + assert(dbc_file != nullptr); + remindSaveChanges(); + dbc()->close(dbc_file); + // Ensure we always have at least one file open + if (dbc()->dbcCount() == 0) { + newFile(); + } +} + +void MainWindow::saveFile(DBCFile *dbc_file) { + assert(dbc_file != nullptr); + if (!dbc_file->filename.empty()) { + dbc_file->save(); + UndoStack::instance()->setClean(); + statusBar()->showMessage(tr("File saved"), 2000); + } else if (!dbc_file->isEmpty()) { + saveFileAs(dbc_file); + } +} + +void MainWindow::saveFileAs(DBCFile *dbc_file) { + QString title = tr("Save File (bus: %1)").arg(QString::fromStdString(toString(dbc()->sources(dbc_file)))); + QString fn = QFileDialog::getSaveFileName(this, title, QString::fromStdString((std::filesystem::path(settings.last_dir) / "untitled.dbc").string()), tr("DBC (*.dbc)")); + if (!fn.isEmpty()) { + dbc_file->saveAs(fn.toStdString()); + UndoStack::instance()->setClean(); + statusBar()->showMessage(tr("File saved as %1").arg(fn), 2000); + updateRecentFiles(fn); + } +} + +void MainWindow::saveToClipboard() { + // Copy all open DBC files to clipboard. Should not be called with more than 1 file open + for (auto dbc_file : dbc()->allDBCFiles()) { + if (dbc_file->isEmpty()) continue; + saveFileToClipboard(dbc_file); + } +} + +void MainWindow::saveFileToClipboard(DBCFile *dbc_file) { + assert(dbc_file != nullptr); + if (utils::setClipboardText(dbc_file->generateDBC())) { + QMessageBox::information(this, tr("Copy To Clipboard"), tr("DBC Successfully copied!")); + } else { + QMessageBox::warning(this, tr("Copy To Clipboard"), tr("Failed to copy DBC to clipboard. Install xclip (X11) or wl-clipboard (Wayland).")); + } +} + +void MainWindow::updateLoadSaveMenus() { + manage_dbcs_menu->clear(); + + for (int source : can->sources) { + if (source >= 64) continue; // Sent and blocked buses are handled implicitly + + SourceSet ss = {source, uint8_t(source + 128), uint8_t(source + 192)}; + + QMenu *bus_menu = new QMenu(this); + bus_menu->addAction(tr("New DBC File..."), [=]() { newFile(ss); }); + bus_menu->addAction(tr("Open DBC File..."), [=]() { openFile(ss); }); + bus_menu->addAction(tr("Load DBC From Clipboard..."), [=]() { loadFromClipboard(ss, false); }); + + // Show sub-menu for each dbc for this source. + auto dbc_file = dbc()->findDBCFile(source); + if (dbc_file) { + bus_menu->addSeparator(); + bus_menu->addAction(QString::fromStdString(dbc_file->name()) + " (" + QString::fromStdString(toString(dbc()->sources(dbc_file))) + ")")->setEnabled(false); + bus_menu->addAction(tr("Save..."), [=]() { saveFile(dbc_file); }); + bus_menu->addAction(tr("Save As..."), [=]() { saveFileAs(dbc_file); }); + bus_menu->addAction(tr("Copy to Clipboard..."), [=]() { saveFileToClipboard(dbc_file); }); + bus_menu->addAction(tr("Remove from this bus..."), [=]() { closeFile(ss); }); + bus_menu->addAction(tr("Remove from all buses..."), [=]() { closeFile(dbc_file); }); + } + bus_menu->setTitle(tr("Bus %1 (%2)").arg(source).arg(dbc_file ? QString::fromStdString(dbc_file->name()) : "No DBCs loaded")); + + manage_dbcs_menu->addMenu(bus_menu); + } +} + +void MainWindow::updateRecentFiles(const QString &fn) { + const std::string filename = fn.toStdString(); + settings.recent_files.erase(std::remove(settings.recent_files.begin(), settings.recent_files.end(), filename), settings.recent_files.end()); + settings.recent_files.insert(settings.recent_files.begin(), filename); + while (settings.recent_files.size() > MAX_RECENT_FILES) { + settings.recent_files.pop_back(); + } + settings.last_dir = std::filesystem::absolute(fn.toStdString()).parent_path().string(); +} + +void MainWindow::updateRecentFileMenu() { + open_recent_menu->clear(); + + int num_recent_files = std::min(settings.recent_files.size(), MAX_RECENT_FILES); + if (!num_recent_files) { + open_recent_menu->addAction(tr("No Recent Files"))->setEnabled(false); + return; + } + + for (int i = 0; i < num_recent_files; ++i) { + QString text = tr("&%1 %2").arg(i + 1).arg(QString::fromStdString(std::filesystem::path(settings.recent_files[i]).filename().string())); + open_recent_menu->addAction(text, this, [this, file = settings.recent_files[i]]() { loadFile(QString::fromStdString(file)); }); + } +} + +void MainWindow::remindSaveChanges() { + while (!UndoStack::instance()->isClean()) { + QString text = tr("You have unsaved changes. Press ok to save them, cancel to discard."); + int ret = QMessageBox::question(this, tr("Unsaved Changes"), text, QMessageBox::Ok | QMessageBox::Cancel); + if (ret != QMessageBox::Ok) break; + save(); + } + UndoStack::instance()->clear(); +} + +void MainWindow::updateDownloadProgress(uint64_t cur, uint64_t total, bool success) { + if (success && cur < total) { + progress_bar->setValue((cur / (double)total) * 100); + progress_bar->setFormat(tr("Downloading %p% (%1)").arg(formattedDataSize(total).c_str())); + progress_bar->show(); + } else { + progress_bar->hide(); + } +} + +void MainWindow::updateStatus() { + status_label->setText(tr("Cached Minutes:%1 FPS:%2").arg(settings.max_cached_minutes).arg(settings.fps)); +} + +bool MainWindow::eventFilter(QObject *obj, QEvent *event) { + if (obj == floating_window && event->type() == QEvent::Close) { + toggleChartsDocking(); + return true; + } + return QMainWindow::eventFilter(obj, event); +} + +void MainWindow::toggleChartsDocking() { + if (floating_window) { + // Dock the charts widget back to the main window + floating_window->removeEventFilter(this); + charts_layout->insertWidget(0, charts_widget, 1); + floating_window->deleteLater(); + floating_window = nullptr; + charts_widget->setIsDocked(true); + } else { + // Float the charts widget in a separate window + floating_window = new QWidget(this, Qt::Window); + floating_window->setWindowTitle("Charts"); + floating_window->setLayout(new QVBoxLayout()); + floating_window->layout()->addWidget(charts_widget); + floating_window->installEventFilter(this); + floating_window->showMaximized(); + charts_widget->setIsDocked(false); + } +} + +void MainWindow::closeEvent(QCloseEvent *event) { + remindSaveChanges(); + + installDownloadProgressHandler(nullptr); + installMessageHandler(nullptr); + + if (floating_window) + floating_window->deleteLater(); + + // save states + settings.geometry = utils::toBytes(saveGeometry()); + settings.window_state = utils::toBytes(saveState()); + if (can && !can->liveStreaming()) { + settings.video_splitter_state = utils::toBytes(video_splitter->saveState()); + } + if (messages_widget) { + settings.message_header_state = messages_widget->saveHeaderState(); + } + + saveSessionState(); + settings.save(); + QWidget::closeEvent(event); +} + +void MainWindow::setOption() { + SettingsDlg dlg(this); + dlg.exec(); +} + +void MainWindow::findSimilarBits() { + FindSimilarBitsDlg *dlg = new FindSimilarBitsDlg(this); + QObject::connect(dlg, &FindSimilarBitsDlg::openMessage, messages_widget, &MessagesWidget::selectMessage); + dlg->show(); +} + +void MainWindow::findSignal() { + FindSignalDlg *dlg = new FindSignalDlg(this); + QObject::connect(dlg, &FindSignalDlg::openMessage, messages_widget, &MessagesWidget::selectMessage); + dlg->show(); +} + +void MainWindow::onlineHelp() { + if (auto help = findChild()) { + help->close(); + } else { + help = new HelpOverlay(this); + help->setGeometry(rect()); + help->show(); + help->raise(); + } +} + +void MainWindow::toggleFullScreen() { + if (isFullScreen()) { + menuBar()->show(); + statusBar()->show(); + showNormal(); + showMaximized(); + } else { + menuBar()->hide(); + statusBar()->hide(); + showFullScreen(); + } +} + +void MainWindow::saveSessionState() { + settings.recent_dbc_file = ""; + settings.active_msg_id = ""; + settings.selected_msg_ids.clear(); + settings.active_charts.clear(); + + for (auto &f : dbc()->allDBCFiles()) + if (!f->isEmpty()) { settings.recent_dbc_file = f->filename; break; } + + if (auto *detail = center_widget->getDetailWidget()) { + auto [active_id, ids] = detail->serializeMessageIds(); + settings.active_msg_id = active_id.toStdString(); + settings.selected_msg_ids.clear(); + for (const auto &id : ids) settings.selected_msg_ids.push_back(id.toStdString()); + } + if (charts_widget) { + settings.active_charts.clear(); + for (const auto &id : charts_widget->serializeChartIds()) settings.active_charts.push_back(id.toStdString()); + } +} + +void MainWindow::restoreSessionState() { + if (settings.recent_dbc_file.empty() || dbc()->nonEmptyDBCCount() == 0) return; + + QString dbc_file; + for (auto& f : dbc()->allDBCFiles()) + if (!f->isEmpty()) { dbc_file = QString::fromStdString(f->filename); break; } + if (dbc_file.toStdString() != settings.recent_dbc_file) return; + + if (!settings.selected_msg_ids.empty()) { + QStringList ids; + for (const auto &id : settings.selected_msg_ids) ids.push_back(QString::fromStdString(id)); + center_widget->ensureDetailWidget()->restoreTabs(QString::fromStdString(settings.active_msg_id), ids); + } + + if (charts_widget != nullptr && !settings.active_charts.empty()) { + QStringList ids; + for (const auto &id : settings.active_charts) ids.push_back(QString::fromStdString(id)); + charts_widget->restoreChartsFromIds(ids); + } +} + +// HelpOverlay +HelpOverlay::HelpOverlay(MainWindow *parent) : QWidget(parent) { + setAttribute(Qt::WA_NoSystemBackground, true); + setAttribute(Qt::WA_TranslucentBackground, true); + setAttribute(Qt::WA_DeleteOnClose); + parent->installEventFilter(this); +} + +void HelpOverlay::paintEvent(QPaintEvent *event) { + QPainter painter(this); + painter.fillRect(rect(), QColor(0, 0, 0, 50)); + auto parent = parentWidget(); + drawHelpForWidget(painter, parent->findChild()); + drawHelpForWidget(painter, parent->findChild()); + drawHelpForWidget(painter, parent->findChild()); + drawHelpForWidget(painter, parent->findChild()); + drawHelpForWidget(painter, parent->findChild()); +} + +void HelpOverlay::drawHelpForWidget(QPainter &painter, QWidget *w) { + if (w && w->isVisible() && !w->whatsThis().isEmpty()) { + QPoint pt = mapFromGlobal(w->mapToGlobal(w->rect().center())); + if (rect().contains(pt)) { + QTextDocument document; + document.setHtml(w->whatsThis()); + QSize doc_size = document.size().toSize(); + QPoint topleft = {pt.x() - doc_size.width() / 2, pt.y() - doc_size.height() / 2}; + painter.translate(topleft); + painter.fillRect(QRect{{0, 0}, doc_size}, palette().toolTipBase()); + document.drawContents(&painter); + painter.translate(-topleft); + } + } +} + +bool HelpOverlay::eventFilter(QObject *obj, QEvent *event) { + if (obj == parentWidget() && event->type() == QEvent::Resize) { + QResizeEvent *resize_event = (QResizeEvent *)(event); + setGeometry(QRect{QPoint(0, 0), resize_event->size()}); + } + return false; +} + +void HelpOverlay::mouseReleaseEvent(QMouseEvent *event) { + close(); +} diff --git a/tools/cabana/mainwin.h b/openpilot/tools/cabana/mainwin.h similarity index 89% rename from tools/cabana/mainwin.h rename to openpilot/tools/cabana/mainwin.h index 9bc94c090f..279ea3b969 100644 --- a/tools/cabana/mainwin.h +++ b/openpilot/tools/cabana/mainwin.h @@ -1,13 +1,16 @@ #pragma once #include -#include #include #include #include #include #include +#include #include +#include +#include +#include #include "tools/cabana/chart/chartswidget.h" #include "tools/cabana/dbc/dbcmanager.h" @@ -44,6 +47,7 @@ signals: void updateProgressBar(uint64_t cur, uint64_t total, bool success); protected: + void startStream(AbstractStream *stream, QString dbc_file); bool eventFilter(QObject *obj, QEvent *event) override; void remindSaveChanges(); void closeFile(SourceSet s = SOURCE_ALL); @@ -66,12 +70,15 @@ protected: void findSimilarBits(); void findSignal(); void undoStackCleanChanged(bool clean); + void updateUndoRedoActions(); void onlineHelp(); void toggleFullScreen(); void updateStatus(); void updateLoadSaveMenus(); void createDockWidgets(); void eventsMerged(); + void saveSessionState(); + void restoreSessionState(); VideoWidget *video_widget = nullptr; QDockWidget *video_dock; @@ -82,7 +89,7 @@ protected: QVBoxLayout *charts_layout; QProgressBar *progress_bar; QLabel *status_label; - QJsonDocument fingerprint_to_dbc; + std::unordered_map fingerprint_to_dbc; QSplitter *video_splitter = nullptr; enum { MAX_RECENT_FILES = 15 }; QMenu *open_recent_menu = nullptr; @@ -93,8 +100,10 @@ protected: QAction *save_dbc = nullptr; QAction *save_dbc_as = nullptr; QAction *copy_dbc_to_clipboard = nullptr; + QAction *undo_act = nullptr; + QAction *redo_act = nullptr; QString car_fingerprint; - QByteArray default_state; + std::vector default_state; }; class HelpOverlay : public QWidget { diff --git a/tools/cabana/messageswidget.cc b/openpilot/tools/cabana/messageswidget.cc similarity index 87% rename from tools/cabana/messageswidget.cc rename to openpilot/tools/cabana/messageswidget.cc index ed9aeaf311..b07e3ea0bf 100644 --- a/tools/cabana/messageswidget.cc +++ b/openpilot/tools/cabana/messageswidget.cc @@ -1,4 +1,5 @@ #include "tools/cabana/messageswidget.h" +#include "tools/cabana/dbc/dbcqt.h" #include #include @@ -43,8 +44,8 @@ MessagesWidget::MessagesWidget(QWidget *parent) : menu(new QMenu(this)), QWidget QObject::connect(header, &MessageViewHeader::customContextMenuRequested, this, &MessagesWidget::headerContextMenuEvent); QObject::connect(view->horizontalScrollBar(), &QScrollBar::valueChanged, header, &MessageViewHeader::updateHeaderPositions); QObject::connect(can, &AbstractStream::msgsReceived, model, &MessageListModel::msgsReceived); - QObject::connect(dbc(), &DBCManager::DBCFileChanged, model, &MessageListModel::dbcModified); - QObject::connect(UndoStack::instance(), &QUndoStack::indexChanged, model, &MessageListModel::dbcModified); + QObject::connect(dbcNotifier(), &QtDBCNotifier::DBCFileChanged, model, &MessageListModel::dbcModified); + QObject::connect(undoNotifier(), &QtUndoNotifier::indexChanged, model, &MessageListModel::dbcModified); QObject::connect(model, &MessageListModel::modelReset, [this]() { if (current_msg_id) { selectMessage(*current_msg_id); @@ -64,7 +65,7 @@ MessagesWidget::MessagesWidget(QWidget *parent) : menu(new QMenu(this)), QWidget setWhatsThis(tr(R"( Message View
- + Byte color
constant changing
increasing
@@ -146,7 +147,7 @@ void MessagesWidget::menuAboutToShow() { action->setCheckable(true); action->setChecked(settings.multiple_lines_hex); - action = menu->addAction(tr("Show inactive Messages"), model, &MessageListModel::showInactivemessages); + action = menu->addAction(tr("Show inactive messages"), model, &MessageListModel::showInactiveMessages); action->setCheckable(true); action->setChecked(model->show_inactive_messages); } @@ -205,18 +206,18 @@ QVariant MessageListModel::data(const QModelIndex &index, int role) const { } else if (role == Qt::ToolTipRole && index.column() == Column::NAME) { auto msg = dbc()->msg(item.id); auto tooltip = item.name; - if (msg && !msg->comment.isEmpty()) tooltip += "
" + msg->comment + ""; + if (msg && !msg->comment.empty()) tooltip += "
" + QString::fromStdString(msg->comment) + ""; return tooltip; } return {}; } -void MessageListModel::setFilterStrings(const QMap &filters) { +void MessageListModel::setFilterStrings(const std::map &filters) { filters_ = filters; filterAndSort(); } -void MessageListModel::showInactivemessages(bool show) { +void MessageListModel::showInactiveMessages(bool show) { show_inactive_messages = show; filterAndSort(); } @@ -264,20 +265,20 @@ static bool parseRange(const QString &filter, uint32_t value, int base = 10) { } bool MessageListModel::match(const MessageListModel::Item &item) { - if (filters_.isEmpty()) + if (filters_.empty()) return true; bool match = true; const auto &data = can->lastMessage(item.id); for (auto it = filters_.cbegin(); it != filters_.cend() && match; ++it) { - const QString &txt = it.value(); - switch (it.key()) { + const QString &txt = it->second; + switch (it->first) { case Column::NAME: { match = item.name.contains(txt, Qt::CaseInsensitive); if (!match) { const auto m = dbc()->msg(item.id); match = m && std::any_of(m->sigs.cbegin(), m->sigs.cend(), - [&txt](const auto &s) { return s->name.contains(txt, Qt::CaseInsensitive); }); + [&txt](const auto &s) { return QString::fromStdString(s->name).contains(txt, Qt::CaseInsensitive); }); } break; } @@ -323,8 +324,8 @@ bool MessageListModel::filterAndSort() { if (show_inactive_messages || can->isMessageActive(id)) { auto msg = dbc()->msg(id); Item item = {.id = id, - .name = msg ? msg->name : UNTITLED, - .node = msg ? msg->transmitter : QString()}; + .name = msg ? QString::fromStdString(msg->name) : QString::fromStdString(UNTITLED), + .node = msg ? QString::fromStdString(msg->transmitter) : QString()}; if (match(item)) items.emplace_back(item); } @@ -387,10 +388,13 @@ void MessageView::drawRow(QPainter *painter, const QStyleOptionViewItem &option, painter->setPen(oldPen); } -void MessageView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector &roles) { +void MessageView::setModel(QAbstractItemModel *model) { + QTreeView::setModel(model); // Bypass the slow call to QTreeView::dataChanged. // QTreeView::dataChanged will invalidate the height cache and that's what we don't need in MessageView. - QAbstractItemView::dataChanged(topLeft, bottomRight, roles); + QObject::disconnect(model, &QAbstractItemModel::dataChanged, this, nullptr); + QObject::connect(model, &QAbstractItemModel::dataChanged, this, + [this](const QModelIndex &tl, const QModelIndex &br, const auto &roles) { QAbstractItemView::dataChanged(tl, br, roles); }); } void MessageView::updateBytesSectionSize() { @@ -421,9 +425,9 @@ MessageViewHeader::MessageViewHeader(QWidget *parent) : QHeaderView(Qt::Horizont } void MessageViewHeader::updateFilters() { - QMap filters; - for (int i = 0; i < count(); i++) { - if (editors[i] && !editors[i]->text().isEmpty()) { + std::map filters; + for (int i = 0; i < (int)editors.size(); i++) { + if (!editors[i]->text().isEmpty()) { filters[i] = editors[i]->text(); } } @@ -432,27 +436,24 @@ void MessageViewHeader::updateFilters() { void MessageViewHeader::updateHeaderPositions() { QSize sz = QHeaderView::sizeHint(); - for (int i = 0; i < count(); i++) { - if (editors[i]) { - int h = editors[i]->sizeHint().height(); - editors[i]->setGeometry(sectionViewportPosition(i), sz.height(), sectionSize(i), h); - editors[i]->setHidden(isSectionHidden(i)); - } + for (int i = 0; i < (int)editors.size(); i++) { + int h = editors[i]->sizeHint().height(); + editors[i]->setGeometry(sectionViewportPosition(i), sz.height(), sectionSize(i), h); + editors[i]->setHidden(isSectionHidden(i)); } } void MessageViewHeader::updateGeometries() { - for (int i = 0; i < count(); i++) { - if (!editors[i]) { - QString column_name = model()->headerData(i, Qt::Horizontal, Qt::DisplayRole).toString(); - editors[i] = new QLineEdit(this); - editors[i]->setClearButtonEnabled(true); - editors[i]->setPlaceholderText(tr("Filter %1").arg(column_name)); + for (int i = (int)editors.size(); i < count(); i++) { + QString column_name = model()->headerData(i, Qt::Horizontal, Qt::DisplayRole).toString(); + auto edit = new QLineEdit(this); + edit->setClearButtonEnabled(true); + edit->setPlaceholderText(tr("Filter %1").arg(column_name)); - QObject::connect(editors[i], &QLineEdit::textChanged, this, &MessageViewHeader::updateFilters); - } + QObject::connect(edit, &QLineEdit::textChanged, this, &MessageViewHeader::updateFilters); + editors.push_back(edit); } - setViewportMargins(0, 0, 0, editors[0] ? editors[0]->sizeHint().height() : 0); + setViewportMargins(0, 0, 0, !editors.empty() ? editors[0]->sizeHint().height() : 0); QHeaderView::updateGeometries(); updateHeaderPositions(); @@ -460,5 +461,5 @@ void MessageViewHeader::updateGeometries() { QSize MessageViewHeader::sizeHint() const { QSize sz = QHeaderView::sizeHint(); - return editors[0] ? QSize(sz.width(), sz.height() + editors[0]->height() + 1) : sz; + return !editors.empty() ? QSize(sz.width(), sz.height() + editors[0]->height() + 1) : sz; } diff --git a/tools/cabana/messageswidget.h b/openpilot/tools/cabana/messageswidget.h similarity index 84% rename from tools/cabana/messageswidget.h rename to openpilot/tools/cabana/messageswidget.h index 0fc09519a3..0a9cd256d8 100644 --- a/tools/cabana/messageswidget.h +++ b/openpilot/tools/cabana/messageswidget.h @@ -1,6 +1,8 @@ #pragma once #include +#include +#include #include #include #include @@ -35,8 +37,8 @@ public: QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; int rowCount(const QModelIndex &parent = QModelIndex()) const override { return items_.size(); } void sort(int column, Qt::SortOrder order = Qt::AscendingOrder) override; - void setFilterStrings(const QMap &filters); - void showInactivemessages(bool show); + void setFilterStrings(const std::map &filters); + void showInactiveMessages(bool show); void msgsReceived(const std::set *new_msgs, bool has_new_ids); bool filterAndSort(); void dbcModified(); @@ -56,7 +58,7 @@ private: void sortItems(std::vector &items); bool match(const MessageListModel::Item &id); - QMap filters_; + std::map filters_; std::set dbc_messages_; int sort_column = 0; Qt::SortOrder sort_order = Qt::AscendingOrder; @@ -68,11 +70,11 @@ class MessageView : public QTreeView { public: MessageView(QWidget *parent) : QTreeView(parent) {} void updateBytesSectionSize(); + void setModel(QAbstractItemModel *model) override; protected: void drawRow(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override; void drawBranches(QPainter *painter, const QRect &rect, const QModelIndex &index) const override {} - void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector &roles = QVector()) override; void wheelEvent(QWheelEvent *event) override; }; @@ -86,7 +88,7 @@ public: QSize sizeHint() const override; void updateFilters(); - QMap editors; + std::vector editors; }; class MessagesWidget : public QWidget { @@ -95,8 +97,13 @@ class MessagesWidget : public QWidget { public: MessagesWidget(QWidget *parent); void selectMessage(const MessageId &message_id); - QByteArray saveHeaderState() const { return view->header()->saveState(); } - bool restoreHeaderState(const QByteArray &state) const { return view->header()->restoreState(state); } + std::vector saveHeaderState() const { + const auto state = view->header()->saveState(); + return {state.begin(), state.end()}; + } + bool restoreHeaderState(const std::vector &state) const { + return view->header()->restoreState({(const char *)state.data(), (int)state.size()}); + } void suppressHighlighted(); signals: diff --git a/openpilot/tools/cabana/panda.cc b/openpilot/tools/cabana/panda.cc new file mode 100644 index 0000000000..33117812d3 --- /dev/null +++ b/openpilot/tools/cabana/panda.cc @@ -0,0 +1,346 @@ +#include "tools/cabana/panda.h" + +#include +#include +#include +#include +#include + +#include "openpilot/cereal/messaging/messaging.h" +#include "common/swaglog.h" +#include "common/util.h" + +static libusb_context *init_usb_ctx() { + libusb_context *context = nullptr; + int err = libusb_init(&context); + if (err != 0) { + LOGE("libusb initialization error"); + return nullptr; + } + +#if LIBUSB_API_VERSION >= 0x01000106 + libusb_set_option(context, LIBUSB_OPTION_LOG_LEVEL, LIBUSB_LOG_LEVEL_INFO); +#else + libusb_set_debug(context, 3); +#endif + return context; +} + +Panda::Panda(std::string serial, uint32_t bus_offset) : bus_offset(bus_offset) { + if (!init_usb_connection(serial)) { + throw std::runtime_error("Error connecting to panda"); + } + + LOGW("connected to %s over USB", serial.c_str()); + hw_type = get_hw_type(); + can_reset_communications(); +} + +Panda::~Panda() { + cleanup_usb(); +} + +bool Panda::connected() { + return connected_flag; +} + +bool Panda::comms_healthy() { + return comms_healthy_flag; +} + +std::string Panda::hw_serial() { + return hw_serial_str; +} + +std::vector Panda::list(bool usb_only) { + static std::unique_ptr context(init_usb_ctx(), libusb_exit); + + ssize_t num_devices; + libusb_device **dev_list = NULL; + std::vector serials; + if (!context) { return serials; } + + num_devices = libusb_get_device_list(context.get(), &dev_list); + if (num_devices < 0) { + LOGE("libusb can't get device list"); + goto finish; + } + + for (size_t i = 0; i < num_devices; ++i) { + libusb_device *device = dev_list[i]; + libusb_device_descriptor desc; + libusb_get_device_descriptor(device, &desc); + if (desc.idVendor == 0x3801 && desc.idProduct == 0xddcc) { + libusb_device_handle *handle = NULL; + int ret = libusb_open(device, &handle); + if (ret < 0) { goto finish; } + + unsigned char desc_serial[26] = { 0 }; + ret = libusb_get_string_descriptor_ascii(handle, desc.iSerialNumber, desc_serial, std::size(desc_serial)); + libusb_close(handle); + if (ret < 0) { goto finish; } + + serials.push_back(std::string((char *)desc_serial, ret)); + } + } + +finish: + if (dev_list != NULL) { + libusb_free_device_list(dev_list, 1); + } + return serials; +} + +void Panda::set_safety_model(cereal::CarParams::SafetyModel safety_model, uint16_t safety_param) { + control_write(0xdc, (uint16_t)safety_model, safety_param); +} + + +cereal::PandaState::PandaType Panda::get_hw_type() { + unsigned char hw_query[1] = {0}; + + control_read(0xc1, 0, 0, hw_query, 1); + return (cereal::PandaState::PandaType)(hw_query[0]); +} + + + + +void Panda::send_heartbeat(bool engaged, bool engaged_mads) { + control_write(0xf3, engaged, engaged_mads); +} + +void Panda::set_can_speed_kbps(uint16_t bus, uint16_t speed) { + control_write(0xde, bus, (speed * 10)); +} + + +void Panda::set_data_speed_kbps(uint16_t bus, uint16_t speed) { + control_write(0xf9, bus, (speed * 10)); +} + + + +bool Panda::can_receive(std::vector& out_vec) { + // Check if enough space left in buffer to store RECV_SIZE data + assert(receive_buffer_size + RECV_SIZE <= sizeof(receive_buffer)); + + int recv = bulk_read(0x81, &receive_buffer[receive_buffer_size], RECV_SIZE); + if (!comms_healthy()) { + return false; + } + + bool ret = true; + if (recv > 0) { + receive_buffer_size += recv; + ret = unpack_can_buffer(receive_buffer, receive_buffer_size, out_vec); + } + return ret; +} + +void Panda::can_reset_communications() { + control_write(0xc0, 0, 0); +} + +bool Panda::unpack_can_buffer(uint8_t *data, uint32_t &size, std::vector &out_vec) { + int pos = 0; + + while (pos <= size - sizeof(can_header)) { + can_header header; + memcpy(&header, &data[pos], sizeof(can_header)); + + const uint8_t data_len = dlc_to_len[header.data_len_code]; + if (pos + sizeof(can_header) + data_len > size) { + // we don't have all the data for this message yet + break; + } + + if (calculate_checksum(&data[pos], sizeof(can_header) + data_len) != 0) { + LOGE("Panda CAN checksum failed"); + size = 0; + can_reset_communications(); + return false; + } + + can_frame &canData = out_vec.emplace_back(); + canData.address = header.addr; + canData.src = header.bus + bus_offset; + if (header.rejected) { + canData.src += CAN_REJECTED_BUS_OFFSET; + } + if (header.returned) { + canData.src += CAN_RETURNED_BUS_OFFSET; + } + + canData.dat.assign((char *)&data[pos + sizeof(can_header)], data_len); + + pos += sizeof(can_header) + data_len; + } + + // move the overflowing data to the beginning of the buffer for the next round + memmove(data, &data[pos], size - pos); + size -= pos; + + return true; +} + +uint8_t Panda::calculate_checksum(uint8_t *data, uint32_t len) { + uint8_t checksum = 0U; + for (uint32_t i = 0U; i < len; i++) { + checksum ^= data[i]; + } + return checksum; +} + +// USB implementation methods +bool Panda::init_usb_connection(const std::string& serial) { + ssize_t num_devices; + libusb_device **dev_list = NULL; + int err = 0; + + ctx = init_usb_ctx(); + if (!ctx) { goto fail; } + + // connect by serial + num_devices = libusb_get_device_list(ctx, &dev_list); + if (num_devices < 0) { goto fail; } + + for (size_t i = 0; i < num_devices; ++i) { + libusb_device_descriptor desc; + libusb_get_device_descriptor(dev_list[i], &desc); + if (desc.idVendor == 0x3801 && desc.idProduct == 0xddcc) { + int ret = libusb_open(dev_list[i], &dev_handle); + if (dev_handle == NULL || ret < 0) { goto fail; } + + unsigned char desc_serial[26] = { 0 }; + ret = libusb_get_string_descriptor_ascii(dev_handle, desc.iSerialNumber, desc_serial, std::size(desc_serial)); + if (ret < 0) { goto fail; } + + hw_serial_str = std::string((char *)desc_serial, ret); + if (serial.empty() || serial == hw_serial_str) { + break; + } + libusb_close(dev_handle); + dev_handle = NULL; + } + } + if (dev_handle == NULL) goto fail; + libusb_free_device_list(dev_list, 1); + + if (libusb_kernel_driver_active(dev_handle, 0) == 1) { + libusb_detach_kernel_driver(dev_handle, 0); + } + + err = libusb_set_configuration(dev_handle, 1); + if (err != 0) { goto fail; } + + err = libusb_claim_interface(dev_handle, 0); + if (err != 0) { goto fail; } + + return true; + +fail: + if (dev_list != NULL) { + libusb_free_device_list(dev_list, 1); + } + cleanup_usb(); + return false; +} + +void Panda::cleanup_usb() { + if (dev_handle) { + libusb_release_interface(dev_handle, 0); + libusb_close(dev_handle); + dev_handle = nullptr; + } + + if (ctx) { + libusb_exit(ctx); + ctx = nullptr; + } + connected_flag = false; +} + +void Panda::handle_usb_issue(int err, const char func[]) { + LOGE_100("usb error %d \"%s\" in %s", err, libusb_strerror((enum libusb_error)err), func); + if (err == LIBUSB_ERROR_NO_DEVICE) { + LOGE("lost connection"); + connected_flag = false; + } +} + +int Panda::control_write(uint8_t bRequest, uint16_t wValue, uint16_t wIndex, unsigned int timeout) { + int err; + const uint8_t bmRequestType = LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE; + + if (!connected_flag) { + return LIBUSB_ERROR_NO_DEVICE; + } + + do { + err = libusb_control_transfer(dev_handle, bmRequestType, bRequest, wValue, wIndex, NULL, 0, timeout); + if (err < 0) handle_usb_issue(err, __func__); + } while (err < 0 && connected_flag); + + return err; +} + +int Panda::control_read(uint8_t bRequest, uint16_t wValue, uint16_t wIndex, unsigned char *data, uint16_t wLength, unsigned int timeout) { + int err; + const uint8_t bmRequestType = LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE; + + if (!connected_flag) { + return LIBUSB_ERROR_NO_DEVICE; + } + + do { + err = libusb_control_transfer(dev_handle, bmRequestType, bRequest, wValue, wIndex, data, wLength, timeout); + if (err < 0) handle_usb_issue(err, __func__); + } while (err < 0 && connected_flag); + + return err; +} + +int Panda::bulk_write(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout) { + int err; + int transferred = 0; + + if (!connected_flag) { + return 0; + } + + do { + err = libusb_bulk_transfer(dev_handle, endpoint, data, length, &transferred, timeout); + if (err == LIBUSB_ERROR_TIMEOUT) { + LOGW("Transmit buffer full"); + break; + } else if (err != 0 || length != transferred) { + handle_usb_issue(err, __func__); + } + } while (err != 0 && connected_flag); + + return transferred; +} + +int Panda::bulk_read(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout) { + int err; + int transferred = 0; + + if (!connected_flag) { + return 0; + } + + do { + err = libusb_bulk_transfer(dev_handle, endpoint, data, length, &transferred, timeout); + if (err == LIBUSB_ERROR_TIMEOUT) { + break; // timeout is okay to exit, recv still happened + } else if (err == LIBUSB_ERROR_OVERFLOW) { + comms_healthy_flag = false; + LOGE_100("overflow got 0x%x", transferred); + } else if (err != 0) { + handle_usb_issue(err, __func__); + } + } while (err != 0 && connected_flag); + + return transferred; +} diff --git a/openpilot/tools/cabana/panda.h b/openpilot/tools/cabana/panda.h new file mode 100644 index 0000000000..216a6b72d7 --- /dev/null +++ b/openpilot/tools/cabana/panda.h @@ -0,0 +1,95 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "openpilot/cereal/gen/cpp/car.capnp.h" +#include "openpilot/cereal/gen/cpp/log.capnp.h" +#include "panda/board/health.h" +#include "panda/board/can.h" + +#define USB_TX_SOFT_LIMIT (0x100U) +#define USBPACKET_MAX_SIZE (0x40) +#define RECV_SIZE (0x4000U) +#define TIMEOUT 0 + +#define CAN_REJECTED_BUS_OFFSET 0xC0U +#define CAN_RETURNED_BUS_OFFSET 0x80U + +#define PANDA_BUS_OFFSET 4 + +struct __attribute__((packed)) can_header { + uint8_t reserved : 1; + uint8_t bus : 3; + uint8_t data_len_code : 4; + uint8_t rejected : 1; + uint8_t returned : 1; + uint8_t extended : 1; + uint32_t addr : 29; + uint8_t checksum : 8; +}; + +struct can_frame { + long address; + std::string dat; + long src; +}; + + +class Panda { +public: + Panda(std::string serial="", uint32_t bus_offset=0); + ~Panda(); + + cereal::PandaState::PandaType hw_type = cereal::PandaState::PandaType::UNKNOWN; + const uint32_t bus_offset; + + bool connected(); + bool comms_healthy(); + std::string hw_serial(); + + // Static functions + static std::vector list(bool usb_only=false); + + // Panda functionality + cereal::PandaState::PandaType get_hw_type(); + void set_safety_model(cereal::CarParams::SafetyModel safety_model, uint16_t safety_param=0U); + void send_heartbeat(bool engaged, bool engaged_mads = false); + void set_can_speed_kbps(uint16_t bus, uint16_t speed); + void set_data_speed_kbps(uint16_t bus, uint16_t speed); + bool can_receive(std::vector& out_vec); + void can_reset_communications(); + +private: + // USB connection members + libusb_context *ctx = nullptr; + libusb_device_handle *dev_handle = nullptr; + std::string hw_serial_str; + std::atomic connected_flag = true; + std::atomic comms_healthy_flag = true; + + // CAN buffer members + uint8_t receive_buffer[RECV_SIZE + sizeof(can_header) + 64]; + uint32_t receive_buffer_size = 0; + + // Internal methods + bool init_usb_connection(const std::string& serial); + void cleanup_usb(); + void handle_usb_issue(int err, const char func[]); + int control_write(uint8_t request, uint16_t param1, uint16_t param2, unsigned int timeout=TIMEOUT); + int control_read(uint8_t request, uint16_t param1, uint16_t param2, unsigned char *data, uint16_t length, unsigned int timeout=TIMEOUT); + int bulk_write(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout=TIMEOUT); + int bulk_read(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout=TIMEOUT); + bool unpack_can_buffer(uint8_t *data, uint32_t &size, std::vector &out_vec); + uint8_t calculate_checksum(uint8_t *data, uint32_t len); +}; diff --git a/openpilot/tools/cabana/settings.cc b/openpilot/tools/cabana/settings.cc new file mode 100644 index 0000000000..0c8136b84c --- /dev/null +++ b/openpilot/tools/cabana/settings.cc @@ -0,0 +1,618 @@ +#include "tools/cabana/settings.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#ifdef __APPLE__ +#include +#endif + +#include +#include +#include +#include +#include +#include + +#include "json11/json11.hpp" +#include "tools/cabana/utils/util.h" + +const int MIN_CACHE_MINIUTES = 30; +const int MAX_CACHE_MINIUTES = 120; + +Settings settings; + +namespace { + +std::filesystem::path settingsFile() { + return utils::configPath() / "cabana.json"; +} + +struct LoadedSettings { + json11::Json::object values; + bool exists = false; + bool valid = true; +}; + +class FileLock { +public: + explicit FileLock(const std::filesystem::path &path) { + fd = open(path.c_str(), O_CREAT | O_CLOEXEC, 0600); + if (fd < 0 || flock(fd, LOCK_EX) < 0) { + fprintf(stderr, "failed to lock Cabana settings %s: %s\n", path.c_str(), strerror(errno)); + if (fd >= 0) close(fd); + fd = -1; + } + } + ~FileLock() { + if (fd >= 0) close(fd); + } + bool isLocked() const { return fd >= 0; } + +private: + int fd = -1; +}; + +LoadedSettings loadSettings() { + std::ifstream input(settingsFile()); + if (!input) return {}; + + const std::string contents{std::istreambuf_iterator(input), std::istreambuf_iterator()}; + std::string error; + auto settings_json = json11::Json::parse(contents, error); + if (!error.empty() || !settings_json.is_object()) { + fprintf(stderr, "failed to read Cabana settings %s%s%s\n", settingsFile().c_str(), error.empty() ? "" : ": ", error.c_str()); + return {.exists = true, .valid = false}; + } + return {.values = settings_json.object_items(), .exists = true}; +} + +bool ensureSettingsDirectory() { + const auto path = settingsFile(); + std::error_code error; + std::filesystem::create_directories(path.parent_path(), error); + if (error) { + fprintf(stderr, "failed to create Cabana settings directory %s: %s\n", path.parent_path().c_str(), error.message().c_str()); + return false; + } + return true; +} + +bool writeAll(int fd, const std::string &data) { + size_t written = 0; + while (written < data.size()) { + ssize_t result = write(fd, data.data() + written, data.size() - written); + if (result < 0 && errno == EINTR) continue; + if (result <= 0) return false; + written += result; + } + return true; +} + +bool saveSettings(const json11::Json::object &settings_json) { + const auto path = settingsFile(); + const std::string contents = json11::Json(settings_json).dump(); + std::string temporary_path = path.string() + ".tmp.XXXXXX"; + int fd = mkstemp(temporary_path.data()); + if (fd < 0) { + fprintf(stderr, "failed to create temporary Cabana settings %s: %s\n", temporary_path.c_str(), strerror(errno)); + return false; + } + + bool success = writeAll(fd, contents) && fsync(fd) == 0; + if (close(fd) < 0) success = false; + if (success && rename(temporary_path.c_str(), path.c_str()) < 0) success = false; + + if (success) { + int dir_fd = open(path.parent_path().c_str(), O_RDONLY | O_CLOEXEC); + success = dir_fd >= 0 && fsync(dir_fd) == 0; + if (dir_fd >= 0 && close(dir_fd) < 0) success = false; + } + + if (!success) { + const int saved_errno = errno; + unlink(temporary_path.c_str()); + fprintf(stderr, "failed to save Cabana settings to %s: %s\n", path.c_str(), strerror(saved_errno)); + } + return success; +} + +bool preserveCorruptSettings() { + const auto path = settingsFile(); + auto backup = path; + backup += ".corrupt"; + for (int i = 1; std::filesystem::exists(backup); ++i) { + backup = path; + backup += ".corrupt." + std::to_string(i); + } + if (rename(path.c_str(), backup.c_str()) < 0) { + fprintf(stderr, "failed to preserve corrupt Cabana settings %s: %s\n", path.c_str(), strerror(errno)); + return false; + } + fprintf(stderr, "preserved corrupt Cabana settings at %s\n", backup.c_str()); + return true; +} + +// TODO: Remove the legacy QSettings migration after users have had time to migrate to cabana.json. +struct LegacyValue { + std::vector strings; + std::string bytes; + bool is_byte_array = false; +}; + +using LegacySettings = std::map; + +int hexDigit(char c) { + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'a' && c <= 'f') return c - 'a' + 10; + if (c >= 'A' && c <= 'F') return c - 'A' + 10; + return -1; +} + +#ifndef __APPLE__ + +void appendUtf8(std::string &result, uint32_t codepoint) { + if (codepoint <= 0x7f) { + result.push_back(codepoint); + } else if (codepoint <= 0x7ff) { + result.push_back(0xc0 | (codepoint >> 6)); + result.push_back(0x80 | (codepoint & 0x3f)); + } else if (codepoint <= 0xffff) { + result.push_back(0xe0 | (codepoint >> 12)); + result.push_back(0x80 | ((codepoint >> 6) & 0x3f)); + result.push_back(0x80 | (codepoint & 0x3f)); + } else { + result.push_back(0xf0 | (codepoint >> 18)); + result.push_back(0x80 | ((codepoint >> 12) & 0x3f)); + result.push_back(0x80 | ((codepoint >> 6) & 0x3f)); + result.push_back(0x80 | (codepoint & 0x3f)); + } +} + +LegacyValue decodeIniValue(std::string_view encoded) { + std::vector> decoded(1); + std::vector quoted(1, false); + bool in_quotes = false; + + for (size_t i = 0; i < encoded.size();) { + char c = encoded[i++]; + if (c == '"') { + in_quotes = !in_quotes; + quoted.back() = true; + } else if (c == ',' && !in_quotes) { + decoded.emplace_back(); + quoted.push_back(false); + while (i < encoded.size() && (encoded[i] == ' ' || encoded[i] == '\t')) ++i; + } else if (c == '\\' && i < encoded.size()) { + c = encoded[i++]; + static const std::map escapes = { + {'a', '\a'}, {'b', '\b'}, {'f', '\f'}, {'n', '\n'}, {'r', '\r'}, {'t', '\t'}, + {'v', '\v'}, {'"', '"'}, {'?', '?'}, {'\'', '\''}, {'\\', '\\'}, + }; + if (auto it = escapes.find(c); it != escapes.end()) { + decoded.back().push_back(static_cast(it->second)); + } else if (c == 'x' && i < encoded.size() && hexDigit(encoded[i]) >= 0) { + uint32_t value = 0; + while (i < encoded.size() && hexDigit(encoded[i]) >= 0) value = (value << 4) + hexDigit(encoded[i++]); + decoded.back().push_back(value & 0xffff); + } else if (c >= '0' && c <= '7') { + uint32_t value = c - '0'; + while (i < encoded.size() && encoded[i] >= '0' && encoded[i] <= '7') value = (value << 3) + (encoded[i++] - '0'); + decoded.back().push_back(value & 0xffff); + } + } else { + decoded.back().push_back(static_cast(c)); + } + } + + LegacyValue result; + for (size_t i = 0; i < decoded.size(); ++i) { + auto &value = decoded[i]; + if (!quoted[i]) { + while (!value.empty() && (value.front() == ' ' || value.front() == '\t')) value.erase(value.begin()); + while (!value.empty() && (value.back() == ' ' || value.back() == '\t')) value.pop_back(); + } + + std::string string_value; + for (size_t j = 0; j < value.size(); ++j) { + uint32_t codepoint = value[j]; + if (codepoint >= 0xd800 && codepoint <= 0xdbff && j + 1 < value.size() && value[j + 1] >= 0xdc00 && value[j + 1] <= 0xdfff) { + codepoint = 0x10000 + ((codepoint - 0xd800) << 10) + (value[++j] - 0xdc00); + } + appendUtf8(string_value, codepoint); + } + result.strings.push_back(std::move(string_value)); + } + + if (result.strings.size() == 1 && result.strings[0] == "@Invalid()") { + result.strings.clear(); + } else if (decoded.size() == 1) { + static constexpr std::string_view prefix = "@ByteArray("; + const auto &value = decoded[0]; + if (value.size() >= prefix.size() + 1 && std::equal(prefix.begin(), prefix.end(), value.begin()) && value.back() == ')') { + result.is_byte_array = true; + result.bytes.reserve(value.size() - prefix.size() - 1); + for (size_t i = prefix.size(); i + 1 < value.size(); ++i) result.bytes.push_back(value[i] & 0xff); + } + } + if (!result.is_byte_array) { + for (auto &value : result.strings) { + if (value.compare(0, 2, "@@") == 0) value.erase(0, 1); + } + } + return result; +} + +LegacySettings loadLegacySettings() { + auto path = settingsFile(); + path.replace_filename("cabana.conf"); + std::ifstream input(path); + if (!input) return {}; + + LegacySettings settings; + bool in_general_section = false; + std::string line; + while (std::getline(input, line)) { + if (!line.empty() && line.back() == '\r') line.pop_back(); + if (line == "[General]") { + in_general_section = true; + continue; + } + if (!line.empty() && line.front() == '[') { + in_general_section = false; + continue; + } + if (!in_general_section || line.empty() || line.front() == ';') continue; + if (auto separator = line.find('='); separator != std::string::npos) { + settings[line.substr(0, separator)] = decodeIniValue(std::string_view(line).substr(separator + 1)); + } + } + return settings; +} + +#else + +std::string cfStringToUtf8(CFStringRef value) { + CFIndex length = CFStringGetLength(value); + CFIndex size = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8) + 1; + std::string result(size, '\0'); + if (!CFStringGetCString(value, result.data(), size, kCFStringEncodingUTF8)) return {}; + result.resize(strlen(result.c_str())); + return result; +} + +LegacyValue cfStringValue(CFStringRef string) { + LegacyValue value; + if (CFStringHasPrefix(string, CFSTR("@ByteArray(")) && CFStringHasSuffix(string, CFSTR(")"))) { + CFRange range{11, CFStringGetLength(string) - 12}; + std::vector data(range.length); + CFStringGetCharacters(string, range, data.data()); + value.is_byte_array = true; + value.bytes.reserve(data.size()); + for (UniChar c : data) value.bytes.push_back(c & 0xff); + } else { + std::string string_value = cfStringToUtf8(string); + if (string_value.compare(0, 2, "@@") == 0) string_value.erase(0, 1); + value.strings.push_back(std::move(string_value)); + } + return value; +} + +LegacySettings loadLegacySettings() { + LegacySettings settings; + CFDictionaryRef values = CFPreferencesCopyMultiple(nullptr, CFSTR("com.cabana"), + kCFPreferencesCurrentUser, kCFPreferencesAnyHost); + if (values == nullptr) return settings; + + CFIndex count = CFDictionaryGetCount(values); + std::vector keys(count); + std::vector objects(count); + CFDictionaryGetKeysAndValues(values, keys.data(), objects.data()); + for (CFIndex i = 0; i < count; ++i) { + if (CFGetTypeID(keys[i]) != CFStringGetTypeID()) continue; + std::string key = cfStringToUtf8(static_cast(keys[i])); + CFTypeRef object = objects[i]; + LegacyValue value; + if (CFGetTypeID(object) == CFBooleanGetTypeID()) { + value.strings.push_back(CFBooleanGetValue(static_cast(object)) ? "true" : "false"); + } else if (CFGetTypeID(object) == CFNumberGetTypeID()) { + int number = 0; + if (CFNumberGetValue(static_cast(object), kCFNumberIntType, &number)) value.strings.push_back(std::to_string(number)); + } else if (CFGetTypeID(object) == CFStringGetTypeID()) { + value = cfStringValue(static_cast(object)); + } else if (CFGetTypeID(object) == CFDataGetTypeID()) { + auto data = static_cast(object); + value.is_byte_array = true; + value.bytes.assign(reinterpret_cast(CFDataGetBytePtr(data)), CFDataGetLength(data)); + } else if (CFGetTypeID(object) == CFArrayGetTypeID()) { + auto array = static_cast(object); + for (CFIndex j = 0; j < CFArrayGetCount(array); ++j) { + CFTypeRef item = CFArrayGetValueAtIndex(array, j); + if (CFGetTypeID(item) != CFStringGetTypeID()) { + value.strings.clear(); + break; + } + auto item_value = cfStringValue(static_cast(item)); + if (item_value.strings.size() != 1) { + value.strings.clear(); + break; + } + value.strings.push_back(std::move(item_value.strings[0])); + } + } + if (!value.strings.empty() || value.is_byte_array || CFGetTypeID(object) == CFArrayGetTypeID()) { + settings.emplace(std::move(key), std::move(value)); + } + } + CFRelease(values); + return settings; +} + +#endif + +template +void readLegacySetting(const LegacySettings &legacy_settings, const char *key, T &value) { + auto it = legacy_settings.find(key); + if (it == legacy_settings.end() || it->second.strings.size() != 1) return; + const auto &stored = it->second.strings[0]; + + if constexpr (std::is_same_v) { + if (stored == "true") value = true; + if (stored == "false") value = false; + } else if constexpr (std::is_integral_v || std::is_enum_v) { + int number = 0; + auto [end, error] = std::from_chars(stored.data(), stored.data() + stored.size(), number); + if (error == std::errc{} && end == stored.data() + stored.size()) value = static_cast(number); + } +} + +void readLegacySetting(const LegacySettings &legacy_settings, const char *key, std::string &value) { + auto it = legacy_settings.find(key); + if (it != legacy_settings.end() && it->second.strings.size() == 1) value = it->second.strings[0]; +} + +void readLegacySetting(const LegacySettings &legacy_settings, const char *key, std::vector &value) { + auto it = legacy_settings.find(key); + if (it != legacy_settings.end() && !it->second.is_byte_array) value = it->second.strings; +} + +void readLegacySetting(const LegacySettings &legacy_settings, const char *key, std::vector &value) { + auto it = legacy_settings.find(key); + if (it != legacy_settings.end() && it->second.is_byte_array) { + value.assign(it->second.bytes.begin(), it->second.bytes.end()); + } +} + +template +void readSetting(const json11::Json::object &settings_json, const char *key, T &value) { + auto it = settings_json.find(key); + if (it == settings_json.end()) return; + + if constexpr (std::is_same_v) { + if (it->second.is_bool()) value = it->second.bool_value(); + } else if constexpr (std::is_integral_v) { + if (it->second.is_number()) value = it->second.int_value(); + } else if constexpr (std::is_enum_v) { + if (it->second.is_number()) value = static_cast(it->second.int_value()); + } +} + +void readSetting(const json11::Json::object &settings_json, const char *key, std::string &value) { + auto it = settings_json.find(key); + if (it != settings_json.end() && it->second.is_string()) value = it->second.string_value(); +} + +void readSetting(const json11::Json::object &settings_json, const char *key, std::vector &value) { + auto it = settings_json.find(key); + if (it == settings_json.end() || !it->second.is_array()) return; + + std::vector stored; + for (const auto &item : it->second.array_items()) { + if (!item.is_string()) return; + stored.push_back(item.string_value()); + } + value = std::move(stored); +} + +void readSetting(const json11::Json::object &settings_json, const char *key, std::vector &value) { + auto it = settings_json.find(key); + if (it == settings_json.end() || !it->second.is_string()) return; + + const auto &hex = it->second.string_value(); + if (hex.size() % 2 == 0 && std::all_of(hex.begin(), hex.end(), [](unsigned char c) { return std::isxdigit(c); })) { + value.clear(); + value.reserve(hex.size() / 2); + for (size_t i = 0; i < hex.size(); i += 2) { + value.push_back((hexDigit(hex[i]) << 4) | hexDigit(hex[i + 1])); + } + } +} + +template +void writeSetting(json11::Json::object &settings_json, const char *key, const T &value) { + if constexpr (std::is_same_v) { + settings_json[key] = value; + } else if constexpr (std::is_integral_v || std::is_enum_v) { + settings_json[key] = static_cast(value); + } +} + +void writeSetting(json11::Json::object &settings_json, const char *key, const std::string &value) { + settings_json[key] = value; +} + +void writeSetting(json11::Json::object &settings_json, const char *key, const std::vector &value) { + settings_json[key] = value; +} + +void writeSetting(json11::Json::object &settings_json, const char *key, const std::vector &value) { + static const char digits[] = "0123456789abcdef"; + std::string hex; + hex.reserve(value.size() * 2); + for (uint8_t b : value) { + hex.push_back(digits[b >> 4]); + hex.push_back(digits[b & 0xf]); + } + settings_json[key] = hex; +} + +template +void settingsOp(Store &s, SettingOperation op) { + op(s, "absolute_time", settings.absolute_time); + op(s, "fps", settings.fps); + op(s, "max_cached_minutes", settings.max_cached_minutes); + op(s, "chart_height", settings.chart_height); + op(s, "chart_range", settings.chart_range); + op(s, "chart_column_count", settings.chart_column_count); + op(s, "last_dir", settings.last_dir); + op(s, "last_route_dir", settings.last_route_dir); + op(s, "window_state", settings.window_state); + op(s, "geometry", settings.geometry); + op(s, "video_splitter_state", settings.video_splitter_state); + op(s, "recent_files", settings.recent_files); + op(s, "message_header_state", settings.message_header_state); + op(s, "chart_series_type", settings.chart_series_type); + op(s, "theme", settings.theme); + op(s, "sparkline_range", settings.sparkline_range); + op(s, "multiple_lines_hex", settings.multiple_lines_hex); + op(s, "log_livestream", settings.log_livestream); + op(s, "log_path", settings.log_path); + op(s, "drag_direction", (int &)settings.drag_direction); + op(s, "suppress_defined_signals", settings.suppress_defined_signals); + op(s, "recent_dbc_file", settings.recent_dbc_file); + op(s, "active_msg_id", settings.active_msg_id); + op(s, "selected_msg_ids", settings.selected_msg_ids); + op(s, "active_charts", settings.active_charts); +} + +} // namespace + +Settings::Settings() { + last_dir = last_route_dir = utils::homePath(); + log_path = utils::homePath() + "/cabana_live_stream/"; + const auto stored_settings = loadSettings(); + if (stored_settings.valid) { + if (stored_settings.exists) { + settingsOp(stored_settings.values, [](const auto &s, const char *key, auto &value) { readSetting(s, key, value); }); + } else { + auto legacy_settings = loadLegacySettings(); + settingsOp(legacy_settings, [](const auto &s, const char *key, auto &value) { readLegacySetting(s, key, value); }); + } + } + fps = std::clamp(fps, 1, 100); +} + +// Must be called before main() returns: json11's internal statistics are constructed on first +// use at runtime, so they are destroyed before this pre-main global. Saving from ~Settings +// would use them after destruction and corrupt the heap. +void Settings::save() { + if (!ensureSettingsDirectory()) return; + + auto lock_path = settingsFile(); + lock_path += ".lock"; + FileLock lock(lock_path); + if (!lock.isLocked()) return; + + auto stored_settings = loadSettings(); + if (!stored_settings.valid && !preserveCorruptSettings()) return; + settingsOp(stored_settings.values, [](auto &s, const char *key, const auto &value) { writeSetting(s, key, value); }); + saveSettings(stored_settings.values); +} + +// SettingsDlg + +SettingsDlg::SettingsDlg(QWidget *parent) : QDialog(parent) { + setWindowTitle(tr("Settings")); + QVBoxLayout *main_layout = new QVBoxLayout(this); + QGroupBox *groupbox = new QGroupBox("General"); + QFormLayout *form_layout = new QFormLayout(groupbox); + + form_layout->addRow(tr("Color Theme"), theme = new QComboBox(this)); + theme->setToolTip(tr("You may need to restart cabana after changes theme")); + theme->addItems({tr("Automatic"), tr("Light"), tr("Dark")}); + theme->setCurrentIndex(settings.theme); + + form_layout->addRow("FPS", fps = new QSpinBox(this)); + fps->setRange(10, 100); + fps->setSingleStep(10); + fps->setValue(settings.fps); + + form_layout->addRow(tr("Max Cached Minutes"), cached_minutes = new QSpinBox(this)); + cached_minutes->setRange(MIN_CACHE_MINIUTES, MAX_CACHE_MINIUTES); + cached_minutes->setSingleStep(1); + cached_minutes->setValue(settings.max_cached_minutes); + main_layout->addWidget(groupbox); + + groupbox = new QGroupBox("New Signal Settings"); + form_layout = new QFormLayout(groupbox); + form_layout->addRow(tr("Drag Direction"), drag_direction = new QComboBox(this)); + drag_direction->addItems({tr("MSB First"), tr("LSB First"), tr("Always Little Endian"), tr("Always Big Endian")}); + drag_direction->setCurrentIndex(settings.drag_direction); + main_layout->addWidget(groupbox); + + groupbox = new QGroupBox("Chart"); + form_layout = new QFormLayout(groupbox); + form_layout->addRow(tr("Chart Height"), chart_height = new QSpinBox(this)); + chart_height->setRange(100, 500); + chart_height->setSingleStep(10); + chart_height->setValue(settings.chart_height); + main_layout->addWidget(groupbox); + + log_livestream = new QGroupBox(tr("Enable live stream logging"), this); + log_livestream->setCheckable(true); + log_livestream->setChecked(settings.log_livestream); + QHBoxLayout *path_layout = new QHBoxLayout(log_livestream); + path_layout->addWidget(log_path = new QLineEdit(QString::fromStdString(settings.log_path), this)); + log_path->setReadOnly(true); + auto browse_btn = new QPushButton(tr("B&rowse...")); + path_layout->addWidget(browse_btn); + main_layout->addWidget(log_livestream); + + auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + main_layout->addWidget(buttonBox); + setFixedSize(400, sizeHint().height()); + + QObject::connect(browse_btn, &QPushButton::clicked, [this]() { + QString fn = QFileDialog::getExistingDirectory( + this, tr("Log File Location"), + QString::fromStdString(utils::homePath()), + QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); + if (!fn.isEmpty()) { + log_path->setText(fn); + } + }); + QObject::connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); + QObject::connect(buttonBox, &QDialogButtonBox::accepted, this, &SettingsDlg::save); +} + +void SettingsDlg::save() { + if (std::exchange(settings.theme, theme->currentIndex()) != settings.theme) { + // set theme before emit changed + utils::setTheme(settings.theme); + } + settings.fps = fps->value(); + settings.max_cached_minutes = cached_minutes->value(); + settings.chart_height = chart_height->value(); + settings.log_livestream = log_livestream->isChecked(); + settings.log_path = log_path->text().toStdString(); + settings.drag_direction = (Settings::DragDirection)drag_direction->currentIndex(); + emit settings.changed(); + QDialog::accept(); +} diff --git a/openpilot/tools/cabana/settings.h b/openpilot/tools/cabana/settings.h new file mode 100644 index 0000000000..7357ecf4fc --- /dev/null +++ b/openpilot/tools/cabana/settings.h @@ -0,0 +1,45 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include + +#include "tools/cabana/core/settings.h" + +class Settings : public QObject, public CabanaSettingsState { + Q_OBJECT + +public: + Settings(); + void save(); + + // Qt frontend layout state. This intentionally stays outside CabanaSettingsState. + std::vector geometry; + std::vector video_splitter_state; + std::vector window_state; + std::vector message_header_state; + +signals: + void changed(); +}; + +class SettingsDlg : public QDialog { +public: + SettingsDlg(QWidget *parent); + void save(); + QSpinBox *fps; + QSpinBox *cached_minutes; + QSpinBox *chart_height; + QComboBox *chart_series_type; + QComboBox *theme; + QGroupBox *log_livestream; + QLineEdit *log_path; + QComboBox *drag_direction; +}; + +extern Settings settings; diff --git a/tools/cabana/signalview.cc b/openpilot/tools/cabana/signalview.cc similarity index 86% rename from tools/cabana/signalview.cc rename to openpilot/tools/cabana/signalview.cc index 9fe70c3ee8..ebb5374140 100644 --- a/tools/cabana/signalview.cc +++ b/openpilot/tools/cabana/signalview.cc @@ -1,8 +1,9 @@ #include "tools/cabana/signalview.h" +#include "tools/cabana/dbc/dbcqt.h" #include +#include -#include #include #include #include @@ -11,10 +12,10 @@ #include #include #include -#include #include #include "tools/cabana/commands.h" +#include "tools/cabana/utils/util.h" // SignalModel @@ -25,21 +26,21 @@ static QString signalTypeToString(cabana::Signal::Type type) { } SignalModel::SignalModel(QObject *parent) : root(new Item), QAbstractItemModel(parent) { - QObject::connect(dbc(), &DBCManager::DBCFileChanged, this, &SignalModel::refresh); - QObject::connect(dbc(), &DBCManager::msgUpdated, this, &SignalModel::handleMsgChanged); - QObject::connect(dbc(), &DBCManager::msgRemoved, this, &SignalModel::handleMsgChanged); - QObject::connect(dbc(), &DBCManager::signalAdded, this, &SignalModel::handleSignalAdded); - QObject::connect(dbc(), &DBCManager::signalUpdated, this, &SignalModel::handleSignalUpdated); - QObject::connect(dbc(), &DBCManager::signalRemoved, this, &SignalModel::handleSignalRemoved); + QObject::connect(dbcNotifier(), &QtDBCNotifier::DBCFileChanged, this, &SignalModel::refresh); + QObject::connect(dbcNotifier(), &QtDBCNotifier::msgUpdated, this, &SignalModel::handleMsgChanged); + QObject::connect(dbcNotifier(), &QtDBCNotifier::msgRemoved, this, &SignalModel::handleMsgChanged); + QObject::connect(dbcNotifier(), &QtDBCNotifier::signalAdded, this, &SignalModel::handleSignalAdded); + QObject::connect(dbcNotifier(), &QtDBCNotifier::signalUpdated, this, &SignalModel::handleSignalUpdated); + QObject::connect(dbcNotifier(), &QtDBCNotifier::signalRemoved, this, &SignalModel::handleSignalRemoved); } void SignalModel::insertItem(SignalModel::Item *root_item, int pos, const cabana::Signal *sig) { - Item *parent_item = new Item{.sig = sig, .parent = root_item, .title = sig->name, .type = Item::Sig}; - root_item->children.insert(pos, parent_item); + Item *parent_item = new Item{.type = Item::Sig, .parent = root_item, .sig = sig, .title = QString::fromStdString(sig->name)}; + root_item->children.insert(root_item->children.begin() + pos, parent_item); QString titles[]{"Name", "Size", "Receiver Nodes", "Little Endian", "Signed", "Offset", "Factor", "Type", "Multiplex Value", "Extra Info", "Unit", "Comment", "Minimum Value", "Maximum Value", "Value Table"}; for (int i = 0; i < std::size(titles); ++i) { - auto item = new Item{.sig = sig, .parent = parent_item, .title = titles[i], .type = (Item::Type)(i + Item::Name)}; + auto item = new Item{.type = (Item::Type)(i + Item::Name), .parent = parent_item, .sig = sig, .title = titles[i]}; parent_item->children.push_back(item); if (item->type == Item::ExtraInfo) { parent_item = item; @@ -63,7 +64,7 @@ void SignalModel::refresh() { root.reset(new SignalModel::Item); if (auto msg = dbc()->msg(msg_id)) { for (auto s : msg->getSignals()) { - if (filter_str.isEmpty() || s->name.contains(filter_str, Qt::CaseInsensitive)) { + if (filter_str.isEmpty() || QString::fromStdString(s->name).contains(filter_str, Qt::CaseInsensitive)) { insertItem(root.get(), root->children.size(), s); } } @@ -124,25 +125,25 @@ QVariant SignalModel::data(const QModelIndex &index, int role) const { const Item *item = getItem(index); if (role == Qt::DisplayRole || role == Qt::EditRole) { if (index.column() == 0) { - return item->type == Item::Sig ? item->sig->name : item->title; + return item->type == Item::Sig ? QString::fromStdString(item->sig->name) : item->title; } else { switch (item->type) { case Item::Sig: return item->sig_val; - case Item::Name: return item->sig->name; + case Item::Name: return QString::fromStdString(item->sig->name); case Item::Size: return item->sig->size; - case Item::Node: return item->sig->receiver_name; + case Item::Node: return QString::fromStdString(item->sig->receiver_name); case Item::SignalType: return signalTypeToString(item->sig->type); case Item::MultiplexValue: return item->sig->multiplex_value; - case Item::Offset: return doubleToString(item->sig->offset); - case Item::Factor: return doubleToString(item->sig->factor); - case Item::Unit: return item->sig->unit; - case Item::Comment: return item->sig->comment; - case Item::Min: return doubleToString(item->sig->min); - case Item::Max: return doubleToString(item->sig->max); + case Item::Offset: return QString::fromStdString(doubleToString(item->sig->offset)); + case Item::Factor: return QString::fromStdString(doubleToString(item->sig->factor)); + case Item::Unit: return QString::fromStdString(item->sig->unit); + case Item::Comment: return QString::fromStdString(item->sig->comment); + case Item::Min: return QString::fromStdString(doubleToString(item->sig->min)); + case Item::Max: return QString::fromStdString(doubleToString(item->sig->max)); case Item::Desc: { QStringList val_desc; for (auto &[val, desc] : item->sig->val_desc) { - val_desc << QString("%1 \"%2\"").arg(val).arg(desc); + val_desc << QString("%1 \"%2\"").arg(val).arg(QString::fromStdString(desc)); } return val_desc.join(" "); } @@ -165,17 +166,17 @@ bool SignalModel::setData(const QModelIndex &index, const QVariant &value, int r Item *item = getItem(index); cabana::Signal s = *item->sig; switch (item->type) { - case Item::Name: s.name = value.toString(); break; + case Item::Name: s.name = value.toString().toStdString(); break; case Item::Size: s.size = value.toInt(); break; - case Item::Node: s.receiver_name = value.toString().trimmed(); break; + case Item::Node: s.receiver_name = value.toString().trimmed().toStdString(); break; case Item::SignalType: s.type = (cabana::Signal::Type)value.toInt(); break; case Item::MultiplexValue: s.multiplex_value = value.toInt(); break; case Item::Endian: s.is_little_endian = value.toBool(); break; case Item::Signed: s.is_signed = value.toBool(); break; case Item::Offset: s.offset = value.toDouble(); break; case Item::Factor: s.factor = value.toDouble(); break; - case Item::Unit: s.unit = value.toString(); break; - case Item::Comment: s.comment = value.toString(); break; + case Item::Unit: s.unit = value.toString().toStdString(); break; + case Item::Comment: s.comment = value.toString().toStdString(); break; case Item::Min: s.min = value.toDouble(); break; case Item::Max: s.max = value.toDouble(); break; case Item::Desc: s.val_desc = value.value(); break; @@ -189,7 +190,7 @@ bool SignalModel::setData(const QModelIndex &index, const QVariant &value, int r bool SignalModel::saveSignal(const cabana::Signal *origin_s, cabana::Signal &s) { auto msg = dbc()->msg(msg_id); if (s.name != origin_s->name && msg->sig(s.name) != nullptr) { - QString text = tr("There is already a signal with the same name '%1'").arg(s.name); + QString text = tr("There is already a signal with the same name '%1'").arg(QString::fromStdString(s.name)); QMessageBox::warning(nullptr, tr("Failed to save signal"), text); return false; } @@ -197,7 +198,7 @@ bool SignalModel::saveSignal(const cabana::Signal *origin_s, cabana::Signal &s) if (s.is_little_endian != origin_s->is_little_endian) { s.start_bit = flipBitPos(s.start_bit); } - UndoStack::push(new EditSignalCommand(msg_id, origin_s, s)); + UndoStack::instance()->push(new EditSignalCommand(msg_id, origin_s, s)); return true; } @@ -214,7 +215,7 @@ void SignalModel::handleSignalAdded(MessageId id, const cabana::Signal *sig) { beginInsertRows({}, i, i); insertItem(root.get(), i, sig); endInsertRows(); - } else if (sig->name.contains(filter_str, Qt::CaseInsensitive)) { + } else if (QString::fromStdString(sig->name).contains(filter_str, Qt::CaseInsensitive)) { refresh(); } } @@ -229,7 +230,9 @@ void SignalModel::handleSignalUpdated(const cabana::Signal *sig) { int to = dbc()->msg(msg_id)->indexOf(sig); if (to != row) { beginMoveRows({}, row, row, {}, to > row ? to + 1 : to); - root->children.move(row, to); + auto item = root->children[row]; + root->children.erase(root->children.begin() + row); + root->children.insert(root->children.begin() + to, item); endMoveRows(); } } @@ -239,7 +242,8 @@ void SignalModel::handleSignalUpdated(const cabana::Signal *sig) { void SignalModel::handleSignalRemoved(const cabana::Signal *sig) { if (int row = signalRow(sig); row != -1) { beginRemoveRows({}, row, row); - delete root->children.takeAt(row); + delete root->children[row]; + root->children.erase(root->children.begin() + row); endRemoveRows(); } } @@ -248,7 +252,7 @@ void SignalModel::handleSignalRemoved(const cabana::Signal *sig) { SignalItemDelegate::SignalItemDelegate(QObject *parent) : QStyledItemDelegate(parent) { name_validator = new NameValidator(this); - node_validator = new QRegExpValidator(QRegExp("^\\w+(,\\w+)*$"), this); + node_validator = new NodeValidator(this); double_validator = new DoubleValidator(this); label_font.setPointSize(8); @@ -265,7 +269,7 @@ QSize SignalItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QMo text += item->sig->type == cabana::Signal::Type::Multiplexor ? QString(" M ") : QString(" m%1 ").arg(item->sig->multiplex_value); spacing += (option.widget->style()->pixelMetric(QStyle::PM_FocusFrameHMargin) + 1) * 2; } - width = std::min(option.widget->size().width() / 3.0, option.fontMetrics.width(text) + spacing); + width = std::min(option.widget->size().width() / 3.0, option.fontMetrics.horizontalAdvance(text) + spacing); } return {width, option.fontMetrics.height() + option.widget->style()->pixelMetric(QStyle::PM_FocusFrameVMargin) * 2}; } @@ -301,14 +305,14 @@ void SignalItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &op path.addRoundedRect(icon_rect, 3, 3); painter->setPen(item->highlight ? Qt::white : Qt::black); painter->setFont(label_font); - painter->fillPath(path, item->sig->color.darker(item->highlight ? 125 : 0)); + painter->fillPath(path, toQColor(item->sig->color.darker(item->highlight ? 125 : 0))); painter->drawText(icon_rect, Qt::AlignCenter, QString::number(item->row() + 1)); rect.setLeft(icon_rect.right() + h_margin * 2); // multiplexer indicator if (item->sig->type != cabana::Signal::Type::Normal) { QString indicator = item->sig->type == cabana::Signal::Type::Multiplexor ? QString(" M ") : QString(" m%1 ").arg(item->sig->multiplex_value); - QRect indicator_rect{rect.x(), rect.y(), option.fontMetrics.width(indicator), rect.height()}; + QRect indicator_rect{rect.x(), rect.y(), option.fontMetrics.horizontalAdvance(indicator), rect.height()}; painter->setBrush(Qt::gray); painter->setPen(Qt::NoPen); painter->drawRoundedRect(indicator_rect, 3, 3); @@ -342,13 +346,13 @@ void SignalItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &op painter->drawText(rect, Qt::AlignLeft | Qt::AlignTop, max); painter->drawText(rect, Qt::AlignLeft | Qt::AlignBottom, min); QFontMetrics fm(minmax_font); - value_adjust = std::max(fm.width(min), fm.width(max)) + 5; + value_adjust = std::max(fm.horizontalAdvance(min), fm.horizontalAdvance(max)) + 5; } else if (!item->sparkline.isEmpty() && item->sig->type == cabana::Signal::Type::Multiplexed) { // display freq of multiplexed signal painter->setFont(label_font); QString freq = QString("%1 hz").arg(item->sparkline.freq(), 0, 'g', 2); painter->drawText(rect.adjusted(5, 0, 0, 0), Qt::AlignLeft | Qt::AlignVCenter, freq); - value_adjust = QFontMetrics(label_font).width(freq) + 10; + value_adjust = QFontMetrics(label_font).horizontalAdvance(freq) + 10; } // signal value painter->setFont(option.font); @@ -372,12 +376,6 @@ QWidget *SignalItemDelegate::createEditor(QWidget *parent, const QStyleOptionVie else if (item->type == SignalModel::Item::Node) e->setValidator(node_validator); else e->setValidator(double_validator); - if (item->type == SignalModel::Item::Name) { - QCompleter *completer = new QCompleter(dbc()->signalNames(), e); - completer->setCaseSensitivity(Qt::CaseInsensitive); - completer->setFilterMode(Qt::MatchContains); - e->setCompleter(completer); - } return e; } else if (item->type == SignalModel::Item::Size) { QSpinBox *spin = new QSpinBox(parent); @@ -395,7 +393,7 @@ QWidget *SignalItemDelegate::createEditor(QWidget *parent, const QStyleOptionVie return c; } else if (item->type == SignalModel::Item::Desc) { ValueDescriptionDlg dlg(item->sig->val_desc, parent); - dlg.setWindowTitle(item->sig->name); + dlg.setWindowTitle(QString::fromStdString(item->sig->name)); if (dlg.exec()) { ((QAbstractItemModel *)index.model())->setData(index, QVariant::fromValue(dlg.val_desc)); } @@ -422,8 +420,7 @@ SignalView::SignalView(ChartsWidget *charts, QWidget *parent) : charts(charts), QHBoxLayout *hl = new QHBoxLayout(title_bar); hl->addWidget(signal_count_lb = new QLabel()); filter_edit = new QLineEdit(this); - QRegularExpression re("\\S+"); - filter_edit->setValidator(new QRegularExpressionValidator(re, this)); + filter_edit->setValidator(new NonWhitespaceValidator(this)); filter_edit->setClearButtonEnabled(true); filter_edit->setPlaceholderText(tr("Filter Signal")); hl->addWidget(filter_edit); @@ -475,8 +472,8 @@ SignalView::SignalView(ChartsWidget *charts, QWidget *parent) : charts(charts), QObject::connect(tree, &QTreeView::entered, [this](const QModelIndex &index) { emit highlight(model->getItem(index)->sig); }); QObject::connect(model, &QAbstractItemModel::modelReset, this, &SignalView::rowsChanged); QObject::connect(model, &QAbstractItemModel::rowsRemoved, this, &SignalView::rowsChanged); - QObject::connect(dbc(), &DBCManager::signalAdded, this, &SignalView::handleSignalAdded); - QObject::connect(dbc(), &DBCManager::signalUpdated, this, &SignalView::handleSignalUpdated); + QObject::connect(dbcNotifier(), &QtDBCNotifier::signalAdded, this, &SignalView::handleSignalAdded); + QObject::connect(dbcNotifier(), &QtDBCNotifier::signalUpdated, this, &SignalView::handleSignalUpdated); QObject::connect(tree->verticalScrollBar(), &QScrollBar::valueChanged, [this]() { updateState(); }); QObject::connect(tree->verticalScrollBar(), &QScrollBar::rangeChanged, [this]() { updateState(); }); QObject::connect(can, &AbstractStream::msgsReceived, this, &SignalView::updateState); @@ -489,7 +486,7 @@ SignalView::SignalView(ChartsWidget *charts, QWidget *parent) : charts(charts), setWhatsThis(tr(R"( Signal view
- + )")); } @@ -518,7 +515,7 @@ void SignalView::rowsChanged() { tree->setIndexWidget(index, w); auto sig = model->getItem(index)->sig; - QObject::connect(remove_btn, &QToolButton::clicked, [=]() { UndoStack::push(new RemoveSigCommand(model->msg_id, sig)); }); + QObject::connect(remove_btn, &QToolButton::clicked, [=]() { UndoStack::instance()->push(new RemoveSigCommand(model->msg_id, sig)); }); QObject::connect(plot_btn, &QToolButton::clicked, [=](bool checked) { emit showChart(model->msg_id, sig, checked, QGuiApplication::keyboardModifiers() & Qt::ShiftModifier); }); @@ -621,26 +618,27 @@ void SignalView::updateState(const std::set *msgs) { for (auto item : model->root->children) { double value = 0; if (item->sig->getValue(last_msg.dat.data(), last_msg.dat.size(), &value)) { - item->sig_val = item->sig->formatValue(value); - max_value_width = std::max(max_value_width, fontMetrics().width(item->sig_val)); + item->sig_val = QString::fromStdString(item->sig->formatValue(value)); + max_value_width = std::max(max_value_width, fontMetrics().horizontalAdvance(item->sig_val)); } } auto [first_visible, last_visible] = visibleSignalRange(); if (first_visible.isValid() && last_visible.isValid()) { - const static int min_max_width = QFontMetrics(delegate->minmax_font).width("-000.00") + 5; + const static int min_max_width = QFontMetrics(delegate->minmax_font).horizontalAdvance("-000.00") + 5; int available_width = value_column_width - delegate->button_size.width(); int value_width = std::min(max_value_width + min_max_width, available_width / 2); QSize size(available_width - value_width, delegate->button_size.height() - style()->pixelMetric(QStyle::PM_FocusFrameVMargin) * 2); - QFutureSynchronizer synchronizer; + auto [first, last] = can->eventsInRange(model->msg_id, std::make_pair(last_msg.ts -settings.sparkline_range, last_msg.ts)); + std::vector> futures; for (int i = first_visible.row(); i <= last_visible.row(); ++i) { auto item = model->getItem(model->index(i, 1)); - synchronizer.addFuture(QtConcurrent::run( - &item->sparkline, &Sparkline::update, model->msg_id, item->sig, last_msg.ts, settings.sparkline_range, size)); + futures.push_back(std::async(std::launch::async, + &Sparkline::update, &item->sparkline, item->sig, first, last, settings.sparkline_range, size)); } - synchronizer.waitForFinished(); + for (auto &f : futures) f.get(); } for (int i = 0; i < model->rowCount(); ++i) { @@ -676,7 +674,7 @@ ValueDescriptionDlg::ValueDescriptionDlg(const ValueDescription &descriptions, Q int row = 0; for (auto &[val, desc] : descriptions) { table->setItem(row, 0, new QTableWidgetItem(QString::number(val))); - table->setItem(row, 1, new QTableWidgetItem(desc)); + table->setItem(row, 1, new QTableWidgetItem(QString::fromStdString(desc))); ++row; } @@ -705,7 +703,7 @@ void ValueDescriptionDlg::save() { QString val = table->item(i, 0)->text().trimmed(); QString desc = table->item(i, 1)->text().trimmed(); if (!val.isEmpty() && !desc.isEmpty()) { - val_desc.push_back({val.toDouble(), desc}); + val_desc.push_back({val.toDouble(), desc.toStdString()}); } } QDialog::accept(); diff --git a/tools/cabana/signalview.h b/openpilot/tools/cabana/signalview.h similarity index 88% rename from tools/cabana/signalview.h rename to openpilot/tools/cabana/signalview.h index 4e746ea105..2e44e55cbf 100644 --- a/tools/cabana/signalview.h +++ b/openpilot/tools/cabana/signalview.h @@ -20,12 +20,15 @@ class SignalModel : public QAbstractItemModel { public: struct Item { enum Type {Root, Sig, Name, Size, Node, Endian, Signed, Offset, Factor, SignalType, MultiplexValue, ExtraInfo, Unit, Comment, Min, Max, Desc }; - ~Item() { qDeleteAll(children); } - inline int row() { return parent->children.indexOf(this); } + ~Item() { for (auto c : children) delete c; } + inline int row() { + auto it = std::find(parent->children.begin(), parent->children.end(), this); + return it != parent->children.end() ? std::distance(parent->children.begin(), it) : -1; + } Type type = Type::Root; Item *parent = nullptr; - QList children; + std::vector children; const cabana::Signal *sig = nullptr; QString title; @@ -126,9 +129,12 @@ private: // update widget geometries in QTreeView::rowsInserted QTreeView::rowsInserted(parent, start, end); } - void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector &roles = QVector()) override { + void setModel(QAbstractItemModel *model) override { + QTreeView::setModel(model); // Bypass the slow call to QTreeView::dataChanged. - QAbstractItemView::dataChanged(topLeft, bottomRight, roles); + QObject::disconnect(model, &QAbstractItemModel::dataChanged, this, nullptr); + QObject::connect(model, &QAbstractItemModel::dataChanged, this, + [this](const QModelIndex &tl, const QModelIndex &br, const auto &roles) { QAbstractItemView::dataChanged(tl, br, roles); }); } void leaveEvent(QEvent *event) override { emit static_cast(parentWidget())->highlight(nullptr); diff --git a/tools/cabana/streams/abstractstream.cc b/openpilot/tools/cabana/streams/abstractstream.cc similarity index 93% rename from tools/cabana/streams/abstractstream.cc rename to openpilot/tools/cabana/streams/abstractstream.cc index 1582fcd34d..c58a98084f 100644 --- a/tools/cabana/streams/abstractstream.cc +++ b/openpilot/tools/cabana/streams/abstractstream.cc @@ -1,4 +1,5 @@ #include "tools/cabana/streams/abstractstream.h" +#include "tools/cabana/dbc/dbcqt.h" #include #include @@ -18,8 +19,8 @@ AbstractStream::AbstractStream(QObject *parent) : QObject(parent) { QObject::connect(this, &AbstractStream::privateUpdateLastMsgsSignal, this, &AbstractStream::updateLastMessages, Qt::QueuedConnection); QObject::connect(this, &AbstractStream::seekedTo, this, &AbstractStream::updateLastMsgsTo); QObject::connect(this, &AbstractStream::seeking, this, [this](double sec) { current_sec_ = sec; }); - QObject::connect(dbc(), &DBCManager::DBCFileChanged, this, &AbstractStream::updateMasks); - QObject::connect(dbc(), &DBCManager::maskUpdated, this, &AbstractStream::updateMasks); + QObject::connect(dbcNotifier(), &QtDBCNotifier::DBCFileChanged, this, &AbstractStream::updateMasks); + QObject::connect(dbcNotifier(), &QtDBCNotifier::maskUpdated, this, &AbstractStream::updateMasks); } void AbstractStream::updateMasks() { @@ -233,18 +234,18 @@ std::pair AbstractStream::eventsInRange(const Messag namespace { enum Color { GREYISH_BLUE, CYAN, RED}; -QColor getColor(int c) { +CabanaColor getColor(int c) { constexpr int start_alpha = 128; - static const QColor colors[] = { - [GREYISH_BLUE] = QColor(102, 86, 169, start_alpha / 2), - [CYAN] = QColor(0, 187, 255, start_alpha), - [RED] = QColor(255, 0, 0, start_alpha), + static const CabanaColor colors[] = { + [GREYISH_BLUE] = CabanaColor(102, 86, 169, start_alpha / 2), + [CYAN] = CabanaColor(0, 187, 255, start_alpha), + [RED] = CabanaColor(255, 0, 0, start_alpha), }; return settings.theme == LIGHT_THEME ? colors[c] : colors[c].lighter(135); } -inline QColor blend(const QColor &a, const QColor &b) { - return QColor((a.red() + b.red()) / 2, (a.green() + b.green()) / 2, (a.blue() + b.blue()) / 2, (a.alpha() + b.alpha()) / 2); +inline CabanaColor blend(const CabanaColor &a, const CabanaColor &b) { + return CabanaColor((a.red() + b.red()) / 2, (a.green() + b.green()) / 2, (a.blue() + b.blue()) / 2, (a.alpha() + b.alpha()) / 2); } // Calculate the frequency from the past one minute data @@ -271,7 +272,7 @@ void CanData::compute(const MessageId &msg_id, const uint8_t *can_data, const in if (dat.size() != size) { dat.assign(can_data, can_data + size); - colors.assign(size, QColor(0, 0, 0, 0)); + colors.assign(size, CabanaColor(0, 0, 0, 0)); last_changes.resize(size); bit_flip_counts.resize(size); std::for_each(last_changes.begin(), last_changes.end(), [current_sec](auto &c) { c.ts = current_sec; }); @@ -317,7 +318,7 @@ void CanData::compute(const MessageId &msg_id, const uint8_t *can_data, const in last_change.delta = delta; } else { // Fade out - colors[i].setAlphaF(std::max(0.0, colors[i].alphaF() - alpha_delta)); + colors[i].setAlphaF(std::max(0.0f, colors[i].alphaF() - alpha_delta)); } } } diff --git a/openpilot/tools/cabana/streams/abstractstream.h b/openpilot/tools/cabana/streams/abstractstream.h new file mode 100644 index 0000000000..82cb899937 --- /dev/null +++ b/openpilot/tools/cabana/streams/abstractstream.h @@ -0,0 +1,119 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "openpilot/cereal/messaging/messaging.h" +#include "tools/cabana/core/can_data.h" +#include "tools/cabana/dbc/dbcmanager.h" +#include "tools/cabana/utils/util.h" +#include "tools/replay/util.h" + +class AbstractStream : public QObject { + Q_OBJECT + +public: + AbstractStream(QObject *parent); + virtual ~AbstractStream() {} + virtual void start() = 0; + virtual bool liveStreaming() const { return true; } + virtual void seekTo(double ts) {} + virtual std::string routeName() const = 0; + virtual std::string carFingerprint() const { return ""; } + virtual std::chrono::system_clock::time_point beginDateTime() const { return {}; } + virtual uint64_t beginMonoTime() const { return 0; } + virtual double minSeconds() const { return 0; } + virtual double maxSeconds() const { return 0; } + virtual void setSpeed(float speed) {} + virtual double getSpeed() { return 1; } + virtual bool isPaused() const { return false; } + virtual void pause(bool pause) {} + void setTimeRange(const std::optional> &range); + const std::optional> &timeRange() const { return time_range_; } + + inline double currentSec() const { return current_sec_; } + inline uint64_t toMonoTime(double sec) const { return beginMonoTime() + std::max(sec, 0.0) * 1e9; } + inline double toSeconds(uint64_t mono_time) const { return std::max(0.0, (mono_time - beginMonoTime()) / 1e9); } + + inline const std::unordered_map &lastMessages() const { return last_msgs; } + bool isMessageActive(const MessageId &id) const; + inline const MessageEventsMap &eventsMap() const { return events_; } + inline const std::vector &allEvents() const { return all_events_; } + const CanData &lastMessage(const MessageId &id) const; + const std::vector &events(const MessageId &id) const; + std::pair eventsInRange(const MessageId &id, std::optional> time_range) const; + + size_t suppressHighlighted(); + void clearSuppressed(); + void suppressDefinedSignals(bool suppress); + +signals: + void paused(); + void resume(); + void seeking(double sec); + void seekedTo(double sec); + void timeRangeChanged(const std::optional> &range); + void eventsMerged(const MessageEventsMap &events_map); + void msgsReceived(const std::set *new_msgs, bool has_new_ids); + void sourcesUpdated(const SourceSet &s); + void privateUpdateLastMsgsSignal(); + +public: + SourceSet sources; + +protected: + void mergeEvents(const std::vector &events); + const CanEvent *newEvent(uint64_t mono_time, const cereal::CanData::Reader &c); + void updateEvent(const MessageId &id, double sec, const uint8_t *data, uint8_t size); + void waitForSeekFinshed(); + virtual void updateLastMessages(); + std::vector all_events_; + double current_sec_ = 0; + std::optional> time_range_; + +private: + void updateLastMsgsTo(double sec); + void updateMasks(); + + MessageEventsMap events_; + std::unordered_map last_msgs; + std::unique_ptr event_buffer_; + + // Members accessed in multiple threads. (mutex protected) + std::mutex mutex_; + std::condition_variable seek_finished_cv_; + bool seek_finished_ = false; + std::set new_msgs_; + std::unordered_map messages_; + std::unordered_map> masks_; +}; + +class AbstractOpenStreamWidget : public QWidget { + Q_OBJECT +public: + AbstractOpenStreamWidget(QWidget *parent = nullptr) : QWidget(parent) {} + virtual AbstractStream *open() = 0; + +signals: + void enableOpenButton(bool); +}; + +class DummyStream : public AbstractStream { + Q_OBJECT +public: + DummyStream(QObject *parent) : AbstractStream(parent) {} + std::string routeName() const override { return "No Stream"; } + void start() override {} +}; + +// A global pointer referring to the unique AbstractStream object +extern AbstractStream *can; diff --git a/openpilot/tools/cabana/streams/devicestream.cc b/openpilot/tools/cabana/streams/devicestream.cc new file mode 100644 index 0000000000..91e890316e --- /dev/null +++ b/openpilot/tools/cabana/streams/devicestream.cc @@ -0,0 +1,148 @@ +#include "tools/cabana/streams/devicestream.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "openpilot/cereal/services.h" + +#include +#include +#include +#include + +#include "tools/cabana/utils/util.h" + +// DeviceStream + +DeviceStream::DeviceStream(QObject *parent, QString address) : zmq_address(address), LiveStream(parent) { +} + +DeviceStream::~DeviceStream() { + stop(); + stopBridge(); +} + +void DeviceStream::stopBridge() { + if (bridge_pid <= 0) return; + + ::kill(bridge_pid, SIGTERM); + for (int i = 0; i < 30; ++i) { + int status = 0; + pid_t r = ::waitpid(bridge_pid, &status, WNOHANG); + if (r == bridge_pid || (r < 0 && errno == ECHILD)) { + bridge_pid = -1; + return; + } + usleep(100000); // 100ms, up to ~3s + } + ::kill(bridge_pid, SIGKILL); + ::waitpid(bridge_pid, nullptr, 0); + bridge_pid = -1; +} + +void DeviceStream::start() { + if (!zmq_address.isEmpty()) { + stopBridge(); + const std::string path = (std::filesystem::path(QCoreApplication::applicationDirPath().toStdString()) / + "../../openpilot/cereal/messaging/bridge").lexically_normal().string(); + const std::string addr = zmq_address.toStdString(); + const char *can_filter = "/\"can/\""; + + // Self-pipe: write end is CLOEXEC so it closes on successful exec. If exec + // fails, the child writes errno and the parent aborts stream start. + int err_pipe[2] = {-1, -1}; + if (::pipe(err_pipe) != 0) { + QMessageBox::warning(nullptr, tr("Error"), + tr("Failed to start bridge: %1").arg(QString::fromLocal8Bit(strerror(errno)))); + return; + } + + pid_t pid = ::fork(); + if (pid == 0) { + ::close(err_pipe[0]); + ::fcntl(err_pipe[1], F_SETFD, FD_CLOEXEC); + execl(path.c_str(), path.c_str(), addr.c_str(), can_filter, static_cast(nullptr)); + const int err = errno; + (void)!::write(err_pipe[1], &err, sizeof(err)); + _exit(127); + } + + ::close(err_pipe[1]); + if (pid < 0) { + ::close(err_pipe[0]); + QMessageBox::warning(nullptr, tr("Error"), + tr("Failed to start bridge: %1").arg(QString::fromLocal8Bit(strerror(errno)))); + return; + } + + int exec_errno = 0; + const ssize_t n = ::read(err_pipe[0], &exec_errno, sizeof(exec_errno)); + ::close(err_pipe[0]); + if (n == static_cast(sizeof(exec_errno))) { + // Child failed to exec; reap and surface the error. + int status = 0; + ::waitpid(pid, &status, 0); + QMessageBox::warning(nullptr, tr("Error"), + tr("Failed to start bridge: %1").arg(QString::fromLocal8Bit(strerror(exec_errno)))); + return; + } + + bridge_pid = pid; + } + + LiveStream::start(); +} + +void DeviceStream::streamThread() { + zmq_address.isEmpty() ? unsetenv("ZMQ") : setenv("ZMQ", "1", 1); + + std::unique_ptr context(Context::create()); + std::unique_ptr sock(SubSocket::create(context.get(), "can", "127.0.0.1", false, true, services.at("can").queue_size)); + assert(sock != NULL); + // run as fast as messages come in + while (!exit_) { + std::unique_ptr msg(sock->receive(true)); + if (!msg) { + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + continue; + } + handleEvent(kj::ArrayPtr((capnp::word*)msg->getData(), msg->getSize() / sizeof(capnp::word))); + } +} + +// OpenDeviceWidget + +OpenDeviceWidget::OpenDeviceWidget(QWidget *parent) : AbstractOpenStreamWidget(parent) { + QRadioButton *msgq = new QRadioButton(tr("MSGQ")); + QRadioButton *zmq = new QRadioButton(tr("ZMQ")); + ip_address = new QLineEdit(this); + ip_address->setPlaceholderText(tr("Enter device Ip Address")); + ip_address->setValidator(new IpAddressValidator(this)); + + group = new QButtonGroup(this); + group->addButton(msgq, 0); + group->addButton(zmq, 1); + + QFormLayout *form_layout = new QFormLayout(this); + form_layout->addRow(msgq); + form_layout->addRow(zmq, ip_address); + QObject::connect(group, qOverload(&QButtonGroup::buttonToggled), [=](QAbstractButton *button, bool checked) { + ip_address->setEnabled(button == zmq && checked); + }); + zmq->setChecked(true); +} + +AbstractStream *OpenDeviceWidget::open() { + QString ip = ip_address->text().isEmpty() ? "127.0.0.1" : ip_address->text(); + bool msgq = group->checkedId() == 0; + return new DeviceStream(qApp, msgq ? "" : ip); +} diff --git a/openpilot/tools/cabana/streams/devicestream.h b/openpilot/tools/cabana/streams/devicestream.h new file mode 100644 index 0000000000..0e6951c92c --- /dev/null +++ b/openpilot/tools/cabana/streams/devicestream.h @@ -0,0 +1,34 @@ +#pragma once + +#include "tools/cabana/streams/livestream.h" + +#include + +class DeviceStream : public LiveStream { + Q_OBJECT +public: + DeviceStream(QObject *parent, QString address = {}); + ~DeviceStream(); + inline std::string routeName() const override { + return "Live Streaming From " + (zmq_address.isEmpty() ? std::string("127.0.0.1") : zmq_address.toStdString()); + } + +protected: + void start() override; + void streamThread() override; + void stopBridge(); + pid_t bridge_pid = -1; + const QString zmq_address; +}; + +class OpenDeviceWidget : public AbstractOpenStreamWidget { + Q_OBJECT + +public: + OpenDeviceWidget(QWidget *parent = nullptr); + AbstractStream *open() override; + +private: + QLineEdit *ip_address; + QButtonGroup *group; +}; diff --git a/openpilot/tools/cabana/streams/livestream.cc b/openpilot/tools/cabana/streams/livestream.cc new file mode 100644 index 0000000000..019a67e8f2 --- /dev/null +++ b/openpilot/tools/cabana/streams/livestream.cc @@ -0,0 +1,151 @@ +#include "tools/cabana/streams/livestream.h" + +#include +#include +#include +#include +#include +#include + +#include "common/timing.h" +#include "common/util.h" + +struct LiveStream::Logger { + Logger() : start_ts(seconds_since_epoch()), segment_num(-1) {} + + void write(kj::ArrayPtr data) { + int n = (seconds_since_epoch() - start_ts) / 60.0; + if (std::exchange(segment_num, n) != segment_num) { + const time_t start_time = start_ts; + std::tm local_time = {}; + localtime_r(&start_time, &local_time); + std::ostringstream date; + date << std::put_time(&local_time, "%Y-%m-%d--%H-%M-%S"); + QString dir = QString("%1/%2--%3") + .arg(QString::fromStdString(settings.log_path)) + .arg(QString::fromStdString(date.str())) + .arg(n); + util::create_directories(dir.toStdString(), 0755); + fs.reset(new std::ofstream((dir + "/rlog").toStdString(), std::ios::binary | std::ios::out)); + } + + auto bytes = data.asBytes(); + fs->write((const char*)bytes.begin(), bytes.size()); + } + + std::unique_ptr fs; + int segment_num; + uint64_t start_ts; +}; + +LiveStream::LiveStream(QObject *parent) : AbstractStream(parent) { + if (settings.log_livestream) { + logger = std::make_unique(); + } +} + +LiveStream::~LiveStream() { + stop(); +} + +void LiveStream::start() { + begin_date_time = std::chrono::system_clock::now(); + fps_ = settings.fps; + exit_ = false; + stream_thread = std::thread(&LiveStream::streamThread, this); + update_thread = std::thread(&LiveStream::updateThread, this); +} + +void LiveStream::stop() { + exit_ = true; + if (stream_thread.joinable()) stream_thread.join(); + if (update_thread.joinable()) update_thread.join(); +} + +void LiveStream::updateThread() { + while (!exit_) { + std::this_thread::sleep_for(std::chrono::milliseconds(1000 / fps_)); + // coalesce: skip the emit if the main thread hasn't processed the previous one yet. + if (!update_pending_.exchange(true)) { + emit privateUpdateLastMsgsSignal(); + } + } +} + +// called in streamThread +void LiveStream::handleEvent(kj::ArrayPtr data) { + if (logger) { + logger->write(data); + } + + capnp::FlatArrayMessageReader reader(data); + auto event = reader.getRoot(); + if (event.which() == cereal::Event::Which::CAN) { + const uint64_t mono_time = event.getLogMonoTime(); + std::lock_guard lk(lock); + for (const auto &c : event.getCan()) { + received_events_.push_back(newEvent(mono_time, c)); + } + } +} + +// called on the main thread by the queued privateUpdateLastMsgsSignal connection +void LiveStream::updateLastMessages() { + update_pending_ = false; + fps_ = settings.fps; + { + // merge events received from live stream thread. + std::lock_guard lk(lock); + mergeEvents(received_events_); + uint64_t last_received_ts = !received_events_.empty() ? received_events_.back()->mono_time : 0; + lastest_event_ts = std::max(lastest_event_ts, last_received_ts); + received_events_.clear(); + } + if (!all_events_.empty()) { + begin_event_ts = all_events_.front()->mono_time; + updateEvents(); + } +} + +void LiveStream::updateEvents() { + static double prev_speed = 1.0; + + if (first_update_ts == 0) { + first_update_ts = nanos_since_boot(); + first_event_ts = current_event_ts = all_events_.back()->mono_time; + } + + if (paused_ || prev_speed != speed_) { + prev_speed = speed_; + first_update_ts = nanos_since_boot(); + first_event_ts = current_event_ts; + return; + } + + uint64_t last_ts = post_last_event && speed_ == 1.0 + ? all_events_.back()->mono_time + : first_event_ts + (nanos_since_boot() - first_update_ts) * speed_; + auto first = std::upper_bound(all_events_.cbegin(), all_events_.cend(), current_event_ts, CompareCanEvent()); + auto last = std::upper_bound(first, all_events_.cend(), last_ts, CompareCanEvent()); + + for (auto it = first; it != last; ++it) { + const CanEvent *e = *it; + MessageId id = {.source = e->src, .address = e->address}; + updateEvent(id, (e->mono_time - begin_event_ts) / 1e9, e->dat, e->size); + current_event_ts = e->mono_time; + } + AbstractStream::updateLastMessages(); +} + +void LiveStream::seekTo(double sec) { + sec = std::max(0.0, sec); + first_update_ts = nanos_since_boot(); + current_event_ts = first_event_ts = std::min(sec * 1e9 + begin_event_ts, lastest_event_ts); + post_last_event = (first_event_ts == lastest_event_ts); + emit seekedTo((current_event_ts - begin_event_ts) / 1e9); +} + +void LiveStream::pause(bool pause) { + paused_ = pause; + emit(pause ? paused() : resume()); +} diff --git a/openpilot/tools/cabana/streams/livestream.h b/openpilot/tools/cabana/streams/livestream.h new file mode 100644 index 0000000000..5d65b1743f --- /dev/null +++ b/openpilot/tools/cabana/streams/livestream.h @@ -0,0 +1,57 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include "tools/cabana/streams/abstractstream.h" + +class LiveStream : public AbstractStream { + Q_OBJECT + +public: + LiveStream(QObject *parent); + virtual ~LiveStream(); + void start() override; + void stop(); + inline std::chrono::system_clock::time_point beginDateTime() const override { return begin_date_time; } + inline uint64_t beginMonoTime() const override { return begin_event_ts; } + double maxSeconds() const override { return std::max(1.0, (lastest_event_ts - begin_event_ts) / 1e9); } + void setSpeed(float speed) override { speed_ = speed; } + double getSpeed() override { return speed_; } + bool isPaused() const override { return paused_; } + void pause(bool pause) override; + void seekTo(double sec) override; + +protected: + virtual void streamThread() = 0; + void handleEvent(kj::ArrayPtr event); + + std::atomic exit_ = false; + +private: + void updateThread(); + void updateLastMessages() override; + void updateEvents(); + + std::mutex lock; + std::thread stream_thread, update_thread; + std::atomic update_pending_ = false; + std::atomic fps_ = 10; + std::vector received_events_; + + std::chrono::system_clock::time_point begin_date_time; + uint64_t begin_event_ts = 0; + uint64_t lastest_event_ts = 0; + uint64_t current_event_ts = 0; + uint64_t first_event_ts = 0; + uint64_t first_update_ts = 0; + bool post_last_event = true; + double speed_ = 1; + bool paused_ = false; + + struct Logger; + std::unique_ptr logger; +}; diff --git a/tools/cabana/streams/pandastream.cc b/openpilot/tools/cabana/streams/pandastream.cc similarity index 88% rename from tools/cabana/streams/pandastream.cc rename to openpilot/tools/cabana/streams/pandastream.cc index e66d72e59d..7ccb18a756 100644 --- a/tools/cabana/streams/pandastream.cc +++ b/openpilot/tools/cabana/streams/pandastream.cc @@ -1,11 +1,13 @@ #include "tools/cabana/streams/pandastream.h" -#include +#include +#include +#include + #include #include #include #include -#include #include PandaStream::PandaStream(QObject *parent, PandaStreamConfig config_) : config(config_), LiveStream(parent) { @@ -16,15 +18,15 @@ PandaStream::PandaStream(QObject *parent, PandaStreamConfig config_) : config(co bool PandaStream::connect() { try { - qDebug() << "Connecting to panda " << config.serial; - panda.reset(new Panda(config.serial.toStdString())); + fprintf(stderr, "Connecting to panda %s\n", config.serial.c_str()); + panda.reset(new Panda(config.serial)); config.bus_config.resize(3); - qDebug() << "Connected"; + fprintf(stderr, "Connected\n"); } catch (const std::exception& e) { return false; } - panda->set_safety_model(cereal::CarParams::SafetyModel::SILENT); + panda->set_safety_model(cereal::CarParams::SafetyModel::NO_OUTPUT); for (int bus = 0; bus < config.bus_config.size(); bus++) { panda->set_can_speed_kbps(bus, config.bus_config[bus].can_speed_kbps); @@ -44,20 +46,20 @@ bool PandaStream::connect() { void PandaStream::streamThread() { std::vector raw_can_data; - while (!QThread::currentThread()->isInterruptionRequested()) { - QThread::msleep(1); + while (!exit_) { + std::this_thread::sleep_for(std::chrono::milliseconds(1)); if (!panda->connected()) { - qDebug() << "Connection to panda lost. Attempting reconnect."; + fprintf(stderr, "Connection to panda lost. Attempting reconnect.\n"); if (!connect()){ - QThread::msleep(1000); + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); continue; } } raw_can_data.clear(); if (!panda->can_receive(raw_can_data)) { - qDebug() << "failed to receive"; + fprintf(stderr, "failed to receive\n"); continue; } @@ -72,7 +74,7 @@ void PandaStream::streamThread() { handleEvent(capnp::messageToFlatArray(msg)); - panda->send_heartbeat(false, false); + panda->send_heartbeat(false); } } @@ -81,7 +83,7 @@ void PandaStream::streamThread() { OpenPandaWidget::OpenPandaWidget(QWidget *parent) : AbstractOpenStreamWidget(parent) { form_layout = new QFormLayout(this); if (can && dynamic_cast(can) != nullptr) { - form_layout->addWidget(new QLabel(tr("Already connected to %1.").arg(can->routeName()))); + form_layout->addWidget(new QLabel(tr("Already connected to %1.").arg(QString::fromStdString(can->routeName())))); form_layout->addWidget(new QLabel("Close the current connection via [File menu -> Close Stream] before connecting to another Panda.")); QTimer::singleShot(0, [this]() { emit enableOpenButton(false); }); return; @@ -123,13 +125,13 @@ void OpenPandaWidget::buildConfigForm() { Panda panda(serial.toStdString()); has_fd = (panda.hw_type == cereal::PandaState::PandaType::RED_PANDA) || (panda.hw_type == cereal::PandaState::PandaType::RED_PANDA_V2); } catch (const std::exception& e) { - qDebug() << "failed to open panda" << serial; + fprintf(stderr, "failed to open panda %s\n", serial.toUtf8().constData()); has_panda = false; } } if (has_panda) { - config.serial = serial; + config.serial = serial.toStdString(); config.bus_config.resize(3); for (int i = 0; i < config.bus_config.size(); i++) { QHBoxLayout *bus_layout = new QHBoxLayout; diff --git a/tools/cabana/streams/pandastream.h b/openpilot/tools/cabana/streams/pandastream.h similarity index 87% rename from tools/cabana/streams/pandastream.h rename to openpilot/tools/cabana/streams/pandastream.h index 826b1aa986..f8847f65e5 100644 --- a/tools/cabana/streams/pandastream.h +++ b/openpilot/tools/cabana/streams/pandastream.h @@ -7,7 +7,7 @@ #include #include "tools/cabana/streams/livestream.h" -#include "selfdrive/pandad/panda.h" +#include "tools/cabana/panda.h" const uint32_t speeds[] = {10U, 20U, 50U, 100U, 125U, 250U, 500U, 1000U}; const uint32_t data_speeds[] = {10U, 20U, 50U, 100U, 125U, 250U, 500U, 1000U, 2000U, 5000U}; @@ -19,7 +19,7 @@ struct BusConfig { }; struct PandaStreamConfig { - QString serial = ""; + std::string serial = ""; std::vector bus_config; }; @@ -28,8 +28,8 @@ class PandaStream : public LiveStream { public: PandaStream(QObject *parent, PandaStreamConfig config_ = {}); ~PandaStream() { stop(); } - inline QString routeName() const override { - return QString("Panda: %1").arg(config.serial); + inline std::string routeName() const override { + return "Panda: " + config.serial; } protected: diff --git a/tools/cabana/streams/replaystream.cc b/openpilot/tools/cabana/streams/replaystream.cc similarity index 86% rename from tools/cabana/streams/replaystream.cc rename to openpilot/tools/cabana/streams/replaystream.cc index b8cf1be299..dbd44b54e3 100644 --- a/tools/cabana/streams/replaystream.cc +++ b/openpilot/tools/cabana/streams/replaystream.cc @@ -1,5 +1,7 @@ #include "tools/cabana/streams/replaystream.h" +#include + #include #include #include @@ -14,10 +16,7 @@ ReplayStream::ReplayStream(QObject *parent) : AbstractStream(parent) { unsetenv("ZMQ"); setenv("COMMA_CACHE", "/tmp/comma_download_cache", 1); - // TODO: Remove when OpenpilotPrefix supports ZMQ -#ifndef __APPLE__ op_prefix = std::make_unique(); -#endif QObject::connect(&settings, &Settings::changed, this, [this]() { if (replay) replay->setSegmentCacheLimit(settings.max_cached_minutes); @@ -46,9 +45,9 @@ void ReplayStream::mergeSegments() { } } -bool ReplayStream::loadRoute(const QString &route, const QString &data_dir, uint32_t replay_flags, bool auto_source) { - replay.reset(new Replay(route.toStdString(), {"can", "roadEncodeIdx", "driverEncodeIdx", "wideRoadEncodeIdx", "carParams"}, - {}, nullptr, replay_flags, data_dir.toStdString(), auto_source)); +bool ReplayStream::loadRoute(const std::string &route, const std::string &data_dir, uint32_t replay_flags, bool auto_source) { + replay.reset(new Replay(route, {"can", "roadEncodeIdx", "driverEncodeIdx", "wideRoadEncodeIdx", "carParams"}, + {}, nullptr, replay_flags, data_dir, auto_source)); replay->setSegmentCacheLimit(settings.max_cached_minutes); replay->installEventFilter([this](const Event *event) { return eventFilter(event); }); @@ -68,21 +67,21 @@ bool ReplayStream::loadRoute(const QString &route, const QString &data_dir, uint QString message; if (auth_content.empty()) { message = "Authentication Required. Please run the following command to authenticate:\n\n" - "python3 tools/lib/auth.py\n\n" + "python3 openpilot/tools/lib/auth.py\n\n" "This will grant access to routes from your comma account."; } else { message = tr("Access Denied. You do not have permission to access route:\n\n%1\n\n" - "This is likely a private route.").arg(route); + "This is likely a private route.").arg(QString::fromStdString(route)); } QMessageBox::warning(nullptr, tr("Access Denied"), message); } else if (replay->lastRouteError() == RouteLoadError::NetworkError) { QMessageBox::warning(nullptr, tr("Network Error"), - tr("Unable to load the route:\n\n %1.\n\nPlease check your network connection and try again.").arg(route)); + tr("Unable to load the route:\n\n %1.\n\nPlease check your network connection and try again.").arg(QString::fromStdString(route))); } else if (replay->lastRouteError() == RouteLoadError::FileNotFound) { QMessageBox::warning(nullptr, tr("Route Not Found"), - tr("The specified route could not be found:\n\n %1.\n\nPlease check the route name and try again.").arg(route)); + tr("The specified route could not be found:\n\n %1.\n\nPlease check the route name and try again.").arg(QString::fromStdString(route))); } else { - QMessageBox::warning(nullptr, tr("Route Load Failed"), tr("Failed to load route: '%1'").arg(route)); + QMessageBox::warning(nullptr, tr("Route Load Failed"), tr("Failed to load route: '%1'").arg(QString::fromStdString(route))); } } return success; @@ -136,10 +135,10 @@ OpenReplayWidget::OpenReplayWidget(QWidget *parent) : AbstractOpenStreamWidget(p setMinimumWidth(550); QObject::connect(browse_local_btn, &QPushButton::clicked, [=]() { - QString dir = QFileDialog::getExistingDirectory(this, tr("Open Local Route"), settings.last_route_dir); + QString dir = QFileDialog::getExistingDirectory(this, tr("Open Local Route"), QString::fromStdString(settings.last_route_dir)); if (!dir.isEmpty()) { route_edit->setText(dir); - settings.last_route_dir = QFileInfo(dir).absolutePath(); + settings.last_route_dir = std::filesystem::absolute(dir.toStdString()).parent_path().string(); } }); QObject::connect(browse_remote_btn, &QPushButton::clicked, [this]() { @@ -168,7 +167,7 @@ AbstractStream *OpenReplayWidget::open() { if (cameras[2]->isChecked()) flags |= REPLAY_FLAG_ECAM; if (flags == REPLAY_FLAG_NONE && !cameras[0]->isChecked()) flags = REPLAY_FLAG_NO_VIPC; - if (replay_stream->loadRoute(route, data_dir, flags)) { + if (replay_stream->loadRoute(route.toStdString(), data_dir.toStdString(), flags)) { return replay_stream.release(); } } diff --git a/tools/cabana/streams/replaystream.h b/openpilot/tools/cabana/streams/replaystream.h similarity index 76% rename from tools/cabana/streams/replaystream.h rename to openpilot/tools/cabana/streams/replaystream.h index d429ed1f95..eecd345715 100644 --- a/tools/cabana/streams/replaystream.h +++ b/openpilot/tools/cabana/streams/replaystream.h @@ -18,15 +18,17 @@ class ReplayStream : public AbstractStream { public: ReplayStream(QObject *parent); void start() override { replay->start(); } - bool loadRoute(const QString &route, const QString &data_dir, uint32_t replay_flags = REPLAY_FLAG_NONE, bool auto_source = false); + bool loadRoute(const std::string &route, const std::string &data_dir, uint32_t replay_flags = REPLAY_FLAG_NONE, bool auto_source = false); bool eventFilter(const Event *event); void seekTo(double ts) override { replay->seekTo(std::max(double(0), ts), false); } bool liveStreaming() const override { return false; } - inline QString routeName() const override { return QString::fromStdString(replay->route().name()); } - inline QString carFingerprint() const override { return replay->carFingerprint().c_str(); } + inline std::string routeName() const override { return replay->route().name(); } + inline std::string carFingerprint() const override { return replay->carFingerprint(); } double minSeconds() const override { return replay->minSeconds(); } double maxSeconds() const { return replay->maxSeconds(); } - inline QDateTime beginDateTime() const { return QDateTime::fromSecsSinceEpoch(replay->routeDateTime()); } + inline std::chrono::system_clock::time_point beginDateTime() const override { + return std::chrono::system_clock::from_time_t(replay->routeDateTime()); + } inline uint64_t beginMonoTime() const override { return replay->routeStartNanos(); } inline void setSpeed(float speed) override { replay->setSpeed(speed); } inline float getSpeed() const { return replay->getSpeed(); } diff --git a/openpilot/tools/cabana/streams/routes.cc b/openpilot/tools/cabana/streams/routes.cc new file mode 100644 index 0000000000..b6f98da533 --- /dev/null +++ b/openpilot/tools/cabana/streams/routes.cc @@ -0,0 +1,196 @@ +#include "tools/cabana/streams/routes.h" + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "json11/json11.hpp" +#include "tools/replay/py_downloader.h" + +namespace { + +// Parse a PyDownloader JSON response into (success, error_code). +std::pair checkApiResponse(const std::string &result) { + if (result.empty()) return {false, 500}; + std::string err; + auto doc = json11::Json::parse(result, err); + if (!err.empty()) return {false, 500}; + if (doc.is_object() && doc["error"].is_string()) { + return {false, doc["error"].string_value() == "unauthorized" ? 401 : 500}; + } + return {true, 0}; +} + +int64_t nowUnixMs() { + return std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()) + .count(); +} + +// Parse ISO-8601 (with optional fractional seconds / Z) to unix ms. Returns 0 on failure. +int64_t parseIsoToUnixMs(const std::string &s) { + std::string bytes = s; + if (!bytes.empty() && (bytes.back() == 'Z' || bytes.back() == 'z')) bytes.pop_back(); + int millis = 0; + auto dot = bytes.find('.'); + if (dot != std::string::npos) { + std::string frac = bytes.substr(dot + 1); + bytes = bytes.substr(0, dot); + while (frac.size() < 3) frac.push_back('0'); + millis = std::atoi(frac.substr(0, 3).c_str()); + } + std::tm tm{}; + const char *ret = strptime(bytes.c_str(), "%Y-%m-%dT%H:%M:%S", &tm); + if (!ret) ret = strptime(bytes.c_str(), "%Y-%m-%d %H:%M:%S", &tm); + if (!ret) return 0; + tm.tm_isdst = -1; + time_t secs = timegm(&tm); + if (secs == static_cast(-1)) return 0; + return static_cast(secs) * 1000 + millis; +} + +QString formatUnixMs(int64_t ms) { + time_t secs = static_cast(ms / 1000); + std::tm tm{}; + localtime_r(&secs, &tm); + char buf[64]; + std::strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", &tm); + return QString::fromUtf8(buf); +} + +} // namespace + +// The RouteListWidget class extends QListWidget to display a custom message when empty +class RouteListWidget : public QListWidget { +public: + RouteListWidget(QWidget *parent = nullptr) : QListWidget(parent) {} + void setEmptyText(const QString &text) { + empty_text_ = text; + viewport()->update(); + } + void paintEvent(QPaintEvent *event) override { + QListWidget::paintEvent(event); + if (count() == 0) { + QPainter painter(viewport()); + painter.drawText(viewport()->rect(), Qt::AlignCenter, empty_text_); + } + } + QString empty_text_ = tr("No items"); +}; + +RoutesDialog::RoutesDialog(QWidget *parent) : QDialog(parent) { + setWindowTitle(tr("Remote routes")); + + QFormLayout *layout = new QFormLayout(this); + layout->addRow(tr("Device"), device_list_ = new QComboBox(this)); + layout->addRow(period_selector_ = new QComboBox(this)); + layout->addRow(route_list_ = new RouteListWidget(this)); + auto button_box = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + layout->addRow(button_box); + + device_list_->addItem(tr("Loading...")); + period_selector_->addItem(tr("Last week"), 7); + period_selector_->addItem(tr("Last 2 weeks"), 14); + period_selector_->addItem(tr("Last month"), 30); + period_selector_->addItem(tr("Last 6 months"), 180); + period_selector_->addItem(tr("Preserved"), -1); + + connect(device_list_, QOverload::of(&QComboBox::currentIndexChanged), this, &RoutesDialog::fetchRoutes); + connect(period_selector_, QOverload::of(&QComboBox::currentIndexChanged), this, &RoutesDialog::fetchRoutes); + connect(route_list_, &QListWidget::itemDoubleClicked, this, &QDialog::accept); + connect(button_box, &QDialogButtonBox::accepted, this, &QDialog::accept); + connect(button_box, &QDialogButtonBox::rejected, this, &QDialog::reject); + + // Fetch devices + std::thread([this, alive = std::weak_ptr(alive_)]() { + std::string result = PyDownloader::getDevices(); + QMetaObject::invokeMethod(qApp, [this, alive, r = QString::fromStdString(result), response = checkApiResponse(result)]() { + if (!alive.expired()) parseDeviceList(r, response.first, response.second); + }, Qt::QueuedConnection); + }).detach(); +} + +void RoutesDialog::parseDeviceList(const QString &json, bool success, int error_code) { + if (success) { + device_list_->clear(); + std::string err; + auto doc = json11::Json::parse(json.toStdString(), err); + if (err.empty() && doc.is_array()) { + for (const auto &device : doc.array_items()) { + QString dongle_id = QString::fromStdString(device["dongle_id"].string_value()); + device_list_->addItem(dongle_id, dongle_id); + } + } + } else { + QMessageBox::warning(this, tr("Error"), error_code == 401 ? tr("Unauthorized. Authenticate with openpilot/tools/lib/auth.py") : tr("Network error")); + reject(); + } +} + +void RoutesDialog::fetchRoutes() { + if (device_list_->currentIndex() == -1 || device_list_->currentData().isNull()) + return; + + route_list_->clear(); + route_list_->setEmptyText(tr("Loading...")); + + std::string did = device_list_->currentText().toStdString(); + int period = period_selector_->currentData().toInt(); + + bool preserved = (period == -1); + int64_t start_ms = 0, end_ms = 0; + if (!preserved) { + end_ms = nowUnixMs(); + start_ms = end_ms - static_cast(period) * 24LL * 60LL * 60LL * 1000LL; + } + + int request_id = ++fetch_id_; + std::thread([this, alive = std::weak_ptr(alive_), did, start_ms, end_ms, preserved, request_id]() { + std::string result = PyDownloader::getDeviceRoutes(did, start_ms, end_ms, preserved); + QMetaObject::invokeMethod(qApp, [this, alive, r = QString::fromStdString(result), response = checkApiResponse(result), request_id]() { + if (!alive.expired() && fetch_id_ == request_id) parseRouteList(r, response.first, response.second); + }, Qt::QueuedConnection); + }).detach(); +} + +void RoutesDialog::parseRouteList(const QString &json, bool success, int error_code) { + if (success) { + std::string err; + auto doc = json11::Json::parse(json.toStdString(), err); + if (err.empty() && doc.is_array()) { + for (const auto &route : doc.array_items()) { + int64_t from_ms = 0, to_ms = 0; + if (period_selector_->currentData().toInt() == -1) { + from_ms = parseIsoToUnixMs(route["start_time"].string_value()); + to_ms = parseIsoToUnixMs(route["end_time"].string_value()); + } else { + from_ms = static_cast(route["start_time_utc_millis"].number_value()); + to_ms = static_cast(route["end_time_utc_millis"].number_value()); + } + const int mins = static_cast((to_ms - from_ms) / 60000); + auto item = new QListWidgetItem(QString("%1 %2min").arg(formatUnixMs(from_ms)).arg(mins)); + item->setData(Qt::UserRole, QString::fromStdString(route["fullname"].string_value())); + route_list_->addItem(item); + } + } + if (route_list_->count() > 0) route_list_->setCurrentRow(0); + } else { + QMessageBox::warning(this, tr("Error"), tr("Failed to fetch routes. Check your network connection.")); + reject(); + } + route_list_->setEmptyText(tr("No items")); +} + +QString RoutesDialog::route() { + auto current_item = route_list_->currentItem(); + return current_item ? current_item->data(Qt::UserRole).toString() : ""; +} diff --git a/openpilot/tools/cabana/streams/routes.h b/openpilot/tools/cabana/streams/routes.h new file mode 100644 index 0000000000..6ed145603f --- /dev/null +++ b/openpilot/tools/cabana/streams/routes.h @@ -0,0 +1,28 @@ +#pragma once + +#include +#include + +#include +#include + +class RouteListWidget; + +class RoutesDialog : public QDialog { + Q_OBJECT +public: + RoutesDialog(QWidget *parent); + QString route(); + +protected: + void parseDeviceList(const QString &json, bool success, int error_code); + void parseRouteList(const QString &json, bool success, int error_code); + void fetchRoutes(); + + QComboBox *device_list_; + QComboBox *period_selector_; + RouteListWidget *route_list_; + std::atomic fetch_id_{0}; + // expires on destruction; guards main-thread callbacks from detached worker threads + std::shared_ptr alive_ = std::make_shared(true); +}; diff --git a/openpilot/tools/cabana/streams/socketcanstream.cc b/openpilot/tools/cabana/streams/socketcanstream.cc new file mode 100644 index 0000000000..b616e7f242 --- /dev/null +++ b/openpilot/tools/cabana/streams/socketcanstream.cc @@ -0,0 +1,148 @@ +#include "tools/cabana/streams/socketcanstream.h" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include + +SocketCanStream::SocketCanStream(QObject *parent, SocketCanStreamConfig config_) : config(config_), LiveStream(parent) { + if (!available()) { + throw std::runtime_error("SocketCAN not available"); + } + + fprintf(stderr, "Connecting to SocketCAN device %s\n", config.device.c_str()); + if (!connect()) { + throw std::runtime_error("Failed to connect to SocketCAN device"); + } +} + +SocketCanStream::~SocketCanStream() { + stop(); + if (sock_fd >= 0) { + ::close(sock_fd); + sock_fd = -1; + } +} + +bool SocketCanStream::available() { + int fd = socket(PF_CAN, SOCK_RAW, CAN_RAW); + if (fd < 0) return false; + ::close(fd); + return true; +} + +bool SocketCanStream::connect() { + sock_fd = socket(PF_CAN, SOCK_RAW, CAN_RAW); + if (sock_fd < 0) { + fprintf(stderr, "Failed to create CAN socket\n"); + return false; + } + + // Enable CAN-FD + int fd_enable = 1; + setsockopt(sock_fd, SOL_CAN_RAW, CAN_RAW_FD_FRAMES, &fd_enable, sizeof(fd_enable)); + + struct ifreq ifr = {}; + strncpy(ifr.ifr_name, config.device.c_str(), IFNAMSIZ - 1); + if (ioctl(sock_fd, SIOCGIFINDEX, &ifr) < 0) { + fprintf(stderr, "Failed to get interface index for %s\n", config.device.c_str()); + ::close(sock_fd); + sock_fd = -1; + return false; + } + + struct sockaddr_can addr = {}; + addr.can_family = AF_CAN; + addr.can_ifindex = ifr.ifr_ifindex; + if (bind(sock_fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) { + fprintf(stderr, "Failed to bind CAN socket\n"); + ::close(sock_fd); + sock_fd = -1; + return false; + } + + // Set read timeout so the thread can check for interruption + struct timeval tv = {.tv_sec = 0, .tv_usec = 100000}; // 100ms + setsockopt(sock_fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); + + return true; +} + +void SocketCanStream::streamThread() { + struct canfd_frame frame; + + while (!exit_) { + ssize_t nbytes = read(sock_fd, &frame, sizeof(frame)); + if (nbytes <= 0) continue; + + uint8_t len = (nbytes == CAN_MTU) ? frame.len : frame.len; // works for both CAN and CAN-FD + + MessageBuilder msg; + auto evt = msg.initEvent(); + auto canData = evt.initCan(1); + canData[0].setAddress(frame.can_id & CAN_EFF_MASK); + canData[0].setSrc(0); + canData[0].setDat(kj::arrayPtr(frame.data, len)); + + handleEvent(capnp::messageToFlatArray(msg)); + } +} + +OpenSocketCanWidget::OpenSocketCanWidget(QWidget *parent) : AbstractOpenStreamWidget(parent) { + QVBoxLayout *main_layout = new QVBoxLayout(this); + main_layout->addStretch(1); + + QFormLayout *form_layout = new QFormLayout(); + + QHBoxLayout *device_layout = new QHBoxLayout(); + device_edit = new QComboBox(); + device_edit->setFixedWidth(300); + device_layout->addWidget(device_edit); + + QPushButton *refresh = new QPushButton(tr("Refresh")); + refresh->setFixedWidth(100); + device_layout->addWidget(refresh); + form_layout->addRow(tr("Device"), device_layout); + main_layout->addLayout(form_layout); + + main_layout->addStretch(1); + + QObject::connect(refresh, &QPushButton::clicked, this, &OpenSocketCanWidget::refreshDevices); + QObject::connect(device_edit, &QComboBox::currentTextChanged, this, [=]{ config.device = device_edit->currentText().toStdString(); }); + + // Populate devices + refreshDevices(); +} + +void OpenSocketCanWidget::refreshDevices() { + device_edit->clear(); + // Scan /sys/class/net/ for CAN interfaces (type 280 = ARPHRD_CAN) + std::error_code ec; + for (const auto &entry : std::filesystem::directory_iterator("/sys/class/net", ec)) { + std::ifstream type_file(entry.path() / "type"); + int type = 0; + if (type_file >> type && type == 280) { + device_edit->addItem(QString::fromStdString(entry.path().filename().string())); + } + } +} + +AbstractStream *OpenSocketCanWidget::open() { + try { + return new SocketCanStream(qApp, config); + } catch (std::exception &e) { + QMessageBox::warning(nullptr, tr("Warning"), tr("Failed to connect to SocketCAN device: '%1'").arg(e.what())); + return nullptr; + } +} diff --git a/openpilot/tools/cabana/streams/socketcanstream.h b/openpilot/tools/cabana/streams/socketcanstream.h new file mode 100644 index 0000000000..3c5cd184f7 --- /dev/null +++ b/openpilot/tools/cabana/streams/socketcanstream.h @@ -0,0 +1,42 @@ +#pragma once + +#include + +#include "tools/cabana/streams/livestream.h" + +struct SocketCanStreamConfig { + std::string device = ""; // TODO: support multiple devices/buses at once +}; + +class SocketCanStream : public LiveStream { + Q_OBJECT +public: + SocketCanStream(QObject *parent, SocketCanStreamConfig config_ = {}); + ~SocketCanStream(); + static bool available(); + + inline std::string routeName() const override { + return "Live Streaming From Socket CAN " + config.device; + } + +protected: + void streamThread() override; + bool connect(); + + SocketCanStreamConfig config = {}; + int sock_fd = -1; +}; + +class OpenSocketCanWidget : public AbstractOpenStreamWidget { + Q_OBJECT + +public: + OpenSocketCanWidget(QWidget *parent = nullptr); + AbstractStream *open() override; + +private: + void refreshDevices(); + + QComboBox *device_edit; + SocketCanStreamConfig config = {}; +}; diff --git a/tools/cabana/streamselector.cc b/openpilot/tools/cabana/streamselector.cc similarity index 90% rename from tools/cabana/streamselector.cc rename to openpilot/tools/cabana/streamselector.cc index efd00d3985..7e8adc568d 100644 --- a/tools/cabana/streamselector.cc +++ b/openpilot/tools/cabana/streamselector.cc @@ -1,14 +1,17 @@ #include "tools/cabana/streamselector.h" +#include + #include #include #include -#include "streams/socketcanstream.h" #include "tools/cabana/streams/devicestream.h" #include "tools/cabana/streams/pandastream.h" #include "tools/cabana/streams/replaystream.h" +#ifdef __linux__ #include "tools/cabana/streams/socketcanstream.h" +#endif StreamSelector::StreamSelector(QWidget *parent) : QDialog(parent) { setWindowTitle(tr("Open stream")); @@ -35,9 +38,11 @@ StreamSelector::StreamSelector(QWidget *parent) : QDialog(parent) { addStreamWidget(new OpenReplayWidget, tr("&Replay")); addStreamWidget(new OpenPandaWidget, tr("&Panda")); +#ifdef __linux__ if (SocketCanStream::available()) { addStreamWidget(new OpenSocketCanWidget, tr("&SocketCAN")); } +#endif addStreamWidget(new OpenDeviceWidget, tr("&Device")); QObject::connect(btn_box, &QDialogButtonBox::rejected, this, &QDialog::reject); @@ -49,10 +54,10 @@ StreamSelector::StreamSelector(QWidget *parent) : QDialog(parent) { setEnabled(true); }); QObject::connect(file_btn, &QPushButton::clicked, [this]() { - QString fn = QFileDialog::getOpenFileName(this, tr("Open File"), settings.last_dir, "DBC (*.dbc)"); + QString fn = QFileDialog::getOpenFileName(this, tr("Open File"), QString::fromStdString(settings.last_dir), "DBC (*.dbc)"); if (!fn.isEmpty()) { dbc_file->setText(fn); - settings.last_dir = QFileInfo(fn).absolutePath(); + settings.last_dir = std::filesystem::absolute(fn.toStdString()).parent_path().string(); } }); } diff --git a/tools/cabana/streamselector.h b/openpilot/tools/cabana/streamselector.h similarity index 100% rename from tools/cabana/streamselector.h rename to openpilot/tools/cabana/streamselector.h diff --git a/openpilot/tools/cabana/tests/test_cabana.cc b/openpilot/tools/cabana/tests/test_cabana.cc new file mode 100644 index 0000000000..c66f57d593 --- /dev/null +++ b/openpilot/tools/cabana/tests/test_cabana.cc @@ -0,0 +1,225 @@ + +#undef INFO +#include +#include + +#include "catch2/catch.hpp" +#include "tools/cabana/dbc/dbcfile.h" +#include "tools/cabana/dbc/dbcmanager.h" +#include "tools/cabana/core/settings.h" + +#ifdef QT_CORE_LIB +#include +#endif + +const std::string TEST_RLOG_URL = "https://commadataci.blob.core.windows.net/openpilotci/0c94aa1e1296d7c6/2021-05-05--19-48-37/0/rlog.bz2"; + +TEST_CASE("DBCFile::generateDBC") { + std::string fn = std::string(OPENDBC_FILE_PATH) + "/tesla_can.dbc"; + DBCFile dbc_origin(fn); + DBCFile dbc_from_generated("", dbc_origin.generateDBC()); + + REQUIRE(dbc_origin.getMessages().size() == dbc_from_generated.getMessages().size()); + auto &msgs = dbc_origin.getMessages(); + auto &new_msgs = dbc_from_generated.getMessages(); + for (auto &[id, m] : msgs) { + auto &new_m = new_msgs.at(id); + REQUIRE(m.name == new_m.name); + REQUIRE(m.size == new_m.size); + REQUIRE(m.getSignals().size() == new_m.getSignals().size()); + auto sigs = m.getSignals(); + auto new_sigs = new_m.getSignals(); + for (int i = 0; i < sigs.size(); ++i) { + REQUIRE(*sigs[i] == *new_sigs[i]); + } + } +} + +TEST_CASE("DBCFile::generateDBC - comment order") { + // Ensure that message comments are followed by signal comments and in the correct order + std::string content = R"(BO_ 160 message_1: 8 EON + SG_ signal_1 : 0|12@1+ (1,0) [0|4095] "unit" XXX + +BO_ 162 message_2: 8 EON + SG_ signal_2 : 0|12@1+ (1,0) [0|4095] "unit" XXX + +CM_ BO_ 160 "message comment"; +CM_ SG_ 160 signal_1 "signal comment"; +CM_ BO_ 162 "message comment"; +CM_ SG_ 162 signal_2 "signal comment"; +)"; + DBCFile dbc("", content); + REQUIRE(dbc.generateDBC() == content); +} + +TEST_CASE("DBCFile::generateDBC -- preserve original header") { + std::string content = R"(VERSION "1.0" + +NS_ : + CM_ + +BS_: + +BU_: EON + +BO_ 160 message_1: 8 EON + SG_ signal_1 : 0|12@1+ (1,0) [0|4095] "unit" XXX + +CM_ BO_ 160 "message comment"; +CM_ SG_ 160 signal_1 "signal comment"; +)"; + DBCFile dbc("", content); + REQUIRE(dbc.generateDBC() == content); +} + +TEST_CASE("DBCFile::generateDBC - escaped quotes") { + std::string content = R"(BO_ 160 message_1: 8 EON + SG_ signal_1 : 0|12@1+ (1,0) [0|4095] "unit" XXX + +CM_ BO_ 160 "message comment with \"escaped quotes\""; +CM_ SG_ 160 signal_1 "signal comment with \"escaped quotes\""; +)"; + DBCFile dbc("", content); + REQUIRE(dbc.generateDBC() == content); +} + +TEST_CASE("parse_dbc") { + std::string content = R"( +BO_ 160 message_1: 8 EON + SG_ signal_1 : 0|12@1+ (1,0) [0|4095] "unit" XXX + SG_ signal_2 : 12|1@1+ (1.0,0.0) [0.0|1] "" XXX + +BO_ 162 message_1: 8 XXX + SG_ signal_1 M : 0|12@1+ (1,0) [0|4095] "unit" XXX + SG_ signal_2 M4 : 12|1@1+ (1.0,0.0) [0.0|1] "" XXX + +VAL_ 160 signal_1 0 "disabled" 1.2 "initializing" 2 "fault"; + +CM_ BO_ 160 "message comment" ; +CM_ SG_ 160 signal_1 "signal comment"; +CM_ SG_ 160 signal_2 "multiple line comment +1 +2 +"; + +CM_ BO_ 162 "message comment with \"escaped quotes\""; +CM_ SG_ 162 signal_1 "signal comment with \"escaped quotes\""; +)"; + + DBCFile file("", content); + auto msg = file.msg(160); + REQUIRE(msg != nullptr); + REQUIRE(msg->name == "message_1"); + REQUIRE(msg->size == 8); + REQUIRE(msg->comment == "message comment"); + REQUIRE(msg->sigs.size() == 2); + REQUIRE(msg->transmitter == "EON"); + REQUIRE(file.msg("message_1") != nullptr); + + auto sig_1 = msg->sigs[0]; + REQUIRE(sig_1->name == "signal_1"); + REQUIRE(sig_1->start_bit == 0); + REQUIRE(sig_1->size == 12); + REQUIRE(sig_1->min == 0); + REQUIRE(sig_1->max == 4095); + REQUIRE(sig_1->unit == "unit"); + REQUIRE(sig_1->comment == "signal comment"); + REQUIRE(sig_1->receiver_name == "XXX"); + REQUIRE(sig_1->val_desc.size() == 3); + REQUIRE(sig_1->val_desc[0] == std::pair{0, "disabled"}); + REQUIRE(sig_1->val_desc[1] == std::pair{1.2, "initializing"}); + REQUIRE(sig_1->val_desc[2] == std::pair{2, "fault"}); + + auto &sig_2 = msg->sigs[1]; + REQUIRE(sig_2->comment == "multiple line comment \n1\n2"); + + // multiplexed signals + msg = file.msg(162); + REQUIRE(msg != nullptr); + REQUIRE(msg->sigs.size() == 2); + REQUIRE(msg->sigs[0]->type == cabana::Signal::Type::Multiplexor); + REQUIRE(msg->sigs[1]->type == cabana::Signal::Type::Multiplexed); + REQUIRE(msg->sigs[1]->multiplex_value == 4); + REQUIRE(msg->sigs[1]->start_bit == 12); + REQUIRE(msg->sigs[1]->size == 1); + REQUIRE(msg->sigs[1]->receiver_name == "XXX"); + + // escaped quotes + REQUIRE(msg->comment == "message comment with \"escaped quotes\""); + REQUIRE(msg->sigs[0]->comment == "signal comment with \"escaped quotes\""); +} + +TEST_CASE("parse_opendbc") { + std::vector errors; + for (const auto &entry : std::filesystem::directory_iterator(OPENDBC_FILE_PATH)) { + if (!entry.is_regular_file() || entry.path().extension() != ".dbc") continue; + try { + auto dbc = DBCFile(entry.path().string()); + } catch (std::exception &e) { + errors.push_back(e.what()); + } + } + std::ostringstream details; + for (const auto &error : errors) details << error << '\n'; + INFO(details.str()); + REQUIRE(errors.empty()); +} + +TEST_CASE("DBCManager core callbacks") { + DBCManager manager; + int files_changed = 0; + int signals_added = 0; + int masks_updated = 0; + manager.setCallbacks({ + .signal_added = [&](MessageId, const cabana::Signal *) { ++signals_added; }, + .file_changed = [&]() { ++files_changed; }, + .mask_updated = [&]() { ++masks_updated; }, + }); + + std::string error; + REQUIRE(manager.open(SOURCE_ALL, "test", "BO_ 160 message: 8 XXX\n", &error)); + REQUIRE(error.empty()); + REQUIRE(files_changed == 1); + + cabana::Signal signal{}; + signal.name = "speed"; + signal.start_bit = 0; + signal.size = 8; + signal.is_little_endian = true; + manager.addSignal({.source = 0, .address = 160}, signal); + REQUIRE(signals_added == 1); + REQUIRE(masks_updated == 1); + REQUIRE(manager.msg({.source = 0, .address = 160})->sig("speed") != nullptr); +} + +TEST_CASE("Cabana settings core defaults") { + CabanaSettingsState state; + REQUIRE(state.fps == 10); + REQUIRE(state.chart_range == 180); + REQUIRE(state.drag_direction == CabanaSettingsState::MsbFirst); + REQUIRE(state.recent_files.empty()); +} + +#ifdef QT_CORE_LIB +TEST_CASE("CabanaColor preserves QColor transformations") { + const std::vector colors = { + QColor(102, 86, 169, 64), QColor(0, 187, 255, 128), QColor(255, 0, 0, 128), QColor(45, 120, 75, 255), + }; + for (const auto &qt_color : colors) { + CabanaColor color(qt_color.red(), qt_color.green(), qt_color.blue(), qt_color.alpha()); + for (int factor : {75, 100, 135, 150, 200}) { + const auto lighter = color.lighter(factor); + const auto qt_lighter = qt_color.lighter(factor); + CHECK(std::abs(lighter.red() - qt_lighter.red()) <= 1); + CHECK(std::abs(lighter.green() - qt_lighter.green()) <= 1); + CHECK(std::abs(lighter.blue() - qt_lighter.blue()) <= 1); + + const auto darker = color.darker(factor); + const auto qt_darker = qt_color.darker(factor); + CHECK(std::abs(darker.red() - qt_darker.red()) <= 1); + CHECK(std::abs(darker.green() - qt_darker.green()) <= 1); + CHECK(std::abs(darker.blue() - qt_darker.blue()) <= 1); + } + } +} +#endif diff --git a/openpilot/tools/cabana/tests/test_runner.cc b/openpilot/tools/cabana/tests/test_runner.cc new file mode 100644 index 0000000000..a76c8e16b9 --- /dev/null +++ b/openpilot/tools/cabana/tests/test_runner.cc @@ -0,0 +1,7 @@ +#define CATCH_CONFIG_RUNNER +#include "catch2/catch.hpp" + +int main(int argc, char **argv) { + const int res = Catch::Session().run(argc, argv); + return (res < 0xff ? res : 0xff); +} diff --git a/tools/cabana/tools/findsignal.cc b/openpilot/tools/cabana/tools/findsignal.cc similarity index 79% rename from tools/cabana/tools/findsignal.cc rename to openpilot/tools/cabana/tools/findsignal.cc index ec56fcaac0..4511af7c01 100644 --- a/tools/cabana/tools/findsignal.cc +++ b/openpilot/tools/cabana/tools/findsignal.cc @@ -1,10 +1,12 @@ #include "tools/cabana/tools/findsignal.h" +#include +#include + #include #include #include #include -#include #include #include @@ -20,7 +22,7 @@ QVariant FindSignalModel::data(const QModelIndex &index, int role) const { if (role == Qt::DisplayRole) { const auto &s = filtered_signals[index.row()]; switch (index.column()) { - case 0: return s.id.toString(); + case 0: return QString::fromStdString(s.id.toString()); case 1: return QString("%1, %2").arg(s.sig.start_bit).arg(s.sig.size); case 2: return s.values.join(" "); } @@ -32,36 +34,49 @@ void FindSignalModel::search(std::function cmp) { beginResetModel(); std::mutex lock; - const auto prev_sigs = !histories.isEmpty() ? histories.back() : initial_signals; + const auto prev_sigs = !histories.empty() ? histories.back() : initial_signals; filtered_signals.clear(); filtered_signals.reserve(prev_sigs.size()); - QtConcurrent::blockingMap(prev_sigs, [&](auto &s) { - const auto &events = can->events(s.id); - auto first = std::upper_bound(events.cbegin(), events.cend(), s.mono_time, CompareCanEvent()); - auto last = events.cend(); - if (last_time < std::numeric_limits::max()) { - last = std::upper_bound(events.cbegin(), events.cend(), last_time, CompareCanEvent()); - } - auto it = std::find_if(first, last, [&](const CanEvent *e) { return cmp(get_raw_value(e->dat, e->size, s.sig)); }); - if (it != last) { - auto values = s.values; - values += QString("(%1, %2)").arg(can->toSeconds((*it)->mono_time), 0, 'f', 3).arg(get_raw_value((*it)->dat, (*it)->size, s.sig)); - std::lock_guard lk(lock); - filtered_signals.push_back({.id = s.id, .mono_time = (*it)->mono_time, .sig = s.sig, .values = values}); - } - }); + unsigned int num_threads = std::max(1u, std::thread::hardware_concurrency()); + size_t chunk = (prev_sigs.size() + num_threads - 1) / num_threads; + std::vector threads; + for (unsigned int t = 0; t < num_threads && t * chunk < (size_t)prev_sigs.size(); ++t) { + size_t start = t * chunk; + size_t end = std::min(start + chunk, (size_t)prev_sigs.size()); + threads.emplace_back([&, start, end]() { + for (size_t i = start; i < end; ++i) { + const auto &s = prev_sigs[i]; + const auto &events = can->events(s.id); + auto first = std::upper_bound(events.cbegin(), events.cend(), s.mono_time, CompareCanEvent()); + auto last = events.cend(); + if (last_time < std::numeric_limits::max()) { + last = std::upper_bound(events.cbegin(), events.cend(), last_time, CompareCanEvent()); + } + + auto it = std::find_if(first, last, [&](const CanEvent *e) { return cmp(get_raw_value(e->dat, e->size, s.sig)); }); + if (it != last) { + auto values = s.values; + values += QString("(%1, %2)").arg(can->toSeconds((*it)->mono_time), 0, 'f', 3).arg(get_raw_value((*it)->dat, (*it)->size, s.sig)); + std::lock_guard lk(lock); + filtered_signals.push_back({.id = s.id, .mono_time = (*it)->mono_time, .sig = s.sig, .values = values}); + } + } + }); + } + for (auto &th : threads) th.join(); + histories.push_back(filtered_signals); endResetModel(); } void FindSignalModel::undo() { - if (!histories.isEmpty()) { + if (!histories.empty()) { beginResetModel(); histories.pop_back(); filtered_signals.clear(); - if (!histories.isEmpty()) filtered_signals = histories.back(); + if (!histories.empty()) filtered_signals = histories.back(); endResetModel(); } } @@ -84,9 +99,9 @@ FindSignalDlg::FindSignalDlg(QWidget *parent) : QDialog(parent, Qt::WindowFlags( message_group = new QGroupBox(tr("Messages"), this); QFormLayout *message_layout = new QFormLayout(message_group); message_layout->addRow(tr("Bus"), bus_edit = new QLineEdit()); - bus_edit->setPlaceholderText(tr("comma-seperated values. Leave blank for all")); + bus_edit->setPlaceholderText(tr("comma-separated values. Leave blank for all")); message_layout->addRow(tr("Address"), address_edit = new QLineEdit()); - address_edit->setPlaceholderText(tr("comma-seperated hex values. Leave blank for all")); + address_edit->setPlaceholderText(tr("comma-separated hex values. Leave blank for all")); QHBoxLayout *hlayout = new QHBoxLayout(); hlayout->addWidget(first_time_edit = new QLineEdit("0")); hlayout->addWidget(new QLabel("-")); @@ -172,7 +187,7 @@ FindSignalDlg::FindSignalDlg(QWidget *parent) : QDialog(parent, Qt::WindowFlags( } void FindSignalDlg::search() { - if (model->histories.isEmpty()) { + if (model->histories.empty()) { setInitialSignals(); } auto v1 = value1->text().toDouble(); @@ -196,13 +211,13 @@ void FindSignalDlg::search() { } void FindSignalDlg::setInitialSignals() { - QSet buses; + std::set buses; for (auto bus : bus_edit->text().trimmed().split(",")) { bus = bus.trimmed(); if (!bus.isEmpty()) buses.insert(bus.toUShort()); } - QSet addresses; + std::set addresses; for (auto addr : address_edit->text().trimmed().split(",")) { addr = addr.trimmed(); if (!addr.isEmpty()) addresses.insert(addr.toULong(nullptr, 16)); @@ -225,7 +240,7 @@ void FindSignalDlg::setInitialSignals() { model->initial_signals.clear(); for (const auto &[id, m] : can->lastMessages()) { - if ((buses.isEmpty() || buses.contains(id.source)) && (addresses.isEmpty() || addresses.contains(id.address))) { + if ((buses.empty() || buses.count(id.source)) && (addresses.empty() || addresses.count(id.address))) { const auto &events = can->events(id); auto e = std::lower_bound(events.cbegin(), events.cend(), first_time, CompareCanEvent()); if (e != events.cend()) { @@ -246,12 +261,12 @@ void FindSignalDlg::setInitialSignals() { } void FindSignalDlg::modelReset() { - properties_group->setEnabled(model->histories.isEmpty()); - message_group->setEnabled(model->histories.isEmpty()); - search_btn->setText(model->histories.isEmpty() ? tr("Find") : tr("Find Next")); - reset_btn->setEnabled(!model->histories.isEmpty()); + properties_group->setEnabled(model->histories.empty()); + message_group->setEnabled(model->histories.empty()); + search_btn->setText(model->histories.empty() ? tr("Find") : tr("Find Next")); + reset_btn->setEnabled(!model->histories.empty()); undo_btn->setEnabled(model->histories.size() > 1); - search_btn->setEnabled(model->rowCount() > 0 || model->histories.isEmpty()); + search_btn->setEnabled(model->rowCount() > 0 || model->histories.empty()); stats_label->setVisible(true); stats_label->setText(tr("%1 matches. right click on an item to create signal. double click to open message").arg(model->filtered_signals.size())); } @@ -262,7 +277,7 @@ void FindSignalDlg::customMenuRequested(const QPoint &pos) { menu.addAction(tr("Create Signal")); if (menu.exec(view->mapToGlobal(pos))) { auto &s = model->filtered_signals[index.row()]; - UndoStack::push(new AddSigCommand(s.id, s.sig)); + UndoStack::instance()->push(new AddSigCommand(s.id, s.sig)); emit openMessage(s.id); } } diff --git a/tools/cabana/tools/findsignal.h b/openpilot/tools/cabana/tools/findsignal.h similarity index 87% rename from tools/cabana/tools/findsignal.h rename to openpilot/tools/cabana/tools/findsignal.h index 5ef7461fee..239a08c9c4 100644 --- a/tools/cabana/tools/findsignal.h +++ b/openpilot/tools/cabana/tools/findsignal.h @@ -2,6 +2,8 @@ #include #include +#include +#include #include #include @@ -26,14 +28,14 @@ public: QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; int columnCount(const QModelIndex &parent = QModelIndex()) const override { return 3; } - int rowCount(const QModelIndex &parent = QModelIndex()) const override { return std::min(filtered_signals.size(), 300); } + int rowCount(const QModelIndex &parent = QModelIndex()) const override { return std::min((int)filtered_signals.size(), 300); } void search(std::function cmp); void reset(); void undo(); - QList filtered_signals; - QList initial_signals; - QList> histories; + std::vector filtered_signals; + std::vector initial_signals; + std::vector> histories; uint64_t last_time = std::numeric_limits::max(); }; diff --git a/tools/cabana/tools/findsimilarbits.cc b/openpilot/tools/cabana/tools/findsimilarbits.cc similarity index 88% rename from tools/cabana/tools/findsimilarbits.cc rename to openpilot/tools/cabana/tools/findsimilarbits.cc index c3c659791a..8062b61199 100644 --- a/tools/cabana/tools/findsimilarbits.cc +++ b/openpilot/tools/cabana/tools/findsimilarbits.cc @@ -1,6 +1,7 @@ #include "tools/cabana/tools/findsimilarbits.h" #include +#include #include #include @@ -31,7 +32,7 @@ FindSimilarBitsDlg::FindSimilarBitsDlg(QWidget *parent) : QDialog(parent, Qt::Wi msg_cb = new QComboBox(this); // TODO: update when src_bus_combo changes for (auto &[address, msg] : dbc()->getMessages(-1)) { - msg_cb->addItem(msg.name, address); + msg_cb->addItem(QString::fromStdString(msg.name), address); } msg_cb->model()->sort(0); msg_cb->setCurrentIndex(0); @@ -114,10 +115,10 @@ void FindSimilarBitsDlg::find() { search_btn->setEnabled(true); } -QList FindSimilarBitsDlg::calcBits(uint8_t bus, uint32_t selected_address, int byte_idx, - int bit_idx, uint8_t find_bus, bool equal, int min_msgs_cnt) { - QHash> mismatches; - QHash msg_count; +std::vector FindSimilarBitsDlg::calcBits(uint8_t bus, uint32_t selected_address, int byte_idx, + int bit_idx, uint8_t find_bus, bool equal, int min_msgs_cnt) { + std::unordered_map> mismatches; + std::unordered_map msg_count; const auto &events = can->allEvents(); int bit_to_find = -1; for (const CanEvent *e : events) { @@ -143,14 +144,14 @@ QList FindSimilarBitsDlg::calcBits(uint8_ } } - QList result; + std::vector result; result.reserve(mismatches.size()); for (auto it = mismatches.begin(); it != mismatches.end(); ++it) { - if (auto cnt = msg_count[it.key()]; cnt > min_msgs_cnt) { - auto &mismatched = it.value(); - for (int i = 0; i < mismatched.size(); ++i) { + if (auto cnt = msg_count[it->first]; cnt > (uint32_t)min_msgs_cnt) { + auto &mismatched = it->second; + for (int i = 0; i < (int)mismatched.size(); ++i) { if (float perc = (mismatched[i] / (double)cnt) * 100; perc < 50) { - result.push_back({it.key(), (uint32_t)i / 8, (uint32_t)i % 8, mismatched[i], cnt, perc}); + result.push_back({it->first, (uint32_t)i / 8, (uint32_t)i % 8, mismatched[i], cnt, perc}); } } } diff --git a/tools/cabana/tools/findsimilarbits.h b/openpilot/tools/cabana/tools/findsimilarbits.h similarity index 82% rename from tools/cabana/tools/findsimilarbits.h rename to openpilot/tools/cabana/tools/findsimilarbits.h index 77bfac19ca..3451360654 100644 --- a/tools/cabana/tools/findsimilarbits.h +++ b/openpilot/tools/cabana/tools/findsimilarbits.h @@ -1,5 +1,7 @@ #pragma once +#include + #include #include #include @@ -22,7 +24,7 @@ private: uint32_t address, byte_idx, bit_idx, mismatches, total; float perc; }; - QList calcBits(uint8_t bus, uint32_t selected_address, int byte_idx, int bit_idx, uint8_t find_bus, + std::vector calcBits(uint8_t bus, uint32_t selected_address, int byte_idx, int bit_idx, uint8_t find_bus, bool equal, int min_msgs_cnt); void find(); diff --git a/tools/cabana/tools/routeinfo.cc b/openpilot/tools/cabana/tools/routeinfo.cc similarity index 100% rename from tools/cabana/tools/routeinfo.cc rename to openpilot/tools/cabana/tools/routeinfo.cc diff --git a/tools/cabana/tools/routeinfo.h b/openpilot/tools/cabana/tools/routeinfo.h similarity index 100% rename from tools/cabana/tools/routeinfo.h rename to openpilot/tools/cabana/tools/routeinfo.h diff --git a/openpilot/tools/cabana/utils/elidedlabel.cc b/openpilot/tools/cabana/utils/elidedlabel.cc new file mode 100644 index 0000000000..629a108b16 --- /dev/null +++ b/openpilot/tools/cabana/utils/elidedlabel.cc @@ -0,0 +1,29 @@ +#include "tools/cabana/utils/elidedlabel.h" +#include +#include + +ElidedLabel::ElidedLabel(QWidget *parent) : ElidedLabel({}, parent) {} + +ElidedLabel::ElidedLabel(const QString &text, QWidget *parent) : QLabel(text.trimmed(), parent) { + setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); + setMinimumWidth(1); +} + +void ElidedLabel::resizeEvent(QResizeEvent* event) { + QLabel::resizeEvent(event); + lastText_ = elidedText_ = ""; +} + +void ElidedLabel::paintEvent(QPaintEvent *event) { + const QString curText = text(); + if (curText != lastText_) { + elidedText_ = fontMetrics().elidedText(curText, Qt::ElideRight, contentsRect().width()); + lastText_ = curText; + } + + QPainter painter(this); + drawFrame(&painter); + QStyleOption opt; + opt.initFrom(this); + style()->drawItemText(&painter, contentsRect(), alignment(), opt.palette, isEnabled(), elidedText_, foregroundRole()); +} diff --git a/openpilot/tools/cabana/utils/elidedlabel.h b/openpilot/tools/cabana/utils/elidedlabel.h new file mode 100644 index 0000000000..577eea12a0 --- /dev/null +++ b/openpilot/tools/cabana/utils/elidedlabel.h @@ -0,0 +1,25 @@ +#pragma once + +#include +#include + +class ElidedLabel : public QLabel { + Q_OBJECT + +public: + explicit ElidedLabel(QWidget *parent = 0); + explicit ElidedLabel(const QString &text, QWidget *parent = 0); + +signals: + void clicked(); + +protected: + void paintEvent(QPaintEvent *event) override; + void resizeEvent(QResizeEvent* event) override; + void mouseReleaseEvent(QMouseEvent *event) override { + if (rect().contains(event->pos())) { + emit clicked(); + } + } + QString lastText_, elidedText_; +}; diff --git a/openpilot/tools/cabana/utils/export.cc b/openpilot/tools/cabana/utils/export.cc new file mode 100644 index 0000000000..d585827ef5 --- /dev/null +++ b/openpilot/tools/cabana/utils/export.cc @@ -0,0 +1,45 @@ +#include "tools/cabana/utils/export.h" + +#include +#include + +#include "tools/cabana/streams/abstractstream.h" + +namespace utils { + +void exportToCSV(const std::string &file_name, std::optional msg_id) { + std::ofstream stream(file_name, std::ios::trunc); + if (stream) { + stream << "time,addr,bus,data\n"; + for (auto e : msg_id ? can->events(*msg_id) : can->allEvents()) { + stream << std::fixed << std::setprecision(3) << can->toSeconds(e->mono_time) << "," + << "0x" << std::hex << e->address << std::dec << "," << static_cast(e->src) << ",0x" + << std::uppercase << std::hex << std::setfill('0'); + for (int i = 0; i < e->size; ++i) stream << std::setw(2) << static_cast(e->dat[i]); + stream << std::nouppercase << std::dec << "\n"; + } + } +} + +void exportSignalsToCSV(const std::string &file_name, const MessageId &msg_id) { + std::ofstream stream(file_name, std::ios::trunc); + if (auto msg = dbc()->msg(msg_id); msg && !msg->sigs.empty() && stream) { + stream << "time,addr,bus"; + for (auto s : msg->sigs) + stream << "," << s->name.c_str(); + stream << "\n"; + + for (auto e : can->events(msg_id)) { + stream << std::fixed << std::setprecision(3) << can->toSeconds(e->mono_time) << "," + << "0x" << std::hex << e->address << std::dec << "," << static_cast(e->src); + for (auto s : msg->sigs) { + double value = 0; + s->getValue(e->dat, e->size, &value); + stream << "," << std::fixed << std::setprecision(s->precision) << value; + } + stream << "\n"; + } + } +} + +} // namespace utils diff --git a/openpilot/tools/cabana/utils/export.h b/openpilot/tools/cabana/utils/export.h new file mode 100644 index 0000000000..ee110e8321 --- /dev/null +++ b/openpilot/tools/cabana/utils/export.h @@ -0,0 +1,11 @@ +#pragma once + +#include +#include + +#include "tools/cabana/dbc/dbcmanager.h" + +namespace utils { +void exportToCSV(const std::string &file_name, std::optional msg_id = std::nullopt); +void exportSignalsToCSV(const std::string &file_name, const MessageId &msg_id); +} // namespace utils diff --git a/openpilot/tools/cabana/utils/util.cc b/openpilot/tools/cabana/utils/util.cc new file mode 100644 index 0000000000..87a0f89427 --- /dev/null +++ b/openpilot/tools/cabana/utils/util.cc @@ -0,0 +1,542 @@ +#include "tools/cabana/utils/util.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include "common/util.h" + +// SegmentTree + +void SegmentTree::build(const std::vector &arr) { + size = arr.size(); + tree.resize(4 * size); // size of the tree is 4 times the size of the array + if (size > 0) { + build_tree(arr, 1, 0, size - 1); + } +} + +void SegmentTree::build_tree(const std::vector &arr, int n, int left, int right) { + if (left == right) { + const double y = arr[left].y(); + tree[n] = {y, y}; + } else { + const int mid = (left + right) >> 1; + build_tree(arr, 2 * n, left, mid); + build_tree(arr, 2 * n + 1, mid + 1, right); + tree[n] = {std::min(tree[2 * n].first, tree[2 * n + 1].first), std::max(tree[2 * n].second, tree[2 * n + 1].second)}; + } +} + +std::pair SegmentTree::get_minmax(int n, int left, int right, int range_left, int range_right) const { + if (range_left > right || range_right < left) + return {std::numeric_limits::max(), std::numeric_limits::lowest()}; + if (range_left <= left && range_right >= right) + return tree[n]; + int mid = (left + right) >> 1; + auto l = get_minmax(2 * n, left, mid, range_left, range_right); + auto r = get_minmax(2 * n + 1, mid + 1, right, range_left, range_right); + return {std::min(l.first, r.first), std::max(l.second, r.second)}; +} + +// MessageBytesDelegate + +MessageBytesDelegate::MessageBytesDelegate(QObject *parent, bool multiple_lines) + : font_metrics(QApplication::font()), multiple_lines(multiple_lines), QStyledItemDelegate(parent) { + fixed_font = QFontDatabase::systemFont(QFontDatabase::FixedFont); + byte_size = QFontMetrics(fixed_font).size(Qt::TextSingleLine, "00 ") + QSize(0, 2); + for (int i = 0; i < 256; ++i) { + hex_text_table[i].setText(QStringLiteral("%1").arg(i, 2, 16, QLatin1Char('0')).toUpper()); + hex_text_table[i].prepare({}, fixed_font); + } + h_margin = QApplication::style()->pixelMetric(QStyle::PM_FocusFrameHMargin) + 1; + v_margin = QApplication::style()->pixelMetric(QStyle::PM_FocusFrameVMargin) + 1; +} + +QSize MessageBytesDelegate::sizeForBytes(int n) const { + int rows = multiple_lines ? std::max(1, n / 8) : 1; + return {(n / rows) * byte_size.width() + h_margin * 2, rows * byte_size.height() + v_margin * 2}; +} + +QSize MessageBytesDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { + auto data = index.data(BytesRole); + return sizeForBytes(data.isValid() ? static_cast *>(data.value())->size() : 0); +} + +void MessageBytesDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { + if (option.state & QStyle::State_Selected) { + painter->fillRect(option.rect, option.palette.brush(QPalette::Normal, QPalette::Highlight)); + } + + QRect item_rect = option.rect.adjusted(h_margin, v_margin, -h_margin, -v_margin); + QColor highlighted_color = option.palette.color(QPalette::HighlightedText); + auto text_color = index.data(Qt::ForegroundRole).value(); + bool inactive = text_color.isValid(); + if (!inactive) { + text_color = option.palette.color(QPalette::Text); + } + auto data = index.data(BytesRole); + if (!data.isValid()) { + painter->setFont(option.font); + painter->setPen(option.state & QStyle::State_Selected ? highlighted_color : text_color); + QString text = font_metrics.elidedText(index.data(Qt::DisplayRole).toString(), Qt::ElideRight, item_rect.width()); + painter->drawText(item_rect, Qt::AlignLeft | Qt::AlignVCenter, text); + return; + } + + // Paint hex column + const auto &bytes = *static_cast *>(data.value()); + const auto &colors = *static_cast *>(index.data(ColorsRole).value()); + + painter->setFont(fixed_font); + const QPen text_pen(option.state & QStyle::State_Selected ? highlighted_color : text_color); + const QPoint pt = item_rect.topLeft(); + for (int i = 0; i < bytes.size(); ++i) { + int row = !multiple_lines ? 0 : i / 8; + int column = !multiple_lines ? i : i % 8; + QRect r({pt.x() + column * byte_size.width(), pt.y() + row * byte_size.height()}, byte_size); + + if (!inactive && i < colors.size() && colors[i].alpha() > 0) { + if (option.state & QStyle::State_Selected) { + painter->setPen(option.palette.color(QPalette::Text)); + painter->fillRect(r, option.palette.color(QPalette::Window)); + } + painter->fillRect(r, toQColor(colors[i])); + } else { + painter->setPen(text_pen); + } + utils::drawStaticText(painter, r, hex_text_table[bytes[i]]); + } +} + +// TabBar + +int TabBar::addTab(const QString &text) { + int index = QTabBar::addTab(text); + QToolButton *btn = new ToolButton("x", tr("Close Tab")); + int width = style()->pixelMetric(QStyle::PM_TabCloseIndicatorWidth, nullptr, btn); + int height = style()->pixelMetric(QStyle::PM_TabCloseIndicatorHeight, nullptr, btn); + btn->setFixedSize({width, height}); + setTabButton(index, QTabBar::RightSide, btn); + QObject::connect(btn, &QToolButton::clicked, this, &TabBar::closeTabClicked); + return index; +} + +void TabBar::closeTabClicked() { + QObject *object = sender(); + for (int i = 0; i < count(); ++i) { + if (tabButton(i, QTabBar::RightSide) == object) { + emit tabCloseRequested(i); + break; + } + } +} + +// UnixSignalHandler + +UnixSignalHandler::UnixSignalHandler() { + if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sig_fd)) { + qFatal("Couldn't create TERM socketpair"); + } + + waiter = std::thread([this]() { + int tmp = 0; + while (::read(sig_fd[1], &tmp, sizeof(tmp)) < 0) { + if (errno != EINTR) return; + } + if (shutting_down.load()) return; + + // Marshal exit onto the GUI thread (qApp methods are not thread-safe). + QMetaObject::invokeMethod(qApp, []() { + printf("\nexiting...\n"); + qApp->closeAllWindows(); + qApp->exit(); + }, Qt::QueuedConnection); + }); + + std::signal(SIGINT, signalHandler); + std::signal(SIGTERM, UnixSignalHandler::signalHandler); +} + +UnixSignalHandler::~UnixSignalHandler() { + shutting_down.store(true); + int dummy = 0; + (void)!::write(sig_fd[0], &dummy, sizeof(dummy)); + if (waiter.joinable()) waiter.join(); + ::close(sig_fd[0]); + ::close(sig_fd[1]); +} + +void UnixSignalHandler::signalHandler(int s) { + (void)!::write(sig_fd[0], &s, sizeof(s)); +} + +// NameValidator + +NameValidator::NameValidator(QObject *parent) : QValidator(parent) {} + +QValidator::State NameValidator::validate(QString &input, int &pos) const { + Q_UNUSED(pos); + input.replace(' ', '_'); + if (input.isEmpty()) return QValidator::Intermediate; + for (const QChar &c : input) { + if (!c.isLetterOrNumber() && c != '_') return QValidator::Invalid; + } + return QValidator::Acceptable; +} + +// NodeValidator + +NodeValidator::NodeValidator(QObject *parent) : QValidator(parent) {} + +QValidator::State NodeValidator::validate(QString &input, int &pos) const { + Q_UNUSED(pos); + if (input.isEmpty()) return QValidator::Intermediate; + // Match ^\w+(,\w+)*$ ; a trailing comma is Intermediate (user still typing). + bool need_word = true; + for (const QChar &c : input) { + if (c.isLetterOrNumber() || c == '_') { + need_word = false; + } else if (c == ',' && !need_word) { + need_word = true; + } else { + return QValidator::Invalid; + } + } + return need_word ? QValidator::Intermediate : QValidator::Acceptable; +} + +// NonWhitespaceValidator + +NonWhitespaceValidator::NonWhitespaceValidator(QObject *parent) : QValidator(parent) {} + +QValidator::State NonWhitespaceValidator::validate(QString &input, int &pos) const { + Q_UNUSED(pos); + if (input.isEmpty()) return QValidator::Intermediate; + for (const QChar &c : input) { + if (c.isSpace()) return QValidator::Invalid; + } + return QValidator::Acceptable; +} + +// IpAddressValidator + +IpAddressValidator::IpAddressValidator(QObject *parent) : QValidator(parent) {} + +QValidator::State IpAddressValidator::validate(QString &input, int &pos) const { + Q_UNUSED(pos); + if (input.isEmpty()) return QValidator::Intermediate; + + int dots = 0; + int value = 0; + bool has_digit = false; + for (const QChar &c : input) { + if (c.isDigit()) { + value = has_digit ? value * 10 + c.digitValue() : c.digitValue(); + if (value > 255) return QValidator::Invalid; + has_digit = true; + } else if (c == '.') { + if (!has_digit || dots >= 3) return QValidator::Invalid; + ++dots; + has_digit = false; + value = 0; + } else { + return QValidator::Invalid; + } + } + return (dots == 3 && has_digit) ? QValidator::Acceptable : QValidator::Intermediate; +} + +DoubleValidator::DoubleValidator(QObject *parent) : QValidator(parent) {} + +QValidator::State DoubleValidator::validate(QString &input, int &pos) const { + Q_UNUSED(pos); + if (input.isEmpty()) return QValidator::Intermediate; + + // Match QString::toDouble(): C locale, no hex floats / inf / nan. + const std::string bytes = input.toLatin1().toStdString(); + // strtod accepts 0x… hex floats and p-exponents; QString::toDouble does not. + if (bytes.find_first_of("xXpP") != std::string::npos) { + return QValidator::Invalid; + } + + const char *start = bytes.c_str(); + char *end = nullptr; + const double value = std::strtod(start, &end); + if (end == start) { + // Still typing a sign, decimal point, or exponent prefix. + if (input == "-" || input == "+" || input == "." || input == "-." || input == "+.") { + return QValidator::Intermediate; + } + return QValidator::Invalid; + } + if (*end == '\0') { + // Reject inf/nan (strtod accepts them; QDoubleValidator / toDouble path should not). + return std::isfinite(value) ? QValidator::Acceptable : QValidator::Invalid; + } + + // Partial exponent / trailing sign while typing (e.g. "1e", "1e-", "1."). + for (const char *p = end; *p; ++p) { + const char c = *p; + if (!(c == 'e' || c == 'E' || c == '+' || c == '-' || c == '.' || (c >= '0' && c <= '9'))) { + return QValidator::Invalid; + } + } + return QValidator::Intermediate; +} + +namespace utils { + +std::string homePath() { + const char *home = ::getenv("HOME"); + return home ? home : ""; +} + +std::filesystem::path configPath() { +#ifdef __APPLE__ + return std::filesystem::path(homePath()) / "Library/Preferences"; +#else + const char *xdg = ::getenv("XDG_CONFIG_HOME"); + return (xdg && xdg[0]) ? std::filesystem::path(xdg) : std::filesystem::path(homePath()) / ".config"; +#endif +} + +#ifdef __APPLE__ +static const char *clipboard_read_cmds[] = {"pbpaste"}; +static const char *clipboard_write_cmds[] = {"pbcopy"}; +#else +static const char *clipboard_read_cmds[] = {"wl-paste --no-newline 2>/dev/null", "xclip -selection clipboard -o 2>/dev/null", "xsel -ob 2>/dev/null"}; +static const char *clipboard_write_cmds[] = {"wl-copy 2>/dev/null", "xclip -selection clipboard 2>/dev/null", "xsel -ib 2>/dev/null"}; +#endif + +bool getClipboardText(std::string *text) { + text->clear(); + bool has_tool = false; + for (const char *cmd : clipboard_read_cmds) { + FILE *f = ::popen(cmd, "r"); + if (!f) continue; + std::string out; + char buf[4096]; + for (size_t n; (n = ::fread(buf, 1, sizeof(buf), f)) > 0;) out.append(buf, n); + int status = ::pclose(f); + if (status == 0) { + *text = std::move(out); + return true; + } + has_tool |= WIFEXITED(status) && WEXITSTATUS(status) != 127; // 127: command not found + } + return has_tool; // tool present but clipboard empty +} + +bool setClipboardText(const std::string &text) { + std::signal(SIGPIPE, SIG_IGN); + for (const char *cmd : clipboard_write_cmds) { + FILE *f = ::popen(cmd, "w"); + if (!f) continue; + size_t written = ::fwrite(text.data(), 1, text.size(), f); + if (::pclose(f) == 0 && written == text.size()) return true; + } + return false; +} + +bool isDarkTheme() { + QColor windowColor = QApplication::palette().color(QPalette::Window); + return windowColor.lightness() < 128; +} + +QPixmap icon(const QString &id) { + bool dark_theme = isDarkTheme(); + + QPixmap pm; + QString key = "bootstrap_" % id % (dark_theme ? "1" : "0"); + if (!QPixmapCache::find(key, &pm)) { + pm = bootstrapPixmap(id); + if (dark_theme) { + QPainter p(&pm); + p.setCompositionMode(QPainter::CompositionMode_SourceIn); + p.fillRect(pm.rect(), QColor("#bbbbbb")); + } + QPixmapCache::insert(key, pm); + } + return pm; +} + +void setTheme(int theme) { + auto style = QApplication::style(); + if (!style) return; + + static int prev_theme = 0; + if (theme != prev_theme) { + prev_theme = theme; + QPalette new_palette; + if (theme == DARK_THEME) { + // "Darcula" like dark theme + new_palette.setColor(QPalette::Window, QColor("#353535")); + new_palette.setColor(QPalette::WindowText, QColor("#bbbbbb")); + new_palette.setColor(QPalette::Base, QColor("#3c3f41")); + new_palette.setColor(QPalette::AlternateBase, QColor("#3c3f41")); + new_palette.setColor(QPalette::ToolTipBase, QColor("#3c3f41")); + new_palette.setColor(QPalette::ToolTipText, QColor("#bbb")); + new_palette.setColor(QPalette::Text, QColor("#bbbbbb")); + new_palette.setColor(QPalette::Button, QColor("#3c3f41")); + new_palette.setColor(QPalette::ButtonText, QColor("#bbbbbb")); + new_palette.setColor(QPalette::Highlight, QColor("#2f65ca")); + new_palette.setColor(QPalette::HighlightedText, QColor("#bbbbbb")); + new_palette.setColor(QPalette::BrightText, QColor("#f0f0f0")); + new_palette.setColor(QPalette::Disabled, QPalette::ButtonText, QColor("#777777")); + new_palette.setColor(QPalette::Disabled, QPalette::WindowText, QColor("#777777")); + new_palette.setColor(QPalette::Disabled, QPalette::Text, QColor("#777777")); + new_palette.setColor(QPalette::Light, QColor("#777777")); + new_palette.setColor(QPalette::Dark, QColor("#353535")); + } else { + new_palette = style->standardPalette(); + } + qApp->setPalette(new_palette); + style->polish(qApp); + for (auto w : QApplication::allWidgets()) { + w->setPalette(new_palette); + } + } +} + +QString formatSeconds(double sec, bool include_milliseconds, bool absolute_time) { + if (absolute_time) { + const auto ms_total = static_cast(std::llround(sec * 1000.0)); + const std::time_t secs = static_cast(ms_total / 1000); + int millis = static_cast(ms_total % 1000); + if (millis < 0) millis = -millis; + std::tm tm{}; + localtime_r(&secs, &tm); + char buf[64]; + std::strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", &tm); + if (include_milliseconds) { + return QString::asprintf("%s.%03d", buf, millis); + } + return QString::fromUtf8(buf); + } + + // Relative duration (not wall-clock). + const bool show_hours = sec > 60 * 60; + int total_ms = static_cast(std::llround(std::max(0.0, sec) * 1000.0)); + const int hours = total_ms / (3600 * 1000); + const int minutes = (total_ms / (60 * 1000)) % 60; + const int seconds = (total_ms / 1000) % 60; + const int millis = total_ms % 1000; + if (show_hours) { + return include_milliseconds ? QString::asprintf("%02d:%02d:%02d.%03d", hours, minutes, seconds, millis) + : QString::asprintf("%02d:%02d:%02d", hours, minutes, seconds); + } + return include_milliseconds ? QString::asprintf("%02d:%02d.%03d", minutes, seconds, millis) + : QString::asprintf("%02d:%02d", minutes, seconds); +} + +} // namespace utils + +int num_decimals(double num) { + const QString string = QString::number(num); + auto dot_pos = string.indexOf('.'); + return dot_pos == -1 ? 0 : string.size() - dot_pos - 1; +} + +QString signalToolTip(const cabana::Signal *sig) { + return QObject::tr(R"( + %1
+ Start Bit: %2 Size: %3
+ MSB: %4 LSB: %5
+ Little Endian: %6 Signed: %7
+ )").arg(QString::fromStdString(sig->name)).arg(sig->start_bit).arg(sig->size).arg(sig->msb).arg(sig->lsb) + .arg(sig->is_little_endian ? "Y" : "N").arg(sig->is_signed ? "Y" : "N"); +} + +void sigTermHandler(int s) { + std::signal(s, SIG_DFL); + qApp->quit(); +} + +void initApp(int argc, char *argv[], bool disable_hidpi) { + // setup signal handlers to exit gracefully + std::signal(SIGINT, sigTermHandler); + std::signal(SIGTERM, sigTermHandler); + + std::filesystem::path app_dir; +#ifdef __APPLE__ + // Get the devicePixelRatio, and scale accordingly to maintain 1:1 rendering + QApplication tmp(argc, argv); + app_dir = QCoreApplication::applicationDirPath().toStdString(); + if (disable_hidpi) { + qputenv("QT_SCALE_FACTOR", QString::number(1.0 / tmp.devicePixelRatio()).toLocal8Bit()); + } +#else + app_dir = std::filesystem::path(util::readlink("/proc/self/exe")).parent_path(); +#endif + + qputenv("QT_DBL_CLICK_DIST", "150"); + // ensure the current dir matches the exectuable's directory + std::error_code ec; + std::filesystem::current_path(app_dir, ec); +} + +// embedded at build time from the bootstrap_icons package (see SConscript) +extern const unsigned char bootstrap_icons_svg[]; +extern const size_t bootstrap_icons_svg_len; + +static std::unordered_map load_bootstrap_icons() { + std::unordered_map icons; + + const std::string content(reinterpret_cast(bootstrap_icons_svg), bootstrap_icons_svg_len); + const std::string sym_open = " with + svg_str.replace(0, 7, " ""); // "" (9) -> "" (6) + icons[id] = std::move(svg_str); + } + } + pos = end; + } + return icons; +} + +QPixmap bootstrapPixmap(const QString &id) { + static auto icons = load_bootstrap_icons(); + + QPixmap pixmap; + auto it = icons.find(id.toStdString()); + if (it != icons.end()) { + pixmap.loadFromData((const uchar *)it->second.data(), it->second.size(), "svg"); + } + return pixmap; +} diff --git a/openpilot/tools/cabana/utils/util.h b/openpilot/tools/cabana/utils/util.h new file mode 100644 index 0000000000..5a3c62d118 --- /dev/null +++ b/openpilot/tools/cabana/utils/util.h @@ -0,0 +1,220 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "tools/cabana/dbc/dbc.h" +#include "tools/cabana/settings.h" + +inline QColor toQColor(const CabanaColor &color) { + return QColor(color.r, color.g, color.b, color.a); +} + +class LogSlider : public QSlider { + Q_OBJECT + +public: + LogSlider(double factor, Qt::Orientation orientation, QWidget *parent = nullptr) : factor(factor), QSlider(orientation, parent) {} + + void setRange(double min, double max) { + log_min = factor * std::log10(min); + log_max = factor * std::log10(max); + QSlider::setRange(min, max); + setValue(QSlider::value()); + } + int value() const { + double v = log_min + (log_max - log_min) * ((QSlider::value() - minimum()) / double(maximum() - minimum())); + return std::lround(std::pow(10, v / factor)); + } + void setValue(int v) { + double log_v = std::clamp(factor * std::log10(v), log_min, log_max); + v = minimum() + (maximum() - minimum()) * ((log_v - log_min) / (log_max - log_min)); + QSlider::setValue(v); + } + +private: + double factor, log_min = 0, log_max = 1; +}; + +enum { + ColorsRole = Qt::UserRole + 1, + BytesRole = Qt::UserRole + 2 +}; + +class SegmentTree { +public: + SegmentTree() = default; + void build(const std::vector &arr); + inline std::pair minmax(int left, int right) const { return get_minmax(1, 0, size - 1, left, right); } + +private: + std::pair get_minmax(int n, int left, int right, int range_left, int range_right) const; + void build_tree(const std::vector &arr, int n, int left, int right); + std::vector> tree; + int size = 0; +}; + +class MessageBytesDelegate : public QStyledItemDelegate { + Q_OBJECT +public: + MessageBytesDelegate(QObject *parent, bool multiple_lines = false); + void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override; + QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override; + bool multipleLines() const { return multiple_lines; } + void setMultipleLines(bool v) { multiple_lines = v; } + QSize sizeForBytes(int n) const; + +private: + std::array hex_text_table; + QFontMetrics font_metrics; + QFont fixed_font; + QSize byte_size = {}; + bool multiple_lines = false; + int h_margin, v_margin; +}; + +// Accepts a single identifier: one or more [A-Za-z0-9_], spaces rewritten to '_'. +class NameValidator : public QValidator { + Q_OBJECT +public: + NameValidator(QObject *parent=nullptr); + QValidator::State validate(QString &input, int &pos) const override; +}; + +// Accepts comma-separated identifiers: \w+(,\w+)* +class NodeValidator : public QValidator { + Q_OBJECT +public: + NodeValidator(QObject *parent=nullptr); + QValidator::State validate(QString &input, int &pos) const override; +}; + +// Accepts one or more non-whitespace characters (\S+). +class NonWhitespaceValidator : public QValidator { + Q_OBJECT +public: + NonWhitespaceValidator(QObject *parent=nullptr); + QValidator::State validate(QString &input, int &pos) const override; +}; + +// Accepts a dotted IPv4 address (0-255 per octet). +class IpAddressValidator : public QValidator { + Q_OBJECT +public: + IpAddressValidator(QObject *parent=nullptr); + QValidator::State validate(QString &input, int &pos) const override; +}; + +// C-locale floating-point validator (matches QString::toDouble). +class DoubleValidator : public QValidator { + Q_OBJECT +public: + DoubleValidator(QObject *parent = nullptr); + QValidator::State validate(QString &input, int &pos) const override; +}; + +namespace utils { + +QPixmap icon(const QString &id); +std::string homePath(); +std::filesystem::path configPath(); +bool getClipboardText(std::string *text); // false if no clipboard tool is available +bool setClipboardText(const std::string &text); +bool isDarkTheme(); +void setTheme(int theme); +QString formatSeconds(double sec, bool include_milliseconds = false, bool absolute_time = false); +inline void drawStaticText(QPainter *p, const QRect &r, const QStaticText &text) { + auto size = (r.size() - text.size()) / 2; + p->drawStaticText(r.left() + size.width(), r.top() + size.height(), text); +} +inline QString toHex(const std::vector &dat, char separator = '\0') { + static const char digits[] = "0123456789ABCDEF"; + QString hex; + hex.reserve(dat.size() * (separator ? 3 : 2)); + for (size_t i = 0; i < dat.size(); ++i) { + if (separator && i) hex += QLatin1Char(separator); + hex += QLatin1Char(digits[dat[i] >> 4]); + hex += QLatin1Char(digits[dat[i] & 0xf]); + } + return hex; +} + +// boundary conversions for the remaining Qt byte-array based state APIs +template +std::vector toBytes(const T &dat) { return {dat.begin(), dat.end()}; } +inline auto qbytes(const std::vector &dat) { + return decltype(QString().toUtf8())((const char *)dat.data(), (int)dat.size()); +} + +} + +class ToolButton : public QToolButton { + Q_OBJECT +public: + ToolButton(const QString &icon, const QString &tooltip = {}, QWidget *parent = nullptr) : QToolButton(parent) { + setIcon(icon); + setToolTip(tooltip); + setAutoRaise(true); + const int metric = QApplication::style()->pixelMetric(QStyle::PM_SmallIconSize); + setIconSize({metric, metric}); + theme = settings.theme; + connect(&settings, &Settings::changed, this, &ToolButton::updateIcon); + } + void setIcon(const QString &icon) { + icon_str = icon; + QToolButton::setIcon(utils::icon(icon_str)); + } + +private: + void updateIcon() { if (std::exchange(theme, settings.theme) != theme) setIcon(icon_str); } + QString icon_str; + int theme; +}; + +class TabBar : public QTabBar { + Q_OBJECT + +public: + TabBar(QWidget *parent) : QTabBar(parent) {} + int addTab(const QString &text); + +private: + void closeTabClicked(); +}; + +// Watches SIGINT/SIGTERM via a self-pipe and a dedicated waiter thread +// (no Qt notifiers/timers). Exit is marshaled onto the GUI thread. +class UnixSignalHandler { +public: + UnixSignalHandler(); + ~UnixSignalHandler(); + static void signalHandler(int s); + +private: + inline static int sig_fd[2] = {}; + std::atomic shutting_down{false}; + std::thread waiter; +}; + +int num_decimals(double num); +QString signalToolTip(const cabana::Signal *sig); +inline QString toHexString(int value) { return QString("0x%1").arg(QString::number(value, 16).toUpper(), 2, '0'); } +void initApp(int argc, char *argv[], bool disable_hidpi = true); +QPixmap bootstrapPixmap(const QString &id); diff --git a/tools/cabana/videowidget.cc b/openpilot/tools/cabana/videowidget.cc similarity index 83% rename from tools/cabana/videowidget.cc rename to openpilot/tools/cabana/videowidget.cc index 3d715b0319..67b89cb080 100644 --- a/tools/cabana/videowidget.cc +++ b/openpilot/tools/cabana/videowidget.cc @@ -1,6 +1,7 @@ #include "tools/cabana/videowidget.h" #include +#include #include #include @@ -9,20 +10,20 @@ #include #include #include -#include #include "tools/cabana/tools/routeinfo.h" const int MIN_VIDEO_HEIGHT = 100; const int THUMBNAIL_MARGIN = 3; +// Indexed by TimelineType: None, Engaged, AlertInfo, AlertWarning, AlertCritical, UserBookmark static const QColor timeline_colors[] = { - [(int)TimelineType::None] = QColor(111, 143, 175), - [(int)TimelineType::Engaged] = QColor(0, 163, 108), - [(int)TimelineType::UserFlag] = Qt::magenta, - [(int)TimelineType::AlertInfo] = Qt::green, - [(int)TimelineType::AlertWarning] = QColor(255, 195, 0), - [(int)TimelineType::AlertCritical] = QColor(199, 0, 57), + QColor(111, 143, 175), + QColor(0, 163, 108), + Qt::green, + QColor(255, 195, 0), + QColor(199, 0, 57), + Qt::magenta, }; static Replay *getReplay() { @@ -50,7 +51,7 @@ VideoWidget::VideoWidget(QWidget *parent) : QFrame(parent) { updatePlayBtnState(); setWhatsThis(tr(R"( Video
- + Timeline color @@ -64,7 +65,7 @@ VideoWidget::VideoWidget(QWidget *parent) : QFrame(parent) { Pause/Resume:  space  )").arg(timeline_colors[(int)TimelineType::None].name(), timeline_colors[(int)TimelineType::Engaged].name(), - timeline_colors[(int)TimelineType::UserFlag].name(), + timeline_colors[(int)TimelineType::UserBookmark].name(), timeline_colors[(int)TimelineType::AlertInfo].name(), timeline_colors[(int)TimelineType::AlertWarning].name(), timeline_colors[(int)TimelineType::AlertCritical].name())); @@ -134,7 +135,7 @@ void VideoWidget::createSpeedDropdown(QToolBar *toolbar) { QFont font = speed_btn->font(); font.setBold(true); speed_btn->setFont(font); - speed_btn->setMinimumWidth(speed_btn->fontMetrics().width("0.05x ") + style()->pixelMetric(QStyle::PM_MenuButtonIndicator)); + speed_btn->setMinimumWidth(speed_btn->fontMetrics().horizontalAdvance("0.05x ") + style()->pixelMetric(QStyle::PM_MenuButtonIndicator)); } QWidget *VideoWidget::createCameraWidget() { @@ -156,7 +157,7 @@ QWidget *VideoWidget::createCameraWidget() { slider->setTimeRange(can->minSeconds(), can->maxSeconds()); QObject::connect(slider, &QSlider::sliderReleased, [this]() { can->seekTo(slider->currentSecond()); }); - QObject::connect(can, &AbstractStream::paused, cam_widget, [c = cam_widget]() { c->showPausedOverlay(); }); + QObject::connect(can, &AbstractStream::paused, cam_widget, qOverload<>(&StreamCameraView::update)); QObject::connect(can, &AbstractStream::eventsMerged, this, [this]() { slider->update(); }); QObject::connect(cam_widget, &CameraWidget::clicked, []() { can->pause(!can->isPaused()); }); QObject::connect(cam_widget, &CameraWidget::vipcAvailableStreamsUpdated, this, &VideoWidget::vipcAvailableStreamsUpdated); @@ -202,7 +203,7 @@ void VideoWidget::timeRangeChanged() { QString VideoWidget::formatTime(double sec, bool include_milliseconds) { if (settings.absolute_time) - sec = can->beginDateTime().addMSecs(sec * 1000).toMSecsSinceEpoch() / 1000.0; + sec += std::chrono::duration(can->beginDateTime().time_since_epoch()).count(); return utils::formatSeconds(sec, include_milliseconds, settings.absolute_time); } @@ -261,14 +262,23 @@ void Slider::paintEvent(QPaintEvent *ev) { QStyleOptionSlider opt; initStyleOption(&opt); - QRect r = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderGroove, this); - p.fillRect(r, timeline_colors[(int)TimelineType::None]); + QRect handle_rect = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderHandle, this); + QRect groove_rect = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderGroove, this); + + // Adjust groove height to match handle height + int handle_height = handle_rect.height(); + groove_rect.setHeight(handle_height * 0.5); + groove_rect.moveCenter(QPoint(groove_rect.center().x(), rect().center().y())); + + p.fillRect(groove_rect, timeline_colors[(int)TimelineType::None]); double min = minimum() / factor; double max = maximum() / factor; auto fillRange = [&](double begin, double end, const QColor &color) { if (begin > max || end < min) return; + + QRect r = groove_rect; r.setLeft(((std::max(min, begin) - min) / (max - min)) * width()); r.setRight(((std::min(max, end) - min) / (max - min)) * width()); p.fillRect(r, color); @@ -314,34 +324,40 @@ void Slider::mousePressEvent(QMouseEvent *e) { // StreamCameraView StreamCameraView::StreamCameraView(std::string stream_name, VisionStreamType stream_type, QWidget *parent) : CameraWidget(stream_name, stream_type, parent) { - fade_animation = new QPropertyAnimation(this, "overlayOpacity"); - fade_animation->setDuration(500); - fade_animation->setStartValue(0.2f); - fade_animation->setEndValue(0.7f); - fade_animation->setEasingCurve(QEasingCurve::InOutQuad); - connect(fade_animation, &QPropertyAnimation::valueChanged, this, QOverload<>::of(&StreamCameraView::update)); } void StreamCameraView::parseQLog(std::shared_ptr qlog) { std::mutex mutex; - QtConcurrent::blockingMap(qlog->events.cbegin(), qlog->events.cend(), [this, &mutex](const Event &e) { - if (e.which == cereal::Event::Which::THUMBNAIL) { - capnp::FlatArrayMessageReader reader(e.data); - auto thumb_data = reader.getRoot().getThumbnail(); - auto image_data = thumb_data.getThumbnail(); - if (QPixmap thumb; thumb.loadFromData(image_data.begin(), image_data.size(), "jpeg")) { - QPixmap generated_thumb = generateThumbnail(thumb, can->toSeconds(thumb_data.getTimestampEof())); - std::lock_guard lock(mutex); - thumbnails[thumb_data.getTimestampEof()] = generated_thumb; - big_thumbnails[thumb_data.getTimestampEof()] = thumb; + const auto &events = qlog->events; + unsigned int num_threads = std::max(1u, std::thread::hardware_concurrency()); + size_t chunk = (events.size() + num_threads - 1) / num_threads; + std::vector threads; + for (unsigned int t = 0; t < num_threads && t * chunk < events.size(); ++t) { + size_t start = t * chunk; + size_t end = std::min(start + chunk, events.size()); + threads.emplace_back([this, &mutex, &events, start, end]() { + for (size_t i = start; i < end; ++i) { + const Event &e = events[i]; + if (e.which == cereal::Event::Which::THUMBNAIL) { + capnp::FlatArrayMessageReader reader(e.data); + auto thumb_data = reader.getRoot().getThumbnail(); + auto image_data = thumb_data.getThumbnail(); + if (QPixmap thumb; thumb.loadFromData(image_data.begin(), image_data.size(), "jpeg")) { + QPixmap generated_thumb = generateThumbnail(thumb, can->toSeconds(thumb_data.getTimestampEof())); + std::lock_guard lock(mutex); + thumbnails[thumb_data.getTimestampEof()] = generated_thumb; + big_thumbnails[thumb_data.getTimestampEof()] = thumb; + } + } } - } - }); + }); + } + for (auto &th : threads) th.join(); update(); } -void StreamCameraView::paintGL() { - CameraWidget::paintGL(); +void StreamCameraView::paintEvent(QPaintEvent *event) { + CameraWidget::paintEvent(event); QPainter p(this); bool scrubbing = false; @@ -354,7 +370,7 @@ void StreamCameraView::paintGL() { } if (can->isPaused()) { - p.setPen(QColor(200, 200, 200, static_cast(255 * fade_animation->currentValue().toFloat()))); + p.setPen(QColor(200, 200, 200, static_cast(255 * 0.7f))); p.setFont(QFont(font().family(), 16, QFont::Bold)); p.drawText(rect(), Qt::AlignCenter, tr("PAUSED")); } @@ -374,9 +390,9 @@ QPixmap StreamCameraView::generateThumbnail(QPixmap thumb, double seconds) { void StreamCameraView::drawScrubThumbnail(QPainter &p) { p.fillRect(rect(), Qt::black); - auto it = big_thumbnails.lowerBound(can->toMonoTime(thumbnail_dispaly_time)); + auto it = big_thumbnails.lower_bound(can->toMonoTime(thumbnail_dispaly_time)); if (it != big_thumbnails.end()) { - QPixmap scaled_thumb = it.value().scaled(rect().size(), Qt::KeepAspectRatio, Qt::SmoothTransformation); + QPixmap scaled_thumb = it->second.scaled(rect().size(), Qt::KeepAspectRatio, Qt::SmoothTransformation); QRect thumb_rect(rect().center() - scaled_thumb.rect().center(), scaled_thumb.size()); p.drawPixmap(thumb_rect.topLeft(), scaled_thumb); drawTime(p, thumb_rect, thumbnail_dispaly_time); @@ -384,9 +400,9 @@ void StreamCameraView::drawScrubThumbnail(QPainter &p) { } void StreamCameraView::drawThumbnail(QPainter &p) { - auto it = thumbnails.lowerBound(can->toMonoTime(thumbnail_dispaly_time)); + auto it = thumbnails.lower_bound(can->toMonoTime(thumbnail_dispaly_time)); if (it != thumbnails.end()) { - const QPixmap &thumb = it.value(); + const QPixmap &thumb = it->second; auto [min_sec, max_sec] = can->timeRange().value_or(std::make_pair(can->minSeconds(), can->maxSeconds())); int pos = (thumbnail_dispaly_time - min_sec) * width() / (max_sec - min_sec); int x = std::clamp(pos - thumb.width() / 2, THUMBNAIL_MARGIN, width() - thumb.width() - THUMBNAIL_MARGIN + 1); diff --git a/tools/cabana/videowidget.h b/openpilot/tools/cabana/videowidget.h similarity index 88% rename from tools/cabana/videowidget.h rename to openpilot/tools/cabana/videowidget.h index 6f756448c0..09f7a9931b 100644 --- a/tools/cabana/videowidget.h +++ b/openpilot/tools/cabana/videowidget.h @@ -1,17 +1,17 @@ #pragma once +#include #include #include #include #include #include -#include #include #include #include -#include "selfdrive/ui/qt/widgets/cameraview.h" +#include "tools/cabana/cameraview.h" #include "tools/cabana/utils/util.h" #include "tools/replay/logreader.h" #include "tools/cabana/streams/replaystream.h" @@ -35,8 +35,7 @@ class StreamCameraView : public CameraWidget { public: StreamCameraView(std::string stream_name, VisionStreamType stream_type, QWidget *parent = nullptr); - void paintGL() override; - void showPausedOverlay() { fade_animation->start(); } + void paintEvent(QPaintEvent *event) override; void parseQLog(std::shared_ptr qlog); private: @@ -46,9 +45,8 @@ private: void drawScrubThumbnail(QPainter &p); void drawTime(QPainter &p, const QRect &rect, double seconds); - QPropertyAnimation *fade_animation; - QMap big_thumbnails; - QMap thumbnails; + std::map big_thumbnails; + std::map thumbnails; double thumbnail_dispaly_time = -1; friend class VideoWidget; }; diff --git a/openpilot/tools/camerastream/README.md b/openpilot/tools/camerastream/README.md new file mode 100644 index 0000000000..9671199297 --- /dev/null +++ b/openpilot/tools/camerastream/README.md @@ -0,0 +1,66 @@ +# Camera stream + +`compressed_vipc.py` connects to a remote device running openpilot, decodes the video streams, and republishes them over VisionIPC. + +## Usage + +### On the device +SSH into the device and run following in separate terminals: + +`cd /data/openpilot && ./openpilot/cereal/messaging/bridge` + +`cd /data/openpilot/system/loggerd && ./encoderd` + +`cd /data/openpilot/system/camerad && ./camerad` + +Note that both the device and your PC must be on the same openpilot commit. + +Alternatively paste this as a single command: +``` +( + cd /data/openpilot + ./openpilot/cereal/messaging/bridge & + + cd /data/openpilot/system/camerad/ + ./camerad & + + cd /data/openpilot/system/loggerd/ + ./encoderd & + + wait +) ; trap 'kill $(jobs -p)' SIGINT +``` +Ctrl+C will stop all three processes. + +### On the PC +Decode the stream with `compressed_vipc.py`: + +```cd ~/openpilot/tools/camerastream && ./compressed_vipc.py ``` + +To actually display the stream, run `watch3` in separate terminal: + +```cd ~/openpilot/selfdrive/ui/ && ./watch3.py``` + +## compressed_vipc.py usage +``` +$ python3 compressed_vipc.py -h +usage: compressed_vipc.py [-h] [--cams CAMS] [--server SERVER] [--silent] addr + +Decode video streams and broadcast on VisionIPC + +positional arguments: + addr Address of comma three + +options: + -h, --help show this help message and exit + --cams CAMS Cameras to decode + --server SERVER choose vipc server name + --silent Suppress debug output +``` + + +## Example: +``` +cd ~/openpilot/tools/camerastream && ./compressed_vipc.py comma-ffffffff --cams 0 +cd ~/openpilot/selfdrive/ui/ && ./watch3.py +``` diff --git a/openpilot/tools/camerastream/compressed_vipc.py b/openpilot/tools/camerastream/compressed_vipc.py new file mode 100755 index 0000000000..56ed12889f --- /dev/null +++ b/openpilot/tools/camerastream/compressed_vipc.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python3 +import os +import argparse +import multiprocessing +import time +import signal +from collections import deque + + +import openpilot.cereal.messaging as messaging +from msgq.visionipc import VisionIpcServer, VisionStreamType +from openpilot.tools.camerastream.ffmpeg_decoder import Decoder, FFmpegError + +V4L2_BUF_FLAG_KEYFRAME = 8 + +# start encoderd +# also start cereal messaging bridge +# then run this "./compressed_vipc.py " + +ENCODE_SOCKETS = { + VisionStreamType.VISION_STREAM_ROAD: "roadEncodeData", + VisionStreamType.VISION_STREAM_DRIVER: "driverEncodeData", + VisionStreamType.VISION_STREAM_WIDE_ROAD: "wideRoadEncodeData", +} + +def decoder(addr, vipc_server, vst, W, H, debug=False): + sock_name = ENCODE_SOCKETS[vst] + if debug: + print(f"start decoder for {sock_name}, {W}x{H}") + + codec = Decoder("hevc") + + os.environ["ZMQ"] = "1" + messaging.reset_context() + sock = messaging.sub_sock(sock_name, None, addr=addr, conflate=False) + cnt = 0 + last_idx = -1 + seen_iframe = False + + time_q = deque() + + def resync(): + nonlocal seen_iframe + codec.reset() + seen_iframe = False + time_q.clear() + + while 1: + msgs = messaging.drain_sock(sock, wait_for_one=True) + for evt in msgs: + evta = getattr(evt, evt.which()) + if last_idx != -1 and evta.idx.encodeId != (last_idx + 1): + if debug: + print("DROP PACKET!") + resync() + last_idx = evta.idx.encodeId + if not seen_iframe and not (evta.idx.flags & V4L2_BUF_FLAG_KEYFRAME): + if debug: + print("waiting for iframe") + continue + time_q.append(time.monotonic()) + network_latency = (int(time.time()*1e9) - evta.unixTimestampNanos)/1e6 # noqa: TID251 + frame_latency = ((evta.idx.timestampEof/1e9) - (evta.idx.timestampSof/1e9))*1000 + process_latency = ((evt.logMonoTime/1e9) - (evta.idx.timestampEof/1e9))*1000 + + # put in header (first) — VPS/SPS/PPS only, no frame expected + if not seen_iframe: + try: + codec.decode(evta.header) + except FFmpegError as e: + if debug: + print(f"HEADER ERROR: {e}") + resync() + continue + seen_iframe = True + + try: + img_yuv = codec.decode(evta.data) + except FFmpegError as e: + if debug: + print(f"DECODE ERROR: {e}") + resync() + continue + + if img_yuv is None: + if debug: + print("DROP SURFACE") + continue + + if codec.width != W or codec.height != H: + if debug: + print(f"DECODE ERROR: decoded frame is {codec.width}x{codec.height}, expected {W}x{H}") + resync() + continue + + frame_start_time = time_q.popleft() + vipc_server.send(vst, img_yuv.data, cnt, int(frame_start_time*1e9), int(time.monotonic()*1e9)) + cnt += 1 + + pc_latency = (time.monotonic()-frame_start_time)*1000 + if debug: + print(f"{len(msgs):2d} {evta.idx.encodeId:4d} {evt.logMonoTime/1e9:.3f} {evta.idx.timestampEof/1e6:.3f} \ + roll {frame_latency:6.2f} ms latency {process_latency:6.2f} ms + {network_latency:6.2f} ms + {pc_latency:6.2f} ms \ + = {process_latency+network_latency+pc_latency:6.2f} ms", len(evta.data), sock_name) + +class CompressedVipc: + def __init__(self, addr, vision_streams, server_name, debug=False): + print("getting frame sizes") + os.environ["ZMQ"] = "1" + messaging.reset_context() + sm = messaging.SubMaster([ENCODE_SOCKETS[s] for s in vision_streams], addr=addr) + while min(sm.recv_frame.values()) == 0: + sm.update(100) + os.environ.pop("ZMQ") + messaging.reset_context() + + self.vipc_server = VisionIpcServer(server_name) + for vst in vision_streams: + ed = sm[ENCODE_SOCKETS[vst]] + self.vipc_server.create_buffers(vst, 4, ed.width, ed.height) + self.vipc_server.start_listener() + + self.procs = [] + for vst in vision_streams: + ed = sm[ENCODE_SOCKETS[vst]] + p = multiprocessing.Process(target=decoder, args=(addr, self.vipc_server, vst, ed.width, ed.height, debug)) + p.start() + self.procs.append(p) + + def join(self): + for p in self.procs: + p.join() + + def kill(self): + for p in self.procs: + p.terminate() + self.join() + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Decode video streams and broadcast on VisionIPC") + parser.add_argument("addr", help="Address of comma three") + parser.add_argument("--cams", default="0,1,2", help="Cameras to decode") + parser.add_argument("--server", default="camerad", help="choose vipc server name") + parser.add_argument("--silent", action="store_true", help="Suppress debug output") + args = parser.parse_args() + + vision_streams = [ + VisionStreamType.VISION_STREAM_ROAD, + VisionStreamType.VISION_STREAM_DRIVER, + VisionStreamType.VISION_STREAM_WIDE_ROAD, + ] + + vsts = [vision_streams[int(x)] for x in args.cams.split(",")] + cvipc = CompressedVipc(args.addr, vsts, args.server, debug=(not args.silent)) + + # register exit handler + signal.signal(signal.SIGINT, lambda sig, frame: cvipc.kill()) + + cvipc.join() diff --git a/openpilot/tools/camerastream/ffmpeg_decoder.py b/openpilot/tools/camerastream/ffmpeg_decoder.py new file mode 100644 index 0000000000..13cdc12df1 --- /dev/null +++ b/openpilot/tools/camerastream/ffmpeg_decoder.py @@ -0,0 +1,261 @@ +import ctypes +import errno +import os + +import ffmpeg +import numpy as np + + +AV_INPUT_BUFFER_PADDING_SIZE = 64 +AV_LOG_QUIET = -8 +SWS_FAST_BILINEAR = 1 + + +class FFmpegError(RuntimeError): + pass + + +class AVPacket(ctypes.Structure): + # Public prefix of AVPacket. Only data and size are modified here; the packet + # remains non-refcounted and points at Decoder._packet_buffer. + _fields_ = [ + ("buf", ctypes.c_void_p), + ("pts", ctypes.c_int64), + ("dts", ctypes.c_int64), + ("data", ctypes.POINTER(ctypes.c_uint8)), + ("size", ctypes.c_int), + ] + + +class AVFrame(ctypes.Structure): + # Public prefix of AVFrame through format. Stable within a libavutil major + _fields_ = [ + ("data", ctypes.POINTER(ctypes.c_uint8) * 8), + ("linesize", ctypes.c_int * 8), + ("extended_data", ctypes.POINTER(ctypes.POINTER(ctypes.c_uint8))), + ("width", ctypes.c_int), + ("height", ctypes.c_int), + ("nb_samples", ctypes.c_int), + ("format", ctypes.c_int), + ] + + +def _bind(fn, restype, *argtypes): + fn.restype = restype + fn.argtypes = list(argtypes) + return fn + + +def _load_libraries(): + avutil = ctypes.CDLL(os.path.join(ffmpeg.LIB_DIR, "libavutil.so.59"), mode=ctypes.RTLD_GLOBAL) + avcodec = ctypes.CDLL(os.path.join(ffmpeg.LIB_DIR, "libavcodec.so.61"), mode=ctypes.RTLD_GLOBAL) + swscale = ctypes.CDLL(os.path.join(ffmpeg.LIB_DIR, "libswscale.so.8"), mode=ctypes.RTLD_GLOBAL) + + c_int, c_char_p, c_void_p, c_size_t = ctypes.c_int, ctypes.c_char_p, ctypes.c_void_p, ctypes.c_size_t + c_uint8_p = ctypes.POINTER(ctypes.c_uint8) + c_void_p_p = ctypes.POINTER(c_void_p) + + _bind(avutil.av_log_set_level, None, c_int) + _bind(avutil.av_opt_set, c_int, c_void_p, c_char_p, c_char_p, c_int) + _bind(avutil.av_strerror, c_int, c_int, c_char_p, c_size_t) + _bind(avutil.av_get_pix_fmt, c_int, c_char_p) + + _bind(avcodec.avcodec_find_decoder_by_name, c_void_p, c_char_p) + _bind(avcodec.avcodec_alloc_context3, c_void_p, c_void_p) + _bind(avcodec.avcodec_open2, c_int, c_void_p, c_void_p, c_void_p) + _bind(avcodec.avcodec_free_context, None, c_void_p_p) + _bind(avcodec.avcodec_flush_buffers, None, c_void_p) + _bind(avcodec.avcodec_send_packet, c_int, c_void_p, ctypes.POINTER(AVPacket)) + _bind(avcodec.avcodec_receive_frame, c_int, c_void_p, ctypes.POINTER(AVFrame)) + _bind(avcodec.av_packet_alloc, ctypes.POINTER(AVPacket)) + _bind(avcodec.av_packet_free, None, ctypes.POINTER(ctypes.POINTER(AVPacket))) + _bind(avcodec.av_frame_alloc, ctypes.POINTER(AVFrame)) + _bind(avcodec.av_frame_free, None, ctypes.POINTER(ctypes.POINTER(AVFrame))) + _bind(avcodec.av_frame_unref, None, ctypes.POINTER(AVFrame)) + + _bind(swscale.sws_getCachedContext, c_void_p, + c_void_p, c_int, c_int, c_int, c_int, c_int, c_int, c_int, c_void_p, c_void_p, c_void_p) + _bind(swscale.sws_scale, c_int, + c_void_p, ctypes.POINTER(c_uint8_p), ctypes.POINTER(c_int), + c_int, c_int, ctypes.POINTER(c_uint8_p), ctypes.POINTER(c_int)) + _bind(swscale.sws_freeContext, None, c_void_p) + + avutil.av_log_set_level(AV_LOG_QUIET) + return avutil, avcodec, swscale +_avutil, _avcodec, _swscale = _load_libraries() + +_DataArray = ctypes.POINTER(ctypes.c_uint8) * 4 +_LinesizeArray = ctypes.c_int * 4 + +AV_PIX_FMT_NV12 = _avutil.av_get_pix_fmt(b"nv12") +assert AV_PIX_FMT_NV12 >= 0 + + +def _error_string(code: int) -> str: + buf = ctypes.create_string_buffer(256) + if _avutil.av_strerror(code, buf, len(buf)) == 0: + return buf.value.decode(errors="replace") + return f"FFmpeg error {code}" + + +def _check(code: int, operation: str) -> None: + if code < 0: + raise FFmpegError(f"{operation}: {_error_string(code)}") + + +class Decoder: + def __init__(self, codec_name: str = "hevc"): + self.closed = True + self._sws_context = ctypes.c_void_p() + self._packet_buffer = bytearray() + self._packet_address = 0 + self._packet_data = None + self._output = np.empty(0, dtype=np.uint8) + self._dst_data = _DataArray() + self._dst_linesize = _LinesizeArray() + self.width = 0 + self.height = 0 + self._src_format = -1 + + codec = _avcodec.avcodec_find_decoder_by_name(codec_name.encode()) + if not codec: + raise FFmpegError(f"decoder not found: {codec_name}") + + self._context = ctypes.c_void_p(_avcodec.avcodec_alloc_context3(codec)) + if not self._context: + raise MemoryError("avcodec_alloc_context3 failed") + + self._packet = _avcodec.av_packet_alloc() + if not self._packet: + _avcodec.avcodec_free_context(ctypes.byref(self._context)) + raise MemoryError("av_packet_alloc failed") + + self._frame = _avcodec.av_frame_alloc() + if not self._frame: + _avcodec.av_packet_free(ctypes.byref(self._packet)) + _avcodec.avcodec_free_context(ctypes.byref(self._context)) + raise MemoryError("av_frame_alloc failed") + + try: + # Frame threading holds decoded frames to populate worker pipelines. + # Slice threads can reduce decode time without adding that frame queue; + # four was the latency minimum on the replay camera workload. + _check(_avutil.av_opt_set(self._context, b"threads", b"4", 0), "set decoder threads") + _check(_avutil.av_opt_set(self._context, b"thread_type", b"slice", 0), "set decoder thread type") + _check(_avutil.av_opt_set(self._context, b"flags", b"+low_delay", 0), "set low-delay mode") + _check(_avcodec.avcodec_open2(self._context, codec, None), "open decoder") + except Exception: + _avcodec.av_frame_free(ctypes.byref(self._frame)) + _avcodec.av_packet_free(ctypes.byref(self._packet)) + _avcodec.avcodec_free_context(ctypes.byref(self._context)) + raise + + self.closed = False + + def __enter__(self): + self._ensure_open() + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.close() + + def _ensure_open(self) -> None: + if self.closed: + raise RuntimeError("decoder is closed") + + def _prepare_packet(self, data) -> None: + size = len(data) + required = size + AV_INPUT_BUFFER_PADDING_SIZE + if len(self._packet_buffer) < required: + # Grow-only; the address stays valid until the next reallocation. + self._packet_buffer = bytearray(required) + self._packet_address = ctypes.addressof(ctypes.c_uint8.from_buffer(self._packet_buffer)) + self._packet_data = ctypes.cast(self._packet_address, ctypes.POINTER(ctypes.c_uint8)) + + self._packet_buffer[:size] = data + ctypes.memset(self._packet_address + size, 0, AV_INPUT_BUFFER_PADDING_SIZE) + self._packet.contents.data = self._packet_data + self._packet.contents.size = size + + def _prepare_output(self, frame: AVFrame) -> None: + width, height, src_format = frame.width, frame.height, frame.format + if width <= 0 or height <= 0 or width % 2 or height % 2: + raise FFmpegError(f"unsupported frame dimensions: {width}x{height}") + if (width, height, src_format) == (self.width, self.height, self._src_format): + return + + sws_context = _swscale.sws_getCachedContext( + self._sws_context, width, height, src_format, + width, height, AV_PIX_FMT_NV12, SWS_FAST_BILINEAR, + None, None, None, + ) + if not sws_context: + raise FFmpegError("sws_getCachedContext failed") + self._sws_context = ctypes.c_void_p(sws_context) + + self.width, self.height = width, height + self._src_format = src_format + self._output = np.empty(width * height * 3 // 2, dtype=np.uint8) + output_address = self._output.ctypes.data + self._dst_data = _DataArray( + ctypes.cast(output_address, ctypes.POINTER(ctypes.c_uint8)), + ctypes.cast(output_address + width * height, ctypes.POINTER(ctypes.c_uint8)), + None, + None, + ) + self._dst_linesize = _LinesizeArray(width, width, 0, 0) + + def _receive(self) -> np.ndarray | None: + """Return one NV12 frame, or None if the decoder needs more input. + + The returned buffer is reused on the next successful decode; callers must + use or copy it before calling decode again. + """ + result = _avcodec.avcodec_receive_frame(self._context, self._frame) + if result == -errno.EAGAIN: + return None + _check(result, "receive decoded frame") + + try: + frame = self._frame.contents + self._prepare_output(frame) + rows = _swscale.sws_scale( + self._sws_context, frame.data, frame.linesize, 0, frame.height, + self._dst_data, self._dst_linesize, + ) + if rows != frame.height: + raise FFmpegError(f"convert decoded frame: produced {rows} of {frame.height} rows") + return self._output + finally: + _avcodec.av_frame_unref(self._frame) + + def decode(self, data) -> np.ndarray | None: + self._ensure_open() + if len(data) == 0: + return None + + self._prepare_packet(data) + result = _avcodec.avcodec_send_packet(self._context, self._packet) + # The packet buffer is ours, not FFmpeg's. Clear the borrowed pointer so + # packet teardown can never attempt to release it. + self._packet.contents.data = None + self._packet.contents.size = 0 + _check(result, "send packet to decoder") + return self._receive() + + def reset(self) -> None: + """Discard decoder state after a stream discontinuity.""" + self._ensure_open() + _avcodec.avcodec_flush_buffers(self._context) + + def close(self) -> None: + if self.closed: + return + self.closed = True + _swscale.sws_freeContext(self._sws_context) + _avcodec.av_frame_free(ctypes.byref(self._frame)) + _avcodec.av_packet_free(ctypes.byref(self._packet)) + _avcodec.avcodec_free_context(ctypes.byref(self._context)) + + def __del__(self): + self.close() diff --git a/openpilot/tools/clip/run.py b/openpilot/tools/clip/run.py new file mode 100755 index 0000000000..594383f7fd --- /dev/null +++ b/openpilot/tools/clip/run.py @@ -0,0 +1,374 @@ +#!/usr/bin/env python3 +import os +import sys +import time +import logging +import subprocess +import threading +import queue +import multiprocessing +import itertools +import numpy as np +import tqdm +from argparse import ArgumentParser +from collections.abc import Callable +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor, as_completed + +from openpilot.tools.lib.route import Route +from openpilot.tools.lib.logreader import LogReader +from openpilot.tools.lib.filereader import FileReader +from openpilot.tools.lib.framereader import FrameReader, ffprobe +from openpilot.selfdrive.test.process_replay.migration import migrate_all +from openpilot.common.prefix import OpenpilotPrefix +from openpilot.common.utils import Timer +from msgq.visionipc import VisionIpcServer, VisionStreamType + +FRAMERATE = 20 +DEMO_ROUTE, DEMO_START, DEMO_END = '5beb9b58bd12b691/0000010a--a51155e496', 90, 105 + +logger = logging.getLogger('clip') + + +def parse_args(): + parser = ArgumentParser(description="Direct clip renderer") + parser.add_argument("route", nargs="?", help="Route ID (dongle/route or dongle/route/start/end)") + parser.add_argument("-s", "--start", type=int, help="Start time in seconds") + parser.add_argument("-e", "--end", type=int, help="End time in seconds") + parser.add_argument("-o", "--output", default="output.mp4", help="Output file path") + parser.add_argument("-d", "--data-dir", help="Local directory with route data") + parser.add_argument("-t", "--title", help="Title overlay text") + parser.add_argument("-f", "--file-size", type=float, default=9.0, help="Target file size in MB") + parser.add_argument("-x", "--speed", type=int, default=1, help="Speed multiplier") + parser.add_argument("--demo", action="store_true", help="Use demo route with default timing") + parser.add_argument("--big", action="store_true", help="Use big UI (2160x1080)") + parser.add_argument("--qcam", action="store_true", help="Use qcamera instead of fcamera") + parser.add_argument("--windowed", action="store_true", help="Show window") + parser.add_argument("--no-metadata", action="store_true", help="Disable metadata overlay") + parser.add_argument("--no-time-overlay", action="store_true", help="Disable time overlay") + args = parser.parse_args() + + if args.demo: + args.route, args.start, args.end = args.route or DEMO_ROUTE, args.start or DEMO_START, args.end or DEMO_END + elif not args.route: + parser.error("route is required (or use --demo)") + + if args.route and args.route.count('/') == 3: + parts = args.route.split('/') + args.route, args.start, args.end = '/'.join(parts[:2]), args.start or int(parts[2]), args.end or int(parts[3]) + + if args.start is None or args.end is None: + parser.error("--start and --end are required") + if args.end <= args.start: + parser.error(f"end ({args.end}) must be greater than start ({args.start})") + return args + + +def setup_env(output_path: str, big: bool = False, speed: int = 1, target_mb: float = 0, duration: int = 0, headless: bool = True): + os.environ.update({"RECORD": "1", "RECORD_OUTPUT": str(Path(output_path).with_suffix(".mp4"))}) + if headless: + os.environ["OFFSCREEN"] = "1" + if speed > 1: + os.environ["RECORD_SPEED"] = str(speed) + if target_mb > 0 and duration > 0: + os.environ["RECORD_BITRATE"] = f"{int(target_mb * 8 * 1024 / (duration / speed))}k" + if big: + os.environ["BIG"] = "1" + + +def _download_segment(path: str) -> bytes: + with FileReader(path) as f: + return bytes(f.read()) + + +def _parse_and_chunk_segment(args: tuple) -> list[dict]: + raw_data, fps = args + from openpilot.tools.lib.logreader import _LogFileReader + messages = migrate_all(list(_LogFileReader("", dat=raw_data, sort_by_time=True))) + if not messages: + return [] + + dt_ns, chunks, current, next_time = 1e9 / fps, [], {}, messages[0].logMonoTime + 1e9 / fps + for msg in messages: + if msg.logMonoTime >= next_time: + chunks.append(current) + current, next_time = {}, next_time + dt_ns * ((msg.logMonoTime - next_time) // dt_ns + 1) + current[msg.which()] = msg + return chunks + [current] if current else chunks + + +def load_logs_parallel(log_paths: list[str], fps: int = 20) -> list[dict]: + num_workers = min(16, len(log_paths), (multiprocessing.cpu_count() or 1)) + logger.info(f"Downloading {len(log_paths)} segments with {num_workers} workers...") + + with ThreadPoolExecutor(max_workers=num_workers) as pool: + futures = {pool.submit(_download_segment, path): idx for idx, path in enumerate(log_paths)} + raw_data = {futures[f]: f.result() for f in as_completed(futures)} + + logger.info("Parsing and chunking segments...") + with multiprocessing.Pool(num_workers) as pool: + return list(itertools.chain.from_iterable(pool.map(_parse_and_chunk_segment, [(raw_data[i], fps) for i in range(len(log_paths))]))) + + +def patch_submaster(message_chunks, ui_state): + # Reset started_frame so alerts render correctly (recv_frame must be >= started_frame) + ui_state.started_frame = 0 + ui_state.started_time = time.monotonic() + + def mock_update(timeout=None): + sm, t = ui_state.sm, time.monotonic() + sm.updated = dict.fromkeys(sm.services, False) + if sm.frame < len(message_chunks): + for svc, msg in message_chunks[sm.frame].items(): + if svc in sm.data: + sm.seen[svc] = sm.updated[svc] = sm.alive[svc] = sm.valid[svc] = True + sm.data[svc] = getattr(msg.as_builder(), svc) + sm.logMonoTime[svc], sm.recv_time[svc], sm.recv_frame[svc] = msg.logMonoTime, t, sm.frame + sm.frame += 1 + ui_state.sm.update = mock_update + + +def get_frame_dimensions(camera_path: str) -> tuple[int, int]: + """Get frame dimensions from a video file using ffprobe.""" + probe = ffprobe(camera_path) + stream = probe["streams"][0] + return stream["width"], stream["height"] + + +def iter_segment_frames(camera_paths, start_time, end_time, fps=20, use_qcam=False, frame_size: tuple[int, int] | None = None): + frames_per_seg = fps * 60 + start_frame, end_frame = int(start_time * fps), int(end_time * fps) + current_seg: int = -1 + get_frame: Callable[[int], np.ndarray] | None = None + + for global_idx in range(start_frame, end_frame): + seg_idx, local_idx = global_idx // frames_per_seg, global_idx % frames_per_seg + + if seg_idx != current_seg: + current_seg = seg_idx + path = camera_paths[seg_idx] if seg_idx < len(camera_paths) else None + if not path: + raise RuntimeError(f"No camera file for segment {seg_idx}") + + if use_qcam: + w, h = frame_size or get_frame_dimensions(path) + with FileReader(path) as f: + result = subprocess.run(["ffmpeg", "-v", "quiet", "-i", "-", "-f", "rawvideo", "-pix_fmt", "nv12", "-"], + input=f.read(), capture_output=True) + if result.returncode != 0: + raise RuntimeError(f"ffmpeg failed: {result.stderr.decode()}") + seg_frames = np.frombuffer(result.stdout, dtype=np.uint8).reshape(-1, w * h * 3 // 2) + get_frame = seg_frames.__getitem__ + else: + get_frame = FrameReader(path, pix_fmt="nv12").get + + assert get_frame is not None + yield global_idx, get_frame(local_idx) + + +class FrameQueue: + def __init__(self, camera_paths, start_time, end_time, fps=20, prefetch_count=60, use_qcam=False): + # Probe first valid camera file for dimensions + first_path = next((p for p in camera_paths if p), None) + if not first_path: + raise RuntimeError("No valid camera paths") + self.frame_w, self.frame_h = get_frame_dimensions(first_path) + + self._queue, self._stop, self._error = queue.Queue(maxsize=prefetch_count), threading.Event(), None + self._thread = threading.Thread(target=self._worker, + args=(camera_paths, start_time, end_time, fps, use_qcam, (self.frame_w, self.frame_h)), daemon=True) + self._thread.start() + + def _worker(self, camera_paths, start_time, end_time, fps, use_qcam, frame_size): + try: + for idx, data in iter_segment_frames(camera_paths, start_time, end_time, fps, use_qcam, frame_size): + if self._stop.is_set(): + break + self._queue.put((idx, data.tobytes())) + except Exception as e: + logger.exception("Decode error") + self._error = e + finally: + self._queue.put(None) + + def get(self, timeout=60.0): + if self._error: + raise self._error + result = self._queue.get(timeout=timeout) + if result is None: + raise StopIteration("No more frames") + return result + + def stop(self): + self._stop.set() + while not self._queue.empty(): + try: + self._queue.get_nowait() + except queue.Empty: + break + self._thread.join(timeout=2.0) + + +def load_route_metadata(route): + from openpilot.common.params import Params, UnknownKeyName + path = next((item for item in route.log_paths() if item), None) + if not path: + raise Exception('error getting route metadata: cannot find any uploaded logs') + lr = LogReader(path) + init_data, car_params = lr.first('initData'), lr.first('carParams') + + params = Params() + for entry in init_data.params.entries: + try: + params.put(entry.key, params.cpp2python(entry.key, entry.value), block=True) + except UnknownKeyName: + pass + + origin = init_data.gitRemote.split('/')[3] if len(init_data.gitRemote.split('/')) > 3 else 'unknown' + return { + 'version': init_data.version, 'route': route.name.canonical_name, + 'car': car_params.carFingerprint if car_params else 'unknown', 'origin': origin, + 'branch': init_data.gitBranch, 'commit': init_data.gitCommit[:7], 'modified': str(init_data.dirty).lower(), + } + + +def draw_text_box(text, x, y, size, gui_app, font, color=None, center=False): + import pyray as rl + from openpilot.system.ui.lib.text_measure import measure_text_cached + box_color, text_color = rl.Color(0, 0, 0, 85), color or rl.WHITE + text_size = measure_text_cached(font, text, size) + text_width, text_height = int(text_size.x), int(text_size.y) + if center: + x = (gui_app.width - text_width) // 2 + rl.draw_rectangle(x - 8, y - 4, text_width + 16, text_height + 8, box_color) + rl.draw_text_ex(font, text, rl.Vector2(x, y), size, 0, text_color) + + +def render_overlays(gui_app, font, big, metadata, title, start_time, frame_idx, show_metadata, show_time): + from openpilot.system.ui.lib.text_measure import measure_text_cached + from openpilot.system.ui.lib.wrap_text import wrap_text + metadata_size = 16 if big else 12 + title_size = 32 if big else 24 + time_size = 24 if big else 16 + + # Time overlay + time_width = 0 + if show_time: + t = start_time + frame_idx / FRAMERATE + time_text = f"{int(t) // 60:02d}:{int(t) % 60:02d}" + time_width = int(measure_text_cached(font, time_text, time_size).x) + draw_text_box(time_text, gui_app.width - time_width - 5, 0, time_size, gui_app, font) + + # Metadata overlay (first 5 seconds) + if show_metadata and metadata and frame_idx < FRAMERATE * 5: + m = metadata + text = ", ".join([f"openpilot v{m['version']}", f"route: {m['route']}", f"car: {m['car']}", f"origin: {m['origin']}", + f"branch: {m['branch']}", f"commit: {m['commit']}", f"modified: {m['modified']}"]) + # Wrap text if too wide (leave margin on each side) + margin = 2 * (time_width + 10 if show_time else 20) # leave enough margin for time overlay + max_width = gui_app.width - margin + lines = wrap_text(font, text, metadata_size, max_width) + + # Draw wrapped metadata text + y_offset = 6 + for line in lines: + draw_text_box(line, 0, y_offset, metadata_size, gui_app, font, center=True) + line_height = int(measure_text_cached(font, line, metadata_size).y) + 4 + y_offset += line_height + + # Title overlay + if title: + draw_text_box(title, 0, 60, title_size, gui_app, font, center=True) + + +def clip(route: Route, output: str, start: int, end: int, headless: bool = True, big: bool = False, + title: str | None = None, show_metadata: bool = True, show_time: bool = True, use_qcam: bool = False): + timer, duration = Timer(), end - start + + import pyray as rl + if big: + from openpilot.selfdrive.ui.onroad.augmented_road_view import AugmentedRoadView + else: + from openpilot.selfdrive.ui.mici.onroad.augmented_road_view import AugmentedRoadView + from openpilot.selfdrive.ui.ui_state import ui_state + from openpilot.system.ui.lib.application import gui_app, FontWeight + timer.lap("import") + + logger.info(f"Clipping {route.name.canonical_name}, {start}s-{end}s ({duration}s)") + seg_start, seg_end = start // 60, (end - 1) // 60 + 1 + all_chunks = load_logs_parallel(route.log_paths()[seg_start:seg_end], fps=FRAMERATE) + timer.lap("logs") + + frame_start = (start - seg_start * 60) * FRAMERATE + message_chunks = all_chunks[frame_start:frame_start + duration * FRAMERATE] + if not message_chunks: + logger.error("No messages to render") + sys.exit(1) + + if headless: + rl.set_config_flags(rl.ConfigFlags.FLAG_WINDOW_HIDDEN) + + with OpenpilotPrefix(shared_download_cache=True): + metadata = load_route_metadata(route) if show_metadata else None + camera_paths = route.qcamera_paths() if use_qcam else route.camera_paths() + frame_queue = FrameQueue(camera_paths, start, end, fps=FRAMERATE, use_qcam=use_qcam) + + ecamera_paths = route.ecamera_paths() if not use_qcam else [] + wide_frame_queue: FrameQueue | None = None + if any(p for p in ecamera_paths[seg_start:seg_end] if p): + wide_frame_queue = FrameQueue(ecamera_paths, start, end, fps=FRAMERATE) + + vipc = VisionIpcServer("camerad") + vipc.create_buffers(VisionStreamType.VISION_STREAM_ROAD, 4, frame_queue.frame_w, frame_queue.frame_h) + if wide_frame_queue: + vipc.create_buffers(VisionStreamType.VISION_STREAM_WIDE_ROAD, 4, wide_frame_queue.frame_w, wide_frame_queue.frame_h) + vipc.start_listener() + + patch_submaster(message_chunks, ui_state) + gui_app.init_window("clip", fps=FRAMERATE) + + road_view = AugmentedRoadView() + road_view.set_rect(rl.Rectangle(0, 0, gui_app.width, gui_app.height)) + font = gui_app.font(FontWeight.NORMAL) + timer.lap("setup") + + frame_idx = 0 + with tqdm.tqdm(total=len(message_chunks), desc="Rendering", unit="frame") as pbar: + for should_render, _, _ in gui_app.render(): + if frame_idx >= len(message_chunks): + break + _, frame_bytes = frame_queue.get() + vipc.send(VisionStreamType.VISION_STREAM_ROAD, frame_bytes, frame_idx, int(frame_idx * 5e7), int(frame_idx * 5e7)) + if wide_frame_queue: + _, wide_bytes = wide_frame_queue.get() + vipc.send(VisionStreamType.VISION_STREAM_WIDE_ROAD, wide_bytes, frame_idx, int(frame_idx * 5e7), int(frame_idx * 5e7)) + ui_state.update() + if should_render: + road_view.render() + render_overlays(gui_app, font, big, metadata, title, start, frame_idx, show_metadata, show_time) + frame_idx += 1 + pbar.update(1) + timer.lap("render") + + frame_queue.stop() + if wide_frame_queue: + wide_frame_queue.stop() + gui_app.close() + timer.lap("ffmpeg") + + logger.info(f"Clip saved to: {Path(output).resolve()}") + logger.info(f"Generated {timer.fmt(duration)}") + + +def main(): + logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s\t%(message)s") + args = parse_args() + + headless = not args.windowed + setup_env(args.output, big=args.big, speed=args.speed, target_mb=args.file_size, duration=args.end - args.start, headless=headless) + clip(Route(args.route, data_dir=args.data_dir), args.output, args.start, args.end, headless, + args.big, args.title, not args.no_metadata, not args.no_time_overlay, args.qcam) + + +if __name__ == "__main__": + main() diff --git a/openpilot/tools/jotpluggler/.gitignore b/openpilot/tools/jotpluggler/.gitignore new file mode 100644 index 0000000000..5f5f9dbdec --- /dev/null +++ b/openpilot/tools/jotpluggler/.gitignore @@ -0,0 +1,10 @@ +__pycache__/ +jot_*.o +*.o +jotpluggler +car_fingerprint_to_dbc.h +generated_event_extractors.h +generated_dbcs/.stamp +generated_dbcs/*.dbc +layouts/.jotpluggler_autosave/ +reports/ diff --git a/openpilot/tools/jotpluggler/SConscript b/openpilot/tools/jotpluggler/SConscript new file mode 100644 index 0000000000..d5ebaffb98 --- /dev/null +++ b/openpilot/tools/jotpluggler/SConscript @@ -0,0 +1,114 @@ +import os +import subprocess +import bootstrap_icons +import imgui +import libusb +from opendbc import get_generated_dbcs +from opendbc.car import Bus +from opendbc.car.fingerprints import MIGRATION +from opendbc.car.values import PLATFORMS +from openpilot.common.basedir import BASEDIR + +Import('env', 'arch', 'common', 'messaging', 'visionipc', 'cereal', 'replay_lib', 'ffmpeg_libs') + +jot_env = env.Clone() +jot_env["LIBPATH"] += [imgui.MESA_DIR, libusb.LIB_DIR] +jot_env["CPPPATH"] += [imgui.INCLUDE_DIR, libusb.INCLUDE_DIR] +jot_env["CXXFLAGS"] += [ + "-DGLFW_INCLUDE_NONE", + '-DJOTP_REPO_ROOT=\'"%s"\'' % os.path.realpath(BASEDIR), + '-DBOOTSTRAP_ICONS_TTF=\'"%s"\'' % bootstrap_icons.TTF_PATH, +] + +def materialize_generated_dbcs(target, source, env): + out_dir = os.path.dirname(str(target[0])) + os.makedirs(out_dir, exist_ok=True) + + for name in os.listdir(out_dir): + if name.endswith('.dbc'): + os.unlink(os.path.join(out_dir, name)) + + for name, content in sorted(get_generated_dbcs().items()): + with open(os.path.join(out_dir, f"{name}.dbc"), "w") as f: + f.write(content) + + with open(str(target[0]), "w") as f: + f.write("ok\n") + + return None + +def write_car_fingerprint_to_dbc_header(target, source, env): + pairs = {} + + for name, platform in sorted(PLATFORMS.items()): + dbc = platform.config.dbc_dict.get(Bus.pt, "") + if not dbc and name.startswith("TESLA_"): + dbc = platform.config.dbc_dict.get(Bus.party, "") + if not dbc and name == "COMMA_BODY": + dbc = "comma_body" + if dbc and name != "MOCK": + pairs[name] = dbc + + for fingerprint, car in sorted(MIGRATION.items()): + dbc = pairs.get(str(car), "") + if dbc: + pairs[fingerprint] = dbc + + lines = [ + "#pragma once", + "", + "#include ", + "#include ", + "", + "inline constexpr std::pair kCarFingerprintToDbc[] = {", + ] + lines.extend(f' {{"{fingerprint}", "{dbc}"}},' for fingerprint, dbc in sorted(pairs.items())) + lines.extend([ + "};", + "", + "inline std::string_view dbc_for_car_fingerprint(std::string_view fingerprint) {", + " for (const auto &[car_fingerprint, dbc] : kCarFingerprintToDbc) {", + " if (car_fingerprint == fingerprint) return dbc;", + " }", + " return {};", + "}", + "", + ]) + + with open(str(target[0]), "w") as f: + f.write("\n".join(lines)) + + return None + +def generate_event_extractors(target, source, env): + subprocess.check_call([ + "python3", + "openpilot/tools/jotpluggler/generate_event_extractors.py", + os.path.realpath(BASEDIR), + str(target[0]), + ]) + return None + +generated_dbc_stamp = jot_env.Command(f"generated_dbcs/.stamp", [], materialize_generated_dbcs) +car_fingerprint_to_dbc = jot_env.Command("car_fingerprint_to_dbc.h", [], write_car_fingerprint_to_dbc_header) +event_extractors = jot_env.Command("generated_event_extractors.h", [ + "generate_event_extractors.py", + jot_env.Glob("#openpilot/cereal/*.capnp"), + jot_env.Glob("#openpilot/cereal/include/*.capnp"), + "#opendbc_repo/opendbc/car/car.capnp", + "#opendbc_repo/opendbc/car/include/c++.capnp", + ], + generate_event_extractors, +) + +libs = [replay_lib, common, messaging, visionipc, cereal, File(f"{imgui.LIB_DIR}/libimgui.a"), File(f"{imgui.LIB_DIR}/libglfw3.a")] + \ + ffmpeg_libs + ["bz2", "zstd", "m", "pthread", "usb-1.0"] +if arch == "Darwin": + jot_env["FRAMEWORKS"] = ["OpenGL", "Cocoa", "IOKit", "CoreFoundation", "CoreVideo", "CoreMedia", "VideoToolbox"] +else: + libs += ["GL", "dl"] + +program = jot_env.Program("jotpluggler", jot_env.Glob("*.cc"), LIBS=libs) +jot_env.Depends(program, generated_dbc_stamp) +jot_env.Depends(program, car_fingerprint_to_dbc) +jot_env.Depends(program, event_extractors) diff --git a/openpilot/tools/jotpluggler/app.cc b/openpilot/tools/jotpluggler/app.cc new file mode 100644 index 0000000000..e6ba696bae --- /dev/null +++ b/openpilot/tools/jotpluggler/app.cc @@ -0,0 +1,1907 @@ +#include "tools/jotpluggler/app.h" +#include "tools/jotpluggler/camera.h" +#include "tools/jotpluggler/common.h" +#include "tools/jotpluggler/internal.h" +#include "tools/jotpluggler/map.h" +#include "tools/jotpluggler/thumbnail.h" +#include "common/hardware/hw.h" +#include "imgui_impl_glfw.h" + +#include "imgui_internal.h" +#include "imgui_impl_opengl3.h" +#include "imgui_impl_opengl3_loader.h" +#include "implot.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "json11/json11.hpp" + +namespace fs = std::filesystem; + +constexpr const char *UNTITLED_PANE_TITLE = "..."; +ImFont *g_ui_font = nullptr; +ImFont *g_ui_bold_font = nullptr; +ImFont *g_mono_font = nullptr; + +std::string layout_name_from_arg(const std::string &layout_arg) { + const fs::path raw(layout_arg); + if (raw.extension() == ".xml" || raw.extension() == ".json") { + return raw.stem().string(); + } + if (raw.filename() != raw) { + return raw.filename().replace_extension("").string(); + } + fs::path stem_path = raw; + return stem_path.replace_extension("").string(); +} + +fs::path layouts_dir() { + return repo_root() / "openpilot" / "tools" / "jotpluggler" / "layouts"; +} + +std::string sanitize_layout_stem(std::string_view name) { + std::string out; + out.reserve(name.size()); + bool last_was_dash = false; + for (const char raw : name) { + const unsigned char c = static_cast(raw); + if (std::isalnum(c) != 0) { + out.push_back(static_cast(std::tolower(c))); + last_was_dash = false; + } else if (raw == '-' || raw == '_') { + out.push_back(raw); + last_was_dash = false; + } else if (!last_was_dash && !out.empty()) { + out.push_back('-'); + last_was_dash = true; + } + } + while (!out.empty() && out.back() == '-') { + out.pop_back(); + } + return out.empty() ? "untitled" : out; +} + +fs::path autosave_dir() { + return layouts_dir() / ".jotpluggler_autosave"; +} + +fs::path resolve_layout_path(const std::string &layout_arg) { + const fs::path direct(layout_arg); + if (fs::exists(direct)) { + if (direct.extension() == ".json") return fs::absolute(direct); + const fs::path sibling_json = direct.parent_path() / (direct.stem().string() + ".json"); + if (direct.extension() == ".xml" && fs::exists(sibling_json)) { + return fs::absolute(sibling_json); + } + } + const fs::path candidate = layouts_dir() / (layout_name_from_arg(layout_arg) + ".json"); + if (!fs::exists(candidate)) throw std::runtime_error("Unknown layout: " + layout_arg); + return candidate; +} + +fs::path autosave_path_for_layout(const fs::path &layout_path) { + const std::string stem = layout_path.empty() ? "untitled" : layout_path.stem().string(); + return autosave_dir() / (sanitize_layout_stem(stem) + ".json"); +} + +std::vector available_layout_names() { + std::vector names; + const fs::path root = layouts_dir(); + if (!fs::exists(root) || !fs::is_directory(root)) { + return names; + } + for (const auto &entry : fs::directory_iterator(root)) { + if (!entry.is_regular_file() || entry.path().extension() != ".json") { + continue; + } + names.push_back(entry.path().stem().string()); + } + std::sort(names.begin(), names.end()); + return names; +} + +void refresh_replaced_layout_ui(AppSession *session, UiState *state, bool mark_docks) { + state->tabs.clear(); + cancel_rename_tab(state); + sync_ui_state(state, session->layout); + sync_layout_buffers(state, *session); + if (mark_docks) { + mark_all_docks_dirty(state); + } +} + +void start_new_layout(AppSession *session, UiState *state, const std::string &status_text) { + session->layout = make_empty_layout(); + session->layout_path.clear(); + session->autosave_path.clear(); + state->undo.reset(session->layout); + state->layout_dirty = false; + state->status_text = status_text; + refresh_replaced_layout_ui(session, state, true); + reset_shared_range(state, *session); +} + +bool is_decoded_can_series_path(std::string_view path) { + const std::string value(path); + return util::starts_with(value, "/can/") || util::starts_with(value, "/sendcan/"); +} + +bool apply_route_can_decode_update(AppSession *session, UiState *state); + +void rebuild_series_lookup_preserving_formats(AppSession *session, + std::string_view updated_prefix, + bool refresh_updated_formats_only) { + const std::string prefix(updated_prefix); + if (!updated_prefix.empty()) { + for (auto it = session->route_data.series_formats.begin(); it != session->route_data.series_formats.end();) { + if (util::starts_with(it->first, prefix)) { + it = session->route_data.series_formats.erase(it); + } else { + ++it; + } + } + } + session->series_by_path.clear(); + session->series_by_path.reserve(session->route_data.series.size()); + for (RouteSeries &series : session->route_data.series) { + session->series_by_path.emplace(series.path, &series); + if (refresh_updated_formats_only) { + if (!updated_prefix.empty() && util::starts_with(series.path, prefix)) { + const bool enum_like = session->route_data.enum_info.find(series.path) != session->route_data.enum_info.end(); + session->route_data.series_formats[series.path] = compute_series_format(series.values, enum_like); + } + } else { + const bool enum_like = session->route_data.enum_info.find(series.path) != session->route_data.enum_info.end(); + session->route_data.series_formats[series.path] = compute_series_format(series.values, enum_like); + } + } +} + +bool apply_route_can_decode_update(AppSession *session, UiState *state) { + const std::string active_dbc_name = !session->dbc_override.empty() ? session->dbc_override : session->route_data.dbc_name; + if (!active_dbc_name.empty() && !load_dbc_by_name(active_dbc_name).has_value()) { + state->error_text = "DBC not found: " + active_dbc_name; + state->open_error_popup = true; + return false; + } + std::unordered_map can_enum_info; + std::vector can_series = decode_can_messages(session->route_data.can_messages, active_dbc_name, &can_enum_info); + + std::vector updated_series; + updated_series.reserve(session->route_data.series.size() + can_series.size()); + for (RouteSeries &series : session->route_data.series) { + if (!is_decoded_can_series_path(series.path)) { + updated_series.push_back(std::move(series)); + } + } + for (RouteSeries &series : can_series) { + updated_series.push_back(std::move(series)); + } + std::sort(updated_series.begin(), updated_series.end(), [](const RouteSeries &a, const RouteSeries &b) { + return a.path < b.path; + }); + + std::unordered_map updated_enum_info; + updated_enum_info.reserve(session->route_data.enum_info.size() + can_enum_info.size()); + for (auto &[path, info] : session->route_data.enum_info) { + if (!is_decoded_can_series_path(path)) { + updated_enum_info.emplace(path, std::move(info)); + } + } + for (auto &[path, info] : can_enum_info) { + updated_enum_info[path] = std::move(info); + } + + session->route_data.series = std::move(updated_series); + session->route_data.enum_info = std::move(updated_enum_info); + session->route_data.paths.clear(); + session->route_data.paths.reserve(session->route_data.series.size()); + for (const RouteSeries &series : session->route_data.series) { + session->route_data.paths.push_back(series.path); + } + std::sort(session->route_data.paths.begin(), session->route_data.paths.end()); + session->route_data.roots = collect_route_roots_for_paths(session->route_data.paths); + + rebuild_route_index(session); + rebuild_browser_nodes(session, state); + refresh_all_custom_curves(session, state); + sync_camera_feeds(session); + return true; +} + +void apply_dbc_override_change(AppSession *session, UiState *state, const std::string &dbc_override) { + session->dbc_override = dbc_override; + if (session->data_mode == SessionDataMode::Stream) { + start_stream_session(session, state, session->stream_source, session->stream_buffer_seconds, false); + } else if (!session->route_name.empty()) { + const bool ok = apply_route_can_decode_update(session, state); + if (ok) { + state->status_text = dbc_override.empty() ? "DBC auto-detect enabled" : "DBC set to " + dbc_override; + } else { + state->status_text = "Failed to apply DBC"; + } + } else if (dbc_override.empty()) { + state->status_text = "DBC auto-detect enabled"; + } else { + state->status_text = "DBC set to " + dbc_override; + } +} + +void configure_style() { + ImGui::StyleColorsLight(); + ImPlot::StyleColorsLight(); + + ImGuiIO &io = ImGui::GetIO(); + g_ui_font = nullptr; + g_ui_bold_font = nullptr; + g_mono_font = nullptr; + const fs::path fonts_dir = repo_root() / "openpilot" / "selfdrive" / "assets" / "fonts"; + ImFontConfig font_cfg; + font_cfg.OversampleH = 2; + font_cfg.OversampleV = 2; + font_cfg.RasterizerDensity = 1.0f; + icon_add_font(16.0f); + const auto add_font_with_icons = [&](const fs::path &path, float size) -> ImFont * { + ImFont *font = io.Fonts->AddFontFromFileTTF(path.c_str(), size, &font_cfg); + if (font != nullptr) { + icon_add_font(size, true, font); + } + return font; + }; + if (ImFont *font = add_font_with_icons(fonts_dir / "Inter-Regular.ttf", 16.0f); font != nullptr) { + g_ui_font = font; + io.FontDefault = font; + } + g_ui_bold_font = add_font_with_icons(fonts_dir / "Inter-SemiBold.ttf", 16.75f); + if (g_ui_font == nullptr) { + if (ImFont *font = add_font_with_icons(fonts_dir / "JetBrainsMono-Medium.ttf", 15.75f); font != nullptr) { + g_mono_font = font; + io.FontDefault = font; + } + } + if (g_mono_font == nullptr) { + g_mono_font = add_font_with_icons(fonts_dir / "JetBrainsMono-Medium.ttf", 15.75f); + } + if (g_ui_bold_font == nullptr) { + g_ui_bold_font = g_ui_font; + } + + ImGuiStyle &style = ImGui::GetStyle(); + style.WindowRounding = 0.0f; + style.ChildRounding = 0.0f; + style.PopupRounding = 0.0f; + style.FrameRounding = 2.0f; + style.ScrollbarRounding = 2.0f; + style.GrabRounding = 2.0f; + style.TabRounding = 0.0f; + style.WindowBorderSize = 1.0f; + style.ChildBorderSize = 1.0f; + style.FrameBorderSize = 1.0f; + style.WindowPadding = ImVec2(8.0f, 7.0f); + style.FramePadding = ImVec2(6.0f, 3.0f); + style.ItemSpacing = ImVec2(8.0f, 5.0f); + style.ItemInnerSpacing = ImVec2(6.0f, 3.0f); + struct ColorDef { ImGuiCol idx; int r, g, b; }; + constexpr ColorDef COLORS[] = { + {ImGuiCol_WindowBg, 250, 250, 251}, {ImGuiCol_ChildBg, 255, 255, 255}, + {ImGuiCol_Border, 194, 198, 204}, {ImGuiCol_TitleBg, 252, 252, 253}, + {ImGuiCol_TitleBgActive, 252, 252, 253}, {ImGuiCol_TitleBgCollapsed, 252, 252, 253}, + {ImGuiCol_Text, 74, 80, 88}, {ImGuiCol_TextDisabled, 108, 118, 128}, + {ImGuiCol_Button, 255, 255, 255}, {ImGuiCol_ButtonHovered, 246, 248, 250}, + {ImGuiCol_ButtonActive, 238, 240, 244}, {ImGuiCol_FrameBg, 255, 255, 255}, + {ImGuiCol_FrameBgHovered, 248, 249, 251}, {ImGuiCol_FrameBgActive, 241, 244, 248}, + {ImGuiCol_Header, 243, 245, 248}, {ImGuiCol_HeaderHovered, 237, 240, 244}, + {ImGuiCol_HeaderActive, 232, 236, 240}, {ImGuiCol_PopupBg, 248, 249, 251}, + {ImGuiCol_MenuBarBg, 232, 236, 241}, {ImGuiCol_Separator, 194, 198, 204}, + {ImGuiCol_ScrollbarBg, 240, 242, 245}, {ImGuiCol_ScrollbarGrab, 202, 207, 214}, + {ImGuiCol_ScrollbarGrabHovered, 180, 186, 194}, {ImGuiCol_ScrollbarGrabActive, 164, 171, 180}, + {ImGuiCol_Tab, 219, 224, 230}, {ImGuiCol_TabHovered, 232, 236, 241}, + {ImGuiCol_TabSelected, 250, 251, 253}, {ImGuiCol_TabSelectedOverline, 92, 109, 136}, + {ImGuiCol_TabDimmed, 213, 219, 226}, {ImGuiCol_TabDimmedSelected, 244, 247, 249}, + {ImGuiCol_TabDimmedSelectedOverline, 92, 109, 136}, {ImGuiCol_DockingEmptyBg, 244, 246, 248}, + }; + for (const auto &c : COLORS) { style.Colors[c.idx] = color_rgb(c.r, c.g, c.b); } + style.Colors[ImGuiCol_DockingPreview] = color_rgb(69, 115, 184, 0.22f); + + ImPlotStyle &plot_style = ImPlot::GetStyle(); + plot_style.PlotBorderSize = 1.0f; + plot_style.MinorAlpha = 0.65f; + plot_style.LegendPadding = ImVec2(6.0f, 5.0f); + plot_style.LegendInnerPadding = ImVec2(6.0f, 3.0f); + plot_style.LegendSpacing = ImVec2(7.0f, 2.0f); + plot_style.PlotPadding = ImVec2(4.0f, 8.0f); + plot_style.FitPadding = ImVec2(0.02f, static_cast(PLOT_Y_PADDING_FRACTION)); + + ImPlot::MapInputDefault(); + ImPlotInputMap &input_map = ImPlot::GetInputMap(); + input_map.Pan = ImGuiMouseButton_Right; + input_map.PanMod = ImGuiMod_None; + input_map.Select = ImGuiMouseButton_Left; + input_map.SelectCancel = ImGuiMouseButton_Right; + input_map.SelectMod = ImGuiMod_None; +} + +void app_push_mono_font() { + if (g_mono_font != nullptr) { + ImGui::PushFont(g_mono_font); + } +} + +void app_pop_mono_font() { + if (g_mono_font != nullptr) { + ImGui::PopFont(); + } +} + +void app_push_bold_font() { + if (g_ui_bold_font != nullptr) { + ImGui::PushFont(g_ui_bold_font); + } +} + +void app_pop_bold_font() { + if (g_ui_bold_font != nullptr) { + ImGui::PopFont(); + } +} + +UiMetrics compute_ui_metrics(const ImVec2 &size, float top_offset, float sidebar_width) { + UiMetrics ui; + ui.width = size.x; + ui.height = size.y; + ui.top_offset = top_offset; + ui.sidebar_width = sidebar_width <= 0.0f + ? 0.0f + : std::clamp(sidebar_width, SIDEBAR_MIN_WIDTH, std::min(SIDEBAR_MAX_WIDTH, size.x * 0.6f)); + ui.content_x = ui.sidebar_width; + ui.content_y = top_offset; + ui.content_w = std::max(1.0f, size.x - ui.content_x); + ui.content_h = std::max(1.0f, size.y - ui.content_y - STATUS_BAR_HEIGHT); + ui.status_bar_y = std::max(0.0f, size.y - STATUS_BAR_HEIGHT); + return ui; +} + +void sync_ui_state(UiState *state, const SketchLayout &layout) { + const bool initializing = state->tabs.empty(); + state->tabs.resize(layout.tabs.size()); + if (layout.tabs.empty()) { + state->active_tab_index = 0; + state->requested_tab_index = -1; + return; + } + if (initializing) { + state->active_tab_index = std::clamp(layout.current_tab_index, 0, static_cast(layout.tabs.size()) - 1); + state->requested_tab_index = state->active_tab_index; + } + state->active_tab_index = std::clamp(state->active_tab_index, 0, static_cast(layout.tabs.size()) - 1); + for (size_t i = 0; i < layout.tabs.size(); ++i) { + if (state->tabs[i].runtime_id == 0) { + state->tabs[i].runtime_id = state->next_tab_runtime_id++; + } + const int pane_count = static_cast(layout.tabs[i].panes.size()); + state->tabs[i].map_panes.resize(static_cast(std::max(0, pane_count))); + state->tabs[i].camera_panes.resize(static_cast(std::max(0, pane_count))); + state->tabs[i].active_pane_index = pane_count <= 0 + ? 0 + : std::clamp(state->tabs[i].active_pane_index, 0, pane_count - 1); + } +} + +void resize_tab_pane_state(TabUiState *tab_state, size_t pane_count) { + if (tab_state == nullptr) return; + tab_state->map_panes.resize(pane_count); + tab_state->camera_panes.resize(pane_count); +} + +void sync_route_buffers(UiState *state, const AppSession &session) { + state->route_buffer = session.route_name; + state->data_dir_buffer = session.data_dir; +} + +void sync_stream_buffers(UiState *state, const AppSession &session) { + state->stream_address_buffer = session.stream_source.address; + state->stream_source_kind = session.stream_source.kind; + state->stream_buffer_seconds = session.stream_buffer_seconds; +} + +fs::path default_layout_save_path(const AppSession &session) { + return session.layout_path.empty() ? layouts_dir() / "new-layout.json" : session.layout_path; +} + +void sync_layout_buffers(UiState *state, const AppSession &session) { + state->load_layout_buffer = session.layout_path.empty() ? std::string() : session.layout_path.string(); + state->save_layout_buffer = default_layout_save_path(session).string(); +} + +const WorkspaceTab *app_active_tab(const SketchLayout &layout, const UiState &state) { + if (layout.tabs.empty()) return nullptr; + const int index = std::clamp(state.active_tab_index, 0, static_cast(layout.tabs.size()) - 1); + return &layout.tabs[static_cast(index)]; +} + +WorkspaceTab *app_active_tab(SketchLayout *layout, const UiState &state) { + if (layout->tabs.empty()) return nullptr; + const int index = std::clamp(state.active_tab_index, 0, static_cast(layout->tabs.size()) - 1); + return &layout->tabs[static_cast(index)]; +} + +TabUiState *app_active_tab_state(UiState *state) { + if (state->tabs.empty()) return nullptr; + const int index = std::clamp(state->active_tab_index, 0, static_cast(state->tabs.size()) - 1); + return &state->tabs[static_cast(index)]; +} + +std::string pane_window_name(int tab_runtime_id, int pane_index, const Pane &pane) { + const char *title = pane.title.empty() ? UNTITLED_PANE_TITLE : pane.title.c_str(); + return util::string_format("%s###tab%d_pane%d", title, tab_runtime_id, pane_index); +} + +std::string tab_item_label(const WorkspaceTab &tab, int tab_runtime_id) { + return util::string_format("%s##workspace_tab_%d", tab.tab_name.c_str(), tab_runtime_id); +} + +void request_tab_selection(UiState *state, int tab_index) { + state->active_tab_index = tab_index; + state->requested_tab_index = tab_index; +} + +void begin_rename_tab(const SketchLayout &layout, UiState *state, int tab_index) { + if (tab_index < 0 || tab_index >= static_cast(layout.tabs.size())) { + return; + } + state->rename_tab_buffer = layout.tabs[static_cast(tab_index)].tab_name; + state->rename_tab_index = tab_index; + state->focus_rename_tab_input = true; + request_tab_selection(state, tab_index); +} + +void cancel_rename_tab(UiState *state) { + state->rename_tab_index = -1; + state->focus_rename_tab_input = false; +} + +ImGuiID dockspace_id_for_tab(int tab_runtime_id) { + return ImHashStr(util::string_format("jotpluggler_dockspace_%d", tab_runtime_id).c_str()); +} + +bool curve_has_local_samples(const Curve &curve) { + return curve.xs.size() > 1 && curve.xs.size() == curve.ys.size(); +} + +void mark_all_docks_dirty(UiState *state) { + for (TabUiState &tab_state : state->tabs) { + tab_state.dock_needs_build = true; + } +} + +void mark_tab_dock_dirty(UiState *state, int tab_index) { + if (tab_index >= 0 && tab_index < static_cast(state->tabs.size())) { + state->tabs[static_cast(tab_index)].dock_needs_build = true; + } +} + +void normalize_split_node(WorkspaceNode *node) { + if (node->is_pane) { + return; + } + for (WorkspaceNode &child : node->children) { + normalize_split_node(&child); + } + if (node->children.empty()) { + return; + } + if (node->children.size() == 1) { + *node = node->children.front(); + return; + } + if (node->sizes.size() != node->children.size()) { + node->sizes.assign(node->children.size(), 1.0f / static_cast(node->children.size())); + return; + } + float total = 0.0f; + for (float &size : node->sizes) { + size = std::max(size, 0.0f); + total += size; + } + if (total <= 0.0f) { + node->sizes.assign(node->children.size(), 1.0f / static_cast(node->children.size())); + return; + } + for (float &size : node->sizes) { + size /= total; + } +} + +void decrement_pane_indices(WorkspaceNode *node, int removed_index) { + if (node->is_pane) { + if (node->pane_index > removed_index) { + node->pane_index -= 1; + } + return; + } + for (WorkspaceNode &child : node->children) { + decrement_pane_indices(&child, removed_index); + } +} + +bool remove_pane_node(WorkspaceNode *node, int pane_index) { + if (node->is_pane) return node->pane_index == pane_index; + + for (size_t i = 0; i < node->children.size();) { + if (remove_pane_node(&node->children[i], pane_index)) { + node->children.erase(node->children.begin() + static_cast(i)); + if (i < node->sizes.size()) { + node->sizes.erase(node->sizes.begin() + static_cast(i)); + } + } else { + ++i; + } + } + + normalize_split_node(node); + return !node->is_pane && node->children.empty(); +} + +bool split_pane_node(WorkspaceNode *node, int target_pane_index, SplitOrientation orientation, + bool new_before, int new_pane_index) { + if (node->is_pane) { + if (node->pane_index != target_pane_index) return false; + WorkspaceNode existing_pane; + existing_pane.is_pane = true; + existing_pane.pane_index = target_pane_index; + + WorkspaceNode new_pane; + new_pane.is_pane = true; + new_pane.pane_index = new_pane_index; + + node->is_pane = false; + node->pane_index = -1; + node->orientation = orientation; + node->sizes = {0.5f, 0.5f}; + node->children.clear(); + if (new_before) { + node->children.push_back(std::move(new_pane)); + node->children.push_back(std::move(existing_pane)); + } else { + node->children.push_back(std::move(existing_pane)); + node->children.push_back(std::move(new_pane)); + } + return true; + } + + if (node->orientation == orientation) { + for (size_t i = 0; i < node->children.size(); ++i) { + WorkspaceNode &child = node->children[i]; + if (!child.is_pane || child.pane_index != target_pane_index) { + continue; + } + + WorkspaceNode new_pane; + new_pane.is_pane = true; + new_pane.pane_index = new_pane_index; + + const auto insert_it = node->children.begin() + static_cast(new_before ? i : i + 1); + node->children.insert(insert_it, std::move(new_pane)); + node->sizes.assign(node->children.size(), 1.0f / static_cast(node->children.size())); + return true; + } + } + + for (WorkspaceNode &child : node->children) { + if (split_pane_node(&child, target_pane_index, orientation, new_before, new_pane_index)) return true; + } + return false; +} + +Pane make_empty_pane(const std::string &title = UNTITLED_PANE_TITLE) { + Pane pane; + pane.title = title; + return pane; +} + +WorkspaceTab make_empty_tab(const std::string &tab_name) { + WorkspaceTab tab; + tab.tab_name = tab_name; + tab.panes.push_back(make_empty_pane()); + tab.root.is_pane = true; + tab.root.pane_index = 0; + return tab; +} + +SketchLayout make_empty_layout() { + SketchLayout layout; + layout.tabs.push_back(make_empty_tab("tab1")); + layout.current_tab_index = 0; + layout.roots.push_back("layout"); + return layout; +} + +bool tab_name_exists(const SketchLayout &layout, const std::string &name) { + return std::any_of(layout.tabs.begin(), layout.tabs.end(), [&](const WorkspaceTab &tab) { + return tab.tab_name == name; + }); +} + +std::string next_tab_name(const SketchLayout &layout, const std::string &base_name) { + if (base_name == "tab" || base_name == "tab1") { + int max_suffix = 0; + for (const WorkspaceTab &tab : layout.tabs) { + if (tab.tab_name.size() > 3 && util::starts_with(tab.tab_name, "tab")) { + const std::string suffix = tab.tab_name.substr(3); + if (!suffix.empty() && std::all_of(suffix.begin(), suffix.end(), ::isdigit)) { + max_suffix = std::max(max_suffix, std::stoi(suffix)); + } + } + } + return "tab" + std::to_string(std::max(1, max_suffix + 1)); + } + std::string base = base_name.empty() ? "tab" : base_name; + if (!tab_name_exists(layout, base)) return base; + for (int i = 2; i < 1000; ++i) { + const std::string candidate = base + " " + std::to_string(i); + if (!tab_name_exists(layout, candidate)) return candidate; + } + return base + " copy"; +} + +void clear_layout_autosave(const AppSession &session) { + if (!session.autosave_path.empty() && fs::exists(session.autosave_path)) { + fs::remove(session.autosave_path); + } +} + +bool autosave_layout(AppSession *session, UiState *state) { + try { + if (session->autosave_path.empty()) { + session->autosave_path = autosave_path_for_layout(session->layout_path); + } + session->layout.current_tab_index = state->active_tab_index; + save_layout_json(session->layout, session->autosave_path); + state->layout_dirty = true; + return true; + } catch (const std::exception &err) { + state->error_text = err.what(); + state->open_error_popup = true; + state->status_text = "Failed to save layout draft"; + return false; + } +} + +bool mark_layout_dirty(AppSession *session, UiState *state) { + return autosave_layout(session, state); +} + +bool active_tab_has_map_pane(const SketchLayout &layout) { + if (layout.tabs.empty()) { + return false; + } + const int tab_index = std::clamp(layout.current_tab_index, 0, static_cast(layout.tabs.size()) - 1); + const WorkspaceTab &tab = layout.tabs[static_cast(tab_index)]; + return std::any_of(tab.panes.begin(), tab.panes.end(), [](const Pane &pane) { + return pane_kind_is_special(pane.kind); + }); +} + +void draw_browser_special_item(const char *item_id, const char *label) { + const ImGuiStyle &style = ImGui::GetStyle(); + const ImVec2 row_size(std::max(1.0f, ImGui::GetContentRegionAvail().x), ImGui::GetFrameHeight()); + ImGui::PushID(item_id); + ImGui::InvisibleButton("##special_data_row", row_size); + const bool hovered = ImGui::IsItemHovered(); + const bool held = ImGui::IsItemActive(); + const ImRect rect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax()); + ImDrawList *draw_list = ImGui::GetWindowDrawList(); + if (hovered) { + const ImU32 bg = ImGui::GetColorU32(held ? ImGuiCol_HeaderActive : ImGuiCol_HeaderHovered); + draw_list->AddRectFilled(rect.Min, rect.Max, bg, 0.0f); + } + ImGui::RenderTextEllipsis(draw_list, + ImVec2(rect.Min.x + style.FramePadding.x, rect.Min.y + style.FramePadding.y), + ImVec2(rect.Max.x - style.FramePadding.x, rect.Max.y), + rect.Max.x - style.FramePadding.x, + label, + nullptr, + nullptr); + if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_SourceAllowNullID)) { + ImGui::SetDragDropPayload("JOTP_SPECIAL_ITEM", item_id, std::strlen(item_id) + 1); + ImGui::TextUnformatted(label); + ImGui::EndDragDropSource(); + } + ImGui::PopID(); +} + +std::array app_next_curve_color(const Pane &pane) { + static constexpr std::array, 10> PALETTE = {{ + {35, 107, 180}, + {220, 82, 52}, + {67, 160, 71}, + {243, 156, 18}, + {123, 97, 255}, + {0, 150, 136}, + {214, 48, 49}, + {52, 73, 94}, + {197, 90, 17}, + {96, 125, 139}, + }}; + return PALETTE[pane.curves.size() % PALETTE.size()]; +} + +void draw_sidebar(AppSession *session, const UiMetrics &ui, UiState *state, bool show_camera_feed) { + ImGui::SetNextWindowPos(ImVec2(0.0f, ui.top_offset)); + ImGui::SetNextWindowSize(ImVec2(ui.sidebar_width, std::max(1.0f, ui.height - ui.top_offset))); + ImGui::PushStyleColor(ImGuiCol_WindowBg, color_rgb(238, 240, 244)); + ImGui::PushStyleColor(ImGuiCol_Border, color_rgb(190, 197, 205)); + const ImGuiWindowFlags flags = ImGuiWindowFlags_NoDecoration | + ImGuiWindowFlags_NoMove | + ImGuiWindowFlags_NoResize | + ImGuiWindowFlags_NoSavedSettings; + if (ImGui::Begin("##sidebar", nullptr, flags)) { + const RouteLoadSnapshot load = session->route_loader ? session->route_loader->snapshot() : RouteLoadSnapshot{}; + const bool show_load_progress = session->route_loader && (load.active || load.total_segments > 0); + const bool streaming = session->data_mode == SessionDataMode::Stream; + CameraFeedView *sidebar_camera = session->pane_camera_feeds[static_cast(sidebar_preview_camera_view(*session))].get(); + if (show_camera_feed && sidebar_camera != nullptr) { + sidebar_camera->draw(ImGui::GetContentRegionAvail().x, load.active); + } else if (streaming) { + ImGui::SeparatorText("Camera"); + ImGui::TextDisabled("Camera not available during live stream."); + ImGui::Spacing(); + } + + ImGui::SeparatorText(streaming ? "Stream" : "Route"); + if (streaming) { + const StreamPollSnapshot stream = session->stream_poller ? session->stream_poller->snapshot() : StreamPollSnapshot{}; + const bool paused = stream.paused || session->stream_paused; + const bool live = stream.connected && !paused; + const ImVec4 status_color = live ? color_rgb(38, 135, 67) : (paused ? color_rgb(168, 119, 34) : color_rgb(155, 63, 63)); + ImGui::TextColored(status_color, "%s %s", live ? "●" : "○", stream.source_label.c_str()); + ImGui::TextDisabled("%s%s", stream_source_kind_label(stream.source_kind), paused ? " paused" : ""); + const double span = session->route_data.has_time_range ? (session->route_data.x_max - session->route_data.x_min) : 0.0; + const float fill = stream.buffer_seconds <= 0.0 + ? 0.0f + : std::clamp(static_cast(span / stream.buffer_seconds), 0.0f, 1.0f); + ImGui::ProgressBar(fill, ImVec2(-FLT_MIN, 0.0f), nullptr); + ImGui::TextDisabled("%.0fs buffer | %zu series", session->stream_buffer_seconds, session->route_data.series.size()); + const char *button_label = paused ? "Resume" : "Pause"; + if (ImGui::Button(button_label, ImVec2(std::max(1.0f, ImGui::GetContentRegionAvail().x), 0.0f))) { + if (paused) { + start_stream_session(session, state, session->stream_source, session->stream_buffer_seconds, true); + } else { + stop_stream_session(session, state); + state->status_text = "Paused stream " + stream_source_target_label(session->stream_source); + } + } + } else if (session->route_name.empty()) { + ImGui::TextDisabled("No route loaded"); + } + if (!session->route_data.car_fingerprint.empty()) { + ImGui::TextWrapped("Car: %s", session->route_data.car_fingerprint.c_str()); + } + const std::vector dbc_names = available_dbc_names(); + ImGui::SetNextItemWidth(-FLT_MIN); + if (ImGui::BeginCombo("##dbc_combo", dbc_combo_label(*session).c_str())) { + const bool auto_selected = session->dbc_override.empty(); + if (ImGui::Selectable("Auto", auto_selected)) { + apply_dbc_override_change(session, state, {}); + } + if (auto_selected) { + ImGui::SetItemDefaultFocus(); + } + ImGui::Separator(); + for (const std::string &dbc_name : dbc_names) { + const bool selected = session->dbc_override == dbc_name; + if (ImGui::Selectable(dbc_name.c_str(), selected) && !selected) { + apply_dbc_override_change(session, state, dbc_name); + } + if (selected) { + ImGui::SetItemDefaultFocus(); + } + } + ImGui::EndCombo(); + } + ImGui::SeparatorText("Layout"); + ImGui::SetNextItemWidth(-FLT_MIN); + const std::string layout_combo_label = [&] { + const std::string base = session->layout_path.empty() ? std::string("untitled") : session->layout_path.stem().string(); + return state->layout_dirty ? base + " *" : base; + }(); + if (ImGui::BeginCombo("##layout_combo", layout_combo_label.c_str())) { + if (ImGui::Selectable("New Layout")) { + start_new_layout(session, state); + } + ImGui::Separator(); + const std::vector layouts = available_layout_names(); + const std::string current_layout = session->layout_path.empty() ? std::string("untitled") : session->layout_path.stem().string(); + for (const std::string &layout_name : layouts) { + const bool selected = layout_name == current_layout; + if (ImGui::Selectable(layout_name.c_str(), selected) && !selected) { + reload_layout(session, state, layout_name); + } + if (selected) { + ImGui::SetItemDefaultFocus(); + } + } + ImGui::EndCombo(); + } + const float layout_button_gap = ImGui::GetStyle().ItemSpacing.x; + const float layout_row_width = std::max(1.0f, ImGui::GetContentRegionAvail().x); + const float layout_button_width = std::max(1.0f, (layout_row_width - 2.0f * layout_button_gap) / 3.0f); + if (ImGui::Button("New", ImVec2(layout_button_width, 0.0f))) { + start_new_layout(session, state); + } + ImGui::SameLine(0.0f, layout_button_gap); + if (ImGui::Button("Save", ImVec2(layout_button_width, 0.0f))) { + state->request_save_layout = true; + } + ImGui::SameLine(0.0f, layout_button_gap); + ImGui::BeginDisabled(!state->layout_dirty); + if (ImGui::Button("Reset", ImVec2(layout_button_width, 0.0f))) { + state->request_reset_layout = true; + } + ImGui::EndDisabled(); + ImGui::Spacing(); + + ImGui::SeparatorText("Data Sources"); + ImGui::SetNextItemWidth(-FLT_MIN); + input_text_with_hint_string("##browser_filter", "Search...", &state->browser_filter); + const float footer_height = ImGui::GetFrameHeightWithSpacing() + + ImGui::GetTextLineHeightWithSpacing() + + 16.0f + + (show_load_progress ? (ImGui::GetFrameHeightWithSpacing() + 12.0f) : 0.0f); + const float browser_height = std::max(1.0f, ImGui::GetContentRegionAvail().y - footer_height); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(6.0f, 2.0f)); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(8.0f, 3.0f)); + if (ImGui::BeginChild("##timeseries_browser", ImVec2(0.0f, browser_height), true)) { + const std::string filter = lowercase_copy(state->browser_filter); + std::vector visible_paths; + for (const BrowserNode &node : session->browser_nodes) { + collect_visible_leaf_paths(node, filter, &visible_paths); + } + for (const SpecialItemSpec &spec : kSpecialItemSpecs) { + draw_browser_special_item(spec.id, spec.label); + } + ImGui::Dummy(ImVec2(0.0f, 2.0f)); + ImGui::Separator(); + ImGui::Dummy(ImVec2(0.0f, 2.0f)); + for (const BrowserNode &node : session->browser_nodes) { + draw_browser_node(session, node, state, filter, visible_paths); + } + } + ImGui::EndChild(); + ImGui::PopStyleVar(2); + + ImGui::SeparatorText("Custom Series"); + if (ImGui::Button("Create...", ImVec2(std::max(1.0f, ImGui::GetContentRegionAvail().x), 0.0f))) { + open_custom_series_editor(state, state->selected_browser_path); + } + if (show_load_progress) { + const float total = static_cast(std::max(1, load.total_segments)); + const bool finalizing = load.active + && load.total_segments > 0 + && load.segments_downloaded >= load.total_segments + && load.segments_parsed >= load.total_segments; + const float progress = load.total_segments == 0 + ? 0.0f + : (finalizing + ? 0.99f + : std::clamp(static_cast(load.segments_downloaded + load.segments_parsed) / (2.0f * total), 0.0f, 0.99f)); + ImGui::Dummy(ImVec2(0.0f, 8.0f)); + ImGui::ProgressBar(progress, ImVec2(-FLT_MIN, 0.0f), finalizing ? "Finalizing..." : nullptr); + } + } + ImGui::End(); + ImGui::PopStyleColor(2); +} + +std::string app_curve_display_name(const Curve &curve) { + if (!curve.label.empty()) return curve.label; + if (!curve.name.empty()) return curve.name; + return "curve"; +} + +Curve make_curve_for_path(const Pane &pane, const std::string &path) { + Curve curve; + curve.name = path; + curve.label = path; + curve.color = app_next_curve_color(pane); + return curve; +} + +bool add_curve_to_pane(WorkspaceTab *tab, int pane_index, Curve curve) { + if (pane_index < 0 || pane_index >= static_cast(tab->panes.size())) { + return false; + } + Pane &pane = tab->panes[static_cast(pane_index)]; + if (pane.kind != PaneKind::Plot) { + pane.kind = PaneKind::Plot; + if (is_default_special_title(pane.title)) { + pane.title = UNTITLED_PANE_TITLE; + } + } + for (Curve &existing : pane.curves) { + const bool same_named_curve = !curve.name.empty() && existing.name == curve.name; + const bool same_unnamed_curve = curve.name.empty() && existing.name.empty() && existing.label == curve.label; + if (same_named_curve || same_unnamed_curve) { + existing.visible = true; + return false; + } + } + pane.curves.push_back(std::move(curve)); + return true; +} + +bool add_path_curve_to_pane(AppSession *session, UiState *state, int pane_index, const std::string &path) { + if (app_find_route_series(*session, path) == nullptr) { + state->status_text = "Path not found in route"; + return false; + } + WorkspaceTab *tab = app_active_tab(&session->layout, *state); + if (tab == nullptr || pane_index < 0 || pane_index >= static_cast(tab->panes.size())) { + state->status_text = "No active pane"; + return false; + } + const SketchLayout before_layout = session->layout; + const bool inserted = add_curve_to_pane(tab, pane_index, make_curve_for_path(tab->panes[static_cast(pane_index)], path)); + bool autosave_ok = true; + if (inserted) { + state->undo.push(before_layout); + autosave_ok = mark_layout_dirty(session, state); + } + if (autosave_ok) { + state->status_text = inserted ? "Added " + path : "Curve already present"; + } + return true; +} + +int add_path_curves_to_pane(AppSession *session, UiState *state, int pane_index, const std::vector &paths) { + WorkspaceTab *tab = app_active_tab(&session->layout, *state); + if (tab == nullptr || pane_index < 0 || pane_index >= static_cast(tab->panes.size())) { + state->status_text = "No active pane"; + return 0; + } + + int inserted_count = 0; + int duplicate_count = 0; + const SketchLayout before_layout = session->layout; + for (const std::string &path : paths) { + if (app_find_route_series(*session, path) == nullptr) continue; + if (add_curve_to_pane(tab, pane_index, make_curve_for_path(tab->panes[static_cast(pane_index)], path))) { + ++inserted_count; + } else { + ++duplicate_count; + } + } + + if (inserted_count > 0) { + state->undo.push(before_layout); + if (mark_layout_dirty(session, state)) { + state->status_text = inserted_count == 1 + ? "Added " + paths.front() + : "Added " + std::to_string(inserted_count) + " curves"; + } + return inserted_count; + } + + if (duplicate_count > 0) { + state->status_text = duplicate_count == 1 ? "Curve already present" : "Curves already present"; + } else { + state->status_text = "No matching series found"; + } + return 0; +} + +bool app_add_curve_to_active_pane(AppSession *session, UiState *state, const std::string &path) { + const TabUiState *tab_state = app_active_tab_state(state); + if (tab_state == nullptr) { + state->status_text = "No active pane"; + return false; + } + return add_path_curve_to_pane(session, state, tab_state->active_pane_index, path); +} + +bool apply_special_item_to_pane(WorkspaceTab *tab, TabUiState *tab_state, int pane_index, std::string_view item_id) { + if (tab == nullptr || tab_state == nullptr) return false; + if (pane_index < 0 || pane_index >= static_cast(tab->panes.size())) return false; + const SpecialItemSpec *spec = special_item_spec(item_id); + if (spec == nullptr) return false; + Pane &pane = tab->panes[static_cast(pane_index)]; + if (!((pane.kind == PaneKind::Plot && pane.curves.empty()) || pane_kind_is_special(pane.kind))) { + return false; + } + if (pane.kind == spec->kind && (spec->kind != PaneKind::Camera || pane.camera_view == spec->camera_view)) { + tab_state->active_pane_index = pane_index; + return false; + } + const PaneKind previous_kind = pane.kind; + pane.kind = spec->kind; + pane.camera_view = spec->camera_view; + if (spec->kind == PaneKind::Map) { + if (pane.title == UNTITLED_PANE_TITLE || previous_kind != PaneKind::Plot) { + pane.title = spec->label; + } + } else if (spec->kind == PaneKind::Camera) { + pane.title = spec->label; + resize_tab_pane_state(tab_state, tab->panes.size()); + tab_state->camera_panes[static_cast(pane_index)].fit_to_pane = true; + } else { + pane.title = spec->label; + } + tab_state->active_pane_index = pane_index; + return true; +} + +bool split_pane(WorkspaceTab *tab, int pane_index, PaneDropZone zone, std::optional curve = std::nullopt) { + if (pane_index < 0 || pane_index >= static_cast(tab->panes.size())) { + return false; + } + if (zone == PaneDropZone::Center) return false; + + const int new_pane_index = static_cast(tab->panes.size()); + Pane new_pane = make_empty_pane(); + if (curve.has_value()) { + new_pane.curves.push_back(*curve); + } + tab->panes.push_back(std::move(new_pane)); + + const bool vertical = zone == PaneDropZone::Top || zone == PaneDropZone::Bottom; + const bool new_before = zone == PaneDropZone::Left || zone == PaneDropZone::Top; + return split_pane_node(&tab->root, pane_index, + vertical ? SplitOrientation::Vertical : SplitOrientation::Horizontal, + new_before, new_pane_index); +} + +bool close_pane(WorkspaceTab *tab, int pane_index) { + if (pane_index < 0 || pane_index >= static_cast(tab->panes.size())) { + return false; + } + if (tab->panes.size() <= 1) { + tab->panes[static_cast(pane_index)] = make_empty_pane(); + return true; + } + if (remove_pane_node(&tab->root, pane_index)) return false; + tab->panes.erase(tab->panes.begin() + static_cast(pane_index)); + decrement_pane_indices(&tab->root, pane_index); + normalize_split_node(&tab->root); + return true; +} + +void clear_pane(WorkspaceTab *tab, int pane_index) { + if (pane_index < 0 || pane_index >= static_cast(tab->panes.size())) { + return; + } + Pane &pane = tab->panes[static_cast(pane_index)]; + pane.curves.clear(); + pane.title = UNTITLED_PANE_TITLE; +} + +void create_runtime_tab(SketchLayout *layout, UiState *state) { + const std::string tab_name = next_tab_name(*layout, "tab1"); + layout->tabs.push_back(make_empty_tab(tab_name)); + state->tabs.push_back(TabUiState{.dock_needs_build = true, .active_pane_index = 0, .runtime_id = state->next_tab_runtime_id++}); + request_tab_selection(state, static_cast(layout->tabs.size()) - 1); + state->status_text = "Created " + tab_name; +} + +void duplicate_runtime_tab(SketchLayout *layout, UiState *state) { + if (layout->tabs.empty()) { + return; + } + const int source_index = std::clamp(state->active_tab_index, 0, static_cast(layout->tabs.size()) - 1); + WorkspaceTab copy = layout->tabs[static_cast(source_index)]; + copy.tab_name = next_tab_name(*layout, copy.tab_name + " copy"); + layout->tabs.push_back(std::move(copy)); + const int active_pane_index = source_index < static_cast(state->tabs.size()) ? state->tabs[static_cast(source_index)].active_pane_index : 0; + state->tabs.push_back(TabUiState{.dock_needs_build = true, .active_pane_index = active_pane_index, .runtime_id = state->next_tab_runtime_id++}); + request_tab_selection(state, static_cast(layout->tabs.size()) - 1); + state->status_text = "Duplicated tab"; +} + +void close_runtime_tab(SketchLayout *layout, UiState *state) { + if (layout->tabs.empty()) { + return; + } + const int tab_index = std::clamp(state->active_tab_index, 0, static_cast(layout->tabs.size()) - 1); + if (layout->tabs.size() == 1) { + layout->tabs[0] = make_empty_tab(layout->tabs[0].tab_name.empty() ? "tab1" : layout->tabs[0].tab_name); + if (state->tabs.empty()) { + state->tabs.push_back(TabUiState{.dock_needs_build = true, .active_pane_index = 0}); + } else { + state->tabs.resize(1); + state->tabs[0] = TabUiState{ + .dock_needs_build = true, + .active_pane_index = 0, + .runtime_id = state->tabs[0].runtime_id == 0 ? state->next_tab_runtime_id++ : state->tabs[0].runtime_id, + }; + } + state->active_tab_index = 0; + state->requested_tab_index = 0; + layout->current_tab_index = 0; + cancel_rename_tab(state); + state->status_text = "Closed tab"; + return; + } + layout->tabs.erase(layout->tabs.begin() + static_cast(tab_index)); + if (tab_index < static_cast(state->tabs.size())) { + state->tabs.erase(state->tabs.begin() + static_cast(tab_index)); + } + if (state->active_tab_index >= static_cast(layout->tabs.size())) { + state->active_tab_index = static_cast(layout->tabs.size()) - 1; + } + sync_ui_state(state, *layout); + state->requested_tab_index = state->active_tab_index; + state->status_text = "Closed tab"; +} + +void rename_runtime_tab(SketchLayout *layout, UiState *state) { + if (state->rename_tab_index < 0 || state->rename_tab_index >= static_cast(layout->tabs.size())) { + return; + } + layout->tabs[static_cast(state->rename_tab_index)].tab_name = state->rename_tab_buffer; + state->status_text = "Renamed tab"; + layout->current_tab_index = state->rename_tab_index; + cancel_rename_tab(state); +} + +void draw_inline_tab_editor(AppSession *session, UiState *state, const ImRect &tab_rect) { + const int rename_tab_index = state->rename_tab_index; + if (rename_tab_index < 0 || rename_tab_index >= static_cast(session->layout.tabs.size())) { + return; + } + + const float width = std::max(48.0f, tab_rect.Max.x - tab_rect.Min.x - 10.0f); + const ImVec2 pos = ImVec2(tab_rect.Min.x + 5.0f, tab_rect.Min.y + 2.0f); + ImGui::SetCursorScreenPos(pos); + ImGui::PushItemWidth(width); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(4.0f, 2.0f)); + if (state->focus_rename_tab_input) { + ImGui::SetKeyboardFocusHere(); + state->focus_rename_tab_input = false; + } + const bool submitted = input_text_string("##rename_tab_inline", + &state->rename_tab_buffer, + ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_EnterReturnsTrue); + const bool active = ImGui::IsItemActive(); + const bool escape = active && ImGui::IsKeyPressed(ImGuiKey_Escape); + const bool deactivated = ImGui::IsItemDeactivated(); + ImGui::PopStyleVar(); + ImGui::PopItemWidth(); + + if (escape) { + cancel_rename_tab(state); + } else if (submitted || deactivated) { + const SketchLayout before_layout = session->layout; + rename_runtime_tab(&session->layout, state); + state->undo.push(before_layout); + mark_layout_dirty(session, state); + } +} + + +std::optional draw_pane_drop_target(int tab_index, int pane_index, const Pane &target_pane) { + if (ImGui::GetDragDropPayload() == nullptr) return std::nullopt; + + const ImVec2 window_pos = ImGui::GetWindowPos(); + const ImVec2 content_min = ImGui::GetWindowContentRegionMin(); + const ImVec2 content_max = ImGui::GetWindowContentRegionMax(); + ImRect content_rect(ImVec2(window_pos.x + content_min.x, window_pos.y + content_min.y), + ImVec2(window_pos.x + content_max.x, window_pos.y + content_max.y)); + content_rect.Expand(ImVec2(-6.0f, -6.0f)); + if (content_rect.GetWidth() < 60.0f || content_rect.GetHeight() < 60.0f) { + return std::nullopt; + } + + const float edge_w = std::min(90.0f, content_rect.GetWidth() * 0.24f); + const float edge_h = std::min(72.0f, content_rect.GetHeight() * 0.24f); + struct ZoneRect { + PaneDropZone zone; + ImRect rect; + }; + const std::array zones = {{ + {PaneDropZone::Left, ImRect(content_rect.Min, ImVec2(content_rect.Min.x + edge_w, content_rect.Max.y))}, + {PaneDropZone::Right, ImRect(ImVec2(content_rect.Max.x - edge_w, content_rect.Min.y), content_rect.Max)}, + {PaneDropZone::Top, ImRect(content_rect.Min, ImVec2(content_rect.Max.x, content_rect.Min.y + edge_h))}, + {PaneDropZone::Bottom, ImRect(ImVec2(content_rect.Min.x, content_rect.Max.y - edge_h), content_rect.Max)}, + {PaneDropZone::Center, ImRect(ImVec2(content_rect.Min.x + edge_w, content_rect.Min.y + edge_h), + ImVec2(content_rect.Max.x - edge_w, content_rect.Max.y - edge_h))}, + }}; + + ImDrawList *draw_list = ImGui::GetWindowDrawList(); + for (const ZoneRect &zone : zones) { + if (zone.rect.GetWidth() <= 0.0f || zone.rect.GetHeight() <= 0.0f) { + continue; + } + + ImGui::PushID(static_cast(zone.zone) * 1000 + pane_index + tab_index * 100); + ImGui::SetCursorScreenPos(zone.rect.Min); + ImGui::InvisibleButton("##drop_zone", zone.rect.GetSize()); + if (ImGui::BeginDragDropTarget()) { + auto try_accept = [&](const char *type) -> const ImGuiPayload * { + const ImGuiPayload *p = ImGui::AcceptDragDropPayload(type, ImGuiDragDropFlags_AcceptBeforeDelivery); + if (p && p->Preview) { + draw_list->AddRectFilled(zone.rect.Min, zone.rect.Max, IM_COL32(70, 130, 220, 55)); + draw_list->AddRect(zone.rect.Min, zone.rect.Max, IM_COL32(45, 95, 175, 220), 0.0f, 0, 2.0f); + } + return p; + }; + auto deliver = [&](PaneDropAction action) -> std::optional { + action.zone = zone.zone; + action.target_pane_index = pane_index; + ImGui::EndDragDropTarget(); + ImGui::PopID(); + return action; + }; + if (const ImGuiPayload *p = try_accept("JOTP_BROWSER_PATHS"); p && p->Delivery) { + if (zone.zone != PaneDropZone::Center || target_pane.kind == PaneKind::Plot) { + PaneDropAction action; + action.from_browser = true; + action.browser_paths = decode_browser_drag_payload(static_cast(p->Data)); + return deliver(std::move(action)); + } + } + if (zone.zone != PaneDropZone::Center || (target_pane.kind == PaneKind::Plot && target_pane.curves.empty()) || pane_kind_is_special(target_pane.kind)) { + if (const ImGuiPayload *p = try_accept("JOTP_SPECIAL_ITEM"); p && p->Delivery) { + PaneDropAction action; + action.special_item_id = static_cast(p->Data); + return deliver(std::move(action)); + } + } + if (const ImGuiPayload *p = try_accept("JOTP_PANE_CURVE"); p && p->Delivery) { + if (zone.zone != PaneDropZone::Center || target_pane.kind == PaneKind::Plot) { + PaneDropAction action; + action.curve_ref = *static_cast(p->Data); + return deliver(std::move(action)); + } + } + ImGui::EndDragDropTarget(); + } + ImGui::PopID(); + } + return std::nullopt; +} + +bool commit_tab_layout_change(AppSession *session, + UiState *state, + WorkspaceTab *tab, + TabUiState *tab_state, + const SketchLayout &before_layout, + std::string_view status_text, + bool dock_changed) { + if (dock_changed) { + mark_tab_dock_dirty(state, state->active_tab_index); + } + resize_tab_pane_state(tab_state, tab->panes.size()); + state->undo.push(before_layout); + if (mark_layout_dirty(session, state)) { + state->status_text = std::string(status_text); + } + return true; +} + +bool apply_pane_menu_action(AppSession *session, UiState *state, int pane_index, + const PaneMenuAction &action) { + WorkspaceTab *tab = app_active_tab(&session->layout, *state); + TabUiState *tab_state = app_active_tab_state(state); + if (tab == nullptr || tab_state == nullptr) return false; + + const int original_pane_count = static_cast(tab->panes.size()); + const SketchLayout before_layout = session->layout; + bool dock_changed = false; + bool layout_changed = false; + std::string_view success_status = "Workspace updated"; + switch (action.kind) { + case PaneMenuActionKind::OpenAxisLimits: + tab_state->active_pane_index = pane_index; + open_axis_limits_editor(*session, state, pane_index); + state->status_text = "Axis limits editor opened"; + return true; + case PaneMenuActionKind::OpenCustomSeries: + tab_state->active_pane_index = pane_index; + open_custom_series_editor(state, preferred_custom_series_source(tab->panes[static_cast(pane_index)])); + state->status_text = "Custom series editor opened"; + return true; + case PaneMenuActionKind::SplitLeft: + case PaneMenuActionKind::SplitRight: + case PaneMenuActionKind::SplitTop: + case PaneMenuActionKind::SplitBottom: { + constexpr PaneDropZone kZones[] = {PaneDropZone::Left, PaneDropZone::Right, PaneDropZone::Top, PaneDropZone::Bottom}; + const auto zone = kZones[static_cast(action.kind) - static_cast(PaneMenuActionKind::SplitLeft)]; + if (split_pane(tab, pane_index, zone)) { + tab_state->active_pane_index = static_cast(tab->panes.size()) - 1; + dock_changed = true; + layout_changed = true; + } + break; + } + case PaneMenuActionKind::ResetView: + reset_shared_range(state, *session); + state->follow_latest = session->data_mode == SessionDataMode::Stream; + state->suppress_range_side_effects = true; + clamp_shared_range(state, *session); + persist_shared_range_to_tab(tab, *state); + clear_pane_vertical_limits(&tab->panes[static_cast(pane_index)]); + layout_changed = true; + success_status = "Plot view reset"; + break; + case PaneMenuActionKind::Clear: + clear_pane(tab, pane_index); + tab_state->active_pane_index = pane_index; + layout_changed = true; + break; + case PaneMenuActionKind::Close: + if (close_pane(tab, pane_index)) { + tab_state->active_pane_index = std::clamp(pane_index, 0, static_cast(tab->panes.size()) - 1); + layout_changed = true; + dock_changed = static_cast(tab->panes.size()) != original_pane_count; + } + break; + case PaneMenuActionKind::None: + return false; + } + + if (!layout_changed) { + return false; + } + return commit_tab_layout_change(session, state, tab, tab_state, before_layout, success_status, dock_changed); +} + +bool apply_pane_drop_action(AppSession *session, UiState *state, const PaneDropAction &action) { + WorkspaceTab *tab = app_active_tab(&session->layout, *state); + TabUiState *tab_state = app_active_tab_state(state); + if (tab == nullptr || tab_state == nullptr) return false; + + if (!action.special_item_id.empty()) { + const SpecialItemSpec *spec = special_item_spec(action.special_item_id); + if (spec == nullptr) { + return false; + } + if (action.zone == PaneDropZone::Center) { + if (action.target_pane_index < 0 || action.target_pane_index >= static_cast(tab->panes.size())) { + return false; + } + if (!((tab->panes[static_cast(action.target_pane_index)].kind == PaneKind::Plot + && tab->panes[static_cast(action.target_pane_index)].curves.empty()) + || pane_kind_is_special(tab->panes[static_cast(action.target_pane_index)].kind))) { + state->status_text = std::string(special_item_label(action.special_item_id)) + " can only replace another special pane or use an empty pane"; + return false; + } + const SketchLayout before_layout = session->layout; + const bool changed = apply_special_item_to_pane(tab, tab_state, action.target_pane_index, spec->id); + if (!changed) { + state->status_text = std::string(special_item_label(action.special_item_id)) + " already shown in pane"; + return false; + } + return commit_tab_layout_change(session, state, tab, tab_state, before_layout, + std::string(special_item_label(action.special_item_id)) + " added to pane", + false); + } + const SketchLayout before_layout = session->layout; + if (split_pane(tab, action.target_pane_index, action.zone)) { + tab_state->active_pane_index = static_cast(tab->panes.size()) - 1; + const bool changed = apply_special_item_to_pane(tab, tab_state, tab_state->active_pane_index, spec->id); + if (!changed) { + return false; + } + return commit_tab_layout_change(session, state, tab, tab_state, before_layout, + "Split pane and added " + std::string(special_item_label(action.special_item_id)), + true); + } + return false; + } + + if (action.from_browser) { + if (action.browser_paths.empty()) return false; + if (action.zone == PaneDropZone::Center) { + const int inserted_count = add_path_curves_to_pane(session, state, action.target_pane_index, action.browser_paths); + if (inserted_count > 0) { + tab_state->active_pane_index = action.target_pane_index; + } + return inserted_count > 0; + } + const SketchLayout before_layout = session->layout; + if (split_pane(tab, action.target_pane_index, action.zone)) { + tab_state->active_pane_index = static_cast(tab->panes.size()) - 1; + int inserted_count = 0; + for (const std::string &path : action.browser_paths) { + if (app_find_route_series(*session, path) == nullptr) continue; + if (add_curve_to_pane(tab, tab_state->active_pane_index, + make_curve_for_path(tab->panes[static_cast(tab_state->active_pane_index)], path))) { + ++inserted_count; + } + } + if (inserted_count > 0) { + return commit_tab_layout_change(session, state, tab, tab_state, before_layout, + inserted_count == 1 + ? "Split pane and added " + action.browser_paths.front() + : "Split pane and added " + std::to_string(inserted_count) + " curves", + true); + } + return false; + } + return false; + } + + if (action.curve_ref.tab_index < 0 + || action.curve_ref.tab_index >= static_cast(session->layout.tabs.size())) { + return false; + } + WorkspaceTab &source_tab = session->layout.tabs[static_cast(action.curve_ref.tab_index)]; + if (action.curve_ref.pane_index < 0 + || action.curve_ref.pane_index >= static_cast(source_tab.panes.size())) { + return false; + } + const Pane &source_pane = source_tab.panes[static_cast(action.curve_ref.pane_index)]; + if (action.curve_ref.curve_index < 0 + || action.curve_ref.curve_index >= static_cast(source_pane.curves.size())) { + return false; + } + const Curve curve = source_pane.curves[static_cast(action.curve_ref.curve_index)]; + + if (action.zone == PaneDropZone::Center) { + const SketchLayout before_layout = session->layout; + const bool inserted = add_curve_to_pane(tab, action.target_pane_index, curve); + tab_state->active_pane_index = action.target_pane_index; + if (inserted) { + state->undo.push(before_layout); + if (mark_layout_dirty(session, state)) { + state->status_text = "Added " + app_curve_display_name(curve); + } + } else { + state->status_text = "Curve already present"; + } + return true; + } + const SketchLayout before_layout = session->layout; + if (split_pane(tab, action.target_pane_index, action.zone, curve)) { + tab_state->active_pane_index = static_cast(tab->panes.size()) - 1; + return commit_tab_layout_change(session, state, tab, tab_state, before_layout, + "Split pane and added " + app_curve_display_name(curve), + true); + } + return false; +} + +ImGuiDir dock_direction(SplitOrientation orientation) { + return orientation == SplitOrientation::Horizontal ? ImGuiDir_Left : ImGuiDir_Up; +} + +void build_dock_tree(const WorkspaceNode &node, const WorkspaceTab &tab, int tab_runtime_id, ImGuiID dock_id) { + if (node.is_pane) { + if (node.pane_index >= 0 && node.pane_index < static_cast(tab.panes.size())) { + ImGui::DockBuilderDockWindow( + pane_window_name(tab_runtime_id, node.pane_index, tab.panes[static_cast(node.pane_index)]).c_str(), + dock_id); + if (ImGuiDockNode *dock_node = ImGui::DockBuilderGetNode(dock_id); dock_node != nullptr) { + dock_node->LocalFlags |= ImGuiDockNodeFlags_AutoHideTabBar | + ImGuiDockNodeFlags_NoWindowMenuButton | + ImGuiDockNodeFlags_NoCloseButton; + } + } + return; + } + if (node.children.empty()) { + return; + } + if (node.children.size() == 1) { + build_dock_tree(node.children.front(), tab, tab_runtime_id, dock_id); + return; + } + + float remaining = 1.0f; + ImGuiID current = dock_id; + for (size_t i = 0; i + 1 < node.children.size(); ++i) { + const float child_size = i < node.sizes.size() ? node.sizes[i] : 0.0f; + const float ratio = remaining <= 0.0f ? 0.5f : std::clamp(child_size / remaining, 0.05f, 0.95f); + ImGuiID child_id = 0; + ImGuiID remainder_id = 0; + ImGui::DockBuilderSplitNode(current, dock_direction(node.orientation), ratio, &child_id, &remainder_id); + build_dock_tree(node.children[i], tab, tab_runtime_id, child_id); + current = remainder_id; + remaining = std::max(0.0f, remaining - child_size); + } + build_dock_tree(node.children.back(), tab, tab_runtime_id, current); +} + +void ensure_dockspace(const WorkspaceTab &tab, TabUiState *tab_state, ImVec2 dockspace_size) { + if (dockspace_size.x <= 0.0f || dockspace_size.y <= 0.0f || tab_state == nullptr) { + return; + } + const bool size_changed = std::abs(tab_state->last_dockspace_size.x - dockspace_size.x) > 1.0f + || std::abs(tab_state->last_dockspace_size.y - dockspace_size.y) > 1.0f; + if (!tab_state->dock_needs_build && !size_changed) { + return; + } + + const ImGuiID dockspace_id = dockspace_id_for_tab(tab_state->runtime_id); + ImGui::DockBuilderRemoveNode(dockspace_id); + ImGui::DockBuilderAddNode(dockspace_id, ImGuiDockNodeFlags_DockSpace | ImGuiDockNodeFlags_AutoHideTabBar); + ImGui::DockBuilderSetNodeSize(dockspace_id, dockspace_size); + build_dock_tree(tab.root, tab, tab_state->runtime_id, dockspace_id); + ImGui::DockBuilderFinish(dockspace_id); + tab_state->dock_needs_build = false; + tab_state->last_dockspace_size = dockspace_size; +} + +void draw_pane_windows(AppSession *session, UiState *state) { + WorkspaceTab *tab = app_active_tab(&session->layout, *state); + TabUiState *tab_state = app_active_tab_state(state); + if (tab == nullptr || tab_state == nullptr) { + return; + } + + std::optional> pending_menu_action; + std::optional pending_close_pane; + std::optional pending_drop_action; + + for (size_t i = 0; i < tab->panes.size(); ++i) { + Pane &pane = tab->panes[i]; + std::optional menu_action; + std::optional drop_action; + bool close_pane_requested = false; + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(2.0f, 2.0f)); + ImGui::PushStyleColor(ImGuiCol_WindowBg, color_rgb(250, 250, 251)); + ImGui::PushStyleColor(ImGuiCol_Border, color_rgb(194, 198, 204)); + ImGui::PushStyleColor(ImGuiCol_TitleBg, color_rgb(252, 252, 253)); + ImGui::PushStyleColor(ImGuiCol_TitleBgActive, color_rgb(252, 252, 253)); + ImGui::PushStyleColor(ImGuiCol_TitleBgCollapsed, color_rgb(252, 252, 253)); + const ImGuiWindowFlags flags = ImGuiWindowFlags_NoCollapse; + const std::string window_name = pane_window_name(tab_state->runtime_id, static_cast(i), pane); + const bool opened = ImGui::Begin(window_name.c_str(), nullptr, flags); + if (opened) { + if (ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows) + || (ImGui::IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows) && ImGui::IsMouseClicked(0))) { + tab_state->active_pane_index = static_cast(i); + } + if (pane.kind == PaneKind::Map) { + draw_map_pane(session, state, &pane, static_cast(i)); + } else if (pane.kind == PaneKind::Thumbnail) { + draw_thumbnail_pane(session, state); + } else if (pane.kind == PaneKind::Camera) { + draw_camera_pane(session, state, tab_state, static_cast(i), pane); + } else { + draw_plot(*session, &pane, state); + } + draw_pane_frame_overlay(); + close_pane_requested = draw_pane_close_button_overlay(); + menu_action = draw_pane_context_menu(*tab, static_cast(i)); + drop_action = draw_pane_drop_target(state->active_tab_index, static_cast(i), pane); + } + ImGui::End(); + ImGui::PopStyleVar(); + ImGui::PopStyleColor(5); + if (!pending_menu_action.has_value() && menu_action.has_value()) { + pending_menu_action = std::make_pair(static_cast(i), *menu_action); + } + if (!pending_menu_action.has_value() && !pending_close_pane.has_value() && close_pane_requested) { + pending_close_pane = static_cast(i); + } + if (!pending_menu_action.has_value() && !pending_close_pane.has_value() + && !pending_drop_action.has_value() && drop_action.has_value()) { + pending_drop_action = *drop_action; + } + } + + if (pending_menu_action.has_value()) { + apply_pane_menu_action(session, state, pending_menu_action->first, pending_menu_action->second); + return; + } + if (pending_close_pane.has_value()) { + PaneMenuAction action; + action.kind = PaneMenuActionKind::Close; + action.pane_index = *pending_close_pane; + apply_pane_menu_action(session, state, *pending_close_pane, action); + return; + } + if (pending_drop_action.has_value()) { + apply_pane_drop_action(session, state, *pending_drop_action); + } +} + +void draw_workspace(AppSession *session, const UiMetrics &ui, UiState *state) { + state->custom_series.selected = false; + state->logs.selected = false; + ImGui::SetNextWindowPos(ImVec2(ui.content_x, ui.content_y)); + ImGui::SetNextWindowSize(ImVec2(ui.content_w, ui.content_h)); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); + ImGui::PushStyleColor(ImGuiCol_WindowBg, color_rgb(244, 246, 248)); + ImGui::PushStyleColor(ImGuiCol_Border, color_rgb(186, 191, 198)); + const ImGuiWindowFlags flags = ImGuiWindowFlags_NoDecoration | + ImGuiWindowFlags_NoMove | + ImGuiWindowFlags_NoResize | + ImGuiWindowFlags_NoSavedSettings | + ImGuiWindowFlags_NoScrollbar | + ImGuiWindowFlags_NoScrollWithMouse; + if (ImGui::Begin("##workspace_host", nullptr, flags)) { + const int selection_request = state->requested_tab_index; + std::optional rename_tab_rect; + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(10.0f, 6.0f)); + ImGui::PushStyleVar(ImGuiStyleVar_ItemInnerSpacing, ImVec2(8.0f, 4.0f)); + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.0f, 0.0f, 0.0f, 0.0f)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.0f, 0.0f, 0.0f, 0.0f)); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.0f, 0.0f, 0.0f, 0.0f)); + if (ImGui::BeginTabBar("##layout_tabs", ImGuiTabBarFlags_FittingPolicyScroll)) { + enum class TabActionKind { + None, + New, + Rename, + Duplicate, + Close, + }; + TabActionKind pending_action = TabActionKind::None; + int pending_tab_index = -1; + bool custom_series_tab_open = state->custom_series.open; + bool suppress_aux_tabs_this_frame = state->request_close_tab && session->layout.tabs.size() == 1; + for (size_t i = 0; i < session->layout.tabs.size(); ++i) { + const WorkspaceTab &tab = session->layout.tabs[i]; + const TabUiState &tab_ui = state->tabs[i]; + ImGuiTabItemFlags tab_flags = ImGuiTabItemFlags_None; + if (static_cast(i) == selection_request) { + tab_flags |= ImGuiTabItemFlags_SetSelected; + } + bool tab_open = true; + const bool opened = ImGui::BeginTabItem(tab_item_label(tab, tab_ui.runtime_id).c_str(), &tab_open, tab_flags); + if (state->rename_tab_index == static_cast(i)) { + rename_tab_rect = ImRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax()); + } + if (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) { + pending_action = TabActionKind::Rename; + pending_tab_index = static_cast(i); + } + if (!tab_open) { + pending_action = TabActionKind::Close; + pending_tab_index = static_cast(i); + if (session->layout.tabs.size() == 1) { + suppress_aux_tabs_this_frame = true; + } + } + if (ImGui::BeginPopupContextItem()) { + if (ImGui::MenuItem("New Tab")) { + pending_action = TabActionKind::New; + } + if (ImGui::MenuItem("Rename Tab...")) { + pending_action = TabActionKind::Rename; + pending_tab_index = static_cast(i); + } + if (ImGui::MenuItem("Duplicate Tab")) { + pending_action = TabActionKind::Duplicate; + pending_tab_index = static_cast(i); + } + if (ImGui::MenuItem("Close Tab")) { + pending_action = TabActionKind::Close; + pending_tab_index = static_cast(i); + } + ImGui::EndPopup(); + } + if (opened) { + state->active_tab_index = static_cast(i); + session->layout.current_tab_index = state->active_tab_index; + if (i < state->tabs.size()) { + ensure_dockspace(tab, &state->tabs[i], ImGui::GetContentRegionAvail()); + } + ImGui::DockSpace(dockspace_id_for_tab(tab_ui.runtime_id), + ImVec2(0.0f, 0.0f), + ImGuiDockNodeFlags_AutoHideTabBar | + ImGuiDockNodeFlags_NoWindowMenuButton | + ImGuiDockNodeFlags_NoCloseButton); + ImGui::EndTabItem(); + } + } + if (!suppress_aux_tabs_this_frame) { + ImGuiTabItemFlags logs_flags = ImGuiTabItemFlags_None; + if (state->logs.request_select) { + logs_flags |= ImGuiTabItemFlags_SetSelected; + } + if (ImGui::BeginTabItem("Logs##workspace_logs", nullptr, logs_flags)) { + state->logs.request_select = false; + state->logs.selected = true; + draw_logs_tab(session, state); + ImGui::EndTabItem(); + } + if (custom_series_tab_open) { + ImGuiTabItemFlags custom_flags = ImGuiTabItemFlags_None; + if (state->custom_series.request_select) { + custom_flags |= ImGuiTabItemFlags_SetSelected; + } + if (ImGui::BeginTabItem("Custom Series##workspace_custom_series", &custom_series_tab_open, custom_flags)) { + state->custom_series.request_select = false; + state->custom_series.selected = true; + draw_custom_series_editor(session, state); + ImGui::EndTabItem(); + } + } + } + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(12.0f, 5.0f)); + ImGui::PushStyleColor(ImGuiCol_Tab, color_rgb(210, 217, 225)); + ImGui::PushStyleColor(ImGuiCol_TabHovered, color_rgb(224, 230, 237)); + ImGui::PushStyleColor(ImGuiCol_TabSelected, color_rgb(242, 245, 248)); + if (ImGui::TabItemButton(" ##new_tab_button", ImGuiTabItemFlags_Trailing)) { + pending_action = TabActionKind::New; + } + { + const ImRect rect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax()); + ImDrawList *draw_list = ImGui::GetWindowDrawList(); + const ImU32 color = ImGui::GetColorU32(color_rgb(72, 79, 88)); + const ImVec2 center((rect.Min.x + rect.Max.x) * 0.5f, (rect.Min.y + rect.Max.y) * 0.5f); + constexpr float half_extent = 6.25f; + constexpr float thickness = 2.0f; + draw_list->AddLine(ImVec2(center.x - half_extent, center.y), + ImVec2(center.x + half_extent, center.y), + color, + thickness); + draw_list->AddLine(ImVec2(center.x, center.y - half_extent), + ImVec2(center.x, center.y + half_extent), + color, + thickness); + } + if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayShort)) { + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(8.0f, 6.0f)); + ImGui::BeginTooltip(); + ImGui::TextUnformatted("New Tab"); + ImGui::EndTooltip(); + ImGui::PopStyleVar(); + } + ImGui::PopStyleColor(3); + ImGui::PopStyleVar(); + ImGui::EndTabBar(); + + if (!custom_series_tab_open) { + state->custom_series.open = false; + state->custom_series.request_select = false; + } + + if (rename_tab_rect.has_value()) { + draw_inline_tab_editor(session, state, *rename_tab_rect); + } + + if (state->request_new_tab || pending_action == TabActionKind::New) { + const SketchLayout before_layout = session->layout; + create_runtime_tab(&session->layout, state); + state->undo.push(before_layout); + mark_layout_dirty(session, state); + state->request_new_tab = false; + } else if (pending_action == TabActionKind::Rename) { + begin_rename_tab(session->layout, state, pending_tab_index); + } else if (state->request_duplicate_tab || pending_action == TabActionKind::Duplicate) { + if (pending_tab_index >= 0) { + request_tab_selection(state, pending_tab_index); + } + const SketchLayout before_layout = session->layout; + duplicate_runtime_tab(&session->layout, state); + state->undo.push(before_layout); + mark_layout_dirty(session, state); + state->request_duplicate_tab = false; + } else if (state->request_close_tab || pending_action == TabActionKind::Close) { + if (pending_tab_index >= 0) { + request_tab_selection(state, pending_tab_index); + } + const SketchLayout before_layout = session->layout; + close_runtime_tab(&session->layout, state); + state->undo.push(before_layout); + mark_layout_dirty(session, state); + state->request_close_tab = false; + } + if (state->requested_tab_index == selection_request) { + state->requested_tab_index = -1; + } + } + ImGui::PopStyleColor(3); + ImGui::PopStyleVar(2); + } + ImGui::End(); + ImGui::PopStyleVar(); + ImGui::PopStyleColor(2); +} + +int run(const Options &options) { + try { + const fs::path layout_path = options.layout.empty() ? fs::path() : resolve_layout_path(options.layout); + AppSession session = { + .layout_path = layout_path, + .autosave_path = layout_path.empty() ? fs::path() : autosave_path_for_layout(layout_path), + .route_name = options.route_name, + .data_dir = options.data_dir, + .dbc_override = {}, + .stream_source = StreamSourceConfig{.kind = is_local_stream_address(options.stream_address) + ? StreamSourceKind::CerealLocal + : StreamSourceKind::CerealRemote, + .address = options.stream_address}, + .stream_buffer_seconds = options.stream_buffer_seconds, + .data_mode = options.stream ? SessionDataMode::Stream : SessionDataMode::Route, + .route_id = options.stream ? RouteIdentifier{} : parse_route_identifier(options.route_name), + .layout = options.layout.empty() ? make_empty_layout() : load_sketch_layout(layout_path), + }; + UiState ui_state; + if (!layout_path.empty() && !session.autosave_path.empty() && fs::exists(session.autosave_path)) { + session.layout = load_sketch_layout(session.autosave_path); + ui_state.layout_dirty = true; + } + ui_state.undo.reset(session.layout); + sync_ui_state(&ui_state, session.layout); + sync_route_buffers(&ui_state, session); + sync_stream_buffers(&ui_state, session); + sync_layout_buffers(&ui_state, session); + + session.async_route_loading = session.data_mode == SessionDataMode::Route + && options.show && options.output_path.empty() && !options.sync_load; + if (session.data_mode == SessionDataMode::Route && !session.async_route_loading) { + TerminalRouteProgress route_progress(::isatty(STDERR_FILENO) != 0); + rebuild_session_route_data(&session, &ui_state, [&](const RouteLoadProgress &update) { + route_progress.update(update); + }); + route_progress.finish(); + } + + GlfwRuntime glfw_runtime(options); + ImGuiRuntime imgui_runtime(glfw_runtime.window()); + configure_style(); + session.map_data = std::make_unique(); + for (std::unique_ptr &feed : session.pane_camera_feeds) { + feed = std::make_unique(); + } + session.thumbnail_view = std::make_unique(); + sync_camera_feeds(&session); + + if (session.async_route_loading) { + session.route_loader = std::make_unique(::isatty(STDERR_FILENO) != 0); + start_async_route_load(&session, &ui_state); + } else if (session.data_mode == SessionDataMode::Stream) { + session.stream_poller = std::make_unique(); + start_stream_session(&session, &ui_state, session.stream_source, session.stream_buffer_seconds); + } + + const bool should_capture = !options.output_path.empty(); + const fs::path output_path = should_capture ? fs::path(options.output_path) : fs::path(); + const bool capture_has_map = should_capture && active_tab_has_map_pane(session.layout); + if (options.show) { + bool captured = false; + const auto capture_ready_at = std::chrono::steady_clock::now() + (capture_has_map ? std::chrono::milliseconds(1800) + : std::chrono::milliseconds(0)); + while (!glfwWindowShouldClose(glfw_runtime.window())) { + const bool capture_ready = std::chrono::steady_clock::now() >= capture_ready_at; + const fs::path *capture_path = (!captured && should_capture && capture_ready) ? &output_path : nullptr; + render_frame(glfw_runtime.window(), &session, &ui_state, capture_path); + captured = captured || capture_path != nullptr; + } + } else { + render_frame(glfw_runtime.window(), &session, &ui_state, nullptr); + if (should_capture) { + for (int i = 0; i < 3; ++i) { + render_frame(glfw_runtime.window(), &session, &ui_state, nullptr); + } + if (capture_has_map) { + for (int i = 0; i < 18; ++i) { + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + render_frame(glfw_runtime.window(), &session, &ui_state, nullptr); + } + } + render_frame(glfw_runtime.window(), &session, &ui_state, &output_path); + } + } + if (session.stream_poller) { + session.stream_poller->stop(); + } + session.map_data.reset(); + for (std::unique_ptr &feed : session.pane_camera_feeds) { + feed.reset(); + } + session.thumbnail_view.reset(); + return 0; + } catch (const std::exception &err) { + std::cerr << err.what() << "\n"; + return 1; + } +} diff --git a/openpilot/tools/jotpluggler/app.h b/openpilot/tools/jotpluggler/app.h new file mode 100644 index 0000000000..b7754f51b2 --- /dev/null +++ b/openpilot/tools/jotpluggler/app.h @@ -0,0 +1,914 @@ +#pragma once + +#include "openpilot/cereal/gen/cpp/log.capnp.h" +#include "imgui.h" +#include "tools/jotpluggler/dbc.h" +#include "tools/jotpluggler/util.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// ***** +// app options & entry point +// ***** + +struct Options { + std::string layout; + std::string route_name; + std::string data_dir; + std::string output_path; + std::string stream_address = "127.0.0.1"; + int width = 1600; + int height = 900; + bool show = false; + bool sync_load = false; + bool stream = false; + double stream_buffer_seconds = 30.0; +}; + +int run(const Options &options); + +// ***** +// sketch layout & route data +// ***** + +struct PlotRange { + bool valid = false; + double left = 0.0; + double right = 0.0; + double bottom = 0.0; + double top = 1.0; + bool has_y_limit_min = false; + bool has_y_limit_max = false; + double y_limit_min = 0.0; + double y_limit_max = 1.0; +}; + +struct CustomPythonSeries { + std::string linked_source; + std::vector additional_sources; + std::string globals_code; + std::string function_code; +}; + +struct Curve { + std::string name; + std::string label; + std::array color = {160, 170, 180}; + bool visible = true; + bool derivative = false; + double derivative_dt = 0.0; + double value_scale = 1.0; + double value_offset = 0.0; + bool runtime_only = false; + std::optional custom_python; + std::string runtime_error_message; + std::vector xs; + std::vector ys; +}; + +enum class PaneKind : uint8_t { + Plot, + Map, + Thumbnail, + Camera, +}; + +enum class CameraViewKind : uint8_t { + Road, + Driver, + WideRoad, + QRoad, +}; + +struct Pane { + PaneKind kind = PaneKind::Plot; + CameraViewKind camera_view = CameraViewKind::Road; + std::string title; + PlotRange range; + std::vector curves; +}; + +enum class SplitOrientation { + Horizontal, + Vertical, +}; + +struct WorkspaceNode { + bool is_pane = false; + int pane_index = -1; + SplitOrientation orientation = SplitOrientation::Horizontal; + std::vector sizes; + std::vector children; +}; + +struct WorkspaceTab { + std::string tab_name; + WorkspaceNode root; + std::vector panes; +}; + +struct RouteSeries { + std::string path; + std::vector times; + std::vector values; +}; + +struct CameraSegmentFile { + int segment = -1; + std::string path; +}; + +struct CameraFrameIndexEntry { + double timestamp = 0.0; + int segment = -1; + int decode_index = -1; + uint32_t frame_id = 0; +}; + +struct CameraFeedIndex { + std::vector segment_files; + std::vector entries; +}; + +struct ThumbnailFrame { + double timestamp = 0.0; + int segment = -1; + std::vector jpeg; +}; + +enum class LogOrigin : uint8_t { + Log, + OperatingSystem, + Alert, +}; + +struct LogEntry { + double mono_time = 0.0; + double boot_time = 0.0; + double wall_time = 0.0; + uint8_t level = 20; + std::string source; + std::string func; + std::string message; + std::string context; + LogOrigin origin = LogOrigin::Log; +}; + +struct EnumInfo { + std::vector names; +}; + +struct SeriesFormat { + int decimals = 3; + bool integer_like = false; + bool has_negative = false; + int digits_before = 1; + int total_width = 0; + char fmt[16] = "%7.3f"; +}; + +enum class CanServiceKind : uint8_t { + Can, + Sendcan, +}; + +struct CanMessageId { + CanServiceKind service = CanServiceKind::Can; + uint8_t bus = 0; + uint32_t address = 0; + + bool operator==(const CanMessageId &other) const { + return service == other.service && bus == other.bus && address == other.address; + } +}; + +struct CanMessageIdHash { + size_t operator()(const CanMessageId &id) const { + return (static_cast(id.service) << 40) + ^ (static_cast(id.bus) << 32) + ^ static_cast(id.address); + } +}; + +struct CanFrameSample { + double mono_time = 0.0; + uint16_t bus_time = 0; + std::string data; +}; + +struct LiveCanFrame { + double mono_time = 0.0; + uint8_t bus = 0; + uint32_t address = 0; + uint16_t bus_time = 0; + std::string data; +}; + +struct CanMessageData { + CanMessageId id; + std::vector samples; +}; + +struct TimelineEntry { + enum class Type : uint8_t { + None, + Engaged, + AlertInfo, + AlertWarning, + AlertCritical, + }; + + double start_time = 0.0; + double end_time = 0.0; + Type type = Type::None; +}; + +struct GpsPoint { + double time = 0.0; + double lat = 0.0; + double lon = 0.0; + float bearing = 0.0f; + TimelineEntry::Type type = TimelineEntry::Type::None; +}; + +struct GpsTrace { + std::vector points; + double min_lat = 0.0; + double max_lat = 0.0; + double min_lon = 0.0; + double max_lon = 0.0; +}; + +enum class LogSelector : uint8_t { + Auto, + RLog, + QLog, +}; + +struct RouteIdentifier { + std::string dongle_id; + std::string log_id; + int slice_begin = 0; + int slice_end = -1; + bool slice_explicit = false; + LogSelector selector = LogSelector::Auto; + bool selector_explicit = false; + int available_begin = 0; + int available_end = 0; + + bool empty() const { + return dongle_id.empty() || log_id.empty(); + } + + std::string canonical() const { + return empty() ? std::string() : dongle_id + "/" + log_id; + } + + std::string onebox() const { + return empty() ? std::string() : dongle_id + "|" + log_id; + } + + std::string display_slice() const { + const int begin = slice_explicit ? slice_begin : available_begin; + const int end = slice_explicit ? slice_end : available_end; + if (end < 0) { + return std::to_string(begin) + ":"; + } + if (end == begin) { + return std::to_string(begin); + } + return std::to_string(begin) + ":" + std::to_string(end); + } + + char selector_char() const { + switch (selector) { + case LogSelector::RLog: return 'r'; + case LogSelector::QLog: return 'q'; + case LogSelector::Auto: + default: return 'a'; + } + } + + std::string full_spec() const { + if (empty()) return {}; + std::string spec = dongle_id + "/" + log_id; + if (slice_explicit) { + spec += "/"; + spec += display_slice(); + } + if (selector_explicit) { + spec += "/"; + spec.push_back(selector_char()); + } + return spec; + } +}; + +struct RouteData { + std::vector series; + std::vector paths; + std::vector roots; + std::vector can_messages; + CameraFeedIndex road_camera; + CameraFeedIndex driver_camera; + CameraFeedIndex wide_road_camera; + CameraFeedIndex qroad_camera; + std::vector thumbnails; + GpsTrace gps_trace; + std::vector logs; + std::vector timeline; + std::unordered_map enum_info; + std::unordered_map series_formats; + std::string car_fingerprint; + std::string dbc_name; + RouteIdentifier route_id; + bool has_time_range = false; + double x_min = 0.0; + double x_max = 1.0; +}; + +struct StreamExtractBatch { + std::vector series; + std::vector can_messages; + std::vector logs; + std::vector timeline; + std::unordered_map enum_info; + std::string car_fingerprint; + std::string dbc_name; + bool has_time_offset = false; + double time_offset = 0.0; +}; + +struct SketchLayout { + std::vector tabs; + std::vector roots; + int current_tab_index = 0; +}; + +enum class RouteLoadStage { + Resolving, + DownloadingSegment, + ParsingSegment, + Finished, +}; + +struct RouteLoadProgress { + RouteLoadStage stage = RouteLoadStage::Resolving; + size_t segment_index = 0; + size_t segment_count = 0; + uint64_t current = 0; + uint64_t total = 0; + size_t segments_downloaded = 0; + size_t segments_parsed = 0; + size_t total_segments = 0; + uint64_t bytes_downloaded = 0; + int num_workers = 1; + std::string segment_name; +}; + +using RouteLoadProgressCallback = std::function; + +class StreamAccumulator { +public: + explicit StreamAccumulator(const std::string &dbc_name = {}, std::optional time_offset = std::nullopt); + ~StreamAccumulator(); + + StreamAccumulator(const StreamAccumulator &) = delete; + StreamAccumulator &operator=(const StreamAccumulator &) = delete; + + void setDbcName(const std::string &dbc_name); + void appendEvent(kj::ArrayPtr data); + void appendCanFrames(CanServiceKind service, const std::vector &frames); + StreamExtractBatch takeBatch(); + const std::string &carFingerprint() const; + const std::string &dbc_name() const; + std::optional timeOffset() const; + +private: + struct Impl; + std::unique_ptr impl_; +}; + +SketchLayout load_sketch_layout(const std::filesystem::path &layout_path); +std::vector available_dbc_names(); +std::vector collect_route_roots_for_paths(const std::vector &paths); +std::optional load_dbc_by_name(const std::string &dbc_name); +std::vector decode_can_messages(const std::vector &can_messages, + const std::string &dbc_name, + std::unordered_map *enum_info = nullptr); +RouteData load_route_data(const std::string &route_name, + const std::string &data_dir = {}, + const std::string &dbc_name = {}, + const RouteLoadProgressCallback &progress = {}); +RouteIdentifier parse_route_identifier(std::string_view route_name); +void rebuild_gps_trace(RouteData *route_data); + +// ***** +// icons +// ***** + +namespace icon { +constexpr const char ARROW_DOWN_UP[] = "\xef\x84\xa7"; +constexpr const char ARROW_LEFT_RIGHT[] = "\xef\x84\xab"; +constexpr const char BAR_CHART[] = "\xef\x85\xbe"; +constexpr const char BOX_ARROW_UP_RIGHT[] = "\xef\x87\x85"; +constexpr const char CLIPBOARD[] = "\xef\x8a\x90"; +constexpr const char CLIPBOARD2[] = "\xef\x9c\xb3"; +constexpr const char DISTRIBUTE_HORIZONTAL[] = "\xef\x8c\x83"; +constexpr const char DISTRIBUTE_VERTICAL[] = "\xef\x8c\x84"; +constexpr const char FILE_EARMARK_IMAGE[] = "\xef\x8d\xad"; +constexpr const char FILES[] = "\xef\x8f\x82"; +constexpr const char INFO_CIRCLE[] = "\xef\x90\xb1"; +constexpr const char PALETTE[] = "\xef\x92\xb1"; +constexpr const char PLUS_SLASH_MINUS[] = "\xef\x9a\xaa"; +constexpr const char SAVE[] = "\xef\x94\xa5"; +constexpr const char SLIDERS[] = "\xef\x95\xab"; +constexpr const char TRASH[] = "\xef\x97\x9e"; +constexpr const char X_SQUARE[] = "\xef\x98\xa9"; +constexpr const char ZOOM_OUT[] = "\xef\x98\xad"; +} // namespace icon + +void icon_add_font(float size, bool merge = false, const ImFont *base_font = nullptr); +bool icon_menu_item(const char *glyph, + const char *label, + const char *shortcut = nullptr, + bool selected = false, + bool enabled = true); + +// ***** +// app session, UI state, & internal API +// ***** + +class AsyncRouteLoader; +class CameraFeedView; +class ThumbnailView; +class StreamPoller; +class MapDataManager; + +enum class SessionDataMode : uint8_t { + Route, + Stream, +}; + +enum class StreamSourceKind : uint8_t { + CerealLocal, + CerealRemote, +}; + +struct StreamSourceConfig { + StreamSourceKind kind = StreamSourceKind::CerealLocal; + std::string address = "127.0.0.1"; +}; + +struct BrowserNode { + std::string label; + std::string full_path; + std::vector children; +}; + +struct AppSession { + std::filesystem::path layout_path; + std::filesystem::path autosave_path; + std::string route_name; + std::string data_dir; + std::string dbc_override; + StreamSourceConfig stream_source; + double stream_buffer_seconds = 30.0; + SessionDataMode data_mode = SessionDataMode::Route; + RouteIdentifier route_id; + SketchLayout layout; + RouteData route_data; + std::unordered_map series_by_path; + std::vector browser_nodes; + std::unique_ptr route_loader; + std::unique_ptr stream_poller; + std::array, 4> pane_camera_feeds; + std::unique_ptr thumbnail_view; + std::unique_ptr map_data; + bool async_route_loading = false; + double next_stream_custom_refresh_time = 0.0; + bool stream_paused = false; + std::optional stream_time_offset; +}; + +struct TabUiState { + struct MapPaneState { + bool initialized = false; + bool follow = false; + float zoom = 1.0f; + double center_lat = 0.0; + double center_lon = 0.0; + }; + + struct CameraPaneState { + bool fit_to_pane = true; + }; + + bool dock_needs_build = true; + int active_pane_index = 0; + int runtime_id = 0; + ImVec2 last_dockspace_size = ImVec2(0.0f, 0.0f); + std::vector map_panes; + std::vector camera_panes; +}; + +struct CustomSeriesEditorState { + bool open = false; + bool open_help = false; + bool request_select = false; + bool selected = false; + bool focus_name = false; + int selected_template = 0; + int selected_additional_source = -1; + std::string name; + std::string linked_source; + std::vector additional_sources; + std::string globals_code; + std::string function_code = "return value"; + std::string preview_label; + std::vector preview_xs; + std::vector preview_ys; + bool preview_is_result = false; +}; + +enum class LogTimeMode : uint8_t { + Route, + Boot, + WallClock, +}; + +struct LogsUiState { + bool selected = false; + bool request_select = false; + bool all_sources = true; + uint32_t enabled_levels_mask = 0b11110; + int expanded_index = -1; + std::string search; + std::vector selected_sources; + double last_auto_scroll_time = -1.0; + LogTimeMode time_mode = LogTimeMode::Route; +}; + +struct AxisLimitsEditorState { + bool open = false; + int pane_index = -1; + double x_min = 0.0; + double x_max = 1.0; + bool y_min_enabled = false; + bool y_max_enabled = false; + double y_min = 0.0; + double y_max = 1.0; +}; + +struct DbcEditorState { + bool open = false; + bool loaded = false; + std::string source_name; + std::filesystem::path source_path; + enum class SourceKind : uint8_t { + None, + Generated, + Opendbc, + }; + SourceKind source_kind = SourceKind::None; + std::string save_name; + std::string text; +}; + +enum class TimelineDragMode : uint8_t { + None, + ScrubCursor, + PanViewport, + ResizeLeft, + ResizeRight, +}; + +struct UndoStack { + static constexpr size_t kMaxHistory = 50; + + std::vector history; + int position = -1; + + void reset(const SketchLayout &layout) { + history.clear(); + history.push_back(layout); + position = 0; + } + + void push(const SketchLayout &layout) { + if (position < 0) { + reset(layout); + return; + } + if (position + 1 < static_cast(history.size())) { + history.resize(static_cast(position + 1)); + } + history.push_back(layout); + if (history.size() > kMaxHistory) { + history.erase(history.begin()); + } + position = static_cast(history.size()) - 1; + } + + bool can_undo() const { + return position > 0; + } + + bool can_redo() const { + return position >= 0 && position + 1 < static_cast(history.size()); + } + + const SketchLayout &undo() { + return history[static_cast(--position)]; + } + + const SketchLayout &redo() { + return history[static_cast(++position)]; + } +}; + +struct UiState { + bool open_open_route = false; + bool open_stream = false; + bool open_load_layout = false; + bool open_save_layout = false; + bool open_preferences = false; + bool open_find_signal = false; + bool request_close = false; + bool request_reset_layout = false; + bool request_save_layout = false; + bool request_new_tab = false; + bool request_duplicate_tab = false; + bool request_close_tab = false; + bool follow_latest = false; + bool has_shared_range = false; + bool has_tracker_time = false; + bool layout_dirty = false; + bool playback_loop = false; + bool playback_playing = false; + bool show_deprecated_fields = false; + bool show_fps_overlay = false; + bool fps_overlay_initialized = false; + bool suppress_range_side_effects = false; + bool browser_nodes_dirty = false; + int active_tab_index = 0; + int next_tab_runtime_id = 1; + int requested_tab_index = -1; + int rename_tab_index = -1; + bool focus_rename_tab_input = false; + std::vector tabs; + std::string route_buffer; + std::string stream_address_buffer; + std::string rename_tab_buffer; + std::string browser_filter; + std::string data_dir_buffer; + std::string load_layout_buffer; + std::string save_layout_buffer; + std::string find_signal_buffer; + std::string selected_browser_path; + std::vector selected_browser_paths; + std::string browser_selection_anchor; + std::string route_slice_buffer; + std::string error_text; + bool open_error_popup = false; + std::string status_text = "Ready"; + std::string route_copy_feedback_text; + double route_copy_feedback_until = 0.0; + bool editing_route_slice = false; + bool focus_route_slice_input = false; + StreamSourceKind stream_source_kind = StreamSourceKind::CerealLocal; + float sidebar_width = 320.0f; + double route_x_min = 0.0; + double route_x_max = 1.0; + double x_view_min = 0.0; + double x_view_max = 1.0; + double tracker_time = 0.0; + double playback_rate = 1.0; + double playback_step = 0.1; + double stream_buffer_seconds = 30.0; + TimelineDragMode timeline_drag_mode = TimelineDragMode::None; + double timeline_drag_anchor_time = 0.0; + double timeline_drag_anchor_x_min = 0.0; + double timeline_drag_anchor_x_max = 0.0; + AxisLimitsEditorState axis_limits; + DbcEditorState dbc_editor; + CustomSeriesEditorState custom_series; + LogsUiState logs; + UndoStack undo; +}; + +// app.cc public API + +const WorkspaceTab *app_active_tab(const SketchLayout &layout, const UiState &state); +WorkspaceTab *app_active_tab(SketchLayout *layout, const UiState &state); +TabUiState *app_active_tab_state(UiState *state); + +void app_push_mono_font(); +void app_pop_mono_font(); +bool app_add_curve_to_active_pane(AppSession *session, UiState *state, const std::string &path); + +std::string app_curve_display_name(const Curve &curve); +std::array app_next_curve_color(const Pane &pane); +const RouteSeries *app_find_route_series(const AppSession &session, const std::string &path); +void app_decimate_samples(const std::vector &xs_in, + const std::vector &ys_in, + int max_points, + std::vector *xs_out, + std::vector *ys_out); +std::optional app_sample_xy_value_at_time(const std::vector &xs, + const std::vector &ys, + bool stairs, + double tm); +void save_layout_json(const SketchLayout &layout, const std::filesystem::path &path); + +// ***** +// browser +// ***** + +void rebuild_route_index(AppSession *session); +void rebuild_browser_nodes(AppSession *session, UiState *state); +SeriesFormat compute_series_format(const std::vector &values, bool enum_like = false); +std::string format_display_value(double display_value, + const SeriesFormat &format, + const EnumInfo *enum_info); +std::vector decode_browser_drag_payload(std::string_view payload); +void collect_visible_leaf_paths(const BrowserNode &node, + const std::string &filter, + std::vector *out); +void draw_browser_node(AppSession *session, + const BrowserNode &node, + UiState *state, + const std::string &filter, + const std::vector &visible_paths); + +// ***** +// custom series +// ***** + +void open_custom_series_editor(UiState *state, const std::string &preferred_source = {}); +std::string preferred_custom_series_source(const Pane &pane); +void refresh_all_custom_curves(AppSession *session, UiState *state); +void draw_custom_series_editor(AppSession *session, UiState *state); + +// ***** +// logs +// ***** + +void draw_logs_tab(AppSession *session, UiState *state); + +// ***** +// map +// ***** + +void draw_map_pane(AppSession *session, UiState *state, Pane *pane, int pane_index); + +// ***** +// runtime (GLFW, async loaders, streaming, camera) +// ***** + +struct GLFWwindow; + +struct RouteLoadSnapshot { + bool active = false; + size_t total_segments = 0; + size_t segments_downloaded = 0; + size_t segments_parsed = 0; +}; + +struct StreamPollSnapshot { + bool active = false; + bool connected = false; + bool paused = false; + StreamSourceKind source_kind = StreamSourceKind::CerealLocal; + std::string source_label; + std::string dbc_name; + std::string car_fingerprint; + double buffer_seconds = 30.0; + uint64_t received_messages = 0; +}; + +class GlfwRuntime { +public: + explicit GlfwRuntime(const Options &options); + ~GlfwRuntime(); + + GlfwRuntime(const GlfwRuntime &) = delete; + GlfwRuntime &operator=(const GlfwRuntime &) = delete; + + GLFWwindow *window() const; + +private: + GLFWwindow *window_ = nullptr; +}; + +class ImGuiRuntime { +public: + explicit ImGuiRuntime(GLFWwindow *window); + ~ImGuiRuntime(); + + ImGuiRuntime(const ImGuiRuntime &) = delete; + ImGuiRuntime &operator=(const ImGuiRuntime &) = delete; +}; + +class TerminalRouteProgress { +public: + explicit TerminalRouteProgress(bool enabled); + ~TerminalRouteProgress(); + + TerminalRouteProgress(const TerminalRouteProgress &) = delete; + TerminalRouteProgress &operator=(const TerminalRouteProgress &) = delete; + + void update(const RouteLoadProgress &progress); + void finish(); + +private: + struct Impl; + std::unique_ptr impl_; +}; + +class AsyncRouteLoader { +public: + explicit AsyncRouteLoader(bool enable_terminal_progress); + ~AsyncRouteLoader(); + + AsyncRouteLoader(const AsyncRouteLoader &) = delete; + AsyncRouteLoader &operator=(const AsyncRouteLoader &) = delete; + + void start(const std::string &route_name, const std::string &data_dir, const std::string &dbc_name); + RouteLoadSnapshot snapshot() const; + bool consume(RouteData *route_data, std::string *error_text); + +private: + struct Impl; + std::unique_ptr impl_; +}; + +class StreamPoller { +public: + StreamPoller(); + ~StreamPoller(); + + StreamPoller(const StreamPoller &) = delete; + StreamPoller &operator=(const StreamPoller &) = delete; + + void start(const StreamSourceConfig &source, + double buffer_seconds, + const std::string &dbc_name, + std::optional time_offset = std::nullopt); + void setPaused(bool paused); + void stop(); + StreamPollSnapshot snapshot() const; + bool consume(StreamExtractBatch *batch, std::string *error_text); + +private: + struct Impl; + std::unique_ptr impl_; +}; + +class CameraFeedView { +public: + CameraFeedView(); + ~CameraFeedView(); + + CameraFeedView(const CameraFeedView &) = delete; + CameraFeedView &operator=(const CameraFeedView &) = delete; + + void setRouteData(const RouteData &route_data); + void setCameraIndex(const CameraFeedIndex &camera_index, CameraViewKind view); + void update(double tracker_time); + void draw(float width, bool loading); + void drawSized(ImVec2 size, bool loading, bool fit_to_pane = false); + +private: + struct Impl; + std::unique_ptr impl_; +}; + +class ThumbnailView { +public: + ThumbnailView(); + ~ThumbnailView(); + + ThumbnailView(const ThumbnailView &) = delete; + ThumbnailView &operator=(const ThumbnailView &) = delete; + + void setThumbnails(const std::vector &thumbnails); + void update(double tracker_time); + void drawSized(ImVec2 size, bool loading); + +private: + struct Impl; + std::unique_ptr impl_; +}; diff --git a/openpilot/tools/jotpluggler/browser.cc b/openpilot/tools/jotpluggler/browser.cc new file mode 100644 index 0000000000..91e4a707da --- /dev/null +++ b/openpilot/tools/jotpluggler/browser.cc @@ -0,0 +1,458 @@ +#include "tools/jotpluggler/app.h" + +#include "imgui_internal.h" + +#include +#include +#include + +namespace { + +constexpr float BROWSER_VALUE_WIDTH = 88.0f; + +bool path_matches_filter(const std::string &path, const std::string &lower_filter) { + if (lower_filter.empty()) return true; + return lowercase_copy(path).find(lower_filter) != std::string::npos; +} + +void insert_browser_path(std::vector *nodes, const std::string &path) { + size_t start = 0; + while (start < path.size() && path[start] == '/') { + ++start; + } + std::vector parts; + while (start < path.size()) { + const size_t end = path.find('/', start); + parts.push_back(path.substr(start, end == std::string::npos ? std::string::npos : end - start)); + if (end == std::string::npos) break; + start = end + 1; + } + if (parts.empty()) { + return; + } + + std::vector *current_nodes = nodes; + std::string current_path; + for (size_t i = 0; i < parts.size(); ++i) { + if (!current_path.empty()) { + current_path += "/"; + } + current_path += parts[i]; + auto it = std::find_if(current_nodes->begin(), current_nodes->end(), + [&](const BrowserNode &node) { return node.label == parts[i]; }); + if (it == current_nodes->end()) { + current_nodes->push_back(BrowserNode{.label = parts[i]}); + it = std::prev(current_nodes->end()); + } + if (i + 1 == parts.size()) { + it->full_path = "/" + current_path; + } + current_nodes = &it->children; + } +} + +void sort_browser_nodes(std::vector *nodes) { + std::sort(nodes->begin(), nodes->end(), [](const BrowserNode &a, const BrowserNode &b) { + if (a.children.empty() != b.children.empty()) { + return !a.children.empty(); + } + return a.label < b.label; + }); + for (BrowserNode &node : *nodes) { + sort_browser_nodes(&node.children); + } +} + +std::vector build_browser_tree(const std::vector &paths) { + std::vector nodes; + for (const std::string &path : paths) { + insert_browser_path(&nodes, path); + } + sort_browser_nodes(&nodes); + return nodes; +} + +bool is_deprecated_browser_path(const std::string &path) { + return path.find("DEPRECATED") != std::string::npos || path.find("/deprecated/") != std::string::npos; +} + +std::vector visible_browser_paths(const RouteData &route_data, bool show_deprecated_fields) { + if (show_deprecated_fields) return route_data.paths; + std::vector filtered; + filtered.reserve(route_data.paths.size()); + for (const std::string &path : route_data.paths) { + if (!is_deprecated_browser_path(path)) { + filtered.push_back(path); + } + } + return filtered; +} + +bool browser_selection_contains(const UiState &state, std::string_view path) { + return std::find(state.selected_browser_paths.begin(), state.selected_browser_paths.end(), path) + != state.selected_browser_paths.end(); +} + +std::vector browser_drag_paths(const UiState &state, const std::string &dragged_path) { + if (browser_selection_contains(state, dragged_path) && !state.selected_browser_paths.empty()) { + return state.selected_browser_paths; + } + return {dragged_path}; +} + +std::string encode_browser_drag_payload(const std::vector &paths) { + std::string payload; + for (size_t i = 0; i < paths.size(); ++i) { + if (i != 0) { + payload.push_back('\n'); + } + payload += paths[i]; + } + return payload; +} + +void set_browser_selection_single(UiState *state, const std::string &path) { + state->selected_browser_paths = {path}; + state->selected_browser_path = path; + state->browser_selection_anchor = path; +} + +void toggle_browser_selection(UiState *state, const std::string &path) { + auto it = std::find(state->selected_browser_paths.begin(), state->selected_browser_paths.end(), path); + if (it == state->selected_browser_paths.end()) { + state->selected_browser_paths.push_back(path); + } else { + state->selected_browser_paths.erase(it); + } + state->selected_browser_path = path; + state->browser_selection_anchor = path; + if (state->selected_browser_paths.empty()) { + state->selected_browser_path.clear(); + } +} + +void select_browser_range(UiState *state, const std::vector &visible_paths, const std::string &clicked_path) { + if (visible_paths.empty()) { + set_browser_selection_single(state, clicked_path); + return; + } + + const std::string anchor = state->browser_selection_anchor.empty() ? clicked_path : state->browser_selection_anchor; + const auto anchor_it = std::find(visible_paths.begin(), visible_paths.end(), anchor); + const auto clicked_it = std::find(visible_paths.begin(), visible_paths.end(), clicked_path); + if (clicked_it == visible_paths.end()) { + return; + } + if (anchor_it == visible_paths.end()) { + set_browser_selection_single(state, clicked_path); + return; + } + + const auto [begin_it, end_it] = std::minmax(anchor_it, clicked_it); + std::vector selected; + selected.reserve(static_cast(std::distance(begin_it, end_it)) + 1); + for (auto it = begin_it; it != end_it + 1; ++it) { + selected.push_back(*it); + } + state->selected_browser_paths = std::move(selected); + state->selected_browser_path = clicked_path; +} + +void prune_browser_selection(UiState *state, const std::vector &visible_paths) { + const std::unordered_set visible_set(visible_paths.begin(), visible_paths.end()); + auto is_visible = [&](const std::string &path) { + return visible_set.count(path) > 0; + }; + + state->selected_browser_paths.erase( + std::remove_if(state->selected_browser_paths.begin(), state->selected_browser_paths.end(), + [&](const std::string &path) { return !is_visible(path); }), + state->selected_browser_paths.end()); + + if (!state->selected_browser_path.empty() && !is_visible(state->selected_browser_path)) { + state->selected_browser_path.clear(); + } + if (!state->browser_selection_anchor.empty() && !is_visible(state->browser_selection_anchor)) { + state->browser_selection_anchor.clear(); + } + if (state->selected_browser_paths.empty()) { + state->selected_browser_path.clear(); + } else if (state->selected_browser_path.empty()) { + state->selected_browser_path = state->selected_browser_paths.back(); + } +} + +std::optional sample_route_series_value(const RouteSeries &series, double tm, bool stairs) { + return app_sample_xy_value_at_time(series.times, series.values, stairs, tm); +} + +std::string browser_series_value_text(const AppSession &session, const UiState &state, std::string_view path) { + auto it = session.series_by_path.find(std::string(path)); + if (it == session.series_by_path.end() || it->second == nullptr) return {}; + + const RouteSeries &series = *it->second; + if (series.values.empty()) return {}; + + const auto enum_it = session.route_data.enum_info.find(series.path); + const EnumInfo *enum_info = enum_it == session.route_data.enum_info.end() ? nullptr : &enum_it->second; + const bool stairs = enum_info != nullptr; + + std::optional value; + if (state.has_tracker_time) { + value = sample_route_series_value(series, state.tracker_time, stairs); + } else { + value = series.values.back(); + } + if (!value.has_value()) return {}; + + const auto display_it = session.route_data.series_formats.find(series.path); + const SeriesFormat display_info = display_it == session.route_data.series_formats.end() + ? compute_series_format(series.values, enum_info != nullptr) + : display_it->second; + + return format_display_value(*value, display_info, enum_info); +} + +bool browser_node_matches(const BrowserNode &node, const std::string &filter) { + if (filter.empty()) return true; + if (!node.full_path.empty() && path_matches_filter(node.full_path, filter)) { + return true; + } + for (const BrowserNode &child : node.children) { + if (browser_node_matches(child, filter)) return true; + } + return false; +} + +} // namespace + +namespace { + +int decimals_needed(double value) { + const double abs_value = std::abs(value); + if (abs_value < 1.0e-12) return 0; + for (int decimals = 0; decimals <= 6; ++decimals) { + const double scale = std::pow(10.0, decimals); + if (std::abs(abs_value * scale - std::round(abs_value * scale)) < 1.0e-6) { + return decimals; + } + } + return 6; +} + +void finalize_series_format(SeriesFormat *format) { + format->digits_before = std::max(format->digits_before, 1); + format->decimals = std::clamp(format->decimals, 0, 6); + format->integer_like = format->decimals == 0; + const int sign_width = format->has_negative ? 1 : 0; + const int dot_width = format->decimals > 0 ? 1 : 0; + format->total_width = sign_width + format->digits_before + dot_width + format->decimals; + std::snprintf(format->fmt, sizeof(format->fmt), "%%%d.%df", format->total_width, format->decimals); +} + +} // namespace + +SeriesFormat compute_series_format(const std::vector &values, bool enum_like) { + SeriesFormat format; + if (values.empty()) return format; + + const size_t step = std::max(1, values.size() / 256); + bool saw_finite = false; + bool all_integer = enum_like; + double min_value = 0.0; + double max_value = 0.0; + int max_needed_decimals = 0; + + for (size_t i = 0; i < values.size(); i += step) { + const double value = values[i]; + if (!std::isfinite(value)) continue; + if (!saw_finite) { + min_value = value; + max_value = value; + saw_finite = true; + } else { + min_value = std::min(min_value, value); + max_value = std::max(max_value, value); + } + if (std::abs(value - std::round(value)) > 1.0e-9) { + all_integer = false; + } + if (!all_integer) { + max_needed_decimals = std::max(max_needed_decimals, decimals_needed(value)); + } + } + + if (!saw_finite) return format; + + format.has_negative = min_value < 0.0; + const double peak = std::max(std::abs(min_value), std::abs(max_value)); + format.digits_before = peak < 1.0 ? 1 : static_cast(std::floor(std::log10(peak))) + 1; + + if (enum_like || all_integer) { + format.decimals = 0; + } else if (peak >= 1000.0) { + format.decimals = std::min(max_needed_decimals, 1); + } else if (peak >= 100.0) { + format.decimals = std::min(max_needed_decimals, 2); + } else { + format.decimals = std::min(max_needed_decimals, 4); + } + + finalize_series_format(&format); + return format; +} + +std::string format_display_value(double display_value, + const SeriesFormat &display_info, + const EnumInfo *enum_info) { + if (!std::isfinite(display_value)) return "---"; + if (enum_info != nullptr) { + const int idx = static_cast(std::llround(display_value)); + if (idx >= 0 && std::abs(display_value - static_cast(idx)) < 0.01 + && static_cast(idx) < enum_info->names.size() + && !enum_info->names[static_cast(idx)].empty()) { + return enum_info->names[static_cast(idx)]; + } + } + char buf[64] = {}; + std::snprintf(buf, sizeof(buf), display_info.fmt, display_value); + return buf; +} + +std::vector decode_browser_drag_payload(std::string_view payload) { + std::vector out; + size_t begin = 0; + while (begin <= payload.size()) { + const size_t end = payload.find('\n', begin); + const size_t length = (end == std::string_view::npos ? payload.size() : end) - begin; + if (length > 0) { + out.emplace_back(payload.substr(begin, length)); + } + if (end == std::string_view::npos) break; + begin = end + 1; + } + return out; +} + +void collect_visible_leaf_paths(const BrowserNode &node, + const std::string &filter, + std::vector *out) { + if (!browser_node_matches(node, filter)) { + return; + } + if (node.children.empty()) { + if (!node.full_path.empty()) { + out->push_back(node.full_path); + } + return; + } + for (const BrowserNode &child : node.children) { + collect_visible_leaf_paths(child, filter, out); + } +} + +void rebuild_browser_nodes(AppSession *session, UiState *state) { + const std::vector paths = visible_browser_paths(session->route_data, state->show_deprecated_fields); + session->browser_nodes = build_browser_tree(paths); + prune_browser_selection(state, paths); +} + +void rebuild_route_index(AppSession *session) { + session->series_by_path.clear(); + session->route_data.series_formats.clear(); + for (RouteSeries &series : session->route_data.series) { + session->series_by_path.emplace(series.path, &series); + const bool enum_like = session->route_data.enum_info.find(series.path) != session->route_data.enum_info.end(); + session->route_data.series_formats.emplace(series.path, compute_series_format(series.values, enum_like)); + } +} + +void draw_browser_node(AppSession *session, + const BrowserNode &node, + UiState *state, + const std::string &filter, + const std::vector &visible_paths) { + if (!browser_node_matches(node, filter)) { + return; + } + + if (node.children.empty()) { + const std::string value_text = browser_series_value_text(*session, *state, node.full_path); + const ImGuiStyle &style = ImGui::GetStyle(); + const ImVec2 row_size(std::max(1.0f, ImGui::GetContentRegionAvail().x), ImGui::GetFrameHeight()); + ImGui::PushID(node.full_path.c_str()); + const bool clicked = ImGui::InvisibleButton("##browser_leaf", row_size); + const bool hovered = ImGui::IsItemHovered(); + const ImRect rect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax()); + ImDrawList *draw_list = ImGui::GetWindowDrawList(); + if (hovered) { + const ImU32 bg = ImGui::GetColorU32(ImGuiCol_HeaderHovered); + draw_list->AddRectFilled(rect.Min, rect.Max, bg, 0.0f); + } + + const float value_right = rect.Max.x - style.FramePadding.x; + const float value_left = value_right - (value_text.empty() ? 0.0f : BROWSER_VALUE_WIDTH); + const float label_left = rect.Min.x + style.FramePadding.x; + const float label_right = value_text.empty() + ? rect.Max.x - style.FramePadding.x + : std::max(label_left + 40.0f, value_left - 10.0f); + ImGui::RenderTextEllipsis(draw_list, + ImVec2(label_left, rect.Min.y + style.FramePadding.y), + ImVec2(label_right, rect.Max.y), + label_right, + node.label.c_str(), + nullptr, + nullptr); + if (!value_text.empty()) { + app_push_mono_font(); + ImGui::PushStyleColor(ImGuiCol_Text, color_rgb(116, 124, 133)); + ImGui::RenderTextClipped(ImVec2(value_left, rect.Min.y + style.FramePadding.y), + ImVec2(value_right, rect.Max.y), + value_text.c_str(), + nullptr, + nullptr, + ImVec2(1.0f, 0.0f)); + ImGui::PopStyleColor(); + app_pop_mono_font(); + } + + if (clicked) { + const bool shift_down = ImGui::GetIO().KeyShift; + const bool ctrl_down = ImGui::GetIO().KeyCtrl || ImGui::GetIO().KeySuper; + if (shift_down) { + select_browser_range(state, visible_paths, node.full_path); + } else if (ctrl_down) { + toggle_browser_selection(state, node.full_path); + } else { + set_browser_selection_single(state, node.full_path); + } + } + if (hovered && ImGui::IsMouseDoubleClicked(0)) { + set_browser_selection_single(state, node.full_path); + app_add_curve_to_active_pane(session, state, node.full_path); + } + if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_SourceAllowNullID)) { + const std::vector drag_paths = browser_drag_paths(*state, node.full_path); + const std::string payload = encode_browser_drag_payload(drag_paths); + ImGui::SetDragDropPayload("JOTP_BROWSER_PATHS", payload.c_str(), payload.size() + 1); + if (drag_paths.size() == 1) { + ImGui::TextUnformatted(drag_paths.front().c_str()); + } else { + ImGui::Text("%zu timeseries", drag_paths.size()); + ImGui::TextUnformatted(drag_paths.front().c_str()); + } + ImGui::EndDragDropSource(); + } + ImGui::PopID(); + return; + } + + ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_SpanAvailWidth; + const bool open = ImGui::TreeNodeEx(node.label.c_str(), flags); + if (open) { + for (const BrowserNode &child : node.children) { + draw_browser_node(session, child, state, filter, visible_paths); + } + ImGui::TreePop(); + } +} diff --git a/openpilot/tools/jotpluggler/camera.cc b/openpilot/tools/jotpluggler/camera.cc new file mode 100644 index 0000000000..24a35d8794 --- /dev/null +++ b/openpilot/tools/jotpluggler/camera.cc @@ -0,0 +1,54 @@ +#include "tools/jotpluggler/camera.h" + +#include "imgui.h" +#include "imgui_internal.h" + +namespace { + +bool draw_camera_fit_toggle_overlay(bool fit_to_pane) { + const ImVec2 window_pos = ImGui::GetWindowPos(); + const ImVec2 content_min = ImGui::GetWindowContentRegionMin(); + const ImRect rect(ImVec2(window_pos.x + content_min.x + 8.0f, window_pos.y + content_min.y + 8.0f), + ImVec2(window_pos.x + content_min.x + 58.0f, window_pos.y + content_min.y + 28.0f)); + const bool hovered = ImGui::IsMouseHoveringRect(rect.Min, rect.Max, false); + const bool held = hovered && ImGui::IsMouseDown(ImGuiMouseButton_Left); + if (hovered) ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + + ImDrawList *draw_list = ImGui::GetWindowDrawList(); + draw_list->AddRectFilled(rect.Min, rect.Max, hovered ? IM_COL32(255, 255, 255, 234) : IM_COL32(255, 255, 255, 214), 4.0f); + draw_list->AddRect(rect.Min, rect.Max, IM_COL32(184, 189, 196, 255), 4.0f, 0, 1.0f); + const ImRect box(ImVec2(rect.Min.x + 6.0f, rect.Min.y + 4.0f), ImVec2(rect.Min.x + 18.0f, rect.Min.y + 16.0f)); + draw_list->AddRect(box.Min, box.Max, IM_COL32(112, 120, 129, 255), 2.0f, 0, 1.0f); + if (fit_to_pane) { + draw_list->AddLine(ImVec2(box.Min.x + 2.5f, box.Min.y + 6.5f), ImVec2(box.Min.x + 5.5f, box.Max.y - 2.5f), IM_COL32(60, 111, 202, 255), 1.8f); + draw_list->AddLine(ImVec2(box.Min.x + 5.5f, box.Max.y - 2.5f), ImVec2(box.Max.x - 2.5f, box.Min.y + 2.5f), IM_COL32(60, 111, 202, 255), 1.8f); + } + draw_list->AddText(ImVec2(box.Max.x + 6.0f, rect.Min.y + 3.0f), IM_COL32(72, 79, 88, 255), "Fit"); + return hovered && !held && ImGui::IsMouseReleased(ImGuiMouseButton_Left); +} + +} // namespace + +void draw_camera_pane(AppSession *session, UiState *state, TabUiState *tab_state, int pane_index, const Pane &pane) { + CameraFeedView *feed = session->pane_camera_feeds[static_cast(pane.camera_view)].get(); + if (feed == nullptr) { + ImGui::TextDisabled("Camera unavailable"); + return; + } + + const bool fit_to_pane = tab_state != nullptr + && pane_index >= 0 + && pane_index < static_cast(tab_state->camera_panes.size()) + ? tab_state->camera_panes[static_cast(pane_index)].fit_to_pane + : true; + if (state->has_tracker_time) { + feed->update(state->tracker_time); + } + feed->drawSized(ImGui::GetContentRegionAvail(), session->async_route_loading, fit_to_pane); + if (tab_state != nullptr + && pane_index >= 0 + && pane_index < static_cast(tab_state->camera_panes.size()) + && draw_camera_fit_toggle_overlay(fit_to_pane)) { + tab_state->camera_panes[static_cast(pane_index)].fit_to_pane = !fit_to_pane; + } +} diff --git a/openpilot/tools/jotpluggler/camera.h b/openpilot/tools/jotpluggler/camera.h new file mode 100644 index 0000000000..666e335af8 --- /dev/null +++ b/openpilot/tools/jotpluggler/camera.h @@ -0,0 +1,5 @@ +#pragma once + +#include "tools/jotpluggler/app.h" + +void draw_camera_pane(AppSession *session, UiState *state, TabUiState *tab_state, int pane_index, const Pane &pane); diff --git a/openpilot/tools/jotpluggler/common.cc b/openpilot/tools/jotpluggler/common.cc new file mode 100644 index 0000000000..50f5fc0b95 --- /dev/null +++ b/openpilot/tools/jotpluggler/common.cc @@ -0,0 +1,187 @@ +#include "tools/jotpluggler/common.h" + +#include +#include +#include + +namespace { + +std::string format_coord(const GpsPoint &point) { + return util::string_format("%.5f,%.5f", point.lat, point.lon); +} + +} // namespace + +const CameraViewSpec &camera_view_spec(CameraViewKind view) { + auto it = std::find_if(kCameraViewSpecs.begin(), kCameraViewSpecs.end(), [&](const CameraViewSpec &spec) { + return spec.view == view; + }); + return it != kCameraViewSpecs.end() ? *it : kCameraViewSpecs.front(); +} + +const CameraViewSpec *camera_view_spec_from_special_item(std::string_view item_id) { + auto it = std::find_if(kCameraViewSpecs.begin(), kCameraViewSpecs.end(), [&](const CameraViewSpec &spec) { + return item_id == spec.special_item_id; + }); + return it != kCameraViewSpecs.end() ? &*it : nullptr; +} + +const CameraViewSpec *camera_view_spec_from_layout_name(std::string_view layout_name) { + auto it = std::find_if(kCameraViewSpecs.begin(), kCameraViewSpecs.end(), [&](const CameraViewSpec &spec) { + return layout_name == spec.layout_name; + }); + return it != kCameraViewSpecs.end() ? &*it : nullptr; +} + +const SpecialItemSpec *special_item_spec(std::string_view item_id) { + auto it = std::find_if(kSpecialItemSpecs.begin(), kSpecialItemSpecs.end(), [&](const SpecialItemSpec &spec) { + return item_id == spec.id; + }); + return it != kSpecialItemSpecs.end() ? &*it : nullptr; +} + +const char *special_item_label(std::string_view item_id) { + const SpecialItemSpec *spec = special_item_spec(item_id); + return spec != nullptr ? spec->label : "Item"; +} + +bool pane_kind_is_special(PaneKind kind) { + return kind == PaneKind::Map || kind == PaneKind::Thumbnail || kind == PaneKind::Camera; +} + +bool is_default_special_title(std::string_view title) { + if (title == "Map" || title == "Thumbnail") return true; + return std::any_of(kCameraViewSpecs.begin(), kCameraViewSpecs.end(), [&](const CameraViewSpec &spec) { + return title == spec.label; + }); +} + +CameraViewKind sidebar_preview_camera_view(const AppSession &session) { + return session.route_data.road_camera.entries.empty() && !session.route_data.qroad_camera.entries.empty() + ? CameraViewKind::QRoad + : CameraViewKind::Road; +} + +const std::filesystem::path &repo_root() { + static const std::filesystem::path root(JOTP_REPO_ROOT); + return root; +} + +ImU32 timeline_entry_color(TimelineEntry::Type type, float alpha) { + return timeline_entry_color(type, alpha, {111, 143, 175}); +} + +ImU32 timeline_entry_color(TimelineEntry::Type type, float alpha, std::array none_color) { + switch (type) { + case TimelineEntry::Type::Engaged: + return ImGui::GetColorU32(color_rgb(0, 163, 108, alpha)); + case TimelineEntry::Type::AlertInfo: + return ImGui::GetColorU32(color_rgb(255, 195, 0, alpha)); + case TimelineEntry::Type::AlertWarning: + case TimelineEntry::Type::AlertCritical: + return ImGui::GetColorU32(color_rgb(199, 0, 57, alpha)); + case TimelineEntry::Type::None: + default: + return ImGui::GetColorU32(color_rgb(none_color, alpha)); + } +} + +const char *timeline_entry_label(TimelineEntry::Type type) { + static constexpr const char *kLabels[] = { + "disengaged", + "engaged", + "alert info", + "alert warning", + "alert critical", + }; + const size_t index = static_cast(type); + return index < std::size(kLabels) ? kLabels[index] : kLabels[0]; +} + +TimelineEntry::Type timeline_type_at_time(const std::vector &timeline, double time_value) { + for (const TimelineEntry &entry : timeline) { + if (time_value >= entry.start_time && time_value <= entry.end_time) { + return entry.type; + } + } + return TimelineEntry::Type::None; +} + +std::string normalize_stream_address(std::string address) { + return is_local_stream_address(address) ? "127.0.0.1" : address; +} + +const char *stream_source_kind_label(StreamSourceKind kind) { + static constexpr const char *kLabels[] = { + "Local (MSGQ)", + "Remote (ZMQ)", + }; + const size_t index = static_cast(kind); + return index < std::size(kLabels) ? kLabels[index] : kLabels[0]; +} + +std::string stream_source_target_label(const StreamSourceConfig &source) { + switch (source.kind) { + case StreamSourceKind::CerealRemote: + return normalize_stream_address(source.address); + case StreamSourceKind::CerealLocal: + default: + return "127.0.0.1"; + } +} + +bool env_flag_enabled(const char *name, bool default_value) { + const char *raw = std::getenv(name); + if (raw == nullptr || raw[0] == '\0') { + return default_value; + } + const std::string value = lowercase_copy(util::strip(raw)); + return !(value == "0" || value == "false" || value == "no" || value == "off"); +} + +bool app_begin_popup(const char *str_id, ImGuiWindowFlags flags) { + return ImGui::BeginPopup(str_id, flags | ImGuiWindowFlags_NoMove); +} + +bool app_begin_popup_modal(const char *name, bool *p_open, ImGuiWindowFlags flags) { + return ImGui::BeginPopupModal(name, p_open, flags | ImGuiWindowFlags_NoMove); +} + +void open_external_url(std::string_view url) { +#ifdef __APPLE__ + const std::string command = "open " + shell_quote(url) + " &"; +#else + const std::string command = "xdg-open " + shell_quote(url) + " >/dev/null 2>&1 &"; +#endif + util::check_system(command); +} + +std::string route_useradmin_url(const RouteIdentifier &route_id) { + return route_id.empty() ? std::string() + : "https://useradmin.comma.ai/?onebox=" + route_id.dongle_id + "%7C" + route_id.log_id; +} + +std::string route_connect_url(const RouteIdentifier &route_id) { + return route_id.empty() ? std::string() + : "https://connect.comma.ai/" + route_id.canonical(); +} + +std::string route_google_maps_url(const GpsTrace &trace) { + if (trace.points.size() < 2) { + return {}; + } + + const std::string prefix = "https://www.google.com/maps/dir/?api=1&travelmode=driving&origin=" + + format_coord(trace.points.front()) + "&destination=" + format_coord(trace.points.back()); + for (size_t n = std::min(9, trace.points.size() > 2 ? trace.points.size() - 2 : 0); ; --n) { + std::string url = prefix; + if (n > 0) { + url += "&waypoints="; + for (size_t i = 0; i < n; ++i) { + if (i) url += "%7C"; + url += format_coord(trace.points[1 + ((trace.points.size() - 2) * (i + 1)) / (n + 1)]); + } + } + if (url.size() <= 1900 || n == 0) return url; + } +} diff --git a/openpilot/tools/jotpluggler/common.h b/openpilot/tools/jotpluggler/common.h new file mode 100644 index 0000000000..5c68b0ed22 --- /dev/null +++ b/openpilot/tools/jotpluggler/common.h @@ -0,0 +1,68 @@ +#pragma once + +#include "tools/jotpluggler/app.h" + +#include +#include + +struct CameraViewSpec { + CameraViewKind view = CameraViewKind::Road; + const char *label = ""; + const char *runtime_name = ""; + const char *layout_name = ""; + const char *special_item_id = ""; + CameraFeedIndex RouteData::*route_member = nullptr; +}; + +struct SpecialItemSpec { + const char *id = ""; + const char *label = ""; + PaneKind kind = PaneKind::Plot; + CameraViewKind camera_view = CameraViewKind::Road; +}; + +inline constexpr std::array kCameraViewSpecs = {{ + {CameraViewKind::Road, "Road Camera", "road", "road", "camera_road", &RouteData::road_camera}, + {CameraViewKind::Driver, "Driver Camera", "driver", "driver", "camera_driver", &RouteData::driver_camera}, + {CameraViewKind::WideRoad, "Wide Road Camera", "wide", "wide_road", "camera_wide_road", &RouteData::wide_road_camera}, + {CameraViewKind::QRoad, "qRoad Camera", "qroad", "qroad", "camera_qroad", &RouteData::qroad_camera}, +}}; + +inline constexpr std::array kSpecialItemSpecs = {{ + {"map", "Map", PaneKind::Map, CameraViewKind::Road}, + {"thumbnail", "Thumbnail", PaneKind::Thumbnail, CameraViewKind::Road}, + {kCameraViewSpecs[0].special_item_id, kCameraViewSpecs[0].label, PaneKind::Camera, kCameraViewSpecs[0].view}, + {kCameraViewSpecs[1].special_item_id, kCameraViewSpecs[1].label, PaneKind::Camera, kCameraViewSpecs[1].view}, + {kCameraViewSpecs[2].special_item_id, kCameraViewSpecs[2].label, PaneKind::Camera, kCameraViewSpecs[2].view}, + {kCameraViewSpecs[3].special_item_id, kCameraViewSpecs[3].label, PaneKind::Camera, kCameraViewSpecs[3].view}, +}}; + +const CameraViewSpec &camera_view_spec(CameraViewKind view); +const CameraViewSpec *camera_view_spec_from_special_item(std::string_view item_id); +const CameraViewSpec *camera_view_spec_from_layout_name(std::string_view layout_name); + +const SpecialItemSpec *special_item_spec(std::string_view item_id); +const char *special_item_label(std::string_view item_id); + +bool pane_kind_is_special(PaneKind kind); +bool is_default_special_title(std::string_view title); +CameraViewKind sidebar_preview_camera_view(const AppSession &session); +const std::filesystem::path &repo_root(); + +ImU32 timeline_entry_color(TimelineEntry::Type type, float alpha = 1.0f); +ImU32 timeline_entry_color(TimelineEntry::Type type, float alpha, std::array none_color); +const char *timeline_entry_label(TimelineEntry::Type type); +TimelineEntry::Type timeline_type_at_time(const std::vector &timeline, double time_value); +std::string normalize_stream_address(std::string address); +const char *stream_source_kind_label(StreamSourceKind kind); +std::string stream_source_target_label(const StreamSourceConfig &source); + +bool env_flag_enabled(const char *name, bool default_value = false); +bool app_begin_popup(const char *str_id, ImGuiWindowFlags flags = 0); +bool app_begin_popup_modal(const char *name, + bool *p_open = nullptr, + ImGuiWindowFlags flags = ImGuiWindowFlags_AlwaysAutoResize); +void open_external_url(std::string_view url); +std::string route_useradmin_url(const RouteIdentifier &route_id); +std::string route_connect_url(const RouteIdentifier &route_id); +std::string route_google_maps_url(const GpsTrace &trace); diff --git a/openpilot/tools/jotpluggler/custom_series.cc b/openpilot/tools/jotpluggler/custom_series.cc new file mode 100644 index 0000000000..70b3e8c3cb --- /dev/null +++ b/openpilot/tools/jotpluggler/custom_series.cc @@ -0,0 +1,750 @@ +#include "tools/jotpluggler/app.h" +#include "tools/jotpluggler/common.h" + +#include "implot.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "json11/json11.hpp" + +namespace fs = std::filesystem; + +namespace { + +struct PythonEvalResult { + std::vector xs; + std::vector ys; +}; + +struct CustomSeriesTemplate { + const char *name; + const char *globals_code; + const char *function_code; + const char *preview_text; + int required_additional_sources; + const char *requirement_text; +}; + +void write_binary_vector(const fs::path &path, const std::vector &values) { + write_file_or_throw(path, values.data(), values.size() * sizeof(double)); +} + +std::vector read_binary_vector(const fs::path &path) { + const std::string raw = read_file_or_throw(path); + if (raw.size() % sizeof(double) != 0) { + throw std::runtime_error("Invalid binary series file: " + path.string()); + } + std::vector values(raw.size() / sizeof(double)); + if (!values.empty()) { + std::memcpy(values.data(), raw.data(), raw.size()); + } + return values; +} + +void write_text_file(const fs::path &path, std::string_view text) { + write_file_or_throw(path, text); +} + +fs::path create_custom_series_temp_dir() { + const auto stamp = std::chrono::steady_clock::now().time_since_epoch().count(); + const fs::path dir = fs::temp_directory_path() / ("jotpluggler_math_" + std::to_string(::getpid()) + "_" + std::to_string(stamp)); + fs::create_directories(dir); + return dir; +} + +void reset_custom_series_editor(CustomSeriesEditorState *editor) { + *editor = CustomSeriesEditorState{}; +} + +bool add_additional_source(CustomSeriesEditorState *editor, const std::string &path) { + if (path.empty() || path == editor->linked_source) return false; + if (std::find(editor->additional_sources.begin(), editor->additional_sources.end(), path) != editor->additional_sources.end()) { + return false; + } + editor->additional_sources.push_back(path); + return true; +} + +std::string next_custom_curve_name(const Pane &pane) { + std::set used; + for (const Curve &curve : pane.curves) { + if (!curve.label.empty()) { + used.insert(curve.label); + } + if (!curve.name.empty()) { + used.insert(curve.name); + } + } + for (int i = 1; i < 1000; ++i) { + const std::string candidate = "series" + std::to_string(i); + if (used.find(candidate) == used.end()) { + return candidate; + } + } + return "series"; +} + +Curve make_custom_curve(const Pane &pane, + const std::string &name, + const CustomPythonSeries &spec, + PythonEvalResult result) { + Curve curve; + curve.name = name; + curve.label = name; + curve.color = app_next_curve_color(pane); + curve.runtime_only = true; + curve.custom_python = spec; + curve.xs = std::move(result.xs); + curve.ys = std::move(result.ys); + return curve; +} + +bool upsert_custom_curve_in_pane(WorkspaceTab *tab, int pane_index, Curve curve) { + if (pane_index < 0 || pane_index >= static_cast(tab->panes.size())) { + return false; + } + Pane &pane = tab->panes[static_cast(pane_index)]; + for (Curve &existing : pane.curves) { + if (existing.runtime_only && existing.name == curve.name) { + existing.visible = true; + existing.label = curve.label; + existing.custom_python = curve.custom_python; + existing.xs = std::move(curve.xs); + existing.ys = std::move(curve.ys); + return false; + } + } + pane.curves.push_back(std::move(curve)); + return true; +} + +std::set collect_custom_series_paths(const CustomPythonSeries &spec, + std::string_view globals_code, + std::string_view function_code) { + std::set paths; + if (!spec.linked_source.empty()) { + paths.insert(spec.linked_source); + } + paths.insert(spec.additional_sources.begin(), spec.additional_sources.end()); + + static const std::regex kPathRegex(R"([tv]\(\s*["']([^"']+)["']\s*\))"); + const auto collect_from = [&](std::string_view code) { + std::string owned(code); + for (std::sregex_iterator it(owned.begin(), owned.end(), kPathRegex), end; it != end; ++it) { + paths.insert((*it)[1].str()); + } + }; + collect_from(globals_code); + collect_from(function_code); + return paths; +} + +PythonEvalResult evaluate_custom_python_series(const AppSession &session, + const CustomPythonSeries &spec) { + const std::set referenced_paths = + collect_custom_series_paths(spec, spec.globals_code, spec.function_code); + if (referenced_paths.empty()) throw std::runtime_error("No input series referenced. Set an input timeseries or reference route paths in code."); + + const fs::path temp_dir = create_custom_series_temp_dir(); + try { + const fs::path globals_path = temp_dir / "globals.py"; + const fs::path code_path = temp_dir / "code.py"; + const fs::path manifest_path = temp_dir / "manifest.json"; + const fs::path out_t_path = temp_dir / "result.t.bin"; + const fs::path out_v_path = temp_dir / "result.v.bin"; + + write_text_file(globals_path, spec.globals_code); + write_text_file(code_path, spec.function_code); + + json11::Json::array paths_json(session.route_data.paths.begin(), session.route_data.paths.end()); + json11::Json::array additional_json(spec.additional_sources.begin(), spec.additional_sources.end()); + json11::Json::array series_json; + size_t series_index = 0; + for (const std::string &path : referenced_paths) { + const RouteSeries *series = app_find_route_series(session, path); + if (series == nullptr || series->times.size() < 2 || series->times.size() != series->values.size()) { + throw std::runtime_error("Missing route series " + path); + } + const std::string prefix = "series_" + std::to_string(series_index++); + const fs::path time_path = temp_dir / (prefix + ".t.bin"); + const fs::path value_path = temp_dir / (prefix + ".v.bin"); + write_binary_vector(time_path, series->times); + write_binary_vector(value_path, series->values); + series_json.push_back(json11::Json::object{ + {"path", path}, {"t", time_path.string()}, {"v", value_path.string()}}); + } + const json11::Json manifest_json = json11::Json::object{ + {"paths", std::move(paths_json)}, + {"linked_source", spec.linked_source}, + {"additional_sources", std::move(additional_json)}, + {"series", std::move(series_json)}, + }; + write_text_file(manifest_path, manifest_json.dump()); + + const CommandResult process = run_process_capture_output({ + "python3", + (repo_root() / "openpilot" / "tools" / "jotpluggler" / "math_eval.py").string(), + manifest_path.string(), + globals_path.string(), + code_path.string(), + out_t_path.string(), + out_v_path.string(), + }); + if (process.exit_code != 0) { + const std::string error_text = util::strip(process.output); + throw std::runtime_error(error_text.empty() ? "Python evaluation failed" : error_text); + } + + PythonEvalResult result; + result.xs = read_binary_vector(out_t_path); + result.ys = read_binary_vector(out_v_path); + if (result.xs.size() < 2 || result.xs.size() != result.ys.size()) { + throw std::runtime_error("Custom series returned invalid output"); + } + fs::remove_all(temp_dir); + return result; + } catch (...) { + std::error_code ignore_error; + fs::remove_all(temp_dir, ignore_error); + throw; + } +} + +void refresh_custom_curve_samples(AppSession *session, UiState *state, Curve *curve) { + if (!curve->custom_python.has_value()) { + return; + } + if (!session->route_data.has_time_range || session->route_data.series.empty()) { + curve->runtime_error_message.clear(); + curve->xs.clear(); + curve->ys.clear(); + return; + } + try { + PythonEvalResult result = evaluate_custom_python_series(*session, *curve->custom_python); + curve->runtime_error_message.clear(); + curve->xs = std::move(result.xs); + curve->ys = std::move(result.ys); + } catch (const std::exception &err) { + curve->xs.clear(); + curve->ys.clear(); + const std::string err_text = err.what(); + if (session->data_mode == SessionDataMode::Stream && util::starts_with(err_text, "Missing route series ")) { + curve->runtime_error_message = err_text; + return; + } + const std::string error_message = std::string("Failed to evaluate custom series \"") + + app_curve_display_name(*curve) + "\":\n\n" + err_text; + if (curve->runtime_error_message != error_message) { + curve->runtime_error_message = error_message; + state->error_text = error_message; + state->open_error_popup = true; + } + } +} + +const std::array &custom_series_templates() { + static constexpr std::array kTemplates = {{ + { + .name = "Derivative", + .globals_code = "", + .function_code = "return np.gradient(value, time)", + .preview_text = "return np.gradient(value, time)", + .required_additional_sources = 0, + .requirement_text = "", + }, + { + .name = "Difference", + .globals_code = "", + .function_code = "return value - v1", + .preview_text = "Requires one additional source timeseries.\n\nreturn value - v1", + .required_additional_sources = 1, + .requirement_text = "Difference requires one additional source timeseries for v1.", + }, + { + .name = "Smoothing", + .globals_code = "window = 20\nweights = np.ones(window) / window", + .function_code = "return np.convolve(value, weights, mode='same')", + .preview_text = "window = 20\nweights = np.ones(window) / window\n\nreturn np.convolve(value, weights, mode='same')", + .required_additional_sources = 0, + .requirement_text = "", + }, + { + .name = "Integral", + .globals_code = "", + .function_code = "dt = np.mean(np.diff(time))\nreturn np.cumsum(value) * dt", + .preview_text = "dt = np.mean(np.diff(time))\nreturn np.cumsum(value) * dt", + .required_additional_sources = 0, + .requirement_text = "", + }, + }}; + return kTemplates; +} + +void draw_custom_series_help_popup(CustomSeriesEditorState *editor) { + if (editor->open_help) { + ImGui::OpenPopup("Custom Series Help"); + editor->open_help = false; + } + if (!app_begin_popup_modal("Custom Series Help")) { + return; + } + ImGui::TextUnformatted("Available variables"); + ImGui::Separator(); + ImGui::BulletText("np: numpy"); + ImGui::BulletText("t(path), v(path): timestamps and values for a route series"); + ImGui::BulletText("paths: all available route series paths"); + ImGui::BulletText("time, value: linked input timeseries"); + ImGui::BulletText("t1, v1, t2, v2, ...: additional source timeseries"); + ImGui::Spacing(); + ImGui::TextWrapped("Write either a single expression like \"return np.gradient(value, time)\" " + "or a multi-line Python body that returns an array or a (times, values) tuple."); + ImGui::Spacing(); + if (ImGui::Button("Close", ImVec2(120.0f, 0.0f))) { + ImGui::CloseCurrentPopup(); + } + ImGui::EndPopup(); +} + +void draw_custom_series_preview(const AppSession &session, CustomSeriesEditorState *editor) { + std::vector preview_xs; + std::vector preview_ys; + std::string preview_label = editor->preview_label; + if (editor->preview_is_result && editor->preview_xs.size() > 1 && editor->preview_xs.size() == editor->preview_ys.size()) { + preview_xs = editor->preview_xs; + preview_ys = editor->preview_ys; + if (preview_label.empty()) { + preview_label = "Result preview"; + } + } else if (!editor->linked_source.empty()) { + if (const RouteSeries *series = app_find_route_series(session, editor->linked_source); series != nullptr + && series->times.size() > 1 && series->times.size() == series->values.size()) { + preview_xs = series->times; + preview_ys = series->values; + preview_label = "Input preview (not result)"; + } + } + + if (!preview_xs.empty() && preview_xs.size() == preview_ys.size()) { + std::vector plot_xs; + std::vector plot_ys; + app_decimate_samples(preview_xs, preview_ys, 1200, &plot_xs, &plot_ys); + const double preview_x_min = preview_xs.front(); + const double preview_x_max = preview_xs.back() > preview_xs.front() + ? preview_xs.back() + : preview_xs.front() + 1e-6; + std::string plot_id = "##custom_series_preview"; + if (editor->preview_is_result) { + plot_id += "_result_"; + plot_id += editor->name.empty() ? preview_label : editor->name; + } else if (!editor->linked_source.empty()) { + plot_id += "_input_"; + plot_id += editor->linked_source; + } + ImGui::TextUnformatted(preview_label.c_str()); + if (!editor->linked_source.empty() && !editor->preview_is_result) { + ImGui::SameLine(); + ImGui::TextDisabled("%s", editor->linked_source.c_str()); + } + if (ImPlot::BeginPlot(plot_id.c_str(), + ImVec2(-1.0f, std::max(180.0f, ImGui::GetContentRegionAvail().y - 6.0f)), + ImPlotFlags_NoTitle | ImPlotFlags_NoMenus | ImPlotFlags_NoLegend)) { + ImPlot::SetupAxes(nullptr, nullptr, ImPlotAxisFlags_NoMenus | ImPlotAxisFlags_NoHighlight, + ImPlotAxisFlags_NoMenus | ImPlotAxisFlags_NoHighlight | ImPlotAxisFlags_AutoFit | ImPlotAxisFlags_RangeFit); + ImPlot::SetupAxisLimitsConstraints(ImAxis_X1, preview_x_min, preview_x_max); + ImPlot::SetupAxisLimits(ImAxis_X1, preview_x_min, preview_x_max, ImPlotCond_Once); + ImPlot::SetupAxisFormat(ImAxis_X1, "%.1f"); + ImPlot::SetupAxisFormat(ImAxis_Y1, "%.6g"); + ImPlotSpec spec; + spec.LineColor = color_rgb(35, 107, 180); + spec.LineWeight = 2.0f; + ImPlot::PlotLine("##custom_preview_line", plot_xs.data(), plot_ys.data(), static_cast(plot_xs.size()), spec); + ImPlot::EndPlot(); + } + } else { + ImGui::SetCursorPosY(ImGui::GetCursorPosY() + 72.0f); + ImGui::PushStyleColor(ImGuiCol_Text, color_rgb(116, 124, 133)); + ImGui::TextWrapped("Choose an input timeseries or click Preview to evaluate the custom result."); + ImGui::PopStyleColor(); + } +} + +std::string custom_series_name_status(const Pane &pane, std::string_view name) { + const std::string trimmed = util::strip(std::string(name)); + if (trimmed.empty()) return "name required"; + if (!trimmed.empty() && trimmed.front() == '/') { + return "cannot start with /"; + } + for (const Curve &curve : pane.curves) { + if (curve.runtime_only && curve.name == trimmed) return "updates existing curve"; + } + return "new curve"; +} + +const CustomSeriesTemplate &selected_custom_series_template(const CustomSeriesEditorState &editor) { + const auto &templates = custom_series_templates(); + return templates[static_cast(std::clamp(editor.selected_template, 0, static_cast(templates.size()) - 1))]; +} + +bool custom_series_template_ready(const CustomSeriesEditorState &editor) { + const CustomSeriesTemplate &templ = selected_custom_series_template(editor); + return !editor.linked_source.empty() + && static_cast(editor.additional_sources.size()) >= templ.required_additional_sources; +} + +bool prepare_custom_series_spec(CustomSeriesEditorState *editor, + UiState *state, + bool require_name, + CustomPythonSeries *out_spec) { + editor->name = util::strip(editor->name); + editor->linked_source = util::strip(editor->linked_source); + for (std::string &path : editor->additional_sources) { + path = util::strip(path); + } + editor->additional_sources.erase( + std::remove_if(editor->additional_sources.begin(), editor->additional_sources.end(), + [&](const std::string &path) { return path.empty() || path == editor->linked_source; }), + editor->additional_sources.end()); + + if (require_name && editor->name.empty()) { + state->error_text = "Custom series name is required."; + state->open_error_popup = true; + return false; + } + if (require_name && !editor->name.empty() && editor->name.front() == '/') { + state->error_text = "Custom series names may not start with '/'."; + state->open_error_popup = true; + return false; + } + + *out_spec = CustomPythonSeries{ + .linked_source = editor->linked_source, + .additional_sources = editor->additional_sources, + .globals_code = editor->globals_code, + .function_code = editor->function_code, + }; + return true; +} + +bool preview_custom_series_editor(AppSession *session, UiState *state) { + CustomSeriesEditorState &editor = state->custom_series; + const CustomSeriesTemplate &templ = selected_custom_series_template(editor); + if (editor.linked_source.empty()) { + state->error_text = "Choose an input timeseries before previewing."; + state->open_error_popup = true; + state->status_text = "Custom series preview failed"; + return false; + } + if (static_cast(editor.additional_sources.size()) < templ.required_additional_sources) { + state->error_text = templ.requirement_text; + state->open_error_popup = true; + state->status_text = "Custom series preview failed"; + return false; + } + CustomPythonSeries spec; + if (!prepare_custom_series_spec(&editor, state, false, &spec)) return false; + + try { + PythonEvalResult result = evaluate_custom_python_series(*session, spec); + editor.preview_label = editor.name.empty() ? "Result preview" : editor.name; + editor.preview_xs = std::move(result.xs); + editor.preview_ys = std::move(result.ys); + editor.preview_is_result = true; + state->status_text = "Previewed custom series"; + return true; + } catch (const std::exception &err) { + state->error_text = err.what(); + state->open_error_popup = true; + state->status_text = "Custom series preview failed"; + return false; + } +} + +bool apply_custom_series_editor(AppSession *session, UiState *state) { + WorkspaceTab *tab = app_active_tab(&session->layout, *state); + TabUiState *tab_state = app_active_tab_state(state); + if (tab == nullptr || tab_state == nullptr) { + state->status_text = "No active pane"; + return false; + } + if (tab_state->active_pane_index < 0 || tab_state->active_pane_index >= static_cast(tab->panes.size())) { + state->status_text = "No active pane"; + return false; + } + + CustomSeriesEditorState &editor = state->custom_series; + CustomPythonSeries spec; + if (!prepare_custom_series_spec(&editor, state, true, &spec)) return false; + + try { + PythonEvalResult result = evaluate_custom_python_series(*session, spec); + const SketchLayout before_layout = session->layout; + Pane &pane = tab->panes[static_cast(tab_state->active_pane_index)]; + editor.preview_label = editor.name; + editor.preview_xs = result.xs; + editor.preview_ys = result.ys; + editor.preview_is_result = true; + const bool inserted = upsert_custom_curve_in_pane(tab, + tab_state->active_pane_index, + make_custom_curve(pane, editor.name, spec, std::move(result))); + state->undo.push(before_layout); + state->status_text = inserted ? "Created custom series " + editor.name + : "Updated custom series " + editor.name; + return true; + } catch (const std::exception &err) { + state->error_text = err.what(); + state->open_error_popup = true; + state->status_text = "Custom series failed"; + return false; + } +} + +} // namespace + +void open_custom_series_editor(UiState *state, const std::string &preferred_source) { + CustomSeriesEditorState &editor = state->custom_series; + if (!editor.open && editor.name.empty() && editor.linked_source.empty() && editor.function_code == "return value") { + editor.focus_name = true; + } + if (editor.linked_source.empty() && !preferred_source.empty()) { + editor.linked_source = preferred_source; + } + editor.open = true; + editor.request_select = true; +} + +std::string preferred_custom_series_source(const Pane &pane) { + for (const Curve &curve : pane.curves) { + if (!curve.name.empty() && curve.name.front() == '/') { + return curve.name; + } + if (curve.custom_python.has_value() && !curve.custom_python->linked_source.empty()) { + return curve.custom_python->linked_source; + } + } + return {}; +} + +void refresh_all_custom_curves(AppSession *session, UiState *state) { + for (WorkspaceTab &tab : session->layout.tabs) { + for (Pane &pane : tab.panes) { + for (Curve &curve : pane.curves) { + refresh_custom_curve_samples(session, state, &curve); + } + } + } +} + +void draw_editor_source_panel(UiState *state, CustomSeriesEditorState &editor) { + ImGui::TextWrapped("Input timeseries. Provides arguments time and value:"); + ImGui::SetNextItemWidth(-FLT_MIN); + input_text_string("##custom_linked_source", &editor.linked_source, ImGuiInputTextFlags_ReadOnly); + if (ImGui::BeginDragDropTarget()) { + if (const ImGuiPayload *payload = ImGui::AcceptDragDropPayload("JOTP_BROWSER_PATH")) { + editor.linked_source = static_cast(payload->Data); + editor.additional_sources.erase( + std::remove(editor.additional_sources.begin(), editor.additional_sources.end(), editor.linked_source), + editor.additional_sources.end()); + editor.preview_is_result = false; + } + ImGui::EndDragDropTarget(); + } + if (ImGui::Button("Use Selected", ImVec2(120.0f, 0.0f)) && !state->selected_browser_path.empty()) { + editor.linked_source = state->selected_browser_path; + editor.additional_sources.erase( + std::remove(editor.additional_sources.begin(), editor.additional_sources.end(), editor.linked_source), + editor.additional_sources.end()); + editor.preview_is_result = false; + } + ImGui::SameLine(); + if (ImGui::Button("Clear", ImVec2(120.0f, 0.0f))) { + editor.linked_source.clear(); + editor.preview_is_result = false; + } + + ImGui::Spacing(); + ImGui::TextUnformatted("Additional source timeseries:"); + ImGui::SameLine(); + const CustomSeriesTemplate &tmpl = selected_custom_series_template(editor); + if (tmpl.required_additional_sources > 0) { + const bool ready = static_cast(editor.additional_sources.size()) >= tmpl.required_additional_sources; + ImGui::TextColored(ready ? color_rgb(58, 126, 73) : color_rgb(180, 122, 44), "%s", tmpl.requirement_text); + } + ImGui::SameLine(); + ImGui::BeginDisabled(editor.selected_additional_source < 0 + || editor.selected_additional_source >= static_cast(editor.additional_sources.size())); + if (ImGui::Button("Remove Selected", ImVec2(140.0f, 0.0f)) + && editor.selected_additional_source >= 0 + && editor.selected_additional_source < static_cast(editor.additional_sources.size())) { + editor.additional_sources.erase(editor.additional_sources.begin() + + static_cast(editor.selected_additional_source)); + editor.selected_additional_source = editor.additional_sources.empty() + ? -1 : std::clamp(editor.selected_additional_source, 0, static_cast(editor.additional_sources.size()) - 1); + editor.preview_is_result = false; + } + ImGui::EndDisabled(); + + if (ImGui::BeginChild("##custom_additional_sources", ImVec2(0.0f, 156.0f), true)) { + if (ImGui::BeginTable("##custom_additional_table", 2, + ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingStretchProp)) { + ImGui::TableSetupColumn("id", ImGuiTableColumnFlags_WidthFixed, 42.0f); + ImGui::TableSetupColumn("path", ImGuiTableColumnFlags_WidthStretch); + for (size_t i = 0; i < editor.additional_sources.size(); ++i) { + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::Text("v%zu", i + 1); + ImGui::TableNextColumn(); + if (ImGui::Selectable(editor.additional_sources[i].c_str(), + editor.selected_additional_source == static_cast(i), + ImGuiSelectableFlags_SpanAllColumns)) { + editor.selected_additional_source = static_cast(i); + } + } + ImGui::EndTable(); + } + if (ImGui::BeginDragDropTarget()) { + if (const ImGuiPayload *payload = ImGui::AcceptDragDropPayload("JOTP_BROWSER_PATH")) { + if (add_additional_source(&editor, static_cast(payload->Data))) + editor.preview_is_result = false; + } + ImGui::EndDragDropTarget(); + } + } + ImGui::EndChild(); + if (ImGui::Button("Add Selected", ImVec2(120.0f, 0.0f))) { + for (const std::string &path : state->selected_browser_paths) { + if (add_additional_source(&editor, path)) editor.preview_is_result = false; + } + } + + ImGui::Spacing(); + ImGui::SeparatorText("Function library"); + const auto &templates = custom_series_templates(); + if (ImGui::BeginChild("##custom_series_template_list", ImVec2(0.0f, 132.0f), true)) { + for (size_t i = 0; i < templates.size(); ++i) { + if (ImGui::Selectable(templates[i].name, editor.selected_template == static_cast(i), + ImGuiSelectableFlags_AllowDoubleClick)) { + editor.selected_template = static_cast(i); + if (ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) { + editor.globals_code = templates[i].globals_code; + editor.function_code = templates[i].function_code; + editor.preview_is_result = false; + } + } + } + } + ImGui::EndChild(); + if (ImGui::Button("Use Selected Example")) { + const auto &sel = selected_custom_series_template(editor); + editor.globals_code = sel.globals_code; + editor.function_code = sel.function_code; + editor.preview_is_result = false; + } + ImGui::Spacing(); + ImGui::TextDisabled("Preview"); + ImGui::BeginChild("##custom_series_template_preview", ImVec2(0.0f, 0.0f), true); + ImGui::TextUnformatted(selected_custom_series_template(editor).preview_text); + ImGui::EndChild(); +} + +void draw_editor_code_panel(CustomSeriesEditorState &editor, const Pane *active_pane) { + const std::string name_status = active_pane != nullptr ? custom_series_name_status(*active_pane, editor.name) : "no active pane"; + ImGui::TextUnformatted("New name:"); + ImGui::SameLine(); + const bool name_error = name_status == "name required" || name_status == "cannot start with /"; + ImGui::TextColored(name_error ? color_rgb(200, 72, 64) : color_rgb(58, 126, 73), "%s", name_status.c_str()); + if (editor.focus_name) { ImGui::SetKeyboardFocusHere(); editor.focus_name = false; } + ImGui::SetNextItemWidth(-FLT_MIN); + input_text_string("##custom_series_name", &editor.name, ImGuiInputTextFlags_AutoSelectAll); + + ImGui::Spacing(); + ImGui::SeparatorText("Global variables"); + ImGui::SameLine(); + if (ImGui::SmallButton("Help")) editor.open_help = true; + const float globals_h = std::max(96.0f, ImGui::GetContentRegionAvail().y * 0.28f); + if (input_text_multiline_string("##custom_series_globals", &editor.globals_code, + ImVec2(-FLT_MIN, globals_h), ImGuiInputTextFlags_AllowTabInput)) + editor.preview_is_result = false; + + ImGui::Spacing(); + ImGui::TextUnformatted("def calc(time, value):"); + const float func_h = std::max(180.0f, ImGui::GetContentRegionAvail().y - 16.0f); + if (input_text_multiline_string("##custom_series_function", &editor.function_code, + ImVec2(-FLT_MIN, func_h), ImGuiInputTextFlags_AllowTabInput)) + editor.preview_is_result = false; +} + +void draw_custom_series_editor(AppSession *session, UiState *state) { + CustomSeriesEditorState &editor = state->custom_series; + if (!editor.open) return; + + WorkspaceTab *tab = app_active_tab(&session->layout, *state); + TabUiState *tab_state = app_active_tab_state(state); + Pane *active_pane = (tab && tab_state && tab_state->active_pane_index >= 0 + && tab_state->active_pane_index < static_cast(tab->panes.size())) + ? &tab->panes[static_cast(tab_state->active_pane_index)] : nullptr; + if (editor.focus_name && active_pane && editor.name.empty()) + editor.name = next_custom_curve_name(*active_pane); + + draw_custom_series_help_popup(&editor); + + if (ImGui::BeginTabBar("##custom_series_tabs")) { + if (ImGui::BeginTabItem("Single Function")) { + const float footer_height = ImGui::GetFrameHeightWithSpacing() * 2.0f + 10.0f; + if (ImGui::BeginChild("##custom_series_body", + ImVec2(0.0f, std::max(1.0f, ImGui::GetContentRegionAvail().y - footer_height)), false)) { + if (ImGui::BeginChild("##custom_series_preview_child", + ImVec2(0.0f, std::max(200.0f, ImGui::GetContentRegionAvail().y * 0.28f)), true)) + draw_custom_series_preview(*session, &editor); + ImGui::EndChild(); + ImGui::Spacing(); + + if (ImGui::BeginTable("##custom_series_editor_table", 2, + ImGuiTableFlags_Resizable | ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_SizingStretchProp, + ImVec2(0.0f, std::max(1.0f, ImGui::GetContentRegionAvail().y)))) { + ImGui::TableSetupColumn("left", ImGuiTableColumnFlags_WidthFixed, 320.0f); + ImGui::TableSetupColumn("right", ImGuiTableColumnFlags_WidthStretch); + ImGui::TableNextColumn(); + if (ImGui::BeginChild("##custom_series_left", ImVec2(0.0f, 0.0f), false)) + draw_editor_source_panel(state, editor); + ImGui::EndChild(); + ImGui::TableNextColumn(); + if (ImGui::BeginChild("##custom_series_right", ImVec2(0.0f, 0.0f), false)) + draw_editor_code_panel(editor, active_pane); + ImGui::EndChild(); + ImGui::EndTable(); + } + } + ImGui::EndChild(); + + ImGui::Spacing(); + if (ImGui::Button("New", ImVec2(120.0f, 0.0f))) { + reset_custom_series_editor(&editor); + if (!state->selected_browser_path.empty()) editor.linked_source = state->selected_browser_path; + editor.open = true; + editor.focus_name = true; + } + ImGui::SameLine(); + ImGui::BeginDisabled(!custom_series_template_ready(editor)); + if (ImGui::Button("Preview Result", ImVec2(120.0f, 0.0f))) + preview_custom_series_editor(session, state); + ImGui::EndDisabled(); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) && !custom_series_template_ready(editor)) { + if (editor.linked_source.empty()) ImGui::SetTooltip("Choose an input timeseries first."); + else ImGui::SetTooltip("%s", selected_custom_series_template(editor).requirement_text); + } + ImGui::SameLine(); + if (ImGui::Button("Apply", ImVec2(120.0f, 0.0f))) apply_custom_series_editor(session, state); + ImGui::SameLine(); + if (ImGui::Button("Close", ImVec2(120.0f, 0.0f))) { editor.open = false; editor.request_select = false; } + ImGui::EndTabItem(); + } + ImGui::EndTabBar(); + } +} diff --git a/openpilot/tools/jotpluggler/dbc.h b/openpilot/tools/jotpluggler/dbc.h new file mode 100644 index 0000000000..d7c5461502 --- /dev/null +++ b/openpilot/tools/jotpluggler/dbc.h @@ -0,0 +1,400 @@ +#pragma once + +#include "common/util.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace dbc { + + +struct ValueDescriptionEntry { + double value = 0.0; + std::string text; +}; + +struct Signal { + enum class Type { + Normal = 0, + Multiplexed, + Multiplexor, + }; + + Type type = Type::Normal; + std::string name; + int start_bit = 0; + int msb = 0; + int lsb = 0; + int size = 0; + double factor = 1.0; + double offset = 0.0; + double min = 0.0; + double max = 0.0; + bool is_signed = false; + bool is_little_endian = false; + std::string unit; + std::string comment; + std::string receiver_name; + int multiplex_value = 0; + int multiplexor_index = -1; + std::vector value_descriptions; +}; + +struct Message { + uint32_t address = 0; + std::string name; + uint32_t size = 0; + std::string comment; + std::string transmitter; + std::vector signals; + int multiplexor_index = -1; + + const std::vector &getSignals() const { return signals; } +}; + +class Database { +public: + Database() = default; + explicit Database(const std::filesystem::path &path); + static Database fromContent(const std::string &content, const std::string &filename = ""); + + const Message *message(uint32_t address) const; + const std::unordered_map &messages() const { return messages_; } + std::vector enumNames(const Signal &signal) const; + +private: + void parse(const std::string &content, const std::string &filename); + void parseBo(const std::string &line, int line_number, Message **current_message); + void parseSg(const std::string &line, int line_number, Message *current_message); + void parseVal(const std::string &line, int line_number); + void parseCmBo(const std::string &line, int line_number); + void parseCmSg(const std::string &line, int line_number); + void finalize(); + + std::string filename_; + std::unordered_map messages_; +}; + +void updateMsbLsb(Signal *signal); +double rawSignalValue(const Signal &signal, const uint8_t *data, size_t data_size); +std::optional signalValue(const Signal &signal, const Message &message, const uint8_t *data, size_t data_size); + +namespace { + +std::string unescape_dbc_string(std::string text) { + size_t pos = 0; + while ((pos = text.find("\\\"", pos)) != std::string::npos) { + text.replace(pos, 2, "\""); + ++pos; + } + return text; +} + +int flip_bit_pos(int start_bit) { + return 8 * (start_bit / 8) + 7 - start_bit % 8; +} + +std::string read_multiline_statement(std::istream &stream, std::string statement, int *line_number) { + static const std::regex statement_end(R"(\"\s*;\s*$)"); + while (true) { + const std::string trimmed = util::strip(statement); + if (std::regex_search(trimmed, statement_end)) { + return trimmed; + } + + std::string next_line; + if (!std::getline(stream, next_line)) { + return trimmed; + } + statement += "\n"; + statement += next_line; + ++(*line_number); + } +} + +} // namespace + +inline void updateMsbLsb(Signal *signal) { + if (signal->is_little_endian) { + signal->lsb = signal->start_bit; + signal->msb = signal->start_bit + signal->size - 1; + } else { + signal->lsb = flip_bit_pos(flip_bit_pos(signal->start_bit) + signal->size - 1); + signal->msb = signal->start_bit; + } +} + +inline double rawSignalValue(const Signal &signal, const uint8_t *data, size_t data_size) { + const int msb_byte = signal.msb / 8; + if (msb_byte >= static_cast(data_size)) return 0.0; + + const int lsb_byte = signal.lsb / 8; + uint64_t val = 0; + if (msb_byte == lsb_byte) { + val = (data[msb_byte] >> (signal.lsb & 7)) & ((1ULL << signal.size) - 1); + } else { + int bits = signal.size; + int i = msb_byte; + const int step = signal.is_little_endian ? -1 : 1; + while (i >= 0 && i < static_cast(data_size) && bits > 0) { + const int msb = (i == msb_byte) ? signal.msb & 7 : 7; + const int lsb = (i == lsb_byte) ? signal.lsb & 7 : 0; + const int nbits = msb - lsb + 1; + val = (val << nbits) | ((data[i] >> lsb) & ((1ULL << nbits) - 1)); + bits -= nbits; + i += step; + } + } + + if (signal.is_signed && (val & (1ULL << (signal.size - 1)))) { + val |= ~((1ULL << signal.size) - 1); + } + + return static_cast(val) * signal.factor + signal.offset; +} + +[[noreturn]] inline void parse_error(const std::string &filename, int line_number, const std::string &message, const std::string &line) { + std::ostringstream out; + out << "[" << filename << ":" << line_number << "] " << message << ": " << line; + throw std::runtime_error(out.str()); +} + +inline Database::Database(const std::filesystem::path &path) { + const std::string content = util::read_file(path.string()); + if (content.empty() && !std::filesystem::exists(path)) { + throw std::runtime_error("Failed to open DBC " + path.string()); + } + parse(content, path.filename().string()); +} + +inline Database Database::fromContent(const std::string &content, const std::string &filename) { + Database db; + db.parse(content, filename); + return db; +} + +inline const Message *Database::message(uint32_t address) const { + auto it = messages_.find(address); + return it == messages_.end() ? nullptr : &it->second; +} + +inline std::vector Database::enumNames(const Signal &signal) const { + if (signal.value_descriptions.empty()) return {}; + int max_index = -1; + for (const auto &entry : signal.value_descriptions) { + const double rounded = std::round(entry.value); + if (std::abs(entry.value - rounded) > 1e-6 || rounded < 0.0 || rounded > 512.0) return {}; + max_index = std::max(max_index, static_cast(rounded)); + } + if (max_index < 0) return {}; + std::vector names(static_cast(max_index + 1)); + for (const auto &entry : signal.value_descriptions) { + names[static_cast(std::llround(entry.value))] = entry.text; + } + return names; +} + +inline void Database::parse(const std::string &content, const std::string &filename) { + filename_ = filename; + messages_.clear(); + std::istringstream stream(content); + std::string raw_line; + Message *current_message = nullptr; + int line_number = 0; + while (std::getline(stream, raw_line)) { + ++line_number; + std::string line = util::strip(raw_line); + if (line.empty()) continue; + if (util::starts_with(line, "BO_ ")) { + parseBo(line, line_number, ¤t_message); + } else if (util::starts_with(line, "SG_ ")) { + if (current_message == nullptr) { + parse_error(filename, line_number, "Signal without current message", line); + } + parseSg(line, line_number, current_message); + } else if (util::starts_with(line, "VAL_ ")) { + parseVal(line, line_number); + } else if (util::starts_with(line, "CM_ BO_")) { + parseCmBo(read_multiline_statement(stream, raw_line, &line_number), line_number); + } else if (util::starts_with(line, "CM_ SG_")) { + parseCmSg(read_multiline_statement(stream, raw_line, &line_number), line_number); + } + } + finalize(); +} + +inline void Database::parseBo(const std::string &line, int line_number, Message **current_message) { + static const std::regex pattern(R"(^BO_\s+(\w+)\s+(\w+)\s*:\s*(\w+)\s+(\w+)\s*$)"); + std::smatch match; + if (!std::regex_match(line, match, pattern)) { + parse_error("", line_number, "Invalid BO_ line format", line); + } + uint32_t address = static_cast(std::stoul(match[1].str(), nullptr, 0)); + if (messages_.find(address) != messages_.end()) { + parse_error(filename_, line_number, "Duplicate message address", line); + } + Message &message = messages_[address]; + message.address = address; + message.name = match[2].str(); + message.size = static_cast(std::stoul(match[3].str(), nullptr, 0)); + message.transmitter = match[4].str(); + message.signals.clear(); + message.multiplexor_index = -1; + *current_message = &message; +} + +inline void Database::parseSg(const std::string &line, int line_number, Message *current_message) { + static const std::regex multiplex_pattern(R"(^SG_\s+(\w+)\s+(\w+)\s*:\s*(\d+)\|(\d+)@(\d)([+-])\s+\(([0-9.+\-eE]+),([0-9.+\-eE]+)\)\s+\[([0-9.+\-eE]+)\|([0-9.+\-eE]+)\]\s+\"(.*)\"\s+(.*)$)"); + static const std::regex normal_pattern(R"(^SG_\s+(\w+)\s*:\s*(\d+)\|(\d+)@(\d)([+-])\s+\(([0-9.+\-eE]+),([0-9.+\-eE]+)\)\s+\[([0-9.+\-eE]+)\|([0-9.+\-eE]+)\]\s+\"(.*)\"\s+(.*)$)"); + + std::smatch match; + Signal signal; + int offset = 0; + if (std::regex_match(line, match, normal_pattern)) { + offset = 0; + } else if (std::regex_match(line, match, multiplex_pattern)) { + offset = 1; + const std::string indicator = match[2].str(); + if (indicator == "M") { + if (std::any_of(current_message->signals.begin(), current_message->signals.end(), [](const Signal &existing) { + return existing.type == Signal::Type::Multiplexor; + })) { + parse_error(filename_, line_number, "Multiple multiplexor", line); + } + signal.type = Signal::Type::Multiplexor; + } else if (!indicator.empty() && indicator.front() == 'm') { + signal.type = Signal::Type::Multiplexed; + signal.multiplex_value = std::stoi(indicator.substr(1)); + } else { + parse_error("", line_number, "Invalid multiplex indicator", line); + } + } else { + parse_error("", line_number, "Invalid SG_ line format", line); + } + + signal.name = match[1].str(); + if (std::any_of(current_message->signals.begin(), current_message->signals.end(), [&](const Signal &existing) { + return existing.name == signal.name; + })) { + parse_error(filename_, line_number, "Duplicate signal name", line); + } + signal.start_bit = std::stoi(match[2 + offset].str()); + signal.size = std::stoi(match[3 + offset].str()); + signal.is_little_endian = match[4 + offset].str() == "1"; + signal.is_signed = match[5 + offset].str() == "-"; + signal.factor = std::stod(match[6 + offset].str()); + signal.offset = std::stod(match[7 + offset].str()); + signal.min = std::stod(match[8 + offset].str()); + signal.max = std::stod(match[9 + offset].str()); + signal.unit = match[10 + offset].str(); + signal.receiver_name = util::strip(match[11 + offset].str()); + updateMsbLsb(&signal); + current_message->signals.push_back(std::move(signal)); +} + +inline void Database::parseVal(const std::string &line, int line_number) { + static const std::regex prefix(R"(^VAL_\s+(\w+)\s+(\w+)\s+(.*);$)"); + std::smatch match; + if (!std::regex_match(line, match, prefix)) { + parse_error("", line_number, "Invalid VAL_ line format", line); + } + + const uint32_t address = static_cast(std::stoul(match[1].str(), nullptr, 0)); + auto msg_it = messages_.find(address); + if (msg_it == messages_.end()) { + return; + } + auto sig_it = std::find_if(msg_it->second.signals.begin(), msg_it->second.signals.end(), [&](const Signal &signal) { + return signal.name == match[2].str(); + }); + if (sig_it == msg_it->second.signals.end()) { + return; + } + + static const std::regex entry_pattern(R"(([+-]?\d+(?:\.\d+)?)\s+\"((?:[^\"\\]|\\.)*)\")"); + const std::string defs = match[3].str(); + for (std::sregex_iterator it(defs.begin(), defs.end(), entry_pattern), end; it != end; ++it) { + sig_it->value_descriptions.push_back(ValueDescriptionEntry{ + .value = std::stod((*it)[1].str()), + .text = (*it)[2].str(), + }); + } +} + +inline void Database::parseCmBo(const std::string &line, int line_number) { + static const std::regex pattern(R"(^CM_\s+BO_\s*(\w+)\s*\"((?:[^\"\\]|\\.|[\r\n])*)\"\s*;\s*$)"); + std::smatch match; + if (!std::regex_match(line, match, pattern)) { + parse_error(filename_, line_number, "Invalid message comment format", line); + } + const uint32_t address = static_cast(std::stoul(match[1].str(), nullptr, 0)); + auto it = messages_.find(address); + if (it != messages_.end()) { + it->second.comment = unescape_dbc_string(match[2].str()); + } +} + +inline void Database::parseCmSg(const std::string &line, int line_number) { + static const std::regex pattern(R"(^CM_\s+SG_\s*(\w+)\s*(\w+)\s*\"((?:[^\"\\]|\\.|[\r\n])*)\"\s*;\s*$)"); + std::smatch match; + if (!std::regex_match(line, match, pattern)) { + parse_error(filename_, line_number, "Invalid signal comment format", line); + } + + const uint32_t address = static_cast(std::stoul(match[1].str(), nullptr, 0)); + auto msg_it = messages_.find(address); + if (msg_it == messages_.end()) return; + + auto sig_it = std::find_if(msg_it->second.signals.begin(), msg_it->second.signals.end(), [&](const Signal &signal) { + return signal.name == match[2].str(); + }); + if (sig_it != msg_it->second.signals.end()) { + sig_it->comment = unescape_dbc_string(match[3].str()); + } +} + +inline void Database::finalize() { + for (auto &[_, message] : messages_) { + std::sort(message.signals.begin(), message.signals.end(), [](const Signal &left, const Signal &right) { + return std::tie(right.type, left.multiplex_value, left.start_bit, left.name) + < std::tie(left.type, right.multiplex_value, right.start_bit, right.name); + }); + message.multiplexor_index = -1; + for (size_t i = 0; i < message.signals.size(); ++i) { + if (message.signals[i].type == Signal::Type::Multiplexor) { + message.multiplexor_index = static_cast(i); + break; + } + } + for (Signal &signal : message.signals) { + signal.multiplexor_index = signal.type == Signal::Type::Multiplexed ? message.multiplexor_index : -1; + if (signal.type == Signal::Type::Multiplexed && signal.multiplexor_index < 0) { + signal.type = Signal::Type::Normal; + signal.multiplex_value = 0; + } + } + } +} + +inline std::optional signalValue(const Signal &signal, const Message &message, const uint8_t *data, size_t data_size) { + if (signal.multiplexor_index >= 0) { + const Signal &multiplexor = message.signals[static_cast(signal.multiplexor_index)]; + const double mux_value = rawSignalValue(multiplexor, data, data_size); + if (std::llround(mux_value) != signal.multiplex_value) return std::nullopt; + } + return rawSignalValue(signal, data, data_size); +} + +} // namespace dbc diff --git a/openpilot/tools/jotpluggler/generate_event_extractors.py b/openpilot/tools/jotpluggler/generate_event_extractors.py new file mode 100644 index 0000000000..be9bd49003 --- /dev/null +++ b/openpilot/tools/jotpluggler/generate_event_extractors.py @@ -0,0 +1,327 @@ +import sys +import capnp +from pathlib import Path + +NO_DISCRIMINANT = 65535 +SCALAR_KINDS = { + "bool": "Bool", + "int8": "Int", + "int16": "Int", + "int32": "Int", + "int64": "Int", + "uint8": "UInt", + "uint16": "UInt", + "uint32": "UInt", + "uint64": "UInt", + "float32": "Float", + "float64": "Float", + "enum": "Enum", +} +NESTED_TYPE_KINDS = {"struct", "list"} +IGNORED_TYPE_KINDS = {"void", "text", "data", "interface", "anyPointer"} + + +def cxx_string(value): + return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"' + + +def accessor(prefix, name): + return prefix + name[:1].upper() + name[1:] + + +def field_type(field): + if field.proto.which() == "group": + return "struct" + return field.proto.slot.type.which() + + +def field_type_proto(field): + return field.proto.slot.type if field.proto.which() == "slot" else None + + +def scalar_kind(type_proto): + if type_proto is None: + return None + return SCALAR_KINDS.get(type_proto.which()) + + +def enum_names(schema): + if schema is None: + return [] + names_by_ordinal = schema.enumerants + if not names_by_ordinal: + return [] + max_ordinal = max(names_by_ordinal.values()) + out = [""] * (max_ordinal + 1) + for name, ordinal in names_by_ordinal.items(): + out[ordinal] = name + return out + + +class Generator: + def __init__(self, event_schema): + self.event_schema = event_schema + self.fixed_paths = [] + self.tmp_index = 0 + self.lines = [] + self.emits_memo = {} + + def tmp(self, prefix): + self.tmp_index += 1 + return f"{prefix}_{self.tmp_index}" + + def add_fixed_path(self, path): + slot = len(self.fixed_paths) + self.fixed_paths.append(path) + return slot + + def emit(self, indent, text=""): + self.lines.append(" " * indent + text) + + def scalar_double_expr(self, value_expr, kind): + if kind == "Bool": + return f"({value_expr} ? 1.0 : 0.0)" + if kind == "Enum": + return f"static_cast(static_cast({value_expr}))" + return f"static_cast({value_expr})" + + def emit_enum_capture(self, indent, path_expr, names): + if not names: + return + names_expr = "{" + ", ".join(cxx_string(name) for name in names) + "}" + self.emit(indent, f"capture_static_enum_info({path_expr}, {names_expr}, series);") + + def emit_node(self, indent, type_kind, type_proto, schema, expr, path, path_expr, dynamic_path): + if not self.node_emits(type_kind, type_proto, schema): + return + kind = scalar_kind(type_proto) + if kind is not None: + double_expr = self.scalar_double_expr(expr, kind) + if dynamic_path: + if kind == "Enum": + self.emit_enum_capture(indent, path_expr, enum_names(schema)) + self.emit(indent, f"append_dynamic_scalar_point({path_expr}, tm, {double_expr}, series);") + else: + slot = self.add_fixed_path(path) + if kind == "Enum": + self.emit_enum_capture(indent, cxx_string(path), enum_names(schema)) + self.emit(indent, f"append_fixed_scalar_point(&series->fixed_series[{slot}], tm, {double_expr});") + return + + if type_kind == "struct": + self.emit_struct(indent, schema, expr, path, path_expr, dynamic_path) + return + + if type_kind == "list": + self.emit_list(indent, type_proto, schema, expr, path, path_expr, dynamic_path) + + def emit_field(self, indent, struct_schema, reader_expr, field_name, base_path, base_path_expr, dynamic_path): + field = struct_schema.fields[field_name] + proto = field.proto + type_kind = field_type(field) + type_proto = field_type_proto(field) + kind = scalar_kind(type_proto) + value_schema = field.schema if kind == "Enum" or type_kind in NESTED_TYPE_KINDS else None + if not self.node_emits(type_kind, type_proto, value_schema): + return + + field_path = f"{base_path}/{field_name}" + field_path_expr = None + if dynamic_path: + field_path_var = self.tmp("path") + self.emit(indent, f"const std::string {field_path_var} = {base_path_expr} + {cxx_string('/' + field_name)};") + field_path_expr = field_path_var + + get_call = f"{reader_expr}.{accessor('get', field_name)}()" + has_call = f"{reader_expr}.{accessor('has', field_name)}()" + conditions = [] + if proto.discriminantValue != NO_DISCRIMINANT: + conditions.append(f"{reader_expr}.which() == static_cast({proto.discriminantValue})") + if proto.which() == "slot" and type_kind in NESTED_TYPE_KINDS: + conditions.append(has_call) + + if conditions: + self.emit(indent, f"if ({' && '.join(conditions)}) {{") + indent += 2 + + value_var = self.tmp("value") + self.emit(indent, f"const auto {value_var} = {get_call};") + self.emit_node(indent, type_kind, type_proto, value_schema, value_var, field_path, field_path_expr, dynamic_path) + + if conditions: + indent -= 2 + self.emit(indent, "}") + + def emit_struct(self, indent, schema, reader_expr, path, path_expr, dynamic_path): + if schema is None: + return + for field_name in schema.fieldnames: + self.emit_field(indent, schema, reader_expr, field_name, path, path_expr, dynamic_path) + + def emit_list(self, indent, type_proto, schema, list_expr, path, path_expr, dynamic_path): + elem_type = type_proto.list.elementType + elem_kind = elem_type.which() + if elem_kind in IGNORED_TYPE_KINDS: + return + + base_path_var = path_expr + if base_path_var is None: + base_path_var = self.tmp("base_path") + self.emit(indent, f"const std::string {base_path_var} = {cxx_string(path)};") + + elem_scalar = scalar_kind(elem_type) + if elem_scalar is not None: + self.emit(indent, f"if ({list_expr}.size() <= 16) {{") + index_var = self.tmp("i") + self.emit(indent + 2, f"for (uint {index_var} = 0; {index_var} < {list_expr}.size(); ++{index_var}) {{") + item_series = self.tmp("item_series") + self.emit(indent + 4, f"RouteSeries *{item_series} = ensure_list_scalar_series({base_path_var}, {index_var}, series);") + if elem_scalar == "Enum": + self.emit_enum_capture(indent + 4, f"{item_series}->path", enum_names(schema.elementType)) + self.emit(indent + 4, f"append_fixed_scalar_point({item_series}, tm, {self.scalar_double_expr(f'{list_expr}[{index_var}]', elem_scalar)});") + self.emit(indent + 2, "}") + self.emit(indent, "}") + return + + if elem_kind in {"struct", "list"}: + index_var = self.tmp("i") + self.emit(indent, f"for (uint {index_var} = 0; {index_var} < {list_expr}.size(); ++{index_var}) {{") + item_path = self.tmp("item_path") + self.emit(indent + 2, f"const std::string {item_path} = {base_path_var} + \"/\" + std::to_string({index_var});") + item = self.tmp("item") + self.emit(indent + 2, f"const auto {item} = {list_expr}[{index_var}];") + if elem_kind == "struct": + self.emit_struct(indent + 2, schema.elementType, item, path, item_path, True) + else: + self.emit_list(indent + 2, elem_type, schema.elementType, item, path, item_path, True) + self.emit(indent, "}") + + def node_emits(self, type_kind, type_proto, schema, seen=frozenset()): + if scalar_kind(type_proto) is not None: + return True + if type_kind == "struct": + if schema is None: + return False + schema_id = int(schema.node.id) + if schema_id in seen: + return False + if schema_id in self.emits_memo: + return self.emits_memo[schema_id] + next_seen = seen | {schema_id} + for field_name in schema.fieldnames: + field = schema.fields[field_name] + ft = field_type(field) + ftp = field_type_proto(field) + fkind = scalar_kind(ftp) + if ft in IGNORED_TYPE_KINDS: + continue + fschema = field.schema if fkind == "Enum" or ft in NESTED_TYPE_KINDS else None + if self.node_emits(ft, ftp, fschema, next_seen): + self.emits_memo[schema_id] = True + return True + self.emits_memo[schema_id] = False + return False + if type_kind == "list": + if type_proto is None or schema is None: + return False + elem_type = type_proto.list.elementType + elem_kind = elem_type.which() + if elem_kind in IGNORED_TYPE_KINDS: + return False + if scalar_kind(elem_type) is not None: + return True + if elem_kind == "struct": + return self.node_emits("struct", None, schema.elementType, seen) + if elem_kind == "list": + return self.node_emits("list", elem_type, schema.elementType, seen) + return False + + def emit_can_special(self, indent, service_name): + service_kind = "CanServiceKind::Can" if service_name == "can" else "CanServiceKind::Sendcan" + self.emit(indent, f"const CanServiceKind can_service = {service_kind};") + self.emit(indent, f"for (const auto &msg : event.{accessor('get', service_name)}()) {{") + self.emit(indent + 2, "append_can_frame(can_service, static_cast(msg.getSrc()), msg.getAddress(), msg.getDeprecated().getBusTime(), msg.getDat(), tm, series);") # noqa: E501 + self.emit(indent + 2, "if (skip_raw_can) {") + self.emit(indent + 4, "const auto dat = msg.getDat();") + self.emit(indent + 4, f"decode_can_frame(can_dbc, {cxx_string(service_name)}, static_cast(msg.getSrc()), msg.getAddress(), dat.begin(), dat.size(), tm, series);") # noqa: E501 + self.emit(indent + 2, "}") + self.emit(indent, "}") + self.emit(indent, "if (skip_raw_can) {") + self.emit(indent + 2, "return true;") + self.emit(indent, "}") + + def emit_event_case(self, field_name): + field = self.event_schema.fields[field_name] + proto = field.proto + type_kind = field_type(field) + type_proto = field_type_proto(field) + kind = scalar_kind(type_proto) + schema = field.schema if kind == "Enum" or type_kind in NESTED_TYPE_KINDS else None + self.emit(4, f"case static_cast({proto.discriminantValue}): {{") + valid_slot = self.add_fixed_path(f"/{field_name}/valid") + mono_slot = self.add_fixed_path(f"/{field_name}/logMonoTime") + seconds_slot = self.add_fixed_path(f"/{field_name}/t") + self.emit(6, f"append_fixed_scalar_point(&series->fixed_series[{valid_slot}], tm, event.getValid() ? 1.0 : 0.0);") + self.emit(6, f"append_fixed_scalar_point(&series->fixed_series[{mono_slot}], tm, static_cast(event.getLogMonoTime()));") + self.emit(6, f"append_fixed_scalar_point(&series->fixed_series[{seconds_slot}], tm, tm);") + if field_name in {"can", "sendcan"}: + self.emit_can_special(6, field_name) + if self.node_emits(type_kind, type_proto, schema): + payload = self.tmp("payload") + self.emit(6, f"const auto {payload} = event.{accessor('get', field_name)}();") + self.emit_node(6, type_kind, type_proto, schema, payload, f"/{field_name}", None, False) + self.emit(6, "return true;") + self.emit(4, "}") + + def generate(self): + self.lines = [] + self.emit(0, "// Generated by openpilot/tools/jotpluggler/generate_event_extractors.py; do not edit.") + self.emit(0, "") + self.emit(0, "const std::vector &static_event_fixed_paths() {") + self.emit(2, "static const std::vector paths = {") + path_insert_at = len(self.lines) + self.emit(2, "};") + self.emit(2, "return paths;") + self.emit(0, "}") + self.emit(0, "") + self.emit(0, "void capture_static_enum_info(const std::string &path, std::initializer_list names, SeriesAccumulator *series) {") + self.emit(2, "if (series->enum_info.find(path) != series->enum_info.end()) {") + self.emit(4, "return;") + self.emit(2, "}") + self.emit(2, "EnumInfo info;") + self.emit(2, "info.names.reserve(names.size());") + self.emit(2, "for (std::string_view name : names) {") + self.emit(4, "info.names.emplace_back(name);") + self.emit(2, "}") + self.emit(2, "if (!info.names.empty()) {") + self.emit(4, "series->enum_info.emplace(path, std::move(info));") + self.emit(2, "}") + self.emit(0, "}") + self.emit(0, "") + self.emit(0, "bool append_event_static_reader(cereal::Event::Which which, const cereal::Event::Reader &event, const dbc::Database *can_dbc, bool skip_raw_can, double time_offset, SeriesAccumulator *series) {") # noqa: E501 + self.emit(2, "const double tm = static_cast(event.getLogMonoTime()) / 1.0e9 - time_offset;") + self.emit(2, "switch (which) {") + for field_name in self.event_schema.union_fields: + self.emit_event_case(field_name) + self.emit(4, "default:") + self.emit(6, "return false;") + self.emit(2, "}") + self.emit(0, "}") + + path_lines = [" " + cxx_string(path) + "," for path in self.fixed_paths] + self.lines[path_insert_at:path_insert_at] = path_lines + return "\n".join(self.lines) + "\n" + + +if __name__ == "__main__": + if len(sys.argv) != 3: + print(f"usage: {sys.argv[0]} ", file=sys.stderr) + sys.exit(2) + + repo_root = Path(sys.argv[1]).resolve() + output = Path(sys.argv[2]) + capnp.remove_import_hook() + log = capnp.load(str(repo_root / "openpilot" / "cereal" / "log.capnp"), imports=[str(repo_root / "opendbc_repo" / "opendbc" / "car")]) + generated = Generator(log.Event.schema).generate() + output.parent.mkdir(parents=True, exist_ok=True) + output.write_text(generated) diff --git a/openpilot/tools/jotpluggler/generated_dbcs/.gitignore b/openpilot/tools/jotpluggler/generated_dbcs/.gitignore new file mode 100644 index 0000000000..d6b7ef32c8 --- /dev/null +++ b/openpilot/tools/jotpluggler/generated_dbcs/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore diff --git a/openpilot/tools/jotpluggler/icons.cc b/openpilot/tools/jotpluggler/icons.cc new file mode 100644 index 0000000000..29edabad4e --- /dev/null +++ b/openpilot/tools/jotpluggler/icons.cc @@ -0,0 +1,24 @@ +#include "tools/jotpluggler/app.h" +#include "tools/jotpluggler/common.h" + +#include + +void icon_add_font(float size, bool merge, const ImFont *base_font) { + const std::filesystem::path ttf = BOOTSTRAP_ICONS_TTF; + ImGuiIO &io = ImGui::GetIO(); + ImFontConfig config; + config.MergeMode = merge; + config.GlyphMinAdvanceX = size; + if (base_font != nullptr) { + ImFontBaked *baked = const_cast(base_font)->GetFontBaked(size); + const float base_center = baked != nullptr ? (baked->Ascent + baked->Descent) * 0.5f : size * 0.5f; + config.GlyphOffset.y = std::round(size * 0.5f - base_center); + } + static const ImWchar ranges[] = {0xF000, 0xF8FF, 0}; + io.Fonts->AddFontFromFileTTF(ttf.c_str(), size, &config, ranges); +} + +bool icon_menu_item(const char *glyph, const char *label, const char *shortcut, bool selected, bool enabled) { + assert(glyph != nullptr && glyph[0] != '\0'); + return ImGui::MenuItem(util::string_format("%s %s", glyph, label).c_str(), shortcut, selected, enabled); +} diff --git a/openpilot/tools/jotpluggler/internal.h b/openpilot/tools/jotpluggler/internal.h new file mode 100644 index 0000000000..7b898f0461 --- /dev/null +++ b/openpilot/tools/jotpluggler/internal.h @@ -0,0 +1,165 @@ +#pragma once + +#include "tools/jotpluggler/common.h" +#include "tools/jotpluggler/map.h" + +#include +#include +#include + +struct GLFWwindow; + +enum class PaneDropZone { + Center, + Left, + Right, + Top, + Bottom, +}; + +enum class PaneMenuActionKind { + None, + OpenAxisLimits, + OpenCustomSeries, + SplitLeft, + SplitRight, + SplitTop, + SplitBottom, + ResetView, + Clear, + Close, +}; + +struct PaneMenuAction { + PaneMenuActionKind kind = PaneMenuActionKind::None; + int pane_index = -1; +}; + +struct PaneCurveDragPayload { + int tab_index = -1; + int pane_index = -1; + int curve_index = -1; +}; + +struct PaneDropAction { + PaneDropZone zone = PaneDropZone::Center; + int target_pane_index = -1; + bool from_browser = false; + std::vector browser_paths; + std::string special_item_id; + PaneCurveDragPayload curve_ref; +}; + +inline constexpr float SIDEBAR_WIDTH = 320.0f; +inline constexpr float SIDEBAR_MIN_WIDTH = 220.0f; +inline constexpr float SIDEBAR_MAX_WIDTH = 520.0f; +inline constexpr float TIMELINE_BAR_HEIGHT = 14.0f; +inline constexpr float STATUS_BAR_HEIGHT = 52.0f; +inline constexpr double MIN_HORIZONTAL_ZOOM_SECONDS = 2.0; +inline constexpr double PLOT_Y_PADDING_FRACTION = 0.05; + +struct UiMetrics { + float width = 0.0f; + float height = 0.0f; + float top_offset = 0.0f; + float sidebar_width = SIDEBAR_WIDTH; + float content_x = 0.0f; + float content_y = 0.0f; + float content_w = 0.0f; + float content_h = 0.0f; + float status_bar_y = 0.0f; +}; + +std::filesystem::path resolve_layout_path(const std::string &layout_arg); +std::filesystem::path autosave_path_for_layout(const std::filesystem::path &layout_path); +std::vector available_layout_names(); + +SketchLayout make_empty_layout(); +void cancel_rename_tab(UiState *state); +void sync_ui_state(UiState *state, const SketchLayout &layout); +void sync_route_buffers(UiState *state, const AppSession &session); +void sync_stream_buffers(UiState *state, const AppSession &session); +void sync_layout_buffers(UiState *state, const AppSession &session); +void mark_all_docks_dirty(UiState *state); +void clear_layout_autosave(const AppSession &session); +bool autosave_layout(AppSession *session, UiState *state); +bool apply_axis_limits_editor(AppSession *session, UiState *state); +void open_axis_limits_editor(const AppSession &session, UiState *state, int pane_index); +void persist_shared_range_to_tab(WorkspaceTab *tab, const UiState &state); +void clear_pane_vertical_limits(Pane *pane); + +void refresh_replaced_layout_ui(AppSession *session, UiState *state, bool mark_docks); +void start_new_layout(AppSession *session, UiState *state, const std::string &status_text = "New untitled layout"); +void apply_dbc_override_change(AppSession *session, UiState *state, const std::string &dbc_override); + +void app_push_bold_font(); +void app_pop_bold_font(); +void draw_vertical_splitter(const char *id, float height, float min_left, float max_left, float *left_width); +void draw_right_splitter(const char *id, float height, float min_right, float max_right, float *right_width); +bool draw_horizontal_splitter(const char *id, float width, float min_top, float max_top, float *top_height); +void draw_payload_bytes(std::string_view data, const std::string *prev_data = nullptr); +void draw_payload_preview_boxes(const char *id, std::string_view data, const std::string *prev_data, float max_width); +void draw_signal_sparkline(const AppSession &session, + const UiState &state, + std::string_view signal_path, + bool selected, + ImVec2 size = ImVec2(0.0f, 24.0f)); +ImU32 mix_color(ImU32 a, ImU32 b, float t); +void draw_empty_panel(const char *title, const char *message); + +UiMetrics compute_ui_metrics(const ImVec2 &size, float top_offset, float sidebar_width); +void draw_sidebar(AppSession *session, const UiMetrics &ui, UiState *state, bool show_camera_feed); +void draw_workspace(AppSession *session, const UiMetrics &ui, UiState *state); +void draw_pane_windows(AppSession *session, UiState *state); + +// plot.cc +void draw_plot(const AppSession &session, Pane *pane, UiState *state); +bool draw_pane_close_button_overlay(); +void draw_pane_frame_overlay(); +std::optional draw_pane_context_menu(const WorkspaceTab &tab, int pane_index); +bool curve_has_samples(const AppSession &session, const Curve &curve); +bool curve_has_local_samples(const Curve &curve); +std::string app_curve_display_name(const Curve &curve); +bool mark_layout_dirty(AppSession *session, UiState *state); + +const RouteSeries *app_find_route_series(const AppSession &session, const std::string &path); +void sync_camera_feeds(AppSession *session); +void apply_route_data(AppSession *session, UiState *state, RouteData route_data); +bool apply_undo(AppSession *session, UiState *state); +bool apply_redo(AppSession *session, UiState *state); +bool infer_stream_follow_state(const UiState &state, const AppSession &session); +void ensure_shared_range(UiState *state, const AppSession &session); +void clamp_shared_range(UiState *state, const AppSession &session); +void reset_shared_range(UiState *state, const AppSession &session); +void update_follow_range(UiState *state, const AppSession &session); +void advance_playback(UiState *state, const AppSession &session); +void step_tracker(UiState *state, double direction); +std::string dbc_combo_label(const AppSession &session); +const char *log_selector_name(LogSelector selector); +const char *log_selector_description(LogSelector selector); +std::string format_cache_bytes(uint64_t bytes); +MapCacheStats directory_cache_stats(const std::filesystem::path &root); +float draw_main_menu_bar(AppSession *session, UiState *state); + +bool reset_layout(AppSession *session, UiState *state); +bool reload_layout(AppSession *session, UiState *state, const std::string &layout_arg); +bool save_layout(AppSession *session, UiState *state, const std::string &layout_path); +void rebuild_session_route_data(AppSession *session, UiState *state, + const RouteLoadProgressCallback &progress = {}); +void stop_stream_session(AppSession *session, UiState *state, bool preserve_data = true); +bool start_stream_session(AppSession *session, + UiState *state, + const StreamSourceConfig &source, + double buffer_seconds, + bool preserve_existing_data = false); +void start_async_route_load(AppSession *session, UiState *state); +void poll_async_route_load(AppSession *session, UiState *state); +bool reload_session(AppSession *session, UiState *state, const std::string &route_name, const std::string &data_dir); +void draw_popups(AppSession *session, UiState *state); + +void draw_status_bar(const AppSession &session, const UiMetrics &ui, UiState *state); +void draw_sidebar_resizer(const UiMetrics &ui, UiState *state); + +void apply_stream_batch(AppSession *session, UiState *state, StreamExtractBatch batch); + +void render_frame(GLFWwindow *window, AppSession *session, UiState *state, const std::filesystem::path *capture_path); diff --git a/openpilot/tools/jotpluggler/layout.cc b/openpilot/tools/jotpluggler/layout.cc new file mode 100644 index 0000000000..6bc3a6168a --- /dev/null +++ b/openpilot/tools/jotpluggler/layout.cc @@ -0,0 +1,704 @@ +#include "tools/jotpluggler/internal.h" +#include "common/hardware/hw.h" + +#include + +namespace fs = std::filesystem; + +namespace { + +enum class ModalAction { + None, + Primary, + Secondary, +}; + +struct FindSignalMatch { + const std::string *path = nullptr; + int score = 0; +}; + +struct DbcEditorSource { + fs::path path; + DbcEditorState::SourceKind kind = DbcEditorState::SourceKind::None; +}; + +StreamSourceConfig stream_source_config_from_ui(const UiState &state) { + StreamSourceConfig source; + source.kind = state.stream_source_kind; + source.address = util::strip(state.stream_address_buffer); + if (source.kind == StreamSourceKind::CerealLocal) { + source.address = "127.0.0.1"; + } else { + source.address = normalize_stream_address(std::move(source.address)); + } + return source; +} + +void open_queued_popup(bool &flag, const char *name) { + if (flag) { + ImGui::OpenPopup(name); + flag = false; + } +} + +ModalAction draw_modal_action_row(const char *primary_label, + const char *secondary_label = "Cancel", + float width = 120.0f) { + if (ImGui::Button(primary_label, ImVec2(width, 0.0f))) { + return ModalAction::Primary; + } + ImGui::SameLine(); + if (ImGui::Button(secondary_label, ImVec2(width, 0.0f))) { + return ModalAction::Secondary; + } + return ModalAction::None; +} + +std::vector find_signal_matches(const AppSession &session, std::string_view query) { + std::vector matches; + if (query.empty()) { + return matches; + } + const std::string needle = lowercase_copy(query); + for (const std::string &path : session.route_data.paths) { + const std::string hay = lowercase_copy(path); + const size_t pos = hay.find(needle); + if (pos == std::string::npos) { + continue; + } + const size_t slash = path.find_last_of('/'); + const std::string_view label = slash == std::string::npos ? std::string_view(path) : std::string_view(path).substr(slash + 1); + int score = static_cast(pos * 8 + path.size()); + if (lowercase_copy(label) == needle) score -= 60; + if (util::starts_with(hay, needle)) score -= 30; + matches.push_back({.path = &path, .score = score}); + } + std::sort(matches.begin(), matches.end(), [](const FindSignalMatch &a, const FindSignalMatch &b) { + return std::tie(a.score, *a.path) < std::tie(b.score, *b.path); + }); + if (matches.size() > 200) { + matches.resize(200); + } + return matches; +} + +bool open_find_signal_result(UiState *state, const std::string &path) { + state->selected_browser_paths = {path}; + state->selected_browser_path = path; + state->browser_selection_anchor = path; + state->status_text = "Selected signal " + path; + return true; +} + +void draw_open_route_popup(AppSession *session, UiState *state) { + if (!app_begin_popup_modal("Open Route")) { + return; + } + ImGui::TextUnformatted("Load a route into the current layout."); + ImGui::Separator(); + input_text_string("Route", &state->route_buffer); + input_text_string("Data Dir", &state->data_dir_buffer); + ImGui::Spacing(); + switch (draw_modal_action_row("Load")) { + case ModalAction::Primary: + reload_session(session, state, state->route_buffer, state->data_dir_buffer); + ImGui::CloseCurrentPopup(); + break; + case ModalAction::Secondary: + sync_route_buffers(state, *session); + ImGui::CloseCurrentPopup(); + break; + case ModalAction::None: + break; + } + ImGui::EndPopup(); +} + +void draw_stream_popup(AppSession *session, UiState *state) { + if (!app_begin_popup_modal("Live Stream")) { + return; + } + + ImGui::TextUnformatted("Connect to a live source."); + ImGui::Separator(); + if (ImGui::RadioButton("Local (MSGQ)", state->stream_source_kind == StreamSourceKind::CerealLocal)) { + state->stream_source_kind = StreamSourceKind::CerealLocal; + } + if (ImGui::RadioButton("Remote (ZMQ)", state->stream_source_kind == StreamSourceKind::CerealRemote)) { + state->stream_source_kind = StreamSourceKind::CerealRemote; + } + + if (state->stream_source_kind == StreamSourceKind::CerealRemote) { + input_text_string("Address", &state->stream_address_buffer); + } + ImGui::InputDouble("Buffer (seconds)", &state->stream_buffer_seconds, 0.0, 0.0, "%.0f"); + ImGui::Spacing(); + switch (draw_modal_action_row("Connect")) { + case ModalAction::Primary: { + const StreamSourceConfig source = stream_source_config_from_ui(*state); + if (start_stream_session(session, state, source, state->stream_buffer_seconds, false)) { + ImGui::CloseCurrentPopup(); + } + break; + } + case ModalAction::Secondary: + sync_stream_buffers(state, *session); + ImGui::CloseCurrentPopup(); + break; + case ModalAction::None: + break; + } + ImGui::EndPopup(); +} + +void draw_load_layout_popup(AppSession *session, UiState *state) { + if (!app_begin_popup_modal("Load Layout")) { + return; + } + ImGui::TextUnformatted("Load a JotPlugger JSON layout."); + ImGui::Separator(); + input_text_string("Layout", &state->load_layout_buffer); + ImGui::Spacing(); + switch (draw_modal_action_row("Load")) { + case ModalAction::Primary: + if (reload_layout(session, state, state->load_layout_buffer)) { + ImGui::CloseCurrentPopup(); + } + break; + case ModalAction::Secondary: + sync_layout_buffers(state, *session); + ImGui::CloseCurrentPopup(); + break; + case ModalAction::None: + break; + } + ImGui::EndPopup(); +} + +void draw_save_layout_popup(AppSession *session, UiState *state) { + if (!app_begin_popup_modal("Save Layout")) { + return; + } + ImGui::TextUnformatted("Save the current workspace as a JotPlugger JSON layout."); + ImGui::Separator(); + input_text_string("Layout", &state->save_layout_buffer); + ImGui::Spacing(); + switch (draw_modal_action_row("Save")) { + case ModalAction::Primary: + if (save_layout(session, state, state->save_layout_buffer)) { + ImGui::CloseCurrentPopup(); + } + break; + case ModalAction::Secondary: + sync_layout_buffers(state, *session); + ImGui::CloseCurrentPopup(); + break; + case ModalAction::None: + break; + } + ImGui::EndPopup(); +} + +void draw_preferences_popup(AppSession *session, UiState *state) { + if (!app_begin_popup_modal("Preferences")) { + return; + } + if (session->map_data) { + const MapCacheStats map_cache = session->map_data->cacheStats(); + const MapCacheStats download_cache = directory_cache_stats(Path::download_cache_root()); + ImGui::TextUnformatted("Map"); + ImGui::Separator(); + ImGui::Text("Map cache: %s in %zu file%s", + format_cache_bytes(map_cache.bytes).c_str(), + map_cache.files, + map_cache.files == 1 ? "" : "s"); + if (ImGui::Button("Clear Map Cache", ImVec2(120.0f, 0.0f))) { + session->map_data->clearCache(); + state->status_text = "Cleared map cache"; + } + ImGui::Spacing(); + ImGui::TextUnformatted("comma Download Cache"); + ImGui::Separator(); + ImGui::Text("Download cache: %s in %zu file%s", + format_cache_bytes(download_cache.bytes).c_str(), + download_cache.files, + download_cache.files == 1 ? "" : "s"); + ImGui::TextDisabled("%s", Path::download_cache_root().c_str()); + ImGui::Spacing(); + } + if (ImGui::Button("Close", ImVec2(120.0f, 0.0f))) { + ImGui::CloseCurrentPopup(); + } + ImGui::EndPopup(); +} + +void draw_find_signal_popup(AppSession *session, UiState *state) { + if (!app_begin_popup_modal("Find Signal")) { + return; + } + ImGui::TextUnformatted("Search decoded signals across the loaded route."); + ImGui::Separator(); + ImGui::SetNextItemWidth(560.0f); + input_text_with_hint_string("##find_signal_query", "Search signal path or name...", &state->find_signal_buffer); + if (ImGui::IsWindowAppearing()) { + ImGui::SetKeyboardFocusHere(-1); + } + const std::vector matches = find_signal_matches(*session, state->find_signal_buffer); + ImGui::Spacing(); + ImGui::TextDisabled("%zu match%s", matches.size(), matches.size() == 1 ? "" : "es"); + if (ImGui::BeginChild("##find_signal_results", ImVec2(760.0f, 360.0f), true)) { + for (const FindSignalMatch &match : matches) { + const std::string &path = *match.path; + const size_t slash = path.find_last_of('/'); + const std::string_view label = slash == std::string::npos ? std::string_view(path) : std::string_view(path).substr(slash + 1); + if (ImGui::Selectable((std::string(label) + "##" + path).c_str(), false, ImGuiSelectableFlags_SpanAllColumns)) { + if (open_find_signal_result(state, path)) { + ImGui::CloseCurrentPopup(); + } + } + ImGui::SameLine(280.0f); + ImGui::TextDisabled("%s", path.c_str()); + } + } + ImGui::EndChild(); + ImGui::Spacing(); + if (ImGui::Button("Close", ImVec2(120.0f, 0.0f))) { + ImGui::CloseCurrentPopup(); + } + ImGui::EndPopup(); +} + +std::string default_dbc_template() { + return "VERSION \"\"\n\nNS_ :\nBS_:\nBU_: XXX\n"; +} + +DbcEditorSource resolve_dbc_editor_source(const std::string &dbc_name) { + const fs::path generated_dbc_dir = repo_root() / "openpilot" / "tools" / "jotpluggler" / "generated_dbcs"; + const std::array candidates = {{ + {.path = repo_root() / "opendbc_repo" / "opendbc" / "dbc" / (dbc_name + ".dbc"), .kind = DbcEditorState::SourceKind::Opendbc}, + {.path = generated_dbc_dir / (dbc_name + ".dbc"), .kind = DbcEditorState::SourceKind::Generated}, + }}; + for (const DbcEditorSource &candidate : candidates) { + if (fs::exists(candidate.path)) { + return candidate; + } + } + return {}; +} + +void load_dbc_editor_state(const AppSession &session, UiState *state) { + DbcEditorState &editor = state->dbc_editor; + const std::string dbc_name = !session.dbc_override.empty() ? session.dbc_override : session.route_data.dbc_name; + editor.source_name = dbc_name.empty() ? "untitled" : dbc_name; + editor.source_path.clear(); + editor.source_kind = DbcEditorState::SourceKind::None; + if (dbc_name.empty()) { + editor.save_name = "custom_can"; + editor.text = default_dbc_template(); + } else { + const DbcEditorSource source = resolve_dbc_editor_source(dbc_name); + editor.source_kind = source.kind; + editor.source_path = source.path; + editor.text = source.path.empty() ? default_dbc_template() : read_file_or_throw(source.path); + editor.save_name = source.kind == DbcEditorState::SourceKind::Generated ? dbc_name : dbc_name + "_edited"; + } + editor.loaded = true; +} + +bool ensure_dbc_editor_loaded(const AppSession &session, UiState *state) { + if (!state->dbc_editor.loaded) { + try { + load_dbc_editor_state(session, state); + } catch (const std::exception &err) { + state->error_text = err.what(); + state->open_error_popup = true; + return false; + } + } + return true; +} + +bool save_dbc_editor_contents(AppSession *session, UiState *state) { + DbcEditorState &editor = state->dbc_editor; + editor.save_name = util::strip(editor.save_name); + if (editor.save_name.empty()) { + state->error_text = "DBC name cannot be empty"; + state->open_error_popup = true; + return false; + } + if (editor.source_kind == DbcEditorState::SourceKind::Opendbc && editor.save_name == editor.source_name) { + state->error_text = "Save edited opendbc files under a new name"; + state->open_error_popup = true; + return false; + } + try { + dbc::Database::fromContent(editor.text, editor.save_name + ".dbc"); + const fs::path generated_dbc_dir = repo_root() / "openpilot" / "tools" / "jotpluggler" / "generated_dbcs"; + fs::create_directories(generated_dbc_dir); + const fs::path output = generated_dbc_dir / (editor.save_name + ".dbc"); + write_file_or_throw(output, editor.text); + apply_dbc_override_change(session, state, editor.save_name); + editor.source_name = editor.save_name; + editor.source_path = output; + editor.source_kind = DbcEditorState::SourceKind::Generated; + editor.loaded = false; + state->status_text = "Saved DBC " + editor.save_name; + return true; + } catch (const std::exception &err) { + state->error_text = err.what(); + state->open_error_popup = true; + return false; + } +} + +void draw_dbc_editor_popup(AppSession *session, UiState *state) { + if (!app_begin_popup_modal("DBC Editor")) { + return; + } + DbcEditorState &editor = state->dbc_editor; + if (!ensure_dbc_editor_loaded(*session, state)) { + ImGui::CloseCurrentPopup(); + ImGui::EndPopup(); + return; + } + ImGui::TextUnformatted("Edit DBC text and save it into generated_dbcs."); + ImGui::Separator(); + ImGui::SetNextItemWidth(260.0f); + input_text_string("DBC Name", &editor.save_name, ImGuiInputTextFlags_AutoSelectAll); + if (!editor.source_path.empty()) { + ImGui::TextDisabled("%s", editor.source_path.string().c_str()); + } else { + ImGui::TextDisabled("New in-memory DBC"); + } + ImGui::Spacing(); + input_text_multiline_string("##dbc_editor_text", &editor.text, ImVec2(920.0f, 520.0f), ImGuiInputTextFlags_AllowTabInput); + ImGui::Spacing(); + if (ImGui::Button("Apply + Save", ImVec2(140.0f, 0.0f))) { + if (save_dbc_editor_contents(session, state)) { + ImGui::CloseCurrentPopup(); + } + } + ImGui::SameLine(); + if (ImGui::Button("Reload Source", ImVec2(140.0f, 0.0f))) { + editor.loaded = false; + } + ImGui::SameLine(); + if (ImGui::Button("Close", ImVec2(120.0f, 0.0f))) { + editor.loaded = false; + ImGui::CloseCurrentPopup(); + } + ImGui::EndPopup(); +} + +void draw_axis_limits_popup(AppSession *session, UiState *state) { + if (!app_begin_popup_modal("Edit Axis Limits")) { + return; + } + const WorkspaceTab *tab = app_active_tab(session->layout, *state); + const bool valid_pane = tab != nullptr + && state->axis_limits.pane_index >= 0 + && state->axis_limits.pane_index < static_cast(tab->panes.size()); + if (!valid_pane) { + ImGui::TextWrapped("The selected pane is no longer available."); + ImGui::Spacing(); + if (ImGui::Button("Close", ImVec2(120.0f, 0.0f))) { + state->axis_limits.pane_index = -1; + ImGui::CloseCurrentPopup(); + } + ImGui::EndPopup(); + return; + } + + ImGui::TextUnformatted("X range applies to the active tab. Y limits apply to the selected pane."); + ImGui::Separator(); + ImGui::TextUnformatted("Horizontal"); + ImGui::SetNextItemWidth(180.0f); + ImGui::InputDouble("X Min", &state->axis_limits.x_min, 0.0, 0.0, "%.3f"); + ImGui::SetNextItemWidth(180.0f); + ImGui::InputDouble("X Max", &state->axis_limits.x_max, 0.0, 0.0, "%.3f"); + ImGui::Spacing(); + ImGui::TextUnformatted("Vertical"); + ImGui::Checkbox("Use Y Min", &state->axis_limits.y_min_enabled); + ImGui::BeginDisabled(!state->axis_limits.y_min_enabled); + ImGui::SetNextItemWidth(180.0f); + ImGui::InputDouble("Y Min", &state->axis_limits.y_min, 0.0, 0.0, "%.6g"); + ImGui::EndDisabled(); + ImGui::Checkbox("Use Y Max", &state->axis_limits.y_max_enabled); + ImGui::BeginDisabled(!state->axis_limits.y_max_enabled); + ImGui::SetNextItemWidth(180.0f); + ImGui::InputDouble("Y Max", &state->axis_limits.y_max, 0.0, 0.0, "%.6g"); + ImGui::EndDisabled(); + ImGui::Spacing(); + switch (draw_modal_action_row("Apply")) { + case ModalAction::Primary: + if (apply_axis_limits_editor(session, state)) { + state->axis_limits.pane_index = -1; + ImGui::CloseCurrentPopup(); + } + break; + case ModalAction::Secondary: + state->axis_limits.pane_index = -1; + ImGui::CloseCurrentPopup(); + break; + case ModalAction::None: + break; + } + ImGui::EndPopup(); +} + +void draw_error_popup(UiState *state) { + if (state->open_error_popup) { + ImGui::OpenPopup("Error"); + state->open_error_popup = false; + } + if (!app_begin_popup_modal("Error")) { + return; + } + ImGui::TextWrapped("%s", state->error_text.c_str()); + ImGui::Spacing(); + if (ImGui::Button("Close", ImVec2(120.0f, 0.0f))) { + ImGui::CloseCurrentPopup(); + } + ImGui::EndPopup(); +} + +} // namespace + +bool reset_layout(AppSession *session, UiState *state) { + try { + if (session->layout_path.empty()) { + start_new_layout(session, state, "Reset layout"); + return true; + } + clear_layout_autosave(*session); + session->layout = load_sketch_layout(session->layout_path); + state->layout_dirty = false; + session->autosave_path = autosave_path_for_layout(session->layout_path); + state->undo.reset(session->layout); + refresh_replaced_layout_ui(session, state, false); + reset_shared_range(state, *session); + state->status_text = "Reset layout"; + return true; + } catch (const std::exception &err) { + state->error_text = err.what(); + state->open_error_popup = true; + state->status_text = "Failed to reset layout"; + return false; + } +} + +bool reload_layout(AppSession *session, UiState *state, const std::string &layout_arg) { + try { + const bool preserve_shared_range = session->route_data.has_time_range && state->has_shared_range; + const double preserved_x_min = state->x_view_min; + const double preserved_x_max = state->x_view_max; + const fs::path layout_path = resolve_layout_path(layout_arg); + session->autosave_path = autosave_path_for_layout(layout_path); + const bool load_draft = fs::exists(session->autosave_path); + session->layout = load_sketch_layout(load_draft ? session->autosave_path : layout_path); + session->layout_path = layout_path; + state->layout_dirty = load_draft; + state->undo.reset(session->layout); + refresh_replaced_layout_ui(session, state, true); + if (preserve_shared_range) { + state->has_shared_range = true; + state->x_view_min = preserved_x_min; + state->x_view_max = preserved_x_max; + clamp_shared_range(state, *session); + } else { + reset_shared_range(state, *session); + } + state->status_text = std::string(load_draft ? "Loaded layout draft " : "Loaded layout ") + + layout_path.filename().string(); + return true; + } catch (const std::exception &err) { + state->error_text = err.what(); + state->open_error_popup = true; + state->status_text = "Failed to load layout"; + return false; + } +} + +bool save_layout(AppSession *session, UiState *state, const std::string &layout_path) { + try { + if (layout_path.empty()) throw std::runtime_error("Layout path is empty"); + session->layout.current_tab_index = state->active_tab_index; + const fs::path previous_autosave = session->autosave_path; + const fs::path output = fs::absolute(fs::path(layout_path)); + save_layout_json(session->layout, output); + session->layout_path = output; + session->autosave_path = autosave_path_for_layout(output); + if (!previous_autosave.empty() && previous_autosave != session->autosave_path && fs::exists(previous_autosave)) { + fs::remove(previous_autosave); + } + clear_layout_autosave(*session); + state->layout_dirty = false; + sync_layout_buffers(state, *session); + state->status_text = "Saved layout " + output.filename().string(); + return true; + } catch (const std::exception &err) { + state->error_text = err.what(); + state->open_error_popup = true; + state->status_text = "Failed to save layout"; + return false; + } +} + +void rebuild_session_route_data(AppSession *session, UiState *state, + const RouteLoadProgressCallback &progress) { + apply_route_data(session, state, load_route_data(session->route_name, session->data_dir, session->dbc_override, progress)); +} + +void stop_stream_session(AppSession *session, UiState *state, bool preserve_data) { + if (preserve_data && session->stream_poller && session->data_mode == SessionDataMode::Stream) { + session->stream_poller->setPaused(true); + } else if (session->stream_poller) { + session->stream_poller->stop(); + } + session->stream_paused = preserve_data && session->data_mode == SessionDataMode::Stream; + if (!preserve_data) { + session->stream_time_offset.reset(); + apply_route_data(session, state, RouteData{}); + } + sync_stream_buffers(state, *session); +} + +bool start_stream_session(AppSession *session, + UiState *state, + const StreamSourceConfig &source, + double buffer_seconds, + bool preserve_existing_data) { + try { + if (session->route_loader) { + session->route_loader.reset(); + } + session->data_mode = SessionDataMode::Stream; + session->route_id = {}; + session->route_name.clear(); + session->data_dir.clear(); + session->stream_source = source; + if (session->stream_source.kind == StreamSourceKind::CerealLocal) { + session->stream_source.address = "127.0.0.1"; + } + session->stream_buffer_seconds = std::max(1.0, buffer_seconds); + session->next_stream_custom_refresh_time = 0.0; + session->stream_paused = false; + if (preserve_existing_data && session->stream_poller) { + StreamPollSnapshot snapshot = session->stream_poller->snapshot(); + if (snapshot.active) { + session->stream_poller->setPaused(false); + sync_route_buffers(state, *session); + sync_stream_buffers(state, *session); + state->follow_latest = true; + state->playback_playing = false; + state->status_text = "Resumed stream " + stream_source_target_label(session->stream_source); + return true; + } + } + if (!preserve_existing_data) { + session->stream_time_offset.reset(); + apply_route_data(session, state, RouteData{}); + } + if (!session->stream_poller) { + session->stream_poller = std::make_unique(); + } + session->stream_poller->start(session->stream_source, + session->stream_buffer_seconds, + session->dbc_override, + session->stream_time_offset); + sync_route_buffers(state, *session); + sync_stream_buffers(state, *session); + state->follow_latest = true; + state->playback_playing = false; + state->status_text = preserve_existing_data ? "Resumed stream " + stream_source_target_label(session->stream_source) + : "Streaming from " + stream_source_target_label(session->stream_source); + return true; + } catch (const std::exception &err) { + state->error_text = err.what(); + state->open_error_popup = true; + state->status_text = "Failed to start stream"; + return false; + } +} + +void start_async_route_load(AppSession *session, UiState *state) { + if (!session->route_loader) { + return; + } + apply_route_data(session, state, RouteData{}); + session->route_loader->start(session->route_name, session->data_dir, session->dbc_override); + state->status_text = session->route_name.empty() ? "Ready" : "Loading route " + session->route_name; +} + +void poll_async_route_load(AppSession *session, UiState *state) { + if (!session->route_loader) { + return; + } + RouteData loaded_route; + std::string error_text; + if (!session->route_loader->consume(&loaded_route, &error_text)) { + return; + } + if (!error_text.empty()) { + state->error_text = error_text; + state->open_error_popup = true; + state->status_text = "Failed to load route"; + return; + } + apply_route_data(session, state, std::move(loaded_route)); + state->status_text = session->route_name.empty() ? "Ready" : "Loaded route " + session->route_name; +} + +bool reload_session(AppSession *session, UiState *state, const std::string &route_name, const std::string &data_dir) { + try { + stop_stream_session(session, state, false); + session->data_mode = SessionDataMode::Route; + session->route_name = route_name; + session->route_id = parse_route_identifier(route_name); + session->data_dir = data_dir; + if (session->async_route_loading) { + if (!session->route_loader) { + session->route_loader = std::make_unique(::isatty(STDERR_FILENO) != 0); + } + start_async_route_load(session, state); + } else { + rebuild_session_route_data(session, state); + state->status_text = "Loaded route " + route_name; + } + sync_route_buffers(state, *session); + return true; + } catch (const std::exception &err) { + state->error_text = err.what(); + state->open_error_popup = true; + state->status_text = "Failed to load route"; + return false; + } +} + +void draw_popups(AppSession *session, UiState *state) { + open_queued_popup(state->open_open_route, "Open Route"); + if (state->open_stream) { + sync_stream_buffers(state, *session); + } + open_queued_popup(state->open_stream, "Live Stream"); + if (state->open_load_layout || state->open_save_layout) { + sync_layout_buffers(state, *session); + } + open_queued_popup(state->open_load_layout, "Load Layout"); + open_queued_popup(state->open_save_layout, "Save Layout"); + open_queued_popup(state->open_preferences, "Preferences"); + open_queued_popup(state->dbc_editor.open, "DBC Editor"); + open_queued_popup(state->open_find_signal, "Find Signal"); + open_queued_popup(state->axis_limits.open, "Edit Axis Limits"); + + draw_open_route_popup(session, state); + draw_stream_popup(session, state); + draw_load_layout_popup(session, state); + draw_save_layout_popup(session, state); + draw_preferences_popup(session, state); + draw_dbc_editor_popup(session, state); + draw_find_signal_popup(session, state); + draw_axis_limits_popup(session, state); + draw_error_popup(state); +} diff --git a/openpilot/tools/jotpluggler/layout_io.cc b/openpilot/tools/jotpluggler/layout_io.cc new file mode 100644 index 0000000000..24e3a4b51f --- /dev/null +++ b/openpilot/tools/jotpluggler/layout_io.cc @@ -0,0 +1,130 @@ +#include "tools/jotpluggler/app.h" +#include "tools/jotpluggler/common.h" + +#include +#include +#include +#include + +#include "json11/json11.hpp" + +namespace fs = std::filesystem; + +namespace { + +std::string curve_color_hex(const std::array &color) { + std::ostringstream hex; + hex << "#" << std::hex << std::setfill('0') + << std::setw(2) << static_cast(color[0]) + << std::setw(2) << static_cast(color[1]) + << std::setw(2) << static_cast(color[2]); + return hex.str(); +} + +json11::Json curve_to_json(const Curve &curve) { + json11::Json::object obj = { + {"name", curve.name}, + {"color", curve_color_hex(curve.color)}, + }; + if (curve.derivative) { + obj["transform"] = "derivative"; + if (curve.derivative_dt > 0.0) { + obj["derivative_dt"] = curve.derivative_dt; + } + } else if (std::abs(curve.value_scale - 1.0) > 1.0e-9 || std::abs(curve.value_offset) > 1.0e-9) { + obj["transform"] = "scale"; + obj["scale"] = curve.value_scale; + obj["offset"] = curve.value_offset; + } + if (curve.custom_python.has_value()) { + json11::Json::array additional_sources; + for (const std::string &path : curve.custom_python->additional_sources) { + additional_sources.push_back(path); + } + obj["custom_python"] = json11::Json::object{ + {"linked_source", curve.custom_python->linked_source}, + {"additional_sources", additional_sources}, + {"globals_code", curve.custom_python->globals_code}, + {"function_code", curve.custom_python->function_code}, + }; + } + return obj; +} + +json11::Json workspace_node_to_json(const WorkspaceNode &node, const WorkspaceTab &tab) { + if (node.is_pane) { + if (node.pane_index < 0 || node.pane_index >= static_cast(tab.panes.size())) { + return nullptr; + } + const Pane &pane = tab.panes[static_cast(node.pane_index)]; + json11::Json::object obj = { + {"title", pane.title.empty() ? std::string("...") : pane.title}, + }; + if (pane.kind == PaneKind::Map) { + obj["kind"] = "map"; + } else if (pane.kind == PaneKind::Thumbnail) { + obj["kind"] = "thumbnail"; + } else if (pane.kind == PaneKind::Camera) { + obj["kind"] = "camera"; + obj["camera_view"] = camera_view_spec(pane.camera_view).layout_name; + } + if (pane.range.valid) { + obj["range"] = json11::Json::object{ + {"left", pane.range.left}, {"right", pane.range.right}, + {"top", pane.range.top}, {"bottom", pane.range.bottom}, + }; + } + if (pane.range.has_y_limit_min || pane.range.has_y_limit_max) { + json11::Json::object limits; + if (pane.range.has_y_limit_min) { + limits["min"] = pane.range.y_limit_min; + } + if (pane.range.has_y_limit_max) { + limits["max"] = pane.range.y_limit_max; + } + obj["y_limits"] = limits; + } + json11::Json::array curves; + for (const Curve &curve : pane.curves) { + if (!curve.runtime_only) { + curves.push_back(curve_to_json(curve)); + } + } + obj["curves"] = curves; + return obj; + } + + if (node.children.empty()) return nullptr; + json11::Json::array sizes; + for (size_t i = 0; i < node.children.size(); ++i) { + sizes.push_back(i < node.sizes.size() ? static_cast(node.sizes[i]) + : 1.0 / static_cast(node.children.size())); + } + json11::Json::array children; + for (const WorkspaceNode &child : node.children) { + children.push_back(workspace_node_to_json(child, tab)); + } + return json11::Json::object{ + {"split", node.orientation == SplitOrientation::Horizontal ? "horizontal" : "vertical"}, + {"sizes", sizes}, + {"children", children}, + }; +} + +} // namespace + +void save_layout_json(const SketchLayout &layout, const fs::path &path) { + ensure_parent_dir(path); + json11::Json::array tabs; + for (const WorkspaceTab &tab : layout.tabs) { + tabs.push_back(json11::Json::object{ + {"name", tab.tab_name}, + {"root", workspace_node_to_json(tab.root, tab)}, + }); + } + const json11::Json root = json11::Json::object{ + {"current_tab_index", std::clamp(layout.current_tab_index, 0, std::max(0, static_cast(layout.tabs.size()) - 1))}, + {"tabs", tabs}, + }; + write_file_or_throw(path, root.dump() + "\n"); +} diff --git a/openpilot/tools/jotpluggler/layouts/.gitignore b/openpilot/tools/jotpluggler/layouts/.gitignore new file mode 100644 index 0000000000..a965bb777d --- /dev/null +++ b/openpilot/tools/jotpluggler/layouts/.gitignore @@ -0,0 +1 @@ +.jotpluggler_autosave/ diff --git a/openpilot/tools/jotpluggler/layouts/CAN-bus-debug.json b/openpilot/tools/jotpluggler/layouts/CAN-bus-debug.json new file mode 100644 index 0000000000..496993a1fd --- /dev/null +++ b/openpilot/tools/jotpluggler/layouts/CAN-bus-debug.json @@ -0,0 +1 @@ +{"current_tab_index":0,"tabs":[{"name":"tab1","root":{"split":"vertical","sizes":[0.33362,0.33276,0.33362],"children":[{"title":"CAN RX","range":{"left":0.0,"right":60.526742,"top":1101.875,"bottom":-26.875},"curves":[{"name":"/pandaStates/0/canState0/totalRxCnt","color":"#f14cc1","transform":"derivative","derivative_dt":1.0},{"name":"/pandaStates/0/canState1/totalRxCnt","color":"#9467bd","transform":"derivative","derivative_dt":1.0},{"name":"/pandaStates/0/canState2/totalRxCnt","color":"#ff7f0e","transform":"derivative","derivative_dt":1.0}]},{"title":"CAN TX","range":{"left":0.0,"right":60.526742,"top":455.1,"bottom":-11.1},"curves":[{"name":"/pandaStates/0/canState0/totalTxCnt","color":"#17becf","transform":"derivative","derivative_dt":1.0},{"name":"/pandaStates/0/canState1/totalTxCnt","color":"#bcbd22","transform":"derivative","derivative_dt":1.0},{"name":"/pandaStates/0/canState2/totalTxCnt","color":"#1f77b4","transform":"derivative","derivative_dt":1.0}]},{"title":"CAN errors","range":{"left":0.0,"right":60.526742,"top":2515.35,"bottom":-61.35},"curves":[{"name":"/pandaStates/0/canState0/totalErrorCnt","color":"#1f77b4","transform":"derivative","derivative_dt":1.0},{"name":"/pandaStates/0/canState1/totalErrorCnt","color":"#d62728","transform":"derivative","derivative_dt":1.0},{"name":"/pandaStates/0/canState2/totalErrorCnt","color":"#1ac938","transform":"derivative","derivative_dt":1.0}]}]}}]} diff --git a/openpilot/tools/jotpluggler/layouts/camera-timings.json b/openpilot/tools/jotpluggler/layouts/camera-timings.json new file mode 100644 index 0000000000..64decf15d3 --- /dev/null +++ b/openpilot/tools/jotpluggler/layouts/camera-timings.json @@ -0,0 +1 @@ +{"current_tab_index":0,"tabs":[{"name":"SOF / EOF (encodeIdx)","root":{"split":"vertical","sizes":[0.500885,0.499115],"children":[{"title":"...","range":{"left":0.0,"right":630.006367,"top":65000000.0,"bottom":35000000.0},"curves":[{"name":"/driverEncodeIdx/timestampSof","color":"#1f77b4","transform":"derivative","derivative_dt":1.0},{"name":"/roadEncodeIdx/timestampSof","color":"#d62728","transform":"derivative","derivative_dt":1.0},{"name":"/wideRoadEncodeIdx/timestampSof","color":"#1ac938","transform":"derivative","derivative_dt":1.0}],"y_limits":{"min":35000000.0,"max":65000000.0}},{"title":"...","range":{"left":0.0,"right":630.006367,"top":65000000.0,"bottom":35000000.0},"curves":[{"name":"/driverEncodeIdx/timestampEof","color":"#f14cc1","transform":"derivative","derivative_dt":1.0},{"name":"/roadEncodeIdx/timestampEof","color":"#9467bd","transform":"derivative","derivative_dt":1.0},{"name":"/wideRoadEncodeIdx/timestampEof","color":"#17becf","transform":"derivative","derivative_dt":1.0}],"y_limits":{"min":35000000.0,"max":65000000.0}}]}},{"name":"model timings","root":{"split":"vertical","sizes":[0.5,0.5],"children":[{"title":"...","range":{"left":0.0,"right":630.006367,"top":0.016865,"bottom":0.015143},"curves":[{"name":"/modelV2/modelExecutionTime","color":"#ff7f0e"}]},{"title":"...","range":{"left":0.0,"right":630.006367,"top":0.1,"bottom":-0.1},"curves":[{"name":"/modelV2/frameDropPerc","color":"#f14cc1"}]}]}},{"name":"sensor info","root":{"split":"vertical","sizes":[1.0],"children":[{"title":"...","range":{"left":0.0,"right":630.006367,"top":0.1,"bottom":-0.1},"curves":[{"name":"/driverCameraState/sensor","color":"#bcbd22"},{"name":"/roadCameraState/sensor","color":"#1f77b4"},{"name":"/wideRoadCameraState/sensor","color":"#d62728"}]}]}},{"name":"SOF / EOF (cameraState)","root":{"split":"vertical","sizes":[0.500885,0.499115],"children":[{"title":"...","range":{"left":0.0,"right":630.006367,"top":65000000.0,"bottom":35000000.0},"curves":[{"name":"/driverCameraState/timestampSof","color":"#1f77b4","transform":"derivative","derivative_dt":1.0},{"name":"/roadCameraState/timestampSof","color":"#d62728","transform":"derivative","derivative_dt":1.0},{"name":"/wideRoadCameraState/timestampSof","color":"#1ac938","transform":"derivative","derivative_dt":1.0}],"y_limits":{"min":35000000.0,"max":65000000.0}},{"title":"...","range":{"left":0.0,"right":630.006367,"top":65000000.0,"bottom":35000000.0},"curves":[{"name":"/driverCameraState/timestampEof","color":"#ff7f0e","transform":"derivative","derivative_dt":1.0},{"name":"/roadCameraState/timestampEof","color":"#f14cc1","transform":"derivative","derivative_dt":1.0},{"name":"/wideRoadCameraState/timestampEof","color":"#9467bd","transform":"derivative","derivative_dt":1.0}],"y_limits":{"min":35000000.0,"max":65000000.0}}]}}]} diff --git a/openpilot/tools/jotpluggler/layouts/cameras-and-map.json b/openpilot/tools/jotpluggler/layouts/cameras-and-map.json new file mode 100644 index 0000000000..68c590f7bc --- /dev/null +++ b/openpilot/tools/jotpluggler/layouts/cameras-and-map.json @@ -0,0 +1 @@ +{"current_tab_index": 0, "tabs": [{"name": "tab1", "root": {"children": [{"children": [{"curves": [], "kind": "map", "title": "Map"}, {"camera_view": "road", "curves": [], "kind": "camera", "title": "Road Camera"}], "sizes": [0.5, 0.5], "split": "horizontal"}, {"children": [{"camera_view": "wide_road", "curves": [], "kind": "camera", "title": "Wide Road Camera"}, {"camera_view": "driver", "curves": [], "kind": "camera", "title": "Driver Camera"}], "sizes": [0.5, 0.5], "split": "horizontal"}], "sizes": [0.5, 0.5], "split": "vertical"}}]} diff --git a/openpilot/tools/jotpluggler/layouts/can-states.json b/openpilot/tools/jotpluggler/layouts/can-states.json new file mode 100644 index 0000000000..6f04940a33 --- /dev/null +++ b/openpilot/tools/jotpluggler/layouts/can-states.json @@ -0,0 +1 @@ +{"current_tab_index":0,"tabs":[{"name":"tab1","root":{"split":"vertical","sizes":[0.500381,0.499619],"children":[{"split":"horizontal","sizes":[0.5,0.5],"children":[{"title":"...","range":{"left":0.0,"right":632.799721,"top":771630.925,"bottom":-17755.925},"curves":[{"name":"/pandaStates/0/canState0/totalRxCnt","color":"#1f77b4"},{"name":"/pandaStates/0/canState1/totalRxCnt","color":"#d62728"},{"name":"/pandaStates/0/canState2/totalRxCnt","color":"#1ac938"}]},{"title":"...","range":{"left":0.0,"right":632.799721,"top":760365.5,"bottom":-18545.5},"curves":[{"name":"/pandaStates/0/canState0/totalTxCnt","color":"#ff7f0e"},{"name":"/pandaStates/0/canState1/totalTxCnt","color":"#f14cc1"},{"name":"/pandaStates/0/canState2/totalTxCnt","color":"#9467bd"}]}]},{"split":"horizontal","sizes":[0.333333,0.333333,0.333333],"children":[{"title":"...","range":{"left":0.0,"right":632.799721,"top":55.35,"bottom":-1.35},"curves":[{"name":"/pandaStates/0/canState0/totalRxLostCnt","color":"#ff7f0e"},{"name":"/pandaStates/0/canState1/totalRxLostCnt","color":"#f14cc1"},{"name":"/pandaStates/0/canState2/totalRxLostCnt","color":"#9467bd"}]},{"title":"...","range":{"left":0.0,"right":632.799721,"top":2.05,"bottom":-0.05},"curves":[{"name":"/pandaStates/0/canState0/totalTxLostCnt","color":"#17becf"},{"name":"/pandaStates/0/canState1/totalTxLostCnt","color":"#bcbd22"},{"name":"/pandaStates/0/canState2/totalTxLostCnt","color":"#1f77b4"}]},{"title":"...","range":{"left":0.0,"right":632.799721,"top":0.1,"bottom":-0.1},"curves":[{"name":"/pandaStates/0/canState0/busOffCnt","color":"#17becf"},{"name":"/pandaStates/0/canState1/busOffCnt","color":"#1ac938"},{"name":"/pandaStates/0/canState2/busOffCnt","color":"#bcbd22"}]}]}]}}]} diff --git a/openpilot/tools/jotpluggler/layouts/controls_mismatch_debug.json b/openpilot/tools/jotpluggler/layouts/controls_mismatch_debug.json new file mode 100644 index 0000000000..16912cd684 --- /dev/null +++ b/openpilot/tools/jotpluggler/layouts/controls_mismatch_debug.json @@ -0,0 +1 @@ +{"current_tab_index":0,"tabs":[{"name":"tab1","root":{"split":"vertical","sizes":[0.2,0.2,0.2,0.2,0.2],"children":[{"title":"...","range":{"left":0.018309,"right":59.674401,"top":1.025,"bottom":-0.025},"curves":[{"name":"/carControl/enabled","color":"#1f77b4"},{"name":"/pandaStates/0/controlsAllowed","color":"#d62728"}]},{"title":"...","range":{"left":0.018309,"right":59.674401,"top":27.087398,"bottom":-0.905168},"curves":[{"name":"/carState/cumLagMs","color":"#9467bd"}]},{"title":"...","range":{"left":0.018309,"right":59.674401,"top":1.025,"bottom":-0.025},"curves":[{"name":"/pandaStates/0/safetyRxInvalid","color":"#1f77b4"},{"name":"/pandaStates/0/safetyRxChecksInvalid","color":"#e801ce"}]},{"title":"...","range":{"left":0.018309,"right":59.674401,"top":158.85,"bottom":-2.85},"curves":[{"name":"/pandaStates/0/safetyTxBlocked","color":"#d62728"}]},{"title":"...","range":{"left":0.018309,"right":59.674401,"top":1.025,"bottom":-0.025},"curves":[{"name":"/carState/gasPressed","color":"#1ac938"},{"name":"/carState/brakePressed","color":"#ff7f0e"}]}]}}]} diff --git a/openpilot/tools/jotpluggler/layouts/driver-monitoring-debug.json b/openpilot/tools/jotpluggler/layouts/driver-monitoring-debug.json new file mode 100644 index 0000000000..07a5c2fd6e --- /dev/null +++ b/openpilot/tools/jotpluggler/layouts/driver-monitoring-debug.json @@ -0,0 +1 @@ +{"current_tab_index": 0, "tabs": [{"name": "tab1", "root": {"children": [{"children": [{"camera_view": "driver", "curves": [], "kind": "camera", "title": "Driver Camera"}, {"curves": [{"color": "#236bb4", "name": "/driverMonitoringState/alertLevel"}], "title": "..."}], "sizes": [0.5, 0.5], "split": "vertical"}, {"children": [{"curves": [{"color": "#236bb4", "name": "/driverMonitoringState/activePolicy"}], "title": "..."}, {"curves": [{"color": "#236bb4", "name": "/driverMonitoringState/visionPolicyState/faceDetected"}], "title": "..."}, {"curves": [{"color": "#236bb4", "name": "/driverMonitoringState/visionPolicyState/distractedTypes/eye"}, {"color": "#dc5234", "name": "/driverMonitoringState/visionPolicyState/distractedTypes/phone"}, {"color": "#43a047", "name": "/driverMonitoringState/visionPolicyState/distractedTypes/pose"}], "title": "..."}, {"curves": [{"color": "#236bb4", "name": "/driverMonitoringState/visionPolicyState/awarenessPercent"}], "title": "..."}], "sizes": [0.25, 0.25, 0.25, 0.25], "split": "vertical"}], "sizes": [0.5, 0.5], "split": "horizontal"}}]} diff --git a/openpilot/tools/jotpluggler/layouts/gps.json b/openpilot/tools/jotpluggler/layouts/gps.json new file mode 100644 index 0000000000..fdabbfd381 --- /dev/null +++ b/openpilot/tools/jotpluggler/layouts/gps.json @@ -0,0 +1 @@ +{"current_tab_index":0,"tabs":[{"name":"tab1","root":{"split":"vertical","sizes":[0.24977,0.250689,0.24977,0.24977],"children":[{"title":"...","range":{"left":0.0,"right":1678.753571,"top":1.025,"bottom":-0.025},"curves":[{"name":"/gpsLocationExternal/hasFix","color":"#1f77b4"}]},{"title":"...","range":{"left":0.0,"right":1678.753571,"top":17.425,"bottom":-0.425},"curves":[{"name":"/gpsLocationExternal/satelliteCount","color":"#d62728"}]},{"title":"...","range":{"left":0.0,"right":1678.753571,"top":3.0,"bottom":0.0},"curves":[{"name":"/gpsLocationExternal/horizontalAccuracy","color":"#1ac938"}],"y_limits":{"min":0.0,"max":3.0}},{"title":"...","range":{"left":0.0,"right":1678.753571,"top":766.374004,"bottom":-17.262},"curves":[{"name":"/gpsLocationExternal/horizontalAccuracy","color":"#1ac938"}]}]}}]} diff --git a/openpilot/tools/jotpluggler/layouts/gps_vs_llk.json b/openpilot/tools/jotpluggler/layouts/gps_vs_llk.json new file mode 100644 index 0000000000..878e0a57a8 --- /dev/null +++ b/openpilot/tools/jotpluggler/layouts/gps_vs_llk.json @@ -0,0 +1 @@ +{"current_tab_index":0,"tabs":[{"name":"tab1","root":{"split":"vertical","sizes":[0.333805,0.33239,0.333805],"children":[{"title":"...","range":{"left":76.646983,"right":196.811937,"top":32.070386,"bottom":0.368228},"curves":[{"name":"haversine distance [m]","color":"#1f77b4","custom_python":{"linked_source":"/gpsLocationExternal/latitude","additional_sources":["/gpsLocationExternal/longitude","/liveLocationKalmanDEPRECATED/positionGeodetic/value/0","/liveLocationKalmanDEPRECATED/positionGeodetic/value/1"],"globals_code":"R = 6378.137 # Radius of earth in KM","function_code":"def __jotpluggler_eval_sample(time, value, v1, v2, v3):\n global R\n # Compute the Haversine distance between\n # two points defined by latitude and longitude.\n # Return the distance in meters\n lat1, lon1 = value, v1\n lat2, lon2 = v2, v3\n dLat = (lat2 - lat1) * np.pi / 180\n dLon = (lon2 - lon1) * np.pi / 180\n a = np.sin(dLat/2) * np.sin(dLat/2) +\n np.cos(lat1 * np.pi / 180) * np.cos(lat2 * np.pi / 180) *\n np.sin(dLon/2) * np.sin(dLon/2)\n c = 2 * np.arctan2(np.sqrt(a), np.sqrt(1-a))\n d = R * c\n distance = d * 1000 # meters\n return distance\n\n__jotpluggler_result = np.empty_like(value, dtype=np.float64)\nfor __jotpluggler_i in range(len(value)):\n __jotpluggler_result[__jotpluggler_i] = __jotpluggler_eval_sample(time[__jotpluggler_i], value[__jotpluggler_i], v1[__jotpluggler_i], v2[__jotpluggler_i], v3[__jotpluggler_i])\nreturn __jotpluggler_result"}}]},{"title":"...","range":{"left":76.646983,"right":196.811937,"top":12.637299,"bottom":-0.259115},"curves":[{"name":"/carState/vEgo","color":"#17becf"},{"name":"/gpsLocationExternal/speed","color":"#bcbd22"}]},{"split":"horizontal","sizes":[0.500516,0.499484],"children":[{"title":"...","range":{"left":76.646983,"right":196.811937,"top":0.1,"bottom":-0.1},"curves":[{"name":"/liveLocationKalmanDEPRECATED/positionGeodetic/std/0","color":"#d62728"},{"name":"/liveLocationKalmanDEPRECATED/positionGeodetic/std/1","color":"#1ac938"}]},{"title":"...","range":{"left":76.646983,"right":196.811937,"top":7.160833,"bottom":-0.449385},"curves":[{"name":"/gpsLocationExternal/horizontalAccuracy","color":"#ff7f0e"},{"name":"/gpsLocationExternal/verticalAccuracy","color":"#f14cc1"},{"name":"/gpsLocationExternal/speedAccuracy","color":"#9467bd"}]}]}]}}]} diff --git a/openpilot/tools/jotpluggler/layouts/locationd_debug.json b/openpilot/tools/jotpluggler/layouts/locationd_debug.json new file mode 100644 index 0000000000..0541427bc1 --- /dev/null +++ b/openpilot/tools/jotpluggler/layouts/locationd_debug.json @@ -0,0 +1 @@ +{"current_tab_index":0,"tabs":[{"name":"tab1","root":{"split":"vertical","sizes":[0.166588,0.167062,0.166113,0.166588,0.167062,0.166588],"children":[{"title":"...","range":{"left":0.0,"right":2280.128382,"top":1.025,"bottom":-0.025},"curves":[{"name":"/livePose/inputsOK","color":"#ff7f0e"}]},{"title":"...","range":{"left":0.0,"right":2280.128382,"top":14.542814,"bottom":-5.586039},"curves":[{"name":"/accelerometer/acceleration/v/0","color":"#f14cc1"},{"name":"/accelerometer/acceleration/v/1","color":"#9467bd"},{"name":"/accelerometer/acceleration/v/2","color":"#17becf"}]},{"title":"...","range":{"left":0.0,"right":2280.128382,"top":0.988911,"bottom":-0.745939},"curves":[{"name":"/gyroscope/gyroUncalibrated/v/0","color":"#d62728"},{"name":"/gyroscope/gyroUncalibrated/v/1","color":"#1ac938"},{"name":"/gyroscope/gyroUncalibrated/v/2","color":"#ff7f0e"}]},{"title":"...","range":{"left":0.0,"right":2280.128382,"top":1.025,"bottom":-0.025},"curves":[{"name":"/accelerometer/__valid","color":"#17becf"},{"name":"/gyroscope/__valid","color":"#bcbd22"},{"name":"/carState/__valid","color":"#f14cc1"},{"name":"/liveCalibration/__valid","color":"#1ac938"},{"name":"/cameraOdometry/__valid","color":"#9467bd"}]},{"title":"...","range":{"left":0.0,"right":2280.128382,"top":1000000000.292252,"bottom":999999999.735447},"curves":[{"name":"/gyroscope/__logMonoTime","color":"#1f77b4","transform":"derivative"},{"name":"/accelerometer/__logMonoTime","color":"#d62728","transform":"derivative"}]},{"title":"...","range":{"left":0.0,"right":2280.128382,"top":20790107743.93223,"bottom":-529653831.495853},"curves":[{"name":"/accelerometer/timestamp","color":"#bcbd22","transform":"derivative"},{"name":"/gyroscope/timestamp","color":"#1f77b4","transform":"derivative"}]}]}}]} diff --git a/openpilot/tools/jotpluggler/layouts/longitudinal.json b/openpilot/tools/jotpluggler/layouts/longitudinal.json new file mode 100644 index 0000000000..27f43eb357 --- /dev/null +++ b/openpilot/tools/jotpluggler/layouts/longitudinal.json @@ -0,0 +1 @@ +{"current_tab_index":0,"tabs":[{"name":"tab1","root":{"split":"vertical","sizes":[0.250401,0.249599,0.250401,0.249599],"children":[{"title":"...","range":{"left":104.907277,"right":126.285782,"top":1.391623,"bottom":-2.563614},"curves":[{"name":"/carState/aEgo","color":"#f14cc1"},{"name":"/longitudinalPlan/accels/0","color":"#9467bd"},{"name":"/carControl/actuators/accel","color":"#17becf"},{"name":"/carOutput/actuatorsOutput/accel","color":"#d62728"}]},{"title":"...","range":{"left":104.907277,"right":126.285782,"top":1.18496,"bottom":-1.811222},"curves":[{"name":"/controlsState/upAccelCmd","color":"#1f77b4"},{"name":"/controlsState/uiAccelCmd","color":"#d62728"},{"name":"/controlsState/ufAccelCmd","color":"#1ac938"}]},{"title":"...","range":{"left":104.907277,"right":126.285782,"top":15.862889,"bottom":-0.568809},"curves":[{"name":"/carState/vEgo","color":"#1ac938"},{"name":"/longitudinalPlan/speeds/0","color":"#ff7f0e"}]},{"title":"...","range":{"left":104.907277,"right":126.285782,"top":1.025,"bottom":-0.025},"curves":[{"name":"/carControl/longActive","color":"#1f77b4"},{"name":"/carState/gasPressed","color":"#d62728"}]}]}}]} diff --git a/openpilot/tools/jotpluggler/layouts/max-torque-debug.json b/openpilot/tools/jotpluggler/layouts/max-torque-debug.json new file mode 100644 index 0000000000..3a87fb3217 --- /dev/null +++ b/openpilot/tools/jotpluggler/layouts/max-torque-debug.json @@ -0,0 +1 @@ +{"current_tab_index":0,"tabs":[{"name":"tab1","root":{"split":"vertical","sizes":[0.249724,0.250829,0.249724,0.249724],"children":[{"title":"...","range":{"left":0.00045,"right":2483.624998,"top":6.050533,"bottom":-7.599037},"curves":[{"name":"Actual lateral accel (roll compensated)","color":"#1ac938","custom_python":{"linked_source":"/controlsState/curvature","additional_sources":["/carState/vEgo","/liveParameters/roll"],"globals_code":"","function_code":"def __jotpluggler_eval_sample(time, value, v1, v2):\n return (value * v1 ** 2) - (v2 * 9.81)\n\n__jotpluggler_result = np.empty_like(value, dtype=np.float64)\nfor __jotpluggler_i in range(len(value)):\n __jotpluggler_result[__jotpluggler_i] = __jotpluggler_eval_sample(time[__jotpluggler_i], value[__jotpluggler_i], v1[__jotpluggler_i], v2[__jotpluggler_i])\nreturn __jotpluggler_result"}},{"name":"Desired lateral accel (roll compensated)","color":"#ff7f0e","custom_python":{"linked_source":"/controlsState/desiredCurvature","additional_sources":["/carState/vEgo","/liveParameters/roll"],"globals_code":"","function_code":"def __jotpluggler_eval_sample(time, value, v1, v2):\n return (value * v1 ** 2) - (v2 * 9.81)\n\n__jotpluggler_result = np.empty_like(value, dtype=np.float64)\nfor __jotpluggler_i in range(len(value)):\n __jotpluggler_result[__jotpluggler_i] = __jotpluggler_eval_sample(time[__jotpluggler_i], value[__jotpluggler_i], v1[__jotpluggler_i], v2[__jotpluggler_i])\nreturn __jotpluggler_result"}}]},{"title":"...","range":{"left":0.00045,"right":2483.624998,"top":5.384416,"bottom":-7.503945},"curves":[{"name":"roll compensated lateral acceleration","color":"#1ac938","custom_python":{"linked_source":"/controlsState/curvature","additional_sources":["/carState/vEgo","/liveParameters/roll","/carState/steeringPressed","/carControl/latActive"],"globals_code":"","function_code":"def __jotpluggler_eval_sample(time, value, v1, v2, v3, v4):\n if (v3 == 0 and v4 == 1):\n return (value * v1 ** 2) - (v2 * 9.81)\n return 0\n\n__jotpluggler_result = np.empty_like(value, dtype=np.float64)\nfor __jotpluggler_i in range(len(value)):\n __jotpluggler_result[__jotpluggler_i] = __jotpluggler_eval_sample(time[__jotpluggler_i], value[__jotpluggler_i], v1[__jotpluggler_i], v2[__jotpluggler_i], v3[__jotpluggler_i], v4[__jotpluggler_i])\nreturn __jotpluggler_result"}}]},{"title":"...","range":{"left":0.00045,"right":2483.624998,"top":1.05,"bottom":-1.05},"curves":[{"name":"/carState/steeringPressed","color":"#0097ff"},{"name":"/carOutput/actuatorsOutput/torque","color":"#d62728"}]},{"title":"...","range":{"left":0.00045,"right":2483.624998,"top":80.762969,"bottom":-2.181837},"curves":[{"name":"/carState/vEgo","color":"#f14cc1","transform":"scale","scale":2.23694,"offset":0.0}]}]}}]} diff --git a/openpilot/tools/jotpluggler/layouts/new-layout.json b/openpilot/tools/jotpluggler/layouts/new-layout.json new file mode 100644 index 0000000000..bffb62d7c7 --- /dev/null +++ b/openpilot/tools/jotpluggler/layouts/new-layout.json @@ -0,0 +1 @@ +{"current_tab_index": 0, "tabs": [{"name": "tab1", "root": {"curves": [], "title": "..."}}]} diff --git a/openpilot/tools/jotpluggler/layouts/system_lag_debug.json b/openpilot/tools/jotpluggler/layouts/system_lag_debug.json new file mode 100644 index 0000000000..281de440fa --- /dev/null +++ b/openpilot/tools/jotpluggler/layouts/system_lag_debug.json @@ -0,0 +1 @@ +{"current_tab_index":0,"tabs":[{"name":"tab1","root":{"split":"vertical","sizes":[0.249729,0.250814,0.249729,0.249729],"children":[{"title":"...","range":{"left":0.0,"right":59.992103,"top":102.5,"bottom":-2.5},"curves":[{"name":"/deviceState/cpuUsagePercent/0","color":"#1f77b4"},{"name":"/deviceState/cpuUsagePercent/1","color":"#d62728"},{"name":"/deviceState/cpuUsagePercent/2","color":"#1ac938"},{"name":"/deviceState/cpuUsagePercent/3","color":"#ff7f0e"},{"name":"/deviceState/cpuUsagePercent/4","color":"#f14cc1"},{"name":"/deviceState/cpuUsagePercent/5","color":"#9467bd"},{"name":"/deviceState/cpuUsagePercent/6","color":"#17becf"},{"name":"/deviceState/cpuUsagePercent/7","color":"#bcbd22"}]},{"title":"...","range":{"left":0.0,"right":59.992103,"top":64.005001,"bottom":51.195},"curves":[{"name":"/deviceState/cpuTempC/0","color":"#d62728"},{"name":"/deviceState/cpuTempC/1","color":"#1ac938"},{"name":"/deviceState/cpuTempC/2","color":"#ff7f0e"},{"name":"/deviceState/cpuTempC/3","color":"#f14cc1"},{"name":"/deviceState/cpuTempC/4","color":"#9467bd"},{"name":"/deviceState/cpuTempC/5","color":"#17becf"},{"name":"/deviceState/cpuTempC/6","color":"#bcbd22"},{"name":"/deviceState/cpuTempC/7","color":"#1f77b4"},{"name":"/deviceState/gpuTempC/0","color":"#d62728"},{"name":"/deviceState/gpuTempC/1","color":"#1ac938"}]},{"title":"...","range":{"left":0.0,"right":59.992103,"top":37.371108,"bottom":-0.91149},"curves":[{"name":"/modelV2/frameDropPerc","color":"#f14cc1"}]},{"title":"...","range":{"left":0.0,"right":59.992103,"top":-3.593455,"bottom":-12.190956},"curves":[{"name":"/carState/cumLagMs","color":"#9467bd"}]}]}}]} diff --git a/openpilot/tools/jotpluggler/layouts/thermal_debug.json b/openpilot/tools/jotpluggler/layouts/thermal_debug.json new file mode 100644 index 0000000000..3a7ce454cf --- /dev/null +++ b/openpilot/tools/jotpluggler/layouts/thermal_debug.json @@ -0,0 +1 @@ +{"current_tab_index":0,"tabs":[{"name":"tab1","root":{"split":"vertical","sizes":[0.166785,0.166785,0.166075,0.166785,0.166785,0.166785],"children":[{"title":"...","range":{"left":0.006955,"right":301.842654,"top":87.987497,"bottom":75.912497},"curves":[{"name":"/deviceState/cpuTempC/0","color":"#1f77b4"},{"name":"/deviceState/cpuTempC/1","color":"#d62728"},{"name":"/deviceState/cpuTempC/2","color":"#1ac938"},{"name":"/deviceState/cpuTempC/3","color":"#ff7f0e"},{"name":"/deviceState/cpuTempC/4","color":"#f14cc1"},{"name":"/deviceState/cpuTempC/5","color":"#9467bd"},{"name":"/deviceState/cpuTempC/6","color":"#17becf"},{"name":"/deviceState/cpuTempC/7","color":"#bcbd22"}]},{"title":"...","range":{"left":0.006955,"right":301.842654,"top":85.861052,"bottom":66.49695},"curves":[{"name":"/deviceState/pmicTempC/0","color":"#1f77b4"},{"name":"/deviceState/gpuTempC/0","color":"#d62728"},{"name":"/deviceState/gpuTempC/1","color":"#1ac938"},{"name":"/deviceState/memoryTempC","color":"#f14cc1"}]},{"title":"...","range":{"left":0.006955,"right":301.842654,"top":86.207876,"bottom":70.665918},"curves":[{"name":"/deviceState/maxTempC","color":"#1f77b4"}]},{"title":"...","range":{"left":0.006955,"right":301.842654,"top":1.025,"bottom":-0.025},"curves":[{"name":"/deviceState/thermalStatus","color":"#1f77b4"}]},{"split":"horizontal","sizes":[0.333124,0.333752,0.333124],"children":[{"title":"...","range":{"left":0.006955,"right":301.842654,"top":12.057358,"bottom":4.843517},"curves":[{"name":"/deviceState/powerDrawW","color":"#ff7f0e"}]},{"title":"...","range":{"left":0.006955,"right":301.842654,"top":100.0,"bottom":0.0},"curves":[{"name":"/deviceState/fanSpeedPercentDesired","color":"#9467bd"},{"name":"/pandaStates/0/fanPower","color":"#1f77b4"}],"y_limits":{"min":0.0,"max":100.0}},{"title":"...","range":{"left":0.006955,"right":301.842654,"top":5018.4,"bottom":255.6},"curves":[{"name":"/peripheralState/fanSpeedRpm","color":"#1f77b4"}]}]},{"split":"horizontal","sizes":[0.502513,0.497487],"children":[{"title":"...","range":{"left":0.006955,"right":301.842654,"top":100.025,"bottom":14.975},"curves":[{"name":"/deviceState/cpuUsagePercent/0","color":"#1f77b4"},{"name":"/deviceState/cpuUsagePercent/1","color":"#d62728"},{"name":"/deviceState/cpuUsagePercent/2","color":"#1ac938"},{"name":"/deviceState/cpuUsagePercent/3","color":"#ff7f0e"}]},{"title":"...","range":{"left":0.006955,"right":301.842654,"top":102.5,"bottom":-2.5},"curves":[{"name":"/deviceState/cpuUsagePercent/4","color":"#f14cc1"},{"name":"/deviceState/cpuUsagePercent/5","color":"#9467bd"},{"name":"/deviceState/cpuUsagePercent/6","color":"#17becf"},{"name":"/deviceState/cpuUsagePercent/7","color":"#bcbd22"}]}]}]}}]} diff --git a/openpilot/tools/jotpluggler/layouts/torque-controller.json b/openpilot/tools/jotpluggler/layouts/torque-controller.json new file mode 100644 index 0000000000..7e269e59e6 --- /dev/null +++ b/openpilot/tools/jotpluggler/layouts/torque-controller.json @@ -0,0 +1 @@ +{"current_tab_index":0,"tabs":[{"name":"Lateral Plan Conformance","root":{"split":"vertical","sizes":[0.250949,0.249051,0.250949,0.249051],"children":[{"title":"desired vs actual lateral acceleration (closer means better conformance to plan)","range":{"left":0.000194,"right":1138.891674,"top":1.858161,"bottom":-1.823407},"curves":[{"name":"/controlsState/lateralControlState/torqueState/actualLateralAccel","color":"#1f77b4"},{"name":"/controlsState/lateralControlState/torqueState/desiredLateralAccel","color":"#d62728"}]},{"title":"desired vs actual lateral acceleration, road-roll factored out (closer means better conformance to plan)","range":{"left":0.000194,"right":1138.891674,"top":2.749816,"bottom":-3.723091},"curves":[{"name":"Actual lateral accel (roll compensated)","color":"#1ac938","custom_python":{"linked_source":"/controlsState/curvature","additional_sources":["/carState/vEgo","/liveParameters/roll"],"globals_code":"","function_code":"def __jotpluggler_eval_sample(time, value, v1, v2):\n return (value * v1 ** 2) - (v2 * 9.81)\n\n__jotpluggler_result = np.empty_like(value, dtype=np.float64)\nfor __jotpluggler_i in range(len(value)):\n __jotpluggler_result[__jotpluggler_i] = __jotpluggler_eval_sample(time[__jotpluggler_i], value[__jotpluggler_i], v1[__jotpluggler_i], v2[__jotpluggler_i])\nreturn __jotpluggler_result"}},{"name":"Desired lateral accel (roll compensated)","color":"#ff7f0e","custom_python":{"linked_source":"/controlsState/desiredCurvature","additional_sources":["/carState/vEgo","/liveParameters/roll"],"globals_code":"","function_code":"def __jotpluggler_eval_sample(time, value, v1, v2):\n return (value * v1 ** 2) - (v2 * 9.81)\n\n__jotpluggler_result = np.empty_like(value, dtype=np.float64)\nfor __jotpluggler_i in range(len(value)):\n __jotpluggler_result[__jotpluggler_i] = __jotpluggler_eval_sample(time[__jotpluggler_i], value[__jotpluggler_i], v1[__jotpluggler_i], v2[__jotpluggler_i])\nreturn __jotpluggler_result"}}]},{"title":"controller feed-forward vs actuator output (closer means controller prediction is more accurate)","range":{"left":0.000194,"right":1138.891674,"top":1.978032,"bottom":-1.570956},"curves":[{"name":"/carOutput/actuatorsOutput/torque","color":"#9467bd","transform":"scale","scale":-1.0,"offset":0.0},{"name":"/controlsState/lateralControlState/torqueState/f","color":"#1f77b4"},{"name":"/carState/steeringPressed","color":"#ff000f"}]},{"title":"vehicle speed","range":{"left":0.000194,"right":1138.891674,"top":105.981304,"bottom":-2.709314},"curves":[{"name":"carState.vEgo mph","color":"#d62728","custom_python":{"linked_source":"/carState/vEgo","additional_sources":[],"globals_code":"","function_code":"def __jotpluggler_eval_sample(time, value):\n return value * 2.23694\n\n__jotpluggler_result = np.empty_like(value, dtype=np.float64)\nfor __jotpluggler_i in range(len(value)):\n __jotpluggler_result[__jotpluggler_i] = __jotpluggler_eval_sample(time[__jotpluggler_i], value[__jotpluggler_i])\nreturn __jotpluggler_result"}},{"name":"carState.vEgo kmh","color":"#1ac938","custom_python":{"linked_source":"/carState/vEgo","additional_sources":[],"globals_code":"","function_code":"def __jotpluggler_eval_sample(time, value):\n return value * 3.6\n\n__jotpluggler_result = np.empty_like(value, dtype=np.float64)\nfor __jotpluggler_i in range(len(value)):\n __jotpluggler_result[__jotpluggler_i] = __jotpluggler_eval_sample(time[__jotpluggler_i], value[__jotpluggler_i])\nreturn __jotpluggler_result"}},{"name":"/carState/vEgo","color":"#ff7f0e"}]}]}},{"name":"Vehicle Dynamics","root":{"split":"vertical","sizes":[0.334282,0.331437,0.334282],"children":[{"title":"configured-initial vs online-learned steerRatio, set configured value to match learned","range":{"left":0.0,"right":1138.816328,"top":19.665784,"bottom":19.359553},"curves":[{"name":"/carParams/steerRatio","color":"#1f77b4"},{"name":"/liveParameters/steerRatio","color":"#1ac938"}]},{"title":"configured-initial vs online-learned tireStiffnessRatio, set configured value to match learned","range":{"left":0.0,"right":1138.816328,"top":1.11221,"bottom":0.995631},"curves":[{"name":"/carParams/tireStiffnessFactor","color":"#d62728"},{"name":"/liveParameters/stiffnessFactor","color":"#ff7f0e"}]},{"title":"live steering angle offsets for straight-ahead driving, large values here may indicate alignment problems","range":{"left":0.0,"right":1138.816328,"top":-1.081041,"bottom":-4.494133},"curves":[{"name":"/liveParameters/angleOffsetAverageDeg","color":"#f14cc1"},{"name":"/liveParameters/angleOffsetDeg","color":"#9467bd"}]}]}},{"name":"Actuator Performance","root":{"split":"vertical","sizes":[0.333333,0.333333,0.333333],"children":[{"title":"offline-calculated vs online-learned lateral accel scaling factor, accel obtained from 100% actuator output","range":{"left":0.0,"right":1138.920072,"top":1.21611,"bottom":0.539474},"curves":[{"name":"/liveTorqueParameters/latAccelFactorFiltered","color":"#1f77b4"},{"name":"/liveTorqueParameters/latAccelFactorRaw","color":"#d62728"},{"name":"/carParams/lateralTuning/torque/latAccelFactor","color":"#1c9222"}]},{"title":"learned lateral accel offset, vehicle-specific compensation to obtain true zero lateral accel","range":{"left":0.0,"right":1138.920072,"top":-0.304367,"bottom":-0.418688},"curves":[{"name":"/liveTorqueParameters/latAccelOffsetFiltered","color":"#1ac938"},{"name":"/liveTorqueParameters/latAccelOffsetRaw","color":"#ff7f0e"}]},{"title":"offline-calculated vs online-learned EPS friction factor, necessary to start moving the steering wheel","range":{"left":0.0,"right":1138.920072,"top":0.226389,"bottom":0.15805},"curves":[{"name":"/liveTorqueParameters/frictionCoefficientFiltered","color":"#f14cc1"},{"name":"/liveTorqueParameters/frictionCoefficientRaw","color":"#9467bd"},{"name":"/carParams/lateralTuning/torque/friction","color":"#1c9222"}]}]}},{"name":"Actuator Delay","root":{"split":"vertical","sizes":[0.30441,0.358464,0.337127],"children":[{"title":"actuator lag learning state, 0 = learning, 1 = learned/applying, 2 = invalid","range":{"left":0.0,"right":1138.749979,"top":1.025,"bottom":-0.025},"curves":[{"name":"/liveDelay/status","color":"#ff7f0e"}]},{"title":"offline default vs online estimated steering actuator lag","range":{"left":0.0,"right":1138.749979,"top":0.419648,"bottom":0.318362},"curves":[{"name":"/liveDelay/lateralDelay","color":"#1f77b4"},{"name":"/liveDelay/lateralDelayEstimate","color":"#d62728"},{"name":"opendbc default steering lag","color":"#1ac938","custom_python":{"linked_source":"/carParams/steerActuatorDelay","additional_sources":[],"globals_code":"","function_code":"def __jotpluggler_eval_sample(time, value):\n return value + 0.2\n\n__jotpluggler_result = np.empty_like(value, dtype=np.float64)\nfor __jotpluggler_i in range(len(value)):\n __jotpluggler_result[__jotpluggler_i] = __jotpluggler_eval_sample(time[__jotpluggler_i], value[__jotpluggler_i])\nreturn __jotpluggler_result"}}]},{"title":"online estimated steering actuator lag, standard deviation","range":{"left":0.0,"right":1138.749979,"top":0.06732,"bottom":-0.001642},"curves":[{"name":"/liveDelay/lateralDelayEstimateStd","color":"#f14cc1"}]}]}},{"name":"Controls Performance","root":{"split":"vertical","sizes":[0.265655,0.251898,0.245731,0.236717],"children":[{"title":"rate-of-change limits on steering actuator (blue = original, green = rate-limited before CAN output)","range":{"left":0.000194,"right":1138.891921,"top":1.05,"bottom":-1.05},"curves":[{"name":"/carControl/actuators/torque","color":"#0c00f2"},{"name":"/carOutput/actuatorsOutput/torque","color":"#2cd63a"}]},{"title":"controller feed-forward vs actuator output (closer means controller prediction is more accurate)","range":{"left":0.000194,"right":1138.891921,"top":1.978032,"bottom":-1.570956},"curves":[{"name":"/carOutput/actuatorsOutput/torque","color":"#9467bd","transform":"scale","scale":-1.0,"offset":0.0},{"name":"/controlsState/lateralControlState/torqueState/f","color":"#1f77b4"},{"name":"/carState/steeringPressed","color":"#ff000f"}]},{"title":"proportional, integral, and feed-forward terms (actuator output = sum of PIF terms)","range":{"left":0.000194,"right":1138.891921,"top":2.099784,"bottom":-4.027542},"curves":[{"name":"/controlsState/lateralControlState/torqueState/f","color":"#0ab027"},{"name":"/controlsState/lateralControlState/torqueState/p","color":"#d62728"},{"name":"/controlsState/lateralControlState/torqueState/i","color":"#ffaf00"},{"name":"Zero","color":"#756a6a","custom_python":{"linked_source":"/carState/canValid","additional_sources":[],"globals_code":"","function_code":"def __jotpluggler_eval_sample(time, value):\n return (0)\n\n__jotpluggler_result = np.empty_like(value, dtype=np.float64)\nfor __jotpluggler_i in range(len(value)):\n __jotpluggler_result[__jotpluggler_i] = __jotpluggler_eval_sample(time[__jotpluggler_i], value[__jotpluggler_i])\nreturn __jotpluggler_result"}}]},{"title":"road roll angle, from openpilot localizer","range":{"left":0.000194,"right":1138.891921,"top":0.109446,"bottom":-0.045525},"curves":[{"name":"/liveParameters/roll","color":"#f14cc1"}]}]}}]} diff --git a/openpilot/tools/jotpluggler/layouts/tuning.json b/openpilot/tools/jotpluggler/layouts/tuning.json new file mode 100644 index 0000000000..0a8e81743e --- /dev/null +++ b/openpilot/tools/jotpluggler/layouts/tuning.json @@ -0,0 +1 @@ +{"current_tab_index":0,"tabs":[{"name":"Lateral","root":{"split":"vertical","sizes":[0.200458,0.199313,0.200458,0.199313,0.200458],"children":[{"title":"Velocity [m/s]","range":{"left":1.253354,"right":631.055584,"top":29.954036,"bottom":-0.841715},"curves":[{"name":"/carState/vEgo","color":"#0072b2"}]},{"title":"Curvature [1/m] True [blue] Vehicle Model [purple] Plan [green]","range":{"left":0.0,"right":631.055209,"top":0.006648,"bottom":-0.00315},"curves":[{"name":"engaged curvature plan","color":"#009e73","custom_python":{"linked_source":"/modelV2/action/desiredCurvature","additional_sources":["/carState/steeringPressed","/carControl/enabled"],"globals_code":"engage_delay = 5\nlast_bad_time = -engage_delay","function_code":"def __jotpluggler_eval_sample(time, value, v1, v2):\n global engage_delay, last_bad_time\n curvature = value\n pressed = v1\n enabled = v2\n if (pressed == 1 or enabled == 0):\n last_bad_time = time\n if (time > last_bad_time + engage_delay):\n return value\n else:\n return 0\n\n__jotpluggler_result = np.empty_like(value, dtype=np.float64)\nfor __jotpluggler_i in range(len(value)):\n __jotpluggler_result[__jotpluggler_i] = __jotpluggler_eval_sample(time[__jotpluggler_i], value[__jotpluggler_i], v1[__jotpluggler_i], v2[__jotpluggler_i])\nreturn __jotpluggler_result"}},{"name":"engaged curvature vehicle model","color":"#785ef0","custom_python":{"linked_source":"/controlsState/curvature","additional_sources":["/carState/steeringPressed","/carControl/enabled"],"globals_code":"engage_delay = 5\nlast_bad_time = -engage_delay","function_code":"def __jotpluggler_eval_sample(time, value, v1, v2):\n global engage_delay, last_bad_time\n curvature = value\n pressed = v1\n enabled = v2\n if (pressed == 1 or enabled == 0):\n last_bad_time = time\n if (time > last_bad_time + engage_delay):\n return value\n else:\n return 0\n\n__jotpluggler_result = np.empty_like(value, dtype=np.float64)\nfor __jotpluggler_i in range(len(value)):\n __jotpluggler_result[__jotpluggler_i] = __jotpluggler_eval_sample(time[__jotpluggler_i], value[__jotpluggler_i], v1[__jotpluggler_i], v2[__jotpluggler_i])\nreturn __jotpluggler_result"}},{"name":"engaged curvature yaw","color":"#0072b2","custom_python":{"linked_source":"/carControl/angularVelocity/2","additional_sources":["/carState/steeringPressed","/carControl/enabled","/carState/vEgo"],"globals_code":"engage_delay = 5\nlast_bad_time = -engage_delay","function_code":"def __jotpluggler_eval_sample(time, value, v1, v2, v3):\n global engage_delay, last_bad_time\n curvature = value / v3\n pressed = v1\n enabled = v2\n if (pressed == 1 or enabled == 0):\n last_bad_time = time\n if (time > last_bad_time + engage_delay):\n return curvature\n else:\n return 0\n\n__jotpluggler_result = np.empty_like(value, dtype=np.float64)\nfor __jotpluggler_i in range(len(value)):\n __jotpluggler_result[__jotpluggler_i] = __jotpluggler_eval_sample(time[__jotpluggler_i], value[__jotpluggler_i], v1[__jotpluggler_i], v2[__jotpluggler_i], v3[__jotpluggler_i])\nreturn __jotpluggler_result"}}]},{"title":"Roll [rad]","range":{"left":0.0,"right":631.038276,"top":0.166067,"bottom":-1.598381},"curves":[{"name":"/carControl/orientationNED/0","color":"#ffb000"}]},{"title":"Engaged [green] Steering Pressed [blue]","range":{"left":1.252984,"right":631.055584,"top":1.025,"bottom":-0.025},"curves":[{"name":"/selfdriveState/enabled","color":"#009e73"},{"name":"/carState/steeringPressed","color":"#0072b2"}]},{"title":"Steering Limited: Rate [orange] Saturated [magenta]","range":{"left":1.253354,"right":631.055584,"top":1.025,"bottom":-0.025},"curves":[{"name":"steering rate limited","color":"#ffb000","custom_python":{"linked_source":"/carControl/actuators/torque","additional_sources":["/carOutput/actuatorsOutput/torque","/carControl/actuators/steeringAngleDeg","/carOutput/actuatorsOutput/steeringAngleDeg"],"globals_code":"","function_code":"def __jotpluggler_eval_sample(time, value, v1, v2, v3):\n return (np.abs(value - v1) > 0.001 or np.abs(v2 - v3) > 0.05) and 1 or 0\n\n__jotpluggler_result = np.empty_like(value, dtype=np.float64)\nfor __jotpluggler_i in range(len(value)):\n __jotpluggler_result[__jotpluggler_i] = __jotpluggler_eval_sample(time[__jotpluggler_i], value[__jotpluggler_i], v1[__jotpluggler_i], v2[__jotpluggler_i], v3[__jotpluggler_i])\nreturn __jotpluggler_result"}},{"name":"/controlsState/lateralControlState/pidState/saturated","color":"#dc267f"}]}]}},{"name":"Longitudinal","root":{"split":"vertical","sizes":[0.1875,0.1875,0.1875,0.1875,0.25],"children":[{"title":"Velocity [m/s] True [blue] Plan [green] Cruise [magenta]","range":{"left":0.0,"right":631.055584,"top":42.713492,"bottom":-1.041792},"curves":[{"name":"/carState/cruiseState/speed","color":"#dc267f"},{"name":"/longitudinalPlan/speeds/0","color":"#009e73"},{"name":"/carState/vEgo","color":"#0072b2"}]},{"title":"Acceleration [m/s^2] True [blue] Actuator [purple] Plan [green]","range":{"left":1.253354,"right":631.055759,"top":0.808303,"bottom":-1.213305},"curves":[{"name":"engaged_accel_plan","color":"#009e73","custom_python":{"linked_source":"/longitudinalPlan/accels/0","additional_sources":["/carState/brakePressed","/carState/gasPressed","/carControl/enabled"],"globals_code":"engage_delay = 5\nlast_bad_time = -engage_delay","function_code":"def __jotpluggler_eval_sample(time, value, v1, v2, v3):\n global engage_delay, last_bad_time\n accel = value\n brake = v1\n gas = v2\n enabled = v3\n if (brake != 0 or gas != 0 or enabled == 0):\n last_bad_time = time\n if (time > last_bad_time + engage_delay):\n return value\n else:\n return 0\n\n__jotpluggler_result = np.empty_like(value, dtype=np.float64)\nfor __jotpluggler_i in range(len(value)):\n __jotpluggler_result[__jotpluggler_i] = __jotpluggler_eval_sample(time[__jotpluggler_i], value[__jotpluggler_i], v1[__jotpluggler_i], v2[__jotpluggler_i], v3[__jotpluggler_i])\nreturn __jotpluggler_result"}},{"name":"engaged_accel_actuator","color":"#785ef0","custom_python":{"linked_source":"/carControl/actuators/accel","additional_sources":["/carState/brakePressed","/carState/gasPressed","/carControl/enabled"],"globals_code":"engage_delay = 5\nlast_bad_time = -engage_delay","function_code":"def __jotpluggler_eval_sample(time, value, v1, v2, v3):\n global engage_delay, last_bad_time\n accel = value\n brake = v1\n gas = v2\n enabled = v3\n if (brake != 0 or gas != 0 or enabled == 0):\n last_bad_time = time\n if (time > last_bad_time + engage_delay):\n return value\n else:\n return 0\n\n__jotpluggler_result = np.empty_like(value, dtype=np.float64)\nfor __jotpluggler_i in range(len(value)):\n __jotpluggler_result[__jotpluggler_i] = __jotpluggler_eval_sample(time[__jotpluggler_i], value[__jotpluggler_i], v1[__jotpluggler_i], v2[__jotpluggler_i], v3[__jotpluggler_i])\nreturn __jotpluggler_result"}},{"name":"engaged_accel_actual","color":"#0072b2","custom_python":{"linked_source":"/carState/aEgo","additional_sources":["/carState/brakePressed","/carState/gasPressed","/carControl/enabled"],"globals_code":"engage_delay = 5\nlast_bad_time = -engage_delay","function_code":"def __jotpluggler_eval_sample(time, value, v1, v2, v3):\n global engage_delay, last_bad_time\n accel = value\n brake = v1\n gas = v2\n enabled = v3\n if (brake != 0 or gas != 0 or enabled == 0):\n last_bad_time = time\n if (time > last_bad_time + engage_delay):\n return value\n else:\n return 0\n\n__jotpluggler_result = np.empty_like(value, dtype=np.float64)\nfor __jotpluggler_i in range(len(value)):\n __jotpluggler_result[__jotpluggler_i] = __jotpluggler_eval_sample(time[__jotpluggler_i], value[__jotpluggler_i], v1[__jotpluggler_i], v2[__jotpluggler_i], v3[__jotpluggler_i])\nreturn __jotpluggler_result"}}]},{"title":"Pitch [rad]","range":{"left":0.0,"right":631.038276,"top":0.158854,"bottom":-0.594843},"curves":[{"name":"/carControl/orientationNED/1","color":"#ffb000"}]},{"title":"Engaged [green] Gas [orange] Brake [magenta]","range":{"left":1.253354,"right":631.055759,"top":1.025,"bottom":-0.025},"curves":[{"name":"/carControl/enabled","color":"#009e73"},{"name":"/carState/gasPressed","color":"#ffb000"},{"name":"/carState/brakePressed","color":"#dc267f"}]},{"title":"State [blue: off,pid,stop,start] Source [green: cruise,lead0,lead1,lead2,e2e]","range":{"left":1.25362,"right":631.055759,"top":5.125,"bottom":-0.125},"curves":[{"name":"/carControl/actuators/longControlState","color":"#0072b2"},{"name":"/longitudinalPlan/longitudinalPlanSource","color":"#009e73"}]}]}},{"name":"Lateral Debug","root":{"split":"vertical","sizes":[0.25,0.25,0.25,0.25],"children":[{"title":"Controller F [magenta] P [purple] I [blue]","range":{"left":0.0,"right":1.0,"top":1.0,"bottom":0.0},"curves":[{"name":"/controlsState/lateralControlState/pidState/f","color":"#f14cc1"},{"name":"/controlsState/lateralControlState/pidState/p","color":"#9467bd"},{"name":"/controlsState/lateralControlState/pidState/i","color":"#17becf"}]},{"title":"Driver Torque [blue] EPS Torque [green]","range":{"left":1.253354,"right":631.055584,"top":2690.99903,"bottom":-3450.198981},"curves":[{"name":"/carState/steeringTorqueEps","color":"#009e73"},{"name":"/carState/steeringTorque","color":"#0072b2"}]},{"title":"Engaged [green] Steering Pressed [blue]","range":{"left":1.253354,"right":631.055759,"top":1.025,"bottom":-0.025},"curves":[{"name":"/carControl/enabled","color":"#009e73"},{"name":"/carState/steeringPressed","color":"#0072b2"}]},{"title":"Steering Limited: Rate [orange] Saturated [magenta]","range":{"left":1.253354,"right":631.055584,"top":1.025,"bottom":-0.025},"curves":[{"name":"steering rate limited","color":"#ffb000","custom_python":{"linked_source":"/carControl/actuators/torque","additional_sources":["/carOutput/actuatorsOutput/torque","/carControl/actuators/steeringAngleDeg","/carOutput/actuatorsOutput/steeringAngleDeg"],"globals_code":"","function_code":"def __jotpluggler_eval_sample(time, value, v1, v2, v3):\n return (np.abs(value - v1) > 0.001 or np.abs(v2 - v3) > 0.05) and 1 or 0\n\n__jotpluggler_result = np.empty_like(value, dtype=np.float64)\nfor __jotpluggler_i in range(len(value)):\n __jotpluggler_result[__jotpluggler_i] = __jotpluggler_eval_sample(time[__jotpluggler_i], value[__jotpluggler_i], v1[__jotpluggler_i], v2[__jotpluggler_i], v3[__jotpluggler_i])\nreturn __jotpluggler_result"}},{"name":"/controlsState/lateralControlState/pidState/saturated","color":"#dc267f"}]}]}}]} diff --git a/openpilot/tools/jotpluggler/layouts/ublox-debug.json b/openpilot/tools/jotpluggler/layouts/ublox-debug.json new file mode 100644 index 0000000000..4509a192df --- /dev/null +++ b/openpilot/tools/jotpluggler/layouts/ublox-debug.json @@ -0,0 +1 @@ +{"current_tab_index":0,"tabs":[{"name":"tab1","root":{"split":"vertical","sizes":[0.333333,0.333333,0.333333],"children":[{"title":"...","range":{"left":0.0,"right":134.825489,"top":4402341.574525,"bottom":-107369.555525},"curves":[{"name":"/gpsLocationExternal/horizontalAccuracy","color":"#1f77b4"}]},{"title":"...","range":{"left":0.0,"right":134.825489,"top":1.025,"bottom":-0.025},"curves":[{"name":"/gpsLocationExternal/flags","color":"#d62728"}]},{"title":"...","range":{"left":0.0,"right":134.825489,"top":6.15,"bottom":-0.15},"curves":[{"name":"/ubloxGnss/measurementReport/numMeas","color":"#1ac938"}]}]}}]} diff --git a/openpilot/tools/jotpluggler/logs.cc b/openpilot/tools/jotpluggler/logs.cc new file mode 100644 index 0000000000..4da1cbf501 --- /dev/null +++ b/openpilot/tools/jotpluggler/logs.cc @@ -0,0 +1,419 @@ +#include "tools/jotpluggler/app.h" + +#include +#include + +namespace { + +struct LevelOption { + const char *label; + int value; +}; + +constexpr std::array LEVEL_OPTIONS = {{ + {"DEBUG", 10}, + {"INFO", 20}, + {"WARNING", 30}, + {"ERROR", 40}, + {"CRITICAL", 50}, +}}; +constexpr uint32_t ALL_LEVEL_MASK = (1u << LEVEL_OPTIONS.size()) - 1u; + +bool log_matches_search(const LogEntry &entry, std::string_view query) { + if (query.empty()) return true; + const std::string needle = lowercase_copy(query); + const auto contains = [&](std::string_view haystack) { + return lowercase_copy(haystack).find(needle) != std::string::npos; + }; + return contains(entry.message) || contains(entry.source) || contains(entry.func); +} + +std::vector collect_log_sources(const std::vector &logs) { + std::vector sources; + for (const LogEntry &entry : logs) { + if (entry.source.empty()) continue; + if (std::find(sources.begin(), sources.end(), entry.source) == sources.end()) { + sources.push_back(entry.source); + } + } + std::sort(sources.begin(), sources.end()); + return sources; +} + +std::vector filter_log_indices(const RouteData &route_data, const LogsUiState &logs_state) { + std::vector indices; + indices.reserve(route_data.logs.size()); + for (size_t i = 0; i < route_data.logs.size(); ++i) { + const LogEntry &entry = route_data.logs[i]; + int level_index = 0; + if (entry.level >= 50) { + level_index = 4; + } else if (entry.level >= 40) { + level_index = 3; + } else if (entry.level >= 30) { + level_index = 2; + } else if (entry.level >= 20) { + level_index = 1; + } + if ((logs_state.enabled_levels_mask & (1u << level_index)) == 0) { + continue; + } + if (!logs_state.all_sources) { + const auto it = std::find(logs_state.selected_sources.begin(), + logs_state.selected_sources.end(), + entry.source); + if (it == logs_state.selected_sources.end()) continue; + } + if (!log_matches_search(entry, logs_state.search)) continue; + indices.push_back(static_cast(i)); + } + return indices; +} + +int find_active_log_position(const RouteData &route_data, + const std::vector &filtered_indices, + double tracker_time) { + if (filtered_indices.empty()) return -1; + auto it = std::lower_bound(filtered_indices.begin(), filtered_indices.end(), tracker_time, + [&](int log_index, double tm) { + return route_data.logs[static_cast(log_index)].mono_time < tm; + }); + if (it == filtered_indices.begin()) return static_cast(std::distance(filtered_indices.begin(), it)); + if (it == filtered_indices.end()) return static_cast(filtered_indices.size()) - 1; + if (route_data.logs[static_cast(*it)].mono_time > tracker_time) { + --it; + } + return static_cast(std::distance(filtered_indices.begin(), it)); +} + +std::string format_route_time(double seconds) { + if (seconds < 0.0) { + seconds = 0.0; + } + const int minutes = static_cast(seconds / 60.0); + const double remaining = seconds - static_cast(minutes) * 60.0; + return util::string_format("%d:%06.3f", minutes, remaining); +} + +std::string format_boot_time(double seconds) { + return util::string_format("%.3f", seconds); +} + +std::string format_wall_time(double seconds) { + if (seconds <= 0.0) return "--"; + const time_t wall_seconds = static_cast(seconds); + std::tm wall_tm = {}; + localtime_r(&wall_seconds, &wall_tm); + const int millis = static_cast(std::llround((seconds - std::floor(seconds)) * 1000.0)); + return util::string_format("%02d:%02d:%02d.%03d", + wall_tm.tm_hour, wall_tm.tm_min, wall_tm.tm_sec, millis); +} + +std::string format_log_time(const LogEntry &entry, LogTimeMode mode) { + switch (mode) { + case LogTimeMode::Route: + return format_route_time(entry.mono_time); + case LogTimeMode::Boot: + return format_boot_time(entry.boot_time); + case LogTimeMode::WallClock: + return format_wall_time(entry.wall_time); + } + return format_route_time(entry.mono_time); +} + +const char *time_mode_label(LogTimeMode mode) { + switch (mode) { + case LogTimeMode::Route: return "Route"; + case LogTimeMode::Boot: return "Boot"; + case LogTimeMode::WallClock: return "Wall clock"; + } + return "Route"; +} + +std::string level_filter_label(uint32_t mask) { + if (mask == ALL_LEVEL_MASK) return "All levels"; + if (mask == 0b11110) return "INFO+"; + if (mask == 0b11100) return "WARNING+"; + if (mask == 0b11000) return "ERROR+"; + if (mask == 0b10000) return "CRITICAL"; + + int enabled_count = 0; + const char *last_label = "None"; + for (size_t i = 0; i < LEVEL_OPTIONS.size(); ++i) { + if ((mask & (1u << i)) == 0) { + continue; + } + ++enabled_count; + last_label = LEVEL_OPTIONS[i].label; + } + if (enabled_count == 0) return "None"; + if (enabled_count == 1) return last_label; + return "Custom"; +} + +std::string source_filter_label(const LogsUiState &logs_state, const std::vector &sources) { + if (logs_state.all_sources || logs_state.selected_sources.size() == sources.size()) { + return "All sources"; + } + if (logs_state.selected_sources.empty()) return "No sources"; + if (logs_state.selected_sources.size() == 1) return logs_state.selected_sources.front(); + return std::to_string(logs_state.selected_sources.size()) + " sources"; +} + +const char *level_label(const LogEntry &entry) { + if (entry.origin == LogOrigin::Alert) return "ALRT"; + if (entry.level >= 50) return "CRIT"; + if (entry.level >= 40) return "ERR"; + if (entry.level >= 30) return "WARN"; + if (entry.level >= 20) return "INFO"; + return "DBG"; +} + +ImVec4 level_text_color(const LogEntry &entry, bool active) { + if (active) return color_rgb(46, 54, 63); + if (entry.origin == LogOrigin::Alert) return color_rgb(50, 100, 200); + if (entry.level >= 50) return color_rgb(176, 26, 18); + if (entry.level >= 40) return color_rgb(200, 50, 40); + if (entry.level >= 30) return color_rgb(200, 130, 0); + if (entry.level >= 20) return color_rgb(80, 86, 94); + return color_rgb(126, 133, 141); +} + +ImU32 row_bg_color(const LogEntry &entry, bool active) { + if (active) return IM_COL32(80, 140, 210, 38); + return 0; +} + +void set_tracker_to_log(UiState *state, const LogEntry &entry) { + state->tracker_time = entry.mono_time; + state->has_tracker_time = true; + state->logs.last_auto_scroll_time = entry.mono_time; +} + +void draw_log_expansion_row(const LogEntry &entry) { + ImGui::TableNextRow(); + ImGui::TableSetColumnIndex(0); + ImGui::TextUnformatted(""); + ImGui::TableSetColumnIndex(1); + ImGui::TextUnformatted(""); + ImGui::TableSetColumnIndex(2); + ImGui::TextUnformatted(entry.func.empty() ? "" : entry.func.c_str()); + ImGui::TableSetColumnIndex(3); + ImGui::PushStyleColor(ImGuiCol_Text, color_rgb(96, 104, 113)); + ImGui::TextWrapped("%s", entry.message.c_str()); + if (!entry.func.empty()) { + ImGui::TextWrapped("func: %s", entry.func.c_str()); + } + if (!entry.context.empty()) { + ImGui::TextWrapped("ctx: %s", entry.context.c_str()); + } + ImGui::PopStyleColor(); +} + +void draw_log_row(const LogEntry &entry, + int log_index, + bool active, + UiState *state) { + ImGui::PushID(log_index); + const ImU32 bg = row_bg_color(entry, active); + ImGui::TableNextRow(); + if (bg != 0) { + ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg0, bg); + } + + const std::string time_text = std::string(active ? "\xE2\x96\xB6 " : " ") + format_log_time(entry, state->logs.time_mode); + const auto clickable_text = [&](const char *id, const std::string &text, ImVec4 color = color_rgb(74, 80, 88)) { + ImGui::PushID(id); + ImGui::PushStyleColor(ImGuiCol_Text, color); + ImGui::PushStyleColor(ImGuiCol_Header, ImVec4(0, 0, 0, 0)); + ImGui::PushStyleColor(ImGuiCol_HeaderHovered, ImVec4(0, 0, 0, 0)); + ImGui::PushStyleColor(ImGuiCol_HeaderActive, ImVec4(0, 0, 0, 0)); + const bool clicked = ImGui::Selectable(text.c_str(), false, ImGuiSelectableFlags_AllowDoubleClick); + ImGui::PopStyleColor(4); + ImGui::PopID(); + return clicked; + }; + + bool clicked = false; + ImGui::TableSetColumnIndex(0); + app_push_mono_font(); + clicked = clickable_text("time", time_text); + app_pop_mono_font(); + + ImGui::TableSetColumnIndex(1); + clicked = clickable_text("level", level_label(entry), level_text_color(entry, active)) || clicked; + + ImGui::TableSetColumnIndex(2); + clicked = clickable_text("source", entry.source) || clicked; + + ImGui::TableSetColumnIndex(3); + clicked = clickable_text("message", entry.message) || clicked; + + if (clicked) { + set_tracker_to_log(state, entry); + state->logs.expanded_index = state->logs.expanded_index == log_index ? -1 : log_index; + } + ImGui::PopID(); +} + +} // namespace + +void draw_logs_tab(AppSession *session, UiState *state) { + LogsUiState &logs_state = state->logs; + const RouteData &route_data = session->route_data; + const RouteLoadSnapshot load = session->route_loader ? session->route_loader->snapshot() : RouteLoadSnapshot{}; + const bool loading_logs = load.active && route_data.logs.empty(); + const std::vector sources = collect_log_sources(route_data.logs); + + if (!logs_state.all_sources) { + logs_state.selected_sources.erase( + std::remove_if(logs_state.selected_sources.begin(), + logs_state.selected_sources.end(), + [&](const std::string &source) { + return std::find(sources.begin(), sources.end(), source) == sources.end(); + }), + logs_state.selected_sources.end()); + } + + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(6.0f, 3.0f)); + ImGui::SetNextItemWidth(110.0f); + const std::string levels_label = level_filter_label(logs_state.enabled_levels_mask); + if (ImGui::BeginCombo("##logs_level", levels_label.c_str())) { + bool all_levels = logs_state.enabled_levels_mask == ALL_LEVEL_MASK; + if (ImGui::Checkbox("All levels", &all_levels)) { + logs_state.enabled_levels_mask = all_levels ? ALL_LEVEL_MASK : 0u; + } + ImGui::Separator(); + for (size_t i = 0; i < LEVEL_OPTIONS.size(); ++i) { + bool enabled = (logs_state.enabled_levels_mask & (1u << i)) != 0; + if (ImGui::Checkbox(LEVEL_OPTIONS[i].label, &enabled)) { + if (enabled) { + logs_state.enabled_levels_mask |= (1u << i); + } else { + logs_state.enabled_levels_mask &= ~(1u << i); + } + } + } + ImGui::EndCombo(); + } + ImGui::SameLine(); + + ImGui::SetNextItemWidth(150.0f); + input_text_with_hint_string("##logs_search", "Search...", &logs_state.search); + ImGui::SameLine(); + + const std::string sources_label = source_filter_label(logs_state, sources); + ImGui::SetNextItemWidth(180.0f); + if (ImGui::BeginCombo("##logs_source", sources_label.c_str())) { + bool all_sources = logs_state.all_sources; + if (ImGui::Checkbox("All sources", &all_sources)) { + logs_state.all_sources = all_sources; + if (logs_state.all_sources) { + logs_state.selected_sources.clear(); + } else { + logs_state.selected_sources = sources; + } + } + ImGui::Separator(); + for (const std::string &source : sources) { + bool enabled = logs_state.all_sources + || std::find(logs_state.selected_sources.begin(), logs_state.selected_sources.end(), source) != logs_state.selected_sources.end(); + if (ImGui::Checkbox(source.c_str(), &enabled)) { + if (logs_state.all_sources) { + logs_state.all_sources = false; + logs_state.selected_sources = sources; + } + auto it = std::find(logs_state.selected_sources.begin(), logs_state.selected_sources.end(), source); + if (enabled) { + if (it == logs_state.selected_sources.end()) { + logs_state.selected_sources.push_back(source); + } + } else if (it != logs_state.selected_sources.end()) { + logs_state.selected_sources.erase(it); + } + if (logs_state.selected_sources.size() == sources.size()) { + logs_state.all_sources = true; + logs_state.selected_sources.clear(); + } + } + } + ImGui::EndCombo(); + } + ImGui::SameLine(); + + ImGui::SetNextItemWidth(110.0f); + if (ImGui::BeginCombo("##logs_time_mode", time_mode_label(logs_state.time_mode))) { + for (LogTimeMode mode : {LogTimeMode::Route, LogTimeMode::Boot, LogTimeMode::WallClock}) { + const bool selected = logs_state.time_mode == mode; + if (ImGui::Selectable(time_mode_label(mode), selected)) { + logs_state.time_mode = mode; + } + } + ImGui::EndCombo(); + } + + const std::vector filtered_indices = filter_log_indices(route_data, logs_state); + const bool have_tracker = state->has_tracker_time && !filtered_indices.empty(); + const int active_pos = have_tracker ? find_active_log_position(route_data, filtered_indices, state->tracker_time) : -1; + + ImGui::SameLine(); + ImGui::SetCursorPosX(std::max(ImGui::GetCursorPosX(), ImGui::GetWindowContentRegionMax().x - 110.0f)); + ImGui::Text("%zu / %zu", filtered_indices.size(), route_data.logs.size()); + ImGui::PopStyleVar(); + + if (route_data.logs.empty()) { + ImGui::Spacing(); + ImGui::PushStyleColor(ImGuiCol_Text, color_rgb(116, 124, 133)); + ImGui::TextWrapped("%s", loading_logs ? "Loading logs..." : "No text logs available for this route."); + ImGui::PopStyleColor(); + return; + } + + if (ImGui::BeginChild("##logs_table_child", ImVec2(0.0f, 0.0f), false)) { + if (have_tracker && std::abs(logs_state.last_auto_scroll_time - state->tracker_time) > 1.0e-6) { + const float row_height = ImGui::GetTextLineHeightWithSpacing() + 6.0f; + const float visible_h = std::max(1.0f, ImGui::GetWindowHeight()); + const float target = std::max(0.0f, static_cast(active_pos) * row_height - visible_h * 0.45f); + ImGui::SetScrollY(target); + logs_state.last_auto_scroll_time = state->tracker_time; + } + + if (ImGui::BeginTable("##logs_table", + 4, + ImGuiTableFlags_BordersInnerV | + ImGuiTableFlags_RowBg | + ImGuiTableFlags_Resizable | + ImGuiTableFlags_SizingStretchProp)) { + ImGui::TableSetupColumn("Time", ImGuiTableColumnFlags_WidthFixed, 120.0f); + ImGui::TableSetupColumn("Level", ImGuiTableColumnFlags_WidthFixed, 72.0f); + ImGui::TableSetupColumn("Source", ImGuiTableColumnFlags_WidthFixed, 180.0f); + ImGui::TableSetupColumn("Message", ImGuiTableColumnFlags_WidthStretch); + ImGui::TableHeadersRow(); + + const bool use_clipper = logs_state.expanded_index < 0; + if (use_clipper) { + ImGuiListClipper clipper; + clipper.Begin(static_cast(filtered_indices.size())); + while (clipper.Step()) { + for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; ++i) { + const int log_index = filtered_indices[static_cast(i)]; + const LogEntry &entry = route_data.logs[static_cast(log_index)]; + draw_log_row(entry, log_index, i == active_pos, state); + } + } + } else { + for (int i = 0; i < static_cast(filtered_indices.size()); ++i) { + const int log_index = filtered_indices[static_cast(i)]; + const LogEntry &entry = route_data.logs[static_cast(log_index)]; + draw_log_row(entry, log_index, i == active_pos, state); + if (logs_state.expanded_index == log_index) { + draw_log_expansion_row(entry); + } + } + } + + ImGui::EndTable(); + } + } + ImGui::EndChild(); +} diff --git a/openpilot/tools/jotpluggler/main.cc b/openpilot/tools/jotpluggler/main.cc new file mode 100644 index 0000000000..22bc29664c --- /dev/null +++ b/openpilot/tools/jotpluggler/main.cc @@ -0,0 +1,126 @@ +#include +#include + +#include "tools/jotpluggler/app.h" + +namespace { + +constexpr const char *DEMO_ROUTE = "5beb9b58bd12b691/0000010a--a51155e496"; + +void print_usage(const char *argv0) { + std::cerr + << "Usage: " << argv0 << " [--layout ] [options] [route]\n" + << "\n" + << "Options:\n" + << " --demo\n" + << " --data-dir \n" + << " --stream\n" + << " --address \n" + << " --buffer-seconds \n" + << " --width \n" + << " --height \n" + << " --output \n" + << " --show\n" + << " --sync-load\n" + << "\n" + << "Examples:\n" + << " " << argv0 << "\n" + << " " << argv0 << " --demo\n" + << " " << argv0 << " --layout longitudinal --demo\n" + << " " << argv0 << " --layout longitudinal --demo --output /tmp/longitudinal.png\n" + << " " << argv0 << " --stream --show\n" + << " " << argv0 << " --stream --address 192.168.60.52 --buffer-seconds 45 --show\n"; +} + +bool parse_int(const char *value, int *out) { + char *end = nullptr; + const long parsed = std::strtol(value, &end, 10); + if (end == nullptr || *end != '\0') return false; + *out = static_cast(parsed); + return true; +} + +bool parse_double(const char *value, double *out) { + char *end = nullptr; + const double parsed = std::strtod(value, &end); + if (end == nullptr || *end != '\0') return false; + *out = parsed; + return true; +} + +} // namespace + +int main(int argc, char *argv[]) { + Options options; + for (int i = 1; i < argc; ++i) { + const std::string arg = argv[i]; + const auto require_value = [&](const char *flag) -> const char * { + if (i + 1 >= argc) { + std::cerr << "Missing value for " << flag << "\n"; + print_usage(argv[0]); + std::exit(2); + } + return argv[++i]; + }; + + if (arg == "--layout") { + options.layout = require_value("--layout"); + } else if (arg == "--demo") { + options.route_name = DEMO_ROUTE; + } else if (arg == "--data-dir") { + options.data_dir = require_value("--data-dir"); + } else if (arg == "--stream") { + options.stream = true; + } else if (arg == "--address") { + options.stream_address = require_value("--address"); + } else if (arg == "--buffer-seconds") { + if (!parse_double(require_value("--buffer-seconds"), &options.stream_buffer_seconds)) { + std::cerr << "Invalid buffer seconds\n"; + return 2; + } + } else if (arg == "--output") { + options.output_path = require_value("--output"); + } else if (arg == "--width") { + if (!parse_int(require_value("--width"), &options.width)) { + std::cerr << "Invalid width\n"; + return 2; + } + } else if (arg == "--height") { + if (!parse_int(require_value("--height"), &options.height)) { + std::cerr << "Invalid height\n"; + return 2; + } + } else if (arg == "--show") { + options.show = true; + } else if (arg == "--sync-load") { + options.sync_load = true; + } else if (arg == "--help" || arg == "-h") { + print_usage(argv[0]); + return 0; + } else if (!arg.empty() && arg[0] != '-' && options.route_name.empty()) { + options.route_name = arg; + } else { + std::cerr << "Unknown argument: " << arg << "\n"; + print_usage(argv[0]); + return 2; + } + } + + if (options.output_path.empty() && !options.show) { + options.show = true; + } + if (options.width <= 0 || options.height <= 0) { + std::cerr << "Width and height must be positive\n"; + return 2; + } + if (options.stream && !options.route_name.empty()) { + std::cerr << "Route/file mode and --stream are mutually exclusive\n"; + return 2; + } + if (options.stream_buffer_seconds <= 0.0) { + std::cerr << "Buffer seconds must be positive\n"; + return 2; + } + + return run(options); +} diff --git a/openpilot/tools/jotpluggler/map.cc b/openpilot/tools/jotpluggler/map.cc new file mode 100644 index 0000000000..fb4e03c912 --- /dev/null +++ b/openpilot/tools/jotpluggler/map.cc @@ -0,0 +1,1328 @@ +#include "tools/jotpluggler/app.h" +#include "tools/jotpluggler/common.h" +#include "tools/jotpluggler/map.h" + +#include + +extern "C" { +#include +} + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "common/util.h" +#include "json11/json11.hpp" + +namespace fs = std::filesystem; + +namespace { + +constexpr int MAP_MIN_ZOOM = 1; +constexpr int MAP_MAX_ZOOM = 18; +constexpr int MAP_SINGLE_POINT_MIN_ZOOM = 14; +constexpr float MAP_WHEEL_ZOOM_STEP = 0.25f; +constexpr double MAP_TRACE_PAD_FRAC = 0.45; +constexpr double MAP_TRACE_MIN_LAT_PAD = 0.01; +constexpr double MAP_BOUNDS_GRID = 0.005; +constexpr double MAP_CORRIDOR_LAT_PAD = 0.010; +constexpr double MAP_CORRIDOR_MIN_STEP_S = 1.5; +constexpr size_t MAP_CORRIDOR_MAX_BOXES = 36; +constexpr float MAP_INITIAL_FIT_FILL = 0.88f; +constexpr float MAP_MIN_ZOOM_FILL = 0.98f; +constexpr float MAP_EDGE_FADE_FRAC = 0.28f; +constexpr const char *MAP_QUERY_ENDPOINTS[] = { + "https://overpass-api.de/api/interpreter", + "https://overpass.private.coffee/api/interpreter", +}; +struct GeoPoint { + double lat = 0.0; + double lon = 0.0; +}; + +struct ProjectedPoint { + float x = 0.0f; + float y = 0.0f; +}; + +struct ProjectedBounds { + float min_x = 0.0f; + float min_y = 0.0f; + float max_x = 0.0f; + float max_y = 0.0f; + + bool valid() const { + return max_x >= min_x && max_y >= min_y; + } +}; + +enum class RoadClass : uint8_t { + Motorway, + Primary, + Secondary, + Local, +}; + +struct RoadFeature { + RoadClass road_class = RoadClass::Local; + ProjectedBounds bounds; + std::vector points; +}; + +struct WaterLineFeature { + ProjectedBounds bounds; + std::vector points; +}; + +struct WaterPolygonFeature { + ProjectedBounds bounds; + std::vector ring; +}; + +} // namespace + +struct RouteBasemap { + std::string key; + GeoBounds bounds; + ProjectedBounds projected_bounds; + std::vector roads; + std::vector water_lines; + std::vector water_polygons; +}; + +struct MapRequestSpec { + std::string key; + GeoBounds bounds; + std::string query; +}; + +namespace { + +double lon_to_world_x(double lon, double zoom) { + return (lon + 180.0) / 360.0 * 256.0 * std::exp2(zoom); +} + +double lat_to_world_y(double lat, double zoom) { + const double lat_rad = lat * M_PI / 180.0; + return (1.0 - std::log(std::tan(lat_rad) + 1.0 / std::cos(lat_rad)) / M_PI) / 2.0 * 256.0 * std::exp2(zoom); +} + +double world_x_to_lon(double x, double zoom) { + return x / std::exp2(zoom) / 256.0 * 360.0 - 180.0; +} + +double world_y_to_lat(double y, double zoom) { + const double n = M_PI - (2.0 * M_PI * (y / std::exp2(zoom))) / 256.0; + return 180.0 / M_PI * std::atan(std::sinh(n)); +} + +double map_trace_center_lat(const GpsTrace &trace) { + return (trace.min_lat + trace.max_lat) * 0.5; +} + +double map_trace_center_lon(const GpsTrace &trace) { + return (trace.min_lon + trace.max_lon) * 0.5; +} + +double clamp_lat(double lat) { + return std::clamp(lat, -85.0, 85.0); +} + +double clamp_lon(double lon) { + return std::clamp(lon, -179.999, 179.999); +} + +float project_lon0(double lon) { + return static_cast((lon + 180.0) / 360.0 * 256.0); +} + +float project_lat0(double lat) { + const double lat_rad = lat * M_PI / 180.0; + return static_cast((1.0 - std::log(std::tan(lat_rad) + 1.0 / std::cos(lat_rad)) / M_PI) / 2.0 * 256.0); +} + +double cos_lat_scale(double lat) { + return std::max(0.2, std::cos(lat * M_PI / 180.0)); +} + +double quantize_down(double value, double step) { + return std::floor(value / step) * step; +} + +double quantize_up(double value, double step) { + return std::ceil(value / step) * step; +} + +ProjectedBounds compute_projected_bounds(const std::vector &points) { + ProjectedBounds bounds; + if (points.empty()) { + return bounds; + } + bounds.min_x = bounds.max_x = points.front().x; + bounds.min_y = bounds.max_y = points.front().y; + for (const ProjectedPoint &point : points) { + bounds.min_x = std::min(bounds.min_x, point.x); + bounds.max_x = std::max(bounds.max_x, point.x); + bounds.min_y = std::min(bounds.min_y, point.y); + bounds.max_y = std::max(bounds.max_y, point.y); + } + return bounds; +} + +ProjectedBounds project_bounds0(const GeoBounds &bounds) { + if (!bounds.valid()) { + return {}; + } + return ProjectedBounds{ + .min_x = project_lon0(bounds.west), + .min_y = project_lat0(bounds.north), + .max_x = project_lon0(bounds.east), + .max_y = project_lat0(bounds.south), + }; +} + +bool feature_intersects_view(const ProjectedBounds &feature, const ProjectedBounds &view, float zoom_scale) { + const float min_x = feature.min_x * zoom_scale; + const float max_x = feature.max_x * zoom_scale; + const float min_y = feature.min_y * zoom_scale; + const float max_y = feature.max_y * zoom_scale; + return !(max_x < view.min_x || min_x > view.max_x + || max_y < view.min_y || min_y > view.max_y); +} + +GeoBounds requested_bounds_for_trace(const GpsTrace &trace) { + if (trace.points.empty()) { + return {}; + } + const double center_lat = map_trace_center_lat(trace); + const double lat_span = std::max(trace.max_lat - trace.min_lat, 0.002); + const double lon_span = std::max(trace.max_lon - trace.min_lon, 0.002 / cos_lat_scale(center_lat)); + const double lat_pad = std::max(lat_span * MAP_TRACE_PAD_FRAC, MAP_TRACE_MIN_LAT_PAD); + const double lon_pad = std::max(lon_span * MAP_TRACE_PAD_FRAC, MAP_TRACE_MIN_LAT_PAD / cos_lat_scale(center_lat)); + + GeoBounds bounds; + bounds.south = clamp_lat(quantize_down(trace.min_lat - lat_pad, MAP_BOUNDS_GRID)); + bounds.north = clamp_lat(quantize_up(trace.max_lat + lat_pad, MAP_BOUNDS_GRID)); + bounds.west = clamp_lon(quantize_down(trace.min_lon - lon_pad, MAP_BOUNDS_GRID)); + bounds.east = clamp_lon(quantize_up(trace.max_lon + lon_pad, MAP_BOUNDS_GRID)); + return bounds; +} + +GeoBounds merge_bounds(const GeoBounds &a, const GeoBounds &b) { + if (!a.valid()) return b; + if (!b.valid()) return a; + return GeoBounds{ + .south = std::min(a.south, b.south), + .west = std::min(a.west, b.west), + .north = std::max(a.north, b.north), + .east = std::max(a.east, b.east), + }; +} + +bool bounds_overlap_or_touch(const GeoBounds &a, const GeoBounds &b) { + return !(a.east < b.west || b.east < a.west || a.north < b.south || b.north < a.south); +} + +std::vector corridor_boxes_for_trace(const GpsTrace &trace) { + std::vector boxes; + if (trace.points.empty()) { + return boxes; + } + + const double center_lat = map_trace_center_lat(trace); + const double lon_pad = MAP_CORRIDOR_LAT_PAD / cos_lat_scale(center_lat); + const double total_time = trace.points.back().time - trace.points.front().time; + const double target_boxes = std::min(MAP_CORRIDOR_MAX_BOXES, std::max(8.0, total_time / MAP_CORRIDOR_MIN_STEP_S)); + const size_t stride = std::max(1, static_cast(std::ceil(trace.points.size() / target_boxes))); + + auto add_box = [&](double lat, double lon) { + GeoBounds box{ + .south = clamp_lat(quantize_down(lat - MAP_CORRIDOR_LAT_PAD, MAP_BOUNDS_GRID)), + .west = clamp_lon(quantize_down(lon - lon_pad, MAP_BOUNDS_GRID)), + .north = clamp_lat(quantize_up(lat + MAP_CORRIDOR_LAT_PAD, MAP_BOUNDS_GRID)), + .east = clamp_lon(quantize_up(lon + lon_pad, MAP_BOUNDS_GRID)), + }; + if (!box.valid()) { + return; + } + for (GeoBounds &existing : boxes) { + if (bounds_overlap_or_touch(existing, box)) { + existing = merge_bounds(existing, box); + return; + } + } + boxes.push_back(box); + }; + + add_box(trace.points.front().lat, trace.points.front().lon); + for (size_t i = stride; i < trace.points.size(); i += stride) { + add_box(trace.points[i].lat, trace.points[i].lon); + } + add_box(trace.points.back().lat, trace.points.back().lon); + + bool merged = true; + while (merged) { + merged = false; + for (size_t i = 0; i < boxes.size() && !merged; ++i) { + for (size_t j = i + 1; j < boxes.size(); ++j) { + if (bounds_overlap_or_touch(boxes[i], boxes[j])) { + boxes[i] = merge_bounds(boxes[i], boxes[j]); + boxes.erase(boxes.begin() + static_cast(j)); + merged = true; + break; + } + } + } + } + return boxes; +} + +ProjectedBounds view_bounds(double top_left_x, double top_left_y, float width, float height) { + return ProjectedBounds{ + .min_x = static_cast(top_left_x), + .min_y = static_cast(top_left_y), + .max_x = static_cast(top_left_x + width), + .max_y = static_cast(top_left_y + height), + }; +} + +int fit_map_zoom_for_bounds(const GeoBounds &bounds, float width, float height, float fill_fraction) { + if (!bounds.valid()) { + return MAP_MIN_ZOOM; + } + const double max_width = std::max(1.0f, width * fill_fraction); + const double max_height = std::max(1.0f, height * fill_fraction); + for (int z = MAP_MAX_ZOOM; z >= MAP_MIN_ZOOM; --z) { + const double pixel_width = std::abs(lon_to_world_x(bounds.east, z) - lon_to_world_x(bounds.west, z)); + const double pixel_height = std::abs(lat_to_world_y(bounds.south, z) - lat_to_world_y(bounds.north, z)); + if (pixel_width <= max_width && pixel_height <= max_height) { + return z; + } + } + return MAP_MIN_ZOOM; +} + +int fit_map_zoom_for_trace(const GpsTrace &trace, float width, float height) { + return fit_map_zoom_for_bounds(requested_bounds_for_trace(trace), width, height, MAP_INITIAL_FIT_FILL); +} + +int minimum_allowed_map_zoom(const GeoBounds &bounds, const GpsTrace &trace, ImVec2 size) { + if (trace.points.size() <= 1) { + return MAP_SINGLE_POINT_MIN_ZOOM; + } + const int fit_zoom = fit_map_zoom_for_bounds(bounds.valid() ? bounds : requested_bounds_for_trace(trace), + size.x, size.y, MAP_MIN_ZOOM_FILL); + return std::clamp(fit_zoom, MAP_MIN_ZOOM, MAP_MAX_ZOOM); +} + +std::optional interpolate_gps(const GpsTrace &trace, double time_value) { + if (trace.points.empty()) { + return std::nullopt; + } + if (time_value <= trace.points.front().time) { + return trace.points.front(); + } + if (time_value >= trace.points.back().time) { + return trace.points.back(); + } + auto upper = std::lower_bound(trace.points.begin(), trace.points.end(), time_value, + [](const GpsPoint &point, double target) { + return point.time < target; + }); + if (upper == trace.points.begin()) { + return trace.points.front(); + } + const GpsPoint &p1 = *upper; + const GpsPoint &p0 = *(upper - 1); + const double dt = p1.time - p0.time; + if (dt <= 1.0e-9) { + return p0; + } + const double alpha = (time_value - p0.time) / dt; + GpsPoint out; + out.time = time_value; + out.lat = p0.lat + (p1.lat - p0.lat) * alpha; + out.lon = p0.lon + (p1.lon - p0.lon) * alpha; + out.bearing = static_cast(p0.bearing + (p1.bearing - p0.bearing) * alpha); + out.type = alpha < 0.5 ? p0.type : p1.type; + return out; +} + +ImU32 map_timeline_color(TimelineEntry::Type type, float alpha = 1.0f) { + return timeline_entry_color(type, alpha, {140, 150, 165}); +} + +ImVec2 gps_to_screen(double lat, double lon, double zoom, double top_left_x, double top_left_y, const ImVec2 &rect_min) { + return ImVec2(rect_min.x + static_cast(lon_to_world_x(lon, zoom) - top_left_x), + rect_min.y + static_cast(lat_to_world_y(lat, zoom) - top_left_y)); +} + +bool point_in_rect_with_margin(const ImVec2 &point, const ImVec2 &rect_min, const ImVec2 &rect_max, + float margin_fraction) { + const float width = rect_max.x - rect_min.x; + const float height = rect_max.y - rect_min.y; + const float margin_x = width * margin_fraction; + const float margin_y = height * margin_fraction; + return point.x >= rect_min.x + margin_x && point.x <= rect_max.x - margin_x + && point.y >= rect_min.y + margin_y && point.y <= rect_max.y - margin_y; +} + +void draw_car_marker(ImDrawList *draw_list, ImVec2 center, float bearing_deg, ImU32 color, float size) { + const float rad = bearing_deg * static_cast(M_PI / 180.0); + const ImVec2 forward(std::sin(rad), -std::cos(rad)); + const ImVec2 perp(-forward.y, forward.x); + const ImVec2 tip(center.x + forward.x * size, center.y + forward.y * size); + const ImVec2 base(center.x - forward.x * size * 0.45f, center.y - forward.y * size * 0.45f); + const ImVec2 left(base.x + perp.x * size * 0.6f, base.y + perp.y * size * 0.6f); + const ImVec2 right(base.x - perp.x * size * 0.6f, base.y - perp.y * size * 0.6f); + draw_list->AddTriangleFilled(tip, left, right, color); + draw_list->AddTriangle(tip, left, right, IM_COL32(255, 255, 255, 210), 2.0f); +} + +bool is_convex_ring(const std::vector &points) { + if (points.size() < 4) { + return false; + } + float sign = 0.0f; + const size_t n = points.size(); + for (size_t i = 0; i < n; ++i) { + const ImVec2 &a = points[i]; + const ImVec2 &b = points[(i + 1) % n]; + const ImVec2 &c = points[(i + 2) % n]; + const float cross = (b.x - a.x) * (c.y - b.y) - (b.y - a.y) * (c.x - b.x); + if (std::abs(cross) < 1.0e-3f) { + continue; + } + if (sign == 0.0f) { + sign = cross; + } else if ((cross > 0.0f) != (sign > 0.0f)) { + return false; + } + } + return sign != 0.0f; +} + +uint64_t fnv1a64(std::string_view text) { + uint64_t value = 1469598103934665603ULL; + for (unsigned char c : text) { + value ^= static_cast(c); + value *= 1099511628211ULL; + } + return value; +} + +fs::path basemap_cache_root() { + const char *home = std::getenv("HOME"); + fs::path root = home != nullptr ? fs::path(home) / ".comma" : fs::temp_directory_path(); + root /= "jotpluggler_vector_map"; + fs::create_directories(root); + return root; +} + +std::string bounds_key(const GeoBounds &bounds) { + return util::string_format("v2_%.5f_%.5f_%.5f_%.5f", + bounds.south, bounds.west, bounds.north, bounds.east); +} + +fs::path basemap_cache_path(const std::string &key) { + const uint64_t hash = fnv1a64(key); + return basemap_cache_root() / util::string_format("%016llx.bin.zst", static_cast(hash)); +} + +uint64_t cache_directory_size_bytes() { + uint64_t total = 0; + const fs::path root = basemap_cache_root(); + if (!fs::exists(root)) { + return 0; + } + for (const fs::directory_entry &entry : fs::directory_iterator(root)) { + if (entry.is_regular_file()) { + total += static_cast(entry.file_size()); + } + } + return total; +} + +size_t cache_directory_file_count() { + size_t count = 0; + const fs::path root = basemap_cache_root(); + if (!fs::exists(root)) { + return 0; + } + for (const fs::directory_entry &entry : fs::directory_iterator(root)) { + if (entry.is_regular_file()) { + ++count; + } + } + return count; +} + +void clear_cache_directory() { + const fs::path root = basemap_cache_root(); + if (!fs::exists(root)) { + return; + } + for (const fs::directory_entry &entry : fs::directory_iterator(root)) { + if (entry.is_regular_file()) { + std::error_code ec; + fs::remove(entry.path(), ec); + } + } +} + +std::string percent_encode(std::string_view text) { + std::string out; + out.reserve(text.size() * 3); + for (unsigned char c : text) { + if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') + || c == '-' || c == '_' || c == '.' || c == '~') { + out.push_back(static_cast(c)); + } else { + out += util::string_format("%%%02X", static_cast(c)); + } + } + return out; +} + +std::string bbox_string(const GeoBounds &bounds) { + return util::string_format("%.6f,%.6f,%.6f,%.6f", + bounds.south, bounds.west, bounds.north, bounds.east); +} + +MapRequestSpec build_request_for_trace(const GpsTrace &trace) { + const std::vector boxes = corridor_boxes_for_trace(trace); + GeoBounds union_bounds; + std::string query = "[out:json][timeout:25];("; + for (const GeoBounds &box : boxes) { + union_bounds = merge_bounds(union_bounds, box); + const std::string bbox = bbox_string(box); + query += "way[\"highway\"][\"area\"!=\"yes\"](" + bbox + ");"; + query += "way[\"natural\"=\"water\"](" + bbox + ");"; + query += "way[\"waterway\"=\"riverbank\"](" + bbox + ");"; + query += "way[\"waterway\"~\"river|stream|canal\"](" + bbox + ");"; + } + query += ");out tags geom;"; + + std::string key = bounds_key(union_bounds); + key += ":"; + key += std::to_string(boxes.size()); + for (const GeoBounds &box : boxes) { + key += ":"; + key += bbox_string(box); + } + return MapRequestSpec{ + .key = std::move(key), + .bounds = union_bounds, + .query = std::move(query), + }; +} + +bool fetch_overpass_json(std::string_view query, std::string *out) { + const std::string body = std::string("data=") + percent_encode(query); + for (const char *endpoint : MAP_QUERY_ENDPOINTS) { + const std::string command = "curl -fsSL --compressed --connect-timeout 8 --max-time 30 " + "-A 'jotpluggler-vector-map/1.0' " + "-H 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8' " + "--data-raw " + shell_quote(body) + " " + + shell_quote(endpoint); + const std::string response = util::check_output(command); + if (!response.empty() && response.front() == '{') { + *out = response; + return true; + } + } + return false; +} + +std::string load_overpass_json(std::string_view query) { + std::string response; + if (!fetch_overpass_json(query, &response)) { + return {}; + } + return response; +} + +template +void append_pod(std::string *out, const T &value) { + const size_t start = out->size(); + out->resize(start + sizeof(T)); + std::memcpy(out->data() + start, &value, sizeof(T)); +} + +template +bool read_pod(std::string_view data, size_t *offset, T *value) { + if (*offset + sizeof(T) > data.size()) { + return false; + } + std::memcpy(value, data.data() + *offset, sizeof(T)); + *offset += sizeof(T); + return true; +} + +void append_points(std::string *out, const std::vector &points) { + const uint32_t count = static_cast(points.size()); + append_pod(out, count); + for (const ProjectedPoint &point : points) { + append_pod(out, point.x); + append_pod(out, point.y); + } +} + +bool read_points(std::string_view data, size_t *offset, std::vector *points) { + uint32_t count = 0; + if (!read_pod(data, offset, &count)) { + return false; + } + points->clear(); + points->reserve(count); + for (uint32_t i = 0; i < count; ++i) { + ProjectedPoint point; + if (!read_pod(data, offset, &point.x) || !read_pod(data, offset, &point.y)) { + return false; + } + points->push_back(point); + } + return true; +} + +std::string serialize_basemap_payload(const RouteBasemap &basemap) { + std::string raw; + raw.reserve(1024 + basemap.roads.size() * 48); + raw.append("JBM2", 4); + append_pod(&raw, basemap.bounds.south); + append_pod(&raw, basemap.bounds.west); + append_pod(&raw, basemap.bounds.north); + append_pod(&raw, basemap.bounds.east); + + const uint32_t road_count = static_cast(basemap.roads.size()); + const uint32_t water_line_count = static_cast(basemap.water_lines.size()); + const uint32_t water_polygon_count = static_cast(basemap.water_polygons.size()); + append_pod(&raw, road_count); + append_pod(&raw, water_line_count); + append_pod(&raw, water_polygon_count); + + for (const RoadFeature &road : basemap.roads) { + const uint8_t kind = static_cast(road.road_class); + append_pod(&raw, kind); + append_points(&raw, road.points); + } + for (const WaterLineFeature &water : basemap.water_lines) { + append_points(&raw, water.points); + } + for (const WaterPolygonFeature &water : basemap.water_polygons) { + append_points(&raw, water.ring); + } + return raw; +} + +std::optional deserialize_basemap_payload(std::string_view raw, const std::string &key) { + if (!util::starts_with(std::string(raw), "JBM2")) { + return std::nullopt; + } + size_t offset = 4; + RouteBasemap basemap; + basemap.key = key; + if (!read_pod(raw, &offset, &basemap.bounds.south) + || !read_pod(raw, &offset, &basemap.bounds.west) + || !read_pod(raw, &offset, &basemap.bounds.north) + || !read_pod(raw, &offset, &basemap.bounds.east)) { + return std::nullopt; + } + basemap.projected_bounds = project_bounds0(basemap.bounds); + + uint32_t road_count = 0; + uint32_t water_line_count = 0; + uint32_t water_polygon_count = 0; + if (!read_pod(raw, &offset, &road_count) + || !read_pod(raw, &offset, &water_line_count) + || !read_pod(raw, &offset, &water_polygon_count)) { + return std::nullopt; + } + + basemap.roads.reserve(road_count); + for (uint32_t i = 0; i < road_count; ++i) { + uint8_t kind = 0; + std::vector points; + if (!read_pod(raw, &offset, &kind) || !read_points(raw, &offset, &points)) { + return std::nullopt; + } + basemap.roads.push_back(RoadFeature{ + .road_class = static_cast(kind), + .bounds = compute_projected_bounds(points), + .points = std::move(points), + }); + } + + basemap.water_lines.reserve(water_line_count); + for (uint32_t i = 0; i < water_line_count; ++i) { + std::vector points; + if (!read_points(raw, &offset, &points)) { + return std::nullopt; + } + basemap.water_lines.push_back(WaterLineFeature{ + .bounds = compute_projected_bounds(points), + .points = std::move(points), + }); + } + + basemap.water_polygons.reserve(water_polygon_count); + for (uint32_t i = 0; i < water_polygon_count; ++i) { + std::vector ring; + if (!read_points(raw, &offset, &ring)) { + return std::nullopt; + } + basemap.water_polygons.push_back(WaterPolygonFeature{ + .bounds = compute_projected_bounds(ring), + .ring = std::move(ring), + }); + } + return basemap; +} + +bool save_compressed_basemap(const fs::path &path, const RouteBasemap &basemap) { + const std::string raw = serialize_basemap_payload(basemap); + const size_t bound = ZSTD_compressBound(raw.size()); + std::string compressed(bound, '\0'); + const size_t size = ZSTD_compress(compressed.data(), compressed.size(), raw.data(), raw.size(), 5); + if (ZSTD_isError(size)) { + return false; + } + compressed.resize(size); + ensure_parent_dir(path); + const std::string path_string = path.string(); + return util::write_file(path_string.c_str(), compressed.data(), compressed.size(), O_WRONLY | O_CREAT | O_TRUNC) == 0; +} + +std::optional load_compressed_basemap(const fs::path &path, const std::string &key) { + const std::string compressed = util::read_file(path.string()); + if (compressed.empty()) { + return std::nullopt; + } + const unsigned long long raw_size = ZSTD_getFrameContentSize(compressed.data(), compressed.size()); + if (raw_size == ZSTD_CONTENTSIZE_ERROR || raw_size == ZSTD_CONTENTSIZE_UNKNOWN || raw_size > (1ULL << 31)) { + return std::nullopt; + } + std::string raw(static_cast(raw_size), '\0'); + const size_t actual = ZSTD_decompress(raw.data(), raw.size(), compressed.data(), compressed.size()); + if (ZSTD_isError(actual)) { + return std::nullopt; + } + raw.resize(actual); + return deserialize_basemap_payload(raw, key); +} + +std::vector geometry_points(const json11::Json &geometry_json) { + std::vector points; + const auto items = geometry_json.array_items(); + points.reserve(items.size()); + for (const json11::Json &point : items) { + if (!point["lat"].is_number() || !point["lon"].is_number()) { + continue; + } + points.push_back(ProjectedPoint{ + .x = project_lon0(point["lon"].number_value()), + .y = project_lat0(point["lat"].number_value()), + }); + } + return points; +} + +std::optional classify_road(std::string_view highway) { + if (highway == "motorway" || highway == "motorway_link" || highway == "trunk" || highway == "trunk_link") { + return RoadClass::Motorway; + } + if (highway == "primary" || highway == "primary_link") { + return RoadClass::Primary; + } + if (highway == "secondary" || highway == "secondary_link" || highway == "tertiary" || highway == "tertiary_link") { + return RoadClass::Secondary; + } + if (highway == "residential" || highway == "unclassified" || highway == "living_street" || highway == "road") { + return RoadClass::Local; + } + return std::nullopt; +} + +std::optional parse_basemap_json(const std::string &raw, const GeoBounds &bounds, const std::string &key) { + std::string parse_error; + const json11::Json root = json11::Json::parse(raw, parse_error); + if (!parse_error.empty() || !root.is_object()) { + return std::nullopt; + } + + RouteBasemap basemap; + basemap.key = key; + basemap.bounds = bounds; + basemap.projected_bounds = project_bounds0(bounds); + + for (const json11::Json &element : root["elements"].array_items()) { + if (element["type"].string_value() != "way") { + continue; + } + const json11::Json &tags = element["tags"]; + const std::vector points = geometry_points(element["geometry"]); + if (points.size() < 2) { + continue; + } + + const std::string highway = tags["highway"].string_value(); + if (!highway.empty()) { + const std::optional road_class = classify_road(highway); + if (!road_class.has_value()) { + continue; + } + basemap.roads.push_back(RoadFeature{ + .road_class = *road_class, + .bounds = compute_projected_bounds(points), + .points = points, + }); + continue; + } + + const std::string natural = tags["natural"].string_value(); + const std::string waterway = tags["waterway"].string_value(); + const bool closed = points.size() >= 4 + && std::abs(points.front().x - points.back().x) < 1.0e-6f + && std::abs(points.front().y - points.back().y) < 1.0e-6f; + if ((natural == "water" || waterway == "riverbank") && closed) { + basemap.water_polygons.push_back(WaterPolygonFeature{ + .bounds = compute_projected_bounds(points), + .ring = points, + }); + continue; + } + if (waterway == "river" || waterway == "stream" || waterway == "canal") { + basemap.water_lines.push_back(WaterLineFeature{ + .bounds = compute_projected_bounds(points), + .points = points, + }); + } + } + + return basemap; +} + +struct RoadPaint { + ImU32 casing = 0; + ImU32 fill = 0; + float casing_width = 1.0f; + float fill_width = 1.0f; +}; + +constexpr ImU32 MAP_BG_COLOR = IM_COL32(244, 243, 238, 255); +constexpr ImU32 MAP_WATER_FILL = IM_COL32(193, 216, 235, 185); +constexpr ImU32 MAP_WATER_OUTLINE = IM_COL32(143, 173, 201, 220); +constexpr ImU32 MAP_WATER_LINE = IM_COL32(156, 186, 214, 205); +constexpr ImU32 MAP_ROUTE_HALO = IM_COL32(31, 40, 50, 92); + +RoadPaint road_paint(RoadClass road_class, float zoom) { + const float scale = std::clamp(0.88f + 0.12f * (zoom - 12.0f), 0.76f, 1.95f); + switch (road_class) { + case RoadClass::Motorway: + return { + .casing = IM_COL32(163, 157, 149, 235), + .fill = IM_COL32(245, 235, 215, 255), + .casing_width = 5.6f * scale, + .fill_width = 3.7f * scale, + }; + case RoadClass::Primary: + return { + .casing = IM_COL32(171, 171, 168, 220), + .fill = IM_COL32(249, 246, 237, 248), + .casing_width = 4.6f * scale, + .fill_width = 2.95f * scale, + }; + case RoadClass::Secondary: + return { + .casing = IM_COL32(183, 186, 189, 210), + .fill = IM_COL32(252, 251, 247, 240), + .casing_width = 3.5f * scale, + .fill_width = 2.15f * scale, + }; + case RoadClass::Local: + default: + return { + .casing = IM_COL32(200, 202, 205, 195), + .fill = IM_COL32(255, 255, 254, 230), + .casing_width = 2.5f * scale, + .fill_width = 1.5f * scale, + }; + } +} + +void clamp_map_center(TabUiState::MapPaneState *map_state, const GeoBounds &bounds, const ImVec2 &size) { + if (!bounds.valid() || size.x <= 1.0f || size.y <= 1.0f) { + return; + } + const double zoom = map_state->zoom; + const double min_x = lon_to_world_x(bounds.west, zoom); + const double max_x = lon_to_world_x(bounds.east, zoom); + const double min_y = lat_to_world_y(bounds.north, zoom); + const double max_y = lat_to_world_y(bounds.south, zoom); + const double half_w = size.x * 0.5; + const double half_h = size.y * 0.5; + double center_x = lon_to_world_x(map_state->center_lon, zoom); + double center_y = lat_to_world_y(map_state->center_lat, zoom); + if (max_x - min_x <= size.x) { + center_x = (min_x + max_x) * 0.5; + } else { + center_x = std::clamp(center_x, min_x + half_w, max_x - half_w); + } + if (max_y - min_y <= size.y) { + center_y = (min_y + max_y) * 0.5; + } else { + center_y = std::clamp(center_y, min_y + half_h, max_y - half_h); + } + map_state->center_lon = world_x_to_lon(center_x, zoom); + map_state->center_lat = world_y_to_lat(center_y, zoom); +} + +void initialize_map_pane_state(TabUiState::MapPaneState *map_state, + const GpsTrace &trace, + const GeoBounds &bounds, + ImVec2 size, + SessionDataMode mode, + std::optional cursor_point) { + if (trace.points.empty()) { + return; + } + map_state->initialized = true; + map_state->follow = mode == SessionDataMode::Stream; + const int min_zoom = minimum_allowed_map_zoom(bounds, trace, size); + if (mode == SessionDataMode::Stream && cursor_point.has_value()) { + map_state->zoom = std::max(16.0f, static_cast(min_zoom)); + map_state->center_lat = cursor_point->lat; + map_state->center_lon = cursor_point->lon; + } else { + map_state->zoom = std::max(static_cast(fit_map_zoom_for_trace(trace, size.x, size.y)), + static_cast(min_zoom)); + map_state->center_lat = map_trace_center_lat(trace); + map_state->center_lon = map_trace_center_lon(trace); + } + clamp_map_center(map_state, bounds, size); +} + +void draw_feature_polyline(ImDrawList *draw_list, + const std::vector &points, + float zoom_scale, + double top_left_x, + double top_left_y, + const ImVec2 &rect_min, + ImU32 color, + float thickness, + bool closed = false) { + if (points.size() < 2) { + return; + } + std::vector screen; + screen.reserve(points.size()); + for (const ProjectedPoint &point : points) { + screen.push_back(ImVec2(rect_min.x + point.x * zoom_scale - static_cast(top_left_x), + rect_min.y + point.y * zoom_scale - static_cast(top_left_y))); + } + draw_list->AddPolyline(screen.data(), static_cast(screen.size()), color, + closed ? ImDrawFlags_Closed : ImDrawFlags_None, thickness); +} + +void draw_water_polygon(ImDrawList *draw_list, + const WaterPolygonFeature &feature, + float zoom_scale, + double top_left_x, + double top_left_y, + const ImVec2 &rect_min) { + if (feature.ring.size() < 3) { + return; + } + std::vector screen; + screen.reserve(feature.ring.size()); + for (const ProjectedPoint &point : feature.ring) { + screen.push_back(ImVec2(rect_min.x + point.x * zoom_scale - static_cast(top_left_x), + rect_min.y + point.y * zoom_scale - static_cast(top_left_y))); + } + if (screen.size() >= 3 && is_convex_ring(screen)) { + draw_list->AddConvexPolyFilled(screen.data(), static_cast(screen.size()), MAP_WATER_FILL); + } + draw_list->AddPolyline(screen.data(), static_cast(screen.size()), MAP_WATER_OUTLINE, + ImDrawFlags_Closed, 1.8f); +} + +void draw_edge_fade(ImDrawList *draw_list, + const GeoBounds &bounds, + double zoom, + double top_left_x, + double top_left_y, + const ImVec2 &rect_min, + const ImVec2 &rect_max) { + if (!bounds.valid()) { + return; + } + + const float west_x = rect_min.x + static_cast(lon_to_world_x(bounds.west, zoom) - top_left_x); + const float east_x = rect_min.x + static_cast(lon_to_world_x(bounds.east, zoom) - top_left_x); + const float north_y = rect_min.y + static_cast(lat_to_world_y(bounds.north, zoom) - top_left_y); + const float south_y = rect_min.y + static_cast(lat_to_world_y(bounds.south, zoom) - top_left_y); + + const float fade_x = std::max(28.0f, (rect_max.x - rect_min.x) * MAP_EDGE_FADE_FRAC); + const float fade_y = std::max(28.0f, (rect_max.y - rect_min.y) * MAP_EDGE_FADE_FRAC); + const ImU32 solid = MAP_BG_COLOR; + const ImU32 clear = IM_COL32(244, 243, 238, 6); + + if (west_x > rect_min.x) { + const float x0 = rect_min.x; + const float x1 = std::min(rect_max.x, west_x); + const float xfade = std::max(x0, x1 - fade_x); + draw_list->AddRectFilledMultiColor(ImVec2(x0, rect_min.y), ImVec2(xfade, rect_max.y), solid, solid, solid, solid); + draw_list->AddRectFilledMultiColor(ImVec2(xfade, rect_min.y), ImVec2(x1, rect_max.y), solid, clear, clear, solid); + } + if (east_x < rect_max.x) { + const float x0 = std::max(rect_min.x, east_x); + const float x1 = rect_max.x; + const float xfade = std::min(x1, x0 + fade_x); + draw_list->AddRectFilledMultiColor(ImVec2(x0, rect_min.y), ImVec2(xfade, rect_max.y), clear, solid, solid, clear); + draw_list->AddRectFilledMultiColor(ImVec2(xfade, rect_min.y), ImVec2(x1, rect_max.y), solid, solid, solid, solid); + } + if (north_y > rect_min.y) { + const float y0 = rect_min.y; + const float y1 = std::min(rect_max.y, north_y); + const float yfade = std::max(y0, y1 - fade_y); + draw_list->AddRectFilledMultiColor(ImVec2(rect_min.x, y0), ImVec2(rect_max.x, yfade), solid, solid, solid, solid); + draw_list->AddRectFilledMultiColor(ImVec2(rect_min.x, yfade), ImVec2(rect_max.x, y1), solid, solid, clear, clear); + } + if (south_y < rect_max.y) { + const float y0 = std::max(rect_min.y, south_y); + const float y1 = rect_max.y; + const float yfade = std::min(y1, y0 + fade_y); + draw_list->AddRectFilledMultiColor(ImVec2(rect_min.x, y0), ImVec2(rect_max.x, yfade), clear, clear, solid, solid); + draw_list->AddRectFilledMultiColor(ImVec2(rect_min.x, yfade), ImVec2(rect_max.x, y1), solid, solid, solid, solid); + } +} + +} // namespace + +MapDataManager::MapDataManager() : worker_([this]() { run(); }) {} + +MapDataManager::~MapDataManager() { + { + std::lock_guard lock(mutex_); + stopping_ = true; + } + cv_.notify_all(); + if (worker_.joinable()) { + worker_.join(); + } +} + +void MapDataManager::pump() { + std::unique_ptr ready; + { + std::lock_guard lock(mutex_); + ready = std::move(completed_); + } + if (ready) { + current_ = std::move(ready); + } +} + +void MapDataManager::ensureTrace(const GpsTrace &trace) { + if (trace.points.empty()) { + return; + } + const MapRequestSpec wanted = build_request_for_trace(trace); + if (!wanted.bounds.valid()) { + return; + } + + std::lock_guard lock(mutex_); + if ((current_ && current_->key == wanted.key) || (pending_ && pending_->key == wanted.key)) { + return; + } + + if (const auto cached = load_compressed_basemap(basemap_cache_path(wanted.key), wanted.key)) { + current_ = std::make_unique(std::move(*cached)); + completed_.reset(); + pending_.reset(); + active_.reset(); + return; + } + + pending_ = std::make_unique(Request{ + .key = wanted.key, + .bounds = wanted.bounds, + .query = wanted.query, + }); + cv_.notify_one(); +} + +bool MapDataManager::loading() const { + std::lock_guard lock(mutex_); + return active_ || pending_; +} + +const RouteBasemap *MapDataManager::current() const { + return current_.get(); +} + +void MapDataManager::clearCache() { + std::lock_guard lock(mutex_); + clear_cache_directory(); +} + +MapCacheStats MapDataManager::cacheStats() const { + return MapCacheStats{ + .bytes = cache_directory_size_bytes(), + .files = cache_directory_file_count(), + }; +} + +void MapDataManager::run() { + while (true) { + Request request; + { + std::unique_lock lock(mutex_); + cv_.wait(lock, [&]() { return stopping_ || pending_ != nullptr; }); + if (stopping_) { + return; + } + request = *pending_; + active_ = std::move(pending_); + } + + std::unique_ptr parsed; + const std::string raw = load_overpass_json(request.query); + if (!raw.empty()) { + if (auto basemap = parse_basemap_json(raw, request.bounds, request.key)) { + save_compressed_basemap(basemap_cache_path(request.key), *basemap); + parsed = std::make_unique(std::move(*basemap)); + } + } + + { + std::lock_guard lock(mutex_); + if (active_ && active_->key == request.key) { + completed_ = std::move(parsed); + active_.reset(); + } + } + } +} + +void draw_map_pane(AppSession *session, UiState *state, Pane *, int pane_index) { + TabUiState *tab_state = app_active_tab_state(state); + if (tab_state == nullptr || pane_index < 0 || pane_index >= static_cast(tab_state->map_panes.size())) { + ImGui::TextUnformatted("Map unavailable"); + return; + } + if (!session->map_data) { + ImGui::TextUnformatted("Map unavailable"); + return; + } + + session->map_data->ensureTrace(session->route_data.gps_trace); + session->map_data->pump(); + + TabUiState::MapPaneState &map_state = tab_state->map_panes[static_cast(pane_index)]; + const GpsTrace &trace = session->route_data.gps_trace; + const RouteBasemap *basemap = session->map_data->current(); + const GeoBounds map_bounds = basemap != nullptr ? basemap->bounds : requested_bounds_for_trace(trace); + + const ImVec2 rect_min = ImGui::GetCursorScreenPos(); + const ImVec2 size = ImGui::GetContentRegionAvail(); + const ImVec2 input_size(std::max(1.0f, size.x - 22.0f), std::max(1.0f, size.y)); + ImGui::SetNextItemAllowOverlap(); + ImGui::InvisibleButton("##map_canvas", input_size); + const ImVec2 rect_max(rect_min.x + size.x, rect_min.y + size.y); + const float rect_width = rect_max.x - rect_min.x; + const float rect_height = rect_max.y - rect_min.y; + ImDrawList *draw_list = ImGui::GetWindowDrawList(); + + draw_list->PushClipRect(rect_min, rect_max, true); + draw_list->AddRectFilled(rect_min, rect_max, MAP_BG_COLOR); + + if (trace.points.empty()) { + const char *label = session->async_route_loading ? "Loading map..." : "No GPS trace"; + const ImVec2 text = ImGui::CalcTextSize(label); + draw_list->AddText(ImVec2(rect_min.x + (rect_width - text.x) * 0.5f, + rect_min.y + (rect_height - text.y) * 0.5f), + IM_COL32(110, 118, 128, 255), label); + draw_list->PopClipRect(); + return; + } + + const std::optional cursor_point = state->has_tracker_time + ? interpolate_gps(trace, state->tracker_time) + : std::optional{}; + if (!map_state.initialized) { + initialize_map_pane_state(&map_state, trace, map_bounds, size, session->data_mode, cursor_point); + } + + const int min_zoom = minimum_allowed_map_zoom(map_bounds, trace, size); + if (map_state.follow && cursor_point.has_value()) { + const float follow_zoom = std::clamp(map_state.zoom, static_cast(min_zoom), static_cast(MAP_MAX_ZOOM)); + const double center_x = lon_to_world_x(map_state.center_lon, follow_zoom); + const double center_y = lat_to_world_y(map_state.center_lat, follow_zoom); + const double top_left_x = center_x - rect_width * 0.5; + const double top_left_y = center_y - rect_height * 0.5; + const ImVec2 car_screen = gps_to_screen(cursor_point->lat, cursor_point->lon, follow_zoom, top_left_x, top_left_y, rect_min); + if (!point_in_rect_with_margin(car_screen, rect_min, rect_max, 0.22f)) { + map_state.center_lat = cursor_point->lat; + map_state.center_lon = cursor_point->lon; + } + } + + map_state.zoom = std::clamp(map_state.zoom, static_cast(min_zoom), static_cast(MAP_MAX_ZOOM)); + clamp_map_center(&map_state, map_bounds, size); + + const double zoom = map_state.zoom; + const float zoom_scale = static_cast(std::exp2(zoom)); + const double center_x = lon_to_world_x(map_state.center_lon, zoom); + const double center_y = lat_to_world_y(map_state.center_lat, zoom); + const double top_left_x = center_x - rect_width * 0.5; + const double top_left_y = center_y - rect_height * 0.5; + const ProjectedBounds current_view = view_bounds(top_left_x, top_left_y, rect_width, rect_height); + + if (basemap != nullptr) { + for (const WaterPolygonFeature &water : basemap->water_polygons) { + if (feature_intersects_view(water.bounds, current_view, zoom_scale)) { + draw_water_polygon(draw_list, water, zoom_scale, top_left_x, top_left_y, rect_min); + } + } + for (const WaterLineFeature &water : basemap->water_lines) { + if (feature_intersects_view(water.bounds, current_view, zoom_scale)) { + draw_feature_polyline(draw_list, water.points, zoom_scale, top_left_x, top_left_y, rect_min, + MAP_WATER_LINE, 2.4f); + } + } + + std::array order = { + RoadClass::Local, + RoadClass::Secondary, + RoadClass::Primary, + RoadClass::Motorway, + }; + for (RoadClass road_class : order) { + const RoadPaint paint = road_paint(road_class, static_cast(zoom)); + for (const RoadFeature &road : basemap->roads) { + if (road.road_class != road_class || !feature_intersects_view(road.bounds, current_view, zoom_scale)) { + continue; + } + draw_feature_polyline(draw_list, road.points, zoom_scale, top_left_x, top_left_y, rect_min, + paint.casing, paint.casing_width); + draw_feature_polyline(draw_list, road.points, zoom_scale, top_left_x, top_left_y, rect_min, + paint.fill, paint.fill_width); + } + } + } + + if (basemap != nullptr) { + draw_edge_fade(draw_list, basemap->bounds, zoom, top_left_x, top_left_y, rect_min, rect_max); + } + + for (size_t i = 1; i < trace.points.size(); ++i) { + const GpsPoint &p0 = trace.points[i - 1]; + const GpsPoint &p1 = trace.points[i]; + const ImVec2 s0 = gps_to_screen(p0.lat, p0.lon, zoom, top_left_x, top_left_y, rect_min); + const ImVec2 s1 = gps_to_screen(p1.lat, p1.lon, zoom, top_left_x, top_left_y, rect_min); + draw_list->AddLine(s0, s1, MAP_ROUTE_HALO, 5.8f); + draw_list->AddLine(s0, s1, map_timeline_color(p1.type, 1.0f), 3.25f); + } + + if (cursor_point.has_value()) { + const ImVec2 marker = gps_to_screen(cursor_point->lat, cursor_point->lon, zoom, top_left_x, top_left_y, rect_min); + const float marker_size = std::clamp(9.0f + 1.0f * static_cast(zoom - min_zoom), 9.0f, 20.0f); + draw_car_marker(draw_list, marker, cursor_point->bearing, map_timeline_color(cursor_point->type, 1.0f), marker_size); + } + + if (session->map_data->loading()) { + const char *label = basemap != nullptr ? "Refreshing roads..." : "Loading roads..."; + const ImVec2 text = ImGui::CalcTextSize(label); + const ImVec2 pos(rect_min.x + 12.0f, rect_max.y - text.y - 12.0f); + draw_list->AddRectFilled(ImVec2(pos.x - 6.0f, pos.y - 4.0f), + ImVec2(pos.x + text.x + 6.0f, pos.y + text.y + 4.0f), + IM_COL32(255, 255, 255, 180), 4.0f); + draw_list->AddText(pos, IM_COL32(84, 93, 105, 255), label); + } + draw_list->PopClipRect(); + + const bool canvas_hovered = ImGui::IsItemHovered(); + const bool double_clicked = canvas_hovered && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left); + bool overlay_hovered = false; + if (const std::string google_maps_url = route_google_maps_url(trace); !google_maps_url.empty()) { + std::string label = std::string("Google Maps ") + icon::BOX_ARROW_UP_RIGHT; + const ImVec2 text_size = ImGui::CalcTextSize(label.c_str()); + const ImVec2 button_size(text_size.x + 20.0f, text_size.y + 10.0f); + const ImVec2 button_pos(rect_max.x - button_size.x - 28.0f, rect_min.y + 10.0f); + ImGui::SetCursorScreenPos(button_pos); + ImGui::SetNextItemAllowOverlap(); + if (ImGui::Button("##open_google_maps", button_size)) { + open_external_url(google_maps_url); + state->status_text = "Opened Google Maps"; + } + overlay_hovered = ImGui::IsItemHovered(); + draw_list->AddText(ImVec2(button_pos.x + 10.0f, button_pos.y + (button_size.y - text_size.y) * 0.5f), + ImGui::GetColorU32(ImGuiCol_Text), label.c_str()); + } + const bool hovered = canvas_hovered && !overlay_hovered; + if (hovered && ImGui::GetIO().MouseWheel != 0.0f) { + const float next_zoom = std::clamp(static_cast(zoom) + ImGui::GetIO().MouseWheel * MAP_WHEEL_ZOOM_STEP, + static_cast(min_zoom), static_cast(MAP_MAX_ZOOM)); + if (std::abs(next_zoom - zoom) > 1.0e-4f) { + const ImVec2 mouse = ImGui::GetIO().MousePos; + const double mouse_world_x = top_left_x + (mouse.x - rect_min.x); + const double mouse_world_y = top_left_y + (mouse.y - rect_min.y); + const double mouse_lon = world_x_to_lon(mouse_world_x, zoom); + const double mouse_lat = world_y_to_lat(mouse_world_y, zoom); + const double next_center_x = lon_to_world_x(mouse_lon, next_zoom) - (mouse.x - rect_min.x) + rect_width * 0.5; + const double next_center_y = lat_to_world_y(mouse_lat, next_zoom) - (mouse.y - rect_min.y) + rect_height * 0.5; + map_state.zoom = next_zoom; + map_state.center_lon = world_x_to_lon(next_center_x, next_zoom); + map_state.center_lat = world_y_to_lat(next_center_y, next_zoom); + map_state.follow = false; + clamp_map_center(&map_state, map_bounds, size); + } + } + if (hovered && ImGui::IsMouseDragging(ImGuiMouseButton_Left, 2.0f)) { + const ImVec2 delta = ImGui::GetIO().MouseDelta; + const double next_center_x = center_x - delta.x; + const double next_center_y = center_y - delta.y; + map_state.center_lon = world_x_to_lon(next_center_x, zoom); + map_state.center_lat = world_y_to_lat(next_center_y, zoom); + map_state.follow = false; + clamp_map_center(&map_state, map_bounds, size); + } else if (hovered && ImGui::IsMouseReleased(ImGuiMouseButton_Left)) { + const ImVec2 drag_delta = ImGui::GetMouseDragDelta(ImGuiMouseButton_Left); + if (drag_delta.x * drag_delta.x + drag_delta.y * drag_delta.y < 16.0f) { + const ImVec2 mouse = ImGui::GetIO().MousePos; + double best_dist = std::numeric_limits::max(); + double best_time = state->tracker_time; + for (const GpsPoint &point : trace.points) { + const ImVec2 screen = gps_to_screen(point.lat, point.lon, zoom, top_left_x, top_left_y, rect_min); + const double dx = static_cast(screen.x - mouse.x); + const double dy = static_cast(screen.y - mouse.y); + const double dist = dx * dx + dy * dy; + if (dist < best_dist) { + best_dist = dist; + best_time = point.time; + } + } + state->tracker_time = best_time; + state->has_tracker_time = true; + } + ImGui::ResetMouseDragDelta(ImGuiMouseButton_Left); + } + if (double_clicked) { + map_state.initialized = false; + } +} diff --git a/openpilot/tools/jotpluggler/map.h b/openpilot/tools/jotpluggler/map.h new file mode 100644 index 0000000000..97473f1ba9 --- /dev/null +++ b/openpilot/tools/jotpluggler/map.h @@ -0,0 +1,61 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +struct GpsTrace; +struct GeoBounds { + double south = 0.0; + double west = 0.0; + double north = 0.0; + double east = 0.0; + + bool valid() const { + return south < north && west < east; + } +}; + +struct RouteBasemap; +struct MapCacheStats { + uint64_t bytes = 0; + size_t files = 0; +}; + +class MapDataManager { +public: + MapDataManager(); + ~MapDataManager(); + + MapDataManager(const MapDataManager &) = delete; + MapDataManager &operator=(const MapDataManager &) = delete; + + void pump(); + void ensureTrace(const GpsTrace &trace); + void clearCache(); + bool loading() const; + const RouteBasemap *current() const; + MapCacheStats cacheStats() const; + +private: + struct Request { + std::string key; + GeoBounds bounds; + std::string query; + }; + + void run(); + + mutable std::mutex mutex_; + std::condition_variable cv_; + bool stopping_ = false; + std::unique_ptr pending_; + std::unique_ptr active_; + std::unique_ptr completed_; + std::unique_ptr current_; + std::thread worker_; +}; diff --git a/openpilot/tools/jotpluggler/math_eval.py b/openpilot/tools/jotpluggler/math_eval.py new file mode 100755 index 0000000000..a865c88a3a --- /dev/null +++ b/openpilot/tools/jotpluggler/math_eval.py @@ -0,0 +1,145 @@ +#!/usr/bin/env python3 + +import json +import sys +import textwrap +import traceback + +import numpy as np + + +def _load_manifest(path: str) -> dict: + with open(path, encoding="utf-8") as f: + return json.load(f) + + +def _load_vector(path: str) -> np.ndarray: + return np.fromfile(path, dtype=np.float64) + + +def _write_vector(path: str, values: np.ndarray) -> None: + np.asarray(values, dtype=np.float64).tofile(path) + + +def _resample_to_reference(ref_t: np.ndarray, src_t: np.ndarray, src_v: np.ndarray) -> np.ndarray: + ref_t = np.asarray(ref_t, dtype=np.float64).reshape(-1) + src_t = np.asarray(src_t, dtype=np.float64).reshape(-1) + src_v = np.asarray(src_v, dtype=np.float64).reshape(-1) + if ref_t.size == 0 or src_t.size == 0 or src_v.size == 0: + return np.empty_like(ref_t) + indices = np.searchsorted(src_t, ref_t, side="right") - 1 + indices = np.clip(indices, 0, src_v.size - 1) + return src_v[indices] + + +def _evaluate_user_code(code: str, env: dict): + stripped = code.strip() + if not stripped: + raise ValueError("Function body is empty") + + expr = stripped + if expr.startswith("return "): + expr = expr[7:].strip() + try: + return eval(expr, env, env) + except SyntaxError: + pass + + function_src = "def __jotpluggler_eval__():\n" + textwrap.indent(code, " ") + exec(function_src, env, env) + return env["__jotpluggler_eval__"]() + + +def main() -> int: + if len(sys.argv) != 6: + print("usage: math_eval.py ", file=sys.stderr) + return 2 + + manifest_path, globals_path, code_path, out_t_path, out_v_path = sys.argv[1:6] + manifest = _load_manifest(manifest_path) + + series_t = {} + series_v = {} + for entry in manifest.get("series", []): + path = entry["path"] + series_t[path] = _load_vector(entry["t"]) + series_v[path] = _load_vector(entry["v"]) + + first_path = manifest.get("linked_source") or None + + def remember(path: str) -> None: + nonlocal first_path + if first_path is None: + first_path = path + + def t(path: str) -> np.ndarray: + remember(path) + return series_t[path] + + def v(path: str) -> np.ndarray: + remember(path) + return series_v[path] + + additional_sources = list(manifest.get("additional_sources", [])) + linked_source = manifest.get("linked_source") or "" + paths = list(manifest.get("paths", [])) + + env = { + "__builtins__": __builtins__, + "np": np, + "t": t, + "v": v, + "paths": paths, + "linked_source": linked_source, + "additional_sources": additional_sources, + } + + reference_time = None + if linked_source: + reference_time = series_t[linked_source] + env["time"] = reference_time + env["value"] = series_v[linked_source] + + for i, path in enumerate(additional_sources, start=1): + if reference_time is None: + env[f"t{i}"] = series_t[path] + env[f"v{i}"] = series_v[path] + else: + env[f"t{i}"] = reference_time + env[f"v{i}"] = _resample_to_reference(reference_time, series_t[path], series_v[path]) + + with open(globals_path, encoding="utf-8") as f: + globals_code = f.read() + if globals_code.strip(): + exec(globals_code, env, env) + + with open(code_path, encoding="utf-8") as f: + user_code = f.read() + result = _evaluate_user_code(user_code, env) + + if isinstance(result, tuple) and len(result) == 2: + result_t, result_v = result + else: + if first_path is None: + raise ValueError("No reference series found. Set an input timeseries or return (times, values).") + result_t = series_t[first_path] + result_v = result + + result_t = np.asarray(result_t, dtype=np.float64).reshape(-1) + result_v = np.asarray(result_v, dtype=np.float64).reshape(-1) + if result_t.size == 0 or result_v.size == 0: + raise ValueError("Custom series returned an empty result") + if result_t.shape != result_v.shape: + raise ValueError(f"Time/value arrays must have the same shape, got {result_t.shape} and {result_v.shape}") + + _write_vector(out_t_path, result_t) + _write_vector(out_v_path, result_v) + return 0 + + +if __name__ == "__main__": + try: + raise SystemExit(main()) + except Exception as err: + traceback.print_exc() + raise SystemExit(1) from err diff --git a/openpilot/tools/jotpluggler/plot.cc b/openpilot/tools/jotpluggler/plot.cc new file mode 100644 index 0000000000..019eff7070 --- /dev/null +++ b/openpilot/tools/jotpluggler/plot.cc @@ -0,0 +1,936 @@ +#include "tools/jotpluggler/internal.h" + +#include "implot.h" +#include "imgui_internal.h" + +#include +#include +#include + +struct PlotBounds { + double x_min = 0.0; + double x_max = 1.0; + double y_min = 0.0; + double y_max = 1.0; +}; + +bool curve_has_samples(const AppSession &session, const Curve &curve) { + if (curve_has_local_samples(curve)) return true; + if (curve.name.empty() || curve.name.front() != '/') { + return false; + } + const RouteSeries *series = app_find_route_series(session, curve.name); + return series != nullptr && series->times.size() > 1 && series->times.size() == series->values.size(); +} + +void extend_range(const std::vector &values, bool *found, double *min_value, double *max_value) { + if (values.empty()) { + return; + } + const auto [min_it, max_it] = std::minmax_element(values.begin(), values.end()); + if (!*found) { + *min_value = *min_it; + *max_value = *max_it; + *found = true; + return; + } + *min_value = std::min(*min_value, *min_it); + *max_value = std::max(*max_value, *max_it); +} + +void ensure_non_degenerate_range(double *min_value, double *max_value, double pad_fraction, double fallback_pad) { + if (*max_value <= *min_value) { + const double pad = std::max(std::abs(*min_value) * 0.1, fallback_pad); + *min_value -= pad; + *max_value += pad; + return; + } + const double span = *max_value - *min_value; + const double pad = std::max(span * pad_fraction, fallback_pad); + *min_value -= pad; + *max_value += pad; +} + +struct PreparedCurve { + int pane_curve_index = -1; + std::string label; + std::array color = {160, 170, 180}; + float line_weight = 2.0f; + bool stairs = false; + const EnumInfo *enum_info = nullptr; + SeriesFormat display_info; + std::optional legend_value; + std::vector xs; + std::vector ys; +}; + +struct StateBlock { + double t0 = 0.0; + double t1 = 0.0; + int value = 0; + std::string label; +}; + +struct PaneValueFormatContext { + SeriesFormat format; + bool valid = false; +}; + +bool curves_are_bool_like(const std::vector &prepared_curves) { + if (prepared_curves.empty()) { + return false; + } + for (const PreparedCurve &curve : prepared_curves) { + if (!curve.display_info.integer_like || curve.ys.empty()) { + return false; + } + bool found_finite = false; + for (double value : curve.ys) { + if (!std::isfinite(value)) continue; + found_finite = true; + if (std::abs(value) > 0.01 && std::abs(value - 1.0) > 0.01) { + return false; + } + } + if (!found_finite) { + return false; + } + } + return true; +} + +ImU32 state_block_color(int value, float alpha = 1.0f) { + static constexpr std::array, 8> kPalette = {{ + {{111, 143, 175}}, + {{0, 163, 108}}, + {{255, 195, 0}}, + {{199, 0, 57}}, + {{123, 97, 255}}, + {{0, 150, 136}}, + {{214, 48, 49}}, + {{52, 73, 94}}, + }}; + const size_t index = static_cast(std::abs(value)) % kPalette.size(); + return ImGui::GetColorU32(color_rgb(kPalette[index], alpha)); +} + +std::string state_block_label(const PreparedCurve &curve, int value) { + if (curve.enum_info != nullptr && value >= 0 && static_cast(value) < curve.enum_info->names.size()) { + const std::string &name = curve.enum_info->names[static_cast(value)]; + if (!name.empty()) { + return name; + } + } + return std::to_string(value); +} + +std::vector build_state_blocks(const PreparedCurve &curve) { + std::vector blocks; + if (curve.xs.size() < 2 || curve.xs.size() != curve.ys.size()) { + return blocks; + } + + int current_value = static_cast(std::llround(curve.ys.front())); + double start_time = curve.xs.front(); + for (size_t i = 1; i < curve.xs.size(); ++i) { + const int value = static_cast(std::llround(curve.ys[i])); + if (value == current_value) { + continue; + } + const double end_time = curve.xs[i]; + if (end_time > start_time) { + blocks.push_back(StateBlock{ + .t0 = start_time, + .t1 = end_time, + .value = current_value, + .label = state_block_label(curve, current_value), + }); + } + current_value = value; + start_time = end_time; + } + + const double final_time = curve.xs.back(); + if (final_time >= start_time) { + blocks.push_back(StateBlock{ + .t0 = start_time, + .t1 = final_time, + .value = current_value, + .label = state_block_label(curve, current_value), + }); + } + return blocks; +} + +void app_decimate_samples_impl(const std::vector &xs_in, + const std::vector &ys_in, + int max_points, + std::vector *xs_out, + std::vector *ys_out) { + + const size_t bucket_count = std::max(1, static_cast(max_points / 4)); + const size_t bucket_size = std::max( + 1, + static_cast(std::ceil(static_cast(xs_in.size()) / static_cast(bucket_count)))); + xs_out->reserve(bucket_count * 4 + 2); + ys_out->reserve(bucket_count * 4 + 2); + + size_t last_index = std::numeric_limits::max(); + auto append_index = [&](size_t index) { + if (index >= xs_in.size() || index == last_index) { + return; + } + xs_out->push_back(xs_in[index]); + ys_out->push_back(ys_in[index]); + last_index = index; + }; + + for (size_t start = 0; start < xs_in.size(); start += bucket_size) { + const size_t end = std::min(xs_in.size(), start + bucket_size); + size_t min_index = start; + size_t max_index = start; + for (size_t index = start + 1; index < end; ++index) { + if (ys_in[index] < ys_in[min_index]) { + min_index = index; + } + if (ys_in[index] > ys_in[max_index]) { + max_index = index; + } + } + + std::array indices = {start, min_index, max_index, end - 1}; + std::sort(indices.begin(), indices.end()); + for (size_t index : indices) { + append_index(index); + } + } +} + +void app_decimate_samples(const std::vector &xs_in, + const std::vector &ys_in, + int max_points, + std::vector *xs_out, + std::vector *ys_out) { + xs_out->clear(); + ys_out->clear(); + if (xs_in.empty() || xs_in.size() != ys_in.size()) { + return; + } + if (max_points <= 0 || static_cast(xs_in.size()) <= max_points) { + *xs_out = xs_in; + *ys_out = ys_in; + return; + } + app_decimate_samples_impl(xs_in, ys_in, max_points, xs_out, ys_out); +} + +void app_decimate_samples(std::vector &&xs_in, + std::vector &&ys_in, + int max_points, + std::vector *xs_out, + std::vector *ys_out) { + xs_out->clear(); + ys_out->clear(); + if (xs_in.empty() || xs_in.size() != ys_in.size()) { + return; + } + if (max_points <= 0 || static_cast(xs_in.size()) <= max_points) { + *xs_out = std::move(xs_in); + *ys_out = std::move(ys_in); + return; + } + app_decimate_samples_impl(xs_in, ys_in, max_points, xs_out, ys_out); +} + +std::optional app_sample_xy_value_at_time(const std::vector &xs, + const std::vector &ys, + bool stairs, + double tm) { + if (xs.size() < 2 || xs.size() != ys.size()) { + return std::nullopt; + } + if (tm <= xs.front()) return ys.front(); + if (tm >= xs.back()) return ys.back(); + + const auto upper = std::lower_bound(xs.begin(), xs.end(), tm); + if (upper == xs.begin()) return ys.front(); + if (upper == xs.end()) return ys.back(); + + const size_t upper_index = static_cast(std::distance(xs.begin(), upper)); + const size_t lower_index = upper_index - 1; + const double x0 = xs[lower_index]; + const double x1 = xs[upper_index]; + const double y0 = ys[lower_index]; + const double y1 = ys[upper_index]; + if (std::abs(tm - x1) < 1.0e-9) return y1; + if (stairs || x1 <= x0) return y0; + const double alpha = (tm - x0) / (x1 - x0); + return y0 + (y1 - y0) * alpha; +} + +int format_numeric_axis_tick(double value, char *buf, int size, void *user_data) { + const auto *ctx = static_cast(user_data); + if (ctx == nullptr || !ctx->valid) { + return std::snprintf(buf, size, "%.6g", value); + } + if (ctx->format.integer_like) { + const double nearest_int = std::round(value); + if (std::abs(value - nearest_int) > 1.0e-6) { + int decimals = 1; + while (decimals < 4) { + const double scale = std::pow(10.0, decimals); + const double rounded = std::round(value * scale) / scale; + if (std::abs(value - rounded) <= 1.0e-6) { + break; + } + ++decimals; + } + return std::snprintf(buf, size, "%.*f", decimals, value); + } + } + return std::snprintf(buf, size, ctx->format.fmt, value); +} + +void merge_pane_value_format(PaneValueFormatContext *ctx, const SeriesFormat &format) { + if (!ctx->valid) { + ctx->format = format; + ctx->valid = true; + return; + } + ctx->format.has_negative = ctx->format.has_negative || format.has_negative; + ctx->format.digits_before = std::max(ctx->format.digits_before, format.digits_before); + ctx->format.decimals = std::max(ctx->format.decimals, format.decimals); + ctx->format.integer_like = ctx->format.decimals == 0; + const int sign_width = ctx->format.has_negative ? 1 : 0; + const int dot_width = ctx->format.decimals > 0 ? 1 : 0; + ctx->format.total_width = sign_width + ctx->format.digits_before + dot_width + ctx->format.decimals; + std::snprintf(ctx->format.fmt, sizeof(ctx->format.fmt), "%%%d.%df", + ctx->format.total_width, ctx->format.decimals); +} + +std::string curve_legend_label(const PreparedCurve &curve, bool has_cursor_time, size_t label_width) { + if (!has_cursor_time) return curve.label; + if (!curve.legend_value.has_value()) return curve.label; + const std::string value_text = format_display_value(*curve.legend_value, curve.display_info, curve.enum_info); + if (value_text.empty()) return curve.label; + const size_t padded_width = std::max(label_width, curve.label.size()); + return curve.label + std::string(padded_width - curve.label.size() + 2, ' ') + value_text; +} + +bool build_curve_series(const AppSession &session, + const Curve &curve, + const UiState &state, + int max_points, + PreparedCurve *prepared) { + std::vector xs; + std::vector ys; + if (curve_has_local_samples(curve)) { + xs = curve.xs; + ys = curve.ys; + } else { + const RouteSeries *series = app_find_route_series(session, curve.name); + if (series == nullptr || series->times.size() < 2 || series->times.size() != series->values.size()) { + return false; + } + + size_t begin_index = 0; + size_t end_index = series->times.size(); + if (state.has_shared_range && state.x_view_max > state.x_view_min) { + auto begin_it = std::lower_bound(series->times.begin(), series->times.end(), state.x_view_min); + auto end_it = std::upper_bound(series->times.begin(), series->times.end(), state.x_view_max); + begin_index = begin_it == series->times.begin() ? 0 : static_cast(std::distance(series->times.begin(), begin_it - 1)); + end_index = end_it == series->times.end() ? series->times.size() : static_cast(std::distance(series->times.begin(), end_it + 1)); + end_index = std::min(end_index, series->times.size()); + } + if (end_index <= begin_index + 1) return false; + xs.assign(series->times.begin() + begin_index, series->times.begin() + end_index); + ys.assign(series->values.begin() + begin_index, series->values.begin() + end_index); + } + + std::vector transformed_xs; + std::vector transformed_ys; + if (curve.derivative) { + if (xs.size() < 2) return false; + transformed_xs.reserve(xs.size() - 1); + transformed_ys.reserve(ys.size() - 1); + for (size_t i = 1; i < xs.size(); ++i) { + const double dt = curve.derivative_dt > 0.0 ? curve.derivative_dt : (xs[i] - xs[i - 1]); + if (dt <= 0.0) continue; + transformed_xs.push_back(xs[i]); + transformed_ys.push_back((ys[i] - ys[i - 1]) / dt); + } + } else { + transformed_xs = std::move(xs); + transformed_ys = std::move(ys); + } + + if (transformed_xs.size() < 2 || transformed_xs.size() != transformed_ys.size()) { + return false; + } + + for (double &value : transformed_ys) { + value = value * curve.value_scale + curve.value_offset; + } + + prepared->label = app_curve_display_name(curve); + prepared->color = curve.color; + prepared->line_weight = curve.derivative ? 1.8f : 2.25f; + if (!curve.derivative + && curve.value_scale == 1.0 + && curve.value_offset == 0.0 + && !curve_has_local_samples(curve) + && !curve.name.empty() + && curve.name.front() == '/') { + auto it = session.route_data.enum_info.find(curve.name); + if (it != session.route_data.enum_info.end()) { + prepared->enum_info = &it->second; + } + } + if (prepared->enum_info != nullptr) { + prepared->display_info = compute_series_format(transformed_ys, true); + } else if (!curve_has_local_samples(curve) + && !curve.derivative + && curve.value_scale == 1.0 + && curve.value_offset == 0.0 + && !curve.name.empty() + && curve.name.front() == '/') { + auto display_it = session.route_data.series_formats.find(curve.name); + if (display_it != session.route_data.series_formats.end()) { + prepared->display_info = display_it->second; + } else { + prepared->display_info = compute_series_format(transformed_ys, false); + } + } else { + prepared->display_info = compute_series_format(transformed_ys, false); + } + const bool stairs = !curve.derivative && prepared->display_info.integer_like; + if (state.has_tracker_time) { + prepared->legend_value = app_sample_xy_value_at_time(transformed_xs, transformed_ys, stairs, state.tracker_time); + } + if (stairs) { + prepared->xs = std::move(transformed_xs); + prepared->ys = std::move(transformed_ys); + } else { + app_decimate_samples(std::move(transformed_xs), std::move(transformed_ys), max_points, &prepared->xs, &prepared->ys); + } + prepared->stairs = stairs; + return prepared->xs.size() > 1 && prepared->xs.size() == prepared->ys.size(); +} + +bool draw_pane_close_button_overlay() { + const ImVec2 window_pos = ImGui::GetWindowPos(); + const ImVec2 content_min = ImGui::GetWindowContentRegionMin(); + const ImVec2 content_max = ImGui::GetWindowContentRegionMax(); + const ImRect rect(ImVec2(window_pos.x + content_max.x - 42.0f, window_pos.y + content_min.y + 4.0f), + ImVec2(window_pos.x + content_max.x - 4.0f, window_pos.y + content_min.y + 42.0f)); + const bool hovered = ImGui::IsMouseHoveringRect(rect.Min, rect.Max, false); + const bool held = hovered && ImGui::IsMouseDown(ImGuiMouseButton_Left); + if (hovered) { + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + } + ImDrawList *draw_list = ImGui::GetWindowDrawList(); + const float pad = 11.0f; + const ImU32 color = hovered || held + ? ImGui::GetColorU32(color_rgb(72, 79, 88)) + : ImGui::GetColorU32(color_rgb(138, 146, 156)); + draw_list->AddLine(ImVec2(rect.Min.x + pad, rect.Min.y + pad), + ImVec2(rect.Max.x - pad, rect.Max.y - pad), + color, + 2.4f); + draw_list->AddLine(ImVec2(rect.Min.x + pad, rect.Max.y - pad), + ImVec2(rect.Max.x - pad, rect.Min.y + pad), + color, + 2.4f); + return hovered && ImGui::IsMouseClicked(ImGuiMouseButton_Left); +} + +void draw_pane_frame_overlay() { + const ImVec2 window_pos = ImGui::GetWindowPos(); + const ImVec2 content_min = ImGui::GetWindowContentRegionMin(); + const ImVec2 content_max = ImGui::GetWindowContentRegionMax(); + const ImRect frame_rect(ImVec2(window_pos.x + content_min.x, window_pos.y + content_min.y), + ImVec2(window_pos.x + content_max.x, window_pos.y + content_max.y)); + ImGui::GetWindowDrawList()->AddRect(frame_rect.Min, + frame_rect.Max, + ImGui::GetColorU32(color_rgb(186, 190, 196)), + 0.0f, + 0, + 1.0f); +} + +PlotBounds compute_plot_bounds(const Pane &pane, + const std::vector &prepared_curves, + const UiState &state) { + PlotBounds bounds; + bounds.x_min = state.has_shared_range ? state.x_view_min : 0.0; + bounds.x_max = state.has_shared_range ? state.x_view_max : 1.0; + if (bounds.x_max <= bounds.x_min) { + bounds.x_max = bounds.x_min + 1.0; + } + + bool found = false; + double min_value = 0.0; + double max_value = 1.0; + for (const PreparedCurve &curve : prepared_curves) { + extend_range(curve.ys, &found, &min_value, &max_value); + } + if (!found) { + min_value = 0.0; + max_value = 1.0; + } + if (curves_are_bool_like(prepared_curves)) { + min_value = std::min(min_value, 0.0); + max_value = std::max(max_value, 1.0); + } + ensure_non_degenerate_range(&min_value, &max_value, PLOT_Y_PADDING_FRACTION, 0.1); + if (pane.range.has_y_limit_min) { + min_value = pane.range.y_limit_min; + } + if (pane.range.has_y_limit_max) { + max_value = pane.range.y_limit_max; + } + ensure_non_degenerate_range(&min_value, &max_value, 0.0, 0.1); + bounds.y_min = min_value; + bounds.y_max = max_value; + return bounds; +} + +void draw_state_blocks_pane(const std::vector &prepared_curves, UiState *state) { + if (prepared_curves.empty() || !state->has_shared_range || state->x_view_max <= state->x_view_min) { + return; + } + + ImDrawList *draw_list = ImPlot::GetPlotDrawList(); + const ImVec2 plot_min = ImPlot::GetPlotPos(); + const ImVec2 plot_size = ImPlot::GetPlotSize(); + const int curve_count = static_cast(prepared_curves.size()); + if (plot_size.x <= 2.0f || plot_size.y <= 2.0f || curve_count <= 0) { + return; + } + + float label_width = 0.0f; + if (curve_count > 1) { + for (const PreparedCurve &curve : prepared_curves) { + label_width = std::max(label_width, ImGui::CalcTextSize(curve.label.c_str()).x); + } + label_width = std::clamp(label_width + 14.0f, 72.0f, std::min(160.0f, plot_size.x * 0.35f)); + } + + const float row_height = plot_size.y / static_cast(curve_count); + const float blocks_min_x = plot_min.x + label_width; + const float blocks_max_x = plot_min.x + plot_size.x; + const float blocks_width = std::max(1.0f, blocks_max_x - blocks_min_x); + const double x_span = std::max(1.0e-9, state->x_view_max - state->x_view_min); + + struct HoveredBlock { + int curve_index = -1; + StateBlock block; + }; + std::optional hovered; + + const ImVec2 mouse_pos = ImGui::GetMousePos(); + const bool plot_hovered = ImPlot::IsPlotHovered(); + + for (int curve_index = 0; curve_index < curve_count; ++curve_index) { + const PreparedCurve &curve = prepared_curves[static_cast(curve_index)]; + const float y0 = plot_min.y + row_height * static_cast(curve_index); + const float y1 = y0 + row_height; + const std::vector blocks = build_state_blocks(curve); + + if (curve_index > 0) { + draw_list->AddLine(ImVec2(plot_min.x, y0), ImVec2(plot_min.x + plot_size.x, y0), + IM_COL32(210, 214, 220, 255), 1.0f); + } + if (curve_count > 1) { + draw_list->AddLine(ImVec2(blocks_min_x, y0), ImVec2(blocks_min_x, y1), + IM_COL32(210, 214, 220, 255), 1.0f); + const float label_left = plot_min.x + 6.0f; + const float label_right = std::max(label_left + 12.0f, blocks_min_x - 6.0f); + ImGui::PushStyleColor(ImGuiCol_Text, color_rgb(120, 128, 138)); + ImGui::RenderTextEllipsis(draw_list, + ImVec2(label_left, y0 + 4.0f), + ImVec2(label_right, y1 - 4.0f), + label_right, + curve.label.c_str(), + nullptr, + nullptr); + ImGui::PopStyleColor(); + } + + for (const StateBlock &block : blocks) { + const double visible_t0 = std::max(block.t0, state->x_view_min); + const double visible_t1 = std::min(block.t1, state->x_view_max); + if (visible_t1 <= visible_t0) { + continue; + } + const float x0 = blocks_min_x + static_cast((visible_t0 - state->x_view_min) / x_span) * blocks_width; + const float x1 = blocks_min_x + static_cast((visible_t1 - state->x_view_min) / x_span) * blocks_width; + const ImU32 fill_color = state_block_color(block.value, 0.15f); + const ImU32 line_color = state_block_color(block.value, 0.90f); + draw_list->AddRectFilled(ImVec2(x0, y0), ImVec2(std::max(x1, x0 + 1.0f), y1), fill_color); + draw_list->AddLine(ImVec2(x0, y0), ImVec2(x0, y1), line_color, 2.0f); + + const float block_width = x1 - x0; + if (block_width > 14.0f) { + const float text_left = x0 + 6.0f; + const float text_right = x1 - 6.0f; + if (text_right > text_left) { + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::ColorConvertU32ToFloat4(state_block_color(block.value, 0.80f))); + ImGui::RenderTextEllipsis(draw_list, + ImVec2(text_left, y0 + 4.0f), + ImVec2(text_right, y1 - 4.0f), + text_right, + block.label.c_str(), + nullptr, + nullptr); + ImGui::PopStyleColor(); + } + } + + if (plot_hovered && mouse_pos.x >= blocks_min_x && mouse_pos.x <= blocks_max_x && mouse_pos.y >= y0 && mouse_pos.y <= y1) { + const double hover_time = state->x_view_min + static_cast((mouse_pos.x - blocks_min_x) / blocks_width) * x_span; + if (hover_time >= block.t0 && hover_time <= block.t1) { + hovered = HoveredBlock{ + .curve_index = curve_index, + .block = block, + }; + } + } + } + } + + if (hovered.has_value()) { + const HoveredBlock &info = *hovered; + ImGui::BeginTooltip(); + if (curve_count > 1) { + ImGui::Text("%s: %s (%d)", prepared_curves[static_cast(info.curve_index)].label.c_str(), + info.block.label.c_str(), info.block.value); + } else { + ImGui::Text("%s (%d)", info.block.label.c_str(), info.block.value); + } + ImGui::Separator(); + ImGui::Text("%.3fs -> %.3fs", info.block.t0, info.block.t1); + ImGui::Text("duration: %.3fs", info.block.t1 - info.block.t0); + ImGui::EndTooltip(); + } +} + +void persist_shared_range_to_tab(WorkspaceTab *tab, const UiState &state) { + if (tab == nullptr || !state.has_shared_range) { + return; + } + const double x_min = state.x_view_min; + const double x_max = state.x_view_max > state.x_view_min ? state.x_view_max : state.x_view_min + 1.0; + for (Pane &pane : tab->panes) { + pane.range.valid = true; + pane.range.left = x_min; + pane.range.right = x_max; + } +} + +void clear_pane_vertical_limits(Pane *pane) { + if (pane == nullptr) { + return; + } + pane->range.has_y_limit_min = false; + pane->range.has_y_limit_max = false; +} + +PlotBounds current_plot_bounds_for_pane(const AppSession &session, const Pane &pane, const UiState &state) { + std::vector prepared_curves; + prepared_curves.reserve(pane.curves.size()); + constexpr int kAxisEditorMaxPoints = 2048; + for (size_t curve_index = 0; curve_index < pane.curves.size(); ++curve_index) { + const Curve &curve = pane.curves[curve_index]; + if (!curve.visible || !curve_has_samples(session, curve)) continue; + PreparedCurve prepared; + if (build_curve_series(session, curve, state, kAxisEditorMaxPoints, &prepared)) { + prepared.pane_curve_index = static_cast(curve_index); + prepared_curves.push_back(std::move(prepared)); + } + } + return compute_plot_bounds(pane, prepared_curves, state); +} + +void open_axis_limits_editor(const AppSession &session, UiState *state, int pane_index) { + ensure_shared_range(state, session); + clamp_shared_range(state, session); + const WorkspaceTab *tab = app_active_tab(session.layout, *state); + if (tab == nullptr || pane_index < 0 || pane_index >= static_cast(tab->panes.size())) { + return; + } + + const Pane &pane = tab->panes[static_cast(pane_index)]; + const PlotBounds bounds = current_plot_bounds_for_pane(session, pane, *state); + AxisLimitsEditorState &editor = state->axis_limits; + editor.open = true; + editor.pane_index = pane_index; + editor.x_min = state->x_view_min; + editor.x_max = state->x_view_max; + editor.y_min_enabled = pane.range.has_y_limit_min; + editor.y_max_enabled = pane.range.has_y_limit_max; + editor.y_min = pane.range.has_y_limit_min ? pane.range.y_limit_min : bounds.y_min; + editor.y_max = pane.range.has_y_limit_max ? pane.range.y_limit_max : bounds.y_max; +} + +bool apply_axis_limits_editor(AppSession *session, UiState *state) { + WorkspaceTab *tab = app_active_tab(&session->layout, *state); + if (tab == nullptr) return false; + + AxisLimitsEditorState &editor = state->axis_limits; + if (editor.pane_index < 0 || editor.pane_index >= static_cast(tab->panes.size())) { + state->error_text = "The selected pane is no longer available."; + state->open_error_popup = true; + return false; + } + if (!std::isfinite(editor.x_min) || !std::isfinite(editor.x_max)) { + state->error_text = "Axis limits must be finite numbers."; + state->open_error_popup = true; + return false; + } + if (editor.x_max <= editor.x_min) { + state->error_text = "X max must be greater than X min."; + state->open_error_popup = true; + return false; + } + if (editor.y_min_enabled && !std::isfinite(editor.y_min)) { + state->error_text = "Y min must be a finite number."; + state->open_error_popup = true; + return false; + } + if (editor.y_max_enabled && !std::isfinite(editor.y_max)) { + state->error_text = "Y max must be a finite number."; + state->open_error_popup = true; + return false; + } + if (editor.y_min_enabled && editor.y_max_enabled && editor.y_max <= editor.y_min) { + state->error_text = "Y max must be greater than Y min."; + state->open_error_popup = true; + return false; + } + + const SketchLayout before_layout = session->layout; + state->has_shared_range = true; + state->x_view_min = editor.x_min; + state->x_view_max = editor.x_max; + if (session->data_mode == SessionDataMode::Stream) { + state->follow_latest = infer_stream_follow_state(*state, *session); + } else { + state->follow_latest = false; + } + state->suppress_range_side_effects = true; + clamp_shared_range(state, *session); + persist_shared_range_to_tab(tab, *state); + + Pane &pane = tab->panes[static_cast(editor.pane_index)]; + pane.range.has_y_limit_min = editor.y_min_enabled; + pane.range.has_y_limit_max = editor.y_max_enabled; + if (editor.y_min_enabled) { + pane.range.y_limit_min = editor.y_min; + } + if (editor.y_max_enabled) { + pane.range.y_limit_max = editor.y_max; + } + + const PlotBounds bounds = current_plot_bounds_for_pane(*session, pane, *state); + pane.range.valid = true; + pane.range.left = state->x_view_min; + pane.range.right = state->x_view_max; + pane.range.bottom = bounds.y_min; + pane.range.top = bounds.y_max; + + state->undo.push(before_layout); + const bool ok = mark_layout_dirty(session, state); + if (ok) { + state->status_text = "Axis limits updated"; + } + return ok; +} + +void draw_plot(const AppSession &session, Pane *pane, UiState *state) { + std::vector prepared_curves; + prepared_curves.reserve(pane->curves.size()); + const int max_points = std::max(256, static_cast(ImGui::GetContentRegionAvail().x) * 2); + for (size_t curve_index = 0; curve_index < pane->curves.size(); ++curve_index) { + const Curve &curve = pane->curves[curve_index]; + if (!curve.visible || !curve_has_samples(session, curve)) continue; + PreparedCurve prepared; + if (build_curve_series(session, curve, *state, max_points, &prepared)) { + prepared.pane_curve_index = static_cast(curve_index); + prepared_curves.push_back(std::move(prepared)); + } + } + + const PlotBounds bounds = compute_plot_bounds(*pane, prepared_curves, *state); + PaneValueFormatContext pane_value_format; + bool state_block_mode = !prepared_curves.empty(); + size_t max_legend_label_width = 0; + for (const PreparedCurve &curve : prepared_curves) { + max_legend_label_width = std::max(max_legend_label_width, curve.label.size()); + if (curve.enum_info == nullptr) { + state_block_mode = false; + merge_pane_value_format(&pane_value_format, curve.display_info); + } + } + const int supported_count = static_cast(prepared_curves.size()); + const ImVec2 plot_size = ImGui::GetContentRegionAvail(); + const bool has_cursor_time = state->has_tracker_time; + const double cursor_time = state->tracker_time; + + ImPlot::PushStyleColor(ImPlotCol_PlotBg, color_rgb(255, 255, 255)); + ImPlot::PushStyleColor(ImPlotCol_PlotBorder, color_rgb(186, 190, 196)); + ImPlot::PushStyleColor(ImPlotCol_LegendBg, color_rgb(248, 249, 251, 0.92f)); + ImPlot::PushStyleColor(ImPlotCol_LegendBorder, color_rgb(168, 175, 184)); + ImPlot::PushStyleColor(ImPlotCol_LegendText, color_rgb(57, 62, 69)); + ImPlot::PushStyleColor(ImPlotCol_TitleText, color_rgb(57, 62, 69)); + ImPlot::PushStyleColor(ImPlotCol_InlayText, color_rgb(95, 103, 112)); + ImPlot::PushStyleColor(ImPlotCol_AxisGrid, color_rgb(188, 196, 206)); + ImPlot::PushStyleColor(ImPlotCol_AxisText, color_rgb(95, 103, 112)); + ImPlot::PushStyleColor(ImPlotCol_AxisBg, color_rgb(255, 255, 255, 0.0f)); + ImPlot::PushStyleColor(ImPlotCol_AxisBgHovered, color_rgb(214, 220, 228, 0.45f)); + ImPlot::PushStyleColor(ImPlotCol_AxisBgActive, color_rgb(199, 209, 222, 0.55f)); + ImPlot::PushStyleColor(ImPlotCol_Selection, color_rgb(252, 211, 77, 0.28f)); + ImPlot::PushStyleColor(ImPlotCol_Crosshairs, color_rgb(120, 128, 138, 0.70f)); + ImPlot::PushStyleVar(ImPlotStyleVar_LegendPadding, ImVec2(56.0f, 10.0f)); + + ImPlotFlags plot_flags = ImPlotFlags_NoTitle | ImPlotFlags_NoMenus; + if (state_block_mode) { + plot_flags |= ImPlotFlags_NoLegend | ImPlotFlags_NoMouseText; + } + if (supported_count == 0) { + plot_flags |= ImPlotFlags_NoLegend; + } + + const ImPlotAxisFlags x_axis_flags = ImPlotAxisFlags_NoMenus | ImPlotAxisFlags_NoHighlight; + ImPlotAxisFlags y_axis_flags = ImPlotAxisFlags_NoMenus | ImPlotAxisFlags_NoHighlight; + if (state_block_mode) { + y_axis_flags |= ImPlotAxisFlags_NoDecorations; + } + const bool explicit_y = pane->range.has_y_limit_min || pane->range.has_y_limit_max; + if (!state_block_mode && !explicit_y && supported_count > 0) { + y_axis_flags |= ImPlotAxisFlags_AutoFit | ImPlotAxisFlags_RangeFit; + } + + const double previous_x_min = state->x_view_min; + const double previous_x_max = state->x_view_max; + app_push_mono_font(); + if (ImPlot::BeginPlot("##plot", plot_size, plot_flags)) { + ImPlot::SetupAxes(nullptr, nullptr, x_axis_flags, y_axis_flags); + ImPlot::SetupAxisFormat(ImAxis_X1, "%.1f"); + if (state_block_mode) { + ImPlot::SetupAxisLimits(ImAxis_Y1, 0.0, 1.0, ImPlotCond_Always); + } else if (pane_value_format.valid) { + ImPlot::SetupAxisFormat(ImAxis_Y1, format_numeric_axis_tick, &pane_value_format); + } else { + ImPlot::SetupAxisFormat(ImAxis_Y1, "%.6g"); + } + ImPlot::SetupAxisLinks(ImAxis_X1, &state->x_view_min, &state->x_view_max); + if (state->route_x_max > state->route_x_min) { + const double x_constraint_min = session.data_mode == SessionDataMode::Stream + ? state->route_x_min - std::max(MIN_HORIZONTAL_ZOOM_SECONDS, session.stream_buffer_seconds) + : state->route_x_min; + ImPlot::SetupAxisLimitsConstraints(ImAxis_X1, x_constraint_min, state->route_x_max); + } + if (!state_block_mode) { + ImPlot::SetupMouseText(ImPlotLocation_SouthEast, ImPlotMouseTextFlags_NoAuxAxes); + } + if (!state_block_mode && (explicit_y || supported_count == 0)) { + ImPlot::SetupAxisLimits(ImAxis_Y1, bounds.y_min, bounds.y_max, ImPlotCond_Always); + } + if (!state_block_mode && supported_count > 0) { + ImPlot::SetupLegend(ImPlotLocation_NorthEast); + } + + if (state_block_mode) { + draw_state_blocks_pane(prepared_curves, state); + } else { + for (size_t i = 0; i < prepared_curves.size(); ++i) { + const PreparedCurve &curve = prepared_curves[i]; + std::string series_id = curve_legend_label(curve, has_cursor_time, max_legend_label_width) + "###curve" + std::to_string(curve.pane_curve_index); + ImPlotSpec spec; + spec.LineColor = color_rgb(curve.color); + spec.LineWeight = curve.line_weight; + spec.Flags = ImPlotLineFlags_SkipNaN; + if (!curve.xs.empty() && curve.xs.size() == curve.ys.size()) { + if (curve.stairs) { + spec.Flags = ImPlotStairsFlags_PreStep; + ImPlot::PlotStairs(series_id.c_str(), curve.xs.data(), curve.ys.data(), static_cast(curve.xs.size()), spec); + } else { + ImPlot::PlotLine(series_id.c_str(), curve.xs.data(), curve.ys.data(), static_cast(curve.xs.size()), spec); + } + } + } + } + if (has_cursor_time) { + const double clamped_cursor_time = std::clamp(cursor_time, state->route_x_min, state->route_x_max); + ImPlotSpec cursor_spec; + cursor_spec.LineColor = color_rgb(108, 118, 128, 0.7f); + cursor_spec.LineWeight = 1.0f; + cursor_spec.Flags = ImPlotItemFlags_NoLegend; + ImPlot::PlotInfLines("##tracker_cursor", &clamped_cursor_time, 1, cursor_spec); + } + if (ImPlot::IsPlotHovered() && ImGui::IsMouseClicked(ImGuiMouseButton_Left)) { + state->tracker_time = std::clamp(ImPlot::GetPlotMousePos().x, state->route_x_min, state->route_x_max); + state->has_tracker_time = true; + } + ImPlot::EndPlot(); + } + app_pop_mono_font(); + clamp_shared_range(state, session); + if (std::abs(state->x_view_min - previous_x_min) > 1.0e-6 + || std::abs(state->x_view_max - previous_x_max) > 1.0e-6) { + if (!state->suppress_range_side_effects) { + if (session.data_mode == SessionDataMode::Stream) { + state->follow_latest = infer_stream_follow_state(*state, session); + } else { + state->follow_latest = false; + } + } + } + ImPlot::PopStyleVar(); + ImPlot::PopStyleColor(12); +} + +std::optional draw_pane_context_menu(const WorkspaceTab &tab, int pane_index) { + if (!ImGui::BeginPopupContextWindow("##pane_context")) return std::nullopt; + + PaneMenuAction action; + action.pane_index = pane_index; + const Pane *pane = pane_index >= 0 && pane_index < static_cast(tab.panes.size()) + ? &tab.panes[static_cast(pane_index)] + : nullptr; + const bool has_curves = pane_index >= 0 + && pane_index < static_cast(tab.panes.size()) + && !tab.panes[static_cast(pane_index)].curves.empty(); + const bool is_plot = pane != nullptr && pane->kind == PaneKind::Plot; + if (icon_menu_item(icon::SLIDERS, "Edit Axis Limits...", nullptr, false, is_plot)) { + action.kind = PaneMenuActionKind::OpenAxisLimits; + } + icon_menu_item(icon::PALETTE, "Edit Curve Style...", nullptr, false, false && is_plot); + if (action.kind == PaneMenuActionKind::None + && icon_menu_item(icon::PLUS_SLASH_MINUS, "Apply filter to data...", nullptr, false, has_curves && is_plot)) { + action.kind = PaneMenuActionKind::OpenCustomSeries; + } + ImGui::Separator(); + if (action.kind == PaneMenuActionKind::None && icon_menu_item(icon::DISTRIBUTE_HORIZONTAL, "Split Left / Right")) { + action.kind = PaneMenuActionKind::SplitRight; + } else if (action.kind == PaneMenuActionKind::None + && icon_menu_item(icon::DISTRIBUTE_VERTICAL, "Split Top / Bottom")) { + action.kind = PaneMenuActionKind::SplitBottom; + } + ImGui::Separator(); + if (icon_menu_item(icon::ZOOM_OUT, "Zoom Out", nullptr, false, is_plot)) { + action.kind = PaneMenuActionKind::ResetView; + } + ImGui::Separator(); + if (icon_menu_item(icon::TRASH, "Remove ALL curves", nullptr, false, is_plot)) { + action.kind = PaneMenuActionKind::Clear; + } + ImGui::Separator(); + icon_menu_item(icon::FILE_EARMARK_IMAGE, "Copy image to clipboard", nullptr, false, false); + icon_menu_item(icon::SAVE, "Save plot to file", nullptr, false, false); + icon_menu_item(icon::BAR_CHART, "Show data statistics", nullptr, false, false); + ImGui::EndPopup(); + if (action.kind == PaneMenuActionKind::None) return std::nullopt; + return action; +} diff --git a/openpilot/tools/jotpluggler/render.cc b/openpilot/tools/jotpluggler/render.cc new file mode 100644 index 0000000000..54f0c16cc3 --- /dev/null +++ b/openpilot/tools/jotpluggler/render.cc @@ -0,0 +1,173 @@ +#include "tools/jotpluggler/internal.h" + +#include "imgui_impl_glfw.h" +#include "imgui_impl_opengl3.h" +#include "imgui_impl_opengl3_loader.h" + +#include + +namespace fs = std::filesystem; + +void draw_fps_overlay(const UiState &state, float top_offset) { + if (!state.show_fps_overlay) { + return; + } + ImGuiViewport *viewport = ImGui::GetMainViewport(); + const ImGuiIO &io = ImGui::GetIO(); + const float fps = io.Framerate; + const std::string label = util::string_format("%.1f fps", fps); + + const ImVec2 padding(10.0f, 8.0f); + const ImVec2 margin(12.0f, 10.0f); + app_push_mono_font(); + ImFont *font = ImGui::GetFont(); + const float font_size = ImGui::GetFontSize(); + const ImVec2 text_size = ImGui::CalcTextSize(label.c_str()); + app_pop_mono_font(); + const ImVec2 size(text_size.x + padding.x * 2.0f, text_size.y + padding.y * 2.0f); + const ImVec2 pos(viewport->Pos.x + viewport->Size.x - size.x - margin.x, + viewport->Pos.y + top_offset + margin.y); + ImDrawList *draw_list = ImGui::GetForegroundDrawList(viewport); + const ImVec2 max(pos.x + size.x, pos.y + size.y); + draw_list->AddRectFilled(pos, max, ImGui::GetColorU32(color_rgb(248, 249, 251, 0.92f)), 4.0f); + draw_list->AddRect(pos, max, ImGui::GetColorU32(color_rgb(182, 188, 196, 0.95f)), 4.0f); + draw_list->AddText(font, font_size, ImVec2(pos.x + padding.x, pos.y + padding.y), + ImGui::GetColorU32(color_rgb(57, 62, 69)), label.c_str(), nullptr); +} + +void render_layout(AppSession *session, UiState *state, bool show_camera_feed) { + if (!state->fps_overlay_initialized) { + state->show_fps_overlay = false; + state->fps_overlay_initialized = true; + } + ensure_shared_range(state, *session); + if (state->follow_latest) { + update_follow_range(state, *session); + state->suppress_range_side_effects = true; + } else { + clamp_shared_range(state, *session); + } + const bool ctrl = ImGui::GetIO().KeyCtrl || ImGui::GetIO().KeySuper; + const bool shift = ImGui::GetIO().KeyShift; + if (!ImGui::GetIO().WantTextInput && ctrl && ImGui::IsKeyPressed(ImGuiKey_Z, false)) { + if (shift) { + apply_redo(session, state); + } else { + apply_undo(session, state); + } + } + if (!ImGui::GetIO().WantTextInput && ctrl && ImGui::IsKeyPressed(ImGuiKey_F, false)) { + state->open_find_signal = true; + } + if (ImGui::IsKeyPressed(ImGuiKey_LeftArrow, false)) { + step_tracker(state, -1.0); + } + if (ImGui::IsKeyPressed(ImGuiKey_RightArrow, false)) { + step_tracker(state, 1.0); + } + if (!ImGui::GetIO().WantTextInput && ImGui::IsKeyPressed(ImGuiKey_Space, false)) { + state->playback_playing = !state->playback_playing; + } + advance_playback(state, *session); + CameraFeedView *sidebar_camera = session->pane_camera_feeds[static_cast(sidebar_preview_camera_view(*session))].get(); + if (show_camera_feed && sidebar_camera != nullptr && state->has_tracker_time) { + sidebar_camera->update(state->tracker_time); + } + const float menu_height = draw_main_menu_bar(session, state); + UiMetrics ui = compute_ui_metrics(ImGui::GetMainViewport()->Size, menu_height, state->sidebar_width); + if (state->browser_nodes_dirty) { + rebuild_browser_nodes(session, state); + state->browser_nodes_dirty = false; + } + state->sidebar_width = ui.sidebar_width; + draw_sidebar(session, ui, state, show_camera_feed); + draw_workspace(session, ui, state); + draw_sidebar_resizer(ui, state); + if (!state->custom_series.selected && !state->logs.selected) { + draw_pane_windows(session, state); + } + draw_status_bar(*session, ui, state); + draw_popups(session, state); + draw_fps_overlay(*state, menu_height); +} + +void save_framebuffer_png(const fs::path &output_path, int width, int height) { + ensure_parent_dir(output_path); + if (width <= 0 || height <= 0) throw std::runtime_error("Invalid framebuffer size"); + + std::vector pixels(static_cast(width) * static_cast(height) * 4U, 0); + glPixelStorei(GL_PACK_ALIGNMENT, 1); + glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels.data()); + + const fs::path ppm_path = output_path.parent_path() / (output_path.stem().string() + ".ppm"); + std::string ppm = util::string_format("P6\n%d %d\n255\n", width, height); + ppm.reserve(ppm.size() + static_cast(width) * static_cast(height) * 3U); + for (int y = height - 1; y >= 0; --y) { + for (int x = 0; x < width; ++x) { + const size_t index = static_cast((y * width + x) * 4); + ppm.append(reinterpret_cast(&pixels[index]), 3); + } + } + write_file_or_throw(ppm_path, ppm.data(), ppm.size()); + + const std::string command = "convert " + shell_quote(ppm_path.string()) + " " + shell_quote(output_path.string()); + run_system_or_throw(command, "image conversion"); + fs::remove(ppm_path); +} + +void render_frame(GLFWwindow *window, AppSession *session, UiState *state, const fs::path *capture_path) { + glfwPollEvents(); + + int framebuffer_width = 0; + int framebuffer_height = 0; + glfwGetFramebufferSize(window, &framebuffer_width, &framebuffer_height); + + ImGui_ImplOpenGL3_NewFrame(); + ImGui_ImplGlfw_NewFrame(); + ImGui::NewFrame(); + + if (state->request_save_layout) { + if (session->layout_path.empty()) { + state->open_save_layout = true; + } else { + save_layout(session, state, session->layout_path.string()); + } + state->request_save_layout = false; + } + if (state->request_reset_layout) { + reset_layout(session, state); + state->request_reset_layout = false; + } + poll_async_route_load(session, state); + if (session->data_mode == SessionDataMode::Stream && session->stream_poller) { + StreamExtractBatch batch; + std::string error_text; + if (session->stream_poller->consume(&batch, &error_text)) { + if (!error_text.empty()) { + state->error_text = error_text; + state->open_error_popup = true; + state->status_text = "Stream disconnected"; + } else { + apply_stream_batch(session, state, std::move(batch)); + } + } + } + + const bool show_camera = capture_path == nullptr && session->data_mode != SessionDataMode::Stream; + render_layout(session, state, show_camera); + ImGui::Render(); + if (state->request_close) { + glfwSetWindowShouldClose(window, GLFW_TRUE); + state->request_close = false; + } + + glViewport(0, 0, framebuffer_width, framebuffer_height); + glClearColor(227.0f / 255.0f, 229.0f / 255.0f, 233.0f / 255.0f, 1.0f); + glClear(GL_COLOR_BUFFER_BIT); + ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); + if (capture_path != nullptr) { + save_framebuffer_png(*capture_path, framebuffer_width, framebuffer_height); + } + glfwSwapBuffers(window); + state->suppress_range_side_effects = false; +} diff --git a/openpilot/tools/jotpluggler/runtime.cc b/openpilot/tools/jotpluggler/runtime.cc new file mode 100644 index 0000000000..a1e47c7e8e --- /dev/null +++ b/openpilot/tools/jotpluggler/runtime.cc @@ -0,0 +1,1277 @@ +#include "tools/jotpluggler/app.h" +#include "tools/jotpluggler/common.h" + +#include "openpilot/cereal/services.h" +#include "common/timing.h" +#include "imgui_impl_glfw.h" +#include "imgui_impl_opengl3.h" +#include "imgui_impl_opengl3_loader.h" +#include "implot.h" +#include "common/yuv.h" +#include "msgq_repo/msgq/ipc.h" +#include "tools/replay/framereader.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "system/camerad/cameras/nv12_info.h" + +namespace { + +std::atomic g_glfw_alive{false}; +const bool kLogCameraTimings = env_flag_enabled("JOTP_CAMERA_TIMINGS"); + +CameraType decoder_camera_type(CameraViewKind view) { + switch (view) { + case CameraViewKind::Driver: return DriverCam; + case CameraViewKind::WideRoad: return WideRoadCam; + case CameraViewKind::QRoad: return RoadCam; + case CameraViewKind::Road: + default: return RoadCam; + } +} + +bool stream_batch_has_data(const StreamExtractBatch &batch) { + return !batch.series.empty() + || !batch.can_messages.empty() + || !batch.logs.empty() + || !batch.timeline.empty() + || !batch.enum_info.empty() + || !batch.car_fingerprint.empty() + || !batch.dbc_name.empty(); +} + +bool should_subscribe_stream_service(const std::string &name) { + static const std::array kSkippedServices = {{ + "roadEncodeIdx", + "driverEncodeIdx", + "wideRoadEncodeIdx", + "qRoadEncodeIdx", + "roadEncodeData", + "driverEncodeData", + "wideRoadEncodeData", + "qRoadEncodeData", + "livestreamWideRoadEncodeIdx", + "livestreamRoadEncodeIdx", + "livestreamDriverEncodeIdx", + "thumbnail", + }}; + if (name == "rawAudioData") return false; + for (std::string_view skipped : kSkippedServices) { + if (name == skipped) return false; + } + return true; +} + +void glfw_error_callback(int error, const char *description) { + const std::string_view desc = description != nullptr ? description : "unknown"; + if (error == 65539 && desc.find("Invalid window attribute 0x0002000D") != std::string_view::npos) { + return; + } + std::cerr << "GLFW error " << error << ": " << desc << "\n"; +} + +} // namespace + +GlfwRuntime::GlfwRuntime(const Options &options) { + glfwSetErrorCallback(glfw_error_callback); + if (!glfwInit()) throw std::runtime_error("glfwInit failed"); + g_glfw_alive.store(true); + + glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); + glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); + glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); +#ifdef __APPLE__ + glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE); +#endif + const bool fixed_size = !options.show; + glfwWindowHint(GLFW_RESIZABLE, fixed_size ? GLFW_FALSE : GLFW_TRUE); + glfwWindowHint(GLFW_VISIBLE, options.show ? GLFW_TRUE : GLFW_FALSE); + + window_ = glfwCreateWindow(options.width, options.height, "jotpluggler", nullptr, nullptr); + if (window_ == nullptr) { + glfwTerminate(); + throw std::runtime_error("glfwCreateWindow failed"); + } + + if (fixed_size) { + glfwSetWindowSizeLimits(window_, options.width, options.height, options.width, options.height); + } + glfwMakeContextCurrent(window_); + glfwSwapInterval(options.show ? 1 : 0); +} + +GlfwRuntime::~GlfwRuntime() { + if (window_ != nullptr) { + glfwDestroyWindow(window_); + } + g_glfw_alive.store(false); + glfwTerminate(); +} + +GLFWwindow *GlfwRuntime::window() const { + return window_; +} + +ImGuiRuntime::ImGuiRuntime(GLFWwindow *window) { + IMGUI_CHECKVERSION(); + ImGui::CreateContext(); + ImPlot::CreateContext(); + + ImGuiIO &io = ImGui::GetIO(); + io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; + io.IniFilename = nullptr; + io.LogFilename = nullptr; + + if (!ImGui_ImplGlfw_InitForOpenGL(window, true)) { + ImPlot::DestroyContext(); + ImGui::DestroyContext(); + throw std::runtime_error("ImGui_ImplGlfw_InitForOpenGL failed"); + } + if (!ImGui_ImplOpenGL3_Init("#version 330")) { + ImGui_ImplGlfw_Shutdown(); + ImPlot::DestroyContext(); + ImGui::DestroyContext(); + throw std::runtime_error("ImGui_ImplOpenGL3_Init failed"); + } +} + +ImGuiRuntime::~ImGuiRuntime() { + ImGui_ImplOpenGL3_Shutdown(); + ImGui_ImplGlfw_Shutdown(); + ImPlot::DestroyContext(); + ImGui::DestroyContext(); +} + +struct TerminalRouteProgress::Impl { + explicit Impl(bool enabled) : enabled_(enabled) {} + + void update(const RouteLoadProgress &progress) { + std::lock_guard lock(mutex_); + if (!enabled_) { + return; + } + + double overall = 0.0; + std::string detail = "Resolving route"; + if (progress.stage == RouteLoadStage::Finished) { + overall = 1.0; + detail = "Ready"; + } else if (progress.total_segments > 0) { + const bool finalizing = progress.segments_downloaded >= progress.total_segments + && progress.segments_parsed >= progress.total_segments; + if (finalizing) { + overall = 0.99; + detail = "Finalizing route data"; + } else { + const double total_work = static_cast(progress.total_segments) * 2.0; + const double complete_work = static_cast(progress.segments_downloaded + progress.segments_parsed); + overall = total_work <= 0.0 ? 0.0 : std::clamp(complete_work / total_work, 0.0, 0.99); + std::ostringstream desc; + desc << "Downloaded " << progress.segments_downloaded << "/" << progress.total_segments + << " Parsed " << progress.segments_parsed << "/" << progress.total_segments; + detail = desc.str(); + } + } + + render(overall, detail); + } + + void finish() { + std::lock_guard lock(mutex_); + if (!enabled_ || !rendered_) { + return; + } + render(1.0, "Ready"); + std::fputc('\n', stderr); + std::fflush(stderr); + rendered_ = false; + } + + void render(double progress, const std::string &detail) { + const int percent = std::clamp(static_cast(std::round(progress * 100.0)), 0, 100); + if (percent == last_percent_ && detail == last_detail_) { + return; + } + + constexpr int kWidth = 20; + const int filled = std::clamp(static_cast(std::round(progress * kWidth)), 0, kWidth); + const std::string bar = std::string(static_cast(filled), '=') + std::string(static_cast(kWidth - filled), ' '); + std::ostringstream line; + line << "\r[" << bar << "] " << percent << "% " << detail; + + const std::string text = line.str(); + std::fprintf(stderr, "%s", text.c_str()); + if (text.size() < last_line_width_) { + std::fprintf(stderr, "%s", std::string(last_line_width_ - text.size(), ' ').c_str()); + } + std::fflush(stderr); + + rendered_ = true; + last_percent_ = percent; + last_detail_ = detail; + last_line_width_ = text.size(); + } + + bool enabled_ = false; + bool rendered_ = false; + int last_percent_ = -1; + size_t last_line_width_ = 0; + std::string last_detail_; + std::mutex mutex_; +}; + +TerminalRouteProgress::TerminalRouteProgress(bool enabled) + : impl_(std::make_unique(enabled)) {} + +TerminalRouteProgress::~TerminalRouteProgress() { + finish(); +} + +void TerminalRouteProgress::update(const RouteLoadProgress &progress) { + impl_->update(progress); +} + +void TerminalRouteProgress::finish() { + impl_->finish(); +} + +struct AsyncRouteLoader::Impl { + explicit Impl(bool enable_terminal_progress) + : terminal_progress(enable_terminal_progress) {} + + ~Impl() { + join(); + } + + void start(const std::string &route_name_value, const std::string &data_dir_value, const std::string &dbc_name_value) { + join(); + { + std::lock_guard lock(mutex); + route_name = route_name_value; + data_dir = data_dir_value; + dbc_name = dbc_name_value; + result.reset(); + error_text.clear(); + } + active.store(!route_name_value.empty()); + completed.store(route_name_value.empty()); + success.store(route_name_value.empty()); + total_segments.store(0); + segments_downloaded.store(0); + segments_parsed.store(0); + if (route_name_value.empty()) { + return; + } + + worker = std::thread([this]() { + try { + RouteData route_data = load_route_data(route_name, data_dir, dbc_name, [this](const RouteLoadProgress &progress) { + total_segments.store(progress.total_segments > 0 ? progress.total_segments : progress.segment_count); + segments_downloaded.store(progress.segments_downloaded); + segments_parsed.store(progress.segments_parsed); + terminal_progress.update(progress); + }); + { + std::lock_guard lock(mutex); + result = std::make_unique(std::move(route_data)); + error_text.clear(); + } + success.store(true); + } catch (const std::exception &err) { + std::lock_guard lock(mutex); + result.reset(); + error_text = err.what(); + success.store(false); + } + active.store(false); + completed.store(true); + terminal_progress.finish(); + }); + } + + RouteLoadSnapshot snapshot() const { + RouteLoadSnapshot snapshot; + snapshot.active = active.load(); + snapshot.total_segments = total_segments.load(); + snapshot.segments_downloaded = segments_downloaded.load(); + snapshot.segments_parsed = segments_parsed.load(); + return snapshot; + } + + bool consume(RouteData *route_data, std::string *error_text_out) { + if (!completed.load()) return false; + join(); + std::lock_guard lock(mutex); + completed.store(false); + if (result) { + *route_data = std::move(*result); + result.reset(); + if (error_text_out != nullptr) { + error_text_out->clear(); + } + return true; + } + if (error_text_out != nullptr) { + *error_text_out = error_text; + } + return true; + } + + void join() { + if (worker.joinable()) { + worker.join(); + } + } + + mutable std::mutex mutex; + std::thread worker; + std::unique_ptr result; + std::string route_name; + std::string data_dir; + std::string dbc_name; + std::string error_text; + std::atomic active{false}; + std::atomic completed{false}; + std::atomic success{false}; + std::atomic total_segments{0}; + std::atomic segments_downloaded{0}; + std::atomic segments_parsed{0}; + TerminalRouteProgress terminal_progress; +}; + +AsyncRouteLoader::AsyncRouteLoader(bool enable_terminal_progress) + : impl_(std::make_unique(enable_terminal_progress)) {} + +AsyncRouteLoader::~AsyncRouteLoader() = default; + +void AsyncRouteLoader::start(const std::string &route_name, const std::string &data_dir, const std::string &dbc_name) { + impl_->start(route_name, data_dir, dbc_name); +} + +RouteLoadSnapshot AsyncRouteLoader::snapshot() const { + return impl_->snapshot(); +} + +bool AsyncRouteLoader::consume(RouteData *route_data, std::string *error_text) { + return impl_->consume(route_data, error_text); +} + +struct StreamPoller::Impl { + ~Impl() { + stop(); + } + + void start(const StreamSourceConfig &requested_source, + double requested_buffer_seconds, + const std::string &dbc_name, + std::optional time_offset) { + stop(); + { + std::lock_guard lock(mutex); + pending = {}; + pending_series_slots.clear(); + pending_can_slots.clear(); + error_text.clear(); + source = requested_source; + if (source.kind == StreamSourceKind::CerealLocal) { + source.address = "127.0.0.1"; + } else if (source.kind == StreamSourceKind::CerealRemote) { + source.address = normalize_stream_address(source.address); + } + buffer_seconds = std::max(1.0, requested_buffer_seconds); + latest_dbc_name = dbc_name; + latest_car_fingerprint.clear(); + } + received_messages.store(0); + connected.store(false); + paused.store(false); + running.store(true); + worker = std::thread([this, dbc_name, time_offset]() { + try { + StreamAccumulator accumulator(dbc_name, time_offset); + switch (source.kind) { + case StreamSourceKind::CerealLocal: + case StreamSourceKind::CerealRemote: + run_cereal_source(&accumulator); + break; + } + } catch (const std::exception &err) { + std::lock_guard lock(mutex); + error_text = err.what(); + } + connected.store(false); + running.store(false); + }); + } + + void setPaused(bool paused_value) { + paused.store(paused_value); + if (paused_value) { + std::lock_guard lock(mutex); + pending = {}; + pending_series_slots.clear(); + pending_can_slots.clear(); + error_text.clear(); + } + } + + void set_error_text(std::string text) { + std::lock_guard lock(mutex); + error_text = std::move(text); + } + + void clear_error_text() { + std::lock_guard lock(mutex); + error_text.clear(); + } + + void stop() { + running.store(false); + paused.store(false); + if (worker.joinable()) { + worker.join(); + } + connected.store(false); + } + + StreamPollSnapshot snapshot() const { + StreamPollSnapshot out; + out.active = running.load(); + out.connected = connected.load(); + out.paused = paused.load(); + out.source_kind = source.kind; + out.source_label = stream_source_target_label(source); + out.buffer_seconds = buffer_seconds; + out.received_messages = received_messages.load(); + std::lock_guard lock(mutex); + out.dbc_name = latest_dbc_name; + out.car_fingerprint = latest_car_fingerprint; + return out; + } + + bool consume(StreamExtractBatch *batch, std::string *out_error_text) { + std::lock_guard lock(mutex); + const bool has_error = !error_text.empty(); + const bool has_batch = stream_batch_has_data(pending); + if (!has_error && !has_batch) return false; + if (batch != nullptr) { + *batch = std::move(pending); + pending = {}; + pending_series_slots.clear(); + pending_can_slots.clear(); + } + if (out_error_text != nullptr) { + *out_error_text = error_text; + error_text.clear(); + } + return true; + } + + static void merge_route_series(RouteSeries *dst, RouteSeries *src) { + if (src->times.empty()) { + return; + } + if (dst->path.empty()) { + dst->path = src->path; + } + dst->times.insert(dst->times.end(), src->times.begin(), src->times.end()); + dst->values.insert(dst->values.end(), src->values.begin(), src->values.end()); + } + + static void merge_can_message_data(CanMessageData *dst, CanMessageData *src) { + if (src->samples.empty()) { + return; + } + if (dst->samples.empty()) { + *dst = std::move(*src); + return; + } + dst->samples.insert(dst->samples.end(), + std::make_move_iterator(src->samples.begin()), + std::make_move_iterator(src->samples.end())); + } + + static void merge_batch(StreamExtractBatch *dst, + std::unordered_map *series_slots, + std::unordered_map *can_slots, + StreamExtractBatch *src) { + for (RouteSeries &series : src->series) { + auto [it, inserted] = series_slots->try_emplace(series.path, dst->series.size()); + if (inserted) { + dst->series.push_back(RouteSeries{.path = series.path}); + } + merge_route_series(&dst->series[it->second], &series); + } + for (CanMessageData &message : src->can_messages) { + auto [it, inserted] = can_slots->try_emplace(message.id, dst->can_messages.size()); + if (inserted) { + dst->can_messages.push_back(CanMessageData{.id = message.id}); + } + merge_can_message_data(&dst->can_messages[it->second], &message); + } + if (!src->logs.empty()) { + dst->logs.insert(dst->logs.end(), + std::make_move_iterator(src->logs.begin()), + std::make_move_iterator(src->logs.end())); + } + if (!src->timeline.empty()) { + dst->timeline.insert(dst->timeline.end(), + std::make_move_iterator(src->timeline.begin()), + std::make_move_iterator(src->timeline.end())); + } + for (auto &[path, info] : src->enum_info) { + dst->enum_info[path] = std::move(info); + } + if (!src->car_fingerprint.empty()) { + dst->car_fingerprint = src->car_fingerprint; + } + if (!src->dbc_name.empty()) { + dst->dbc_name = src->dbc_name; + } + } + + void publish_batch(StreamAccumulator *accumulator) { + StreamExtractBatch batch = accumulator->takeBatch(); + if (!stream_batch_has_data(batch)) { + return; + } + std::lock_guard lock(mutex); + merge_batch(&pending, &pending_series_slots, &pending_can_slots, &batch); + latest_dbc_name = pending.dbc_name; + latest_car_fingerprint = pending.car_fingerprint; + } + + void run_cereal_source(StreamAccumulator *accumulator) { + if (source.kind == StreamSourceKind::CerealRemote) { + setenv("ZMQ", "1", 1); + } else { + unsetenv("ZMQ"); + } + + std::unique_ptr context(Context::create()); + std::unique_ptr poller(Poller::create()); + std::vector> sockets; + sockets.reserve(services.size()); + for (const auto &[name, info] : services) { + if (!should_subscribe_stream_service(name)) continue; + std::unique_ptr socket( + SubSocket::create(context.get(), name.c_str(), source.address.c_str(), false, true, info.queue_size)); + if (socket == nullptr) continue; + socket->setTimeout(0); + poller->registerSocket(socket.get()); + sockets.push_back(std::move(socket)); + } + if (sockets.empty()) throw std::runtime_error("Failed to connect to any cereal service"); + connected.store(true); + + while (running.load()) { + std::vector ready = poller->poll(1); + for (SubSocket *socket : ready) { + while (running.load()) { + std::unique_ptr msg(socket->receive(true)); + if (!msg) break; + const size_t size = msg->getSize(); + if (size < sizeof(capnp::word) || (size % sizeof(capnp::word)) != 0) { + continue; + } + if (paused.load()) { + received_messages.fetch_add(1); + continue; + } + kj::ArrayPtr data(reinterpret_cast(msg->getData()), + size / sizeof(capnp::word)); + accumulator->appendEvent(data); + received_messages.fetch_add(1); + } + } + publish_batch(accumulator); + } + } + + mutable std::mutex mutex; + std::thread worker; + std::atomic running{false}; + std::atomic connected{false}; + std::atomic paused{false}; + std::atomic received_messages{0}; + StreamExtractBatch pending; + std::unordered_map pending_series_slots; + std::unordered_map pending_can_slots; + std::string error_text; + StreamSourceConfig source; + std::string latest_dbc_name; + std::string latest_car_fingerprint; + double buffer_seconds = 30.0; +}; + +StreamPoller::StreamPoller() + : impl_(std::make_unique()) {} + +StreamPoller::~StreamPoller() = default; + +void StreamPoller::start(const StreamSourceConfig &source, + double buffer_seconds, + const std::string &dbc_name, + std::optional time_offset) { + impl_->start(source, buffer_seconds, dbc_name, time_offset); +} + +void StreamPoller::setPaused(bool paused) { + impl_->setPaused(paused); +} + +void StreamPoller::stop() { + impl_->stop(); +} + +StreamPollSnapshot StreamPoller::snapshot() const { + return impl_->snapshot(); +} + +bool StreamPoller::consume(StreamExtractBatch *batch, std::string *error_text) { + return impl_->consume(batch, error_text); +} + +struct CameraFeedView::Impl { + struct RequestKey { + int segment = -1; + int decode_index = -1; + }; + + struct DecodeRequest { + RequestKey key; + std::string path; + uint64_t serial = 0; + uint64_t generation = 0; + }; + + struct PreloadTask { + int segment = -1; + std::string path; + uint64_t generation = 0; + }; + + struct DecodeResult { + RequestKey key; + bool success = false; + int width = 0; + int height = 0; + double decode_ms = 0.0; + std::vector rgba; + }; + + static constexpr float kDefaultAspect = 1208.0f / 1928.0f; + static constexpr size_t kCachedFrames = 8; + static constexpr int kPrefetchAhead = 2; + static constexpr int kImmediateNearbyFrameDistance = 8; + static constexpr int kPreloadWorkerCount = 2; + + Impl() { + demand_worker = std::thread([this]() { demand_worker_loop(); }); + for (int i = 0; i < kPreloadWorkerCount; ++i) { + preload_workers.emplace_back([this]() { preload_worker_loop(); }); + } + } + + ~Impl() { + stop.store(true); + cv.notify_all(); + if (demand_worker.joinable()) { + demand_worker.join(); + } + for (std::thread &worker : preload_workers) { + if (worker.joinable()) { + worker.join(); + } + } + destroy_texture(); + } + + void setRouteData(const RouteData &route_data) { + setCameraIndex(route_data.road_camera, CameraViewKind::Road); + } + + void setCameraIndex(const CameraFeedIndex &camera_index, CameraViewKind view) { + destroy_texture(); + { + std::lock_guard lock(mutex); + route_index = camera_index; + camera_view = view; + pending_request.reset(); + pending_result.reset(); + cached_results.clear(); + preload_queue.clear(); + preload_focus_segment = -1; + ++route_generation; + latest_request_serial = 0; + int initial_focus_segment = -1; + if (!route_index.entries.empty()) { + initial_focus_segment = route_index.entries.front().segment; + } else { + for (const CameraSegmentFile &segment_file : route_index.segment_files) { + if (!segment_file.path.empty()) { + initial_focus_segment = segment_file.segment; + break; + } + } + } + if (initial_focus_segment >= 0) { + rebuild_preload_queue_locked(initial_focus_segment); + } + } + abort_demand_work.store(true); + abort_preload_work.store(true); + active_request.reset(); + displayed_request.reset(); + failed_request.reset(); + frame_width = 0; + frame_height = 0; + cv.notify_all(); + } + + void update(double tracker_time) { + upload_pending_result(); + std::optional request = request_for_time(tracker_time); + if (!request.has_value()) { + return; + } + if (same_request(active_request, request->key) || same_request(displayed_request, request->key) || + same_request(failed_request, request->key)) { + return; + } + if (try_upload_cached_result(request->key)) { + return; + } + try_upload_nearby_cached_result(request->key); + + bool focus_changed = false; + { + std::lock_guard lock(mutex); + if (preload_focus_segment != request->key.segment) { + rebuild_preload_queue_locked(request->key.segment); + focus_changed = true; + } + request->serial = ++latest_request_serial; + request->generation = route_generation; + pending_request = request; + } + abort_demand_work.store(true); + if (focus_changed) { + abort_preload_work.store(true); + } + active_request = request->key; + failed_request.reset(); + cv.notify_all(); + } + + void draw(float width, bool loading) { + const float preview_width = std::max(1.0f, width); + const float preview_height = preview_width * preview_aspect(); + drawSized(ImVec2(preview_width, preview_height), loading, false); + ImGui::Spacing(); + } + + void drawSized(ImVec2 size, bool loading, bool fit_to_pane) { + size.x = std::max(1.0f, size.x); + size.y = std::max(1.0f, size.y); + const float aspect = preview_aspect(); + ImVec2 frame_size = size; + ImVec2 top_left = ImGui::GetCursorScreenPos(); + ImVec2 uv0(0.0f, 0.0f); + ImVec2 uv1(1.0f, 1.0f); + if (aspect > 0.0f && !fit_to_pane) { + frame_size.y = std::min(size.y, size.x * aspect); + frame_size.x = std::min(size.x, frame_size.y / aspect); + top_left = ImVec2(top_left.x + (size.x - frame_size.x) * 0.5f, + top_left.y + (size.y - frame_size.y) * 0.5f); + } else if (aspect > 0.0f && fit_to_pane) { + const float src_aspect = 1.0f / aspect; + const float dst_aspect = size.x / size.y; + if (dst_aspect > src_aspect) { + const float visible_v = std::clamp(src_aspect / dst_aspect, 0.0f, 1.0f); + const float v_pad = (1.0f - visible_v) * 0.5f; + uv0.y = v_pad; + uv1.y = 1.0f - v_pad; + } else if (dst_aspect < src_aspect) { + const float visible_u = std::clamp(dst_aspect / src_aspect, 0.0f, 1.0f); + const float u_pad = (1.0f - visible_u) * 0.5f; + uv0.x = u_pad; + uv1.x = 1.0f - u_pad; + } + } + ImGui::InvisibleButton("##camera_feed_sized", size); + if (texture != 0) { + ImGui::GetWindowDrawList()->AddImage(static_cast(texture), + top_left, + ImVec2(top_left.x + frame_size.x, top_left.y + frame_size.y), + uv0, + uv1); + } else { + ImDrawList *draw_list = ImGui::GetWindowDrawList(); + draw_list->AddRectFilled(top_left, ImVec2(top_left.x + frame_size.x, top_left.y + frame_size.y), IM_COL32(45, 47, 50, 255)); + draw_list->AddRect(top_left, ImVec2(top_left.x + frame_size.x, top_left.y + frame_size.y), IM_COL32(95, 100, 106, 255)); + + const char *label = (loading || has_video_source()) ? "loading" : "no video"; + const ImVec2 text_size = ImGui::CalcTextSize(label); + const ImVec2 text_pos(top_left.x + (frame_size.x - text_size.x) * 0.5f, + top_left.y + (frame_size.y - text_size.y) * 0.5f); + draw_list->AddText(text_pos, IM_COL32(187, 187, 187, 255), label); + } + } + + static bool same_request(const std::optional &lhs, const RequestKey &rhs) { + return lhs.has_value() && lhs->segment == rhs.segment && lhs->decode_index == rhs.decode_index; + } + + bool has_video_source() const { + std::lock_guard lock(mutex); + return !route_index.entries.empty() && !route_index.segment_files.empty(); + } + + float preview_aspect() const { + if (frame_width > 0 && frame_height > 0) return static_cast(frame_height) / static_cast(frame_width); + return kDefaultAspect; + } + + std::optional request_for_time(double tracker_time) const { + std::lock_guard lock(mutex); + if (route_index.entries.empty()) return std::nullopt; + + auto it = std::lower_bound(route_index.entries.begin(), route_index.entries.end(), tracker_time, + [](const CameraFrameIndexEntry &entry, double tm) { + return entry.timestamp < tm; + }); + if (it == route_index.entries.end()) { + it = std::prev(route_index.entries.end()); + } else if (it != route_index.entries.begin()) { + const auto prev = std::prev(it); + if (std::abs(prev->timestamp - tracker_time) <= std::abs(it->timestamp - tracker_time)) { + it = prev; + } + } + + auto path_it = std::find_if(route_index.segment_files.begin(), route_index.segment_files.end(), + [&](const CameraSegmentFile &segment) { + return segment.segment == it->segment && !segment.path.empty(); + }); + if (path_it == route_index.segment_files.end()) return std::nullopt; + + return DecodeRequest{ + .key = RequestKey{.segment = it->segment, .decode_index = it->decode_index}, + .path = path_it->path, + }; + } + + void upload_pending_result() { + std::optional result; + { + std::lock_guard lock(mutex); + if (!pending_result.has_value()) { + return; + } + result = std::move(pending_result); + pending_result.reset(); + } + + active_request.reset(); + if (!result->success || result->rgba.empty() || result->width <= 0 || result->height <= 0) { + failed_request = result->key; + return; + } + + upload_result(*result); + } + + void upload_result(const DecodeResult &result) { + remember_cached_result(result); + + const bool new_size = texture_width != result.width || texture_height != result.height; + if (texture == 0) { + glGenTextures(1, &texture); + } + glBindTexture(GL_TEXTURE_2D, texture); + if (new_size) { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, result.width, result.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, result.rgba.data()); + texture_width = result.width; + texture_height = result.height; + } else { + glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, result.width, result.height, GL_RGBA, GL_UNSIGNED_BYTE, result.rgba.data()); + } + glBindTexture(GL_TEXTURE_2D, 0); + + frame_width = result.width; + frame_height = result.height; + displayed_request = result.key; + failed_request.reset(); + } + + bool try_upload_cached_result(const RequestKey &key) { + std::optional result; + { + std::lock_guard lock(mutex); + auto it = std::find_if(cached_results.begin(), cached_results.end(), [&](const DecodeResult &cached) { + return cached.key.segment == key.segment && cached.key.decode_index == key.decode_index; + }); + if (it == cached_results.end()) { + return false; + } + result = *it; + } + active_request.reset(); + upload_result(*result); + return true; + } + + bool try_upload_nearby_cached_result(const RequestKey &key) { + std::optional result; + int best_distance = std::numeric_limits::max(); + { + std::lock_guard lock(mutex); + for (const DecodeResult &cached : cached_results) { + if (cached.key.segment != key.segment) continue; + const int distance = std::abs(cached.key.decode_index - key.decode_index); + if (distance == 0 || distance > kImmediateNearbyFrameDistance || distance >= best_distance) continue; + best_distance = distance; + result = cached; + } + } + if (!result.has_value()) { + return false; + } + upload_result(*result); + return true; + } + + void remember_cached_result(const DecodeResult &result) { + std::lock_guard lock(mutex); + auto it = std::find_if(cached_results.begin(), cached_results.end(), [&](const DecodeResult &cached) { + return cached.key.segment == result.key.segment && cached.key.decode_index == result.key.decode_index; + }); + if (it != cached_results.end()) { + cached_results.erase(it); + } + cached_results.push_front(result); + while (cached_results.size() > kCachedFrames) { + cached_results.pop_back(); + } + } + + void destroy_texture() { + if (texture != 0 && g_glfw_alive.load() && glfwGetCurrentContext() != nullptr) { + glDeleteTextures(1, &texture); + } + texture = 0; + texture_width = 0; + texture_height = 0; + frame_width = 0; + frame_height = 0; + } + + static bool ensure_decode_buffer(FrameReader *reader, VisionBuf *buf, bool &allocated, int &w, int &h) { + if (!reader) return false; + if (allocated && w == reader->width && h == reader->height) return true; + if (allocated) { buf->free(); allocated = false; } + const auto [stride, y_height, _uv_height, size] = get_nv12_info(reader->width, reader->height); + buf->allocate(size); + buf->init_yuv(reader->width, reader->height, stride, stride * y_height); + w = reader->width; + h = reader->height; + allocated = true; + return true; + } + + void publish_result(const DecodeRequest &request, DecodeResult result) { + std::lock_guard lock(mutex); + if (!pending_request.has_value() || pending_request->serial != request.serial || + pending_request->generation != request.generation) { + return; + } + pending_result = std::move(result); + } + + bool has_newer_pending_request(uint64_t serial) const { + std::lock_guard lock(mutex); + return pending_request.has_value() && pending_request->serial != serial; + } + + void rebuild_preload_queue_locked(int focus_segment) { + std::vector ordered; + ordered.reserve(route_index.segment_files.size()); + for (const CameraSegmentFile &segment_file : route_index.segment_files) { + if (segment_file.path.empty()) continue; + if (segment_file.segment == focus_segment) continue; + ordered.push_back(PreloadTask{ + .segment = segment_file.segment, + .path = segment_file.path, + .generation = route_generation, + }); + } + std::sort(ordered.begin(), ordered.end(), [&](const PreloadTask &a, const PreloadTask &b) { + const int distance_a = std::abs(a.segment - focus_segment); + const int distance_b = std::abs(b.segment - focus_segment); + if (distance_a != distance_b) return distance_a < distance_b; + return a.segment < b.segment; + }); + preload_queue.assign(ordered.begin(), ordered.end()); + preload_focus_segment = focus_segment; + } + + std::shared_ptr find_loaded_reader_locked(int segment, uint64_t generation) { + if (readers_generation != generation) { + readers.clear(); + loading_segments.clear(); + readers_generation = generation; + } + auto it = readers.find(segment); + return it != readers.end() ? it->second : nullptr; + } + + std::shared_ptr ensure_reader_loaded(int segment, + const std::string &path, + uint64_t generation, + const char *reason, + std::atomic *abort_flag, + bool wait_for_inflight) { + while (!stop.load()) { + { + std::unique_lock lock(readers_mutex); + if (std::shared_ptr cached = find_loaded_reader_locked(segment, generation)) { + return cached; + } + if (loading_segments.find(segment) != loading_segments.end()) { + if (!wait_for_inflight) { + return nullptr; + } + readers_cv.wait(lock, [&]() { + return stop.load() + || readers_generation != generation + || loading_segments.find(segment) == loading_segments.end(); + }); + continue; + } + loading_segments.insert(segment); + } + + auto reader = std::make_shared(); + const auto load_begin = std::chrono::steady_clock::now(); + const bool loaded = reader->load(decoder_camera_type(camera_view), path, false, abort_flag, true); + + { + std::lock_guard lock(readers_mutex); + if (readers_generation != generation) { + readers.clear(); + loading_segments.clear(); + readers_generation = generation; + } + loading_segments.erase(segment); + if (loaded) { + readers[segment] = reader; + } + } + readers_cv.notify_all(); + + if (!loaded) { + return nullptr; + } + if (kLogCameraTimings) { + const double load_ms = std::chrono::duration(std::chrono::steady_clock::now() - load_begin).count(); + std::fprintf(stderr, "camera[%s] %s-load seg=%d %.1fms\n", + camera_view_spec(camera_view).runtime_name, reason, segment, load_ms); + } + return reader; + } + return nullptr; + } + + void preload_worker_loop() { + while (true) { + std::optional preload; + { + std::unique_lock lock(mutex); + cv.wait(lock, [&]() { return stop.load() || !preload_queue.empty(); }); + if (stop.load()) { + break; + } + preload = preload_queue.front(); + preload_queue.pop_front(); + } + + abort_preload_work.store(false); + { + std::lock_guard lock(readers_mutex); + if (find_loaded_reader_locked(preload->segment, preload->generation)) { + continue; + } + } + ensure_reader_loaded(preload->segment, preload->path, preload->generation, "preload", + &abort_preload_work, false); + } + } + + void demand_worker_loop() { + uint64_t handled_serial = 0; + VisionBuf decode_buffer; + bool buffer_allocated = false; + int buffer_width = 0; + int buffer_height = 0; + + while (true) { + std::optional request; + { + std::unique_lock lock(mutex); + cv.wait(lock, [&]() { + return stop.load() || (pending_request.has_value() && pending_request->serial != handled_serial); + }); + if (stop.load()) break; + request = *pending_request; + handled_serial = request->serial; + } + + abort_demand_work.store(false); + + DecodeResult result{.key = request->key}; + std::shared_ptr reader = ensure_reader_loaded(request->key.segment, request->path, + request->generation, "demand", + &abort_demand_work, true); + if (!reader) { + publish_result(*request, std::move(result)); + continue; + } + if (has_newer_pending_request(request->serial)) { + continue; + } + + const auto decode_begin = std::chrono::steady_clock::now(); + if (!ensure_decode_buffer(reader.get(), &decode_buffer, buffer_allocated, buffer_width, buffer_height) || + !reader->get(request->key.decode_index, &decode_buffer)) { + publish_result(*request, std::move(result)); + continue; + } + + result.width = reader->width; + result.height = reader->height; + result.rgba.resize(static_cast(result.width) * static_cast(result.height) * 4U, 0); + yuv::nv12_to_rgba(decode_buffer.y, + static_cast(decode_buffer.stride), + decode_buffer.uv, + static_cast(decode_buffer.stride), + result.rgba.data(), + result.width * 4, + result.width, + result.height); + result.success = true; + result.decode_ms = std::chrono::duration(std::chrono::steady_clock::now() - decode_begin).count(); + publish_result(*request, std::move(result)); + + for (int offset = 1; offset <= kPrefetchAhead; ++offset) { + if (stop.load() || has_newer_pending_request(request->serial)) { + break; + } + const int next_index = request->key.decode_index + offset; + if (next_index < 0 || next_index >= static_cast(reader->getFrameCount())) { + break; + } + if (!reader->get(next_index, &decode_buffer)) { + break; + } + DecodeResult prefetched{ + .key = RequestKey{.segment = request->key.segment, .decode_index = next_index}, + .success = true, + .width = reader->width, + .height = reader->height, + }; + prefetched.rgba.resize(static_cast(prefetched.width) * static_cast(prefetched.height) * 4U, 0); + yuv::nv12_to_rgba(decode_buffer.y, + static_cast(decode_buffer.stride), + decode_buffer.uv, + static_cast(decode_buffer.stride), + prefetched.rgba.data(), + prefetched.width * 4, + prefetched.width, + prefetched.height); + remember_cached_result(prefetched); + } + } + + if (buffer_allocated) { + decode_buffer.free(); + } + } + + mutable std::mutex mutex; + std::condition_variable cv; + std::thread demand_worker; + std::vector preload_workers; + std::atomic stop{false}; + std::atomic abort_demand_work{false}; + std::atomic abort_preload_work{false}; + CameraFeedIndex route_index; + CameraViewKind camera_view = CameraViewKind::Road; + std::optional pending_request; + std::optional pending_result; + std::deque preload_queue; + int preload_focus_segment = -1; + std::deque cached_results; + uint64_t latest_request_serial = 0; + uint64_t route_generation = 1; + std::optional active_request; + std::optional displayed_request; + std::optional failed_request; + std::mutex readers_mutex; + std::condition_variable readers_cv; + std::unordered_map> readers; + std::unordered_set loading_segments; + uint64_t readers_generation = 0; + GLuint texture = 0; + int texture_width = 0; + int texture_height = 0; + int frame_width = 0; + int frame_height = 0; +}; + +CameraFeedView::CameraFeedView() + : impl_(std::make_unique()) {} + +CameraFeedView::~CameraFeedView() = default; + +void CameraFeedView::setRouteData(const RouteData &route_data) { + impl_->setRouteData(route_data); +} + +void CameraFeedView::setCameraIndex(const CameraFeedIndex &camera_index, CameraViewKind view) { + impl_->setCameraIndex(camera_index, view); +} + +void CameraFeedView::update(double tracker_time) { + impl_->update(tracker_time); +} + +void CameraFeedView::draw(float width, bool loading) { + impl_->draw(width, loading); +} + +void CameraFeedView::drawSized(ImVec2 size, bool loading, bool fit_to_pane) { + impl_->drawSized(size, loading, fit_to_pane); +} diff --git a/openpilot/tools/jotpluggler/session.cc b/openpilot/tools/jotpluggler/session.cc new file mode 100644 index 0000000000..4c694a8daa --- /dev/null +++ b/openpilot/tools/jotpluggler/session.cc @@ -0,0 +1,775 @@ +#include "tools/jotpluggler/internal.h" + +#include "imgui_internal.h" + +#include +#include +#include + +namespace fs = std::filesystem; + +const RouteSeries *app_find_route_series(const AppSession &session, const std::string &path) { + auto it = session.series_by_path.find(path); + return it == session.series_by_path.end() ? nullptr : it->second; +} + +void sync_camera_feeds(AppSession *session) { + for (size_t i = 0; i < kCameraViewSpecs.size(); ++i) { + if (session->pane_camera_feeds[i]) { + session->pane_camera_feeds[i]->setCameraIndex(session->route_data.*(kCameraViewSpecs[i].route_member), kCameraViewSpecs[i].view); + } + } + if (session->thumbnail_view) { + session->thumbnail_view->setThumbnails(session->route_data.thumbnails); + } +} + +void apply_route_data(AppSession *session, UiState *state, RouteData route_data) { + if (!route_data.route_id.empty()) { + session->route_id = route_data.route_id; + } else if (session->route_name.empty() && session->data_mode == SessionDataMode::Route) { + session->route_id = {}; + } + session->route_data = std::move(route_data); + rebuild_route_index(session); + rebuild_browser_nodes(session, state); + state->browser_nodes_dirty = false; + refresh_all_custom_curves(session, state); + sync_camera_feeds(session); + state->has_shared_range = false; + state->has_tracker_time = false; + reset_shared_range(state, *session); +} + +bool restore_undo_layout(AppSession *session, UiState *state, const SketchLayout &layout, const char *status_text) { + session->layout = layout; + cancel_rename_tab(state); + state->custom_series.request_select = false; + state->active_tab_index = std::clamp(layout.current_tab_index, 0, std::max(0, static_cast(layout.tabs.size()) - 1)); + state->requested_tab_index = state->active_tab_index; + sync_ui_state(state, session->layout); + mark_all_docks_dirty(state); + const bool autosave_ok = autosave_layout(session, state); + if (autosave_ok) { + state->status_text = status_text; + } + return autosave_ok; +} + +bool apply_undo(AppSession *session, UiState *state) { + if (!state->undo.can_undo()) { + return false; + } + return restore_undo_layout(session, state, state->undo.undo(), "Undo"); +} + +bool apply_redo(AppSession *session, UiState *state) { + if (!state->undo.can_redo()) { + return false; + } + return restore_undo_layout(session, state, state->undo.redo(), "Redo"); +} + +std::optional> tab_default_x_range(const WorkspaceTab &tab) { + bool found = false; + double min_value = 0.0; + double max_value = 1.0; + for (const Pane &pane : tab.panes) { + if (!pane.range.valid || pane.range.right <= pane.range.left) continue; + if (!found) { + min_value = pane.range.left; + max_value = pane.range.right; + found = true; + } else { + min_value = std::min(min_value, pane.range.left); + max_value = std::max(max_value, pane.range.right); + } + } + if (!found) return std::nullopt; + return std::make_pair(min_value, max_value); +} + +bool infer_stream_follow_state(const UiState &state, const AppSession &session) { + if (session.data_mode != SessionDataMode::Stream || !state.has_shared_range || !session.route_data.has_time_range) { + return false; + } + const double target_span = std::max(MIN_HORIZONTAL_ZOOM_SECONDS, session.stream_buffer_seconds); + const double current_span = std::max(0.0, state.x_view_max - state.x_view_min); + const double edge_epsilon = std::max(0.05, target_span * 0.02); + return std::abs(state.x_view_max - state.route_x_max) <= edge_epsilon + && std::abs(current_span - target_span) <= edge_epsilon; +} + +void ensure_shared_range(UiState *state, const AppSession &session) { + if (session.route_data.has_time_range) { + state->route_x_min = session.route_data.x_min; + state->route_x_max = session.route_data.x_max; + } else { + state->route_x_min = 0.0; + state->route_x_max = 1.0; + } + + if (state->has_shared_range) { + return; + } + + if (session.data_mode == SessionDataMode::Stream) { + const double target_span = std::max(MIN_HORIZONTAL_ZOOM_SECONDS, session.stream_buffer_seconds); + if (session.route_data.has_time_range) { + state->x_view_max = state->route_x_max; + state->x_view_min = state->x_view_max - target_span; + } else { + state->x_view_min = 0.0; + state->x_view_max = target_span; + } + if (state->x_view_max <= state->x_view_min) { + state->x_view_max = state->x_view_min + 1.0; + } + state->has_shared_range = true; + if (!state->has_tracker_time || state->tracker_time < state->route_x_min || state->tracker_time > state->route_x_max) { + state->tracker_time = state->route_x_max; + state->has_tracker_time = session.route_data.has_time_range; + } + return; + } + + if (const WorkspaceTab *tab = app_active_tab(session.layout, *state); tab != nullptr) { + if (std::optional> tab_range = tab_default_x_range(*tab); tab_range.has_value()) { + state->x_view_min = tab_range->first; + state->x_view_max = tab_range->second; + state->has_shared_range = true; + if (!state->has_tracker_time || state->tracker_time < state->route_x_min || state->tracker_time > state->route_x_max) { + state->tracker_time = state->route_x_min; + state->has_tracker_time = true; + } + return; + } + } + + state->x_view_min = state->route_x_min; + state->x_view_max = state->route_x_max; + if (state->x_view_max <= state->x_view_min) { + state->x_view_max = state->x_view_min + 1.0; + } + state->has_shared_range = true; + if (!state->has_tracker_time || state->tracker_time < state->route_x_min || state->tracker_time > state->route_x_max) { + state->tracker_time = state->route_x_min; + state->has_tracker_time = true; + } +} + +void clamp_shared_range(UiState *state, const AppSession &session) { + if (!state->has_shared_range) { + return; + } + const double min_span = MIN_HORIZONTAL_ZOOM_SECONDS; + double span = state->x_view_max - state->x_view_min; + if (span < min_span) { + const double center = 0.5 * (state->x_view_min + state->x_view_max); + span = min_span; + state->x_view_min = center - span * 0.5; + state->x_view_max = center + span * 0.5; + } + if (session.data_mode == SessionDataMode::Stream) { + if (session.route_data.has_time_range && state->x_view_max > state->route_x_max) { + state->x_view_min -= state->x_view_max - state->route_x_max; + state->x_view_max = state->route_x_max; + } + if (state->x_view_max <= state->x_view_min) { + state->x_view_max = state->x_view_min + min_span; + } + if (state->has_tracker_time && session.route_data.has_time_range) { + state->tracker_time = std::clamp(state->tracker_time, state->route_x_min, state->route_x_max); + } + if (session.route_data.has_time_range) { + state->follow_latest = infer_stream_follow_state(*state, session); + } + return; + } + if (state->route_x_max > state->route_x_min) { + if (state->x_view_min < state->route_x_min) { + state->x_view_max += state->route_x_min - state->x_view_min; + state->x_view_min = state->route_x_min; + } + if (state->x_view_max > state->route_x_max) { + state->x_view_min -= state->x_view_max - state->route_x_max; + state->x_view_max = state->route_x_max; + } + if (state->x_view_min < state->route_x_min) { + state->x_view_min = state->route_x_min; + } + if (state->x_view_max <= state->x_view_min) { + state->x_view_max = std::min(state->route_x_max, state->x_view_min + min_span); + } + } + if (state->has_tracker_time) { + state->tracker_time = std::clamp(state->tracker_time, state->route_x_min, state->route_x_max); + } +} + +void reset_shared_range(UiState *state, const AppSession &session) { + state->has_shared_range = false; + ensure_shared_range(state, session); + clamp_shared_range(state, session); +} + +void update_follow_range(UiState *state, const AppSession &session) { + if (!state->follow_latest || !state->has_shared_range) { + return; + } + const double span = session.data_mode == SessionDataMode::Stream + ? std::max(MIN_HORIZONTAL_ZOOM_SECONDS, session.stream_buffer_seconds) + : std::max(MIN_HORIZONTAL_ZOOM_SECONDS, state->x_view_max - state->x_view_min); + const double route_span = state->route_x_max - state->route_x_min; + if (route_span <= 0.0) { + return; + } + state->x_view_max = state->route_x_max; + state->x_view_min = state->x_view_max - span; + clamp_shared_range(state, session); +} + +void advance_playback(UiState *state, const AppSession &session) { + if (!state->playback_playing || !state->has_shared_range || state->route_x_max <= state->route_x_min) { + return; + } + + const double delta = std::max(0.0, static_cast(ImGui::GetIO().DeltaTime)) * state->playback_rate; + const double view_span = std::max(MIN_HORIZONTAL_ZOOM_SECONDS, state->x_view_max - state->x_view_min); + const double loop_min = state->playback_loop + ? std::clamp(state->x_view_min, state->route_x_min, state->route_x_max) + : state->route_x_min; + const double loop_max = state->playback_loop + ? std::clamp(state->x_view_max, state->route_x_min, state->route_x_max) + : state->route_x_max; + + state->tracker_time += delta; + if (state->tracker_time >= loop_max) { + if (state->playback_loop) { + state->tracker_time = loop_min; + } else { + state->tracker_time = state->route_x_max; + state->playback_playing = false; + } + } + + if (!state->playback_loop) { + constexpr double kScrollStartFraction = 0.70; + const double scroll_anchor = state->x_view_min + view_span * kScrollStartFraction; + if (state->tracker_time > scroll_anchor && state->x_view_max < state->route_x_max) { + state->x_view_min = state->tracker_time - view_span * kScrollStartFraction; + state->x_view_max = state->x_view_min + view_span; + clamp_shared_range(state, session); + } else if (state->tracker_time < state->x_view_min || state->tracker_time > state->x_view_max) { + state->x_view_min = state->tracker_time - view_span * 0.5; + state->x_view_max = state->x_view_min + view_span; + clamp_shared_range(state, session); + } + } +} + +void step_tracker(UiState *state, double direction) { + if (!state->has_shared_range) { + return; + } + state->tracker_time += direction * std::max(0.001, state->playback_step); + state->tracker_time = std::clamp(state->tracker_time, state->route_x_min, state->route_x_max); +} + +const char *log_selector_name(LogSelector selector) { + static constexpr const char *kLabels[] = {"a", "r", "q"}; + const size_t index = static_cast(selector); + return index < std::size(kLabels) ? kLabels[index] : kLabels[0]; +} + +const char *log_selector_description(LogSelector selector) { + static constexpr const char *kLabels[] = { + "any of rlog or qlog", + "rlog only", + "qlog only", + }; + const size_t index = static_cast(selector); + return index < std::size(kLabels) ? kLabels[index] : kLabels[0]; +} + +std::string shorten_route_part(std::string_view text, size_t keep) { + if (text.size() <= keep) { + return std::string(text); + } + return std::string(text.substr(0, keep)); +} + +bool parse_slice_spec(std::string_view text, int *begin, int *end) { + const auto parse_nonnegative = [](std::string_view value, int *out) { + if (value.empty()) return false; + char *end_ptr = nullptr; + const long parsed = std::strtol(std::string(value).c_str(), &end_ptr, 10); + if (end_ptr == nullptr || *end_ptr != '\0' || parsed < 0) { + return false; + } + *out = static_cast(parsed); + return true; + }; + const std::string trimmed = util::strip(std::string(text)); + if (trimmed.empty()) { + return false; + } + const size_t colon = trimmed.find(':'); + int parsed_begin = 0; + if (!parse_nonnegative(trimmed.substr(0, colon), &parsed_begin)) { + return false; + } + int parsed_end = parsed_begin; + if (colon != std::string::npos) { + const std::string end_text = trimmed.substr(colon + 1); + if (end_text.empty()) { + parsed_end = -1; + } else if (!parse_nonnegative(end_text, &parsed_end) || parsed_end < parsed_begin) { + return false; + } + } + *begin = parsed_begin; + *end = parsed_end; + return true; +} + +std::string format_duration_short(double seconds) { + const double clamped = std::max(0.0, seconds); + const int total_ms = static_cast(std::round(clamped * 1000.0)); + const int minutes = total_ms / 60000; + const int rem_ms = total_ms % 60000; + const int secs = rem_ms / 1000; + const int millis = rem_ms % 1000; + return util::string_format("%d:%02d.%03d", minutes, secs, millis); +} + +bool apply_route_identifier(AppSession *session, UiState *state, const RouteIdentifier &route_id, const char *status_text) { + if (route_id.empty()) { + return false; + } + if (!reload_session(session, state, route_id.full_spec(), session->data_dir)) { + return false; + } + state->status_text = status_text; + return true; +} + +bool apply_route_slice_change(AppSession *session, UiState *state, std::string_view slice_text) { + int begin = 0; + int end = 0; + if (!parse_slice_spec(slice_text, &begin, &end)) { + state->error_text = "Slice must be N, N:, or N:M."; + state->open_error_popup = true; + return false; + } + RouteIdentifier next = session->route_id; + next.slice_begin = begin; + next.slice_end = end; + next.slice_explicit = true; + return apply_route_identifier(session, state, next, "Updated route slice"); +} + +bool apply_route_selector_change(AppSession *session, UiState *state, LogSelector selector) { + RouteIdentifier next = session->route_id; + next.selector = selector; + next.selector_explicit = true; + return apply_route_identifier(session, state, next, "Updated log selector"); +} + +ImU32 route_chip_part_color(int part_index, bool explicit_part) { + constexpr std::array, 4> BASE = {{ + {70, 96, 126}, // dongle + {100, 86, 148}, // log id + {72, 112, 86}, // slice + {156, 104, 38}, // selector + }}; + const std::array &base = BASE[static_cast(std::clamp(part_index, 0, 3))]; + if (explicit_part) { + return ImGui::GetColorU32(color_rgb(base[0], base[1], base[2])); + } + const int gray = 144; + return ImGui::GetColorU32(color_rgb((base[0] + gray) / 2, (base[1] + gray) / 2, (base[2] + gray) / 2)); +} + +bool draw_route_chip_text_button(const char *id, + std::string_view text, + ImVec2 pos, + ImU32 color, + ImDrawList *draw_list, + const char *tooltip = nullptr) { + const ImVec2 size = ImGui::CalcTextSize(text.data(), text.data() + text.size()); + ImGui::SetCursorScreenPos(pos); + ImGui::InvisibleButton(id, size); + const bool hovered = ImGui::IsItemHovered(); + if (hovered) { + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + draw_list->AddRectFilled(ImVec2(pos.x - 5.0f, pos.y - 1.0f), + ImVec2(pos.x + size.x + 5.0f, pos.y + size.y + 2.0f), + ImGui::GetColorU32(color_rgb(225, 231, 239, 0.95f)), 0.0f); + } + draw_list->AddText(pos, color, text.data(), text.data() + text.size()); + if (tooltip != nullptr && ImGui::IsItemHovered(ImGuiHoveredFlags_DelayShort)) { + ImGui::BeginTooltip(); + ImGui::TextUnformatted(tooltip); + ImGui::EndTooltip(); + } + return ImGui::IsItemClicked(ImGuiMouseButton_Left); +} + +void draw_route_copy_feedback(UiState *state, ImDrawList *draw_list, ImVec2 chip_max) { + if (state->route_copy_feedback_text.empty()) { + return; + } + const double now = ImGui::GetTime(); + if (now >= state->route_copy_feedback_until) { + state->route_copy_feedback_text.clear(); + state->route_copy_feedback_until = 0.0; + return; + } + + const float alpha = static_cast(std::clamp((state->route_copy_feedback_until - now) / 1.1, 0.0, 1.0)); + const ImVec2 text_size = ImGui::CalcTextSize(state->route_copy_feedback_text.c_str()); + const ImVec2 pad(9.0f, 5.0f); + const ImVec2 bubble_min(chip_max.x - text_size.x - pad.x * 2.0f, chip_max.y + 7.0f); + const ImVec2 bubble_max(chip_max.x, bubble_min.y + text_size.y + pad.y * 2.0f); + draw_list->AddRectFilled(bubble_min, bubble_max, + ImGui::GetColorU32(color_rgb(46, 125, 80, 0.96f * alpha)), 7.0f); + draw_list->AddRect(bubble_min, bubble_max, + ImGui::GetColorU32(color_rgb(35, 96, 61, 0.9f * alpha)), 7.0f, 0, 1.0f); + draw_list->AddText(ImVec2(std::floor(bubble_min.x + pad.x), std::floor(bubble_min.y + pad.y)), + ImGui::GetColorU32(color_rgb(247, 251, 248, alpha)), + state->route_copy_feedback_text.c_str()); +} + +void draw_route_info_popup(AppSession *session, UiState *state, ImVec2 anchor) { + if (session->route_id.empty()) { + return; + } + ImGui::SetNextWindowPos(anchor, ImGuiCond_Appearing); + ImGui::SetNextWindowSizeConstraints(ImVec2(300.0f, 0.0f), ImVec2(420.0f, FLT_MAX)); + if (!app_begin_popup("##route_info_popup", ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings)) { + return; + } + + ImGui::TextUnformatted("Route Info"); + ImGui::Separator(); + app_push_mono_font(); + ImGui::TextUnformatted(session->route_id.canonical().c_str()); + app_pop_mono_font(); + + const char *copy_icon = icon::CLIPBOARD; + const char *link_icon = icon::BOX_ARROW_UP_RIGHT; + const std::string useradmin_label = std::string("Useradmin ") + link_icon; + const std::string connect_label = std::string("comma connect ") + link_icon; + if (ImGui::Button(copy_icon, ImVec2(34.0f, 26.0f))) { + ImGui::SetClipboardText(session->route_id.canonical().c_str()); + state->status_text = "Copied route to clipboard"; + state->route_copy_feedback_text = "Copied"; + state->route_copy_feedback_until = ImGui::GetTime() + 1.1; + } + if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayShort)) { + ImGui::BeginTooltip(); + ImGui::TextUnformatted("Copy route"); + ImGui::EndTooltip(); + } + ImGui::SameLine(); + if (ImGui::Button(useradmin_label.c_str(), ImVec2(132.0f, 26.0f))) { + open_external_url(route_useradmin_url(session->route_id)); + state->status_text = "Opened useradmin"; + } + ImGui::SameLine(); + if (ImGui::Button(connect_label.c_str(), ImVec2(156.0f, 26.0f))) { + open_external_url(route_connect_url(session->route_id)); + state->status_text = "Opened comma connect"; + } + + ImGui::Spacing(); + const int loaded_begin = session->route_id.available_begin; + const int loaded_end = session->route_id.available_end; + const int loaded_count = loaded_end >= loaded_begin ? (loaded_end - loaded_begin + 1) : 0; + ImGui::Text("Duration %s", format_duration_short(session->route_data.x_max - session->route_data.x_min).c_str()); + ImGui::Text("Segments %s (%d)", session->route_id.display_slice().c_str(), loaded_count); + ImGui::Text("Selector %s", log_selector_description(session->route_id.selector)); + if (!session->route_data.car_fingerprint.empty()) { + ImGui::TextWrapped("Car %s", session->route_data.car_fingerprint.c_str()); + } + if (!session->route_data.dbc_name.empty()) { + ImGui::TextWrapped("DBC %s", session->route_data.dbc_name.c_str()); + } + + ImGui::EndPopup(); +} + +void draw_route_id_chip(AppSession *session, UiState *state) { + if (session->data_mode != SessionDataMode::Route || session->route_id.empty()) { + return; + } + + ImGuiWindow *window = ImGui::GetCurrentWindow(); + ImDrawList *draw_list = ImGui::GetWindowDrawList(); + const RouteIdentifier &route_id = session->route_id; + app_push_bold_font(); + const std::string dongle_text = shorten_route_part(route_id.dongle_id, 8); + const std::string log_text = shorten_route_part(route_id.log_id, 16); + const std::string slice_text = route_id.display_slice(); + const std::string selector_text(1, route_id.selector_char()); + const std::string sep_text = " / "; + + const ImVec2 dongle_size = ImGui::CalcTextSize(dongle_text.c_str()); + const ImVec2 log_size = ImGui::CalcTextSize(log_text.c_str()); + const ImVec2 slice_size = state->editing_route_slice + ? ImVec2(68.0f, ImGui::GetFrameHeight()) + : ImGui::CalcTextSize(slice_text.c_str()); + const ImVec2 selector_size = ImGui::CalcTextSize(selector_text.c_str()); + const ImVec2 sep_size = ImGui::CalcTextSize(sep_text.c_str()); + constexpr float chip_pad_x = 12.0f; + constexpr float info_size = 18.0f; + const float chip_h = 28.0f; + const float chip_w = chip_pad_x * 2.0f + dongle_size.x + sep_size.x + log_size.x + sep_size.x + + slice_size.x + sep_size.x + selector_size.x + 10.0f + info_size; + const float menu_right = window->Pos.x + window->Size.x - 8.0f; + const float cursor_x = ImGui::GetCursorScreenPos().x + 4.0f; + const float chip_x = std::clamp(cursor_x, window->Pos.x + 48.0f, std::max(window->Pos.x + 48.0f, menu_right - chip_w)); + const float chip_y = std::floor(window->Pos.y + std::max(0.0f, (window->Size.y - chip_h) * 0.5f)); + const ImVec2 chip_min(chip_x, chip_y); + const ImVec2 chip_max(chip_x + chip_w, chip_y + chip_h); + const float text_y = std::floor(chip_y + std::max(0.0f, (chip_h - ImGui::GetTextLineHeight()) * 0.5f)); + const ImU32 chip_bg = ImGui::GetColorU32(color_rgb(247, 249, 252)); + const ImU32 chip_border = ImGui::GetColorU32(color_rgb(184, 191, 200)); + const ImU32 sep = ImGui::GetColorU32(color_rgb(162, 170, 178)); + draw_list->AddRectFilled(chip_min, chip_max, chip_bg, 0.0f); + draw_list->AddRect(chip_min, chip_max, chip_border, 0.0f, 0, 1.0f); + + float x = chip_x + chip_pad_x; + const bool dongle_click = draw_route_chip_text_button( + "##route_dongle", dongle_text, ImVec2(x, text_y), route_chip_part_color(0, true), draw_list, + "Device identifier"); + x += dongle_size.x; + draw_list->AddText(ImVec2(x, text_y), sep, sep_text.c_str()); + x += sep_size.x; + const bool log_click = draw_route_chip_text_button( + "##route_log", log_text, ImVec2(x, text_y), route_chip_part_color(1, true), draw_list, + "Route identifier"); + x += log_size.x; + draw_list->AddText(ImVec2(x, text_y), sep, sep_text.c_str()); + x += sep_size.x; + + if (state->editing_route_slice) { + ImGui::SetCursorScreenPos(ImVec2(x - 4.0f, chip_y + 1.0f)); + ImGui::SetNextItemWidth(76.0f); + if (state->focus_route_slice_input) { + ImGui::SetKeyboardFocusHere(); + state->focus_route_slice_input = false; + } + const bool applied = input_text_string("##route_slice_edit", &state->route_slice_buffer, + ImGuiInputTextFlags_EnterReturnsTrue); + const bool deactivated = ImGui::IsItemDeactivated(); + const bool clicked_elsewhere = ImGui::IsMouseClicked(ImGuiMouseButton_Left) + && !ImGui::IsItemHovered() + && !ImGui::IsItemActive(); + if (applied) { + if (apply_route_slice_change(session, state, state->route_slice_buffer)) { + state->editing_route_slice = false; + } + } else if (ImGui::IsKeyPressed(ImGuiKey_Escape)) { + state->editing_route_slice = false; + } else if (deactivated || clicked_elsewhere) { + const std::string trimmed = util::strip(state->route_slice_buffer); + if (trimmed != route_id.display_slice()) { + int begin = 0; + int end = 0; + if (parse_slice_spec(trimmed, &begin, &end)) { + apply_route_slice_change(session, state, trimmed); + } else { + state->status_text = "Canceled route slice edit"; + } + } + state->editing_route_slice = false; + } + x += slice_size.x; + } else { + const bool slice_click = draw_route_chip_text_button( + "##route_slice", slice_text, ImVec2(x, text_y), + route_chip_part_color(2, route_id.slice_explicit), draw_list, + "Segment range"); + if (slice_click) { + state->editing_route_slice = true; + state->focus_route_slice_input = true; + state->route_slice_buffer = route_id.display_slice(); + } + x += slice_size.x; + } + + draw_list->AddText(ImVec2(x, text_y), sep, sep_text.c_str()); + x += sep_size.x; + const bool selector_click = draw_route_chip_text_button( + "##route_selector", selector_text, ImVec2(x, text_y), + route_chip_part_color(3, route_id.selector_explicit), draw_list, + "Log selector"); + if (selector_click) { + ImGui::OpenPopup("##route_selector_popup"); + } + x += selector_size.x + 10.0f; + + const ImVec2 info_center(x + info_size * 0.5f, chip_y + chip_h * 0.5f); + ImGui::SetCursorScreenPos(ImVec2(x, chip_y + (chip_h - info_size) * 0.5f)); + ImGui::InvisibleButton("##route_info_button", ImVec2(info_size, info_size)); + const bool info_hovered = ImGui::IsItemHovered(); + if (info_hovered) { + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + } + draw_list->AddCircleFilled(info_center, info_size * 0.5f, + ImGui::GetColorU32(info_hovered ? color_rgb(220, 229, 240) : color_rgb(239, 243, 248))); + draw_list->AddCircle(info_center, info_size * 0.5f, chip_border, 20, 1.0f); + const char *info_text = icon::INFO_CIRCLE; + const ImVec2 info_text_size = ImGui::CalcTextSize(info_text); + draw_list->AddText(ImVec2(std::floor(info_center.x - info_text_size.x * 0.5f), + std::floor(info_center.y - info_text_size.y * 0.5f)), + route_chip_part_color(0, true), info_text); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayShort)) { + ImGui::BeginTooltip(); + ImGui::TextUnformatted("Route details"); + ImGui::EndTooltip(); + } + if (ImGui::IsItemClicked(ImGuiMouseButton_Left)) { + ImGui::OpenPopup("##route_info_popup"); + } + + app_pop_bold_font(); + + if (dongle_click || log_click) { + ImGui::SetClipboardText(route_id.canonical().c_str()); + state->status_text = "Copied route to clipboard"; + state->route_copy_feedback_text = "Copied"; + state->route_copy_feedback_until = ImGui::GetTime() + 1.1; + } + + ImGui::SetNextWindowPos(ImVec2(chip_max.x - 60.0f, chip_max.y + 4.0f), ImGuiCond_Appearing); + if (app_begin_popup("##route_selector_popup")) { + for (LogSelector selector : {LogSelector::Auto, LogSelector::RLog, LogSelector::QLog}) { + const bool selected = route_id.selector == selector; + const std::string label = std::string(log_selector_name(selector)) + " " + log_selector_description(selector); + if (ImGui::Selectable(label.c_str(), selected) && !selected) { + apply_route_selector_change(session, state, selector); + } + if (selected) { + ImGui::SetItemDefaultFocus(); + } + } + ImGui::EndPopup(); + } + + draw_route_copy_feedback(state, draw_list, chip_max); + draw_route_info_popup(session, state, ImVec2(std::max(window->Pos.x + 16.0f, chip_max.x - 360.0f), chip_max.y + 6.0f)); +} + +std::string format_cache_bytes(uint64_t bytes) { + if (bytes >= (1ULL << 30)) { + return util::string_format("%.1f GiB", static_cast(bytes) / static_cast(1ULL << 30)); + } else if (bytes >= (1ULL << 20)) { + return util::string_format("%.1f MiB", static_cast(bytes) / static_cast(1ULL << 20)); + } else if (bytes >= (1ULL << 10)) { + return util::string_format("%.1f KiB", static_cast(bytes) / static_cast(1ULL << 10)); + } + return util::string_format("%llu B", static_cast(bytes)); +} + +MapCacheStats directory_cache_stats(const fs::path &root) { + MapCacheStats stats; + std::error_code ec; + if (!fs::exists(root, ec)) { + return stats; + } + fs::recursive_directory_iterator it(root, fs::directory_options::skip_permission_denied, ec); + for (const fs::directory_entry &entry : it) { + if (ec) { + ec.clear(); + continue; + } + const fs::file_status status = entry.symlink_status(ec); + if (ec || !fs::is_regular_file(status)) { + ec.clear(); + continue; + } + const uintmax_t size = entry.file_size(ec); + if (!ec) { + stats.bytes += static_cast(size); + ++stats.files; + } else { + ec.clear(); + } + } + return stats; +} + +float draw_main_menu_bar(AppSession *session, UiState *state) { + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(7.0f, 5.0f)); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(9.0f, 6.0f)); + float height = ImGui::GetFrameHeight(); + if (ImGui::BeginMainMenuBar()) { + if (ImGui::BeginMenu("File")) { + if (ImGui::MenuItem("Undo", "Ctrl+Z", false, state->undo.can_undo())) { + apply_undo(session, state); + } + if (ImGui::MenuItem("Redo", "Ctrl+Shift+Z", false, state->undo.can_redo())) { + apply_redo(session, state); + } + ImGui::Separator(); + if (ImGui::MenuItem("Open Route...")) { + state->open_open_route = true; + } + if (ImGui::MenuItem("Stream...")) { + state->open_stream = true; + } + if (ImGui::MenuItem("Find Signal...", "Ctrl+F")) { + state->open_find_signal = true; + } + ImGui::Separator(); + if (ImGui::MenuItem("New Layout")) { + start_new_layout(session, state); + } + if (ImGui::MenuItem("Load Layout...")) { + state->open_load_layout = true; + } + if (ImGui::MenuItem("Save Layout")) { + state->request_save_layout = true; + } + if (ImGui::MenuItem("Save Layout As...")) { + state->open_save_layout = true; + } + if (ImGui::MenuItem("Reset Layout")) { + state->request_reset_layout = true; + } + ImGui::Separator(); + if (ImGui::MenuItem("Show DEPRECATED Fields", nullptr, state->show_deprecated_fields)) { + state->show_deprecated_fields = !state->show_deprecated_fields; + rebuild_browser_nodes(session, state); + } + if (ImGui::MenuItem("Show FPS", nullptr, state->show_fps_overlay)) { + state->show_fps_overlay = !state->show_fps_overlay; + } + if (ImGui::MenuItem("Preferences...")) { + state->open_preferences = true; + } + ImGui::Separator(); + if (ImGui::MenuItem("Reset Plot View")) { + reset_shared_range(state, *session); + state->follow_latest = session->data_mode == SessionDataMode::Stream; + clamp_shared_range(state, *session); + state->suppress_range_side_effects = true; + state->status_text = "Plot view reset"; + } + ImGui::Separator(); + if (ImGui::MenuItem("Close")) { + state->request_close = true; + } + ImGui::EndMenu(); + } + ImGui::SameLine(0.0f, 8.0f); + draw_route_id_chip(session, state); + height = ImGui::GetWindowSize().y; + ImGui::EndMainMenuBar(); + } + ImGui::PopStyleVar(2); + return height; +} diff --git a/openpilot/tools/jotpluggler/sidebar.cc b/openpilot/tools/jotpluggler/sidebar.cc new file mode 100644 index 0000000000..c120b47908 --- /dev/null +++ b/openpilot/tools/jotpluggler/sidebar.cc @@ -0,0 +1,215 @@ +#include "tools/jotpluggler/internal.h" + +std::string dbc_combo_label(const AppSession &session) { + if (!session.dbc_override.empty()) return session.dbc_override; + if (!session.route_data.dbc_name.empty()) return "Auto: " + session.route_data.dbc_name; + return "Auto"; +} + +float timeline_time_to_x(double time_value, double route_min, double route_max, float x_min, float x_max) { + const double span = route_max - route_min; + if (span <= 0.0) { + return x_min; + } + const double ratio = (time_value - route_min) / span; + return x_min + static_cast(ratio * static_cast(x_max - x_min)); +} + +double timeline_x_to_time(float x, double route_min, double route_max, float x_min, float x_max) { + const float width = std::max(1.0f, x_max - x_min); + const float clamped_x = std::clamp(x, x_min, x_max); + const double ratio = static_cast((clamped_x - x_min) / width); + return route_min + ratio * (route_max - route_min); +} + +void reset_timeline_view(UiState *state, const AppSession &session) { + state->follow_latest = session.data_mode == SessionDataMode::Stream; + reset_shared_range(state, session); +} + +void draw_timeline_bar_contents(const AppSession &session, UiState *state, float width) { + if (!session.route_data.has_time_range) { + ImGui::Dummy(ImVec2(width, TIMELINE_BAR_HEIGHT)); + return; + } + + const ImVec2 cursor = ImGui::GetCursorScreenPos(); + const ImVec2 size(width, TIMELINE_BAR_HEIGHT); + const ImVec2 bar_min(cursor.x + 1.0f, cursor.y + 1.0f); + const ImVec2 bar_max(cursor.x + size.x - 1.0f, cursor.y + size.y - 1.0f); + const double route_min = state->route_x_min; + const double route_max = state->route_x_max; + const float vp_left = timeline_time_to_x(std::clamp(state->x_view_min, route_min, route_max), + route_min, route_max, bar_min.x, bar_max.x); + const float vp_right = timeline_time_to_x(std::clamp(state->x_view_max, route_min, route_max), + route_min, route_max, bar_min.x, bar_max.x); + + ImGui::InvisibleButton("##timeline_button", size); + const bool hovered = ImGui::IsItemHovered(); + const bool active = ImGui::IsItemActive(); + const bool double_clicked = hovered && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left); + ImDrawList *draw_list = ImGui::GetWindowDrawList(); + + draw_list->AddRectFilled(bar_min, bar_max, timeline_entry_color(TimelineEntry::Type::None, 0.2f)); + if (session.route_data.timeline.empty()) { + draw_list->AddRectFilled(ImVec2(vp_left, bar_min.y), ImVec2(vp_right, bar_max.y), + timeline_entry_color(TimelineEntry::Type::None, 1.0f)); + } else { + for (const TimelineEntry &entry : session.route_data.timeline) { + float x0 = timeline_time_to_x(entry.start_time, route_min, route_max, bar_min.x, bar_max.x); + float x1 = timeline_time_to_x(entry.end_time, route_min, route_max, bar_min.x, bar_max.x); + x1 = std::max(x1, x0 + 1.0f); + draw_list->AddRectFilled(ImVec2(x0, bar_min.y), ImVec2(x1, bar_max.y), + timeline_entry_color(entry.type, 0.25f)); + } + for (const TimelineEntry &entry : session.route_data.timeline) { + float x0 = std::max(timeline_time_to_x(entry.start_time, route_min, route_max, bar_min.x, bar_max.x), vp_left); + float x1 = std::min(std::max(timeline_time_to_x(entry.end_time, route_min, route_max, bar_min.x, bar_max.x), x0 + 1.0f), vp_right); + if (x1 <= x0) { + continue; + } + draw_list->AddRectFilled(ImVec2(x0, bar_min.y), ImVec2(x1, bar_max.y), + timeline_entry_color(entry.type, 1.0f)); + } + } + + draw_list->AddLine(ImVec2(vp_left, bar_min.y), ImVec2(vp_left, bar_max.y), IM_COL32(60, 70, 80, 200), 1.0f); + draw_list->AddLine(ImVec2(vp_right, bar_min.y), ImVec2(vp_right, bar_max.y), IM_COL32(60, 70, 80, 200), 1.0f); + if (state->has_tracker_time) { + const float cx = timeline_time_to_x(std::clamp(state->tracker_time, route_min, route_max), + route_min, route_max, bar_min.x, bar_max.x); + draw_list->AddLine(ImVec2(cx, bar_min.y), ImVec2(cx, bar_max.y), IM_COL32(220, 60, 50, 255), 1.5f); + } + draw_list->AddRect(bar_min, bar_max, IM_COL32(170, 178, 186, 255), 0.0f, 0, 1.0f); + + const float edge_grab = 4.0f; + const float mouse_x = ImGui::GetIO().MousePos.x; + const double mouse_time = timeline_x_to_time(mouse_x, route_min, route_max, bar_min.x, bar_max.x); + if (double_clicked) { + reset_timeline_view(state, session); + } else if (hovered && ImGui::IsMouseClicked(ImGuiMouseButton_Left)) { + state->timeline_drag_anchor_time = mouse_time; + state->timeline_drag_anchor_x_min = state->x_view_min; + state->timeline_drag_anchor_x_max = state->x_view_max; + if (std::abs(mouse_x - vp_left) <= edge_grab) { + state->timeline_drag_mode = TimelineDragMode::ResizeLeft; + } else if (std::abs(mouse_x - vp_right) <= edge_grab) { + state->timeline_drag_mode = TimelineDragMode::ResizeRight; + } else if (mouse_x >= vp_left && mouse_x <= vp_right) { + state->timeline_drag_mode = TimelineDragMode::PanViewport; + } else { + state->timeline_drag_mode = TimelineDragMode::ScrubCursor; + state->tracker_time = std::clamp(mouse_time, route_min, route_max); + state->has_tracker_time = true; + } + } + + if (!ImGui::IsMouseDown(ImGuiMouseButton_Left)) { + state->timeline_drag_mode = TimelineDragMode::None; + } else if (active || state->timeline_drag_mode != TimelineDragMode::None) { + switch (state->timeline_drag_mode) { + case TimelineDragMode::ScrubCursor: + state->tracker_time = std::clamp(mouse_time, route_min, route_max); + state->has_tracker_time = true; + break; + case TimelineDragMode::PanViewport: { + const double delta = mouse_time - state->timeline_drag_anchor_time; + state->x_view_min = state->timeline_drag_anchor_x_min + delta; + state->x_view_max = state->timeline_drag_anchor_x_max + delta; + clamp_shared_range(state, session); + break; + } + case TimelineDragMode::ResizeLeft: + state->x_view_min = std::min(mouse_time, state->x_view_max - MIN_HORIZONTAL_ZOOM_SECONDS); + clamp_shared_range(state, session); + break; + case TimelineDragMode::ResizeRight: + state->x_view_max = std::max(mouse_time, state->x_view_min + MIN_HORIZONTAL_ZOOM_SECONDS); + clamp_shared_range(state, session); + break; + case TimelineDragMode::None: + break; + } + } + + if (hovered) { + if (std::abs(mouse_x - vp_left) <= edge_grab || std::abs(mouse_x - vp_right) <= edge_grab) { + ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeEW); + } else if (mouse_x >= vp_left && mouse_x <= vp_right) { + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + } + ImGui::BeginTooltip(); + ImGui::Text("t=%.1fs — %s", mouse_time, timeline_entry_label(timeline_type_at_time(session.route_data.timeline, mouse_time))); + ImGui::EndTooltip(); + } +} + +void draw_status_bar(const AppSession &session, const UiMetrics &ui, UiState *state) { + ImGui::SetNextWindowPos(ImVec2(ui.content_x, ui.status_bar_y)); + ImGui::SetNextWindowSize(ImVec2(ui.content_w, STATUS_BAR_HEIGHT)); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); + ImGui::PushStyleColor(ImGuiCol_WindowBg, color_rgb(247, 248, 250)); + ImGui::PushStyleColor(ImGuiCol_Border, color_rgb(188, 193, 199)); + const ImGuiWindowFlags flags = ImGuiWindowFlags_NoDecoration | + ImGuiWindowFlags_NoMove | + ImGuiWindowFlags_NoResize | + ImGuiWindowFlags_NoSavedSettings; + if (ImGui::Begin("##status_bar", nullptr, flags)) { + draw_timeline_bar_contents(session, state, ui.content_w); + const float row_y = TIMELINE_BAR_HEIGHT + 8.0f; + ImGui::SetCursorPos(ImVec2(8.0f, row_y)); + ImGui::BeginDisabled(!session.route_data.has_time_range); + ImGui::Checkbox("Loop", &state->playback_loop); + ImGui::SameLine(0.0f, 10.0f); + if (ImGui::Button(state->playback_playing ? "Pause" : "Play", ImVec2(56.0f, 0.0f))) { + state->playback_playing = !state->playback_playing; + } + ImGui::SameLine(0.0f, 10.0f); + if (ImGui::Button("Reset View", ImVec2(86.0f, 0.0f))) { + reset_timeline_view(state, session); + } + const float controls_end_x = ImGui::GetItemRectMax().x - ImGui::GetWindowPos().x; + ImGui::EndDisabled(); + + const char *status_text = state->status_text.empty() ? "Ready" : state->status_text.c_str(); + const float status_x = controls_end_x + 16.0f; + ImGui::SetCursorPos(ImVec2(status_x, row_y + 2.0f)); + ImGui::PushStyleColor(ImGuiCol_Text, color_rgb(102, 110, 118)); + ImGui::TextUnformatted(status_text); + ImGui::PopStyleColor(); + + } + ImGui::End(); + ImGui::PopStyleColor(2); + ImGui::PopStyleVar(); +} + +void draw_sidebar_resizer(const UiMetrics &ui, UiState *state) { + constexpr float kHandleWidth = 14.0f; + ImGui::SetNextWindowPos(ImVec2(ui.sidebar_width - kHandleWidth * 0.5f, ui.top_offset)); + ImGui::SetNextWindowSize(ImVec2(kHandleWidth, std::max(1.0f, ui.height - ui.top_offset))); + const ImGuiWindowFlags flags = ImGuiWindowFlags_NoDecoration | + ImGuiWindowFlags_NoMove | + ImGuiWindowFlags_NoResize | + ImGuiWindowFlags_NoSavedSettings | + ImGuiWindowFlags_NoBackground; + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); + if (ImGui::Begin("##sidebar_resizer", nullptr, flags)) { + ImGui::InvisibleButton("##sidebar_resizer_button", ImVec2(kHandleWidth, std::max(1.0f, ui.height - ui.top_offset))); + if (ImGui::IsItemHovered() || ImGui::IsItemActive()) { + ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeEW); + } + if (ImGui::IsItemActive()) { + const float max_width = std::min(SIDEBAR_MAX_WIDTH, ui.width * 0.6f); + state->sidebar_width = std::clamp(ImGui::GetIO().MousePos.x, SIDEBAR_MIN_WIDTH, max_width); + } + + ImDrawList *draw_list = ImGui::GetWindowDrawList(); + const ImVec2 origin = ImGui::GetWindowPos(); + draw_list->AddLine(ImVec2(origin.x + kHandleWidth * 0.5f, origin.y), + ImVec2(origin.x + kHandleWidth * 0.5f, origin.y + std::max(1.0f, ui.height - ui.top_offset)), + IM_COL32(194, 198, 204, 255)); + } + ImGui::End(); + ImGui::PopStyleVar(); +} diff --git a/openpilot/tools/jotpluggler/sketch_layout.cc b/openpilot/tools/jotpluggler/sketch_layout.cc new file mode 100644 index 0000000000..1f7df72fed --- /dev/null +++ b/openpilot/tools/jotpluggler/sketch_layout.cc @@ -0,0 +1,1944 @@ +#include "tools/jotpluggler/app.h" +#include "tools/jotpluggler/car_fingerprint_to_dbc.h" +#include "tools/jotpluggler/common.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "common/util.h" +#include "json11/json11.hpp" +#include "tools/replay/logreader.h" +#include "tools/replay/py_downloader.h" + +namespace fs = std::filesystem; + +namespace { + +struct RouteSelection { + std::string dongle_id; + std::string timestamp; + int begin_segment = 0; + int end_segment = -1; + bool slice_explicit = false; + LogSelector selector = LogSelector::Auto; + bool selector_explicit = false; + std::string canonical_name; +}; + +struct SegmentLogs { + std::string rlog; + std::string qlog; + std::string fcamera; + std::string dcamera; + std::string ecamera; + std::string qcamera; +}; + +struct SchemaIndex { + size_t fixed_series_count = 0; + std::vector fixed_paths; + + static const SchemaIndex &instance(); +}; + +constexpr size_t INVALID_DYNAMIC_SLOT = std::numeric_limits::max(); + +struct SeriesAccumulator { + explicit SeriesAccumulator(size_t fixed_count = 0) : fixed_series(fixed_count) {} + + std::vector fixed_series; + std::vector dynamic_series; + std::vector can_messages; + std::unordered_map dynamic_slots; + std::unordered_map> list_scalar_slots; + std::unordered_map can_message_slots; + std::unordered_map enum_info; +}; + +void append_fixed_scalar_point(RouteSeries *series, double tm, double value); +void append_dynamic_scalar_point(const std::string &path, double tm, double value, SeriesAccumulator *series); +RouteSeries *ensure_list_scalar_series(const std::string &base_path, size_t index, SeriesAccumulator *series); +void append_can_frame(CanServiceKind service, + uint8_t bus, + uint32_t address, + uint16_t bus_time, + capnp::Data::Reader dat, + double tm, + SeriesAccumulator *series); +void decode_can_frame(const dbc::Database *can_dbc, + const std::string &service_name, + uint8_t bus, + uint32_t address, + const uint8_t *raw, + size_t data_size, + double tm, + SeriesAccumulator *series); + +#include "tools/jotpluggler/generated_event_extractors.h" + +struct LoadedRouteArtifacts { + std::vector series; + std::vector can_messages; + std::vector logs; + std::vector timeline; + std::vector thumbnails; + std::unordered_map enum_info; +}; + +struct RouteMetadata { + std::string car_fingerprint; +}; + +struct LoadStats { + using Clock = std::chrono::steady_clock; + using TimePoint = Clock::time_point; + + struct SegmentStats { + int segment_number = -1; + std::string log_path; + double download_seconds = 0.0; + double decompress_seconds = 0.0; + double parse_seconds = 0.0; + double extract_seconds = 0.0; + size_t compressed_bytes = 0; + size_t decompressed_bytes = 0; + size_t event_count = 0; + size_t series_count = 0; + bool failed = false; + }; + + explicit LoadStats(const RouteLoadProgressCallback &callback) : progress(callback) {} + + void publish(RouteLoadStage stage, size_t segment_index, const std::string &segment_name) { + if (!progress) { + return; + } + RouteLoadProgress update; + update.stage = stage; + update.segment_index = segment_index; + update.segment_count = segment_count; + update.current = stage == RouteLoadStage::DownloadingSegment + ? segments_downloaded.load() + : segments_parsed.load(); + update.total = total_segments.load(); + update.segments_downloaded = segments_downloaded.load(); + update.segments_parsed = segments_parsed.load(); + update.total_segments = total_segments.load(); + update.bytes_downloaded = bytes_downloaded.load(); + update.num_workers = num_workers; + update.segment_name = segment_name; + std::lock_guard lock(progress_mutex); + progress(update); + } + + void print_summary(size_t final_series_count) const { + const auto secs = [](TimePoint a, TimePoint b) { return std::chrono::duration(b - a).count(); }; + const auto mb = [](size_t bytes) { return static_cast(bytes) / (1024.0 * 1024.0); }; + double dl = 0, dc = 0, pa = 0, ex = 0; + size_t ev = 0, cb = 0, db = 0; + for (const auto &s : segments) { + dl += s.download_seconds; dc += s.decompress_seconds; + pa += s.parse_seconds; ex += s.extract_seconds; + ev += s.event_count; cb += s.compressed_bytes; db += s.decompressed_bytes; + } + std::cerr << std::fixed << std::setprecision(1) + << "route loaded in " << secs(load_start, load_end) << "s (" << segment_count << " segments, " << num_workers << " workers)\n" + << " resolve: " << secs(load_start, resolve_end) << "s fetch: " << dl << "s (" << mb(cb) << " MB)" + << " decompress: " << dc << "s (" << mb(db) << " MB)\n" + << " parse: " << pa << "s (" << ev << " events) extract: " << ex << "s merge: " << secs(merge_start, merge_end) << "s" + << " series: " << final_series_count << " paths\n"; + for (const auto &s : segments) { + std::cerr << " seg " << std::setw(2) << s.segment_number << ": " + << (s.failed ? "FAILED" : std::to_string(s.download_seconds) + "s + " + std::to_string(s.parse_seconds) + + "s (" + std::to_string(s.event_count) + " ev, " + std::to_string(s.series_count) + " series)") << "\n"; + } + std::cerr.unsetf(std::ios::floatfield); + } + + TimePoint load_start; + TimePoint resolve_end; + TimePoint merge_start; + TimePoint merge_end; + TimePoint load_end; + size_t segment_count = 0; + int num_workers = 1; + std::vector segments; + std::atomic segments_downloaded{0}; + std::atomic segments_parsed{0}; + std::atomic total_segments{0}; + std::atomic bytes_downloaded{0}; + RouteLoadProgressCallback progress; + mutable std::mutex progress_mutex; +}; + +// Skip individual messages that our local Cap'n Proto schema can't project, +// such as logs recorded by a newer build. +template +void with_parseable_event(kj::ArrayPtr data, Fn &&fn) { + try { + capnp::FlatArrayMessageReader event_reader(data); + fn(event_reader.getRoot()); + } catch (const kj::Exception &) { + return; + } +} + +std::string curve_label(std::string_view series_name) { + return std::string(series_name.empty() ? std::string_view{"plot"} : series_name); +} + +bool parse_segment_number(std::string_view value, int *out) { + if (value.empty()) return false; + char *end = nullptr; + const long parsed = std::strtol(std::string(value).c_str(), &end, 10); + if (end == nullptr || *end != '\0') return false; + *out = static_cast(parsed); + return true; +} + +bool is_log_selector_char(char c) { + return c == 'a' || c == 'r' || c == 'q'; +} + +LogSelector parse_log_selector_char(char c) { + switch (c) { + case 'r': return LogSelector::RLog; + case 'q': return LogSelector::QLog; + case 'a': + default: return LogSelector::Auto; + } +} + +const std::string &selected_log_path(const SegmentLogs &segment, LogSelector selector) { + switch (selector) { + case LogSelector::RLog: + return segment.rlog; + case LogSelector::QLog: + return segment.qlog; + case LogSelector::Auto: + default: + return !segment.rlog.empty() ? segment.rlog : segment.qlog; + } +} + +RouteSelection parse_route_selection(std::string route_name) { + RouteSelection route = {}; + route_name = util::strip(route_name); + if (route_name.size() >= 2 && route_name[route_name.size() - 2] == '/' + && is_log_selector_char(static_cast(std::tolower(route_name.back())))) { + route.selector = parse_log_selector_char(static_cast(std::tolower(route_name.back()))); + route.selector_explicit = true; + route_name.resize(route_name.size() - 2); + } + static const std::regex pattern(R"(^(([a-z0-9]{16})[|_/])?(.{20})((--|/)((-?\d+(:(-?\d+)?)?)|(:-?\d+)))?$)"); + std::smatch match; + if (!std::regex_match(route_name, match, pattern)) return route; + + route.dongle_id = match[2].str(); + route.timestamp = match[3].str(); + route.canonical_name = route.dongle_id + "|" + route.timestamp; + + const std::string separator = match[5].str(); + const std::string range_str = match[6].str(); + if (!range_str.empty()) { + route.slice_explicit = true; + if (separator == "/") { + size_t pos = range_str.find(':'); + int begin_segment = 0; + if (!parse_segment_number(range_str.substr(0, pos), &begin_segment)) { + return {}; + } + route.begin_segment = begin_segment; + route.end_segment = begin_segment; + if (pos != std::string::npos) { + int end_segment = -1; + const std::string end_str = range_str.substr(pos + 1); + if (!end_str.empty() && !parse_segment_number(end_str, &end_segment)) { + return {}; + } + route.end_segment = end_str.empty() ? -1 : end_segment; + } + } else if (separator == "--") { + int begin_segment = 0; + if (!parse_segment_number(range_str, &begin_segment)) return {}; + route.begin_segment = begin_segment; + } + } + return route; +} + +void add_log_file_to_segments(std::map *segments, int segment_number, const std::string &file) { + std::string name = extractFileName(file); + const size_t pos = name.find_last_of("--"); + name = pos != std::string::npos ? name.substr(pos + 2) : name; + SegmentLogs &segment = (*segments)[segment_number]; + if (name == "rlog.bz2" || name == "rlog.zst" || name == "rlog") { + segment.rlog = file; + } else if (name == "qlog.bz2" || name == "qlog.zst" || name == "qlog") { + segment.qlog = file; + } else if (name == "fcamera.hevc") { + segment.fcamera = file; + } else if (name == "dcamera.hevc") { + segment.dcamera = file; + } else if (name == "ecamera.hevc") { + segment.ecamera = file; + } else if (name == "qcamera.ts") { + segment.qcamera = file; + } +} + +std::map trim_segments(std::map segments, const RouteSelection &route) { + if (route.begin_segment > 0) { + segments.erase(segments.begin(), segments.lower_bound(route.begin_segment)); + } + if (route.end_segment >= 0) { + segments.erase(segments.upper_bound(route.end_segment), segments.end()); + } + return segments; +} + +std::map load_segments_from_json(const json11::Json &json) { + std::map segments; + static const std::regex rx(R"(\/(\d+)\/)"); + for (const auto &value : json.object_items()) { + for (const auto &url : value.second.array_items()) { + const std::string url_str = url.string_value(); + std::smatch match; + if (!std::regex_search(url_str, match, rx)) continue; + add_log_file_to_segments(&segments, std::stoi(match[1].str()), url_str); + } + } + return segments; +} + +std::map load_segments_from_server(const RouteSelection &route) { + const std::string result = PyDownloader::getRouteFiles(route.canonical_name); + if (result.empty()) throw std::runtime_error("Failed to fetch route files for " + route.canonical_name); + + std::string parse_error; + const auto json = json11::Json::parse(result, parse_error); + if (!parse_error.empty()) throw std::runtime_error("Failed to parse route file list for " + route.canonical_name); + if (json.is_object() && json["error"].is_string()) { + throw std::runtime_error("Route API error for " + route.canonical_name + ": " + json["error"].string_value()); + } + return load_segments_from_json(json); +} + +std::map load_segments_from_local(const RouteSelection &route, const std::string &data_dir) { + std::map segments; + const std::string pattern = route.timestamp + "--"; + for (const auto &entry : fs::directory_iterator(data_dir)) { + if (!entry.is_directory()) continue; + const std::string dirname = entry.path().filename().string(); + if (dirname.find(pattern) == std::string::npos) continue; + const size_t marker = dirname.rfind("--"); + if (marker == std::string::npos) continue; + int segment_number = 0; + if (!parse_segment_number(dirname.substr(marker + 2), &segment_number)) { + continue; + } + for (const auto &file : fs::directory_iterator(entry.path())) { + if (file.is_regular_file()) { + add_log_file_to_segments(&segments, segment_number, file.path().string()); + } + } + } + return segments; +} + +RouteIdentifier make_route_identifier(const RouteSelection &route, const std::map &segments) { + RouteIdentifier route_id; + route_id.dongle_id = route.dongle_id; + route_id.log_id = route.timestamp; + route_id.slice_begin = route.begin_segment; + route_id.slice_end = route.end_segment; + route_id.slice_explicit = route.slice_explicit; + route_id.selector = route.selector; + route_id.selector_explicit = route.selector_explicit; + if (!segments.empty()) { + route_id.available_begin = segments.begin()->first; + route_id.available_end = segments.rbegin()->first; + } + return route_id; +} + +std::string detect_dbc_for_fingerprint(std::string_view car_fingerprint) { + return std::string(dbc_for_car_fingerprint(car_fingerprint)); +} + +std::vector available_dbc_names_impl() { + std::set names; + for (const fs::path &dbc_dir : { + repo_root() / "opendbc_repo" / "opendbc" / "dbc", + repo_root() / "openpilot" / "tools" / "jotpluggler" / "generated_dbcs", + }) { + if (fs::exists(dbc_dir) && fs::is_directory(dbc_dir)) { + for (const auto &entry : fs::directory_iterator(dbc_dir)) { + if (!entry.is_regular_file() || entry.path().extension() != ".dbc") { + continue; + } + names.insert(entry.path().stem().string()); + } + } + } + for (const auto &[_, dbc_name] : kCarFingerprintToDbc) { + if (!dbc_name.empty()) { + names.insert(std::string(dbc_name)); + } + } + return std::vector(names.begin(), names.end()); +} + +fs::path resolve_dbc_path(const std::string &dbc_name) { + for (const fs::path &candidate : { + repo_root() / "opendbc_repo" / "opendbc" / "dbc" / (dbc_name + ".dbc"), + repo_root() / "openpilot" / "tools" / "jotpluggler" / "generated_dbcs" / (dbc_name + ".dbc"), + }) { + if (fs::exists(candidate)) return candidate; + } + throw std::runtime_error("DBC not found: " + dbc_name); +} + +std::array parse_color(std::string_view color) { + if (!color.empty() && color.front() == '#') { + color.remove_prefix(1); + } + if (color.size() != 6) return {160, 170, 180}; + + std::array out = {}; + for (size_t i = 0; i < 3; ++i) { + const std::string byte(color.substr(i * 2, 2)); + char *end = nullptr; + const long parsed = std::strtol(byte.c_str(), &end, 16); + if (end == nullptr || *end != '\0' || parsed < 0 || parsed > 255) return {160, 170, 180}; + out[i] = static_cast(parsed); + } + return out; +} + +uint8_t operating_system_priority_to_level(uint8_t priority) { + switch (priority) { + case 2: + case 3: + return 10; + case 4: + return 20; + case 5: + return 30; + case 6: + return 40; + case 7: + default: + return 50; + } +} + +uint8_t alert_status_to_level(cereal::SelfdriveState::AlertStatus status) { + switch (status) { + case cereal::SelfdriveState::AlertStatus::NORMAL: + return 20; + case cereal::SelfdriveState::AlertStatus::USER_PROMPT: + return 30; + case cereal::SelfdriveState::AlertStatus::CRITICAL: + return 40; + } + return 20; +} + +TimelineEntry::Type alert_status_to_timeline_type(cereal::SelfdriveState::AlertStatus status, bool enabled) { + if (!enabled) { + return TimelineEntry::Type::None; + } + switch (status) { + case cereal::SelfdriveState::AlertStatus::NORMAL: + return TimelineEntry::Type::Engaged; + case cereal::SelfdriveState::AlertStatus::USER_PROMPT: + return TimelineEntry::Type::AlertInfo; + case cereal::SelfdriveState::AlertStatus::CRITICAL: + return TimelineEntry::Type::AlertCritical; + } + return TimelineEntry::Type::Engaged; +} + +void append_timeline_entry(std::vector *timeline, double mono_time, TimelineEntry::Type type) { + if (timeline == nullptr) { + return; + } + if (!timeline->empty() && timeline->back().type == type) { + timeline->back().end_time = std::max(timeline->back().end_time, mono_time); + return; + } + timeline->push_back(TimelineEntry{ + .start_time = mono_time, + .end_time = mono_time, + .type = type, + }); +} + +double operating_system_wall_time_seconds(uint64_t timestamp) { + if (timestamp == 0) return 0.0; + if (timestamp > 1000000000000ULL) return static_cast(timestamp) / 1.0e9; + if (timestamp > 1000000000ULL) return static_cast(timestamp) / 1.0e6; + return static_cast(timestamp); +} + +std::optional json_u64_value(const json11::Json &value) { + if (value.is_number()) { + const double number = value.number_value(); + if (number >= 0.0) return static_cast(number); + } + if (value.is_string()) { + try { + return static_cast(std::stoull(value.string_value())); + } catch (...) { + } + } + return std::nullopt; +} + +std::optional json_int_value(const json11::Json &value) { + if (value.is_number()) return value.int_value(); + if (value.is_string()) { + try { + return std::stoi(value.string_value()); + } catch (...) { + } + } + return std::nullopt; +} + +std::string json_value_for_log(const json11::Json &value) { + if (value.is_string()) return value.string_value(); + if (value.is_bool()) return value.bool_value() ? "true" : "false"; + return value.dump(); +} + +std::string format_journal_context(const json11::Json &parsed, int pid, int tid) { + std::vector lines; + if (pid != 0 || tid != 0) { + lines.push_back("pid=" + std::to_string(pid) + ", tid=" + std::to_string(tid)); + } + + const std::array preferred_keys = { + "_HOSTNAME", + "_TRANSPORT", + "PRIORITY", + "SYSLOG_FACILITY", + "__MONOTONIC_TIMESTAMP", + }; + for (const char *key : preferred_keys) { + const json11::Json &value = parsed[key]; + if (!value.is_null()) { + lines.push_back(std::string(key) + "=" + json_value_for_log(value)); + } + } + return join(lines, "\n"); +} + +std::string alert_message_text(const cereal::SelfdriveState::Reader &state) { + std::string text = state.getAlertText1().cStr(); + const std::string text2 = state.getAlertText2().cStr(); + if (!text2.empty()) { + text += " - " + text2; + } + return text; +} + +bool same_log_entry(const LogEntry &a, const LogEntry &b) { + return a.mono_time == b.mono_time + && a.level == b.level + && a.source == b.source + && a.func == b.func + && a.message == b.message + && a.context == b.context + && a.origin == b.origin; +} + +void append_log_event(cereal::Event::Which which, + const cereal::Event::Reader &event, + double time_offset, + std::vector *logs, + std::string *last_alert_key) { + const double boot_time = static_cast(event.getLogMonoTime()) / 1.0e9; + const double mono_time = boot_time - time_offset; + + auto make_entry = [&](LogOrigin origin, uint8_t level = 20) { + LogEntry e; + e.mono_time = mono_time; + e.boot_time = boot_time; + e.origin = origin; + e.level = level; + return e; + }; + + switch (which) { + case cereal::Event::Which::LOG_MESSAGE: + case cereal::Event::Which::ERROR_LOG_MESSAGE: { + const std::string raw = which == cereal::Event::Which::LOG_MESSAGE + ? event.getLogMessage().cStr() : event.getErrorLogMessage().cStr(); + auto entry = make_entry(LogOrigin::Log, which == cereal::Event::Which::ERROR_LOG_MESSAGE ? 40 : 20); + entry.source = "log"; + entry.message = raw; + std::string err; + if (const auto p = json11::Json::parse(raw, err); err.empty() && p.is_object()) { + entry.wall_time = p["created"].number_value(); + if (p["levelnum"].is_number()) entry.level = static_cast(p["levelnum"].int_value()); + const std::string fn = p["filename"].string_value(); + const int ln = p["lineno"].is_number() ? p["lineno"].int_value() : 0; + entry.source = fn.empty() ? "log" : fn + (ln > 0 ? ":" + std::to_string(ln) : ""); + entry.func = p["funcname"].string_value(); + if (p["msg"].is_string()) entry.message = p["msg"].string_value(); + if (!p["ctx"].is_null()) entry.context = p["ctx"].dump(); + } + logs->push_back(std::move(entry)); + break; + } + case cereal::Event::Which::OPERATING_SYSTEM_LOG: { + const auto operating_system_log = event.getOperatingSystemLog(); + auto entry = make_entry(LogOrigin::OperatingSystem, operating_system_priority_to_level(operating_system_log.getPriority())); + entry.wall_time = operating_system_wall_time_seconds(operating_system_log.getTs()); + entry.source = operating_system_log.hasTag() ? operating_system_log.getTag().cStr() : "operating_system"; + entry.message = operating_system_log.hasMessage() ? operating_system_log.getMessage().cStr() : std::string(); + entry.context = "pid=" + std::to_string(operating_system_log.getPid()) + ", tid=" + std::to_string(operating_system_log.getTid()); + if (!entry.message.empty()) { + std::string err; + if (const auto p = json11::Json::parse(entry.message, err); err.empty() && p.is_object()) { + if (p["MESSAGE"].is_string()) entry.message = p["MESSAGE"].string_value(); + if (p["SYSLOG_IDENTIFIER"].is_string() && !p["SYSLOG_IDENTIFIER"].string_value().empty()) + entry.source = p["SYSLOG_IDENTIFIER"].string_value(); + if (auto pri = json_int_value(p["PRIORITY"]); pri.has_value()) + entry.level = operating_system_priority_to_level(*pri); + if (auto ts = json_u64_value(p["__REALTIME_TIMESTAMP"]); ts.has_value()) + entry.wall_time = operating_system_wall_time_seconds(*ts); + entry.context = format_journal_context(p, operating_system_log.getPid(), operating_system_log.getTid()); + } + } + logs->push_back(std::move(entry)); + break; + } + case cereal::Event::Which::SELFDRIVE_STATE: { + const auto sd = event.getSelfdriveState(); + const std::string alert_type = sd.getAlertType().cStr(); + const std::string alert_text1 = sd.getAlertText1().cStr(); + if (alert_text1.empty() && alert_type.empty()) break; + const std::string key = alert_type + "\n" + alert_text1 + "\n" + std::string(sd.getAlertText2().cStr()); + if (last_alert_key != nullptr && key == *last_alert_key) break; + if (last_alert_key != nullptr) *last_alert_key = key; + auto entry = make_entry(LogOrigin::Alert, alert_status_to_level(sd.getAlertStatus())); + entry.source = "alert"; + entry.func = alert_type; + entry.message = alert_message_text(sd); + logs->push_back(std::move(entry)); + break; + } + default: + break; + } +} + +std::vector extract_segment_timeline(const std::vector &events) { + std::vector timeline; + timeline.reserve(events.size() / 16); + + for (const Event &event_record : events) { + if (event_record.which != cereal::Event::Which::SELFDRIVE_STATE) { + continue; + } + with_parseable_event(event_record.data, [&](const cereal::Event::Reader &event) { + const auto sd = event.getSelfdriveState(); + const double mono_time = static_cast(event.getLogMonoTime()) / 1.0e9; + append_timeline_entry(&timeline, mono_time, alert_status_to_timeline_type(sd.getAlertStatus(), sd.getEnabled())); + }); + } + + return timeline; +} + +std::vector extract_segment_logs(const std::vector &events) { + std::vector logs; + logs.reserve(events.size() / 8); + std::string last_alert_key; + + for (const Event &event_record : events) { + with_parseable_event(event_record.data, [&](const cereal::Event::Reader &event) { + append_log_event(event_record.which, event, 0.0, &logs, &last_alert_key); + }); + } + + return logs; +} + +std::vector extract_segment_thumbnails(const std::vector &events, int segment) { + std::vector thumbnails; + for (const Event &event_record : events) { + if (event_record.which != cereal::Event::Which::THUMBNAIL) continue; + with_parseable_event(event_record.data, [&](const cereal::Event::Reader &event) { + const auto thumbnail = event.getThumbnail(); + const auto jpeg = thumbnail.getThumbnail(); + if (jpeg.size() == 0) return; + const uint64_t timestamp = thumbnail.getTimestampEof(); + ThumbnailFrame frame; + frame.timestamp = static_cast(timestamp != 0 ? timestamp : event.getLogMonoTime()) / 1.0e9; + frame.segment = segment; + frame.jpeg.assign(jpeg.begin(), jpeg.end()); + thumbnails.push_back(std::move(frame)); + }); + } + return thumbnails; +} + +RouteMetadata extract_segment_metadata(const std::vector &events) { + RouteMetadata metadata; + for (const Event &event_record : events) { + if (event_record.which != cereal::Event::Which::CAR_PARAMS) continue; + with_parseable_event(event_record.data, [&](const cereal::Event::Reader &event) { + metadata.car_fingerprint = event.getCarParams().getCarFingerprint().cStr(); + }); + if (!metadata.car_fingerprint.empty()) break; + } + return metadata; +} + +RouteMetadata detect_route_metadata(const std::map &segments, LogSelector selector) { + for (const auto &[_, segment] : segments) { + const std::string &log_path = selector == LogSelector::Auto + ? (!segment.qlog.empty() ? segment.qlog : segment.rlog) + : selected_log_path(segment, selector); + if (log_path.empty()) { + continue; + } + LogReader reader; + if (!reader.load(log_path, nullptr, true)) continue; + RouteMetadata metadata = extract_segment_metadata(reader.events); + if (!metadata.car_fingerprint.empty()) return metadata; + } + return {}; +} + +std::vector normalize_sizes(const json11::Json &sizes_json, size_t child_count) { + std::vector parsed; + if (sizes_json.is_array()) { + for (const json11::Json &value : sizes_json.array_items()) { + if (value.is_number()) { + parsed.push_back(std::max(value.number_value(), 0.0)); + } + } + } + + if (parsed.size() != child_count || child_count == 0) return std::vector(child_count, child_count == 0 ? 0.0 : 1.0 / static_cast(child_count)); + + const double total = std::accumulate(parsed.begin(), parsed.end(), 0.0); + if (total <= 0.0) return std::vector(child_count, 1.0 / static_cast(child_count)); + for (double &value : parsed) { + value /= total; + } + return parsed; +} + +PlotRange parse_range(const json11::Json &pane_node) { + PlotRange range; + const json11::Json &range_node = pane_node["range"]; + if (range_node.is_object()) { + range.valid = true; + range.left = range_node["left"].number_value(); + range.right = range_node["right"].number_value(); + range.bottom = range_node["bottom"].number_value(); + range.top = range_node["top"].is_number() ? range_node["top"].number_value() : 1.0; + } + const json11::Json &limit_y_node = pane_node["y_limits"]; + if (limit_y_node.is_object()) { + if (limit_y_node["min"].is_number()) { + range.has_y_limit_min = true; + range.y_limit_min = limit_y_node["min"].number_value(); + } + if (limit_y_node["max"].is_number()) { + range.has_y_limit_max = true; + range.y_limit_max = limit_y_node["max"].number_value(); + } + } + return range; +} + +Curve parse_curve(const json11::Json &curve_node) { + Curve curve; + curve.name = curve_node["name"].string_value(); + curve.label = curve_label(curve.name); + curve.color = parse_color(curve_node["color"].string_value()); + + const std::string transform_name = curve_node["transform"].string_value(); + if (transform_name == "derivative") { + curve.derivative = true; + curve.derivative_dt = curve_node["derivative_dt"].is_number() ? curve_node["derivative_dt"].number_value() : 0.0; + } else if (transform_name == "scale") { + curve.value_scale = curve_node["scale"].is_number() ? curve_node["scale"].number_value() : 1.0; + curve.value_offset = curve_node["offset"].is_number() ? curve_node["offset"].number_value() : 0.0; + } + const json11::Json &custom_node = curve_node["custom_python"]; + if (custom_node.is_object()) { + CustomPythonSeries spec; + spec.linked_source = custom_node["linked_source"].string_value(); + spec.globals_code = custom_node["globals_code"].string_value(); + spec.function_code = custom_node["function_code"].string_value(); + for (const json11::Json &source : custom_node["additional_sources"].array_items()) { + if (source.is_string()) { + spec.additional_sources.push_back(source.string_value()); + } + } + curve.custom_python = std::move(spec); + } + return curve; +} + +std::string pane_title(const json11::Json &dock_area_node) { + const std::string raw = dock_area_node["title"].string_value(); + return raw.empty() ? "..." : raw; +} + +Pane parse_dock_area(const json11::Json &dock_area_node) { + Pane pane; + const std::string kind = dock_area_node["kind"].string_value(); + if (kind == "map") { + pane.kind = PaneKind::Map; + } else if (kind == "thumbnail") { + pane.kind = PaneKind::Thumbnail; + } else if (kind == "camera") { + pane.kind = PaneKind::Camera; + const std::string camera_view = dock_area_node["camera_view"].string_value(); + if (const CameraViewSpec *spec = camera_view_spec_from_layout_name(camera_view)) { + pane.camera_view = spec->view; + } else { + pane.camera_view = CameraViewKind::Road; + } + } + pane.range = parse_range(dock_area_node); + const json11::Json &curves_node = dock_area_node["curves"]; + if (curves_node.is_array()) { + for (const json11::Json &curve_node : curves_node.array_items()) { + if (curve_node.is_object()) { + pane.curves.push_back(parse_curve(curve_node)); + } + } + } + pane.title = pane_title(dock_area_node); + return pane; +} + +WorkspaceNode parse_workspace_node(const json11::Json &node, WorkspaceTab *tab) { + WorkspaceNode workspace_node; + if (!node.is_object()) return workspace_node; + + if (node["curves"].is_array()) { + workspace_node.is_pane = true; + workspace_node.pane_index = static_cast(tab->panes.size()); + tab->panes.push_back(parse_dock_area(node)); + return workspace_node; + } + + const json11::Json &children_node = node["children"]; + if (!children_node.is_array()) return workspace_node; + + const std::vector children = children_node.array_items(); + if (children.empty()) return workspace_node; + + const std::string split = node["split"].string_value(); + workspace_node.orientation = split == "vertical" ? SplitOrientation::Vertical : SplitOrientation::Horizontal; + const std::vector sizes = normalize_sizes(node["sizes"], children.size()); + workspace_node.sizes.reserve(sizes.size()); + workspace_node.children.reserve(children.size()); + for (size_t i = 0; i < children.size(); ++i) { + workspace_node.sizes.push_back(static_cast(sizes[i])); + workspace_node.children.push_back(parse_workspace_node(children[i], tab)); + } + return workspace_node; +} + +WorkspaceTab parse_tab(const json11::Json &tab, const fs::path &layout_path) { + WorkspaceTab workspace_tab; + workspace_tab.tab_name = tab["name"].string_value().empty() ? "tab1" : tab["name"].string_value(); + const json11::Json &dock_root = tab["root"]; + if (!dock_root.is_object()) throw std::runtime_error("Layout tab has no dock content: " + layout_path.string()); + workspace_tab.root = parse_workspace_node(dock_root, &workspace_tab); + return workspace_tab; +} + +SketchLayout parse_layout(const fs::path &layout_path) { + const std::string text = util::read_file(layout_path.string()); + if (text.empty()) throw std::runtime_error("Failed to read layout JSON: " + layout_path.string()); + + std::string parse_error; + const json11::Json root = json11::Json::parse(text, parse_error); + if (!parse_error.empty() || !root.is_object()) { + throw std::runtime_error("Failed to parse layout JSON: " + layout_path.string()); + } + SketchLayout layout; + for (const json11::Json &tab : root["tabs"].array_items()) { + if (tab.is_object()) { + layout.tabs.push_back(parse_tab(tab, layout_path)); + } + } + if (layout.tabs.empty()) throw std::runtime_error("Layout has no tabs: " + layout_path.string()); + const json11::Json &tab_index = root["current_tab_index"].is_number() ? root["current_tab_index"] : root["currentTabIndex"]; + layout.current_tab_index = std::clamp(tab_index.is_number() ? tab_index.int_value() : 0, + 0, + static_cast(layout.tabs.size()) - 1); + return layout; +} + +const SchemaIndex &SchemaIndex::instance() { + static const SchemaIndex index = [] { + SchemaIndex out; + out.fixed_paths = static_event_fixed_paths(); + out.fixed_series_count = out.fixed_paths.size(); + return out; + }(); + return index; +} + +bool is_absolute_curve(const std::string &name) { + return !name.empty() && name.front() == '/'; +} + +void append_scalar_point(RouteSeries *series, + const std::string &path, + double tm, + double value) { + if (series->path.empty()) { + series->path = path; + } + series->times.push_back(tm); + series->values.push_back(value); +} + +void append_fixed_scalar_point(RouteSeries *series, double tm, double value) { + series->times.push_back(tm); + series->values.push_back(value); +} + +CanMessageData *ensure_can_message(CanServiceKind service, uint8_t bus, uint32_t address, SeriesAccumulator *series) { + const CanMessageId id{service, bus, address}; + auto [it, inserted] = series->can_message_slots.try_emplace(id, series->can_messages.size()); + if (inserted) { + series->can_messages.push_back(CanMessageData{.id = id}); + } + return &series->can_messages[it->second]; +} + +void append_can_frame(CanServiceKind service, + uint8_t bus, + uint32_t address, + uint16_t bus_time, + capnp::Data::Reader dat, + double tm, + SeriesAccumulator *series) { + CanMessageData *message = ensure_can_message(service, bus, address, series); + message->samples.push_back(CanFrameSample{ + .mono_time = tm, + .bus_time = bus_time, + .data = std::string(reinterpret_cast(dat.begin()), dat.size()), + }); +} + +void append_dynamic_scalar_point(const std::string &path, double tm, double value, SeriesAccumulator *series); + +void decode_can_frame(const dbc::Database *can_dbc, + const std::string &service_name, + uint8_t bus, + uint32_t address, + const uint8_t *raw, + size_t data_size, + double tm, + SeriesAccumulator *series) { + if (can_dbc == nullptr) { + return; + } + const dbc::Message *message = can_dbc->message(address); + if (message == nullptr) { + return; + } + const std::string base_path = "/" + service_name + "/" + std::to_string(bus) + "/" + message->name; + for (const dbc::Signal &signal : message->signals) { + std::optional value = dbc::signalValue(signal, *message, raw, data_size); + if (!value.has_value()) continue; + const std::string path = base_path + "/" + signal.name; + append_dynamic_scalar_point(path, tm, *value, series); + if (series->enum_info.find(path) == series->enum_info.end()) { + std::vector enum_names = can_dbc->enumNames(signal); + if (!enum_names.empty()) { + series->enum_info.emplace(path, EnumInfo{.names = std::move(enum_names)}); + } + } + } +} + +void append_live_can_frame(CanServiceKind service, + const LiveCanFrame &frame, + double time_offset, + const dbc::Database *can_dbc, + SeriesAccumulator *series) { + const double tm = frame.mono_time - time_offset; + CanMessageData *message = ensure_can_message(service, frame.bus, frame.address, series); + message->samples.push_back(CanFrameSample{ + .mono_time = tm, + .bus_time = frame.bus_time, + .data = frame.data, + }); + decode_can_frame(can_dbc, + service == CanServiceKind::Can ? "can" : "sendcan", + frame.bus, + frame.address, + reinterpret_cast(frame.data.data()), + frame.data.size(), + tm, + series); +} + +SeriesAccumulator make_series_accumulator(const SchemaIndex &schema) { + SeriesAccumulator out(schema.fixed_series_count); + for (size_t i = 0; i < schema.fixed_paths.size(); ++i) { + out.fixed_series[i].path = schema.fixed_paths[i]; + } + return out; +} + +size_t ensure_dynamic_slot(const std::string &path, SeriesAccumulator *series) { + auto [it, inserted] = series->dynamic_slots.try_emplace(path, series->dynamic_series.size()); + if (inserted) { + series->dynamic_series.push_back(RouteSeries{it->first}); + } + return it->second; +} + +RouteSeries *ensure_dynamic_series(const std::string &path, SeriesAccumulator *series) { + return &series->dynamic_series[ensure_dynamic_slot(path, series)]; +} + +RouteSeries *ensure_list_scalar_series(const std::string &base_path, size_t index, SeriesAccumulator *series) { + auto [it, _] = series->list_scalar_slots.try_emplace(base_path); + std::vector &slots = it->second; + if (slots.size() <= index) { + slots.resize(index + 1, INVALID_DYNAMIC_SLOT); + } + if (slots[index] == INVALID_DYNAMIC_SLOT) { + slots[index] = ensure_dynamic_slot(base_path + "/" + std::to_string(index), series); + } + return &series->dynamic_series[slots[index]]; +} + +void append_dynamic_scalar_point(const std::string &path, double tm, double value, SeriesAccumulator *series) { + append_scalar_point(ensure_dynamic_series(path, series), path, tm, value); +} + +void append_event_fast(cereal::Event::Which which, + int32_t eidx_segnum, + kj::ArrayPtr data, + const dbc::Database *can_dbc, + bool skip_raw_can, + double time_offset, + SeriesAccumulator *series) { + if (eidx_segnum != -1) { + return; + } + with_parseable_event(data, [&](const cereal::Event::Reader &event) { + append_event_static_reader(which, event, can_dbc, skip_raw_can, time_offset, series); + }); +} + +void append_events_fast_range(const std::vector &events, + size_t begin, + size_t end, + const dbc::Database *can_dbc, + bool skip_raw_can, + SeriesAccumulator *series) { + for (size_t i = begin; i < end; ++i) { + const Event &event_record = events[i]; + append_event_fast(event_record.which, + event_record.eidx_segnum, + event_record.data, + can_dbc, + skip_raw_can, + 0.0, + series); + } +} + +void merge_route_series(RouteSeries *dst, RouteSeries *src) { + if (src->times.empty()) { + return; + } + if (dst->times.empty()) { + *dst = std::move(*src); + return; + } + + dst->times.reserve(dst->times.size() + src->times.size()); + dst->values.reserve(dst->values.size() + src->values.size()); + dst->times.insert(dst->times.end(), src->times.begin(), src->times.end()); + dst->values.insert(dst->values.end(), src->values.begin(), src->values.end()); +} + +void merge_can_message_data(CanMessageData *dst, CanMessageData *src) { + if (src->samples.empty()) { + return; + } + if (dst->samples.empty()) { + *dst = std::move(*src); + return; + } + dst->samples.reserve(dst->samples.size() + src->samples.size()); + dst->samples.insert(dst->samples.end(), + std::make_move_iterator(src->samples.begin()), + std::make_move_iterator(src->samples.end())); +} + +void merge_series_accumulator(SeriesAccumulator *dst, SeriesAccumulator *src) { + if (dst->fixed_series.size() != src->fixed_series.size()) { + throw std::runtime_error("Fixed-series slot count mismatch during merge"); + } + + for (size_t i = 0; i < dst->fixed_series.size(); ++i) { + merge_route_series(&dst->fixed_series[i], &src->fixed_series[i]); + } + for (auto &series : src->dynamic_series) { + if (series.path.empty()) continue; + RouteSeries &dst_series = dst->dynamic_series[ensure_dynamic_slot(series.path, dst)]; + merge_route_series(&dst_series, &series); + } + for (auto &message : src->can_messages) { + CanMessageData &dst_message = *ensure_can_message(message.id.service, message.id.bus, message.id.address, dst); + merge_can_message_data(&dst_message, &message); + } + for (auto &[path, info] : src->enum_info) { + dst->enum_info.try_emplace(path, std::move(info)); + } +} + +size_t populated_series_count(const SeriesAccumulator &series) { + size_t count = 0; + for (const RouteSeries &fixed : series.fixed_series) { + count += !fixed.times.empty(); + } + for (const RouteSeries &dynamic : series.dynamic_series) { + count += !dynamic.times.empty(); + } + return count; +} + +bool series_is_sorted(const RouteSeries &series) { + for (size_t i = 1; i < series.times.size(); ++i) { + if (series.times[i] < series.times[i - 1]) return false; + } + return true; +} + +void sort_series_by_time(RouteSeries *series) { + if (series->times.size() <= 1 || series_is_sorted(*series)) { + return; + } + std::vector order(series->times.size()); + std::iota(order.begin(), order.end(), 0); + std::sort(order.begin(), order.end(), [&](size_t a, size_t b) { + return series->times[a] < series->times[b]; + }); + + std::vector sorted_times(series->times.size()); + std::vector sorted_values(series->values.size()); + for (size_t i = 0; i < order.size(); ++i) { + sorted_times[i] = series->times[order[i]]; + sorted_values[i] = series->values[order[i]]; + } + series->times = std::move(sorted_times); + series->values = std::move(sorted_values); +} + +std::vector collect_series(SeriesAccumulator &&series) { + std::vector out; + out.reserve(series.fixed_series.size() + series.dynamic_series.size()); + for (auto &fixed : series.fixed_series) { + sort_series_by_time(&fixed); + if (!fixed.times.empty()) { + out.push_back(std::move(fixed)); + } + } + for (auto &dynamic : series.dynamic_series) { + sort_series_by_time(&dynamic); + if (!dynamic.times.empty()) { + out.push_back(std::move(dynamic)); + } + } + return out; +} + +RouteData build_route_data(std::vector &&series_list, + std::vector &&can_messages, + std::vector &&logs, + std::vector &&timeline, + std::vector &&thumbnails, + std::unordered_map &&enum_info, + std::string car_fingerprint, + std::string dbc_name) { + RouteData route_data; + route_data.series.reserve(series_list.size()); + route_data.paths.reserve(series_list.size()); + for (RouteSeries &series : series_list) { + if (series.times.empty()) continue; + route_data.has_time_range = true; + route_data.x_min = route_data.series.empty() ? series.times.front() : std::min(route_data.x_min, series.times.front()); + route_data.x_max = route_data.series.empty() ? series.times.back() : std::max(route_data.x_max, series.times.back()); + route_data.paths.push_back(series.path); + route_data.series.push_back(std::move(series)); + } + + std::sort(route_data.paths.begin(), route_data.paths.end()); + std::sort(route_data.series.begin(), route_data.series.end(), [](const RouteSeries &a, const RouteSeries &b) { + return a.path < b.path; + }); + std::sort(logs.begin(), logs.end(), [](const LogEntry &a, const LogEntry &b) { + return a.mono_time < b.mono_time; + }); + logs.erase(std::unique(logs.begin(), logs.end(), [](const LogEntry &a, const LogEntry &b) { + return same_log_entry(a, b); + }), + logs.end()); + + std::vector deduped_logs; + deduped_logs.reserve(logs.size()); + for (LogEntry &entry : logs) { + if (!deduped_logs.empty() + && entry.origin == LogOrigin::Alert + && deduped_logs.back().origin == LogOrigin::Alert + && deduped_logs.back().func == entry.func + && deduped_logs.back().message == entry.message) { + continue; + } + deduped_logs.push_back(std::move(entry)); + } + route_data.logs = std::move(deduped_logs); + + if (!route_data.has_time_range && !route_data.logs.empty()) { + route_data.has_time_range = true; + route_data.x_min = route_data.logs.front().mono_time; + route_data.x_max = route_data.logs.back().mono_time; + } + if (!route_data.has_time_range) { + bool initialized = false; + for (const CanMessageData &message : can_messages) { + if (message.samples.empty()) continue; + if (!initialized) { + route_data.x_min = message.samples.front().mono_time; + route_data.x_max = message.samples.back().mono_time; + initialized = true; + } else { + route_data.x_min = std::min(route_data.x_min, message.samples.front().mono_time); + route_data.x_max = std::max(route_data.x_max, message.samples.back().mono_time); + } + } + route_data.has_time_range = initialized; + } + if (!route_data.has_time_range && !timeline.empty()) { + route_data.has_time_range = true; + route_data.x_min = timeline.front().start_time; + route_data.x_max = timeline.back().end_time; + } + std::sort(thumbnails.begin(), thumbnails.end(), [](const ThumbnailFrame &a, const ThumbnailFrame &b) { + return a.timestamp < b.timestamp; + }); + if (!route_data.has_time_range && !thumbnails.empty()) { + route_data.has_time_range = true; + route_data.x_min = thumbnails.front().timestamp; + route_data.x_max = thumbnails.back().timestamp; + } + + if (route_data.has_time_range) { + const double time_offset = route_data.x_min; + for (RouteSeries &series : route_data.series) { + for (double &tm : series.times) { + tm -= time_offset; + } + } + for (LogEntry &entry : route_data.logs) { + entry.boot_time = entry.mono_time; + entry.mono_time -= time_offset; + } + for (CanMessageData &message : can_messages) { + for (CanFrameSample &sample : message.samples) { + sample.mono_time -= time_offset; + } + } + for (TimelineEntry &entry : timeline) { + entry.start_time -= time_offset; + entry.end_time -= time_offset; + } + for (ThumbnailFrame &thumbnail : thumbnails) { + thumbnail.timestamp -= time_offset; + } + route_data.x_max -= time_offset; + route_data.x_min = 0.0; + } + + std::sort(timeline.begin(), timeline.end(), [](const TimelineEntry &a, const TimelineEntry &b) { + return a.start_time < b.start_time; + }); + std::vector merged_timeline; + merged_timeline.reserve(timeline.size()); + for (TimelineEntry &entry : timeline) { + if (!merged_timeline.empty() && merged_timeline.back().type == entry.type) { + merged_timeline.back().end_time = std::max(merged_timeline.back().end_time, entry.end_time); + continue; + } + merged_timeline.push_back(std::move(entry)); + } + route_data.timeline = std::move(merged_timeline); + route_data.thumbnails = std::move(thumbnails); + std::sort(can_messages.begin(), can_messages.end(), [](const CanMessageData &a, const CanMessageData &b) { + return std::make_tuple(a.id.service, a.id.bus, a.id.address) + < std::make_tuple(b.id.service, b.id.bus, b.id.address); + }); + route_data.can_messages = std::move(can_messages); + + route_data.enum_info = std::move(enum_info); + route_data.car_fingerprint = std::move(car_fingerprint); + route_data.dbc_name = std::move(dbc_name); + rebuild_gps_trace(&route_data); + route_data.roots = collect_route_roots_for_paths(route_data.paths); + return route_data; +} + +const RouteSeries *find_route_series(const RouteData &route_data, std::string_view path) { + auto it = std::lower_bound(route_data.series.begin(), route_data.series.end(), path, + [](const RouteSeries &series, std::string_view target) { + return series.path < target; + }); + if (it == route_data.series.end() || it->path != path) return nullptr; + return &(*it); +} + +std::optional sample_series_at_time(const RouteSeries &series, double tm) { + if (series.times.empty() || series.times.size() != series.values.size()) { + return std::nullopt; + } + if (tm <= series.times.front()) { + return series.values.front(); + } + if (tm >= series.times.back()) { + return series.values.back(); + } + auto upper = std::lower_bound(series.times.begin(), series.times.end(), tm); + if (upper == series.times.begin()) { + return series.values.front(); + } + if (upper == series.times.end()) { + return series.values.back(); + } + const size_t upper_index = static_cast(std::distance(series.times.begin(), upper)); + const size_t lower_index = upper_index - 1; + const double t0 = series.times[lower_index]; + const double t1 = series.times[upper_index]; + const double v0 = series.values[lower_index]; + const double v1 = series.values[upper_index]; + if (t1 <= t0) { + return v0; + } + const double alpha = (tm - t0) / (t1 - t0); + return v0 + (v1 - v0) * alpha; +} + +} // namespace + +void rebuild_gps_trace(RouteData *route_data) { + route_data->gps_trace = {}; + const RouteSeries *latitude = find_route_series(*route_data, "/gpsLocationExternal/latitude"); + const RouteSeries *longitude = find_route_series(*route_data, "/gpsLocationExternal/longitude"); + const RouteSeries *has_fix = find_route_series(*route_data, "/gpsLocationExternal/hasFix"); + if (latitude == nullptr || longitude == nullptr || has_fix == nullptr) { + return; + } + + const RouteSeries *bearing = find_route_series(*route_data, "/gpsLocationExternal/bearingDeg"); + size_t count = std::min({latitude->times.size(), latitude->values.size(), + longitude->times.size(), longitude->values.size(), + has_fix->times.size(), has_fix->values.size()}); + if (count == 0) { + return; + } + + bool found = false; + route_data->gps_trace.points.reserve(count); + for (size_t i = 0; i < count; ++i) { + if (has_fix->values[i] < 0.5) { + continue; + } + const double lat = latitude->values[i]; + const double lon = longitude->values[i]; + if (!std::isfinite(lat) || !std::isfinite(lon)) { + continue; + } + const double tm = latitude->times[i]; + const float bearing_value = bearing != nullptr + ? static_cast(sample_series_at_time(*bearing, tm).value_or(0.0)) + : 0.0f; + route_data->gps_trace.points.push_back(GpsPoint{ + .time = tm, + .lat = lat, + .lon = lon, + .bearing = bearing_value, + .type = timeline_type_at_time(route_data->timeline, tm), + }); + if (!found) { + route_data->gps_trace.min_lat = route_data->gps_trace.max_lat = lat; + route_data->gps_trace.min_lon = route_data->gps_trace.max_lon = lon; + found = true; + } else { + route_data->gps_trace.min_lat = std::min(route_data->gps_trace.min_lat, lat); + route_data->gps_trace.max_lat = std::max(route_data->gps_trace.max_lat, lat); + route_data->gps_trace.min_lon = std::min(route_data->gps_trace.min_lon, lon); + route_data->gps_trace.max_lon = std::max(route_data->gps_trace.max_lon, lon); + } + } + if (!found) { + route_data->gps_trace = {}; + } +} + +namespace { + +void build_camera_index(const std::map &segments, + const RouteData &route_data, + std::string SegmentLogs::*file_member, + std::string_view index_name, + CameraFeedIndex *out) { + *out = {}; + out->segment_files.reserve(segments.size()); + + std::unordered_set available_segments; + available_segments.reserve(segments.size()); + for (const auto &[segment_number, segment] : segments) { + const std::string &path = segment.*file_member; + if (path.empty()) continue; + out->segment_files.push_back(CameraSegmentFile{ + .segment = segment_number, + .path = path, + }); + available_segments.insert(segment_number); + } + if (out->segment_files.empty()) { + return; + } + + const std::string prefix = "/" + std::string(index_name); + const RouteSeries *segment_numbers = find_route_series(route_data, prefix + "/segmentNum"); + const RouteSeries *decode_indices = find_route_series(route_data, prefix + "/segmentId"); + if (decode_indices == nullptr) { + decode_indices = find_route_series(route_data, prefix + "/segmentIdEncode"); + } + const RouteSeries *frame_ids = find_route_series(route_data, prefix + "/frameId"); + if (segment_numbers == nullptr || decode_indices == nullptr) { + return; + } + + size_t count = std::min(segment_numbers->times.size(), segment_numbers->values.size()); + count = std::min(count, decode_indices->values.size()); + if (frame_ids != nullptr) { + count = std::min(count, frame_ids->values.size()); + } + out->entries.reserve(count); + for (size_t i = 0; i < count; ++i) { + const int segment_number = static_cast(std::llround(segment_numbers->values[i])); + if (available_segments.find(segment_number) == available_segments.end()) { + continue; + } + const int decode_index = static_cast(std::llround(decode_indices->values[i])); + const uint32_t frame_id = frame_ids != nullptr + ? static_cast(std::llround(frame_ids->values[i])) + : static_cast(std::max(0, decode_index)); + out->entries.push_back(CameraFrameIndexEntry{ + .timestamp = segment_numbers->times[i], + .segment = segment_number, + .decode_index = decode_index, + .frame_id = frame_id, + }); + } + + std::sort(out->entries.begin(), out->entries.end(), + [](const CameraFrameIndexEntry &a, const CameraFrameIndexEntry &b) { + return a.timestamp < b.timestamp; + }); +} + +size_t load_worker_budget() { + size_t worker_count = std::thread::hardware_concurrency(); + if (worker_count == 0) { + worker_count = 1; + } + if (const char *raw = std::getenv("JOTP_LOAD_WORKERS"); raw != nullptr && std::strlen(raw) > 0) { + char *end = nullptr; + const unsigned long parsed = std::strtoul(raw, &end, 10); + if (end != nullptr && *end == '\0' && parsed > 0) { + worker_count = static_cast(parsed); + } + } + return std::max(1, worker_count); +} + +size_t segment_worker_count(size_t segment_count, size_t worker_budget) { + return std::max(1, std::min(worker_budget, segment_count)); +} + +size_t extract_chunk_count(size_t event_count, size_t worker_budget, size_t segment_workers) { + if (event_count < 4096) return 1; + const size_t per_segment_budget = std::max(1, worker_budget / std::max(1, segment_workers)); + const size_t chunk_target = std::max(1, (event_count + 14999) / 15000); + return std::max(1, std::min({per_segment_budget, chunk_target, static_cast(8)})); +} + +SeriesAccumulator extract_segment_series(const std::vector &events, + const SchemaIndex &schema, + const dbc::Database *can_dbc, + bool skip_raw_can, + size_t worker_budget, + size_t segment_workers) { + const size_t chunk_count = extract_chunk_count(events.size(), worker_budget, segment_workers); + if (chunk_count <= 1 || events.empty()) { + SeriesAccumulator series = make_series_accumulator(schema); + append_events_fast_range(events, 0, events.size(), can_dbc, skip_raw_can, &series); + return series; + } + + const size_t events_per_chunk = (events.size() + chunk_count - 1) / chunk_count; + std::vector chunk_results; + chunk_results.reserve(chunk_count); + for (size_t i = 0; i < chunk_count; ++i) { + chunk_results.push_back(make_series_accumulator(schema)); + } + + std::vector workers; + workers.reserve(chunk_count > 0 ? chunk_count - 1 : 0); + for (size_t chunk = 1; chunk < chunk_count; ++chunk) { + workers.emplace_back([&, chunk]() { + const size_t begin = chunk * events_per_chunk; + const size_t end = std::min(events.size(), begin + events_per_chunk); + append_events_fast_range(events, begin, end, can_dbc, skip_raw_can, &chunk_results[chunk]); + }); + } + append_events_fast_range(events, 0, std::min(events.size(), events_per_chunk), can_dbc, skip_raw_can, &chunk_results[0]); + for (std::thread &worker : workers) { + worker.join(); + } + + SeriesAccumulator merged = make_series_accumulator(schema); + for (SeriesAccumulator &chunk : chunk_results) { + merge_series_accumulator(&merged, &chunk); + } + return merged; +} + +LoadedRouteArtifacts load_route_series_parallel( + const std::map &segments, + const SchemaIndex &schema, + const dbc::Database *can_dbc, + LogSelector selector, + bool skip_raw_can, + LoadStats *stats) { + struct SegmentResult { + SeriesAccumulator series; + std::vector logs; + std::vector timeline; + std::vector thumbnails; + }; + + const std::vector> segment_list(segments.begin(), segments.end()); + std::vector results; + results.reserve(segment_list.size()); + for (size_t i = 0; i < segment_list.size(); ++i) { + results.emplace_back(SegmentResult{make_series_accumulator(schema)}); + } + std::atomic next_segment{0}; + std::mutex error_mutex; + std::string first_error; + const size_t worker_budget = static_cast(stats->num_workers); + const size_t segment_workers = segment_worker_count(segment_list.size(), worker_budget); + + auto worker = [&]() { + while (true) { + const size_t index = next_segment.fetch_add(1); + if (index >= segment_list.size()) { + return; + } + + const auto &[segment_number, segment] = segment_list[index]; + const std::string &log_path = selected_log_path(segment, selector); + LoadStats::SegmentStats &segment_stats = stats->segments[index]; + segment_stats.segment_number = segment_number; + segment_stats.log_path = log_path; + if (log_path.empty()) { + segment_stats.failed = true; + std::lock_guard lock(error_mutex); + if (first_error.empty()) { + first_error = "Missing log path for segment " + std::to_string(segment_number); + } + stats->publish(RouteLoadStage::DownloadingSegment, index, std::to_string(segment_number)); + stats->publish(RouteLoadStage::ParsingSegment, index, std::to_string(segment_number)); + continue; + } + + LogReader reader; + if (!reader.load(log_path, nullptr, true)) { + segment_stats.failed = true; + std::lock_guard lock(error_mutex); + if (first_error.empty()) { + first_error = "Failed to load log segment: " + log_path; + } + stats->publish(RouteLoadStage::DownloadingSegment, index, std::to_string(segment_number)); + stats->publish(RouteLoadStage::ParsingSegment, index, std::to_string(segment_number)); + continue; + } + + segment_stats.download_seconds = reader.download_seconds(); + segment_stats.decompress_seconds = reader.decompress_seconds(); + segment_stats.parse_seconds = reader.parse_seconds(); + segment_stats.compressed_bytes = reader.compressed_size(); + segment_stats.decompressed_bytes = reader.decompressed_size(); + stats->bytes_downloaded.fetch_add(reader.compressed_size()); + stats->segments_downloaded.fetch_add(1); + stats->publish(RouteLoadStage::DownloadingSegment, index, std::to_string(segment_number)); + + const auto extract_start = LoadStats::Clock::now(); + results[index].series = extract_segment_series(reader.events, schema, can_dbc, skip_raw_can, worker_budget, segment_workers); + results[index].logs = extract_segment_logs(reader.events); + results[index].timeline = extract_segment_timeline(reader.events); + results[index].thumbnails = extract_segment_thumbnails(reader.events, segment_number); + segment_stats.extract_seconds = std::chrono::duration(LoadStats::Clock::now() - extract_start).count(); + segment_stats.event_count = reader.events.size(); + segment_stats.series_count = populated_series_count(results[index].series); + stats->segments_parsed.fetch_add(1); + stats->publish(RouteLoadStage::ParsingSegment, index, std::to_string(segment_number)); + } + }; + + std::vector workers; + workers.reserve(segment_workers); + for (size_t i = 0; i < segment_workers; ++i) { + workers.emplace_back(worker); + } + for (std::thread &thread : workers) { + thread.join(); + } + + if (!first_error.empty()) throw std::runtime_error(first_error); + + stats->merge_start = LoadStats::Clock::now(); + SeriesAccumulator merged = make_series_accumulator(schema); + for (size_t i = 0; i < results.size(); ++i) { + merge_series_accumulator(&merged, &results[i].series); + } + std::vector logs; + std::vector timeline; + std::vector thumbnails; + for (SegmentResult &result : results) { + if (!result.logs.empty()) { + logs.insert(logs.end(), + std::make_move_iterator(result.logs.begin()), + std::make_move_iterator(result.logs.end())); + } + if (!result.timeline.empty()) { + timeline.insert(timeline.end(), + std::make_move_iterator(result.timeline.begin()), + std::make_move_iterator(result.timeline.end())); + } + if (!result.thumbnails.empty()) { + thumbnails.insert(thumbnails.end(), + std::make_move_iterator(result.thumbnails.begin()), + std::make_move_iterator(result.thumbnails.end())); + } + } + LoadedRouteArtifacts artifacts; + artifacts.series = collect_series(std::move(merged)); + artifacts.can_messages = std::move(merged.can_messages); + artifacts.logs = std::move(logs); + artifacts.timeline = std::move(timeline); + artifacts.thumbnails = std::move(thumbnails); + artifacts.enum_info = std::move(merged.enum_info); + stats->merge_end = LoadStats::Clock::now(); + return artifacts; +} + +std::vector collect_layout_roots(const SketchLayout &layout) { + std::vector roots; + for (const auto &tab : layout.tabs) { + for (const auto &pane : tab.panes) { + for (const auto &curve : pane.curves) { + std::string root = "custom"; + if (is_absolute_curve(curve.name)) { + const size_t slash = curve.name.find('/', 1); + root = curve.name.substr(1, slash == std::string::npos ? std::string::npos : slash - 1); + } + if (std::find(roots.begin(), roots.end(), root) == roots.end()) { + roots.push_back(root); + } + } + } + } + if (roots.empty()) { + roots.push_back("layout"); + } + return roots; +} + +} // namespace + +std::vector collect_route_roots_for_paths(const std::vector &paths) { + std::vector roots; + for (const std::string &path : paths) { + if (!is_absolute_curve(path)) continue; + const size_t slash = path.find('/', 1); + const std::string root = path.substr(1, slash == std::string::npos ? std::string::npos : slash - 1); + if (!root.empty() && std::find(roots.begin(), roots.end(), root) == roots.end()) { + roots.push_back(root); + } + } + std::sort(roots.begin(), roots.end()); + return roots; +} + +struct StreamAccumulator::Impl { + const SchemaIndex &schema = SchemaIndex::instance(); + SeriesAccumulator series = make_series_accumulator(schema); + std::vector logs; + std::vector timeline; + std::string last_alert_key; + std::string manual_dbc_name; + std::string detected_dbc_name; + std::string car_fingerprint; + std::optional can_dbc; + std::optional time_offset; + + void refresh_dbc() { + const std::string next_dbc = !manual_dbc_name.empty() ? manual_dbc_name : detect_dbc_for_fingerprint(car_fingerprint); + if (next_dbc == detected_dbc_name) { + return; + } + detected_dbc_name = next_dbc; + can_dbc = load_dbc_by_name(detected_dbc_name); + } +}; + +StreamAccumulator::StreamAccumulator(const std::string &dbc_name, std::optional time_offset) + : impl_(std::make_unique()) { + impl_->manual_dbc_name = dbc_name; + impl_->time_offset = time_offset; + impl_->refresh_dbc(); +} + +StreamAccumulator::~StreamAccumulator() = default; + +void StreamAccumulator::setDbcName(const std::string &dbc_name) { + impl_->manual_dbc_name = dbc_name; + impl_->refresh_dbc(); +} + +void StreamAccumulator::appendEvent(kj::ArrayPtr data) { + with_parseable_event(data, [&](const cereal::Event::Reader &event) { + const cereal::Event::Which which = event.which(); + const double boot_time = static_cast(event.getLogMonoTime()) / 1.0e9; + if (!impl_->time_offset.has_value()) { + impl_->time_offset = boot_time; + } + if (which == cereal::Event::Which::CAR_PARAMS) { + const std::string fingerprint = event.getCarParams().getCarFingerprint().cStr(); + if (!fingerprint.empty() && fingerprint != impl_->car_fingerprint) { + impl_->car_fingerprint = fingerprint; + impl_->refresh_dbc(); + } + } + + append_event_static_reader(which, + event, + impl_->can_dbc ? &*impl_->can_dbc : nullptr, + impl_->can_dbc.has_value(), + *impl_->time_offset, + &impl_->series); + append_log_event(which, event, *impl_->time_offset, &impl_->logs, &impl_->last_alert_key); + if (which == cereal::Event::Which::SELFDRIVE_STATE) { + const auto sd = event.getSelfdriveState(); + append_timeline_entry(&impl_->timeline, boot_time - *impl_->time_offset, + alert_status_to_timeline_type(sd.getAlertStatus(), sd.getEnabled())); + } + }); +} + +void StreamAccumulator::appendCanFrames(CanServiceKind service, const std::vector &frames) { + if (frames.empty()) { + return; + } + if (!impl_->time_offset.has_value()) { + impl_->time_offset = frames.front().mono_time; + } + for (const LiveCanFrame &frame : frames) { + append_live_can_frame(service, + frame, + *impl_->time_offset, + impl_->can_dbc ? &*impl_->can_dbc : nullptr, + &impl_->series); + } +} + +StreamExtractBatch StreamAccumulator::takeBatch() { + StreamExtractBatch batch; + batch.car_fingerprint = impl_->car_fingerprint; + batch.dbc_name = impl_->detected_dbc_name; + if (impl_->time_offset.has_value()) { + batch.has_time_offset = true; + batch.time_offset = *impl_->time_offset; + } + if (impl_->logs.empty() && impl_->timeline.empty() + && populated_series_count(impl_->series) == 0 + && impl_->series.enum_info.empty() + && impl_->series.can_messages.empty()) { + return batch; + } + + SeriesAccumulator emitted = std::move(impl_->series); + batch.can_messages = std::move(emitted.can_messages); + batch.enum_info = std::move(emitted.enum_info); + batch.series = collect_series(std::move(emitted)); + batch.logs = std::move(impl_->logs); + batch.timeline = std::move(impl_->timeline); + impl_->series = make_series_accumulator(impl_->schema); + impl_->logs.clear(); + impl_->timeline.clear(); + return batch; +} + +const std::string &StreamAccumulator::carFingerprint() const { + return impl_->car_fingerprint; +} + +const std::string &StreamAccumulator::dbc_name() const { + return impl_->detected_dbc_name; +} + +std::optional StreamAccumulator::timeOffset() const { + return impl_->time_offset; +} + +SketchLayout load_sketch_layout(const fs::path &layout_path) { + SketchLayout layout = parse_layout(layout_path); + layout.roots = collect_layout_roots(layout); + return layout; +} + +RouteData load_route_data(const std::string &route_name, + const std::string &data_dir, + const std::string &dbc_name, + const RouteLoadProgressCallback &progress) { + if (route_name.empty()) return RouteData{}; + + const RouteSelection route = parse_route_selection(route_name); + if (route.canonical_name.empty() || (data_dir.empty() && route.dongle_id.empty())) { + throw std::runtime_error("Invalid route format: " + route_name); + } + LoadStats stats(progress); + stats.load_start = LoadStats::Clock::now(); + std::map segments = data_dir.empty() + ? load_segments_from_server(route) + : load_segments_from_local(route, data_dir); + segments = trim_segments(std::move(segments), route); + if (segments.empty()) throw std::runtime_error("No log segments found for " + route_name); + stats.resolve_end = LoadStats::Clock::now(); + stats.segment_count = segments.size(); + stats.total_segments.store(segments.size()); + stats.num_workers = static_cast(load_worker_budget()); + stats.segments.resize(segments.size()); + stats.publish(RouteLoadStage::Resolving, 0, {}); + + const RouteMetadata metadata = detect_route_metadata(segments, route.selector); + const std::string resolved_dbc = !dbc_name.empty() ? dbc_name : detect_dbc_for_fingerprint(metadata.car_fingerprint); + const std::optional can_dbc = load_dbc_by_name(resolved_dbc); + + const SchemaIndex &schema = SchemaIndex::instance(); + LoadedRouteArtifacts artifacts = load_route_series_parallel(segments, schema, can_dbc ? &*can_dbc : nullptr, + route.selector, can_dbc.has_value(), &stats); + RouteData route_data = build_route_data(std::move(artifacts.series), + std::move(artifacts.can_messages), + std::move(artifacts.logs), + std::move(artifacts.timeline), + std::move(artifacts.thumbnails), + std::move(artifacts.enum_info), + metadata.car_fingerprint, + resolved_dbc); + route_data.route_id = make_route_identifier(route, segments); + build_camera_index(segments, route_data, &SegmentLogs::fcamera, "roadEncodeIdx", &route_data.road_camera); + build_camera_index(segments, route_data, &SegmentLogs::dcamera, "driverEncodeIdx", &route_data.driver_camera); + build_camera_index(segments, route_data, &SegmentLogs::ecamera, "wideRoadEncodeIdx", &route_data.wide_road_camera); + build_camera_index(segments, route_data, &SegmentLogs::qcamera, "qRoadEncodeIdx", &route_data.qroad_camera); + stats.load_end = LoadStats::Clock::now(); + stats.publish(RouteLoadStage::Finished, segments.size(), {}); + stats.print_summary(route_data.series.size()); + return route_data; +} + +RouteIdentifier parse_route_identifier(std::string_view route_name) { + return make_route_identifier(parse_route_selection(std::string(route_name)), {}); +} + +std::vector available_dbc_names() { + return available_dbc_names_impl(); +} + +std::optional load_dbc_by_name(const std::string &dbc_name) { + if (dbc_name.empty()) { + return std::nullopt; + } + try { + return std::optional(std::in_place, resolve_dbc_path(dbc_name)); + } catch (...) { + return std::nullopt; + } +} + +std::vector decode_can_messages(const std::vector &can_messages, + const std::string &dbc_name, + std::unordered_map *enum_info) { + if (enum_info != nullptr) { + enum_info->clear(); + } + const std::optional can_dbc = load_dbc_by_name(dbc_name); + if (!can_dbc.has_value()) { + return {}; + } + + SeriesAccumulator series; + for (const CanMessageData &message : can_messages) { + const char *service_name = message.id.service == CanServiceKind::Can ? "can" : "sendcan"; + for (const CanFrameSample &sample : message.samples) { + decode_can_frame(&*can_dbc, + service_name, + message.id.bus, + message.id.address, + reinterpret_cast(sample.data.data()), + sample.data.size(), + sample.mono_time, + &series); + } + } + if (enum_info != nullptr) { + *enum_info = std::move(series.enum_info); + } + return collect_series(std::move(series)); +} diff --git a/openpilot/tools/jotpluggler/stream.cc b/openpilot/tools/jotpluggler/stream.cc new file mode 100644 index 0000000000..fcfa6585bb --- /dev/null +++ b/openpilot/tools/jotpluggler/stream.cc @@ -0,0 +1,207 @@ +#include "tools/jotpluggler/internal.h" + +#include + +template +std::optional stream_batch_extreme_time(const StreamExtractBatch &batch, + Cmp cmp, + SeriesAccessor series_time, + LogAccessor log_time_fn) { + std::optional result; + for (const RouteSeries &series : batch.series) { + if (!series.times.empty()) { + const double t = series_time(series); + result = result.has_value() ? cmp(*result, t) : t; + } + } + if (!batch.logs.empty()) { + const double t = log_time_fn(batch); + result = result.has_value() ? cmp(*result, t) : t; + } + if (!batch.timeline.empty()) { + const double t = cmp(batch.timeline.front().start_time, batch.timeline.back().end_time); + result = result.has_value() ? cmp(*result, t) : t; + } + for (const CanMessageData &message : batch.can_messages) { + if (!message.samples.empty()) { + const double t = cmp(message.samples.front().mono_time, message.samples.back().mono_time); + result = result.has_value() ? cmp(*result, t) : t; + } + } + return result; +} + +std::optional earliest_stream_batch_time(const StreamExtractBatch &batch) { + return stream_batch_extreme_time(batch, + [](double a, double b) { return std::min(a, b); }, + [](const RouteSeries &s) { return s.times.front(); }, + [](const StreamExtractBatch &b) { return b.logs.front().mono_time; }); +} + +std::optional latest_stream_batch_time(const StreamExtractBatch &batch) { + return stream_batch_extreme_time(batch, + [](double a, double b) { return std::max(a, b); }, + [](const RouteSeries &s) { return s.times.back(); }, + [](const StreamExtractBatch &b) { return b.logs.back().mono_time; }); +} + +bool layout_has_custom_curves(const SketchLayout &layout) { + for (const WorkspaceTab &tab : layout.tabs) { + for (const Pane &pane : tab.panes) { + for (const Curve &curve : pane.curves) { + if (curve.custom_python.has_value()) return true; + } + } + } + return false; +} + +void append_stream_timeline_entries(std::vector *timeline, std::vector entries) { + for (TimelineEntry &entry : entries) { + if (!timeline->empty() && timeline->back().type == entry.type) { + timeline->back().end_time = std::max(timeline->back().end_time, entry.end_time); + } else { + timeline->push_back(std::move(entry)); + } + } +} + +bool can_message_less(const CanMessageData &a, const CanMessageData &b) { + return std::make_tuple(a.id.service, a.id.bus, a.id.address) + < std::make_tuple(b.id.service, b.id.bus, b.id.address); +} + +void apply_stream_batch(AppSession *session, UiState *state, StreamExtractBatch batch) { + if (batch.has_time_offset) { + session->stream_time_offset = batch.time_offset; + } + if (!batch.car_fingerprint.empty()) { + session->route_data.car_fingerprint = batch.car_fingerprint; + } + if (!batch.dbc_name.empty()) { + session->route_data.dbc_name = batch.dbc_name; + } + if (!batch.enum_info.empty()) { + for (auto &[path, info] : batch.enum_info) { + session->route_data.enum_info[path] = std::move(info); + } + } + + bool new_paths = false; + std::vector new_series; + std::vector touched_paths; + touched_paths.reserve(batch.series.size()); + for (RouteSeries &incoming : batch.series) { + touched_paths.push_back(incoming.path); + auto existing_it = session->series_by_path.find(incoming.path); + if (existing_it == session->series_by_path.end()) { + new_series.push_back(std::move(incoming)); + new_paths = true; + continue; + } + RouteSeries &existing = *existing_it->second; + existing.times.insert(existing.times.end(), incoming.times.begin(), incoming.times.end()); + existing.values.insert(existing.values.end(), incoming.values.begin(), incoming.values.end()); + } + for (RouteSeries &series : new_series) { + session->route_data.paths.push_back(series.path); + session->route_data.series.push_back(std::move(series)); + } + + if (!batch.logs.empty()) { + std::sort(batch.logs.begin(), batch.logs.end(), [](const LogEntry &a, const LogEntry &b) { + return a.mono_time < b.mono_time; + }); + const size_t old_size = session->route_data.logs.size(); + session->route_data.logs.insert(session->route_data.logs.end(), + std::make_move_iterator(batch.logs.begin()), + std::make_move_iterator(batch.logs.end())); + if (old_size > 0 && session->route_data.logs.size() > old_size + && session->route_data.logs[old_size - 1].mono_time > session->route_data.logs[old_size].mono_time) { + std::inplace_merge(session->route_data.logs.begin(), + session->route_data.logs.begin() + static_cast(old_size), + session->route_data.logs.end(), + [](const LogEntry &a, const LogEntry &b) { + return a.mono_time < b.mono_time; + }); + } + } + if (!batch.timeline.empty()) { + append_stream_timeline_entries(&session->route_data.timeline, std::move(batch.timeline)); + } + + for (CanMessageData &incoming : batch.can_messages) { + auto it = std::lower_bound(session->route_data.can_messages.begin(), + session->route_data.can_messages.end(), + incoming, + can_message_less); + if (it == session->route_data.can_messages.end() + || can_message_less(incoming, *it) + || can_message_less(*it, incoming)) { + session->route_data.can_messages.insert(it, std::move(incoming)); + } else { + it->samples.insert(it->samples.end(), + std::make_move_iterator(incoming.samples.begin()), + std::make_move_iterator(incoming.samples.end())); + } + } + + if (new_paths) { + const size_t old_path_count = session->route_data.paths.size() - new_series.size(); + std::sort(session->route_data.paths.begin() + static_cast(old_path_count), session->route_data.paths.end()); + std::inplace_merge(session->route_data.paths.begin(), + session->route_data.paths.begin() + static_cast(old_path_count), + session->route_data.paths.end()); + const size_t old_series_count = session->route_data.series.size() - new_series.size(); + auto series_cmp = [](const RouteSeries &a, const RouteSeries &b) { return a.path < b.path; }; + std::sort(session->route_data.series.begin() + static_cast(old_series_count), + session->route_data.series.end(), series_cmp); + std::inplace_merge(session->route_data.series.begin(), + session->route_data.series.begin() + static_cast(old_series_count), + session->route_data.series.end(), series_cmp); + session->route_data.roots = collect_route_roots_for_paths(session->route_data.paths); + rebuild_route_index(session); + rebuild_browser_nodes(session, state); + state->browser_nodes_dirty = false; + } else { + for (const std::string &path : touched_paths) { + auto series_it = session->series_by_path.find(path); + if (series_it == session->series_by_path.end() || series_it->second == nullptr) continue; + const bool enum_like = session->route_data.enum_info.find(path) != session->route_data.enum_info.end(); + session->route_data.series_formats[path] = compute_series_format(series_it->second->values, enum_like); + } + } + const std::optional earliest_time = earliest_stream_batch_time(batch); + const std::optional latest_time = latest_stream_batch_time(batch); + if (earliest_time.has_value() && latest_time.has_value()) { + if (!session->route_data.has_time_range) { + session->route_data.x_min = *earliest_time; + session->route_data.x_max = *latest_time; + } else { + session->route_data.x_min = std::min(session->route_data.x_min, *earliest_time); + session->route_data.x_max = std::max(session->route_data.x_max, *latest_time); + } + session->route_data.has_time_range = true; + } + + if (new_paths + || std::find(touched_paths.begin(), touched_paths.end(), "/gpsLocationExternal/latitude") != touched_paths.end() + || std::find(touched_paths.begin(), touched_paths.end(), "/gpsLocationExternal/longitude") != touched_paths.end() + || std::find(touched_paths.begin(), touched_paths.end(), "/gpsLocationExternal/hasFix") != touched_paths.end() + || std::find(touched_paths.begin(), touched_paths.end(), "/gpsLocationExternal/bearingDeg") != touched_paths.end()) { + rebuild_gps_trace(&session->route_data); + } + + if (latest_time.has_value() && layout_has_custom_curves(session->layout) + && *latest_time >= session->next_stream_custom_refresh_time) { + refresh_all_custom_curves(session, state); + session->next_stream_custom_refresh_time = *latest_time + 0.1; + } + if (state->follow_latest || !state->has_tracker_time) { + state->tracker_time = session->route_data.x_max; + state->has_tracker_time = session->route_data.has_time_range; + } + if (!state->has_shared_range) { + reset_shared_range(state, *session); + } +} diff --git a/openpilot/tools/jotpluggler/test_jotpluggler.py b/openpilot/tools/jotpluggler/test_jotpluggler.py new file mode 100644 index 0000000000..0729e3b2e3 --- /dev/null +++ b/openpilot/tools/jotpluggler/test_jotpluggler.py @@ -0,0 +1,12 @@ +import subprocess +from pathlib import Path + + +JOTPLUGGLER_DIR = Path(__file__).parent + + +class TestJotpluggler: + def test_help(self): + result = subprocess.run(["./jotpluggler", "-h"], cwd=JOTPLUGGLER_DIR, capture_output=True, text=True) + assert result.returncode == 0, result.stderr + assert "Usage:" in result.stderr diff --git a/openpilot/tools/jotpluggler/thumbnail.cc b/openpilot/tools/jotpluggler/thumbnail.cc new file mode 100644 index 0000000000..11e184323a --- /dev/null +++ b/openpilot/tools/jotpluggler/thumbnail.cc @@ -0,0 +1,253 @@ +#include "tools/jotpluggler/thumbnail.h" + +#include "imgui_impl_opengl3_loader.h" + +#include +#include +#include + +extern "C" { +#include +#include +} + +namespace { + +bool decode_jpeg(const std::vector &jpeg, int *width, int *height, std::vector *rgba) { + if (jpeg.empty()) return false; + + const AVCodec *codec = avcodec_find_decoder(AV_CODEC_ID_MJPEG); + AVCodecContext *context = codec != nullptr ? avcodec_alloc_context3(codec) : nullptr; + AVFrame *frame = av_frame_alloc(); + AVPacket *packet = av_packet_alloc(); + if (context == nullptr || frame == nullptr || packet == nullptr) { + av_packet_free(&packet); + av_frame_free(&frame); + avcodec_free_context(&context); + return false; + } + + const bool packet_ready = jpeg.size() <= static_cast(std::numeric_limits::max()) + && av_new_packet(packet, static_cast(jpeg.size())) >= 0; + if (packet_ready) { + std::copy(jpeg.begin(), jpeg.end(), packet->data); + } + const bool decoded = packet_ready + && avcodec_open2(context, codec, nullptr) >= 0 + && avcodec_send_packet(context, packet) >= 0 + && avcodec_receive_frame(context, frame) >= 0; + if (!decoded || frame->width <= 0 || frame->height <= 0) { + av_packet_free(&packet); + av_frame_free(&frame); + avcodec_free_context(&context); + return false; + } + + int chroma_x_shift = 0; + int chroma_y_shift = 0; + switch (static_cast(frame->format)) { + case AV_PIX_FMT_YUV420P: + case AV_PIX_FMT_YUVJ420P: + chroma_x_shift = 1; + chroma_y_shift = 1; + break; + case AV_PIX_FMT_YUV422P: + case AV_PIX_FMT_YUVJ422P: + chroma_x_shift = 1; + break; + case AV_PIX_FMT_YUV444P: + case AV_PIX_FMT_YUVJ444P: + break; + default: + av_packet_free(&packet); + av_frame_free(&frame); + avcodec_free_context(&context); + return false; + } + + *width = frame->width; + *height = frame->height; + rgba->resize(static_cast(*width) * static_cast(*height) * 4U); + const bool full_range = frame->color_range == AVCOL_RANGE_JPEG + || frame->format == AV_PIX_FMT_YUVJ420P + || frame->format == AV_PIX_FMT_YUVJ422P + || frame->format == AV_PIX_FMT_YUVJ444P; + for (int y = 0; y < *height; ++y) { + const uint8_t *y_row = frame->data[0] + y * frame->linesize[0]; + const uint8_t *u_row = frame->data[1] + (y >> chroma_y_shift) * frame->linesize[1]; + const uint8_t *v_row = frame->data[2] + (y >> chroma_y_shift) * frame->linesize[2]; + uint8_t *out = rgba->data() + static_cast(y) * static_cast(*width) * 4U; + for (int x = 0; x < *width; ++x) { + const double luma = full_range ? static_cast(y_row[x]) + : 1.164383 * (static_cast(y_row[x]) - 16.0); + const double u = static_cast(u_row[x >> chroma_x_shift]) - 128.0; + const double v = static_cast(v_row[x >> chroma_x_shift]) - 128.0; + const double red = luma + (full_range ? 1.402 : 1.596027) * v; + const double green = luma - (full_range ? 0.344136 : 0.391762) * u + - (full_range ? 0.714136 : 0.812968) * v; + const double blue = luma + (full_range ? 1.772 : 2.017232) * u; + out[x * 4 + 0] = static_cast(std::clamp(std::lround(red), 0L, 255L)); + out[x * 4 + 1] = static_cast(std::clamp(std::lround(green), 0L, 255L)); + out[x * 4 + 2] = static_cast(std::clamp(std::lround(blue), 0L, 255L)); + out[x * 4 + 3] = 255; + } + } + + av_packet_free(&packet); + av_frame_free(&frame); + avcodec_free_context(&context); + return true; +} + +std::string format_thumbnail_time(double seconds) { + const int rounded = std::max(0, static_cast(std::lround(seconds))); + const int hours = rounded / 3600; + const int minutes = (rounded % 3600) / 60; + const int secs = rounded % 60; + if (hours > 0) { + return util::string_format("%d:%02d:%02d", hours, minutes, secs); + } + return util::string_format("%02d:%02d", minutes, secs); +} + +} // namespace + +struct ThumbnailView::Impl { + ~Impl() { + destroy_texture(); + } + + void setThumbnails(const std::vector &next_thumbnails) { + destroy_texture(); + thumbnails = &next_thumbnails; + displayed_index = -1; + failed_index = -1; + } + + void update(double tracker_time) { + if (thumbnails == nullptr || thumbnails->empty()) return; + auto it = std::lower_bound(thumbnails->begin(), thumbnails->end(), tracker_time, + [](const ThumbnailFrame &frame, double time) { + return frame.timestamp < time; + }); + if (it == thumbnails->end()) { + it = std::prev(thumbnails->end()); + } else if (it != thumbnails->begin()) { + const auto previous = std::prev(it); + if (std::abs(previous->timestamp - tracker_time) <= std::abs(it->timestamp - tracker_time)) { + it = previous; + } + } + const int index = static_cast(std::distance(thumbnails->begin(), it)); + if (index == displayed_index || index == failed_index) return; + + int width = 0; + int height = 0; + std::vector rgba; + if (!decode_jpeg(it->jpeg, &width, &height, &rgba)) { + failed_index = index; + return; + } + + if (texture == 0) { + glGenTextures(1, &texture); + } + glBindTexture(GL_TEXTURE_2D, texture); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, rgba.data()); + glBindTexture(GL_TEXTURE_2D, 0); + texture_width = width; + texture_height = height; + displayed_index = index; + failed_index = -1; + } + + void drawSized(ImVec2 size, bool loading) const { + size.x = std::max(1.0f, size.x); + size.y = std::max(1.0f, size.y); + ImGui::InvisibleButton("##thumbnail_sized", size); + const ImVec2 pane_min = ImGui::GetItemRectMin(); + const ImVec2 pane_max = ImGui::GetItemRectMax(); + ImDrawList *draw_list = ImGui::GetWindowDrawList(); + draw_list->AddRectFilled(pane_min, pane_max, IM_COL32(24, 24, 24, 255)); + + if (texture != 0 && texture_width > 0 && texture_height > 0) { + const float scale = std::min(size.x / static_cast(texture_width), + size.y / static_cast(texture_height)); + const ImVec2 image_size(static_cast(texture_width) * scale, + static_cast(texture_height) * scale); + const ImVec2 image_min(pane_min.x + (size.x - image_size.x) * 0.5f, + pane_min.y + (size.y - image_size.y) * 0.5f); + const ImVec2 image_max(image_min.x + image_size.x, image_min.y + image_size.y); + draw_list->AddImage(static_cast(texture), image_min, image_max); + + if (thumbnails != nullptr && displayed_index >= 0 + && displayed_index < static_cast(thumbnails->size())) { + const ThumbnailFrame &frame = (*thumbnails)[static_cast(displayed_index)]; + const std::string label = util::string_format("%s · segment %d · %d/%zu", + format_thumbnail_time(frame.timestamp).c_str(), + frame.segment, + displayed_index + 1, + thumbnails->size()); + const ImVec2 text_size = ImGui::CalcTextSize(label.c_str()); + const ImVec2 label_min(image_min.x, std::max(image_min.y, image_max.y - text_size.y - 14.0f)); + draw_list->AddRectFilled(label_min, image_max, IM_COL32(0, 0, 0, 175)); + draw_list->AddText(ImVec2(label_min.x + 7.0f, label_min.y + 7.0f), IM_COL32_WHITE, label.c_str()); + } + return; + } + + const bool has_thumbnails = thumbnails != nullptr && !thumbnails->empty(); + const char *label = loading ? "loading" : (has_thumbnails ? "invalid thumbnail" : "no thumbnails"); + const ImVec2 text_size = ImGui::CalcTextSize(label); + draw_list->AddText(ImVec2(pane_min.x + (size.x - text_size.x) * 0.5f, + pane_min.y + (size.y - text_size.y) * 0.5f), + IM_COL32(187, 187, 187, 255), label); + } + + void destroy_texture() { + if (texture != 0) { + glDeleteTextures(1, &texture); + } + texture = 0; + texture_width = 0; + texture_height = 0; + } + + const std::vector *thumbnails = nullptr; + int displayed_index = -1; + int failed_index = -1; + GLuint texture = 0; + int texture_width = 0; + int texture_height = 0; +}; + +ThumbnailView::ThumbnailView() : impl_(std::make_unique()) {} +ThumbnailView::~ThumbnailView() = default; + +void ThumbnailView::setThumbnails(const std::vector &thumbnails) { + impl_->setThumbnails(thumbnails); +} + +void ThumbnailView::update(double tracker_time) { + impl_->update(tracker_time); +} + +void ThumbnailView::drawSized(ImVec2 size, bool loading) { + impl_->drawSized(size, loading); +} + +void draw_thumbnail_pane(AppSession *session, UiState *state) { + if (session->thumbnail_view == nullptr) { + ImGui::TextDisabled("Thumbnails unavailable"); + return; + } + if (state->has_tracker_time) { + session->thumbnail_view->update(state->tracker_time); + } + session->thumbnail_view->drawSized(ImGui::GetContentRegionAvail(), session->async_route_loading); +} diff --git a/openpilot/tools/jotpluggler/thumbnail.h b/openpilot/tools/jotpluggler/thumbnail.h new file mode 100644 index 0000000000..6970173a5c --- /dev/null +++ b/openpilot/tools/jotpluggler/thumbnail.h @@ -0,0 +1,5 @@ +#pragma once + +#include "tools/jotpluggler/app.h" + +void draw_thumbnail_pane(AppSession *session, UiState *state); diff --git a/openpilot/tools/jotpluggler/util.cc b/openpilot/tools/jotpluggler/util.cc new file mode 100644 index 0000000000..5c20e795f6 --- /dev/null +++ b/openpilot/tools/jotpluggler/util.cc @@ -0,0 +1,59 @@ +#include "tools/jotpluggler/util.h" + +#include +#include +#include +#include + +std::string read_file_or_throw(const std::filesystem::path &path) { + const std::string contents = util::read_file(path.string()); + if (!contents.empty() || std::filesystem::exists(path)) { + return contents; + } + throw std::runtime_error("Failed to read " + path.string()); +} + +void write_file_or_throw(const std::filesystem::path &path, const void *data, size_t size) { + ensure_parent_dir(path); + const std::string path_string = path.string(); + const void *bytes = size == 0 ? static_cast("") : data; + if (util::write_file(path_string.c_str(), bytes, size, O_WRONLY | O_CREAT | O_TRUNC) != 0) { + throw std::runtime_error("Failed to write " + path_string); + } +} + +void write_file_or_throw(const std::filesystem::path &path, std::string_view contents) { + write_file_or_throw(path, contents.data(), contents.size()); +} + +void run_system_or_throw(const std::string &command, std::string_view action) { + const int ret = std::system(command.c_str()); + if (ret != 0) { + throw std::runtime_error(util::string_format("%.*s failed with exit code %d", + static_cast(action.size()), action.data(), ret)); + } +} + +CommandResult run_process_capture_output(const std::vector &args) { + std::string command; + for (const std::string &arg : args) { + if (!command.empty()) command += ' '; + command += shell_quote(arg); + } + command += " 2>&1"; + + FILE *pipe = popen(command.c_str(), "r"); + if (pipe == nullptr) { + throw std::runtime_error("popen() failed"); + } + + CommandResult result; + std::array buf = {}; + while (fgets(buf.data(), static_cast(buf.size()), pipe) != nullptr) { + result.output += buf.data(); + } + + const int status = pclose(pipe); + result.exit_code = WIFEXITED(status) ? WEXITSTATUS(status) : 1; + return result; +} diff --git a/openpilot/tools/jotpluggler/util.h b/openpilot/tools/jotpluggler/util.h new file mode 100644 index 0000000000..ea77a236f0 --- /dev/null +++ b/openpilot/tools/jotpluggler/util.h @@ -0,0 +1,103 @@ +#pragma once + +#include "common/util.h" +#include "imgui.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +inline ImVec4 color_rgb(int r, int g, int b, float alpha = 1.0f) { + return ImVec4(static_cast(r) / 255.0f, + static_cast(g) / 255.0f, + static_cast(b) / 255.0f, + alpha); +} + +inline ImVec4 color_rgb(const std::array &color, float alpha = 1.0f) { + return color_rgb(color[0], color[1], color[2], alpha); +} + +inline std::string lowercase_copy(std::string_view value) { + std::string out(value); + std::transform(out.begin(), out.end(), out.begin(), [](unsigned char c) { + return static_cast(std::tolower(c)); + }); + return out; +} + +inline int imgui_resize_callback(ImGuiInputTextCallbackData *data) { + if (data->EventFlag != ImGuiInputTextFlags_CallbackResize || data->UserData == nullptr) return 0; + auto *text = static_cast(data->UserData); + text->resize(static_cast(data->BufTextLen)); + data->Buf = text->data(); + return 0; +} + +inline bool input_text_string(const char *label, + std::string *text, + ImGuiInputTextFlags flags = 0) { + flags |= ImGuiInputTextFlags_CallbackResize; + return ImGui::InputText(label, text->data(), text->capacity() + 1, + flags, imgui_resize_callback, text); +} + +inline bool input_text_with_hint_string(const char *label, + const char *hint, + std::string *text, + ImGuiInputTextFlags flags = 0) { + flags |= ImGuiInputTextFlags_CallbackResize; + return ImGui::InputTextWithHint(label, hint, text->data(), text->capacity() + 1, + flags, imgui_resize_callback, text); +} + +inline bool input_text_multiline_string(const char *label, + std::string *text, + const ImVec2 &size = ImVec2(0.0f, 0.0f), + ImGuiInputTextFlags flags = 0) { + flags |= ImGuiInputTextFlags_CallbackResize; + return ImGui::InputTextMultiline(label, text->data(), text->capacity() + 1, + size, flags, imgui_resize_callback, text); +} + +inline bool is_local_stream_address(std::string_view address) { + return address.empty() || address == "127.0.0.1" || address == "localhost"; +} + +inline void ensure_parent_dir(const std::filesystem::path &path) { + if (path.has_parent_path()) { + std::filesystem::create_directories(path.parent_path()); + } +} + +inline std::string shell_quote(std::string_view value) { + std::string quoted; + quoted.reserve(value.size() + 8); + quoted.push_back('\''); + for (char c : value) { + if (c == '\'') { + quoted += "'\\''"; + } else { + quoted.push_back(c); + } + } + quoted.push_back('\''); + return quoted; +} + +struct CommandResult { + int exit_code = 0; + std::string output; +}; + +std::string read_file_or_throw(const std::filesystem::path &path); +void write_file_or_throw(const std::filesystem::path &path, std::string_view contents); +void write_file_or_throw(const std::filesystem::path &path, const void *data, size_t size); +void run_system_or_throw(const std::string &command, std::string_view action); +CommandResult run_process_capture_output(const std::vector &args); diff --git a/openpilot/tools/joystick/README.md b/openpilot/tools/joystick/README.md new file mode 100644 index 0000000000..3ce308927c --- /dev/null +++ b/openpilot/tools/joystick/README.md @@ -0,0 +1,53 @@ +# Joystick + +**Hardware needed**: device running openpilot, laptop, joystick (optional) + +With joystick_control, you can connect your laptop to your comma device over the network and debug controls using a joystick or keyboard. +joystick_control uses [inputs](https://pypi.org/project/inputs) which supports many common gamepads and joysticks. + +## Usage + +The car must be off, and openpilot must be offroad before starting `joystick_control`. + +### Using a keyboard + +SSH into your comma device and start joystick_control with the following command: + +```shell +openpilot/tools/joystick/joystick_control.py --keyboard +``` + +The available buttons and axes will print showing their key mappings. In general, the WASD keys control gas and brakes and steering torque in 5% increments. + +### Joystick on your comma three + +Plug the joystick into your comma three aux USB-C port. Then, SSH into the device and start `joystick_control.py`. + +### Joystick on your laptop + +In order to use a joystick over the network, we need to run joystick_control locally from your laptop and have it send `testJoystick` packets over the network to the comma device. + +1. Connect a joystick to your PC. +2. Connect your laptop to your comma device's hotspot and open a new SSH shell. Since joystick_control is being run on your laptop, we need to write a parameter to let controlsd know to start in joystick debug mode: + ```shell + # on your comma device + echo -n "1" > /data/params/d/JoystickDebugMode + ``` +3. Run bridge with your laptop's IP address. This republishes the `testJoystick` packets sent from your laptop so that openpilot can receive them: + ```shell + # on your comma device + openpilot/cereal/messaging/bridge {LAPTOP_IP} testJoystick + ``` +4. Start joystick_control on your laptop in ZMQ mode. + ```shell + # on your laptop + export ZMQ=1 + openpilot/tools/joystick/joystick_control.py + ``` + +--- +Now start your car and openpilot should go into joystick mode with an alert on startup! The status of the axes will display on the alert, while button statuses print in the shell. + +Make sure the conditions are met in the panda to allow controls (e.g. cruise control engaged). You can also make a modification to the panda code to always allow controls. + +![](https://github.com/commaai/openpilot/assets/8762862/e640cbca-cb7a-4dcb-abce-b23b036ad8e7) diff --git a/openpilot/tools/joystick/joystick_control.py b/openpilot/tools/joystick/joystick_control.py new file mode 100755 index 0000000000..9a39d564db --- /dev/null +++ b/openpilot/tools/joystick/joystick_control.py @@ -0,0 +1,147 @@ +#!/usr/bin/env python3 +import os +import argparse +import threading +import numpy as np +from inputs import UnpluggedError, get_gamepad + +from openpilot.cereal import messaging +from openpilot.common.params import Params +from openpilot.common.realtime import Ratekeeper +from openpilot.common.hardware import HARDWARE +from openpilot.tools.lib.kbhit import KBHit + +EXPO = 0.4 + + +class Keyboard: + def __init__(self): + self.kb = KBHit() + self.axis_increment = 0.05 # 5% of full actuation each key press + self.axes_map = {'w': 'gb', 's': 'gb', + 'a': 'steer', 'd': 'steer'} + self.axes_values = {'gb': 0., 'steer': 0.} + self.axes_order = ['gb', 'steer'] + self.cancel = False + + def update(self): + key = self.kb.getch().lower() + self.cancel = False + if key == 'r': + self.axes_values = dict.fromkeys(self.axes_values, 0.) + elif key == 'c': + self.cancel = True + elif key in self.axes_map: + axis = self.axes_map[key] + incr = self.axis_increment if key in ['w', 'a'] else -self.axis_increment + self.axes_values[axis] = float(np.clip(self.axes_values[axis] + incr, -1, 1)) + else: + return False + return True + + +class Joystick: + def __init__(self): + # This class supports a PlayStation 5 DualSense controller on the comma 3X + # TODO: find a way to get this from API or detect gamepad/PC, perhaps "inputs" doesn't support it + self.cancel_button = 'BTN_NORTH' # BTN_NORTH=X/triangle + if HARDWARE.get_device_type() == 'pc': + accel_axis = 'ABS_Z' + steer_axis = 'ABS_RX' + # TODO: once the longcontrol API is finalized, we can replace this with outputting gas/brake and steering + self.flip_map = {'ABS_RZ': accel_axis} + else: + accel_axis = 'ABS_RX' + steer_axis = 'ABS_Z' + self.flip_map = {'ABS_RY': accel_axis} + + self.min_axis_value = {accel_axis: 0., steer_axis: 0.} + self.max_axis_value = {accel_axis: 255., steer_axis: 255.} + self.axes_values = {accel_axis: 0., steer_axis: 0.} + self.axes_order = [accel_axis, steer_axis] + self.cancel = False + + def update(self): + try: + joystick_event = get_gamepad()[0] + except (OSError, UnpluggedError): + self.axes_values = dict.fromkeys(self.axes_values, 0.) + return False + + event = (joystick_event.code, joystick_event.state) + + # flip left trigger to negative accel + if event[0] in self.flip_map: + event = (self.flip_map[event[0]], -event[1]) + + if event[0] == self.cancel_button: + if event[1] == 1: + self.cancel = True + elif event[1] == 0: # state 0 is falling edge + self.cancel = False + elif event[0] in self.axes_values: + self.max_axis_value[event[0]] = max(event[1], self.max_axis_value[event[0]]) + self.min_axis_value[event[0]] = min(event[1], self.min_axis_value[event[0]]) + + norm = -float(np.interp(event[1], [self.min_axis_value[event[0]], self.max_axis_value[event[0]]], [-1., 1.])) + norm = norm if abs(norm) > 0.03 else 0. # center can be noisy, deadzone of 3% + self.axes_values[event[0]] = EXPO * norm ** 3 + (1 - EXPO) * norm # less action near center for fine control + else: + return False + return True + + +def send_thread(joystick): + pm = messaging.PubMaster(['testJoystick']) + + rk = Ratekeeper(100, print_delay_threshold=None) + + while True: + if rk.frame % 20 == 0: + print('\n' + ', '.join(f'{name}: {round(v, 3)}' for name, v in joystick.axes_values.items())) + + joystick_msg = messaging.new_message('testJoystick') + joystick_msg.valid = True + joystick_msg.testJoystick.axes = [joystick.axes_values[ax] for ax in joystick.axes_order] + + pm.send('testJoystick', joystick_msg) + + rk.keep_time() + + +def joystick_control_thread(joystick): + Params().put_bool('JoystickDebugMode', True, block=True) + threading.Thread(target=send_thread, args=(joystick,), daemon=True).start() + while True: + joystick.update() + + +def main(): + joystick_control_thread(Joystick()) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='Publishes events from your joystick to control your car.\n' + + 'openpilot must be offroad before starting joystick_control. This tool supports ' + + 'a PlayStation 5 DualSense controller on the comma 3X.', + formatter_class=argparse.ArgumentDefaultsHelpFormatter) + parser.add_argument('--keyboard', action='store_true', help='Use your keyboard instead of a joystick') + args = parser.parse_args() + + if not Params().get_bool("IsOffroad") and "ZMQ" not in os.environ: + print("The car must be off before running joystick_control.") + exit() + + print() + if args.keyboard: + print('Gas/brake control: `W` and `S` keys') + print('Steering control: `A` and `D` keys') + print('Buttons') + print('- `R`: Resets axes') + print('- `C`: Cancel cruise control') + else: + print('Using joystick, make sure to run openpilot/cereal/messaging/bridge on your device if running over the network!') + print('If not running on a comma device, the mapping may need to be adjusted.') + + joystick = Keyboard() if args.keyboard else Joystick() + joystick_control_thread(joystick) diff --git a/tools/joystick/joystickd.py b/openpilot/tools/joystick/joystickd.py similarity index 84% rename from tools/joystick/joystickd.py rename to openpilot/tools/joystick/joystickd.py index fb65df36a0..ac2f99f67e 100755 --- a/tools/joystick/joystickd.py +++ b/openpilot/tools/joystick/joystickd.py @@ -3,7 +3,8 @@ import math import numpy as np -from cereal import messaging, car +from openpilot.cereal import messaging +from opendbc.car.structs import car from opendbc.car.vehicle_model import VehicleModel from openpilot.common.realtime import DT_CTRL, Ratekeeper from openpilot.common.params import Params @@ -19,24 +20,18 @@ def joystickd_thread(): CP = messaging.log_from_bytes(params.get("CarParams", block=True), car.CarParams) VM = VehicleModel(CP) - sm = messaging.SubMaster(['carState', 'onroadEvents', 'liveParameters', 'selfdriveState', 'testJoystick', 'selfdriveStateSP'], frequency=1. / DT_CTRL) + sm = messaging.SubMaster(['carState', 'onroadEvents', 'liveParameters', 'selfdriveState', 'testJoystick'], frequency=1. / DT_CTRL) pm = messaging.PubMaster(['carControl', 'controlsState']) rk = Ratekeeper(100, print_delay_threshold=None) while 1: sm.update(0) - ss_sp = sm['selfdriveStateSP'] - _lat_active = False - if ss_sp.mads.available: - _lat_active = ss_sp.mads.active - else: - _lat_active = sm['selfdriveState'].active cc_msg = messaging.new_message('carControl') cc_msg.valid = True CC = cc_msg.carControl CC.enabled = sm['selfdriveState'].enabled - CC.latActive = _lat_active and not sm['carState'].steerFaultTemporary and not sm['carState'].steerFaultPermanent + CC.latActive = sm['selfdriveState'].active and not sm['carState'].steerFaultTemporary and not sm['carState'].steerFaultPermanent CC.longActive = CC.enabled and not any(e.overrideLongitudinal for e in sm['onroadEvents']) and CP.openpilotLongitudinalControl CC.cruiseControl.cancel = sm['carState'].cruiseState.enabled and (not CC.enabled or not CP.pcmCruise) CC.hudControl.leadDistanceBars = 2 @@ -53,7 +48,8 @@ def joystickd_thread(): if CC.longActive: actuators.accel = 4.0 * float(np.clip(joystick_axes[0], -1, 1)) - actuators.longControlState = LongCtrlState.pid if sm['carState'].vEgo > CP.vEgoStopping else LongCtrlState.stopping + actuators.longControlState = LongCtrlState.pid if sm['carState'].vEgo > 0.1 else LongCtrlState.stopping + CC.cruiseControl.resume = actuators.accel > 0.0 if CC.latActive: max_curvature = MAX_LAT_ACCEL / max(sm['carState'].vEgo ** 2, 5) diff --git a/openpilot/tools/lateral_maneuvers/.gitignore b/openpilot/tools/lateral_maneuvers/.gitignore new file mode 100644 index 0000000000..a0b6efe6b3 --- /dev/null +++ b/openpilot/tools/lateral_maneuvers/.gitignore @@ -0,0 +1 @@ +/lateral_reports/ diff --git a/openpilot/tools/lateral_maneuvers/README.md b/openpilot/tools/lateral_maneuvers/README.md new file mode 100644 index 0000000000..7a4c381b15 --- /dev/null +++ b/openpilot/tools/lateral_maneuvers/README.md @@ -0,0 +1,42 @@ +# Lateral Maneuvers Testing Tool + +> [!WARNING] +> Use caution when using this tool. + +Test your vehicle's lateral control tuning with this tool. The tool will test the vehicle's ability to follow a few lateral maneuvers and includes a tool to generate a report from the route. + +## Instructions + +1. Check out a development branch such as `master` on your comma device. +2. The full maneuver suite runs at 20 and 30 mph. +3. Enable "Lateral Maneuver Mode" in Settings > Developer on the device while offroad. Alternatively, set the parameter manually: + + ```sh + echo -n 1 > /data/params/d/LateralManeuverMode + ``` + +4. Turn your vehicle back on. You will see "Lateral Maneuver Mode". + +5. Ensure the area ahead is clear, as openpilot will command lateral acceleration steps in this mode. Once you are ready, set ACC manually to the target speed shown on screen and let openpilot stabilize lateral. After 1 seconds of steady straight driving, the maneuver will begin automatically. openpilot lateral control stays engaged between maneuvers normally while waiting for the next maneuver's readiness conditions. The maneuver will be aborted and repeated if speed is out of range, steering is touched or openpilot disengages. + +6. When the testing is complete, you'll see an alert that says "Maneuvers Finished." Complete the route by pulling over and turning off the vehicle. + +7. Visit https://connect.comma.ai and locate the route(s). They will stand out with lots of orange intervals in their timeline. Ensure "All logs" show as "uploaded." + + ![image](https://github.com/user-attachments/assets/cfe4c6d9-752f-4b24-b421-4b90a01933dc) + +8. Gather the route ID and then run the report generator. The file will be exported to the same directory: + + ```sh + $ python openpilot/tools/lateral_maneuvers/generate_report.py 98395b7c5b27882e/000001cc--5a73bde686 + + processing report for KIA_EV6 + plotting maneuver: step right 20mph, runs: 3 + plotting maneuver: step left 20mph, runs: 3 + plotting maneuver: sine 0.5Hz 20mph, runs: 3 + plotting maneuver: step right 30mph, runs: 3 + + Opening report: /home/batman/openpilot/tools/lateral_maneuvers/lateral_reports/KIA_EV6_98395b7c5b27882e_000001cc--5a73bde686.html + ``` + +You can reach out on [Discord](https://discord.comma.ai) if you have any questions about these instructions or the tool itself. diff --git a/openpilot/tools/lateral_maneuvers/generate_report.py b/openpilot/tools/lateral_maneuvers/generate_report.py new file mode 100755 index 0000000000..e26690e2da --- /dev/null +++ b/openpilot/tools/lateral_maneuvers/generate_report.py @@ -0,0 +1,251 @@ +#!/usr/bin/env python3 +import argparse +import base64 +import io +import math +import numpy as np +import os +import webbrowser +from collections import defaultdict +from pathlib import Path +import matplotlib.pyplot as plt +from openpilot.common.utils import tabulate + +from opendbc.car.structs import car +from openpilot.common.filter_simple import FirstOrderFilter +from openpilot.selfdrive.controls.lib.latcontrol_torque import LP_FILTER_CUTOFF_HZ +from openpilot.tools.lib.logreader import LogReader +from openpilot.common.hardware.hw import Paths +from openpilot.common.constants import CV +from openpilot.tools.longitudinal_maneuvers.generate_report import format_car_params + + +def lat_accel(curvature, v): + return curvature * max(v, 1.0) ** 2 + + +def report(platform, route, _description, CP, ID, maneuvers): + output_path = Path(__file__).resolve().parent / "lateral_reports" + output_fn = output_path / f"{platform}_{route.replace('/', '_')}.html" + output_path.mkdir(exist_ok=True) + target_cross_times = defaultdict(list) + + builder = [ + "\n", + "

Lateral maneuver report

\n", + f"

{platform}

\n", + f"

{route}

\n", + f"

{ID.gitCommit}, {ID.gitBranch}, {ID.gitRemote}

\n", + ] + if _description is not None: + builder.append(f"

Description: {_description}

\n") + builder.append(f"

CarParams

{format_car_params(CP)}
\n") + builder.append('{ summary }') # to be replaced below + for description, runs in maneuvers: + # filter incomplete runs + completed_runs = [msgs for msgs in runs + if any(m.alertDebug.alertText1 == 'Complete' for m in msgs if m.which() == 'alertDebug')] + print(f'plotting maneuver: {description}') + if not completed_runs: + continue + builder.append("
\n") + builder.append(f"

{description}

\n") + for run, msgs in enumerate(completed_runs): + last_active = max(m.logMonoTime for m in msgs if m.which() == 'lateralManeuverPlan' and m.valid) + msgs = [m for m in msgs if m.logMonoTime <= last_active] + t_carControl, carControl = zip(*[(m.logMonoTime, m.carControl) for m in msgs if m.which() == 'carControl'], strict=True) + t_carState, carState = zip(*[(m.logMonoTime, m.carState) for m in msgs if m.which() == 'carState'], strict=True) + t_controlsState, controlsState = zip(*[(m.logMonoTime, m.controlsState) for m in msgs if m.which() == 'controlsState'], strict=True) + t_lateralPlan, lateralPlan = zip(*[(m.logMonoTime, m.lateralManeuverPlan) for m in msgs if m.which() == 'lateralManeuverPlan' and m.valid], strict=True) + t_carOutput, carOutput = zip(*[(m.logMonoTime, m.carOutput) for m in msgs if m.which() == 'carOutput'], strict=True) + + # make time relative seconds + t_carControl = [(t - t_carControl[0]) / 1e9 for t in t_carControl] + t_carState = [(t - t_carState[0]) / 1e9 for t in t_carState] + t_controlsState = [(t - t_controlsState[0]) / 1e9 for t in t_controlsState] + t_lateralPlan = [(t - t_lateralPlan[0]) / 1e9 for t in t_lateralPlan] + t_carOutput = [(t - t_carOutput[0]) / 1e9 for t in t_carOutput] + + # maneuver validity + latActive = [m.latActive for m in carControl] + maneuver_valid = all(latActive) and not any(cs.steeringPressed for cs in carState) + + _open = 'open' if maneuver_valid else '' + title = f'Run #{int(run)+1}' + (' (invalid maneuver!)' if not maneuver_valid else '') + + builder.append(f"

{title}

\n") + + baseline_accel = lat_accel(controlsState[0].curvature, carState[0].vEgo) + v_ego = [m.vEgo for m in carState] + cross_markers = [] + + if description.startswith(('sine', 'jitter')): + amplitude = max(abs(lat_accel(lp.desiredCurvature, v) - baseline_accel) + for lp, v in zip(lateralPlan, v_ego, strict=False)) + threshold = amplitude * 0.5 + builder.append('

50% peak') + for t, cs, v in zip(t_controlsState, controlsState, v_ego, strict=False): + actual = lat_accel(cs.curvature, v) - baseline_accel + if abs(actual) > threshold: + builder.append(f', crossed in {t:.3f}s') + cross_markers.append((t, actual + baseline_accel)) + if maneuver_valid: + target_cross_times[description].append(t) + break + else: + builder.append(', not crossed') + builder.append('

') + if maneuver_valid: + target_cross_times.setdefault(description, []) + else: + action_targets = [(0, lat_accel(lateralPlan[0].desiredCurvature, v_ego[0]) - baseline_accel)] + for i in range(1, min(len(lateralPlan), len(v_ego))): + if abs(lateralPlan[i].desiredCurvature - lateralPlan[i - 1].desiredCurvature) > 0.001: + desired = lat_accel(lateralPlan[i].desiredCurvature, v_ego[i]) - baseline_accel + action_targets.append((i, desired)) + + for j, (start_i, act_target) in enumerate(action_targets): + start_time = t_lateralPlan[start_i] + end_time = t_lateralPlan[action_targets[j + 1][0]] if j + 1 < len(action_targets) else t_controlsState[-1] + + builder.append(f'

aTarget: {round(act_target, 1)} m/s^2') + prev_crossed = False + for t, cs, v in zip(t_controlsState, controlsState, v_ego, strict=False): + if not (start_time <= t <= end_time): + continue + actual_accel = lat_accel(cs.curvature, v) - baseline_accel + crossed = (0 < act_target < actual_accel) or (0 > act_target > actual_accel) + if crossed and prev_crossed: + cross_time = t - start_time + builder.append(f', crossed in {cross_time:.3f}s') + cross_markers.append((t, act_target + baseline_accel)) + if maneuver_valid: + target_cross_times[description].append(cross_time) + break + prev_crossed = crossed + else: + builder.append(', not crossed') + builder.append('

') + if maneuver_valid: + target_cross_times.setdefault(description, []) + + plt.rcParams['font.size'] = 40 + fig = plt.figure(figsize=(30, 40)) + ax = fig.subplots(5, 1, sharex=True, gridspec_kw={'height_ratios': [5, 5, 3, 3, 3]}) + + ax[0].grid(linewidth=4) + desired_label = 'lateralManeuverPlan.desiredCurvature * vEgo^2' + desired_lat_accel = [lat_accel(m.desiredCurvature, v) for m, v in zip(lateralPlan, v_ego, strict=False)] + if description.startswith(('sine', 'jitter')): + ax[0].plot(t_lateralPlan[:len(desired_lat_accel)], desired_lat_accel, 'C1', label=desired_label, linewidth=6) + else: + t_desired = [t_lateralPlan[0]] + t_lateralPlan[:len(desired_lat_accel)] + desired_lat_accel = [baseline_accel] + desired_lat_accel + ax[0].step(t_desired, desired_lat_accel, 'C1', label=desired_label, linewidth=6, where='post') + actual_lat_accel = [lat_accel(cs.curvature, v) for cs, v in zip(controlsState, v_ego, strict=False)] + ax[0].plot(t_controlsState[:len(actual_lat_accel)], actual_lat_accel, 'g', label='controlsState.curvature * vEgo^2', linewidth=6) + ax[0].set_ylabel('Lateral Accel (m/s^2)') + for ct, cv in cross_markers: + ax[0].plot(ct, cv, marker='o', markersize=50, markeredgewidth=7, markeredgecolor='black', markerfacecolor='None') + ax[0].legend(prop={'size': 30}) + + ax[1].grid(linewidth=4) + if CP.steerControlType == car.CarParams.SteerControlType.angle: + steer_field, steer_ylabel = 'steeringAngleDeg', 'Steer angle (deg)' + elif CP.steerControlType == car.CarParams.SteerControlType.curvature: + steer_field, steer_ylabel = 'curvature', 'Curvature (1/m)' + else: + steer_field, steer_ylabel = 'torque', 'Steer torque' + ax[1].plot(t_carControl, [getattr(m.actuators, steer_field) for m in carControl], 'C1', label=f'carControl.actuators.{steer_field}', linewidth=6) + ax[1].plot(t_carOutput, [getattr(m.actuatorsOutput, steer_field) for m in carOutput], 'g', label=f'carOutput.actuatorsOutput.{steer_field}', linewidth=6) + ax[1].set_ylabel(steer_ylabel) + ax[1].legend(prop={'size': 30}) + + ax[2].grid(linewidth=4) + ax[2].plot(t_carState, [v * CV.MS_TO_MPH for v in v_ego], label='carState.vEgo', linewidth=6) + ax[2].set_ylabel('Velocity (mph)') + ax[2].yaxis.set_major_formatter(plt.FormatStrFormatter('%.1f')) + ax[2].legend() + + t_accel = np.array(t_controlsState[:len(actual_lat_accel)]) + raw_jerk = np.gradient(actual_lat_accel, t_accel) + dt_avg = np.mean(np.diff(t_accel)) + jerk_filter = FirstOrderFilter(0.0, 1 / (2 * np.pi * LP_FILTER_CUTOFF_HZ), dt_avg) + filtered_jerk = [jerk_filter.update(j) for j in raw_jerk] + ax[3].grid(linewidth=4) + ax[3].plot(t_accel, filtered_jerk, label='d/dt(controlsState.curvature * vEgo^2)', linewidth=6) + ax[3].set_ylabel('Jerk (m/s^3)') + ax[3].legend() + + ax[4].grid(linewidth=4) + ax[4].plot(t_carControl, [math.degrees(m.orientationNED[0]) for m in carControl], label='carControl.orientationNED[0]', linewidth=6) + ax[4].set_ylabel('Roll (deg)') + ax[4].legend() + + ax[-1].set_xlabel("Time (s)") + fig.tight_layout() + + buffer = io.BytesIO() + fig.savefig(buffer, format='webp') + plt.close(fig) + buffer.seek(0) + builder.append(f"\n") + builder.append("
\n") + + summary = ["

Summary

\n"] + cols = ['maneuver', 'crossed', 'mean', 'min', 'max'] + table = [] + for description, times in target_cross_times.items(): + l = [description, len(times)] + if len(times): + l.extend([round(sum(times) / len(times), 2), round(min(times), 2), round(max(times), 2)]) + table.append(l) + summary.append(tabulate(table, headers=cols, tablefmt='html', numalign='left') + '\n') + + sum_idx = builder.index('{ summary }') + builder[sum_idx:sum_idx + 1] = summary + + with open(output_fn, "w") as f: + f.write(''.join(builder)) + + print(f"\nOpening report: {output_fn}\n") + webbrowser.open_new_tab(str(output_fn)) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='Generate lateral maneuver report from route') + parser.add_argument('route', type=str, help='Route name (e.g. 00000000--5f742174be)') + parser.add_argument('description', type=str, nargs='?') + + args = parser.parse_args() + + if '/' in args.route or '|' in args.route: + lr = LogReader(args.route, only_union_types=True) + else: + segs = [seg for seg in os.listdir(Paths.log_root()) if args.route in seg] + lr = LogReader([os.path.join(Paths.log_root(), seg, 'rlog.zst') for seg in segs], only_union_types=True) + + CP = lr.first('carParams') + ID = lr.first('initData') + platform = CP.carFingerprint + print('processing report for', platform) + + maneuvers: list[tuple[str, list[list]]] = [] + active_prev = False + description_prev = None + + for msg in lr: + if msg.which() == 'alertDebug': + active = 'Active' in msg.alertDebug.alertText1 or msg.alertDebug.alertText1 == 'Complete' + if active and not active_prev: + if msg.alertDebug.alertText2 == description_prev: + maneuvers[-1][1].append([]) + else: + maneuvers.append((msg.alertDebug.alertText2, [[]])) + description_prev = maneuvers[-1][0] + active_prev = active + + if active_prev: + maneuvers[-1][1][-1].append(msg) + + report(platform, args.route, args.description, CP, ID, maneuvers) diff --git a/openpilot/tools/lateral_maneuvers/lateral_maneuversd.py b/openpilot/tools/lateral_maneuvers/lateral_maneuversd.py new file mode 100755 index 0000000000..ed07c896f9 --- /dev/null +++ b/openpilot/tools/lateral_maneuvers/lateral_maneuversd.py @@ -0,0 +1,204 @@ +#!/usr/bin/env python3 +import numpy as np +from dataclasses import dataclass + +from openpilot.cereal import messaging +from opendbc.car.structs import car +from openpilot.common.constants import CV +from openpilot.common.realtime import DT_MDL +from openpilot.common.params import Params +from openpilot.common.swaglog import cloudlog +from openpilot.selfdrive.controls.lib.drive_helpers import MIN_SPEED +from openpilot.tools.longitudinal_maneuvers.maneuversd import Action, Maneuver as _Maneuver + +# thresholds for starting maneuvers +MAX_SPEED_DEV = 0.7 # deviation in m/s +MAX_CURV = 0.004 # 250 m radius +MAX_ROLL = 0.12 # 6.8° +TIMER = 2.0 # sec stable conditions before starting maneuver + +@dataclass +class Maneuver(_Maneuver): + _baseline_curvature: float = 0.0 + + def get_accel(self, v_ego: float, lat_active: bool, curvature: float, roll: float) -> float: + self._run_completed = False + # only start maneuver on straight, flat roads + ready = abs(v_ego - self.initial_speed) < MAX_SPEED_DEV and lat_active and abs(curvature) < MAX_CURV and abs(roll) < MAX_ROLL + self._ready_cnt = (self._ready_cnt + 1) if ready else max(self._ready_cnt - 1, 0) + + if self._ready_cnt > (TIMER / DT_MDL): + if not self._active: + self._baseline_curvature = curvature + self._active = True + + if not self._active: + return 0.0 + + return self._step() + + def reset(self): + super().reset() + self._ready_cnt = 0 + + +def _sine_action(amplitude, period, duration): + t = np.linspace(0, duration, int(duration / DT_MDL) + 1) + a = amplitude * np.sin(2 * np.pi * t / period) + return Action(a.tolist(), t.tolist()) + + +MANEUVERS = [ + Maneuver( + "step right 20mph", + [Action([0.5], [1.0]), Action([-0.5], [1.5])], + repeat=2, + initial_speed=20. * CV.MPH_TO_MS, + ), + Maneuver( + "step left 20mph", + [Action([-0.5], [1.0]), Action([0.5], [1.5])], + repeat=2, + initial_speed=20. * CV.MPH_TO_MS, + ), + Maneuver( + "sine 0.5Hz 20mph", + [_sine_action(1.0, 2.0, 2.0), Action([0.0], [0.5])], + repeat=2, + initial_speed=20. * CV.MPH_TO_MS, + ), + Maneuver( + "jitter 20mph", + [Action([-0.5 if i % 2 == 0 else 0.5], [0.1]) for i in range(10)], + repeat=2, + initial_speed=20. * CV.MPH_TO_MS, + ), + Maneuver( + "step right 30mph", + [Action([0.5], [1.0]), Action([-0.5], [1.5])], + repeat=2, + initial_speed=30. * CV.MPH_TO_MS, + ), + Maneuver( + "step left 30mph", + [Action([-0.5], [1.0]), Action([0.5], [1.5])], + repeat=2, + initial_speed=30. * CV.MPH_TO_MS, + ), + Maneuver( + "sine 0.5Hz 30mph", + [_sine_action(1.0, 2.0, 2.0), Action([0.0], [0.5])], + repeat=2, + initial_speed=30. * CV.MPH_TO_MS, + ), + Maneuver( + "jitter 30mph", + [Action([-0.5 if i % 2 == 0 else 0.5], [0.1]) for i in range(10)], + repeat=2, + initial_speed=30. * CV.MPH_TO_MS, + ), +] + + +def main(): + params = Params() + cloudlog.info("lateral_maneuversd is waiting for CarParams") + messaging.log_from_bytes(params.get("CarParams", block=True), car.CarParams) + + sm = messaging.SubMaster(['carState', 'carControl', 'controlsState', 'selfdriveState', 'modelV2'], poll='modelV2') + pm = messaging.PubMaster(['lateralManeuverPlan', 'alertDebug']) + + maneuvers = iter(MANEUVERS) + maneuver = None + complete_cnt = 0 + aborted_cnt = 0 + abort_reason = '' + display_holdoff = 0 + prev_text = '' + + while True: + sm.update() + + if maneuver is None: + maneuver = next(maneuvers, None) + + alert_msg = messaging.new_message('alertDebug') + alert_msg.valid = True + + plan_send = messaging.new_message('lateralManeuverPlan') + + accel = 0 + v_ego = max(sm['carState'].vEgo, 0) + curvature = sm['controlsState'].desiredCurvature + + if complete_cnt > 0: + complete_cnt -= 1 + alert_msg.alertDebug.alertText1 = 'Completed' + alert_msg.alertDebug.alertText2 = maneuver.description + elif maneuver is not None: + # any driver input aborts the maneuver + CS = sm['carState'] + if CS.steeringPressed or CS.gasPressed: + aborted_cnt = int(1.0 / DT_MDL) + abort_reason = ('steering pressed' if CS.steeringPressed else 'gas pressed').ljust(20) + aborted = aborted_cnt > 0 + speed_out_of_range = maneuver.active and abs(v_ego - maneuver.initial_speed) > MAX_SPEED_DEV + if aborted or speed_out_of_range: + maneuver.reset() + + roll = sm['carControl'].orientationNED[0] if len(sm['carControl'].orientationNED) == 3 else 0.0 + accel = maneuver.get_accel(v_ego, sm['carControl'].latActive, curvature, roll) + + if maneuver._run_completed: + complete_cnt = int(1.0 / DT_MDL) + alert_msg.alertDebug.alertText1 = 'Complete' + alert_msg.alertDebug.alertText2 = maneuver.description + elif maneuver.active: + action_remaining = maneuver.actions[maneuver._action_index].time_bp[-1] - maneuver._action_frames * DT_MDL + if maneuver.description.startswith('sine'): + freq = maneuver.description.split()[1] + alert_msg.alertDebug.alertText1 = f'Active sine {freq} {max(action_remaining, 0):.1f}s' + else: + alert_msg.alertDebug.alertText1 = f'Active {accel:+.1f}m/s² {max(action_remaining, 0):.1f}s' + alert_msg.alertDebug.alertText2 = maneuver.description + elif aborted_cnt > 0: + aborted_cnt -= 1 + alert_msg.alertDebug.alertText1 = abort_reason + elif not (abs(v_ego - maneuver.initial_speed) < MAX_SPEED_DEV and sm['carControl'].latActive): + alert_msg.alertDebug.alertText1 = f'Set speed to {maneuver.initial_speed * CV.MS_TO_MPH:0.0f} mph' + elif maneuver._ready_cnt > 0: + ready_time = max(TIMER - maneuver._ready_cnt * DT_MDL, 0) + alert_msg.alertDebug.alertText1 = f'Starting: {int(ready_time) + 1}' + alert_msg.alertDebug.alertText2 = maneuver.description + else: + curv_ok = abs(curvature) < MAX_CURV + reason = 'road not straight' if not curv_ok else 'road not flat' + alert_msg.alertDebug.alertText1 = f'Waiting: {reason}' + alert_msg.alertDebug.alertText2 = maneuver.description + else: + alert_msg.alertDebug.alertText1 = 'Maneuvers Finished' + + # prevent flickering text + setup = ('Set speed', 'Starting', 'Waiting') + text = alert_msg.alertDebug.alertText1 + same = text == prev_text or (text.startswith('Starting') and prev_text.startswith('Starting')) + if not same and text.startswith(setup) and prev_text.startswith(setup) and display_holdoff > 0: + alert_msg.alertDebug.alertText1 = prev_text + display_holdoff -= 1 + else: + prev_text = text + display_holdoff = int(0.5 / DT_MDL) if text.startswith(setup) else 0 + + pm.send('alertDebug', alert_msg) + + plan_send.valid = maneuver is not None and maneuver.active and complete_cnt == 0 + if plan_send.valid: + plan_send.lateralManeuverPlan.desiredCurvature = maneuver._baseline_curvature + accel / max(v_ego, MIN_SPEED) ** 2 + pm.send('lateralManeuverPlan', plan_send) + + if maneuver is not None and maneuver.finished and complete_cnt == 0: + maneuver = None + + +if __name__ == "__main__": + main() diff --git a/openpilot/tools/lib/README.md b/openpilot/tools/lib/README.md new file mode 100644 index 0000000000..17e24816ec --- /dev/null +++ b/openpilot/tools/lib/README.md @@ -0,0 +1,59 @@ +## LogReader + +Route is a class for conveniently accessing all the [logs](/openpilot/system/loggerd/) from your routes. The LogReader class reads the non-video logs, i.e. rlog.bz2 and qlog.bz2. There's also a matching FrameReader class for reading the videos. + +```python +from openpilot.tools.lib.route import Route +from openpilot.tools.lib.logreader import LogReader + +r = Route("a2a0ccea32023010|2023-07-27--13-01-19") + +# get a list of paths for the route's rlog files +print(r.log_paths()) + +# and road camera (fcamera.hevc) files +print(r.camera_paths()) + +# setup a LogReader to read the route's first rlog +lr = LogReader(r.log_paths()[0]) + +# print out all the messages in the log +import codecs +codecs.register_error("strict", codecs.backslashreplace_errors) +for msg in lr: + print(msg) + +# setup a LogReader for the route's second qlog +lr = LogReader(r.log_paths()[1]) + +# print all the steering angles values from the log +for msg in lr: + if msg.which() == "carState": + print(msg.carState.steeringAngleDeg) +``` + +### Segment Ranges + +We also support a new format called a "segment range": + +``` +344c5c15b34f2d8a / 2024-01-03--09-37-12 / 2:6 / q +[ dongle id ] [ timestamp ] [ selector ] [ query type] +``` + +you can specify which segments from a route to load + +```python +lr = LogReader("a2a0ccea32023010|2023-07-27--13-01-19/4") # 4th segment +lr = LogReader("a2a0ccea32023010|2023-07-27--13-01-19/4:6") # 4th and 5th segment +lr = LogReader("a2a0ccea32023010|2023-07-27--13-01-19/-1") # last segment +lr = LogReader("a2a0ccea32023010|2023-07-27--13-01-19/:5") # first 5 segments +lr = LogReader("a2a0ccea32023010|2023-07-27--13-01-19/1:") # all except first segment +``` + +and can select which type of logs to grab + +```python +lr = LogReader("a2a0ccea32023010|2023-07-27--13-01-19/4/q") # get qlogs +lr = LogReader("a2a0ccea32023010|2023-07-27--13-01-19/4/r") # get rlogs (default) +``` diff --git a/openpilot/tools/lib/__init__.py b/openpilot/tools/lib/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/openpilot/tools/lib/api.py b/openpilot/tools/lib/api.py new file mode 100644 index 0000000000..7fca9b320f --- /dev/null +++ b/openpilot/tools/lib/api.py @@ -0,0 +1,40 @@ +import os +import requests +from requests.adapters import HTTPAdapter, Retry +API_HOST = os.getenv('API_HOST', 'https://api.commadotai.com') + +# TODO: this should be merged into common.api + +class CommaApi: + def __init__(self, token=None): + self.session = requests.Session() + self.session.headers['User-agent'] = 'OpenpilotTools' + if token: + self.session.headers['Authorization'] = 'JWT ' + token + + retries = Retry(total=5, backoff_factor=1, status_forcelist=[500, 502, 503, 504]) + self.session.mount('https://', HTTPAdapter(max_retries=retries)) + + def request(self, method, endpoint, **kwargs): + with self.session.request(method, API_HOST + '/' + endpoint, **kwargs) as resp: + resp_json = resp.json() + if isinstance(resp_json, dict) and resp_json.get('error'): + if resp.status_code in [401, 403]: + raise UnauthorizedError('Unauthorized. Authenticate with openpilot/tools/lib/auth.py') + + e = APIError(str(resp.status_code) + ":" + resp_json.get('description', str(resp_json['error']))) + e.status_code = resp.status_code + raise e + return resp_json + + def get(self, endpoint, **kwargs): + return self.request('GET', endpoint, **kwargs) + + def post(self, endpoint, **kwargs): + return self.request('POST', endpoint, **kwargs) + +class APIError(Exception): + pass + +class UnauthorizedError(Exception): + pass diff --git a/tools/lib/auth.py b/openpilot/tools/lib/auth.py similarity index 97% rename from tools/lib/auth.py rename to openpilot/tools/lib/auth.py index 5988397d0a..9139d8b42d 100755 --- a/tools/lib/auth.py +++ b/openpilot/tools/lib/auth.py @@ -54,7 +54,7 @@ class ClientRedirectHandler(BaseHTTPRequestHandler): self.end_headers() self.wfile.write(b'Return to the CLI to continue') - def log_message(self, *args): + def log_message(self, format: str, *args: object) -> None: # noqa: A002 # stdlib override pass # this prevent http server from dumping messages to stdout diff --git a/tools/lib/auth_config.py b/openpilot/tools/lib/auth_config.py similarity index 92% rename from tools/lib/auth_config.py rename to openpilot/tools/lib/auth_config.py index c4e7b6261b..5966bd34a9 100644 --- a/tools/lib/auth_config.py +++ b/openpilot/tools/lib/auth_config.py @@ -1,6 +1,6 @@ import json import os -from openpilot.system.hardware.hw import Paths +from openpilot.common.hardware.hw import Paths class MissingAuthConfigError(Exception): diff --git a/tools/lib/azure_container.py b/openpilot/tools/lib/azure_container.py similarity index 100% rename from tools/lib/azure_container.py rename to openpilot/tools/lib/azure_container.py diff --git a/tools/lib/bootlog.py b/openpilot/tools/lib/bootlog.py similarity index 100% rename from tools/lib/bootlog.py rename to openpilot/tools/lib/bootlog.py diff --git a/tools/lib/cache.py b/openpilot/tools/lib/cache.py similarity index 100% rename from tools/lib/cache.py rename to openpilot/tools/lib/cache.py diff --git a/tools/lib/comma_car_segments.py b/openpilot/tools/lib/comma_car_segments.py similarity index 90% rename from tools/lib/comma_car_segments.py rename to openpilot/tools/lib/comma_car_segments.py index fe9c350a9b..b27887ed29 100644 --- a/tools/lib/comma_car_segments.py +++ b/openpilot/tools/lib/comma_car_segments.py @@ -14,7 +14,8 @@ def get_comma_car_segments_database(): ret = {} for platform in database: - ret[MIGRATION.get(platform, platform)] = database[platform] + # TODO: remove this when commaCarSegments is updated to remove selector + ret[MIGRATION.get(platform, platform)] = [s.rstrip('/s') for s in database[platform]] return ret @@ -73,7 +74,7 @@ def get_repo_url(path): response = requests.head(get_repo_raw_url(path)) - if "text/plain" in response.headers.get("content-type"): + if "text/plain" in response.headers.get("content-type", ""): # This is an LFS pointer, so download the raw data from lfs response = requests.get(get_repo_raw_url(path)) assert response.status_code == 200 @@ -86,5 +87,5 @@ def get_repo_url(path): return get_repo_raw_url(path) -def get_url(route, segment, file="rlog.bz2"): +def get_url(route, segment, file="rlog.zst"): return get_repo_url(f"segments/{route.replace('|', '/')}/{segment}/{file}") diff --git a/tools/lib/exceptions.py b/openpilot/tools/lib/exceptions.py similarity index 100% rename from tools/lib/exceptions.py rename to openpilot/tools/lib/exceptions.py diff --git a/openpilot/tools/lib/file_downloader.py b/openpilot/tools/lib/file_downloader.py new file mode 100755 index 0000000000..68061b201e --- /dev/null +++ b/openpilot/tools/lib/file_downloader.py @@ -0,0 +1,157 @@ +#!/usr/bin/env python3 +""" +CLI tool for downloading files and querying the comma API. +Called by C++ replay/cabana via subprocess. + +Subcommands: + route-files - Get route file URLs as JSON + download - Download URL to local cache, print local path + devices - List user's devices as JSON + device-routes - List routes for a device as JSON +""" +import argparse +import hashlib +import json +import os +import sys +import tempfile +import shutil + +from openpilot.common.hardware.hw import Paths +from openpilot.tools.lib.api import CommaApi, UnauthorizedError, APIError +from openpilot.tools.lib.auth_config import get_token +from openpilot.tools.lib.url_file import URLFile + + +def api_call(func): + """Run an API call, outputting JSON result or error to stdout.""" + try: + result = func(CommaApi(get_token())) + json.dump(result, sys.stdout) + except UnauthorizedError: + json.dump({"error": "unauthorized"}, sys.stdout) + except APIError as e: + error = "not_found" if getattr(e, 'status_code', 0) == 404 else str(e) + json.dump({"error": error}, sys.stdout) + except Exception as e: + json.dump({"error": str(e)}, sys.stdout) + sys.stdout.write("\n") + sys.stdout.flush() + + +def cache_file_path(url): + url_without_query = url.split("?")[0] + return os.path.join(Paths.download_cache_root(), hashlib.sha256(url_without_query.encode()).hexdigest()) + + +def cmd_route_files(args): + api_call(lambda api: api.get(f"v1/route/{args.route}/files")) + + +def cmd_download(args): + url = args.url + use_cache = not args.no_cache + + if use_cache: + local_path = cache_file_path(url) + if os.path.exists(local_path): + sys.stdout.write(local_path + "\n") + sys.stdout.flush() + return + + try: + # Stream the file in a single HTTP request instead of making + # a separate Range request per chunk (which was very slow). + pool = URLFile.pool_manager() + r = pool.request("GET", url, preload_content=False) + if r.status not in (200, 206): + sys.stderr.write(f"ERROR:HTTP {r.status}\n") + sys.stderr.flush() + sys.exit(1) + + total = int(r.headers.get('content-length', 0)) + if total <= 0: + sys.stderr.write("ERROR:File not found or empty\n") + sys.stderr.flush() + sys.exit(1) + + os.makedirs(Paths.download_cache_root(), exist_ok=True) + tmp_fd, tmp_path = tempfile.mkstemp(dir=Paths.download_cache_root()) + try: + downloaded = 0 + chunk_size = 1024 * 1024 + with os.fdopen(tmp_fd, 'wb') as f: + for data in r.stream(chunk_size): + f.write(data) + downloaded += len(data) + sys.stderr.write(f"PROGRESS:{downloaded}:{total}\n") + sys.stderr.flush() + + if use_cache: + shutil.move(tmp_path, local_path) + sys.stdout.write(local_path + "\n") + else: + sys.stdout.write(tmp_path + "\n") + except Exception: + try: + os.unlink(tmp_path) + except OSError: + pass + raise + finally: + r.release_conn() + + except Exception as e: + sys.stderr.write(f"ERROR:{e}\n") + sys.stderr.flush() + sys.exit(1) + + sys.stdout.flush() + + +def cmd_devices(args): + api_call(lambda api: api.get("v1/me/devices/")) + + +def cmd_device_routes(args): + def fetch(api): + if args.preserved: + return api.get(f"v1/devices/{args.dongle_id}/routes/preserved") + params = {} + if args.start is not None: + params['start'] = args.start + if args.end is not None: + params['end'] = args.end + return api.get(f"v1/devices/{args.dongle_id}/routes_segments", params=params) + api_call(fetch) + + +def main(): + parser = argparse.ArgumentParser(description="File downloader CLI for openpilot tools") + subparsers = parser.add_subparsers(dest="command", required=True) + + p_rf = subparsers.add_parser("route-files") + p_rf.add_argument("route") + p_rf.set_defaults(func=cmd_route_files) + + p_dl = subparsers.add_parser("download") + p_dl.add_argument("url") + p_dl.add_argument("--no-cache", action="store_true") + p_dl.set_defaults(func=cmd_download) + + p_dev = subparsers.add_parser("devices") + p_dev.set_defaults(func=cmd_devices) + + p_dr = subparsers.add_parser("device-routes") + p_dr.add_argument("dongle_id") + p_dr.add_argument("--start", type=int, default=None) + p_dr.add_argument("--end", type=int, default=None) + p_dr.add_argument("--preserved", action="store_true") + p_dr.set_defaults(func=cmd_device_routes) + + args = parser.parse_args() + args.func(args) + + +if __name__ == "__main__": + main() diff --git a/openpilot/tools/lib/file_sources.py b/openpilot/tools/lib/file_sources.py new file mode 100755 index 0000000000..2d2bfccfd7 --- /dev/null +++ b/openpilot/tools/lib/file_sources.py @@ -0,0 +1,57 @@ +from collections.abc import Callable + +from openpilot.tools.lib.comma_car_segments import get_url as get_comma_segments_url +from openpilot.tools.lib.openpilotci import get_url +from openpilot.tools.lib.filereader import DATA_ENDPOINT, file_exists, internal_source_available +from openpilot.tools.lib.route import Route, SegmentRange, FileName + +# When passed a tuple of file names, each source will return the first that exists (rlog.zst, rlog.bz2) +FileNames = tuple[str, ...] +Source = Callable[[SegmentRange, list[int], FileNames], dict[int, str]] + +InternalUnavailableException = Exception("Internal source not available") + + +def comma_api_source(sr: SegmentRange, seg_idxs: list[int], fns: FileNames, /) -> dict[int, str]: + route = Route(sr.route_name) + + # comma api will have already checked if the file exists + if fns == FileName.RLOG: + return {seg: route.log_paths()[seg] for seg in seg_idxs if route.log_paths()[seg] is not None} + else: + return {seg: route.qlog_paths()[seg] for seg in seg_idxs if route.qlog_paths()[seg] is not None} + + +def internal_source(sr: SegmentRange, seg_idxs: list[int], fns: FileNames, /, endpoint_url: str = DATA_ENDPOINT) -> dict[int, str]: + if not internal_source_available(endpoint_url): + raise InternalUnavailableException + + def get_internal_url(sr: SegmentRange, seg, file): + return f"{endpoint_url.rstrip('/')}/{sr.dongle_id}/{sr.log_id}/{seg}/{file}" + + return eval_source({seg: [get_internal_url(sr, seg, fn) for fn in fns] for seg in seg_idxs}) + + +def openpilotci_source(sr: SegmentRange, seg_idxs: list[int], fns: FileNames, /) -> dict[int, str]: + return eval_source({seg: [get_url(sr.route_name, seg, fn) for fn in fns] for seg in seg_idxs}) + + +def comma_car_segments_source(sr: SegmentRange, seg_idxs: list[int], fns: FileNames, /) -> dict[int, str]: + return eval_source({seg: get_comma_segments_url(sr.route_name, seg) for seg in seg_idxs}) + + +def eval_source(files: dict[int, list[str] | str]) -> dict[int, str]: + # Returns valid file URLs given a list of possible file URLs for each segment (e.g. rlog.bz2, rlog.zst) + valid_files: dict[int, str] = {} + + for seg_idx, urls in files.items(): + if isinstance(urls, str): + urls = [urls] + + # Add first valid file URL + for url in urls: + if file_exists(url): + valid_files[seg_idx] = url + break + + return valid_files diff --git a/openpilot/tools/lib/filereader.py b/openpilot/tools/lib/filereader.py new file mode 100644 index 0000000000..f5418be81a --- /dev/null +++ b/openpilot/tools/lib/filereader.py @@ -0,0 +1,58 @@ +import os +import io +import posixpath +import socket +from functools import cache +from openpilot.common.utils import retry +from urllib.parse import urlparse + +from openpilot.tools.lib.url_file import URLFile + +DATA_ENDPOINT = os.getenv("DATA_ENDPOINT", "http://data-raw.comma.internal/") + + +@cache +@retry(delay=0.0) +def internal_source_available(url: str) -> bool: + if os.path.isdir(url): + return True + + try: + hostname = urlparse(url).hostname + port = urlparse(url).port or 80 + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.settimeout(0.5) + s.connect((hostname, port)) + return True + except (socket.gaierror, ConnectionRefusedError): + pass + return False + + +def resolve_name(fn): + if fn.startswith("cd:/"): + return posixpath.join(DATA_ENDPOINT, fn[4:]) + return fn + + +@cache +def file_exists(fn): + fn = resolve_name(fn) + if fn.startswith(("http://", "https://")): + return URLFile(fn).get_length_online() != -1 + return os.path.exists(fn) + +class DiskFile(io.BufferedReader): + def get_multi_range(self, ranges: list[tuple[int, int]]) -> list[bytes]: + parts = [] + for r in ranges: + self.seek(r[0]) + parts.append(self.read(r[1] - r[0])) + return parts + +def FileReader(fn): + fn = resolve_name(fn) + if fn.startswith(("http://", "https://")): + return URLFile(fn) + else: + return DiskFile(open(fn, "rb")) diff --git a/tools/lib/framereader.py b/openpilot/tools/lib/framereader.py similarity index 82% rename from tools/lib/framereader.py rename to openpilot/tools/lib/framereader.py index 8f7f723c28..c923651563 100644 --- a/tools/lib/framereader.py +++ b/openpilot/tools/lib/framereader.py @@ -1,6 +1,7 @@ import os import subprocess import json +import logging from collections.abc import Iterator from collections import OrderedDict @@ -9,12 +10,12 @@ from openpilot.tools.lib.filereader import FileReader, resolve_name from openpilot.tools.lib.exceptions import DataUnreadableError from openpilot.tools.lib.vidindex import hevc_index +logger = logging.getLogger("tools") HEVC_SLICE_B = 0 HEVC_SLICE_P = 1 HEVC_SLICE_I = 2 - class LRUCache: def __init__(self, capacity: int): self._cache: OrderedDict = OrderedDict() @@ -32,7 +33,6 @@ class LRUCache: def __contains__(self, key): return key in self._cache - def assert_hvec(fn: str) -> None: with FileReader(fn) as f: header = f.read(4) @@ -42,20 +42,22 @@ def assert_hvec(fn: str) -> None: if 'hevc' not in fn: raise NotImplementedError(fn) -def decompress_video_data(rawdat, w, h, pix_fmt="rgb24", vid_fmt='hevc') -> np.ndarray: +def decompress_video_data(rawdat, w, h, pix_fmt="rgb24", vid_fmt='hevc', hwaccel="auto", loglevel="info") -> np.ndarray: threads = os.getenv("FFMPEG_THREADS", "0") - args = ["ffmpeg", "-v", "quiet", + args = ["ffmpeg", "-v", loglevel, "-threads", threads, + "-hwaccel", hwaccel, "-c:v", "hevc", "-vsync", "0", "-f", vid_fmt, "-flags2", "showall", - "-i", "-", + "-i", "pipe:0", "-f", "rawvideo", "-pix_fmt", pix_fmt, - "-"] + "pipe:1"] dat = subprocess.check_output(args, input=rawdat) + ret: np.ndarray if pix_fmt == "rgb24": ret = np.frombuffer(dat, dtype=np.uint8).reshape(-1, h, w, 3) elif pix_fmt in ["nv12", "yuv420p"]: @@ -69,7 +71,7 @@ def ffprobe(fn, fmt=None): cmd = ["ffprobe", "-v", "quiet", "-print_format", "json", "-show_format", "-show_streams"] if fmt: cmd += ["-f", fmt] - cmd += ["-i", "-"] + cmd += ["-i", "pipe:0"] try: with FileReader(fn) as f: @@ -97,15 +99,15 @@ def get_video_index(fn): 'probe': probe } - class FfmpegDecoder: def __init__(self, fn: str, index_data: dict|None = None, - pix_fmt: str = "rgb24"): + pix_fmt: str = "rgb24", hwaccel="auto", loglevel="quiet"): self.fn = fn self.index, self.prefix, self.w, self.h = get_index_data(fn, index_data) self.frame_count = len(self.index) - 1 # sentinel row at the end self.iframes = np.where(self.index[:, 0] == HEVC_SLICE_I)[0] self.pix_fmt = pix_fmt + self.loglevel, self.hwaccel = loglevel, hwaccel def _gop_bounds(self, frame_idx: int): f_b = frame_idx @@ -117,7 +119,7 @@ class FfmpegDecoder: return f_b, f_e, self.index[f_b, 1], self.index[f_e, 1] def _decode_gop(self, raw: bytes) -> Iterator[np.ndarray]: - yield from decompress_video_data(raw, self.w, self.h, self.pix_fmt) + yield from decompress_video_data(raw, self.w, self.h, pix_fmt=self.pix_fmt, hwaccel=self.hwaccel, loglevel=self.loglevel) def get_gop_start(self, frame_idx: int): return self.iframes[np.searchsorted(self.iframes, frame_idx, side="right") - 1] @@ -132,7 +134,7 @@ class FfmpegDecoder: f.seek(off_b) raw = self.prefix + f.read(off_e - off_b) # number of frames to discard inside this GOP before the wanted one - for i, frm in enumerate(decompress_video_data(raw, self.w, self.h, self.pix_fmt)): + for i, frm in enumerate(decompress_video_data(raw, self.w, self.h, self.pix_fmt, hwaccel=self.hwaccel, loglevel=self.loglevel)): fidx = f_b + i if fidx >= end_fidx: return @@ -140,17 +142,16 @@ class FfmpegDecoder: yield fidx, frm fidx += 1 -def FrameIterator(fn: str, index_data: dict|None=None, - pix_fmt: str = "rgb24", - start_fidx:int=0, end_fidx=None, frame_skip:int=1) -> Iterator[np.ndarray]: - dec = FfmpegDecoder(fn, pix_fmt=pix_fmt, index_data=index_data) +def FrameIterator(fn: str, index_data: dict|None=None, pix_fmt: str = "rgb24", + start_fidx:int=0, end_fidx=None, frame_skip:int=1, hwaccel="auto", loglevel="quiet") -> Iterator[np.ndarray]: + dec = FfmpegDecoder(fn, pix_fmt=pix_fmt, index_data=index_data, hwaccel=hwaccel, loglevel=loglevel) for _, frame in dec.get_iterator(start_fidx=start_fidx, end_fidx=end_fidx, frame_skip=frame_skip): yield frame class FrameReader: - def __init__(self, fn: str, index_data: dict|None = None, - cache_size: int = 30, pix_fmt: str = "rgb24"): - self.decoder = FfmpegDecoder(fn, index_data, pix_fmt) + def __init__(self, fn: str, index_data: dict|None = None, cache_size: int = 30, + pix_fmt: str = "rgb24", hwaccel="auto", loglevel="quiet"): + self.decoder = FfmpegDecoder(fn, index_data=index_data, pix_fmt=pix_fmt, hwaccel=hwaccel, loglevel=loglevel) self.iframes = self.decoder.iframes self._cache: LRUCache = LRUCache(cache_size) self.w, self.h, self.frame_count, = self.decoder.w, self.decoder.h, self.decoder.frame_count diff --git a/tools/lib/github_utils.py b/openpilot/tools/lib/github_utils.py similarity index 98% rename from tools/lib/github_utils.py rename to openpilot/tools/lib/github_utils.py index 46a0dcf3cb..6a443b4155 100644 --- a/tools/lib/github_utils.py +++ b/openpilot/tools/lib/github_utils.py @@ -62,7 +62,7 @@ class GithubUtils: self.api_call(github_path, data=data, method=HTTPMethod.POST, data_call=True) def get_bucket_sha(self, bucket): - github_path = f"git/refs/heads/{bucket}" + github_path = f"git/ref/heads/{bucket}" r = self.api_call(github_path, data_call=True, raise_on_failure=False) return r.json()['object']['sha'] if r.ok else None diff --git a/openpilot/tools/lib/helpers.py b/openpilot/tools/lib/helpers.py new file mode 100644 index 0000000000..8c976e7ecc --- /dev/null +++ b/openpilot/tools/lib/helpers.py @@ -0,0 +1,17 @@ +# regex patterns +class RE: + DONGLE_ID = r'(?P[a-f0-9]{16})' + TIMESTAMP = r'(?P[0-9]{4}-[0-9]{2}-[0-9]{2}--[0-9]{2}-[0-9]{2}-[0-9]{2})' + LOG_ID_V2 = r'(?P[a-f0-9]{8})--(?P[a-z0-9]{10})' + LOG_ID = fr'(?P(?:{TIMESTAMP}|{LOG_ID_V2}))' + ROUTE_NAME = fr'(?P{DONGLE_ID}[|_/]{LOG_ID})' + SEGMENT_NAME = fr'{ROUTE_NAME}(?:--|/)(?P[0-9]+)' + + INDEX = r'-?[0-9]+' + SLICE = fr'(?P{INDEX})?:?(?P{INDEX})?:?(?P{INDEX})?' + SEGMENT_RANGE = fr'{ROUTE_NAME}(?:(--|/)(?P({SLICE})))?(?:/(?P([qra])))?' + + BOOTLOG_NAME = ROUTE_NAME + + EXPLORER_FILE = fr'^(?P{SEGMENT_NAME})--(?P[a-z]+\.[a-z0-9]+)$' + OP_SEGMENT_DIR = fr'^(?P{SEGMENT_NAME})$' diff --git a/tools/lib/kbhit.py b/openpilot/tools/lib/kbhit.py similarity index 100% rename from tools/lib/kbhit.py rename to openpilot/tools/lib/kbhit.py diff --git a/tools/lib/live_logreader.py b/openpilot/tools/lib/live_logreader.py similarity index 87% rename from tools/lib/live_logreader.py rename to openpilot/tools/lib/live_logreader.py index edc4ac1611..20f8c3502c 100644 --- a/tools/lib/live_logreader.py +++ b/openpilot/tools/lib/live_logreader.py @@ -1,6 +1,6 @@ import os -from cereal import log as capnp_log, messaging -from cereal.services import SERVICE_LIST +from openpilot.cereal import log as capnp_log, messaging +from openpilot.cereal.services import SERVICE_LIST from openpilot.tools.lib.logreader import LogIterable, RawLogIterable diff --git a/tools/lib/log_time_series.py b/openpilot/tools/lib/log_time_series.py similarity index 100% rename from tools/lib/log_time_series.py rename to openpilot/tools/lib/log_time_series.py diff --git a/openpilot/tools/lib/logreader.py b/openpilot/tools/lib/logreader.py new file mode 100755 index 0000000000..805e411b53 --- /dev/null +++ b/openpilot/tools/lib/logreader.py @@ -0,0 +1,312 @@ +#!/usr/bin/env python3 +import bz2 +from functools import partial +import multiprocessing +import capnp +import enum +import os +import pathlib +import sys +import tqdm +import urllib.parse +import warnings +import zstandard as zstd + +from collections.abc import Iterable, Iterator +from urllib.parse import parse_qs, urlparse + +from openpilot.cereal import log as capnp_log +from openpilot.common.swaglog import cloudlog +from openpilot.tools.lib.filereader import FileReader +from openpilot.tools.lib.file_sources import comma_api_source, internal_source, openpilotci_source, comma_car_segments_source, Source +from openpilot.tools.lib.route import SegmentRange, FileName +from openpilot.tools.lib.log_time_series import msgs_to_time_series + +LogMessage = type[capnp._DynamicStructReader] +LogIterable = Iterable[LogMessage] +RawLogIterable = Iterable[bytes] + + +def save_log(dest, log_msgs, compress=True): + dat = b"".join(msg.as_builder().to_bytes() for msg in log_msgs) + + if compress and dest.endswith(".bz2"): + dat = bz2.compress(dat) + elif compress and dest.endswith(".zst"): + dat = zstd.compress(dat, 10) + + with open(dest, "wb") as f: + f.write(dat) + + +def decompress_stream(data: bytes): + dctx = zstd.ZstdDecompressor() + decompressed_data = b"" + + with dctx.stream_reader(data) as reader: + decompressed_data = reader.read() + + return decompressed_data + + +class CachedEventReader: + __slots__ = ('_evt', '_enum') + + def __init__(self, evt: capnp._DynamicStructReader, _enum: str | None = None): + """All capnp attribute accesses are expensive, and which() is often called multiple times""" + self._evt = evt + self._enum: str | None = _enum + + # fast pickle support + def __reduce__(self): + return CachedEventReader._reducer, (self._evt.as_builder().to_bytes(), self._enum) + + @staticmethod + def _reducer(data: bytes, _enum: str | None = None): + with capnp_log.Event.from_bytes(data) as evt: + return CachedEventReader(evt, _enum) + + def __repr__(self): + return self._evt.__repr__() + + def __str__(self): + return self._evt.__str__() + + def __dir__(self): + return dir(self._evt) + + def which(self) -> str: + if self._enum is None: + self._enum = self._evt.which() + return self._enum + + def __getattr__(self, name: str): + if name.startswith("__") and name.endswith("__"): + return getattr(self, name) + return getattr(self._evt, name) + + +class _LogFileReader: + def __init__(self, fn, only_union_types=False, sort_by_time=False, dat=None): + self.data_version = None + self._only_union_types = only_union_types + + ext = None + if not dat: + _, ext = os.path.splitext(urllib.parse.urlparse(fn).path) + if ext not in ('', '.bz2', '.zst'): + # old rlogs weren't compressed + raise ValueError(f"unknown extension {ext}") + + with FileReader(fn) as f: + dat = f.read() + + if ext == ".bz2" or dat.startswith(b'BZh9'): + dat = bz2.decompress(dat) + elif ext == ".zst" or dat.startswith(b'\x28\xB5\x2F\xFD'): + # https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#zstandard-frames + dat = decompress_stream(dat) + + ents = capnp_log.Event.read_multiple_bytes(dat) + + self._ents = [] + try: + for e in ents: + self._ents.append(CachedEventReader(e)) + except capnp.KjException: + warnings.warn("Corrupted events detected", RuntimeWarning, stacklevel=1) + + if sort_by_time: + self._ents.sort(key=lambda x: x.logMonoTime) + + def __iter__(self) -> Iterator[capnp._DynamicStructReader]: + for ent in self._ents: + if self._only_union_types: + try: + ent.which() + yield ent + except capnp.lib.capnp.KjException: + pass + else: + yield ent + + +class ReadMode(enum.StrEnum): + RLOG = "r" # only read rlogs + QLOG = "q" # only read qlogs + AUTO = "a" # default to rlogs, fallback to qlogs + AUTO_INTERACTIVE = "i" # default to rlogs, fallback to qlogs with a prompt from the user + + +class LogsUnavailable(Exception): + pass + + +def direct_source(file_or_url: str) -> list[str]: + return [file_or_url] + + +# TODO this should apply to camera files as well +def auto_source(identifier: str, sources: list[Source], default_mode: ReadMode) -> list[str]: + exceptions = {} + + sr = SegmentRange(identifier) + needed_seg_idxs = sr.seg_idxs + + mode = default_mode if sr.selector is None else ReadMode(sr.selector) + if mode == ReadMode.QLOG: + try_fns = [FileName.QLOG] + else: + try_fns = [FileName.RLOG] + + # If selector allows it, fallback to qlogs + if mode in (ReadMode.AUTO, ReadMode.AUTO_INTERACTIVE): + try_fns.append(FileName.QLOG) + + # Build a dict of valid files as we evaluate each source. May contain mix of rlogs, qlogs, and None. + # This function only returns when we've sourced all files, or throws an exception + valid_files: dict[int, str] = {} + for fn in try_fns: + for source in sources: + try: + files = source(sr, needed_seg_idxs, fn) + + # Build a dict of valid files + valid_files |= files + + # Don't check for segment files that have already been found + needed_seg_idxs = [idx for idx in needed_seg_idxs if idx not in valid_files] + + # We've found all files, return them + if len(needed_seg_idxs) == 0: + return list(valid_files.values()) + else: + raise FileNotFoundError(f"Did not find {fn} for seg idxs {needed_seg_idxs} of {sr.route_name}") + + except Exception as e: + exceptions[source.__name__] = e + + if fn == try_fns[0]: + missing_logs = len(needed_seg_idxs) + if mode == ReadMode.AUTO: + cloudlog.warning(f"{missing_logs}/{len(sr.seg_idxs)} rlogs were not found, falling back to qlogs for those segments...") + elif mode == ReadMode.AUTO_INTERACTIVE: + if input(f"{missing_logs}/{len(sr.seg_idxs)} rlogs were not found, would you like to fallback to qlogs for those segments? (y/N) ").lower() != "y": + break + + missing_logs = len(needed_seg_idxs) + raise LogsUnavailable(f"{missing_logs}/{len(sr.seg_idxs)} logs were not found, please ensure all logs " + + "are uploaded. You can fall back to qlogs with '/a' selector at the end of the route name.\n\n" + + "Exceptions for sources:\n - " + "\n - ".join([f"{k}: {repr(v)}" for k, v in exceptions.items()])) + + +def parse_indirect(identifier: str) -> str: + if "useradmin.comma.ai" in identifier: + query = parse_qs(urlparse(identifier).query) + identifier = query["onebox"][0] + elif "connect.comma.ai" in identifier: + path = urlparse(identifier).path.strip("/").split("/") + path = ['/'.join(path[:2]), *path[2:]] # recombine log id + + identifier = path[0] + if len(path) > 2: + # convert url with seconds to segments + start, end = int(path[1]) // 60, int(path[2]) // 60 + 1 + identifier = f"{identifier}/{start}:{end}" + + # add selector if it exists + if len(path) > 3: + identifier += f"/{path[3]}" + else: + # add selector if it exists + identifier = "/".join(path) + + return identifier + + +def parse_direct(identifier: str): + if identifier.startswith(("http://", "https://", "cd:/")) or pathlib.Path(identifier).exists(): + return identifier + return None + + +class LogReader: + def _parse_identifier(self, identifier: str) -> list[str]: + # useradmin, etc. + identifier = parse_indirect(identifier) + + # direct url or file + direct_parsed = parse_direct(identifier) + if direct_parsed is not None: + return direct_source(identifier) + + identifiers = auto_source(identifier, self.sources, self.default_mode) + return identifiers + + def __init__(self, identifier: str | list[str], default_mode: ReadMode = ReadMode.RLOG, + sources: list[Source] | None = None, sort_by_time=False, only_union_types=False): + if sources is None: + sources = [internal_source, comma_api_source, openpilotci_source, comma_car_segments_source] + + self.default_mode = default_mode + self.sources = sources + self.identifier = identifier + if isinstance(identifier, str): + self.identifier = [identifier] + + self.sort_by_time = sort_by_time + self.only_union_types = only_union_types + + self.__lrs: dict[int, _LogFileReader] = {} + self.reset() + + def _get_lr(self, i): + if i not in self.__lrs: + self.__lrs[i] = _LogFileReader(self.logreader_identifiers[i], sort_by_time=self.sort_by_time, only_union_types=self.only_union_types) + return self.__lrs[i] + + def __iter__(self): + for i in range(len(self.logreader_identifiers)): + yield from self._get_lr(i) + + def _run_on_segment(self, func, i): + return func(self._get_lr(i)) + + def run_across_segments(self, num_processes, func, disable_tqdm=False, desc=None): + with multiprocessing.Pool(num_processes) as pool: + ret = [] + num_segs = len(self.logreader_identifiers) + for p in tqdm.tqdm(pool.imap(partial(self._run_on_segment, func), range(num_segs)), total=num_segs, disable=disable_tqdm, desc=desc): + ret.extend(p) + return ret + + def reset(self): + self.logreader_identifiers = [] + for identifier in self.identifier: + self.logreader_identifiers.extend(self._parse_identifier(identifier)) + + @staticmethod + def from_bytes(dat): + return _LogFileReader("", dat=dat) + + def filter(self, msg_type: str): + return (getattr(m, m.which()) for m in filter(lambda m: m.which() == msg_type, self)) + + def first(self, msg_type: str): + return next(self.filter(msg_type), None) + + @property + def time_series(self): + return msgs_to_time_series(self) + + +if __name__ == "__main__": + import codecs + + # capnproto <= 0.8.0 throws errors converting byte data to string + # below line catches those errors and replaces the bytes with \x__ + codecs.register_error("strict", codecs.backslashreplace_errors) + log_path = sys.argv[1] + lr = LogReader(log_path, sort_by_time=True) + for msg in lr: + print(msg) diff --git a/openpilot/tools/lib/openpilotci.py b/openpilot/tools/lib/openpilotci.py new file mode 100644 index 0000000000..6b484dfdad --- /dev/null +++ b/openpilot/tools/lib/openpilotci.py @@ -0,0 +1,4 @@ +BASE_URL = "https://commadataci.blob.core.windows.net/openpilotci/" + +def get_url(route_name: str, segment_num, filename: str) -> str: + return BASE_URL + f"{route_name.replace('|', '/')}/{segment_num}/{filename}" diff --git a/tools/lib/openpilotcontainers.py b/openpilot/tools/lib/openpilotcontainers.py similarity index 100% rename from tools/lib/openpilotcontainers.py rename to openpilot/tools/lib/openpilotcontainers.py diff --git a/tools/lib/route.py b/openpilot/tools/lib/route.py similarity index 77% rename from tools/lib/route.py rename to openpilot/tools/lib/route.py index 0a4700f083..98334a06c8 100644 --- a/tools/lib/route.py +++ b/openpilot/tools/lib/route.py @@ -10,17 +10,19 @@ from openpilot.tools.lib.auth_config import get_token from openpilot.tools.lib.api import APIError, CommaApi from openpilot.tools.lib.helpers import RE -QLOG_FILENAMES = ['qlog', 'qlog.bz2', 'qlog.zst'] -QCAMERA_FILENAMES = ['qcamera.ts'] -LOG_FILENAMES = ['rlog', 'rlog.bz2', 'raw_log.bz2', 'rlog.zst'] -CAMERA_FILENAMES = ['fcamera.hevc', 'video.hevc'] -DCAMERA_FILENAMES = ['dcamera.hevc'] -ECAMERA_FILENAMES = ['ecamera.hevc'] + +class FileName: + RLOG = ("rlog.zst", "rlog.bz2") + QLOG = ("qlog.zst", "qlog.bz2") + QCAMERA = ('qcamera.ts',) + FCAMERA = ('fcamera.hevc',) + ECAMERA = ('ecamera.hevc',) + DCAMERA = ('dcamera.hevc',) + BOOTLOG = ('bootlog.zst', 'bootlog.bz2') class Route: def __init__(self, name, data_dir=None): - self._metadata = None self._name = RouteName(name) self.files = None if data_dir is not None: @@ -29,13 +31,6 @@ class Route: self._segments = self._get_segments_remote() self.max_seg_number = self._segments[-1].name.segment_num - @property - def metadata(self): - if not self._metadata: - api = CommaApi(get_token()) - self._metadata = api.get('v1/route/' + self.name.canonical_name) - return self._metadata - @property def name(self): return self._name @@ -81,24 +76,22 @@ class Route: if segments.get(segment_name): segments[segment_name] = Segment( segment_name, - url if fn in LOG_FILENAMES else segments[segment_name].log_path, - url if fn in QLOG_FILENAMES else segments[segment_name].qlog_path, - url if fn in CAMERA_FILENAMES else segments[segment_name].camera_path, - url if fn in DCAMERA_FILENAMES else segments[segment_name].dcamera_path, - url if fn in ECAMERA_FILENAMES else segments[segment_name].ecamera_path, - url if fn in QCAMERA_FILENAMES else segments[segment_name].qcamera_path, - self.metadata['url'], + url if fn in FileName.RLOG else segments[segment_name].log_path, + url if fn in FileName.QLOG else segments[segment_name].qlog_path, + url if fn in FileName.FCAMERA else segments[segment_name].camera_path, + url if fn in FileName.DCAMERA else segments[segment_name].dcamera_path, + url if fn in FileName.ECAMERA else segments[segment_name].ecamera_path, + url if fn in FileName.QCAMERA else segments[segment_name].qcamera_path, ) else: segments[segment_name] = Segment( segment_name, - url if fn in LOG_FILENAMES else None, - url if fn in QLOG_FILENAMES else None, - url if fn in CAMERA_FILENAMES else None, - url if fn in DCAMERA_FILENAMES else None, - url if fn in ECAMERA_FILENAMES else None, - url if fn in QCAMERA_FILENAMES else None, - self.metadata['url'], + url if fn in FileName.RLOG else None, + url if fn in FileName.QLOG else None, + url if fn in FileName.FCAMERA else None, + url if fn in FileName.DCAMERA else None, + url if fn in FileName.ECAMERA else None, + url if fn in FileName.QCAMERA else None, ) return sorted(segments.values(), key=lambda seg: seg.name.segment_num) @@ -135,36 +128,36 @@ class Route: for segment, files in segment_files.items(): try: - log_path = next(path for path, filename in files if filename in LOG_FILENAMES) + log_path = next(path for path, filename in files if filename in FileName.RLOG) except StopIteration: log_path = None try: - qlog_path = next(path for path, filename in files if filename in QLOG_FILENAMES) + qlog_path = next(path for path, filename in files if filename in FileName.QLOG) except StopIteration: qlog_path = None try: - camera_path = next(path for path, filename in files if filename in CAMERA_FILENAMES) + camera_path = next(path for path, filename in files if filename in FileName.FCAMERA) except StopIteration: camera_path = None try: - dcamera_path = next(path for path, filename in files if filename in DCAMERA_FILENAMES) + dcamera_path = next(path for path, filename in files if filename in FileName.DCAMERA) except StopIteration: dcamera_path = None try: - ecamera_path = next(path for path, filename in files if filename in ECAMERA_FILENAMES) + ecamera_path = next(path for path, filename in files if filename in FileName.ECAMERA) except StopIteration: ecamera_path = None try: - qcamera_path = next(path for path, filename in files if filename in QCAMERA_FILENAMES) + qcamera_path = next(path for path, filename in files if filename in FileName.QCAMERA) except StopIteration: qcamera_path = None - segments.append(Segment(segment, log_path, qlog_path, camera_path, dcamera_path, ecamera_path, qcamera_path, self.metadata['url'])) + segments.append(Segment(segment, log_path, qlog_path, camera_path, dcamera_path, ecamera_path, qcamera_path)) if len(segments) == 0: raise ValueError(f'Could not find segments for route {self.name.canonical_name} in data directory {data_dir}') @@ -172,10 +165,9 @@ class Route: class Segment: - def __init__(self, name, log_path, qlog_path, camera_path, dcamera_path, ecamera_path, qcamera_path, url): + def __init__(self, name, log_path, qlog_path, camera_path, dcamera_path, ecamera_path, qcamera_path): self._events = None self._name = SegmentName(name) - self.url = f'{url}/{self._name.segment_num}' self.log_path = log_path self.qlog_path = qlog_path self.camera_path = camera_path @@ -187,6 +179,18 @@ class Segment: def name(self): return self._name + @staticmethod + @cache + def _get_route_metadata(route_name: str): + api = CommaApi(get_token()) + return api.get(f'v1/route/{route_name}') + + @property + def url(self): + route_name = self._name.route_name.canonical_name + metadata = self._get_route_metadata(route_name) + return f'{metadata["url"]}/{self._name.segment_num}' + @property def events(self): if not self._events: @@ -215,9 +219,16 @@ class RouteName: @property def dongle_id(self) -> str: return self._dongle_id + @property + def log_id(self) -> str: return self._time_str + @property def time_str(self) -> str: return self._time_str + @property + def azure_prefix(self): + return f'{self.dongle_id}/{self.log_id}' + def __str__(self) -> str: return self._canonical_name @@ -241,12 +252,23 @@ class SegmentName: @property def canonical_name(self) -> str: return self._canonical_name + # TODO should only use one name + @property + def data_name(self) -> str: return f"{self._route_name.canonical_name}/{self._num}" + + @property + def azure_prefix(self): + return f'{self.dongle_id}/{self.log_id}/{self._num}' + @property def dongle_id(self) -> str: return self._route_name.dongle_id @property def time_str(self) -> str: return self._route_name.time_str + @property + def log_id(self) -> str: return self._route_name.time_str + @property def segment_num(self) -> int: return self._num @@ -258,6 +280,30 @@ class SegmentName: def __str__(self) -> str: return self._canonical_name + @staticmethod + def from_file_name(file_name): + # ??????/xxxxxxxxxxxxxxxx|1111-11-11-11--11-11-11/1/rlog.bz2 + dongle_id, route_name, segment_num = file_name.replace('|', '/').split('/')[-4:-1] + return SegmentName(dongle_id + "|" + route_name + "--" + segment_num) + + @staticmethod + def from_device_key(dongle_id, key): + # 2018-05-07--18-56-13--5/rlog.bz2 + segment_name = key.split('/')[0] + return SegmentName(dongle_id + "|" + segment_name) + + @staticmethod + def from_file_key(key): + # 38c52c217150700f/2018-05-07--18-56-13/5/rlog.bz2 + az_prefix = '/'.join(key.split('/')[:3]) + return SegmentName.from_azure_prefix(az_prefix) + + @staticmethod + def from_azure_prefix(prefix): + # xxxxxxxx/1111-11-11-11--11-11-11/0 + dongle_id, route_name, segment_num = prefix.split("/") + return SegmentName(dongle_id + "|" + route_name + "--" + segment_num) + @cache def get_max_seg_number_cached(sr: 'SegmentRange') -> int: diff --git a/tools/lib/sanitizer.py b/openpilot/tools/lib/sanitizer.py similarity index 100% rename from tools/lib/sanitizer.py rename to openpilot/tools/lib/sanitizer.py diff --git a/openpilot/tools/lib/tests/__init__.py b/openpilot/tools/lib/tests/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/openpilot/tools/lib/tests/test_caching.py b/openpilot/tools/lib/tests/test_caching.py new file mode 100644 index 0000000000..c70d7fc81b --- /dev/null +++ b/openpilot/tools/lib/tests/test_caching.py @@ -0,0 +1,167 @@ +import http.server +import os +import shutil +import socket +import tempfile +import pytest + +from openpilot.selfdrive.test.helpers import http_server_context +from openpilot.common.hardware.hw import Paths +from openpilot.tools.lib.url_file import URLFile, prune_cache +import openpilot.tools.lib.url_file as url_file_module + + +class CachingTestRequestHandler(http.server.BaseHTTPRequestHandler): + FILE_EXISTS = True + + def do_GET(self): + if self.FILE_EXISTS: + self.send_response(206 if "Range" in self.headers else 200, '1234') + else: + self.send_response(404) + self.end_headers() + + def do_HEAD(self): + if self.FILE_EXISTS: + self.send_response(200) + self.send_header("Content-Length", "4") + else: + self.send_response(404) + self.end_headers() + + +@pytest.fixture +def host(): + with http_server_context(handler=CachingTestRequestHandler) as (host, port): + yield f"http://{host}:{port}" + +class TestFileDownload: + + def test_pipeline_defaults(self, host): + # TODO: parameterize the defaults so we don't rely on hard-coded values in xx + + assert URLFile.pool_manager().pools._maxsize == 10# PoolManager num_pools param + pool_manager_defaults = { + "maxsize": 100, + "socket_options": [(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),], + } + for k, v in pool_manager_defaults.items(): + assert URLFile.pool_manager().connection_pool_kw.get(k) == v + + retry_defaults = { + "total": 5, + "backoff_factor": 0.5, + "status_forcelist": [409, 429, 503, 504], + } + for k, v in retry_defaults.items(): + assert getattr(URLFile.pool_manager().connection_pool_kw["retries"], k) == v + + # ensure caching on by default and cache dir gets created + os.environ.pop("DISABLE_FILEREADER_CACHE", None) + if os.path.exists(Paths.download_cache_root()): + shutil.rmtree(Paths.download_cache_root()) + URLFile(f"{host}/test.txt").get_length() + URLFile(f"{host}/test.txt").read() + assert os.path.exists(Paths.download_cache_root()) + + def compare_loads(self, url, start=0, length=None): + """Compares range between cached and non cached version""" + file_cached = URLFile(url, cache=True) + file_downloaded = URLFile(url, cache=False) + + file_cached.seek(start) + file_downloaded.seek(start) + + assert file_cached.get_length() == file_downloaded.get_length() + assert length + start if length is not None else 0 <= file_downloaded.get_length() + + response_cached = file_cached.read(ll=length) + response_downloaded = file_downloaded.read(ll=length) + + assert response_cached == response_downloaded + + # Now test with cache in place + file_cached = URLFile(url, cache=True) + file_cached.seek(start) + response_cached = file_cached.read(ll=length) + + assert file_cached.get_length() == file_downloaded.get_length() + assert response_cached == response_downloaded + + def test_small_file(self): + # Make sure we don't force cache + os.environ.pop("DISABLE_FILEREADER_CACHE", None) + small_file_url = "https://raw.githubusercontent.com/commaai/openpilot/master/docs/SAFETY.md" + # If you want large file to be larger than a chunk + # large_file_url = "https://commadataci.blob.core.windows.net/openpilotci/0375fdf7b1ce594d/2019-06-13--08-32-25/3/fcamera.hevc" + + # Load full small file + self.compare_loads(small_file_url) + + file_small = URLFile(small_file_url) + length = file_small.get_length() + + self.compare_loads(small_file_url, length - 100, 100) + self.compare_loads(small_file_url, 50, 100) + + # Load small file 100 bytes at a time + for i in range(length // 100): + self.compare_loads(small_file_url, 100 * i, 100) + + def test_large_file(self): + large_file_url = "https://commadataci.blob.core.windows.net/openpilotci/0375fdf7b1ce594d/2019-06-13--08-32-25/3/qlog.bz2" + # Load the end 100 bytes of both files + file_large = URLFile(large_file_url) + length = file_large.get_length() + + self.compare_loads(large_file_url, length - 100, 100) + self.compare_loads(large_file_url) + + @pytest.mark.parametrize("cache_enabled", [True, False]) + def test_recover_from_missing_file(self, host, cache_enabled): + if cache_enabled: + os.environ.pop("DISABLE_FILEREADER_CACHE", None) + else: + os.environ["DISABLE_FILEREADER_CACHE"] = "1" + + file_url = f"{host}/test.png" + + CachingTestRequestHandler.FILE_EXISTS = False + length = URLFile(file_url).get_length() + assert length == -1 + + CachingTestRequestHandler.FILE_EXISTS = True + length = URLFile(file_url).get_length() + assert length == 4 + + +class TestCache: + def test_prune_cache(self, monkeypatch): + with tempfile.TemporaryDirectory() as tmpdir: + monkeypatch.setattr(Paths, 'download_cache_root', staticmethod(lambda: tmpdir + "/")) + + # setup test files and manifest + manifest_lines = [] + for i in range(3): + fname = f"hash_{i}" + with open(tmpdir + "/" + fname, "wb") as f: + f.truncate(1000) + manifest_lines.append(f"{fname} {1000 + i}") + with open(tmpdir + "/manifest.txt", "w") as f: + f.write('\n'.join(manifest_lines)) + + # under limit, shouldn't prune + assert len(os.listdir(tmpdir)) == 4 + prune_cache() + assert len(os.listdir(tmpdir)) == 4 + + # set a tiny cache limit to force eviction (1.5 chunks worth) + monkeypatch.setattr(url_file_module, 'CACHE_SIZE', url_file_module.CHUNK_SIZE + url_file_module.CHUNK_SIZE // 2) + + # prune_cache should evict oldest files to get under limit + prune_cache() + remaining = os.listdir(tmpdir) + # should have evicted at least one file + manifest + assert len(remaining) < 4 + # newest file should remain + assert manifest_lines[2].split()[0] in remaining diff --git a/tools/lib/tests/test_comma_car_segments.py b/openpilot/tools/lib/tests/test_comma_car_segments.py similarity index 100% rename from tools/lib/tests/test_comma_car_segments.py rename to openpilot/tools/lib/tests/test_comma_car_segments.py diff --git a/tools/lib/tests/test_logreader.py b/openpilot/tools/lib/tests/test_logreader.py similarity index 88% rename from tools/lib/tests/test_logreader.py rename to openpilot/tools/lib/tests/test_logreader.py index 230b6a65ea..a27a348d9e 100644 --- a/tools/lib/tests/test_logreader.py +++ b/openpilot/tools/lib/tests/test_logreader.py @@ -7,10 +7,11 @@ import os import pytest import requests -from parameterized import parameterized +from openpilot.common.parameterized import parameterized -from cereal import log as capnp_log -from openpilot.tools.lib.logreader import LogIterable, LogReader, comma_api_source, parse_indirect, ReadMode, InternalUnavailableException +from openpilot.cereal import log as capnp_log +from openpilot.tools.lib.logreader import LogsUnavailable, LogIterable, LogReader, parse_indirect, ReadMode +from openpilot.tools.lib.file_sources import comma_api_source, InternalUnavailableException from openpilot.tools.lib.route import SegmentRange from openpilot.tools.lib.url_file import URLFileException @@ -36,12 +37,12 @@ def setup_source_scenario(mocker, is_internal=False): comma_api_source_mock.__name__ = comma_api_source_mock._mock_name if is_internal: - internal_source_mock.return_value = [QLOG_FILE] + internal_source_mock.return_value = {3: QLOG_FILE} else: internal_source_mock.side_effect = InternalUnavailableException - openpilotci_source_mock.return_value = [None] - comma_api_source_mock.return_value = [QLOG_FILE] + openpilotci_source_mock.return_value = {} + comma_api_source_mock.return_value = {3: QLOG_FILE} yield @@ -71,6 +72,7 @@ class TestLogReader: (f"https://useradmin.comma.ai/?onebox={TEST_ROUTE.replace('/', '|')}", ALL_SEGS), (f"https://useradmin.comma.ai/?onebox={TEST_ROUTE.replace('/', '%7C')}", ALL_SEGS), ]) + @pytest.mark.skip("this got flaky. internet tests are stupid.") def test_indirect_parsing(self, identifier, expected): parsed = parse_indirect(identifier) sr = SegmentRange(parsed) @@ -90,8 +92,11 @@ class TestLogReader: @pytest.mark.parametrize("cache_enabled", [True, False]) def test_direct_parsing(self, mocker, cache_enabled): - file_exists_mock = mocker.patch("openpilot.tools.lib.logreader.file_exists") - os.environ["FILEREADER_CACHE"] = "1" if cache_enabled else "0" + file_exists_mock = mocker.patch("openpilot.tools.lib.filereader.file_exists") + if cache_enabled: + os.environ.pop("DISABLE_FILEREADER_CACHE", None) + else: + os.environ["DISABLE_FILEREADER_CACHE"] = "1" qlog = tempfile.NamedTemporaryFile(mode='wb', delete=False) with requests.get(QLOG_FILE, stream=True) as r: @@ -179,7 +184,10 @@ class TestLogReader: @parameterized.expand([(True,), (False,)]) @pytest.mark.slow def test_run_across_segments(self, cache_enabled): - os.environ["FILEREADER_CACHE"] = "1" if cache_enabled else "0" + if cache_enabled: + os.environ.pop("DISABLE_FILEREADER_CACHE", None) + else: + os.environ["DISABLE_FILEREADER_CACHE"] = "1" lr = LogReader(f"{TEST_ROUTE}/0:4") assert len(lr.run_across_segments(4, noop)) == len(list(lr)) @@ -193,28 +201,27 @@ class TestLogReader: with subtests.test("interactive_yes"): mocker.patch("sys.stdin", new=io.StringIO("y\n")) - lr = LogReader(f"{TEST_ROUTE}/0", default_mode=ReadMode.AUTO_INTERACTIVE, source=comma_api_source) + lr = LogReader(f"{TEST_ROUTE}/0", default_mode=ReadMode.AUTO_INTERACTIVE, sources=[comma_api_source]) log_len = len(list(lr)) assert qlog_len == log_len with subtests.test("interactive_no"): mocker.patch("sys.stdin", new=io.StringIO("n\n")) - with pytest.raises(AssertionError): - lr = LogReader(f"{TEST_ROUTE}/0", default_mode=ReadMode.AUTO_INTERACTIVE, source=comma_api_source) + with pytest.raises(LogsUnavailable): + lr = LogReader(f"{TEST_ROUTE}/0", default_mode=ReadMode.AUTO_INTERACTIVE, sources=[comma_api_source]) with subtests.test("non_interactive"): - lr = LogReader(f"{TEST_ROUTE}/0", default_mode=ReadMode.AUTO, source=comma_api_source) + lr = LogReader(f"{TEST_ROUTE}/0", default_mode=ReadMode.AUTO, sources=[comma_api_source]) log_len = len(list(lr)) assert qlog_len == log_len @pytest.mark.parametrize("is_internal", [True, False]) - @pytest.mark.slow def test_auto_source_scenarios(self, mocker, is_internal): lr = LogReader(QLOG_FILE) qlog_len = len(list(lr)) with setup_source_scenario(mocker, is_internal=is_internal): - lr = LogReader(f"{TEST_ROUTE}/0/q") + lr = LogReader(f"{TEST_ROUTE}/3/q") log_len = len(list(lr)) assert qlog_len == log_len diff --git a/tools/lib/tests/test_route_library.py b/openpilot/tools/lib/tests/test_route_library.py similarity index 100% rename from tools/lib/tests/test_route_library.py rename to openpilot/tools/lib/tests/test_route_library.py diff --git a/openpilot/tools/lib/url_file.py b/openpilot/tools/lib/url_file.py new file mode 100644 index 0000000000..ec0a3d5815 --- /dev/null +++ b/openpilot/tools/lib/url_file.py @@ -0,0 +1,220 @@ +import logging +import os +import re +import socket +import time +from hashlib import md5 +from urllib3 import PoolManager, Retry +from urllib3.response import BaseHTTPResponse +from urllib3.util import Timeout + +from openpilot.common.utils import atomic_write +from openpilot.common.hardware.hw import Paths +from urllib3.exceptions import MaxRetryError + +# Cache chunk size +K = 1000 +CHUNK_SIZE = 1000 * K +CACHE_SIZE = 10 * 1024 * 1024 * 1024 # total cache size in GB + +logging.getLogger("urllib3").setLevel(logging.WARNING) + + +def hash_url(link: str) -> str: + return md5(link.split("?", maxsplit=1)[0].encode('utf-8')).hexdigest() + + +def prune_cache(new_entry: str | None = None) -> None: + """Evicts oldest cache files (LRU) until cache is under the size limit.""" + # we use a manifest to avoid tons of os.stat syscalls (slow) + manifest = {} + manifest_path = Paths.download_cache_root() + "manifest.txt" + if os.path.exists(manifest_path): + with open(manifest_path) as f: + manifest = {parts[0]: int(parts[1]) for line in f if (parts := line.strip().split()) and len(parts) == 2} + + if new_entry: + manifest[new_entry] = int(time.time()) # noqa: TID251 + + # evict the least recently used files until under limit + sorted_items = sorted(manifest.items(), key=lambda x: x[1]) + while len(manifest) * CHUNK_SIZE > CACHE_SIZE and sorted_items: + key, _ = sorted_items.pop(0) + try: + os.remove(Paths.download_cache_root() + key) + except OSError: + pass + manifest.pop(key, None) + + # write out manifest + with atomic_write(manifest_path, mode="w", overwrite=True) as f: + f.write('\n'.join(f"{k} {v}" for k, v in manifest.items())) + +class URLFileException(Exception): + pass + + +class URLFile: + _pool_manager: PoolManager | None = None + + @staticmethod + def reset() -> None: + URLFile._pool_manager = None + + @staticmethod + def pool_manager() -> PoolManager: + if URLFile._pool_manager is None: + socket_options = [(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)] + retries = Retry(total=5, backoff_factor=0.5, status_forcelist=[409, 429, 503, 504]) + URLFile._pool_manager = PoolManager(num_pools=10, maxsize=100, socket_options=socket_options, retries=retries) + return URLFile._pool_manager + + def __init__(self, url: str, timeout: int = 10, cache: bool | None = None): + self._url = url + self._timeout = Timeout(connect=timeout, read=timeout) + self._pos = 0 + self._length: int | None = None + # Caching enabled by default, can be disabled with DISABLE_FILEREADER_CACHE=1, or overwritten by the cache input + self._force_download = int(os.environ.get("DISABLE_FILEREADER_CACHE", "0")) == 1 + if cache is not None: + self._force_download = not cache + + if not self._force_download: + os.makedirs(Paths.download_cache_root(), exist_ok=True) + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback) -> None: + pass + + def _request(self, method: str, url: str, headers: dict[str, str] | None = None) -> BaseHTTPResponse: + try: + return URLFile.pool_manager().request(method, url, timeout=self._timeout, headers=headers) + except MaxRetryError as e: + raise URLFileException(f"Failed to {method} {url}: {e}") from e + + def get_length_online(self) -> int: + response = self._request('HEAD', self._url) + if not (200 <= response.status <= 299): + return -1 + length = response.headers.get('content-length', 0) + return int(length) + + def get_length(self) -> int: + if self._length is not None: + return self._length + + file_length_path = os.path.join(Paths.download_cache_root(), hash_url(self._url) + "_length") + if not self._force_download and os.path.exists(file_length_path): + with open(file_length_path) as file_length: + content = file_length.read() + self._length = int(content) + return self._length + + self._length = self.get_length_online() + if not self._force_download and self._length != -1: + with atomic_write(file_length_path, mode="w", overwrite=True) as file_length: + file_length.write(str(self._length)) + return self._length + + def read(self, ll: int | None = None) -> bytes: + if self._force_download: + return self.read_aux(ll=ll) + + file_begin = self._pos + file_end = self._pos + ll if ll is not None else self.get_length() + assert file_end != -1, f"Remote file is empty or doesn't exist: {self._url}" + # We have to align with chunks we store. Position is the begginiing of the latest chunk that starts before or at our file + position = (file_begin // CHUNK_SIZE) * CHUNK_SIZE + response = b"" + while True: + self._pos = position + chunk_number = self._pos / CHUNK_SIZE + file_name = hash_url(self._url) + "_" + str(chunk_number) + full_path = os.path.join(Paths.download_cache_root(), str(file_name)) + data = None + # If we don't have a file, download it + if not os.path.exists(full_path): + data = self.read_aux(ll=CHUNK_SIZE) + with atomic_write(full_path, mode="wb", overwrite=True) as new_cached_file: + new_cached_file.write(data) + prune_cache(file_name) + else: + with open(full_path, "rb") as cached_file: + data = cached_file.read() + + response += data[max(0, file_begin - position): min(CHUNK_SIZE, file_end - position)] + + position += CHUNK_SIZE + if position >= file_end: + self._pos = file_end + return response + + def read_aux(self, ll: int | None = None) -> bytes: + if ll is None: + length = self.get_length() + if length == -1: + raise URLFileException(f"Remote file is empty or doesn't exist: {self._url}") + end = length + else: + end = self._pos + ll + data = self.get_multi_range([(self._pos, end)]) + self._pos += len(data[0]) + return data[0] + + def get_multi_range(self, ranges: list[tuple[int, int]]) -> list[bytes]: + # HTTP range requests are inclusive + assert all(e > s for s, e in ranges), "Range end must be greater than start" + rs = [f"{s}-{e-1}" for s, e in ranges if e > s] + + r = self._request("GET", self._url, headers={"Range": "bytes=" + ",".join(rs)}) + if r.status not in [200, 206]: + raise URLFileException(f"Expected 206 or 200 response {r.status} ({self._url})") + + ctype = (r.headers.get("content-type") or "").lower() + if "multipart/byteranges" not in ctype: + return [r.data,] + + m = re.search(r'boundary="?([^";]+)"?', ctype) + if not m: + raise URLFileException(f"Missing multipart boundary ({self._url})") + boundary = m.group(1).encode() + + parts = [] + for chunk in r.data.split(b"--" + boundary): + if b"\r\n\r\n" not in chunk: + continue + payload = chunk.split(b"\r\n\r\n", 1)[1].rstrip(b"\r\n") + if payload and payload != b"--": + parts.append(payload) + if len(parts) != len(ranges): + raise URLFileException(f"Expected {len(ranges)} parts, got {len(parts)} ({self._url})") + return parts + + def seekable(self) -> bool: + return True + + def seek(self, pos: int, whence: int = 0) -> int: + pos = int(pos) + if whence == os.SEEK_SET: + self._pos = pos + elif whence == os.SEEK_CUR: + self._pos += pos + elif whence == os.SEEK_END: + length = self.get_length() + assert length != -1, "Cannot seek from end on unknown length file" + self._pos = length + pos + else: + raise URLFileException("Invalid whence value") + return self._pos + + def tell(self) -> int: + return self._pos + + @property + def name(self) -> str: + return self._url + + +os.register_at_fork(after_in_child=URLFile.reset) diff --git a/tools/lib/vidindex.py b/openpilot/tools/lib/vidindex.py similarity index 99% rename from tools/lib/vidindex.py rename to openpilot/tools/lib/vidindex.py index f2e4e9ca45..b200700887 100755 --- a/tools/lib/vidindex.py +++ b/openpilot/tools/lib/vidindex.py @@ -140,7 +140,7 @@ def get_ue(dat: bytes, start_idx: int, skip_bits: int) -> tuple[int, int]: j -= 1 if prefix_val == 1 and prefix_len - 1 == suffix_len: - val = 2**(prefix_len-1) - 1 + suffix_val + val = int(2**(prefix_len-1) - 1 + suffix_val) size = prefix_len + suffix_len return val, size i += 1 @@ -269,7 +269,7 @@ def hevc_index(hevc_file_name: str, allow_corrupt: bool=False) -> tuple[list, in raise VideoFileInvalid("first byte must be 0x00") prefix_dat = b"" - frame_types = list() + frame_types = [] i = 1 # skip past first byte 0x00 try: diff --git a/tools/longitudinal_maneuvers/.gitignore b/openpilot/tools/longitudinal_maneuvers/.gitignore similarity index 100% rename from tools/longitudinal_maneuvers/.gitignore rename to openpilot/tools/longitudinal_maneuvers/.gitignore diff --git a/openpilot/tools/longitudinal_maneuvers/README.md b/openpilot/tools/longitudinal_maneuvers/README.md new file mode 100644 index 0000000000..96b989b555 --- /dev/null +++ b/openpilot/tools/longitudinal_maneuvers/README.md @@ -0,0 +1,48 @@ +# Longitudinal Maneuvers Testing Tool + +Test your vehicle's longitudinal control tuning with this tool. The tool will test the vehicle's ability to follow a few longitudinal maneuvers and includes a tool to generate a report from the route. + +
Sample snapshot of a report.
+ +## Instructions + +1. Check out a development branch such as `master` on your comma device. +2. Locate either a large empty parking lot or road devoid of any car or foot traffic. Flat, straight road is preferred. The full maneuver suite can take 1 mile or more if left running, however it is recommended to disengage openpilot between maneuvers and turn around if there is not enough space. +3. Turn off the vehicle and set this parameter which will signal to openpilot to start the longitudinal maneuver daemon: + + ```sh + echo -n 1 > /data/params/d/LongitudinalManeuverMode + ``` + +4. Turn your vehicle back on. You will see the "Longitudinal Maneuver Mode" alert: + + ![videoframe_6652](https://github.com/user-attachments/assets/e9d4c95a-cd76-4ab7-933e-19937792fa0f) + +5. Ensure the road ahead is clear, as openpilot will not brake for any obstructions in this mode. Once you are ready, press "Set" on your steering wheel to start the tests. The tests will run for about 4 minutes. If you need to pause the tests, press "Cancel" on your steering wheel. You can resume the tests by pressing "Resume" on your steering wheel. + + **Note:** For GM cars, it is recommended to hold down the resume button for all low-speed tests (starting, stopping and creep) to avoid the car entering standstill. + + ![cog-clip-00 01 11 250-00 01 22 250](https://github.com/user-attachments/assets/c312c1cc-76e8-46e1-a05e-bb9dfb58994f) + +6. When the testing is complete, you'll see an alert that says "Maneuvers Finished." Complete the route by pulling over and turning off the vehicle. + + ![fin2](https://github.com/user-attachments/assets/c06960ae-7cfb-44af-beaa-4dc28848e49d) + +7. Visit https://connect.comma.ai and locate the route(s). They will stand out with lots of orange intervals in their timeline. Ensure "All logs" show as "uploaded." + + ![image](https://github.com/user-attachments/assets/cfe4c6d9-752f-4b24-b421-4b90a01933dc) + +8. Gather the route ID and then run the report generator. The file will be exported to the same directory: + + ```sh + $ python openpilot/tools/longitudinal_maneuvers/generate_report.py 57048cfce01d9625/0000010e--5b26bc3be7 'pcm accel compensation' + + processing report for LEXUS_ES_TSS2 + plotting maneuver: start from stop, runs: 4 + plotting maneuver: creep: alternate between +1m/s^2 and -1m/s^2, runs: 2 + plotting maneuver: gas step response: +1m/s^2 from 20mph, runs: 2 + + Report written to /home/batman/openpilot/tools/longitudinal_maneuvers/longitudinal_reports/LEXUS_ES_TSS2_57048cfce01d9625_0000010e--5b26bc3be7.html + ``` + +You can reach out on [Discord](https://discord.comma.ai) if you have any questions about these instructions or the tool itself. diff --git a/openpilot/tools/longitudinal_maneuvers/generate_report.py b/openpilot/tools/longitudinal_maneuvers/generate_report.py new file mode 100755 index 0000000000..dbd9f6db91 --- /dev/null +++ b/openpilot/tools/longitudinal_maneuvers/generate_report.py @@ -0,0 +1,187 @@ +#!/usr/bin/env python3 +import argparse +import base64 +import io +import os +import math +import pprint +import webbrowser +from collections import defaultdict +from pathlib import Path +import matplotlib.pyplot as plt +from openpilot.common.utils import tabulate + +from openpilot.tools.lib.logreader import LogReader +from openpilot.common.hardware.hw import Paths + + +def format_car_params(CP): + return pprint.pformat({k: v for k, v in CP.to_dict().items() if not k.endswith('DEPRECATED')}, indent=2) + + +def report(platform, route, _description, CP, ID, maneuvers): + output_path = Path(__file__).resolve().parent / "longitudinal_reports" + output_fn = output_path / f"{platform}_{route.replace('/', '_')}.html" + output_path.mkdir(exist_ok=True) + target_cross_times = defaultdict(list) + + builder = [ + "\n", + "

Longitudinal maneuver report

\n", + f"

{platform}

\n", + f"

{route}

\n", + f"

{ID.gitCommit}, {ID.gitBranch}, {ID.gitRemote}

\n", + ] + if _description is not None: + builder.append(f"

Description: {_description}

\n") + builder.append(f"

CarParams

{format_car_params(CP)}
\n") + builder.append('{ summary }') # to be replaced below + for description, runs in maneuvers: + print(f'plotting maneuver: {description}, runs: {len(runs)}') + builder.append("
\n") + builder.append(f"

{description}

\n") + for run, msgs in enumerate(runs): + t_carControl, carControl = zip(*[(m.logMonoTime, m.carControl) for m in msgs if m.which() == 'carControl'], strict=True) + t_carOutput, carOutput = zip(*[(m.logMonoTime, m.carOutput) for m in msgs if m.which() == 'carOutput'], strict=True) + t_carState, carState = zip(*[(m.logMonoTime, m.carState) for m in msgs if m.which() == 'carState'], strict=True) + t_livePose, livePose = zip(*[(m.logMonoTime, m.livePose) for m in msgs if m.which() == 'livePose'], strict=True) + t_longitudinalPlan, longitudinalPlan = zip(*[(m.logMonoTime, m.longitudinalPlan) for m in msgs if m.which() == 'longitudinalPlan'], strict=True) + + # make time relative seconds + t_carControl = [(t - t_carControl[0]) / 1e9 for t in t_carControl] + t_carOutput = [(t - t_carOutput[0]) / 1e9 for t in t_carOutput] + t_carState = [(t - t_carState[0]) / 1e9 for t in t_carState] + t_livePose = [(t - t_livePose[0]) / 1e9 for t in t_livePose] + t_longitudinalPlan = [(t - t_longitudinalPlan[0]) / 1e9 for t in t_longitudinalPlan] + + # maneuver validity + longActive = [m.longActive for m in carControl] + maneuver_valid = all(longActive) and (not any(cs.cruiseState.standstill for cs in carState) or CP.autoResumeSng) + + _open = 'open' if maneuver_valid else '' + title = f'Run #{int(run)+1}' + (' (invalid maneuver!)' if not maneuver_valid else '') + + builder.append(f"

{title}

\n") + + # get first acceleration target and first intersection + aTarget = longitudinalPlan[0].aTarget + target_cross_time = None + builder.append(f'

Initial aTarget: {round(aTarget, 2)} m/s^2') + + # Localizer is noisy, require two consecutive 20Hz frames above threshold + prev_crossed = False + for t, lp in zip(t_livePose, livePose, strict=True): + crossed = (0 < aTarget < lp.accelerationDevice.x) or (0 > aTarget > lp.accelerationDevice.x) + if crossed and prev_crossed: + builder.append(f', crossed in {t:.3f}s') + target_cross_time = t + if maneuver_valid: + target_cross_times[description].append(t) + break + prev_crossed = crossed + else: + builder.append(', not crossed') + builder.append('

') + + pitches = [math.degrees(m.orientationNED[1]) for m in carControl] + builder.append(f'

Average pitch: {sum(pitches) / len(pitches):0.2f} degrees

') + + plt.rcParams['font.size'] = 40 + fig = plt.figure(figsize=(30, 26)) + ax = fig.subplots(4, 1, sharex=True, gridspec_kw={'height_ratios': [5, 3, 1, 1]}) + + ax[0].grid(linewidth=4) + ax[0].plot(t_carControl, [m.actuators.accel for m in carControl], label='carControl.actuators.accel', linewidth=6) + ax[0].plot(t_carOutput, [m.actuatorsOutput.accel for m in carOutput], label='carOutput.actuatorsOutput.accel', linewidth=6) + ax[0].plot(t_longitudinalPlan, [m.aTarget for m in longitudinalPlan], label='longitudinalPlan.aTarget', linewidth=6) + ax[0].plot(t_carState, [m.aEgo for m in carState], label='carState.aEgo', linewidth=6) + ax[0].plot(t_livePose, [m.accelerationDevice.x for m in livePose], label='livePose.accelerationDevice.x', linewidth=6) + # TODO localizer accel + ax[0].set_ylabel('Acceleration (m/s^2)') + #ax[0].set_ylim(-6.5, 6.5) + ax[0].legend(prop={'size': 30}) + + if target_cross_time is not None: + ax[0].plot(target_cross_time, aTarget, marker='o', markersize=50, markeredgewidth=7, markeredgecolor='black', markerfacecolor='None') + + ax[1].grid(linewidth=4) + ax[1].plot(t_carState, [m.vEgo for m in carState], 'g', label='vEgo', linewidth=6) + ax[1].set_ylabel('Velocity (m/s)') + ax[1].legend() + + ax[2].plot(t_carControl, longActive, label='longActive', linewidth=6) + ax[3].plot(t_carState, [m.gasPressed for m in carState], label='gasPressed', linewidth=6) + ax[3].plot(t_carState, [m.brakePressed for m in carState], label='brakePressed', linewidth=6) + for i in (2, 3): + ax[i].set_yticks([0, 1], minor=False) + ax[i].set_ylim(-1, 2) + ax[i].legend() + + ax[-1].set_xlabel("Time (s)") + fig.tight_layout() + + buffer = io.BytesIO() + fig.savefig(buffer, format='webp') + plt.close(fig) + buffer.seek(0) + builder.append(f"\n") + builder.append("
\n") + + summary = ["

Summary

\n"] + cols = ['maneuver', 'crossed', 'runs', 'mean', 'min', 'max'] + table = [] + for description, runs in maneuvers: + times = target_cross_times[description] + l = [description, len(times), len(runs)] + if len(times): + l.extend([round(sum(times) / len(times), 2), round(min(times), 2), round(max(times), 2)]) + table.append(l) + summary.append(tabulate(table, headers=cols, tablefmt='html', numalign='left') + '\n') + + sum_idx = builder.index('{ summary }') + builder[sum_idx:sum_idx + 1] = summary + + with open(output_fn, "w") as f: + f.write(''.join(builder)) + + print(f"\nOpening report: {output_fn}\n") + webbrowser.open_new_tab(str(output_fn)) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='Generate longitudinal maneuver report from route') + parser.add_argument('route', type=str, help='Route name (e.g. 00000000--5f742174be)') + parser.add_argument('description', type=str, nargs='?') + + args = parser.parse_args() + + if '/' in args.route or '|' in args.route: + lr = LogReader(args.route) + else: + segs = [seg for seg in os.listdir(Paths.log_root()) if args.route in seg] + lr = LogReader([os.path.join(Paths.log_root(), seg, 'rlog.zst') for seg in segs]) + + CP = lr.first('carParams') + ID = lr.first('initData') + platform = CP.carFingerprint + print('processing report for', platform) + + maneuvers: list[tuple[str, list[list]]] = [] + active_prev = False + description_prev = None + + for msg in lr: + if msg.which() == 'alertDebug': + active = 'Maneuver Active' in msg.alertDebug.alertText1 + if active and not active_prev: + if msg.alertDebug.alertText2 == description_prev: + maneuvers[-1][1].append([]) + else: + maneuvers.append((msg.alertDebug.alertText2, [[]])) + description_prev = maneuvers[-1][0] + active_prev = active + + if active_prev: + maneuvers[-1][1][-1].append(msg) + + report(platform, args.route, args.description, CP, ID, maneuvers) diff --git a/openpilot/tools/longitudinal_maneuvers/maneuver_helpers.py b/openpilot/tools/longitudinal_maneuvers/maneuver_helpers.py new file mode 100644 index 0000000000..9fc65fb9e6 --- /dev/null +++ b/openpilot/tools/longitudinal_maneuvers/maneuver_helpers.py @@ -0,0 +1,18 @@ +from enum import IntEnum + +class Axis(IntEnum): + TIME = 0 + EGO_POSITION = 1 + LEAD_DISTANCE= 2 + EGO_V = 3 + LEAD_V = 4 + EGO_A = 5 + D_REL = 6 + +axis_labels = {Axis.TIME: 'Time (s)', + Axis.EGO_POSITION: 'Ego position (m)', + Axis.LEAD_DISTANCE: 'Lead absolute position (m)', + Axis.EGO_V: 'Ego Velocity (m/s)', + Axis.LEAD_V: 'Lead Velocity (m/s)', + Axis.EGO_A: 'Ego acceleration (m/s^2)', + Axis.D_REL: 'Lead distance (m)'} diff --git a/tools/longitudinal_maneuvers/maneuversd.py b/openpilot/tools/longitudinal_maneuvers/maneuversd.py similarity index 83% rename from tools/longitudinal_maneuvers/maneuversd.py rename to openpilot/tools/longitudinal_maneuvers/maneuversd.py index 6c6e252a57..a644e1dc32 100755 --- a/tools/longitudinal_maneuvers/maneuversd.py +++ b/openpilot/tools/longitudinal_maneuvers/maneuversd.py @@ -2,11 +2,12 @@ import numpy as np from dataclasses import dataclass -from cereal import messaging, car -from opendbc.car.common.conversions import Conversions as CV +from openpilot.cereal import messaging +from openpilot.common.constants import CV from openpilot.common.realtime import DT_MDL from openpilot.common.params import Params from openpilot.common.swaglog import cloudlog +from openpilot.selfdrive.controls.lib.drive_helpers import should_stop @dataclass @@ -27,23 +28,14 @@ class Maneuver: _active: bool = False _finished: bool = False + _run_completed: bool = False _action_index: int = 0 _action_frames: int = 0 _ready_cnt: int = 0 _repeated: int = 0 - def get_accel(self, v_ego: float, long_active: bool, standstill: bool, cruise_standstill: bool) -> float: - ready = abs(v_ego - self.initial_speed) < 0.3 and long_active and not cruise_standstill - if self.initial_speed < 0.01: - ready = ready and standstill - self._ready_cnt = (self._ready_cnt + 1) if ready else 0 - - if self._ready_cnt > (3. / DT_MDL): - self._active = True - - if not self._active: - return min(max(self.initial_speed - v_ego, -2.), 2.) - + def _step(self) -> float: + self._run_completed = False action = self.actions[self._action_index] action_accel = np.interp(self._action_frames * DT_MDL, action.time_bp, action.accel_bp) @@ -58,15 +50,34 @@ class Maneuver: # repeat maneuver elif self._repeated < self.repeat: self._repeated += 1 - self._action_index = 0 - self._action_frames = 0 - self._active = False + self._run_completed = True + self.reset() # finish maneuver else: + self._run_completed = True self._finished = True return float(action_accel) + def get_accel(self, v_ego: float, long_active: bool, standstill: bool, cruise_standstill: bool, /) -> float: + ready = abs(v_ego - self.initial_speed) < 0.3 and long_active and not cruise_standstill + if self.initial_speed < 0.01: + ready = ready and standstill + self._ready_cnt = (self._ready_cnt + 1) if ready else 0 + + if self._ready_cnt > (3. / DT_MDL): + self._active = True + + if not self._active: + return min(max(self.initial_speed - v_ego, -2.), 2.) + + return self._step() + + def reset(self): + self._active = False + self._action_frames = 0 + self._action_index = 0 + @property def finished(self): return self._finished @@ -128,11 +139,11 @@ MANEUVERS = [ def main(): params = Params() - cloudlog.info("joystickd is waiting for CarParams") - CP = messaging.log_from_bytes(params.get("CarParams", block=True), car.CarParams) + cloudlog.info("maneuversd is waiting for CarParams") + params.get("CarParams", block=True) sm = messaging.SubMaster(['carState', 'carControl', 'controlsState', 'selfdriveState', 'modelV2'], poll='modelV2') - pm = messaging.PubMaster(['longitudinalPlan', 'driverAssistance', 'alertDebug']) + pm = messaging.PubMaster(['longitudinalPlan', 'longitudinalPlanSP', 'driverAssistance', 'alertDebug']) maneuvers = iter(MANEUVERS) maneuver = None @@ -167,7 +178,7 @@ def main(): pm.send('alertDebug', alert_msg) longitudinalPlan.aTarget = accel - longitudinalPlan.shouldStop = v_ego < CP.vEgoStopping and accel < 1e-2 + longitudinalPlan.shouldStop = should_stop(v_ego, accel) longitudinalPlan.allowBrake = True longitudinalPlan.allowThrottle = True @@ -177,6 +188,10 @@ def main(): pm.send('longitudinalPlan', plan_send) + plan_sp_send = messaging.new_message('longitudinalPlanSP') + plan_sp_send.valid = True + pm.send('longitudinalPlanSP', plan_sp_send) + assistance_send = messaging.new_message('driverAssistance') assistance_send.valid = True pm.send('driverAssistance', assistance_send) diff --git a/openpilot/tools/longitudinal_maneuvers/mpc_longitudinal_tuning_report.py b/openpilot/tools/longitudinal_maneuvers/mpc_longitudinal_tuning_report.py new file mode 100644 index 0000000000..6b711a0847 --- /dev/null +++ b/openpilot/tools/longitudinal_maneuvers/mpc_longitudinal_tuning_report.py @@ -0,0 +1,305 @@ +import io +import sys +import markdown +import numpy as np +import matplotlib.pyplot as plt +from openpilot.common.realtime import DT_MDL +from openpilot.selfdrive.controls.tests.test_following_distance import desired_follow_distance +from openpilot.tools.longitudinal_maneuvers.maneuver_helpers import Axis, axis_labels +from openpilot.selfdrive.test.longitudinal_maneuvers.maneuver import Maneuver + + +def get_html_from_results(results, labels, AXIS): + fig, ax = plt.subplots(figsize=(16, 8)) + for idx, key in enumerate(results.keys()): + ax.plot(results[key][:, Axis.TIME], results[key][:, AXIS], label=labels[idx]) + + ax.set_xlabel(axis_labels[Axis.TIME]) + ax.set_ylabel(axis_labels[AXIS]) + ax.legend(bbox_to_anchor=(1.02, 1), loc='upper left', borderaxespad=0) + ax.grid(True, linestyle='--', alpha=0.7) + ax.text(-0.075, 0.5, '.', transform=ax.transAxes, color='none') + + fig_buffer = io.StringIO() + fig.savefig(fig_buffer, format='svg', bbox_inches='tight') + plt.close(fig) + return fig_buffer.getvalue() + '
' + +def generate_mpc_tuning_report(e2e=False): + htmls = [] + + results = {} + name = 'Resuming behind lead' + labels = [] + for lead_accel in np.linspace(1.0, 4.0, 4): + man = Maneuver( + '', + duration=11, + initial_speed=0.0, + lead_relevancy=True, + initial_distance_lead=desired_follow_distance(0.0, 0.0), + speed_lead_values=[0.0, 10 * lead_accel], + cruise_values=[100, 100], + prob_lead_values=[1.0, 1.0], + breakpoints=[1., 11], + e2e=e2e, + ) + valid, results[lead_accel] = man.evaluate() + labels.append(f'{lead_accel} m/s^2 lead acceleration') + + htmls.append(markdown.markdown('# ' + name)) + htmls.append(get_html_from_results(results, labels, Axis.EGO_V)) + htmls.append(get_html_from_results(results, labels, Axis.EGO_A)) + + + results = {} + name = 'Approaching stopped car from 140m' + labels = [] + for speed in np.arange(0,45,5): + man = Maneuver( + name, + duration=30., + initial_speed=float(speed), + lead_relevancy=True, + initial_distance_lead=140., + speed_lead_values=[0.0, 0.], + breakpoints=[0., 30.], + e2e=e2e, + ) + valid, results[speed] = man.evaluate() + labels.append(f'{speed} m/s approach speed') + + htmls.append(markdown.markdown('# ' + name)) + htmls.append(get_html_from_results(results, labels, Axis.EGO_A)) + htmls.append(get_html_from_results(results, labels, Axis.D_REL)) + + + results = {} + name = 'Following 5s (triangular) oscillating lead' + labels = [] + speed = np.int64(10) + for oscil in np.arange(0, 10, 1): + man = Maneuver( + '', + duration=30., + initial_speed=float(speed), + lead_relevancy=True, + initial_distance_lead=desired_follow_distance(speed, speed), + speed_lead_values=[speed, speed, speed - oscil, speed + oscil, speed - oscil, speed + oscil, speed - oscil], + breakpoints=[0.,2., 5, 8, 15, 18, 25.], + e2e=e2e, + ) + valid, results[oscil] = man.evaluate() + labels.append(f'{oscil} m/s oscillation size') + + htmls.append(markdown.markdown('# ' + name)) + htmls.append(get_html_from_results(results, labels, Axis.D_REL)) + htmls.append(get_html_from_results(results, labels, Axis.EGO_V)) + htmls.append(get_html_from_results(results, labels, Axis.EGO_A)) + + + results = {} + name = 'Following 5s (sinusoidal) oscillating lead' + labels = [] + speed = np.int64(10) + duration = float(30) + f_osc = 1. / 5 + for oscil in np.arange(0, 10, 1): + bps = DT_MDL * np.arange(int(duration / DT_MDL)) + lead_speeds = speed + oscil * np.sin(2 * np.pi * f_osc * bps) + man = Maneuver( + '', + duration=duration, + initial_speed=float(speed), + lead_relevancy=True, + initial_distance_lead=desired_follow_distance(speed, speed), + speed_lead_values=lead_speeds, + breakpoints=bps, + e2e=e2e, + ) + valid, results[oscil] = man.evaluate() + labels.append(f'{oscil} m/s oscillation size') + + htmls.append(markdown.markdown('# ' + name)) + htmls.append(get_html_from_results(results, labels, Axis.D_REL)) + htmls.append(get_html_from_results(results, labels, Axis.EGO_V)) + htmls.append(get_html_from_results(results, labels, Axis.EGO_A)) + + + results = {} + name = 'Speed profile when converging to steady state lead at 30m/s' + labels = [] + for distance in np.arange(20, 140, 10): + man = Maneuver( + '', + duration=50, + initial_speed=30.0, + lead_relevancy=True, + initial_distance_lead=distance, + speed_lead_values=[30.0], + breakpoints=[0.], + e2e=e2e, + ) + valid, results[distance] = man.evaluate() + labels.append(f'{distance} m initial distance') + + htmls.append(markdown.markdown('# ' + name)) + htmls.append(get_html_from_results(results, labels, Axis.EGO_V)) + htmls.append(get_html_from_results(results, labels, Axis.D_REL)) + + + results = {} + name = 'Speed profile when converging to steady state lead at 20m/s' + labels = [] + for distance in np.arange(20, 140, 10): + man = Maneuver( + '', + duration=50, + initial_speed=20.0, + lead_relevancy=True, + initial_distance_lead=distance, + speed_lead_values=[20.0], + breakpoints=[0.], + e2e=e2e, + ) + valid, results[distance] = man.evaluate() + labels.append(f'{distance} m initial distance') + + htmls.append(markdown.markdown('# ' + name)) + htmls.append(get_html_from_results(results, labels, Axis.EGO_V)) + htmls.append(get_html_from_results(results, labels, Axis.D_REL)) + + + results = {} + name = 'Following car at 30m/s that comes to a stop' + labels = [] + for stop_time in np.arange(4, 14, 1): + man = Maneuver( + '', + duration=30, + initial_speed=30.0, + cruise_values=[30.0, 30.0, 30.0], + lead_relevancy=True, + initial_distance_lead=60.0, + speed_lead_values=[30.0, 30.0, 0.0], + breakpoints=[0., 5., 5 + stop_time], + e2e=e2e, + ) + valid, results[stop_time] = man.evaluate() + labels.append(f'{stop_time} seconds stop time') + + htmls.append(markdown.markdown('# ' + name)) + htmls.append(get_html_from_results(results, labels, Axis.EGO_A)) + htmls.append(get_html_from_results(results, labels, Axis.D_REL)) + + + results = {} + name = 'Response to cut-in at half follow distance' + labels = [] + for speed in np.arange(0, 40, 5): + man = Maneuver( + '', + duration=20, + initial_speed=float(speed), + cruise_values=[speed, speed, speed], + lead_relevancy=True, + initial_distance_lead=desired_follow_distance(speed, speed)/2, + speed_lead_values=[speed, speed, speed], + prob_lead_values=[0.0, 0.0, 1.0], + breakpoints=[0., 5.0, 5.01], + e2e=e2e, + ) + valid, results[speed] = man.evaluate() + labels.append(f'{speed} m/s speed') + + htmls.append(markdown.markdown('# ' + name)) + htmls.append(get_html_from_results(results, labels, Axis.EGO_A)) + htmls.append(get_html_from_results(results, labels, Axis.D_REL)) + + + results = {} + name = 'Follow a lead that accelerates at 2m/s^2 until steady state speed' + labels = [] + for speed in np.arange(0, 40, 5): + man = Maneuver( + '', + duration=60, + initial_speed=0.0, + lead_relevancy=True, + initial_distance_lead=desired_follow_distance(0.0, 0.0), + speed_lead_values=[0.0, 0.0, speed], + prob_lead_values=[1.0, 1.0, 1.0], + breakpoints=[0., 1.0, speed/2], + e2e=e2e, + ) + valid, results[speed] = man.evaluate() + labels.append(f'{speed} m/s speed') + + htmls.append(markdown.markdown('# ' + name)) + htmls.append(get_html_from_results(results, labels, Axis.EGO_V)) + htmls.append(get_html_from_results(results, labels, Axis.EGO_A)) + + + results = {} + name = 'From stop to cruise' + labels = [] + for speed in np.arange(0, 40, 5): + man = Maneuver( + '', + duration=50, + initial_speed=0.0, + lead_relevancy=True, + initial_distance_lead=desired_follow_distance(0.0, 0.0), + speed_lead_values=[0.0, 0.0], + cruise_values=[0.0, speed], + prob_lead_values=[0.0, 0.0], + breakpoints=[1., 1.01], + e2e=e2e, + ) + valid, results[speed] = man.evaluate() + labels.append(f'{speed} m/s speed') + + htmls.append(markdown.markdown('# ' + name)) + htmls.append(get_html_from_results(results, labels, Axis.EGO_V)) + htmls.append(get_html_from_results(results, labels, Axis.EGO_A)) + + + results = {} + name = 'From cruise to min' + labels = [] + for speed in np.arange(10, 40, 5): + man = Maneuver( + '', + duration=50, + initial_speed=float(speed), + lead_relevancy=True, + initial_distance_lead=desired_follow_distance(0.0, 0.0), + speed_lead_values=[0.0, 0.0], + cruise_values=[speed, 10.0], + prob_lead_values=[0.0, 0.0], + breakpoints=[1., 1.01], + e2e=e2e, + ) + valid, results[speed] = man.evaluate() + labels.append(f'{speed} m/s speed') + + htmls.append(markdown.markdown('# ' + name)) + htmls.append(get_html_from_results(results, labels, Axis.EGO_V)) + htmls.append(get_html_from_results(results, labels, Axis.EGO_A)) + + return htmls + +if __name__ == '__main__': + e2e = '--e2e' in sys.argv + file_name = 'long_mpc_tune_report.html' + for arg in sys.argv[1:]: + if not arg.startswith('-'): + file_name = arg + break + + htmls = generate_mpc_tuning_report(e2e=e2e) + + with open(file_name, 'w') as f: + f.write(markdown.markdown('# MPC longitudinal tuning report')) + for html in htmls: + f.write(html) diff --git a/openpilot/tools/plotjuggler/README.md b/openpilot/tools/plotjuggler/README.md new file mode 100644 index 0000000000..efccbdc0bd --- /dev/null +++ b/openpilot/tools/plotjuggler/README.md @@ -0,0 +1,77 @@ +# PlotJuggler + +[PlotJuggler](https://github.com/facontidavide/PlotJuggler) is a tool to quickly visualize time series data, and we've written plugins to parse openpilot logs. Check out our plugins: https://github.com/commaai/PlotJuggler. + +## Installation + +Once you've [set up the openpilot environment](../README.md), this command will download PlotJuggler and install our plugins: + +`cd openpilot/tools/plotjuggler && ./juggle.py --install` + +## Usage + +``` +$ ./juggle.py -h +usage: juggle.py [-h] [--demo] [--can] [--stream] [--layout [LAYOUT]] [--install] [--dbc DBC] + [route_or_segment_name] + +A helper to run PlotJuggler on openpilot routes + +positional arguments: + route_or_segment_name + The route or segment name to plot (cabana share URL accepted) (default: None) + +optional arguments: + -h, --help show this help message and exit + --demo Use the demo route instead of providing one (default: False) + --can Parse CAN data (default: False) + --stream Start PlotJuggler in streaming mode (default: False) + --layout [LAYOUT] Run PlotJuggler with a pre-defined layout (default: None) + --install Install or update PlotJuggler + plugins (default: False) + --dbc DBC Set the DBC name to load for parsing CAN data. If not set, the DBC will be automatically + inferred from the logs. (default: None) + +``` + +Example using route name: + +`./juggle.py "5beb9b58bd12b691/0000010a--a51155e496"` + +Examples using segment: + +`./juggle.py "5beb9b58bd12b691/0000010a--a51155e496/1"` + +`./juggle.py "5beb9b58bd12b691/0000010a--a51155e496/1/q" # use qlogs` + +Example using segment range: + +`./juggle.py "5beb9b58bd12b691/0000010a--a51155e496/0:1"` + +## Streaming + +Explore live data from your car! Follow these steps to stream from your comma device to your laptop: +- Enable wifi tethering on your comma device +- [SSH into your device](https://github.com/commaai/openpilot/wiki/SSH) and run `cd /data/openpilot && ./openpilot/cereal/messaging/bridge` +- On your laptop, connect to the device's wifi hotspot +- Start PlotJuggler with `ZMQ=1 ./juggle.py --stream`, find the `Cereal Subscriber` plugin in the dropdown under Streaming, and click `Start`. + +If streaming to PlotJuggler from a replay on your PC, simply run: `./juggle.py --stream` and start the cereal subscriber. + +## Demo + +For a quick demo, go through the installation step and run this command: + +`./juggle.py --demo --layout=layouts/tuning.xml` + +## Layouts + +If you create a layout that's useful for others, consider upstreaming it. + +### Tuning + +Use this layout to improve your car's tuning and generate plots for tuning PRs. Also see the [tuning wiki](https://github.com/commaai/openpilot/wiki/Tuning) and tuning PR template. + +`--layout layouts/tuning.xml` + + +![screenshot](https://i.imgur.com/cizHCH3.png) diff --git a/openpilot/tools/plotjuggler/juggle.py b/openpilot/tools/plotjuggler/juggle.py new file mode 100755 index 0000000000..6ddbdbeb3e --- /dev/null +++ b/openpilot/tools/plotjuggler/juggle.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +import os +import sys +import platform +import shutil +import subprocess +import tarfile +import tempfile +import requests +import argparse +from functools import partial +from opendbc.car.fingerprints import MIGRATION +from openpilot.common.basedir import BASEDIR +from openpilot.common.swaglog import cloudlog +from openpilot.tools.cabana.dbc.generate_dbc_json import generate_dbc_dict +from openpilot.tools.lib.logreader import LogReader, ReadMode, save_log +from openpilot.selfdrive.test.process_replay.migration import migrate_all + +juggle_dir = os.path.dirname(os.path.realpath(__file__)) + +os.environ['LD_LIBRARY_PATH'] = os.environ.get('LD_LIBRARY_PATH', '') + f":{juggle_dir}/bin/" + +DEMO_ROUTE = "5beb9b58bd12b691/0000010a--a51155e496" +RELEASES_URL = "https://github.com/commaai/PlotJuggler/releases/download/latest" +INSTALL_DIR = os.path.join(juggle_dir, "bin") +PLOTJUGGLER_BIN = os.path.join(juggle_dir, "bin/plotjuggler") +MINIMUM_PLOTJUGGLER_VERSION = (3, 5, 2) +MAX_STREAMING_BUFFER_SIZE = 1000 + + +def print_jotpluggler_banner(): + purple = "\033[95m" if sys.stdout.isatty() else "" + reset = "\033[0m" if purple else "" + print(f"{purple}+-------------------------------------------------------------+{reset}") + print(f"{purple}|{reset} JotPluggler is the future! Try it like this: {purple}|{reset}") + print(f"{purple}|{reset} ./openpilot/tools/jotpluggler/jotpluggler --demo --layout tuning {purple}|{reset}") + print(f"{purple}|{reset} {purple}|{reset}") + print(f"{purple}|{reset} PlotJuggler will be deleted soon. {purple}|{reset}") + print(f"{purple}|{reset} Missing a feature? Open an issue or post in #dev-openpilot. {purple}|{reset}") + print(f"{purple}+-------------------------------------------------------------+{reset}") + + +def install(): + m = f"{platform.system()}-{platform.machine()}" + supported = ("Linux-x86_64", "Linux-aarch64", "Darwin-arm64") + if m not in supported: + raise Exception(f"Unsupported platform: '{m}'. Supported platforms: {supported}") + + if os.path.exists(INSTALL_DIR): + shutil.rmtree(INSTALL_DIR) + os.mkdir(INSTALL_DIR) + + url = os.path.join(RELEASES_URL, m + ".tar.gz") + with requests.get(url, stream=True, timeout=10) as r, tempfile.NamedTemporaryFile() as tmp: + r.raise_for_status() + with open(tmp.name, 'wb') as tmpf: + for chunk in r.iter_content(chunk_size=1024 * 1024): + tmpf.write(chunk) + + with tarfile.open(tmp.name) as tar: + tar.extractall(path=INSTALL_DIR, filter="data") + + +def get_plotjuggler_version(): + out = subprocess.check_output([PLOTJUGGLER_BIN, "-v"], encoding="utf-8").strip() + version = out.split(" ")[1] + return tuple(map(int, version.split("."))) + + +def start_juggler(fn=None, dbc=None, layout=None, route_or_segment_name=None, platform=None): + env = os.environ.copy() + env["PATH"] = f"{INSTALL_DIR}:{os.getenv('PATH', '')}" + if dbc: + if os.path.exists(dbc): + dbc = os.path.abspath(dbc) + env["DBC_NAME"] = dbc + + extra_args = "" + if fn is not None: + extra_args += f" -d {os.path.abspath(fn)}" + if layout is not None: + extra_args += f" -l {os.path.abspath(layout)}" + if route_or_segment_name is not None: + extra_args += f" --window_title \"{route_or_segment_name}{f' ({platform})' if platform is not None else ''}\"" + + cmd = f'{PLOTJUGGLER_BIN} --buffer_size {MAX_STREAMING_BUFFER_SIZE} --plugin_folders {INSTALL_DIR}{extra_args}' + with tempfile.TemporaryDirectory() as schema_root: + tmp_cereal = os.path.join(schema_root, "cereal") + os.mkdir(tmp_cereal) + for schema in ("log.capnp", "deprecated.capnp", "custom.capnp"): + with open(os.path.join(BASEDIR, "openpilot", "cereal", schema)) as src: + contents = src.read() + contents = contents.replace('import "/include/c++.capnp"', 'import "./include/c++.capnp"') + contents = contents.replace('import "/car.capnp"', 'import "car.capnp"') + with open(os.path.join(tmp_cereal, schema), "w") as dst: + dst.write(contents) + os.symlink(os.path.join(BASEDIR, "openpilot", "cereal", "include"), os.path.join(tmp_cereal, "include"), target_is_directory=True) + os.symlink(os.path.join(BASEDIR, "opendbc_repo", "opendbc", "car", "car.capnp"), os.path.join(tmp_cereal, "car.capnp")) + os.symlink(os.path.join(BASEDIR, "opendbc_repo", "opendbc"), os.path.join(schema_root, "opendbc"), target_is_directory=True) + env["BASEDIR"] = schema_root + subprocess.call(cmd, shell=True, env=env, cwd=juggle_dir) + + +def process(can, lr): + return [d for d in lr if can or d.which() not in ['can', 'sendcan'] and not d.which().startswith('customReserved')] + + +def juggle_route(route_or_segment_name, can, layout, dbc, should_migrate): + lr = LogReader(route_or_segment_name, default_mode=ReadMode.AUTO_INTERACTIVE) + + all_data = lr.run_across_segments(24, partial(process, can)) + if should_migrate: + all_data = migrate_all(all_data) + + # Infer DBC name from logs + platform = None + if dbc is None: + try: + CP = lr.first('carParams') + platform = MIGRATION.get(CP.carFingerprint, CP.carFingerprint) + dbc = generate_dbc_dict()[platform] + except Exception: + cloudlog.exception("Failed to get DBC name from logs!") + + with tempfile.NamedTemporaryFile(suffix='.rlog', dir=juggle_dir) as tmp: + save_log(tmp.name, all_data, compress=False) + del all_data + start_juggler(tmp.name, dbc, layout, route_or_segment_name, platform) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="A helper to run PlotJuggler on openpilot routes", + formatter_class=argparse.ArgumentDefaultsHelpFormatter) + + parser.add_argument("--demo", action="store_true", help="Use the demo route instead of providing one") + parser.add_argument("--can", action="store_true", help="Parse CAN data") + parser.add_argument("--stream", action="store_true", help="Start PlotJuggler in streaming mode") + parser.add_argument("--no-migration", action="store_true", help="Do not perform log migration") + parser.add_argument("--layout", nargs='?', help="Run PlotJuggler with a pre-defined layout") + parser.add_argument("--install", action="store_true", help="Install or update PlotJuggler + plugins") + parser.add_argument("--dbc", help="Set the DBC name to load for parsing CAN data. If not set, the DBC will be automatically inferred from the logs.") + parser.add_argument("route_or_segment_name", nargs='?', help="The route or segment name to plot (cabana share URL accepted)") + + if len(sys.argv) == 1: + print_jotpluggler_banner() + print() + parser.print_help() + sys.exit() + args = parser.parse_args() + + print_jotpluggler_banner() + print() + + if args.install: + install() + sys.exit() + + if not os.path.exists(PLOTJUGGLER_BIN): + print("PlotJuggler is missing. Downloading...") + install() + + if get_plotjuggler_version() < MINIMUM_PLOTJUGGLER_VERSION: + print("PlotJuggler is out of date. Installing update...") + install() + + if args.stream: + start_juggler(layout=args.layout) + else: + route_or_segment_name = DEMO_ROUTE if args.demo else args.route_or_segment_name.strip() + juggle_route(route_or_segment_name, args.can, args.layout, args.dbc, not args.no_migration) diff --git a/tools/plotjuggler/layouts/CAN-bus-debug.xml b/openpilot/tools/plotjuggler/layouts/CAN-bus-debug.xml similarity index 100% rename from tools/plotjuggler/layouts/CAN-bus-debug.xml rename to openpilot/tools/plotjuggler/layouts/CAN-bus-debug.xml diff --git a/tools/plotjuggler/layouts/camera-timings.xml b/openpilot/tools/plotjuggler/layouts/camera-timings.xml similarity index 100% rename from tools/plotjuggler/layouts/camera-timings.xml rename to openpilot/tools/plotjuggler/layouts/camera-timings.xml diff --git a/tools/plotjuggler/layouts/can-states.xml b/openpilot/tools/plotjuggler/layouts/can-states.xml similarity index 100% rename from tools/plotjuggler/layouts/can-states.xml rename to openpilot/tools/plotjuggler/layouts/can-states.xml diff --git a/tools/plotjuggler/layouts/controls_mismatch_debug.xml b/openpilot/tools/plotjuggler/layouts/controls_mismatch_debug.xml similarity index 97% rename from tools/plotjuggler/layouts/controls_mismatch_debug.xml rename to openpilot/tools/plotjuggler/layouts/controls_mismatch_debug.xml index 646e12a281..cf337aa7df 100644 --- a/tools/plotjuggler/layouts/controls_mismatch_debug.xml +++ b/openpilot/tools/plotjuggler/layouts/controls_mismatch_debug.xml @@ -16,7 +16,7 @@ - + @@ -58,4 +58,3 @@ - diff --git a/tools/plotjuggler/layouts/gps.xml b/openpilot/tools/plotjuggler/layouts/gps.xml similarity index 100% rename from tools/plotjuggler/layouts/gps.xml rename to openpilot/tools/plotjuggler/layouts/gps.xml diff --git a/tools/plotjuggler/layouts/gps_vs_llk.xml b/openpilot/tools/plotjuggler/layouts/gps_vs_llk.xml similarity index 90% rename from tools/plotjuggler/layouts/gps_vs_llk.xml rename to openpilot/tools/plotjuggler/layouts/gps_vs_llk.xml index 69b8f20058..2051c2bef2 100644 --- a/tools/plotjuggler/layouts/gps_vs_llk.xml +++ b/openpilot/tools/plotjuggler/layouts/gps_vs_llk.xml @@ -24,8 +24,8 @@ - - + + @@ -72,12 +72,11 @@ return distance /gpsLocationExternal/latitude /gpsLocationExternal/longitude - /liveLocationKalman/positionGeodetic/value/0 - /liveLocationKalman/positionGeodetic/value/1 + /liveLocationKalmanDEPRECATED/positionGeodetic/value/0 + /liveLocationKalmanDEPRECATED/positionGeodetic/value/1 - diff --git a/tools/plotjuggler/layouts/locationd_debug.xml b/openpilot/tools/plotjuggler/layouts/locationd_debug.xml similarity index 100% rename from tools/plotjuggler/layouts/locationd_debug.xml rename to openpilot/tools/plotjuggler/layouts/locationd_debug.xml diff --git a/tools/plotjuggler/layouts/longitudinal.xml b/openpilot/tools/plotjuggler/layouts/longitudinal.xml similarity index 100% rename from tools/plotjuggler/layouts/longitudinal.xml rename to openpilot/tools/plotjuggler/layouts/longitudinal.xml diff --git a/tools/plotjuggler/layouts/max-torque-debug.xml b/openpilot/tools/plotjuggler/layouts/max-torque-debug.xml similarity index 100% rename from tools/plotjuggler/layouts/max-torque-debug.xml rename to openpilot/tools/plotjuggler/layouts/max-torque-debug.xml diff --git a/tools/plotjuggler/layouts/system_lag_debug.xml b/openpilot/tools/plotjuggler/layouts/system_lag_debug.xml similarity index 97% rename from tools/plotjuggler/layouts/system_lag_debug.xml rename to openpilot/tools/plotjuggler/layouts/system_lag_debug.xml index a90bba0e27..88511ffe09 100644 --- a/tools/plotjuggler/layouts/system_lag_debug.xml +++ b/openpilot/tools/plotjuggler/layouts/system_lag_debug.xml @@ -45,7 +45,7 @@ - + @@ -64,4 +64,3 @@ - diff --git a/tools/plotjuggler/layouts/thermal_debug.xml b/openpilot/tools/plotjuggler/layouts/thermal_debug.xml similarity index 100% rename from tools/plotjuggler/layouts/thermal_debug.xml rename to openpilot/tools/plotjuggler/layouts/thermal_debug.xml diff --git a/openpilot/tools/plotjuggler/layouts/torque-controller.xml b/openpilot/tools/plotjuggler/layouts/torque-controller.xml new file mode 100644 index 0000000000..8e9a1a8526 --- /dev/null +++ b/openpilot/tools/plotjuggler/layouts/torque-controller.xml @@ -0,0 +1,250 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + return value * 3.6 + /carState/vEgo + + + + return value * 2.23694 + /carState/vEgo + + + + return (value * v1 ^ 2) - (v2 * 9.81) + /controlsState/desiredCurvature + + /carState/vEgo + /liveParameters/roll + + + + + return (value * v1 ^ 2) - (v2 * 9.81) + /controlsState/curvature + + /carState/vEgo + /liveParameters/roll + + + + + return value + 0.2 + /carParams/steerActuatorDelay + + + + return (0) + /carState/canValid + + + + + + diff --git a/tools/plotjuggler/layouts/tuning.xml b/openpilot/tools/plotjuggler/layouts/tuning.xml similarity index 91% rename from tools/plotjuggler/layouts/tuning.xml rename to openpilot/tools/plotjuggler/layouts/tuning.xml index 503e726caf..699f6ff683 100644 --- a/tools/plotjuggler/layouts/tuning.xml +++ b/openpilot/tools/plotjuggler/layouts/tuning.xml @@ -24,14 +24,14 @@ - + - + @@ -39,7 +39,7 @@ - + @@ -71,7 +71,7 @@ - + @@ -126,7 +126,7 @@ - + @@ -161,11 +161,11 @@ if (time > last_bad_time + engage_delay) then else return 0 end - /liveLocationKalman/angularVelocityCalibrated/value/2 + /carControl/angularVelocity/2 /carState/steeringPressed /carControl/enabled - /liveLocationKalman/velocityCalibrated/value/0 + /carState/vEgo @@ -206,7 +206,7 @@ if (time > last_bad_time + engage_delay) then else return 0 end - /lateralPlan/curvatures/0 + /modelV2/action/desiredCurvature /carState/steeringPressed /carControl/enabled @@ -284,8 +284,17 @@ end /carControl/enabled + + + return (math.abs(value - v1) > 0.001 or math.abs(v2 - v3) > 0.05) and 1 or 0 + /carControl/actuators/torque + + /carOutput/actuatorsOutput/torque + /carControl/actuators/steeringAngleDeg + /carOutput/actuatorsOutput/steeringAngleDeg + + - diff --git a/tools/plotjuggler/layouts/ublox-debug.xml b/openpilot/tools/plotjuggler/layouts/ublox-debug.xml similarity index 100% rename from tools/plotjuggler/layouts/ublox-debug.xml rename to openpilot/tools/plotjuggler/layouts/ublox-debug.xml diff --git a/tools/plotjuggler/test_plotjuggler.py b/openpilot/tools/plotjuggler/test_plotjuggler.py similarity index 90% rename from tools/plotjuggler/test_plotjuggler.py rename to openpilot/tools/plotjuggler/test_plotjuggler.py index a2c509f943..d55aafe9be 100644 --- a/tools/plotjuggler/test_plotjuggler.py +++ b/openpilot/tools/plotjuggler/test_plotjuggler.py @@ -1,17 +1,21 @@ import os import glob +import shutil import signal import subprocess import time +import pytest + from openpilot.common.basedir import BASEDIR from openpilot.common.timeout import Timeout from openpilot.tools.plotjuggler.juggle import DEMO_ROUTE, install -PJ_DIR = os.path.join(BASEDIR, "tools/plotjuggler") +PJ_DIR = os.path.join(BASEDIR, "openpilot/tools/plotjuggler") class TestPlotJuggler: + @pytest.mark.skipif(not shutil.which('qmake'), reason="Qt not installed") def test_demo(self): install() diff --git a/openpilot/tools/replay/.gitignore b/openpilot/tools/replay/.gitignore new file mode 100644 index 0000000000..aa615770a2 --- /dev/null +++ b/openpilot/tools/replay/.gitignore @@ -0,0 +1,2 @@ +replay +tests/test_replay diff --git a/openpilot/tools/replay/README.md b/openpilot/tools/replay/README.md new file mode 100644 index 0000000000..108df08935 --- /dev/null +++ b/openpilot/tools/replay/README.md @@ -0,0 +1,142 @@ +# Replay + +`replay` allows you to simulate a driving session by replaying all messages logged during the use of openpilot. This provides a way to analyze and visualize system behavior as if it were live. + +## Setup + +Before starting a replay, you need to authenticate with your comma account using `auth.py`. This will allow you to access your routes from the server. + +```bash +# Authenticate to access routes from your comma account: +python3 openpilot/tools/lib/auth.py +``` + +## Replay a Remote Route +You can replay a route from your comma account by specifying the route name. + +```bash +# Start a replay with a specific route: +openpilot/tools/replay/replay + +# Example: +openpilot/tools/replay/replay '5beb9b58bd12b691/0000010a--a51155e496' + +# Replay the default demo route: +openpilot/tools/replay/replay --demo +``` + +## Replay a Local Route +To replay a route stored locally on your machine, specify the route name and provide the path to the directory where the route files are stored. + +```bash +# Replay a local route +openpilot/tools/replay/replay --data_dir="/path_to/route" + +# Example: +# If you have a local route stored at /path_to_routes with segments like: +# 5beb9b58bd12b691/0000010a--a51155e496--0 +# 5beb9b58bd12b691/0000010a--a51155e496--1 +# You can replay it like this: +openpilot/tools/replay/replay "5beb9b58bd12b691/0000010a--a51155e496" --data_dir="/path_to_routes" +``` + +## Send Messages via ZMQ +By default, replay sends messages via MSGQ. To switch to ZMQ, set the ZMQ environment variable. + +```bash +# Start replay and send messages via ZMQ: +ZMQ=1 openpilot/tools/replay/replay +``` + +## Usage +For more information on available options and arguments, use the help command: + +``` bash +$ openpilot/tools/replay/replay -h +Usage: openpilot/tools/replay/replay [options] route +Mock openpilot components by publishing logged messages. + +Options: + -h, --help Displays this help. + -a, --allow whitelist of services to send (comma-separated) + -b, --block blacklist of services to send (comma-separated) + -c, --cache cache segments in memory. default is 5 + -s, --start start from + -x playback . between 0.2 - 3 + --demo use a demo route instead of providing your own + --auto Auto load the route from the best available source (no video): + internal, openpilotci, comma_api, car_segments, testing_closet + --data_dir local directory with routes + --prefix set OPENPILOT_PREFIX + --dcam load driver camera + --ecam load wide road camera + --no-loop stop at the end of the route + --no-cache turn off local cache + --qcam load qcamera + --no-hw-decoder disable HW video decoding + --no-vipc do not output video + --all do output all messages including uiDebug, userBookmark. + this may causes issues when used along with UI + +Arguments: + route the drive to replay. find your drives at + connect.comma.ai +``` + +## Visualize the Replay in the openpilot UI +To visualize the replay within the openpilot UI, run the following commands: + +```bash +openpilot/tools/replay/replay +cd openpilot/selfdrive/ui && ./ui.py +``` + +## Work with plotjuggler +If you want to use replay with plotjuggler, you can stream messages by running: + +```bash +openpilot/tools/replay/replay +openpilot/tools/plotjuggler/juggle.py --stream +``` + +## watch3 + +watch all three cameras simultaneously from your comma three routes with watch3 + +simply replay a route using the `--dcam` and `--ecam` flags: + +```bash +# start a replay +cd openpilot/tools/replay && ./replay --demo --dcam --ecam + +# then start watch3 +cd openpilot/selfdrive/ui && ./watch3.py +``` + +![](https://i.imgur.com/IeaOdAb.png) + +## Stream CAN messages to your device + +Replay CAN messages as they were recorded using a [panda jungle](https://comma.ai/shop/products/panda-jungle). The jungle has 6x OBD-C ports for connecting all your comma devices. Check out the [jungle repo](https://github.com/commaai/panda_jungle) for more info. + +In order to run your device as if it was in a car: +* connect a panda jungle to your PC +* connect a comma device or panda to the jungle via OBD-C +* run `can_replay.py` + +``` bash +batman:replay$ ./can_replay.py -h +usage: can_replay.py [-h] [route_or_segment_name] + +Replay CAN messages from a route to all connected pandas and jungles +in a loop. + +positional arguments: + route_or_segment_name + The route or segment name to replay. If not + specified, a default public route will be + used. (default: None) + +optional arguments: + -h, --help show this help message and exit +``` diff --git a/openpilot/tools/replay/SConscript b/openpilot/tools/replay/SConscript new file mode 100644 index 0000000000..643de97bb9 --- /dev/null +++ b/openpilot/tools/replay/SConscript @@ -0,0 +1,19 @@ +Import('env', 'arch', 'common', 'messaging', 'visionipc', 'cereal', 'ffmpeg_libs') + +replay_env = env.Clone() +replay_env['CCFLAGS'] += ['-Wno-deprecated-declarations'] + +base_frameworks = ['VideoToolbox', 'CoreMedia', 'CoreFoundation', 'CoreVideo'] if arch == "Darwin" else [] +base_libs = [common, messaging, cereal, visionipc, 'm', 'pthread'] + +replay_lib_src = ["replay.cc", "consoleui.cc", "camera.cc", "filereader.cc", "logreader.cc", "framereader.cc", + "route.cc", "util.cc", "seg_mgr.cc", "timeline.cc", "py_downloader.cc"] +if arch != "Darwin": + replay_lib_src.append("qcom_decoder.cc") +replay_lib = replay_env.Library("replay", replay_lib_src, LIBS=base_libs, FRAMEWORKS=base_frameworks) +Export('replay_lib') +replay_libs = [replay_lib] + ffmpeg_libs + ['bz2', 'zstd', 'ncurses'] + base_libs +replay_env.Program("replay", ["main.cc"], LIBS=replay_libs, FRAMEWORKS=base_frameworks) + +if GetOption('extras'): + replay_env.Program('tests/test_replay', ['tests/test_replay.cc'], LIBS=replay_libs) diff --git a/openpilot/tools/replay/__init__.py b/openpilot/tools/replay/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/openpilot/tools/replay/camera.cc b/openpilot/tools/replay/camera.cc new file mode 100644 index 0000000000..671c0320bb --- /dev/null +++ b/openpilot/tools/replay/camera.cc @@ -0,0 +1,116 @@ +#include "tools/replay/camera.h" + +#include + +#include + +#include "system/camerad/cameras/nv12_info.h" +#include "tools/replay/util.h" + +const int BUFFER_COUNT = 40; + +CameraServer::CameraServer(std::pair camera_size[MAX_CAMERAS]) { + for (int i = 0; i < MAX_CAMERAS; ++i) { + std::tie(cameras_[i].width, cameras_[i].height) = camera_size[i]; + } + startVipcServer(); +} + +CameraServer::~CameraServer() { + for (auto &cam : cameras_) { + if (cam.thread.joinable()) { + // Clear the queue + std::pair item; + while (cam.queue.try_pop(item)) { + --publishing_; + } + + // Signal termination and join the thread + cam.queue.push({}); + cam.thread.join(); + } + } + vipc_server_.reset(nullptr); +} + +void CameraServer::startVipcServer() { + vipc_server_.reset(new VisionIpcServer("camerad")); + for (auto &cam : cameras_) { + cam.cached_buf.clear(); + + if (cam.width > 0 && cam.height > 0) { + rInfo("camera[%d] frame size %dx%d", cam.type, cam.width, cam.height); + auto [stride, y_height, uv_height_, buffer_size] = get_nv12_info(cam.width, cam.height); + (void)uv_height_; // unused in replay + vipc_server_->create_buffers_with_sizes(cam.stream_type, BUFFER_COUNT, cam.width, cam.height, + buffer_size, stride, stride * y_height); + if (!cam.thread.joinable()) { + cam.thread = std::thread(&CameraServer::cameraThread, this, std::ref(cam)); + } + } + } + vipc_server_->start_listener(); +} + +void CameraServer::cameraThread(Camera &cam) { + while (true) { + const auto [fr, event] = cam.queue.pop(); + if (!fr) break; + + capnp::FlatArrayMessageReader reader(event->data); + auto evt = reader.getRoot(); + auto eidx = capnp::AnyStruct::Reader(evt).getPointerSection()[0].getAs(); + + int segment_id = eidx.getSegmentId(); + uint32_t frame_id = eidx.getFrameId(); + if (auto yuv = getFrame(cam, fr, segment_id, frame_id)) { + VisionIpcBufExtra extra = { + .frame_id = frame_id, + .timestamp_sof = eidx.getTimestampSof(), + .timestamp_eof = eidx.getTimestampEof(), + }; + vipc_server_->send(yuv, &extra); + } else { + rError("camera[%d] failed to get frame: %lu", cam.type, segment_id); + } + + // Prefetch the next frame + getFrame(cam, fr, segment_id + 1, frame_id + 1); + + --publishing_; + } +} + +VisionBuf *CameraServer::getFrame(Camera &cam, FrameReader *fr, int32_t segment_id, uint32_t frame_id) { + // Check if the frame is cached + auto buf_it = std::find_if(cam.cached_buf.begin(), cam.cached_buf.end(), + [frame_id](VisionBuf *buf) { return buf->get_frame_id() == frame_id; }); + if (buf_it != cam.cached_buf.end()) return *buf_it; + + VisionBuf *yuv_buf = vipc_server_->get_buffer(cam.stream_type); + if (fr->get(segment_id, yuv_buf)) { + yuv_buf->set_frame_id(frame_id); + cam.cached_buf.insert(yuv_buf); + return yuv_buf; + } + return nullptr; +} + +void CameraServer::pushFrame(CameraType type, FrameReader *fr, const Event *event) { + auto &cam = cameras_[type]; + if (cam.width != fr->width || cam.height != fr->height) { + cam.width = fr->width; + cam.height = fr->height; + waitForSent(); + startVipcServer(); + } + + ++publishing_; + cam.queue.push({fr, event}); +} + +void CameraServer::waitForSent() { + while (publishing_ > 0) { + std::this_thread::yield(); + } +} diff --git a/openpilot/tools/replay/camera.h b/openpilot/tools/replay/camera.h new file mode 100644 index 0000000000..9433018848 --- /dev/null +++ b/openpilot/tools/replay/camera.h @@ -0,0 +1,41 @@ +#pragma once + +#include +#include +#include +#include + +#include "msgq/visionipc/visionipc_server.h" +#include "common/queue.h" +#include "tools/replay/framereader.h" +#include "tools/replay/logreader.h" + +class CameraServer { +public: + CameraServer(std::pair camera_size[MAX_CAMERAS] = nullptr); + ~CameraServer(); + void pushFrame(CameraType type, FrameReader* fr, const Event *event); + void waitForSent(); + +protected: + struct Camera { + CameraType type; + VisionStreamType stream_type; + int width; + int height; + std::thread thread; + SafeQueue> queue; + std::set cached_buf; + }; + void startVipcServer(); + void cameraThread(Camera &cam); + VisionBuf *getFrame(Camera &cam, FrameReader *fr, int32_t segment_id, uint32_t frame_id); + + Camera cameras_[MAX_CAMERAS] = { + {.type = RoadCam, .stream_type = VISION_STREAM_ROAD}, + {.type = DriverCam, .stream_type = VISION_STREAM_DRIVER}, + {.type = WideRoadCam, .stream_type = VISION_STREAM_WIDE_ROAD}, + }; + std::atomic publishing_ = 0; + std::unique_ptr vipc_server_; +}; diff --git a/tools/replay/can_replay.py b/openpilot/tools/replay/can_replay.py similarity index 98% rename from tools/replay/can_replay.py rename to openpilot/tools/replay/can_replay.py index 13c30a62ad..0717320077 100755 --- a/tools/replay/can_replay.py +++ b/openpilot/tools/replay/can_replay.py @@ -5,8 +5,6 @@ import time import usb1 import threading -os.environ['FILEREADER_CACHE'] = '1' - from openpilot.common.realtime import config_realtime_process, Ratekeeper, DT_CTRL from openpilot.selfdrive.pandad import can_capnp_to_list from openpilot.tools.lib.logreader import LogReader diff --git a/tools/replay/consoleui.cc b/openpilot/tools/replay/consoleui.cc similarity index 94% rename from tools/replay/consoleui.cc rename to openpilot/tools/replay/consoleui.cc index 871e41c273..eeb385f8a4 100644 --- a/tools/replay/consoleui.cc +++ b/openpilot/tools/replay/consoleui.cc @@ -9,6 +9,9 @@ #include "common/ratekeeper.h" #include "common/util.h" #include "common/version.h" +#include "tools/replay/py_downloader.h" + +#include "sunnypilot/common/version.h" namespace { @@ -115,16 +118,21 @@ void ConsoleUI::initWindows() { w[Win::Log] = newwin(log_height - 2, max_width - 2 * BORDER_SIZE, 18, BORDER_SIZE); scrollok(w[Win::Log], true); } - w[Win::Help] = newwin(5, max_width - (2 * BORDER_SIZE), max_height - 6, BORDER_SIZE); + if (max_height >= 23) { + w[Win::Help] = newwin(5, max_width - (2 * BORDER_SIZE), max_height - 6, BORDER_SIZE); + } else if (max_height >= 17) { + w[Win::Help] = newwin(1, max_width - (2 * BORDER_SIZE), max_height - 1, BORDER_SIZE); + mvwprintw(w[Win::Help], 0, 0, "Expand screen vertically to list available commands"); + } // set the title bar wbkgd(w[Win::Title], A_REVERSE); - mvwprintw(w[Win::Title], 0, 3, "sunnypilot replay %s", COMMA_VERSION); + mvwprintw(w[Win::Title], 0, 3, "sunnypilot replay %s", SUNNYPILOT_VERSION); // show windows on the real screen refresh(); displayTimelineDesc(); - displayHelp(); + if (max_height >= 23) displayHelp(); updateSummary(); updateTimeline(); for (auto win : w) { @@ -257,7 +265,7 @@ void ConsoleUI::updateTimeline() { if (entry.type == TimelineType::Engaged) { mvwchgat(win, 1, start_pos, end_pos - start_pos + 1, A_COLOR, Color::Engaged, NULL); mvwchgat(win, 2, start_pos, end_pos - start_pos + 1, A_COLOR, Color::Engaged, NULL); - } else if (entry.type == TimelineType::UserFlag) { + } else if (entry.type == TimelineType::UserBookmark) { mvwchgat(win, 3, start_pos, end_pos - start_pos + 1, ACS_S3, Color::Cyan, NULL); } else { auto color_id = Color::Green; @@ -329,7 +337,7 @@ void ConsoleUI::handleKey(char c) { } else if (c == 'd') { replay->seekToFlag(FindFlag::nextDisEngagement); } else if (c == 't') { - replay->seekToFlag(FindFlag::nextUserFlag); + replay->seekToFlag(FindFlag::nextUserBookmark); } else if (c == 'i') { replay->seekToFlag(FindFlag::nextInfo); } else if (c == 'w') { diff --git a/tools/replay/consoleui.h b/openpilot/tools/replay/consoleui.h similarity index 100% rename from tools/replay/consoleui.h rename to openpilot/tools/replay/consoleui.h diff --git a/openpilot/tools/replay/filereader.cc b/openpilot/tools/replay/filereader.cc new file mode 100644 index 0000000000..93a6a1193f --- /dev/null +++ b/openpilot/tools/replay/filereader.cc @@ -0,0 +1,14 @@ +#include "tools/replay/filereader.h" + +#include "common/util.h" +#include "tools/replay/py_downloader.h" + +std::string FileReader::read(const std::string &file, std::atomic *abort) { + const bool is_remote = (file.find("https://") == 0) || (file.find("http://") == 0); + if (is_remote) { + std::string local_path = PyDownloader::download(file, cache_to_local_, abort); + if (local_path.empty()) return {}; + return util::read_file(local_path); + } + return util::read_file(file); +} diff --git a/openpilot/tools/replay/filereader.h b/openpilot/tools/replay/filereader.h new file mode 100644 index 0000000000..30740cd0ac --- /dev/null +++ b/openpilot/tools/replay/filereader.h @@ -0,0 +1,14 @@ +#pragma once + +#include +#include + +class FileReader { +public: + FileReader(bool cache_to_local) : cache_to_local_(cache_to_local) {} + virtual ~FileReader() {} + std::string read(const std::string &file, std::atomic *abort = nullptr); + +private: + bool cache_to_local_; +}; diff --git a/openpilot/tools/replay/framereader.cc b/openpilot/tools/replay/framereader.cc new file mode 100644 index 0000000000..7c6f144148 --- /dev/null +++ b/openpilot/tools/replay/framereader.cc @@ -0,0 +1,313 @@ +#include "tools/replay/framereader.h" + +#include +#include +#include +#include + +#include "common/util.h" +#include "common/yuv.h" +#include "tools/replay/py_downloader.h" +#include "tools/replay/util.h" +#include "common/hardware/hw.h" + +#ifdef __APPLE__ +#define HW_DEVICE_TYPE AV_HWDEVICE_TYPE_VIDEOTOOLBOX +#define HW_PIX_FMT AV_PIX_FMT_VIDEOTOOLBOX +#else +#define HW_DEVICE_TYPE AV_HWDEVICE_TYPE_CUDA +#define HW_PIX_FMT AV_PIX_FMT_CUDA +#endif + +namespace { + +enum AVPixelFormat get_hw_format(AVCodecContext *ctx, const enum AVPixelFormat *pix_fmts) { + enum AVPixelFormat *hw_pix_fmt = reinterpret_cast(ctx->opaque); + for (const enum AVPixelFormat *p = pix_fmts; *p != -1; p++) { + if (*p == *hw_pix_fmt) return *p; + } + rWarning("Please run replay with the --no-hw-decoder flag!"); + *hw_pix_fmt = AV_PIX_FMT_NONE; + return AV_PIX_FMT_YUV420P; +} + +struct DecoderManager { + VideoDecoder *acquire(CameraType type, AVCodecParameters *codecpar, bool hw_decoder) { + auto key = std::tuple(type, codecpar->width, codecpar->height); + std::unique_lock lock(mutex_); + if (auto it = decoders_.find(key); it != decoders_.end()) { + return it->second.get(); + } + + std::unique_ptr decoder; + #ifndef __APPLE__ + if (!Hardware::PC() && hw_decoder) { + decoder = std::make_unique(); + } else + #endif + { + decoder = std::make_unique(); + } + + if (!decoder->open(codecpar, hw_decoder)) { + decoder.reset(nullptr); + } + decoders_[key] = std::move(decoder); + return decoders_[key].get(); + } + + std::mutex mutex_; + std::map, std::unique_ptr> decoders_; +}; + +DecoderManager decoder_manager; + +} // namespace + +FrameReader::FrameReader() { + av_log_set_level(AV_LOG_QUIET); +} + +FrameReader::~FrameReader() { + if (input_ctx) avformat_close_input(&input_ctx); +} + +bool FrameReader::load(CameraType type, const std::string &url, bool no_hw_decoder, std::atomic *abort, bool local_cache) { + std::string local_file_path; + if (url.find("https://") == 0 || url.find("http://") == 0) { + local_file_path = PyDownloader::download(url, local_cache, abort); + if (local_file_path.empty()) return false; + } else { + local_file_path = url; + } + return loadFromFile(type, local_file_path, no_hw_decoder, abort); +} + +bool FrameReader::loadFromFile(CameraType type, const std::string &file, bool no_hw_decoder, std::atomic *abort) { + if (avformat_open_input(&input_ctx, file.c_str(), nullptr, nullptr) != 0 || + avformat_find_stream_info(input_ctx, nullptr) < 0) { + rError("Failed to open input file or find video stream"); + return false; + } + input_ctx->probesize = 10 * 1024 * 1024; // 10MB + + video_stream_idx_ = av_find_best_stream(input_ctx, AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0); + if (video_stream_idx_ < 0) { + rError("No video stream found in file"); + return false; + } + + decoder_ = decoder_manager.acquire(type, input_ctx->streams[video_stream_idx_]->codecpar, !no_hw_decoder); + if (!decoder_) { + return false; + } + width = decoder_->width; + height = decoder_->height; + + AVPacket pkt; + packets_info.reserve(60 * 20); // 20fps, one minute + while (!(abort && *abort) && av_read_frame(input_ctx, &pkt) == 0) { + if (pkt.stream_index == video_stream_idx_) { + packets_info.emplace_back(PacketInfo{.flags = pkt.flags, .pos = pkt.pos}); + } + av_packet_unref(&pkt); + } + avio_seek(input_ctx->pb, 0, SEEK_SET); + return !packets_info.empty(); +} + +bool FrameReader::get(int idx, VisionBuf *buf) { + if (!buf || idx < 0 || idx >= packets_info.size()) { + return false; + } + return decoder_->decode(this, idx, buf); +} + +// class VideoDecoder + +FFmpegVideoDecoder::FFmpegVideoDecoder() { + av_frame_ = av_frame_alloc(); + hw_frame_ = av_frame_alloc(); +} + +FFmpegVideoDecoder::~FFmpegVideoDecoder() { + if (hw_device_ctx) av_buffer_unref(&hw_device_ctx); + if (decoder_ctx) avcodec_free_context(&decoder_ctx); + av_frame_free(&av_frame_); + av_frame_free(&hw_frame_); +} + +bool FFmpegVideoDecoder::open(AVCodecParameters *codecpar, bool hw_decoder) { + const AVCodec *decoder = avcodec_find_decoder(codecpar->codec_id); + if (!decoder) return false; + + decoder_ctx = avcodec_alloc_context3(decoder); + if (!decoder_ctx || avcodec_parameters_to_context(decoder_ctx, codecpar) != 0) { + rError("Failed to allocate or initialize codec context"); + return false; + } + width = (decoder_ctx->width + 3) & ~3; + height = decoder_ctx->height; + + if (hw_decoder && !initHardwareDecoder(HW_DEVICE_TYPE)) { + rWarning("No device with hardware decoder found. fallback to CPU decoding."); + } + + if (avcodec_open2(decoder_ctx, decoder, nullptr) < 0) { + rError("Failed to open codec"); + return false; + } + return true; +} + +bool FFmpegVideoDecoder::initHardwareDecoder(AVHWDeviceType hw_device_type) { + const AVCodecHWConfig *config = nullptr; + for (int i = 0; (config = avcodec_get_hw_config(decoder_ctx->codec, i)) != nullptr; i++) { + if (config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX && config->device_type == hw_device_type) { + hw_pix_fmt = config->pix_fmt; + break; + } + } + if (!config) { + rWarning("Hardware configuration not found"); + return false; + } + + int ret = av_hwdevice_ctx_create(&hw_device_ctx, hw_device_type, nullptr, nullptr, 0); + if (ret < 0) { + hw_pix_fmt = AV_PIX_FMT_NONE; + rWarning("Failed to create specified HW device %d.", ret); + return false; + } + + decoder_ctx->hw_device_ctx = av_buffer_ref(hw_device_ctx); + decoder_ctx->opaque = &hw_pix_fmt; + decoder_ctx->get_format = get_hw_format; + return true; +} + +bool FFmpegVideoDecoder::decode(FrameReader *reader, int idx, VisionBuf *buf) { + int current_idx = idx; + if (idx != reader->prev_idx + 1) { + // seeking to the nearest key frame + for (int i = idx; i >= 0; --i) { + if (reader->packets_info[i].flags & AV_PKT_FLAG_KEY) { + current_idx = i; + break; + } + } + + auto pos = reader->packets_info[current_idx].pos; + int ret = avformat_seek_file(reader->input_ctx, 0, pos, pos, pos, AVSEEK_FLAG_BYTE); + if (ret < 0) { + rError("Failed to seek to byte position %lld: %d", pos, AVERROR(ret)); + return false; + } + avcodec_flush_buffers(decoder_ctx); + } + reader->prev_idx = idx; + + AVPacket pkt; + while (av_read_frame(reader->input_ctx, &pkt) >= 0) { + // Skip non-video packets + if (pkt.stream_index != reader->video_stream_idx_) { + av_packet_unref(&pkt); + continue; + } + + AVFrame *frame = decodeFrame(&pkt); + av_packet_unref(&pkt); + if (!frame) { + rError("Failed to decode frame at index %d", current_idx); + return false; + } + + if (current_idx++ == idx) { + return copyBuffer(frame, buf); + } + } + rError("Failed to find frame at index %d", idx); + return false; +} + +AVFrame *FFmpegVideoDecoder::decodeFrame(AVPacket *pkt) { + int ret = avcodec_send_packet(decoder_ctx, pkt); + if (ret < 0) { + rError("Error sending a packet for decoding: %d", ret); + return nullptr; + } + + ret = avcodec_receive_frame(decoder_ctx, av_frame_); + if (ret != 0) { + rError("avcodec_receive_frame error: %d", ret); + return nullptr; + } + + if (av_frame_->format == hw_pix_fmt && av_hwframe_transfer_data(hw_frame_, av_frame_, 0) < 0) { + rError("error transferring frame data from GPU to CPU"); + return nullptr; + } + return (av_frame_->format == hw_pix_fmt) ? hw_frame_ : av_frame_; +} + +bool FFmpegVideoDecoder::copyBuffer(AVFrame *f, VisionBuf *buf) { + if (hw_pix_fmt == HW_PIX_FMT) { + for (int i = 0; i < height/2; i++) { + memcpy(buf->y + (i*2 + 0)*buf->stride, f->data[0] + (i*2 + 0)*f->linesize[0], width); + memcpy(buf->y + (i*2 + 1)*buf->stride, f->data[0] + (i*2 + 1)*f->linesize[0], width); + memcpy(buf->uv + i*buf->stride, f->data[1] + i*f->linesize[1], width); + } + } else { + yuv::i420_to_nv12(f->data[0], f->linesize[0], + f->data[1], f->linesize[1], + f->data[2], f->linesize[2], + buf->y, buf->stride, + buf->uv, buf->stride, + width, height); + } + return true; +} + +#ifndef __APPLE__ +bool QcomVideoDecoder::open(AVCodecParameters *codecpar, bool hw_decoder) { + if (codecpar->codec_id != AV_CODEC_ID_HEVC) { + rError("Hardware decoder only supports HEVC codec"); + return false; + } + width = codecpar->width; + height = codecpar->height; + msm_vidc.init(VIDEO_DEVICE, width, height, V4L2_PIX_FMT_HEVC); + return true; +} + +bool QcomVideoDecoder::decode(FrameReader *reader, int idx, VisionBuf *buf) { + int from_idx = idx; + if (idx != reader->prev_idx + 1) { + // seeking to the nearest key frame + for (int i = idx; i >= 0; --i) { + if (reader->packets_info[i].flags & AV_PKT_FLAG_KEY) { + from_idx = i; + break; + } + } + + auto pos = reader->packets_info[from_idx].pos; + int ret = avformat_seek_file(reader->input_ctx, 0, pos, pos, pos, AVSEEK_FLAG_BYTE); + if (ret < 0) { + rError("Failed to seek to byte position %lld: %d", pos, AVERROR(ret)); + return false; + } + } + reader->prev_idx = idx; + bool result = false; + AVPacket pkt; + msm_vidc.avctx = reader->input_ctx; + for (int i = from_idx; i <= idx; ++i) { + if (av_read_frame(reader->input_ctx, &pkt) == 0) { + result = msm_vidc.decodeFrame(&pkt, buf) && (i == idx); + av_packet_unref(&pkt); + } + } + return result; +} +#endif diff --git a/openpilot/tools/replay/framereader.h b/openpilot/tools/replay/framereader.h new file mode 100644 index 0000000000..3609d64f8b --- /dev/null +++ b/openpilot/tools/replay/framereader.h @@ -0,0 +1,80 @@ +#pragma once + +#include +#include + +#include "msgq/visionipc/visionbuf.h" +#include "tools/replay/util.h" + +#ifndef __APPLE__ +#include "tools/replay/qcom_decoder.h" +#endif + +extern "C" { +#include +#include +} + +class VideoDecoder; + +class FrameReader { +public: + FrameReader(); + ~FrameReader(); + bool load(CameraType type, const std::string &url, bool no_hw_decoder = false, std::atomic *abort = nullptr, bool local_cache = false); + bool loadFromFile(CameraType type, const std::string &file, bool no_hw_decoder = false, std::atomic *abort = nullptr); + bool get(int idx, VisionBuf *buf); + size_t getFrameCount() const { return packets_info.size(); } + + int width = 0, height = 0; + + VideoDecoder *decoder_ = nullptr; + AVFormatContext *input_ctx = nullptr; + int video_stream_idx_ = -1; + int prev_idx = -1; + struct PacketInfo { + int flags; + int64_t pos; + }; + std::vector packets_info; +}; + + +class VideoDecoder { +public: + virtual ~VideoDecoder() = default; + virtual bool open(AVCodecParameters *codecpar, bool hw_decoder) = 0; + virtual bool decode(FrameReader *reader, int idx, VisionBuf *buf) = 0; + int width = 0, height = 0; +}; + +class FFmpegVideoDecoder : public VideoDecoder { +public: + FFmpegVideoDecoder(); + ~FFmpegVideoDecoder() override; + bool open(AVCodecParameters *codecpar, bool hw_decoder) override; + bool decode(FrameReader *reader, int idx, VisionBuf *buf) override; + +private: + bool initHardwareDecoder(AVHWDeviceType hw_device_type); + AVFrame *decodeFrame(AVPacket *pkt); + bool copyBuffer(AVFrame *f, VisionBuf *buf); + + AVFrame *av_frame_, *hw_frame_; + AVCodecContext *decoder_ctx = nullptr; + AVPixelFormat hw_pix_fmt = AV_PIX_FMT_NONE; + AVBufferRef *hw_device_ctx = nullptr; +}; + +#ifndef __APPLE__ +class QcomVideoDecoder : public VideoDecoder { +public: + QcomVideoDecoder() {}; + ~QcomVideoDecoder() override {}; + bool open(AVCodecParameters *codecpar, bool hw_decoder) override; + bool decode(FrameReader *reader, int idx, VisionBuf *buf) override; + +private: + MsmVidc msm_vidc = MsmVidc(); +}; +#endif diff --git a/openpilot/tools/replay/lib/__init__.py b/openpilot/tools/replay/lib/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/openpilot/tools/replay/lib/ui_helpers.py b/openpilot/tools/replay/lib/ui_helpers.py new file mode 100644 index 0000000000..b9da0d225f --- /dev/null +++ b/openpilot/tools/replay/lib/ui_helpers.py @@ -0,0 +1,221 @@ +import itertools + +import matplotlib.pyplot as plt +import numpy as np +import pyray as rl + +from matplotlib.backends.backend_agg import FigureCanvasAgg +from matplotlib.artist import Artist +from matplotlib.offsetbox import AnchoredOffsetbox, HPacker, TextArea + +from openpilot.common.transformations.camera import get_view_frame_from_calib_frame +from openpilot.selfdrive.controls.radard import RADAR_TO_CAMERA + + +RED = (255, 0, 0) +GREEN = (0, 255, 0) +BLUE = (0, 0, 255) +YELLOW = (255, 255, 0) +BLACK = (0, 0, 0) +WHITE = (255, 255, 255) + + +class UIParams: + lidar_x, lidar_y, lidar_zoom = 384, 960, 6 + lidar_car_x, lidar_car_y = lidar_x / 2.0, lidar_y / 1.1 + car_hwidth = 1.7272 / 2 * lidar_zoom + car_front = 2.6924 * lidar_zoom + car_back = 1.8796 * lidar_zoom + car_color = 110 + + +UP = UIParams + +METER_WIDTH = 20 + + +class Calibration: + def __init__(self, num_px, rpy, intrinsic, calib_scale): + self.intrinsic = intrinsic + self.extrinsics_matrix = get_view_frame_from_calib_frame(rpy[0], rpy[1], rpy[2], 0.0)[:, :3] + self.zoom = calib_scale + + def car_space_to_ff(self, x, y, z): + car_space_projective = np.column_stack((x, y, z)).T + + ep = self.extrinsics_matrix.dot(car_space_projective) + kep = self.intrinsic.dot(ep) + return (kep[:-1, :] / kep[-1, :]).T + + def car_space_to_bb(self, x, y, z): + pts = self.car_space_to_ff(x, y, z) + return pts / self.zoom + + +_COLOR_CACHE: dict[tuple[int, int, int], int] = { + (255, 0, 0): 1, # RED + (0, 255, 0): 2, # GREEN + (0, 0, 255): 3, # BLUE + (255, 255, 0): 4, # YELLOW + (0, 0, 0): 0, # BLACK + (255, 255, 255): 255, # WHITE +} + + +def find_color(lidar_surface, color): + return _COLOR_CACHE.get(color, 255) + + +def to_topdown_pt(y, x): + px, py = x * UP.lidar_zoom + UP.lidar_car_x, -y * UP.lidar_zoom + UP.lidar_car_y + if px > 0 and py > 0 and px < UP.lidar_x and py < UP.lidar_y: + return int(px), int(py) + return -1, -1 + + +def draw_path(path, color, img, calibration, top_down, lid_color=None, z_off=0): + x, y, z = np.asarray(path.x), np.asarray(path.y), np.asarray(path.z) + z_off + pts = calibration.car_space_to_bb(x, y, z) + pts = np.round(pts).astype(int) + + # draw lidar path point on lidar + # find color in 8 bit + if lid_color is not None and top_down is not None: + tcolor = find_color(top_down[0], lid_color) + for i in range(len(x)): + px, py = to_topdown_pt(x[i], y[i]) + if px != -1: + top_down[1][px, py] = tcolor + + height, width = img.shape[:2] + for x, y in pts: + if 1 < x < width - 1 and 1 < y < height - 1: + for a, b in itertools.permutations([-1, 0, -1], 2): + img[y + a, x + b] = color + + +def init_plots(arr, name_to_arr_idx, plot_xlims, plot_ylims, plot_names, plot_colors, plot_styles): + color_palette = {"r": (1, 0, 0), "g": (0, 1, 0), "b": (0, 0, 1), "k": (0, 0, 0), "y": (1, 1, 0), "p": (0, 1, 1), "m": (1, 0, 1)} + label_palette = {**color_palette, "b": (43/255, 114/255, 1.0)} + + dpi = 90 + fig = plt.figure(figsize=(575 / dpi, 600 / dpi), dpi=dpi) + canvas = FigureCanvasAgg(fig) + + fig.set_facecolor((0.2, 0.2, 0.2)) + + axs = [] + for pn in range(len(plot_ylims)): + ax = fig.add_subplot(len(plot_ylims), 1, len(axs) + 1) + ax.set_xlim(plot_xlims[pn][0], plot_xlims[pn][1]) + ax.set_ylim(plot_ylims[pn][0], plot_ylims[pn][1]) + ax.patch.set_facecolor((0.4, 0.4, 0.4)) + axs.append(ax) + + plots, idxs, plot_select = [], [], [] + for i, pl_list in enumerate(plot_names): + for j, item in enumerate(pl_list): + (plot,) = axs[i].plot(arr[:, name_to_arr_idx[item]], label=item, color=color_palette[plot_colors[i][j]], linestyle=plot_styles[i][j]) + plots.append(plot) + idxs.append(name_to_arr_idx[item]) + plot_select.append(i) + # Build colored title: each label colored to match its plot line + title_texts: list[Artist] = [] + for j2, (nm, cl) in enumerate(zip(pl_list, plot_colors[i], strict=False)): + if j2 > 0: + title_texts.append(TextArea(", ", textprops={"color": "white", "fontsize": 10})) + title_texts.append(TextArea(nm, textprops={"color": label_palette[cl], "fontsize": 10})) + packed = HPacker(children=title_texts, pad=0, sep=0) + ab = AnchoredOffsetbox(loc='lower center', child=packed, bbox_to_anchor=(0.5, 1.0), + bbox_transform=axs[i].transAxes, frameon=False, pad=0) + axs[i].add_artist(ab) + axs[i].tick_params(axis="x", colors="white") + axs[i].tick_params(axis="y", colors="white") + + if i < len(plot_ylims) - 1: + axs[i].set_xticks([]) + + canvas.draw() + + # Pre-create texture for plots (reuse each frame to avoid log spam) + w, h = canvas.get_width_height() + plot_image = rl.gen_image_color(w, h, rl.BLACK) + plot_texture = rl.load_texture_from_image(plot_image) + rl.unload_image(plot_image) + + def draw_plots(arr): + for ax in axs: + ax.draw_artist(ax.patch) + for i in range(len(plots)): + plots[i].set_ydata(arr[:, idxs[i]]) + axs[plot_select[i]].draw_artist(plots[i]) + + raw_data = np.ascontiguousarray(canvas.buffer_rgba(), dtype=np.uint8) + rl.update_texture(plot_texture, rl.ffi.cast("void *", raw_data.ctypes.data)) + return plot_texture + + return draw_plots + + +def plot_model(m, img, calibration, top_down): + if calibration is None or top_down is None: + return + + for lead in m.leadsV3: + if lead.prob < 0.5: + continue + + x, y = lead.x[0], lead.y[0] + x_std = lead.xStd[0] + x -= RADAR_TO_CAMERA + + _, py_top = to_topdown_pt(x + x_std, y) + px, py_bottom = to_topdown_pt(x - x_std, y) + top_down[1][int(round(px - 4)) : int(round(px + 4)), py_top:py_bottom] = find_color(top_down[0], YELLOW) + + for path, prob, _ in zip(m.laneLines, m.laneLineProbs, m.laneLineStds, strict=True): + color = (0, int(255 * prob), 0) + draw_path(path, color, img, calibration, top_down, YELLOW) + + for edge, std in zip(m.roadEdges, m.roadEdgeStds, strict=True): + prob = max(1 - std, 0) + color = (int(255 * prob), 0, 0) + draw_path(edge, color, img, calibration, top_down, RED) + + color = (255, 0, 0) + draw_path(m.position, color, img, calibration, top_down, RED, 1.22) + + +def plot_lead(rs, top_down): + for lead in [rs.leadOne, rs.leadTwo]: + if not lead.present: + continue + + x = lead.dRel + px_left, py = to_topdown_pt(x, -10) + px_right, _ = to_topdown_pt(x, 10) + top_down[1][px_left:px_right, py] = find_color(top_down[0], RED) + + +def maybe_update_radar_points(lt, lid_overlay): + ar_pts = [] + if lt is not None: + ar_pts = {} + for track in lt: + ar_pts[track.trackId] = [track.dRel, track.yRel, track.vRel] + for pt in ar_pts.values(): + # negative here since radar is left positive + px, py = to_topdown_pt(pt[0], -pt[1]) + if px != -1: + lid_overlay[px - 4 : px + 4, py - 4 : py + 4] = 0 + lid_overlay[px - 2 : px + 2, py - 2 : py + 2] = 255 + + +def get_blank_lid_overlay(UP): + lid_overlay = np.zeros((UP.lidar_x, UP.lidar_y), 'uint8') + # Draw the car. + lid_overlay[int(round(UP.lidar_car_x - UP.car_hwidth)) : int(round(UP.lidar_car_x + UP.car_hwidth)), int(round(UP.lidar_car_y - UP.car_front))] = UP.car_color + lid_overlay[int(round(UP.lidar_car_x - UP.car_hwidth)) : int(round(UP.lidar_car_x + UP.car_hwidth)), int(round(UP.lidar_car_y + UP.car_back))] = UP.car_color + lid_overlay[int(round(UP.lidar_car_x - UP.car_hwidth)), int(round(UP.lidar_car_y - UP.car_front)) : int(round(UP.lidar_car_y + UP.car_back))] = UP.car_color + lid_overlay[int(round(UP.lidar_car_x + UP.car_hwidth)), int(round(UP.lidar_car_y - UP.car_front)) : int(round(UP.lidar_car_y + UP.car_back))] = UP.car_color + return lid_overlay diff --git a/openpilot/tools/replay/logreader.cc b/openpilot/tools/replay/logreader.cc new file mode 100644 index 0000000000..54b69dc168 --- /dev/null +++ b/openpilot/tools/replay/logreader.cc @@ -0,0 +1,169 @@ +#include "tools/replay/logreader.h" + +#include +#include +#include +#include "tools/replay/filereader.h" +#include "tools/replay/py_downloader.h" +#include "tools/replay/util.h" +#include "common/util.h" + +bool LogReader::load(const std::string &url, std::atomic *abort, bool local_cache, + const ProgressCallback &progress) { + using Clock = std::chrono::steady_clock; + compressed_size_ = 0; + decompressed_size_ = 0; + download_seconds_ = 0.0; + decompress_seconds_ = 0.0; + parse_seconds_ = 0.0; + + if (progress) { + installDownloadProgressHandler([progress](uint64_t cur, uint64_t total, bool success) { + if (success) { + progress(ProgressStage::Downloading, cur, total); + } + }); + } + const auto download_start = Clock::now(); + std::string data = FileReader(local_cache).read(url, abort); + const auto download_end = Clock::now(); + if (progress) { + installDownloadProgressHandler(nullptr); + } + compressed_size_ = data.size(); + download_seconds_ = std::chrono::duration(download_end - download_start).count(); + if (!data.empty()) { + const auto decompress_start = Clock::now(); + if (url.find(".bz2") != std::string::npos || util::starts_with(data, "BZh9")) { + data = decompressBZ2(data, abort); + } else if (url.find(".zst") != std::string::npos || util::starts_with(data, "\x28\xB5\x2F\xFD")) { + data = decompressZST(data, abort); + } + const auto decompress_end = Clock::now(); + decompress_seconds_ = std::chrono::duration(decompress_end - decompress_start).count(); + } + decompressed_size_ = data.size(); + + bool success = !data.empty() && load(data.data(), data.size(), abort, progress); + if (filters_.empty()) + raw_ = std::move(data); + return success; +} + +bool LogReader::load(const char *data, size_t size, std::atomic *abort, + const ProgressCallback &progress) { + using Clock = std::chrono::steady_clock; + const auto parse_start = Clock::now(); + try { + events.reserve(65000); + kj::ArrayPtr words((const capnp::word *)data, size / sizeof(capnp::word)); + const uint64_t total_bytes = size; + const uint64_t report_step = std::max(1, total_bytes / 200); + uint64_t last_reported = 0; + if (progress) { + progress(ProgressStage::Parsing, 0, total_bytes); + } + while (words.size() > 0 && !(abort && *abort)) { + capnp::FlatArrayMessageReader reader(words); + auto event = reader.getRoot(); + auto which = event.which(); + auto event_data = kj::arrayPtr(words.begin(), reader.getEnd()); + words = kj::arrayPtr(reader.getEnd(), words.end()); + if (which == cereal::Event::Which::SELFDRIVE_STATE) { + requires_migration = false; + } + + if (!filters_.empty()) { + if (which >= filters_.size() || !filters_[which]) + continue; + auto buf = buffer_.allocate(event_data.size() * sizeof(capnp::word)); + memcpy(buf, event_data.begin(), event_data.size() * sizeof(capnp::word)); + event_data = kj::arrayPtr((const capnp::word *)buf, event_data.size()); + } + + uint64_t mono_time = event.getLogMonoTime(); + const Event &evt = events.emplace_back(which, mono_time, event_data); + // Add encodeIdx packet again as a frame packet for the video stream + if (evt.which == cereal::Event::ROAD_ENCODE_IDX || + evt.which == cereal::Event::DRIVER_ENCODE_IDX || + evt.which == cereal::Event::WIDE_ROAD_ENCODE_IDX) { + auto idx = capnp::AnyStruct::Reader(event).getPointerSection()[0].getAs(); + if (idx.getType() == cereal::EncodeIndex::Type::FULL_H_E_V_C) { + uint64_t sof = idx.getTimestampSof(); + events.emplace_back(which, sof ? sof : mono_time, event_data, idx.getSegmentNum()); + } + } + + if (progress) { + const uint64_t current_bytes = + total_bytes - static_cast(words.size() * sizeof(capnp::word)); + if (current_bytes >= total_bytes || current_bytes - last_reported >= report_step) { + progress(ProgressStage::Parsing, current_bytes, total_bytes); + last_reported = current_bytes; + } + } + } + } catch (const kj::Exception &e) { + rWarning("Failed to parse log : %s.\nRetrieved %zu events from corrupt log", e.getDescription().cStr(), events.size()); + } + + if (progress) { + progress(ProgressStage::Parsing, size, size); + } + + if (requires_migration) { + migrateOldEvents(); + } + + parse_seconds_ = std::chrono::duration(Clock::now() - parse_start).count(); + + if (!events.empty() && !(abort && *abort)) { + events.shrink_to_fit(); + std::sort(events.begin(), events.end()); + return true; + } + return false; +} + +void LogReader::migrateOldEvents() { + size_t events_size = events.size(); + for (int i = 0; i < events_size; ++i) { + // Check if the event is of the old CONTROLS_STATE type + auto &event = events[i]; + if (event.which == cereal::Event::CONTROLS_STATE) { + // Read the old event data + capnp::FlatArrayMessageReader reader(event.data); + auto old_evt = reader.getRoot(); + auto old_state = old_evt.getControlsState(); + + // Migrate relevant fields from old CONTROLS_STATE to new SelfdriveState + MessageBuilder msg; + auto new_evt = msg.initEvent(old_evt.getValid()); + new_evt.setLogMonoTime(old_evt.getLogMonoTime()); + auto new_state = new_evt.initSelfdriveState(); + + auto old_dep = old_state.getDeprecated(); + new_state.setActive(old_dep.getActive()); + new_state.setAlertSize(old_dep.getAlertSize()); + new_state.setAlertSound(old_dep.getAlertSound2()); + new_state.setAlertStatus(old_dep.getAlertStatus()); + new_state.setAlertText1(old_dep.getAlertText1()); + new_state.setAlertText2(old_dep.getAlertText2()); + new_state.setAlertType(old_dep.getAlertType()); + new_state.setEnabled(old_dep.getEnabled()); + new_state.setEngageable(old_dep.getEngageable()); + new_state.setExperimentalMode(old_dep.getExperimentalMode()); + new_state.setPersonality(old_dep.getPersonality()); + new_state.setState(old_dep.getState()); + + // Serialize the new event to the buffer + auto buf_size = msg.getSerializedSize(); + auto buf = buffer_.allocate(buf_size); + msg.serializeToBuffer(reinterpret_cast(buf), buf_size); + + // Store the migrated event in the events list + auto event_data = kj::arrayPtr(reinterpret_cast(buf), buf_size); + events.emplace_back(new_evt.which(), new_evt.getLogMonoTime(), event_data); + } + } +} diff --git a/openpilot/tools/replay/logreader.h b/openpilot/tools/replay/logreader.h new file mode 100644 index 0000000000..63f7468401 --- /dev/null +++ b/openpilot/tools/replay/logreader.h @@ -0,0 +1,63 @@ +#pragma once + +#include +#include +#include +#include + +#include "openpilot/cereal/gen/cpp/log.capnp.h" +#include "tools/replay/util.h" + +const CameraType ALL_CAMERAS[] = {RoadCam, DriverCam, WideRoadCam}; +const int MAX_CAMERAS = std::size(ALL_CAMERAS); + +class Event { +public: + Event(cereal::Event::Which which, uint64_t mono_time, const kj::ArrayPtr &data, int eidx_segnum = -1) + : which(which), mono_time(mono_time), data(data), eidx_segnum(eidx_segnum) {} + + bool operator<(const Event &other) const { + return mono_time < other.mono_time || (mono_time == other.mono_time && which < other.which); + } + + uint64_t mono_time; + cereal::Event::Which which; + kj::ArrayPtr data; + int32_t eidx_segnum; +}; + +class LogReader { +public: + enum class ProgressStage { + Downloading, + Parsing, + }; + + using ProgressCallback = std::function; + + LogReader(const std::vector &filters = {}) { filters_ = filters; } + bool load(const std::string &url, std::atomic *abort = nullptr, + bool local_cache = false, const ProgressCallback &progress = {}); + bool load(const char *data, size_t size, std::atomic *abort = nullptr, + const ProgressCallback &progress = {}); + std::vector events; + + uint64_t compressed_size() const { return compressed_size_; } + uint64_t decompressed_size() const { return decompressed_size_; } + double download_seconds() const { return download_seconds_; } + double decompress_seconds() const { return decompress_seconds_; } + double parse_seconds() const { return parse_seconds_; } + +private: + void migrateOldEvents(); + + std::string raw_; + bool requires_migration = true; + std::vector filters_; + MonotonicBuffer buffer_{1024 * 1024}; + uint64_t compressed_size_ = 0; + uint64_t decompressed_size_ = 0; + double download_seconds_ = 0.0; + double decompress_seconds_ = 0.0; + double parse_seconds_ = 0.0; +}; diff --git a/openpilot/tools/replay/main.cc b/openpilot/tools/replay/main.cc new file mode 100644 index 0000000000..bdb9cf4f35 --- /dev/null +++ b/openpilot/tools/replay/main.cc @@ -0,0 +1,187 @@ +#include + +#include +#include +#include +#include +#include +#include + +#include "common/prefix.h" +#include "common/timing.h" +#include "tools/replay/consoleui.h" +#include "tools/replay/replay.h" +#include "tools/replay/util.h" + +const std::string helpText = +R"(Usage: replay [options] [route] +Options: + -a, --allow Whitelist of services to send (comma-separated) + -b, --block Blacklist of services to send (comma-separated) + -c, --cache Cache segments in memory. Default is 5 + -s, --start Start from + -x, --playback Playback + --demo Use a demo route instead of providing your own + --auto Auto load the route from the best available source (no video): + internal, openpilotci, comma_api, car_segments, testing_closet + -d, --data_dir Local directory with routes + -p, --prefix Set OPENPILOT_PREFIX + --dcam Load driver camera + --ecam Load wide road camera + --no-loop Stop at the end of the route + --no-cache Turn off local cache + --qcam Load qcamera + --no-hw-decoder Disable HW video decoding + --no-vipc Do not output video + --all Output all messages including bookmarkButton, uiDebug, userBookmark + --benchmark Run in benchmark mode (process all events then exit with stats) + -h, --help Show this help message +)"; + +struct ReplayConfig { + std::string route; + std::vector allow; + std::vector block; + std::string data_dir; + std::string prefix; + uint32_t flags = REPLAY_FLAG_NONE; + bool auto_source = false; + int start_seconds = 0; + int cache_segments = -1; + float playback_speed = -1; +}; + +bool parseArgs(int argc, char *argv[], ReplayConfig &config) { + const struct option cli_options[] = { + {"allow", required_argument, nullptr, 'a'}, + {"block", required_argument, nullptr, 'b'}, + {"cache", required_argument, nullptr, 'c'}, + {"start", required_argument, nullptr, 's'}, + {"playback", required_argument, nullptr, 'x'}, + {"demo", no_argument, nullptr, 0}, + {"auto", no_argument, nullptr, 0}, + {"data_dir", required_argument, nullptr, 'd'}, + {"prefix", required_argument, nullptr, 'p'}, + {"dcam", no_argument, nullptr, 0}, + {"ecam", no_argument, nullptr, 0}, + {"no-loop", no_argument, nullptr, 0}, + {"no-cache", no_argument, nullptr, 0}, + {"qcam", no_argument, nullptr, 0}, + {"no-hw-decoder", no_argument, nullptr, 0}, + {"no-vipc", no_argument, nullptr, 0}, + {"all", no_argument, nullptr, 0}, + {"benchmark", no_argument, nullptr, 0}, + {"help", no_argument, nullptr, 'h'}, + {nullptr, 0, nullptr, 0}, // Terminating entry + }; + + const std::map flag_map = { + {"dcam", REPLAY_FLAG_DCAM}, + {"ecam", REPLAY_FLAG_ECAM}, + {"no-loop", REPLAY_FLAG_NO_LOOP}, + {"no-cache", REPLAY_FLAG_NO_FILE_CACHE}, + {"qcam", REPLAY_FLAG_QCAMERA}, + {"no-hw-decoder", REPLAY_FLAG_NO_HW_DECODER}, + {"no-vipc", REPLAY_FLAG_NO_VIPC}, + {"all", REPLAY_FLAG_ALL_SERVICES}, + {"benchmark", REPLAY_FLAG_BENCHMARK}, + }; + + if (argc == 1) { + std::cout << helpText; + return false; + } + + int opt, option_index = 0; + while ((opt = getopt_long(argc, argv, "a:b:c:s:x:d:p:h", cli_options, &option_index)) != -1) { + switch (opt) { + case 'a': config.allow = split(optarg, ','); break; + case 'b': config.block = split(optarg, ','); break; + case 'c': config.cache_segments = std::atoi(optarg); break; + case 's': config.start_seconds = std::atoi(optarg); break; + case 'x': config.playback_speed = std::atof(optarg); break; + case 'd': config.data_dir = optarg; break; + case 'p': config.prefix = optarg; break; + case 0: { + std::string name = cli_options[option_index].name; + if (name == "demo") config.route = DEMO_ROUTE; + else if (name == "auto") config.auto_source = true; + else config.flags |= flag_map.at(name); + break; + } + case 'h': std::cout << helpText; return false; + default: return false; + } + } + + // Check for a route name (first positional argument) + if (config.route.empty() && optind < argc) { + config.route = argv[optind]; + } + + if (config.route.empty()) { + std::cerr << "No route provided. Use --help for usage information.\n"; + return false; + } + + return true; +} + +int main(int argc, char *argv[]) { +#ifdef __APPLE__ + // With all sockets opened, we might hit the default limit of 256 on macOS + util::set_file_descriptor_limit(1024); +#endif + + // The vendored ncurses static library has a wrong compiled-in terminfo path. + // Point it at the system terminfo database if not already set. + setenv("TERMINFO_DIRS", "/usr/share/terminfo:/lib/terminfo:/usr/lib/terminfo", 0); + + ReplayConfig config; + + if (!parseArgs(argc, argv, config)) { + return 1; + } + + std::unique_ptr op_prefix; + if (!config.prefix.empty()) { + op_prefix = std::make_unique(config.prefix); + } + + Replay replay(config.route, config.allow, config.block, nullptr, config.flags, config.data_dir, config.auto_source); + if (config.cache_segments > 0) { + replay.setSegmentCacheLimit(config.cache_segments); + } + if (config.playback_speed > 0) { + replay.setSpeed(std::clamp(config.playback_speed, ConsoleUI::speed_array.front(), ConsoleUI::speed_array.back())); + } + if (!replay.load()) { + return 1; + } + + if (config.flags & REPLAY_FLAG_BENCHMARK) { + replay.start(config.start_seconds); + replay.waitForFinished(); + + const auto &stats = replay.getBenchmarkStats(); + uint64_t process_start = stats.process_start_ts; + + std::cout << "\n===== REPLAY BENCHMARK RESULTS =====\n"; + std::cout << "Route: " << replay.route().name() << "\n\n"; + + std::cout << "TIMELINE:\n"; + std::cout << " t=0 ms process start\n"; + for (const auto &[ts, event] : stats.timeline) { + double ms = (ts - process_start) / 1e6; + std::cout << " t=" << std::fixed << std::setprecision(0) << ms << " ms" + << std::string(std::max(1, 8 - static_cast(std::to_string(static_cast(ms)).length())), ' ') + << event << "\n"; + } + + return 0; + } + + ConsoleUI console_ui(&replay); + replay.start(config.start_seconds); + return console_ui.exec(); +} diff --git a/openpilot/tools/replay/py_downloader.cc b/openpilot/tools/replay/py_downloader.cc new file mode 100644 index 0000000000..d27a77e6ee --- /dev/null +++ b/openpilot/tools/replay/py_downloader.cc @@ -0,0 +1,180 @@ +#include "tools/replay/py_downloader.h" + +#include +#include +#include +#include +#include +#include + +#include "tools/replay/util.h" + +namespace { + +static std::mutex handler_mutex; +static DownloadProgressHandler progress_handler = nullptr; + +// Run a Python command and capture stdout. Stderr is left attached to the parent. +// Returns stdout content. If abort is signaled, kills the child process. +std::string runPython(const std::vector &args, std::atomic *abort = nullptr) { + // Build argv for execvp + std::vector argv; + argv.push_back("python3"); + argv.push_back("-m"); + argv.push_back("openpilot.tools.lib.file_downloader"); + for (const auto &a : args) { + argv.push_back(a.c_str()); + } + argv.push_back(nullptr); + + int stdout_pipe[2]; + if (pipe(stdout_pipe) != 0) { + rWarning("py_downloader: pipe() failed"); + return {}; + } + + pid_t pid = fork(); + if (pid < 0) { + rWarning("py_downloader: fork() failed"); + close(stdout_pipe[0]); close(stdout_pipe[1]); + return {}; + } + + if (pid == 0) { + // Child process — detach from controlling terminal so Python + // cannot corrupt terminal settings needed by ncurses in the parent. + setsid(); + int devnull = open("/dev/null", O_RDONLY); + if (devnull >= 0) { + dup2(devnull, STDIN_FILENO); + if (devnull > STDERR_FILENO) close(devnull); + } + + // Clear OPENPILOT_PREFIX so the Python process uses default paths + // (e.g. ~/.comma/auth.json). The prefix is only for IPC in the parent. + unsetenv("OPENPILOT_PREFIX"); + + close(stdout_pipe[0]); + dup2(stdout_pipe[1], STDOUT_FILENO); + close(stdout_pipe[1]); + + execvp("python3", const_cast(argv.data())); + _exit(127); + } + + // Parent process + close(stdout_pipe[1]); + + std::string stdout_data; + char buf[4096]; + + // Use select() so abort can interrupt while waiting for Python output. + fd_set rfds; + bool stdout_open = true; + + while (stdout_open) { + if (abort && *abort) { + kill(pid, SIGTERM); + break; + } + + FD_ZERO(&rfds); + FD_SET(stdout_pipe[0], &rfds); + + struct timeval tv = {0, 100000}; // 100ms timeout + int ret = select(stdout_pipe[0] + 1, &rfds, nullptr, nullptr, &tv); + if (ret < 0) break; + + if (FD_ISSET(stdout_pipe[0], &rfds)) { + ssize_t n = read(stdout_pipe[0], buf, sizeof(buf)); + if (n <= 0) { + stdout_open = false; + } else { + stdout_data.append(buf, n); + } + } + } + + // Drain remaining pipe data to prevent child from blocking on write + while (true) { + ssize_t n = read(stdout_pipe[0], buf, sizeof(buf)); + if (n <= 0) break; + stdout_data.append(buf, n); + } + close(stdout_pipe[0]); + + int status; + waitpid(pid, &status, 0); + + const bool aborted = abort && *abort; + const bool expected_sigterm = aborted && WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM; + bool failed = aborted || + (WIFEXITED(status) && WEXITSTATUS(status) != 0) || + WIFSIGNALED(status); + if (failed) { + if (expected_sigterm) { + // Route/camera teardown cancels outstanding downloader subprocesses. + // Keep that expected shutdown path quiet. + } else if (WIFEXITED(status) && WEXITSTATUS(status) != 0) { + rWarning("py_downloader: process exited with code %d", WEXITSTATUS(status)); + } else if (WIFSIGNALED(status)) { + rWarning("py_downloader: process killed by signal %d", WTERMSIG(status)); + } + std::lock_guard lk(handler_mutex); + if (progress_handler) { + progress_handler(0, 0, false); + } + return {}; + } + + // Trim trailing newline + while (!stdout_data.empty() && (stdout_data.back() == '\n' || stdout_data.back() == '\r')) { + stdout_data.pop_back(); + } + + return stdout_data; +} + +} // namespace + +void installDownloadProgressHandler(DownloadProgressHandler handler) { + std::lock_guard lk(handler_mutex); + progress_handler = handler; +} + +namespace PyDownloader { + +std::string download(const std::string &url, bool use_cache, std::atomic *abort) { + std::vector args = {"download", url}; + if (!use_cache) { + args.push_back("--no-cache"); + } + return runPython(args, abort); +} + +std::string getRouteFiles(const std::string &route) { + return runPython({"route-files", route}); +} + +std::string getDevices() { + return runPython({"devices"}); +} + +std::string getDeviceRoutes(const std::string &dongle_id, int64_t start_ms, int64_t end_ms, bool preserved) { + std::vector args = {"device-routes", dongle_id}; + if (preserved) { + args.push_back("--preserved"); + } else { + if (start_ms > 0) { + args.push_back("--start"); + args.push_back(std::to_string(start_ms)); + } + if (end_ms > 0) { + args.push_back("--end"); + args.push_back(std::to_string(end_ms)); + } + } + return runPython(args); +} + +} // namespace PyDownloader diff --git a/openpilot/tools/replay/py_downloader.h b/openpilot/tools/replay/py_downloader.h new file mode 100644 index 0000000000..535189784c --- /dev/null +++ b/openpilot/tools/replay/py_downloader.h @@ -0,0 +1,24 @@ +#pragma once + +#include +#include +#include + +typedef std::function DownloadProgressHandler; +void installDownloadProgressHandler(DownloadProgressHandler handler); + +namespace PyDownloader { + +// Downloads url to local cache, returns local file path. Reports progress via installDownloadProgressHandler. +std::string download(const std::string &url, bool use_cache = true, std::atomic *abort = nullptr); + +// Returns JSON string of route files (same format as /v1/route/.../files API) +std::string getRouteFiles(const std::string &route); + +// Returns JSON string of user's devices +std::string getDevices(); + +// Returns JSON string of device routes +std::string getDeviceRoutes(const std::string &dongle_id, int64_t start_ms = 0, int64_t end_ms = 0, bool preserved = false); + +} // namespace PyDownloader diff --git a/openpilot/tools/replay/qcom_decoder.cc b/openpilot/tools/replay/qcom_decoder.cc new file mode 100644 index 0000000000..b7f04a063b --- /dev/null +++ b/openpilot/tools/replay/qcom_decoder.cc @@ -0,0 +1,346 @@ +#include "qcom_decoder.h" + +#include +#include +#include + + +#include "common/swaglog.h" +#include "common/util.h" + +// echo "0xFFFF" > /sys/kernel/debug/msm_vidc/debug_level + +static void copyBuffer(VisionBuf *src_buf, VisionBuf *dst_buf) { + // Copy Y plane + memcpy(dst_buf->y, src_buf->y, src_buf->height * src_buf->stride); + // Copy UV plane + memcpy(dst_buf->uv, src_buf->uv, src_buf->height / 2 * src_buf->stride); +} + +static void request_buffers(int fd, v4l2_buf_type buf_type, unsigned int count) { + struct v4l2_requestbuffers reqbuf = { + .count = count, + .type = buf_type, + .memory = V4L2_MEMORY_USERPTR + }; + util::safe_ioctl(fd, VIDIOC_REQBUFS, &reqbuf, "VIDIOC_REQBUFS failed"); +} + +MsmVidc::~MsmVidc() { + if (fd > 0) { + close(fd); + } +} + +bool MsmVidc::init(const char* dev, size_t width, size_t height, uint64_t codec) { + LOG("Initializing msm_vidc device %s", dev); + this->w = width; + this->h = height; + this->fd = open(dev, O_RDWR, 0); + if (fd < 0) { + LOGE("failed to open video device %s", dev); + return false; + } + subscribeEvents(); + v4l2_buf_type out_type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; + setPlaneFormat(out_type, V4L2_PIX_FMT_HEVC); // Also allocates the output buffer + setFPS(FPS); + request_buffers(fd, out_type, OUTPUT_BUFFER_COUNT); + util::safe_ioctl(fd, VIDIOC_STREAMON, &out_type, "VIDIOC_STREAMON OUTPUT failed"); + restartCapture(); + setupPolling(); + + this->initialized = true; + return true; +} + +VisionBuf* MsmVidc::decodeFrame(AVPacket *pkt, VisionBuf *buf) { + assert(initialized && (pkt != nullptr) && (buf != nullptr)); + + this->frame_ready = false; + this->current_output_buf = buf; + bool sent_packet = false; + + while (!this->frame_ready) { + if (!sent_packet) { + int buf_index = getBufferUnlocked(); + if (buf_index >= 0) { + assert(buf_index < out_buf_cnt); + sendPacket(buf_index, pkt); + sent_packet = true; + } + } + + if (poll(pfd, nfds, -1) < 0) { + LOGE("poll() error: %d", errno); + return nullptr; + } + + if (VisionBuf* result = processEvents()) { + return result; + } + } + + return buf; +} + +VisionBuf* MsmVidc::processEvents() { + for (int idx = 0; idx < nfds; idx++) { + short revents = pfd[idx].revents; + if (!revents) continue; + + if (idx == ev[EV_VIDEO]) { + if (revents & (POLLIN | POLLRDNORM)) { + VisionBuf *result = handleCapture(); + if (result == this->current_output_buf) { + this->frame_ready = true; + } + } + if (revents & (POLLOUT | POLLWRNORM)) { + handleOutput(); + } + if (revents & POLLPRI) { + handleEvent(); + } + } else { + LOGE("Unexpected event on fd %d", pfd[idx].fd); + } + } + return nullptr; +} + +VisionBuf* MsmVidc::handleCapture() { + struct v4l2_buffer buf = {0}; + struct v4l2_plane planes[1] = {0}; + buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; + buf.memory = V4L2_MEMORY_USERPTR; + buf.m.planes = planes; + buf.length = 1; + util::safe_ioctl(this->fd, VIDIOC_DQBUF, &buf, "VIDIOC_DQBUF CAPTURE failed"); + + if (this->reconfigure_pending || buf.m.planes[0].bytesused == 0) { + return nullptr; + } + + copyBuffer(&cap_bufs[buf.index], this->current_output_buf); + queueCaptureBuffer(buf.index); + return this->current_output_buf; +} + +bool MsmVidc::subscribeEvents() { + for (uint32_t event : subscriptions) { + struct v4l2_event_subscription sub = { .type = event}; + util::safe_ioctl(fd, VIDIOC_SUBSCRIBE_EVENT, &sub, "VIDIOC_SUBSCRIBE_EVENT failed"); + } + return true; +} + +bool MsmVidc::setPlaneFormat(enum v4l2_buf_type type, uint32_t fourcc) { + struct v4l2_format fmt = {.type = type}; + struct v4l2_pix_format_mplane *pix = &fmt.fmt.pix_mp; + *pix = { + .width = (__u32)this->w, + .height = (__u32)this->h, + .pixelformat = fourcc + }; + util::safe_ioctl(fd, VIDIOC_S_FMT, &fmt, "VIDIOC_S_FMT failed"); + if (type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) { + this->out_buf_size = pix->plane_fmt[0].sizeimage; + int ion_size = this->out_buf_size * OUTPUT_BUFFER_COUNT; // Output (input) buffers are ION buffer. + this->out_buf.allocate(ion_size); // mmap rw + for (int i = 0; i < OUTPUT_BUFFER_COUNT; i++) { + this->out_buf_off[i] = i * this->out_buf_size; + this->out_buf_addr[i] = (char *)this->out_buf.addr + this->out_buf_off[i]; + this->out_buf_flag[i] = false; + } + LOGD("Set output buffer size to %d, count %d, addr %p", this->out_buf_size, OUTPUT_BUFFER_COUNT, this->out_buf.addr); + } else if (type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) { + request_buffers(this->fd, type, CAPTURE_BUFFER_COUNT); + util::safe_ioctl(fd, VIDIOC_G_FMT, &fmt, "VIDIOC_G_FMT failed"); + const __u32 y_size = pix->plane_fmt[0].sizeimage; + const __u32 y_stride = pix->plane_fmt[0].bytesperline; + for (int i = 0; i < CAPTURE_BUFFER_COUNT; i++) { + size_t uv_offset = (size_t)y_stride * pix->height; + size_t required = uv_offset + (y_stride * pix->height / 2); // enough for Y + UV. For linear NV12, UV plane starts at y_stride * height. + size_t alloc_size = std::max(y_size, required); + this->cap_bufs[i].allocate(alloc_size); + this->cap_bufs[i].init_yuv(pix->width, pix->height, y_stride, uv_offset); + } + LOGD("Set capture buffer size to %d, count %d, addr %p, extradata size %d", + pix->plane_fmt[0].sizeimage, CAPTURE_BUFFER_COUNT, this->cap_bufs[0].addr, pix->plane_fmt[1].sizeimage); + } + return true; +} + +bool MsmVidc::setFPS(uint32_t fps) { + struct v4l2_streamparm streamparam = { + .type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE, + }; + streamparam.parm.output.timeperframe = {1, fps}; + util::safe_ioctl(fd, VIDIOC_S_PARM, &streamparam, "VIDIOC_S_PARM failed"); + return true; +} + +bool MsmVidc::restartCapture() { + // stop if already initialized + enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; + if (this->initialized) { + LOGD("Restarting capture, flushing buffers..."); + util::safe_ioctl(this->fd, VIDIOC_STREAMOFF, &type, "VIDIOC_STREAMOFF CAPTURE failed"); + struct v4l2_requestbuffers reqbuf = {.type = type, .memory = V4L2_MEMORY_USERPTR}; + util::safe_ioctl(this->fd, VIDIOC_REQBUFS, &reqbuf, "VIDIOC_REQBUFS failed"); + for (size_t i = 0; i < CAPTURE_BUFFER_COUNT; ++i) { + this->cap_bufs[i].free(); + this->cap_buf_flag[i] = false; // mark as not queued + cap_bufs[i].~VisionBuf(); + new (&cap_bufs[i]) VisionBuf(); + } + } + // setup, start and queue capture buffers + setDBP(); + setPlaneFormat(type, V4L2_PIX_FMT_NV12); + util::safe_ioctl(this->fd, VIDIOC_STREAMON, &type, "VIDIOC_STREAMON CAPTURE failed"); + for (size_t i = 0; i < CAPTURE_BUFFER_COUNT; ++i) { + queueCaptureBuffer(i); + } + + return true; +} + +bool MsmVidc::queueCaptureBuffer(int i) { + struct v4l2_buffer buf = {0}; + struct v4l2_plane planes[1] = {0}; + + buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; + buf.memory = V4L2_MEMORY_USERPTR; + buf.index = i; + buf.m.planes = planes; + buf.length = 1; + // decoded frame plane + planes[0].m.userptr = (unsigned long)this->cap_bufs[i].addr; // no security + planes[0].length = this->cap_bufs[i].len; + planes[0].reserved[0] = this->cap_bufs[i].fd; // ION fd + planes[0].reserved[1] = 0; + planes[0].bytesused = this->cap_bufs[i].len; + planes[0].data_offset = 0; + util::safe_ioctl(this->fd, VIDIOC_QBUF, &buf, "VIDIOC_QBUF failed"); + this->cap_buf_flag[i] = true; // mark as queued + return true; +} + +bool MsmVidc::queueOutputBuffer(int i, size_t size) { + struct v4l2_buffer buf = {0}; + struct v4l2_plane planes[1] = {0}; + + buf.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; + buf.memory = V4L2_MEMORY_USERPTR; + buf.index = i; + buf.m.planes = planes; + buf.length = 1; + // decoded frame plane + planes[0].m.userptr = (unsigned long)this->out_buf_off[i]; // check this + planes[0].length = this->out_buf_size; + planes[0].reserved[0] = this->out_buf.fd; // ION fd + planes[0].reserved[1] = 0; + planes[0].bytesused = size; + planes[0].data_offset = 0; + assert((this->out_buf_off[i] & 0xfff) == 0); // must be 4 KiB aligned + assert(this->out_buf_size % 4096 == 0); // ditto for size + + util::safe_ioctl(this->fd, VIDIOC_QBUF, &buf, "VIDIOC_QBUF failed"); + this->out_buf_flag[i] = true; // mark as queued + return true; +} + +bool MsmVidc::setDBP() { + struct v4l2_ext_control control[2] = {0}; + struct v4l2_ext_controls controls = {0}; + control[0].id = V4L2_CID_MPEG_VIDC_VIDEO_STREAM_OUTPUT_MODE; + control[0].value = 1; // V4L2_CID_MPEG_VIDC_VIDEO_STREAM_OUTPUT_SECONDARY + control[1].id = V4L2_CID_MPEG_VIDC_VIDEO_DPB_COLOR_FORMAT; + control[1].value = 0; // V4L2_MPEG_VIDC_VIDEO_DPB_COLOR_FMT_NONE + controls.count = 2; + controls.ctrl_class = V4L2_CTRL_CLASS_MPEG; + controls.controls = control; + util::safe_ioctl(fd, VIDIOC_S_EXT_CTRLS, &controls, "VIDIOC_S_EXT_CTRLS failed"); + return true; +} + +bool MsmVidc::setupPolling() { + // Initialize poll array + pfd[EV_VIDEO] = {fd, POLLIN | POLLOUT | POLLWRNORM | POLLRDNORM | POLLPRI, 0}; + ev[EV_VIDEO] = EV_VIDEO; + nfds = 1; + return true; +} + +bool MsmVidc::sendPacket(int buf_index, AVPacket *pkt) { + assert(buf_index >= 0 && buf_index < out_buf_cnt); + assert(pkt != nullptr && pkt->data != nullptr && pkt->size > 0); + // Prepare output buffer + memset(this->out_buf_addr[buf_index], 0, this->out_buf_size); + uint8_t * data = (uint8_t *)this->out_buf_addr[buf_index]; + memcpy(data, pkt->data, pkt->size); + queueOutputBuffer(buf_index, pkt->size); + return true; +} + +int MsmVidc::getBufferUnlocked() { + for (int i = 0; i < this->out_buf_cnt; i++) { + if (!out_buf_flag[i]) { + return i; + } + } + return -1; +} + + +bool MsmVidc::handleOutput() { + struct v4l2_buffer buf = {0}; + struct v4l2_plane planes[1]; + buf.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; + buf.memory = V4L2_MEMORY_USERPTR; + buf.m.planes = planes; + buf.length = 1; + util::safe_ioctl(this->fd, VIDIOC_DQBUF, &buf, "VIDIOC_DQBUF OUTPUT failed"); + this->out_buf_flag[buf.index] = false; // mark as not queued + return true; +} + +bool MsmVidc::handleEvent() { + // dequeue event + struct v4l2_event event = {0}; + util::safe_ioctl(this->fd, VIDIOC_DQEVENT, &event, "VIDIOC_DQEVENT failed"); + switch (event.type) { + case V4L2_EVENT_MSM_VIDC_PORT_SETTINGS_CHANGED_INSUFFICIENT: { + unsigned int *ptr = (unsigned int *)event.u.data; + unsigned int height = ptr[0]; + unsigned int width = ptr[1]; + this->w = width; + this->h = height; + LOGD("Port Reconfig received insufficient, new size %ux%u, flushing capture bufs...", width, height); // This is normal + struct v4l2_decoder_cmd dec; + dec.flags = V4L2_QCOM_CMD_FLUSH_CAPTURE; + dec.cmd = V4L2_QCOM_CMD_FLUSH; + util::safe_ioctl(this->fd, VIDIOC_DECODER_CMD, &dec, "VIDIOC_DECODER_CMD FLUSH_CAPTURE failed"); + this->reconfigure_pending = true; + LOGD("Waiting for flush done event to reconfigure capture queue"); + break; + } + + case V4L2_EVENT_MSM_VIDC_FLUSH_DONE: { + unsigned int *ptr = (unsigned int *)event.u.data; + unsigned int flags = ptr[0]; + if (flags & V4L2_QCOM_CMD_FLUSH_CAPTURE) { + if (this->reconfigure_pending) { + this->restartCapture(); + this->reconfigure_pending = false; + } + } + break; + } + default: + break; + } + return true; +} diff --git a/openpilot/tools/replay/qcom_decoder.h b/openpilot/tools/replay/qcom_decoder.h new file mode 100644 index 0000000000..1d7522cc70 --- /dev/null +++ b/openpilot/tools/replay/qcom_decoder.h @@ -0,0 +1,88 @@ +#pragma once + +#include +#include + +#include "msgq/visionipc/visionbuf.h" + +extern "C" { + #include + #include +} + +#define V4L2_EVENT_MSM_VIDC_START (V4L2_EVENT_PRIVATE_START + 0x00001000) +#define V4L2_EVENT_MSM_VIDC_FLUSH_DONE (V4L2_EVENT_MSM_VIDC_START + 1) +#define V4L2_EVENT_MSM_VIDC_PORT_SETTINGS_CHANGED_INSUFFICIENT (V4L2_EVENT_MSM_VIDC_START + 3) +#define V4L2_CID_MPEG_MSM_VIDC_BASE 0x00992000 +#define V4L2_CID_MPEG_VIDC_VIDEO_DPB_COLOR_FORMAT (V4L2_CID_MPEG_MSM_VIDC_BASE + 44) +#define V4L2_CID_MPEG_VIDC_VIDEO_STREAM_OUTPUT_MODE (V4L2_CID_MPEG_MSM_VIDC_BASE + 22) +#define V4L2_QCOM_CMD_FLUSH_CAPTURE (1 << 1) +#define V4L2_QCOM_CMD_FLUSH (4) + +#define VIDEO_DEVICE "/dev/video32" +#define OUTPUT_BUFFER_COUNT 8 +#define CAPTURE_BUFFER_COUNT 8 +#define FPS 20 + + +class MsmVidc { +public: + MsmVidc() = default; + ~MsmVidc(); + + bool init(const char* dev, size_t width, size_t height, uint64_t codec); + VisionBuf* decodeFrame(AVPacket* pkt, VisionBuf* buf); + + AVFormatContext* avctx = nullptr; + int fd = 0; + +private: + bool initialized = false; + bool reconfigure_pending = false; + bool frame_ready = false; + + VisionBuf* current_output_buf = nullptr; + VisionBuf out_buf; // Single input buffer + VisionBuf cap_bufs[CAPTURE_BUFFER_COUNT]; // Capture (output) buffers + + size_t w = 1928, h = 1208; + size_t cap_height = 0, cap_width = 0; + + int cap_buf_size = 0; + int out_buf_size = 0; + + size_t cap_plane_off[CAPTURE_BUFFER_COUNT] = {0}; + size_t cap_plane_stride[CAPTURE_BUFFER_COUNT] = {0}; + bool cap_buf_flag[CAPTURE_BUFFER_COUNT] = {false}; + + size_t out_buf_off[OUTPUT_BUFFER_COUNT] = {0}; + void* out_buf_addr[OUTPUT_BUFFER_COUNT] = {0}; + bool out_buf_flag[OUTPUT_BUFFER_COUNT] = {false}; + const int out_buf_cnt = OUTPUT_BUFFER_COUNT; + + const int subscriptions[2] = { + V4L2_EVENT_MSM_VIDC_FLUSH_DONE, + V4L2_EVENT_MSM_VIDC_PORT_SETTINGS_CHANGED_INSUFFICIENT + }; + + enum { EV_VIDEO, EV_COUNT }; + struct pollfd pfd[EV_COUNT] = {0}; + int ev[EV_COUNT] = {-1}; + int nfds = 0; + + VisionBuf* processEvents(); + bool setupOutput(); + bool subscribeEvents(); + bool setPlaneFormat(v4l2_buf_type type, uint32_t fourcc); + bool setFPS(uint32_t fps); + bool restartCapture(); + bool queueCaptureBuffer(int i); + bool queueOutputBuffer(int i, size_t size); + bool setDBP(); + bool setupPolling(); + bool sendPacket(int buf_index, AVPacket* pkt); + int getBufferUnlocked(); + VisionBuf* handleCapture(); + bool handleOutput(); + bool handleEvent(); +}; diff --git a/tools/replay/replay.cc b/openpilot/tools/replay/replay.cc similarity index 77% rename from tools/replay/replay.cc rename to openpilot/tools/replay/replay.cc index a8e5cd9d43..75aecfd0c2 100644 --- a/tools/replay/replay.cc +++ b/openpilot/tools/replay/replay.cc @@ -2,7 +2,9 @@ #include #include -#include "cereal/services.h" +#include +#include +#include "openpilot/cereal/services.h" #include "common/params.h" #include "tools/replay/util.h" @@ -19,8 +21,16 @@ Replay::Replay(const std::string &route, std::vector allow, std::ve : sm_(sm), flags_(flags), seg_mgr_(std::make_unique(route, flags, data_dir, auto_source)) { std::signal(SIGUSR1, interrupt_sleep_handler); + if (flags_ & REPLAY_FLAG_BENCHMARK) { + benchmark_stats_.process_start_ts = nanos_since_boot(); + seg_mgr_->setBenchmarkCallback([this](int seg_num, const std::string& event) { + benchmark_stats_.timeline.emplace_back(nanos_since_boot(), + "segment " + std::to_string(seg_num) + " " + event); + }); + } + if (!(flags_ & REPLAY_FLAG_ALL_SERVICES)) { - block.insert(block.end(), {"uiDebug", "userFlag"}); + block.insert(block.end(), {"bookmarkButton", "uiDebug", "userBookmark"}); } setupServices(allow, block); setupSegmentManager(!allow.empty() || !block.empty()); @@ -31,6 +41,8 @@ void Replay::setupServices(const std::vector &allow, const std::vec sockets_.resize(event_schema.getUnionFields().size(), nullptr); std::vector active_services; + active_services.reserve(services.size()); + for (const auto &[name, _] : services) { bool is_blocked = std::find(block.begin(), block.end(), name) != block.end(); bool is_allowed = allow.empty() || std::find(allow.begin(), allow.end(), name) != allow.end(); @@ -40,7 +52,9 @@ void Replay::setupServices(const std::vector &allow, const std::vec active_services.push_back(name.c_str()); } } - rInfo("active services: %s", join(active_services, ", ").c_str()); + + std::string services_str = join(active_services, ", "); + rInfo("active services: %s", services_str.c_str()); if (!sm_) { pm_ = std::make_unique(active_services); } @@ -59,7 +73,6 @@ void Replay::setupSegmentManager(bool has_filters) { } Replay::~Replay() { - seg_mgr_.reset(); if (stream_thread_.joinable()) { rInfo("shutdown: in progress..."); interruptStream([this]() { @@ -70,12 +83,18 @@ Replay::~Replay() { rInfo("shutdown: done"); } camera_server_.reset(); + seg_mgr_.reset(); } bool Replay::load() { rInfo("loading route %s", seg_mgr_->route_.name().c_str()); + if (!seg_mgr_->load()) return false; + if (hasFlag(REPLAY_FLAG_BENCHMARK)) { + benchmark_stats_.timeline.emplace_back(nanos_since_boot(), "route metadata loaded"); + } + min_seconds_ = seg_mgr_->route_.segments().begin()->first * 60; max_seconds_ = (seg_mgr_->route_.segments().rbegin()->first + 1) * 60; return true; @@ -174,7 +193,7 @@ void Replay::startStream(const std::shared_ptr segment) { auto event = reader.getRoot(); uint64_t wall_time = event.getInitData().getWallTimeNanos(); if (wall_time > 0) { - route_date_time_ = wall_time / 1e6; + route_date_time_ = wall_time / 1e9; } } @@ -253,8 +272,13 @@ void Replay::streamThread() { stream_thread_id = pthread_self(); std::unique_lock lk(stream_lock_); + int last_processed_segment = -1; + uint64_t segment_start_time = 0; + bool streaming_started = false; + while (true) { stream_cv_.wait(lk, [this]() { return exit_ || (events_ready_ && !interrupt_requested_); }); + if (exit_) break; event_data_ = seg_mgr_->getEventData(); @@ -266,14 +290,19 @@ void Replay::streamThread() { continue; } - auto it = publishEvents(first, events.cend()); + if (!streaming_started && hasFlag(REPLAY_FLAG_BENCHMARK)) { + benchmark_stats_.timeline.emplace_back(nanos_since_boot(), "streaming started"); + streaming_started = true; + } + + auto it = publishEvents(first, events.cend(), last_processed_segment, segment_start_time); // Ensure frames are sent before unlocking to prevent race conditions if (camera_server_) { camera_server_->waitForSent(); } - if (it == events.cend() && !hasFlag(REPLAY_FLAG_NO_LOOP)) { + if (it == events.cend() && !hasFlag(REPLAY_FLAG_NO_LOOP) && !hasFlag(REPLAY_FLAG_BENCHMARK)) { int last_segment = seg_mgr_->route_.segments().rbegin()->first; if (event_data_->isSegmentLoaded(last_segment)) { rInfo("reaches the end of route, restart from beginning"); @@ -281,12 +310,28 @@ void Replay::streamThread() { seekTo(minSeconds(), false); stream_lock_.lock(); } + } else if (it == events.cend() && hasFlag(REPLAY_FLAG_BENCHMARK)) { + // Exit benchmark mode after first segment completes + exit_ = true; + break; } } + + if (hasFlag(REPLAY_FLAG_BENCHMARK)) { + benchmark_stats_.timeline.emplace_back(nanos_since_boot(), "benchmark done"); + + { + std::unique_lock lock(benchmark_lock_); + benchmark_done_ = true; + } + benchmark_cv_.notify_one(); + } } std::vector::const_iterator Replay::publishEvents(std::vector::const_iterator first, - std::vector::const_iterator last) { + std::vector::const_iterator last, + int &last_processed_segment, + uint64_t &segment_start_time) { uint64_t evt_start_ts = cur_mono_time_; uint64_t loop_start_ts = nanos_since_boot(); double prev_replay_speed = speed_; @@ -300,6 +345,23 @@ std::vector::const_iterator Replay::publishEvents(std::vector::con seg_mgr_->setCurrentSegment(segment); } + // Track segment completion for benchmark timeline + if (hasFlag(REPLAY_FLAG_BENCHMARK) && segment != last_processed_segment) { + if (last_processed_segment >= 0 && segment_start_time > 0) { + uint64_t processing_time_ns = nanos_since_boot() - segment_start_time; + double processing_time_ms = processing_time_ns / 1e6; + double realtime_factor = 60.0 / (processing_time_ns / 1e9); // 60s per segment + + std::ostringstream oss; + oss << "segment " << last_processed_segment << " done publishing (" + << std::fixed << std::setprecision(0) << processing_time_ms << " ms, " + << std::fixed << std::setprecision(0) << realtime_factor << "x realtime)"; + benchmark_stats_.timeline.emplace_back(nanos_since_boot(), oss.str()); + } + segment_start_time = nanos_since_boot(); + last_processed_segment = segment; + } + cur_mono_time_ = evt.mono_time; cur_which_ = evt.which; @@ -316,7 +378,8 @@ std::vector::const_iterator Replay::publishEvents(std::vector::con evt_start_ts = evt.mono_time; loop_start_ts = current_nanos; prev_replay_speed = speed_; - } else if (time_diff > 0) { + } else if (time_diff > 0 && !hasFlag(REPLAY_FLAG_BENCHMARK)) { + // Skip sleep in benchmark mode for maximum throughput precise_nano_sleep(time_diff, interrupt_requested_); } @@ -334,3 +397,12 @@ std::vector::const_iterator Replay::publishEvents(std::vector::con return first; } + +void Replay::waitForFinished() { + if (!hasFlag(REPLAY_FLAG_BENCHMARK)) { + return; + } + + std::unique_lock lock(benchmark_lock_); + benchmark_cv_.wait(lock, [this]() { return benchmark_done_; }); +} diff --git a/tools/replay/replay.h b/openpilot/tools/replay/replay.h similarity index 87% rename from tools/replay/replay.h rename to openpilot/tools/replay/replay.h index 5e868d2427..ce6d75bd6d 100644 --- a/tools/replay/replay.h +++ b/openpilot/tools/replay/replay.h @@ -12,7 +12,7 @@ #include "tools/replay/seg_mgr.h" #include "tools/replay/timeline.h" -#define DEMO_ROUTE "a2a0ccea32023010|2023-07-27--13-01-19" +#define DEMO_ROUTE "5beb9b58bd12b691/0000010a--a51155e496" enum REPLAY_FLAGS { REPLAY_FLAG_NONE = 0x0000, @@ -24,6 +24,12 @@ enum REPLAY_FLAGS { REPLAY_FLAG_NO_HW_DECODER = 0x0100, REPLAY_FLAG_NO_VIPC = 0x0400, REPLAY_FLAG_ALL_SERVICES = 0x0800, + REPLAY_FLAG_BENCHMARK = 0x1000, +}; + +struct BenchmarkStats { + uint64_t process_start_ts = 0; + std::vector> timeline; }; class Replay { @@ -57,6 +63,8 @@ public: inline const std::optional findAlertAtTime(double sec) const { return timeline_.findAlertAtTime(sec); } const std::shared_ptr getEventData() const { return seg_mgr_->getEventData(); } void installEventFilter(std::function filter) { event_filter_ = filter; } + void waitForFinished(); + const BenchmarkStats &getBenchmarkStats() const { return benchmark_stats_; } // Event callback functions std::function onSegmentsMerged = nullptr; @@ -72,7 +80,9 @@ private: void handleSegmentMerge(); void interruptStream(const std::function& update_fn); std::vector::const_iterator publishEvents(std::vector::const_iterator first, - std::vector::const_iterator last); + std::vector::const_iterator last, + int &last_processed_segment, + uint64_t &segment_start_time); void publishMessage(const Event *e); void publishFrame(const Event *e); void checkSeekProgress(); @@ -90,7 +100,7 @@ private: std::atomic exit_ = false; std::atomic interrupt_requested_ = false; bool events_ready_ = false; - std::time_t route_date_time_; + std::time_t route_date_time_ = 0; uint64_t route_start_ts_ = 0; std::atomic cur_mono_time_ = 0; cereal::Event::Which cur_which_ = cereal::Event::Which::INIT_DATA; @@ -107,4 +117,9 @@ private: std::function event_filter_ = nullptr; std::shared_ptr event_data_ = std::make_shared(); + + BenchmarkStats benchmark_stats_; + std::condition_variable benchmark_cv_; + std::mutex benchmark_lock_; + bool benchmark_done_ = false; }; diff --git a/tools/replay/route.cc b/openpilot/tools/replay/route.cc similarity index 85% rename from tools/replay/route.cc rename to openpilot/tools/replay/route.cc index ba00828267..326d28d726 100644 --- a/tools/replay/route.cc +++ b/openpilot/tools/replay/route.cc @@ -4,9 +4,9 @@ #include #include -#include "third_party/json11/json11.hpp" -#include "system/hardware/hw.h" -#include "tools/replay/api.h" +#include "json11/json11.hpp" +#include "common/hardware/hw.h" +#include "tools/replay/py_downloader.h" #include "tools/replay/replay.h" #include "tools/replay/util.h" @@ -103,43 +103,44 @@ bool Route::loadFromAutoSource() { return !segments_.empty(); } -bool Route::loadFromServer(int retries) { - const std::string url = CommaApi2::BASE_URL + "/v1/route/" + route_.str + "/files"; - for (int i = 1; i <= retries; ++i) { - long response_code = 0; - std::string result = CommaApi2::httpGet(url, &response_code); - if (response_code == 200) { - return loadFromJson(result); - } - - if (response_code == 401 || response_code == 403) { - rWarning(">> Unauthorized. Authenticate with tools/lib/auth.py <<"); - err_ = RouteLoadError::Unauthorized; - break; - } - if (response_code == 404) { - rWarning("The specified route could not be found on the server."); - err_ = RouteLoadError::FileNotFound; - break; - } - +bool Route::loadFromServer() { + std::string result = PyDownloader::getRouteFiles(route_.str); + if (result.empty()) { err_ = RouteLoadError::NetworkError; - rWarning("Retrying %d/%d", i, retries); - util::sleep_for(3000); - } - - return false; -} - -bool Route::loadFromJson(const std::string &json) { - const static std::regex rx(R"(\/(\d+)\/)"); - std::string err; - auto jsonData = json11::Json::parse(json, err); - if (!err.empty()) { - rWarning("JSON parsing error: %s", err.c_str()); + rWarning("Failed to fetch route files from server"); return false; } - for (const auto &value : jsonData.object_items()) { + + // Check for error field in JSON response + std::string parse_err; + auto json = json11::Json::parse(result, parse_err); + if (!parse_err.empty()) { + err_ = RouteLoadError::NetworkError; + rWarning("Failed to parse route files response"); + return false; + } + + if (json.is_object() && json["error"].is_string()) { + const std::string &error = json["error"].string_value(); + if (error == "unauthorized") { + rWarning(">> Unauthorized. Authenticate with openpilot/tools/lib/auth.py <<"); + err_ = RouteLoadError::Unauthorized; + } else if (error == "not_found") { + rWarning("The specified route could not be found on the server."); + err_ = RouteLoadError::FileNotFound; + } else { + rWarning("API error: %s", error.c_str()); + err_ = RouteLoadError::NetworkError; + } + return false; + } + + return loadFromJson(json); +} + +bool Route::loadFromJson(const json11::Json &json) { + const static std::regex rx(R"(\/(\d+)\/)"); + for (const auto &value : json.object_items()) { const auto &urlArray = value.second.array_items(); for (const auto &url : urlArray) { std::string url_str = url.string_value(); @@ -225,10 +226,10 @@ void Segment::loadFile(int id, const std::string file) { bool success = false; if (id < MAX_CAMERAS) { frames[id] = std::make_unique(); - success = frames[id]->load((CameraType)id, file, flags & REPLAY_FLAG_NO_HW_DECODER, &abort_, local_cache, 20 * 1024 * 1024, 3); + success = frames[id]->load((CameraType)id, file, flags & REPLAY_FLAG_NO_HW_DECODER, &abort_, local_cache); } else { log = std::make_unique(filters_); - success = log->load(file, &abort_, local_cache, 0, 3); + success = log->load(file, &abort_, local_cache); } if (!success) { diff --git a/tools/replay/route.h b/openpilot/tools/replay/route.h similarity index 96% rename from tools/replay/route.h rename to openpilot/tools/replay/route.h index 0375252a19..50f3eba854 100644 --- a/tools/replay/route.h +++ b/openpilot/tools/replay/route.h @@ -8,6 +8,7 @@ #include #include +#include "json11/json11.hpp" #include "tools/replay/framereader.h" #include "tools/replay/logreader.h" #include "tools/replay/util.h" @@ -55,8 +56,8 @@ protected: bool loadSegments(); bool loadFromAutoSource(); bool loadFromLocal(); - bool loadFromServer(int retries = 3); - bool loadFromJson(const std::string &json); + bool loadFromServer(); + bool loadFromJson(const json11::Json &json); void addFileToSegment(int seg_num, const std::string &file); RouteIdentifier route_ = {}; std::string data_dir_; diff --git a/tools/replay/seg_mgr.cc b/openpilot/tools/replay/seg_mgr.cc similarity index 92% rename from tools/replay/seg_mgr.cc rename to openpilot/tools/replay/seg_mgr.cc index ee034fb083..0778cacbc1 100644 --- a/tools/replay/seg_mgr.cc +++ b/openpilot/tools/replay/seg_mgr.cc @@ -91,7 +91,8 @@ bool SegmentManager::mergeSegments(const SegmentMap::iterator &begin, const Segm auto &merged_events = merged_event_data->events; merged_events.reserve(total_event_count); - rDebug("merging segments: %s", join(segments_to_merge, ", ").c_str()); + std::string segments_str = join(segments_to_merge, ", "); + rDebug("merging segments: %s", segments_str.c_str()); for (int n : segments_to_merge) { const auto &events = segments_.at(n)->log->events; if (events.empty()) continue; @@ -117,9 +118,15 @@ void SegmentManager::loadSegmentsInRange(SegmentMap::iterator begin, SegmentMap: for (auto it = first; it != last; ++it) { auto &segment_ptr = it->second; if (!segment_ptr) { + if (onBenchmarkEvent_) { + onBenchmarkEvent_(it->first, "loading"); + } segment_ptr = std::make_shared( it->first, route_.at(it->first), flags_, filters_, [this](int seg_num, bool success) { + if (onBenchmarkEvent_) { + onBenchmarkEvent_(seg_num, success ? "loaded" : "load failed"); + } std::unique_lock lock(mutex_); needs_update_ = true; cv_.notify_one(); diff --git a/tools/replay/seg_mgr.h b/openpilot/tools/replay/seg_mgr.h similarity index 90% rename from tools/replay/seg_mgr.h rename to openpilot/tools/replay/seg_mgr.h index 640169749e..54e156fb60 100644 --- a/tools/replay/seg_mgr.h +++ b/openpilot/tools/replay/seg_mgr.h @@ -27,6 +27,7 @@ public: bool load(); void setCurrentSegment(int seg_num); void setCallback(const std::function &callback) { onSegmentMergedCallback_ = callback; } + void setBenchmarkCallback(const std::function &callback) { onBenchmarkEvent_ = callback; } void setFilters(const std::vector &filters) { filters_ = filters; } const std::shared_ptr getEventData() const { return std::atomic_load(&event_data_); } bool hasSegment(int n) const { return segments_.find(n) != segments_.end(); } @@ -52,5 +53,6 @@ private: SegmentMap segments_; std::shared_ptr event_data_; std::function onSegmentMergedCallback_ = nullptr; + std::function onBenchmarkEvent_ = nullptr; std::set merged_segments_; }; diff --git a/tools/replay/tests/test_replay.cc b/openpilot/tools/replay/tests/test_replay.cc similarity index 94% rename from tools/replay/tests/test_replay.cc rename to openpilot/tools/replay/tests/test_replay.cc index aed3de59a8..45fcc98191 100644 --- a/tools/replay/tests/test_replay.cc +++ b/openpilot/tools/replay/tests/test_replay.cc @@ -1,5 +1,6 @@ #define CATCH_CONFIG_MAIN #include "catch2/catch.hpp" +#include "tools/replay/filereader.h" #include "tools/replay/replay.h" const std::string TEST_RLOG_URL = "https://commadataci.blob.core.windows.net/openpilotci/0c94aa1e1296d7c6/2021-05-05--19-48-37/0/rlog.bz2"; diff --git a/tools/replay/timeline.cc b/openpilot/tools/replay/timeline.cc similarity index 93% rename from tools/replay/timeline.cc rename to openpilot/tools/replay/timeline.cc index a4c2ffb700..34729f5214 100644 --- a/tools/replay/timeline.cc +++ b/openpilot/tools/replay/timeline.cc @@ -3,7 +3,7 @@ #include #include -#include "cereal/gen/cpp/log.capnp.h" +#include "openpilot/cereal/gen/cpp/log.capnp.h" Timeline::~Timeline() { should_exit_.store(true); @@ -26,7 +26,7 @@ std::optional Timeline::find(double cur_ts, FindFlag flag) const { return entry.end_time; } } else if (entry.start_time > cur_ts) { - if ((flag == FindFlag::nextUserFlag && entry.type == TimelineType::UserFlag) || + if ((flag == FindFlag::nextUserBookmark && entry.type == TimelineType::UserBookmark) || (flag == FindFlag::nextInfo && entry.type == TimelineType::AlertInfo) || (flag == FindFlag::nextWarning && entry.type == TimelineType::AlertWarning) || (flag == FindFlag::nextCritical && entry.type == TimelineType::AlertCritical)) { @@ -55,7 +55,7 @@ void Timeline::buildTimeline(const Route &route, uint64_t route_start_ts, bool l if (should_exit_) break; auto log = std::make_shared(); - if (!log->load(segment.second.qlog, &should_exit_, local_cache, 0, 3) || log->events.empty()) { + if (!log->load(segment.second.qlog, &should_exit_, local_cache) || log->events.empty()) { continue; // Skip if log loading fails or no events } @@ -66,8 +66,8 @@ void Timeline::buildTimeline(const Route &route, uint64_t route_start_ts, bool l auto cs = reader.getRoot().getSelfdriveState(); updateEngagementStatus(cs, current_engaged_idx, seconds); updateAlertStatus(cs, current_alert_idx, seconds); - } else if (e.which == cereal::Event::Which::USER_FLAG) { - staging_entries_.emplace_back(Entry{seconds, seconds, TimelineType::UserFlag}); + } else if (e.which == cereal::Event::Which::USER_BOOKMARK) { + staging_entries_.emplace_back(Entry{seconds, seconds, TimelineType::UserBookmark}); } } diff --git a/tools/replay/timeline.h b/openpilot/tools/replay/timeline.h similarity index 95% rename from tools/replay/timeline.h rename to openpilot/tools/replay/timeline.h index 74add9e5cc..9688b6b95e 100644 --- a/tools/replay/timeline.h +++ b/openpilot/tools/replay/timeline.h @@ -7,8 +7,8 @@ #include "tools/replay/route.h" -enum class TimelineType { None, Engaged, AlertInfo, AlertWarning, AlertCritical, UserFlag }; -enum class FindFlag { nextEngagement, nextDisEngagement, nextUserFlag, nextInfo, nextWarning, nextCritical }; +enum class TimelineType { None, Engaged, AlertInfo, AlertWarning, AlertCritical, UserBookmark }; +enum class FindFlag { nextEngagement, nextDisEngagement, nextUserBookmark, nextInfo, nextWarning, nextCritical }; class Timeline { public: diff --git a/openpilot/tools/replay/ui.py b/openpilot/tools/replay/ui.py new file mode 100755 index 0000000000..4fbede2be9 --- /dev/null +++ b/openpilot/tools/replay/ui.py @@ -0,0 +1,271 @@ +#!/usr/bin/env python3 +import argparse +import os +import sys + +import numpy as np +import pyray as rl + +import openpilot.cereal.messaging as messaging +from openpilot.common.basedir import BASEDIR +from openpilot.common.transformations.camera import DEVICE_CAMERAS +from openpilot.tools.replay.lib.ui_helpers import ( + UP, + BLACK, + GREEN, + YELLOW, + Calibration, + get_blank_lid_overlay, + init_plots, + maybe_update_radar_points, + plot_lead, + plot_model, +) +from msgq.visionipc import VisionStreamType +from openpilot.selfdrive.ui.mici.onroad.cameraview import CameraView + +os.environ['BASEDIR'] = BASEDIR + +ANGLE_SCALE = 5.0 + + +def ui_thread(addr): + # Get monitor info before creating window + rl.set_config_flags(rl.ConfigFlags.FLAG_MSAA_4X_HINT) + rl.init_window(1, 1, "") + max_height = rl.get_monitor_height(0) + rl.close_window() + + hor_mode = os.getenv("HORIZONTAL") is not None + hor_mode = True if max_height < 960 + 300 else hor_mode + + if hor_mode: + size = (640 + 384 + 640, 960) + write_x = 5 + write_y = 680 + else: + size = (640 + 384, 960 + 300) + write_x = 645 + write_y = 970 + + rl.set_trace_log_level(rl.TraceLogLevel.LOG_ERROR) + rl.set_config_flags(rl.ConfigFlags.FLAG_MSAA_4X_HINT) + rl.init_window(size[0], size[1], "openpilot debug UI") + rl.set_target_fps(60) + + # Load font + font_path = os.path.join(BASEDIR, "openpilot/selfdrive/assets/fonts/JetBrainsMono-Medium.ttf") + font = rl.load_font_ex(font_path, 32, None, 0) + + camera_view = CameraView("camerad", VisionStreamType.VISION_STREAM_ROAD) + + # Overlay texture for model/lane line drawing + overlay_img = np.zeros((480, 640, 4), dtype='uint8') + overlay_image = rl.gen_image_color(640, 480, rl.BLANK) + overlay_texture = rl.load_texture_from_image(overlay_image) + rl.unload_image(overlay_image) + + # lid_overlay array is (lidar_x, lidar_y) = (384, 960) + top_down_image = rl.gen_image_color(UP.lidar_x, UP.lidar_y, rl.BLACK) + top_down_texture = rl.load_texture_from_image(top_down_image) + rl.unload_image(top_down_image) + + sm = messaging.SubMaster( + [ + 'carState', + 'longitudinalPlan', + 'carControl', + 'radarState', + 'liveCalibration', + 'controlsState', + 'selfdriveState', + 'liveTracks', + 'modelV2', + 'liveParameters', + 'roadCameraState', + ], + addr=addr, + ) + + img = np.zeros((480, 640, 3), dtype='uint8') + num_px = 0 + calibration = None + + lid_overlay_blank = get_blank_lid_overlay(UP) + + # plots + name_to_arr_idx = { + "gas": 0, + "computer_gas": 1, + "user_brake": 2, + "computer_brake": 3, + "v_ego": 4, + "v_pid": 5, + "angle_steers_des": 6, + "angle_steers": 7, + "angle_steers_k": 8, + "steer_torque": 9, + "v_override": 10, + "v_cruise": 11, + "a_ego": 12, + "a_target": 13, + } + + plot_arr = np.zeros((100, len(name_to_arr_idx.values()))) + + plot_xlims = [(0, plot_arr.shape[0]), (0, plot_arr.shape[0]), (0, plot_arr.shape[0]), (0, plot_arr.shape[0])] + plot_ylims = [(-0.1, 1.1), (-ANGLE_SCALE, ANGLE_SCALE), (0.0, 75.0), (-3.5, 2.0)] + plot_names = [ + ["gas", "computer_gas", "user_brake", "computer_brake"], + ["angle_steers", "angle_steers_des", "angle_steers_k", "steer_torque"], + ["v_ego", "v_override", "v_pid", "v_cruise"], + ["a_ego", "a_target"], + ] + plot_colors = [["b", "b", "g", "r", "y"], ["b", "g", "y", "r"], ["b", "g", "r", "y"], ["b", "r"]] + plot_styles = [["-", "-", "-", "-", "-"], ["-", "-", "-", "-"], ["-", "-", "-", "-"], ["-", "-"]] + + draw_plots = init_plots(plot_arr, name_to_arr_idx, plot_xlims, plot_ylims, plot_names, plot_colors, plot_styles) + + # Palette for converting lid_overlay grayscale indices to RGBA colors + palette = np.zeros((256, 4), dtype=np.uint8) + palette[:, 3] = 255 # alpha + palette[1] = [255, 0, 0, 255] # RED + palette[2] = [0, 255, 0, 255] # GREEN + palette[3] = [0, 0, 255, 255] # BLUE + palette[4] = [255, 255, 0, 255] # YELLOW + palette[110] = [110, 110, 110, 255] # car_color (gray) + palette[255] = [255, 255, 255, 255] # WHITE + + while not rl.window_should_close(): + rl.begin_drawing() + rl.clear_background(rl.Color(64, 64, 64, 255)) + + # Render camera (NV12->RGB on GPU via shader) + if camera_view.frame: + cam_h = 640.0 * camera_view.frame.height / camera_view.frame.width + else: + cam_h = 480.0 + camera_view.render(rl.Rectangle(0, 0, 640, cam_h)) + + lid_overlay = lid_overlay_blank.copy() + top_down = top_down_texture, lid_overlay + + sm.update(0) + + camera = DEVICE_CAMERAS[("tici", str(sm['roadCameraState'].sensor))] + calib_scale = camera.fcam.width / 640.0 + + if camera_view.frame: + num_px = camera_view.frame.width * camera_view.frame.height + + intrinsic_matrix = camera.fcam.intrinsics + + w = sm['controlsState'].lateralControlState.which() + if w == 'lqrStateDEPRECATED': + angle_steers_k = sm['controlsState'].lateralControlState.lqrStateDEPRECATED.steeringAngleDeg + elif w == 'indiState': + angle_steers_k = sm['controlsState'].lateralControlState.indiState.steeringAngleDeg + else: + angle_steers_k = np.inf + + if sm.updated['carState']: + plot_arr[:-1] = plot_arr[1:] + plot_arr[-1, name_to_arr_idx['angle_steers']] = sm['carState'].steeringAngleDeg + plot_arr[-1, name_to_arr_idx['angle_steers_des']] = sm['carControl'].actuators.steeringAngleDeg + plot_arr[-1, name_to_arr_idx['angle_steers_k']] = angle_steers_k + plot_arr[-1, name_to_arr_idx['gas']] = sm['carState'].deprecated.gas + # TODO gas is deprecated + plot_arr[-1, name_to_arr_idx['computer_gas']] = np.clip(sm['carControl'].actuators.accel / 4.0, 0.0, 1.0) + plot_arr[-1, name_to_arr_idx['user_brake']] = sm['carState'].brakePressed + plot_arr[-1, name_to_arr_idx['steer_torque']] = sm['carControl'].actuators.torque * ANGLE_SCALE + # TODO brake is deprecated + plot_arr[-1, name_to_arr_idx['computer_brake']] = np.clip(-sm['carControl'].actuators.accel / 4.0, 0.0, 1.0) + plot_arr[-1, name_to_arr_idx['v_ego']] = sm['carState'].vEgo + plot_arr[-1, name_to_arr_idx['v_cruise']] = sm['carState'].cruiseState.speed + plot_arr[-1, name_to_arr_idx['a_ego']] = sm['carState'].aEgo + + plot_arr[-1, name_to_arr_idx['a_target']] = sm['longitudinalPlan'].aTarget + + # Draw model overlays onto img, then blit as transparent overlay + img[:] = 0 + if sm.recv_frame['modelV2']: + plot_model(sm['modelV2'], img, calibration, top_down) + + if sm.recv_frame['radarState']: + plot_lead(sm['radarState'], top_down) + + # draw all radar points + maybe_update_radar_points(sm['liveTracks'].points, top_down[1]) + + if sm.updated['liveCalibration'] and num_px: + rpyCalib = np.asarray(sm['liveCalibration'].rpyCalib) + calibration = Calibration(num_px, rpyCalib, intrinsic_matrix, calib_scale) + + # Update overlay texture (RGB img -> RGBA with non-black pixels visible) + mask = np.any(img > 0, axis=2) + overlay_img[:, :, :3] = img + overlay_img[:, :, 3] = mask * 255 + rl.update_texture(overlay_texture, rl.ffi.cast("void *", overlay_img.ctypes.data)) + rl.draw_texture(overlay_texture, 0, 0, rl.WHITE) # noqa: TID251 + + # display alerts + rl.draw_text_ex(font, sm['selfdriveState'].alertText1, rl.Vector2(180, 150), 30, 0, rl.RED) + rl.draw_text_ex(font, sm['selfdriveState'].alertText2, rl.Vector2(180, 190), 20, 0, rl.RED) + + # draw plots (texture is reused internally) + plot_texture = draw_plots(plot_arr) + if hor_mode: + rl.draw_texture(plot_texture, 640 + 384, 0, rl.WHITE) # noqa: TID251 + else: + rl.draw_texture(plot_texture, 0, 600, rl.WHITE) # noqa: TID251 + + # Convert lid_overlay to RGBA and update top_down texture + # lid_overlay is (384, 960), need to transpose to (960, 384) for row-major RGBA buffer + lid_rgba = palette[lid_overlay.T] + rl.update_texture(top_down_texture, rl.ffi.cast("void *", np.ascontiguousarray(lid_rgba).ctypes.data)) + rl.draw_texture(top_down_texture, 640, 0, rl.WHITE) # noqa: TID251 + + SPACING = 25 + lines = [ + ("ENABLED", GREEN if sm['selfdriveState'].enabled else BLACK), + ("SPEED: " + str(round(sm['carState'].vEgo, 1)) + " m/s", YELLOW), + ("LONG CONTROL STATE: " + str(sm['controlsState'].longControlState), YELLOW), + ("LONG MPC SOURCE: " + str(sm['longitudinalPlan'].longitudinalPlanSource), YELLOW), + None, + ("ANGLE OFFSET (AVG): " + str(round(sm['liveParameters'].angleOffsetAverageDeg, 2)) + " deg", YELLOW), + ("ANGLE OFFSET (INSTANT): " + str(round(sm['liveParameters'].angleOffsetDeg, 2)) + " deg", YELLOW), + ("STIFFNESS: " + str(round(sm['liveParameters'].stiffnessFactor * 100.0, 2)) + " %", YELLOW), + ("STEER RATIO: " + str(round(sm['liveParameters'].steerRatio, 2)), YELLOW), + ] + + for i, line in enumerate(lines): + if line is not None: + color = rl.Color(line[1][0], line[1][1], line[1][2], 255) + rl.draw_text_ex(font, line[0], rl.Vector2(write_x, write_y + i * SPACING), 20, 0, color) + + rl.end_drawing() + + rl.unload_texture(overlay_texture) + rl.unload_texture(top_down_texture) + rl.unload_font(font) + camera_view.close() + rl.close_window() + + +def get_arg_parser(): + parser = argparse.ArgumentParser(description="Show replay data in a UI.", formatter_class=argparse.ArgumentDefaultsHelpFormatter) + + parser.add_argument("ip_address", nargs="?", default="127.0.0.1", help="The ip address on which to receive zmq messages.") + + parser.add_argument("--frame-address", default=None, help="The frame address (fully qualified ZMQ endpoint for frames) on which to receive zmq messages.") + return parser + + +if __name__ == "__main__": + args = get_arg_parser().parse_args(sys.argv[1:]) + + if args.ip_address != "127.0.0.1": + os.environ["ZMQ"] = "1" + messaging.reset_context() + + ui_thread(args.ip_address) diff --git a/openpilot/tools/replay/util.cc b/openpilot/tools/replay/util.cc new file mode 100644 index 0000000000..7b308b5c3d --- /dev/null +++ b/openpilot/tools/replay/util.cc @@ -0,0 +1,205 @@ +#include "tools/replay/util.h" + +#include + +#include +#include +#include +#include +#include +#include + +#include "common/timing.h" +#include "common/util.h" + +ReplayMessageHandler message_handler = nullptr; +void installMessageHandler(ReplayMessageHandler handler) { message_handler = handler; } + +void logMessage(ReplyMsgType type, const char *fmt, ...) { + static std::mutex lock; + std::lock_guard lk(lock); + + char *msg_buf = nullptr; + va_list args; + va_start(args, fmt); + int ret = vasprintf(&msg_buf, fmt, args); + va_end(args); + if (ret <= 0 || !msg_buf) return; + + if (message_handler) { + message_handler(type, msg_buf); + } else { + if (type == ReplyMsgType::Debug) { + std::cout << "\033[38;5;248m" << msg_buf << "\033[00m" << std::endl; + } else if (type == ReplyMsgType::Warning) { + std::cout << "\033[38;5;227m" << msg_buf << "\033[00m" << std::endl; + } else if (type == ReplyMsgType::Critical) { + std::cout << "\033[38;5;196m" << msg_buf << "\033[00m" << std::endl; + } else { + std::cout << msg_buf << std::endl; + } + } + + free(msg_buf); +} + +std::string formattedDataSize(size_t size) { + if (size < 1024) { + return std::to_string(size) + " B"; + } else if (size < 1024 * 1024) { + return util::string_format("%.2f KB", (float)size / 1024); + } else { + return util::string_format("%.2f MB", (float)size / (1024 * 1024)); + } +} + +std::string getUrlWithoutQuery(const std::string &url) { + size_t idx = url.find("?"); + return (idx == std::string::npos ? url : url.substr(0, idx)); +} + +std::string decompressBZ2(const std::string &in, std::atomic *abort) { + return decompressBZ2((std::byte *)in.data(), in.size(), abort); +} + +std::string decompressBZ2(const std::byte *in, size_t in_size, std::atomic *abort) { + if (in_size == 0) return {}; + + bz_stream strm = {}; + int bzerror = BZ2_bzDecompressInit(&strm, 0, 0); + assert(bzerror == BZ_OK); + + strm.next_in = (char *)in; + strm.avail_in = in_size; + std::string out(in_size * 5, '\0'); + do { + strm.next_out = (char *)(&out[strm.total_out_lo32]); + strm.avail_out = out.size() - strm.total_out_lo32; + + const char *prev_write_pos = strm.next_out; + bzerror = BZ2_bzDecompress(&strm); + if (bzerror == BZ_OK && prev_write_pos == strm.next_out) { + // content is corrupt + bzerror = BZ_STREAM_END; + rWarning("decompressBZ2 error: content is corrupt"); + break; + } + + if (bzerror == BZ_OK && strm.avail_in > 0 && strm.avail_out == 0) { + out.resize(out.size() * 2); + } + } while (bzerror == BZ_OK && !(abort && *abort)); + + BZ2_bzDecompressEnd(&strm); + if (bzerror == BZ_STREAM_END && !(abort && *abort)) { + out.resize(strm.total_out_lo32); + out.shrink_to_fit(); + return out; + } + return {}; +} + +std::string decompressZST(const std::string &in, std::atomic *abort) { + return decompressZST((std::byte *)in.data(), in.size(), abort); +} + +std::string decompressZST(const std::byte *in, size_t in_size, std::atomic *abort) { + ZSTD_DCtx *dctx = ZSTD_createDCtx(); + assert(dctx != nullptr); + + // Initialize input and output buffers + ZSTD_inBuffer input = {in, in_size, 0}; + + // Estimate and reserve memory for decompressed data + size_t estimatedDecompressedSize = ZSTD_getFrameContentSize(in, in_size); + if (estimatedDecompressedSize == ZSTD_CONTENTSIZE_ERROR || estimatedDecompressedSize == ZSTD_CONTENTSIZE_UNKNOWN) { + estimatedDecompressedSize = in_size * 2; // Use a fallback size + } + + std::string decompressedData; + decompressedData.reserve(estimatedDecompressedSize); + + const size_t bufferSize = ZSTD_DStreamOutSize(); // Recommended output buffer size + std::string outputBuffer(bufferSize, '\0'); + + while (input.pos < input.size && !(abort && *abort)) { + ZSTD_outBuffer output = {outputBuffer.data(), bufferSize, 0}; + + size_t result = ZSTD_decompressStream(dctx, &output, &input); + if (ZSTD_isError(result)) { + rWarning("decompressZST error: content is corrupt"); + break; + } + + decompressedData.append(outputBuffer.data(), output.pos); + } + + ZSTD_freeDCtx(dctx); + if (!(abort && *abort)) { + decompressedData.shrink_to_fit(); + return decompressedData; + } + return {}; +} + +void precise_nano_sleep(int64_t nanoseconds, std::atomic &interrupt_requested) { + struct timespec req, rem; + req.tv_sec = nanoseconds / 1000000000; + req.tv_nsec = nanoseconds % 1000000000; + while (!interrupt_requested) { +#ifdef __APPLE__ + int ret = nanosleep(&req, &rem); + if (ret == 0 || errno != EINTR) + break; +#else + int ret = clock_nanosleep(CLOCK_MONOTONIC, 0, &req, &rem); + if (ret == 0 || ret != EINTR) + break; +#endif + // Retry sleep if interrupted by a signal + req = rem; + } +} + +std::vector split(std::string_view source, char delimiter) { + std::vector fields; + size_t last = 0; + for (size_t i = 0; i < source.length(); ++i) { + if (source[i] == delimiter) { + fields.emplace_back(source.substr(last, i - last)); + last = i + 1; + } + } + fields.emplace_back(source.substr(last)); + return fields; +} + +std::string extractFileName(const std::string &file) { + size_t queryPos = file.find_first_of("?"); + std::string path = (queryPos != std::string::npos) ? file.substr(0, queryPos) : file; + size_t lastSlash = path.find_last_of("/\\"); + return (lastSlash != std::string::npos) ? path.substr(lastSlash + 1) : path; +} + +// MonotonicBuffer + +void *MonotonicBuffer::allocate(size_t bytes, size_t alignment) { + assert(bytes > 0); + void *p = std::align(alignment, bytes, current_buf, available); + if (p == nullptr) { + available = next_buffer_size = std::max(next_buffer_size, bytes); + current_buf = buffers.emplace_back(std::aligned_alloc(alignment, next_buffer_size)); + next_buffer_size *= growth_factor; + p = current_buf; + } + + current_buf = (char *)current_buf + bytes; + available -= bytes; + return p; +} + +MonotonicBuffer::~MonotonicBuffer() { + for (auto buf : buffers) { + free(buf); + } +} diff --git a/openpilot/tools/replay/util.h b/openpilot/tools/replay/util.h new file mode 100644 index 0000000000..03a15787b2 --- /dev/null +++ b/openpilot/tools/replay/util.h @@ -0,0 +1,67 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include "openpilot/cereal/messaging/messaging.h" + +enum CameraType { + RoadCam = 0, + DriverCam, + WideRoadCam +}; + +enum class ReplyMsgType { + Info, + Debug, + Warning, + Critical +}; + +typedef std::function ReplayMessageHandler; +void installMessageHandler(ReplayMessageHandler); +void logMessage(ReplyMsgType type, const char* fmt, ...); + +#define rInfo(fmt, ...) ::logMessage(ReplyMsgType::Info, fmt, ## __VA_ARGS__) +#define rDebug(fmt, ...) ::logMessage(ReplyMsgType::Debug, fmt, ## __VA_ARGS__) +#define rWarning(fmt, ...) ::logMessage(ReplyMsgType::Warning, fmt, ## __VA_ARGS__) +#define rError(fmt, ...) ::logMessage(ReplyMsgType::Critical , fmt, ## __VA_ARGS__) + +class MonotonicBuffer { +public: + MonotonicBuffer(size_t initial_size) : next_buffer_size(initial_size) {} + ~MonotonicBuffer(); + void *allocate(size_t bytes, size_t alignment = 16ul); + void deallocate(void *p) {} + +private: + void *current_buf = nullptr; + size_t next_buffer_size = 0; + size_t available = 0; + std::deque buffers; + static constexpr float growth_factor = 1.5; +}; + +void precise_nano_sleep(int64_t nanoseconds, std::atomic &interrupt_requested); +std::string decompressBZ2(const std::string &in, std::atomic *abort = nullptr); +std::string decompressBZ2(const std::byte *in, size_t in_size, std::atomic *abort = nullptr); +std::string decompressZST(const std::string &in, std::atomic *abort = nullptr); +std::string decompressZST(const std::byte *in, size_t in_size, std::atomic *abort = nullptr); +std::string getUrlWithoutQuery(const std::string &url); +std::string formattedDataSize(size_t size); +std::string extractFileName(const std::string& file); +std::vector split(std::string_view source, char delimiter); + +template +std::string join(const Iterable& elements, const std::string& separator) { + std::ostringstream oss; + for (auto it = elements.begin(); it != elements.end(); ++it) { + if (it != elements.begin()) oss << separator; + oss << *it; + } + return oss.str(); +} diff --git a/openpilot/tools/sim/README.md b/openpilot/tools/sim/README.md new file mode 100644 index 0000000000..b3e60a119b --- /dev/null +++ b/openpilot/tools/sim/README.md @@ -0,0 +1,50 @@ +openpilot in simulator +===================== + +openpilot implements a [bridge](run_bridge.py) that allows it to run in the [MetaDrive simulator](https://github.com/metadriverse/metadrive). + +## Launching openpilot +First, start openpilot. +``` bash +# Run locally +./openpilot/tools/sim/launch_openpilot.sh +``` + +## Bridge usage +``` +$ ./run_bridge.py -h +usage: run_bridge.py [-h] [--joystick] [--high_quality] [--dual_camera] +Bridge between the simulator and openpilot. + +options: + -h, --help show this help message and exit + --joystick + --high_quality + --dual_camera +``` + +#### Bridge Controls: +- To engage openpilot press 2, then press 1 to increase the speed and 2 to decrease. +- To disengage, press "S" (simulates a user brake) + +#### All inputs: + +``` +| key | functionality | +|------|-----------------------| +| 1 | Cruise Resume / Accel | +| 2 | Cruise Set / Decel | +| 3 | Cruise Cancel | +| r | Reset Simulation | +| i | Toggle Ignition | +| q | Exit all | +| wasd | Control manually | +``` + +## MetaDrive + +### Launching Metadrive +Start bridge processes located in openpilot/tools/sim: +``` bash +./run_bridge.py +``` \ No newline at end of file diff --git a/openpilot/tools/sim/__init__.py b/openpilot/tools/sim/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/openpilot/tools/sim/bridge/__init__.py b/openpilot/tools/sim/bridge/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/openpilot/tools/sim/bridge/common.py b/openpilot/tools/sim/bridge/common.py new file mode 100644 index 0000000000..1d00e3b0f9 --- /dev/null +++ b/openpilot/tools/sim/bridge/common.py @@ -0,0 +1,205 @@ +import signal +import threading +import functools +import numpy as np + +from collections import namedtuple +from enum import Enum +from multiprocessing import Process, Queue, Value +from abc import ABC, abstractmethod +from opendbc.car.honda.values import CruiseButtons +from openpilot.common.params import Params +from openpilot.common.realtime import Ratekeeper +from openpilot.selfdrive.test.helpers import set_params_enabled +from openpilot.tools.sim.lib.common import SimulatorState, World +from openpilot.tools.sim.lib.simulated_car import SimulatedCar +from openpilot.tools.sim.lib.simulated_sensors import SimulatedSensors + +QueueMessage = namedtuple("QueueMessage", ["type", "info"], defaults=[None]) + +class QueueMessageType(Enum): + START_STATUS = 0 + CONTROL_COMMAND = 1 + TERMINATION_INFO = 2 + CLOSE_STATUS = 3 + +def control_cmd_gen(cmd: str): + return QueueMessage(QueueMessageType.CONTROL_COMMAND, cmd) + +def rk_loop(function, hz, exit_event: threading.Event): + rk = Ratekeeper(hz, None) + while not exit_event.is_set(): + function() + rk.keep_time() + + +class SimulatorBridge(ABC): + TICKS_PER_FRAME = 5 + + def __init__(self, dual_camera, high_quality): + set_params_enabled() + self.params = Params() + self.params.put_bool("AlphaLongitudinalEnabled", True, block=True) + + self.rk = Ratekeeper(100, None) + + self.dual_camera = dual_camera + self.high_quality = high_quality + + self._exit_event: threading.Event | None = None + self._threads = [] + self._keep_alive = True + self.started = Value('i', False) + signal.signal(signal.SIGTERM, self._on_shutdown) + self.simulator_state = SimulatorState() + + self.world: World | None = None + + self.past_startup_engaged = False + self.startup_button_prev = True + + self.test_run = False + + def _on_shutdown(self, signal, frame): + self.shutdown() + + def shutdown(self): + self._keep_alive = False + + def bridge_keep_alive(self, q: Queue, retries: int): + try: + self._run(q) + finally: + self.close("bridge terminated") + + def close(self, reason): + self.started.value = False + + if self._exit_event is not None: + self._exit_event.set() + + if self.world is not None: + self.world.close(reason) + + def run(self, queue, retries=-1): + bridge_p = Process(name="bridge", target=self.bridge_keep_alive, args=(queue, retries)) + bridge_p.start() + return bridge_p + + def print_status(self): + print( + f""" +State: +Ignition: {self.simulator_state.ignition} Engaged: {self.simulator_state.is_engaged} + """) + + @abstractmethod + def spawn_world(self, q: Queue, /) -> World: + pass + + def _run(self, q: Queue): + self.world = self.spawn_world(q) + + self.simulated_car = SimulatedCar() + self.simulated_sensors = SimulatedSensors(self.dual_camera) + + self._exit_event = threading.Event() + + self.simulated_car_thread = threading.Thread(target=rk_loop, args=(functools.partial(self.simulated_car.update, self.simulator_state), + 100, self._exit_event)) + self.simulated_car_thread.start() + + self.simulated_camera_thread = threading.Thread(target=rk_loop, args=(functools.partial(self.simulated_sensors.send_camera_images, self.world), + 20, self._exit_event)) + self.simulated_camera_thread.start() + + # Simulation tends to be slow in the initial steps. This prevents lagging later + for _ in range(20): + self.world.tick() + + while self._keep_alive: + throttle_out = steer_out = brake_out = 0.0 + throttle_op = steer_op = brake_op = 0.0 + + self.simulator_state.cruise_button = 0 + self.simulator_state.left_blinker = False + self.simulator_state.right_blinker = False + + throttle_manual = steer_manual = brake_manual = 0. + + # Read manual controls + if not q.empty(): + message = q.get() + if message.type == QueueMessageType.CONTROL_COMMAND: + m = message.info.split('_') + if m[0] == "steer": + steer_manual = float(m[1]) + elif m[0] == "throttle": + throttle_manual = float(m[1]) + elif m[0] == "brake": + brake_manual = float(m[1]) + elif m[0] == "cruise": + if m[1] == "down": + self.simulator_state.cruise_button = CruiseButtons.DECEL_SET + elif m[1] == "up": + self.simulator_state.cruise_button = CruiseButtons.RES_ACCEL + elif m[1] == "cancel": + self.simulator_state.cruise_button = CruiseButtons.CANCEL + elif m[1] == "main": + self.simulator_state.cruise_button = CruiseButtons.MAIN + elif m[0] == "blinker": + if m[1] == "left": + self.simulator_state.left_blinker = True + elif m[1] == "right": + self.simulator_state.right_blinker = True + elif m[0] == "ignition": + self.simulator_state.ignition = not self.simulator_state.ignition + elif m[0] == "reset": + self.world.reset() + elif m[0] == "quit": + break + + self.simulator_state.user_brake = brake_manual + self.simulator_state.user_gas = throttle_manual + self.simulator_state.user_torque = steer_manual * -10000 + + steer_manual = steer_manual * -40 + + # Update openpilot on current sensor state + self.simulated_sensors.update(self.simulator_state, self.world) + + self.simulated_car.sm.update(0) + self.simulator_state.is_engaged = self.simulated_car.sm['selfdriveState'].active + + if self.simulator_state.is_engaged: + throttle_op = np.clip(self.simulated_car.sm['carControl'].actuators.accel / 1.6, 0.0, 1.0) + brake_op = np.clip(-self.simulated_car.sm['carControl'].actuators.accel / 4.0, 0.0, 1.0) + steer_op = self.simulated_car.sm['carControl'].actuators.steeringAngleDeg + + self.past_startup_engaged = True + elif not self.past_startup_engaged and self.simulated_car.sm['selfdriveState'].engageable: + self.simulator_state.cruise_button = CruiseButtons.DECEL_SET if self.startup_button_prev else CruiseButtons.MAIN # force engagement on startup + self.startup_button_prev = not self.startup_button_prev + + throttle_out = throttle_op if self.simulator_state.is_engaged else throttle_manual + brake_out = brake_op if self.simulator_state.is_engaged else brake_manual + steer_out = steer_op if self.simulator_state.is_engaged else steer_manual + + self.world.apply_controls(steer_out, throttle_out, brake_out) + self.world.read_state() + self.world.read_sensors(self.simulator_state) + + if self.world.exit_event.is_set(): + self.shutdown() + + if self.rk.frame % self.TICKS_PER_FRAME == 0: + self.world.tick() + self.world.read_cameras() + + # don't print during test, so no print/IO Block between OP and metadrive processes + if not self.test_run and self.rk.frame % 25 == 0: + self.print_status() + + self.started.value = True + + self.rk.keep_time() diff --git a/openpilot/tools/sim/bridge/metadrive/metadrive_bridge.py b/openpilot/tools/sim/bridge/metadrive/metadrive_bridge.py new file mode 100644 index 0000000000..4222ba45a7 --- /dev/null +++ b/openpilot/tools/sim/bridge/metadrive/metadrive_bridge.py @@ -0,0 +1,93 @@ +import math +from multiprocessing import Queue + +from metadrive.component.sensors.base_camera import _cuda_enable +from metadrive.component.map.pg_map import MapGenerateMethod + +from openpilot.tools.sim.bridge.common import SimulatorBridge +from openpilot.tools.sim.bridge.metadrive.metadrive_common import RGBCameraRoad, RGBCameraWide +from openpilot.tools.sim.bridge.metadrive.metadrive_world import MetaDriveWorld +from openpilot.tools.sim.lib.camerad import W, H + + +def straight_block(length): + return { + "id": "S", + "pre_block_socket_index": 0, + "length": length + } + +def curve_block(length, angle=45, direction=0): + return { + "id": "C", + "pre_block_socket_index": 0, + "length": length, + "radius": length, + "angle": angle, + "dir": direction + } + +def create_map(track_size=60): + curve_len = track_size * 2 + return { + "type": MapGenerateMethod.PG_MAP_FILE, + "lane_num": 2, + "lane_width": 4.5, + "config": [ + None, + straight_block(track_size), + curve_block(curve_len, 90), + straight_block(track_size), + curve_block(curve_len, 90), + straight_block(track_size), + curve_block(curve_len, 90), + straight_block(track_size), + curve_block(curve_len, 90), + ] + } + + +class MetaDriveBridge(SimulatorBridge): + TICKS_PER_FRAME = 5 + + def __init__(self, dual_camera, high_quality, test_duration=math.inf, test_run=False): + super().__init__(dual_camera, high_quality) + + self.should_render = False + self.test_run = test_run + self.test_duration = test_duration if self.test_run else math.inf + + def spawn_world(self, queue: Queue): + sensors = { + "rgb_road": (RGBCameraRoad, W, H, ) + } + + if self.dual_camera: + sensors["rgb_wide"] = (RGBCameraWide, W, H) + + config = { + "use_render": self.should_render, + "vehicle_config": { + "enable_reverse": False, + "render_vehicle": False, + "image_source": "rgb_road", + }, + "sensors": sensors, + "image_on_cuda": _cuda_enable, + "image_observation": True, + "interface_panel": [], + "out_of_route_done": False, + "on_continuous_line_done": False, + "crash_vehicle_done": False, + "crash_object_done": False, + "arrive_dest_done": False, + "traffic_density": 0.0, # traffic is incredibly expensive + "map_config": create_map(), + "decision_repeat": 1, + "physics_world_step_size": self.TICKS_PER_FRAME/100, + "preload_models": False, + "show_logo": False, + "anisotropic_filtering": False + } + + return MetaDriveWorld(queue, config, self.test_duration, self.test_run, self.dual_camera) diff --git a/tools/sim/bridge/metadrive/metadrive_common.py b/openpilot/tools/sim/bridge/metadrive/metadrive_common.py similarity index 82% rename from tools/sim/bridge/metadrive/metadrive_common.py rename to openpilot/tools/sim/bridge/metadrive/metadrive_common.py index 42a7eb60dd..0106579b20 100644 --- a/tools/sim/bridge/metadrive/metadrive_common.py +++ b/openpilot/tools/sim/bridge/metadrive/metadrive_common.py @@ -13,11 +13,9 @@ class CopyRamRGBCamera(RGBCamera): def get_rgb_array_cpu(self): origin_img = self.cpu_texture - img = np.frombuffer(origin_img.getRamImage().getData(), dtype=np.uint8) - img = img.reshape((origin_img.getYSize(), origin_img.getXSize(), -1)) - img = img[:,:,:3] # RGBA to RGB - # img = np.swapaxes(img, 1, 0) - img = img[::-1] # Flip on vertical axis + img = np.frombuffer(origin_img.getRamImageAs("RGB").getData(), dtype=np.uint8) + img = img.reshape((origin_img.getYSize(), origin_img.getXSize(), 3)) + img = img[::-1] # Flip on vertical axis return img diff --git a/tools/sim/bridge/metadrive/metadrive_process.py b/openpilot/tools/sim/bridge/metadrive/metadrive_process.py similarity index 100% rename from tools/sim/bridge/metadrive/metadrive_process.py rename to openpilot/tools/sim/bridge/metadrive/metadrive_process.py diff --git a/tools/sim/bridge/metadrive/metadrive_world.py b/openpilot/tools/sim/bridge/metadrive/metadrive_world.py similarity index 97% rename from tools/sim/bridge/metadrive/metadrive_world.py rename to openpilot/tools/sim/bridge/metadrive/metadrive_world.py index c5111289d0..54b461a46c 100644 --- a/tools/sim/bridge/metadrive/metadrive_world.py +++ b/openpilot/tools/sim/bridge/metadrive/metadrive_world.py @@ -97,7 +97,7 @@ class MetaDriveWorld(World): self.op_engaged.set() # check moving 5 seconds after engaged, doesn't move right away - after_engaged_check = is_engaged and time.monotonic() - self.first_engage >= 5 and self.test_run + after_engaged_check = is_engaged and self.first_engage is not None and time.monotonic() - self.first_engage >= 5 and self.test_run x_dist = abs(curr_pos[0] - self.vehicle_last_pos[0]) y_dist = abs(curr_pos[1] - self.vehicle_last_pos[1]) diff --git a/tools/sim/launch_openpilot.sh b/openpilot/tools/sim/launch_openpilot.sh similarity index 94% rename from tools/sim/launch_openpilot.sh rename to openpilot/tools/sim/launch_openpilot.sh index fa5ac731bd..ea3c4cb8f1 100755 --- a/tools/sim/launch_openpilot.sh +++ b/openpilot/tools/sim/launch_openpilot.sh @@ -6,7 +6,7 @@ export SIMULATION="1" export SKIP_FW_QUERY="1" export FINGERPRINT="HONDA_CIVIC_2022" -export BLOCK="${BLOCK},camerad,loggerd,encoderd,micd,logmessaged" +export BLOCK="${BLOCK},camerad,loggerd,encoderd,micd,logmessaged,manage_athenad,manage_sunnylinkd" if [[ "$CI" ]]; then # TODO: offscreen UI should work export BLOCK="${BLOCK},ui" diff --git a/openpilot/tools/sim/lib/__init__.py b/openpilot/tools/sim/lib/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/openpilot/tools/sim/lib/camerad.py b/openpilot/tools/sim/lib/camerad.py new file mode 100644 index 0000000000..8efb3e5dab --- /dev/null +++ b/openpilot/tools/sim/lib/camerad.py @@ -0,0 +1,78 @@ +import numpy as np + +from msgq.visionipc import VisionIpcServer, VisionStreamType +from openpilot.cereal import messaging + +from openpilot.tools.sim.lib.common import W, H + + +def rgb_to_nv12(rgb): + """Convert RGB image to NV12 (YUV420) format using BT.601 coefficients.""" + h, w = rgb.shape[:2] + r = rgb[:, :, 0].astype(np.int32) + g = rgb[:, :, 1].astype(np.int32) + b = rgb[:, :, 2].astype(np.int32) + + # Y plane - BT.601 coefficients (matches original OpenCL kernel) + y = (((b * 13 + g * 65 + r * 33) + 64) >> 7) + 16 + y = np.clip(y, 0, 255).astype(np.uint8) + + # Subsample RGB for UV (2x2 box filter) + r_sub = (r[0::2, 0::2] + r[0::2, 1::2] + r[1::2, 0::2] + r[1::2, 1::2] + 2) >> 2 + g_sub = (g[0::2, 0::2] + g[0::2, 1::2] + g[1::2, 0::2] + g[1::2, 1::2] + 2) >> 2 + b_sub = (b[0::2, 0::2] + b[0::2, 1::2] + b[1::2, 0::2] + b[1::2, 1::2] + 2) >> 2 + + # U and V planes + u = np.clip((b_sub * 56 - g_sub * 37 - r_sub * 19 + 0x8080) >> 8, 0, 255).astype(np.uint8) + v = np.clip((r_sub * 56 - g_sub * 47 - b_sub * 9 + 0x8080) >> 8, 0, 255).astype(np.uint8) + + # Interleave UV for NV12 format + uv = np.empty((h // 2, w), dtype=np.uint8) + uv[:, 0::2] = u + uv[:, 1::2] = v + + return np.concatenate([y.ravel(), uv.ravel()]).tobytes() + + +class Camerad: + """Simulates the camerad daemon""" + def __init__(self, dual_camera): + self.pm = messaging.PubMaster(['roadCameraState', 'wideRoadCameraState']) + + self.frame_road_id = 0 + self.frame_wide_id = 0 + self.vipc_server = VisionIpcServer("camerad") + + self.vipc_server.create_buffers(VisionStreamType.VISION_STREAM_ROAD, 5, W, H) + if dual_camera: + self.vipc_server.create_buffers(VisionStreamType.VISION_STREAM_WIDE_ROAD, 5, W, H) + + self.vipc_server.start_listener() + + def cam_send_yuv_road(self, yuv): + self._send_yuv(yuv, self.frame_road_id, 'roadCameraState', VisionStreamType.VISION_STREAM_ROAD) + self.frame_road_id += 1 + + def cam_send_yuv_wide_road(self, yuv): + self._send_yuv(yuv, self.frame_wide_id, 'wideRoadCameraState', VisionStreamType.VISION_STREAM_WIDE_ROAD) + self.frame_wide_id += 1 + + def rgb_to_yuv(self, rgb): + """Convert RGB to NV12 YUV format.""" + assert rgb.shape == (H, W, 3), f"{rgb.shape}" + assert rgb.dtype == np.uint8 + return rgb_to_nv12(rgb) + + def _send_yuv(self, yuv, frame_id, pub_type, yuv_type): + eof = int(frame_id * 0.05 * 1e9) + self.vipc_server.send(yuv_type, yuv, frame_id, eof, eof) + + dat = messaging.new_message(pub_type, valid=True) + msg = { + "frameId": frame_id, + "transform": [1.0, 0.0, 0.0, + 0.0, 1.0, 0.0, + 0.0, 0.0, 1.0] + } + setattr(dat, pub_type, msg) + self.pm.send(pub_type, dat) diff --git a/openpilot/tools/sim/lib/common.py b/openpilot/tools/sim/lib/common.py new file mode 100644 index 0000000000..eb29119fb4 --- /dev/null +++ b/openpilot/tools/sim/lib/common.py @@ -0,0 +1,100 @@ +import math +import multiprocessing +import numpy as np + +from abc import ABC, abstractmethod +from collections import namedtuple + +W, H = 1928, 1208 + + +vec3 = namedtuple("vec3", ["x", "y", "z"]) + +class GPSState: + def __init__(self): + self.latitude = 0 + self.longitude = 0 + self.altitude = 0 + + def from_xy(self, xy): + """Simulates a lat/lon from an xy coordinate on a plane, for simple simulation. TODO: proper global projection?""" + BASE_LAT = 32.75308505188913 + BASE_LON = -117.2095393365393 + DEG_TO_METERS = 100000 + + self.latitude = float(BASE_LAT + xy[0] / DEG_TO_METERS) + self.longitude = float(BASE_LON + xy[1] / DEG_TO_METERS) + self.altitude = 0 + + +class IMUState: + def __init__(self): + self.accelerometer: vec3 = vec3(0,0,0) + self.gyroscope: vec3 = vec3(0,0,0) + self.bearing: float = 0 + + +class SimulatorState: + def __init__(self): + self.valid = False + self.is_engaged = False + self.ignition = True + + self.velocity = vec3(0, 0, 0) + self.bearing: float = 0 + self.gps = GPSState() + self.imu = IMUState() + + self.steering_angle: float = 0 + + self.user_gas: float = 0 + self.user_brake: float = 0 + self.user_torque: float = 0 + + self.cruise_button = 0 + + self.left_blinker = False + self.right_blinker = False + + @property + def speed(self): + return math.sqrt(self.velocity.x ** 2 + self.velocity.y ** 2 + self.velocity.z ** 2) + + +class World(ABC): + def __init__(self, dual_camera): + self.dual_camera = dual_camera + + self.image_lock = multiprocessing.Semaphore(value=0) + self.road_image = np.zeros((H, W, 3), dtype=np.uint8) + self.wide_road_image = np.zeros((H, W, 3), dtype=np.uint8) + + self.exit_event = multiprocessing.Event() + + @abstractmethod + def apply_controls(self, steer_sim, throttle_out, brake_out, /): + pass + + @abstractmethod + def tick(self): + pass + + @abstractmethod + def read_state(self): + pass + + @abstractmethod + def read_sensors(self, simulator_state: SimulatorState, /): + pass + + @abstractmethod + def read_cameras(self): + pass + + @abstractmethod + def close(self, reason: str): + pass + + @abstractmethod + def reset(self): + pass diff --git a/tools/sim/lib/keyboard_ctrl.py b/openpilot/tools/sim/lib/keyboard_ctrl.py similarity index 100% rename from tools/sim/lib/keyboard_ctrl.py rename to openpilot/tools/sim/lib/keyboard_ctrl.py diff --git a/tools/sim/lib/manual_ctrl.py b/openpilot/tools/sim/lib/manual_ctrl.py similarity index 100% rename from tools/sim/lib/manual_ctrl.py rename to openpilot/tools/sim/lib/manual_ctrl.py diff --git a/tools/sim/lib/simulated_car.py b/openpilot/tools/sim/lib/simulated_car.py similarity index 91% rename from tools/sim/lib/simulated_car.py rename to openpilot/tools/sim/lib/simulated_car.py index ad0f4de5d0..9c430646f2 100644 --- a/tools/sim/lib/simulated_car.py +++ b/openpilot/tools/sim/lib/simulated_car.py @@ -1,5 +1,5 @@ import traceback -import cereal.messaging as messaging +import openpilot.cereal.messaging as messaging from opendbc.can.packer import CANPacker from opendbc.can.parser import CANParser @@ -11,7 +11,7 @@ from openpilot.tools.sim.lib.common import SimulatorState class SimulatedCar: """Simulates a honda civic 2022 (panda state + can messages) to OpenPilot""" - packer = CANPacker("honda_civic_ex_2022_can_generated") + packer = CANPacker("honda_bosch_radarless_generated") def __init__(self): self.pm = messaging.PubMaster(['can', 'pandaStates']) @@ -23,7 +23,7 @@ class SimulatedCar: @staticmethod def get_car_can_parser(): - dbc_f = 'honda_civic_ex_2022_can_generated' + dbc_f = 'honda_bosch_radarless_generated' checks = [] return CANParser(dbc_f, checks, 0) @@ -46,7 +46,7 @@ class SimulatedCar: msg.append(self.packer.make_can_msg("SCM_BUTTONS", 0, {"CRUISE_BUTTONS": simulator_state.cruise_button})) - msg.append(self.packer.make_can_msg("GEARBOX", 0, {"GEAR": 4, "GEAR_SHIFTER": 8})) + msg.append(self.packer.make_can_msg("GEARBOX_AUTO", 0, {"GEAR_SHIFTER": 4})) msg.append(self.packer.make_can_msg("GAS_PEDAL_2", 0, {})) msg.append(self.packer.make_can_msg("SEATBELT_STATUS", 0, {"SEATBELT_DRIVER_LATCHED": 1})) msg.append(self.packer.make_can_msg("STEER_STATUS", 0, {"STEER_TORQUE_SENSOR": simulator_state.user_torque})) @@ -56,7 +56,6 @@ class SimulatedCar: msg.append(self.packer.make_can_msg("STEER_MOTOR_TORQUE", 0, {})) msg.append(self.packer.make_can_msg("EPB_STATUS", 0, {})) msg.append(self.packer.make_can_msg("DOORS_STATUS", 0, {})) - msg.append(self.packer.make_can_msg("CRUISE_PARAMS", 0, {})) msg.append(self.packer.make_can_msg("CRUISE", 0, {})) msg.append(self.packer.make_can_msg("CRUISE_FAULT_STATUS", 0, {})) msg.append(self.packer.make_can_msg("SCM_FEEDBACK", 0, @@ -85,7 +84,7 @@ class SimulatedCar: if self.params.get_bool("ObdMultiplexingEnabled") != self.obd_multiplexing: self.obd_multiplexing = not self.obd_multiplexing - self.params.put_bool("ObdMultiplexingChanged", True) + self.params.put_bool("ObdMultiplexingChanged", True, block=True) dat = messaging.new_message('pandaStates', 1) dat.valid = True @@ -93,6 +92,8 @@ class SimulatedCar: 'ignitionLine': simulator_state.ignition, 'pandaType': "blackPanda", 'controlsAllowed': True, + 'controlsAllowedLateral': True, + 'controlsAllowedLongitudinal': True, 'safetyModel': 'hondaBosch', 'alternativeExperience': self.sm["carParams"].alternativeExperience, 'safetyParam': HondaSafetyFlags.RADARLESS.value | HondaSafetyFlags.BOSCH_LONG.value, diff --git a/tools/sim/lib/simulated_sensors.py b/openpilot/tools/sim/lib/simulated_sensors.py similarity index 89% rename from tools/sim/lib/simulated_sensors.py rename to openpilot/tools/sim/lib/simulated_sensors.py index e78f984736..63935d3068 100644 --- a/tools/sim/lib/simulated_sensors.py +++ b/openpilot/tools/sim/lib/simulated_sensors.py @@ -1,7 +1,7 @@ import time -from cereal import log -import cereal.messaging as messaging +from openpilot.cereal import log +import openpilot.cereal.messaging as messaging from openpilot.common.realtime import DT_DMON from openpilot.tools.sim.lib.camerad import Camerad @@ -23,17 +23,12 @@ class SimulatedSensors: def send_imu_message(self, simulator_state: 'SimulatorState'): for _ in range(5): dat = messaging.new_message('accelerometer', valid=True) - dat.accelerometer.sensor = 4 - dat.accelerometer.type = 0x10 dat.accelerometer.timestamp = dat.logMonoTime # TODO: use the IMU timestamp dat.accelerometer.init('acceleration') dat.accelerometer.acceleration.v = [simulator_state.imu.accelerometer.x, simulator_state.imu.accelerometer.y, simulator_state.imu.accelerometer.z] self.pm.send('accelerometer', dat) - # copied these numbers from locationd dat = messaging.new_message('gyroscope', valid=True) - dat.gyroscope.sensor = 5 - dat.gyroscope.type = 0x10 dat.gyroscope.timestamp = dat.logMonoTime # TODO: use the IMU timestamp dat.gyroscope.init('gyroUncalibrated') dat.gyroscope.gyroUncalibrated.v = [simulator_state.imu.gyroscope.x, simulator_state.imu.gyroscope.y, simulator_state.imu.gyroscope.z] @@ -53,7 +48,7 @@ class SimulatedSensors: for _ in range(10): dat = messaging.new_message('gpsLocationExternal', valid=True) dat.gpsLocationExternal = { - "unixTimestampMillis": int(time.time() * 1000), + "unixTimestampMillis": int(time.time() * 1000), # noqa: TID251 "flags": 1, # valid fix "horizontalAccuracy": 1.0, "verticalAccuracy": 1.0, @@ -92,11 +87,12 @@ class SimulatedSensors: # dmonitoringd output dat = messaging.new_message('driverMonitoringState', valid=True) - dat.driverMonitoringState = { - "faceDetected": True, - "isDistracted": False, - "awarenessStatus": 1., - } + dm = dat.driverMonitoringState + dm.alertLevel = log.DriverMonitoringState.AlertLevel.none + dm.activePolicy = log.DriverMonitoringState.MonitoringPolicy.vision + dm.visionPolicyState.faceDetected = True + dm.visionPolicyState.isDistracted = False + dm.visionPolicyState.awarenessPercent = 100 self.pm.send('driverMonitoringState', dat) def send_camera_images(self, world: 'World'): @@ -109,7 +105,7 @@ class SimulatedSensors: self.camerad.cam_send_yuv_wide_road(yuv) def update(self, simulator_state: 'SimulatorState', world: 'World'): - now = time.time() + now = time.monotonic() self.send_imu_message(simulator_state) self.send_gps_message(simulator_state) diff --git a/tools/sim/run_bridge.py b/openpilot/tools/sim/run_bridge.py similarity index 100% rename from tools/sim/run_bridge.py rename to openpilot/tools/sim/run_bridge.py diff --git a/openpilot/tools/sim/tests/__init__.py b/openpilot/tools/sim/tests/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tools/sim/tests/conftest.py b/openpilot/tools/sim/tests/conftest.py similarity index 100% rename from tools/sim/tests/conftest.py rename to openpilot/tools/sim/tests/conftest.py diff --git a/tools/sim/tests/test_metadrive_bridge.py b/openpilot/tools/sim/tests/test_metadrive_bridge.py similarity index 84% rename from tools/sim/tests/test_metadrive_bridge.py rename to openpilot/tools/sim/tests/test_metadrive_bridge.py index 04ce5d584f..9be640d736 100644 --- a/tools/sim/tests/test_metadrive_bridge.py +++ b/openpilot/tools/sim/tests/test_metadrive_bridge.py @@ -8,7 +8,6 @@ from openpilot.tools.sim.bridge.metadrive.metadrive_bridge import MetaDriveBridg from openpilot.tools.sim.tests.test_sim_bridge import TestSimBridgeBase @pytest.mark.slow -@pytest.mark.filterwarnings("ignore::pyopencl.CompilerWarning") # Unimportant warning of non-empty compile log class TestMetaDriveBridge(TestSimBridgeBase): @pytest.fixture(autouse=True) def setup_create_bridge(self, test_duration): diff --git a/tools/sim/tests/test_sim_bridge.py b/openpilot/tools/sim/tests/test_sim_bridge.py similarity index 97% rename from tools/sim/tests/test_sim_bridge.py rename to openpilot/tools/sim/tests/test_sim_bridge.py index d58cddff7f..f93cc2ef50 100644 --- a/tools/sim/tests/test_sim_bridge.py +++ b/openpilot/tools/sim/tests/test_sim_bridge.py @@ -5,11 +5,11 @@ import pytest from multiprocessing import Queue -from cereal import messaging +from openpilot.cereal import messaging from openpilot.common.basedir import BASEDIR from openpilot.tools.sim.bridge.common import QueueMessageType -SIM_DIR = os.path.join(BASEDIR, "tools/sim") +SIM_DIR = os.path.join(BASEDIR, "openpilot/tools/sim") class TestSimBridgeBase: @classmethod diff --git a/panda b/panda index c33cfa0803..61b050f1bd 160000 --- a/panda +++ b/panda @@ -1 +1 @@ -Subproject commit c33cfa0803deef5dc53d103ae1a2513e2ab94196 +Subproject commit 61b050f1bd36fad04d4ceccca8a72c92ee1422df diff --git a/pyproject.toml b/pyproject.toml index 591711b9db..d400ff5678 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,272 +1,212 @@ [project] name = "openpilot" -requires-python = ">= 3.11, < 3.13" +requires-python = ">= 3.12.3, < 3.13" license = {text = "MIT License"} version = "0.1.0" description = "an open source driver assistance system" authors = [ - {name ="Vehicle Researcher", email="user@comma.ai"} + {name = "Vehicle Researcher", email="user@comma.ai"} ] dependencies = [ # multiple users "sounddevice", # micd + soundd - "pyserial", # pigeond + qcomgpsd "requests", # many one-off uses - "sympy", # rednose + friends - "crcmod", # cars + qcomgpsd "tqdm", # cars (fw_versions.py) on start + many one-off uses - # hardwared - "smbus2", # configuring amp - # core - "cffi", "scons", - "pycapnp", + "pycapnp==2.1.0", # 2.2 introduces a memory leak due to cyclic references "Cython", - "setuptools", - "numpy >=2.0, <2.2", # Linting issues with mypy in 2.2 + "numpy >=2.0", - # body / webrtcd - "aiohttp", - "aiortc", - # aiortc does not put an upper bound on pyopenssl and is now incompatible - # with the latest release - "pyopenssl < 24.3.0", - "pyaudio", - - # panda - "libusb1", - "spidev; platform_system == 'Linux'", - - # modeld - "onnx >= 1.14.0", - "llvmlite", + # vendored native dependencies + "comma-deps-capnproto", + "comma-deps-catch2", + "comma-deps-acados", + "comma-deps-ffmpeg", + "comma-deps-zstd", + "comma-deps-zeromq", + "comma-deps-json11", + "comma-deps-git-lfs", + "comma-deps-gcc-arm-none-eabi", # logging "pyzmq", "sentry-sdk", - "xattr", # used in place of 'os.getxattr' for macos compatibility # athena - "PyJWT", - "json-rpc", + "PyJWT[crypto]", "websocket_client", - # acados deps - "casadi >=3.6.6", # 3.12 fixed in 3.6.6 - "future-fstrings", - # joystickd - "pygame", + "inputs", # these should be removed - "psutil", - "pycryptodome", # used in updated/casync, panda, body, and a test "setproctitle", # logreader "zstandard", # ui + "comma-deps-raylib", "qrcode", + "jeepney", + "pillow", ] [project.optional-dependencies] docs = [ - "Jinja2", - "natsort", - "mkdocs", + "zensical", ] testing = [ "coverage", "hypothesis ==6.47.*", - "mypy", + "ty", "pytest", - "pytest-cov", "pytest-cpp", "pytest-subtests", - # https://github.com/pytest-dev/pytest-xdist/issues/1215 - "pytest-xdist @ git+https://github.com/sshane/pytest-xdist@909e97b49d12401c10608f9d777bfc9dab8a4413", - "pytest-timeout", - "pytest-randomly", - "pytest-asyncio", + # https://github.com/pytest-dev/pytest-xdist/pull/1229 + "pytest-xdist @ git+https://github.com/sshane/pytest-xdist@2b4372bd62699fb412c4fe2f95bf9f01bd2018da", "pytest-mock", - "pytest-repeat", "ruff", "codespell", - "pre-commit-hooks", ] dev = [ - "av", - "azure-identity", - "azure-storage-blob", - "dbus-next", - "dictdiffer", "matplotlib", - "opencv-python-headless", - "parameterized >=0.8, <0.9", - "pyautogui", - "pyopencl; platform_machine != 'aarch64'", # broken on arm64 - "pytools < 2024.1.11; platform_machine != 'aarch64'", # pyopencl use a broken version - "pywinctl", - "pyprof2calltree", - "tabulate", - "types-requests", - "types-tabulate", - "raylib", ] tools = [ - "metadrive-simulator @ https://github.com/commaai/metadrive/releases/download/MetaDrive-minimal-0.4.2.4/metadrive_simulator-0.4.2.4-py3-none-any.whl ; (platform_machine != 'aarch64')", - "rerun-sdk >= 0.18", + "comma-deps-imgui", + "comma-deps-bzip2", + "comma-deps-bootstrap-icons", + "comma-deps-libusb", + "comma-deps-ncurses", + + # this can be added back once it's stripped down some more + #"metadrive-simulator @ git+https://github.com/commaai/metadrive.git@minimal ; (platform_machine != 'aarch64')", +] + +submodules = [ + "msgq", + "opendbc", + "pandacan", + "rednose", + "teleoprtc", + "tinygrad", ] [project.urls] Homepage = "https://github.com/commaai/openpilot" +[dependency-groups] +standalone = [ + "openpilot[submodules]", +] + [build-system] requires = ["hatchling"] build-backend = "hatchling.build" [tool.hatch.build.targets.wheel] -packages = [ "." ] +packages = [ + "openpilot", +] [tool.hatch.metadata] allow-direct-references = true [tool.pytest.ini_options] minversion = "6.0" -addopts = "--ignore=openpilot/ --ignore=opendbc/ --ignore=panda/ --ignore=rednose_repo/ --ignore=tinygrad_repo/ --ignore=teleoprtc_repo/ --ignore=msgq/ -Werror --strict-config --strict-markers --durations=10 -n auto --dist=loadgroup" +addopts = "-Werror --strict-config --strict-markers --durations=10 -n auto --dist=loadgroup" cpp_files = "test_*" -cpp_harness = "selfdrive/test/cpp_harness.py" +cpp_harness = "openpilot/selfdrive/test/cpp_harness.py" python_files = "test_*.py" -asyncio_default_fixture_loop_scope = "function" -#timeout = "30" # you get this long by default markers = [ "slow: tests that take awhile to run and can be skipped with -m 'not slow'", "tici: tests that are only meant to run on the C3/C3X", - "skip_tici_setup: mark test to skip tici setup fixture" + "skip_tici_setup: mark test to skip tici setup fixture", + "nocapture: don't capture test output", + "shared_download_cache: share download cache between tests", + "xdist_group_class_property: group tests by a property of the class that contains them", ] testpaths = [ - "common", - "selfdrive", - "system/updated", - "system/athena", - "system/camerad", - "system/hardware", - "system/loggerd", - "system/proclogd", - "system/tests", - "system/ubloxd", - "system/webrtc", - "tools/lib/tests", - "tools/replay", - "tools/cabana", - "cereal/messaging/tests", - "sunnypilot", + "openpilot", ] [tool.codespell] quiet-level = 3 # if you've got a short variable name that's getting flagged, add it here -ignore-words-list = "bu,ro,te,ue,alo,hda,ois,nam,nams,ned,som,parm,setts,inout,warmup,bumb,nd,sie,preints,whit,indexIn,ws,uint,grey,deque,stdio,amin,BA,LITE,atEnd,UIs,errorString,arange,FocusIn,od,tim,relA,hist,copyable,jupyter,thead,TGE,abl,lite" +ignore-words-list = "bu,ro,te,ue,alo,hda,ois,nam,nams,ned,som,parm,setts,inout,warmup,bumb,nd,sie,preints,whit,indexIn,ws,uint,grey,deque,stdio,amin,BA,LITE,atEnd,UIs,errorString,arange,FocusIn,od,tim,relA,hist,copyable,jupyter,thead,TGE,abl,lite,ser" builtin = "clear,rare,informal,code,names,en-GB_to_en-US" -skip = "./third_party/*, ./tinygrad/*, ./tinygrad_repo/*, ./msgq/*, ./panda/*, ./opendbc/*, ./opendbc_repo/*, ./rednose/*, ./rednose_repo/*, ./teleoprtc/*, ./teleoprtc_repo/*, *.ts, uv.lock, *.onnx, ./cereal/gen/*, */c_generated_code/*, docs/assets/*" +skip = "*.po, uv.lock, *.onnx, *.pem, */c_generated_code/*, docs/assets/*, openpilot/tools/plotjuggler/layouts/*, openpilot/selfdrive/assets/offroad/mici_fcc.html, ./openpilot/third_party/*, ./openpilot/cereal/gen/*" -[tool.mypy] -python_version = "3.11" -plugins = [ - "numpy.typing.mypy_plugin", -] -exclude = [ - "cereal/", - "msgq/", - "msgq_repo/", - "opendbc/", - "opendbc_repo/", - "panda/", - "rednose/", - "rednose_repo/", - "tinygrad/", - "tinygrad_repo/", - "teleoprtc/", - "teleoprtc_repo/", - "third_party/", -] - -# third-party packages -ignore_missing_imports=true - -# helpful warnings -warn_redundant_casts=true -warn_unreachable=true -warn_unused_ignores=true - -# restrict dynamic typing -warn_return_any=true - -# allow implicit optionals for default args -implicit_optional = true - -local_partial_types=true -explicit_package_bases=true -disable_error_code = "annotation-unchecked" - -# https://beta.ruff.rs/docs/configuration/#using-pyprojecttoml +# https://docs.astral.sh/ruff/configuration/#using-pyprojecttoml [tool.ruff] indent-width = 2 lint.select = [ "E", "F", "W", "PIE", "C4", "ISC", "A", "B", "NPY", # numpy "UP", # pyupgrade + "ASYNC", + "B904", "B905", + "PLC0207", "TRY203", "TRY400", "TRY401", # try/excepts - "RUF008", "RUF100", + "RUF006", "RUF008", "RUF009", "RUF061", "RUF064", "RUF100", "RUF102", "RUF103", "RUF104", "TID251", - "PLR1704", + "PLE", "PLR1704", ] lint.ignore = [ "E741", "E402", - "C408", - "ISC003", "B027", - "B024", - "NPY002", # new numpy random syntax is worse - "UP038", # (x, y) -> x|y for isinstance + "UP007", # this doesn't play nice with raylib atm ] line-length = 160 -target-version ="py311" exclude = [ - "body", - "cereal", - "panda", - "opendbc", - "opendbc_repo", - "rednose_repo", - "tinygrad_repo", - "teleoprtc", - "teleoprtc_repo", - "third_party", + "openpilot/cereal", + "openpilot/third_party", "*.ipynb", + "generated", ] lint.flake8-implicit-str-concat.allow-multiline = false [tool.ruff.lint.flake8-tidy-imports.banned-api] -"selfdrive".msg = "Use openpilot.selfdrive" -"common".msg = "Use openpilot.common" -"system".msg = "Use openpilot.system" -"third_party".msg = "Use openpilot.third_party" -"tools".msg = "Use openpilot.tools" "pytest.main".msg = "pytest.main requires special handling that is easy to mess up!" -"unittest".msg = "Use pytest" -"pyray.measure_text_ex".msg = "Use openpilot.system.ui.lib.text_measure" +"time.time".msg = "Use time.monotonic" # time.time can skip due to its reference clock, you probably want a monotonic clock -[tool.coverage.run] -concurrency = ["multiprocessing", "thread"] +# raylib banned APIs +"pyray.measure_text_ex".msg = "Use openpilot.system.ui.lib.text_measure" +"pyray.is_mouse_button_pressed".msg = "This can miss events. Use Widget._handle_mouse_press" +"pyray.is_mouse_button_released".msg = "This can miss events. Use Widget._handle_mouse_release" +"pyray.draw_text".msg = "Use a function (such as rl.draw_font_ex) that takes font as an argument" +"pyray.draw_texture".msg = "Use rl.draw_texture_ex for float position support" [tool.ruff.format] quote-style = "preserve" + +[tool.ty.src] +exclude = [ + "openpilot/third_party/", +] + +[tool.ty.rules] +unresolved-import = "ignore" # Cython-compiled modules (.pyx) +unresolved-attribute = "ignore" # many from capnp and Cython modules + +[tool.uv] +python-preference = "only-managed" +default-groups = ["standalone"] +override-dependencies = [ + "opendbc", # panda pins opendbc from git for standalone use; always use our submodule +] + +[tool.uv.sources] +msgq = { path = "msgq_repo", editable = true } +opendbc = { path = "opendbc_repo", editable = true } +pandacan = { path = "panda", editable = true } +rednose = { path = "rednose_repo", editable = true } +teleoprtc = { path = "teleoprtc_repo", editable = true } +tinygrad = { path = "tinygrad_repo", editable = true } diff --git a/rednose b/rednose deleted file mode 120000 index 674cfec35f..0000000000 --- a/rednose +++ /dev/null @@ -1 +0,0 @@ -rednose_repo/rednose \ No newline at end of file diff --git a/rednose_repo b/rednose_repo index 7fddc8e6d4..9e19086c26 160000 --- a/rednose_repo +++ b/rednose_repo @@ -1 +1 @@ -Subproject commit 7fddc8e6d49def83c952a78673179bdc62789214 +Subproject commit 9e19086c26ca35708870d50ebcf237d65d0b163e diff --git a/release/README.md b/release/README.md deleted file mode 100644 index 06404be6ab..0000000000 --- a/release/README.md +++ /dev/null @@ -1,31 +0,0 @@ -# openpilot releases - -``` -## release checklist - -**Go to `devel-staging`** -- [ ] update RELEASES.md -- [ ] update `devel-staging`: `git reset --hard origin/master-ci` -- [ ] open a pull request from `devel-staging` to `devel` -- [ ] post on Discord - -**Go to `devel`** -- [ ] bump version on master: `common/version.h` and `RELEASES.md` -- [ ] before merging the pull request - - [ ] update from previous release -> new release - - [ ] update from new release -> previous release - - [ ] fresh install with `openpilot-test.comma.ai` - - [ ] drive on fresh install - - [ ] no submodules or LFS - - [ ] check sentry, MTBF, etc. - -**Go to `release3`** -- [ ] publish the blog post -- [ ] `git reset --hard origin/release3-staging` -- [ ] tag the release: `git tag v0.X.X && git push origin v0.X.X` -- [ ] create GitHub release -- [ ] final test install on `openpilot.comma.ai` -- [ ] update factory provisioning -- [ ] close out milestone -- [ ] post on Discord, X, etc. -``` diff --git a/release/build_devel.sh b/release/build_devel.sh deleted file mode 100755 index 05dcaafcaa..0000000000 --- a/release/build_devel.sh +++ /dev/null @@ -1,91 +0,0 @@ -#!/usr/bin/env bash -set -ex - -DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null && pwd)" - -SOURCE_DIR="$(git -C $DIR rev-parse --show-toplevel)" -if [ -z "$TARGET_DIR" ]; then - TARGET_DIR="$(mktemp -d)" -fi - -# set git identity -source $DIR/identity.sh - -echo "[-] Setting up target repo T=$SECONDS" - -rm -rf $TARGET_DIR -mkdir -p $TARGET_DIR -cd $TARGET_DIR -cp -r $SOURCE_DIR/.git $TARGET_DIR -pre-commit uninstall || true - -echo "[-] bringing __nightly and devel in sync T=$SECONDS" -cd $TARGET_DIR - -git fetch --depth 1 origin __nightly -git fetch --depth 1 origin devel - -git checkout -f --track origin/__nightly -git reset --hard __nightly -git checkout __nightly -git reset --hard origin/devel -git clean -xdff -git lfs uninstall - -# remove everything except .git -echo "[-] erasing old openpilot T=$SECONDS" -find . -maxdepth 1 -not -path './.git' -not -name '.' -not -name '..' -exec rm -rf '{}' \; - -# reset source tree -cd $SOURCE_DIR -git clean -xdff - -# do the files copy -echo "[-] copying files T=$SECONDS" -cd $SOURCE_DIR -cp -pR --parents $(./release/release_files.py) $TARGET_DIR/ - -# in the directory -cd $TARGET_DIR -rm -f panda/board/obj/panda.bin.signed - -# include source commit hash and build date in commit -GIT_HASH=$(git --git-dir=$SOURCE_DIR/.git rev-parse HEAD) -GIT_COMMIT_DATE=$(git --git-dir=$SOURCE_DIR/.git show --no-patch --format='%ct %ci' HEAD) -DATETIME=$(date '+%Y-%m-%dT%H:%M:%S') -VERSION=$(cat $SOURCE_DIR/common/version.h | awk -F\" '{print $2}') - -echo -n "$GIT_HASH" > git_src_commit -echo -n "$GIT_COMMIT_DATE" > git_src_commit_date - -echo "[-] committing version $VERSION T=$SECONDS" -git add -f . -git status -git commit -a -m "openpilot v$VERSION release - -date: $DATETIME -master commit: $GIT_HASH -" - -# should be no submodules or LFS files -git submodule status -if [ ! -z "$(git lfs ls-files)" ]; then - echo "LFS files detected!" - exit 1 -fi - -# ensure files are within GitHub's limit -BIG_FILES="$(find . -type f -not -path './.git/*' -size +95M)" -if [ ! -z "$BIG_FILES" ]; then - printf '\n\n\n' - echo "Found files exceeding GitHub's 100MB limit:" - echo "$BIG_FILES" - exit 1 -fi - -if [ ! -z "$BRANCH" ]; then - echo "[-] Pushing to $BRANCH T=$SECONDS" - git push -f origin __nightly:$BRANCH -fi - -echo "[-] done T=$SECONDS, ready at $TARGET_DIR" diff --git a/release/build_release.sh b/release/build_release.sh deleted file mode 100755 index 5ada9c5ecc..0000000000 --- a/release/build_release.sh +++ /dev/null @@ -1,103 +0,0 @@ -#!/usr/bin/env bash -set -e -set -x - -# git diff --name-status origin/release3-staging | grep "^A" | less - -DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null && pwd)" - -cd $DIR - -BUILD_DIR=/data/openpilot -SOURCE_DIR="$(git rev-parse --show-toplevel)" - -if [ -z "$RELEASE_BRANCH" ]; then - echo "RELEASE_BRANCH is not set" - exit 1 -fi - - -# set git identity -source $DIR/identity.sh - -echo "[-] Setting up repo T=$SECONDS" -rm -rf $BUILD_DIR -mkdir -p $BUILD_DIR -cd $BUILD_DIR -git init -git remote add origin git@github.com:commaai/openpilot.git -git checkout --orphan $RELEASE_BRANCH - -# do the files copy -echo "[-] copying files T=$SECONDS" -cd $SOURCE_DIR -cp -pR --parents $(./release/release_files.py) $BUILD_DIR/ - -# in the directory -cd $BUILD_DIR - -rm -f panda/board/obj/panda.bin.signed -rm -f panda/board/obj/panda_h7.bin.signed - -VERSION=$(cat common/version.h | awk -F[\"-] '{print $2}') -echo "[-] committing version $VERSION T=$SECONDS" -git add -f . -git commit -a -m "openpilot v$VERSION release" - -# Build -export PYTHONPATH="$BUILD_DIR" -scons -j$(nproc) --minimal - -if [ -z "$PANDA_DEBUG_BUILD" ]; then - # release panda fw - CERT=/data/pandaextra/certs/release RELEASE=1 scons -j$(nproc) panda/ -else - # build with ALLOW_DEBUG=1 to enable features like experimental longitudinal - scons -j$(nproc) panda/ -fi - -# Ensure no submodules in release -if test "$(git submodule--helper list | wc -l)" -gt "0"; then - echo "submodules found:" - git submodule--helper list - exit 1 -fi -git submodule status - -# Cleanup -find . -name '*.a' -delete -find . -name '*.o' -delete -find . -name '*.os' -delete -find . -name '*.pyc' -delete -find . -name 'moc_*' -delete -find . -name '__pycache__' -delete -rm -rf .sconsign.dblite Jenkinsfile release/ -rm selfdrive/modeld/models/driving_vision.onnx -rm selfdrive/modeld/models/driving_policy.onnx -rm sunnypilot/modeld*/models/supercombo.onnx - -find third_party/ -name '*x86*' -exec rm -r {} + -find third_party/ -name '*Darwin*' -exec rm -r {} + - - -# Restore third_party -git checkout third_party/ - -# Mark as prebuilt release -touch prebuilt - -# Add built files to git -git add -f . -git commit --amend -m "openpilot v$VERSION" - -# Run tests -cd $BUILD_DIR -RELEASE=1 pytest -n0 -s selfdrive/test/test_onroad.py -#pytest selfdrive/car/tests/test_car_interfaces.py - -if [ ! -z "$RELEASE_BRANCH" ]; then - echo "[-] pushing release T=$SECONDS" - git push -f origin $RELEASE_BRANCH:$RELEASE_BRANCH -fi - -echo "[-] done T=$SECONDS" diff --git a/release/check-submodules.sh b/release/check-submodules.sh deleted file mode 100755 index 93869a7403..0000000000 --- a/release/check-submodules.sh +++ /dev/null @@ -1,17 +0,0 @@ -#!/usr/bin/env bash - -while read hash submodule ref; do - if [ "$submodule" = "tinygrad_repo" ]; then - echo "Skipping $submodule" - continue - fi - - git -C $submodule fetch --depth 100 origin master - git -C $submodule branch -r --contains $hash | grep "origin/master" - if [ "$?" -eq 0 ]; then - echo "$submodule ok" - else - echo "$submodule: $hash is not on master" - exit 1 - fi -done <<< $(git submodule status --recursive) diff --git a/release/ci/docker_build_sp.sh b/release/ci/docker_build_sp.sh new file mode 100755 index 0000000000..369daf5233 --- /dev/null +++ b/release/ci/docker_build_sp.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +set -e + +SCRIPT_DIR=$(dirname "$0") +OPENPILOT_DIR=$SCRIPT_DIR/../../ + +DOCKER_IMAGE=sunnypilot +DOCKER_FILE=Dockerfile.openpilot +DOCKER_REGISTRY=ghcr.io/sunnypilot +COMMIT_SHA=$(git rev-parse HEAD) + +if [ -n "$TARGET_ARCHITECTURE" ]; then + PLATFORM="linux/$TARGET_ARCHITECTURE" + TAG_SUFFIX="-$TARGET_ARCHITECTURE" +else + PLATFORM="linux/$(uname -m)" + TAG_SUFFIX="" +fi + +LOCAL_TAG=$DOCKER_IMAGE$TAG_SUFFIX +REMOTE_TAG=$DOCKER_REGISTRY/$LOCAL_TAG +REMOTE_SHA_TAG=$DOCKER_REGISTRY/$LOCAL_TAG:$COMMIT_SHA + +DOCKER_BUILDKIT=1 docker buildx build --provenance false --pull --platform $PLATFORM --load -t $DOCKER_IMAGE:latest -t $REMOTE_TAG -t $LOCAL_TAG -f $OPENPILOT_DIR/$DOCKER_FILE $OPENPILOT_DIR + +if [ -n "$PUSH_IMAGE" ]; then + docker push $REMOTE_TAG + docker tag $REMOTE_TAG $REMOTE_SHA_TAG + docker push $REMOTE_SHA_TAG +fi diff --git a/release/ci/install_github_runner.sh b/release/ci/install_github_runner.sh index f6b1e217c5..9f11e4841c 100755 --- a/release/ci/install_github_runner.sh +++ b/release/ci/install_github_runner.sh @@ -5,6 +5,7 @@ set -e DEFAULT_REPO_URL="https://github.com/sunnypilot" START_AT_BOOT=false RESTORE_MODE=false +RUNNER_VERSION="2.325.0" # Parse command line arguments while [[ $# -gt 0 ]]; do @@ -108,9 +109,9 @@ setup_system_configs() { install_runner() { echo "Downloading and setting up runner..." cd "$RUNNER_DIR" - curl -o actions-runner-linux-arm64-2.322.0.tar.gz -L https://github.com/actions/runner/releases/download/v2.322.0/actions-runner-linux-arm64-2.322.0.tar.gz - sudo -u ${RUNNER_USER} tar -xzf ./actions-runner-linux-arm64-2.322.0.tar.gz - sudo rm ./actions-runner-linux-arm64-2.322.0.tar.gz + curl -o actions-runner-linux-arm64-${RUNNER_VERSION}.tar.gz -L https://github.com/actions/runner/releases/download/v${RUNNER_VERSION}/actions-runner-linux-arm64-${RUNNER_VERSION}.tar.gz + sudo -u ${RUNNER_USER} tar -xzf ./actions-runner-linux-arm64-${RUNNER_VERSION}.tar.gz + sudo rm ./actions-runner-linux-arm64-${RUNNER_VERSION}.tar.gz sudo chmod +x ./config.sh } @@ -149,25 +150,32 @@ EOL } install_service() { + local service_name + if [ -f "${RUNNER_DIR}/.service" ]; then + service_name=$(cat "${RUNNER_DIR}/.service") + else + service_name="actions.runner.sunnypilot.$(uname -n)" + fi + + create_service_template remount_rw + local service_path="/etc/systemd/system/${service_name}" echo "Installing systemd service..." + if [ -f "${service_path}" ]; then + echo "Service ${service_path} found in systemd, we will delete it" + sudo rm -f "${service_path}" + fi + cd "$RUNNER_DIR" sudo ./svc.sh install $RUNNER_USER if [ "$START_AT_BOOT" = false ]; then - local service_name - if [ -f "${RUNNER_DIR}/.service" ]; then - service_name=$(cat "${RUNNER_DIR}/.service") - else - service_name="actions.runner.sunnypilot.$(uname -n)" - fi sudo systemctl disable "${service_name}" fi remount_ro } check_restore_prerequisites() { - local needs_restore=false local can_restore=false local service_name="" @@ -189,25 +197,16 @@ check_restore_prerequisites() { exit 1 fi - # Then check if restoration is needed (if either service or user is missing) - if ! systemctl list-unit-files "${service_name}" &>/dev/null; then - echo "Service ${service_name} not found in systemd" - needs_restore=true - fi - if ! id "${RUNNER_USER}" &>/dev/null; then echo "User ${RUNNER_USER} does not exist" - needs_restore=true fi # Only proceed if we can restore AND need to restore - if [ "$can_restore" = true ] && [ "$needs_restore" = true ]; then - echo "Restoration is needed and possible" + if [ "$can_restore" = true ]; then + echo "Restoration is possible" return 0 else - if [ "$needs_restore" = false ]; then - echo "System is already properly configured (user and service exist)" - fi + echo "No restoration possible" exit 0 fi } @@ -226,7 +225,6 @@ perform_install() { setup_system_configs install_runner set_directory_permissions - create_service_template configure_runner install_service echo "Installation completed successfully" diff --git a/release/ci/model_generator.py b/release/ci/model_generator.py index 069b8e41af..afee782beb 100755 --- a/release/ci/model_generator.py +++ b/release/ci/model_generator.py @@ -1,4 +1,12 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" + import os +import pickle import sys import hashlib import json @@ -6,6 +14,44 @@ import re from pathlib import Path from datetime import datetime, UTC +REQUIRED_OUTPUT_KEYS = frozenset({ + "plan", + "lane_lines", + "road_edges", + "lead", + "desire_state", + "desire_pred", + "meta", + "lead_prob", + "lane_lines_prob", + "pose", + "wide_from_device_euler", + "road_transform", + "hidden_state", +}) +OPTIONAL_OUTPUT_KEYS = frozenset({ + "planplus", + "sim_pose", + "desired_curvature", +}) + + +def validate_model_outputs(metadata_paths: list[Path]) -> None: + combined_keys: set[str] = set() + for path in metadata_paths: + if path.stat().st_size == 0: + print(f"skipping empty metadata: {path}") + continue + with open(path, "rb") as f: + metadata = pickle.load(f) + combined_keys.update(metadata.get("output_slices", {}).keys()) + missing = REQUIRED_OUTPUT_KEYS - combined_keys + if missing: + raise ValueError(f"Combined model metadata is missing required output keys: {sorted(missing)}") + detected_optional = sorted(OPTIONAL_OUTPUT_KEYS & combined_keys) + if detected_optional: + print(f"Optional output keys detected: {detected_optional}") + def create_short_name(full_name): # Remove parentheses and extract alphanumeric words @@ -13,67 +59,108 @@ def create_short_name(full_name): words = [re.sub(r'[^a-zA-Z0-9]', '', word) for word in clean_name.split() if re.sub(r'[^a-zA-Z0-9]', '', word)] if len(words) == 1: - # If there's only one word, return it as is, lowercased, truncated to 8 characters - truncated = words[0][:8] - return truncated.lower() if truncated.isupper() else truncated + return words[0][:8].upper() # Handle special case: Name + Version (e.g., "Word A1" -> "WordA1") if len(words) == 2 and re.match(r'^[A-Za-z]\d+$', words[1]): - first_word = words[0].lower() if words[0].isupper() else words[0] - return (first_word + words[1])[:8] + return (words[0] + words[1])[:8].upper() - # Normal case: first letter and trailing numbers from each word - result = ''.join(word if word.isdigit() else word[0] + (re.search(r'\d+$', word) or [''])[0] for word in words) + result = "" + for word in words: + # Version or number patterns + if (re.match(r'^\d+[a-zA-Z]+$', word) or + re.match(r'^\d+[vVbB]\d+$', word) or + re.match(r'^[vVbB]\d+$', word) or + re.match(r'^\d{4}$', word)): + result += word.upper() + # All uppercase abbreviations (2-3 letters) + elif re.match(r'^[A-Z]{2,3}$', word): + result += word + # Letters+digits (for example tr15 rev2) + elif re.match(r'^[a-zA-Z]+[0-9]+$', word): + result += word[0].upper() + ''.join(re.findall(r'\d+', word)) + elif word.isalpha(): + result += word[0].upper() + elif word.isdigit(): + result += word + else: + result += word[0].upper() return result[:8] -def generate_metadata(model_path: Path, output_dir: Path, short_name: str): - model_path = model_path - output_path = output_dir +def _read_pkl_bytes(pkl_path: Path) -> bytes: + manifest = Path(f"{pkl_path}.chunkmanifest") + if manifest.exists(): + num_chunks = int(manifest.read_text().strip()) + parts = [] + for i in range(num_chunks): + chunk = Path(f"{pkl_path}.chunk{i + 1:02d}of{num_chunks:02d}") + parts.append(chunk.read_bytes()) + return b''.join(parts) + return pkl_path.read_bytes() + + +def _find_driving_pkl(output_path: Path) -> Path | None: + for pattern in ('driving_tinygrad.pkl', 'driving_*_tinygrad.pkl'): + matches = sorted(output_path.glob(pattern)) + if matches: + return matches[0] + for pattern in ('driving_tinygrad.pkl.chunkmanifest', 'driving_*_tinygrad.pkl.chunkmanifest'): + matches = sorted(output_path.glob(pattern)) + if matches: + return Path(str(matches[0]).removesuffix('.chunkmanifest')) + return None + + +def _rename_pkl_with_chunks(old_pkl: Path, new_pkl: Path) -> Path: + manifest = Path(f"{old_pkl}.chunkmanifest") + if manifest.exists(): + for f in sorted(old_pkl.parent.glob(f"{old_pkl.name}.chunk*")): + f.rename(old_pkl.parent / f.name.replace(old_pkl.name, new_pkl.name, 1)) + return new_pkl + return old_pkl.rename(new_pkl) + + +def generate_metadata(model_path: Path, output_dir: Path, short_name: str, driving_pkl: Path): base = model_path.stem + metadata_file = output_dir / f"{base}_metadata.pkl" - # Define output files for tinygrad and metadata - tinygrad_file = output_path / f"{base}_tinygrad.pkl" - metadata_file = output_path / f"{base}_metadata.pkl" + if short_name: + renamed_meta = output_dir / f"{base}_{short_name.lower()}_metadata.pkl" + if metadata_file.exists() and not renamed_meta.exists(): + metadata_file = metadata_file.rename(renamed_meta) + elif renamed_meta.exists(): + metadata_file = renamed_meta - if not tinygrad_file.exists() or not metadata_file.exists(): - print(f"Error: Missing files for model {base} ({tinygrad_file} or {metadata_file})", file=sys.stderr) + if not metadata_file.exists(): + print(f"Warning: Missing metadata for {base} ({metadata_file}), skipping", file=sys.stderr) return - # Calculate the sha256 hashes - with open(tinygrad_file, 'rb') as f: - tinygrad_hash = hashlib.sha256(f.read()).hexdigest() + tinygrad_hash = hashlib.sha256(_read_pkl_bytes(driving_pkl)).hexdigest() with open(metadata_file, 'rb') as f: metadata_hash = hashlib.sha256(f.read()).hexdigest() - # Rename the files if a custom file name is provided - if short_name: - tinygrad_file = tinygrad_file.rename(output_path / f"{base}_{short_name.lower()}_tinygrad.pkl") - metadata_file = metadata_file.rename(output_path / f"{base}_{short_name.lower()}_metadata.pkl") + model_type = "offPolicy" if "off_policy" in base else "onPolicy" if "on_policy" in base else base.split("_")[-1] - # Build the metadata structure - model_metadata = { - "type": base.split("_")[-1] if "dmonitoring" not in base else "dmonitoring", + return { + "type": model_type, "artifact": { - "file_name": tinygrad_file.name, + "file_name": driving_pkl.name, "download_uri": { - "url": "https://gitlab.com/sunnypilot/public/docs.sunnypilot.ai/-/raw/main/", + "url": "https://gitlab.com/sunnypilot/public/docs.sunnypilot.ai/-/raw/main/", "sha256": tinygrad_hash } }, "metadata": { "file_name": metadata_file.name, "download_uri": { - "url": "https://gitlab.com/sunnypilot/public/docs.sunnypilot.ai/-/raw/main/", + "url": "https://gitlab.com/sunnypilot/public/docs.sunnypilot.ai/-/raw/main/", "sha256": metadata_hash } } } - # Return model metadata - return model_metadata - def create_metadata_json(models: list, output_dir: Path, custom_name=None, short_name=None, is_20hz=False, upstream_branch="unknown"): metadata_json = { @@ -83,12 +170,12 @@ def create_metadata_json(models: list, output_dir: Path, custom_name=None, short "ref": upstream_branch, "environment": "development", "runner": "tinygrad", - "build_time": datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ"), - "models": models, - "overrides": {}, "index": -1, "minimum_selector_version": "-1", "generation": "-1", + "build_time": datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ"), + "overrides": {}, + "models": models, } # Write metadata to output_dir @@ -107,9 +194,19 @@ if __name__ == "__main__": parser.add_argument("--output-dir", default="./output", help="Output directory for metadata") parser.add_argument("--custom-name", help="Custom display name for the model") parser.add_argument("--is-20hz", action="store_true", help="Whether this is a 20Hz model") + parser.add_argument("--validate-only", action="store_true") parser.add_argument("--upstream-branch", default="unknown", help="Upstream branch name") args = parser.parse_args() + if args.validate_only: + metadata_paths = glob.glob(os.path.join(args.model_dir, "*_metadata.pkl")) + if not metadata_paths: + print(f"No metadata files found in {args.model_dir}", file=sys.stderr) + sys.exit(1) + validate_model_outputs([Path(p) for p in metadata_paths]) + print(f"Validated {len(metadata_paths)} metadata files successfully.") + sys.exit(0) + # Find all ONNX files in the given directory model_paths = glob.glob(os.path.join(args.model_dir, "*.onnx")) if not model_paths: @@ -118,14 +215,28 @@ if __name__ == "__main__": _output_dir = Path(args.output_dir) _output_dir.mkdir(exist_ok=True, parents=True) + _short_name = create_short_name(args.custom_name) if args.custom_name else None + + _driving_pkl = _find_driving_pkl(_output_dir) + if not _driving_pkl: + print(f"No driving_tinygrad.pkl found in {_output_dir}", file=sys.stderr) + sys.exit(1) + + if _short_name: + new_pkl = _output_dir / f"driving_{_short_name.lower()}_tinygrad.pkl" + if not new_pkl.exists(): + _driving_pkl = _rename_pkl_with_chunks(_driving_pkl, new_pkl) + else: + _driving_pkl = new_pkl + _models = [] for _model_path in model_paths: - _model_metadata = generate_metadata(Path(_model_path), _output_dir, create_short_name(args.custom_name)) + _model_metadata = generate_metadata(Path(_model_path), _output_dir, _short_name, _driving_pkl) if _model_metadata: _models.append(_model_metadata) if _models: - create_metadata_json(_models, _output_dir, args.custom_name, create_short_name(args.custom_name), args.is_20hz, args.upstream_branch) + create_metadata_json(_models, _output_dir, args.custom_name, _short_name, args.is_20hz, args.upstream_branch) else: print("No models processed.", file=sys.stderr) diff --git a/release/ci/publish.sh b/release/ci/publish.sh index d723782934..27904caf5d 100755 --- a/release/ci/publish.sh +++ b/release/ci/publish.sh @@ -30,7 +30,7 @@ if [ -z "$GIT_ORIGIN" ]; then fi # "Tagging" -echo "#define COMMA_VERSION \"$VERSION\"" > ${OUTPUT_DIR}/common/version.h +echo "#define SUNNYPILOT_VERSION \"$VERSION\"" > ${OUTPUT_DIR}/openpilot/sunnypilot/common/version.h ## set git identity #source $DIR/identity.sh @@ -51,26 +51,19 @@ git fetch origin $DEV_BRANCH || (git checkout -b $DEV_BRANCH && git commit --all echo "[-] committing version $VERSION T=$SECONDS" git add -f . -git commit -a -m "sunnypilot v$VERSION release" -git branch --set-upstream-to=origin/$DEV_BRANCH # include source commit hash and build date in commit GIT_HASH=$(git --git-dir=$SOURCE_DIR/.git rev-parse HEAD) DATETIME=$(date '+%Y-%m-%dT%H:%M:%S') -SP_VERSION=$(cat $SOURCE_DIR/common/version.h | awk -F\" '{print $2}') +SP_VERSION=$(awk -F\" '{print $2}' $SOURCE_DIR/openpilot/sunnypilot/common/version.h) -# Add built files to git -git add -f . -if [ "$EXTRA_VERSION_IDENTIFIER" = "-release" ] || [ "$EXTRA_VERSION_IDENTIFIER" = "-staging" ]; then - export VERSION=${VERSION%"$EXTRA_VERSION_IDENTIFIER"} - git commit --amend -m "sunnypilot v$VERSION" -else - git commit --amend -m "sunnypilot v$VERSION - version: sunnypilot v$SP_VERSION release - date: $DATETIME - master commit: $GIT_HASH - " -fi +# Commit with detailed message +git commit -a -m "sunnypilot v$VERSION +version: sunnypilot v$SP_VERSION (${EXTRA_VERSION_IDENTIFIER}) +date: $DATETIME +master commit: $GIT_HASH +" +git branch --set-upstream-to=origin/$DEV_BRANCH git branch -m $DEV_BRANCH # Push! diff --git a/release/ci/squash_and_merge_prs.py b/release/ci/squash_and_merge_prs.py index b26b08d500..24922288be 100755 --- a/release/ci/squash_and_merge_prs.py +++ b/release/ci/squash_and_merge_prs.py @@ -12,9 +12,9 @@ TRUST_FORK_LABEL = "trust-fork-pr" def setup_argument_parser(): parser = argparse.ArgumentParser(description='Process and squash GitHub PRs') parser.add_argument('--pr-data', type=str, help='PR data in JSON format') - parser.add_argument('--source-branch', type=str, default='master-new', + parser.add_argument('--source-branch', type=str, default='master', help='Source branch for merging') - parser.add_argument('--target-branch', type=str, default='master-dev-c3-new-test', + parser.add_argument('--target-branch', type=str, default='master-dev-test', help='Target branch for merging') parser.add_argument('--squash-script-path', type=str, required=True, help='Path to the squash_and_merge.py script') diff --git a/release/identity.sh b/release/identity.sh deleted file mode 100644 index c699c94650..0000000000 --- a/release/identity.sh +++ /dev/null @@ -1,4 +0,0 @@ -export GIT_COMMITTER_NAME="Vehicle Researcher" -export GIT_COMMITTER_EMAIL="user@comma.ai" -export GIT_AUTHOR_NAME="Vehicle Researcher" -export GIT_AUTHOR_EMAIL="user@comma.ai" diff --git a/scripts/cell.sh b/scripts/cell.sh deleted file mode 100755 index 310a9694fd..0000000000 --- a/scripts/cell.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/usr/bin/env bash -nmcli connection modify --temporary esim ipv4.route-metric 1 ipv6.route-metric 1 -nmcli con up esim diff --git a/scripts/ci_results.py b/scripts/ci_results.py new file mode 100755 index 0000000000..a133541c69 --- /dev/null +++ b/scripts/ci_results.py @@ -0,0 +1,212 @@ +#!/usr/bin/env python3 +"""Fetch CI results from GitHub Actions and Jenkins.""" + +import argparse +import json +import subprocess +import time +import urllib.error +import urllib.request +from datetime import datetime + +JENKINS_URL = "https://jenkins.comma.life" +DEFAULT_TIMEOUT = 1800 # 30 minutes +POLL_INTERVAL = 30 # seconds +LOG_TAIL_LINES = 10 # lines of log to include for failed jobs + + +def get_git_info(): + branch = subprocess.check_output(["git", "rev-parse", "--abbrev-ref", "HEAD"], text=True).strip() + commit = subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip() + return branch, commit + + +def get_github_actions_status(commit_sha): + result = subprocess.run( + ["gh", "run", "list", "--commit", commit_sha, "--workflow", "tests.yaml", "--json", "databaseId,status,conclusion"], + capture_output=True, text=True, check=True + ) + runs = json.loads(result.stdout) + if not runs: + return None, None + + run_id = runs[0]["databaseId"] + result = subprocess.run( + ["gh", "run", "view", str(run_id), "--json", "jobs"], + capture_output=True, text=True, check=True + ) + data = json.loads(result.stdout) + jobs = {job["name"]: {"status": job["status"], "conclusion": job["conclusion"], + "duration": format_duration(job) if job["conclusion"] not in ("skipped", None) and job.get("startedAt") else "", + "id": job["databaseId"]} + for job in data.get("jobs", [])} + return jobs, run_id + + +def get_github_job_log(run_id, job_id): + result = subprocess.run( + ["gh", "run", "view", str(run_id), "--job", str(job_id), "--log-failed"], + capture_output=True, text=True + ) + lines = result.stdout.strip().split('\n') + return '\n'.join(lines[-LOG_TAIL_LINES:]) if len(lines) > LOG_TAIL_LINES else result.stdout.strip() + + +def format_duration(job): + start = datetime.fromisoformat(job["startedAt"].replace("Z", "+00:00")) + end = datetime.fromisoformat(job["completedAt"].replace("Z", "+00:00")) + secs = int((end - start).total_seconds()) + return f"{secs // 60}m {secs % 60}s" + + +def get_jenkins_status(branch, commit_sha): + base_url = f"{JENKINS_URL}/job/openpilot/job/{branch}" + try: + # Get list of recent builds + with urllib.request.urlopen(f"{base_url}/api/json?tree=builds[number,url]", timeout=10) as resp: + builds = json.loads(resp.read().decode()).get("builds", []) + + # Find build matching commit + for build in builds[:20]: # check last 20 builds + with urllib.request.urlopen(f"{build['url']}api/json", timeout=10) as resp: + data = json.loads(resp.read().decode()) + for action in data.get("actions", []): + if action.get("_class") == "hudson.plugins.git.util.BuildData": + build_sha = action.get("lastBuiltRevision", {}).get("SHA1", "") + if build_sha.startswith(commit_sha) or commit_sha.startswith(build_sha): + # Get stages info + stages = [] + try: + with urllib.request.urlopen(f"{build['url']}wfapi/describe", timeout=10) as resp2: + wf_data = json.loads(resp2.read().decode()) + stages = [{"name": s["name"], "status": s["status"]} for s in wf_data.get("stages", [])] + except urllib.error.HTTPError: + pass + return { + "number": data["number"], + "in_progress": data.get("inProgress", False), + "result": data.get("result"), + "url": data.get("url", ""), + "stages": stages, + } + return None # no build found for this commit + except urllib.error.HTTPError: + return None # branch doesn't exist on Jenkins + + +def get_jenkins_log(build_url): + url = f"{build_url}consoleText" + with urllib.request.urlopen(url, timeout=30) as resp: + text = resp.read().decode(errors='replace') + lines = text.strip().split('\n') + return '\n'.join(lines[-LOG_TAIL_LINES:]) if len(lines) > LOG_TAIL_LINES else text.strip() + + +def is_complete(gh_status, jenkins_status): + gh_done = gh_status is None or all(j["status"] == "completed" for j in gh_status.values()) + jenkins_done = jenkins_status is None or not jenkins_status.get("in_progress", True) + return gh_done and jenkins_done + + +def status_icon(status, conclusion=None): + if status == "completed": + return ":white_check_mark:" if conclusion == "success" else ":x:" + return ":hourglass:" if status == "in_progress" else ":grey_question:" + + +def format_markdown(gh_status, gh_run_id, jenkins_status, commit_sha, branch): + lines = ["# CI Results", "", + f"**Branch**: {branch}", + f"**Commit**: {commit_sha[:7]}", + f"**Generated**: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", ""] + + lines.extend(["## GitHub Actions", "", "| Job | Status | Duration |", "|-----|--------|----------|"]) + failed_gh_jobs = [] + if gh_status: + for job_name, job in gh_status.items(): + icon = status_icon(job["status"], job.get("conclusion")) + conclusion = job.get("conclusion") or job["status"] + lines.append(f"| {job_name} | {icon} {conclusion} | {job.get('duration', '')} |") + if job.get("conclusion") == "failure": + failed_gh_jobs.append((job_name, job.get("id"))) + else: + lines.append("| - | No workflow runs found | |") + + lines.extend(["", "## Jenkins", "", "| Stage | Status |", "|-------|--------|"]) + failed_jenkins_stages = [] + if jenkins_status: + stages = jenkins_status.get("stages", []) + if stages: + for stage in stages: + icon = ":white_check_mark:" if stage["status"] == "SUCCESS" else ( + ":x:" if stage["status"] == "FAILED" else ":hourglass:") + lines.append(f"| {stage['name']} | {icon} {stage['status'].lower()} |") + if stage["status"] == "FAILED": + failed_jenkins_stages.append(stage["name"]) + # Show overall build status if still in progress + if jenkins_status["in_progress"]: + lines.append("| (build in progress) | :hourglass: in_progress |") + else: + icon = ":hourglass:" if jenkins_status["in_progress"] else ( + ":white_check_mark:" if jenkins_status["result"] == "SUCCESS" else ":x:") + status = "in progress" if jenkins_status["in_progress"] else (jenkins_status["result"] or "unknown") + lines.append(f"| #{jenkins_status['number']} | {icon} {status.lower()} |") + if jenkins_status.get("url"): + lines.append(f"\n[View build]({jenkins_status['url']})") + else: + lines.append("| - | No builds found for branch |") + + if failed_gh_jobs or failed_jenkins_stages: + lines.extend(["", "## Failure Logs", ""]) + + for job_name, job_id in failed_gh_jobs: + lines.append(f"### GitHub Actions: {job_name}") + log = get_github_job_log(gh_run_id, job_id) + lines.extend(["", "```", log, "```", ""]) + + for stage_name in failed_jenkins_stages: + lines.append(f"### Jenkins: {stage_name}") + log = get_jenkins_log(jenkins_status["url"]) + lines.extend(["", "```", log, "```", ""]) + + return "\n".join(lines) + "\n" + + +def main(): + parser = argparse.ArgumentParser(description="Fetch CI results from GitHub Actions and Jenkins") + parser.add_argument("--wait", action="store_true", help="Wait for CI to complete") + parser.add_argument("--timeout", type=int, default=DEFAULT_TIMEOUT, help="Timeout in seconds (default: 1800)") + parser.add_argument("-o", "--output", default="ci_results.md", help="Output file (default: ci_results.md)") + parser.add_argument("--branch", help="Branch to check (default: current branch)") + parser.add_argument("--commit", help="Commit SHA to check (default: HEAD)") + args = parser.parse_args() + + branch, commit = get_git_info() + branch = args.branch or branch + commit = args.commit or commit + print(f"Fetching CI results for {branch} @ {commit[:7]}") + + start_time = time.monotonic() + while True: + gh_status, gh_run_id = get_github_actions_status(commit) + jenkins_status = get_jenkins_status(branch, commit) if branch != "HEAD" else None + + if not args.wait or is_complete(gh_status, jenkins_status): + break + + elapsed = time.monotonic() - start_time + if elapsed >= args.timeout: + print(f"Timeout after {int(elapsed)}s") + break + + print(f"CI still running, waiting {POLL_INTERVAL}s... ({int(elapsed)}s elapsed)") + time.sleep(POLL_INTERVAL) + + content = format_markdown(gh_status, gh_run_id, jenkins_status, commit, branch) + with open(args.output, "w") as f: + f.write(content) + print(f"Results written to {args.output}") + + +if __name__ == "__main__": + main() diff --git a/scripts/disable-powersave.py b/scripts/disable-powersave.py index 367b4108b0..093275fd77 100755 --- a/scripts/disable-powersave.py +++ b/scripts/disable-powersave.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -from openpilot.system.hardware import HARDWARE +from openpilot.common.hardware import HARDWARE if __name__ == "__main__": HARDWARE.set_power_save(False) diff --git a/scripts/docs.py b/scripts/docs.py new file mode 100644 index 0000000000..d60bfb791f --- /dev/null +++ b/scripts/docs.py @@ -0,0 +1,63 @@ +""" + wrapper that materializes symlinks in docs/ before build + + we can delete this once zensical supports symlinks: + https://github.com/zensical/backlog/issues/55 +""" +import os +import shutil +import signal +import sys +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parent.parent +DOCS_DIR = REPO_ROOT / "docs" +SITE_DIR = REPO_ROOT / "docs_site" +sys.path.insert(0, str(REPO_ROOT)) +# Local docs build helpers live under docs/ so they stay near the content +# source. The wrapper prunes them from docs_site/ after build. +sys.path.insert(0, str(DOCS_DIR)) + + +def _materialize(docs: Path) -> dict[Path, str]: + originals: dict[Path, str] = {} + for link in docs.rglob("*"): + if not link.is_symlink(): + continue + target = link.resolve() + if not target.is_file(): + continue + originals[link] = os.readlink(link) + link.unlink() + shutil.copy2(target, link) + return originals + + +def _restore(originals: dict[Path, str]) -> None: + for link, target in originals.items(): + link.unlink(missing_ok=True) + os.symlink(target, link) + + +def _raise_interrupt(*_): + raise KeyboardInterrupt + + +def _prune_site_output() -> None: + shutil.rmtree(SITE_DIR / "ext", ignore_errors=True) + + +def main() -> None: + signal.signal(signal.SIGTERM, _raise_interrupt) + originals = _materialize(DOCS_DIR) + try: + from zensical.main import cli + cli(standalone_mode=False) + if len(sys.argv) > 1 and sys.argv[1] == "build": + _prune_site_output() + finally: + _restore(originals) + + +if __name__ == "__main__": + main() diff --git a/scripts/lint/check_added_large_files.py b/scripts/lint/check_added_large_files.py new file mode 100755 index 0000000000..c1aa820181 --- /dev/null +++ b/scripts/lint/check_added_large_files.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python3 +import argparse +import math +import os +import subprocess + + +def lfs_files(filenames: list[str]) -> set[str]: + if not filenames: + return set() + + result = subprocess.run( + ("git", "check-attr", "filter", "-z", "--stdin"), + input="\0".join(filenames), + check=True, + capture_output=True, + text=True, + ) + fields = result.stdout.rstrip("\0").split("\0") if result.stdout else [] + return {fields[i] for i in range(0, len(fields), 3) if fields[i + 2] == "lfs"} + + +def check_added_large_files(filenames: list[str], max_kb: int) -> int: + failed = False + ignored = lfs_files(filenames) + for filename in filenames: + if filename in ignored: + continue + + size_kb = math.ceil(os.stat(filename).st_size / 1024) + if size_kb > max_kb: + print(f"{filename} ({size_kb} KB) exceeds {max_kb} KB.") + failed = True + + return int(failed) + + +def main() -> int: + parser = argparse.ArgumentParser(description="Check that tracked files do not exceed a size limit.") + parser.add_argument("filenames", nargs="*") + parser.add_argument("--maxkb", type=int, default=500, help="maximum allowable size in KiB") + args = parser.parse_args() + return check_added_large_files(args.filenames, args.maxkb) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/lint/check_raylib_includes.sh b/scripts/lint/check_raylib_includes.sh deleted file mode 100755 index e3be73a489..0000000000 --- a/scripts/lint/check_raylib_includes.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env bash - -FAIL=0 - -if grep -n '#include "third_party/raylib/include/raylib\.h"' $@ | grep -v '^system/ui/raylib/raylib\.h'; then - echo -e "Bad raylib include found! Use '#include \"system/ui/raylib/raylib.h\"' instead\n" - FAIL=1 -fi - -exit $FAIL diff --git a/scripts/lint/check_shebang_scripts_are_executable.py b/scripts/lint/check_shebang_scripts_are_executable.py new file mode 100755 index 0000000000..7288640091 --- /dev/null +++ b/scripts/lint/check_shebang_scripts_are_executable.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python3 +import argparse +import shlex +import subprocess +import sys + + +def staged_modes(filenames: list[str]) -> list[tuple[str, str]]: + if not filenames: + return [] + + result = subprocess.run( + ("git", "ls-files", "-z", "--stage", "--", *filenames), + check=True, + capture_output=True, + text=True, + ) + entries = result.stdout.rstrip("\0").split("\0") if result.stdout else [] + return [(entry.split(" ", 1)[0], entry.split("\t", 1)[1]) for entry in entries] + + +def has_shebang(filename: str) -> bool: + with open(filename, "rb") as f: + return f.read(2) == b"#!" + + +def check_shebang_scripts_are_executable(filenames: list[str]) -> int: + failed = False + for mode, filename in staged_modes(filenames): + if mode != "100755" and has_shebang(filename): + quoted = shlex.quote(filename) + print("\n".join(( + f"{filename}: has a shebang but is not marked executable!", + f" If it is supposed to be executable, try: `chmod +x {quoted}`", + " If it is not supposed to be executable, double-check its shebang is wanted.\n", + )), file=sys.stderr) + failed = True + + return int(failed) + + +def main() -> int: + parser = argparse.ArgumentParser(description="Check that tracked files with shebangs are executable.") + parser.add_argument("filenames", nargs="*") + args = parser.parse_args() + return check_shebang_scripts_are_executable(args.filenames) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/lint/lint.sh b/scripts/lint/lint.sh index f988a88564..69ed3951d8 100755 --- a/scripts/lint/lint.sh +++ b/scripts/lint/lint.sh @@ -13,9 +13,6 @@ cd $ROOT FAILED=0 -IGNORED_FILES="uv\.lock|docs\/CARS.md|LICENSE\.md|layouts\/.*\.xml" -IGNORED_DIRS="^third_party.*|^msgq.*|^msgq_repo.*|^opendbc.*|^opendbc_repo.*|^cereal.*|^panda.*|^rednose.*|^rednose_repo.*|^tinygrad.*|^tinygrad_repo.*|^teleoprtc.*|^teleoprtc_repo.*" - function run() { shopt -s extglob case $1 in @@ -48,14 +45,14 @@ function run_tests() { ALL_FILES=$1 PYTHON_FILES=$2 - run "ruff" ruff check $ROOT --quiet - run "check_added_large_files" python3 -m pre_commit_hooks.check_added_large_files --enforce-all $ALL_FILES --maxkb=120 - run "check_shebang_scripts_are_executable" python3 -m pre_commit_hooks.check_shebang_scripts_are_executable $ALL_FILES + run "ruff" ruff check openpilot --quiet + run "check_added_large_files" $DIR/check_added_large_files.py --maxkb=120 $ALL_FILES + run "check_shebang_scripts_are_executable" $DIR/check_shebang_scripts_are_executable.py $ALL_FILES run "check_shebang_format" $DIR/check_shebang_format.sh $ALL_FILES run "check_nomerge_comments" $DIR/check_nomerge_comments.sh $ALL_FILES if [[ -z "$FAST" ]]; then - run "mypy" mypy $PYTHON_FILES + run "ty" ty check openpilot run "codespell" codespell $ALL_FILES --ignore-words=$ROOT/.codespellignore fi @@ -69,7 +66,7 @@ function help() { echo "" echo -e "${BOLD}${UNDERLINE}Tests:${NC}" echo -e " ${BOLD}ruff${NC}" - echo -e " ${BOLD}mypy${NC}" + echo -e " ${BOLD}ty${NC}" echo -e " ${BOLD}codespell${NC}" echo -e " ${BOLD}check_added_large_files${NC}" echo -e " ${BOLD}check_shebang_scripts_are_executable${NC}" @@ -81,11 +78,11 @@ function help() { echo " Specify tests to skip separated by spaces" echo "" echo -e "${BOLD}${UNDERLINE}Examples:${NC}" - echo " op lint mypy ruff" - echo " Only run the mypy and ruff tests" + echo " op lint ty ruff" + echo " Only run the ty and ruff tests" echo "" - echo " op lint --skip mypy ruff" - echo " Skip the mypy and ruff tests" + echo " op lint --skip ty ruff" + echo " Skip the ty and ruff tests" echo "" echo " op lint" echo " Run all the tests" @@ -105,7 +102,8 @@ done RUN=$([ -z "$RUN" ] && echo "" || echo "!($(echo $RUN | sed 's/ /|/g'))") SKIP="@($(echo $SKIP | sed 's/ /|/g'))" -GIT_FILES="$(git ls-files | sed -E "s/$IGNORED_FILES|$IGNORED_DIRS//g")" +IGNORED_DIRS="^openpilot/third_party/.*" +GIT_FILES="$(git ls-files openpilot | grep -vE "$IGNORED_DIRS")" ALL_FILES="" for f in $GIT_FILES; do if [[ -f $f ]]; then diff --git a/scripts/manage-powersave.py b/scripts/manage-powersave.py index 1a82810a7f..2c736ecd69 100755 --- a/scripts/manage-powersave.py +++ b/scripts/manage-powersave.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 import argparse import multiprocessing -from openpilot.system.hardware import HARDWARE +from openpilot.common.hardware import HARDWARE def main(): diff --git a/scripts/reporter.py b/scripts/reporter.py index 903fcc8911..5de5521835 100755 --- a/scripts/reporter.py +++ b/scripts/reporter.py @@ -1,31 +1,46 @@ #!/usr/bin/env python3 import os import glob -import onnx + +from tinygrad.nn.onnx import OnnxPBParser BASEDIR = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "../")) + MASTER_PATH = os.getenv("MASTER_PATH", BASEDIR) -MODEL_PATH = "/selfdrive/modeld/models/" +MODEL_PATH = "/openpilot/selfdrive/modeld/models/" + + +class MetadataOnnxPBParser(OnnxPBParser): + def _parse_ModelProto(self) -> dict: + obj = {"metadata_props": []} + for fid, wire_type in self._parse_message(self.reader.len): + match fid: + case 14: + obj["metadata_props"].append(self._parse_StringStringEntryProto()) + case _: + self.reader.skip_field(wire_type) + return obj + def get_checkpoint(f): - model = onnx.load(f) - metadata = {prop.key: prop.value for prop in model.metadata_props} - return metadata['model_checkpoint'].split('/')[0] + model = MetadataOnnxPBParser(f).parse() + metadata = {prop["key"]: prop["value"] for prop in model["metadata_props"]} + # "" or "...//"; combined models list vision then policy + parts = metadata['model_checkpoint'].split('/') + return parts[-2] if len(parts) > 1 else parts[0] + if __name__ == "__main__": print("| | master | PR branch |") print("|-| ----- | --------- |") for f in glob.glob(BASEDIR + MODEL_PATH + "/*.onnx"): - # TODO: add checkpoint to DM - if "dmonitoring" in f: - continue - fn = os.path.basename(f) - master = get_checkpoint(MASTER_PATH + MODEL_PATH + fn) + master_path = MASTER_PATH + MODEL_PATH + fn + if os.path.exists(master_path): + master = get_checkpoint(master_path) + master_col = f"[{master}](https://reporter.comma.life/{master})" + else: + master_col = "N/A (new model)" pr = get_checkpoint(BASEDIR + MODEL_PATH + fn) - print( - "|", fn, "|", - f"[{master}](https://reporter.comma.life/experiment/{master})", "|", - f"[{pr}](https://reporter.comma.life/experiment/{pr})", "|" - ) + print("|", fn, "|", master_col, "|", f"[{pr}](https://reporter.comma.life/{pr})", "|") diff --git a/scripts/stop_updater.sh b/scripts/stop_updater.sh deleted file mode 100755 index 703b363928..0000000000 --- a/scripts/stop_updater.sh +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env sh - -# Stop updater -pkill -2 -f system.updated.updated - -# Remove pending update -rm -f /data/safe_staging/finalized/.overlay_consistent diff --git a/scripts/test_pip_install.sh b/scripts/test_pip_install.sh new file mode 100755 index 0000000000..d2dbedff0a --- /dev/null +++ b/scripts/test_pip_install.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +set -euxo pipefail + +SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(git -C "$SCRIPT_DIR/.." rev-parse --show-toplevel)" +PYTHON_VERSION="$(cat "$REPO_ROOT/.python-version")" +PACKAGE="${1:-$REPO_ROOT}" + +TMPDIR="$(mktemp -d)" +trap 'rm -rf "$TMPDIR"' EXIT + +cd "$TMPDIR" + +uv venv --python "$PYTHON_VERSION" +source .venv/bin/activate +uv pip install "$PACKAGE" +python3 - <<'PY' +from openpilot.tools.lib.logreader import LogReader + +assert LogReader.__name__ == "LogReader" +print("ok: imported LogReader") +PY diff --git a/scripts/usb.sh b/scripts/usb.sh deleted file mode 100755 index 5796cfa028..0000000000 --- a/scripts/usb.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/usr/bin/env bash - -# testing the GPU box - -export XDG_CACHE_HOME=/data/tinycache -mkdir -p $XDG_CACHE_HOME - -cd /data/openpilot/tinygrad_repo/examples -while true; do - AMD=1 AMD_IFACE=usb python ./beautiful_cartpole.py - sleep 1 -done diff --git a/scripts/waste.c b/scripts/waste.c index 2e492916a7..fc230846f2 100644 --- a/scripts/waste.c +++ b/scripts/waste.c @@ -11,7 +11,7 @@ #include #include #include -#include "../common/timing.h" +#include "../openpilot/common/timing.h" int get_nprocs(void); double *ttime, *oout; @@ -86,4 +86,3 @@ int main() { sleep(1); } } - diff --git a/selfdrive/SConscript b/selfdrive/SConscript deleted file mode 100644 index 0b49e69116..0000000000 --- a/selfdrive/SConscript +++ /dev/null @@ -1,6 +0,0 @@ -SConscript(['pandad/SConscript']) -SConscript(['controls/lib/lateral_mpc_lib/SConscript']) -SConscript(['controls/lib/longitudinal_mpc_lib/SConscript']) -SConscript(['locationd/SConscript']) -SConscript(['modeld/SConscript']) -SConscript(['ui/SConscript']) \ No newline at end of file diff --git a/selfdrive/assets/.gitignore b/selfdrive/assets/.gitignore deleted file mode 100644 index 1f90a2a932..0000000000 --- a/selfdrive/assets/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -*.cc -translations_assets.qrc diff --git a/selfdrive/assets/assets.qrc b/selfdrive/assets/assets.qrc deleted file mode 100644 index 26a7d998ed..0000000000 --- a/selfdrive/assets/assets.qrc +++ /dev/null @@ -1,20 +0,0 @@ - - - ../../third_party/bootstrap/bootstrap-icons.svg - images/button_continue_triangle.svg - icons/circled_check.svg - icons/circled_slash.svg - icons/eye_open.svg - icons/eye_closed.svg - icons/close.svg - icons/lock_closed.svg - icons/checkmark.svg - icons/warning.png - icons/wifi_strength_low.svg - icons/wifi_strength_medium.svg - icons/wifi_strength_high.svg - icons/wifi_strength_full.svg - - ../ui/translations/languages.json - - diff --git a/selfdrive/assets/sounds/prompt.wav b/selfdrive/assets/sounds/prompt.wav deleted file mode 100644 index e482c85a62..0000000000 --- a/selfdrive/assets/sounds/prompt.wav +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:ad19268e4aaaeac8dd21f6b26c16a121e7b3f50bba867748e7226727643ae682 -size 144642 diff --git a/selfdrive/assets/sounds/prompt_distracted.wav b/selfdrive/assets/sounds/prompt_distracted.wav deleted file mode 100644 index 750d580f04..0000000000 --- a/selfdrive/assets/sounds/prompt_distracted.wav +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:1810ad0418ac234f02dec005883c8f0e1c3e0e5ece7a3157803c5a66cb8e5adc -size 85662 diff --git a/selfdrive/assets/sounds/refuse.wav b/selfdrive/assets/sounds/refuse.wav deleted file mode 100644 index 1e0c47697d..0000000000 --- a/selfdrive/assets/sounds/refuse.wav +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4af81cbf1d96a42cc351878b015298aee82874b46baaf1a615ca91ec36c0ced6 -size 83228 diff --git a/selfdrive/assets/sounds/warning_immediate.wav b/selfdrive/assets/sounds/warning_immediate.wav deleted file mode 100644 index fcbfed79ed..0000000000 --- a/selfdrive/assets/sounds/warning_immediate.wav +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:5a390831afca3bfc6ea3c2739b872ebf866e70df8ae30653f8587e5cd3993959 -size 68306 diff --git a/selfdrive/assets/sounds/warning_soft.wav b/selfdrive/assets/sounds/warning_soft.wav deleted file mode 100644 index 7db30303d6..0000000000 --- a/selfdrive/assets/sounds/warning_soft.wav +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:67e636d072703e6b1233a12344c0a6304fd43d64dbb31c66b71c2c8870a339c1 -size 153764 diff --git a/selfdrive/car/car_specific.py b/selfdrive/car/car_specific.py deleted file mode 100644 index 151a8479a7..0000000000 --- a/selfdrive/car/car_specific.py +++ /dev/null @@ -1,216 +0,0 @@ -from cereal import car, log, custom -import cereal.messaging as messaging -from opendbc.car import DT_CTRL, structs -from opendbc.car.interfaces import MAX_CTRL_SPEED - -from openpilot.selfdrive.selfdrived.events import Events - -ButtonType = structs.CarState.ButtonEvent.Type -GearShifter = structs.CarState.GearShifter -EventName = log.OnroadEvent.EventName -NetworkLocation = structs.CarParams.NetworkLocation - - -# TODO: the goal is to abstract this file into the CarState struct and make events generic -class MockCarState: - def __init__(self): - self.sm = messaging.SubMaster(['gpsLocation', 'gpsLocationExternal']) - - def update(self, CS: car.CarState, CS_SP: custom.CarStateSP): - self.sm.update(0) - gps_sock = 'gpsLocationExternal' if self.sm.recv_frame['gpsLocationExternal'] > 1 else 'gpsLocation' - - CS.vEgo = self.sm[gps_sock].speed - CS.vEgoRaw = self.sm[gps_sock].speed - - return CS, CS_SP - - -class CarSpecificEvents: - def __init__(self, CP: structs.CarParams): - self.CP = CP - - self.steering_unpressed = 0 - self.low_speed_alert = False - self.no_steer_warning = False - self.silent_steer_warning = True - - def update(self, CS: car.CarState, CS_prev: car.CarState, CC: car.CarControl): - if self.CP.brand in ('body', 'mock'): - events = Events() - - elif self.CP.brand == 'ford': - events = self.create_common_events(CS, CS_prev, extra_gears=[GearShifter.low, GearShifter.manumatic]) - - elif self.CP.brand == 'nissan': - events = self.create_common_events(CS, CS_prev, extra_gears=[GearShifter.brake]) - - elif self.CP.brand == 'chrysler': - events = self.create_common_events(CS, CS_prev, extra_gears=[GearShifter.low]) - - # Low speed steer alert hysteresis logic - if self.CP.minSteerSpeed > 0. and CS.vEgo < (self.CP.minSteerSpeed + 0.5): - self.low_speed_alert = True - elif CS.vEgo > (self.CP.minSteerSpeed + 1.): - self.low_speed_alert = False - if self.low_speed_alert: - events.add(EventName.belowSteerSpeed) - - elif self.CP.brand == 'honda': - events = self.create_common_events(CS, CS_prev, pcm_enable=False) - - if self.CP.pcmCruise and CS.vEgo < self.CP.minEnableSpeed: - events.add(EventName.belowEngageSpeed) - - if self.CP.pcmCruise: - # we engage when pcm is active (rising edge) - if CS.cruiseState.enabled and not CS_prev.cruiseState.enabled: - events.add(EventName.pcmEnable) - elif not CS.cruiseState.enabled and (CC.actuators.accel >= 0. or not self.CP.openpilotLongitudinalControl): - # it can happen that car cruise disables while comma system is enabled: need to - # keep braking if needed or if the speed is very low - if CS.vEgo < self.CP.minEnableSpeed + 2.: - # non loud alert if cruise disables below 25mph as expected (+ a little margin) - events.add(EventName.speedTooLow) - else: - events.add(EventName.cruiseDisabled) - if self.CP.minEnableSpeed > 0 and CS.vEgo < 0.001: - events.add(EventName.manualRestart) - - elif self.CP.brand == 'toyota': - events = self.create_common_events(CS, CS_prev) - - if self.CP.openpilotLongitudinalControl: - if CS.cruiseState.standstill and not CS.brakePressed: - events.add(EventName.resumeRequired) - if CS.vEgo < self.CP.minEnableSpeed: - events.add(EventName.belowEngageSpeed) - if CC.actuators.accel > 0.3: - # some margin on the actuator to not false trigger cancellation while stopping - events.add(EventName.speedTooLow) - if CS.vEgo < 0.001: - # while in standstill, send a user alert - events.add(EventName.manualRestart) - - elif self.CP.brand == 'gm': - events = self.create_common_events(CS, CS_prev, extra_gears=[GearShifter.sport, GearShifter.low, - GearShifter.eco, GearShifter.manumatic], - pcm_enable=self.CP.pcmCruise) - - # Enabling at a standstill with brake is allowed - # TODO: verify 17 Volt can enable for the first time at a stop and allow for all GMs - if CS.vEgo < self.CP.minEnableSpeed and not (CS.standstill and CS.brake >= 20 and - self.CP.networkLocation == NetworkLocation.fwdCamera): - events.add(EventName.belowEngageSpeed) - if CS.cruiseState.standstill: - events.add(EventName.resumeRequired) - - elif self.CP.brand == 'volkswagen': - events = self.create_common_events(CS, CS_prev, extra_gears=[GearShifter.eco, GearShifter.sport, GearShifter.manumatic], - pcm_enable=self.CP.pcmCruise) - - if self.CP.openpilotLongitudinalControl: - if CS.vEgo < self.CP.minEnableSpeed + 0.5: - events.add(EventName.belowEngageSpeed) - if CC.enabled and CS.vEgo < self.CP.minEnableSpeed: - events.add(EventName.speedTooLow) - - # TODO: this needs to be implemented generically in carState struct - # if CC.eps_timer_soft_disable_alert: # type: ignore[attr-defined] - # events.add(EventName.steerTimeLimit) - - elif self.CP.brand == 'hyundai': - events = self.create_common_events(CS, CS_prev, extra_gears=(GearShifter.sport, GearShifter.manumatic), - pcm_enable=self.CP.pcmCruise, allow_button_cancel=False) - - else: - events = self.create_common_events(CS, CS_prev) - - return events - - def create_common_events(self, CS: structs.CarState, CS_prev: car.CarState, extra_gears=None, pcm_enable=True, - allow_button_cancel=True): - events = Events() - - if CS.doorOpen: - events.add(EventName.doorOpen) - if CS.seatbeltUnlatched: - events.add(EventName.seatbeltNotLatched) - if CS.gearShifter != GearShifter.drive and (extra_gears is None or - CS.gearShifter not in extra_gears): - events.add(EventName.wrongGear) - if CS.gearShifter == GearShifter.reverse: - events.add(EventName.reverseGear) - if not CS.cruiseState.available: - events.add(EventName.wrongCarMode) - if CS.espDisabled: - events.add(EventName.espDisabled) - if CS.espActive: - events.add(EventName.espActive) - if CS.stockFcw: - events.add(EventName.stockFcw) - if CS.stockAeb: - events.add(EventName.stockAeb) - if CS.vEgo > MAX_CTRL_SPEED: - events.add(EventName.speedTooHigh) - if CS.cruiseState.nonAdaptive: - events.add(EventName.wrongCruiseMode) - if CS.brakeHoldActive and self.CP.openpilotLongitudinalControl: - events.add(EventName.brakeHold) - if CS.parkingBrake: - events.add(EventName.parkBrake) - if CS.accFaulted: - events.add(EventName.accFaulted) - if CS.steeringPressed: - events.add(EventName.steerOverride) - if CS.steeringDisengage and not CS_prev.steeringDisengage: - events.add(EventName.steerDisengage) - if CS.brakePressed and CS.standstill: - events.add(EventName.preEnableStandstill) - if CS.gasPressed: - events.add(EventName.gasPressedOverride) - if CS.vehicleSensorsInvalid: - events.add(EventName.vehicleSensorsInvalid) - if CS.invalidLkasSetting: - events.add(EventName.invalidLkasSetting) - if CS.lowSpeedAlert: - events.add(EventName.belowSteerSpeed) - if CS.buttonEnable: - events.add(EventName.buttonEnable) - - # Handle cancel button presses - for b in CS.buttonEvents: - # Disable on rising and falling edge of cancel for both stock and OP long - # TODO: only check the cancel button with openpilot longitudinal on all brands to match panda safety - if b.type == ButtonType.cancel and (allow_button_cancel or not self.CP.pcmCruise): - events.add(EventName.buttonCancel) - - # Handle permanent and temporary steering faults - self.steering_unpressed = 0 if CS.steeringPressed else self.steering_unpressed + 1 - if CS.steerFaultTemporary: - if CS.steeringPressed and (not CS_prev.steerFaultTemporary or self.no_steer_warning): - self.no_steer_warning = True - else: - self.no_steer_warning = False - - # if the user overrode recently, show a less harsh alert - if self.silent_steer_warning or CS.standstill or self.steering_unpressed < int(1.5 / DT_CTRL): - self.silent_steer_warning = True - events.add(EventName.steerTempUnavailableSilent) - else: - events.add(EventName.steerTempUnavailable) - else: - self.no_steer_warning = False - self.silent_steer_warning = False - if CS.steerFaultPermanent: - events.add(EventName.steerUnavailable) - - # we engage when pcm is active (rising edge) - # enabling can optionally be blocked by the car interface - if pcm_enable: - if CS.cruiseState.enabled and not CS_prev.cruiseState.enabled and not CS.blockPcmEnable: - events.add(EventName.pcmEnable) - elif not CS.cruiseState.enabled: - events.add(EventName.pcmDisable) - - return events diff --git a/selfdrive/car/cruise.py b/selfdrive/car/cruise.py deleted file mode 100644 index 01ef2d7c99..0000000000 --- a/selfdrive/car/cruise.py +++ /dev/null @@ -1,141 +0,0 @@ -import math -import numpy as np - -from cereal import car -from openpilot.common.conversions import Conversions as CV -from openpilot.sunnypilot.selfdrive.car.cruise_ext import VCruiseHelperSP - - -# WARNING: this value was determined based on the model's training distribution, -# model predictions above this speed can be unpredictable -# V_CRUISE's are in kph -V_CRUISE_MIN = 8 -V_CRUISE_MAX = 145 -V_CRUISE_UNSET = 255 -V_CRUISE_INITIAL = 40 -V_CRUISE_INITIAL_EXPERIMENTAL_MODE = 105 -IMPERIAL_INCREMENT = round(CV.MPH_TO_KPH, 1) # round here to avoid rounding errors incrementing set speed - -ButtonEvent = car.CarState.ButtonEvent -ButtonType = car.CarState.ButtonEvent.Type -CRUISE_LONG_PRESS = 50 -CRUISE_NEAREST_FUNC = { - ButtonType.accelCruise: math.ceil, - ButtonType.decelCruise: math.floor, -} -CRUISE_INTERVAL_SIGN = { - ButtonType.accelCruise: +1, - ButtonType.decelCruise: -1, -} - - -class VCruiseHelper(VCruiseHelperSP): - def __init__(self, CP): - VCruiseHelperSP.__init__(self) - self.CP = CP - self.v_cruise_kph = V_CRUISE_UNSET - self.v_cruise_cluster_kph = V_CRUISE_UNSET - self.v_cruise_kph_last = 0 - self.button_timers = {ButtonType.decelCruise: 0, ButtonType.accelCruise: 0} - self.button_change_states = {btn: {"standstill": False, "enabled": False} for btn in self.button_timers} - - @property - def v_cruise_initialized(self): - return self.v_cruise_kph != V_CRUISE_UNSET - - def update_v_cruise(self, CS, enabled, is_metric): - self.v_cruise_kph_last = self.v_cruise_kph - - if CS.cruiseState.available: - if not self.CP.pcmCruise: - # if stock cruise is completely disabled, then we can use our own set speed logic - self._update_v_cruise_non_pcm(CS, enabled, is_metric) - self.v_cruise_cluster_kph = self.v_cruise_kph - self.update_button_timers(CS, enabled) - else: - self.v_cruise_kph = CS.cruiseState.speed * CV.MS_TO_KPH - self.v_cruise_cluster_kph = CS.cruiseState.speedCluster * CV.MS_TO_KPH - if CS.cruiseState.speed == 0: - self.v_cruise_kph = V_CRUISE_UNSET - self.v_cruise_cluster_kph = V_CRUISE_UNSET - elif CS.cruiseState.speed == -1: - self.v_cruise_kph = -1 - self.v_cruise_cluster_kph = -1 - else: - self.v_cruise_kph = V_CRUISE_UNSET - self.v_cruise_cluster_kph = V_CRUISE_UNSET - - def _update_v_cruise_non_pcm(self, CS, enabled, is_metric): - # handle button presses. TODO: this should be in state_control, but a decelCruise press - # would have the effect of both enabling and changing speed is checked after the state transition - if not enabled: - return - - long_press = False - button_type = None - - v_cruise_delta = 1. if is_metric else IMPERIAL_INCREMENT - - for b in CS.buttonEvents: - if b.type.raw in self.button_timers and not b.pressed: - if self.button_timers[b.type.raw] > CRUISE_LONG_PRESS: - return # end long press - button_type = b.type.raw - break - else: - for k, timer in self.button_timers.items(): - if timer and timer % CRUISE_LONG_PRESS == 0: - button_type = k - long_press = True - break - - if button_type is None: - return - - # Don't adjust speed when pressing resume to exit standstill - cruise_standstill = self.button_change_states[button_type]["standstill"] or CS.cruiseState.standstill - if button_type == ButtonType.accelCruise and cruise_standstill: - return - - # Don't adjust speed if we've enabled since the button was depressed (some ports enable on rising edge) - if not self.button_change_states[button_type]["enabled"]: - return - - long_press, v_cruise_delta = VCruiseHelperSP.update_v_cruise_delta(self, long_press, v_cruise_delta) - if long_press and self.v_cruise_kph % v_cruise_delta != 0: # partial interval - self.v_cruise_kph = CRUISE_NEAREST_FUNC[button_type](self.v_cruise_kph / v_cruise_delta) * v_cruise_delta - else: - self.v_cruise_kph += v_cruise_delta * CRUISE_INTERVAL_SIGN[button_type] - - # If set is pressed while overriding, clip cruise speed to minimum of vEgo - if CS.gasPressed and button_type in (ButtonType.decelCruise, ButtonType.setCruise): - self.v_cruise_kph = max(self.v_cruise_kph, CS.vEgo * CV.MS_TO_KPH) - - self.v_cruise_kph = np.clip(round(self.v_cruise_kph, 1), V_CRUISE_MIN, V_CRUISE_MAX) - - def update_button_timers(self, CS, enabled): - # increment timer for buttons still pressed - for k in self.button_timers: - if self.button_timers[k] > 0: - self.button_timers[k] += 1 - - for b in CS.buttonEvents: - if b.type.raw in self.button_timers: - # Start/end timer and store current state on change of button pressed - self.button_timers[b.type.raw] = 1 if b.pressed else 0 - self.button_change_states[b.type.raw] = {"standstill": CS.cruiseState.standstill, "enabled": enabled} - - def initialize_v_cruise(self, CS, experimental_mode: bool, dynamic_experimental_control: bool) -> None: - # initializing is handled by the PCM - if self.CP.pcmCruise: - return - - initial_experimental_mode = experimental_mode and not dynamic_experimental_control - initial = V_CRUISE_INITIAL_EXPERIMENTAL_MODE if initial_experimental_mode else V_CRUISE_INITIAL - - if any(b.type in (ButtonType.accelCruise, ButtonType.resumeCruise) for b in CS.buttonEvents) and self.v_cruise_initialized: - self.v_cruise_kph = self.v_cruise_kph_last - else: - self.v_cruise_kph = int(round(np.clip(CS.vEgo * CV.MS_TO_KPH, initial, V_CRUISE_MAX))) - - self.v_cruise_cluster_kph = self.v_cruise_kph diff --git a/selfdrive/car/docs.py b/selfdrive/car/docs.py deleted file mode 100755 index f807fc320e..0000000000 --- a/selfdrive/car/docs.py +++ /dev/null @@ -1,21 +0,0 @@ -#!/usr/bin/env python3 -import argparse -import os - -from openpilot.common.basedir import BASEDIR -from opendbc.car.docs import get_all_car_docs, generate_cars_md - -CARS_MD_OUT = os.path.join(BASEDIR, "docs", "CARS.md") -CARS_MD_TEMPLATE = os.path.join(BASEDIR, "selfdrive", "car", "CARS_template.md") - -if __name__ == "__main__": - parser = argparse.ArgumentParser(description="Auto generates supported cars documentation", - formatter_class=argparse.ArgumentDefaultsHelpFormatter) - - parser.add_argument("--template", default=CARS_MD_TEMPLATE, help="Override default template filename") - parser.add_argument("--out", default=CARS_MD_OUT, help="Override default generated filename") - args = parser.parse_args() - - with open(args.out, 'w') as f: - f.write(generate_cars_md(get_all_car_docs(), args.template)) - print(f"Generated and written to {args.out}") diff --git a/selfdrive/car/helpers.py b/selfdrive/car/helpers.py deleted file mode 100644 index 6187be1474..0000000000 --- a/selfdrive/car/helpers.py +++ /dev/null @@ -1,62 +0,0 @@ -import capnp -from typing import Any - -from cereal import custom -from opendbc.car import structs - -_FIELDS = '__dataclass_fields__' # copy of dataclasses._FIELDS - - -def is_dataclass(obj): - """Similar to dataclasses.is_dataclass without instance type check checking""" - return hasattr(obj, _FIELDS) - - -def _asdictref_inner(obj) -> dict[str, Any] | Any: - if is_dataclass(obj): - ret = {} - for field in getattr(obj, _FIELDS): # similar to dataclasses.fields() - ret[field] = _asdictref_inner(getattr(obj, field)) - return ret - elif isinstance(obj, (tuple, list)): - return type(obj)(_asdictref_inner(v) for v in obj) - else: - return obj - - -def asdictref(obj) -> dict[str, Any]: - """ - Similar to dataclasses.asdict without recursive type checking and copy.deepcopy - Note that the resulting dict will contain references to the original struct as a result - """ - if not is_dataclass(obj): - raise TypeError("asdictref() should be called on dataclass instances") - - return _asdictref_inner(obj) - - -def convert_to_capnp(struct: structs.CarParamsSP | structs.CarStateSP) -> capnp.lib.capnp._DynamicStructBuilder: - struct_dict = asdictref(struct) - - if isinstance(struct, structs.CarParamsSP): - struct_capnp = custom.CarParamsSP.new_message(**struct_dict) - elif isinstance(struct, structs.CarStateSP): - struct_capnp = custom.CarStateSP.new_message(**struct_dict) - else: - raise ValueError(f"Unsupported struct type: {type(struct)}") - - return struct_capnp - - -def convert_carControlSP(struct: capnp.lib.capnp._DynamicStructReader) -> structs.CarControlSP: - # TODO: recursively handle any car struct as needed - def remove_deprecated(s: dict) -> dict: - return {k: v for k, v in s.items() if not k.endswith('DEPRECATED')} - - struct_dict = struct.to_dict() - struct_dataclass = structs.CarControlSP(**remove_deprecated({k: v for k, v in struct_dict.items() if not isinstance(k, dict)})) - - struct_dataclass.mads = structs.ModularAssistiveDrivingSystem(**remove_deprecated(struct_dict.get('mads', {}))) - struct_dataclass.params = [structs.CarControlSP.Param(**remove_deprecated(p)) for p in struct_dict.get('params', [])] - - return struct_dataclass diff --git a/selfdrive/car/tests/.gitignore b/selfdrive/car/tests/.gitignore deleted file mode 100644 index 192fb0945e..0000000000 --- a/selfdrive/car/tests/.gitignore +++ /dev/null @@ -1 +0,0 @@ -*.bz2 diff --git a/selfdrive/car/tests/big_cars_test.sh b/selfdrive/car/tests/big_cars_test.sh deleted file mode 100755 index 863b8bead0..0000000000 --- a/selfdrive/car/tests/big_cars_test.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/usr/bin/env bash - -SCRIPT_DIR=$(dirname "$0") -BASEDIR=$(realpath "$SCRIPT_DIR/../../../") -cd $BASEDIR - -export MAX_EXAMPLES=300 -export INTERNAL_SEG_CNT=300 -export FILEREADER_CACHE=1 -export INTERNAL_SEG_LIST=selfdrive/car/tests/test_models_segs.txt - -cd selfdrive/car/tests && pytest test_models.py test_car_interfaces.py diff --git a/selfdrive/car/tests/test_car_interfaces.py b/selfdrive/car/tests/test_car_interfaces.py deleted file mode 100644 index 7d136b824c..0000000000 --- a/selfdrive/car/tests/test_car_interfaces.py +++ /dev/null @@ -1,110 +0,0 @@ -import os -import math -import hypothesis.strategies as st -from hypothesis import Phase, given, settings -from parameterized import parameterized - -from cereal import car, custom -from opendbc.car import DT_CTRL -from opendbc.car.car_helpers import interfaces -from opendbc.car.structs import CarParams -from opendbc.car.tests.test_car_interfaces import get_fuzzy_car_interface_args -from opendbc.car.fw_versions import FW_VERSIONS, FW_QUERY_CONFIGS -from opendbc.car.mock.values import CAR as MOCK -from opendbc.car.values import PLATFORMS -from openpilot.selfdrive.car.helpers import convert_carControlSP -from openpilot.selfdrive.controls.lib.latcontrol_angle import LatControlAngle -from openpilot.selfdrive.controls.lib.latcontrol_pid import LatControlPID -from openpilot.selfdrive.controls.lib.latcontrol_torque import LatControlTorque -from openpilot.selfdrive.controls.lib.longcontrol import LongControl -from openpilot.selfdrive.test.fuzzy_generation import FuzzyGenerator - -from openpilot.sunnypilot.selfdrive.car import interfaces as sunnypilot_interfaces - -ALL_ECUS = {ecu for ecus in FW_VERSIONS.values() for ecu in ecus.keys()} -ALL_ECUS |= {ecu for config in FW_QUERY_CONFIGS.values() for ecu in config.extra_ecus} - -ALL_REQUESTS = {tuple(r.request) for config in FW_QUERY_CONFIGS.values() for r in config.requests} - -MAX_EXAMPLES = int(os.environ.get('MAX_EXAMPLES', '60')) - - -class TestCarInterfaces: - # FIXME: Due to the lists used in carParams, Phase.target is very slow and will cause - # many generated examples to overrun when max_examples > ~20, don't use it - @parameterized.expand([(car,) for car in sorted(PLATFORMS)] + [MOCK.MOCK]) - @settings(max_examples=MAX_EXAMPLES, deadline=None, - phases=(Phase.reuse, Phase.generate, Phase.shrink)) - @given(data=st.data()) - def test_car_interfaces(self, car_name, data): - CarInterface = interfaces[car_name] - - args = get_fuzzy_car_interface_args(data.draw) - - car_params = CarInterface.get_params(car_name, args['fingerprints'], args['car_fw'], - alpha_long=args['alpha_long'], is_release=False, docs=False) - car_params_sp = CarInterface.get_params_sp(car_params, car_name, args['fingerprints'], args['car_fw'], - alpha_long=args['alpha_long'], docs=False) - car_params = car_params.as_reader() - car_interface = CarInterface(car_params, car_params_sp) - sunnypilot_interfaces.setup_interfaces(car_interface) - assert car_params - assert car_params_sp - assert car_interface - - assert car_params.mass > 1 - assert car_params.wheelbase > 0 - # centerToFront is center of gravity to front wheels, assert a reasonable range - assert car_params.wheelbase * 0.3 < car_params.centerToFront < car_params.wheelbase * 0.7 - assert car_params.maxLateralAccel > 0 - - # Longitudinal sanity checks - assert len(car_params.longitudinalTuning.kpV) == len(car_params.longitudinalTuning.kpBP) - assert len(car_params.longitudinalTuning.kiV) == len(car_params.longitudinalTuning.kiBP) - - # Lateral sanity checks - if car_params.steerControlType != CarParams.SteerControlType.angle: - tune = car_params.lateralTuning - if tune.which() == 'pid': - if car_name != MOCK.MOCK: - assert not math.isnan(tune.pid.kf) and tune.pid.kf > 0 - assert len(tune.pid.kpV) > 0 and len(tune.pid.kpV) == len(tune.pid.kpBP) - assert len(tune.pid.kiV) > 0 and len(tune.pid.kiV) == len(tune.pid.kiBP) - - elif tune.which() == 'torque': - assert not math.isnan(tune.torque.kf) and tune.torque.kf > 0 - assert not math.isnan(tune.torque.friction) and tune.torque.friction > 0 - - cc_msg = FuzzyGenerator.get_random_msg(data.draw, car.CarControl, real_floats=True) - cc_sp_msg = FuzzyGenerator.get_random_msg(data.draw, custom.CarControlSP, real_floats=True) - # Run car interface - now_nanos = 0 - CC = car.CarControl.new_message(**cc_msg) - CC = CC.as_reader() - CC_SP = custom.CarControlSP.new_message(**cc_sp_msg) - CC_SP = convert_carControlSP(CC_SP.as_reader()) - for _ in range(10): - car_interface.update([]) - car_interface.apply(CC, CC_SP, now_nanos) - now_nanos += DT_CTRL * 1e9 # 10 ms - - CC = car.CarControl.new_message(**cc_msg) - CC.enabled = True - CC.latActive = True - CC.longActive = True - CC = CC.as_reader() - for _ in range(10): - car_interface.update([]) - car_interface.apply(CC, CC_SP, now_nanos) - now_nanos += DT_CTRL * 1e9 # 10ms - - # Test controller initialization - # TODO: wait until card refactor is merged to run controller a few times, - # hypothesis also slows down significantly with just one more message draw - LongControl(car_params) - if car_params.steerControlType == CarParams.SteerControlType.angle: - LatControlAngle(car_params, car_params_sp, car_interface) - elif car_params.lateralTuning.which() == 'pid': - LatControlPID(car_params, car_params_sp, car_interface) - elif car_params.lateralTuning.which() == 'torque': - LatControlTorque(car_params, car_params_sp, car_interface) diff --git a/selfdrive/car/tests/test_docs.py b/selfdrive/car/tests/test_docs.py deleted file mode 100644 index 6e13d55b29..0000000000 --- a/selfdrive/car/tests/test_docs.py +++ /dev/null @@ -1,22 +0,0 @@ -import os - -from openpilot.common.basedir import BASEDIR -from opendbc.car.docs import generate_cars_md, get_all_car_docs -from openpilot.selfdrive.debug.dump_car_docs import dump_car_docs -from openpilot.selfdrive.debug.print_docs_diff import print_car_docs_diff -from openpilot.selfdrive.car.docs import CARS_MD_TEMPLATE - - -class TestCarDocs: - @classmethod - def setup_class(cls): - cls.all_cars = get_all_car_docs() - - def test_generator(self): - generate_cars_md(self.all_cars, CARS_MD_TEMPLATE) - - def test_docs_diff(self): - dump_path = os.path.join(BASEDIR, "selfdrive", "car", "tests", "cars_dump") - dump_car_docs(dump_path) - print_car_docs_diff(dump_path) - os.remove(dump_path) diff --git a/selfdrive/controls/.gitignore b/selfdrive/controls/.gitignore deleted file mode 100644 index 22a371d8ff..0000000000 --- a/selfdrive/controls/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -calibration_param -traces diff --git a/selfdrive/controls/controlsd.py b/selfdrive/controls/controlsd.py deleted file mode 100755 index 08b22a444e..0000000000 --- a/selfdrive/controls/controlsd.py +++ /dev/null @@ -1,261 +0,0 @@ -#!/usr/bin/env python3 -import math -import threading -import time -from typing import SupportsFloat - -from cereal import car, log -import cereal.messaging as messaging -from openpilot.common.conversions import Conversions as CV -from openpilot.common.params import Params -from openpilot.common.realtime import config_realtime_process, Priority, Ratekeeper -from openpilot.common.swaglog import cloudlog - -from opendbc.car.car_helpers import interfaces -from opendbc.car.vehicle_model import VehicleModel -from openpilot.selfdrive.controls.lib.drive_helpers import clip_curvature -from openpilot.selfdrive.controls.lib.latcontrol import LatControl -from openpilot.selfdrive.controls.lib.latcontrol_pid import LatControlPID -from openpilot.selfdrive.controls.lib.latcontrol_angle import LatControlAngle, STEER_ANGLE_SATURATION_THRESHOLD -from openpilot.selfdrive.controls.lib.latcontrol_angle_torque import LatControlAngleTorque -from openpilot.selfdrive.controls.lib.latcontrol_torque import LatControlTorque -from openpilot.selfdrive.controls.lib.longcontrol import LongControl -from openpilot.selfdrive.locationd.helpers import PoseCalibrator, Pose - -from openpilot.sunnypilot.selfdrive.controls.controlsd_ext import ControlsExt - -State = log.SelfdriveState.OpenpilotState -LaneChangeState = log.LaneChangeState -LaneChangeDirection = log.LaneChangeDirection - -ACTUATOR_FIELDS = tuple(car.CarControl.Actuators.schema.fields.keys()) - - -class Controls(ControlsExt): - def __init__(self) -> None: - self.params = Params() - cloudlog.info("controlsd is waiting for CarParams") - self.CP = messaging.log_from_bytes(self.params.get("CarParams", block=True), car.CarParams) - cloudlog.info("controlsd got CarParams") - - # Initialize sunnypilot controlsd extension - ControlsExt.__init__(self, self.CP, self.params) - - self.CI = interfaces[self.CP.carFingerprint](self.CP, self.CP_SP) - - self.sm = messaging.SubMaster(['liveParameters', 'liveTorqueParameters', 'modelV2', 'selfdriveState', - 'liveCalibration', 'livePose', 'longitudinalPlan', 'carState', 'carOutput', - 'driverMonitoringState', 'onroadEvents', 'driverAssistance', 'liveDelay'] + self.sm_services_ext, - poll='selfdriveState') - self.pm = messaging.PubMaster(['carControl', 'controlsState'] + self.pm_services_ext) - - self.steer_limited_by_controls = False - self.curvature = 0.0 - self.desired_curvature = 0.0 - - self.pose_calibrator = PoseCalibrator() - self.calibrated_pose: Pose | None = None - - self.LoC = LongControl(self.CP) - self.VM = VehicleModel(self.CP) - self.LaC: LatControl - if self.CP.steerControlType == car.CarParams.SteerControlType.angle and self.CP.lateralTuning.which() == 'torque': - self.LaC = LatControlAngleTorque(self.CP, self.CP_SP, self.CI) - elif self.CP.steerControlType == car.CarParams.SteerControlType.angle: - self.LaC = LatControlAngle(self.CP, self.CP_SP, self.CI) - elif self.CP.lateralTuning.which() == 'pid': - self.LaC = LatControlPID(self.CP, self.CP_SP, self.CI) - elif self.CP.lateralTuning.which() == 'torque': - self.LaC = LatControlTorque(self.CP, self.CP_SP, self.CI) - - def update(self): - self.sm.update(15) - if self.sm.updated["liveCalibration"]: - self.pose_calibrator.feed_live_calib(self.sm['liveCalibration']) - if self.sm.updated["livePose"]: - device_pose = Pose.from_live_pose(self.sm['livePose']) - self.calibrated_pose = self.pose_calibrator.build_calibrated_pose(device_pose) - - def state_control(self): - CS = self.sm['carState'] - - # Update VehicleModel - lp = self.sm['liveParameters'] - x = max(lp.stiffnessFactor, 0.1) - sr = max(lp.steerRatio, 0.1) - self.VM.update_params(x, sr) - - steer_angle_without_offset = math.radians(CS.steeringAngleDeg - lp.angleOffsetDeg) - self.curvature = -self.VM.calc_curvature(steer_angle_without_offset, CS.vEgo, lp.roll) - - # Update Torque Params - if self.CP.lateralTuning.which() == 'torque': - torque_params = self.sm['liveTorqueParameters'] - if self.sm.all_checks(['liveTorqueParameters']) and torque_params.useParams: - self.LaC.update_live_torque_params(torque_params.latAccelFactorFiltered, torque_params.latAccelOffsetFiltered, - torque_params.frictionCoefficientFiltered) - - self.LaC.extension.update_model_v2(self.sm['modelV2']) - self.LaC.extension.update_lateral_lag(self.sm['liveDelay'].lateralDelay) - - long_plan = self.sm['longitudinalPlan'] - model_v2 = self.sm['modelV2'] - - CC = car.CarControl.new_message() - CC.enabled = self.sm['selfdriveState'].enabled - - # Check which actuators can be enabled - standstill = abs(CS.vEgo) <= max(self.CP.minSteerSpeed, 0.3) or CS.standstill - - # Get which state to use for active lateral control - _lat_active = self.get_lat_active(self.sm) - - CC.latActive = _lat_active and not CS.steerFaultTemporary and not CS.steerFaultPermanent and \ - (not standstill or self.CP.steerAtStandstill) - CC.longActive = CC.enabled and not any(e.overrideLongitudinal for e in self.sm['onroadEvents']) and self.CP.openpilotLongitudinalControl - - actuators = CC.actuators - actuators.longControlState = self.LoC.long_control_state - - # Enable blinkers while lane changing - if model_v2.meta.laneChangeState != LaneChangeState.off: - CC.leftBlinker = model_v2.meta.laneChangeDirection == LaneChangeDirection.left - CC.rightBlinker = model_v2.meta.laneChangeDirection == LaneChangeDirection.right - - if not CC.latActive: - self.LaC.reset() - if not CC.longActive: - self.LoC.reset() - - # accel PID loop - pid_accel_limits = self.CI.get_pid_accel_limits(self.CP, CS.vEgo, CS.vCruise * CV.KPH_TO_MS) - actuators.accel = float(self.LoC.update(CC.longActive, CS, long_plan.aTarget, long_plan.shouldStop, pid_accel_limits)) - - # Steering PID loop and lateral MPC - # Reset desired curvature to current to avoid violating the limits on engage - new_desired_curvature = model_v2.action.desiredCurvature if CC.latActive else self.curvature - self.desired_curvature, curvature_limited = clip_curvature(CS.vEgo, self.desired_curvature, new_desired_curvature, lp.roll) - - actuators.curvature = self.desired_curvature - steer, steeringAngleDeg, lac_log = self.LaC.update(CC.latActive, CS, self.VM, lp, - self.steer_limited_by_controls, self.desired_curvature, - self.calibrated_pose, curvature_limited) # TODO what if not available - actuators.torque = float(steer) - actuators.steeringAngleDeg = float(steeringAngleDeg) - # Ensure no NaNs/Infs - for p in ACTUATOR_FIELDS: - attr = getattr(actuators, p) - if not isinstance(attr, SupportsFloat): - continue - - if not math.isfinite(attr): - cloudlog.error(f"actuators.{p} not finite {actuators.to_dict()}") - setattr(actuators, p, 0.0) - - return CC, lac_log - - def publish(self, CC, lac_log): - CS = self.sm['carState'] - - # Orientation and angle rates can be useful for carcontroller - # Only calibrated (car) frame is relevant for the carcontroller - CC.currentCurvature = self.curvature - if self.calibrated_pose is not None: - CC.orientationNED = self.calibrated_pose.orientation.xyz.tolist() - CC.angularVelocity = self.calibrated_pose.angular_velocity.xyz.tolist() - - CC.cruiseControl.override = CC.enabled and not CC.longActive and self.CP.openpilotLongitudinalControl - CC.cruiseControl.cancel = CS.cruiseState.enabled and (not CC.enabled or not self.CP.pcmCruise) - - speeds = self.sm['longitudinalPlan'].speeds - if len(speeds): - CC.cruiseControl.resume = CC.enabled and CS.cruiseState.standstill and speeds[-1] > 0.1 - - hudControl = CC.hudControl - hudControl.setSpeed = float(CS.vCruiseCluster * CV.KPH_TO_MS) - hudControl.speedVisible = CC.enabled - hudControl.lanesVisible = CC.enabled - hudControl.leadVisible = self.sm['longitudinalPlan'].hasLead - hudControl.leadDistanceBars = self.sm['selfdriveState'].personality.raw + 1 - hudControl.visualAlert = self.sm['selfdriveState'].alertHudVisual - - hudControl.rightLaneVisible = True - hudControl.leftLaneVisible = True - if self.sm.valid['driverAssistance']: - hudControl.leftLaneDepart = self.sm['driverAssistance'].leftLaneDeparture - hudControl.rightLaneDepart = self.sm['driverAssistance'].rightLaneDeparture - - if self.sm['selfdriveState'].active: - CO = self.sm['carOutput'] - if self.CP.steerControlType == car.CarParams.SteerControlType.angle: - self.steer_limited_by_controls = abs(CC.actuators.steeringAngleDeg - CO.actuatorsOutput.steeringAngleDeg) > \ - STEER_ANGLE_SATURATION_THRESHOLD - else: - self.steer_limited_by_controls = abs(CC.actuators.torque - CO.actuatorsOutput.torque) > 1e-2 - - # TODO: both controlsState and carControl valids should be set by - # sm.all_checks(), but this creates a circular dependency - - # controlsState - dat = messaging.new_message('controlsState') - dat.valid = CS.canValid - cs = dat.controlsState - - cs.curvature = self.curvature - cs.longitudinalPlanMonoTime = self.sm.logMonoTime['longitudinalPlan'] - cs.lateralPlanMonoTime = self.sm.logMonoTime['modelV2'] - cs.desiredCurvature = self.desired_curvature - cs.longControlState = self.LoC.long_control_state - cs.upAccelCmd = float(self.LoC.pid.p) - cs.uiAccelCmd = float(self.LoC.pid.i) - cs.ufAccelCmd = float(self.LoC.pid.f) - cs.forceDecel = bool((self.sm['driverMonitoringState'].awarenessStatus < 0.) or - (self.sm['selfdriveState'].state == State.softDisabling)) - - lat_tuning = self.CP.lateralTuning.which() - if self.CP.steerControlType == car.CarParams.SteerControlType.angle: - cs.lateralControlState.angleState = lac_log - elif lat_tuning == 'pid': - cs.lateralControlState.pidState = lac_log - elif lat_tuning == 'torque': - cs.lateralControlState.torqueState = lac_log - - self.pm.send('controlsState', dat) - - # carControl - cc_send = messaging.new_message('carControl') - cc_send.valid = CS.canValid - cc_send.carControl = CC - self.pm.send('carControl', cc_send) - - def params_thread(self, evt): - while not evt.is_set(): - self.get_params_sp() - - time.sleep(0.1) - - def run(self): - rk = Ratekeeper(100, print_delay_threshold=None) - e = threading.Event() - t = threading.Thread(target=self.params_thread, args=(e,)) - try: - t.start() - while True: - self.update() - CC, lac_log = self.state_control() - self.publish(CC, lac_log) - self.run_ext(self.sm, self.pm) - rk.monitor_time() - finally: - e.set() - t.join() - - -def main(): - config_realtime_process(4, Priority.CTRL_HIGH) - controls = Controls() - controls.run() - - -if __name__ == "__main__": - main() diff --git a/selfdrive/controls/lib/desire_helper.py b/selfdrive/controls/lib/desire_helper.py deleted file mode 100644 index 23386e2ad7..0000000000 --- a/selfdrive/controls/lib/desire_helper.py +++ /dev/null @@ -1,121 +0,0 @@ -from cereal import log -from openpilot.common.conversions import Conversions as CV -from openpilot.common.realtime import DT_MDL -from openpilot.sunnypilot.selfdrive.controls.lib.auto_lane_change import AutoLaneChangeController, AutoLaneChangeMode - -LaneChangeState = log.LaneChangeState -LaneChangeDirection = log.LaneChangeDirection - -LANE_CHANGE_SPEED_MIN = 20 * CV.MPH_TO_MS -LANE_CHANGE_TIME_MAX = 10. - -DESIRES = { - LaneChangeDirection.none: { - LaneChangeState.off: log.Desire.none, - LaneChangeState.preLaneChange: log.Desire.none, - LaneChangeState.laneChangeStarting: log.Desire.none, - LaneChangeState.laneChangeFinishing: log.Desire.none, - }, - LaneChangeDirection.left: { - LaneChangeState.off: log.Desire.none, - LaneChangeState.preLaneChange: log.Desire.none, - LaneChangeState.laneChangeStarting: log.Desire.laneChangeLeft, - LaneChangeState.laneChangeFinishing: log.Desire.laneChangeLeft, - }, - LaneChangeDirection.right: { - LaneChangeState.off: log.Desire.none, - LaneChangeState.preLaneChange: log.Desire.none, - LaneChangeState.laneChangeStarting: log.Desire.laneChangeRight, - LaneChangeState.laneChangeFinishing: log.Desire.laneChangeRight, - }, -} - - -class DesireHelper: - def __init__(self): - self.lane_change_state = LaneChangeState.off - self.lane_change_direction = LaneChangeDirection.none - self.lane_change_timer = 0.0 - self.lane_change_ll_prob = 1.0 - self.keep_pulse_timer = 0.0 - self.prev_one_blinker = False - self.desire = log.Desire.none - self.alc = AutoLaneChangeController(self) - - def update(self, carstate, lateral_active, lane_change_prob): - self.alc.update_params() - v_ego = carstate.vEgo - one_blinker = carstate.leftBlinker != carstate.rightBlinker - below_lane_change_speed = v_ego < LANE_CHANGE_SPEED_MIN - - if not lateral_active or self.lane_change_timer > LANE_CHANGE_TIME_MAX or self.alc.lane_change_set_timer == AutoLaneChangeMode.OFF: - self.lane_change_state = LaneChangeState.off - self.lane_change_direction = LaneChangeDirection.none - else: - # LaneChangeState.off - if self.lane_change_state == LaneChangeState.off and one_blinker and not self.prev_one_blinker and not below_lane_change_speed: - self.lane_change_state = LaneChangeState.preLaneChange - self.lane_change_ll_prob = 1.0 - - # LaneChangeState.preLaneChange - elif self.lane_change_state == LaneChangeState.preLaneChange: - # Set lane change direction - self.lane_change_direction = LaneChangeDirection.left if \ - carstate.leftBlinker else LaneChangeDirection.right - - torque_applied = carstate.steeringPressed and \ - ((carstate.steeringTorque > 0 and self.lane_change_direction == LaneChangeDirection.left) or - (carstate.steeringTorque < 0 and self.lane_change_direction == LaneChangeDirection.right)) - - blindspot_detected = ((carstate.leftBlindspot and self.lane_change_direction == LaneChangeDirection.left) or - (carstate.rightBlindspot and self.lane_change_direction == LaneChangeDirection.right)) - - self.alc.update_lane_change(blindspot_detected, carstate.brakePressed) - - if not one_blinker or below_lane_change_speed: - self.lane_change_state = LaneChangeState.off - self.lane_change_direction = LaneChangeDirection.none - elif (torque_applied or self.alc.auto_lane_change_allowed) and not blindspot_detected: - self.lane_change_state = LaneChangeState.laneChangeStarting - - # LaneChangeState.laneChangeStarting - elif self.lane_change_state == LaneChangeState.laneChangeStarting: - # fade out over .5s - self.lane_change_ll_prob = max(self.lane_change_ll_prob - 2 * DT_MDL, 0.0) - - # 98% certainty - if lane_change_prob < 0.02 and self.lane_change_ll_prob < 0.01: - self.lane_change_state = LaneChangeState.laneChangeFinishing - - # LaneChangeState.laneChangeFinishing - elif self.lane_change_state == LaneChangeState.laneChangeFinishing: - # fade in laneline over 1s - self.lane_change_ll_prob = min(self.lane_change_ll_prob + DT_MDL, 1.0) - - if self.lane_change_ll_prob > 0.99: - self.lane_change_direction = LaneChangeDirection.none - if one_blinker: - self.lane_change_state = LaneChangeState.preLaneChange - else: - self.lane_change_state = LaneChangeState.off - - if self.lane_change_state in (LaneChangeState.off, LaneChangeState.preLaneChange): - self.lane_change_timer = 0.0 - else: - self.lane_change_timer += DT_MDL - - self.prev_one_blinker = one_blinker - - self.desire = DESIRES[self.lane_change_direction][self.lane_change_state] - - # Send keep pulse once per second during LaneChangeStart.preLaneChange - if self.lane_change_state in (LaneChangeState.off, LaneChangeState.laneChangeStarting): - self.keep_pulse_timer = 0.0 - elif self.lane_change_state == LaneChangeState.preLaneChange: - self.keep_pulse_timer += DT_MDL - if self.keep_pulse_timer > 1.0: - self.keep_pulse_timer = 0.0 - elif self.desire in (log.Desire.keepLeft, log.Desire.keepRight): - self.desire = log.Desire.none - - self.alc.update_state() diff --git a/selfdrive/controls/lib/drive_helpers.py b/selfdrive/controls/lib/drive_helpers.py deleted file mode 100644 index 56eeac3bdf..0000000000 --- a/selfdrive/controls/lib/drive_helpers.py +++ /dev/null @@ -1,74 +0,0 @@ -import numpy as np -from cereal import log -from opendbc.car.vehicle_model import ACCELERATION_DUE_TO_GRAVITY -from openpilot.common.realtime import DT_CTRL, DT_MDL - -MIN_SPEED = 1.0 -CONTROL_N = 17 -CAR_ROTATION_RADIUS = 0.0 -# This is a turn radius smaller than most cars can achieve -MAX_CURVATURE = 0.2 -MAX_VEL_ERR = 5.0 # m/s - -# EU guidelines -MAX_LATERAL_JERK = 5.0 # m/s^3 -MAX_LATERAL_ACCEL_NO_ROLL = 3.0 # m/s^2 - - -def clamp(val, min_val, max_val): - clamped_val = float(np.clip(val, min_val, max_val)) - return clamped_val, clamped_val != val - -def smooth_value(val, prev_val, tau, dt=DT_MDL): - alpha = 1 - np.exp(-dt/tau) if tau > 0 else 1 - return alpha * val + (1 - alpha) * prev_val - -def clip_curvature(v_ego, prev_curvature, new_curvature, roll): - # This function respects ISO lateral jerk and acceleration limits + a max curvature - v_ego = max(v_ego, MIN_SPEED) - max_curvature_rate = MAX_LATERAL_JERK / (v_ego ** 2) # inexact calculation, check https://github.com/commaai/openpilot/pull/24755 - new_curvature = np.clip(new_curvature, - prev_curvature - max_curvature_rate * DT_CTRL, - prev_curvature + max_curvature_rate * DT_CTRL) - - roll_compensation = roll * ACCELERATION_DUE_TO_GRAVITY - max_lat_accel = MAX_LATERAL_ACCEL_NO_ROLL + roll_compensation - min_lat_accel = -MAX_LATERAL_ACCEL_NO_ROLL + roll_compensation - new_curvature, limited_accel = clamp(new_curvature, min_lat_accel / v_ego ** 2, max_lat_accel / v_ego ** 2) - - new_curvature, limited_max_curv = clamp(new_curvature, -MAX_CURVATURE, MAX_CURVATURE) - return float(new_curvature), limited_accel or limited_max_curv - - -def get_speed_error(modelV2: log.ModelDataV2, v_ego: float) -> float: - # ToDo: Try relative error, and absolute speed - if len(modelV2.temporalPose.trans): - vel_err = np.clip(modelV2.temporalPose.trans[0] - v_ego, -MAX_VEL_ERR, MAX_VEL_ERR) - return float(vel_err) - return 0.0 - - -def get_accel_from_plan(speeds, accels, t_idxs, action_t=DT_MDL, vEgoStopping=0.05): - if len(speeds) == len(t_idxs): - v_now = speeds[0] - a_now = accels[0] - v_target = np.interp(action_t, t_idxs, speeds) - a_target = 2 * (v_target - v_now) / (action_t) - a_now - v_target_1sec = np.interp(action_t + 1.0, t_idxs, speeds) - else: - v_target = 0.0 - v_target_1sec = 0.0 - a_target = 0.0 - should_stop = (v_target < vEgoStopping and - v_target_1sec < vEgoStopping) - return a_target, should_stop - -def curv_from_psis(psi_target, psi_rate, vego, action_t): - vego = np.clip(vego, MIN_SPEED, np.inf) - curv_from_psi = psi_target / (vego * action_t) - return 2*curv_from_psi - psi_rate / vego - -def get_curvature_from_plan(yaws, yaw_rates, t_idxs, vego, action_t): - psi_target = np.interp(action_t, t_idxs, yaws) - psi_rate = yaw_rates[0] - return curv_from_psis(psi_target, psi_rate, vego, action_t) diff --git a/selfdrive/controls/lib/latcontrol.py b/selfdrive/controls/lib/latcontrol.py deleted file mode 100644 index a2c28ed8ce..0000000000 --- a/selfdrive/controls/lib/latcontrol.py +++ /dev/null @@ -1,31 +0,0 @@ -import numpy as np -from abc import abstractmethod, ABC - -from openpilot.common.realtime import DT_CTRL - - -class LatControl(ABC): - def __init__(self, CP, CP_SP, CI): - self.sat_count_rate = 1.0 * DT_CTRL - self.sat_limit = CP.steerLimitTimer - self.sat_count = 0. - self.sat_check_min_speed = 10. - - # we define the steer torque scale as [-1.0...1.0] - self.steer_max = 1.0 - - @abstractmethod - def update(self, active, CS, VM, params, steer_limited_by_controls, desired_curvature, calibrated_pose, curvature_limited): - pass - - def reset(self): - self.sat_count = 0. - - def _check_saturation(self, saturated, CS, steer_limited_by_controls, curvature_limited): - # Saturated only if control output is not being limited by car torque/angle rate limits - if (saturated or curvature_limited) and CS.vEgo > self.sat_check_min_speed and not steer_limited_by_controls and not CS.steeringPressed: - self.sat_count += self.sat_count_rate - else: - self.sat_count -= self.sat_count_rate - self.sat_count = np.clip(self.sat_count, 0.0, self.sat_limit) - return self.sat_count > (self.sat_limit - 1e-3) diff --git a/selfdrive/controls/lib/latcontrol_angle.py b/selfdrive/controls/lib/latcontrol_angle.py deleted file mode 100644 index fe6275d9d0..0000000000 --- a/selfdrive/controls/lib/latcontrol_angle.py +++ /dev/null @@ -1,36 +0,0 @@ -import math - -from cereal import log -from openpilot.selfdrive.controls.lib.latcontrol import LatControl - -STEER_ANGLE_SATURATION_THRESHOLD = 2.5 # Degrees - - -class LatControlAngle(LatControl): - def __init__(self, CP, CP_SP, CI): - super().__init__(CP, CP_SP, CI) - self.sat_check_min_speed = 5. - self.use_steer_limited_by_controls = CP.brand == "tesla" - - def update(self, active, CS, VM, params, steer_limited_by_controls, desired_curvature, calibrated_pose, curvature_limited): - angle_log = log.ControlsState.LateralAngleState.new_message() - - if not active: - angle_log.active = False - angle_steers_des = float(CS.steeringAngleDeg) - else: - angle_log.active = True - angle_steers_des = math.degrees(VM.get_steer_from_curvature(-desired_curvature, CS.vEgo, params.roll)) - angle_steers_des += params.angleOffsetDeg - - if self.use_steer_limited_by_controls: - # these cars' carcontrollers calculate max lateral accel and jerk, so we can rely on carOutput for saturation - angle_control_saturated = steer_limited_by_controls - else: - # for cars which use a method of limiting torque such as a torque signal (Nissan and Toyota) - # or relying on EPS (Ford Q3), carOutput does not capture maxing out torque # TODO: this can be improved - angle_control_saturated = abs(angle_steers_des - CS.steeringAngleDeg) > STEER_ANGLE_SATURATION_THRESHOLD - angle_log.saturated = bool(self._check_saturation(angle_control_saturated, CS, False, curvature_limited)) - angle_log.steeringAngleDeg = float(CS.steeringAngleDeg) - angle_log.steeringAngleDesiredDeg = angle_steers_des - return 0, float(angle_steers_des), angle_log diff --git a/selfdrive/controls/lib/latcontrol_angle_torque.py b/selfdrive/controls/lib/latcontrol_angle_torque.py deleted file mode 100644 index 7c6691f738..0000000000 --- a/selfdrive/controls/lib/latcontrol_angle_torque.py +++ /dev/null @@ -1,13 +0,0 @@ -from openpilot.selfdrive.controls.lib.latcontrol_torque import LatControlTorque -from openpilot.selfdrive.controls.lib.latcontrol_angle import LatControlAngle - - -class LatControlAngleTorque(LatControlTorque, LatControlAngle): - def __init__(self, CP, CP_SP, CI): - LatControlTorque.__init__(self, CP, CP_SP, CI) - LatControlAngle.__init__(self, CP, CP_SP, CI) - - def update(self, active, CS, VM, params, steer_limited_by_controls, desired_curvature, calibrated_pose, curvature_limited): - torque, _, _ = LatControlTorque.update(self, active, CS, VM, params, steer_limited_by_controls, desired_curvature, calibrated_pose, curvature_limited) - _, angle, angle_log = LatControlAngle.update(self, active, CS, VM, params, steer_limited_by_controls, desired_curvature, calibrated_pose, curvature_limited) - return torque, angle, angle_log diff --git a/selfdrive/controls/lib/latcontrol_pid.py b/selfdrive/controls/lib/latcontrol_pid.py deleted file mode 100644 index eb8a1ed5f9..0000000000 --- a/selfdrive/controls/lib/latcontrol_pid.py +++ /dev/null @@ -1,48 +0,0 @@ -import math - -from cereal import log -from openpilot.selfdrive.controls.lib.latcontrol import LatControl -from openpilot.common.pid import PIDController - - -class LatControlPID(LatControl): - def __init__(self, CP, CP_SP, CI): - super().__init__(CP, CP_SP, CI) - self.pid = PIDController((CP.lateralTuning.pid.kpBP, CP.lateralTuning.pid.kpV), - (CP.lateralTuning.pid.kiBP, CP.lateralTuning.pid.kiV), - k_f=CP.lateralTuning.pid.kf, pos_limit=self.steer_max, neg_limit=-self.steer_max) - self.get_steer_feedforward = CI.get_steer_feedforward_function() - - def reset(self): - super().reset() - self.pid.reset() - - def update(self, active, CS, VM, params, steer_limited_by_controls, desired_curvature, calibrated_pose, curvature_limited): - pid_log = log.ControlsState.LateralPIDState.new_message() - pid_log.steeringAngleDeg = float(CS.steeringAngleDeg) - pid_log.steeringRateDeg = float(CS.steeringRateDeg) - - angle_steers_des_no_offset = math.degrees(VM.get_steer_from_curvature(-desired_curvature, CS.vEgo, params.roll)) - angle_steers_des = angle_steers_des_no_offset + params.angleOffsetDeg - error = angle_steers_des - CS.steeringAngleDeg - - pid_log.steeringAngleDesiredDeg = angle_steers_des - pid_log.angleError = error - if not active: - output_steer = 0.0 - pid_log.active = False - self.pid.reset() - else: - # offset does not contribute to resistive torque - steer_feedforward = self.get_steer_feedforward(angle_steers_des_no_offset, CS.vEgo) - - output_steer = self.pid.update(error, override=CS.steeringPressed, - feedforward=steer_feedforward, speed=CS.vEgo) - pid_log.active = True - pid_log.p = float(self.pid.p) - pid_log.i = float(self.pid.i) - pid_log.f = float(self.pid.f) - pid_log.output = float(output_steer) - pid_log.saturated = bool(self._check_saturation(self.steer_max - abs(output_steer) < 1e-3, CS, steer_limited_by_controls, curvature_limited)) - - return output_steer, angle_steers_des, pid_log diff --git a/selfdrive/controls/lib/latcontrol_torque.py b/selfdrive/controls/lib/latcontrol_torque.py deleted file mode 100644 index 5edf4cf91b..0000000000 --- a/selfdrive/controls/lib/latcontrol_torque.py +++ /dev/null @@ -1,103 +0,0 @@ -import math -import numpy as np - -from cereal import log -from opendbc.car.interfaces import LatControlInputs -from opendbc.car.vehicle_model import ACCELERATION_DUE_TO_GRAVITY -from openpilot.selfdrive.controls.lib.latcontrol import LatControl -from openpilot.common.pid import PIDController - -from openpilot.sunnypilot.selfdrive.controls.lib.latcontrol_torque_ext import LatControlTorqueExt - -# At higher speeds (25+mph) we can assume: -# Lateral acceleration achieved by a specific car correlates to -# torque applied to the steering rack. It does not correlate to -# wheel slip, or to speed. - -# This controller applies torque to achieve desired lateral -# accelerations. To compensate for the low speed effects we -# use a LOW_SPEED_FACTOR in the error. Additionally, there is -# friction in the steering wheel that needs to be overcome to -# move it at all, this is compensated for too. - -LOW_SPEED_X = [0, 10, 20, 30] -LOW_SPEED_Y = [15, 13, 10, 5] - - -class LatControlTorque(LatControl): - def __init__(self, CP, CP_SP, CI): - super().__init__(CP, CP_SP, CI) - self.torque_params = CP.lateralTuning.torque.as_builder() - self.pid = PIDController(self.torque_params.kp, self.torque_params.ki, - k_f=self.torque_params.kf, pos_limit=self.steer_max, neg_limit=-self.steer_max) - self.torque_from_lateral_accel = CI.torque_from_lateral_accel() - self.use_steering_angle = self.torque_params.useSteeringAngle - self.steering_angle_deadzone_deg = self.torque_params.steeringAngleDeadzoneDeg - - self.extension = LatControlTorqueExt(self, CP, CP_SP) - - def update_live_torque_params(self, latAccelFactor, latAccelOffset, friction): - self.torque_params.latAccelFactor = latAccelFactor - self.torque_params.latAccelOffset = latAccelOffset - self.torque_params.friction = friction - - def update(self, active, CS, VM, params, steer_limited_by_controls, desired_curvature, calibrated_pose, curvature_limited): - pid_log = log.ControlsState.LateralTorqueState.new_message() - if not active: - output_torque = 0.0 - pid_log.active = False - else: - actual_curvature_vm = -VM.calc_curvature(math.radians(CS.steeringAngleDeg - params.angleOffsetDeg), CS.vEgo, params.roll) - roll_compensation = params.roll * ACCELERATION_DUE_TO_GRAVITY - if self.use_steering_angle: - actual_curvature = actual_curvature_vm - curvature_deadzone = abs(VM.calc_curvature(math.radians(self.steering_angle_deadzone_deg), CS.vEgo, 0.0)) - else: - assert calibrated_pose is not None - actual_curvature_pose = calibrated_pose.angular_velocity.yaw / CS.vEgo - actual_curvature = np.interp(CS.vEgo, [2.0, 5.0], [actual_curvature_vm, actual_curvature_pose]) - curvature_deadzone = 0.0 - desired_lateral_accel = desired_curvature * CS.vEgo ** 2 - - # desired rate is the desired rate of change in the setpoint, not the absolute desired curvature - # desired_lateral_jerk = desired_curvature_rate * CS.vEgo ** 2 - actual_lateral_accel = actual_curvature * CS.vEgo ** 2 - lateral_accel_deadzone = curvature_deadzone * CS.vEgo ** 2 - - low_speed_factor = np.interp(CS.vEgo, LOW_SPEED_X, LOW_SPEED_Y)**2 - setpoint = desired_lateral_accel + low_speed_factor * desired_curvature - measurement = actual_lateral_accel + low_speed_factor * actual_curvature - gravity_adjusted_lateral_accel = desired_lateral_accel - roll_compensation - torque_from_setpoint = self.torque_from_lateral_accel(LatControlInputs(setpoint, roll_compensation, CS.vEgo, CS.aEgo), self.torque_params, - setpoint, lateral_accel_deadzone, friction_compensation=False, gravity_adjusted=False) - torque_from_measurement = self.torque_from_lateral_accel(LatControlInputs(measurement, roll_compensation, CS.vEgo, CS.aEgo), self.torque_params, - measurement, lateral_accel_deadzone, friction_compensation=False, gravity_adjusted=False) - pid_log.error = float(torque_from_setpoint - torque_from_measurement) - ff = self.torque_from_lateral_accel(LatControlInputs(gravity_adjusted_lateral_accel, roll_compensation, CS.vEgo, CS.aEgo), self.torque_params, - desired_lateral_accel - actual_lateral_accel, lateral_accel_deadzone, friction_compensation=True, - gravity_adjusted=True) - - # Lateral acceleration torque controller extension updates - # Overrides stock ff and pid_log.error - ff, pid_log = self.extension.update(CS, VM, params, ff, pid_log, setpoint, measurement, calibrated_pose, roll_compensation, - desired_lateral_accel, actual_lateral_accel, lateral_accel_deadzone, gravity_adjusted_lateral_accel, - desired_curvature, actual_curvature) - - freeze_integrator = steer_limited_by_controls or CS.steeringPressed or CS.vEgo < 5 - output_torque = self.pid.update(pid_log.error, - feedforward=ff, - speed=CS.vEgo, - freeze_integrator=freeze_integrator) - - pid_log.active = True - pid_log.p = float(self.pid.p) - pid_log.i = float(self.pid.i) - pid_log.d = float(self.pid.d) - pid_log.f = float(self.pid.f) - pid_log.output = float(-output_torque) - pid_log.actualLateralAccel = float(actual_lateral_accel) - pid_log.desiredLateralAccel = float(desired_lateral_accel) - pid_log.saturated = bool(self._check_saturation(self.steer_max - abs(output_torque) < 1e-3, CS, steer_limited_by_controls, curvature_limited)) - - # TODO left is positive in this convention - return -output_torque, 0.0, pid_log diff --git a/selfdrive/controls/lib/lateral_mpc_lib/.gitignore b/selfdrive/controls/lib/lateral_mpc_lib/.gitignore deleted file mode 100644 index aff2eb082b..0000000000 --- a/selfdrive/controls/lib/lateral_mpc_lib/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -acados_ocp_lat.json -c_generated_code/ diff --git a/selfdrive/controls/lib/lateral_mpc_lib/SConscript b/selfdrive/controls/lib/lateral_mpc_lib/SConscript deleted file mode 100644 index 2c03da06a6..0000000000 --- a/selfdrive/controls/lib/lateral_mpc_lib/SConscript +++ /dev/null @@ -1,91 +0,0 @@ -Import('env', 'envCython', 'arch', 'msgq_python', 'common_python', 'opendbc_python', 'np_version') - -gen = "c_generated_code" - -casadi_model = [ - f'{gen}/lat_model/lat_expl_ode_fun.c', - f'{gen}/lat_model/lat_expl_vde_forw.c', -] - -casadi_cost_y = [ - f'{gen}/lat_cost/lat_cost_y_fun.c', - f'{gen}/lat_cost/lat_cost_y_fun_jac_ut_xt.c', - f'{gen}/lat_cost/lat_cost_y_hess.c', -] - -casadi_cost_e = [ - f'{gen}/lat_cost/lat_cost_y_e_fun.c', - f'{gen}/lat_cost/lat_cost_y_e_fun_jac_ut_xt.c', - f'{gen}/lat_cost/lat_cost_y_e_hess.c', -] - -casadi_cost_0 = [ - f'{gen}/lat_cost/lat_cost_y_0_fun.c', - f'{gen}/lat_cost/lat_cost_y_0_fun_jac_ut_xt.c', - f'{gen}/lat_cost/lat_cost_y_0_hess.c', -] - -build_files = [f'{gen}/acados_solver_lat.c'] + casadi_model + casadi_cost_y + casadi_cost_e + casadi_cost_0 - -# extra generated files used to trigger a rebuild -generated_files = [ - f'{gen}/Makefile', - - f'{gen}/main_lat.c', - f'{gen}/main_sim_lat.c', - f'{gen}/acados_solver_lat.h', - f'{gen}/acados_sim_solver_lat.h', - f'{gen}/acados_sim_solver_lat.c', - f'{gen}/acados_solver.pxd', - - f'{gen}/lat_model/lat_expl_vde_adj.c', - - f'{gen}/lat_model/lat_model.h', - f'{gen}/lat_constraints/lat_constraints.h', - f'{gen}/lat_cost/lat_cost.h', -] + build_files - -acados_dir = '#third_party/acados' -acados_templates_dir = '#third_party/acados/acados_template/c_templates_tera' - -source_list = ['lat_mpc.py', - '#selfdrive/modeld/constants.py', - f'{acados_dir}/include/acados_c/ocp_nlp_interface.h', - f'{acados_templates_dir}/acados_solver.in.c', -] - -lenv = env.Clone() -lenv.Clean(generated_files, Dir(gen)) - -generated_lat = lenv.Command(generated_files, - source_list, - f"cd {Dir('.').abspath} && python3 lat_mpc.py") -lenv.Depends(generated_lat, [msgq_python, common_python, opendbc_python]) - -lenv["CFLAGS"].append("-DACADOS_WITH_QPOASES") -lenv["CXXFLAGS"].append("-DACADOS_WITH_QPOASES") -lenv["CCFLAGS"].append("-Wno-unused") -if arch != "Darwin": - lenv["LINKFLAGS"].append("-Wl,--disable-new-dtags") -lib_solver = lenv.SharedLibrary(f"{gen}/acados_ocp_solver_lat", - build_files, - LIBS=['m', 'acados', 'hpipm', 'blasfeo', 'qpOASES_e']) - -# generate cython stuff -acados_ocp_solver_pyx = File("#third_party/acados/acados_template/acados_ocp_solver_pyx.pyx") -acados_ocp_solver_common = File("#third_party/acados/acados_template/acados_solver_common.pxd") -libacados_ocp_solver_pxd = File(f'{gen}/acados_solver.pxd') -libacados_ocp_solver_c = File(f'{gen}/acados_ocp_solver_pyx.c') - -lenv2 = envCython.Clone() -lenv2["LINKFLAGS"] += [lib_solver[0].get_labspath()] -lenv2.Command(libacados_ocp_solver_c, - [acados_ocp_solver_pyx, acados_ocp_solver_common, libacados_ocp_solver_pxd], - f'cython' + \ - f' -o {libacados_ocp_solver_c.get_labspath()}' + \ - f' -I {libacados_ocp_solver_pxd.get_dir().get_labspath()}' + \ - f' -I {acados_ocp_solver_common.get_dir().get_labspath()}' + \ - f' {acados_ocp_solver_pyx.get_labspath()}') -lib_cython = lenv2.Program(f'{gen}/acados_ocp_solver_pyx.so', [libacados_ocp_solver_c]) -lenv2.Depends(lib_cython, lib_solver) -lenv2.Depends(libacados_ocp_solver_c, np_version) diff --git a/selfdrive/controls/lib/lateral_mpc_lib/lat_mpc.py b/selfdrive/controls/lib/lateral_mpc_lib/lat_mpc.py deleted file mode 100755 index ad60861088..0000000000 --- a/selfdrive/controls/lib/lateral_mpc_lib/lat_mpc.py +++ /dev/null @@ -1,199 +0,0 @@ -#!/usr/bin/env python3 -import os -import time -import numpy as np - -from casadi import SX, vertcat, sin, cos -# WARNING: imports outside of constants will not trigger a rebuild -from openpilot.selfdrive.modeld.constants import ModelConstants - -if __name__ == '__main__': # generating code - from openpilot.third_party.acados.acados_template import AcadosModel, AcadosOcp, AcadosOcpSolver -else: - from openpilot.selfdrive.controls.lib.lateral_mpc_lib.c_generated_code.acados_ocp_solver_pyx import AcadosOcpSolverCython - -LAT_MPC_DIR = os.path.dirname(os.path.abspath(__file__)) -EXPORT_DIR = os.path.join(LAT_MPC_DIR, "c_generated_code") -JSON_FILE = os.path.join(LAT_MPC_DIR, "acados_ocp_lat.json") -X_DIM = 4 -P_DIM = 2 -COST_E_DIM = 3 -COST_DIM = COST_E_DIM + 2 -SPEED_OFFSET = 10.0 -MODEL_NAME = 'lat' -ACADOS_SOLVER_TYPE = 'SQP_RTI' -N = 32 - -def gen_lat_model(): - model = AcadosModel() - model.name = MODEL_NAME - - # set up states & controls - x_ego = SX.sym('x_ego') - y_ego = SX.sym('y_ego') - psi_ego = SX.sym('psi_ego') - psi_rate_ego = SX.sym('psi_rate_ego') - model.x = vertcat(x_ego, y_ego, psi_ego, psi_rate_ego) - - # parameters - v_ego = SX.sym('v_ego') - rotation_radius = SX.sym('rotation_radius') - model.p = vertcat(v_ego, rotation_radius) - - # controls - psi_accel_ego = SX.sym('psi_accel_ego') - model.u = vertcat(psi_accel_ego) - - # xdot - x_ego_dot = SX.sym('x_ego_dot') - y_ego_dot = SX.sym('y_ego_dot') - psi_ego_dot = SX.sym('psi_ego_dot') - psi_rate_ego_dot = SX.sym('psi_rate_ego_dot') - - model.xdot = vertcat(x_ego_dot, y_ego_dot, psi_ego_dot, psi_rate_ego_dot) - - # dynamics model - f_expl = vertcat(v_ego * cos(psi_ego) - rotation_radius * sin(psi_ego) * psi_rate_ego, - v_ego * sin(psi_ego) + rotation_radius * cos(psi_ego) * psi_rate_ego, - psi_rate_ego, - psi_accel_ego) - model.f_impl_expr = model.xdot - f_expl - model.f_expl_expr = f_expl - return model - - -def gen_lat_ocp(): - ocp = AcadosOcp() - ocp.model = gen_lat_model() - - Tf = np.array(ModelConstants.T_IDXS)[N] - - # set dimensions - ocp.dims.N = N - - # set cost module - ocp.cost.cost_type = 'NONLINEAR_LS' - ocp.cost.cost_type_e = 'NONLINEAR_LS' - - Q = np.diag(np.zeros(COST_E_DIM)) - QR = np.diag(np.zeros(COST_DIM)) - - ocp.cost.W = QR - ocp.cost.W_e = Q - - y_ego, psi_ego, psi_rate_ego = ocp.model.x[1], ocp.model.x[2], ocp.model.x[3] - psi_rate_ego_dot = ocp.model.u[0] - v_ego = ocp.model.p[0] - - ocp.parameter_values = np.zeros((P_DIM, )) - - ocp.cost.yref = np.zeros((COST_DIM, )) - ocp.cost.yref_e = np.zeros((COST_E_DIM, )) - # Add offset to smooth out low speed control - # TODO unclear if this right solution long term - v_ego_offset = v_ego + SPEED_OFFSET - # TODO there are two costs on psi_rate_ego_dot, one - # is correlated to jerk the other to steering wheel movement - # the steering wheel movement cost is added to prevent excessive - # wheel movements - ocp.model.cost_y_expr = vertcat(y_ego, - v_ego_offset * psi_ego, - v_ego_offset * psi_rate_ego, - v_ego_offset * psi_rate_ego_dot, - psi_rate_ego_dot / (v_ego + 0.1)) - ocp.model.cost_y_expr_e = vertcat(y_ego, - v_ego_offset * psi_ego, - v_ego_offset * psi_rate_ego) - - # set constraints - ocp.constraints.constr_type = 'BGH' - ocp.constraints.idxbx = np.array([2,3]) - ocp.constraints.ubx = np.array([np.radians(90), np.radians(50)]) - ocp.constraints.lbx = np.array([-np.radians(90), -np.radians(50)]) - x0 = np.zeros((X_DIM,)) - ocp.constraints.x0 = x0 - - ocp.solver_options.qp_solver = 'PARTIAL_CONDENSING_HPIPM' - ocp.solver_options.hessian_approx = 'GAUSS_NEWTON' - ocp.solver_options.integrator_type = 'ERK' - ocp.solver_options.nlp_solver_type = ACADOS_SOLVER_TYPE - ocp.solver_options.qp_solver_iter_max = 1 - ocp.solver_options.qp_solver_cond_N = 1 - - # set prediction horizon - ocp.solver_options.tf = Tf - ocp.solver_options.shooting_nodes = np.array(ModelConstants.T_IDXS)[:N+1] - - ocp.code_export_directory = EXPORT_DIR - return ocp - - -class LateralMpc: - def __init__(self, x0=None): - if x0 is None: - x0 = np.zeros(X_DIM) - self.solver = AcadosOcpSolverCython(MODEL_NAME, ACADOS_SOLVER_TYPE, N) - self.reset(x0) - - def reset(self, x0=None): - if x0 is None: - x0 = np.zeros(X_DIM) - self.x_sol = np.zeros((N+1, X_DIM)) - self.u_sol = np.zeros((N, 1)) - self.yref = np.zeros((N+1, COST_DIM)) - for i in range(N): - self.solver.cost_set(i, "yref", self.yref[i]) - self.solver.cost_set(N, "yref", self.yref[N][:COST_E_DIM]) - - # Somehow needed for stable init - for i in range(N+1): - self.solver.set(i, 'x', np.zeros(X_DIM)) - self.solver.set(i, 'p', np.zeros(P_DIM)) - self.solver.constraints_set(0, "lbx", x0) - self.solver.constraints_set(0, "ubx", x0) - self.solver.solve() - self.solution_status = 0 - self.solve_time = 0.0 - self.cost = 0 - - def set_weights(self, path_weight, heading_weight, - lat_accel_weight, lat_jerk_weight, - steering_rate_weight): - W = np.asfortranarray(np.diag([path_weight, heading_weight, - lat_accel_weight, lat_jerk_weight, - steering_rate_weight])) - for i in range(N): - self.solver.cost_set(i, 'W', W) - self.solver.cost_set(N, 'W', W[:COST_E_DIM,:COST_E_DIM]) - - def run(self, x0, p, y_pts, heading_pts, yaw_rate_pts): - x0_cp = np.copy(x0) - p_cp = np.copy(p) - self.solver.constraints_set(0, "lbx", x0_cp) - self.solver.constraints_set(0, "ubx", x0_cp) - self.yref[:,0] = y_pts - v_ego = p_cp[0, 0] - # rotation_radius = p_cp[1] - self.yref[:,1] = heading_pts * (v_ego + SPEED_OFFSET) - self.yref[:,2] = yaw_rate_pts * (v_ego + SPEED_OFFSET) - for i in range(N): - self.solver.cost_set(i, "yref", self.yref[i]) - self.solver.set(i, "p", p_cp[i]) - self.solver.set(N, "p", p_cp[N]) - self.solver.cost_set(N, "yref", self.yref[N][:COST_E_DIM]) - - t = time.monotonic() - self.solution_status = self.solver.solve() - self.solve_time = time.monotonic() - t - - for i in range(N+1): - self.x_sol[i] = self.solver.get(i, 'x') - for i in range(N): - self.u_sol[i] = self.solver.get(i, 'u') - self.cost = self.solver.get_cost() - - -if __name__ == "__main__": - ocp = gen_lat_ocp() - AcadosOcpSolver.generate(ocp, json_file=JSON_FILE) - # AcadosOcpSolver.build(ocp.code_export_directory, with_cython=True) diff --git a/selfdrive/controls/lib/longcontrol.py b/selfdrive/controls/lib/longcontrol.py deleted file mode 100644 index 6d4f922461..0000000000 --- a/selfdrive/controls/lib/longcontrol.py +++ /dev/null @@ -1,88 +0,0 @@ -import numpy as np -from cereal import car -from openpilot.common.realtime import DT_CTRL -from openpilot.selfdrive.controls.lib.drive_helpers import CONTROL_N -from openpilot.common.pid import PIDController -from openpilot.selfdrive.modeld.constants import ModelConstants - -CONTROL_N_T_IDX = ModelConstants.T_IDXS[:CONTROL_N] - -LongCtrlState = car.CarControl.Actuators.LongControlState - - -def long_control_state_trans(CP, active, long_control_state, v_ego, - should_stop, brake_pressed, cruise_standstill): - stopping_condition = should_stop - starting_condition = (not should_stop and - not cruise_standstill and - not brake_pressed) - started_condition = v_ego > CP.vEgoStarting - - if not active: - long_control_state = LongCtrlState.off - - else: - if long_control_state == LongCtrlState.off: - if not starting_condition: - long_control_state = LongCtrlState.stopping - else: - if starting_condition and CP.startingState: - long_control_state = LongCtrlState.starting - else: - long_control_state = LongCtrlState.pid - - elif long_control_state == LongCtrlState.stopping: - if starting_condition and CP.startingState: - long_control_state = LongCtrlState.starting - elif starting_condition: - long_control_state = LongCtrlState.pid - - elif long_control_state in [LongCtrlState.starting, LongCtrlState.pid]: - if stopping_condition: - long_control_state = LongCtrlState.stopping - elif started_condition: - long_control_state = LongCtrlState.pid - return long_control_state - -class LongControl: - def __init__(self, CP): - self.CP = CP - self.long_control_state = LongCtrlState.off - self.pid = PIDController((CP.longitudinalTuning.kpBP, CP.longitudinalTuning.kpV), - (CP.longitudinalTuning.kiBP, CP.longitudinalTuning.kiV), - k_f=CP.longitudinalTuning.kf, rate=1 / DT_CTRL) - self.last_output_accel = 0.0 - - def reset(self): - self.pid.reset() - - def update(self, active, CS, a_target, should_stop, accel_limits): - """Update longitudinal control. This updates the state machine and runs a PID loop""" - self.pid.neg_limit = accel_limits[0] - self.pid.pos_limit = accel_limits[1] - - self.long_control_state = long_control_state_trans(self.CP, active, self.long_control_state, CS.vEgo, - should_stop, CS.brakePressed, - CS.cruiseState.standstill) - if self.long_control_state == LongCtrlState.off: - self.reset() - output_accel = 0. - - elif self.long_control_state == LongCtrlState.stopping: - output_accel = self.last_output_accel - if output_accel > self.CP.stopAccel: - output_accel = min(output_accel, 0.0) - output_accel -= self.CP.stoppingDecelRate * DT_CTRL - self.reset() - - elif self.long_control_state == LongCtrlState.starting: - output_accel = self.CP.startAccel - self.reset() - - else: # LongCtrlState.pid - error = a_target - CS.aEgo - output_accel = self.pid.update(error, speed=CS.vEgo, - feedforward=a_target) - - self.last_output_accel = np.clip(output_accel, accel_limits[0], accel_limits[1]) - return self.last_output_accel diff --git a/selfdrive/controls/lib/longitudinal_mpc_lib/SConscript b/selfdrive/controls/lib/longitudinal_mpc_lib/SConscript deleted file mode 100644 index 2a155717c0..0000000000 --- a/selfdrive/controls/lib/longitudinal_mpc_lib/SConscript +++ /dev/null @@ -1,99 +0,0 @@ -Import('env', 'envCython', 'arch', 'msgq_python', 'common_python', 'opendbc_python', 'pandad_python', 'np_version') - -gen = "c_generated_code" - -casadi_model = [ - f'{gen}/long_model/long_expl_ode_fun.c', - f'{gen}/long_model/long_expl_vde_forw.c', -] - -casadi_cost_y = [ - f'{gen}/long_cost/long_cost_y_fun.c', - f'{gen}/long_cost/long_cost_y_fun_jac_ut_xt.c', - f'{gen}/long_cost/long_cost_y_hess.c', -] - -casadi_cost_e = [ - f'{gen}/long_cost/long_cost_y_e_fun.c', - f'{gen}/long_cost/long_cost_y_e_fun_jac_ut_xt.c', - f'{gen}/long_cost/long_cost_y_e_hess.c', -] - -casadi_cost_0 = [ - f'{gen}/long_cost/long_cost_y_0_fun.c', - f'{gen}/long_cost/long_cost_y_0_fun_jac_ut_xt.c', - f'{gen}/long_cost/long_cost_y_0_hess.c', -] - -casadi_constraints = [ - f'{gen}/long_constraints/long_constr_h_fun.c', - f'{gen}/long_constraints/long_constr_h_fun_jac_uxt_zt.c', -] - -build_files = [f'{gen}/acados_solver_long.c'] + casadi_model + casadi_cost_y + casadi_cost_e + \ - casadi_cost_0 + casadi_constraints - -# extra generated files used to trigger a rebuild -generated_files = [ - f'{gen}/Makefile', - - f'{gen}/main_long.c', - f'{gen}/main_sim_long.c', - f'{gen}/acados_solver_long.h', - f'{gen}/acados_sim_solver_long.h', - f'{gen}/acados_sim_solver_long.c', - f'{gen}/acados_solver.pxd', - - f'{gen}/long_model/long_expl_vde_adj.c', - - f'{gen}/long_model/long_model.h', - f'{gen}/long_constraints/long_constraints.h', - f'{gen}/long_cost/long_cost.h', -] + build_files - -acados_dir = '#third_party/acados' -acados_templates_dir = '#third_party/acados/acados_template/c_templates_tera' - -source_list = ['long_mpc.py', - '#selfdrive/modeld/constants.py', - f'{acados_dir}/include/acados_c/ocp_nlp_interface.h', - f'{acados_templates_dir}/acados_solver.in.c', -] - -lenv = env.Clone() -lenv.Clean(generated_files, Dir(gen)) - -generated_long = lenv.Command(generated_files, - source_list, - f"cd {Dir('.').abspath} && python3 long_mpc.py") -lenv.Depends(generated_long, [msgq_python, common_python, opendbc_python, pandad_python]) - -lenv["CFLAGS"].append("-DACADOS_WITH_QPOASES") -lenv["CXXFLAGS"].append("-DACADOS_WITH_QPOASES") -lenv["CCFLAGS"].append("-Wno-unused") -if arch != "Darwin": - lenv["LINKFLAGS"].append("-Wl,--disable-new-dtags") -else: - lenv["LINKFLAGS"].append("-Wl,-install_name,@loader_path/libacados_ocp_solver_long.dylib") -lib_solver = lenv.SharedLibrary(f"{gen}/acados_ocp_solver_long", - build_files, - LIBS=['m', 'acados', 'hpipm', 'blasfeo', 'qpOASES_e']) - -# generate cython stuff -acados_ocp_solver_pyx = File("#third_party/acados/acados_template/acados_ocp_solver_pyx.pyx") -acados_ocp_solver_common = File("#third_party/acados/acados_template/acados_solver_common.pxd") -libacados_ocp_solver_pxd = File(f'{gen}/acados_solver.pxd') -libacados_ocp_solver_c = File(f'{gen}/acados_ocp_solver_pyx.c') - -lenv2 = envCython.Clone() -lenv2["LINKFLAGS"] += [lib_solver[0].get_labspath()] -lenv2.Command(libacados_ocp_solver_c, - [acados_ocp_solver_pyx, acados_ocp_solver_common, libacados_ocp_solver_pxd], - f'cython' + \ - f' -o {libacados_ocp_solver_c.get_labspath()}' + \ - f' -I {libacados_ocp_solver_pxd.get_dir().get_labspath()}' + \ - f' -I {acados_ocp_solver_common.get_dir().get_labspath()}' + \ - f' {acados_ocp_solver_pyx.get_labspath()}') -lib_cython = lenv2.Program(f'{gen}/acados_ocp_solver_pyx.so', [libacados_ocp_solver_c]) -lenv2.Depends(lib_cython, lib_solver) -lenv2.Depends(libacados_ocp_solver_c, np_version) diff --git a/selfdrive/controls/lib/longitudinal_mpc_lib/long_mpc.py b/selfdrive/controls/lib/longitudinal_mpc_lib/long_mpc.py deleted file mode 100755 index 3f9d8245bd..0000000000 --- a/selfdrive/controls/lib/longitudinal_mpc_lib/long_mpc.py +++ /dev/null @@ -1,457 +0,0 @@ -#!/usr/bin/env python3 -import os -import time -import numpy as np -from cereal import log -from opendbc.car.interfaces import ACCEL_MIN, ACCEL_MAX -from openpilot.common.realtime import DT_MDL -from openpilot.common.swaglog import cloudlog -# WARNING: imports outside of constants will not trigger a rebuild -from openpilot.selfdrive.modeld.constants import index_function -from openpilot.selfdrive.controls.radard import _LEAD_ACCEL_TAU - -if __name__ == '__main__': # generating code - from openpilot.third_party.acados.acados_template import AcadosModel, AcadosOcp, AcadosOcpSolver -else: - from openpilot.selfdrive.controls.lib.longitudinal_mpc_lib.c_generated_code.acados_ocp_solver_pyx import AcadosOcpSolverCython - -from casadi import SX, vertcat - -MODEL_NAME = 'long' -LONG_MPC_DIR = os.path.dirname(os.path.abspath(__file__)) -EXPORT_DIR = os.path.join(LONG_MPC_DIR, "c_generated_code") -JSON_FILE = os.path.join(LONG_MPC_DIR, "acados_ocp_long.json") - -SOURCES = ['lead0', 'lead1', 'cruise', 'e2e'] - -X_DIM = 3 -U_DIM = 1 -PARAM_DIM = 6 -COST_E_DIM = 5 -COST_DIM = COST_E_DIM + 1 -CONSTR_DIM = 4 - -X_EGO_OBSTACLE_COST = 3. -X_EGO_COST = 0. -V_EGO_COST = 0. -A_EGO_COST = 0. -J_EGO_COST = 5.0 -A_CHANGE_COST = 200. -DANGER_ZONE_COST = 100. -CRASH_DISTANCE = .25 -LEAD_DANGER_FACTOR = 0.75 -LIMIT_COST = 1e6 -ACADOS_SOLVER_TYPE = 'SQP_RTI' - - -# Fewer timestamps don't hurt performance and lead to -# much better convergence of the MPC with low iterations -N = 12 -MAX_T = 10.0 -T_IDXS_LST = [index_function(idx, max_val=MAX_T, max_idx=N) for idx in range(N+1)] - -T_IDXS = np.array(T_IDXS_LST) -FCW_IDXS = T_IDXS < 5.0 -T_DIFFS = np.diff(T_IDXS, prepend=[0.]) -COMFORT_BRAKE = 2.5 -STOP_DISTANCE = 6.0 -CRUISE_MIN_ACCEL = -1.2 -CRUISE_MAX_ACCEL = 1.6 - -def get_jerk_factor(personality=log.LongitudinalPersonality.standard): - if personality==log.LongitudinalPersonality.relaxed: - return 1.0 - elif personality==log.LongitudinalPersonality.standard: - return 1.0 - elif personality==log.LongitudinalPersonality.aggressive: - return 0.5 - else: - raise NotImplementedError("Longitudinal personality not supported") - - -def get_T_FOLLOW(personality=log.LongitudinalPersonality.standard): - if personality==log.LongitudinalPersonality.relaxed: - return 1.75 - elif personality==log.LongitudinalPersonality.standard: - return 1.45 - elif personality==log.LongitudinalPersonality.aggressive: - return 1.25 - else: - raise NotImplementedError("Longitudinal personality not supported") - -def get_stopped_equivalence_factor(v_lead): - return (v_lead**2) / (2 * COMFORT_BRAKE) - -def get_safe_obstacle_distance(v_ego, t_follow): - return (v_ego**2) / (2 * COMFORT_BRAKE) + t_follow * v_ego + STOP_DISTANCE - -def desired_follow_distance(v_ego, v_lead, t_follow=None): - if t_follow is None: - t_follow = get_T_FOLLOW() - return get_safe_obstacle_distance(v_ego, t_follow) - get_stopped_equivalence_factor(v_lead) - - -def gen_long_model(): - model = AcadosModel() - model.name = MODEL_NAME - - # set up states & controls - x_ego = SX.sym('x_ego') - v_ego = SX.sym('v_ego') - a_ego = SX.sym('a_ego') - model.x = vertcat(x_ego, v_ego, a_ego) - - # controls - j_ego = SX.sym('j_ego') - model.u = vertcat(j_ego) - - # xdot - x_ego_dot = SX.sym('x_ego_dot') - v_ego_dot = SX.sym('v_ego_dot') - a_ego_dot = SX.sym('a_ego_dot') - model.xdot = vertcat(x_ego_dot, v_ego_dot, a_ego_dot) - - # live parameters - a_min = SX.sym('a_min') - a_max = SX.sym('a_max') - x_obstacle = SX.sym('x_obstacle') - prev_a = SX.sym('prev_a') - lead_t_follow = SX.sym('lead_t_follow') - lead_danger_factor = SX.sym('lead_danger_factor') - model.p = vertcat(a_min, a_max, x_obstacle, prev_a, lead_t_follow, lead_danger_factor) - - # dynamics model - f_expl = vertcat(v_ego, a_ego, j_ego) - model.f_impl_expr = model.xdot - f_expl - model.f_expl_expr = f_expl - return model - - -def gen_long_ocp(): - ocp = AcadosOcp() - ocp.model = gen_long_model() - - Tf = T_IDXS[-1] - - # set dimensions - ocp.dims.N = N - - # set cost module - ocp.cost.cost_type = 'NONLINEAR_LS' - ocp.cost.cost_type_e = 'NONLINEAR_LS' - - QR = np.zeros((COST_DIM, COST_DIM)) - Q = np.zeros((COST_E_DIM, COST_E_DIM)) - - ocp.cost.W = QR - ocp.cost.W_e = Q - - x_ego, v_ego, a_ego = ocp.model.x[0], ocp.model.x[1], ocp.model.x[2] - j_ego = ocp.model.u[0] - - a_min, a_max = ocp.model.p[0], ocp.model.p[1] - x_obstacle = ocp.model.p[2] - prev_a = ocp.model.p[3] - lead_t_follow = ocp.model.p[4] - lead_danger_factor = ocp.model.p[5] - - ocp.cost.yref = np.zeros((COST_DIM, )) - ocp.cost.yref_e = np.zeros((COST_E_DIM, )) - - desired_dist_comfort = get_safe_obstacle_distance(v_ego, lead_t_follow) - - # The main cost in normal operation is how close you are to the "desired" distance - # from an obstacle at every timestep. This obstacle can be a lead car - # or other object. In e2e mode we can use x_position targets as a cost - # instead. - costs = [((x_obstacle - x_ego) - (desired_dist_comfort)) / (v_ego + 10.), - x_ego, - v_ego, - a_ego, - a_ego - prev_a, - j_ego] - ocp.model.cost_y_expr = vertcat(*costs) - ocp.model.cost_y_expr_e = vertcat(*costs[:-1]) - - # Constraints on speed, acceleration and desired distance to - # the obstacle, which is treated as a slack constraint so it - # behaves like an asymmetrical cost. - constraints = vertcat(v_ego, - (a_ego - a_min), - (a_max - a_ego), - ((x_obstacle - x_ego) - lead_danger_factor * (desired_dist_comfort)) / (v_ego + 10.)) - ocp.model.con_h_expr = constraints - - x0 = np.zeros(X_DIM) - ocp.constraints.x0 = x0 - ocp.parameter_values = np.array([-1.2, 1.2, 0.0, 0.0, get_T_FOLLOW(), LEAD_DANGER_FACTOR]) - - - # We put all constraint cost weights to 0 and only set them at runtime - cost_weights = np.zeros(CONSTR_DIM) - ocp.cost.zl = cost_weights - ocp.cost.Zl = cost_weights - ocp.cost.Zu = cost_weights - ocp.cost.zu = cost_weights - - ocp.constraints.lh = np.zeros(CONSTR_DIM) - ocp.constraints.uh = 1e4*np.ones(CONSTR_DIM) - ocp.constraints.idxsh = np.arange(CONSTR_DIM) - - # The HPIPM solver can give decent solutions even when it is stopped early - # Which is critical for our purpose where compute time is strictly bounded - # We use HPIPM in the SPEED_ABS mode, which ensures fastest runtime. This - # does not cause issues since the problem is well bounded. - ocp.solver_options.qp_solver = 'PARTIAL_CONDENSING_HPIPM' - ocp.solver_options.hessian_approx = 'GAUSS_NEWTON' - ocp.solver_options.integrator_type = 'ERK' - ocp.solver_options.nlp_solver_type = ACADOS_SOLVER_TYPE - ocp.solver_options.qp_solver_cond_N = 1 - - # More iterations take too much time and less lead to inaccurate convergence in - # some situations. Ideally we would run just 1 iteration to ensure fixed runtime. - ocp.solver_options.qp_solver_iter_max = 10 - ocp.solver_options.qp_tol = 1e-3 - - # set prediction horizon - ocp.solver_options.tf = Tf - ocp.solver_options.shooting_nodes = T_IDXS - - ocp.code_export_directory = EXPORT_DIR - return ocp - - -class LongitudinalMpc: - def __init__(self, mode='acc', dt=DT_MDL): - self.mode = mode - self.dt = dt - self.solver = AcadosOcpSolverCython(MODEL_NAME, ACADOS_SOLVER_TYPE, N) - self.reset() - self.source = SOURCES[2] - - def reset(self): - # self.solver = AcadosOcpSolverCython(MODEL_NAME, ACADOS_SOLVER_TYPE, N) - self.solver.reset() - # self.solver.options_set('print_level', 2) - self.v_solution = np.zeros(N+1) - self.a_solution = np.zeros(N+1) - self.prev_a = np.array(self.a_solution) - self.j_solution = np.zeros(N) - self.yref = np.zeros((N+1, COST_DIM)) - for i in range(N): - self.solver.cost_set(i, "yref", self.yref[i]) - self.solver.cost_set(N, "yref", self.yref[N][:COST_E_DIM]) - self.x_sol = np.zeros((N+1, X_DIM)) - self.u_sol = np.zeros((N,1)) - self.params = np.zeros((N+1, PARAM_DIM)) - for i in range(N+1): - self.solver.set(i, 'x', np.zeros(X_DIM)) - self.last_cloudlog_t = 0 - self.status = False - self.crash_cnt = 0.0 - self.solution_status = 0 - # timers - self.solve_time = 0.0 - self.time_qp_solution = 0.0 - self.time_linearization = 0.0 - self.time_integrator = 0.0 - self.x0 = np.zeros(X_DIM) - self.set_weights() - - def set_cost_weights(self, cost_weights, constraint_cost_weights): - W = np.asfortranarray(np.diag(cost_weights)) - for i in range(N): - # TODO don't hardcode A_CHANGE_COST idx - # reduce the cost on (a-a_prev) later in the horizon. - W[4,4] = cost_weights[4] * np.interp(T_IDXS[i], [0.0, 1.0, 2.0], [1.0, 1.0, 0.0]) - self.solver.cost_set(i, 'W', W) - # Setting the slice without the copy make the array not contiguous, - # causing issues with the C interface. - self.solver.cost_set(N, 'W', np.copy(W[:COST_E_DIM, :COST_E_DIM])) - - # Set L2 slack cost on lower bound constraints - Zl = np.array(constraint_cost_weights) - for i in range(N): - self.solver.cost_set(i, 'Zl', Zl) - - def set_weights(self, prev_accel_constraint=True, personality=log.LongitudinalPersonality.standard): - jerk_factor = get_jerk_factor(personality) - if self.mode == 'acc': - a_change_cost = A_CHANGE_COST if prev_accel_constraint else 0 - cost_weights = [X_EGO_OBSTACLE_COST, X_EGO_COST, V_EGO_COST, A_EGO_COST, jerk_factor * a_change_cost, jerk_factor * J_EGO_COST] - constraint_cost_weights = [LIMIT_COST, LIMIT_COST, LIMIT_COST, DANGER_ZONE_COST] - elif self.mode == 'blended': - a_change_cost = 40.0 if prev_accel_constraint else 0 - cost_weights = [0., 0.1, 0.2, 5.0, a_change_cost, 1.0] - constraint_cost_weights = [LIMIT_COST, LIMIT_COST, LIMIT_COST, DANGER_ZONE_COST] - else: - raise NotImplementedError(f'Planner mode {self.mode} not recognized in planner cost set') - self.set_cost_weights(cost_weights, constraint_cost_weights) - - def set_cur_state(self, v, a): - v_prev = self.x0[1] - self.x0[1] = v - self.x0[2] = a - if abs(v_prev - v) > 2.: # probably only helps if v < v_prev - for i in range(N+1): - self.solver.set(i, 'x', self.x0) - - @staticmethod - def extrapolate_lead(x_lead, v_lead, a_lead, a_lead_tau): - a_lead_traj = a_lead * np.exp(-a_lead_tau * (T_IDXS**2)/2.) - v_lead_traj = np.clip(v_lead + np.cumsum(T_DIFFS * a_lead_traj), 0.0, 1e8) - x_lead_traj = x_lead + np.cumsum(T_DIFFS * v_lead_traj) - lead_xv = np.column_stack((x_lead_traj, v_lead_traj)) - return lead_xv - - def process_lead(self, lead): - v_ego = self.x0[1] - if lead is not None and lead.status: - x_lead = lead.dRel - v_lead = lead.vLead - a_lead = lead.aLeadK - a_lead_tau = lead.aLeadTau - else: - # Fake a fast lead car, so mpc can keep running in the same mode - x_lead = 50.0 - v_lead = v_ego + 10.0 - a_lead = 0.0 - a_lead_tau = _LEAD_ACCEL_TAU - - # MPC will not converge if immediate crash is expected - # Clip lead distance to what is still possible to brake for - min_x_lead = ((v_ego + v_lead)/2) * (v_ego - v_lead) / (-ACCEL_MIN * 2) - x_lead = np.clip(x_lead, min_x_lead, 1e8) - v_lead = np.clip(v_lead, 0.0, 1e8) - a_lead = np.clip(a_lead, -10., 5.) - lead_xv = self.extrapolate_lead(x_lead, v_lead, a_lead, a_lead_tau) - return lead_xv - - def update(self, radarstate, v_cruise, x, v, a, j, personality=log.LongitudinalPersonality.standard): - t_follow = get_T_FOLLOW(personality) - v_ego = self.x0[1] - self.status = radarstate.leadOne.status or radarstate.leadTwo.status - - lead_xv_0 = self.process_lead(radarstate.leadOne) - lead_xv_1 = self.process_lead(radarstate.leadTwo) - - # To estimate a safe distance from a moving lead, we calculate how much stopping - # distance that lead needs as a minimum. We can add that to the current distance - # and then treat that as a stopped car/obstacle at this new distance. - lead_0_obstacle = lead_xv_0[:,0] + get_stopped_equivalence_factor(lead_xv_0[:,1]) - lead_1_obstacle = lead_xv_1[:,0] + get_stopped_equivalence_factor(lead_xv_1[:,1]) - - self.params[:,0] = ACCEL_MIN - self.params[:,1] = ACCEL_MAX - - # Update in ACC mode or ACC/e2e blend - if self.mode == 'acc': - self.params[:,5] = LEAD_DANGER_FACTOR - - # Fake an obstacle for cruise, this ensures smooth acceleration to set speed - # when the leads are no factor. - v_lower = v_ego + (T_IDXS * CRUISE_MIN_ACCEL * 1.05) - # TODO does this make sense when max_a is negative? - v_upper = v_ego + (T_IDXS * CRUISE_MAX_ACCEL * 1.05) - v_cruise_clipped = np.clip(v_cruise * np.ones(N+1), - v_lower, - v_upper) - cruise_obstacle = np.cumsum(T_DIFFS * v_cruise_clipped) + get_safe_obstacle_distance(v_cruise_clipped, t_follow) - x_obstacles = np.column_stack([lead_0_obstacle, lead_1_obstacle, cruise_obstacle]) - self.source = SOURCES[np.argmin(x_obstacles[0])] - - # These are not used in ACC mode - x[:], v[:], a[:], j[:] = 0.0, 0.0, 0.0, 0.0 - - elif self.mode == 'blended': - self.params[:,5] = 1.0 - - x_obstacles = np.column_stack([lead_0_obstacle, - lead_1_obstacle]) - cruise_target = T_IDXS * np.clip(v_cruise, v_ego - 2.0, 1e3) + x[0] - xforward = ((v[1:] + v[:-1]) / 2) * (T_IDXS[1:] - T_IDXS[:-1]) - x = np.cumsum(np.insert(xforward, 0, x[0])) - - x_and_cruise = np.column_stack([x, cruise_target]) - x = np.min(x_and_cruise, axis=1) - - self.source = 'e2e' if x_and_cruise[1,0] < x_and_cruise[1,1] else 'cruise' - - else: - raise NotImplementedError(f'Planner mode {self.mode} not recognized in planner update') - - self.yref[:,1] = x - self.yref[:,2] = v - self.yref[:,3] = a - self.yref[:,5] = j - for i in range(N): - self.solver.set(i, "yref", self.yref[i]) - self.solver.set(N, "yref", self.yref[N][:COST_E_DIM]) - - self.params[:,2] = np.min(x_obstacles, axis=1) - self.params[:,3] = np.copy(self.prev_a) - self.params[:,4] = t_follow - - self.run() - if (np.any(lead_xv_0[FCW_IDXS,0] - self.x_sol[FCW_IDXS,0] < CRASH_DISTANCE) and - radarstate.leadOne.modelProb > 0.9): - self.crash_cnt += 1 - else: - self.crash_cnt = 0 - - # Check if it got within lead comfort range - # TODO This should be done cleaner - if self.mode == 'blended': - if any((lead_0_obstacle - get_safe_obstacle_distance(self.x_sol[:,1], t_follow))- self.x_sol[:,0] < 0.0): - self.source = 'lead0' - if any((lead_1_obstacle - get_safe_obstacle_distance(self.x_sol[:,1], t_follow))- self.x_sol[:,0] < 0.0) and \ - (lead_1_obstacle[0] - lead_0_obstacle[0]): - self.source = 'lead1' - - def run(self): - # t0 = time.monotonic() - # reset = 0 - for i in range(N+1): - self.solver.set(i, 'p', self.params[i]) - self.solver.constraints_set(0, "lbx", self.x0) - self.solver.constraints_set(0, "ubx", self.x0) - - self.solution_status = self.solver.solve() - self.solve_time = float(self.solver.get_stats('time_tot')[0]) - self.time_qp_solution = float(self.solver.get_stats('time_qp')[0]) - self.time_linearization = float(self.solver.get_stats('time_lin')[0]) - self.time_integrator = float(self.solver.get_stats('time_sim')[0]) - - # qp_iter = self.solver.get_stats('statistics')[-1][-1] # SQP_RTI specific - # print(f"long_mpc timings: tot {self.solve_time:.2e}, qp {self.time_qp_solution:.2e}, lin {self.time_linearization:.2e}, \ - # integrator {self.time_integrator:.2e}, qp_iter {qp_iter}") - # res = self.solver.get_residuals() - # print(f"long_mpc residuals: {res[0]:.2e}, {res[1]:.2e}, {res[2]:.2e}, {res[3]:.2e}") - # self.solver.print_statistics() - - for i in range(N+1): - self.x_sol[i] = self.solver.get(i, 'x') - for i in range(N): - self.u_sol[i] = self.solver.get(i, 'u') - - self.v_solution = self.x_sol[:,1] - self.a_solution = self.x_sol[:,2] - self.j_solution = self.u_sol[:,0] - - self.prev_a = np.interp(T_IDXS + self.dt, T_IDXS, self.a_solution) - - t = time.monotonic() - if self.solution_status != 0: - if t > self.last_cloudlog_t + 5.0: - self.last_cloudlog_t = t - cloudlog.warning(f"Long mpc reset, solution_status: {self.solution_status}") - self.reset() - # reset = 1 - # print(f"long_mpc timings: total internal {self.solve_time:.2e}, external: {(time.monotonic() - t0):.2e} qp {self.time_qp_solution:.2e}, \ - # lin {self.time_linearization:.2e} qp_iter {qp_iter}, reset {reset}") - - -if __name__ == "__main__": - ocp = gen_long_ocp() - AcadosOcpSolver.generate(ocp, json_file=JSON_FILE) - # AcadosOcpSolver.build(ocp.code_export_directory, with_cython=True) diff --git a/selfdrive/controls/lib/longitudinal_planner.py b/selfdrive/controls/lib/longitudinal_planner.py deleted file mode 100755 index 4e842f8d1b..0000000000 --- a/selfdrive/controls/lib/longitudinal_planner.py +++ /dev/null @@ -1,211 +0,0 @@ -#!/usr/bin/env python3 -import math -import numpy as np - -import cereal.messaging as messaging -from opendbc.car.interfaces import ACCEL_MIN, ACCEL_MAX -from openpilot.common.conversions import Conversions as CV -from openpilot.common.filter_simple import FirstOrderFilter -from openpilot.common.realtime import DT_MDL -from openpilot.selfdrive.modeld.constants import ModelConstants -from openpilot.selfdrive.controls.lib.longcontrol import LongCtrlState -from openpilot.selfdrive.controls.lib.longitudinal_mpc_lib.long_mpc import LongitudinalMpc -from openpilot.selfdrive.controls.lib.longitudinal_mpc_lib.long_mpc import T_IDXS as T_IDXS_MPC -from openpilot.selfdrive.controls.lib.drive_helpers import CONTROL_N, get_speed_error, get_accel_from_plan -from openpilot.selfdrive.car.cruise import V_CRUISE_MAX, V_CRUISE_UNSET -from openpilot.common.swaglog import cloudlog - -from openpilot.sunnypilot.selfdrive.controls.lib.longitudinal_planner import LongitudinalPlannerSP - -LON_MPC_STEP = 0.2 # first step is 0.2s -A_CRUISE_MAX_VALS = [1.6, 1.2, 0.8, 0.6] -A_CRUISE_MAX_BP = [0., 10.0, 25., 40.] -CONTROL_N_T_IDX = ModelConstants.T_IDXS[:CONTROL_N] -ALLOW_THROTTLE_THRESHOLD = 0.5 -MIN_ALLOW_THROTTLE_SPEED = 2.5 - -# Lookup table for turns -_A_TOTAL_MAX_V = [1.7, 3.2] -_A_TOTAL_MAX_BP = [20., 40.] - - -def get_max_accel(v_ego): - return np.interp(v_ego, A_CRUISE_MAX_BP, A_CRUISE_MAX_VALS) - -def get_coast_accel(pitch): - return np.sin(pitch) * -5.65 - 0.3 # fitted from data using xx/projects/allow_throttle/compute_coast_accel.py - - -def limit_accel_in_turns(v_ego, angle_steers, a_target, CP): - """ - This function returns a limited long acceleration allowed, depending on the existing lateral acceleration - this should avoid accelerating when losing the target in turns - """ - # FIXME: This function to calculate lateral accel is incorrect and should use the VehicleModel - # The lookup table for turns should also be updated if we do this - a_total_max = np.interp(v_ego, _A_TOTAL_MAX_BP, _A_TOTAL_MAX_V) - a_y = v_ego ** 2 * angle_steers * CV.DEG_TO_RAD / (CP.steerRatio * CP.wheelbase) - a_x_allowed = math.sqrt(max(a_total_max ** 2 - a_y ** 2, 0.)) - - return [a_target[0], min(a_target[1], a_x_allowed)] - - -class LongitudinalPlanner(LongitudinalPlannerSP): - def __init__(self, CP, init_v=0.0, init_a=0.0, dt=DT_MDL): - self.CP = CP - self.mpc = LongitudinalMpc(dt=dt) - self.mpc.mode = 'acc' - LongitudinalPlannerSP.__init__(self, self.CP, self.mpc) - self.fcw = False - self.dt = dt - self.allow_throttle = True - - self.a_desired = init_a - self.v_desired_filter = FirstOrderFilter(init_v, 2.0, self.dt) - self.prev_accel_clip = [ACCEL_MIN, ACCEL_MAX] - self.v_model_error = 0.0 - self.output_a_target = 0.0 - self.output_should_stop = False - - self.v_desired_trajectory = np.zeros(CONTROL_N) - self.a_desired_trajectory = np.zeros(CONTROL_N) - self.j_desired_trajectory = np.zeros(CONTROL_N) - self.solverExecutionTime = 0.0 - - @staticmethod - def parse_model(model_msg, model_error): - if (len(model_msg.position.x) == ModelConstants.IDX_N and - len(model_msg.velocity.x) == ModelConstants.IDX_N and - len(model_msg.acceleration.x) == ModelConstants.IDX_N): - x = np.interp(T_IDXS_MPC, ModelConstants.T_IDXS, model_msg.position.x) - model_error * T_IDXS_MPC - v = np.interp(T_IDXS_MPC, ModelConstants.T_IDXS, model_msg.velocity.x) - model_error - a = np.interp(T_IDXS_MPC, ModelConstants.T_IDXS, model_msg.acceleration.x) - j = np.zeros(len(T_IDXS_MPC)) - else: - x = np.zeros(len(T_IDXS_MPC)) - v = np.zeros(len(T_IDXS_MPC)) - a = np.zeros(len(T_IDXS_MPC)) - j = np.zeros(len(T_IDXS_MPC)) - if len(model_msg.meta.disengagePredictions.gasPressProbs) > 1: - throttle_prob = model_msg.meta.disengagePredictions.gasPressProbs[1] - else: - throttle_prob = 1.0 - return x, v, a, j, throttle_prob - - def update(self, sm): - self.mode = 'blended' if sm['selfdriveState'].experimentalMode else 'acc' - LongitudinalPlannerSP.update(self, sm) - if dec_mpc_mode := self.get_mpc_mode(): - self.mode = dec_mpc_mode - - if len(sm['carControl'].orientationNED) == 3: - accel_coast = get_coast_accel(sm['carControl'].orientationNED[1]) - else: - accel_coast = ACCEL_MAX - - v_ego = sm['carState'].vEgo - v_cruise_kph = min(sm['carState'].vCruise, V_CRUISE_MAX) - v_cruise = v_cruise_kph * CV.KPH_TO_MS - v_cruise_initialized = sm['carState'].vCruise != V_CRUISE_UNSET - - long_control_off = sm['controlsState'].longControlState == LongCtrlState.off - force_slow_decel = sm['controlsState'].forceDecel - - # Reset current state when not engaged, or user is controlling the speed - reset_state = long_control_off if self.CP.openpilotLongitudinalControl else not sm['selfdriveState'].enabled - # PCM cruise speed may be updated a few cycles later, check if initialized - reset_state = reset_state or not v_cruise_initialized - - # No change cost when user is controlling the speed, or when standstill - prev_accel_constraint = not (reset_state or sm['carState'].standstill) - - if self.mode == 'acc': - accel_clip = [ACCEL_MIN, get_max_accel(v_ego)] - steer_angle_without_offset = sm['carState'].steeringAngleDeg - sm['liveParameters'].angleOffsetDeg - accel_clip = limit_accel_in_turns(v_ego, steer_angle_without_offset, accel_clip, self.CP) - else: - accel_clip = [ACCEL_MIN, ACCEL_MAX] - - if reset_state: - self.v_desired_filter.x = v_ego - # Clip aEgo to cruise limits to prevent large accelerations when becoming active - self.a_desired = np.clip(sm['carState'].aEgo, accel_clip[0], accel_clip[1]) - - # Prevent divergence, smooth in current v_ego - self.v_desired_filter.x = max(0.0, self.v_desired_filter.update(v_ego)) - # Compute model v_ego error - self.v_model_error = get_speed_error(sm['modelV2'], v_ego) - x, v, a, j, throttle_prob = self.parse_model(sm['modelV2'], self.v_model_error) - # Don't clip at low speeds since throttle_prob doesn't account for creep - self.allow_throttle = throttle_prob > ALLOW_THROTTLE_THRESHOLD or v_ego <= MIN_ALLOW_THROTTLE_SPEED - - if not self.allow_throttle: - clipped_accel_coast = max(accel_coast, accel_clip[0]) - clipped_accel_coast_interp = np.interp(v_ego, [MIN_ALLOW_THROTTLE_SPEED, MIN_ALLOW_THROTTLE_SPEED*2], [accel_clip[1], clipped_accel_coast]) - accel_clip[1] = min(accel_clip[1], clipped_accel_coast_interp) - - if force_slow_decel: - v_cruise = 0.0 - - self.mpc.set_weights(prev_accel_constraint, personality=sm['selfdriveState'].personality) - self.mpc.set_cur_state(self.v_desired_filter.x, self.a_desired) - self.mpc.update(sm['radarState'], v_cruise, x, v, a, j, personality=sm['selfdriveState'].personality) - - self.v_desired_trajectory = np.interp(CONTROL_N_T_IDX, T_IDXS_MPC, self.mpc.v_solution) - self.a_desired_trajectory = np.interp(CONTROL_N_T_IDX, T_IDXS_MPC, self.mpc.a_solution) - self.j_desired_trajectory = np.interp(CONTROL_N_T_IDX, T_IDXS_MPC[:-1], self.mpc.j_solution) - - # TODO counter is only needed because radar is glitchy, remove once radar is gone - self.fcw = self.mpc.crash_cnt > 2 and not sm['carState'].standstill - if self.fcw: - cloudlog.info("FCW triggered") - - # Interpolate 0.05 seconds and save as starting point for next iteration - a_prev = self.a_desired - self.a_desired = float(np.interp(self.dt, CONTROL_N_T_IDX, self.a_desired_trajectory)) - self.v_desired_filter.x = self.v_desired_filter.x + self.dt * (self.a_desired + a_prev) / 2.0 - - action_t = self.CP.longitudinalActuatorDelay + DT_MDL - output_a_target_mpc, output_should_stop_mpc = get_accel_from_plan(self.v_desired_trajectory, self.a_desired_trajectory, CONTROL_N_T_IDX, - action_t=action_t, vEgoStopping=self.CP.vEgoStopping) - output_a_target_e2e = sm['modelV2'].action.desiredAcceleration - output_should_stop_e2e = sm['modelV2'].action.shouldStop - - if self.mode == 'acc': - output_a_target = output_a_target_mpc - self.output_should_stop = output_should_stop_mpc - else: - output_a_target = min(output_a_target_mpc, output_a_target_e2e) - self.output_should_stop = output_should_stop_e2e or output_should_stop_mpc - - for idx in range(2): - accel_clip[idx] = np.clip(accel_clip[idx], self.prev_accel_clip[idx] - 0.05, self.prev_accel_clip[idx] + 0.05) - self.output_a_target = np.clip(output_a_target, accel_clip[0], accel_clip[1]) - self.prev_accel_clip = accel_clip - - def publish(self, sm, pm): - plan_send = messaging.new_message('longitudinalPlan') - - plan_send.valid = sm.all_checks(service_list=['carState', 'controlsState', 'selfdriveState']) - - longitudinalPlan = plan_send.longitudinalPlan - longitudinalPlan.modelMonoTime = sm.logMonoTime['modelV2'] - longitudinalPlan.processingDelay = (plan_send.logMonoTime / 1e9) - sm.logMonoTime['modelV2'] - longitudinalPlan.solverExecutionTime = self.mpc.solve_time - - longitudinalPlan.speeds = self.v_desired_trajectory.tolist() - longitudinalPlan.accels = self.a_desired_trajectory.tolist() - longitudinalPlan.jerks = self.j_desired_trajectory.tolist() - - longitudinalPlan.hasLead = sm['radarState'].leadOne.status - longitudinalPlan.longitudinalPlanSource = self.mpc.source - longitudinalPlan.fcw = self.fcw - - longitudinalPlan.aTarget = float(self.output_a_target) - longitudinalPlan.shouldStop = bool(self.output_should_stop) - longitudinalPlan.allowBrake = True - longitudinalPlan.allowThrottle = bool(self.allow_throttle) - - pm.send('longitudinalPlan', plan_send) - - self.publish_longitudinal_plan_sp(sm, pm) diff --git a/selfdrive/controls/plannerd.py b/selfdrive/controls/plannerd.py deleted file mode 100755 index 60036c3082..0000000000 --- a/selfdrive/controls/plannerd.py +++ /dev/null @@ -1,40 +0,0 @@ -#!/usr/bin/env python3 -from cereal import car -from openpilot.common.params import Params -from openpilot.common.realtime import Priority, config_realtime_process -from openpilot.common.swaglog import cloudlog -from openpilot.selfdrive.controls.lib.ldw import LaneDepartureWarning -from openpilot.selfdrive.controls.lib.longitudinal_planner import LongitudinalPlanner -import cereal.messaging as messaging - - -def main(): - config_realtime_process(5, Priority.CTRL_LOW) - - cloudlog.info("plannerd is waiting for CarParams") - params = Params() - CP = messaging.log_from_bytes(params.get("CarParams", block=True), car.CarParams) - cloudlog.info("plannerd got CarParams: %s", CP.brand) - - ldw = LaneDepartureWarning() - longitudinal_planner = LongitudinalPlanner(CP) - pm = messaging.PubMaster(['longitudinalPlan', 'driverAssistance', 'longitudinalPlanSP']) - sm = messaging.SubMaster(['carControl', 'carState', 'controlsState', 'liveParameters', 'radarState', 'modelV2', 'selfdriveState'], - poll='modelV2') - - while True: - sm.update() - if sm.updated['modelV2']: - longitudinal_planner.update(sm) - longitudinal_planner.publish(sm, pm) - - ldw.update(sm.frame, sm['modelV2'], sm['carState'], sm['carControl']) - msg = messaging.new_message('driverAssistance') - msg.valid = sm.all_checks(['carState', 'carControl', 'modelV2', 'liveParameters']) - msg.driverAssistance.leftLaneDeparture = ldw.left - msg.driverAssistance.rightLaneDeparture = ldw.right - pm.send('driverAssistance', msg) - - -if __name__ == "__main__": - main() diff --git a/selfdrive/controls/tests/test_following_distance.py b/selfdrive/controls/tests/test_following_distance.py deleted file mode 100644 index 0fd543dd60..0000000000 --- a/selfdrive/controls/tests/test_following_distance.py +++ /dev/null @@ -1,40 +0,0 @@ -import pytest -import itertools -from parameterized import parameterized_class - -from cereal import log - -from openpilot.selfdrive.controls.lib.longitudinal_mpc_lib.long_mpc import desired_follow_distance, get_T_FOLLOW -from openpilot.selfdrive.test.longitudinal_maneuvers.maneuver import Maneuver - - -def run_following_distance_simulation(v_lead, t_end=100.0, e2e=False, personality=0): - man = Maneuver( - '', - duration=t_end, - initial_speed=float(v_lead), - lead_relevancy=True, - initial_distance_lead=100, - speed_lead_values=[v_lead], - breakpoints=[0.], - e2e=e2e, - personality=personality, - ) - valid, output = man.evaluate() - assert valid - return output[-1,2] - output[-1,1] - - -@parameterized_class(("e2e", "personality", "speed"), itertools.product( - [True, False], # e2e - [log.LongitudinalPersonality.relaxed, # personality - log.LongitudinalPersonality.standard, - log.LongitudinalPersonality.aggressive], - [0,10,35])) # speed -class TestFollowingDistance: - def test_following_distance(self): - v_lead = float(self.speed) - simulation_steady_state = run_following_distance_simulation(v_lead, e2e=self.e2e, personality=self.personality) - correct_steady_state = desired_follow_distance(v_lead, v_lead, get_T_FOLLOW(self.personality)) - err_ratio = 0.2 if self.e2e else 0.1 - assert simulation_steady_state == pytest.approx(correct_steady_state, abs=err_ratio * correct_steady_state + .5) diff --git a/selfdrive/controls/tests/test_lateral_mpc.py b/selfdrive/controls/tests/test_lateral_mpc.py deleted file mode 100644 index 3aa0fd1bce..0000000000 --- a/selfdrive/controls/tests/test_lateral_mpc.py +++ /dev/null @@ -1,85 +0,0 @@ -import pytest -import numpy as np -from openpilot.selfdrive.controls.lib.lateral_mpc_lib.lat_mpc import LateralMpc -from openpilot.selfdrive.controls.lib.drive_helpers import CAR_ROTATION_RADIUS -from openpilot.selfdrive.controls.lib.lateral_mpc_lib.lat_mpc import N as LAT_MPC_N - - -def run_mpc(lat_mpc=None, v_ref=30., x_init=0., y_init=0., psi_init=0., curvature_init=0., - lane_width=3.6, poly_shift=0.): - - if lat_mpc is None: - lat_mpc = LateralMpc() - lat_mpc.set_weights(1., .1, 0.0, .05, 800) - - y_pts = poly_shift * np.ones(LAT_MPC_N + 1) - heading_pts = np.zeros(LAT_MPC_N + 1) - curv_rate_pts = np.zeros(LAT_MPC_N + 1) - - x0 = np.array([x_init, y_init, psi_init, curvature_init]) - p = np.column_stack([v_ref * np.ones(LAT_MPC_N + 1), - CAR_ROTATION_RADIUS * np.ones(LAT_MPC_N + 1)]) - - # converge in no more than 10 iterations - for _ in range(10): - lat_mpc.run(x0, p, - y_pts, heading_pts, curv_rate_pts) - return lat_mpc.x_sol - - -class TestLateralMpc: - - def _assert_null(self, sol, curvature=1e-6): - for i in range(len(sol)): - assert sol[0,i,1] == pytest.approx(0, abs=curvature) - assert sol[0,i,2] == pytest.approx(0, abs=curvature) - assert sol[0,i,3] == pytest.approx(0, abs=curvature) - - def _assert_simmetry(self, sol, curvature=1e-6): - for i in range(len(sol)): - assert sol[0,i,1] == pytest.approx(-sol[1,i,1], abs=curvature) - assert sol[0,i,2] == pytest.approx(-sol[1,i,2], abs=curvature) - assert sol[0,i,3] == pytest.approx(-sol[1,i,3], abs=curvature) - assert sol[0,i,0] == pytest.approx(sol[1,i,0], abs=curvature) - - def test_straight(self): - sol = run_mpc() - self._assert_null(np.array([sol])) - - def test_y_symmetry(self): - sol = [] - for y_init in [-0.5, 0.5]: - sol.append(run_mpc(y_init=y_init)) - self._assert_simmetry(np.array(sol)) - - def test_poly_symmetry(self): - sol = [] - for poly_shift in [-1., 1.]: - sol.append(run_mpc(poly_shift=poly_shift)) - self._assert_simmetry(np.array(sol)) - - def test_curvature_symmetry(self): - sol = [] - for curvature_init in [-0.1, 0.1]: - sol.append(run_mpc(curvature_init=curvature_init)) - self._assert_simmetry(np.array(sol)) - - def test_psi_symmetry(self): - sol = [] - for psi_init in [-0.1, 0.1]: - sol.append(run_mpc(psi_init=psi_init)) - self._assert_simmetry(np.array(sol)) - - def test_no_overshoot(self): - y_init = 1. - sol = run_mpc(y_init=y_init) - for y in list(sol[:,1]): - assert y_init >= abs(y) - - def test_switch_convergence(self): - lat_mpc = LateralMpc() - sol = run_mpc(lat_mpc=lat_mpc, poly_shift=3.0, v_ref=7.0) - right_psi_deg = np.degrees(sol[:,2]) - sol = run_mpc(lat_mpc=lat_mpc, poly_shift=-3.0, v_ref=7.0) - left_psi_deg = np.degrees(sol[:,2]) - np.testing.assert_almost_equal(right_psi_deg, -left_psi_deg, decimal=3) diff --git a/selfdrive/controls/tests/test_longcontrol.py b/selfdrive/controls/tests/test_longcontrol.py deleted file mode 100644 index ab50810d89..0000000000 --- a/selfdrive/controls/tests/test_longcontrol.py +++ /dev/null @@ -1,56 +0,0 @@ -from cereal import car -from openpilot.selfdrive.controls.lib.longcontrol import LongCtrlState, long_control_state_trans - - - - -class TestLongControlStateTransition: - - def test_stay_stopped(self): - CP = car.CarParams.new_message() - active = True - current_state = LongCtrlState.stopping - next_state = long_control_state_trans(CP, active, current_state, v_ego=0.1, - should_stop=True, brake_pressed=False, cruise_standstill=False) - assert next_state == LongCtrlState.stopping - next_state = long_control_state_trans(CP, active, current_state, v_ego=0.1, - should_stop=False, brake_pressed=True, cruise_standstill=False) - assert next_state == LongCtrlState.stopping - next_state = long_control_state_trans(CP, active, current_state, v_ego=0.1, - should_stop=False, brake_pressed=False, cruise_standstill=True) - assert next_state == LongCtrlState.stopping - next_state = long_control_state_trans(CP, active, current_state, v_ego=1.0, - should_stop=False, brake_pressed=False, cruise_standstill=False) - assert next_state == LongCtrlState.pid - active = False - next_state = long_control_state_trans(CP, active, current_state, v_ego=1.0, - should_stop=False, brake_pressed=False, cruise_standstill=False) - assert next_state == LongCtrlState.off - -def test_engage(): - CP = car.CarParams.new_message() - active = True - current_state = LongCtrlState.off - next_state = long_control_state_trans(CP, active, current_state, v_ego=0.1, - should_stop=True, brake_pressed=False, cruise_standstill=False) - assert next_state == LongCtrlState.stopping - next_state = long_control_state_trans(CP, active, current_state, v_ego=0.1, - should_stop=False, brake_pressed=True, cruise_standstill=False) - assert next_state == LongCtrlState.stopping - next_state = long_control_state_trans(CP, active, current_state, v_ego=0.1, - should_stop=False, brake_pressed=False, cruise_standstill=True) - assert next_state == LongCtrlState.stopping - next_state = long_control_state_trans(CP, active, current_state, v_ego=0.1, - should_stop=False, brake_pressed=False, cruise_standstill=False) - assert next_state == LongCtrlState.pid - -def test_starting(): - CP = car.CarParams.new_message(startingState=True, vEgoStarting=0.5) - active = True - current_state = LongCtrlState.starting - next_state = long_control_state_trans(CP, active, current_state, v_ego=0.1, - should_stop=False, brake_pressed=False, cruise_standstill=False) - assert next_state == LongCtrlState.starting - next_state = long_control_state_trans(CP, active, current_state, v_ego=1.0, - should_stop=False, brake_pressed=False, cruise_standstill=False) - assert next_state == LongCtrlState.pid diff --git a/selfdrive/debug/README.md b/selfdrive/debug/README.md deleted file mode 100644 index 83b8a994db..0000000000 --- a/selfdrive/debug/README.md +++ /dev/null @@ -1,59 +0,0 @@ -# debug scripts - -## [can_printer.py](can_printer.py) - -``` -usage: can_printer.py [-h] [--bus BUS] [--max_msg MAX_MSG] [--addr ADDR] - -simple CAN data viewer - -optional arguments: - -h, --help show this help message and exit - --bus BUS CAN bus to print out (default: 0) - --max_msg MAX_MSG max addr (default: None) - --addr ADDR -``` - -## [dump.py](dump.py) - -``` -usage: dump.py [-h] [--pipe] [--raw] [--json] [--dump-json] [--no-print] [--addr ADDR] [--values VALUES] [socket [socket ...]] - -Dump communication sockets. See cereal/services.py for a complete list of available sockets. - -positional arguments: - socket socket names to dump. defaults to all services defined in cereal - -optional arguments: - -h, --help show this help message and exit - --pipe - --raw - --json - --dump-json - --no-print - --addr ADDR - --values VALUES values to monitor (instead of entire event) -``` - -## [vw_mqb_config.py](vw_mqb_config.py) - -``` -usage: vw_mqb_config.py [-h] [--debug] {enable,show,disable} - -Shows Volkswagen EPS software and coding info, and enables or disables Heading Control -Assist (Lane Assist). Useful for enabling HCA on cars without factory Lane Assist that want -to use openpilot integrated at the CAN gateway (J533). - -positional arguments: - {enable,show,disable} - show or modify current EPS HCA config - -optional arguments: - -h, --help show this help message and exit - --debug enable ISO-TP/UDS stack debugging output - -This tool is meant to run directly on a vehicle-installed comma three, with -the openpilot/tmux processes stopped. It should also work on a separate PC with a USB- -attached comma panda. Vehicle ignition must be on. Recommend engine not be running when -making changes. Must turn ignition off and on again for any changes to take effect. -``` diff --git a/selfdrive/debug/check_can_parser_performance.py b/selfdrive/debug/check_can_parser_performance.py deleted file mode 100755 index 20987b3cf4..0000000000 --- a/selfdrive/debug/check_can_parser_performance.py +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env python3 -import numpy as np -import time -from tqdm import tqdm - -from cereal import car -from opendbc.car.tests.routes import CarTestRoute -from openpilot.selfdrive.car.tests.test_models import TestCarModelBase -from openpilot.tools.plotjuggler.juggle import DEMO_ROUTE - -N_RUNS = 10 - - -class CarModelTestCase(TestCarModelBase): - test_route = CarTestRoute(DEMO_ROUTE, None) - - -if __name__ == '__main__': - # Get CAN messages and parsers - tm = CarModelTestCase() - tm.setUpClass() - tm.setUp() - - CC = car.CarControl.new_message() - ets = [] - for _ in tqdm(range(N_RUNS)): - start_t = time.process_time_ns() - for msg in tm.can_msgs: - for cp in tm.CI.can_parsers.values(): - if cp is not None: - cp.update_strings(msg) - ets.append((time.process_time_ns() - start_t) * 1e-6) - - print(f'{len(tm.can_msgs)} CAN packets, {N_RUNS} runs') - print(f'{np.mean(ets):.2f} mean ms, {max(ets):.2f} max ms, {min(ets):.2f} min ms, {np.std(ets):.2f} std ms') - print(f'{np.mean(ets) / len(tm.can_msgs):.4f} mean ms / CAN packet') diff --git a/selfdrive/debug/check_freq.py b/selfdrive/debug/check_freq.py deleted file mode 100755 index 1765aeb86b..0000000000 --- a/selfdrive/debug/check_freq.py +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/env python3 -import argparse -import numpy as np -import time -from collections import defaultdict, deque -from collections.abc import MutableSequence - -import cereal.messaging as messaging - - -if __name__ == "__main__": - context = messaging.Context() - poller = messaging.Poller() - - parser = argparse.ArgumentParser() - parser.add_argument("socket", type=str, nargs='*', help="socket name") - args = parser.parse_args() - - socket_names = args.socket - sockets = {} - - rcv_times: defaultdict[str, MutableSequence[float]] = defaultdict(lambda: deque(maxlen=100)) - valids: defaultdict[str, deque[bool]] = defaultdict(lambda: deque(maxlen=100)) - - t = time.monotonic() - for name in socket_names: - sock = messaging.sub_sock(name, poller=poller) - sockets[sock] = name - - prev_print = t - while True: - for socket in poller.poll(100): - msg = messaging.recv_one(socket) - if msg is None: - continue - - name = msg.which() - - t = time.monotonic() - rcv_times[name].append(msg.logMonoTime / 1e9) - valids[name].append(msg.valid) - - if t - prev_print > 1: - print() - for name in socket_names: - dts = np.diff(rcv_times[name]) - mean = np.mean(dts) - print(f"{name}: Freq {1.0 / mean:.2f} Hz, Min {np.min(dts) / mean * 100:.2f}%, Max {np.max(dts) / mean * 100:.2f}%, valid ", all(valids[name])) - - prev_print = t diff --git a/selfdrive/debug/check_lag.py b/selfdrive/debug/check_lag.py deleted file mode 100755 index 341ae79c8b..0000000000 --- a/selfdrive/debug/check_lag.py +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env python3 - -import cereal.messaging as messaging -from cereal.services import SERVICE_LIST - -TO_CHECK = ['carState'] - - -if __name__ == "__main__": - sm = messaging.SubMaster(TO_CHECK) - - prev_t: dict[str, float] = {} - - while True: - sm.update() - - for s in TO_CHECK: - if sm.updated[s]: - t = sm.logMonoTime[s] / 1e9 - - if s in prev_t: - expected = 1.0 / (SERVICE_LIST[s].frequency) - dt = t - prev_t[s] - if dt > 10 * expected: - print(t, s, dt) - - prev_t[s] = t diff --git a/selfdrive/debug/check_timings.py b/selfdrive/debug/check_timings.py deleted file mode 100755 index fc527cd81b..0000000000 --- a/selfdrive/debug/check_timings.py +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env python3 -import sys -import time -import numpy as np -import datetime -from collections.abc import MutableSequence -from collections import defaultdict - -import cereal.messaging as messaging - - -if __name__ == "__main__": - ts: defaultdict[str, MutableSequence[float]] = defaultdict(list) - socks = {s: messaging.sub_sock(s, conflate=False) for s in sys.argv[1:]} - try: - st = time.monotonic() - while True: - print() - for s, sock in socks.items(): - msgs = messaging.drain_sock(sock) - for m in msgs: - ts[s].append(m.logMonoTime / 1e6) - - if len(ts[s]) > 2: - d = np.diff(ts[s])[-100:] - print(f"{s:25} {np.mean(d):7.2f} {np.std(d):7.2f} {np.max(d):7.2f} {np.min(d):7.2f}") - time.sleep(1) - except KeyboardInterrupt: - print("\n") - print("="*5, "timing summary", "="*5) - for s, sock in socks.items(): - msgs = messaging.drain_sock(sock) - if len(ts[s]) > 2: - d = np.diff(ts[s]) - print(f"{s:25} {np.mean(d):7.2f} {np.std(d):7.2f} {np.max(d):7.2f} {np.min(d):7.2f}") - print("="*5, datetime.timedelta(seconds=time.monotonic()-st), "="*5) diff --git a/selfdrive/debug/cpu_usage_stat.py b/selfdrive/debug/cpu_usage_stat.py deleted file mode 100755 index 234dfea3cc..0000000000 --- a/selfdrive/debug/cpu_usage_stat.py +++ /dev/null @@ -1,123 +0,0 @@ -#!/usr/bin/env python3 -# type: ignore -''' -System tools like top/htop can only show current cpu usage values, so I write this script to do statistics jobs. - Features: - Use psutil library to sample cpu usage(avergage for all cores) of openpilot processes, at a rate of 5 samples/sec. - Do cpu usage statistics periodically, 5 seconds as a cycle. - Calculate the average cpu usage within this cycle. - Calculate minumium/maximum/accumulated_average cpu usage as long term inspections. - Monitor multiple processes simuteneously. - Sample usage: - root@localhost:/data/openpilot$ python selfdrive/debug/cpu_usage_stat.py pandad,ubloxd - ('Add monitored proc:', './pandad') - ('Add monitored proc:', 'python locationd/ubloxd.py') - pandad: 1.96%, min: 1.96%, max: 1.96%, acc: 1.96% - ubloxd.py: 0.39%, min: 0.39%, max: 0.39%, acc: 0.39% -''' -import psutil -import time -import os -import sys -import numpy as np -import argparse -import re -from collections import defaultdict - -from openpilot.system.manager.process_config import managed_processes - -# Do statistics every 5 seconds -PRINT_INTERVAL = 5 -SLEEP_INTERVAL = 0.2 - -monitored_proc_names = [ - # android procs - 'SurfaceFlinger', 'sensors.qcom' -] + list(managed_processes.keys()) - -cpu_time_names = ['user', 'system', 'children_user', 'children_system'] - -timer = getattr(time, 'monotonic', time.time) - - -def get_arg_parser(): - parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) - - parser.add_argument("proc_names", nargs="?", default='', - help="Process names to be monitored, comma separated") - parser.add_argument("--list_all", action='store_true', - help="Show all running processes' cmdline") - parser.add_argument("--detailed_times", action='store_true', - help="show cpu time details (split by user, system, child user, child system)") - return parser - - -if __name__ == "__main__": - args = get_arg_parser().parse_args(sys.argv[1:]) - if args.list_all: - for p in psutil.process_iter(): - print('cmdline', p.cmdline(), 'name', p.name()) - sys.exit(0) - - if len(args.proc_names) > 0: - monitored_proc_names = args.proc_names.split(',') - monitored_procs = [] - stats = {} - for p in psutil.process_iter(): - if p == psutil.Process(): - continue - matched = any(l for l in p.cmdline() if any(pn for pn in monitored_proc_names if re.match(fr'.*{pn}.*', l, re.M | re.I))) - if matched: - k = ' '.join(p.cmdline()) - print('Add monitored proc:', k) - stats[k] = {'cpu_samples': defaultdict(list), 'min': defaultdict(lambda: None), 'max': defaultdict(lambda: None), - 'avg': defaultdict(float), 'last_cpu_times': None, 'last_sys_time': None} - stats[k]['last_sys_time'] = timer() - stats[k]['last_cpu_times'] = p.cpu_times() - monitored_procs.append(p) - i = 0 - interval_int = int(PRINT_INTERVAL / SLEEP_INTERVAL) - while True: - for p in monitored_procs: - k = ' '.join(p.cmdline()) - cur_sys_time = timer() - cur_cpu_times = p.cpu_times() - cpu_times = np.subtract(cur_cpu_times, stats[k]['last_cpu_times']) / (cur_sys_time - stats[k]['last_sys_time']) - stats[k]['last_sys_time'] = cur_sys_time - stats[k]['last_cpu_times'] = cur_cpu_times - cpu_percent = 0 - for num, name in enumerate(cpu_time_names): - stats[k]['cpu_samples'][name].append(cpu_times[num]) - cpu_percent += cpu_times[num] - stats[k]['cpu_samples']['total'].append(cpu_percent) - time.sleep(SLEEP_INTERVAL) - i += 1 - if i % interval_int == 0: - l = [] - for k, stat in stats.items(): - if len(stat['cpu_samples']) <= 0: - continue - for name, samples in stat['cpu_samples'].items(): - samples = np.array(samples) - avg = samples.mean() - c = samples.size - min_cpu = np.amin(samples) - max_cpu = np.amax(samples) - if stat['min'][name] is None or min_cpu < stat['min'][name]: - stat['min'][name] = min_cpu - if stat['max'][name] is None or max_cpu > stat['max'][name]: - stat['max'][name] = max_cpu - stat['avg'][name] = (stat['avg'][name] * (i - c) + avg * c) / (i) - stat['cpu_samples'][name] = [] - - msg = f"avg: {stat['avg']['total']:.2%}, min: {stat['min']['total']:.2%}, max: {stat['max']['total']:.2%} {os.path.basename(k)}" - if args.detailed_times: - for stat_type in ['avg', 'min', 'max']: - msg += f"\n {stat_type}: {[(name + ':' + str(round(stat[stat_type][name] * 100, 2))) for name in cpu_time_names]}" - l.append((os.path.basename(k), stat['avg']['total'], msg)) - l.sort(key=lambda x: -x[1]) - for x in l: - print(x[2]) - print('avg sum: {:.2%} over {} samples {} seconds\n'.format( - sum(stat['avg']['total'] for k, stat in stats.items()), i, i * SLEEP_INTERVAL - )) diff --git a/selfdrive/debug/dump_car_docs.py b/selfdrive/debug/dump_car_docs.py deleted file mode 100755 index f0e99cda24..0000000000 --- a/selfdrive/debug/dump_car_docs.py +++ /dev/null @@ -1,18 +0,0 @@ -#!/usr/bin/env python3 -import argparse -import pickle - -from opendbc.car.docs import get_all_car_docs - - -def dump_car_docs(path): - with open(path, 'wb') as f: - pickle.dump(get_all_car_docs(), f) - print(f'Dumping car info to {path}') - - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument("--path", required=True) - args = parser.parse_args() - dump_car_docs(args.path) diff --git a/selfdrive/debug/print_docs_diff.py b/selfdrive/debug/print_docs_diff.py deleted file mode 100755 index 388acf3af5..0000000000 --- a/selfdrive/debug/print_docs_diff.py +++ /dev/null @@ -1,120 +0,0 @@ -#!/usr/bin/env python3 -import argparse -from collections import defaultdict -import difflib -import pickle - -from opendbc.car.docs import get_all_car_docs -from opendbc.car.docs_definitions import Column - -FOOTNOTE_TAG = "{}" -STAR_ICON = '' -VIDEO_ICON = '' + \ - '' -COLUMNS = "|" + "|".join([column.value for column in Column]) + "|" -COLUMN_HEADER = "|---|---|---|{}|".format("|".join([":---:"] * (len(Column) - 3))) -ARROW_SYMBOL = "➡️" - - -def load_base_car_docs(path): - with open(path, "rb") as f: - return pickle.load(f) - - -def match_cars(base_cars, new_cars): - changes = [] - additions = [] - for new in new_cars: - # Addition if no close matches or close match already used - # Change if close match and not already used - matches = difflib.get_close_matches(new.name, [b.name for b in base_cars], cutoff=0.) - if not len(matches) or matches[0] in [c[1].name for c in changes]: - additions.append(new) - else: - changes.append((new, next(car for car in base_cars if car.name == matches[0]))) - - # Removal if base car not in changes - removals = [b for b in base_cars if b.name not in [c[1].name for c in changes]] - return changes, additions, removals - - -def build_column_diff(base_car, new_car): - row_builder = [] - for column in Column: - base_column = base_car.get_column(column, STAR_ICON, VIDEO_ICON, FOOTNOTE_TAG) - new_column = new_car.get_column(column, STAR_ICON, VIDEO_ICON, FOOTNOTE_TAG) - - if base_column != new_column: - row_builder.append(f"{base_column} {ARROW_SYMBOL} {new_column}") - else: - row_builder.append(new_column) - - return format_row(row_builder) - - -def format_row(builder): - return "|" + "|".join(builder) + "|" - - -def print_car_docs_diff(path): - base_car_docs = defaultdict(list) - new_car_docs = defaultdict(list) - - for car in load_base_car_docs(path): - base_car_docs[car.car_fingerprint].append(car) - for car in get_all_car_docs(): - new_car_docs[car.car_fingerprint].append(car) - - # Add new platforms to base cars so we can detect additions and removals in one pass - base_car_docs.update({car: [] for car in new_car_docs if car not in base_car_docs}) - - changes = defaultdict(list) - for base_car_model, base_cars in base_car_docs.items(): - # Match car info changes, and get additions and removals - new_cars = new_car_docs[base_car_model] - car_changes, car_additions, car_removals = match_cars(base_cars, new_cars) - - # Removals - for car_docs in car_removals: - changes["removals"].append(format_row([car_docs.get_column(column, STAR_ICON, VIDEO_ICON, FOOTNOTE_TAG) for column in Column])) - - # Additions - for car_docs in car_additions: - changes["additions"].append(format_row([car_docs.get_column(column, STAR_ICON, VIDEO_ICON, FOOTNOTE_TAG) for column in Column])) - - for new_car, base_car in car_changes: - # Column changes - row_diff = build_column_diff(base_car, new_car) - if ARROW_SYMBOL in row_diff: - changes["column"].append(row_diff) - - # Detail sentence changes - if base_car.detail_sentence != new_car.detail_sentence: - changes["detail"].append(f"- Sentence for {base_car.name} changed!\n" + - " ```diff\n" + - f" - {base_car.detail_sentence}\n" + - f" + {new_car.detail_sentence}\n" + - " ```") - - # Print diff - if any(len(c) for c in changes.values()): - markdown_builder = ["### ⚠️ This PR makes changes to [CARS.md](../blob/master/docs/CARS.md) ⚠️"] - - for title, category in (("## 🔀 Column Changes", "column"), ("## ❌ Removed", "removals"), - ("## ➕ Added", "additions"), ("## 📖 Detail Sentence Changes", "detail")): - if len(changes[category]): - markdown_builder.append(title) - if category not in ("detail",): - markdown_builder.append(COLUMNS) - markdown_builder.append(COLUMN_HEADER) - markdown_builder.extend(changes[category]) - - print("\n".join(markdown_builder)) - - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument("--path", required=True) - args = parser.parse_args() - print_car_docs_diff(args.path) diff --git a/selfdrive/debug/run_process_on_route.py b/selfdrive/debug/run_process_on_route.py deleted file mode 100755 index 2ccb0fb3e7..0000000000 --- a/selfdrive/debug/run_process_on_route.py +++ /dev/null @@ -1,30 +0,0 @@ -#!/usr/bin/env python3 - -import argparse - -from openpilot.selfdrive.test.process_replay.process_replay import CONFIGS, replay_process -from openpilot.tools.lib.logreader import LogReader, save_log - -if __name__ == "__main__": - parser = argparse.ArgumentParser(description="Run process on route and create new logs", - formatter_class=argparse.ArgumentDefaultsHelpFormatter) - parser.add_argument("--fingerprint", help="The fingerprint to use") - parser.add_argument("route", help="The route name to use") - parser.add_argument("process", nargs='+', help="The process(s) to run") - args = parser.parse_args() - - cfgs = [c for c in CONFIGS if c.proc_name in args.process] - - lr = LogReader(args.route) - inputs = list(lr) - - outputs = replay_process(cfgs, inputs, fingerprint=args.fingerprint) - - # Remove message generated by the process under test and merge in the new messages - produces = {o.which() for o in outputs} - inputs = [i for i in inputs if i.which() not in produces] - outputs = sorted(inputs + outputs, key=lambda x: x.logMonoTime) - - fn = f"{args.route.replace('/', '_')}_{'_'.join(args.process)}.zst" - print(f"Saving log to {fn}") - save_log(fn, outputs) diff --git a/selfdrive/debug/touch_replay.py b/selfdrive/debug/touch_replay.py deleted file mode 100755 index 6e5ecbbe5b..0000000000 --- a/selfdrive/debug/touch_replay.py +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env python3 -import argparse - -import numpy as np -import matplotlib.pyplot as plt - -from openpilot.tools.lib.logreader import LogReader - -if __name__ == '__main__': - parser = argparse.ArgumentParser() - parser.add_argument('--width', default=2160, type=int) - parser.add_argument('--height', default=1080, type=int) - parser.add_argument('--route', default='rlog', type=str) - args = parser.parse_args() - - w = args.width - h = args.height - route = args.route - - fingers = [[-1, -1]] * 5 - touch_points = [] - current_slot = 0 - - lr = list(LogReader(route)) - for msg in lr: - if msg.which() == 'touch': - for event in msg.touch: - if event.type == 3 and event.code == 47: - current_slot = event.value - elif event.type == 3 and event.code == 57 and event.value == -1: - fingers[current_slot] = [-1, -1] - elif event.type == 3 and event.code == 53: - fingers[current_slot][1] = event.value - if fingers[current_slot][0] != -1: - touch_points.append(fingers[current_slot].copy()) - elif event.type == 3 and event.code == 54: - fingers[current_slot][0] = w - event.value - if fingers[current_slot][1] != -1: - touch_points.append(fingers[current_slot].copy()) - - if not touch_points: - print(f'No touch events found for {route}') - quit() - - unique_points, counts = np.unique(touch_points, axis=0, return_counts=True) - - plt.figure(figsize=(10, 3)) - plt.scatter(unique_points[:, 0], unique_points[:, 1], c=counts, s=counts * 20, edgecolors='red') - plt.colorbar() - plt.title(f'Touches for {route}') - plt.xlim(0, w) - plt.ylim(0, h) - plt.grid(True) - plt.show() diff --git a/selfdrive/locationd/.gitignore b/selfdrive/locationd/.gitignore deleted file mode 100644 index 1a8c72388a..0000000000 --- a/selfdrive/locationd/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -params_learner -paramsd diff --git a/selfdrive/locationd/helpers.py b/selfdrive/locationd/helpers.py deleted file mode 100644 index bf4588a40c..0000000000 --- a/selfdrive/locationd/helpers.py +++ /dev/null @@ -1,183 +0,0 @@ -import numpy as np -from typing import Any -from functools import cache - -from cereal import log -from openpilot.common.transformations.orientation import rot_from_euler, euler_from_rot - - -@cache -def fft_next_good_size(n: int) -> int: - """ - smallest composite of 2, 3, 5, 7, 11 that is >= n - inspired by pocketfft - """ - if n <= 6: - return n - best, f2 = 2 * n, 1 - while f2 < best: - f23 = f2 - while f23 < best: - f235 = f23 - while f235 < best: - f2357 = f235 - while f2357 < best: - f235711 = f2357 - while f235711 < best: - best = f235711 if f235711 >= n else best - f235711 *= 11 - f2357 *= 7 - f235 *= 5 - f23 *= 3 - f2 *= 2 - return best - - -def parabolic_peak_interp(R, max_index): - if max_index == 0 or max_index == len(R) - 1: - return max_index - - y_m1, y_0, y_p1 = R[max_index - 1], R[max_index], R[max_index + 1] - offset = 0.5 * (y_p1 - y_m1) / (2 * y_0 - y_p1 - y_m1) - - return max_index + offset - - -def rotate_cov(rot_matrix, cov_in): - return rot_matrix @ cov_in @ rot_matrix.T - - -def rotate_std(rot_matrix, std_in): - return np.sqrt(np.diag(rotate_cov(rot_matrix, np.diag(std_in**2)))) - - -class NPQueue: - def __init__(self, maxlen: int, rowsize: int) -> None: - self.maxlen = maxlen - self.arr = np.empty((0, rowsize)) - - def __len__(self) -> int: - return len(self.arr) - - def append(self, pt: list[float]) -> None: - if len(self.arr) < self.maxlen: - self.arr = np.append(self.arr, [pt], axis=0) - else: - self.arr[:-1] = self.arr[1:] - self.arr[-1] = pt - - -class PointBuckets: - def __init__(self, x_bounds: list[tuple[float, float]], min_points: list[float], min_points_total: int, points_per_bucket: int, rowsize: int) -> None: - self.x_bounds = x_bounds - self.buckets = {bounds: NPQueue(maxlen=points_per_bucket, rowsize=rowsize) for bounds in x_bounds} - self.buckets_min_points = dict(zip(x_bounds, min_points, strict=True)) - self.min_points_total = min_points_total - - def __len__(self) -> int: - return sum([len(v) for v in self.buckets.values()]) - - def is_valid(self) -> bool: - individual_buckets_valid = all(len(v) >= min_pts for v, min_pts in zip(self.buckets.values(), self.buckets_min_points.values(), strict=True)) - total_points_valid = self.__len__() >= self.min_points_total - return individual_buckets_valid and total_points_valid - - def get_valid_percent(self) -> int: - total_points_perc = min(self.__len__() / self.min_points_total * 100, 100) - individual_buckets_perc = min(min(len(v) / min_pts * 100 for v, min_pts in - zip(self.buckets.values(), self.buckets_min_points.values(), strict=True)), 100) - return int((total_points_perc + individual_buckets_perc) / 2) - - def is_calculable(self) -> bool: - return all(len(v) > 0 for v in self.buckets.values()) - - def add_point(self, x: float, y: float) -> None: - raise NotImplementedError - - def get_points(self, num_points: int = None) -> Any: - points = np.vstack([x.arr for x in self.buckets.values()]) - if num_points is None: - return points - return points[np.random.choice(np.arange(len(points)), min(len(points), num_points), replace=False)] - - def load_points(self, points: list[list[float]]) -> None: - for point in points: - self.add_point(*point) - - -class ParameterEstimator: - """ Base class for parameter estimators """ - def reset(self) -> None: - raise NotImplementedError - - def handle_log(self, t: int, which: str, msg: log.Event) -> None: - raise NotImplementedError - - def get_msg(self, valid: bool, with_points: bool) -> log.Event: - raise NotImplementedError - - -class Measurement: - x, y, z = (property(lambda self: self.xyz[0]), property(lambda self: self.xyz[1]), property(lambda self: self.xyz[2])) - x_std, y_std, z_std = (property(lambda self: self.xyz_std[0]), property(lambda self: self.xyz_std[1]), property(lambda self: self.xyz_std[2])) - roll, pitch, yaw = x, y, z - roll_std, pitch_std, yaw_std = x_std, y_std, z_std - - def __init__(self, xyz: np.ndarray, xyz_std: np.ndarray): - self.xyz: np.ndarray = xyz - self.xyz_std: np.ndarray = xyz_std - - @classmethod - def from_measurement_xyz(cls, measurement: log.LivePose.XYZMeasurement) -> 'Measurement': - return cls( - xyz=np.array([measurement.x, measurement.y, measurement.z]), - xyz_std=np.array([measurement.xStd, measurement.yStd, measurement.zStd]) - ) - - -class Pose: - def __init__(self, orientation: Measurement, velocity: Measurement, acceleration: Measurement, angular_velocity: Measurement): - self.orientation = orientation - self.velocity = velocity - self.acceleration = acceleration - self.angular_velocity = angular_velocity - - @classmethod - def from_live_pose(cls, live_pose: log.LivePose) -> 'Pose': - return Pose( - orientation=Measurement.from_measurement_xyz(live_pose.orientationNED), - velocity=Measurement.from_measurement_xyz(live_pose.velocityDevice), - acceleration=Measurement.from_measurement_xyz(live_pose.accelerationDevice), - angular_velocity=Measurement.from_measurement_xyz(live_pose.angularVelocityDevice) - ) - - -class PoseCalibrator: - def __init__(self): - self.calib_valid = False - self.calib_from_device = np.eye(3) - - def _transform_calib_from_device(self, meas: Measurement): - new_xyz = self.calib_from_device @ meas.xyz - new_xyz_std = rotate_std(self.calib_from_device, meas.xyz_std) - return Measurement(new_xyz, new_xyz_std) - - def _ned_from_calib(self, orientation: Measurement): - ned_from_device = rot_from_euler(orientation.xyz) - ned_from_calib = ned_from_device @ self.calib_from_device.T - ned_from_calib_euler_meas = Measurement(euler_from_rot(ned_from_calib), np.full(3, np.nan)) - return ned_from_calib_euler_meas - - def build_calibrated_pose(self, pose: Pose) -> Pose: - ned_from_calib_euler = self._ned_from_calib(pose.orientation) - angular_velocity_calib = self._transform_calib_from_device(pose.angular_velocity) - acceleration_calib = self._transform_calib_from_device(pose.acceleration) - velocity_calib = self._transform_calib_from_device(pose.angular_velocity) - - return Pose(ned_from_calib_euler, velocity_calib, acceleration_calib, angular_velocity_calib) - - def feed_live_calib(self, live_calib: log.LiveCalibrationData): - calib_rpy = np.array(live_calib.rpyCalib) - device_from_calib = rot_from_euler(calib_rpy) - self.calib_from_device = device_from_calib.T - self.calib_valid = live_calib.calStatus == log.LiveCalibrationData.Status.calibrated diff --git a/selfdrive/locationd/models/car_kf.py b/selfdrive/locationd/models/car_kf.py deleted file mode 100755 index 349897f371..0000000000 --- a/selfdrive/locationd/models/car_kf.py +++ /dev/null @@ -1,179 +0,0 @@ -#!/usr/bin/env python3 -import math -import sys -from typing import Any - -import numpy as np - -from opendbc.car.vehicle_model import ACCELERATION_DUE_TO_GRAVITY -from openpilot.selfdrive.locationd.models.constants import ObservationKind -from openpilot.common.swaglog import cloudlog - -from rednose.helpers.kalmanfilter import KalmanFilter - -if __name__ == '__main__': # Generating sympy - import sympy as sp - from rednose.helpers.ekf_sym import gen_code -else: - from rednose.helpers.ekf_sym_pyx import EKF_sym_pyx - - -i = 0 - -def _slice(n): - global i - s = slice(i, i + n) - i += n - - return s - - -class States: - # Vehicle model params - STIFFNESS = _slice(1) # [-] - STEER_RATIO = _slice(1) # [-] - ANGLE_OFFSET = _slice(1) # [rad] - ANGLE_OFFSET_FAST = _slice(1) # [rad] - - VELOCITY = _slice(2) # (x, y) [m/s] - YAW_RATE = _slice(1) # [rad/s] - STEER_ANGLE = _slice(1) # [rad] - ROAD_ROLL = _slice(1) # [rad] - - -class CarKalman(KalmanFilter): - name = 'car' - - initial_x = np.array([ - 1.0, - 15.0, - 0.0, - 0.0, - - 10.0, 0.0, - 0.0, - 0.0, - 0.0 - ]) - - # process noise - Q = np.diag([ - (.05 / 100)**2, - .01**2, - math.radians(0.02)**2, - math.radians(0.25)**2, - - .1**2, .01**2, - math.radians(0.1)**2, - math.radians(0.1)**2, - math.radians(1)**2, - ]) - P_initial = Q.copy() - - obs_noise: dict[int, Any] = { - ObservationKind.STEER_ANGLE: np.atleast_2d(math.radians(0.05)**2), - ObservationKind.ANGLE_OFFSET_FAST: np.atleast_2d(math.radians(10.0)**2), - ObservationKind.ROAD_ROLL: np.atleast_2d(math.radians(1.0)**2), - ObservationKind.STEER_RATIO: np.atleast_2d(5.0**2), - ObservationKind.STIFFNESS: np.atleast_2d(0.5**2), - ObservationKind.ROAD_FRAME_X_SPEED: np.atleast_2d(0.1**2), - } - - global_vars = [ - 'mass', - 'rotational_inertia', - 'center_to_front', - 'center_to_rear', - 'stiffness_front', - 'stiffness_rear', - ] - - @staticmethod - def generate_code(generated_dir): - dim_state = CarKalman.initial_x.shape[0] - name = CarKalman.name - - # vehicle models comes from The Science of Vehicle Dynamics: Handling, Braking, and Ride of Road and Race Cars - # Model used is in 6.15 with formula from 6.198 - - # globals - global_vars = [sp.Symbol(name) for name in CarKalman.global_vars] - m, j, aF, aR, cF_orig, cR_orig = global_vars - - # make functions and jacobians with sympy - # state variables - state_sym = sp.MatrixSymbol('state', dim_state, 1) - state = sp.Matrix(state_sym) - - # Vehicle model constants - sf = state[States.STIFFNESS, :][0, 0] - - cF, cR = sf * cF_orig, sf * cR_orig - angle_offset = state[States.ANGLE_OFFSET, :][0, 0] - angle_offset_fast = state[States.ANGLE_OFFSET_FAST, :][0, 0] - theta = state[States.ROAD_ROLL, :][0, 0] - sa = state[States.STEER_ANGLE, :][0, 0] - - sR = state[States.STEER_RATIO, :][0, 0] - u, v = state[States.VELOCITY, :] - r = state[States.YAW_RATE, :][0, 0] - - A = sp.Matrix(np.zeros((2, 2))) - A[0, 0] = -(cF + cR) / (m * u) - A[0, 1] = -(cF * aF - cR * aR) / (m * u) - u - A[1, 0] = -(cF * aF - cR * aR) / (j * u) - A[1, 1] = -(cF * aF**2 + cR * aR**2) / (j * u) - - B = sp.Matrix(np.zeros((2, 1))) - B[0, 0] = cF / m / sR - B[1, 0] = (cF * aF) / j / sR - - C = sp.Matrix(np.zeros((2, 1))) - C[0, 0] = ACCELERATION_DUE_TO_GRAVITY - C[1, 0] = 0 - - x = sp.Matrix([v, r]) # lateral velocity, yaw rate - x_dot = A * x + B * (sa - angle_offset - angle_offset_fast) - C * theta - - dt = sp.Symbol('dt') - state_dot = sp.Matrix(np.zeros((dim_state, 1))) - state_dot[States.VELOCITY.start + 1, 0] = x_dot[0] - state_dot[States.YAW_RATE.start, 0] = x_dot[1] - - # Basic descretization, 1st order integrator - # Can be pretty bad if dt is big - f_sym = state + dt * state_dot - - # - # Observation functions - # - obs_eqs = [ - [sp.Matrix([r]), ObservationKind.ROAD_FRAME_YAW_RATE, None], - [sp.Matrix([u, v]), ObservationKind.ROAD_FRAME_XY_SPEED, None], - [sp.Matrix([u]), ObservationKind.ROAD_FRAME_X_SPEED, None], - [sp.Matrix([sa]), ObservationKind.STEER_ANGLE, None], - [sp.Matrix([angle_offset_fast]), ObservationKind.ANGLE_OFFSET_FAST, None], - [sp.Matrix([sR]), ObservationKind.STEER_RATIO, None], - [sp.Matrix([sf]), ObservationKind.STIFFNESS, None], - [sp.Matrix([theta]), ObservationKind.ROAD_ROLL, None], - ] - - gen_code(generated_dir, name, f_sym, dt, state_sym, obs_eqs, dim_state, dim_state, global_vars=global_vars) - - def __init__(self, generated_dir): - dim_state, dim_state_err = CarKalman.initial_x.shape[0], CarKalman.P_initial.shape[0] - self.filter = EKF_sym_pyx(generated_dir, CarKalman.name, CarKalman.Q, CarKalman.initial_x, CarKalman.P_initial, - dim_state, dim_state_err, global_vars=CarKalman.global_vars, logger=cloudlog) - - def set_globals(self, mass, rotational_inertia, center_to_front, center_to_rear, stiffness_front, stiffness_rear): - self.filter.set_global("mass", mass) - self.filter.set_global("rotational_inertia", rotational_inertia) - self.filter.set_global("center_to_front", center_to_front) - self.filter.set_global("center_to_rear", center_to_rear) - self.filter.set_global("stiffness_front", stiffness_front) - self.filter.set_global("stiffness_rear", stiffness_rear) - - -if __name__ == "__main__": - generated_dir = sys.argv[2] - CarKalman.generate_code(generated_dir) diff --git a/selfdrive/locationd/test/test_lagd.py b/selfdrive/locationd/test/test_lagd.py deleted file mode 100644 index 8fb829edd8..0000000000 --- a/selfdrive/locationd/test/test_lagd.py +++ /dev/null @@ -1,149 +0,0 @@ -import random -import numpy as np -import time -import pytest - -from cereal import messaging, log, car -from openpilot.selfdrive.locationd.lagd import LateralLagEstimator, retrieve_initial_lag, masked_normalized_cross_correlation, \ - BLOCK_NUM_NEEDED, BLOCK_SIZE, MIN_OKAY_WINDOW_SEC -from openpilot.selfdrive.test.process_replay.migration import migrate, migrate_carParams -from openpilot.selfdrive.locationd.test.test_locationd_scenarios import TEST_ROUTE -from openpilot.common.params import Params -from openpilot.tools.lib.logreader import LogReader -from openpilot.system.hardware import PC - -MAX_ERR_FRAMES = 1 -DT = 0.05 - - -def process_messages(estimator, lag_frames, n_frames, vego=20.0, rejection_threshold=0.0): - for i in range(n_frames): - t = i * estimator.dt - desired_la = np.cos(10 * t) * 0.1 - actual_la = np.cos(10 * (t - lag_frames * estimator.dt)) * 0.1 - - # if sample is masked out, set it to desired value (no lag) - rejected = random.uniform(0, 1) < rejection_threshold - if rejected: - actual_la = desired_la - - desired_cuvature = float(desired_la / (vego ** 2)) - actual_yr = float(actual_la / vego) - msgs = [ - (t, "carControl", car.CarControl(latActive=not rejected)), - (t, "carState", car.CarState(vEgo=vego, steeringPressed=False)), - (t, "controlsState", log.ControlsState(desiredCurvature=desired_cuvature)), - (t, "livePose", log.LivePose(angularVelocityDevice=log.LivePose.XYZMeasurement(z=actual_yr, valid=True), - posenetOK=True, inputsOK=True)), - (t, "liveCalibration", log.LiveCalibrationData(rpyCalib=[0, 0, 0], calStatus=log.LiveCalibrationData.Status.calibrated)), - ] - for t, w, m in msgs: - estimator.handle_log(t, w, m) - estimator.update_points() - estimator.update_estimate() - - -class TestLagd: - def test_read_saved_params(self): - params = Params() - - lr = migrate(LogReader(TEST_ROUTE), [migrate_carParams]) - CP = next(m for m in lr if m.which() == "carParams").carParams - - msg = messaging.new_message('liveDelay') - msg.liveDelay.lateralDelayEstimate = random.random() - msg.liveDelay.validBlocks = random.randint(1, 10) - params.put("LiveDelay", msg.to_bytes()) - params.put("CarParamsPrevRoute", CP.as_builder().to_bytes()) - - saved_lag_params = retrieve_initial_lag(params, CP) - assert saved_lag_params is not None - - lag, valid_blocks = saved_lag_params - assert lag == msg.liveDelay.lateralDelayEstimate - assert valid_blocks == msg.liveDelay.validBlocks - - def test_ncc(self): - lag_frames = random.randint(1, 19) - - desired_sig = np.sin(np.arange(0.0, 10.0, 0.1)) - actual_sig = np.sin(np.arange(0.0, 10.0, 0.1) - lag_frames * 0.1) - mask = np.ones(len(desired_sig), dtype=bool) - - corr = masked_normalized_cross_correlation(desired_sig, actual_sig, mask, 200)[len(desired_sig) - 1:len(desired_sig) + 20] - assert np.argmax(corr) == lag_frames - - # add some noise - desired_sig += np.random.normal(0, 0.05, len(desired_sig)) - actual_sig += np.random.normal(0, 0.05, len(actual_sig)) - corr = masked_normalized_cross_correlation(desired_sig, actual_sig, mask, 200)[len(desired_sig) - 1:len(desired_sig) + 20] - assert np.argmax(corr) in range(lag_frames - MAX_ERR_FRAMES, lag_frames + MAX_ERR_FRAMES + 1) - - # mask out 40% of the values, and make them noise - mask = np.random.choice([True, False], size=len(desired_sig), p=[0.6, 0.4]) - desired_sig[~mask] = np.random.normal(0, 1, size=np.sum(~mask)) - actual_sig[~mask] = np.random.normal(0, 1, size=np.sum(~mask)) - corr = masked_normalized_cross_correlation(desired_sig, actual_sig, mask, 200)[len(desired_sig) - 1:len(desired_sig) + 20] - assert np.argmax(corr) in range(lag_frames - MAX_ERR_FRAMES, lag_frames + MAX_ERR_FRAMES + 1) - - def test_empty_estimator(self): - mocked_CP = car.CarParams(steerActuatorDelay=0.8) - estimator = LateralLagEstimator(mocked_CP, DT) - msg = estimator.get_msg(True) - assert msg.liveDelay.status == 'unestimated' - assert np.allclose(msg.liveDelay.lateralDelay, estimator.initial_lag) - assert np.allclose(msg.liveDelay.lateralDelayEstimate, estimator.initial_lag) - assert msg.liveDelay.validBlocks == 0 - assert msg.liveDelay.calPerc == 0 - - def test_estimator_basics(self, subtests): - for lag_frames in range(5): - with subtests.test(msg=f"lag_frames={lag_frames}"): - mocked_CP = car.CarParams(steerActuatorDelay=0.8) - estimator = LateralLagEstimator(mocked_CP, DT, min_recovery_buffer_sec=0.0, min_yr=0.0) - process_messages(estimator, lag_frames, int(MIN_OKAY_WINDOW_SEC / DT) + BLOCK_NUM_NEEDED * BLOCK_SIZE) - msg = estimator.get_msg(True) - assert msg.liveDelay.status == 'estimated' - assert np.allclose(msg.liveDelay.lateralDelay, lag_frames * DT, atol=0.01) - assert np.allclose(msg.liveDelay.lateralDelayEstimate, lag_frames * DT, atol=0.01) - assert np.allclose(msg.liveDelay.lateralDelayEstimateStd, 0.0, atol=0.01) - assert msg.liveDelay.validBlocks == BLOCK_NUM_NEEDED - assert msg.liveDelay.calPerc == 100 - - def test_disabled_estimator(self): - mocked_CP = car.CarParams(steerActuatorDelay=0.8) - estimator = LateralLagEstimator(mocked_CP, DT, min_recovery_buffer_sec=0.0, min_yr=0.0, enabled=False) - lag_frames = 5 - process_messages(estimator, lag_frames, int(MIN_OKAY_WINDOW_SEC / DT) + BLOCK_NUM_NEEDED * BLOCK_SIZE) - msg = estimator.get_msg(True) - assert msg.liveDelay.status == 'unestimated' - assert np.allclose(msg.liveDelay.lateralDelay, 1.0, atol=0.01) - assert np.allclose(msg.liveDelay.lateralDelayEstimate, lag_frames * DT, atol=0.01) - assert np.allclose(msg.liveDelay.lateralDelayEstimateStd, 0.0, atol=0.01) - assert msg.liveDelay.validBlocks == BLOCK_NUM_NEEDED - assert msg.liveDelay.calPerc == 100 - - def test_estimator_masking(self): - mocked_CP, lag_frames = car.CarParams(steerActuatorDelay=0.8), random.randint(1, 19) - estimator = LateralLagEstimator(mocked_CP, DT, min_recovery_buffer_sec=0.0, min_yr=0.0, min_valid_block_count=1) - process_messages(estimator, lag_frames, (int(MIN_OKAY_WINDOW_SEC / DT) + BLOCK_SIZE) * 2, rejection_threshold=0.4) - msg = estimator.get_msg(True) - assert np.allclose(msg.liveDelay.lateralDelayEstimate, lag_frames * DT, atol=0.01) - assert np.allclose(msg.liveDelay.lateralDelayEstimateStd, 0.0, atol=0.01) - assert msg.liveDelay.calPerc == 100 - - @pytest.mark.skipif(PC, reason="only on device") - @pytest.mark.timeout(60) - def test_estimator_performance(self): - mocked_CP = car.CarParams(steerActuatorDelay=0.8) - estimator = LateralLagEstimator(mocked_CP, DT) - - ds = [] - for _ in range(1000): - st = time.perf_counter() - estimator.update_points() - estimator.update_estimate() - d = time.perf_counter() - st - ds.append(d) - - assert np.mean(ds) < DT diff --git a/selfdrive/locationd/test/test_paramsd.py b/selfdrive/locationd/test/test_paramsd.py deleted file mode 100644 index 2129bf4386..0000000000 --- a/selfdrive/locationd/test/test_paramsd.py +++ /dev/null @@ -1,68 +0,0 @@ -import random -import numpy as np -import json - -from cereal import messaging -from openpilot.selfdrive.locationd.paramsd import retrieve_initial_vehicle_params, migrate_cached_vehicle_params_if_needed -from openpilot.selfdrive.locationd.models.car_kf import CarKalman -from openpilot.selfdrive.locationd.test.test_locationd_scenarios import TEST_ROUTE -from openpilot.selfdrive.test.process_replay.migration import migrate, migrate_carParams -from openpilot.common.params import Params -from openpilot.tools.lib.logreader import LogReader - - -def get_random_live_parameters(CP): - msg = messaging.new_message("liveParameters") - msg.liveParameters.steerRatio = (random.random() + 0.5) * CP.steerRatio - msg.liveParameters.stiffnessFactor = random.random() - msg.liveParameters.angleOffsetAverageDeg = random.random() - msg.liveParameters.debugFilterState.std = [random.random() for _ in range(CarKalman.P_initial.shape[0])] - return msg - - -class TestParamsd: - def test_read_saved_params(self): - params = Params() - - lr = migrate(LogReader(TEST_ROUTE), [migrate_carParams]) - CP = next(m for m in lr if m.which() == "carParams").carParams - - msg = get_random_live_parameters(CP) - params.put("LiveParametersV2", msg.to_bytes()) - params.put("CarParamsPrevRoute", CP.as_builder().to_bytes()) - - migrate_cached_vehicle_params_if_needed(params) # this is not tested here but should not mess anything up or throw an error - sr, sf, offset, p_init = retrieve_initial_vehicle_params(params, CP, replay=True, debug=True) - np.testing.assert_allclose(sr, msg.liveParameters.steerRatio) - np.testing.assert_allclose(sf, msg.liveParameters.stiffnessFactor) - np.testing.assert_allclose(offset, msg.liveParameters.angleOffsetAverageDeg) - np.testing.assert_equal(p_init.shape, CarKalman.P_initial.shape) - np.testing.assert_allclose(np.diagonal(p_init), msg.liveParameters.debugFilterState.std) - - # TODO Remove this test after the support for old format is removed - def test_read_saved_params_old_format(self): - params = Params() - - lr = migrate(LogReader(TEST_ROUTE), [migrate_carParams]) - CP = next(m for m in lr if m.which() == "carParams").carParams - - msg = get_random_live_parameters(CP) - params.put("LiveParameters", json.dumps(msg.liveParameters.to_dict())) - params.put("CarParamsPrevRoute", CP.as_builder().to_bytes()) - params.remove("LiveParametersV2") - - migrate_cached_vehicle_params_if_needed(params) - sr, sf, offset, _ = retrieve_initial_vehicle_params(params, CP, replay=True, debug=True) - np.testing.assert_allclose(sr, msg.liveParameters.steerRatio) - np.testing.assert_allclose(sf, msg.liveParameters.stiffnessFactor) - np.testing.assert_allclose(offset, msg.liveParameters.angleOffsetAverageDeg) - assert params.get("LiveParametersV2") is not None - - def test_read_saved_params_corrupted_old_format(self): - params = Params() - params.put("LiveParameters", b'\x00\x00\x02\x00\x01\x00:F\xde\xed\xae;') - params.remove("LiveParametersV2") - - migrate_cached_vehicle_params_if_needed(params) - assert params.get("LiveParameters") is None - assert params.get("LiveParametersV2") is None diff --git a/selfdrive/locationd/test/test_torqued.py b/selfdrive/locationd/test/test_torqued.py deleted file mode 100644 index 53f3120c36..0000000000 --- a/selfdrive/locationd/test/test_torqued.py +++ /dev/null @@ -1,25 +0,0 @@ -from cereal import car -from openpilot.selfdrive.locationd.torqued import TorqueEstimator - - -def test_cal_percent(): - est = TorqueEstimator(car.CarParams()) - msg = est.get_msg() - assert msg.liveTorqueParameters.calPerc == 0 - - for (low, high), min_pts in zip(est.filtered_points.buckets.keys(), - est.filtered_points.buckets_min_points.values(), strict=True): - for _ in range(int(min_pts)): - est.filtered_points.add_point((low + high) / 2.0, 0.0) - - # enough bucket points, but not enough total points - msg = est.get_msg() - assert msg.liveTorqueParameters.calPerc == (len(est.filtered_points) / est.min_points_total * 100 + 100) / 2 - - # add enough points to bucket with most capacity - key = list(est.filtered_points.buckets)[0] - for _ in range(est.min_points_total - len(est.filtered_points)): - est.filtered_points.add_point((key[0] + key[1]) / 2.0, 0.0) - - msg = est.get_msg() - assert msg.liveTorqueParameters.calPerc == 100 diff --git a/selfdrive/modeld/SConscript b/selfdrive/modeld/SConscript deleted file mode 100644 index 545fcdcff7..0000000000 --- a/selfdrive/modeld/SConscript +++ /dev/null @@ -1,72 +0,0 @@ -import os -import glob - -Import('env', 'envCython', 'arch', 'cereal', 'messaging', 'common', 'gpucommon', 'visionipc', 'transformations') -lenv = env.Clone() -lenvCython = envCython.Clone() - -libs = [cereal, messaging, visionipc, gpucommon, common, 'capnp', 'kj', 'pthread'] -frameworks = [] - -common_src = [ - "models/commonmodel.cc", - "transforms/loadyuv.cc", - "transforms/transform.cc", -] - -# OpenCL is a framework on Mac -if arch == "Darwin": - frameworks += ['OpenCL'] -else: - libs += ['OpenCL'] - -# Set path definitions -for pathdef, fn in {'TRANSFORM': 'transforms/transform.cl', 'LOADYUV': 'transforms/loadyuv.cl'}.items(): - for xenv in (lenv, lenvCython): - xenv['CXXFLAGS'].append(f'-D{pathdef}_PATH=\\"{File(fn).abspath}\\"') - -# Compile cython -cython_libs = envCython["LIBS"] + libs -commonmodel_lib = lenv.Library('commonmodel', common_src) -lenvCython.Program('models/commonmodel_pyx.so', 'models/commonmodel_pyx.pyx', LIBS=[commonmodel_lib, *cython_libs], FRAMEWORKS=frameworks) -tinygrad_files = ["#"+x for x in glob.glob(env.Dir("#tinygrad_repo").relpath + "/**", recursive=True, root_dir=env.Dir("#").abspath) if 'pycache' not in x] - -# Get model metadata -for model_name in ['driving_vision', 'driving_policy']: - fn = File(f"models/{model_name}").abspath - script_files = [File(Dir("#selfdrive/modeld").File("get_model_metadata.py").abspath)] - cmd = f'python3 {Dir("#selfdrive/modeld").abspath}/get_model_metadata.py {fn}.onnx' - lenv.Command(fn + "_metadata.pkl", [fn + ".onnx"] + tinygrad_files + script_files, cmd) - -def tg_compile(flags, model_name): - pythonpath_string = 'PYTHONPATH="${PYTHONPATH}:' + env.Dir("#tinygrad_repo").abspath + '"' - fn = File(f"models/{model_name}").abspath - return lenv.Command( - fn + "_tinygrad.pkl", - [fn + ".onnx"] + tinygrad_files, - f'{pythonpath_string} {flags} python3 {Dir("#tinygrad_repo").abspath}/examples/openpilot/compile3.py {fn}.onnx {fn}_tinygrad.pkl' - ) - -# Compile small models -for model_name in ['driving_vision', 'driving_policy', 'dmonitoring_model']: - flags = { - 'larch64': 'QCOM=1', - 'Darwin': 'CPU=1 IMAGE=0 JIT=2', - }.get(arch, 'LLVM=1 LLVMOPT=1 BEAM=0 IMAGE=0 JIT=2') - tg_compile(flags, model_name) - -# Compile BIG model if USB GPU is available -import subprocess -from tinygrad import Device - -# because tg doesn't support multi-process -devs = subprocess.check_output('python3 -c "from tinygrad import Device; print(list(Device.get_available_devices()))"', shell=True, cwd=env.Dir('#').abspath) -if b"AMD" in devs: - del Device - print("USB GPU detected... building") - flags = "AMD=1 AMD_IFACE=USB AMD_LLVM=1 NOLOCALS=0 IMAGE=0" - bp = tg_compile(flags, "big_driving_policy") - bv = tg_compile(flags, "big_driving_vision") - lenv.SideEffect('lock', [bp, bv]) # tg doesn't support multi-process so build serially -else: - print("USB GPU not detected... skipping") diff --git a/selfdrive/modeld/constants.py b/selfdrive/modeld/constants.py deleted file mode 100644 index 5ca0a86bc8..0000000000 --- a/selfdrive/modeld/constants.py +++ /dev/null @@ -1,90 +0,0 @@ -import numpy as np - -def index_function(idx, max_val=192, max_idx=32): - return (max_val) * ((idx/max_idx)**2) - -class ModelConstants: - # time and distance indices - IDX_N = 33 - T_IDXS = [index_function(idx, max_val=10.0) for idx in range(IDX_N)] - X_IDXS = [index_function(idx, max_val=192.0) for idx in range(IDX_N)] - LEAD_T_IDXS = [0., 2., 4., 6., 8., 10.] - LEAD_T_OFFSETS = [0., 2., 4.] - META_T_IDXS = [2., 4., 6., 8., 10.] - - # model inputs constants - MODEL_FREQ = 20 - HISTORY_FREQ = 5 - HISTORY_LEN_SECONDS = 5 - TEMPORAL_SKIP = MODEL_FREQ // HISTORY_FREQ - FULL_HISTORY_BUFFER_LEN = MODEL_FREQ * HISTORY_LEN_SECONDS - INPUT_HISTORY_BUFFER_LEN = HISTORY_FREQ * HISTORY_LEN_SECONDS - - FEATURE_LEN = 512 - - DESIRE_LEN = 8 - TRAFFIC_CONVENTION_LEN = 2 - LAT_PLANNER_STATE_LEN = 4 - LATERAL_CONTROL_PARAMS_LEN = 2 - PREV_DESIRED_CURV_LEN = 1 - - # model outputs constants - FCW_THRESHOLDS_5MS2 = np.array([.05, .05, .15, .15, .15], dtype=np.float32) - FCW_THRESHOLDS_3MS2 = np.array([.7, .7], dtype=np.float32) - FCW_5MS2_PROBS_WIDTH = 5 - FCW_3MS2_PROBS_WIDTH = 2 - - DISENGAGE_WIDTH = 5 - POSE_WIDTH = 6 - WIDE_FROM_DEVICE_WIDTH = 3 - LEAD_WIDTH = 4 - LANE_LINES_WIDTH = 2 - ROAD_EDGES_WIDTH = 2 - PLAN_WIDTH = 15 - DESIRE_PRED_WIDTH = 8 - LAT_PLANNER_SOLUTION_WIDTH = 4 - DESIRED_CURV_WIDTH = 1 - - NUM_LANE_LINES = 4 - NUM_ROAD_EDGES = 2 - - LEAD_TRAJ_LEN = 6 - DESIRE_PRED_LEN = 4 - - PLAN_MHP_N = 5 - LEAD_MHP_N = 2 - PLAN_MHP_SELECTION = 1 - LEAD_MHP_SELECTION = 3 - - FCW_THRESHOLD_5MS2_HIGH = 0.15 - FCW_THRESHOLD_5MS2_LOW = 0.05 - FCW_THRESHOLD_3MS2 = 0.7 - - CONFIDENCE_BUFFER_LEN = 5 - RYG_GREEN = 0.01165 - RYG_YELLOW = 0.06157 - - POLY_PATH_DEGREE = 4 - -# model outputs slices -class Plan: - POSITION = slice(0, 3) - VELOCITY = slice(3, 6) - ACCELERATION = slice(6, 9) - T_FROM_CURRENT_EULER = slice(9, 12) - ORIENTATION_RATE = slice(12, 15) - -class Meta: - ENGAGED = slice(0, 1) - # next 2, 4, 6, 8, 10 seconds - GAS_DISENGAGE = slice(1, 31, 6) - BRAKE_DISENGAGE = slice(2, 31, 6) - STEER_OVERRIDE = slice(3, 31, 6) - HARD_BRAKE_3 = slice(4, 31, 6) - HARD_BRAKE_4 = slice(5, 31, 6) - HARD_BRAKE_5 = slice(6, 31, 6) - # next 0, 2, 4, 6, 8, 10 seconds - GAS_PRESS = slice(31, 55, 4) - BRAKE_PRESS = slice(32, 55, 4) - LEFT_BLINKER = slice(33, 55, 4) - RIGHT_BLINKER = slice(34, 55, 4) diff --git a/selfdrive/modeld/dmonitoringmodeld.py b/selfdrive/modeld/dmonitoringmodeld.py deleted file mode 100755 index 2a3df3f652..0000000000 --- a/selfdrive/modeld/dmonitoringmodeld.py +++ /dev/null @@ -1,186 +0,0 @@ -#!/usr/bin/env python3 -import os -from openpilot.system.hardware import TICI -from tinygrad.tensor import Tensor -from tinygrad.dtype import dtypes -if TICI: - from openpilot.selfdrive.modeld.runners.tinygrad_helpers import qcom_tensor_from_opencl_address - os.environ['QCOM'] = '1' -else: - os.environ['LLVM'] = '1' -import math -import time -import pickle -import ctypes -import numpy as np -from pathlib import Path -from setproctitle import setproctitle - -from cereal import messaging -from cereal.messaging import PubMaster, SubMaster -from msgq.visionipc import VisionIpcClient, VisionStreamType, VisionBuf -from openpilot.common.swaglog import cloudlog -from openpilot.common.realtime import config_realtime_process -from openpilot.common.transformations.model import dmonitoringmodel_intrinsics, DM_INPUT_SIZE -from openpilot.common.transformations.camera import _ar_ox_fisheye, _os_fisheye -from openpilot.selfdrive.modeld.models.commonmodel_pyx import CLContext, MonitoringModelFrame -from openpilot.selfdrive.modeld.parse_model_outputs import sigmoid -from openpilot.system import sentry - -MODEL_WIDTH, MODEL_HEIGHT = DM_INPUT_SIZE -CALIB_LEN = 3 -FEATURE_LEN = 512 -OUTPUT_SIZE = 84 + FEATURE_LEN - -PROCESS_NAME = "selfdrive.modeld.dmonitoringmodeld" -SEND_RAW_PRED = os.getenv('SEND_RAW_PRED') -MODEL_PKL_PATH = Path(__file__).parent / 'models/dmonitoring_model_tinygrad.pkl' - - -class DriverStateResult(ctypes.Structure): - _fields_ = [ - ("face_orientation", ctypes.c_float*3), - ("face_position", ctypes.c_float*3), - ("face_orientation_std", ctypes.c_float*3), - ("face_position_std", ctypes.c_float*3), - ("face_prob", ctypes.c_float), - ("_unused_a", ctypes.c_float*8), - ("left_eye_prob", ctypes.c_float), - ("_unused_b", ctypes.c_float*8), - ("right_eye_prob", ctypes.c_float), - ("left_blink_prob", ctypes.c_float), - ("right_blink_prob", ctypes.c_float), - ("sunglasses_prob", ctypes.c_float), - ("occluded_prob", ctypes.c_float), - ("ready_prob", ctypes.c_float*4), - ("not_ready_prob", ctypes.c_float*2)] - - -class DMonitoringModelResult(ctypes.Structure): - _fields_ = [ - ("driver_state_lhd", DriverStateResult), - ("driver_state_rhd", DriverStateResult), - ("poor_vision_prob", ctypes.c_float), - ("wheel_on_right_prob", ctypes.c_float), - ("features", ctypes.c_float*FEATURE_LEN)] - - -class ModelState: - inputs: dict[str, np.ndarray] - output: np.ndarray - - def __init__(self, cl_ctx): - assert ctypes.sizeof(DMonitoringModelResult) == OUTPUT_SIZE * ctypes.sizeof(ctypes.c_float) - - self.frame = MonitoringModelFrame(cl_ctx) - self.numpy_inputs = { - 'calib': np.zeros((1, CALIB_LEN), dtype=np.float32), - } - - self.tensor_inputs = {k: Tensor(v, device='NPY').realize() for k,v in self.numpy_inputs.items()} - with open(MODEL_PKL_PATH, "rb") as f: - self.model_run = pickle.load(f) - - def run(self, buf: VisionBuf, calib: np.ndarray, transform: np.ndarray) -> tuple[np.ndarray, float]: - self.numpy_inputs['calib'][0,:] = calib - - t1 = time.perf_counter() - - input_img_cl = self.frame.prepare(buf, transform.flatten()) - if TICI: - # The imgs tensors are backed by opencl memory, only need init once - if 'input_img' not in self.tensor_inputs: - self.tensor_inputs['input_img'] = qcom_tensor_from_opencl_address(input_img_cl.mem_address, (1, MODEL_WIDTH*MODEL_HEIGHT), dtype=dtypes.uint8) - else: - self.tensor_inputs['input_img'] = Tensor(self.frame.buffer_from_cl(input_img_cl).reshape((1, MODEL_WIDTH*MODEL_HEIGHT)), dtype=dtypes.uint8).realize() - - - output = self.model_run(**self.tensor_inputs).numpy().flatten() - - t2 = time.perf_counter() - return output, t2 - t1 - - -def fill_driver_state(msg, ds_result: DriverStateResult): - msg.faceOrientation = list(ds_result.face_orientation) - msg.faceOrientationStd = [math.exp(x) for x in ds_result.face_orientation_std] - msg.facePosition = list(ds_result.face_position[:2]) - msg.facePositionStd = [math.exp(x) for x in ds_result.face_position_std[:2]] - msg.faceProb = float(sigmoid(ds_result.face_prob)) - msg.leftEyeProb = float(sigmoid(ds_result.left_eye_prob)) - msg.rightEyeProb = float(sigmoid(ds_result.right_eye_prob)) - msg.leftBlinkProb = float(sigmoid(ds_result.left_blink_prob)) - msg.rightBlinkProb = float(sigmoid(ds_result.right_blink_prob)) - msg.sunglassesProb = float(sigmoid(ds_result.sunglasses_prob)) - msg.occludedProb = float(sigmoid(ds_result.occluded_prob)) - msg.readyProb = [float(sigmoid(x)) for x in ds_result.ready_prob] - msg.notReadyProb = [float(sigmoid(x)) for x in ds_result.not_ready_prob] - - -def get_driverstate_packet(model_output: np.ndarray, frame_id: int, location_ts: int, execution_time: float, gpu_execution_time: float): - model_result = ctypes.cast(model_output.ctypes.data, ctypes.POINTER(DMonitoringModelResult)).contents - msg = messaging.new_message('driverStateV2', valid=True) - ds = msg.driverStateV2 - ds.frameId = frame_id - ds.modelExecutionTime = execution_time - ds.gpuExecutionTime = gpu_execution_time - ds.poorVisionProb = float(sigmoid(model_result.poor_vision_prob)) - ds.wheelOnRightProb = float(sigmoid(model_result.wheel_on_right_prob)) - ds.rawPredictions = model_output.tobytes() if SEND_RAW_PRED else b'' - fill_driver_state(ds.leftDriverData, model_result.driver_state_lhd) - fill_driver_state(ds.rightDriverData, model_result.driver_state_rhd) - return msg - - -def main(): - setproctitle(PROCESS_NAME) - config_realtime_process(7, 5) - - sentry.set_tag("daemon", PROCESS_NAME) - cloudlog.bind(daemon=PROCESS_NAME) - - cl_context = CLContext() - model = ModelState(cl_context) - cloudlog.warning("models loaded, dmonitoringmodeld starting") - - cloudlog.warning("connecting to driver stream") - vipc_client = VisionIpcClient("camerad", VisionStreamType.VISION_STREAM_DRIVER, True, cl_context) - while not vipc_client.connect(False): - time.sleep(0.1) - assert vipc_client.is_connected() - cloudlog.warning(f"connected with buffer size: {vipc_client.buffer_len}") - - sm = SubMaster(["liveCalibration"]) - pm = PubMaster(["driverStateV2"]) - - calib = np.zeros(CALIB_LEN, dtype=np.float32) - model_transform = None - - while True: - buf = vipc_client.recv() - if buf is None: - continue - - if model_transform is None: - cam = _os_fisheye if buf.width == _os_fisheye.width else _ar_ox_fisheye - model_transform = np.linalg.inv(np.dot(dmonitoringmodel_intrinsics, np.linalg.inv(cam.intrinsics))).astype(np.float32) - - sm.update(0) - if sm.updated["liveCalibration"]: - calib[:] = np.array(sm["liveCalibration"].rpyCalib) - - t1 = time.perf_counter() - model_output, gpu_execution_time = model.run(buf, calib, model_transform) - t2 = time.perf_counter() - - pm.send("driverStateV2", get_driverstate_packet(model_output, vipc_client.frame_id, vipc_client.timestamp_sof, t2 - t1, gpu_execution_time)) - - -if __name__ == "__main__": - try: - main() - except KeyboardInterrupt: - cloudlog.warning(f"child {PROCESS_NAME} got SIGINT") - except Exception: - sentry.capture_exception() - raise diff --git a/selfdrive/modeld/fill_model_msg.py b/selfdrive/modeld/fill_model_msg.py deleted file mode 100644 index a91c6395c7..0000000000 --- a/selfdrive/modeld/fill_model_msg.py +++ /dev/null @@ -1,200 +0,0 @@ -import os -import capnp -import numpy as np -from cereal import log -from openpilot.selfdrive.modeld.constants import ModelConstants, Plan, Meta - -SEND_RAW_PRED = os.getenv('SEND_RAW_PRED') - -ConfidenceClass = log.ModelDataV2.ConfidenceClass - - -class PublishState: - def __init__(self): - self.disengage_buffer = np.zeros(ModelConstants.CONFIDENCE_BUFFER_LEN*ModelConstants.DISENGAGE_WIDTH, dtype=np.float32) - self.prev_brake_5ms2_probs = np.zeros(ModelConstants.FCW_5MS2_PROBS_WIDTH, dtype=np.float32) - self.prev_brake_3ms2_probs = np.zeros(ModelConstants.FCW_3MS2_PROBS_WIDTH, dtype=np.float32) - -def fill_xyzt(builder, t, x, y, z, x_std=None, y_std=None, z_std=None): - builder.t = t - builder.x = x.tolist() - builder.y = y.tolist() - builder.z = z.tolist() - if x_std is not None: - builder.xStd = x_std.tolist() - if y_std is not None: - builder.yStd = y_std.tolist() - if z_std is not None: - builder.zStd = z_std.tolist() - -def fill_xyvat(builder, t, x, y, v, a, x_std=None, y_std=None, v_std=None, a_std=None): - builder.t = t - builder.x = x.tolist() - builder.y = y.tolist() - builder.v = v.tolist() - builder.a = a.tolist() - if x_std is not None: - builder.xStd = x_std.tolist() - if y_std is not None: - builder.yStd = y_std.tolist() - if v_std is not None: - builder.vStd = v_std.tolist() - if a_std is not None: - builder.aStd = a_std.tolist() - -def fill_xyz_poly(builder, degree, x, y, z): - xyz = np.stack([x, y, z], axis=1) - coeffs = np.polynomial.polynomial.polyfit(ModelConstants.T_IDXS, xyz, deg=degree) - builder.xCoefficients = coeffs[:, 0].tolist() - builder.yCoefficients = coeffs[:, 1].tolist() - builder.zCoefficients = coeffs[:, 2].tolist() - -def fill_lane_line_meta(builder, lane_lines, lane_line_probs): - builder.leftY = lane_lines[1].y[0] - builder.leftProb = lane_line_probs[1] - builder.rightY = lane_lines[2].y[0] - builder.rightProb = lane_line_probs[2] - -def fill_model_msg(base_msg: capnp._DynamicStructBuilder, extended_msg: capnp._DynamicStructBuilder, - net_output_data: dict[str, np.ndarray], action: log.ModelDataV2.Action, - publish_state: PublishState, vipc_frame_id: int, vipc_frame_id_extra: int, - frame_id: int, frame_drop: float, timestamp_eof: int, model_execution_time: float, - valid: bool) -> None: - frame_age = frame_id - vipc_frame_id if frame_id > vipc_frame_id else 0 - frame_drop_perc = frame_drop * 100 - extended_msg.valid = valid - base_msg.valid = valid - - driving_model_data = base_msg.drivingModelData - - driving_model_data.frameId = vipc_frame_id - driving_model_data.frameIdExtra = vipc_frame_id_extra - driving_model_data.frameDropPerc = frame_drop_perc - driving_model_data.modelExecutionTime = model_execution_time - - driving_model_data.action = action - - modelV2 = extended_msg.modelV2 - modelV2.frameId = vipc_frame_id - modelV2.frameIdExtra = vipc_frame_id_extra - modelV2.frameAge = frame_age - modelV2.frameDropPerc = frame_drop_perc - modelV2.timestampEof = timestamp_eof - modelV2.modelExecutionTime = model_execution_time - - # plan - fill_xyzt(modelV2.position, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.POSITION].T, *net_output_data['plan_stds'][0,:,Plan.POSITION].T) - fill_xyzt(modelV2.velocity, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.VELOCITY].T) - fill_xyzt(modelV2.acceleration, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.ACCELERATION].T) - fill_xyzt(modelV2.orientation, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.T_FROM_CURRENT_EULER].T) - fill_xyzt(modelV2.orientationRate, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.ORIENTATION_RATE].T) - - # temporal pose - temporal_pose = modelV2.temporalPose - temporal_pose.trans = net_output_data['sim_pose'][0,:ModelConstants.POSE_WIDTH//2].tolist() - temporal_pose.transStd = net_output_data['sim_pose_stds'][0,:ModelConstants.POSE_WIDTH//2].tolist() - temporal_pose.rot = net_output_data['sim_pose'][0,ModelConstants.POSE_WIDTH//2:].tolist() - temporal_pose.rotStd = net_output_data['sim_pose_stds'][0,ModelConstants.POSE_WIDTH//2:].tolist() - - # poly path - fill_xyz_poly(driving_model_data.path, ModelConstants.POLY_PATH_DEGREE, *net_output_data['plan'][0,:,Plan.POSITION].T) - - # action - modelV2.action = action - - # times at X_IDXS of edges and lines aren't used - LINE_T_IDXS: list[float] = [] - - # lane lines - modelV2.init('laneLines', 4) - for i in range(4): - lane_line = modelV2.laneLines[i] - fill_xyzt(lane_line, LINE_T_IDXS, np.array(ModelConstants.X_IDXS), net_output_data['lane_lines'][0,i,:,0], net_output_data['lane_lines'][0,i,:,1]) - modelV2.laneLineStds = net_output_data['lane_lines_stds'][0,:,0,0].tolist() - modelV2.laneLineProbs = net_output_data['lane_lines_prob'][0,1::2].tolist() - - fill_lane_line_meta(driving_model_data.laneLineMeta, modelV2.laneLines, modelV2.laneLineProbs) - - # road edges - modelV2.init('roadEdges', 2) - for i in range(2): - road_edge = modelV2.roadEdges[i] - fill_xyzt(road_edge, LINE_T_IDXS, np.array(ModelConstants.X_IDXS), net_output_data['road_edges'][0,i,:,0], net_output_data['road_edges'][0,i,:,1]) - modelV2.roadEdgeStds = net_output_data['road_edges_stds'][0,:,0,0].tolist() - - # leads - modelV2.init('leadsV3', 3) - for i in range(3): - lead = modelV2.leadsV3[i] - fill_xyvat(lead, ModelConstants.LEAD_T_IDXS, *net_output_data['lead'][0,i].T, *net_output_data['lead_stds'][0,i].T) - lead.prob = net_output_data['lead_prob'][0,i].tolist() - lead.probTime = ModelConstants.LEAD_T_OFFSETS[i] - - # meta - meta = modelV2.meta - meta.desireState = net_output_data['desire_state'][0].reshape(-1).tolist() - meta.desirePrediction = net_output_data['desire_pred'][0].reshape(-1).tolist() - meta.engagedProb = net_output_data['meta'][0,Meta.ENGAGED].item() - meta.init('disengagePredictions') - disengage_predictions = meta.disengagePredictions - disengage_predictions.t = ModelConstants.META_T_IDXS - disengage_predictions.brakeDisengageProbs = net_output_data['meta'][0,Meta.BRAKE_DISENGAGE].tolist() - disengage_predictions.gasDisengageProbs = net_output_data['meta'][0,Meta.GAS_DISENGAGE].tolist() - disengage_predictions.steerOverrideProbs = net_output_data['meta'][0,Meta.STEER_OVERRIDE].tolist() - disengage_predictions.brake3MetersPerSecondSquaredProbs = net_output_data['meta'][0,Meta.HARD_BRAKE_3].tolist() - disengage_predictions.brake4MetersPerSecondSquaredProbs = net_output_data['meta'][0,Meta.HARD_BRAKE_4].tolist() - disengage_predictions.brake5MetersPerSecondSquaredProbs = net_output_data['meta'][0,Meta.HARD_BRAKE_5].tolist() - disengage_predictions.gasPressProbs = net_output_data['meta'][0,Meta.GAS_PRESS].tolist() - disengage_predictions.brakePressProbs = net_output_data['meta'][0,Meta.BRAKE_PRESS].tolist() - - publish_state.prev_brake_5ms2_probs[:-1] = publish_state.prev_brake_5ms2_probs[1:] - publish_state.prev_brake_5ms2_probs[-1] = net_output_data['meta'][0,Meta.HARD_BRAKE_5][0] - publish_state.prev_brake_3ms2_probs[:-1] = publish_state.prev_brake_3ms2_probs[1:] - publish_state.prev_brake_3ms2_probs[-1] = net_output_data['meta'][0,Meta.HARD_BRAKE_3][0] - hard_brake_predicted = (publish_state.prev_brake_5ms2_probs > ModelConstants.FCW_THRESHOLDS_5MS2).all() and \ - (publish_state.prev_brake_3ms2_probs > ModelConstants.FCW_THRESHOLDS_3MS2).all() - meta.hardBrakePredicted = hard_brake_predicted.item() - - # confidence - if vipc_frame_id % (2*ModelConstants.MODEL_FREQ) == 0: - # any disengage prob - brake_disengage_probs = net_output_data['meta'][0,Meta.BRAKE_DISENGAGE] - gas_disengage_probs = net_output_data['meta'][0,Meta.GAS_DISENGAGE] - steer_override_probs = net_output_data['meta'][0,Meta.STEER_OVERRIDE] - any_disengage_probs = 1-((1-brake_disengage_probs)*(1-gas_disengage_probs)*(1-steer_override_probs)) - # independent disengage prob for each 2s slice - ind_disengage_probs = np.r_[any_disengage_probs[0], np.diff(any_disengage_probs) / (1 - any_disengage_probs[:-1])] - # rolling buf for 2, 4, 6, 8, 10s - publish_state.disengage_buffer[:-ModelConstants.DISENGAGE_WIDTH] = publish_state.disengage_buffer[ModelConstants.DISENGAGE_WIDTH:] - publish_state.disengage_buffer[-ModelConstants.DISENGAGE_WIDTH:] = ind_disengage_probs - - score = 0. - for i in range(ModelConstants.DISENGAGE_WIDTH): - score += publish_state.disengage_buffer[i*ModelConstants.DISENGAGE_WIDTH+ModelConstants.DISENGAGE_WIDTH-1-i].item() / ModelConstants.DISENGAGE_WIDTH - if score < ModelConstants.RYG_GREEN: - modelV2.confidence = ConfidenceClass.green - elif score < ModelConstants.RYG_YELLOW: - modelV2.confidence = ConfidenceClass.yellow - else: - modelV2.confidence = ConfidenceClass.red - - # raw prediction if enabled - if SEND_RAW_PRED: - modelV2.rawPredictions = net_output_data['raw_pred'].tobytes() - -def fill_pose_msg(msg: capnp._DynamicStructBuilder, net_output_data: dict[str, np.ndarray], - vipc_frame_id: int, vipc_dropped_frames: int, timestamp_eof: int, live_calib_seen: bool) -> None: - msg.valid = live_calib_seen & (vipc_dropped_frames < 1) - cameraOdometry = msg.cameraOdometry - - cameraOdometry.frameId = vipc_frame_id - cameraOdometry.timestampEof = timestamp_eof - - cameraOdometry.trans = net_output_data['pose'][0,:3].tolist() - cameraOdometry.rot = net_output_data['pose'][0,3:].tolist() - cameraOdometry.wideFromDeviceEuler = net_output_data['wide_from_device_euler'][0,:].tolist() - cameraOdometry.roadTransformTrans = net_output_data['road_transform'][0,:3].tolist() - cameraOdometry.transStd = net_output_data['pose_stds'][0,:3].tolist() - cameraOdometry.rotStd = net_output_data['pose_stds'][0,3:].tolist() - cameraOdometry.wideFromDeviceEulerStd = net_output_data['wide_from_device_euler_stds'][0,:].tolist() - cameraOdometry.roadTransformTransStd = net_output_data['road_transform_stds'][0,:3].tolist() diff --git a/selfdrive/modeld/get_model_metadata.py b/selfdrive/modeld/get_model_metadata.py deleted file mode 100755 index 2001d23d75..0000000000 --- a/selfdrive/modeld/get_model_metadata.py +++ /dev/null @@ -1,37 +0,0 @@ -#!/usr/bin/env python3 -import sys -import pathlib -import onnx -import codecs -import pickle -from typing import Any - -def get_name_and_shape(value_info:onnx.ValueInfoProto) -> tuple[str, tuple[int,...]]: - shape = tuple([int(dim.dim_value) for dim in value_info.type.tensor_type.shape.dim]) - name = value_info.name - return name, shape - -def get_metadata_value_by_name(model:onnx.ModelProto, name:str) -> str | Any: - for prop in model.metadata_props: - if prop.key == name: - return prop.value - return None - -if __name__ == "__main__": - model_path = pathlib.Path(sys.argv[1]) - model = onnx.load(str(model_path)) - output_slices = get_metadata_value_by_name(model, 'output_slices') - assert output_slices is not None, 'output_slices not found in metadata' - - metadata = { - 'model_checkpoint': get_metadata_value_by_name(model, 'model_checkpoint'), - 'output_slices': pickle.loads(codecs.decode(output_slices.encode(), "base64")), - 'input_shapes': dict([get_name_and_shape(x) for x in model.graph.input]), - 'output_shapes': dict([get_name_and_shape(x) for x in model.graph.output]) - } - - metadata_path = model_path.parent / (model_path.stem + '_metadata.pkl') - with open(metadata_path, 'wb') as f: - pickle.dump(metadata, f) - - print(f'saved metadata to {metadata_path}') diff --git a/selfdrive/modeld/modeld.py b/selfdrive/modeld/modeld.py deleted file mode 100755 index ac88dfbb5f..0000000000 --- a/selfdrive/modeld/modeld.py +++ /dev/null @@ -1,380 +0,0 @@ -#!/usr/bin/env python3 -import os -from openpilot.system.hardware import TICI -USBGPU = "USBGPU" in os.environ -if USBGPU: - os.environ['AMD'] = '1' - os.environ['AMD_IFACE'] = 'USB' -elif TICI: - from openpilot.selfdrive.modeld.runners.tinygrad_helpers import qcom_tensor_from_opencl_address - os.environ['QCOM'] = '1' -else: - os.environ['LLVM'] = '1' - os.environ['JIT'] = '2' -from tinygrad.tensor import Tensor -from tinygrad.dtype import dtypes -import time -import pickle -import numpy as np -import cereal.messaging as messaging -from cereal import car, log -from pathlib import Path -from setproctitle import setproctitle -from cereal.messaging import PubMaster, SubMaster -from msgq.visionipc import VisionIpcClient, VisionStreamType, VisionBuf -from opendbc.car.car_helpers import get_demo_car_params -from openpilot.common.swaglog import cloudlog -from openpilot.common.params import Params -from openpilot.common.filter_simple import FirstOrderFilter -from openpilot.common.realtime import config_realtime_process, DT_MDL -from openpilot.common.transformations.camera import DEVICE_CAMERAS -from openpilot.common.transformations.model import get_warp_matrix -from openpilot.system import sentry -from openpilot.selfdrive.controls.lib.desire_helper import DesireHelper -from openpilot.selfdrive.controls.lib.drive_helpers import get_accel_from_plan, smooth_value -from openpilot.selfdrive.modeld.parse_model_outputs import Parser -from openpilot.selfdrive.modeld.fill_model_msg import fill_model_msg, fill_pose_msg, PublishState -from openpilot.selfdrive.modeld.constants import ModelConstants, Plan -from openpilot.selfdrive.modeld.models.commonmodel_pyx import DrivingModelFrame, CLContext - - -PROCESS_NAME = "selfdrive.modeld.modeld" -SEND_RAW_PRED = os.getenv('SEND_RAW_PRED') - -VISION_PKL_PATH = Path(__file__).parent / 'models/driving_vision_tinygrad.pkl' -POLICY_PKL_PATH = Path(__file__).parent / 'models/driving_policy_tinygrad.pkl' -VISION_METADATA_PATH = Path(__file__).parent / 'models/driving_vision_metadata.pkl' -POLICY_METADATA_PATH = Path(__file__).parent / 'models/driving_policy_metadata.pkl' - -LAT_SMOOTH_SECONDS = 0.0 -LONG_SMOOTH_SECONDS = 0.0 -MIN_LAT_CONTROL_SPEED = 0.3 - - -def get_action_from_model(model_output: dict[str, np.ndarray], prev_action: log.ModelDataV2.Action, - lat_action_t: float, long_action_t: float, v_ego: float) -> log.ModelDataV2.Action: - plan = model_output['plan'][0] - desired_accel, should_stop = get_accel_from_plan(plan[:,Plan.VELOCITY][:,0], - plan[:,Plan.ACCELERATION][:,0], - ModelConstants.T_IDXS, - action_t=long_action_t) - desired_accel = smooth_value(desired_accel, prev_action.desiredAcceleration, LONG_SMOOTH_SECONDS) - - desired_curvature = model_output['desired_curvature'][0, 0] - if v_ego > MIN_LAT_CONTROL_SPEED: - desired_curvature = smooth_value(desired_curvature, prev_action.desiredCurvature, LAT_SMOOTH_SECONDS) - else: - desired_curvature = prev_action.desiredCurvature - - return log.ModelDataV2.Action(desiredCurvature=float(desired_curvature), - desiredAcceleration=float(desired_accel), - shouldStop=bool(should_stop)) - -class FrameMeta: - frame_id: int = 0 - timestamp_sof: int = 0 - timestamp_eof: int = 0 - - def __init__(self, vipc=None): - if vipc is not None: - self.frame_id, self.timestamp_sof, self.timestamp_eof = vipc.frame_id, vipc.timestamp_sof, vipc.timestamp_eof - -class ModelState: - frames: dict[str, DrivingModelFrame] - inputs: dict[str, np.ndarray] - output: np.ndarray - prev_desire: np.ndarray # for tracking the rising edge of the pulse - - def __init__(self, context: CLContext): - with open(VISION_METADATA_PATH, 'rb') as f: - vision_metadata = pickle.load(f) - self.vision_input_shapes = vision_metadata['input_shapes'] - self.vision_input_names = list(self.vision_input_shapes.keys()) - self.vision_output_slices = vision_metadata['output_slices'] - vision_output_size = vision_metadata['output_shapes']['outputs'][1] - - with open(POLICY_METADATA_PATH, 'rb') as f: - policy_metadata = pickle.load(f) - self.policy_input_shapes = policy_metadata['input_shapes'] - self.policy_output_slices = policy_metadata['output_slices'] - policy_output_size = policy_metadata['output_shapes']['outputs'][1] - - self.frames = {name: DrivingModelFrame(context, ModelConstants.TEMPORAL_SKIP) for name in self.vision_input_names} - self.prev_desire = np.zeros(ModelConstants.DESIRE_LEN, dtype=np.float32) - - self.full_features_buffer = np.zeros((1, ModelConstants.FULL_HISTORY_BUFFER_LEN, ModelConstants.FEATURE_LEN), dtype=np.float32) - self.full_desire = np.zeros((1, ModelConstants.FULL_HISTORY_BUFFER_LEN, ModelConstants.DESIRE_LEN), dtype=np.float32) - self.full_prev_desired_curv = np.zeros((1, ModelConstants.FULL_HISTORY_BUFFER_LEN, ModelConstants.PREV_DESIRED_CURV_LEN), dtype=np.float32) - self.temporal_idxs = slice(-1-(ModelConstants.TEMPORAL_SKIP*(ModelConstants.INPUT_HISTORY_BUFFER_LEN-1)), None, ModelConstants.TEMPORAL_SKIP) - - # policy inputs - self.numpy_inputs = { - 'desire': np.zeros((1, ModelConstants.INPUT_HISTORY_BUFFER_LEN, ModelConstants.DESIRE_LEN), dtype=np.float32), - 'traffic_convention': np.zeros((1, ModelConstants.TRAFFIC_CONVENTION_LEN), dtype=np.float32), - 'lateral_control_params': np.zeros((1, ModelConstants.LATERAL_CONTROL_PARAMS_LEN), dtype=np.float32), - 'prev_desired_curv': np.zeros((1, ModelConstants.INPUT_HISTORY_BUFFER_LEN, ModelConstants.PREV_DESIRED_CURV_LEN), dtype=np.float32), - 'features_buffer': np.zeros((1, ModelConstants.INPUT_HISTORY_BUFFER_LEN, ModelConstants.FEATURE_LEN), dtype=np.float32), - } - - # img buffers are managed in openCL transform code - self.vision_inputs: dict[str, Tensor] = {} - self.vision_output = np.zeros(vision_output_size, dtype=np.float32) - self.policy_inputs = {k: Tensor(v, device='NPY').realize() for k,v in self.numpy_inputs.items()} - self.policy_output = np.zeros(policy_output_size, dtype=np.float32) - self.parser = Parser() - - with open(VISION_PKL_PATH, "rb") as f: - self.vision_run = pickle.load(f) - - with open(POLICY_PKL_PATH, "rb") as f: - self.policy_run = pickle.load(f) - - def slice_outputs(self, model_outputs: np.ndarray, output_slices: dict[str, slice]) -> dict[str, np.ndarray]: - parsed_model_outputs = {k: model_outputs[np.newaxis, v] for k,v in output_slices.items()} - return parsed_model_outputs - - def run(self, bufs: dict[str, VisionBuf], transforms: dict[str, np.ndarray], - inputs: dict[str, np.ndarray], prepare_only: bool) -> dict[str, np.ndarray] | None: - # Model decides when action is completed, so desire input is just a pulse triggered on rising edge - inputs['desire'][0] = 0 - new_desire = np.where(inputs['desire'] - self.prev_desire > .99, inputs['desire'], 0) - self.prev_desire[:] = inputs['desire'] - - self.full_desire[0,:-1] = self.full_desire[0,1:] - self.full_desire[0,-1] = new_desire - self.numpy_inputs['desire'][:] = self.full_desire.reshape((1,ModelConstants.INPUT_HISTORY_BUFFER_LEN,ModelConstants.TEMPORAL_SKIP,-1)).max(axis=2) - - self.numpy_inputs['traffic_convention'][:] = inputs['traffic_convention'] - self.numpy_inputs['lateral_control_params'][:] = inputs['lateral_control_params'] - imgs_cl = {name: self.frames[name].prepare(bufs[name], transforms[name].flatten()) for name in self.vision_input_names} - - if TICI and not USBGPU: - # The imgs tensors are backed by opencl memory, only need init once - for key in imgs_cl: - if key not in self.vision_inputs: - self.vision_inputs[key] = qcom_tensor_from_opencl_address(imgs_cl[key].mem_address, self.vision_input_shapes[key], dtype=dtypes.uint8) - else: - for key in imgs_cl: - frame_input = self.frames[key].buffer_from_cl(imgs_cl[key]).reshape(self.vision_input_shapes[key]) - self.vision_inputs[key] = Tensor(frame_input, dtype=dtypes.uint8).realize() - - if prepare_only: - return None - - self.vision_output = self.vision_run(**self.vision_inputs).numpy().flatten() - vision_outputs_dict = self.parser.parse_vision_outputs(self.slice_outputs(self.vision_output, self.vision_output_slices)) - - self.full_features_buffer[0,:-1] = self.full_features_buffer[0,1:] - self.full_features_buffer[0,-1] = vision_outputs_dict['hidden_state'][0, :] - self.numpy_inputs['features_buffer'][:] = self.full_features_buffer[0, self.temporal_idxs] - - self.policy_output = self.policy_run(**self.policy_inputs).numpy().flatten() - policy_outputs_dict = self.parser.parse_policy_outputs(self.slice_outputs(self.policy_output, self.policy_output_slices)) - - # TODO model only uses last value now - self.full_prev_desired_curv[0,:-1] = self.full_prev_desired_curv[0,1:] - self.full_prev_desired_curv[0,-1,:] = policy_outputs_dict['desired_curvature'][0, :] - self.numpy_inputs['prev_desired_curv'][:] = self.full_prev_desired_curv[0, self.temporal_idxs] - - combined_outputs_dict = {**vision_outputs_dict, **policy_outputs_dict} - if SEND_RAW_PRED: - combined_outputs_dict['raw_pred'] = np.concatenate([self.vision_output.copy(), self.policy_output.copy()]) - - return combined_outputs_dict - - -def main(demo=False): - cloudlog.warning("modeld init") - - sentry.set_tag("daemon", PROCESS_NAME) - cloudlog.bind(daemon=PROCESS_NAME) - setproctitle(PROCESS_NAME) - if not USBGPU: - # USB GPU currently saturates a core so can't do this yet, - # also need to move the aux USB interrupts for good timings - config_realtime_process(7, 54) - - st = time.monotonic() - cloudlog.warning("setting up CL context") - cl_context = CLContext() - cloudlog.warning("CL context ready; loading model") - model = ModelState(cl_context) - cloudlog.warning(f"models loaded in {time.monotonic() - st:.1f}s, modeld starting") - - # visionipc clients - while True: - available_streams = VisionIpcClient.available_streams("camerad", block=False) - if available_streams: - use_extra_client = VisionStreamType.VISION_STREAM_WIDE_ROAD in available_streams and VisionStreamType.VISION_STREAM_ROAD in available_streams - main_wide_camera = VisionStreamType.VISION_STREAM_ROAD not in available_streams - break - time.sleep(.1) - - vipc_client_main_stream = VisionStreamType.VISION_STREAM_WIDE_ROAD if main_wide_camera else VisionStreamType.VISION_STREAM_ROAD - vipc_client_main = VisionIpcClient("camerad", vipc_client_main_stream, True, cl_context) - vipc_client_extra = VisionIpcClient("camerad", VisionStreamType.VISION_STREAM_WIDE_ROAD, False, cl_context) - cloudlog.warning(f"vision stream set up, main_wide_camera: {main_wide_camera}, use_extra_client: {use_extra_client}") - - while not vipc_client_main.connect(False): - time.sleep(0.1) - while use_extra_client and not vipc_client_extra.connect(False): - time.sleep(0.1) - - cloudlog.warning(f"connected main cam with buffer size: {vipc_client_main.buffer_len} ({vipc_client_main.width} x {vipc_client_main.height})") - if use_extra_client: - cloudlog.warning(f"connected extra cam with buffer size: {vipc_client_extra.buffer_len} ({vipc_client_extra.width} x {vipc_client_extra.height})") - - # messaging - pm = PubMaster(["modelV2", "drivingModelData", "cameraOdometry"]) - sm = SubMaster(["deviceState", "carState", "roadCameraState", "liveCalibration", "driverMonitoringState", "carControl", "liveDelay"]) - - publish_state = PublishState() - params = Params() - - # setup filter to track dropped frames - frame_dropped_filter = FirstOrderFilter(0., 10., 1. / ModelConstants.MODEL_FREQ) - frame_id = 0 - last_vipc_frame_id = 0 - run_count = 0 - - model_transform_main = np.zeros((3, 3), dtype=np.float32) - model_transform_extra = np.zeros((3, 3), dtype=np.float32) - live_calib_seen = False - buf_main, buf_extra = None, None - meta_main = FrameMeta() - meta_extra = FrameMeta() - - - if demo: - CP = get_demo_car_params() - else: - CP = messaging.log_from_bytes(params.get("CarParams", block=True), car.CarParams) - cloudlog.info("modeld got CarParams: %s", CP.brand) - - # TODO this needs more thought, use .2s extra for now to estimate other delays - # TODO Move smooth seconds to action function - long_delay = CP.longitudinalActuatorDelay + LONG_SMOOTH_SECONDS - prev_action = log.ModelDataV2.Action() - - DH = DesireHelper() - - while True: - # Keep receiving frames until we are at least 1 frame ahead of previous extra frame - while meta_main.timestamp_sof < meta_extra.timestamp_sof + 25000000: - buf_main = vipc_client_main.recv() - meta_main = FrameMeta(vipc_client_main) - if buf_main is None: - break - - if buf_main is None: - cloudlog.debug("vipc_client_main no frame") - continue - - if use_extra_client: - # Keep receiving extra frames until frame id matches main camera - while True: - buf_extra = vipc_client_extra.recv() - meta_extra = FrameMeta(vipc_client_extra) - if buf_extra is None or meta_main.timestamp_sof < meta_extra.timestamp_sof + 25000000: - break - - if buf_extra is None: - cloudlog.debug("vipc_client_extra no frame") - continue - - if abs(meta_main.timestamp_sof - meta_extra.timestamp_sof) > 10000000: - cloudlog.error(f"frames out of sync! main: {meta_main.frame_id} ({meta_main.timestamp_sof / 1e9:.5f}),\ - extra: {meta_extra.frame_id} ({meta_extra.timestamp_sof / 1e9:.5f})") - - else: - # Use single camera - buf_extra = buf_main - meta_extra = meta_main - - sm.update(0) - desire = DH.desire - is_rhd = sm["driverMonitoringState"].isRHD - frame_id = sm["roadCameraState"].frameId - v_ego = max(sm["carState"].vEgo, 0.) - lat_delay = sm["liveDelay"].lateralDelay + LAT_SMOOTH_SECONDS - lateral_control_params = np.array([v_ego, lat_delay], dtype=np.float32) - if sm.updated["liveCalibration"] and sm.seen['roadCameraState'] and sm.seen['deviceState']: - device_from_calib_euler = np.array(sm["liveCalibration"].rpyCalib, dtype=np.float32) - dc = DEVICE_CAMERAS[(str(sm['deviceState'].deviceType), str(sm['roadCameraState'].sensor))] - model_transform_main = get_warp_matrix(device_from_calib_euler, dc.ecam.intrinsics if main_wide_camera else dc.fcam.intrinsics, False).astype(np.float32) - model_transform_extra = get_warp_matrix(device_from_calib_euler, dc.ecam.intrinsics, True).astype(np.float32) - live_calib_seen = True - - traffic_convention = np.zeros(2) - traffic_convention[int(is_rhd)] = 1 - - vec_desire = np.zeros(ModelConstants.DESIRE_LEN, dtype=np.float32) - if desire >= 0 and desire < ModelConstants.DESIRE_LEN: - vec_desire[desire] = 1 - - # tracked dropped frames - vipc_dropped_frames = max(0, meta_main.frame_id - last_vipc_frame_id - 1) - frames_dropped = frame_dropped_filter.update(min(vipc_dropped_frames, 10)) - if run_count < 10: # let frame drops warm up - frame_dropped_filter.x = 0. - frames_dropped = 0. - run_count = run_count + 1 - - frame_drop_ratio = frames_dropped / (1 + frames_dropped) - prepare_only = vipc_dropped_frames > 0 - if prepare_only: - cloudlog.error(f"skipping model eval. Dropped {vipc_dropped_frames} frames") - - bufs = {name: buf_extra if 'big' in name else buf_main for name in model.vision_input_names} - transforms = {name: model_transform_extra if 'big' in name else model_transform_main for name in model.vision_input_names} - inputs:dict[str, np.ndarray] = { - 'desire': vec_desire, - 'traffic_convention': traffic_convention, - 'lateral_control_params': lateral_control_params, - } - - mt1 = time.perf_counter() - model_output = model.run(bufs, transforms, inputs, prepare_only) - mt2 = time.perf_counter() - model_execution_time = mt2 - mt1 - - if model_output is not None: - modelv2_send = messaging.new_message('modelV2') - drivingdata_send = messaging.new_message('drivingModelData') - posenet_send = messaging.new_message('cameraOdometry') - - action = get_action_from_model(model_output, prev_action, lat_delay + DT_MDL, long_delay + DT_MDL, v_ego) - prev_action = action - fill_model_msg(drivingdata_send, modelv2_send, model_output, action, - publish_state, meta_main.frame_id, meta_extra.frame_id, frame_id, - frame_drop_ratio, meta_main.timestamp_eof, model_execution_time, live_calib_seen) - - desire_state = modelv2_send.modelV2.meta.desireState - l_lane_change_prob = desire_state[log.Desire.laneChangeLeft] - r_lane_change_prob = desire_state[log.Desire.laneChangeRight] - lane_change_prob = l_lane_change_prob + r_lane_change_prob - DH.update(sm['carState'], sm['carControl'].latActive, lane_change_prob) - modelv2_send.modelV2.meta.laneChangeState = DH.lane_change_state - modelv2_send.modelV2.meta.laneChangeDirection = DH.lane_change_direction - drivingdata_send.drivingModelData.meta.laneChangeState = DH.lane_change_state - drivingdata_send.drivingModelData.meta.laneChangeDirection = DH.lane_change_direction - - fill_pose_msg(posenet_send, model_output, meta_main.frame_id, vipc_dropped_frames, meta_main.timestamp_eof, live_calib_seen) - pm.send('modelV2', modelv2_send) - pm.send('drivingModelData', drivingdata_send) - pm.send('cameraOdometry', posenet_send) - last_vipc_frame_id = meta_main.frame_id - - -if __name__ == "__main__": - try: - import argparse - parser = argparse.ArgumentParser() - parser.add_argument('--demo', action='store_true', help='A boolean for demo mode.') - args = parser.parse_args() - main(demo=args.demo) - except KeyboardInterrupt: - cloudlog.warning(f"child {PROCESS_NAME} got SIGINT") - except Exception: - sentry.capture_exception() - raise diff --git a/selfdrive/modeld/models/README.md b/selfdrive/modeld/models/README.md deleted file mode 100644 index 255f28d80e..0000000000 --- a/selfdrive/modeld/models/README.md +++ /dev/null @@ -1,67 +0,0 @@ -## Neural networks in openpilot -To view the architecture of the ONNX networks, you can use [netron](https://netron.app/) - -## Driving Model (vision model + temporal policy model) -### Vision inputs (Full size: 799906 x float32) -* **image stream** - * Two consecutive images (256 * 512 * 3 in RGB) recorded at 20 Hz : 393216 = 2 * 6 * 128 * 256 - * Each 256 * 512 image is represented in YUV420 with 6 channels : 6 * 128 * 256 - * Channels 0,1,2,3 represent the full-res Y channel and are represented in numpy as Y[::2, ::2], Y[::2, 1::2], Y[1::2, ::2], and Y[1::2, 1::2] - * Channel 4 represents the half-res U channel - * Channel 5 represents the half-res V channel -* **wide image stream** - * Two consecutive images (256 * 512 * 3 in RGB) recorded at 20 Hz : 393216 = 2 * 6 * 128 * 256 - * Each 256 * 512 image is represented in YUV420 with 6 channels : 6 * 128 * 256 - * Channels 0,1,2,3 represent the full-res Y channel and are represented in numpy as Y[::2, ::2], Y[::2, 1::2], Y[1::2, ::2], and Y[1::2, 1::2] - * Channel 4 represents the half-res U channel - * Channel 5 represents the half-res V channel -### Policy inputs -* **desire** - * one-hot encoded buffer to command model to execute certain actions, bit needs to be sent for the past 5 seconds (at 20FPS) : 100 * 8 -* **traffic convention** - * one-hot encoded vector to tell model whether traffic is right-hand or left-hand traffic : 2 -* **lateral control params** - * speed and steering delay for predicting the desired curvature: 2 -* **previous desired curvatures** - * vector of previously predicted desired curvatures: 100 * 1 -* **feature buffer** - * a buffer of intermediate features including the current feature to form a 5 seconds temporal context (at 20FPS) : 100 * 512 - - -### Driving Model output format (Full size: XXX x float32) -Refer to **slice_outputs** and **parse_vision_outputs/parse_policy_outputs** in modeld. - - -## Driver Monitoring Model -* .onnx model can be run with onnx runtimes -* .dlc file is a pre-quantized model and only runs on qualcomm DSPs - -### input format -* single image W = 1440 H = 960 luminance channel (Y) from the planar YUV420 format: - * full input size is 1440 * 960 = 1382400 - * normalized ranging from 0.0 to 1.0 in float32 (onnx runner) or ranging from 0 to 255 in uint8 (snpe runner) -* camera calibration angles (roll, pitch, yaw) from liveCalibration: 3 x float32 inputs - -### output format -* 84 x float32 outputs = 2 + 41 * 2 ([parsing example](https://github.com/commaai/openpilot/blob/22ce4e17ba0d3bfcf37f8255a4dd1dc683fe0c38/selfdrive/modeld/models/dmonitoring.cc#L33)) - * for each person in the front seats (2 * 41) - * face pose: 12 = 6 + 6 - * face orientation [pitch, yaw, roll] in camera frame: 3 - * face position [dx, dy] relative to image center: 2 - * normalized face size: 1 - * standard deviations for above outputs: 6 - * face visible probability: 1 - * eyes: 20 = (8 + 1) + (8 + 1) + 1 + 1 - * eye position and size, and their standard deviations: 8 - * eye visible probability: 1 - * eye closed probability: 1 - * wearing sunglasses probability: 1 - * face occluded probability: 1 - * touching wheel probability: 1 - * paying attention probability: 1 - * (deprecated) distracted probabilities: 2 - * using phone probability: 1 - * distracted probability: 1 - * common outputs 2 - * poor camera vision probability: 1 - * left hand drive probability: 1 diff --git a/selfdrive/modeld/models/big_driving_policy.onnx b/selfdrive/modeld/models/big_driving_policy.onnx deleted file mode 120000 index e1b653a14a..0000000000 --- a/selfdrive/modeld/models/big_driving_policy.onnx +++ /dev/null @@ -1 +0,0 @@ -driving_policy.onnx \ No newline at end of file diff --git a/selfdrive/modeld/models/big_driving_vision.onnx b/selfdrive/modeld/models/big_driving_vision.onnx deleted file mode 120000 index 28ee71dd74..0000000000 --- a/selfdrive/modeld/models/big_driving_vision.onnx +++ /dev/null @@ -1 +0,0 @@ -driving_vision.onnx \ No newline at end of file diff --git a/selfdrive/modeld/models/commonmodel.cc b/selfdrive/modeld/models/commonmodel.cc deleted file mode 100644 index d3341e76ec..0000000000 --- a/selfdrive/modeld/models/commonmodel.cc +++ /dev/null @@ -1,64 +0,0 @@ -#include "selfdrive/modeld/models/commonmodel.h" - -#include -#include - -#include "common/clutil.h" - -DrivingModelFrame::DrivingModelFrame(cl_device_id device_id, cl_context context, int _temporal_skip) : ModelFrame(device_id, context) { - input_frames = std::make_unique(buf_size); - temporal_skip = _temporal_skip; - input_frames_cl = CL_CHECK_ERR(clCreateBuffer(context, CL_MEM_READ_WRITE, buf_size, NULL, &err)); - img_buffer_20hz_cl = CL_CHECK_ERR(clCreateBuffer(context, CL_MEM_READ_WRITE, (temporal_skip+1)*frame_size_bytes, NULL, &err)); - region.origin = temporal_skip * frame_size_bytes; - region.size = frame_size_bytes; - last_img_cl = CL_CHECK_ERR(clCreateSubBuffer(img_buffer_20hz_cl, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err)); - - loadyuv_init(&loadyuv, context, device_id, MODEL_WIDTH, MODEL_HEIGHT); - init_transform(device_id, context, MODEL_WIDTH, MODEL_HEIGHT); -} - -cl_mem* DrivingModelFrame::prepare(cl_mem yuv_cl, int frame_width, int frame_height, int frame_stride, int frame_uv_offset, const mat3& projection) { - run_transform(yuv_cl, MODEL_WIDTH, MODEL_HEIGHT, frame_width, frame_height, frame_stride, frame_uv_offset, projection); - - for (int i = 0; i < temporal_skip; i++) { - CL_CHECK(clEnqueueCopyBuffer(q, img_buffer_20hz_cl, img_buffer_20hz_cl, (i+1)*frame_size_bytes, i*frame_size_bytes, frame_size_bytes, 0, nullptr, nullptr)); - } - loadyuv_queue(&loadyuv, q, y_cl, u_cl, v_cl, last_img_cl); - - copy_queue(&loadyuv, q, img_buffer_20hz_cl, input_frames_cl, 0, 0, frame_size_bytes); - copy_queue(&loadyuv, q, last_img_cl, input_frames_cl, 0, frame_size_bytes, frame_size_bytes); - - // NOTE: Since thneed is using a different command queue, this clFinish is needed to ensure the image is ready. - clFinish(q); - return &input_frames_cl; -} - -DrivingModelFrame::~DrivingModelFrame() { - deinit_transform(); - loadyuv_destroy(&loadyuv); - CL_CHECK(clReleaseMemObject(input_frames_cl)); - CL_CHECK(clReleaseMemObject(img_buffer_20hz_cl)); - CL_CHECK(clReleaseMemObject(last_img_cl)); - CL_CHECK(clReleaseCommandQueue(q)); -} - - -MonitoringModelFrame::MonitoringModelFrame(cl_device_id device_id, cl_context context) : ModelFrame(device_id, context) { - input_frames = std::make_unique(buf_size); - input_frame_cl = CL_CHECK_ERR(clCreateBuffer(context, CL_MEM_READ_WRITE, buf_size, NULL, &err)); - - init_transform(device_id, context, MODEL_WIDTH, MODEL_HEIGHT); -} - -cl_mem* MonitoringModelFrame::prepare(cl_mem yuv_cl, int frame_width, int frame_height, int frame_stride, int frame_uv_offset, const mat3& projection) { - run_transform(yuv_cl, MODEL_WIDTH, MODEL_HEIGHT, frame_width, frame_height, frame_stride, frame_uv_offset, projection); - clFinish(q); - return &y_cl; -} - -MonitoringModelFrame::~MonitoringModelFrame() { - deinit_transform(); - CL_CHECK(clReleaseMemObject(input_frame_cl)); - CL_CHECK(clReleaseCommandQueue(q)); -} diff --git a/selfdrive/modeld/models/commonmodel.h b/selfdrive/modeld/models/commonmodel.h deleted file mode 100644 index 176d7eb6dc..0000000000 --- a/selfdrive/modeld/models/commonmodel.h +++ /dev/null @@ -1,97 +0,0 @@ -#pragma once - -#include -#include -#include - -#include - -#define CL_USE_DEPRECATED_OPENCL_1_2_APIS -#ifdef __APPLE__ -#include -#else -#include -#endif - -#include "common/mat.h" -#include "selfdrive/modeld/transforms/loadyuv.h" -#include "selfdrive/modeld/transforms/transform.h" - -class ModelFrame { -public: - ModelFrame(cl_device_id device_id, cl_context context) { - q = CL_CHECK_ERR(clCreateCommandQueue(context, device_id, 0, &err)); - } - virtual ~ModelFrame() {} - virtual cl_mem* prepare(cl_mem yuv_cl, int frame_width, int frame_height, int frame_stride, int frame_uv_offset, const mat3& projection) { return NULL; } - uint8_t* buffer_from_cl(cl_mem *in_frames, int buffer_size) { - CL_CHECK(clEnqueueReadBuffer(q, *in_frames, CL_TRUE, 0, buffer_size, input_frames.get(), 0, nullptr, nullptr)); - clFinish(q); - return &input_frames[0]; - } - - int MODEL_WIDTH; - int MODEL_HEIGHT; - int MODEL_FRAME_SIZE; - int buf_size; - -protected: - cl_mem y_cl, u_cl, v_cl; - Transform transform; - cl_command_queue q; - std::unique_ptr input_frames; - - void init_transform(cl_device_id device_id, cl_context context, int model_width, int model_height) { - y_cl = CL_CHECK_ERR(clCreateBuffer(context, CL_MEM_READ_WRITE, model_width * model_height, NULL, &err)); - u_cl = CL_CHECK_ERR(clCreateBuffer(context, CL_MEM_READ_WRITE, (model_width / 2) * (model_height / 2), NULL, &err)); - v_cl = CL_CHECK_ERR(clCreateBuffer(context, CL_MEM_READ_WRITE, (model_width / 2) * (model_height / 2), NULL, &err)); - transform_init(&transform, context, device_id); - } - - void deinit_transform() { - transform_destroy(&transform); - CL_CHECK(clReleaseMemObject(v_cl)); - CL_CHECK(clReleaseMemObject(u_cl)); - CL_CHECK(clReleaseMemObject(y_cl)); - } - - void run_transform(cl_mem yuv_cl, int model_width, int model_height, int frame_width, int frame_height, int frame_stride, int frame_uv_offset, const mat3& projection) { - transform_queue(&transform, q, - yuv_cl, frame_width, frame_height, frame_stride, frame_uv_offset, - y_cl, u_cl, v_cl, model_width, model_height, projection); - } -}; - -class DrivingModelFrame : public ModelFrame { -public: - DrivingModelFrame(cl_device_id device_id, cl_context context, int _temporal_skip); - ~DrivingModelFrame(); - cl_mem* prepare(cl_mem yuv_cl, int frame_width, int frame_height, int frame_stride, int frame_uv_offset, const mat3& projection); - - const int MODEL_WIDTH = 512; - const int MODEL_HEIGHT = 256; - const int MODEL_FRAME_SIZE = MODEL_WIDTH * MODEL_HEIGHT * 3 / 2; - const int buf_size = MODEL_FRAME_SIZE * 2; // 2 frames are temporal_skip frames apart - const size_t frame_size_bytes = MODEL_FRAME_SIZE * sizeof(uint8_t); - -private: - LoadYUVState loadyuv; - cl_mem img_buffer_20hz_cl, last_img_cl, input_frames_cl; - cl_buffer_region region; - int temporal_skip; -}; - -class MonitoringModelFrame : public ModelFrame { -public: - MonitoringModelFrame(cl_device_id device_id, cl_context context); - ~MonitoringModelFrame(); - cl_mem* prepare(cl_mem yuv_cl, int frame_width, int frame_height, int frame_stride, int frame_uv_offset, const mat3& projection); - - const int MODEL_WIDTH = 1440; - const int MODEL_HEIGHT = 960; - const int MODEL_FRAME_SIZE = MODEL_WIDTH * MODEL_HEIGHT; - const int buf_size = MODEL_FRAME_SIZE; - -private: - cl_mem input_frame_cl; -}; diff --git a/selfdrive/modeld/models/commonmodel.pxd b/selfdrive/modeld/models/commonmodel.pxd deleted file mode 100644 index 4ac64d9172..0000000000 --- a/selfdrive/modeld/models/commonmodel.pxd +++ /dev/null @@ -1,27 +0,0 @@ -# distutils: language = c++ - -from msgq.visionipc.visionipc cimport cl_device_id, cl_context, cl_mem - -cdef extern from "common/mat.h": - cdef struct mat3: - float v[9] - -cdef extern from "common/clutil.h": - cdef unsigned long CL_DEVICE_TYPE_DEFAULT - cl_device_id cl_get_device_id(unsigned long) - cl_context cl_create_context(cl_device_id) - void cl_release_context(cl_context) - -cdef extern from "selfdrive/modeld/models/commonmodel.h": - cppclass ModelFrame: - int buf_size - unsigned char * buffer_from_cl(cl_mem*, int); - cl_mem * prepare(cl_mem, int, int, int, int, mat3) - - cppclass DrivingModelFrame: - int buf_size - DrivingModelFrame(cl_device_id, cl_context, int) - - cppclass MonitoringModelFrame: - int buf_size - MonitoringModelFrame(cl_device_id, cl_context) diff --git a/selfdrive/modeld/models/commonmodel_pyx.pxd b/selfdrive/modeld/models/commonmodel_pyx.pxd deleted file mode 100644 index 0bb798625b..0000000000 --- a/selfdrive/modeld/models/commonmodel_pyx.pxd +++ /dev/null @@ -1,13 +0,0 @@ -# distutils: language = c++ - -from msgq.visionipc.visionipc cimport cl_mem -from msgq.visionipc.visionipc_pyx cimport CLContext as BaseCLContext - -cdef class CLContext(BaseCLContext): - pass - -cdef class CLMem: - cdef cl_mem * mem - - @staticmethod - cdef create(void*) diff --git a/selfdrive/modeld/models/commonmodel_pyx.pyx b/selfdrive/modeld/models/commonmodel_pyx.pyx deleted file mode 100644 index 5b7d11bc71..0000000000 --- a/selfdrive/modeld/models/commonmodel_pyx.pyx +++ /dev/null @@ -1,74 +0,0 @@ -# distutils: language = c++ -# cython: c_string_encoding=ascii, language_level=3 - -import numpy as np -cimport numpy as cnp -from libc.string cimport memcpy -from libc.stdint cimport uintptr_t - -from msgq.visionipc.visionipc cimport cl_mem -from msgq.visionipc.visionipc_pyx cimport VisionBuf, CLContext as BaseCLContext -from .commonmodel cimport CL_DEVICE_TYPE_DEFAULT, cl_get_device_id, cl_create_context, cl_release_context -from .commonmodel cimport mat3, ModelFrame as cppModelFrame, DrivingModelFrame as cppDrivingModelFrame, MonitoringModelFrame as cppMonitoringModelFrame - - -cdef class CLContext(BaseCLContext): - def __cinit__(self): - self.device_id = cl_get_device_id(CL_DEVICE_TYPE_DEFAULT) - self.context = cl_create_context(self.device_id) - - def __dealloc__(self): - if self.context: - cl_release_context(self.context) - -cdef class CLMem: - @staticmethod - cdef create(void * cmem): - mem = CLMem() - mem.mem = cmem - return mem - - @property - def mem_address(self): - return (self.mem) - -def cl_from_visionbuf(VisionBuf buf): - return CLMem.create(&buf.buf.buf_cl) - - -cdef class ModelFrame: - cdef cppModelFrame * frame - cdef int buf_size - - def __dealloc__(self): - del self.frame - - def prepare(self, VisionBuf buf, float[:] projection): - cdef mat3 cprojection - memcpy(cprojection.v, &projection[0], 9*sizeof(float)) - cdef cl_mem * data - data = self.frame.prepare(buf.buf.buf_cl, buf.width, buf.height, buf.stride, buf.uv_offset, cprojection) - return CLMem.create(data) - - def buffer_from_cl(self, CLMem in_frames): - cdef unsigned char * data2 - data2 = self.frame.buffer_from_cl(in_frames.mem, self.buf_size) - return np.asarray( data2) - - -cdef class DrivingModelFrame(ModelFrame): - cdef cppDrivingModelFrame * _frame - - def __cinit__(self, CLContext context, int temporal_skip): - self._frame = new cppDrivingModelFrame(context.device_id, context.context, temporal_skip) - self.frame = (self._frame) - self.buf_size = self._frame.buf_size - -cdef class MonitoringModelFrame(ModelFrame): - cdef cppMonitoringModelFrame * _frame - - def __cinit__(self, CLContext context): - self._frame = new cppMonitoringModelFrame(context.device_id, context.context) - self.frame = (self._frame) - self.buf_size = self._frame.buf_size - diff --git a/selfdrive/modeld/models/dmonitoring_model.current b/selfdrive/modeld/models/dmonitoring_model.current deleted file mode 100644 index 121871ef2b..0000000000 --- a/selfdrive/modeld/models/dmonitoring_model.current +++ /dev/null @@ -1,2 +0,0 @@ -fa69be01-b430-4504-9d72-7dcb058eb6dd -d9fb22d1c4fa3ca3d201dbc8edf1d0f0918e53e6 diff --git a/selfdrive/modeld/models/dmonitoring_model.onnx b/selfdrive/modeld/models/dmonitoring_model.onnx deleted file mode 100644 index dcc727510e..0000000000 --- a/selfdrive/modeld/models/dmonitoring_model.onnx +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:50efe6451a3fb3fa04b6bb0e846544533329bd46ecefe9e657e91214dee2aaeb -size 7196502 diff --git a/selfdrive/modeld/models/driving_policy.onnx b/selfdrive/modeld/models/driving_policy.onnx deleted file mode 100644 index 343c3a0aa8..0000000000 --- a/selfdrive/modeld/models/driving_policy.onnx +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:5f714fb38bcd44b5d9f44e3a8e1595e1dfdf7558f0eec3485cf3f2dbb6dc7d8d -size 15971805 diff --git a/selfdrive/modeld/models/driving_vision.onnx b/selfdrive/modeld/models/driving_vision.onnx deleted file mode 100644 index 924d11304d..0000000000 --- a/selfdrive/modeld/models/driving_vision.onnx +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:3ac4867fbc618037e8d03143edbfeeae960f2025644b5dcf36c6665271b4f874 -size 34883375 diff --git a/selfdrive/modeld/parse_model_outputs.py b/selfdrive/modeld/parse_model_outputs.py deleted file mode 100644 index 810c44ccb9..0000000000 --- a/selfdrive/modeld/parse_model_outputs.py +++ /dev/null @@ -1,115 +0,0 @@ -import numpy as np -from openpilot.selfdrive.modeld.constants import ModelConstants - -def safe_exp(x, out=None): - # -11 is around 10**14, more causes float16 overflow - return np.exp(np.clip(x, -np.inf, 11), out=out) - -def sigmoid(x): - return 1. / (1. + safe_exp(-x)) - -def softmax(x, axis=-1): - x -= np.max(x, axis=axis, keepdims=True) - if x.dtype == np.float32 or x.dtype == np.float64: - safe_exp(x, out=x) - else: - x = safe_exp(x) - x /= np.sum(x, axis=axis, keepdims=True) - return x - -class Parser: - def __init__(self, ignore_missing=False): - self.ignore_missing = ignore_missing - - def check_missing(self, outs, name): - if name not in outs and not self.ignore_missing: - raise ValueError(f"Missing output {name}") - return name not in outs - - def parse_categorical_crossentropy(self, name, outs, out_shape=None): - if self.check_missing(outs, name): - return - raw = outs[name] - if out_shape is not None: - raw = raw.reshape((raw.shape[0],) + out_shape) - outs[name] = softmax(raw, axis=-1) - - def parse_binary_crossentropy(self, name, outs): - if self.check_missing(outs, name): - return - raw = outs[name] - outs[name] = sigmoid(raw) - - def parse_mdn(self, name, outs, in_N=0, out_N=1, out_shape=None): - if self.check_missing(outs, name): - return - raw = outs[name] - raw = raw.reshape((raw.shape[0], max(in_N, 1), -1)) - - n_values = (raw.shape[2] - out_N)//2 - pred_mu = raw[:,:,:n_values] - pred_std = safe_exp(raw[:,:,n_values: 2*n_values]) - - if in_N > 1: - weights = np.zeros((raw.shape[0], in_N, out_N), dtype=raw.dtype) - for i in range(out_N): - weights[:,:,i - out_N] = softmax(raw[:,:,i - out_N], axis=-1) - - if out_N == 1: - for fidx in range(weights.shape[0]): - idxs = np.argsort(weights[fidx][:,0])[::-1] - weights[fidx] = weights[fidx][idxs] - pred_mu[fidx] = pred_mu[fidx][idxs] - pred_std[fidx] = pred_std[fidx][idxs] - full_shape = tuple([raw.shape[0], in_N] + list(out_shape)) - outs[name + '_weights'] = weights - outs[name + '_hypotheses'] = pred_mu.reshape(full_shape) - outs[name + '_stds_hypotheses'] = pred_std.reshape(full_shape) - - pred_mu_final = np.zeros((raw.shape[0], out_N, n_values), dtype=raw.dtype) - pred_std_final = np.zeros((raw.shape[0], out_N, n_values), dtype=raw.dtype) - for fidx in range(weights.shape[0]): - for hidx in range(out_N): - idxs = np.argsort(weights[fidx,:,hidx])[::-1] - pred_mu_final[fidx, hidx] = pred_mu[fidx, idxs[0]] - pred_std_final[fidx, hidx] = pred_std[fidx, idxs[0]] - else: - pred_mu_final = pred_mu - pred_std_final = pred_std - - if out_N > 1: - final_shape = tuple([raw.shape[0], out_N] + list(out_shape)) - else: - final_shape = tuple([raw.shape[0],] + list(out_shape)) - outs[name] = pred_mu_final.reshape(final_shape) - outs[name + '_stds'] = pred_std_final.reshape(final_shape) - - def parse_vision_outputs(self, outs: dict[str, np.ndarray]) -> dict[str, np.ndarray]: - self.parse_mdn('pose', outs, in_N=0, out_N=0, out_shape=(ModelConstants.POSE_WIDTH,)) - self.parse_mdn('wide_from_device_euler', outs, in_N=0, out_N=0, out_shape=(ModelConstants.WIDE_FROM_DEVICE_WIDTH,)) - self.parse_mdn('road_transform', outs, in_N=0, out_N=0, out_shape=(ModelConstants.POSE_WIDTH,)) - self.parse_categorical_crossentropy('desire_pred', outs, out_shape=(ModelConstants.DESIRE_PRED_LEN,ModelConstants.DESIRE_PRED_WIDTH)) - self.parse_binary_crossentropy('meta', outs) - return outs - - def parse_policy_outputs(self, outs: dict[str, np.ndarray]) -> dict[str, np.ndarray]: - self.parse_mdn('plan', outs, in_N=ModelConstants.PLAN_MHP_N, out_N=ModelConstants.PLAN_MHP_SELECTION, - out_shape=(ModelConstants.IDX_N,ModelConstants.PLAN_WIDTH)) - self.parse_mdn('lane_lines', outs, in_N=0, out_N=0, out_shape=(ModelConstants.NUM_LANE_LINES,ModelConstants.IDX_N,ModelConstants.LANE_LINES_WIDTH)) - self.parse_mdn('road_edges', outs, in_N=0, out_N=0, out_shape=(ModelConstants.NUM_ROAD_EDGES,ModelConstants.IDX_N,ModelConstants.LANE_LINES_WIDTH)) - self.parse_mdn('sim_pose', outs, in_N=0, out_N=0, out_shape=(ModelConstants.POSE_WIDTH,)) - self.parse_mdn('lead', outs, in_N=ModelConstants.LEAD_MHP_N, out_N=ModelConstants.LEAD_MHP_SELECTION, - out_shape=(ModelConstants.LEAD_TRAJ_LEN,ModelConstants.LEAD_WIDTH)) - if 'lat_planner_solution' in outs: - self.parse_mdn('lat_planner_solution', outs, in_N=0, out_N=0, out_shape=(ModelConstants.IDX_N,ModelConstants.LAT_PLANNER_SOLUTION_WIDTH)) - if 'desired_curvature' in outs: - self.parse_mdn('desired_curvature', outs, in_N=0, out_N=0, out_shape=(ModelConstants.DESIRED_CURV_WIDTH,)) - for k in ['lead_prob', 'lane_lines_prob']: - self.parse_binary_crossentropy(k, outs) - self.parse_categorical_crossentropy('desire_state', outs, out_shape=(ModelConstants.DESIRE_PRED_WIDTH,)) - return outs - - def parse_outputs(self, outs: dict[str, np.ndarray]) -> dict[str, np.ndarray]: - outs = self.parse_vision_outputs(outs) - outs = self.parse_policy_outputs(outs) - return outs diff --git a/selfdrive/modeld/runners/tinygrad_helpers.py b/selfdrive/modeld/runners/tinygrad_helpers.py deleted file mode 100644 index 776381341c..0000000000 --- a/selfdrive/modeld/runners/tinygrad_helpers.py +++ /dev/null @@ -1,8 +0,0 @@ - -from tinygrad.tensor import Tensor -from tinygrad.helpers import to_mv - -def qcom_tensor_from_opencl_address(opencl_address, shape, dtype): - cl_buf_desc_ptr = to_mv(opencl_address, 8).cast('Q')[0] - rawbuf_ptr = to_mv(cl_buf_desc_ptr, 0x100).cast('Q')[20] # offset 0xA0 is a raw gpu pointer. - return Tensor.from_blob(rawbuf_ptr, shape, dtype=dtype, device='QCOM') diff --git a/selfdrive/modeld/tests/test_modeld.py b/selfdrive/modeld/tests/test_modeld.py deleted file mode 100644 index 6927c9e473..0000000000 --- a/selfdrive/modeld/tests/test_modeld.py +++ /dev/null @@ -1,102 +0,0 @@ -import numpy as np -import random - -import cereal.messaging as messaging -from msgq.visionipc import VisionIpcServer, VisionStreamType -from opendbc.car.car_helpers import get_demo_car_params -from openpilot.common.params import Params -from openpilot.common.transformations.camera import DEVICE_CAMERAS -from openpilot.common.realtime import DT_MDL -from openpilot.system.manager.process_config import managed_processes -from openpilot.selfdrive.test.process_replay.vision_meta import meta_from_camera_state - -CAM = DEVICE_CAMERAS[("tici", "ar0231")].fcam -IMG = np.zeros(int(CAM.width*CAM.height*(3/2)), dtype=np.uint8) -IMG_BYTES = IMG.flatten().tobytes() - - -class TestModeld: - - def setup_method(self): - self.vipc_server = VisionIpcServer("camerad") - self.vipc_server.create_buffers(VisionStreamType.VISION_STREAM_ROAD, 40, CAM.width, CAM.height) - self.vipc_server.create_buffers(VisionStreamType.VISION_STREAM_DRIVER, 40, CAM.width, CAM.height) - self.vipc_server.create_buffers(VisionStreamType.VISION_STREAM_WIDE_ROAD, 40, CAM.width, CAM.height) - self.vipc_server.start_listener() - Params().put("CarParams", get_demo_car_params().to_bytes()) - - self.sm = messaging.SubMaster(['modelV2', 'cameraOdometry']) - self.pm = messaging.PubMaster(['roadCameraState', 'wideRoadCameraState', 'liveCalibration']) - - managed_processes['modeld'].start() - self.pm.wait_for_readers_to_update("roadCameraState", 10) - - def teardown_method(self): - managed_processes['modeld'].stop() - del self.vipc_server - - def _send_frames(self, frame_id, cams=None): - if cams is None: - cams = ('roadCameraState', 'wideRoadCameraState') - - cs = None - for cam in cams: - msg = messaging.new_message(cam) - cs = getattr(msg, cam) - cs.frameId = frame_id - cs.timestampSof = int((frame_id * DT_MDL) * 1e9) - cs.timestampEof = int(cs.timestampSof + (DT_MDL * 1e9)) - cam_meta = meta_from_camera_state(cam) - - self.pm.send(msg.which(), msg) - self.vipc_server.send(cam_meta.stream, IMG_BYTES, cs.frameId, - cs.timestampSof, cs.timestampEof) - return cs - - def _wait(self): - self.sm.update(5000) - if self.sm['modelV2'].frameId != self.sm['cameraOdometry'].frameId: - self.sm.update(1000) - - def test_modeld(self): - for n in range(1, 500): - cs = self._send_frames(n) - self._wait() - - mdl = self.sm['modelV2'] - assert mdl.frameId == n - assert mdl.frameIdExtra == n - assert mdl.timestampEof == cs.timestampEof - assert mdl.frameAge == 0 - assert mdl.frameDropPerc == 0 - - odo = self.sm['cameraOdometry'] - assert odo.frameId == n - assert odo.timestampEof == cs.timestampEof - - def test_dropped_frames(self): - """ - modeld should only run on consecutive road frames - """ - frame_id = -1 - road_frames = list() - for n in range(1, 50): - if (random.random() < 0.1) and n > 3: - cams = random.choice([(), ('wideRoadCameraState', )]) - self._send_frames(n, cams) - else: - self._send_frames(n) - road_frames.append(n) - self._wait() - - if len(road_frames) < 3 or road_frames[-1] - road_frames[-2] == 1: - frame_id = road_frames[-1] - - mdl = self.sm['modelV2'] - odo = self.sm['cameraOdometry'] - assert mdl.frameId == frame_id - assert mdl.frameIdExtra == frame_id - assert odo.frameId == frame_id - if n != frame_id: - assert not self.sm.updated['modelV2'] - assert not self.sm.updated['cameraOdometry'] diff --git a/selfdrive/modeld/transforms/loadyuv.cc b/selfdrive/modeld/transforms/loadyuv.cc deleted file mode 100644 index c93f5cd038..0000000000 --- a/selfdrive/modeld/transforms/loadyuv.cc +++ /dev/null @@ -1,76 +0,0 @@ -#include "selfdrive/modeld/transforms/loadyuv.h" - -#include -#include -#include - -void loadyuv_init(LoadYUVState* s, cl_context ctx, cl_device_id device_id, int width, int height) { - memset(s, 0, sizeof(*s)); - - s->width = width; - s->height = height; - - char args[1024]; - snprintf(args, sizeof(args), - "-cl-fast-relaxed-math -cl-denorms-are-zero " - "-DTRANSFORMED_WIDTH=%d -DTRANSFORMED_HEIGHT=%d", - width, height); - cl_program prg = cl_program_from_file(ctx, device_id, LOADYUV_PATH, args); - - s->loadys_krnl = CL_CHECK_ERR(clCreateKernel(prg, "loadys", &err)); - s->loaduv_krnl = CL_CHECK_ERR(clCreateKernel(prg, "loaduv", &err)); - s->copy_krnl = CL_CHECK_ERR(clCreateKernel(prg, "copy", &err)); - - // done with this - CL_CHECK(clReleaseProgram(prg)); -} - -void loadyuv_destroy(LoadYUVState* s) { - CL_CHECK(clReleaseKernel(s->loadys_krnl)); - CL_CHECK(clReleaseKernel(s->loaduv_krnl)); - CL_CHECK(clReleaseKernel(s->copy_krnl)); -} - -void loadyuv_queue(LoadYUVState* s, cl_command_queue q, - cl_mem y_cl, cl_mem u_cl, cl_mem v_cl, - cl_mem out_cl) { - cl_int global_out_off = 0; - - CL_CHECK(clSetKernelArg(s->loadys_krnl, 0, sizeof(cl_mem), &y_cl)); - CL_CHECK(clSetKernelArg(s->loadys_krnl, 1, sizeof(cl_mem), &out_cl)); - CL_CHECK(clSetKernelArg(s->loadys_krnl, 2, sizeof(cl_int), &global_out_off)); - - const size_t loadys_work_size = (s->width*s->height)/8; - CL_CHECK(clEnqueueNDRangeKernel(q, s->loadys_krnl, 1, NULL, - &loadys_work_size, NULL, 0, 0, NULL)); - - const size_t loaduv_work_size = ((s->width/2)*(s->height/2))/8; - global_out_off += (s->width*s->height); - - CL_CHECK(clSetKernelArg(s->loaduv_krnl, 0, sizeof(cl_mem), &u_cl)); - CL_CHECK(clSetKernelArg(s->loaduv_krnl, 1, sizeof(cl_mem), &out_cl)); - CL_CHECK(clSetKernelArg(s->loaduv_krnl, 2, sizeof(cl_int), &global_out_off)); - - CL_CHECK(clEnqueueNDRangeKernel(q, s->loaduv_krnl, 1, NULL, - &loaduv_work_size, NULL, 0, 0, NULL)); - - global_out_off += (s->width/2)*(s->height/2); - - CL_CHECK(clSetKernelArg(s->loaduv_krnl, 0, sizeof(cl_mem), &v_cl)); - CL_CHECK(clSetKernelArg(s->loaduv_krnl, 1, sizeof(cl_mem), &out_cl)); - CL_CHECK(clSetKernelArg(s->loaduv_krnl, 2, sizeof(cl_int), &global_out_off)); - - CL_CHECK(clEnqueueNDRangeKernel(q, s->loaduv_krnl, 1, NULL, - &loaduv_work_size, NULL, 0, 0, NULL)); -} - -void copy_queue(LoadYUVState* s, cl_command_queue q, cl_mem src, cl_mem dst, - size_t src_offset, size_t dst_offset, size_t size) { - CL_CHECK(clSetKernelArg(s->copy_krnl, 0, sizeof(cl_mem), &src)); - CL_CHECK(clSetKernelArg(s->copy_krnl, 1, sizeof(cl_mem), &dst)); - CL_CHECK(clSetKernelArg(s->copy_krnl, 2, sizeof(cl_int), &src_offset)); - CL_CHECK(clSetKernelArg(s->copy_krnl, 3, sizeof(cl_int), &dst_offset)); - const size_t copy_work_size = size/8; - CL_CHECK(clEnqueueNDRangeKernel(q, s->copy_krnl, 1, NULL, - ©_work_size, NULL, 0, 0, NULL)); -} \ No newline at end of file diff --git a/selfdrive/modeld/transforms/loadyuv.cl b/selfdrive/modeld/transforms/loadyuv.cl deleted file mode 100644 index 970187a6d7..0000000000 --- a/selfdrive/modeld/transforms/loadyuv.cl +++ /dev/null @@ -1,47 +0,0 @@ -#define UV_SIZE ((TRANSFORMED_WIDTH/2)*(TRANSFORMED_HEIGHT/2)) - -__kernel void loadys(__global uchar8 const * const Y, - __global uchar * out, - int out_offset) -{ - const int gid = get_global_id(0); - const int ois = gid * 8; - const int oy = ois / TRANSFORMED_WIDTH; - const int ox = ois % TRANSFORMED_WIDTH; - - const uchar8 ys = Y[gid]; - - // 02 - // 13 - - __global uchar* outy0; - __global uchar* outy1; - if ((oy & 1) == 0) { - outy0 = out + out_offset; //y0 - outy1 = out + out_offset + UV_SIZE*2; //y2 - } else { - outy0 = out + out_offset + UV_SIZE; //y1 - outy1 = out + out_offset + UV_SIZE*3; //y3 - } - - vstore4(ys.s0246, 0, outy0 + (oy/2) * (TRANSFORMED_WIDTH/2) + ox/2); - vstore4(ys.s1357, 0, outy1 + (oy/2) * (TRANSFORMED_WIDTH/2) + ox/2); -} - -__kernel void loaduv(__global uchar8 const * const in, - __global uchar8 * out, - int out_offset) -{ - const int gid = get_global_id(0); - const uchar8 inv = in[gid]; - out[gid + out_offset / 8] = inv; -} - -__kernel void copy(__global uchar8 * in, - __global uchar8 * out, - int in_offset, - int out_offset) -{ - const int gid = get_global_id(0); - out[gid + out_offset / 8] = in[gid + in_offset / 8]; -} diff --git a/selfdrive/modeld/transforms/loadyuv.h b/selfdrive/modeld/transforms/loadyuv.h deleted file mode 100644 index 659059cd25..0000000000 --- a/selfdrive/modeld/transforms/loadyuv.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once - -#include "common/clutil.h" - -typedef struct { - int width, height; - cl_kernel loadys_krnl, loaduv_krnl, copy_krnl; -} LoadYUVState; - -void loadyuv_init(LoadYUVState* s, cl_context ctx, cl_device_id device_id, int width, int height); - -void loadyuv_destroy(LoadYUVState* s); - -void loadyuv_queue(LoadYUVState* s, cl_command_queue q, - cl_mem y_cl, cl_mem u_cl, cl_mem v_cl, - cl_mem out_cl); - - -void copy_queue(LoadYUVState* s, cl_command_queue q, cl_mem src, cl_mem dst, - size_t src_offset, size_t dst_offset, size_t size); \ No newline at end of file diff --git a/selfdrive/modeld/transforms/transform.cc b/selfdrive/modeld/transforms/transform.cc deleted file mode 100644 index 305643cf42..0000000000 --- a/selfdrive/modeld/transforms/transform.cc +++ /dev/null @@ -1,97 +0,0 @@ -#include "selfdrive/modeld/transforms/transform.h" - -#include -#include - -#include "common/clutil.h" - -void transform_init(Transform* s, cl_context ctx, cl_device_id device_id) { - memset(s, 0, sizeof(*s)); - - cl_program prg = cl_program_from_file(ctx, device_id, TRANSFORM_PATH, ""); - s->krnl = CL_CHECK_ERR(clCreateKernel(prg, "warpPerspective", &err)); - // done with this - CL_CHECK(clReleaseProgram(prg)); - - s->m_y_cl = CL_CHECK_ERR(clCreateBuffer(ctx, CL_MEM_READ_WRITE, 3*3*sizeof(float), NULL, &err)); - s->m_uv_cl = CL_CHECK_ERR(clCreateBuffer(ctx, CL_MEM_READ_WRITE, 3*3*sizeof(float), NULL, &err)); -} - -void transform_destroy(Transform* s) { - CL_CHECK(clReleaseMemObject(s->m_y_cl)); - CL_CHECK(clReleaseMemObject(s->m_uv_cl)); - CL_CHECK(clReleaseKernel(s->krnl)); -} - -void transform_queue(Transform* s, - cl_command_queue q, - cl_mem in_yuv, int in_width, int in_height, int in_stride, int in_uv_offset, - cl_mem out_y, cl_mem out_u, cl_mem out_v, - int out_width, int out_height, - const mat3& projection) { - const int zero = 0; - - // sampled using pixel center origin - // (because that's how fastcv and opencv does it) - - mat3 projection_y = projection; - - // in and out uv is half the size of y. - mat3 projection_uv = transform_scale_buffer(projection, 0.5); - - CL_CHECK(clEnqueueWriteBuffer(q, s->m_y_cl, CL_TRUE, 0, 3*3*sizeof(float), (void*)projection_y.v, 0, NULL, NULL)); - CL_CHECK(clEnqueueWriteBuffer(q, s->m_uv_cl, CL_TRUE, 0, 3*3*sizeof(float), (void*)projection_uv.v, 0, NULL, NULL)); - - const int in_y_width = in_width; - const int in_y_height = in_height; - const int in_y_px_stride = 1; - const int in_uv_width = in_width/2; - const int in_uv_height = in_height/2; - const int in_uv_px_stride = 2; - const int in_u_offset = in_uv_offset; - const int in_v_offset = in_uv_offset + 1; - - const int out_y_width = out_width; - const int out_y_height = out_height; - const int out_uv_width = out_width/2; - const int out_uv_height = out_height/2; - - CL_CHECK(clSetKernelArg(s->krnl, 0, sizeof(cl_mem), &in_yuv)); // src - CL_CHECK(clSetKernelArg(s->krnl, 1, sizeof(cl_int), &in_stride)); // src_row_stride - CL_CHECK(clSetKernelArg(s->krnl, 2, sizeof(cl_int), &in_y_px_stride)); // src_px_stride - CL_CHECK(clSetKernelArg(s->krnl, 3, sizeof(cl_int), &zero)); // src_offset - CL_CHECK(clSetKernelArg(s->krnl, 4, sizeof(cl_int), &in_y_height)); // src_rows - CL_CHECK(clSetKernelArg(s->krnl, 5, sizeof(cl_int), &in_y_width)); // src_cols - CL_CHECK(clSetKernelArg(s->krnl, 6, sizeof(cl_mem), &out_y)); // dst - CL_CHECK(clSetKernelArg(s->krnl, 7, sizeof(cl_int), &out_y_width)); // dst_row_stride - CL_CHECK(clSetKernelArg(s->krnl, 8, sizeof(cl_int), &zero)); // dst_offset - CL_CHECK(clSetKernelArg(s->krnl, 9, sizeof(cl_int), &out_y_height)); // dst_rows - CL_CHECK(clSetKernelArg(s->krnl, 10, sizeof(cl_int), &out_y_width)); // dst_cols - CL_CHECK(clSetKernelArg(s->krnl, 11, sizeof(cl_mem), &s->m_y_cl)); // M - - const size_t work_size_y[2] = {(size_t)out_y_width, (size_t)out_y_height}; - - CL_CHECK(clEnqueueNDRangeKernel(q, s->krnl, 2, NULL, - (const size_t*)&work_size_y, NULL, 0, 0, NULL)); - - const size_t work_size_uv[2] = {(size_t)out_uv_width, (size_t)out_uv_height}; - - CL_CHECK(clSetKernelArg(s->krnl, 2, sizeof(cl_int), &in_uv_px_stride)); // src_px_stride - CL_CHECK(clSetKernelArg(s->krnl, 3, sizeof(cl_int), &in_u_offset)); // src_offset - CL_CHECK(clSetKernelArg(s->krnl, 4, sizeof(cl_int), &in_uv_height)); // src_rows - CL_CHECK(clSetKernelArg(s->krnl, 5, sizeof(cl_int), &in_uv_width)); // src_cols - CL_CHECK(clSetKernelArg(s->krnl, 6, sizeof(cl_mem), &out_u)); // dst - CL_CHECK(clSetKernelArg(s->krnl, 7, sizeof(cl_int), &out_uv_width)); // dst_row_stride - CL_CHECK(clSetKernelArg(s->krnl, 8, sizeof(cl_int), &zero)); // dst_offset - CL_CHECK(clSetKernelArg(s->krnl, 9, sizeof(cl_int), &out_uv_height)); // dst_rows - CL_CHECK(clSetKernelArg(s->krnl, 10, sizeof(cl_int), &out_uv_width)); // dst_cols - CL_CHECK(clSetKernelArg(s->krnl, 11, sizeof(cl_mem), &s->m_uv_cl)); // M - - CL_CHECK(clEnqueueNDRangeKernel(q, s->krnl, 2, NULL, - (const size_t*)&work_size_uv, NULL, 0, 0, NULL)); - CL_CHECK(clSetKernelArg(s->krnl, 3, sizeof(cl_int), &in_v_offset)); // src_ofset - CL_CHECK(clSetKernelArg(s->krnl, 6, sizeof(cl_mem), &out_v)); // dst - - CL_CHECK(clEnqueueNDRangeKernel(q, s->krnl, 2, NULL, - (const size_t*)&work_size_uv, NULL, 0, 0, NULL)); -} diff --git a/selfdrive/modeld/transforms/transform.cl b/selfdrive/modeld/transforms/transform.cl deleted file mode 100644 index 2ca25920cd..0000000000 --- a/selfdrive/modeld/transforms/transform.cl +++ /dev/null @@ -1,54 +0,0 @@ -#define INTER_BITS 5 -#define INTER_TAB_SIZE (1 << INTER_BITS) -#define INTER_SCALE 1.f / INTER_TAB_SIZE - -#define INTER_REMAP_COEF_BITS 15 -#define INTER_REMAP_COEF_SCALE (1 << INTER_REMAP_COEF_BITS) - -__kernel void warpPerspective(__global const uchar * src, - int src_row_stride, int src_px_stride, int src_offset, int src_rows, int src_cols, - __global uchar * dst, - int dst_row_stride, int dst_offset, int dst_rows, int dst_cols, - __constant float * M) -{ - int dx = get_global_id(0); - int dy = get_global_id(1); - - if (dx < dst_cols && dy < dst_rows) - { - float X0 = M[0] * dx + M[1] * dy + M[2]; - float Y0 = M[3] * dx + M[4] * dy + M[5]; - float W = M[6] * dx + M[7] * dy + M[8]; - W = W != 0.0f ? INTER_TAB_SIZE / W : 0.0f; - int X = rint(X0 * W), Y = rint(Y0 * W); - - int sx = convert_short_sat(X >> INTER_BITS); - int sy = convert_short_sat(Y >> INTER_BITS); - - short sx_clamp = clamp(sx, 0, src_cols - 1); - short sx_p1_clamp = clamp(sx + 1, 0, src_cols - 1); - short sy_clamp = clamp(sy, 0, src_rows - 1); - short sy_p1_clamp = clamp(sy + 1, 0, src_rows - 1); - int v0 = convert_int(src[mad24(sy_clamp, src_row_stride, src_offset + sx_clamp*src_px_stride)]); - int v1 = convert_int(src[mad24(sy_clamp, src_row_stride, src_offset + sx_p1_clamp*src_px_stride)]); - int v2 = convert_int(src[mad24(sy_p1_clamp, src_row_stride, src_offset + sx_clamp*src_px_stride)]); - int v3 = convert_int(src[mad24(sy_p1_clamp, src_row_stride, src_offset + sx_p1_clamp*src_px_stride)]); - - short ay = (short)(Y & (INTER_TAB_SIZE - 1)); - short ax = (short)(X & (INTER_TAB_SIZE - 1)); - float taby = 1.f/INTER_TAB_SIZE*ay; - float tabx = 1.f/INTER_TAB_SIZE*ax; - - int dst_index = mad24(dy, dst_row_stride, dst_offset + dx); - - int itab0 = convert_short_sat_rte( (1.0f-taby)*(1.0f-tabx) * INTER_REMAP_COEF_SCALE ); - int itab1 = convert_short_sat_rte( (1.0f-taby)*tabx * INTER_REMAP_COEF_SCALE ); - int itab2 = convert_short_sat_rte( taby*(1.0f-tabx) * INTER_REMAP_COEF_SCALE ); - int itab3 = convert_short_sat_rte( taby*tabx * INTER_REMAP_COEF_SCALE ); - - int val = v0 * itab0 + v1 * itab1 + v2 * itab2 + v3 * itab3; - - uchar pix = convert_uchar_sat((val + (1 << (INTER_REMAP_COEF_BITS-1))) >> INTER_REMAP_COEF_BITS); - dst[dst_index] = pix; - } -} diff --git a/selfdrive/modeld/transforms/transform.h b/selfdrive/modeld/transforms/transform.h deleted file mode 100644 index 771a7054b3..0000000000 --- a/selfdrive/modeld/transforms/transform.h +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once - -#define CL_USE_DEPRECATED_OPENCL_1_2_APIS -#ifdef __APPLE__ -#include -#else -#include -#endif - -#include "common/mat.h" - -typedef struct { - cl_kernel krnl; - cl_mem m_y_cl, m_uv_cl; -} Transform; - -void transform_init(Transform* s, cl_context ctx, cl_device_id device_id); - -void transform_destroy(Transform* transform); - -void transform_queue(Transform* s, cl_command_queue q, - cl_mem yuv, int in_width, int in_height, int in_stride, int in_uv_offset, - cl_mem out_y, cl_mem out_u, cl_mem out_v, - int out_width, int out_height, - const mat3& projection); diff --git a/selfdrive/monitoring/README.md b/selfdrive/monitoring/README.md deleted file mode 100644 index 2a29ea06b5..0000000000 --- a/selfdrive/monitoring/README.md +++ /dev/null @@ -1,15 +0,0 @@ -# driver monitoring (DM) - -Uploading driver-facing camera footage is opt-in, but it is encouraged to opt-in to improve the DM model. You can always change your preference using the "Record and Upload Driver Camera" toggle. - -## Troubleshooting - -Before creating a bug report, go through these troubleshooting steps. - -* Ensure the driver-facing camera has a good view of the driver in normal driving positions. - * This can be checked in Settings -> Device -> Preview Driver Camera (when car is off). -* If the camera can't see the driver, the device should be re-mounted. - -## Bug report - -In order for us to look into DM bug reports, we'll need the driver-facing camera footage. If you don't normally have this enabled, simply enable the toggle for a single drive. Also ensure the "Upload Raw Logs" toggle is enabled before going for a drive. diff --git a/selfdrive/monitoring/dmonitoringd.py b/selfdrive/monitoring/dmonitoringd.py deleted file mode 100755 index 71733f99fc..0000000000 --- a/selfdrive/monitoring/dmonitoringd.py +++ /dev/null @@ -1,48 +0,0 @@ -#!/usr/bin/env python3 -import cereal.messaging as messaging -from openpilot.common.params import Params -from openpilot.common.realtime import config_realtime_process -from openpilot.selfdrive.monitoring.helpers import DriverMonitoring - - -def dmonitoringd_thread(): - config_realtime_process([0, 1, 2, 3], 5) - - params = Params() - pm = messaging.PubMaster(['driverMonitoringState']) - sm = messaging.SubMaster(['driverStateV2', 'liveCalibration', 'carState', 'selfdriveState', 'modelV2', - 'carControl'], poll='driverStateV2') - - DM = DriverMonitoring(rhd_saved=params.get_bool("IsRhdDetected"), always_on=params.get_bool("AlwaysOnDM")) - - # 20Hz <- dmonitoringmodeld - while True: - sm.update() - if not sm.updated['driverStateV2']: - # iterate when model has new output - continue - - valid = sm.all_checks() - if valid: - DM.run_step(sm) - - # publish - dat = DM.get_state_packet(valid=valid) - pm.send('driverMonitoringState', dat) - - # load live always-on toggle - if sm['driverStateV2'].frameId % 40 == 1: - DM.always_on = params.get_bool("AlwaysOnDM") - - # save rhd virtual toggle every 5 mins - if (sm['driverStateV2'].frameId % 6000 == 0 and - DM.wheelpos_learner.filtered_stat.n > DM.settings._WHEELPOS_FILTER_MIN_COUNT and - DM.wheel_on_right == (DM.wheelpos_learner.filtered_stat.M > DM.settings._WHEELPOS_THRESHOLD)): - params.put_bool_nonblocking("IsRhdDetected", DM.wheel_on_right) - -def main(): - dmonitoringd_thread() - - -if __name__ == '__main__': - main() diff --git a/selfdrive/monitoring/helpers.py b/selfdrive/monitoring/helpers.py deleted file mode 100644 index 67776994f0..0000000000 --- a/selfdrive/monitoring/helpers.py +++ /dev/null @@ -1,416 +0,0 @@ -from math import atan2 -import numpy as np - -from cereal import car, log -import cereal.messaging as messaging -from openpilot.selfdrive.selfdrived.events import Events -from openpilot.common.realtime import DT_DMON -from openpilot.common.filter_simple import FirstOrderFilter -from openpilot.common.stat_live import RunningStatFilter -from openpilot.common.transformations.camera import DEVICE_CAMERAS - -EventName = log.OnroadEvent.EventName - -# ****************************************************************************************** -# NOTE: To fork maintainers. -# Disabling or nerfing safety features will get you and your users banned from our servers. -# We recommend that you do not change these numbers from the defaults. -# ****************************************************************************************** - -class DRIVER_MONITOR_SETTINGS: - def __init__(self): - self._DT_DMON = DT_DMON - # ref (page15-16): https://eur-lex.europa.eu/legal-content/EN/TXT/PDF/?uri=CELEX:42018X1947&rid=2 - self._AWARENESS_TIME = 30. # passive wheeltouch total timeout - self._AWARENESS_PRE_TIME_TILL_TERMINAL = 15. - self._AWARENESS_PROMPT_TIME_TILL_TERMINAL = 6. - self._DISTRACTED_TIME = 11. # active monitoring total timeout - self._DISTRACTED_PRE_TIME_TILL_TERMINAL = 8. - self._DISTRACTED_PROMPT_TIME_TILL_TERMINAL = 6. - - self._FACE_THRESHOLD = 0.7 - self._EYE_THRESHOLD = 0.65 - self._SG_THRESHOLD = 0.9 - self._BLINK_THRESHOLD = 0.865 - - self._EE_THRESH11 = 0.4 - self._EE_THRESH12 = 15.0 - self._EE_MAX_OFFSET1 = 0.06 - self._EE_MIN_OFFSET1 = 0.025 - self._EE_THRESH21 = 0.01 - self._EE_THRESH22 = 0.35 - - self._POSE_PITCH_THRESHOLD = 0.3133 - self._POSE_PITCH_THRESHOLD_SLACK = 0.3237 - self._POSE_PITCH_THRESHOLD_STRICT = self._POSE_PITCH_THRESHOLD - self._POSE_YAW_THRESHOLD = 0.4020 - self._POSE_YAW_THRESHOLD_SLACK = 0.5042 - self._POSE_YAW_THRESHOLD_STRICT = self._POSE_YAW_THRESHOLD - self._PITCH_NATURAL_OFFSET = 0.029 # initial value before offset is learned - self._PITCH_NATURAL_THRESHOLD = 0.449 - self._YAW_NATURAL_OFFSET = 0.097 # initial value before offset is learned - self._PITCH_MAX_OFFSET = 0.124 - self._PITCH_MIN_OFFSET = -0.0881 - self._YAW_MAX_OFFSET = 0.289 - self._YAW_MIN_OFFSET = -0.0246 - - self._POSESTD_THRESHOLD = 0.3 - self._HI_STD_FALLBACK_TIME = int(10 / self._DT_DMON) # fall back to wheel touch if model is uncertain for 10s - self._DISTRACTED_FILTER_TS = 0.25 # 0.6Hz - self._ALWAYS_ON_ALERT_MIN_SPEED = 11 - - self._POSE_CALIB_MIN_SPEED = 13 # 30 mph - self._POSE_OFFSET_MIN_COUNT = int(60 / self._DT_DMON) # valid data counts before calibration completes, 1min cumulative - self._POSE_OFFSET_MAX_COUNT = int(360 / self._DT_DMON) # stop deweighting new data after 6 min, aka "short term memory" - - self._WHEELPOS_CALIB_MIN_SPEED = 11 - self._WHEELPOS_THRESHOLD = 0.5 - self._WHEELPOS_FILTER_MIN_COUNT = int(15 / self._DT_DMON) # allow 15 seconds to converge wheel side - - self._RECOVERY_FACTOR_MAX = 5. # relative to minus step change - self._RECOVERY_FACTOR_MIN = 1.25 # relative to minus step change - - self._MAX_TERMINAL_ALERTS = 3 # not allowed to engage after 3 terminal alerts - self._MAX_TERMINAL_DURATION = int(30 / self._DT_DMON) # not allowed to engage after 30s of terminal alerts - -class DistractedType: - NOT_DISTRACTED = 0 - DISTRACTED_POSE = 1 << 0 - DISTRACTED_BLINK = 1 << 1 - DISTRACTED_E2E = 1 << 2 - -class DriverPose: - def __init__(self, max_trackable): - self.yaw = 0. - self.pitch = 0. - self.roll = 0. - self.yaw_std = 0. - self.pitch_std = 0. - self.roll_std = 0. - self.pitch_offseter = RunningStatFilter(max_trackable=max_trackable) - self.yaw_offseter = RunningStatFilter(max_trackable=max_trackable) - self.calibrated = False - self.low_std = True - self.cfactor_pitch = 1. - self.cfactor_yaw = 1. - -class DriverBlink: - def __init__(self): - self.left = 0. - self.right = 0. - - -# model output refers to center of undistorted+leveled image -EFL = 598.0 # focal length in K -cam = DEVICE_CAMERAS[("tici", "ar0231")] # corrected image has same size as raw -W, H = (cam.dcam.width, cam.dcam.height) # corrected image has same size as raw - -def face_orientation_from_net(angles_desc, pos_desc, rpy_calib): - # the output of these angles are in device frame - # so from driver's perspective, pitch is up and yaw is right - - pitch_net, yaw_net, roll_net = angles_desc - - face_pixel_position = ((pos_desc[0]+0.5)*W, (pos_desc[1]+0.5)*H) - yaw_focal_angle = atan2(face_pixel_position[0] - W//2, EFL) - pitch_focal_angle = atan2(face_pixel_position[1] - H//2, EFL) - - pitch = pitch_net + pitch_focal_angle - yaw = -yaw_net + yaw_focal_angle - - # no calib for roll - pitch -= rpy_calib[1] - yaw -= rpy_calib[2] - return roll_net, pitch, yaw - - -class DriverMonitoring: - def __init__(self, rhd_saved=False, settings=None, always_on=False): - if settings is None: - settings = DRIVER_MONITOR_SETTINGS() - # init policy settings - self.settings = settings - - # init driver status - self.wheelpos_learner = RunningStatFilter() - self.pose = DriverPose(self.settings._POSE_OFFSET_MAX_COUNT) - self.blink = DriverBlink() - self.eev1 = 0. - self.eev2 = 1. - self.ee1_offseter = RunningStatFilter(max_trackable=self.settings._POSE_OFFSET_MAX_COUNT) - self.ee2_offseter = RunningStatFilter(max_trackable=self.settings._POSE_OFFSET_MAX_COUNT) - self.ee1_calibrated = False - self.ee2_calibrated = False - - self.always_on = always_on - self.distracted_types = [] - self.driver_distracted = False - self.driver_distraction_filter = FirstOrderFilter(0., self.settings._DISTRACTED_FILTER_TS, self.settings._DT_DMON) - self.wheel_on_right = False - self.wheel_on_right_last = None - self.wheel_on_right_default = rhd_saved - self.face_detected = False - self.terminal_alert_cnt = 0 - self.terminal_time = 0 - self.step_change = 0. - self.active_monitoring_mode = True - self.is_model_uncertain = False - self.hi_stds = 0 - self.threshold_pre = self.settings._DISTRACTED_PRE_TIME_TILL_TERMINAL / self.settings._DISTRACTED_TIME - self.threshold_prompt = self.settings._DISTRACTED_PROMPT_TIME_TILL_TERMINAL / self.settings._DISTRACTED_TIME - - self._reset_awareness() - self._set_timers(active_monitoring=True) - self._reset_events() - - def _reset_awareness(self): - self.awareness = 1. - self.awareness_active = 1. - self.awareness_passive = 1. - - def _reset_events(self): - self.current_events = Events() - - def _set_timers(self, active_monitoring): - if self.active_monitoring_mode and self.awareness <= self.threshold_prompt: - if active_monitoring: - self.step_change = self.settings._DT_DMON / self.settings._DISTRACTED_TIME - else: - self.step_change = 0. - return # no exploit after orange alert - elif self.awareness <= 0.: - return - - if active_monitoring: - # when falling back from passive mode to active mode, reset awareness to avoid false alert - if not self.active_monitoring_mode: - self.awareness_passive = self.awareness - self.awareness = self.awareness_active - - self.threshold_pre = self.settings._DISTRACTED_PRE_TIME_TILL_TERMINAL / self.settings._DISTRACTED_TIME - self.threshold_prompt = self.settings._DISTRACTED_PROMPT_TIME_TILL_TERMINAL / self.settings._DISTRACTED_TIME - self.step_change = self.settings._DT_DMON / self.settings._DISTRACTED_TIME - self.active_monitoring_mode = True - else: - if self.active_monitoring_mode: - self.awareness_active = self.awareness - self.awareness = self.awareness_passive - - self.threshold_pre = self.settings._AWARENESS_PRE_TIME_TILL_TERMINAL / self.settings._AWARENESS_TIME - self.threshold_prompt = self.settings._AWARENESS_PROMPT_TIME_TILL_TERMINAL / self.settings._AWARENESS_TIME - self.step_change = self.settings._DT_DMON / self.settings._AWARENESS_TIME - self.active_monitoring_mode = False - - def _set_policy(self, model_data, car_speed): - bp = model_data.meta.disengagePredictions.brakeDisengageProbs[0] # brake disengage prob in next 2s - k1 = max(-0.00156*((car_speed-16)**2)+0.6, 0.2) - bp_normal = max(min(bp / k1, 0.5),0) - self.pose.cfactor_pitch = np.interp(bp_normal, [0, 0.5], - [self.settings._POSE_PITCH_THRESHOLD_SLACK, - self.settings._POSE_PITCH_THRESHOLD_STRICT]) / self.settings._POSE_PITCH_THRESHOLD - self.pose.cfactor_yaw = np.interp(bp_normal, [0, 0.5], - [self.settings._POSE_YAW_THRESHOLD_SLACK, - self.settings._POSE_YAW_THRESHOLD_STRICT]) / self.settings._POSE_YAW_THRESHOLD - - def _get_distracted_types(self): - distracted_types = [] - - if not self.pose.calibrated: - pitch_error = self.pose.pitch - self.settings._PITCH_NATURAL_OFFSET - yaw_error = self.pose.yaw - self.settings._YAW_NATURAL_OFFSET - else: - pitch_error = self.pose.pitch - min(max(self.pose.pitch_offseter.filtered_stat.mean(), - self.settings._PITCH_MIN_OFFSET), self.settings._PITCH_MAX_OFFSET) - yaw_error = self.pose.yaw - min(max(self.pose.yaw_offseter.filtered_stat.mean(), - self.settings._YAW_MIN_OFFSET), self.settings._YAW_MAX_OFFSET) - pitch_error = 0 if pitch_error > 0 else abs(pitch_error) # no positive pitch limit - yaw_error = abs(yaw_error) - if pitch_error > (self.settings._POSE_PITCH_THRESHOLD*self.pose.cfactor_pitch if self.pose.calibrated else self.settings._PITCH_NATURAL_THRESHOLD) or \ - yaw_error > self.settings._POSE_YAW_THRESHOLD*self.pose.cfactor_yaw: - distracted_types.append(DistractedType.DISTRACTED_POSE) - - if (self.blink.left + self.blink.right)*0.5 > self.settings._BLINK_THRESHOLD: - distracted_types.append(DistractedType.DISTRACTED_BLINK) - - if self.ee1_calibrated: - ee1_dist = self.eev1 > max(min(self.ee1_offseter.filtered_stat.M, self.settings._EE_MAX_OFFSET1), self.settings._EE_MIN_OFFSET1) \ - * self.settings._EE_THRESH12 - else: - ee1_dist = self.eev1 > self.settings._EE_THRESH11 - if ee1_dist: - distracted_types.append(DistractedType.DISTRACTED_E2E) - - return distracted_types - - def _update_states(self, driver_state, cal_rpy, car_speed, op_engaged): - rhd_pred = driver_state.wheelOnRightProb - # calibrates only when there's movement and either face detected - if car_speed > self.settings._WHEELPOS_CALIB_MIN_SPEED and (driver_state.leftDriverData.faceProb > self.settings._FACE_THRESHOLD or - driver_state.rightDriverData.faceProb > self.settings._FACE_THRESHOLD): - self.wheelpos_learner.push_and_update(rhd_pred) - if self.wheelpos_learner.filtered_stat.n > self.settings._WHEELPOS_FILTER_MIN_COUNT: - self.wheel_on_right = self.wheelpos_learner.filtered_stat.M > self.settings._WHEELPOS_THRESHOLD - else: - self.wheel_on_right = self.wheel_on_right_default # use default/saved if calibration is unfinished - # make sure no switching when engaged - if op_engaged and self.wheel_on_right_last is not None and self.wheel_on_right_last != self.wheel_on_right: - self.wheel_on_right = self.wheel_on_right_last - driver_data = driver_state.rightDriverData if self.wheel_on_right else driver_state.leftDriverData - if not all(len(x) > 0 for x in (driver_data.faceOrientation, driver_data.facePosition, - driver_data.faceOrientationStd, driver_data.facePositionStd, - driver_data.readyProb, driver_data.notReadyProb)): - return - - self.face_detected = driver_data.faceProb > self.settings._FACE_THRESHOLD - self.pose.roll, self.pose.pitch, self.pose.yaw = face_orientation_from_net(driver_data.faceOrientation, driver_data.facePosition, cal_rpy) - if self.wheel_on_right: - self.pose.yaw *= -1 - self.wheel_on_right_last = self.wheel_on_right - self.pose.pitch_std = driver_data.faceOrientationStd[0] - self.pose.yaw_std = driver_data.faceOrientationStd[1] - model_std_max = max(self.pose.pitch_std, self.pose.yaw_std) - self.pose.low_std = model_std_max < self.settings._POSESTD_THRESHOLD - self.blink.left = driver_data.leftBlinkProb * (driver_data.leftEyeProb > self.settings._EYE_THRESHOLD) \ - * (driver_data.sunglassesProb < self.settings._SG_THRESHOLD) - self.blink.right = driver_data.rightBlinkProb * (driver_data.rightEyeProb > self.settings._EYE_THRESHOLD) \ - * (driver_data.sunglassesProb < self.settings._SG_THRESHOLD) - self.eev1 = driver_data.notReadyProb[0] - self.eev2 = driver_data.readyProb[0] - - self.distracted_types = self._get_distracted_types() - self.driver_distracted = (DistractedType.DISTRACTED_E2E in self.distracted_types or DistractedType.DISTRACTED_POSE in self.distracted_types - or DistractedType.DISTRACTED_BLINK in self.distracted_types) \ - and driver_data.faceProb > self.settings._FACE_THRESHOLD and self.pose.low_std - self.driver_distraction_filter.update(self.driver_distracted) - - # update offseter - # only update when driver is actively driving the car above a certain speed - if self.face_detected and car_speed > self.settings._POSE_CALIB_MIN_SPEED and self.pose.low_std and (not op_engaged or not self.driver_distracted): - self.pose.pitch_offseter.push_and_update(self.pose.pitch) - self.pose.yaw_offseter.push_and_update(self.pose.yaw) - self.ee1_offseter.push_and_update(self.eev1) - self.ee2_offseter.push_and_update(self.eev2) - - self.pose.calibrated = self.pose.pitch_offseter.filtered_stat.n > self.settings._POSE_OFFSET_MIN_COUNT and \ - self.pose.yaw_offseter.filtered_stat.n > self.settings._POSE_OFFSET_MIN_COUNT - self.ee1_calibrated = self.ee1_offseter.filtered_stat.n > self.settings._POSE_OFFSET_MIN_COUNT - self.ee2_calibrated = self.ee2_offseter.filtered_stat.n > self.settings._POSE_OFFSET_MIN_COUNT - - self.is_model_uncertain = self.hi_stds > self.settings._HI_STD_FALLBACK_TIME - self._set_timers(self.face_detected and not self.is_model_uncertain) - if self.face_detected and not self.pose.low_std and not self.driver_distracted: - self.hi_stds += 1 - elif self.face_detected and self.pose.low_std: - self.hi_stds = 0 - - def _update_events(self, driver_engaged, op_engaged, standstill, wrong_gear, car_speed): - self._reset_events() - # Block engaging after max number of distrations or when alert active - if self.terminal_alert_cnt >= self.settings._MAX_TERMINAL_ALERTS or \ - self.terminal_time >= self.settings._MAX_TERMINAL_DURATION or \ - self.always_on and self.awareness <= self.threshold_prompt: - self.current_events.add(EventName.tooDistracted) - - always_on_valid = self.always_on and not wrong_gear - if (driver_engaged and self.awareness > 0 and not self.active_monitoring_mode) or \ - (not always_on_valid and not op_engaged) or \ - (always_on_valid and not op_engaged and self.awareness <= 0): - # always reset on disengage with normal mode; disengage resets only on red if always on - self._reset_awareness() - return - - driver_attentive = self.driver_distraction_filter.x < 0.37 - awareness_prev = self.awareness - - if (driver_attentive and self.face_detected and self.pose.low_std and self.awareness > 0): - if driver_engaged: - self._reset_awareness() - return - # only restore awareness when paying attention and alert is not red - self.awareness = min(self.awareness + ((self.settings._RECOVERY_FACTOR_MAX-self.settings._RECOVERY_FACTOR_MIN)* - (1.-self.awareness)+self.settings._RECOVERY_FACTOR_MIN)*self.step_change, 1.) - if self.awareness == 1.: - self.awareness_passive = min(self.awareness_passive + self.step_change, 1.) - # don't display alert banner when awareness is recovering and has cleared orange - if self.awareness > self.threshold_prompt: - return - - _reaching_audible = self.awareness - self.step_change <= self.threshold_prompt - _reaching_terminal = self.awareness - self.step_change <= 0 - standstill_orange_exemption = standstill and _reaching_audible - always_on_red_exemption = always_on_valid and not op_engaged and _reaching_terminal - always_on_lowspeed_exemption = always_on_valid and not op_engaged and car_speed < self.settings._ALWAYS_ON_ALERT_MIN_SPEED - - certainly_distracted = self.driver_distraction_filter.x > 0.63 and self.driver_distracted and self.face_detected - maybe_distracted = self.hi_stds > self.settings._HI_STD_FALLBACK_TIME or not self.face_detected - - if certainly_distracted or maybe_distracted: - # should always be counting if distracted unless at standstill (lowspeed for always-on) and reaching orange - # also will not be reaching 0 if DM is active when not engaged - if not (standstill_orange_exemption or always_on_red_exemption or (always_on_lowspeed_exemption and _reaching_audible)): - self.awareness = max(self.awareness - self.step_change, -0.1) - - alert = None - if self.awareness <= 0.: - # terminal red alert: disengagement required - alert = EventName.driverDistracted if self.active_monitoring_mode else EventName.driverUnresponsive - self.terminal_time += 1 - if awareness_prev > 0.: - self.terminal_alert_cnt += 1 - elif self.awareness <= self.threshold_prompt: - # prompt orange alert - alert = EventName.promptDriverDistracted if self.active_monitoring_mode else EventName.promptDriverUnresponsive - elif self.awareness <= self.threshold_pre and not always_on_lowspeed_exemption: - # pre green alert - alert = EventName.preDriverDistracted if self.active_monitoring_mode else EventName.preDriverUnresponsive - - if alert is not None: - self.current_events.add(alert) - - - def get_state_packet(self, valid=True): - # build driverMonitoringState packet - dat = messaging.new_message('driverMonitoringState', valid=valid) - dat.driverMonitoringState = { - "events": self.current_events.to_msg(), - "faceDetected": self.face_detected, - "isDistracted": self.driver_distracted, - "distractedType": sum(self.distracted_types), - "awarenessStatus": self.awareness, - "posePitchOffset": self.pose.pitch_offseter.filtered_stat.mean(), - "posePitchValidCount": self.pose.pitch_offseter.filtered_stat.n, - "poseYawOffset": self.pose.yaw_offseter.filtered_stat.mean(), - "poseYawValidCount": self.pose.yaw_offseter.filtered_stat.n, - "stepChange": self.step_change, - "awarenessActive": self.awareness_active, - "awarenessPassive": self.awareness_passive, - "isLowStd": self.pose.low_std, - "hiStdCount": self.hi_stds, - "isActiveMode": self.active_monitoring_mode, - "isRHD": self.wheel_on_right, - } - return dat - - def run_step(self, sm): - # Set strictness - self._set_policy( - model_data=sm['modelV2'], - car_speed=sm['carState'].vEgo - ) - - # Parse data from dmonitoringmodeld - self._update_states( - driver_state=sm['driverStateV2'], - cal_rpy=sm['liveCalibration'].rpyCalib, - car_speed=sm['carState'].vEgo, - op_engaged=sm['selfdriveState'].enabled or sm['carControl'].latActive - ) - - # Update distraction events - self._update_events( - driver_engaged=sm['carState'].steeringPressed or sm['carState'].gasPressed, - op_engaged=sm['selfdriveState'].enabled or sm['carControl'].latActive, - standstill=sm['carState'].standstill, - wrong_gear=sm['carState'].gearShifter in [car.CarState.GearShifter.reverse, car.CarState.GearShifter.park], - car_speed=sm['carState'].vEgo - ) diff --git a/selfdrive/monitoring/test_monitoring.py b/selfdrive/monitoring/test_monitoring.py deleted file mode 100644 index 2a20b20dc1..0000000000 --- a/selfdrive/monitoring/test_monitoring.py +++ /dev/null @@ -1,206 +0,0 @@ -import numpy as np - -from cereal import log -from openpilot.common.realtime import DT_DMON -from openpilot.selfdrive.monitoring.helpers import DriverMonitoring, DRIVER_MONITOR_SETTINGS - -EventName = log.OnroadEvent.EventName -dm_settings = DRIVER_MONITOR_SETTINGS() - -TEST_TIMESPAN = 120 # seconds -DISTRACTED_SECONDS_TO_ORANGE = dm_settings._DISTRACTED_TIME - dm_settings._DISTRACTED_PROMPT_TIME_TILL_TERMINAL + 1 -DISTRACTED_SECONDS_TO_RED = dm_settings._DISTRACTED_TIME + 1 -INVISIBLE_SECONDS_TO_ORANGE = dm_settings._AWARENESS_TIME - dm_settings._AWARENESS_PROMPT_TIME_TILL_TERMINAL + 1 -INVISIBLE_SECONDS_TO_RED = dm_settings._AWARENESS_TIME + 1 - -def make_msg(face_detected, distracted=False, model_uncertain=False): - ds = log.DriverStateV2.new_message() - ds.leftDriverData.faceOrientation = [0., 0., 0.] - ds.leftDriverData.facePosition = [0., 0.] - ds.leftDriverData.faceProb = 1. * face_detected - ds.leftDriverData.leftEyeProb = 1. - ds.leftDriverData.rightEyeProb = 1. - ds.leftDriverData.leftBlinkProb = 1. * distracted - ds.leftDriverData.rightBlinkProb = 1. * distracted - ds.leftDriverData.faceOrientationStd = [1.*model_uncertain, 1.*model_uncertain, 1.*model_uncertain] - ds.leftDriverData.facePositionStd = [1.*model_uncertain, 1.*model_uncertain] - # TODO: test both separately when e2e is used - ds.leftDriverData.readyProb = [0., 0., 0., 0.] - ds.leftDriverData.notReadyProb = [0., 0.] - return ds - - -# driver state from neural net, 10Hz -msg_NO_FACE_DETECTED = make_msg(False) -msg_ATTENTIVE = make_msg(True) -msg_DISTRACTED = make_msg(True, distracted=True) -msg_ATTENTIVE_UNCERTAIN = make_msg(True, model_uncertain=True) -msg_DISTRACTED_UNCERTAIN = make_msg(True, distracted=True, model_uncertain=True) -msg_DISTRACTED_BUT_SOMEHOW_UNCERTAIN = make_msg(True, distracted=True, model_uncertain=dm_settings._POSESTD_THRESHOLD*1.5) - -# driver interaction with car -car_interaction_DETECTED = True -car_interaction_NOT_DETECTED = False - -# some common state vectors -always_no_face = [msg_NO_FACE_DETECTED] * int(TEST_TIMESPAN / DT_DMON) -always_attentive = [msg_ATTENTIVE] * int(TEST_TIMESPAN / DT_DMON) -always_distracted = [msg_DISTRACTED] * int(TEST_TIMESPAN / DT_DMON) -always_true = [True] * int(TEST_TIMESPAN / DT_DMON) -always_false = [False] * int(TEST_TIMESPAN / DT_DMON) - -class TestMonitoring: - def _run_seq(self, msgs, interaction, engaged, standstill): - DM = DriverMonitoring() - events = [] - for idx in range(len(msgs)): - DM._update_states(msgs[idx], [0, 0, 0], 0, engaged[idx]) - # cal_rpy and car_speed don't matter here - - # evaluate events at 10Hz for tests - DM._update_events(interaction[idx], engaged[idx], standstill[idx], 0, 0) - events.append(DM.current_events) - assert len(events) == len(msgs), f"got {len(events)} for {len(msgs)} driverState input msgs" - return events, DM - - def _assert_no_events(self, events): - assert all(not len(e) for e in events) - - # engaged, driver is attentive all the time - def test_fully_aware_driver(self): - events, _ = self._run_seq(always_attentive, always_false, always_true, always_false) - self._assert_no_events(events) - - # engaged, driver is distracted and does nothing - def test_fully_distracted_driver(self): - events, d_status = self._run_seq(always_distracted, always_false, always_true, always_false) - assert len(events[int((d_status.settings._DISTRACTED_TIME-d_status.settings._DISTRACTED_PRE_TIME_TILL_TERMINAL)/2/DT_DMON)]) == 0 - assert events[int((d_status.settings._DISTRACTED_TIME-d_status.settings._DISTRACTED_PRE_TIME_TILL_TERMINAL + \ - ((d_status.settings._DISTRACTED_PRE_TIME_TILL_TERMINAL-d_status.settings._DISTRACTED_PROMPT_TIME_TILL_TERMINAL)/2))/DT_DMON)].names[0] == \ - EventName.preDriverDistracted - assert events[int((d_status.settings._DISTRACTED_TIME-d_status.settings._DISTRACTED_PROMPT_TIME_TILL_TERMINAL + \ - ((d_status.settings._DISTRACTED_PROMPT_TIME_TILL_TERMINAL)/2))/DT_DMON)].names[0] == EventName.promptDriverDistracted - assert events[int((d_status.settings._DISTRACTED_TIME + \ - ((TEST_TIMESPAN-10-d_status.settings._DISTRACTED_TIME)/2))/DT_DMON)].names[0] == EventName.driverDistracted - assert isinstance(d_status.awareness, float) - - # engaged, no face detected the whole time, no action - def test_fully_invisible_driver(self): - events, d_status = self._run_seq(always_no_face, always_false, always_true, always_false) - assert len(events[int((d_status.settings._AWARENESS_TIME-d_status.settings._AWARENESS_PRE_TIME_TILL_TERMINAL)/2/DT_DMON)]) == 0 - assert events[int((d_status.settings._AWARENESS_TIME-d_status.settings._AWARENESS_PRE_TIME_TILL_TERMINAL + \ - ((d_status.settings._AWARENESS_PRE_TIME_TILL_TERMINAL-d_status.settings._AWARENESS_PROMPT_TIME_TILL_TERMINAL)/2))/DT_DMON)].names[0] == \ - EventName.preDriverUnresponsive - assert events[int((d_status.settings._AWARENESS_TIME-d_status.settings._AWARENESS_PROMPT_TIME_TILL_TERMINAL + \ - ((d_status.settings._AWARENESS_PROMPT_TIME_TILL_TERMINAL)/2))/DT_DMON)].names[0] == EventName.promptDriverUnresponsive - assert events[int((d_status.settings._AWARENESS_TIME + \ - ((TEST_TIMESPAN-10-d_status.settings._AWARENESS_TIME)/2))/DT_DMON)].names[0] == EventName.driverUnresponsive - - # engaged, down to orange, driver pays attention, back to normal; then down to orange, driver touches wheel - # - should have short orange recovery time and no green afterwards; wheel touch only recovers when paying attention - def test_normal_driver(self): - ds_vector = [msg_DISTRACTED] * int(DISTRACTED_SECONDS_TO_ORANGE/DT_DMON) + \ - [msg_ATTENTIVE] * int(DISTRACTED_SECONDS_TO_ORANGE/DT_DMON) + \ - [msg_DISTRACTED] * int((DISTRACTED_SECONDS_TO_ORANGE+2)/DT_DMON) + \ - [msg_ATTENTIVE] * (int(TEST_TIMESPAN/DT_DMON)-int((DISTRACTED_SECONDS_TO_ORANGE*3+2)/DT_DMON)) - interaction_vector = [car_interaction_NOT_DETECTED] * int(DISTRACTED_SECONDS_TO_ORANGE*3/DT_DMON) + \ - [car_interaction_DETECTED] * (int(TEST_TIMESPAN/DT_DMON)-int(DISTRACTED_SECONDS_TO_ORANGE*3/DT_DMON)) - events, _ = self._run_seq(ds_vector, interaction_vector, always_true, always_false) - assert len(events[int(DISTRACTED_SECONDS_TO_ORANGE*0.5/DT_DMON)]) == 0 - assert events[int((DISTRACTED_SECONDS_TO_ORANGE-0.1)/DT_DMON)].names[0] == EventName.promptDriverDistracted - assert len(events[int(DISTRACTED_SECONDS_TO_ORANGE*1.5/DT_DMON)]) == 0 - assert events[int((DISTRACTED_SECONDS_TO_ORANGE*3-0.1)/DT_DMON)].names[0] == EventName.promptDriverDistracted - assert events[int((DISTRACTED_SECONDS_TO_ORANGE*3+0.1)/DT_DMON)].names[0] == EventName.promptDriverDistracted - assert len(events[int((DISTRACTED_SECONDS_TO_ORANGE*3+2.5)/DT_DMON)]) == 0 - - # engaged, down to orange, driver dodges camera, then comes back still distracted, down to red, \ - # driver dodges, and then touches wheel to no avail, disengages and reengages - # - orange/red alert should remain after disappearance, and only disengaging clears red - def test_biggest_comma_fan(self): - _invisible_time = 2 # seconds - ds_vector = always_distracted[:] - interaction_vector = always_false[:] - op_vector = always_true[:] - ds_vector[int(DISTRACTED_SECONDS_TO_ORANGE/DT_DMON):int((DISTRACTED_SECONDS_TO_ORANGE+_invisible_time)/DT_DMON)] \ - = [msg_NO_FACE_DETECTED] * int(_invisible_time/DT_DMON) - ds_vector[int((DISTRACTED_SECONDS_TO_RED+_invisible_time)/DT_DMON):int((DISTRACTED_SECONDS_TO_RED+2*_invisible_time)/DT_DMON)] \ - = [msg_NO_FACE_DETECTED] * int(_invisible_time/DT_DMON) - interaction_vector[int((DISTRACTED_SECONDS_TO_RED+2*_invisible_time+0.5)/DT_DMON):int((DISTRACTED_SECONDS_TO_RED+2*_invisible_time+1.5)/DT_DMON)] \ - = [True] * int(1/DT_DMON) - op_vector[int((DISTRACTED_SECONDS_TO_RED+2*_invisible_time+2.5)/DT_DMON):int((DISTRACTED_SECONDS_TO_RED+2*_invisible_time+3)/DT_DMON)] \ - = [False] * int(0.5/DT_DMON) - events, _ = self._run_seq(ds_vector, interaction_vector, op_vector, always_false) - assert events[int((DISTRACTED_SECONDS_TO_ORANGE+0.5*_invisible_time)/DT_DMON)].names[0] == EventName.promptDriverDistracted - assert events[int((DISTRACTED_SECONDS_TO_RED+1.5*_invisible_time)/DT_DMON)].names[0] == EventName.driverDistracted - assert events[int((DISTRACTED_SECONDS_TO_RED+2*_invisible_time+1.5)/DT_DMON)].names[0] == EventName.driverDistracted - assert len(events[int((DISTRACTED_SECONDS_TO_RED+2*_invisible_time+3.5)/DT_DMON)]) == 0 - - # engaged, invisible driver, down to orange, driver touches wheel; then down to orange again, driver appears - # - both actions should clear the alert, but momentary appearance should not - def test_sometimes_transparent_commuter(self): - _visible_time = np.random.choice([0.5, 10]) - ds_vector = always_no_face[:]*2 - interaction_vector = always_false[:]*2 - ds_vector[int((2*INVISIBLE_SECONDS_TO_ORANGE+1)/DT_DMON):int((2*INVISIBLE_SECONDS_TO_ORANGE+1+_visible_time)/DT_DMON)] = \ - [msg_ATTENTIVE] * int(_visible_time/DT_DMON) - interaction_vector[int((INVISIBLE_SECONDS_TO_ORANGE)/DT_DMON):int((INVISIBLE_SECONDS_TO_ORANGE+1)/DT_DMON)] = [True] * int(1/DT_DMON) - events, _ = self._run_seq(ds_vector, interaction_vector, 2*always_true, 2*always_false) - assert len(events[int(INVISIBLE_SECONDS_TO_ORANGE*0.5/DT_DMON)]) == 0 - assert events[int((INVISIBLE_SECONDS_TO_ORANGE-0.1)/DT_DMON)].names[0] == EventName.promptDriverUnresponsive - assert len(events[int((INVISIBLE_SECONDS_TO_ORANGE+0.1)/DT_DMON)]) == 0 - if _visible_time == 0.5: - assert events[int((INVISIBLE_SECONDS_TO_ORANGE*2+1-0.1)/DT_DMON)].names[0] == EventName.promptDriverUnresponsive - assert events[int((INVISIBLE_SECONDS_TO_ORANGE*2+1+0.1+_visible_time)/DT_DMON)].names[0] == EventName.preDriverUnresponsive - elif _visible_time == 10: - assert events[int((INVISIBLE_SECONDS_TO_ORANGE*2+1-0.1)/DT_DMON)].names[0] == EventName.promptDriverUnresponsive - assert len(events[int((INVISIBLE_SECONDS_TO_ORANGE*2+1+0.1+_visible_time)/DT_DMON)]) == 0 - - # engaged, invisible driver, down to red, driver appears and then touches wheel, then disengages/reengages - # - only disengage will clear the alert - def test_last_second_responder(self): - _visible_time = 2 # seconds - ds_vector = always_no_face[:] - interaction_vector = always_false[:] - op_vector = always_true[:] - ds_vector[int(INVISIBLE_SECONDS_TO_RED/DT_DMON):int((INVISIBLE_SECONDS_TO_RED+_visible_time)/DT_DMON)] = [msg_ATTENTIVE] * int(_visible_time/DT_DMON) - interaction_vector[int((INVISIBLE_SECONDS_TO_RED+_visible_time)/DT_DMON):int((INVISIBLE_SECONDS_TO_RED+_visible_time+1)/DT_DMON)] = [True] * int(1/DT_DMON) - op_vector[int((INVISIBLE_SECONDS_TO_RED+_visible_time+1)/DT_DMON):int((INVISIBLE_SECONDS_TO_RED+_visible_time+0.5)/DT_DMON)] = [False] * int(0.5/DT_DMON) - events, _ = self._run_seq(ds_vector, interaction_vector, op_vector, always_false) - assert len(events[int(INVISIBLE_SECONDS_TO_ORANGE*0.5/DT_DMON)]) == 0 - assert events[int((INVISIBLE_SECONDS_TO_ORANGE-0.1)/DT_DMON)].names[0] == EventName.promptDriverUnresponsive - assert events[int((INVISIBLE_SECONDS_TO_RED-0.1)/DT_DMON)].names[0] == EventName.driverUnresponsive - assert events[int((INVISIBLE_SECONDS_TO_RED+0.5*_visible_time)/DT_DMON)].names[0] == EventName.driverUnresponsive - assert events[int((INVISIBLE_SECONDS_TO_RED+_visible_time+0.5)/DT_DMON)].names[0] == EventName.driverUnresponsive - assert len(events[int((INVISIBLE_SECONDS_TO_RED+_visible_time+1+0.1)/DT_DMON)]) == 0 - - # disengaged, always distracted driver - # - dm should stay quiet when not engaged - def test_pure_dashcam_user(self): - events, _ = self._run_seq(always_distracted, always_false, always_false, always_false) - assert sum(len(event) for event in events) == 0 - - # engaged, car stops at traffic light, down to orange, no action, then car starts moving - # - should only reach green when stopped, but continues counting down on launch - def test_long_traffic_light_victim(self): - _redlight_time = 60 # seconds - standstill_vector = always_true[:] - standstill_vector[int(_redlight_time/DT_DMON):] = [False] * int((TEST_TIMESPAN-_redlight_time)/DT_DMON) - events, d_status = self._run_seq(always_distracted, always_false, always_true, standstill_vector) - assert events[int((d_status.settings._DISTRACTED_TIME-d_status.settings._DISTRACTED_PRE_TIME_TILL_TERMINAL+1)/DT_DMON)].names[0] == \ - EventName.preDriverDistracted - assert events[int((_redlight_time-0.1)/DT_DMON)].names[0] == EventName.preDriverDistracted - assert events[int((_redlight_time+0.5)/DT_DMON)].names[0] == EventName.promptDriverDistracted - - # engaged, model is somehow uncertain and driver is distracted - # - should fall back to wheel touch after uncertain alert - def test_somehow_indecisive_model(self): - ds_vector = [msg_DISTRACTED_BUT_SOMEHOW_UNCERTAIN] * int(TEST_TIMESPAN/DT_DMON) - interaction_vector = always_false[:] - events, d_status = self._run_seq(ds_vector, interaction_vector, always_true, always_false) - assert EventName.preDriverUnresponsive in \ - events[int((INVISIBLE_SECONDS_TO_ORANGE-1+DT_DMON*d_status.settings._HI_STD_FALLBACK_TIME-0.1)/DT_DMON)].names - assert EventName.promptDriverUnresponsive in \ - events[int((INVISIBLE_SECONDS_TO_ORANGE-1+DT_DMON*d_status.settings._HI_STD_FALLBACK_TIME+0.1)/DT_DMON)].names - assert EventName.driverUnresponsive in \ - events[int((INVISIBLE_SECONDS_TO_RED-1+DT_DMON*d_status.settings._HI_STD_FALLBACK_TIME+0.1)/DT_DMON)].names - diff --git a/selfdrive/pandad/.gitignore b/selfdrive/pandad/.gitignore deleted file mode 100644 index f7226cdb87..0000000000 --- a/selfdrive/pandad/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -pandad -pandad_api_impl.cpp -tests/test_pandad_usbprotocol diff --git a/selfdrive/pandad/SConscript b/selfdrive/pandad/SConscript deleted file mode 100644 index 58777cafe9..0000000000 --- a/selfdrive/pandad/SConscript +++ /dev/null @@ -1,13 +0,0 @@ -Import('env', 'envCython', 'common', 'messaging') - -libs = ['usb-1.0', common, messaging, 'pthread'] -panda = env.Library('panda', ['panda.cc', 'panda_comms.cc', 'spi.cc']) - -env.Program('pandad', ['main.cc', 'pandad.cc', 'panda_safety.cc'], LIBS=[panda] + libs) -env.Library('libcan_list_to_can_capnp', ['can_list_to_can_capnp.cc']) - -pandad_python = envCython.Program('pandad_api_impl.so', 'pandad_api_impl.pyx', LIBS=["can_list_to_can_capnp", 'capnp', 'kj'] + envCython["LIBS"]) -Export('pandad_python') - -if GetOption('extras'): - env.Program('tests/test_pandad_usbprotocol', ['tests/test_pandad_usbprotocol.cc'], LIBS=[panda] + libs) diff --git a/selfdrive/pandad/__init__.py b/selfdrive/pandad/__init__.py deleted file mode 100644 index cc680e1676..0000000000 --- a/selfdrive/pandad/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -# Cython, now uses scons to build -from openpilot.selfdrive.pandad.pandad_api_impl import can_list_to_can_capnp, can_capnp_to_list -assert can_list_to_can_capnp -assert can_capnp_to_list diff --git a/selfdrive/pandad/can_list_to_can_capnp.cc b/selfdrive/pandad/can_list_to_can_capnp.cc deleted file mode 100644 index 6ad999da91..0000000000 --- a/selfdrive/pandad/can_list_to_can_capnp.cc +++ /dev/null @@ -1,50 +0,0 @@ -#include "cereal/messaging/messaging.h" -#include "opendbc/can/common.h" - -void can_list_to_can_capnp_cpp(const std::vector &can_list, std::string &out, bool sendcan, bool valid) { - MessageBuilder msg; - auto event = msg.initEvent(valid); - - auto canData = sendcan ? event.initSendcan(can_list.size()) : event.initCan(can_list.size()); - int j = 0; - for (auto it = can_list.begin(); it != can_list.end(); it++, j++) { - auto c = canData[j]; - c.setAddress(it->address); - c.setDat(kj::arrayPtr((uint8_t*)it->dat.data(), it->dat.size())); - c.setSrc(it->src); - } - const uint64_t msg_size = capnp::computeSerializedSizeInWords(msg) * sizeof(capnp::word); - out.resize(msg_size); - kj::ArrayOutputStream output_stream(kj::ArrayPtr((unsigned char *)out.data(), msg_size)); - capnp::writeMessage(output_stream, msg); -} - -// Converts a vector of Cap'n Proto serialized can strings into a vector of CanData structures. -void can_capnp_to_can_list_cpp(const std::vector &strings, std::vector &can_list, bool sendcan) { - AlignedBuffer aligned_buf; - can_list.reserve(strings.size()); - - for (const auto &str : strings) { - // extract the messages - capnp::FlatArrayMessageReader reader(aligned_buf.align(str.data(), str.size())); - cereal::Event::Reader event = reader.getRoot(); - - auto frames = sendcan ? event.getSendcan() : event.getCan(); - - // Add new CanData entry - CanData &can_data = can_list.emplace_back(); - can_data.nanos = event.getLogMonoTime(); - can_data.frames.reserve(frames.size()); - - // Populate CAN frames - for (const auto &frame : frames) { - CanFrame &can_frame = can_data.frames.emplace_back(); - can_frame.src = frame.getSrc(); - can_frame.address = frame.getAddress(); - - // Copy CAN data - auto dat = frame.getDat(); - can_frame.dat.assign(dat.begin(), dat.end()); - } - } -} diff --git a/selfdrive/pandad/main.cc b/selfdrive/pandad/main.cc deleted file mode 100644 index b63d884a45..0000000000 --- a/selfdrive/pandad/main.cc +++ /dev/null @@ -1,22 +0,0 @@ -#include - -#include "selfdrive/pandad/pandad.h" -#include "common/swaglog.h" -#include "common/util.h" -#include "system/hardware/hw.h" - -int main(int argc, char *argv[]) { - LOGW("starting pandad"); - - if (!Hardware::PC()) { - int err; - err = util::set_realtime_priority(54); - assert(err == 0); - err = util::set_core_affinity({3}); - assert(err == 0); - } - - std::vector serials(argv + 1, argv + argc); - pandad_main_thread(serials); - return 0; -} diff --git a/selfdrive/pandad/panda.cc b/selfdrive/pandad/panda.cc deleted file mode 100644 index 72b8ddcf81..0000000000 --- a/selfdrive/pandad/panda.cc +++ /dev/null @@ -1,312 +0,0 @@ -#include "selfdrive/pandad/panda.h" - -#include - -#include -#include -#include - -#include "cereal/messaging/messaging.h" -#include "common/swaglog.h" -#include "common/util.h" - -const bool PANDAD_MAXOUT = getenv("PANDAD_MAXOUT") != nullptr; - -Panda::Panda(std::string serial, uint32_t bus_offset) : bus_offset(bus_offset) { - // try USB first, then SPI - try { - handle = std::make_unique(serial); - LOGW("connected to %s over USB", serial.c_str()); - } catch (std::exception &e) { -#ifndef __APPLE__ - handle = std::make_unique(serial); - LOGW("connected to %s over SPI", serial.c_str()); -#else - throw e; -#endif - } - - hw_type = get_hw_type(); - can_reset_communications(); -} - -bool Panda::connected() { - return handle->connected; -} - -bool Panda::comms_healthy() { - return handle->comms_healthy; -} - -std::string Panda::hw_serial() { - return handle->hw_serial; -} - -std::vector Panda::list(bool usb_only) { - std::vector serials = PandaUsbHandle::list(); - -#ifndef __APPLE__ - if (!usb_only) { - for (const auto &s : PandaSpiHandle::list()) { - if (std::find(serials.begin(), serials.end(), s) == serials.end()) { - serials.push_back(s); - } - } - } -#endif - - return serials; -} - -void Panda::set_safety_model(cereal::CarParams::SafetyModel safety_model, uint16_t safety_param) { - handle->control_write(0xdc, (uint16_t)safety_model, safety_param); -} - -void Panda::set_alternative_experience(uint16_t alternative_experience, uint16_t safety_param_sp) { - handle->control_write(0xdf, alternative_experience, safety_param_sp); -} - -std::string Panda::serial_read(int port_number) { - std::string ret; - char buffer[USBPACKET_MAX_SIZE] = {}; - - while (true) { - int bytes_read = handle->control_read(0xe0, port_number, 0, (unsigned char *)buffer, USBPACKET_MAX_SIZE); - if (bytes_read <= 0) { - break; - } - ret.append(buffer, bytes_read); - } - - return ret; -} - -void Panda::set_uart_baud(int uart, int rate) { - handle->control_write(0xe4, uart, int(rate / 300)); -} - -cereal::PandaState::PandaType Panda::get_hw_type() { - unsigned char hw_query[1] = {0}; - - handle->control_read(0xc1, 0, 0, hw_query, 1); - return (cereal::PandaState::PandaType)(hw_query[0]); -} - -void Panda::set_fan_speed(uint16_t fan_speed) { - handle->control_write(0xb1, fan_speed, 0); -} - -uint16_t Panda::get_fan_speed() { - uint16_t fan_speed_rpm = 0; - handle->control_read(0xb2, 0, 0, (unsigned char*)&fan_speed_rpm, sizeof(fan_speed_rpm)); - return fan_speed_rpm; -} - -void Panda::set_ir_pwr(uint16_t ir_pwr) { - handle->control_write(0xb0, ir_pwr, 0); -} - -std::optional Panda::get_state() { - health_t health {0}; - int err = handle->control_read(0xd2, 0, 0, (unsigned char*)&health, sizeof(health)); - return err >= 0 ? std::make_optional(health) : std::nullopt; -} - -std::optional Panda::get_can_state(uint16_t can_number) { - can_health_t can_health {0}; - int err = handle->control_read(0xc2, can_number, 0, (unsigned char*)&can_health, sizeof(can_health)); - return err >= 0 ? std::make_optional(can_health) : std::nullopt; -} - -void Panda::set_loopback(bool loopback) { - handle->control_write(0xe5, loopback, 0); -} - -std::optional> Panda::get_firmware_version() { - std::vector fw_sig_buf(128); - int read_1 = handle->control_read(0xd3, 0, 0, &fw_sig_buf[0], 64); - int read_2 = handle->control_read(0xd4, 0, 0, &fw_sig_buf[64], 64); - return ((read_1 == 64) && (read_2 == 64)) ? std::make_optional(fw_sig_buf) : std::nullopt; -} - -std::optional Panda::get_serial() { - char serial_buf[17] = {'\0'}; - int err = handle->control_read(0xd0, 0, 0, (uint8_t*)serial_buf, 16); - return err >= 0 ? std::make_optional(serial_buf) : std::nullopt; -} - -bool Panda::up_to_date() { - if (auto fw_sig = get_firmware_version()) { - for (auto fn : { "panda.bin.signed", "panda_h7.bin.signed" }) { - auto content = util::read_file(std::string("../../panda/board/obj/") + fn); - if (content.size() >= fw_sig->size() && - memcmp(content.data() + content.size() - fw_sig->size(), fw_sig->data(), fw_sig->size()) == 0) { - return true; - } - } - } - return false; -} - -void Panda::set_power_saving(bool power_saving) { - handle->control_write(0xe7, power_saving, 0); -} - -void Panda::enable_deepsleep() { - handle->control_write(0xfb, 0, 0); -} - -void Panda::send_heartbeat(bool engaged, bool engaged_mads) { - handle->control_write(0xf3, engaged, engaged_mads); -} - -void Panda::set_can_speed_kbps(uint16_t bus, uint16_t speed) { - handle->control_write(0xde, bus, (speed * 10)); -} - -void Panda::set_can_fd_auto(uint16_t bus, bool enabled) { - handle->control_write(0xe8, bus, enabled); -} - -void Panda::set_data_speed_kbps(uint16_t bus, uint16_t speed) { - handle->control_write(0xf9, bus, (speed * 10)); -} - -void Panda::set_canfd_non_iso(uint16_t bus, bool non_iso) { - handle->control_write(0xfc, bus, non_iso); -} - -static uint8_t len_to_dlc(uint8_t len) { - if (len <= 8) { - return len; - } - if (len <= 24) { - return 8 + ((len - 8) / 4) + ((len % 4) ? 1 : 0); - } else { - return 11 + (len / 16) + ((len % 16) ? 1 : 0); - } -} - -void Panda::pack_can_buffer(const capnp::List::Reader &can_data_list, - std::function write_func) { - int32_t pos = 0; - uint8_t send_buf[2 * USB_TX_SOFT_LIMIT]; - - for (const auto &cmsg : can_data_list) { - // check if the message is intended for this panda - uint8_t bus = cmsg.getSrc(); - if (bus < bus_offset || bus >= (bus_offset + PANDA_BUS_OFFSET)) { - continue; - } - auto can_data = cmsg.getDat(); - uint8_t data_len_code = len_to_dlc(can_data.size()); - assert(can_data.size() <= 64); - assert(can_data.size() == dlc_to_len[data_len_code]); - - can_header header = {}; - header.addr = cmsg.getAddress(); - header.extended = (cmsg.getAddress() >= 0x800) ? 1 : 0; - header.data_len_code = data_len_code; - header.bus = bus - bus_offset; - header.checksum = 0; - - memcpy(&send_buf[pos], (uint8_t *)&header, sizeof(can_header)); - memcpy(&send_buf[pos + sizeof(can_header)], (uint8_t *)can_data.begin(), can_data.size()); - uint32_t msg_size = sizeof(can_header) + can_data.size(); - - // set checksum - ((can_header *) &send_buf[pos])->checksum = calculate_checksum(&send_buf[pos], msg_size); - - pos += msg_size; - - if (pos >= USB_TX_SOFT_LIMIT) { - write_func(send_buf, pos); - pos = 0; - } - } - - // send remaining packets - if (pos > 0) write_func(send_buf, pos); -} - -void Panda::can_send(const capnp::List::Reader &can_data_list) { - pack_can_buffer(can_data_list, [=](uint8_t* data, size_t size) { - handle->bulk_write(3, data, size, 5); - }); -} - -bool Panda::can_receive(std::vector& out_vec) { - // Check if enough space left in buffer to store RECV_SIZE data - assert(receive_buffer_size + RECV_SIZE <= sizeof(receive_buffer)); - - int recv = handle->bulk_read(0x81, &receive_buffer[receive_buffer_size], RECV_SIZE); - if (!comms_healthy()) { - return false; - } - - if (PANDAD_MAXOUT) { - static uint8_t junk[RECV_SIZE]; - handle->bulk_read(0xab, junk, RECV_SIZE - recv); - } - - bool ret = true; - if (recv > 0) { - receive_buffer_size += recv; - ret = unpack_can_buffer(receive_buffer, receive_buffer_size, out_vec); - } - return ret; -} - -void Panda::can_reset_communications() { - handle->control_write(0xc0, 0, 0); -} - -bool Panda::unpack_can_buffer(uint8_t *data, uint32_t &size, std::vector &out_vec) { - int pos = 0; - - while (pos <= size - sizeof(can_header)) { - can_header header; - memcpy(&header, &data[pos], sizeof(can_header)); - - const uint8_t data_len = dlc_to_len[header.data_len_code]; - if (pos + sizeof(can_header) + data_len > size) { - // we don't have all the data for this message yet - break; - } - - if (calculate_checksum(&data[pos], sizeof(can_header) + data_len) != 0) { - LOGE("Panda CAN checksum failed"); - size = 0; - can_reset_communications(); - return false; - } - - can_frame &canData = out_vec.emplace_back(); - canData.address = header.addr; - canData.src = header.bus + bus_offset; - if (header.rejected) { - canData.src += CAN_REJECTED_BUS_OFFSET; - } - if (header.returned) { - canData.src += CAN_RETURNED_BUS_OFFSET; - } - - canData.dat.assign((char *)&data[pos + sizeof(can_header)], data_len); - - pos += sizeof(can_header) + data_len; - } - - // move the overflowing data to the beginning of the buffer for the next round - memmove(data, &data[pos], size - pos); - size -= pos; - - return true; -} - -uint8_t Panda::calculate_checksum(uint8_t *data, uint32_t len) { - uint8_t checksum = 0U; - for (uint32_t i = 0U; i < len; i++) { - checksum ^= data[i]; - } - return checksum; -} diff --git a/selfdrive/pandad/panda.h b/selfdrive/pandad/panda.h deleted file mode 100644 index 8545b558a9..0000000000 --- a/selfdrive/pandad/panda.h +++ /dev/null @@ -1,99 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "cereal/gen/cpp/car.capnp.h" -#include "cereal/gen/cpp/log.capnp.h" -#include "panda/board/health.h" -#include "panda/board/can.h" -#include "selfdrive/pandad/panda_comms.h" - -#define USB_TX_SOFT_LIMIT (0x100U) -#define USBPACKET_MAX_SIZE (0x40) - -#define RECV_SIZE (0x4000U) - -#define CAN_REJECTED_BUS_OFFSET 0xC0U -#define CAN_RETURNED_BUS_OFFSET 0x80U - -#define PANDA_BUS_OFFSET 4 - -struct __attribute__((packed)) can_header { - uint8_t reserved : 1; - uint8_t bus : 3; - uint8_t data_len_code : 4; - uint8_t rejected : 1; - uint8_t returned : 1; - uint8_t extended : 1; - uint32_t addr : 29; - uint8_t checksum : 8; -}; - -struct can_frame { - long address; - std::string dat; - long src; -}; - - -class Panda { -private: - std::unique_ptr handle; - -public: - Panda(std::string serial="", uint32_t bus_offset=0); - - cereal::PandaState::PandaType hw_type = cereal::PandaState::PandaType::UNKNOWN; - const uint32_t bus_offset; - - bool connected(); - bool comms_healthy(); - std::string hw_serial(); - - // Static functions - static std::vector list(bool usb_only=false); - - // Panda functionality - cereal::PandaState::PandaType get_hw_type(); - void set_safety_model(cereal::CarParams::SafetyModel safety_model, uint16_t safety_param=0U); - void set_alternative_experience(uint16_t alternative_experience, uint16_t safety_param_sp=0U); - std::string serial_read(int port_number = 0); - void set_uart_baud(int uart, int rate); - void set_fan_speed(uint16_t fan_speed); - uint16_t get_fan_speed(); - void set_ir_pwr(uint16_t ir_pwr); - std::optional get_state(); - std::optional get_can_state(uint16_t can_number); - void set_loopback(bool loopback); - std::optional> get_firmware_version(); - bool up_to_date(); - std::optional get_serial(); - void set_power_saving(bool power_saving); - void enable_deepsleep(); - void send_heartbeat(bool engaged, bool engaged_mads); - void set_can_speed_kbps(uint16_t bus, uint16_t speed); - void set_can_fd_auto(uint16_t bus, bool enabled); - void set_data_speed_kbps(uint16_t bus, uint16_t speed); - void set_canfd_non_iso(uint16_t bus, bool non_iso); - void can_send(const capnp::List::Reader &can_data_list); - bool can_receive(std::vector& out_vec); - void can_reset_communications(); - -protected: - // for unit tests - uint8_t receive_buffer[RECV_SIZE + sizeof(can_header) + 64]; - uint32_t receive_buffer_size = 0; - - Panda(uint32_t bus_offset) : bus_offset(bus_offset) {} - void pack_can_buffer(const capnp::List::Reader &can_data_list, - std::function write_func); - bool unpack_can_buffer(uint8_t *data, uint32_t &size, std::vector &out_vec); - uint8_t calculate_checksum(uint8_t *data, uint32_t len); -}; diff --git a/selfdrive/pandad/panda_comms.cc b/selfdrive/pandad/panda_comms.cc deleted file mode 100644 index 8a20f397d3..0000000000 --- a/selfdrive/pandad/panda_comms.cc +++ /dev/null @@ -1,227 +0,0 @@ -#include "selfdrive/pandad/panda.h" - -#include -#include -#include - -#include "common/swaglog.h" - -static libusb_context *init_usb_ctx() { - libusb_context *context = nullptr; - int err = libusb_init(&context); - if (err != 0) { - LOGE("libusb initialization error"); - return nullptr; - } - -#if LIBUSB_API_VERSION >= 0x01000106 - libusb_set_option(context, LIBUSB_OPTION_LOG_LEVEL, LIBUSB_LOG_LEVEL_INFO); -#else - libusb_set_debug(context, 3); -#endif - return context; -} - -PandaUsbHandle::PandaUsbHandle(std::string serial) : PandaCommsHandle(serial) { - // init libusb - ssize_t num_devices; - libusb_device **dev_list = NULL; - int err = 0; - ctx = init_usb_ctx(); - if (!ctx) { goto fail; } - - // connect by serial - num_devices = libusb_get_device_list(ctx, &dev_list); - if (num_devices < 0) { goto fail; } - for (size_t i = 0; i < num_devices; ++i) { - libusb_device_descriptor desc; - libusb_get_device_descriptor(dev_list[i], &desc); - if (desc.idVendor == 0x3801 && desc.idProduct == 0xddcc) { - int ret = libusb_open(dev_list[i], &dev_handle); - if (dev_handle == NULL || ret < 0) { goto fail; } - - unsigned char desc_serial[26] = { 0 }; - ret = libusb_get_string_descriptor_ascii(dev_handle, desc.iSerialNumber, desc_serial, std::size(desc_serial)); - if (ret < 0) { goto fail; } - - hw_serial = std::string((char *)desc_serial, ret); - if (serial.empty() || serial == hw_serial) { - break; - } - libusb_close(dev_handle); - dev_handle = NULL; - } - } - if (dev_handle == NULL) goto fail; - libusb_free_device_list(dev_list, 1); - dev_list = nullptr; - - if (libusb_kernel_driver_active(dev_handle, 0) == 1) { - libusb_detach_kernel_driver(dev_handle, 0); - } - - err = libusb_set_configuration(dev_handle, 1); - if (err != 0) { goto fail; } - - err = libusb_claim_interface(dev_handle, 0); - if (err != 0) { goto fail; } - - return; - -fail: - if (dev_list != NULL) { - libusb_free_device_list(dev_list, 1); - } - cleanup(); - throw std::runtime_error("Error connecting to panda"); -} - -PandaUsbHandle::~PandaUsbHandle() { - std::lock_guard lk(hw_lock); - cleanup(); - connected = false; -} - -void PandaUsbHandle::cleanup() { - if (dev_handle) { - libusb_release_interface(dev_handle, 0); - libusb_close(dev_handle); - } - - if (ctx) { - libusb_exit(ctx); - } -} - -std::vector PandaUsbHandle::list() { - static std::unique_ptr context(init_usb_ctx(), libusb_exit); - // init libusb - ssize_t num_devices; - libusb_device **dev_list = NULL; - std::vector serials; - if (!context) { return serials; } - - num_devices = libusb_get_device_list(context.get(), &dev_list); - if (num_devices < 0) { - LOGE("libusb can't get device list"); - goto finish; - } - for (size_t i = 0; i < num_devices; ++i) { - libusb_device *device = dev_list[i]; - libusb_device_descriptor desc; - libusb_get_device_descriptor(device, &desc); - if (desc.idVendor == 0x3801 && desc.idProduct == 0xddcc) { - libusb_device_handle *handle = NULL; - int ret = libusb_open(device, &handle); - if (ret < 0) { goto finish; } - - unsigned char desc_serial[26] = { 0 }; - ret = libusb_get_string_descriptor_ascii(handle, desc.iSerialNumber, desc_serial, std::size(desc_serial)); - libusb_close(handle); - if (ret < 0) { goto finish; } - - serials.push_back(std::string((char *)desc_serial, ret)); - } - } - -finish: - if (dev_list != NULL) { - libusb_free_device_list(dev_list, 1); - } - return serials; -} - -void PandaUsbHandle::handle_usb_issue(int err, const char func[]) { - LOGE_100("usb error %d \"%s\" in %s", err, libusb_strerror((enum libusb_error)err), func); - if (err == LIBUSB_ERROR_NO_DEVICE) { - LOGE("lost connection"); - connected = false; - } - // TODO: check other errors, is simply retrying okay? -} - -int PandaUsbHandle::control_write(uint8_t bRequest, uint16_t wValue, uint16_t wIndex, unsigned int timeout) { - int err; - const uint8_t bmRequestType = LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE; - - if (!connected) { - return LIBUSB_ERROR_NO_DEVICE; - } - - std::lock_guard lk(hw_lock); - do { - err = libusb_control_transfer(dev_handle, bmRequestType, bRequest, wValue, wIndex, NULL, 0, timeout); - if (err < 0) handle_usb_issue(err, __func__); - } while (err < 0 && connected); - - return err; -} - -int PandaUsbHandle::control_read(uint8_t bRequest, uint16_t wValue, uint16_t wIndex, unsigned char *data, uint16_t wLength, unsigned int timeout) { - int err; - const uint8_t bmRequestType = LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE; - - if (!connected) { - return LIBUSB_ERROR_NO_DEVICE; - } - - std::lock_guard lk(hw_lock); - do { - err = libusb_control_transfer(dev_handle, bmRequestType, bRequest, wValue, wIndex, data, wLength, timeout); - if (err < 0) handle_usb_issue(err, __func__); - } while (err < 0 && connected); - - return err; -} - -int PandaUsbHandle::bulk_write(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout) { - int err; - int transferred = 0; - - if (!connected) { - return 0; - } - - std::lock_guard lk(hw_lock); - do { - // Try sending can messages. If the receive buffer on the panda is full it will NAK - // and libusb will try again. After 5ms, it will time out. We will drop the messages. - err = libusb_bulk_transfer(dev_handle, endpoint, data, length, &transferred, timeout); - - if (err == LIBUSB_ERROR_TIMEOUT) { - LOGW("Transmit buffer full"); - break; - } else if (err != 0 || length != transferred) { - handle_usb_issue(err, __func__); - } - } while (err != 0 && connected); - - return transferred; -} - -int PandaUsbHandle::bulk_read(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout) { - int err; - int transferred = 0; - - if (!connected) { - return 0; - } - - std::lock_guard lk(hw_lock); - - do { - err = libusb_bulk_transfer(dev_handle, endpoint, data, length, &transferred, timeout); - - if (err == LIBUSB_ERROR_TIMEOUT) { - break; // timeout is okay to exit, recv still happened - } else if (err == LIBUSB_ERROR_OVERFLOW) { - comms_healthy = false; - LOGE_100("overflow got 0x%x", transferred); - } else if (err != 0) { - handle_usb_issue(err, __func__); - } - - } while (err != 0 && connected); - - return transferred; -} diff --git a/selfdrive/pandad/panda_comms.h b/selfdrive/pandad/panda_comms.h deleted file mode 100644 index 9c452faf6d..0000000000 --- a/selfdrive/pandad/panda_comms.h +++ /dev/null @@ -1,93 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include - -#ifndef __APPLE__ -#include -#endif - -#include - - -#define TIMEOUT 0 -#define SPI_BUF_SIZE 2048 - - -// comms base class -class PandaCommsHandle { -public: - PandaCommsHandle(std::string serial) {} - virtual ~PandaCommsHandle() {} - virtual void cleanup() = 0; - - std::string hw_serial; - std::atomic connected = true; - std::atomic comms_healthy = true; - static std::vector list(); - - // HW communication - virtual int control_write(uint8_t request, uint16_t param1, uint16_t param2, unsigned int timeout=TIMEOUT) = 0; - virtual int control_read(uint8_t request, uint16_t param1, uint16_t param2, unsigned char *data, uint16_t length, unsigned int timeout=TIMEOUT) = 0; - virtual int bulk_write(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout=TIMEOUT) = 0; - virtual int bulk_read(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout=TIMEOUT) = 0; -}; - -class PandaUsbHandle : public PandaCommsHandle { -public: - PandaUsbHandle(std::string serial); - ~PandaUsbHandle(); - int control_write(uint8_t request, uint16_t param1, uint16_t param2, unsigned int timeout=TIMEOUT); - int control_read(uint8_t request, uint16_t param1, uint16_t param2, unsigned char *data, uint16_t length, unsigned int timeout=TIMEOUT); - int bulk_write(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout=TIMEOUT); - int bulk_read(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout=TIMEOUT); - void cleanup(); - - static std::vector list(); - -private: - libusb_context *ctx = NULL; - libusb_device_handle *dev_handle = NULL; - std::recursive_mutex hw_lock; - void handle_usb_issue(int err, const char func[]); -}; - -#ifndef __APPLE__ -struct __attribute__((packed)) spi_header { - uint8_t sync; - uint8_t endpoint; - uint16_t tx_len; - uint16_t max_rx_len; -}; - -class PandaSpiHandle : public PandaCommsHandle { -public: - PandaSpiHandle(std::string serial); - ~PandaSpiHandle(); - int control_write(uint8_t request, uint16_t param1, uint16_t param2, unsigned int timeout=TIMEOUT); - int control_read(uint8_t request, uint16_t param1, uint16_t param2, unsigned char *data, uint16_t length, unsigned int timeout=TIMEOUT); - int bulk_write(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout=TIMEOUT); - int bulk_read(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout=TIMEOUT); - void cleanup(); - - static std::vector list(); - -private: - int spi_fd = -1; - uint8_t tx_buf[SPI_BUF_SIZE]; - uint8_t rx_buf[SPI_BUF_SIZE]; - inline static std::recursive_mutex hw_lock; - - int wait_for_ack(uint8_t ack, uint8_t tx, unsigned int timeout, unsigned int length); - int bulk_transfer(uint8_t endpoint, uint8_t *tx_data, uint16_t tx_len, uint8_t *rx_data, uint16_t rx_len, unsigned int timeout); - int spi_transfer(uint8_t endpoint, uint8_t *tx_data, uint16_t tx_len, uint8_t *rx_data, uint16_t max_rx_len, unsigned int timeout); - int spi_transfer_retry(uint8_t endpoint, uint8_t *tx_data, uint16_t tx_len, uint8_t *rx_data, uint16_t max_rx_len, unsigned int timeout); - int lltransfer(spi_ioc_transfer &t); - - spi_header header; - uint32_t xfer_count = 0; -}; -#endif diff --git a/selfdrive/pandad/panda_safety.cc b/selfdrive/pandad/panda_safety.cc deleted file mode 100644 index 48589c4146..0000000000 --- a/selfdrive/pandad/panda_safety.cc +++ /dev/null @@ -1,97 +0,0 @@ -#include "selfdrive/pandad/pandad.h" -#include "cereal/messaging/messaging.h" -#include "common/swaglog.h" - -void PandaSafety::configureSafetyMode() { - bool is_onroad = params_.getBool("IsOnroad"); - - if (is_onroad && !safety_configured_) { - updateMultiplexingMode(); - - auto car_params = fetchCarParams(); - if (!car_params.empty()) { - LOGW("got %lu bytes CarParams", car_params[0].size()); - LOGW("got %lu bytes CarParamsSP", car_params[1].size()); - setSafetyMode(car_params); - safety_configured_ = true; - } - } else if (!is_onroad) { - initialized_ = false; - safety_configured_ = false; - log_once_ = false; - } -} - -void PandaSafety::updateMultiplexingMode() { - // Initialize to ELM327 without OBD multiplexing for initial fingerprinting - if (!initialized_) { - prev_obd_multiplexing_ = false; - for (int i = 0; i < pandas_.size(); ++i) { - pandas_[i]->set_safety_model(cereal::CarParams::SafetyModel::ELM327, 1U); - } - initialized_ = true; - } - - // Switch between multiplexing modes based on the OBD multiplexing request - bool obd_multiplexing_requested = params_.getBool("ObdMultiplexingEnabled"); - if (obd_multiplexing_requested != prev_obd_multiplexing_) { - for (int i = 0; i < pandas_.size(); ++i) { - const uint16_t safety_param = (i > 0 || !obd_multiplexing_requested) ? 1U : 0U; - pandas_[i]->set_safety_model(cereal::CarParams::SafetyModel::ELM327, safety_param); - } - prev_obd_multiplexing_ = obd_multiplexing_requested; - params_.putBool("ObdMultiplexingChanged", true); - } -} - -// TODO-SP: Use structs instead of vector -std::vector PandaSafety::fetchCarParams() { - if (!params_.getBool("FirmwareQueryDone")) { - return {}; - } - - if (!log_once_) { - LOGW("Finished FW query, Waiting for params to set safety model"); - log_once_ = true; - } - - if (!params_.getBool("ControlsReady")) { - return {}; - } - return {params_.get("CarParams"), params_.get("CarParamsSP")}; -} - -// TODO-SP: Use structs instead of vector -void PandaSafety::setSafetyMode(const std::vector ¶ms_string) { - AlignedBuffer aligned_buf; - AlignedBuffer aligned_buf_sp; - - capnp::FlatArrayMessageReader cmsg(aligned_buf.align(params_string[0].data(), params_string[0].size())); - cereal::CarParams::Reader car_params = cmsg.getRoot(); - - capnp::FlatArrayMessageReader cmsg_sp(aligned_buf_sp.align(params_string[1].data(), params_string[1].size())); - cereal::CarParamsSP::Reader car_params_sp = cmsg_sp.getRoot(); - - auto safety_configs = car_params.getSafetyConfigs(); - uint16_t alternative_experience = car_params.getAlternativeExperience(); - uint16_t safety_param_sp = car_params_sp.getSafetyParam(); - - for (int i = 0; i < pandas_.size(); ++i) { - // Default to SILENT safety model if not specified - cereal::CarParams::SafetyModel safety_model = cereal::CarParams::SafetyModel::SILENT; - uint16_t safety_param = 0U; - if (i < safety_configs.size()) { - safety_model = safety_configs[i].getSafetyModel(); - safety_param = safety_configs[i].getSafetyParam(); - } - - LOGW("Panda %d: setting safety model: %d, param: %d, alternative experience: %d, param_sp: %d", i, (int)safety_model, safety_param, alternative_experience, safety_param_sp); - pandas_[i]->set_alternative_experience(alternative_experience, safety_param_sp); - pandas_[i]->set_safety_model(safety_model, safety_param); - } -} - -bool PandaSafety::getOffroadMode() { - auto offroad_mode = params_.getBool("OffroadMode"); - return offroad_mode; -} diff --git a/selfdrive/pandad/pandad.cc b/selfdrive/pandad/pandad.cc deleted file mode 100644 index af27276510..0000000000 --- a/selfdrive/pandad/pandad.cc +++ /dev/null @@ -1,540 +0,0 @@ -#include "selfdrive/pandad/pandad.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "cereal/gen/cpp/car.capnp.h" -#include "cereal/messaging/messaging.h" -#include "common/ratekeeper.h" -#include "common/swaglog.h" -#include "common/timing.h" -#include "common/util.h" -#include "system/hardware/hw.h" - -// -- Multi-panda conventions -- -// Ordering: -// - The internal panda will always be the first panda -// - Consecutive pandas will be sorted based on panda type, and then serial number -// Connecting: -// - If a panda connection is dropped, pandad will reconnect to all pandas -// - If a panda is added, we will only reconnect when we are offroad -// CAN buses: -// - Each panda will have its block of 4 buses. E.g.: the second panda will use -// bus numbers 4, 5, 6 and 7 -// - The internal panda will always be used for accessing the OBD2 port, -// and thus firmware queries -// Safety: -// - SafetyConfig is a list, which is mapped to the connected pandas -// - If there are more pandas connected than there are SafetyConfigs, -// the excess pandas will remain in "silent" or "noOutput" mode -// Ignition: -// - If any of the ignition sources in any panda is high, ignition is high - -#define MAX_IR_POWER 0.5f -#define MIN_IR_POWER 0.0f -#define CUTOFF_IL 400 -#define SATURATE_IL 1000 - -#define ALT_EXP_MADS_DISENGAGE_LATERAL_ON_BRAKE 2048 - -ExitHandler do_exit; - -bool check_all_connected(const std::vector &pandas) { - for (const auto& panda : pandas) { - if (!panda->connected()) { - do_exit = true; - return false; - } - } - return true; -} - -bool process_mads_heartbeat(SubMaster *sm) { - const int &alt_exp = (*sm)["carParams"].getCarParams().getAlternativeExperience(); - const bool disengage_lateral_on_brake = (alt_exp & ALT_EXP_MADS_DISENGAGE_LATERAL_ON_BRAKE) != 0; - - const auto &mads = (*sm)["selfdriveStateSP"].getSelfdriveStateSP().getMads(); - const bool heartbeat_type = disengage_lateral_on_brake ? mads.getActive() : mads.getEnabled(); - - const bool engaged = sm->allAliveAndValid({"selfdriveStateSP"}) && heartbeat_type; - - return engaged; -} - -Panda *connect(std::string serial="", uint32_t index=0) { - std::unique_ptr panda; - try { - panda = std::make_unique(serial, (index * PANDA_BUS_OFFSET)); - } catch (std::exception &e) { - return nullptr; - } - - // common panda config - if (getenv("BOARDD_LOOPBACK")) { - panda->set_loopback(true); - } - //panda->enable_deepsleep(); - - for (int i = 0; i < PANDA_BUS_CNT; i++) { - panda->set_can_fd_auto(i, true); - } - - if (!panda->up_to_date() && !getenv("BOARDD_SKIP_FW_CHECK")) { - throw std::runtime_error("Panda firmware out of date. Run pandad.py to update."); - } - - return panda.release(); -} - -void can_send_thread(std::vector pandas, bool fake_send) { - util::set_thread_name("pandad_can_send"); - - AlignedBuffer aligned_buf; - std::unique_ptr context(Context::create()); - std::unique_ptr subscriber(SubSocket::create(context.get(), "sendcan")); - assert(subscriber != NULL); - subscriber->setTimeout(100); - - // run as fast as messages come in - while (!do_exit && check_all_connected(pandas)) { - std::unique_ptr msg(subscriber->receive()); - if (!msg) { - continue; - } - - capnp::FlatArrayMessageReader cmsg(aligned_buf.align(msg.get())); - cereal::Event::Reader event = cmsg.getRoot(); - - // Don't send if older than 1 second - if ((nanos_since_boot() - event.getLogMonoTime() < 1e9) && !fake_send) { - for (const auto& panda : pandas) { - LOGT("sending sendcan to panda: %s", (panda->hw_serial()).c_str()); - panda->can_send(event.getSendcan()); - LOGT("sendcan sent to panda: %s", (panda->hw_serial()).c_str()); - } - } else { - LOGE("sendcan too old to send: %" PRIu64 ", %" PRIu64, nanos_since_boot(), event.getLogMonoTime()); - } - } -} - -void can_recv(std::vector &pandas, PubMaster *pm) { - static std::vector raw_can_data; - { - bool comms_healthy = true; - raw_can_data.clear(); - for (const auto& panda : pandas) { - comms_healthy &= panda->can_receive(raw_can_data); - } - - MessageBuilder msg; - auto evt = msg.initEvent(); - evt.setValid(comms_healthy); - auto canData = evt.initCan(raw_can_data.size()); - for (size_t i = 0; i < raw_can_data.size(); ++i) { - canData[i].setAddress(raw_can_data[i].address); - canData[i].setDat(kj::arrayPtr((uint8_t*)raw_can_data[i].dat.data(), raw_can_data[i].dat.size())); - canData[i].setSrc(raw_can_data[i].src); - } - pm->send("can", msg); - } -} - -void fill_panda_state(cereal::PandaState::Builder &ps, cereal::PandaState::PandaType hw_type, const health_t &health) { - ps.setVoltage(health.voltage_pkt); - ps.setCurrent(health.current_pkt); - ps.setUptime(health.uptime_pkt); - ps.setSafetyTxBlocked(health.safety_tx_blocked_pkt); - ps.setSafetyRxInvalid(health.safety_rx_invalid_pkt); - ps.setIgnitionLine(health.ignition_line_pkt); - ps.setIgnitionCan(health.ignition_can_pkt); - ps.setControlsAllowed(health.controls_allowed_pkt); - ps.setTxBufferOverflow(health.tx_buffer_overflow_pkt); - ps.setRxBufferOverflow(health.rx_buffer_overflow_pkt); - ps.setPandaType(hw_type); - ps.setSafetyModel(cereal::CarParams::SafetyModel(health.safety_mode_pkt)); - ps.setSafetyParam(health.safety_param_pkt); - ps.setFaultStatus(cereal::PandaState::FaultStatus(health.fault_status_pkt)); - ps.setPowerSaveEnabled((bool)(health.power_save_enabled_pkt)); - ps.setHeartbeatLost((bool)(health.heartbeat_lost_pkt)); - ps.setAlternativeExperience(health.alternative_experience_pkt); - ps.setHarnessStatus(cereal::PandaState::HarnessStatus(health.car_harness_status_pkt)); - ps.setInterruptLoad(health.interrupt_load_pkt); - ps.setFanPower(health.fan_power); - ps.setFanStallCount(health.fan_stall_count); - ps.setSafetyRxChecksInvalid((bool)(health.safety_rx_checks_invalid_pkt)); - ps.setSpiChecksumErrorCount(health.spi_checksum_error_count_pkt); - ps.setSbu1Voltage(health.sbu1_voltage_mV / 1000.0f); - ps.setSbu2Voltage(health.sbu2_voltage_mV / 1000.0f); -} - -void fill_panda_can_state(cereal::PandaState::PandaCanState::Builder &cs, const can_health_t &can_health) { - cs.setBusOff((bool)can_health.bus_off); - cs.setBusOffCnt(can_health.bus_off_cnt); - cs.setErrorWarning((bool)can_health.error_warning); - cs.setErrorPassive((bool)can_health.error_passive); - cs.setLastError(cereal::PandaState::PandaCanState::LecErrorCode(can_health.last_error)); - cs.setLastStoredError(cereal::PandaState::PandaCanState::LecErrorCode(can_health.last_stored_error)); - cs.setLastDataError(cereal::PandaState::PandaCanState::LecErrorCode(can_health.last_data_error)); - cs.setLastDataStoredError(cereal::PandaState::PandaCanState::LecErrorCode(can_health.last_data_stored_error)); - cs.setReceiveErrorCnt(can_health.receive_error_cnt); - cs.setTransmitErrorCnt(can_health.transmit_error_cnt); - cs.setTotalErrorCnt(can_health.total_error_cnt); - cs.setTotalTxLostCnt(can_health.total_tx_lost_cnt); - cs.setTotalRxLostCnt(can_health.total_rx_lost_cnt); - cs.setTotalTxCnt(can_health.total_tx_cnt); - cs.setTotalRxCnt(can_health.total_rx_cnt); - cs.setTotalFwdCnt(can_health.total_fwd_cnt); - cs.setCanSpeed(can_health.can_speed); - cs.setCanDataSpeed(can_health.can_data_speed); - cs.setCanfdEnabled(can_health.canfd_enabled); - cs.setBrsEnabled(can_health.brs_enabled); - cs.setCanfdNonIso(can_health.canfd_non_iso); - cs.setIrq0CallRate(can_health.irq0_call_rate); - cs.setIrq1CallRate(can_health.irq1_call_rate); - cs.setIrq2CallRate(can_health.irq2_call_rate); - cs.setCanCoreResetCnt(can_health.can_core_reset_cnt); -} - -std::optional send_panda_states(PubMaster *pm, const std::vector &pandas, bool spoofing_started, bool always_offroad) { - bool ignition_local = false; - const uint32_t pandas_cnt = pandas.size(); - - // build msg - MessageBuilder msg; - auto evt = msg.initEvent(); - auto pss = evt.initPandaStates(pandas_cnt); - - std::vector pandaStates; - pandaStates.reserve(pandas_cnt); - - std::vector> pandaCanStates; - pandaCanStates.reserve(pandas_cnt); - - const bool red_panda_comma_three = (pandas.size() == 2) && - (pandas[0]->hw_type == cereal::PandaState::PandaType::DOS) && - (pandas[1]->hw_type == cereal::PandaState::PandaType::RED_PANDA); - - for (const auto& panda : pandas){ - auto health_opt = panda->get_state(); - if (!health_opt) { - return std::nullopt; - } - - health_t health = *health_opt; - - std::array can_health{}; - for (uint32_t i = 0; i < PANDA_CAN_CNT; i++) { - auto can_health_opt = panda->get_can_state(i); - if (!can_health_opt) { - return std::nullopt; - } - can_health[i] = *can_health_opt; - } - pandaCanStates.push_back(can_health); - - if (spoofing_started) { - health.ignition_line_pkt = 1; - } - - // on comma three setups with a red panda, the dos can - // get false positive ignitions due to the harness box - // without a harness connector, so ignore it - if (red_panda_comma_three && (panda->hw_type == cereal::PandaState::PandaType::DOS)) { - health.ignition_line_pkt = 0; - } - - ignition_local |= ((health.ignition_line_pkt != 0) || (health.ignition_can_pkt != 0)) && !always_offroad; - - pandaStates.push_back(health); - } - - for (uint32_t i = 0; i < pandas_cnt; i++) { - auto panda = pandas[i]; - const auto &health = pandaStates[i]; - - // Make sure CAN buses are live: safety_setter_thread does not work if Panda CAN are silent and there is only one other CAN node - if (health.safety_mode_pkt == (uint8_t)(cereal::CarParams::SafetyModel::SILENT)) { - panda->set_safety_model(cereal::CarParams::SafetyModel::NO_OUTPUT); - } - - bool power_save_desired = !ignition_local; - if (health.power_save_enabled_pkt != power_save_desired) { - panda->set_power_saving(power_save_desired); - } - - // set safety mode to NO_OUTPUT when car is off. ELM327 is an alternative if we want to leverage athenad/connect - if (!ignition_local && (health.safety_mode_pkt != (uint8_t)(cereal::CarParams::SafetyModel::NO_OUTPUT))) { - panda->set_safety_model(cereal::CarParams::SafetyModel::NO_OUTPUT); - } - - if (!panda->comms_healthy()) { - evt.setValid(false); - } - - auto ps = pss[i]; - fill_panda_state(ps, panda->hw_type, health); - - auto cs = std::array{ps.initCanState0(), ps.initCanState1(), ps.initCanState2()}; - for (uint32_t j = 0; j < PANDA_CAN_CNT; j++) { - fill_panda_can_state(cs[j], pandaCanStates[i][j]); - } - - // Convert faults bitset to capnp list - std::bitset fault_bits(health.faults_pkt); - auto faults = ps.initFaults(fault_bits.count()); - - size_t j = 0; - for (size_t f = size_t(cereal::PandaState::FaultType::RELAY_MALFUNCTION); - f <= size_t(cereal::PandaState::FaultType::HEARTBEAT_LOOP_WATCHDOG); f++) { - if (fault_bits.test(f)) { - faults.set(j, cereal::PandaState::FaultType(f)); - j++; - } - } - } - - pm->send("pandaStates", msg); - return ignition_local; -} - -void send_peripheral_state(Panda *panda, PubMaster *pm) { - // build msg - MessageBuilder msg; - auto evt = msg.initEvent(); - evt.setValid(panda->comms_healthy()); - - auto ps = evt.initPeripheralState(); - ps.setPandaType(panda->hw_type); - - double read_time = millis_since_boot(); - ps.setVoltage(Hardware::get_voltage()); - ps.setCurrent(Hardware::get_current()); - read_time = millis_since_boot() - read_time; - if (read_time > 50) { - LOGW("reading hwmon took %lfms", read_time); - } - - // fall back to panda's voltage and current measurement - if (ps.getVoltage() == 0 && ps.getCurrent() == 0) { - auto health_opt = panda->get_state(); - if (health_opt) { - health_t health = *health_opt; - ps.setVoltage(health.voltage_pkt); - ps.setCurrent(health.current_pkt); - } - } - - uint16_t fan_speed_rpm = panda->get_fan_speed(); - ps.setFanSpeedRpm(fan_speed_rpm); - - pm->send("peripheralState", msg); -} - -void process_panda_state(std::vector &pandas, PubMaster *pm, bool engaged, bool engaged_mads, bool spoofing_started, bool always_offroad) { - std::vector connected_serials; - for (Panda *p : pandas) { - connected_serials.push_back(p->hw_serial()); - } - - { - auto ignition_opt = send_panda_states(pm, pandas, spoofing_started, always_offroad); - if (!ignition_opt) { - LOGE("Failed to get ignition_opt"); - return; - } - - // check if we should have pandad reconnect - if (!ignition_opt.value()) { - bool comms_healthy = true; - for (const auto &panda : pandas) { - comms_healthy &= panda->comms_healthy(); - } - - if (!comms_healthy) { - LOGE("Reconnecting, communication to pandas not healthy"); - do_exit = true; - - } else { - // check for new pandas - for (std::string &s : Panda::list(true)) { - if (!std::count(connected_serials.begin(), connected_serials.end(), s)) { - LOGW("Reconnecting to new panda: %s", s.c_str()); - do_exit = true; - break; - } - } - } - } - - for (const auto &panda : pandas) { - panda->send_heartbeat(engaged, engaged_mads); - } - } -} - -void process_peripheral_state(Panda *panda, PubMaster *pm, bool no_fan_control) { - static SubMaster sm({"deviceState", "driverCameraState"}); - - static uint64_t last_driver_camera_t = 0; - static uint16_t prev_fan_speed = 999; - static uint16_t ir_pwr = 0; - static uint16_t prev_ir_pwr = 999; - - static FirstOrderFilter integ_lines_filter(0, 30.0, 0.05); - - { - sm.update(0); - if (sm.updated("deviceState") && !no_fan_control) { - // Fan speed - uint16_t fan_speed = sm["deviceState"].getDeviceState().getFanSpeedPercentDesired(); - if (fan_speed != prev_fan_speed || sm.frame % 100 == 0) { - panda->set_fan_speed(fan_speed); - prev_fan_speed = fan_speed; - } - } - - if (sm.updated("driverCameraState")) { - auto event = sm["driverCameraState"]; - int cur_integ_lines = event.getDriverCameraState().getIntegLines(); - - cur_integ_lines = integ_lines_filter.update(cur_integ_lines); - last_driver_camera_t = event.getLogMonoTime(); - - if (cur_integ_lines <= CUTOFF_IL) { - ir_pwr = 100.0 * MIN_IR_POWER; - } else if (cur_integ_lines > SATURATE_IL) { - ir_pwr = 100.0 * MAX_IR_POWER; - } else { - ir_pwr = 100.0 * (MIN_IR_POWER + ((cur_integ_lines - CUTOFF_IL) * (MAX_IR_POWER - MIN_IR_POWER) / (SATURATE_IL - CUTOFF_IL))); - } - } - - // Disable IR on input timeout - if (nanos_since_boot() - last_driver_camera_t > 1e9) { - ir_pwr = 0; - } - - if (ir_pwr != prev_ir_pwr || sm.frame % 100 == 0 || ir_pwr >= 50.0) { - panda->set_ir_pwr(ir_pwr); - Hardware::set_ir_power(ir_pwr); - prev_ir_pwr = ir_pwr; - } - } -} - -void pandad_run(std::vector &pandas) { - const bool no_fan_control = getenv("NO_FAN_CONTROL") != nullptr; - const bool spoofing_started = getenv("STARTED") != nullptr; - const bool fake_send = getenv("FAKESEND") != nullptr; - - // Start the CAN send thread - std::thread send_thread(can_send_thread, pandas, fake_send); - - RateKeeper rk("pandad", 100); - SubMaster sm({"selfdriveState", "selfdriveStateSP", "carParams"}); - PubMaster pm({"can", "pandaStates", "peripheralState"}); - PandaSafety panda_safety(pandas); - Panda *peripheral_panda = pandas[0]; - bool engaged = false; - bool engaged_mads = false; - bool always_offroad = false; - - // Main loop: receive CAN data and process states - while (!do_exit && check_all_connected(pandas)) { - can_recv(pandas, &pm); - - // Process peripheral state at 20 Hz - if (rk.frame() % 5 == 0) { - process_peripheral_state(peripheral_panda, &pm, no_fan_control); - } - - // Process panda state at 10 Hz - if (rk.frame() % 10 == 0) { - sm.update(0); - engaged = sm.allAliveAndValid({"selfdriveState"}) && sm["selfdriveState"].getSelfdriveState().getEnabled(); - engaged_mads = process_mads_heartbeat(&sm); - always_offroad = panda_safety.getOffroadMode(); - process_panda_state(pandas, &pm, engaged, engaged_mads, spoofing_started, always_offroad); - panda_safety.configureSafetyMode(); - } - - // Send out peripheralState at 2Hz - if (rk.frame() % 50 == 0) { - send_peripheral_state(peripheral_panda, &pm); - } - - // Forward logs from pandas to cloudlog if available - for (auto *panda : pandas) { - std::string log = panda->serial_read(); - if (!log.empty()) { - if (log.find("Register 0x") != std::string::npos) { - // Log register divergent faults as errors - LOGE("%s", log.c_str()); - } else { - LOGD("%s", log.c_str()); - } - } - } - - rk.keepTime(); - } - - // Close relay on exit to prevent a fault - const bool is_onroad = Params().getBool("IsOnroad"); - if (is_onroad && !engaged) { - for (auto &p : pandas) { - if (p->connected()) { - p->set_safety_model(cereal::CarParams::SafetyModel::NO_OUTPUT); - } - } - } - - send_thread.join(); -} - -void pandad_main_thread(std::vector serials) { - if (serials.size() == 0) { - serials = Panda::list(); - - if (serials.size() == 0) { - LOGW("no pandas found, exiting"); - return; - } - } - - std::string serials_str; - for (int i = 0; i < serials.size(); i++) { - serials_str += serials[i]; - if (i < serials.size() - 1) serials_str += ", "; - } - LOGW("connecting to pandas: %s", serials_str.c_str()); - - // connect to all provided serials - std::vector pandas; - for (int i = 0; i < serials.size() && !do_exit; /**/) { - Panda *p = connect(serials[i], i); - if (!p) { - util::sleep_for(100); - continue; - } - - pandas.push_back(p); - ++i; - } - - if (!do_exit) { - LOGW("connected to all pandas"); - pandad_run(pandas); - } - - for (Panda *panda : pandas) { - delete panda; - } -} diff --git a/selfdrive/pandad/pandad.h b/selfdrive/pandad/pandad.h deleted file mode 100644 index 7b37fbe59a..0000000000 --- a/selfdrive/pandad/pandad.h +++ /dev/null @@ -1,28 +0,0 @@ -#pragma once - -#include -#include - -#include "common/params.h" -#include "selfdrive/pandad/panda.h" - -void pandad_main_thread(std::vector serials); - -class PandaSafety { -public: - PandaSafety(const std::vector &pandas) : pandas_(pandas) {} - void configureSafetyMode(); - bool getOffroadMode(); - -private: - void updateMultiplexingMode(); - std::vector fetchCarParams(); - void setSafetyMode(const std::vector ¶ms_string); - - bool initialized_ = false; - bool log_once_ = false; - bool safety_configured_ = false; - bool prev_obd_multiplexing_ = false; - std::vector pandas_; - Params params_; -}; diff --git a/selfdrive/pandad/pandad.py b/selfdrive/pandad/pandad.py deleted file mode 100755 index b33ffb6473..0000000000 --- a/selfdrive/pandad/pandad.py +++ /dev/null @@ -1,179 +0,0 @@ -#!/usr/bin/env python3 -# simple pandad wrapper that updates the panda first -import os -import usb1 -import time -import signal -import subprocess - -from panda import Panda, PandaDFU, PandaProtocolMismatch, FW_PATH -from openpilot.common.basedir import BASEDIR -from openpilot.common.params import Params -from openpilot.system.hardware import HARDWARE -from openpilot.common.swaglog import cloudlog - - -def get_expected_signature(panda: Panda) -> bytes: - try: - fn = os.path.join(FW_PATH, panda.get_mcu_type().config.app_fn) - return Panda.get_signature_from_firmware(fn) - except Exception: - cloudlog.exception("Error computing expected signature") - return b"" - -def flash_panda(panda_serial: str) -> Panda: - try: - panda = Panda(panda_serial) - except PandaProtocolMismatch: - cloudlog.warning("detected protocol mismatch, reflashing panda") - HARDWARE.recover_internal_panda() - raise - - fw_signature = get_expected_signature(panda) - internal_panda = panda.is_internal() - - panda_version = "bootstub" if panda.bootstub else panda.get_version() - panda_signature = b"" if panda.bootstub else panda.get_signature() - cloudlog.warning(f"Panda {panda_serial} connected, version: {panda_version}, signature {panda_signature.hex()[:16]}, expected {fw_signature.hex()[:16]}") - - if panda.bootstub or panda_signature != fw_signature: - cloudlog.info("Panda firmware out of date, update required") - panda.flash() - cloudlog.info("Done flashing") - - if panda.bootstub: - bootstub_version = panda.get_version() - cloudlog.info(f"Flashed firmware not booting, flashing development bootloader. {bootstub_version=}, {internal_panda=}") - if internal_panda: - HARDWARE.recover_internal_panda() - panda.recover(reset=(not internal_panda)) - cloudlog.info("Done flashing bootstub") - - if panda.bootstub: - cloudlog.info("Panda still not booting, exiting") - raise AssertionError - - panda_signature = panda.get_signature() - if panda_signature != fw_signature: - cloudlog.info("Version mismatch after flashing, exiting") - raise AssertionError - - return panda - - -def main() -> None: - # signal pandad to close the relay and exit - def signal_handler(signum, frame): - cloudlog.info(f"Caught signal {signum}, exiting") - nonlocal do_exit - do_exit = True - if process is not None: - process.send_signal(signal.SIGINT) - - process = None - do_exit = False - signal.signal(signal.SIGINT, signal_handler) - - count = 0 - first_run = True - params = Params() - no_internal_panda_count = 0 - - while not do_exit: - try: - count += 1 - cloudlog.event("pandad.flash_and_connect", count=count) - params.remove("PandaSignatures") - - # TODO: remove this in the next AGNOS - # wait until USB is up before counting - if time.monotonic() < 35.: - no_internal_panda_count = 0 - - # Handle missing internal panda - if no_internal_panda_count > 0: - if no_internal_panda_count == 3: - cloudlog.info("No pandas found, putting internal panda into DFU") - HARDWARE.recover_internal_panda() - else: - cloudlog.info("No pandas found, resetting internal panda") - HARDWARE.reset_internal_panda() - time.sleep(3) # wait to come back up - - # Flash all Pandas in DFU mode - dfu_serials = PandaDFU.list() - if len(dfu_serials) > 0: - for serial in dfu_serials: - cloudlog.info(f"Panda in DFU mode found, flashing recovery {serial}") - PandaDFU(serial).recover() - time.sleep(1) - - panda_serials = Panda.list() - if len(panda_serials) == 0: - no_internal_panda_count += 1 - continue - - cloudlog.info(f"{len(panda_serials)} panda(s) found, connecting - {panda_serials}") - - # Flash pandas - pandas: list[Panda] = [] - for serial in panda_serials: - pandas.append(flash_panda(serial)) - - # Ensure internal panda is present if expected - internal_pandas = [panda for panda in pandas if panda.is_internal()] - if HARDWARE.has_internal_panda() and len(internal_pandas) == 0: - cloudlog.error("Internal panda is missing, trying again") - no_internal_panda_count += 1 - continue - no_internal_panda_count = 0 - - # sort pandas to have deterministic order - # * the internal one is always first - # * then sort by hardware type - # * as a last resort, sort by serial number - pandas.sort(key=lambda x: (not x.is_internal(), x.get_type(), x.get_usb_serial())) - panda_serials = [p.get_usb_serial() for p in pandas] - - # log panda fw versions - params.put("PandaSignatures", b','.join(p.get_signature() for p in pandas)) - - for panda in pandas: - # check health for lost heartbeat - health = panda.health() - if health["heartbeat_lost"]: - params.put_bool("PandaHeartbeatLost", True) - cloudlog.event("heartbeat lost", deviceState=health, serial=panda.get_usb_serial()) - if health["som_reset_triggered"]: - params.put_bool("PandaSomResetTriggered", True) - cloudlog.event("panda.som_reset_triggered", health=health, serial=panda.get_usb_serial()) - - if first_run: - # reset panda to ensure we're in a good state - cloudlog.info(f"Resetting panda {panda.get_usb_serial()}") - panda.reset(reconnect=True) - - for p in pandas: - p.close() - # TODO: wrap all panda exceptions in a base panda exception - except (usb1.USBErrorNoDevice, usb1.USBErrorPipe): - # a panda was disconnected while setting everything up. let's try again - cloudlog.exception("Panda USB exception while setting up") - continue - except PandaProtocolMismatch: - cloudlog.exception("pandad.protocol_mismatch") - continue - except Exception: - cloudlog.exception("pandad.uncaught_exception") - continue - - first_run = False - - # run pandad with all connected serials as arguments - os.environ['MANAGER_DAEMON'] = 'pandad' - process = subprocess.Popen(["./pandad", *panda_serials], cwd=os.path.join(BASEDIR, "selfdrive/pandad")) - process.wait() - - -if __name__ == "__main__": - main() diff --git a/selfdrive/pandad/pandad_api_impl.pyx b/selfdrive/pandad/pandad_api_impl.pyx deleted file mode 100644 index 6683b843ae..0000000000 --- a/selfdrive/pandad/pandad_api_impl.pyx +++ /dev/null @@ -1,56 +0,0 @@ -# distutils: language = c++ -# cython: language_level=3 -from cython.operator cimport dereference as deref, preincrement as preinc -from libcpp.vector cimport vector -from libcpp.string cimport string -from libcpp cimport bool -from libc.stdint cimport uint8_t, uint32_t, uint64_t - -cdef extern from "opendbc/can/common.h": - cdef struct CanFrame: - long src - uint32_t address - vector[uint8_t] dat - - cdef struct CanData: - uint64_t nanos - vector[CanFrame] frames - -cdef extern from "can_list_to_can_capnp.cc": - void can_list_to_can_capnp_cpp(const vector[CanFrame] &can_list, string &out, bool sendcan, bool valid) nogil - void can_capnp_to_can_list_cpp(const vector[string] &strings, vector[CanData] &can_data, bool sendcan) - -def can_list_to_can_capnp(can_msgs, msgtype='can', valid=True): - cdef CanFrame *f - cdef vector[CanFrame] can_list - cdef uint32_t cpp_can_msgs_len = len(can_msgs) - - with nogil: - can_list.reserve(cpp_can_msgs_len) - - for can_msg in can_msgs: - f = &(can_list.emplace_back()) - f.address = can_msg[0] - f.dat = can_msg[1] - f.src = can_msg[2] - - cdef string out - cdef bool is_sendcan = (msgtype == 'sendcan') - cdef bool is_valid = valid - with nogil: - can_list_to_can_capnp_cpp(can_list, out, is_sendcan, is_valid) - return out - -def can_capnp_to_list(strings, msgtype='can'): - cdef vector[CanData] data - can_capnp_to_can_list_cpp(strings, data, msgtype == 'sendcan') - - result = [] - cdef CanData *d - cdef vector[CanData].iterator it = data.begin() - while it != data.end(): - d = &deref(it) - frames = [(f.address, (&f.dat[0])[:f.dat.size()], f.src) for f in d.frames] - result.append((d.nanos, frames)) - preinc(it) - return result diff --git a/selfdrive/pandad/tests/bootstub.panda.bin b/selfdrive/pandad/tests/bootstub.panda.bin deleted file mode 100755 index 43db537061..0000000000 Binary files a/selfdrive/pandad/tests/bootstub.panda.bin and /dev/null differ diff --git a/selfdrive/pandad/tests/bootstub.panda_h7_spiv0.bin b/selfdrive/pandad/tests/bootstub.panda_h7_spiv0.bin deleted file mode 100755 index 5cf2fa4519..0000000000 Binary files a/selfdrive/pandad/tests/bootstub.panda_h7_spiv0.bin and /dev/null differ diff --git a/selfdrive/pandad/tests/test_pandad.py b/selfdrive/pandad/tests/test_pandad.py deleted file mode 100644 index 87f30e4793..0000000000 --- a/selfdrive/pandad/tests/test_pandad.py +++ /dev/null @@ -1,129 +0,0 @@ -import os -import pytest -import time - -import cereal.messaging as messaging -from cereal import log -from openpilot.common.gpio import gpio_set, gpio_init -from panda import Panda, PandaDFU, PandaProtocolMismatch -from openpilot.common.retry import retry -from openpilot.system.manager.process_config import managed_processes -from openpilot.system.hardware import HARDWARE -from openpilot.system.hardware.tici.pins import GPIO - -HERE = os.path.dirname(os.path.realpath(__file__)) - - -@pytest.mark.tici -class TestPandad: - - def setup_method(self): - # ensure panda is up - if len(Panda.list()) == 0: - self._run_test(60) - - self.spi = HARDWARE.get_device_type() != 'tici' - - def teardown_method(self): - managed_processes['pandad'].stop() - - def _run_test(self, timeout=30) -> float: - st = time.monotonic() - sm = messaging.SubMaster(['pandaStates']) - - managed_processes['pandad'].start() - while (time.monotonic() - st) < timeout: - sm.update(100) - if len(sm['pandaStates']) and sm['pandaStates'][0].pandaType != log.PandaState.PandaType.unknown: - break - dt = time.monotonic() - st - managed_processes['pandad'].stop() - - if len(sm['pandaStates']) == 0 or sm['pandaStates'][0].pandaType == log.PandaState.PandaType.unknown: - raise Exception("pandad failed to start") - - return dt - - def _go_to_dfu(self): - HARDWARE.recover_internal_panda() - assert Panda.wait_for_dfu(None, 10) - - def _assert_no_panda(self): - assert not Panda.wait_for_dfu(None, 3) - assert not Panda.wait_for_panda(None, 3) - - @retry(attempts=3) - def _flash_bootstub_and_test(self, fn, expect_mismatch=False): - self._go_to_dfu() - pd = PandaDFU(None) - if fn is None: - fn = os.path.join(HERE, pd.get_mcu_type().config.bootstub_fn) - with open(fn, "rb") as f: - pd.program_bootstub(f.read()) - pd.reset() - HARDWARE.reset_internal_panda() - - assert Panda.wait_for_panda(None, 10) - if expect_mismatch: - with pytest.raises(PandaProtocolMismatch): - Panda() - else: - with Panda() as p: - assert p.bootstub - - self._run_test(45) - - def test_in_dfu(self): - HARDWARE.recover_internal_panda() - self._run_test(60) - - def test_in_bootstub(self): - with Panda() as p: - p.reset(enter_bootstub=True) - assert p.bootstub - self._run_test() - - def test_internal_panda_reset(self): - gpio_init(GPIO.STM_RST_N, True) - gpio_set(GPIO.STM_RST_N, 1) - time.sleep(0.5) - assert all(not Panda(s).is_internal() for s in Panda.list()) - self._run_test() - - assert any(Panda(s).is_internal() for s in Panda.list()) - - def test_best_case_startup_time(self): - # run once so we're up to date - self._run_test(60) - - ts = [] - for _ in range(10): - # should be nearly instant this time - dt = self._run_test(5) - ts.append(dt) - - # 5s for USB (due to enumeration) - # - 0.2s pandad -> pandad - # - plus some buffer - print("startup times", ts, sum(ts) / len(ts)) - assert 0.1 < (sum(ts)/len(ts)) < (0.7 if self.spi else 5.0) - - def test_protocol_version_check(self): - if not self.spi: - pytest.skip("SPI test") - # flash old fw - fn = os.path.join(HERE, "bootstub.panda_h7_spiv0.bin") - self._flash_bootstub_and_test(fn, expect_mismatch=True) - - def test_release_to_devel_bootstub(self): - self._flash_bootstub_and_test(None) - - def test_recover_from_bad_bootstub(self): - self._go_to_dfu() - with PandaDFU(None) as pd: - pd.program_bootstub(b"\x00"*1024) - pd.reset() - HARDWARE.reset_internal_panda() - self._assert_no_panda() - - self._run_test(60) diff --git a/selfdrive/pandad/tests/test_pandad_usbprotocol.cc b/selfdrive/pandad/tests/test_pandad_usbprotocol.cc deleted file mode 100644 index 11f7184efd..0000000000 --- a/selfdrive/pandad/tests/test_pandad_usbprotocol.cc +++ /dev/null @@ -1,135 +0,0 @@ -#define CATCH_CONFIG_MAIN -#define CATCH_CONFIG_ENABLE_BENCHMARKING - -#include "catch2/catch.hpp" -#include "cereal/messaging/messaging.h" -#include "common/util.h" -#include "selfdrive/pandad/panda.h" - -struct PandaTest : public Panda { - PandaTest(uint32_t bus_offset, int can_list_size, cereal::PandaState::PandaType hw_type); - void test_can_send(); - void test_can_recv(uint32_t chunk_size = 0); - void test_chunked_can_recv(); - - std::map test_data; - int can_list_size = 0; - int total_pakets_size = 0; - MessageBuilder msg; - capnp::List::Reader can_data_list; -}; - -PandaTest::PandaTest(uint32_t bus_offset_, int can_list_size, cereal::PandaState::PandaType hw_type) : can_list_size(can_list_size), Panda(bus_offset_) { - this->hw_type = hw_type; - int data_limit = ((hw_type == cereal::PandaState::PandaType::RED_PANDA) ? std::size(dlc_to_len) : 8); - // prepare test data - for (int i = 0; i < data_limit; ++i) { - std::random_device rd; - std::independent_bits_engine rbe(rd()); - - int data_len = dlc_to_len[i]; - std::string bytes(data_len, '\0'); - std::generate(bytes.begin(), bytes.end(), std::ref(rbe)); - test_data[data_len] = bytes; - } - - // generate can messages for this panda - auto can_list = msg.initEvent().initSendcan(can_list_size); - for (uint8_t i = 0; i < can_list_size; ++i) { - auto can = can_list[i]; - uint32_t id = util::random_int(0, std::size(dlc_to_len) - 1); - const std::string &dat = test_data[dlc_to_len[id]]; - can.setAddress(i); - can.setSrc(util::random_int(0, 2) + bus_offset); - can.setDat(kj::ArrayPtr((uint8_t *)dat.data(), dat.size())); - total_pakets_size += sizeof(can_header) + dat.size(); - } - - can_data_list = can_list.asReader(); - INFO("test " << can_list_size << " packets, total size " << total_pakets_size); -} - -void PandaTest::test_can_send() { - std::vector unpacked_data; - this->pack_can_buffer(can_data_list, [&](uint8_t *chunk, size_t size) { - unpacked_data.insert(unpacked_data.end(), chunk, &chunk[size]); - }); - REQUIRE(unpacked_data.size() == total_pakets_size); - - int cnt = 0; - INFO("test can message integrity"); - for (int pos = 0, pckt_len = 0; pos < unpacked_data.size(); pos += pckt_len) { - can_header header; - memcpy(&header, &unpacked_data[pos], sizeof(can_header)); - const uint8_t data_len = dlc_to_len[header.data_len_code]; - pckt_len = sizeof(can_header) + data_len; - - REQUIRE(header.addr == cnt); - REQUIRE(test_data.find(data_len) != test_data.end()); - const std::string &dat = test_data[data_len]; - REQUIRE(memcmp(dat.data(), &unpacked_data[pos + sizeof(can_header)], dat.size()) == 0); - ++cnt; - } - REQUIRE(cnt == can_list_size); -} - -void PandaTest::test_can_recv(uint32_t rx_chunk_size) { - std::vector frames; - this->pack_can_buffer(can_data_list, [&](uint8_t *data, uint32_t size) { - if (rx_chunk_size == 0) { - REQUIRE(this->unpack_can_buffer(data, size, frames)); - } else { - this->receive_buffer_size = 0; - uint32_t pos = 0; - - while (pos < size) { - uint32_t chunk_size = std::min(rx_chunk_size, size - pos); - memcpy(&this->receive_buffer[this->receive_buffer_size], &data[pos], chunk_size); - this->receive_buffer_size += chunk_size; - pos += chunk_size; - - REQUIRE(this->unpack_can_buffer(this->receive_buffer, this->receive_buffer_size, frames)); - } - } - }); - - REQUIRE(frames.size() == can_list_size); - for (int i = 0; i < frames.size(); ++i) { - REQUIRE(frames[i].address == i); - REQUIRE(test_data.find(frames[i].dat.size()) != test_data.end()); - const std::string &dat = test_data[frames[i].dat.size()]; - REQUIRE(memcmp(dat.data(), frames[i].dat.data(), dat.size()) == 0); - } -} - -TEST_CASE("send/recv CAN 2.0 packets") { - auto bus_offset = GENERATE(0, 4); - auto can_list_size = GENERATE(1, 3, 5, 10, 30, 60, 100, 200); - PandaTest test(bus_offset, can_list_size, cereal::PandaState::PandaType::DOS); - - SECTION("can_send") { - test.test_can_send(); - } - SECTION("can_receive") { - test.test_can_recv(); - } - SECTION("chunked_can_receive") { - test.test_can_recv(0x40); - } -} - -TEST_CASE("send/recv CAN FD packets") { - auto bus_offset = GENERATE(0, 4); - auto can_list_size = GENERATE(1, 3, 5, 10, 30, 60, 100, 200); - PandaTest test(bus_offset, can_list_size, cereal::PandaState::PandaType::RED_PANDA); - - SECTION("can_send") { - test.test_can_send(); - } - SECTION("can_receive") { - test.test_can_recv(); - } - SECTION("chunked_can_receive") { - test.test_can_recv(0x40); - } -} diff --git a/selfdrive/selfdrived/alerts_offroad.json b/selfdrive/selfdrived/alerts_offroad.json deleted file mode 100644 index 1668bf17fd..0000000000 --- a/selfdrive/selfdrived/alerts_offroad.json +++ /dev/null @@ -1,52 +0,0 @@ -{ - "Offroad_TemperatureTooHigh": { - "text": "Device temperature too high. System cooling down before starting. Current internal component temperature: %1", - "severity": 0 - }, - "Offroad_ConnectivityNeededPrompt": { - "text": "Immediately connect to the internet to check for updates. If you do not connect to the internet, sunnypilot won't engage in %1", - "severity": 0, - "_comment": "Set extra field to number of days" - }, - "Offroad_ConnectivityNeeded": { - "text": "Connect to internet to check for updates. sunnypilot won't automatically start until it connects to internet to check for updates.", - "severity": 1 - }, - "Offroad_UpdateFailed": { - "text": "Unable to download updates\n%1", - "severity": 1, - "_comment": "Set extra field to the failed reason." - }, - "Offroad_IsTakingSnapshot": { - "text": "Taking camera snapshots. System won't start until finished.", - "severity": 0 - }, - "Offroad_NeosUpdate": { - "text": "An update to your device's operating system is downloading in the background. You will be prompted to update when it's ready to install.", - "severity": 0 - }, - "Offroad_UnofficialHardware": { - "text": "Device failed to register. It will not connect to or upload to comma.ai servers, and receives no support from comma.ai. If this is an official device, visit https://comma.ai/support.", - "severity": 1 - }, - "Offroad_StorageMissing": { - "text": "NVMe drive not mounted.", - "severity": 1 - }, - "Offroad_BadNvme": { - "text": "Unsupported NVMe drive detected. Device may draw significantly more power and overheat due to the unsupported NVMe.", - "severity": 1 - }, - "Offroad_CarUnrecognized": { - "text": "sunnypilot was unable to identify your car. Your car is either unsupported or its ECUs are not recognized. Please submit a pull request to add the firmware versions to the proper vehicle. Need help? Join discord.comma.ai.", - "severity": 0 - }, - "Offroad_Recalibration": { - "text": "sunnypilot detected a change in the device's mounting position. Ensure the device is fully seated in the mount and the mount is firmly secured to the windshield.", - "severity": 0 - }, - "Offroad_OSMUpdateRequired": { - "text": "OpenStreetMap database is out of date. New maps must be downloaded if you wish to continue using OpenStreetMap data for Enhanced Speed Control and road name display.\n\n%1", - "severity": 0 - } -} diff --git a/selfdrive/selfdrived/events.py b/selfdrive/selfdrived/events.py deleted file mode 100755 index 9bfc638db3..0000000000 --- a/selfdrive/selfdrived/events.py +++ /dev/null @@ -1,854 +0,0 @@ -#!/usr/bin/env python3 -import math -import os - -from cereal import log, car -import cereal.messaging as messaging -from openpilot.common.conversions import Conversions as CV -from openpilot.common.git import get_short_branch -from openpilot.common.realtime import DT_CTRL -from openpilot.selfdrive.locationd.calibrationd import MIN_SPEED_FILTER - -from openpilot.sunnypilot.selfdrive.selfdrived.events_base import EventsBase, Priority, ET, Alert, \ - NoEntryAlert, SoftDisableAlert, UserSoftDisableAlert, ImmediateDisableAlert, EngagementAlert, NormalPermanentAlert, \ - StartupAlert, AlertCallbackType, wrong_car_mode_alert - - -AlertSize = log.SelfdriveState.AlertSize -AlertStatus = log.SelfdriveState.AlertStatus -VisualAlert = car.CarControl.HUDControl.VisualAlert -AudibleAlert = car.CarControl.HUDControl.AudibleAlert -EventName = log.OnroadEvent.EventName - - -# get event name from enum -EVENT_NAME = {v: k for k, v in EventName.schema.enumerants.items()} - - -class Events(EventsBase): - def __init__(self): - super().__init__() - self.event_counters = dict.fromkeys(EVENTS.keys(), 0) - - def get_events_mapping(self) -> dict[int, dict[str, Alert | AlertCallbackType]]: - return EVENTS - - def get_event_name(self, event: int): - return EVENT_NAME[event] - - def get_event_msg_type(self): - return log.OnroadEvent - - -# ********** helper functions ********** -def get_display_speed(speed_ms: float, metric: bool) -> str: - speed = int(round(speed_ms * (CV.MS_TO_KPH if metric else CV.MS_TO_MPH))) - unit = 'km/h' if metric else 'mph' - return f"{speed} {unit}" - - -# ********** alert callback functions ********** - - -def soft_disable_alert(alert_text_2: str) -> AlertCallbackType: - def func(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: - if soft_disable_time < int(0.5 / DT_CTRL): - return ImmediateDisableAlert(alert_text_2) - return SoftDisableAlert(alert_text_2) - return func - -def user_soft_disable_alert(alert_text_2: str) -> AlertCallbackType: - def func(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: - if soft_disable_time < int(0.5 / DT_CTRL): - return ImmediateDisableAlert(alert_text_2) - return UserSoftDisableAlert(alert_text_2) - return func - -def startup_master_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: - branch = get_short_branch() # Ensure get_short_branch is cached to avoid lags on startup - if "REPLAY" in os.environ: - branch = "replay" - - return StartupAlert("WARNING: This branch is not tested", branch, alert_status=AlertStatus.userPrompt) - -def below_engage_speed_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: - return NoEntryAlert(f"Drive above {get_display_speed(CP.minEnableSpeed, metric)} to engage") - - -def below_steer_speed_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: - return Alert( - f"Steer Unavailable Below {get_display_speed(CP.minSteerSpeed, metric)}", - "", - AlertStatus.userPrompt, AlertSize.small, - Priority.LOW, VisualAlert.steerRequired, AudibleAlert.prompt, 0.4) - - -def calibration_incomplete_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: - first_word = 'Recalibration' if sm['liveCalibration'].calStatus == log.LiveCalibrationData.Status.recalibrating else 'Calibration' - return Alert( - f"{first_word} in Progress: {sm['liveCalibration'].calPerc:.0f}%", - f"Drive Above {get_display_speed(MIN_SPEED_FILTER, metric)}", - AlertStatus.normal, AlertSize.mid, - Priority.LOWEST, VisualAlert.none, AudibleAlert.none, .2) - - -# *** debug alerts *** - -def out_of_space_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: - full_perc = round(100. - sm['deviceState'].freeSpacePercent) - return NormalPermanentAlert("Out of Storage", f"{full_perc}% full") - - -def posenet_invalid_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: - mdl = sm['modelV2'].velocity.x[0] if len(sm['modelV2'].velocity.x) else math.nan - err = CS.vEgo - mdl - msg = f"Speed Error: {err:.1f} m/s" - return NoEntryAlert(msg, alert_text_1="Posenet Speed Invalid") - - -def process_not_running_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: - not_running = [p.name for p in sm['managerState'].processes if not p.running and p.shouldBeRunning] - msg = ', '.join(not_running) - return NoEntryAlert(msg, alert_text_1="Process Not Running") - - -def comm_issue_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: - bs = [s for s in sm.data.keys() if not sm.all_checks([s, ])] - msg = ', '.join(bs[:4]) # can't fit too many on one line - return NoEntryAlert(msg, alert_text_1="Communication Issue Between Processes") - - -def camera_malfunction_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: - all_cams = ('roadCameraState', 'driverCameraState', 'wideRoadCameraState') - bad_cams = [s.replace('State', '') for s in all_cams if s in sm.data.keys() and not sm.all_checks([s, ])] - return NormalPermanentAlert("Camera Malfunction", ', '.join(bad_cams)) - - -def calibration_invalid_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: - rpy = sm['liveCalibration'].rpyCalib - yaw = math.degrees(rpy[2] if len(rpy) == 3 else math.nan) - pitch = math.degrees(rpy[1] if len(rpy) == 3 else math.nan) - angles = f"Remount Device (Pitch: {pitch:.1f}°, Yaw: {yaw:.1f}°)" - return NormalPermanentAlert("Calibration Invalid", angles) - - -def paramsd_invalid_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: - if not sm['liveParameters'].angleOffsetValid: - angle_offset_deg = sm['liveParameters'].angleOffsetDeg - title = "Steering misalignment detected" - text = f"Angle offset too high (Offset: {angle_offset_deg:.1f}°)" - elif not sm['liveParameters'].steerRatioValid: - steer_ratio = sm['liveParameters'].steerRatio - title = "Steer ratio mismatch" - text = f"Steering rack geometry may be off (Ratio: {steer_ratio:.1f})" - elif not sm['liveParameters'].stiffnessFactorValid: - stiffness_factor = sm['liveParameters'].stiffnessFactor - title = "Abnormal tire stiffness" - text = f"Check tires, pressure, or alignment (Factor: {stiffness_factor:.1f})" - else: - return NoEntryAlert("paramsd Temporary Error") - - return NoEntryAlert(alert_text_1=title, alert_text_2=text) - -def overheat_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: - cpu = max(sm['deviceState'].cpuTempC, default=0.) - gpu = max(sm['deviceState'].gpuTempC, default=0.) - temp = max((cpu, gpu, sm['deviceState'].memoryTempC)) - return NormalPermanentAlert("System Overheated", f"{temp:.0f} °C") - - -def low_memory_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: - return NormalPermanentAlert("Low Memory", f"{sm['deviceState'].memoryUsagePercent}% used") - - -def high_cpu_usage_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: - x = max(sm['deviceState'].cpuUsagePercent, default=0.) - return NormalPermanentAlert("High CPU Usage", f"{x}% used") - - -def modeld_lagging_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: - return NormalPermanentAlert("Driving Model Lagging", f"{sm['modelV2'].frameDropPerc:.1f}% frames dropped") - - -def joystick_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: - gb = sm['carControl'].actuators.accel / 4. - steer = sm['carControl'].actuators.torque - vals = f"Gas: {round(gb * 100.)}%, Steer: {round(steer * 100.)}%" - return NormalPermanentAlert("Joystick Mode", vals) - - -def longitudinal_maneuver_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: - ad = sm['alertDebug'] - audible_alert = AudibleAlert.prompt if 'Active' in ad.alertText1 else AudibleAlert.none - alert_status = AlertStatus.userPrompt if 'Active' in ad.alertText1 else AlertStatus.normal - alert_size = AlertSize.mid if ad.alertText2 else AlertSize.small - return Alert(ad.alertText1, ad.alertText2, - alert_status, alert_size, - Priority.LOW, VisualAlert.none, audible_alert, 0.2) - - -def personality_changed_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: - personality = str(personality).title() - return NormalPermanentAlert(f"Driving Personality: {personality}", duration=1.5) - - -def invalid_lkas_setting_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: - text = "Toggle stock LKAS on or off to engage" - if CP.brand == "tesla": - text = "Switch to Traffic-Aware Cruise Control to engage" - elif CP.brand == "mazda": - text = "Enable your car's LKAS to engage" - elif CP.brand == "nissan": - text = "Disable your car's stock LKAS to engage" - return NormalPermanentAlert("Invalid LKAS setting", text) - - -EVENTS: dict[int, dict[str, Alert | AlertCallbackType]] = { - # ********** events with no alerts ********** - - EventName.stockFcw: {}, - EventName.actuatorsApiUnavailable: {}, - - # ********** events only containing alerts displayed in all states ********** - - EventName.joystickDebug: { - ET.WARNING: joystick_alert, - ET.PERMANENT: NormalPermanentAlert("Joystick Mode"), - }, - - EventName.longitudinalManeuver: { - ET.WARNING: longitudinal_maneuver_alert, - ET.PERMANENT: NormalPermanentAlert("Longitudinal Maneuver Mode", - "Ensure road ahead is clear"), - }, - - EventName.selfdriveInitializing: { - ET.NO_ENTRY: NoEntryAlert("System Initializing"), - }, - - EventName.startup: { - ET.PERMANENT: StartupAlert("Be ready to take over at any time") - }, - - EventName.startupMaster: { - ET.PERMANENT: startup_master_alert, - }, - - EventName.startupNoControl: { - ET.PERMANENT: StartupAlert("Dashcam mode"), - ET.NO_ENTRY: NoEntryAlert("Dashcam mode"), - }, - - EventName.startupNoCar: { - ET.PERMANENT: StartupAlert("Dashcam mode for unsupported car"), - }, - - EventName.startupNoSecOcKey: { - ET.PERMANENT: NormalPermanentAlert("Dashcam Mode", - "Security Key Not Available", - priority=Priority.HIGH), - }, - - EventName.dashcamMode: { - ET.PERMANENT: NormalPermanentAlert("Dashcam Mode", - priority=Priority.LOWEST), - }, - - EventName.invalidLkasSetting: { - ET.PERMANENT: invalid_lkas_setting_alert, - ET.NO_ENTRY: NoEntryAlert("Invalid LKAS setting"), - }, - - EventName.cruiseMismatch: { - #ET.PERMANENT: ImmediateDisableAlert("openpilot failed to cancel cruise"), - }, - - # openpilot doesn't recognize the car. This switches openpilot into a - # read-only mode. This can be solved by adding your fingerprint. - # See https://github.com/commaai/openpilot/wiki/Fingerprinting for more information - EventName.carUnrecognized: { - ET.PERMANENT: NormalPermanentAlert("Dashcam Mode", - "Car Unrecognized", - priority=Priority.LOWEST), - }, - - EventName.aeb: { - ET.PERMANENT: Alert( - "BRAKE!", - "Emergency Braking: Risk of Collision", - AlertStatus.critical, AlertSize.full, - Priority.HIGHEST, VisualAlert.fcw, AudibleAlert.none, 2.), - ET.NO_ENTRY: NoEntryAlert("AEB: Risk of Collision"), - }, - - EventName.stockAeb: { - ET.PERMANENT: Alert( - "BRAKE!", - "Stock AEB: Risk of Collision", - AlertStatus.critical, AlertSize.full, - Priority.HIGHEST, VisualAlert.fcw, AudibleAlert.none, 2.), - ET.NO_ENTRY: NoEntryAlert("Stock AEB: Risk of Collision"), - }, - - EventName.fcw: { - ET.PERMANENT: Alert( - "BRAKE!", - "Risk of Collision", - AlertStatus.critical, AlertSize.full, - Priority.HIGHEST, VisualAlert.fcw, AudibleAlert.warningSoft, 2.), - }, - - EventName.ldw: { - ET.PERMANENT: Alert( - "Lane Departure Detected", - "", - AlertStatus.userPrompt, AlertSize.small, - Priority.LOW, VisualAlert.ldw, AudibleAlert.prompt, 3.), - }, - - # ********** events only containing alerts that display while engaged ********** - - EventName.steerTempUnavailableSilent: { - ET.WARNING: Alert( - "Steering Temporarily Unavailable", - "", - AlertStatus.userPrompt, AlertSize.small, - Priority.LOW, VisualAlert.steerRequired, AudibleAlert.prompt, 1.8), - }, - - EventName.preDriverDistracted: { - ET.PERMANENT: Alert( - "Pay Attention", - "", - AlertStatus.normal, AlertSize.small, - Priority.LOW, VisualAlert.none, AudibleAlert.none, .1), - }, - - EventName.promptDriverDistracted: { - ET.PERMANENT: Alert( - "Pay Attention", - "Driver Distracted", - AlertStatus.userPrompt, AlertSize.mid, - Priority.MID, VisualAlert.steerRequired, AudibleAlert.promptDistracted, .1), - }, - - EventName.driverDistracted: { - ET.PERMANENT: Alert( - "DISENGAGE IMMEDIATELY", - "Driver Distracted", - AlertStatus.critical, AlertSize.full, - Priority.HIGH, VisualAlert.steerRequired, AudibleAlert.warningImmediate, .1), - }, - - EventName.preDriverUnresponsive: { - ET.PERMANENT: Alert( - "Touch Steering Wheel: No Face Detected", - "", - AlertStatus.normal, AlertSize.small, - Priority.LOW, VisualAlert.steerRequired, AudibleAlert.none, .1), - }, - - EventName.promptDriverUnresponsive: { - ET.PERMANENT: Alert( - "Touch Steering Wheel", - "Driver Unresponsive", - AlertStatus.userPrompt, AlertSize.mid, - Priority.MID, VisualAlert.steerRequired, AudibleAlert.promptDistracted, .1), - }, - - EventName.driverUnresponsive: { - ET.PERMANENT: Alert( - "DISENGAGE IMMEDIATELY", - "Driver Unresponsive", - AlertStatus.critical, AlertSize.full, - Priority.HIGH, VisualAlert.steerRequired, AudibleAlert.warningImmediate, .1), - }, - - EventName.manualRestart: { - ET.WARNING: Alert( - "TAKE CONTROL", - "Resume Driving Manually", - AlertStatus.userPrompt, AlertSize.mid, - Priority.LOW, VisualAlert.none, AudibleAlert.none, .2), - }, - - EventName.resumeRequired: { - ET.WARNING: Alert( - "Press Resume to Exit Standstill", - "", - AlertStatus.userPrompt, AlertSize.small, - Priority.LOW, VisualAlert.none, AudibleAlert.none, .2), - }, - - EventName.belowSteerSpeed: { - ET.WARNING: below_steer_speed_alert, - }, - - EventName.preLaneChangeLeft: { - ET.WARNING: Alert( - "Steer Left to Start Lane Change Once Safe", - "", - AlertStatus.normal, AlertSize.small, - Priority.LOW, VisualAlert.none, AudibleAlert.none, .1), - }, - - EventName.preLaneChangeRight: { - ET.WARNING: Alert( - "Steer Right to Start Lane Change Once Safe", - "", - AlertStatus.normal, AlertSize.small, - Priority.LOW, VisualAlert.none, AudibleAlert.none, .1), - }, - - EventName.laneChangeBlocked: { - ET.WARNING: Alert( - "Car Detected in Blindspot", - "", - AlertStatus.userPrompt, AlertSize.small, - Priority.LOW, VisualAlert.none, AudibleAlert.prompt, .1), - }, - - EventName.laneChange: { - ET.WARNING: Alert( - "Changing Lanes", - "", - AlertStatus.normal, AlertSize.small, - Priority.LOW, VisualAlert.none, AudibleAlert.none, .1), - }, - - EventName.steerSaturated: { - ET.WARNING: Alert( - "Take Control", - "Turn Exceeds Steering Limit", - AlertStatus.userPrompt, AlertSize.mid, - Priority.LOW, VisualAlert.steerRequired, AudibleAlert.promptRepeat, 2.), - }, - - # Thrown when the fan is driven at >50% but is not rotating - EventName.fanMalfunction: { - ET.PERMANENT: NormalPermanentAlert("Fan Malfunction", "Likely Hardware Issue"), - }, - - # Camera is not outputting frames - EventName.cameraMalfunction: { - ET.PERMANENT: camera_malfunction_alert, - ET.SOFT_DISABLE: soft_disable_alert("Camera Malfunction"), - ET.NO_ENTRY: NoEntryAlert("Camera Malfunction: Reboot Your Device"), - }, - # Camera framerate too low - EventName.cameraFrameRate: { - ET.PERMANENT: NormalPermanentAlert("Camera Frame Rate Low", "Reboot your Device"), - ET.SOFT_DISABLE: soft_disable_alert("Camera Frame Rate Low"), - ET.NO_ENTRY: NoEntryAlert("Camera Frame Rate Low: Reboot Your Device"), - }, - - # Unused - - EventName.locationdTemporaryError: { - ET.NO_ENTRY: NoEntryAlert("locationd Temporary Error"), - ET.SOFT_DISABLE: soft_disable_alert("locationd Temporary Error"), - }, - - EventName.locationdPermanentError: { - ET.NO_ENTRY: NoEntryAlert("locationd Permanent Error"), - ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("locationd Permanent Error"), - ET.PERMANENT: NormalPermanentAlert("locationd Permanent Error"), - }, - - # openpilot tries to learn certain parameters about your car by observing - # how the car behaves to steering inputs from both human and openpilot driving. - # This includes: - # - steer ratio: gear ratio of the steering rack. Steering angle divided by tire angle - # - tire stiffness: how much grip your tires have - # - angle offset: most steering angle sensors are offset and measure a non zero angle when driving straight - # This alert is thrown when any of these values exceed a sanity check. This can be caused by - # bad alignment or bad sensor data. If this happens consistently consider creating an issue on GitHub - EventName.paramsdTemporaryError: { - ET.NO_ENTRY: paramsd_invalid_alert, - ET.SOFT_DISABLE: soft_disable_alert("paramsd Temporary Error"), - }, - - EventName.paramsdPermanentError: { - ET.NO_ENTRY: NoEntryAlert("paramsd Permanent Error"), - ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("paramsd Permanent Error"), - ET.PERMANENT: NormalPermanentAlert("paramsd Permanent Error"), - }, - - # ********** events that affect controls state transitions ********** - - EventName.pcmEnable: { - ET.ENABLE: EngagementAlert(AudibleAlert.engage), - }, - - EventName.buttonEnable: { - ET.ENABLE: EngagementAlert(AudibleAlert.engage), - }, - - EventName.pcmDisable: { - ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), - }, - - EventName.buttonCancel: { - ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), - ET.NO_ENTRY: NoEntryAlert("Cancel Pressed"), - }, - - EventName.brakeHold: { - ET.WARNING: Alert( - "Press Resume to Exit Brake Hold", - "", - AlertStatus.userPrompt, AlertSize.small, - Priority.LOW, VisualAlert.none, AudibleAlert.none, .2), - }, - - EventName.parkBrake: { - ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), - ET.NO_ENTRY: NoEntryAlert("Parking Brake Engaged"), - }, - - EventName.pedalPressed: { - ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), - ET.NO_ENTRY: NoEntryAlert("Pedal Pressed", - visual_alert=VisualAlert.brakePressed), - }, - - EventName.steerDisengage: { - ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), - ET.NO_ENTRY: NoEntryAlert("Steering Pressed"), - }, - - EventName.preEnableStandstill: { - ET.PRE_ENABLE: Alert( - "Release Brake to Engage", - "", - AlertStatus.normal, AlertSize.small, - Priority.LOWEST, VisualAlert.none, AudibleAlert.none, .1, creation_delay=1.), - }, - - EventName.gasPressedOverride: { - ET.OVERRIDE_LONGITUDINAL: Alert( - "", - "", - AlertStatus.normal, AlertSize.none, - Priority.LOWEST, VisualAlert.none, AudibleAlert.none, .1), - }, - - EventName.steerOverride: { - ET.OVERRIDE_LATERAL: Alert( - "", - "", - AlertStatus.normal, AlertSize.none, - Priority.LOWEST, VisualAlert.none, AudibleAlert.none, .1), - }, - - EventName.wrongCarMode: { - ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), - ET.NO_ENTRY: wrong_car_mode_alert, - }, - - EventName.resumeBlocked: { - ET.NO_ENTRY: NoEntryAlert("Press Set to Engage"), - }, - - EventName.wrongCruiseMode: { - ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), - ET.NO_ENTRY: NoEntryAlert("Adaptive Cruise Disabled"), - }, - - EventName.steerTempUnavailable: { - ET.SOFT_DISABLE: soft_disable_alert("Steering Temporarily Unavailable"), - ET.NO_ENTRY: NoEntryAlert("Steering Temporarily Unavailable"), - }, - - EventName.steerTimeLimit: { - ET.SOFT_DISABLE: soft_disable_alert("Vehicle Steering Time Limit"), - ET.NO_ENTRY: NoEntryAlert("Vehicle Steering Time Limit"), - }, - - EventName.outOfSpace: { - ET.PERMANENT: out_of_space_alert, - ET.NO_ENTRY: NoEntryAlert("Out of Storage"), - }, - - EventName.belowEngageSpeed: { - ET.NO_ENTRY: below_engage_speed_alert, - }, - - EventName.sensorDataInvalid: { - ET.PERMANENT: Alert( - "Sensor Data Invalid", - "Possible Hardware Issue", - AlertStatus.normal, AlertSize.mid, - Priority.LOWER, VisualAlert.none, AudibleAlert.none, .2, creation_delay=1.), - ET.NO_ENTRY: NoEntryAlert("Sensor Data Invalid"), - ET.SOFT_DISABLE: soft_disable_alert("Sensor Data Invalid"), - }, - - EventName.noGps: { - }, - - EventName.tooDistracted: { - ET.NO_ENTRY: NoEntryAlert("Distraction Level Too High"), - }, - - EventName.overheat: { - ET.PERMANENT: overheat_alert, - ET.SOFT_DISABLE: soft_disable_alert("System Overheated"), - ET.NO_ENTRY: NoEntryAlert("System Overheated"), - }, - - EventName.wrongGear: { - ET.SOFT_DISABLE: user_soft_disable_alert("Gear not D"), - ET.NO_ENTRY: NoEntryAlert("Gear not D"), - }, - - # This alert is thrown when the calibration angles are outside of the acceptable range. - # For example if the device is pointed too much to the left or the right. - # Usually this can only be solved by removing the mount from the windshield completely, - # and attaching while making sure the device is pointed straight forward and is level. - # See https://comma.ai/setup for more information - EventName.calibrationInvalid: { - ET.PERMANENT: calibration_invalid_alert, - ET.SOFT_DISABLE: soft_disable_alert("Calibration Invalid: Remount Device & Recalibrate"), - ET.NO_ENTRY: NoEntryAlert("Calibration Invalid: Remount Device & Recalibrate"), - }, - - EventName.calibrationIncomplete: { - ET.PERMANENT: calibration_incomplete_alert, - ET.SOFT_DISABLE: soft_disable_alert("Calibration Incomplete"), - ET.NO_ENTRY: NoEntryAlert("Calibration in Progress"), - }, - - EventName.calibrationRecalibrating: { - ET.PERMANENT: calibration_incomplete_alert, - ET.SOFT_DISABLE: soft_disable_alert("Device Remount Detected: Recalibrating"), - ET.NO_ENTRY: NoEntryAlert("Remount Detected: Recalibrating"), - }, - - EventName.doorOpen: { - ET.SOFT_DISABLE: user_soft_disable_alert("Door Open"), - ET.NO_ENTRY: NoEntryAlert("Door Open"), - }, - - EventName.seatbeltNotLatched: { - ET.SOFT_DISABLE: user_soft_disable_alert("Seatbelt Unlatched"), - ET.NO_ENTRY: NoEntryAlert("Seatbelt Unlatched"), - }, - - EventName.espDisabled: { - ET.SOFT_DISABLE: soft_disable_alert("Electronic Stability Control Disabled"), - ET.NO_ENTRY: NoEntryAlert("Electronic Stability Control Disabled"), - }, - - EventName.lowBattery: { - ET.SOFT_DISABLE: soft_disable_alert("Low Battery"), - ET.NO_ENTRY: NoEntryAlert("Low Battery"), - }, - - # Different openpilot services communicate between each other at a certain - # interval. If communication does not follow the regular schedule this alert - # is thrown. This can mean a service crashed, did not broadcast a message for - # ten times the regular interval, or the average interval is more than 10% too high. - EventName.commIssue: { - ET.SOFT_DISABLE: soft_disable_alert("Communication Issue Between Processes"), - ET.NO_ENTRY: comm_issue_alert, - }, - EventName.commIssueAvgFreq: { - ET.SOFT_DISABLE: soft_disable_alert("Low Communication Rate Between Processes"), - ET.NO_ENTRY: NoEntryAlert("Low Communication Rate Between Processes"), - }, - - EventName.selfdrivedLagging: { - ET.SOFT_DISABLE: soft_disable_alert("System Lagging"), - ET.NO_ENTRY: NoEntryAlert("Selfdrive Process Lagging: Reboot Your Device"), - }, - - # Thrown when manager detects a service exited unexpectedly while driving - EventName.processNotRunning: { - ET.NO_ENTRY: process_not_running_alert, - ET.SOFT_DISABLE: soft_disable_alert("Process Not Running"), - }, - - EventName.radarFault: { - ET.SOFT_DISABLE: soft_disable_alert("Radar Error: Restart the Car"), - ET.NO_ENTRY: NoEntryAlert("Radar Error: Restart the Car"), - }, - - EventName.radarTempUnavailable: { - ET.SOFT_DISABLE: soft_disable_alert("Radar Temporarily Unavailable"), - ET.NO_ENTRY: NoEntryAlert("Radar Temporarily Unavailable"), - }, - - # Every frame from the camera should be processed by the model. If modeld - # is not processing frames fast enough they have to be dropped. This alert is - # thrown when over 20% of frames are dropped. - EventName.modeldLagging: { - ET.SOFT_DISABLE: soft_disable_alert("Driving Model Lagging"), - ET.NO_ENTRY: NoEntryAlert("Driving Model Lagging"), - ET.PERMANENT: modeld_lagging_alert, - }, - - # Besides predicting the path, lane lines and lead car data the model also - # predicts the current velocity and rotation speed of the car. If the model is - # very uncertain about the current velocity while the car is moving, this - # usually means the model has trouble understanding the scene. This is used - # as a heuristic to warn the driver. - EventName.posenetInvalid: { - ET.SOFT_DISABLE: soft_disable_alert("Posenet Speed Invalid"), - ET.NO_ENTRY: posenet_invalid_alert, - }, - - # When the localizer detects an acceleration of more than 40 m/s^2 (~4G) we - # alert the driver the device might have fallen from the windshield. - EventName.deviceFalling: { - ET.SOFT_DISABLE: soft_disable_alert("Device Fell Off Mount"), - ET.NO_ENTRY: NoEntryAlert("Device Fell Off Mount"), - }, - - EventName.lowMemory: { - ET.SOFT_DISABLE: soft_disable_alert("Low Memory: Reboot Your Device"), - ET.PERMANENT: low_memory_alert, - ET.NO_ENTRY: NoEntryAlert("Low Memory: Reboot Your Device"), - }, - - EventName.accFaulted: { - ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("Cruise Fault: Restart the Car"), - ET.PERMANENT: NormalPermanentAlert("Cruise Fault: Restart the car to engage"), - ET.NO_ENTRY: NoEntryAlert("Cruise Fault: Restart the Car"), - }, - - EventName.espActive: { - ET.SOFT_DISABLE: soft_disable_alert("Electronic Stability Control Active"), - ET.NO_ENTRY: NoEntryAlert("Electronic Stability Control Active"), - }, - - EventName.controlsMismatch: { - ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("Controls Mismatch"), - ET.NO_ENTRY: NoEntryAlert("Controls Mismatch"), - }, - - # Sometimes the USB stack on the device can get into a bad state - # causing the connection to the panda to be lost - EventName.usbError: { - ET.SOFT_DISABLE: soft_disable_alert("USB Error: Reboot Your Device"), - ET.PERMANENT: NormalPermanentAlert("USB Error: Reboot Your Device"), - ET.NO_ENTRY: NoEntryAlert("USB Error: Reboot Your Device"), - }, - - # This alert can be thrown for the following reasons: - # - No CAN data received at all - # - CAN data is received, but some message are not received at the right frequency - # If you're not writing a new car port, this is usually cause by faulty wiring - EventName.canError: { - ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("CAN Error"), - ET.PERMANENT: Alert( - "CAN Error: Check Connections", - "", - AlertStatus.normal, AlertSize.small, - Priority.LOW, VisualAlert.none, AudibleAlert.none, 1., creation_delay=1.), - ET.NO_ENTRY: NoEntryAlert("CAN Error: Check Connections"), - }, - - EventName.canBusMissing: { - ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("CAN Bus Disconnected"), - ET.PERMANENT: Alert( - "CAN Bus Disconnected: Likely Faulty Cable", - "", - AlertStatus.normal, AlertSize.small, - Priority.LOW, VisualAlert.none, AudibleAlert.none, 1., creation_delay=1.), - ET.NO_ENTRY: NoEntryAlert("CAN Bus Disconnected: Check Connections"), - }, - - EventName.steerUnavailable: { - ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("LKAS Fault: Restart the Car"), - ET.PERMANENT: NormalPermanentAlert("LKAS Fault: Restart the car to engage"), - ET.NO_ENTRY: NoEntryAlert("LKAS Fault: Restart the Car"), - }, - - EventName.reverseGear: { - ET.PERMANENT: Alert( - "Reverse\nGear", - "", - AlertStatus.normal, AlertSize.full, - Priority.LOWEST, VisualAlert.none, AudibleAlert.none, .2, creation_delay=0.5), - ET.USER_DISABLE: ImmediateDisableAlert("Reverse Gear"), - ET.NO_ENTRY: NoEntryAlert("Reverse Gear"), - }, - - # On cars that use stock ACC the car can decide to cancel ACC for various reasons. - # When this happens we can no long control the car so the user needs to be warned immediately. - EventName.cruiseDisabled: { - ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("Cruise Is Off"), - }, - - # When the relay in the harness box opens the CAN bus between the LKAS camera - # and the rest of the car is separated. When messages from the LKAS camera - # are received on the car side this usually means the relay hasn't opened correctly - # and this alert is thrown. - EventName.relayMalfunction: { - ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("Harness Relay Malfunction"), - ET.PERMANENT: NormalPermanentAlert("Harness Relay Malfunction", "Check Hardware"), - ET.NO_ENTRY: NoEntryAlert("Harness Relay Malfunction"), - }, - - EventName.speedTooLow: { - ET.IMMEDIATE_DISABLE: Alert( - "openpilot Canceled", - "Speed too low", - AlertStatus.normal, AlertSize.mid, - Priority.HIGH, VisualAlert.none, AudibleAlert.disengage, 3.), - }, - - # When the car is driving faster than most cars in the training data, the model outputs can be unpredictable. - EventName.speedTooHigh: { - ET.WARNING: Alert( - "Speed Too High", - "Model uncertain at this speed", - AlertStatus.userPrompt, AlertSize.mid, - Priority.HIGH, VisualAlert.steerRequired, AudibleAlert.promptRepeat, 4.), - ET.NO_ENTRY: NoEntryAlert("Slow down to engage"), - }, - - EventName.vehicleSensorsInvalid: { - ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("Vehicle Sensors Invalid"), - ET.PERMANENT: NormalPermanentAlert("Vehicle Sensors Calibrating", "Drive to Calibrate"), - ET.NO_ENTRY: NoEntryAlert("Vehicle Sensors Calibrating"), - }, - - EventName.personalityChanged: { - ET.WARNING: personality_changed_alert, - }, - - EventName.userFlag: { - ET.PERMANENT: NormalPermanentAlert("Bookmark Saved", duration=1.5), - }, -} - - -if __name__ == '__main__': - # print all alerts by type and priority - from cereal.services import SERVICE_LIST - from collections import defaultdict - - event_names = {v: k for k, v in EventName.schema.enumerants.items()} - alerts_by_type: dict[str, dict[Priority, list[str]]] = defaultdict(lambda: defaultdict(list)) - - CP = car.CarParams.new_message() - CS = car.CarState.new_message() - sm = messaging.SubMaster(list(SERVICE_LIST.keys())) - - for i, alerts in EVENTS.items(): - for et, alert in alerts.items(): - if callable(alert): - alert = alert(CP, CS, sm, False, 1, log.LongitudinalPersonality.standard) - alerts_by_type[et][alert.priority].append(event_names[i]) - - all_alerts: dict[str, list[tuple[Priority, list[str]]]] = {} - for et, priority_alerts in alerts_by_type.items(): - all_alerts[et] = sorted(priority_alerts.items(), key=lambda x: x[0], reverse=True) - - for status, evs in sorted(all_alerts.items(), key=lambda x: x[0]): - print(f"**** {status} ****") - for p, alert_list in evs: - print(f" {repr(p)}:") - print(" ", ', '.join(alert_list), "\n") diff --git a/selfdrive/selfdrived/state.py b/selfdrive/selfdrived/state.py deleted file mode 100644 index 073ddb56eb..0000000000 --- a/selfdrive/selfdrived/state.py +++ /dev/null @@ -1,98 +0,0 @@ -from cereal import log -from openpilot.selfdrive.selfdrived.events import Events, ET -from openpilot.common.realtime import DT_CTRL - -State = log.SelfdriveState.OpenpilotState - -SOFT_DISABLE_TIME = 3 # seconds -ACTIVE_STATES = (State.enabled, State.softDisabling, State.overriding) -ENABLED_STATES = (State.preEnabled, *ACTIVE_STATES) - -class StateMachine: - def __init__(self): - self.current_alert_types = [ET.PERMANENT] - self.state = State.disabled - self.soft_disable_timer = 0 - - def update(self, events: Events): - # decrement the soft disable timer at every step, as it's reset on - # entrance in SOFT_DISABLING state - self.soft_disable_timer = max(0, self.soft_disable_timer - 1) - - self.current_alert_types = [ET.PERMANENT] - - # ENABLED, SOFT DISABLING, PRE ENABLING, OVERRIDING - if self.state != State.disabled: - # user and immediate disable always have priority in a non-disabled state - if events.contains(ET.USER_DISABLE): - self.state = State.disabled - self.current_alert_types.append(ET.USER_DISABLE) - - elif events.contains(ET.IMMEDIATE_DISABLE): - self.state = State.disabled - self.current_alert_types.append(ET.IMMEDIATE_DISABLE) - - else: - # ENABLED - if self.state == State.enabled: - if events.contains(ET.SOFT_DISABLE): - self.state = State.softDisabling - self.soft_disable_timer = int(SOFT_DISABLE_TIME / DT_CTRL) - self.current_alert_types.append(ET.SOFT_DISABLE) - - elif events.contains(ET.OVERRIDE_LATERAL) or events.contains(ET.OVERRIDE_LONGITUDINAL): - self.state = State.overriding - self.current_alert_types += [ET.OVERRIDE_LATERAL, ET.OVERRIDE_LONGITUDINAL] - - # SOFT DISABLING - elif self.state == State.softDisabling: - if not events.contains(ET.SOFT_DISABLE): - # no more soft disabling condition, so go back to ENABLED - self.state = State.enabled - - elif self.soft_disable_timer > 0: - self.current_alert_types.append(ET.SOFT_DISABLE) - - elif self.soft_disable_timer <= 0: - self.state = State.disabled - - # PRE ENABLING - elif self.state == State.preEnabled: - if not events.contains(ET.PRE_ENABLE): - self.state = State.enabled - else: - self.current_alert_types.append(ET.PRE_ENABLE) - - # OVERRIDING - elif self.state == State.overriding: - if events.contains(ET.SOFT_DISABLE): - self.state = State.softDisabling - self.soft_disable_timer = int(SOFT_DISABLE_TIME / DT_CTRL) - self.current_alert_types.append(ET.SOFT_DISABLE) - elif not (events.contains(ET.OVERRIDE_LATERAL) or events.contains(ET.OVERRIDE_LONGITUDINAL)): - self.state = State.enabled - else: - self.current_alert_types += [ET.OVERRIDE_LATERAL, ET.OVERRIDE_LONGITUDINAL] - - # DISABLED - elif self.state == State.disabled: - if events.contains(ET.ENABLE): - if events.contains(ET.NO_ENTRY): - self.current_alert_types.append(ET.NO_ENTRY) - - else: - if events.contains(ET.PRE_ENABLE): - self.state = State.preEnabled - elif events.contains(ET.OVERRIDE_LATERAL) or events.contains(ET.OVERRIDE_LONGITUDINAL): - self.state = State.overriding - else: - self.state = State.enabled - self.current_alert_types.append(ET.ENABLE) - - # Check if openpilot is engaged and actuators are enabled - enabled = self.state in ENABLED_STATES - active = self.state in ACTIVE_STATES - if active: - self.current_alert_types.append(ET.WARNING) - return enabled, active - diff --git a/selfdrive/test/.gitignore b/selfdrive/test/.gitignore deleted file mode 100644 index 5801faadf4..0000000000 --- a/selfdrive/test/.gitignore +++ /dev/null @@ -1,9 +0,0 @@ -out/ -docker_out/ - -process_replay/diff.txt -process_replay/model_diff.txt -valgrind_logs.txt - -*.bz2 -*.hevc diff --git a/selfdrive/test/docker_build.sh b/selfdrive/test/docker_build.sh deleted file mode 100755 index 4d58a1507c..0000000000 --- a/selfdrive/test/docker_build.sh +++ /dev/null @@ -1,26 +0,0 @@ -#!/usr/bin/env bash -set -e - -# To build sim and docs, you can run the following to mount the scons cache to the same place as in CI: -# mkdir -p .ci_cache/scons_cache -# sudo mount --bind /tmp/scons_cache/ .ci_cache/scons_cache - -SCRIPT_DIR=$(dirname "$0") -OPENPILOT_DIR=$SCRIPT_DIR/../../ -if [ -n "$TARGET_ARCHITECTURE" ]; then - PLATFORM="linux/$TARGET_ARCHITECTURE" - TAG_SUFFIX="-$TARGET_ARCHITECTURE" -else - PLATFORM="linux/$(uname -m)" - TAG_SUFFIX="" -fi - -source $SCRIPT_DIR/docker_common.sh $1 "$TAG_SUFFIX" - -DOCKER_BUILDKIT=1 docker buildx build --provenance false --pull --platform $PLATFORM --load --cache-to type=inline --cache-from type=registry,ref=$REMOTE_TAG -t $DOCKER_IMAGE:latest -t $REMOTE_TAG -t $LOCAL_TAG -f $OPENPILOT_DIR/$DOCKER_FILE $OPENPILOT_DIR - -if [ -n "$PUSH_IMAGE" ]; then - docker push $REMOTE_TAG - docker tag $REMOTE_TAG $REMOTE_SHA_TAG - docker push $REMOTE_SHA_TAG -fi diff --git a/selfdrive/test/docker_common.sh b/selfdrive/test/docker_common.sh deleted file mode 100644 index 2887fff74b..0000000000 --- a/selfdrive/test/docker_common.sh +++ /dev/null @@ -1,18 +0,0 @@ -if [ "$1" = "base" ]; then - export DOCKER_IMAGE=openpilot-base - export DOCKER_FILE=Dockerfile.openpilot_base -elif [ "$1" = "prebuilt" ]; then - export DOCKER_IMAGE=openpilot-prebuilt - export DOCKER_FILE=Dockerfile.openpilot -else - echo "Invalid docker build image: '$1'" - exit 1 -fi - -export DOCKER_REGISTRY=ghcr.io/commaai -export COMMIT_SHA=$(git rev-parse HEAD) - -TAG_SUFFIX=$2 -LOCAL_TAG=$DOCKER_IMAGE$TAG_SUFFIX -REMOTE_TAG=$DOCKER_REGISTRY/$LOCAL_TAG -REMOTE_SHA_TAG=$DOCKER_REGISTRY/$LOCAL_TAG:$COMMIT_SHA diff --git a/selfdrive/test/helpers.py b/selfdrive/test/helpers.py deleted file mode 100644 index 81635aa31f..0000000000 --- a/selfdrive/test/helpers.py +++ /dev/null @@ -1,128 +0,0 @@ -import contextlib -import http.server -import os -import threading -import time -import pytest - -from functools import wraps - -import cereal.messaging as messaging -from openpilot.common.params import Params -from openpilot.system.manager.process_config import managed_processes -from openpilot.system.version import training_version, terms_version - - -def set_params_enabled(): - os.environ['FINGERPRINT'] = "TOYOTA_COROLLA_TSS2" - os.environ['LOGPRINT'] = "debug" - - params = Params() - params.put("HasAcceptedTerms", terms_version) - params.put("CompletedTrainingVersion", training_version) - params.put_bool("OpenpilotEnabledToggle", True) - - # valid calib - msg = messaging.new_message('liveCalibration') - msg.liveCalibration.validBlocks = 20 - msg.liveCalibration.rpyCalib = [0.0, 0.0, 0.0] - params.put("CalibrationParams", msg.to_bytes()) - -def release_only(f): - @wraps(f) - def wrap(self, *args, **kwargs): - if "RELEASE" not in os.environ: - pytest.skip("This test is only for release branches") - f(self, *args, **kwargs) - return wrap - - -@contextlib.contextmanager -def processes_context(processes, init_time=0, ignore_stopped=None): - ignore_stopped = [] if ignore_stopped is None else ignore_stopped - - # start and assert started - for n, p in enumerate(processes): - managed_processes[p].start() - if n < len(processes) - 1: - time.sleep(init_time) - - assert all(managed_processes[name].proc.exitcode is None for name in processes) - - try: - yield [managed_processes[name] for name in processes] - # assert processes are still started - assert all(managed_processes[name].proc.exitcode is None for name in processes if name not in ignore_stopped) - finally: - for p in processes: - managed_processes[p].stop() - - -def with_processes(processes, init_time=0, ignore_stopped=None): - def wrapper(func): - @wraps(func) - def wrap(*args, **kwargs): - with processes_context(processes, init_time, ignore_stopped): - return func(*args, **kwargs) - - return wrap - return wrapper - - -def noop(*args, **kwargs): - pass - - -def read_segment_list(segment_list_path): - with open(segment_list_path) as f: - seg_list = f.read().splitlines() - - return [(platform[2:], segment) for platform, segment in zip(seg_list[::2], seg_list[1::2], strict=True)] - - -@contextlib.contextmanager -def http_server_context(handler, setup=None): - host = '127.0.0.1' - server = http.server.HTTPServer((host, 0), handler) - port = server.server_port - t = threading.Thread(target=server.serve_forever) - t.start() - - if setup is not None: - setup(host, port) - - try: - yield (host, port) - finally: - server.shutdown() - server.server_close() - t.join() - - -def with_http_server(func, handler=http.server.BaseHTTPRequestHandler, setup=None): - @wraps(func) - def inner(*args, **kwargs): - with http_server_context(handler, setup) as (host, port): - return func(*args, f"http://{host}:{port}", **kwargs) - return inner - - -def DirectoryHttpServer(directory) -> type[http.server.SimpleHTTPRequestHandler]: - # creates an http server that serves files from directory - class Handler(http.server.SimpleHTTPRequestHandler): - API_NO_RESPONSE = False - API_BAD_RESPONSE = False - - def do_GET(self): - if self.API_NO_RESPONSE: - return - - if self.API_BAD_RESPONSE: - self.send_response(500, "") - return - super().do_GET() - - def __init__(self, *args, **kwargs): - super().__init__(*args, directory=str(directory), **kwargs) - - return Handler diff --git a/selfdrive/test/process_replay/.gitignore b/selfdrive/test/process_replay/.gitignore deleted file mode 100644 index a35cd58d41..0000000000 --- a/selfdrive/test/process_replay/.gitignore +++ /dev/null @@ -1 +0,0 @@ -fakedata/ diff --git a/selfdrive/test/process_replay/README.md b/selfdrive/test/process_replay/README.md deleted file mode 100644 index dc801e4285..0000000000 --- a/selfdrive/test/process_replay/README.md +++ /dev/null @@ -1,126 +0,0 @@ -# Process replay - -Process replay is a regression test designed to identify any changes in the output of a process. This test replays a segment through individual processes and compares the output to a known good replay. Each make is represented in the test with a segment. - -If the test fails, make sure that you didn't unintentionally change anything. If there are intentional changes, the reference logs will be updated. - -Use `test_processes.py` to run the test locally. -Use `FILEREADER_CACHE='1' test_processes.py` to cache log files. - -Currently the following processes are tested: - -* controlsd -* radard -* plannerd -* calibrationd -* dmonitoringd -* locationd -* paramsd -* ubloxd -* torqued - -### Usage -``` -Usage: test_processes.py [-h] [--whitelist-procs PROCS] [--whitelist-cars CARS] [--blacklist-procs PROCS] - [--blacklist-cars CARS] [--ignore-fields FIELDS] [--ignore-msgs MSGS] [--update-refs] [--upload-only] -Regression test to identify changes in a process's output -optional arguments: - -h, --help show this help message and exit - --whitelist-procs PROCS Whitelist given processes from the test (e.g. controlsd) - --whitelist-cars WHITELIST_CARS Whitelist given cars from the test (e.g. HONDA) - --blacklist-procs BLACKLIST_PROCS Blacklist given processes from the test (e.g. controlsd) - --blacklist-cars BLACKLIST_CARS Blacklist given cars from the test (e.g. HONDA) - --ignore-fields IGNORE_FIELDS Extra fields or msgs to ignore (e.g. driverMonitoringState.events) - --ignore-msgs IGNORE_MSGS Msgs to ignore (e.g. onroadEvents) - --update-refs Updates reference logs using current commit - --upload-only Skips testing processes and uploads logs from previous test run -``` - -## Forks - -openpilot forks can use this test with their own reference logs, by default `test_proccesses.py` saves logs locally. - -To generate new logs: - -`./test_processes.py` - -Then, check in the new logs using git-lfs. Make sure to also update the `ref_commit` file to the current commit. - -## API - -Process replay test suite exposes programmatic APIs for simultaneously running processes or groups of processes on provided logs. - -```py -def replay_process_with_name(name: Union[str, Iterable[str]], lr: LogIterable, *args, **kwargs) -> List[capnp._DynamicStructReader]: - -def replay_process( - cfg: Union[ProcessConfig, Iterable[ProcessConfig]], lr: LogIterable, frs: Optional[Dict[str, Any]] = None, - fingerprint: Optional[str] = None, return_all_logs: bool = False, custom_params: Optional[Dict[str, Any]] = None, disable_progress: bool = False -) -> List[capnp._DynamicStructReader]: -``` - -Example usage: -```py -from openpilot.selfdrive.test.process_replay import replay_process_with_name -from openpilot.tools.lib.logreader import LogReader - -lr = LogReader(...) - -# provide a name of the process to replay -output_logs = replay_process_with_name('locationd', lr) - -# or list of names -output_logs = replay_process_with_name(['ubloxd', 'locationd'], lr) -``` - -Supported processes: -* controlsd -* radard -* plannerd -* calibrationd -* dmonitoringd -* locationd -* paramsd -* ubloxd -* torqued -* modeld -* dmonitoringmodeld - -Certain processes may require an initial state, which is usually supplied within `Params` and persisting from segment to segment (e.g CalibrationParams, LiveParameters). The `custom_params` is dictionary used to prepopulate `Params` with arbitrary values. The `get_custom_params_from_lr` helper is provided to fetch meaningful values from log files. - -```py -from openpilot.selfdrive.test.process_replay import get_custom_params_from_lr - -previous_segment_lr = LogReader(...) -current_segment_lr = LogReader(...) - -custom_params = get_custom_params_from_lr(previous_segment_lr, 'last') - -output_logs = replay_process_with_name('calibrationd', lr, custom_params=custom_params) -``` - -Replaying processes that use VisionIPC (e.g. modeld, dmonitoringmodeld) require additional `frs` dictionary with camera states as keys and `FrameReader` objects as values. - -```py -from openpilot.tools.lib.framereader import FrameReader - -frs = { - 'roadCameraState': FrameReader(...), - 'wideRoadCameraState': FrameReader(...), - 'driverCameraState': FrameReader(...), -} - -output_logs = replay_process_with_name(['modeld', 'dmonitoringmodeld'], lr, frs=frs) -``` - -To capture stdout/stderr of the replayed process, `captured_output_store` can be provided. - -```py -output_store = dict() -# pass dictionary by reference, it will be filled with standard outputs - even if process replay fails -output_logs = replay_process_with_name(['radard', 'plannerd'], lr, captured_output_store=output_store) - -# entries with captured output in format { 'out': '...', 'err': '...' } will be added to provided dictionary for each replayed process -print(output_store['radard']['out']) # radard stdout -print(output_store['radard']['err']) # radard stderr -``` diff --git a/selfdrive/test/process_replay/compare_logs.py b/selfdrive/test/process_replay/compare_logs.py deleted file mode 100755 index 13d51a636f..0000000000 --- a/selfdrive/test/process_replay/compare_logs.py +++ /dev/null @@ -1,150 +0,0 @@ -#!/usr/bin/env python3 -import sys -import math -import capnp -import numbers -import dictdiffer -from collections import Counter - -from openpilot.tools.lib.logreader import LogReader - -EPSILON = sys.float_info.epsilon - - -def remove_ignored_fields(msg, ignore): - msg = msg.as_builder() - for key in ignore: - attr = msg - keys = key.split(".") - if msg.which() != keys[0] and len(keys) > 1: - continue - - for k in keys[:-1]: - # indexing into list - if k.isdigit(): - attr = attr[int(k)] - else: - attr = getattr(attr, k) - - v = getattr(attr, keys[-1]) - if isinstance(v, bool): - val = False - elif isinstance(v, numbers.Number): - val = 0 - elif isinstance(v, (list, capnp.lib.capnp._DynamicListBuilder)): - val = [] - else: - raise NotImplementedError(f"Unknown type: {type(v)}") - setattr(attr, keys[-1], val) - return msg - - -def compare_logs(log1, log2, ignore_fields=None, ignore_msgs=None, tolerance=None,): - if ignore_fields is None: - ignore_fields = [] - if ignore_msgs is None: - ignore_msgs = [] - tolerance = EPSILON if tolerance is None else tolerance - - log1, log2 = ( - [m for m in log if m.which() not in ignore_msgs] - for log in (log1, log2) - ) - - if len(log1) != len(log2): - cnt1 = Counter(m.which() for m in log1) - cnt2 = Counter(m.which() for m in log2) - raise Exception(f"logs are not same length: {len(log1)} VS {len(log2)}\n\t\t{cnt1}\n\t\t{cnt2}") - - diff = [] - for msg1, msg2 in zip(log1, log2, strict=True): - if msg1.which() != msg2.which(): - raise Exception("msgs not aligned between logs") - - msg1 = remove_ignored_fields(msg1, ignore_fields) - msg2 = remove_ignored_fields(msg2, ignore_fields) - - if msg1.to_bytes() != msg2.to_bytes(): - msg1_dict = msg1.as_reader().to_dict(verbose=True) - msg2_dict = msg2.as_reader().to_dict(verbose=True) - - dd = dictdiffer.diff(msg1_dict, msg2_dict, ignore=ignore_fields) - - # Dictdiffer only supports relative tolerance, we also want to check for absolute - # TODO: add this to dictdiffer - def outside_tolerance(diff): - try: - if diff[0] == "change": - a, b = diff[2] - finite = math.isfinite(a) and math.isfinite(b) - if finite and isinstance(a, numbers.Number) and isinstance(b, numbers.Number): - return abs(a - b) > max(tolerance, tolerance * max(abs(a), abs(b))) - except TypeError: - pass - return True - - dd = list(filter(outside_tolerance, dd)) - - diff.extend(dd) - return diff - - -def format_process_diff(diff): - diff_short, diff_long = "", "" - - if isinstance(diff, str): - diff_short += f" {diff}\n" - diff_long += f"\t{diff}\n" - else: - cnt: dict[str, int] = {} - for d in diff: - diff_long += f"\t{str(d)}\n" - - k = str(d[1]) - cnt[k] = 1 if k not in cnt else cnt[k] + 1 - - for k, v in sorted(cnt.items()): - diff_short += f" {k}: {v}\n" - - return diff_short, diff_long - - -def format_diff(results, log_paths, ref_commit): - diff_short, diff_long = "", "" - diff_long += f"***** tested against commit {ref_commit} *****\n" - - failed = False - for segment, result in list(results.items()): - diff_short += f"***** results for segment {segment} *****\n" - diff_long += f"***** differences for segment {segment} *****\n" - - for proc, diff in list(result.items()): - diff_long += f"*** process: {proc} ***\n" - diff_long += f"\tref: {log_paths[segment][proc]['ref']}\n" - diff_long += f"\tnew: {log_paths[segment][proc]['new']}\n\n" - - diff_short += f" {proc}\n" - - if isinstance(diff, str) or len(diff): - diff_short += f" ref: {log_paths[segment][proc]['ref']}\n" - diff_short += f" new: {log_paths[segment][proc]['new']}\n\n" - failed = True - - proc_diff_short, proc_diff_long = format_process_diff(diff) - - diff_long += proc_diff_long - diff_short += proc_diff_short - - return diff_short, diff_long, failed - - -if __name__ == "__main__": - log1 = list(LogReader(sys.argv[1])) - log2 = list(LogReader(sys.argv[2])) - ignore_fields = sys.argv[3:] or ["logMonoTime"] - results = {"segment": {"proc": compare_logs(log1, log2, ignore_fields)}} - log_paths = {"segment": {"proc": {"ref": sys.argv[1], "new": sys.argv[2]}}} - diff_short, diff_long, failed = format_diff(results, log_paths, None) - - print(diff_long) - print(diff_short) diff --git a/selfdrive/test/process_replay/migration.py b/selfdrive/test/process_replay/migration.py deleted file mode 100644 index 33b363cfd9..0000000000 --- a/selfdrive/test/process_replay/migration.py +++ /dev/null @@ -1,472 +0,0 @@ -from collections import defaultdict -from collections.abc import Callable -import capnp -import functools -import traceback - -from cereal import messaging, car, log -from opendbc.car.fingerprints import MIGRATION -from opendbc.car.toyota.values import EPS_SCALE, ToyotaSafetyFlags -from opendbc.car.ford.values import CAR as FORD, FordFlags, FordSafetyFlags -from opendbc.car.hyundai.values import HyundaiSafetyFlags -from opendbc.car.gm.values import GMSafetyFlags -from openpilot.selfdrive.modeld.constants import ModelConstants -from openpilot.selfdrive.modeld.fill_model_msg import fill_xyz_poly, fill_lane_line_meta -from openpilot.selfdrive.test.process_replay.vision_meta import meta_from_encode_index -from openpilot.selfdrive.controls.lib.longitudinal_planner import get_accel_from_plan, CONTROL_N_T_IDX -from openpilot.system.manager.process_config import managed_processes -from openpilot.tools.lib.logreader import LogIterable - -MessageWithIndex = tuple[int, capnp.lib.capnp._DynamicStructReader] -MigrationOps = tuple[list[tuple[int, capnp.lib.capnp._DynamicStructReader]], list[capnp.lib.capnp._DynamicStructReader], list[int]] -MigrationFunc = Callable[[list[MessageWithIndex]], MigrationOps] - - -# rules for migration functions -# 1. must use the decorator @migration(inputs=[...], product="...") and MigrationFunc signature -# 2. it only gets the messages that are in the inputs list -# 3. product is the message type created by the migration function, and the function will be skipped if product type already exists in lr -# 4. it must return a list of operations to be applied to the logreader (replace, add, delete) -# 5. all migration functions must be independent of each other -def migrate_all(lr: LogIterable, manager_states: bool = False, panda_states: bool = False, camera_states: bool = False): - migrations = [ - migrate_sensorEvents, - migrate_carParams, - migrate_gpsLocation, - migrate_deviceState, - migrate_carOutput, - migrate_controlsState, - migrate_carState, - migrate_liveLocationKalman, - migrate_liveTracks, - migrate_driverAssistance, - migrate_drivingModelData, - migrate_onroadEvents, - migrate_driverMonitoringState, - migrate_longitudinalPlan, - ] - if manager_states: - migrations.append(migrate_managerState) - if panda_states: - migrations.extend([migrate_pandaStates, migrate_peripheralState]) - if camera_states: - migrations.append(migrate_cameraStates) - - return migrate(lr, migrations) - - -def migrate(lr: LogIterable, migration_funcs: list[MigrationFunc]): - lr = list(lr) - grouped = defaultdict(list) - for i, msg in enumerate(lr): - grouped[msg.which()].append(i) - - replace_ops, add_ops, del_ops = [], [], [] - for migration in migration_funcs: - assert hasattr(migration, "inputs") and hasattr(migration, "product"), "Migration functions must use @migration decorator" - if migration.product in grouped: # skip if product already exists - continue - - sorted_indices = sorted(ii for i in migration.inputs for ii in grouped[i]) - msg_gen = [(i, lr[i]) for i in sorted_indices] - r_ops, a_ops, d_ops = migration(msg_gen) - replace_ops.extend(r_ops) - add_ops.extend(a_ops) - del_ops.extend(d_ops) - - for index, msg in replace_ops: - lr[index] = msg - for index in sorted(del_ops, reverse=True): - del lr[index] - for msg in add_ops: - lr.append(msg) - lr = sorted(lr, key=lambda x: x.logMonoTime) - - return lr - - -def migration(inputs: list[str], product: str|None=None): - def decorator(func): - @functools.wraps(func) - def wrapper(*args, **kwargs): - return func(*args, **kwargs) - wrapper.inputs = inputs - wrapper.product = product - return wrapper - return decorator - - -@migration(inputs=["longitudinalPlan", "carParams"]) -def migrate_longitudinalPlan(msgs): - ops = [] - - needs_migration = all(msg.longitudinalPlan.aTarget == 0.0 for _, msg in msgs if msg.which() == 'longitudinalPlan') - CP = next((m.carParams for _, m in msgs if m.which() == 'carParams'), None) - if not needs_migration or CP is None: - return [], [], [] - - for index, msg in msgs: - if msg.which() != 'longitudinalPlan': - continue - new_msg = msg.as_builder() - a_target, should_stop = get_accel_from_plan(msg.longitudinalPlan.speeds, msg.longitudinalPlan.accels, CONTROL_N_T_IDX) - new_msg.longitudinalPlan.aTarget, new_msg.longitudinalPlan.shouldStop = float(a_target), bool(should_stop) - ops.append((index, new_msg.as_reader())) - return ops, [], [] - - -@migration(inputs=["longitudinalPlan"], product="driverAssistance") -def migrate_driverAssistance(msgs): - add_ops = [] - for _, msg in msgs: - new_msg = messaging.new_message('driverAssistance', valid=True, logMonoTime=msg.logMonoTime) - add_ops.append(new_msg.as_reader()) - return [], add_ops, [] - - -@migration(inputs=["modelV2"], product="drivingModelData") -def migrate_drivingModelData(msgs): - add_ops = [] - for _, msg in msgs: - dmd = messaging.new_message('drivingModelData', valid=msg.valid, logMonoTime=msg.logMonoTime) - for field in ["frameId", "frameIdExtra", "frameDropPerc", "modelExecutionTime", "action"]: - setattr(dmd.drivingModelData, field, getattr(msg.modelV2, field)) - for meta_field in ["laneChangeState", "laneChangeState"]: - setattr(dmd.drivingModelData.meta, meta_field, getattr(msg.modelV2.meta, meta_field)) - if len(msg.modelV2.laneLines) and len(msg.modelV2.laneLineProbs): - fill_lane_line_meta(dmd.drivingModelData.laneLineMeta, msg.modelV2.laneLines, msg.modelV2.laneLineProbs) - if all(len(a) for a in [msg.modelV2.position.x, msg.modelV2.position.y, msg.modelV2.position.z]): - fill_xyz_poly(dmd.drivingModelData.path, ModelConstants.POLY_PATH_DEGREE, msg.modelV2.position.x, msg.modelV2.position.y, msg.modelV2.position.z) - add_ops.append( dmd.as_reader()) - return [], add_ops, [] - - -@migration(inputs=["liveTracksDEPRECATED"], product="liveTracks") -def migrate_liveTracks(msgs): - ops = [] - for index, msg in msgs: - new_msg = messaging.new_message('liveTracks') - new_msg.valid = msg.valid - new_msg.logMonoTime = msg.logMonoTime - - pts = [] - for track in msg.liveTracksDEPRECATED: - pt = car.RadarData.RadarPoint() - pt.trackId = track.trackId - - pt.dRel = track.dRel - pt.yRel = track.yRel - pt.vRel = track.vRel - pt.aRel = track.aRel - pt.measured = True - pts.append(pt) - - new_msg.liveTracks.points = pts - ops.append((index, new_msg.as_reader())) - return ops, [], [] - - -@migration(inputs=["liveLocationKalmanDEPRECATED"], product="livePose") -def migrate_liveLocationKalman(msgs): - nans = [float('nan')] * 3 - ops = [] - for index, msg in msgs: - m = messaging.new_message('livePose') - m.valid = msg.valid - m.logMonoTime = msg.logMonoTime - for field in ["orientationNED", "velocityDevice", "accelerationDevice", "angularVelocityDevice"]: - lp_field, llk_field = getattr(m.livePose, field), getattr(msg.liveLocationKalmanDEPRECATED, field) - lp_field.x, lp_field.y, lp_field.z = llk_field.value or nans - lp_field.xStd, lp_field.yStd, lp_field.zStd = llk_field.std or nans - lp_field.valid = llk_field.valid - for flag in ["inputsOK", "posenetOK", "sensorsOK"]: - setattr(m.livePose, flag, getattr(msg.liveLocationKalmanDEPRECATED, flag)) - ops.append((index, m.as_reader())) - return ops, [], [] - - -@migration(inputs=["controlsState"], product="selfdriveState") -def migrate_controlsState(msgs): - add_ops = [] - for _, msg in msgs: - m = messaging.new_message('selfdriveState') - m.valid = msg.valid - m.logMonoTime = msg.logMonoTime - ss = m.selfdriveState - for field in ("enabled", "active", "state", "engageable", "alertText1", "alertText2", - "alertStatus", "alertSize", "alertType", "experimentalMode", - "personality"): - setattr(ss, field, getattr(msg.controlsState, field+"DEPRECATED")) - add_ops.append(m.as_reader()) - return [], add_ops, [] - - -@migration(inputs=["carState", "controlsState"]) -def migrate_carState(msgs): - ops = [] - last_cs = None - for index, msg in msgs: - if msg.which() == 'controlsState': - last_cs = msg - elif msg.which() == 'carState' and last_cs is not None: - if last_cs.controlsState.vCruiseDEPRECATED - msg.carState.vCruise > 0.1: - msg = msg.as_builder() - msg.carState.vCruise = last_cs.controlsState.vCruiseDEPRECATED - msg.carState.vCruiseCluster = last_cs.controlsState.vCruiseClusterDEPRECATED - ops.append((index, msg.as_reader())) - return ops, [], [] - - -@migration(inputs=["managerState"]) -def migrate_managerState(msgs): - ops = [] - for index, msg in msgs: - new_msg = msg.as_builder() - new_msg.managerState.processes = [{'name': name, 'running': True} for name in managed_processes] - ops.append((index, new_msg.as_reader())) - return ops, [], [] - - -@migration(inputs=["gpsLocation", "gpsLocationExternal"]) -def migrate_gpsLocation(msgs): - ops = [] - for index, msg in msgs: - new_msg = msg.as_builder() - g = getattr(new_msg, new_msg.which()) - # hasFix is a newer field - if not g.hasFix and g.flags == 1: - g.hasFix = True - ops.append((index, new_msg.as_reader())) - return ops, [], [] - - -@migration(inputs=["deviceState", "initData"]) -def migrate_deviceState(msgs): - init_data = next((m.initData for _, m in msgs if m.which() == 'initData'), None) - device_state = next((m.deviceState for _, m in msgs if m.which() == 'deviceState'), None) - if init_data is None or device_state is None: - return [], [], [] - - ops = [] - for i, msg in msgs: - if msg.which() == 'deviceState': - n = msg.as_builder() - n.deviceState.deviceType = init_data.deviceType - ops.append((i, n.as_reader())) - return ops, [], [] - - -@migration(inputs=["carControl"], product="carOutput") -def migrate_carOutput(msgs): - add_ops = [] - for _, msg in msgs: - co = messaging.new_message('carOutput') - co.valid = msg.valid - co.logMonoTime = msg.logMonoTime - co.carOutput.actuatorsOutput = msg.carControl.actuatorsOutputDEPRECATED - add_ops.append(co.as_reader()) - return [], add_ops, [] - - -@migration(inputs=["pandaStates", "pandaStateDEPRECATED", "carParams"]) -def migrate_pandaStates(msgs): - # TODO: safety param migration should be handled automatically - safety_param_migration = { - "TOYOTA_PRIUS": EPS_SCALE["TOYOTA_PRIUS"] | ToyotaSafetyFlags.STOCK_LONGITUDINAL, - "TOYOTA_RAV4": EPS_SCALE["TOYOTA_RAV4"] | ToyotaSafetyFlags.ALT_BRAKE, - "KIA_EV6": HyundaiSafetyFlags.EV_GAS | HyundaiSafetyFlags.CANFD_LKA_STEERING, - "CHEVROLET_VOLT": GMSafetyFlags.EV, - "CHEVROLET_BOLT_EUV": GMSafetyFlags.EV | GMSafetyFlags.HW_CAM, - } - # TODO: get new Ford route - safety_param_migration |= dict.fromkeys((set(FORD) - FORD.with_flags(FordFlags.CANFD)), FordSafetyFlags.LONG_CONTROL) - - # Migrate safety param base on carParams - CP = next((m.carParams for _, m in msgs if m.which() == 'carParams'), None) - assert CP is not None, "carParams message not found" - fingerprint = MIGRATION.get(CP.carFingerprint, CP.carFingerprint) - if fingerprint in safety_param_migration: - safety_param = safety_param_migration[fingerprint].value - elif len(CP.safetyConfigs): - safety_param = CP.safetyConfigs[0].safetyParam - if CP.safetyConfigs[0].safetyParamDEPRECATED != 0: - safety_param = CP.safetyConfigs[0].safetyParamDEPRECATED - else: - safety_param = CP.safetyParamDEPRECATED - - ops = [] - for index, msg in msgs: - if msg.which() == 'pandaStateDEPRECATED': - new_msg = messaging.new_message('pandaStates', 1) - new_msg.valid = msg.valid - new_msg.logMonoTime = msg.logMonoTime - new_msg.pandaStates[0] = msg.pandaStateDEPRECATED - new_msg.pandaStates[0].safetyParam = safety_param - ops.append((index, new_msg.as_reader())) - elif msg.which() == 'pandaStates': - new_msg = msg.as_builder() - new_msg.pandaStates[-1].safetyParam = safety_param - # Clear DISABLE_DISENGAGE_ON_GAS bit to fix controls mismatch - new_msg.pandaStates[-1].alternativeExperience &= ~1 - ops.append((index, new_msg.as_reader())) - return ops, [], [] - - -@migration(inputs=["pandaStates", "pandaStateDEPRECATED"], product="peripheralState") -def migrate_peripheralState(msgs): - add_ops = [] - - which = "pandaStates" if any(msg.which() == "pandaStates" for _, msg in msgs) else "pandaStateDEPRECATED" - for _, msg in msgs: - if msg.which() != which: - continue - new_msg = messaging.new_message("peripheralState") - new_msg.valid = msg.valid - new_msg.logMonoTime = msg.logMonoTime - add_ops.append(new_msg.as_reader()) - return [], add_ops, [] - - -@migration(inputs=["roadEncodeIdx", "wideRoadEncodeIdx", "driverEncodeIdx", "roadCameraState", "wideRoadCameraState", "driverCameraState"]) -def migrate_cameraStates(msgs): - add_ops, del_ops = [], [] - frame_to_encode_id = defaultdict(dict) - # just for encodeId fallback mechanism - min_frame_id = defaultdict(lambda: float('inf')) - - for _, msg in msgs: - if msg.which() not in ["roadEncodeIdx", "wideRoadEncodeIdx", "driverEncodeIdx"]: - continue - - encode_index = getattr(msg, msg.which()) - meta = meta_from_encode_index(msg.which()) - - assert encode_index.segmentId < 1200, f"Encoder index segmentId greater that 1200: {msg.which()} {encode_index.segmentId}" - frame_to_encode_id[meta.camera_state][encode_index.frameId] = encode_index.segmentId - - for index, msg in msgs: - if msg.which() not in ["roadCameraState", "wideRoadCameraState", "driverCameraState"]: - continue - - camera_state = getattr(msg, msg.which()) - min_frame_id[msg.which()] = min(min_frame_id[msg.which()], camera_state.frameId) - - encode_id = frame_to_encode_id[msg.which()].get(camera_state.frameId) - if encode_id is None: - print(f"Missing encoded frame for camera feed {msg.which()} with frameId: {camera_state.frameId}") - if len(frame_to_encode_id[msg.which()]) != 0: - del_ops.append(index) - continue - - # fallback mechanism for logs without encodeIdx (e.g. logs from before 2022 with dcamera recording disabled) - # try to fake encode_id by subtracting lowest frameId - encode_id = camera_state.frameId - min_frame_id[msg.which()] - print(f"Faking encodeId to {encode_id} for camera feed {msg.which()} with frameId: {camera_state.frameId}") - - new_msg = messaging.new_message(msg.which()) - new_camera_state = getattr(new_msg, new_msg.which()) - new_camera_state.sensor = camera_state.sensor - new_camera_state.frameId = encode_id - new_camera_state.encodeId = encode_id - # timestampSof was added later so it might be missing on some old segments - if camera_state.timestampSof == 0 and camera_state.timestampEof > 25000000: - new_camera_state.timestampSof = camera_state.timestampEof - 18000000 - else: - new_camera_state.timestampSof = camera_state.timestampSof - new_camera_state.timestampEof = camera_state.timestampEof - new_msg.logMonoTime = msg.logMonoTime - new_msg.valid = msg.valid - - del_ops.append(index) - add_ops.append(new_msg.as_reader()) - return [], add_ops, del_ops - - -@migration(inputs=["carParams"]) -def migrate_carParams(msgs): - ops = [] - for index, msg in msgs: - CP = msg.as_builder() - CP.carParams.carFingerprint = MIGRATION.get(CP.carParams.carFingerprint, CP.carParams.carFingerprint) - for car_fw in CP.carParams.carFw: - car_fw.brand = CP.carParams.brand - ops.append((index, CP.as_reader())) - return ops, [], [] - - -@migration(inputs=["sensorEventsDEPRECATED"], product="sensorEvents") -def migrate_sensorEvents(msgs): - add_ops, del_ops = [], [] - for index, msg in msgs: - # migrate to split sensor events - for evt in msg.sensorEventsDEPRECATED: - # build new message for each sensor type - sensor_service = '' - if evt.which() == 'acceleration': - sensor_service = 'accelerometer' - elif evt.which() == 'gyro' or evt.which() == 'gyroUncalibrated': - sensor_service = 'gyroscope' - elif evt.which() == 'light' or evt.which() == 'proximity': - sensor_service = 'lightSensor' - elif evt.which() == 'magnetic' or evt.which() == 'magneticUncalibrated': - sensor_service = 'magnetometer' - elif evt.which() == 'temperature': - sensor_service = 'temperatureSensor' - - m = messaging.new_message(sensor_service) - m.valid = True - m.logMonoTime = msg.logMonoTime - - m_dat = getattr(m, sensor_service) - m_dat.version = evt.version - m_dat.sensor = evt.sensor - m_dat.type = evt.type - m_dat.source = evt.source - m_dat.timestamp = evt.timestamp - setattr(m_dat, evt.which(), getattr(evt, evt.which())) - - add_ops.append(m.as_reader()) - del_ops.append(index) - return [], add_ops, del_ops - - -@migration(inputs=["onroadEventsDEPRECATED"], product="onroadEvents") -def migrate_onroadEvents(msgs): - ops = [] - for index, msg in msgs: - onroadEvents = [] - for event in msg.onroadEventsDEPRECATED: - try: - if not str(event.name).endswith('DEPRECATED'): - # dict converts name enum into string representation - onroadEvents.append(log.OnroadEvent(**event.to_dict())) - except RuntimeError: # Member was null - traceback.print_exc() - - new_msg = messaging.new_message('onroadEvents', len(msg.onroadEventsDEPRECATED)) - new_msg.valid = msg.valid - new_msg.logMonoTime = msg.logMonoTime - new_msg.onroadEvents = onroadEvents - ops.append((index, new_msg.as_reader())) - - return ops, [], [] - - -@migration(inputs=["driverMonitoringState"]) -def migrate_driverMonitoringState(msgs): - ops = [] - for index, msg in msgs: - msg = msg.as_builder() - events = [] - for event in msg.driverMonitoringState.eventsDEPRECATED: - try: - if not str(event.name).endswith('DEPRECATED'): - # dict converts name enum into string representation - events.append(log.OnroadEvent(**event.to_dict())) - except RuntimeError: # Member was null - traceback.print_exc() - - msg.driverMonitoringState.events = events - ops.append((index, msg.as_reader())) - - return ops, [], [] diff --git a/selfdrive/test/process_replay/ref_commit b/selfdrive/test/process_replay/ref_commit deleted file mode 100644 index f839238098..0000000000 --- a/selfdrive/test/process_replay/ref_commit +++ /dev/null @@ -1 +0,0 @@ -f440c9e0469d32d350aa99ddaa8f44591a2ce690 \ No newline at end of file diff --git a/selfdrive/test/process_replay/test_processes.py b/selfdrive/test/process_replay/test_processes.py deleted file mode 100755 index 39c1e408eb..0000000000 --- a/selfdrive/test/process_replay/test_processes.py +++ /dev/null @@ -1,298 +0,0 @@ -#!/usr/bin/env python3 -import argparse -import concurrent.futures -import os -import sys -from collections import defaultdict -from tqdm import tqdm -from typing import Any - -from opendbc.car.car_helpers import interface_names -from openpilot.common.git import get_commit -from openpilot.tools.lib.openpilotci import get_url, upload_file -from openpilot.selfdrive.test.process_replay.compare_logs import compare_logs, format_diff -from openpilot.selfdrive.test.process_replay.process_replay import CONFIGS, PROC_REPLAY_DIR, FAKEDATA, replay_process, \ - check_most_messages_valid -from openpilot.tools.lib.filereader import FileReader -from openpilot.tools.lib.logreader import LogReader, save_log - -IS_AZURE_TOKEN_DEFINED = os.getenv("AZURE_TOKEN") - -source_segments = [ - ("HYUNDAI", "02c45f73a2e5c6e9|2021-01-01--19-08-22--1"), # HYUNDAI.HYUNDAI_SONATA - ("HYUNDAI2", "d545129f3ca90f28|2022-11-07--20-43-08--3"), # HYUNDAI.HYUNDAI_KIA_EV6 (+ QCOM GPS) - ("TOYOTA", "0982d79ebb0de295|2021-01-04--17-13-21--13"), # TOYOTA.TOYOTA_PRIUS - ("TOYOTA2", "0982d79ebb0de295|2021-01-03--20-03-36--6"), # TOYOTA.TOYOTA_RAV4 - ("TOYOTA3", "8011d605be1cbb77|000000cc--8e8d8ec716--6"), # TOYOTA.TOYOTA_COROLLA_TSS2 - ("HONDA", "eb140f119469d9ab|2021-06-12--10-46-24--27"), # HONDA.HONDA_CIVIC (NIDEC) - ("HONDA2", "7d2244f34d1bbcda|2021-06-25--12-25-37--26"), # HONDA.HONDA_ACCORD (BOSCH) - ("CHRYSLER", "4deb27de11bee626|2021-02-20--11-28-55--8"), # CHRYSLER.CHRYSLER_PACIFICA_2018_HYBRID - ("RAM", "17fc16d840fe9d21|2023-04-26--13-28-44--5"), # CHRYSLER.RAM_1500_5TH_GEN - ("SUBARU", "341dccd5359e3c97|2022-09-12--10-35-33--3"), # SUBARU.SUBARU_OUTBACK - ("GM", "376bf99325883932|2022-10-27--13-41-22--1"), # GM.CHEVROLET_BOLT_EUV - ("NISSAN", "35336926920f3571|2021-02-12--18-38-48--46"), # NISSAN.NISSAN_XTRAIL - ("VOLKSWAGEN", "de9592456ad7d144|2021-06-29--11-00-15--6"), # VOLKSWAGEN.VOLKSWAGEN_GOLF - # FIXME the sensor timings are bad in mazda segment, we're not fully testing it, but it should be replaced - ("MAZDA", "bd6a637565e91581|2021-10-30--15-14-53--4"), # MAZDA.MAZDA_CX9_2021 - ("FORD", "54827bf84c38b14f|2023-01-26--21-59-07--4"), # FORD.FORD_BRONCO_SPORT_MK1 - ("RIVIAN", "bc095dc92e101734|000000db--ee9fe46e57--1"), # RIVIAN.RIVIAN_R1_GEN1 - ("TESLA", "2c912ca5de3b1ee9|0000025d--6eb6bcbca4--4"), # TESLA.TESLA_MODEL_Y - - # Enable when port is tested and dashcamOnly is no longer set - #("VOLKSWAGEN2", "3cfdec54aa035f3f|2022-07-19--23-45-10--2"), # VOLKSWAGEN.VOLKSWAGEN_PASSAT_NMS -] - -segments = [ - ("HYUNDAI", "regenAA0FC4ED71E|2025-04-08--22-57-50--0"), - ("HYUNDAI2", "regenAFB9780D823|2025-04-08--23-00-34--0"), - ("TOYOTA", "regen218A4DCFAA1|2025-04-08--22-57-51--0"), - ("TOYOTA2", "regen107352E20EB|2025-04-08--22-57-46--0"), - ("TOYOTA3", "regen1455E3B4BDF|2025-04-09--03-26-06--0"), - ("HONDA", "regenB328FF8BA0A|2025-04-08--22-57-45--0"), - ("HONDA2", "regen6170C8C9A35|2025-04-08--22-57-46--0"), - ("CHRYSLER", "regen5B28FC2A437|2025-04-08--23-04-24--0"), - ("RAM", "regenBF81EA96E08|2025-04-08--23-06-54--0"), - ("SUBARU", "regen7366F13F6A1|2025-04-08--23-07-07--0"), - ("GM", "regen1271097D038|2025-04-09--03-26-00--0"), - ("NISSAN", "regen15D60604EAB|2025-04-08--23-06-59--0"), - ("VOLKSWAGEN", "regen0F2F06C9539|2025-04-08--23-06-56--0"), - ("MAZDA", "regenACF84CCF482|2024-08-30--03-21-55--0"), - ("FORD", "regen755D8CB1E1F|2025-04-08--23-13-43--0"), - ("RIVIAN", "regen5FCAC896BBE|2025-04-08--23-13-35--0"), - ("TESLA", "2c912ca5de3b1ee9|0000025d--6eb6bcbca4--4"), -] - -# dashcamOnly makes don't need to be tested until a full port is done -excluded_interfaces = ["mock", "body"] - -BASE_URL = "https://commadataci.blob.core.windows.net/openpilotci/" -REF_COMMIT_FN = os.path.join(PROC_REPLAY_DIR, "ref_commit") -EXCLUDED_PROCS = {"modeld", "dmonitoringmodeld"} - - -def preserve_only_specified_files_from_ref_commit(*commits_to_keep): - """Keep only files in fakedata that contain any of the specified commit hashes.""" - removed = 0 - for f in os.listdir(FAKEDATA): - if not any(commit in f for commit in commits_to_keep): - os.remove(os.path.join(FAKEDATA, f)) - removed += 1 - if removed > 0: - print(f"Removed {removed} old files from {FAKEDATA}") - - -def handle_output_file(cur_log_fn, local): - """Handle the output file based on whether we're using remote or local storage.""" - assert os.path.exists(cur_log_fn), f"Cannot find log to upload: {cur_log_fn}" - - if local: - os.system(f"git add '{os.path.realpath(cur_log_fn)}'") - else: - upload_file(cur_log_fn, os.path.basename(cur_log_fn)) - os.remove(cur_log_fn) - - -def run_test_process(data): - segment, cfg, args, cur_log_fn, ref_log_path, lr_dat = data - res = None - if not args.upload_only: - lr = LogReader.from_bytes(lr_dat) - res, log_msgs = test_process(cfg, lr, segment, ref_log_path, cur_log_fn, args.ignore_fields, args.ignore_msgs) - # save logs so we can upload when updating refs - save_log(cur_log_fn, log_msgs) - - if args.update_refs or args.upload_only: - print(f'Processing: {os.path.basename(cur_log_fn)}') - handle_output_file(cur_log_fn, args.local) - - return (segment, cfg.proc_name, res) - - -def get_log_data(segment): - r, n = segment.rsplit("--", 1) - with FileReader(get_url(r, n, "rlog.zst")) as f: - return (segment, f.read()) - - -def test_process(cfg, lr, segment, ref_log_path, new_log_path, ignore_fields=None, ignore_msgs=None): - if ignore_fields is None: - ignore_fields = [] - if ignore_msgs is None: - ignore_msgs = [] - - ref_log_msgs = list(LogReader(ref_log_path)) - - try: - log_msgs = replay_process(cfg, lr, disable_progress=True) - except Exception as e: - raise Exception("failed on segment: " + segment) from e - - if not check_most_messages_valid(log_msgs): - return f"Route did not have enough valid messages: {new_log_path}", log_msgs - - # skip this check if the segment is using qcom gps - if cfg.proc_name != 'ubloxd' or any(m.which() in cfg.pubs for m in lr): - seen_msgs = {m.which() for m in log_msgs} - expected_msgs = set(cfg.subs) - if seen_msgs != expected_msgs: - return f"Expected messages: {expected_msgs}, but got: {seen_msgs}", log_msgs - - try: - return compare_logs(ref_log_msgs, log_msgs, ignore_fields + cfg.ignore, ignore_msgs, cfg.tolerance), log_msgs - except Exception as e: - return str(e), log_msgs - - -def finalize_git_updates(cur_commit, ref_commit_fn): - """Finalize git updates and create commit.""" - try: - # Add all new files first - os.system(f"git add {os.path.realpath(ref_commit_fn)}") - os.system(f"git add {os.path.realpath(FAKEDATA)}/*.zst") - - # Clean up old files - keep only new ref files since they're becoming the reference - preserve_only_specified_files_from_ref_commit(cur_commit) - - # Add the deletions to git - os.system(f"git add -u {os.path.realpath(FAKEDATA)}") - - # Create the commit - commit_msg = f"test_processes: update ref logs to {cur_commit[:7]}" - os.system(f'git commit -m "{commit_msg}"') - print("Successfully committed reference log updates") - except Exception as e: - print(f"Failed to commit changes: {e}") - - -if __name__ == "__main__": - all_cars = {car for car, _ in segments} - all_procs = {cfg.proc_name for cfg in CONFIGS if cfg.proc_name not in EXCLUDED_PROCS} - - cpu_count = os.cpu_count() or 1 - - parser = argparse.ArgumentParser(description="Regression test to identify changes in a process's output") - parser.add_argument("--whitelist-procs", type=str, nargs="*", default=all_procs, - help="Whitelist given processes from the test (e.g. controlsd)") - parser.add_argument("--whitelist-cars", type=str, nargs="*", default=all_cars, - help="Whitelist given cars from the test (e.g. HONDA)") - parser.add_argument("--blacklist-procs", type=str, nargs="*", default=[], - help="Blacklist given processes from the test (e.g. controlsd)") - parser.add_argument("--blacklist-cars", type=str, nargs="*", default=[], - help="Blacklist given cars from the test (e.g. HONDA)") - parser.add_argument("--ignore-fields", type=str, nargs="*", default=[], - help="Extra fields or msgs to ignore (e.g. driverMonitoringState.events)") - parser.add_argument("--ignore-msgs", type=str, nargs="*", default=[], - help="Msgs to ignore (e.g. carEvents)") - parser.add_argument("--update-refs", action="store_true", - help="Updates reference logs using current commit") - parser.add_argument("--upload-only", action="store_true", - help="Skips testing processes and uploads logs from previous test run") - parser.add_argument("--local", action="store_true", - help="Use local git/ storage instead of remote (Azure for Comma)") - parser.add_argument("-j", "--jobs", type=int, default=max(cpu_count - 2, 1), - help="Max amount of parallel jobs") - args = parser.parse_args() - - tested_procs = set(args.whitelist_procs) - set(args.blacklist_procs) - tested_cars = set(args.whitelist_cars) - set(args.blacklist_cars) - tested_cars = {c.upper() for c in tested_cars} - - full_test = (tested_procs == all_procs) and (tested_cars == all_cars) and all(len(x) == 0 for x in (args.ignore_fields, args.ignore_msgs)) - upload = args.update_refs or args.upload_only - os.makedirs(os.path.dirname(FAKEDATA), exist_ok=True) - - if upload: - assert full_test, "Need to run full test when updating refs" - - try: - with open(REF_COMMIT_FN) as f: - ref_commit = f.read().strip() - except FileNotFoundError: - print("Couldn't find reference commit") - sys.exit(1) - - cur_commit = get_commit() - if not cur_commit: - raise Exception("Couldn't get current commit") - - # Could be set as default in args, but wanted to be more explicit on the flow. - if upload and not args.local and not IS_AZURE_TOKEN_DEFINED: - print("***** Warning: local/git run was used by default since AZURE_TOKEN was NOT found on the env variables! *****") - args.local = True - - # Clean up old files before starting - if upload and args.local: - print("***** Cleaning up old fakedata for local/git tracked refs *****") - preserve_only_specified_files_from_ref_commit(cur_commit, ref_commit) - - print(f"***** testing against commit {ref_commit} *****") - - # check to make sure all car brands are tested - if full_test: - untested = (set(interface_names) - set(excluded_interfaces)) - {c.lower() for c in tested_cars} - assert len(untested) == 0, f"Cars missing routes: {str(untested)}" - - log_paths: defaultdict[str, dict[str, dict[str, str]]] = defaultdict(lambda: defaultdict(dict)) - with concurrent.futures.ProcessPoolExecutor(max_workers=args.jobs) as pool: - if not args.upload_only: - download_segments = [seg for car, seg in segments if car in tested_cars] - log_data: dict[str, LogReader] = {} - p1 = pool.map(get_log_data, download_segments) - for segment, lr in tqdm(p1, desc="Getting Logs", total=len(download_segments)): - log_data[segment] = lr - - pool_args: Any = [] - for car_brand, segment in segments: - if car_brand not in tested_cars: - continue - - for cfg in CONFIGS: - if cfg.proc_name not in tested_procs: - continue - - # to speed things up, we only test all segments on card - if cfg.proc_name not in ('card', 'controlsd', 'lagd') and car_brand not in ('HYUNDAI', 'TOYOTA'): - continue - - cur_log_fn = os.path.join(FAKEDATA, f"{segment}_{cfg.proc_name}_{cur_commit}.zst") - if args.update_refs: # reference logs will not exist if routes were just regenerated - ref_log_path = get_url(*segment.rsplit("--", 1,), "rlog.zst") - else: - ref_log_fn = os.path.join(FAKEDATA, f"{segment}_{cfg.proc_name}_{ref_commit}.zst") - ref_log_path = ref_log_fn if os.path.exists(ref_log_fn) else BASE_URL + os.path.basename(ref_log_fn) - - dat = None if args.upload_only else log_data[segment] - pool_args.append((segment, cfg, args, cur_log_fn, ref_log_path, dat)) - - log_paths[segment][cfg.proc_name]['ref'] = ref_log_path - log_paths[segment][cfg.proc_name]['new'] = cur_log_fn - - results: Any = defaultdict(dict) - p2 = pool.map(run_test_process, pool_args) - for (segment, proc, result) in tqdm(p2, desc="Running Tests", total=len(pool_args)): - if not args.upload_only: - results[segment][proc] = result - - diff_short, diff_long, failed = format_diff(results, log_paths, ref_commit) - if not upload: - with open(os.path.join(PROC_REPLAY_DIR, "diff.txt"), "w") as f: - f.write(diff_long) - print(diff_short) - - if failed: - print("TEST FAILED") - print("\n\nTo push the new reference logs for this commit run:") - print("./test_processes.py --upload-only") - else: - print("TEST SUCCEEDED") - - else: - with open(REF_COMMIT_FN, "w") as f: - f.write(cur_commit) - print(f"\n\nUpdated reference logs for commit: {cur_commit}") - - # Only do git operations if we're in local mode - if upload and args.local: - finalize_git_updates(cur_commit, REF_COMMIT_FN) - - sys.exit(int(failed)) diff --git a/selfdrive/test/setup_device_ci.sh b/selfdrive/test/setup_device_ci.sh deleted file mode 100755 index d717698514..0000000000 --- a/selfdrive/test/setup_device_ci.sh +++ /dev/null @@ -1,133 +0,0 @@ -#!/usr/bin/env bash - -set -e -set -x - -if [ -z "$SOURCE_DIR" ]; then - echo "SOURCE_DIR must be set" - exit 1 -fi - -if [ -z "$GIT_COMMIT" ]; then - echo "GIT_COMMIT must be set" - exit 1 -fi - -if [ -z "$TEST_DIR" ]; then - echo "TEST_DIR must be set" - exit 1 -fi - -# prevent storage from filling up -rm -rf /data/media/0/realdata/* - -rm -rf /data/safe_staging/ || true -if [ -d /data/safe_staging/ ]; then - sudo umount /data/safe_staging/merged/ || true - rm -rf /data/safe_staging/ || true -fi - -CONTINUE_PATH="/data/continue.sh" -tee $CONTINUE_PATH << EOF -#!/usr/bin/env bash - -sudo abctl --set_success - -# patch sshd config -sudo mount -o rw,remount / -sudo sed -i "s,/data/params/d/GithubSshKeys,/usr/comma/setup_keys," /etc/ssh/sshd_config -sudo systemctl daemon-reload -sudo systemctl restart ssh -sudo systemctl restart NetworkManager -sudo systemctl disable ssh-param-watcher.path -sudo systemctl disable ssh-param-watcher.service -sudo mount -o ro,remount / - -while true; do - if ! sudo systemctl is-active -q ssh; then - sudo systemctl start ssh - fi - - #if ! pgrep -f 'ciui.py' > /dev/null 2>&1; then - # echo 'starting UI' - # cp $SOURCE_DIR/selfdrive/test/ciui.py /data/ - # /data/ciui.py & - #fi - - sleep 5s -done - -sleep infinity -EOF -chmod +x $CONTINUE_PATH - -safe_checkout() { - # completely clean TEST_DIR - - cd $SOURCE_DIR - - # cleanup orphaned locks - find .git -type f -name "*.lock" -exec rm {} + - - git reset --hard - git fetch --no-tags --no-recurse-submodules -j4 --verbose --depth 1 origin $GIT_COMMIT - find . -maxdepth 1 -not -path './.git' -not -name '.' -not -name '..' -exec rm -rf '{}' \; - git reset --hard $GIT_COMMIT - git checkout $GIT_COMMIT - git clean -xdff - git submodule sync - git submodule foreach --recursive "git reset --hard && git clean -xdff" - git submodule update --init --recursive - git submodule foreach --recursive "git reset --hard && git clean -xdff" - - git lfs pull - (ulimit -n 65535 && git lfs prune) - - echo "git checkout done, t=$SECONDS" - du -hs $SOURCE_DIR $SOURCE_DIR/.git - - rsync -a --delete $SOURCE_DIR $TEST_DIR -} - -unsafe_checkout() {( set -e - # checkout directly in test dir, leave old build products - - cd $TEST_DIR - - # cleanup orphaned locks - find .git -type f -name "*.lock" -exec rm {} + - - git fetch --no-tags --no-recurse-submodules -j8 --verbose --depth 1 origin $GIT_COMMIT - git checkout --force --no-recurse-submodules $GIT_COMMIT - git reset --hard $GIT_COMMIT - git clean -dff - git submodule sync - git submodule foreach --recursive "git reset --hard && git clean -df" - git submodule update --init --recursive - git submodule foreach --recursive "git reset --hard && git clean -df" - - git lfs pull - (ulimit -n 65535 && git lfs prune) -)} - -export GIT_PACK_THREADS=8 - -# set up environment -if [ ! -d "$SOURCE_DIR" ]; then - git clone https://github.com/commaai/openpilot.git $SOURCE_DIR -fi - -if [ ! -z "$UNSAFE" ]; then - echo "trying unsafe checkout" - set +e - unsafe_checkout - if [[ "$?" -ne 0 ]]; then - safe_checkout - fi - set -e -else - echo "doing safe checkout" - safe_checkout -fi - -echo "$TEST_DIR synced with $GIT_COMMIT, t=$SECONDS" diff --git a/selfdrive/test/setup_vsound.sh b/selfdrive/test/setup_vsound.sh deleted file mode 100755 index aab1499744..0000000000 --- a/selfdrive/test/setup_vsound.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env bash - -{ - #start pulseaudio daemon - sudo pulseaudio -D - - # create a virtual null audio and set it to default device - sudo pactl load-module module-null-sink sink_name=virtual_audio - sudo pactl set-default-sink virtual_audio -} > /dev/null 2>&1 diff --git a/selfdrive/test/setup_xvfb.sh b/selfdrive/test/setup_xvfb.sh deleted file mode 100755 index 692b84d65f..0000000000 --- a/selfdrive/test/setup_xvfb.sh +++ /dev/null @@ -1,19 +0,0 @@ -#!/usr/bin/env bash - -# Sets up a virtual display for running map renderer and simulator without an X11 display - -DISP_ID=99 -export DISPLAY=:$DISP_ID - -sudo Xvfb $DISPLAY -screen 0 2160x1080x24 2>/dev/null & - -# check for x11 socket for the specified display ID -while [ ! -S /tmp/.X11-unix/X$DISP_ID ] -do - echo "Waiting for Xvfb..." - sleep 1 -done - -touch ~/.Xauthority -export XDG_SESSION_TYPE="x11" -xset -q \ No newline at end of file diff --git a/selfdrive/test/test_updated.py b/selfdrive/test/test_updated.py deleted file mode 100644 index ea945d94c2..0000000000 --- a/selfdrive/test/test_updated.py +++ /dev/null @@ -1,296 +0,0 @@ -import datetime -import os -import pytest -import time -import tempfile -import shutil -import signal -import subprocess -import random - -from openpilot.common.basedir import BASEDIR -from openpilot.common.params import Params - - -@pytest.mark.tici -class TestUpdated: - - def setup_method(self): - self.updated_proc = None - - self.tmp_dir = tempfile.TemporaryDirectory() - org_dir = os.path.join(self.tmp_dir.name, "commaai") - - self.basedir = os.path.join(org_dir, "openpilot") - self.git_remote_dir = os.path.join(org_dir, "openpilot_remote") - self.staging_dir = os.path.join(org_dir, "safe_staging") - for d in [org_dir, self.basedir, self.git_remote_dir, self.staging_dir]: - os.mkdir(d) - - self.neos_version = os.path.join(org_dir, "neos_version") - self.neosupdate_dir = os.path.join(org_dir, "neosupdate") - with open(self.neos_version, "w") as f: - v = subprocess.check_output(r"bash -c 'source launch_env.sh && echo $REQUIRED_NEOS_VERSION'", - cwd=BASEDIR, shell=True, encoding='utf8').strip() - f.write(v) - - self.upper_dir = os.path.join(self.staging_dir, "upper") - self.merged_dir = os.path.join(self.staging_dir, "merged") - self.finalized_dir = os.path.join(self.staging_dir, "finalized") - - # setup local submodule remotes - submodules = subprocess.check_output("git submodule --quiet foreach 'echo $name'", - shell=True, cwd=BASEDIR, encoding='utf8').split() - for s in submodules: - sub_path = os.path.join(org_dir, s.split("_repo")[0]) - self._run(f"git clone {s} {sub_path}.git", cwd=BASEDIR) - - # setup two git repos, a remote and one we'll run updated in - self._run([ - f"git clone {BASEDIR} {self.git_remote_dir}", - f"git clone {self.git_remote_dir} {self.basedir}", - f"cd {self.basedir} && git submodule init && git submodule update", - f"cd {self.basedir} && scons -j{os.cpu_count()} cereal/ common/" - ]) - - self.params = Params(os.path.join(self.basedir, "persist/params")) - self.params.clear_all() - os.sync() - - def teardown_method(self): - try: - if self.updated_proc is not None: - self.updated_proc.terminate() - self.updated_proc.wait(30) - except Exception as e: - print(e) - self.tmp_dir.cleanup() - - - # *** test helpers *** - - - def _run(self, cmd, cwd=None): - if not isinstance(cmd, list): - cmd = (cmd,) - - for c in cmd: - subprocess.check_output(c, cwd=cwd, shell=True) - - def _get_updated_proc(self): - os.environ["PYTHONPATH"] = self.basedir - os.environ["GIT_AUTHOR_NAME"] = "testy tester" - os.environ["GIT_COMMITTER_NAME"] = "testy tester" - os.environ["GIT_AUTHOR_EMAIL"] = "testy@tester.test" - os.environ["GIT_COMMITTER_EMAIL"] = "testy@tester.test" - os.environ["UPDATER_TEST_IP"] = "localhost" - os.environ["UPDATER_LOCK_FILE"] = os.path.join(self.tmp_dir.name, "updater.lock") - os.environ["UPDATER_STAGING_ROOT"] = self.staging_dir - os.environ["UPDATER_NEOS_VERSION"] = self.neos_version - os.environ["UPDATER_NEOSUPDATE_DIR"] = self.neosupdate_dir - updated_path = os.path.join(self.basedir, "system/updated.py") - return subprocess.Popen(updated_path, env=os.environ) - - def _start_updater(self, offroad=True, nosleep=False): - self.params.put_bool("IsOffroad", offroad) - self.updated_proc = self._get_updated_proc() - if not nosleep: - time.sleep(1) - - def _update_now(self): - self.updated_proc.send_signal(signal.SIGHUP) - - # TODO: this should be implemented in params - def _read_param(self, key, timeout=1): - ret = None - start_time = time.monotonic() - while ret is None: - ret = self.params.get(key, encoding='utf8') - if time.monotonic() - start_time > timeout: - break - time.sleep(0.01) - return ret - - def _wait_for_update(self, timeout=30, clear_param=False): - if clear_param: - self.params.remove("LastUpdateTime") - - self._update_now() - t = self._read_param("LastUpdateTime", timeout=timeout) - if t is None: - raise Exception("timed out waiting for update to complete") - - def _make_commit(self): - all_dirs, all_files = [], [] - for root, dirs, files in os.walk(self.git_remote_dir): - if ".git" in root: - continue - for d in dirs: - all_dirs.append(os.path.join(root, d)) - for f in files: - all_files.append(os.path.join(root, f)) - - # make a new dir and some new files - new_dir = os.path.join(self.git_remote_dir, "this_is_a_new_dir") - os.mkdir(new_dir) - for _ in range(random.randrange(5, 30)): - for d in (new_dir, random.choice(all_dirs)): - with tempfile.NamedTemporaryFile(dir=d, delete=False) as f: - f.write(os.urandom(random.randrange(1, 1000000))) - - # modify some files - for f in random.sample(all_files, random.randrange(5, 50)): - with open(f, "w+") as ff: - txt = ff.readlines() - ff.seek(0) - for line in txt: - ff.write(line[::-1]) - - # remove some files - for f in random.sample(all_files, random.randrange(5, 50)): - os.remove(f) - - # remove some dirs - for d in random.sample(all_dirs, random.randrange(1, 10)): - shutil.rmtree(d) - - # commit the changes - self._run([ - "git add -A", - "git commit -m 'an update'", - ], cwd=self.git_remote_dir) - - def _check_update_state(self, update_available): - # make sure LastUpdateTime is recent - t = self._read_param("LastUpdateTime") - last_update_time = datetime.datetime.fromisoformat(t) - td = datetime.datetime.now(datetime.UTC).replace(tzinfo=None) - last_update_time - assert td.total_seconds() < 10 - self.params.remove("LastUpdateTime") - - # wait a bit for the rest of the params to be written - time.sleep(0.1) - - # check params - update = self._read_param("UpdateAvailable") - assert update == "1" == update_available, f"UpdateAvailable: {repr(update)}" - assert self._read_param("UpdateFailedCount") == "0" - - # TODO: check that the finalized update actually matches remote - # check the .overlay_init and .overlay_consistent flags - assert os.path.isfile(os.path.join(self.basedir, ".overlay_init")) - assert os.path.isfile(os.path.join(self.finalized_dir, ".overlay_consistent")) == update_available - - - # *** test cases *** - - - # Run updated for 100 cycles with no update - def test_no_update(self): - self._start_updater() - for _ in range(100): - self._wait_for_update(clear_param=True) - self._check_update_state(False) - - # Let the updater run with no update for a cycle, then write an update - def test_update(self): - self._start_updater() - - # run for a cycle with no update - self._wait_for_update(clear_param=True) - self._check_update_state(False) - - # write an update to our remote - self._make_commit() - - # run for a cycle to get the update - self._wait_for_update(timeout=60, clear_param=True) - self._check_update_state(True) - - # run another cycle with no update - self._wait_for_update(clear_param=True) - self._check_update_state(True) - - # Let the updater run for 10 cycles, and write an update every cycle - @pytest.mark.skip("need to make this faster") - def test_update_loop(self): - self._start_updater() - - # run for a cycle with no update - self._wait_for_update(clear_param=True) - for _ in range(10): - time.sleep(0.5) - self._make_commit() - self._wait_for_update(timeout=90, clear_param=True) - self._check_update_state(True) - - # Test overlay re-creation after tracking a new file in basedir's git - def test_overlay_reinit(self): - self._start_updater() - - overlay_init_fn = os.path.join(self.basedir, ".overlay_init") - - # run for a cycle with no update - self._wait_for_update(clear_param=True) - self.params.remove("LastUpdateTime") - first_mtime = os.path.getmtime(overlay_init_fn) - - # touch a file in the basedir - self._run("touch new_file && git add new_file", cwd=self.basedir) - - # run another cycle, should have a new mtime - self._wait_for_update(clear_param=True) - second_mtime = os.path.getmtime(overlay_init_fn) - assert first_mtime != second_mtime - - # run another cycle, mtime should be same as last cycle - self._wait_for_update(clear_param=True) - new_mtime = os.path.getmtime(overlay_init_fn) - assert second_mtime == new_mtime - - # Make sure updated exits if another instance is running - def test_multiple_instances(self): - # start updated and let it run for a cycle - self._start_updater() - time.sleep(1) - self._wait_for_update(clear_param=True) - - # start another instance - second_updated = self._get_updated_proc() - ret_code = second_updated.wait(timeout=5) - assert ret_code is not None - - - # *** test cases with NEOS updates *** - - - # Run updated with no update, make sure it clears the old NEOS update - def test_clear_neos_cache(self): - # make the dir and some junk files - os.mkdir(self.neosupdate_dir) - for _ in range(15): - with tempfile.NamedTemporaryFile(dir=self.neosupdate_dir, delete=False) as f: - f.write(os.urandom(random.randrange(1, 1000000))) - - self._start_updater() - self._wait_for_update(clear_param=True) - self._check_update_state(False) - assert not os.path.isdir(self.neosupdate_dir) - - # Let the updater run with no update for a cycle, then write an update - @pytest.mark.skip("TODO: only runs on device") - def test_update_with_neos_update(self): - # bump the NEOS version and commit it - self._run([ - "echo 'export REQUIRED_NEOS_VERSION=3' >> launch_env.sh", - "git -c user.name='testy' -c user.email='testy@tester.test' \ - commit -am 'a neos update'", - ], cwd=self.git_remote_dir) - - # run for a cycle to get the update - self._start_updater() - self._wait_for_update(timeout=60, clear_param=True) - self._check_update_state(True) - - # TODO: more comprehensive check - assert os.path.isdir(self.neosupdate_dir) diff --git a/selfdrive/ui/.gitignore b/selfdrive/ui/.gitignore deleted file mode 100644 index 7e9eaf932f..0000000000 --- a/selfdrive/ui/.gitignore +++ /dev/null @@ -1,14 +0,0 @@ -moc_* -*.moc - -translations/main_test_en.* - -ui -mui -watch3 -installer/installers/* -qt/setup/setup -qt/setup/reset -qt/setup/wifi -qt/setup/updater -translations/alerts_generated.h diff --git a/selfdrive/ui/SConscript b/selfdrive/ui/SConscript deleted file mode 100644 index d883ca5b15..0000000000 --- a/selfdrive/ui/SConscript +++ /dev/null @@ -1,119 +0,0 @@ -import json -Import('env', 'qt_env', 'arch', 'common', 'messaging', 'visionipc', 'transformations') - -base_libs = [common, messaging, visionipc, transformations, - 'm', 'OpenCL', 'ssl', 'crypto', 'pthread'] + qt_env["LIBS"] - -if arch == 'larch64': - base_libs.append('EGL') - -if arch == "Darwin": - del base_libs[base_libs.index('OpenCL')] - qt_env['FRAMEWORKS'] += ['OpenCL'] - -sp_widgets_src = [] -sp_qt_src = [] -sp_qt_util = [] -if not GetOption('stock_ui'): - SConscript(['sunnypilot/SConscript']) - Import('sp_widgets_src', 'sp_qt_src', 'sp_qt_util') - -# FIXME: remove this once we're on 5.15 (24.04) -qt_env['CXXFLAGS'] += ["-Wno-deprecated-declarations"] - -qt_util = qt_env.Library("qt_util", ["#selfdrive/ui/qt/api.cc", "#selfdrive/ui/qt/util.cc"] + sp_qt_util, LIBS=base_libs) -widgets_src = ["qt/widgets/input.cc", "qt/widgets/wifi.cc", "qt/prime_state.cc", - "qt/widgets/ssh_keys.cc", "qt/widgets/toggle.cc", "qt/widgets/controls.cc", - "qt/widgets/offroad_alerts.cc", "qt/widgets/prime.cc", "qt/widgets/keyboard.cc", - "qt/widgets/scrollview.cc", "qt/widgets/cameraview.cc", "#third_party/qrcode/QrCode.cc", - "qt/request_repeater.cc", "qt/qt_window.cc", "qt/network/networking.cc", "qt/network/wifi_manager.cc"] + sp_widgets_src - -widgets = qt_env.Library("qt_widgets", widgets_src, LIBS=base_libs) -Export('widgets') -qt_libs = [widgets, qt_util] + base_libs - -qt_src = ["main.cc", "ui.cc", "qt/sidebar.cc", "qt/body.cc", - "qt/window.cc", "qt/home.cc", "qt/offroad/settings.cc", "qt/offroad/offroad_home.cc", - "qt/offroad/software_settings.cc", "qt/offroad/developer_panel.cc", "qt/offroad/onboarding.cc", - "qt/offroad/driverview.cc", "qt/offroad/experimental_mode.cc", "qt/offroad/firehose.cc", - "qt/onroad/onroad_home.cc", "qt/onroad/annotated_camera.cc", "qt/onroad/model.cc", - "qt/onroad/buttons.cc", "qt/onroad/alerts.cc", "qt/onroad/driver_monitoring.cc", "qt/onroad/hud.cc"] + sp_qt_src - -# build translation files -with open(File("translations/languages.json").abspath) as f: - languages = json.loads(f.read()) -translation_sources = [f"#selfdrive/ui/translations/{l}.ts" for l in languages.values()] -translation_targets = [src.replace(".ts", ".qm") for src in translation_sources] -lrelease_bin = 'third_party/qt5/larch64/bin/lrelease' if arch == 'larch64' else 'lrelease' - -lrelease = qt_env.Command(translation_targets, translation_sources, f"{lrelease_bin} $SOURCES") -qt_env.NoClean(translation_sources) -qt_env.Precious(translation_sources) - -# create qrc file for compiled translations to include with assets -translations_assets_src = "#selfdrive/assets/translations_assets.qrc" -with open(File(translations_assets_src).abspath, 'w') as f: - f.write('\n\n') - f.write('\n'.join([f'../ui/translations/{l}.qm' for l in languages.values()])) - f.write('\n\n') - -# build assets -assets = "#selfdrive/assets/assets.cc" -assets_src = "#selfdrive/assets/assets.qrc" -qt_env.Command(assets, [assets_src, translations_assets_src], f"rcc $SOURCES -o $TARGET") -qt_env.Depends(assets, Glob('#selfdrive/assets/*', exclude=[assets, assets_src, translations_assets_src, "#selfdrive/assets/assets.o"]) + [lrelease]) -asset_obj = qt_env.Object("assets", assets) - -# build main UI -qt_env.Program("ui", qt_src + [asset_obj], LIBS=qt_libs) -if GetOption('extras'): - qt_src.remove("main.cc") # replaced by test_runner - qt_env.Program('tests/test_translations', [asset_obj, 'tests/test_runner.cc', 'tests/test_translations.cc'] + qt_src, LIBS=qt_libs) - - qt_env.SharedLibrary("qt/python_helpers", ["qt/qt_window.cc"], LIBS=qt_libs) - - # setup and factory resetter - qt_env.Program("qt/setup/reset", ["qt/setup/reset.cc"], LIBS=qt_libs) - qt_env.Program("qt/setup/setup", ["qt/setup/setup.cc", asset_obj], - LIBS=qt_libs + ['curl', 'common']) - - # build updater UI - qt_env.Program("qt/setup/updater", ["qt/setup/updater.cc", asset_obj], LIBS=qt_libs) - - if arch != "Darwin": - # build installers - raylib_env = env.Clone() - raylib_env['LIBPATH'] += [f'#third_party/raylib/{arch}/'] - raylib_env['LINKFLAGS'].append('-Wl,-strip-debug') - - raylib_libs = common + ["raylib"] - if arch == "larch64": - raylib_libs += ["GLESv2", "wayland-client", "wayland-egl", "EGL"] - else: - raylib_libs += ["GL"] - - release = "release3" - installers = [ - ("openpilot", release), - ("openpilot_test", f"{release}-staging"), - ("openpilot_nightly", "nightly"), - ("openpilot_internal", "nightly-dev"), - ] - - cont = raylib_env.Command("installer/continue_openpilot.o", "installer/continue_openpilot.sh", - "ld -r -b binary -o $TARGET $SOURCE") - inter = raylib_env.Command("installer/inter_ttf.o", "installer/inter-ascii.ttf", - "ld -r -b binary -o $TARGET $SOURCE") - for name, branch in installers: - d = {'BRANCH': f"'\"{branch}\"'"} - if "internal" in name: - d['INTERNAL'] = "1" - - obj = raylib_env.Object(f"installer/installers/installer_{name}.o", ["installer/installer.cc"], CPPDEFINES=d) - f = raylib_env.Program(f"installer/installers/installer_{name}", [obj, cont, inter], LIBS=raylib_libs) - # keep installers small - assert f[0].get_size() < 1900*1e3, f[0].get_size() - -# build watch3 -if arch in ['x86_64', 'aarch64', 'Darwin'] or GetOption('extras'): - qt_env.Program("watch3", ["watch3.cc"], LIBS=qt_libs + ['common', 'msgq', 'visionipc']) diff --git a/selfdrive/ui/installer/installer.cc b/selfdrive/ui/installer/installer.cc deleted file mode 100644 index 7326e089ab..0000000000 --- a/selfdrive/ui/installer/installer.cc +++ /dev/null @@ -1,187 +0,0 @@ -#include -#include -#include -#include - -#include "common/swaglog.h" -#include "common/util.h" -#include "third_party/raylib/include/raylib.h" - -int freshClone(); -int cachedFetch(const std::string &cache); -int executeGitCommand(const std::string &cmd); - -std::string get_str(std::string const s) { - std::string::size_type pos = s.find('?'); - assert(pos != std::string::npos); - return s.substr(0, pos); -} - -// Leave some extra space for the fork installer -const std::string GIT_URL = get_str("https://github.com/commaai/openpilot.git" "? "); -const std::string BRANCH_STR = get_str(BRANCH "? "); - -#define GIT_SSH_URL "git@github.com:commaai/openpilot.git" -#define CONTINUE_PATH "/data/continue.sh" - -const std::string CACHE_PATH = "/data/openpilot.cache"; - -#define INSTALL_PATH "/data/openpilot" -#define TMP_INSTALL_PATH "/data/tmppilot" - -extern const uint8_t str_continue[] asm("_binary_selfdrive_ui_installer_continue_openpilot_sh_start"); -extern const uint8_t str_continue_end[] asm("_binary_selfdrive_ui_installer_continue_openpilot_sh_end"); -extern const uint8_t inter_ttf[] asm("_binary_selfdrive_ui_installer_inter_ascii_ttf_start"); -extern const uint8_t inter_ttf_end[] asm("_binary_selfdrive_ui_installer_inter_ascii_ttf_end"); - -Font font; - -void run(const char* cmd) { - int err = std::system(cmd); - assert(err == 0); -} - -void renderProgress(int progress) { - BeginDrawing(); - ClearBackground(BLACK); - DrawTextEx(font, "Installing...", (Vector2){150, 290}, 110, 0, WHITE); - Rectangle bar = {150, 570, (float)GetScreenWidth() - 300, 72}; - DrawRectangleRec(bar, (Color){41, 41, 41, 255}); - progress = std::clamp(progress, 0, 100); - bar.width *= progress / 100.0f; - DrawRectangleRec(bar, (Color){70, 91, 234, 255}); - DrawTextEx(font, (std::to_string(progress) + "%").c_str(), (Vector2){150, 670}, 85, 0, WHITE); - EndDrawing(); -} - -int doInstall() { - // wait for valid time - while (!util::system_time_valid()) { - util::sleep_for(500); - LOGD("Waiting for valid time"); - } - - // cleanup previous install attempts - run("rm -rf " TMP_INSTALL_PATH " " INSTALL_PATH); - - // do the install - if (util::file_exists(CACHE_PATH)) { - return cachedFetch(CACHE_PATH); - } else { - return freshClone(); - } -} - -int freshClone() { - LOGD("Doing fresh clone"); - std::string cmd = util::string_format("git clone --progress %s -b %s --depth=1 --recurse-submodules %s 2>&1", - GIT_URL.c_str(), BRANCH_STR.c_str(), TMP_INSTALL_PATH); - return executeGitCommand(cmd); -} - -int cachedFetch(const std::string &cache) { - LOGD("Fetching with cache: %s", cache.c_str()); - - run(util::string_format("cp -rp %s %s", cache.c_str(), TMP_INSTALL_PATH).c_str()); - run(util::string_format("cd %s && git remote set-branches --add origin %s", TMP_INSTALL_PATH, BRANCH_STR.c_str()).c_str()); - - renderProgress(10); - - return executeGitCommand(util::string_format("cd %s && git fetch --progress origin %s 2>&1", TMP_INSTALL_PATH, BRANCH_STR.c_str())); -} - -int executeGitCommand(const std::string &cmd) { - static const std::array stages = { - // prefix, weight in percentage - std::pair{"Receiving objects: ", 91}, - std::pair{"Resolving deltas: ", 2}, - std::pair{"Updating files: ", 7}, - }; - - FILE *pipe = popen(cmd.c_str(), "r"); - if (!pipe) return -1; - - char buffer[512]; - while (fgets(buffer, sizeof(buffer), pipe) != nullptr) { - std::string line(buffer); - int base = 0; - for (const auto &[text, weight] : stages) { - if (line.find(text) != std::string::npos) { - size_t percentPos = line.find("%"); - if (percentPos != std::string::npos && percentPos >= 3) { - int percent = std::stoi(line.substr(percentPos - 3, 3)); - int progress = base + int(percent / 100. * weight); - renderProgress(progress); - } - break; - } - base += weight; - } - } - return pclose(pipe); -} - -void cloneFinished(int exitCode) { - LOGD("git finished with %d", exitCode); - assert(exitCode == 0); - - renderProgress(100); - - // ensure correct branch is checked out - int err = chdir(TMP_INSTALL_PATH); - assert(err == 0); - run(("git checkout " + BRANCH_STR).c_str()); - run(("git reset --hard origin/" + BRANCH_STR).c_str()); - run("git submodule update --init"); - - // move into place - run("mv " TMP_INSTALL_PATH " " INSTALL_PATH); - -#ifdef INTERNAL - run("mkdir -p /data/params/d/"); - - // https://github.com/commaci2.keys - const std::string ssh_keys = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIMX2kU8eBZyEWmbq0tjMPxksWWVuIV/5l64GabcYbdpI"; - std::map params = { - {"SshEnabled", "1"}, - {"RecordFrontLock", "1"}, - {"GithubSshKeys", ssh_keys}, - }; - for (const auto& [key, value] : params) { - std::ofstream param; - param.open("/data/params/d/" + key); - param << value; - param.close(); - } - run("cd " INSTALL_PATH " && " - "git remote set-url origin --push " GIT_SSH_URL " && " - "git config --replace-all remote.origin.fetch \"+refs/heads/*:refs/remotes/origin/*\""); -#endif - - // write continue.sh - FILE *of = fopen("/data/continue.sh.new", "wb"); - assert(of != NULL); - - size_t num = str_continue_end - str_continue; - size_t num_written = fwrite(str_continue, 1, num, of); - assert(num == num_written); - fclose(of); - - run("chmod +x /data/continue.sh.new"); - run("mv /data/continue.sh.new " CONTINUE_PATH); - - // wait for the installed software's UI to take over - util::sleep_for(60 * 1000); -} - -int main(int argc, char *argv[]) { - InitWindow(2160, 1080, "Installer"); - font = LoadFontFromMemory(".ttf", inter_ttf, inter_ttf_end - inter_ttf, 120, NULL, 0); - SetTextureFilter(font.texture, TEXTURE_FILTER_BILINEAR); - renderProgress(0); - int result = doInstall(); - cloneFinished(result); - CloseWindow(); - UnloadFont(font); - return 0; -} diff --git a/selfdrive/ui/layouts/home.py b/selfdrive/ui/layouts/home.py deleted file mode 100644 index 0fa91da552..0000000000 --- a/selfdrive/ui/layouts/home.py +++ /dev/null @@ -1,214 +0,0 @@ -import time -import pyray as rl -from collections.abc import Callable -from enum import IntEnum -from openpilot.common.params import Params -from openpilot.selfdrive.ui.widgets.offroad_alerts import UpdateAlert, OffroadAlert -from openpilot.selfdrive.ui.widgets.exp_mode_button import ExperimentalModeButton -from openpilot.selfdrive.ui.widgets.prime import PrimeWidget -from openpilot.selfdrive.ui.widgets.setup import SetupWidget -from openpilot.system.ui.lib.text_measure import measure_text_cached -from openpilot.system.ui.lib.application import gui_app, FontWeight, DEFAULT_TEXT_COLOR -from openpilot.system.ui.lib.widget import Widget - -HEADER_HEIGHT = 80 -HEAD_BUTTON_FONT_SIZE = 40 -CONTENT_MARGIN = 40 -SPACING = 25 -RIGHT_COLUMN_WIDTH = 750 -REFRESH_INTERVAL = 10.0 - -PRIME_BG_COLOR = rl.Color(51, 51, 51, 255) - - -class HomeLayoutState(IntEnum): - HOME = 0 - UPDATE = 1 - ALERTS = 2 - - -class HomeLayout(Widget): - def __init__(self): - super().__init__() - self.params = Params() - - self.update_alert = UpdateAlert() - self.offroad_alert = OffroadAlert() - - self.current_state = HomeLayoutState.HOME - self.last_refresh = 0 - self.settings_callback: callable | None = None - - self.update_available = False - self.alert_count = 0 - - self.header_rect = rl.Rectangle(0, 0, 0, 0) - self.content_rect = rl.Rectangle(0, 0, 0, 0) - self.left_column_rect = rl.Rectangle(0, 0, 0, 0) - self.right_column_rect = rl.Rectangle(0, 0, 0, 0) - - self.update_notif_rect = rl.Rectangle(0, 0, 200, HEADER_HEIGHT - 10) - self.alert_notif_rect = rl.Rectangle(0, 0, 220, HEADER_HEIGHT - 10) - - self._prime_widget = PrimeWidget() - self._setup_widget = SetupWidget() - - self._exp_mode_button = ExperimentalModeButton() - self._setup_callbacks() - - def _setup_callbacks(self): - self.update_alert.set_dismiss_callback(lambda: self._set_state(HomeLayoutState.HOME)) - self.offroad_alert.set_dismiss_callback(lambda: self._set_state(HomeLayoutState.HOME)) - - def set_settings_callback(self, callback: Callable): - self.settings_callback = callback - - def _set_state(self, state: HomeLayoutState): - self.current_state = state - - def _render(self, rect: rl.Rectangle): - current_time = time.time() - if current_time - self.last_refresh >= REFRESH_INTERVAL: - self._refresh() - self.last_refresh = current_time - - self._handle_input() - self._render_header() - - # Render content based on current state - if self.current_state == HomeLayoutState.HOME: - self._render_home_content() - elif self.current_state == HomeLayoutState.UPDATE: - self._render_update_view() - elif self.current_state == HomeLayoutState.ALERTS: - self._render_alerts_view() - - def _update_layout_rects(self): - self.header_rect = rl.Rectangle( - self._rect.x + CONTENT_MARGIN, self._rect.y + CONTENT_MARGIN, self._rect.width - 2 * CONTENT_MARGIN, HEADER_HEIGHT - ) - - content_y = self._rect.y + CONTENT_MARGIN + HEADER_HEIGHT + SPACING - content_height = self._rect.height - CONTENT_MARGIN - HEADER_HEIGHT - SPACING - CONTENT_MARGIN - - self.content_rect = rl.Rectangle( - self._rect.x + CONTENT_MARGIN, content_y, self._rect.width - 2 * CONTENT_MARGIN, content_height - ) - - left_width = self.content_rect.width - RIGHT_COLUMN_WIDTH - SPACING - - self.left_column_rect = rl.Rectangle(self.content_rect.x, self.content_rect.y, left_width, self.content_rect.height) - - self.right_column_rect = rl.Rectangle( - self.content_rect.x + left_width + SPACING, self.content_rect.y, RIGHT_COLUMN_WIDTH, self.content_rect.height - ) - - self.update_notif_rect.x = self.header_rect.x - self.update_notif_rect.y = self.header_rect.y + (self.header_rect.height - 60) // 2 - - notif_x = self.header_rect.x + (220 if self.update_available else 0) - self.alert_notif_rect.x = notif_x - self.alert_notif_rect.y = self.header_rect.y + (self.header_rect.height - 60) // 2 - - def _handle_input(self): - if not rl.is_mouse_button_pressed(rl.MouseButton.MOUSE_BUTTON_LEFT): - return - - mouse_pos = rl.get_mouse_position() - - if self.update_available and rl.check_collision_point_rec(mouse_pos, self.update_notif_rect): - self._set_state(HomeLayoutState.UPDATE) - return - - if self.alert_count > 0 and rl.check_collision_point_rec(mouse_pos, self.alert_notif_rect): - self._set_state(HomeLayoutState.ALERTS) - return - - # Content area input handling - if self.current_state == HomeLayoutState.UPDATE: - self.update_alert.handle_input(mouse_pos, True) - elif self.current_state == HomeLayoutState.ALERTS: - self.offroad_alert.handle_input(mouse_pos, True) - - def _render_header(self): - font = gui_app.font(FontWeight.MEDIUM) - - # Update notification button - if self.update_available: - # Highlight if currently viewing updates - highlight_color = rl.Color(255, 140, 40, 255) if self.current_state == HomeLayoutState.UPDATE else rl.Color(255, 102, 0, 255) - rl.draw_rectangle_rounded(self.update_notif_rect, 0.3, 10, highlight_color) - - text = "UPDATE" - text_width = measure_text_cached(font, text, HEAD_BUTTON_FONT_SIZE).x - text_x = self.update_notif_rect.x + (self.update_notif_rect.width - text_width) // 2 - text_y = self.update_notif_rect.y + (self.update_notif_rect.height - HEAD_BUTTON_FONT_SIZE) // 2 - rl.draw_text_ex(font, text, rl.Vector2(int(text_x), int(text_y)), HEAD_BUTTON_FONT_SIZE, 0, rl.WHITE) - - # Alert notification button - if self.alert_count > 0: - # Highlight if currently viewing alerts - highlight_color = rl.Color(255, 70, 70, 255) if self.current_state == HomeLayoutState.ALERTS else rl.Color(226, 44, 44, 255) - rl.draw_rectangle_rounded(self.alert_notif_rect, 0.3, 10, highlight_color) - - alert_text = f"{self.alert_count} ALERT{'S' if self.alert_count > 1 else ''}" - text_width = measure_text_cached(font, alert_text, HEAD_BUTTON_FONT_SIZE).x - text_x = self.alert_notif_rect.x + (self.alert_notif_rect.width - text_width) // 2 - text_y = self.alert_notif_rect.y + (self.alert_notif_rect.height - HEAD_BUTTON_FONT_SIZE) // 2 - rl.draw_text_ex(font, alert_text, rl.Vector2(int(text_x), int(text_y)), HEAD_BUTTON_FONT_SIZE, 0, rl.WHITE) - - # Version text (right aligned) - version_text = self._get_version_text() - text_width = measure_text_cached(gui_app.font(FontWeight.NORMAL), version_text, 48).x - version_x = self.header_rect.x + self.header_rect.width - text_width - version_y = self.header_rect.y + (self.header_rect.height - 48) // 2 - rl.draw_text_ex(gui_app.font(FontWeight.NORMAL), version_text, rl.Vector2(int(version_x), int(version_y)), 48, 0, DEFAULT_TEXT_COLOR) - - def _render_home_content(self): - self._render_left_column() - self._render_right_column() - - def _render_update_view(self): - self.update_alert.render(self.content_rect) - - def _render_alerts_view(self): - self.offroad_alert.render(self.content_rect) - - def _render_left_column(self): - self._prime_widget.render(self.left_column_rect) - - def _render_right_column(self): - exp_height = 125 - exp_rect = rl.Rectangle( - self.right_column_rect.x, self.right_column_rect.y, self.right_column_rect.width, exp_height - ) - self._exp_mode_button.render(exp_rect) - - setup_rect = rl.Rectangle( - self.right_column_rect.x, - self.right_column_rect.y + exp_height + SPACING, - self.right_column_rect.width, - self.right_column_rect.height - exp_height - SPACING, - ) - self._setup_widget.render(setup_rect) - - def _refresh(self): - # TODO: implement _update_state with a timer - self.update_available = self.update_alert.refresh() - self.alert_count = self.offroad_alert.refresh() - self._update_state_priority(self.update_available, self.alert_count > 0) - - def _update_state_priority(self, update_available: bool, alerts_present: bool): - current_state = self.current_state - - if not update_available and not alerts_present: - self.current_state = HomeLayoutState.HOME - elif update_available and (current_state == HomeLayoutState.HOME or (not alerts_present and current_state == HomeLayoutState.ALERTS)): - self.current_state = HomeLayoutState.UPDATE - elif alerts_present and (current_state == HomeLayoutState.HOME or (not update_available and current_state == HomeLayoutState.UPDATE)): - self.current_state = HomeLayoutState.ALERTS - - def _get_version_text(self) -> str: - brand = "openpilot" - description = self.params.get("UpdaterCurrentDescription", encoding='utf-8') - return f"{brand} {description}" if description else brand diff --git a/selfdrive/ui/layouts/main.py b/selfdrive/ui/layouts/main.py deleted file mode 100644 index a3081143f4..0000000000 --- a/selfdrive/ui/layouts/main.py +++ /dev/null @@ -1,93 +0,0 @@ -import pyray as rl -from enum import IntEnum -import cereal.messaging as messaging -from openpilot.selfdrive.ui.layouts.sidebar import Sidebar, SIDEBAR_WIDTH -from openpilot.selfdrive.ui.layouts.home import HomeLayout -from openpilot.selfdrive.ui.layouts.settings.settings import SettingsLayout, PanelType -from openpilot.selfdrive.ui.ui_state import device, ui_state -from openpilot.selfdrive.ui.onroad.augmented_road_view import AugmentedRoadView -from openpilot.system.ui.lib.widget import Widget - - -class MainState(IntEnum): - HOME = 0 - SETTINGS = 1 - ONROAD = 2 - - -class MainLayout(Widget): - def __init__(self): - super().__init__() - - self._pm = messaging.PubMaster(['userFlag']) - - self._sidebar = Sidebar() - self._current_mode = MainState.HOME - self._prev_onroad = False - - # Initialize layouts - self._layouts = {MainState.HOME: HomeLayout(), MainState.SETTINGS: SettingsLayout(), MainState.ONROAD: AugmentedRoadView()} - - self._sidebar_rect = rl.Rectangle(0, 0, 0, 0) - self._content_rect = rl.Rectangle(0, 0, 0, 0) - - # Set callbacks - self._setup_callbacks() - - def _render(self, _): - self._handle_onroad_transition() - self._render_main_content() - - def _setup_callbacks(self): - self._sidebar.set_callbacks(on_settings=self._on_settings_clicked, - on_flag=self._on_flag_clicked) - self._layouts[MainState.HOME]._setup_widget.set_open_settings_callback(lambda: self.open_settings(PanelType.FIREHOSE)) - self._layouts[MainState.SETTINGS].set_callbacks(on_close=self._set_mode_for_state) - self._layouts[MainState.ONROAD].set_callbacks(on_click=self._on_onroad_clicked) - device.add_interactive_timeout_callback(self._set_mode_for_state) - - def _update_layout_rects(self): - self._sidebar_rect = rl.Rectangle(self._rect.x, self._rect.y, SIDEBAR_WIDTH, self._rect.height) - - x_offset = SIDEBAR_WIDTH if self._sidebar.is_visible else 0 - self._content_rect = rl.Rectangle(self._rect.y + x_offset, self._rect.y, self._rect.width - x_offset, self._rect.height) - - def _handle_onroad_transition(self): - if ui_state.started != self._prev_onroad: - self._prev_onroad = ui_state.started - - self._set_mode_for_state() - - def _set_mode_for_state(self): - if ui_state.started: - # Don't hide sidebar from interactive timeout - if self._current_mode != MainState.ONROAD: - self._sidebar.set_visible(False) - self._current_mode = MainState.ONROAD - else: - self._current_mode = MainState.HOME - self._sidebar.set_visible(True) - - def open_settings(self, panel_type: PanelType): - self._layouts[MainState.SETTINGS].set_current_panel(panel_type) - self._current_mode = MainState.SETTINGS - self._sidebar.set_visible(False) - - def _on_settings_clicked(self): - self.open_settings(PanelType.DEVICE) - - def _on_flag_clicked(self): - user_flag = messaging.new_message('userFlag') - user_flag.valid = True - self._pm.send('userFlag', user_flag) - - def _on_onroad_clicked(self): - self._sidebar.set_visible(not self._sidebar.is_visible) - - def _render_main_content(self): - # Render sidebar - if self._sidebar.is_visible: - self._sidebar.render(self._sidebar_rect) - - content_rect = self._content_rect if self._sidebar.is_visible else self._rect - self._layouts[self._current_mode].render(content_rect) diff --git a/selfdrive/ui/layouts/network.py b/selfdrive/ui/layouts/network.py deleted file mode 100644 index c227facd04..0000000000 --- a/selfdrive/ui/layouts/network.py +++ /dev/null @@ -1,17 +0,0 @@ -import pyray as rl -from openpilot.system.ui.lib.widget import Widget -from openpilot.system.ui.lib.wifi_manager import WifiManagerWrapper -from openpilot.system.ui.widgets.network import WifiManagerUI - - -class NetworkLayout(Widget): - def __init__(self): - super().__init__() - self.wifi_manager = WifiManagerWrapper() - self.wifi_ui = WifiManagerUI(self.wifi_manager) - - def _render(self, rect: rl.Rectangle): - self.wifi_ui.render(rect) - - def shutdown(self): - self.wifi_manager.shutdown() diff --git a/selfdrive/ui/layouts/settings/developer.py b/selfdrive/ui/layouts/settings/developer.py deleted file mode 100644 index ce6e9e4af6..0000000000 --- a/selfdrive/ui/layouts/settings/developer.py +++ /dev/null @@ -1,61 +0,0 @@ -from openpilot.system.ui.lib.list_view import toggle_item -from openpilot.system.ui.lib.scroller import Scroller -from openpilot.system.ui.lib.widget import Widget -from openpilot.common.params import Params -from openpilot.selfdrive.ui.widgets.ssh_key import ssh_key_item - -# Description constants -DESCRIPTIONS = { - 'enable_adb': ( - "ADB (Android Debug Bridge) allows connecting to your device over USB or over the network. " + - "See https://docs.comma.ai/how-to/connect-to-comma for more info." - ), - 'joystick_debug_mode': "Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off)", - 'ssh_key': ( - "Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username " + - "other than your own. A comma employee will NEVER ask you to add their GitHub username." - ), -} - - -class DeveloperLayout(Widget): - def __init__(self): - super().__init__() - self._params = Params() - items = [ - toggle_item( - "Enable ADB", - description=DESCRIPTIONS["enable_adb"], - initial_state=self._params.get_bool("AdbEnabled"), - callback=self._on_enable_adb, - ), - ssh_key_item("SSH Key", description=DESCRIPTIONS["ssh_key"]), - toggle_item( - "Joystick Debug Mode", - description=DESCRIPTIONS["joystick_debug_mode"], - initial_state=self._params.get_bool("JoystickDebugMode"), - callback=self._on_joystick_debug_mode, - ), - toggle_item( - "Longitudinal Maneuver Mode", - description="", - initial_state=self._params.get_bool("LongitudinalManeuverMode"), - callback=self._on_long_maneuver_mode, - ), - toggle_item( - "openpilot Longitudinal Control (Alpha)", - description="", - initial_state=self._params.get_bool("AlphaLongitudinalEnabled"), - callback=self._on_alpha_long_enabled, - ), - ] - - self._scroller = Scroller(items, line_separator=True, spacing=0) - - def _render(self, rect): - self._scroller.render(rect) - - def _on_enable_adb(self): pass - def _on_joystick_debug_mode(self): pass - def _on_long_maneuver_mode(self): pass - def _on_alpha_long_enabled(self): pass diff --git a/selfdrive/ui/layouts/settings/device.py b/selfdrive/ui/layouts/settings/device.py deleted file mode 100644 index 69b7822ba9..0000000000 --- a/selfdrive/ui/layouts/settings/device.py +++ /dev/null @@ -1,150 +0,0 @@ -import os -import json - -from openpilot.common.basedir import BASEDIR -from openpilot.common.params import Params -from openpilot.selfdrive.ui.onroad.driver_camera_dialog import DriverCameraDialog -from openpilot.selfdrive.ui.ui_state import ui_state -from openpilot.system.hardware import TICI -from openpilot.system.ui.lib.application import gui_app -from openpilot.system.ui.lib.list_view import text_item, button_item, dual_button_item -from openpilot.system.ui.lib.scroller import Scroller -from openpilot.system.ui.lib.widget import Widget, DialogResult -from openpilot.selfdrive.ui.widgets.pairing_dialog import PairingDialog -from openpilot.system.ui.widgets.option_dialog import MultiOptionDialog -from openpilot.system.ui.widgets.confirm_dialog import confirm_dialog, alert_dialog -from openpilot.system.ui.widgets.html_render import HtmlRenderer - -# Description constants -DESCRIPTIONS = { - 'pair_device': "Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer.", - 'driver_camera': "Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off)", - 'reset_calibration': ( - "openpilot requires the device to be mounted within 4° left or right and within 5° " + - "up or 9° down. openpilot is continuously calibrating, resetting is rarely required." - ), - 'review_guide': "Review the rules, features, and limitations of openpilot", -} - - -class DeviceLayout(Widget): - def __init__(self): - super().__init__() - - self._params = Params() - self._select_language_dialog: MultiOptionDialog | None = None - self._driver_camera: DriverCameraDialog | None = None - self._pair_device_dialog: PairingDialog | None = None - self._fcc_dialog: HtmlRenderer | None = None - - items = self._initialize_items() - self._scroller = Scroller(items, line_separator=True, spacing=0) - - def _initialize_items(self): - dongle_id = self._params.get("DongleId", encoding="utf-8") or "N/A" - serial = self._params.get("HardwareSerial") or "N/A" - - items = [ - text_item("Dongle ID", dongle_id), - text_item("Serial", serial), - button_item("Pair Device", "PAIR", DESCRIPTIONS['pair_device'], callback=self._pair_device), - button_item("Driver Camera", "PREVIEW", DESCRIPTIONS['driver_camera'], callback=self._show_driver_camera, enabled=ui_state.is_offroad), - button_item("Reset Calibration", "RESET", DESCRIPTIONS['reset_calibration'], callback=self._reset_calibration_prompt), - regulatory_btn := button_item("Regulatory", "VIEW", callback=self._on_regulatory), - button_item("Review Training Guide", "REVIEW", DESCRIPTIONS['review_guide'], self._on_review_training_guide), - button_item("Change Language", "CHANGE", callback=self._show_language_selection, enabled=ui_state.is_offroad), - dual_button_item("Reboot", "Power Off", left_callback=self._reboot_prompt, right_callback=self._power_off_prompt), - ] - regulatory_btn.set_visible(TICI) - return items - - def _render(self, rect): - self._scroller.render(rect) - - def _show_language_selection(self): - try: - languages_file = os.path.join(BASEDIR, "selfdrive/ui/translations/languages.json") - with open(languages_file, encoding='utf-8') as f: - languages = json.load(f) - - self._select_language_dialog = MultiOptionDialog("Select a language", languages) - gui_app.set_modal_overlay(self._select_language_dialog, callback=self._handle_language_selection) - except FileNotFoundError: - pass - - def _handle_language_selection(self, result: int): - if result == 1 and self._select_language_dialog: - selected_language = self._select_language_dialog.selection - self._params.put("LanguageSetting", selected_language) - - self._select_language_dialog = None - - def _show_driver_camera(self): - if not self._driver_camera: - self._driver_camera = DriverCameraDialog() - - gui_app.set_modal_overlay(self._driver_camera, callback=lambda result: setattr(self, '_driver_camera', None)) - - def _reset_calibration_prompt(self): - if ui_state.engaged: - gui_app.set_modal_overlay(lambda: alert_dialog("Disengage to Reset Calibration")) - return - - gui_app.set_modal_overlay( - lambda: confirm_dialog("Are you sure you want to reset calibration?", "Reset"), - callback=self._reset_calibration, - ) - - def _reset_calibration(self, result: int): - if ui_state.engaged or result != DialogResult.CONFIRM: - return - - self._params.remove("CalibrationParams") - self._params.remove("LiveTorqueParameters") - self._params.remove("LiveParameters") - self._params.remove("LiveParametersV2") - self._params.remove("LiveDelay") - self._params.put_bool("OnroadCycleRequested", True) - - def _reboot_prompt(self): - if ui_state.engaged: - gui_app.set_modal_overlay(lambda: alert_dialog("Disengage to Reboot")) - return - - gui_app.set_modal_overlay( - lambda: confirm_dialog("Are you sure you want to reboot?", "Reboot"), - callback=self._perform_reboot, - ) - - def _perform_reboot(self, result: int): - if not ui_state.engaged and result == DialogResult.CONFIRM: - self._params.put_bool_nonblocking("DoReboot", True) - - def _power_off_prompt(self): - if ui_state.engaged: - gui_app.set_modal_overlay(lambda: alert_dialog("Disengage to Power Off")) - return - - gui_app.set_modal_overlay( - lambda: confirm_dialog("Are you sure you want to power off?", "Power Off"), - callback=self._perform_power_off, - ) - - def _perform_power_off(self, result: int): - if not ui_state.engaged and result == DialogResult.CONFIRM: - self._params.put_bool_nonblocking("DoShutdown", True) - - def _pair_device(self): - if not self._pair_device_dialog: - self._pair_device_dialog = PairingDialog() - gui_app.set_modal_overlay(self._pair_device_dialog, callback=lambda result: setattr(self, '_pair_device_dialog', None)) - - def _on_regulatory(self): - if not self._fcc_dialog: - self._fcc_dialog = HtmlRenderer(os.path.join(BASEDIR, "selfdrive/assets/offroad/fcc.html")) - - gui_app.set_modal_overlay(self._fcc_dialog, - callback=lambda result: setattr(self, '_fcc_dialog', None), - ) - - def _on_review_training_guide(self): pass diff --git a/selfdrive/ui/layouts/settings/firehose.py b/selfdrive/ui/layouts/settings/firehose.py deleted file mode 100644 index 298f66e276..0000000000 --- a/selfdrive/ui/layouts/settings/firehose.py +++ /dev/null @@ -1,180 +0,0 @@ -import pyray as rl -import json -import time -import threading - -from openpilot.common.api import Api, api_get -from openpilot.common.params import Params -from openpilot.common.swaglog import cloudlog -from openpilot.system.athena.registration import UNREGISTERED_DONGLE_ID -from openpilot.system.ui.lib.application import gui_app, FontWeight -from openpilot.system.ui.lib.wrap_text import wrap_text -from openpilot.system.ui.lib.scroll_panel import GuiScrollPanel -from openpilot.system.ui.lib.widget import Widget -from openpilot.selfdrive.ui.ui_state import ui_state - - -TITLE = "Firehose Mode" -DESCRIPTION = ( - "openpilot learns to drive by watching humans, like you, drive.\n\n" - + "Firehose Mode allows you to maximize your training data uploads to improve " - + "openpilot's driving models. More data means bigger models, which means better Experimental Mode." -) -INSTRUCTIONS = ( - "For maximum effectiveness, bring your device inside and connect to a good USB-C adapter and Wi-Fi weekly.\n\n" - + "Firehose Mode can also work while you're driving if connected to a hotspot or unlimited SIM card.\n\n" - + "Frequently Asked Questions\n\n" - + "Does it matter how or where I drive? Nope, just drive as you normally would.\n\n" - + "Do all of my segments get pulled in Firehose Mode? No, we selectively pull a subset of your segments.\n\n" - + "What's a good USB-C adapter? Any fast phone or laptop charger should be fine.\n\n" - + "Does it matter which software I run? Yes, only upstream openpilot (and particular forks) are able to be used for training." -) - - -class FirehoseLayout(Widget): - PARAM_KEY = "ApiCache_FirehoseStats" - GREEN = rl.Color(46, 204, 113, 255) - RED = rl.Color(231, 76, 60, 255) - GRAY = rl.Color(68, 68, 68, 255) - LIGHT_GRAY = rl.Color(228, 228, 228, 255) - UPDATE_INTERVAL = 30 # seconds - - def __init__(self): - super().__init__() - self.params = Params() - self.segment_count = self._get_segment_count() - self.scroll_panel = GuiScrollPanel() - - self.running = True - self.update_thread = threading.Thread(target=self._update_loop, daemon=True) - self.update_thread.start() - self.last_update_time = 0 - - def _get_segment_count(self) -> int: - stats = self.params.get(self.PARAM_KEY, encoding='utf8') - if not stats: - return 0 - try: - return int(json.loads(stats).get("firehose", 0)) - except Exception: - cloudlog.exception(f"Failed to decode firehose stats: {stats}") - return 0 - - def __del__(self): - self.running = False - if self.update_thread and self.update_thread.is_alive(): - self.update_thread.join(timeout=1.0) - - def _render(self, rect: rl.Rectangle): - # Calculate content dimensions - content_width = rect.width - 80 - content_height = self._calculate_content_height(int(content_width)) - content_rect = rl.Rectangle(rect.x, rect.y, rect.width, content_height) - - # Handle scrolling and render with clipping - scroll_offset = self.scroll_panel.handle_scroll(rect, content_rect) - rl.begin_scissor_mode(int(rect.x), int(rect.y), int(rect.width), int(rect.height)) - self._render_content(rect, scroll_offset) - rl.end_scissor_mode() - - def _calculate_content_height(self, content_width: int) -> int: - height = 80 # Top margin - - # Title - height += 100 + 40 - - # Description - desc_font = gui_app.font(FontWeight.NORMAL) - desc_lines = wrap_text(desc_font, DESCRIPTION, 45, content_width) - height += len(desc_lines) * 45 + 40 - - # Status section - height += 32 # Separator - status_text, _ = self._get_status() - status_lines = wrap_text(gui_app.font(FontWeight.BOLD), status_text, 60, content_width) - height += len(status_lines) * 60 + 20 - - # Contribution count (if available) - if self.segment_count > 0: - contrib_text = f"{self.segment_count} segment(s) of your driving is in the training dataset so far." - contrib_lines = wrap_text(gui_app.font(FontWeight.BOLD), contrib_text, 52, content_width) - height += len(contrib_lines) * 52 + 20 - - # Instructions section - height += 32 # Separator - inst_lines = wrap_text(gui_app.font(FontWeight.NORMAL), INSTRUCTIONS, 40, content_width) - height += len(inst_lines) * 40 + 40 # Bottom margin - - return height - - def _render_content(self, rect: rl.Rectangle, scroll_offset: rl.Vector2): - x = int(rect.x + 40) - y = int(rect.y + 40 + scroll_offset.y) - w = int(rect.width - 80) - - # Title - title_font = gui_app.font(FontWeight.MEDIUM) - rl.draw_text_ex(title_font, TITLE, rl.Vector2(x, y), 100, 0, rl.WHITE) - y += 140 - - # Description - y = self._draw_wrapped_text(x, y, w, DESCRIPTION, gui_app.font(FontWeight.NORMAL), 45, rl.WHITE) - y += 40 - - # Separator - rl.draw_rectangle(x, y, w, 2, self.GRAY) - y += 30 - - # Status - status_text, status_color = self._get_status() - y = self._draw_wrapped_text(x, y, w, status_text, gui_app.font(FontWeight.BOLD), 60, status_color) - y += 20 - - # Contribution count (if available) - if self.segment_count > 0: - contrib_text = f"{self.segment_count} segment(s) of your driving is in the training dataset so far." - y = self._draw_wrapped_text(x, y, w, contrib_text, gui_app.font(FontWeight.BOLD), 52, rl.WHITE) - y += 20 - - # Separator - rl.draw_rectangle(x, y, w, 2, self.GRAY) - y += 30 - - # Instructions - self._draw_wrapped_text(x, y, w, INSTRUCTIONS, gui_app.font(FontWeight.NORMAL), 40, self.LIGHT_GRAY) - - def _draw_wrapped_text(self, x, y, width, text, font, size, color): - wrapped = wrap_text(font, text, size, width) - for line in wrapped: - rl.draw_text_ex(font, line, rl.Vector2(x, y), size, 0, color) - y += size - return y - - def _get_status(self) -> tuple[str, rl.Color]: - network_type = ui_state.sm["deviceState"].networkType - network_metered = ui_state.sm["deviceState"].networkMetered - - if not network_metered and network_type != 0: # Not metered and connected - return "ACTIVE", self.GREEN - else: - return "INACTIVE: connect to an unmetered network", self.RED - - def _fetch_firehose_stats(self): - try: - dongle_id = self.params.get("DongleId", encoding='utf8') - if not dongle_id or dongle_id == UNREGISTERED_DONGLE_ID: - return - identity_token = Api(dongle_id).get_token() - response = api_get(f"v1/devices/{dongle_id}/firehose_stats", access_token=identity_token) - if response.status_code == 200: - data = response.json() - self.segment_count = data.get("firehose", 0) - self.params.put(self.PARAM_KEY, json.dumps(data)) - except Exception as e: - cloudlog.error(f"Failed to fetch firehose stats: {e}") - - def _update_loop(self): - while self.running: - if not ui_state.started: - self._fetch_firehose_stats() - time.sleep(self.UPDATE_INTERVAL) diff --git a/selfdrive/ui/layouts/settings/settings.py b/selfdrive/ui/layouts/settings/settings.py deleted file mode 100644 index 4a29f408ee..0000000000 --- a/selfdrive/ui/layouts/settings/settings.py +++ /dev/null @@ -1,156 +0,0 @@ -import pyray as rl -from dataclasses import dataclass -from enum import IntEnum -from collections.abc import Callable -from openpilot.selfdrive.ui.layouts.settings.developer import DeveloperLayout -from openpilot.selfdrive.ui.layouts.settings.device import DeviceLayout -from openpilot.selfdrive.ui.layouts.settings.firehose import FirehoseLayout -from openpilot.selfdrive.ui.layouts.settings.software import SoftwareLayout -from openpilot.selfdrive.ui.layouts.settings.toggles import TogglesLayout -from openpilot.system.ui.lib.application import gui_app, FontWeight -from openpilot.system.ui.lib.text_measure import measure_text_cached -from openpilot.selfdrive.ui.layouts.network import NetworkLayout -from openpilot.system.ui.lib.widget import Widget - -# Import individual panels - -SETTINGS_CLOSE_TEXT = "X" -# Constants -SIDEBAR_WIDTH = 500 -CLOSE_BTN_SIZE = 200 -NAV_BTN_HEIGHT = 110 -PANEL_MARGIN = 50 - -# Colors -SIDEBAR_COLOR = rl.BLACK -PANEL_COLOR = rl.Color(41, 41, 41, 255) -CLOSE_BTN_COLOR = rl.Color(41, 41, 41, 255) -CLOSE_BTN_PRESSED = rl.Color(59, 59, 59, 255) -TEXT_NORMAL = rl.Color(128, 128, 128, 255) -TEXT_SELECTED = rl.Color(255, 255, 255, 255) - - -class PanelType(IntEnum): - DEVICE = 0 - NETWORK = 1 - TOGGLES = 2 - SOFTWARE = 3 - FIREHOSE = 4 - DEVELOPER = 5 - - -@dataclass -class PanelInfo: - name: str - instance: object - button_rect: rl.Rectangle = rl.Rectangle(0, 0, 0, 0) - - -class SettingsLayout(Widget): - def __init__(self): - super().__init__() - self._current_panel = PanelType.DEVICE - - # Panel configuration - self._panels = { - PanelType.DEVICE: PanelInfo("Device", DeviceLayout()), - PanelType.NETWORK: PanelInfo("Network", NetworkLayout()), - PanelType.TOGGLES: PanelInfo("Toggles", TogglesLayout()), - PanelType.SOFTWARE: PanelInfo("Software", SoftwareLayout()), - PanelType.FIREHOSE: PanelInfo("Firehose", FirehoseLayout()), - PanelType.DEVELOPER: PanelInfo("Developer", DeveloperLayout()), - } - - self._font_medium = gui_app.font(FontWeight.MEDIUM) - self._font_bold = gui_app.font(FontWeight.SEMI_BOLD) - - # Callbacks - self._close_callback: Callable | None = None - - def set_callbacks(self, on_close: Callable): - self._close_callback = on_close - - def _render(self, rect: rl.Rectangle): - # Calculate layout - sidebar_rect = rl.Rectangle(rect.x, rect.y, SIDEBAR_WIDTH, rect.height) - panel_rect = rl.Rectangle(rect.x + SIDEBAR_WIDTH, rect.y, rect.width - SIDEBAR_WIDTH, rect.height) - - # Draw components - self._draw_sidebar(sidebar_rect) - self._draw_current_panel(panel_rect) - - def _draw_sidebar(self, rect: rl.Rectangle): - rl.draw_rectangle_rec(rect, SIDEBAR_COLOR) - - # Close button - close_btn_rect = rl.Rectangle( - rect.x + (rect.width - CLOSE_BTN_SIZE) / 2, rect.y + 45, CLOSE_BTN_SIZE, CLOSE_BTN_SIZE - ) - - pressed = (rl.is_mouse_button_down(rl.MouseButton.MOUSE_BUTTON_LEFT) and - rl.check_collision_point_rec(rl.get_mouse_position(), close_btn_rect)) - close_color = CLOSE_BTN_PRESSED if pressed else CLOSE_BTN_COLOR - rl.draw_rectangle_rounded(close_btn_rect, 1.0, 20, close_color) - - close_text_size = measure_text_cached(self._font_bold, SETTINGS_CLOSE_TEXT, 140) - close_text_pos = rl.Vector2( - close_btn_rect.x + (close_btn_rect.width - close_text_size.x) / 2, - close_btn_rect.y + (close_btn_rect.height - close_text_size.y) / 2, - ) - rl.draw_text_ex(self._font_bold, SETTINGS_CLOSE_TEXT, close_text_pos, 140, 0, TEXT_SELECTED) - - # Store close button rect for click detection - self._close_btn_rect = close_btn_rect - - # Navigation buttons - y = rect.y + 300 - for panel_type, panel_info in self._panels.items(): - button_rect = rl.Rectangle(rect.x + 50, y, rect.width - 150, NAV_BTN_HEIGHT) - - # Button styling - is_selected = panel_type == self._current_panel - text_color = TEXT_SELECTED if is_selected else TEXT_NORMAL - # Draw button text (right-aligned) - text_size = measure_text_cached(self._font_medium, panel_info.name, 65) - text_pos = rl.Vector2( - button_rect.x + button_rect.width - text_size.x, button_rect.y + (button_rect.height - text_size.y) / 2 - ) - rl.draw_text_ex(self._font_medium, panel_info.name, text_pos, 65, 0, text_color) - - # Store button rect for click detection - panel_info.button_rect = button_rect - - y += NAV_BTN_HEIGHT - - def _draw_current_panel(self, rect: rl.Rectangle): - rl.draw_rectangle_rounded( - rl.Rectangle(rect.x + 10, rect.y + 10, rect.width - 20, rect.height - 20), 0.04, 30, PANEL_COLOR - ) - content_rect = rl.Rectangle(rect.x + PANEL_MARGIN, rect.y + 25, rect.width - (PANEL_MARGIN * 2), rect.height - 50) - # rl.draw_rectangle_rounded(content_rect, 0.03, 30, PANEL_COLOR) - panel = self._panels[self._current_panel] - if panel.instance: - panel.instance.render(content_rect) - - def _handle_mouse_release(self, mouse_pos: rl.Vector2) -> bool: - # Check close button - if rl.check_collision_point_rec(mouse_pos, self._close_btn_rect): - if self._close_callback: - self._close_callback() - return True - - # Check navigation buttons - for panel_type, panel_info in self._panels.items(): - if rl.check_collision_point_rec(mouse_pos, panel_info.button_rect): - self.set_current_panel(panel_type) - return True - - return False - - def set_current_panel(self, panel_type: PanelType): - if panel_type != self._current_panel: - self._current_panel = panel_type - - def close_settings(self): - if self._close_callback: - self._close_callback() diff --git a/selfdrive/ui/layouts/settings/software.py b/selfdrive/ui/layouts/settings/software.py deleted file mode 100644 index b97e306ff9..0000000000 --- a/selfdrive/ui/layouts/settings/software.py +++ /dev/null @@ -1,42 +0,0 @@ -from openpilot.common.params import Params -from openpilot.system.ui.lib.application import gui_app -from openpilot.system.ui.lib.list_view import button_item, text_item -from openpilot.system.ui.lib.scroller import Scroller -from openpilot.system.ui.lib.widget import Widget, DialogResult -from openpilot.system.ui.widgets.confirm_dialog import confirm_dialog - - -class SoftwareLayout(Widget): - def __init__(self): - super().__init__() - - self._params = Params() - items = self._init_items() - self._scroller = Scroller(items, line_separator=True, spacing=0) - - def _init_items(self): - items = [ - text_item("Current Version", ""), - button_item("Download", "CHECK", callback=self._on_download_update), - button_item("Install Update", "INSTALL", callback=self._on_install_update), - button_item("Target Branch", "SELECT", callback=self._on_select_branch), - button_item("Uninstall", "UNINSTALL", callback=self._on_uninstall), - ] - return items - - def _render(self, rect): - self._scroller.render(rect) - - def _on_download_update(self): pass - def _on_install_update(self): pass - def _on_select_branch(self): pass - - def _on_uninstall(self): - def handle_uninstall_confirmation(result): - if result == DialogResult.CONFIRM: - self._params.put_bool("DoUninstall", True) - - gui_app.set_modal_overlay( - lambda: confirm_dialog("Are you sure you want to uninstall?", "Uninstall"), - callback=handle_uninstall_confirmation, - ) diff --git a/selfdrive/ui/layouts/settings/toggles.py b/selfdrive/ui/layouts/settings/toggles.py deleted file mode 100644 index 5c17082769..0000000000 --- a/selfdrive/ui/layouts/settings/toggles.py +++ /dev/null @@ -1,88 +0,0 @@ -from openpilot.system.ui.lib.list_view import multiple_button_item, toggle_item -from openpilot.system.ui.lib.scroller import Scroller -from openpilot.system.ui.lib.widget import Widget -from openpilot.common.params import Params - -# Description constants -DESCRIPTIONS = { - "OpenpilotEnabledToggle": ( - "Use the openpilot system for adaptive cruise control and lane keep driver assistance. " + - "Your attention is required at all times to use this feature." - ), - "DisengageOnAccelerator": "When enabled, pressing the accelerator pedal will disengage openpilot.", - "LongitudinalPersonality": ( - "Standard is recommended. In aggressive mode, openpilot will follow lead cars closer and be more aggressive with the gas and brake. " + - "In relaxed mode openpilot will stay further away from lead cars. On supported cars, you can cycle through these personalities with " + - "your steering wheel distance button." - ), - "IsLdwEnabled": ( - "Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line " + - "without a turn signal activated while driving over 31 mph (50 km/h)." - ), - "AlwaysOnDM": "Enable driver monitoring even when openpilot is not engaged.", - 'RecordFront': "Upload data from the driver facing camera and help improve the driver monitoring algorithm.", - "IsMetric": "Display speed in km/h instead of mph.", -} - - -class TogglesLayout(Widget): - def __init__(self): - super().__init__() - self._params = Params() - items = [ - toggle_item( - "Enable openpilot", - DESCRIPTIONS["OpenpilotEnabledToggle"], - self._params.get_bool("OpenpilotEnabledToggle"), - icon="chffr_wheel.png", - ), - toggle_item( - "Experimental Mode", - initial_state=self._params.get_bool("ExperimentalMode"), - icon="experimental_white.png", - ), - toggle_item( - "Disengage on Accelerator Pedal", - DESCRIPTIONS["DisengageOnAccelerator"], - self._params.get_bool("DisengageOnAccelerator"), - icon="disengage_on_accelerator.png", - ), - multiple_button_item( - "Driving Personality", - DESCRIPTIONS["LongitudinalPersonality"], - buttons=["Aggressive", "Standard", "Relaxed"], - button_width=255, - callback=self._set_longitudinal_personality, - selected_index=int(self._params.get("LongitudinalPersonality") or 0), - icon="speed_limit.png" - ), - toggle_item( - "Enable Lane Departure Warnings", - DESCRIPTIONS["IsLdwEnabled"], - self._params.get_bool("IsLdwEnabled"), - icon="warning.png", - ), - toggle_item( - "Always-On Driver Monitoring", - DESCRIPTIONS["AlwaysOnDM"], - self._params.get_bool("AlwaysOnDM"), - icon="monitoring.png", - ), - toggle_item( - "Record and Upload Driver Camera", - DESCRIPTIONS["RecordFront"], - self._params.get_bool("RecordFront"), - icon="monitoring.png", - ), - toggle_item( - "Use Metric System", DESCRIPTIONS["IsMetric"], self._params.get_bool("IsMetric"), icon="monitoring.png" - ), - ] - - self._scroller = Scroller(items, line_separator=True, spacing=0) - - def _render(self, rect): - self._scroller.render(rect) - - def _set_longitudinal_personality(self, button_index: int): - self._params.put("LongitudinalPersonality", str(button_index)) diff --git a/selfdrive/ui/layouts/sidebar.py b/selfdrive/ui/layouts/sidebar.py deleted file mode 100644 index 13f69b79d4..0000000000 --- a/selfdrive/ui/layouts/sidebar.py +++ /dev/null @@ -1,204 +0,0 @@ -import pyray as rl -import time -from dataclasses import dataclass -from collections.abc import Callable -from cereal import log -from openpilot.selfdrive.ui.ui_state import ui_state -from openpilot.system.ui.lib.application import gui_app, FontWeight -from openpilot.system.ui.lib.text_measure import measure_text_cached -from openpilot.system.ui.lib.widget import Widget - -SIDEBAR_WIDTH = 300 -METRIC_HEIGHT = 126 -METRIC_WIDTH = 240 -METRIC_MARGIN = 30 - -SETTINGS_BTN = rl.Rectangle(50, 35, 200, 117) -HOME_BTN = rl.Rectangle(60, 860, 180, 180) - -ThermalStatus = log.DeviceState.ThermalStatus -NetworkType = log.DeviceState.NetworkType - - -# Color scheme -class Colors: - SIDEBAR_BG = rl.Color(57, 57, 57, 255) - WHITE = rl.Color(255, 255, 255, 255) - WHITE_DIM = rl.Color(255, 255, 255, 85) - GRAY = rl.Color(84, 84, 84, 255) - - # Status colors - GOOD = rl.Color(255, 255, 255, 255) - WARNING = rl.Color(218, 202, 37, 255) - DANGER = rl.Color(201, 34, 49, 255) - - # UI elements - METRIC_BORDER = rl.Color(255, 255, 255, 85) - BUTTON_NORMAL = rl.Color(255, 255, 255, 255) - BUTTON_PRESSED = rl.Color(255, 255, 255, 166) - - -NETWORK_TYPES = { - NetworkType.none: "Offline", - NetworkType.wifi: "WiFi", - NetworkType.cell2G: "2G", - NetworkType.cell3G: "3G", - NetworkType.cell4G: "LTE", - NetworkType.cell5G: "5G", - NetworkType.ethernet: "Ethernet", -} - - -@dataclass(slots=True) -class MetricData: - label: str - value: str - color: rl.Color - - def update(self, label: str, value: str, color: rl.Color): - self.label = label - self.value = value - self.color = color - - -class Sidebar(Widget): - def __init__(self): - super().__init__() - self._net_type = NETWORK_TYPES.get(NetworkType.none) - self._net_strength = 0 - - self._temp_status = MetricData("TEMP", "GOOD", Colors.GOOD) - self._panda_status = MetricData("VEHICLE", "ONLINE", Colors.GOOD) - self._connect_status = MetricData("CONNECT", "OFFLINE", Colors.WARNING) - - self._home_img = gui_app.texture("images/button_home.png", HOME_BTN.width, HOME_BTN.height) - self._flag_img = gui_app.texture("images/button_flag.png", HOME_BTN.width, HOME_BTN.height) - self._settings_img = gui_app.texture("images/button_settings.png", SETTINGS_BTN.width, SETTINGS_BTN.height) - self._font_regular = gui_app.font(FontWeight.NORMAL) - self._font_bold = gui_app.font(FontWeight.SEMI_BOLD) - - # Callbacks - self._on_settings_click: Callable | None = None - self._on_flag_click: Callable | None = None - - def set_callbacks(self, on_settings: Callable | None = None, on_flag: Callable | None = None): - self._on_settings_click = on_settings - self._on_flag_click = on_flag - - def _render(self, rect: rl.Rectangle): - # Background - rl.draw_rectangle_rec(rect, Colors.SIDEBAR_BG) - - self._draw_buttons(rect) - self._draw_network_indicator(rect) - self._draw_metrics(rect) - - def _update_state(self): - sm = ui_state.sm - if not sm.updated['deviceState']: - return - - device_state = sm['deviceState'] - - self._update_network_status(device_state) - self._update_temperature_status(device_state) - self._update_connection_status(device_state) - self._update_panda_status() - - def _update_network_status(self, device_state): - self._net_type = NETWORK_TYPES.get(device_state.networkType.raw, "Unknown") - strength = device_state.networkStrength - self._net_strength = max(0, min(5, strength.raw + 1)) if strength > 0 else 0 - - def _update_temperature_status(self, device_state): - thermal_status = device_state.thermalStatus - - if thermal_status == ThermalStatus.green: - self._temp_status.update("TEMP", "GOOD", Colors.GOOD) - elif thermal_status == ThermalStatus.yellow: - self._temp_status.update("TEMP", "OK", Colors.WARNING) - else: - self._temp_status.update("TEMP", "HIGH", Colors.DANGER) - - def _update_connection_status(self, device_state): - last_ping = device_state.lastAthenaPingTime - if last_ping == 0: - self._connect_status.update("CONNECT", "OFFLINE", Colors.WARNING) - elif time.monotonic_ns() - last_ping < 80_000_000_000: # 80 seconds in nanoseconds - self._connect_status.update("CONNECT", "ONLINE", Colors.GOOD) - else: - self._connect_status.update("CONNECT", "ERROR", Colors.DANGER) - - def _update_panda_status(self): - if ui_state.panda_type == log.PandaState.PandaType.unknown: - self._panda_status.update("NO", "PANDA", Colors.DANGER) - else: - self._panda_status.update("VEHICLE", "ONLINE", Colors.GOOD) - - def _handle_mouse_release(self, mouse_pos: rl.Vector2): - if rl.check_collision_point_rec(mouse_pos, SETTINGS_BTN): - if self._on_settings_click: - self._on_settings_click() - elif rl.check_collision_point_rec(mouse_pos, HOME_BTN) and ui_state.started: - if self._on_flag_click: - self._on_flag_click() - - def _draw_buttons(self, rect: rl.Rectangle): - mouse_pos = rl.get_mouse_position() - mouse_down = self._is_pressed and rl.is_mouse_button_down(rl.MouseButton.MOUSE_BUTTON_LEFT) - - # Settings button - settings_down = mouse_down and rl.check_collision_point_rec(mouse_pos, SETTINGS_BTN) - tint = Colors.BUTTON_PRESSED if settings_down else Colors.BUTTON_NORMAL - rl.draw_texture(self._settings_img, int(SETTINGS_BTN.x), int(SETTINGS_BTN.y), tint) - - # Home/Flag button - flag_pressed = mouse_down and rl.check_collision_point_rec(mouse_pos, HOME_BTN) - button_img = self._flag_img if ui_state.started else self._home_img - - tint = Colors.BUTTON_PRESSED if (ui_state.started and flag_pressed) else Colors.BUTTON_NORMAL - rl.draw_texture(button_img, int(HOME_BTN.x), int(HOME_BTN.y), tint) - - def _draw_network_indicator(self, rect: rl.Rectangle): - # Signal strength dots - x_start = rect.x + 58 - y_pos = rect.y + 196 - dot_size = 27 - dot_spacing = 37 - - for i in range(5): - color = Colors.WHITE if i < self._net_strength else Colors.GRAY - x = int(x_start + i * dot_spacing + dot_size // 2) - y = int(y_pos + dot_size // 2) - rl.draw_circle(x, y, dot_size // 2, color) - - # Network type text - text_y = rect.y + 247 - text_pos = rl.Vector2(rect.x + 58, text_y) - rl.draw_text_ex(self._font_regular, self._net_type, text_pos, 35, 0, Colors.WHITE) - - def _draw_metrics(self, rect: rl.Rectangle): - metrics = [(self._temp_status, 338), (self._panda_status, 496), (self._connect_status, 654)] - - for metric, y_offset in metrics: - self._draw_metric(rect, metric, rect.y + y_offset) - - def _draw_metric(self, rect: rl.Rectangle, metric: MetricData, y: float): - metric_rect = rl.Rectangle(rect.x + METRIC_MARGIN, y, METRIC_WIDTH, METRIC_HEIGHT) - # Draw colored left edge (clipped rounded rectangle) - edge_rect = rl.Rectangle(metric_rect.x + 4, metric_rect.y + 4, 100, 118) - rl.begin_scissor_mode(int(metric_rect.x + 4), int(metric_rect.y), 18, int(metric_rect.height)) - rl.draw_rectangle_rounded(edge_rect, 0.18, 10, metric.color) - rl.end_scissor_mode() - - # Draw border - rl.draw_rectangle_rounded_lines_ex(metric_rect, 0.15, 10, 2, Colors.METRIC_BORDER) - - # Draw text - text = f"{metric.label}\n{metric.value}" - text_size = measure_text_cached(self._font_bold, text, 35) - text_pos = rl.Vector2( - metric_rect.x + 22 + (metric_rect.width - 22 - text_size.x) / 2, - metric_rect.y + (metric_rect.height - text_size.y) / 2 - ) - rl.draw_text_ex(self._font_bold, text, text_pos, 35, 0, Colors.WHITE) diff --git a/selfdrive/ui/lib/prime_state.py b/selfdrive/ui/lib/prime_state.py deleted file mode 100644 index 6b87540f65..0000000000 --- a/selfdrive/ui/lib/prime_state.py +++ /dev/null @@ -1,99 +0,0 @@ -from enum import IntEnum -import os -import threading -import time - -from openpilot.common.api import Api, api_get -from openpilot.common.params import Params -from openpilot.common.swaglog import cloudlog -from openpilot.system.athena.registration import UNREGISTERED_DONGLE_ID - - -class PrimeType(IntEnum): - UNKNOWN = -2, - UNPAIRED = -1, - NONE = 0, - MAGENTA = 1, - LITE = 2, - BLUE = 3, - MAGENTA_NEW = 4, - PURPLE = 5, - - -class PrimeState: - FETCH_INTERVAL = 5.0 # seconds between API calls - API_TIMEOUT = 10.0 # seconds for API requests - SLEEP_INTERVAL = 0.5 # seconds to sleep between checks in the worker thread - - def __init__(self): - self._params = Params() - self._lock = threading.Lock() - self.prime_type: PrimeType = self._load_initial_state() - - self._running = False - self._thread = None - self.start() - - def _load_initial_state(self) -> PrimeType: - prime_type_str = os.getenv("PRIME_TYPE") or self._params.get("PrimeType", encoding='utf8') - try: - if prime_type_str is not None: - return PrimeType(int(prime_type_str)) - except (ValueError, TypeError): - pass - return PrimeType.UNKNOWN - - def _fetch_prime_status(self) -> None: - dongle_id = self._params.get("DongleId", encoding='utf8') - if not dongle_id or dongle_id == UNREGISTERED_DONGLE_ID: - return - - try: - identity_token = Api(dongle_id).get_token() - response = api_get(f"v1.1/devices/{dongle_id}", timeout=self.API_TIMEOUT, access_token=identity_token) - if response.status_code == 200: - data = response.json() - is_paired = data.get("is_paired", False) - prime_type = data.get("prime_type", 0) - self.set_type(PrimeType(prime_type) if is_paired else PrimeType.UNPAIRED) - except Exception as e: - cloudlog.error(f"Failed to fetch prime status: {e}") - - def set_type(self, prime_type: PrimeType) -> None: - with self._lock: - if prime_type != self.prime_type: - self.prime_type = prime_type - self._params.put("PrimeType", str(int(prime_type))) - cloudlog.info(f"Prime type updated to {prime_type}") - - def _worker_thread(self) -> None: - while self._running: - self._fetch_prime_status() - - for _ in range(int(self.FETCH_INTERVAL / self.SLEEP_INTERVAL)): - if not self._running: - break - time.sleep(self.SLEEP_INTERVAL) - - def start(self) -> None: - if self._thread and self._thread.is_alive(): - return - self._running = True - self._thread = threading.Thread(target=self._worker_thread, daemon=True) - self._thread.start() - - def stop(self) -> None: - self._running = False - if self._thread and self._thread.is_alive(): - self._thread.join(timeout=1.0) - - def get_type(self) -> PrimeType: - with self._lock: - return self.prime_type - - def is_prime(self) -> bool: - with self._lock: - return bool(self.prime_type > PrimeType.NONE) - - def __del__(self): - self.stop() diff --git a/selfdrive/ui/main.cc b/selfdrive/ui/main.cc deleted file mode 100644 index db96817f1a..0000000000 --- a/selfdrive/ui/main.cc +++ /dev/null @@ -1,36 +0,0 @@ -#include - -#include -#include - -#include "system/hardware/hw.h" -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/qt/window.h" - -#ifdef SUNNYPILOT -#include "selfdrive/ui/sunnypilot/qt/window.h" -#define MainWindow MainWindowSP -#else -#include "selfdrive/ui/qt/qt_window.h" -#endif - -int main(int argc, char *argv[]) { - setpriority(PRIO_PROCESS, 0, -20); - - qInstallMessageHandler(swagLogMessageHandler); - initApp(argc, argv); - - QTranslator translator; - QString translation_file = QString::fromStdString(Params().get("LanguageSetting")); - if (!translator.load(QString(":/%1").arg(translation_file)) && translation_file.length()) { - qCritical() << "Failed to load translation file:" << translation_file; - } - - QApplication a(argc, argv); - a.installTranslator(&translator); - - MainWindow w; - setMainWindow(&w); - a.installEventFilter(&w); - return a.exec(); -} diff --git a/selfdrive/ui/onroad/alert_renderer.py b/selfdrive/ui/onroad/alert_renderer.py deleted file mode 100644 index 7a17291bbe..0000000000 --- a/selfdrive/ui/onroad/alert_renderer.py +++ /dev/null @@ -1,162 +0,0 @@ -import time -import pyray as rl -from dataclasses import dataclass -from cereal import messaging, log -from openpilot.system.hardware import TICI -from openpilot.system.ui.lib.application import gui_app, FontWeight, DEFAULT_FPS -from openpilot.system.ui.lib.label import gui_text_box -from openpilot.system.ui.lib.text_measure import measure_text_cached -from openpilot.system.ui.lib.widget import Widget -from openpilot.selfdrive.ui.ui_state import ui_state - -ALERT_MARGIN = 40 -ALERT_PADDING = 60 -ALERT_LINE_SPACING = 45 -ALERT_BORDER_RADIUS = 30 - -ALERT_FONT_SMALL = 66 -ALERT_FONT_MEDIUM = 74 -ALERT_FONT_BIG = 88 - -SELFDRIVE_STATE_TIMEOUT = 5 # Seconds -SELFDRIVE_UNRESPONSIVE_TIMEOUT = 10 # Seconds - -# Constants -ALERT_COLORS = { - log.SelfdriveState.AlertStatus.normal: rl.Color(0, 0, 0, 235), # Black - log.SelfdriveState.AlertStatus.userPrompt: rl.Color(0xFE, 0x8C, 0x34, 235), # Orange - log.SelfdriveState.AlertStatus.critical: rl.Color(0xC9, 0x22, 0x31, 235), # Red -} - - -@dataclass -class Alert: - text1: str = "" - text2: str = "" - size: int = 0 - status: int = 0 - - -# Pre-defined alert instances -ALERT_STARTUP_PENDING = Alert( - text1="openpilot Unavailable", - text2="Waiting to start", - size=log.SelfdriveState.AlertSize.mid, - status=log.SelfdriveState.AlertStatus.normal, -) - -ALERT_CRITICAL_TIMEOUT = Alert( - text1="TAKE CONTROL IMMEDIATELY", - text2="System Unresponsive", - size=log.SelfdriveState.AlertSize.full, - status=log.SelfdriveState.AlertStatus.critical, -) - -ALERT_CRITICAL_REBOOT = Alert( - text1="System Unresponsive", - text2="Reboot Device", - size=log.SelfdriveState.AlertSize.full, - status=log.SelfdriveState.AlertStatus.critical, -) - - -class AlertRenderer(Widget): - def __init__(self): - super().__init__() - self.font_regular: rl.Font = gui_app.font(FontWeight.NORMAL) - self.font_bold: rl.Font = gui_app.font(FontWeight.BOLD) - - def get_alert(self, sm: messaging.SubMaster) -> Alert | None: - """Generate the current alert based on selfdrive state.""" - ss = sm['selfdriveState'] - - # Check if selfdriveState messages have stopped arriving - if not sm.updated['selfdriveState']: - recv_frame = sm.recv_frame['selfdriveState'] - time_since_onroad = (sm.frame - ui_state.started_frame) / DEFAULT_FPS - - # 1. Never received selfdriveState since going onroad - waiting_for_startup = recv_frame < ui_state.started_frame - if waiting_for_startup and time_since_onroad > 5: - return ALERT_STARTUP_PENDING - - # 2. Lost communication with selfdriveState after receiving it - if TICI and not waiting_for_startup: - ss_missing = time.monotonic() - sm.recv_time['selfdriveState'] - if ss_missing > SELFDRIVE_STATE_TIMEOUT: - if ss.enabled and (ss_missing - SELFDRIVE_STATE_TIMEOUT) < SELFDRIVE_UNRESPONSIVE_TIMEOUT: - return ALERT_CRITICAL_TIMEOUT - return ALERT_CRITICAL_REBOOT - - # No alert if size is none - if ss.alertSize == 0: - return None - - # Return current alert - return Alert(text1=ss.alertText1, text2=ss.alertText2, size=ss.alertSize, status=ss.alertStatus) - - def _render(self, rect: rl.Rectangle) -> bool: - alert = self.get_alert(ui_state.sm) - if not alert: - return False - - alert_rect = self._get_alert_rect(rect, alert.size) - self._draw_background(alert_rect, alert) - - text_rect = rl.Rectangle( - alert_rect.x + ALERT_PADDING, - alert_rect.y + ALERT_PADDING, - alert_rect.width - 2 * ALERT_PADDING, - alert_rect.height - 2 * ALERT_PADDING - ) - self._draw_text(text_rect, alert) - return True - - def _get_alert_rect(self, rect: rl.Rectangle, size: int) -> rl.Rectangle: - if size == log.SelfdriveState.AlertSize.full: - return rect - - height = (ALERT_FONT_MEDIUM + 2 * ALERT_PADDING if size == log.SelfdriveState.AlertSize.small else - ALERT_FONT_BIG + ALERT_LINE_SPACING + ALERT_FONT_SMALL + 2 * ALERT_PADDING) - - return rl.Rectangle( - rect.x + ALERT_MARGIN, - rect.y + rect.height - ALERT_MARGIN - height, - rect.width - 2 * ALERT_MARGIN, - height - ) - - def _draw_background(self, rect: rl.Rectangle, alert: Alert) -> None: - color = ALERT_COLORS.get(alert.status, ALERT_COLORS[log.SelfdriveState.AlertStatus.normal]) - - if alert.size != log.SelfdriveState.AlertSize.full: - roundness = ALERT_BORDER_RADIUS / (min(rect.width, rect.height) / 2) - rl.draw_rectangle_rounded(rect, roundness, 10, color) - else: - rl.draw_rectangle_rec(rect, color) - - def _draw_text(self, rect: rl.Rectangle, alert: Alert) -> None: - if alert.size == log.SelfdriveState.AlertSize.small: - self._draw_centered(alert.text1, rect, self.font_bold, ALERT_FONT_MEDIUM) - - elif alert.size == log.SelfdriveState.AlertSize.mid: - self._draw_centered(alert.text1, rect, self.font_bold, ALERT_FONT_BIG, center_y=False) - rect.y += ALERT_FONT_BIG + ALERT_LINE_SPACING - self._draw_centered(alert.text2, rect, self.font_regular, ALERT_FONT_SMALL, center_y=False) - - else: - is_long = len(alert.text1) > 15 - font_size1 = 132 if is_long else 177 - align_ment = rl.GuiTextAlignment.TEXT_ALIGN_CENTER - vertical_align = rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE - text_rect = rl.Rectangle(rect.x, rect.y, rect.width, rect.height // 2) - - gui_text_box(text_rect, alert.text1, font_size1, alignment=align_ment, alignment_vertical=vertical_align, font_weight=FontWeight.BOLD) - text_rect.y = rect.y + rect.height // 2 - gui_text_box(text_rect, alert.text2, ALERT_FONT_BIG, alignment=align_ment) - - def _draw_centered(self, text, rect, font, font_size, center_y=True, color=rl.WHITE) -> None: - text_size = measure_text_cached(font, text, font_size) - x = rect.x + (rect.width - text_size.x) / 2 - y = rect.y + ((rect.height - text_size.y) / 2 if center_y else 0) - rl.draw_text_ex(font, text, rl.Vector2(x, y), font_size, 0, color) diff --git a/selfdrive/ui/onroad/augmented_road_view.py b/selfdrive/ui/onroad/augmented_road_view.py deleted file mode 100644 index dbc1919221..0000000000 --- a/selfdrive/ui/onroad/augmented_road_view.py +++ /dev/null @@ -1,227 +0,0 @@ -import numpy as np -import pyray as rl -from collections.abc import Callable -from cereal import log -from msgq.visionipc import VisionStreamType -from openpilot.selfdrive.ui.ui_state import ui_state, UIStatus, UI_BORDER_SIZE -from openpilot.selfdrive.ui.onroad.alert_renderer import AlertRenderer -from openpilot.selfdrive.ui.onroad.driver_state import DriverStateRenderer -from openpilot.selfdrive.ui.onroad.hud_renderer import HudRenderer -from openpilot.selfdrive.ui.onroad.model_renderer import ModelRenderer -from openpilot.selfdrive.ui.onroad.cameraview import CameraView -from openpilot.system.ui.lib.application import gui_app -from openpilot.common.transformations.camera import DEVICE_CAMERAS, DeviceCameraConfig, view_frame_from_device_frame -from openpilot.common.transformations.orientation import rot_from_euler - -OpState = log.SelfdriveState.OpenpilotState -CALIBRATED = log.LiveCalibrationData.Status.calibrated -ROAD_CAM = VisionStreamType.VISION_STREAM_ROAD -WIDE_CAM = VisionStreamType.VISION_STREAM_WIDE_ROAD -DEFAULT_DEVICE_CAMERA = DEVICE_CAMERAS["tici", "ar0231"] - -BORDER_COLORS = { - UIStatus.DISENGAGED: rl.Color(0x17, 0x33, 0x49, 0xC8), # Blue for disengaged state - UIStatus.OVERRIDE: rl.Color(0x91, 0x9B, 0x95, 0xF1), # Gray for override state - UIStatus.ENGAGED: rl.Color(0x17, 0x86, 0x44, 0xF1), # Green for engaged state -} - -WIDE_CAM_MAX_SPEED = 10.0 # m/s (22 mph) -ROAD_CAM_MIN_SPEED = 15.0 # m/s (34 mph) - - -class AugmentedRoadView(CameraView): - def __init__(self, stream_type: VisionStreamType = VisionStreamType.VISION_STREAM_ROAD): - super().__init__("camerad", stream_type) - self._set_placeholder_color(BORDER_COLORS[UIStatus.DISENGAGED]) - - self.device_camera: DeviceCameraConfig | None = None - self.view_from_calib = view_frame_from_device_frame.copy() - self.view_from_wide_calib = view_frame_from_device_frame.copy() - - self._last_calib_time: float = 0 - self._last_rect_dims = (0.0, 0.0) - self._last_stream_type = stream_type - self._cached_matrix: np.ndarray | None = None - self._content_rect = rl.Rectangle() - - self.model_renderer = ModelRenderer() - self._hud_renderer = HudRenderer() - self.alert_renderer = AlertRenderer() - self.driver_state_renderer = DriverStateRenderer() - - # Callbacks - self._click_callback: Callable | None = None - - def set_callbacks(self, on_click: Callable | None = None): - self._click_callback = on_click - - def _render(self, rect): - # Only render when system is started to avoid invalid data access - if not ui_state.started: - return - - self._switch_stream_if_needed(ui_state.sm) - - # Update calibration before rendering - self._update_calibration() - - # Create inner content area with border padding - self._content_rect = rl.Rectangle( - rect.x + UI_BORDER_SIZE, - rect.y + UI_BORDER_SIZE, - rect.width - 2 * UI_BORDER_SIZE, - rect.height - 2 * UI_BORDER_SIZE, - ) - - # Draw colored border based on driving state - self._draw_border(rect) - - # Enable scissor mode to clip all rendering within content rectangle boundaries - # This creates a rendering viewport that prevents graphics from drawing outside the border - rl.begin_scissor_mode( - int(self._content_rect.x), - int(self._content_rect.y), - int(self._content_rect.width), - int(self._content_rect.height) - ) - - # Render the base camera view - super()._render(rect) - - # Draw all UI overlays - self.model_renderer.render(self._content_rect) - self._hud_renderer.render(self._content_rect) - if not self.alert_renderer.render(self._content_rect): - self.driver_state_renderer.render(self._content_rect) - - # Custom UI extension point - add custom overlays here - # Use self._content_rect for positioning within camera bounds - - # End clipping region - rl.end_scissor_mode() - - # Handle click events if no HUD interaction occurred - if not self._hud_renderer.handle_mouse_event(): - if self._click_callback and rl.is_mouse_button_pressed(rl.MouseButton.MOUSE_BUTTON_LEFT): - if rl.check_collision_point_rec(rl.get_mouse_position(), self._content_rect): - self._click_callback() - - def _draw_border(self, rect: rl.Rectangle): - border_color = BORDER_COLORS.get(ui_state.status, BORDER_COLORS[UIStatus.DISENGAGED]) - rl.draw_rectangle_lines_ex(rect, UI_BORDER_SIZE, border_color) - - def _switch_stream_if_needed(self, sm): - if sm['selfdriveState'].experimentalMode and WIDE_CAM in self.available_streams: - v_ego = sm['carState'].vEgo - if v_ego < WIDE_CAM_MAX_SPEED: - target = WIDE_CAM - elif v_ego > ROAD_CAM_MIN_SPEED: - target = ROAD_CAM - else: - # Hysteresis zone - keep current stream - target = self.stream_type - else: - target = ROAD_CAM - - if self.stream_type != target: - self.switch_stream(target) - - def _update_calibration(self): - # Update device camera if not already set - sm = ui_state.sm - if not self.device_camera and sm.seen['roadCameraState'] and sm.seen['deviceState']: - self.device_camera = DEVICE_CAMERAS[(str(sm['deviceState'].deviceType), str(sm['roadCameraState'].sensor))] - - # Check if live calibration data is available and valid - if not (sm.updated["liveCalibration"] and sm.valid['liveCalibration']): - return - - calib = sm['liveCalibration'] - if len(calib.rpyCalib) != 3 or calib.calStatus != CALIBRATED: - return - - # Update view_from_calib matrix - device_from_calib = rot_from_euler(calib.rpyCalib) - self.view_from_calib = view_frame_from_device_frame @ device_from_calib - - # Update wide calibration if available - if hasattr(calib, 'wideFromDeviceEuler') and len(calib.wideFromDeviceEuler) == 3: - wide_from_device = rot_from_euler(calib.wideFromDeviceEuler) - self.view_from_wide_calib = view_frame_from_device_frame @ wide_from_device @ device_from_calib - - def _calc_frame_matrix(self, rect: rl.Rectangle) -> np.ndarray: - # Check if we can use cached matrix - calib_time = ui_state.sm.recv_frame['liveCalibration'] - current_dims = (self._content_rect.width, self._content_rect.height) - if (self._last_calib_time == calib_time and - self._last_rect_dims == current_dims and - self._last_stream_type == self.stream_type and - self._cached_matrix is not None): - return self._cached_matrix - - # Get camera configuration - device_camera = self.device_camera or DEFAULT_DEVICE_CAMERA - is_wide_camera = self.stream_type == WIDE_CAM - intrinsic = device_camera.ecam.intrinsics if is_wide_camera else device_camera.fcam.intrinsics - calibration = self.view_from_wide_calib if is_wide_camera else self.view_from_calib - zoom = 2.0 if is_wide_camera else 1.1 - - # Calculate transforms for vanishing point - inf_point = np.array([1000.0, 0.0, 0.0]) - calib_transform = intrinsic @ calibration - kep = calib_transform @ inf_point - - # Calculate center points and dimensions - x, y = self._content_rect.x, self._content_rect.y - w, h = self._content_rect.width, self._content_rect.height - cx, cy = intrinsic[0, 2], intrinsic[1, 2] - - # Calculate max allowed offsets with margins - margin = 5 - max_x_offset = cx * zoom - w / 2 - margin - max_y_offset = cy * zoom - h / 2 - margin - - # Calculate and clamp offsets to prevent out-of-bounds issues - try: - if abs(kep[2]) > 1e-6: - x_offset = np.clip((kep[0] / kep[2] - cx) * zoom, -max_x_offset, max_x_offset) - y_offset = np.clip((kep[1] / kep[2] - cy) * zoom, -max_y_offset, max_y_offset) - else: - x_offset, y_offset = 0, 0 - except (ZeroDivisionError, OverflowError): - x_offset, y_offset = 0, 0 - - # Cache the computed transformation matrix to avoid recalculations - self._last_calib_time = calib_time - self._last_rect_dims = current_dims - self._last_stream_type = self.stream_type - self._cached_matrix = np.array([ - [zoom * 2 * cx / w, 0, -x_offset / w * 2], - [0, zoom * 2 * cy / h, -y_offset / h * 2], - [0, 0, 1.0] - ]) - - video_transform = np.array([ - [zoom, 0.0, (w / 2 + x - x_offset) - (cx * zoom)], - [0.0, zoom, (h / 2 + y - y_offset) - (cy * zoom)], - [0.0, 0.0, 1.0] - ]) - self.model_renderer.set_transform(video_transform @ calib_transform) - - return self._cached_matrix - - -if __name__ == "__main__": - gui_app.init_window("OnRoad Camera View") - road_camera_view = AugmentedRoadView(ROAD_CAM) - print("***press space to switch camera view***") - try: - for _ in gui_app.render(): - ui_state.update() - if rl.is_key_released(rl.KeyboardKey.KEY_SPACE): - if WIDE_CAM in road_camera_view.available_streams: - stream = ROAD_CAM if road_camera_view.stream_type == WIDE_CAM else WIDE_CAM - road_camera_view.switch_stream(stream) - road_camera_view.render(rl.Rectangle(0, 0, gui_app.width, gui_app.height)) - finally: - road_camera_view.close() diff --git a/selfdrive/ui/onroad/cameraview.py b/selfdrive/ui/onroad/cameraview.py deleted file mode 100644 index 33f1961d2b..0000000000 --- a/selfdrive/ui/onroad/cameraview.py +++ /dev/null @@ -1,349 +0,0 @@ -import platform -import numpy as np -import pyray as rl - -from openpilot.system.hardware import TICI -from msgq.visionipc import VisionIpcClient, VisionStreamType, VisionBuf -from openpilot.common.swaglog import cloudlog -from openpilot.system.ui.lib.application import gui_app -from openpilot.system.ui.lib.egl import init_egl, create_egl_image, destroy_egl_image, bind_egl_image_to_texture, EGLImage -from openpilot.system.ui.lib.widget import Widget - -CONNECTION_RETRY_INTERVAL = 0.2 # seconds between connection attempts - -VERSION = """ -#version 300 es -precision mediump float; -""" -if platform.system() == "Darwin": - VERSION = """ - #version 330 core - """ - - -VERTEX_SHADER = VERSION + """ -in vec3 vertexPosition; -in vec2 vertexTexCoord; -in vec3 vertexNormal; -in vec4 vertexColor; -uniform mat4 mvp; -out vec2 fragTexCoord; -out vec4 fragColor; -void main() { - fragTexCoord = vertexTexCoord; - fragColor = vertexColor; - gl_Position = mvp * vec4(vertexPosition, 1.0); -} -""" - -# Choose fragment shader based on platform capabilities -if TICI: - FRAME_FRAGMENT_SHADER = """ - #version 300 es - #extension GL_OES_EGL_image_external_essl3 : enable - precision mediump float; - in vec2 fragTexCoord; - uniform samplerExternalOES texture0; - out vec4 fragColor; - void main() { - vec4 color = texture(texture0, fragTexCoord); - fragColor = vec4(pow(color.rgb, vec3(1.0/1.28)), color.a); - } - """ -else: - FRAME_FRAGMENT_SHADER = VERSION + """ - in vec2 fragTexCoord; - uniform sampler2D texture0; - uniform sampler2D texture1; - out vec4 fragColor; - void main() { - float y = texture(texture0, fragTexCoord).r; - vec2 uv = texture(texture1, fragTexCoord).ra - 0.5; - fragColor = vec4(y + 1.402*uv.y, y - 0.344*uv.x - 0.714*uv.y, y + 1.772*uv.x, 1.0); - } - """ - - -class CameraView(Widget): - def __init__(self, name: str, stream_type: VisionStreamType): - super().__init__() - self._name = name - # Primary stream - self.client = VisionIpcClient(name, stream_type, conflate=True) - self._stream_type = stream_type - self.available_streams: list[VisionStreamType] = [] - - # Target stream for switching - self._target_client: VisionIpcClient | None = None - self._target_stream_type: VisionStreamType | None = None - self._switching: bool = False - - self._texture_needs_update = True - self.last_connection_attempt: float = 0.0 - self.shader = rl.load_shader_from_memory(VERTEX_SHADER, FRAME_FRAGMENT_SHADER) - self._texture1_loc: int = rl.get_shader_location(self.shader, "texture1") if not TICI else -1 - - self.frame: VisionBuf | None = None - self.texture_y: rl.Texture | None = None - self.texture_uv: rl.Texture | None = None - - # EGL resources - self.egl_images: dict[int, EGLImage] = {} - self.egl_texture: rl.Texture | None = None - - self._placeholder_color: rl.Color | None = None - - # Initialize EGL for zero-copy rendering on TICI - if TICI: - if not init_egl(): - raise RuntimeError("Failed to initialize EGL") - - # Create a 1x1 pixel placeholder texture for EGL image binding - temp_image = rl.gen_image_color(1, 1, rl.BLACK) - self.egl_texture = rl.load_texture_from_image(temp_image) - rl.unload_image(temp_image) - - def _set_placeholder_color(self, color: rl.Color): - """Set a placeholder color to be drawn when no frame is available.""" - self._placeholder_color = color - - def switch_stream(self, stream_type: VisionStreamType) -> None: - if self._stream_type == stream_type: - return - - if self._switching and self._target_stream_type == stream_type: - return - - cloudlog.debug(f'Preparing switch from {self._stream_type} to {stream_type}') - - if self._target_client: - del self._target_client - - self._target_stream_type = stream_type - self._target_client = VisionIpcClient(self._name, stream_type, conflate=True) - self._switching = True - - @property - def stream_type(self) -> VisionStreamType: - return self._stream_type - - def close(self) -> None: - self._clear_textures() - - # Clean up EGL texture - if TICI and self.egl_texture: - rl.unload_texture(self.egl_texture) - self.egl_texture = None - - # Clean up shader - if self.shader and self.shader.id: - rl.unload_shader(self.shader) - - self.client = None - - def _calc_frame_matrix(self, rect: rl.Rectangle) -> np.ndarray: - if not self.frame: - return np.eye(3) - - # Calculate aspect ratios - widget_aspect_ratio = rect.width / rect.height - frame_aspect_ratio = self.frame.width / self.frame.height - - # Calculate scaling factors to maintain aspect ratio - zx = min(frame_aspect_ratio / widget_aspect_ratio, 1.0) - zy = min(widget_aspect_ratio / frame_aspect_ratio, 1.0) - - return np.array([ - [zx, 0.0, 0.0], - [0.0, zy, 0.0], - [0.0, 0.0, 1.0] - ]) - - def _render(self, rect: rl.Rectangle): - if self._switching: - self._handle_switch() - - if not self._ensure_connection(): - self._draw_placeholder(rect) - return - - # Try to get a new buffer without blocking - buffer = self.client.recv(timeout_ms=0) - if buffer: - self._texture_needs_update = True - self.frame = buffer - - if not self.frame: - self._draw_placeholder(rect) - return - - transform = self._calc_frame_matrix(rect) - src_rect = rl.Rectangle(0, 0, float(self.frame.width), float(self.frame.height)) - - # Calculate scale - scale_x = rect.width * transform[0, 0] # zx - scale_y = rect.height * transform[1, 1] # zy - - # Calculate base position (centered) - x_offset = rect.x + (rect.width - scale_x) / 2 - y_offset = rect.y + (rect.height - scale_y) / 2 - - x_offset += transform[0, 2] * rect.width / 2 - y_offset += transform[1, 2] * rect.height / 2 - - dst_rect = rl.Rectangle(x_offset, y_offset, scale_x, scale_y) - - # Render with appropriate method - if TICI: - self._render_egl(src_rect, dst_rect) - else: - self._render_textures(src_rect, dst_rect) - - def _draw_placeholder(self, rect: rl.Rectangle): - if self._placeholder_color: - rl.draw_rectangle_rec(rect, self._placeholder_color) - - def _render_egl(self, src_rect: rl.Rectangle, dst_rect: rl.Rectangle) -> None: - """Render using EGL for direct buffer access""" - if self.frame is None or self.egl_texture is None: - return - - idx = self.frame.idx - egl_image = self.egl_images.get(idx) - - # Create EGL image if needed - if egl_image is None: - egl_image = create_egl_image(self.frame.width, self.frame.height, self.frame.stride, self.frame.fd, self.frame.uv_offset) - if egl_image: - self.egl_images[idx] = egl_image - else: - return - - # Update texture dimensions to match current frame - self.egl_texture.width = self.frame.width - self.egl_texture.height = self.frame.height - - # Bind the EGL image to our texture - bind_egl_image_to_texture(self.egl_texture.id, egl_image) - - # Render with shader - rl.begin_shader_mode(self.shader) - rl.draw_texture_pro(self.egl_texture, src_rect, dst_rect, rl.Vector2(0, 0), 0.0, rl.WHITE) - rl.end_shader_mode() - - def _render_textures(self, src_rect: rl.Rectangle, dst_rect: rl.Rectangle) -> None: - """Render using texture copies""" - if not self.texture_y or not self.texture_uv or self.frame is None: - return - - # Update textures with new frame data - if self._texture_needs_update: - y_data = self.frame.data[: self.frame.uv_offset] - uv_data = self.frame.data[self.frame.uv_offset:] - - rl.update_texture(self.texture_y, rl.ffi.cast("void *", y_data.ctypes.data)) - rl.update_texture(self.texture_uv, rl.ffi.cast("void *", uv_data.ctypes.data)) - self._texture_needs_update = False - - # Render with shader - rl.begin_shader_mode(self.shader) - rl.set_shader_value_texture(self.shader, self._texture1_loc, self.texture_uv) - rl.draw_texture_pro(self.texture_y, src_rect, dst_rect, rl.Vector2(0, 0), 0.0, rl.WHITE) - rl.end_shader_mode() - - def _ensure_connection(self) -> bool: - if not self.client.is_connected(): - self.frame = None - self.available_streams.clear() - - # Throttle connection attempts - current_time = rl.get_time() - if current_time - self.last_connection_attempt < CONNECTION_RETRY_INTERVAL: - return False - self.last_connection_attempt = current_time - - if not self.client.connect(False) or not self.client.num_buffers: - return False - - cloudlog.debug(f"Connected to {self._name} stream: {self._stream_type}, buffers: {self.client.num_buffers}") - self._initialize_textures() - self.available_streams = self.client.available_streams(self._name, block=False) - - return True - - def _handle_switch(self) -> None: - """Check if target stream is ready and switch immediately.""" - if not self._target_client or not self._switching: - return - - # Try to connect target if needed - if not self._target_client.is_connected(): - if not self._target_client.connect(False) or not self._target_client.num_buffers: - return - - cloudlog.debug(f"Target stream connected: {self._target_stream_type}") - - # Check if target has frames ready - target_frame = self._target_client.recv(timeout_ms=0) - if target_frame: - self.frame = target_frame # Update current frame to target frame - self._complete_switch() - - def _complete_switch(self) -> None: - """Instantly switch to target stream.""" - cloudlog.debug(f"Switching to {self._target_stream_type}") - # Clean up current resources - if self.client: - del self.client - - # Switch to target - self.client = self._target_client - self._stream_type = self._target_stream_type - self._texture_needs_update = True - - # Reset state - self._target_client = None - self._target_stream_type = None - self._switching = False - - # Initialize textures for new stream - self._initialize_textures() - - def _initialize_textures(self): - self._clear_textures() - if not TICI: - self.texture_y = rl.load_texture_from_image(rl.Image(None, int(self.client.stride), - int(self.client.height), 1, rl.PixelFormat.PIXELFORMAT_UNCOMPRESSED_GRAYSCALE)) - self.texture_uv = rl.load_texture_from_image(rl.Image(None, int(self.client.stride // 2), - int(self.client.height // 2), 1, rl.PixelFormat.PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA)) - - def _clear_textures(self): - if self.texture_y and self.texture_y.id: - rl.unload_texture(self.texture_y) - self.texture_y = None - - if self.texture_uv and self.texture_uv.id: - rl.unload_texture(self.texture_uv) - self.texture_uv = None - - # Clean up EGL resources - if TICI: - for data in self.egl_images.values(): - destroy_egl_image(data) - self.egl_images = {} - - -if __name__ == "__main__": - gui_app.init_window("watch3") - road_camera_view = CameraView("camerad", VisionStreamType.VISION_STREAM_ROAD) - driver_camera_view = CameraView("camerad", VisionStreamType.VISION_STREAM_DRIVER) - wide_road_camera_view = CameraView("camerad", VisionStreamType.VISION_STREAM_WIDE_ROAD) - try: - for _ in gui_app.render(): - road_camera_view.render(rl.Rectangle(gui_app.width // 4, 0, gui_app.width // 2, gui_app.height // 2)) - driver_camera_view.render(rl.Rectangle(0, gui_app.height // 2, gui_app.width // 2, gui_app.height // 2)) - wide_road_camera_view.render(rl.Rectangle(gui_app.width // 2, gui_app.height // 2, gui_app.width // 2, gui_app.height // 2)) - finally: - road_camera_view.close() - driver_camera_view.close() - wide_road_camera_view.close() diff --git a/selfdrive/ui/onroad/driver_camera_dialog.py b/selfdrive/ui/onroad/driver_camera_dialog.py deleted file mode 100644 index 40c72f292b..0000000000 --- a/selfdrive/ui/onroad/driver_camera_dialog.py +++ /dev/null @@ -1,98 +0,0 @@ -import numpy as np -import pyray as rl -from msgq.visionipc import VisionStreamType -from openpilot.selfdrive.ui.onroad.cameraview import CameraView -from openpilot.selfdrive.ui.onroad.driver_state import DriverStateRenderer -from openpilot.selfdrive.ui.ui_state import ui_state -from openpilot.system.ui.lib.application import gui_app, FontWeight -from openpilot.system.ui.lib.label import gui_label - - -class DriverCameraDialog(CameraView): - def __init__(self): - super().__init__("camerad", VisionStreamType.VISION_STREAM_DRIVER) - self.driver_state_renderer = DriverStateRenderer() - - def _render(self, rect): - super()._render(rect) - - if rl.is_mouse_button_pressed(rl.MouseButton.MOUSE_BUTTON_LEFT): - return 1 - - if not self.frame: - gui_label( - rect, - "camera starting", - font_size=100, - font_weight=FontWeight.BOLD, - alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER, - ) - return -1 - - self._draw_face_detection(rect) - self.driver_state_renderer.render(rect) - - return -1 - - def _draw_face_detection(self, rect: rl.Rectangle) -> None: - driver_state = ui_state.sm["driverStateV2"] - is_rhd = driver_state.wheelOnRightProb > 0.5 - driver_data = driver_state.rightDriverData if is_rhd else driver_state.leftDriverData - face_detect = driver_data.faceProb > 0.7 - if not face_detect: - return - - # Get face position and orientation - face_x, face_y = driver_data.facePosition - face_std = max(driver_data.faceOrientationStd[0], driver_data.faceOrientationStd[1]) - alpha = 0.7 - if face_std > 0.15: - alpha = max(0.7 - (face_std - 0.15) * 3.5, 0.0) - - # use approx instead of distort_points - # TODO: replace with distort_points - fbox_x = int(1080.0 - 1714.0 * face_x) - fbox_y = int(-135.0 + (504.0 + abs(face_x) * 112.0) + (1205.0 - abs(face_x) * 724.0) * face_y) - box_size = 220 - - line_color = rl.Color(255, 255, 255, int(alpha * 255)) - rl.draw_rectangle_rounded_lines_ex( - rl.Rectangle(fbox_x - box_size / 2, fbox_y - box_size / 2, box_size, box_size), - 35.0 / box_size / 2, - 10, - 10, - line_color, - ) - - def _calc_frame_matrix(self, rect: rl.Rectangle) -> np.ndarray: - driver_view_ratio = 2.0 - - # Get stream dimensions - if self.frame: - stream_width = self.frame.width - stream_height = self.frame.height - else: - # Default values if frame not available - stream_width = 1928 - stream_height = 1208 - - yscale = stream_height * driver_view_ratio / stream_width - xscale = yscale * rect.height / rect.width * stream_width / stream_height - - return np.array([ - [xscale, 0.0, 0.0], - [0.0, yscale, 0.0], - [0.0, 0.0, 1.0] - ]) - - -if __name__ == "__main__": - gui_app.init_window("Driver Camera View") - - driver_camera_view = DriverCameraDialog() - try: - for _ in gui_app.render(): - ui_state.update() - driver_camera_view.render(rl.Rectangle(0, 0, gui_app.width, gui_app.height)) - finally: - driver_camera_view.close() diff --git a/selfdrive/ui/onroad/driver_state.py b/selfdrive/ui/onroad/driver_state.py deleted file mode 100644 index 8d5fb951d0..0000000000 --- a/selfdrive/ui/onroad/driver_state.py +++ /dev/null @@ -1,232 +0,0 @@ -import numpy as np -import pyray as rl -from dataclasses import dataclass -from openpilot.selfdrive.ui.ui_state import ui_state, UI_BORDER_SIZE -from openpilot.system.ui.lib.application import gui_app -from openpilot.system.ui.lib.widget import Widget - -# Default 3D coordinates for face keypoints as a NumPy array -DEFAULT_FACE_KPTS_3D = np.array([ - [-5.98, -51.20, 8.00], [-17.64, -49.14, 8.00], [-23.81, -46.40, 8.00], [-29.98, -40.91, 8.00], - [-32.04, -37.49, 8.00], [-34.10, -32.00, 8.00], [-36.16, -21.03, 8.00], [-36.16, 6.40, 8.00], - [-35.47, 10.51, 8.00], [-32.73, 19.43, 8.00], [-29.30, 26.29, 8.00], [-24.50, 33.83, 8.00], - [-19.01, 41.37, 8.00], [-14.21, 46.17, 8.00], [-12.16, 47.54, 8.00], [-4.61, 49.60, 8.00], - [4.99, 49.60, 8.00], [12.53, 47.54, 8.00], [14.59, 46.17, 8.00], [19.39, 41.37, 8.00], - [24.87, 33.83, 8.00], [29.67, 26.29, 8.00], [33.10, 19.43, 8.00], [35.84, 10.51, 8.00], - [36.53, 6.40, 8.00], [36.53, -21.03, 8.00], [34.47, -32.00, 8.00], [32.42, -37.49, 8.00], - [30.36, -40.91, 8.00], [24.19, -46.40, 8.00], [18.02, -49.14, 8.00], [6.36, -51.20, 8.00], - [-5.98, -51.20, 8.00], -], dtype=np.float32) - -# UI constants -BTN_SIZE = 192 -IMG_SIZE = 144 -ARC_LENGTH = 133 -ARC_THICKNESS_DEFAULT = 6.7 -ARC_THICKNESS_EXTEND = 12.0 - -SCALES_POS = np.array([0.9, 0.4, 0.4], dtype=np.float32) -SCALES_NEG = np.array([0.7, 0.4, 0.4], dtype=np.float32) - -ARC_POINT_COUNT = 37 # Number of points in the arc -ARC_ANGLES = np.linspace(0.0, np.pi, ARC_POINT_COUNT, dtype=np.float32) - - -@dataclass -class ArcData: - """Data structure for arc rendering parameters.""" - x: float - y: float - width: float - height: float - thickness: float - - -class DriverStateRenderer(Widget): - def __init__(self): - super().__init__() - # Initial state with NumPy arrays - self.face_kpts_draw = DEFAULT_FACE_KPTS_3D.copy() - self.is_active = False - self.is_rhd = False - self.dm_fade_state = 0.0 - self.last_rect: rl.Rectangle = rl.Rectangle(0, 0, 0, 0) - self.driver_pose_vals = np.zeros(3, dtype=np.float32) - self.driver_pose_diff = np.zeros(3, dtype=np.float32) - self.driver_pose_sins = np.zeros(3, dtype=np.float32) - self.driver_pose_coss = np.zeros(3, dtype=np.float32) - self.face_keypoints_transformed = np.zeros((DEFAULT_FACE_KPTS_3D.shape[0], 2), dtype=np.float32) - self.position_x: float = 0.0 - self.position_y: float = 0.0 - self.h_arc_data = None - self.v_arc_data = None - - # Pre-allocate drawing arrays - self.face_lines = [rl.Vector2(0, 0) for _ in range(len(DEFAULT_FACE_KPTS_3D))] - self.h_arc_lines = [rl.Vector2(0, 0) for _ in range(ARC_POINT_COUNT)] - self.v_arc_lines = [rl.Vector2(0, 0) for _ in range(ARC_POINT_COUNT)] - - # Load the driver face icon - self.dm_img = gui_app.texture("icons/driver_face.png", IMG_SIZE, IMG_SIZE) - - # Colors - self.white_color = rl.Color(255, 255, 255, 255) - self.arc_color = rl.Color(26, 242, 66, 255) - self.engaged_color = rl.Color(26, 242, 66, 255) - self.disengaged_color = rl.Color(139, 139, 139, 255) - - self.set_visible(lambda: (ui_state.sm.recv_frame['driverStateV2'] > ui_state.started_frame and - ui_state.sm.seen['driverMonitoringState'])) - - def _render(self, rect): - # Set opacity based on active state - opacity = 0.65 if self.is_active else 0.2 - - # Draw background circle - rl.draw_circle(int(self.position_x), int(self.position_y), BTN_SIZE // 2, rl.Color(0, 0, 0, 70)) - - # Draw face icon - icon_pos = rl.Vector2(self.position_x - self.dm_img.width // 2, self.position_y - self.dm_img.height // 2) - rl.draw_texture_v(self.dm_img, icon_pos, rl.Color(255, 255, 255, int(255 * opacity))) - - # Draw face outline - self.white_color.a = int(255 * opacity) - rl.draw_spline_linear(self.face_lines, len(self.face_lines), 5.2, self.white_color) - - # Set arc color based on engaged state - self.arc_color = self.engaged_color if ui_state.engaged else self.disengaged_color - self.arc_color.a = int(0.4 * 255 * (1.0 - self.dm_fade_state)) # Fade out when inactive - - # Draw arcs - if self.h_arc_data: - rl.draw_spline_linear(self.h_arc_lines, len(self.h_arc_lines), self.h_arc_data.thickness, self.arc_color) - if self.v_arc_data: - rl.draw_spline_linear(self.v_arc_lines, len(self.v_arc_lines), self.v_arc_data.thickness, self.arc_color) - - def _update_state(self): - """Update the driver monitoring state based on model data""" - sm = ui_state.sm - if not sm.updated["driverMonitoringState"]: - if (self._rect.x != self.last_rect.x or self._rect.y != self.last_rect.y or - self._rect.width != self.last_rect.width or self._rect.height != self.last_rect.height): - self._pre_calculate_drawing_elements() - self.last_rect = self._rect - return - - # Get monitoring state - dm_state = sm["driverMonitoringState"] - self.is_active = dm_state.isActiveMode - self.is_rhd = dm_state.isRHD - - # Update fade state (smoother transition between active/inactive) - fade_target = 0.0 if self.is_active else 0.5 - self.dm_fade_state = np.clip(self.dm_fade_state + 0.2 * (fade_target - self.dm_fade_state), 0.0, 1.0) - - # Get driver orientation data from appropriate camera - driverstate = sm["driverStateV2"] - driver_data = driverstate.rightDriverData if self.is_rhd else driverstate.leftDriverData - driver_orient = driver_data.faceOrientation - - # Update pose values with scaling and smoothing - driver_orient = np.array(driver_orient) - scales = np.where(driver_orient < 0, SCALES_NEG, SCALES_POS) - v_this = driver_orient * scales - self.driver_pose_diff = np.abs(self.driver_pose_vals - v_this) - self.driver_pose_vals = 0.8 * v_this + 0.2 * self.driver_pose_vals # Smooth changes - - # Apply fade to rotation and compute sin/cos - rotation_amount = self.driver_pose_vals * (1.0 - self.dm_fade_state) - self.driver_pose_sins = np.sin(rotation_amount) - self.driver_pose_coss = np.cos(rotation_amount) - - # Create rotation matrix for 3D face model - sin_y, sin_x, sin_z = self.driver_pose_sins - cos_y, cos_x, cos_z = self.driver_pose_coss - r_xyz = np.array( - [ - [cos_x * cos_z, cos_x * sin_z, -sin_x], - [-sin_y * sin_x * cos_z - cos_y * sin_z, -sin_y * sin_x * sin_z + cos_y * cos_z, -sin_y * cos_x], - [cos_y * sin_x * cos_z - sin_y * sin_z, cos_y * sin_x * sin_z + sin_y * cos_z, cos_y * cos_x], - ] - ) - - # Transform face keypoints using vectorized matrix multiplication - self.face_kpts_draw = DEFAULT_FACE_KPTS_3D @ r_xyz.T - self.face_kpts_draw[:, 2] = self.face_kpts_draw[:, 2] * (1.0 - self.dm_fade_state) + 8 * self.dm_fade_state - - # Pre-calculate the transformed keypoints - kp_depth = (self.face_kpts_draw[:, 2] - 8) / 120.0 + 1.0 - self.face_keypoints_transformed = self.face_kpts_draw[:, :2] * kp_depth[:, None] - - # Pre-calculate all drawing elements - self._pre_calculate_drawing_elements() - - def _pre_calculate_drawing_elements(self): - """Pre-calculate all drawing elements based on the current rectangle""" - # Calculate icon position (bottom-left or bottom-right) - width, height = self._rect.width, self._rect.height - offset = UI_BORDER_SIZE + BTN_SIZE // 2 - self.position_x = self._rect.x + (width - offset if self.is_rhd else offset) - self.position_y = self._rect.y + height - offset - - # Pre-calculate the face lines positions - positioned_keypoints = self.face_keypoints_transformed + np.array([self.position_x, self.position_y]) - for i in range(len(positioned_keypoints)): - self.face_lines[i].x = positioned_keypoints[i][0] - self.face_lines[i].y = positioned_keypoints[i][1] - - # Calculate arc dimensions based on head rotation - delta_x = -self.driver_pose_sins[1] * ARC_LENGTH / 2.0 # Horizontal movement - delta_y = -self.driver_pose_sins[0] * ARC_LENGTH / 2.0 # Vertical movement - - # Horizontal arc - h_width = abs(delta_x) - self.h_arc_data = self._calculate_arc_data( - delta_x, h_width, self.position_x, self.position_y - ARC_LENGTH / 2, - self.driver_pose_sins[1], self.driver_pose_diff[1], is_horizontal=True - ) - - # Vertical arc - v_height = abs(delta_y) - self.v_arc_data = self._calculate_arc_data( - delta_y, v_height, self.position_x - ARC_LENGTH / 2, self.position_y, - self.driver_pose_sins[0], self.driver_pose_diff[0], is_horizontal=False - ) - - def _calculate_arc_data( - self, delta: float, size: float, x: float, y: float, sin_val: float, diff_val: float, is_horizontal: bool - ): - """Calculate arc data and pre-compute arc points.""" - if size <= 0: - return None - - thickness = ARC_THICKNESS_DEFAULT + ARC_THICKNESS_EXTEND * min(1.0, diff_val * 5.0) - start_angle = (90 if sin_val > 0 else -90) if is_horizontal else (0 if sin_val > 0 else 180) - x = min(x + delta, x) if is_horizontal else x - y = y if is_horizontal else min(y + delta, y) - - arc_data = ArcData( - x=x, - y=y, - width=size if is_horizontal else ARC_LENGTH, - height=ARC_LENGTH if is_horizontal else size, - thickness=thickness, - ) - - # Pre-calculate arc points - angles = ARC_ANGLES + np.deg2rad(start_angle) - - center_x = x + arc_data.width / 2 - center_y = y + arc_data.height / 2 - radius_x = arc_data.width / 2 - radius_y = arc_data.height / 2 - - x_coords = center_x + np.cos(angles) * radius_x - y_coords = center_y + np.sin(angles) * radius_y - - arc_lines = self.h_arc_lines if is_horizontal else self.v_arc_lines - for i, (x_coord, y_coord) in enumerate(zip(x_coords, y_coords, strict=True)): - arc_lines[i].x = x_coord - arc_lines[i].y = y_coord - - return arc_data diff --git a/selfdrive/ui/onroad/exp_button.py b/selfdrive/ui/onroad/exp_button.py deleted file mode 100644 index 8c835090d0..0000000000 --- a/selfdrive/ui/onroad/exp_button.py +++ /dev/null @@ -1,78 +0,0 @@ -import time -import pyray as rl -from openpilot.selfdrive.ui.ui_state import ui_state -from openpilot.system.ui.lib.application import gui_app -from openpilot.system.ui.lib.widget import Widget -from openpilot.common.params import Params - - -class ExpButton(Widget): - def __init__(self, button_size: int, icon_size: int): - super().__init__() - self._params = Params() - self._experimental_mode: bool = False - self._engageable: bool = False - - # State hold mechanism - self._hold_duration = 2.0 # seconds - self._held_mode: bool | None = None - self._hold_end_time: float | None = None - - self._white_color: rl.Color = rl.Color(255, 255, 255, 255) - self._black_bg: rl.Color = rl.Color(0, 0, 0, 166) - self._txt_wheel: rl.Texture = gui_app.texture('icons/chffr_wheel.png', icon_size, icon_size) - self._txt_exp: rl.Texture = gui_app.texture('icons/experimental.png', icon_size, icon_size) - self._rect = rl.Rectangle(0, 0, button_size, button_size) - - def set_rect(self, rect: rl.Rectangle) -> None: - self._rect.x, self._rect.y = rect.x, rect.y - - def _update_state(self) -> None: - selfdrive_state = ui_state.sm["selfdriveState"] - self._experimental_mode = selfdrive_state.experimentalMode - self._engageable = selfdrive_state.engageable or selfdrive_state.enabled - - def handle_mouse_event(self) -> bool: - if rl.check_collision_point_rec(rl.get_mouse_position(), self._rect): - if (rl.is_mouse_button_released(rl.MouseButton.MOUSE_BUTTON_LEFT) and - self._is_toggle_allowed()): - new_mode = not self._experimental_mode - self._params.put_bool("ExperimentalMode", new_mode) - - # Hold new state temporarily - self._held_mode = new_mode - self._hold_end_time = time.time() + self._hold_duration - return True - return False - - def _render(self, rect: rl.Rectangle) -> None: - center_x = int(self._rect.x + self._rect.width // 2) - center_y = int(self._rect.y + self._rect.height // 2) - - mouse_over = rl.check_collision_point_rec(rl.get_mouse_position(), self._rect) - mouse_down = rl.is_mouse_button_down(rl.MouseButton.MOUSE_BUTTON_LEFT) and self._is_pressed - self._white_color.a = 180 if (mouse_down and mouse_over) or not self._engageable else 255 - - texture = self._txt_exp if self._held_or_actual_mode() else self._txt_wheel - rl.draw_circle(center_x, center_y, self._rect.width / 2, self._black_bg) - rl.draw_texture(texture, center_x - texture.width // 2, center_y - texture.height // 2, self._white_color) - - def _held_or_actual_mode(self): - now = time.time() - if self._hold_end_time and now < self._hold_end_time: - return self._held_mode - - if self._hold_end_time and now >= self._hold_end_time: - self._hold_end_time = self._held_mode = None - - return self._experimental_mode - - def _is_toggle_allowed(self): - if not self._params.get_bool("ExperimentalModeConfirmed"): - return False - - car_params = ui_state.sm["carParams"] - if car_params.alphaLongitudinalAvailable: - return self._params.get_bool("AlphaLongitudinalEnabled") - else: - return car_params.openpilotLongitudinalControl diff --git a/selfdrive/ui/onroad/hud_renderer.py b/selfdrive/ui/onroad/hud_renderer.py deleted file mode 100644 index da292d38d5..0000000000 --- a/selfdrive/ui/onroad/hud_renderer.py +++ /dev/null @@ -1,179 +0,0 @@ -import pyray as rl -from dataclasses import dataclass -from openpilot.selfdrive.ui.ui_state import ui_state, UIStatus -from openpilot.selfdrive.ui.onroad.exp_button import ExpButton -from openpilot.system.ui.lib.application import gui_app, FontWeight -from openpilot.system.ui.lib.text_measure import measure_text_cached -from openpilot.common.conversions import Conversions as CV -from openpilot.system.ui.lib.widget import Widget - -# Constants -SET_SPEED_NA = 255 -KM_TO_MILE = 0.621371 -CRUISE_DISABLED_CHAR = '–' - - -@dataclass(frozen=True) -class UIConfig: - header_height: int = 300 - border_size: int = 30 - button_size: int = 192 - set_speed_width_metric: int = 200 - set_speed_width_imperial: int = 172 - set_speed_height: int = 204 - wheel_icon_size: int = 144 - - -@dataclass(frozen=True) -class FontSizes: - current_speed: int = 176 - speed_unit: int = 66 - max_speed: int = 40 - set_speed: int = 90 - - -@dataclass(frozen=True) -class Colors: - white: rl.Color = rl.Color(255, 255, 255, 255) - disengaged: rl.Color = rl.Color(145, 155, 149, 255) - override: rl.Color = rl.Color(145, 155, 149, 255) # Added - engaged: rl.Color = rl.Color(128, 216, 166, 255) - disengaged_bg: rl.Color = rl.Color(0, 0, 0, 153) - override_bg: rl.Color = rl.Color(145, 155, 149, 204) - engaged_bg: rl.Color = rl.Color(128, 216, 166, 204) - grey: rl.Color = rl.Color(166, 166, 166, 255) - dark_grey: rl.Color = rl.Color(114, 114, 114, 255) - black_translucent: rl.Color = rl.Color(0, 0, 0, 166) - white_translucent: rl.Color = rl.Color(255, 255, 255, 200) - border_translucent: rl.Color = rl.Color(255, 255, 255, 75) - header_gradient_start: rl.Color = rl.Color(0, 0, 0, 114) - header_gradient_end: rl.Color = rl.Color(0, 0, 0, 0) - - -UI_CONFIG = UIConfig() -FONT_SIZES = FontSizes() -COLORS = Colors() - - -class HudRenderer(Widget): - def __init__(self): - super().__init__() - """Initialize the HUD renderer.""" - self.is_cruise_set: bool = False - self.is_cruise_available: bool = False - self.set_speed: float = SET_SPEED_NA - self.speed: float = 0.0 - self.v_ego_cluster_seen: bool = False - - self._font_semi_bold: rl.Font = gui_app.font(FontWeight.SEMI_BOLD) - self._font_bold: rl.Font = gui_app.font(FontWeight.BOLD) - self._font_medium: rl.Font = gui_app.font(FontWeight.MEDIUM) - - self._exp_button = ExpButton(UI_CONFIG.button_size, UI_CONFIG.wheel_icon_size) - - def _update_state(self) -> None: - """Update HUD state based on car state and controls state.""" - sm = ui_state.sm - if sm.recv_frame["carState"] < ui_state.started_frame: - self.is_cruise_set = False - self.set_speed = SET_SPEED_NA - self.speed = 0.0 - return - - controls_state = sm['controlsState'] - car_state = sm['carState'] - - v_cruise_cluster = car_state.vCruiseCluster - self.set_speed = ( - controls_state.vCruiseDEPRECATED if v_cruise_cluster == 0.0 else v_cruise_cluster - ) - self.is_cruise_set = 0 < self.set_speed < SET_SPEED_NA - self.is_cruise_available = self.set_speed != -1 - - if self.is_cruise_set and not ui_state.is_metric: - self.set_speed *= KM_TO_MILE - - v_ego_cluster = car_state.vEgoCluster - self.v_ego_cluster_seen = self.v_ego_cluster_seen or v_ego_cluster != 0.0 - v_ego = v_ego_cluster if self.v_ego_cluster_seen else car_state.vEgo - speed_conversion = CV.MS_TO_KPH if ui_state.is_metric else CV.MS_TO_MPH - self.speed = max(0.0, v_ego * speed_conversion) - - def _render(self, rect: rl.Rectangle) -> None: - """Render HUD elements to the screen.""" - # Draw the header background - rl.draw_rectangle_gradient_v( - int(rect.x), - int(rect.y), - int(rect.width), - UI_CONFIG.header_height, - COLORS.header_gradient_start, - COLORS.header_gradient_end, - ) - - if self.is_cruise_available: - self._draw_set_speed(rect) - - self._draw_current_speed(rect) - - button_x = rect.x + rect.width - UI_CONFIG.border_size - UI_CONFIG.button_size - button_y = rect.y + UI_CONFIG.border_size - self._exp_button.render(rl.Rectangle(button_x, button_y, UI_CONFIG.button_size, UI_CONFIG.button_size)) - - def handle_mouse_event(self) -> bool: - return bool(self._exp_button.handle_mouse_event()) - - def _draw_set_speed(self, rect: rl.Rectangle) -> None: - """Draw the MAX speed indicator box.""" - set_speed_width = UI_CONFIG.set_speed_width_metric if ui_state.is_metric else UI_CONFIG.set_speed_width_imperial - x = rect.x + 60 + (UI_CONFIG.set_speed_width_imperial - set_speed_width) // 2 - y = rect.y + 45 - - set_speed_rect = rl.Rectangle(x, y, set_speed_width, UI_CONFIG.set_speed_height) - rl.draw_rectangle_rounded(set_speed_rect, 0.2, 30, COLORS.black_translucent) - rl.draw_rectangle_rounded_lines_ex(set_speed_rect, 0.2, 30, 6, COLORS.border_translucent) - - max_color = COLORS.grey - set_speed_color = COLORS.dark_grey - if self.is_cruise_set: - set_speed_color = COLORS.white - if ui_state.status == UIStatus.ENGAGED: - max_color = COLORS.engaged - elif ui_state.status == UIStatus.DISENGAGED: - max_color = COLORS.disengaged - elif ui_state.status == UIStatus.OVERRIDE: - max_color = COLORS.override - - max_text = "MAX" - max_text_width = measure_text_cached(self._font_semi_bold, max_text, FONT_SIZES.max_speed).x - rl.draw_text_ex( - self._font_semi_bold, - max_text, - rl.Vector2(x + (set_speed_width - max_text_width) / 2, y + 27), - FONT_SIZES.max_speed, - 0, - max_color, - ) - - set_speed_text = CRUISE_DISABLED_CHAR if not self.is_cruise_set else str(round(self.set_speed)) - speed_text_width = measure_text_cached(self._font_bold, set_speed_text, FONT_SIZES.set_speed).x - rl.draw_text_ex( - self._font_bold, - set_speed_text, - rl.Vector2(x + (set_speed_width - speed_text_width) / 2, y + 77), - FONT_SIZES.set_speed, - 0, - set_speed_color, - ) - - def _draw_current_speed(self, rect: rl.Rectangle) -> None: - """Draw the current vehicle speed and unit.""" - speed_text = str(round(self.speed)) - speed_text_size = measure_text_cached(self._font_bold, speed_text, FONT_SIZES.current_speed) - speed_pos = rl.Vector2(rect.x + rect.width / 2 - speed_text_size.x / 2, 180 - speed_text_size.y / 2) - rl.draw_text_ex(self._font_bold, speed_text, speed_pos, FONT_SIZES.current_speed, 0, COLORS.white) - - unit_text = "km/h" if ui_state.is_metric else "mph" - unit_text_size = measure_text_cached(self._font_medium, unit_text, FONT_SIZES.speed_unit) - unit_pos = rl.Vector2(rect.x + rect.width / 2 - unit_text_size.x / 2, 290 - unit_text_size.y / 2) - rl.draw_text_ex(self._font_medium, unit_text, unit_pos, FONT_SIZES.speed_unit, 0, COLORS.white_translucent) diff --git a/selfdrive/ui/onroad/model_renderer.py b/selfdrive/ui/onroad/model_renderer.py deleted file mode 100644 index ab2b7aaefb..0000000000 --- a/selfdrive/ui/onroad/model_renderer.py +++ /dev/null @@ -1,442 +0,0 @@ -import colorsys -import numpy as np -import pyray as rl -from cereal import messaging, car -from dataclasses import dataclass, field -from openpilot.common.params import Params -from openpilot.selfdrive.ui.ui_state import ui_state -from openpilot.system.ui.lib.application import DEFAULT_FPS -from openpilot.system.ui.lib.shader_polygon import draw_polygon -from openpilot.system.ui.lib.widget import Widget -from openpilot.selfdrive.locationd.calibrationd import HEIGHT_INIT - -CLIP_MARGIN = 500 -MIN_DRAW_DISTANCE = 10.0 -MAX_DRAW_DISTANCE = 100.0 -PATH_COLOR_TRANSITION_DURATION = 0.5 # Seconds for color transition animation -PATH_BLEND_INCREMENT = 1.0 / (PATH_COLOR_TRANSITION_DURATION * DEFAULT_FPS) - -MAX_POINTS = 200 - -THROTTLE_COLORS = [ - rl.Color(13, 248, 122, 102), # HSLF(148/360, 0.94, 0.51, 0.4) - rl.Color(114, 255, 92, 89), # HSLF(112/360, 1.0, 0.68, 0.35) - rl.Color(114, 255, 92, 0), # HSLF(112/360, 1.0, 0.68, 0.0) -] - -NO_THROTTLE_COLORS = [ - rl.Color(242, 242, 242, 102), # HSLF(148/360, 0.0, 0.95, 0.4) - rl.Color(242, 242, 242, 89), # HSLF(112/360, 0.0, 0.95, 0.35) - rl.Color(242, 242, 242, 0), # HSLF(112/360, 0.0, 0.95, 0.0) -] - - -@dataclass -class ModelPoints: - raw_points: np.ndarray = field(default_factory=lambda: np.empty((0, 3), dtype=np.float32)) - projected_points: np.ndarray = field(default_factory=lambda: np.empty((0, 2), dtype=np.float32)) - - -@dataclass -class LeadVehicle: - glow: list[float] = field(default_factory=list) - chevron: list[float] = field(default_factory=list) - fill_alpha: int = 0 - - -class ModelRenderer(Widget): - def __init__(self): - super().__init__() - self._longitudinal_control = False - self._experimental_mode = False - self._blend_factor = 1.0 - self._prev_allow_throttle = True - self._lane_line_probs = np.zeros(4, dtype=np.float32) - self._road_edge_stds = np.zeros(2, dtype=np.float32) - self._lead_vehicles = [LeadVehicle(), LeadVehicle()] - self._path_offset_z = HEIGHT_INIT[0] - - # Initialize ModelPoints objects - self._path = ModelPoints() - self._lane_lines = [ModelPoints() for _ in range(4)] - self._road_edges = [ModelPoints() for _ in range(2)] - self._acceleration_x = np.empty((0,), dtype=np.float32) - - # Transform matrix (3x3 for car space to screen space) - self._car_space_transform = np.zeros((3, 3), dtype=np.float32) - self._transform_dirty = True - self._clip_region = None - - self._exp_gradient = { - 'start': (0.0, 1.0), # Bottom of path - 'end': (0.0, 0.0), # Top of path - 'colors': [], - 'stops': [], - } - - # Get longitudinal control setting from car parameters - if car_params := Params().get("CarParams"): - cp = messaging.log_from_bytes(car_params, car.CarParams) - self._longitudinal_control = cp.openpilotLongitudinalControl - - def set_transform(self, transform: np.ndarray): - self._car_space_transform = transform.astype(np.float32) - self._transform_dirty = True - - def _render(self, rect: rl.Rectangle): - sm = ui_state.sm - - # Check if data is up-to-date - if (sm.recv_frame["liveCalibration"] < ui_state.started_frame or - sm.recv_frame["modelV2"] < ui_state.started_frame): - return - - # Set up clipping region - self._clip_region = rl.Rectangle( - rect.x - CLIP_MARGIN, rect.y - CLIP_MARGIN, rect.width + 2 * CLIP_MARGIN, rect.height + 2 * CLIP_MARGIN - ) - - # Update state - self._experimental_mode = sm['selfdriveState'].experimentalMode - - live_calib = sm['liveCalibration'] - self._path_offset_z = live_calib.height[0] if live_calib.height else HEIGHT_INIT[0] - - if sm.updated['carParams']: - self._longitudinal_control = sm['carParams'].openpilotLongitudinalControl - - model = sm['modelV2'] - radar_state = sm['radarState'] if sm.valid['radarState'] else None - lead_one = radar_state.leadOne if radar_state else None - render_lead_indicator = self._longitudinal_control and radar_state is not None - - # Update model data when needed - model_updated = sm.updated['modelV2'] - if model_updated or sm.updated['radarState'] or self._transform_dirty: - if model_updated: - self._update_raw_points(model) - - path_x_array = self._path.raw_points[:, 0] - if path_x_array.size == 0: - return - - self._update_model(lead_one, path_x_array) - if render_lead_indicator: - self._update_leads(radar_state, path_x_array) - self._transform_dirty = False - - # Draw elements - self._draw_lane_lines() - self._draw_path(sm) - - if render_lead_indicator and radar_state: - self._draw_lead_indicator() - - def _update_raw_points(self, model): - """Update raw 3D points from model data""" - self._path.raw_points = np.array([model.position.x, model.position.y, model.position.z], dtype=np.float32).T - - for i, lane_line in enumerate(model.laneLines): - self._lane_lines[i].raw_points = np.array([lane_line.x, lane_line.y, lane_line.z], dtype=np.float32).T - - for i, road_edge in enumerate(model.roadEdges): - self._road_edges[i].raw_points = np.array([road_edge.x, road_edge.y, road_edge.z], dtype=np.float32).T - - self._lane_line_probs = np.array(model.laneLineProbs, dtype=np.float32) - self._road_edge_stds = np.array(model.roadEdgeStds, dtype=np.float32) - self._acceleration_x = np.array(model.acceleration.x, dtype=np.float32) - - def _update_leads(self, radar_state, path_x_array): - """Update positions of lead vehicles""" - self._lead_vehicles = [LeadVehicle(), LeadVehicle()] - leads = [radar_state.leadOne, radar_state.leadTwo] - - for i, lead_data in enumerate(leads): - if lead_data and lead_data.status: - d_rel, y_rel, v_rel = lead_data.dRel, lead_data.yRel, lead_data.vRel - idx = self._get_path_length_idx(path_x_array, d_rel) - - # Get z-coordinate from path at the lead vehicle position - z = self._path.raw_points[idx, 2] if idx < len(self._path.raw_points) else 0.0 - point = self._map_to_screen(d_rel, -y_rel, z + self._path_offset_z) - if point: - self._lead_vehicles[i] = self._update_lead_vehicle(d_rel, v_rel, point, self._rect) - - def _update_model(self, lead, path_x_array): - """Update model visualization data based on model message""" - max_distance = np.clip(path_x_array[-1], MIN_DRAW_DISTANCE, MAX_DRAW_DISTANCE) - max_idx = self._get_path_length_idx(self._lane_lines[0].raw_points[:, 0], max_distance) - - # Update lane lines using raw points - for i, lane_line in enumerate(self._lane_lines): - lane_line.projected_points = self._map_line_to_polygon( - lane_line.raw_points, 0.025 * self._lane_line_probs[i], 0.0, max_idx - ) - - # Update road edges using raw points - for road_edge in self._road_edges: - road_edge.projected_points = self._map_line_to_polygon(road_edge.raw_points, 0.025, 0.0, max_idx) - - # Update path using raw points - if lead and lead.status: - lead_d = lead.dRel * 2.0 - max_distance = np.clip(lead_d - min(lead_d * 0.35, 10.0), 0.0, max_distance) - - max_idx = self._get_path_length_idx(path_x_array, max_distance) - self._path.projected_points = self._map_line_to_polygon( - self._path.raw_points, 0.9, self._path_offset_z, max_idx, allow_invert=False - ) - - self._update_experimental_gradient(self._rect.height) - - def _update_experimental_gradient(self, height): - """Pre-calculate experimental mode gradient colors""" - if not self._experimental_mode: - return - - max_len = min(len(self._path.projected_points) // 2, len(self._acceleration_x)) - - segment_colors = [] - gradient_stops = [] - - i = 0 - while i < max_len: - track_idx = max_len - i - 1 # flip idx to start from bottom right - track_y = self._path.projected_points[track_idx][1] - if track_y < 0 or track_y > height: - i += 1 - continue - - # Calculate color based on acceleration - lin_grad_point = (height - track_y) / height - - # speed up: 120, slow down: 0 - path_hue = max(min(60 + self._acceleration_x[i] * 35, 120), 0) - path_hue = int(path_hue * 100 + 0.5) / 100 - - saturation = min(abs(self._acceleration_x[i] * 1.5), 1) - lightness = self._map_val(saturation, 0.0, 1.0, 0.95, 0.62) - alpha = self._map_val(lin_grad_point, 0.75 / 2.0, 0.75, 0.4, 0.0) - - # Use HSL to RGB conversion - color = self._hsla_to_color(path_hue / 360.0, saturation, lightness, alpha) - - gradient_stops.append(lin_grad_point) - segment_colors.append(color) - - # Skip a point, unless next is last - i += 1 + (1 if (i + 2) < max_len else 0) - - # Store the gradient in the path object - self._exp_gradient['colors'] = segment_colors - self._exp_gradient['stops'] = gradient_stops - - def _update_lead_vehicle(self, d_rel, v_rel, point, rect): - speed_buff, lead_buff = 10.0, 40.0 - - # Calculate fill alpha - fill_alpha = 0 - if d_rel < lead_buff: - fill_alpha = 255 * (1.0 - (d_rel / lead_buff)) - if v_rel < 0: - fill_alpha += 255 * (-1 * (v_rel / speed_buff)) - fill_alpha = min(fill_alpha, 255) - - # Calculate size and position - sz = np.clip((25 * 30) / (d_rel / 3 + 30), 15.0, 30.0) * 2.35 - x = np.clip(point[0], 0.0, rect.width - sz / 2) - y = min(point[1], rect.height - sz * 0.6) - - g_xo = sz / 5 - g_yo = sz / 10 - - glow = [(x + (sz * 1.35) + g_xo, y + sz + g_yo), (x, y - g_yo), (x - (sz * 1.35) - g_xo, y + sz + g_yo)] - chevron = [(x + (sz * 1.25), y + sz), (x, y), (x - (sz * 1.25), y + sz)] - - return LeadVehicle(glow=glow, chevron=chevron, fill_alpha=int(fill_alpha)) - - def _draw_lane_lines(self): - """Draw lane lines and road edges""" - for i, lane_line in enumerate(self._lane_lines): - if lane_line.projected_points.size == 0: - continue - - alpha = np.clip(self._lane_line_probs[i], 0.0, 0.7) - color = rl.Color(255, 255, 255, int(alpha * 255)) - draw_polygon(self._rect, lane_line.projected_points, color) - - for i, road_edge in enumerate(self._road_edges): - if road_edge.projected_points.size == 0: - continue - - alpha = np.clip(1.0 - self._road_edge_stds[i], 0.0, 1.0) - color = rl.Color(255, 0, 0, int(alpha * 255)) - draw_polygon(self._rect, road_edge.projected_points, color) - - def _draw_path(self, sm): - """Draw path with dynamic coloring based on mode and throttle state.""" - if not self._path.projected_points.size: - return - - if self._experimental_mode: - # Draw with acceleration coloring - if len(self._exp_gradient['colors']) > 2: - draw_polygon(self._rect, self._path.projected_points, gradient=self._exp_gradient) - else: - draw_polygon(self._rect, self._path.projected_points, rl.Color(255, 255, 255, 30)) - else: - # Draw with throttle/no throttle gradient - allow_throttle = sm['longitudinalPlan'].allowThrottle or not self._longitudinal_control - - # Start transition if throttle state changes - if allow_throttle != self._prev_allow_throttle: - self._prev_allow_throttle = allow_throttle - self._blend_factor = max(1.0 - self._blend_factor, 0.0) - - # Update blend factor - if self._blend_factor < 1.0: - self._blend_factor = min(self._blend_factor + PATH_BLEND_INCREMENT, 1.0) - - begin_colors = NO_THROTTLE_COLORS if allow_throttle else THROTTLE_COLORS - end_colors = THROTTLE_COLORS if allow_throttle else NO_THROTTLE_COLORS - - # Blend colors based on transition - blended_colors = self._blend_colors(begin_colors, end_colors, self._blend_factor) - gradient = { - 'start': (0.0, 1.0), # Bottom of path - 'end': (0.0, 0.0), # Top of path - 'colors': blended_colors, - 'stops': [0.0, 0.5, 1.0], - } - draw_polygon(self._rect, self._path.projected_points, gradient=gradient) - - def _draw_lead_indicator(self): - # Draw lead vehicles if available - for lead in self._lead_vehicles: - if not lead.glow or not lead.chevron: - continue - - rl.draw_triangle_fan(lead.glow, len(lead.glow), rl.Color(218, 202, 37, 255)) - rl.draw_triangle_fan(lead.chevron, len(lead.chevron), rl.Color(201, 34, 49, lead.fill_alpha)) - - @staticmethod - def _get_path_length_idx(pos_x_array: np.ndarray, path_height: float) -> int: - """Get the index corresponding to the given path height""" - if len(pos_x_array) == 0: - return 0 - indices = np.where(pos_x_array <= path_height)[0] - return indices[-1] if indices.size > 0 else 0 - - def _map_to_screen(self, in_x, in_y, in_z): - """Project a point in car space to screen space""" - input_pt = np.array([in_x, in_y, in_z]) - pt = self._car_space_transform @ input_pt - - if abs(pt[2]) < 1e-6: - return None - - x, y = pt[0] / pt[2], pt[1] / pt[2] - - clip = self._clip_region - if not (clip.x <= x <= clip.x + clip.width and clip.y <= y <= clip.y + clip.height): - return None - - return (x, y) - - def _map_line_to_polygon(self, line: np.ndarray, y_off: float, z_off: float, max_idx: int, allow_invert: bool = True) -> np.ndarray: - """Convert 3D line to 2D polygon for rendering.""" - if line.shape[0] == 0: - return np.empty((0, 2), dtype=np.float32) - - # Slice points and filter non-negative x-coordinates - points = line[:max_idx + 1] - points = points[points[:, 0] >= 0] - if points.shape[0] == 0: - return np.empty((0, 2), dtype=np.float32) - - N = points.shape[0] - # Generate left and right 3D points in one array using broadcasting - offsets = np.array([[0, -y_off, z_off], [0, y_off, z_off]], dtype=np.float32) - points_3d = points[None, :, :] + offsets[:, None, :] # Shape: 2xNx3 - points_3d = points_3d.reshape(2 * N, 3) # Shape: (2*N)x3 - - # Transform all points to projected space in one operation - proj = self._car_space_transform @ points_3d.T # Shape: 3x(2*N) - proj = proj.reshape(3, 2, N) - left_proj = proj[:, 0, :] - right_proj = proj[:, 1, :] - - # Filter points where z is sufficiently large - valid_proj = (np.abs(left_proj[2]) >= 1e-6) & (np.abs(right_proj[2]) >= 1e-6) - if not np.any(valid_proj): - return np.empty((0, 2), dtype=np.float32) - - # Compute screen coordinates - left_screen = left_proj[:2, valid_proj] / left_proj[2, valid_proj][None, :] - right_screen = right_proj[:2, valid_proj] / right_proj[2, valid_proj][None, :] - - # Define clip region bounds - clip = self._clip_region - x_min, x_max = clip.x, clip.x + clip.width - y_min, y_max = clip.y, clip.y + clip.height - - # Filter points within clip region - left_in_clip = ( - (left_screen[0] >= x_min) & (left_screen[0] <= x_max) & - (left_screen[1] >= y_min) & (left_screen[1] <= y_max) - ) - right_in_clip = ( - (right_screen[0] >= x_min) & (right_screen[0] <= x_max) & - (right_screen[1] >= y_min) & (right_screen[1] <= y_max) - ) - both_in_clip = left_in_clip & right_in_clip - - if not np.any(both_in_clip): - return np.empty((0, 2), dtype=np.float32) - - # Select valid and clipped points - left_screen = left_screen[:, both_in_clip] - right_screen = right_screen[:, both_in_clip] - - # Handle Y-coordinate inversion on hills - if not allow_invert and left_screen.shape[1] > 1: - y = left_screen[1, :] # y-coordinates - keep = y == np.minimum.accumulate(y) - if not np.any(keep): - return np.empty((0, 2), dtype=np.float32) - left_screen = left_screen[:, keep] - right_screen = right_screen[:, keep] - - return np.vstack((left_screen.T, right_screen[:, ::-1].T)).astype(np.float32) - - @staticmethod - def _map_val(x, x0, x1, y0, y1): - x = np.clip(x, x0, x1) - ra = x1 - x0 - rb = y1 - y0 - return (x - x0) * rb / ra + y0 if ra != 0 else y0 - - @staticmethod - def _hsla_to_color(h, s, l, a): - rgb = colorsys.hls_to_rgb(h, l, s) - return rl.Color( - int(rgb[0] * 255), - int(rgb[1] * 255), - int(rgb[2] * 255), - int(a * 255) - ) - - @staticmethod - def _blend_colors(begin_colors, end_colors, t): - if t >= 1.0: - return end_colors - if t <= 0.0: - return begin_colors - - inv_t = 1.0 - t - return [rl.Color( - int(inv_t * start.r + t * end.r), - int(inv_t * start.g + t * end.g), - int(inv_t * start.b + t * end.b), - int(inv_t * start.a + t * end.a) - ) for start, end in zip(begin_colors, end_colors, strict=True)] diff --git a/selfdrive/ui/qt/api.cc b/selfdrive/ui/qt/api.cc deleted file mode 100644 index 85a3144bd2..0000000000 --- a/selfdrive/ui/qt/api.cc +++ /dev/null @@ -1,147 +0,0 @@ -#include "selfdrive/ui/qt/api.h" - -#include -#include - -#include -#include -#include -#include -#include -#include - -#include -#include - -#include "common/util.h" -#include "system/hardware/hw.h" -#include "selfdrive/ui/qt/util.h" - -namespace CommaApi { - -RSA *get_rsa_private_key() { - static std::unique_ptr rsa_private(nullptr, RSA_free); - if (!rsa_private) { - FILE *fp = fopen(Path::rsa_file().c_str(), "rb"); - if (!fp) { - qDebug() << "No RSA private key found, please run manager.py or registration.py"; - return nullptr; - } - rsa_private.reset(PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL)); - fclose(fp); - } - return rsa_private.get(); -} - -QByteArray rsa_sign(const QByteArray &data) { - RSA *rsa_private = get_rsa_private_key(); - if (!rsa_private) return {}; - - QByteArray sig(RSA_size(rsa_private), Qt::Uninitialized); - unsigned int sig_len; - int ret = RSA_sign(NID_sha256, (unsigned char*)data.data(), data.size(), (unsigned char*)sig.data(), &sig_len, rsa_private); - assert(ret == 1); - assert(sig.size() == sig_len); - return sig; -} - -QString create_jwt(const QJsonObject &payloads, int expiry) { - QJsonObject header = {{"alg", "RS256"}}; - - auto t = QDateTime::currentSecsSinceEpoch(); - QJsonObject payload = {{"identity", getDongleId().value_or("")}, {"nbf", t}, {"iat", t}, {"exp", t + expiry}}; - for (auto it = payloads.begin(); it != payloads.end(); ++it) { - payload.insert(it.key(), it.value()); - } - - auto b64_opts = QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals; - QString jwt = QJsonDocument(header).toJson(QJsonDocument::Compact).toBase64(b64_opts) + '.' + - QJsonDocument(payload).toJson(QJsonDocument::Compact).toBase64(b64_opts); - - auto hash = QCryptographicHash::hash(jwt.toUtf8(), QCryptographicHash::Sha256); - return jwt + "." + rsa_sign(hash).toBase64(b64_opts); -} - -} // namespace CommaApi - -HttpRequest::HttpRequest(QObject *parent, bool create_jwt, int timeout) : create_jwt(create_jwt), QObject(parent) { - networkTimer = new QTimer(this); - networkTimer->setSingleShot(true); - networkTimer->setInterval(timeout); - connect(networkTimer, &QTimer::timeout, this, &HttpRequest::requestTimeout); -} - -bool HttpRequest::active() const { - return reply != nullptr; -} - -bool HttpRequest::timeout() const { - return reply && reply->error() == QNetworkReply::OperationCanceledError; -} - -QNetworkRequest HttpRequest::prepareRequest(const QString &requestURL) { - QNetworkRequest request; - QString token; - if (create_jwt) { - token = GetJwtToken(); - } else { - QString token_json = QString::fromStdString(util::read_file(util::getenv("HOME") + "/.comma/auth.json")); - QJsonDocument json_d = QJsonDocument::fromJson(token_json.toUtf8()); - token = json_d["access_token"].toString(); - } - - request.setUrl(QUrl(requestURL)); - request.setRawHeader("User-Agent", GetUserAgent().toUtf8()); - - if (!token.isEmpty()) { - request.setRawHeader(QByteArray("Authorization"), ("JWT " + token).toUtf8()); - } - return request; -} - -void HttpRequest::sendRequest(const QString &requestURL, const Method method) { - if (active()) { - qDebug() << "HttpRequest is active"; - return; - } - - QNetworkRequest request = prepareRequest(requestURL); - if (method == Method::GET) { - reply = nam()->get(request); - } else if (method == Method::DELETE) { - reply = nam()->deleteResource(request); - } - - networkTimer->start(); - connect(reply, &QNetworkReply::finished, this, &HttpRequest::requestFinished); -} - -void HttpRequest::requestTimeout() { - reply->abort(); -} - -void HttpRequest::requestFinished() { - networkTimer->stop(); - - if (reply->error() == QNetworkReply::NoError) { - emit requestDone(reply->readAll(), true, reply->error()); - } else { - QString error; - if (reply->error() == QNetworkReply::OperationCanceledError) { - nam()->clearAccessCache(); - nam()->clearConnectionCache(); - error = "Request timed out"; - } else { - error = reply->errorString(); - } - emit requestDone(error, false, reply->error()); - } - - reply->deleteLater(); - reply = nullptr; -} - -QNetworkAccessManager *HttpRequest::nam() { - static QNetworkAccessManager *networkAccessManager = new QNetworkAccessManager(qApp); - return networkAccessManager; -} diff --git a/selfdrive/ui/qt/api.h b/selfdrive/ui/qt/api.h deleted file mode 100644 index 80b85f7ca7..0000000000 --- a/selfdrive/ui/qt/api.h +++ /dev/null @@ -1,50 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -#include "util.h" -#include "common/util.h" - -namespace CommaApi { - -const QString BASE_URL = util::getenv("API_HOST", "https://api.commadotai.com").c_str(); -QByteArray rsa_sign(const QByteArray &data); -QString create_jwt(const QJsonObject &payloads = {}, int expiry = 3600); - -} // namespace CommaApi - -/** - * Makes a request to the request endpoint. - */ - -class HttpRequest : public QObject { - Q_OBJECT - -public: - enum class Method {GET, DELETE, POST, PUT}; - - explicit HttpRequest(QObject* parent, bool create_jwt = true, int timeout = 20000); - virtual void sendRequest(const QString &requestURL, Method method); - void sendRequest(const QString &requestURL) { sendRequest(requestURL, Method::GET);} - bool active() const; - bool timeout() const; - -signals: - void requestDone(const QString &response, bool success, QNetworkReply::NetworkError error); - -protected: - QNetworkReply *reply = nullptr; - static QNetworkAccessManager *nam(); - QTimer *networkTimer = nullptr; - bool create_jwt; - virtual QNetworkRequest prepareRequest(const QString& requestURL); - [[nodiscard]] virtual QString GetJwtToken() const { return CommaApi::create_jwt(); } - [[nodiscard]] virtual QString GetUserAgent() const { return getUserAgent(); } - -protected slots: - void requestTimeout(); - void requestFinished(); -}; diff --git a/selfdrive/ui/qt/body.cc b/selfdrive/ui/qt/body.cc deleted file mode 100644 index e01adbe063..0000000000 --- a/selfdrive/ui/qt/body.cc +++ /dev/null @@ -1,161 +0,0 @@ -#include "selfdrive/ui/qt/body.h" - -#include -#include - -#include -#include - -#include "common/params.h" -#include "common/timing.h" - -RecordButton::RecordButton(QWidget *parent) : QPushButton(parent) { - setCheckable(true); - setChecked(false); - setFixedSize(148, 148); - - QObject::connect(this, &QPushButton::toggled, [=]() { - setEnabled(false); - }); -} - -void RecordButton::paintEvent(QPaintEvent *event) { - QPainter p(this); - p.setRenderHint(QPainter::Antialiasing); - - QPoint center(width() / 2, height() / 2); - - QColor bg(isChecked() ? "#FFFFFF" : "#737373"); - QColor accent(isChecked() ? "#FF0000" : "#FFFFFF"); - if (!isEnabled()) { - bg = QColor("#404040"); - accent = QColor("#FFFFFF"); - } - - if (isDown()) { - accent.setAlphaF(0.7); - } - - p.setPen(Qt::NoPen); - p.setBrush(bg); - p.drawEllipse(center, 74, 74); - - p.setPen(QPen(accent, 6)); - p.setBrush(Qt::NoBrush); - p.drawEllipse(center, 42, 42); - - p.setPen(Qt::NoPen); - p.setBrush(accent); - p.drawEllipse(center, 22, 22); -} - - -BodyWindow::BodyWindow(QWidget *parent) : fuel_filter(1.0, 5., 1. / UI_FREQ), QWidget(parent) { - QStackedLayout *layout = new QStackedLayout(this); - layout->setStackingMode(QStackedLayout::StackAll); - - QWidget *w = new QWidget; - QVBoxLayout *vlayout = new QVBoxLayout(w); - vlayout->setMargin(45); - layout->addWidget(w); - - // face - face = new QLabel(); - face->setAlignment(Qt::AlignCenter); - layout->addWidget(face); - awake = new QMovie("../assets/body/awake.gif", {}, this); - awake->setCacheMode(QMovie::CacheAll); - sleep = new QMovie("../assets/body/sleep.gif", {}, this); - sleep->setCacheMode(QMovie::CacheAll); - - // record button - btn = new RecordButton(this); - vlayout->addWidget(btn, 0, Qt::AlignBottom | Qt::AlignRight); - QObject::connect(btn, &QPushButton::clicked, [=](bool checked) { - btn->setEnabled(false); - Params().putBool("DisableLogging", !checked); - last_button = nanos_since_boot(); - }); - w->raise(); - - QObject::connect(uiState(), &UIState::uiUpdate, this, &BodyWindow::updateState); -} - -void BodyWindow::paintEvent(QPaintEvent *event) { - QPainter p(this); - p.setRenderHint(QPainter::Antialiasing); - - p.fillRect(rect(), QColor(0, 0, 0)); - - // battery outline + detail - p.translate(width() - 136, 16); - const QColor gray = QColor("#737373"); - p.setBrush(Qt::NoBrush); - p.setPen(QPen(gray, 4, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); - p.drawRoundedRect(2, 2, 78, 36, 8, 8); - - p.setPen(Qt::NoPen); - p.setBrush(gray); - p.drawRoundedRect(84, 12, 6, 16, 4, 4); - p.drawRect(84, 12, 3, 16); - - // battery level - double fuel = std::clamp(fuel_filter.x(), 0.2f, 1.0f); - const int m = 5; // manual margin since we can't do an inner border - p.setPen(Qt::NoPen); - p.setBrush(fuel > 0.25 ? QColor("#32D74B") : QColor("#FF453A")); - p.drawRoundedRect(2 + m, 2 + m, (78 - 2*m)*fuel, 36 - 2*m, 4, 4); - - // charging status - if (charging) { - p.setPen(Qt::NoPen); - p.setBrush(Qt::white); - const QPolygonF charger({ - QPointF(12.31, 0), - QPointF(12.31, 16.92), - QPointF(18.46, 16.92), - QPointF(6.15, 40), - QPointF(6.15, 23.08), - QPointF(0, 23.08), - }); - p.drawPolygon(charger.translated(98, 0)); - } -} - -void BodyWindow::offroadTransition(bool offroad) { - btn->setChecked(true); - btn->setEnabled(true); - fuel_filter.reset(1.0); -} - -void BodyWindow::updateState(const UIState &s) { - if (!isVisible()) { - return; - } - - const SubMaster &sm = *(s.sm); - auto cs = sm["carState"].getCarState(); - - charging = cs.getCharging(); - fuel_filter.update(cs.getFuelGauge()); - - // TODO: use carState.standstill when that's fixed - const bool standstill = std::abs(cs.getVEgo()) < 0.01; - QMovie *m = standstill ? sleep : awake; - if (m != face->movie()) { - face->setMovie(m); - face->movie()->start(); - } - - // update record button state - if (sm.updated("managerState") && (sm.rcv_time("managerState") - last_button)*1e-9 > 0.5) { - for (auto proc : sm["managerState"].getManagerState().getProcesses()) { - if (proc.getName() == "loggerd") { - btn->setEnabled(true); - btn->setChecked(proc.getRunning()); - } - } - } - - update(); -} diff --git a/selfdrive/ui/qt/body.h b/selfdrive/ui/qt/body.h deleted file mode 100644 index 187e015af7..0000000000 --- a/selfdrive/ui/qt/body.h +++ /dev/null @@ -1,44 +0,0 @@ -#pragma once - -#include -#include -#include - -#include "common/util.h" - -#ifdef SUNNYPILOT -#include "selfdrive/ui/sunnypilot/ui.h" -#define UIState UIStateSP -#else -#include "selfdrive/ui/ui.h" -#endif - -class RecordButton : public QPushButton { - Q_OBJECT - -public: - RecordButton(QWidget* parent = 0); - -private: - void paintEvent(QPaintEvent*) override; -}; - -class BodyWindow : public QWidget { - Q_OBJECT - -public: - BodyWindow(QWidget* parent = 0); - -private: - bool charging = false; - uint64_t last_button = 0; - FirstOrderFilter fuel_filter; - QLabel *face; - QMovie *awake, *sleep; - RecordButton *btn; - void paintEvent(QPaintEvent*) override; - -private slots: - void updateState(const UIState &s); - void offroadTransition(bool onroad); -}; diff --git a/selfdrive/ui/qt/home.cc b/selfdrive/ui/qt/home.cc deleted file mode 100644 index 3f7457192e..0000000000 --- a/selfdrive/ui/qt/home.cc +++ /dev/null @@ -1,95 +0,0 @@ -#include "selfdrive/ui/qt/home.h" - -#include -#include - -#include "selfdrive/ui/qt/util.h" - -// HomeWindow: the container for the offroad and onroad UIs - -HomeWindow::HomeWindow(QWidget* parent) : QWidget(parent) { - QHBoxLayout *main_layout = new QHBoxLayout(this); - main_layout->setMargin(0); - main_layout->setSpacing(0); - - sidebar = new Sidebar(this); - main_layout->addWidget(sidebar); - QObject::connect(sidebar, &Sidebar::openSettings, this, &HomeWindow::openSettings); - - slayout = new QStackedLayout(); - main_layout->addLayout(slayout); - - home = new OffroadHome(this); - QObject::connect(home, &OffroadHome::openSettings, this, &HomeWindow::openSettings); - slayout->addWidget(home); - - onroad = new OnroadWindow(this); - slayout->addWidget(onroad); - - body = new BodyWindow(this); - slayout->addWidget(body); - - driver_view = new DriverViewWindow(this); - connect(driver_view, &DriverViewWindow::done, [=] { - showDriverView(false); - }); - slayout->addWidget(driver_view); - setAttribute(Qt::WA_NoSystemBackground); - QObject::connect(uiState(), &UIState::uiUpdate, this, &HomeWindow::updateState); - QObject::connect(uiState(), &UIState::offroadTransition, this, &HomeWindow::offroadTransition); - QObject::connect(uiState(), &UIState::offroadTransition, sidebar, &Sidebar::offroadTransition); -} - -void HomeWindow::showSidebar(bool show) { - sidebar->setVisible(show); -} - -void HomeWindow::updateState(const UIState &s) { - const SubMaster &sm = *(s.sm); - - // switch to the generic robot UI - if (onroad->isVisible() && !body->isEnabled() && sm["carParams"].getCarParams().getNotCar()) { - body->setEnabled(true); - slayout->setCurrentWidget(body); - } -} - -void HomeWindow::offroadTransition(bool offroad) { - body->setEnabled(false); - sidebar->setVisible(offroad); - if (offroad) { - slayout->setCurrentWidget(home); - } else { - slayout->setCurrentWidget(onroad); - } -} - -void HomeWindow::showDriverView(bool show) { - if (show) { - emit closeSettings(); - slayout->setCurrentWidget(driver_view); - } else { - slayout->setCurrentWidget(home); - } - sidebar->setVisible(show == false); -} - -void HomeWindow::mousePressEvent(QMouseEvent* e) { - // Handle sidebar collapsing - if ((onroad->isVisible() || body->isVisible()) && (!sidebar->isVisible() || e->x() > sidebar->width())) { - sidebar->setVisible(!sidebar->isVisible()); - } -} - -void HomeWindow::mouseDoubleClickEvent(QMouseEvent* e) { - HomeWindow::mousePressEvent(e); - const SubMaster &sm = *(uiState()->sm); - if (sm["carParams"].getCarParams().getNotCar()) { - if (onroad->isVisible()) { - slayout->setCurrentWidget(body); - } else if (body->isVisible()) { - slayout->setCurrentWidget(onroad); - } - showSidebar(false); - } -} diff --git a/selfdrive/ui/qt/home.h b/selfdrive/ui/qt/home.h deleted file mode 100644 index b333624163..0000000000 --- a/selfdrive/ui/qt/home.h +++ /dev/null @@ -1,60 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include - -#include "selfdrive/ui/ui.h" -#include "selfdrive/ui/qt/offroad/driverview.h" - -#ifdef SUNNYPILOT -#include "selfdrive/ui/sunnypilot/qt/widgets/controls.h" -#include "selfdrive/ui/sunnypilot/qt/onroad/onroad_home.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/offroad_home.h" -#include "selfdrive/ui/sunnypilot/qt/sidebar.h" -#define OnroadWindow OnroadWindowSP -#define OffroadHome OffroadHomeSP -#define LayoutWidget LayoutWidgetSP -#define Sidebar SidebarSP -#define ElidedLabel ElidedLabelSP -#define SetupWidget SetupWidgetSP -#else -#include "selfdrive/ui/qt/widgets/controls.h" -#include "selfdrive/ui/qt/onroad/onroad_home.h" -#include "selfdrive/ui/qt/sidebar.h" -#endif - -#include "selfdrive/ui/qt/offroad/offroad_home.h" - -class HomeWindow : public QWidget { - Q_OBJECT - -public: - explicit HomeWindow(QWidget* parent = 0); - -signals: - void openSettings(int index = 0, const QString ¶m = ""); - void closeSettings(); - -public slots: - void offroadTransition(bool offroad); - void showDriverView(bool show); - void showSidebar(bool show); - -protected: - void mousePressEvent(QMouseEvent* e) override; - void mouseDoubleClickEvent(QMouseEvent* e) override; - - Sidebar *sidebar; - OffroadHome *home; - OnroadWindow *onroad; - BodyWindow *body; - DriverViewWindow *driver_view; - QStackedLayout *slayout; - -protected slots: - virtual void updateState(const UIState &s); -}; diff --git a/selfdrive/ui/qt/network/networking.cc b/selfdrive/ui/qt/network/networking.cc deleted file mode 100644 index 7754e6e5ba..0000000000 --- a/selfdrive/ui/qt/network/networking.cc +++ /dev/null @@ -1,420 +0,0 @@ -#include "selfdrive/ui/qt/network/networking.h" - -#include - -#include -#include -#include - -#include "selfdrive/ui/qt/qt_window.h" -#include "selfdrive/ui/qt/util.h" - -#ifdef SUNNYPILOT -#include "selfdrive/ui/sunnypilot/qt/widgets/controls.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/scrollview.h" -#else -#include "selfdrive/ui/qt/widgets/controls.h" -#include "selfdrive/ui/qt/widgets/scrollview.h" -#endif - -static const int ICON_WIDTH = 49; - -// Networking functions - -Networking::Networking(QWidget* parent, bool show_advanced) : QFrame(parent) { - main_layout = new QStackedLayout(this); - - wifi = new WifiManager(this); - connect(wifi, &WifiManager::refreshSignal, this, &Networking::refresh); - connect(wifi, &WifiManager::wrongPassword, this, &Networking::wrongPassword); - - wifiScreen = new QWidget(this); - QVBoxLayout* vlayout = new QVBoxLayout(wifiScreen); - vlayout->setContentsMargins(20, 20, 20, 20); - if (show_advanced) { - QPushButton* advancedSettings = new QPushButton(tr("Advanced")); - advancedSettings->setObjectName("advanced_btn"); - advancedSettings->setStyleSheet("margin-right: 30px;"); - advancedSettings->setFixedSize(400, 100); - connect(advancedSettings, &QPushButton::clicked, [=]() { main_layout->setCurrentWidget(an); }); - vlayout->addSpacing(10); - vlayout->addWidget(advancedSettings, 0, Qt::AlignRight); - vlayout->addSpacing(10); - } - - wifiWidget = new WifiUI(this, wifi); - wifiWidget->setObjectName("wifiWidget"); - connect(wifiWidget, &WifiUI::connectToNetwork, this, &Networking::connectToNetwork); - - ScrollView *wifiScroller = new ScrollView(wifiWidget, this); - wifiScroller->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); - vlayout->addWidget(wifiScroller, 1); - main_layout->addWidget(wifiScreen); - - an = new AdvancedNetworking(this, wifi); - connect(an, &AdvancedNetworking::backPress, [=]() { main_layout->setCurrentWidget(wifiScreen); }); - connect(an, &AdvancedNetworking::requestWifiScreen, [=]() { main_layout->setCurrentWidget(wifiScreen); }); - main_layout->addWidget(an); - - QPalette pal = palette(); - pal.setColor(QPalette::Window, QColor(0x29, 0x29, 0x29)); - setAutoFillBackground(true); - setPalette(pal); - - setStyleSheet(R"( - #wifiWidget > QPushButton, #back_btn, #advanced_btn { - font-size: 50px; - margin: 0px; - padding: 15px; - border-width: 0; - border-radius: 30px; - color: #dddddd; - background-color: #393939; - } - #back_btn:pressed, #advanced_btn:pressed { - background-color: #4a4a4a; - } - )"); - main_layout->setCurrentWidget(wifiScreen); -} - -void Networking::setPrimeType(PrimeState::Type type) { - an->setGsmVisible(type == PrimeState::PRIME_TYPE_NONE || type == PrimeState::PRIME_TYPE_UNKNOWN || \ - type == PrimeState::PRIME_TYPE_PURPLE || type == PrimeState::PRIME_TYPE_LITE); - wifi->ipv4_forward = (type == PrimeState::PRIME_TYPE_NONE || type == PrimeState::PRIME_TYPE_LITE); -} - -void Networking::refresh() { - wifiWidget->refresh(); - an->refresh(); -} - -void Networking::connectToNetwork(const Network n) { - if (wifi->isKnownConnection(n.ssid)) { - wifi->activateWifiConnection(n.ssid); - } else if (n.security_type == SecurityType::OPEN) { - wifi->connect(n, false); - } else if (n.security_type == SecurityType::WPA) { - QString pass = InputDialog::getText(tr("Enter password"), this, tr("for \"%1\"").arg(QString::fromUtf8(n.ssid)), true, 8); - if (!pass.isEmpty()) { - wifi->connect(n, false, pass); - } - } -} - -void Networking::wrongPassword(const QString &ssid) { - if (wifi->seenNetworks.contains(ssid)) { - const Network &n = wifi->seenNetworks.value(ssid); - QString pass = InputDialog::getText(tr("Wrong password"), this, tr("for \"%1\"").arg(QString::fromUtf8(n.ssid)), true, 8); - if (!pass.isEmpty()) { - wifi->connect(n, false, pass); - } - } -} - -void Networking::showEvent(QShowEvent *event) { - wifi->start(); -} - -void Networking::hideEvent(QHideEvent *event) { - main_layout->setCurrentWidget(wifiScreen); - wifi->stop(); -} - -// AdvancedNetworking functions - -AdvancedNetworking::AdvancedNetworking(QWidget* parent, WifiManager* wifi): QWidget(parent), wifi(wifi) { - - QVBoxLayout* main_layout = new QVBoxLayout(this); - main_layout->setMargin(40); - main_layout->setSpacing(20); - - // Back button - QPushButton* back = new QPushButton(tr("Back")); - back->setObjectName("back_btn"); - back->setFixedSize(400, 100); - connect(back, &QPushButton::clicked, [=]() { emit backPress(); }); - main_layout->addWidget(back, 0, Qt::AlignLeft); - - ListWidget *list = new ListWidget(this); - // Enable tethering layout - tetheringToggle = new ToggleControl(tr("Enable Tethering"), "", "", wifi->isTetheringEnabled()); - list->addItem(tetheringToggle); - QObject::connect(tetheringToggle, &ToggleControl::toggleFlipped, this, &AdvancedNetworking::toggleTethering); - - // Change tethering password - ButtonControl *editPasswordButton = new ButtonControl(tr("Tethering Password"), tr("EDIT")); - connect(editPasswordButton, &ButtonControl::clicked, [=]() { - QString pass = InputDialog::getText(tr("Enter new tethering password"), this, "", true, 8, wifi->getTetheringPassword()); - if (!pass.isEmpty()) { - wifi->changeTetheringPassword(pass); - } - }); - list->addItem(editPasswordButton); - - // IP address - ipLabel = new LabelControl(tr("IP Address"), wifi->ipv4_address); - list->addItem(ipLabel); - - // Roaming toggle - const bool roamingEnabled = params.getBool("GsmRoaming"); - roamingToggle = new ToggleControl(tr("Enable Roaming"), "", "", roamingEnabled); - QObject::connect(roamingToggle, &ToggleControl::toggleFlipped, [=](bool state) { - params.putBool("GsmRoaming", state); - wifi->updateGsmSettings(state, QString::fromStdString(params.get("GsmApn")), params.getBool("GsmMetered")); - }); - list->addItem(roamingToggle); - - // APN settings - editApnButton = new ButtonControl(tr("APN Setting"), tr("EDIT")); - connect(editApnButton, &ButtonControl::clicked, [=]() { - const QString cur_apn = QString::fromStdString(params.get("GsmApn")); - QString apn = InputDialog::getText(tr("Enter APN"), this, tr("leave blank for automatic configuration"), false, -1, cur_apn).trimmed(); - - if (apn.isEmpty()) { - params.remove("GsmApn"); - } else { - params.put("GsmApn", apn.toStdString()); - } - wifi->updateGsmSettings(params.getBool("GsmRoaming"), apn, params.getBool("GsmMetered")); - }); - list->addItem(editApnButton); - - // Cellular metered toggle (prime lite or none) - const bool metered = params.getBool("GsmMetered"); - cellularMeteredToggle = new ToggleControl(tr("Cellular Metered"), tr("Prevent large data uploads when on a metered cellular connection"), "", metered); - QObject::connect(cellularMeteredToggle, &SshToggle::toggleFlipped, [=](bool state) { - params.putBool("GsmMetered", state); - wifi->updateGsmSettings(params.getBool("GsmRoaming"), QString::fromStdString(params.get("GsmApn")), state); - }); - list->addItem(cellularMeteredToggle); - - // Wi-Fi metered toggle - std::vector metered_button_texts{tr("default"), tr("metered"), tr("unmetered")}; - wifiMeteredToggle = new MultiButtonControl(tr("Wi-Fi Network Metered"), tr("Prevent large data uploads when on a metered Wi-Fi connection"), "", metered_button_texts); - QObject::connect(wifiMeteredToggle, &MultiButtonControl::buttonClicked, [=](int id) { - wifiMeteredToggle->setEnabled(false); - MeteredType metered = MeteredType::UNKNOWN; - if (id == NM_METERED_YES) { - metered = MeteredType::YES; - } else if (id == NM_METERED_NO) { - metered = MeteredType::NO; - } - auto pending_call = wifi->setCurrentNetworkMetered(metered); - if (pending_call) { - QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(*pending_call); - QObject::connect(watcher, &QDBusPendingCallWatcher::finished, this, [=]() { - refresh(); - watcher->deleteLater(); - }); - } - }); - list->addItem(wifiMeteredToggle); - - // Hidden Network - hiddenNetworkButton = new ButtonControl(tr("Hidden Network"), tr("CONNECT")); - connect(hiddenNetworkButton, &ButtonControl::clicked, [=]() { - QString ssid = InputDialog::getText(tr("Enter SSID"), this, "", false, 1); - if (!ssid.isEmpty()) { - QString pass = InputDialog::getText(tr("Enter password"), this, tr("for \"%1\"").arg(ssid), true, -1); - Network hidden_network; - hidden_network.ssid = ssid.toUtf8(); - if (!pass.isEmpty()) { - hidden_network.security_type = SecurityType::WPA; - wifi->connect(hidden_network, true, pass); - } else { - wifi->connect(hidden_network, true); - } - emit requestWifiScreen(); - } - }); - list->addItem(hiddenNetworkButton); - - // Set initial config - wifi->updateGsmSettings(roamingEnabled, QString::fromStdString(params.get("GsmApn")), metered); - - main_layout->addWidget(new ScrollView(list, this)); - main_layout->addStretch(1); -} - -void AdvancedNetworking::setGsmVisible(bool visible) { - roamingToggle->setVisible(visible); - editApnButton->setVisible(visible); - cellularMeteredToggle->setVisible(visible); -} - -void AdvancedNetworking::refresh() { - ipLabel->setText(wifi->ipv4_address); - tetheringToggle->setEnabled(true); - - if (wifi->isTetheringEnabled() || wifi->ipv4_address == "") { - wifiMeteredToggle->setEnabled(false); - wifiMeteredToggle->setCheckedButton(0); - } else if (wifi->ipv4_address != "") { - MeteredType metered = wifi->currentNetworkMetered(); - wifiMeteredToggle->setEnabled(true); - wifiMeteredToggle->setCheckedButton(static_cast(metered)); - } - - update(); -} - -void AdvancedNetworking::toggleTethering(bool enabled) { - wifi->setTetheringEnabled(enabled); - tetheringToggle->setEnabled(false); - if (enabled) { - wifiMeteredToggle->setEnabled(false); - wifiMeteredToggle->setCheckedButton(0); - } -} - -// WifiUI functions - -WifiUI::WifiUI(QWidget *parent, WifiManager* wifi) : QWidget(parent), wifi(wifi) { - QVBoxLayout *main_layout = new QVBoxLayout(this); - main_layout->setContentsMargins(0, 0, 0, 0); - main_layout->setSpacing(0); - - // load imgs - for (const auto &s : {"low", "medium", "high", "full"}) { - QPixmap pix(ASSET_PATH + "/icons/wifi_strength_" + s + ".svg"); - strengths.push_back(pix.scaledToHeight(68, Qt::SmoothTransformation)); - } - lock = QPixmap(ASSET_PATH + "icons/lock_closed.svg").scaledToWidth(ICON_WIDTH, Qt::SmoothTransformation); - checkmark = QPixmap(ASSET_PATH + "icons/checkmark.svg").scaledToWidth(ICON_WIDTH, Qt::SmoothTransformation); - circled_slash = QPixmap(ASSET_PATH + "icons/circled_slash.svg").scaledToWidth(ICON_WIDTH, Qt::SmoothTransformation); - - scanningLabel = new QLabel(tr("Scanning for networks...")); - scanningLabel->setStyleSheet("font-size: 65px;"); - main_layout->addWidget(scanningLabel, 0, Qt::AlignCenter); - - wifi_list_widget = new ListWidget(this); - wifi_list_widget->setVisible(false); - main_layout->addWidget(wifi_list_widget); - - setStyleSheet(R"( - QScrollBar::handle:vertical { - min-height: 0px; - border-radius: 4px; - background-color: #8A8A8A; - } - #forgetBtn { - font-size: 32px; - font-weight: 600; - color: #292929; - background-color: #BDBDBD; - border-width: 1px solid #828282; - border-radius: 5px; - padding: 40px; - padding-bottom: 16px; - padding-top: 16px; - } - #forgetBtn:pressed { - background-color: #828282; - } - #connecting { - font-size: 32px; - font-weight: 600; - color: white; - border-radius: 0; - padding: 27px; - padding-left: 43px; - padding-right: 43px; - background-color: black; - } - #ssidLabel { - text-align: left; - border: none; - padding-top: 50px; - padding-bottom: 50px; - } - #ssidLabel:disabled { - color: #696969; - } - )"); -} - -void WifiUI::refresh() { - bool is_empty = wifi->seenNetworks.isEmpty(); - scanningLabel->setVisible(is_empty); - wifi_list_widget->setVisible(!is_empty); - if (is_empty) return; - - setUpdatesEnabled(false); - - const bool is_tethering_enabled = wifi->isTetheringEnabled(); - QList sortedNetworks = wifi->seenNetworks.values(); - std::sort(sortedNetworks.begin(), sortedNetworks.end(), compare_by_strength); - - int n = 0; - for (Network &network : sortedNetworks) { - QPixmap status_icon; - if (network.connected == ConnectedType::CONNECTED) { - status_icon = checkmark; - } else if (network.security_type == SecurityType::UNSUPPORTED) { - status_icon = circled_slash; - } else if (network.security_type == SecurityType::WPA) { - status_icon = lock; - } - bool show_forget_btn = wifi->isKnownConnection(network.ssid) && !is_tethering_enabled; - QPixmap strength = strengths[strengthLevel(network.strength)]; - - auto item = getItem(n++); - item->setItem(network, status_icon, show_forget_btn, strength); - item->setVisible(true); - } - for (; n < wifi_items.size(); ++n) wifi_items[n]->setVisible(false); - - setUpdatesEnabled(true); -} - -WifiItem *WifiUI::getItem(int n) { - auto item = n < wifi_items.size() ? wifi_items[n] : wifi_items.emplace_back(new WifiItem(tr("CONNECTING..."), tr("FORGET"))); - if (!item->parentWidget()) { - QObject::connect(item, &WifiItem::connectToNetwork, this, &WifiUI::connectToNetwork); - QObject::connect(item, &WifiItem::forgotNetwork, [this](const Network n) { - if (ConfirmationDialog::confirm(tr("Forget Wi-Fi Network \"%1\"?").arg(QString::fromUtf8(n.ssid)), tr("Forget"), this)) - wifi->forgetConnection(n.ssid); - }); - wifi_list_widget->addItem(item); - } - return item; -} - -// WifiItem - -WifiItem::WifiItem(const QString &connecting_text, const QString &forget_text, QWidget *parent) : QWidget(parent) { - QHBoxLayout *hlayout = new QHBoxLayout(this); - hlayout->setContentsMargins(44, 0, 73, 0); - hlayout->setSpacing(50); - - hlayout->addWidget(ssidLabel = new ElidedLabel()); - ssidLabel->setObjectName("ssidLabel"); - ssidLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); - hlayout->addWidget(connecting = new QPushButton(connecting_text), 0, Qt::AlignRight); - connecting->setObjectName("connecting"); - hlayout->addWidget(forgetBtn = new QPushButton(forget_text), 0, Qt::AlignRight); - forgetBtn->setObjectName("forgetBtn"); - hlayout->addWidget(iconLabel = new QLabel(), 0, Qt::AlignRight); - hlayout->addWidget(strengthLabel = new QLabel(), 0, Qt::AlignRight); - - iconLabel->setFixedWidth(ICON_WIDTH); - QObject::connect(forgetBtn, &QPushButton::clicked, [this]() { emit forgotNetwork(network); }); - QObject::connect(ssidLabel, &ElidedLabel::clicked, [this]() { - if (network.connected == ConnectedType::DISCONNECTED) emit connectToNetwork(network); - }); -} - -void WifiItem::setItem(const Network &n, const QPixmap &status_icon, bool show_forget_btn, const QPixmap &strength_icon) { - network = n; - - ssidLabel->setText(n.ssid); - ssidLabel->setEnabled(n.security_type != SecurityType::UNSUPPORTED); - ssidLabel->setFont(InterFont(55, network.connected == ConnectedType::DISCONNECTED ? QFont::Normal : QFont::Bold)); - - connecting->setVisible(n.connected == ConnectedType::CONNECTING); - forgetBtn->setVisible(show_forget_btn); - - iconLabel->setPixmap(status_icon); - strengthLabel->setPixmap(strength_icon); -} diff --git a/selfdrive/ui/qt/network/networking.h b/selfdrive/ui/qt/network/networking.h deleted file mode 100644 index 73c2226a34..0000000000 --- a/selfdrive/ui/qt/network/networking.h +++ /dev/null @@ -1,117 +0,0 @@ -#pragma once - -#include - -#include "selfdrive/ui/qt/network/wifi_manager.h" -#include "selfdrive/ui/qt/prime_state.h" -#include "selfdrive/ui/qt/widgets/input.h" -#include "selfdrive/ui/qt/widgets/ssh_keys.h" -#include "selfdrive/ui/qt/widgets/toggle.h" - -#ifdef SUNNYPILOT -#include "selfdrive/ui/sunnypilot/qt/widgets/controls.h" -#define ButtonControl ButtonControlSP -#define MultiButtonControl MultiButtonControlSP -#define ElidedLabel ElidedLabelSP -#define LabelControl LabelControlSP -#define ListWidget ListWidgetSP -#define ToggleControl ToggleControlSP -#else -#include "selfdrive/ui/qt/widgets/controls.h" -#endif - -class WifiItem : public QWidget { - Q_OBJECT -public: - explicit WifiItem(const QString &connecting_text, const QString &forget_text, QWidget* parent = nullptr); - void setItem(const Network& n, const QPixmap &icon, bool show_forget_btn, const QPixmap &strength); - -signals: - // Cannot pass Network by reference. it may change after the signal is sent. - void connectToNetwork(const Network n); - void forgotNetwork(const Network n); - -protected: - ElidedLabel* ssidLabel; - QPushButton* connecting; - QPushButton* forgetBtn; - QLabel* iconLabel; - QLabel* strengthLabel; - Network network; -}; - -class WifiUI : public QWidget { - Q_OBJECT - -public: - explicit WifiUI(QWidget *parent = 0, WifiManager* wifi = 0); - -private: - WifiItem *getItem(int n); - - WifiManager *wifi = nullptr; - QLabel *scanningLabel = nullptr; - QPixmap lock; - QPixmap checkmark; - QPixmap circled_slash; - QVector strengths; - ListWidget *wifi_list_widget = nullptr; - std::vector wifi_items; - -signals: - void connectToNetwork(const Network n); - -public slots: - void refresh(); -}; - -class AdvancedNetworking : public QWidget { - Q_OBJECT -public: - explicit AdvancedNetworking(QWidget* parent = 0, WifiManager* wifi = 0); - void setGsmVisible(bool visible); - -private: - LabelControl* ipLabel; - ToggleControl* tetheringToggle; - ToggleControl* roamingToggle; - ButtonControl* editApnButton; - ButtonControl* hiddenNetworkButton; - ToggleControl* cellularMeteredToggle; - MultiButtonControl* wifiMeteredToggle; - WifiManager* wifi = nullptr; - Params params; - -signals: - void backPress(); - void requestWifiScreen(); - -public slots: - void toggleTethering(bool enabled); - void refresh(); -}; - -class Networking : public QFrame { - Q_OBJECT - -public: - explicit Networking(QWidget* parent = 0, bool show_advanced = true); - void setPrimeType(PrimeState::Type type); - WifiManager* wifi = nullptr; - -protected: - QStackedLayout* main_layout = nullptr; - QWidget* wifiScreen = nullptr; - AdvancedNetworking* an = nullptr; - WifiUI* wifiWidget; - - void showEvent(QShowEvent* event) override; - void hideEvent(QHideEvent* event) override; - -public slots: - void refresh(); - -private slots: - void connectToNetwork(const Network n); - void wrongPassword(const QString &ssid); -}; diff --git a/selfdrive/ui/qt/network/networkmanager.h b/selfdrive/ui/qt/network/networkmanager.h deleted file mode 100644 index 8bdeaf3bbd..0000000000 --- a/selfdrive/ui/qt/network/networkmanager.h +++ /dev/null @@ -1,48 +0,0 @@ -#pragma once - -/** - * We are using a NetworkManager DBUS API : https://developer.gnome.org/NetworkManager/1.26/spec.html - * */ - -// https://developer.gnome.org/NetworkManager/1.26/nm-dbus-types.html#NM80211ApFlags -const int NM_802_11_AP_FLAGS_NONE = 0x00000000; -const int NM_802_11_AP_FLAGS_PRIVACY = 0x00000001; -const int NM_802_11_AP_FLAGS_WPS = 0x00000002; - -// https://developer.gnome.org/NetworkManager/1.26/nm-dbus-types.html#NM80211ApSecurityFlags -const int NM_802_11_AP_SEC_PAIR_WEP40 = 0x00000001; -const int NM_802_11_AP_SEC_PAIR_WEP104 = 0x00000002; -const int NM_802_11_AP_SEC_GROUP_WEP40 = 0x00000010; -const int NM_802_11_AP_SEC_GROUP_WEP104 = 0x00000020; -const int NM_802_11_AP_SEC_KEY_MGMT_PSK = 0x00000100; -const int NM_802_11_AP_SEC_KEY_MGMT_802_1X = 0x00000200; - -const QString NM_DBUS_PATH = "/org/freedesktop/NetworkManager"; -const QString NM_DBUS_PATH_SETTINGS = "/org/freedesktop/NetworkManager/Settings"; - -const QString NM_DBUS_INTERFACE = "org.freedesktop.NetworkManager"; -const QString NM_DBUS_INTERFACE_PROPERTIES = "org.freedesktop.DBus.Properties"; -const QString NM_DBUS_INTERFACE_SETTINGS = "org.freedesktop.NetworkManager.Settings"; -const QString NM_DBUS_INTERFACE_SETTINGS_CONNECTION = "org.freedesktop.NetworkManager.Settings.Connection"; -const QString NM_DBUS_INTERFACE_DEVICE = "org.freedesktop.NetworkManager.Device"; -const QString NM_DBUS_INTERFACE_DEVICE_WIRELESS = "org.freedesktop.NetworkManager.Device.Wireless"; -const QString NM_DBUS_INTERFACE_ACCESS_POINT = "org.freedesktop.NetworkManager.AccessPoint"; -const QString NM_DBUS_INTERFACE_ACTIVE_CONNECTION = "org.freedesktop.NetworkManager.Connection.Active"; -const QString NM_DBUS_INTERFACE_IP4_CONFIG = "org.freedesktop.NetworkManager.IP4Config"; - -const QString NM_DBUS_SERVICE = "org.freedesktop.NetworkManager"; - -const int NM_DEVICE_STATE_UNKNOWN = 0; -const int NM_DEVICE_STATE_ACTIVATED = 100; -const int NM_DEVICE_STATE_NEED_AUTH = 60; -const int NM_DEVICE_TYPE_WIFI = 2; -const int NM_DEVICE_TYPE_MODEM = 8; -const int NM_DEVICE_STATE_REASON_SUPPLICANT_DISCONNECT = 8; -const int DBUS_TIMEOUT = 100; - -// https://developer-old.gnome.org/NetworkManager/1.26/nm-dbus-types.html#NMMetered -const int NM_METERED_UNKNOWN = 0; -const int NM_METERED_YES = 1; -const int NM_METERED_NO = 2; -const int NM_METERED_GUESS_YES = 3; -const int NM_METERED_GUESS_NO = 4; diff --git a/selfdrive/ui/qt/network/wifi_manager.cc b/selfdrive/ui/qt/network/wifi_manager.cc deleted file mode 100644 index 8a104c0fbe..0000000000 --- a/selfdrive/ui/qt/network/wifi_manager.cc +++ /dev/null @@ -1,539 +0,0 @@ -#include "selfdrive/ui/qt/network/wifi_manager.h" - -#include - -#include "common/swaglog.h" -#include "selfdrive/ui/qt/util.h" - -bool compare_by_strength(const Network &a, const Network &b) { - return std::tuple(a.connected, strengthLevel(a.strength), b.ssid) > - std::tuple(b.connected, strengthLevel(b.strength), a.ssid); -} - -template -T call(const QString &path, const QString &interface, const QString &method, Args &&...args) { - QDBusInterface nm(NM_DBUS_SERVICE, path, interface, QDBusConnection::systemBus()); - nm.setTimeout(DBUS_TIMEOUT); - - QDBusMessage response = nm.call(method, std::forward(args)...); - if (response.type() == QDBusMessage::ErrorMessage) { - qCritical() << "DBus call error:" << response.errorMessage(); - return T(); - } - - if constexpr (std::is_same_v) { - return response; - } else if (response.arguments().count() >= 1) { - QVariant vFirst = response.arguments().at(0).value().variant(); - if (vFirst.canConvert()) { - return vFirst.value(); - } - QDebug critical = qCritical(); - critical << "Variant unpacking failure :" << method << ','; - (critical << ... << args); - } - return T(); -} - -template -QDBusPendingCall asyncCall(const QString &path, const QString &interface, const QString &method, Args &&...args) { - QDBusInterface nm = QDBusInterface(NM_DBUS_SERVICE, path, interface, QDBusConnection::systemBus()); - return nm.asyncCall(method, args...); -} - -bool emptyPath(const QString &path) { - return path == "" || path == "/"; -} - -WifiManager::WifiManager(QObject *parent) : QObject(parent) { - qDBusRegisterMetaType(); - qDBusRegisterMetaType(); - - // Set tethering ssid as "weedle" + first 4 characters of a dongle id - tethering_ssid = "weedle"; - if (auto dongle_id = getDongleId()) { - tethering_ssid += "-" + dongle_id->left(4); - } - - adapter = getAdapter(); - if (!adapter.isEmpty()) { - setup(); - } else { - QDBusConnection::systemBus().connect(NM_DBUS_SERVICE, NM_DBUS_PATH, NM_DBUS_INTERFACE, "DeviceAdded", this, SLOT(deviceAdded(QDBusObjectPath))); - } - - timer.callOnTimeout(this, &WifiManager::requestScan); - - initConnections(); -} - -void WifiManager::setup() { - auto bus = QDBusConnection::systemBus(); - bus.connect(NM_DBUS_SERVICE, adapter, NM_DBUS_INTERFACE_DEVICE, "StateChanged", this, SLOT(stateChange(unsigned int, unsigned int, unsigned int))); - bus.connect(NM_DBUS_SERVICE, adapter, NM_DBUS_INTERFACE_PROPERTIES, "PropertiesChanged", this, SLOT(propertyChange(QString, QVariantMap, QStringList))); - - bus.connect(NM_DBUS_SERVICE, NM_DBUS_PATH_SETTINGS, NM_DBUS_INTERFACE_SETTINGS, "ConnectionRemoved", this, SLOT(connectionRemoved(QDBusObjectPath))); - bus.connect(NM_DBUS_SERVICE, NM_DBUS_PATH_SETTINGS, NM_DBUS_INTERFACE_SETTINGS, "NewConnection", this, SLOT(newConnection(QDBusObjectPath))); - - raw_adapter_state = call(adapter, NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_DEVICE, "State"); - activeAp = call(adapter, NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_DEVICE_WIRELESS, "ActiveAccessPoint").path(); - - requestScan(); -} - -void WifiManager::start() { - timer.start(5000); - refreshNetworks(); -} - -void WifiManager::stop() { - timer.stop(); -} - -void WifiManager::refreshNetworks() { - if (adapter.isEmpty() || !timer.isActive()) return; - - QDBusPendingCall pending_call = asyncCall(adapter, NM_DBUS_INTERFACE_DEVICE_WIRELESS, "GetAllAccessPoints"); - QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(pending_call); - QObject::connect(watcher, &QDBusPendingCallWatcher::finished, this, &WifiManager::refreshFinished); -} - -void WifiManager::refreshFinished(QDBusPendingCallWatcher *watcher) { - ipv4_address = getIp4Address(); - seenNetworks.clear(); - - const QDBusReply> watcher_reply = *watcher; - if (!watcher_reply.isValid()) { - qCritical() << "Failed to refresh"; - watcher->deleteLater(); - return; - } - - for (const QDBusObjectPath &path : watcher_reply.value()) { - QDBusReply reply = call(path.path(), NM_DBUS_INTERFACE_PROPERTIES, "GetAll", NM_DBUS_INTERFACE_ACCESS_POINT); - if (!reply.isValid()) { - qCritical() << "Failed to retrieve properties for path:" << path.path(); - continue; - } - - auto properties = reply.value(); - const QByteArray ssid = properties["Ssid"].toByteArray(); - if (ssid.isEmpty()) continue; - - // May be multiple access points for each SSID. - // Use first for ssid and security type, then update connected status and strength using all - if (!seenNetworks.contains(ssid)) { - seenNetworks[ssid] = {ssid, 0U, ConnectedType::DISCONNECTED, getSecurityType(properties)}; - } - - if (path.path() == activeAp) { - seenNetworks[ssid].connected = (ssid == connecting_to_network) ? ConnectedType::CONNECTING : ConnectedType::CONNECTED; - } - - uint32_t strength = properties["Strength"].toUInt(); - if (seenNetworks[ssid].strength < strength) { - seenNetworks[ssid].strength = strength; - } - } - - emit refreshSignal(); - watcher->deleteLater(); -} - -QString WifiManager::getIp4Address() { - if (raw_adapter_state != NM_DEVICE_STATE_ACTIVATED) return ""; - - for (const auto &p : getActiveConnections()) { - QString type = call(p.path(), NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_ACTIVE_CONNECTION, "Type"); - if (type == "802-11-wireless") { - auto ip4config = call(p.path(), NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_ACTIVE_CONNECTION, "Ip4Config"); - const auto &arr = call(ip4config.path(), NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_IP4_CONFIG, "AddressData"); - QVariantMap path; - arr.beginArray(); - while (!arr.atEnd()) { - arr >> path; - arr.endArray(); - return path.value("address").value(); - } - arr.endArray(); - } - } - return ""; -} - -SecurityType WifiManager::getSecurityType(const QVariantMap &properties) { - int sflag = properties["Flags"].toUInt(); - int wpaflag = properties["WpaFlags"].toUInt(); - int rsnflag = properties["RsnFlags"].toUInt(); - int wpa_props = wpaflag | rsnflag; - - // obtained by looking at flags of networks in the office as reported by an Android phone - const int supports_wpa = NM_802_11_AP_SEC_PAIR_WEP40 | NM_802_11_AP_SEC_PAIR_WEP104 | NM_802_11_AP_SEC_GROUP_WEP40 | NM_802_11_AP_SEC_GROUP_WEP104 | NM_802_11_AP_SEC_KEY_MGMT_PSK; - - if ((sflag == NM_802_11_AP_FLAGS_NONE) || ((sflag & NM_802_11_AP_FLAGS_WPS) && !(wpa_props & supports_wpa))) { - return SecurityType::OPEN; - } else if ((sflag & NM_802_11_AP_FLAGS_PRIVACY) && (wpa_props & supports_wpa) && !(wpa_props & NM_802_11_AP_SEC_KEY_MGMT_802_1X)) { - return SecurityType::WPA; - } else { - LOGW("Unsupported network! sflag: %d, wpaflag: %d, rsnflag: %d", sflag, wpaflag, rsnflag); - return SecurityType::UNSUPPORTED; - } -} - -void WifiManager::connect(const Network &n, const bool is_hidden, const QString &password, const QString &username) { - setCurrentConnecting(n.ssid); - forgetConnection(n.ssid); // Clear all connections that may already exist to the network we are connecting - Connection connection; - connection["connection"]["type"] = "802-11-wireless"; - connection["connection"]["uuid"] = QUuid::createUuid().toString().remove('{').remove('}'); - connection["connection"]["id"] = "sunnypilot connection " + QString::fromStdString(n.ssid.toStdString()); - connection["connection"]["autoconnect-retries"] = 0; - - connection["802-11-wireless"]["ssid"] = n.ssid; - connection["802-11-wireless"]["hidden"] = is_hidden; - connection["802-11-wireless"]["mode"] = "infrastructure"; - - if (n.security_type == SecurityType::WPA) { - connection["802-11-wireless-security"]["key-mgmt"] = "wpa-psk"; - connection["802-11-wireless-security"]["auth-alg"] = "open"; - connection["802-11-wireless-security"]["psk"] = password; - } - - connection["ipv4"]["method"] = "auto"; - connection["ipv4"]["dns-priority"] = 600; - connection["ipv6"]["method"] = "ignore"; - - asyncCall(NM_DBUS_PATH_SETTINGS, NM_DBUS_INTERFACE_SETTINGS, "AddConnection", QVariant::fromValue(connection)); -} - -void WifiManager::deactivateConnectionBySsid(const QString &ssid) { - for (QDBusObjectPath active_connection : getActiveConnections()) { - auto pth = call(active_connection.path(), NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_ACTIVE_CONNECTION, "SpecificObject"); - if (!emptyPath(pth.path())) { - QString Ssid = get_property(pth.path(), "Ssid"); - if (Ssid == ssid) { - deactivateConnection(active_connection); - return; - } - } - } -} - -void WifiManager::deactivateConnection(const QDBusObjectPath &path) { - asyncCall(NM_DBUS_PATH, NM_DBUS_INTERFACE, "DeactivateConnection", QVariant::fromValue(path)); -} - -QVector WifiManager::getActiveConnections() { - auto result = call(NM_DBUS_PATH, NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE, "ActiveConnections"); - return qdbus_cast>(result); -} - -bool WifiManager::isKnownConnection(const QString &ssid) { - return !getConnectionPath(ssid).path().isEmpty(); -} - -void WifiManager::forgetConnection(const QString &ssid) { - const QDBusObjectPath &path = getConnectionPath(ssid); - if (!path.path().isEmpty()) { - call(path.path(), NM_DBUS_INTERFACE_SETTINGS_CONNECTION, "Delete"); - } -} - -void WifiManager::setCurrentConnecting(const QString &ssid) { - connecting_to_network = ssid; - for (auto &network : seenNetworks) { - network.connected = (network.ssid == ssid) ? ConnectedType::CONNECTING : ConnectedType::DISCONNECTED; - } - emit refreshSignal(); -} - -uint WifiManager::getAdapterType(const QDBusObjectPath &path) { - return call(path.path(), NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_DEVICE, "DeviceType"); -} - -void WifiManager::requestScan() { - if (!adapter.isEmpty()) { - asyncCall(adapter, NM_DBUS_INTERFACE_DEVICE_WIRELESS, "RequestScan", QVariantMap()); - } -} - -QByteArray WifiManager::get_property(const QString &network_path , const QString &property) { - return call(network_path, NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_ACCESS_POINT, property); -} - -QString WifiManager::getAdapter(const uint adapter_type) { - QDBusReply> response = call(NM_DBUS_PATH, NM_DBUS_INTERFACE, "GetDevices"); - for (const QDBusObjectPath &path : response.value()) { - if (getAdapterType(path) == adapter_type) { - return path.path(); - } - } - return ""; -} - -void WifiManager::stateChange(unsigned int new_state, unsigned int previous_state, unsigned int change_reason) { - raw_adapter_state = new_state; - if (new_state == NM_DEVICE_STATE_NEED_AUTH && change_reason == NM_DEVICE_STATE_REASON_SUPPLICANT_DISCONNECT && !connecting_to_network.isEmpty()) { - forgetConnection(connecting_to_network); - emit wrongPassword(connecting_to_network); - } else if (new_state == NM_DEVICE_STATE_ACTIVATED) { - connecting_to_network = ""; - refreshNetworks(); - } -} - -// https://developer.gnome.org/NetworkManager/stable/gdbus-org.freedesktop.NetworkManager.Device.Wireless.html -void WifiManager::propertyChange(const QString &interface, const QVariantMap &props, const QStringList &invalidated_props) { - if (interface == NM_DBUS_INTERFACE_DEVICE_WIRELESS && props.contains("LastScan")) { - refreshNetworks(); - } else if (interface == NM_DBUS_INTERFACE_DEVICE_WIRELESS && props.contains("ActiveAccessPoint")) { - activeAp = props.value("ActiveAccessPoint").value().path(); - } -} - -void WifiManager::deviceAdded(const QDBusObjectPath &path) { - if (getAdapterType(path) == NM_DEVICE_TYPE_WIFI && emptyPath(adapter)) { - adapter = path.path(); - setup(); - } -} - -void WifiManager::connectionRemoved(const QDBusObjectPath &path) { - knownConnections.remove(path); -} - -void WifiManager::newConnection(const QDBusObjectPath &path) { - Connection settings = getConnectionSettings(path); - if (settings.value("connection").value("type") == "802-11-wireless") { - knownConnections[path] = settings.value("802-11-wireless").value("ssid").toString(); - if (knownConnections[path] != tethering_ssid) { - activateWifiConnection(knownConnections[path]); - } - } -} - -QDBusObjectPath WifiManager::getConnectionPath(const QString &ssid) { - return knownConnections.key(ssid); -} - -Connection WifiManager::getConnectionSettings(const QDBusObjectPath &path) { - return QDBusReply(call(path.path(), NM_DBUS_INTERFACE_SETTINGS_CONNECTION, "GetSettings")).value(); -} - -void WifiManager::initConnections() { - const QDBusReply> response = call(NM_DBUS_PATH_SETTINGS, NM_DBUS_INTERFACE_SETTINGS, "ListConnections"); - for (const QDBusObjectPath &path : response.value()) { - const Connection settings = getConnectionSettings(path); - if (settings.value("connection").value("type") == "802-11-wireless") { - knownConnections[path] = settings.value("802-11-wireless").value("ssid").toString(); - } else if (settings.value("connection").value("id") == "lte") { - lteConnectionPath = path; - } - } - - if (!isKnownConnection(tethering_ssid)) { - addTetheringConnection(); - } -} - -std::optional WifiManager::activateWifiConnection(const QString &ssid) { - const QDBusObjectPath &path = getConnectionPath(ssid); - if (!path.path().isEmpty()) { - setCurrentConnecting(ssid); - return asyncCall(NM_DBUS_PATH, NM_DBUS_INTERFACE, "ActivateConnection", QVariant::fromValue(path), QVariant::fromValue(QDBusObjectPath(adapter)), QVariant::fromValue(QDBusObjectPath("/"))); - } - return std::nullopt; -} - -void WifiManager::activateModemConnection(const QDBusObjectPath &path) { - QString modem = getAdapter(NM_DEVICE_TYPE_MODEM); - if (!path.path().isEmpty() && !modem.isEmpty()) { - asyncCall(NM_DBUS_PATH, NM_DBUS_INTERFACE, "ActivateConnection", QVariant::fromValue(path), QVariant::fromValue(QDBusObjectPath(modem)), QVariant::fromValue(QDBusObjectPath("/"))); - } -} - -// function matches tici/hardware.py -// FIXME: it can mistakenly show CELL when connected to WIFI -NetworkType WifiManager::currentNetworkType() { - auto primary_conn = call(NM_DBUS_PATH, NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE, "PrimaryConnection"); - auto primary_type = call(primary_conn.path(), NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_ACTIVE_CONNECTION, "Type"); - - if (primary_type == "802-3-ethernet") { - return NetworkType::ETHERNET; - } else if (primary_type == "802-11-wireless" && !isTetheringEnabled()) { - return NetworkType::WIFI; - } else { - for (const QDBusObjectPath &conn : getActiveConnections()) { - auto type = call(conn.path(), NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_ACTIVE_CONNECTION, "Type"); - if (type == "gsm") { - return NetworkType::CELL; - } - } - } - return NetworkType::NONE; -} - -MeteredType WifiManager::currentNetworkMetered() { - MeteredType metered = MeteredType::UNKNOWN; - for (const auto &active_conn : getActiveConnections()) { - QString type = call(active_conn.path(), NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_ACTIVE_CONNECTION, "Type"); - if (type == "802-11-wireless") { - QDBusObjectPath conn = call(active_conn.path(), NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_ACTIVE_CONNECTION, "Connection"); - if (!conn.path().isEmpty()) { - Connection settings = getConnectionSettings(conn); - int metered_prop = settings.value("connection").value("metered").toInt(); - if (metered_prop == NM_METERED_YES) { - metered = MeteredType::YES; - } else if (metered_prop == NM_METERED_NO) { - metered = MeteredType::NO; - } - } - break; - } - } - return metered; -} - -std::optional WifiManager::setCurrentNetworkMetered(MeteredType metered) { - for (const auto &active_conn : getActiveConnections()) { - QString type = call(active_conn.path(), NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_ACTIVE_CONNECTION, "Type"); - if (type == "802-11-wireless") { - if (!isTetheringEnabled()) { - QDBusObjectPath conn = call(active_conn.path(), NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_ACTIVE_CONNECTION, "Connection"); - if (!conn.path().isEmpty()) { - Connection settings = getConnectionSettings(conn); - settings["connection"]["metered"] = static_cast(metered); - return asyncCall(conn.path(), NM_DBUS_INTERFACE_SETTINGS_CONNECTION, "Update", QVariant::fromValue(settings)); - } - } - } - } - return std::nullopt; -} - -void WifiManager::updateGsmSettings(bool roaming, QString apn, bool metered) { - if (!lteConnectionPath.path().isEmpty()) { - bool changes = false; - bool auto_config = apn.isEmpty(); - Connection settings = getConnectionSettings(lteConnectionPath); - if (settings.value("gsm").value("auto-config").toBool() != auto_config) { - qWarning() << "Changing gsm.auto-config to" << auto_config; - settings["gsm"]["auto-config"] = auto_config; - changes = true; - } - - if (settings.value("gsm").value("apn").toString() != apn) { - qWarning() << "Changing gsm.apn to" << apn; - settings["gsm"]["apn"] = apn; - changes = true; - } - - if (settings.value("gsm").value("home-only").toBool() == roaming) { - qWarning() << "Changing gsm.home-only to" << !roaming; - settings["gsm"]["home-only"] = !roaming; - changes = true; - } - - int meteredInt = metered ? NM_METERED_UNKNOWN : NM_METERED_NO; - if (settings.value("connection").value("metered").toInt() != meteredInt) { - qWarning() << "Changing connection.metered to" << meteredInt; - settings["connection"]["metered"] = meteredInt; - changes = true; - } - - if (changes) { - QDBusPendingCall pending_call = asyncCall(lteConnectionPath.path(), NM_DBUS_INTERFACE_SETTINGS_CONNECTION, "UpdateUnsaved", QVariant::fromValue(settings)); // update is temporary - QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(pending_call); - QObject::connect(watcher, &QDBusPendingCallWatcher::finished, this, [this, watcher]() { - deactivateConnection(lteConnectionPath); - activateModemConnection(lteConnectionPath); - watcher->deleteLater(); - }); - } - } -} - -// Functions for tethering -void WifiManager::addTetheringConnection() { - Connection connection; - connection["connection"]["id"] = "Hotspot"; - connection["connection"]["uuid"] = QUuid::createUuid().toString().remove('{').remove('}'); - connection["connection"]["type"] = "802-11-wireless"; - connection["connection"]["interface-name"] = "wlan0"; - connection["connection"]["autoconnect"] = false; - - connection["802-11-wireless"]["band"] = "bg"; - connection["802-11-wireless"]["mode"] = "ap"; - connection["802-11-wireless"]["ssid"] = tethering_ssid.toUtf8(); - - connection["802-11-wireless-security"]["group"] = QStringList("ccmp"); - connection["802-11-wireless-security"]["key-mgmt"] = "wpa-psk"; - connection["802-11-wireless-security"]["pairwise"] = QStringList("ccmp"); - connection["802-11-wireless-security"]["proto"] = QStringList("rsn"); - connection["802-11-wireless-security"]["psk"] = defaultTetheringPassword; - - connection["ipv4"]["method"] = "shared"; - QVariantMap address; - address["address"] = "192.168.43.1"; - address["prefix"] = 24u; - connection["ipv4"]["address-data"] = QVariant::fromValue(IpConfig() << address); - connection["ipv4"]["gateway"] = "192.168.43.1"; - connection["ipv4"]["never-default"] = true; - connection["ipv6"]["method"] = "ignore"; - - asyncCall(NM_DBUS_PATH_SETTINGS, NM_DBUS_INTERFACE_SETTINGS, "AddConnection", QVariant::fromValue(connection)); -} - -void WifiManager::tetheringActivated(QDBusPendingCallWatcher *call) { - if (!ipv4_forward) { - QTimer::singleShot(5000, this, [=] { - qWarning() << "net.ipv4.ip_forward = 0"; - std::system("sudo sysctl net.ipv4.ip_forward=0"); - }); - } - call->deleteLater(); - tethering_on = true; -} - -void WifiManager::setTetheringEnabled(bool enabled) { - if (enabled) { - auto pending_call = activateWifiConnection(tethering_ssid); - - if (pending_call) { - QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(*pending_call); - QObject::connect(watcher, &QDBusPendingCallWatcher::finished, this, &WifiManager::tetheringActivated); - } - - } else { - deactivateConnectionBySsid(tethering_ssid); - tethering_on = false; - } -} - -bool WifiManager::isTetheringEnabled() { - if (!emptyPath(activeAp)) { - return get_property(activeAp, "Ssid") == tethering_ssid; - } - return false; -} - -QString WifiManager::getTetheringPassword() { - const QDBusObjectPath &path = getConnectionPath(tethering_ssid); - if (!path.path().isEmpty()) { - QDBusReply> response = call(path.path(), NM_DBUS_INTERFACE_SETTINGS_CONNECTION, "GetSecrets", "802-11-wireless-security"); - return response.value().value("802-11-wireless-security").value("psk").toString(); - } - return ""; -} - -void WifiManager::changeTetheringPassword(const QString &newPassword) { - const QDBusObjectPath &path = getConnectionPath(tethering_ssid); - if (!path.path().isEmpty()) { - Connection settings = getConnectionSettings(path); - settings["802-11-wireless-security"]["psk"] = newPassword; - call(path.path(), NM_DBUS_INTERFACE_SETTINGS_CONNECTION, "Update", QVariant::fromValue(settings)); - if (isTetheringEnabled()) { - activateWifiConnection(tethering_ssid); - } - } -} diff --git a/selfdrive/ui/qt/network/wifi_manager.h b/selfdrive/ui/qt/network/wifi_manager.h deleted file mode 100644 index cab932a388..0000000000 --- a/selfdrive/ui/qt/network/wifi_manager.h +++ /dev/null @@ -1,111 +0,0 @@ -#pragma once - -#include -#include -#include - -#include "selfdrive/ui/qt/network/networkmanager.h" - -enum class SecurityType { - OPEN, - WPA, - UNSUPPORTED -}; -enum class ConnectedType { - DISCONNECTED, - CONNECTING, - CONNECTED -}; -enum class NetworkType { - NONE, - WIFI, - CELL, - ETHERNET -}; -enum class MeteredType { - UNKNOWN, - YES, - NO -}; - -typedef QMap Connection; -typedef QVector IpConfig; - -struct Network { - QByteArray ssid; - unsigned int strength; - ConnectedType connected; - SecurityType security_type; -}; -bool compare_by_strength(const Network &a, const Network &b); -inline int strengthLevel(unsigned int strength) { return std::clamp((int)round(strength / 33.), 0, 3); } - -class WifiManager : public QObject { - Q_OBJECT - -public: - QMap seenNetworks; - QMap knownConnections; - QString ipv4_address; - bool tethering_on = false; - bool ipv4_forward = false; - - explicit WifiManager(QObject* parent); - void start(); - void stop(); - void requestScan(); - void forgetConnection(const QString &ssid); - bool isKnownConnection(const QString &ssid); - std::optional activateWifiConnection(const QString &ssid); - NetworkType currentNetworkType(); - MeteredType currentNetworkMetered(); - std::optional setCurrentNetworkMetered(MeteredType metered); - void updateGsmSettings(bool roaming, QString apn, bool metered); - void connect(const Network &ssid, const bool is_hidden = false, const QString &password = {}, const QString &username = {}); - - // Tethering functions - void setTetheringEnabled(bool enabled); - bool isTetheringEnabled(); - void changeTetheringPassword(const QString &newPassword); - QString getTetheringPassword(); - -private: - QString adapter; // Path to network manager wifi-device - QTimer timer; - unsigned int raw_adapter_state = NM_DEVICE_STATE_UNKNOWN; // Connection status https://developer.gnome.org/NetworkManager/1.26/nm-dbus-types.html#NMDeviceState - QString connecting_to_network; - QString tethering_ssid; - const QString defaultTetheringPassword = "swagswagcomma"; - QString activeAp; - QDBusObjectPath lteConnectionPath; - - QString getAdapter(const uint = NM_DEVICE_TYPE_WIFI); - uint getAdapterType(const QDBusObjectPath &path); - QString getIp4Address(); - void deactivateConnectionBySsid(const QString &ssid); - void deactivateConnection(const QDBusObjectPath &path); - QVector getActiveConnections(); - QByteArray get_property(const QString &network_path, const QString &property); - SecurityType getSecurityType(const QVariantMap &properties); - QDBusObjectPath getConnectionPath(const QString &ssid); - Connection getConnectionSettings(const QDBusObjectPath &path); - void initConnections(); - void setup(); - void refreshNetworks(); - void activateModemConnection(const QDBusObjectPath &path); - void addTetheringConnection(); - void setCurrentConnecting(const QString &ssid); - -signals: - void wrongPassword(const QString &ssid); - void refreshSignal(); - -private slots: - void stateChange(unsigned int new_state, unsigned int previous_state, unsigned int change_reason); - void propertyChange(const QString &interface, const QVariantMap &props, const QStringList &invalidated_props); - void deviceAdded(const QDBusObjectPath &path); - void connectionRemoved(const QDBusObjectPath &path); - void newConnection(const QDBusObjectPath &path); - void refreshFinished(QDBusPendingCallWatcher *call); - void tetheringActivated(QDBusPendingCallWatcher *call); -}; diff --git a/selfdrive/ui/qt/offroad/developer_panel.cc b/selfdrive/ui/qt/offroad/developer_panel.cc deleted file mode 100644 index 3e9647d2cf..0000000000 --- a/selfdrive/ui/qt/offroad/developer_panel.cc +++ /dev/null @@ -1,116 +0,0 @@ -#include "selfdrive/ui/qt/offroad/developer_panel.h" -#include "selfdrive/ui/qt/widgets/ssh_keys.h" - -#ifdef SUNNYPILOT -#include "selfdrive/ui/sunnypilot/qt/widgets/controls.h" -#else -#include "selfdrive/ui/qt/widgets/controls.h" -#endif - -DeveloperPanel::DeveloperPanel(SettingsWindow *parent) : ListWidget(parent) { - adbToggle = new ParamControl("AdbEnabled", tr("Enable ADB"), - tr("ADB (Android Debug Bridge) allows connecting to your device over USB or over the network. See https://docs.comma.ai/how-to/connect-to-comma for more info."), ""); - addItem(adbToggle); - - // SSH keys - addItem(new SshToggle()); - addItem(new SshControl()); - - joystickToggle = new ParamControl("JoystickDebugMode", tr("Joystick Debug Mode"), "", ""); - QObject::connect(joystickToggle, &ParamControl::toggleFlipped, [=](bool state) { - params.putBool("LongitudinalManeuverMode", false); - longManeuverToggle->refresh(); - }); - addItem(joystickToggle); - - longManeuverToggle = new ParamControl("LongitudinalManeuverMode", tr("Longitudinal Maneuver Mode"), "", ""); - QObject::connect(longManeuverToggle, &ParamControl::toggleFlipped, [=](bool state) { - params.putBool("JoystickDebugMode", false); - joystickToggle->refresh(); - }); - addItem(longManeuverToggle); - - experimentalLongitudinalToggle = new ParamControl( - "AlphaLongitudinalEnabled", - tr("openpilot Longitudinal Control (Alpha)"), - QString("%1

%2") - .arg(tr("WARNING: openpilot longitudinal control is in alpha for this car and will disable Automatic Emergency Braking (AEB).")) - .arg(tr("On this car, sunnypilot defaults to the car's built-in ACC instead of openpilot's longitudinal control. " - "Enable this to switch to openpilot longitudinal control. Enabling Experimental mode is recommended when enabling openpilot longitudinal control alpha.")), - "" - ); - experimentalLongitudinalToggle->setConfirmation(true, false); - QObject::connect(experimentalLongitudinalToggle, &ParamControl::toggleFlipped, [=]() { - updateToggles(offroad); - }); - addItem(experimentalLongitudinalToggle); - - enableGithubRunner = new ParamControl("EnableGithubRunner", tr("Enable GitHub runner service"), tr("Enables or disables the github runner service."), ""); - addItem(enableGithubRunner); - - // error log button - errorLogBtn = new ButtonControl(tr("Error Log"), tr("VIEW"), tr("View the error log for sunnypilot crashes.")); - connect(errorLogBtn, &ButtonControl::clicked, [=]() { - std::string txt = util::read_file("/data/community/crashes/error.log"); - ConfirmationDialog::rich(QString::fromStdString(txt), this); - }); - addItem(errorLogBtn); - - // Joystick and longitudinal maneuvers should be hidden on release branches - is_release = params.getBool("IsReleaseBranch"); - - // Toggles should be not available to change in onroad state - QObject::connect(uiState(), &UIState::offroadTransition, this, &DeveloperPanel::updateToggles); -} - -void DeveloperPanel::updateToggles(bool _offroad) { - for (auto btn : findChildren()) { - btn->setVisible(!is_release); - - /* - * experimentalLongitudinalToggle should be toggelable when: - * - visible, and - * - during onroad & offroad states - */ - if (btn != experimentalLongitudinalToggle) { - btn->setEnabled(_offroad); - } - } - - // longManeuverToggle and experimentalLongitudinalToggle should not be toggleable if the car does not have longitudinal control - auto cp_bytes = params.get("CarParamsPersistent"); - if (!cp_bytes.empty()) { - AlignedBuffer aligned_buf; - capnp::FlatArrayMessageReader cmsg(aligned_buf.align(cp_bytes.data(), cp_bytes.size())); - cereal::CarParams::Reader CP = cmsg.getRoot(); - - if (!CP.getAlphaLongitudinalAvailable() || is_release) { - params.remove("AlphaLongitudinalEnabled"); - experimentalLongitudinalToggle->setEnabled(false); - } - - /* - * experimentalLongitudinalToggle should be visible when: - * - is not a release branch, and - * - the car supports experimental longitudinal control (alpha) - */ - experimentalLongitudinalToggle->setVisible(CP.getAlphaLongitudinalAvailable() && !is_release); - - longManeuverToggle->setEnabled(hasLongitudinalControl(CP) && _offroad); - } else { - longManeuverToggle->setEnabled(false); - experimentalLongitudinalToggle->setVisible(false); - } - experimentalLongitudinalToggle->refresh(); - - // Handle specific controls visibility for release branches - enableGithubRunner->setVisible(!is_release); - errorLogBtn->setVisible(!is_release); - joystickToggle->setVisible(!is_release); - - offroad = _offroad; -} - -void DeveloperPanel::showEvent(QShowEvent *event) { - updateToggles(offroad); -} diff --git a/selfdrive/ui/qt/offroad/developer_panel.h b/selfdrive/ui/qt/offroad/developer_panel.h deleted file mode 100644 index c15b574f5a..0000000000 --- a/selfdrive/ui/qt/offroad/developer_panel.h +++ /dev/null @@ -1,28 +0,0 @@ -#pragma once - -#ifdef SUNNYPILOT -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/settings.h" -#else -#include "selfdrive/ui/qt/offroad/settings.h" -#endif - -class DeveloperPanel : public ListWidget { - Q_OBJECT -public: - explicit DeveloperPanel(SettingsWindow *parent); - void showEvent(QShowEvent *event) override; - -private: - Params params; - ParamControl* adbToggle; - ParamControl* joystickToggle; - ButtonControl* errorLogBtn; - ParamControl* longManeuverToggle; - ParamControl* experimentalLongitudinalToggle; - ParamControl* enableGithubRunner; - bool is_release; - bool offroad = false; - -private slots: - void updateToggles(bool _offroad); -}; diff --git a/selfdrive/ui/qt/offroad/driverview.cc b/selfdrive/ui/qt/offroad/driverview.cc deleted file mode 100644 index 9010227f18..0000000000 --- a/selfdrive/ui/qt/offroad/driverview.cc +++ /dev/null @@ -1,82 +0,0 @@ -#include "selfdrive/ui/qt/offroad/driverview.h" - -#include -#include - -#include "selfdrive/ui/qt/util.h" - -DriverViewWindow::DriverViewWindow(QWidget* parent) : CameraWidget("camerad", VISION_STREAM_DRIVER, parent) { - QObject::connect(this, &CameraWidget::clicked, this, &DriverViewWindow::done); - QObject::connect(device(), &Device::interactiveTimeout, this, [this]() { - if (isVisible()) { - emit done(); - } - }); -} - -void DriverViewWindow::showEvent(QShowEvent* event) { - params.putBool("IsDriverViewEnabled", true); - device()->resetInteractiveTimeout(60); - CameraWidget::showEvent(event); -} - -void DriverViewWindow::hideEvent(QHideEvent* event) { - params.putBool("IsDriverViewEnabled", false); - stopVipcThread(); - CameraWidget::hideEvent(event); -} - -void DriverViewWindow::paintGL() { - CameraWidget::paintGL(); - - std::lock_guard lk(frame_lock); - QPainter p(this); - // startup msg - if (frames.empty()) { - p.setPen(Qt::white); - p.setRenderHint(QPainter::TextAntialiasing); - p.setFont(InterFont(100, QFont::Bold)); - p.drawText(geometry(), Qt::AlignCenter, tr("camera starting")); - return; - } - - const auto &sm = *(uiState()->sm); - cereal::DriverStateV2::Reader driver_state = sm["driverStateV2"].getDriverStateV2(); - bool is_rhd = driver_state.getWheelOnRightProb() > 0.5; - auto driver_data = is_rhd ? driver_state.getRightDriverData() : driver_state.getLeftDriverData(); - - bool face_detected = driver_data.getFaceProb() > 0.7; - if (face_detected) { - auto fxy_list = driver_data.getFacePosition(); - auto std_list = driver_data.getFaceOrientationStd(); - float face_x = fxy_list[0]; - float face_y = fxy_list[1]; - float face_std = std::max(std_list[0], std_list[1]); - - float alpha = 0.7; - if (face_std > 0.15) { - alpha = std::max(0.7 - (face_std-0.15)*3.5, 0.0); - } - const int box_size = 220; - // use approx instead of distort_points - int fbox_x = 1080.0 - 1714.0 * face_x; - int fbox_y = -135.0 + (504.0 + std::abs(face_x)*112.0) + (1205.0 - std::abs(face_x)*724.0) * face_y; - p.setPen(QPen(QColor(255, 255, 255, alpha * 255), 10)); - p.drawRoundedRect(fbox_x - box_size / 2, fbox_y - box_size / 2, box_size, box_size, 35.0, 35.0); - } - - driver_monitor.updateState(*uiState()); - driver_monitor.draw(p, rect()); -} - -mat4 DriverViewWindow::calcFrameMatrix() { - const float driver_view_ratio = 2.0; - const float yscale = stream_height * driver_view_ratio / stream_width; - const float xscale = yscale * glHeight() / glWidth() * stream_width / stream_height; - return mat4{{ - xscale, 0.0, 0.0, 0.0, - 0.0, yscale, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0, - }}; -} diff --git a/selfdrive/ui/qt/offroad/driverview.h b/selfdrive/ui/qt/offroad/driverview.h deleted file mode 100644 index f6eb752fe6..0000000000 --- a/selfdrive/ui/qt/offroad/driverview.h +++ /dev/null @@ -1,23 +0,0 @@ -#pragma once - -#include "selfdrive/ui/qt/widgets/cameraview.h" -#include "selfdrive/ui/qt/onroad/driver_monitoring.h" - -class DriverViewWindow : public CameraWidget { - Q_OBJECT - -public: - explicit DriverViewWindow(QWidget *parent); - -signals: - void done(); - -protected: - mat4 calcFrameMatrix() override; - void showEvent(QShowEvent *event) override; - void hideEvent(QHideEvent *event) override; - void paintGL() override; - - Params params; - DriverMonitorRenderer driver_monitor; -}; diff --git a/selfdrive/ui/qt/offroad/experimental_mode.cc b/selfdrive/ui/qt/offroad/experimental_mode.cc deleted file mode 100644 index a3288a3e96..0000000000 --- a/selfdrive/ui/qt/offroad/experimental_mode.cc +++ /dev/null @@ -1,82 +0,0 @@ -#include "selfdrive/ui/qt/offroad/experimental_mode.h" - -#include -#include -#include -#include -#include - -#include "selfdrive/ui/ui.h" - -#ifdef SUNNYPILOT -constexpr int toggles_settings_index = 3; -#else -constexpr int toggles_settings_index = 2; -#endif - -ExperimentalModeButton::ExperimentalModeButton(QWidget *parent) : QPushButton(parent) { - chill_pixmap = QPixmap("../assets/icons/couch.svg").scaledToWidth(img_width, Qt::SmoothTransformation); - experimental_pixmap = QPixmap("../assets/icons/experimental_grey.svg").scaledToWidth(img_width, Qt::SmoothTransformation); - - // go to toggles and expand experimental mode description - connect(this, &QPushButton::clicked, [=]() { emit openSettings(toggles_settings_index, "ExperimentalMode"); }); - - setFixedHeight(125); - QHBoxLayout *main_layout = new QHBoxLayout; - main_layout->setContentsMargins(horizontal_padding, 0, horizontal_padding, 0); - - mode_label = new QLabel; - mode_icon = new QLabel; - mode_icon->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); - - main_layout->addWidget(mode_label, 1, Qt::AlignLeft); - main_layout->addWidget(mode_icon, 0, Qt::AlignRight); - - setLayout(main_layout); - - setStyleSheet(R"( - QPushButton { - border: none; - } - - QLabel { - font-size: 45px; - font-weight: 300; - text-align: left; - font-family: JetBrainsMono; - color: #000000; - } - )"); -} - -void ExperimentalModeButton::paintEvent(QPaintEvent *event) { - QPainter p(this); - p.setPen(Qt::NoPen); - p.setRenderHint(QPainter::Antialiasing); - - QPainterPath path; - path.addRoundedRect(rect(), 10, 10); - - // gradient - bool pressed = isDown(); - QLinearGradient gradient(rect().left(), 0, rect().right(), 0); - if (experimental_mode) { - gradient.setColorAt(0, QColor(255, 155, 63, pressed ? 0xcc : 0xff)); - gradient.setColorAt(1, QColor(219, 56, 34, pressed ? 0xcc : 0xff)); - } else { - gradient.setColorAt(0, QColor(20, 255, 171, pressed ? 0xcc : 0xff)); - gradient.setColorAt(1, QColor(35, 149, 255, pressed ? 0xcc : 0xff)); - } - p.fillPath(path, gradient); - - // vertical line - p.setPen(QPen(QColor(0, 0, 0, 0x4d), 3, Qt::SolidLine)); - int line_x = rect().right() - img_width - (2 * horizontal_padding); - p.drawLine(line_x, rect().bottom(), line_x, rect().top()); -} - -void ExperimentalModeButton::showEvent(QShowEvent *event) { - experimental_mode = params.getBool("ExperimentalMode"); - mode_icon->setPixmap(experimental_mode ? experimental_pixmap : chill_pixmap); - mode_label->setText(experimental_mode ? tr("EXPERIMENTAL MODE ON") : tr("CHILL MODE ON")); -} diff --git a/selfdrive/ui/qt/offroad/experimental_mode.h b/selfdrive/ui/qt/offroad/experimental_mode.h deleted file mode 100644 index bfb7638bbe..0000000000 --- a/selfdrive/ui/qt/offroad/experimental_mode.h +++ /dev/null @@ -1,31 +0,0 @@ -#pragma once - -#include -#include - -#include "common/params.h" - -class ExperimentalModeButton : public QPushButton { - Q_OBJECT - -public: - explicit ExperimentalModeButton(QWidget* parent = 0); - -signals: - void openSettings(int index = 0, const QString &toggle = ""); - -private: - void showEvent(QShowEvent *event) override; - - Params params; - bool experimental_mode; - int img_width = 100; - int horizontal_padding = 30; - QPixmap experimental_pixmap; - QPixmap chill_pixmap; - QLabel *mode_label; - QLabel *mode_icon; - -protected: - void paintEvent(QPaintEvent *event) override; -}; diff --git a/selfdrive/ui/qt/offroad/firehose.cc b/selfdrive/ui/qt/offroad/firehose.cc deleted file mode 100644 index 17df440c36..0000000000 --- a/selfdrive/ui/qt/offroad/firehose.cc +++ /dev/null @@ -1,114 +0,0 @@ -#include "selfdrive/ui/qt/offroad/firehose.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef SUNNYPILOT -#define UIState UIStateSP -#endif - -FirehosePanel::FirehosePanel(SettingsWindow *parent) : QWidget((QWidget*)parent) { - layout = new QVBoxLayout(this); - layout->setContentsMargins(40, 40, 40, 40); - layout->setSpacing(20); - - // header - QLabel *title = new QLabel(tr("Firehose Mode")); - title->setStyleSheet("font-size: 100px; font-weight: 500; font-family: 'Noto Color Emoji';"); - layout->addWidget(title, 0, Qt::AlignCenter); - - // Create a container for the content - QFrame *content = new QFrame(); - content->setStyleSheet("background-color: #292929; border-radius: 15px; padding: 20px;"); - QVBoxLayout *content_layout = new QVBoxLayout(content); - content_layout->setSpacing(20); - - // Top description - QLabel *description = new QLabel(tr("sunnypilot learns to drive by watching humans, like you, drive.\n\nFirehose Mode allows you to maximize your training data uploads to improve openpilot's driving models. More data means bigger models, which means better Experimental Mode.")); - description->setStyleSheet("font-size: 45px; padding-bottom: 20px;"); - description->setWordWrap(true); - content_layout->addWidget(description); - - // Add a separator - QFrame *line = new QFrame(); - line->setFrameShape(QFrame::HLine); - line->setFrameShadow(QFrame::Sunken); - line->setStyleSheet("background-color: #444444; margin-top: 5px; margin-bottom: 5px;"); - content_layout->addWidget(line); - - toggle_label = new QLabel(tr("Firehose Mode: ACTIVE")); - toggle_label->setStyleSheet("font-size: 60px; font-weight: bold; color: white;"); - content_layout->addWidget(toggle_label); - - // Add contribution label - contribution_label = new QLabel(); - contribution_label->setStyleSheet("font-size: 52px; margin-top: 10px; margin-bottom: 10px;"); - contribution_label->setWordWrap(true); - contribution_label->hide(); - content_layout->addWidget(contribution_label); - - // Add a separator before detailed instructions - QFrame *line2 = new QFrame(); - line2->setFrameShape(QFrame::HLine); - line2->setFrameShadow(QFrame::Sunken); - line2->setStyleSheet("background-color: #444444; margin-top: 10px; margin-bottom: 10px;"); - content_layout->addWidget(line2); - - // Detailed instructions at the bottom - detailed_instructions = new QLabel(tr( - "For maximum effectiveness, bring your device inside and connect to a good USB-C adapter and Wi-Fi weekly.
" - "
" - "Firehose Mode can also work while you're driving if connected to a hotspot or unlimited SIM card.
" - "

" - "Frequently Asked Questions

" - "Does it matter how or where I drive? Nope, just drive as you normally would.

" - "Do all of my segments get pulled in Firehose Mode? No, we selectively pull a subset of your segments.

" - "What's a good USB-C adapter? Any fast phone or laptop charger should be fine.

" - "Does it matter which software I run? Yes, only upstream sunnypilot (and particular forks) are able to be used for training." - )); - detailed_instructions->setStyleSheet("font-size: 40px; color: #E4E4E4;"); - detailed_instructions->setWordWrap(true); - content_layout->addWidget(detailed_instructions); - - layout->addWidget(content, 1); - - // Set up the API request for firehose stats - const QString dongle_id = QString::fromStdString(Params().get("DongleId")); - firehose_stats = new RequestRepeater(this, CommaApi::BASE_URL + "/v1/devices/" + dongle_id + "/firehose_stats", - "ApiCache_FirehoseStats", 30, true); - QObject::connect(firehose_stats, &RequestRepeater::requestDone, [=](const QString &response, bool success) { - if (success) { - QJsonDocument doc = QJsonDocument::fromJson(response.toUtf8()); - QJsonObject json = doc.object(); - int count = json["firehose"].toInt(); - contribution_label->setText(tr("%n segment(s) of your driving is in the training dataset so far.", "", count)); - contribution_label->show(); - } - }); - - QObject::connect(uiState(), &UIState::uiUpdate, this, &FirehosePanel::refresh); -} - -void FirehosePanel::refresh() { - auto deviceState = (*uiState()->sm)["deviceState"].getDeviceState(); - auto networkType = deviceState.getNetworkType(); - bool networkMetered = deviceState.getNetworkMetered(); - - bool is_active = !networkMetered && (networkType != cereal::DeviceState::NetworkType::NONE); - if (is_active) { - toggle_label->setText(tr("ACTIVE")); - toggle_label->setStyleSheet("font-size: 60px; font-weight: bold; color: #2ecc71;"); - } else { - toggle_label->setText(tr("INACTIVE: connect to an unmetered network")); - toggle_label->setStyleSheet("font-size: 60px;"); - } -} diff --git a/selfdrive/ui/qt/offroad/firehose.h b/selfdrive/ui/qt/offroad/firehose.h deleted file mode 100644 index 0a5fd77ba3..0000000000 --- a/selfdrive/ui/qt/offroad/firehose.h +++ /dev/null @@ -1,37 +0,0 @@ -#pragma once - -#include -#include -#include -#include "selfdrive/ui/qt/request_repeater.h" - -#ifdef SUNNYPILOT -#include "selfdrive/ui/sunnypilot/ui.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/controls.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/settings.h" -#else -#include "selfdrive/ui/ui.h" -#include "selfdrive/ui/qt/widgets/controls.h" -#include "selfdrive/ui/qt/offroad/settings.h" -#endif - -// Forward declarations -class SettingsWindow; - -class FirehosePanel : public QWidget { - Q_OBJECT -public: - explicit FirehosePanel(SettingsWindow *parent); - -private: - QVBoxLayout *layout; - - QLabel *detailed_instructions; - QLabel *contribution_label; - QLabel *toggle_label; - - RequestRepeater *firehose_stats; - -private slots: - void refresh(); -}; diff --git a/selfdrive/ui/qt/offroad/offroad_home.cc b/selfdrive/ui/qt/offroad/offroad_home.cc deleted file mode 100644 index 9ca41e5567..0000000000 --- a/selfdrive/ui/qt/offroad/offroad_home.cc +++ /dev/null @@ -1,158 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/qt/offroad/offroad_home.h" - -#include "selfdrive/ui/qt/offroad/experimental_mode.h" -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/qt/widgets/prime.h" - -// OffroadHome: the offroad home page - -OffroadHome::OffroadHome(QWidget* parent) : QFrame(parent) { - QVBoxLayout* main_layout = new QVBoxLayout(this); - main_layout->setContentsMargins(40, 40, 40, 40); - - // top header - header_layout = new QHBoxLayout(); - header_layout->setContentsMargins(0, 0, 0, 0); - header_layout->setSpacing(16); - - update_notif = new QPushButton(tr("UPDATE")); - update_notif->setVisible(false); - update_notif->setStyleSheet("background-color: #364DEF;"); - QObject::connect(update_notif, &QPushButton::clicked, [=]() { center_layout->setCurrentIndex(1); }); - header_layout->addWidget(update_notif, 0, Qt::AlignHCenter | Qt::AlignLeft); - - alert_notif = new QPushButton(); - alert_notif->setVisible(false); - alert_notif->setStyleSheet("background-color: #E22C2C;"); - QObject::connect(alert_notif, &QPushButton::clicked, [=] { center_layout->setCurrentIndex(2); }); - header_layout->addWidget(alert_notif, 0, Qt::AlignHCenter | Qt::AlignLeft); - - version = new ElidedLabel(); - header_layout->addWidget(version, 0, Qt::AlignHCenter | Qt::AlignRight); - - main_layout->addLayout(header_layout); - - // main content - main_layout->addSpacing(25); - center_layout = new QStackedLayout(); - - QWidget *home_widget = new QWidget(this); - { - home_layout = new QHBoxLayout(home_widget); - home_layout->setContentsMargins(0, 0, 0, 0); - home_layout->setSpacing(30); - -#ifndef SUNNYPILOT - // left: PrimeAdWidget - QStackedWidget *left_widget = new QStackedWidget(this); - QVBoxLayout *left_prime_layout = new QVBoxLayout(); - left_prime_layout->setContentsMargins(0, 0, 0, 0); - QWidget *prime_user = new PrimeUserWidget(); - prime_user->setStyleSheet(R"( - border-radius: 10px; - background-color: #333333; - )"); - left_prime_layout->addWidget(prime_user); - left_prime_layout->addStretch(); - left_widget->addWidget(new LayoutWidget(left_prime_layout)); - left_widget->addWidget(new PrimeAdWidget); - left_widget->setStyleSheet("border-radius: 10px;"); - - connect(uiState()->prime_state, &PrimeState::changed, [left_widget]() { - left_widget->setCurrentIndex(uiState()->prime_state->isSubscribed() ? 0 : 1); - }); - - home_layout->addWidget(left_widget, 1); -#endif - - // right: ExperimentalModeButton, SetupWidget - QWidget* right_widget = new QWidget(this); - QVBoxLayout* right_column = new QVBoxLayout(right_widget); - right_column->setContentsMargins(0, 0, 0, 0); - right_widget->setFixedWidth(750); - right_column->setSpacing(30); - - ExperimentalModeButton *experimental_mode = new ExperimentalModeButton(this); - QObject::connect(experimental_mode, &ExperimentalModeButton::openSettings, this, &OffroadHome::openSettings); - right_column->addWidget(experimental_mode, 1); - - SetupWidget *setup_widget = new SetupWidget; - QObject::connect(setup_widget, &SetupWidget::openSettings, this, &OffroadHome::openSettings); - right_column->addWidget(setup_widget, 1); - - home_layout->addWidget(right_widget, 1); - } - center_layout->addWidget(home_widget); - - // add update & alerts widgets - update_widget = new UpdateAlert(); - QObject::connect(update_widget, &UpdateAlert::dismiss, [=]() { center_layout->setCurrentIndex(0); }); - center_layout->addWidget(update_widget); - alerts_widget = new OffroadAlert(); - QObject::connect(alerts_widget, &OffroadAlert::dismiss, [=]() { center_layout->setCurrentIndex(0); }); - center_layout->addWidget(alerts_widget); - - main_layout->addLayout(center_layout, 1); - - // set up refresh timer - timer = new QTimer(this); - timer->callOnTimeout(this, &OffroadHome::refresh); - - setStyleSheet(R"( - * { - color: white; - } - OffroadHome { - background-color: black; - } - OffroadHome > QPushButton { - padding: 15px 30px; - border-radius: 5px; - font-size: 40px; - font-weight: 500; - } - OffroadHome > QLabel { - font-size: 55px; - } - )"); -} - -void OffroadHome::showEvent(QShowEvent *event) { - refresh(); - timer->start(10 * 1000); -} - -void OffroadHome::hideEvent(QHideEvent *event) { - timer->stop(); -} - -void OffroadHome::refresh() { - version->setText(getBrand() + " " + QString::fromStdString(params.get("UpdaterCurrentDescription"))); - - bool updateAvailable = update_widget->refresh(); - int alerts = alerts_widget->refresh(); - - // pop-up new notification - int idx = center_layout->currentIndex(); - if (!updateAvailable && !alerts) { - idx = 0; - } else if (updateAvailable && (!update_notif->isVisible() || (!alerts && idx == 2))) { - idx = 1; - } else if (alerts && (!alert_notif->isVisible() || (!updateAvailable && idx == 1))) { - idx = 2; - } - center_layout->setCurrentIndex(idx); - - update_notif->setVisible(updateAvailable); - alert_notif->setVisible(alerts); - if (alerts) { - alert_notif->setText(QString::number(alerts) + (alerts > 1 ? tr(" ALERTS") : tr(" ALERT"))); - } -} diff --git a/selfdrive/ui/qt/offroad/offroad_home.h b/selfdrive/ui/qt/offroad/offroad_home.h deleted file mode 100644 index cac37d58cd..0000000000 --- a/selfdrive/ui/qt/offroad/offroad_home.h +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "common/params.h" -#include "selfdrive/ui/qt/body.h" -#include "selfdrive/ui/qt/widgets/offroad_alerts.h" - -#ifdef SUNNYPILOT -#include "selfdrive/ui/sunnypilot/qt/widgets/controls.h" -#include "selfdrive/ui/sunnypilot/qt/onroad/onroad_home.h" -#include "selfdrive/ui/sunnypilot/qt/sidebar.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/prime.h" -#define OnroadWindow OnroadWindowSP -#define LayoutWidget LayoutWidgetSP -#define Sidebar SidebarSP -#define ElidedLabel ElidedLabelSP -#define SetupWidget SetupWidgetSP -#else -#include "selfdrive/ui/qt/widgets/controls.h" -#include "selfdrive/ui/qt/onroad/onroad_home.h" -#include "selfdrive/ui/qt/sidebar.h" -#include "selfdrive/ui/qt/widgets/prime.h" -#endif - -class OffroadHome : public QFrame { - Q_OBJECT - -public: - explicit OffroadHome(QWidget* parent = 0); - - signals: - void openSettings(int index = 0, const QString ¶m = ""); - -protected: - QHBoxLayout *home_layout; - QHBoxLayout *header_layout; - - void showEvent(QShowEvent *event) override; - void refresh(); - -private: - void hideEvent(QHideEvent *event) override; - - Params params; - - QTimer* timer; - ElidedLabel* version; - QStackedLayout* center_layout; - UpdateAlert *update_widget; - OffroadAlert* alerts_widget; - QPushButton* alert_notif; - QPushButton* update_notif; -}; diff --git a/selfdrive/ui/qt/offroad/onboarding.cc b/selfdrive/ui/qt/offroad/onboarding.cc deleted file mode 100644 index 309a73b939..0000000000 --- a/selfdrive/ui/qt/offroad/onboarding.cc +++ /dev/null @@ -1,211 +0,0 @@ -#include "selfdrive/ui/qt/offroad/onboarding.h" - -#include - -#include -#include -#include -#include - -#include "common/util.h" -#include "common/params.h" -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/qt/widgets/input.h" - -TrainingGuide::TrainingGuide(QWidget *parent) : QFrame(parent) { - setAttribute(Qt::WA_OpaquePaintEvent); -} - -void TrainingGuide::mouseReleaseEvent(QMouseEvent *e) { - if (click_timer.elapsed() < 250) { - return; - } - click_timer.restart(); - - auto contains = [this](QRect r, const QPoint &pt) { - if (image.size() != image_raw_size) { - QTransform transform; - transform.translate((width()- image.width()) / 2.0, (height()- image.height()) / 2.0); - transform.scale(image.width() / (float)image_raw_size.width(), image.height() / (float)image_raw_size.height()); - r= transform.mapRect(r); - } - return r.contains(pt); - }; - - if (contains(boundingRect[currentIndex], e->pos())) { - if (currentIndex == 9) { - const QRect yes = QRect(707, 804, 531, 164); - Params().putBool("RecordFront", contains(yes, e->pos())); - } - currentIndex += 1; - } else if (currentIndex == (boundingRect.size() - 2) && contains(boundingRect.last(), e->pos())) { - currentIndex = 0; - } - - if (currentIndex >= (boundingRect.size() - 1)) { - emit completedTraining(); - } else { - update(); - } -} - -void TrainingGuide::showEvent(QShowEvent *event) { - currentIndex = 0; - click_timer.start(); -} - -QImage TrainingGuide::loadImage(int id) { - QImage img(img_path + QString("step%1.png").arg(id)); - image_raw_size = img.size(); - if (image_raw_size != rect().size()) { - img = img.scaled(width(), height(), Qt::KeepAspectRatio, Qt::SmoothTransformation); - } - return img; -} - -void TrainingGuide::paintEvent(QPaintEvent *event) { - QPainter painter(this); - - QRect bg(0, 0, painter.device()->width(), painter.device()->height()); - painter.fillRect(bg, QColor("#000000")); - - image = loadImage(currentIndex); - QRect rect(image.rect()); - rect.moveCenter(bg.center()); - painter.drawImage(rect.topLeft(), image); - - // progress bar - if (currentIndex > 0 && currentIndex < (boundingRect.size() - 2)) { - const int h = 20; - const int w = (currentIndex / (float)(boundingRect.size() - 2)) * width(); - painter.fillRect(QRect(0, height() - h, w, h), QColor("#465BEA")); - } -} - -void TermsPage::showEvent(QShowEvent *event) { - QVBoxLayout *main_layout = new QVBoxLayout(this); - main_layout->setContentsMargins(45, 35, 45, 45); - main_layout->setSpacing(0); - - QVBoxLayout *vlayout = new QVBoxLayout(); - vlayout->setContentsMargins(165, 165, 165, 0); - main_layout->addLayout(vlayout); - - QLabel *title = new QLabel(tr("Welcome to sunnypilot")); - title->setStyleSheet("font-size: 90px; font-weight: 500;"); - vlayout->addWidget(title, 0, Qt::AlignTop | Qt::AlignLeft); - - vlayout->addSpacing(90); - QLabel *desc = new QLabel(tr("You must accept the Terms and Conditions to use sunnypilot. Read the latest terms at https://comma.ai/terms before continuing.")); - desc->setWordWrap(true); - desc->setStyleSheet("font-size: 80px; font-weight: 300;"); - vlayout->addWidget(desc, 0); - - vlayout->addStretch(); - - QHBoxLayout* buttons = new QHBoxLayout; - buttons->setMargin(0); - buttons->setSpacing(45); - main_layout->addLayout(buttons); - - QPushButton *decline_btn = new QPushButton(tr("Decline")); - buttons->addWidget(decline_btn); - QObject::connect(decline_btn, &QPushButton::clicked, this, &TermsPage::declinedTerms); - - accept_btn = new QPushButton(tr("Agree")); - accept_btn->setStyleSheet(R"( - QPushButton { - background-color: #465BEA; - } - QPushButton:pressed { - background-color: #3049F4; - } - )"); - buttons->addWidget(accept_btn); - QObject::connect(accept_btn, &QPushButton::clicked, this, &TermsPage::acceptedTerms); -} - -void DeclinePage::showEvent(QShowEvent *event) { - if (layout()) { - return; - } - - QVBoxLayout *main_layout = new QVBoxLayout(this); - main_layout->setMargin(45); - main_layout->setSpacing(40); - - QLabel *text = new QLabel(this); - text->setText(tr("You must accept the Terms and Conditions in order to use sunnypilot.")); - text->setStyleSheet(R"(font-size: 80px; font-weight: 300; margin: 200px;)"); - text->setWordWrap(true); - main_layout->addWidget(text, 0, Qt::AlignCenter); - - QHBoxLayout* buttons = new QHBoxLayout; - buttons->setSpacing(45); - main_layout->addLayout(buttons); - - QPushButton *back_btn = new QPushButton(tr("Back")); - buttons->addWidget(back_btn); - - QObject::connect(back_btn, &QPushButton::clicked, this, &DeclinePage::getBack); - - QPushButton *uninstall_btn = new QPushButton(tr("Decline, uninstall %1").arg(getBrand())); - uninstall_btn->setStyleSheet("background-color: #B73D3D"); - buttons->addWidget(uninstall_btn); - QObject::connect(uninstall_btn, &QPushButton::clicked, [=]() { - Params().putBool("DoUninstall", true); - }); -} - -void OnboardingWindow::updateActiveScreen() { - if (!accepted_terms) { - setCurrentIndex(0); - } else if (!training_done) { - setCurrentIndex(1); - } else { - emit onboardingDone(); - } -} - -OnboardingWindow::OnboardingWindow(QWidget *parent) : QStackedWidget(parent) { - std::string current_terms_version = params.get("TermsVersion"); - std::string current_training_version = params.get("TrainingVersion"); - accepted_terms = params.get("HasAcceptedTerms") == current_terms_version; - training_done = params.get("CompletedTrainingVersion") == current_training_version; - - TermsPage* terms = new TermsPage(this); - addWidget(terms); - connect(terms, &TermsPage::acceptedTerms, [=]() { - params.put("HasAcceptedTerms", current_terms_version); - accepted_terms = true; - updateActiveScreen(); - }); - connect(terms, &TermsPage::declinedTerms, [=]() { setCurrentIndex(2); }); - - TrainingGuide* tr = new TrainingGuide(this); - addWidget(tr); - connect(tr, &TrainingGuide::completedTraining, [=]() { - training_done = true; - params.put("CompletedTrainingVersion", current_training_version); - updateActiveScreen(); - }); - - DeclinePage* declinePage = new DeclinePage(this); - addWidget(declinePage); - connect(declinePage, &DeclinePage::getBack, [=]() { updateActiveScreen(); }); - - setStyleSheet(R"( - * { - color: white; - background-color: black; - } - QPushButton { - height: 160px; - font-size: 55px; - font-weight: 400; - border-radius: 10px; - background-color: #4F4F4F; - } - )"); - updateActiveScreen(); -} diff --git a/selfdrive/ui/qt/offroad/onboarding.h b/selfdrive/ui/qt/offroad/onboarding.h deleted file mode 100644 index 0c6c58e4a7..0000000000 --- a/selfdrive/ui/qt/offroad/onboarding.h +++ /dev/null @@ -1,108 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include - -#include "common/params.h" -#include "selfdrive/ui/qt/qt_window.h" - -class TrainingGuide : public QFrame { - Q_OBJECT - -public: - explicit TrainingGuide(QWidget *parent = 0); - -private: - void showEvent(QShowEvent *event) override; - void paintEvent(QPaintEvent *event) override; - void mouseReleaseEvent(QMouseEvent* e) override; - QImage loadImage(int id); - - QImage image; - QSize image_raw_size; - int currentIndex = 0; - - // Bounding boxes for each training guide step - const QRect continueBtn = {1840, 0, 320, 1080}; - QVector boundingRect { - QRect(112, 804, 618, 164), - continueBtn, - continueBtn, - QRect(1641, 558, 210, 313), - QRect(1662, 528, 184, 108), - continueBtn, - QRect(1814, 621, 211, 170), - QRect(1350, 0, 497, 755), - QRect(1540, 386, 468, 238), - QRect(112, 804, 1126, 164), - QRect(1598, 199, 316, 333), - continueBtn, - QRect(1364, 90, 796, 990), - continueBtn, - QRect(1593, 114, 318, 853), - QRect(1379, 511, 391, 243), - continueBtn, - continueBtn, - QRect(630, 804, 626, 164), - QRect(108, 804, 426, 164), - }; - - const QString img_path = "../assets/training/"; - QElapsedTimer click_timer; - -signals: - void completedTraining(); -}; - - -class TermsPage : public QFrame { - Q_OBJECT - -public: - explicit TermsPage(QWidget *parent = 0) : QFrame(parent) {} - -private: - void showEvent(QShowEvent *event) override; - -protected: - QPushButton *accept_btn; - -signals: - void acceptedTerms(); - void declinedTerms(); -}; - -class DeclinePage : public QFrame { - Q_OBJECT - -public: - explicit DeclinePage(QWidget *parent = 0) : QFrame(parent) {} - -private: - void showEvent(QShowEvent *event) override; - -signals: - void getBack(); -}; - -class OnboardingWindow : public QStackedWidget { - Q_OBJECT - -public: - explicit OnboardingWindow(QWidget *parent = 0); - inline void showTrainingGuide() { setCurrentIndex(1); } - virtual inline bool completed() const { return accepted_terms && training_done; } - -protected: - virtual void updateActiveScreen(); - - Params params; - bool accepted_terms = false, training_done = false; - -signals: - void onboardingDone(); -}; diff --git a/selfdrive/ui/qt/offroad/settings.cc b/selfdrive/ui/qt/offroad/settings.cc deleted file mode 100644 index 6b97342966..0000000000 --- a/selfdrive/ui/qt/offroad/settings.cc +++ /dev/null @@ -1,556 +0,0 @@ -#include -#include -#include -#include -#include - -#include - -#include "common/watchdog.h" -#include "common/util.h" -#include "selfdrive/ui/qt/network/networking.h" -#include "selfdrive/ui/qt/offroad/settings.h" -#include "selfdrive/ui/qt/qt_window.h" -#include "selfdrive/ui/qt/widgets/prime.h" -#include "selfdrive/ui/qt/widgets/scrollview.h" -#include "selfdrive/ui/qt/offroad/developer_panel.h" -#include "selfdrive/ui/qt/offroad/firehose.h" - -TogglesPanel::TogglesPanel(SettingsWindow *parent) : ListWidget(parent) { - // param, title, desc, icon, restart needed - std::vector> toggle_defs{ - { - "OpenpilotEnabledToggle", - tr("Enable sunnypilot"), - tr("Use the sunnypilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature."), - "../assets/icons/chffr_wheel.png", - true, - }, - { - "ExperimentalMode", - tr("Experimental Mode"), - "", - "../assets/icons/experimental_white.svg", - false, - }, - { - "DynamicExperimentalControl", - tr("Enable Dynamic Experimental Control"), - tr("Enable toggle to allow the model to determine when to use sunnypilot ACC or sunnypilot End to End Longitudinal."), - "../assets/offroad/icon_blank.png", - false, - }, - { - "DisengageOnAccelerator", - tr("Disengage on Accelerator Pedal"), - tr("When enabled, pressing the accelerator pedal will disengage sunnypilot."), - "../assets/icons/disengage_on_accelerator.svg", - false, - }, - { - "IsLdwEnabled", - tr("Enable Lane Departure Warnings"), - tr("Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h)."), - "../assets/icons/warning.png", - false, - }, - { - "AlwaysOnDM", - tr("Always-On Driver Monitoring"), - tr("Enable driver monitoring even when sunnypilot is not engaged."), - "../assets/icons/monitoring.png", - false, - }, - { - "RecordFront", - tr("Record and Upload Driver Camera"), - tr("Upload data from the driver facing camera and help improve the driver monitoring algorithm."), - "../assets/icons/monitoring.png", - true, - }, - { - "IsMetric", - tr("Use Metric System"), - tr("Display speed in km/h instead of mph."), - "../assets/icons/metric.png", - false, - }, - }; - - - std::vector longi_button_texts{tr("Aggressive"), tr("Standard"), tr("Relaxed")}; - long_personality_setting = new ButtonParamControl("LongitudinalPersonality", tr("Driving Personality"), - tr("Standard is recommended. In aggressive mode, sunnypilot will follow lead cars closer and be more aggressive with the gas and brake. " - "In relaxed mode sunnypilot will stay further away from lead cars. On supported cars, you can cycle through these personalities with " - "your steering wheel distance button."), - "../assets/icons/speed_limit.png", - longi_button_texts); - - // set up uiState update for personality setting - QObject::connect(uiState(), &UIState::uiUpdate, this, &TogglesPanel::updateState); - - for (auto &[param, title, desc, icon, needs_restart] : toggle_defs) { - auto toggle = new ParamControl(param, title, desc, icon, this); - - bool locked = params.getBool((param + "Lock").toStdString()); - toggle->setEnabled(!locked); - - if (needs_restart && !locked) { - toggle->setDescription(toggle->getDescription() + tr(" Changing this setting will restart openpilot if the car is powered on.")); - - QObject::connect(uiState(), &UIState::engagedChanged, [toggle](bool engaged) { - toggle->setEnabled(!engaged); - }); - - QObject::connect(toggle, &ParamControl::toggleFlipped, [=](bool state) { - params.putBool("OnroadCycleRequested", true); - }); - } - - addItem(toggle); - toggles[param.toStdString()] = toggle; - - // insert longitudinal personality after NDOG toggle - if (param == "DisengageOnAccelerator") { - addItem(long_personality_setting); - } - } - - // Toggles with confirmation dialogs -#ifndef SUNNYPILOT - toggles["ExperimentalMode"]->setActiveIcon("../assets/icons/experimental.svg"); -#endif - toggles["ExperimentalMode"]->setConfirmation(true, true); -} - -void TogglesPanel::updateState(const UIState &s) { - const SubMaster &sm = *(s.sm); - - if (sm.updated("selfdriveState")) { - auto personality = sm["selfdriveState"].getSelfdriveState().getPersonality(); - if (personality != s.scene.personality && s.scene.started && isVisible()) { - long_personality_setting->setCheckedButton(static_cast(personality)); - } - uiState()->scene.personality = personality; - } -} - -void TogglesPanel::expandToggleDescription(const QString ¶m) { - toggles[param.toStdString()]->showDescription(); -} - -void TogglesPanel::scrollToToggle(const QString ¶m) { - if (auto it = toggles.find(param.toStdString()); it != toggles.end()) { - auto scroll_area = qobject_cast(parent()->parent()); - if (scroll_area) { - scroll_area->ensureWidgetVisible(it->second); - } - } -} - -void TogglesPanel::showEvent(QShowEvent *event) { - updateToggles(); -} - -void TogglesPanel::updateToggles() { - auto experimental_mode_toggle = toggles["ExperimentalMode"]; - const QString e2e_description = QString("%1
" - "

%2


" - "%3
" - "

%4


" - "%5
") - .arg(tr("sunnypilot defaults to driving in chill mode. Experimental mode enables alpha-level features that aren't ready for chill mode. Experimental features are listed below:")) - .arg(tr("End-to-End Longitudinal Control")) - .arg(tr("Let the driving model control the gas and brakes. sunnypilot will drive as it thinks a human would, including stopping for red lights and stop signs. " - "Since the driving model decides the speed to drive, the set speed will only act as an upper bound. This is an alpha quality feature; " - "mistakes should be expected.")) - .arg(tr("New Driving Visualization")) - .arg(tr("The driving visualization will transition to the road-facing wide-angle camera at low speeds to better show some turns. The Experimental mode logo will also be shown in the top right corner.")); - - const bool is_release = params.getBool("IsReleaseBranch"); - auto cp_bytes = params.get("CarParamsPersistent"); - if (!cp_bytes.empty()) { - AlignedBuffer aligned_buf; - capnp::FlatArrayMessageReader cmsg(aligned_buf.align(cp_bytes.data(), cp_bytes.size())); - cereal::CarParams::Reader CP = cmsg.getRoot(); - - if (hasLongitudinalControl(CP)) { - // normal description and toggle - experimental_mode_toggle->setEnabled(true); - experimental_mode_toggle->setDescription(e2e_description); - long_personality_setting->setEnabled(true); - } else { - // no long for now - experimental_mode_toggle->setEnabled(false); - long_personality_setting->setEnabled(false); - params.remove("ExperimentalMode"); - - const QString unavailable = tr("Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control."); - - QString long_desc = unavailable + " " + \ - tr("openpilot longitudinal control may come in a future update."); - if (CP.getAlphaLongitudinalAvailable()) { - if (is_release) { - long_desc = unavailable + " " + tr("An alpha version of sunnypilot longitudinal control can be tested, along with Experimental mode, on non-release branches."); - } else { - long_desc = tr("Enable the sunnypilot longitudinal control (alpha) toggle to allow Experimental mode."); - } - } - experimental_mode_toggle->setDescription("" + long_desc + "

" + e2e_description); - } - - experimental_mode_toggle->refresh(); - } else { - experimental_mode_toggle->setDescription(e2e_description); - } -} - -DevicePanel::DevicePanel(SettingsWindow *parent) : ListWidget(parent) { - setSpacing(50); - addItem(new LabelControl(tr("Dongle ID"), getDongleId().value_or(tr("N/A")))); - addItem(new LabelControl(tr("Serial"), params.get("HardwareSerial").c_str())); - - pair_device = new ButtonControl(tr("Pair Device"), tr("PAIR"), - tr("Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer.")); - connect(pair_device, &ButtonControl::clicked, [=]() { - PairingPopup popup(this); - popup.exec(); - }); - addItem(pair_device); - - QObject::connect(uiState()->prime_state, &PrimeState::changed, [this] (PrimeState::Type type) { - pair_device->setVisible(type == PrimeState::PRIME_TYPE_UNPAIRED); - }); - -#ifndef SUNNYPILOT - // offroad-only buttons - - auto dcamBtn = new ButtonControl(tr("Driver Camera"), tr("PREVIEW"), - tr("Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off)")); - connect(dcamBtn, &ButtonControl::clicked, [=]() { emit showDriverView(); }); - addItem(dcamBtn); -#endif - - resetCalibBtn = new ButtonControl(tr("Reset Calibration"), tr("RESET"), ""); - connect(resetCalibBtn, &ButtonControl::showDescriptionEvent, this, &DevicePanel::updateCalibDescription); - connect(resetCalibBtn, &ButtonControl::clicked, [&]() { - if (!uiState()->engaged()) { - if (ConfirmationDialog::confirm(tr("Are you sure you want to reset calibration?"), tr("Reset"), this)) { - // Check engaged again in case it changed while the dialog was open - if (!uiState()->engaged()) { - params.remove("CalibrationParams"); - params.remove("LiveTorqueParameters"); - params.remove("LiveParameters"); - params.remove("LiveParametersV2"); - params.remove("LiveDelay"); - params.putBool("OnroadCycleRequested", true); - updateCalibDescription(); - } - } - } else { - ConfirmationDialog::alert(tr("Disengage to Reset Calibration"), this); - } - }); - addItem(resetCalibBtn); - -#ifndef SUNNYPILOT - auto retrainingBtn = new ButtonControl(tr("Review Training Guide"), tr("REVIEW"), tr("Review the rules, features, and limitations of sunnypilot")); - connect(retrainingBtn, &ButtonControl::clicked, [=]() { - if (ConfirmationDialog::confirm(tr("Are you sure you want to review the training guide?"), tr("Review"), this)) { - emit reviewTrainingGuide(); - } - }); - addItem(retrainingBtn); - - if (Hardware::TICI()) { - auto regulatoryBtn = new ButtonControl(tr("Regulatory"), tr("VIEW"), ""); - connect(regulatoryBtn, &ButtonControl::clicked, [=]() { - const std::string txt = util::read_file("../assets/offroad/fcc.html"); - ConfirmationDialog::rich(QString::fromStdString(txt), this); - }); - addItem(regulatoryBtn); - } - - auto translateBtn = new ButtonControl(tr("Change Language"), tr("CHANGE"), ""); - connect(translateBtn, &ButtonControl::clicked, [=]() { - QMap langs = getSupportedLanguages(); - QString selection = MultiOptionDialog::getSelection(tr("Select a language"), langs.keys(), langs.key(uiState()->language), this); - if (!selection.isEmpty()) { - // put language setting, exit Qt UI, and trigger fast restart - params.put("LanguageSetting", langs[selection].toStdString()); - qApp->exit(18); - watchdog_kick(0); - } - }); - addItem(translateBtn); -#endif - - QObject::connect(uiState(), &UIState::offroadTransition, [=](bool offroad) { - for (auto btn : findChildren()) { - if (btn != pair_device && btn != resetCalibBtn) { - btn->setEnabled(offroad); - } - } - }); - -#ifndef SUNNYPILOT - // power buttons - QHBoxLayout *power_layout = new QHBoxLayout(); - power_layout->setSpacing(30); - - QPushButton *reboot_btn = new QPushButton(tr("Reboot")); - reboot_btn->setObjectName("reboot_btn"); - power_layout->addWidget(reboot_btn); - QObject::connect(reboot_btn, &QPushButton::clicked, this, &DevicePanel::reboot); - - QPushButton *poweroff_btn = new QPushButton(tr("Power Off")); - poweroff_btn->setObjectName("poweroff_btn"); - power_layout->addWidget(poweroff_btn); - QObject::connect(poweroff_btn, &QPushButton::clicked, this, &DevicePanel::poweroff); - - if (!Hardware::PC()) { - connect(uiState(), &UIState::offroadTransition, poweroff_btn, &QPushButton::setVisible); - } - - setStyleSheet(R"( - #reboot_btn { height: 120px; border-radius: 15px; background-color: #393939; } - #reboot_btn:pressed { background-color: #4a4a4a; } - #poweroff_btn { height: 120px; border-radius: 15px; background-color: #E22C2C; } - #poweroff_btn:pressed { background-color: #FF2424; } - )"); - addItem(power_layout); -#endif -} - -void DevicePanel::updateCalibDescription() { - QString desc = tr("sunnypilot requires the device to be mounted within 4° left or right and within 5° up or 9° down."); - std::string calib_bytes = params.get("CalibrationParams"); - if (!calib_bytes.empty()) { - try { - AlignedBuffer aligned_buf; - capnp::FlatArrayMessageReader cmsg(aligned_buf.align(calib_bytes.data(), calib_bytes.size())); - auto calib = cmsg.getRoot().getLiveCalibration(); - if (calib.getCalStatus() != cereal::LiveCalibrationData::Status::UNCALIBRATED) { - double pitch = calib.getRpyCalib()[1] * (180 / M_PI); - double yaw = calib.getRpyCalib()[2] * (180 / M_PI); - desc += tr(" Your device is pointed %1° %2 and %3° %4.") - .arg(QString::number(std::abs(pitch), 'g', 1), pitch > 0 ? tr("down") : tr("up"), - QString::number(std::abs(yaw), 'g', 1), yaw > 0 ? tr("left") : tr("right")); - } - } catch (kj::Exception) { - qInfo() << "invalid CalibrationParams"; - } - } - - const bool is_release = params.getBool("IsReleaseBranch"); - if (!is_release) { - int lag_perc = 0; - std::string lag_bytes = params.get("LiveDelay"); - if (!lag_bytes.empty()) { - try { - AlignedBuffer aligned_buf; - capnp::FlatArrayMessageReader cmsg(aligned_buf.align(lag_bytes.data(), lag_bytes.size())); - lag_perc = cmsg.getRoot().getLiveDelay().getCalPerc(); - } catch (kj::Exception) { - qInfo() << "invalid LiveDelay"; - } - } - desc += "\n\n"; - if (lag_perc < 100) { - desc += tr("Steering lag calibration is %1% complete.").arg(lag_perc); - } else { - desc += tr("Steering lag calibration is complete."); - } - } - - std::string torque_bytes = params.get("LiveTorqueParameters"); - if (!torque_bytes.empty()) { - try { - AlignedBuffer aligned_buf; - capnp::FlatArrayMessageReader cmsg(aligned_buf.align(torque_bytes.data(), torque_bytes.size())); - auto torque = cmsg.getRoot().getLiveTorqueParameters(); - // don't add for non-torque cars - if (torque.getUseParams()) { - int torque_perc = torque.getCalPerc(); - desc += is_release ? "\n\n" : " "; - if (torque_perc < 100) { - desc += tr("Steering torque response calibration is %1% complete.").arg(torque_perc); - } else { - desc += tr("Steering torque response calibration is complete."); - } - } - } catch (kj::Exception) { - qInfo() << "invalid LiveTorqueParameters"; - } - } - - desc += "\n\n"; - desc += tr("openpilot is continuously calibrating, resetting is rarely required. " - "Resetting calibration will restart openpilot if the car is powered on."); - resetCalibBtn->setDescription(desc); -} - -void DevicePanel::reboot() { - if (!uiState()->engaged()) { - if (ConfirmationDialog::confirm(tr("Are you sure you want to reboot?"), tr("Reboot"), this)) { - // Check engaged again in case it changed while the dialog was open - if (!uiState()->engaged()) { - params.putBool("DoReboot", true); - } - } - } else { - ConfirmationDialog::alert(tr("Disengage to Reboot"), this); - } -} - -void DevicePanel::poweroff() { - if (!uiState()->engaged()) { - if (ConfirmationDialog::confirm(tr("Are you sure you want to power off?"), tr("Power Off"), this)) { - // Check engaged again in case it changed while the dialog was open - if (!uiState()->engaged()) { - params.putBool("DoShutdown", true); - } - } - } else { - ConfirmationDialog::alert(tr("Disengage to Power Off"), this); - } -} - -void SettingsWindow::showEvent(QShowEvent *event) { - setCurrentPanel(0); -} - -void SettingsWindow::setCurrentPanel(int index, const QString ¶m) { - if (!param.isEmpty()) { - // Check if param ends with "Panel" to determine if it's a panel name - if (param.endsWith("Panel")) { - QString panelName = param; - panelName.chop(5); // Remove "Panel" suffix - - // Find the panel by name - for (int i = 0; i < nav_btns->buttons().size(); i++) { - bool panel_trimmed = false; -#ifdef SUNNYPILOT - panel_trimmed = nav_btns->buttons()[i]->text().trimmed() == tr(panelName.toStdString().c_str()); -#endif - if ((nav_btns->buttons()[i]->text() == tr(panelName.toStdString().c_str())) || panel_trimmed) { - index = i; - break; - } - } - } else { - emit expandToggleDescription(param); - emit scrollToToggle(param); - } - } - - panel_widget->setCurrentIndex(index); - nav_btns->buttons()[index]->setChecked(true); -} - -SettingsWindow::SettingsWindow(QWidget *parent) : QFrame(parent) { -#ifndef SUNNYPILOT - // setup two main layouts - sidebar_widget = new QWidget; - QVBoxLayout *sidebar_layout = new QVBoxLayout(sidebar_widget); - panel_widget = new QStackedWidget(); - - // close button - QPushButton *close_btn = new QPushButton(tr("×")); - close_btn->setStyleSheet(R"( - QPushButton { - font-size: 140px; - padding-bottom: 20px; - border-radius: 100px; - background-color: #292929; - font-weight: 400; - } - QPushButton:pressed { - background-color: #3B3B3B; - } - )"); - close_btn->setFixedSize(200, 200); - sidebar_layout->addSpacing(45); - sidebar_layout->addWidget(close_btn, 0, Qt::AlignCenter); - QObject::connect(close_btn, &QPushButton::clicked, this, &SettingsWindow::closeSettings); - - // setup panels - DevicePanel *device = new DevicePanel(this); - QObject::connect(device, &DevicePanel::reviewTrainingGuide, this, &SettingsWindow::reviewTrainingGuide); - QObject::connect(device, &DevicePanel::showDriverView, this, &SettingsWindow::showDriverView); - - TogglesPanel *toggles = new TogglesPanel(this); - QObject::connect(this, &SettingsWindow::expandToggleDescription, toggles, &TogglesPanel::expandToggleDescription); - QObject::connect(this, &SettingsWindow::scrollToToggle, toggles, &TogglesPanel::scrollToToggle); - - auto networking = new Networking(this); - QObject::connect(uiState()->prime_state, &PrimeState::changed, networking, &Networking::setPrimeType); - - QList> panels = { - {tr("Device"), device}, - {tr("Network"), networking}, - {tr("Toggles"), toggles}, - {tr("Software"), new SoftwarePanel(this)}, - {tr("Firehose"), new FirehosePanel(this)}, - {tr("Developer"), new DeveloperPanel(this)}, - }; - - nav_btns = new QButtonGroup(this); - for (auto &[name, panel] : panels) { - QPushButton *btn = new QPushButton(name); - btn->setCheckable(true); - btn->setChecked(nav_btns->buttons().size() == 0); - btn->setStyleSheet(R"( - QPushButton { - color: grey; - border: none; - background: none; - font-size: 65px; - font-weight: 500; - } - QPushButton:checked { - color: white; - } - QPushButton:pressed { - color: #ADADAD; - } - )"); - btn->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding); - nav_btns->addButton(btn); - sidebar_layout->addWidget(btn, 0, Qt::AlignRight); - - const int lr_margin = name != tr("Network") ? 50 : 0; // Network panel handles its own margins - panel->setContentsMargins(lr_margin, 25, lr_margin, 25); - - ScrollView *panel_frame = new ScrollView(panel, this); - panel_widget->addWidget(panel_frame); - - QObject::connect(btn, &QPushButton::clicked, [=, w = panel_frame]() { - btn->setChecked(true); - panel_widget->setCurrentWidget(w); - }); - } - sidebar_layout->setContentsMargins(50, 50, 100, 50); - - // main settings layout, sidebar + main panel - QHBoxLayout *main_layout = new QHBoxLayout(this); - - sidebar_widget->setFixedWidth(500); - main_layout->addWidget(sidebar_widget); - main_layout->addWidget(panel_widget); - - setStyleSheet(R"( - * { - color: white; - font-size: 50px; - } - SettingsWindow { - background-color: black; - } - QStackedWidget, ScrollView { - background-color: #292929; - border-radius: 30px; - } - )"); -#endif -} diff --git a/selfdrive/ui/qt/offroad/settings.h b/selfdrive/ui/qt/offroad/settings.h deleted file mode 100644 index a11a300128..0000000000 --- a/selfdrive/ui/qt/offroad/settings.h +++ /dev/null @@ -1,118 +0,0 @@ -#pragma once - -#include -#include - -#include -#include -#include -#include -#include -#include - -#include "selfdrive/ui/qt/util.h" - -#ifdef SUNNYPILOT -#include "selfdrive/ui/sunnypilot/ui.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/controls.h" -#define ListWidget ListWidgetSP -#define ParamControl ParamControlSP -#define ButtonControl ButtonControlSP -#define ButtonParamControl ButtonParamControlSP -#define ToggleControl ToggleControlSP -#define LabelControl LabelControlSP -#else -#include "selfdrive/ui/ui.h" -#include "selfdrive/ui/qt/widgets/controls.h" -#endif - -// ********** settings window + top-level panels ********** -class SettingsWindow : public QFrame { - Q_OBJECT - -public: - explicit SettingsWindow(QWidget *parent = 0); - void setCurrentPanel(int index, const QString ¶m = ""); - -protected: - void showEvent(QShowEvent *event) override; - -signals: - void closeSettings(); - void reviewTrainingGuide(); - void showDriverView(); - void expandToggleDescription(const QString ¶m); - void scrollToToggle(const QString ¶m); - -protected: - QPushButton *sidebar_alert_widget; - QWidget *sidebar_widget; - QButtonGroup *nav_btns; - QStackedWidget *panel_widget; -}; - -class DevicePanel : public ListWidget { - Q_OBJECT -public: - explicit DevicePanel(SettingsWindow *parent); - -signals: - void reviewTrainingGuide(); - void showDriverView(); - -protected slots: - void poweroff(); - void reboot(); - void updateCalibDescription(); - -protected: - Params params; - ButtonControl *pair_device; - ButtonControl *resetCalibBtn; -}; - -class TogglesPanel : public ListWidget { - Q_OBJECT -public: - explicit TogglesPanel(SettingsWindow *parent); - void showEvent(QShowEvent *event) override; - -public slots: - void expandToggleDescription(const QString ¶m); - void scrollToToggle(const QString ¶m); - -protected slots: - virtual void updateState(const UIState &s); - -protected: - Params params; - std::map toggles; - ButtonParamControl *long_personality_setting; - - virtual void updateToggles(); -}; - -class SoftwarePanel : public ListWidget { - Q_OBJECT -public: - explicit SoftwarePanel(QWidget* parent = nullptr); - -protected: - void showEvent(QShowEvent *event) override; - virtual void updateLabels(); - void checkForUpdates(); - - bool is_onroad = false; - - QLabel *onroadLbl; - LabelControl *versionLbl; - ButtonControl *installBtn; - ButtonControl *downloadBtn; - ButtonControl *targetBranchBtn; - - Params params; - ParamWatcher *fs_watch; -}; - -// Forward declaration -class FirehosePanel; diff --git a/selfdrive/ui/qt/offroad/software_settings.cc b/selfdrive/ui/qt/offroad/software_settings.cc deleted file mode 100644 index 449f3c5203..0000000000 --- a/selfdrive/ui/qt/offroad/software_settings.cc +++ /dev/null @@ -1,154 +0,0 @@ -#include "selfdrive/ui/qt/offroad/settings.h" - -#include -#include -#include - -#include -#include - -#include "common/params.h" -#include "common/util.h" -#include "selfdrive/ui/ui.h" -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/qt/widgets/controls.h" -#include "selfdrive/ui/qt/widgets/input.h" -#include "system/hardware/hw.h" - - -void SoftwarePanel::checkForUpdates() { - std::system("pkill -SIGUSR1 -f system.updated.updated"); -} - -SoftwarePanel::SoftwarePanel(QWidget* parent) : ListWidget(parent) { - onroadLbl = new QLabel(tr("Updates are only downloaded while the car is off.")); - onroadLbl->setStyleSheet("font-size: 50px; font-weight: 400; text-align: left; padding-top: 30px; padding-bottom: 30px;"); - addItem(onroadLbl); - - // current version - versionLbl = new LabelControl(tr("Current Version"), ""); - addItem(versionLbl); - - // download update btn - downloadBtn = new ButtonControl(tr("Download"), tr("CHECK")); - connect(downloadBtn, &ButtonControl::clicked, [=]() { - downloadBtn->setEnabled(false); - if (downloadBtn->text() == tr("CHECK")) { - checkForUpdates(); - } else { - std::system("pkill -SIGHUP -f system.updated.updated"); - } - }); - addItem(downloadBtn); - - // install update btn - installBtn = new ButtonControl(tr("Install Update"), tr("INSTALL")); - connect(installBtn, &ButtonControl::clicked, [=]() { - installBtn->setEnabled(false); - params.putBool("DoReboot", true); - }); - addItem(installBtn); - - // branch selecting - targetBranchBtn = new ButtonControl(tr("Target Branch"), tr("SELECT")); - connect(targetBranchBtn, &ButtonControl::clicked, [=]() { - auto current = params.get("GitBranch"); - QStringList branches = QString::fromStdString(params.get("UpdaterAvailableBranches")).split(","); - for (QString b : {current.c_str(), "devel-staging", "devel", "nightly", "nightly-dev", "master"}) { - auto i = branches.indexOf(b); - if (i >= 0) { - branches.removeAt(i); - branches.insert(0, b); - } - } - - QString cur = QString::fromStdString(params.get("UpdaterTargetBranch")); - QString selection = MultiOptionDialog::getSelection(tr("Select a branch"), branches, cur, this); - if (!selection.isEmpty()) { - params.put("UpdaterTargetBranch", selection.toStdString()); - targetBranchBtn->setValue(QString::fromStdString(params.get("UpdaterTargetBranch"))); - checkForUpdates(); - } - }); - addItem(targetBranchBtn); - - // uninstall button - auto uninstallBtn = new ButtonControl(tr("Uninstall %1").arg(getBrand()), tr("UNINSTALL")); - connect(uninstallBtn, &ButtonControl::clicked, [&]() { - if (ConfirmationDialog::confirm(tr("Are you sure you want to uninstall?"), tr("Uninstall"), this)) { - params.putBool("DoUninstall", true); - } - }); - addItem(uninstallBtn); - - fs_watch = new ParamWatcher(this); - QObject::connect(fs_watch, &ParamWatcher::paramChanged, [=](const QString ¶m_name, const QString ¶m_value) { - updateLabels(); - }); - - connect(uiState(), &UIState::offroadTransition, [=](bool offroad) { - is_onroad = !offroad; - updateLabels(); - }); - - updateLabels(); -} - -void SoftwarePanel::showEvent(QShowEvent *event) { - // nice for testing on PC - installBtn->setEnabled(true); - - updateLabels(); -} - -void SoftwarePanel::updateLabels() { - // add these back in case the files got removed - fs_watch->addParam("LastUpdateTime"); - fs_watch->addParam("UpdateFailedCount"); - fs_watch->addParam("UpdaterState"); - fs_watch->addParam("UpdateAvailable"); - - if (!isVisible()) { - return; - } - - // updater only runs offroad - onroadLbl->setVisible(is_onroad); - downloadBtn->setVisible(!is_onroad); - - // download update - QString updater_state = QString::fromStdString(params.get("UpdaterState")); - bool failed = std::atoi(params.get("UpdateFailedCount").c_str()) > 0; - if (updater_state != "idle") { - downloadBtn->setEnabled(false); - downloadBtn->setValue(updater_state); - } else { - if (failed) { - downloadBtn->setText(tr("CHECK")); - downloadBtn->setValue(tr("failed to check for update")); - } else if (params.getBool("UpdaterFetchAvailable")) { - downloadBtn->setText(tr("DOWNLOAD")); - downloadBtn->setValue(tr("update available")); - } else { - QString lastUpdate = tr("never"); - auto tm = params.get("LastUpdateTime"); - if (!tm.empty()) { - lastUpdate = timeAgo(QDateTime::fromString(QString::fromStdString(tm + "Z"), Qt::ISODate)); - } - downloadBtn->setText(tr("CHECK")); - downloadBtn->setValue(tr("up to date, last checked %1").arg(lastUpdate)); - } - downloadBtn->setEnabled(true); - } - targetBranchBtn->setValue(QString::fromStdString(params.get("UpdaterTargetBranch"))); - - // current + new versions - versionLbl->setText(QString::fromStdString(params.get("UpdaterCurrentDescription"))); - versionLbl->setDescription(QString::fromStdString(params.get("UpdaterCurrentReleaseNotes"))); - - installBtn->setVisible(!is_onroad && params.getBool("UpdateAvailable")); - installBtn->setValue(QString::fromStdString(params.get("UpdaterNewDescription"))); - installBtn->setDescription(QString::fromStdString(params.get("UpdaterNewReleaseNotes"))); - - update(); -} diff --git a/selfdrive/ui/qt/onroad/alerts.cc b/selfdrive/ui/qt/onroad/alerts.cc deleted file mode 100644 index d6829c6b08..0000000000 --- a/selfdrive/ui/qt/onroad/alerts.cc +++ /dev/null @@ -1,112 +0,0 @@ -#include "selfdrive/ui/qt/onroad/alerts.h" - -#include -#include - -#include "selfdrive/ui/qt/util.h" - -void OnroadAlerts::updateState(const UIState &s) { - Alert a = getAlert(*(s.sm), s.scene.started_frame); - if (!alert.equal(a)) { - alert = a; - update(); - } -} - -void OnroadAlerts::clear() { - alert = {}; - update(); -} - -OnroadAlerts::Alert OnroadAlerts::getAlert(const SubMaster &sm, uint64_t started_frame) { - const cereal::SelfdriveState::Reader &ss = sm["selfdriveState"].getSelfdriveState(); - const uint64_t selfdrive_frame = sm.rcv_frame("selfdriveState"); - - Alert a = {}; - if (selfdrive_frame >= started_frame) { // Don't get old alert. - a = {ss.getAlertText1().cStr(), ss.getAlertText2().cStr(), - ss.getAlertType().cStr(), ss.getAlertSize(), ss.getAlertStatus()}; - } - - if (!sm.updated("selfdriveState") && (sm.frame - started_frame) > 5 * UI_FREQ) { - const int SELFDRIVE_STATE_TIMEOUT = 5; - const int ss_missing = (nanos_since_boot() - sm.rcv_time("selfdriveState")) / 1e9; - - // Handle selfdrive timeout - if (selfdrive_frame < started_frame) { - // car is started, but selfdriveState hasn't been seen at all - a = {tr("sunnypilot Unavailable"), tr("Waiting to start"), - "selfdriveWaiting", cereal::SelfdriveState::AlertSize::MID, - cereal::SelfdriveState::AlertStatus::NORMAL}; - } else if (ss_missing > SELFDRIVE_STATE_TIMEOUT && !Hardware::PC()) { - // car is started, but selfdrive is lagging or died - if (ss.getEnabled() && (ss_missing - SELFDRIVE_STATE_TIMEOUT) < 10) { - a = {tr("TAKE CONTROL IMMEDIATELY"), tr("System Unresponsive"), - "selfdriveUnresponsive", cereal::SelfdriveState::AlertSize::FULL, - cereal::SelfdriveState::AlertStatus::CRITICAL}; - } else { - a = {tr("System Unresponsive"), tr("Reboot Device"), - "selfdriveUnresponsivePermanent", cereal::SelfdriveState::AlertSize::MID, - cereal::SelfdriveState::AlertStatus::NORMAL}; - } - } - } - return a; -} - -void OnroadAlerts::paintEvent(QPaintEvent *event) { - if (alert.size == cereal::SelfdriveState::AlertSize::NONE) { - return; - } - static std::map alert_heights = { - {cereal::SelfdriveState::AlertSize::SMALL, 271}, - {cereal::SelfdriveState::AlertSize::MID, 420}, - {cereal::SelfdriveState::AlertSize::FULL, height()}, - }; - int h = alert_heights[alert.size]; - - int margin = 40; - int radius = 30; - if (alert.size == cereal::SelfdriveState::AlertSize::FULL) { - margin = 0; - radius = 0; - } - QRect r = QRect(0 + margin, height() - h + margin, width() - margin*2, h - margin*2); - - QPainter p(this); - - // draw background + gradient - p.setPen(Qt::NoPen); - p.setCompositionMode(QPainter::CompositionMode_SourceOver); - p.setBrush(QBrush(alert_colors[alert.status])); - p.drawRoundedRect(r, radius, radius); - - QLinearGradient g(0, r.y(), 0, r.bottom()); - g.setColorAt(0, QColor::fromRgbF(0, 0, 0, 0.05)); - g.setColorAt(1, QColor::fromRgbF(0, 0, 0, 0.35)); - - p.setCompositionMode(QPainter::CompositionMode_DestinationOver); - p.setBrush(QBrush(g)); - p.drawRoundedRect(r, radius, radius); - p.setCompositionMode(QPainter::CompositionMode_SourceOver); - - // text - const QPoint c = r.center(); - p.setPen(QColor(0xff, 0xff, 0xff)); - p.setRenderHint(QPainter::TextAntialiasing); - if (alert.size == cereal::SelfdriveState::AlertSize::SMALL) { - p.setFont(InterFont(74, QFont::DemiBold)); - p.drawText(r, Qt::AlignCenter, alert.text1); - } else if (alert.size == cereal::SelfdriveState::AlertSize::MID) { - p.setFont(InterFont(88, QFont::Bold)); - p.drawText(QRect(0, c.y() - 125, width(), 150), Qt::AlignHCenter | Qt::AlignTop, alert.text1); - p.setFont(InterFont(66)); - p.drawText(QRect(0, c.y() + 21, width(), 90), Qt::AlignHCenter, alert.text2); - } else if (alert.size == cereal::SelfdriveState::AlertSize::FULL) { - bool l = alert.text1.length() > 15; - p.setFont(InterFont(l ? 132 : 177, QFont::Bold)); - p.drawText(QRect(0, r.y() + (l ? 240 : 270), width(), 600), Qt::AlignHCenter | Qt::TextWordWrap, alert.text1); - p.setFont(InterFont(88)); - p.drawText(QRect(0, r.height() - (l ? 361 : 420), width(), 300), Qt::AlignHCenter | Qt::TextWordWrap, alert.text2); - } -} diff --git a/selfdrive/ui/qt/onroad/alerts.h b/selfdrive/ui/qt/onroad/alerts.h deleted file mode 100644 index de38d8ffc3..0000000000 --- a/selfdrive/ui/qt/onroad/alerts.h +++ /dev/null @@ -1,39 +0,0 @@ -#pragma once - -#include - -#include "selfdrive/ui/ui.h" - -class OnroadAlerts : public QWidget { - Q_OBJECT - -public: - OnroadAlerts(QWidget *parent = 0) : QWidget(parent) {} - void updateState(const UIState &s); - void clear(); - -protected: - struct Alert { - QString text1; - QString text2; - QString type; - cereal::SelfdriveState::AlertSize size; - cereal::SelfdriveState::AlertStatus status; - - bool equal(const Alert &other) const { - return text1 == other.text1 && text2 == other.text2 && type == other.type; - } - }; - - const QMap alert_colors = { - {cereal::SelfdriveState::AlertStatus::NORMAL, QColor(0x15, 0x15, 0x15, 0xf1)}, - {cereal::SelfdriveState::AlertStatus::USER_PROMPT, QColor(0xDA, 0x6F, 0x25, 0xf1)}, - {cereal::SelfdriveState::AlertStatus::CRITICAL, QColor(0xC9, 0x22, 0x31, 0xf1)}, - }; - - void paintEvent(QPaintEvent*) override; - OnroadAlerts::Alert getAlert(const SubMaster &sm, uint64_t started_frame); - - QColor bg; - Alert alert = {}; -}; diff --git a/selfdrive/ui/qt/onroad/annotated_camera.cc b/selfdrive/ui/qt/onroad/annotated_camera.cc deleted file mode 100644 index f504ad69f1..0000000000 --- a/selfdrive/ui/qt/onroad/annotated_camera.cc +++ /dev/null @@ -1,157 +0,0 @@ - -#include "selfdrive/ui/qt/onroad/annotated_camera.h" - -#include -#include -#include - -#include "common/swaglog.h" -#include "selfdrive/ui/qt/util.h" - -// Window that shows camera view and variety of info drawn on top -AnnotatedCameraWidget::AnnotatedCameraWidget(VisionStreamType type, QWidget *parent) - : fps_filter(UI_FREQ, 3, 1. / UI_FREQ), CameraWidget("camerad", type, parent) { - pm = std::make_unique(std::vector{"uiDebug"}); - - main_layout = new QVBoxLayout(this); - main_layout->setMargin(UI_BORDER_SIZE); - main_layout->setSpacing(0); - - experimental_btn = new ExperimentalButton(this); - main_layout->addWidget(experimental_btn, 0, Qt::AlignTop | Qt::AlignRight); -} - -void AnnotatedCameraWidget::updateState(const UIState &s) { - // update engageability/experimental mode button - experimental_btn->updateState(s); - dmon.updateState(s); -} - -void AnnotatedCameraWidget::initializeGL() { - CameraWidget::initializeGL(); - qInfo() << "OpenGL version:" << QString((const char*)glGetString(GL_VERSION)); - qInfo() << "OpenGL vendor:" << QString((const char*)glGetString(GL_VENDOR)); - qInfo() << "OpenGL renderer:" << QString((const char*)glGetString(GL_RENDERER)); - qInfo() << "OpenGL language version:" << QString((const char*)glGetString(GL_SHADING_LANGUAGE_VERSION)); - - prev_draw_t = millis_since_boot(); - setBackgroundColor(bg_colors[STATUS_DISENGAGED]); -} - -mat4 AnnotatedCameraWidget::calcFrameMatrix() { - // Project point at "infinity" to compute x and y offsets - // to ensure this ends up in the middle of the screen - // for narrow come and a little lower for wide cam. - // TODO: use proper perspective transform? - - // Select intrinsic matrix and calibration based on camera type - auto *s = uiState(); - bool wide_cam = active_stream_type == VISION_STREAM_WIDE_ROAD; - const auto &intrinsic_matrix = wide_cam ? ECAM_INTRINSIC_MATRIX : FCAM_INTRINSIC_MATRIX; - const auto &calibration = wide_cam ? s->scene.view_from_wide_calib : s->scene.view_from_calib; - - // Compute the calibration transformation matrix - const auto calib_transform = intrinsic_matrix * calibration; - - float zoom = wide_cam ? 2.0 : 1.1; - Eigen::Vector3f inf(1000., 0., 0.); - auto Kep = calib_transform * inf; - - int w = width(), h = height(); - float center_x = intrinsic_matrix(0, 2); - float center_y = intrinsic_matrix(1, 2); - - float max_x_offset = center_x * zoom - w / 2 - 5; - float max_y_offset = center_y * zoom - h / 2 - 5; - float x_offset = std::clamp((Kep.x() / Kep.z() - center_x) * zoom, -max_x_offset, max_x_offset); - float y_offset = std::clamp((Kep.y() / Kep.z() - center_y) * zoom, -max_y_offset, max_y_offset); - - // Apply transformation such that video pixel coordinates match video - // 1) Put (0, 0) in the middle of the video - // 2) Apply same scaling as video - // 3) Put (0, 0) in top left corner of video - Eigen::Matrix3f video_transform =(Eigen::Matrix3f() << - zoom, 0.0f, (w / 2 - x_offset) - (center_x * zoom), - 0.0f, zoom, (h / 2 - y_offset) - (center_y * zoom), - 0.0f, 0.0f, 1.0f).finished(); - - model.setTransform(video_transform * calib_transform); - - float zx = zoom * 2 * center_x / w; - float zy = zoom * 2 * center_y / h; - return mat4{{ - zx, 0.0, 0.0, -x_offset / w * 2, - 0.0, zy, 0.0, y_offset / h * 2, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0, - }}; -} - -void AnnotatedCameraWidget::paintGL() { - UIState *s = uiState(); - SubMaster &sm = *(s->sm); - const double start_draw_t = millis_since_boot(); - - // draw camera frame - { - std::lock_guard lk(frame_lock); - - if (frames.empty()) { - if (skip_frame_count > 0) { - skip_frame_count--; - qDebug() << "skipping frame, not ready"; - return; - } - } else { - // skip drawing up to this many frames if we're - // missing camera frames. this smooths out the - // transitions from the narrow and wide cameras - skip_frame_count = 5; - } - - // Wide or narrow cam dependent on speed - bool has_wide_cam = available_streams.count(VISION_STREAM_WIDE_ROAD); - if (has_wide_cam) { - float v_ego = sm["carState"].getCarState().getVEgo(); - if ((v_ego < 10) || available_streams.size() == 1) { - wide_cam_requested = true; - } else if (v_ego > 15) { - wide_cam_requested = false; - } - wide_cam_requested = wide_cam_requested && sm["selfdriveState"].getSelfdriveState().getExperimentalMode(); - } - CameraWidget::setStreamType(wide_cam_requested ? VISION_STREAM_WIDE_ROAD : VISION_STREAM_ROAD); - CameraWidget::setFrameId(sm["modelV2"].getModelV2().getFrameId()); - CameraWidget::paintGL(); - } - - QPainter painter(this); - painter.setRenderHint(QPainter::Antialiasing); - painter.setPen(Qt::NoPen); - - model.draw(painter, rect()); - dmon.draw(painter, rect()); - hud.updateState(*s); - hud.draw(painter, rect()); - - double cur_draw_t = millis_since_boot(); - double dt = cur_draw_t - prev_draw_t; - double fps = fps_filter.update(1. / dt * 1000); - if (fps < 15) { - LOGW("slow frame rate: %.2f fps", fps); - } - prev_draw_t = cur_draw_t; - - // publish debug msg - MessageBuilder msg; - auto m = msg.initEvent().initUiDebug(); - m.setDrawTimeMillis(cur_draw_t - start_draw_t); - pm->send("uiDebug", msg); -} - -void AnnotatedCameraWidget::showEvent(QShowEvent *event) { - CameraWidget::showEvent(event); - - ui_update_params(uiState()); - prev_draw_t = millis_since_boot(); -} diff --git a/selfdrive/ui/qt/onroad/annotated_camera.h b/selfdrive/ui/qt/onroad/annotated_camera.h deleted file mode 100644 index e3ca837907..0000000000 --- a/selfdrive/ui/qt/onroad/annotated_camera.h +++ /dev/null @@ -1,47 +0,0 @@ -#pragma once - -#include -#include -#include "selfdrive/ui/qt/onroad/driver_monitoring.h" -#include "selfdrive/ui/qt/onroad/model.h" -#include "selfdrive/ui/qt/widgets/cameraview.h" - -#ifdef SUNNYPILOT -#include "selfdrive/ui/sunnypilot/qt/onroad/buttons.h" -#include "selfdrive/ui/sunnypilot/qt/onroad/hud.h" -#include "selfdrive/ui/sunnypilot/qt/onroad/model.h" -#define ExperimentalButton ExperimentalButtonSP -#define ModelRenderer ModelRendererSP -#else -#include "selfdrive/ui/qt/onroad/buttons.h" -#include "selfdrive/ui/qt/onroad/hud.h" -#endif - -class AnnotatedCameraWidget : public CameraWidget { - Q_OBJECT - -public: - explicit AnnotatedCameraWidget(VisionStreamType type, QWidget* parent = 0); - virtual ~AnnotatedCameraWidget() = default; - virtual void updateState(const UIState &s); - -private: - QVBoxLayout *main_layout; - ExperimentalButton *experimental_btn; - DriverMonitorRenderer dmon; - HudRenderer hud; - ModelRenderer model; - std::unique_ptr pm; - - int skip_frame_count = 0; - bool wide_cam_requested = false; - -protected: - void paintGL() override; - void initializeGL() override; - void showEvent(QShowEvent *event) override; - mat4 calcFrameMatrix() override; - - double prev_draw_t = 0; - FirstOrderFilter fps_filter; -}; diff --git a/selfdrive/ui/qt/onroad/buttons.cc b/selfdrive/ui/qt/onroad/buttons.cc deleted file mode 100644 index 75b8a8b7e6..0000000000 --- a/selfdrive/ui/qt/onroad/buttons.cc +++ /dev/null @@ -1,53 +0,0 @@ -#include "selfdrive/ui/qt/onroad/buttons.h" - -#include - -#include "selfdrive/ui/qt/util.h" - -void drawIcon(QPainter &p, const QPoint ¢er, const QPixmap &img, const QBrush &bg, float opacity) { - p.setRenderHint(QPainter::Antialiasing); - p.setOpacity(1.0); // bg dictates opacity of ellipse - p.setPen(Qt::NoPen); - p.setBrush(bg); - p.drawEllipse(center, btn_size / 2, btn_size / 2); - p.setOpacity(opacity); - p.drawPixmap(center - QPoint(img.width() / 2, img.height() / 2), img); - p.setOpacity(1.0); -} - -// ExperimentalButton -ExperimentalButton::ExperimentalButton(QWidget *parent) : experimental_mode(false), engageable(false), QPushButton(parent) { - setFixedSize(btn_size, btn_size); - - engage_img = loadPixmap("../assets/icons/chffr_wheel.png", {img_size, img_size}); - experimental_img = loadPixmap("../assets/icons/experimental.svg", {img_size, img_size}); - QObject::connect(this, &QPushButton::clicked, this, &ExperimentalButton::changeMode); -} - -void ExperimentalButton::changeMode() { - const auto cp = (*uiState()->sm)["carParams"].getCarParams(); - bool can_change = hasLongitudinalControl(cp) && params.getBool("ExperimentalModeConfirmed"); - if (can_change) { - params.putBool("ExperimentalMode", !experimental_mode); - } -} - -void ExperimentalButton::updateState(const UIState &s) { - const auto cs = (*s.sm)["selfdriveState"].getSelfdriveState(); - bool eng = cs.getEngageable() || cs.getEnabled(); - if ((cs.getExperimentalMode() != experimental_mode) || (eng != engageable)) { - engageable = eng; - experimental_mode = cs.getExperimentalMode(); - update(); - } -} - -void ExperimentalButton::paintEvent(QPaintEvent *event) { - QPainter p(this); - drawButton(p); -} - -void ExperimentalButton::drawButton(QPainter &p) { - QPixmap img = experimental_mode ? experimental_img : engage_img; - drawIcon(p, QPoint(btn_size / 2, btn_size / 2), img, QColor(0, 0, 0, 166), (isDown() || !engageable) ? 0.6 : 1.0); -} diff --git a/selfdrive/ui/qt/onroad/buttons.h b/selfdrive/ui/qt/onroad/buttons.h deleted file mode 100644 index fca909f9b2..0000000000 --- a/selfdrive/ui/qt/onroad/buttons.h +++ /dev/null @@ -1,36 +0,0 @@ -#pragma once - -#include - -#ifdef SUNNYPILOT -#include "selfdrive/ui/sunnypilot/ui.h" -#else -#include "selfdrive/ui/ui.h" -#endif - -const int btn_size = 192; -const int img_size = (btn_size / 4) * 3; - -class ExperimentalButton : public QPushButton { - Q_OBJECT - -public: - explicit ExperimentalButton(QWidget *parent = 0); - virtual void updateState(const UIState &s); - -private: - void paintEvent(QPaintEvent *event) override; - void changeMode(); - - Params params; - -protected: - virtual void drawButton(QPainter &p); - - QPixmap engage_img; - QPixmap experimental_img; - bool experimental_mode; - bool engageable; -}; - -void drawIcon(QPainter &p, const QPoint ¢er, const QPixmap &img, const QBrush &bg, float opacity); diff --git a/selfdrive/ui/qt/onroad/driver_monitoring.cc b/selfdrive/ui/qt/onroad/driver_monitoring.cc deleted file mode 100644 index 49f2c950b4..0000000000 --- a/selfdrive/ui/qt/onroad/driver_monitoring.cc +++ /dev/null @@ -1,107 +0,0 @@ -#include "selfdrive/ui/qt/onroad/driver_monitoring.h" -#include -#include - -#include "selfdrive/ui/qt/onroad/buttons.h" -#include "selfdrive/ui/qt/util.h" - -// Default 3D coordinates for face keypoints -static constexpr vec3 DEFAULT_FACE_KPTS_3D[] = { - {-5.98, -51.20, 8.00}, {-17.64, -49.14, 8.00}, {-23.81, -46.40, 8.00}, {-29.98, -40.91, 8.00}, {-32.04, -37.49, 8.00}, - {-34.10, -32.00, 8.00}, {-36.16, -21.03, 8.00}, {-36.16, 6.40, 8.00}, {-35.47, 10.51, 8.00}, {-32.73, 19.43, 8.00}, - {-29.30, 26.29, 8.00}, {-24.50, 33.83, 8.00}, {-19.01, 41.37, 8.00}, {-14.21, 46.17, 8.00}, {-12.16, 47.54, 8.00}, - {-4.61, 49.60, 8.00}, {4.99, 49.60, 8.00}, {12.53, 47.54, 8.00}, {14.59, 46.17, 8.00}, {19.39, 41.37, 8.00}, - {24.87, 33.83, 8.00}, {29.67, 26.29, 8.00}, {33.10, 19.43, 8.00}, {35.84, 10.51, 8.00}, {36.53, 6.40, 8.00}, - {36.53, -21.03, 8.00}, {34.47, -32.00, 8.00}, {32.42, -37.49, 8.00}, {30.36, -40.91, 8.00}, {24.19, -46.40, 8.00}, - {18.02, -49.14, 8.00}, {6.36, -51.20, 8.00}, {-5.98, -51.20, 8.00}, -}; - -// Colors used for drawing based on monitoring state -static const QColor DMON_ENGAGED_COLOR = QColor::fromRgbF(0.1, 0.945, 0.26); -static const QColor DMON_DISENGAGED_COLOR = QColor::fromRgbF(0.545, 0.545, 0.545); - -DriverMonitorRenderer::DriverMonitorRenderer() : face_kpts_draw(std::size(DEFAULT_FACE_KPTS_3D)) { - dm_img = loadPixmap("../assets/icons/driver_face.png", {img_size + 5, img_size + 5}); -} - -void DriverMonitorRenderer::updateState(const UIState &s) { - auto &sm = *(s.sm); - is_visible = sm["selfdriveState"].getSelfdriveState().getAlertSize() == cereal::SelfdriveState::AlertSize::NONE && - sm.rcv_frame("driverStateV2") > s.scene.started_frame; - if (!is_visible) return; - - auto dm_state = sm["driverMonitoringState"].getDriverMonitoringState(); - is_active = dm_state.getIsActiveMode(); - is_rhd = dm_state.getIsRHD(); - dm_fade_state = std::clamp(dm_fade_state + 0.2f * (0.5f - is_active), 0.0f, 1.0f); - - const auto &driverstate = sm["driverStateV2"].getDriverStateV2(); - const auto driver_orient = is_rhd ? driverstate.getRightDriverData().getFaceOrientation() : driverstate.getLeftDriverData().getFaceOrientation(); - - for (int i = 0; i < 3; ++i) { - float v_this = (i == 0 ? (driver_orient[i] < 0 ? 0.7 : 0.9) : 0.4) * driver_orient[i]; - driver_pose_diff[i] = std::abs(driver_pose_vals[i] - v_this); - driver_pose_vals[i] = 0.8f * v_this + (1 - 0.8) * driver_pose_vals[i]; - driver_pose_sins[i] = std::sin(driver_pose_vals[i] * (1.0f - dm_fade_state)); - driver_pose_coss[i] = std::cos(driver_pose_vals[i] * (1.0f - dm_fade_state)); - } - - auto [sin_y, sin_x, sin_z] = driver_pose_sins; - auto [cos_y, cos_x, cos_z] = driver_pose_coss; - - // Rotation matrix for transforming face keypoints based on driver's head orientation - const mat3 r_xyz = {{ - cos_x * cos_z, cos_x * sin_z, -sin_x, - -sin_y * sin_x * cos_z - cos_y * sin_z, -sin_y * sin_x * sin_z + cos_y * cos_z, -sin_y * cos_x, - cos_y * sin_x * cos_z - sin_y * sin_z, cos_y * sin_x * sin_z + sin_y * cos_z, cos_y * cos_x, - }}; - - // Transform vertices - for (int i = 0; i < face_kpts_draw.size(); ++i) { - vec3 kpt = matvecmul3(r_xyz, DEFAULT_FACE_KPTS_3D[i]); - face_kpts_draw[i] = {{kpt.v[0], kpt.v[1], kpt.v[2] * (1.0f - dm_fade_state) + 8 * dm_fade_state}}; - } -} - -void DriverMonitorRenderer::draw(QPainter &painter, const QRect &surface_rect) { - if (!is_visible) return; - - painter.save(); - - int offset = UI_BORDER_SIZE + btn_size / 2; - float x = is_rhd ? surface_rect.width() - offset : offset; - float y = surface_rect.height() - offset; - float opacity = is_active ? 0.65f : 0.2f; - - drawIcon(painter, QPoint(x, y), dm_img, QColor(0, 0, 0, 70), opacity); - - QPointF keypoints[std::size(DEFAULT_FACE_KPTS_3D)]; - for (int i = 0; i < std::size(keypoints); ++i) { - const auto &v = face_kpts_draw[i].v; - float kp = (v[2] - 8) / 120.0f + 1.0f; - keypoints[i] = QPointF(v[0] * kp + x, v[1] * kp + y); - } - - painter.setPen(QPen(QColor::fromRgbF(1.0, 1.0, 1.0, opacity), 5.2, Qt::SolidLine, Qt::RoundCap)); - painter.drawPolyline(keypoints, std::size(keypoints)); - - // tracking arcs - const int arc_l = 133; - const float arc_t_default = 6.7f; - const float arc_t_extend = 12.0f; - QColor arc_color = uiState()->engaged() ? DMON_ENGAGED_COLOR : DMON_DISENGAGED_COLOR; - arc_color.setAlphaF(0.4 * (1.0f - dm_fade_state)); - - float delta_x = -driver_pose_sins[1] * arc_l / 2.0f; - float delta_y = -driver_pose_sins[0] * arc_l / 2.0f; - - // Draw horizontal tracking arc - painter.setPen(QPen(arc_color, arc_t_default + arc_t_extend * std::min(1.0, driver_pose_diff[1] * 5.0), Qt::SolidLine, Qt::RoundCap)); - painter.drawArc(QRectF(std::min(x + delta_x, x), y - arc_l / 2, std::abs(delta_x), arc_l), (driver_pose_sins[1] > 0 ? 90 : -90) * 16, 180 * 16); - - // Draw vertical tracking arc - painter.setPen(QPen(arc_color, arc_t_default + arc_t_extend * std::min(1.0, driver_pose_diff[0] * 5.0), Qt::SolidLine, Qt::RoundCap)); - painter.drawArc(QRectF(x - arc_l / 2, std::min(y + delta_y, y), arc_l, std::abs(delta_y)), (driver_pose_sins[0] > 0 ? 0 : 180) * 16, 180 * 16); - - painter.restore(); -} diff --git a/selfdrive/ui/qt/onroad/driver_monitoring.h b/selfdrive/ui/qt/onroad/driver_monitoring.h deleted file mode 100644 index 47db151c81..0000000000 --- a/selfdrive/ui/qt/onroad/driver_monitoring.h +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once - -#include -#include -#include "selfdrive/ui/ui.h" - -class DriverMonitorRenderer { -public: - DriverMonitorRenderer(); - void updateState(const UIState &s); - void draw(QPainter &painter, const QRect &surface_rect); - -private: - float driver_pose_vals[3] = {}; - float driver_pose_diff[3] = {}; - float driver_pose_sins[3] = {}; - float driver_pose_coss[3] = {}; - bool is_visible = false; - bool is_active = false; - bool is_rhd = false; - float dm_fade_state = 1.0; - QPixmap dm_img; - std::vector face_kpts_draw; -}; diff --git a/selfdrive/ui/qt/onroad/hud.cc b/selfdrive/ui/qt/onroad/hud.cc deleted file mode 100644 index 4cfa3d0e3c..0000000000 --- a/selfdrive/ui/qt/onroad/hud.cc +++ /dev/null @@ -1,112 +0,0 @@ -#include "selfdrive/ui/qt/onroad/hud.h" - -#include - -#include "selfdrive/ui/qt/util.h" - -constexpr int SET_SPEED_NA = 255; - -HudRenderer::HudRenderer() {} - -void HudRenderer::updateState(const UIState &s) { - is_metric = s.scene.is_metric; - status = s.status; - - const SubMaster &sm = *(s.sm); - if (sm.rcv_frame("carState") < s.scene.started_frame) { - is_cruise_set = false; - set_speed = SET_SPEED_NA; - speed = 0.0; - return; - } - - const auto &controls_state = sm["controlsState"].getControlsState(); - const auto &car_state = sm["carState"].getCarState(); - - // Handle older routes where vCruiseCluster is not set - set_speed = car_state.getVCruiseCluster() == 0.0 ? controls_state.getVCruiseDEPRECATED() : car_state.getVCruiseCluster(); - is_cruise_set = set_speed > 0 && set_speed != SET_SPEED_NA; - is_cruise_available = set_speed != -1; - - if (is_cruise_set && !is_metric) { - set_speed *= KM_TO_MILE; - } - - // Handle older routes where vEgoCluster is not set - v_ego_cluster_seen = v_ego_cluster_seen || car_state.getVEgoCluster() != 0.0; - float v_ego = v_ego_cluster_seen ? car_state.getVEgoCluster() : car_state.getVEgo(); - speed = std::max(0.0f, v_ego * (is_metric ? MS_TO_KPH : MS_TO_MPH)); -} - -void HudRenderer::draw(QPainter &p, const QRect &surface_rect) { - p.save(); - - // Draw header gradient - QLinearGradient bg(0, UI_HEADER_HEIGHT - (UI_HEADER_HEIGHT / 2.5), 0, UI_HEADER_HEIGHT); - bg.setColorAt(0, QColor::fromRgbF(0, 0, 0, 0.45)); - bg.setColorAt(1, QColor::fromRgbF(0, 0, 0, 0)); - p.fillRect(0, 0, surface_rect.width(), UI_HEADER_HEIGHT, bg); - - - if (is_cruise_available) { - drawSetSpeed(p, surface_rect); - } - drawCurrentSpeed(p, surface_rect); - - p.restore(); -} - -void HudRenderer::drawSetSpeed(QPainter &p, const QRect &surface_rect) { - // Draw outer box + border to contain set speed - const QSize default_size = {172, 204}; - QSize set_speed_size = is_metric ? QSize(200, 204) : default_size; - QRect set_speed_rect(QPoint(60 + (default_size.width() - set_speed_size.width()) / 2, 45), set_speed_size); - - // Draw set speed box - p.setPen(QPen(QColor(255, 255, 255, 75), 6)); - p.setBrush(QColor(0, 0, 0, 166)); - p.drawRoundedRect(set_speed_rect, 32, 32); - - // Colors based on status - QColor max_color = QColor(0xa6, 0xa6, 0xa6, 0xff); - QColor set_speed_color = QColor(0x72, 0x72, 0x72, 0xff); - if (is_cruise_set) { - set_speed_color = QColor(255, 255, 255); - if (status == STATUS_DISENGAGED) { - max_color = QColor(255, 255, 255); - } else if (status == STATUS_OVERRIDE) { - max_color = QColor(0x91, 0x9b, 0x95, 0xff); - } else { - max_color = QColor(0x80, 0xd8, 0xa6, 0xff); - } - } - - // Draw "MAX" text - p.setFont(InterFont(40, QFont::DemiBold)); - p.setPen(max_color); - p.drawText(set_speed_rect.adjusted(0, 27, 0, 0), Qt::AlignTop | Qt::AlignHCenter, tr("MAX")); - - // Draw set speed - QString setSpeedStr = is_cruise_set ? QString::number(std::nearbyint(set_speed)) : "–"; - p.setFont(InterFont(90, QFont::Bold)); - p.setPen(set_speed_color); - p.drawText(set_speed_rect.adjusted(0, 77, 0, 0), Qt::AlignTop | Qt::AlignHCenter, setSpeedStr); -} - -void HudRenderer::drawCurrentSpeed(QPainter &p, const QRect &surface_rect) { - QString speedStr = QString::number(std::nearbyint(speed)); - - p.setFont(InterFont(176, QFont::Bold)); - drawText(p, surface_rect.center().x(), 210, speedStr); - - p.setFont(InterFont(66)); - drawText(p, surface_rect.center().x(), 290, is_metric ? tr("km/h") : tr("mph"), 200); -} - -void HudRenderer::drawText(QPainter &p, int x, int y, const QString &text, int alpha) { - QRect real_rect = p.fontMetrics().boundingRect(text); - real_rect.moveCenter({x, y - real_rect.height() / 2}); - - p.setPen(QColor(0xff, 0xff, 0xff, alpha)); - p.drawText(real_rect.x(), real_rect.bottom(), text); -} diff --git a/selfdrive/ui/qt/onroad/hud.h b/selfdrive/ui/qt/onroad/hud.h deleted file mode 100644 index 6638af8a05..0000000000 --- a/selfdrive/ui/qt/onroad/hud.h +++ /dev/null @@ -1,32 +0,0 @@ -#pragma once - -#include - -#ifdef SUNNYPILOT -#include "selfdrive/ui/sunnypilot/ui.h" -#else -#include "selfdrive/ui/ui.h" -#endif - -class HudRenderer : public QObject { - Q_OBJECT - -public: - HudRenderer(); - virtual ~HudRenderer() = default; - virtual void updateState(const UIState &s); - virtual void draw(QPainter &p, const QRect &surface_rect); - -protected: - void drawSetSpeed(QPainter &p, const QRect &surface_rect); - void drawCurrentSpeed(QPainter &p, const QRect &surface_rect); - void drawText(QPainter &p, int x, int y, const QString &text, int alpha = 255); - - float speed = 0; - float set_speed = 0; - bool is_cruise_set = false; - bool is_cruise_available = true; - bool is_metric = false; - bool v_ego_cluster_seen = false; - int status = STATUS_DISENGAGED; -}; diff --git a/selfdrive/ui/qt/onroad/model.cc b/selfdrive/ui/qt/onroad/model.cc deleted file mode 100644 index dc801e591f..0000000000 --- a/selfdrive/ui/qt/onroad/model.cc +++ /dev/null @@ -1,237 +0,0 @@ -#include "selfdrive/ui/qt/onroad/model.h" - -void ModelRenderer::draw(QPainter &painter, const QRect &surface_rect) { - auto *s = uiState(); - auto &sm = *(s->sm); - // Check if data is up-to-date - if (sm.rcv_frame("liveCalibration") < s->scene.started_frame || - sm.rcv_frame("modelV2") < s->scene.started_frame) { - return; - } - - clip_region = surface_rect.adjusted(-CLIP_MARGIN, -CLIP_MARGIN, CLIP_MARGIN, CLIP_MARGIN); - experimental_mode = sm["selfdriveState"].getSelfdriveState().getExperimentalMode(); - longitudinal_control = sm["carParams"].getCarParams().getOpenpilotLongitudinalControl(); - path_offset_z = sm["liveCalibration"].getLiveCalibration().getHeight()[0]; - - painter.save(); - - const auto &model = sm["modelV2"].getModelV2(); - const auto &radar_state = sm["radarState"].getRadarState(); - const auto &lead_one = radar_state.getLeadOne(); - - update_model(model, lead_one); - drawLaneLines(painter); - drawPath(painter, model, surface_rect); - - if (longitudinal_control && sm.alive("radarState")) { - update_leads(radar_state, model.getPosition()); - const auto &lead_two = radar_state.getLeadTwo(); - if (lead_one.getStatus()) { - drawLead(painter, lead_one, lead_vertices[0], surface_rect); - } - if (lead_two.getStatus() && (std::abs(lead_one.getDRel() - lead_two.getDRel()) > 3.0)) { - drawLead(painter, lead_two, lead_vertices[1], surface_rect); - } - } - - painter.restore(); -} - -void ModelRenderer::update_leads(const cereal::RadarState::Reader &radar_state, const cereal::XYZTData::Reader &line) { - for (int i = 0; i < 2; ++i) { - const auto &lead_data = (i == 0) ? radar_state.getLeadOne() : radar_state.getLeadTwo(); - if (lead_data.getStatus()) { - float z = line.getZ()[get_path_length_idx(line, lead_data.getDRel())]; - mapToScreen(lead_data.getDRel(), -lead_data.getYRel(), z + path_offset_z, &lead_vertices[i]); - } - } -} - -void ModelRenderer::update_model(const cereal::ModelDataV2::Reader &model, const cereal::RadarState::LeadData::Reader &lead) { - const auto &model_position = model.getPosition(); - float max_distance = std::clamp(*(model_position.getX().end() - 1), MIN_DRAW_DISTANCE, MAX_DRAW_DISTANCE); - - // update lane lines - const auto &lane_lines = model.getLaneLines(); - const auto &line_probs = model.getLaneLineProbs(); - int max_idx = get_path_length_idx(lane_lines[0], max_distance); - for (int i = 0; i < std::size(lane_line_vertices); i++) { - lane_line_probs[i] = line_probs[i]; - mapLineToPolygon(lane_lines[i], 0.025 * lane_line_probs[i], 0, &lane_line_vertices[i], max_idx); - } - - // update road edges - const auto &road_edges = model.getRoadEdges(); - const auto &edge_stds = model.getRoadEdgeStds(); - for (int i = 0; i < std::size(road_edge_vertices); i++) { - road_edge_stds[i] = edge_stds[i]; - mapLineToPolygon(road_edges[i], 0.025, 0, &road_edge_vertices[i], max_idx); - } - - // update path - if (lead.getStatus()) { - const float lead_d = lead.getDRel() * 2.; - max_distance = std::clamp((float)(lead_d - fmin(lead_d * 0.35, 10.)), 0.0f, max_distance); - } - max_idx = get_path_length_idx(model_position, max_distance); - mapLineToPolygon(model_position, 0.9, path_offset_z, &track_vertices, max_idx, false); -} - -void ModelRenderer::drawLaneLines(QPainter &painter) { - // lanelines - for (int i = 0; i < std::size(lane_line_vertices); ++i) { - painter.setBrush(QColor::fromRgbF(1.0, 1.0, 1.0, std::clamp(lane_line_probs[i], 0.0, 0.7))); - painter.drawPolygon(lane_line_vertices[i]); - } - - // road edges - for (int i = 0; i < std::size(road_edge_vertices); ++i) { - painter.setBrush(QColor::fromRgbF(1.0, 0, 0, std::clamp(1.0 - road_edge_stds[i], 0.0, 1.0))); - painter.drawPolygon(road_edge_vertices[i]); - } -} - -void ModelRenderer::drawPath(QPainter &painter, const cereal::ModelDataV2::Reader &model, int height) { - QLinearGradient bg(0, height, 0, 0); - if (experimental_mode) { - // The first half of track_vertices are the points for the right side of the path - const auto &acceleration = model.getAcceleration().getX(); - const int max_len = std::min(track_vertices.length() / 2, acceleration.size()); - - for (int i = 0; i < max_len; ++i) { - // Some points are out of frame - int track_idx = max_len - i - 1; // flip idx to start from bottom right - if (track_vertices[track_idx].y() < 0 || track_vertices[track_idx].y() > height) continue; - - // Flip so 0 is bottom of frame - float lin_grad_point = (height - track_vertices[track_idx].y()) / height; - - // speed up: 120, slow down: 0 - float path_hue = fmax(fmin(60 + acceleration[i] * 35, 120), 0); - // FIXME: painter.drawPolygon can be slow if hue is not rounded - path_hue = int(path_hue * 100 + 0.5) / 100; - - float saturation = fmin(fabs(acceleration[i] * 1.5), 1); - float lightness = util::map_val(saturation, 0.0f, 1.0f, 0.95f, 0.62f); // lighter when grey - float alpha = util::map_val(lin_grad_point, 0.75f / 2.f, 0.75f, 0.4f, 0.0f); // matches previous alpha fade - bg.setColorAt(lin_grad_point, QColor::fromHslF(path_hue / 360., saturation, lightness, alpha)); - - // Skip a point, unless next is last - i += (i + 2) < max_len ? 1 : 0; - } - - } else { - updatePathGradient(bg); - } - - painter.setBrush(bg); - painter.drawPolygon(track_vertices); -} - -void ModelRenderer::updatePathGradient(QLinearGradient &bg) { - static const QColor throttle_colors[] = { - QColor::fromHslF(148. / 360., 0.94, 0.51, 0.4), - QColor::fromHslF(112. / 360., 1.0, 0.68, 0.35), - QColor::fromHslF(112. / 360., 1.0, 0.68, 0.0)}; - - static const QColor no_throttle_colors[] = { - QColor::fromHslF(148. / 360., 0.0, 0.95, 0.4), - QColor::fromHslF(112. / 360., 0.0, 0.95, 0.35), - QColor::fromHslF(112. / 360., 0.0, 0.95, 0.0), - }; - - // Transition speed; 0.1 corresponds to 0.5 seconds at UI_FREQ - constexpr float transition_speed = 0.1f; - - // Start transition if throttle state changes - bool allow_throttle = (*uiState()->sm)["longitudinalPlan"].getLongitudinalPlan().getAllowThrottle() || !longitudinal_control; - if (allow_throttle != prev_allow_throttle) { - prev_allow_throttle = allow_throttle; - // Invert blend factor for a smooth transition when the state changes mid-animation - blend_factor = std::max(1.0f - blend_factor, 0.0f); - } - - const QColor *begin_colors = allow_throttle ? no_throttle_colors : throttle_colors; - const QColor *end_colors = allow_throttle ? throttle_colors : no_throttle_colors; - if (blend_factor < 1.0f) { - blend_factor = std::min(blend_factor + transition_speed, 1.0f); - } - - // Set gradient colors by blending the start and end colors - bg.setColorAt(0.0f, blendColors(begin_colors[0], end_colors[0], blend_factor)); - bg.setColorAt(0.5f, blendColors(begin_colors[1], end_colors[1], blend_factor)); - bg.setColorAt(1.0f, blendColors(begin_colors[2], end_colors[2], blend_factor)); -} - -QColor ModelRenderer::blendColors(const QColor &start, const QColor &end, float t) { - if (t == 1.0f) return end; - return QColor::fromRgbF( - (1 - t) * start.redF() + t * end.redF(), - (1 - t) * start.greenF() + t * end.greenF(), - (1 - t) * start.blueF() + t * end.blueF(), - (1 - t) * start.alphaF() + t * end.alphaF()); -} - -void ModelRenderer::drawLead(QPainter &painter, const cereal::RadarState::LeadData::Reader &lead_data, - const QPointF &vd, const QRect &surface_rect) { - const float speedBuff = 10.; - const float leadBuff = 40.; - const float d_rel = lead_data.getDRel(); - const float v_rel = lead_data.getVRel(); - - float fillAlpha = 0; - if (d_rel < leadBuff) { - fillAlpha = 255 * (1.0 - (d_rel / leadBuff)); - if (v_rel < 0) { - fillAlpha += 255 * (-1 * (v_rel / speedBuff)); - } - fillAlpha = (int)(fmin(fillAlpha, 255)); - } - - float sz = std::clamp((25 * 30) / (d_rel / 3 + 30), 15.0f, 30.0f) * 2.35; - float x = std::clamp(vd.x(), 0.f, surface_rect.width() - sz / 2); - float y = std::min(vd.y(), surface_rect.height() - sz * 0.6); - - float g_xo = sz / 5; - float g_yo = sz / 10; - - QPointF glow[] = {{x + (sz * 1.35) + g_xo, y + sz + g_yo}, {x, y - g_yo}, {x - (sz * 1.35) - g_xo, y + sz + g_yo}}; - painter.setBrush(QColor(218, 202, 37, 255)); - painter.drawPolygon(glow, std::size(glow)); - - // chevron - QPointF chevron[] = {{x + (sz * 1.25), y + sz}, {x, y}, {x - (sz * 1.25), y + sz}}; - painter.setBrush(QColor(201, 34, 49, fillAlpha)); - painter.drawPolygon(chevron, std::size(chevron)); -} - -// Projects a point in car to space to the corresponding point in full frame image space. -bool ModelRenderer::mapToScreen(float in_x, float in_y, float in_z, QPointF *out) { - Eigen::Vector3f input(in_x, in_y, in_z); - auto pt = car_space_transform * input; - *out = QPointF(pt.x() / pt.z(), pt.y() / pt.z()); - return clip_region.contains(*out); -} - -void ModelRenderer::mapLineToPolygon(const cereal::XYZTData::Reader &line, float y_off, float z_off, - QPolygonF *pvd, int max_idx, bool allow_invert) { - const auto line_x = line.getX(), line_y = line.getY(), line_z = line.getZ(); - QPointF left, right; - pvd->clear(); - for (int i = 0; i <= max_idx; i++) { - // highly negative x positions are drawn above the frame and cause flickering, clip to zy plane of camera - if (line_x[i] < 0) continue; - - bool l = mapToScreen(line_x[i], line_y[i] - y_off, line_z[i] + z_off, &left); - bool r = mapToScreen(line_x[i], line_y[i] + y_off, line_z[i] + z_off, &right); - if (l && r) { - // For wider lines the drawn polygon will "invert" when going over a hill and cause artifacts - if (!allow_invert && pvd->size() && left.y() > pvd->back().y()) { - continue; - } - pvd->push_back(left); - pvd->push_front(right); - } - } -} diff --git a/selfdrive/ui/qt/onroad/model.h b/selfdrive/ui/qt/onroad/model.h deleted file mode 100644 index 85eb236e76..0000000000 --- a/selfdrive/ui/qt/onroad/model.h +++ /dev/null @@ -1,61 +0,0 @@ -#pragma once - -#include -#include - -#ifdef SUNNYPILOT -#include "selfdrive/ui/sunnypilot/ui.h" -#else -#include "selfdrive/ui/ui.h" -#endif - -constexpr int CLIP_MARGIN = 500; -constexpr float MIN_DRAW_DISTANCE = 10.0; -constexpr float MAX_DRAW_DISTANCE = 100.0; - -inline int get_path_length_idx(const cereal::XYZTData::Reader &line, const float path_height) { - const auto &line_x = line.getX(); - int max_idx = 0; - for (int i = 1; i < line_x.size() && line_x[i] <= path_height; ++i) { - max_idx = i; - } - return max_idx; -} - -class ModelRenderer { -public: - virtual ~ModelRenderer() = default; - - ModelRenderer() {} - void setTransform(const Eigen::Matrix3f &transform) { car_space_transform = transform; } - void draw(QPainter &painter, const QRect &surface_rect); - -protected: - bool mapToScreen(float in_x, float in_y, float in_z, QPointF *out); - void mapLineToPolygon(const cereal::XYZTData::Reader &line, float y_off, float z_off, - QPolygonF *pvd, int max_idx, bool allow_invert = true); - void drawLead(QPainter &painter, const cereal::RadarState::LeadData::Reader &lead_data, const QPointF &vd, const QRect &surface_rect); - void update_leads(const cereal::RadarState::Reader &radar_state, const cereal::XYZTData::Reader &line); - virtual void update_model(const cereal::ModelDataV2::Reader &model, const cereal::RadarState::LeadData::Reader &lead); - void drawLaneLines(QPainter &painter); - void drawPath(QPainter &painter, const cereal::ModelDataV2::Reader &model, int height); - virtual void drawPath(QPainter &painter, const cereal::ModelDataV2::Reader &model, const QRect &surface_rect) {; - drawPath(painter, model, surface_rect.height()); - } - void updatePathGradient(QLinearGradient &bg); - QColor blendColors(const QColor &start, const QColor &end, float t); - - bool longitudinal_control = false; - bool experimental_mode = false; - float blend_factor = 1.0f; - bool prev_allow_throttle = true; - float lane_line_probs[4] = {}; - float road_edge_stds[2] = {}; - float path_offset_z = 1.22f; - QPolygonF track_vertices; - QPolygonF lane_line_vertices[4] = {}; - QPolygonF road_edge_vertices[2] = {}; - QPointF lead_vertices[2] = {}; - Eigen::Matrix3f car_space_transform = Eigen::Matrix3f::Zero(); - QRectF clip_region; -}; diff --git a/selfdrive/ui/qt/onroad/onroad_home.cc b/selfdrive/ui/qt/onroad/onroad_home.cc deleted file mode 100644 index 7db9a05a0c..0000000000 --- a/selfdrive/ui/qt/onroad/onroad_home.cc +++ /dev/null @@ -1,69 +0,0 @@ -#include "selfdrive/ui/qt/onroad/onroad_home.h" - -#include -#include - -#include "selfdrive/ui/qt/util.h" - -OnroadWindow::OnroadWindow(QWidget *parent) : QWidget(parent) { - QVBoxLayout *main_layout = new QVBoxLayout(this); - main_layout->setMargin(UI_BORDER_SIZE); - QStackedLayout *stacked_layout = new QStackedLayout; - stacked_layout->setStackingMode(QStackedLayout::StackAll); - main_layout->addLayout(stacked_layout); - - nvg = new AnnotatedCameraWidget(VISION_STREAM_ROAD, this); - - QWidget * split_wrapper = new QWidget; - split = new QHBoxLayout(split_wrapper); - split->setContentsMargins(0, 0, 0, 0); - split->setSpacing(0); - split->addWidget(nvg); - - if (getenv("DUAL_CAMERA_VIEW")) { - CameraWidget *arCam = new CameraWidget("camerad", VISION_STREAM_ROAD, this); - split->insertWidget(0, arCam); - } - - stacked_layout->addWidget(split_wrapper); - - alerts = new OnroadAlerts(this); - alerts->setAttribute(Qt::WA_TransparentForMouseEvents, true); - stacked_layout->addWidget(alerts); - - // setup stacking order - alerts->raise(); - - setAttribute(Qt::WA_OpaquePaintEvent); - - // We handle the connection of the signals on the derived class -#ifndef SUNNYPILOT - QObject::connect(uiState(), &UIState::uiUpdate, this, &OnroadWindow::updateState); - QObject::connect(uiState(), &UIState::offroadTransition, this, &OnroadWindow::offroadTransition); -#endif -} - -void OnroadWindow::updateState(const UIState &s) { - if (!s.scene.started) { - return; - } - - alerts->updateState(s); - nvg->updateState(s); - - QColor bgColor = bg_colors[s.status]; - if (bg != bgColor) { - // repaint border - bg = bgColor; - update(); - } -} - -void OnroadWindow::offroadTransition(bool offroad) { - alerts->clear(); -} - -void OnroadWindow::paintEvent(QPaintEvent *event) { - QPainter p(this); - p.fillRect(rect(), QColor(bg.red(), bg.green(), bg.blue(), 255)); -} diff --git a/selfdrive/ui/qt/onroad/onroad_home.h b/selfdrive/ui/qt/onroad/onroad_home.h deleted file mode 100644 index 9b51bb62e4..0000000000 --- a/selfdrive/ui/qt/onroad/onroad_home.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include "selfdrive/ui/qt/onroad/alerts.h" - -#ifdef SUNNYPILOT -#include "selfdrive/ui/sunnypilot/qt/onroad/annotated_camera.h" -#define UIState UIStateSP -#define AnnotatedCameraWidget AnnotatedCameraWidgetSP -#else -#include "selfdrive/ui/qt/onroad/annotated_camera.h" -#endif - -class OnroadWindow : public QWidget { - Q_OBJECT - -public: - OnroadWindow(QWidget* parent = 0); - -protected: - void paintEvent(QPaintEvent *event); - OnroadAlerts *alerts; - AnnotatedCameraWidget *nvg; - QColor bg = bg_colors[STATUS_DISENGAGED]; - QHBoxLayout* split; - -protected slots: - virtual void offroadTransition(bool offroad); - virtual void updateState(const UIState &s); -}; diff --git a/selfdrive/ui/qt/prime_state.cc b/selfdrive/ui/qt/prime_state.cc deleted file mode 100644 index f12daf1e3c..0000000000 --- a/selfdrive/ui/qt/prime_state.cc +++ /dev/null @@ -1,48 +0,0 @@ -#include "selfdrive/ui/qt/prime_state.h" - -#include - -#include "selfdrive/ui/qt/api.h" -#include "selfdrive/ui/qt/request_repeater.h" -#include "selfdrive/ui/qt/util.h" - -PrimeState::PrimeState(QObject* parent) : QObject(parent) { - const char *env_prime_type = std::getenv("PRIME_TYPE"); - auto type = env_prime_type ? env_prime_type : Params().get("PrimeType"); - - if (!type.empty()) { - prime_type = static_cast(std::atoi(type.c_str())); - } - - if (auto dongleId = getDongleId()) { - QString url = CommaApi::BASE_URL + "/v1.1/devices/" + *dongleId + "/"; - RequestRepeater* repeater = new RequestRepeater(this, url, "ApiCache_Device", 5); - QObject::connect(repeater, &RequestRepeater::requestDone, this, &PrimeState::handleReply); - } - - // Emit the initial state change - QTimer::singleShot(1, [this]() { emit changed(prime_type); }); -} - -void PrimeState::handleReply(const QString& response, bool success) { - if (!success) return; - - QJsonDocument doc = QJsonDocument::fromJson(response.toUtf8()); - if (doc.isNull()) { - qDebug() << "JSON Parse failed on getting pairing and PrimeState status"; - return; - } - - QJsonObject json = doc.object(); - bool is_paired = json["is_paired"].toBool(); - auto type = static_cast(json["prime_type"].toInt()); - setType(is_paired ? type : PrimeState::PRIME_TYPE_UNPAIRED); -} - -void PrimeState::setType(PrimeState::Type type) { - if (type != prime_type) { - prime_type = type; - Params().put("PrimeType", std::to_string(prime_type)); - emit changed(prime_type); - } -} diff --git a/selfdrive/ui/qt/prime_state.h b/selfdrive/ui/qt/prime_state.h deleted file mode 100644 index 0e2e3bb043..0000000000 --- a/selfdrive/ui/qt/prime_state.h +++ /dev/null @@ -1,33 +0,0 @@ -#pragma once - -#include - -class PrimeState : public QObject { - Q_OBJECT - -public: - - enum Type { - PRIME_TYPE_UNKNOWN = -2, - PRIME_TYPE_UNPAIRED = -1, - PRIME_TYPE_NONE = 0, - PRIME_TYPE_MAGENTA = 1, - PRIME_TYPE_LITE = 2, - PRIME_TYPE_BLUE = 3, - PRIME_TYPE_MAGENTA_NEW = 4, - PRIME_TYPE_PURPLE = 5, - }; - - PrimeState(QObject *parent); - void setType(PrimeState::Type type); - inline PrimeState::Type currentType() const { return prime_type; } - inline bool isSubscribed() const { return prime_type > PrimeState::PRIME_TYPE_NONE; } - -signals: - void changed(PrimeState::Type prime_type); - -private: - void handleReply(const QString &response, bool success); - - PrimeState::Type prime_type = PrimeState::PRIME_TYPE_UNKNOWN; -}; diff --git a/selfdrive/ui/qt/python_helpers.py b/selfdrive/ui/qt/python_helpers.py deleted file mode 100644 index 1f6d43f309..0000000000 --- a/selfdrive/ui/qt/python_helpers.py +++ /dev/null @@ -1,23 +0,0 @@ -import os -import platform -from cffi import FFI - -import sip - -from openpilot.common.basedir import BASEDIR - -def suffix(): - return ".dylib" if platform.system() == "Darwin" else ".so" - - -def get_ffi(): - lib = os.path.join(BASEDIR, "selfdrive", "ui", "qt", "libpython_helpers" + suffix()) - - ffi = FFI() - ffi.cdef("void set_main_window(void *w);") - return ffi, ffi.dlopen(lib) - - -def set_main_window(widget): - ffi, lib = get_ffi() - lib.set_main_window(ffi.cast('void*', sip.unwrapinstance(widget))) diff --git a/selfdrive/ui/qt/qt_window.cc b/selfdrive/ui/qt/qt_window.cc deleted file mode 100644 index 8d3d7cf72e..0000000000 --- a/selfdrive/ui/qt/qt_window.cc +++ /dev/null @@ -1,36 +0,0 @@ -#include "selfdrive/ui/qt/qt_window.h" - -void setMainWindow(QWidget *w) { - const float scale = util::getenv("SCALE", 1.0f); - const QSize sz = QGuiApplication::primaryScreen()->size(); - - if (Hardware::PC() && scale == 1.0 && !(sz - DEVICE_SCREEN_SIZE).isValid()) { - w->setMinimumSize(QSize(640, 480)); // allow resize smaller than fullscreen - w->setMaximumSize(DEVICE_SCREEN_SIZE); - w->resize(sz); - } else { - w->setFixedSize(DEVICE_SCREEN_SIZE * scale); - } - w->show(); - -#ifdef QCOM2 - QPlatformNativeInterface *native = QGuiApplication::platformNativeInterface(); - wl_surface *s = reinterpret_cast(native->nativeResourceForWindow("surface", w->windowHandle())); - wl_surface_set_buffer_transform(s, WL_OUTPUT_TRANSFORM_270); - wl_surface_commit(s); - - w->setWindowState(Qt::WindowFullScreen); - w->setVisible(true); - - // ensure we have a valid eglDisplay, otherwise the ui will silently fail - void *egl = native->nativeResourceForWindow("egldisplay", w->windowHandle()); - assert(egl != nullptr); -#endif -} - - -extern "C" { - void set_main_window(void *w) { - setMainWindow((QWidget*)w); - } -} diff --git a/selfdrive/ui/qt/qt_window.h b/selfdrive/ui/qt/qt_window.h deleted file mode 100644 index 6f16e00957..0000000000 --- a/selfdrive/ui/qt/qt_window.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once - -#include - -#include -#include -#include - -#ifdef QCOM2 -#include -#include -#include -#endif - -#include "system/hardware/hw.h" - -const QString ASSET_PATH = ":/"; -const QSize DEVICE_SCREEN_SIZE = {2160, 1080}; - -void setMainWindow(QWidget *w); diff --git a/selfdrive/ui/qt/request_repeater.cc b/selfdrive/ui/qt/request_repeater.cc deleted file mode 100644 index 7aa731898c..0000000000 --- a/selfdrive/ui/qt/request_repeater.cc +++ /dev/null @@ -1,27 +0,0 @@ -#include "selfdrive/ui/qt/request_repeater.h" - -RequestRepeater::RequestRepeater(QObject *parent, const QString &requestURL, const QString &cacheKey, - int period, bool while_onroad) : HttpRequest(parent) { - timer = new QTimer(this); - timer->setTimerType(Qt::VeryCoarseTimer); - QObject::connect(timer, &QTimer::timeout, [=]() { - if ((!uiState()->scene.started || while_onroad) && device()->isAwake() && !active()) { - sendRequest(requestURL); - } - }); - - timer->start(period * 1000); - - if (!cacheKey.isEmpty()) { - prevResp = QString::fromStdString(params.get(cacheKey.toStdString())); - if (!prevResp.isEmpty()) { - QTimer::singleShot(500, [=]() { emit requestDone(prevResp, true, QNetworkReply::NoError); }); - } - QObject::connect(this, &HttpRequest::requestDone, [=](const QString &resp, bool success) { - if (success && resp != prevResp) { - params.put(cacheKey.toStdString(), resp.toStdString()); - prevResp = resp; - } - }); - } -} diff --git a/selfdrive/ui/qt/request_repeater.h b/selfdrive/ui/qt/request_repeater.h deleted file mode 100644 index a0e8bde0eb..0000000000 --- a/selfdrive/ui/qt/request_repeater.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once - -#include "common/util.h" -#include "selfdrive/ui/qt/api.h" - -#ifdef SUNNYPILOT -#include "selfdrive/ui/sunnypilot/ui.h" -#else -#include "selfdrive/ui/ui.h" -#endif - -class RequestRepeater : public HttpRequest { -public: - RequestRepeater(QObject *parent, const QString &requestURL, const QString &cacheKey = "", int period = 0, bool while_onroad=false); - -private: - Params params; - QTimer *timer; - QString prevResp; -}; diff --git a/selfdrive/ui/qt/setup/reset.cc b/selfdrive/ui/qt/setup/reset.cc deleted file mode 100644 index 82fd5a7820..0000000000 --- a/selfdrive/ui/qt/setup/reset.cc +++ /dev/null @@ -1,141 +0,0 @@ -#include -#include -#include -#include -#include -#include - -#include "selfdrive/ui/qt/qt_window.h" -#include "selfdrive/ui/qt/setup/reset.h" - -#define NVME "/dev/nvme0n1" -#define USERDATA "/dev/disk/by-partlabel/userdata" - -void Reset::doErase() { - // best effort to wipe nvme - std::system("sudo umount " NVME); - std::system("yes | sudo mkfs.ext4 " NVME); - - int rm = std::system("sudo rm -rf /data/*"); - std::system("sudo umount " USERDATA); - int fmt = std::system("yes | sudo mkfs.ext4 " USERDATA); - - if (rm == 0 || fmt == 0) { - std::system("sudo reboot"); - } - body->setText(tr("Reset failed. Reboot to try again.")); - rebootBtn->show(); -} - -void Reset::startReset() { - body->setText(tr("Resetting device...\nThis may take up to a minute.")); - rejectBtn->hide(); - rebootBtn->hide(); - confirmBtn->hide(); -#ifdef __aarch64__ - QTimer::singleShot(100, this, &Reset::doErase); -#endif -} - -void Reset::confirm() { - const QString confirm_txt = tr("Are you sure you want to reset your device?"); - if (body->text() != confirm_txt) { - body->setText(confirm_txt); - } else { - startReset(); - } -} - -Reset::Reset(ResetMode mode, QWidget *parent) : QWidget(parent) { - QVBoxLayout *main_layout = new QVBoxLayout(this); - main_layout->setContentsMargins(45, 220, 45, 45); - main_layout->setSpacing(0); - - QLabel *title = new QLabel(tr("System Reset")); - title->setStyleSheet("font-size: 90px; font-weight: 600;"); - main_layout->addWidget(title, 0, Qt::AlignTop | Qt::AlignLeft); - - main_layout->addSpacing(60); - - body = new QLabel(tr("System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot.")); - body->setWordWrap(true); - body->setStyleSheet("font-size: 80px; font-weight: light;"); - main_layout->addWidget(body, 1, Qt::AlignTop | Qt::AlignLeft); - - QHBoxLayout *blayout = new QHBoxLayout(); - main_layout->addLayout(blayout); - blayout->setSpacing(50); - - rejectBtn = new QPushButton(tr("Cancel")); - blayout->addWidget(rejectBtn); - QObject::connect(rejectBtn, &QPushButton::clicked, QCoreApplication::instance(), &QCoreApplication::quit); - - rebootBtn = new QPushButton(tr("Reboot")); - blayout->addWidget(rebootBtn); -#ifdef __aarch64__ - QObject::connect(rebootBtn, &QPushButton::clicked, [=]{ - std::system("sudo reboot"); - }); -#endif - - confirmBtn = new QPushButton(tr("Confirm")); - confirmBtn->setStyleSheet(R"( - QPushButton { - background-color: #465BEA; - } - QPushButton:pressed { - background-color: #3049F4; - } - )"); - blayout->addWidget(confirmBtn); - QObject::connect(confirmBtn, &QPushButton::clicked, this, &Reset::confirm); - - bool recover = mode == ResetMode::RECOVER; - rejectBtn->setVisible(!recover); - rebootBtn->setVisible(recover); - if (recover) { - body->setText(tr("Unable to mount data partition. Partition may be corrupted. Press confirm to erase and reset your device.")); - } - - // automatically start if we're just finishing up an ABL reset - if (mode == ResetMode::FORMAT) { - startReset(); - } - - setStyleSheet(R"( - * { - font-family: Inter; - color: white; - background-color: black; - } - QLabel { - margin-left: 140; - } - QPushButton { - height: 160; - font-size: 55px; - font-weight: 400; - border-radius: 10px; - background-color: #333333; - } - QPushButton:pressed { - background-color: #444444; - } - )"); -} - -int main(int argc, char *argv[]) { - ResetMode mode = ResetMode::USER_RESET; - if (argc > 1) { - if (strcmp(argv[1], "--recover") == 0) { - mode = ResetMode::RECOVER; - } else if (strcmp(argv[1], "--format") == 0) { - mode = ResetMode::FORMAT; - } - } - - QApplication a(argc, argv); - Reset reset(mode); - setMainWindow(&reset); - return a.exec(); -} diff --git a/selfdrive/ui/qt/setup/reset.h b/selfdrive/ui/qt/setup/reset.h deleted file mode 100644 index 2e0784cdc9..0000000000 --- a/selfdrive/ui/qt/setup/reset.h +++ /dev/null @@ -1,27 +0,0 @@ -#include -#include -#include - -enum ResetMode { - USER_RESET, // user initiated a factory reset from openpilot - RECOVER, // userdata is corrupt for some reason, give a chance to recover - FORMAT, // finish up a factory reset from a tool that doesn't flash an empty partition to userdata -}; - -class Reset : public QWidget { - Q_OBJECT - -public: - explicit Reset(ResetMode mode, QWidget *parent = 0); - -private: - QLabel *body; - QPushButton *rejectBtn; - QPushButton *rebootBtn; - QPushButton *confirmBtn; - void doErase(); - void startReset(); - -private slots: - void confirm(); -}; diff --git a/selfdrive/ui/qt/setup/setup.cc b/selfdrive/ui/qt/setup/setup.cc deleted file mode 100644 index 90ed973b0d..0000000000 --- a/selfdrive/ui/qt/setup/setup.cc +++ /dev/null @@ -1,541 +0,0 @@ -#include "selfdrive/ui/qt/setup/setup.h" - -#include -#include -#include -#include - -#include -#include -#include - -#include - -#include "common/util.h" -#include "system/hardware/hw.h" -#include "selfdrive/ui/qt/api.h" -#include "selfdrive/ui/qt/qt_window.h" -#include "selfdrive/ui/qt/network/networking.h" -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/qt/widgets/input.h" - -const std::string USER_AGENT = "AGNOSSetup-"; -const QString OPENPILOT_URL = "https://openpilot.comma.ai"; - -bool is_elf(char *fname) { - FILE *fp = fopen(fname, "rb"); - if (fp == NULL) { - return false; - } - char buf[4]; - size_t n = fread(buf, 1, 4, fp); - fclose(fp); - return n == 4 && buf[0] == 0x7f && buf[1] == 'E' && buf[2] == 'L' && buf[3] == 'F'; -} - -void Setup::download(QString url) { - // autocomplete incomplete urls - if (QRegularExpression("^([^/.]+)/([^/]+)$").match(url).hasMatch()) { - url.prepend("https://installer.comma.ai/"); - } - - CURL *curl = curl_easy_init(); - if (!curl) { - emit finished(url, tr("Something went wrong. Reboot the device.")); - return; - } - - auto version = util::read_file("/VERSION"); - - struct curl_slist *list = NULL; - std::string header = "X-openpilot-serial: " + Hardware::get_serial(); - list = curl_slist_append(list, header.c_str()); - - char tmpfile[] = "/tmp/installer_XXXXXX"; - FILE *fp = fdopen(mkstemp(tmpfile), "wb"); - - curl_easy_setopt(curl, CURLOPT_URL, url.toStdString().c_str()); - curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, NULL); - curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); - curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); - curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); - curl_easy_setopt(curl, CURLOPT_USERAGENT, (USER_AGENT + version).c_str()); - curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list); - curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30L); - - int ret = curl_easy_perform(curl); - long res_status = 0; - curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &res_status); - - if (ret != CURLE_OK || res_status != 200) { - emit finished(url, tr("Ensure the entered URL is valid, and the device’s internet connection is good.")); - } else if (!is_elf(tmpfile)) { - emit finished(url, tr("No custom software found at this URL.")); - } else { - rename(tmpfile, "/tmp/installer"); - - FILE *fp_url = fopen("/tmp/installer_url", "w"); - fprintf(fp_url, "%s", url.toStdString().c_str()); - fclose(fp_url); - - emit finished(url); - } - - curl_slist_free_all(list); - curl_easy_cleanup(curl); - fclose(fp); -} - -QWidget * Setup::low_voltage() { - QWidget *widget = new QWidget(); - QVBoxLayout *main_layout = new QVBoxLayout(widget); - main_layout->setContentsMargins(55, 0, 55, 55); - main_layout->setSpacing(0); - - // inner text layout: warning icon, title, and body - QVBoxLayout *inner_layout = new QVBoxLayout(); - inner_layout->setContentsMargins(110, 144, 365, 0); - main_layout->addLayout(inner_layout); - - QLabel *triangle = new QLabel(); - triangle->setPixmap(QPixmap(ASSET_PATH + "icons/warning.png")); - inner_layout->addWidget(triangle, 0, Qt::AlignTop | Qt::AlignLeft); - inner_layout->addSpacing(80); - - QLabel *title = new QLabel(tr("WARNING: Low Voltage")); - title->setStyleSheet("font-size: 90px; font-weight: 500; color: #FF594F;"); - inner_layout->addWidget(title, 0, Qt::AlignTop | Qt::AlignLeft); - - inner_layout->addSpacing(25); - - QLabel *body = new QLabel(tr("Power your device in a car with a harness or proceed at your own risk.")); - body->setWordWrap(true); - body->setAlignment(Qt::AlignTop | Qt::AlignLeft); - body->setStyleSheet("font-size: 80px; font-weight: 300;"); - inner_layout->addWidget(body); - - inner_layout->addStretch(); - - // power off + continue buttons - QHBoxLayout *blayout = new QHBoxLayout(); - blayout->setSpacing(50); - main_layout->addLayout(blayout, 0); - - QPushButton *poweroff = new QPushButton(tr("Power off")); - poweroff->setObjectName("navBtn"); - blayout->addWidget(poweroff); - QObject::connect(poweroff, &QPushButton::clicked, this, [=]() { - Hardware::poweroff(); - }); - - QPushButton *cont = new QPushButton(tr("Continue")); - cont->setObjectName("navBtn"); - blayout->addWidget(cont); - QObject::connect(cont, &QPushButton::clicked, this, &Setup::nextPage); - - return widget; -} - -QWidget * Setup::custom_software_warning() { - QWidget *widget = new QWidget(); - QVBoxLayout *main_layout = new QVBoxLayout(widget); - main_layout->setContentsMargins(55, 0, 55, 55); - main_layout->setSpacing(0); - - QVBoxLayout *inner_layout = new QVBoxLayout(); - inner_layout->setContentsMargins(110, 110, 300, 0); - main_layout->addLayout(inner_layout); - - QLabel *title = new QLabel(tr("WARNING: Custom Software")); - title->setStyleSheet("font-size: 90px; font-weight: 500; color: #FF594F;"); - inner_layout->addWidget(title, 0, Qt::AlignTop | Qt::AlignLeft); - - inner_layout->addSpacing(25); - - QLabel *body = new QLabel(tr("Use caution when installing third-party software. Third-party software has not been tested by comma, and may cause damage to your device and/or vehicle.\n\nIf you'd like to proceed, use https://flash.comma.ai to restore your device to a factory state later.")); - body->setWordWrap(true); - body->setAlignment(Qt::AlignTop | Qt::AlignLeft); - body->setStyleSheet("font-size: 65px; font-weight: 300;"); - inner_layout->addWidget(body); - - inner_layout->addStretch(); - - QHBoxLayout *blayout = new QHBoxLayout(); - blayout->setSpacing(50); - main_layout->addLayout(blayout, 0); - - QPushButton *back = new QPushButton(tr("Back")); - back->setObjectName("navBtn"); - blayout->addWidget(back); - QObject::connect(back, &QPushButton::clicked, this, &Setup::prevPage); - - QPushButton *cont = new QPushButton(tr("Continue")); - cont->setObjectName("navBtn"); - blayout->addWidget(cont); - QObject::connect(cont, &QPushButton::clicked, this, [=]() { - QTimer::singleShot(0, [=]() { - setCurrentWidget(downloading_widget); - }); - QString url = InputDialog::getText(tr("Enter URL"), this, tr("for Custom Software")); - if (!url.isEmpty()) { - QTimer::singleShot(1000, this, [=]() { - download(url); - }); - } else { - setCurrentWidget(software_selection_widget); - } - }); - - return widget; -} - -QWidget * Setup::getting_started() { - QWidget *widget = new QWidget(); - - QHBoxLayout *main_layout = new QHBoxLayout(widget); - main_layout->setMargin(0); - - QVBoxLayout *vlayout = new QVBoxLayout(); - vlayout->setContentsMargins(165, 280, 100, 0); - main_layout->addLayout(vlayout); - - QLabel *title = new QLabel(tr("Getting Started")); - title->setStyleSheet("font-size: 90px; font-weight: 500;"); - vlayout->addWidget(title, 0, Qt::AlignTop | Qt::AlignLeft); - - vlayout->addSpacing(90); - QLabel *desc = new QLabel(tr("Before we get on the road, let’s finish installation and cover some details.")); - desc->setWordWrap(true); - desc->setStyleSheet("font-size: 80px; font-weight: 300;"); - vlayout->addWidget(desc, 0, Qt::AlignTop | Qt::AlignLeft); - - vlayout->addStretch(); - - QPushButton *btn = new QPushButton(); - btn->setIcon(QIcon(":/images/button_continue_triangle.svg")); - btn->setIconSize(QSize(54, 106)); - btn->setFixedSize(310, 1080); - btn->setProperty("primary", true); - btn->setStyleSheet("border: none;"); - main_layout->addWidget(btn, 0, Qt::AlignRight); - QObject::connect(btn, &QPushButton::clicked, this, &Setup::nextPage); - - return widget; -} - -QWidget * Setup::network_setup() { - QWidget *widget = new QWidget(); - QVBoxLayout *main_layout = new QVBoxLayout(widget); - main_layout->setContentsMargins(55, 50, 55, 50); - - // title - QLabel *title = new QLabel(tr("Connect to Wi-Fi")); - title->setStyleSheet("font-size: 90px; font-weight: 500;"); - main_layout->addWidget(title, 0, Qt::AlignLeft | Qt::AlignTop); - - main_layout->addSpacing(25); - - // wifi widget - Networking *networking = new Networking(this, false); - networking->setStyleSheet("Networking {background-color: #292929; border-radius: 13px;}"); - main_layout->addWidget(networking, 1); - - main_layout->addSpacing(35); - - // back + continue buttons - QHBoxLayout *blayout = new QHBoxLayout; - main_layout->addLayout(blayout); - blayout->setSpacing(50); - - QPushButton *back = new QPushButton(tr("Back")); - back->setObjectName("navBtn"); - QObject::connect(back, &QPushButton::clicked, this, &Setup::prevPage); - blayout->addWidget(back); - - QPushButton *cont = new QPushButton(); - cont->setObjectName("navBtn"); - cont->setProperty("primary", true); - cont->setEnabled(false); - QObject::connect(cont, &QPushButton::clicked, this, &Setup::nextPage); - blayout->addWidget(cont); - - // setup timer for testing internet connection - HttpRequest *request = new HttpRequest(this, false, 2500); - QObject::connect(request, &HttpRequest::requestDone, [=](const QString &, bool success) { - cont->setEnabled(success); - if (success) { - const bool wifi = networking->wifi->currentNetworkType() == NetworkType::WIFI; - cont->setText(wifi ? tr("Continue") : tr("Continue without Wi-Fi")); - } else { - cont->setText(tr("Waiting for internet")); - } - repaint(); - }); - request->sendRequest(OPENPILOT_URL); - QTimer *timer = new QTimer(this); - QObject::connect(timer, &QTimer::timeout, [=]() { - if (!request->active() && cont->isVisible()) { - request->sendRequest(OPENPILOT_URL); - } - }); - timer->start(1000); - - return widget; -} - -QWidget * radio_button(QString title, QButtonGroup *group) { - QPushButton *btn = new QPushButton(title); - btn->setCheckable(true); - group->addButton(btn); - btn->setStyleSheet(R"( - QPushButton { - height: 230; - padding-left: 100px; - padding-right: 100px; - text-align: left; - font-size: 80px; - font-weight: 400; - border-radius: 10px; - background-color: #4F4F4F; - } - QPushButton:checked { - background-color: #465BEA; - } - )"); - - // checkmark icon - QPixmap pix(":/icons/circled_check.svg"); - btn->setIcon(pix); - btn->setIconSize(QSize(0, 0)); - btn->setLayoutDirection(Qt::RightToLeft); - QObject::connect(btn, &QPushButton::toggled, [=](bool checked) { - btn->setIconSize(checked ? QSize(104, 104) : QSize(0, 0)); - }); - return btn; -} - -QWidget * Setup::software_selection() { - QWidget *widget = new QWidget(); - QVBoxLayout *main_layout = new QVBoxLayout(widget); - main_layout->setContentsMargins(55, 50, 55, 50); - main_layout->setSpacing(0); - - // title - QLabel *title = new QLabel(tr("Choose Software to Install")); - title->setStyleSheet("font-size: 90px; font-weight: 500;"); - main_layout->addWidget(title, 0, Qt::AlignLeft | Qt::AlignTop); - - main_layout->addSpacing(50); - - // sunnypilot + custom radio buttons - QButtonGroup *group = new QButtonGroup(widget); - group->setExclusive(true); - - QWidget *openpilot = radio_button(tr("sunnypilot"), group); - main_layout->addWidget(openpilot); - - main_layout->addSpacing(30); - - QWidget *custom = radio_button(tr("Custom Software"), group); - main_layout->addWidget(custom); - - main_layout->addStretch(); - - // back + continue buttons - QHBoxLayout *blayout = new QHBoxLayout; - main_layout->addLayout(blayout); - blayout->setSpacing(50); - - QPushButton *back = new QPushButton(tr("Back")); - back->setObjectName("navBtn"); - QObject::connect(back, &QPushButton::clicked, this, &Setup::prevPage); - blayout->addWidget(back); - - QPushButton *cont = new QPushButton(tr("Continue")); - cont->setObjectName("navBtn"); - cont->setEnabled(false); - cont->setProperty("primary", true); - blayout->addWidget(cont); - - QObject::connect(cont, &QPushButton::clicked, [=]() { - if (group->checkedButton() != openpilot) { - QTimer::singleShot(0, [=]() { - setCurrentWidget(custom_software_warning_widget); - }); - } else { - QTimer::singleShot(0, [=]() { - setCurrentWidget(downloading_widget); - }); - QTimer::singleShot(1000, this, [=]() { - download(OPENPILOT_URL); - }); - } - }); - - connect(group, QOverload::of(&QButtonGroup::buttonClicked), [=](QAbstractButton *btn) { - btn->setChecked(true); - cont->setEnabled(true); - }); - - return widget; -} - -QWidget * Setup::downloading() { - QWidget *widget = new QWidget(); - QVBoxLayout *main_layout = new QVBoxLayout(widget); - QLabel *txt = new QLabel(tr("Downloading...")); - txt->setStyleSheet("font-size: 90px; font-weight: 500;"); - main_layout->addWidget(txt, 0, Qt::AlignCenter); - return widget; -} - -QWidget * Setup::download_failed(QLabel *url, QLabel *body) { - QWidget *widget = new QWidget(); - QVBoxLayout *main_layout = new QVBoxLayout(widget); - main_layout->setContentsMargins(55, 185, 55, 55); - main_layout->setSpacing(0); - - QLabel *title = new QLabel(tr("Download Failed")); - title->setStyleSheet("font-size: 90px; font-weight: 500;"); - main_layout->addWidget(title, 0, Qt::AlignTop | Qt::AlignLeft); - - main_layout->addSpacing(67); - - url->setWordWrap(true); - url->setAlignment(Qt::AlignTop | Qt::AlignLeft); - url->setStyleSheet("font-family: \"JetBrains Mono\"; font-size: 64px; font-weight: 400; margin-right: 100px;"); - main_layout->addWidget(url); - - main_layout->addSpacing(48); - - body->setWordWrap(true); - body->setAlignment(Qt::AlignTop | Qt::AlignLeft); - body->setStyleSheet("font-size: 80px; font-weight: 300; margin-right: 100px;"); - main_layout->addWidget(body); - - main_layout->addStretch(); - - // reboot + start over buttons - QHBoxLayout *blayout = new QHBoxLayout(); - blayout->setSpacing(50); - main_layout->addLayout(blayout, 0); - - QPushButton *reboot = new QPushButton(tr("Reboot device")); - reboot->setObjectName("navBtn"); - blayout->addWidget(reboot); - QObject::connect(reboot, &QPushButton::clicked, this, [=]() { - Hardware::reboot(); - }); - - QPushButton *restart = new QPushButton(tr("Start over")); - restart->setObjectName("navBtn"); - restart->setProperty("primary", true); - blayout->addWidget(restart); - QObject::connect(restart, &QPushButton::clicked, this, [=]() { - setCurrentIndex(1); - }); - - widget->setStyleSheet(R"( - QLabel { - margin-left: 117; - } - )"); - return widget; -} - -void Setup::prevPage() { - setCurrentIndex(currentIndex() - 1); -} - -void Setup::nextPage() { - setCurrentIndex(currentIndex() + 1); -} - -Setup::Setup(QWidget *parent) : QStackedWidget(parent) { - if (std::getenv("MULTILANG")) { - selectLanguage(); - } - - std::stringstream buffer; - buffer << std::ifstream("/sys/class/hwmon/hwmon1/in1_input").rdbuf(); - float voltage = (float)std::atoi(buffer.str().c_str()) / 1000.; - if (voltage < 7) { - addWidget(low_voltage()); - } - - addWidget(getting_started()); - addWidget(network_setup()); - software_selection_widget = software_selection(); - addWidget(software_selection_widget); - custom_software_warning_widget = custom_software_warning(); - addWidget(custom_software_warning_widget); - downloading_widget = downloading(); - addWidget(downloading_widget); - - QLabel *url_label = new QLabel(); - QLabel *body_label = new QLabel(); - failed_widget = download_failed(url_label, body_label); - addWidget(failed_widget); - - QObject::connect(this, &Setup::finished, [=](const QString &url, const QString &error) { - qDebug() << "finished" << url << error; - if (error.isEmpty()) { - // hide setup on success - QTimer::singleShot(3000, this, &QWidget::hide); - } else { - url_label->setText(url); - body_label->setText(error); - setCurrentWidget(failed_widget); - } - }); - - // TODO: revisit pressed bg color - setStyleSheet(R"( - * { - color: white; - font-family: Inter; - } - Setup { - background-color: black; - } - QPushButton#navBtn { - height: 160; - font-size: 55px; - font-weight: 400; - border-radius: 10px; - background-color: #333333; - } - QPushButton#navBtn:disabled, QPushButton[primary='true']:disabled { - color: #808080; - background-color: #333333; - } - QPushButton#navBtn:pressed { - background-color: #444444; - } - QPushButton[primary='true'], #navBtn[primary='true'] { - background-color: #465BEA; - } - QPushButton[primary='true']:pressed, #navBtn:pressed[primary='true'] { - background-color: #3049F4; - } - )"); -} - -void Setup::selectLanguage() { - QMap langs = getSupportedLanguages(); - QString selection = MultiOptionDialog::getSelection(tr("Select a language"), langs.keys(), "", this); - if (!selection.isEmpty()) { - QString selectedLang = langs[selection]; - Params().put("LanguageSetting", selectedLang.toStdString()); - if (translator.load(":/" + selectedLang)) { - qApp->installTranslator(&translator); - } - } -} - -int main(int argc, char *argv[]) { - QApplication a(argc, argv); - Setup setup; - setMainWindow(&setup); - return a.exec(); -} diff --git a/selfdrive/ui/qt/setup/setup.h b/selfdrive/ui/qt/setup/setup.h deleted file mode 100644 index 986956c902..0000000000 --- a/selfdrive/ui/qt/setup/setup.h +++ /dev/null @@ -1,38 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include - -class Setup : public QStackedWidget { - Q_OBJECT - -public: - explicit Setup(QWidget *parent = 0); - -private: - void selectLanguage(); - QWidget *low_voltage(); - QWidget *custom_software_warning(); - QWidget *getting_started(); - QWidget *network_setup(); - QWidget *software_selection(); - QWidget *downloading(); - QWidget *download_failed(QLabel *url, QLabel *body); - - QWidget *failed_widget; - QWidget *downloading_widget; - QWidget *custom_software_warning_widget; - QWidget *software_selection_widget; - QTranslator translator; - -signals: - void finished(const QString &url, const QString &error = ""); - -public slots: - void nextPage(); - void prevPage(); - void download(QString url); -}; diff --git a/selfdrive/ui/qt/setup/updater.cc b/selfdrive/ui/qt/setup/updater.cc deleted file mode 100644 index ed47590aa3..0000000000 --- a/selfdrive/ui/qt/setup/updater.cc +++ /dev/null @@ -1,186 +0,0 @@ -#include -#include -#include - -#include "system/hardware/hw.h" -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/qt/qt_window.h" -#include "selfdrive/ui/qt/setup/updater.h" -#include "selfdrive/ui/qt/network/networking.h" - -Updater::Updater(const QString &updater_path, const QString &manifest_path, QWidget *parent) - : updater(updater_path), manifest(manifest_path), QStackedWidget(parent) { - - assert(updater.size()); - assert(manifest.size()); - - // initial prompt screen - prompt = new QWidget; - { - QVBoxLayout *layout = new QVBoxLayout(prompt); - layout->setContentsMargins(100, 250, 100, 100); - - QLabel *title = new QLabel(tr("Update Required")); - title->setStyleSheet("font-size: 80px; font-weight: bold;"); - layout->addWidget(title); - - layout->addSpacing(75); - - QLabel *desc = new QLabel(tr("An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. The download size is approximately 1GB.")); - desc->setWordWrap(true); - desc->setStyleSheet("font-size: 65px;"); - layout->addWidget(desc); - - layout->addStretch(); - - QHBoxLayout *hlayout = new QHBoxLayout; - hlayout->setSpacing(30); - layout->addLayout(hlayout); - - QPushButton *connect = new QPushButton(tr("Connect to Wi-Fi")); - connect->setObjectName("navBtn"); - QObject::connect(connect, &QPushButton::clicked, [=]() { - setCurrentWidget(wifi); - }); - hlayout->addWidget(connect); - - QPushButton *install = new QPushButton(tr("Install")); - install->setObjectName("navBtn"); - install->setStyleSheet(R"( - QPushButton { - background-color: #465BEA; - } - QPushButton:pressed { - background-color: #3049F4; - } - )"); - QObject::connect(install, &QPushButton::clicked, this, &Updater::installUpdate); - hlayout->addWidget(install); - } - - // wifi connection screen - wifi = new QWidget; - { - QVBoxLayout *layout = new QVBoxLayout(wifi); - layout->setContentsMargins(100, 100, 100, 100); - - Networking *networking = new Networking(this, false); - networking->setStyleSheet("Networking { background-color: #292929; border-radius: 13px; }"); - layout->addWidget(networking, 1); - - QPushButton *back = new QPushButton(tr("Back")); - back->setObjectName("navBtn"); - back->setStyleSheet("padding-left: 60px; padding-right: 60px;"); - QObject::connect(back, &QPushButton::clicked, [=]() { - setCurrentWidget(prompt); - }); - layout->addWidget(back, 0, Qt::AlignLeft); - } - - // progress screen - progress = new QWidget; - { - QVBoxLayout *layout = new QVBoxLayout(progress); - layout->setContentsMargins(150, 330, 150, 150); - layout->setSpacing(0); - - text = new QLabel(tr("Loading...")); - text->setStyleSheet("font-size: 90px; font-weight: 600;"); - layout->addWidget(text, 0, Qt::AlignTop); - - layout->addSpacing(100); - - bar = new QProgressBar(); - bar->setRange(0, 100); - bar->setTextVisible(false); - bar->setFixedHeight(72); - layout->addWidget(bar, 0, Qt::AlignTop); - - layout->addStretch(); - - reboot = new QPushButton(tr("Reboot")); - reboot->setObjectName("navBtn"); - reboot->setStyleSheet("padding-left: 60px; padding-right: 60px;"); - QObject::connect(reboot, &QPushButton::clicked, [=]() { - Hardware::reboot(); - }); - layout->addWidget(reboot, 0, Qt::AlignLeft); - reboot->hide(); - - layout->addStretch(); - } - - addWidget(prompt); - addWidget(wifi); - addWidget(progress); - - setStyleSheet(R"( - * { - color: white; - outline: none; - font-family: Inter; - } - Updater { - color: white; - background-color: black; - } - QPushButton#navBtn { - height: 160; - font-size: 55px; - font-weight: 400; - border-radius: 10px; - background-color: #333333; - } - QPushButton#navBtn:pressed { - background-color: #444444; - } - QProgressBar { - border: none; - background-color: #292929; - } - QProgressBar::chunk { - background-color: #364DEF; - } - )"); -} - -void Updater::installUpdate() { - setCurrentWidget(progress); - QObject::connect(&proc, &QProcess::readyReadStandardOutput, this, &Updater::readProgress); - QObject::connect(&proc, QOverload::of(&QProcess::finished), this, &Updater::updateFinished); - proc.setProcessChannelMode(QProcess::ForwardedErrorChannel); - proc.start(updater, {"--swap", manifest}); -} - -void Updater::readProgress() { - auto lines = QString(proc.readAllStandardOutput()); - for (const QString &line : lines.trimmed().split("\n")) { - auto parts = line.split(":"); - if (parts.size() == 2) { - text->setText(parts[0]); - bar->setValue((int)parts[1].toDouble()); - } else { - qDebug() << line; - } - } - update(); -} - -void Updater::updateFinished(int exitCode, QProcess::ExitStatus exitStatus) { - qDebug() << "finished with " << exitCode; - if (exitCode == 0) { - Hardware::reboot(); - } else { - text->setText(tr("Update failed")); - reboot->show(); - } -} - -int main(int argc, char *argv[]) { - initApp(argc, argv); - QApplication a(argc, argv); - Updater updater(argv[1], argv[2]); - setMainWindow(&updater); - a.installEventFilter(&updater); - return a.exec(); -} diff --git a/selfdrive/ui/qt/setup/updater.h b/selfdrive/ui/qt/setup/updater.h deleted file mode 100644 index ce46c0aabd..0000000000 --- a/selfdrive/ui/qt/setup/updater.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include - -class Updater : public QStackedWidget { - Q_OBJECT - -public: - explicit Updater(const QString &updater_path, const QString &manifest_path, QWidget *parent = 0); - -private slots: - void installUpdate(); - void readProgress(); - void updateFinished(int exitCode, QProcess::ExitStatus exitStatus); - -private: - QProcess proc; - QString updater, manifest; - - QLabel *text; - QProgressBar *bar; - QPushButton *reboot; - QWidget *prompt, *wifi, *progress; -}; diff --git a/selfdrive/ui/qt/sidebar.cc b/selfdrive/ui/qt/sidebar.cc deleted file mode 100644 index fd8ea5bcf5..0000000000 --- a/selfdrive/ui/qt/sidebar.cc +++ /dev/null @@ -1,149 +0,0 @@ -#include "selfdrive/ui/qt/sidebar.h" - -#include - -#include "selfdrive/ui/qt/util.h" - -void Sidebar::drawMetric(QPainter &p, const QPair &label, QColor c, int y) { - const QRect rect = {30, y, 240, 126}; - - p.setPen(Qt::NoPen); - p.setBrush(QBrush(c)); - p.setClipRect(rect.x() + 4, rect.y(), 18, rect.height(), Qt::ClipOperation::ReplaceClip); - p.drawRoundedRect(QRect(rect.x() + 4, rect.y() + 4, 100, 118), 18, 18); - p.setClipping(false); - - QPen pen = QPen(QColor(0xff, 0xff, 0xff, 0x55)); - pen.setWidth(2); - p.setPen(pen); - p.setBrush(Qt::NoBrush); - p.drawRoundedRect(rect, 20, 20); - - p.setPen(QColor(0xff, 0xff, 0xff)); - p.setFont(InterFont(35, QFont::DemiBold)); - p.drawText(rect.adjusted(22, 0, 0, 0), Qt::AlignCenter, label.first + "\n" + label.second); -} - -Sidebar::Sidebar(QWidget *parent) : QFrame(parent), onroad(false), flag_pressed(false), settings_pressed(false) { - home_img = loadPixmap("../assets/images/button_home.png", home_btn.size()); - flag_img = loadPixmap("../assets/images/button_flag.png", home_btn.size()); - settings_img = loadPixmap("../assets/images/button_settings.png", settings_btn.size(), Qt::IgnoreAspectRatio); - - connect(this, &Sidebar::valueChanged, [=] { update(); }); - - setAttribute(Qt::WA_OpaquePaintEvent); - setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding); - setFixedWidth(300); - - QObject::connect(uiState(), &UIState::uiUpdate, this, &Sidebar::updateState); - - pm = std::make_unique(std::vector{"userFlag"}); -} - -void Sidebar::mousePressEvent(QMouseEvent *event) { - if (onroad && home_btn.contains(event->pos())) { - flag_pressed = true; - update(); - } else if (settings_btn.contains(event->pos())) { - settings_pressed = true; - update(); - } -} - -void Sidebar::mouseReleaseEvent(QMouseEvent *event) { - if (flag_pressed || settings_pressed) { - flag_pressed = settings_pressed = false; - update(); - } - if (onroad && home_btn.contains(event->pos())) { - MessageBuilder msg; - msg.initEvent().initUserFlag(); - pm->send("userFlag", msg); - } else if (settings_btn.contains(event->pos())) { - emit openSettings(); - } -} - -void Sidebar::offroadTransition(bool offroad) { - onroad = !offroad; - update(); -} - -void Sidebar::updateState(const UIState &s) { - if (!isVisible()) return; - - auto &sm = *(s.sm); - - networking = networking ? networking : window()->findChild(""); - bool tethering_on = networking && networking->wifi->tethering_on; - auto deviceState = sm["deviceState"].getDeviceState(); - setProperty("netType", tethering_on ? "Hotspot": network_type[deviceState.getNetworkType()]); - int strength = tethering_on ? 4 : (int)deviceState.getNetworkStrength(); - setProperty("netStrength", strength > 0 ? strength + 1 : 0); - - ItemStatus connectStatus; - auto last_ping = deviceState.getLastAthenaPingTime(); - if (last_ping == 0) { - connectStatus = ItemStatus{{tr("CONNECT"), tr("OFFLINE")}, warning_color}; - } else { - connectStatus = nanos_since_boot() - last_ping < 80e9 - ? ItemStatus{{tr("CONNECT"), tr("ONLINE")}, good_color} - : ItemStatus{{tr("CONNECT"), tr("ERROR")}, danger_color}; - } - setProperty("connectStatus", QVariant::fromValue(connectStatus)); - - ItemStatus tempStatus = {{tr("TEMP"), tr("HIGH")}, danger_color}; - auto ts = deviceState.getThermalStatus(); - if (ts == cereal::DeviceState::ThermalStatus::GREEN) { - tempStatus = {{tr("TEMP"), tr("GOOD")}, good_color}; - } else if (ts == cereal::DeviceState::ThermalStatus::YELLOW) { - tempStatus = {{tr("TEMP"), tr("OK")}, warning_color}; - } - setProperty("tempStatus", QVariant::fromValue(tempStatus)); - - ItemStatus pandaStatus = {{tr("VEHICLE"), tr("ONLINE")}, good_color}; - if (s.scene.pandaType == cereal::PandaState::PandaType::UNKNOWN) { - pandaStatus = {{tr("NO"), tr("PANDA")}, danger_color}; - } - setProperty("pandaStatus", QVariant::fromValue(pandaStatus)); -} - -void Sidebar::paintEvent(QPaintEvent *event) { - QPainter p(this); - drawSidebar(p); -} - -void Sidebar::drawSidebar(QPainter &p) { - p.setPen(Qt::NoPen); - p.setRenderHint(QPainter::Antialiasing); - - p.fillRect(rect(), QColor(57, 57, 57)); - - // buttons - p.setOpacity(settings_pressed ? 0.65 : 1.0); - p.drawPixmap(settings_btn.x(), settings_btn.y(), settings_img); - p.setOpacity(onroad && flag_pressed ? 0.65 : 1.0); - p.drawPixmap(home_btn.x(), home_btn.y(), onroad ? flag_img : home_img); - p.setOpacity(1.0); - - // network - int x = 58; - const QColor gray(0x54, 0x54, 0x54); - for (int i = 0; i < 5; ++i) { - p.setBrush(i < net_strength ? Qt::white : gray); - p.drawEllipse(x, 196, 27, 27); - x += 37; - } - - p.setFont(InterFont(35)); - p.setPen(QColor(0xff, 0xff, 0xff)); - const QRect r = QRect(58, 247, width() - 100, 50); - p.drawText(r, Qt::AlignLeft | Qt::AlignVCenter, net_type); - -#ifndef SUNNYPILOT - // metrics - drawMetric(p, temp_status.first, temp_status.second, 338); - drawMetric(p, panda_status.first, panda_status.second, 496); - drawMetric(p, connect_status.first, connect_status.second, 654); -#endif -} diff --git a/selfdrive/ui/qt/sidebar.h b/selfdrive/ui/qt/sidebar.h deleted file mode 100644 index 3c57d10a1a..0000000000 --- a/selfdrive/ui/qt/sidebar.h +++ /dev/null @@ -1,70 +0,0 @@ -#pragma once - -#include - -#include -#include - -#include "selfdrive/ui/qt/network/networking.h" - -#ifdef SUNNYPILOT -#include "selfdrive/ui/sunnypilot/ui.h" -#else -#include "selfdrive/ui/ui.h" -#endif - -typedef QPair, QColor> ItemStatus; -Q_DECLARE_METATYPE(ItemStatus); - -class Sidebar : public QFrame { - Q_OBJECT - Q_PROPERTY(ItemStatus connectStatus MEMBER connect_status NOTIFY valueChanged); - Q_PROPERTY(ItemStatus pandaStatus MEMBER panda_status NOTIFY valueChanged); - Q_PROPERTY(ItemStatus tempStatus MEMBER temp_status NOTIFY valueChanged); - Q_PROPERTY(QString netType MEMBER net_type NOTIFY valueChanged); - Q_PROPERTY(int netStrength MEMBER net_strength NOTIFY valueChanged); - -public: - explicit Sidebar(QWidget* parent = 0); - -signals: - void openSettings(int index = 0, const QString ¶m = ""); - void valueChanged(); - -public slots: - void offroadTransition(bool offroad); - void updateState(const UIState &s); - -protected: - void paintEvent(QPaintEvent *event) override; - void mousePressEvent(QMouseEvent *event) override; - void mouseReleaseEvent(QMouseEvent *event) override; - void drawMetric(QPainter &p, const QPair &label, QColor c, int y); - virtual void drawSidebar(QPainter &p); - - QPixmap home_img, flag_img, settings_img; - bool onroad, flag_pressed, settings_pressed; - const QMap network_type = { - {cereal::DeviceState::NetworkType::NONE, tr("--")}, - {cereal::DeviceState::NetworkType::WIFI, tr("Wi-Fi")}, - {cereal::DeviceState::NetworkType::ETHERNET, tr("ETH")}, - {cereal::DeviceState::NetworkType::CELL2_G, tr("2G")}, - {cereal::DeviceState::NetworkType::CELL3_G, tr("3G")}, - {cereal::DeviceState::NetworkType::CELL4_G, tr("LTE")}, - {cereal::DeviceState::NetworkType::CELL5_G, tr("5G")} - }; - - const QRect home_btn = QRect(60, 860, 180, 180); - const QRect settings_btn = QRect(50, 35, 200, 117); - const QColor good_color = QColor(255, 255, 255); - const QColor warning_color = QColor(218, 202, 37); - const QColor danger_color = QColor(201, 34, 49); - - ItemStatus connect_status, panda_status, temp_status; - QString net_type; - int net_strength = 0; - -private: - std::unique_ptr pm; - Networking *networking = nullptr; -}; diff --git a/selfdrive/ui/qt/util.cc b/selfdrive/ui/qt/util.cc deleted file mode 100644 index dedc59f0e4..0000000000 --- a/selfdrive/ui/qt/util.cc +++ /dev/null @@ -1,223 +0,0 @@ -#include "selfdrive/ui/qt/util.h" - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "common/swaglog.h" -#include "system/hardware/hw.h" - -QString getVersion() { - static QString version = QString::fromStdString(Params().get("Version")); - return version; -} - -QString getBrand() { - return QObject::tr("sunnypilot"); -} - -QString getUserAgent() { - return "openpilot-" + getVersion(); -} - -std::optional getDongleId() { - std::string id = Params().get("DongleId"); - - if (!id.empty() && (id != "UnregisteredDevice")) { - return QString::fromStdString(id); - } else { - return {}; - } -} - -QMap getSupportedLanguages() { - QFile f(":/languages.json"); - f.open(QIODevice::ReadOnly | QIODevice::Text); - QString val = f.readAll(); - - QJsonObject obj = QJsonDocument::fromJson(val.toUtf8()).object(); - QMap map; - for (auto key : obj.keys()) { - map[key] = obj[key].toString(); - } - return map; -} - -QString timeAgo(const QDateTime &date) { - int diff = date.secsTo(QDateTime::currentDateTimeUtc()); - - QString s; - if (diff < 60) { - s = QObject::tr("now"); - } else if (diff < 60 * 60) { - int minutes = diff / 60; - s = QObject::tr("%n minute(s) ago", "", minutes); - } else if (diff < 60 * 60 * 24) { - int hours = diff / (60 * 60); - s = QObject::tr("%n hour(s) ago", "", hours); - } else if (diff < 3600 * 24 * 7) { - int days = diff / (60 * 60 * 24); - s = QObject::tr("%n day(s) ago", "", days); - } else { - s = date.date().toString(); - } - - return s; -} - -void setQtSurfaceFormat() { - QSurfaceFormat fmt; -#ifdef __APPLE__ - fmt.setVersion(3, 2); - fmt.setProfile(QSurfaceFormat::OpenGLContextProfile::CoreProfile); - fmt.setRenderableType(QSurfaceFormat::OpenGL); -#else - fmt.setRenderableType(QSurfaceFormat::OpenGLES); -#endif - fmt.setSamples(16); - fmt.setStencilBufferSize(1); - QSurfaceFormat::setDefaultFormat(fmt); -} - -void sigTermHandler(int s) { - std::signal(s, SIG_DFL); - qApp->quit(); -} - -void initApp(int argc, char *argv[], bool disable_hidpi) { - Hardware::set_display_power(true); - Hardware::set_brightness(65); - - // setup signal handlers to exit gracefully - std::signal(SIGINT, sigTermHandler); - std::signal(SIGTERM, sigTermHandler); - - QString app_dir; -#ifdef __APPLE__ - // Get the devicePixelRatio, and scale accordingly to maintain 1:1 rendering - QApplication tmp(argc, argv); - app_dir = QCoreApplication::applicationDirPath(); - if (disable_hidpi) { - qputenv("QT_SCALE_FACTOR", QString::number(1.0 / tmp.devicePixelRatio()).toLocal8Bit()); - } -#else - app_dir = QFileInfo(util::readlink("/proc/self/exe").c_str()).path(); -#endif - - qputenv("QT_DBL_CLICK_DIST", QByteArray::number(150)); - // ensure the current dir matches the exectuable's directory - QDir::setCurrent(app_dir); - - setQtSurfaceFormat(); -} - -void swagLogMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg) { - static std::map levels = { - {QtMsgType::QtDebugMsg, CLOUDLOG_DEBUG}, - {QtMsgType::QtInfoMsg, CLOUDLOG_INFO}, - {QtMsgType::QtWarningMsg, CLOUDLOG_WARNING}, - {QtMsgType::QtCriticalMsg, CLOUDLOG_ERROR}, - {QtMsgType::QtSystemMsg, CLOUDLOG_ERROR}, - {QtMsgType::QtFatalMsg, CLOUDLOG_CRITICAL}, - }; - - std::string file, function; - if (context.file != nullptr) file = context.file; - if (context.function != nullptr) function = context.function; - - auto bts = msg.toUtf8(); - cloudlog_e(levels[type], file.c_str(), context.line, function.c_str(), "%s", bts.constData()); -} - - -QWidget* topWidget(QWidget* widget) { - while (widget->parentWidget() != nullptr) widget=widget->parentWidget(); - return widget; -} - -QPixmap loadPixmap(const QString &fileName, const QSize &size, Qt::AspectRatioMode aspectRatioMode) { - if (size.isEmpty()) { - return QPixmap(fileName); - } else { - return QPixmap(fileName).scaled(size, aspectRatioMode, Qt::SmoothTransformation); - } -} - -static QHash load_bootstrap_icons() { - QHash icons; - - QFile f(":/bootstrap-icons.svg"); - if (f.open(QIODevice::ReadOnly | QIODevice::Text)) { - QDomDocument xml; - xml.setContent(&f); - QDomNode n = xml.documentElement().firstChild(); - while (!n.isNull()) { - QDomElement e = n.toElement(); - if (!e.isNull() && e.hasAttribute("id")) { - QString svg_str; - QTextStream stream(&svg_str); - n.save(stream, 0); - svg_str.replace("", ""); - icons[e.attribute("id")] = svg_str.toUtf8(); - } - n = n.nextSibling(); - } - } - return icons; -} - -QPixmap bootstrapPixmap(const QString &id) { - static QHash icons = load_bootstrap_icons(); - - QPixmap pixmap; - if (auto it = icons.find(id); it != icons.end()) { - pixmap.loadFromData(it.value(), "svg"); - } - return pixmap; -} - -bool hasLongitudinalControl(const cereal::CarParams::Reader &car_params) { - // Using the experimental longitudinal toggle, returns whether longitudinal control - // will be active without needing a restart of openpilot - return car_params.getAlphaLongitudinalAvailable() - ? Params().getBool("AlphaLongitudinalEnabled") - : car_params.getOpenpilotLongitudinalControl(); -} - -// ParamWatcher - -ParamWatcher::ParamWatcher(QObject *parent) : QObject(parent) { - watcher = new QFileSystemWatcher(this); - QObject::connect(watcher, &QFileSystemWatcher::fileChanged, this, &ParamWatcher::fileChanged); -} - -void ParamWatcher::fileChanged(const QString &path) { - auto param_name = QFileInfo(path).fileName(); - auto param_value = QString::fromStdString(params.get(param_name.toStdString())); - - auto it = params_hash.find(param_name); - bool content_changed = (it == params_hash.end()) || (it.value() != param_value); - params_hash[param_name] = param_value; - // emit signal when the content changes. - if (content_changed) { - emit paramChanged(param_name, param_value); - } -} - -void ParamWatcher::addParam(const QString ¶m_name) { - watcher->addPath(QString::fromStdString(params.getParamPath(param_name.toStdString()))); -} diff --git a/selfdrive/ui/qt/util.h b/selfdrive/ui/qt/util.h deleted file mode 100644 index 2bf1a70a62..0000000000 --- a/selfdrive/ui/qt/util.h +++ /dev/null @@ -1,54 +0,0 @@ -#pragma once - -#include -#include - -#include -#include -#include -#include -#include -#include - -#include "cereal/gen/cpp/car.capnp.h" -#include "common/params.h" - -QString getVersion(); -QString getBrand(); -QString getUserAgent(); -std::optional getDongleId(); -QMap getSupportedLanguages(); -void setQtSurfaceFormat(); -void sigTermHandler(int s); -QString timeAgo(const QDateTime &date); -void swagLogMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg); -void initApp(int argc, char *argv[], bool disable_hidpi = true); -QWidget* topWidget(QWidget* widget); -QPixmap loadPixmap(const QString &fileName, const QSize &size = {}, Qt::AspectRatioMode aspectRatioMode = Qt::KeepAspectRatio); -QPixmap bootstrapPixmap(const QString &id); -bool hasLongitudinalControl(const cereal::CarParams::Reader &car_params); - -struct InterFont : public QFont { - InterFont(int pixel_size, QFont::Weight weight = QFont::Normal) : QFont("Inter") { - setPixelSize(pixel_size); - setWeight(weight); - } -}; - -class ParamWatcher : public QObject { - Q_OBJECT - -public: - ParamWatcher(QObject *parent); - void addParam(const QString ¶m_name); - -signals: - void paramChanged(const QString ¶m_name, const QString ¶m_value); - -private: - void fileChanged(const QString &path); - - QFileSystemWatcher *watcher; - QHash params_hash; - Params params; -}; diff --git a/selfdrive/ui/qt/widgets/cameraview.cc b/selfdrive/ui/qt/widgets/cameraview.cc deleted file mode 100644 index 81ef613393..0000000000 --- a/selfdrive/ui/qt/widgets/cameraview.cc +++ /dev/null @@ -1,365 +0,0 @@ -#include "selfdrive/ui/qt/widgets/cameraview.h" - -#ifdef __APPLE__ -#include -#else -#include -#endif - -#include -#include - -namespace { - -const char frame_vertex_shader[] = -#ifdef __APPLE__ - "#version 330 core\n" -#else - "#version 300 es\n" -#endif - "layout(location = 0) in vec4 aPosition;\n" - "layout(location = 1) in vec2 aTexCoord;\n" - "uniform mat4 uTransform;\n" - "out vec2 vTexCoord;\n" - "void main() {\n" - " gl_Position = uTransform * aPosition;\n" - " vTexCoord = aTexCoord;\n" - "}\n"; - -const char frame_fragment_shader[] = -#ifdef QCOM2 - "#version 300 es\n" - "#extension GL_OES_EGL_image_external_essl3 : enable\n" - "precision mediump float;\n" - "uniform samplerExternalOES uTexture;\n" - "in vec2 vTexCoord;\n" - "out vec4 colorOut;\n" - "void main() {\n" - " colorOut = texture(uTexture, vTexCoord);\n" - // gamma to improve worst case visibility when dark - " colorOut.rgb = pow(colorOut.rgb, vec3(1.0/1.28));\n" - "}\n"; -#else -#ifdef __APPLE__ - "#version 330 core\n" -#else - "#version 300 es\n" - "precision mediump float;\n" -#endif - "uniform sampler2D uTextureY;\n" - "uniform sampler2D uTextureUV;\n" - "in vec2 vTexCoord;\n" - "out vec4 colorOut;\n" - "void main() {\n" - " float y = texture(uTextureY, vTexCoord).r;\n" - " vec2 uv = texture(uTextureUV, vTexCoord).rg - 0.5;\n" - " float r = y + 1.402 * uv.y;\n" - " float g = y - 0.344 * uv.x - 0.714 * uv.y;\n" - " float b = y + 1.772 * uv.x;\n" - " colorOut = vec4(r, g, b, 1.0);\n" - "}\n"; -#endif - -} // namespace - -CameraWidget::CameraWidget(std::string stream_name, VisionStreamType type, QWidget* parent) : - stream_name(stream_name), active_stream_type(type), requested_stream_type(type), QOpenGLWidget(parent) { - setAttribute(Qt::WA_OpaquePaintEvent); - qRegisterMetaType>("availableStreams"); - QObject::connect(this, &CameraWidget::vipcThreadConnected, this, &CameraWidget::vipcConnected, Qt::BlockingQueuedConnection); - QObject::connect(this, &CameraWidget::vipcThreadFrameReceived, this, &CameraWidget::vipcFrameReceived, Qt::QueuedConnection); - QObject::connect(this, &CameraWidget::vipcAvailableStreamsUpdated, this, &CameraWidget::availableStreamsUpdated, Qt::QueuedConnection); - QObject::connect(QApplication::instance(), &QCoreApplication::aboutToQuit, this, &CameraWidget::stopVipcThread); -} - -CameraWidget::~CameraWidget() { - makeCurrent(); - stopVipcThread(); - if (isValid()) { - glDeleteVertexArrays(1, &frame_vao); - glDeleteBuffers(1, &frame_vbo); - glDeleteBuffers(1, &frame_ibo); -#ifndef QCOM2 - glDeleteTextures(2, textures); -#endif - } - doneCurrent(); -} - -// Qt uses device-independent pixels, depending on platform this may be -// different to what OpenGL uses -int CameraWidget::glWidth() { - return width() * devicePixelRatio(); -} - -int CameraWidget::glHeight() { - return height() * devicePixelRatio(); -} - -void CameraWidget::initializeGL() { - initializeOpenGLFunctions(); - - program = std::make_unique(context()); - bool ret = program->addShaderFromSourceCode(QOpenGLShader::Vertex, frame_vertex_shader); - assert(ret); - ret = program->addShaderFromSourceCode(QOpenGLShader::Fragment, frame_fragment_shader); - assert(ret); - - program->link(); - GLint frame_pos_loc = program->attributeLocation("aPosition"); - GLint frame_texcoord_loc = program->attributeLocation("aTexCoord"); - - auto [x1, x2, y1, y2] = requested_stream_type == VISION_STREAM_DRIVER ? std::tuple(0.f, 1.f, 1.f, 0.f) : std::tuple(1.f, 0.f, 1.f, 0.f); - const uint8_t frame_indicies[] = {0, 1, 2, 0, 2, 3}; - const float frame_coords[4][4] = { - {-1.0, -1.0, x2, y1}, // bl - {-1.0, 1.0, x2, y2}, // tl - { 1.0, 1.0, x1, y2}, // tr - { 1.0, -1.0, x1, y1}, // br - }; - - glGenVertexArrays(1, &frame_vao); - glBindVertexArray(frame_vao); - glGenBuffers(1, &frame_vbo); - glBindBuffer(GL_ARRAY_BUFFER, frame_vbo); - glBufferData(GL_ARRAY_BUFFER, sizeof(frame_coords), frame_coords, GL_STATIC_DRAW); - glEnableVertexAttribArray(frame_pos_loc); - glVertexAttribPointer(frame_pos_loc, 2, GL_FLOAT, GL_FALSE, - sizeof(frame_coords[0]), (const void *)0); - glEnableVertexAttribArray(frame_texcoord_loc); - glVertexAttribPointer(frame_texcoord_loc, 2, GL_FLOAT, GL_FALSE, - sizeof(frame_coords[0]), (const void *)(sizeof(float) * 2)); - glGenBuffers(1, &frame_ibo); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, frame_ibo); - glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(frame_indicies), frame_indicies, GL_STATIC_DRAW); - glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindVertexArray(0); - - glUseProgram(program->programId()); - -#ifdef QCOM2 - glUniform1i(program->uniformLocation("uTexture"), 0); -#else - glGenTextures(2, textures); - glUniform1i(program->uniformLocation("uTextureY"), 0); - glUniform1i(program->uniformLocation("uTextureUV"), 1); -#endif -} - -void CameraWidget::showEvent(QShowEvent *event) { - if (!vipc_thread) { - clearFrames(); - vipc_thread = new QThread(); - connect(vipc_thread, &QThread::started, [=]() { vipcThread(); }); - connect(vipc_thread, &QThread::finished, vipc_thread, &QObject::deleteLater); - vipc_thread->start(); - } -} - -void CameraWidget::stopVipcThread() { - makeCurrent(); - if (vipc_thread) { - vipc_thread->requestInterruption(); - vipc_thread->quit(); - vipc_thread->wait(); - vipc_thread = nullptr; - } - -#ifdef QCOM2 - EGLDisplay egl_display = eglGetCurrentDisplay(); - assert(egl_display != EGL_NO_DISPLAY); - for (auto &pair : egl_images) { - eglDestroyImageKHR(egl_display, pair.second); - assert(eglGetError() == EGL_SUCCESS); - } - egl_images.clear(); -#endif -} - -void CameraWidget::availableStreamsUpdated(std::set streams) { - available_streams = streams; -} - -mat4 CameraWidget::calcFrameMatrix() { - // Scale the frame to fit the widget while maintaining the aspect ratio. - float widget_aspect_ratio = (float)width() / height(); - float frame_aspect_ratio = (float)stream_width / stream_height; - float zx = std::min(frame_aspect_ratio / widget_aspect_ratio, 1.0f); - float zy = std::min(widget_aspect_ratio / frame_aspect_ratio, 1.0f); - - return mat4{{ - zx, 0.0, 0.0, 0.0, - 0.0, zy, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0, - }}; -} - -void CameraWidget::paintGL() { - glClearColor(bg.redF(), bg.greenF(), bg.blueF(), bg.alphaF()); - glClear(GL_STENCIL_BUFFER_BIT | GL_COLOR_BUFFER_BIT); - - std::lock_guard lk(frame_lock); - if (frames.empty()) return; - - int frame_idx = frames.size() - 1; - - // Always draw latest frame until sync logic is more stable - // for (frame_idx = 0; frame_idx < frames.size() - 1; frame_idx++) { - // if (frames[frame_idx].first == draw_frame_id) break; - // } - - // Log duplicate/dropped frames - if (frames[frame_idx].first == prev_frame_id) { - qDebug() << "Drawing same frame twice" << frames[frame_idx].first; - } else if (frames[frame_idx].first != prev_frame_id + 1) { - qDebug() << "Skipped frame" << frames[frame_idx].first; - } - prev_frame_id = frames[frame_idx].first; - VisionBuf *frame = frames[frame_idx].second; - assert(frame != nullptr); - - auto frame_mat = calcFrameMatrix(); - - glViewport(0, 0, glWidth(), glHeight()); - glBindVertexArray(frame_vao); - glUseProgram(program->programId()); - glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - -#ifdef QCOM2 - // no frame copy - glActiveTexture(GL_TEXTURE0); - glEGLImageTargetTexture2DOES(GL_TEXTURE_EXTERNAL_OES, egl_images[frame->idx]); - assert(glGetError() == GL_NO_ERROR); -#else - // fallback to copy - glPixelStorei(GL_UNPACK_ROW_LENGTH, stream_stride); - glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_2D, textures[0]); - glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, stream_width, stream_height, GL_RED, GL_UNSIGNED_BYTE, frame->y); - assert(glGetError() == GL_NO_ERROR); - - glPixelStorei(GL_UNPACK_ROW_LENGTH, stream_stride/2); - glActiveTexture(GL_TEXTURE0 + 1); - glBindTexture(GL_TEXTURE_2D, textures[1]); - glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, stream_width/2, stream_height/2, GL_RG, GL_UNSIGNED_BYTE, frame->uv); - assert(glGetError() == GL_NO_ERROR); -#endif - - glUniformMatrix4fv(program->uniformLocation("uTransform"), 1, GL_TRUE, frame_mat.v); - glEnableVertexAttribArray(0); - glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, (const void *)0); - glDisableVertexAttribArray(0); - glBindVertexArray(0); - glBindTexture(GL_TEXTURE_2D, 0); - glActiveTexture(GL_TEXTURE0); - glPixelStorei(GL_UNPACK_ALIGNMENT, 4); - glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); -} - -void CameraWidget::vipcConnected(VisionIpcClient *vipc_client) { - makeCurrent(); - stream_width = vipc_client->buffers[0].width; - stream_height = vipc_client->buffers[0].height; - stream_stride = vipc_client->buffers[0].stride; - -#ifdef QCOM2 - EGLDisplay egl_display = eglGetCurrentDisplay(); - assert(egl_display != EGL_NO_DISPLAY); - for (auto &pair : egl_images) { - eglDestroyImageKHR(egl_display, pair.second); - } - egl_images.clear(); - - for (int i = 0; i < vipc_client->num_buffers; i++) { // import buffers into OpenGL - int fd = dup(vipc_client->buffers[i].fd); // eglDestroyImageKHR will close, so duplicate - EGLint img_attrs[] = { - EGL_WIDTH, (int)vipc_client->buffers[i].width, - EGL_HEIGHT, (int)vipc_client->buffers[i].height, - EGL_LINUX_DRM_FOURCC_EXT, DRM_FORMAT_NV12, - EGL_DMA_BUF_PLANE0_FD_EXT, fd, - EGL_DMA_BUF_PLANE0_OFFSET_EXT, 0, - EGL_DMA_BUF_PLANE0_PITCH_EXT, (int)vipc_client->buffers[i].stride, - EGL_DMA_BUF_PLANE1_FD_EXT, fd, - EGL_DMA_BUF_PLANE1_OFFSET_EXT, (int)vipc_client->buffers[i].uv_offset, - EGL_DMA_BUF_PLANE1_PITCH_EXT, (int)vipc_client->buffers[i].stride, - EGL_NONE - }; - egl_images[i] = eglCreateImageKHR(egl_display, EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, 0, img_attrs); - assert(eglGetError() == EGL_SUCCESS); - } -#else - glBindTexture(GL_TEXTURE_2D, textures[0]); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, stream_width, stream_height, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr); - assert(glGetError() == GL_NO_ERROR); - - glBindTexture(GL_TEXTURE_2D, textures[1]); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RG8, stream_width/2, stream_height/2, 0, GL_RG, GL_UNSIGNED_BYTE, nullptr); - assert(glGetError() == GL_NO_ERROR); -#endif -} - -void CameraWidget::vipcFrameReceived() { - update(); -} - -void CameraWidget::vipcThread() { - VisionStreamType cur_stream = requested_stream_type; - std::unique_ptr vipc_client; - VisionIpcBufExtra meta_main = {0}; - - while (!QThread::currentThread()->isInterruptionRequested()) { - if (!vipc_client || cur_stream != requested_stream_type) { - clearFrames(); - qDebug().nospace() << "connecting to stream " << requested_stream_type << ", was connected to " << cur_stream; - cur_stream = requested_stream_type; - vipc_client.reset(new VisionIpcClient(stream_name, cur_stream, false)); - } - active_stream_type = cur_stream; - - if (!vipc_client->connected) { - clearFrames(); - auto streams = VisionIpcClient::getAvailableStreams(stream_name, false); - if (streams.empty()) { - QThread::msleep(100); - continue; - } - emit vipcAvailableStreamsUpdated(streams); - - if (!vipc_client->connect(false)) { - QThread::msleep(100); - continue; - } - emit vipcThreadConnected(vipc_client.get()); - } - - if (VisionBuf *buf = vipc_client->recv(&meta_main, 1000)) { - { - std::lock_guard lk(frame_lock); - frames.push_back(std::make_pair(meta_main.frame_id, buf)); - while (frames.size() > FRAME_BUFFER_SIZE) { - frames.pop_front(); - } - } - emit vipcThreadFrameReceived(); - } else { - if (!isVisible()) { - vipc_client->connected = false; - } - } - } -} - -void CameraWidget::clearFrames() { - std::lock_guard lk(frame_lock); - frames.clear(); - available_streams.clear(); -} diff --git a/selfdrive/ui/qt/widgets/cameraview.h b/selfdrive/ui/qt/widgets/cameraview.h deleted file mode 100644 index e446ef5987..0000000000 --- a/selfdrive/ui/qt/widgets/cameraview.h +++ /dev/null @@ -1,94 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#ifdef QCOM2 -#define EGL_EGLEXT_PROTOTYPES -#define EGL_NO_X11 -#define GL_TEXTURE_EXTERNAL_OES 0x8D65 -#include -#include -#include -#endif - -#include "msgq/visionipc/visionipc_client.h" - -#ifdef SUNNYPILOT -#include "selfdrive/ui/sunnypilot/ui.h" -#else -#include "selfdrive/ui/ui.h" -#endif - -const int FRAME_BUFFER_SIZE = 5; - -class CameraWidget : public QOpenGLWidget, protected QOpenGLFunctions { - Q_OBJECT - -public: - using QOpenGLWidget::QOpenGLWidget; - explicit CameraWidget(std::string stream_name, VisionStreamType stream_type, QWidget* parent = nullptr); - ~CameraWidget(); - void setBackgroundColor(const QColor &color) { bg = color; } - void setFrameId(int frame_id) { draw_frame_id = frame_id; } - void setStreamType(VisionStreamType type) { requested_stream_type = type; } - VisionStreamType getStreamType() { return active_stream_type; } - void stopVipcThread(); - -signals: - void clicked(); - void vipcThreadConnected(VisionIpcClient *); - void vipcThreadFrameReceived(); - void vipcAvailableStreamsUpdated(std::set); - -protected: - void paintGL() override; - void initializeGL() override; - void showEvent(QShowEvent *event) override; - void mouseReleaseEvent(QMouseEvent *event) override { emit clicked(); } - virtual mat4 calcFrameMatrix(); - void vipcThread(); - void clearFrames(); - - int glWidth(); - int glHeight(); - - GLuint frame_vao, frame_vbo, frame_ibo; - GLuint textures[2]; - std::unique_ptr program; - QColor bg = QColor("#000000"); - -#ifdef QCOM2 - std::map egl_images; -#endif - - std::string stream_name; - int stream_width = 0; - int stream_height = 0; - int stream_stride = 0; - std::atomic active_stream_type; - std::atomic requested_stream_type; - std::set available_streams; - QThread *vipc_thread = nullptr; - std::recursive_mutex frame_lock; - std::deque> frames; - uint32_t draw_frame_id = 0; - uint32_t prev_frame_id = 0; - -protected slots: - void vipcConnected(VisionIpcClient *vipc_client); - void vipcFrameReceived(); - void availableStreamsUpdated(std::set streams); -}; - -Q_DECLARE_METATYPE(std::set); diff --git a/selfdrive/ui/qt/widgets/controls.cc b/selfdrive/ui/qt/widgets/controls.cc deleted file mode 100644 index df6e6932c7..0000000000 --- a/selfdrive/ui/qt/widgets/controls.cc +++ /dev/null @@ -1,145 +0,0 @@ -#include "selfdrive/ui/qt/widgets/controls.h" - -#include -#include - -#include "selfdrive/ui/qt/util.h" - -AbstractControl::AbstractControl(const QString &title, const QString &desc, const QString &icon, QWidget *parent) : QFrame(parent) { -#ifndef SUNNYPILOT - QVBoxLayout *main_layout = new QVBoxLayout(this); - main_layout->setMargin(0); - - hlayout = new QHBoxLayout; - hlayout->setMargin(0); - hlayout->setSpacing(20); - - // left icon - icon_label = new QLabel(this); - hlayout->addWidget(icon_label); - if (!icon.isEmpty()) { - icon_pixmap = QPixmap(icon).scaledToWidth(80, Qt::SmoothTransformation); - icon_label->setPixmap(icon_pixmap); - icon_label->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); - } - icon_label->setVisible(!icon.isEmpty()); - - // title - title_label = new QPushButton(title); - title_label->setFixedHeight(120); - title_label->setStyleSheet("font-size: 50px; font-weight: 400; text-align: left; border: none;"); - hlayout->addWidget(title_label, 1); - - // value next to control button - value = new ElidedLabel(); - value->setAlignment(Qt::AlignRight | Qt::AlignVCenter); - value->setStyleSheet("color: #aaaaaa"); - hlayout->addWidget(value); - - main_layout->addLayout(hlayout); - - // description - description = new QLabel(desc); - description->setContentsMargins(40, 20, 40, 20); - description->setStyleSheet("font-size: 40px; color: grey"); - description->setWordWrap(true); - description->setVisible(false); - main_layout->addWidget(description); - - connect(title_label, &QPushButton::clicked, [=]() { - if (!description->isVisible()) { - emit showDescriptionEvent(); - } - - if (!description->text().isEmpty()) { - description->setVisible(!description->isVisible()); - } - }); - - main_layout->addStretch(); -#endif -} - -void AbstractControl::hideEvent(QHideEvent *e) { - if (description != nullptr) { - description->hide(); - } -} - -// controls - -ButtonControl::ButtonControl(const QString &title, const QString &text, const QString &desc, QWidget *parent) : AbstractControl(title, desc, "", parent) { - btn.setText(text); - btn.setStyleSheet(R"( - QPushButton { - padding: 0; - border-radius: 50px; - font-size: 35px; - font-weight: 500; - color: #E4E4E4; - background-color: #393939; - } - QPushButton:pressed { - background-color: #4a4a4a; - } - QPushButton:disabled { - color: #33E4E4E4; - } - )"); - btn.setFixedSize(250, 100); - QObject::connect(&btn, &QPushButton::clicked, this, &ButtonControl::clicked); - hlayout->addWidget(&btn); -} - -// ElidedLabel - -ElidedLabel::ElidedLabel(QWidget *parent) : ElidedLabel({}, parent) {} - -ElidedLabel::ElidedLabel(const QString &text, QWidget *parent) : QLabel(text.trimmed(), parent) { - setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); - setMinimumWidth(1); -} - -void ElidedLabel::resizeEvent(QResizeEvent* event) { - QLabel::resizeEvent(event); - lastText_ = elidedText_ = ""; -} - -void ElidedLabel::paintEvent(QPaintEvent *event) { - const QString curText = text(); - if (curText != lastText_) { - elidedText_ = fontMetrics().elidedText(curText, Qt::ElideRight, contentsRect().width()); - lastText_ = curText; - } - - QPainter painter(this); - drawFrame(&painter); - QStyleOption opt; - opt.initFrom(this); - style()->drawItemText(&painter, contentsRect(), alignment(), opt.palette, isEnabled(), elidedText_, foregroundRole()); -} - -// ParamControl - -ParamControl::ParamControl(const QString ¶m, const QString &title, const QString &desc, const QString &icon, QWidget *parent) - : ToggleControl(title, desc, icon, false, parent) { - key = param.toStdString(); - QObject::connect(this, &ParamControl::toggleFlipped, this, &ParamControl::toggleClicked); -} - -void ParamControl::toggleClicked(bool state) { - auto do_confirm = [this]() { - QString content("

" + title_label->text() + "


" - "

" + getDescription() + "

"); - return ConfirmationDialog(content, tr("Enable"), tr("Cancel"), true, this).exec(); - }; - - bool confirmed = store_confirm && params.getBool(key + "Confirmed"); - if (!confirm || confirmed || !state || do_confirm()) { - if (store_confirm && state) params.putBool(key + "Confirmed", true); - params.putBool(key, state); - setIcon(state); - } else { - toggle.togglePosition(); - } -} diff --git a/selfdrive/ui/qt/widgets/controls.h b/selfdrive/ui/qt/widgets/controls.h deleted file mode 100644 index bf56ab185d..0000000000 --- a/selfdrive/ui/qt/widgets/controls.h +++ /dev/null @@ -1,319 +0,0 @@ -#pragma once - -#include -#include - -#include -#include -#include -#include -#include -#include - -#include "common/params.h" -#include "selfdrive/ui/qt/widgets/input.h" -#include "selfdrive/ui/qt/widgets/toggle.h" - -class ElidedLabel : public QLabel { - Q_OBJECT - -public: - explicit ElidedLabel(QWidget *parent = 0); - explicit ElidedLabel(const QString &text, QWidget *parent = 0); - -signals: - void clicked(); - -protected: - void paintEvent(QPaintEvent *event) override; - void resizeEvent(QResizeEvent* event) override; - void mouseReleaseEvent(QMouseEvent *event) override { - if (rect().contains(event->pos())) { - emit clicked(); - } - } - QString lastText_, elidedText_; -}; - - -class AbstractControl : public QFrame { - Q_OBJECT - -public: - virtual void setDescription(const QString &desc) { - if (description) description->setText(desc); - } - - void setTitle(const QString &title) { - title_label->setText(title); - } - - void setValue(const QString &val) { - value->setText(val); - } - - virtual const QString getDescription() { - return description->text(); - } - - QLabel *icon_label; - QPixmap icon_pixmap; - -public slots: - virtual void showDescription() { - description->setVisible(true); - } - -signals: - void showDescriptionEvent(); - -protected: - AbstractControl(const QString &title, const QString &desc = "", const QString &icon = "", QWidget *parent = nullptr); - void hideEvent(QHideEvent *e) override; - - QHBoxLayout *hlayout; - QPushButton *title_label; - -private: - ElidedLabel *value; - QLabel *description = nullptr; -}; - -// widget to display a value -class LabelControl : public AbstractControl { - Q_OBJECT - -public: - LabelControl(const QString &title, const QString &text = "", const QString &desc = "", QWidget *parent = nullptr) : AbstractControl(title, desc, "", parent) { - label.setText(text); - label.setAlignment(Qt::AlignRight | Qt::AlignVCenter); - hlayout->addWidget(&label); - } - void setText(const QString &text) { label.setText(text); } - -private: - ElidedLabel label; -}; - -// widget for a button with a label -class ButtonControl : public AbstractControl { - Q_OBJECT - -public: - ButtonControl(const QString &title, const QString &text, const QString &desc = "", QWidget *parent = nullptr); - inline void setText(const QString &text) { btn.setText(text); } - inline QString text() const { return btn.text(); } - -signals: - void clicked(); - -public slots: - void setEnabled(bool enabled) { btn.setEnabled(enabled); } - -private: - QPushButton btn; -}; - -class ToggleControl : public AbstractControl { - Q_OBJECT - -public: - ToggleControl(const QString &title, const QString &desc = "", const QString &icon = "", const bool state = false, QWidget *parent = nullptr) : AbstractControl(title, desc, icon, parent) { - toggle.setFixedSize(150, 100); - if (state) { - toggle.togglePosition(); - } - hlayout->addWidget(&toggle); - QObject::connect(&toggle, &Toggle::stateChanged, this, &ToggleControl::toggleFlipped); - } - - void setEnabled(bool enabled) { - toggle.setEnabled(enabled); - toggle.update(); - } - -signals: - void toggleFlipped(bool state); - -protected: - Toggle toggle; -}; - -// widget to toggle params -class ParamControl : public ToggleControl { - Q_OBJECT - -public: - ParamControl(const QString ¶m, const QString &title, const QString &desc, const QString &icon, QWidget *parent = nullptr); - void setConfirmation(bool _confirm, bool _store_confirm) { - confirm = _confirm; - store_confirm = _store_confirm; - } - - void setActiveIcon(const QString &icon) { - active_icon_pixmap = QPixmap(icon).scaledToWidth(80, Qt::SmoothTransformation); - } - - void refresh() { - bool state = params.getBool(key); - if (state != toggle.on) { - toggle.togglePosition(); - setIcon(state); - } - } - - void showEvent(QShowEvent *event) override { - refresh(); - } - -private: - void toggleClicked(bool state); - void setIcon(bool state) { - if (state && !active_icon_pixmap.isNull()) { - icon_label->setPixmap(active_icon_pixmap); - } else if (!icon_pixmap.isNull()) { - icon_label->setPixmap(icon_pixmap); - } - } - - std::string key; - Params params; - QPixmap active_icon_pixmap; - bool confirm = false; - bool store_confirm = false; -}; - -class MultiButtonControl : public AbstractControl { - Q_OBJECT -public: - MultiButtonControl(const QString &title, const QString &desc, const QString &icon, - const std::vector &button_texts, const int minimum_button_width = 225) : AbstractControl(title, desc, icon) { - const QString style = R"( - QPushButton { - border-radius: 50px; - font-size: 40px; - font-weight: 500; - height:100px; - padding: 0 25 0 25; - color: #E4E4E4; - background-color: #393939; - } - QPushButton:pressed { - background-color: #4a4a4a; - } - QPushButton:checked:enabled { - background-color: #33Ab4C; - } - QPushButton:checked:disabled { - background-color: #9933Ab4C; - } - QPushButton:disabled { - color: #33E4E4E4; - } - )"; - - button_group = new QButtonGroup(this); - button_group->setExclusive(true); - for (int i = 0; i < button_texts.size(); i++) { - QPushButton *button = new QPushButton(button_texts[i], this); - button->setCheckable(true); - button->setChecked(i == 0); - button->setStyleSheet(style); - button->setMinimumWidth(minimum_button_width); - hlayout->addWidget(button); - button_group->addButton(button, i); - } - - QObject::connect(button_group, QOverload::of(&QButtonGroup::buttonClicked), this, &MultiButtonControl::buttonClicked); - } - - void setEnabled(bool enable) { - for (auto btn : button_group->buttons()) { - btn->setEnabled(enable); - } - } - - void setCheckedButton(int id) { - button_group->button(id)->setChecked(true); - } - -signals: - void buttonClicked(int id); - -protected: - QButtonGroup *button_group; -}; - -class ButtonParamControl : public MultiButtonControl { - Q_OBJECT -public: - ButtonParamControl(const QString ¶m, const QString &title, const QString &desc, const QString &icon, - const std::vector &button_texts, const int minimum_button_width = 225) : MultiButtonControl(title, desc, icon, - button_texts, minimum_button_width) { - key = param.toStdString(); - int value = atoi(params.get(key).c_str()); - - if (value > 0 && value < button_group->buttons().size()) { - button_group->button(value)->setChecked(true); - } - - QObject::connect(this, QOverload::of(&MultiButtonControl::buttonClicked), [=](int id) { - params.put(key, std::to_string(id)); - }); - } - - void refresh() { - int value = atoi(params.get(key).c_str()); - button_group->button(value)->setChecked(true); - } - - void showEvent(QShowEvent *event) override { - refresh(); - } - -private: - std::string key; - Params params; -}; - -class ListWidget : public QWidget { - Q_OBJECT - public: - explicit ListWidget(QWidget *parent = 0) : QWidget(parent), outer_layout(this) { - outer_layout.setMargin(0); - outer_layout.setSpacing(0); - outer_layout.addLayout(&inner_layout); - inner_layout.setMargin(0); - inner_layout.setSpacing(25); // default spacing is 25 - outer_layout.addStretch(1); - } - inline void addItem(QWidget *w) { inner_layout.addWidget(w); } - inline void addItem(QLayout *layout) { inner_layout.addLayout(layout); } - inline void setSpacing(int spacing) { inner_layout.setSpacing(spacing); } - -private: - void paintEvent(QPaintEvent *) override { - QPainter p(this); - p.setPen(Qt::gray); - for (int i = 0; i < inner_layout.count() - 1; ++i) { - QWidget *widget = inner_layout.itemAt(i)->widget(); - if (widget == nullptr || widget->isVisible()) { - QRect r = inner_layout.itemAt(i)->geometry(); - int bottom = r.bottom() + inner_layout.spacing() / 2; - p.drawLine(r.left() + 40, bottom, r.right() - 40, bottom); - } - } - } - QVBoxLayout outer_layout; - QVBoxLayout inner_layout; -}; - -// convenience class for wrapping layouts -class LayoutWidget : public QWidget { - Q_OBJECT - -public: - LayoutWidget(QLayout *l, QWidget *parent = nullptr) : QWidget(parent) { - setLayout(l); - } -}; diff --git a/selfdrive/ui/qt/widgets/input.cc b/selfdrive/ui/qt/widgets/input.cc deleted file mode 100644 index 0cbf14931b..0000000000 --- a/selfdrive/ui/qt/widgets/input.cc +++ /dev/null @@ -1,336 +0,0 @@ -#include "selfdrive/ui/qt/widgets/input.h" - -#include -#include - -#include "system/hardware/hw.h" -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/qt/qt_window.h" -#include "selfdrive/ui/qt/widgets/scrollview.h" - - -DialogBase::DialogBase(QWidget *parent) : QDialog(parent) { - Q_ASSERT(parent != nullptr); - parent->installEventFilter(this); - - setStyleSheet(R"( - * { - outline: none; - color: white; - font-family: Inter; - } - DialogBase { - background-color: black; - } - QPushButton { - height: 160; - font-size: 55px; - font-weight: 400; - border-radius: 10px; - color: white; - background-color: #333333; - } - QPushButton:pressed { - background-color: #444444; - } - )"); -} - -bool DialogBase::eventFilter(QObject *o, QEvent *e) { - if (o == parent() && e->type() == QEvent::Hide) { - reject(); - } - return QDialog::eventFilter(o, e); -} - -int DialogBase::exec() { - setMainWindow(this); - return QDialog::exec(); -} - -InputDialog::InputDialog(const QString &title, QWidget *parent, const QString &subtitle, bool secret) : DialogBase(parent) { - main_layout = new QVBoxLayout(this); - main_layout->setContentsMargins(50, 55, 50, 50); - main_layout->setSpacing(0); - - // build header - QHBoxLayout *header_layout = new QHBoxLayout(); - - QVBoxLayout *vlayout = new QVBoxLayout; - header_layout->addLayout(vlayout); - label = new QLabel(title, this); - label->setStyleSheet("font-size: 90px; font-weight: bold;"); - vlayout->addWidget(label, 1, Qt::AlignTop | Qt::AlignLeft); - - if (!subtitle.isEmpty()) { - sublabel = new QLabel(subtitle, this); - sublabel->setStyleSheet("font-size: 55px; font-weight: light; color: #BDBDBD;"); - vlayout->addWidget(sublabel, 1, Qt::AlignTop | Qt::AlignLeft); - } - - QPushButton* cancel_btn = new QPushButton(tr("Cancel")); - cancel_btn->setFixedSize(386, 125); - cancel_btn->setStyleSheet(R"( - QPushButton { - font-size: 48px; - border-radius: 10px; - color: #E4E4E4; - background-color: #333333; - } - QPushButton:pressed { - background-color: #444444; - } - )"); - header_layout->addWidget(cancel_btn, 0, Qt::AlignRight); - QObject::connect(cancel_btn, &QPushButton::clicked, this, &InputDialog::reject); - QObject::connect(cancel_btn, &QPushButton::clicked, this, &InputDialog::cancel); - - main_layout->addLayout(header_layout); - - // text box - main_layout->addStretch(2); - - QWidget *textbox_widget = new QWidget; - textbox_widget->setObjectName("textbox"); - QHBoxLayout *textbox_layout = new QHBoxLayout(textbox_widget); - textbox_layout->setContentsMargins(50, 0, 50, 0); - - textbox_widget->setStyleSheet(R"( - #textbox { - margin-left: 50px; - margin-right: 50px; - border-radius: 0; - border-bottom: 3px solid #BDBDBD; - } - * { - border: none; - font-size: 80px; - font-weight: light; - background-color: transparent; - } - )"); - - line = new QLineEdit(); - line->setStyleSheet("lineedit-password-character: 8226; lineedit-password-mask-delay: 1500;"); - textbox_layout->addWidget(line, 1); - - if (secret) { - eye_btn = new QPushButton(); - eye_btn->setCheckable(true); - eye_btn->setFixedSize(150, 120); - QObject::connect(eye_btn, &QPushButton::toggled, [=](bool checked) { - if (checked) { - eye_btn->setIcon(QIcon(ASSET_PATH + "icons/eye_closed.svg")); - eye_btn->setIconSize(QSize(81, 54)); - line->setEchoMode(QLineEdit::Password); - } else { - eye_btn->setIcon(QIcon(ASSET_PATH + "icons/eye_open.svg")); - eye_btn->setIconSize(QSize(81, 44)); - line->setEchoMode(QLineEdit::Normal); - } - }); - eye_btn->toggle(); - eye_btn->setChecked(false); - textbox_layout->addWidget(eye_btn); - } - - main_layout->addWidget(textbox_widget, 0, Qt::AlignBottom); - main_layout->addSpacing(25); - - k = new Keyboard(this); - QObject::connect(k, &Keyboard::emitEnter, this, &InputDialog::handleEnter); - QObject::connect(k, &Keyboard::emitBackspace, this, [=]() { - line->backspace(); - }); - QObject::connect(k, &Keyboard::emitKey, this, [=](const QString &key) { - line->insert(key.left(1)); - }); - - main_layout->addWidget(k, 2, Qt::AlignBottom); -} - -QString InputDialog::getText(const QString &prompt, QWidget *parent, const QString &subtitle, - bool secret, int minLength, const QString &defaultText) { - InputDialog d(prompt, parent, subtitle, secret); - d.line->setText(defaultText); - d.setMinLength(minLength); - const int ret = d.exec(); - return ret ? d.text() : QString(); -} - -QString InputDialog::text() { - return line->text(); -} - -void InputDialog::show() { - setMainWindow(this); -} - -void InputDialog::handleEnter() { - if (line->text().length() >= minLength) { - done(QDialog::Accepted); - emitText(line->text()); - } else { - setMessage(tr("Need at least %n character(s)!", "", minLength), false); - } -} - -void InputDialog::setMessage(const QString &message, bool clearInputField) { - label->setText(message); - if (clearInputField) { - line->setText(""); - } -} - -void InputDialog::setMinLength(int length) { - minLength = length; -} - -// ConfirmationDialog - -ConfirmationDialog::ConfirmationDialog(const QString &prompt_text, const QString &confirm_text, const QString &cancel_text, - const bool rich, QWidget *parent) : DialogBase(parent) { - QFrame *container = new QFrame(this); - container->setStyleSheet(R"( - QFrame { background-color: #1B1B1B; color: #C9C9C9; } - #confirm_btn { background-color: #465BEA; } - #confirm_btn:pressed { background-color: #3049F4; } - )"); - QVBoxLayout *main_layout = new QVBoxLayout(container); - main_layout->setContentsMargins(32, rich ? 32 : 120, 32, 32); - - QLabel *prompt = new QLabel(prompt_text, this); - prompt->setWordWrap(true); - prompt->setAlignment(rich ? Qt::AlignLeft : Qt::AlignHCenter); - prompt->setStyleSheet((rich ? "font-size: 42px; font-weight: light;" : "font-size: 70px; font-weight: bold;") + QString(" margin: 45px;")); - main_layout->addWidget(rich ? (QWidget*)new ScrollView(prompt, this) : (QWidget*)prompt, 1, Qt::AlignTop); - - // cancel + confirm buttons - QHBoxLayout *btn_layout = new QHBoxLayout(); - btn_layout->setSpacing(30); - main_layout->addLayout(btn_layout); - - if (cancel_text.length()) { - QPushButton* cancel_btn = new QPushButton(cancel_text); - btn_layout->addWidget(cancel_btn); - QObject::connect(cancel_btn, &QPushButton::clicked, this, &ConfirmationDialog::reject); - } - - if (confirm_text.length()) { - QPushButton* confirm_btn = new QPushButton(confirm_text); - confirm_btn->setObjectName("confirm_btn"); - btn_layout->addWidget(confirm_btn); - QObject::connect(confirm_btn, &QPushButton::clicked, this, &ConfirmationDialog::accept); - } - - QVBoxLayout *outer_layout = new QVBoxLayout(this); - int margin = rich ? 100 : 200; - outer_layout->setContentsMargins(margin, margin, margin, margin); - outer_layout->addWidget(container); -} - -bool ConfirmationDialog::alert(const QString &prompt_text, QWidget *parent) { - ConfirmationDialog d(prompt_text, tr("Ok"), "", false, parent); - return d.exec(); -} - -bool ConfirmationDialog::confirm(const QString &prompt_text, const QString &confirm_text, QWidget *parent) { - ConfirmationDialog d(prompt_text, confirm_text, tr("Cancel"), false, parent); - return d.exec(); -} - -bool ConfirmationDialog::rich(const QString &prompt_text, QWidget *parent) { - ConfirmationDialog d(prompt_text, tr("Ok"), "", true, parent); - return d.exec(); -} - -// MultiOptionDialog - -MultiOptionDialog::MultiOptionDialog(const QString &prompt_text, const QStringList &l, const QString ¤t, QWidget *parent) : DialogBase(parent) { - QFrame *container = new QFrame(this); - container->setStyleSheet(R"( - QFrame { background-color: #1B1B1B; } - #confirm_btn[enabled="false"] { background-color: #2B2B2B; } - #confirm_btn:enabled { background-color: #465BEA; } - #confirm_btn:enabled:pressed { background-color: #3049F4; } - )"); - - QVBoxLayout *main_layout = new QVBoxLayout(container); - main_layout->setContentsMargins(55, 50, 55, 50); - - QLabel *title = new QLabel(prompt_text, this); - title->setStyleSheet("font-size: 70px; font-weight: 500;"); - main_layout->addWidget(title, 0, Qt::AlignLeft | Qt::AlignTop); - main_layout->addSpacing(25); - - QWidget *listWidget = new QWidget(this); - QVBoxLayout *listLayout = new QVBoxLayout(listWidget); - listLayout->setSpacing(20); - listWidget->setStyleSheet(R"( - QPushButton { - height: 135; - padding: 0px 50px; - text-align: left; - font-size: 55px; - font-weight: 300; - border-radius: 10px; - background-color: #4F4F4F; - } - QPushButton:checked { background-color: #465BEA; } - )"); - - QButtonGroup *group = new QButtonGroup(listWidget); - group->setExclusive(true); - - QPushButton *confirm_btn = new QPushButton(tr("Select")); - confirm_btn->setObjectName("confirm_btn"); - confirm_btn->setEnabled(false); - - for (const QString &s : l) { - QPushButton *selectionLabel = new QPushButton(s); - selectionLabel->setCheckable(true); - selectionLabel->setChecked(s == current); - QObject::connect(selectionLabel, &QPushButton::toggled, [=](bool checked) { - if (checked) selection = s; - if (selection != current) { - confirm_btn->setEnabled(true); - } else { - confirm_btn->setEnabled(false); - } - }); - - group->addButton(selectionLabel); - listLayout->addWidget(selectionLabel); - } - // add stretch to keep buttons spaced correctly - listLayout->addStretch(1); - - ScrollView *scroll_view = new ScrollView(listWidget, this); - scroll_view->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); - - main_layout->addWidget(scroll_view); - main_layout->addSpacing(35); - - // cancel + confirm buttons - QHBoxLayout *blayout = new QHBoxLayout; - main_layout->addLayout(blayout); - blayout->setSpacing(50); - - QPushButton *cancel_btn = new QPushButton(tr("Cancel")); - QObject::connect(cancel_btn, &QPushButton::clicked, this, &ConfirmationDialog::reject); - QObject::connect(confirm_btn, &QPushButton::clicked, this, &ConfirmationDialog::accept); - blayout->addWidget(cancel_btn); - blayout->addWidget(confirm_btn); - - QVBoxLayout *outer_layout = new QVBoxLayout(this); - outer_layout->setContentsMargins(50, 50, 50, 50); - outer_layout->addWidget(container); -} - -QString MultiOptionDialog::getSelection(const QString &prompt_text, const QStringList &l, const QString ¤t, QWidget *parent) { - MultiOptionDialog d(prompt_text, l, current, parent); - if (d.exec()) { - return d.selection; - } - return ""; -} diff --git a/selfdrive/ui/qt/widgets/input.h b/selfdrive/ui/qt/widgets/input.h deleted file mode 100644 index 089e54e4a0..0000000000 --- a/selfdrive/ui/qt/widgets/input.h +++ /dev/null @@ -1,71 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include - -#include "selfdrive/ui/qt/widgets/keyboard.h" - - -class DialogBase : public QDialog { - Q_OBJECT - -protected: - DialogBase(QWidget *parent); - bool eventFilter(QObject *o, QEvent *e) override; - -public slots: - int exec() override; -}; - -class InputDialog : public DialogBase { - Q_OBJECT - -public: - explicit InputDialog(const QString &title, QWidget *parent, const QString &subtitle = "", bool secret = false); - static QString getText(const QString &title, QWidget *parent, const QString &subtitle = "", - bool secret = false, int minLength = -1, const QString &defaultText = ""); - QString text(); - void setMessage(const QString &message, bool clearInputField = true); - void setMinLength(int length); - void show(); - -private: - int minLength; - QLineEdit *line; - Keyboard *k; - QLabel *label; - QLabel *sublabel; - QVBoxLayout *main_layout; - QPushButton *eye_btn; - -private slots: - void handleEnter(); - -signals: - void cancel(); - void emitText(const QString &text); -}; - -class ConfirmationDialog : public DialogBase { - Q_OBJECT - -public: - explicit ConfirmationDialog(const QString &prompt_text, const QString &confirm_text, - const QString &cancel_text, const bool rich, QWidget* parent); - static bool alert(const QString &prompt_text, QWidget *parent); - static bool confirm(const QString &prompt_text, const QString &confirm_text, QWidget *parent); - static bool rich(const QString &prompt_text, QWidget *parent); -}; - -class MultiOptionDialog : public DialogBase { - Q_OBJECT - -public: - explicit MultiOptionDialog(const QString &prompt_text, const QStringList &l, const QString ¤t, QWidget *parent); - static QString getSelection(const QString &prompt_text, const QStringList &l, const QString ¤t, QWidget *parent); - QString selection; -}; diff --git a/selfdrive/ui/qt/widgets/keyboard.cc b/selfdrive/ui/qt/widgets/keyboard.cc deleted file mode 100644 index 9ead27b8d5..0000000000 --- a/selfdrive/ui/qt/widgets/keyboard.cc +++ /dev/null @@ -1,182 +0,0 @@ -#include "selfdrive/ui/qt/widgets/keyboard.h" - -#include - -#include -#include -#include -#include -#include - -const QString BACKSPACE_KEY = "⌫"; -const QString ENTER_KEY = "→"; -const QString SHIFT_KEY = "⇧"; -const QString CAPS_LOCK_KEY = "⇪"; - -const QMap KEY_STRETCH = {{" ", 3}, {ENTER_KEY, 2}}; - -const QStringList CONTROL_BUTTONS = {SHIFT_KEY, CAPS_LOCK_KEY, "ABC", "#+=", "123", BACKSPACE_KEY, ENTER_KEY}; - -const float key_spacing_vertical = 20; -const float key_spacing_horizontal = 15; - -KeyButton::KeyButton(const QString &text, QWidget *parent) : QPushButton(text, parent) { - setAttribute(Qt::WA_AcceptTouchEvents); - setFocusPolicy(Qt::NoFocus); -} - -bool KeyButton::event(QEvent *event) { - if (event->type() == QEvent::TouchBegin || event->type() == QEvent::TouchEnd) { - QTouchEvent *touchEvent = static_cast(event); - if (!touchEvent->touchPoints().empty()) { - const QEvent::Type mouseType = event->type() == QEvent::TouchBegin ? QEvent::MouseButtonPress : QEvent::MouseButtonRelease; - QMouseEvent mouseEvent(mouseType, touchEvent->touchPoints().front().pos(), Qt::LeftButton, Qt::LeftButton, Qt::NoModifier); - QPushButton::event(&mouseEvent); - event->accept(); - parentWidget()->update(); - return true; - } - } - return QPushButton::event(event); -} - -KeyboardLayout::KeyboardLayout(QWidget* parent, const std::vector>& layout) : QWidget(parent) { - QVBoxLayout* main_layout = new QVBoxLayout(this); - main_layout->setMargin(0); - main_layout->setSpacing(0); - - QButtonGroup* btn_group = new QButtonGroup(this); - QObject::connect(btn_group, SIGNAL(buttonClicked(QAbstractButton*)), parent, SLOT(handleButton(QAbstractButton*))); - - for (const auto &s : layout) { - QHBoxLayout *hlayout = new QHBoxLayout; - hlayout->setSpacing(0); - - if (main_layout->count() == 1) { - hlayout->addSpacing(90); - } - - for (const QString &p : s) { - KeyButton* btn = new KeyButton(p); - if (p == BACKSPACE_KEY) { - btn->setAutoRepeat(true); - } else if (p == ENTER_KEY) { - btn->setStyleSheet(R"( - QPushButton { - background-color: #465BEA; - } - QPushButton:pressed { - background-color: #444444; - } - )"); - } - btn->setFixedHeight(135 + key_spacing_vertical); - btn_group->addButton(btn); - hlayout->addWidget(btn, KEY_STRETCH.value(p, 1)); - } - - if (main_layout->count() == 1) { - hlayout->addSpacing(90); - } - - main_layout->addLayout(hlayout); - } - - setStyleSheet(QString(R"( - QPushButton { - font-size: 75px; - margin-left: %1px; - margin-right: %1px; - margin-top: %2px; - margin-bottom: %2px; - padding: 0px; - border-radius: 10px; - color: #dddddd; - background-color: #444444; - } - QPushButton:pressed { - background-color: #333333; - } - )").arg(key_spacing_vertical / 2).arg(key_spacing_horizontal / 2)); -} - -Keyboard::Keyboard(QWidget *parent) : QFrame(parent) { - main_layout = new QStackedLayout(this); - main_layout->setMargin(0); - - // lowercase - std::vector> lowercase = { - {"q", "w", "e", "r", "t", "y", "u", "i", "o", "p"}, - {"a", "s", "d", "f", "g", "h", "j", "k", "l"}, - {SHIFT_KEY, "z", "x", "c", "v", "b", "n", "m", BACKSPACE_KEY}, - {"123", "/", "-", " ", ".", ENTER_KEY}, - }; - main_layout->addWidget(new KeyboardLayout(this, lowercase)); - - // uppercase - std::vector> uppercase = { - {"Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P"}, - {"A", "S", "D", "F", "G", "H", "J", "K", "L"}, - {SHIFT_KEY, "Z", "X", "C", "V", "B", "N", "M", BACKSPACE_KEY}, - {"123", "/", "-", " ", ".", ENTER_KEY}, - }; - main_layout->addWidget(new KeyboardLayout(this, uppercase)); - - // numbers + specials - std::vector> numbers = { - {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0"}, - {"-", "/", ":", ";", "(", ")", "$", "&&", "@", "\""}, - {"#+=", ".", ",", "?", "!", "`", BACKSPACE_KEY}, - {"ABC", " ", ".", ENTER_KEY}, - }; - main_layout->addWidget(new KeyboardLayout(this, numbers)); - - // extra specials - std::vector> specials = { - {"[", "]", "{", "}", "#", "%", "^", "*", "+", "="}, - {"_", "\\", "|", "~", "<", ">", "€", "£", "¥", "•"}, - {"123", ".", ",", "?", "!", "'", BACKSPACE_KEY}, - {"ABC", " ", ".", ENTER_KEY}, - }; - main_layout->addWidget(new KeyboardLayout(this, specials)); - - main_layout->setCurrentIndex(0); -} - -void Keyboard::handleCapsPress() { - shift_state = (shift_state + 1) % 3; - bool is_uppercase = shift_state > 0; - main_layout->setCurrentIndex(is_uppercase); - - for (KeyButton* btn : main_layout->currentWidget()->findChildren()) { - if (btn->text() == SHIFT_KEY || btn->text() == CAPS_LOCK_KEY) { - btn->setText(shift_state == 2 ? CAPS_LOCK_KEY : SHIFT_KEY); - btn->setStyleSheet(is_uppercase ? "background-color: #465BEA;" : ""); - } - } -} - -void Keyboard::handleButton(QAbstractButton* btn) { - const QString &key = btn->text(); - if (CONTROL_BUTTONS.contains(key)) { - if (key == "ABC" || key == "123" || key == "#+=") { - int index = (key == "ABC") ? 0 : (key == "123" ? 2 : 3); - main_layout->setCurrentIndex(index); - shift_state = 0; - } else if (key == SHIFT_KEY || key == CAPS_LOCK_KEY) { - handleCapsPress(); - } else if (key == ENTER_KEY) { - main_layout->setCurrentIndex(0); - shift_state = 0; - emit emitEnter(); - } else if (key == BACKSPACE_KEY) { - emit emitBackspace(); - } - } else { - if (shift_state == 1 && "A" <= key && key <= "Z") { - main_layout->setCurrentIndex(0); - shift_state = 0; - } - emit emitKey(key); - } -} diff --git a/selfdrive/ui/qt/widgets/keyboard.h b/selfdrive/ui/qt/widgets/keyboard.h deleted file mode 100644 index e61617283a..0000000000 --- a/selfdrive/ui/qt/widgets/keyboard.h +++ /dev/null @@ -1,42 +0,0 @@ -#pragma once - -#include - -#include -#include -#include - -class KeyButton : public QPushButton { - Q_OBJECT - -public: - KeyButton(const QString &text, QWidget *parent = 0); - bool event(QEvent *event) override; -}; - -class KeyboardLayout : public QWidget { - Q_OBJECT - -public: - explicit KeyboardLayout(QWidget* parent, const std::vector>& layout); -}; - -class Keyboard : public QFrame { - Q_OBJECT - -public: - explicit Keyboard(QWidget *parent = 0); - -private: - QStackedLayout* main_layout; - int shift_state = 0; - -private slots: - void handleButton(QAbstractButton* m_button); - void handleCapsPress(); - -signals: - void emitKey(const QString &s); - void emitBackspace(); - void emitEnter(); -}; diff --git a/selfdrive/ui/qt/widgets/offroad_alerts.cc b/selfdrive/ui/qt/widgets/offroad_alerts.cc deleted file mode 100644 index f630875978..0000000000 --- a/selfdrive/ui/qt/widgets/offroad_alerts.cc +++ /dev/null @@ -1,127 +0,0 @@ -#include "selfdrive/ui/qt/widgets/offroad_alerts.h" - -#include -#include -#include -#include - -#include -#include -#include - -#include "common/util.h" -#include "system/hardware/hw.h" -#include "selfdrive/ui/qt/widgets/scrollview.h" - -AbstractAlert::AbstractAlert(bool hasRebootBtn, QWidget *parent) : QFrame(parent) { - QVBoxLayout *main_layout = new QVBoxLayout(this); - main_layout->setMargin(50); - main_layout->setSpacing(30); - - QWidget *widget = new QWidget; - scrollable_layout = new QVBoxLayout(widget); - widget->setStyleSheet("background-color: transparent;"); - main_layout->addWidget(new ScrollView(widget)); - - // bottom footer, dismiss + reboot buttons - QHBoxLayout *footer_layout = new QHBoxLayout(); - main_layout->addLayout(footer_layout); - - QPushButton *dismiss_btn = new QPushButton(tr("Close")); - dismiss_btn->setFixedSize(400, 125); - footer_layout->addWidget(dismiss_btn, 0, Qt::AlignBottom | Qt::AlignLeft); - QObject::connect(dismiss_btn, &QPushButton::clicked, this, &AbstractAlert::dismiss); - - snooze_btn = new QPushButton(tr("Snooze Update")); - snooze_btn->setVisible(false); - snooze_btn->setFixedSize(550, 125); - footer_layout->addWidget(snooze_btn, 0, Qt::AlignBottom | Qt::AlignRight); - QObject::connect(snooze_btn, &QPushButton::clicked, [=]() { - params.putBool("SnoozeUpdate", true); - }); - QObject::connect(snooze_btn, &QPushButton::clicked, this, &AbstractAlert::dismiss); - snooze_btn->setStyleSheet(R"(color: white; background-color: #4F4F4F;)"); - - if (hasRebootBtn) { - QPushButton *rebootBtn = new QPushButton(tr("Reboot and Update")); - rebootBtn->setFixedSize(600, 125); - footer_layout->addWidget(rebootBtn, 0, Qt::AlignBottom | Qt::AlignRight); - QObject::connect(rebootBtn, &QPushButton::clicked, [=]() { Hardware::reboot(); }); - } - - setStyleSheet(R"( - * { - font-size: 48px; - color: white; - } - QFrame { - border-radius: 30px; - background-color: #393939; - } - QPushButton { - color: black; - font-weight: 500; - border-radius: 30px; - background-color: white; - } - )"); -} - -int OffroadAlert::refresh() { - // build widgets for each offroad alert on first refresh - if (alerts.empty()) { - QString json = util::read_file("../selfdrived/alerts_offroad.json").c_str(); - QJsonObject obj = QJsonDocument::fromJson(json.toUtf8()).object(); - - // descending sort labels by severity - std::vector> sorted; - for (auto it = obj.constBegin(); it != obj.constEnd(); ++it) { - sorted.push_back({it.key().toStdString(), it.value()["severity"].toInt()}); - } - std::sort(sorted.begin(), sorted.end(), [=](auto &l, auto &r) { return l.second > r.second; }); - - for (auto &[key, severity] : sorted) { - QLabel *l = new QLabel(this); - alerts[key] = l; - l->setMargin(60); - l->setWordWrap(true); - l->setStyleSheet(QString("background-color: %1").arg(severity ? "#E22C2C" : "#292929")); - scrollable_layout->addWidget(l); - } - scrollable_layout->addStretch(1); - } - - int alertCount = 0; - for (const auto &[key, label] : alerts) { - QString text; - std::string bytes = params.get(key); - if (bytes.size()) { - auto doc_par = QJsonDocument::fromJson(bytes.c_str()); - text = tr(doc_par["text"].toString().toUtf8().data()); - auto extra = doc_par["extra"].toString(); - if (!extra.isEmpty()) { - text = text.arg(extra); - } - } - label->setText(text); - label->setVisible(!text.isEmpty()); - alertCount += !text.isEmpty(); - } - snooze_btn->setVisible(!alerts["Offroad_ConnectivityNeeded"]->text().isEmpty()); - return alertCount; -} - -UpdateAlert::UpdateAlert(QWidget *parent) : AbstractAlert(true, parent) { - releaseNotes = new QLabel(this); - releaseNotes->setWordWrap(true); - releaseNotes->setAlignment(Qt::AlignTop); - scrollable_layout->addWidget(releaseNotes); -} - -bool UpdateAlert::refresh() { - bool updateAvailable = params.getBool("UpdateAvailable"); - if (updateAvailable) { - releaseNotes->setText(params.get("UpdaterNewReleaseNotes").c_str()); - } - return updateAvailable; -} diff --git a/selfdrive/ui/qt/widgets/offroad_alerts.h b/selfdrive/ui/qt/widgets/offroad_alerts.h deleted file mode 100644 index ace2e75456..0000000000 --- a/selfdrive/ui/qt/widgets/offroad_alerts.h +++ /dev/null @@ -1,46 +0,0 @@ -#pragma once - -#include -#include - -#include -#include -#include - -#include "common/params.h" - -class AbstractAlert : public QFrame { - Q_OBJECT - -protected: - AbstractAlert(bool hasRebootBtn, QWidget *parent = nullptr); - - QPushButton *snooze_btn; - QVBoxLayout *scrollable_layout; - Params params; - -signals: - void dismiss(); -}; - -class UpdateAlert : public AbstractAlert { - Q_OBJECT - -public: - UpdateAlert(QWidget *parent = 0); - bool refresh(); - -private: - QLabel *releaseNotes = nullptr; -}; - -class OffroadAlert : public AbstractAlert { - Q_OBJECT - -public: - explicit OffroadAlert(QWidget *parent = 0) : AbstractAlert(false, parent) {} - int refresh(); - -private: - std::map alerts; -}; diff --git a/selfdrive/ui/qt/widgets/prime.cc b/selfdrive/ui/qt/widgets/prime.cc deleted file mode 100644 index a69580ea50..0000000000 --- a/selfdrive/ui/qt/widgets/prime.cc +++ /dev/null @@ -1,265 +0,0 @@ -#include "selfdrive/ui/qt/widgets/prime.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include "selfdrive/ui/qt/request_repeater.h" -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/qt/qt_window.h" -#include "selfdrive/ui/qt/widgets/wifi.h" - -using qrcodegen::QrCode; - -PairingQRWidget::PairingQRWidget(QWidget* parent) : QWidget(parent) { - timer = new QTimer(this); - connect(timer, &QTimer::timeout, this, &PairingQRWidget::refresh); -} - -void PairingQRWidget::showEvent(QShowEvent *event) { - refresh(); - timer->start(5 * 60 * 1000); - device()->setOffroadBrightness(100); -} - -void PairingQRWidget::hideEvent(QHideEvent *event) { - timer->stop(); - device()->setOffroadBrightness(BACKLIGHT_OFFROAD); -} - -void PairingQRWidget::refresh() { - QString pairToken = CommaApi::create_jwt({{"pair", true}}); - QString qrString = "https://connect.comma.ai/?pair=" + pairToken; - this->updateQrCode(qrString); - update(); -} - -void PairingQRWidget::updateQrCode(const QString &text) { - QrCode qr = QrCode::encodeText(text.toUtf8().data(), QrCode::Ecc::LOW); - qint32 sz = qr.getSize(); - QImage im(sz, sz, QImage::Format_RGB32); - - QRgb black = qRgb(0, 0, 0); - QRgb white = qRgb(255, 255, 255); - for (int y = 0; y < sz; y++) { - for (int x = 0; x < sz; x++) { - im.setPixel(x, y, qr.getModule(x, y) ? black : white); - } - } - - // Integer division to prevent anti-aliasing - int final_sz = ((width() / sz) - 1) * sz; - img = QPixmap::fromImage(im.scaled(final_sz, final_sz, Qt::KeepAspectRatio), Qt::MonoOnly); -} - -void PairingQRWidget::paintEvent(QPaintEvent *e) { - QPainter p(this); - p.fillRect(rect(), Qt::white); - - QSize s = (size() - img.size()) / 2; - p.drawPixmap(s.width(), s.height(), img); -} - - -PairingPopup::PairingPopup(QWidget *parent) : DialogBase(parent) { - QHBoxLayout *hlayout = new QHBoxLayout(this); - hlayout->setContentsMargins(0, 0, 0, 0); - hlayout->setSpacing(0); - - setStyleSheet("PairingPopup { background-color: #E0E0E0; }"); - - // text - QVBoxLayout *vlayout = new QVBoxLayout(); - vlayout->setContentsMargins(85, 70, 50, 70); - vlayout->setSpacing(50); - hlayout->addLayout(vlayout, 1); - { - QPushButton *close = new QPushButton(QIcon(":/icons/close.svg"), "", this); - close->setIconSize(QSize(80, 80)); - close->setStyleSheet("border: none;"); - vlayout->addWidget(close, 0, Qt::AlignLeft); - QObject::connect(close, &QPushButton::clicked, this, &QDialog::reject); - - vlayout->addSpacing(30); - - QLabel *title = new QLabel(tr("Pair your device to your comma account"), this); - title->setStyleSheet("font-size: 75px; color: black;"); - title->setWordWrap(true); - vlayout->addWidget(title); - - QLabel *instructions = new QLabel(QString(R"( -
    -
  1. %1
  2. -
  3. %2
  4. -
  5. %3
  6. -
- )").arg(tr("Go to https://connect.comma.ai on your phone")) - .arg(tr("Click \"add new device\" and scan the QR code on the right")) - .arg(tr("Bookmark connect.comma.ai to your home screen to use it like an app")), this); - - instructions->setStyleSheet("font-size: 47px; font-weight: bold; color: black;"); - instructions->setWordWrap(true); - vlayout->addWidget(instructions); - - vlayout->addStretch(); - } - - // QR code - PairingQRWidget *qr = new PairingQRWidget(this); - hlayout->addWidget(qr, 1); -} - -int PairingPopup::exec() { - if (!util::system_time_valid()) { - ConfirmationDialog::alert(tr("Please connect to Wi-Fi to complete initial pairing"), parentWidget()); - return QDialog::Rejected; - } - return DialogBase::exec(); -} - - -PrimeUserWidget::PrimeUserWidget(QWidget *parent) : QFrame(parent) { - setObjectName("primeWidget"); - QVBoxLayout *mainLayout = new QVBoxLayout(this); - mainLayout->setContentsMargins(56, 40, 56, 40); - mainLayout->setSpacing(20); - - QLabel *subscribed = new QLabel(tr("✓ SUBSCRIBED")); - subscribed->setStyleSheet("font-size: 41px; font-weight: bold; color: #86FF4E;"); - mainLayout->addWidget(subscribed); - - QLabel *commaPrime = new QLabel(tr("comma prime")); - commaPrime->setStyleSheet("font-size: 75px; font-weight: bold;"); - mainLayout->addWidget(commaPrime); -} - - -PrimeAdWidget::PrimeAdWidget(QWidget* parent) : QFrame(parent) { - QVBoxLayout *main_layout = new QVBoxLayout(this); - main_layout->setContentsMargins(80, 90, 80, 60); - main_layout->setSpacing(0); - - QLabel *upgrade = new QLabel(tr("Upgrade Now")); - upgrade->setStyleSheet("font-size: 75px; font-weight: bold;"); - main_layout->addWidget(upgrade, 0, Qt::AlignTop); - main_layout->addSpacing(50); - - QLabel *description = new QLabel(tr("Become a comma prime member at connect.comma.ai")); - description->setStyleSheet("font-size: 56px; font-weight: light; color: white;"); - description->setWordWrap(true); - main_layout->addWidget(description, 0, Qt::AlignTop); - - main_layout->addStretch(); - - QLabel *features = new QLabel(tr("PRIME FEATURES:")); - features->setStyleSheet("font-size: 41px; font-weight: bold; color: #E5E5E5;"); - main_layout->addWidget(features, 0, Qt::AlignBottom); - main_layout->addSpacing(30); - - QVector bullets = {tr("Remote access"), tr("24/7 LTE connectivity"), tr("1 year of drive storage"), tr("Remote snapshots")}; - for (auto &b : bullets) { - const QString check = " "; - QLabel *l = new QLabel(check + b); - l->setAlignment(Qt::AlignLeft); - l->setStyleSheet("font-size: 50px; margin-bottom: 15px;"); - main_layout->addWidget(l, 0, Qt::AlignBottom); - } - - setStyleSheet(R"( - PrimeAdWidget { - border-radius: 10px; - background-color: #333333; - } - )"); -} - - -SetupWidget::SetupWidget(QWidget* parent) : QFrame(parent) { - mainLayout = new QStackedWidget; - - // Unpaired, registration prompt layout - - QFrame* finishRegistration = new QFrame; - finishRegistration->setObjectName("primeWidget"); - QVBoxLayout* finishRegistrationLayout = new QVBoxLayout(finishRegistration); - finishRegistrationLayout->setSpacing(38); - finishRegistrationLayout->setContentsMargins(64, 48, 64, 48); - - QLabel* registrationTitle = new QLabel(tr("Finish Setup")); - registrationTitle->setStyleSheet("font-size: 75px; font-weight: bold;"); - finishRegistrationLayout->addWidget(registrationTitle); - - QLabel* registrationDescription = new QLabel(tr("Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer.")); - registrationDescription->setWordWrap(true); - registrationDescription->setStyleSheet("font-size: 50px; font-weight: light;"); - finishRegistrationLayout->addWidget(registrationDescription); - - finishRegistrationLayout->addStretch(); - - QPushButton* pair = new QPushButton(tr("Pair device")); - pair->setStyleSheet(R"( - QPushButton { - font-size: 55px; - font-weight: 500; - border-radius: 10px; - background-color: #465BEA; - padding: 64px; - } - QPushButton:pressed { - background-color: #3049F4; - } - )"); - finishRegistrationLayout->addWidget(pair); - - popup = new PairingPopup(this); - QObject::connect(pair, &QPushButton::clicked, popup, &PairingPopup::exec); - - mainLayout->addWidget(finishRegistration); - - // build stacked layout - QVBoxLayout *outer_layout = new QVBoxLayout(this); - outer_layout->setContentsMargins(0, 0, 0, 0); - outer_layout->addWidget(mainLayout); - - QWidget *content = new QWidget; - content_layout = new QVBoxLayout(content); - content_layout->setContentsMargins(0, 0, 0, 0); - content_layout->setSpacing(30); - - WiFiPromptWidget *wifi_prompt = new WiFiPromptWidget; - QObject::connect(wifi_prompt, &WiFiPromptWidget::openSettings, this, &SetupWidget::openSettings); - content_layout->addWidget(wifi_prompt); - content_layout->addStretch(); - - mainLayout->addWidget(content); - - mainLayout->setCurrentIndex(1); - - setStyleSheet(R"( - #primeWidget { - border-radius: 10px; - background-color: #333333; - } - )"); - - // Retain size while hidden - QSizePolicy sp_retain = sizePolicy(); - sp_retain.setRetainSizeWhenHidden(true); - setSizePolicy(sp_retain); - - QObject::connect(uiState()->prime_state, &PrimeState::changed, [this](PrimeState::Type type) { - if (type == PrimeState::PRIME_TYPE_UNPAIRED) { - mainLayout->setCurrentIndex(0); // Display "Pair your device" widget - } else { - popup->reject(); - mainLayout->setCurrentIndex(1); // Display Wi-Fi prompt widget - } - }); -} diff --git a/selfdrive/ui/qt/widgets/prime.h b/selfdrive/ui/qt/widgets/prime.h deleted file mode 100644 index 53d743398d..0000000000 --- a/selfdrive/ui/qt/widgets/prime.h +++ /dev/null @@ -1,73 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -#include "selfdrive/ui/qt/widgets/input.h" - -// pairing QR code -class PairingQRWidget : public QWidget { - Q_OBJECT - -public: - explicit PairingQRWidget(QWidget* parent = 0); - void paintEvent(QPaintEvent*) override; - -private: - QPixmap img; - QTimer *timer; - void updateQrCode(const QString &text); - void showEvent(QShowEvent *event) override; - void hideEvent(QHideEvent *event) override; - -private slots: - void refresh(); -}; - - -// pairing popup widget -class PairingPopup : public DialogBase { - Q_OBJECT - -public: - explicit PairingPopup(QWidget* parent); - int exec() override; -}; - - -// widget for paired users with prime -class PrimeUserWidget : public QFrame { - Q_OBJECT - -public: - explicit PrimeUserWidget(QWidget* parent = 0); -}; - - -// widget for paired users without prime -class PrimeAdWidget : public QFrame { - Q_OBJECT -public: - explicit PrimeAdWidget(QWidget* parent = 0); -}; - - -// container widget -class SetupWidget : public QFrame { - Q_OBJECT - -public: - explicit SetupWidget(QWidget* parent = 0); - -signals: - void openSettings(int index = 0, const QString ¶m = ""); - -protected: - QVBoxLayout *content_layout; - -private: - PairingPopup *popup; - QStackedWidget *mainLayout; -}; diff --git a/selfdrive/ui/qt/widgets/scrollview.cc b/selfdrive/ui/qt/widgets/scrollview.cc deleted file mode 100644 index 978bf83a63..0000000000 --- a/selfdrive/ui/qt/widgets/scrollview.cc +++ /dev/null @@ -1,49 +0,0 @@ -#include "selfdrive/ui/qt/widgets/scrollview.h" - -#include -#include - -// TODO: disable horizontal scrolling and resize - -ScrollView::ScrollView(QWidget *w, QWidget *parent) : QScrollArea(parent) { - setWidget(w); - setWidgetResizable(true); - setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - setStyleSheet("background-color: transparent; border:none"); - - QString style = R"( - QScrollBar:vertical { - border: none; - background: transparent; - width: 10px; - margin: 0; - } - QScrollBar::handle:vertical { - min-height: 0px; - border-radius: 5px; - background-color: white; - } - QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { - height: 0px; - } - QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical { - background: none; - } - )"; - verticalScrollBar()->setStyleSheet(style); - horizontalScrollBar()->setStyleSheet(style); - - QScroller *scroller = QScroller::scroller(this->viewport()); - QScrollerProperties sp = scroller->scrollerProperties(); - - sp.setScrollMetric(QScrollerProperties::VerticalOvershootPolicy, QVariant::fromValue(QScrollerProperties::OvershootAlwaysOff)); - sp.setScrollMetric(QScrollerProperties::HorizontalOvershootPolicy, QVariant::fromValue(QScrollerProperties::OvershootAlwaysOff)); - sp.setScrollMetric(QScrollerProperties::MousePressEventDelay, 0.01); - scroller->grabGesture(this->viewport(), QScroller::LeftMouseButtonGesture); - scroller->setScrollerProperties(sp); -} - -void ScrollView::hideEvent(QHideEvent *e) { - verticalScrollBar()->setValue(0); -} diff --git a/selfdrive/ui/qt/widgets/scrollview.h b/selfdrive/ui/qt/widgets/scrollview.h deleted file mode 100644 index 024331aa39..0000000000 --- a/selfdrive/ui/qt/widgets/scrollview.h +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once - -#include - -class ScrollView : public QScrollArea { - Q_OBJECT - -public: - explicit ScrollView(QWidget *w = nullptr, QWidget *parent = nullptr); -protected: - void hideEvent(QHideEvent *e) override; -}; diff --git a/selfdrive/ui/qt/widgets/ssh_keys.cc b/selfdrive/ui/qt/widgets/ssh_keys.cc deleted file mode 100644 index 26743952de..0000000000 --- a/selfdrive/ui/qt/widgets/ssh_keys.cc +++ /dev/null @@ -1,64 +0,0 @@ -#include "selfdrive/ui/qt/widgets/ssh_keys.h" - -#include "common/params.h" -#include "selfdrive/ui/qt/api.h" -#include "selfdrive/ui/qt/widgets/input.h" - -SshControl::SshControl() : - ButtonControl(tr("SSH Keys"), "", tr("Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username " - "other than your own. A comma employee will NEVER ask you to add their GitHub username.")) { - - QObject::connect(this, &ButtonControl::clicked, [=]() { - if (text() == tr("ADD")) { - QString username = InputDialog::getText(tr("Enter your GitHub username"), this); - if (username.length() > 0) { - setText(tr("LOADING")); - setEnabled(false); - getUserKeys(username); - } - } else { - params.remove("GithubUsername"); - params.remove("GithubSshKeys"); - refresh(); - } - }); - - refresh(); -} - -void SshControl::refresh() { - QString param = QString::fromStdString(params.get("GithubSshKeys")); - if (param.length()) { - setValue(QString::fromStdString(params.get("GithubUsername"))); - setText(tr("REMOVE")); - } else { - setValue(""); - setText(tr("ADD")); - } - setEnabled(true); -} - -void SshControl::getUserKeys(const QString &username) { - HttpRequest *request = new HttpRequest(this, false); - QObject::connect(request, &HttpRequest::requestDone, [=](const QString &resp, bool success) { - if (success) { - if (!resp.isEmpty()) { - params.put("GithubUsername", username.toStdString()); - params.put("GithubSshKeys", resp.toStdString()); - } else { - ConfirmationDialog::alert(tr("Username '%1' has no keys on GitHub").arg(username), this); - } - } else { - if (request->timeout()) { - ConfirmationDialog::alert(tr("Request timed out"), this); - } else { - ConfirmationDialog::alert(tr("Username '%1' doesn't exist on GitHub").arg(username), this); - } - } - - refresh(); - request->deleteLater(); - }); - - request->sendRequest("https://github.com/" + username + ".keys"); -} diff --git a/selfdrive/ui/qt/widgets/ssh_keys.h b/selfdrive/ui/qt/widgets/ssh_keys.h deleted file mode 100644 index ef40346c83..0000000000 --- a/selfdrive/ui/qt/widgets/ssh_keys.h +++ /dev/null @@ -1,39 +0,0 @@ -#pragma once - -#include - -#include "system/hardware/hw.h" - -#ifdef SUNNYPILOT -#include "selfdrive/ui/sunnypilot/qt/widgets/controls.h" -#define ButtonControl ButtonControlSP -#define ToggleControl ToggleControlSP -#else -#include "selfdrive/ui/qt/widgets/controls.h" -#endif - -// SSH enable toggle -class SshToggle : public ToggleControl { - Q_OBJECT - -public: - SshToggle() : ToggleControl(tr("Enable SSH"), "", "", Hardware::get_ssh_enabled()) { - QObject::connect(this, &SshToggle::toggleFlipped, [=](bool state) { - Hardware::set_ssh_enabled(state); - }); - } -}; - -// SSH key management widget -class SshControl : public ButtonControl { - Q_OBJECT - -public: - SshControl(); - -private: - Params params; - - void refresh(); - void getUserKeys(const QString &username); -}; diff --git a/selfdrive/ui/qt/widgets/toggle.cc b/selfdrive/ui/qt/widgets/toggle.cc deleted file mode 100644 index 82302ad5bc..0000000000 --- a/selfdrive/ui/qt/widgets/toggle.cc +++ /dev/null @@ -1,83 +0,0 @@ -#include "selfdrive/ui/qt/widgets/toggle.h" - -#include - -Toggle::Toggle(QWidget *parent) : QAbstractButton(parent), -_height(80), -_height_rect(60), -on(false), -_anim(new QPropertyAnimation(this, "offset_circle", this)) -{ - _radius = _height / 2; - _x_circle = _radius; - _y_circle = _radius; - _y_rect = (_height - _height_rect)/2; - circleColor = QColor(0xffffff); // placeholder - green = QColor(0xffffff); // placeholder - setEnabled(true); -} - -void Toggle::paintEvent(QPaintEvent *e) { - this->setFixedHeight(_height); - QPainter p(this); - p.setPen(Qt::NoPen); - p.setRenderHint(QPainter::Antialiasing, true); - - // Draw toggle background left - p.setBrush(green); - p.drawRoundedRect(QRect(0, _y_rect, _x_circle + _radius, _height_rect), _height_rect/2, _height_rect/2); - - // Draw toggle background right - p.setBrush(QColor(0x393939)); - p.drawRoundedRect(QRect(_x_circle - _radius, _y_rect, width() - (_x_circle - _radius), _height_rect), _height_rect/2, _height_rect/2); - - // Draw toggle circle - p.setBrush(circleColor); - p.drawEllipse(QRectF(_x_circle - _radius, _y_circle - _radius, 2 * _radius, 2 * _radius)); -} - -void Toggle::mouseReleaseEvent(QMouseEvent *e) { - if (!enabled) { - return; - } - const int left = _radius; - const int right = width() - _radius; - if ((_x_circle != left && _x_circle != right) || !this->rect().contains(e->localPos().toPoint())) { - // If mouse release isn't in rect or animation is running, don't parse touch events - return; - } - if (e->button() & Qt::LeftButton) { - togglePosition(); - emit stateChanged(on); - } -} - -void Toggle::togglePosition() { - on = !on; - const int left = _radius; - const int right = width() - _radius; - _anim->setStartValue(on ? left + immediateOffset : right - immediateOffset); - _anim->setEndValue(on ? right : left); - _anim->setDuration(animation_duration); - _anim->start(); - repaint(); -} - -void Toggle::enterEvent(QEvent *e) { - QAbstractButton::enterEvent(e); -} - -bool Toggle::getEnabled() { - return enabled; -} - -void Toggle::setEnabled(bool value) { - enabled = value; - if (value) { - circleColor.setRgb(0xfafafa); - green.setRgb(0x33ab4c); - } else { - circleColor.setRgb(0x888888); - green.setRgb(0x227722); - } -} diff --git a/selfdrive/ui/qt/widgets/toggle.h b/selfdrive/ui/qt/widgets/toggle.h deleted file mode 100644 index a0fa434a4c..0000000000 --- a/selfdrive/ui/qt/widgets/toggle.h +++ /dev/null @@ -1,43 +0,0 @@ -#pragma once - -#include -#include -#include - -class Toggle : public QAbstractButton { - Q_OBJECT - Q_PROPERTY(int offset_circle READ offset_circle WRITE set_offset_circle CONSTANT) - -public: - Toggle(QWidget* parent = nullptr); - void togglePosition(); - bool on; - int animation_duration = 150; - int immediateOffset = 0; - int offset_circle() const { - return _x_circle; - } - - void set_offset_circle(int o) { - _x_circle = o; - update(); - } - bool getEnabled(); - virtual void setEnabled(bool value); - -protected: - void paintEvent(QPaintEvent*) override; - void mouseReleaseEvent(QMouseEvent*) override; - void enterEvent(QEvent*) override; - - QColor circleColor; - QColor green; - bool enabled = true; - int _x_circle, _y_circle; - int _height, _radius; - int _height_rect, _y_rect; - QPropertyAnimation *_anim = nullptr; - -signals: - void stateChanged(bool new_state); -}; diff --git a/selfdrive/ui/qt/widgets/wifi.cc b/selfdrive/ui/qt/widgets/wifi.cc deleted file mode 100644 index d7eb8beeb3..0000000000 --- a/selfdrive/ui/qt/widgets/wifi.cc +++ /dev/null @@ -1,45 +0,0 @@ -#include "selfdrive/ui/qt/widgets/wifi.h" - -#include -#include -#include -#include - -WiFiPromptWidget::WiFiPromptWidget(QWidget *parent) : QFrame(parent) { - // Setup Firehose Mode - QVBoxLayout *main_layout = new QVBoxLayout(this); - main_layout->setContentsMargins(56, 40, 56, 40); - main_layout->setSpacing(42); - - QLabel *title = new QLabel(tr("🔥 Firehose Mode 🔥")); - title->setStyleSheet("font-size: 64px; font-weight: 500;"); - main_layout->addWidget(title); - - QLabel *desc = new QLabel(tr("Maximize your training data uploads to improve openpilot's driving models.")); - desc->setStyleSheet("font-size: 40px; font-weight: 400;"); - desc->setWordWrap(true); - main_layout->addWidget(desc); - - QPushButton *settings_btn = new QPushButton(tr("Open")); - connect(settings_btn, &QPushButton::clicked, [=]() { emit openSettings(1, "FirehosePanel"); }); - settings_btn->setStyleSheet(R"( - QPushButton { - font-size: 48px; - font-weight: 500; - border-radius: 10px; - background-color: #465BEA; - padding: 32px; - } - QPushButton:pressed { - background-color: #3049F4; - } - )"); - main_layout->addWidget(settings_btn); - - setStyleSheet(R"( - WiFiPromptWidget { - background-color: #333333; - border-radius: 10px; - } - )"); -} \ No newline at end of file diff --git a/selfdrive/ui/qt/widgets/wifi.h b/selfdrive/ui/qt/widgets/wifi.h deleted file mode 100644 index 3e68a15b7b..0000000000 --- a/selfdrive/ui/qt/widgets/wifi.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#include -#include - -class WiFiPromptWidget : public QFrame { - Q_OBJECT - -public: - explicit WiFiPromptWidget(QWidget* parent = 0); - -signals: - void openSettings(int index = 0, const QString ¶m = ""); -}; diff --git a/selfdrive/ui/qt/window.cc b/selfdrive/ui/qt/window.cc deleted file mode 100644 index 36f12c266b..0000000000 --- a/selfdrive/ui/qt/window.cc +++ /dev/null @@ -1,101 +0,0 @@ -#include "selfdrive/ui/qt/window.h" - -#include - -#include "system/hardware/hw.h" - -// We have this constructor so that we can provide custom implementations of the windows. By default (stock_ui) would receive them as nullptr, so they'll be instantiated with stock. Otherwise they'd be SP instances -MainWindow::MainWindow(QWidget *parent, HomeWindow *hw, SettingsWindow *sw) : - QWidget(parent), - homeWindow(hw ? hw : new HomeWindow(this)), - settingsWindow(sw ? sw : new SettingsWindow(this)) { - - main_layout = new QStackedLayout(this); - main_layout->setMargin(0); - - main_layout->addWidget(homeWindow); - QObject::connect(homeWindow, &HomeWindow::openSettings, this, &MainWindow::openSettings); - QObject::connect(homeWindow, &HomeWindow::closeSettings, this, &MainWindow::closeSettings); - - main_layout->addWidget(settingsWindow); - QObject::connect(settingsWindow, &SettingsWindow::closeSettings, this, &MainWindow::closeSettings); - QObject::connect(settingsWindow, &SettingsWindow::reviewTrainingGuide, [=]() { - onboardingWindow->showTrainingGuide(); - main_layout->setCurrentWidget(onboardingWindow); - }); - QObject::connect(settingsWindow, &SettingsWindow::showDriverView, [=] { - homeWindow->showDriverView(true); - }); - - onboardingWindow = new OnboardingWindow(this); - main_layout->addWidget(onboardingWindow); - QObject::connect(onboardingWindow, &OnboardingWindow::onboardingDone, [=]() { - main_layout->setCurrentWidget(homeWindow); - }); - if (!onboardingWindow->completed()) { - main_layout->setCurrentWidget(onboardingWindow); - } - - QObject::connect(uiState(), &UIState::offroadTransition, [=](bool offroad) { - if (!offroad) { - closeSettings(); - } - }); - QObject::connect(device(), &Device::interactiveTimeout, [=]() { - if (main_layout->currentWidget() == settingsWindow) { - closeSettings(); - } - }); - - // load fonts - QFontDatabase::addApplicationFont("../assets/fonts/Inter-Black.ttf"); - QFontDatabase::addApplicationFont("../assets/fonts/Inter-Bold.ttf"); - QFontDatabase::addApplicationFont("../assets/fonts/Inter-ExtraBold.ttf"); - QFontDatabase::addApplicationFont("../assets/fonts/Inter-ExtraLight.ttf"); - QFontDatabase::addApplicationFont("../assets/fonts/Inter-Medium.ttf"); - QFontDatabase::addApplicationFont("../assets/fonts/Inter-Regular.ttf"); - QFontDatabase::addApplicationFont("../assets/fonts/Inter-SemiBold.ttf"); - QFontDatabase::addApplicationFont("../assets/fonts/Inter-Thin.ttf"); - QFontDatabase::addApplicationFont("../assets/fonts/JetBrainsMono-Medium.ttf"); - - // no outline to prevent the focus rectangle - setStyleSheet(R"( - * { - font-family: Inter; - outline: none; - } - )"); - setAttribute(Qt::WA_NoSystemBackground); -} - -void MainWindow::openSettings(int index, const QString ¶m) { - main_layout->setCurrentWidget(settingsWindow); - settingsWindow->setCurrentPanel(index, param); -} - -void MainWindow::closeSettings() { - main_layout->setCurrentWidget(homeWindow); - - if (uiState()->scene.started) { - homeWindow->showSidebar(false); - } -} - -bool MainWindow::eventFilter(QObject *obj, QEvent *event) { - bool ignore = false; - switch (event->type()) { - case QEvent::TouchBegin: - case QEvent::TouchUpdate: - case QEvent::TouchEnd: - case QEvent::MouseButtonPress: - case QEvent::MouseMove: { - // ignore events when device is awakened by resetInteractiveTimeout - ignore = !device()->isAwake(); - device()->resetInteractiveTimeout(); - break; - } - default: - break; - } - return ignore; -} diff --git a/selfdrive/ui/qt/window.h b/selfdrive/ui/qt/window.h deleted file mode 100644 index 8a118b0bb6..0000000000 --- a/selfdrive/ui/qt/window.h +++ /dev/null @@ -1,28 +0,0 @@ -#pragma once - -#include -#include - -#include "selfdrive/ui/qt/home.h" -#include "selfdrive/ui/qt/offroad/onboarding.h" -#include "selfdrive/ui/qt/offroad/settings.h" - -class MainWindow : public QWidget { - Q_OBJECT - -public: - explicit MainWindow(QWidget *parent = 0) : MainWindow(parent, nullptr, nullptr) {} - -protected: - explicit MainWindow(QWidget *parent, HomeWindow *hw = nullptr, SettingsWindow *sw = nullptr); - HomeWindow *homeWindow; - SettingsWindow *settingsWindow; - virtual void closeSettings(); - -private: - bool eventFilter(QObject *obj, QEvent *event) override; - void openSettings(int index = 0, const QString ¶m = ""); - - QStackedLayout *main_layout; - OnboardingWindow *onboardingWindow; -}; diff --git a/selfdrive/ui/soundd.py b/selfdrive/ui/soundd.py deleted file mode 100644 index facb398339..0000000000 --- a/selfdrive/ui/soundd.py +++ /dev/null @@ -1,170 +0,0 @@ -import math -import numpy as np -import time -import wave - - -from cereal import car, messaging -from openpilot.common.basedir import BASEDIR -from openpilot.common.filter_simple import FirstOrderFilter -from openpilot.common.realtime import Ratekeeper -from openpilot.common.retry import retry -from openpilot.common.swaglog import cloudlog - -from openpilot.system import micd - -from openpilot.selfdrive.ui.sunnypilot.quiet_mode import QuietMode - -SAMPLE_RATE = 48000 -SAMPLE_BUFFER = 4096 # (approx 100ms) -MAX_VOLUME = 1.0 -MIN_VOLUME = 0.1 -SELFDRIVE_STATE_TIMEOUT = 5 # 5 seconds -FILTER_DT = 1. / (micd.SAMPLE_RATE / micd.FFT_SAMPLES) - -AMBIENT_DB = 30 # DB where MIN_VOLUME is applied -DB_SCALE = 30 # AMBIENT_DB + DB_SCALE is where MAX_VOLUME is applied - -AudibleAlert = car.CarControl.HUDControl.AudibleAlert - - -sound_list: dict[int, tuple[str, int | None, float]] = { - # AudibleAlert, file name, play count (none for infinite) - AudibleAlert.engage: ("engage.wav", 1, MAX_VOLUME), - AudibleAlert.disengage: ("disengage.wav", 1, MAX_VOLUME), - AudibleAlert.refuse: ("refuse.wav", 1, MAX_VOLUME), - - AudibleAlert.prompt: ("prompt.wav", 1, MAX_VOLUME), - AudibleAlert.promptRepeat: ("prompt.wav", None, MAX_VOLUME), - AudibleAlert.promptDistracted: ("prompt_distracted.wav", None, MAX_VOLUME), - - AudibleAlert.warningSoft: ("warning_soft.wav", None, MAX_VOLUME), - AudibleAlert.warningImmediate: ("warning_immediate.wav", None, MAX_VOLUME), -} - -def check_selfdrive_timeout_alert(sm): - ss_missing = time.monotonic() - sm.recv_time['selfdriveState'] - - if ss_missing > SELFDRIVE_STATE_TIMEOUT: - if sm['selfdriveState'].enabled and (ss_missing - SELFDRIVE_STATE_TIMEOUT) < 10: - return True - - return False - - -class Soundd(QuietMode): - def __init__(self): - super().__init__() - - self.load_sounds() - - self.current_alert = AudibleAlert.none - self.current_volume = MIN_VOLUME - self.current_sound_frame = 0 - - self.selfdrive_timeout_alert = False - - self.spl_filter_weighted = FirstOrderFilter(0, 2.5, FILTER_DT, initialized=False) - - def load_sounds(self): - self.loaded_sounds: dict[int, np.ndarray] = {} - - # Load all sounds - for sound in sound_list: - filename, play_count, volume = sound_list[sound] - - with wave.open(BASEDIR + "/selfdrive/assets/sounds/" + filename, 'r') as wavefile: - assert wavefile.getnchannels() == 1 - assert wavefile.getsampwidth() == 2 - assert wavefile.getframerate() == SAMPLE_RATE - - length = wavefile.getnframes() - self.loaded_sounds[sound] = np.frombuffer(wavefile.readframes(length), dtype=np.int16).astype(np.float32) / (2**16/2) - - def get_sound_data(self, frames): # get "frames" worth of data from the current alert sound, looping when required - - ret = np.zeros(frames, dtype=np.float32) - - if self.should_play_sound(self.current_alert): - num_loops = sound_list[self.current_alert][1] - sound_data = self.loaded_sounds[self.current_alert] - written_frames = 0 - - current_sound_frame = self.current_sound_frame % len(sound_data) - loops = self.current_sound_frame // len(sound_data) - - while written_frames < frames and (num_loops is None or loops < num_loops): - available_frames = sound_data.shape[0] - current_sound_frame - frames_to_write = min(available_frames, frames - written_frames) - ret[written_frames:written_frames+frames_to_write] = sound_data[current_sound_frame:current_sound_frame+frames_to_write] - written_frames += frames_to_write - self.current_sound_frame += frames_to_write - - return ret * self.current_volume - - def callback(self, data_out: np.ndarray, frames: int, time, status) -> None: - if status: - cloudlog.warning(f"soundd stream over/underflow: {status}") - data_out[:frames, 0] = self.get_sound_data(frames) - - def update_alert(self, new_alert): - current_alert_played_once = self.current_alert == AudibleAlert.none or self.current_sound_frame > len(self.loaded_sounds[self.current_alert]) - if self.current_alert != new_alert and (new_alert != AudibleAlert.none or current_alert_played_once): - self.current_alert = new_alert - self.current_sound_frame = 0 - - def get_audible_alert(self, sm): - if sm.updated['selfdriveState']: - new_alert = sm['selfdriveState'].alertSound.raw - self.update_alert(new_alert) - elif check_selfdrive_timeout_alert(sm): - self.update_alert(AudibleAlert.warningImmediate) - self.selfdrive_timeout_alert = True - elif self.selfdrive_timeout_alert: - self.update_alert(AudibleAlert.none) - self.selfdrive_timeout_alert = False - - def calculate_volume(self, weighted_db): - volume = ((weighted_db - AMBIENT_DB) / DB_SCALE) * (MAX_VOLUME - MIN_VOLUME) + MIN_VOLUME - return math.pow(10, (np.clip(volume, MIN_VOLUME, MAX_VOLUME) - 1)) - - @retry(attempts=7, delay=3) - def get_stream(self, sd): - # reload sounddevice to reinitialize portaudio - sd._terminate() - sd._initialize() - return sd.OutputStream(channels=1, samplerate=SAMPLE_RATE, callback=self.callback, blocksize=SAMPLE_BUFFER) - - def soundd_thread(self): - # sounddevice must be imported after forking processes - import sounddevice as sd - - sm = messaging.SubMaster(['selfdriveState', 'microphone']) - - with self.get_stream(sd) as stream: - rk = Ratekeeper(20) - - cloudlog.info(f"soundd stream started: {stream.samplerate=} {stream.channels=} {stream.dtype=} {stream.device=}, {stream.blocksize=}") - while True: - sm.update(0) - - self.load_param() - - if sm.updated['microphone'] and self.current_alert == AudibleAlert.none: # only update volume filter when not playing alert - self.spl_filter_weighted.update(sm["microphone"].soundPressureWeightedDb) - self.current_volume = self.calculate_volume(float(self.spl_filter_weighted.x)) - - self.get_audible_alert(sm) - - rk.keep_time() - - assert stream.active - - -def main(): - s = Soundd() - s.soundd_thread() - - -if __name__ == "__main__": - main() diff --git a/selfdrive/ui/sunnypilot/SConscript b/selfdrive/ui/sunnypilot/SConscript deleted file mode 100644 index f143d94dce..0000000000 --- a/selfdrive/ui/sunnypilot/SConscript +++ /dev/null @@ -1,94 +0,0 @@ -widgets_src = [ - "sunnypilot/qt/request_repeater.cc", - "sunnypilot/qt/widgets/toggle.cc", - "sunnypilot/qt/widgets/controls.cc", - "sunnypilot/qt/widgets/drive_stats.cc", - "sunnypilot/qt/widgets/expandable_row.cc", - "sunnypilot/qt/widgets/prime.cc", - "sunnypilot/qt/widgets/scrollview.cc", - "sunnypilot/qt/network/networking.cc", -] - -qt_util = [ - "sunnypilot/qt/util.cc", -] - -qt_src = [ - "sunnypilot/ui.cc", - "sunnypilot/qt/api.cc", - "sunnypilot/qt/sidebar.cc", - "sunnypilot/qt/window.cc", - "sunnypilot/qt/home.cc", - "sunnypilot/qt/offroad/exit_offroad_button.cc", - "sunnypilot/qt/offroad/offroad_home.cc", - "sunnypilot/qt/offroad/settings/device_panel.cc", - "sunnypilot/qt/offroad/settings/lateral_panel.cc", - "sunnypilot/qt/offroad/settings/longitudinal_panel.cc", - "sunnypilot/qt/offroad/settings/max_time_offroad.cc", - "sunnypilot/qt/offroad/settings/brightness.cc", - "sunnypilot/qt/offroad/settings/models_panel.cc", - "sunnypilot/qt/offroad/settings/osm_panel.cc", - "sunnypilot/qt/offroad/settings/settings.cc", - "sunnypilot/qt/offroad/settings/software_panel.cc", - "sunnypilot/qt/offroad/settings/sunnylink_panel.cc", - "sunnypilot/qt/offroad/settings/sunnylink/sponsor_widget.cc", - "sunnypilot/qt/offroad/settings/trips_panel.cc", - "sunnypilot/qt/offroad/settings/vehicle_panel.cc", - "sunnypilot/qt/offroad/settings/visuals_panel.cc", - "sunnypilot/qt/onroad/annotated_camera.cc", - "sunnypilot/qt/onroad/buttons.cc", - "sunnypilot/qt/onroad/hud.cc", - "sunnypilot/qt/onroad/model.cc", - "sunnypilot/qt/onroad/onroad_home.cc", -] - -lateral_panel_qt_src = [ - "sunnypilot/qt/offroad/settings/lateral/blinker_pause_lateral_settings.cc", - "sunnypilot/qt/offroad/settings/lateral/lane_change_settings.cc", - "sunnypilot/qt/offroad/settings/lateral/mads_settings.cc", - "sunnypilot/qt/offroad/settings/lateral/angle_tuning_settings.cc", - "sunnypilot/qt/offroad/settings/lateral/neural_network_lateral_control.cc", -] - -longitudinal_panel_qt_src = [ - "sunnypilot/qt/offroad/settings/longitudinal/custom_acc_increment.cc", -] - -network_src = [ - "sunnypilot/qt/network/sunnylink/sunnylink_client.cc", - "sunnypilot/qt/network/sunnylink/services/base_device_service.cc", - "sunnypilot/qt/network/sunnylink/services/role_service.cc", - "sunnypilot/qt/network/sunnylink/services/user_service.cc", -] - -osm_panel_qt_src = [ - "sunnypilot/qt/offroad/settings/osm/models_fetcher.cc", -] - -vehicle_panel_qt_src = [ - "sunnypilot/qt/offroad/settings/vehicle/brand_settings_factory.cc", - "sunnypilot/qt/offroad/settings/vehicle/brand_settings_interface.cc", - "sunnypilot/qt/offroad/settings/vehicle/platform_selector.cc", -] - -brand_settings_qt_src = [ - "sunnypilot/qt/offroad/settings/vehicle/chrysler_settings.cc", - "sunnypilot/qt/offroad/settings/vehicle/ford_settings.cc", - "sunnypilot/qt/offroad/settings/vehicle/gm_settings.cc", - "sunnypilot/qt/offroad/settings/vehicle/honda_settings.cc", - "sunnypilot/qt/offroad/settings/vehicle/hyundai_settings.cc", - "sunnypilot/qt/offroad/settings/vehicle/mazda_settings.cc", - "sunnypilot/qt/offroad/settings/vehicle/nissan_settings.cc", - "sunnypilot/qt/offroad/settings/vehicle/rivian_settings.cc", - "sunnypilot/qt/offroad/settings/vehicle/subaru_settings.cc", - "sunnypilot/qt/offroad/settings/vehicle/tesla_settings.cc", - "sunnypilot/qt/offroad/settings/vehicle/toyota_settings.cc", - "sunnypilot/qt/offroad/settings/vehicle/volkswagen_settings.cc", -] - - -sp_widgets_src = widgets_src + network_src -sp_qt_src = qt_src + lateral_panel_qt_src + vehicle_panel_qt_src + brand_settings_qt_src + longitudinal_panel_qt_src + osm_panel_qt_src -sp_qt_util = qt_util - -Export('sp_widgets_src', 'sp_qt_src', "sp_qt_util") diff --git a/selfdrive/ui/sunnypilot/qt/api.cc b/selfdrive/ui/sunnypilot/qt/api.cc deleted file mode 100644 index d75d8d39f0..0000000000 --- a/selfdrive/ui/sunnypilot/qt/api.cc +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/api.h" - -#include -#include - -#include "util.h" -#include "selfdrive/ui/qt/util.h" - -namespace SunnylinkApi { - QString create_jwt(const QJsonObject &payloads, int expiry, bool sunnylink) { - QJsonObject header = {{"alg", "RS256"}}; - - auto t = QDateTime::currentSecsSinceEpoch(); - auto dongle_id = sunnylink ? getSunnylinkDongleId() : getDongleId(); - QJsonObject payload = {{"identity", dongle_id.value_or("")}, {"nbf", t}, {"iat", t}, {"exp", t + expiry}}; - for (auto it = payloads.begin(); it != payloads.end(); ++it) { - payload.insert(it.key(), it.value()); - } - - auto b64_opts = QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals; - QString jwt = QJsonDocument(header).toJson(QJsonDocument::Compact).toBase64(b64_opts) + '.' + - QJsonDocument(payload).toJson(QJsonDocument::Compact).toBase64(b64_opts); - - auto hash = QCryptographicHash::hash(jwt.toUtf8(), QCryptographicHash::Sha256); - return jwt + "." + CommaApi::rsa_sign(hash).toBase64(b64_opts); - } -} // namespace SunnylinkApi - -void HttpRequestSP::sendRequest(const QString& requestURL, Method method, const QByteArray& payload) { - if (active()) { - return; - } - QNetworkRequest request = prepareRequest(requestURL); - - if(!payload.isEmpty() && (method == Method::POST || method == Method::PUT)) { - request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); - } - - switch (method) { - case Method::GET: - reply = nam()->get(request); - break; - case Method::DELETE: - reply = nam()->deleteResource(request); - break; - case Method::POST: - reply = nam()->post(request, payload); - break; - case Method::PUT: - reply = nam()->put(request, payload); - break; - } - - networkTimer->start(); - connect(reply, &QNetworkReply::finished, this, &HttpRequestSP::requestFinished); -} diff --git a/selfdrive/ui/sunnypilot/qt/api.h b/selfdrive/ui/sunnypilot/qt/api.h deleted file mode 100644 index 592b2e668f..0000000000 --- a/selfdrive/ui/sunnypilot/qt/api.h +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/qt/api.h" -#include "selfdrive/ui/sunnypilot/qt/util.h" -#include "common/util.h" - -namespace SunnylinkApi { - QByteArray rsa_encrypt(const QByteArray& data); - QByteArray rsa_decrypt(const QByteArray& data); - QString create_jwt(const QJsonObject& payloads = {}, int expiry = 3600, bool sunnylink = false); -} - -class HttpRequestSP : public HttpRequest { - Q_OBJECT - -public: - explicit HttpRequestSP(QObject* parent, bool create_jwt = true, int timeout = 20000, bool sunnylink = false) : - HttpRequest(parent, create_jwt, timeout), sunnylink(sunnylink) {} - - using HttpRequest::sendRequest; - void sendRequest(const QString& requestURL, Method method, const QByteArray& payload); - -private: - bool sunnylink; - -protected: - [[nodiscard]] QString GetJwtToken() const override { return SunnylinkApi::create_jwt({}, 3600, sunnylink); } - [[nodiscard]] QString GetUserAgent() const override { return getUserAgent(sunnylink); } -}; diff --git a/selfdrive/ui/sunnypilot/qt/common/json_fetcher.h b/selfdrive/ui/sunnypilot/qt/common/json_fetcher.h deleted file mode 100644 index 5691f600a6..0000000000 --- a/selfdrive/ui/sunnypilot/qt/common/json_fetcher.h +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include -#include -#include -#include - -class JsonFetcher { -public: - static QJsonObject getJsonFromURL(const QString &url) { - const auto qurl = QUrl(url); - QNetworkAccessManager manager; - const QNetworkRequest request(qurl); - QNetworkReply *reply = manager.get(request); - QEventLoop loop; - - // Send GET request - - QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit); - loop.exec(); - - if (reply->error() != QNetworkReply::NoError) { - qWarning() << "Failed to fetch data from URL: " << reply->errorString(); - return QJsonObject(); - } - - const QByteArray responseData = reply->readAll(); - const QJsonDocument doc = QJsonDocument::fromJson(responseData); - QJsonObject json = doc.object(); - - reply->deleteLater(); - return json; - } -}; diff --git a/selfdrive/ui/sunnypilot/qt/home.cc b/selfdrive/ui/sunnypilot/qt/home.cc deleted file mode 100644 index 92b6e724fe..0000000000 --- a/selfdrive/ui/sunnypilot/qt/home.cc +++ /dev/null @@ -1,21 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/home.h" - -#include "selfdrive/ui/sunnypilot/qt/widgets/drive_stats.h" - -HomeWindowSP::HomeWindowSP(QWidget *parent) : HomeWindow(parent) { -} - -void HomeWindowSP::updateState(const UIState &s) { - HomeWindow::updateState(s); -} - -void HomeWindowSP::mousePressEvent(QMouseEvent *e) { - HomeWindow::mousePressEvent(e); -} diff --git a/selfdrive/ui/sunnypilot/qt/home.h b/selfdrive/ui/sunnypilot/qt/home.h deleted file mode 100644 index 4cf532d14c..0000000000 --- a/selfdrive/ui/sunnypilot/qt/home.h +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include -#include - -#include "common/params.h" -#include "selfdrive/ui/qt/body.h" -#include "selfdrive/ui/qt/widgets/offroad_alerts.h" -#include "selfdrive/ui/sunnypilot/ui.h" -#include "selfdrive/ui/qt/home.h" - -#ifdef SUNNYPILOT -#include "selfdrive/ui/sunnypilot/qt/sidebar.h" -#define OnroadWindow OnroadWindowSP -#else -#include "selfdrive/ui/qt/sidebar.h" -#include "selfdrive/ui/qt/onroad/onroad_home.h" -#endif - -class HomeWindowSP : public HomeWindow { - Q_OBJECT - -public: - explicit HomeWindowSP(QWidget *parent = 0); - -protected: - void mousePressEvent(QMouseEvent *e) override; - -private slots: - void updateState(const UIState &s) override; -}; diff --git a/selfdrive/ui/sunnypilot/qt/network/networking.cc b/selfdrive/ui/sunnypilot/qt/network/networking.cc deleted file mode 100644 index 3db65a5b51..0000000000 --- a/selfdrive/ui/sunnypilot/qt/network/networking.cc +++ /dev/null @@ -1,45 +0,0 @@ -#include "selfdrive/ui/sunnypilot/qt/network/networking.h" -#include -#include -#include - -NetworkingSP::NetworkingSP(QWidget *parent) : Networking(parent) { - auto vlayout = wifiScreen->findChild(); - auto hlayout = new QHBoxLayout(); - - // Create and setup scan button - auto scanButton = new QPushButton(tr("Scan")); - scanButton->setObjectName("scan_btn"); - scanButton->setFixedSize(400, 100); - - connect(wifi, &WifiManager::refreshSignal, this, [=]() { scanButton->setText(tr("Scan")); scanButton->setEnabled(true); }); - connect(scanButton, &QPushButton::clicked, [=]() { scanButton->setText(tr("Scanning...")); scanButton->setEnabled(false); wifi->requestScan(); }); - - hlayout->addWidget(scanButton); - hlayout->addStretch(1); - - // Look for an existing Advanced button - QPushButton* existingAdvanced = wifiScreen->findChild("advanced_btn"); - if (existingAdvanced) { - hlayout->addWidget(existingAdvanced); - } - - // Insert our new layout at the top of vlayout - vlayout->setMargin(40); - vlayout->insertLayout(0, hlayout); - - // Add our scan button to the existing style selectors - auto newStyleSheet = styleSheet().replace( - ", #advanced_btn ", - ", #advanced_btn, #scan_btn " - ).replace( - ", #advanced_btn:pressed", - ", #advanced_btn:pressed, #scan_btn:pressed" - ).append(R"( - #scan_btn:disabled { - background-color: #121212; - color: #33FFFFFF; - } - )"); - setStyleSheet(newStyleSheet); -} diff --git a/selfdrive/ui/sunnypilot/qt/network/networking.h b/selfdrive/ui/sunnypilot/qt/network/networking.h deleted file mode 100644 index f220b8a50a..0000000000 --- a/selfdrive/ui/sunnypilot/qt/network/networking.h +++ /dev/null @@ -1,17 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once -#include "selfdrive/ui/qt/network/networking.h" - - -class NetworkingSP : public Networking { - Q_OBJECT - -public: - explicit NetworkingSP(QWidget *parent = nullptr); -}; diff --git a/selfdrive/ui/sunnypilot/qt/network/sunnylink/models/role_model.h b/selfdrive/ui/sunnypilot/qt/network/sunnylink/models/role_model.h deleted file mode 100644 index 04b4dccf14..0000000000 --- a/selfdrive/ui/sunnypilot/qt/network/sunnylink/models/role_model.h +++ /dev/null @@ -1,56 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include - -enum class RoleType { - ReadOnly, - Sponsor, - Admin -}; - -// haha, a role model xD -class RoleModel { -protected: - QJsonObject m_raw_json_object; - -public: - RoleType roleType; - - explicit RoleModel(const RoleType &roleType) : roleType(roleType) { m_raw_json_object = toJson(); } - explicit RoleModel(const QJsonObject &json) : RoleModel(stringToRoleType(json["role_type"].toString())) { m_raw_json_object = json; } - - [[nodiscard]] QJsonObject toJson() const { - QJsonObject json; - json["role_type"] = roleTypeToString(roleType); - return json; - } - - static RoleType stringToRoleType(const QString &roleTypeString) { - if (roleTypeString == "ReadOnly") return RoleType::ReadOnly; - if (roleTypeString == "Sponsor") return RoleType::Sponsor; - - return RoleType::Admin; // Default to Admin - } - - static QString roleTypeToString(const RoleType &roleType) { - switch (roleType) { - case RoleType::ReadOnly: - return "ReadOnly"; - case RoleType::Sponsor: - return "Sponsor"; - default: // RoleType::Admin - return "Admin"; - } - } - - template ::value>::type> T as() const { - return T(m_raw_json_object); - } -}; diff --git a/selfdrive/ui/sunnypilot/qt/network/sunnylink/models/sponsor_role_model.h b/selfdrive/ui/sunnypilot/qt/network/sunnylink/models/sponsor_role_model.h deleted file mode 100644 index 7e1772b591..0000000000 --- a/selfdrive/ui/sunnypilot/qt/network/sunnylink/models/sponsor_role_model.h +++ /dev/null @@ -1,83 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include - -enum class SponsorTier { - Free, - Novice, - Supporter, - Contributor, - Benefactor, - Guardian, -}; - -// haha, a role model xD -class SponsorRoleModel final : RoleModel { -public: - SponsorTier roleTier; - - explicit SponsorRoleModel(const RoleType &roleType, const SponsorTier &roleTier) : RoleModel(roleType), roleTier(roleTier) {} - explicit SponsorRoleModel(const QJsonObject &json) : RoleModel(json), roleTier(stringToSponsorTier(json["role_tier"].toString())) {} - - [[nodiscard]] QJsonObject toJson() const { - QJsonObject json = RoleModel::toJson(); - json["role_tier"] = sponsorTierToString(roleTier); - return json; - } - - static SponsorTier stringToSponsorTier(const QString &sponsorTierString) { - const auto sponsorTierStringLower = sponsorTierString.toLower(); - if (sponsorTierStringLower == "guardian") return SponsorTier::Guardian; - if (sponsorTierStringLower == "novice") return SponsorTier::Novice; - if (sponsorTierStringLower == "supporter") return SponsorTier::Supporter; - if (sponsorTierStringLower == "contributor") return SponsorTier::Contributor; - if (sponsorTierStringLower == "benefactor") return SponsorTier::Benefactor; - - // Default to Free - return SponsorTier::Free; - } - - static QString sponsorTierToString(const SponsorTier &sponsorTier) { - switch (sponsorTier) { - case SponsorTier::Guardian: - return "Guardian"; - case SponsorTier::Novice: - return "Novice"; - case SponsorTier::Supporter: - return "Supporter"; - case SponsorTier::Contributor: - return "Contributor"; - case SponsorTier::Benefactor: - return "Benefactor"; - - default: // SponsorTier::Free - return "Free"; - } - } - [[nodiscard]] auto getSponsorTierString() const { return sponsorTierToString(roleTier); } - - static QString sponsorTierToColor(const SponsorTier &sponsorTier) { - switch (sponsorTier) { - case SponsorTier::Guardian: - return "gold"; - case SponsorTier::Benefactor: - return "mediumseagreen"; - case SponsorTier::Contributor: - return "steelblue"; - case SponsorTier::Supporter: - return "mediumpurple"; - case SponsorTier::Novice: - return "white"; - default: // SponsorTier::Free - return "silver"; - } - } - [[nodiscard]] auto getSponsorTierColor() const { return sponsorTierToColor(roleTier); } -}; diff --git a/selfdrive/ui/sunnypilot/qt/network/sunnylink/models/user_model.h b/selfdrive/ui/sunnypilot/qt/network/sunnylink/models/user_model.h deleted file mode 100644 index 4d255ac8e3..0000000000 --- a/selfdrive/ui/sunnypilot/qt/network/sunnylink/models/user_model.h +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include - -class UserModel { -public: - QString device_id; - QString user_id; - qint64 created_at; - qint64 updated_at; - QString token_hash; - - explicit UserModel(const QJsonObject &json) { - device_id = json["device_id"].toString(); - user_id = json["user_id"].toString(); - created_at = json["created_at"].toInt(); - updated_at = json["updated_at"].toInt(); - token_hash = json["token_hash"].toString(); - } - - [[nodiscard]] QJsonObject toJson() const { - QJsonObject json; - json["device_id"] = device_id; - json["user_id"] = user_id; - json["created_at"] = created_at; - json["updated_at"] = updated_at; - json["token_hash"] = token_hash; - return json; - } -}; diff --git a/selfdrive/ui/sunnypilot/qt/network/sunnylink/services/base_device_service.cc b/selfdrive/ui/sunnypilot/qt/network/sunnylink/services/base_device_service.cc deleted file mode 100644 index 3919a1821f..0000000000 --- a/selfdrive/ui/sunnypilot/qt/network/sunnylink/services/base_device_service.cc +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/network/sunnylink//services/base_device_service.h" - -#include "selfdrive/ui/sunnypilot/qt/request_repeater.h" - -#include "common/swaglog.h" -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/sunnylink_panel.h" - -BaseDeviceService::BaseDeviceService(QObject* parent) : QObject(parent) { - param_watcher = new ParamWatcher(this); - connect(param_watcher, &ParamWatcher::paramChanged, [=](const QString ¶m_name, const QString ¶m_value) { - paramsRefresh(); - }); - param_watcher->addParam("SunnylinkEnabled"); -} - -void BaseDeviceService::paramsRefresh() { -} - -void BaseDeviceService::loadDeviceData(const QString &url, bool poll) { - if (!is_sunnylink_enabled()) { - LOGW("Sunnylink is not enabled, refusing to load data."); - return; - } - - auto sl_dongle_id = getSunnylinkDongleId(); - if (!sl_dongle_id.has_value()) - return; - - QString fullUrl = SUNNYLINK_BASE_URL + "/device/" + *sl_dongle_id + url; - if (poll && !isCurrentyPolling()) { - LOGD("Polling %s", qPrintable(fullUrl)); - LOGD("Cache key: SunnylinkCache_%s", qPrintable(QString(getCacheKey()))); - repeater = new RequestRepeaterSP(this, fullUrl, "SunnylinkCache_" + getCacheKey(), 60, false, true); - connect(repeater, &RequestRepeaterSP::requestDone, this, &BaseDeviceService::handleResponse); - } else if (isCurrentyPolling()) { - repeater->ForceUpdate(); - } else { - LOGD("Sending one-time %s", qPrintable(fullUrl)); - initial_request = new HttpRequestSP(this, true, 10000, true); - connect(initial_request, &HttpRequestSP::requestDone, this, &BaseDeviceService::handleResponse); - } -} - -void BaseDeviceService::stopPolling() { - if (repeater != nullptr) { - repeater->deleteLater(); - repeater = nullptr; - } -} diff --git a/selfdrive/ui/sunnypilot/qt/network/sunnylink/services/base_device_service.h b/selfdrive/ui/sunnypilot/qt/network/sunnylink/services/base_device_service.h deleted file mode 100644 index 8ef99d1013..0000000000 --- a/selfdrive/ui/sunnypilot/qt/network/sunnylink/services/base_device_service.h +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/sunnypilot/qt/request_repeater.h" -#include "selfdrive/ui/qt/util.h" - -class BaseDeviceService : public QObject { - Q_OBJECT - -protected: - void paramsRefresh(); - void loadDeviceData(const QString &url, bool poll = false); - virtual void handleResponse(const QString &response, bool success) = 0; - - static bool is_sunnylink_enabled() { return Params().getBool("SunnylinkEnabled");} - ParamWatcher* param_watcher; - HttpRequestSP* initial_request = nullptr; - RequestRepeaterSP* repeater = nullptr; - -public: - explicit BaseDeviceService(QObject* parent = nullptr); - virtual QString getCacheKey() const = 0; - bool isCurrentyPolling() {return repeater != nullptr;} - void stopPolling(); -}; diff --git a/selfdrive/ui/sunnypilot/qt/network/sunnylink/services/role_service.cc b/selfdrive/ui/sunnypilot/qt/network/sunnylink/services/role_service.cc deleted file mode 100644 index bffe32839f..0000000000 --- a/selfdrive/ui/sunnypilot/qt/network/sunnylink/services/role_service.cc +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/network/sunnylink/services/role_service.h" - -#include -#include - -RoleService::RoleService(QObject* parent) : BaseDeviceService(parent) {} - -void RoleService::load() { - loadDeviceData(url); -} - -void RoleService::startPolling() { - loadDeviceData(url, true); -} - -void RoleService::handleResponse(const QString &response, bool success) { - if (!success) return; - - QJsonDocument doc = QJsonDocument::fromJson(response.toUtf8()); - QJsonArray jsonArray = doc.array(); - - std::vector roles; - for (const auto &value : jsonArray) { - roles.emplace_back(value.toObject()); - } - - emit rolesReady(roles); - uiStateSP()->setSunnylinkRoles(roles); -} diff --git a/selfdrive/ui/sunnypilot/qt/network/sunnylink/services/role_service.h b/selfdrive/ui/sunnypilot/qt/network/sunnylink/services/role_service.h deleted file mode 100644 index abd0e1ab83..0000000000 --- a/selfdrive/ui/sunnypilot/qt/network/sunnylink/services/role_service.h +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include - -#include "selfdrive/ui/sunnypilot/qt/network/sunnylink/services/base_device_service.h" -#include "selfdrive/ui/sunnypilot/qt/network/sunnylink/models/role_model.h" - -class RoleService : public BaseDeviceService { - Q_OBJECT - -public: - explicit RoleService(QObject* parent = nullptr); - void load(); - void startPolling(); - [[nodiscard]] QString getCacheKey() const final { return "Roles"; } - -signals: - void rolesReady(const std::vector &roles); - -protected: - void handleResponse(const QString&response, bool success) override; - -private: - QString url = "/roles"; -}; diff --git a/selfdrive/ui/sunnypilot/qt/network/sunnylink/services/user_service.cc b/selfdrive/ui/sunnypilot/qt/network/sunnylink/services/user_service.cc deleted file mode 100644 index cd16360c26..0000000000 --- a/selfdrive/ui/sunnypilot/qt/network/sunnylink/services/user_service.cc +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/network/sunnylink/services/user_service.h" - -#include -#include - -#include "selfdrive/ui/sunnypilot/ui.h" - -UserService::UserService(QObject* parent) : BaseDeviceService(parent) { - url = "/users"; -} - -void UserService::load() { - loadDeviceData(url); -} - -void UserService::startPolling() { - loadDeviceData(url, true); -} - -void UserService::handleResponse(const QString &response, bool success) { - if (!success) { - return; - } - - QJsonDocument doc = QJsonDocument::fromJson(response.toUtf8()); - QJsonArray jsonArray = doc.array(); - - std::vector users; - for (const auto &value : jsonArray) { - users.emplace_back(value.toObject()); - } - - emit usersReady(users); - uiStateSP()->setSunnylinkDeviceUsers(users); -} diff --git a/selfdrive/ui/sunnypilot/qt/network/sunnylink/services/user_service.h b/selfdrive/ui/sunnypilot/qt/network/sunnylink/services/user_service.h deleted file mode 100644 index 90eb354751..0000000000 --- a/selfdrive/ui/sunnypilot/qt/network/sunnylink/services/user_service.h +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include - -#include "selfdrive/ui/sunnypilot/qt/network/sunnylink/services/base_device_service.h" -#include "selfdrive/ui/sunnypilot/qt/network/sunnylink/models/user_model.h" - -class UserService : public BaseDeviceService { - Q_OBJECT - -public: - explicit UserService(QObject* parent = nullptr); - void load(); - void startPolling(); - [[nodiscard]] QString getCacheKey() const final { return "Users"; }; - -signals: - void usersReady(const std::vector&users); - -protected: - void handleResponse(const QString&response, bool success) override; - -private: - QString url = "/users"; -}; diff --git a/selfdrive/ui/sunnypilot/qt/network/sunnylink/sunnylink_client.cc b/selfdrive/ui/sunnypilot/qt/network/sunnylink/sunnylink_client.cc deleted file mode 100644 index 4428eb55c4..0000000000 --- a/selfdrive/ui/sunnypilot/qt/network/sunnylink/sunnylink_client.cc +++ /dev/null @@ -1,14 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/network/sunnylink/sunnylink_client.h" -#include "selfdrive/ui/sunnypilot/qt/network/sunnylink/services/user_service.h" - -SunnylinkClient::SunnylinkClient(QObject* parent) : QObject(parent) { - role_service = new RoleService(parent); - user_service = new UserService(parent); -} diff --git a/selfdrive/ui/sunnypilot/qt/network/sunnylink/sunnylink_client.h b/selfdrive/ui/sunnypilot/qt/network/sunnylink/sunnylink_client.h deleted file mode 100644 index 0961449926..0000000000 --- a/selfdrive/ui/sunnypilot/qt/network/sunnylink/sunnylink_client.h +++ /dev/null @@ -1,22 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include - -#include "selfdrive/ui/sunnypilot/qt/network/sunnylink/services/role_service.h" -#include "selfdrive/ui/sunnypilot/qt/network/sunnylink/services/user_service.h" - -class SunnylinkClient : public QObject { - Q_OBJECT - -public: - explicit SunnylinkClient(QObject* parent); - RoleService* role_service; - UserService* user_service; -}; diff --git a/selfdrive/ui/sunnypilot/qt/offroad/exit_offroad_button.cc b/selfdrive/ui/sunnypilot/qt/offroad/exit_offroad_button.cc deleted file mode 100644 index 0c7902476a..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/exit_offroad_button.cc +++ /dev/null @@ -1,100 +0,0 @@ -#include -#include -#include -#include -#include - -#include "selfdrive/ui/ui.h" -#include "selfdrive/ui/qt/widgets/input.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/exit_offroad_button.h" - - -ExitOffroadButton::ExitOffroadButton(QWidget *parent) : QPushButton(parent), glowTimer(new QTimer(this)) { - setMouseTracking(true); - - connect(glowTimer, &QTimer::timeout, this, [this]() { - // Pulse alpha up and down - glowAlpha += glowDelta; - if (glowAlpha > 220 || glowAlpha < 10) { - glowDelta *= -1; - } - update(); // trigger repaint - }); - - glowTimer->start(45); - - pixmap = QPixmap("../../sunnypilot/selfdrive/assets/offroad/icon_exit_offroad.png").scaledToWidth(img_width, Qt::SmoothTransformation); - - // go to toggles and expand experimental mode description - connect(this, &QPushButton::clicked, [=]() { - if (ConfirmationDialog::confirm(tr("Are you sure you want to exit Always Offroad mode?"), tr("Confirm"), this)) { - params.remove("OffroadMode"); - } - }); - - setFixedHeight(125); - QHBoxLayout *main_layout = new QHBoxLayout; - main_layout->setContentsMargins(horizontal_padding, 0, horizontal_padding, 0); - - mode_label = new QLabel(tr("EXIT ALWAYS OFFROAD MODE")); - mode_icon = new QLabel; - mode_icon->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); - mode_icon->setPixmap(pixmap); - - main_layout->addWidget(mode_label, 1, Qt::AlignLeft); - main_layout->addWidget(mode_icon, 0, Qt::AlignRight); - - setLayout(main_layout); - - setStyleSheet(R"( - QPushButton { - border: none; - } - - QLabel { - font-size: 45px; - font-weight: 300; - text-align: left; - font-family: JetBrainsMono; - color: #000000; - } - )"); -} - -void drawPulsingGlowOverlay(QPainter &p, QPainterPath path, int glowAlpha) { - // Draw pulsing glow effect clipped to button area - p.save(); - p.setClipPath(path); - p.setCompositionMode(QPainter::CompositionMode_HardLight); - - const QColor animatedGlowColor(255, 255, 255, std::min(255, glowAlpha)); - QPen glowPen(animatedGlowColor, 8); - glowPen.setJoinStyle(Qt::RoundJoin); - p.setPen(glowPen); - p.drawPath(path); - - p.restore(); -} - -void ExitOffroadButton::paintEvent(QPaintEvent *event) { - QPainter p(this); - p.setRenderHint(QPainter::Antialiasing); - - QPainterPath path; - path.addRoundedRect(rect(), 10, 10); - - // gradient - bool pressed = isDown(); - QLinearGradient gradient(rect().left(), 0, rect().right(), 0); - gradient.setColorAt(0, QColor(35, 149, 255, pressed ? 0xcc : 0xff)); - gradient.setColorAt(0.3, QColor(35, 149, 255, pressed ? 0xcc : 0xff)); - gradient.setColorAt(1, QColor(20, 255, 171, pressed ? 0xcc : 0xff)); - p.fillPath(path, gradient); - - drawPulsingGlowOverlay(p, path, glowAlpha); - - // vertical line - p.setPen(QPen(QColor(0, 0, 0, 0x4d), 3, Qt::SolidLine)); - int line_x = rect().right() - img_width - (2 * horizontal_padding); - p.drawLine(line_x, rect().bottom(), line_x, rect().top()); -} diff --git a/selfdrive/ui/sunnypilot/qt/offroad/exit_offroad_button.h b/selfdrive/ui/sunnypilot/qt/offroad/exit_offroad_button.h deleted file mode 100644 index 673d9fff73..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/exit_offroad_button.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include -#include - -#include "common/params.h" - -class ExitOffroadButton : public QPushButton { - Q_OBJECT - -private: - QTimer *glowTimer; - int glowAlpha = 100; // Current alpha of glow - int glowDelta = 10; // Change per tick - -public: - explicit ExitOffroadButton(QWidget* parent = 0); - - Params params; - bool offroad_mode; - int img_width = 100; - int horizontal_padding = 30; - QPixmap pixmap; - QLabel *mode_label; - QLabel *mode_icon; - -protected: - void paintEvent(QPaintEvent *event) override; -}; diff --git a/selfdrive/ui/sunnypilot/qt/offroad/offroad_home.cc b/selfdrive/ui/sunnypilot/qt/offroad/offroad_home.cc deleted file mode 100644 index cc82e6ddb9..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/offroad_home.cc +++ /dev/null @@ -1,49 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include - -#include "selfdrive/ui/sunnypilot/qt/offroad/offroad_home.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/drive_stats.h" - -OffroadHomeSP::OffroadHomeSP(QWidget *parent) : OffroadHome(parent) { - QFrame *left_widget = new QFrame(this); - QVBoxLayout *left_layout = new QVBoxLayout(left_widget); - left_layout->setContentsMargins(0, 0, 0, 0); - left_layout->setSpacing(30); - - btn_exit_offroad = new ExitOffroadButton(this); - QObject::connect(btn_exit_offroad, &ExitOffroadButton::clicked, [=]() { - refreshOffroadStatus(); - }); - left_layout->addWidget(btn_exit_offroad); - - left_layout->addWidget(new DriveStats(this)); - left_widget->setStyleSheet("border-radius: 10px;"); - - home_layout->insertWidget(0, left_widget); - - offroad_notif = new QPushButton(tr("ALWAYS OFFROAD ACTIVE")); - offroad_notif->setVisible(false); - offroad_notif->setStyleSheet("background-color: #E22C2C;"); - header_layout->insertWidget(0, offroad_notif, 0, Qt::AlignHCenter | Qt::AlignLeft); - - QObject::connect(deviceSP(), &DeviceSP::displayPowerChanged, this, &OffroadHomeSP::refreshOffroadStatus); - -} - -void OffroadHomeSP::showEvent(QShowEvent *event) { - refreshOffroadStatus(); - OffroadHome::showEvent(event); -} - -void OffroadHomeSP::refreshOffroadStatus() { - bool is_offroad = params.getBool("OffroadMode"); - btn_exit_offroad->setVisible(is_offroad); - offroad_notif->setVisible(is_offroad); - OffroadHome::refresh(); -} diff --git a/selfdrive/ui/sunnypilot/qt/offroad/offroad_home.h b/selfdrive/ui/sunnypilot/qt/offroad/offroad_home.h deleted file mode 100644 index 30816f666c..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/offroad_home.h +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/qt/offroad/offroad_home.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/exit_offroad_button.h" - -class OffroadHomeSP : public OffroadHome { - Q_OBJECT - -public: - explicit OffroadHomeSP(QWidget *parent = 0); - -private: - ExitOffroadButton *btn_exit_offroad; - QPushButton *offroad_notif; - Params params; - - void showEvent(QShowEvent *event) override; - void refreshOffroadStatus(); -}; diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/brightness.cc b/selfdrive/ui/sunnypilot/qt/offroad/settings/brightness.cc deleted file mode 100644 index ffd3ce1d8b..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/brightness.cc +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/brightness.h" - -// Map of Brightness Options -const QMap Brightness::brightness_options = { - {"0", "1"}, // Auto (Dark) - {"1", "0"}, // Auto - {"2", "10"}, - {"3", "20"}, - {"4", "30"}, - {"5", "40"}, - {"6", "50"}, - {"7", "60"}, - {"8", "70"}, - {"9", "80"}, - {"10", "90"}, - {"11", "100"} -}; - -Brightness::Brightness() : OptionControlSP( - "Brightness", - tr("Brightness"), - tr("Overrides the brightness of the device."), - "../assets/offroad/icon_blank.png", - {0, 11}, 1, true, &brightness_options) { - - refresh(); -} - -void Brightness::refresh() { - const int brightness = QString::fromStdString(params.get("Brightness")).toInt(); - - QString label; - if (brightness == 1) { - label = tr("Auto (Dark)"); - } else if (brightness == 0) { - label = tr("Auto"); - } else { - const int value = brightness; - label = QString("%1").arg(value); - } - - setLabel(label); -} diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/brightness.h b/selfdrive/ui/sunnypilot/qt/offroad/settings/brightness.h deleted file mode 100644 index 20d0a291d9..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/brightness.h +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/sunnypilot/ui.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/settings.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/controls.h" - -class Brightness : public OptionControlSP { - Q_OBJECT - -public: - static const QMap brightness_options; - - Brightness(); - void refresh(); - -private: - Params params; -}; diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/device_panel.cc b/selfdrive/ui/sunnypilot/qt/offroad/settings/device_panel.cc deleted file mode 100644 index b89116d424..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/device_panel.cc +++ /dev/null @@ -1,201 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/device_panel.h" - -#include "common/watchdog.h" -#include "selfdrive/ui/qt/qt_window.h" - -DevicePanelSP::DevicePanelSP(SettingsWindowSP *parent) : DevicePanel(parent) { - QGridLayout *device_grid_layout = new QGridLayout(); - device_grid_layout->setSpacing(30); - device_grid_layout->setHorizontalSpacing(5); - device_grid_layout->setVerticalSpacing(25); - - std::vector> device_btns = { - {"quietModeBtn", tr("Quiet Mode"), "QuietMode"}, - {"dcamBtn", tr("Driver Camera Preview"), ""}, - {"retrainingBtn", tr("Training Guide"), ""}, - {"regulatoryBtn", tr("Regulatory"), ""}, - {"translateBtn", tr("Language"), ""}, - {"resetParams", tr("Reset Settings"), ""}, - }; - - int row = 0, col = 0; - for (const auto &[id, text, param] : device_btns) { - if (id == "regulatoryBtn" && !Hardware::TICI()) { - continue; - } - - auto *btn = new PushButtonSP(text, 750, this, param); - btn->setObjectName(id); - buttons[id] = btn; - - if (col==0) { - device_grid_layout->addWidget(btn, row, col, Qt::AlignLeft); - col++; - } else { - device_grid_layout->addWidget(btn, row, col, Qt::AlignRight); - col=0; - row++; - } - } - - connect(buttons["dcamBtn"], &PushButtonSP::clicked, [=]() { emit showDriverView(); }); - - connect(buttons["quietModeBtn"], &PushButtonSP::clicked, buttons["quietModeBtn"], &PushButtonSP::updateButton); - - connect(buttons["retrainingBtn"], &PushButtonSP::clicked, [=]() { - if (ConfirmationDialog::confirm(tr("Are you sure you want to review the training guide?"), tr("Review"), this)) { - emit reviewTrainingGuide(); - } - }); - - if (Hardware::TICI()) { - connect(buttons["regulatoryBtn"], &PushButtonSP::clicked, [=]() { - const std::string txt = util::read_file("../assets/offroad/fcc.html"); - ConfirmationDialog::rich(QString::fromStdString(txt), this); - }); - } - - connect(buttons["translateBtn"], &PushButtonSP::clicked, [=]() { - QMap langs = getSupportedLanguages(); - QString selection = MultiOptionDialog::getSelection(tr("Select a language"), langs.keys(), langs.key(uiState()->language), this); - if (!selection.isEmpty()) { - // put language setting, exit Qt UI, and trigger fast restart - params.put("LanguageSetting", langs[selection].toStdString()); - qApp->exit(18); - watchdog_kick(0); - } - }); - - connect(buttons["resetParams"], &PushButtonSP::clicked, this, &DevicePanelSP::resetSettings); - - // Max Time Offroad - maxTimeOffroad = new MaxTimeOffroad(); - connect(maxTimeOffroad, &OptionControlSP::updateLabels, maxTimeOffroad, &MaxTimeOffroad::refresh); - addItem(maxTimeOffroad); - - toggleDeviceBootMode = new ButtonParamControlSP("DeviceBootMode", tr("Wake-Up Behavior"), "", "", {"Default", "Offroad"}, 375, true); - addItem(toggleDeviceBootMode); - - connect(toggleDeviceBootMode, &ButtonParamControlSP::buttonClicked, this, [=](int index) { - params.put("DeviceBootMode", QString::number(index).toStdString()); - updateState(); - }); - - // Brightness - brightness = new Brightness(); - connect(brightness, &OptionControlSP::updateLabels, brightness, &Brightness::refresh); - addItem(brightness); - - addItem(device_grid_layout); - - // offroad mode and power buttons - - QHBoxLayout *power_layout = new QHBoxLayout(); - power_layout->setSpacing(25); - - PushButtonSP *rebootBtn = new PushButtonSP(tr("Reboot"), 750, this); - rebootBtn->setStyleSheet(rebootButtonStyle); - power_layout->addWidget(rebootBtn); - QObject::connect(rebootBtn, &PushButtonSP::clicked, this, &DevicePanelSP::reboot); - - PushButtonSP *poweroffBtn = new PushButtonSP(tr("Power Off"), 750, this); - poweroffBtn->setStyleSheet(powerOffButtonStyle); - power_layout->addWidget(poweroffBtn); - QObject::connect(poweroffBtn, &PushButtonSP::clicked, this, &DevicePanelSP::poweroff); - - if (!Hardware::PC()) { - connect(uiState(), &UIState::offroadTransition, poweroffBtn, &PushButtonSP::setVisible); - } - - offroadBtn = new PushButtonSP(tr("Offroad Mode")); - offroadBtn->setFixedWidth(power_layout->sizeHint().width()); - QObject::connect(offroadBtn, &PushButtonSP::clicked, this, &DevicePanelSP::setOffroadMode); - - QVBoxLayout *power_group_layout = new QVBoxLayout(); - power_group_layout->setSpacing(25); - power_group_layout->addWidget(offroadBtn, 0, Qt::AlignHCenter); - power_group_layout->addLayout(power_layout); - - addItem(power_group_layout); - - std::vector always_enabled_btns = { - rebootBtn, - poweroffBtn, - offroadBtn, - buttons["quietModeBtn"], - }; - - QObject::connect(uiState(), &UIState::offroadTransition, [=](bool offroad) { - for (auto btn : findChildren()) { - bool always_enabled = std::find(always_enabled_btns.begin(), always_enabled_btns.end(), btn) != always_enabled_btns.end(); - - if (!always_enabled) { - btn->setEnabled(offroad); - } - } - }); -} - -void DevicePanelSP::setOffroadMode() { - if (!uiState()->engaged()) { - if (params.getBool("OffroadMode")) { - if (ConfirmationDialog::confirm(tr("Are you sure you want to exit Always Offroad mode?"), tr("Confirm"), this)) { - // Check engaged again in case it changed while the dialog was open - if (!uiState()->engaged()) { - params.remove("OffroadMode"); - } - } - } else { - if (ConfirmationDialog::confirm(tr("Are you sure you want to enter Always Offroad mode?"), tr("Confirm"), this)) { - // Check engaged again in case it changed while the dialog was open - if (!uiState()->engaged()) { - params.putBool("OffroadMode", true); - } - } - } - } else { - ConfirmationDialog::alert(tr("Disengage to Enter Always Offroad Mode"), this); - } - - updateState(); -} - -void DevicePanelSP::resetSettings() { - if (ConfirmationDialog::confirm(tr("Are you sure you want to reset all sunnypilot settings to default? Once the settings are reset, there is no going back."), tr("Reset"), this)) { - if (ConfirmationDialog::confirm(tr("The reset cannot be undone. You have been warned."), tr("Confirm"), this)) { - const std::vector keys = params.allKeys(); - for (const auto& key : keys) { - params.remove(key); - } - - Hardware::reboot(); - } - } -} - -void DevicePanelSP::showEvent(QShowEvent *event) { - updateState(); -} - -void DevicePanelSP::updateState() { - if (!isVisible()) { - return; - } - - bool offroad_mode_param = params.getBool("OffroadMode"); - offroadBtn->setText(offroad_mode_param ? tr("Exit Always Offroad") : tr("Always Offroad")); - offroadBtn->setStyleSheet(offroad_mode_param ? alwaysOffroadStyle : autoOffroadStyle); - - DeviceSleepModeStatus currStatus = DeviceSleepModeStatus::DEFAULT; - if (params.get("DeviceBootMode") == "1") { - currStatus = DeviceSleepModeStatus::OFFROAD; - } - toggleDeviceBootMode->setDescription(deviceSleepModeDescription(currStatus)); -} diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/device_panel.h b/selfdrive/ui/sunnypilot/qt/offroad/settings/device_panel.h deleted file mode 100644 index 2cd3281d1f..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/device_panel.h +++ /dev/null @@ -1,112 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/max_time_offroad.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/brightness.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/settings.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/controls.h" - -enum class DeviceSleepModeStatus { - DEFAULT, - OFFROAD, -}; - -class DevicePanelSP : public DevicePanel { - Q_OBJECT - -public: - explicit DevicePanelSP(SettingsWindowSP *parent = 0); - void showEvent(QShowEvent *event) override; - void setOffroadMode(); - void updateState(); - void resetSettings(); - -private: - std::map buttons; - PushButtonSP *offroadBtn; - MaxTimeOffroad *maxTimeOffroad; - ButtonParamControlSP *toggleDeviceBootMode; - Brightness *brightness; - - const QString alwaysOffroadStyle = R"( - PushButtonSP { - border-radius: 20px; - font-size: 50px; - font-weight: 450; - height: 150px; - padding: 0 25px 0 25px; - color: #FFFFFF; - background-color: #393939; - } - PushButtonSP:pressed { - background-color: #4A4A4A; - } - )"; - - const QString autoOffroadStyle = R"( - PushButtonSP { - border-radius: 20px; - font-size: 50px; - font-weight: 450; - height: 150px; - padding: 0 25px 0 25px; - color: #FFFFFF; - background-color: #E22C2C; - } - PushButtonSP:pressed { - background-color: #FF2424; - } - )"; - - const QString rebootButtonStyle = R"( - PushButtonSP { - border-radius: 20px; - font-size: 50px; - font-weight: 450; - height: 150px; - padding: 0 25px 0 25px; - color: #FFFFFF; - background-color: #393939; - } - PushButtonSP:pressed { - background-color: #4A4A4A; - } - )"; - - const QString powerOffButtonStyle = R"( - PushButtonSP { - border-radius: 20px; - font-size: 50px; - font-weight: 450; - height: 150px; - padding: 0 25px 0 25px; - color: #FFFFFF; - background-color: #E22C2C; - } - PushButtonSP:pressed { - background-color: #FF2424; - } - )"; - - static QString deviceSleepModeDescription(DeviceSleepModeStatus status = DeviceSleepModeStatus::DEFAULT) { - QString def_str = tr("⁍ Default: Device will boot/wake-up normally & will be ready to engage."); - QString offrd_str = tr("⁍ Offroad: Device will be in Always Offroad mode after boot/wake-up."); - - if (status == DeviceSleepModeStatus::DEFAULT) { - def_str = "" + def_str + ""; - } else if (status == DeviceSleepModeStatus::OFFROAD) { - offrd_str = "" + offrd_str + ""; - } - - return QString("%1

%2
%3") - .arg(tr("Controls state of the device after boot/sleep.")) - .arg(def_str) - .arg(offrd_str); - } -}; diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/lateral/angle_tuning_settings.cc b/selfdrive/ui/sunnypilot/qt/offroad/settings/lateral/angle_tuning_settings.cc deleted file mode 100644 index 55b39717ba..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/lateral/angle_tuning_settings.cc +++ /dev/null @@ -1,87 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/lateral/angle_tuning_settings.h" - -#include "selfdrive/ui/sunnypilot/qt/widgets/scrollview.h" - -AngleTunningSettings::AngleTunningSettings(QWidget *parent) : QWidget(parent) { - QVBoxLayout *main_layout = new QVBoxLayout(this); - main_layout->setContentsMargins(50, 20, 50, 20); - main_layout->setSpacing(20); - - // Back button - PanelBackButton *back = new PanelBackButton(); - connect(back, &QPushButton::clicked, [=]() { emit backPress(); }); - main_layout->addWidget(back, 0, Qt::AlignLeft); - - auto *list = new ListWidgetSP(this, false); - - main_layout->addWidget(new QWidget()); - - enableHkgAngleSmoothingFactor = new ExpandableToggleRow("EnableHkgTuningAngleSmoothingFactor", tr("HKG Angle Smoothing Factor"), tr("Applies EMA (Exponential Moving Average) to the desired angle steering and avoid overcorrections."), "../assets/offroad/icon_blank.png"); - list->addItem(enableHkgAngleSmoothingFactor); - - auto first_row = new QHBoxLayout(); - hkgTuningOverridingCycles = new OptionControlSP("HkgTuningOverridingCycles", tr("Override Ramp-Down Cycles"), tr("Number of cycles to ramp down the current amount of torque on the steering wheel.
A smaller value means a faster override by the user (less effort)"), "../assets/offroad/icon_blank.png", {10, 30}, 1); - connect(hkgTuningOverridingCycles, &OptionControlSP::updateLabels, hkgTuningOverridingCycles, [=]() { - this->updateToggles(offroad); - }); - first_row->addWidget(hkgTuningOverridingCycles); - - hkgAngleMinTorque = new OptionControlSP("HkgTuningAngleMinTorqueReductionGain", tr("Override Steering Effort"), tr("Sets the steering effort percentage used when the driver is overriding lateral control.
Higher values increase resistance and make the wheel feel stiffer."), "../assets/offroad/icon_blank.png", {5, 60}, 1); - connect(hkgAngleMinTorque, &OptionControlSP::updateLabels, hkgAngleMinTorque, [=]() { - this->updateToggles(offroad); - }); - first_row->addWidget(hkgAngleMinTorque); - list->addItem(first_row); - - auto second_row = new QHBoxLayout(); - hkgAngleActiveTorque = new OptionControlSP("HkgTuningAngleActiveTorqueReductionGain", tr("Min Active Torque"), tr("Torque applied when lateral control is active but the vehicle is not turning.
Used to maintain lane centering on straight paths when no user input is detected."), "../assets/offroad/icon_blank.png", {10, 100}, 1); - connect(hkgAngleActiveTorque, &OptionControlSP::updateLabels, hkgAngleActiveTorque, [=]() { - this->updateToggles(offroad); - }); - second_row->addWidget(hkgAngleActiveTorque); - - hkgAngleMaxTorque = new OptionControlSP("HkgTuningAngleMaxTorqueReductionGain", tr("Max Torque Allowance"), tr("Sets the maximum torque reduction percentage the controller can apply during normal lateral control.
"), "../assets/offroad/icon_blank.png", {10, 100}, 1); - connect(hkgAngleMaxTorque, &OptionControlSP::updateLabels, hkgAngleMaxTorque, [=]() { - this->updateToggles(offroad); - }); - second_row->addWidget(hkgAngleMaxTorque); - list->addItem(second_row); - - QObject::connect(uiState(), &UIState::offroadTransition, this, &AngleTunningSettings::updateToggles); - - main_layout->addWidget(new ScrollViewSP(list, this)); - - auto *warning = new QLabel(tr("Reboot required for settings to apply; Tap on each setting to see more details.")); - warning->setStyleSheet("font-size: 30px; font-weight: 500; font-family: 'Noto Color Emoji'; color: orange;"); - main_layout->addWidget(warning, 0, Qt::AlignCenter); -} - -void AngleTunningSettings::showEvent(QShowEvent *event) { - updateToggles(offroad); -} - -void AngleTunningSettings::updateToggles(bool _offroad) { - auto HkgAngleSmoothingFactorValue = params.getBool("EnableHkgTuningAngleSmoothingFactor"); - enableHkgAngleSmoothingFactor->toggleFlipped(HkgAngleSmoothingFactorValue); - - auto HkgAngleMinTorqueValue = QString::fromStdString(params.get("HkgTuningAngleMinTorqueReductionGain")).toInt(); - hkgAngleMinTorque->setLabel(QString::number(HkgAngleMinTorqueValue)+"%"); - - auto HkgAngleActiveTorqueValue = QString::fromStdString(params.get("HkgTuningAngleActiveTorqueReductionGain")).toInt(); - hkgAngleActiveTorque->setLabel(QString::number(HkgAngleActiveTorqueValue)+"%"); - - auto HkgAngleMaxTorqueValue = QString::fromStdString(params.get("HkgTuningAngleMaxTorqueReductionGain")).toInt(); - hkgAngleMaxTorque->setLabel(QString::number(HkgAngleMaxTorqueValue)+"%"); - - auto HkgTuningOverridingCyclesValue = QString::fromStdString(params.get("HkgTuningOverridingCycles")).toInt(); - hkgTuningOverridingCycles->setLabel(QString::number(HkgTuningOverridingCyclesValue)); - - offroad = _offroad; -} diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/lateral/angle_tuning_settings.h b/selfdrive/ui/sunnypilot/qt/offroad/settings/lateral/angle_tuning_settings.h deleted file mode 100644 index cbad88268e..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/lateral/angle_tuning_settings.h +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/sunnypilot/ui.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/settings.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/controls.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/expandable_row.h" - -class AngleTunningSettings : public QWidget { - Q_OBJECT - -public: - explicit AngleTunningSettings(QWidget *parent = nullptr); - - void showEvent(QShowEvent *event) override; - -signals: - void backPress(); - -public slots: - void updateToggles(bool _offroad); - -private: - Params params; - bool offroad; - - ExpandableToggleRow* enableHkgAngleSmoothingFactor; - OptionControlSP* hkgAngleMinTorque; - OptionControlSP* hkgAngleActiveTorque; - OptionControlSP* hkgAngleMaxTorque; - OptionControlSP* hkgTuningOverridingCycles; - ParamControlSP* hkgAngleLiveTuning; -}; diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/lateral/blinker_pause_lateral_settings.cc b/selfdrive/ui/sunnypilot/qt/offroad/settings/lateral/blinker_pause_lateral_settings.cc deleted file mode 100644 index b43c6162c6..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/lateral/blinker_pause_lateral_settings.cc +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/lateral/blinker_pause_lateral_settings.h" - -BlinkerPauseLateralSettings::BlinkerPauseLateralSettings(const QString ¶m, const QString &title, const QString &description, const QString &icon, QWidget *parent) - : ExpandableToggleRow(param, title, description, icon, parent) { - - pauseLateralSpeed = new OptionControlSP("BlinkerMinLateralControlSpeed", "", "", "", {0, 255}, 5); - connect(pauseLateralSpeed, &OptionControlSP::updateLabels, this, &BlinkerPauseLateralSettings::refresh); - addItem(pauseLateralSpeed); - - refresh(); -} - -void BlinkerPauseLateralSettings::refresh() { - const QString option = QString::fromStdString(params.get("BlinkerMinLateralControlSpeed")); - const bool is_metric = params.getBool("IsMetric"); - const QString unit = is_metric ? "km/h" : "mph"; - - pauseLateralSpeed->setLabel(option + " " + unit); -} diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/lateral/blinker_pause_lateral_settings.h b/selfdrive/ui/sunnypilot/qt/offroad/settings/lateral/blinker_pause_lateral_settings.h deleted file mode 100644 index 7f02337b9c..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/lateral/blinker_pause_lateral_settings.h +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/sunnypilot/ui.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/settings.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/controls.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/expandable_row.h" - -class BlinkerPauseLateralSettings : public ExpandableToggleRow { - Q_OBJECT - -public: - BlinkerPauseLateralSettings(const QString ¶m, const QString &title, const QString &description, const QString &icon, QWidget *parent = nullptr); - void refresh(); - -private: - Params params; - OptionControlSP *pauseLateralSpeed; -}; diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/lateral/lane_change_settings.cc b/selfdrive/ui/sunnypilot/qt/offroad/settings/lateral/lane_change_settings.cc deleted file mode 100644 index 53717508bf..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/lateral/lane_change_settings.cc +++ /dev/null @@ -1,111 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - * - * Created by kumar on March 10, 2025 - */ - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/lateral/lane_change_settings.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/scrollview.h" -#include -#include -#include -#include - -LaneChangeSettings::LaneChangeSettings(QWidget* parent) : QWidget(parent) { - QVBoxLayout* main_layout = new QVBoxLayout(this); - main_layout->setContentsMargins(50, 20, 50, 20); - main_layout->setSpacing(20); - - // Back button - PanelBackButton* back = new PanelBackButton(tr("Back")); - connect(back, &QPushButton::clicked, [=]() { emit backPress(); }); - main_layout->addWidget(back, 0, Qt::AlignLeft); - - ListWidgetSP *list = new ListWidgetSP(this, false); - // param, title, desc, icon - std::vector> toggle_defs{ - { - "AutoLaneChangeBsmDelay", - tr("Auto Lane Change: Delay with Blind Spot"), - tr("Toggle to enable a delay timer for seamless lane changes when blind spot monitoring (BSM) detects a obstructing vehicle, ensuring safe maneuvering."), - "../assets/offroad/icon_blank.png", - }, - }; - - // Controls: Auto Lane Change Timer - autoLaneChangeTimer = new AutoLaneChangeTimer(); - autoLaneChangeTimer->setUpdateOtherToggles(true); - autoLaneChangeTimer->showDescription(); - connect(autoLaneChangeTimer, &OptionControlSP::updateLabels, autoLaneChangeTimer, &AutoLaneChangeTimer::refresh); - connect(autoLaneChangeTimer, &AutoLaneChangeTimer::updateOtherToggles, this, &LaneChangeSettings::updateToggles); - list->addItem(autoLaneChangeTimer); - - for (auto &[param, title, desc, icon] : toggle_defs) { - auto toggle = new ParamControlSP(param, title, desc, icon, this); - list->addItem(toggle); - toggles[param.toStdString()] = toggle; - } - - main_layout->addWidget(new ScrollViewSP(list, this)); -} - -void LaneChangeSettings::showEvent(QShowEvent *event) { - updateToggles(); -} - -void LaneChangeSettings::updateToggles() { - if (!isVisible()) { - return; - } - - auto auto_lane_change_bsm_delay_toggle = toggles["AutoLaneChangeBsmDelay"]; - auto autoLaneChangeTimer_param = std::atoi(params.get("AutoLaneChangeTimer").c_str()); - - auto cp_bytes = params.get("CarParamsPersistent"); - if (!cp_bytes.empty()) { - AlignedBuffer aligned_buf; - capnp::FlatArrayMessageReader cmsg(aligned_buf.align(cp_bytes.data(), cp_bytes.size())); - cereal::CarParams::Reader CP = cmsg.getRoot(); - - if (!CP.getEnableBsm()) { - params.remove("AutoLaneChangeBsmDelay"); - } - auto_lane_change_bsm_delay_toggle->setEnabled(CP.getEnableBsm() && (autoLaneChangeTimer_param > 0)); - auto_lane_change_bsm_delay_toggle->refresh(); - } else { - auto_lane_change_bsm_delay_toggle->setEnabled(false); - } -} - -// Auto Lane Change Timer (ALCT) -AutoLaneChangeTimer::AutoLaneChangeTimer() : OptionControlSP( - "AutoLaneChangeTimer", - tr("Auto Lane Change by Blinker"), - tr("Set a timer to delay the auto lane change operation when the blinker is used. " - "No nudge on the steering wheel is required to auto lane change if a timer is set. Default is Nudge.\n" - "Please use caution when using this feature. Only use the blinker when traffic and road conditions permit."), - "../assets/offroad/icon_blank.png", - {-1, 5}) { - - refresh(); -} - -void AutoLaneChangeTimer::refresh() { - QString option = QString::fromStdString(params.get("AutoLaneChangeTimer")); - const QString second = tr("s"); - - static const QMap options = { - {"-1", tr("Off")}, - {"0", tr("Nudge")}, - {"1", tr("Nudgeless")}, - {"2", "0.5 " + second}, - {"3", "1 " + second}, - {"4", "2 " + second}, - {"5", "3 " + second}, - }; - - setLabel(options.value(option, tr("Nudge"))); -} diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/lateral/lane_change_settings.h b/selfdrive/ui/sunnypilot/qt/offroad/settings/lateral/lane_change_settings.h deleted file mode 100644 index 5bd458c47d..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/lateral/lane_change_settings.h +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include -#include - -#include "selfdrive/ui/sunnypilot/ui.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/settings.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/controls.h" - -class AutoLaneChangeTimer : public OptionControlSP { - Q_OBJECT - -public: - AutoLaneChangeTimer(); - - void refresh(); - -signals: - void toggleUpdated(); - -private: - Params params; -}; - - -class LaneChangeSettings : public QWidget { - Q_OBJECT - -public: - explicit LaneChangeSettings(QWidget* parent = nullptr); - void showEvent(QShowEvent *event) override; - -signals: - void backPress(); - -public slots: - void updateToggles(); - -private: - Params params; - std::map toggles; - - AutoLaneChangeTimer *autoLaneChangeTimer; -}; diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/lateral/mads_settings.cc b/selfdrive/ui/sunnypilot/qt/offroad/settings/lateral/mads_settings.cc deleted file mode 100644 index 72e7a5c8cb..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/lateral/mads_settings.cc +++ /dev/null @@ -1,102 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/lateral/mads_settings.h" - -#include "selfdrive/ui/sunnypilot/qt/widgets/scrollview.h" - -MadsSettings::MadsSettings(QWidget *parent) : QWidget(parent) { - QVBoxLayout *main_layout = new QVBoxLayout(this); - main_layout->setContentsMargins(50, 20, 50, 20); - main_layout->setSpacing(20); - - // Back button - PanelBackButton *back = new PanelBackButton(); - connect(back, &QPushButton::clicked, [=]() { emit backPress(); }); - main_layout->addWidget(back, 0, Qt::AlignLeft); - - ListWidget *list = new ListWidget(this, false); - // Main cruise - madsMainCruiseToggle = new ParamControl("MadsMainCruiseAllowed", tr("Toggle with Main Cruise"), "", ""); - list->addItem(madsMainCruiseToggle); - - // Unified Engagement Mode - madsUnifiedEngagementModeToggle = new ParamControl("MadsUnifiedEngagementMode", tr("Unified Engagement Mode (UEM)"), "", ""); - list->addItem(madsUnifiedEngagementModeToggle); - - // Steering Mode On Brake - madsSteeringMode = new ButtonParamControl("MadsSteeringMode", tr("Steering Mode on Brake Pedal"), "", "", madsSteeringModeTexts(), 500); - QObject::connect(madsSteeringMode, &ButtonParamControl::buttonClicked, [=] { - updateToggles(offroad); - }); - list->addItem(madsSteeringMode); - - QObject::connect(uiState(), &UIState::offroadTransition, this, &MadsSettings::updateToggles); - - main_layout->addWidget(new ScrollViewSP(list, this)); -} - -void MadsSettings::showEvent(QShowEvent *event) { - updateToggles(offroad); -} - -void MadsSettings::updateToggles(bool _offroad) { - auto mads_steering_mode_param = std::atoi(params.get("MadsSteeringMode").c_str()); - - auto steering_mode = static_cast( - std::clamp(mads_steering_mode_param, static_cast(MadsSteeringMode::REMAIN_ACTIVE), static_cast(MadsSteeringMode::DISENGAGE)) - ); - - auto cp_bytes = params.get("CarParamsPersistent"); - if (!cp_bytes.empty()) { - AlignedBuffer aligned_buf; - capnp::FlatArrayMessageReader cmsg(aligned_buf.align(cp_bytes.data(), cp_bytes.size())); - cereal::CarParams::Reader CP = cmsg.getRoot(); - - if (isBrandInList(CP.getBrand(), mads_limited_settings_brands)) { - params.remove("MadsMainCruiseAllowed"); - params.putBool("MadsUnifiedEngagementMode", true); - params.put("MadsSteeringMode", std::to_string(static_cast(MadsSteeringMode::DISENGAGE))); - - madsMainCruiseToggle->setEnabled(false); - madsMainCruiseToggle->setDescription(madsDescriptionBuilder(DEFAULT_TO_OFF, MADS_MAIN_CRUISE_BASE_DESC)); - madsMainCruiseToggle->showDescription(); - - madsUnifiedEngagementModeToggle->setEnabled(false); - madsUnifiedEngagementModeToggle->setDescription(madsDescriptionBuilder(DEFAULT_TO_ON, MADS_UNIFIED_ENGAGEMENT_MODE_BASE_DESC)); - madsUnifiedEngagementModeToggle->showDescription(); - - madsSteeringModeValues = convertMadsSteeringModeValues({MadsSteeringMode::DISENGAGE}); - madsSteeringMode->setDescription(madsDescriptionBuilder(STATUS_DISENGAGE_ONLY, madsSteeringModeDescription(steering_mode))); - } else { - madsMainCruiseToggle->setEnabled(true); - madsMainCruiseToggle->setDescription(MADS_MAIN_CRUISE_BASE_DESC); - - madsUnifiedEngagementModeToggle->setEnabled(true); - madsUnifiedEngagementModeToggle->setDescription(MADS_UNIFIED_ENGAGEMENT_MODE_BASE_DESC); - - madsSteeringModeValues = convertMadsSteeringModeValues(getMadsSteeringModeValues()); - madsSteeringMode->setDescription(madsSteeringModeDescription(steering_mode)); - } - } else { - madsMainCruiseToggle->setEnabled(false); - madsMainCruiseToggle->setDescription(madsDescriptionBuilder(STATUS_CHECK_COMPATIBILITY, MADS_MAIN_CRUISE_BASE_DESC)); - madsMainCruiseToggle->showDescription(); - - madsUnifiedEngagementModeToggle->setEnabled(false); - madsUnifiedEngagementModeToggle->setDescription(madsDescriptionBuilder(STATUS_CHECK_COMPATIBILITY, MADS_UNIFIED_ENGAGEMENT_MODE_BASE_DESC)); - madsUnifiedEngagementModeToggle->showDescription(); - - madsSteeringModeValues = {}; - madsSteeringMode->setDescription(madsDescriptionBuilder(STATUS_CHECK_COMPATIBILITY, madsSteeringModeDescription(steering_mode))); - } - - madsSteeringMode->setEnableSelectedButtons(_offroad, madsSteeringModeValues); - madsSteeringMode->showDescription(); - - offroad = _offroad; -} diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/lateral/mads_settings.h b/selfdrive/ui/sunnypilot/qt/offroad/settings/lateral/mads_settings.h deleted file mode 100644 index af624865c7..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/lateral/mads_settings.h +++ /dev/null @@ -1,115 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/sunnypilot/ui.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/settings.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/controls.h" - -const std::vector mads_limited_settings_brands = {"rivian", "tesla"}; - -enum class MadsSteeringMode { - REMAIN_ACTIVE = 0, - PAUSE = 1, - DISENGAGE = 2, -}; - -struct MadsSteeringModeOption { - MadsSteeringMode mode; - QString display_text; - QString description; -}; - -class MadsSettings : public QWidget { - Q_OBJECT - -public: - explicit MadsSettings(QWidget *parent = nullptr); - - void showEvent(QShowEvent *event) override; - -signals: - void backPress(); - -public slots: - void updateToggles(bool _offroad); - -private: - Params params; - bool offroad; - - ParamControl *madsMainCruiseToggle; - ParamControl *madsUnifiedEngagementModeToggle; - ButtonParamControl *madsSteeringMode; - - std::vector madsSteeringModeValues = {}; - - const QString MADS_MAIN_CRUISE_BASE_DESC = tr("Note: For vehicles without LFA/LKAS button, disabling this will prevent lateral control engagement."); - const QString MADS_UNIFIED_ENGAGEMENT_MODE_BASE_DESC = QString("%1
" - "

%2

") - .arg(tr("Engage lateral and longitudinal control with cruise control engagement.")) - .arg(tr("Note: Once lateral control is engaged via UEM, it will remain engaged until it is manually disabled via the MADS button or car shut off.")); - - const QString STATUS_CHECK_COMPATIBILITY = tr("Start the vehicle to check vehicle compatibility."); - const QString DEFAULT_TO_OFF = tr("This feature defaults to OFF, and does not allow selection due to vehicle limitations."); - const QString DEFAULT_TO_ON = tr("This feature defaults to ON, and does not allow selection due to vehicle limitations."); - const QString STATUS_DISENGAGE_ONLY = tr("This platform only supports Disengage mode due to vehicle limitations."); - - static const std::vector &madsSteeringModeOptions() { - static const std::vector options = { - {MadsSteeringMode::REMAIN_ACTIVE, tr("Remain Active"), tr("Remain Active: ALC will remain active when the brake pedal is pressed.")}, - {MadsSteeringMode::PAUSE, tr("Pause"), tr("Pause: ALC will pause when the brake pedal is pressed.")}, - {MadsSteeringMode::DISENGAGE, tr("Disengage"), tr("Disengage: ALC will disengage when the brake pedal is pressed.")}, - }; - return options; - } - - static std::vector getMadsSteeringModeValues() { - std::vector values; - for (const auto& option : madsSteeringModeOptions()) { - values.push_back(option.mode); - } - return values; - } - - static std::vector convertMadsSteeringModeValues(const std::vector &modes) { - std::vector values; - for (const auto& mode : modes) { - values.push_back(static_cast(mode)); - } - return values; - } - - static std::vector madsSteeringModeTexts() { - std::vector texts; - for (const auto& option : madsSteeringModeOptions()) { - texts.push_back(option.display_text); - } - return texts; - } - - static QString madsSteeringModeDescription(const MadsSteeringMode mode = MadsSteeringMode::REMAIN_ACTIVE) { - QString base_desc = tr("Choose how Automatic Lane Centering (ALC) behaves after the brake pedal is manually pressed in sunnypilot."); - QString result = base_desc + "

"; - - for (const auto& option : madsSteeringModeOptions()) { - QString desc = option.description; - if (option.mode == mode) { - desc = "" + desc + ""; - } - result += desc + "
"; - } - - return result; - } - - static QString madsDescriptionBuilder(const QString &custom_description, const QString &base_description) { - return "" + custom_description + "

" + base_description; - } -}; diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/lateral/neural_network_lateral_control.cc b/selfdrive/ui/sunnypilot/qt/offroad/settings/lateral/neural_network_lateral_control.cc deleted file mode 100644 index 0b66b83660..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/lateral/neural_network_lateral_control.cc +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/lateral/neural_network_lateral_control.h" - -NeuralNetworkLateralControl::NeuralNetworkLateralControl() : - ParamControl("NeuralNetworkLateralControl", tr("Neural Network Lateral Control (NNLC)"), "", "") { - setConfirmation(true, false); - updateToggle(); -} - -void NeuralNetworkLateralControl::updateToggle() { - QString statusInitText = "" + STATUS_CHECK_COMPATIBILITY + ""; - QString notLoadedText = "" + STATUS_NOT_LOADED + ""; - QString loadedText = "" + STATUS_LOADED + ""; - - auto cp_bytes = params.get("CarParamsPersistent"); - auto cp_sp_bytes = params.get("CarParamsSPPersistent"); - if (!cp_bytes.empty() && !cp_sp_bytes.empty()) { - AlignedBuffer aligned_buf; - AlignedBuffer aligned_buf_sp; - capnp::FlatArrayMessageReader cmsg(aligned_buf.align(cp_bytes.data(), cp_bytes.size())); - capnp::FlatArrayMessageReader cmsg_sp(aligned_buf_sp.align(cp_sp_bytes.data(), cp_sp_bytes.size())); - cereal::CarParams::Reader CP = cmsg.getRoot(); - cereal::CarParamsSP::Reader CP_SP = cmsg_sp.getRoot(); - - if (CP.getSteerControlType() == cereal::CarParams::SteerControlType::ANGLE) { - params.remove("NeuralNetworkLateralControl"); - setDescription(nnffDescriptionBuilder(STATUS_NOT_AVAILABLE)); - setEnabled(false); - } else { - QString nn_model_name = QString::fromStdString(CP_SP.getNeuralNetworkLateralControl().getModel().getName()); - QString nn_fuzzy = CP_SP.getNeuralNetworkLateralControl().getFuzzyFingerprint() ? - STATUS_MATCH_FUZZY : STATUS_MATCH_EXACT; - - if (nn_model_name.isEmpty()) { - setDescription(nnffDescriptionBuilder(statusInitText)); - } else if (nn_model_name == "MOCK") { - setDescription(nnffDescriptionBuilder( - notLoadedText + "
" + buildSupportText(SUPPORT_DONATE_LOGS) - )); - } else { - QString statusText = loadedText + " | " + STATUS_MATCH + " = " + nn_fuzzy + " | " + nn_model_name; - QString explanationText = EXPLANATION_MATCH + " " + buildSupportText(SUPPORT_ISSUES); - setDescription(nnffDescriptionBuilder(statusText + "

" + explanationText)); - } - } - } else { - setDescription(nnffDescriptionBuilder(statusInitText)); - } - - if (getDescription() != getBaseDescription()) { - showDescription(); - } -} diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/lateral/neural_network_lateral_control.h b/selfdrive/ui/sunnypilot/qt/offroad/settings/lateral/neural_network_lateral_control.h deleted file mode 100644 index df80fbf097..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/lateral/neural_network_lateral_control.h +++ /dev/null @@ -1,61 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include - -#include "selfdrive/ui/sunnypilot/ui.h" -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/settings.h" - -class NeuralNetworkLateralControl : public ParamControl { - Q_OBJECT - -public: - NeuralNetworkLateralControl(); - -public slots: - void updateToggle(); - -private: - Params params; - - // Status messages - const QString STATUS_NOT_AVAILABLE = tr("NNLC is currently not available on this platform."); - const QString STATUS_CHECK_COMPATIBILITY = tr("Start the car to check car compatibility"); - const QString STATUS_NOT_LOADED = tr("NNLC Not Loaded"); - const QString STATUS_LOADED = tr("NNLC Loaded"); - const QString STATUS_MATCH = tr("Match"); - const QString STATUS_MATCH_EXACT = tr("Exact"); - const QString STATUS_MATCH_FUZZY = tr("Fuzzy"); - - // Explanations - const QString EXPLANATION_MATCH = tr("Match: \"Exact\" is ideal, but \"Fuzzy\" is fine too."); - const QString EXPLANATION_FEATURE = tr("Formerly known as \"NNFF\", this replaces the lateral \"torque\" controller, " - "with one using a neural network trained on each car's (actually, each separate EPS firmware) driving data for increased controls accuracy."); - - // Support information - const QString SUPPORT_CHANNEL = "#tuning-nnlc"; - const QString SUPPORT_REACH_OUT = tr("Reach out to the sunnypilot team in the following channel at the sunnypilot Discord server"); - const QString SUPPORT_FEEDBACK = tr("with feedback, or to provide log data for your car if your car is currently unsupported:"); - const QString SUPPORT_ISSUES = tr("if there are any issues:"); - const QString SUPPORT_DONATE_LOGS = tr("and donate logs to get NNLC loaded for your car:"); - - // Description builders - QString buildSupportText(const QString& context) const { - return SUPPORT_REACH_OUT + " " + context + " " + SUPPORT_CHANNEL; - } - - QString nnffDescriptionBuilder(const QString &custom_description) const { - return "" + custom_description + "

" + getBaseDescription(); - } - - QString getBaseDescription() const { - return EXPLANATION_FEATURE + "

" + buildSupportText(SUPPORT_FEEDBACK); - } -}; diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/lateral_panel.cc b/selfdrive/ui/sunnypilot/qt/offroad/settings/lateral_panel.cc deleted file mode 100644 index 8a110a2aa3..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/lateral_panel.cc +++ /dev/null @@ -1,188 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/lateral_panel.h" - -#include "common/util.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/controls.h" - -LateralPanel::LateralPanel(SettingsWindowSP *parent) : QFrame(parent) { - main_layout = new QStackedLayout(this); - ListWidget *list = new ListWidget(this, false); - - sunnypilotScreen = new QWidget(this); - QVBoxLayout* vlayout = new QVBoxLayout(sunnypilotScreen); - vlayout->setContentsMargins(50, 20, 50, 20); - - // MADS - madsToggle = new ParamControl( - "Mads", - tr("Modular Assistive Driving System (MADS)"), - tr("Enable the beloved MADS feature. Disable toggle to revert back to stock sunnypilot engagement/disengagement."), - ""); - madsToggle->setConfirmation(true, false); - list->addItem(madsToggle); - - madsSettingsButton = new PushButtonSP(tr("Customize MADS")); - madsSettingsButton->setObjectName("mads_btn"); - connect(madsSettingsButton, &QPushButton::clicked, [=]() { - sunnypilotScroller->setLastScrollPosition(); - main_layout->setCurrentWidget(madsWidget); - }); - QObject::connect(madsToggle, &ToggleControl::toggleFlipped, madsSettingsButton, &PushButtonSP::setEnabled); - - madsWidget = new MadsSettings(this); - connect(madsWidget, &MadsSettings::backPress, [=]() { - sunnypilotScroller->restoreScrollPosition(); - main_layout->setCurrentWidget(sunnypilotScreen); - }); - list->addItem(madsSettingsButton); - - list->addItem(vertical_space()); - list->addItem(horizontal_line()); - list->addItem(vertical_space()); - - // Lane Change Settings - laneChangeSettingsButton = new PushButtonSP(tr("Customize Lane Change")); - laneChangeSettingsButton->setObjectName("lane_change_btn"); - connect(laneChangeSettingsButton, &QPushButton::clicked, [=]() { - sunnypilotScroller->setLastScrollPosition(); - main_layout->setCurrentWidget(laneChangeWidget); - }); - - laneChangeWidget = new LaneChangeSettings(this); - connect(laneChangeWidget, &LaneChangeSettings::backPress, [=]() { - sunnypilotScroller->restoreScrollPosition(); - main_layout->setCurrentWidget(sunnypilotScreen); - }); - list->addItem(laneChangeSettingsButton); - - list->addItem(vertical_space(0)); - list->addItem(horizontal_line()); - - // Blinker Pause Lateral Control - blinkerPauseLateralSettings = new BlinkerPauseLateralSettings( - "BlinkerPauseLateralControl", - tr("Pause Lateral Control with Blinker"), - tr("Pause lateral control with blinker when traveling below the desired speed selected."), - "", - this); - list->addItem(blinkerPauseLateralSettings); - - list->addItem(horizontal_line()); - - // Neural Network Lateral Control - nnlcToggle = new NeuralNetworkLateralControl(); - list->addItem(nnlcToggle); - - QObject::connect(nnlcToggle, &ParamControl::toggleFlipped, [=](bool state) { - if (state) { - nnlcToggle->showDescription(); - } else { - nnlcToggle->hideDescription(); - } - - nnlcToggle->updateToggle(); - }); - -#pragma region hkg angle tuning - list->addItem(vertical_space()); - list->addItem(horizontal_line()); - list->addItem(vertical_space()); - - // HKG Angle Tuning - // angleTuningToggle = new ParamControl( - // "AngleTuning", - // tr("Modular Assistive Driving System (MADS)"), - // tr("Enable the beloved MADS feature. Disable toggle to revert back to stock sunnypilot engagement/disengagement."), - // ""); - // angleTuningToggle->setConfirmation(true, false); - // list->addItem(angleTuningToggle); - - angleTuningSettingsButton = new PushButtonSP(tr("Customize ANGLE Tuning")); - angleTuningSettingsButton->setObjectName("angle_btn"); - connect(angleTuningSettingsButton, &QPushButton::clicked, [=]() { - sunnypilotScroller->setLastScrollPosition(); - main_layout->setCurrentWidget(angleTuningWidget); - }); - // QObject::connect(angleTuningToggle, &ToggleControl::toggleFlipped, angleTuningSettingsButton, &PushButtonSP::setEnabled); - - angleTuningWidget = new AngleTunningSettings(this); - connect(angleTuningWidget, &AngleTunningSettings::backPress, [=]() { - sunnypilotScroller->restoreScrollPosition(); - main_layout->setCurrentWidget(sunnypilotScreen); - }); - list->addItem(angleTuningSettingsButton); -#pragma endregion - - toggleOffroadOnly = { - madsToggle, nnlcToggle, - }; - QObject::connect(uiState(), &UIState::offroadTransition, this, &LateralPanel::updateToggles); - - sunnypilotScroller = new ScrollViewSP(list, this); - vlayout->addWidget(sunnypilotScroller); - - main_layout->addWidget(sunnypilotScreen); - main_layout->addWidget(madsWidget); - main_layout->addWidget(angleTuningWidget); - main_layout->addWidget(laneChangeWidget); - - setStyleSheet(R"( - #back_btn { - font-size: 50px; - margin: 0px; - padding: 15px; - border-width: 0; - border-radius: 30px; - color: #dddddd; - background-color: #393939; - } - #back_btn:pressed { - background-color: #4a4a4a; - } - )"); - - main_layout->setCurrentWidget(sunnypilotScreen); -} - -void LateralPanel::showEvent(QShowEvent *event) { - nnlcToggle->updateToggle(); - updateToggles(offroad); -} - -void LateralPanel::hideEvent(QHideEvent *event) { - main_layout->setCurrentWidget(sunnypilotScreen); -} - -void LateralPanel::updateToggles(bool _offroad) { - for (auto *toggle : toggleOffroadOnly) { - toggle->setEnabled(_offroad); - } - - auto cp_bytes = params.get("CarParamsPersistent"); - if (!cp_bytes.empty()) { - AlignedBuffer aligned_buf; - capnp::FlatArrayMessageReader cmsg(aligned_buf.align(cp_bytes.data(), cp_bytes.size())); - cereal::CarParams::Reader CP = cmsg.getRoot(); - - if (isBrandInList(CP.getBrand(), mads_limited_settings_brands)) { - madsToggle->setDescription(descriptionBuilder(STATUS_MADS_SETTINGS_LIMITED_COMPATIBILITY, MADS_BASE_DESC)); - } else { - madsToggle->setDescription(descriptionBuilder(STATUS_MADS_SETTINGS_FULL_COMPATIBILITY, MADS_BASE_DESC)); - } - } else { - madsToggle->setDescription(descriptionBuilder(STATUS_MADS_CHECK_COMPATIBILITY, MADS_BASE_DESC)); - } - - madsSettingsButton->setEnabled(madsToggle->isToggled()); - // angleTuningSettingsButton->setEnabled(angleTuningToggle->isToggled()); - - blinkerPauseLateralSettings->refresh(); - - offroad = _offroad; -} diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/lateral_panel.h b/selfdrive/ui/sunnypilot/qt/offroad/settings/lateral_panel.h deleted file mode 100644 index 36cfd4f664..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/lateral_panel.h +++ /dev/null @@ -1,62 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include -#include - -#include "selfdrive/ui/sunnypilot/ui.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/lateral/blinker_pause_lateral_settings.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/lateral/mads_settings.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/lateral/angle_tuning_settings.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/lateral/neural_network_lateral_control.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/lateral/lane_change_settings.h" -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/settings.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/scrollview.h" - -class LateralPanel : public QFrame { - Q_OBJECT - -public: - explicit LateralPanel(SettingsWindowSP *parent = nullptr); - void showEvent(QShowEvent *event) override; - void hideEvent(QHideEvent* event) override; - -public slots: - void updateToggles(bool _offroad); - -private: - Params params; - QStackedLayout* main_layout = nullptr; - QWidget* sunnypilotScreen = nullptr; - ScrollViewSP *sunnypilotScroller = nullptr; - std::vector toggleOffroadOnly; - bool offroad; - - ParamControl *madsToggle; - // ParamControl *angleTuningToggle; - PushButtonSP *madsSettingsButton; - PushButtonSP *angleTuningSettingsButton; - MadsSettings *madsWidget = nullptr; - AngleTunningSettings *angleTuningWidget = nullptr; - PushButtonSP *laneChangeSettingsButton; - LaneChangeSettings *laneChangeWidget = nullptr; - NeuralNetworkLateralControl *nnlcToggle = nullptr; - BlinkerPauseLateralSettings *blinkerPauseLateralSettings = nullptr; - - const QString MADS_BASE_DESC = tr("Enables independent engagements of Automatic Lane Centering (ALC) and Adaptive Cruise Control (ACC)."); - - const QString STATUS_MADS_CHECK_COMPATIBILITY = tr("Start the vehicle to check vehicle compatibility."); - const QString STATUS_MADS_SETTINGS_FULL_COMPATIBILITY = tr("This platform supports all MADS settings."); - const QString STATUS_MADS_SETTINGS_LIMITED_COMPATIBILITY = tr("This platform supports limited MADS settings."); - - static QString descriptionBuilder(const QString &custom_description, const QString &base_description) { - return "" + custom_description + "

" + base_description; - } -}; diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/longitudinal/custom_acc_increment.cc b/selfdrive/ui/sunnypilot/qt/offroad/settings/longitudinal/custom_acc_increment.cc deleted file mode 100644 index 29cadeaa62..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/longitudinal/custom_acc_increment.cc +++ /dev/null @@ -1,47 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/longitudinal/custom_acc_increment.h" - -CustomAccIncrement::CustomAccIncrement(const QString ¶m, const QString &title, const QString &desc, const QString &icon, QWidget *parent) - : ExpandableToggleRow(param, title, desc, icon, parent) { - auto *accFrame = new QFrame(this); - auto *accFrameLayout = new QGridLayout(); - accFrame->setLayout(accFrameLayout); - accFrameLayout->setSpacing(0); - - auto *shortPressControl = new AccIncrementOptionControl("CustomAccShortPressIncrement", {1, 10}, 1); - connect(shortPressControl, &OptionControlSP::updateLabels, shortPressControl, &AccIncrementOptionControl::refresh); - - auto *longPressControl = new AccIncrementOptionControl("CustomAccLongPressIncrement", {1, 3}, 1, &customLongValues); - connect(longPressControl, &OptionControlSP::updateLabels, longPressControl, &AccIncrementOptionControl::refresh); - - shortPressControl->setFixedWidth(280); - longPressControl->setFixedWidth(280); - accFrameLayout->addWidget(shortPressControl, 0, 0, Qt::AlignLeft); - accFrameLayout->addWidget(longPressControl, 0, 1, Qt::AlignRight); - - addItem(accFrame); -} - -AccIncrementOptionControl::AccIncrementOptionControl(const QString ¶m, const MinMaxValue &range, const int per_value_change, const QMap *valMap) - : OptionControlSP(param, "", "", "", range, per_value_change, true, valMap) { - param_name = param.toStdString(); - refresh(); -} - -void AccIncrementOptionControl::refresh() { - std::string val = params.get(param_name); - std::string label = ""; - label += param_name == "CustomAccShortPressIncrement" ? "Short Press" : "Long Press"; - label += "
" + val; - label += param_name == "CustomAccShortPressIncrement" - ? (val == "1" ? " (Default)" : "") - : (val == "5" ? " (Default)" : ""); - label += "
"; - setLabel(QString::fromStdString(label)); -} diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/longitudinal/custom_acc_increment.h b/selfdrive/ui/sunnypilot/qt/offroad/settings/longitudinal/custom_acc_increment.h deleted file mode 100644 index 707d4143bc..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/longitudinal/custom_acc_increment.h +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/sunnypilot/ui.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/settings.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/controls.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/expandable_row.h" - -class CustomAccIncrement : public ExpandableToggleRow { - Q_OBJECT - -public: - CustomAccIncrement(const QString ¶m, const QString &title, const QString &desc, const QString &icon, QWidget *parent = nullptr); - -private: - QMap customLongValues = { - {"1", "1"}, - {"2", "5"}, // Default - {"3", "10"} - }; -}; - -class AccIncrementOptionControl : public OptionControlSP { - Q_OBJECT - -public: - AccIncrementOptionControl(const QString ¶m, const MinMaxValue &range, int per_value_change, const QMap *valMap = nullptr); - void refresh(); - -protected: - std::string param_name; - -private: - Params params; -}; diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/longitudinal_panel.cc b/selfdrive/ui/sunnypilot/qt/offroad/settings/longitudinal_panel.cc deleted file mode 100644 index 15ed10bf9a..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/longitudinal_panel.cc +++ /dev/null @@ -1,79 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/longitudinal_panel.h" - -LongitudinalPanel::LongitudinalPanel(QWidget *parent) : QWidget(parent) { - main_layout = new QStackedLayout(this); - ListWidget *list = new ListWidget(this, false); - - cruisePanelScreen = new QWidget(this); - QVBoxLayout *vlayout = new QVBoxLayout(cruisePanelScreen); - vlayout->setContentsMargins(0, 0, 0, 0); - - cruisePanelScroller = new ScrollViewSP(list, this); - vlayout->addWidget(cruisePanelScroller); - - customAccIncrement = new CustomAccIncrement("CustomAccIncrementsEnabled", tr("Custom ACC Speed Increments"), "", "", this); - list->addItem(customAccIncrement); - - QObject::connect(uiState(), &UIState::offroadTransition, this, &LongitudinalPanel::refresh); - - main_layout->addWidget(cruisePanelScreen); - main_layout->setCurrentWidget(cruisePanelScreen); - refresh(offroad); -} - -void LongitudinalPanel::showEvent(QShowEvent *event) { - main_layout->setCurrentWidget(cruisePanelScreen); - refresh(offroad); -} - -void LongitudinalPanel::refresh(bool _offroad) { - auto cp_bytes = params.get("CarParamsPersistent"); - if (!cp_bytes.empty()) { - AlignedBuffer aligned_buf; - capnp::FlatArrayMessageReader cmsg(aligned_buf.align(cp_bytes.data(), cp_bytes.size())); - cereal::CarParams::Reader CP = cmsg.getRoot(); - - has_longitudinal_control = hasLongitudinalControl(CP); - is_pcm_cruise = CP.getPcmCruise(); - } else { - has_longitudinal_control = false; - is_pcm_cruise = false; - } - - QString accEnabledDescription = tr("Enable custom Short & Long press increments for cruise speed increase/decrease."); - QString accNoLongDescription = tr("This feature can only be used with openpilot longitudinal control enabled."); - QString accPcmCruiseDisabledDescription = tr("This feature is not supported on this platform due to vehicle limitations."); - QString onroadOnlyDescription = tr("Start the vehicle to check vehicle compatibility."); - - if (offroad) { - customAccIncrement->setDescription(onroadOnlyDescription); - customAccIncrement->showDescription(); - } else { - if (has_longitudinal_control) { - if (is_pcm_cruise) { - customAccIncrement->setDescription(accPcmCruiseDisabledDescription); - customAccIncrement->showDescription(); - } else { - customAccIncrement->setDescription(accEnabledDescription); - } - } else { - params.remove("CustomAccIncrementsEnabled"); - customAccIncrement->toggleFlipped(false); - customAccIncrement->setDescription(accNoLongDescription); - customAccIncrement->showDescription(); - } - } - - // enable toggle when long is available and is not PCM cruise - customAccIncrement->setEnabled(has_longitudinal_control && !is_pcm_cruise && !offroad); - customAccIncrement->refresh(); - - offroad = _offroad; -} diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/longitudinal_panel.h b/selfdrive/ui/sunnypilot/qt/offroad/settings/longitudinal_panel.h deleted file mode 100644 index 58e94f333b..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/longitudinal_panel.h +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/longitudinal/custom_acc_increment.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/settings.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/scrollview.h" - -class LongitudinalPanel : public QWidget { - Q_OBJECT - -public: - explicit LongitudinalPanel(QWidget *parent = nullptr); - void showEvent(QShowEvent *event) override; - void refresh(bool _offroad); - -private: - Params params; - bool has_longitudinal_control = false; - bool is_pcm_cruise = false; - bool offroad = false; - - QStackedLayout *main_layout = nullptr; - ScrollViewSP *cruisePanelScroller = nullptr; - QWidget *cruisePanelScreen = nullptr; - CustomAccIncrement *customAccIncrement = nullptr; -}; diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/max_time_offroad.cc b/selfdrive/ui/sunnypilot/qt/offroad/settings/max_time_offroad.cc deleted file mode 100644 index 4cc7351b03..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/max_time_offroad.cc +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/max_time_offroad.h" - -// Map of Max Offroad Time Options (Minutes) -const QMap MaxTimeOffroad::offroad_time_options = { - {"0", "0"}, // Always On - {"1", "5"}, - {"2", "10"}, - {"3", "15"}, - {"4", "30"}, - {"5", "60"}, - {"6", "120"}, - {"7", "180"}, - {"8", "300"}, - {"9", "600"}, - {"10", "1440"}, - {"11", "1800"} -}; - -MaxTimeOffroad::MaxTimeOffroad() : OptionControlSP( - "MaxTimeOffroad", - tr("Max Time Offroad"), - tr("Device will automatically shutdown after set time once the engine is turned off.
(30h is the default)"), - "../assets/offroad/icon_blank.png", - {0, 11}, 1, true, &offroad_time_options) { - - refresh(); -} - -void MaxTimeOffroad::refresh() { - const int maxOffroadInMinutes = QString::fromStdString(params.get("MaxTimeOffroad")).toInt(); - const bool useHours = maxOffroadInMinutes >= 60; - - QString label; - if (maxOffroadInMinutes == 0) { - label = tr("Always On"); - } else { - const int value = useHours ? maxOffroadInMinutes / 60 : maxOffroadInMinutes; - label = QString("%1%2").arg(value).arg(useHours ? tr("h") : tr("m")); - } - - if (maxOffroadInMinutes == 1800) { - label += tr(" (default)"); - } - - setLabel(label); -} diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/max_time_offroad.h b/selfdrive/ui/sunnypilot/qt/offroad/settings/max_time_offroad.h deleted file mode 100644 index 31c6a335c7..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/max_time_offroad.h +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/sunnypilot/ui.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/settings.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/controls.h" - -class MaxTimeOffroad : public OptionControlSP { - Q_OBJECT - -public: - static const QMap offroad_time_options; - - MaxTimeOffroad(); - void refresh(); - -private: - Params params; -}; diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/models_panel.cc b/selfdrive/ui/sunnypilot/qt/offroad/settings/models_panel.cc deleted file mode 100644 index b8237c3627..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/models_panel.cc +++ /dev/null @@ -1,312 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include -#include -#include - -#include "common/model.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/models_panel.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/scrollview.h" - -static const QString progressStyleActive = "QProgressBar {" - " font-size: 40px;" - " font-weight: 200;" - " padding: 1px;" - " border: 3px solid black;" - " border-radius: 10px;" - "}" - "QProgressBar::chunk {" - " background-color: #1e79e8;" - " border-radius: 10px;" - "}"; - -static const QString progressStyleInactive = progressStyleActive + - "QProgressBar::chunk {" - " background-color: transparent;" - "}"; - -static const QString progressStyleDone = progressStyleActive + - "QProgressBar {" - " color: #33ab4c;" - "}" - "QProgressBar::chunk {" - " background-color: transparent;" - "}"; - -static const QString progressStyleError = progressStyleActive + - "QProgressBar {" - " color: red;" - "}" - "QProgressBar::chunk {" - " background-color: transparent;" - "}"; - -ModelsPanel::ModelsPanel(QWidget *parent) : QWidget(parent) { - QVBoxLayout *main_layout = new QVBoxLayout(this); - main_layout->setContentsMargins(50, 20, 50, 20); - - ListWidgetSP *list = new ListWidgetSP(this, false); - ScrollViewSP *scroller = new ScrollViewSP(list, this); - main_layout->addWidget(scroller); - - const auto current_model = GetActiveModelName(); - currentModelLblBtn = new ButtonControlSP(tr("Current Model"), tr("SELECT"), "", this); - currentModelLblBtn->setValue(current_model); - - connect(currentModelLblBtn, &ButtonControlSP::clicked, this, &ModelsPanel::handleCurrentModelLblBtnClicked); - connect(uiState(), &UIState::offroadTransition, [=](bool offroad) { - is_onroad = !offroad; - updateLabels(); - }); - connect(uiStateSP(), &UIStateSP::uiUpdate, this, &ModelsPanel::updateLabels); - list->addItem(currentModelLblBtn); - - // Create progress bars for downloads - supercomboProgressBar = createProgressBar(this); - QString supercomboType = tr("Driving Model"); - supercomboFrame = createModelDetailFrame(this, supercomboType, supercomboProgressBar); - list->addItem(supercomboFrame); - - navigationProgressBar = createProgressBar(this); - QString navigationType = tr("Navigation Model"); - navigationFrame = createModelDetailFrame(this, navigationType, navigationProgressBar); - list->addItem(navigationFrame); - - visionProgressBar = createProgressBar(this); - QString visionType = tr("Vision Model"); - visionFrame = createModelDetailFrame(this, visionType, visionProgressBar); - list->addItem(visionFrame); - - policyProgressBar = createProgressBar(this); - QString policyType = tr("Policy Model"); - policyFrame = createModelDetailFrame(this, policyType, policyProgressBar); - list->addItem(policyFrame); - - list->addItem(horizontal_line()); - - // LiveDelay toggle - list->addItem(new ParamControlSP("LagdToggle", - tr("Live Learning Steer Delay"), - tr("Enable this for the car to learn and adapt its steering response time. " - "Disable to use a fixed steering response time. Keeping this on provides the stock openpilot experience."), - "../assets/offroad/icon_shell.png")); -} - -QProgressBar* ModelsPanel::createProgressBar(QWidget *parent) { - QProgressBar *progressBar = new QProgressBar(parent); - progressBar->setRange(0, 100); - progressBar->setValue(0); - progressBar->setTextVisible(true); - progressBar->setAlignment(Qt::AlignVCenter); - return progressBar; -} - -QFrame* ModelsPanel::createModelDetailFrame(QWidget *parent, QString &typeName, QProgressBar *progressBar) { - QFrame *frame = new QFrame(parent); - QHBoxLayout *layout = new QHBoxLayout(frame); - layout->setContentsMargins(0, 0, 0, 0); - layout->setSpacing(50); - layout->addWidget(new QLabel(typeName)); - layout->addWidget(progressBar); - frame->setVisible(false); - return frame; -} - -/** - * @brief Updates the UI with bundle download progress information - * Reads status from modelManagerSP cereal message and displays status for all models - */ -void ModelsPanel::handleBundleDownloadProgress() { - supercomboFrame->setVisible(false); - visionFrame->setVisible(false); - policyFrame->setVisible(false); - navigationFrame->setVisible(false); - - using DS = cereal::ModelManagerSP::DownloadStatus; - if (!model_manager.hasSelectedBundle() && !model_manager.hasActiveBundle()) { - return; - } - - const bool showSelectedBundle = model_manager.hasSelectedBundle() && (isDownloading() || model_manager.getSelectedBundle().getStatus() == DS::FAILED); - const auto &bundle = showSelectedBundle ? model_manager.getSelectedBundle() : model_manager.getActiveBundle(); - const auto &models = bundle.getModels(); - download_status = bundle.getStatus(); - const auto download_status_changed = prev_download_status != download_status; - QStringList status; - - // Get status for each model type in order - for (const auto &model: models) { - QString modelName = QString::fromStdString(bundle.getDisplayName()); - - QProgressBar *progressBar = nullptr; - QFrame *modelFrame = nullptr; - - switch (model.getType()) { - case cereal::ModelManagerSP::Model::Type::SUPERCOMBO: - progressBar = supercomboProgressBar; - modelFrame = supercomboFrame; - break; - case cereal::ModelManagerSP::Model::Type::NAVIGATION: - progressBar = navigationProgressBar; - modelFrame = navigationFrame; - break; - case cereal::ModelManagerSP::Model::Type::VISION: - progressBar = visionProgressBar; - modelFrame = visionFrame; - break; - case cereal::ModelManagerSP::Model::Type::POLICY: - progressBar = policyProgressBar; - modelFrame = policyFrame; - break; - } - - const auto &progress = model.getArtifact().getDownloadProgress(); - QString line; - - if (progress.getStatus() == cereal::ModelManagerSP::DownloadStatus::DOWNLOADING) { - progressBar->setStyleSheet(progressStyleActive); - progressBar->setValue(progress.getProgress()); - progressBar->setFormat(QString(" %1% - %2").arg(static_cast(progress.getProgress())).arg(modelName)); - device()->resetInteractiveTimeout(); - } else if (progress.getStatus() == cereal::ModelManagerSP::DownloadStatus::DOWNLOADED) { - progressBar->setStyleSheet(progressStyleDone); - progressBar->setFormat(tr(" %1 - %2").arg(modelName, download_status_changed ? tr("downloaded") : tr("ready"))); - } else if (progress.getStatus() == cereal::ModelManagerSP::DownloadStatus::CACHED) { - progressBar->setStyleSheet(progressStyleDone); - progressBar->setFormat(tr(" %1 - %2").arg(modelName, download_status_changed ? tr("from cache") : tr("ready"))); - } else if (progress.getStatus() == cereal::ModelManagerSP::DownloadStatus::FAILED) { - progressBar->setStyleSheet(progressStyleError); - progressBar->setFormat(tr(" download failed - %1").arg(modelName)); - } else { - progressBar->setStyleSheet(progressStyleInactive); - progressBar->setFormat(tr(" pending - %1").arg(modelName)); - } - // keep navigation hidden for now to avoid confusion - if (model.getType() != cereal::ModelManagerSP::Model::Type::NAVIGATION) { - modelFrame->setVisible(true); - } - } - prev_download_status = download_status; -} - -/** - * @brief Gets the name of the currently selected model bundle - * @return Display name of the selected bundle or default model name - */ -QString ModelsPanel::GetActiveModelName() { - if (model_manager.hasActiveBundle()) { - return QString::fromStdString(model_manager.getActiveBundle().getDisplayName()); - } - - return DEFAULT_MODEL; -} - -/** - * @brief Gets the short name of the currently selected model bundle - * @return Display short name of the selected bundle or default model name - */ -QString ModelsPanel::GetActiveModelInternalName() { - if (model_manager.hasActiveBundle()) { - return QString::fromStdString(model_manager.getActiveBundle().getInternalName()); - } - return DEFAULT_MODEL; -} - -void ModelsPanel::updateModelManagerState() { - const SubMaster &sm = *(uiStateSP()->sm); - model_manager = sm["modelManagerSP"].getModelManagerSP(); -} - -/** - * @brief Handles the model bundle selection button click - * Displays available bundles, allows selection, and initiates download - */ -void ModelsPanel::handleCurrentModelLblBtnClicked() { - currentModelLblBtn->setEnabled(false); - currentModelLblBtn->setValue(tr("Fetching models...")); - - // Create mapping of bundle indices to display names - QMap index_to_bundle; - const auto bundles = model_manager.getAvailableBundles(); - for (const auto &bundle: bundles) { - index_to_bundle.insert(bundle.getIndex(), QString::fromStdString(bundle.getDisplayName())); - } - - // Sort bundles by index in descending order - QStringList bundleNames; - // Add "Default" as the first option - bundleNames.append(DEFAULT_MODEL); - - auto indices = index_to_bundle.keys(); - std::sort(indices.begin(), indices.end(), std::greater()); - for (const auto &index: indices) { - bundleNames.append(index_to_bundle[index]); - } - - currentModelLblBtn->setValue(GetActiveModelInternalName()); - - const QString selectedBundleName = MultiOptionDialog::getSelection( - tr("Select a Model"), bundleNames, GetActiveModelName(), this); - - if (selectedBundleName.isEmpty() || !canContinueOnMeteredDialog()) { - return; - } - - // Handle "Stock" selection differently - if (selectedBundleName == DEFAULT_MODEL) { - params.remove("ModelManager_ActiveBundle"); - currentModelLblBtn->setValue(tr("Default")); - showResetParamsDialog(); - } else { - // Find selected bundle and initiate download - for (const auto &bundle: bundles) { - if (QString::fromStdString(bundle.getDisplayName()) == selectedBundleName) { - params.put("ModelManager_DownloadIndex", std::to_string(bundle.getIndex())); - if (bundle.getGeneration() != model_manager.getActiveBundle().getGeneration()) { - showResetParamsDialog(); - } - break; - } - } - } - - updateLabels(); -} - -/** - * @brief Updates the UI elements based on current state - */ -void ModelsPanel::updateLabels() { - if (!isVisible()) { - return; - } - - updateModelManagerState(); - handleBundleDownloadProgress(); - currentModelLblBtn->setEnabled(!is_onroad && !isDownloading()); - currentModelLblBtn->setValue(GetActiveModelInternalName()); -} - -/** - * @brief Shows dialog prompting user to reset calibration after model download - */ -void ModelsPanel::showResetParamsDialog() { - const auto confirmMsg = QString("%1

%2

%3") - .arg(tr("Model download has started in the background.")) - .arg(tr("We STRONGLY suggest you to reset calibration.")) - .arg(tr("Would you like to do that now?")); - const auto button_text = tr("Reset Calibration"); - - QString content("

" + tr("Driving Model Selector") + "


" - "

" + confirmMsg + "

"); - - if (showConfirmationDialog(content, button_text, false)) { - params.remove("CalibrationParams"); - params.remove("LiveTorqueParameters"); - } -} diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/models_panel.h b/selfdrive/ui/sunnypilot/qt/offroad/settings/models_panel.h deleted file mode 100644 index 8b8cf69759..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/models_panel.h +++ /dev/null @@ -1,77 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/settings.h" - -class ModelsPanel : public QWidget { - Q_OBJECT - -public: - explicit ModelsPanel(QWidget *parent = nullptr); - -private: - QString GetActiveModelName(); - QString GetActiveModelInternalName(); - void updateModelManagerState(); - - bool isDownloading() const { - if (!model_manager.hasSelectedBundle()) { - return false; - } - - const auto &selected_bundle = model_manager.getSelectedBundle(); - return selected_bundle.getStatus() == cereal::ModelManagerSP::DownloadStatus::DOWNLOADING; - } - - // UI update related methods - void updateLabels(); - void handleCurrentModelLblBtnClicked(); - void handleBundleDownloadProgress(); - void showResetParamsDialog(); - QProgressBar* createProgressBar(QWidget *parent); - QFrame* createModelDetailFrame(QWidget *parent, QString &typeName, QProgressBar *progressBar); - cereal::ModelManagerSP::Reader model_manager; - cereal::ModelManagerSP::DownloadStatus download_status{}; - cereal::ModelManagerSP::DownloadStatus prev_download_status{}; - - bool canContinueOnMeteredDialog() { - if (!is_metered) return true; - return showConfirmationDialog(QString(), QString(), is_metered); - } - - inline bool showConfirmationDialog(const QString &message = QString(), const QString &confirmButtonText = QString(), const bool show_metered_warning = false) { - return showConfirmationDialog(this, message, confirmButtonText, show_metered_warning); - } - - static inline bool showConfirmationDialog(QWidget *parent, const QString &message = QString(), const QString &confirmButtonText = QString(), const bool show_metered_warning = false) { - const QString warning_message = show_metered_warning ? tr("Warning: You are on a metered connection!") : QString(); - const QString final_message = QString("%1%2").arg(!message.isEmpty() ? message + "\n" : QString(), warning_message); - const QString final_buttonText = !confirmButtonText.isEmpty() ? confirmButtonText : QString(tr("Continue") + " %1").arg(show_metered_warning ? tr("on Metered") : ""); - - return ConfirmationDialog(final_message, final_buttonText, tr("Cancel"), true, parent).exec(); - } - - bool is_metered{}; - bool is_wifi{}; - bool is_onroad = false; - - ButtonControlSP *currentModelLblBtn; - QProgressBar *supercomboProgressBar; - QFrame *supercomboFrame; - QProgressBar *navigationProgressBar; - QFrame *navigationFrame; - QProgressBar *visionProgressBar; - QFrame *visionFrame; - QProgressBar *policyProgressBar; - QFrame *policyFrame; - Params params; - -}; diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/osm/locations_fetcher.h b/selfdrive/ui/sunnypilot/qt/offroad/settings/osm/locations_fetcher.h deleted file mode 100644 index 32d169ad15..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/osm/locations_fetcher.h +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include // for std::sort -#include -#include -#include - -#include -#include - -#include "selfdrive/ui/sunnypilot/qt/common/json_fetcher.h" - -static const std::tuple defaultLocation = std::make_tuple("== None ==", ""); - -// New class LocationsFetcher that handles web requests and JSON parsing -class LocationsFetcher { -public: - inline std::vector > - getLocationsFromURL(const QUrl &url, const std::tuple &customLocation = defaultLocation) const { - // Initialize an empty vector to hold the locations - std::vector > locations; - - JsonFetcher fetcher; - QJsonObject json = fetcher.getJsonFromURL(url.toString()); - - for (auto it = json.begin(); it != json.end(); ++it) { - QString code = it.key(); - QJsonObject obj = it.value().toObject(); - QString fullName = obj["full_name"].toString(); - - locations.push_back(std::make_tuple(fullName, code, QString(), QString())); - } - // Sort locations by full name - std::sort(locations.begin(), locations.end(), [](const auto &lhs, const auto &rhs) { - return std::get<0>(lhs) < std::get<0>(rhs); // Compare full names - }); - // Optionally, you can now add defaultName entry at the beginning - locations.insert(locations.begin(), std::tuple_cat(customLocation, std::make_tuple("", ""))); - return locations; - } - - inline std::vector > - getLocationsFromURL(const QString &url, const std::tuple &customLocation = defaultLocation) const { - return getLocationsFromURL(QUrl(url), customLocation); - } - - inline std::vector > - getOsmLocations(const std::tuple &customLocation = defaultLocation) const { - return getLocationsFromURL( "https://raw.githubusercontent.com/pfeiferj/openpilot-mapd/main/nation_bounding_boxes.json", customLocation); - } - - inline std::vector > - getUsStatesLocations(const std::tuple &customLocation = defaultLocation) const { - return getLocationsFromURL( "https://raw.githubusercontent.com/pfeiferj/openpilot-mapd/main/us_states_bounding_boxes.json", customLocation); - } -}; diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/osm/models_fetcher.cc b/selfdrive/ui/sunnypilot/qt/offroad/settings/osm/models_fetcher.cc deleted file mode 100644 index b67e41e09d..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/osm/models_fetcher.cc +++ /dev/null @@ -1,158 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/osm/models_fetcher.h" - -#include - -ModelsFetcher::ModelsFetcher(QObject *parent) : QObject(parent) { - manager = new QNetworkAccessManager(this); -} - -QByteArray ModelsFetcher::verifyFileHash(const QString &filePath, const QString &expectedHash, bool &hashMatches) { - hashMatches = false; // Default to false - QByteArray fileData; - - if (expectedHash.isEmpty()) { - // If no hash is provided, assume verification isn't required but return the file data - hashMatches = true; - } else { - QFile file(filePath); - if (file.open(QIODevice::ReadOnly)) { - QCryptographicHash hash(QCryptographicHash::Sha256); // Or your chosen algorithm - fileData = file.readAll(); // Read the file data once - hash.addData(fileData); - file.close(); - - QString currentHash = QString(hash.result().toHex()); - hashMatches = (currentHash == expectedHash); - } - } - - // Return the file data if hash matches or no hash was provided; empty otherwise - return hashMatches ? fileData : QByteArray(); -} - - -void ModelsFetcher::download(const DownloadInfo &downloadInfo, const QString &filename, const QString &destinationPath) { - QString fullPath = destinationPath + "/" + filename; - QFileInfo fileInfo(fullPath); - bool hashMatches = false; - QByteArray data = verifyFileHash(fullPath, downloadInfo.sha256, hashMatches); - - if (fileInfo.exists() && hashMatches) { - // Hash matches or no hash provided, and we have the file data - LOGD("File already downloaded and verified: %s", filename.toStdString().c_str()); - emit downloadProgress(100); - emit downloadComplete(data, true); // Use the data returned from verifyFileHash - return; // Exit early - } - - // Proceed with download if file does not exist or hash verification failed - QNetworkRequest request(downloadInfo.url); - QNetworkReply *reply = manager->get(request); - connect(reply, &QNetworkReply::downloadProgress, this, &ModelsFetcher::onDownloadProgress); - connect(reply, &QNetworkReply::finished, this, [this, reply, destinationPath, filename, downloadInfo]() { - onFinished(reply, destinationPath, filename, downloadInfo.sha256); - }); -} - -QString extractFileName(const QString &contentDisposition) { - const QString filenameTag = "filename="; - const int idx = contentDisposition.indexOf(filenameTag); - if (idx < 0) { - return QString(); - } - - QString filename = contentDisposition.mid(idx + filenameTag.length()); - if (filename.startsWith("\"") && filename.endsWith("\"")) { - return filename.mid(1, filename.size() - 2); - } - - return filename; -} - -void ModelsFetcher::onFinished(QNetworkReply *reply, const QString &destinationPath, const QString &filename, const QString &expectedHash) { - // Handle download error - if (reply->error()) { - return; // Possibly emit a signal or log an error as per your error handling policy - } - - const QByteArray data = reply->readAll(); - - QString finalFilename = filename; - if (finalFilename.isEmpty()) { - finalFilename = extractFileName(reply->header(QNetworkRequest::ContentDispositionHeader).toString()); - } - - QString finalPath = QDir(destinationPath).filePath(finalFilename); - - // Save the downloaded file - QFile file(finalPath); - //ensure if the path exists and if not create it - if (!QDir().mkpath(destinationPath)) { - LOGE("Unable to create directory: %s", destinationPath.toStdString().c_str()); - emit downloadFailed(filename); - return; // Stop further processing - } - - //Retry the file open and write 3 times with a little delay between each retry - for (int i = 0; i < 3; i++) { - if (file.isOpen()) break; - - file.open(QIODevice::WriteOnly); - if (!file.isOpen()) QThread::msleep(100); - } - - // If the file is still not open, log an error and emit a failure signal - if (!file.isOpen()) { - LOGE("Unable to open file for writing: %s", finalPath.toStdString().c_str()); - emit downloadFailed(filename); - return; // Stop further processing - } - - file.write(data); - file.close(); - - bool hashMatches = false; - verifyFileHash(finalPath, expectedHash, hashMatches); - - // Verify the file hash if expectedHash is provided - if (!expectedHash.isEmpty() && !hashMatches) { - LOGE("The downloaded file didn't pass the hash validation!: %s", filename.toStdString().c_str()); - // Hash verification failed, handle accordingly - // This could involve deleting the file, logging an error, or emitting a failure signal - QFile::remove(finalPath); // Example action: Remove the invalid file - emit downloadFailed(filename); - return; // Stop further processing - } - - emit downloadComplete(data, false); // Emit your success signal -} - -void ModelsFetcher::onDownloadProgress(qint64 bytesReceived, qint64 bytesTotal) { - const double progress = (bytesReceived * 100.0) / bytesTotal; - emit downloadProgress(progress); -} - -std::vector ModelsFetcher::getModelsFromURL(const QUrl &url) { - std::vector models; - JsonFetcher fetcher; - QJsonObject json = fetcher.getJsonFromURL(url.toString()); - for (auto it = json.begin(); it != json.end(); ++it) { - models.push_back(Model(it.value().toObject())); - } - return models; -} - -std::vector ModelsFetcher::getModelsFromURL(const QString &url) { - return getModelsFromURL(QUrl(url)); -} - -std::vector ModelsFetcher::getModelsFromURL() { - return getModelsFromURL("https://docs.sunnypilot.ai/models_v5.json"); -} diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/osm/models_fetcher.h b/selfdrive/ui/sunnypilot/qt/offroad/settings/osm/models_fetcher.h deleted file mode 100644 index 73890e9d5a..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/osm/models_fetcher.h +++ /dev/null @@ -1,143 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include // for std::sort -#include -#include -#include - -#include -#include -#include - -#include "common/swaglog.h" -#include "common/util.h" -#include "selfdrive/ui/sunnypilot/ui.h" -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/sunnypilot/qt/common/json_fetcher.h" -#ifdef SUNNYPILOT -#include "selfdrive/ui/sunnypilot/qt/widgets/controls.h" -#else -#include "selfdrive/ui/qt/widgets/controls.h" -#endif -#include "system/hardware/hw.h" - -static const QString MODELS_PATH = Hardware::PC() ? QDir::homePath() + "/.comma/media/0/models/" : "/data/media/0/models/"; - -struct DownloadInfo { - QString url; - QString sha256; -}; - -// New class ModelsFetcher with a new function that handles web requests and JSON parsing for the new JSON structure -class Model { -public: - explicit Model(const QJsonObject &json) { - displayName = json["display_name"].toString(); - fullName = json["full_name"].toString(); - fileName = json["file_name"].toString(); - - // Parse downloadUri as an object - QJsonObject downloadUriObj = json["download_uri"].toObject(); - downloadUri.url = downloadUriObj["url"].toString(); - downloadUri.sha256 = downloadUriObj["sha256"].toString(); - - fullNameNav = json["full_name_nav"].toString(); - fileNameNav = json["file_name_nav"].toString(); - - // Parse downloadUriNav as an object - QJsonObject downloadUriNavObj = json["download_uri_nav"].toObject(); - downloadUriNav.url = downloadUriNavObj["url"].toString(); - downloadUriNav.sha256 = downloadUriNavObj["sha256"].toString(); - - fullNameMetadata = json["full_name_metadata"].toString(); - fileNameMetadata = json["file_name_metadata"].toString(); - - // Parse downloadUriMetadata as an object - QJsonObject downloadUriMetadataObj = json["download_uri_metadata"].toObject(); - downloadUriMetadata.url = downloadUriMetadataObj["url"].toString(); - downloadUriMetadata.sha256 = downloadUriMetadataObj["sha256"].toString(); - - index = json["index"].toString(); - environment = json["environment"].toString(); - generation = json["generation"].toString(); - } - - // Method to convert model back to QJsonObject, if needed - QJsonObject toJson() const { - QJsonObject json; - json["display_name"] = displayName; - json["full_name"] = fullName; - json["file_name"] = fileName; - - QJsonObject uriObj; - uriObj["url"] = downloadUri.url; - uriObj["sha256"] = downloadUri.sha256; - json["download_uri"] = uriObj; - - QJsonObject uriNavObj; - uriNavObj["url"] = downloadUriNav.url; - uriNavObj["sha256"] = downloadUriNav.sha256; - json["download_uri_nav"] = uriNavObj; - - QJsonObject uriMetadataObj; - uriMetadataObj["url"] = downloadUriMetadata.url; - uriMetadataObj["sha256"] = downloadUriMetadata.sha256; - json["download_uri_metadata"] = uriMetadataObj; - - json["full_name_nav"] = fullNameNav; - json["file_name_nav"] = fileNameNav; - json["full_name_metadata"] = fullNameMetadata; - json["file_name_metadata"] = fileNameMetadata; - json["index"] = index; - json["environment"] = environment; - json["generation"] = generation; - return json; - } - - QString displayName; - QString fullName; - QString fileName; - DownloadInfo downloadUri; - DownloadInfo downloadUriNav; - DownloadInfo downloadUriMetadata; - - QString fullNameNav; - QString fileNameNav; - QString fullNameMetadata; - QString fileNameMetadata; - QString index; - QString environment; - QString generation; -}; - -class ModelsFetcher : public QObject { - Q_OBJECT - -public: - explicit ModelsFetcher(QObject *parent = nullptr); - void download(const DownloadInfo &url, const QString &filename = "", const QString &destinationPath = MODELS_PATH); - static std::vector getModelsFromURL(const QUrl &url); - static std::vector getModelsFromURL(const QString &url); - static std::vector getModelsFromURL(); - -signals: - void downloadProgress(double percentage); - void downloadComplete(const QByteArray &data, bool fromCache = false); - void downloadFailed(const QString &filename); - -private: - // static bool verifyFileHash(const QString& filePath, const QString& expectedHash); - static QByteArray verifyFileHash(const QString &filePath, const QString &expectedHash, bool &hashMatches); - void onDownloadProgress(qint64 bytesReceived, qint64 bytesTotal); - void onFinished(QNetworkReply *reply, const QString &destinationPath, const QString &filename, - const QString &expectedHash); - - QNetworkAccessManager *manager; -}; diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/osm_panel.cc b/selfdrive/ui/sunnypilot/qt/offroad/settings/osm_panel.cc deleted file mode 100644 index 332fd71a18..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/osm_panel.cc +++ /dev/null @@ -1,283 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/osm_panel.h" - -#include -#include -#include - -#include "common/swaglog.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/scrollview.h" - -OsmPanel::OsmPanel(QWidget *parent) : QFrame(parent) { - main_layout = new QStackedLayout(this); - - const auto list = new ListWidgetSP(this, false); - list->addItem(mapdVersion = new LabelControlSP(tr("Mapd Version"), "Loading...")); - list->addItem(setupOsmDeleteMapsButton(parent)); - list->addItem(offlineMapsETA = new LabelControlSP(tr("Offline Maps ETA"), "")); - list->addItem(offlineMapsElapsed = new LabelControlSP(tr("Time Elapsed"), "")); - list->addItem(setupOsmUpdateButton(parent)); - list->addItem(setupOsmDownloadButton(parent)); - list->addItem(setupUsStatesButton(parent)); - - connect(uiStateSP(), &UIStateSP::offroadTransition, [=](bool offroad) { - updateLabels(); - }); - - timer = new QTimer(this); - connect(timer, &QTimer::timeout, this, QOverload<>::of(&OsmPanel::updateLabels)); - timer->start(FAST_REFRESH_INTERVAL); // Time specified in milliseconds. - updateLabels(); - - osmScreen = new QWidget(this); - auto *vlayout = new QVBoxLayout(osmScreen); - vlayout->setContentsMargins(50, 20, 50, 20); - vlayout->addWidget(new ScrollViewSP(list, this), 1); - main_layout->addWidget(osmScreen); -} - -ButtonControlSP *OsmPanel::setupOsmDeleteMapsButton(QWidget *parent) { - osmDeleteMapsBtn = new ButtonControlSP(tr("Downloaded Maps"), tr("DELETE")); // Updated on updateLabels() - connect(osmDeleteMapsBtn, &ButtonControlSP::clicked, [=]() { - if (showConfirmationDialog(parent, tr("This will delete ALL downloaded maps\n\nAre you sure you want to delete all the maps?"), tr("Yes, delete all the maps."))) { - QtConcurrent::run([=]() { - QDir dir(MAP_PATH); - osmDeleteMapsBtn->setEnabled(false); - osmDeleteMapsBtn->setText("⌛"); - dir.removeRecursively(); - updateMapSize(); - osmDeleteMapsBtn->setEnabled(true); - osmDeleteMapsBtn->setText(tr("DELETE")); - }); - updateLabels(); - } - }); - return osmDeleteMapsBtn; -} - -ButtonControlSP *OsmPanel::setupOsmUpdateButton(QWidget *parent) { - osmUpdateBtn = new ButtonControlSP(tr("Database Update"), tr("CHECK")); // Updated on updateLabels() - connect(osmUpdateBtn, &ButtonControlSP::clicked, [=]() { - if (osm_download_in_progress && !download_failed_state) { - updateLabels(); - } else if (showConfirmationDialog(parent)) { - osm_download_in_progress = true; - params.putBool("OsmDbUpdatesCheck", true); - updateLabels(); - } - }); - return osmUpdateBtn; -} - -ButtonControlSP *OsmPanel::setupOsmDownloadButton(QWidget *parent) { - osmDownloadBtn = new ButtonControlSP(tr("Country"), tr("SELECT")); - connect(osmDownloadBtn, &ButtonControlSP::clicked, [=]() { - osmDownloadBtn->setEnabled(false); - osmDownloadBtn->setValue(tr("Fetching Country list...")); - const std::vector > locations = getOsmLocations(); - osmDownloadBtn->setEnabled(true); - osmDownloadBtn->setValue(""); - const QString initTitle = QString::fromStdString(params.get("OsmLocationTitle")); - const QString currentTitle = ((initTitle == "== None ==") || (initTitle.length() == 0)) ? "== None ==" : initTitle; - - QStringList locationTitles; - for (auto &loc: locations) { - locationTitles.push_back(std::get<0>(loc)); - } - - const QString selection = MultiOptionDialog::getSelection(tr("Country"), locationTitles, currentTitle, this); - if (!selection.isEmpty()) { - params.put("OsmLocal", "1"); - params.put("OsmLocationTitle", selection.toStdString()); - for (auto &loc: locations) { - if (std::get<0>(loc) == selection) { - params.put("OsmLocationName", std::get<1>(loc).toStdString()); - break; - } - } - if (params.get("OsmLocationName") == "US") { - usStatesBtn->click(); - return; - } else if (selection != "== None ==") { - if (showConfirmationDialog(parent)) { - osm_download_in_progress = true; - params.putBool("OsmDbUpdatesCheck", true); - updateLabels(); - } - } - } - updateLabels(); - }); - return osmDownloadBtn; -} - -ButtonControlSP *OsmPanel::setupUsStatesButton(QWidget *parent) { - usStatesBtn = new ButtonControlSP(tr("State"), tr("SELECT")); - connect(usStatesBtn, &ButtonControlSP::clicked, [=]() { - const std::tuple allStatesOption = std::make_tuple("All States (~4.8 GB)", "All"); - usStatesBtn->setEnabled(false); - usStatesBtn->setValue(tr("Fetching State list...")); - const std::vector > locations = - getUsStatesLocations(allStatesOption); - usStatesBtn->setEnabled(true); - usStatesBtn->setValue(""); - const QString initTitle = QString::fromStdString(params.get("OsmStateTitle")); - const QString currentTitle = ((initTitle == std::get<0>(allStatesOption)) || (initTitle.length() == 0)) ? tr("All") : initTitle; - - QStringList locationTitles; - for (auto &loc: locations) { - locationTitles.push_back(std::get<0>(loc)); - } - - const QString selection = MultiOptionDialog::getSelection(tr("State"), locationTitles, currentTitle, this); - if (!selection.isEmpty()) { - params.put("OsmStateTitle", selection.toStdString()); - for (auto &loc: locations) { - if (std::get<0>(loc) == selection) { - params.put("OsmStateName", std::get<1>(loc).toStdString()); - break; - } - } - usStatesBtn->setValue(selection); - if (showConfirmationDialog(parent)) { - osm_download_in_progress = true; - params.putBool("OsmDbUpdatesCheck", true); - updateLabels(); - } - } - updateLabels(); - }); - usStatesBtn->setVisible(false); // initially hidden - return usStatesBtn; -} - -void OsmPanel::showEvent(QShowEvent *event) { - updateLabels(); // For snappier feeling - if (!timer->isActive()) { - timer->start(FAST_REFRESH_INTERVAL); - } -} - -void OsmPanel::hideEvent(QHideEvent *event) { - if (timer->isActive()) { - timer->stop(); - } -} - - -void OsmPanel::updateLabels() { - if (!isVisible()) { - return; - } - mapd_version = params.get("MapdVersion"); - mapdVersion->setText(mapd_version.c_str()); - - updateMapSize(); - osm_download_locations = mem_params.get("OSMDownloadLocations"); - osm_download_in_progress = !osm_download_locations.empty(); - - timer->setInterval(osm_download_in_progress ? FAST_REFRESH_INTERVAL : SLOW_REFRESH_INTERVAL); - LOGT("Timer Interval %d", timer->interval()); - - const std::string osmLastDownloadTimeStr = params.get("OsmDownloadedDate"); - if (!lastDownloadedTimePoint.has_value() && !osmLastDownloadTimeStr.empty()) { - const double osmLastDownloadTime = std::stod(osmLastDownloadTimeStr); - lastDownloadedTimePoint = std::chrono::system_clock::from_time_t(static_cast(osmLastDownloadTime)); - } - - osmDownloadBtn->setEnabled(!osm_download_in_progress); - usStatesBtn->setEnabled(!osm_download_in_progress); - - updateDownloadProgress(); - - const QString locationName = QString::fromStdString(params.get("OsmLocationName")); - const bool isUs = !locationName.isEmpty() && locationName == "US"; - usStatesBtn->setVisible(isUs); - - if (!locationName.isEmpty()) { - if (!isUs) { - params.remove("OsmStateName"); - params.remove("OsmStateTitle"); - } - osmUpdateBtn->setVisible(true); - } else { - params.remove("OsmLocal"); - params.remove("OsmLocationName"); - params.remove("OsmLocationTitle"); - params.remove("OsmStateName"); - params.remove("OsmStateTitle"); - osmUpdateBtn->setVisible(false); - usStatesBtn->setVisible(false); - } - - osmDownloadBtn->setValue(QString::fromStdString(params.get("OsmLocationTitle"))); - usStatesBtn->setValue(QString::fromStdString(params.get("OsmStateTitle"))); - update(); -} - -void OsmPanel::updateDownloadProgress() { - const auto pending_update_check = params.getBool("OsmDbUpdatesCheck"); - const QJsonObject osmDownloadProgress = QJsonDocument::fromJson(params.get("OSMDownloadProgress").c_str()).object(); - if (osm_download_in_progress && lastDownloadedTimePoint.has_value()) { - offlineMapsETA->setVisible(true); - offlineMapsElapsed->setVisible(true); - offlineMapsETA->setText(calculateETA(osmDownloadProgress, lastDownloadedTimePoint.value())); - offlineMapsElapsed->setText(calculateElapsedTime(osmDownloadProgress, lastDownloadedTimePoint.value())); - } else { - offlineMapsETA->setVisible(false); - offlineMapsElapsed->setVisible(false); - } - - const int total_files = extractIntFromJson(osmDownloadProgress, "total_files"); - const int downloaded_files = extractIntFromJson(osmDownloadProgress, "downloaded_files"); - download_failed_state = total_files && osm_download_in_progress && !lastDownloadedTimePoint.has_value() && downloaded_files < total_files; - - QString updateButtonText = processUpdateStatus(pending_update_check, total_files, downloaded_files, osmDownloadProgress, download_failed_state); - - osmUpdateBtn->setValue(updateButtonText); - osmUpdateBtn->setText(osm_download_in_progress && !download_failed_state ? tr("REFRESH") : tr("UPDATE")); - osmDeleteMapsBtn->setValue(formatSize(mapsDirSize)); -} - -int OsmPanel::extractIntFromJson(const QJsonObject &json, const QString &key) { - return (json.contains(key)) ? json[key].toInt() : 0; -} - -QString OsmPanel::processUpdateStatus(bool pending_update, int total_files, int downloaded_files, const QJsonObject &json, bool failed_state) { - if (pending_update && !osm_download_in_progress && !total_files) { - lastDownloadedTimePoint.reset(); - return tr("Download starting..."); - } else if (failed_state) { - return tr("Error: Invalid download. Retry."); - } else if (osm_download_in_progress && total_files > downloaded_files) { - return formatDownloadStatus(json); - } else if (osm_download_in_progress && downloaded_files >= total_files) { - osm_download_in_progress = false; - lastDownloadedTimePoint.reset(); - return tr("Download complete!"); - } - - if (lastDownloadedTimePoint.has_value()) { - QDateTime dateTime = QDateTime::fromTime_t(std::chrono::system_clock::to_time_t(lastDownloadedTimePoint.value())); //fromMSecsSinceEpoch(duration); - dateTime = dateTime.toLocalTime(); - return QString("%1").arg(dateTime.toString("yyyy-MM-dd HH:mm:ss")); - } - - return ""; -} - -void OsmPanel::updateMapSize() { - if (mapSizeFuture.has_value() && mapSizeFuture.value().isFinished()) { - mapsDirSize = mapSizeFuture.value().result(); - } - - if (!mapSizeFuture.has_value() || !mapSizeFuture.value().isRunning()) { - mapSizeFuture = QtConcurrent::run(getDirSize, MAP_PATH); - } -} diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/osm_panel.h b/selfdrive/ui/sunnypilot/qt/offroad/settings/osm_panel.h deleted file mode 100644 index 171129a11c..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/osm_panel.h +++ /dev/null @@ -1,232 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "selfdrive/ui/qt/network/wifi_manager.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/controls.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/osm/locations_fetcher.h" -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/sunnypilot/ui.h" -#include "system/hardware/hw.h" - -constexpr int FAST_REFRESH_INTERVAL = 1000; // ms -constexpr int SLOW_REFRESH_INTERVAL = 5000; // ms - -static const QString MAP_PATH = Hardware::PC() ? QDir::homePath() + "/.comma/media/0/osm/offline/" : "/data/media/0/osm/offline/"; - -class OsmPanel : public QFrame { - Q_OBJECT - -public: - explicit OsmPanel(QWidget *parent = nullptr); - -private: - QStackedLayout *main_layout = nullptr; - QWidget *osmScreen = nullptr; - Params params; - Params mem_params{Hardware::PC() ? "" : "/dev/shm/params"}; - std::map toggles; - std::optional > mapSizeFuture; - const SubMaster &sm = *uiStateSP()->sm; - - - bool is_onroad = false; - std::string mapd_version; - - bool isWifi() const { return sm["deviceState"].getDeviceState().getNetworkType() == cereal::DeviceState::NetworkType::WIFI; } - bool isMetered() const { return sm["deviceState"].getDeviceState().getNetworkMetered(); } - bool osm_download_in_progress = false; - bool download_failed_state = false; - quint64 mapsDirSize = 0; - - QLabel *osmUpdateLbl; - ButtonControlSP *osmDownloadBtn; - ButtonControlSP *osmUpdateBtn; - ButtonControlSP *usStatesBtn; - ButtonControlSP *osmDeleteMapsBtn; - - ButtonControlSP *setupOsmDeleteMapsButton(QWidget *parent);; - ButtonControlSP *setupOsmUpdateButton(QWidget *parent); - ButtonControlSP *setupOsmDownloadButton(QWidget *parent); - ButtonControlSP *setupUsStatesButton(QWidget *parent); - - QTimer *timer; - std::string osm_download_locations; - // void updateButtonControlSP(ButtonControlSP *btnControl, QWidget *parent, const QString &initTitle, const QString &allStatesOption); - - void showEvent(QShowEvent *event) override; - void hideEvent(QHideEvent *event) override; - void updateLabels(); - void updateDownloadProgress(); - static int extractIntFromJson(const QJsonObject &json, const QString &key); - QString processUpdateStatus(bool pending_update_check, int total_files, int downloaded_files, const QJsonObject &json, bool failed_state); - - ConfirmationDialog *confirmationDialog; - LabelControlSP *mapdVersion; - LabelControlSP *offlineMapsStatus; - LabelControlSP *offlineMapsETA; - LabelControlSP *offlineMapsElapsed; - std::optional lastDownloadedTimePoint; - LocationsFetcher locationsFetcher; - - void updateMapSize(); - - bool showConfirmationDialog(QWidget *parent, - const QString &message = QString(), - const QString &confirmButtonText = QString()) const { - const auto _is_metered = isMetered(); - const QString warning_message = _is_metered ? tr("\n\nWarning: You are on a metered connection!") : QString(); - QString final_message = message.isEmpty() ? tr("This will start the download process and it might take a while to complete.") : message; - final_message += warning_message; // Append the warning message if the connection is metered - - const QString final_buttonText = confirmButtonText.isEmpty() ? (_is_metered ? tr("Continue on Metered") : tr("Start Download")) : confirmButtonText; - - return ConfirmationDialog::confirm(final_message, final_buttonText, parent); - } - - // Refactored methods - std::vector > getOsmLocations(const std::tuple &customLocation = defaultLocation) const { - return locationsFetcher.getOsmLocations(customLocation); - } - - std::vector > getUsStatesLocations(const std::tuple &customLocation = defaultLocation) const { - return locationsFetcher.getUsStatesLocations(customLocation); - } - - static QString formatTime(const long timeInSeconds) { - const long minutes = timeInSeconds / 60; - const long seconds = timeInSeconds % 60; - - QString formattedTime; - if (minutes > 0) { - formattedTime = QString::number(minutes) + tr("m "); - } - formattedTime += QString::number(seconds) + tr("s"); - return formattedTime; - } - - static QString calculateElapsedTime(const QJsonObject &jsonData, const std::chrono::system_clock::time_point &startTime) { - using namespace std::chrono; - if (!jsonData.contains("total_files") || !jsonData.contains("downloaded_files")) - return tr("Calculating..."); - - const int totalFiles = jsonData["total_files"].toInt(); - const int downloadedFiles = jsonData["downloaded_files"].toInt(); - - if (downloadedFiles >= totalFiles || totalFiles <= 0) return tr("Downloaded"); - - const long elapsed = duration_cast(system_clock::now() - startTime).count(); - - if (elapsed == 0 || downloadedFiles == 0) return tr("Calculating..."); - - return formatTime(elapsed); - } - - static QString calculateETA(const QJsonObject &jsonData, const std::chrono::system_clock::time_point &startTime) { - using namespace std::chrono; - static steady_clock::time_point lastUpdateTime = steady_clock::now(); - static std::deque rateHistory; - - constexpr int minDataPoints = 3; - constexpr int historySize = 10; - - static QString lastETA = tr("Calculating ETA..."); - - if (duration_cast(steady_clock::now() - lastUpdateTime).count() < 1) { - return lastETA; - } - - if (!jsonData.contains("total_files") || !jsonData.contains("downloaded_files")) - return lastETA; - - const int totalFiles = jsonData["total_files"].toInt(); - const int downloadedFiles = jsonData["downloaded_files"].toInt(); - - if (totalFiles <= 0 || downloadedFiles >= totalFiles) { - return totalFiles <= 0 ? tr("Ready") : tr("Downloaded"); - } - - const long elapsed = duration_cast(system_clock::now() - startTime).count(); - if (elapsed == 0 || downloadedFiles == 0) return lastETA; - - const double rate = downloadedFiles / static_cast(elapsed); - if (rateHistory.size() >= historySize) rateHistory.pop_front(); - rateHistory.push_back(rate); - - if (rateHistory.size() < minDataPoints) return lastETA; - - double weightedSum = 0; - for (int i = 0, weight = 1; i < rateHistory.size(); ++i, ++weight) { - weightedSum += rateHistory[i] * weight; - } - const double avgRate = 2 * weightedSum / (rateHistory.size() * (rateHistory.size() + 1)); - - const long remainingTime = static_cast((totalFiles - downloadedFiles) / avgRate); - if (remainingTime <= 0) return lastETA; - - lastETA = tr("Time remaining: ") + formatTime(remainingTime); - lastUpdateTime = steady_clock::now(); - return lastETA; - } - - static QString formatDownloadStatus(const QJsonObject &json) { - if (!json.contains("total_files") || !json.contains("downloaded_files")) - return ""; - - const int total_files = json["total_files"].toInt(); - const int downloaded_files = json["downloaded_files"].toInt(); - - if (total_files <= 0) return tr("Ready"); - if (downloaded_files >= total_files) return tr("Downloaded"); - - const int percentage = static_cast(100.0 * downloaded_files / total_files); - return QString::asprintf("%d/%d (%d%%)", downloaded_files, total_files, percentage); - } - - QString formatSize(quint64 size) const { - if (size == 0 && (!mapSizeFuture.has_value() || mapSizeFuture.value().isRunning())) { - return tr("Calculating..."); - } - - constexpr qint64 kb = 1024; - constexpr qint64 mb = 1024 * kb; - constexpr qint64 gb = 1024 * mb; - - if (size < gb) { - const double sizeMB = size / static_cast(mb); - return QString::number(sizeMB, 'f', 2) + " MB"; - } else { - const double sizeGB = size / static_cast(gb); - return QString::number(sizeGB, 'f', 2) + " GB"; - } - } - - static quint64 getDirSize(QString dirPath) { - quint64 size = 0; - const QString actualDirPath = dirPath.startsWith("~") ? dirPath.replace(0, 1, QDir::homePath()) : dirPath; - QDirIterator it(actualDirPath, QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks, QDirIterator::Subdirectories); - while (it.hasNext()) { - it.next(); - if (it.fileInfo().isFile()) { - size += it.fileInfo().size(); - } - } - return size; - } -}; diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/settings.cc b/selfdrive/ui/sunnypilot/qt/offroad/settings/settings.cc deleted file mode 100644 index 05ea5ff899..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/settings.cc +++ /dev/null @@ -1,169 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/settings.h" - -#include "selfdrive/ui/sunnypilot/qt/widgets/scrollview.h" -#include "selfdrive/ui/qt/offroad/developer_panel.h" -#include "selfdrive/ui/qt/offroad/firehose.h" -#include "selfdrive/ui/sunnypilot/qt/network/networking.h" - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/device_panel.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/models_panel.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/software_panel.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/sunnylink_panel.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/lateral_panel.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/longitudinal_panel.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/osm_panel.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/trips_panel.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle_panel.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/visuals_panel.h" - -TogglesPanelSP::TogglesPanelSP(SettingsWindowSP *parent) : TogglesPanel(parent) { - QObject::connect(uiStateSP(), &UIStateSP::uiUpdate, this, &TogglesPanelSP::updateState); -} - -void TogglesPanelSP::updateState(const UIStateSP &s) { - TogglesPanel::updateState(s); -} - -SettingsWindowSP::SettingsWindowSP(QWidget *parent) : SettingsWindow(parent) { - // setup two main layouts - sidebar_widget = new QWidget; - QVBoxLayout *sidebar_layout = new QVBoxLayout(sidebar_widget); - panel_widget = new QStackedWidget(); - - // setup layout for close button - QVBoxLayout *close_btn_layout = new QVBoxLayout; - close_btn_layout->setContentsMargins(0, 0, 0, 20); - - // close button - QPushButton *close_btn = new QPushButton(tr("×")); - close_btn->setStyleSheet(R"( - QPushButton { - font-size: 140px; - padding-bottom: 20px; - border-radius: 76px; - background-color: #292929; - font-weight: 400; - } - QPushButton:pressed { - background-color: #3B3B3B; - } - )"); - close_btn->setFixedSize(152, 152); - close_btn_layout->addWidget(close_btn, 0, Qt::AlignLeft); - QObject::connect(close_btn, &QPushButton::clicked, this, &SettingsWindowSP::closeSettings); - - // setup buttons widget - QWidget *buttons_widget = new QWidget; - QVBoxLayout *buttons_layout = new QVBoxLayout(buttons_widget); - buttons_layout->setMargin(0); - buttons_layout->addSpacing(10); - - // setup panels - DevicePanelSP *device = new DevicePanelSP(this); - QObject::connect(device, &DevicePanelSP::reviewTrainingGuide, this, &SettingsWindowSP::reviewTrainingGuide); - QObject::connect(device, &DevicePanelSP::showDriverView, this, &SettingsWindowSP::showDriverView); - - TogglesPanelSP *toggles = new TogglesPanelSP(this); - QObject::connect(this, &SettingsWindowSP::expandToggleDescription, toggles, &TogglesPanel::expandToggleDescription); - QObject::connect(this, &SettingsWindowSP::scrollToToggle, toggles, &TogglesPanel::scrollToToggle); - - auto networking = new NetworkingSP(this); - QObject::connect(uiState()->prime_state, &PrimeState::changed, networking, &NetworkingSP::setPrimeType); - - QList panels = { - PanelInfo(" " + tr("Device"), device, "../../sunnypilot/selfdrive/assets/offroad/icon_home.svg"), - PanelInfo(" " + tr("Network"), networking, "../assets/icons/network.png"), - PanelInfo(" " + tr("sunnylink"), new SunnylinkPanel(this), "../assets/icons/wifi_strength_full.svg"), - PanelInfo(" " + tr("Toggles"), toggles, "../../sunnypilot/selfdrive/assets/offroad/icon_toggle.png"), - PanelInfo(" " + tr("Software"), new SoftwarePanelSP(this), "../../sunnypilot/selfdrive/assets/offroad/icon_software.png"), - PanelInfo(" " + tr("Models"), new ModelsPanel(this), "../../sunnypilot/selfdrive/assets/offroad/icon_models.png"), - PanelInfo(" " + tr("Steering"), new LateralPanel(this), "../../sunnypilot/selfdrive/assets/offroad/icon_lateral.png"), - PanelInfo(" " + tr("Cruise"), new LongitudinalPanel(this), "../assets/icons/speed_limit.png"), - PanelInfo(" " + tr("Visuals"), new VisualsPanel(this), "../../sunnypilot/selfdrive/assets/offroad/icon_visuals.png"), - PanelInfo(" " + tr("OSM"), new OsmPanel(this), "../../sunnypilot/selfdrive/assets/offroad/icon_map.png"), - PanelInfo(" " + tr("Trips"), new TripsPanel(this), "../../sunnypilot/selfdrive/assets/offroad/icon_trips.png"), - PanelInfo(" " + tr("Vehicle"), new VehiclePanel(this), "../../sunnypilot/selfdrive/assets/offroad/icon_vehicle.png"), - PanelInfo(" " + tr("Firehose"), new FirehosePanel(this), "../../sunnypilot/selfdrive/assets/offroad/icon_firehose.svg"), - PanelInfo(" " + tr("Developer"), new DeveloperPanel(this), "../assets/icons/shell.png"), - }; - - nav_btns = new QButtonGroup(this); - for (auto &[name, panel, icon] : panels) { - QPushButton *btn = new QPushButton(name); - btn->setCheckable(true); - btn->setChecked(nav_btns->buttons().size() == 0); - btn->setIcon(QIcon(QPixmap(icon))); - btn->setIconSize(QSize(70, 70)); - btn->setStyleSheet(R"( - QPushButton { - border-radius: 20px; - width: 400px; - height: 98px; - color: #bdbdbd; - border: none; - background: none; - font-size: 50px; - font-weight: 500; - text-align: left; - padding-left: 22px; - } - QPushButton:checked { - background-color: #696868; - color: white; - } - QPushButton:pressed { - color: #ADADAD; - } - )"); - btn->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding); - nav_btns->addButton(btn); - buttons_layout->addWidget(btn, 0, Qt::AlignLeft | Qt::AlignBottom); - - const int lr_margin = (name != (" " + tr("Network"))) ? 50 : 0; // Network panel handles its own margins - panel->setContentsMargins(lr_margin, 25, lr_margin, 25); - - ScrollViewSP *panel_frame = new ScrollViewSP(panel, this); - panel_widget->addWidget(panel_frame); - - QObject::connect(btn, &QPushButton::clicked, [=, w = panel_frame]() { - btn->setChecked(true); - panel_widget->setCurrentWidget(w); - }); - } - sidebar_layout->setContentsMargins(50, 50, 25, 50); - - // main settings layout, sidebar + main panel - QHBoxLayout *main_layout = new QHBoxLayout(this); - - // add layout for close button - sidebar_layout->addLayout(close_btn_layout); - - // add layout for buttons scrolling - ScrollViewSP *buttons_scrollview = new ScrollViewSP(buttons_widget, this); - sidebar_layout->addWidget(buttons_scrollview); - - sidebar_widget->setFixedWidth(500); - main_layout->addWidget(sidebar_widget); - main_layout->addWidget(panel_widget); - - setStyleSheet(R"( - * { - color: white; - font-size: 50px; - } - SettingsWindow { - background-color: black; - } - QStackedWidget, ScrollViewSP { - background-color: black; - border-radius: 30px; - } - )"); -} diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/settings.h b/selfdrive/ui/sunnypilot/qt/offroad/settings/settings.h deleted file mode 100644 index ff25d3b64f..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/settings.h +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include -#include - -#include "selfdrive/ui/qt/offroad/settings.h" - -inline bool isBrandInList(const std::string &brand, const std::vector &list) { - return std::find(list.begin(), list.end(), brand) != list.end(); -} - -class SettingsWindowSP : public SettingsWindow { - Q_OBJECT - -public: - explicit SettingsWindowSP(QWidget *parent = nullptr); - -protected: - struct PanelInfo { - QString name; - QWidget *widget; - QString icon; - - PanelInfo(const QString &name, QWidget *widget, const QString &icon) : name(name), widget(widget), icon(icon) {} - }; -}; - -class TogglesPanelSP : public TogglesPanel { - Q_OBJECT - -public: - explicit TogglesPanelSP(SettingsWindowSP *parent); - -private slots: - void updateState(const UIStateSP &s); -}; diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/software_panel.cc b/selfdrive/ui/sunnypilot/qt/offroad/settings/software_panel.cc deleted file mode 100644 index 9430d02ba8..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/software_panel.cc +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/software_panel.h" - -SoftwarePanelSP::SoftwarePanelSP(QWidget *parent) : SoftwarePanel(parent) { - // branch selector - QObject::disconnect(targetBranchBtn, nullptr, nullptr, nullptr); - connect(targetBranchBtn, &ButtonControlSP::clicked, [=]() { - InputDialog d(tr("Search Branch"), this, tr("Enter search keywords, or leave blank to list all branches."), false); - d.setMinLength(0); - const int ret = d.exec(); - if (ret) { - searchBranches(d.text()); - } - }); -} - -/** - * @brief Searches for available branches based on a query string, presents the results in a dialog, - * and updates the target branch if a selection is made. - * - * This function filters the list of branches based on the provided query, and displays the filtered branches in a selection dialog. - * If a branch is selected, the "UpdaterTargetBranch" parameter is updated and a check for updates is triggered. - * If no branches are found matching the query, an alert dialog is displayed. - * - * @param query The search query string. - */ -void SoftwarePanelSP::searchBranches(const QString &query) { - - QStringList branches = QString::fromStdString(params.get("UpdaterAvailableBranches")).split(","); - QStringList results = searchFromList(query, branches); - results.sort(); - - if (results.isEmpty()) { - ConfirmationDialog::alert(tr("No branches found for keywords: %1").arg(query), this); - return; - } - - QString selected_branch = MultiOptionDialog::getSelection(tr("Select a branch"), results, "", this); - - if (!selected_branch.isEmpty()) { - params.put("UpdaterTargetBranch", selected_branch.toStdString()); - targetBranchBtn->setValue(selected_branch); - checkForUpdates(); - } -} diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/software_panel.h b/selfdrive/ui/sunnypilot/qt/offroad/settings/software_panel.h deleted file mode 100644 index 56d8b9be5b..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/software_panel.h +++ /dev/null @@ -1,22 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/sunnypilot/ui.h" -#include "selfdrive/ui/sunnypilot/qt/util.h" -#include "selfdrive/ui/qt/offroad/settings.h" - -class SoftwarePanelSP final : public SoftwarePanel { - Q_OBJECT - -public: - explicit SoftwarePanelSP(QWidget *parent = nullptr); - -private: - void searchBranches(const QString &query); -}; diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/sunnylink/sponsor_widget.cc b/selfdrive/ui/sunnypilot/qt/offroad/settings/sunnylink/sponsor_widget.cc deleted file mode 100644 index 7b5ce48238..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/sunnylink/sponsor_widget.cc +++ /dev/null @@ -1,142 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/sunnylink/sponsor_widget.h" - -#include "selfdrive/ui/sunnypilot/ui.h" -#include "selfdrive/ui/sunnypilot/qt/api.h" -#include "selfdrive/ui/sunnypilot/qt/util.h" -#include "selfdrive/ui/sunnypilot/qt/network/sunnylink/sunnylink_client.h" - -// Sponsor Upsell -using qrcodegen::QrCode; - -SunnylinkSponsorQRWidget::SunnylinkSponsorQRWidget(bool sponsor_pair, QWidget* parent) : QWidget(parent), sponsor_pair(sponsor_pair) { - timer = new QTimer(this); - connect(timer, &QTimer::timeout, this, &SunnylinkSponsorQRWidget::refresh); -} - -void SunnylinkSponsorQRWidget::showEvent(QShowEvent *event) { - refresh(); - timer->start(5 * 60 * 1000); - device()->setOffroadBrightness(100); -} - -void SunnylinkSponsorQRWidget::hideEvent(QHideEvent *event) { - timer->stop(); - device()->setOffroadBrightness(BACKLIGHT_OFFROAD); -} - -void SunnylinkSponsorQRWidget::refresh() { - QString qrString; - - if (sponsor_pair) { - QString token = SunnylinkApi::create_jwt({}, 3600, true); - auto sl_dongle_id = getSunnylinkDongleId(); - QByteArray payload = QString("1|" + sl_dongle_id.value_or("") + "|" + token).toUtf8().toBase64(); - qrString = SUNNYLINK_BASE_URL + "/sso?state=" + payload; - } else { - qrString = "https://github.com/sponsors/sunnyhaibin"; - } - - this->updateQrCode(qrString); - update(); -} - -void SunnylinkSponsorQRWidget::updateQrCode(const QString &text) { - QrCode qr = QrCode::encodeText(text.toUtf8().data(), QrCode::Ecc::LOW); - qint32 sz = qr.getSize(); - QImage im(sz, sz, QImage::Format_RGB32); - - QRgb black = qRgb(0, 0, 0); - QRgb white = qRgb(255, 255, 255); - for (int y = 0; y < sz; y++) { - for (int x = 0; x < sz; x++) { - im.setPixel(x, y, qr.getModule(x, y) ? black : white); - } - } - - // Integer division to prevent anti-aliasing - int final_sz = ((width() / sz) - 1) * sz; - img = QPixmap::fromImage(im.scaled(final_sz, final_sz, Qt::KeepAspectRatio), Qt::MonoOnly); -} - -void SunnylinkSponsorQRWidget::paintEvent(QPaintEvent *e) { - QPainter p(this); - p.fillRect(rect(), Qt::white); - - QSize s = (size() - img.size()) / 2; - p.drawPixmap(s.width(), s.height(), img); -} - -QStringList SunnylinkSponsorPopup::getInstructions(bool sponsor_pair) { - QStringList instructions; - if (sponsor_pair) { - instructions << tr("Scan the QR code to login to your GitHub account") - << tr("Follow the prompts to complete the pairing process") - << tr("Re-enter the \"sunnylink\" panel to verify sponsorship status") - << tr("If sponsorship status was not updated, please contact a moderator on Discord at https://discord.gg/sunnypilot"); - } else { - instructions << tr("Scan the QR code to visit sunnyhaibin's GitHub Sponsors page") - << tr("Choose your sponsorship tier and confirm your support") - << tr("Join our community on Discord at https://discord.gg/sunnypilot and reach out to a moderator to confirm your sponsor status"); - } - return instructions; -} - -SunnylinkSponsorPopup::SunnylinkSponsorPopup(bool sponsor_pair, QWidget *parent) : DialogBase(parent), sponsor_pair(sponsor_pair) { - auto *hlayout = new QHBoxLayout(this); - auto sunnylink_client = new SunnylinkClient(this); - hlayout->setContentsMargins(0, 0, 0, 0); - hlayout->setSpacing(0); - - setStyleSheet("SunnylinkSponsorPopup { background-color: #E0E0E0; }"); - - // text - auto vlayout = new QVBoxLayout(); - vlayout->setContentsMargins(85, 70, 50, 70); - vlayout->setSpacing(50); - hlayout->addLayout(vlayout, 1); - { - auto close = new QPushButton(QIcon(":/icons/close.svg"), "", this); - close->setIconSize(QSize(80, 80)); - close->setStyleSheet("border: none;"); - vlayout->addWidget(close, 0, Qt::AlignLeft); - connect(close, &QPushButton::clicked, this, [=] { - sunnylink_client->role_service->load(); - sunnylink_client->user_service->load(); - QDialog::reject(); - }); - - //vlayout->addSpacing(30); - - const QString titleText = sponsor_pair ? tr("Pair your GitHub account") : tr("Early Access: Become a sunnypilot Sponsor"); - const auto title = new QLabel(titleText, this); - title->setStyleSheet("font-size: 75px; color: black;"); - title->setWordWrap(true); - vlayout->addWidget(title); - - QStringList instructions = getInstructions(sponsor_pair); - QString instructionsHtml = "
    "; - for (const auto & instruction : instructions) { - instructionsHtml += QString("
  1. %1
  2. ").arg(instruction); - } - instructionsHtml += "
"; - const auto instructionsLabel = new QLabel(instructionsHtml, this); - - - instructionsLabel->setStyleSheet("font-size: 47px; font-weight: bold; color: black;"); - instructionsLabel->setWordWrap(true); - vlayout->addWidget(instructionsLabel); - - vlayout->addStretch(); - } - - // QR code - auto *qr = new SunnylinkSponsorQRWidget(sponsor_pair, this); - hlayout->addWidget(qr, 1); -} diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/sunnylink/sponsor_widget.h b/selfdrive/ui/sunnypilot/qt/offroad/settings/sunnylink/sponsor_widget.h deleted file mode 100644 index 9f15a6084f..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/sunnylink/sponsor_widget.h +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include -#include - -#include "common/util.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/controls.h" - -const QString SUNNYLINK_BASE_URL = util::getenv("SUNNYLINK_API_HOST", "https://stg.api.sunnypilot.ai").c_str(); - -class SunnylinkSponsorQRWidget : public QWidget { - Q_OBJECT - -public: - explicit SunnylinkSponsorQRWidget(bool sponsor_pair = false, QWidget* parent = 0); - void paintEvent(QPaintEvent*) override; - -private: - QPixmap img; - QTimer *timer; - void updateQrCode(const QString &text); - void showEvent(QShowEvent *event) override; - void hideEvent(QHideEvent *event) override; - - bool sponsor_pair = false; - -private slots: - void refresh(); -}; - -// sponsor popup widget -class SunnylinkSponsorPopup : public DialogBase { - Q_OBJECT - -public: - explicit SunnylinkSponsorPopup(bool sponsor_pair = false, QWidget* parent = 0); - -private: - static QStringList getInstructions(bool sponsor_pair); - bool sponsor_pair = false; -}; diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/sunnylink_panel.cc b/selfdrive/ui/sunnypilot/qt/offroad/settings/sunnylink_panel.cc deleted file mode 100644 index 1358cbc959..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/sunnylink_panel.cc +++ /dev/null @@ -1,271 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/sunnylink_panel.h" - -#include "common/watchdog.h" -#include "selfdrive/ui/sunnypilot/qt/util.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/controls.h" -#include - -SunnylinkPanel::SunnylinkPanel(QWidget *parent) : QFrame(parent) { - main_layout = new QStackedLayout(this); - sunnylink_client = new SunnylinkClient(this); - param_watcher = new ParamWatcher(this); - param_watcher->addParam("SunnylinkEnabled"); - connect(param_watcher, &ParamWatcher::paramChanged, [=](const QString ¶m_name, const QString ¶m_value) { - paramsRefresh(param_name, param_value); - }); - - is_sunnylink_enabled = Params().getBool("SunnylinkEnabled"); - connect(uiStateSP(), &UIStateSP::sunnylinkRolesChanged, this, &SunnylinkPanel::updatePanel); - connect(uiStateSP(), &UIStateSP::sunnylinkDeviceUsersChanged, this, &SunnylinkPanel::updatePanel); - connect(uiStateSP(), &UIStateSP::offroadTransition, [=](bool offroad) { - is_onroad = !offroad; - updatePanel(); - }); - - sunnylinkScreen = new QWidget(this); - auto vlayout = new QVBoxLayout(sunnylinkScreen); - vlayout->setContentsMargins(50, 20, 50, 20); - - auto *list = new ListWidget(this, false); - QString sunnylinkEnabledBtnDesc = tr("This is the master switch, it will allow you to cutoff any sunnylink requests should you want to do that."); - sunnylinkEnabledBtn = new ParamControl( - "SunnylinkEnabled", - tr("Enable sunnylink"), - sunnylinkEnabledBtnDesc, - ""); - list->addItem(sunnylinkEnabledBtn); - - status_popup = new SunnylinkSponsorPopup(false, this); - sponsorBtn = new ButtonControlSP( - tr("Sponsor Status"), tr("SPONSOR"), - tr("Become a sponsor of sunnypilot to get early access to sunnylink features when they become available.")); - list->addItem(sponsorBtn); - connect(sponsorBtn, &ButtonControlSP::clicked, [=]() { - status_popup->exec(); - }); - list->addItem(horizontal_line()); - - pair_popup = new SunnylinkSponsorPopup(true, this); - pairSponsorBtn = new ButtonControlSP( - tr("Pair GitHub Account"), tr("PAIR"), - tr("Pair your GitHub account to grant your device sponsor benefits, including API access on sunnylink.") + "🌟"); - list->addItem(pairSponsorBtn); - connect(pairSponsorBtn, &ButtonControlSP::clicked, [=]() { - if (getSunnylinkDongleId().value_or(tr("N/A")) == "N/A") { - ConfirmationDialog::alert(tr("sunnylink Dongle ID not found. This may be due to weak internet connection or sunnylink registration issue. Please reboot and try again."), this); - } else { - pair_popup->exec(); - } - }); - list->addItem(horizontal_line()); - - connect(sunnylinkEnabledBtn, &ParamControl::showDescriptionEvent, [=]() { - // resets the description to the default one for the Easter egg - sunnylinkEnabledBtn->setDescription(sunnylinkEnabledBtnDesc); - }); - - connect(sunnylinkEnabledBtn, &ParamControl::toggleFlipped, [=](bool enabled) { - QString description; - if (enabled) { - description = ""+ tr("🎉Welcome back! We're excited to see you've enabled sunnylink again! 🚀")+ ""; - } else { - description = ""+ tr("👋Not going to lie, it's sad to see you disabled sunnylink 😢, but we'll be here when you're ready to come back 🎉.")+ ""; - } - sunnylinkEnabledBtn->showDescription(); - sunnylinkEnabledBtn->setDescription(description); - - updatePanel(); - }); - - // Backup Settings - backupSettings = new PushButtonSP(tr("Backup Settings"), 750, this); - backupSettings->setObjectName("backup_btn"); - connect(backupSettings, &QPushButton::clicked, [=]() { - backupSettings->setEnabled(false); - if (ConfirmationDialog::confirm(tr("Are you sure you want to backup sunnypilot settings?"), tr("Back Up"), this)) { - params.putBool("BackupManager_CreateBackup", true); - backup_request_pending = true; - } - }); - - // Restore Settings - restoreSettings = new PushButtonSP(tr("Restore Settings"), 750, this); - restoreSettings->setObjectName("restore_btn"); - connect(restoreSettings, &QPushButton::clicked, [=]() { - restoreSettings->setEnabled(false); - if (ConfirmationDialog::confirm(tr("Are you sure you want to restore the last backed up sunnypilot settings?"), tr("Restore"), this)) { - params.put("BackupManager_RestoreVersion", "latest"); - restore_request_pending = true; - } - }); - // Settings Restore and Settings Backup in the same horizontal space - auto settings_layout = new QHBoxLayout; - settings_layout->setContentsMargins(0, 0, 0, 30); - settings_layout->addWidget(backupSettings, 0, Qt::AlignLeft); - settings_layout->addSpacing(10); - settings_layout->addWidget(restoreSettings, 0, Qt::AlignRight); - list->addItem(settings_layout); - - QObject::connect(uiState(), &UIState::offroadTransition, this, &SunnylinkPanel::updatePanel); - QObject::connect(uiStateSP(), &UIStateSP::uiUpdate, this, &SunnylinkPanel::updatePanel); - - sunnylinkScroller = new ScrollViewSP(list, this); - vlayout->addWidget(sunnylinkScroller); - - main_layout->addWidget(sunnylinkScreen); - - if (is_sunnylink_enabled) { - startSunnylink(); - } -} - -void SunnylinkPanel::updateBackupManagerState() { - const SubMaster &sm = *(uiStateSP()->sm); - backup_manager = sm["backupManagerSP"].getBackupManagerSP(); -} - -void SunnylinkPanel::handleBackupProgress() { - auto backup_status = backup_manager.getBackupStatus(); - auto restore_status = backup_manager.getRestoreStatus(); - auto backup_progress = backup_manager.getBackupProgress(); - auto restore_progress = backup_manager.getRestoreProgress(); - - switch (backup_status) { - case cereal::BackupManagerSP::Status::IN_PROGRESS: - backup_request_pending = false; - backup_request_started = true; - backupSettings->setEnabled(false); - backupSettings->setText(QString(tr("Backup in progress %1%").arg(backup_progress))); - break; - case cereal::BackupManagerSP::Status::FAILED: - backup_request_pending = false; - backup_request_started = false; - backupSettings->setEnabled(!is_onroad); - backupSettings->setText(tr("Backup Failed")); - break; - case cereal::BackupManagerSP::Status::COMPLETED: - backup_request_pending = false; - break; - default: - if (!backup_request_pending && backup_request_started) { - backup_request_started = false; - ConfirmationDialog::alert(tr("Settings backup completed."), this); - } else { - backupSettings->setEnabled(!is_onroad && !backup_request_pending && is_sunnylink_enabled); - } - backupSettings->setText(tr("Backup Settings")); - break; - } - - switch (restore_status) { - case cereal::BackupManagerSP::Status::IN_PROGRESS: - restore_request_pending = false; - restore_request_started = true; - restoreSettings->setEnabled(false); - restoreSettings->setText(QString(tr("Restore in progress %1%").arg(restore_progress))); - break; - case cereal::BackupManagerSP::Status::FAILED: - restore_request_pending = false; - restore_request_started = false; - restoreSettings->setEnabled(!is_onroad); - restoreSettings->setText(tr("Restore Failed")); - ConfirmationDialog::alert(tr("Unable to restore the settings, try again later."), this); - break; - case cereal::BackupManagerSP::Status::COMPLETED: - restore_request_pending = false; - break; - default: - if (!restore_request_pending && restore_request_started) { - restore_request_started = false; - if (ConfirmationDialog::alert(tr("Settings restored. Confirm to restart the interface."), this)) { - qApp->exit(18); - watchdog_kick(0); - } - } else { - restoreSettings->setEnabled(!is_onroad && !restore_request_pending && is_sunnylink_enabled); - } - restoreSettings->setText(tr("Restore Settings")); - break; - } -} - -void SunnylinkPanel::paramsRefresh(const QString ¶m_name, const QString ¶m_value) { - // We do it on paramsRefresh because the toggleEvent happens before the value is updated - if (param_name == "SunnylinkEnabled" && param_value == "1") { - startSunnylink(); - } else if (param_name == "SunnylinkEnabled" && param_value == "0") { - stopSunnylink(); - } - - updatePanel(); -} - -void SunnylinkPanel::startSunnylink() const { - if (!sunnylink_client->role_service->isCurrentyPolling()) { - sunnylink_client->role_service->startPolling(); - } else { - sunnylink_client->role_service->load(); - } - - if (!sunnylink_client->user_service->isCurrentyPolling()) { - sunnylink_client->user_service->startPolling(); - } else { - sunnylink_client->user_service->load(); - } -} - -void SunnylinkPanel::stopSunnylink() const { - sunnylink_client->role_service->stopPolling(); - sunnylink_client->user_service->stopPolling(); -} - -void SunnylinkPanel::showEvent(QShowEvent *event) { - updatePanel(); - if (is_sunnylink_enabled) { - startSunnylink(); - } -} - -void SunnylinkPanel::updatePanel() { - if (!isVisible()) { - return; - } - - updateBackupManagerState(); - handleBackupProgress(); - const auto sunnylinkDongleId = getSunnylinkDongleId().value_or(tr("N/A")); - sunnylinkEnabledBtn->setEnabled(!is_onroad); - - is_sunnylink_enabled = Params().getBool("SunnylinkEnabled"); - bool is_sub = uiStateSP()->isSunnylinkSponsor() && is_sunnylink_enabled; - auto max_current_sponsor_rule = uiStateSP()->sunnylinkSponsorRole(); - auto role_name = max_current_sponsor_rule.getSponsorTierString(); - std::optional role_color = max_current_sponsor_rule.getSponsorTierColor(); - bool is_paired = uiStateSP()->isSunnylinkPaired(); - auto paired_users = uiStateSP()->sunnylinkDeviceUsers(); - - sunnylinkEnabledBtn->setEnabled(!is_onroad); - sunnylinkEnabledBtn->setValue(tr("Device ID") + " " + sunnylinkDongleId); - - sponsorBtn->setEnabled(!is_onroad && is_sunnylink_enabled); - sponsorBtn->setText(is_sub ? tr("THANKS ♥") : tr("SPONSOR")); - sponsorBtn->setValue(is_sub ? tr(role_name.toStdString().c_str()) : tr("Not Sponsor"), role_color); - - pairSponsorBtn->setEnabled(!is_onroad && is_sunnylink_enabled); - pairSponsorBtn->setValue(is_paired ? tr("Paired") : tr("Not Paired")); - - if (!is_sunnylink_enabled) { - sunnylinkEnabledBtn->setValue(""); - sponsorBtn->setValue(""); - pairSponsorBtn->setValue(""); - } - - update(); -} diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/sunnylink_panel.h b/selfdrive/ui/sunnypilot/qt/offroad/settings/sunnylink_panel.h deleted file mode 100644 index e17c68d3a3..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/sunnylink_panel.h +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/sunnypilot/qt/network/sunnylink/sunnylink_client.h" - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/settings.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/sunnylink/sponsor_widget.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/scrollview.h" - -class SunnylinkPanel : public QFrame { - Q_OBJECT - -public: - explicit SunnylinkPanel(QWidget *parent = nullptr); - void showEvent(QShowEvent *event) override; - void paramsRefresh(const QString ¶m_name, const QString ¶m_value); - void updateBackupManagerState(); - void handleBackupProgress(); - -public slots: - void updatePanel(); - -private: - Params params; - QStackedLayout *main_layout = nullptr; - QWidget *sunnylinkScreen = nullptr; - ScrollViewSP *sunnylinkScroller = nullptr; - SunnylinkSponsorPopup *status_popup; - SunnylinkSponsorPopup *pair_popup; - ButtonControlSP *sponsorBtn; - ButtonControlSP *pairSponsorBtn; - SunnylinkClient *sunnylink_client; - cereal::BackupManagerSP::Reader backup_manager; - - ParamControl *sunnylinkEnabledBtn; - bool is_onroad = false; - bool is_sunnylink_enabled = false; - bool backup_request_pending = false; - bool backup_request_started = false; - bool restore_request_pending = false; - bool restore_request_started = false; - ParamWatcher *param_watcher; - QString sunnylinkBtnDescription; - PushButtonSP *restoreSettings; - PushButtonSP *backupSettings; - - void stopSunnylink() const; - void startSunnylink() const; -}; diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/trips_panel.cc b/selfdrive/ui/sunnypilot/qt/offroad/settings/trips_panel.cc deleted file mode 100644 index dcb16d168d..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/trips_panel.cc +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/trips_panel.h" - -TripsPanel::TripsPanel(QWidget* parent) : QFrame(parent) { - QVBoxLayout* main_layout = new QVBoxLayout(this); - main_layout->setMargin(0); - - // main content - main_layout->addSpacing(25); - center_layout = new QStackedLayout(); - - driveStatsWidget = new DriveStats; - driveStatsWidget->setStyleSheet(R"( - QLabel[type="title"] { font-size: 51px; font-weight: 500; } - QLabel[type="number"] { font-size: 78px; font-weight: 500; } - QLabel[type="unit"] { font-size: 51px; font-weight: 300; color: #A0A0A0; } - )"); - center_layout->addWidget(driveStatsWidget); - - main_layout->addLayout(center_layout, 1); - - setStyleSheet(R"( - * { - color: white; - } - TripsPanel > QLabel { - font-size: 55px; - } - )"); -} diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/trips_panel.h b/selfdrive/ui/sunnypilot/qt/offroad/settings/trips_panel.h deleted file mode 100644 index 67a49e21a4..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/trips_panel.h +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/sunnypilot/qt/widgets/controls.h" - -#include "selfdrive/ui/sunnypilot/qt/widgets/drive_stats.h" - -class TripsPanel : public QFrame { - Q_OBJECT - -public: - explicit TripsPanel(QWidget* parent = 0); - -private: - Params params; - - QStackedLayout* center_layout; - DriveStats *driveStatsWidget; -}; diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/brand_settings_factory.cc b/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/brand_settings_factory.cc deleted file mode 100644 index bebc6c3032..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/brand_settings_factory.cc +++ /dev/null @@ -1,62 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/brand_settings_factory.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/brands.h" - -static const QStringList supportedBrands = { - "chrysler", - "ford", - "gm", - "honda", - "hyundai", - "mazda", - "nissan", - "rivian", - "subaru", - "tesla", - "toyota", - "volkswagen", -}; - -BrandSettingsInterface* BrandSettingsFactory::createBrandSettings(const QString& brand, QWidget* parent) { - if (brand == "chrysler") - return new ChryslerSettings(parent); - if (brand == "ford") - return new FordSettings(parent); - if (brand == "gm") - return new GMSettings(parent); - if (brand == "honda") - return new HondaSettings(parent); - if (brand == "hyundai") - return new HyundaiSettings(parent); - if (brand == "mazda") - return new MazdaSettings(parent); - if (brand == "nissan") - return new NissanSettings(parent); - if (brand == "rivian") - return new RivianSettings(parent); - if (brand == "subaru") - return new SubaruSettings(parent); - if (brand == "tesla") - return new TeslaSettings(parent); - if (brand == "toyota") - return new ToyotaSettings(parent); - if (brand == "volkswagen") - return new VolkswagenSettings(parent); - - // Default empty settings if brand not supported - return nullptr; -} - -bool BrandSettingsFactory::isBrandSupported(const QString& brand) { - return supportedBrands.contains(brand); -} - -QStringList BrandSettingsFactory::getSupportedBrands() { - return supportedBrands; -} diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/brand_settings_factory.h b/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/brand_settings_factory.h deleted file mode 100644 index b4dc9fc81b..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/brand_settings_factory.h +++ /dev/null @@ -1,18 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/brand_settings_interface.h" - -class BrandSettingsFactory { - -public: - static BrandSettingsInterface* createBrandSettings(const QString &brand, QWidget *parent = nullptr); - static bool isBrandSupported(const QString& brand); - static QStringList getSupportedBrands(); -}; diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/brand_settings_interface.cc b/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/brand_settings_interface.cc deleted file mode 100644 index 03921c01a3..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/brand_settings_interface.cc +++ /dev/null @@ -1,21 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/brand_settings_interface.h" - -BrandSettingsInterface::BrandSettingsInterface(QWidget *parent) : QWidget(parent) { - QVBoxLayout *main_layout = new QVBoxLayout(this); - main_layout->setContentsMargins(0, 0, 0, 0); - - list = new ListWidget(this, false); - main_layout->addWidget(list); -} - -void BrandSettingsInterface::updatePanel(bool _offroad) { - offroad = _offroad; - updateSettings(); -} diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/brand_settings_interface.h b/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/brand_settings_interface.h deleted file mode 100644 index 4aff123177..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/brand_settings_interface.h +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/sunnypilot/ui.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/settings.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/controls.h" - -class BrandSettingsInterface : public QWidget { - Q_OBJECT - -public: - explicit BrandSettingsInterface(QWidget *parent = nullptr); - virtual ~BrandSettingsInterface() = default; - - void updatePanel(bool _offroad); - virtual void updateSettings() = 0; - -protected: - ListWidget *list = nullptr; - Params params; - bool offroad = false; -}; diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/brands.h b/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/brands.h deleted file mode 100644 index 795dba5739..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/brands.h +++ /dev/null @@ -1,21 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/chrysler_settings.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/ford_settings.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/gm_settings.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/honda_settings.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/hyundai_settings.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/mazda_settings.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/nissan_settings.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/rivian_settings.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/subaru_settings.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/tesla_settings.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/toyota_settings.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/volkswagen_settings.h" diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/chrysler_settings.cc b/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/chrysler_settings.cc deleted file mode 100644 index fd8fc423fe..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/chrysler_settings.cc +++ /dev/null @@ -1,14 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/chrysler_settings.h" - -ChryslerSettings::ChryslerSettings(QWidget *parent) : BrandSettingsInterface(parent) { -} - -void ChryslerSettings::updateSettings() { -} diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/chrysler_settings.h b/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/chrysler_settings.h deleted file mode 100644 index ab84bec16a..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/chrysler_settings.h +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/brand_settings_interface.h" - -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/sunnypilot/ui.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/settings.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/controls.h" - -class ChryslerSettings : public BrandSettingsInterface { - Q_OBJECT - -public: - explicit ChryslerSettings(QWidget *parent = nullptr); - void updateSettings() override; - -private: - bool offroad = false; -}; diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/ford_settings.cc b/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/ford_settings.cc deleted file mode 100644 index 96564cb8a9..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/ford_settings.cc +++ /dev/null @@ -1,14 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/ford_settings.h" - -FordSettings::FordSettings(QWidget *parent) : BrandSettingsInterface(parent) { -} - -void FordSettings::updateSettings() { -} diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/ford_settings.h b/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/ford_settings.h deleted file mode 100644 index 468bd6b7dd..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/ford_settings.h +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/brand_settings_interface.h" - -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/sunnypilot/ui.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/settings.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/controls.h" - -class FordSettings : public BrandSettingsInterface { - Q_OBJECT - -public: - explicit FordSettings(QWidget *parent = nullptr); - void updateSettings() override; - -private: - bool offroad = false; -}; diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/gm_settings.cc b/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/gm_settings.cc deleted file mode 100644 index 060a28424b..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/gm_settings.cc +++ /dev/null @@ -1,14 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/gm_settings.h" - -GMSettings::GMSettings(QWidget *parent) : BrandSettingsInterface(parent) { -} - -void GMSettings::updateSettings() { -} diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/gm_settings.h b/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/gm_settings.h deleted file mode 100644 index 211563ab61..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/gm_settings.h +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/brand_settings_interface.h" - -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/sunnypilot/ui.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/settings.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/controls.h" - -class GMSettings : public BrandSettingsInterface { - Q_OBJECT - -public: - explicit GMSettings(QWidget *parent = nullptr); - void updateSettings() override; - -private: - bool offroad = false; -}; diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/honda_settings.cc b/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/honda_settings.cc deleted file mode 100644 index ca18fa7240..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/honda_settings.cc +++ /dev/null @@ -1,14 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/honda_settings.h" - -HondaSettings::HondaSettings(QWidget *parent) : BrandSettingsInterface(parent) { -} - -void HondaSettings::updateSettings() { -} diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/honda_settings.h b/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/honda_settings.h deleted file mode 100644 index e41602dc11..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/honda_settings.h +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/brand_settings_interface.h" - -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/sunnypilot/ui.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/settings.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/controls.h" - -class HondaSettings : public BrandSettingsInterface { - Q_OBJECT - -public: - explicit HondaSettings(QWidget *parent = nullptr); - void updateSettings() override; - -private: - bool offroad = false; -}; diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/hyundai_settings.cc b/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/hyundai_settings.cc deleted file mode 100644 index 01ea64f0cb..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/hyundai_settings.cc +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/hyundai_settings.h" - -HyundaiSettings::HyundaiSettings(QWidget *parent) : BrandSettingsInterface(parent) { - std::vector tuning_texts{ tr("Off"), tr("Dynamic"), tr("Predictive") }; - longitudinalTuningToggle = new ButtonParamControl( - "HyundaiLongitudinalTuning", - tr("Custom Longitudinal Tuning"), - "", - "", - tuning_texts, - 500 - ); - QObject::connect(longitudinalTuningToggle, &ButtonParamControlSP::buttonClicked, this, &HyundaiSettings::updateSettings); - list->addItem(longitudinalTuningToggle); - longitudinalTuningToggle->showDescription(); -} - -void HyundaiSettings::updateSettings() { - auto longitudinal_tuning_param = std::atoi(params.get("HyundaiLongitudinalTuning").c_str()); - - auto cp_bytes = params.get("CarParamsPersistent"); - if (!cp_bytes.empty()) { - AlignedBuffer aligned_buf; - capnp::FlatArrayMessageReader cmsg(aligned_buf.align(cp_bytes.data(), cp_bytes.size())); - cereal::CarParams::Reader CP = cmsg.getRoot(); - - has_longitudinal_control = hasLongitudinalControl(CP); - } else { - has_longitudinal_control = false; - } - - LongitudinalTuningOption longitudinal_tuning_option; - if (longitudinal_tuning_param == int(LongitudinalTuningOption::PREDICTIVE)) { - longitudinal_tuning_option = LongitudinalTuningOption::PREDICTIVE; - } else if (longitudinal_tuning_param == int(LongitudinalTuningOption::DYNAMIC)) { - longitudinal_tuning_option = LongitudinalTuningOption::DYNAMIC; - } else { - longitudinal_tuning_option = LongitudinalTuningOption::OFF; - } - - bool longitudinal_tuning_disabled = !offroad || !has_longitudinal_control; - QString longitudinal_tuning_description = longitudinalTuningDescription(longitudinal_tuning_option); - if (longitudinal_tuning_disabled) { - longitudinal_tuning_description = toggleDisableMsg(offroad, has_longitudinal_control); - } - - longitudinalTuningToggle->setEnabled(!longitudinal_tuning_disabled); - longitudinalTuningToggle->setDescription(longitudinal_tuning_description); - longitudinalTuningToggle->showDescription(); -} diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/hyundai_settings.h b/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/hyundai_settings.h deleted file mode 100644 index c94d40cfde..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/hyundai_settings.h +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/brand_settings_interface.h" - -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/sunnypilot/ui.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/settings.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/controls.h" - -enum class LongitudinalTuningOption { - OFF, - DYNAMIC, - PREDICTIVE, -}; - -class HyundaiSettings : public BrandSettingsInterface { - Q_OBJECT - -public: - explicit HyundaiSettings(QWidget *parent = nullptr); - void updateSettings() override; - -private: - bool has_longitudinal_control = false; - ButtonParamControl *longitudinalTuningToggle = nullptr; - - static QString toggleDisableMsg(bool _offroad, bool _has_longitudinal_control) { - if (!_has_longitudinal_control) { - return tr("This feature can only be used with openpilot longitudinal control enabled."); - } - - if (!_offroad) { - return tr("Enable \"Always Offroad\" in Device panel, or turn vehicle off to select an option."); - } - - return QString(); - } - - static QString longitudinalTuningDescription(LongitudinalTuningOption option = LongitudinalTuningOption::OFF) { - QString off_str = tr("Off: Uses default tuning"); - QString dynamic_str = tr("Dynamic: Adjusts acceleration limits based on current speed"); - QString predictive_str = tr("Predictive: Uses future trajectory data to anticipate needed adjustments"); - - if (option == LongitudinalTuningOption::PREDICTIVE) { - predictive_str = "" + predictive_str + ""; - } else if (option == LongitudinalTuningOption::DYNAMIC) { - dynamic_str = "" + dynamic_str + ""; - } else { - off_str = "" + off_str + ""; - } - - return QString("%1

%2
%3
%4
") - .arg(tr("Fine-tune your driving experience by adjusting acceleration smoothness with openpilot longitudinal control.")) - .arg(off_str) - .arg(dynamic_str) - .arg(predictive_str); - } -}; diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/mazda_settings.cc b/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/mazda_settings.cc deleted file mode 100644 index b8b8825f27..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/mazda_settings.cc +++ /dev/null @@ -1,14 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/mazda_settings.h" - -MazdaSettings::MazdaSettings(QWidget *parent) : BrandSettingsInterface(parent) { -} - -void MazdaSettings::updateSettings() { -} diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/mazda_settings.h b/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/mazda_settings.h deleted file mode 100644 index cbbc38de7f..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/mazda_settings.h +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/brand_settings_interface.h" - -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/sunnypilot/ui.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/settings.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/controls.h" - -class MazdaSettings : public BrandSettingsInterface { - Q_OBJECT - -public: - explicit MazdaSettings(QWidget *parent = nullptr); - void updateSettings() override; - -private: - bool offroad = false; -}; diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/nissan_settings.cc b/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/nissan_settings.cc deleted file mode 100644 index 3c21943622..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/nissan_settings.cc +++ /dev/null @@ -1,14 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/nissan_settings.h" - -NissanSettings::NissanSettings(QWidget *parent) : BrandSettingsInterface(parent) { -} - -void NissanSettings::updateSettings() { -} diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/nissan_settings.h b/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/nissan_settings.h deleted file mode 100644 index d6eabac0bf..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/nissan_settings.h +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/brand_settings_interface.h" - -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/sunnypilot/ui.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/settings.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/controls.h" - -class NissanSettings : public BrandSettingsInterface { - Q_OBJECT - -public: - explicit NissanSettings(QWidget *parent = nullptr); - void updateSettings() override; - -private: - bool offroad = false; -}; diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/platform_selector.cc b/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/platform_selector.cc deleted file mode 100644 index 0d4dde681f..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/platform_selector.cc +++ /dev/null @@ -1,235 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/platform_selector.h" - -#include -#include -#include -#include - -#include "selfdrive/ui/sunnypilot/qt/util.h" - -QVariant PlatformSelector::getPlatformBundle(const QString &key) { - QString platform_bundle = QString::fromStdString(params.get("CarPlatformBundle")); - if (!platform_bundle.isEmpty()) { - QJsonDocument json = QJsonDocument::fromJson(platform_bundle.toUtf8()); - if (!json.isNull() && json.isObject()) { - return json.object().value(key).toVariant(); - } - } - return {}; -} - -PlatformSelector::PlatformSelector() : ButtonControl(tr("Vehicle"), "", "") { - platforms = loadPlatformList(); - - QObject::connect(this, &ButtonControl::clicked, [=]() { - if (text() == tr("SEARCH")) { - QString query = InputDialog::getText(tr("Search your vehicle"), this, tr("Enter model year (e.g., 2021) and model name (Toyota Corolla):"), false); - if (query.length() > 0) { - setText(tr("SEARCHING")); - setEnabled(false); - searchPlatforms(query); - refresh(offroad); - } - } else { - params.remove("CarPlatformBundle"); - refresh(offroad); - } - }); - - main_layout->addStretch(0); - refresh(offroad); -} - -void PlatformSelector::refresh(bool _offroad) { - QString name = getPlatformBundle("name").toString(); - platform = unrecognized_str; - QString platform_color = YELLOW_PLATFORM; - - if (!name.isEmpty()) { - platform = name; - platform_color = BLUE_PLATFORM; - brand = getPlatformBundle("brand").toString(); - setText(tr("REMOVE")); - } else { - setText(tr("SEARCH")); - - platform = unrecognized_str; - brand = ""; - auto cp_bytes = params.get("CarParamsPersistent"); - if (!cp_bytes.empty()) { - AlignedBuffer aligned_buf; - capnp::FlatArrayMessageReader cmsg(aligned_buf.align(cp_bytes.data(), cp_bytes.size())); - cereal::CarParams::Reader CP = cmsg.getRoot(); - - platform = QString::fromStdString(CP.getCarFingerprint().cStr()); - - for (auto it = platforms.constBegin(); it != platforms.constEnd(); ++it) { - if (it.value()["platform"].toString() == platform) { - brand = it.value()["brand"].toString(); - break; - } - } - - if (platform == "MOCK") { - platform = unrecognized_str; - } else { - platform_color = GREEN_PLATFORM; - } - } - } - setValue(platform, platform_color); - setEnabled(true); - emit refreshPanel(); - - offroad = _offroad; - - FingerprintStatus cur_status; - if (platform_color == GREEN_PLATFORM) { - cur_status = FingerprintStatus::AUTO_FINGERPRINT; - } else if (platform_color == BLUE_PLATFORM) { - cur_status = FingerprintStatus::MANUAL_FINGERPRINT; - } else { - cur_status = FingerprintStatus::UNRECOGNIZED; - } - - setDescription(platformDescription(cur_status)); - showDescription(); -} - -void PlatformSelector::setPlatform(const QString &_platform) { - QVariantMap platform_data = platforms[_platform]; - - const QString offroad_msg = offroad ? tr("This setting will take effect immediately.") : - tr("This setting will take effect once the device enters offroad state."); - const QString msg = QString("%1

%2") - .arg(_platform, offroad_msg); - - QString content("

" + tr("Vehicle Selector") + "


" - "

" + msg + "

"); - - if (ConfirmationDialog(content, tr("Confirm"), tr("Cancel"), true, this).exec()) { - QJsonObject json_bundle; - json_bundle["platform"] = platform_data["platform"].toString(); - json_bundle["name"] = _platform; - json_bundle["make"] = platform_data["make"].toString(); - json_bundle["brand"] = platform_data["brand"].toString(); - json_bundle["model"] = platform_data["model"].toString(); - json_bundle["package"] = platform_data["package"].toString(); - - QVariantList yearList = platform_data["year"].toList(); - QJsonArray yearArray; - for (const QVariant &year : yearList) { - yearArray.append(year.toString()); - } - json_bundle["year"] = yearArray; - - QString json_bundle_str = QString::fromUtf8(QJsonDocument(json_bundle).toJson(QJsonDocument::Compact)); - - params.put("CarPlatformBundle", json_bundle_str.toStdString()); - } -} - -void PlatformSelector::searchPlatforms(const QString &query) { - if (query.isEmpty()) { - return; - } - - QSet matched_cars; - - QString normalized_query = query.simplified().toLower(); - QStringList tokens = normalized_query.split(" ", QString::SkipEmptyParts); - - int search_year = -1; - QStringList search_terms; - - for (const QString &token : tokens) { - bool ok; - int year = token.toInt(&ok); - if (ok && year >= 1900 && year <= 2100) { - search_year = year; - } else { - search_terms << token; - } - } - - for (auto it = platforms.constBegin(); it != platforms.constEnd(); ++it) { - QString platform_name = it.key(); - QVariantMap platform_data = it.value(); - - if (search_year != -1) { - QVariantList year_list = platform_data["year"].toList(); - bool year_match = false; - for (const QVariant &year_var : year_list) { - int year = year_var.toString().toInt(); - if (year == search_year) { - year_match = true; - break; - } - } - if (!year_match) continue; - } - - QString normalized_make = platform_data["make"].toString().normalized(QString::NormalizationForm_KD).toLower(); - QString normalized_model = platform_data["model"].toString().normalized(QString::NormalizationForm_KD).toLower(); - normalized_make.remove(QRegExp("[^a-zA-Z0-9\\s]")); - normalized_model.remove(QRegExp("[^a-zA-Z0-9\\s]")); - - bool all_terms_match = true; - for (const QString &term : search_terms) { - QString normalized_term = term.normalized(QString::NormalizationForm_KD).toLower(); - normalized_term.remove(QRegExp("[^a-zA-Z0-9\\s]")); - - bool term_matched = false; - - if (normalized_make.contains(normalized_term, Qt::CaseInsensitive)) { - term_matched = true; - } - - if (!term_matched) { - if (term.contains(QRegExp("[a-z]\\d|\\d[a-z]", Qt::CaseInsensitive))) { - QString clean_model = normalized_model; - QString clean_term = normalized_term; - clean_model.remove(" "); - clean_term.remove(" "); - if (clean_model.contains(clean_term, Qt::CaseInsensitive)) { - term_matched = true; - } - } else { - if (normalized_model.contains(normalized_term, Qt::CaseInsensitive)) { - term_matched = true; - } - } - } - - if (!term_matched) { - all_terms_match = false; - break; - } - } - - if (all_terms_match) { - matched_cars.insert(platform_name); - } - } - - QStringList results = matched_cars.toList(); - results.sort(); - - if (results.isEmpty()) { - ConfirmationDialog::alert(tr("No vehicles found for query: %1").arg(query), this); - return; - } - - QString selected_platform = MultiOptionDialog::getSelection(tr("Select a vehicle"), results, "", this); - - if (!selected_platform.isEmpty()) { - setPlatform(selected_platform); - } -} diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/platform_selector.h b/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/platform_selector.h deleted file mode 100644 index 9867371ef6..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/platform_selector.h +++ /dev/null @@ -1,68 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/settings.h" - -static const QString GREEN_PLATFORM = "#00F100"; -static const QString BLUE_PLATFORM = "#0086E9"; -static const QString YELLOW_PLATFORM = "#FFD500"; - -enum class FingerprintStatus { - AUTO_FINGERPRINT, - MANUAL_FINGERPRINT, - UNRECOGNIZED, -}; - -class PlatformSelector : public ButtonControl { - Q_OBJECT - -public: - PlatformSelector(); - QVariant getPlatformBundle(const QString &key); - - QString platform; - QString brand; - -public slots: - void refresh(bool _offroad); - -signals: - void refreshPanel(); - -private: - void searchPlatforms(const QString &query); - void setPlatform(const QString &platform = ""); - QMap platforms; - - Params params; - bool offroad; - - QString unrecognized_str = tr("Unrecognized Vehicle"); - - static QString platformDescription(FingerprintStatus status = FingerprintStatus::UNRECOGNIZED) { - QString auto_str = "🟢 - " + tr("Fingerprinted automatically"); - QString manual_str = "🔵 - " + tr("Manually selected"); - QString unrecognized_str = "🟡 - " + tr("Not fingerprinted or manually selected"); - - if (status == FingerprintStatus::AUTO_FINGERPRINT) { - auto_str = "" + auto_str + ""; - } else if (status == FingerprintStatus::MANUAL_FINGERPRINT) { - manual_str = "" + manual_str + ""; - } else { - unrecognized_str = "" + unrecognized_str + ""; - } - - return QString("%1
%2

%3
%4
%5") - .arg(tr("Select vehicle to force fingerprint manually.")) - .arg(tr("Colors represent fingerprint status:")) - .arg(auto_str) - .arg(manual_str) - .arg(unrecognized_str); - } -}; diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/rivian_settings.cc b/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/rivian_settings.cc deleted file mode 100644 index 92cf3dcd6c..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/rivian_settings.cc +++ /dev/null @@ -1,14 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/rivian_settings.h" - -RivianSettings::RivianSettings(QWidget *parent) : BrandSettingsInterface(parent) { -} - -void RivianSettings::updateSettings() { -} diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/rivian_settings.h b/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/rivian_settings.h deleted file mode 100644 index be25d01b37..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/rivian_settings.h +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/brand_settings_interface.h" - -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/sunnypilot/ui.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/settings.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/controls.h" - -class RivianSettings : public BrandSettingsInterface { - Q_OBJECT - -public: - explicit RivianSettings(QWidget *parent = nullptr); - void updateSettings() override; - -private: - bool offroad = false; -}; diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/subaru_settings.cc b/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/subaru_settings.cc deleted file mode 100644 index 47c4057f44..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/subaru_settings.cc +++ /dev/null @@ -1,14 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/subaru_settings.h" - -SubaruSettings::SubaruSettings(QWidget *parent) : BrandSettingsInterface(parent) { -} - -void SubaruSettings::updateSettings() { -} diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/subaru_settings.h b/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/subaru_settings.h deleted file mode 100644 index a715951ad9..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/subaru_settings.h +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/brand_settings_interface.h" - -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/sunnypilot/ui.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/settings.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/controls.h" - -class SubaruSettings : public BrandSettingsInterface { - Q_OBJECT - -public: - explicit SubaruSettings(QWidget *parent = nullptr); - void updateSettings() override; - -private: - bool offroad = false; -}; diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/tesla_settings.cc b/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/tesla_settings.cc deleted file mode 100644 index 50ab023021..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/tesla_settings.cc +++ /dev/null @@ -1,14 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/tesla_settings.h" - -TeslaSettings::TeslaSettings(QWidget *parent) : BrandSettingsInterface(parent) { -} - -void TeslaSettings::updateSettings() { -} diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/tesla_settings.h b/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/tesla_settings.h deleted file mode 100644 index 37f2936cdf..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/tesla_settings.h +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/brand_settings_interface.h" - -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/sunnypilot/ui.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/settings.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/controls.h" - -class TeslaSettings : public BrandSettingsInterface { - Q_OBJECT - -public: - explicit TeslaSettings(QWidget *parent = nullptr); - void updateSettings() override; - -private: - bool offroad = false; -}; diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/toyota_settings.cc b/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/toyota_settings.cc deleted file mode 100644 index c416177916..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/toyota_settings.cc +++ /dev/null @@ -1,14 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/toyota_settings.h" - -ToyotaSettings::ToyotaSettings(QWidget *parent) : BrandSettingsInterface(parent) { -} - -void ToyotaSettings::updateSettings() { -} diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/toyota_settings.h b/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/toyota_settings.h deleted file mode 100644 index 9fc18a2a65..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/toyota_settings.h +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/brand_settings_interface.h" - -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/sunnypilot/ui.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/settings.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/controls.h" - -class ToyotaSettings : public BrandSettingsInterface { - Q_OBJECT - -public: - explicit ToyotaSettings(QWidget *parent = nullptr); - void updateSettings() override; - -private: - bool offroad = false; -}; diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/volkswagen_settings.cc b/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/volkswagen_settings.cc deleted file mode 100644 index 59f0aab727..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/volkswagen_settings.cc +++ /dev/null @@ -1,14 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/volkswagen_settings.h" - -VolkswagenSettings::VolkswagenSettings(QWidget *parent) : BrandSettingsInterface(parent) { -} - -void VolkswagenSettings::updateSettings() { -} diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/volkswagen_settings.h b/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/volkswagen_settings.h deleted file mode 100644 index 25d3a07faf..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/volkswagen_settings.h +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/brand_settings_interface.h" - -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/sunnypilot/ui.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/settings.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/controls.h" - -class VolkswagenSettings : public BrandSettingsInterface { - Q_OBJECT - -public: - explicit VolkswagenSettings(QWidget *parent = nullptr); - void updateSettings() override; - -private: - bool offroad = false; -}; diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle_panel.cc b/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle_panel.cc deleted file mode 100644 index 5c00e746f8..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle_panel.cc +++ /dev/null @@ -1,67 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle_panel.h" - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/brand_settings_factory.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/brands.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/scrollview.h" - -VehiclePanel::VehiclePanel(QWidget *parent) : QFrame(parent) { - QVBoxLayout *main_layout = new QVBoxLayout(this); - main_layout->setContentsMargins(50, 20, 50, 20); - - ListWidget *list = new ListWidget(this); - - platformSelector = new PlatformSelector(); - QObject::connect(platformSelector, &PlatformSelector::refreshPanel, this, &VehiclePanel::updateBrandSettings); - list->addItem(platformSelector); - - brandSettingsContainer = new QWidget(this); - brandSettingsContainerLayout = new QVBoxLayout(brandSettingsContainer); - brandSettingsContainerLayout->setContentsMargins(0, 0, 0, 0); - brandSettingsContainerLayout->setSpacing(0); - list->addItem(brandSettingsContainer); - - ScrollViewSP *scroller = new ScrollViewSP(list, this); - main_layout->addWidget(scroller); - - currentBrandSettings = nullptr; - - QObject::connect(uiState(), &UIState::offroadTransition, this, &VehiclePanel::updatePanel); -} - -void VehiclePanel::showEvent(QShowEvent *event) { - updatePanel(offroad); -} - -void VehiclePanel::updatePanel(bool _offroad) { - offroad = _offroad; - platformSelector->refresh(_offroad); - updateBrandSettings(); -} - -void VehiclePanel::updateBrandSettings() { - if (!isVisible()) { - return; - } - - if (currentBrandSettings) { - brandSettingsContainerLayout->removeWidget(currentBrandSettings); - delete currentBrandSettings; - currentBrandSettings = nullptr; - } - - if (BrandSettingsFactory::isBrandSupported(platformSelector->brand)) { - currentBrandSettings = BrandSettingsFactory::createBrandSettings(platformSelector->brand, this); - if (currentBrandSettings) { - currentBrandSettings->setContentsMargins(0, 0, 0, 0); - brandSettingsContainerLayout->addWidget(currentBrandSettings); - currentBrandSettings->updatePanel(offroad); - } - } -} diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle_panel.h b/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle_panel.h deleted file mode 100644 index a170aa87c3..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle_panel.h +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/settings.h" - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/brand_settings_interface.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/vehicle/platform_selector.h" - -class VehiclePanel : public QFrame { - Q_OBJECT - -public: - explicit VehiclePanel(QWidget *parent = nullptr); - void showEvent(QShowEvent *event) override; - -public slots: - void updatePanel(bool _offroad); - -private: - PlatformSelector* platformSelector = nullptr; - BrandSettingsInterface* currentBrandSettings = nullptr; - QWidget* brandSettingsContainer = nullptr; - QVBoxLayout* brandSettingsContainerLayout = nullptr; - bool offroad = false; - -private slots: - void updateBrandSettings(); -}; diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/visuals_panel.cc b/selfdrive/ui/sunnypilot/qt/offroad/settings/visuals_panel.cc deleted file mode 100644 index 0d42bd74f4..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/visuals_panel.cc +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/visuals_panel.h" - -VisualsPanel::VisualsPanel(QWidget *parent) : QWidget(parent) { - param_watcher = new ParamWatcher(this); - connect(param_watcher, &ParamWatcher::paramChanged, [=](const QString ¶m_name, const QString ¶m_value) { - paramsRefresh(); - }); - - main_layout = new QStackedLayout(this); - ListWidgetSP *list = new ListWidgetSP(this, false); - - sunnypilotScreen = new QWidget(this); - QVBoxLayout* vlayout = new QVBoxLayout(sunnypilotScreen); - vlayout->setContentsMargins(50, 20, 50, 20); - - std::vector > toggle_defs{ - { - "BlindSpot", - tr("Show Blind Spot Warnings"), - tr("Enabling this will display warnings when a vehicle is detected in your blind spot as long as your car has BSM supported."), - "../assets/offroad/icon_monitoring.png", - false, - }, - }; - - for (auto &[param, title, desc, icon, needs_restart] : toggle_defs) { - auto toggle = new ParamControlSP(param, title, desc, icon, this); - - bool locked = params.getBool((param + "Lock").toStdString()); - toggle->setEnabled(!locked); - - if (needs_restart && !locked) { - toggle->setDescription(toggle->getDescription() + tr(" Changing this setting will restart openpilot if the car is powered on.")); - - QObject::connect(uiState(), &UIState::engagedChanged, [toggle](bool engaged) { - toggle->setEnabled(!engaged); - }); - - QObject::connect(toggle, &ParamControlSP::toggleFlipped, [=](bool state) { - params.putBool("OnroadCycleRequested", true); - }); - } - - list->addItem(toggle); - toggles[param.toStdString()] = toggle; - param_watcher->addParam(param); - } - - sunnypilotScroller = new ScrollViewSP(list, this); - vlayout->addWidget(sunnypilotScroller); - - main_layout->addWidget(sunnypilotScreen); -} - -void VisualsPanel::paramsRefresh() { - if (!isVisible()) { - return; - } - - for (auto toggle : toggles) { - toggle.second->refresh(); - } -} diff --git a/selfdrive/ui/sunnypilot/qt/offroad/settings/visuals_panel.h b/selfdrive/ui/sunnypilot/qt/offroad/settings/visuals_panel.h deleted file mode 100644 index 42e0688957..0000000000 --- a/selfdrive/ui/sunnypilot/qt/offroad/settings/visuals_panel.h +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/settings.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/scrollview.h" - -class ScrollViewSP; - -class VisualsPanel : public QWidget { - Q_OBJECT - -public: - explicit VisualsPanel(QWidget *parent = nullptr); - - void paramsRefresh(); - -protected: - QStackedLayout* main_layout = nullptr; - QWidget* sunnypilotScreen = nullptr; - ScrollViewSP *sunnypilotScroller = nullptr; - Params params; - std::map toggles; - ParamWatcher * param_watcher; -}; diff --git a/selfdrive/ui/sunnypilot/qt/onroad/annotated_camera.cc b/selfdrive/ui/sunnypilot/qt/onroad/annotated_camera.cc deleted file mode 100644 index 3721a3d198..0000000000 --- a/selfdrive/ui/sunnypilot/qt/onroad/annotated_camera.cc +++ /dev/null @@ -1,16 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/onroad/annotated_camera.h" - -AnnotatedCameraWidgetSP::AnnotatedCameraWidgetSP(VisionStreamType type, QWidget *parent) - : AnnotatedCameraWidget(type, parent) { -} - -void AnnotatedCameraWidgetSP::updateState(const UIState &s) { - AnnotatedCameraWidget::updateState(s); -} diff --git a/selfdrive/ui/sunnypilot/qt/onroad/annotated_camera.h b/selfdrive/ui/sunnypilot/qt/onroad/annotated_camera.h deleted file mode 100644 index 46ce7d4be3..0000000000 --- a/selfdrive/ui/sunnypilot/qt/onroad/annotated_camera.h +++ /dev/null @@ -1,18 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/qt/onroad/annotated_camera.h" - -class AnnotatedCameraWidgetSP : public AnnotatedCameraWidget { - Q_OBJECT - -public: - explicit AnnotatedCameraWidgetSP(VisionStreamType type, QWidget *parent = nullptr); - void updateState(const UIState &s) override; -}; diff --git a/selfdrive/ui/sunnypilot/qt/onroad/buttons.cc b/selfdrive/ui/sunnypilot/qt/onroad/buttons.cc deleted file mode 100644 index 97f6a391ce..0000000000 --- a/selfdrive/ui/sunnypilot/qt/onroad/buttons.cc +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/onroad/buttons.h" - -#include - -ExperimentalButtonSP::ExperimentalButtonSP(QWidget *parent) : ExperimentalButton(parent) { - QObject::disconnect(uiState(), &UIState::uiUpdate, this, &ExperimentalButton::updateState); - QObject::connect(uiState(), &UIState::uiUpdate, this, &ExperimentalButtonSP::updateState); -} - -void ExperimentalButtonSP::updateState(const UIState &s) { - ExperimentalButton::updateState(s); - const auto long_plan_sp = (*s.sm)["longitudinalPlanSP"].getLongitudinalPlanSP(); - - int mode = int(long_plan_sp.getDec().getState()); - if ((long_plan_sp.getDec().getActive() != dynamic_experimental_control) || (mode != dec_mpc_mode)) { - dynamic_experimental_control = long_plan_sp.getDec().getActive(); - dec_mpc_mode = mode; - update(); - } -} - -void ExperimentalButtonSP::drawButton(QPainter &p) { - if (dynamic_experimental_control) { - QPixmap left_half = engage_img.copy(0, 0, engage_img.width() / 2, engage_img.height()); - QPixmap right_half = experimental_img.copy(experimental_img.width() / 2, 0, experimental_img.width() / 2, experimental_img.height()); - - QPixmap combined_img(engage_img.width(), engage_img.height()); - combined_img.fill(Qt::transparent); - - QPainter combined_painter(&combined_img); - - combined_painter.setOpacity(dec_mpc_mode == 1 ? 0.1 : 1.0); - combined_painter.drawPixmap(0, 0, left_half); - - combined_painter.setOpacity(dec_mpc_mode == 1 ? 1.0 : 0.1); - combined_painter.drawPixmap(engage_img.width() / 2, 0, right_half); - - combined_painter.end(); - - drawIcon(p, QPoint(btn_size / 2, btn_size / 2), combined_img, QColor(0, 0, 0, 166), (isDown() || !engageable) ? 0.6 : 1.0); - } else { - ExperimentalButton::drawButton(p); - } -} diff --git a/selfdrive/ui/sunnypilot/qt/onroad/buttons.h b/selfdrive/ui/sunnypilot/qt/onroad/buttons.h deleted file mode 100644 index ce62a69e2d..0000000000 --- a/selfdrive/ui/sunnypilot/qt/onroad/buttons.h +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/qt/onroad/buttons.h" - -class ExperimentalButtonSP : public ExperimentalButton { - Q_OBJECT - -public: - explicit ExperimentalButtonSP(QWidget *parent = nullptr); - void updateState(const UIState &s) override; - -private: - void drawButton(QPainter &p) override; - - bool dynamic_experimental_control; - int dec_mpc_mode; -}; diff --git a/selfdrive/ui/sunnypilot/qt/onroad/hud.cc b/selfdrive/ui/sunnypilot/qt/onroad/hud.cc deleted file mode 100644 index 233ca59f98..0000000000 --- a/selfdrive/ui/sunnypilot/qt/onroad/hud.cc +++ /dev/null @@ -1,18 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/onroad/hud.h" - -HudRendererSP::HudRendererSP() {} - -void HudRendererSP::updateState(const UIState &s) { - HudRenderer::updateState(s); -} - -void HudRendererSP::draw(QPainter &p, const QRect &surface_rect) { - HudRenderer::draw(p, surface_rect); -} diff --git a/selfdrive/ui/sunnypilot/qt/onroad/hud.h b/selfdrive/ui/sunnypilot/qt/onroad/hud.h deleted file mode 100644 index 1e98cd3a52..0000000000 --- a/selfdrive/ui/sunnypilot/qt/onroad/hud.h +++ /dev/null @@ -1,21 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include - -#include "selfdrive/ui/qt/onroad/hud.h" - -class HudRendererSP : public HudRenderer { - Q_OBJECT - -public: - HudRendererSP(); - void updateState(const UIState &s) override; - void draw(QPainter &p, const QRect &surface_rect) override; -}; diff --git a/selfdrive/ui/sunnypilot/qt/onroad/model.cc b/selfdrive/ui/sunnypilot/qt/onroad/model.cc deleted file mode 100644 index af0177c344..0000000000 --- a/selfdrive/ui/sunnypilot/qt/onroad/model.cc +++ /dev/null @@ -1,52 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/onroad/model.h" - - -void ModelRendererSP::update_model(const cereal::ModelDataV2::Reader &model, const cereal::RadarState::LeadData::Reader &lead) { - ModelRenderer::update_model(model, lead); - const auto &model_position = model.getPosition(); - const auto &lane_lines = model.getLaneLines(); - float max_distance = std::clamp(*(model_position.getX().end() - 1), MIN_DRAW_DISTANCE, MAX_DRAW_DISTANCE); - int max_idx = get_path_length_idx(lane_lines[0], max_distance); - // update blindspot vertices - float max_distance_barrier = 100; - int max_idx_barrier = std::min(max_idx, get_path_length_idx(lane_lines[0], max_distance_barrier)); - mapLineToPolygon(model.getLaneLines()[1], 0.2, -0.05, &left_blindspot_vertices, max_idx_barrier); - mapLineToPolygon(model.getLaneLines()[2], 0.2, -0.05, &right_blindspot_vertices, max_idx_barrier); -} - -void ModelRendererSP::drawPath(QPainter &painter, const cereal::ModelDataV2::Reader &model, const QRect &surface_rect) { - auto *s = uiState(); - auto &sm = *(s->sm); - bool blindspot = Params().getBool("BlindSpot"); - - if (blindspot) { - bool left_blindspot = sm["carState"].getCarState().getLeftBlindspot(); - bool right_blindspot = sm["carState"].getCarState().getRightBlindspot(); - - //painter.setBrush(QColor::fromRgbF(1.0, 0.0, 0.0, 0.4)); // Red with alpha for blind spot - - if (left_blindspot && !left_blindspot_vertices.isEmpty()) { - QLinearGradient gradient(0, 0, surface_rect.width(), 0); // Horizontal gradient from left to right - gradient.setColorAt(0.0, QColor(255, 165, 0, 102)); // Orange with alpha - gradient.setColorAt(1.0, QColor(255, 255, 0, 102)); // Yellow with alpha - painter.setBrush(gradient); - painter.drawPolygon(left_blindspot_vertices); - } - - if (right_blindspot && !right_blindspot_vertices.isEmpty()) { - QLinearGradient gradient(surface_rect.width(), 0, 0, 0); // Horizontal gradient from right to left - gradient.setColorAt(0.0, QColor(255, 165, 0, 102)); // Orange with alpha - gradient.setColorAt(1.0, QColor(255, 255, 0, 102)); // Yellow with alpha - painter.setBrush(gradient); - painter.drawPolygon(right_blindspot_vertices); - } - } - ModelRenderer::drawPath(painter, model, surface_rect.height()); -} diff --git a/selfdrive/ui/sunnypilot/qt/onroad/model.h b/selfdrive/ui/sunnypilot/qt/onroad/model.h deleted file mode 100644 index 24404f32f0..0000000000 --- a/selfdrive/ui/sunnypilot/qt/onroad/model.h +++ /dev/null @@ -1,22 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/qt/onroad/model.h" - -class ModelRendererSP : public ModelRenderer { -public: - ModelRendererSP() = default; - -private: - void update_model(const cereal::ModelDataV2::Reader &model, const cereal::RadarState::LeadData::Reader &lead) override; - void drawPath(QPainter &painter, const cereal::ModelDataV2::Reader &model, const QRect &rect) override; - - QPolygonF left_blindspot_vertices; - QPolygonF right_blindspot_vertices; -}; diff --git a/selfdrive/ui/sunnypilot/qt/onroad/onroad_home.cc b/selfdrive/ui/sunnypilot/qt/onroad/onroad_home.cc deleted file mode 100644 index b26d1b828a..0000000000 --- a/selfdrive/ui/sunnypilot/qt/onroad/onroad_home.cc +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/onroad/onroad_home.h" - -#include "common/swaglog.h" -#include "selfdrive/ui/qt/util.h" - -OnroadWindowSP::OnroadWindowSP(QWidget *parent) : OnroadWindow(parent) { - QObject::connect(uiStateSP(), &UIStateSP::uiUpdate, this, &OnroadWindowSP::updateState); - QObject::connect(uiStateSP(), &UIStateSP::offroadTransition, this, &OnroadWindowSP::offroadTransition); -} - -void OnroadWindowSP::updateState(const UIStateSP &s) { - if (!s.scene.started) { - return; - } - - OnroadWindow::updateState(s); -} - -void OnroadWindowSP::mousePressEvent(QMouseEvent *e) { - OnroadWindow::mousePressEvent(e); -} - -void OnroadWindowSP::offroadTransition(bool offroad) { - OnroadWindow::offroadTransition(offroad); -} diff --git a/selfdrive/ui/sunnypilot/qt/onroad/onroad_home.h b/selfdrive/ui/sunnypilot/qt/onroad/onroad_home.h deleted file mode 100644 index 193fdae0dc..0000000000 --- a/selfdrive/ui/sunnypilot/qt/onroad/onroad_home.h +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/qt/onroad/onroad_home.h" - -class OnroadWindowSP : public OnroadWindow { - Q_OBJECT - -public: - OnroadWindowSP(QWidget *parent = 0); - -private: - void mousePressEvent(QMouseEvent *e) override; - -protected slots: - void offroadTransition(bool offroad) override; - void updateState(const UIStateSP &s) override; -}; diff --git a/selfdrive/ui/sunnypilot/qt/request_repeater.cc b/selfdrive/ui/sunnypilot/qt/request_repeater.cc deleted file mode 100644 index e137d56172..0000000000 --- a/selfdrive/ui/sunnypilot/qt/request_repeater.cc +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/request_repeater.h" - -RequestRepeaterSP::RequestRepeaterSP(QObject *parent, const QString &requestURL, const QString &cacheKey, - int period, bool whileOnroad, bool sunnylink) : HttpRequestSP(parent, true, 20000, sunnylink) { - request_url = requestURL; - while_onroad = whileOnroad; - timer = new QTimer(this); - timer->setTimerType(Qt::VeryCoarseTimer); - connect(timer, &QTimer::timeout, [=]() { this->timerTick(); }); - timer->start(period * 1000); - - if (!cacheKey.isEmpty()) { - prevResp = QString::fromStdString(params.get(cacheKey.toStdString())); - if (!prevResp.isEmpty()) { - QTimer::singleShot(500, [=]() { emit requestDone(prevResp, true, QNetworkReply::NoError); }); - } - connect(this, &HttpRequest::requestDone, [=](const QString &resp, bool success) { - if (success && resp != prevResp) { - params.put(cacheKey.toStdString(), resp.toStdString()); - prevResp = resp; - } - }); - } - - // Don't wait for the timer to fire to send the first request - ForceUpdate(); -} - -void RequestRepeaterSP::timerTick() { - if ((!uiState()->scene.started || while_onroad) && device()->isAwake() && !active()) { - LOGD("Sending request for %s", qPrintable(request_url)); - sendRequest(request_url); - } -} diff --git a/selfdrive/ui/sunnypilot/qt/request_repeater.h b/selfdrive/ui/sunnypilot/qt/request_repeater.h deleted file mode 100644 index 0cdb370f9b..0000000000 --- a/selfdrive/ui/sunnypilot/qt/request_repeater.h +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/qt/request_repeater.h" - -#include "common/swaglog.h" -#include "common/util.h" -#include "selfdrive/ui/sunnypilot/ui.h" -#include "selfdrive/ui/sunnypilot/qt/api.h" - -class RequestRepeaterSP : public HttpRequestSP { - -private: - Params params; - QTimer *timer; - QString prevResp; - QString request_url; - bool while_onroad; - void timerTick(); - -public: - RequestRepeaterSP(QObject *parent, const QString &requestURL, const QString &cacheKey = "", int period = 0, bool whileOnroad=false, bool sunnylink = false); - void ForceUpdate() { - LOGD("Forcing update for %s", qPrintable(request_url)); - timerTick(); - } -}; diff --git a/selfdrive/ui/sunnypilot/qt/sidebar.cc b/selfdrive/ui/sunnypilot/qt/sidebar.cc deleted file mode 100644 index a4dc1d6763..0000000000 --- a/selfdrive/ui/sunnypilot/qt/sidebar.cc +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/sidebar.h" - -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/sunnypilot/qt/util.h" -#include "common/params.h" - -SidebarSP::SidebarSP(QWidget *parent) : Sidebar(parent) { - // Redirect uiUpdate signal to SidebarSP::updateState instead of Sidebar::updateState - QObject::disconnect(uiState(), &UIState::uiUpdate, this, &Sidebar::updateState); - QObject::connect(uiStateSP(), &UIStateSP::uiUpdate, this, &SidebarSP::updateState); -} - -void SidebarSP::updateState(const UIStateSP &s) { - if (!isVisible()) return; - Sidebar::updateState(s); - - ItemStatus sunnylinkStatus; - auto sl_dongle_id = getSunnylinkDongleId(); - auto last_sunnylink_ping_str = params.get("LastSunnylinkPingTime"); - auto last_sunnylink_ping = std::stoull(last_sunnylink_ping_str.empty() ? "0" : last_sunnylink_ping_str); - auto elapsed_sunnylink_ping = nanos_since_boot() - last_sunnylink_ping; - auto sunnylink_enabled = params.getBool("SunnylinkEnabled"); - - QString status = tr("DISABLED"); - QColor color = disabled_color; - - if (sunnylink_enabled && last_sunnylink_ping == 0) { - // If sunnylink is enabled, but we don't have a dongle id, and we haven't received a ping yet, we are registering - status = sl_dongle_id.has_value() ? tr("OFFLINE") : tr("REGIST..."); - color = sl_dongle_id.has_value() ? warning_color : progress_color; - } else if (sunnylink_enabled) { - // If sunnylink is enabled, we are considered online if we have received a ping in the last 80 seconds, else error. - status = elapsed_sunnylink_ping < 80000000000ULL ? tr("ONLINE") : tr("ERROR"); - color = elapsed_sunnylink_ping < 80000000000ULL ? good_color : danger_color; - } - sunnylinkStatus = ItemStatus{{tr("SUNNYLINK"), status}, color}; - setProperty("sunnylinkStatus", QVariant::fromValue(sunnylinkStatus)); -} - -void SidebarSP::drawSidebar(QPainter &p) { - Sidebar::drawSidebar(p); - // metrics - drawMetric(p, temp_status.first, temp_status.second, 310); - drawMetric(p, panda_status.first, panda_status.second, 440); - drawMetric(p, connect_status.first, connect_status.second, 570); - drawMetric(p, sunnylink_status.first, sunnylink_status.second, 700); -} diff --git a/selfdrive/ui/sunnypilot/qt/sidebar.h b/selfdrive/ui/sunnypilot/qt/sidebar.h deleted file mode 100644 index 133106cfdf..0000000000 --- a/selfdrive/ui/sunnypilot/qt/sidebar.h +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include - -#include "selfdrive/ui/qt/sidebar.h" - -#include "selfdrive/ui/sunnypilot/ui.h" - -class SidebarSP : public Sidebar { - Q_OBJECT - Q_PROPERTY(ItemStatus sunnylinkStatus MEMBER sunnylink_status NOTIFY valueChanged); - Q_PROPERTY(QString sidebarTemp MEMBER sidebar_temp_str NOTIFY valueChanged); - -public slots: - void updateState(const UIStateSP &s); - -public: - explicit SidebarSP(QWidget *parent = 0); - -private: - void drawSidebar(QPainter &p) override; - - Params params; - QString sidebar_temp = "0"; - QString sidebar_temp_str = "0"; - -protected: - const QColor progress_color = QColor(3, 132, 252); - const QColor disabled_color = QColor(128, 128, 128); - - ItemStatus sunnylink_status; -}; diff --git a/selfdrive/ui/sunnypilot/qt/util.cc b/selfdrive/ui/sunnypilot/qt/util.cc deleted file mode 100644 index ca85935d0b..0000000000 --- a/selfdrive/ui/sunnypilot/qt/util.cc +++ /dev/null @@ -1,112 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/util.h" -#include "selfdrive/ui/qt/util.h" - -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#include "system/hardware/hw.h" - -std::optional getParamIgnoringDefault(const std::string ¶m_name, const std::string &default_value) { - std::string value = Params().get(param_name); - - if (!value.empty() && value != default_value) - return QString::fromStdString(value); - - return {}; -} - -QString getUserAgent(bool sunnylink) { - return (sunnylink ? "sunnypilot-" : "openpilot-") + getVersion(); -} - -std::optional getSunnylinkDongleId() { - return getParamIgnoringDefault("SunnylinkDongleId", "UnregisteredDevice"); -} - -QMap loadPlatformList() { - QMap _platforms; - - std::string json_data = util::read_file("../../sunnypilot/selfdrive/car/car_list.json"); - - if (json_data.empty()) { - return _platforms; - } - - QJsonParseError json_error{}; - QJsonDocument doc = QJsonDocument::fromJson(QString::fromStdString(json_data).toUtf8(), &json_error); - if (doc.isNull()) { - return _platforms; - } - - if (doc.isObject()) { - QJsonObject obj = doc.object(); - for (const QString &key : obj.keys()) { - QJsonObject attributes = obj.value(key).toObject(); - QVariantMap platform_data; - - QJsonArray yearArray = attributes.value("year").toArray(); - QVariantList yearList; - for (const QJsonValue &year : yearArray) { - yearList.append(year.toString()); - } - - platform_data["year"] = yearList; - platform_data["make"] = attributes.value("make").toString(); - platform_data["brand"] = attributes.value("brand").toString(); - platform_data["model"] = attributes.value("model").toString(); - platform_data["platform"] = attributes.value("platform").toString(); - platform_data["package"] = attributes.value("package").toString(); - - _platforms[key] = platform_data; - } - } - - return _platforms; -} - -/** - * @brief Searches a list of strings for elements containing all search terms in a query. - * - * The search is case-insensitive and normalizes both the query and the list elements - * using Unicode KD normalization before comparison. Non-alphanumeric characters are - * removed from the search terms before comparison. - * - * @param query The search query string. Multiple words can be separated by spaces. - * @param list The source list of strings to search. - * @return A list of strings from the input list that contain all of the search terms. - */ -QStringList searchFromList(const QString &query, const QStringList &list) { - if (query.isEmpty()) { - return list; - } - - QStringList search_terms = query.simplified().toLower().split(" ", QString::SkipEmptyParts); - QStringList search_results; - - for (const QString &element : list) { - if (std::all_of(search_terms.begin(), search_terms.end(), [&](const QString &term) { - QString normalized_term = term.normalized(QString::NormalizationForm_KD).toLower(); - normalized_term.remove(QRegularExpression("[^a-zA-Z0-9\\s]")); - QString normalized_element = element.normalized(QString::NormalizationForm_KD).toLower(); - return normalized_element.contains(normalized_term, Qt::CaseInsensitive); - })) { - search_results << element; - } - } - return search_results; -} diff --git a/selfdrive/ui/sunnypilot/qt/util.h b/selfdrive/ui/sunnypilot/qt/util.h deleted file mode 100644 index 089b5370cc..0000000000 --- a/selfdrive/ui/sunnypilot/qt/util.h +++ /dev/null @@ -1,22 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include -#include - -#include -#include -#include -#include - -QString getUserAgent(bool sunnylink = false); -std::optional getSunnylinkDongleId(); -std::optional getParamIgnoringDefault(const std::string ¶m_name, const std::string &default_value); -QMap loadPlatformList(); -QStringList searchFromList(const QString &query, const QStringList &list); diff --git a/selfdrive/ui/sunnypilot/qt/widgets/controls.cc b/selfdrive/ui/sunnypilot/qt/widgets/controls.cc deleted file mode 100644 index d873913b57..0000000000 --- a/selfdrive/ui/sunnypilot/qt/widgets/controls.cc +++ /dev/null @@ -1,256 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/widgets/controls.h" - -#include -#include - -QFrame *horizontal_line(QWidget *parent) { - QFrame *line = new QFrame(parent); - line->setFrameShape(QFrame::StyledPanel); - line->setStyleSheet(R"( - border-width: 2px; - border-bottom-style: solid; - border-color: gray; - )"); - line->setFixedHeight(10); - return line; -} - -QFrame *vertical_space(int height, QWidget *parent) { - QFrame *v_space = new QFrame(parent); - v_space->setFrameShape(QFrame::StyledPanel); - v_space->setFixedHeight(height); - return v_space; -} - -// AbstractControlSP - -AbstractControlSP::AbstractControlSP(const QString &title, const QString &desc, const QString &icon, QWidget *parent) - : AbstractControl(title, desc, icon, parent) { - - main_layout = new QVBoxLayout(this); - main_layout->setMargin(0); - - hlayout = new QHBoxLayout; - hlayout->setMargin(0); - hlayout->setSpacing(20); - - // title - title_label = new QPushButton(title); - title_label->setFixedHeight(120); - title_label->setStyleSheet("font-size: 50px; font-weight: 450; text-align: left; border: none;"); - hlayout->addWidget(title_label, 1); - - // value next to control button - value = new ElidedLabelSP(); - value->setAlignment(Qt::AlignRight | Qt::AlignVCenter); - value->setStyleSheet("color: #aaaaaa"); - hlayout->addWidget(value); - - main_layout->addLayout(hlayout); - - // description - description = new QLabel(desc); - description->setContentsMargins(40, 20, 40, 20); - description->setStyleSheet("font-size: 40px; color: grey"); - description->setWordWrap(true); - description->setVisible(false); - main_layout->addWidget(description); - - connect(title_label, &QPushButton::clicked, [=]() { - if (!description->isVisible()) { - emit showDescriptionEvent(); - } - - if (!description->text().isEmpty()) { - description->setVisible(!description->isVisible()); - } - }); - - main_layout->addStretch(); -} - -void AbstractControlSP::hideEvent(QHideEvent *e) { - if (description != nullptr) { - description->hide(); - } -} - -AbstractControlSP_SELECTOR::AbstractControlSP_SELECTOR(const QString &title, const QString &desc, const QString &icon, QWidget *parent) - : AbstractControlSP(title, desc, icon, parent) { - - if (title_label != nullptr) { - delete title_label; - title_label = nullptr; - } - - if (description != nullptr) { - delete description; - description = nullptr; - } - - if (value != nullptr) { - ReplaceWidget(value, new QWidget()); - value = nullptr; - } - - QLayoutItem *item; - while ((item = main_layout->takeAt(0)) != nullptr) { - if (item->widget()) { - delete item->widget(); - } - delete item; - } - - main_layout->setMargin(0); - - hlayout = new QHBoxLayout; - hlayout->setMargin(0); - hlayout->setSpacing(0); - - // title - if (!title.isEmpty()) { - title_label = new QPushButton(title); - title_label->setFixedHeight(120); - title_label->setStyleSheet("font-size: 50px; font-weight: 450; text-align: left; border: none; padding: 0 0 0 0"); - main_layout->addWidget(title_label, 1); - - connect(title_label, &QPushButton::clicked, [=]() { - if (!description->isVisible()) { - emit showDescriptionEvent(); - } - - if (!description->text().isEmpty()) { - bool isVisible = !description->isVisible(); - description->setVisible(isVisible); - - if (isVisible && spacingItem) { - main_layout->removeItem(spacingItem); - } else if (!isVisible && spacingItem != nullptr && main_layout->indexOf(spacingItem) == -1) { - main_layout->insertItem(main_layout->indexOf(description), spacingItem); - } - } - }); - } else { - main_layout->addSpacing(20); - } - - main_layout->addLayout(hlayout); - if (!desc.isEmpty() && spacingItem != nullptr && main_layout->indexOf(spacingItem) == -1) { - main_layout->insertItem(main_layout->count(), spacingItem); - } - - // description - description = new QLabel(desc); - description->setContentsMargins(40, 20, 40, 20); - description->setStyleSheet("font-size: 40px; color: grey"); - description->setWordWrap(true); - description->setVisible(false); - main_layout->addWidget(description); - - main_layout->addStretch(); -} - -void AbstractControlSP_SELECTOR::hideEvent(QHideEvent *e) { - if (description != nullptr) { - description->hide(); - } - - if (spacingItem != nullptr && main_layout->indexOf(spacingItem) == -1) { - main_layout->insertItem(main_layout->indexOf(description), spacingItem); - } -} - -// controls - -ButtonControlSP::ButtonControlSP(const QString &title, const QString &text, const QString &desc, QWidget *parent) - : AbstractControlSP(title, desc, "", parent) { - - btn.setText(text); - btn.setStyleSheet(R"( - QPushButton { - padding: 0; - border-radius: 50px; - font-size: 35px; - font-weight: 500; - color: #E4E4E4; - background-color: #393939; - } - QPushButton:pressed { - background-color: #4a4a4a; - } - QPushButton:disabled { - color: #33E4E4E4; - } - )"); - btn.setFixedSize(250, 100); - QObject::connect(&btn, &QPushButton::clicked, this, &ButtonControlSP::clicked); - hlayout->addWidget(&btn); -} - -// ElidedLabelSP - -ElidedLabelSP::ElidedLabelSP(QWidget *parent) : ElidedLabelSP({}, parent) { -} - -ElidedLabelSP::ElidedLabelSP(const QString &text, QWidget *parent) : QLabel(text.trimmed(), parent) { - setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); - setMinimumWidth(1); -} - -void ElidedLabelSP::resizeEvent(QResizeEvent *event) { - QLabel::resizeEvent(event); - lastText_ = elidedText_ = ""; -} - -void ElidedLabelSP::paintEvent(QPaintEvent *event) { - const QString curText = text(); - if (curText != lastText_) { - elidedText_ = fontMetrics().elidedText(curText, Qt::ElideRight, contentsRect().width()); - lastText_ = curText; - } - - QPainter painter(this); - drawFrame(&painter); - QStyleOption opt; - opt.initFrom(this); - style()->drawItemText(&painter, contentsRect(), alignment(), opt.palette, isEnabled(), elidedText_, foregroundRole()); -} - -// ParamControlSP - -ParamControlSP::ParamControlSP(const QString ¶m, const QString &title, const QString &desc, const QString &icon, QWidget *parent) - : ToggleControlSP(title, desc, icon, false, parent) { - - key = param.toStdString(); - QObject::connect(this, &ParamControlSP::toggleFlipped, this, &ParamControlSP::toggleClicked); - - hlayout->removeWidget(&toggle); - hlayout->insertWidget(0, &toggle); - - hlayout->removeWidget(this->icon_label); - hlayout->insertWidget(1, this->icon_label); -} - -void ParamControlSP::toggleClicked(bool state) { - auto do_confirm = [this]() { - QString content("

" + title_label->text() + "


" - "

" + getDescription() + "

"); - return ConfirmationDialog(content, tr("Enable"), tr("Cancel"), true, this).exec(); - }; - - bool confirmed = store_confirm && params.getBool(key + "Confirmed"); - if (!confirm || confirmed || !state || do_confirm()) { - if (store_confirm && state) params.putBool(key + "Confirmed", true); - params.putBool(key, state); - setIcon(state); - } else { - toggle.togglePosition(); - } -} diff --git a/selfdrive/ui/sunnypilot/qt/widgets/controls.h b/selfdrive/ui/sunnypilot/qt/widgets/controls.h deleted file mode 100644 index c8849faf53..0000000000 --- a/selfdrive/ui/sunnypilot/qt/widgets/controls.h +++ /dev/null @@ -1,717 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include -#include -#include -#include - -#include "common/params.h" -#include "selfdrive/ui/qt/widgets/controls.h" -#include "selfdrive/ui/qt/widgets/input.h" -#include "selfdrive/ui/sunnypilot/qt/widgets/toggle.h" - -QFrame *horizontal_line(QWidget *parent = nullptr); -QFrame *vertical_space(int height = 10, QWidget *parent = nullptr); - -inline void ReplaceWidget(QWidget *old_widget, QWidget *new_widget) { - if (old_widget && old_widget->parentWidget() && old_widget->parentWidget()->layout()) { - old_widget->parentWidget()->layout()->replaceWidget(old_widget, new_widget); - old_widget->hide(); - old_widget->deleteLater(); - } -} - -class ElidedLabelSP : public QLabel { - Q_OBJECT - -public: - explicit ElidedLabelSP(QWidget *parent = 0); - explicit ElidedLabelSP(const QString &text, QWidget *parent = 0); - - void setColor(const QString &color) { - setStyleSheet("QLabel { color : " + color + "; }"); - } - -signals: - void clicked(); - -protected: - void paintEvent(QPaintEvent *event) override; - void resizeEvent(QResizeEvent *event) override; - void mouseReleaseEvent(QMouseEvent *event) override { - if (rect().contains(event->pos())) { - emit clicked(); - } - } - QString lastText_, elidedText_; -}; - -class AbstractControlSP : public AbstractControl { - Q_OBJECT - -public: - void setDescription(const QString &desc) override { - if (description) description->setText(desc); - } - - void setValue(const QString &val, std::optional color = std::nullopt) { - value->setText(val); - if (color.has_value()) { - value->setColor(color.value()); - } - } - - const QString getDescription() override { - return description->text(); - } - - void hideDescription() { - description->setVisible(false); - } - -public slots: - void showDescription() override { - description->setVisible(true); - } - -protected: - AbstractControlSP(const QString &title, const QString &desc = "", const QString &icon = "", QWidget *parent = nullptr); - void hideEvent(QHideEvent *e) override; - - QVBoxLayout *main_layout; - ElidedLabelSP *value; - QLabel *description = nullptr; -}; - -// AbstractControlSP_SELECTOR - -class AbstractControlSP_SELECTOR : public AbstractControlSP { - Q_OBJECT - -protected: - QSpacerItem *spacingItem = new QSpacerItem(44, 44, QSizePolicy::Minimum, QSizePolicy::Fixed); - AbstractControlSP_SELECTOR(const QString &title, const QString &desc = "", const QString &icon = "", QWidget *parent = nullptr); - void hideEvent(QHideEvent *e) override; - -}; - -// widget to display a value -class LabelControlSP : public AbstractControlSP { - Q_OBJECT - -public: - LabelControlSP(const QString &title, const QString &text = "", const QString &desc = "", QWidget *parent = nullptr) : AbstractControlSP(title, desc, "", parent) { - label.setText(text); - label.setAlignment(Qt::AlignRight | Qt::AlignVCenter); - hlayout->addWidget(&label); - } - void setText(const QString &text) { label.setText(text); } - -private: - ElidedLabelSP label; -}; - -// widget for a button with a label -class ButtonControlSP : public AbstractControlSP { - Q_OBJECT - -public: - ButtonControlSP(const QString &title, const QString &text, const QString &desc = "", QWidget *parent = nullptr); - inline void setText(const QString &text) { btn.setText(text); } - inline QString text() const { return btn.text(); } - inline void click() { btn.click(); } - -signals: - void clicked(); - -public slots: - void setEnabled(bool enabled) { btn.setEnabled(enabled); } - -private: - QPushButton btn; -}; - -class ToggleControlSP : public AbstractControlSP { - Q_OBJECT - -public: - ToggleControlSP(const QString &title, const QString &desc = "", const QString &icon = "", const bool state = false, QWidget *parent = nullptr) : AbstractControlSP(title, desc, icon, parent) { - // space between toggle and title - icon_label = new QLabel(this); - hlayout->addWidget(icon_label); - - toggle.setFixedSize(150, 100); - if (state) { - toggle.togglePosition(); - } - hlayout->insertWidget(0, &toggle); - hlayout->insertWidget(1, this->icon_label); - QObject::connect(&toggle, &ToggleSP::stateChanged, this, &ToggleControlSP::toggleFlipped); - } - - void setEnabled(bool enabled) { - toggle.setEnabled(enabled); - toggle.update(); - } - -signals: - void toggleFlipped(bool state); - -protected: - ToggleSP toggle; -}; - -// widget to toggle params -class ParamControlSP : public ToggleControlSP { - Q_OBJECT - -public: - ParamControlSP(const QString ¶m, const QString &title, const QString &desc, const QString &icon, QWidget *parent = nullptr); - void setConfirmation(bool _confirm, bool _store_confirm) { - confirm = _confirm; - store_confirm = _store_confirm; - } - - void setActiveIcon(const QString &icon) { - active_icon_pixmap = QPixmap(icon).scaledToWidth(80, Qt::SmoothTransformation); - } - - void refresh() { - bool state = params.getBool(key); - if (state != toggle.on) { - toggle.togglePosition(); - setIcon(state); - } - } - - void showEvent(QShowEvent *event) override { - refresh(); - } - - bool isToggled() { return params.getBool(key); } - -private: - void toggleClicked(bool state); - void setIcon(bool state) { - if (state && !active_icon_pixmap.isNull()) { - icon_label->setPixmap(active_icon_pixmap); - } else if (!icon_pixmap.isNull()) { - icon_label->setPixmap(icon_pixmap); - } - } - - std::string key; - Params params; - QPixmap active_icon_pixmap; - bool confirm = false; - bool store_confirm = false; -}; - -class MultiButtonControlSP : public AbstractControlSP_SELECTOR { - Q_OBJECT - -public: - MultiButtonControlSP(const QString &title, const QString &desc, const QString &icon, - const std::vector &button_texts, const int minimum_button_width = 225, const bool inline_layout = false) : AbstractControlSP_SELECTOR(title, desc, icon), button_texts(button_texts), is_inline_layout(inline_layout) { - const QString style = R"( - QPushButton { - border-radius: 20px; - font-size: 50px; - font-weight: 450; - height:150px; - padding: 0 25 0 25; - color: #FFFFFF; - } - QPushButton:pressed { - background-color: #4a4a4a; - } - QPushButton:checked:enabled { - background-color: #696868; - } - QPushButton:disabled { - color: #33FFFFFF; - } - QPushButton:checked:disabled { - background-color: #121212; - color: #33FFFFFF; - } - )"; - - if (inline_layout) { - button_param_layout->setMargin(0); - button_param_layout->setSpacing(0); - spacingItem = nullptr; - if (!title.isEmpty()) { - main_layout->removeWidget(title_label); - hlayout->addWidget(title_label, 1); - } - } - - button_group = new QButtonGroup(this); - button_group->setExclusive(true); - for (int i = 0; i < button_texts.size(); i++) { - QPushButton *button = new QPushButton(button_texts[i], this); - button->setCheckable(true); - button->setStyleSheet(style); - button->setMinimumWidth(minimum_button_width); - if (i == 0) button_param_layout->addSpacing(2); - button_param_layout->addWidget(button); - button_group->addButton(button, i); - } - - button_param_layout->setAlignment(Qt::AlignLeft); - if (is_inline_layout) { - QFrame *container = new QFrame; - container->setLayout(button_param_layout); - container->setStyleSheet("background-color: #393939; border-radius: 20px;"); - hlayout->addWidget(container); - } - - QObject::connect(button_group, QOverload::of(&QButtonGroup::buttonClicked), this, &MultiButtonControlSP::buttonClicked); - } - - void setEnabled(bool enable) { - for (auto btn: button_group->buttons()) { - btn->setEnabled(enable); - } - button_group_enabled = enable; - - update(); - } - - void setCheckedButton(int id) { - button_group->button(id)->setChecked(true); - } - - void refresh() { - int value = atoi(params.get(key).c_str()); - - if (value >= button_texts.size()) { - value = button_texts.size() - 1; - } - if (value < 0) { - value = 0; - } - - button_group->button(value)->setChecked(true); - } - - void showEvent(QShowEvent *event) override { - refresh(); - } - - void setButton(QString param) { - key = param.toStdString(); - int value = atoi(params.get(key).c_str()); - for (int i = 0; i < button_group->buttons().size(); i++) { - button_group->buttons()[i]->setChecked(i == value); - } - } - - void setEnableSelectedButtons(bool enable, const std::vector& enabled_btns = {}) const { - for (int i = 0; i < button_group->buttons().size(); i++) { - // Enable the button if its index is in the enabled list - bool should_enable = std::find(enabled_btns.begin(), enabled_btns.end(), i) != enabled_btns.end(); - button_group->buttons()[i]->setEnabled(enable && should_enable); - } - } - -protected: - QButtonGroup *button_group; - void paintEvent(QPaintEvent *event) override { - if (is_inline_layout) { - return; - } - - QPainter p(this); - p.setRenderHint(QPainter::Antialiasing); - - // Calculate the total width and height for the background rectangle - int w = 0; - int h = 150; - - for (int i = 0; i < hlayout->count(); ++i) { - QPushButton *button = qobject_cast(hlayout->itemAt(i)->widget()); - if (button) { - w += button->width(); - } - } - - // Draw the rectangle -#ifdef __APPLE__ - QRect rect(0 + 2, h - 16, w, h); -#else - QRect rect(0 + 2, h - 24, w, h); -#endif - p.setPen(QPen(QColor(button_group_enabled ? "#696868" : "#121212"), 3)); - p.drawRoundedRect(rect, 20, 20); - } - -signals: - void buttonClicked(int id); - -private: - std::string key; - Params params; - std::vector button_texts; - - bool button_group_enabled = true; - bool is_inline_layout; - QHBoxLayout *button_param_layout = is_inline_layout ? new QHBoxLayout() : hlayout; -}; - -class ButtonParamControlSP : public MultiButtonControlSP { - Q_OBJECT -public: - ButtonParamControlSP(const QString ¶m, const QString &title, const QString &desc, const QString &icon, - const std::vector &button_texts, const int minimum_button_width = 225, const bool inline_layout = false) : MultiButtonControlSP(title, desc, icon, - button_texts, minimum_button_width, inline_layout) { - key = param.toStdString(); - int value = atoi(params.get(key).c_str()); - - if (value > 0 && value < button_group->buttons().size()) { - button_group->button(value)->setChecked(true); - } - - QObject::connect(this, QOverload::of(&MultiButtonControlSP::buttonClicked), [=](int id) { - params.put(key, std::to_string(id)); - }); - } - - void refresh() { - int value = atoi(params.get(key).c_str()); - button_group->button(value)->setChecked(true); - } - - void showEvent(QShowEvent *event) override { - refresh(); - } - -private: - std::string key; - Params params; -}; - -class ListWidgetSP : public QWidget { - Q_OBJECT - -public: - explicit ListWidgetSP(QWidget *parent = 0, const bool split_line = true) : QWidget(parent), _split_line(split_line), outer_layout(this) { - outer_layout.setMargin(0); - outer_layout.setSpacing(0); - outer_layout.addLayout(&inner_layout); - inner_layout.setMargin(0); - inner_layout.setSpacing(25); // default spacing is 25 - outer_layout.addStretch(1); - } - inline void addItem(QWidget *w) { inner_layout.addWidget(w); } - inline void addItem(QLayout *layout) { inner_layout.addLayout(layout); } - inline void setSpacing(int spacing) { inner_layout.setSpacing(spacing); } - - inline void AddWidgetAt(const int index, QWidget *new_widget) { inner_layout.insertWidget(index, new_widget); } - inline void RemoveWidgetAt(const int index) { - if (QLayoutItem *item; (item = inner_layout.takeAt(index)) != nullptr) { - if (item->widget()) delete item->widget(); - delete item; - } - } - - inline void ReplaceOrAddWidget(QWidget *old_widget, QWidget *new_widget) { - if (const int index = inner_layout.indexOf(old_widget); index != -1) { - RemoveWidgetAt(index); - AddWidgetAt(index, new_widget); - } else { - addItem(new_widget); - } - } - -private: - void paintEvent(QPaintEvent *) override { - QPainter p(this); - p.setPen(Qt::gray); - for (int i = 0; i < inner_layout.count() - 1; ++i) { - QWidget *widget = inner_layout.itemAt(i)->widget(); - if ((widget == nullptr || widget->isVisible()) && _split_line) { - QRect r = inner_layout.itemAt(i)->geometry(); - int bottom = r.bottom() + inner_layout.spacing() / 2; - p.drawLine(r.left(), bottom, r.right(), bottom); - } - } - } - QVBoxLayout outer_layout; - QVBoxLayout inner_layout; - - bool _split_line; -}; - -// convenience class for wrapping layouts -class LayoutWidgetSP : public QWidget { - Q_OBJECT - -public: - LayoutWidgetSP(QLayout *l, QWidget *parent = nullptr) : QWidget(parent) { - setLayout(l); - } -}; - -class OptionControlSP : public AbstractControlSP_SELECTOR { - Q_OBJECT - -protected: - struct MinMaxValue { - int min_value; - int max_value; - }; - -private: - bool is_inline_layout; - QHBoxLayout *optionSelectorLayout = is_inline_layout ? new QHBoxLayout() : hlayout; - - int getParamValue() { - const auto param_value = QString::fromStdString(params.get(key)); - const auto result = valueMap != nullptr ? valueMap->key(param_value) : param_value; - return result.toInt(); - } - - // Although the method is not static, and thus has access to the value property, I prefer to be explicit about the value. - void setParamValue(const int new_value) { - const auto value_str = valueMap != nullptr ? valueMap->value(QString::number(new_value)) : QString::number(new_value); - params.put(key, value_str.toStdString()); - } - -public: - OptionControlSP(const QString ¶m, const QString &title, const QString &desc, const QString &icon, - const MinMaxValue &range, const int per_value_change = 1, const bool inline_layout = false, const QMap *valMap = nullptr) : AbstractControlSP_SELECTOR(title, desc, icon, nullptr), _title(title), valueMap(valMap), is_inline_layout(inline_layout) { - const QString style = R"( - QPushButton { - border-radius: 20px; - font-size: 60px; - font-weight: 500; - width: 150px; - height: 150px; - padding: -3 25 3 25; - color: #FFFFFF; - font-weight: bold; - } - QPushButton:pressed { - color: #5C5C5C; - } - QPushButton:disabled { - color: #5C5C5C; - } - )"; - - if (inline_layout) { - optionSelectorLayout->setMargin(0); - optionSelectorLayout->setSpacing(0); - if (!title.isEmpty()) { - main_layout->removeWidget(title_label); - hlayout->addWidget(title_label, 1); - } - if (spacingItem != nullptr && main_layout->indexOf(spacingItem) != -1) { - main_layout->removeItem(spacingItem); - spacingItem = nullptr; - } - } - - label.setStyleSheet(label_enabled_style); - label.setFixedWidth(inline_layout ? 350 : 300); - label.setAlignment(Qt::AlignCenter); - - const std::vector button_texts{"-", "+"}; - - key = param.toStdString(); - value = getParamValue(); - - button_group = new QButtonGroup(this); - button_group->setExclusive(true); - for (int i = 0; i < button_texts.size(); i++) { - QPushButton *button = new QPushButton(button_texts[i], this); - button->setStyleSheet(style + ((i == 0) ? "QPushButton { text-align: left; }" : - "QPushButton { text-align: right; }")); - optionSelectorLayout->addWidget(button, 0, ((i == 0) ? Qt::AlignLeft : Qt::AlignRight) | Qt::AlignVCenter); - if (i == 0) { - optionSelectorLayout->addWidget(&label, 0, Qt::AlignCenter); - } - button->setEnabled((i == 0) ? !(value <= range.min_value) : !(value >= range.max_value)); - button->setFocusPolicy(Qt::NoFocus); // This prevents unintended scroll due to loss of focus when the button gets disabled based on min/max values - button_group->addButton(button, i); - - QObject::connect(button, &QPushButton::clicked, [=]() { - int change_value = (i == 0) ? -per_value_change : per_value_change; - value = getParamValue(); // in case it changed externally, we need to get the latest value. - value += change_value; - value = std::clamp(value, range.min_value, range.max_value); - setParamValue(value); - - button_group->button(0)->setEnabled(!(value <= range.min_value)); - button_group->button(1)->setEnabled(!(value >= range.max_value)); - - updateLabels(); - - if (request_update) { - emit updateOtherToggles(); - } - }); - } - - optionSelectorLayout->setAlignment(Qt::AlignLeft); - if (is_inline_layout) { - QFrame *container = new QFrame; - container->setLayout(optionSelectorLayout); - container->setStyleSheet("background-color: #393939; border-radius: 20px;"); - hlayout->addWidget(container); - } - } - - void setUpdateOtherToggles(bool _update) { - request_update = _update; - } - - void setFixedWidth(int width) { - label.setFixedWidth(width); - } - - inline void setLabel(const QString &text) { label.setText(text); } - - void setEnabled(bool enabled) { - for (auto btn: button_group->buttons()) { - btn->setEnabled(enabled); - } - label.setEnabled(enabled); - label.setStyleSheet(enabled ? label_enabled_style : label_disabled_style); - button_enabled = enabled; - - update(); - } - -protected: - void paintEvent(QPaintEvent *event) override { - if (is_inline_layout) { - return; - } - - QPainter p(this); - p.setRenderHint(QPainter::Antialiasing); - - // Calculate the total width and height for the background rectangle - int w = 0; - int h = 150; - - for (int i = 0; i < optionSelectorLayout->count(); ++i) { - QWidget *widget = qobject_cast(optionSelectorLayout->itemAt(i)->widget()); - if (widget) { - w += widget->width(); - } - } - - // Draw the rectangle -#ifdef __APPLE__ - QRect rect(0, !_title.isEmpty() ? (h - 16) : 20, w, h); -#else - QRect rect(0, !_title.isEmpty() ? (h - 24) : 20, w, h); -#endif - p.setBrush(QColor(button_enabled ? "#b24a4a4a" : "#121212")); // Background color - p.setPen(QPen(Qt::NoPen)); - p.drawRoundedRect(rect, 20, 20); - } - -signals: - void updateLabels(); - void updateOtherToggles(); - -private: - std::string key; - int value; - QButtonGroup *button_group; - QLabel label; - Params params; - std::map option_label = {}; - bool request_update = false; - QString _title = ""; - const QMap *valueMap; - - const QString label_enabled_style = "font-size: 50px; font-weight: 450; color: #FFFFFF;"; - const QString label_disabled_style = "font-size: 50px; font-weight: 450; color: #5C5C5C;"; - - bool button_enabled = true; -}; - -class PushButtonSP : public QPushButton { - Q_OBJECT - -public: - PushButtonSP(const QString &text, const int minimum_button_width = 800, QWidget *parent = nullptr, const QString ¶m = "") : QPushButton(text, parent) { - buttonStyle = R"( - QPushButton { - border-radius: 20px; - font-size: 50px; - font-weight: 450; - height: 150px; - padding: 0 25px 0 25px; - color: #FFFFFF; - } - )"; - - if (!param.isEmpty()) { - key = param.toStdString(); - refresh(); - } else { - updateStyle(false); - } - - setFixedWidth(minimum_button_width); - } - - void refresh() { - if (!key.empty()) { - bool state = params.getBool(key); - if (state != is_enabled) { - is_enabled = state; - } - updateStyle(is_enabled); - } - } - - void updateButton() { - if (!key.empty()) { - params.putBool(key, !is_enabled); - refresh(); - } - } - -private: - std::string key = ""; - Params params; - bool is_enabled; - QString buttonStyle; - - QString btn_enabled_off_style = "QPushButton:enabled { background-color: #393939; }"; - QString btn_enabled_on_style = "QPushButton:enabled { background-color: #1e79e8; }"; - QString btn_off_pressed_style = "QPushButton:pressed { background-color: #4A4A4A; }"; - QString btn_on_pressed_style = "QPushButton:pressed { background-color: #1E8FFF; }"; - QString btn_disabled_style = "QPushButton:disabled { background-color: #121212; color: #5C5C5C; }"; - - void updateStyle(bool enabled) { - QString enabled_style = enabled ? btn_enabled_on_style : btn_enabled_off_style; - QString pressed_style = enabled ? btn_on_pressed_style : btn_off_pressed_style; - setStyleSheet(buttonStyle + enabled_style + pressed_style + btn_disabled_style); - } -}; - -class PanelBackButton : public QPushButton { - Q_OBJECT - -public: - PanelBackButton(const QString &label = "Back", QWidget *parent = nullptr) : QPushButton(label, parent) { - setObjectName("back_btn"); - setFixedSize(400, 100); - } -}; diff --git a/selfdrive/ui/sunnypilot/qt/widgets/drive_stats.cc b/selfdrive/ui/sunnypilot/qt/widgets/drive_stats.cc deleted file mode 100644 index bfdcac2564..0000000000 --- a/selfdrive/ui/sunnypilot/qt/widgets/drive_stats.cc +++ /dev/null @@ -1,103 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/widgets/drive_stats.h" - -#include -#include -#include - -#include "common/params.h" -#include "selfdrive/ui/qt/request_repeater.h" -#include "selfdrive/ui/qt/util.h" - -static QLabel* newLabel(const QString& text, const QString &type) { - QLabel* label = new QLabel(text); - label->setProperty("type", type); - return label; -} - -DriveStats::DriveStats(QWidget* parent) : QFrame(parent) { - metric_ = Params().getBool("IsMetric"); - - QVBoxLayout* main_layout = new QVBoxLayout(this); - main_layout->setContentsMargins(50, 50, 50, 60); - - auto add_stats_layouts = [=](const QString &title, StatsLabels& labels) { - QGridLayout* grid_layout = new QGridLayout; - grid_layout->setVerticalSpacing(10); - grid_layout->setContentsMargins(0, 10, 0, 10); - - int row = 0; - grid_layout->addWidget(newLabel(title, "title"), row++, 0, 1, 3); - grid_layout->addItem(new QSpacerItem(0, 30), row++, 0, 1, 1); - - grid_layout->addWidget(labels.routes = newLabel("0", "number"), row, 0, Qt::AlignLeft); - grid_layout->addWidget(labels.distance = newLabel("0", "number"), row, 1, Qt::AlignLeft); - grid_layout->addWidget(labels.hours = newLabel("0", "number"), row, 2, Qt::AlignLeft); - - grid_layout->addWidget(newLabel((tr("Drives")), "unit"), row + 1, 0, Qt::AlignLeft); - grid_layout->addWidget(labels.distance_unit = newLabel(getDistanceUnit(), "unit"), row + 1, 1, Qt::AlignLeft); - grid_layout->addWidget(newLabel(tr("Hours"), "unit"), row + 1, 2, Qt::AlignLeft); - - main_layout->addLayout(grid_layout); - }; - - add_stats_layouts(tr("ALL TIME"), all_); - main_layout->addStretch(); - add_stats_layouts(tr("PAST WEEK"), week_); - - if (auto dongleId = getDongleId()) { - QString url = CommaApi::BASE_URL + "/v1.1/devices/" + *dongleId + "/stats"; - RequestRepeater* repeater = new RequestRepeater(this, url, "ApiCache_DriveStats", 30); - QObject::connect(repeater, &RequestRepeater::requestDone, this, &DriveStats::parseResponse); - } - - setStyleSheet(R"( - DriveStats { - background-color: #333333; - border-radius: 10px; - } - - QLabel[type="title"] { font-size: 51px; font-weight: 500; } - QLabel[type="number"] { font-size: 78px; font-weight: 500; } - QLabel[type="unit"] { font-size: 51px; font-weight: 300; color: #A0A0A0; } - )"); -} - -void DriveStats::updateStats() { - auto update = [=](const QJsonObject& obj, StatsLabels& labels) { - labels.routes->setText(QString::number((int)obj["routes"].toDouble())); - labels.distance->setText(QString::number(int(obj["distance"].toDouble() * (metric_ ? MILE_TO_KM : 1)))); - labels.distance_unit->setText(getDistanceUnit()); - labels.hours->setText(QString::number((int)(obj["minutes"].toDouble() / 60))); - }; - - QJsonObject json = stats_.object(); - update(json["all"].toObject(), all_); - update(json["week"].toObject(), week_); -} - -void DriveStats::parseResponse(const QString& response, bool success) { - if (!success) return; - - QJsonDocument doc = QJsonDocument::fromJson(response.trimmed().toUtf8()); - if (doc.isNull()) { - qDebug() << "JSON Parse failed on getting past drives statistics"; - return; - } - stats_ = doc; - updateStats(); -} - -void DriveStats::showEvent(QShowEvent* event) { - bool metric = Params().getBool("IsMetric"); - if (metric_ != metric) { - metric_ = metric; - updateStats(); - } -} diff --git a/selfdrive/ui/sunnypilot/qt/widgets/drive_stats.h b/selfdrive/ui/sunnypilot/qt/widgets/drive_stats.h deleted file mode 100644 index 0b2802ed8c..0000000000 --- a/selfdrive/ui/sunnypilot/qt/widgets/drive_stats.h +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include -#include - -class DriveStats : public QFrame { - Q_OBJECT - -public: - explicit DriveStats(QWidget* parent = 0); - -private: - void showEvent(QShowEvent *event) override; - void updateStats(); - inline QString getDistanceUnit() const { return metric_ ? tr("KM") : tr("Miles"); } - - bool metric_; - QJsonDocument stats_; - struct StatsLabels { - QLabel *routes, *distance, *distance_unit, *hours; - } all_, week_; - -private slots: - void parseResponse(const QString &response, bool success); -}; diff --git a/selfdrive/ui/sunnypilot/qt/widgets/expandable_row.cc b/selfdrive/ui/sunnypilot/qt/widgets/expandable_row.cc deleted file mode 100644 index b918938d11..0000000000 --- a/selfdrive/ui/sunnypilot/qt/widgets/expandable_row.cc +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/widgets/expandable_row.h" - -ExpandableToggleRow::ExpandableToggleRow(const QString ¶m, const QString &title, const QString &desc, const QString &icon, QWidget *parent) - : ToggleControlSP(title, desc, icon, false, parent) { - - key = param.toStdString(); - QObject::connect(this, &ExpandableToggleRow::toggleFlipped, this, &ExpandableToggleRow::toggleClicked); - - collapsibleWidget = new QFrame(this); - collapsibleWidget->setContentsMargins(0, 0, 0, 0); - collapsibleWidget->setVisible(false); - QVBoxLayout *collapsible_layout = new QVBoxLayout(); - collapsibleWidget->setLayout(collapsible_layout); - - list = new ListWidgetSP(this, false); - - main_layout->addWidget(collapsibleWidget); - collapsible_layout->addWidget(list); -} - -void ExpandableToggleRow::toggleClicked(bool state) { - params.putBool(key, state); - collapsibleWidget->setVisible(state); -} diff --git a/selfdrive/ui/sunnypilot/qt/widgets/expandable_row.h b/selfdrive/ui/sunnypilot/qt/widgets/expandable_row.h deleted file mode 100644 index 4bfcb9ef55..0000000000 --- a/selfdrive/ui/sunnypilot/qt/widgets/expandable_row.h +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/sunnypilot/qt/widgets/controls.h" - -class ExpandableToggleRow : public ToggleControlSP { - Q_OBJECT - -public: - ExpandableToggleRow(const QString ¶m, const QString &title, const QString &desc, const QString &icon, QWidget *parent = nullptr); - - void addItem(QWidget *widget) { - list->addItem(widget); - } - - ListWidgetSP *innerList() { - return list; - } - - void refresh() { - bool state = params.getBool(key); - if (state != toggle.on) { - toggle.togglePosition(); - } - collapsibleWidget->setVisible(state); - } - - bool isToggled() { - return params.getBool(key); - } - - void showEvent(QShowEvent *event) override { - refresh(); - } - -private: - void toggleClicked(bool state); - - std::string key; - Params params; - - ListWidgetSP *list; - QFrame *collapsibleWidget = nullptr; -}; diff --git a/selfdrive/ui/sunnypilot/qt/widgets/prime.cc b/selfdrive/ui/sunnypilot/qt/widgets/prime.cc deleted file mode 100644 index a1bb85c787..0000000000 --- a/selfdrive/ui/sunnypilot/qt/widgets/prime.cc +++ /dev/null @@ -1,19 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/widgets/prime.h" - -SetupWidgetSP::SetupWidgetSP(QWidget *parent) : SetupWidget(parent) { - PrimeUserWidget *primeUser = new PrimeUserWidget; - content_layout->insertWidget(0, primeUser); - - primeUser->setVisible(uiState()->prime_state->isSubscribed()); - - QObject::connect(uiState()->prime_state, &PrimeState::changed, [=]() { - primeUser->setVisible(uiState()->prime_state->isSubscribed()); - }); -} diff --git a/selfdrive/ui/sunnypilot/qt/widgets/prime.h b/selfdrive/ui/sunnypilot/qt/widgets/prime.h deleted file mode 100644 index 598b0e62eb..0000000000 --- a/selfdrive/ui/sunnypilot/qt/widgets/prime.h +++ /dev/null @@ -1,19 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/qt/widgets/prime.h" - -#include "selfdrive/ui/sunnypilot/ui.h" - -class SetupWidgetSP : public SetupWidget { - Q_OBJECT - -public: - explicit SetupWidgetSP(QWidget *parent = nullptr); -}; diff --git a/selfdrive/ui/sunnypilot/qt/widgets/scrollview.cc b/selfdrive/ui/sunnypilot/qt/widgets/scrollview.cc deleted file mode 100644 index ba9a367b0e..0000000000 --- a/selfdrive/ui/sunnypilot/qt/widgets/scrollview.cc +++ /dev/null @@ -1,18 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/widgets/scrollview.h" - -#include - -void ScrollViewSP::setLastScrollPosition() { - lastScrollPosition = verticalScrollBar()->value(); -} - -void ScrollViewSP::restoreScrollPosition() { - verticalScrollBar()->setValue(lastScrollPosition); -} diff --git a/selfdrive/ui/sunnypilot/qt/widgets/scrollview.h b/selfdrive/ui/sunnypilot/qt/widgets/scrollview.h deleted file mode 100644 index 5c20bce2f2..0000000000 --- a/selfdrive/ui/sunnypilot/qt/widgets/scrollview.h +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/qt/widgets/scrollview.h" - -class ScrollViewSP : public ScrollView { - Q_OBJECT - -public: - explicit ScrollViewSP(QWidget *w = nullptr, QWidget *parent = nullptr) : ScrollView(w, parent) {} - -public slots: - void setLastScrollPosition(); - void restoreScrollPosition(); - -private: - int lastScrollPosition = 0; -}; diff --git a/selfdrive/ui/sunnypilot/qt/widgets/toggle.cc b/selfdrive/ui/sunnypilot/qt/widgets/toggle.cc deleted file mode 100644 index 601c8f94c1..0000000000 --- a/selfdrive/ui/sunnypilot/qt/widgets/toggle.cc +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/widgets/toggle.h" - -#include - -ToggleSP::ToggleSP(QWidget *parent) : Toggle(parent) { - _height_rect = 80; -} - -void ToggleSP::paintEvent(QPaintEvent *e) { - this->setFixedHeight(100); - QPainter p(this); - p.setPen(Qt::NoPen); - p.setRenderHint(QPainter::Antialiasing, true); - - // Draw toggle background - enabled ? green.setRgb(0x1e79e8) : green.setRgb(0x125db8); - p.setBrush(on ? green : QColor(0x292929)); - p.drawRoundedRect(QRect(0, 10, width(), _height_rect), _height_rect / 2, _height_rect / 2); - - // Draw toggle circle - p.setBrush(circleColor); - p.drawEllipse(QRectF(_x_circle - _radius + 6, 16, 68, 68)); -} diff --git a/selfdrive/ui/sunnypilot/qt/widgets/toggle.h b/selfdrive/ui/sunnypilot/qt/widgets/toggle.h deleted file mode 100644 index e98dea39af..0000000000 --- a/selfdrive/ui/sunnypilot/qt/widgets/toggle.h +++ /dev/null @@ -1,20 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/qt/widgets/toggle.h" - -class ToggleSP : public Toggle { - Q_OBJECT - -public: - explicit ToggleSP(QWidget *parent = nullptr); - -protected: - void paintEvent(QPaintEvent *) override; -}; diff --git a/selfdrive/ui/sunnypilot/qt/window.cc b/selfdrive/ui/sunnypilot/qt/window.cc deleted file mode 100644 index f332e1ed8e..0000000000 --- a/selfdrive/ui/sunnypilot/qt/window.cc +++ /dev/null @@ -1,19 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/qt/window.h" - -MainWindowSP::MainWindowSP(QWidget *parent) - : MainWindow(parent, new HomeWindowSP(parent), new SettingsWindowSP(parent)) { - - homeWindow = dynamic_cast(MainWindow::homeWindow); - settingsWindow = dynamic_cast(MainWindow::settingsWindow); -} - -void MainWindowSP::closeSettings() { - MainWindow::closeSettings(); -} diff --git a/selfdrive/ui/sunnypilot/qt/window.h b/selfdrive/ui/sunnypilot/qt/window.h deleted file mode 100644 index d4c0900901..0000000000 --- a/selfdrive/ui/sunnypilot/qt/window.h +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include "selfdrive/ui/qt/window.h" -#include "selfdrive/ui/sunnypilot/qt/home.h" -#include "selfdrive/ui/sunnypilot/qt/offroad/settings/settings.h" - -class MainWindowSP : public MainWindow { - Q_OBJECT - -public: - explicit MainWindowSP(QWidget *parent = 0); - -private: - HomeWindowSP *homeWindow; - SettingsWindowSP *settingsWindow; - void closeSettings() override; -}; diff --git a/selfdrive/ui/sunnypilot/ui.cc b/selfdrive/ui/sunnypilot/ui.cc deleted file mode 100644 index b2701356cc..0000000000 --- a/selfdrive/ui/sunnypilot/ui.cc +++ /dev/null @@ -1,72 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#include "selfdrive/ui/sunnypilot/ui.h" - -#include "common/watchdog.h" - -void UIStateSP::updateStatus() { - UIState::updateStatus(); -} - -UIStateSP::UIStateSP(QObject *parent) : UIState(parent) { - sm = std::make_unique(std::vector{ - "modelV2", "controlsState", "liveCalibration", "radarState", "deviceState", - "pandaStates", "carParams", "driverMonitoringState", "carState", "driverStateV2", - "wideRoadCameraState", "managerState", "selfdriveState", "longitudinalPlan", - "modelManagerSP", "selfdriveStateSP", "longitudinalPlanSP", "backupManagerSP" - }); - - // update timer - timer = new QTimer(this); - QObject::connect(timer, &QTimer::timeout, this, &UIStateSP::update); - timer->start(1000 / UI_FREQ); -} - -// This method overrides completely the update method from the parent class intentionally. -void UIStateSP::update() { - update_sockets(this); - update_state(this); - updateStatus(); - - if (sm->frame % UI_FREQ == 0) { - watchdog_kick(nanos_since_boot()); - } - emit uiUpdate(*this); -} - -DeviceSP::DeviceSP(QObject *parent) : Device(parent) { - QObject::connect(uiStateSP(), &UIStateSP::uiUpdate, this, &DeviceSP::update); - QObject::connect(this, &Device::displayPowerChanged, this, &DeviceSP::handleDisplayPowerChanged); -} - -UIStateSP *uiStateSP() { - static UIStateSP ui_state; - return &ui_state; -} - -void UIStateSP::setSunnylinkRoles(const std::vector& roles) { - sunnylinkRoles = roles; - emit sunnylinkRolesChanged(roles); -} - -void UIStateSP::setSunnylinkDeviceUsers(const std::vector& users) { - sunnylinkUsers = users; - emit sunnylinkDeviceUsersChanged(users); -} - -DeviceSP *deviceSP() { - static DeviceSP _device; - return &_device; -} - -void DeviceSP::handleDisplayPowerChanged(bool on) { - // if enabled, trigger offroad mode when device goes to sleep - if (params.get("DeviceBootMode") == "1" && not on) { - params.putBool("OffroadMode", true); - } -} diff --git a/selfdrive/ui/sunnypilot/ui.h b/selfdrive/ui/sunnypilot/ui.h deleted file mode 100644 index cf8de1c4bb..0000000000 --- a/selfdrive/ui/sunnypilot/ui.h +++ /dev/null @@ -1,94 +0,0 @@ -/** - * Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - * - * This file is part of sunnypilot and is licensed under the MIT License. - * See the LICENSE.md file in the root directory for more details. - */ - -#pragma once - -#include - -#include "selfdrive/ui/sunnypilot/qt/network/sunnylink/models/user_model.h" -#include "selfdrive/ui/sunnypilot/qt/network/sunnylink/models/role_model.h" -#include "selfdrive/ui/sunnypilot/qt/network/sunnylink/models/sponsor_role_model.h" -#include "selfdrive/ui/ui.h" - -class UIStateSP : public UIState { - Q_OBJECT - -public: - UIStateSP(QObject *parent = 0); - void updateStatus() override; - inline bool engaged() const override { - return scene.started && ( - (*sm)["selfdriveState"].getSelfdriveState().getEnabled() || (*sm)["selfdriveStateSP"].getSelfdriveStateSP().getMads().getEnabled() - ); - } - void setSunnylinkRoles(const std::vector &roles); - void setSunnylinkDeviceUsers(const std::vector &users); - - inline std::vector sunnylinkDeviceRoles() const { return sunnylinkRoles; } - inline bool isSunnylinkAdmin() const { - return std::any_of(sunnylinkRoles.begin(), sunnylinkRoles.end(), [](const RoleModel &role) { - return role.roleType == RoleType::Admin; - }); - } - inline bool isSunnylinkSponsor() const { - return std::any_of(sunnylinkRoles.begin(), sunnylinkRoles.end(), [](const RoleModel &role) { - return role.roleType == RoleType::Sponsor && role.as().roleTier != SponsorTier::Free; - }); - } - inline SponsorRoleModel sunnylinkSponsorRole() const { - std::optional sponsorRoleWithHighestTier = std::nullopt; - for (const auto &role : sunnylinkRoles) { - if(role.roleType != RoleType::Sponsor) - continue; - - if (auto sponsorRole = role.as(); !sponsorRoleWithHighestTier.has_value() || sponsorRoleWithHighestTier->roleTier < sponsorRole.roleTier) { - sponsorRoleWithHighestTier = sponsorRole; - } - } - return sponsorRoleWithHighestTier.value_or(SponsorRoleModel(RoleType::Sponsor, SponsorTier::Free)); - } - inline SponsorTier sunnylinkSponsorTier() const { - return sunnylinkSponsorRole().roleTier; - } - inline std::vector sunnylinkDeviceUsers() const { return sunnylinkUsers; } - inline bool isSunnylinkPaired() const { - return std::any_of(sunnylinkUsers.begin(), sunnylinkUsers.end(), [](const UserModel &user) { - return user.user_id.toLower() != "unregisteredsponsor" && user.user_id.toLower() != "temporarysponsor"; - }); - } - -signals: - void sunnylinkRoleChanged(bool subscriber); - void sunnylinkRolesChanged(std::vector roles); - void sunnylinkDeviceUsersChanged(std::vector users); - void uiUpdate(const UIStateSP &s); - -private slots: - void update() override; - -private: - std::vector sunnylinkRoles = {}; - std::vector sunnylinkUsers = {}; -}; - -UIStateSP *uiStateSP(); -inline UIStateSP *uiState() { return uiStateSP(); }; - -// device management class -class DeviceSP : public Device { - Q_OBJECT - -public: - DeviceSP(QObject *parent = 0); - -private: - Params params; - void handleDisplayPowerChanged(bool on); -}; - -DeviceSP *deviceSP(); -inline DeviceSP *device() { return deviceSP(); } diff --git a/selfdrive/ui/tests/.gitignore b/selfdrive/ui/tests/.gitignore deleted file mode 100644 index 91898ac59a..0000000000 --- a/selfdrive/ui/tests/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -test -test_translations -test_ui/report_1 \ No newline at end of file diff --git a/selfdrive/ui/tests/body.py b/selfdrive/ui/tests/body.py deleted file mode 100755 index 07a2ef5128..0000000000 --- a/selfdrive/ui/tests/body.py +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/env python3 -import time -import cereal.messaging as messaging - -if __name__ == "__main__": - while True: - pm = messaging.PubMaster(['carParams', 'carState']) - batt = 1. - while True: - msg = messaging.new_message('carParams') - msg.carParams.brand = "body" - msg.carParams.notCar = True - pm.send('carParams', msg) - - for b in range(100, 0, -1): - msg = messaging.new_message('carState') - msg.carState.charging = True - msg.carState.fuelGauge = b / 100. - pm.send('carState', msg) - time.sleep(0.1) - - time.sleep(1) diff --git a/selfdrive/ui/tests/create_test_translations.sh b/selfdrive/ui/tests/create_test_translations.sh deleted file mode 100755 index ed0890d946..0000000000 --- a/selfdrive/ui/tests/create_test_translations.sh +++ /dev/null @@ -1,18 +0,0 @@ -#!/usr/bin/env bash - -set -e - -UI_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )"/.. -TEST_TEXT="(WRAPPED_SOURCE_TEXT)" -TEST_TS_FILE=$UI_DIR/translations/main_test_en.ts -TEST_QM_FILE=$UI_DIR/translations/main_test_en.qm - -# translation strings -UNFINISHED="<\/translation>" -TRANSLATED="$TEST_TEXT<\/translation>" - -mkdir -p $UI_DIR/translations -rm -f $TEST_TS_FILE $TEST_QM_FILE -lupdate -recursive "$UI_DIR" -ts $TEST_TS_FILE -sed -i "s/$UNFINISHED/$TRANSLATED/" $TEST_TS_FILE -lrelease $TEST_TS_FILE diff --git a/selfdrive/ui/tests/cycle_offroad_alerts.py b/selfdrive/ui/tests/cycle_offroad_alerts.py deleted file mode 100755 index e468d88e0e..0000000000 --- a/selfdrive/ui/tests/cycle_offroad_alerts.py +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env python3 -import os -import sys -import time -import json - -from openpilot.common.basedir import BASEDIR -from openpilot.common.params import Params -from openpilot.selfdrive.selfdrived.alertmanager import set_offroad_alert - -if __name__ == "__main__": - params = Params() - - with open(os.path.join(BASEDIR, "selfdrive/selfdrived/alerts_offroad.json")) as f: - offroad_alerts = json.load(f) - - t = 10 if len(sys.argv) < 2 else int(sys.argv[1]) - while True: - print("setting alert update") - params.put_bool("UpdateAvailable", True) - r = open(os.path.join(BASEDIR, "RELEASES.md")).read() - r = r[:r.find('\n\n')] # Slice latest release notes - params.put("UpdaterNewReleaseNotes", r + "\n") - - time.sleep(t) - params.put_bool("UpdateAvailable", False) - - # cycle through normal alerts - for a in offroad_alerts: - print("setting alert:", a) - set_offroad_alert(a, True) - time.sleep(t) - set_offroad_alert(a, False) - - print("no alert") - time.sleep(t) diff --git a/selfdrive/ui/tests/test_runner.cc b/selfdrive/ui/tests/test_runner.cc deleted file mode 100644 index c8cc0d3e05..0000000000 --- a/selfdrive/ui/tests/test_runner.cc +++ /dev/null @@ -1,26 +0,0 @@ -#define CATCH_CONFIG_RUNNER -#include "catch2/catch.hpp" - -#include -#include -#include -#include - -int main(int argc, char **argv) { - // unit tests for Qt - QApplication app(argc, argv); - - QString language_file = "main_test_en"; - // FIXME: pytest-cpp considers this print as a test case - qDebug() << "Loading language:" << language_file; - - QTranslator translator; - QString translationsPath = QDir::cleanPath(qApp->applicationDirPath() + "/../translations"); - if (!translator.load(language_file, translationsPath)) { - qDebug() << "Failed to load translation file!"; - } - app.installTranslator(&translator); - - const int res = Catch::Session().run(argc, argv); - return (res < 0xff ? res : 0xff); -} diff --git a/selfdrive/ui/tests/test_soundd.py b/selfdrive/ui/tests/test_soundd.py deleted file mode 100644 index a9da8455eb..0000000000 --- a/selfdrive/ui/tests/test_soundd.py +++ /dev/null @@ -1,35 +0,0 @@ -from cereal import car -from cereal import messaging -from cereal.messaging import SubMaster, PubMaster -from openpilot.selfdrive.ui.soundd import SELFDRIVE_STATE_TIMEOUT, check_selfdrive_timeout_alert - -import time - -AudibleAlert = car.CarControl.HUDControl.AudibleAlert - - -class TestSoundd: - def test_check_selfdrive_timeout_alert(self): - sm = SubMaster(['selfdriveState']) - pm = PubMaster(['selfdriveState']) - - for _ in range(100): - cs = messaging.new_message('selfdriveState') - cs.selfdriveState.enabled = True - - pm.send("selfdriveState", cs) - - time.sleep(0.01) - - sm.update(0) - - assert not check_selfdrive_timeout_alert(sm) - - for _ in range(SELFDRIVE_STATE_TIMEOUT * 110): - sm.update(0) - time.sleep(0.01) - - assert check_selfdrive_timeout_alert(sm) - - # TODO: add test with micd for checking that soundd actually outputs sounds - diff --git a/selfdrive/ui/tests/test_translations.cc b/selfdrive/ui/tests/test_translations.cc deleted file mode 100644 index fcefc5784f..0000000000 --- a/selfdrive/ui/tests/test_translations.cc +++ /dev/null @@ -1,48 +0,0 @@ -#include "catch2/catch.hpp" - -#include "common/params.h" -#include "selfdrive/ui/qt/window.h" - -const QString TEST_TEXT = "(WRAPPED_SOURCE_TEXT)"; // what each string should be translated to -QRegExp RE_NUM("\\d*"); - -QStringList getParentWidgets(QWidget* widget){ - QStringList parentWidgets; - while (widget->parentWidget() != Q_NULLPTR) { - widget = widget->parentWidget(); - parentWidgets.append(widget->metaObject()->className()); - } - return parentWidgets; -} - -template -void checkWidgetTrWrap(MainWindow &w) { - for (auto widget : w.findChildren()) { - const QString text = widget->text(); - bool isNumber = RE_NUM.exactMatch(text); - bool wrapped = text.contains(TEST_TEXT); - QString parentWidgets = getParentWidgets(widget).join("->"); - - if (!text.isEmpty() && !isNumber && !wrapped) { - FAIL(("\"" + text + "\" must be wrapped. Parent widgets: " + parentWidgets).toStdString()); - } - - // warn if source string wrapped, but UI adds text - // TODO: add way to ignore this - if (wrapped && text != TEST_TEXT) { - WARN(("\"" + text + "\" is dynamic and needs a custom retranslate function. Parent widgets: " + parentWidgets).toStdString()); - } - } -} - -// Tests all strings in the UI are wrapped with tr() -TEST_CASE("UI: test all strings wrapped") { - Params().remove("LanguageSetting"); - Params().remove("HardwareSerial"); - Params().remove("DongleId"); - qputenv("TICI", "1"); - - MainWindow w; - checkWidgetTrWrap(w); - checkWidgetTrWrap(w); -} diff --git a/selfdrive/ui/tests/test_translations.py b/selfdrive/ui/tests/test_translations.py deleted file mode 100644 index 2ae3356bb8..0000000000 --- a/selfdrive/ui/tests/test_translations.py +++ /dev/null @@ -1,124 +0,0 @@ -import pytest -import json -import os -import re -import xml.etree.ElementTree as ET -import string -import requests -from parameterized import parameterized_class - -from openpilot.selfdrive.ui.update_translations import TRANSLATIONS_DIR, LANGUAGES_FILE - -with open(LANGUAGES_FILE) as f: - translation_files = json.load(f) - -UNFINISHED_TRANSLATION_TAG = "" not in cur_translations, \ - f"{self.file} ({self.name}) translation file has obsolete translations. Run selfdrive/ui/update_translations.py --vanish to remove them" - - def test_finished_translations(self): - """ - Tests ran on each translation marked "finished" - Plural: - - that any numerus (plural) translations have all plural forms non-empty - - that the correct format specifier is used (%n) - Non-plural: - - that translation is not empty - - that translation format arguments are consistent - """ - tr_xml = ET.parse(os.path.join(TRANSLATIONS_DIR, f"{self.file}.ts")) - - for context in tr_xml.getroot(): - for message in context.iterfind("message"): - translation = message.find("translation") - source_text = message.find("source").text - - # Do not test unfinished translations - if translation.get("type") == "unfinished": - continue - - if message.get("numerus") == "yes": - numerusform = [t.text for t in translation.findall("numerusform")] - - for nf in numerusform: - assert nf is not None, f"Ensure all plural translation forms are completed: {source_text}" - assert "%n" in nf, "Ensure numerus argument (%n) exists in translation." - assert FORMAT_ARG.search(nf) is None, f"Plural translations must use %n, not %1, %2, etc.: {numerusform}" - - else: - assert translation.text is not None, f"Ensure translation is completed: {source_text}" - - source_args = FORMAT_ARG.findall(source_text) - translation_args = FORMAT_ARG.findall(translation.text) - assert sorted(source_args) == sorted(translation_args), \ - f"Ensure format arguments are consistent: `{source_text}` vs. `{translation.text}`" - - def test_no_locations(self): - for line in self._read_translation_file(TRANSLATIONS_DIR, self.file).splitlines(): - assert not line.strip().startswith(LOCATION_TAG), \ - f"Line contains location tag: {line.strip()}, remove all line numbers." - - def test_entities_error(self): - cur_translations = self._read_translation_file(TRANSLATIONS_DIR, self.file) - matches = re.findall(r'@(\w+);', cur_translations) - assert len(matches) == 0, f"The string(s) {matches} were found with '@' instead of '&'" - - def test_bad_language(self): - IGNORED_WORDS = {'pédale'} - - match = re.search(r'_([a-zA-Z]{2,3})', self.file) - assert match, f"{self.name} - could not parse language" - - try: - response = requests.get( - f"https://raw.githubusercontent.com/LDNOOBW/List-of-Dirty-Naughty-Obscene-and-Otherwise-Bad-Words/master/{match.group(1)}" - ) - response.raise_for_status() - except requests.exceptions.HTTPError as e: - if e.response is not None and e.response.status_code == 429: - pytest.skip("word list rate limited") - raise - - banned_words = {line.strip() for line in response.text.splitlines()} - - for context in ET.parse(os.path.join(TRANSLATIONS_DIR, f"{self.file}.ts")).getroot(): - for message in context.iterfind("message"): - translation = message.find("translation") - if translation.get("type") == "unfinished": - continue - - translation_text = " ".join([t.text for t in translation.findall("numerusform")]) if message.get("numerus") == "yes" else translation.text - - if not translation_text: - continue - - words = set(translation_text.translate(str.maketrans('', '', string.punctuation + '%n')).lower().split()) - bad_words_found = words & (banned_words - IGNORED_WORDS) - assert not bad_words_found, f"Bad language found in {self.name}: '{translation_text}'. Bad word(s): {', '.join(bad_words_found)}" diff --git a/selfdrive/ui/tests/test_ui/run.py b/selfdrive/ui/tests/test_ui/run.py deleted file mode 100755 index b263e28297..0000000000 --- a/selfdrive/ui/tests/test_ui/run.py +++ /dev/null @@ -1,419 +0,0 @@ -#!/usr/bin/env python3 -import capnp -import json -import pathlib -import shutil -import sys -import os -import pywinctl -import pyautogui -import pickle -import time -from collections import namedtuple - -from cereal import car, log, custom -from msgq.visionipc import VisionIpcServer, VisionStreamType -from cereal.messaging import PubMaster, log_from_bytes, sub_sock -from openpilot.common.basedir import BASEDIR -from openpilot.common.params import Params -from openpilot.common.prefix import OpenpilotPrefix -from openpilot.common.transformations.camera import CameraConfig, DEVICE_CAMERAS -from openpilot.selfdrive.selfdrived.alertmanager import set_offroad_alert -from openpilot.selfdrive.test.helpers import with_processes -from openpilot.selfdrive.test.process_replay.migration import migrate, migrate_controlsState, migrate_carState -from openpilot.tools.lib.logreader import LogReader -from openpilot.tools.lib.framereader import FrameReader -from openpilot.tools.lib.route import Route -from openpilot.tools.lib.cache import DEFAULT_CACHE_DIR - -UI_DELAY = 0.5 # may be slower on CI? -TEST_ROUTE = "a2a0ccea32023010|2023-07-27--13-01-19" - -STREAMS: list[tuple[VisionStreamType, CameraConfig, bytes]] = [] -OFFROAD_ALERTS = ['Offroad_StorageMissing', 'Offroad_IsTakingSnapshot'] -DATA: dict[str, capnp.lib.capnp._DynamicStructBuilder] = dict.fromkeys( - ["carParams", "deviceState", "pandaStates", "controlsState", "selfdriveState", - "liveCalibration", "modelV2", "radarState", "driverMonitoringState", "carState", - "driverStateV2", "roadCameraState", "wideRoadCameraState", "driverCameraState"], None) - -def setup_homescreen(click, pm: PubMaster, scroll=None): - time.sleep(UI_DELAY) - -def setup_settings_device(click, pm: PubMaster, scroll=None): - click(100, 100) - -def setup_settings_network(click, pm: PubMaster, scroll=None): - setup_settings_device(click, pm) - click(278, 405) - -def setup_settings_network_advanced(click, pm: PubMaster, scroll=None): - setup_settings_network(click, pm) - click(1913, 90) - -def setup_settings_toggles(click, pm: PubMaster, scroll=None): - setup_settings_device(click, pm) - click(278, 632) - time.sleep(UI_DELAY) - -def setup_settings_software(click, pm: PubMaster, scroll=None): - setup_settings_device(click, pm) - click(278, 742) - time.sleep(UI_DELAY) - -def setup_settings_firehose(click, pm: PubMaster, scroll=None): - setup_settings_device(click, pm) - scroll(-400, 278, 962) - click(278, 862) - -def setup_settings_developer(click, pm: PubMaster, scroll=None): - CP = car.CarParams() - CP.alphaLongitudinalAvailable = True - Params().put("CarParamsPersistent", CP.to_bytes()) - - setup_settings_device(click, pm) - scroll(-400, 278, 962) - click(278, 970) - time.sleep(UI_DELAY) - -def setup_onroad(click, pm: PubMaster, scroll=None): - vipc_server = VisionIpcServer("camerad") - for stream_type, cam, _ in STREAMS: - vipc_server.create_buffers(stream_type, 5, cam.width, cam.height) - vipc_server.start_listener() - - uidebug_received_cnt = 0 - packet_id = 0 - uidebug_sock = sub_sock('uiDebug') - - # Condition check for uiDebug processing - check_uidebug = DATA['deviceState'].deviceState.started and not DATA['carParams'].carParams.notCar - - # Loop until 20 'uiDebug' messages are received - while uidebug_received_cnt <= 20: - for service, data in DATA.items(): - if data: - data.clear_write_flag() - pm.send(service, data) - - for stream_type, _, image in STREAMS: - vipc_server.send(stream_type, image, packet_id, packet_id, packet_id) - - if check_uidebug: - while uidebug_sock.receive(non_blocking=True): - uidebug_received_cnt += 1 - else: - uidebug_received_cnt += 1 - - packet_id += 1 - time.sleep(0.05) - -def setup_onroad_disengaged(click, pm: PubMaster, scroll=None): - DATA['selfdriveState'].selfdriveState.enabled = False - setup_onroad(click, pm) - DATA['selfdriveState'].selfdriveState.enabled = True - -def setup_onroad_override(click, pm: PubMaster, scroll=None): - DATA['selfdriveState'].selfdriveState.state = log.SelfdriveState.OpenpilotState.overriding - setup_onroad(click, pm) - DATA['selfdriveState'].selfdriveState.state = log.SelfdriveState.OpenpilotState.enabled - - -def setup_onroad_wide(click, pm: PubMaster, scroll=None): - DATA['selfdriveState'].selfdriveState.experimentalMode = True - DATA["carState"].carState.vEgo = 1 - setup_onroad(click, pm) - -def setup_onroad_sidebar(click, pm: PubMaster, scroll=None): - setup_onroad(click, pm) - click(500, 500) - setup_onroad(click, pm) - -def setup_onroad_wide_sidebar(click, pm: PubMaster, scroll=None): - setup_onroad_wide(click, pm) - click(500, 500) - setup_onroad_wide(click, pm) - -def setup_body(click, pm: PubMaster, scroll=None): - DATA['carParams'].carParams.brand = "body" - DATA['carParams'].carParams.notCar = True - DATA['carState'].carState.charging = True - DATA['carState'].carState.fuelGauge = 50.0 - setup_onroad(click, pm) - -def setup_keyboard(click, pm: PubMaster, scroll=None): - setup_settings_device(click, pm) - scroll(-400, 278, 962) - click(278, 970) - click(1930, 390) - -def setup_keyboard_uppercase(click, pm: PubMaster, scroll=None): - setup_keyboard(click, pm, scroll) - click(200, 800) - -def setup_driver_camera(click, pm: PubMaster, scroll=None): - setup_settings_device(click, pm) - click(1720, 825) - DATA['deviceState'].deviceState.started = False - setup_onroad(click, pm) - DATA['deviceState'].deviceState.started = True - -def setup_onroad_alert(click, pm: PubMaster, text1, text2, size, status=log.SelfdriveState.AlertStatus.normal): - print(f'setup onroad alert, size: {size}') - state = DATA['selfdriveState'] - origin_state_bytes = state.to_bytes() - cs = state.selfdriveState - cs.alertText1 = text1 - cs.alertText2 = text2 - cs.alertSize = size - cs.alertStatus = status - cs.alertType = "test_onroad_alert" - setup_onroad(click, pm) - DATA['selfdriveState'] = log_from_bytes(origin_state_bytes).as_builder() - -def setup_onroad_alert_small(click, pm: PubMaster, scroll=None): - setup_onroad_alert(click, pm, 'This is a small alert message', '', log.SelfdriveState.AlertSize.small) - -def setup_onroad_alert_mid(click, pm: PubMaster, scroll=None): - setup_onroad_alert(click, pm, 'Medium Alert', 'This is a medium alert message', log.SelfdriveState.AlertSize.mid) - -def setup_onroad_alert_full(click, pm: PubMaster, scroll=None): - setup_onroad_alert(click, pm, 'Full Alert', 'This is a full alert message', log.SelfdriveState.AlertSize.full) - -def setup_offroad_alert(click, pm: PubMaster, scroll=None): - for alert in OFFROAD_ALERTS: - set_offroad_alert(alert, True) - - # Toggle between settings and home to refresh the offroad alert widget - setup_settings_device(click, pm) - click(100, 100) - -def setup_update_available(click, pm: PubMaster, scroll=None): - Params().put_bool("UpdateAvailable", True) - release_notes_path = os.path.join(BASEDIR, "RELEASES.md") - with open(release_notes_path) as file: - release_notes = file.read().split('\n\n', 1)[0] - Params().put("UpdaterNewReleaseNotes", release_notes + "\n") - - setup_settings_device(click, pm) - click(100, 100) - -def setup_pair_device(click, pm: PubMaster, scroll=None): - click(1950, 435) - click(1800, 900) - -def setup_settings_sunnylink(click, pm: PubMaster, scroll=None): - Params().put_bool("SunnylinkEnabled", True) - - setup_settings_device(click, pm) - click(278, 522) - time.sleep(UI_DELAY) - -def setup_settings_sunnylink_sponsor_button(click, pm: PubMaster, scroll=None): - setup_settings_sunnylink(click, pm) - click(1967, 225) - time.sleep(UI_DELAY) - -def setup_settings_models(click, pm: PubMaster, scroll=None): - setup_settings_device(click, pm) - click(278, 852) - time.sleep(UI_DELAY) - - -def setup_settings_steering(click, pm: PubMaster, scroll=None): - CP = car.CarParams() - CP.carFingerprint = "HONDA_CIVIC" - CP_SP = custom.CarParamsSP() - CP_SP.neuralNetworkLateralControl.model.name = CP.carFingerprint - CP_SP.neuralNetworkLateralControl.fuzzyFingerprint = True - Params().put("CarParamsPersistent", CP.to_bytes()) - Params().put("CarParamsSPPersistent", CP_SP.to_bytes()) - - setup_settings_device(click, pm) - click(278, 962) - time.sleep(UI_DELAY) - -def setup_settings_steering_mads(click, pm: PubMaster, scroll=None): - Params().put_bool("Mads", True) - - setup_settings_device(click, pm) - click(278, 962) - click(970, 250) - time.sleep(UI_DELAY) - -def setup_settings_steering_alc(click, pm: PubMaster, scroll=None): - setup_settings_device(click, pm) - click(278, 962) - click(970, 534) - time.sleep(UI_DELAY) - -def setup_settings_cruise(click, pm: PubMaster, scroll=None): - setup_settings_device(click, pm) - scroll(-400, 278, 962) - click(278, 324) - time.sleep(UI_DELAY) - -def setup_settings_visuals(click, pm: PubMaster, scroll=None): - setup_settings_device(click, pm) - scroll(-400, 278, 962) - click(278, 560) - time.sleep(UI_DELAY) - -def setup_settings_trips(click, pm: PubMaster, scroll=None): - setup_settings_device(click, pm) - scroll(-400, 278, 962) - click(278, 646) - time.sleep(UI_DELAY) - -def setup_settings_vehicle(click, pm: PubMaster, scroll=None): - Params().put("CarPlatformBundle", json.dumps( - { - "platform": "HONDA_CIVIC_2022", - "name": "Honda Civic 2022-24" - } - )) - - setup_settings_device(click, pm) - scroll(-400, 278, 962) - click(278, 754) - time.sleep(UI_DELAY) - -CASES = { - "homescreen": setup_homescreen, - "prime": setup_homescreen, - "pair_device": setup_pair_device, - "settings_device": setup_settings_device, - "settings_network": setup_settings_network, - "settings_network_advanced": setup_settings_network_advanced, - "settings_toggles": setup_settings_toggles, - "settings_software": setup_settings_software, - "settings_firehose": setup_settings_firehose, - "settings_developer": setup_settings_developer, - "onroad": setup_onroad, - "onroad_disengaged": setup_onroad_disengaged, - "onroad_override": setup_onroad_override, - "onroad_sidebar": setup_onroad_sidebar, - "onroad_alert_small": setup_onroad_alert_small, - "onroad_alert_mid": setup_onroad_alert_mid, - "onroad_alert_full": setup_onroad_alert_full, - "onroad_wide": setup_onroad_wide, - "onroad_wide_sidebar": setup_onroad_wide_sidebar, - "driver_camera": setup_driver_camera, - "body": setup_body, - "offroad_alert": setup_offroad_alert, - "update_available": setup_update_available, - "keyboard": setup_keyboard, - "keyboard_uppercase": setup_keyboard_uppercase -} - -CASES.update({ - "settings_sunnylink": setup_settings_sunnylink, - "settings_sunnylink_sponsor_button": setup_settings_sunnylink_sponsor_button, - "settings_models": setup_settings_models, - "settings_steering": setup_settings_steering, - "settings_steering_mads": setup_settings_steering_mads, - "settings_steering_alc": setup_settings_steering_alc, - "settings_cruise": setup_settings_cruise, - "settings_visuals": setup_settings_visuals, - "settings_trips": setup_settings_trips, - "settings_vehicle": setup_settings_vehicle, -}) - -TEST_DIR = pathlib.Path(__file__).parent - -TEST_OUTPUT_DIR = TEST_DIR / "report_1" -SCREENSHOTS_DIR = TEST_OUTPUT_DIR / "screenshots" - - -class TestUI: - def __init__(self): - os.environ["SCALE"] = "1" - sys.modules["mouseinfo"] = False - - def setup(self): - self.pm = PubMaster(list(DATA.keys())) - DATA['deviceState'].deviceState.networkType = log.DeviceState.NetworkType.wifi - DATA['deviceState'].deviceState.lastAthenaPingTime = 0 - for _ in range(10): - self.pm.send('deviceState', DATA['deviceState']) - DATA['deviceState'].clear_write_flag() - time.sleep(0.05) - try: - self.ui = pywinctl.getWindowsWithTitle("ui")[0] - except Exception as e: - print(f"failed to find ui window, assuming that it's in the top left (for Xvfb) {e}") - self.ui = namedtuple("bb", ["left", "top", "width", "height"])(0,0,2160,1080) - - def screenshot(self, name): - im = pyautogui.screenshot(SCREENSHOTS_DIR / f"{name}.png", region=(self.ui.left, self.ui.top, self.ui.width, self.ui.height)) - assert im.width == 2160 - assert im.height == 1080 - - def click(self, x, y, *args, **kwargs): - pyautogui.click(self.ui.left + x, self.ui.top + y, *args, **kwargs) - time.sleep(UI_DELAY) # give enough time for the UI to react - - def scroll(self, clicks, x, y, *args, **kwargs): - pyautogui.scroll(clicks, self.ui.left + x, self.ui.top + y, *args, **kwargs) - time.sleep(UI_DELAY) - - @with_processes(["ui"]) - def test_ui(self, name, setup_case): - self.setup() - setup_case(self.click, self.pm, self.scroll) - self.screenshot(name) - -def create_screenshots(): - if TEST_OUTPUT_DIR.exists(): - shutil.rmtree(TEST_OUTPUT_DIR) - - SCREENSHOTS_DIR.mkdir(parents=True) - - route = Route(TEST_ROUTE) - - segnum = 2 - lr = LogReader(route.qlog_paths()[segnum]) - DATA['carParams'] = next((event.as_builder() for event in lr if event.which() == 'carParams'), None) - for event in migrate(lr, [migrate_controlsState, migrate_carState]): - if event.which() in DATA: - DATA[event.which()] = event.as_builder() - - if all(DATA.values()): - break - - cam = DEVICE_CAMERAS[("tici", "ar0231")] - - frames_cache = f'{DEFAULT_CACHE_DIR}/ui_frames' - if os.path.isfile(frames_cache): - with open(frames_cache, 'rb') as f: - frames = pickle.load(f) - road_img = frames[0] - wide_road_img = frames[1] - driver_img = frames[2] - else: - with open(frames_cache, 'wb') as f: - road_img = FrameReader(route.camera_paths()[segnum], pix_fmt="nv12").get(0) - wide_road_img = FrameReader(route.ecamera_paths()[segnum], pix_fmt="nv12").get(0) - driver_img = FrameReader(route.dcamera_paths()[segnum], pix_fmt="nv12").get(0) - pickle.dump([road_img, wide_road_img, driver_img], f) - - STREAMS.append((VisionStreamType.VISION_STREAM_ROAD, cam.fcam, road_img.flatten().tobytes())) - STREAMS.append((VisionStreamType.VISION_STREAM_WIDE_ROAD, cam.ecam, wide_road_img.flatten().tobytes())) - STREAMS.append((VisionStreamType.VISION_STREAM_DRIVER, cam.dcam, driver_img.flatten().tobytes())) - - t = TestUI() - - for name, setup in CASES.items(): - with OpenpilotPrefix(): - params = Params() - params.put("DongleId", "123456789012345") - params.put("SunnylinkDongleId", "123456789012345") - if name == 'prime': - params.put('PrimeType', '1') - elif name == 'pair_device': - params.put('ApiCache_Device', '{"is_paired":0, "prime_type":-1}') - - t.test_ui(name, setup) - -if __name__ == "__main__": - print("creating test screenshots") - create_screenshots() diff --git a/selfdrive/ui/tests/test_ui/template.html b/selfdrive/ui/tests/test_ui/template.html deleted file mode 100644 index 68df5879e6..0000000000 --- a/selfdrive/ui/tests/test_ui/template.html +++ /dev/null @@ -1,34 +0,0 @@ - - - - -{% for name, (image, ref_image) in cases.items() %} - -

{{name}}

-
-
- -
-
- -
- -{% endfor %} - \ No newline at end of file diff --git a/selfdrive/ui/translations/README.md b/selfdrive/ui/translations/README.md deleted file mode 100644 index 4f11fe3388..0000000000 --- a/selfdrive/ui/translations/README.md +++ /dev/null @@ -1,71 +0,0 @@ -# Multilanguage - -[![languages](https://raw.githubusercontent.com/commaai/openpilot/badges/translation_badge.svg)](#) - -## Contributing - -Before getting started, make sure you have set up the openpilot Ubuntu development environment by reading the [tools README.md](/tools/README.md). - -### Policy - -Most of the languages supported by openpilot come from and are maintained by the community via pull requests. A pull request likely to be merged is one that [fixes a translation or adds missing translations.](https://github.com/commaai/openpilot/blob/master/selfdrive/ui/translations/README.md#improving-an-existing-language) - -We also generally merge pull requests adding support for a new language if there are community members willing to maintain it. Maintaining a language is ensuring quality and completion of translations before each openpilot release. - -comma may remove or hide language support from releases depending on translation quality and completeness. - -### Adding a New Language - -openpilot provides a few tools to help contributors manage their translations and to ensure quality. To get started: - -1. Add your new language to [languages.json](/selfdrive/ui/translations/languages.json) with the appropriate [language code](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) and the localized language name (Traditional Chinese is `中文(繁體)`). -2. Generate the XML translation file (`*.ts`): - ```shell - selfdrive/ui/update_translations.py - ``` -3. Edit the translation file, marking each translation as completed: - ```shell - linguist selfdrive/ui/translations/your_language_file.ts - ``` -4. View your finished translations by compiling and starting the UI, then find it in the language selector: - ```shell - scons -j$(nproc) selfdrive/ui && selfdrive/ui/ui - ``` -5. Read [Checking the UI](#checking-the-ui) to double-check your translations fit in the UI. - -### Improving an Existing Language - -Follow step 3. above, you can review existing translations and add missing ones. Once you're done, just open a pull request to openpilot. - -### Checking the UI -Different languages use varying space to convey the same message, so it's a good idea to double-check that your translations do not overlap and fit into each widget. Start the UI (step 4. above) and view each page, making adjustments to translations as needed. - -#### To view offroad alerts: - -With the UI started, you can view the offroad alerts with: -```shell -selfdrive/ui/tests/cycle_offroad_alerts.py -``` - -### Updating the UI - -Any time you edit source code in the UI, you need to update the translations to ensure the line numbers and contexts are up to date (first step above). - -### Testing - -openpilot has a few unit tests to make sure all translations are up-to-date and that all strings are wrapped in a translation marker. They are run in CI, but you can also run them locally. - -Tests translation files up to date: - -```shell -selfdrive/ui/tests/test_translations.py -``` - -Tests all static source strings are wrapped: - -```shell -selfdrive/ui/tests/create_test_translations.sh && selfdrive/ui/tests/test_translations -``` - ---- -![multilanguage_onroad](https://user-images.githubusercontent.com/25857203/178912800-2c798af8-78e3-498e-9e19-35906e0bafff.png) diff --git a/selfdrive/ui/translations/auto_translate.py b/selfdrive/ui/translations/auto_translate.py deleted file mode 100755 index c2e4bbc552..0000000000 --- a/selfdrive/ui/translations/auto_translate.py +++ /dev/null @@ -1,138 +0,0 @@ -#!/usr/bin/env python3 - -import argparse -import json -import os -import pathlib -import xml.etree.ElementTree as ET -from typing import cast - -import requests - -TRANSLATIONS_DIR = pathlib.Path(__file__).resolve().parent -TRANSLATIONS_LANGUAGES = TRANSLATIONS_DIR / "languages.json" - -OPENAI_MODEL = "gpt-4" -OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY") -OPENAI_PROMPT = "You are a professional translator from English to {language} (ISO 639 language code). " + \ - "The following sentence or word is in the GUI of a software called openpilot, translate it accordingly." - - -def get_language_files(languages: list[str] = None) -> dict[str, pathlib.Path]: - files = {} - - with open(TRANSLATIONS_LANGUAGES) as fp: - language_dict = json.load(fp) - - for filename in language_dict.values(): - path = TRANSLATIONS_DIR / f"{filename}.ts" - language = path.stem.split("main_")[1] - - if languages is None or language in languages: - files[language] = path - - return files - - -def translate_phrase(text: str, language: str) -> str: - response = requests.post( - "https://api.openai.com/v1/chat/completions", - json={ - "model": OPENAI_MODEL, - "messages": [ - { - "role": "system", - "content": OPENAI_PROMPT.format(language=language), - }, - { - "role": "user", - "content": text, - }, - ], - "temperature": 0.8, - "max_tokens": 1024, - "top_p": 1, - }, - headers={ - "Authorization": f"Bearer {OPENAI_API_KEY}", - "Content-Type": "application/json", - }, - ) - - if 400 <= response.status_code < 600: - raise requests.HTTPError(f'Error {response.status_code}: {response.json()}', response=response) - - data = response.json() - - return cast(str, data["choices"][0]["message"]["content"]) - - -def translate_file(path: pathlib.Path, language: str, all_: bool) -> None: - tree = ET.parse(path) - - root = tree.getroot() - - for context in root.findall("./context"): - name = context.find("name") - if name is None: - raise ValueError("name not found") - - print(f"Context: {name.text}") - - for message in context.findall("./message"): - source = message.find("source") - translation = message.find("translation") - - if source is None or translation is None: - raise ValueError("source or translation not found") - - if not all_ and translation.attrib.get("type") != "unfinished": - continue - - llm_translation = translate_phrase(cast(str, source.text), language) - - print(f"Source: {source.text}\n" + - f"Current translation: {translation.text}\n" + - f"LLM translation: {llm_translation}") - - translation.text = llm_translation - - with path.open("w", encoding="utf-8") as fp: - fp.write('\n' + - '\n' + - ET.tostring(root, encoding="utf-8").decode()) - - -def main(): - arg_parser = argparse.ArgumentParser("Auto translate") - - group = arg_parser.add_mutually_exclusive_group(required=True) - group.add_argument("-a", "--all-files", action="store_true", help="Translate all files") - group.add_argument("-f", "--file", nargs="+", help="Translate the selected files. (Example: -f fr de)") - - arg_parser.add_argument("-t", "--all-translations", action="store_true", default=False, help="Translate all sections. (Default: only unfinished)") - - args = arg_parser.parse_args() - - if OPENAI_API_KEY is None: - print("OpenAI API key is missing. (Hint: use `export OPENAI_API_KEY=YOUR-KEY` before you run the script).\n" + - "If you don't have one go to: https://beta.openai.com/account/api-keys.") - exit(1) - - files = get_language_files(None if args.all_files else args.file) - - if args.file: - missing_files = set(args.file) - set(files) - if len(missing_files): - print(f"No language files found: {missing_files}") - exit(1) - - print(f"Translation mode: {'all' if args.all_translations else 'only unfinished'}. Files: {list(files)}") - - for lang, path in files.items(): - print(f"Translate {lang} ({path})") - translate_file(path, lang, args.all_translations) - - -if __name__ == "__main__": - main() diff --git a/selfdrive/ui/translations/create_badges.py b/selfdrive/ui/translations/create_badges.py deleted file mode 100755 index 3e14c33255..0000000000 --- a/selfdrive/ui/translations/create_badges.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env python3 -import json -import os -import requests -import xml.etree.ElementTree as ET - -from openpilot.common.basedir import BASEDIR -from openpilot.selfdrive.ui.tests.test_translations import UNFINISHED_TRANSLATION_TAG -from openpilot.selfdrive.ui.update_translations import LANGUAGES_FILE, TRANSLATIONS_DIR - -TRANSLATION_TAG = " 90 else (204, 55, 27)}" - - # Download badge - badge_label = f"LANGUAGE {name}" - badge_message = f"{percent_finished}% complete" - if unfinished_translations != 0: - badge_message += f" ({unfinished_translations} unfinished)" - - r = requests.get(f"{SHIELDS_URL}/{badge_label}-{badge_message}-{color}", timeout=10) - assert r.status_code == 200, "Error downloading badge" - content_svg = r.content.decode("utf-8") - - xml = ET.fromstring(content_svg) - assert "width" in xml.attrib - max_badge_width = max(max_badge_width, int(xml.attrib["width"])) - - # Make tag ids in each badge unique to combine them into one svg - for tag in ("r", "s"): - content_svg = content_svg.replace(f'id="{tag}"', f'id="{tag}{idx}"') - content_svg = content_svg.replace(f'"url(#{tag})"', f'"url(#{tag}{idx})"') - - badge_svg.extend([f'', content_svg, ""]) - - badge_svg.insert(0, '') - badge_svg.append("") - - with open(os.path.join(BASEDIR, "translation_badge.svg"), "w") as badge_f: - badge_f.write("\n".join(badge_svg)) diff --git a/selfdrive/ui/translations/languages.json b/selfdrive/ui/translations/languages.json deleted file mode 100644 index 132b5088d7..0000000000 --- a/selfdrive/ui/translations/languages.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "English": "main_en", - "Deutsch": "main_de", - "Français": "main_fr", - "Português": "main_pt-BR", - "Español": "main_es", - "Türkçe": "main_tr", - "العربية": "main_ar", - "ไทย": "main_th", - "中文(繁體)": "main_zh-CHT", - "中文(简体)": "main_zh-CHS", - "한국어": "main_ko", - "日本語": "main_ja" -} diff --git a/selfdrive/ui/translations/main_ar.ts b/selfdrive/ui/translations/main_ar.ts deleted file mode 100644 index de24097d8f..0000000000 --- a/selfdrive/ui/translations/main_ar.ts +++ /dev/null @@ -1,2134 +0,0 @@ - - - - - AbstractAlert - - Close - إغلاق - - - Snooze Update - تأخير التحديث - - - Reboot and Update - إعادة التشغيل والتحديث - - - - AdvancedNetworking - - Back - السابق - - - Enable Tethering - تمكين الربط - - - Tethering Password - كلمة مرور الربط - - - EDIT - تعديل - - - Enter new tethering password - أدخل كلمة مرور الربط الجديدة - - - IP Address - عنوان IP - - - Enable Roaming - تمكين التجوال - - - APN Setting - إعدادات APN - - - Enter APN - إدخال APN - - - leave blank for automatic configuration - اتركه فارغاً من أجل التكوين التلقائي - - - Cellular Metered - محدود بالاتصال الخلوي - - - Hidden Network - شبكة مخفية - - - CONNECT - الاتصال - - - Enter SSID - أدخل SSID - - - Enter password - أدخل كلمة المرور - - - for "%1" - من أجل "%1" - - - Prevent large data uploads when on a metered cellular connection - - - - default - - - - metered - - - - unmetered - - - - Wi-Fi Network Metered - - - - Prevent large data uploads when on a metered Wi-Fi connection - - - - - AutoLaneChangeTimer - - Auto Lane Change by Blinker - - - - Set a timer to delay the auto lane change operation when the blinker is used. No nudge on the steering wheel is required to auto lane change if a timer is set. Default is Nudge. -Please use caution when using this feature. Only use the blinker when traffic and road conditions permit. - - - - s - - - - Off - - - - Nudge - - - - Nudgeless - - - - - ConfirmationDialog - - Ok - موافق - - - Cancel - إلغاء - - - - DeclinePage - - You must accept the Terms and Conditions in order to use sunnypilot. - يجب عليك قبول الشروط والأحكام من أجل استخدام sunnypilot. - - - Back - السابق - - - Decline, uninstall %1 - رفض، إلغاء التثبيت %1 - - - - DeveloperPanel - - Joystick Debug Mode - وضع تصحيح أخطاء عصا التحكم - - - Longitudinal Maneuver Mode - وضع المناورة الطولية - - - Enable ADB - تمكين ADB - - - ADB (Android Debug Bridge) allows connecting to your device over USB or over the network. See https://docs.comma.ai/how-to/connect-to-comma for more info. - أداة ADB (Android Debug Bridge) تسمح بالاتصال بجهازك عبر USB أو عبر الشبكة. راجع هذا الرابط: https://docs.comma.ai/how-to/connect-to-comma لمزيد من المعلومات. - - - Enable GitHub runner service - - - - Enables or disables the github runner service. - - - - Error Log - - - - VIEW - عرض - - - View the error log for sunnypilot crashes. - - - - openpilot Longitudinal Control (Alpha) - - - - WARNING: openpilot longitudinal control is in alpha for this car and will disable Automatic Emergency Braking (AEB). - - - - On this car, sunnypilot defaults to the car's built-in ACC instead of openpilot's longitudinal control. Enable this to switch to openpilot longitudinal control. Enabling Experimental mode is recommended when enabling openpilot longitudinal control alpha. - - - - - DevicePanel - - Dongle ID - معرف دونجل - - - N/A - غير متاح - - - Serial - الرقم التسلسلي - - - Driver Camera - كاميرة السائق - - - PREVIEW - معاينة - - - Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off) - قم بمعاينة الكاميرا المواجهة للسائق للتأكد من أن نظام مراقبة السائق يتمتع برؤية جيدة. (يجب أن تكون السيارة متوقفة) - - - Reset Calibration - إعادة ضبط المعايرة - - - RESET - إعادة الضبط - - - Are you sure you want to reset calibration? - هل أنت متأكد أنك تريد إعادة ضبط المعايرة؟ - - - Review Training Guide - مراجعة دليل التدريب - - - REVIEW - مراجعة - - - Review the rules, features, and limitations of sunnypilot - مراجعة الأدوار والميزات والقيود في sunnypilot - - - Are you sure you want to review the training guide? - هل أنت متأكد أنك تريد مراجعة دليل التدريب؟ - - - Regulatory - التنظيمية - - - VIEW - عرض - - - Change Language - تغيير اللغة - - - CHANGE - تغيير - - - Select a language - اختر لغة - - - Reboot - إعادة التشغيل - - - Power Off - إيقاف التشغيل - - - sunnypilot requires the device to be mounted within 4° left or right and within 5° up or 9° down. sunnypilot is continuously calibrating, resetting is rarely required. - يحتاج sunnypilot أن يتم ضبط الجهاز ضمن حدود 4 درجات يميناً أو يساراً و5 درجات نحو الأعلى أو 9 نحو الأسفل. يقوم sunnypilot بالمعايرة باستمرار، ونادراً ما يحتاج إلى عملية إعادة الضبط. - - - Your device is pointed %1° %2 and %3° %4. - يشير جهازك إلى %1 درجة %2، و%3 درجة %4. - - - down - نحو الأسفل - - - up - نحو الأعلى - - - left - نحو اليسار - - - right - نحو اليمين - - - Are you sure you want to reboot? - هل أنت متأكد أنك تريد إعادة التشغيل؟ - - - Disengage to Reboot - فك الارتباط من أجل إعادة التشغيل - - - Are you sure you want to power off? - هل أنت متأكد أنك تريد إيقاف التشغيل؟ - - - Disengage to Power Off - فك الارتباط من أجل إيقاف التشغيل - - - Reset - إعادة الضبط - - - Review - مراجعة - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - اقرن جهازك بجهاز (connect.comma.ai) واحصل على عرضك من comma prime. - - - Pair Device - إقران الجهاز - - - PAIR - إقران - - - Disengage to Reset Calibration - - - - Resetting calibration will restart openpilot if the car is powered on. - - - - - DevicePanelSP - - Driver Camera Preview - - - - Training Guide - - - - Regulatory - التنظيمية - - - Language - - - - Are you sure you want to review the training guide? - هل أنت متأكد أنك تريد مراجعة دليل التدريب؟ - - - Review - مراجعة - - - Select a language - اختر لغة - - - Reboot - إعادة التشغيل - - - Power Off - إيقاف التشغيل - - - Offroad Mode - - - - Are you sure you want to exit Always Offroad mode? - - - - Confirm - تأكيد - - - Are you sure you want to enter Always Offroad mode? - - - - Disengage to Enter Always Offroad Mode - - - - Exit Always Offroad - - - - Always Offroad - - - - Quiet Mode - - - - Reset Settings - - - - Are you sure you want to reset all sunnypilot settings to default? Once the settings are reset, there is no going back. - - - - Reset - إعادة الضبط - - - The reset cannot be undone. You have been warned. - - - - - DriveStats - - Drives - - - - Hours - - - - ALL TIME - - - - PAST WEEK - - - - KM - - - - Miles - - - - - DriverViewWindow - - camera starting - بدء تشغيل الكاميرا - - - - ExperimentalModeButton - - EXPERIMENTAL MODE ON - تشغيل الوضع التجريبي - - - CHILL MODE ON - تشغيل وضع الراحة - - - - FirehosePanel - - 🔥 Firehose Mode 🔥 - 🔥 وضع خرطوم الحريق 🔥 - - - Firehose Mode: ACTIVE - وضع خرطوم الحريق: نشط - - - ACTIVE - نشط - - - For maximum effectiveness, bring your device inside and connect to a good USB-C adapter and Wi-Fi weekly.<br><br>Firehose Mode can also work while you're driving if connected to a hotspot or unlimited SIM card.<br><br><br><b>Frequently Asked Questions</b><br><br><i>Does it matter how or where I drive?</i> Nope, just drive as you normally would.<br><br><i>Do all of my segments get pulled in Firehose Mode?</i> No, we selectively pull a subset of your segments.<br><br><i>What's a good USB-C adapter?</i> Any fast phone or laptop charger should be fine.<br><br><i>Does it matter which software I run?</i> Yes, only upstream sunnypilot (and particular forks) are able to be used for training. - للحصول على أقصى فعالية، أحضر جهازك إلى الداخل واتصل بمحول USB-C جيد وشبكة Wi-Fi أسبوعياً.<br><br>يمكن أن يعمل وضع خرطوم الحريق أيضاً أثناء القيادة إذا كنت متصلاً بنقطة اتصال أو ببطاقة SIM غير محدودة.<br><br><br><b>الأسئلة المتكررة</b><br><br><i>هل يهم كيف أو أين أقود؟</i> لا، فقط قد كما تفعل عادة.<br><br><i>هل يتم سحب كل مقاطع رحلاتي في وضع خرطوم الحريق؟</i> لا، نقوم بسحب مجموعة مختارة من مقاطع رحلاتك.<br><br><i>ما هو محول USB-C الجيد؟</i> أي شاحن سريع للهاتف أو اللابتوب يجب أن يكون مناسباً.<br><br><i>هل يهم أي برنامج أستخدم؟</i> نعم، فقط النسخة الأصلية من sunnypilot (وأفرع معينة) يمكن استخدامها للتدريب. - - - <b>%n segment(s)</b> of your driving is in the training dataset so far. - - حتى الآن، يوجد </b>%n مقطع<b>%n من قيادتك في مجموعة بيانات التدريب. - حتى الآن، يوجد </b>%n مقطع<b>%n من قيادتك في مجموعة بيانات التدريب. - حتى الآن، يوجد </b>%n مقطع<b>%n من قيادتك في مجموعة بيانات التدريب. - حتى الآن، يوجد </b>%n مقطع<b>%n من قيادتك في مجموعة بيانات التدريب. - حتى الآن، يوجد </b>%n مقطع<b>%n من قيادتك في مجموعة بيانات التدريب. - حتى الآن، يوجد </b>%n مقطع<b>%n من قيادتك في مجموعة بيانات التدريب. - - - - sunnypilot learns to drive by watching humans, like you, drive. - -Firehose Mode allows you to maximize your training data uploads to improve openpilot's driving models. More data means bigger models, which means better Experimental Mode. - - - - <span stylesheet='font-size: 60px; font-weight: bold; color: #e74c3c;'>INACTIVE</span>: connect to an unmetered network - - - - - HudRenderer - - km/h - كم/س - - - mph - ميل/س - - - MAX - MAX - - - - HyundaiSettings - - Off - - - - Dynamic - - - - Predictive - - - - Custom Longitudinal Tuning - - - - This feature can only be used with openpilot longitudinal control enabled. - - - - Enable "Always Offroad" in Device panel, or turn vehicle off to select an option. - - - - Off: Uses default tuning - - - - Dynamic: Adjusts acceleration limits based on current speed - - - - Predictive: Uses future trajectory data to anticipate needed adjustments - - - - Fine-tune your driving experience by adjusting acceleration smoothness with openpilot longitudinal control. - - - - - InputDialog - - Cancel - إلغاء - - - Need at least %n character(s)! - - تحتاج إلى حرف %n على الأقل! - تحتاج إلى حرف %n على الأقل! - تحتاج إلى حرفين %n على الأقل! - تحتاج إلى %n أحرف على الأقل! - تحتاج إلى %n أحرف على الأقل! - تحتاج إلى %n حرف على الأقل! - - - - - LaneChangeSettings - - Back - السابق - - - Auto Lane Change: Delay with Blind Spot - - - - Toggle to enable a delay timer for seamless lane changes when blind spot monitoring (BSM) detects a obstructing vehicle, ensuring safe maneuvering. - - - - - LateralPanel - - Modular Assistive Driving System (MADS) - - - - Enable the beloved MADS feature. Disable toggle to revert back to stock sunnypilot engagement/disengagement. - - - - Customize MADS - - - - Customize Lane Change - - - - Enables independent engagements of Automatic Lane Centering (ALC) and Adaptive Cruise Control (ACC). - - - - Start the vehicle to check vehicle compatibility. - - - - This platform supports all MADS settings. - - - - This platform supports limited MADS settings. - - - - - MadsSettings - - Toggle with Main Cruise - - - - Note: For vehicles without LFA/LKAS button, disabling this will prevent lateral control engagement. - - - - Unified Engagement Mode (UEM) - - - - Engage lateral and longitudinal control with cruise control engagement. - - - - Note: Once lateral control is engaged via UEM, it will remain engaged until it is manually disabled via the MADS button or car shut off. - - - - Remain Active - - - - Disengage - - - - Steering Mode on Brake Pedal - - - - Start the vehicle to check vehicle compatibility. - - - - This feature defaults to OFF, and does not allow selection due to vehicle limitations. - - - - This feature defaults to ON, and does not allow selection due to vehicle limitations. - - - - This platform only supports Disengage mode due to vehicle limitations. - - - - Remain Active: ALC will remain active when the brake pedal is pressed. - - - - Pause - - - - Pause: ALC will pause when the brake pedal is pressed. - - - - Disengage: ALC will disengage when the brake pedal is pressed. - - - - Choose how Automatic Lane Centering (ALC) behaves after the brake pedal is manually pressed in sunnypilot. - - - - - MaxTimeOffroad - - Max Time Offroad - - - - Device will automatically shutdown after set time once the engine is turned off.<br/>(30h is the default) - - - - Always On - - - - h - - - - m - - - - (default) - - - - - ModelsPanel - - Current Model - - - - SELECT - اختيار - - - No custom model selected! - - - - Driving - - - - Navigation - - - - Vision - - - - Policy - - - - Downloading %1 model [%2]... (%3%) - - - - %1 model [%2] %3 - - - - downloaded - - - - ready - - - - from cache - - - - %1 model [%2] download failed - - - - %1 model [%2] pending... - - - - Fetching models... - - - - Use Default - - - - Select a Model - - - - Default - - - - Model download has started in the background. - - - - We STRONGLY suggest you to reset calibration. - - - - Would you like to do that now? - - - - Reset Calibration - إعادة ضبط المعايرة - - - Driving Model Selector - - - - Warning: You are on a metered connection! - - - - Continue - متابعة - - - on Metered - - - - Cancel - إلغاء - - - - MultiOptionDialog - - Select - اختيار - - - Cancel - إلغاء - - - - Networking - - Advanced - متقدم - - - Enter password - أدخل كلمة المرور - - - for "%1" - من أجل "%1" - - - Wrong password - كلمة مرور خاطئة - - - - NetworkingSP - - Scan - - - - Scanning... - - - - - NeuralNetworkLateralControl - - Neural Network Lateral Control (NNLC) - - - - NNLC is currently not available on this platform. - - - - Start the car to check car compatibility - - - - NNLC Not Loaded - - - - NNLC Loaded - - - - Match - - - - Exact - - - - Fuzzy - - - - Match: "Exact" is ideal, but "Fuzzy" is fine too. - - - - Formerly known as <b>"NNFF"</b>, this replaces the lateral <b>"torque"</b> controller, with one using a neural network trained on each car's (actually, each separate EPS firmware) driving data for increased controls accuracy. - - - - Reach out to the sunnypilot team in the following channel at the sunnypilot Discord server - - - - with feedback, or to provide log data for your car if your car is currently unsupported: - - - - if there are any issues: - - - - and donate logs to get NNLC loaded for your car: - - - - - OffroadAlert - - Device temperature too high. System cooling down before starting. Current internal component temperature: %1 - درجة حرارة الجهاز مرتفعة جداً. يقوم النظام بالتبريد قبل البدء. درجة الحرارة الحالية للمكونات الداخلية: %1 - - - Immediately connect to the internet to check for updates. If you do not connect to the internet, sunnypilot won't engage in %1 - اتصل فوراً بالإنترنت للتحقق من وجود تحديثات. إذا لم تكم متصلاً بالإنترنت فإن sunnypilot لن يساهم في %1 - - - Connect to internet to check for updates. sunnypilot won't automatically start until it connects to internet to check for updates. - اتصل بالإنترنت للتحقق من وجود تحديثات. لا يعمل sunnypilot تلقائياً إلا إذا اتصل بالإنترنت من أجل التحقق من التحديثات. - - - Unable to download updates -%1 - غير قادر على تحميل التحديثات -%1 - - - Taking camera snapshots. System won't start until finished. - التقاط لقطات كاميرا. لن يبدأ النظام حتى تنتهي هذه العملية. - - - An update to your device's operating system is downloading in the background. You will be prompted to update when it's ready to install. - يتم تنزيل تحديث لنظام تشغيل جهازك في الخلفية. سيطلَب منك التحديث عندما يصبح جاهزاً للتثبيت. - - - Device failed to register. It will not connect to or upload to comma.ai servers, and receives no support from comma.ai. If this is an official device, visit https://comma.ai/support. - فشل تسجيل الجهاز. لن يقوم بالاتصال أو تحميل خوادم comma.ai، ولا تلقي الدعم من comma.ai. إذا كان هذا الجهاز نظامياً فيرجى زيارة الموقع https://comma.ai/support. - - - NVMe drive not mounted. - محرك NVMe غير مثبَّت. - - - Unsupported NVMe drive detected. Device may draw significantly more power and overheat due to the unsupported NVMe. - تم اكتشاف محرك NVMe غير مدعوم. قد يستهلك الجهاز قدراً أكبر بكثير من الطاقة، وزيادة في ارتفاع درجة الحرارة بسبب وجود NVMe غير مدعوم. - - - sunnypilot was unable to identify your car. Your car is either unsupported or its ECUs are not recognized. Please submit a pull request to add the firmware versions to the proper vehicle. Need help? Join discord.comma.ai. - لم يكن sunnypilot قادراً على تحديد سيارتك. إما أن تكون سيارتك غير مدعومة أو أنه لم يتم التعرف على وحدة التحكم الإلكتروني (ECUs) فيها. يرجى تقديم طلب سحب من أجل إضافة نسخ برمجيات ثابتة إلى السيارة المناسبة. هل تحتاج إلى أي مساعدة؟ لا تتردد في التواصل مع doscord.comma.ai. - - - sunnypilot detected a change in the device's mounting position. Ensure the device is fully seated in the mount and the mount is firmly secured to the windshield. - لقد اكتشف sunnypilot تغييراً في موقع تركيب الجهاز. تأكد من تثبيت الجهاز بشكل كامل في موقعه وتثبيته بإحكام على الزجاج الأمامي. - - - sunnypilot is now in Always Offroad mode. sunnypilot won't start until Always Offroad mode is disabled. Go to "Settings" -> "Device" to exit Always Offroad mode. - - - - - OffroadHome - - UPDATE - تحديث - - - ALERTS - التنبهات - - - ALERT - تنبيه - - - - OnroadAlerts - - sunnypilot Unavailable - sunnypilot غير متوفر - - - TAKE CONTROL IMMEDIATELY - تحكم على الفور - - - Reboot Device - إعادة التشغيل - - - Waiting to start - في انتظار البدء - - - System Unresponsive - النظام لا يستجيب - - - - PairingPopup - - Pair your device to your comma account - اقرن جهازك مع حسابك على comma - - - Go to https://connect.comma.ai on your phone - انتقل إلى https://connect.comma.ai على جوالك - - - Click "add new device" and scan the QR code on the right - انقر "،إضافة جهاز جديد"، وامسح رمز الاستجابة السريعة (QR) على اليمين - - - Bookmark connect.comma.ai to your home screen to use it like an app - اجعل لـconnect.comma.ai إشارة مرجعية على شاشتك الرئيسية من أجل استخدامه مثل أي تطبيق - - - Please connect to Wi-Fi to complete initial pairing - يرجى الاتصال بشبكة الواي فاي لإكمال الاقتران الأولي - - - - ParamControl - - Enable - تمكين - - - Cancel - إلغاء - - - - ParamControlSP - - Enable - تمكين - - - Cancel - إلغاء - - - - PlatformSelector - - Vehicle - - - - SEARCH - - - - Search your vehicle - - - - Enter model year (e.g., 2021) and model name (Toyota Corolla): - - - - SEARCHING - - - - REMOVE - إزالة - - - This setting will take effect immediately. - - - - This setting will take effect once the device enters offroad state. - - - - Vehicle Selector - - - - Confirm - تأكيد - - - Cancel - إلغاء - - - No vehicles found for query: %1 - - - - Select a vehicle - - - - Unrecognized Vehicle - - - - Fingerprinted automatically - - - - Manually selected - - - - Not fingerprinted or manually selected - - - - Select vehicle to force fingerprint manually. - - - - Colors represent fingerprint status: - - - - - PrimeAdWidget - - Upgrade Now - الترقية الآن - - - Become a comma prime member at connect.comma.ai - كن عضوًا في comma prime على connect.comma.ai - - - PRIME FEATURES: - الميزات الأساسية: - - - Remote access - التحكم عن بعد - - - 24/7 LTE connectivity - اتصال LTE على مدار الساعة 24/7 - - - 1 year of drive storage - سنة واحدة من تخزين القرص - - - Remote snapshots - لقطات عن بُعد - - - - PrimeUserWidget - - ✓ SUBSCRIBED - ✓ مشترك - - - comma prime - comma prime - - - - QObject - - sunnypilot - sunnypilot - - - %n minute(s) ago - - منذ %n دقيقة - منذ %n دقيقة - منذ دقيقتين %n - منذ %n دقائق - منذ %n دقائق - منذ %n دقيقة - - - - %n hour(s) ago - - منذ %n ساعة - منذ %n ساعة - منذ ساعتين %n - منذ %n ساعات - منذ %n ساعات - منذ %n ساعة - - - - %n day(s) ago - - منذ %n يوم - منذ %n يوم - منذ يومين %n - منذ %n أيام - منذ %n أيام - منذ %n يوم - - - - now - الآن - - - - Reset - - Reset failed. Reboot to try again. - فشل إعاة الضبط. أعد التشغيل للمحاولة من جديد. - - - Are you sure you want to reset your device? - هل أنت متأكد أنك تريد إعادة ضبط جهازك؟ - - - System Reset - إعادة ضبط النظام - - - Cancel - إلغاء - - - Reboot - إعادة التشغيل - - - Confirm - تأكيد - - - Resetting device... -This may take up to a minute. - يتم إعادة ضبط الجهاز... -قد يستغرق الأمر حوالي الدقيقة. - - - Unable to mount data partition. Partition may be corrupted. Press confirm to erase and reset your device. - غير قادر على تحميل جزء البيانات. قد يكون الجزء تالفاً. اضغط على تأكيد لمسح جهازك وإعادة ضبطه. - - - System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot. - تم تفعيل إعادة ضبط النظام. اضغط على تأكيد لمسح جميع المحتويات والإعدادات. اضغط على إلغاء لاستئناف التمهيد. - - - - SettingsWindow - - × - × - - - Device - الجهاز - - - Network - الشبكة - - - Toggles - المثبتتات - - - Software - البرنامج - - - Developer - المطور - - - Firehose - خرطوم الحريق - - - - SettingsWindowSP - - × - × - - - Device - الجهاز - - - Network - الشبكة - - - sunnylink - - - - Toggles - المثبتتات - - - Software - البرنامج - - - Trips - - - - Vehicle - - - - Developer - المطور - - - Firehose - خرطوم الحريق - - - Steering - - - - Models - - - - Cruise - - - - Visuals - - - - - Setup - - WARNING: Low Voltage - تحذير: الجهد منخفض - - - Power your device in a car with a harness or proceed at your own risk. - شغل جهازك في السيارة عن طريق شرطان التوصيل، أو تابع على مسؤوليتك. - - - Power off - إيقاف التشغيل - - - Continue - متابعة - - - Getting Started - البدء - - - Before we get on the road, let’s finish installation and cover some details. - قبل أن ننطلق في الطريق، دعنا ننتهي من التثبيت ونغطي بعض التفاصيل. - - - Connect to Wi-Fi - الاتصال بشبكة الواي فاي - - - Back - السابق - - - Continue without Wi-Fi - المتابعة بدون شبكة الواي فاي - - - Waiting for internet - بانتظار الاتصال بالإنترنت - - - Enter URL - أدخل رابط URL - - - for Custom Software - للبرامج المخصصة - - - Downloading... - يتم الآن التنزيل... - - - Download Failed - فشل التنزيل - - - Ensure the entered URL is valid, and the device’s internet connection is good. - تأكد من أن رابط URL الذي أدخلته صالح، وأن اتصال الجهاز بالإنترنت جيد. - - - Reboot device - إعادة التشغيل - - - Start over - البدء من جديد - - - Something went wrong. Reboot the device. - حدث خطأ ما. أعد التشغيل الجهاز. - - - No custom software found at this URL. - لم يتم العثور على برنامج خاص لعنوان URL ها. - - - Select a language - اختر لغة - - - Choose Software to Install - اختر البرنامج للتثبيت - - - sunnypilot - sunnypilot - - - Custom Software - البرمجيات المخصصة - - - - SetupWidget - - Finish Setup - إنهاء الإعداد - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - اقرن جهازك بجهاز (connect.comma.ai) واحصل على عرضك من comma prime. - - - Pair device - اقتران الجهاز - - - - Sidebar - - CONNECT - الاتصال - - - OFFLINE - غير متصل - - - ONLINE - متصل - - - ERROR - خطأ - - - TEMP - درجة الحرارة - - - HIGH - مرتفع - - - GOOD - جيد - - - OK - موافق - - - VEHICLE - المركبة - - - NO - لا - - - PANDA - PANDA - - - -- - -- - - - Wi-Fi - Wi-Fi - - - ETH - ETH - - - 2G - 2G - - - 3G - 3G - - - LTE - LTE - - - 5G - 5G - - - - SidebarSP - - DISABLED - - - - OFFLINE - غير متصل - - - REGIST... - - - - ONLINE - متصل - - - ERROR - خطأ - - - SUNNYLINK - - - - - SoftwarePanel - - UNINSTALL - إلغاء التثبيت - - - Uninstall %1 - إلغاء التثبيت %1 - - - Are you sure you want to uninstall? - هل أنت متأكد أنك تريد إلغاء التثبيت؟ - - - CHECK - التحقق - - - Updates are only downloaded while the car is off. - يتم تحميل التحديثات فقط عندما تكون السيارة متوقفة. - - - Current Version - النسخة الحالية - - - Download - تنزيل - - - Install Update - تثبيت التحديث - - - INSTALL - تثبيت - - - Target Branch - فرع الهدف - - - SELECT - اختيار - - - Select a branch - اختر فرعاً - - - Uninstall - إلغاء التثبيت - - - failed to check for update - فشل التحقق من التحديث - - - DOWNLOAD - تنزيل - - - update available - يتوفر تحديث - - - never - إطلاقاً - - - up to date, last checked %1 - أحدث نسخة، آخر تحقق %1 - - - - SoftwarePanelSP - - Search Branch - - - - Enter search keywords, or leave blank to list all branches. - - - - No branches found for keywords: %1 - - - - Select a branch - اختر فرعاً - - - - SshControl - - SSH Keys - مفاتيح SSH - - - Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username other than your own. A comma employee will NEVER ask you to add their GitHub username. - تنبيه: هذا يمنح SSH إمكانية الوصول إلى جميع المفاتيح العامة في إعدادات GitHub. لا تقم بإدخال اسم مستخدم GitHub بدلاً من اسمك. لن تطلب منك comma employee إطلاقاً أن تضيف اسم مستخدم GitHub الخاص بهم. - - - ADD - إضافة - - - Enter your GitHub username - ادخل اسم المستخدم GitHub الخاص بك - - - LOADING - يتم التحميل - - - REMOVE - إزالة - - - Username '%1' has no keys on GitHub - لا يحتوي اسم المستخدم '%1' أي مفاتيح على GitHub - - - Request timed out - انتهى وقت الطلب - - - Username '%1' doesn't exist on GitHub - اسم المستخدم '%1' غير موجود على GitHub - - - - SshToggle - - Enable SSH - تمكين SSH - - - - SunnylinkPanel - - This is the master switch, it will allow you to cutoff any sunnylink requests should you want to do that. - - - - Enable sunnylink - - - - 🎉Welcome back! We're excited to see you've enabled sunnylink again! 🚀 - - - - 👋Not going to lie, it's sad to see you disabled sunnylink 😢, but we'll be here when you're ready to come back 🎉. - - - - Device ID - - - - N/A - غير متاح - - - Sponsor Status - - - - SPONSOR - - - - Become a sponsor of sunnypilot to get early access to sunnylink features when they become available. - - - - Pair GitHub Account - - - - PAIR - إقران - - - Pair your GitHub account to grant your device sponsor benefits, including API access on sunnylink. - - - - sunnylink Dongle ID not found. This may be due to weak internet connection or sunnylink registration issue. Please reboot and try again. - - - - Not Sponsor - - - - Paired - - - - Not Paired - - - - THANKS ♥ - - - - Backup Settings - - - - Are you sure you want to backup sunnypilot settings? - - - - Back Up - - - - Restore Settings - - - - Are you sure you want to restore the last backed up sunnypilot settings? - - - - Restore - - - - Backup in progress %1% - - - - Backup Failed - - - - Settings backup completed. - - - - Restore in progress %1% - - - - Restore Failed - - - - Unable to restore the settings, try again later. - - - - Settings restored. Confirm to restart the interface. - - - - - SunnylinkSponsorPopup - - Scan the QR code to login to your GitHub account - - - - Follow the prompts to complete the pairing process - - - - Re-enter the "sunnylink" panel to verify sponsorship status - - - - If sponsorship status was not updated, please contact a moderator on Discord at https://discord.gg/sunnypilot - - - - Scan the QR code to visit sunnyhaibin's GitHub Sponsors page - - - - Choose your sponsorship tier and confirm your support - - - - Join our community on Discord at https://discord.gg/sunnypilot and reach out to a moderator to confirm your sponsor status - - - - Pair your GitHub account - - - - Early Access: Become a sunnypilot Sponsor - - - - - TermsPage - - Decline - رفض - - - Agree - أوافق - - - Welcome to sunnypilot - مرحباً بكم في sunnypilot - - - You must accept the Terms and Conditions to use sunnypilot. Read the latest terms at <span style='color: #465BEA;'>https://comma.ai/terms</span> before continuing. - يجب عليك قبول الشروط والأحكام لاستخدام sunnypilot. اقرأ أحدث الشروط على <span style='color: #465BEA;'>https://comma.ai/terms</span> قبل الاستمرار. - - - - TogglesPanel - - Enable Lane Departure Warnings - قم بتمكين تحذيرات مغادرة المسار - - - Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h). - تلقي التنبيهات من أجل الالتفاف للعودة إلى المسار عندما تنحرف سيارتك فوق الخط المحدد للمسار دون تشغيل إشارة الانعطاف عند القيادة لمسافة تزيد عن 31 ميل/سا (50 كم/سا). - - - Use Metric System - استخدام النظام المتري - - - Display speed in km/h instead of mph. - عرض السرعة بواحدات كم/سا بدلاً من ميل/سا. - - - Record and Upload Driver Camera - تسجيل وتحميل كاميرا السائق - - - Upload data from the driver facing camera and help improve the driver monitoring algorithm. - تحميل البيانات من الكاميرا المواجهة للسائق، والمساعدة في تحسين خوارزمية مراقبة السائق. - - - Disengage on Accelerator Pedal - فك الارتباط عن دواسة الوقود - - - When enabled, pressing the accelerator pedal will disengage sunnypilot. - عند تمكين هذه الميزة، فإن الضغط على دواسة الوقود سيؤدي إلى فك ارتباط sunnypilot. - - - Experimental Mode - الوضع التجريبي - - - Aggressive - الهجومي - - - Standard - القياسي - - - Relaxed - الراحة - - - Driving Personality - شخصية القيادة - - - sunnypilot defaults to driving in <b>chill mode</b>. Experimental mode enables <b>alpha-level features</b> that aren't ready for chill mode. Experimental features are listed below: - يتم وضع sunnypilot بشكل قياسي في <b>وضعية الراحة</b>. يمكن الوضع التجريبي <b>ميزات المستوى ألفا</b> التي لا تكون جاهزة في وضع الراحة: - - - End-to-End Longitudinal Control - التحكم الطولي من طرف إلى طرف - - - Let the driving model control the gas and brakes. sunnypilot will drive as it thinks a human would, including stopping for red lights and stop signs. Since the driving model decides the speed to drive, the set speed will only act as an upper bound. This is an alpha quality feature; mistakes should be expected. - دع نظام القيادة يتحكم بالوقود والمكابح. سيقوم sunnypilot بالقيادة كما لو أنه كائن بشري، بما في ذلك التوقف عند الإشارة الحمراء، وإشارات التوقف. وبما أن نمط القيادة يحدد سرعة القيادة، فإن السرعة المضبوطة تشكل الحد الأقصى فقط. هذه خاصية الجودة ألفا، فيجب توقع حدوث الأخطاء. - - - New Driving Visualization - تصور القيادة الديد - - - Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control. - الوضع التجريبي غير متوفر حالياً في هذه السيارة نظراً لاستخدام رصيد التحكم التكيفي بالسرعة من أجل التحكم الطولي. - - - An alpha version of sunnypilot longitudinal control can be tested, along with Experimental mode, on non-release branches. - يمكن اختبار نسخة ألفا من التحكم الطولي من sunnypilot، مع الوضع التجريبي، لكن على الفروع غير المطلقة. - - - Enable the sunnypilot longitudinal control (alpha) toggle to allow Experimental mode. - تمكين التحكم الطولي من sunnypilot (ألفا) للسماح بالوضع التجريبي. - - - Standard is recommended. In aggressive mode, sunnypilot will follow lead cars closer and be more aggressive with the gas and brake. In relaxed mode sunnypilot will stay further away from lead cars. On supported cars, you can cycle through these personalities with your steering wheel distance button. - يوصى بالمعيار. في الوضع العدواني، سيتبع الطيار المفتوح السيارات الرائدة بشكل أقرب ويكون أكثر عدوانية مع البنزين والفرامل. في الوضع المريح، سيبقى sunnypilot بعيدًا عن السيارات الرائدة. في السيارات المدعومة، يمكنك التنقل بين هذه الشخصيات باستخدام زر مسافة عجلة القيادة. - - - The driving visualization will transition to the road-facing wide-angle camera at low speeds to better show some turns. The Experimental mode logo will also be shown in the top right corner. - ستتحول واجهة القيادة إلى الكاميرا الواسعة المواجهة للطريق عند السرعات المنخفضة لعرض بعض المنعطفات بشكل أفضل. كما سيتم عرض شعار وضع التجريبي في الزاوية العلوية اليمنى. - - - Always-On Driver Monitoring - مراقبة السائق المستمرة - - - Enable driver monitoring even when sunnypilot is not engaged. - تمكين مراقبة السائق حتى عندما لا يكون نظام OpenPilot مُفعّلاً. - - - Enable Dynamic Experimental Control - - - - Enable toggle to allow the model to determine when to use sunnypilot ACC or sunnypilot End to End Longitudinal. - - - - Enable sunnypilot - تمكين sunnypilot - - - Use the sunnypilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature. - - - - Changing this setting will restart openpilot if the car is powered on. - - - - openpilot longitudinal control may come in a future update. - - - - - Updater - - Update Required - التحديث مطلوب - - - An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. The download size is approximately 1GB. - تحديث نظام التشغيل مطلوب. قم بوصل جهازك بشبكة واي فاي من أجل تحديث أسرع. حجم التحميل حوالي 1 غيغا بايت تقريباً. - - - Connect to Wi-Fi - الاتصال بشبكة الواي فاي - - - Install - تثبيت - - - Back - السابق - - - Loading... - يتم التحميل... - - - Reboot - إعادة التشغيل - - - Update failed - فشل التحديث - - - - WiFiPromptWidget - - Open - انفتح - - - <span style='font-family: "Noto Color Emoji";'>🔥</span> Firehose Mode <span style='font-family: Noto Color Emoji;'>🔥</span> - <span style='font-family: "Noto Color Emoji";'>🔥</span> وضع خرطوم الحريق <span style='font-family: Noto Color Emoji;'>🔥</span> - - - Maximize your training data uploads to improve openpilot's driving models. - - - - - WifiUI - - Scanning for networks... - يتم البحث عن شبكات... - - - CONNECTING... - يتم الاتصال... - - - FORGET - نسيان هذه الشبكة - - - Forget Wi-Fi Network "%1"? - هل تريد نسيان شبكة الواي فاي "%1"؟ - - - Forget - نسيان - - - diff --git a/selfdrive/ui/translations/main_de.ts b/selfdrive/ui/translations/main_de.ts deleted file mode 100644 index 6229920121..0000000000 --- a/selfdrive/ui/translations/main_de.ts +++ /dev/null @@ -1,2116 +0,0 @@ - - - - - AbstractAlert - - Close - Schließen - - - Snooze Update - Update pausieren - - - Reboot and Update - Aktualisieren und neu starten - - - - AdvancedNetworking - - Back - Zurück - - - Enable Tethering - Tethering aktivieren - - - Tethering Password - Tethering Passwort - - - EDIT - ÄNDERN - - - Enter new tethering password - Neues tethering Passwort eingeben - - - IP Address - IP Adresse - - - Enable Roaming - Roaming aktivieren - - - APN Setting - APN Einstellungen - - - Enter APN - APN eingeben - - - leave blank for automatic configuration - für automatische Konfiguration leer lassen - - - Cellular Metered - Getaktete Verbindung - - - Hidden Network - Verborgenes Netzwerk - - - CONNECT - VERBINDEN - - - Enter SSID - SSID eingeben - - - Enter password - Passwort eingeben - - - for "%1" - für "%1" - - - Prevent large data uploads when on a metered cellular connection - - - - default - - - - metered - - - - unmetered - - - - Wi-Fi Network Metered - - - - Prevent large data uploads when on a metered Wi-Fi connection - - - - - AutoLaneChangeTimer - - Auto Lane Change by Blinker - - - - Set a timer to delay the auto lane change operation when the blinker is used. No nudge on the steering wheel is required to auto lane change if a timer is set. Default is Nudge. -Please use caution when using this feature. Only use the blinker when traffic and road conditions permit. - - - - s - - - - Off - - - - Nudge - - - - Nudgeless - - - - - ConfirmationDialog - - Ok - Ok - - - Cancel - Abbrechen - - - - DeclinePage - - Back - Zurück - - - Decline, uninstall %1 - Ablehnen, deinstallieren %1 - - - You must accept the Terms and Conditions in order to use sunnypilot. - - - - - DeveloperPanel - - Joystick Debug Mode - Joystick Debug-Modus - - - Longitudinal Maneuver Mode - Längsmanöver-Modus - - - openpilot Longitudinal Control (Alpha) - openpilot Längsregelung (Alpha) - - - WARNING: openpilot longitudinal control is in alpha for this car and will disable Automatic Emergency Braking (AEB). - WARNUNG: Die openpilot Längsregelung befindet sich für dieses Fahrzeug im Alpha-Stadium und deaktiviert das automatische Notbremsen (AEB). - - - Enable ADB - ADB aktivieren - - - ADB (Android Debug Bridge) allows connecting to your device over USB or over the network. See https://docs.comma.ai/how-to/connect-to-comma for more info. - ADB (Android Debug Bridge) ermöglicht die Verbindung zu deinem Gerät über USB oder Netzwerk. Siehe https://docs.comma.ai/how-to/connect-to-comma für weitere Informationen. - - - On this car, sunnypilot defaults to the car's built-in ACC instead of openpilot's longitudinal control. Enable this to switch to openpilot longitudinal control. Enabling Experimental mode is recommended when enabling openpilot longitudinal control alpha. - - - - Enable GitHub runner service - - - - Enables or disables the github runner service. - - - - Error Log - - - - VIEW - ANSEHEN - - - View the error log for sunnypilot crashes. - - - - - DevicePanel - - Dongle ID - Dongle ID - - - N/A - Nicht verfügbar - - - Serial - Seriennummer - - - Driver Camera - Fahrerkamera - - - PREVIEW - VORSCHAU - - - Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off) - Vorschau der auf den Fahrer gerichteten Kamera, um sicherzustellen, dass die Fahrerüberwachung eine gute Sicht hat. (Fahrzeug muss aus sein) - - - Reset Calibration - Neu kalibrieren - - - RESET - RESET - - - Are you sure you want to reset calibration? - Bist du sicher, dass du die Kalibrierung zurücksetzen möchtest? - - - Review Training Guide - Trainingsanleitung wiederholen - - - REVIEW - TRAINING - - - Are you sure you want to review the training guide? - Bist du sicher, dass du die Trainingsanleitung wiederholen möchtest? - - - Regulatory - Rechtliche Hinweise - - - VIEW - ANSEHEN - - - Change Language - Sprache ändern - - - CHANGE - ÄNDERN - - - Select a language - Sprache wählen - - - Reboot - Neustart - - - Power Off - Ausschalten - - - Your device is pointed %1° %2 and %3° %4. - Deine Geräteausrichtung ist %1° %2 und %3° %4. - - - down - unten - - - up - oben - - - left - links - - - right - rechts - - - Are you sure you want to reboot? - Bist du sicher, dass du das Gerät neu starten möchtest? - - - Disengage to Reboot - Für Neustart deaktivieren - - - Are you sure you want to power off? - Bist du sicher, dass du das Gerät ausschalten möchtest? - - - Disengage to Power Off - Zum Ausschalten deaktivieren - - - Reset - Zurücksetzen - - - Review - Überprüfen - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - Koppele dein Gerät mit Comma Connect (connect.comma.ai) und sichere dir dein Comma Prime Angebot. - - - Pair Device - Gerät koppeln - - - PAIR - KOPPELN - - - Disengage to Reset Calibration - - - - Review the rules, features, and limitations of sunnypilot - - - - sunnypilot requires the device to be mounted within 4° left or right and within 5° up or 9° down. sunnypilot is continuously calibrating, resetting is rarely required. - - - - Resetting calibration will restart openpilot if the car is powered on. - - - - - DevicePanelSP - - Quiet Mode - - - - Driver Camera Preview - - - - Training Guide - - - - Regulatory - Rechtliche Hinweise - - - Language - - - - Reset Settings - - - - Are you sure you want to review the training guide? - Bist du sicher, dass du die Trainingsanleitung wiederholen möchtest? - - - Review - Überprüfen - - - Select a language - Sprache wählen - - - Reboot - Neustart - - - Power Off - Ausschalten - - - Offroad Mode - - - - Are you sure you want to exit Always Offroad mode? - - - - Confirm - Bestätigen - - - Are you sure you want to enter Always Offroad mode? - - - - Disengage to Enter Always Offroad Mode - - - - Are you sure you want to reset all sunnypilot settings to default? Once the settings are reset, there is no going back. - - - - Reset - Zurücksetzen - - - The reset cannot be undone. You have been warned. - - - - Exit Always Offroad - - - - Always Offroad - - - - - DriveStats - - Drives - - - - Hours - - - - ALL TIME - - - - PAST WEEK - - - - KM - - - - Miles - - - - - DriverViewWindow - - camera starting - Kamera startet - - - - ExperimentalModeButton - - EXPERIMENTAL MODE ON - EXPERIMENTELLER MODUS AN - - - CHILL MODE ON - ENTSPANNTER MODUS AN - - - - FirehosePanel - - 🔥 Firehose Mode 🔥 - 🔥 Firehose-Modus 🔥 - - - Firehose Mode: ACTIVE - Firehose-Modus: AKTIV - - - ACTIVE - AKTIV - - - <b>%n segment(s)</b> of your driving is in the training dataset so far. - - <b>%n Segment</b> deiner Fahrten ist bisher im Trainingsdatensatz. - <b>%n Segmente</b> deiner Fahrten sind bisher im Trainingsdatensatz. - - - - <span stylesheet='font-size: 60px; font-weight: bold; color: #e74c3c;'>INACTIVE</span>: connect to an unmetered network - <span stylesheet='font-size: 60px; font-weight: bold; color: #e74c3c;'>INAKTIV</span>: Verbinde dich mit einem ungedrosselten Netzwerk - - - sunnypilot learns to drive by watching humans, like you, drive. - -Firehose Mode allows you to maximize your training data uploads to improve openpilot's driving models. More data means bigger models, which means better Experimental Mode. - - - - For maximum effectiveness, bring your device inside and connect to a good USB-C adapter and Wi-Fi weekly.<br><br>Firehose Mode can also work while you're driving if connected to a hotspot or unlimited SIM card.<br><br><br><b>Frequently Asked Questions</b><br><br><i>Does it matter how or where I drive?</i> Nope, just drive as you normally would.<br><br><i>Do all of my segments get pulled in Firehose Mode?</i> No, we selectively pull a subset of your segments.<br><br><i>What's a good USB-C adapter?</i> Any fast phone or laptop charger should be fine.<br><br><i>Does it matter which software I run?</i> Yes, only upstream sunnypilot (and particular forks) are able to be used for training. - - - - - HudRenderer - - km/h - km/h - - - mph - mph - - - MAX - MAX - - - - HyundaiSettings - - Off - - - - Dynamic - - - - Predictive - - - - Custom Longitudinal Tuning - - - - This feature can only be used with openpilot longitudinal control enabled. - - - - Enable "Always Offroad" in Device panel, or turn vehicle off to select an option. - - - - Off: Uses default tuning - - - - Dynamic: Adjusts acceleration limits based on current speed - - - - Predictive: Uses future trajectory data to anticipate needed adjustments - - - - Fine-tune your driving experience by adjusting acceleration smoothness with openpilot longitudinal control. - - - - - InputDialog - - Cancel - Abbrechen - - - Need at least %n character(s)! - - Mindestens %n Buchstabe benötigt! - Mindestens %n Buchstaben benötigt! - - - - - LaneChangeSettings - - Back - Zurück - - - Auto Lane Change: Delay with Blind Spot - - - - Toggle to enable a delay timer for seamless lane changes when blind spot monitoring (BSM) detects a obstructing vehicle, ensuring safe maneuvering. - - - - - LateralPanel - - Modular Assistive Driving System (MADS) - - - - Enable the beloved MADS feature. Disable toggle to revert back to stock sunnypilot engagement/disengagement. - - - - Customize MADS - - - - Customize Lane Change - - - - Enables independent engagements of Automatic Lane Centering (ALC) and Adaptive Cruise Control (ACC). - - - - Start the vehicle to check vehicle compatibility. - - - - This platform supports all MADS settings. - - - - This platform supports limited MADS settings. - - - - - MadsSettings - - Toggle with Main Cruise - - - - Unified Engagement Mode (UEM) - - - - Steering Mode on Brake Pedal - - - - Note: For vehicles without LFA/LKAS button, disabling this will prevent lateral control engagement. - - - - Engage lateral and longitudinal control with cruise control engagement. - - - - Note: Once lateral control is engaged via UEM, it will remain engaged until it is manually disabled via the MADS button or car shut off. - - - - Start the vehicle to check vehicle compatibility. - - - - This feature defaults to OFF, and does not allow selection due to vehicle limitations. - - - - This feature defaults to ON, and does not allow selection due to vehicle limitations. - - - - This platform only supports Disengage mode due to vehicle limitations. - - - - Remain Active - - - - Remain Active: ALC will remain active when the brake pedal is pressed. - - - - Pause - - - - Pause: ALC will pause when the brake pedal is pressed. - - - - Disengage - - - - Disengage: ALC will disengage when the brake pedal is pressed. - - - - Choose how Automatic Lane Centering (ALC) behaves after the brake pedal is manually pressed in sunnypilot. - - - - - MaxTimeOffroad - - Max Time Offroad - - - - Device will automatically shutdown after set time once the engine is turned off.<br/>(30h is the default) - - - - Always On - - - - h - - - - m - - - - (default) - - - - - ModelsPanel - - Current Model - - - - SELECT - AUSWÄHLEN - - - No custom model selected! - - - - Driving - - - - Navigation - - - - Vision - - - - Policy - - - - Downloading %1 model [%2]... (%3%) - - - - %1 model [%2] %3 - - - - downloaded - - - - ready - - - - from cache - - - - %1 model [%2] download failed - - - - %1 model [%2] pending... - - - - Fetching models... - - - - Use Default - - - - Select a Model - - - - Default - - - - Model download has started in the background. - - - - We STRONGLY suggest you to reset calibration. - - - - Would you like to do that now? - - - - Reset Calibration - Neu kalibrieren - - - Driving Model Selector - - - - Warning: You are on a metered connection! - - - - Continue - Fortsetzen - - - on Metered - - - - Cancel - Abbrechen - - - - MultiOptionDialog - - Select - Auswählen - - - Cancel - Abbrechen - - - - Networking - - Advanced - Erweitert - - - Enter password - Passwort eingeben - - - for "%1" - für "%1" - - - Wrong password - Falsches Passwort - - - - NetworkingSP - - Scan - - - - Scanning... - - - - - NeuralNetworkLateralControl - - Neural Network Lateral Control (NNLC) - - - - NNLC is currently not available on this platform. - - - - Start the car to check car compatibility - - - - NNLC Not Loaded - - - - NNLC Loaded - - - - Match - - - - Exact - - - - Fuzzy - - - - Match: "Exact" is ideal, but "Fuzzy" is fine too. - - - - Formerly known as <b>"NNFF"</b>, this replaces the lateral <b>"torque"</b> controller, with one using a neural network trained on each car's (actually, each separate EPS firmware) driving data for increased controls accuracy. - - - - Reach out to the sunnypilot team in the following channel at the sunnypilot Discord server - - - - with feedback, or to provide log data for your car if your car is currently unsupported: - - - - if there are any issues: - - - - and donate logs to get NNLC loaded for your car: - - - - - OffroadAlert - - Unable to download updates -%1 - Updates konnten nicht heruntergeladen werden -%1 - - - Taking camera snapshots. System won't start until finished. - Kamera-Snapshots werden aufgenommen. Das System startet erst, wenn dies abgeschlossen ist. - - - An update to your device's operating system is downloading in the background. You will be prompted to update when it's ready to install. - Ein Update für das Betriebssystem deines Geräts wird im Hintergrund heruntergeladen. Du wirst aufgefordert, das Update zu installieren, sobald es bereit ist. - - - Device failed to register. It will not connect to or upload to comma.ai servers, and receives no support from comma.ai. If this is an official device, visit https://comma.ai/support. - Gerät konnte nicht registriert werden. Es wird keine Verbindung zu den comma.ai-Servern herstellen oder Daten hochladen und erhält keinen Support von comma.ai. Wenn dies ein offizielles Gerät ist, besuche https://comma.ai/support. - - - NVMe drive not mounted. - NVMe-Laufwerk nicht gemounted. - - - Unsupported NVMe drive detected. Device may draw significantly more power and overheat due to the unsupported NVMe. - Nicht unterstütztes NVMe-Laufwerk erkannt. Das Gerät kann dadurch deutlich mehr Strom verbrauchen und überhitzen. - - - Device temperature too high. System cooling down before starting. Current internal component temperature: %1 - Gerätetemperatur zu hoch. Das System kühlt ab, bevor es startet. Aktuelle interne Komponententemperatur: %1 - - - Immediately connect to the internet to check for updates. If you do not connect to the internet, sunnypilot won't engage in %1 - - - - Connect to internet to check for updates. sunnypilot won't automatically start until it connects to internet to check for updates. - - - - sunnypilot was unable to identify your car. Your car is either unsupported or its ECUs are not recognized. Please submit a pull request to add the firmware versions to the proper vehicle. Need help? Join discord.comma.ai. - - - - sunnypilot detected a change in the device's mounting position. Ensure the device is fully seated in the mount and the mount is firmly secured to the windshield. - - - - sunnypilot is now in Always Offroad mode. sunnypilot won't start until Always Offroad mode is disabled. Go to "Settings" -> "Device" to exit Always Offroad mode. - - - - - OffroadHome - - UPDATE - Aktualisieren - - - ALERTS - HINWEISE - - - ALERT - HINWEIS - - - - OnroadAlerts - - TAKE CONTROL IMMEDIATELY - ÜBERNIMM SOFORT DIE KONTROLLE - - - Reboot Device - Gerät neu starten - - - Waiting to start - Warten auf Start - - - System Unresponsive - System reagiert nicht - - - sunnypilot Unavailable - - - - - PairingPopup - - Pair your device to your comma account - Verbinde dein Gerät mit deinem comma Konto - - - Go to https://connect.comma.ai on your phone - Gehe zu https://connect.comma.ai auf deinem Handy - - - Click "add new device" and scan the QR code on the right - Klicke auf "neues Gerät hinzufügen" und scanne den QR code rechts - - - Bookmark connect.comma.ai to your home screen to use it like an app - Füge connect.comma.ai als Lesezeichen auf deinem Homescreen hinzu um es wie eine App zu verwenden - - - Please connect to Wi-Fi to complete initial pairing - Bitte verbinde dich mit WLAN, um die Koppelung abzuschließen. - - - - ParamControl - - Cancel - Abbrechen - - - Enable - Aktivieren - - - - ParamControlSP - - Enable - Aktivieren - - - Cancel - Abbrechen - - - - PlatformSelector - - Vehicle - - - - SEARCH - - - - Search your vehicle - - - - Enter model year (e.g., 2021) and model name (Toyota Corolla): - - - - SEARCHING - - - - REMOVE - LÖSCHEN - - - This setting will take effect immediately. - - - - This setting will take effect once the device enters offroad state. - - - - Vehicle Selector - - - - Confirm - Bestätigen - - - Cancel - Abbrechen - - - No vehicles found for query: %1 - - - - Select a vehicle - - - - Unrecognized Vehicle - - - - Fingerprinted automatically - - - - Manually selected - - - - Not fingerprinted or manually selected - - - - Select vehicle to force fingerprint manually. - - - - Colors represent fingerprint status: - - - - - PrimeAdWidget - - Upgrade Now - Jetzt abonieren - - - Become a comma prime member at connect.comma.ai - Werde Comma Prime Mitglied auf connect.comma.ai - - - PRIME FEATURES: - PRIME FUNKTIONEN: - - - Remote access - Fernzugriff - - - 24/7 LTE connectivity - 24/7 LTE-Verbindung - - - 1 year of drive storage - Fahrdaten-Speicherung für 1 Jahr - - - Remote snapshots - Remote-Snapshots - - - - PrimeUserWidget - - ✓ SUBSCRIBED - ✓ ABBONIERT - - - comma prime - comma prime - - - - QObject - - %n minute(s) ago - - vor %n Minute - vor %n Minuten - - - - %n hour(s) ago - - vor %n Stunde - vor %n Stunden - - - - %n day(s) ago - - vor %n Tag - vor %n Tagen - - - - now - jetzt - - - sunnypilot - - - - - Reset - - Reset failed. Reboot to try again. - Zurücksetzen fehlgeschlagen. Starte das Gerät neu und versuche es wieder. - - - Are you sure you want to reset your device? - Bist du sicher, dass du das Gerät auf Werkseinstellungen zurücksetzen möchtest? - - - System Reset - System auf Werkseinstellungen zurücksetzen - - - Cancel - Abbrechen - - - Reboot - Neustart - - - Confirm - Bestätigen - - - Unable to mount data partition. Partition may be corrupted. Press confirm to erase and reset your device. - Datenpartition konnte nicht gemounted werden. Die Partition ist möglicherweise beschädigt. Drücke Bestätigen, um das Gerät zu löschen und zurückzusetzen. - - - Resetting device... -This may take up to a minute. - Gerät wird zurückgesetzt... -Dies kann bis zu einer Minute dauern. - - - System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot. - System-Reset ausgelöst. Drücke Bestätigen, um alle Inhalte und Einstellungen zu löschen. Drücke Abbrechen, um den Startvorgang fortzusetzen. - - - - SettingsWindow - - × - x - - - Device - Gerät - - - Network - Netzwerk - - - Toggles - Schalter - - - Software - Software - - - Developer - Entwickler - - - Firehose - Firehose - - - - SettingsWindowSP - - × - x - - - Device - Gerät - - - Network - Netzwerk - - - sunnylink - - - - Toggles - Schalter - - - Software - Software - - - Models - - - - Steering - - - - Cruise - - - - Trips - - - - Vehicle - - - - Firehose - Firehose - - - Developer - Entwickler - - - Visuals - - - - - Setup - - WARNING: Low Voltage - Warnung: Batteriespannung niedrig - - - Power your device in a car with a harness or proceed at your own risk. - Versorge dein Gerät über einen Kabelbaum im Auto mit Strom, oder fahre auf eigene Gefahr fort. - - - Power off - Ausschalten - - - Continue - Fortsetzen - - - Getting Started - Loslegen - - - Before we get on the road, let’s finish installation and cover some details. - Bevor wir uns auf die Straße begeben, lass uns die Installation fertigstellen und einige Details prüfen. - - - Connect to Wi-Fi - Mit WLAN verbinden - - - Back - Zurück - - - Continue without Wi-Fi - Ohne WLAN fortsetzen - - - Waiting for internet - Auf Internet warten - - - Enter URL - URL eingeben - - - for Custom Software - für spezifische Software - - - Downloading... - Herunterladen... - - - Download Failed - Herunterladen fehlgeschlagen - - - Ensure the entered URL is valid, and the device’s internet connection is good. - Stelle sicher, dass die eingegebene URL korrekt ist und dein Gerät eine stabile Internetverbindung hat. - - - Reboot device - Gerät neustarten - - - Start over - Von neuem beginnen - - - No custom software found at this URL. - Keine benutzerdefinierte Software unter dieser URL gefunden. - - - Something went wrong. Reboot the device. - Etwas ist schiefgelaufen. Starte das Gerät neu. - - - Select a language - Sprache wählen - - - Choose Software to Install - Wähle die zu installierende Software - - - Custom Software - Benutzerdefinierte Software - - - sunnypilot - - - - - SetupWidget - - Finish Setup - Einrichtung beenden - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - Koppele dein Gerät mit Comma Connect (connect.comma.ai) und sichere dir dein Comma Prime Angebot. - - - Pair device - Gerät koppeln - - - - Sidebar - - CONNECT - This is a brand/service name for comma connect, don't translate - CONNECT - - - OFFLINE - OFFLINE - - - ONLINE - ONLINE - - - ERROR - FEHLER - - - TEMP - TEMP - - - HIGH - HOCH - - - GOOD - GUT - - - OK - OK - - - VEHICLE - FAHRZEUG - - - NO - KEIN - - - PANDA - PANDA - - - -- - -- - - - Wi-Fi - WLAN - - - ETH - LAN - - - 2G - 2G - - - 3G - 3G - - - LTE - LTE - - - 5G - 5G - - - - SidebarSP - - DISABLED - - - - OFFLINE - OFFLINE - - - REGIST... - - - - ONLINE - ONLINE - - - ERROR - FEHLER - - - SUNNYLINK - - - - - SoftwarePanel - - UNINSTALL - Too long for UI - DEINSTALL - - - Uninstall %1 - Deinstalliere %1 - - - Are you sure you want to uninstall? - Bist du sicher, dass du Openpilot entfernen möchtest? - - - CHECK - ÜBERPRÜFEN - - - Updates are only downloaded while the car is off. - Updates werden nur heruntergeladen, wenn das Auto aus ist. - - - Current Version - Aktuelle Version - - - Download - Download - - - Install Update - Update installieren - - - INSTALL - INSTALLIEREN - - - Target Branch - Ziel Branch - - - SELECT - AUSWÄHLEN - - - Select a branch - Wähle einen Branch - - - Uninstall - Deinstallieren - - - failed to check for update - Update-Prüfung fehlgeschlagen - - - up to date, last checked %1 - Auf dem neuesten Stand, zuletzt geprüft am %1 - - - DOWNLOAD - HERUNTERLADEN - - - update available - Update verfügbar - - - never - nie - - - - SoftwarePanelSP - - Search Branch - - - - Enter search keywords, or leave blank to list all branches. - - - - No branches found for keywords: %1 - - - - Select a branch - Wähle einen Branch - - - - SshControl - - SSH Keys - SSH Schlüssel - - - Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username other than your own. A comma employee will NEVER ask you to add their GitHub username. - Warnung: Dies ermöglicht SSH zugriff für alle öffentlichen Schlüssel in deinen Github Einstellungen. Gib niemals einen anderen Benutzernamen, als deinen Eigenen an. Comma Angestellte fragen dich niemals danach ihren Github Benutzernamen hinzuzufügen. - - - ADD - HINZUFÜGEN - - - Enter your GitHub username - Gib deinen GitHub Benutzernamen ein - - - LOADING - LADEN - - - REMOVE - LÖSCHEN - - - Username '%1' has no keys on GitHub - Benutzername '%1' hat keine Schlüssel auf GitHub - - - Request timed out - Zeitüberschreitung der Anforderung - - - Username '%1' doesn't exist on GitHub - Benutzername '%1' existiert nicht auf GitHub - - - - SshToggle - - Enable SSH - SSH aktivieren - - - - SunnylinkPanel - - This is the master switch, it will allow you to cutoff any sunnylink requests should you want to do that. - - - - Enable sunnylink - - - - Sponsor Status - - - - SPONSOR - - - - Become a sponsor of sunnypilot to get early access to sunnylink features when they become available. - - - - Pair GitHub Account - - - - PAIR - KOPPELN - - - Pair your GitHub account to grant your device sponsor benefits, including API access on sunnylink. - - - - N/A - Nicht verfügbar - - - sunnylink Dongle ID not found. This may be due to weak internet connection or sunnylink registration issue. Please reboot and try again. - - - - 🎉Welcome back! We're excited to see you've enabled sunnylink again! 🚀 - - - - 👋Not going to lie, it's sad to see you disabled sunnylink 😢, but we'll be here when you're ready to come back 🎉. - - - - Backup Settings - - - - Are you sure you want to backup sunnypilot settings? - - - - Back Up - - - - Restore Settings - - - - Are you sure you want to restore the last backed up sunnypilot settings? - - - - Restore - - - - Backup in progress %1% - - - - Backup Failed - - - - Settings backup completed. - - - - Restore in progress %1% - - - - Restore Failed - - - - Unable to restore the settings, try again later. - - - - Settings restored. Confirm to restart the interface. - - - - Device ID - - - - THANKS ♥ - - - - Not Sponsor - - - - Paired - - - - Not Paired - - - - - SunnylinkSponsorPopup - - Scan the QR code to login to your GitHub account - - - - Follow the prompts to complete the pairing process - - - - Re-enter the "sunnylink" panel to verify sponsorship status - - - - If sponsorship status was not updated, please contact a moderator on Discord at https://discord.gg/sunnypilot - - - - Scan the QR code to visit sunnyhaibin's GitHub Sponsors page - - - - Choose your sponsorship tier and confirm your support - - - - Join our community on Discord at https://discord.gg/sunnypilot and reach out to a moderator to confirm your sponsor status - - - - Pair your GitHub account - - - - Early Access: Become a sunnypilot Sponsor - - - - - TermsPage - - Decline - Ablehnen - - - Agree - Zustimmen - - - Welcome to sunnypilot - - - - You must accept the Terms and Conditions to use sunnypilot. Read the latest terms at <span style='color: #465BEA;'>https://comma.ai/terms</span> before continuing. - - - - - TogglesPanel - - Enable Lane Departure Warnings - Spurverlassenswarnungen aktivieren - - - Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h). - Erhalte Warnungen, zurück in die Spur zu lenken, wenn dein Auto über eine erkannte Fahrstreifenmarkierung ohne aktivierten Blinker mit mehr als 50 km/h fährt. - - - Use Metric System - Benutze das metrische System - - - Display speed in km/h instead of mph. - Zeige die Geschwindigkeit in km/h anstatt von mph. - - - Record and Upload Driver Camera - Fahrerkamera aufnehmen und hochladen - - - Upload data from the driver facing camera and help improve the driver monitoring algorithm. - Lade Daten der Fahreraufmerksamkeitsüberwachungskamera hoch, um die Fahreraufmerksamkeitsüberwachungsalgorithmen zu verbessern. - - - Experimental Mode - Experimenteller Modus - - - Disengage on Accelerator Pedal - Bei Gasbetätigung ausschalten - - - New Driving Visualization - Neue Fahrvisualisierung - - - Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control. - Der experimentelle Modus ist momentan für dieses Auto nicht verfügbar da es den eingebauten adaptiven Tempomaten des Autos benutzt. - - - Aggressive - Aggressiv - - - Standard - Standard - - - Relaxed - Entspannt - - - Driving Personality - Fahrstil - - - End-to-End Longitudinal Control - Ende-zu-Ende Längsregelung - - - openpilot longitudinal control may come in a future update. - Die openpilot Längsregelung könnte in einem zukünftigen Update verfügbar sein. - - - The driving visualization will transition to the road-facing wide-angle camera at low speeds to better show some turns. The Experimental mode logo will also be shown in the top right corner. - Die Fahrvisualisierung wechselt bei niedrigen Geschwindigkeiten auf die nach vorne gerichtete Weitwinkelkamera, um Kurven besser darzustellen. Das Logo des Experimentellen Modus wird außerdem oben rechts angezeigt. - - - Always-On Driver Monitoring - Dauerhaft aktive Fahrerüberwachung - - - Enable sunnypilot - - - - Use the sunnypilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature. - - - - Enable Dynamic Experimental Control - - - - Enable toggle to allow the model to determine when to use sunnypilot ACC or sunnypilot End to End Longitudinal. - - - - When enabled, pressing the accelerator pedal will disengage sunnypilot. - - - - Enable driver monitoring even when sunnypilot is not engaged. - - - - Standard is recommended. In aggressive mode, sunnypilot will follow lead cars closer and be more aggressive with the gas and brake. In relaxed mode sunnypilot will stay further away from lead cars. On supported cars, you can cycle through these personalities with your steering wheel distance button. - - - - Changing this setting will restart openpilot if the car is powered on. - - - - sunnypilot defaults to driving in <b>chill mode</b>. Experimental mode enables <b>alpha-level features</b> that aren't ready for chill mode. Experimental features are listed below: - - - - Let the driving model control the gas and brakes. sunnypilot will drive as it thinks a human would, including stopping for red lights and stop signs. Since the driving model decides the speed to drive, the set speed will only act as an upper bound. This is an alpha quality feature; mistakes should be expected. - - - - An alpha version of sunnypilot longitudinal control can be tested, along with Experimental mode, on non-release branches. - - - - Enable the sunnypilot longitudinal control (alpha) toggle to allow Experimental mode. - - - - - Updater - - Update Required - Aktualisierung notwendig - - - An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. The download size is approximately 1GB. - Eine Aktualisierung des Betriebssystems ist notwendig. Verbinde dein Gerät mit WLAN für ein schnelleres Update. Die Download Größe ist ungefähr 1GB. - - - Connect to Wi-Fi - Mit WLAN verbinden - - - Install - Installieren - - - Back - Zurück - - - Loading... - Laden... - - - Reboot - Neustart - - - Update failed - Aktualisierung fehlgeschlagen - - - - WiFiPromptWidget - - Open - Öffnen - - - Maximize your training data uploads to improve openpilot's driving models. - Maximiere deine Trainingsdaten-Uploads, um die Fahrmodelle von openpilot zu verbessern. - - - <span style='font-family: "Noto Color Emoji";'>🔥</span> Firehose Mode <span style='font-family: Noto Color Emoji;'>🔥</span> - <span style='font-family: "Noto Color Emoji";'>🔥</span> Firehose-Modus <span style='font-family: Noto Color Emoji;'>🔥</span> - - - - WifiUI - - Scanning for networks... - Suche nach Netzwerken... - - - CONNECTING... - VERBINDEN... - - - FORGET - VERGESSEN - - - Forget Wi-Fi Network "%1"? - WLAN Netzwerk "%1" vergessen? - - - Forget - Vergessen - - - diff --git a/selfdrive/ui/translations/main_en.ts b/selfdrive/ui/translations/main_en.ts deleted file mode 100644 index fbccbedb20..0000000000 --- a/selfdrive/ui/translations/main_en.ts +++ /dev/null @@ -1,48 +0,0 @@ - - - - - FirehosePanel - - <b>%n segment(s)</b> of your driving is in the training dataset so far. - - <b>%n segment</b> of your driving is in the training dataset so far. - <b>%n segments</b> of your driving are in the training dataset so far. - - - - - InputDialog - - Need at least %n character(s)! - - Need at least %n character! - Need at least %n characters! - - - - - QObject - - %n minute(s) ago - - %n minute ago - %n minutes ago - - - - %n hour(s) ago - - %n hour ago - %n hours ago - - - - %n day(s) ago - - %n day ago - %n days ago - - - - diff --git a/selfdrive/ui/translations/main_es.ts b/selfdrive/ui/translations/main_es.ts deleted file mode 100644 index 3d9622166a..0000000000 --- a/selfdrive/ui/translations/main_es.ts +++ /dev/null @@ -1,2114 +0,0 @@ - - - - - AbstractAlert - - Close - Cerrar - - - Snooze Update - Posponer Actualización - - - Reboot and Update - Reiniciar y Actualizar - - - - AdvancedNetworking - - Back - Volver - - - Enable Tethering - Activar Tether - - - Tethering Password - Contraseña de Tethering - - - EDIT - EDITAR - - - Enter new tethering password - Nueva contraseña de tethering - - - IP Address - Dirección IP - - - Enable Roaming - Activar Roaming - - - APN Setting - Configuración de APN - - - Enter APN - Insertar APN - - - leave blank for automatic configuration - dejar en blanco para configuración automática - - - Cellular Metered - Plano de datos limitado - - - Hidden Network - Red Oculta - - - CONNECT - CONECTAR - - - Enter SSID - Ingrese SSID - - - Enter password - Ingrese contraseña - - - for "%1" - para "%1" - - - Prevent large data uploads when on a metered cellular connection - - - - default - - - - metered - - - - unmetered - - - - Wi-Fi Network Metered - - - - Prevent large data uploads when on a metered Wi-Fi connection - - - - - AutoLaneChangeTimer - - Auto Lane Change by Blinker - - - - Set a timer to delay the auto lane change operation when the blinker is used. No nudge on the steering wheel is required to auto lane change if a timer is set. Default is Nudge. -Please use caution when using this feature. Only use the blinker when traffic and road conditions permit. - - - - s - - - - Off - - - - Nudge - - - - Nudgeless - - - - - ConfirmationDialog - - Ok - OK - - - Cancel - Cancelar - - - - DeclinePage - - You must accept the Terms and Conditions in order to use sunnypilot. - Debe aceptar los términos y condiciones para poder utilizar sunnypilot. - - - Back - Atrás - - - Decline, uninstall %1 - Rechazar, desinstalar %1 - - - - DeveloperPanel - - Joystick Debug Mode - Modo de depuración de joystick - - - Longitudinal Maneuver Mode - Modo de maniobra longitudinal - - - Enable ADB - - - - ADB (Android Debug Bridge) allows connecting to your device over USB or over the network. See https://docs.comma.ai/how-to/connect-to-comma for more info. - - - - Enable GitHub runner service - - - - Enables or disables the github runner service. - - - - Error Log - - - - VIEW - VER - - - View the error log for sunnypilot crashes. - - - - openpilot Longitudinal Control (Alpha) - - - - WARNING: openpilot longitudinal control is in alpha for this car and will disable Automatic Emergency Braking (AEB). - - - - On this car, sunnypilot defaults to the car's built-in ACC instead of openpilot's longitudinal control. Enable this to switch to openpilot longitudinal control. Enabling Experimental mode is recommended when enabling openpilot longitudinal control alpha. - - - - - DevicePanel - - Dongle ID - Dongle ID - - - N/A - N/A - - - Serial - Serial - - - Pair Device - Emparejar Dispositivo - - - PAIR - EMPAREJAR - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - Empareja tu dispositivo con comma connect (connect.comma.ai) y reclama tu oferta de comma prime. - - - Driver Camera - Cámara del conductor - - - PREVIEW - VISUALIZAR - - - Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off) - Previsualizar la cámara del conductor para garantizar que la monitorización del sistema tenga buena visibilidad (el vehículo tiene que estar apagado) - - - Reset Calibration - Formatear Calibración - - - RESET - REINICIAR - - - Are you sure you want to reset calibration? - ¿Seguro que quiere formatear la calibración? - - - Reset - Formatear - - - Review Training Guide - Revisar la Guía de Entrenamiento - - - REVIEW - REVISAR - - - Review the rules, features, and limitations of sunnypilot - Revisar las reglas, características y limitaciones de sunnypilot - - - Are you sure you want to review the training guide? - ¿Seguro que quiere revisar la guía de entrenamiento? - - - Review - Revisar - - - Regulatory - Regulador - - - VIEW - VER - - - Change Language - Cambiar Idioma - - - CHANGE - CAMBIAR - - - Select a language - Seleccione el idioma - - - Reboot - Reiniciar - - - Power Off - Apagar - - - sunnypilot requires the device to be mounted within 4° left or right and within 5° up or 9° down. sunnypilot is continuously calibrating, resetting is rarely required. - sunnypilot requiere que el dispositivo sea montado entre 4° grados a la izquierda o derecha y entre 5° grados hacia arriba o 9° grados hacia abajo. sunnypilot está constantemente en calibración, formatear rara vez es necesario. - - - Your device is pointed %1° %2 and %3° %4. - Su dispositivo está apuntando %1° %2 y %3° %4. - - - down - abajo - - - up - arriba - - - left - izquierda - - - right - derecha - - - Are you sure you want to reboot? - ¿Seguro qué quiere reiniciar? - - - Disengage to Reboot - Desactivar para Reiniciar - - - Are you sure you want to power off? - ¿Seguro qué quiere apagar? - - - Disengage to Power Off - Desactivar para apagar - - - Disengage to Reset Calibration - - - - Resetting calibration will restart openpilot if the car is powered on. - - - - - DevicePanelSP - - Driver Camera Preview - - - - Training Guide - - - - Regulatory - Regulador - - - Language - - - - Are you sure you want to review the training guide? - ¿Seguro que quiere revisar la guía de entrenamiento? - - - Review - Revisar - - - Select a language - - - - Reboot - Reiniciar - - - Power Off - Apagar - - - Offroad Mode - - - - Are you sure you want to exit Always Offroad mode? - - - - Confirm - Confirmar - - - Are you sure you want to enter Always Offroad mode? - - - - Disengage to Enter Always Offroad Mode - - - - Exit Always Offroad - - - - Always Offroad - - - - Quiet Mode - - - - Reset Settings - - - - Are you sure you want to reset all sunnypilot settings to default? Once the settings are reset, there is no going back. - - - - Reset - Formatear - - - The reset cannot be undone. You have been warned. - - - - - DriveStats - - Drives - - - - Hours - - - - ALL TIME - - - - PAST WEEK - - - - KM - - - - Miles - - - - - DriverViewWindow - - camera starting - iniciando cámara - - - - ExperimentalModeButton - - EXPERIMENTAL MODE ON - MODO EXPERIMENTAL - - - CHILL MODE ON - MODO CHILL - - - - FirehosePanel - - 🔥 Firehose Mode 🔥 - - - - Firehose Mode: ACTIVE - - - - ACTIVE - - - - For maximum effectiveness, bring your device inside and connect to a good USB-C adapter and Wi-Fi weekly.<br><br>Firehose Mode can also work while you're driving if connected to a hotspot or unlimited SIM card.<br><br><br><b>Frequently Asked Questions</b><br><br><i>Does it matter how or where I drive?</i> Nope, just drive as you normally would.<br><br><i>Do all of my segments get pulled in Firehose Mode?</i> No, we selectively pull a subset of your segments.<br><br><i>What's a good USB-C adapter?</i> Any fast phone or laptop charger should be fine.<br><br><i>Does it matter which software I run?</i> Yes, only upstream sunnypilot (and particular forks) are able to be used for training. - - - - <b>%n segment(s)</b> of your driving is in the training dataset so far. - - - - - - - sunnypilot learns to drive by watching humans, like you, drive. - -Firehose Mode allows you to maximize your training data uploads to improve openpilot's driving models. More data means bigger models, which means better Experimental Mode. - - - - <span stylesheet='font-size: 60px; font-weight: bold; color: #e74c3c;'>INACTIVE</span>: connect to an unmetered network - - - - - HudRenderer - - km/h - km/h - - - mph - mph - - - MAX - MAX - - - - HyundaiSettings - - Off - - - - Dynamic - - - - Predictive - - - - Custom Longitudinal Tuning - - - - This feature can only be used with openpilot longitudinal control enabled. - - - - Enable "Always Offroad" in Device panel, or turn vehicle off to select an option. - - - - Off: Uses default tuning - - - - Dynamic: Adjusts acceleration limits based on current speed - - - - Predictive: Uses future trajectory data to anticipate needed adjustments - - - - Fine-tune your driving experience by adjusting acceleration smoothness with openpilot longitudinal control. - - - - - InputDialog - - Cancel - Cancelar - - - Need at least %n character(s)! - - ¡Necesita mínimo %n caracter! - ¡Necesita mínimo %n caracteres! - - - - - LaneChangeSettings - - Back - - - - Auto Lane Change: Delay with Blind Spot - - - - Toggle to enable a delay timer for seamless lane changes when blind spot monitoring (BSM) detects a obstructing vehicle, ensuring safe maneuvering. - - - - - LateralPanel - - Modular Assistive Driving System (MADS) - - - - Enable the beloved MADS feature. Disable toggle to revert back to stock sunnypilot engagement/disengagement. - - - - Customize MADS - - - - Customize Lane Change - - - - Enables independent engagements of Automatic Lane Centering (ALC) and Adaptive Cruise Control (ACC). - - - - Start the vehicle to check vehicle compatibility. - - - - This platform supports all MADS settings. - - - - This platform supports limited MADS settings. - - - - - MadsSettings - - Toggle with Main Cruise - - - - Note: For vehicles without LFA/LKAS button, disabling this will prevent lateral control engagement. - - - - Unified Engagement Mode (UEM) - - - - Engage lateral and longitudinal control with cruise control engagement. - - - - Note: Once lateral control is engaged via UEM, it will remain engaged until it is manually disabled via the MADS button or car shut off. - - - - Remain Active - - - - Disengage - - - - Steering Mode on Brake Pedal - - - - Start the vehicle to check vehicle compatibility. - - - - This feature defaults to OFF, and does not allow selection due to vehicle limitations. - - - - This feature defaults to ON, and does not allow selection due to vehicle limitations. - - - - This platform only supports Disengage mode due to vehicle limitations. - - - - Remain Active: ALC will remain active when the brake pedal is pressed. - - - - Pause - - - - Pause: ALC will pause when the brake pedal is pressed. - - - - Disengage: ALC will disengage when the brake pedal is pressed. - - - - Choose how Automatic Lane Centering (ALC) behaves after the brake pedal is manually pressed in sunnypilot. - - - - - MaxTimeOffroad - - Max Time Offroad - - - - Device will automatically shutdown after set time once the engine is turned off.<br/>(30h is the default) - - - - Always On - - - - h - - - - m - - - - (default) - - - - - ModelsPanel - - Current Model - - - - SELECT - SELECCIONAR - - - No custom model selected! - - - - Driving - - - - Navigation - - - - Vision - - - - Policy - - - - Downloading %1 model [%2]... (%3%) - - - - %1 model [%2] %3 - - - - downloaded - - - - ready - - - - from cache - - - - %1 model [%2] download failed - - - - %1 model [%2] pending... - - - - Fetching models... - - - - Use Default - - - - Select a Model - - - - Default - - - - Model download has started in the background. - - - - We STRONGLY suggest you to reset calibration. - - - - Would you like to do that now? - - - - Reset Calibration - Formatear Calibración - - - Driving Model Selector - - - - Warning: You are on a metered connection! - - - - Continue - Continuar - - - on Metered - - - - Cancel - Cancelar - - - - MultiOptionDialog - - Select - Seleccionar - - - Cancel - Cancelar - - - - Networking - - Advanced - Avanzado - - - Enter password - Ingresar contraseña - - - for "%1" - para "%1" - - - Wrong password - Contraseña incorrecta - - - - NetworkingSP - - Scan - - - - Scanning... - - - - - NeuralNetworkLateralControl - - Neural Network Lateral Control (NNLC) - - - - NNLC is currently not available on this platform. - - - - Start the car to check car compatibility - - - - NNLC Not Loaded - - - - NNLC Loaded - - - - Match - - - - Exact - - - - Fuzzy - - - - Match: "Exact" is ideal, but "Fuzzy" is fine too. - - - - Formerly known as <b>"NNFF"</b>, this replaces the lateral <b>"torque"</b> controller, with one using a neural network trained on each car's (actually, each separate EPS firmware) driving data for increased controls accuracy. - - - - Reach out to the sunnypilot team in the following channel at the sunnypilot Discord server - - - - with feedback, or to provide log data for your car if your car is currently unsupported: - - - - if there are any issues: - - - - and donate logs to get NNLC loaded for your car: - - - - - OffroadAlert - - Device temperature too high. System cooling down before starting. Current internal component temperature: %1 - La temperatura del dispositivo es muy alta. El sistema se está enfriando antes de iniciar. Temperatura actual del componente interno: %1 - - - Immediately connect to the internet to check for updates. If you do not connect to the internet, sunnypilot won't engage in %1 - Conéctese inmediatamente al internet para buscar actualizaciones. Si no se conecta al internet, sunnypilot no iniciará en %1 - - - Connect to internet to check for updates. sunnypilot won't automatically start until it connects to internet to check for updates. - Conectese al internet para buscar actualizaciones. sunnypilot no iniciará automáticamente hasta conectarse al internet para buscar actualizaciones. - - - Unable to download updates -%1 - Incapaz de descargar actualizaciones. -%1 - - - Taking camera snapshots. System won't start until finished. - Tomando capturas de las cámaras. El sistema no se iniciará hasta que finalice. - - - An update to your device's operating system is downloading in the background. You will be prompted to update when it's ready to install. - Se está descargando una actualización del sistema operativo de su dispositivo en segundo plano. Se le pedirá que actualice cuando esté listo para instalarse. - - - Device failed to register. It will not connect to or upload to comma.ai servers, and receives no support from comma.ai. If this is an official device, visit https://comma.ai/support. - El dispositivo no pudo registrarse. No se conectará ni subirá datos a los servidores de comma.ai y no recibe soporte de comma.ai. Si este es un dispositivo oficial, visite https://comma.ai/support. - - - NVMe drive not mounted. - Unidad NVMe no montada. - - - Unsupported NVMe drive detected. Device may draw significantly more power and overheat due to the unsupported NVMe. - Se detectó una unidad NVMe incompatible. El dispositivo puede consumir mucha más energía y sobrecalentarse debido a esto. - - - sunnypilot was unable to identify your car. Your car is either unsupported or its ECUs are not recognized. Please submit a pull request to add the firmware versions to the proper vehicle. Need help? Join discord.comma.ai. - sunnypilot no pudo identificar su automóvil. Su automóvil no es compatible o no se reconocen sus ECU. Por favor haga un pull request para agregar las versiones de firmware del vehículo adecuado. ¿Necesita ayuda? Únase a discord.comma.ai. - - - sunnypilot detected a change in the device's mounting position. Ensure the device is fully seated in the mount and the mount is firmly secured to the windshield. - sunnypilot detectó un cambio en la posición de montaje del dispositivo. Asegúrese de que el dispositivo esté completamente asentado en el soporte y que el soporte esté firmemente asegurado al parabrisas. - - - sunnypilot is now in Always Offroad mode. sunnypilot won't start until Always Offroad mode is disabled. Go to "Settings" -> "Device" to exit Always Offroad mode. - - - - - OffroadHome - - UPDATE - ACTUALIZAR - - - ALERTS - ALERTAS - - - ALERT - ALERTA - - - - OnroadAlerts - - sunnypilot Unavailable - sunnypilot no disponible - - - TAKE CONTROL IMMEDIATELY - TOME CONTROL INMEDIATAMENTE - - - Reboot Device - Reiniciar Dispositivo - - - Waiting to start - Esperando para iniciar - - - System Unresponsive - Systema no responde - - - - PairingPopup - - Pair your device to your comma account - Empareje su dispositivo con su cuenta de comma - - - Go to https://connect.comma.ai on your phone - Vaya a https://connect.comma.ai en su teléfono - - - Click "add new device" and scan the QR code on the right - Seleccione "agregar nuevo dispositivo" y escanee el código QR a la derecha - - - Bookmark connect.comma.ai to your home screen to use it like an app - Añada connect.comma.ai a su pantalla de inicio para usarlo como una aplicación - - - Please connect to Wi-Fi to complete initial pairing - Conéctese a Wi-Fi para completar el emparejamiento inicial - - - - ParamControl - - Enable - Activar - - - Cancel - Cancelar - - - - ParamControlSP - - Enable - Activar - - - Cancel - Cancelar - - - - PlatformSelector - - Vehicle - - - - SEARCH - - - - Search your vehicle - - - - Enter model year (e.g., 2021) and model name (Toyota Corolla): - - - - SEARCHING - - - - REMOVE - ELIMINAR - - - This setting will take effect immediately. - - - - This setting will take effect once the device enters offroad state. - - - - Vehicle Selector - - - - Confirm - Confirmar - - - Cancel - Cancelar - - - No vehicles found for query: %1 - - - - Select a vehicle - - - - Unrecognized Vehicle - - - - Fingerprinted automatically - - - - Manually selected - - - - Not fingerprinted or manually selected - - - - Select vehicle to force fingerprint manually. - - - - Colors represent fingerprint status: - - - - - PrimeAdWidget - - Upgrade Now - Actualizar Ahora - - - Become a comma prime member at connect.comma.ai - Hazte miembro de comma prime en connect.comma.ai - - - PRIME FEATURES: - BENEFICIOS PRIME: - - - Remote access - Acceso remoto - - - 24/7 LTE connectivity - Conectividad LTE 24/7 - - - 1 year of drive storage - 1 año de almacenamiento - - - Remote snapshots - Capturas remotas - - - - PrimeUserWidget - - ✓ SUBSCRIBED - ✓ SUSCRITO - - - comma prime - comma prime - - - - QObject - - sunnypilot - sunnypilot - - - now - ahora - - - %n minute(s) ago - - hace %n min - hace %n mins - - - - %n hour(s) ago - - hace %n hora - hace %n horas - - - - %n day(s) ago - - hace %n día - hace %n días - - - - - Reset - - Reset failed. Reboot to try again. - Formateo fallido. Reinicie para reintentar. - - - Resetting device... -This may take up to a minute. - formateando dispositivo... -Esto puede tardar un minuto. - - - Are you sure you want to reset your device? - ¿Seguro que quiere formatear su dispositivo? - - - System Reset - Formatear Sistema - - - System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot. - Formateo del sistema activado. Presione confirmar para borrar todo el contenido y la configuración. Presione cancelar para reanudar el inicio. - - - Cancel - Cancelar - - - Reboot - Reiniciar - - - Confirm - Confirmar - - - Unable to mount data partition. Partition may be corrupted. Press confirm to erase and reset your device. - No es posible montar una partición de datos. La partición podría estar corrompida. Confirme para borrar y formatear su dispositivo. - - - - SettingsWindow - - × - × - - - Device - Dispositivo - - - Network - Red - - - Toggles - Ajustes - - - Software - Software - - - Developer - Desarrollador - - - Firehose - - - - - SettingsWindowSP - - × - × - - - Device - Dispositivo - - - Network - Red - - - sunnylink - - - - Toggles - Ajustes - - - Software - Software - - - Trips - - - - Vehicle - - - - Developer - Desarrollador - - - Firehose - - - - Steering - - - - Models - - - - Cruise - - - - Visuals - - - - - Setup - - Something went wrong. Reboot the device. - Algo ha ido mal. Reinicie el dispositivo. - - - Ensure the entered URL is valid, and the device’s internet connection is good. - Asegúrese de que la URL insertada es válida y que el dispositivo tiene buena conexión. - - - No custom software found at this URL. - No encontramos software personalizado en esta URL. - - - WARNING: Low Voltage - ALERTA: Voltaje bajo - - - Power your device in a car with a harness or proceed at your own risk. - Encienda su dispositivo en un auto con el arnés o proceda bajo su propio riesgo. - - - Power off - Apagar - - - Continue - Continuar - - - Getting Started - Comenzando - - - Before we get on the road, let’s finish installation and cover some details. - Antes de ponernos en marcha, terminemos la instalación y cubramos algunos detalles. - - - Connect to Wi-Fi - Conectarse al Wi-Fi - - - Back - Volver - - - Continue without Wi-Fi - Continuar sin Wi-Fi - - - Waiting for internet - Esperando conexión a internet - - - Choose Software to Install - Elija el software a instalar - - - sunnypilot - sunnypilot - - - Custom Software - Software personalizado - - - Enter URL - Insertar URL - - - for Custom Software - para Software personalizado - - - Downloading... - Descargando... - - - Download Failed - Descarga fallida - - - Reboot device - Reiniciar Dispositivo - - - Start over - Comenzar de nuevo - - - Select a language - Seleccione un idioma - - - - SetupWidget - - Finish Setup - Terminar configuración - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - Empareje su dispositivo con comma connect (connect.comma.ai) y reclame su oferta de comma prime. - - - Pair device - Emparejar dispositivo - - - - Sidebar - - CONNECT - CONNECT - - - OFFLINE - OFFLINE - - - ONLINE - EN LÍNEA - - - ERROR - ERROR - - - TEMP - TEMP - - - HIGH - ALTA - - - GOOD - BUENA - - - OK - OK - - - VEHICLE - VEHÍCULO - - - NO - SIN - - - PANDA - PANDA - - - -- - -- - - - Wi-Fi - Wi-Fi - - - ETH - ETH - - - 2G - 2G - - - 3G - 3G - - - LTE - LTE - - - 5G - 5G - - - - SidebarSP - - DISABLED - - - - OFFLINE - OFFLINE - - - REGIST... - - - - ONLINE - EN LÍNEA - - - ERROR - ERROR - - - SUNNYLINK - - - - - SoftwarePanel - - Updates are only downloaded while the car is off. - Actualizaciones solo se descargan con el auto apagado. - - - Current Version - Versión Actual - - - Download - Descargar - - - CHECK - VERIFICAR - - - Install Update - Actualizar - - - INSTALL - INSTALAR - - - Target Branch - Rama objetivo - - - SELECT - SELECCIONAR - - - Select a branch - Selecione una rama - - - Uninstall %1 - Desinstalar %1 - - - UNINSTALL - DESINSTALAR - - - Are you sure you want to uninstall? - ¿Seguro qué desea desinstalar? - - - Uninstall - Desinstalar - - - failed to check for update - no se pudo buscar actualizaciones - - - DOWNLOAD - DESCARGAR - - - update available - actualización disponible - - - never - nunca - - - up to date, last checked %1 - actualizado, último chequeo %1 - - - - SoftwarePanelSP - - Search Branch - - - - Enter search keywords, or leave blank to list all branches. - - - - No branches found for keywords: %1 - - - - Select a branch - Selecione una rama - - - - SshControl - - SSH Keys - Clave SSH - - - Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username other than your own. A comma employee will NEVER ask you to add their GitHub username. - Aviso: Esto otorga acceso SSH a todas las claves públicas en su Github. Nunca ingrese un nombre de usuario de Github que no sea suyo. Un empleado de comma NUNCA le pedirá que añada un usuario de Github que no sea el suyo. - - - ADD - AÑADIR - - - Enter your GitHub username - Ingrese su usuario de GitHub - - - LOADING - CARGANDO - - - REMOVE - ELIMINAR - - - Username '%1' has no keys on GitHub - El usuario "%1” no tiene claves en GitHub - - - Request timed out - Solicitud expirada - - - Username '%1' doesn't exist on GitHub - El usuario '%1' no existe en Github - - - - SshToggle - - Enable SSH - Habilitar SSH - - - - SunnylinkPanel - - This is the master switch, it will allow you to cutoff any sunnylink requests should you want to do that. - - - - Enable sunnylink - - - - 🎉Welcome back! We're excited to see you've enabled sunnylink again! 🚀 - - - - 👋Not going to lie, it's sad to see you disabled sunnylink 😢, but we'll be here when you're ready to come back 🎉. - - - - Device ID - - - - N/A - N/A - - - Sponsor Status - Estado de patrocinio - - - SPONSOR - PATROCINADOR - - - Become a sponsor of sunnypilot to get early access to sunnylink features when they become available. - Conviértete en patrocinador de sunnypilot para obtener acceso anticipado a las funciones de sunnylink cuando estén disponibles. - - - Pair GitHub Account - Emparejar cuenta de GitHub - - - PAIR - EMPAREJAR - - - Pair your GitHub account to grant your device sponsor benefits, including API access on sunnylink. - Empareja tu cuenta de GitHub para otorgar a tu dispositivo beneficios de patrocinador, incluido acceso a la API en sunnylink. - - - sunnylink Dongle ID not found. This may be due to weak internet connection or sunnylink registration issue. Please reboot and try again. - ID del dongle de sunnylink no encontrado. Esto puede deberse a una conexión débil o a un problema de registro en sunnylink. Por favor, reinicia y vuelve a intentarlo. - - - Not Sponsor - No patrocinador - - - Paired - Emparejado - - - Not Paired - No emparejado - - - THANKS ♥ - GRACIAS ♥ - - - Backup Settings - - - - Are you sure you want to backup sunnypilot settings? - - - - Back Up - - - - Restore Settings - - - - Are you sure you want to restore the last backed up sunnypilot settings? - - - - Restore - - - - Backup in progress %1% - - - - Backup Failed - - - - Settings backup completed. - - - - Restore in progress %1% - - - - Restore Failed - - - - Unable to restore the settings, try again later. - - - - Settings restored. Confirm to restart the interface. - - - - - SunnylinkSponsorPopup - - Scan the QR code to login to your GitHub account - Escanea el código QR para iniciar sesión en tu cuenta de GitHub - - - Follow the prompts to complete the pairing process - Sigue las indicaciones para completar el proceso de emparejamiento - - - Re-enter the "sunnylink" panel to verify sponsorship status - Vuelve a ingresar al panel de "sunnylink" para verificar el estado de patrocinio - - - If sponsorship status was not updated, please contact a moderator on Discord at https://discord.gg/sunnypilot - Si el estado de patrocinio no se actualizó, por favor contacta a un moderador en Discord en https://discord.gg/sunnypilot - - - Scan the QR code to visit sunnyhaibin's GitHub Sponsors page - Escanea el código QR para visitar la página de GitHub Sponsors de sunnyhaibin - - - Choose your sponsorship tier and confirm your support - Elige tu nivel de patrocinio y confirma tu apoyo - - - Join our community on Discord at https://discord.gg/sunnypilot and reach out to a moderator to confirm your sponsor status - Únete a nuestra comunidad en Discord en https://discord.gg/sunnypilot y contacta a un moderador para confirmar tu estado de patrocinio - - - Pair your GitHub account - Empareja tu cuenta de GitHub - - - Early Access: Become a sunnypilot Sponsor - Acceso temprano: conviértete en patrocinador de sunnypilot - - - - TermsPage - - Decline - Rechazar - - - Agree - Aceptar - - - Welcome to sunnypilot - - - - You must accept the Terms and Conditions to use sunnypilot. Read the latest terms at <span style='color: #465BEA;'>https://comma.ai/terms</span> before continuing. - - - - - TogglesPanel - - Experimental Mode - Modo Experimental - - - Disengage on Accelerator Pedal - Desactivar con el Acelerador - - - When enabled, pressing the accelerator pedal will disengage sunnypilot. - Cuando esté activado, presionar el acelerador deshabilitará sunnypilot. - - - Enable Lane Departure Warnings - Activar Avisos de Salida de Carril - - - Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h). - Recibir alertas para volver al carril cuando su vehículo se salga fuera del carril sin que esté activada la señal de giro y esté conduciendo por encima de 50 km/h (31 mph). - - - Always-On Driver Monitoring - Monitoreo Permanente del Conductor - - - Enable driver monitoring even when sunnypilot is not engaged. - Habilitar el monitoreo del conductor incluso cuando Openpilot no esté activado. - - - Record and Upload Driver Camera - Grabar y Subir Cámara del Conductor - - - Upload data from the driver facing camera and help improve the driver monitoring algorithm. - Subir datos de la cámara del conductor para ayudar a mejorar el algoritmo de monitoreo del conductor. - - - Use Metric System - Usar Sistema Métrico - - - Display speed in km/h instead of mph. - Mostrar velocidad en km/h en vez de mph. - - - Aggressive - Agresivo - - - Standard - Estándar - - - Relaxed - Relajado - - - Driving Personality - Personalidad de conducción - - - Standard is recommended. In aggressive mode, sunnypilot will follow lead cars closer and be more aggressive with the gas and brake. In relaxed mode sunnypilot will stay further away from lead cars. On supported cars, you can cycle through these personalities with your steering wheel distance button. - Se recomienda el modo estándar. En el modo agresivo, sunnypilot seguirá más cerca a los autos delante suyo y será más agresivo con el acelerador y el freno. En modo relajado, sunnypilot se mantendrá más alejado de los autos delante suyo. En automóviles compatibles, puede recorrer estas personalidades con el botón de distancia del volante. - - - sunnypilot defaults to driving in <b>chill mode</b>. Experimental mode enables <b>alpha-level features</b> that aren't ready for chill mode. Experimental features are listed below: - sunnypilot por defecto conduce en <b>modo chill</b>. El modo Experimental activa <b>funcionalidades en fase experimental</b>, que no están listas para el modo chill. Las funcionalidades del modo expeimental están listados abajo: - - - End-to-End Longitudinal Control - Control Longitudinal de Punta a Punta - - - Let the driving model control the gas and brakes. sunnypilot will drive as it thinks a human would, including stopping for red lights and stop signs. Since the driving model decides the speed to drive, the set speed will only act as an upper bound. This is an alpha quality feature; mistakes should be expected. - Dajar que el modelo de conducción controle la aceleración y el frenado. sunnypilot conducirá como piensa que lo haría una persona, incluiyendo parar en los semáforos en rojo y las señales de alto. Dado que el modelo decide la velocidad de conducción, la velocidad de crucero establecida solo actuará como el límite superior. Este recurso aún está en fase experimental; deberían esperarse errores. - - - New Driving Visualization - Nueva Visualización de la conducción - - - The driving visualization will transition to the road-facing wide-angle camera at low speeds to better show some turns. The Experimental mode logo will also be shown in the top right corner. - La visualización de la conducción cambiará a la cámara que enfoca la carretera a velocidades bajas para mostrar mejor los giros. El logo del modo experimental también se mostrará en la esquina superior derecha. - - - Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control. - El modo Experimental no está disponible actualmente para este auto, ya que el ACC default del auto está siendo usado para el control longitudinal. - - - An alpha version of sunnypilot longitudinal control can be tested, along with Experimental mode, on non-release branches. - Se puede probar una versión experimental del control longitudinal sunnypilot, junto con el modo Experimental, en ramas no liberadas. - - - Enable the sunnypilot longitudinal control (alpha) toggle to allow Experimental mode. - Activar el control longitudinal (fase experimental) para permitir el modo Experimental. - - - Enable Dynamic Experimental Control - - - - Enable toggle to allow the model to determine when to use sunnypilot ACC or sunnypilot End to End Longitudinal. - - - - Enable sunnypilot - Activar sunnypilot - - - Use the sunnypilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature. - - - - Changing this setting will restart openpilot if the car is powered on. - - - - openpilot longitudinal control may come in a future update. - - - - - Updater - - Update Required - Actualización Requerida - - - An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. The download size is approximately 1GB. - Es necesario la actualización del sistema operativo. Conecte su dispositivo al Wi-Fi para una actualización rápida. El tamaño de descarga es de aproximadamente 1GB. - - - Connect to Wi-Fi - Conectarse a la Wi-Fi - - - Install - Instalar - - - Back - Volver - - - Loading... - Cargando... - - - Reboot - Reiniciar - - - Update failed - Actualización fallida - - - - WiFiPromptWidget - - Open - - - - <span style='font-family: "Noto Color Emoji";'>🔥</span> Firehose Mode <span style='font-family: Noto Color Emoji;'>🔥</span> - - - - Maximize your training data uploads to improve openpilot's driving models. - - - - - WifiUI - - Scanning for networks... - Buscando redes... - - - CONNECTING... - CONECTANDO... - - - FORGET - OLVIDAR - - - Forget Wi-Fi Network "%1"? - ¿Olvidar la Red de Wi-Fi "%1"? - - - Forget - Olvidar - - - diff --git a/selfdrive/ui/translations/main_fr.ts b/selfdrive/ui/translations/main_fr.ts deleted file mode 100644 index 741cc606a7..0000000000 --- a/selfdrive/ui/translations/main_fr.ts +++ /dev/null @@ -1,2114 +0,0 @@ - - - - - AbstractAlert - - Close - Fermer - - - Snooze Update - Reporter la mise à jour - - - Reboot and Update - Redémarrer et mettre à jour - - - - AdvancedNetworking - - Back - Retour - - - Enable Tethering - Activer le partage de connexion - - - Tethering Password - Mot de passe du partage de connexion - - - EDIT - MODIFIER - - - Enter new tethering password - Entrez le nouveau mot de passe du partage de connexion - - - IP Address - Adresse IP - - - Enable Roaming - Activer l'itinérance - - - APN Setting - Paramètre APN - - - Enter APN - Entrer le nom du point d'accès - - - leave blank for automatic configuration - laisser vide pour une configuration automatique - - - Cellular Metered - Connexion cellulaire limitée - - - Hidden Network - Réseau Caché - - - CONNECT - CONNECTER - - - Enter SSID - Entrer le SSID - - - Enter password - Entrer le mot de passe - - - for "%1" - pour "%1" - - - Prevent large data uploads when on a metered cellular connection - - - - default - - - - metered - - - - unmetered - - - - Wi-Fi Network Metered - - - - Prevent large data uploads when on a metered Wi-Fi connection - - - - - AutoLaneChangeTimer - - Auto Lane Change by Blinker - - - - Set a timer to delay the auto lane change operation when the blinker is used. No nudge on the steering wheel is required to auto lane change if a timer is set. Default is Nudge. -Please use caution when using this feature. Only use the blinker when traffic and road conditions permit. - - - - s - - - - Off - - - - Nudge - - - - Nudgeless - - - - - ConfirmationDialog - - Ok - Ok - - - Cancel - Annuler - - - - DeclinePage - - You must accept the Terms and Conditions in order to use sunnypilot. - Vous devez accepter les conditions générales pour utiliser sunnypilot. - - - Back - Retour - - - Decline, uninstall %1 - Refuser, désinstaller %1 - - - - DeveloperPanel - - Joystick Debug Mode - Mode débogage au joystick - - - Longitudinal Maneuver Mode - Mode manœuvre longitudinale - - - Enable ADB - - - - ADB (Android Debug Bridge) allows connecting to your device over USB or over the network. See https://docs.comma.ai/how-to/connect-to-comma for more info. - - - - Enable GitHub runner service - - - - Enables or disables the github runner service. - - - - Error Log - - - - VIEW - VOIR - - - View the error log for sunnypilot crashes. - - - - openpilot Longitudinal Control (Alpha) - - - - WARNING: openpilot longitudinal control is in alpha for this car and will disable Automatic Emergency Braking (AEB). - - - - On this car, sunnypilot defaults to the car's built-in ACC instead of openpilot's longitudinal control. Enable this to switch to openpilot longitudinal control. Enabling Experimental mode is recommended when enabling openpilot longitudinal control alpha. - - - - - DevicePanel - - Dongle ID - Dongle ID - - - N/A - N/A - - - Serial - N° de série - - - Driver Camera - Caméra conducteur - - - PREVIEW - APERÇU - - - Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off) - Aperçu de la caméra orientée vers le conducteur pour assurer une bonne visibilité de la surveillance du conducteur. (véhicule doit être éteint) - - - Reset Calibration - Réinitialiser la calibration - - - RESET - RÉINITIALISER - - - Are you sure you want to reset calibration? - Êtes-vous sûr de vouloir réinitialiser la calibration ? - - - Reset - Réinitialiser - - - Review Training Guide - Revoir le guide de formation - - - REVIEW - REVOIR - - - Review the rules, features, and limitations of sunnypilot - Revoir les règles, fonctionnalités et limitations d'sunnypilot - - - Are you sure you want to review the training guide? - Êtes-vous sûr de vouloir revoir le guide de formation ? - - - Review - Revoir - - - Regulatory - Réglementaire - - - VIEW - VOIR - - - Change Language - Changer de langue - - - CHANGE - CHANGER - - - Select a language - Choisir une langue - - - Reboot - Redémarrer - - - Power Off - Éteindre - - - sunnypilot requires the device to be mounted within 4° left or right and within 5° up or 9° down. sunnypilot is continuously calibrating, resetting is rarely required. - sunnypilot nécessite que l'appareil soit monté à 4° à gauche ou à droite et à 5° vers le haut ou 9° vers le bas. sunnypilot se calibre en continu, la réinitialisation est rarement nécessaire. - - - Your device is pointed %1° %2 and %3° %4. - Votre appareil est orienté %1° %2 et %3° %4. - - - down - bas - - - up - haut - - - left - gauche - - - right - droite - - - Are you sure you want to reboot? - Êtes-vous sûr de vouloir redémarrer ? - - - Disengage to Reboot - Désengager pour redémarrer - - - Are you sure you want to power off? - Êtes-vous sûr de vouloir éteindre ? - - - Disengage to Power Off - Désengager pour éteindre - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - Associez votre appareil avec comma connect (connect.comma.ai) et profitez de l'offre comma prime. - - - Pair Device - Associer l'appareil - - - PAIR - ASSOCIER - - - Disengage to Reset Calibration - - - - Resetting calibration will restart openpilot if the car is powered on. - - - - - DevicePanelSP - - Driver Camera Preview - - - - Training Guide - - - - Regulatory - Réglementaire - - - Language - - - - Are you sure you want to review the training guide? - Êtes-vous sûr de vouloir revoir le guide de formation ? - - - Review - Revoir - - - Select a language - Choisir une langue - - - Reboot - Redémarrer - - - Power Off - Éteindre - - - Offroad Mode - - - - Are you sure you want to exit Always Offroad mode? - - - - Confirm - Confirmer - - - Are you sure you want to enter Always Offroad mode? - - - - Disengage to Enter Always Offroad Mode - - - - Exit Always Offroad - - - - Always Offroad - - - - Quiet Mode - - - - Reset Settings - - - - Are you sure you want to reset all sunnypilot settings to default? Once the settings are reset, there is no going back. - - - - Reset - Réinitialiser - - - The reset cannot be undone. You have been warned. - - - - - DriveStats - - Drives - - - - Hours - - - - ALL TIME - - - - PAST WEEK - - - - KM - - - - Miles - - - - - DriverViewWindow - - camera starting - démarrage de la caméra - - - - ExperimentalModeButton - - EXPERIMENTAL MODE ON - MODE EXPÉRIMENTAL ACTIVÉ - - - CHILL MODE ON - MODE DÉTENTE ACTIVÉ - - - - FirehosePanel - - 🔥 Firehose Mode 🔥 - - - - Firehose Mode: ACTIVE - - - - ACTIVE - - - - For maximum effectiveness, bring your device inside and connect to a good USB-C adapter and Wi-Fi weekly.<br><br>Firehose Mode can also work while you're driving if connected to a hotspot or unlimited SIM card.<br><br><br><b>Frequently Asked Questions</b><br><br><i>Does it matter how or where I drive?</i> Nope, just drive as you normally would.<br><br><i>Do all of my segments get pulled in Firehose Mode?</i> No, we selectively pull a subset of your segments.<br><br><i>What's a good USB-C adapter?</i> Any fast phone or laptop charger should be fine.<br><br><i>Does it matter which software I run?</i> Yes, only upstream sunnypilot (and particular forks) are able to be used for training. - - - - <b>%n segment(s)</b> of your driving is in the training dataset so far. - - - - - - - sunnypilot learns to drive by watching humans, like you, drive. - -Firehose Mode allows you to maximize your training data uploads to improve openpilot's driving models. More data means bigger models, which means better Experimental Mode. - - - - <span stylesheet='font-size: 60px; font-weight: bold; color: #e74c3c;'>INACTIVE</span>: connect to an unmetered network - - - - - HudRenderer - - km/h - km/h - - - mph - mi/h - - - MAX - MAX - - - - HyundaiSettings - - Off - - - - Dynamic - - - - Predictive - - - - Custom Longitudinal Tuning - - - - This feature can only be used with openpilot longitudinal control enabled. - - - - Enable "Always Offroad" in Device panel, or turn vehicle off to select an option. - - - - Off: Uses default tuning - - - - Dynamic: Adjusts acceleration limits based on current speed - - - - Predictive: Uses future trajectory data to anticipate needed adjustments - - - - Fine-tune your driving experience by adjusting acceleration smoothness with openpilot longitudinal control. - - - - - InputDialog - - Cancel - Annuler - - - Need at least %n character(s)! - - Besoin d'au moins %n caractère ! - Besoin d'au moins %n caractères ! - - - - - LaneChangeSettings - - Back - Retour - - - Auto Lane Change: Delay with Blind Spot - - - - Toggle to enable a delay timer for seamless lane changes when blind spot monitoring (BSM) detects a obstructing vehicle, ensuring safe maneuvering. - - - - - LateralPanel - - Modular Assistive Driving System (MADS) - - - - Enable the beloved MADS feature. Disable toggle to revert back to stock sunnypilot engagement/disengagement. - - - - Customize MADS - - - - Customize Lane Change - - - - Enables independent engagements of Automatic Lane Centering (ALC) and Adaptive Cruise Control (ACC). - - - - Start the vehicle to check vehicle compatibility. - - - - This platform supports all MADS settings. - - - - This platform supports limited MADS settings. - - - - - MadsSettings - - Toggle with Main Cruise - - - - Note: For vehicles without LFA/LKAS button, disabling this will prevent lateral control engagement. - - - - Unified Engagement Mode (UEM) - - - - Engage lateral and longitudinal control with cruise control engagement. - - - - Note: Once lateral control is engaged via UEM, it will remain engaged until it is manually disabled via the MADS button or car shut off. - - - - Remain Active - - - - Disengage - - - - Steering Mode on Brake Pedal - - - - Start the vehicle to check vehicle compatibility. - - - - This feature defaults to OFF, and does not allow selection due to vehicle limitations. - - - - This feature defaults to ON, and does not allow selection due to vehicle limitations. - - - - This platform only supports Disengage mode due to vehicle limitations. - - - - Remain Active: ALC will remain active when the brake pedal is pressed. - - - - Pause - - - - Pause: ALC will pause when the brake pedal is pressed. - - - - Disengage: ALC will disengage when the brake pedal is pressed. - - - - Choose how Automatic Lane Centering (ALC) behaves after the brake pedal is manually pressed in sunnypilot. - - - - - MaxTimeOffroad - - Max Time Offroad - - - - Device will automatically shutdown after set time once the engine is turned off.<br/>(30h is the default) - - - - Always On - - - - h - - - - m - - - - (default) - - - - - ModelsPanel - - Current Model - - - - SELECT - SÉLECTIONNER - - - No custom model selected! - - - - Driving - - - - Navigation - - - - Vision - - - - Policy - - - - Downloading %1 model [%2]... (%3%) - - - - %1 model [%2] %3 - - - - downloaded - - - - ready - - - - from cache - - - - %1 model [%2] download failed - - - - %1 model [%2] pending... - - - - Fetching models... - - - - Use Default - - - - Select a Model - - - - Default - - - - Model download has started in the background. - - - - We STRONGLY suggest you to reset calibration. - - - - Would you like to do that now? - - - - Reset Calibration - Réinitialiser la calibration - - - Driving Model Selector - - - - Warning: You are on a metered connection! - - - - Continue - Continuer - - - on Metered - - - - Cancel - Annuler - - - - MultiOptionDialog - - Select - Sélectionner - - - Cancel - Annuler - - - - Networking - - Advanced - Avancé - - - Enter password - Entrer le mot de passe - - - for "%1" - pour "%1" - - - Wrong password - Mot de passe incorrect - - - - NetworkingSP - - Scan - - - - Scanning... - - - - - NeuralNetworkLateralControl - - Neural Network Lateral Control (NNLC) - - - - NNLC is currently not available on this platform. - - - - Start the car to check car compatibility - - - - NNLC Not Loaded - - - - NNLC Loaded - - - - Match - - - - Exact - - - - Fuzzy - - - - Match: "Exact" is ideal, but "Fuzzy" is fine too. - - - - Formerly known as <b>"NNFF"</b>, this replaces the lateral <b>"torque"</b> controller, with one using a neural network trained on each car's (actually, each separate EPS firmware) driving data for increased controls accuracy. - - - - Reach out to the sunnypilot team in the following channel at the sunnypilot Discord server - - - - with feedback, or to provide log data for your car if your car is currently unsupported: - - - - if there are any issues: - - - - and donate logs to get NNLC loaded for your car: - - - - - OffroadAlert - - Device temperature too high. System cooling down before starting. Current internal component temperature: %1 - Température de l'appareil trop élevée. Le système doit refroidir avant de démarrer. Température actuelle de l'appareil : %1 - - - Immediately connect to the internet to check for updates. If you do not connect to the internet, sunnypilot won't engage in %1 - Connectez-vous immédiatement à internet pour vérifier les mises à jour. Si vous ne vous connectez pas à internet, sunnypilot ne s'engagera pas dans %1 - - - Connect to internet to check for updates. sunnypilot won't automatically start until it connects to internet to check for updates. - Connectez l'appareil à internet pour vérifier les mises à jour. sunnypilot ne démarrera pas automatiquement tant qu'il ne se connecte pas à internet pour vérifier les mises à jour. - - - Unable to download updates -%1 - Impossible de télécharger les mises à jour -%1 - - - Taking camera snapshots. System won't start until finished. - Capture de clichés photo. Le système ne démarrera pas tant qu'il n'est pas terminé. - - - An update to your device's operating system is downloading in the background. You will be prompted to update when it's ready to install. - Une mise à jour du système d'exploitation de votre appareil est en cours de téléchargement en arrière-plan. Vous serez invité à effectuer la mise à jour lorsqu'elle sera prête à être installée. - - - Device failed to register. It will not connect to or upload to comma.ai servers, and receives no support from comma.ai. If this is an official device, visit https://comma.ai/support. - L'appareil n'a pas réussi à s'enregistrer. Il ne se connectera pas aux serveurs de comma.ai, n'enverra rien et ne recevra aucune assistance de comma.ai. S'il s'agit d'un appareil officiel, visitez https://comma.ai/support. - - - NVMe drive not mounted. - Le disque NVMe n'est pas monté. - - - Unsupported NVMe drive detected. Device may draw significantly more power and overheat due to the unsupported NVMe. - Disque NVMe non supporté détecté. L'appareil peut consommer beaucoup plus d'énergie et surchauffer en raison du NVMe non supporté. - - - sunnypilot was unable to identify your car. Your car is either unsupported or its ECUs are not recognized. Please submit a pull request to add the firmware versions to the proper vehicle. Need help? Join discord.comma.ai. - sunnypilot n'a pas pu identifier votre voiture. Votre voiture n'est pas supportée ou ses ECUs ne sont pas reconnues. Veuillez soumettre un pull request pour ajouter les versions de firmware au véhicule approprié. Besoin d'aide ? Rejoignez discord.comma.ai. - - - sunnypilot detected a change in the device's mounting position. Ensure the device is fully seated in the mount and the mount is firmly secured to the windshield. - sunnypilot a détecté un changement dans la position de montage de l'appareil. Assurez-vous que l'appareil est totalement inséré dans le support et que le support est fermement fixé au pare-brise. - - - sunnypilot is now in Always Offroad mode. sunnypilot won't start until Always Offroad mode is disabled. Go to "Settings" -> "Device" to exit Always Offroad mode. - - - - - OffroadHome - - UPDATE - MISE À JOUR - - - ALERTS - ALERTES - - - ALERT - ALERTE - - - - OnroadAlerts - - sunnypilot Unavailable - sunnypilot indisponible - - - TAKE CONTROL IMMEDIATELY - REPRENEZ LE CONTRÔLE IMMÉDIATEMENT - - - Reboot Device - Redémarrer l'appareil - - - Waiting to start - En attente de démarrage - - - System Unresponsive - Système inopérant - - - - PairingPopup - - Pair your device to your comma account - Associez votre appareil à votre compte comma - - - Go to https://connect.comma.ai on your phone - Allez sur https://connect.comma.ai sur votre téléphone - - - Click "add new device" and scan the QR code on the right - Cliquez sur "ajouter un nouvel appareil" et scannez le code QR à droite - - - Bookmark connect.comma.ai to your home screen to use it like an app - Ajoutez connect.comma.ai à votre écran d'accueil pour l'utiliser comme une application - - - Please connect to Wi-Fi to complete initial pairing - Connectez-vous au Wi-Fi pour terminer l'appairage initial - - - - ParamControl - - Enable - Activer - - - Cancel - Annuler - - - - ParamControlSP - - Enable - Activer - - - Cancel - Annuler - - - - PlatformSelector - - Vehicle - - - - SEARCH - - - - Search your vehicle - - - - Enter model year (e.g., 2021) and model name (Toyota Corolla): - - - - SEARCHING - - - - REMOVE - SUPPRIMER - - - This setting will take effect immediately. - - - - This setting will take effect once the device enters offroad state. - - - - Vehicle Selector - - - - Confirm - Confirmer - - - Cancel - Annuler - - - No vehicles found for query: %1 - - - - Select a vehicle - - - - Unrecognized Vehicle - - - - Fingerprinted automatically - - - - Manually selected - - - - Not fingerprinted or manually selected - - - - Select vehicle to force fingerprint manually. - - - - Colors represent fingerprint status: - - - - - PrimeAdWidget - - Upgrade Now - Mettre à niveau - - - Become a comma prime member at connect.comma.ai - Devenez membre comma prime sur connect.comma.ai - - - PRIME FEATURES: - FONCTIONNALITÉS PRIME : - - - Remote access - Accès à distance - - - 24/7 LTE connectivity - Connexion LTE 24/7 - - - 1 year of drive storage - 1 an de stockage de trajets - - - Remote snapshots - Captures à distance - - - - PrimeUserWidget - - ✓ SUBSCRIBED - ✓ ABONNÉ - - - comma prime - comma prime - - - - QObject - - sunnypilot - sunnypilot - - - %n minute(s) ago - - il y a %n minute - il y a %n minutes - - - - %n hour(s) ago - - il y a %n heure - il y a %n heures - - - - %n day(s) ago - - il y a %n jour - il y a %n jours - - - - now - maintenant - - - - Reset - - Reset failed. Reboot to try again. - Réinitialisation échouée. Redémarrez pour réessayer. - - - Resetting device... -This may take up to a minute. - Réinitialisation de l'appareil... -Cela peut prendre jusqu'à une minute. - - - Are you sure you want to reset your device? - Êtes-vous sûr de vouloir réinitialiser votre appareil ? - - - System Reset - Réinitialisation du système - - - Cancel - Annuler - - - Reboot - Redémarrer - - - Confirm - Confirmer - - - Unable to mount data partition. Partition may be corrupted. Press confirm to erase and reset your device. - Impossible de monter la partition data. La partition peut être corrompue. Appuyez sur confirmer pour effacer et réinitialiser votre appareil. - - - System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot. - Réinitialisation système déclenchée. Appuyez sur confirmer pour effacer tout le contenu et les paramètres. Appuyez sur annuler pour reprendre le démarrage. - - - - SettingsWindow - - × - × - - - Device - Appareil - - - Network - Réseau - - - Toggles - Options - - - Software - Logiciel - - - Developer - Dév. - - - Firehose - - - - - SettingsWindowSP - - × - × - - - Device - Appareil - - - Network - Réseau - - - sunnylink - - - - Toggles - Options - - - Software - Logiciel - - - Trips - - - - Vehicle - - - - Developer - Dév. - - - Firehose - - - - Steering - - - - Models - - - - Cruise - - - - Visuals - - - - - Setup - - Something went wrong. Reboot the device. - Un problème est survenu. Redémarrez l'appareil. - - - Ensure the entered URL is valid, and the device’s internet connection is good. - Assurez-vous que l'URL saisie est valide et que la connexion internet de l'appareil est bonne. - - - No custom software found at this URL. - Aucun logiciel personnalisé trouvé à cette URL. - - - WARNING: Low Voltage - ATTENTION : Tension faible - - - Power your device in a car with a harness or proceed at your own risk. - Alimentez votre appareil dans une voiture avec un harness ou continuez à vos risques et périls. - - - Power off - Éteindre - - - Continue - Continuer - - - Getting Started - Commencer - - - Before we get on the road, let’s finish installation and cover some details. - Avant de prendre la route, terminons l'installation et passons en revue quelques détails. - - - Connect to Wi-Fi - Se connecter au Wi-Fi - - - Back - Retour - - - Enter URL - Entrer l'URL - - - for Custom Software - pour logiciel personnalisé - - - Continue without Wi-Fi - Continuer sans Wi-Fi - - - Waiting for internet - En attente d'internet - - - Downloading... - Téléchargement... - - - Download Failed - Échec du téléchargement - - - Reboot device - Redémarrer l'appareil - - - Start over - Recommencer - - - Select a language - Choisir une langue - - - Choose Software to Install - Choisir le logiciel à installer - - - sunnypilot - sunnypilot - - - Custom Software - Logiciel personnalisé - - - - SetupWidget - - Finish Setup - Terminer l'installation - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - Associez votre appareil avec comma connect (connect.comma.ai) et profitez de l'offre comma prime. - - - Pair device - Associer l'appareil - - - - Sidebar - - CONNECT - CONNECTER - - - OFFLINE - HORS LIGNE - - - ONLINE - EN LIGNE - - - ERROR - ERREUR - - - TEMP - TEMP - - - HIGH - HAUT - - - GOOD - BON - - - OK - OK - - - VEHICLE - VÉHICULE - - - NO - NON - - - PANDA - PANDA - - - -- - -- - - - Wi-Fi - Wi-Fi - - - ETH - ETH - - - 2G - 2G - - - 3G - 3G - - - LTE - LTE - - - 5G - 5G - - - - SidebarSP - - DISABLED - - - - OFFLINE - HORS LIGNE - - - REGIST... - - - - ONLINE - EN LIGNE - - - ERROR - ERREUR - - - SUNNYLINK - - - - - SoftwarePanel - - Updates are only downloaded while the car is off. - Les MàJ sont téléchargées uniquement si la voiture est éteinte. - - - Current Version - Version actuelle - - - Download - Télécharger - - - CHECK - VÉRIFIER - - - Install Update - Installer la mise à jour - - - INSTALL - INSTALLER - - - Target Branch - Branche cible - - - SELECT - SÉLECTIONNER - - - Select a branch - Sélectionner une branche - - - Uninstall %1 - Désinstaller %1 - - - UNINSTALL - DÉSINSTALLER - - - Are you sure you want to uninstall? - Êtes-vous sûr de vouloir désinstaller ? - - - Uninstall - Désinstaller - - - failed to check for update - échec de la vérification de la mise à jour - - - DOWNLOAD - TÉLÉCHARGER - - - update available - mise à jour disponible - - - never - jamais - - - up to date, last checked %1 - à jour, dernière vérification %1 - - - - SoftwarePanelSP - - Search Branch - - - - Enter search keywords, or leave blank to list all branches. - - - - No branches found for keywords: %1 - - - - Select a branch - Sélectionner une branche - - - - SshControl - - SSH Keys - Clés SSH - - - Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username other than your own. A comma employee will NEVER ask you to add their GitHub username. - Attention : Ceci accorde l'accès SSH à toutes les clés publiques de vos paramètres GitHub. N'entrez jamais un nom d'utilisateur GitHub autre que le vôtre. Un employé de comma ne vous demandera JAMAIS d'ajouter son nom d'utilisateur GitHub. - - - ADD - AJOUTER - - - Enter your GitHub username - Entrez votre nom d'utilisateur GitHub - - - LOADING - CHARGEMENT - - - REMOVE - SUPPRIMER - - - Username '%1' has no keys on GitHub - L'utilisateur '%1' n'a pas de clés sur GitHub - - - Request timed out - Délai de la demande dépassé - - - Username '%1' doesn't exist on GitHub - L'utilisateur '%1' n'existe pas sur GitHub - - - - SshToggle - - Enable SSH - Activer SSH - - - - SunnylinkPanel - - This is the master switch, it will allow you to cutoff any sunnylink requests should you want to do that. - - - - Enable sunnylink - - - - 🎉Welcome back! We're excited to see you've enabled sunnylink again! 🚀 - - - - 👋Not going to lie, it's sad to see you disabled sunnylink 😢, but we'll be here when you're ready to come back 🎉. - - - - Device ID - - - - N/A - N/A - - - Sponsor Status - - - - SPONSOR - - - - Become a sponsor of sunnypilot to get early access to sunnylink features when they become available. - - - - Pair GitHub Account - - - - PAIR - ASSOCIER - - - Pair your GitHub account to grant your device sponsor benefits, including API access on sunnylink. - - - - sunnylink Dongle ID not found. This may be due to weak internet connection or sunnylink registration issue. Please reboot and try again. - - - - Not Sponsor - - - - Paired - - - - Not Paired - - - - THANKS ♥ - - - - Backup Settings - - - - Are you sure you want to backup sunnypilot settings? - - - - Back Up - - - - Restore Settings - - - - Are you sure you want to restore the last backed up sunnypilot settings? - - - - Restore - - - - Backup in progress %1% - - - - Backup Failed - - - - Settings backup completed. - - - - Restore in progress %1% - - - - Restore Failed - - - - Unable to restore the settings, try again later. - - - - Settings restored. Confirm to restart the interface. - - - - - SunnylinkSponsorPopup - - Scan the QR code to login to your GitHub account - - - - Follow the prompts to complete the pairing process - - - - Re-enter the "sunnylink" panel to verify sponsorship status - - - - If sponsorship status was not updated, please contact a moderator on Discord at https://discord.gg/sunnypilot - - - - Scan the QR code to visit sunnyhaibin's GitHub Sponsors page - - - - Choose your sponsorship tier and confirm your support - - - - Join our community on Discord at https://discord.gg/sunnypilot and reach out to a moderator to confirm your sponsor status - - - - Pair your GitHub account - - - - Early Access: Become a sunnypilot Sponsor - - - - - TermsPage - - Decline - Refuser - - - Agree - Accepter - - - Welcome to sunnypilot - - - - You must accept the Terms and Conditions to use sunnypilot. Read the latest terms at <span style='color: #465BEA;'>https://comma.ai/terms</span> before continuing. - - - - - TogglesPanel - - Experimental Mode - Mode expérimental - - - Disengage on Accelerator Pedal - Désengager avec la pédale d'accélérateur - - - When enabled, pressing the accelerator pedal will disengage sunnypilot. - Lorsqu'il est activé, appuyer sur la pédale d'accélérateur désengagera sunnypilot. - - - Enable Lane Departure Warnings - Activer les avertissements de sortie de voie - - - Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h). - Recevez des alertes pour revenir dans la voie lorsque votre véhicule dérive au-delà d'une ligne de voie détectée sans clignotant activé en roulant à plus de 31 mph (50 km/h). - - - Record and Upload Driver Camera - Enregistrer et télécharger la caméra conducteur - - - Upload data from the driver facing camera and help improve the driver monitoring algorithm. - Publiez les données de la caméra orientée vers le conducteur et aidez à améliorer l'algorithme de surveillance du conducteur. - - - Use Metric System - Utiliser le système métrique - - - Display speed in km/h instead of mph. - Afficher la vitesse en km/h au lieu de mph. - - - Aggressive - Aggressif - - - Standard - Standard - - - Relaxed - Détendu - - - Driving Personality - Personnalité de conduite - - - sunnypilot defaults to driving in <b>chill mode</b>. Experimental mode enables <b>alpha-level features</b> that aren't ready for chill mode. Experimental features are listed below: - Par défaut, sunnypilot conduit en <b>mode détente</b>. Le mode expérimental permet d'activer des <b>fonctionnalités alpha</b> qui ne sont pas prêtes pour le mode détente. Les fonctionnalités expérimentales sont listées ci-dessous : - - - Let the driving model control the gas and brakes. sunnypilot will drive as it thinks a human would, including stopping for red lights and stop signs. Since the driving model decides the speed to drive, the set speed will only act as an upper bound. This is an alpha quality feature; mistakes should be expected. - Laissez le modèle de conduite contrôler l'accélérateur et les freins. sunnypilot conduira comme il pense qu'un humain le ferait, y compris s'arrêter aux feux rouges et aux panneaux stop. Comme le modèle de conduite décide de la vitesse à adopter, la vitesse définie ne servira que de limite supérieure. Cette fonctionnalité est de qualité alpha ; des erreurs sont à prévoir. - - - New Driving Visualization - Nouvelle visualisation de la conduite - - - Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control. - Le mode expérimental est actuellement indisponible pour cette voiture car le régulateur de vitesse adaptatif d'origine est utilisé pour le contrôle longitudinal. - - - An alpha version of sunnypilot longitudinal control can be tested, along with Experimental mode, on non-release branches. - Une version alpha du contrôle longitudinal sunnypilot peut être testée, avec le mode expérimental, sur des branches non publiées. - - - End-to-End Longitudinal Control - Contrôle longitudinal de bout en bout - - - Enable the sunnypilot longitudinal control (alpha) toggle to allow Experimental mode. - Activer le contrôle longitudinal d'sunnypilot (en alpha) pour autoriser le mode expérimental. - - - Standard is recommended. In aggressive mode, sunnypilot will follow lead cars closer and be more aggressive with the gas and brake. In relaxed mode sunnypilot will stay further away from lead cars. On supported cars, you can cycle through these personalities with your steering wheel distance button. - Le mode Standard est recommandé. En mode Agressif, sunnypilot suivra les véhicules de plus près et sera plus dynamique avec l'accélérateur et le frein. En mode Détendu, sunnypilot maintiendra une distance plus importante avec les véhicules qui précèdent. Sur les véhicules compatibles, vous pouvez alterner entre ces personnalités à l'aide du bouton de distance au volant. - - - The driving visualization will transition to the road-facing wide-angle camera at low speeds to better show some turns. The Experimental mode logo will also be shown in the top right corner. - La visualisation de la conduite passera sur la caméra grand angle dirigée vers la route à faible vitesse afin de mieux montrer certains virages. Le logo du mode expérimental s'affichera également dans le coin supérieur droit. - - - Always-On Driver Monitoring - Surveillance continue du conducteur - - - Enable driver monitoring even when sunnypilot is not engaged. - Activer la surveillance conducteur lorsque sunnypilot n'est pas actif. - - - Enable Dynamic Experimental Control - - - - Enable toggle to allow the model to determine when to use sunnypilot ACC or sunnypilot End to End Longitudinal. - - - - Enable sunnypilot - Activer sunnypilot - - - Use the sunnypilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature. - - - - Changing this setting will restart openpilot if the car is powered on. - - - - openpilot longitudinal control may come in a future update. - - - - - Updater - - Update Required - Mise à jour requise - - - An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. The download size is approximately 1GB. - Une mise à jour du système d'exploitation est requise. Connectez votre appareil au Wi-Fi pour une mise à jour plus rapide. La taille du téléchargement est d'environ 1 Go. - - - Connect to Wi-Fi - Se connecter au Wi-Fi - - - Install - Installer - - - Back - Retour - - - Loading... - Chargement... - - - Reboot - Redémarrer - - - Update failed - Échec de la mise à jour - - - - WiFiPromptWidget - - Open - - - - <span style='font-family: "Noto Color Emoji";'>🔥</span> Firehose Mode <span style='font-family: Noto Color Emoji;'>🔥</span> - - - - Maximize your training data uploads to improve openpilot's driving models. - - - - - WifiUI - - Scanning for networks... - Recherche de réseaux... - - - CONNECTING... - CONNEXION... - - - FORGET - OUBLIER - - - Forget Wi-Fi Network "%1"? - Oublier le réseau Wi-Fi "%1" ? - - - Forget - Oublier - - - diff --git a/selfdrive/ui/translations/main_ja.ts b/selfdrive/ui/translations/main_ja.ts deleted file mode 100644 index f85ee37689..0000000000 --- a/selfdrive/ui/translations/main_ja.ts +++ /dev/null @@ -1,2109 +0,0 @@ - - - - - AbstractAlert - - Close - 閉じる - - - Snooze Update - 更新の一時停止 - - - Reboot and Update - 再起動してアップデート - - - - AdvancedNetworking - - Back - 戻る - - - Enable Tethering - テザリング有効 - - - Tethering Password - テザリングパスワード - - - EDIT - 編集 - - - Enter new tethering password - 新しいテザリングパスワードを入力 - - - IP Address - IPアドレス - - - Enable Roaming - ローミング有効 - - - APN Setting - APN設定 - - - Enter APN - APNを入力 - - - leave blank for automatic configuration - 自動で設定するには空白のままにしてください - - - Cellular Metered - 従量制通信設定 - - - Hidden Network - ネットワーク非表示 - - - CONNECT - 接続 - - - Enter SSID - SSIDを入力 - - - Enter password - パスワードを入力 - - - for "%1" - [%1] - - - Prevent large data uploads when on a metered cellular connection - - - - default - - - - metered - - - - unmetered - - - - Wi-Fi Network Metered - - - - Prevent large data uploads when on a metered Wi-Fi connection - - - - - AutoLaneChangeTimer - - Auto Lane Change by Blinker - - - - Set a timer to delay the auto lane change operation when the blinker is used. No nudge on the steering wheel is required to auto lane change if a timer is set. Default is Nudge. -Please use caution when using this feature. Only use the blinker when traffic and road conditions permit. - - - - s - - - - Off - - - - Nudge - - - - Nudgeless - - - - - ConfirmationDialog - - Ok - OK - - - Cancel - キャンセル - - - - DeclinePage - - You must accept the Terms and Conditions in order to use sunnypilot. - sunnypilotを使用するためには利用規約に同意する必要があります - - - Back - 戻る - - - Decline, uninstall %1 - 同意しない(%1をアンインストール) - - - - DeveloperPanel - - Joystick Debug Mode - ジョイスティックデバッグモード - - - Longitudinal Maneuver Mode - アクセル制御マニューバー - - - Enable ADB - ADBを有効にする - - - ADB (Android Debug Bridge) allows connecting to your device over USB or over the network. See https://docs.comma.ai/how-to/connect-to-comma for more info. - ADB(Android Debug Bridge)により、USBまたはネットワーク経由でデバイスに接続できます。詳細は、https://docs.comma.ai/how-to/connect-to-comma を参照してください。 - - - Enable GitHub runner service - - - - Enables or disables the github runner service. - - - - Error Log - - - - VIEW - 確認 - - - View the error log for sunnypilot crashes. - - - - openpilot Longitudinal Control (Alpha) - - - - WARNING: openpilot longitudinal control is in alpha for this car and will disable Automatic Emergency Braking (AEB). - - - - On this car, sunnypilot defaults to the car's built-in ACC instead of openpilot's longitudinal control. Enable this to switch to openpilot longitudinal control. Enabling Experimental mode is recommended when enabling openpilot longitudinal control alpha. - - - - - DevicePanel - - Dongle ID - ドングルID - - - N/A - 該当なし - - - Serial - シリアル番号 - - - Driver Camera - 車内カメラ - - - PREVIEW - プレビュー - - - Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off) - 車内カメラでドライバー監視システムのカメラ画像を確認できます。(車両のパワーOFF時の機能です) - - - Reset Calibration - キャリブレーションリセット - - - RESET - リセット - - - Are you sure you want to reset calibration? - キャリブレーションをリセットしますか? - - - Review Training Guide - トレーニングガイドを見る - - - REVIEW - 確認 - - - Review the rules, features, and limitations of sunnypilot - sunnypilotのルール、機能、および制限を確認してください - - - Are you sure you want to review the training guide? - トレーニングガイドを始めてもよろしいですか? - - - Regulatory - 規約 - - - VIEW - 確認 - - - Change Language - 多言語対応 - - - CHANGE - 変更 - - - Select a language - 言語を選択 - - - Reboot - 再起動 - - - Power Off - パワーオフ - - - sunnypilot requires the device to be mounted within 4° left or right and within 5° up or 9° down. sunnypilot is continuously calibrating, resetting is rarely required. - sunnypilotの本体は左右4°以内、上5°下9°以内の角度で取付ける必要があります。常にキャリブレーションされておりリセットはほとんど必要ありません。 - - - Your device is pointed %1° %2 and %3° %4. - このデバイスは%2 %1°、%4 %3°の向きに設置されています。 - - - down - - - - up - - - - left - - - - right - - - - Are you sure you want to reboot? - 再起動してもよろしいですか? - - - Disengage to Reboot - 再起動するには車を一旦停止してください - - - Are you sure you want to power off? - パワーオフしてもよろしいですか? - - - Disengage to Power Off - パワーオフするには車を一旦停止してください - - - Reset - リセット - - - Review - 見る - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - デバイスをcommaコネクト(connect.comma.ai)でペアリングしてcommaプライムの特典を受け取ってください。 - - - Pair Device - デバイスのペアリング - - - PAIR - OK - - - Disengage to Reset Calibration - - - - Resetting calibration will restart openpilot if the car is powered on. - - - - - DevicePanelSP - - Driver Camera Preview - - - - Training Guide - - - - Regulatory - 規約 - - - Language - - - - Are you sure you want to review the training guide? - トレーニングガイドを始めてもよろしいですか? - - - Review - 見る - - - Select a language - 言語を選択 - - - Reboot - 再起動 - - - Power Off - パワーオフ - - - Offroad Mode - - - - Are you sure you want to exit Always Offroad mode? - - - - Confirm - 確認 - - - Are you sure you want to enter Always Offroad mode? - - - - Disengage to Enter Always Offroad Mode - - - - Exit Always Offroad - - - - Always Offroad - - - - Quiet Mode - - - - Reset Settings - - - - Are you sure you want to reset all sunnypilot settings to default? Once the settings are reset, there is no going back. - - - - Reset - リセット - - - The reset cannot be undone. You have been warned. - - - - - DriveStats - - Drives - - - - Hours - - - - ALL TIME - - - - PAST WEEK - - - - KM - - - - Miles - - - - - DriverViewWindow - - camera starting - カメラ起動中 - - - - ExperimentalModeButton - - EXPERIMENTAL MODE ON - EXPERIMENTALモード - - - CHILL MODE ON - CHILLモード - - - - FirehosePanel - - 🔥 Firehose Mode 🔥 - 🔥 Firehoseモード 🔥 - - - Firehose Mode: ACTIVE - - - - ACTIVE - - - - For maximum effectiveness, bring your device inside and connect to a good USB-C adapter and Wi-Fi weekly.<br><br>Firehose Mode can also work while you're driving if connected to a hotspot or unlimited SIM card.<br><br><br><b>Frequently Asked Questions</b><br><br><i>Does it matter how or where I drive?</i> Nope, just drive as you normally would.<br><br><i>Do all of my segments get pulled in Firehose Mode?</i> No, we selectively pull a subset of your segments.<br><br><i>What's a good USB-C adapter?</i> Any fast phone or laptop charger should be fine.<br><br><i>Does it matter which software I run?</i> Yes, only upstream sunnypilot (and particular forks) are able to be used for training. - - - - <b>%n segment(s)</b> of your driving is in the training dataset so far. - - - - - - sunnypilot learns to drive by watching humans, like you, drive. - -Firehose Mode allows you to maximize your training data uploads to improve openpilot's driving models. More data means bigger models, which means better Experimental Mode. - - - - <span stylesheet='font-size: 60px; font-weight: bold; color: #e74c3c;'>INACTIVE</span>: connect to an unmetered network - <span stylesheet='font-size: 60px; font-weight: bold; color: #e74c3c;'>動作停止</span>: 大容量のネットワークに接続してください - - - - HudRenderer - - km/h - km/h - - - mph - mph - - - MAX - 最大速度 - - - - HyundaiSettings - - Off - - - - Dynamic - - - - Predictive - - - - Custom Longitudinal Tuning - - - - This feature can only be used with openpilot longitudinal control enabled. - - - - Enable "Always Offroad" in Device panel, or turn vehicle off to select an option. - - - - Off: Uses default tuning - - - - Dynamic: Adjusts acceleration limits based on current speed - - - - Predictive: Uses future trajectory data to anticipate needed adjustments - - - - Fine-tune your driving experience by adjusting acceleration smoothness with openpilot longitudinal control. - - - - - InputDialog - - Cancel - キャンセル - - - Need at least %n character(s)! - - %n文字以上にして下さい! - - - - - LaneChangeSettings - - Back - 戻る - - - Auto Lane Change: Delay with Blind Spot - - - - Toggle to enable a delay timer for seamless lane changes when blind spot monitoring (BSM) detects a obstructing vehicle, ensuring safe maneuvering. - - - - - LateralPanel - - Modular Assistive Driving System (MADS) - - - - Enable the beloved MADS feature. Disable toggle to revert back to stock sunnypilot engagement/disengagement. - - - - Customize MADS - - - - Customize Lane Change - - - - Enables independent engagements of Automatic Lane Centering (ALC) and Adaptive Cruise Control (ACC). - - - - Start the vehicle to check vehicle compatibility. - - - - This platform supports all MADS settings. - - - - This platform supports limited MADS settings. - - - - - MadsSettings - - Toggle with Main Cruise - - - - Note: For vehicles without LFA/LKAS button, disabling this will prevent lateral control engagement. - - - - Unified Engagement Mode (UEM) - - - - Engage lateral and longitudinal control with cruise control engagement. - - - - Note: Once lateral control is engaged via UEM, it will remain engaged until it is manually disabled via the MADS button or car shut off. - - - - Remain Active - - - - Disengage - - - - Steering Mode on Brake Pedal - - - - Start the vehicle to check vehicle compatibility. - - - - This feature defaults to OFF, and does not allow selection due to vehicle limitations. - - - - This feature defaults to ON, and does not allow selection due to vehicle limitations. - - - - This platform only supports Disengage mode due to vehicle limitations. - - - - Remain Active: ALC will remain active when the brake pedal is pressed. - - - - Pause - - - - Pause: ALC will pause when the brake pedal is pressed. - - - - Disengage: ALC will disengage when the brake pedal is pressed. - - - - Choose how Automatic Lane Centering (ALC) behaves after the brake pedal is manually pressed in sunnypilot. - - - - - MaxTimeOffroad - - Max Time Offroad - - - - Device will automatically shutdown after set time once the engine is turned off.<br/>(30h is the default) - - - - Always On - - - - h - - - - m - - - - (default) - - - - - ModelsPanel - - Current Model - - - - SELECT - 選択 - - - No custom model selected! - - - - Driving - - - - Navigation - - - - Vision - - - - Policy - - - - Downloading %1 model [%2]... (%3%) - - - - %1 model [%2] %3 - - - - downloaded - - - - ready - - - - from cache - - - - %1 model [%2] download failed - - - - %1 model [%2] pending... - - - - Fetching models... - - - - Use Default - - - - Select a Model - - - - Default - - - - Model download has started in the background. - - - - We STRONGLY suggest you to reset calibration. - - - - Would you like to do that now? - - - - Reset Calibration - キャリブレーションリセット - - - Driving Model Selector - - - - Warning: You are on a metered connection! - - - - Continue - 続ける - - - on Metered - - - - Cancel - キャンセル - - - - MultiOptionDialog - - Select - 選択 - - - Cancel - キャンセル - - - - Networking - - Advanced - 詳細 - - - Enter password - パスワードを入力 - - - for "%1" - [%1] - - - Wrong password - パスワードが違います - - - - NetworkingSP - - Scan - - - - Scanning... - - - - - NeuralNetworkLateralControl - - Neural Network Lateral Control (NNLC) - - - - NNLC is currently not available on this platform. - - - - Start the car to check car compatibility - - - - NNLC Not Loaded - - - - NNLC Loaded - - - - Match - - - - Exact - - - - Fuzzy - - - - Match: "Exact" is ideal, but "Fuzzy" is fine too. - - - - Formerly known as <b>"NNFF"</b>, this replaces the lateral <b>"torque"</b> controller, with one using a neural network trained on each car's (actually, each separate EPS firmware) driving data for increased controls accuracy. - - - - Reach out to the sunnypilot team in the following channel at the sunnypilot Discord server - - - - with feedback, or to provide log data for your car if your car is currently unsupported: - - - - if there are any issues: - - - - and donate logs to get NNLC loaded for your car: - - - - - OffroadAlert - - Immediately connect to the internet to check for updates. If you do not connect to the internet, sunnypilot won't engage in %1 - インターネットへ接続してアップデートを確認してください。未接続のままではsunnypilotを使用できなくなります。あと[%1] - - - Connect to internet to check for updates. sunnypilot won't automatically start until it connects to internet to check for updates. - インターネットに接続してアップデートを確認してください。接続するまでsunnypilotは使用できません。 - - - Unable to download updates -%1 - 更新をダウンロードできませんでした -%1 - - - Taking camera snapshots. System won't start until finished. - スナップショットを撮影中です。完了するまでシステムは起動しません。 - - - An update to your device's operating system is downloading in the background. You will be prompted to update when it's ready to install. - オペレーティングシステムがバックグラウンドでダウンロードされています。インストールの準備が整うと更新を促されます。 - - - Device failed to register. It will not connect to or upload to comma.ai servers, and receives no support from comma.ai. If this is an official device, visit https://comma.ai/support. - 登録に失敗しました。このデバイスはcomma.aiのサーバーに接続したりデータをアップロードしたりできません。またcomma.aiのサポートも受けられません。公式デバイスである場合は https://comma.ai/support に問い合わせて下さい。 - - - NVMe drive not mounted. - SSDドライブ(NVMe)がマウントされていません。 - - - Unsupported NVMe drive detected. Device may draw significantly more power and overheat due to the unsupported NVMe. - 非サポートのSSDドライブ(NVMe)が検出されました。このドライブを使用するとデバイスが多大な電力を消費し過熱する可能性があります。 - - - sunnypilot was unable to identify your car. Your car is either unsupported or its ECUs are not recognized. Please submit a pull request to add the firmware versions to the proper vehicle. Need help? Join discord.comma.ai. - sunnypilotが車両を識別できませんでした。車が未対応またはECUが認識されていない可能性があります。該当車両のファームウェアバージョンを追加するためにプルリクエストしてください。サポートが必要な場合は discord.comma.ai に参加することができます。 - - - sunnypilot detected a change in the device's mounting position. Ensure the device is fully seated in the mount and the mount is firmly secured to the windshield. - sunnypilotがデバイスの取り付け位置にずれを検出しました。デバイスの固定とマウントがフロントガラスにしっかりと取り付けられていることを確認してください。 - - - Device temperature too high. System cooling down before starting. Current internal component temperature: %1 - デバイスの温度が高すぎるためシステム起動前の冷却中です。現在のデバイス内部温度: %1 - - - sunnypilot is now in Always Offroad mode. sunnypilot won't start until Always Offroad mode is disabled. Go to "Settings" -> "Device" to exit Always Offroad mode. - - - - - OffroadHome - - UPDATE - 更新 - - - ALERTS - 警告 - - - ALERT - 警告 - - - - OnroadAlerts - - sunnypilot Unavailable - sunnypilotは使用できません - - - TAKE CONTROL IMMEDIATELY - 直ちに車の運転に戻って下さい - - - Reboot Device - デバイスを再起動してください - - - Waiting to start - 始動を待機しています - - - System Unresponsive - システムが応答しません - - - - PairingPopup - - Pair your device to your comma account - デバイスとcommaアカウントを連携して下さい - - - Go to https://connect.comma.ai on your phone - スマートフォンで https://connect.comma.ai にアクセスしてください - - - Click "add new device" and scan the QR code on the right - 「add new device」を押して右側のQRコードをスキャンしてください - - - Bookmark connect.comma.ai to your home screen to use it like an app - connect.comma.aiのサイトをホーム画面に追加して、アプリのように使うことができます。 - - - Please connect to Wi-Fi to complete initial pairing - 最初にペアリングするため、Wi-Fiに接続してください - - - - ParamControl - - Cancel - キャンセル - - - Enable - 有効にする - - - - ParamControlSP - - Enable - 有効にする - - - Cancel - キャンセル - - - - PlatformSelector - - Vehicle - - - - SEARCH - - - - Search your vehicle - - - - Enter model year (e.g., 2021) and model name (Toyota Corolla): - - - - SEARCHING - - - - REMOVE - 削除 - - - This setting will take effect immediately. - - - - This setting will take effect once the device enters offroad state. - - - - Vehicle Selector - - - - Confirm - 確認 - - - Cancel - キャンセル - - - No vehicles found for query: %1 - - - - Select a vehicle - - - - Unrecognized Vehicle - - - - Fingerprinted automatically - - - - Manually selected - - - - Not fingerprinted or manually selected - - - - Select vehicle to force fingerprint manually. - - - - Colors represent fingerprint status: - - - - - PrimeAdWidget - - Upgrade Now - 今すぐアップグレード - - - Become a comma prime member at connect.comma.ai - connect.comma.ai からプライム会員に登録できます - - - PRIME FEATURES: - 特典: - - - Remote access - リモートアクセス - - - 24/7 LTE connectivity - 24時間365日のLTE接続 - - - 1 year of drive storage - 1年間分のドライブストレージ - - - Remote snapshots - リモートスナップショット - - - - PrimeUserWidget - - ✓ SUBSCRIBED - ✓ 有効です - - - comma prime - commaプライム - - - - QObject - - sunnypilot - sunnypilot - - - %n minute(s) ago - - %n分前 - - - - %n hour(s) ago - - %n時間前 - - - - %n day(s) ago - - %n日前 - - - - now - たった今 - - - - Reset - - Reset failed. Reboot to try again. - 初期化に失敗しました。再起動後に再試行してください。 - - - Are you sure you want to reset your device? - 初期化してもよろしいですか? - - - System Reset - システムを初期化 - - - Cancel - キャンセル - - - Reboot - 再起動 - - - Confirm - 確認 - - - Unable to mount data partition. Partition may be corrupted. Press confirm to erase and reset your device. - Dataパーティションをマウントできません。パーティションが破損している可能性があります。デバイスを消去してリセットしますので確認を押して下さい。 - - - Resetting device... -This may take up to a minute. - デバイスをリセットしています… -この処理には最大で1分ほどかかる場合があります。 - - - System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot. - システムリセットの準備が整いました。すべてのデータと設定を消去するには「確認」を押してください。「キャンセル」を押すとブートを再開します。 - - - - SettingsWindow - - × - × - - - Device - デバイス - - - Network - ネット - - - Toggles - 機能 - - - Software - ソフト - - - Developer - 開発 - - - Firehose - データ学習 - - - - SettingsWindowSP - - × - × - - - Device - デバイス - - - Network - ネット - - - sunnylink - - - - Toggles - 機能 - - - Software - ソフト - - - Trips - - - - Vehicle - - - - Developer - 開発 - - - Firehose - データ学習 - - - Steering - - - - Models - - - - Cruise - - - - Visuals - - - - - Setup - - WARNING: Low Voltage - 警告:電圧低下 - - - Power your device in a car with a harness or proceed at your own risk. - ハーネスを使って車でデバイスに電源を供給するか、自己責任でこのまま継続して下さい。 - - - Power off - 電源を切る - - - Continue - 続ける - - - Getting Started - はじめに - - - Before we get on the road, let’s finish installation and cover some details. - 出発する前に、インストールを完了させて少し詳細を確認しましょう。 - - - Connect to Wi-Fi - Wi-Fiに接続 - - - Back - 戻る - - - Continue without Wi-Fi - Wi-Fiに接続せずに続行 - - - Waiting for internet - インターネット接続を待機中 - - - Enter URL - URLの入力 - - - for Custom Software - カスタムソフトウェア - - - Downloading... - ダウンロード中... - - - Download Failed - ダウンロードに失敗しました - - - Ensure the entered URL is valid, and the device’s internet connection is good. - 入力されたURLが正しいかどうか、インターネットに正常に接続できているかを確認してください。 - - - Reboot device - デバイスを再起動 - - - Start over - やり直す - - - No custom software found at this URL. - このURLはカスタムソフトウェアではありません。 - - - Something went wrong. Reboot the device. - 何かの問題が発生しました。デバイスを再起動してください。 - - - Select a language - 言語を選択 - - - Choose Software to Install - インストールするソフトウェアを選択してください。 - - - sunnypilot - sunnypilot - - - Custom Software - カスタムソフトウェア - - - - SetupWidget - - Finish Setup - セットアップの完了 - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - デバイスをcommaコネクト(connect.comma.ai)でペアリングしてcommaプライムの特典を受け取ってください。 - - - Pair device - デバイスのペアリング - - - - Sidebar - - CONNECT - 接続 - - - OFFLINE - オフライン - - - ONLINE - オンライン - - - ERROR - エラー - - - TEMP - 温度 - - - HIGH - 高温 - - - GOOD - 最適 - - - OK - OK - - - VEHICLE - 車両 - - - NO - NO - - - PANDA - PANDA - - - -- - -- - - - Wi-Fi - Wi-Fi - - - ETH - ETH - - - 2G - 2G - - - 3G - 3G - - - LTE - LTE - - - 5G - 5G - - - - SidebarSP - - DISABLED - - - - OFFLINE - オフライン - - - REGIST... - - - - ONLINE - オンライン - - - ERROR - エラー - - - SUNNYLINK - - - - - SoftwarePanel - - Updates are only downloaded while the car is off. - 車の電源がオフの間のみアップデートがダウンロードできます。 - - - Current Version - 現在のバージョン - - - Download - ダウンロード - - - Install Update - アップデート - - - INSTALL - インストール - - - Target Branch - 対象のブランチ - - - SELECT - 選択 - - - Select a branch - ブランチを選択 - - - UNINSTALL - 実行 - - - Uninstall %1 - %1をアンインストール - - - Are you sure you want to uninstall? - アンインストールしてもよろしいですか? - - - CHECK - 確認 - - - Uninstall - アンインストール - - - failed to check for update - アップデートの確認に失敗しました。 - - - up to date, last checked %1 - 最新の状態です。最終確認日時:%1 - - - DOWNLOAD - ダウンロード - - - update available - アップデートが利用可能です - - - never - 無効 - - - - SoftwarePanelSP - - Search Branch - - - - Enter search keywords, or leave blank to list all branches. - - - - No branches found for keywords: %1 - - - - Select a branch - ブランチを選択 - - - - SshControl - - SSH Keys - SSH 鍵 - - - Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username other than your own. A comma employee will NEVER ask you to add their GitHub username. - 警告: これは、GitHub の設定にあるすべての公開鍵への SSH アクセスを許可するものです。自分以外の GitHub のユーザー名を入力しないでください。commaのスタッフが GitHub のユーザー名を追加するようお願いすることはありません。 - - - ADD - 追加 - - - Enter your GitHub username - GitHub のユーザー名を入力してください - - - LOADING - 読み込み中 - - - REMOVE - 削除 - - - Username '%1' has no keys on GitHub - ユーザー名“%1”は GitHub に公開鍵がありません - - - Request timed out - リクエストタイムアウト - - - Username '%1' doesn't exist on GitHub - ユーザー名”%1”は GitHub に存在しません - - - - SshToggle - - Enable SSH - SSHの有効化 - - - - SunnylinkPanel - - This is the master switch, it will allow you to cutoff any sunnylink requests should you want to do that. - - - - Enable sunnylink - - - - 🎉Welcome back! We're excited to see you've enabled sunnylink again! 🚀 - - - - 👋Not going to lie, it's sad to see you disabled sunnylink 😢, but we'll be here when you're ready to come back 🎉. - - - - Device ID - - - - N/A - 該当なし - - - Sponsor Status - - - - SPONSOR - - - - Become a sponsor of sunnypilot to get early access to sunnylink features when they become available. - - - - Pair GitHub Account - - - - PAIR - OK - - - Pair your GitHub account to grant your device sponsor benefits, including API access on sunnylink. - - - - sunnylink Dongle ID not found. This may be due to weak internet connection or sunnylink registration issue. Please reboot and try again. - - - - Not Sponsor - - - - Paired - - - - Not Paired - - - - THANKS ♥ - - - - Backup Settings - - - - Are you sure you want to backup sunnypilot settings? - - - - Back Up - - - - Restore Settings - - - - Are you sure you want to restore the last backed up sunnypilot settings? - - - - Restore - - - - Backup in progress %1% - - - - Backup Failed - - - - Settings backup completed. - - - - Restore in progress %1% - - - - Restore Failed - - - - Unable to restore the settings, try again later. - - - - Settings restored. Confirm to restart the interface. - - - - - SunnylinkSponsorPopup - - Scan the QR code to login to your GitHub account - - - - Follow the prompts to complete the pairing process - - - - Re-enter the "sunnylink" panel to verify sponsorship status - - - - If sponsorship status was not updated, please contact a moderator on Discord at https://discord.gg/sunnypilot - - - - Scan the QR code to visit sunnyhaibin's GitHub Sponsors page - - - - Choose your sponsorship tier and confirm your support - - - - Join our community on Discord at https://discord.gg/sunnypilot and reach out to a moderator to confirm your sponsor status - - - - Pair your GitHub account - - - - Early Access: Become a sunnypilot Sponsor - - - - - TermsPage - - Decline - 拒否 - - - Agree - 同意 - - - Welcome to sunnypilot - - - - You must accept the Terms and Conditions to use sunnypilot. Read the latest terms at <span style='color: #465BEA;'>https://comma.ai/terms</span> before continuing. - - - - - TogglesPanel - - Enable Lane Departure Warnings - 車線逸脱警報機能の有効化 - - - Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h). - 時速31マイル(50km)以上のスピードで走行中、ウインカーを作動させずに検出したレーン上に車両が触れた場合、手動で車線内に戻るように警告を行います。 - - - Use Metric System - メートル法の使用 - - - Display speed in km/h instead of mph. - 速度は mph ではなく km/h で表示されます。 - - - Record and Upload Driver Camera - 車内カメラの録画とアップロード - - - Upload data from the driver facing camera and help improve the driver monitoring algorithm. - 車内カメラの映像をアップロードし、ドライバー監視システムのアルゴリズムの向上に役立てます。 - - - Disengage on Accelerator Pedal - アクセルを踏むと運転サポートを中断 - - - When enabled, pressing the accelerator pedal will disengage sunnypilot. - この機能を有効化すると、sunnypilotを利用中にアクセルを踏むとsunnypilotによる運転サポートを中断します。 - - - Experimental Mode - Experimentalモード - - - sunnypilot defaults to driving in <b>chill mode</b>. Experimental mode enables <b>alpha-level features</b> that aren't ready for chill mode. Experimental features are listed below: - sunnypilotは標準ではゆっくりとくつろげる運転を提供します。このExperimental(実験)モードを有効にすると、以下のアグレッシブな開発中の機能を利用する事ができます。 - - - Let the driving model control the gas and brakes. sunnypilot will drive as it thinks a human would, including stopping for red lights and stop signs. Since the driving model decides the speed to drive, the set speed will only act as an upper bound. This is an alpha quality feature; mistakes should be expected. - sunnypilotにアクセルとブレーキを任せます。sunnypilotは赤信号や一時停止サインでの停止を含み、人間と同じように考えて運転を行います。sunnypilotが運転速度を決定するため、あなたが設定する速度は上限速度になります。この機能は実験段階のため、sunnypilotの運転ミスに常に備えて注意してください。 - - - New Driving Visualization - 新しい運転画面 - - - Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control. - 車両の標準ACC(アダプティブ・クルーズ・コントロール)がアクセル制御に使用されているため、現在Experimentalモードは利用できません。 - - - Aggressive - アグレッシブ - - - Standard - 標準 - - - Relaxed - リラックス - - - Driving Personality - 運転傾向 - - - End-to-End Longitudinal Control - End-to-Endアクセル制御 - - - An alpha version of sunnypilot longitudinal control can be tested, along with Experimental mode, on non-release branches. - sunnypilotのアルファ版アクセル制御は、Experimentalモードと共に非リリースのブランチでテストすることができます。 - - - Enable the sunnypilot longitudinal control (alpha) toggle to allow Experimental mode. - sunnypilotのアクセル制御機能(アルファ)を有効にして、Experimentalモードを許可してください。 - - - Standard is recommended. In aggressive mode, sunnypilot will follow lead cars closer and be more aggressive with the gas and brake. In relaxed mode sunnypilot will stay further away from lead cars. On supported cars, you can cycle through these personalities with your steering wheel distance button. - 標準モードが推奨されます。アグレッシブモードではsunnypilotは先行車に近づいて追従し、アクセルとブレーキがより強気になります。リラックスモードではsunnypilotは先行車から距離を取って走行します。サポートされている車両ではステアリングホイールの距離ボタンでこれらのモードを切り替えることができます。 - - - The driving visualization will transition to the road-facing wide-angle camera at low speeds to better show some turns. The Experimental mode logo will also be shown in the top right corner. - 運転時の画面効果として、低速時にカーブをより良く表示するために道路用の広角カメラに切り替わります。またExperimentalモードのロゴが右上隅に表示されます。 - - - Always-On Driver Monitoring - 運転者の常時モニタリング - - - Enable driver monitoring even when sunnypilot is not engaged. - sunnypilotが作動していない場合でも運転者モニタリングを有効にする。 - - - Enable Dynamic Experimental Control - - - - Enable toggle to allow the model to determine when to use sunnypilot ACC or sunnypilot End to End Longitudinal. - - - - Enable sunnypilot - sunnypilot を有効化 - - - Use the sunnypilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature. - - - - Changing this setting will restart openpilot if the car is powered on. - - - - openpilot longitudinal control may come in a future update. - - - - - Updater - - Update Required - アップデートが必要です - - - An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. The download size is approximately 1GB. - OSのアップデートが必要です。Wi-Fiに接続してアップデートする事をお勧めします。ダウンロードサイズは約1GBです。 - - - Connect to Wi-Fi - Wi-Fiに接続 - - - Install - インストール - - - Back - 戻る - - - Loading... - 読み込み中... - - - Reboot - 再起動 - - - Update failed - 更新失敗 - - - - WiFiPromptWidget - - Open - 開く - - - <span style='font-family: "Noto Color Emoji";'>🔥</span> Firehose Mode <span style='font-family: Noto Color Emoji;'>🔥</span> - <span style='font-family: "Noto Color Emoji";'>🔥</span> Firehoseモード <span style='font-family: Noto Color Emoji;'>🔥</span> - - - Maximize your training data uploads to improve openpilot's driving models. - - - - - WifiUI - - Scanning for networks... - ネットワークをスキャン中... - - - CONNECTING... - 接続中... - - - FORGET - 削除 - - - Forget Wi-Fi Network "%1"? - Wi-Fiネットワーク%1を削除してもよろしいですか? - - - Forget - 削除 - - - diff --git a/selfdrive/ui/translations/main_ko.ts b/selfdrive/ui/translations/main_ko.ts deleted file mode 100644 index 89f30ea545..0000000000 --- a/selfdrive/ui/translations/main_ko.ts +++ /dev/null @@ -1,2109 +0,0 @@ - - - - - AbstractAlert - - Close - 닫기 - - - Snooze Update - 업데이트 일시 중지 - - - Reboot and Update - 업데이트 및 재부팅 - - - - AdvancedNetworking - - Back - 뒤로 - - - Enable Tethering - 테더링 사용 - - - Tethering Password - 테더링 비밀번호 - - - EDIT - 편집 - - - Enter new tethering password - 새 테더링 비밀번호를 입력하세요 - - - IP Address - IP 주소 - - - Enable Roaming - 로밍 사용 - - - APN Setting - APN 설정 - - - Enter APN - APN 입력 - - - leave blank for automatic configuration - 자동 설정하려면 빈 칸으로 두세요 - - - Cellular Metered - 데이터 요금제 - - - Hidden Network - 숨겨진 네트워크 - - - CONNECT - 연결됨 - - - Enter SSID - SSID 입력 - - - Enter password - 비밀번호를 입력하세요 - - - for "%1" - "%1"에 접속하려면 비밀번호가 필요합니다 - - - Prevent large data uploads when on a metered cellular connection - - - - default - - - - metered - - - - unmetered - - - - Wi-Fi Network Metered - - - - Prevent large data uploads when on a metered Wi-Fi connection - - - - - AutoLaneChangeTimer - - Auto Lane Change by Blinker - - - - Set a timer to delay the auto lane change operation when the blinker is used. No nudge on the steering wheel is required to auto lane change if a timer is set. Default is Nudge. -Please use caution when using this feature. Only use the blinker when traffic and road conditions permit. - - - - s - - - - Off - - - - Nudge - - - - Nudgeless - - - - - ConfirmationDialog - - Ok - 확인 - - - Cancel - 취소 - - - - DeclinePage - - You must accept the Terms and Conditions in order to use sunnypilot. - sunnypilot을 사용하려면 이용약관에 동의해야 합니다. - - - Back - 뒤로 - - - Decline, uninstall %1 - 거절, %1 제거 - - - - DeveloperPanel - - Joystick Debug Mode - 조이스틱 디버그 모드 - - - Longitudinal Maneuver Mode - 롱컨 제어 모드 - - - Enable ADB - ADB 사용 - - - ADB (Android Debug Bridge) allows connecting to your device over USB or over the network. See https://docs.comma.ai/how-to/connect-to-comma for more info. - ADB (안드로이드 디버그 브릿지) USB 또는 네트워크를 통해 장치에 연결할 수 있습니다. 자세한 내용은 https://docs.comma.ai/how-to/connect-to-comma를 참조하세요. - - - Enable GitHub runner service - - - - Enables or disables the github runner service. - - - - Error Log - - - - VIEW - 보기 - - - View the error log for sunnypilot crashes. - - - - openpilot Longitudinal Control (Alpha) - - - - WARNING: openpilot longitudinal control is in alpha for this car and will disable Automatic Emergency Braking (AEB). - - - - On this car, sunnypilot defaults to the car's built-in ACC instead of openpilot's longitudinal control. Enable this to switch to openpilot longitudinal control. Enabling Experimental mode is recommended when enabling openpilot longitudinal control alpha. - - - - - DevicePanel - - Dongle ID - 동글 ID - - - N/A - N/A - - - Serial - 시리얼 - - - Driver Camera - 운전자 카메라 - - - PREVIEW - 미리보기 - - - Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off) - 운전자 모니터링이 잘 되는지 확인하기 위해 후면 카메라를 미리 봅니다. (차량 시동이 꺼져 있어야 합니다) - - - Reset Calibration - 캘리브레이션 - - - RESET - 초기화 - - - Are you sure you want to reset calibration? - 캘리브레이션을 초기화하시겠습니까? - - - Review Training Guide - 트레이닝 가이드 - - - REVIEW - 다시보기 - - - Review the rules, features, and limitations of sunnypilot - sunnypilot의 규칙, 기능 및 제한 다시 확인 - - - Are you sure you want to review the training guide? - 트레이닝 가이드를 다시 확인하시겠습니까? - - - Regulatory - 규제 - - - VIEW - 보기 - - - Change Language - 언어 변경 - - - CHANGE - 변경 - - - Select a language - 언어를 선택하세요 - - - Reboot - 재부팅 - - - Power Off - 전원 끄기 - - - sunnypilot requires the device to be mounted within 4° left or right and within 5° up or 9° down. sunnypilot is continuously calibrating, resetting is rarely required. - sunnypilot 장치는 좌우 4°, 위로 5°, 아래로 9° 이내 각도로 장착되어야 합니다. sunnypilot은 지속적으로 자동 보정되며 재설정은 거의 필요하지 않습니다. - - - Your device is pointed %1° %2 and %3° %4. - 사용자의 장치는 %2 %1° 및 %4 %3° 의 방향으로 장착되어 있습니다. - - - down - 아래로 - - - up - 위로 - - - left - 좌측으로 - - - right - 우측으로 - - - Are you sure you want to reboot? - 재부팅하시겠습니까? - - - Disengage to Reboot - 재부팅하려면 연결을 해제하세요 - - - Are you sure you want to power off? - 전원을 끄시겠습니까? - - - Disengage to Power Off - 전원을 끄려면 연결을 해제하세요 - - - Reset - 초기화 - - - Review - 다시보기 - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - 장치를 comma connect (connect.comma.ai)에서 동기화하고 comma prime 무료 이용권을 사용하세요. - - - Pair Device - 장치 동기화 - - - PAIR - 동기화 - - - Disengage to Reset Calibration - - - - Resetting calibration will restart openpilot if the car is powered on. - - - - - DevicePanelSP - - Driver Camera Preview - - - - Training Guide - - - - Regulatory - 규제 - - - Language - - - - Are you sure you want to review the training guide? - 트레이닝 가이드를 다시 확인하시겠습니까? - - - Review - 다시보기 - - - Select a language - 언어를 선택하세요 - - - Reboot - 재부팅 - - - Power Off - 전원 끄기 - - - Offroad Mode - - - - Are you sure you want to exit Always Offroad mode? - - - - Confirm - 확인 - - - Are you sure you want to enter Always Offroad mode? - - - - Disengage to Enter Always Offroad Mode - - - - Exit Always Offroad - - - - Always Offroad - - - - Quiet Mode - - - - Reset Settings - - - - Are you sure you want to reset all sunnypilot settings to default? Once the settings are reset, there is no going back. - - - - Reset - 초기화 - - - The reset cannot be undone. You have been warned. - - - - - DriveStats - - Drives - - - - Hours - - - - ALL TIME - - - - PAST WEEK - - - - KM - - - - Miles - - - - - DriverViewWindow - - camera starting - 카메라 시작 중 - - - - ExperimentalModeButton - - EXPERIMENTAL MODE ON - 실험 모드 사용 - - - CHILL MODE ON - 안정 모드 사용 - - - - FirehosePanel - - 🔥 Firehose Mode 🔥 - 🔥 파이어호스 모드 🔥 - - - Firehose Mode: ACTIVE - 파이어호스 모드: 활성화 - - - ACTIVE - 활성화 - - - For maximum effectiveness, bring your device inside and connect to a good USB-C adapter and Wi-Fi weekly.<br><br>Firehose Mode can also work while you're driving if connected to a hotspot or unlimited SIM card.<br><br><br><b>Frequently Asked Questions</b><br><br><i>Does it matter how or where I drive?</i> Nope, just drive as you normally would.<br><br><i>Do all of my segments get pulled in Firehose Mode?</i> No, we selectively pull a subset of your segments.<br><br><i>What's a good USB-C adapter?</i> Any fast phone or laptop charger should be fine.<br><br><i>Does it matter which software I run?</i> Yes, only upstream sunnypilot (and particular forks) are able to be used for training. - 최대한의 효과를 얻으려면 매주 장치를 실내로 가져와 좋은 USB-C 케이블에 연결하고 Wi-Fi에 연결하세요.<br><br>파이어호스 모드는 핫스팟 또는 무제한 SIM 카드에 연결된 경우에는 운전 중에도 작동할 수 있습니다.<br><br><br><b>자주 묻는 질문</b><br><br><i>운전 방법이나 장소가 중요한가요?</i> 아니요, 평소처럼 운전하시면 됩니다.<br><br><i>파이어호스 모드에서 제 모든 구간을 가져오나요?.<br><br><i> 아니요, 저희는 여러분의 구간 중 일부를 선별적으로 가져옵니다.<br><br><i>좋은 USB-C 케이블은 무엇인가요?</i> 휴대폰이나 노트북 고속 충전기가 있으면 됩니다.<br><br><i>어떤 소프트웨어를 실행하는지가 중요한가요?</i> 예, 오직 공식 sunnypilot의 특정 포크만 트레이닝에 사용할 수 있습니다. - - - <b>%n segment(s)</b> of your driving is in the training dataset so far. - - - - - - sunnypilot learns to drive by watching humans, like you, drive. - -Firehose Mode allows you to maximize your training data uploads to improve openpilot's driving models. More data means bigger models, which means better Experimental Mode. - - - - <span stylesheet='font-size: 60px; font-weight: bold; color: #e74c3c;'>INACTIVE</span>: connect to an unmetered network - - - - - HudRenderer - - km/h - km/h - - - mph - mph - - - MAX - MAX - - - - HyundaiSettings - - Off - - - - Dynamic - - - - Predictive - - - - Custom Longitudinal Tuning - - - - This feature can only be used with openpilot longitudinal control enabled. - - - - Enable "Always Offroad" in Device panel, or turn vehicle off to select an option. - - - - Off: Uses default tuning - - - - Dynamic: Adjusts acceleration limits based on current speed - - - - Predictive: Uses future trajectory data to anticipate needed adjustments - - - - Fine-tune your driving experience by adjusting acceleration smoothness with openpilot longitudinal control. - - - - - InputDialog - - Cancel - 취소 - - - Need at least %n character(s)! - - 최소 %n자 이상이어야 합니다! - - - - - LaneChangeSettings - - Back - 뒤로 - - - Auto Lane Change: Delay with Blind Spot - - - - Toggle to enable a delay timer for seamless lane changes when blind spot monitoring (BSM) detects a obstructing vehicle, ensuring safe maneuvering. - - - - - LateralPanel - - Modular Assistive Driving System (MADS) - - - - Enable the beloved MADS feature. Disable toggle to revert back to stock sunnypilot engagement/disengagement. - - - - Customize MADS - - - - Customize Lane Change - - - - Enables independent engagements of Automatic Lane Centering (ALC) and Adaptive Cruise Control (ACC). - - - - Start the vehicle to check vehicle compatibility. - - - - This platform supports all MADS settings. - - - - This platform supports limited MADS settings. - - - - - MadsSettings - - Toggle with Main Cruise - - - - Note: For vehicles without LFA/LKAS button, disabling this will prevent lateral control engagement. - - - - Unified Engagement Mode (UEM) - - - - Engage lateral and longitudinal control with cruise control engagement. - - - - Note: Once lateral control is engaged via UEM, it will remain engaged until it is manually disabled via the MADS button or car shut off. - - - - Remain Active - - - - Disengage - - - - Steering Mode on Brake Pedal - - - - Start the vehicle to check vehicle compatibility. - - - - This feature defaults to OFF, and does not allow selection due to vehicle limitations. - - - - This feature defaults to ON, and does not allow selection due to vehicle limitations. - - - - This platform only supports Disengage mode due to vehicle limitations. - - - - Remain Active: ALC will remain active when the brake pedal is pressed. - - - - Pause - - - - Pause: ALC will pause when the brake pedal is pressed. - - - - Disengage: ALC will disengage when the brake pedal is pressed. - - - - Choose how Automatic Lane Centering (ALC) behaves after the brake pedal is manually pressed in sunnypilot. - - - - - MaxTimeOffroad - - Max Time Offroad - - - - Device will automatically shutdown after set time once the engine is turned off.<br/>(30h is the default) - - - - Always On - - - - h - - - - m - - - - (default) - - - - - ModelsPanel - - Current Model - - - - SELECT - 선택 - - - No custom model selected! - - - - Driving - - - - Navigation - - - - Vision - - - - Policy - - - - Downloading %1 model [%2]... (%3%) - - - - %1 model [%2] %3 - - - - downloaded - - - - ready - - - - from cache - - - - %1 model [%2] download failed - - - - %1 model [%2] pending... - - - - Fetching models... - - - - Use Default - - - - Select a Model - - - - Default - - - - Model download has started in the background. - - - - We STRONGLY suggest you to reset calibration. - - - - Would you like to do that now? - - - - Reset Calibration - 캘리브레이션 - - - Driving Model Selector - - - - Warning: You are on a metered connection! - - - - Continue - 계속 - - - on Metered - - - - Cancel - 취소 - - - - MultiOptionDialog - - Select - 선택 - - - Cancel - 취소 - - - - Networking - - Advanced - 고급 설정 - - - Enter password - 비밀번호를 입력하세요 - - - for "%1" - "%1"에 접속하려면 비밀번호가 필요합니다 - - - Wrong password - 비밀번호가 틀렸습니다 - - - - NetworkingSP - - Scan - - - - Scanning... - - - - - NeuralNetworkLateralControl - - Neural Network Lateral Control (NNLC) - - - - NNLC is currently not available on this platform. - - - - Start the car to check car compatibility - - - - NNLC Not Loaded - - - - NNLC Loaded - - - - Match - - - - Exact - - - - Fuzzy - - - - Match: "Exact" is ideal, but "Fuzzy" is fine too. - - - - Formerly known as <b>"NNFF"</b>, this replaces the lateral <b>"torque"</b> controller, with one using a neural network trained on each car's (actually, each separate EPS firmware) driving data for increased controls accuracy. - - - - Reach out to the sunnypilot team in the following channel at the sunnypilot Discord server - - - - with feedback, or to provide log data for your car if your car is currently unsupported: - - - - if there are any issues: - - - - and donate logs to get NNLC loaded for your car: - - - - - OffroadAlert - - Immediately connect to the internet to check for updates. If you do not connect to the internet, sunnypilot won't engage in %1 - 즉시 인터넷에 연결하여 업데이트를 확인하세요. 인터넷에 연결되어 있지 않으면 %1 이후에는 sunnypilot이 활성화되지 않습니다. - - - Connect to internet to check for updates. sunnypilot won't automatically start until it connects to internet to check for updates. - 업데이트를 확인하려면 인터넷에 연결하세요. sunnypilot은 업데이트를 확인하기 위해 인터넷에 연결할 때까지 자동으로 시작되지 않습니다. - - - Unable to download updates -%1 - 업데이트를 다운로드할 수 없습니다 -%1 - - - Taking camera snapshots. System won't start until finished. - 카메라 스냅샷 찍기가 완료될 때까지 시스템이 시작되지 않습니다. - - - An update to your device's operating system is downloading in the background. You will be prompted to update when it's ready to install. - 백그라운드에서 운영 체제에 대한 업데이트가 다운로드되고 있습니다. 설치가 준비되면 업데이트 메시지가 표시됩니다. - - - Device failed to register. It will not connect to or upload to comma.ai servers, and receives no support from comma.ai. If this is an official device, visit https://comma.ai/support. - 장치를 등록하지 못했습니다. comma.ai 서버에 연결하거나 데이터를 업로드하지 않으며 comma.ai에서 지원을 받지 않습니다. 공식 장치인 경우 https://comma.ai/support 에 방문하여 문의하세요. - - - NVMe drive not mounted. - NVMe 드라이브가 마운트되지 않았습니다. - - - Unsupported NVMe drive detected. Device may draw significantly more power and overheat due to the unsupported NVMe. - 지원되지 않는 NVMe 드라이브가 감지되었습니다. 지원되지 않는 NVMe 드라이브는 많은 전력을 소비하고 장치를 과열시킬 수 있습니다. - - - sunnypilot was unable to identify your car. Your car is either unsupported or its ECUs are not recognized. Please submit a pull request to add the firmware versions to the proper vehicle. Need help? Join discord.comma.ai. - sunnypilot이 차량을 식별할 수 없습니다. 지원되지 않는 차량이거나 ECU가 인식되지 않습니다. 해당 차량에 맞는 펌웨어 버전을 추가하려면 PR을 제출하세요. 도움이 필요하시면 discord.comma.ai에 가입하세요. - - - sunnypilot detected a change in the device's mounting position. Ensure the device is fully seated in the mount and the mount is firmly secured to the windshield. - sunnypilot 장치의 장착 위치가 변경되었습니다. 장치가 마운트에 완전히 장착되고 마운트가 앞유리에 단단히 고정되었는지 확인하세요. - - - Device temperature too high. System cooling down before starting. Current internal component temperature: %1 - 장치의 온도가 너무 높습니다. 시작 전에 온도를 낮춰주세요. 현재 내부 구성 요소 온도: %1 - - - sunnypilot is now in Always Offroad mode. sunnypilot won't start until Always Offroad mode is disabled. Go to "Settings" -> "Device" to exit Always Offroad mode. - - - - - OffroadHome - - UPDATE - 업데이트 - - - ALERTS - 알림 - - - ALERT - 알림 - - - - OnroadAlerts - - sunnypilot Unavailable - 오픈파일럿을 사용할수없습니다 - - - TAKE CONTROL IMMEDIATELY - 핸들을 잡아주세요 - - - Reboot Device - 장치를 재부팅하세요 - - - Waiting to start - 시작을 기다리는중 - - - System Unresponsive - 시스템이 응답하지않습니다 - - - - PairingPopup - - Pair your device to your comma account - 장치를 comma 계정에 동기화합니다 - - - Go to https://connect.comma.ai on your phone - https://connect.comma.ai에 접속하세요 - - - Click "add new device" and scan the QR code on the right - "새 장치 추가"를 클릭하고 오른쪽 QR 코드를 스캔하세요 - - - Bookmark connect.comma.ai to your home screen to use it like an app - connect.comma.ai를 앱처럼 사용하려면 홈 화면에 바로가기를 만드세요 - - - Please connect to Wi-Fi to complete initial pairing - 초기 동기화를 완료하려면 Wi-Fi에 연결하세요. - - - - ParamControl - - Cancel - 취소 - - - Enable - 활성화 - - - - ParamControlSP - - Enable - 활성화 - - - Cancel - 취소 - - - - PlatformSelector - - Vehicle - - - - SEARCH - - - - Search your vehicle - - - - Enter model year (e.g., 2021) and model name (Toyota Corolla): - - - - SEARCHING - - - - REMOVE - 삭제 - - - This setting will take effect immediately. - - - - This setting will take effect once the device enters offroad state. - - - - Vehicle Selector - - - - Confirm - 확인 - - - Cancel - 취소 - - - No vehicles found for query: %1 - - - - Select a vehicle - - - - Unrecognized Vehicle - - - - Fingerprinted automatically - - - - Manually selected - - - - Not fingerprinted or manually selected - - - - Select vehicle to force fingerprint manually. - - - - Colors represent fingerprint status: - - - - - PrimeAdWidget - - Upgrade Now - 지금 업그레이드하세요 - - - Become a comma prime member at connect.comma.ai - connect.comma.ai에 접속하여 comma prime 회원으로 등록하세요 - - - PRIME FEATURES: - PRIME 기능: - - - Remote access - 원격 접속 - - - 24/7 LTE connectivity - 항상 LTE 연결 - - - 1 year of drive storage - 1년간 드라이브 로그 저장 - - - Remote snapshots - 원격 스냅샷 - - - - PrimeUserWidget - - ✓ SUBSCRIBED - ✓ 구독함 - - - comma prime - comma prime - - - - QObject - - sunnypilot - sunnypilot - - - %n minute(s) ago - - %n 분 전 - - - - %n hour(s) ago - - %n 시간 전 - - - - %n day(s) ago - - %n 일 전 - - - - now - now - - - - Reset - - Reset failed. Reboot to try again. - 초기화 실패. 재부팅 후 다시 시도하세요. - - - Are you sure you want to reset your device? - 장치를 초기화하시겠습니까? - - - System Reset - 장치 초기화 - - - Cancel - 취소 - - - Reboot - 재부팅 - - - Confirm - 확인 - - - Unable to mount data partition. Partition may be corrupted. Press confirm to erase and reset your device. - 데이터 파티션을 마운트할 수 없습니다. 파티션이 손상되었을 수 있습니다. 모든 설정을 삭제하고 장치를 초기화하려면 확인을 누르세요. - - - Resetting device... -This may take up to a minute. - 장치를 초기화하는 중... -최대 1분이 소요될 수 있습니다. - - - System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot. - 시스템 재설정이 시작되었습니다. 모든 콘텐츠와 설정을 지우려면 확인을 누르시고 부팅을 재개하려면 취소를 누르세요. - - - - SettingsWindow - - × - × - - - Device - 장치 - - - Network - 네트워크 - - - Toggles - 토글 - - - Software - 소프트웨어 - - - Developer - 개발자 - - - Firehose - 파이어호스 - - - - SettingsWindowSP - - × - × - - - Device - 장치 - - - Network - 네트워크 - - - sunnylink - - - - Toggles - 토글 - - - Software - 소프트웨어 - - - Trips - - - - Vehicle - - - - Developer - 개발자 - - - Firehose - 파이어호스 - - - Steering - - - - Models - - - - Cruise - - - - Visuals - - - - - Setup - - WARNING: Low Voltage - 경고: 전압이 낮습니다 - - - Power your device in a car with a harness or proceed at your own risk. - 장치를 하네스를 통해 차량 전원에 연결하세요. USB 전원에서는 예상치 못한 문제가 생길 수 있습니다. - - - Power off - 전원 끄기 - - - Continue - 계속 - - - Getting Started - 시작하기 - - - Before we get on the road, let’s finish installation and cover some details. - 출발 전 설정을 완료하고 세부 사항을 살펴봅니다. - - - Connect to Wi-Fi - Wi-Fi 연결 - - - Back - 뒤로 - - - Continue without Wi-Fi - Wi-Fi 연결 없이 진행 - - - Waiting for internet - 인터넷 연결 대기 중 - - - Enter URL - URL 입력 - - - for Custom Software - 커스텀 소프트웨어 - - - Downloading... - 다운로드 중... - - - Download Failed - 다운로드 실패 - - - Ensure the entered URL is valid, and the device’s internet connection is good. - 입력된 URL이 유효하고 인터넷 연결이 원활한지 확인하세요. - - - Reboot device - 장치 재부팅 - - - Start over - 다시 시작 - - - Something went wrong. Reboot the device. - 문제가 발생했습니다. 장치를 재부팅하세요. - - - No custom software found at this URL. - 이 URL에서 커스텀 소프트웨어를 찾을 수 없습니다. - - - Select a language - 언어를 선택하세요 - - - Choose Software to Install - 설치할 소프트웨어 선택 - - - sunnypilot - sunnypilot - - - Custom Software - 커스텀 소프트웨어 - - - - SetupWidget - - Finish Setup - 설정 완료 - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - 장치를 comma connect (connect.comma.ai)에서 동기화하고 comma prime 무료 이용권을 사용하세요. - - - Pair device - 장치 동기화 - - - - Sidebar - - CONNECT - 커넥트 - - - OFFLINE - 연결 안됨 - - - ONLINE - 온라인 - - - ERROR - 오류 - - - TEMP - 온도 - - - HIGH - 높음 - - - GOOD - 좋음 - - - OK - OK - - - VEHICLE - 차량 - - - NO - NO - - - PANDA - PANDA - - - -- - -- - - - Wi-Fi - Wi-Fi - - - ETH - LAN - - - 2G - 2G - - - 3G - 3G - - - LTE - LTE - - - 5G - 5G - - - - SidebarSP - - DISABLED - - - - OFFLINE - 연결 안됨 - - - REGIST... - - - - ONLINE - 온라인 - - - ERROR - 오류 - - - SUNNYLINK - - - - - SoftwarePanel - - Updates are only downloaded while the car is off. - 업데이트는 차량 시동이 꺼졌을 때 다운로드됩니다. - - - Current Version - 현재 버전 - - - Download - 다운로드 - - - Install Update - 업데이트 설치 - - - INSTALL - 설치 - - - Target Branch - 대상 브랜치 - - - SELECT - 선택 - - - Select a branch - 브랜치 선택 - - - UNINSTALL - 제거 - - - Uninstall %1 - %1 제거 - - - Are you sure you want to uninstall? - 제거하시겠습니까? - - - CHECK - 확인 - - - Uninstall - 제거 - - - failed to check for update - 업데이트를 확인하지 못했습니다 - - - up to date, last checked %1 - 최신 버전입니다. 마지막 확인: %1 - - - DOWNLOAD - 다운로드 - - - update available - 업데이트 가능 - - - never - 업데이트 안함 - - - - SoftwarePanelSP - - Search Branch - - - - Enter search keywords, or leave blank to list all branches. - - - - No branches found for keywords: %1 - - - - Select a branch - 브랜치 선택 - - - - SshControl - - SSH Keys - SSH 키 - - - Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username other than your own. A comma employee will NEVER ask you to add their GitHub username. - 경고: 이 설정은 GitHub에 등록된 모든 공용 키에 대해 SSH 액세스 권한을 부여합니다. 본인의 GitHub 사용자 아이디 이외에는 입력하지 마십시오. comma에서는 GitHub 아이디를 추가하라는 요청을 하지 않습니다. - - - ADD - 추가 - - - Enter your GitHub username - GitHub 사용자 ID - - - LOADING - 로딩 중 - - - REMOVE - 삭제 - - - Username '%1' has no keys on GitHub - 사용자 '%1'의 GitHub에 키가 등록되어 있지 않습니다 - - - Request timed out - 요청 시간 초과 - - - Username '%1' doesn't exist on GitHub - GitHub 사용자 '%1'를 찾지 못했습니다 - - - - SshToggle - - Enable SSH - SSH 사용 - - - - SunnylinkPanel - - This is the master switch, it will allow you to cutoff any sunnylink requests should you want to do that. - - - - Enable sunnylink - - - - 🎉Welcome back! We're excited to see you've enabled sunnylink again! 🚀 - - - - 👋Not going to lie, it's sad to see you disabled sunnylink 😢, but we'll be here when you're ready to come back 🎉. - - - - Device ID - - - - N/A - N/A - - - Sponsor Status - - - - SPONSOR - - - - Become a sponsor of sunnypilot to get early access to sunnylink features when they become available. - - - - Pair GitHub Account - - - - PAIR - 동기화 - - - Pair your GitHub account to grant your device sponsor benefits, including API access on sunnylink. - - - - sunnylink Dongle ID not found. This may be due to weak internet connection or sunnylink registration issue. Please reboot and try again. - - - - Not Sponsor - - - - Paired - - - - Not Paired - - - - THANKS ♥ - - - - Backup Settings - - - - Are you sure you want to backup sunnypilot settings? - - - - Back Up - - - - Restore Settings - - - - Are you sure you want to restore the last backed up sunnypilot settings? - - - - Restore - - - - Backup in progress %1% - - - - Backup Failed - - - - Settings backup completed. - - - - Restore in progress %1% - - - - Restore Failed - - - - Unable to restore the settings, try again later. - - - - Settings restored. Confirm to restart the interface. - - - - - SunnylinkSponsorPopup - - Scan the QR code to login to your GitHub account - - - - Follow the prompts to complete the pairing process - - - - Re-enter the "sunnylink" panel to verify sponsorship status - - - - If sponsorship status was not updated, please contact a moderator on Discord at https://discord.gg/sunnypilot - - - - Scan the QR code to visit sunnyhaibin's GitHub Sponsors page - - - - Choose your sponsorship tier and confirm your support - - - - Join our community on Discord at https://discord.gg/sunnypilot and reach out to a moderator to confirm your sponsor status - - - - Pair your GitHub account - - - - Early Access: Become a sunnypilot Sponsor - - - - - TermsPage - - Decline - 거절 - - - Agree - 동의 - - - Welcome to sunnypilot - 오픈 파일럿에 오신 것을 환영합니다. - - - You must accept the Terms and Conditions to use sunnypilot. Read the latest terms at <span style='color: #465BEA;'>https://comma.ai/terms</span> before continuing. - 오픈파일럿을 사용하려면 이용약관에 동의해야 합니다. 최신 약관은 <span style='color: #465BEA;'>https://comma.ai/terms</span> 에서 최신 약관을 읽은 후 계속하세요. - - - - TogglesPanel - - Enable Lane Departure Warnings - 차선 이탈 경고 활성화 - - - Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h). - 차량이 50km/h(31mph) 이상의 속도로 주행할 때 방향지시등이 켜지지 않은 상태에서 차선을 벗어나면 경고합니다. - - - Use Metric System - 미터법 사용 - - - Display speed in km/h instead of mph. - mph 대신 km/h로 속도를 표시합니다. - - - Record and Upload Driver Camera - 운전자 카메라 녹화 및 업로드 - - - Upload data from the driver facing camera and help improve the driver monitoring algorithm. - 운전자 카메라의 영상 데이터를 업로드하여 운전자 모니터링 알고리즘을 개선합니다. - - - Disengage on Accelerator Pedal - 가속페달 조작 시 해제 - - - When enabled, pressing the accelerator pedal will disengage sunnypilot. - 활성화된 경우 가속 페달을 밟으면 sunnypilot이 해제됩니다. - - - Experimental Mode - 실험 모드 - - - sunnypilot defaults to driving in <b>chill mode</b>. Experimental mode enables <b>alpha-level features</b> that aren't ready for chill mode. Experimental features are listed below: - sunnypilot은 기본적으로 <b>안정 모드</b>로 주행합니다. 실험 모드는 안정화되지 않은 <b>알파 수준의 기능</b>을 활성화합니다. 실험 모드의 기능은 아래와 같습니다: - - - Let the driving model control the gas and brakes. sunnypilot will drive as it thinks a human would, including stopping for red lights and stop signs. Since the driving model decides the speed to drive, the set speed will only act as an upper bound. This is an alpha quality feature; mistakes should be expected. - sunnypilot의 주행모델이 가감속을 제어합니다. sunnypilot은 신호등과 정지 표지판을 보고 멈추는 것을 포함하여 인간이 운전하는 것처럼 생각하고 주행합니다. 주행 모델이 주행할 속도를 결정하므로 설정된 속도는 최대 주행 속도로만 기능합니다. 이 기능은 알파 수준이므로 사용에 각별히 주의해야 합니다. - - - New Driving Visualization - 새로운 주행 시각화 - - - Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control. - 차량에 장착된 ACC로 가감속을 제어하기 때문에 현재 이 차량에서는 실험 모드를 사용할 수 없습니다. - - - Aggressive - 공격적 - - - Standard - 표준 - - - Relaxed - 편안한 - - - Driving Personality - 주행 모드 - - - An alpha version of sunnypilot longitudinal control can be tested, along with Experimental mode, on non-release branches. - sunnypilot 가감속 제어 알파 버전은 비 릴리즈 브랜치에서 실험 모드와 함께 테스트할 수 있습니다. - - - Enable the sunnypilot longitudinal control (alpha) toggle to allow Experimental mode. - 실험 모드를 사용하려면 sunnypilot E2E 가감속 제어 (알파) 토글을 활성화하세요. - - - End-to-End Longitudinal Control - E2E 가감속 제어 - - - Standard is recommended. In aggressive mode, sunnypilot will follow lead cars closer and be more aggressive with the gas and brake. In relaxed mode sunnypilot will stay further away from lead cars. On supported cars, you can cycle through these personalities with your steering wheel distance button. - 표준 모드를 권장합니다. 공격적 모드의 sunnypilot은 선두 차량을 더 가까이 따라가고 가감속제어를 사용하여 더욱 공격적으로 움직입니다. 편안한 모드의 sunnypilot은 선두 차량으로부터 더 멀리 떨어져 있습니다. 지원되는 차량에서는 스티어링 휠 거리 버튼을 사용하여 이러한 특성을 순환할 수 있습니다. - - - The driving visualization will transition to the road-facing wide-angle camera at low speeds to better show some turns. The Experimental mode logo will also be shown in the top right corner. - 운전 시각화는 일부 회전을 더 잘 보여주기 위해 저속에서 도로를 향한 광각 카메라로 전환됩니다. 우측 상단에 실험 모드 로고가 표시됩니다. - - - Always-On Driver Monitoring - 상시 운전자 모니터링 - - - Enable driver monitoring even when sunnypilot is not engaged. - sunnypilot이 활성화되지 않은 경우에도 드라이버 모니터링을 활성화합니다. - - - Enable Dynamic Experimental Control - - - - Enable toggle to allow the model to determine when to use sunnypilot ACC or sunnypilot End to End Longitudinal. - - - - Enable sunnypilot - sunnypilot 사용 - - - Use the sunnypilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature. - - - - Changing this setting will restart openpilot if the car is powered on. - - - - openpilot longitudinal control may come in a future update. - - - - - Updater - - Update Required - 업데이트 필요 - - - An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. The download size is approximately 1GB. - OS 업데이트가 필요합니다. 장치를 Wi-Fi에 연결하면 가장 빠르게 업데이트할 수 있습니다. 다운로드 크기는 약 1GB입니다. - - - Connect to Wi-Fi - Wi-Fi 연결 - - - Install - 설치 - - - Back - 뒤로 - - - Loading... - 로딩 중... - - - Reboot - 재부팅 - - - Update failed - 업데이트 실패 - - - - WiFiPromptWidget - - Open - 열기 - - - <span style='font-family: "Noto Color Emoji";'>🔥</span> Firehose Mode <span style='font-family: Noto Color Emoji;'>🔥</span> - <span style='font-family: "Noto Color Emoji";'>🔥</span> 파이어호스 모드 <span style='font-family: Noto Color Emoji;'>🔥</span> - - - Maximize your training data uploads to improve openpilot's driving models. - - - - - WifiUI - - Scanning for networks... - 네트워크 검색 중... - - - CONNECTING... - 연결 중... - - - FORGET - 삭제 - - - Forget Wi-Fi Network "%1"? - Wi-Fi "%1"에 자동으로 연결하지 않겠습니까? - - - Forget - 삭제 - - - diff --git a/selfdrive/ui/translations/main_nl.ts b/selfdrive/ui/translations/main_nl.ts deleted file mode 100644 index 2bfc836773..0000000000 --- a/selfdrive/ui/translations/main_nl.ts +++ /dev/null @@ -1,1120 +0,0 @@ - - - - - AbstractAlert - - Close - Sluit - - - Snooze Update - Update uitstellen - - - Reboot and Update - Opnieuw Opstarten en Updaten - - - - AdvancedNetworking - - Back - Terug - - - Enable Tethering - Tethering Inschakelen - - - Tethering Password - Tethering Wachtwoord - - - EDIT - AANPASSEN - - - Enter new tethering password - Voer nieuw tethering wachtwoord in - - - IP Address - IP Adres - - - Enable Roaming - Roaming Inschakelen - - - APN Setting - APN Instelling - - - Enter APN - Voer APN in - - - leave blank for automatic configuration - laat leeg voor automatische configuratie - - - Cellular Metered - - - - Prevent large data uploads when on a metered connection - - - - - AnnotatedCameraWidget - - km/h - km/u - - - mph - mph - - - MAX - MAX - - - SPEED - SPEED - - - LIMIT - LIMIT - - - - ConfirmationDialog - - Ok - Ok - - - Cancel - Annuleren - - - - DeclinePage - - You must accept the Terms and Conditions in order to use sunnypilot. - U moet de Algemene Voorwaarden accepteren om sunnypilot te gebruiken. - - - Back - Terug - - - Decline, uninstall %1 - Afwijzen, verwijder %1 - - - - DevicePanel - - Dongle ID - Dongle ID - - - N/A - Nvt - - - Serial - Serienummer - - - Driver Camera - Bestuurders Camera - - - PREVIEW - BEKIJKEN - - - Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off) - Bekijk de naar de bestuurder gerichte camera om ervoor te zorgen dat het monitoren van de bestuurder goed zicht heeft. (Voertuig moet uitgschakeld zijn) - - - Reset Calibration - Kalibratie Resetten - - - RESET - RESET - - - Are you sure you want to reset calibration? - Weet u zeker dat u de kalibratie wilt resetten? - - - Review Training Guide - Doorloop de Training Opnieuw - - - REVIEW - BEKIJKEN - - - Review the rules, features, and limitations of sunnypilot - Bekijk de regels, functies en beperkingen van sunnypilot - - - Are you sure you want to review the training guide? - Weet u zeker dat u de training opnieuw wilt doorlopen? - - - Regulatory - Regelgeving - - - VIEW - BEKIJKEN - - - Change Language - Taal Wijzigen - - - CHANGE - WIJZIGEN - - - Select a language - Selecteer een taal - - - Reboot - Opnieuw Opstarten - - - Power Off - Uitschakelen - - - sunnypilot requires the device to be mounted within 4° left or right and within 5° up or 8° down. sunnypilot is continuously calibrating, resetting is rarely required. - sunnypilot vereist dat het apparaat binnen 4° links of rechts en binnen 5° omhoog of 8° omlaag wordt gemonteerd. sunnypilot kalibreert continu, resetten is zelden nodig. - - - Your device is pointed %1° %2 and %3° %4. - Uw apparaat is gericht op %1° %2 en %3° %4. - - - down - omlaag - - - up - omhoog - - - left - links - - - right - rechts - - - Are you sure you want to reboot? - Weet u zeker dat u opnieuw wilt opstarten? - - - Disengage to Reboot - Deactiveer sunnypilot om opnieuw op te starten - - - Are you sure you want to power off? - Weet u zeker dat u wilt uitschakelen? - - - Disengage to Power Off - Deactiveer sunnypilot om uit te schakelen - - - - DriveStats - - Drives - Ritten - - - Hours - Uren - - - ALL TIME - TOTAAL - - - PAST WEEK - AFGELOPEN WEEK - - - KM - Km - - - Miles - Mijl - - - - DriverViewScene - - camera starting - Camera wordt gestart - - - - InputDialog - - Cancel - Annuleren - - - Need at least %n character(s)! - - Heeft minstens %n karakter nodig! - Heeft minstens %n karakters nodig! - - - - - Installer - - Installing... - Installeren... - - - Receiving objects: - Objecten ontvangen: - - - Resolving deltas: - Deltas verwerken: - - - Updating files: - Bestanden bijwerken: - - - - MapETA - - eta - eta - - - min - min - - - hr - uur - - - km - km - - - mi - mi - - - - MapInstructions - - km - km - - - m - m - - - mi - mi - - - ft - ft - - - - MapPanel - - Current Destination - Huidige Bestemming - - - CLEAR - LEEGMAKEN - - - Recent Destinations - Recente Bestemmingen - - - Try the Navigation Beta - Probeer de Navigatie Bèta - - - Get turn-by-turn directions displayed and more with a comma -prime subscription. Sign up now: https://connect.comma.ai - Krijg stapsgewijze routebeschrijving en meer met een comma -prime abonnement. Meld u nu aan: https://connect.comma.ai - - - No home -location set - Geen thuislocatie -ingesteld - - - No work -location set - Geen werklocatie -ingesteld - - - no recent destinations - geen recente bestemmingen - - - - MapWindow - - Map Loading - Kaart wordt geladen - - - Waiting for GPS - Wachten op GPS - - - - MultiOptionDialog - - Select - Selecteer - - - Cancel - Annuleren - - - - Networking - - Advanced - Geavanceerd - - - Enter password - Voer wachtwoord in - - - for "%1" - voor "%1" - - - Wrong password - Verkeerd wachtwoord - - - - OffroadHome - - UPDATE - UPDATE - - - ALERTS - WAARSCHUWINGEN - - - ALERT - WAARSCHUWING - - - - PairingPopup - - Pair your device to your comma account - Koppel uw apparaat aan uw comma-account - - - Go to https://connect.comma.ai on your phone - Ga naar https://connect.comma.ai op uw telefoon - - - Click "add new device" and scan the QR code on the right - Klik op "add new device" en scan de QR-code aan de rechterkant - - - Bookmark connect.comma.ai to your home screen to use it like an app - Voeg connect.comma.ai toe op uw startscherm om het als een app te gebruiken - - - - PrimeAdWidget - - Upgrade Now - Upgrade nu - - - Become a comma prime member at connect.comma.ai - Word een comma prime lid op connect.comma.ai - - - PRIME FEATURES: - PRIME BEVAT: - - - Remote access - Toegang op afstand - - - 1 year of storage - 1 jaar lang opslag - - - Developer perks - Voordelen voor ontwikkelaars - - - - PrimeUserWidget - - ✓ SUBSCRIBED - ✓ GEABONNEERD - - - comma prime - comma prime - - - CONNECT.COMMA.AI - CONNECT.COMMA.AI - - - COMMA POINTS - COMMA PUNTEN - - - - QObject - - Reboot - Opnieuw Opstarten - - - Exit - Afsluiten - - - dashcam - dashcam - - - sunnypilot - sunnypilot - - - %n minute(s) ago - - %n minuut geleden - %n minuten geleden - - - - %n hour(s) ago - - %n uur geleden - %n uur geleden - - - - %n day(s) ago - - %n dag geleden - %n dagen geleden - - - - - Reset - - Reset failed. Reboot to try again. - Opnieuw instellen mislukt. Start opnieuw op om opnieuw te proberen. - - - Are you sure you want to reset your device? - Weet u zeker dat u uw apparaat opnieuw wilt instellen? - - - Resetting device... - Apparaat opnieuw instellen... - - - System Reset - Systeemreset - - - System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot. - Systeemreset geactiveerd. Druk op bevestigen om alle inhoud en instellingen te wissen. Druk op Annuleren om het opstarten te hervatten. - - - Cancel - Annuleren - - - Reboot - Opnieuw Opstarten - - - Confirm - Bevestigen - - - Unable to mount data partition. Press confirm to reset your device. - Kan gegevenspartitie niet koppelen. Druk op bevestigen om uw apparaat te resetten. - - - - RichTextDialog - - Ok - Ok - - - - SettingsWindow - - × - × - - - Device - Apparaat - - - Network - Netwerk - - - Toggles - Opties - - - Software - Software - - - Navigation - Navigatie - - - - Setup - - WARNING: Low Voltage - WAARCHUWING: Lage Spanning - - - Power your device in a car with a harness or proceed at your own risk. - Voorzie uw apparaat van stroom in een auto met een harnas (car harness) of ga op eigen risico verder. - - - Power off - Uitschakelen - - - Continue - Doorgaan - - - Getting Started - Aan de slag - - - Before we get on the road, let’s finish installation and cover some details. - Laten we, voordat we op pad gaan, de installatie afronden en enkele details bespreken. - - - Connect to Wi-Fi - Maak verbinding met Wi-Fi - - - Back - Terug - - - Continue without Wi-Fi - Doorgaan zonder Wi-Fi - - - Waiting for internet - Wachten op internet - - - Choose Software to Install - Kies Software om te Installeren - - - Dashcam - Dashcam - - - Custom Software - Andere Software - - - Enter URL - Voer URL in - - - for Custom Software - voor Andere Software - - - Downloading... - Downloaden... - - - Download Failed - Downloaden Mislukt - - - Ensure the entered URL is valid, and the device’s internet connection is good. - Zorg ervoor dat de ingevoerde URL geldig is en dat de internetverbinding van het apparaat goed is. - - - Reboot device - Apparaat opnieuw opstarten - - - Start over - Begin opnieuw - - - - SetupWidget - - Finish Setup - Installatie voltooien - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - Koppel uw apparaat met comma connect (connect.comma.ai) en claim uw comma prime-aanbieding. - - - Pair device - Apparaat koppelen - - - - Sidebar - - CONNECT - VERBINDING - - - OFFLINE - OFFLINE - - - ONLINE - ONLINE - - - ERROR - FOUT - - - TEMP - TEMP - - - HIGH - HOOG - - - GOOD - GOED - - - OK - OK - - - VEHICLE - VOERTUIG - - - NO - GEEN - - - PANDA - PANDA - - - GPS - GPS - - - SEARCH - ZOEKEN - - - -- - -- - - - Wi-Fi - Wi-Fi - - - ETH - ETH - - - 2G - 2G - - - 3G - 3G - - - LTE - 4G - - - 5G - 5G - - - - SoftwarePanel - - Git Branch - Git Branch - - - Git Commit - Git Commit - - - OS Version - OS Versie - - - Version - Versie - - - Last Update Check - Laatste Updatecontrole - - - The last time sunnypilot successfully checked for an update. The updater only runs while the car is off. - De laatste keer dat sunnypilot met succes heeft gecontroleerd op een update. De updater werkt alleen als de auto is uitgeschakeld. - - - Check for Update - Controleer op Updates - - - CHECKING - CONTROLEER - - - Switch Branch - Branch Verwisselen - - - ENTER - INVOEREN - - - The new branch will be pulled the next time the updater runs. - Tijdens de volgende update wordt de nieuwe branch opgehaald. - - - Enter branch name - Voer branch naam in - - - Uninstall %1 - Verwijder %1 - - - UNINSTALL - VERWIJDER - - - Are you sure you want to uninstall? - Weet u zeker dat u de installatie ongedaan wilt maken? - - - failed to fetch update - ophalen van update mislukt - - - CHECK - CONTROLEER - - - Updates are only downloaded while the car is off. - - - - Current Version - - - - Download - - - - Install Update - - - - INSTALL - - - - Target Branch - - - - SELECT - - - - Select a branch - - - - - SshControl - - SSH Keys - SSH Sleutels - - - Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username other than your own. A comma employee will NEVER ask you to add their GitHub username. - Waarschuwing: dit geeft SSH toegang tot alle openbare sleutels in uw GitHub-instellingen. Voer nooit een andere GitHub-gebruikersnaam in dan die van uzelf. Een medewerker van comma zal u NOOIT vragen om zijn GitHub-gebruikersnaam toe te voegen. - - - ADD - TOEVOEGEN - - - Enter your GitHub username - Voer uw GitHub gebruikersnaam in - - - LOADING - LADEN - - - REMOVE - VERWIJDEREN - - - Username '%1' has no keys on GitHub - Gebruikersnaam '%1' heeft geen SSH sleutels op GitHub - - - Request timed out - Time-out van aanvraag - - - Username '%1' doesn't exist on GitHub - Gebruikersnaam '%1' bestaat niet op GitHub - - - - SshToggle - - Enable SSH - SSH Inschakelen - - - - TermsPage - - Terms & Conditions - Algemene Voorwaarden - - - Decline - Afwijzen - - - Scroll to accept - Scroll om te accepteren - - - Agree - Akkoord - - - - TogglesPanel - - Enable sunnypilot - sunnypilot Inschakelen - - - Use the sunnypilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature. Changing this setting takes effect when the car is powered off. - Gebruik het sunnypilot-systeem voor adaptieve cruisecontrol en rijstrookassistentie. Uw aandacht is te allen tijde vereist om deze functie te gebruiken. Het wijzigen van deze instelling wordt van kracht wanneer de auto wordt uitgeschakeld. - - - Enable Lane Departure Warnings - Waarschuwingen bij Verlaten Rijstrook Inschakelen - - - Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h). - Ontvang waarschuwingen om terug naar de rijstrook te sturen wanneer uw voertuig over een gedetecteerde rijstrookstreep drijft zonder dat de richtingaanwijzer wordt geactiveerd terwijl u harder rijdt dan 50 km/u (31 mph). - - - Use Metric System - Gebruik Metrisch Systeem - - - Display speed in km/h instead of mph. - Geef snelheid weer in km/u in plaats van mph. - - - Record and Upload Driver Camera - Opnemen en Uploaden van de Bestuurders Camera - - - Upload data from the driver facing camera and help improve the driver monitoring algorithm. - Upload gegevens van de bestuurders camera en help het algoritme voor het monitoren van de bestuurder te verbeteren. - - - Disengage on Accelerator Pedal - Deactiveren Met Gaspedaal - - - When enabled, pressing the accelerator pedal will disengage sunnypilot. - Indien ingeschakeld, zal het indrukken van het gaspedaal sunnypilot deactiveren. - - - Show ETA in 24h Format - Toon verwachte aankomsttijd in 24-uurs formaat - - - Use 24h format instead of am/pm - Gebruik 24-uurs formaat in plaats van AM en PM - - - Show Map on Left Side of UI - Toon kaart aan linkerkant van het scherm - - - Show map on left side when in split screen view. - Toon kaart links in gesplitste schermweergave. - - - sunnypilot Longitudinal Control - sunnypilot Longitudinale Controle - - - sunnypilot will disable the car's radar and will take over control of gas and brakes. Warning: this disables AEB! - sunnypilot zal de radar van de auto uitschakelen en de controle over gas en remmen overnemen. Waarschuwing: hierdoor wordt AEB (automatische noodrem) uitgeschakeld! - - - 🌮 End-to-end longitudinal (extremely alpha) 🌮 - - - - Experimental sunnypilot Longitudinal Control - - - - <b>WARNING: sunnypilot longitudinal control is experimental for this car and will disable AEB.</b> - - - - Let the driving model control the gas and brakes. sunnypilot will drive as it thinks a human would. Super experimental. - - - - sunnypilot longitudinal control is not currently available for this car. - - - - Enable experimental longitudinal control to enable this. - - - - - Updater - - Update Required - Update Vereist - - - An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. The download size is approximately 1GB. - Een update van het besturingssysteem is vereist. Verbind je apparaat met Wi-Fi voor de snelste update-ervaring. De downloadgrootte is ongeveer 1 GB. - - - Connect to Wi-Fi - Maak verbinding met Wi-Fi - - - Install - Installeer - - - Back - Terug - - - Loading... - Aan het laden... - - - Reboot - Opnieuw Opstarten - - - Update failed - Update mislukt - - - - WifiUI - - Scanning for networks... - Scannen naar netwerken... - - - CONNECTING... - VERBINDEN... - - - FORGET - VERGETEN - - - Forget Wi-Fi Network "%1"? - Vergeet Wi-Fi Netwerk "%1"? - - - diff --git a/selfdrive/ui/translations/main_pl.ts b/selfdrive/ui/translations/main_pl.ts deleted file mode 100644 index 6e9170d298..0000000000 --- a/selfdrive/ui/translations/main_pl.ts +++ /dev/null @@ -1,1124 +0,0 @@ - - - - - AbstractAlert - - Close - Zamknij - - - Snooze Update - Zaktualizuj później - - - Reboot and Update - Uruchom ponownie i zaktualizuj - - - - AdvancedNetworking - - Back - Wróć - - - Enable Tethering - Włącz hotspot osobisty - - - Tethering Password - Hasło do hotspotu - - - EDIT - EDYTUJ - - - Enter new tethering password - Wprowadź nowe hasło do hotspotu - - - IP Address - Adres IP - - - Enable Roaming - Włącz roaming danych - - - APN Setting - Ustawienia APN - - - Enter APN - Wprowadź APN - - - leave blank for automatic configuration - Pozostaw puste, aby użyć domyślnej konfiguracji - - - Cellular Metered - - - - Prevent large data uploads when on a metered connection - - - - - AnnotatedCameraWidget - - km/h - km/h - - - mph - mph - - - MAX - MAX - - - SPEED - PRĘDKOŚĆ - - - LIMIT - OGRANICZENIE - - - - ConfirmationDialog - - Ok - Ok - - - Cancel - Anuluj - - - - DeclinePage - - You must accept the Terms and Conditions in order to use sunnypilot. - Aby korzystać z sunnypilota musisz zaakceptować regulamin. - - - Back - Wróć - - - Decline, uninstall %1 - Odrzuć, odinstaluj %1 - - - - DevicePanel - - Dongle ID - ID adaptera - - - N/A - N/A - - - Serial - Numer seryjny - - - Driver Camera - Kamera kierowcy - - - PREVIEW - PODGLĄD - - - Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off) - Wyświetl podgląd z kamery skierowanej na kierowcę, aby upewnić się, że monitoring kierowcy ma dobry zakres widzenia. (pojazd musi być wyłączony) - - - Reset Calibration - Zresetuj kalibrację - - - RESET - ZRESETUJ - - - Are you sure you want to reset calibration? - Czy na pewno chcesz zresetować kalibrację? - - - Review Training Guide - Zapoznaj się z samouczkiem - - - REVIEW - ZAPOZNAJ SIĘ - - - Review the rules, features, and limitations of sunnypilot - Zapoznaj się z zasadami, funkcjami i ograniczeniami sunnypilota - - - Are you sure you want to review the training guide? - Czy na pewno chcesz się zapoznać z samouczkiem? - - - Regulatory - Regulacja - - - VIEW - WIDOK - - - Change Language - Zmień język - - - CHANGE - ZMIEŃ - - - Select a language - Wybierz język - - - Reboot - Uruchom ponownie - - - Power Off - Wyłącz - - - sunnypilot requires the device to be mounted within 4° left or right and within 5° up or 8° down. sunnypilot is continuously calibrating, resetting is rarely required. - sunnypilot wymaga, aby urządzenie było zamontowane z maksymalnym odchyłem 4° poziomo, 5° w górę oraz 8° w dół. sunnypilot jest ciągle kalibrowany, rzadko konieczne jest resetowania urządzenia. - - - Your device is pointed %1° %2 and %3° %4. - Twoje urządzenie jest skierowane %1° %2 oraz %3° %4. - - - down - w dół - - - up - w górę - - - left - w lewo - - - right - w prawo - - - Are you sure you want to reboot? - Czy na pewno chcesz uruchomić ponownie urządzenie? - - - Disengage to Reboot - Aby uruchomić ponownie, odłącz sterowanie - - - Are you sure you want to power off? - Czy na pewno chcesz wyłączyć urządzenie? - - - Disengage to Power Off - Aby wyłączyć urządzenie, odłącz sterowanie - - - - DriveStats - - Drives - Przejazdy - - - Hours - Godziny - - - ALL TIME - CAŁKOWICIE - - - PAST WEEK - OSTATNI TYDZIEŃ - - - KM - KM - - - Miles - Mile - - - - DriverViewScene - - camera starting - uruchamianie kamery - - - - InputDialog - - Cancel - Anuluj - - - Need at least %n character(s)! - - Wpisana wartość powinna składać się przynajmniej z %n znaku! - Wpisana wartość powinna skłądać się przynajmniej z %n znaków! - Wpisana wartość powinna skłądać się przynajmniej z %n znaków! - - - - - Installer - - Installing... - Instalowanie... - - - Receiving objects: - Odbieranie obiektów: - - - Resolving deltas: - Rozwiązywanie różnic: - - - Updating files: - Aktualizacja plików: - - - - MapETA - - eta - przewidywany czas - - - min - min - - - hr - godz - - - km - km - - - mi - mi - - - - MapInstructions - - km - km - - - m - m - - - mi - mi - - - ft - ft - - - - MapPanel - - Current Destination - Miejsce docelowe - - - CLEAR - WYCZYŚĆ - - - Recent Destinations - Ostatnie miejsca docelowe - - - Try the Navigation Beta - Wypróbuj nawigację w wersji beta - - - Get turn-by-turn directions displayed and more with a comma -prime subscription. Sign up now: https://connect.comma.ai - Odblokuj nawigację zakręt po zakęcie i wiele więcej subskrybując -comma prime. Zarejestruj się teraz: https://connect.comma.ai - - - No home -location set - Lokalizacja domu -nie została ustawiona - - - No work -location set - Miejsce pracy -nie zostało ustawione - - - no recent destinations - brak ostatnich miejsc docelowych - - - - MapWindow - - Map Loading - Ładowanie Mapy - - - Waiting for GPS - Oczekiwanie na sygnał GPS - - - - MultiOptionDialog - - Select - Wybierz - - - Cancel - Anuluj - - - - Networking - - Advanced - Zaawansowane - - - Enter password - Wprowadź hasło - - - for "%1" - do "%1" - - - Wrong password - Niepoprawne hasło - - - - OffroadHome - - UPDATE - UAKTUALNIJ - - - ALERTS - ALERTY - - - ALERT - ALERT - - - - PairingPopup - - Pair your device to your comma account - Sparuj swoje urzadzenie ze swoim kontem comma - - - Go to https://connect.comma.ai on your phone - Wejdź na stronę https://connect.comma.ai na swoim telefonie - - - Click "add new device" and scan the QR code on the right - Kliknij "add new device" i zeskanuj kod QR znajdujący się po prawej stronie - - - Bookmark connect.comma.ai to your home screen to use it like an app - Dodaj connect.comma.ai do zakładek na swoim ekranie początkowym, aby korzystać z niej jak z aplikacji - - - - PrimeAdWidget - - Upgrade Now - Uaktualnij teraz - - - Become a comma prime member at connect.comma.ai - Zostań członkiem comma prime na connect.comma.ai - - - PRIME FEATURES: - FUNKCJE PRIME: - - - Remote access - Zdalny dostęp - - - 1 year of storage - 1 rok przechowywania danych - - - Developer perks - Udogodnienia dla programistów - - - - PrimeUserWidget - - ✓ SUBSCRIBED - ✓ ZASUBSKRYBOWANO - - - comma prime - comma prime - - - CONNECT.COMMA.AI - CONNECT.COMMA.AI - - - COMMA POINTS - COMMA POINTS - - - - QObject - - Reboot - Uruchom Ponownie - - - Exit - Wyjdź - - - dashcam - wideorejestrator - - - sunnypilot - sunnypilot - - - %n minute(s) ago - - %n minutę temu - %n minuty temu - %n minut temu - - - - %n hour(s) ago - - % godzinę temu - %n godziny temu - %n godzin temu - - - - %n day(s) ago - - %n dzień temu - %n dni temu - %n dni temu - - - - - Reset - - Reset failed. Reboot to try again. - Wymazywanie zakończone niepowodzeniem. Aby spróbować ponownie, uruchom ponownie urządzenie. - - - Are you sure you want to reset your device? - Czy na pewno chcesz wymazać urządzenie? - - - Resetting device... - Wymazywanie urządzenia... - - - System Reset - Przywróć do ustawień fabrycznych - - - System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot. - Przywracanie do ustawień fabrycznych. Wciśnij potwierdź, aby usunąć wszystkie dane oraz ustawienia. Wciśnij anuluj, aby wznowić uruchamianie. - - - Cancel - Anuluj - - - Reboot - Uruchom ponownie - - - Confirm - Potwiedź - - - Unable to mount data partition. Press confirm to reset your device. - Partycja nie została zamontowana poprawnie. Wciśnij potwierdź, aby uruchomić ponownie urządzenie. - - - - RichTextDialog - - Ok - Ok - - - - SettingsWindow - - × - x - - - Device - Urządzenie - - - Network - Sieć - - - Toggles - Przełączniki - - - Software - Oprogramowanie - - - Navigation - Nawigacja - - - - Setup - - WARNING: Low Voltage - OSTRZEŻENIE: Niskie Napięcie - - - Power your device in a car with a harness or proceed at your own risk. - Podłącz swoje urządzenie do zasilania poprzez podłączenienie go do pojazdu lub kontynuuj na własną odpowiedzialność. - - - Power off - Wyłącz - - - Continue - Kontynuuj - - - Getting Started - Zacznij - - - Before we get on the road, let’s finish installation and cover some details. - Zanim ruszysz w drogę, dokończ instalację i podaj kilka szczegółów. - - - Connect to Wi-Fi - Połącz z Wi-Fi - - - Back - Wróć - - - Continue without Wi-Fi - Kontynuuj bez połączenia z Wif-Fi - - - Waiting for internet - Oczekiwanie na połączenie sieciowe - - - Choose Software to Install - Wybierz oprogramowanie do instalacji - - - Dashcam - Wideorejestrator - - - Custom Software - Własne oprogramowanie - - - Enter URL - Wprowadź adres URL - - - for Custom Software - do własnego oprogramowania - - - Downloading... - Pobieranie... - - - Download Failed - Pobieranie nie powiodło się - - - Ensure the entered URL is valid, and the device’s internet connection is good. - Upewnij się, że wpisany adres URL jest poprawny, a połączenie internetowe działa poprawnie. - - - Reboot device - Uruchom ponownie - - - Start over - Zacznij od początku - - - - SetupWidget - - Finish Setup - Zakończ konfigurację - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - Sparuj swoje urządzenie z comma connect (connect.comma.ai) i wybierz swoją ofertę comma prime. - - - Pair device - Sparuj urządzenie - - - - Sidebar - - CONNECT - POŁĄCZENIE - - - OFFLINE - OFFLINE - - - ONLINE - ONLINE - - - ERROR - BŁĄD - - - TEMP - TEMP - - - HIGH - WYSOKA - - - GOOD - DOBRA - - - OK - OK - - - VEHICLE - POJAZD - - - NO - BRAK - - - PANDA - PANDA - - - GPS - GPS - - - SEARCH - SZUKAJ - - - -- - -- - - - Wi-Fi - Wi-FI - - - ETH - ETH - - - 2G - 2G - - - 3G - 3G - - - LTE - LTE - - - 5G - 5G - - - - SoftwarePanel - - Git Branch - Gałąź Git - - - Git Commit - Git commit - - - OS Version - Wersja systemu - - - Version - Wersja - - - Last Update Check - Ostatnie sprawdzenie aktualizacji - - - The last time sunnypilot successfully checked for an update. The updater only runs while the car is off. - Ostatni raz kiedy sunnypilot znalazł aktualizację. Aktualizator może być uruchomiony wyłącznie wtedy, kiedy pojazd jest wyłączony. - - - Check for Update - Sprawdź uaktualnienia - - - CHECKING - SPRAWDZANIE - - - Switch Branch - Zmień gąłąź - - - ENTER - WPROWADŹ - - - The new branch will be pulled the next time the updater runs. - Nowa gałąź będzie pobrana przy następnym uruchomieniu aktualizatora. - - - Enter branch name - Wprowadź nazwę gałęzi - - - Uninstall %1 - Odinstaluj %1 - - - UNINSTALL - ODINSTALUJ - - - Are you sure you want to uninstall? - Czy na pewno chcesz odinstalować? - - - failed to fetch update - pobieranie aktualizacji zakończone niepowodzeniem - - - CHECK - SPRAWDŹ - - - Updates are only downloaded while the car is off. - - - - Current Version - - - - Download - - - - Install Update - - - - INSTALL - - - - Target Branch - - - - SELECT - - - - Select a branch - - - - - SshControl - - SSH Keys - Klucze SSH - - - Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username other than your own. A comma employee will NEVER ask you to add their GitHub username. - Ostrzeżenie: To spowoduje przekazanie dostępu do wszystkich Twoich publicznych kuczy z ustawień GitHuba. Nigdy nie wprowadzaj nazwy użytkownika innej niż swoja. Pracownik comma NIGDY nie poprosi o dodanie swojej nazwy uzytkownika. - - - ADD - DODAJ - - - Enter your GitHub username - Wpisz swoją nazwę użytkownika GitHub - - - LOADING - ŁADOWANIE - - - REMOVE - USUŃ - - - Username '%1' has no keys on GitHub - Użytkownik '%1' nie posiada żadnych kluczy na GitHubie - - - Request timed out - Limit czasu rządania - - - Username '%1' doesn't exist on GitHub - Użytkownik '%1' nie istnieje na GitHubie - - - - SshToggle - - Enable SSH - Włącz SSH - - - - TermsPage - - Terms & Conditions - Regulamin - - - Decline - Odrzuć - - - Scroll to accept - Przewiń w dół, aby zaakceptować - - - Agree - Zaakceptuj - - - - TogglesPanel - - Enable sunnypilot - Włącz sunnypilota - - - Use the sunnypilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature. Changing this setting takes effect when the car is powered off. - Użyj sunnypilota do zachowania bezpiecznego odstępu między pojazdami i do asystowania w utrzymywaniu pasa ruchu. Twoja pełna uwaga jest wymagana przez cały czas korzystania z tej funkcji. Ustawienie to może być wdrożone wyłącznie wtedy, gdy pojazd jest wyłączony. - - - Enable Lane Departure Warnings - Włącz ostrzeganie przed zmianą pasa ruchu - - - Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h). - Otrzymuj alerty o powrocie na właściwy pas, kiedy Twój pojazd przekroczy linię bez włączonego kierunkowskazu jadąc powyżej 50 km/h (31 mph). - - - Use Metric System - Korzystaj z systemu metrycznego - - - Display speed in km/h instead of mph. - Wyświetl prędkość w km/h zamiast mph. - - - Record and Upload Driver Camera - Nagraj i prześlij nagranie z kamery kierowcy - - - Upload data from the driver facing camera and help improve the driver monitoring algorithm. - Prześlij dane z kamery skierowanej na kierowcę i pomóż poprawiać algorytm monitorowania kierowcy. - - - Disengage on Accelerator Pedal - Odłącz poprzez naciśnięcie gazu - - - When enabled, pressing the accelerator pedal will disengage sunnypilot. - Po włączeniu, naciśnięcie na pedał gazu odłączy sunnypilota. - - - Show ETA in 24h Format - Pokaż oczekiwany czas dojazdu w formacie 24-godzinnym - - - Use 24h format instead of am/pm - Korzystaj z formatu 24-godzinnego zamiast 12-godzinnego - - - Show Map on Left Side of UI - Pokaż mapę po lewej stronie ekranu - - - Show map on left side when in split screen view. - Pokaż mapę po lewej stronie kiedy ekran jest podzielony. - - - sunnypilot Longitudinal Control - Kontrola wzdłużna sunnypilota - - - sunnypilot will disable the car's radar and will take over control of gas and brakes. Warning: this disables AEB! - sunnypilot wyłączy radar samochodu i przejmie kontrolę nad gazem i hamulcem. Ostrzeżenie: wyłączony zostanie system AEB! - - - 🌮 End-to-end longitudinal (extremely alpha) 🌮 - - - - Experimental sunnypilot Longitudinal Control - - - - <b>WARNING: sunnypilot longitudinal control is experimental for this car and will disable AEB.</b> - - - - Let the driving model control the gas and brakes. sunnypilot will drive as it thinks a human would. Super experimental. - - - - sunnypilot longitudinal control is not currently available for this car. - - - - Enable experimental longitudinal control to enable this. - - - - - Updater - - Update Required - Wymagana Aktualizacja - - - An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. The download size is approximately 1GB. - Wymagana aktualizacja systemu operacyjnego. Aby przyspieszyć proces aktualizacji połącz swoje urzeądzenie do Wi-Fi. Rozmiar pobieranej paczki wynosi około 1GB. - - - Connect to Wi-Fi - Połącz się z Wi-Fi - - - Install - Zainstaluj - - - Back - Wróć - - - Loading... - Ładowanie... - - - Reboot - Uruchom ponownie - - - Update failed - Aktualizacja nie powiodła się - - - - WifiUI - - Scanning for networks... - Wyszukiwanie sieci... - - - CONNECTING... - ŁĄCZENIE... - - - FORGET - ZAPOMNIJ - - - Forget Wi-Fi Network "%1"? - Czy chcesz zapomnieć sieć "%1"? - - - diff --git a/selfdrive/ui/translations/main_pt-BR.ts b/selfdrive/ui/translations/main_pt-BR.ts deleted file mode 100644 index bc9e50ee0a..0000000000 --- a/selfdrive/ui/translations/main_pt-BR.ts +++ /dev/null @@ -1,2114 +0,0 @@ - - - - - AbstractAlert - - Close - Fechar - - - Snooze Update - Adiar Atualização - - - Reboot and Update - Reiniciar e Atualizar - - - - AdvancedNetworking - - Back - Voltar - - - Enable Tethering - Ativar Tether - - - Tethering Password - Senha Tethering - - - EDIT - EDITAR - - - Enter new tethering password - Insira nova senha tethering - - - IP Address - Endereço IP - - - Enable Roaming - Ativar Roaming - - - APN Setting - APN Config - - - Enter APN - Insira APN - - - leave blank for automatic configuration - deixe em branco para configuração automática - - - Cellular Metered - Plano de Dados Limitado - - - Hidden Network - Rede Oculta - - - CONNECT - CONECTE - - - Enter SSID - Digite o SSID - - - Enter password - Insira a senha - - - for "%1" - para "%1" - - - Prevent large data uploads when on a metered cellular connection - - - - default - - - - metered - - - - unmetered - - - - Wi-Fi Network Metered - - - - Prevent large data uploads when on a metered Wi-Fi connection - - - - - AutoLaneChangeTimer - - Auto Lane Change by Blinker - - - - Set a timer to delay the auto lane change operation when the blinker is used. No nudge on the steering wheel is required to auto lane change if a timer is set. Default is Nudge. -Please use caution when using this feature. Only use the blinker when traffic and road conditions permit. - - - - s - - - - Off - - - - Nudge - - - - Nudgeless - - - - - ConfirmationDialog - - Ok - OK - - - Cancel - Cancelar - - - - DeclinePage - - You must accept the Terms and Conditions in order to use sunnypilot. - Você precisa aceitar os Termos e Condições para utilizar sunnypilot. - - - Back - Voltar - - - Decline, uninstall %1 - Rejeitar, desintalar %1 - - - - DeveloperPanel - - Joystick Debug Mode - Modo Joystick Debug - - - Longitudinal Maneuver Mode - Modo Longitudinal Maneuver - - - Enable ADB - Habilitar ADB - - - ADB (Android Debug Bridge) allows connecting to your device over USB or over the network. See https://docs.comma.ai/how-to/connect-to-comma for more info. - ADB (Android Debug Bridge) permite conectar ao seu dispositivo por meio do USB ou através da rede. Veja https://docs.comma.ai/how-to/connect-to-comma para maiores informações. - - - Enable GitHub runner service - - - - Enables or disables the github runner service. - - - - Error Log - - - - VIEW - VER - - - View the error log for sunnypilot crashes. - - - - openpilot Longitudinal Control (Alpha) - - - - WARNING: openpilot longitudinal control is in alpha for this car and will disable Automatic Emergency Braking (AEB). - - - - On this car, sunnypilot defaults to the car's built-in ACC instead of openpilot's longitudinal control. Enable this to switch to openpilot longitudinal control. Enabling Experimental mode is recommended when enabling openpilot longitudinal control alpha. - - - - - DevicePanel - - Dongle ID - Dongle ID - - - N/A - N/A - - - Serial - Serial - - - Driver Camera - Câmera do Motorista - - - PREVIEW - VER - - - Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off) - Pré-visualizar a câmera voltada para o motorista para garantir que o monitoramento do sistema tenha uma boa visibilidade (veículo precisa estar desligado) - - - Reset Calibration - Reinicializar Calibragem - - - RESET - RESET - - - Are you sure you want to reset calibration? - Tem certeza que quer resetar a calibragem? - - - Review Training Guide - Revisar Guia de Treinamento - - - REVIEW - REVISAR - - - Review the rules, features, and limitations of sunnypilot - Revisar regras, aprimoramentos e limitações do sunnypilot - - - Are you sure you want to review the training guide? - Tem certeza que quer rever o treinamento? - - - Regulatory - Regulatório - - - VIEW - VER - - - Change Language - Alterar Idioma - - - CHANGE - ALTERAR - - - Select a language - Selecione o Idioma - - - Reboot - Reiniciar - - - Power Off - Desligar - - - sunnypilot requires the device to be mounted within 4° left or right and within 5° up or 9° down. sunnypilot is continuously calibrating, resetting is rarely required. - O sunnypilot requer que o dispositivo seja montado dentro de 4° esquerda ou direita e dentro de 5° para cima ou 9° para baixo. O sunnypilot está continuamente calibrando, resetar raramente é necessário. - - - Your device is pointed %1° %2 and %3° %4. - Seu dispositivo está montado %1° %2 e %3° %4. - - - down - baixo - - - up - cima - - - left - esquerda - - - right - direita - - - Are you sure you want to reboot? - Tem certeza que quer reiniciar? - - - Disengage to Reboot - Desacione para Reiniciar - - - Are you sure you want to power off? - Tem certeza que quer desligar? - - - Disengage to Power Off - Desacione para Desligar - - - Reset - Resetar - - - Review - Revisar - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - Pareie seu dispositivo com comma connect (connect.comma.ai) e reivindique sua oferta de comma prime. - - - Pair Device - Parear Dispositivo - - - PAIR - PAREAR - - - Disengage to Reset Calibration - - - - Resetting calibration will restart openpilot if the car is powered on. - - - - - DevicePanelSP - - Driver Camera Preview - - - - Training Guide - - - - Regulatory - Regulatório - - - Language - - - - Are you sure you want to review the training guide? - Tem certeza que quer rever o treinamento? - - - Review - Revisar - - - Select a language - Selecione o Idioma - - - Reboot - Reiniciar - - - Power Off - Desligar - - - Offroad Mode - - - - Are you sure you want to exit Always Offroad mode? - - - - Confirm - Confirmar - - - Are you sure you want to enter Always Offroad mode? - - - - Disengage to Enter Always Offroad Mode - - - - Exit Always Offroad - - - - Always Offroad - - - - Quiet Mode - - - - Reset Settings - - - - Are you sure you want to reset all sunnypilot settings to default? Once the settings are reset, there is no going back. - - - - Reset - Resetar - - - The reset cannot be undone. You have been warned. - - - - - DriveStats - - Drives - - - - Hours - - - - ALL TIME - - - - PAST WEEK - - - - KM - - - - Miles - - - - - DriverViewWindow - - camera starting - câmera iniciando - - - - ExperimentalModeButton - - EXPERIMENTAL MODE ON - MODO EXPERIMENTAL ON - - - CHILL MODE ON - MODO CHILL ON - - - - FirehosePanel - - 🔥 Firehose Mode 🔥 - 🔥 Modo Firehose 🔥 - - - Firehose Mode: ACTIVE - Modo Firehose: ATIVO - - - ACTIVE - ATIVO - - - For maximum effectiveness, bring your device inside and connect to a good USB-C adapter and Wi-Fi weekly.<br><br>Firehose Mode can also work while you're driving if connected to a hotspot or unlimited SIM card.<br><br><br><b>Frequently Asked Questions</b><br><br><i>Does it matter how or where I drive?</i> Nope, just drive as you normally would.<br><br><i>Do all of my segments get pulled in Firehose Mode?</i> No, we selectively pull a subset of your segments.<br><br><i>What's a good USB-C adapter?</i> Any fast phone or laptop charger should be fine.<br><br><i>Does it matter which software I run?</i> Yes, only upstream sunnypilot (and particular forks) are able to be used for training. - Para maior eficácia, leve seu dispositivo para dentro de casa e conecte-o a um bom adaptador USB-C e Wi-Fi semanalmente.<br><br>O Modo Firehose também pode funcionar enquanto você dirige, se estiver conectado a um hotspot ou a um chip SIM com dados ilimitados.<br><br><br><b>Perguntas Frequentes</b><br><br><i>Importa como ou onde eu dirijo?</i> Não, basta dirigir normalmente.<br><br><i>Todos os meus segmentos são enviados no Modo Firehose?</i> Não, selecionamos apenas um subconjunto dos seus segmentos.<br><br><i>Qual é um bom adaptador USB-C?</i> Qualquer carregador rápido de telefone ou laptop deve ser suficiente.<br><br><i>Importa qual software eu uso?</i> Sim, apenas o sunnypilot oficial (e alguns forks específicos) podem ser usados para treinamento. - - - <b>%n segment(s)</b> of your driving is in the training dataset so far. - - <b>%n segmento</b> da sua direção está no conjunto de dados de treinamento até agora. - <b>%n segmentos</b> da sua direção estão no conjunto de dados de treinamento até agora. - - - - sunnypilot learns to drive by watching humans, like you, drive. - -Firehose Mode allows you to maximize your training data uploads to improve openpilot's driving models. More data means bigger models, which means better Experimental Mode. - - - - <span stylesheet='font-size: 60px; font-weight: bold; color: #e74c3c;'>INACTIVE</span>: connect to an unmetered network - <span stylesheet='font-size: 60px; font-weight: bold; color: #e74c3c;'>INATIVO</span>: conecte-se a uma rede sem limite <br> de dados - - - - HudRenderer - - km/h - km/h - - - mph - mph - - - MAX - LIMITE - - - - HyundaiSettings - - Off - - - - Dynamic - - - - Predictive - - - - Custom Longitudinal Tuning - - - - This feature can only be used with openpilot longitudinal control enabled. - - - - Enable "Always Offroad" in Device panel, or turn vehicle off to select an option. - - - - Off: Uses default tuning - - - - Dynamic: Adjusts acceleration limits based on current speed - - - - Predictive: Uses future trajectory data to anticipate needed adjustments - - - - Fine-tune your driving experience by adjusting acceleration smoothness with openpilot longitudinal control. - - - - - InputDialog - - Cancel - Cancelar - - - Need at least %n character(s)! - - Necessita no mínimo %n caractere! - Necessita no mínimo %n caracteres! - - - - - LaneChangeSettings - - Back - Voltar - - - Auto Lane Change: Delay with Blind Spot - - - - Toggle to enable a delay timer for seamless lane changes when blind spot monitoring (BSM) detects a obstructing vehicle, ensuring safe maneuvering. - - - - - LateralPanel - - Modular Assistive Driving System (MADS) - - - - Enable the beloved MADS feature. Disable toggle to revert back to stock sunnypilot engagement/disengagement. - - - - Customize MADS - - - - Customize Lane Change - - - - Enables independent engagements of Automatic Lane Centering (ALC) and Adaptive Cruise Control (ACC). - - - - Start the vehicle to check vehicle compatibility. - - - - This platform supports all MADS settings. - - - - This platform supports limited MADS settings. - - - - - MadsSettings - - Toggle with Main Cruise - - - - Note: For vehicles without LFA/LKAS button, disabling this will prevent lateral control engagement. - - - - Unified Engagement Mode (UEM) - - - - Engage lateral and longitudinal control with cruise control engagement. - - - - Note: Once lateral control is engaged via UEM, it will remain engaged until it is manually disabled via the MADS button or car shut off. - - - - Remain Active - - - - Disengage - - - - Steering Mode on Brake Pedal - - - - Start the vehicle to check vehicle compatibility. - - - - This feature defaults to OFF, and does not allow selection due to vehicle limitations. - - - - This feature defaults to ON, and does not allow selection due to vehicle limitations. - - - - This platform only supports Disengage mode due to vehicle limitations. - - - - Remain Active: ALC will remain active when the brake pedal is pressed. - - - - Pause - - - - Pause: ALC will pause when the brake pedal is pressed. - - - - Disengage: ALC will disengage when the brake pedal is pressed. - - - - Choose how Automatic Lane Centering (ALC) behaves after the brake pedal is manually pressed in sunnypilot. - - - - - MaxTimeOffroad - - Max Time Offroad - - - - Device will automatically shutdown after set time once the engine is turned off.<br/>(30h is the default) - - - - Always On - - - - h - - - - m - - - - (default) - - - - - ModelsPanel - - Current Model - - - - SELECT - SELECIONE - - - No custom model selected! - - - - Driving - - - - Navigation - - - - Vision - - - - Policy - - - - Downloading %1 model [%2]... (%3%) - - - - %1 model [%2] %3 - - - - downloaded - - - - ready - - - - from cache - - - - %1 model [%2] download failed - - - - %1 model [%2] pending... - - - - Fetching models... - - - - Use Default - - - - Select a Model - - - - Default - - - - Model download has started in the background. - - - - We STRONGLY suggest you to reset calibration. - - - - Would you like to do that now? - - - - Reset Calibration - Reinicializar Calibragem - - - Driving Model Selector - - - - Warning: You are on a metered connection! - - - - Continue - Continuar - - - on Metered - - - - Cancel - Cancelar - - - - MultiOptionDialog - - Select - Selecione - - - Cancel - Cancelar - - - - Networking - - Advanced - Avançado - - - Enter password - Insira a senha - - - for "%1" - para "%1" - - - Wrong password - Senha incorreta - - - - NetworkingSP - - Scan - - - - Scanning... - - - - - NeuralNetworkLateralControl - - Neural Network Lateral Control (NNLC) - - - - NNLC is currently not available on this platform. - - - - Start the car to check car compatibility - - - - NNLC Not Loaded - - - - NNLC Loaded - - - - Match - - - - Exact - - - - Fuzzy - - - - Match: "Exact" is ideal, but "Fuzzy" is fine too. - - - - Formerly known as <b>"NNFF"</b>, this replaces the lateral <b>"torque"</b> controller, with one using a neural network trained on each car's (actually, each separate EPS firmware) driving data for increased controls accuracy. - - - - Reach out to the sunnypilot team in the following channel at the sunnypilot Discord server - - - - with feedback, or to provide log data for your car if your car is currently unsupported: - - - - if there are any issues: - - - - and donate logs to get NNLC loaded for your car: - - - - - OffroadAlert - - Immediately connect to the internet to check for updates. If you do not connect to the internet, sunnypilot won't engage in %1 - Conecte-se imediatamente à internet para verificar se há atualizações. Se você não se conectar à internet em %1 não será possível acionar o sunnypilot. - - - Connect to internet to check for updates. sunnypilot won't automatically start until it connects to internet to check for updates. - Conecte-se à internet para verificar se há atualizações. O sunnypilot não será iniciado automaticamente até que ele se conecte à internet para verificar se há atualizações. - - - Unable to download updates -%1 - Não é possível baixar atualizações -%1 - - - Taking camera snapshots. System won't start until finished. - Tirando fotos da câmera. O sistema não será iniciado até terminar. - - - An update to your device's operating system is downloading in the background. You will be prompted to update when it's ready to install. - Uma atualização para o sistema operacional do seu dispositivo está sendo baixada em segundo plano. Você será solicitado a atualizar quando estiver pronto para instalar. - - - Device failed to register. It will not connect to or upload to comma.ai servers, and receives no support from comma.ai. If this is an official device, visit https://comma.ai/support. - Falha ao registrar o dispositivo. Ele não se conectará ou fará upload para os servidores comma.ai e não receberá suporte da comma.ai. Se este for um dispositivo oficial, visite https://comma.ai/support. - - - NVMe drive not mounted. - Unidade NVMe não montada. - - - Unsupported NVMe drive detected. Device may draw significantly more power and overheat due to the unsupported NVMe. - Unidade NVMe não suportada detectada. O dispositivo pode consumir significativamente mais energia e superaquecimento devido ao NVMe não suportado. - - - sunnypilot was unable to identify your car. Your car is either unsupported or its ECUs are not recognized. Please submit a pull request to add the firmware versions to the proper vehicle. Need help? Join discord.comma.ai. - O sunnypilot não conseguiu identificar o seu carro. Seu carro não é suportado ou seus ECUs não são reconhecidos. Envie um pull request para adicionar as versões de firmware ao veículo adequado. Precisa de ajuda? Junte-se discord.comma.ai. - - - sunnypilot detected a change in the device's mounting position. Ensure the device is fully seated in the mount and the mount is firmly secured to the windshield. - O sunnypilot detectou uma mudança na posição de montagem do dispositivo. Verifique se o dispositivo está totalmente encaixado no suporte e se o suporte está firmemente preso ao para-brisa. - - - Device temperature too high. System cooling down before starting. Current internal component temperature: %1 - Temperatura do dispositivo muito alta. O sistema está sendo resfriado antes de iniciar. A temperatura atual do componente interno é: %1 - - - sunnypilot is now in Always Offroad mode. sunnypilot won't start until Always Offroad mode is disabled. Go to "Settings" -> "Device" to exit Always Offroad mode. - - - - - OffroadHome - - UPDATE - ATUALIZAÇÃO - - - ALERTS - ALERTAS - - - ALERT - ALERTA - - - - OnroadAlerts - - sunnypilot Unavailable - sunnypilot Indisponível - - - TAKE CONTROL IMMEDIATELY - ASSUMA IMEDIATAMENTE - - - Reboot Device - Reinicie o Dispositivo - - - Waiting to start - Aguardando para iniciar - - - System Unresponsive - Sistema sem Resposta - - - - PairingPopup - - Pair your device to your comma account - Pareie seu dispositivo à sua conta comma - - - Go to https://connect.comma.ai on your phone - navegue até https://connect.comma.ai no seu telefone - - - Click "add new device" and scan the QR code on the right - Clique "add new device" e escaneie o QR code a seguir - - - Bookmark connect.comma.ai to your home screen to use it like an app - Salve connect.comma.ai como sua página inicial para utilizar como um app - - - Please connect to Wi-Fi to complete initial pairing - Por favor conecte ao Wi-Fi para completar o pareamento inicial - - - - ParamControl - - Cancel - Cancelar - - - Enable - Ativar - - - - ParamControlSP - - Enable - Ativar - - - Cancel - Cancelar - - - - PlatformSelector - - Vehicle - - - - SEARCH - - - - Search your vehicle - - - - Enter model year (e.g., 2021) and model name (Toyota Corolla): - - - - SEARCHING - - - - REMOVE - REMOVER - - - This setting will take effect immediately. - - - - This setting will take effect once the device enters offroad state. - - - - Vehicle Selector - - - - Confirm - Confirmar - - - Cancel - Cancelar - - - No vehicles found for query: %1 - - - - Select a vehicle - - - - Unrecognized Vehicle - - - - Fingerprinted automatically - - - - Manually selected - - - - Not fingerprinted or manually selected - - - - Select vehicle to force fingerprint manually. - - - - Colors represent fingerprint status: - - - - - PrimeAdWidget - - Upgrade Now - Atualizar Agora - - - Become a comma prime member at connect.comma.ai - Seja um membro comma prime em connect.comma.ai - - - PRIME FEATURES: - BENEFÍCIOS PRIME: - - - Remote access - Acesso remoto (proxy comma) - - - 24/7 LTE connectivity - Conectividade LTE (só nos EUA) - - - 1 year of drive storage - 1 ano de dados em nuvem - - - Remote snapshots - Captura remota - - - - PrimeUserWidget - - ✓ SUBSCRIBED - ✓ INSCRITO - - - comma prime - comma prime - - - - QObject - - sunnypilot - sunnypilot - - - %n minute(s) ago - - há %n minuto - há %n minutos - - - - %n hour(s) ago - - há %n hora - há %n horas - - - - %n day(s) ago - - há %n dia - há %n dias - - - - now - agora - - - - Reset - - Reset failed. Reboot to try again. - Reset falhou. Reinicie para tentar novamente. - - - Are you sure you want to reset your device? - Tem certeza que quer resetar seu dispositivo? - - - System Reset - Resetar Sistema - - - Cancel - Cancelar - - - Reboot - Reiniciar - - - Confirm - Confirmar - - - Unable to mount data partition. Partition may be corrupted. Press confirm to erase and reset your device. - Não é possível montar a partição de dados. Partição corrompida. Confirme para apagar e redefinir o dispositivo. - - - Resetting device... -This may take up to a minute. - Redefinindo o dispositivo -Isso pode levar até um minuto. - - - System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot. - Reinicialização do sistema acionada. Pressione confirmar para apagar todo o conteúdo e configurações. Pressione cancel para retomar a inicialização. - - - - SettingsWindow - - × - × - - - Device - Dispositivo - - - Network - Rede - - - Toggles - Ajustes - - - Software - Software - - - Developer - Desenvdor - - - Firehose - Firehose - - - - SettingsWindowSP - - × - × - - - Device - Dispositivo - - - Network - Rede - - - sunnylink - - - - Toggles - Ajustes - - - Software - Software - - - Trips - - - - Vehicle - - - - Developer - Desenvdor - - - Firehose - Firehose - - - Steering - - - - Models - - - - Cruise - - - - Visuals - - - - - Setup - - WARNING: Low Voltage - ALERTA: Baixa Voltagem - - - Power your device in a car with a harness or proceed at your own risk. - Ligue seu dispositivo em um carro com um chicote ou prossiga por sua conta e risco. - - - Power off - Desligar - - - Continue - Continuar - - - Getting Started - Começando - - - Before we get on the road, let’s finish installation and cover some details. - Antes de pegarmos a estrada, vamos terminar a instalação e cobrir alguns detalhes. - - - Connect to Wi-Fi - Conectar ao Wi-Fi - - - Back - Voltar - - - Continue without Wi-Fi - Continuar sem Wi-Fi - - - Waiting for internet - Esperando pela internet - - - Enter URL - Preencher URL - - - for Custom Software - para o Software Customizado - - - Downloading... - Baixando... - - - Download Failed - Download Falhou - - - Ensure the entered URL is valid, and the device’s internet connection is good. - Garanta que a URL inserida é valida, e uma boa conexão à internet. - - - Reboot device - Reiniciar Dispositivo - - - Start over - Inicializar - - - No custom software found at this URL. - Não há software personalizado nesta URL. - - - Something went wrong. Reboot the device. - Algo deu errado. Reinicie o dispositivo. - - - Select a language - Selecione o Idioma - - - Choose Software to Install - Escolha o Software a ser Instalado - - - sunnypilot - sunnypilot - - - Custom Software - Software Customizado - - - - SetupWidget - - Finish Setup - Concluir - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - Pareie seu dispositivo com comma connect (connect.comma.ai) e reivindique sua oferta de comma prime. - - - Pair device - Parear dispositivo - - - - Sidebar - - CONNECT - CONEXÃO - - - OFFLINE - OFFLINE - - - ONLINE - ONLINE - - - ERROR - ERRO - - - TEMP - TEMP - - - HIGH - ALTA - - - GOOD - BOA - - - OK - OK - - - VEHICLE - VEÍCULO - - - NO - SEM - - - PANDA - PANDA - - - -- - -- - - - Wi-Fi - Wi-Fi - - - ETH - ETH - - - 2G - 2G - - - 3G - 3G - - - LTE - LTE - - - 5G - 5G - - - - SidebarSP - - DISABLED - - - - OFFLINE - OFFLINE - - - REGIST... - - - - ONLINE - ONLINE - - - ERROR - ERRO - - - SUNNYLINK - - - - - SoftwarePanel - - Updates are only downloaded while the car is off. - Atualizações baixadas durante o motor desligado. - - - Current Version - Versão Atual - - - Download - Download - - - Install Update - Instalar Atualização - - - INSTALL - INSTALAR - - - Target Branch - Alterar Branch - - - SELECT - SELECIONE - - - Select a branch - Selecione uma branch - - - UNINSTALL - REMOVER - - - Uninstall %1 - Desinstalar o %1 - - - Are you sure you want to uninstall? - Tem certeza que quer desinstalar? - - - CHECK - VERIFICAR - - - Uninstall - Desinstalar - - - failed to check for update - falha ao verificar por atualizações - - - up to date, last checked %1 - atualizado, última verificação %1 - - - DOWNLOAD - BAIXAR - - - update available - atualização disponível - - - never - nunca - - - - SoftwarePanelSP - - Search Branch - - - - Enter search keywords, or leave blank to list all branches. - - - - No branches found for keywords: %1 - - - - Select a branch - Selecione uma branch - - - - SshControl - - SSH Keys - Chave SSH - - - Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username other than your own. A comma employee will NEVER ask you to add their GitHub username. - Aviso: isso concede acesso SSH a todas as chaves públicas nas configurações do GitHub. Nunca insira um nome de usuário do GitHub que não seja o seu. Um funcionário da comma NUNCA pedirá que você adicione seu nome de usuário do GitHub. - - - ADD - ADICIONAR - - - Enter your GitHub username - Insira seu nome de usuário do GitHub - - - LOADING - CARREGANDO - - - REMOVE - REMOVER - - - Username '%1' has no keys on GitHub - Usuário "%1” não possui chaves no GitHub - - - Request timed out - A solicitação expirou - - - Username '%1' doesn't exist on GitHub - Usuário '%1' não existe no GitHub - - - - SshToggle - - Enable SSH - Habilitar SSH - - - - SunnylinkPanel - - This is the master switch, it will allow you to cutoff any sunnylink requests should you want to do that. - - - - Enable sunnylink - - - - 🎉Welcome back! We're excited to see you've enabled sunnylink again! 🚀 - - - - 👋Not going to lie, it's sad to see you disabled sunnylink 😢, but we'll be here when you're ready to come back 🎉. - - - - Device ID - - - - N/A - N/A - - - Sponsor Status - - - - SPONSOR - - - - Become a sponsor of sunnypilot to get early access to sunnylink features when they become available. - - - - Pair GitHub Account - - - - PAIR - PAREAR - - - Pair your GitHub account to grant your device sponsor benefits, including API access on sunnylink. - - - - sunnylink Dongle ID not found. This may be due to weak internet connection or sunnylink registration issue. Please reboot and try again. - - - - Not Sponsor - - - - Paired - - - - Not Paired - - - - THANKS ♥ - - - - Backup Settings - - - - Are you sure you want to backup sunnypilot settings? - - - - Back Up - - - - Restore Settings - - - - Are you sure you want to restore the last backed up sunnypilot settings? - - - - Restore - - - - Backup in progress %1% - - - - Backup Failed - - - - Settings backup completed. - - - - Restore in progress %1% - - - - Restore Failed - - - - Unable to restore the settings, try again later. - - - - Settings restored. Confirm to restart the interface. - - - - - SunnylinkSponsorPopup - - Scan the QR code to login to your GitHub account - - - - Follow the prompts to complete the pairing process - - - - Re-enter the "sunnylink" panel to verify sponsorship status - - - - If sponsorship status was not updated, please contact a moderator on Discord at https://discord.gg/sunnypilot - - - - Scan the QR code to visit sunnyhaibin's GitHub Sponsors page - - - - Choose your sponsorship tier and confirm your support - - - - Join our community on Discord at https://discord.gg/sunnypilot and reach out to a moderator to confirm your sponsor status - - - - Pair your GitHub account - - - - Early Access: Become a sunnypilot Sponsor - - - - - TermsPage - - Decline - Declinar - - - Agree - Concordo - - - Welcome to sunnypilot - Bem vindo ao sunnypilot - - - You must accept the Terms and Conditions to use sunnypilot. Read the latest terms at <span style='color: #465BEA;'>https://comma.ai/terms</span> before continuing. - Você deve aceitar os Termos e Condições para usar o sunnypilot. Leia os termos mais recentes em <span style='color: #465BEA;'>https://comma.ai/terms</span> antes de continuar. - - - - TogglesPanel - - Enable Lane Departure Warnings - Ativar Avisos de Saída de Faixa - - - Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h). - Receba alertas para voltar para a pista se o seu veículo sair da faixa e a seta não tiver sido acionada previamente quando em velocidades superiores a 50 km/h. - - - Use Metric System - Usar Sistema Métrico - - - Display speed in km/h instead of mph. - Exibir velocidade em km/h invés de mph. - - - Record and Upload Driver Camera - Gravar e Upload Câmera Motorista - - - Upload data from the driver facing camera and help improve the driver monitoring algorithm. - Upload dados da câmera voltada para o motorista e ajude a melhorar o algoritmo de monitoramentor. - - - Disengage on Accelerator Pedal - Desacionar com Pedal do Acelerador - - - When enabled, pressing the accelerator pedal will disengage sunnypilot. - Quando ativado, pressionar o pedal do acelerador desacionará o sunnypilot. - - - Experimental Mode - Modo Experimental - - - sunnypilot defaults to driving in <b>chill mode</b>. Experimental mode enables <b>alpha-level features</b> that aren't ready for chill mode. Experimental features are listed below: - sunnypilot por padrão funciona em <b>modo chill</b>. modo Experimental ativa <b>recursos de nível-embrionário</b> que não estão prontos para o modo chill. Recursos experimentais estão listados abaixo: - - - Let the driving model control the gas and brakes. sunnypilot will drive as it thinks a human would, including stopping for red lights and stop signs. Since the driving model decides the speed to drive, the set speed will only act as an upper bound. This is an alpha quality feature; mistakes should be expected. - Deixe o modelo de IA controlar o acelerador e os freios. O sunnypilot irá dirigir como pensa que um humano faria, incluindo parar em sinais vermelhos e sinais de parada. Uma vez que o modelo de condução decide a velocidade a conduzir, a velocidade definida apenas funcionará como um limite superior. Este é um recurso de qualidade embrionária; erros devem ser esperados. - - - New Driving Visualization - Nova Visualização de Condução - - - Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control. - O modo Experimental está atualmente indisponível para este carro já que o ACC original do carro é usado para controle longitudinal. - - - Aggressive - Disputa - - - Standard - Neutro - - - Relaxed - Calmo - - - Driving Personality - Temperamento de Direção - - - An alpha version of sunnypilot longitudinal control can be tested, along with Experimental mode, on non-release branches. - Uma versão embrionária do controle longitudinal sunnypilot pode ser testada em conjunto com o modo Experimental, em branches que não sejam de produção. - - - Enable the sunnypilot longitudinal control (alpha) toggle to allow Experimental mode. - Habilite o controle longitudinal (embrionário) sunnypilot para permitir o modo Experimental. - - - End-to-End Longitudinal Control - Controle Longitudinal de Ponta a Ponta - - - Standard is recommended. In aggressive mode, sunnypilot will follow lead cars closer and be more aggressive with the gas and brake. In relaxed mode sunnypilot will stay further away from lead cars. On supported cars, you can cycle through these personalities with your steering wheel distance button. - Neutro é o recomendado. No modo disputa o sunnypilot seguirá o carro da frente mais de perto e será mais agressivo com a aceleração e frenagem. No modo calmo o sunnypilot se manterá mais longe do carro da frente. Em carros compatíveis, você pode alternar esses temperamentos com o botão de distância do volante. - - - The driving visualization will transition to the road-facing wide-angle camera at low speeds to better show some turns. The Experimental mode logo will also be shown in the top right corner. - A visualização de condução fará a transição para a câmera grande angular voltada para a estrada em baixas velocidades para mostrar melhor algumas curvas. O logotipo do modo Experimental também será mostrado no canto superior direito. - - - Always-On Driver Monitoring - Monitoramento do Motorista Sempre Ativo - - - Enable driver monitoring even when sunnypilot is not engaged. - Habilite o monitoramento do motorista mesmo quando o sunnypilot não estiver acionado. - - - Enable Dynamic Experimental Control - - - - Enable toggle to allow the model to determine when to use sunnypilot ACC or sunnypilot End to End Longitudinal. - - - - Enable sunnypilot - Ativar sunnypilot - - - Use the sunnypilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature. - - - - Changing this setting will restart openpilot if the car is powered on. - - - - openpilot longitudinal control may come in a future update. - - - - - Updater - - Update Required - Atualização Necessária - - - An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. The download size is approximately 1GB. - Uma atualização do sistema operacional é necessária. Conecte seu dispositivo ao Wi-Fi para a experiência de atualização mais rápida. O tamanho do download é de aproximadamente 1GB. - - - Connect to Wi-Fi - Conecte-se ao Wi-Fi - - - Install - Instalar - - - Back - Voltar - - - Loading... - Carregando... - - - Reboot - Reiniciar - - - Update failed - Falha na atualização - - - - WiFiPromptWidget - - Open - Abrir - - - <span style='font-family: "Noto Color Emoji";'>🔥</span> Firehose Mode <span style='font-family: Noto Color Emoji;'>🔥</span> - <span style='font-family: "Noto Color Emoji";'>🔥</span> Modo Firehose <span style='font-family: Noto Color Emoji;'>🔥</span> - - - Maximize your training data uploads to improve openpilot's driving models. - - - - - WifiUI - - Scanning for networks... - Procurando redes... - - - CONNECTING... - CONECTANDO... - - - FORGET - ESQUECER - - - Forget Wi-Fi Network "%1"? - Esquecer Rede Wi-Fi "%1"? - - - Forget - Esquecer - - - diff --git a/selfdrive/ui/translations/main_th.ts b/selfdrive/ui/translations/main_th.ts deleted file mode 100644 index 2c3d0bdb6c..0000000000 --- a/selfdrive/ui/translations/main_th.ts +++ /dev/null @@ -1,2109 +0,0 @@ - - - - - AbstractAlert - - Close - ปิด - - - Snooze Update - เลื่อนการอัปเดต - - - Reboot and Update - รีบูตและอัปเดต - - - - AdvancedNetworking - - Back - ย้อนกลับ - - - Enable Tethering - ปล่อยฮอตสปอต - - - Tethering Password - รหัสผ่านฮอตสปอต - - - EDIT - แก้ไข - - - Enter new tethering password - ป้อนรหัสผ่านฮอตสปอตใหม่ - - - IP Address - หมายเลขไอพี - - - Enable Roaming - เปิดใช้งานโรมมิ่ง - - - APN Setting - ตั้งค่า APN - - - Enter APN - ป้อนค่า APN - - - leave blank for automatic configuration - เว้นว่างเพื่อตั้งค่าอัตโนมัติ - - - Cellular Metered - ลดการส่งข้อมูลผ่านเซลลูล่าร์ - - - Hidden Network - เครือข่ายที่ซ่อนอยู่ - - - CONNECT - เชื่อมต่อ - - - Enter SSID - ป้อนค่า SSID - - - Enter password - ใส่รหัสผ่าน - - - for "%1" - สำหรับ "%1" - - - Prevent large data uploads when on a metered cellular connection - - - - default - - - - metered - - - - unmetered - - - - Wi-Fi Network Metered - - - - Prevent large data uploads when on a metered Wi-Fi connection - - - - - AutoLaneChangeTimer - - Auto Lane Change by Blinker - - - - Set a timer to delay the auto lane change operation when the blinker is used. No nudge on the steering wheel is required to auto lane change if a timer is set. Default is Nudge. -Please use caution when using this feature. Only use the blinker when traffic and road conditions permit. - - - - s - - - - Off - - - - Nudge - - - - Nudgeless - - - - - ConfirmationDialog - - Ok - ตกลง - - - Cancel - ยกเลิก - - - - DeclinePage - - You must accept the Terms and Conditions in order to use sunnypilot. - คุณต้องยอมรับเงื่อนไขและข้อตกลง เพื่อใช้งาน sunnypilot - - - Back - ย้อนกลับ - - - Decline, uninstall %1 - ปฏิเสธ และถอนการติดตั้ง %1 - - - - DeveloperPanel - - Joystick Debug Mode - - - - Longitudinal Maneuver Mode - - - - Enable ADB - - - - ADB (Android Debug Bridge) allows connecting to your device over USB or over the network. See https://docs.comma.ai/how-to/connect-to-comma for more info. - - - - Enable GitHub runner service - - - - Enables or disables the github runner service. - - - - Error Log - - - - VIEW - ดู - - - View the error log for sunnypilot crashes. - - - - openpilot Longitudinal Control (Alpha) - - - - WARNING: openpilot longitudinal control is in alpha for this car and will disable Automatic Emergency Braking (AEB). - - - - On this car, sunnypilot defaults to the car's built-in ACC instead of openpilot's longitudinal control. Enable this to switch to openpilot longitudinal control. Enabling Experimental mode is recommended when enabling openpilot longitudinal control alpha. - - - - - DevicePanel - - Dongle ID - Dongle ID - - - N/A - ไม่มี - - - Serial - ซีเรียล - - - Driver Camera - กล้องฝั่งคนขับ - - - PREVIEW - แสดงภาพ - - - Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off) - ดูภาพตัวอย่างกล้องที่หันเข้าหาคนขับเพื่อให้แน่ใจว่าการตรวจสอบคนขับมีทัศนวิสัยที่ดี (รถต้องดับเครื่องยนต์) - - - Reset Calibration - รีเซ็ตการคาลิเบรท - - - RESET - รีเซ็ต - - - Are you sure you want to reset calibration? - คุณแน่ใจหรือไม่ว่าต้องการรีเซ็ตการคาลิเบรท? - - - Review Training Guide - ทบทวนคู่มือการใช้งาน - - - REVIEW - ทบทวน - - - Review the rules, features, and limitations of sunnypilot - ตรวจสอบกฎ คุณสมบัติ และข้อจำกัดของ sunnypilot - - - Are you sure you want to review the training guide? - คุณแน่ใจหรือไม่ว่าต้องการทบทวนคู่มือการใช้งาน? - - - Regulatory - ระเบียบข้อบังคับ - - - VIEW - ดู - - - Change Language - เปลี่ยนภาษา - - - CHANGE - เปลี่ยน - - - Select a language - เลือกภาษา - - - Reboot - รีบูต - - - Power Off - ปิดเครื่อง - - - sunnypilot requires the device to be mounted within 4° left or right and within 5° up or 9° down. sunnypilot is continuously calibrating, resetting is rarely required. - sunnypilot กำหนดให้ติดตั้งอุปกรณ์ โดยสามารถเอียงด้านซ้ายหรือขวาไม่เกิน 4° และเอียงขึ้นด้านบนไม่เกิน 5° หรือเอียงลงด้านล่างไม่เกิน 9° sunnypilot ทำการคาลิเบรทอย่างต่อเนื่อง แทบจะไม่จำเป็นต้องทำการรีเซ็ตการคาลิเบรท - - - Your device is pointed %1° %2 and %3° %4. - อุปกรณ์ของคุณเอียงไปทาง %2 %1° และ %4 %3° - - - down - ด้านล่าง - - - up - ด้านบน - - - left - ด้านซ้าย - - - right - ด้านขวา - - - Are you sure you want to reboot? - คุณแน่ใจหรือไม่ว่าต้องการรีบูต? - - - Disengage to Reboot - ยกเลิกระบบช่วยขับเพื่อรีบูต - - - Are you sure you want to power off? - คุณแน่ใจหรือไม่ว่าต้องการปิดเครื่อง? - - - Disengage to Power Off - ยกเลิกระบบช่วยขับเพื่อปิดเครื่อง - - - Reset - รีเซ็ต - - - Review - ทบทวน - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - จับคู่อุปกรณ์ของคุณกับ comma connect (connect.comma.ai) และรับข้อเสนอ comma prime ของคุณ - - - Pair Device - จับคู่อุปกรณ์ - - - PAIR - จับคู่ - - - Disengage to Reset Calibration - - - - Resetting calibration will restart openpilot if the car is powered on. - - - - - DevicePanelSP - - Driver Camera Preview - - - - Training Guide - - - - Regulatory - ระเบียบข้อบังคับ - - - Language - - - - Are you sure you want to review the training guide? - คุณแน่ใจหรือไม่ว่าต้องการทบทวนคู่มือการใช้งาน? - - - Review - ทบทวน - - - Select a language - เลือกภาษา - - - Reboot - รีบูต - - - Power Off - ปิดเครื่อง - - - Offroad Mode - - - - Are you sure you want to exit Always Offroad mode? - - - - Confirm - ยืนยัน - - - Are you sure you want to enter Always Offroad mode? - - - - Disengage to Enter Always Offroad Mode - - - - Exit Always Offroad - - - - Always Offroad - - - - Quiet Mode - - - - Reset Settings - - - - Are you sure you want to reset all sunnypilot settings to default? Once the settings are reset, there is no going back. - - - - Reset - รีเซ็ต - - - The reset cannot be undone. You have been warned. - - - - - DriveStats - - Drives - - - - Hours - - - - ALL TIME - - - - PAST WEEK - - - - KM - - - - Miles - - - - - DriverViewWindow - - camera starting - กำลังเปิดกล้อง - - - - ExperimentalModeButton - - EXPERIMENTAL MODE ON - คุณกำลังใช้โหมดทดลอง - - - CHILL MODE ON - คุณกำลังใช้โหมดชิล - - - - FirehosePanel - - 🔥 Firehose Mode 🔥 - - - - Firehose Mode: ACTIVE - - - - ACTIVE - - - - For maximum effectiveness, bring your device inside and connect to a good USB-C adapter and Wi-Fi weekly.<br><br>Firehose Mode can also work while you're driving if connected to a hotspot or unlimited SIM card.<br><br><br><b>Frequently Asked Questions</b><br><br><i>Does it matter how or where I drive?</i> Nope, just drive as you normally would.<br><br><i>Do all of my segments get pulled in Firehose Mode?</i> No, we selectively pull a subset of your segments.<br><br><i>What's a good USB-C adapter?</i> Any fast phone or laptop charger should be fine.<br><br><i>Does it matter which software I run?</i> Yes, only upstream sunnypilot (and particular forks) are able to be used for training. - - - - <b>%n segment(s)</b> of your driving is in the training dataset so far. - - - - - - sunnypilot learns to drive by watching humans, like you, drive. - -Firehose Mode allows you to maximize your training data uploads to improve openpilot's driving models. More data means bigger models, which means better Experimental Mode. - - - - <span stylesheet='font-size: 60px; font-weight: bold; color: #e74c3c;'>INACTIVE</span>: connect to an unmetered network - - - - - HudRenderer - - km/h - กม./ชม. - - - mph - ไมล์/ชม. - - - MAX - สูงสุด - - - - HyundaiSettings - - Off - - - - Dynamic - - - - Predictive - - - - Custom Longitudinal Tuning - - - - This feature can only be used with openpilot longitudinal control enabled. - - - - Enable "Always Offroad" in Device panel, or turn vehicle off to select an option. - - - - Off: Uses default tuning - - - - Dynamic: Adjusts acceleration limits based on current speed - - - - Predictive: Uses future trajectory data to anticipate needed adjustments - - - - Fine-tune your driving experience by adjusting acceleration smoothness with openpilot longitudinal control. - - - - - InputDialog - - Cancel - ยกเลิก - - - Need at least %n character(s)! - - ต้องการอย่างน้อย %n ตัวอักษร! - - - - - LaneChangeSettings - - Back - ย้อนกลับ - - - Auto Lane Change: Delay with Blind Spot - - - - Toggle to enable a delay timer for seamless lane changes when blind spot monitoring (BSM) detects a obstructing vehicle, ensuring safe maneuvering. - - - - - LateralPanel - - Modular Assistive Driving System (MADS) - - - - Enable the beloved MADS feature. Disable toggle to revert back to stock sunnypilot engagement/disengagement. - - - - Customize MADS - - - - Customize Lane Change - - - - Enables independent engagements of Automatic Lane Centering (ALC) and Adaptive Cruise Control (ACC). - - - - Start the vehicle to check vehicle compatibility. - - - - This platform supports all MADS settings. - - - - This platform supports limited MADS settings. - - - - - MadsSettings - - Toggle with Main Cruise - - - - Note: For vehicles without LFA/LKAS button, disabling this will prevent lateral control engagement. - - - - Unified Engagement Mode (UEM) - - - - Engage lateral and longitudinal control with cruise control engagement. - - - - Note: Once lateral control is engaged via UEM, it will remain engaged until it is manually disabled via the MADS button or car shut off. - - - - Remain Active - - - - Disengage - - - - Steering Mode on Brake Pedal - - - - Start the vehicle to check vehicle compatibility. - - - - This feature defaults to OFF, and does not allow selection due to vehicle limitations. - - - - This feature defaults to ON, and does not allow selection due to vehicle limitations. - - - - This platform only supports Disengage mode due to vehicle limitations. - - - - Remain Active: ALC will remain active when the brake pedal is pressed. - - - - Pause - - - - Pause: ALC will pause when the brake pedal is pressed. - - - - Disengage: ALC will disengage when the brake pedal is pressed. - - - - Choose how Automatic Lane Centering (ALC) behaves after the brake pedal is manually pressed in sunnypilot. - - - - - MaxTimeOffroad - - Max Time Offroad - - - - Device will automatically shutdown after set time once the engine is turned off.<br/>(30h is the default) - - - - Always On - - - - h - - - - m - - - - (default) - - - - - ModelsPanel - - Current Model - - - - SELECT - เลือก - - - No custom model selected! - - - - Driving - - - - Navigation - - - - Vision - - - - Policy - - - - Downloading %1 model [%2]... (%3%) - - - - %1 model [%2] %3 - - - - downloaded - - - - ready - - - - from cache - - - - %1 model [%2] download failed - - - - %1 model [%2] pending... - - - - Fetching models... - - - - Use Default - - - - Select a Model - - - - Default - - - - Model download has started in the background. - - - - We STRONGLY suggest you to reset calibration. - - - - Would you like to do that now? - - - - Reset Calibration - รีเซ็ตการคาลิเบรท - - - Driving Model Selector - - - - Warning: You are on a metered connection! - - - - Continue - ดำเนินการต่อ - - - on Metered - - - - Cancel - ยกเลิก - - - - MultiOptionDialog - - Select - เลือก - - - Cancel - ยกเลิก - - - - Networking - - Advanced - ขั้นสูง - - - Enter password - ใส่รหัสผ่าน - - - for "%1" - สำหรับ "%1" - - - Wrong password - รหัสผ่านผิด - - - - NetworkingSP - - Scan - - - - Scanning... - - - - - NeuralNetworkLateralControl - - Neural Network Lateral Control (NNLC) - - - - NNLC is currently not available on this platform. - - - - Start the car to check car compatibility - - - - NNLC Not Loaded - - - - NNLC Loaded - - - - Match - - - - Exact - - - - Fuzzy - - - - Match: "Exact" is ideal, but "Fuzzy" is fine too. - - - - Formerly known as <b>"NNFF"</b>, this replaces the lateral <b>"torque"</b> controller, with one using a neural network trained on each car's (actually, each separate EPS firmware) driving data for increased controls accuracy. - - - - Reach out to the sunnypilot team in the following channel at the sunnypilot Discord server - - - - with feedback, or to provide log data for your car if your car is currently unsupported: - - - - if there are any issues: - - - - and donate logs to get NNLC loaded for your car: - - - - - OffroadAlert - - Device temperature too high. System cooling down before starting. Current internal component temperature: %1 - อุณหภูมิของอุปกรณ์สูงเกินไป ระบบกำลังทำความเย็นก่อนเริ่ม อุณหภูมิของชิ้นส่วนภายในปัจจุบัน: %1 - - - Immediately connect to the internet to check for updates. If you do not connect to the internet, sunnypilot won't engage in %1 - กรุณาเชื่อมต่ออินเตอร์เน็ตเพื่อตรวจสอบอัปเดทเดี๋ยวนี้ ถ้าคุณไม่เชื่อมต่ออินเตอร์เน็ต sunnypilot จะไม่ทำงานในอีก %1 - - - Connect to internet to check for updates. sunnypilot won't automatically start until it connects to internet to check for updates. - กรุณาเชื่อมต่ออินเตอร์เน็ตเพื่อตรวจสอบอัปเดท sunnypilot จะไม่เริ่มทำงานอัตโนมัติจนกว่าจะได้เชื่อมต่อกับอินเตอร์เน็ตเพื่อตรวจสอบอัปเดท - - - Unable to download updates -%1 - ไม่สามารถดาวน์โหลดอัพเดทได้ -%1 - - - Taking camera snapshots. System won't start until finished. - กล้องกำลังถ่ายภาพ ระบบจะไม่เริ่มทำงานจนกว่าจะเสร็จ - - - An update to your device's operating system is downloading in the background. You will be prompted to update when it's ready to install. - กำลังดาวน์โหลดอัปเดทสำหรับระบบปฏิบัติการอยู่เบื้องหลัง คุณจะได้รับการแจ้งเตือนเมื่อระบบพร้อมสำหรับการติดตั้ง - - - Device failed to register. It will not connect to or upload to comma.ai servers, and receives no support from comma.ai. If this is an official device, visit https://comma.ai/support. - ไม่สามารถลงทะเบียนอุปกรณ์ได้ อุปกรณ์จะไม่สามารถเชื่อมต่อหรืออัปโหลดไปยังเซิร์ฟเวอร์ของ comma.ai ได้และจะไม่ได้รับการสนับสนุนจาก comma.ai ถ้านี่คืออุปกรณ์อย่างเป็นทางการ กรุณาติดต่อ https://comma.ai/support - - - NVMe drive not mounted. - ไม่ได้ติดตั้งไดร์ฟ NVMe - - - Unsupported NVMe drive detected. Device may draw significantly more power and overheat due to the unsupported NVMe. - ตรวจพบไดร์ฟ NVMe ที่ไม่รองรับ อุปกรณ์อาจใช้พลังงานมากขึ้นและร้อนเกินไปเนื่องจากไดร์ฟ NVMe ที่ไม่รองรับ - - - sunnypilot was unable to identify your car. Your car is either unsupported or its ECUs are not recognized. Please submit a pull request to add the firmware versions to the proper vehicle. Need help? Join discord.comma.ai. - sunnypilot ไม่สามารถระบุรถยนต์ของคุณได้ ระบบอาจไม่รองรับรถยนต์ของคุณหรือไม่รู้จัก ECU กรุณาส่ง pull request เพื่อเพิ่มรุ่นของเฟิร์มแวร์ให้กับรถยนต์ที่เหมาะสม หากต้องการความช่วยเหลือให้เข้าร่วม discord.comma.ai - - - sunnypilot detected a change in the device's mounting position. Ensure the device is fully seated in the mount and the mount is firmly secured to the windshield. - sunnypilot ตรวจพบการเปลี่ยนแปลงของตำแหน่งที่ติดตั้ง กรุณาตรวจสอบว่าได้เลื่อนอุปกรณ์เข้ากับจุดติดตั้งจนสุดแล้ว และจุดติดตั้งได้ยึดติดกับกระจกหน้าอย่างแน่นหนา - - - sunnypilot is now in Always Offroad mode. sunnypilot won't start until Always Offroad mode is disabled. Go to "Settings" -> "Device" to exit Always Offroad mode. - - - - - OffroadHome - - UPDATE - อัปเดต - - - ALERTS - การแจ้งเตือน - - - ALERT - การแจ้งเตือน - - - - OnroadAlerts - - sunnypilot Unavailable - sunnypilot ไม่สามารถใช้งานได้ - - - TAKE CONTROL IMMEDIATELY - เข้าควบคุมรถเดี๋ยวนี้ - - - Reboot Device - รีบูตอุปกรณ์ - - - Waiting to start - - - - System Unresponsive - - - - - PairingPopup - - Pair your device to your comma account - จับคู่อุปกรณ์ของคุณกับบัญชี comma ของคุณ - - - Go to https://connect.comma.ai on your phone - ไปที่ https://connect.comma.ai ด้วยโทรศัพท์ของคุณ - - - Click "add new device" and scan the QR code on the right - กดที่ "add new device" และสแกนคิวอาร์โค้ดทางด้านขวา - - - Bookmark connect.comma.ai to your home screen to use it like an app - จดจำ connect.comma.ai โดยการเพิ่มไปยังหน้าจอโฮม เพื่อใช้งานเหมือนเป็นแอปพลิเคชัน - - - Please connect to Wi-Fi to complete initial pairing - - - - - ParamControl - - Enable - เปิดใช้งาน - - - Cancel - ยกเลิก - - - - ParamControlSP - - Enable - เปิดใช้งาน - - - Cancel - ยกเลิก - - - - PlatformSelector - - Vehicle - - - - SEARCH - - - - Search your vehicle - - - - Enter model year (e.g., 2021) and model name (Toyota Corolla): - - - - SEARCHING - - - - REMOVE - ลบ - - - This setting will take effect immediately. - - - - This setting will take effect once the device enters offroad state. - - - - Vehicle Selector - - - - Confirm - ยืนยัน - - - Cancel - ยกเลิก - - - No vehicles found for query: %1 - - - - Select a vehicle - - - - Unrecognized Vehicle - - - - Fingerprinted automatically - - - - Manually selected - - - - Not fingerprinted or manually selected - - - - Select vehicle to force fingerprint manually. - - - - Colors represent fingerprint status: - - - - - PrimeAdWidget - - Upgrade Now - อัพเกรดเดี๋ยวนี้ - - - Become a comma prime member at connect.comma.ai - สมัครสมาชิก comma prime ได้ที่ connect.comma.ai - - - PRIME FEATURES: - คุณสมบัติของ PRIME: - - - Remote access - การเข้าถึงระยะไกล - - - 24/7 LTE connectivity - การเชื่อมต่อ LTE แบบ 24/7 - - - 1 year of drive storage - จัดเก็บข้อมูลการขับขี่นาน 1 ปี - - - Remote snapshots - - - - - PrimeUserWidget - - ✓ SUBSCRIBED - ✓ สมัครสำเร็จ - - - comma prime - comma prime - - - - QObject - - sunnypilot - sunnypilot - - - %n minute(s) ago - - %n นาทีที่แล้ว - - - - %n hour(s) ago - - %n ชั่วโมงที่แล้ว - - - - %n day(s) ago - - %n วันที่แล้ว - - - - now - ตอนนี้ - - - - Reset - - Reset failed. Reboot to try again. - การรีเซ็ตล้มเหลว รีบูตเพื่อลองอีกครั้ง - - - Are you sure you want to reset your device? - คุณแน่ใจหรือไม่ว่าต้องการรีเซ็ตอุปกรณ์? - - - System Reset - รีเซ็ตระบบ - - - Cancel - ยกเลิก - - - Reboot - รีบูต - - - Confirm - ยืนยัน - - - Resetting device... -This may take up to a minute. - กำลังรีเซ็ตอุปกรณ์... -อาจใช้เวลาถึงหนึ่งนาที - - - Unable to mount data partition. Partition may be corrupted. Press confirm to erase and reset your device. - ไม่สามารถเมานต์พาร์ติชั่นข้อมูลได้ พาร์ติชั่นอาจเสียหาย กดยืนยันเพื่อลบและรีเซ็ตอุปกรณ์ของคุณ - - - System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot. - ระบบถูกรีเซ็ต กดยืนยันเพื่อลบข้อมูลและการตั้งค่าทั้งหมด กดยกเลิกเพื่อบูตต่อ - - - - SettingsWindow - - × - × - - - Device - อุปกรณ์ - - - Network - เครือข่าย - - - Toggles - ตัวเลือก - - - Software - ซอฟต์แวร์ - - - Developer - - - - Firehose - - - - - SettingsWindowSP - - × - × - - - Device - อุปกรณ์ - - - Network - เครือข่าย - - - sunnylink - - - - Toggles - ตัวเลือก - - - Software - ซอฟต์แวร์ - - - Trips - - - - Vehicle - - - - Developer - - - - Firehose - - - - Steering - - - - Models - - - - Cruise - - - - Visuals - - - - - Setup - - WARNING: Low Voltage - คำเตือน: แรงดันแบตเตอรี่ต่ำ - - - Power your device in a car with a harness or proceed at your own risk. - โปรดต่ออุปกรณ์ของคุณเข้ากับสายควบคุมในรถยนต์ หรือดำเนินการด้วยความเสี่ยงของคุณเอง - - - Power off - ปิดเครื่อง - - - Continue - ดำเนินการต่อ - - - Getting Started - เริ่มกันเลย - - - Before we get on the road, let’s finish installation and cover some details. - ก่อนออกเดินทาง เรามาทำการติดตั้งซอฟต์แวร์ และตรวจสอบการตั้งค่า - - - Connect to Wi-Fi - เชื่อมต่อ Wi-Fi - - - Back - ย้อนกลับ - - - Continue without Wi-Fi - ดำเนินการต่อโดยไม่ใช้ Wi-Fi - - - Waiting for internet - กำลังรอสัญญาณอินเตอร์เน็ต - - - Enter URL - ป้อน URL - - - for Custom Software - สำหรับซอฟต์แวร์ที่กำหนดเอง - - - Downloading... - กำลังดาวน์โหลด... - - - Download Failed - ดาวน์โหลดล้มเหลว - - - Ensure the entered URL is valid, and the device’s internet connection is good. - ตรวจสอบให้แน่ใจว่า URL ที่ป้อนนั้นถูกต้อง และอุปกรณ์เชื่อมต่ออินเทอร์เน็ตอยู่ - - - Reboot device - รีบูตอุปกรณ์ - - - Start over - เริ่มต้นใหม่ - - - Something went wrong. Reboot the device. - มีบางอย่างผิดพลาด รีบูตอุปกรณ์ - - - No custom software found at this URL. - ไม่พบซอฟต์แวร์ที่กำหนดเองที่ URL นี้ - - - Select a language - เลือกภาษา - - - Choose Software to Install - เลือกซอฟต์แวร์ที่จะติดตั้ง - - - sunnypilot - sunnypilot - - - Custom Software - ซอฟต์แวร์ที่กำหนดเอง - - - - SetupWidget - - Finish Setup - ตั้งค่าเสร็จสิ้น - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - จับคู่อุปกรณ์ของคุณกับ comma connect (connect.comma.ai) และรับข้อเสนอ comma prime ของคุณ - - - Pair device - จับคู่อุปกรณ์ - - - - Sidebar - - CONNECT - เชื่อมต่อ - - - OFFLINE - ออฟไลน์ - - - ONLINE - ออนไลน์ - - - ERROR - เกิดข้อผิดพลาด - - - TEMP - อุณหภูมิ - - - HIGH - สูง - - - GOOD - ดี - - - OK - พอใช้ - - - VEHICLE - รถยนต์ - - - NO - ไม่พบ - - - PANDA - PANDA - - - -- - -- - - - Wi-Fi - Wi-Fi - - - ETH - ETH - - - 2G - 2G - - - 3G - 3G - - - LTE - LTE - - - 5G - 5G - - - - SidebarSP - - DISABLED - - - - OFFLINE - ออฟไลน์ - - - REGIST... - - - - ONLINE - ออนไลน์ - - - ERROR - เกิดข้อผิดพลาด - - - SUNNYLINK - - - - - SoftwarePanel - - Uninstall %1 - ถอนการติดตั้ง %1 - - - UNINSTALL - ถอนการติดตั้ง - - - Are you sure you want to uninstall? - คุณแน่ใจหรือไม่ว่าต้องการถอนการติดตั้ง? - - - CHECK - ตรวจสอบ - - - Updates are only downloaded while the car is off. - ตัวอัปเดตจะดำเนินการดาวน์โหลดเมื่อรถดับเครื่องยนต์อยู่เท่านั้น - - - Current Version - เวอร์ชั่นปัจจุบัน - - - Download - ดาวน์โหลด - - - Install Update - ติดตั้งตัวอัปเดต - - - INSTALL - ติดตั้ง - - - Target Branch - Branch ที่เลือก - - - SELECT - เลือก - - - Select a branch - เลือก Branch - - - Uninstall - ถอนการติดตั้ง - - - failed to check for update - ไม่สามารถตรวจสอบอัปเดตได้ - - - DOWNLOAD - ดาวน์โหลด - - - update available - มีอัปเดตใหม่ - - - never - ไม่เคย - - - up to date, last checked %1 - ล่าสุดแล้ว ตรวจสอบครั้งสุดท้ายเมื่อ %1 - - - - SoftwarePanelSP - - Search Branch - - - - Enter search keywords, or leave blank to list all branches. - - - - No branches found for keywords: %1 - - - - Select a branch - เลือก Branch - - - - SshControl - - SSH Keys - คีย์ SSH - - - Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username other than your own. A comma employee will NEVER ask you to add their GitHub username. - คำเตือน: สิ่งนี้ให้สิทธิ์ SSH เข้าถึงคีย์สาธารณะทั้งหมดใน GitHub ของคุณ อย่าป้อนชื่อผู้ใช้ GitHub อื่นนอกเหนือจากของคุณเอง พนักงาน comma จะไม่ขอให้คุณเพิ่มชื่อผู้ใช้ GitHub ของพวกเขา - - - ADD - เพิ่ม - - - Enter your GitHub username - ป้อนชื่อผู้ใช้ GitHub ของคุณ - - - LOADING - กำลังโหลด - - - REMOVE - ลบ - - - Username '%1' has no keys on GitHub - ชื่อผู้ใช้ '%1' ไม่มีคีย์บน GitHub - - - Request timed out - ตรวจสอบไม่สำเร็จ เนื่องจากใช้เวลามากเกินไป - - - Username '%1' doesn't exist on GitHub - ไม่พบชื่อผู้ใช้ '%1' บน GitHub - - - - SshToggle - - Enable SSH - เปิดใช้งาน SSH - - - - SunnylinkPanel - - This is the master switch, it will allow you to cutoff any sunnylink requests should you want to do that. - - - - Enable sunnylink - - - - 🎉Welcome back! We're excited to see you've enabled sunnylink again! 🚀 - - - - 👋Not going to lie, it's sad to see you disabled sunnylink 😢, but we'll be here when you're ready to come back 🎉. - - - - Device ID - - - - N/A - ไม่มี - - - Sponsor Status - - - - SPONSOR - - - - Become a sponsor of sunnypilot to get early access to sunnylink features when they become available. - - - - Pair GitHub Account - - - - PAIR - จับคู่ - - - Pair your GitHub account to grant your device sponsor benefits, including API access on sunnylink. - - - - sunnylink Dongle ID not found. This may be due to weak internet connection or sunnylink registration issue. Please reboot and try again. - - - - Not Sponsor - - - - Paired - - - - Not Paired - - - - THANKS ♥ - - - - Backup Settings - - - - Are you sure you want to backup sunnypilot settings? - - - - Back Up - - - - Restore Settings - - - - Are you sure you want to restore the last backed up sunnypilot settings? - - - - Restore - - - - Backup in progress %1% - - - - Backup Failed - - - - Settings backup completed. - - - - Restore in progress %1% - - - - Restore Failed - - - - Unable to restore the settings, try again later. - - - - Settings restored. Confirm to restart the interface. - - - - - SunnylinkSponsorPopup - - Scan the QR code to login to your GitHub account - - - - Follow the prompts to complete the pairing process - - - - Re-enter the "sunnylink" panel to verify sponsorship status - - - - If sponsorship status was not updated, please contact a moderator on Discord at https://discord.gg/sunnypilot - - - - Scan the QR code to visit sunnyhaibin's GitHub Sponsors page - - - - Choose your sponsorship tier and confirm your support - - - - Join our community on Discord at https://discord.gg/sunnypilot and reach out to a moderator to confirm your sponsor status - - - - Pair your GitHub account - - - - Early Access: Become a sunnypilot Sponsor - - - - - TermsPage - - Decline - ปฏิเสธ - - - Agree - ยอมรับ - - - Welcome to sunnypilot - - - - You must accept the Terms and Conditions to use sunnypilot. Read the latest terms at <span style='color: #465BEA;'>https://comma.ai/terms</span> before continuing. - - - - - TogglesPanel - - Enable Lane Departure Warnings - เปิดใช้งานการเตือนการออกนอกเลน - - - Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h). - รับการแจ้งเตือนให้เลี้ยวกลับเข้าเลนเมื่อรถของคุณตรวจพบการข้ามช่องจราจรโดยไม่เปิดสัญญาณไฟเลี้ยวในขณะขับขี่ที่ความเร็วเกิน 31 ไมล์ต่อชั่วโมง (50 กม./ชม) - - - Use Metric System - ใช้ระบบเมตริก - - - Display speed in km/h instead of mph. - แสดงความเร็วเป็น กม./ชม. แทน ไมล์/ชั่วโมง - - - Record and Upload Driver Camera - บันทึกและอัปโหลดภาพจากกล้องคนขับ - - - Upload data from the driver facing camera and help improve the driver monitoring algorithm. - อัปโหลดข้อมูลจากกล้องที่หันหน้าไปทางคนขับ และช่วยปรับปรุงอัลกอริธึมการตรวจสอบผู้ขับขี่ - - - Disengage on Accelerator Pedal - ยกเลิกระบบช่วยขับเมื่อเหยียบคันเร่ง - - - When enabled, pressing the accelerator pedal will disengage sunnypilot. - เมื่อเปิดใช้งาน การกดแป้นคันเร่งจะเป็นการยกเลิกระบบช่วยขับโดย sunnypilot - - - Experimental Mode - โหมดทดลอง - - - sunnypilot defaults to driving in <b>chill mode</b>. Experimental mode enables <b>alpha-level features</b> that aren't ready for chill mode. Experimental features are listed below: - โดยปกติ sunnypilot จะขับใน<b>โหมดชิล</b> เปิดโหมดทดลองเพื่อใช้<b>ความสามารถในขั้นพัฒนา</b> ซึ่งยังไม่พร้อมสำหรับโหมดชิล ความสามารถในขั้นพัฒนามีดังนี้: - - - Let the driving model control the gas and brakes. sunnypilot will drive as it thinks a human would, including stopping for red lights and stop signs. Since the driving model decides the speed to drive, the set speed will only act as an upper bound. This is an alpha quality feature; mistakes should be expected. - ให้ sunnypilot ควบคุมการเร่ง/เบรค โดย sunnypilot จะขับอย่างที่มนุษย์คิด รวมถึงการหยุดที่ไฟแดง และป้ายหยุดรถ เนื่องจาก sunnypilot จะกำหนดความเร็วในการขับด้วยตัวเอง การตั้งความเร็วจะเป็นเพียงการกำหนดความเร็วสูงสูดเท่านั้น ความสามารถนี้ยังอยู่ในขั้นพัฒนา อาจเกิดข้อผิดพลาดขึ้นได้ - - - New Driving Visualization - การแสดงภาพการขับขี่แบบใหม่ - - - Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control. - ขณะนี้โหมดทดลองไม่สามารถใช้งานได้ในรถคันนี้ เนื่องจากเปิดใช้ระบบควบคุมการเร่ง/เบรคของรถที่ติดตั้งจากโรงงานอยู่ - - - Aggressive - ดุดัน - - - Standard - มาตรฐาน - - - Relaxed - ผ่อนคลาย - - - Driving Personality - บุคลิกการขับขี่ - - - An alpha version of sunnypilot longitudinal control can be tested, along with Experimental mode, on non-release branches. - ระบบควบคุมการเร่ง/เบรคโดย sunnypilot เวอร์ชัน alpha สามารถทดสอบได้พร้อมกับโหมดการทดลอง บน branch ที่กำลังพัฒนา - - - End-to-End Longitudinal Control - ควบคุมเร่ง/เบรคแบบ End-to-End - - - Enable the sunnypilot longitudinal control (alpha) toggle to allow Experimental mode. - เปิดระบบควบคุมการเร่ง/เบรคโดย sunnypilot (alpha) เพื่อเปิดใช้งานโหมดทดลอง - - - Standard is recommended. In aggressive mode, sunnypilot will follow lead cars closer and be more aggressive with the gas and brake. In relaxed mode sunnypilot will stay further away from lead cars. On supported cars, you can cycle through these personalities with your steering wheel distance button. - แนะนำให้ใช้แบบมาตรฐาน ในโหมดดุดัน sunnypilot จะตามรถคันหน้าใกล้ขึ้นและเร่งและเบรคแบบดุดันมากขึ้น ในโหมดผ่อนคลาย sunnypilot จะอยู่ห่างจากรถคันหน้ามากขึ้น ในรถรุ่นที่รองรับคุณสามารถเปลี่ยนบุคลิกไปแบบต่าง ๆ โดยใช้ปุ่มปรับระยะห่างบนพวงมาลัย - - - The driving visualization will transition to the road-facing wide-angle camera at low speeds to better show some turns. The Experimental mode logo will also be shown in the top right corner. - การแสดงภาพการขับขี่จะเปลี่ยนไปใช้กล้องมุมกว้างที่หันหน้าไปทางถนนเมื่ออยู่ในความเร็วต่ำ เพื่อแสดงภาพการเลี้ยวที่ดีขึ้น โลโก้โหมดการทดลองจะแสดงที่มุมบนขวาด้วย - - - Always-On Driver Monitoring - - - - Enable driver monitoring even when sunnypilot is not engaged. - - - - Enable Dynamic Experimental Control - - - - Enable toggle to allow the model to determine when to use sunnypilot ACC or sunnypilot End to End Longitudinal. - - - - Enable sunnypilot - เปิดใช้งาน sunnypilot - - - Use the sunnypilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature. - - - - Changing this setting will restart openpilot if the car is powered on. - - - - openpilot longitudinal control may come in a future update. - - - - - Updater - - Update Required - จำเป็นต้องอัปเดต - - - An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. The download size is approximately 1GB. - จำเป็นต้องมีการอัปเดตระบบปฏิบัติการ เชื่อมต่ออุปกรณ์ของคุณกับ Wi-Fi เพื่อประสบการณ์การอัปเดตที่เร็วที่สุด ขนาดดาวน์โหลดประมาณ 1GB - - - Connect to Wi-Fi - เชื่อมต่อกับ Wi-Fi - - - Install - ติดตั้ง - - - Back - ย้อนกลับ - - - Loading... - กำลังโหลด... - - - Reboot - รีบูต - - - Update failed - การอัปเดตล้มเหลว - - - - WiFiPromptWidget - - Open - - - - <span style='font-family: "Noto Color Emoji";'>🔥</span> Firehose Mode <span style='font-family: Noto Color Emoji;'>🔥</span> - - - - Maximize your training data uploads to improve openpilot's driving models. - - - - - WifiUI - - Scanning for networks... - กำลังสแกนหาเครือข่าย... - - - CONNECTING... - กำลังเชื่อมต่อ... - - - FORGET - เลิกใช้ - - - Forget Wi-Fi Network "%1"? - เลิกใช้เครือข่าย Wi-Fi "%1"? - - - Forget - เลิกใช้ - - - diff --git a/selfdrive/ui/translations/main_tr.ts b/selfdrive/ui/translations/main_tr.ts deleted file mode 100644 index fd06e81ef1..0000000000 --- a/selfdrive/ui/translations/main_tr.ts +++ /dev/null @@ -1,2107 +0,0 @@ - - - - - AbstractAlert - - Close - Kapat - - - Snooze Update - Güncellemeyi sessize al - - - Reboot and Update - Güncelle ve Yeniden başlat - - - - AdvancedNetworking - - Back - Geri dön - - - Enable Tethering - Kişisel erişim noktasını aç - - - Tethering Password - Kişisel erişim noktasının parolası - - - EDIT - DÜZENLE - - - Enter new tethering password - Erişim noktasına yeni bir sonraki başlatılışında çekilir. parola belirleyin. - - - IP Address - IP Adresi - - - Enable Roaming - Hücresel veri aç - - - APN Setting - APN Ayarları - - - Enter APN - APN Gir - - - leave blank for automatic configuration - otomatik yapılandırma için boş bırakın - - - Cellular Metered - - - - Hidden Network - - - - CONNECT - BAĞLANTI - - - Enter SSID - APN Gir - - - Enter password - Parolayı girin - - - for "%1" - için "%1" - - - Prevent large data uploads when on a metered cellular connection - - - - default - - - - metered - - - - unmetered - - - - Wi-Fi Network Metered - - - - Prevent large data uploads when on a metered Wi-Fi connection - - - - - AutoLaneChangeTimer - - Auto Lane Change by Blinker - - - - Set a timer to delay the auto lane change operation when the blinker is used. No nudge on the steering wheel is required to auto lane change if a timer is set. Default is Nudge. -Please use caution when using this feature. Only use the blinker when traffic and road conditions permit. - - - - s - - - - Off - - - - Nudge - - - - Nudgeless - - - - - ConfirmationDialog - - Ok - Tamam - - - Cancel - Vazgeç - - - - DeclinePage - - You must accept the Terms and Conditions in order to use sunnypilot. - Openpilotu kullanmak için Kullanıcı Koşullarını kabul etmelisiniz. - - - Back - Geri - - - Decline, uninstall %1 - Reddet, Kurulumu kaldır. %1 - - - - DeveloperPanel - - Joystick Debug Mode - - - - Longitudinal Maneuver Mode - - - - Enable ADB - - - - ADB (Android Debug Bridge) allows connecting to your device over USB or over the network. See https://docs.comma.ai/how-to/connect-to-comma for more info. - - - - Enable GitHub runner service - - - - Enables or disables the github runner service. - - - - Error Log - - - - VIEW - BAK - - - View the error log for sunnypilot crashes. - - - - openpilot Longitudinal Control (Alpha) - - - - WARNING: openpilot longitudinal control is in alpha for this car and will disable Automatic Emergency Braking (AEB). - - - - On this car, sunnypilot defaults to the car's built-in ACC instead of openpilot's longitudinal control. Enable this to switch to openpilot longitudinal control. Enabling Experimental mode is recommended when enabling openpilot longitudinal control alpha. - - - - - DevicePanel - - Dongle ID - Adaptör ID - - - N/A - N/A - - - Serial - Seri Numara - - - Driver Camera - Sürücü Kamerası - - - PREVIEW - ÖN İZLEME - - - Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off) - Sürücü kamerasının görüş açısını test etmek için kamerayı önizleyin (Araç kapalı olmalıdır.) - - - Reset Calibration - Kalibrasyonu sıfırla - - - RESET - SIFIRLA - - - Are you sure you want to reset calibration? - Kalibrasyon ayarını sıfırlamak istediğinizden emin misiniz? - - - Review Training Guide - Eğitim kılavuzunu inceleyin - - - REVIEW - GÖZDEN GEÇİR - - - Review the rules, features, and limitations of sunnypilot - sunnypilot sisteminin kurallarını ve sınırlamalarını gözden geçirin. - - - Are you sure you want to review the training guide? - Eğitim kılavuzunu incelemek istediğinizden emin misiniz? - - - Regulatory - Mevzuat - - - VIEW - BAK - - - Change Language - Dili değiştir - - - CHANGE - DEĞİŞTİR - - - Select a language - Dil seçin - - - Reboot - Yeniden başlat - - - Power Off - Sistemi kapat - - - sunnypilot requires the device to be mounted within 4° left or right and within 5° up or 9° down. sunnypilot is continuously calibrating, resetting is rarely required. - sunnypilot, cihazın 4° sola veya 5° yukarı yada 9° aşağı bakıcak şekilde monte edilmesi gerekmektedir. sunnypilot sürekli kendisini kalibre edilmektedir ve nadiren sıfırlama gerebilir. - - - Your device is pointed %1° %2 and %3° %4. - Cihazınız %1° %2 ve %3° %4 yönünde ayarlı - - - down - aşağı - - - up - yukarı - - - left - sol - - - right - sağ - - - Are you sure you want to reboot? - Cihazı Tekrar başlatmak istediğinizden eminmisiniz? - - - Disengage to Reboot - Bağlantıyı kes ve Cihazı Yeniden başlat - - - Are you sure you want to power off? - Cihazı kapatmak istediğizden eminmisiniz? - - - Disengage to Power Off - Bağlantıyı kes ve Cihazı kapat - - - Reset - - - - Review - - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - Cihazınızı comma connect (connect.comma.ai) ile eşleştirin ve comma prime aboneliğine göz atın. - - - Pair Device - - - - PAIR - - - - Disengage to Reset Calibration - - - - Resetting calibration will restart openpilot if the car is powered on. - - - - - DevicePanelSP - - Driver Camera Preview - - - - Training Guide - - - - Regulatory - Mevzuat - - - Language - - - - Are you sure you want to review the training guide? - Eğitim kılavuzunu incelemek istediğinizden emin misiniz? - - - Review - - - - Select a language - Dil seçin - - - Reboot - Yeniden başlat - - - Power Off - Sistemi kapat - - - Offroad Mode - - - - Are you sure you want to exit Always Offroad mode? - - - - Confirm - Onayla - - - Are you sure you want to enter Always Offroad mode? - - - - Disengage to Enter Always Offroad Mode - - - - Exit Always Offroad - - - - Always Offroad - - - - Quiet Mode - - - - Reset Settings - - - - Are you sure you want to reset all sunnypilot settings to default? Once the settings are reset, there is no going back. - - - - Reset - - - - The reset cannot be undone. You have been warned. - - - - - DriveStats - - Drives - - - - Hours - - - - ALL TIME - - - - PAST WEEK - - - - KM - - - - Miles - - - - - DriverViewWindow - - camera starting - kamera başlatılıyor - - - - ExperimentalModeButton - - EXPERIMENTAL MODE ON - - - - CHILL MODE ON - - - - - FirehosePanel - - 🔥 Firehose Mode 🔥 - - - - Firehose Mode: ACTIVE - - - - ACTIVE - - - - For maximum effectiveness, bring your device inside and connect to a good USB-C adapter and Wi-Fi weekly.<br><br>Firehose Mode can also work while you're driving if connected to a hotspot or unlimited SIM card.<br><br><br><b>Frequently Asked Questions</b><br><br><i>Does it matter how or where I drive?</i> Nope, just drive as you normally would.<br><br><i>Do all of my segments get pulled in Firehose Mode?</i> No, we selectively pull a subset of your segments.<br><br><i>What's a good USB-C adapter?</i> Any fast phone or laptop charger should be fine.<br><br><i>Does it matter which software I run?</i> Yes, only upstream sunnypilot (and particular forks) are able to be used for training. - - - - <b>%n segment(s)</b> of your driving is in the training dataset so far. - - - - - - sunnypilot learns to drive by watching humans, like you, drive. - -Firehose Mode allows you to maximize your training data uploads to improve openpilot's driving models. More data means bigger models, which means better Experimental Mode. - - - - <span stylesheet='font-size: 60px; font-weight: bold; color: #e74c3c;'>INACTIVE</span>: connect to an unmetered network - - - - - HudRenderer - - km/h - km/h - - - mph - mph - - - MAX - MAX - - - - HyundaiSettings - - Off - - - - Dynamic - - - - Predictive - - - - Custom Longitudinal Tuning - - - - This feature can only be used with openpilot longitudinal control enabled. - - - - Enable "Always Offroad" in Device panel, or turn vehicle off to select an option. - - - - Off: Uses default tuning - - - - Dynamic: Adjusts acceleration limits based on current speed - - - - Predictive: Uses future trajectory data to anticipate needed adjustments - - - - Fine-tune your driving experience by adjusting acceleration smoothness with openpilot longitudinal control. - - - - - InputDialog - - Cancel - Kapat - - - Need at least %n character(s)! - - En az %n karakter gerekli! - - - - - LaneChangeSettings - - Back - - - - Auto Lane Change: Delay with Blind Spot - - - - Toggle to enable a delay timer for seamless lane changes when blind spot monitoring (BSM) detects a obstructing vehicle, ensuring safe maneuvering. - - - - - LateralPanel - - Modular Assistive Driving System (MADS) - - - - Enable the beloved MADS feature. Disable toggle to revert back to stock sunnypilot engagement/disengagement. - - - - Customize MADS - - - - Customize Lane Change - - - - Enables independent engagements of Automatic Lane Centering (ALC) and Adaptive Cruise Control (ACC). - - - - Start the vehicle to check vehicle compatibility. - - - - This platform supports all MADS settings. - - - - This platform supports limited MADS settings. - - - - - MadsSettings - - Toggle with Main Cruise - - - - Note: For vehicles without LFA/LKAS button, disabling this will prevent lateral control engagement. - - - - Unified Engagement Mode (UEM) - - - - Engage lateral and longitudinal control with cruise control engagement. - - - - Note: Once lateral control is engaged via UEM, it will remain engaged until it is manually disabled via the MADS button or car shut off. - - - - Remain Active - - - - Disengage - - - - Steering Mode on Brake Pedal - - - - Start the vehicle to check vehicle compatibility. - - - - This feature defaults to OFF, and does not allow selection due to vehicle limitations. - - - - This feature defaults to ON, and does not allow selection due to vehicle limitations. - - - - This platform only supports Disengage mode due to vehicle limitations. - - - - Remain Active: ALC will remain active when the brake pedal is pressed. - - - - Pause - - - - Pause: ALC will pause when the brake pedal is pressed. - - - - Disengage: ALC will disengage when the brake pedal is pressed. - - - - Choose how Automatic Lane Centering (ALC) behaves after the brake pedal is manually pressed in sunnypilot. - - - - - MaxTimeOffroad - - Max Time Offroad - - - - Device will automatically shutdown after set time once the engine is turned off.<br/>(30h is the default) - - - - Always On - - - - h - - - - m - - - - (default) - - - - - ModelsPanel - - Current Model - - - - SELECT - - - - No custom model selected! - - - - Driving - - - - Navigation - - - - Vision - - - - Policy - - - - Downloading %1 model [%2]... (%3%) - - - - %1 model [%2] %3 - - - - downloaded - - - - ready - - - - from cache - - - - %1 model [%2] download failed - - - - %1 model [%2] pending... - - - - Fetching models... - - - - Use Default - - - - Select a Model - - - - Default - - - - Model download has started in the background. - - - - We STRONGLY suggest you to reset calibration. - - - - Would you like to do that now? - - - - Reset Calibration - Kalibrasyonu sıfırla - - - Driving Model Selector - - - - Warning: You are on a metered connection! - - - - Continue - Devam et - - - on Metered - - - - Cancel - - - - - MultiOptionDialog - - Select - Seç - - - Cancel - İptal et - - - - Networking - - Advanced - Gelişmiş Seçenekler - - - Enter password - Parolayı girin - - - for "%1" - için "%1" - - - Wrong password - Yalnış parola - - - - NetworkingSP - - Scan - - - - Scanning... - - - - - NeuralNetworkLateralControl - - Neural Network Lateral Control (NNLC) - - - - NNLC is currently not available on this platform. - - - - Start the car to check car compatibility - - - - NNLC Not Loaded - - - - NNLC Loaded - - - - Match - - - - Exact - - - - Fuzzy - - - - Match: "Exact" is ideal, but "Fuzzy" is fine too. - - - - Formerly known as <b>"NNFF"</b>, this replaces the lateral <b>"torque"</b> controller, with one using a neural network trained on each car's (actually, each separate EPS firmware) driving data for increased controls accuracy. - - - - Reach out to the sunnypilot team in the following channel at the sunnypilot Discord server - - - - with feedback, or to provide log data for your car if your car is currently unsupported: - - - - if there are any issues: - - - - and donate logs to get NNLC loaded for your car: - - - - - OffroadAlert - - Device temperature too high. System cooling down before starting. Current internal component temperature: %1 - - - - Immediately connect to the internet to check for updates. If you do not connect to the internet, sunnypilot won't engage in %1 - - - - Connect to internet to check for updates. sunnypilot won't automatically start until it connects to internet to check for updates. - - - - Unable to download updates -%1 - - - - Taking camera snapshots. System won't start until finished. - - - - An update to your device's operating system is downloading in the background. You will be prompted to update when it's ready to install. - - - - Device failed to register. It will not connect to or upload to comma.ai servers, and receives no support from comma.ai. If this is an official device, visit https://comma.ai/support. - - - - NVMe drive not mounted. - - - - Unsupported NVMe drive detected. Device may draw significantly more power and overheat due to the unsupported NVMe. - - - - sunnypilot was unable to identify your car. Your car is either unsupported or its ECUs are not recognized. Please submit a pull request to add the firmware versions to the proper vehicle. Need help? Join discord.comma.ai. - - - - sunnypilot detected a change in the device's mounting position. Ensure the device is fully seated in the mount and the mount is firmly secured to the windshield. - - - - sunnypilot is now in Always Offroad mode. sunnypilot won't start until Always Offroad mode is disabled. Go to "Settings" -> "Device" to exit Always Offroad mode. - - - - - OffroadHome - - UPDATE - GÜNCELLE - - - ALERTS - UYARILAR - - - ALERT - UYARI - - - - OnroadAlerts - - sunnypilot Unavailable - - - - TAKE CONTROL IMMEDIATELY - - - - Reboot Device - - - - Waiting to start - - - - System Unresponsive - - - - - PairingPopup - - Pair your device to your comma account - comma.ai hesabınız ile cihazı eşleştirin - - - Go to https://connect.comma.ai on your phone - Telefonuzdan https://connect.comma.ai sitesine gidin - - - Click "add new device" and scan the QR code on the right - Yeni cihaz eklemek için sağdaki QR kodunu okutun - - - Bookmark connect.comma.ai to your home screen to use it like an app - Uygulama gibi kullanmak için connect.comma.ai sitesini yer işaretlerine ekleyin. - - - Please connect to Wi-Fi to complete initial pairing - - - - - ParamControl - - Enable - - - - Cancel - - - - - ParamControlSP - - Enable - - - - Cancel - - - - - PlatformSelector - - Vehicle - - - - SEARCH - - - - Search your vehicle - - - - Enter model year (e.g., 2021) and model name (Toyota Corolla): - - - - SEARCHING - - - - REMOVE - KALDIR - - - This setting will take effect immediately. - - - - This setting will take effect once the device enters offroad state. - - - - Vehicle Selector - - - - Confirm - Onayla - - - Cancel - - - - No vehicles found for query: %1 - - - - Select a vehicle - - - - Unrecognized Vehicle - - - - Fingerprinted automatically - - - - Manually selected - - - - Not fingerprinted or manually selected - - - - Select vehicle to force fingerprint manually. - - - - Colors represent fingerprint status: - - - - - PrimeAdWidget - - Upgrade Now - Hemen yükselt - - - Become a comma prime member at connect.comma.ai - connect.comma.ai üzerinden comma prime üyesi olun - - - PRIME FEATURES: - PRIME ABONELİĞİNİN ÖZELLİKLERİ: - - - Remote access - Uzaktan erişim - - - 24/7 LTE connectivity - - - - 1 year of drive storage - - - - Remote snapshots - - - - - PrimeUserWidget - - ✓ SUBSCRIBED - ✓ ABONE - - - comma prime - comma prime - - - - QObject - - sunnypilot - sunnypilot - - - %n minute(s) ago - - %n dakika önce - - - - %n hour(s) ago - - %n saat önce - - - - %n day(s) ago - - %n gün önce - - - - now - - - - - Reset - - Reset failed. Reboot to try again. - Sıfırlama başarız oldu. Cihazı yeniden başlatın ve tekrar deneyin. - - - Are you sure you want to reset your device? - Cihazı sıfırlamak istediğinizden eminmisiniz ? - - - System Reset - Sistemi sıfırla - - - Cancel - İptal - - - Reboot - Yeniden başlat - - - Confirm - Onayla - - - Resetting device... -This may take up to a minute. - - - - Unable to mount data partition. Partition may be corrupted. Press confirm to erase and reset your device. - - - - System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot. - - - - - SettingsWindow - - × - x - - - Device - Cihaz - - - Network - - - - Toggles - Değiştirme - - - Software - Yazılım - - - Developer - - - - Firehose - - - - - SettingsWindowSP - - × - x - - - Device - Cihaz - - - Network - - - - sunnylink - - - - Toggles - Değiştirme - - - Software - Yazılım - - - Trips - - - - Vehicle - - - - Developer - - - - Firehose - - - - Steering - - - - Models - - - - Cruise - - - - Visuals - - - - - Setup - - WARNING: Low Voltage - UYARI: Düşük voltaj - - - Power your device in a car with a harness or proceed at your own risk. - Cihazınızı emniyet kemeri olan bir arabada çalıştırın veya riski kabul ederek devam edin. - - - Power off - Sistemi kapat - - - Continue - Devam et - - - Getting Started - Başlarken - - - Before we get on the road, let’s finish installation and cover some details. - Yola çıkmadan önce kurulumu bitirin ve bazı detayları gözden geçirin.. - - - Connect to Wi-Fi - Wi-Fi ile bağlan - - - Back - Geri - - - Continue without Wi-Fi - Wi-Fi bağlantısı olmadan devam edin - - - Waiting for internet - İnternet bağlantısı bekleniyor. - - - Enter URL - URL girin - - - for Custom Software - özel yazılım için - - - Downloading... - İndiriliyor... - - - Download Failed - İndirme başarısız. - - - Ensure the entered URL is valid, and the device’s internet connection is good. - Girilen URL nin geçerli olduğundan ve cihazın internet bağlantısının olduğunu kontrol edin - - - Reboot device - Cihazı yeniden başlat - - - Start over - Zacznij od początku - - - Something went wrong. Reboot the device. - - - - No custom software found at this URL. - - - - Select a language - Dil seçin - - - Choose Software to Install - - - - sunnypilot - sunnypilot - - - Custom Software - - - - - SetupWidget - - Finish Setup - Kurulumu bitir - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - Cihazınızı comma connect (connect.comma.ai) ile eşleştirin ve comma prime aboneliğine göz atın. - - - Pair device - Cihazı eşleştirme - - - - Sidebar - - CONNECT - BAĞLANTI - - - OFFLINE - ÇEVRİMDIŞI - - - ONLINE - ÇEVRİMİÇİ - - - ERROR - HATA - - - TEMP - SICAKLIK - - - HIGH - YÜKSEK - - - GOOD - İYİ - - - OK - TAMAM - - - VEHICLE - ARAÇ - - - NO - HAYIR - - - PANDA - PANDA - - - -- - -- - - - Wi-Fi - Wi-FI - - - ETH - ETH - - - 2G - 2G - - - 3G - 3G - - - LTE - LTE - - - 5G - 5G - - - - SidebarSP - - DISABLED - - - - OFFLINE - ÇEVRİMDIŞI - - - REGIST... - - - - ONLINE - ÇEVRİMİÇİ - - - ERROR - HATA - - - SUNNYLINK - - - - - SoftwarePanel - - Uninstall %1 - Kaldır %1 - - - UNINSTALL - KALDIR - - - Are you sure you want to uninstall? - Kaldırmak istediğinden eminmisin? - - - CHECK - KONTROL ET - - - Updates are only downloaded while the car is off. - - - - Current Version - - - - Download - - - - Install Update - - - - INSTALL - - - - Target Branch - - - - SELECT - - - - Select a branch - - - - Uninstall - - - - failed to check for update - - - - DOWNLOAD - - - - update available - - - - never - - - - up to date, last checked %1 - - - - - SoftwarePanelSP - - Search Branch - - - - Enter search keywords, or leave blank to list all branches. - - - - No branches found for keywords: %1 - - - - Select a branch - - - - - SshControl - - SSH Keys - SSH Anahtarları - - - Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username other than your own. A comma employee will NEVER ask you to add their GitHub username. - UYARI: Bu, GitHub ayarlarınızdaki tüm ortak anahtarlara SSH erişimi sağlar. Asla kendi kullanıcı adınız dışında bir sonraki başlatılışında çekilir. GitHub kullanıcı adı girmeyin. - - - ADD - EKLE - - - Enter your GitHub username - Github kullanıcı adınızı giriniz - - - LOADING - YÜKLENİYOR - - - REMOVE - KALDIR - - - Username '%1' has no keys on GitHub - Kullanısının '%1' Github erişim anahtarı yok - - - Request timed out - İstek zaman aşımına uğradı - - - Username '%1' doesn't exist on GitHub - Github kullanıcısı %1 bulunamadı - - - - SshToggle - - Enable SSH - SSH aç - - - - SunnylinkPanel - - This is the master switch, it will allow you to cutoff any sunnylink requests should you want to do that. - - - - Enable sunnylink - - - - 🎉Welcome back! We're excited to see you've enabled sunnylink again! 🚀 - - - - 👋Not going to lie, it's sad to see you disabled sunnylink 😢, but we'll be here when you're ready to come back 🎉. - - - - Device ID - - - - N/A - N/A - - - Sponsor Status - - - - SPONSOR - - - - Become a sponsor of sunnypilot to get early access to sunnylink features when they become available. - - - - Pair GitHub Account - - - - PAIR - - - - Pair your GitHub account to grant your device sponsor benefits, including API access on sunnylink. - - - - sunnylink Dongle ID not found. This may be due to weak internet connection or sunnylink registration issue. Please reboot and try again. - - - - Not Sponsor - - - - Paired - - - - Not Paired - - - - THANKS ♥ - - - - Backup Settings - - - - Are you sure you want to backup sunnypilot settings? - - - - Back Up - - - - Restore Settings - - - - Are you sure you want to restore the last backed up sunnypilot settings? - - - - Restore - - - - Backup in progress %1% - - - - Backup Failed - - - - Settings backup completed. - - - - Restore in progress %1% - - - - Restore Failed - - - - Unable to restore the settings, try again later. - - - - Settings restored. Confirm to restart the interface. - - - - - SunnylinkSponsorPopup - - Scan the QR code to login to your GitHub account - - - - Follow the prompts to complete the pairing process - - - - Re-enter the "sunnylink" panel to verify sponsorship status - - - - If sponsorship status was not updated, please contact a moderator on Discord at https://discord.gg/sunnypilot - - - - Scan the QR code to visit sunnyhaibin's GitHub Sponsors page - - - - Choose your sponsorship tier and confirm your support - - - - Join our community on Discord at https://discord.gg/sunnypilot and reach out to a moderator to confirm your sponsor status - - - - Pair your GitHub account - - - - Early Access: Become a sunnypilot Sponsor - - - - - TermsPage - - Decline - Reddet - - - Agree - Kabul et - - - Welcome to sunnypilot - - - - You must accept the Terms and Conditions to use sunnypilot. Read the latest terms at <span style='color: #465BEA;'>https://comma.ai/terms</span> before continuing. - - - - - TogglesPanel - - Enable Lane Departure Warnings - Şerit ihlali uyarı alın - - - Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h). - 50 km/s (31 mph) hızın üzerinde sürüş sırasında aracınız dönüş sinyali vermeden algılanan bir sonraki başlatılışında çekilir. şerit çizgisi ihlalinde şeride geri dönmek için uyarılar alın. - - - Use Metric System - Metrik sistemi kullan - - - Display speed in km/h instead of mph. - Hızı mph yerine km/h şeklinde görüntüleyin. - - - Record and Upload Driver Camera - Sürücü kamerasını kayıt et. - - - Upload data from the driver facing camera and help improve the driver monitoring algorithm. - Sürücüye bakan kamera verisini yükleyin ve Cihazın algoritmasını geliştirmemize yardımcı olun. - - - When enabled, pressing the accelerator pedal will disengage sunnypilot. - Aktifleştirilirse eğer gaz pedalına basınca sunnypilot devre dışı kalır. - - - Experimental Mode - - - - Disengage on Accelerator Pedal - - - - Aggressive - - - - Standard - - - - Relaxed - - - - Driving Personality - - - - sunnypilot defaults to driving in <b>chill mode</b>. Experimental mode enables <b>alpha-level features</b> that aren't ready for chill mode. Experimental features are listed below: - - - - End-to-End Longitudinal Control - - - - Let the driving model control the gas and brakes. sunnypilot will drive as it thinks a human would, including stopping for red lights and stop signs. Since the driving model decides the speed to drive, the set speed will only act as an upper bound. This is an alpha quality feature; mistakes should be expected. - - - - New Driving Visualization - - - - Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control. - - - - An alpha version of sunnypilot longitudinal control can be tested, along with Experimental mode, on non-release branches. - - - - Enable the sunnypilot longitudinal control (alpha) toggle to allow Experimental mode. - - - - Standard is recommended. In aggressive mode, sunnypilot will follow lead cars closer and be more aggressive with the gas and brake. In relaxed mode sunnypilot will stay further away from lead cars. On supported cars, you can cycle through these personalities with your steering wheel distance button. - - - - The driving visualization will transition to the road-facing wide-angle camera at low speeds to better show some turns. The Experimental mode logo will also be shown in the top right corner. - - - - Always-On Driver Monitoring - - - - Enable driver monitoring even when sunnypilot is not engaged. - - - - Enable Dynamic Experimental Control - - - - Enable toggle to allow the model to determine when to use sunnypilot ACC or sunnypilot End to End Longitudinal. - - - - Enable sunnypilot - sunnypilot'u aktifleştir - - - Use the sunnypilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature. - - - - Changing this setting will restart openpilot if the car is powered on. - - - - openpilot longitudinal control may come in a future update. - - - - - Updater - - Update Required - Güncelleme yapılması gerekli - - - An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. The download size is approximately 1GB. - İşletim sistemi güncellemesi gerekmektedir. Lütfen Cihazı daha hızlı günceleyebilmesi için bir sonraki başlatılışında çekilir. Wi-Fi ağına bağlayın. Dosyanın boyutu yaklaşık 1GB dır. - - - Connect to Wi-Fi - Wi-Fi ağına bağlan - - - Install - Yükle - - - Back - Geri - - - Loading... - Yükleniyor... - - - Reboot - Yeniden başlat - - - Update failed - Güncelleme başarız oldu - - - - WiFiPromptWidget - - Open - - - - <span style='font-family: "Noto Color Emoji";'>🔥</span> Firehose Mode <span style='font-family: Noto Color Emoji;'>🔥</span> - - - - Maximize your training data uploads to improve openpilot's driving models. - - - - - WifiUI - - Scanning for networks... - Ağ aranıyor... - - - CONNECTING... - BAĞLANILIYOR... - - - FORGET - UNUT - - - Forget Wi-Fi Network "%1"? - Wi-Fi ağını unut "%1"? - - - Forget - - - - diff --git a/selfdrive/ui/translations/main_zh-CHS.ts b/selfdrive/ui/translations/main_zh-CHS.ts deleted file mode 100644 index 06c6c67152..0000000000 --- a/selfdrive/ui/translations/main_zh-CHS.ts +++ /dev/null @@ -1,2109 +0,0 @@ - - - - - AbstractAlert - - Close - 关闭 - - - Snooze Update - 暂停更新 - - - Reboot and Update - 重启并更新 - - - - AdvancedNetworking - - Back - 返回 - - - Enable Tethering - 启用WiFi热点 - - - Tethering Password - WiFi热点密码 - - - EDIT - 编辑 - - - Enter new tethering password - 输入新的WiFi热点密码 - - - IP Address - IP地址 - - - Enable Roaming - 启用数据漫游 - - - APN Setting - APN设置 - - - Enter APN - 输入APN - - - leave blank for automatic configuration - 留空以自动配置 - - - Cellular Metered - 按流量计费的手机移动网络 - - - Hidden Network - 隐藏的网络 - - - CONNECT - 连线 - - - Enter SSID - 输入 SSID - - - Enter password - 输入密码 - - - for "%1" - 网络名称:"%1" - - - Prevent large data uploads when on a metered cellular connection - - - - default - - - - metered - - - - unmetered - - - - Wi-Fi Network Metered - - - - Prevent large data uploads when on a metered Wi-Fi connection - - - - - AutoLaneChangeTimer - - Auto Lane Change by Blinker - - - - Set a timer to delay the auto lane change operation when the blinker is used. No nudge on the steering wheel is required to auto lane change if a timer is set. Default is Nudge. -Please use caution when using this feature. Only use the blinker when traffic and road conditions permit. - - - - s - - - - Off - - - - Nudge - - - - Nudgeless - - - - - ConfirmationDialog - - Ok - 好的 - - - Cancel - 取消 - - - - DeclinePage - - You must accept the Terms and Conditions in order to use sunnypilot. - 您必须接受条款和条件以使用sunnypilot。 - - - Back - 返回 - - - Decline, uninstall %1 - 拒绝并卸载%1 - - - - DeveloperPanel - - Joystick Debug Mode - 摇杆调试模式 - - - Longitudinal Maneuver Mode - 纵向操控测试模式 - - - Enable ADB - 启用 ADB - - - ADB (Android Debug Bridge) allows connecting to your device over USB or over the network. See https://docs.comma.ai/how-to/connect-to-comma for more info. - ADB(Android调试桥接)允许通过USB或网络连接到您的设备。更多信息请参见 [https://docs.comma.ai/how-to/connect-to-comma](https://docs.comma.ai/how-to/connect-to-comma)。 - - - Enable GitHub runner service - - - - Enables or disables the github runner service. - - - - Error Log - - - - VIEW - 查看 - - - View the error log for sunnypilot crashes. - - - - openpilot Longitudinal Control (Alpha) - - - - WARNING: openpilot longitudinal control is in alpha for this car and will disable Automatic Emergency Braking (AEB). - - - - On this car, sunnypilot defaults to the car's built-in ACC instead of openpilot's longitudinal control. Enable this to switch to openpilot longitudinal control. Enabling Experimental mode is recommended when enabling openpilot longitudinal control alpha. - - - - - DevicePanel - - Dongle ID - 设备ID(Dongle ID) - - - N/A - N/A - - - Serial - 序列号 - - - Driver Camera - 驾驶员摄像头 - - - PREVIEW - 预览 - - - Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off) - 打开并预览驾驶员摄像头,以确保驾驶员监控具有良好视野。(仅熄火时可用) - - - Reset Calibration - 重置设备校准 - - - RESET - 重置 - - - Are you sure you want to reset calibration? - 您确定要重置设备校准吗? - - - Review Training Guide - 新手指南 - - - REVIEW - 查看 - - - Review the rules, features, and limitations of sunnypilot - 查看 sunnypilot 的使用规则,以及其功能和限制 - - - Are you sure you want to review the training guide? - 您确定要查看新手指南吗? - - - Regulatory - 监管信息 - - - VIEW - 查看 - - - Change Language - 切换语言 - - - CHANGE - 切换 - - - Select a language - 选择语言 - - - Reboot - 重启 - - - Power Off - 关机 - - - sunnypilot requires the device to be mounted within 4° left or right and within 5° up or 9° down. sunnypilot is continuously calibrating, resetting is rarely required. - sunnypilot要求设备安装的偏航角在左4°和右4°之间,俯仰角在上5°和下9°之间。一般来说,sunnypilot会持续更新校准,很少需要重置。 - - - Your device is pointed %1° %2 and %3° %4. - 您的设备校准为%1° %2、%3° %4。 - - - down - 朝下 - - - up - 朝上 - - - left - 朝左 - - - right - 朝右 - - - Are you sure you want to reboot? - 您确定要重新启动吗? - - - Disengage to Reboot - 取消sunnypilot以重新启动 - - - Are you sure you want to power off? - 您确定要关机吗? - - - Disengage to Power Off - 取消sunnypilot以关机 - - - Reset - 重置 - - - Review - 预览 - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - 将您的设备与comma connect (connect.comma.ai)配对并领取您的comma prime优惠。 - - - Pair Device - 配对设备 - - - PAIR - 配对 - - - Disengage to Reset Calibration - - - - Resetting calibration will restart openpilot if the car is powered on. - - - - - DevicePanelSP - - Driver Camera Preview - - - - Training Guide - - - - Regulatory - 监管信息 - - - Language - - - - Are you sure you want to review the training guide? - 您确定要查看新手指南吗? - - - Review - 预览 - - - Select a language - 选择语言 - - - Reboot - 重启 - - - Power Off - 关机 - - - Offroad Mode - - - - Are you sure you want to exit Always Offroad mode? - - - - Confirm - 确认 - - - Are you sure you want to enter Always Offroad mode? - - - - Disengage to Enter Always Offroad Mode - - - - Exit Always Offroad - - - - Always Offroad - - - - Quiet Mode - - - - Reset Settings - - - - Are you sure you want to reset all sunnypilot settings to default? Once the settings are reset, there is no going back. - - - - Reset - 重置 - - - The reset cannot be undone. You have been warned. - - - - - DriveStats - - Drives - - - - Hours - - - - ALL TIME - - - - PAST WEEK - - - - KM - - - - Miles - - - - - DriverViewWindow - - camera starting - 正在启动相机 - - - - ExperimentalModeButton - - EXPERIMENTAL MODE ON - 试验模式运行 - - - CHILL MODE ON - 轻松模式运行 - - - - FirehosePanel - - 🔥 Firehose Mode 🔥 - 🔥 训练数据上传模式 🔥 - - - Firehose Mode: ACTIVE - 训练数据上传模式:激活中 - - - ACTIVE - 激活中 - - - For maximum effectiveness, bring your device inside and connect to a good USB-C adapter and Wi-Fi weekly.<br><br>Firehose Mode can also work while you're driving if connected to a hotspot or unlimited SIM card.<br><br><br><b>Frequently Asked Questions</b><br><br><i>Does it matter how or where I drive?</i> Nope, just drive as you normally would.<br><br><i>Do all of my segments get pulled in Firehose Mode?</i> No, we selectively pull a subset of your segments.<br><br><i>What's a good USB-C adapter?</i> Any fast phone or laptop charger should be fine.<br><br><i>Does it matter which software I run?</i> Yes, only upstream sunnypilot (and particular forks) are able to be used for training. - 为了达到最佳效果,请每周将您的设备带回室内,并连接到优质的 USB-C 充电器和 Wi-Fi。<br><br>Firehose 模式在行驶时也能运行,但需连接到移动热点或使用不限流量的 SIM 卡。<br><br><br><b>常见问题</b><br><br><i>我开车的方式或地点有影响吗?</i>不会,请像平常一样驾驶即可。<br><br><i>Firehose 模式会上传所有的驾驶片段吗?</i>不会,我们会选择性地上传部分片段。<br><br><i>什么是好的 USB-C 充电器?</i>任何快速手机或笔记本电脑充电器都应该适用。<br><br><i>我使用的软件版本有影响吗?</i>有的,只有官方 sunnypilot(以及特定的分支)可以用于训练。 - - - <b>%n segment(s)</b> of your driving is in the training dataset so far. - - <b>目前已有 %n 段</b> 您的驾驶数据被纳入训练数据集。 - - - - sunnypilot learns to drive by watching humans, like you, drive. - -Firehose Mode allows you to maximize your training data uploads to improve openpilot's driving models. More data means bigger models, which means better Experimental Mode. - - - - <span stylesheet='font-size: 60px; font-weight: bold; color: #e74c3c;'>INACTIVE</span>: connect to an unmetered network - <span stylesheet='font-size: 60px; font-weight: bold; color: #e74c3c;'>闲置</span>:请连接到不限流量的网络 - - - - HudRenderer - - km/h - km/h - - - mph - mph - - - MAX - 最高定速 - - - - HyundaiSettings - - Off - - - - Dynamic - - - - Predictive - - - - Custom Longitudinal Tuning - - - - This feature can only be used with openpilot longitudinal control enabled. - - - - Enable "Always Offroad" in Device panel, or turn vehicle off to select an option. - - - - Off: Uses default tuning - - - - Dynamic: Adjusts acceleration limits based on current speed - - - - Predictive: Uses future trajectory data to anticipate needed adjustments - - - - Fine-tune your driving experience by adjusting acceleration smoothness with openpilot longitudinal control. - - - - - InputDialog - - Cancel - 取消 - - - Need at least %n character(s)! - - 至少需要 %n 个字符! - - - - - LaneChangeSettings - - Back - 返回 - - - Auto Lane Change: Delay with Blind Spot - - - - Toggle to enable a delay timer for seamless lane changes when blind spot monitoring (BSM) detects a obstructing vehicle, ensuring safe maneuvering. - - - - - LateralPanel - - Modular Assistive Driving System (MADS) - - - - Enable the beloved MADS feature. Disable toggle to revert back to stock sunnypilot engagement/disengagement. - - - - Customize MADS - - - - Customize Lane Change - - - - Enables independent engagements of Automatic Lane Centering (ALC) and Adaptive Cruise Control (ACC). - - - - Start the vehicle to check vehicle compatibility. - - - - This platform supports all MADS settings. - - - - This platform supports limited MADS settings. - - - - - MadsSettings - - Toggle with Main Cruise - - - - Note: For vehicles without LFA/LKAS button, disabling this will prevent lateral control engagement. - - - - Unified Engagement Mode (UEM) - - - - Engage lateral and longitudinal control with cruise control engagement. - - - - Note: Once lateral control is engaged via UEM, it will remain engaged until it is manually disabled via the MADS button or car shut off. - - - - Remain Active - - - - Disengage - - - - Steering Mode on Brake Pedal - - - - Start the vehicle to check vehicle compatibility. - - - - This feature defaults to OFF, and does not allow selection due to vehicle limitations. - - - - This feature defaults to ON, and does not allow selection due to vehicle limitations. - - - - This platform only supports Disengage mode due to vehicle limitations. - - - - Remain Active: ALC will remain active when the brake pedal is pressed. - - - - Pause - - - - Pause: ALC will pause when the brake pedal is pressed. - - - - Disengage: ALC will disengage when the brake pedal is pressed. - - - - Choose how Automatic Lane Centering (ALC) behaves after the brake pedal is manually pressed in sunnypilot. - - - - - MaxTimeOffroad - - Max Time Offroad - - - - Device will automatically shutdown after set time once the engine is turned off.<br/>(30h is the default) - - - - Always On - - - - h - - - - m - - - - (default) - - - - - ModelsPanel - - Current Model - - - - SELECT - 选择 - - - No custom model selected! - - - - Driving - - - - Navigation - - - - Vision - - - - Policy - - - - Downloading %1 model [%2]... (%3%) - - - - %1 model [%2] %3 - - - - downloaded - - - - ready - - - - from cache - - - - %1 model [%2] download failed - - - - %1 model [%2] pending... - - - - Fetching models... - - - - Use Default - - - - Select a Model - - - - Default - - - - Model download has started in the background. - - - - We STRONGLY suggest you to reset calibration. - - - - Would you like to do that now? - - - - Reset Calibration - 重置设备校准 - - - Driving Model Selector - - - - Warning: You are on a metered connection! - - - - Continue - 继续 - - - on Metered - - - - Cancel - 取消 - - - - MultiOptionDialog - - Select - 选择 - - - Cancel - 取消 - - - - Networking - - Advanced - 高级 - - - Enter password - 输入密码 - - - for "%1" - 网络名称:"%1" - - - Wrong password - 密码错误 - - - - NetworkingSP - - Scan - - - - Scanning... - - - - - NeuralNetworkLateralControl - - Neural Network Lateral Control (NNLC) - - - - NNLC is currently not available on this platform. - - - - Start the car to check car compatibility - - - - NNLC Not Loaded - - - - NNLC Loaded - - - - Match - - - - Exact - - - - Fuzzy - - - - Match: "Exact" is ideal, but "Fuzzy" is fine too. - - - - Formerly known as <b>"NNFF"</b>, this replaces the lateral <b>"torque"</b> controller, with one using a neural network trained on each car's (actually, each separate EPS firmware) driving data for increased controls accuracy. - - - - Reach out to the sunnypilot team in the following channel at the sunnypilot Discord server - - - - with feedback, or to provide log data for your car if your car is currently unsupported: - - - - if there are any issues: - - - - and donate logs to get NNLC loaded for your car: - - - - - OffroadAlert - - Immediately connect to the internet to check for updates. If you do not connect to the internet, sunnypilot won't engage in %1 - 请立即连接网络检查更新。如果不连接网络,sunnypilot 将在 %1 后便无法使用 - - - Connect to internet to check for updates. sunnypilot won't automatically start until it connects to internet to check for updates. - 请连接至互联网以检查更新。在连接至互联网并完成更新检查之前,sunnypilot 将不会自动启动。 - - - Unable to download updates -%1 - 无法下载更新 -%1 - - - Taking camera snapshots. System won't start until finished. - 正在使用相机拍摄中。在完成之前,系统将无法启动。 - - - An update to your device's operating system is downloading in the background. You will be prompted to update when it's ready to install. - 一个针对您设备的操作系统更新正在后台下载中。当更新准备好安装时,您将收到提示进行更新。 - - - Device failed to register. It will not connect to or upload to comma.ai servers, and receives no support from comma.ai. If this is an official device, visit https://comma.ai/support. - 设备注册失败。它将无法连接或上传至 comma.ai 服务器,并且无法获得 comma.ai 的支持。如果这是一个官方设备,请访问 https://comma.ai/support。 - - - NVMe drive not mounted. - NVMe固态硬盘未被挂载。 - - - Unsupported NVMe drive detected. Device may draw significantly more power and overheat due to the unsupported NVMe. - 检测到不支持的 NVMe 固态硬盘。您的设备因为使用了不支持的 NVMe 固态硬盘可能会消耗更多电力并更易过热。 - - - sunnypilot was unable to identify your car. Your car is either unsupported or its ECUs are not recognized. Please submit a pull request to add the firmware versions to the proper vehicle. Need help? Join discord.comma.ai. - sunnypilot 无法识别您的车辆。您的车辆可能未被支持,或是其电控单元 (ECU) 未被识别。请提交一个 Pull Request 为您的车辆添加正确的固件版本。需要帮助吗?请加入 discord.comma.ai。 - - - sunnypilot detected a change in the device's mounting position. Ensure the device is fully seated in the mount and the mount is firmly secured to the windshield. - sunnypilot 检测到设备的安装位置发生变化。请确保设备完全安装在支架上,并确保支架牢固地固定在挡风玻璃上。 - - - Device temperature too high. System cooling down before starting. Current internal component temperature: %1 - 设备温度过高。系统正在冷却中,等冷却完毕后才会启动。目前内部组件温度:%1 - - - sunnypilot is now in Always Offroad mode. sunnypilot won't start until Always Offroad mode is disabled. Go to "Settings" -> "Device" to exit Always Offroad mode. - - - - - OffroadHome - - UPDATE - 更新 - - - ALERTS - 警报 - - - ALERT - 警报 - - - - OnroadAlerts - - sunnypilot Unavailable - 无法使用 sunnypilot - - - TAKE CONTROL IMMEDIATELY - 立即接管 - - - Reboot Device - 重启设备 - - - Waiting to start - 等待开始 - - - System Unresponsive - 系统无响应 - - - - PairingPopup - - Pair your device to your comma account - 将您的设备与comma账号配对 - - - Go to https://connect.comma.ai on your phone - 在手机上访问 https://connect.comma.ai - - - Click "add new device" and scan the QR code on the right - 点击“添加新设备”,扫描右侧二维码 - - - Bookmark connect.comma.ai to your home screen to use it like an app - 将 connect.comma.ai 收藏到您的主屏幕,以便像应用程序一样使用它 - - - Please connect to Wi-Fi to complete initial pairing - 请连接 Wi-Fi 以完成初始配对 - - - - ParamControl - - Cancel - 取消 - - - Enable - 启用 - - - - ParamControlSP - - Enable - 启用 - - - Cancel - 取消 - - - - PlatformSelector - - Vehicle - - - - SEARCH - - - - Search your vehicle - - - - Enter model year (e.g., 2021) and model name (Toyota Corolla): - - - - SEARCHING - - - - REMOVE - 删除 - - - This setting will take effect immediately. - - - - This setting will take effect once the device enters offroad state. - - - - Vehicle Selector - - - - Confirm - 确认 - - - Cancel - 取消 - - - No vehicles found for query: %1 - - - - Select a vehicle - - - - Unrecognized Vehicle - - - - Fingerprinted automatically - - - - Manually selected - - - - Not fingerprinted or manually selected - - - - Select vehicle to force fingerprint manually. - - - - Colors represent fingerprint status: - - - - - PrimeAdWidget - - Upgrade Now - 现在升级 - - - Become a comma prime member at connect.comma.ai - 打开connect.comma.ai以注册comma prime会员 - - - PRIME FEATURES: - comma prime特权: - - - Remote access - 远程访问 - - - 24/7 LTE connectivity - 全天候 LTE 连接 - - - 1 year of drive storage - 一年的行驶记录储存空间 - - - Remote snapshots - 远程快照 - - - - PrimeUserWidget - - ✓ SUBSCRIBED - ✓ 已订阅 - - - comma prime - comma prime - - - - QObject - - sunnypilot - sunnypilot - - - %n minute(s) ago - - %n 分钟前 - - - - %n hour(s) ago - - %n 小时前 - - - - %n day(s) ago - - %n 天前 - - - - now - 现在 - - - - Reset - - Reset failed. Reboot to try again. - 重置失败。 重新启动以重试。 - - - Are you sure you want to reset your device? - 您确定要重置您的设备吗? - - - System Reset - 恢复出厂设置 - - - Cancel - 取消 - - - Reboot - 重启 - - - Confirm - 确认 - - - Unable to mount data partition. Partition may be corrupted. Press confirm to erase and reset your device. - 无法挂载数据分区。分区可能已经损坏。请确认是否要删除并重新设置。 - - - Resetting device... -This may take up to a minute. - 设备重置中… -这可能需要一分钟的时间。 - - - System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot. - 系统重置已触发。按下“确认”以清除所有内容和设置,按下“取消”以继续启动。 - - - - SettingsWindow - - × - × - - - Device - 设备 - - - Network - 网络 - - - Toggles - 设定 - - - Software - 软件 - - - Developer - 开发人员 - - - Firehose - 训练上传 - - - - SettingsWindowSP - - × - × - - - Device - 设备 - - - Network - 网络 - - - sunnylink - - - - Toggles - 设定 - - - Software - 软件 - - - Trips - - - - Vehicle - - - - Developer - 开发人员 - - - Firehose - 训练上传 - - - Steering - - - - Models - - - - Cruise - - - - Visuals - - - - - Setup - - WARNING: Low Voltage - 警告:低电压 - - - Power your device in a car with a harness or proceed at your own risk. - 请使用car harness线束为您的设备供电,或自行承担风险。 - - - Power off - 关机 - - - Continue - 继续 - - - Getting Started - 开始设置 - - - Before we get on the road, let’s finish installation and cover some details. - 开始旅程之前,让我们完成安装并介绍一些细节。 - - - Connect to Wi-Fi - 连接到WiFi - - - Back - 返回 - - - Continue without Wi-Fi - 不连接WiFi并继续 - - - Waiting for internet - 等待网络连接 - - - Enter URL - 输入网址 - - - for Custom Software - 以下载自定义软件 - - - Downloading... - 正在下载…… - - - Download Failed - 下载失败 - - - Ensure the entered URL is valid, and the device’s internet connection is good. - 请确保互联网连接良好且输入的URL有效。 - - - Reboot device - 重启设备 - - - Start over - 重来 - - - No custom software found at this URL. - 在此网址找不到自定义软件。 - - - Something went wrong. Reboot the device. - 发生了一些错误。请重新启动您的设备。 - - - Select a language - 选择语言 - - - Choose Software to Install - 选择要安装的软件 - - - sunnypilot - sunnypilot - - - Custom Software - 定制软件 - - - - SetupWidget - - Finish Setup - 完成设置 - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - 将您的设备与comma connect (connect.comma.ai)配对并领取您的comma prime优惠。 - - - Pair device - 配对设备 - - - - Sidebar - - CONNECT - CONNECT - - - OFFLINE - 离线 - - - ONLINE - 在线 - - - ERROR - 连接出错 - - - TEMP - 设备温度 - - - HIGH - 过热 - - - GOOD - 良好 - - - OK - 一般 - - - VEHICLE - 车辆连接 - - - NO - - - - PANDA - PANDA - - - -- - -- - - - Wi-Fi - Wi-Fi - - - ETH - 以太网 - - - 2G - 2G - - - 3G - 3G - - - LTE - LTE - - - 5G - 5G - - - - SidebarSP - - DISABLED - - - - OFFLINE - 离线 - - - REGIST... - - - - ONLINE - 在线 - - - ERROR - 连接出错 - - - SUNNYLINK - - - - - SoftwarePanel - - Updates are only downloaded while the car is off. - 车辆熄火时才能下载升级文件。 - - - Current Version - 当前版本 - - - Download - 下载 - - - Install Update - 安装更新 - - - INSTALL - 安装 - - - Target Branch - 目标分支 - - - SELECT - 选择 - - - Select a branch - 选择分支 - - - UNINSTALL - 卸载 - - - Uninstall %1 - 卸载 %1 - - - Are you sure you want to uninstall? - 您确定要卸载吗? - - - CHECK - 查看 - - - Uninstall - 卸载 - - - failed to check for update - 检查更新失败 - - - up to date, last checked %1 - 已经是最新版本,上次检查时间为 %1 - - - DOWNLOAD - 下载 - - - update available - 有可用的更新 - - - never - 从未更新 - - - - SoftwarePanelSP - - Search Branch - - - - Enter search keywords, or leave blank to list all branches. - - - - No branches found for keywords: %1 - - - - Select a branch - 选择分支 - - - - SshControl - - SSH Keys - SSH密钥 - - - Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username other than your own. A comma employee will NEVER ask you to add their GitHub username. - 警告:这将授予SSH访问权限给您GitHub设置中的所有公钥。切勿输入您自己以外的GitHub用户名。comma员工永远不会要求您添加他们的GitHub用户名。 - - - ADD - 添加 - - - Enter your GitHub username - 输入您的GitHub用户名 - - - LOADING - 正在加载 - - - REMOVE - 删除 - - - Username '%1' has no keys on GitHub - 用户名“%1”在GitHub上没有密钥 - - - Request timed out - 请求超时 - - - Username '%1' doesn't exist on GitHub - GitHub上不存在用户名“%1” - - - - SshToggle - - Enable SSH - 启用SSH - - - - SunnylinkPanel - - This is the master switch, it will allow you to cutoff any sunnylink requests should you want to do that. - - - - Enable sunnylink - - - - 🎉Welcome back! We're excited to see you've enabled sunnylink again! 🚀 - - - - 👋Not going to lie, it's sad to see you disabled sunnylink 😢, but we'll be here when you're ready to come back 🎉. - - - - Device ID - - - - N/A - N/A - - - Sponsor Status - - - - SPONSOR - - - - Become a sponsor of sunnypilot to get early access to sunnylink features when they become available. - - - - Pair GitHub Account - - - - PAIR - 配对 - - - Pair your GitHub account to grant your device sponsor benefits, including API access on sunnylink. - - - - sunnylink Dongle ID not found. This may be due to weak internet connection or sunnylink registration issue. Please reboot and try again. - - - - Not Sponsor - - - - Paired - - - - Not Paired - - - - THANKS ♥ - - - - Backup Settings - - - - Are you sure you want to backup sunnypilot settings? - - - - Back Up - - - - Restore Settings - - - - Are you sure you want to restore the last backed up sunnypilot settings? - - - - Restore - - - - Backup in progress %1% - - - - Backup Failed - - - - Settings backup completed. - - - - Restore in progress %1% - - - - Restore Failed - - - - Unable to restore the settings, try again later. - - - - Settings restored. Confirm to restart the interface. - - - - - SunnylinkSponsorPopup - - Scan the QR code to login to your GitHub account - - - - Follow the prompts to complete the pairing process - - - - Re-enter the "sunnylink" panel to verify sponsorship status - - - - If sponsorship status was not updated, please contact a moderator on Discord at https://discord.gg/sunnypilot - - - - Scan the QR code to visit sunnyhaibin's GitHub Sponsors page - - - - Choose your sponsorship tier and confirm your support - - - - Join our community on Discord at https://discord.gg/sunnypilot and reach out to a moderator to confirm your sponsor status - - - - Pair your GitHub account - - - - Early Access: Become a sunnypilot Sponsor - - - - - TermsPage - - Decline - 拒绝 - - - Agree - 同意 - - - Welcome to sunnypilot - 欢迎使用 sunnypilot - - - You must accept the Terms and Conditions to use sunnypilot. Read the latest terms at <span style='color: #465BEA;'>https://comma.ai/terms</span> before continuing. - 您必须接受《条款与条件》才能使用 sunnypilot。在继续之前,请先阅读最新条款:<span style='color: #465BEA;'>https://comma.ai/terms</span>。 - - - - TogglesPanel - - Enable Lane Departure Warnings - 启用车道偏离警告 - - - Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h). - 车速超过31mph(50km/h)时,若检测到车辆越过车道线且未打转向灯,系统将发出警告以提醒您返回车道。 - - - Use Metric System - 使用公制单位 - - - Display speed in km/h instead of mph. - 显示车速时,以km/h代替mph。 - - - Record and Upload Driver Camera - 录制并上传驾驶员摄像头 - - - Upload data from the driver facing camera and help improve the driver monitoring algorithm. - 上传驾驶员摄像头的数据,帮助改进驾驶员监控算法。 - - - Disengage on Accelerator Pedal - 踩油门时取消控制 - - - When enabled, pressing the accelerator pedal will disengage sunnypilot. - 启用后,踩下油门踏板将取消sunnypilot。 - - - Experimental Mode - 测试模式 - - - sunnypilot defaults to driving in <b>chill mode</b>. Experimental mode enables <b>alpha-level features</b> that aren't ready for chill mode. Experimental features are listed below: - sunnypilot 默认 <b>轻松模式</b>驾驶车辆。试验模式启用一些轻松模式之外的 <b>试验性功能</b>。试验性功能包括: - - - Let the driving model control the gas and brakes. sunnypilot will drive as it thinks a human would, including stopping for red lights and stop signs. Since the driving model decides the speed to drive, the set speed will only act as an upper bound. This is an alpha quality feature; mistakes should be expected. - 允许驾驶模型控制加速和制动,sunnypilot将模仿人类驾驶车辆,包括在红灯和停车让行标识前停车。鉴于驾驶模型确定行驶车速,所设定的车速仅作为上限。此功能尚处于早期测试状态,有可能会出现操作错误。 - - - New Driving Visualization - 新驾驶视角 - - - Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control. - 由于此车辆使用自带的ACC纵向控制,当前无法使用试验模式。 - - - Aggressive - 积极 - - - Standard - 标准 - - - Relaxed - 舒适 - - - Driving Personality - 驾驶风格 - - - An alpha version of sunnypilot longitudinal control can be tested, along with Experimental mode, on non-release branches. - 在正式(release)版本以外的分支上,可以测试 sunnypilot 纵向控制的 Alpha 版本以及实验模式。 - - - Enable the sunnypilot longitudinal control (alpha) toggle to allow Experimental mode. - 启用 sunnypilot 纵向控制(alpha)开关以允许实验模式。 - - - End-to-End Longitudinal Control - 端到端纵向控制 - - - Standard is recommended. In aggressive mode, sunnypilot will follow lead cars closer and be more aggressive with the gas and brake. In relaxed mode sunnypilot will stay further away from lead cars. On supported cars, you can cycle through these personalities with your steering wheel distance button. - 推荐使用标准模式。在积极模式下,sunnypilot 会更靠近前方车辆,并在油门和刹车方面更加激进。在放松模式下,sunnypilot 会与前方车辆保持更远距离。在支持的车型上,你可以使用方向盘上的距离按钮来循环切换这些驾驶风格。 - - - The driving visualization will transition to the road-facing wide-angle camera at low speeds to better show some turns. The Experimental mode logo will also be shown in the top right corner. - 在低速时,驾驶可视化将转换为道路朝向的广角摄像头,以更好地展示某些转弯。测试模式标志也将显示在右上角。 - - - Always-On Driver Monitoring - 驾驶员监控常开 - - - Enable driver monitoring even when sunnypilot is not engaged. - 即使在sunnypilot未激活时也启用驾驶员监控。 - - - Enable Dynamic Experimental Control - - - - Enable toggle to allow the model to determine when to use sunnypilot ACC or sunnypilot End to End Longitudinal. - - - - Enable sunnypilot - 启用sunnypilot - - - Use the sunnypilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature. - - - - Changing this setting will restart openpilot if the car is powered on. - - - - openpilot longitudinal control may come in a future update. - - - - - Updater - - Update Required - 需要更新 - - - An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. The download size is approximately 1GB. - 操作系统需要更新。请将您的设备连接到WiFi以获取更快的更新体验。下载大小约为1GB。 - - - Connect to Wi-Fi - 连接到WiFi - - - Install - 安装 - - - Back - 返回 - - - Loading... - 正在加载…… - - - Reboot - 重启 - - - Update failed - 更新失败 - - - - WiFiPromptWidget - - Open - 开启 - - - <span style='font-family: "Noto Color Emoji";'>🔥</span> Firehose Mode <span style='font-family: Noto Color Emoji;'>🔥</span> - <span style='font-family: "Noto Color Emoji";'>🔥</span> 训练数据上传模式 <span style='font-family: Noto Color Emoji;'>🔥</span> - - - Maximize your training data uploads to improve openpilot's driving models. - - - - - WifiUI - - Scanning for networks... - 正在扫描网络…… - - - CONNECTING... - 正在连接…… - - - FORGET - 忽略 - - - Forget Wi-Fi Network "%1"? - 忽略WiFi网络 "%1"? - - - Forget - 忽略 - - - diff --git a/selfdrive/ui/translations/main_zh-CHT.ts b/selfdrive/ui/translations/main_zh-CHT.ts deleted file mode 100644 index c46157e78e..0000000000 --- a/selfdrive/ui/translations/main_zh-CHT.ts +++ /dev/null @@ -1,2109 +0,0 @@ - - - - - AbstractAlert - - Close - 關閉 - - - Snooze Update - 暫停更新 - - - Reboot and Update - 重啟並更新 - - - - AdvancedNetworking - - Back - 回上頁 - - - Enable Tethering - 啟用網路分享 - - - Tethering Password - 網路分享密碼 - - - EDIT - 編輯 - - - Enter new tethering password - 輸入新的網路分享密碼 - - - IP Address - IP 地址 - - - Enable Roaming - 啟用漫遊 - - - APN Setting - APN 設置 - - - Enter APN - 輸入 APN - - - leave blank for automatic configuration - 留空白將自動配置 - - - Cellular Metered - 行動網路 - - - Hidden Network - 隱藏的網路 - - - CONNECT - 連線 - - - Enter SSID - 輸入 SSID - - - Enter password - 輸入密碼 - - - for "%1" - 給 "%1" - - - Prevent large data uploads when on a metered cellular connection - - - - default - - - - metered - - - - unmetered - - - - Wi-Fi Network Metered - - - - Prevent large data uploads when on a metered Wi-Fi connection - - - - - AutoLaneChangeTimer - - Auto Lane Change by Blinker - - - - Set a timer to delay the auto lane change operation when the blinker is used. No nudge on the steering wheel is required to auto lane change if a timer is set. Default is Nudge. -Please use caution when using this feature. Only use the blinker when traffic and road conditions permit. - - - - s - - - - Off - - - - Nudge - - - - Nudgeless - - - - - ConfirmationDialog - - Ok - 確定 - - - Cancel - 取消 - - - - DeclinePage - - You must accept the Terms and Conditions in order to use sunnypilot. - 您必須先接受條款和條件才能使用 sunnypilot。 - - - Back - 回上頁 - - - Decline, uninstall %1 - 拒絕並解除安裝 %1 - - - - DeveloperPanel - - Joystick Debug Mode - 搖桿調試模式 - - - Longitudinal Maneuver Mode - 縱向操控測試模式 - - - Enable ADB - 啟用 ADB - - - ADB (Android Debug Bridge) allows connecting to your device over USB or over the network. See https://docs.comma.ai/how-to/connect-to-comma for more info. - ADB(Android 調試橋接)允許通過 USB 或網絡連接到您的設備。更多信息請參見 [https://docs.comma.ai/how-to/connect-to-comma](https://docs.comma.ai/how-to/connect-to-comma)。 - - - Enable GitHub runner service - - - - Enables or disables the github runner service. - - - - Error Log - - - - VIEW - 觀看 - - - View the error log for sunnypilot crashes. - - - - openpilot Longitudinal Control (Alpha) - - - - WARNING: openpilot longitudinal control is in alpha for this car and will disable Automatic Emergency Braking (AEB). - - - - On this car, sunnypilot defaults to the car's built-in ACC instead of openpilot's longitudinal control. Enable this to switch to openpilot longitudinal control. Enabling Experimental mode is recommended when enabling openpilot longitudinal control alpha. - - - - - DevicePanel - - Dongle ID - Dongle ID - - - N/A - 無法使用 - - - Serial - 序號 - - - Driver Camera - 駕駛員監控鏡頭 - - - PREVIEW - 預覽 - - - Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off) - 預覽駕駛員監控鏡頭畫面,以確保其具有良好視野。(僅在熄火時可用) - - - Reset Calibration - 重設校準 - - - RESET - 重設 - - - Are you sure you want to reset calibration? - 您確定要重設校準嗎? - - - Review Training Guide - 觀看使用教學 - - - REVIEW - 觀看 - - - Review the rules, features, and limitations of sunnypilot - 觀看 sunnypilot 的使用規則、功能和限制 - - - Are you sure you want to review the training guide? - 您確定要觀看使用教學嗎? - - - Regulatory - 法規/監管 - - - VIEW - 觀看 - - - Change Language - 更改語言 - - - CHANGE - 更改 - - - Select a language - 選擇語言 - - - Reboot - 重新啟動 - - - Power Off - 關機 - - - sunnypilot requires the device to be mounted within 4° left or right and within 5° up or 9° down. sunnypilot is continuously calibrating, resetting is rarely required. - sunnypilot 需要將裝置固定在左右偏差 4° 以內,朝上偏差 5° 以內或朝下偏差 9° 以內。鏡頭在後台會持續自動校準,很少有需要重置的情況。 - - - Your device is pointed %1° %2 and %3° %4. - 你的裝置目前朝%2 %1° 以及朝%4 %3° 。 - - - down - - - - up - - - - left - - - - right - - - - Are you sure you want to reboot? - 您確定要重新啟動嗎? - - - Disengage to Reboot - 請先取消控車才能重新啟動 - - - Are you sure you want to power off? - 您確定您要關機嗎? - - - Disengage to Power Off - 請先取消控車才能關機 - - - Reset - 重設 - - - Review - 回顧 - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - 將您的裝置與 comma connect (connect.comma.ai) 配對並領取您的 comma 高級會員優惠。 - - - Pair Device - 配對裝置 - - - PAIR - 配對 - - - Disengage to Reset Calibration - - - - Resetting calibration will restart openpilot if the car is powered on. - - - - - DevicePanelSP - - Driver Camera Preview - - - - Training Guide - - - - Regulatory - 法規/監管 - - - Language - - - - Are you sure you want to review the training guide? - 您確定要觀看使用教學嗎? - - - Review - 回顧 - - - Select a language - 選擇語言 - - - Reboot - 重新啟動 - - - Power Off - 關機 - - - Offroad Mode - - - - Are you sure you want to exit Always Offroad mode? - - - - Confirm - 確認 - - - Are you sure you want to enter Always Offroad mode? - - - - Disengage to Enter Always Offroad Mode - - - - Exit Always Offroad - - - - Always Offroad - - - - Quiet Mode - - - - Reset Settings - - - - Are you sure you want to reset all sunnypilot settings to default? Once the settings are reset, there is no going back. - - - - Reset - 重設 - - - The reset cannot be undone. You have been warned. - - - - - DriveStats - - Drives - - - - Hours - - - - ALL TIME - - - - PAST WEEK - - - - KM - - - - Miles - - - - - DriverViewWindow - - camera starting - 開啟相機中 - - - - ExperimentalModeButton - - EXPERIMENTAL MODE ON - 實驗模式 ON - - - CHILL MODE ON - 輕鬆模式 ON - - - - FirehosePanel - - 🔥 Firehose Mode 🔥 - 🔥 訓練資料上傳模式 🔥 - - - Firehose Mode: ACTIVE - 訓練資料上傳模式:啟用中 - - - ACTIVE - 啟用中 - - - For maximum effectiveness, bring your device inside and connect to a good USB-C adapter and Wi-Fi weekly.<br><br>Firehose Mode can also work while you're driving if connected to a hotspot or unlimited SIM card.<br><br><br><b>Frequently Asked Questions</b><br><br><i>Does it matter how or where I drive?</i> Nope, just drive as you normally would.<br><br><i>Do all of my segments get pulled in Firehose Mode?</i> No, we selectively pull a subset of your segments.<br><br><i>What's a good USB-C adapter?</i> Any fast phone or laptop charger should be fine.<br><br><i>Does it matter which software I run?</i> Yes, only upstream sunnypilot (and particular forks) are able to be used for training. - 為了達到最佳效果,請每週將您的裝置帶回室內,並連接至優質的 USB-C 充電器與 Wi-Fi。<br><br>訓練資料上傳模式在行駛時也能運作,但需連接至行動熱點或使用不限流量的 SIM 卡。<br><br><br><b>常見問題</b><br><br><i>我開車的方式或地點有影響嗎?</i> 不會,請像平常一樣駕駛即可。<br><br><i>訓練資料上傳模式會上傳所有的駕駛片段嗎?</i>不會,我們會選擇性地上傳部分片段。<br><br><i>什麼是好的 USB-C 充電器?</i>任何快速手機或筆電充電器都應該適用。<br><br><i>我使用的軟體版本有影響嗎?</i>有的,只有官方 sunnypilot(以及特定的分支)可以用於訓練。 - - - <b>%n segment(s)</b> of your driving is in the training dataset so far. - - <b>目前已有 %n 段</b> 您的駕駛數據被納入訓練資料集。 - - - - sunnypilot learns to drive by watching humans, like you, drive. - -Firehose Mode allows you to maximize your training data uploads to improve openpilot's driving models. More data means bigger models, which means better Experimental Mode. - - - - <span stylesheet='font-size: 60px; font-weight: bold; color: #e74c3c;'>INACTIVE</span>: connect to an unmetered network - <span stylesheet='font-size: 60px; font-weight: bold; color: #e74c3c;'>閒置中</span>:請連接到不按流量計費的網絡 - - - - HudRenderer - - km/h - km/h - - - mph - mph - - - MAX - 最高 - - - - HyundaiSettings - - Off - - - - Dynamic - - - - Predictive - - - - Custom Longitudinal Tuning - - - - This feature can only be used with openpilot longitudinal control enabled. - - - - Enable "Always Offroad" in Device panel, or turn vehicle off to select an option. - - - - Off: Uses default tuning - - - - Dynamic: Adjusts acceleration limits based on current speed - - - - Predictive: Uses future trajectory data to anticipate needed adjustments - - - - Fine-tune your driving experience by adjusting acceleration smoothness with openpilot longitudinal control. - - - - - InputDialog - - Cancel - 取消 - - - Need at least %n character(s)! - - 需要至少 %n 個字元! - - - - - LaneChangeSettings - - Back - 回上頁 - - - Auto Lane Change: Delay with Blind Spot - - - - Toggle to enable a delay timer for seamless lane changes when blind spot monitoring (BSM) detects a obstructing vehicle, ensuring safe maneuvering. - - - - - LateralPanel - - Modular Assistive Driving System (MADS) - - - - Enable the beloved MADS feature. Disable toggle to revert back to stock sunnypilot engagement/disengagement. - - - - Customize MADS - - - - Customize Lane Change - - - - Enables independent engagements of Automatic Lane Centering (ALC) and Adaptive Cruise Control (ACC). - - - - Start the vehicle to check vehicle compatibility. - - - - This platform supports all MADS settings. - - - - This platform supports limited MADS settings. - - - - - MadsSettings - - Toggle with Main Cruise - - - - Note: For vehicles without LFA/LKAS button, disabling this will prevent lateral control engagement. - - - - Unified Engagement Mode (UEM) - - - - Engage lateral and longitudinal control with cruise control engagement. - - - - Note: Once lateral control is engaged via UEM, it will remain engaged until it is manually disabled via the MADS button or car shut off. - - - - Remain Active - - - - Disengage - - - - Steering Mode on Brake Pedal - - - - Start the vehicle to check vehicle compatibility. - - - - This feature defaults to OFF, and does not allow selection due to vehicle limitations. - - - - This feature defaults to ON, and does not allow selection due to vehicle limitations. - - - - This platform only supports Disengage mode due to vehicle limitations. - - - - Remain Active: ALC will remain active when the brake pedal is pressed. - - - - Pause - - - - Pause: ALC will pause when the brake pedal is pressed. - - - - Disengage: ALC will disengage when the brake pedal is pressed. - - - - Choose how Automatic Lane Centering (ALC) behaves after the brake pedal is manually pressed in sunnypilot. - - - - - MaxTimeOffroad - - Max Time Offroad - - - - Device will automatically shutdown after set time once the engine is turned off.<br/>(30h is the default) - - - - Always On - - - - h - - - - m - - - - (default) - - - - - ModelsPanel - - Current Model - - - - SELECT - 選取 - - - No custom model selected! - - - - Driving - - - - Navigation - - - - Vision - - - - Policy - - - - Downloading %1 model [%2]... (%3%) - - - - %1 model [%2] %3 - - - - downloaded - - - - ready - - - - from cache - - - - %1 model [%2] download failed - - - - %1 model [%2] pending... - - - - Fetching models... - - - - Use Default - - - - Select a Model - - - - Default - - - - Model download has started in the background. - - - - We STRONGLY suggest you to reset calibration. - - - - Would you like to do that now? - - - - Reset Calibration - 重設校準 - - - Driving Model Selector - - - - Warning: You are on a metered connection! - - - - Continue - 繼續 - - - on Metered - - - - Cancel - 取消 - - - - MultiOptionDialog - - Select - 選擇 - - - Cancel - 取消 - - - - Networking - - Advanced - 進階 - - - Enter password - 輸入密碼 - - - for "%1" - 給 "%1" - - - Wrong password - 密碼錯誤 - - - - NetworkingSP - - Scan - - - - Scanning... - - - - - NeuralNetworkLateralControl - - Neural Network Lateral Control (NNLC) - - - - NNLC is currently not available on this platform. - - - - Start the car to check car compatibility - - - - NNLC Not Loaded - - - - NNLC Loaded - - - - Match - - - - Exact - - - - Fuzzy - - - - Match: "Exact" is ideal, but "Fuzzy" is fine too. - - - - Formerly known as <b>"NNFF"</b>, this replaces the lateral <b>"torque"</b> controller, with one using a neural network trained on each car's (actually, each separate EPS firmware) driving data for increased controls accuracy. - - - - Reach out to the sunnypilot team in the following channel at the sunnypilot Discord server - - - - with feedback, or to provide log data for your car if your car is currently unsupported: - - - - if there are any issues: - - - - and donate logs to get NNLC loaded for your car: - - - - - OffroadAlert - - Immediately connect to the internet to check for updates. If you do not connect to the internet, sunnypilot won't engage in %1 - 請立即連接網路檢查更新。如果不連接網路,sunnypilot 將在 %1 後便無法使用 - - - Connect to internet to check for updates. sunnypilot won't automatically start until it connects to internet to check for updates. - 請連接至網際網路以檢查更新。在連接至網際網路並完成更新檢查之前,sunnypilot 將不會自動啟動。 - - - Unable to download updates -%1 - 無法下載更新 -%1 - - - Taking camera snapshots. System won't start until finished. - 正在使用相機拍攝中。在完成之前,系統將無法啟動。 - - - An update to your device's operating system is downloading in the background. You will be prompted to update when it's ready to install. - 一個有關操作系統的更新正在後台下載中。當更新準備好安裝時,您將收到提示進行更新。 - - - Device failed to register. It will not connect to or upload to comma.ai servers, and receives no support from comma.ai. If this is an official device, visit https://comma.ai/support. - 裝置註冊失敗。它將無法連接或上傳至 comma.ai 伺服器,並且無法獲得 comma.ai 的支援。如果這是一個官方裝置,請訪問 https://comma.ai/support 。 - - - NVMe drive not mounted. - NVMe 固態硬碟未被掛載。 - - - Unsupported NVMe drive detected. Device may draw significantly more power and overheat due to the unsupported NVMe. - 檢測到不支援的 NVMe 固態硬碟。您的裝置因為使用了不支援的 NVMe 固態硬碟可能會消耗更多電力並更易過熱。 - - - sunnypilot was unable to identify your car. Your car is either unsupported or its ECUs are not recognized. Please submit a pull request to add the firmware versions to the proper vehicle. Need help? Join discord.comma.ai. - sunnypilot 無法識別您的車輛。您的車輛可能未被支援,或是其電控單元 (ECU) 未被識別。請提交一個 Pull Request 為您的車輛添加正確的韌體版本。需要幫助嗎?請加入 discord.comma.ai 。 - - - sunnypilot detected a change in the device's mounting position. Ensure the device is fully seated in the mount and the mount is firmly secured to the windshield. - sunnypilot 偵測到裝置的安裝位置發生變化。請確保裝置完全安裝在支架上,並確保支架牢固地固定在擋風玻璃上。 - - - Device temperature too high. System cooling down before starting. Current internal component temperature: %1 - 裝置溫度過高。系統正在冷卻中,等冷卻完畢後才會啟動。目前內部組件溫度:%1 - - - sunnypilot is now in Always Offroad mode. sunnypilot won't start until Always Offroad mode is disabled. Go to "Settings" -> "Device" to exit Always Offroad mode. - - - - - OffroadHome - - UPDATE - 更新 - - - ALERTS - 提醒 - - - ALERT - 提醒 - - - - OnroadAlerts - - sunnypilot Unavailable - 無法使用 sunnypilot - - - TAKE CONTROL IMMEDIATELY - 立即接管 - - - Reboot Device - 請重新啟裝置 - - - Waiting to start - 等待開始 - - - System Unresponsive - 系統無回應 - - - - PairingPopup - - Pair your device to your comma account - 將裝置與您的 comma 帳號配對 - - - Go to https://connect.comma.ai on your phone - 用手機連至 https://connect.comma.ai - - - Click "add new device" and scan the QR code on the right - 點選 "add new device" 後掃描右邊的二維碼 - - - Bookmark connect.comma.ai to your home screen to use it like an app - 將 connect.comma.ai 加入您的主螢幕,以便像手機 App 一樣使用它 - - - Please connect to Wi-Fi to complete initial pairing - 請連接 Wi-Fi 以完成初始配對 - - - - ParamControl - - Cancel - 取消 - - - Enable - 啟用 - - - - ParamControlSP - - Enable - 啟用 - - - Cancel - 取消 - - - - PlatformSelector - - Vehicle - - - - SEARCH - - - - Search your vehicle - - - - Enter model year (e.g., 2021) and model name (Toyota Corolla): - - - - SEARCHING - - - - REMOVE - 移除 - - - This setting will take effect immediately. - - - - This setting will take effect once the device enters offroad state. - - - - Vehicle Selector - - - - Confirm - 確認 - - - Cancel - 取消 - - - No vehicles found for query: %1 - - - - Select a vehicle - - - - Unrecognized Vehicle - - - - Fingerprinted automatically - - - - Manually selected - - - - Not fingerprinted or manually selected - - - - Select vehicle to force fingerprint manually. - - - - Colors represent fingerprint status: - - - - - PrimeAdWidget - - Upgrade Now - 馬上升級 - - - Become a comma prime member at connect.comma.ai - 成為 connect.comma.ai 的高級會員 - - - PRIME FEATURES: - 高級會員特點: - - - Remote access - 遠端存取 - - - 24/7 LTE connectivity - 24/7 LTE 連線 - - - 1 year of drive storage - 一年的行駛記錄儲存空間 - - - Remote snapshots - 遠端快照 - - - - PrimeUserWidget - - ✓ SUBSCRIBED - ✓ 已訂閱 - - - comma prime - comma 高級會員 - - - - QObject - - sunnypilot - sunnypilot - - - %n minute(s) ago - - %n 分鐘前 - - - - %n hour(s) ago - - %n 小時前 - - - - %n day(s) ago - - %n 天前 - - - - now - 現在 - - - - Reset - - Reset failed. Reboot to try again. - 重設失敗。請重新啟動後再試。 - - - Are you sure you want to reset your device? - 您確定要重設你的裝置嗎? - - - System Reset - 系統重設 - - - Cancel - 取消 - - - Reboot - 重新啟動 - - - Confirm - 確認 - - - Unable to mount data partition. Partition may be corrupted. Press confirm to erase and reset your device. - 無法掛載資料分割區。分割區可能已經毀損。請確認是否要刪除並重置。 - - - Resetting device... -This may take up to a minute. - 重置中… -這可能需要一分鐘的時間。 - - - System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot. - 系統重設已啟動。按下「確認」以清除所有內容和設定,或按下「取消」以繼續開機。 - - - - SettingsWindow - - × - × - - - Device - 裝置 - - - Network - 網路 - - - Toggles - 設定 - - - Software - 軟體 - - - Developer - 開發人員 - - - Firehose - 訓練上傳 - - - - SettingsWindowSP - - × - × - - - Device - 裝置 - - - Network - 網路 - - - sunnylink - - - - Toggles - 設定 - - - Software - 軟體 - - - Trips - - - - Vehicle - - - - Developer - 開發人員 - - - Firehose - 訓練上傳 - - - Steering - - - - Models - - - - Cruise - - - - Visuals - - - - - Setup - - WARNING: Low Voltage - 警告:電壓過低 - - - Power your device in a car with a harness or proceed at your own risk. - 請使用車上 harness 提供的電源,若繼續的話您需要自擔風險。 - - - Power off - 關機 - - - Continue - 繼續 - - - Getting Started - 入門 - - - Before we get on the road, let’s finish installation and cover some details. - 在我們上路之前,讓我們完成安裝並介紹一些細節。 - - - Connect to Wi-Fi - 連接到無線網路 - - - Back - 回上頁 - - - Continue without Wi-Fi - 在沒有 Wi-Fi 的情況下繼續 - - - Waiting for internet - 連接至網路中 - - - Enter URL - 輸入網址 - - - for Custom Software - 訂製的軟體 - - - Downloading... - 下載中… - - - Download Failed - 下載失敗 - - - Ensure the entered URL is valid, and the device’s internet connection is good. - 請確定您輸入的是有效的安裝網址,並且確定裝置的網路連線狀態良好。 - - - Reboot device - 重新啟動 - - - Start over - 重新開始 - - - No custom software found at this URL. - 在此網址找不到自訂軟體。 - - - Something went wrong. Reboot the device. - 發生了一些錯誤。請重新啟動您的裝置。 - - - Select a language - 選擇語言 - - - Choose Software to Install - 選擇要安裝的軟體 - - - sunnypilot - sunnypilot - - - Custom Software - 自訂軟體 - - - - SetupWidget - - Finish Setup - 完成設置 - - - Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer. - 將您的裝置與 comma connect (connect.comma.ai) 配對並領取您的 comma 高級會員優惠。 - - - Pair device - 配對裝置 - - - - Sidebar - - CONNECT - 雲端服務 - - - OFFLINE - 已離線 - - - ONLINE - 已連線 - - - ERROR - 錯誤 - - - TEMP - 溫度 - - - HIGH - 偏高 - - - GOOD - 正常 - - - OK - 一般 - - - VEHICLE - 車輛通訊 - - - NO - 未連線 - - - PANDA - 車輛通訊 - - - -- - -- - - - Wi-Fi - Wi-Fi - - - ETH - ETH - - - 2G - 2G - - - 3G - 3G - - - LTE - LTE - - - 5G - 5G - - - - SidebarSP - - DISABLED - - - - OFFLINE - 已離線 - - - REGIST... - - - - ONLINE - 已連線 - - - ERROR - 錯誤 - - - SUNNYLINK - - - - - SoftwarePanel - - Updates are only downloaded while the car is off. - 系統更新只會在熄火時下載。 - - - Current Version - 當前版本 - - - Download - 下載 - - - Install Update - 安裝更新 - - - INSTALL - 安裝 - - - Target Branch - 目標分支 - - - SELECT - 選取 - - - Select a branch - 選取一個分支 - - - UNINSTALL - 解除安裝 - - - Uninstall %1 - 解除安裝 %1 - - - Are you sure you want to uninstall? - 您確定您要解除安裝嗎? - - - CHECK - 檢查 - - - Uninstall - 解除安裝 - - - failed to check for update - 檢查更新失敗 - - - up to date, last checked %1 - 已經是最新版本,上次檢查時間為 %1 - - - DOWNLOAD - 下載 - - - update available - 有可用的更新 - - - never - 從未更新 - - - - SoftwarePanelSP - - Search Branch - - - - Enter search keywords, or leave blank to list all branches. - - - - No branches found for keywords: %1 - - - - Select a branch - 選取一個分支 - - - - SshControl - - SSH Keys - SSH 金鑰 - - - Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username other than your own. A comma employee will NEVER ask you to add their GitHub username. - 警告:這將授權給 GitHub 帳號中所有公鑰 SSH 訪問權限。切勿輸入非您自己的 GitHub 使用者名稱。comma 員工「永遠不會」要求您添加他們的 GitHub 使用者名稱。 - - - ADD - 新增 - - - Enter your GitHub username - 請輸入您 GitHub 的使用者名稱 - - - LOADING - 載入中 - - - REMOVE - 移除 - - - Username '%1' has no keys on GitHub - GitHub 用戶 '%1' 沒有設定任何金鑰 - - - Request timed out - 請求超時 - - - Username '%1' doesn't exist on GitHub - GitHub 用戶 '%1' 不存在 - - - - SshToggle - - Enable SSH - 啟用 SSH 服務 - - - - SunnylinkPanel - - This is the master switch, it will allow you to cutoff any sunnylink requests should you want to do that. - - - - Enable sunnylink - - - - 🎉Welcome back! We're excited to see you've enabled sunnylink again! 🚀 - - - - 👋Not going to lie, it's sad to see you disabled sunnylink 😢, but we'll be here when you're ready to come back 🎉. - - - - Device ID - - - - N/A - 無法使用 - - - Sponsor Status - - - - SPONSOR - - - - Become a sponsor of sunnypilot to get early access to sunnylink features when they become available. - - - - Pair GitHub Account - - - - PAIR - 配對 - - - Pair your GitHub account to grant your device sponsor benefits, including API access on sunnylink. - - - - sunnylink Dongle ID not found. This may be due to weak internet connection or sunnylink registration issue. Please reboot and try again. - - - - Not Sponsor - - - - Paired - - - - Not Paired - - - - THANKS ♥ - - - - Backup Settings - - - - Are you sure you want to backup sunnypilot settings? - - - - Back Up - - - - Restore Settings - - - - Are you sure you want to restore the last backed up sunnypilot settings? - - - - Restore - - - - Backup in progress %1% - - - - Backup Failed - - - - Settings backup completed. - - - - Restore in progress %1% - - - - Restore Failed - - - - Unable to restore the settings, try again later. - - - - Settings restored. Confirm to restart the interface. - - - - - SunnylinkSponsorPopup - - Scan the QR code to login to your GitHub account - - - - Follow the prompts to complete the pairing process - - - - Re-enter the "sunnylink" panel to verify sponsorship status - - - - If sponsorship status was not updated, please contact a moderator on Discord at https://discord.gg/sunnypilot - - - - Scan the QR code to visit sunnyhaibin's GitHub Sponsors page - - - - Choose your sponsorship tier and confirm your support - - - - Join our community on Discord at https://discord.gg/sunnypilot and reach out to a moderator to confirm your sponsor status - - - - Pair your GitHub account - - - - Early Access: Become a sunnypilot Sponsor - - - - - TermsPage - - Decline - 拒絕 - - - Agree - 接受 - - - Welcome to sunnypilot - 歡迎使用 sunnypilot - - - You must accept the Terms and Conditions to use sunnypilot. Read the latest terms at <span style='color: #465BEA;'>https://comma.ai/terms</span> before continuing. - 您必須接受《條款與條件》才能使用 sunnypilot。在繼續之前,請先閱讀最新條款:<span style='color: #465BEA;'>https://comma.ai/terms</span>。 - - - - TogglesPanel - - Enable Lane Departure Warnings - 啟用車道偏離警告 - - - Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h). - 車速在時速 50 公里 (31 英里) 以上且未打方向燈的情況下,如果偵測到車輛駛出目前車道線時,發出車道偏離警告。 - - - Use Metric System - 使用公制單位 - - - Display speed in km/h instead of mph. - 啟用後,速度單位顯示將從 mp/h 改為 km/h。 - - - Record and Upload Driver Camera - 記錄並上傳駕駛監控影像 - - - Upload data from the driver facing camera and help improve the driver monitoring algorithm. - 上傳駕駛監控的錄影來協助我們提升駕駛監控的準確率。 - - - Disengage on Accelerator Pedal - 油門取消控車 - - - When enabled, pressing the accelerator pedal will disengage sunnypilot. - 啟用後,踩踏油門將會取消 sunnypilot 控制。 - - - Experimental Mode - 實驗模式 - - - sunnypilot defaults to driving in <b>chill mode</b>. Experimental mode enables <b>alpha-level features</b> that aren't ready for chill mode. Experimental features are listed below: - sunnypilot 預設以 <b>輕鬆模式</b> 駕駛。 實驗模式啟用了尚未準備好進入輕鬆模式的 <b>alpha 級功能</b>。實驗功能如下: - - - Let the driving model control the gas and brakes. sunnypilot will drive as it thinks a human would, including stopping for red lights and stop signs. Since the driving model decides the speed to drive, the set speed will only act as an upper bound. This is an alpha quality feature; mistakes should be expected. - 讓駕駛模型來控制油門及煞車。sunnypilot將會模擬人類的駕駛行為,包含在看見紅燈及停止標示時停車。由於車速將由駕駛模型決定,因此您設定的時速將成為速度上限。本功能仍在早期實驗階段,請預期模型有犯錯的可能性。 - - - New Driving Visualization - 新的駕駛視覺介面 - - - Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control. - 因車輛使用內建ACC系統,無法在本車輛上啟動實驗模式。 - - - Aggressive - 積極 - - - Standard - 標準 - - - Relaxed - 舒適 - - - Driving Personality - 駕駛風格 - - - An alpha version of sunnypilot longitudinal control can be tested, along with Experimental mode, on non-release branches. - 在正式 (release) 版以外的分支上可以測試 sunnypilot 縱向控制的 Alpha 版本以及實驗模式。 - - - Enable the sunnypilot longitudinal control (alpha) toggle to allow Experimental mode. - 啟用 sunnypilot 縱向控制(alpha)切換以允許實驗模式。 - - - End-to-End Longitudinal Control - 端到端縱向控制 - - - Standard is recommended. In aggressive mode, sunnypilot will follow lead cars closer and be more aggressive with the gas and brake. In relaxed mode sunnypilot will stay further away from lead cars. On supported cars, you can cycle through these personalities with your steering wheel distance button. - 建議使用標準模式。在積極模式下,sunnypilot 會更接近前車並更積極地使用油門和剎車。在輕鬆模式下,sunnypilot 會與前車保持較遠距離。對於支援的汽車,您可以使用方向盤上的距離按鈕來切換這些駕駛風格。 - - - The driving visualization will transition to the road-facing wide-angle camera at low speeds to better show some turns. The Experimental mode logo will also be shown in the top right corner. - 在低速時,駕駛可視化將切換至道路朝向的廣角攝影機,以更好地顯示某些彎道。在右上角還會顯示「實驗模式」的標誌。 - - - Always-On Driver Monitoring - 駕駛監控常開 - - - Enable driver monitoring even when sunnypilot is not engaged. - 即使在sunnypilot未激活時也啟用駕駛監控。 - - - Enable Dynamic Experimental Control - - - - Enable toggle to allow the model to determine when to use sunnypilot ACC or sunnypilot End to End Longitudinal. - - - - Enable sunnypilot - 啟用 sunnypilot - - - Use the sunnypilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature. - - - - Changing this setting will restart openpilot if the car is powered on. - - - - openpilot longitudinal control may come in a future update. - - - - - Updater - - Update Required - 系統更新 - - - An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. The download size is approximately 1GB. - 需要進行作業系統更新。建議將您的裝置連接上 Wi-Fi 獲得更快的更新下載。下載大小約為 1GB。 - - - Connect to Wi-Fi - 連接到無線網路 - - - Install - 安裝 - - - Back - 回上頁 - - - Loading... - 載入中… - - - Reboot - 重新啟動 - - - Update failed - 更新失敗 - - - - WiFiPromptWidget - - Open - 開啟 - - - <span style='font-family: "Noto Color Emoji";'>🔥</span> Firehose Mode <span style='font-family: Noto Color Emoji;'>🔥</span> - <span style='font-family: "Noto Color Emoji";'>🔥</span> 訓練資料上傳模式 <span style='font-family: Noto Color Emoji;'>🔥</span> - - - Maximize your training data uploads to improve openpilot's driving models. - - - - - WifiUI - - Scanning for networks... - 掃描無線網路中... - - - CONNECTING... - 連線中... - - - FORGET - 清除 - - - Forget Wi-Fi Network "%1"? - 清除 Wi-Fi 網路 "%1"? - - - Forget - 清除 - - - diff --git a/selfdrive/ui/ui.cc b/selfdrive/ui/ui.cc deleted file mode 100644 index c9dc70cdff..0000000000 --- a/selfdrive/ui/ui.cc +++ /dev/null @@ -1,235 +0,0 @@ -#include "selfdrive/ui/ui.h" - -#include -#include - -#include - -#include "common/transformations/orientation.hpp" -#include "common/swaglog.h" -#include "common/util.h" -#include "common/watchdog.h" -#include "qt/util.h" -#include "system/hardware/hw.h" - -#define BACKLIGHT_DT 0.05 -#define BACKLIGHT_TS 10.00 - -void update_sockets(UIState *s) { - s->sm->update(0); -} - -void update_state(UIState *s) { - SubMaster &sm = *(s->sm); - UIScene &scene = s->scene; - - if (sm.updated("liveCalibration")) { - auto list2rot = [](const capnp::List::Reader &rpy_list) ->Eigen::Matrix3f { - return euler2rot({rpy_list[0], rpy_list[1], rpy_list[2]}).cast(); - }; - - auto live_calib = sm["liveCalibration"].getLiveCalibration(); - if (live_calib.getCalStatus() == cereal::LiveCalibrationData::Status::CALIBRATED) { - auto device_from_calib = list2rot(live_calib.getRpyCalib()); - auto wide_from_device = list2rot(live_calib.getWideFromDeviceEuler()); - s->scene.view_from_calib = VIEW_FROM_DEVICE * device_from_calib; - s->scene.view_from_wide_calib = VIEW_FROM_DEVICE * wide_from_device * device_from_calib; - } else { - s->scene.view_from_calib = s->scene.view_from_wide_calib = VIEW_FROM_DEVICE; - } - } - if (sm.updated("pandaStates")) { - auto pandaStates = sm["pandaStates"].getPandaStates(); - if (pandaStates.size() > 0) { - scene.pandaType = pandaStates[0].getPandaType(); - - if (scene.pandaType != cereal::PandaState::PandaType::UNKNOWN) { - scene.ignition = false; - for (const auto& pandaState : pandaStates) { - scene.ignition |= pandaState.getIgnitionLine() || pandaState.getIgnitionCan(); - } - } - } - } else if ((s->sm->frame - s->sm->rcv_frame("pandaStates")) > 5*UI_FREQ) { - scene.pandaType = cereal::PandaState::PandaType::UNKNOWN; - } - if (sm.updated("wideRoadCameraState")) { - auto cam_state = sm["wideRoadCameraState"].getWideRoadCameraState(); - float scale = (cam_state.getSensor() == cereal::FrameData::ImageSensor::AR0231) ? 6.0f : 1.0f; - scene.light_sensor = std::max(100.0f - scale * cam_state.getExposureValPercent(), 0.0f); - } else if (!sm.allAliveAndValid({"wideRoadCameraState"})) { - scene.light_sensor = -1; - } - scene.started = sm["deviceState"].getDeviceState().getStarted() && scene.ignition; -} - -void ui_update_params(UIState *s) { - auto params = Params(); - s->scene.is_metric = params.getBool("IsMetric"); -} - -void UIState::updateStatus() { - if (scene.started && (sm->updated("selfdriveState") || sm->updated("selfdriveStateSP"))) { - auto ss = (*sm)["selfdriveState"].getSelfdriveState(); - auto mads = (*sm)["selfdriveStateSP"].getSelfdriveStateSP().getMads(); - auto state = ss.getState(); - auto state_mads = mads.getState(); - if (state == cereal::SelfdriveState::OpenpilotState::PRE_ENABLED || state == cereal::SelfdriveState::OpenpilotState::OVERRIDING || - state_mads == cereal::ModularAssistiveDrivingSystem::ModularAssistiveDrivingSystemState::PAUSED || - state_mads == cereal::ModularAssistiveDrivingSystem::ModularAssistiveDrivingSystemState::OVERRIDING) { - status = STATUS_OVERRIDE; - } else { - if (mads.getAvailable()) { - if (mads.getEnabled() && ss.getEnabled()) { - status = STATUS_ENGAGED; - } else if (mads.getEnabled()) { - status = STATUS_LAT_ONLY; - } else if (ss.getEnabled()) { - status = STATUS_LONG_ONLY; - } else { - status = STATUS_DISENGAGED; - } - } else { - status = ss.getEnabled() ? STATUS_ENGAGED : STATUS_DISENGAGED; - } - } - } - - if (engaged() != engaged_prev) { - engaged_prev = engaged(); - emit engagedChanged(engaged()); - } - - // Handle onroad/offroad transition - if (scene.started != started_prev || sm->frame == 1) { - if (scene.started) { - status = STATUS_DISENGAGED; - scene.started_frame = sm->frame; - } - started_prev = scene.started; - emit offroadTransition(!scene.started); - } -} - -UIState::UIState(QObject *parent) : QObject(parent) { - sm = std::make_unique(std::vector{ - "modelV2", "controlsState", "liveCalibration", "radarState", "deviceState", - "pandaStates", "carParams", "driverMonitoringState", "carState", "driverStateV2", - "wideRoadCameraState", "managerState", "selfdriveState", "longitudinalPlan", - }); - prime_state = new PrimeState(this); - language = QString::fromStdString(Params().get("LanguageSetting")); - -#ifndef SUNNYPILOT - // update timer - timer = new QTimer(this); - QObject::connect(timer, &QTimer::timeout, this, &UIState::update); - timer->start(1000 / UI_FREQ); -#endif -} - -void UIState::update() { -#ifndef SUNNYPILOT - update_sockets(this); - update_state(this); - updateStatus(); - - if (sm->frame % UI_FREQ == 0) { - watchdog_kick(nanos_since_boot()); - } - emit uiUpdate(*this); -#endif -} - -Device::Device(QObject *parent) : brightness_filter(BACKLIGHT_OFFROAD, BACKLIGHT_TS, BACKLIGHT_DT), QObject(parent) { - setAwake(true); - resetInteractiveTimeout(); -#ifndef SUNNYPILOT - QObject::connect(uiState(), &UIState::uiUpdate, this, &Device::update); -#endif -} - -void Device::update(const UIState &s) { - updateBrightness(s); - updateWakefulness(s); -} - -void Device::setAwake(bool on) { - if (on != awake) { - awake = on; - Hardware::set_display_power(awake); - LOGD("setting display power %d", awake); - emit displayPowerChanged(awake); - } -} - -void Device::resetInteractiveTimeout(int timeout) { - if (timeout == -1) { - timeout = (ignition_on ? 10 : 30); - } - interactive_timeout = timeout * UI_FREQ; -} - -void Device::updateBrightness(const UIState &s) { - int brightness; - int brightness_override = QString::fromStdString(Params().get("Brightness")).toInt(); - float clipped_brightness = offroad_brightness; - if (s.scene.started && s.scene.light_sensor >= 0) { - clipped_brightness = s.scene.light_sensor; - - // CIE 1931 - https://www.photonstophotos.net/GeneralTopics/Exposure/Psychometric_Lightness_and_Gamma.htm - if (clipped_brightness <= 8) { - clipped_brightness = (clipped_brightness / 903.3); - } else { - clipped_brightness = std::pow((clipped_brightness + 16.0) / 116.0, 3.0); - } - - if (brightness_override == 1) { - clipped_brightness = std::clamp(100.0f * clipped_brightness, 1.0f, 100.0f); // Scale back to 1% to 100% - } else if (brightness_override == 0) { - clipped_brightness = std::clamp(100.0f * clipped_brightness, 10.0f, 100.0f); // Scale back to 10% to 100% - } - } - - if (brightness_override == 0 || brightness_override == 1) { - brightness = brightness_filter.update(clipped_brightness); - } else { - brightness = brightness_override; - } - - if (!awake) { - brightness = 0; - } - - if (brightness != last_brightness) { - if (!brightness_future.isRunning()) { - brightness_future = QtConcurrent::run(Hardware::set_brightness, brightness); - last_brightness = brightness; - } - } -} - -void Device::updateWakefulness(const UIState &s) { - bool ignition_just_turned_off = !s.scene.ignition && ignition_on; - ignition_on = s.scene.ignition; - - if (ignition_just_turned_off) { - resetInteractiveTimeout(); - } else if (interactive_timeout > 0 && --interactive_timeout == 0) { - emit interactiveTimeout(); - } - - setAwake(s.scene.ignition || interactive_timeout > 0); -} - -#ifndef SUNNYPILOT -UIState *uiState() { - static UIState ui_state; - return &ui_state; -} - -Device *device() { - static Device _device; - return &_device; -} -#endif diff --git a/selfdrive/ui/ui.h b/selfdrive/ui/ui.h deleted file mode 100644 index 4ead8aecb9..0000000000 --- a/selfdrive/ui/ui.h +++ /dev/null @@ -1,145 +0,0 @@ -#pragma once - -#include -#include -#include - -#include -#include -#include - -#include "cereal/messaging/messaging.h" -#include "common/mat.h" -#include "common/params.h" -#include "common/util.h" -#include "system/hardware/hw.h" -#include "selfdrive/ui/qt/prime_state.h" - -const int UI_BORDER_SIZE = 30; -const int UI_HEADER_HEIGHT = 420; - -const int UI_FREQ = 20; // Hz -const int BACKLIGHT_OFFROAD = 50; - -const Eigen::Matrix3f VIEW_FROM_DEVICE = (Eigen::Matrix3f() << - 0.0, 1.0, 0.0, - 0.0, 0.0, 1.0, - 1.0, 0.0, 0.0).finished(); - -const Eigen::Matrix3f FCAM_INTRINSIC_MATRIX = (Eigen::Matrix3f() << - 2648.0, 0.0, 1928.0 / 2, - 0.0, 2648.0, 1208.0 / 2, - 0.0, 0.0, 1.0).finished(); - -// tici ecam focal probably wrong? magnification is not consistent across frame -// Need to retrain model before this can be changed -const Eigen::Matrix3f ECAM_INTRINSIC_MATRIX = (Eigen::Matrix3f() << - 567.0, 0.0, 1928.0 / 2, - 0.0, 567.0, 1208.0 / 2, - 0.0, 0.0, 1.0).finished(); - -typedef enum UIStatus { - STATUS_DISENGAGED, - STATUS_OVERRIDE, - STATUS_ENGAGED, - STATUS_LAT_ONLY, - STATUS_LONG_ONLY, -} UIStatus; - -const QColor bg_colors [] = { - [STATUS_DISENGAGED] = QColor(0x17, 0x33, 0x49, 0xc8), - [STATUS_OVERRIDE] = QColor(0x91, 0x9b, 0x95, 0xf1), - [STATUS_ENGAGED] = QColor(0x17, 0x86, 0x44, 0xf1), - [STATUS_LAT_ONLY] = QColor(0x00, 0xc8, 0xc8, 0xf1), - [STATUS_LONG_ONLY] = QColor(0x96, 0x1C, 0xA8, 0xf1), -}; - -typedef struct UIScene { - Eigen::Matrix3f view_from_calib = VIEW_FROM_DEVICE; - Eigen::Matrix3f view_from_wide_calib = VIEW_FROM_DEVICE; - cereal::PandaState::PandaType pandaType; - - cereal::LongitudinalPersonality personality; - - float light_sensor = -1; - bool started, ignition, is_metric; - uint64_t started_frame; -} UIScene; - -class UIState : public QObject { - Q_OBJECT - -public: - UIState(QObject* parent = 0); - virtual void updateStatus(); - virtual inline bool engaged() const { - return scene.started && (*sm)["selfdriveState"].getSelfdriveState().getEnabled(); - } - - std::unique_ptr sm; - UIStatus status; - UIScene scene = {}; - QString language; - PrimeState *prime_state; - -signals: - void uiUpdate(const UIState &s); - void offroadTransition(bool offroad); - void engagedChanged(bool engaged); - -protected slots: - virtual void update(); - -protected: - QTimer *timer; - -private: - bool started_prev = false; - bool engaged_prev = false; -}; - -#ifndef SUNNYPILOT -UIState *uiState(); -#endif - -// device management class -class Device : public QObject { - Q_OBJECT - -public: - Device(QObject *parent = 0); - bool isAwake() { return awake; } - void setOffroadBrightness(int brightness) { - offroad_brightness = std::clamp(brightness, 0, 100); - } - -protected: - bool awake = false; - int interactive_timeout = 0; - bool ignition_on = false; - - int offroad_brightness = BACKLIGHT_OFFROAD; - int last_brightness = 0; - FirstOrderFilter brightness_filter; - QFuture brightness_future; - - void updateBrightness(const UIState &s); - void updateWakefulness(const UIState &s); - void setAwake(bool on); - -signals: - void displayPowerChanged(bool on); - void interactiveTimeout(); - -public slots: - void resetInteractiveTimeout(int timeout = -1); - void update(const UIState &s); -}; - -#ifndef SUNNYPILOT -Device *device(); -#endif - -void ui_update_params(UIState *s); -void update_state(UIState *s); -void update_sockets(UIState *s); diff --git a/selfdrive/ui/ui.py b/selfdrive/ui/ui.py deleted file mode 100755 index bb2b431e03..0000000000 --- a/selfdrive/ui/ui.py +++ /dev/null @@ -1,24 +0,0 @@ -#!/usr/bin/env python3 -import pyray as rl -from openpilot.common.watchdog import kick_watchdog -from openpilot.system.ui.lib.application import gui_app -from openpilot.selfdrive.ui.layouts.main import MainLayout -from openpilot.selfdrive.ui.ui_state import ui_state - - -def main(): - gui_app.init_window("UI") - main_layout = MainLayout() - main_layout.set_rect(rl.Rectangle(0, 0, gui_app.width, gui_app.height)) - for _ in gui_app.render(): - ui_state.update() - - # TODO handle brigntness and awake state here - - main_layout.render() - - kick_watchdog() - - -if __name__ == "__main__": - main() diff --git a/selfdrive/ui/ui_state.py b/selfdrive/ui/ui_state.py deleted file mode 100644 index 3738ea6d5d..0000000000 --- a/selfdrive/ui/ui_state.py +++ /dev/null @@ -1,171 +0,0 @@ -import pyray as rl -import time -from collections.abc import Callable -from enum import Enum -from cereal import messaging, log -from openpilot.common.params import Params, UnknownKeyName -from openpilot.selfdrive.ui.lib.prime_state import PrimeState - -UI_BORDER_SIZE = 30 - - -class UIStatus(Enum): - DISENGAGED = "disengaged" - ENGAGED = "engaged" - OVERRIDE = "override" - - -class UIState: - _instance: 'UIState | None' = None - - def __new__(cls): - if cls._instance is None: - cls._instance = super().__new__(cls) - cls._instance._initialize() - return cls._instance - - def _initialize(self): - self.params = Params() - self.sm = messaging.SubMaster( - [ - "modelV2", - "controlsState", - "liveCalibration", - "radarState", - "deviceState", - "pandaStates", - "carParams", - "driverMonitoringState", - "carState", - "driverStateV2", - "roadCameraState", - "wideRoadCameraState", - "managerState", - "selfdriveState", - "longitudinalPlan", - ] - ) - - self.prime_state = PrimeState() - - # UI Status tracking - self.status: UIStatus = UIStatus.DISENGAGED - self.started_frame: int = 0 - self._engaged_prev: bool = False - self._started_prev: bool = False - - # Core state variables - self.is_metric: bool = self.params.get_bool("IsMetric") - self.started: bool = False - self.ignition: bool = False - self.panda_type: log.PandaState.PandaType = log.PandaState.PandaType.unknown - self.personality: log.LongitudinalPersonality = log.LongitudinalPersonality.standard - self.light_sensor: float = -1.0 - - self._update_params() - - @property - def engaged(self) -> bool: - return self.started and self.sm["selfdriveState"].enabled - - def is_onroad(self) -> bool: - return self.started - - def is_offroad(self) -> bool: - return not self.started - - def update(self) -> None: - self.sm.update(0) - self._update_state() - self._update_status() - device.update() - - def _update_state(self) -> None: - # Handle panda states updates - if self.sm.updated["pandaStates"]: - panda_states = self.sm["pandaStates"] - - if len(panda_states) > 0: - # Get panda type from first panda - self.panda_type = panda_states[0].pandaType - # Check ignition status across all pandas - if self.panda_type != log.PandaState.PandaType.unknown: - self.ignition = any(state.ignitionLine or state.ignitionCan for state in panda_states) - elif self.sm.frame - self.sm.recv_frame["pandaStates"] > 5 * rl.get_fps(): - self.panda_type = log.PandaState.PandaType.unknown - - # Handle wide road camera state updates - if self.sm.updated["wideRoadCameraState"]: - cam_state = self.sm["wideRoadCameraState"] - - # Scale factor based on sensor type - scale = 6.0 if cam_state.sensor == 'ar0231' else 1.0 - self.light_sensor = max(100.0 - scale * cam_state.exposureValPercent, 0.0) - elif not self.sm.alive["wideRoadCameraState"] or not self.sm.valid["wideRoadCameraState"]: - self.light_sensor = -1 - - # Update started state - self.started = self.sm["deviceState"].started and self.ignition - - def _update_status(self) -> None: - if self.started and self.sm.updated["selfdriveState"]: - ss = self.sm["selfdriveState"] - state = ss.state - - if state in (log.SelfdriveState.OpenpilotState.preEnabled, log.SelfdriveState.OpenpilotState.overriding): - self.status = UIStatus.OVERRIDE - else: - self.status = UIStatus.ENGAGED if ss.enabled else UIStatus.DISENGAGED - - # Check for engagement state changes - if self.engaged != self._engaged_prev: - self._engaged_prev = self.engaged - - # Handle onroad/offroad transition - if self.started != self._started_prev or self.sm.frame == 1: - if self.started: - self.status = UIStatus.DISENGAGED - self.started_frame = self.sm.frame - - self._started_prev = self.started - - def _update_params(self) -> None: - try: - self.is_metric = self.params.get_bool("IsMetric") - except UnknownKeyName: - self.is_metric = False - - -class Device: - def __init__(self): - self._ignition = False - self._interaction_time: float = 0.0 - self._interactive_timeout_callbacks: list[Callable] = [] - self._prev_timed_out = False - self.reset_interactive_timeout() - - def reset_interactive_timeout(self, timeout: int = -1) -> None: - if timeout == -1: - timeout = 10 if ui_state.ignition else 30 - self._interaction_time = time.monotonic() + timeout - - def add_interactive_timeout_callback(self, callback: Callable): - self._interactive_timeout_callbacks.append(callback) - - def update(self): - # Handle interactive timeout - ignition_just_turned_off = not ui_state.ignition and self._ignition - self._ignition = ui_state.ignition - - interaction_timeout = time.monotonic() > self._interaction_time - if ignition_just_turned_off or rl.is_mouse_button_down(rl.MouseButton.MOUSE_BUTTON_LEFT): - self.reset_interactive_timeout() - elif interaction_timeout and not self._prev_timed_out: - for callback in self._interactive_timeout_callbacks: - callback() - self._prev_timed_out = interaction_timeout - - -# Global instance -ui_state = UIState() -device = Device() diff --git a/selfdrive/ui/update_translations.py b/selfdrive/ui/update_translations.py deleted file mode 100755 index 65880bdad9..0000000000 --- a/selfdrive/ui/update_translations.py +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/env python3 -import argparse -import json -import os - -from openpilot.common.basedir import BASEDIR - -UI_DIR = os.path.join(BASEDIR, "selfdrive", "ui") -TRANSLATIONS_DIR = os.path.join(UI_DIR, "translations") -LANGUAGES_FILE = os.path.join(TRANSLATIONS_DIR, "languages.json") -TRANSLATIONS_INCLUDE_FILE = os.path.join(TRANSLATIONS_DIR, "alerts_generated.h") -PLURAL_ONLY = ["main_en"] # base language, only create entries for strings with plural forms - - -def generate_translations_include(): - # offroad alerts - # TODO translate events from openpilot.selfdrive/controls/lib/events.py - content = "// THIS IS AN AUTOGENERATED FILE, PLEASE EDIT alerts_offroad.json\n" - with open(os.path.join(BASEDIR, "selfdrive/selfdrived/alerts_offroad.json")) as f: - for alert in json.load(f).values(): - content += f'QT_TRANSLATE_NOOP("OffroadAlert", R"({alert["text"]})");\n' - - with open(TRANSLATIONS_INCLUDE_FILE, "w") as f: - f.write(content) - - -def update_translations(vanish: bool = False, translation_files: None | list[str] = None, translations_dir: str = TRANSLATIONS_DIR): - if translation_files is None: - with open(LANGUAGES_FILE) as f: - translation_files = json.load(f).values() - - for file in translation_files: - tr_file = os.path.join(translations_dir, f"{file}.ts") - args = f"lupdate -locations none -recursive {UI_DIR} -ts {tr_file} -I {BASEDIR}" - if vanish: - args += " -no-obsolete" - if file in PLURAL_ONLY: - args += " -pluralonly" - ret = os.system(args) - assert ret == 0 - - -if __name__ == "__main__": - parser = argparse.ArgumentParser(description="Update translation files for UI", - formatter_class=argparse.ArgumentDefaultsHelpFormatter) - parser.add_argument("--vanish", action="store_true", help="Remove translations with source text no longer found") - args = parser.parse_args() - - generate_translations_include() - update_translations(args.vanish) diff --git a/selfdrive/ui/watch3.cc b/selfdrive/ui/watch3.cc deleted file mode 100644 index 258e2a7bd6..0000000000 --- a/selfdrive/ui/watch3.cc +++ /dev/null @@ -1,33 +0,0 @@ -#include -#include - -#include "selfdrive/ui/qt/qt_window.h" -#include "selfdrive/ui/qt/util.h" -#include "selfdrive/ui/qt/widgets/cameraview.h" - -int main(int argc, char *argv[]) { - initApp(argc, argv); - - QApplication a(argc, argv); - QWidget w; - setMainWindow(&w); - - QVBoxLayout *layout = new QVBoxLayout(&w); - layout->setMargin(0); - layout->setSpacing(0); - - { - QHBoxLayout *hlayout = new QHBoxLayout(); - layout->addLayout(hlayout); - hlayout->addWidget(new CameraWidget("camerad", VISION_STREAM_ROAD)); - } - - { - QHBoxLayout *hlayout = new QHBoxLayout(); - layout->addLayout(hlayout); - hlayout->addWidget(new CameraWidget("camerad", VISION_STREAM_DRIVER)); - hlayout->addWidget(new CameraWidget("camerad", VISION_STREAM_WIDE_ROAD)); - } - - return a.exec(); -} diff --git a/selfdrive/ui/widgets/exp_mode_button.py b/selfdrive/ui/widgets/exp_mode_button.py deleted file mode 100644 index 83caf413d1..0000000000 --- a/selfdrive/ui/widgets/exp_mode_button.py +++ /dev/null @@ -1,74 +0,0 @@ -import pyray as rl -from openpilot.common.params import Params -from openpilot.system.ui.lib.application import gui_app, FontWeight -from openpilot.system.ui.lib.widget import Widget - - -class ExperimentalModeButton(Widget): - def __init__(self): - super().__init__() - - self.img_width = 80 - self.horizontal_padding = 50 - self.button_height = 125 - - self.params = Params() - self.experimental_mode = self.params.get_bool("ExperimentalMode") - self.is_pressed = False - - self.chill_pixmap = gui_app.texture("icons/couch.png", self.img_width, self.img_width) - self.experimental_pixmap = gui_app.texture("icons/experimental_grey.png", self.img_width, self.img_width) - - def _get_gradient_colors(self): - alpha = 0xCC if self.is_pressed else 0xFF - - if self.experimental_mode: - return rl.Color(255, 155, 63, alpha), rl.Color(219, 56, 34, alpha) - else: - return rl.Color(20, 255, 171, alpha), rl.Color(35, 149, 255, alpha) - - def _draw_gradient_background(self, rect): - start_color, end_color = self._get_gradient_colors() - rl.draw_rectangle_gradient_h(int(rect.x), int(rect.y), int(rect.width), int(rect.height), - start_color, end_color) - - def _handle_interaction(self, rect): - mouse_pos = rl.get_mouse_position() - mouse_in_rect = rl.check_collision_point_rec(mouse_pos, rect) - - self.is_pressed = mouse_in_rect and rl.is_mouse_button_down(rl.MOUSE_BUTTON_LEFT) - return mouse_in_rect and rl.is_mouse_button_released(rl.MOUSE_BUTTON_LEFT) - - def _render(self, rect): - if self._handle_interaction(rect): - self.experimental_mode = not self.experimental_mode - # TODO: Opening settings for ExperimentalMode - self.params.put_bool("ExperimentalMode", self.experimental_mode) - - rl.draw_rectangle_rounded(rect, 0.08, 20, rl.Color(255, 255, 255, 255)) - - rl.begin_scissor_mode(int(rect.x), int(rect.y), int(rect.width), int(rect.height)) - self._draw_gradient_background(rect) - rl.end_scissor_mode() - - # Draw vertical separator line - line_x = rect.x + rect.width - self.img_width - (2 * self.horizontal_padding) - separator_color = rl.Color(0, 0, 0, 77) # 0x4d = 77 - rl.draw_line_ex(rl.Vector2(line_x, rect.y), rl.Vector2(line_x, rect.y + rect.height), 3, separator_color) - - # Draw text label (left aligned) - text = "EXPERIMENTAL MODE ON" if self.experimental_mode else "CHILL MODE ON" - text_x = rect.x + self.horizontal_padding - text_y = rect.y + rect.height / 2 - 45 // 2 # Center vertically - - rl.draw_text_ex(gui_app.font(FontWeight.NORMAL), text, rl.Vector2(int(text_x), int(text_y)), 45, 0, rl.Color(0, 0, 0, 255)) - - # Draw icon (right aligned) - icon_x = rect.x + rect.width - self.horizontal_padding - self.img_width - icon_y = rect.y + (rect.height - self.img_width) / 2 - icon_rect = rl.Rectangle(icon_x, icon_y, self.img_width, self.img_width) - - # Draw current mode icon - current_icon = self.experimental_pixmap if self.experimental_mode else self.chill_pixmap - source_rect = rl.Rectangle(0, 0, current_icon.width, current_icon.height) - rl.draw_texture_pro(current_icon, source_rect, icon_rect, rl.Vector2(0, 0), 0, rl.Color(255, 255, 255, 255)) diff --git a/selfdrive/ui/widgets/offroad_alerts.py b/selfdrive/ui/widgets/offroad_alerts.py deleted file mode 100644 index aba07139db..0000000000 --- a/selfdrive/ui/widgets/offroad_alerts.py +++ /dev/null @@ -1,330 +0,0 @@ -import json -import pyray as rl -from abc import ABC, abstractmethod -from collections.abc import Callable -from dataclasses import dataclass -from openpilot.common.params import Params -from openpilot.system.hardware import HARDWARE -from openpilot.system.ui.lib.scroll_panel import GuiScrollPanel -from openpilot.system.ui.lib.wrap_text import wrap_text -from openpilot.system.ui.lib.text_measure import measure_text_cached -from openpilot.system.ui.lib.application import gui_app, FontWeight -from openpilot.system.ui.lib.widget import Widget - - -class AlertColors: - HIGH_SEVERITY = rl.Color(226, 44, 44, 255) - LOW_SEVERITY = rl.Color(41, 41, 41, 255) - BACKGROUND = rl.Color(57, 57, 57, 255) - BUTTON = rl.WHITE - BUTTON_TEXT = rl.BLACK - SNOOZE_BG = rl.Color(79, 79, 79, 255) - TEXT = rl.WHITE - - -class AlertConstants: - BUTTON_SIZE = (400, 125) - SNOOZE_BUTTON_SIZE = (550, 125) - REBOOT_BUTTON_SIZE = (600, 125) - MARGIN = 50 - SPACING = 30 - FONT_SIZE = 48 - BORDER_RADIUS = 30 - ALERT_HEIGHT = 120 - ALERT_SPACING = 20 - - -@dataclass -class AlertData: - key: str - text: str - severity: int - visible: bool = False - - -class AbstractAlert(Widget, ABC): - def __init__(self, has_reboot_btn: bool = False): - super().__init__() - self.params = Params() - self.has_reboot_btn = has_reboot_btn - self.dismiss_callback: Callable | None = None - - self.dismiss_btn_rect = rl.Rectangle(0, 0, *AlertConstants.BUTTON_SIZE) - self.snooze_btn_rect = rl.Rectangle(0, 0, *AlertConstants.SNOOZE_BUTTON_SIZE) - self.reboot_btn_rect = rl.Rectangle(0, 0, *AlertConstants.REBOOT_BUTTON_SIZE) - - self.snooze_visible = False - self.content_rect = rl.Rectangle(0, 0, 0, 0) - self.scroll_panel_rect = rl.Rectangle(0, 0, 0, 0) - self.scroll_panel = GuiScrollPanel() - - def set_dismiss_callback(self, callback: Callable): - self.dismiss_callback = callback - - @abstractmethod - def refresh(self) -> bool: - pass - - @abstractmethod - def get_content_height(self) -> float: - pass - - def handle_input(self, mouse_pos: rl.Vector2, mouse_clicked: bool) -> bool: - if not mouse_clicked or not self.scroll_panel.is_touch_valid(): - return False - - if rl.check_collision_point_rec(mouse_pos, self.dismiss_btn_rect): - if self.dismiss_callback: - self.dismiss_callback() - return True - - if self.snooze_visible and rl.check_collision_point_rec(mouse_pos, self.snooze_btn_rect): - self.params.put_bool("SnoozeUpdate", True) - if self.dismiss_callback: - self.dismiss_callback() - return True - - if self.has_reboot_btn and rl.check_collision_point_rec(mouse_pos, self.reboot_btn_rect): - HARDWARE.reboot() - return True - - return False - - def _render(self, rect: rl.Rectangle): - rl.draw_rectangle_rounded(rect, AlertConstants.BORDER_RADIUS / rect.width, 10, AlertColors.BACKGROUND) - - footer_height = AlertConstants.BUTTON_SIZE[1] + AlertConstants.SPACING - content_height = rect.height - 2 * AlertConstants.MARGIN - footer_height - - self.content_rect = rl.Rectangle( - rect.x + AlertConstants.MARGIN, - rect.y + AlertConstants.MARGIN, - rect.width - 2 * AlertConstants.MARGIN, - content_height, - ) - self.scroll_panel_rect = rl.Rectangle( - self.content_rect.x, self.content_rect.y, self.content_rect.width, self.content_rect.height - ) - - self._render_scrollable_content() - self._render_footer(rect) - - def _render_scrollable_content(self): - content_total_height = self.get_content_height() - content_bounds = rl.Rectangle(0, 0, self.scroll_panel_rect.width, content_total_height) - scroll_offset = self.scroll_panel.handle_scroll(self.scroll_panel_rect, content_bounds) - - rl.begin_scissor_mode( - int(self.scroll_panel_rect.x), - int(self.scroll_panel_rect.y), - int(self.scroll_panel_rect.width), - int(self.scroll_panel_rect.height), - ) - - content_rect_with_scroll = rl.Rectangle( - self.scroll_panel_rect.x, - self.scroll_panel_rect.y + scroll_offset.y, - self.scroll_panel_rect.width, - content_total_height, - ) - - self._render_content(content_rect_with_scroll) - rl.end_scissor_mode() - - @abstractmethod - def _render_content(self, content_rect: rl.Rectangle): - pass - - def _render_footer(self, rect: rl.Rectangle): - footer_y = rect.y + rect.height - AlertConstants.MARGIN - AlertConstants.BUTTON_SIZE[1] - font = gui_app.font(FontWeight.MEDIUM) - - self.dismiss_btn_rect.x = rect.x + AlertConstants.MARGIN - self.dismiss_btn_rect.y = footer_y - rl.draw_rectangle_rounded(self.dismiss_btn_rect, 0.3, 10, AlertColors.BUTTON) - - text = "Close" - text_width = measure_text_cached(font, text, AlertConstants.FONT_SIZE).x - text_x = self.dismiss_btn_rect.x + (AlertConstants.BUTTON_SIZE[0] - text_width) // 2 - text_y = self.dismiss_btn_rect.y + (AlertConstants.BUTTON_SIZE[1] - AlertConstants.FONT_SIZE) // 2 - rl.draw_text_ex( - font, text, rl.Vector2(int(text_x), int(text_y)), AlertConstants.FONT_SIZE, 0, AlertColors.BUTTON_TEXT - ) - - if self.snooze_visible: - self.snooze_btn_rect.x = rect.x + rect.width - AlertConstants.MARGIN - AlertConstants.SNOOZE_BUTTON_SIZE[0] - self.snooze_btn_rect.y = footer_y - rl.draw_rectangle_rounded(self.snooze_btn_rect, 0.3, 10, AlertColors.SNOOZE_BG) - - text = "Snooze Update" - text_width = measure_text_cached(font, text, AlertConstants.FONT_SIZE).x - text_x = self.snooze_btn_rect.x + (AlertConstants.SNOOZE_BUTTON_SIZE[0] - text_width) // 2 - text_y = self.snooze_btn_rect.y + (AlertConstants.SNOOZE_BUTTON_SIZE[1] - AlertConstants.FONT_SIZE) // 2 - rl.draw_text_ex(font, text, rl.Vector2(int(text_x), int(text_y)), AlertConstants.FONT_SIZE, 0, AlertColors.TEXT) - - elif self.has_reboot_btn: - self.reboot_btn_rect.x = rect.x + rect.width - AlertConstants.MARGIN - AlertConstants.REBOOT_BUTTON_SIZE[0] - self.reboot_btn_rect.y = footer_y - rl.draw_rectangle_rounded(self.reboot_btn_rect, 0.3, 10, AlertColors.BUTTON) - - text = "Reboot and Update" - text_width = measure_text_cached(font, text, AlertConstants.FONT_SIZE).x - text_x = self.reboot_btn_rect.x + (AlertConstants.REBOOT_BUTTON_SIZE[0] - text_width) // 2 - text_y = self.reboot_btn_rect.y + (AlertConstants.REBOOT_BUTTON_SIZE[1] - AlertConstants.FONT_SIZE) // 2 - rl.draw_text_ex( - font, text, rl.Vector2(int(text_x), int(text_y)), AlertConstants.FONT_SIZE, 0, AlertColors.BUTTON_TEXT - ) - - -class OffroadAlert(AbstractAlert): - def __init__(self): - super().__init__(has_reboot_btn=False) - self.sorted_alerts: list[AlertData] = [] - - def refresh(self): - if not self.sorted_alerts: - self._build_alerts() - - active_count = 0 - connectivity_needed = False - - for alert_data in self.sorted_alerts: - text = "" - bytes_data = self.params.get(alert_data.key) - - if bytes_data: - try: - alert_json = json.loads(bytes_data) - text = alert_json.get("text", "").replace("{}", alert_json.get("extra", "")) - except json.JSONDecodeError: - text = "" - - alert_data.text = text - alert_data.visible = bool(text) - - if alert_data.visible: - active_count += 1 - - if alert_data.key == "Offroad_ConnectivityNeeded" and alert_data.visible: - connectivity_needed = True - - self.snooze_visible = connectivity_needed - return active_count - - def get_content_height(self) -> float: - if not self.sorted_alerts: - return 0 - - total_height = 20 - font = gui_app.font(FontWeight.NORMAL) - - for alert_data in self.sorted_alerts: - if not alert_data.visible: - continue - - text_width = int(self.content_rect.width - 90) - wrapped_lines = wrap_text(font, alert_data.text, AlertConstants.FONT_SIZE, text_width) - line_count = len(wrapped_lines) - text_height = line_count * (AlertConstants.FONT_SIZE + 5) - alert_item_height = max(text_height + 40, AlertConstants.ALERT_HEIGHT) - total_height += alert_item_height + AlertConstants.ALERT_SPACING - - if total_height > 20: - total_height = total_height - AlertConstants.ALERT_SPACING + 20 - - return total_height - - def _build_alerts(self): - self.sorted_alerts = [] - try: - with open("../selfdrived/alerts_offroad.json", "rb") as f: - alerts_config = json.load(f) - for key, config in sorted(alerts_config.items(), key=lambda x: x[1].get("severity", 0), reverse=True): - severity = config.get("severity", 0) - alert_data = AlertData(key=key, text="", severity=severity) - self.sorted_alerts.append(alert_data) - except (FileNotFoundError, json.JSONDecodeError): - pass - - def _render_content(self, content_rect: rl.Rectangle): - y_offset = 20 - font = gui_app.font(FontWeight.NORMAL) - - for alert_data in self.sorted_alerts: - if not alert_data.visible: - continue - - bg_color = AlertColors.HIGH_SEVERITY if alert_data.severity > 0 else AlertColors.LOW_SEVERITY - text_width = int(content_rect.width - 90) - wrapped_lines = wrap_text(font, alert_data.text, AlertConstants.FONT_SIZE, text_width) - line_count = len(wrapped_lines) - text_height = line_count * (AlertConstants.FONT_SIZE + 5) - alert_item_height = max(text_height + 40, AlertConstants.ALERT_HEIGHT) - - alert_rect = rl.Rectangle( - content_rect.x + 10, - content_rect.y + y_offset, - content_rect.width - 30, - alert_item_height, - ) - - rl.draw_rectangle_rounded(alert_rect, 0.2, 10, bg_color) - - text_x = alert_rect.x + 30 - text_y = alert_rect.y + 20 - - for i, line in enumerate(wrapped_lines): - rl.draw_text_ex( - font, - line, - rl.Vector2(text_x, text_y + i * (AlertConstants.FONT_SIZE + 5)), - AlertConstants.FONT_SIZE, - 0, - AlertColors.TEXT, - ) - - y_offset += alert_item_height + AlertConstants.ALERT_SPACING - - -class UpdateAlert(AbstractAlert): - def __init__(self): - super().__init__(has_reboot_btn=True) - self.release_notes = "" - self._wrapped_release_notes = "" - self._cached_content_height: float = 0.0 - - def refresh(self) -> bool: - update_available: bool = self.params.get_bool("UpdateAvailable") - if update_available: - self.release_notes = self.params.get("UpdaterNewReleaseNotes", encoding='utf-8') - self._cached_content_height = 0 - - return update_available - - def get_content_height(self) -> float: - if not self.release_notes: - return 100 - - if self._cached_content_height == 0: - self._wrapped_release_notes = self.release_notes - size = measure_text_cached(gui_app.font(FontWeight.NORMAL), self._wrapped_release_notes, AlertConstants.FONT_SIZE) - self._cached_content_height = max(size.y + 60, 100) - - return self._cached_content_height - - def _render_content(self, content_rect: rl.Rectangle): - if self.release_notes: - rl.draw_text_ex( - gui_app.font(FontWeight.NORMAL), - self._wrapped_release_notes, - rl.Vector2(content_rect.x + 30, content_rect.y + 30), - AlertConstants.FONT_SIZE, - 0.0, - AlertColors.TEXT, - ) - else: - no_notes_text = "No release notes available." - text_width = rl.measure_text(no_notes_text, AlertConstants.FONT_SIZE) - text_x = content_rect.x + (content_rect.width - text_width) // 2 - text_y = content_rect.y + 50 - rl.draw_text(no_notes_text, int(text_x), int(text_y), AlertConstants.FONT_SIZE, AlertColors.TEXT) diff --git a/selfdrive/ui/widgets/pairing_dialog.py b/selfdrive/ui/widgets/pairing_dialog.py deleted file mode 100644 index 2cb1499499..0000000000 --- a/selfdrive/ui/widgets/pairing_dialog.py +++ /dev/null @@ -1,170 +0,0 @@ -import pyray as rl -import qrcode -import numpy as np -import time - -from openpilot.common.api import Api -from openpilot.common.swaglog import cloudlog -from openpilot.common.params import Params -from openpilot.system.ui.lib.application import FontWeight, gui_app -from openpilot.system.ui.lib.wrap_text import wrap_text -from openpilot.system.ui.lib.text_measure import measure_text_cached - - -class PairingDialog: - """Dialog for device pairing with QR code.""" - - QR_REFRESH_INTERVAL = 300 # 5 minutes in seconds - - def __init__(self): - self.params = Params() - self.qr_texture: rl.Texture | None = None - self.last_qr_generation = 0 - - def _get_pairing_url(self) -> str: - try: - dongle_id = self.params.get("DongleId", encoding='utf8') or "" - token = Api(dongle_id).get_token() - except Exception as e: - cloudlog.warning(f"Failed to get pairing token: {e}") - token = "" - return f"https://connect.comma.ai/setup?token={token}" - - def _generate_qr_code(self) -> None: - try: - qr = qrcode.QRCode(version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4) - qr.add_data(self._get_pairing_url()) - qr.make(fit=True) - - pil_img = qr.make_image(fill_color="black", back_color="white").convert('RGBA') - img_array = np.array(pil_img, dtype=np.uint8) - - if self.qr_texture and self.qr_texture.id != 0: - rl.unload_texture(self.qr_texture) - - rl_image = rl.Image() - rl_image.data = rl.ffi.cast("void *", img_array.ctypes.data) - rl_image.width = pil_img.width - rl_image.height = pil_img.height - rl_image.mipmaps = 1 - rl_image.format = rl.PixelFormat.PIXELFORMAT_UNCOMPRESSED_R8G8B8A8 - - self.qr_texture = rl.load_texture_from_image(rl_image) - except Exception as e: - cloudlog.warning(f"QR code generation failed: {e}") - self.qr_texture = None - - def _check_qr_refresh(self) -> None: - current_time = time.time() - if current_time - self.last_qr_generation >= self.QR_REFRESH_INTERVAL: - self._generate_qr_code() - self.last_qr_generation = current_time - - def render(self, rect: rl.Rectangle) -> int: - rl.clear_background(rl.Color(224, 224, 224, 255)) - - self._check_qr_refresh() - - margin = 70 - content_rect = rl.Rectangle(rect.x + margin, rect.y + margin, rect.width - 2 * margin, rect.height - 2 * margin) - y = content_rect.y - - # Close button - close_size = 80 - close_icon = gui_app.texture("icons/close.png", close_size, close_size) - close_rect = rl.Rectangle(content_rect.x, y, close_size, close_size) - - mouse_pos = rl.get_mouse_position() - is_hover = rl.check_collision_point_rec(mouse_pos, close_rect) - is_pressed = rl.is_mouse_button_down(rl.MouseButton.MOUSE_BUTTON_LEFT) - is_released = rl.is_mouse_button_released(rl.MouseButton.MOUSE_BUTTON_LEFT) - - color = rl.Color(180, 180, 180, 150) if (is_hover and is_pressed) else rl.WHITE - rl.draw_texture(close_icon, int(content_rect.x), int(y), color) - - if (is_hover and is_released) or rl.is_key_pressed(rl.KeyboardKey.KEY_ESCAPE): - return 1 - - y += close_size + 40 - - # Title - title = "Pair your device to your comma account" - title_font = gui_app.font(FontWeight.NORMAL) - left_width = int(content_rect.width * 0.5 - 15) - - title_wrapped = wrap_text(title_font, title, 75, left_width) - rl.draw_text_ex(title_font, "\n".join(title_wrapped), rl.Vector2(content_rect.x, y), 75, 0.0, rl.BLACK) - y += len(title_wrapped) * 75 + 60 - - # Two columns: instructions and QR code - remaining_height = content_rect.height - (y - content_rect.y) - right_width = content_rect.width // 2 - 20 - - # Instructions - self._render_instructions(rl.Rectangle(content_rect.x, y, left_width, remaining_height)) - - # QR code - qr_size = min(right_width, content_rect.height) - 40 - qr_x = content_rect.x + left_width + 40 + (right_width - qr_size) // 2 - qr_y = content_rect.y - self._render_qr_code(rl.Rectangle(qr_x, qr_y, qr_size, qr_size)) - - return -1 - - def _render_instructions(self, rect: rl.Rectangle) -> None: - instructions = [ - "Go to https://connect.comma.ai on your phone", - "Click \"add new device\" and scan the QR code on the right", - "Bookmark connect.comma.ai to your home screen to use it like an app", - ] - - font = gui_app.font(FontWeight.BOLD) - y = rect.y - - for i, text in enumerate(instructions): - circle_radius = 25 - circle_x = rect.x + circle_radius + 15 - text_x = rect.x + circle_radius * 2 + 40 - text_width = rect.width - (circle_radius * 2 + 40) - - wrapped = wrap_text(font, text, 47, int(text_width)) - text_height = len(wrapped) * 47 - circle_y = y + text_height // 2 - - # Circle and number - rl.draw_circle(int(circle_x), int(circle_y), circle_radius, rl.Color(70, 70, 70, 255)) - number = str(i + 1) - number_width = measure_text_cached(font, number, 30).x - rl.draw_text(number, int(circle_x - number_width // 2), int(circle_y - 15), 30, rl.WHITE) - - # Text - rl.draw_text_ex(font, "\n".join(wrapped), rl.Vector2(text_x, y), 47, 0.0, rl.BLACK) - y += text_height + 50 - - def _render_qr_code(self, rect: rl.Rectangle) -> None: - if not self.qr_texture: - rl.draw_rectangle_rounded(rect, 0.1, 20, rl.Color(240, 240, 240, 255)) - error_font = gui_app.font(FontWeight.BOLD) - rl.draw_text_ex( - error_font, "QR Code Error", rl.Vector2(rect.x + 20, rect.y + rect.height // 2 - 15), 30, 0.0, rl.RED - ) - return - - source = rl.Rectangle(0, 0, self.qr_texture.width, self.qr_texture.height) - rl.draw_texture_pro(self.qr_texture, source, rect, rl.Vector2(0, 0), 0, rl.WHITE) - - def __del__(self): - if self.qr_texture and self.qr_texture.id != 0: - rl.unload_texture(self.qr_texture) - - -if __name__ == "__main__": - gui_app.init_window("pairing device") - pairing = PairingDialog() - try: - for _ in gui_app.render(): - result = pairing.render(rl.Rectangle(0, 0, gui_app.width, gui_app.height)) - if result != -1: - break - finally: - del pairing diff --git a/selfdrive/ui/widgets/prime.py b/selfdrive/ui/widgets/prime.py deleted file mode 100644 index afdfa33e7a..0000000000 --- a/selfdrive/ui/widgets/prime.py +++ /dev/null @@ -1,62 +0,0 @@ -import pyray as rl - -from openpilot.selfdrive.ui.ui_state import ui_state -from openpilot.system.ui.lib.application import gui_app, FontWeight -from openpilot.system.ui.lib.label import gui_label -from openpilot.system.ui.lib.wrap_text import wrap_text -from openpilot.system.ui.lib.text_measure import measure_text_cached -from openpilot.system.ui.lib.widget import Widget - - -class PrimeWidget(Widget): - """Widget for displaying comma prime subscription status""" - - PRIME_BG_COLOR = rl.Color(51, 51, 51, 255) - - def _render(self, rect): - if ui_state.prime_state.is_prime(): - self._render_for_prime_user(rect) - else: - self._render_for_non_prime_users(rect) - - def _render_for_non_prime_users(self, rect: rl.Rectangle): - """Renders the advertisement for non-Prime users.""" - - rl.draw_rectangle_rounded(rect, 0.02, 10, self.PRIME_BG_COLOR) - - # Layout - x, y = rect.x + 80, rect.y + 90 - w = rect.width - 160 - - # Title - gui_label(rl.Rectangle(x, y, w, 90), "Upgrade Now", 75, font_weight=FontWeight.BOLD) - - # Description with wrapping - desc_y = y + 140 - font = gui_app.font(FontWeight.LIGHT) - wrapped_text = "\n".join(wrap_text(font, "Become a comma prime member at connect.comma.ai", 56, int(w))) - text_size = measure_text_cached(font, wrapped_text, 56) - rl.draw_text_ex(font, wrapped_text, rl.Vector2(x, desc_y), 56, 0, rl.Color(255, 255, 255, 255)) - - # Features section - features_y = desc_y + text_size.y + 50 - gui_label(rl.Rectangle(x, features_y, w, 50), "PRIME FEATURES:", 41, font_weight=FontWeight.BOLD) - - # Feature list - features = ["Remote access", "24/7 LTE connectivity", "1 year of drive storage", "Remote snapshots"] - for i, feature in enumerate(features): - item_y = features_y + 80 + i * 65 - gui_label(rl.Rectangle(x, item_y, 50, 60), "✓", 50, color=rl.Color(70, 91, 234, 255)) - gui_label(rl.Rectangle(x + 60, item_y, w - 60, 60), feature, 50) - - def _render_for_prime_user(self, rect: rl.Rectangle): - """Renders the prime user widget with subscription status.""" - - rl.draw_rectangle_rounded(rl.Rectangle(rect.x, rect.y, rect.width, 230), 0.02, 10, self.PRIME_BG_COLOR) - - x = rect.x + 56 - y = rect.y + 40 - - font = gui_app.font(FontWeight.BOLD) - rl.draw_text_ex(font, "✓ SUBSCRIBED", rl.Vector2(x, y), 41, 0, rl.Color(134, 255, 78, 255)) - rl.draw_text_ex(font, "comma prime", rl.Vector2(x, y + 61), 75, 0, rl.WHITE) diff --git a/selfdrive/ui/widgets/setup.py b/selfdrive/ui/widgets/setup.py deleted file mode 100644 index 4fd56aa522..0000000000 --- a/selfdrive/ui/widgets/setup.py +++ /dev/null @@ -1,94 +0,0 @@ -import pyray as rl -from openpilot.selfdrive.ui.lib.prime_state import PrimeType -from openpilot.selfdrive.ui.widgets.pairing_dialog import PairingDialog -from openpilot.selfdrive.ui.ui_state import ui_state -from openpilot.system.ui.lib.application import gui_app, FontWeight -from openpilot.system.ui.lib.button import gui_button, ButtonStyle -from openpilot.system.ui.lib.wrap_text import wrap_text -from openpilot.system.ui.lib.widget import Widget - - -class SetupWidget(Widget): - def __init__(self): - super().__init__() - self._open_settings_callback = None - self._pairing_dialog: PairingDialog | None = None - - def set_open_settings_callback(self, callback): - self._open_settings_callback = callback - - def _render(self, rect: rl.Rectangle): - if ui_state.prime_state.get_type() == PrimeType.UNPAIRED: - self._render_registration(rect) - else: - self._render_firehose_prompt(rect) - - def _render_registration(self, rect: rl.Rectangle): - """Render registration prompt.""" - - rl.draw_rectangle_rounded(rl.Rectangle(rect.x, rect.y, rect.width, 590), 0.02, 20, rl.Color(51, 51, 51, 255)) - - x = rect.x + 64 - y = rect.y + 48 - w = rect.width - 128 - - # Title - font = gui_app.font(FontWeight.BOLD) - rl.draw_text_ex(font, "Finish Setup", rl.Vector2(x, y), 75, 0, rl.WHITE) - y += 113 # 75 + 38 spacing - - # Description - desc = "Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer." - light_font = gui_app.font(FontWeight.LIGHT) - wrapped = wrap_text(light_font, desc, 50, int(w)) - for line in wrapped: - rl.draw_text_ex(light_font, line, rl.Vector2(x, y), 50, 0, rl.WHITE) - y += 50 - - button_rect = rl.Rectangle(x, y + 50, w, 128) - if gui_button(button_rect, "Pair device", button_style=ButtonStyle.PRIMARY): - self._show_pairing() - - def _render_firehose_prompt(self, rect: rl.Rectangle): - """Render firehose prompt widget.""" - - rl.draw_rectangle_rounded(rl.Rectangle(rect.x, rect.y, rect.width, 450), 0.02, 20, rl.Color(51, 51, 51, 255)) - - # Content margins (56, 40, 56, 40) - x = rect.x + 56 - y = rect.y + 40 - w = rect.width - 112 - spacing = 42 - - # Title with fire emojis - title_font = gui_app.font(FontWeight.MEDIUM) - title_text = "Firehose Mode" - rl.draw_text_ex(title_font, title_text, rl.Vector2(x, y), 64, 0, rl.WHITE) - y += 64 + spacing - - # Description - desc_font = gui_app.font(FontWeight.NORMAL) - desc_text = "Maximize your training data uploads to improve openpilot's driving models." - wrapped_desc = wrap_text(desc_font, desc_text, 40, int(w)) - - for line in wrapped_desc: - rl.draw_text_ex(desc_font, line, rl.Vector2(x, y), 40, 0, rl.WHITE) - y += 40 - - y += spacing - - # Open button - button_height = 48 + 64 # font size + padding - button_rect = rl.Rectangle(x, y, w, button_height) - if gui_button(button_rect, "Open", button_style=ButtonStyle.PRIMARY): - if self._open_settings_callback: - self._open_settings_callback() - - def _show_pairing(self): - if not self._pairing_dialog: - self._pairing_dialog = PairingDialog() - gui_app.set_modal_overlay(self._pairing_dialog, lambda result: setattr(self, '_pairing_dialog', None)) - - def __del__(self): - if self._pairing_dialog: - del self._pairing_dialog diff --git a/selfdrive/ui/widgets/ssh_key.py b/selfdrive/ui/widgets/ssh_key.py deleted file mode 100644 index 418867c86f..0000000000 --- a/selfdrive/ui/widgets/ssh_key.py +++ /dev/null @@ -1,128 +0,0 @@ -import pyray as rl -import requests -import threading -import copy -from enum import Enum - -from openpilot.common.params import Params -from openpilot.system.ui.lib.application import gui_app, FontWeight -from openpilot.system.ui.lib.button import gui_button, ButtonStyle -from openpilot.system.ui.lib.list_view import ( - ItemAction, - ListItem, - BUTTON_HEIGHT, - BUTTON_BORDER_RADIUS, - BUTTON_FONT_SIZE, - BUTTON_WIDTH, -) -from openpilot.system.ui.lib.text_measure import measure_text_cached -from openpilot.system.ui.lib.widget import DialogResult -from openpilot.system.ui.widgets.confirm_dialog import alert_dialog -from openpilot.system.ui.widgets.keyboard import Keyboard - - -class SshKeyActionState(Enum): - LOADING = "LOADING" - ADD = "ADD" - REMOVE = "REMOVE" - - -class SshKeyAction(ItemAction): - HTTP_TIMEOUT = 15 # seconds - MAX_WIDTH = 500 - - def __init__(self): - super().__init__(self.MAX_WIDTH, True) - - self._keyboard = Keyboard() - self._params = Params() - self._error_message: str = "" - self._text_font = gui_app.font(FontWeight.MEDIUM) - - self._refresh_state() - - def _refresh_state(self): - self._username = self._params.get("GithubUsername", "") - self._state = SshKeyActionState.REMOVE if self._params.get("GithubSshKeys") else SshKeyActionState.ADD - - def _render(self, rect: rl.Rectangle) -> bool: - # Show error dialog if there's an error - if self._error_message: - message = copy.copy(self._error_message) - gui_app.set_modal_overlay(lambda: alert_dialog(message)) - self._username = "" - self._error_message = "" - - # Draw username if exists - if self._username: - text_size = measure_text_cached(self._text_font, self._username, BUTTON_FONT_SIZE) - rl.draw_text_ex( - self._text_font, - self._username, - (rect.x + rect.width - BUTTON_WIDTH - text_size.x - 30, rect.y + (rect.height - text_size.y) / 2), - BUTTON_FONT_SIZE, - 1.0, - rl.WHITE, - ) - - # Draw button - if gui_button( - rl.Rectangle( - rect.x + rect.width - BUTTON_WIDTH, rect.y + (rect.height - BUTTON_HEIGHT) / 2, BUTTON_WIDTH, BUTTON_HEIGHT - ), - self._state.value, - is_enabled=self._state != SshKeyActionState.LOADING, - border_radius=BUTTON_BORDER_RADIUS, - font_size=BUTTON_FONT_SIZE, - button_style=ButtonStyle.LIST_ACTION, - ): - self._handle_button_click() - return True - return False - - def _handle_button_click(self): - if self._state == SshKeyActionState.ADD: - self._keyboard.clear() - self._keyboard.set_title("Enter your GitHub username") - gui_app.set_modal_overlay(self._keyboard, callback=self._on_username_submit) - elif self._state == SshKeyActionState.REMOVE: - self._params.remove("GithubUsername") - self._params.remove("GithubSshKeys") - self._refresh_state() - - def _on_username_submit(self, result: DialogResult): - if result != DialogResult.CONFIRM: - return - - username = self._keyboard.text.strip() - if not username: - return - - self._state = SshKeyActionState.LOADING - threading.Thread(target=lambda: self._fetch_ssh_key(username), daemon=True).start() - - def _fetch_ssh_key(self, username: str): - try: - url = f"https://github.com/{username}.keys" - response = requests.get(url, timeout=self.HTTP_TIMEOUT) - response.raise_for_status() - keys = response.text.strip() - if not keys: - raise requests.exceptions.HTTPError("No SSH keys found") - - # Success - save keys - self._params.put("GithubUsername", username) - self._params.put("GithubSshKeys", keys) - self._state = SshKeyActionState.REMOVE - self._username = username - - except requests.exceptions.Timeout: - self._error_message = "Request timed out" - self._state = SshKeyActionState.ADD - except Exception: - self._error_message = f"No SSH keys found for user '{username}'" - self._state = SshKeyActionState.ADD - - -def ssh_key_item(title: str, description: str): - return ListItem(title=title, description=description, action_item=SshKeyAction()) diff --git a/sunnypilot/SConscript b/sunnypilot/SConscript deleted file mode 100644 index 3aa302b92b..0000000000 --- a/sunnypilot/SConscript +++ /dev/null @@ -1,2 +0,0 @@ -SConscript(['modeld/SConscript']) -SConscript(['modeld_v2/SConscript']) \ No newline at end of file diff --git a/sunnypilot/mads/helpers.py b/sunnypilot/mads/helpers.py deleted file mode 100644 index 4b1095c63e..0000000000 --- a/sunnypilot/mads/helpers.py +++ /dev/null @@ -1,64 +0,0 @@ -""" -Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - -This file is part of sunnypilot and is licensed under the MIT License. -See the LICENSE.md file in the root directory for more details. -""" - -from openpilot.common.params import Params -from opendbc.car import structs -from opendbc.safety import ALTERNATIVE_EXPERIENCE -from opendbc.sunnypilot.car.hyundai.values import HyundaiFlagsSP, HyundaiSafetyFlagsSP - - -class MadsSteeringModeOnBrake: - REMAIN_ACTIVE = 0 - PAUSE = 1 - DISENGAGE = 2 - - -def get_mads_limited_brands(CP: structs.CarParams) -> bool: - return CP.brand in ("rivian", "tesla") - - -def read_steering_mode_param(CP: structs.CarParams, params: Params): - if get_mads_limited_brands(CP): - return MadsSteeringModeOnBrake.DISENGAGE - - try: - return int(params.get("MadsSteeringMode")) - except (ValueError, TypeError): - return MadsSteeringModeOnBrake.REMAIN_ACTIVE - - -def set_alternative_experience(CP: structs.CarParams, params: Params): - enabled = params.get_bool("Mads") - steering_mode = read_steering_mode_param(CP, params) - - if enabled: - CP.alternativeExperience |= ALTERNATIVE_EXPERIENCE.ENABLE_MADS - - if steering_mode == MadsSteeringModeOnBrake.DISENGAGE: - CP.alternativeExperience |= ALTERNATIVE_EXPERIENCE.MADS_DISENGAGE_LATERAL_ON_BRAKE - elif steering_mode == MadsSteeringModeOnBrake.PAUSE: - CP.alternativeExperience |= ALTERNATIVE_EXPERIENCE.MADS_PAUSE_LATERAL_ON_BRAKE - - -def set_car_specific_params(CP: structs.CarParams, CP_SP: structs.CarParamsSP, params: Params): - if CP.brand == "hyundai": - # TODO-SP: This should be separated from MADS module for future implementations - # Use "HyundaiLongitudinalMainCruiseToggleable" param - hyundai_cruise_main_toggleable = True - if hyundai_cruise_main_toggleable: - CP_SP.flags |= HyundaiFlagsSP.LONGITUDINAL_MAIN_CRUISE_TOGGLEABLE.value - CP_SP.safetyParam |= HyundaiSafetyFlagsSP.LONG_MAIN_CRUISE_TOGGLEABLE - - # MADS Partial Support - # MADS is currently partially supported for these platforms due to lack of consistent states to engage controls - # Only MadsSteeringModeOnBrake.DISENGAGE is supported for these platforms - # TODO-SP: To enable MADS full support for Rivian/Tesla, identify consistent signals for MADS toggling - mads_partial_support = get_mads_limited_brands(CP) - if mads_partial_support: - params.put("MadsSteeringMode", "2") - params.put_bool("MadsUnifiedEngagementMode", True) - params.remove("MadsMainCruiseAllowed") diff --git a/sunnypilot/mads/state.py b/sunnypilot/mads/state.py deleted file mode 100644 index 73240c790c..0000000000 --- a/sunnypilot/mads/state.py +++ /dev/null @@ -1,135 +0,0 @@ -""" -Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - -This file is part of sunnypilot and is licensed under the MIT License. -See the LICENSE.md file in the root directory for more details. -""" - -from cereal import log, custom -from openpilot.selfdrive.selfdrived.events import ET -from openpilot.selfdrive.selfdrived.state import SOFT_DISABLE_TIME -from openpilot.common.realtime import DT_CTRL - -State = custom.ModularAssistiveDrivingSystem.ModularAssistiveDrivingSystemState -EventName = log.OnroadEvent.EventName -EventNameSP = custom.OnroadEventSP.EventName - -ACTIVE_STATES = (State.enabled, State.softDisabling, State.overriding) -ENABLED_STATES = (State.paused, *ACTIVE_STATES) - -GEARS_ALLOW_PAUSED_SILENT = [EventNameSP.silentWrongGear, EventNameSP.silentReverseGear, EventNameSP.silentBrakeHold, - EventNameSP.silentDoorOpen, EventNameSP.silentSeatbeltNotLatched, EventNameSP.silentParkBrake] -GEARS_ALLOW_PAUSED = [EventName.wrongGear, EventName.reverseGear, EventName.brakeHold, - EventName.doorOpen, EventName.seatbeltNotLatched, EventName.parkBrake] - - -class StateMachine: - def __init__(self, mads): - self.selfdrive = mads.selfdrive - self.ss_state_machine = mads.selfdrive.state_machine - self._events = mads.selfdrive.events - self._events_sp = mads.selfdrive.events_sp - - self.state = State.disabled - - def add_current_alert_types(self, alert_type): - if not self.selfdrive.enabled: - self.ss_state_machine.current_alert_types.append(alert_type) - - def check_contains(self, event_type: str) -> bool: - return bool(self._events.contains(event_type) or self._events_sp.contains(event_type)) - - def check_contains_in_list(self) -> bool: - return bool(self._events.contains_in_list(GEARS_ALLOW_PAUSED) or self._events_sp.contains_in_list(GEARS_ALLOW_PAUSED_SILENT)) - - def update(self): - # soft disable timer and current alert types are from the state machine of openpilot - # decrement the soft disable timer at every step, as it's reset on - # entrance in SOFT_DISABLING state - - # ENABLED, SOFT DISABLING, PAUSED, OVERRIDING - if self.state != State.disabled: - # user and immediate disable always have priority in a non-disabled state - if self.check_contains(ET.USER_DISABLE): - if self._events_sp.has(EventNameSP.silentLkasDisable): - self.state = State.paused - else: - self.state = State.disabled - self.ss_state_machine.current_alert_types.append(ET.USER_DISABLE) - - elif self.check_contains(ET.IMMEDIATE_DISABLE): - self.state = State.disabled - self.add_current_alert_types(ET.IMMEDIATE_DISABLE) - - else: - # ENABLED - if self.state == State.enabled: - if self.check_contains(ET.SOFT_DISABLE): - self.state = State.softDisabling - if not self.selfdrive.enabled: - self.ss_state_machine.soft_disable_timer = int(SOFT_DISABLE_TIME / DT_CTRL) - self.ss_state_machine.current_alert_types.append(ET.SOFT_DISABLE) - - elif self.check_contains(ET.OVERRIDE_LATERAL): - self.state = State.overriding - self.add_current_alert_types(ET.OVERRIDE_LATERAL) - - # SOFT DISABLING - elif self.state == State.softDisabling: - if not self.check_contains(ET.SOFT_DISABLE): - # no more soft disabling condition, so go back to ENABLED - self.state = State.enabled - - elif self.ss_state_machine.soft_disable_timer > 0: - self.add_current_alert_types(ET.SOFT_DISABLE) - - elif self.ss_state_machine.soft_disable_timer <= 0: - self.state = State.disabled - - # PAUSED - elif self.state == State.paused: - if self.check_contains(ET.ENABLE): - if self.check_contains(ET.NO_ENTRY): - self.add_current_alert_types(ET.NO_ENTRY) - - else: - if self.check_contains(ET.OVERRIDE_LATERAL): - self.state = State.overriding - else: - self.state = State.enabled - self.add_current_alert_types(ET.ENABLE) - - # OVERRIDING - elif self.state == State.overriding: - if self.check_contains(ET.SOFT_DISABLE): - self.state = State.softDisabling - if not self.selfdrive.enabled: - self.ss_state_machine.soft_disable_timer = int(SOFT_DISABLE_TIME / DT_CTRL) - self.ss_state_machine.current_alert_types.append(ET.SOFT_DISABLE) - elif not self.check_contains(ET.OVERRIDE_LATERAL): - self.state = State.enabled - else: - self.ss_state_machine.current_alert_types += [ET.OVERRIDE_LATERAL] - - # DISABLED - elif self.state == State.disabled: - if self.check_contains(ET.ENABLE): - if self.check_contains(ET.NO_ENTRY): - if self.check_contains_in_list(): - self.state = State.paused - self.add_current_alert_types(ET.NO_ENTRY) - - else: - if self.check_contains(ET.OVERRIDE_LATERAL): - self.state = State.overriding - else: - self.state = State.enabled - self.add_current_alert_types(ET.ENABLE) - - # check if MADS is engaged and actuators are enabled - enabled = self.state in ENABLED_STATES - active = self.state in ACTIVE_STATES - if active: - self.add_current_alert_types(ET.WARNING) - - return enabled, active diff --git a/sunnypilot/mapd/live_map_data/base_map_data.py b/sunnypilot/mapd/live_map_data/base_map_data.py deleted file mode 100644 index 536d7720b7..0000000000 --- a/sunnypilot/mapd/live_map_data/base_map_data.py +++ /dev/null @@ -1,76 +0,0 @@ -""" -Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - -This file is part of sunnypilot and is licensed under the MIT License. -See the LICENSE.md file in the root directory for more details. -""" -import time -from abc import abstractmethod, ABC - -from cereal import messaging -from openpilot.common.gps import get_gps_location_service -from openpilot.common.params import Params -from openpilot.sunnypilot.navd.helpers import Coordinate, coordinate_from_param - - -class BaseMapData(ABC): - def __init__(self): - self.params = Params() - - self.gps_location_service = get_gps_location_service(self.params) - self.sm = messaging.SubMaster(['livePose', 'carControl'] + [self.gps_location_service]) - self.pm = messaging.PubMaster(['liveMapDataSP']) - - self.last_position = coordinate_from_param("LastGPSPosition", self.params) - self.last_altitude = None - - @abstractmethod - def update_location(self) -> None: - pass - - @abstractmethod - def get_current_speed_limit(self) -> float: - pass - - @abstractmethod - def get_next_speed_limit_and_distance(self) -> tuple[float, float]: - pass - - @abstractmethod - def get_current_road_name(self) -> str: - pass - - def get_current_location(self) -> None: - gps = self.sm[self.gps_location_service] - - # ignore the message if the fix is invalid - gps_ok = self.sm.updated[self.gps_location_service] or (time.monotonic() - self.sm.logMonoTime[self.gps_location_service] / 1e9) > 2.0 - if not gps_ok and self.sm['livePose'].inputsOK: - return None - - # livePose has these data, but aren't on cereal - self.last_position = Coordinate(gps.latitude, gps.longitude) - self.last_altitude = gps.altitude - - def publish(self) -> None: - speed_limit = self.get_current_speed_limit() - next_speed_limit, next_speed_limit_distance = self.get_next_speed_limit_and_distance() - - mapd_sp_send = messaging.new_message('liveMapDataSP') - mapd_sp_send.valid = self.sm.all_checks(service_list=[self.gps_location_service, 'livePose']) - live_map_data = mapd_sp_send.liveMapDataSP - - live_map_data.speedLimitValid = bool(speed_limit > 0) - live_map_data.speedLimit = speed_limit - live_map_data.speedLimitAheadValid = bool(next_speed_limit > 0) - live_map_data.speedLimitAhead = next_speed_limit - live_map_data.speedLimitAheadDistance = next_speed_limit_distance - live_map_data.roadName = self.get_current_road_name() - - self.pm.send('liveMapDataSP', mapd_sp_send) - - def tick(self) -> None: - self.sm.update() - self.get_current_location() - self.update_location() - self.publish() diff --git a/sunnypilot/mapd/live_map_data/debug.py b/sunnypilot/mapd/live_map_data/debug.py deleted file mode 100644 index da9f4d7771..0000000000 --- a/sunnypilot/mapd/live_map_data/debug.py +++ /dev/null @@ -1,57 +0,0 @@ -""" -Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - -This file is part of sunnypilot and is licensed under the MIT License. -See the LICENSE.md file in the root directory for more details. -""" -# DISCLAIMER: This code is intended principally for development and debugging purposes. -# Although it provides a standalone entry point to the program, users should refer -# to the actual implementations for consumption. Usage outside of development scenarios -# is not advised and could lead to unpredictable results. - -import threading -import traceback - -from cereal import messaging -from openpilot.common.gps import get_gps_location_service -from openpilot.common.params import Params -from openpilot.common.realtime import config_realtime_process -from openpilot.sunnypilot.selfdrive.controls.lib.speed_limit_controller.common import Policy -from openpilot.sunnypilot.selfdrive.controls.lib.speed_limit_controller.speed_limit_resolver import SpeedLimitResolver -from openpilot.sunnypilot.mapd.live_map_data import get_debug - - -def excepthook(args): - get_debug(f'MapD: Threading exception:\n{args}') - traceback.print_exception(args.exc_type, args.exc_value, args.exc_traceback) - - -def live_map_data_sp_thread(): - config_realtime_process([0, 1, 2, 3], 5) - - params = Params() - gps_location_service = get_gps_location_service(params) - - while True: - live_map_data_sp_thread_debug(gps_location_service) - - -def live_map_data_sp_thread_debug(gps_location_service): - _sub_master = messaging.SubMaster(['carState', 'livePose', 'liveMapDataSP', 'longitudinalPlanSP', gps_location_service]) - _sub_master.update() - - v_ego = _sub_master['carState'].vEgo - long_spl = _sub_master['longitudinalPlanSP'].speedLimit - _policy = Policy.car_state_priority - _resolver = SpeedLimitResolver(_policy) - _speed_limit, _distance, _source = _resolver.resolve(v_ego, long_spl, _sub_master) - print(_speed_limit, _distance, _source, " <-> ", long_spl) - - -def main(): - threading.excepthook = excepthook - live_map_data_sp_thread() - - -if __name__ == "__main__": - main() diff --git a/sunnypilot/mapd/live_map_data/osm_map_data.py b/sunnypilot/mapd/live_map_data/osm_map_data.py deleted file mode 100644 index 5f74a5d011..0000000000 --- a/sunnypilot/mapd/live_map_data/osm_map_data.py +++ /dev/null @@ -1,51 +0,0 @@ -""" -Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - -This file is part of sunnypilot and is licensed under the MIT License. -See the LICENSE.md file in the root directory for more details. -""" -import json -import platform - -from openpilot.common.params import Params -from openpilot.sunnypilot.mapd.live_map_data.base_map_data import BaseMapData -from openpilot.sunnypilot.navd.helpers import Coordinate - - -class OsmMapData(BaseMapData): - def __init__(self): - super().__init__() - self.params = Params() - self.mem_params = Params("/dev/shm/params") if platform.system() != "Darwin" else self.params - - def update_location(self) -> None: - if self.last_position is None or self.last_altitude is None: - return - - params = { - "latitude": self.last_position.latitude, - "longitude": self.last_position.longitude, - "altitude": self.last_altitude, - } - - self.mem_params.put("LastGPSPosition", json.dumps(params)) - - def get_current_speed_limit(self) -> float: - return float(self.mem_params.get("MapSpeedLimit", encoding='utf8') or 0.0) - - def get_current_road_name(self) -> str: - return self.mem_params.get("RoadName", encoding='utf8') or "" - - def get_next_speed_limit_and_distance(self) -> tuple[float, float]: - next_speed_limit_section_str = self.mem_params.get("NextMapSpeedLimit", encoding='utf8') - next_speed_limit_section = json.loads(next_speed_limit_section_str) if next_speed_limit_section_str else {} - next_speed_limit = next_speed_limit_section.get('speedlimit', 0.0) - next_speed_limit_latitude = next_speed_limit_section.get('latitude') - next_speed_limit_longitude = next_speed_limit_section.get('longitude') - next_speed_limit_distance = 0.0 - - if next_speed_limit_latitude and next_speed_limit_longitude: - next_speed_limit_coordinates = Coordinate(next_speed_limit_latitude, next_speed_limit_longitude) - next_speed_limit_distance = (self.last_position or Coordinate(0, 0)).distance_to(next_speed_limit_coordinates) - - return next_speed_limit, next_speed_limit_distance diff --git a/sunnypilot/modeld/SConscript b/sunnypilot/modeld/SConscript deleted file mode 100644 index df897e3049..0000000000 --- a/sunnypilot/modeld/SConscript +++ /dev/null @@ -1,59 +0,0 @@ -import glob - -Import('env', 'envCython', 'arch', 'cereal', 'messaging', 'common', 'gpucommon', 'visionipc', 'transformations') -lenv = env.Clone() -lenvCython = envCython.Clone() - -libs = [cereal, messaging, visionipc, gpucommon, common, 'capnp', 'kj', 'pthread'] -frameworks = [] - -common_src = [ - "models/commonmodel.cc", - "transforms/loadyuv.cc", - "transforms/transform.cc", -] - -thneed_src_common = [ - "thneed/clutil_legacy.cc", - "thneed/thneed_common.cc", - "thneed/serialize.cc", -] - -thneed_src_qcom = thneed_src_common + ["thneed/thneed_qcom2.cc"] -thneed_src_pc = thneed_src_common + ["thneed/thneed_pc.cc"] -thneed_src = thneed_src_qcom if arch == "larch64" else thneed_src_pc - -# SNPE except on Mac and ARM Linux -snpe_lib = [] -if arch != "Darwin" and arch != "aarch64": - common_src += ['runners/snpemodel.cc'] - snpe_lib += ['SNPE'] - -# OpenCL is a framework on Mac -if arch == "Darwin": - frameworks += ['OpenCL'] -else: - libs += ['OpenCL'] - -# Set path definitions -for pathdef, fn in {'TRANSFORM': 'transforms/transform.cl', 'LOADYUV': 'transforms/loadyuv.cl'}.items(): - for xenv in (lenv, lenvCython): - xenv['CXXFLAGS'].append(f'-D{pathdef}_PATH=\\"{File(fn).abspath}\\"') - -# Compile cython -snpe_rpath_qcom = "/data/pythonpath/third_party/snpe/larch64" -snpe_rpath_pc = f"{Dir('#').abspath}/third_party/snpe/x86_64-linux-clang" -snpe_rpath = lenvCython['RPATH'] + [snpe_rpath_qcom if arch == "larch64" else snpe_rpath_pc] - -cython_libs = envCython["LIBS"] + libs -snpemodel_lib = lenv.Library('snpemodel', ['runners/snpemodel.cc']) -commonmodel_lib = lenv.Library('commonmodel', common_src) - -lenvCython.Program('runners/runmodel_pyx.so', 'runners/runmodel_pyx.pyx', LIBS=cython_libs, FRAMEWORKS=frameworks) -lenvCython.Program('runners/snpemodel_pyx.so', 'runners/snpemodel_pyx.pyx', LIBS=[snpemodel_lib, snpe_lib, *cython_libs], FRAMEWORKS=frameworks, RPATH=snpe_rpath) -lenvCython.Program('models/commonmodel_pyx.so', 'models/commonmodel_pyx.pyx', LIBS=[commonmodel_lib, *cython_libs], FRAMEWORKS=frameworks) - -if arch == "larch64": - thneed_lib = env.SharedLibrary('thneed', thneed_src, LIBS=[gpucommon, common, 'OpenCL', 'dl']) - thneedmodel_lib = env.Library('thneedmodel', ['runners/thneedmodel.cc']) - lenvCython.Program('runners/thneedmodel_pyx.so', 'runners/thneedmodel_pyx.pyx', LIBS=envCython["LIBS"]+[thneedmodel_lib, thneed_lib, gpucommon, common, 'dl', 'OpenCL']) \ No newline at end of file diff --git a/sunnypilot/modeld/fill_model_msg.py b/sunnypilot/modeld/fill_model_msg.py deleted file mode 100644 index 608f24424d..0000000000 --- a/sunnypilot/modeld/fill_model_msg.py +++ /dev/null @@ -1,238 +0,0 @@ -import os -import capnp -import numpy as np -from cereal import log -from openpilot.sunnypilot.modeld.constants import ModelConstants, Plan -from openpilot.sunnypilot.selfdrive.controls.lib.drive_helpers import CONTROL_N, get_lag_adjusted_curvature, MIN_SPEED - -SEND_RAW_PRED = os.getenv('SEND_RAW_PRED') - -ConfidenceClass = log.ModelDataV2.ConfidenceClass - -class PublishState: - def __init__(self): - self.disengage_buffer = np.zeros(ModelConstants.CONFIDENCE_BUFFER_LEN*ModelConstants.DISENGAGE_WIDTH, dtype=np.float32) - self.prev_brake_5ms2_probs = np.zeros(ModelConstants.FCW_5MS2_PROBS_WIDTH, dtype=np.float32) - self.prev_brake_3ms2_probs = np.zeros(ModelConstants.FCW_3MS2_PROBS_WIDTH, dtype=np.float32) - -def fill_xyzt(builder, t, x, y, z, x_std=None, y_std=None, z_std=None): - builder.t = t - builder.x = x.tolist() - builder.y = y.tolist() - builder.z = z.tolist() - if x_std is not None: - builder.xStd = x_std.tolist() - if y_std is not None: - builder.yStd = y_std.tolist() - if z_std is not None: - builder.zStd = z_std.tolist() - -def fill_xyvat(builder, t, x, y, v, a, x_std=None, y_std=None, v_std=None, a_std=None): - builder.t = t - builder.x = x.tolist() - builder.y = y.tolist() - builder.v = v.tolist() - builder.a = a.tolist() - if x_std is not None: - builder.xStd = x_std.tolist() - if y_std is not None: - builder.yStd = y_std.tolist() - if v_std is not None: - builder.vStd = v_std.tolist() - if a_std is not None: - builder.aStd = a_std.tolist() - -def fill_xyz_poly(builder, degree, x, y, z): - xyz = np.stack([x, y, z], axis=1) - coeffs = np.polynomial.polynomial.polyfit(ModelConstants.T_IDXS, xyz, deg=degree) - builder.xCoefficients = coeffs[:, 0].tolist() - builder.yCoefficients = coeffs[:, 1].tolist() - builder.zCoefficients = coeffs[:, 2].tolist() - -def fill_model_msg(base_msg: capnp._DynamicStructBuilder, extended_msg: capnp._DynamicStructBuilder, - net_output_data: dict[str, np.ndarray], action: log.ModelDataV2.Action, publish_state: PublishState, - vipc_frame_id: int, vipc_frame_id_extra: int, frame_id: int, frame_drop: float, - timestamp_eof: int, model_execution_time: float, valid: bool, - v_ego: float, steer_delay: float, meta_const) -> None: - frame_age = frame_id - vipc_frame_id if frame_id > vipc_frame_id else 0 - frame_drop_perc = frame_drop * 100 - extended_msg.valid = valid - base_msg.valid = valid - - if 'lat_planner_solution' in net_output_data: - x, y, yaw, yawRate = [net_output_data['lat_planner_solution'][0, :, i].tolist() for i in range(4)] - x_sol = np.column_stack([x, y, yaw, yawRate]) - v_ego = max(MIN_SPEED, v_ego) - psis = x_sol[0:CONTROL_N, 2].tolist() - curvatures = (x_sol[0:CONTROL_N, 3] / v_ego).tolist() - desired_curvature = get_lag_adjusted_curvature(steer_delay, v_ego, psis, curvatures) - else: - desired_curvature = float(net_output_data['desired_curvature'][0, 0]) - - driving_model_data = base_msg.drivingModelData - - driving_model_data.frameId = vipc_frame_id - driving_model_data.frameIdExtra = vipc_frame_id_extra - driving_model_data.frameDropPerc = frame_drop_perc - driving_model_data.modelExecutionTime = model_execution_time - - # Populate drivingModelData.action - driving_model_data_action = driving_model_data.action - driving_model_data_action.desiredAcceleration = action.desiredAcceleration - driving_model_data_action.shouldStop = action.shouldStop - driving_model_data_action.desiredCurvature = desired_curvature - - modelV2 = extended_msg.modelV2 - modelV2.frameId = vipc_frame_id - modelV2.frameIdExtra = vipc_frame_id_extra - modelV2.frameAge = frame_age - modelV2.frameDropPerc = frame_drop_perc - modelV2.timestampEof = timestamp_eof - modelV2.modelExecutionTime = model_execution_time - - # plan - position = modelV2.position - fill_xyzt(position, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.POSITION].T, *net_output_data['plan_stds'][0,:,Plan.POSITION].T) - velocity = modelV2.velocity - fill_xyzt(velocity, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.VELOCITY].T) - acceleration = modelV2.acceleration - fill_xyzt(acceleration, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.ACCELERATION].T) - orientation = modelV2.orientation - fill_xyzt(orientation, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.T_FROM_CURRENT_EULER].T) - orientation_rate = modelV2.orientationRate - fill_xyzt(orientation_rate, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.ORIENTATION_RATE].T) - - # temporal pose - temporal_pose = modelV2.temporalPose - temporal_pose.trans = net_output_data['plan'][0,0,Plan.VELOCITY].tolist() - temporal_pose.transStd = net_output_data['plan_stds'][0,0,Plan.VELOCITY].tolist() - temporal_pose.rot = net_output_data['plan'][0,0,Plan.ORIENTATION_RATE].tolist() - temporal_pose.rotStd = net_output_data['plan_stds'][0,0,Plan.ORIENTATION_RATE].tolist() - - # poly path - poly_path = driving_model_data.path - fill_xyz_poly(poly_path, ModelConstants.POLY_PATH_DEGREE, *net_output_data['plan'][0,:,Plan.POSITION].T) - - # lateral planning - modelV2_action = modelV2.action - modelV2_action.desiredAcceleration = action.desiredAcceleration - modelV2_action.shouldStop = action.shouldStop - modelV2_action.desiredCurvature = desired_curvature - - # times at X_IDXS according to model plan - PLAN_T_IDXS = [np.nan] * ModelConstants.IDX_N - PLAN_T_IDXS[0] = 0.0 - plan_x = net_output_data['plan'][0,:,Plan.POSITION][:,0].tolist() - for xidx in range(1, ModelConstants.IDX_N): - tidx = 0 - # increment tidx until we find an element that's further away than the current xidx - while tidx < ModelConstants.IDX_N - 1 and plan_x[tidx+1] < ModelConstants.X_IDXS[xidx]: - tidx += 1 - if tidx == ModelConstants.IDX_N - 1: - # if the Plan doesn't extend far enough, set plan_t to the max value (10s), then break - PLAN_T_IDXS[xidx] = ModelConstants.T_IDXS[ModelConstants.IDX_N - 1] - break - # interpolate to find `t` for the current xidx - current_x_val = plan_x[tidx] - next_x_val = plan_x[tidx+1] - p = (ModelConstants.X_IDXS[xidx] - current_x_val) / (next_x_val - current_x_val) if abs(next_x_val - current_x_val) > 1e-9 else float('nan') - PLAN_T_IDXS[xidx] = p * ModelConstants.T_IDXS[tidx+1] + (1 - p) * ModelConstants.T_IDXS[tidx] - - # lane lines - modelV2.init('laneLines', 4) - for i in range(4): - lane_line = modelV2.laneLines[i] - fill_xyzt(lane_line, PLAN_T_IDXS, np.array(ModelConstants.X_IDXS), net_output_data['lane_lines'][0,i,:,0], net_output_data['lane_lines'][0,i,:,1]) - modelV2.laneLineStds = net_output_data['lane_lines_stds'][0,:,0,0].tolist() - modelV2.laneLineProbs = net_output_data['lane_lines_prob'][0,1::2].tolist() - - lane_line_meta = driving_model_data.laneLineMeta - lane_line_meta.leftY = modelV2.laneLines[1].y[0] - lane_line_meta.leftProb = modelV2.laneLineProbs[1] - lane_line_meta.rightY = modelV2.laneLines[2].y[0] - lane_line_meta.rightProb = modelV2.laneLineProbs[2] - - # road edges - modelV2.init('roadEdges', 2) - for i in range(2): - road_edge = modelV2.roadEdges[i] - fill_xyzt(road_edge, PLAN_T_IDXS, np.array(ModelConstants.X_IDXS), net_output_data['road_edges'][0,i,:,0], net_output_data['road_edges'][0,i,:,1]) - modelV2.roadEdgeStds = net_output_data['road_edges_stds'][0,:,0,0].tolist() - - # leads - modelV2.init('leadsV3', 3) - for i in range(3): - lead = modelV2.leadsV3[i] - fill_xyvat(lead, ModelConstants.LEAD_T_IDXS, *net_output_data['lead'][0,i].T, *net_output_data['lead_stds'][0,i].T) - lead.prob = net_output_data['lead_prob'][0,i].tolist() - lead.probTime = ModelConstants.LEAD_T_OFFSETS[i] - - # meta - meta = modelV2.meta - meta.desireState = net_output_data['desire_state'][0].reshape(-1).tolist() - meta.desirePrediction = net_output_data['desire_pred'][0].reshape(-1).tolist() - meta.engagedProb = net_output_data['meta'][0,meta_const.ENGAGED].item() - meta.init('disengagePredictions') - disengage_predictions = meta.disengagePredictions - disengage_predictions.t = ModelConstants.META_T_IDXS - disengage_predictions.brakeDisengageProbs = net_output_data['meta'][0,meta_const.BRAKE_DISENGAGE].tolist() - disengage_predictions.gasDisengageProbs = net_output_data['meta'][0,meta_const.GAS_DISENGAGE].tolist() - disengage_predictions.steerOverrideProbs = net_output_data['meta'][0,meta_const.STEER_OVERRIDE].tolist() - disengage_predictions.brake3MetersPerSecondSquaredProbs = net_output_data['meta'][0,meta_const.HARD_BRAKE_3].tolist() - disengage_predictions.brake4MetersPerSecondSquaredProbs = net_output_data['meta'][0,meta_const.HARD_BRAKE_4].tolist() - disengage_predictions.brake5MetersPerSecondSquaredProbs = net_output_data['meta'][0,meta_const.HARD_BRAKE_5].tolist() - if 'sim_pose' not in net_output_data: - disengage_predictions.gasPressProbs = net_output_data['meta'][0,meta_const.GAS_PRESS].tolist() - disengage_predictions.brakePressProbs = net_output_data['meta'][0,meta_const.BRAKE_PRESS].tolist() - - publish_state.prev_brake_5ms2_probs[:-1] = publish_state.prev_brake_5ms2_probs[1:] - publish_state.prev_brake_5ms2_probs[-1] = net_output_data['meta'][0,meta_const.HARD_BRAKE_5][0] - publish_state.prev_brake_3ms2_probs[:-1] = publish_state.prev_brake_3ms2_probs[1:] - publish_state.prev_brake_3ms2_probs[-1] = net_output_data['meta'][0,meta_const.HARD_BRAKE_3][0] - hard_brake_predicted = (publish_state.prev_brake_5ms2_probs > ModelConstants.FCW_THRESHOLDS_5MS2).all() and \ - (publish_state.prev_brake_3ms2_probs > ModelConstants.FCW_THRESHOLDS_3MS2).all() - meta.hardBrakePredicted = hard_brake_predicted.item() - - # confidence - if vipc_frame_id % (2*ModelConstants.MODEL_FREQ) == 0: - # any disengage prob - brake_disengage_probs = net_output_data['meta'][0,meta_const.BRAKE_DISENGAGE] - gas_disengage_probs = net_output_data['meta'][0,meta_const.GAS_DISENGAGE] - steer_override_probs = net_output_data['meta'][0,meta_const.STEER_OVERRIDE] - any_disengage_probs = 1-((1-brake_disengage_probs)*(1-gas_disengage_probs)*(1-steer_override_probs)) - # independent disengage prob for each 2s slice - ind_disengage_probs = np.r_[any_disengage_probs[0], np.diff(any_disengage_probs) / (1 - any_disengage_probs[:-1])] - # rolling buf for 2, 4, 6, 8, 10s - publish_state.disengage_buffer[:-ModelConstants.DISENGAGE_WIDTH] = publish_state.disengage_buffer[ModelConstants.DISENGAGE_WIDTH:] - publish_state.disengage_buffer[-ModelConstants.DISENGAGE_WIDTH:] = ind_disengage_probs - - score = 0. - for i in range(ModelConstants.DISENGAGE_WIDTH): - score += publish_state.disengage_buffer[i*ModelConstants.DISENGAGE_WIDTH+ModelConstants.DISENGAGE_WIDTH-1-i].item() / ModelConstants.DISENGAGE_WIDTH - if score < ModelConstants.RYG_GREEN: - modelV2.confidence = ConfidenceClass.green - elif score < ModelConstants.RYG_YELLOW: - modelV2.confidence = ConfidenceClass.yellow - else: - modelV2.confidence = ConfidenceClass.red - - # raw prediction if enabled - if SEND_RAW_PRED: - modelV2.rawPredictions = net_output_data['raw_pred'].tobytes() - -def fill_pose_msg(msg: capnp._DynamicStructBuilder, net_output_data: dict[str, np.ndarray], - vipc_frame_id: int, vipc_dropped_frames: int, timestamp_eof: int, live_calib_seen: bool) -> None: - msg.valid = live_calib_seen & (vipc_dropped_frames < 1) - cameraOdometry = msg.cameraOdometry - - cameraOdometry.frameId = vipc_frame_id - cameraOdometry.timestampEof = timestamp_eof - - cameraOdometry.trans = net_output_data['pose'][0,:3].tolist() - cameraOdometry.rot = net_output_data['pose'][0,3:].tolist() - cameraOdometry.wideFromDeviceEuler = net_output_data['wide_from_device_euler'][0,:].tolist() - cameraOdometry.roadTransformTrans = net_output_data['road_transform'][0,:3].tolist() - cameraOdometry.transStd = net_output_data['pose_stds'][0,:3].tolist() - cameraOdometry.rotStd = net_output_data['pose_stds'][0,3:].tolist() - cameraOdometry.wideFromDeviceEulerStd = net_output_data['wide_from_device_euler_stds'][0,:].tolist() - cameraOdometry.roadTransformTransStd = net_output_data['road_transform_stds'][0,:3].tolist() diff --git a/sunnypilot/modeld/get_model_metadata.py b/sunnypilot/modeld/get_model_metadata.py deleted file mode 100755 index 144860204f..0000000000 --- a/sunnypilot/modeld/get_model_metadata.py +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env python3 -import sys -import pathlib -import onnx -import codecs -import pickle - -def get_name_and_shape(value_info:onnx.ValueInfoProto) -> tuple[str, tuple[int,...]]: - shape = tuple([int(dim.dim_value) for dim in value_info.type.tensor_type.shape.dim]) - name = value_info.name - return name, shape - -if __name__ == "__main__": - model_path = pathlib.Path(sys.argv[1]) - model = onnx.load(str(model_path)) - i = [x.key for x in model.metadata_props].index('output_slices') - output_slices = model.metadata_props[i].value - - metadata = {} - metadata['output_slices'] = pickle.loads(codecs.decode(output_slices.encode(), "base64")) - metadata['input_shapes'] = dict([get_name_and_shape(x) for x in model.graph.input]) - metadata['output_shapes'] = dict([get_name_and_shape(x) for x in model.graph.output]) - - metadata_path = model_path.parent / (model_path.stem + '_metadata.pkl') - with open(metadata_path, 'wb') as f: - pickle.dump(metadata, f) - - print(f'saved metadata to {metadata_path}') diff --git a/sunnypilot/modeld/modeld b/sunnypilot/modeld/modeld deleted file mode 100755 index e1cef4dcc3..0000000000 --- a/sunnypilot/modeld/modeld +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env bash - -DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null && pwd)" -cd "$DIR/../../" - -if [ -f "$DIR/libthneed.so" ]; then - export LD_PRELOAD="$DIR/libthneed.so" -fi - -exec "$DIR/modeld.py" "$@" diff --git a/sunnypilot/modeld/modeld.py b/sunnypilot/modeld/modeld.py deleted file mode 100755 index d4bd96ff66..0000000000 --- a/sunnypilot/modeld/modeld.py +++ /dev/null @@ -1,340 +0,0 @@ -#!/usr/bin/env python3 -import os -import time -import numpy as np -import cereal.messaging as messaging -from cereal import car, log -from pathlib import Path -from setproctitle import setproctitle -from cereal.messaging import PubMaster, SubMaster -from msgq.visionipc import VisionIpcClient, VisionStreamType, VisionBuf -from opendbc.car.car_helpers import get_demo_car_params -from openpilot.common.swaglog import cloudlog -from openpilot.common.params import Params -from openpilot.common.filter_simple import FirstOrderFilter -from openpilot.common.realtime import DT_MDL, config_realtime_process -from numpy import interp -from openpilot.common.transformations.camera import DEVICE_CAMERAS -from openpilot.common.transformations.model import get_warp_matrix -from openpilot.system import sentry -from openpilot.selfdrive.controls.lib.desire_helper import DesireHelper -from openpilot.selfdrive.controls.lib.drive_helpers import get_accel_from_plan, smooth_value - -from openpilot.sunnypilot.modeld.runners import ModelRunner, Runtime -from openpilot.sunnypilot.modeld.parse_model_outputs import Parser -from openpilot.sunnypilot.modeld.fill_model_msg import fill_model_msg, fill_pose_msg, PublishState -from openpilot.sunnypilot.modeld.constants import ModelConstants, Plan -from openpilot.sunnypilot.models.helpers import get_active_bundle, get_model_path, load_metadata, prepare_inputs, load_meta_constants -from openpilot.sunnypilot.models.modeld_lagd import ModeldLagd -from openpilot.sunnypilot.modeld.models.commonmodel_pyx import ModelFrame, CLContext - - -PROCESS_NAME = "selfdrive.modeld.modeld_snpe" -SEND_RAW_PRED = os.getenv('SEND_RAW_PRED') - -MODEL_PATHS = { - ModelRunner.THNEED: Path(__file__).parent / 'models/supercombo.thneed', - ModelRunner.ONNX: Path(__file__).parent / 'models/supercombo.onnx'} - -METADATA_PATH = Path(__file__).parent / 'models/supercombo_metadata.pkl' - - -class FrameMeta: - frame_id: int = 0 - timestamp_sof: int = 0 - timestamp_eof: int = 0 - - def __init__(self, vipc=None): - if vipc is not None: - self.frame_id, self.timestamp_sof, self.timestamp_eof = vipc.frame_id, vipc.timestamp_sof, vipc.timestamp_eof - -class ModelState: - frame: ModelFrame - wide_frame: ModelFrame - inputs: dict[str, np.ndarray] - output: np.ndarray - prev_desire: np.ndarray # for tracking the rising edge of the pulse - model: ModelRunner - - def __init__(self, context: CLContext): - self.frame = ModelFrame(context) - self.wide_frame = ModelFrame(context) - self.prev_desire = np.zeros(ModelConstants.DESIRE_LEN, dtype=np.float32) - bundle = get_active_bundle() - overrides = {override.key: override.value for override in bundle.overrides} - self.LAT_SMOOTH_SECONDS = float(overrides.get('lat', ".2")) - self.LONG_SMOOTH_SECONDS = float(overrides.get('long', ".0")) - - model_paths = get_model_path() - self.model_metadata = load_metadata() - self.inputs = prepare_inputs(self.model_metadata) - self.meta = load_meta_constants(self.model_metadata) - - self.output_slices = self.model_metadata['output_slices'] - net_output_size = self.model_metadata['output_shapes']['outputs'][1] - self.output = np.zeros(net_output_size, dtype=np.float32) - self.parser = Parser() - - self.model = ModelRunner(model_paths, self.output, Runtime.GPU, False, context) - self.model.addInput("input_imgs", None) - self.model.addInput("big_input_imgs", None) - for k,v in self.inputs.items(): - self.model.addInput(k, v) - - def slice_outputs(self, model_outputs: np.ndarray) -> dict[str, np.ndarray]: - parsed_model_outputs = {k: model_outputs[np.newaxis, v] for k,v in self.output_slices.items()} - if SEND_RAW_PRED: - parsed_model_outputs['raw_pred'] = model_outputs.copy() - return parsed_model_outputs - - def run(self, buf: VisionBuf, wbuf: VisionBuf, transform: np.ndarray, transform_wide: np.ndarray, - inputs: dict[str, np.ndarray], prepare_only: bool) -> dict[str, np.ndarray] | None: - # Model decides when action is completed, so desire input is just a pulse triggered on rising edge - inputs['desire'][0] = 0 - self.inputs['desire'][:-ModelConstants.DESIRE_LEN] = self.inputs['desire'][ModelConstants.DESIRE_LEN:] - self.inputs['desire'][-ModelConstants.DESIRE_LEN:] = np.where(inputs['desire'] - self.prev_desire > .99, inputs['desire'], 0) - self.prev_desire[:] = inputs['desire'] - - for k in self.inputs: - if k in inputs and k != 'desire': - self.inputs[k][:] = inputs[k] - - # if getCLBuffer is not None, frame will be None - self.model.setInputBuffer("input_imgs", self.frame.prepare(buf, transform.flatten(), self.model.getCLBuffer("input_imgs"))) - if wbuf is not None: - self.model.setInputBuffer("big_input_imgs", self.wide_frame.prepare(wbuf, transform_wide.flatten(), self.model.getCLBuffer("big_input_imgs"))) - - if prepare_only: - return None - - self.model.execute() - outputs = self.parser.parse_outputs(self.slice_outputs(self.output)) - - self.inputs['features_buffer'][:-ModelConstants.FEATURE_LEN] = self.inputs['features_buffer'][ModelConstants.FEATURE_LEN:] - self.inputs['features_buffer'][-ModelConstants.FEATURE_LEN:] = outputs['hidden_state'][0, :] - - if "lat_planner_solution" in outputs and "lat_planner_state" in self.inputs.keys(): - self.inputs['lat_planner_state'][2] = interp(DT_MDL, ModelConstants.T_IDXS, outputs['lat_planner_solution'][0, :, 2]) - self.inputs['lat_planner_state'][3] = interp(DT_MDL, ModelConstants.T_IDXS, outputs['lat_planner_solution'][0, :, 3]) - - if "desired_curvature" in outputs: - if "prev_desired_curvs" in self.inputs.keys(): - self.inputs['prev_desired_curvs'][:-1] = self.inputs['prev_desired_curvs'][1:] - self.inputs['prev_desired_curvs'][-1] = outputs['desired_curvature'][0, 0] - - if "prev_desired_curv" in self.inputs.keys(): - self.inputs['prev_desired_curv'][:-1] = self.inputs['prev_desired_curv'][1:] - self.inputs['prev_desired_curv'][-1:] = outputs['desired_curvature'][0, :] - return outputs - - def get_action_from_model(self, model_output: dict[str, np.ndarray], prev_action: log.ModelDataV2.Action, - long_action_t: float) -> log.ModelDataV2.Action: - plan = model_output['plan'][0] - desired_accel, should_stop = get_accel_from_plan(plan[:, Plan.VELOCITY][:, 0], plan[:, Plan.ACCELERATION][:, 0], ModelConstants.T_IDXS, - action_t=long_action_t) - desired_accel = smooth_value(desired_accel, prev_action.desiredAcceleration, self.LONG_SMOOTH_SECONDS) - - return log.ModelDataV2.Action(desiredAcceleration=float(desired_accel), shouldStop=bool(should_stop)) - - -def main(demo=False): - cloudlog.warning("modeld init") - - sentry.set_tag("daemon", PROCESS_NAME) - cloudlog.bind(daemon=PROCESS_NAME) - setproctitle(PROCESS_NAME) - config_realtime_process(7, 54) - - cloudlog.warning("setting up CL context") - cl_context = CLContext() - cloudlog.warning("CL context ready; loading model") - model = ModelState(cl_context) - cloudlog.warning("models loaded, modeld starting") - - # visionipc clients - while True: - available_streams = VisionIpcClient.available_streams("camerad", block=False) - if available_streams: - use_extra_client = VisionStreamType.VISION_STREAM_WIDE_ROAD in available_streams and VisionStreamType.VISION_STREAM_ROAD in available_streams - main_wide_camera = VisionStreamType.VISION_STREAM_ROAD not in available_streams - break - time.sleep(.1) - - vipc_client_main_stream = VisionStreamType.VISION_STREAM_WIDE_ROAD if main_wide_camera else VisionStreamType.VISION_STREAM_ROAD - vipc_client_main = VisionIpcClient("camerad", vipc_client_main_stream, True, cl_context) - vipc_client_extra = VisionIpcClient("camerad", VisionStreamType.VISION_STREAM_WIDE_ROAD, False, cl_context) - cloudlog.warning(f"vision stream set up, main_wide_camera: {main_wide_camera}, use_extra_client: {use_extra_client}") - - while not vipc_client_main.connect(False): - time.sleep(0.1) - while use_extra_client and not vipc_client_extra.connect(False): - time.sleep(0.1) - - cloudlog.warning(f"connected main cam with buffer size: {vipc_client_main.buffer_len} ({vipc_client_main.width} x {vipc_client_main.height})") - if use_extra_client: - cloudlog.warning(f"connected extra cam with buffer size: {vipc_client_extra.buffer_len} ({vipc_client_extra.width} x {vipc_client_extra.height})") - - # messaging - pm = PubMaster(["modelV2", "drivingModelData", "cameraOdometry"]) - sm = SubMaster(["deviceState", "carState", "roadCameraState", "liveCalibration", "driverMonitoringState", "carControl", "liveDelay"]) - - publish_state = PublishState() - params = Params() - - # setup filter to track dropped frames - frame_dropped_filter = FirstOrderFilter(0., 10., 1. / ModelConstants.MODEL_FREQ) - frame_id = 0 - last_vipc_frame_id = 0 - run_count = 0 - - model_transform_main = np.zeros((3, 3), dtype=np.float32) - model_transform_extra = np.zeros((3, 3), dtype=np.float32) - live_calib_seen = False - buf_main, buf_extra = None, None - meta_main = FrameMeta() - meta_extra = FrameMeta() - - - if demo: - CP = get_demo_car_params() - else: - CP = messaging.log_from_bytes(params.get("CarParams", block=True), car.CarParams) - - cloudlog.info("modeld got CarParams: %s", CP.brand) - - modeld_lagd = ModeldLagd() - - # Enable lagd support for sunnypilot modeld - long_delay = CP.longitudinalActuatorDelay + model.LONG_SMOOTH_SECONDS - prev_action = log.ModelDataV2.Action() - - DH = DesireHelper() - - while True: - # Keep receiving frames until we are at least 1 frame ahead of previous extra frame - while meta_main.timestamp_sof < meta_extra.timestamp_sof + 25000000: - buf_main = vipc_client_main.recv() - meta_main = FrameMeta(vipc_client_main) - if buf_main is None: - break - - if buf_main is None: - cloudlog.debug("vipc_client_main no frame") - continue - - if use_extra_client: - # Keep receiving extra frames until frame id matches main camera - while True: - buf_extra = vipc_client_extra.recv() - meta_extra = FrameMeta(vipc_client_extra) - if buf_extra is None or meta_main.timestamp_sof < meta_extra.timestamp_sof + 25000000: - break - - if buf_extra is None: - cloudlog.debug("vipc_client_extra no frame") - continue - - if abs(meta_main.timestamp_sof - meta_extra.timestamp_sof) > 10000000: - cloudlog.error(f"frames out of sync! main: {meta_main.frame_id} ({meta_main.timestamp_sof / 1e9:.5f}),\ - extra: {meta_extra.frame_id} ({meta_extra.timestamp_sof / 1e9:.5f})") - - else: - # Use single camera - buf_extra = buf_main - meta_extra = meta_main - - sm.update(0) - desire = DH.desire - v_ego = sm["carState"].vEgo - is_rhd = sm["driverMonitoringState"].isRHD - frame_id = sm["roadCameraState"].frameId - steer_delay = modeld_lagd.lagd_main(CP, sm, model) - - if sm.updated["liveCalibration"] and sm.seen['roadCameraState'] and sm.seen['deviceState']: - device_from_calib_euler = np.array(sm["liveCalibration"].rpyCalib, dtype=np.float32) - dc = DEVICE_CAMERAS[(str(sm['deviceState'].deviceType), str(sm['roadCameraState'].sensor))] - model_transform_main = get_warp_matrix(device_from_calib_euler, dc.ecam.intrinsics if main_wide_camera else dc.fcam.intrinsics, False).astype(np.float32) - model_transform_extra = get_warp_matrix(device_from_calib_euler, dc.ecam.intrinsics, True).astype(np.float32) - live_calib_seen = True - - traffic_convention = np.zeros(2) - traffic_convention[int(is_rhd)] = 1 - - vec_desire = np.zeros(ModelConstants.DESIRE_LEN, dtype=np.float32) - if desire >= 0 and desire < ModelConstants.DESIRE_LEN: - vec_desire[desire] = 1 - - # tracked dropped frames - vipc_dropped_frames = max(0, meta_main.frame_id - last_vipc_frame_id - 1) - frames_dropped = frame_dropped_filter.update(min(vipc_dropped_frames, 10)) - if run_count < 10: # let frame drops warm up - frame_dropped_filter.x = 0. - frames_dropped = 0. - run_count = run_count + 1 - - frame_drop_ratio = frames_dropped / (1 + frames_dropped) - prepare_only = vipc_dropped_frames > 0 - if prepare_only: - cloudlog.error(f"skipping model eval. Dropped {vipc_dropped_frames} frames") - - inputs:dict[str, np.ndarray] = { - 'desire': vec_desire, - 'traffic_convention': traffic_convention, - } - - if "lateral_control_params" in model.inputs.keys(): - inputs['lateral_control_params'] = np.array([max(v_ego, 0.), steer_delay], dtype=np.float32) - - if "driving_style" in model.inputs.keys(): - inputs['driving_style'] = np.array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0], dtype=np.float32) - - if "nav_features" in model.inputs.keys(): - inputs['nav_features'] = np.zeros(ModelConstants.NAV_FEATURE_LEN, dtype=np.float32) - - if "nav_instructions" in model.inputs.keys(): - inputs['nav_instructions'] = np.zeros(ModelConstants.NAV_INSTRUCTION_LEN, dtype=np.float32) - - mt1 = time.perf_counter() - model_output = model.run(buf_main, buf_extra, model_transform_main, model_transform_extra, inputs, prepare_only) - mt2 = time.perf_counter() - model_execution_time = mt2 - mt1 - - if model_output is not None: - modelv2_send = messaging.new_message('modelV2') - drivingdata_send = messaging.new_message('drivingModelData') - posenet_send = messaging.new_message('cameraOdometry') - action = model.get_action_from_model(model_output, prev_action, long_delay + DT_MDL) - fill_model_msg(drivingdata_send, modelv2_send, model_output, action, publish_state, meta_main.frame_id, meta_extra.frame_id, frame_id, - frame_drop_ratio, meta_main.timestamp_eof, model_execution_time, live_calib_seen, - v_ego, steer_delay, model.meta) - - desire_state = modelv2_send.modelV2.meta.desireState - l_lane_change_prob = desire_state[log.Desire.laneChangeLeft] - r_lane_change_prob = desire_state[log.Desire.laneChangeRight] - lane_change_prob = l_lane_change_prob + r_lane_change_prob - DH.update(sm['carState'], sm['carControl'].latActive, lane_change_prob) - modelv2_send.modelV2.meta.laneChangeState = DH.lane_change_state - modelv2_send.modelV2.meta.laneChangeDirection = DH.lane_change_direction - drivingdata_send.drivingModelData.meta.laneChangeState = DH.lane_change_state - drivingdata_send.drivingModelData.meta.laneChangeDirection = DH.lane_change_direction - - fill_pose_msg(posenet_send, model_output, meta_main.frame_id, vipc_dropped_frames, meta_main.timestamp_eof, live_calib_seen) - pm.send('modelV2', modelv2_send) - pm.send('drivingModelData', drivingdata_send) - pm.send('cameraOdometry', posenet_send) - - last_vipc_frame_id = meta_main.frame_id - - -if __name__ == "__main__": - try: - import argparse - parser = argparse.ArgumentParser() - parser.add_argument('--demo', action='store_true', help='A boolean for demo mode.') - args = parser.parse_args() - main(demo=args.demo) - except KeyboardInterrupt: - cloudlog.warning(f"child {PROCESS_NAME} got SIGINT") - except Exception: - sentry.capture_exception() - raise diff --git a/sunnypilot/modeld/models/commonmodel.cc b/sunnypilot/modeld/models/commonmodel.cc deleted file mode 100644 index f1e15e5a4e..0000000000 --- a/sunnypilot/modeld/models/commonmodel.cc +++ /dev/null @@ -1,50 +0,0 @@ -#include "sunnypilot/modeld/models/commonmodel.h" - -#include -#include -#include - -#include "common/clutil.h" - -ModelFrame::ModelFrame(cl_device_id device_id, cl_context context) { - input_frames = std::make_unique(buf_size); - - q = CL_CHECK_ERR(clCreateCommandQueue(context, device_id, 0, &err)); - y_cl = CL_CHECK_ERR(clCreateBuffer(context, CL_MEM_READ_WRITE, MODEL_WIDTH * MODEL_HEIGHT, NULL, &err)); - u_cl = CL_CHECK_ERR(clCreateBuffer(context, CL_MEM_READ_WRITE, (MODEL_WIDTH / 2) * (MODEL_HEIGHT / 2), NULL, &err)); - v_cl = CL_CHECK_ERR(clCreateBuffer(context, CL_MEM_READ_WRITE, (MODEL_WIDTH / 2) * (MODEL_HEIGHT / 2), NULL, &err)); - net_input_cl = CL_CHECK_ERR(clCreateBuffer(context, CL_MEM_READ_WRITE, MODEL_FRAME_SIZE * sizeof(float), NULL, &err)); - - transform_init(&transform, context, device_id); - loadyuv_init(&loadyuv, context, device_id, MODEL_WIDTH, MODEL_HEIGHT); -} - -float* ModelFrame::prepare(cl_mem yuv_cl, int frame_width, int frame_height, int frame_stride, int frame_uv_offset, const mat3 &projection, cl_mem *output) { - transform_queue(&this->transform, q, - yuv_cl, frame_width, frame_height, frame_stride, frame_uv_offset, - y_cl, u_cl, v_cl, MODEL_WIDTH, MODEL_HEIGHT, projection); - - if (output == NULL) { - loadyuv_queue(&loadyuv, q, y_cl, u_cl, v_cl, net_input_cl); - - std::memmove(&input_frames[0], &input_frames[MODEL_FRAME_SIZE], sizeof(float) * MODEL_FRAME_SIZE); - CL_CHECK(clEnqueueReadBuffer(q, net_input_cl, CL_TRUE, 0, MODEL_FRAME_SIZE * sizeof(float), &input_frames[MODEL_FRAME_SIZE], 0, nullptr, nullptr)); - clFinish(q); - return &input_frames[0]; - } else { - loadyuv_queue(&loadyuv, q, y_cl, u_cl, v_cl, *output, true); - // NOTE: Since thneed is using a different command queue, this clFinish is needed to ensure the image is ready. - clFinish(q); - return NULL; - } -} - -ModelFrame::~ModelFrame() { - transform_destroy(&transform); - loadyuv_destroy(&loadyuv); - CL_CHECK(clReleaseMemObject(net_input_cl)); - CL_CHECK(clReleaseMemObject(v_cl)); - CL_CHECK(clReleaseMemObject(u_cl)); - CL_CHECK(clReleaseMemObject(y_cl)); - CL_CHECK(clReleaseCommandQueue(q)); -} diff --git a/sunnypilot/modeld/models/commonmodel.h b/sunnypilot/modeld/models/commonmodel.h deleted file mode 100644 index 9d34ebb6d3..0000000000 --- a/sunnypilot/modeld/models/commonmodel.h +++ /dev/null @@ -1,36 +0,0 @@ -#pragma once - -#include -#include - -#include - -#define CL_USE_DEPRECATED_OPENCL_1_2_APIS -#ifdef __APPLE__ -#include -#else -#include -#endif - -#include "common/mat.h" -#include "sunnypilot/modeld/transforms/loadyuv.h" -#include "sunnypilot/modeld/transforms/transform.h" - -class ModelFrame { -public: - ModelFrame(cl_device_id device_id, cl_context context); - ~ModelFrame(); - float* prepare(cl_mem yuv_cl, int width, int height, int frame_stride, int frame_uv_offset, const mat3& transform, cl_mem *output); - - const int MODEL_WIDTH = 512; - const int MODEL_HEIGHT = 256; - const int MODEL_FRAME_SIZE = MODEL_WIDTH * MODEL_HEIGHT * 3 / 2; - const int buf_size = MODEL_FRAME_SIZE * 2; - -private: - Transform transform; - LoadYUVState loadyuv; - cl_command_queue q; - cl_mem y_cl, u_cl, v_cl, net_input_cl; - std::unique_ptr input_frames; -}; diff --git a/sunnypilot/modeld/models/commonmodel.pxd b/sunnypilot/modeld/models/commonmodel.pxd deleted file mode 100644 index c7fd85411d..0000000000 --- a/sunnypilot/modeld/models/commonmodel.pxd +++ /dev/null @@ -1,18 +0,0 @@ -# distutils: language = c++ - -from msgq.visionipc.visionipc cimport cl_device_id, cl_context, cl_mem - -cdef extern from "common/mat.h": - cdef struct mat3: - float v[9] - -cdef extern from "common/clutil.h": - cdef unsigned long CL_DEVICE_TYPE_DEFAULT - cl_device_id cl_get_device_id(unsigned long) - cl_context cl_create_context(cl_device_id) - -cdef extern from "sunnypilot/modeld/models/commonmodel.h": - cppclass ModelFrame: - int buf_size - ModelFrame(cl_device_id, cl_context) - float * prepare(cl_mem, int, int, int, int, mat3, cl_mem*) diff --git a/sunnypilot/modeld/models/commonmodel_pyx.pxd b/sunnypilot/modeld/models/commonmodel_pyx.pxd deleted file mode 100644 index 0bb798625b..0000000000 --- a/sunnypilot/modeld/models/commonmodel_pyx.pxd +++ /dev/null @@ -1,13 +0,0 @@ -# distutils: language = c++ - -from msgq.visionipc.visionipc cimport cl_mem -from msgq.visionipc.visionipc_pyx cimport CLContext as BaseCLContext - -cdef class CLContext(BaseCLContext): - pass - -cdef class CLMem: - cdef cl_mem * mem - - @staticmethod - cdef create(void*) diff --git a/sunnypilot/modeld/models/commonmodel_pyx.pyx b/sunnypilot/modeld/models/commonmodel_pyx.pyx deleted file mode 100644 index d66fddea54..0000000000 --- a/sunnypilot/modeld/models/commonmodel_pyx.pyx +++ /dev/null @@ -1,45 +0,0 @@ -# distutils: language = c++ -# cython: c_string_encoding=ascii, language_level=3 - -import numpy as np -cimport numpy as cnp -from libc.string cimport memcpy - -from msgq.visionipc.visionipc cimport cl_mem -from msgq.visionipc.visionipc_pyx cimport VisionBuf, CLContext as BaseCLContext -from openpilot.sunnypilot.modeld.models.commonmodel cimport CL_DEVICE_TYPE_DEFAULT, cl_get_device_id, cl_create_context -from openpilot.sunnypilot.modeld.models.commonmodel cimport mat3, ModelFrame as cppModelFrame - - -cdef class CLContext(BaseCLContext): - def __cinit__(self): - self.device_id = cl_get_device_id(CL_DEVICE_TYPE_DEFAULT) - self.context = cl_create_context(self.device_id) - -cdef class CLMem: - @staticmethod - cdef create(void * cmem): - mem = CLMem() - mem.mem = cmem - return mem - -cdef class ModelFrame: - cdef cppModelFrame * frame - - def __cinit__(self, CLContext context): - self.frame = new cppModelFrame(context.device_id, context.context) - - def __dealloc__(self): - del self.frame - - def prepare(self, VisionBuf buf, float[:] projection, CLMem output): - cdef mat3 cprojection - memcpy(cprojection.v, &projection[0], 9*sizeof(float)) - cdef float * data - if output is None: - data = self.frame.prepare(buf.buf.buf_cl, buf.width, buf.height, buf.stride, buf.uv_offset, cprojection, NULL) - else: - data = self.frame.prepare(buf.buf.buf_cl, buf.width, buf.height, buf.stride, buf.uv_offset, cprojection, output.mem) - if not data: - return None - return np.asarray( data) diff --git a/sunnypilot/modeld/parse_model_outputs.py b/sunnypilot/modeld/parse_model_outputs.py deleted file mode 100644 index 9cd5f1465c..0000000000 --- a/sunnypilot/modeld/parse_model_outputs.py +++ /dev/null @@ -1,107 +0,0 @@ -import numpy as np -from openpilot.sunnypilot.modeld.constants import ModelConstants - -def safe_exp(x, out=None): - # -11 is around 10**14, more causes float16 overflow - return np.exp(np.clip(x, -np.inf, 11), out=out) - -def sigmoid(x): - return 1. / (1. + safe_exp(-x)) - -def softmax(x, axis=-1): - x -= np.max(x, axis=axis, keepdims=True) - if x.dtype == np.float32 or x.dtype == np.float64: - safe_exp(x, out=x) - else: - x = safe_exp(x) - x /= np.sum(x, axis=axis, keepdims=True) - return x - -class Parser: - def __init__(self, ignore_missing=False): - self.ignore_missing = ignore_missing - - def check_missing(self, outs, name): - if name not in outs and not self.ignore_missing: - raise ValueError(f"Missing output {name}") - return name not in outs - - def parse_categorical_crossentropy(self, name, outs, out_shape=None): - if self.check_missing(outs, name): - return - raw = outs[name] - if out_shape is not None: - raw = raw.reshape((raw.shape[0],) + out_shape) - outs[name] = softmax(raw, axis=-1) - - def parse_binary_crossentropy(self, name, outs): - if self.check_missing(outs, name): - return - raw = outs[name] - outs[name] = sigmoid(raw) - - def parse_mdn(self, name, outs, in_N=0, out_N=1, out_shape=None): - if self.check_missing(outs, name): - return - raw = outs[name] - raw = raw.reshape((raw.shape[0], max(in_N, 1), -1)) - - n_values = (raw.shape[2] - out_N)//2 - pred_mu = raw[:,:,:n_values] - pred_std = safe_exp(raw[:,:,n_values: 2*n_values]) - - if in_N > 1: - weights = np.zeros((raw.shape[0], in_N, out_N), dtype=raw.dtype) - for i in range(out_N): - weights[:,:,i - out_N] = softmax(raw[:,:,i - out_N], axis=-1) - - if out_N == 1: - for fidx in range(weights.shape[0]): - idxs = np.argsort(weights[fidx][:,0])[::-1] - weights[fidx] = weights[fidx][idxs] - pred_mu[fidx] = pred_mu[fidx][idxs] - pred_std[fidx] = pred_std[fidx][idxs] - full_shape = tuple([raw.shape[0], in_N] + list(out_shape)) - outs[name + '_weights'] = weights - outs[name + '_hypotheses'] = pred_mu.reshape(full_shape) - outs[name + '_stds_hypotheses'] = pred_std.reshape(full_shape) - - pred_mu_final = np.zeros((raw.shape[0], out_N, n_values), dtype=raw.dtype) - pred_std_final = np.zeros((raw.shape[0], out_N, n_values), dtype=raw.dtype) - for fidx in range(weights.shape[0]): - for hidx in range(out_N): - idxs = np.argsort(weights[fidx,:,hidx])[::-1] - pred_mu_final[fidx, hidx] = pred_mu[fidx, idxs[0]] - pred_std_final[fidx, hidx] = pred_std[fidx, idxs[0]] - else: - pred_mu_final = pred_mu - pred_std_final = pred_std - - if out_N > 1: - final_shape = tuple([raw.shape[0], out_N] + list(out_shape)) - else: - final_shape = tuple([raw.shape[0],] + list(out_shape)) - outs[name] = pred_mu_final.reshape(final_shape) - outs[name + '_stds'] = pred_std_final.reshape(final_shape) - - def parse_outputs(self, outs: dict[str, np.ndarray]) -> dict[str, np.ndarray]: - self.parse_mdn('plan', outs, in_N=ModelConstants.PLAN_MHP_N, out_N=ModelConstants.PLAN_MHP_SELECTION, - out_shape=(ModelConstants.IDX_N,ModelConstants.PLAN_WIDTH)) - self.parse_mdn('lane_lines', outs, in_N=0, out_N=0, out_shape=(ModelConstants.NUM_LANE_LINES,ModelConstants.IDX_N,ModelConstants.LANE_LINES_WIDTH)) - self.parse_mdn('road_edges', outs, in_N=0, out_N=0, out_shape=(ModelConstants.NUM_ROAD_EDGES,ModelConstants.IDX_N,ModelConstants.LANE_LINES_WIDTH)) - self.parse_mdn('pose', outs, in_N=0, out_N=0, out_shape=(ModelConstants.POSE_WIDTH,)) - self.parse_mdn('road_transform', outs, in_N=0, out_N=0, out_shape=(ModelConstants.POSE_WIDTH,)) - if 'sim_pose' in outs: - self.parse_mdn('sim_pose', outs, in_N=0, out_N=0, out_shape=(ModelConstants.POSE_WIDTH,)) - self.parse_mdn('wide_from_device_euler', outs, in_N=0, out_N=0, out_shape=(ModelConstants.WIDE_FROM_DEVICE_WIDTH,)) - self.parse_mdn('lead', outs, in_N=ModelConstants.LEAD_MHP_N, out_N=ModelConstants.LEAD_MHP_SELECTION, - out_shape=(ModelConstants.LEAD_TRAJ_LEN,ModelConstants.LEAD_WIDTH)) - if 'lat_planner_solution' in outs: - self.parse_mdn('lat_planner_solution', outs, in_N=0, out_N=0, out_shape=(ModelConstants.IDX_N,ModelConstants.LAT_PLANNER_SOLUTION_WIDTH)) - if 'desired_curvature' in outs: - self.parse_mdn('desired_curvature', outs, in_N=0, out_N=0, out_shape=(ModelConstants.DESIRED_CURV_WIDTH,)) - for k in ['lead_prob', 'lane_lines_prob', 'meta']: - self.parse_binary_crossentropy(k, outs) - self.parse_categorical_crossentropy('desire_state', outs, out_shape=(ModelConstants.DESIRE_PRED_WIDTH,)) - self.parse_categorical_crossentropy('desire_pred', outs, out_shape=(ModelConstants.DESIRE_PRED_LEN,ModelConstants.DESIRE_PRED_WIDTH)) - return outs diff --git a/sunnypilot/modeld/runners/__init__.py b/sunnypilot/modeld/runners/__init__.py deleted file mode 100644 index 3f4507e4eb..0000000000 --- a/sunnypilot/modeld/runners/__init__.py +++ /dev/null @@ -1,27 +0,0 @@ -import os -from openpilot.system.hardware import TICI -from openpilot.sunnypilot.modeld.runners.runmodel_pyx import RunModel, Runtime -assert Runtime - -USE_THNEED = int(os.getenv('USE_THNEED', str(int(TICI)))) -USE_SNPE = int(os.getenv('USE_SNPE', str(int(TICI)))) - -class ModelRunner(RunModel): - THNEED = 'THNEED' - SNPE = 'SNPE' - ONNX = 'ONNX' - - def __new__(cls, paths, *args, **kwargs): - if ModelRunner.THNEED in paths and USE_THNEED: - from openpilot.sunnypilot.modeld.runners.thneedmodel_pyx import ThneedModel as Runner - runner_type = ModelRunner.THNEED - elif ModelRunner.SNPE in paths and USE_SNPE: - from openpilot.sunnypilot.modeld.runners.snpemodel_pyx import SNPEModel as Runner - runner_type = ModelRunner.SNPE - elif ModelRunner.ONNX in paths: - from openpilot.sunnypilot.modeld.runners.onnxmodel import ONNXModel as Runner - runner_type = ModelRunner.ONNX - else: - raise Exception("Couldn't select a model runner, make sure to pass at least one valid model path") - - return Runner(str(paths[runner_type]), *args, **kwargs) diff --git a/sunnypilot/modeld/runners/onnxmodel.py b/sunnypilot/modeld/runners/onnxmodel.py deleted file mode 100644 index 047f13dc9d..0000000000 --- a/sunnypilot/modeld/runners/onnxmodel.py +++ /dev/null @@ -1,98 +0,0 @@ -import onnx -import itertools -import os -import sys -import numpy as np -from typing import Any - -from openpilot.sunnypilot.modeld.runners.runmodel_pyx import RunModel - -ORT_TYPES_TO_NP_TYPES = {'tensor(float16)': np.float16, 'tensor(float)': np.float32, 'tensor(uint8)': np.uint8} - -def attributeproto_fp16_to_fp32(attr): - float32_list = np.frombuffer(attr.raw_data, dtype=np.float16) - attr.data_type = 1 - attr.raw_data = float32_list.astype(np.float32).tobytes() - -def convert_fp16_to_fp32(onnx_path_or_bytes): - if isinstance(onnx_path_or_bytes, bytes): - model = onnx.load_from_string(onnx_path_or_bytes) - elif isinstance(onnx_path_or_bytes, str): - model = onnx.load(onnx_path_or_bytes) - - for i in model.graph.initializer: - if i.data_type == 10: - attributeproto_fp16_to_fp32(i) - for i in itertools.chain(model.graph.input, model.graph.output): - if i.type.tensor_type.elem_type == 10: - i.type.tensor_type.elem_type = 1 - for i in model.graph.node: - if i.op_type == 'Cast' and i.attribute[0].i == 10: - i.attribute[0].i = 1 - for a in i.attribute: - if hasattr(a, 't'): - if a.t.data_type == 10: - attributeproto_fp16_to_fp32(a.t) - return model.SerializeToString() - -def create_ort_session(path, fp16_to_fp32): - os.environ["OMP_NUM_THREADS"] = "4" - os.environ["OMP_WAIT_POLICY"] = "PASSIVE" - - import onnxruntime as ort - print("Onnx available providers: ", ort.get_available_providers(), file=sys.stderr) - options = ort.SessionOptions() - options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_DISABLE_ALL - - provider: str | tuple[str, dict[Any, Any]] - if 'OpenVINOExecutionProvider' in ort.get_available_providers() and 'ONNXCPU' not in os.environ: - provider = 'OpenVINOExecutionProvider' - elif 'CUDAExecutionProvider' in ort.get_available_providers() and 'ONNXCPU' not in os.environ: - options.intra_op_num_threads = 2 - provider = ('CUDAExecutionProvider', {'cudnn_conv_algo_search': 'DEFAULT'}) - else: - options.intra_op_num_threads = 2 - options.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL - options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL - provider = 'CPUExecutionProvider' - - model_data = convert_fp16_to_fp32(path) if fp16_to_fp32 else path - print("Onnx selected provider: ", [provider], file=sys.stderr) - ort_session = ort.InferenceSession(model_data, options, providers=[provider]) - print("Onnx using ", ort_session.get_providers(), file=sys.stderr) - return ort_session - - -class ONNXModel(RunModel): - def __init__(self, path, output, runtime, use_tf8, cl_context): - self.inputs = {} - self.output = output - - self.session = create_ort_session(path, fp16_to_fp32=True) - self.input_names = [x.name for x in self.session.get_inputs()] - self.input_shapes = {x.name: [1, *x.shape[1:]] for x in self.session.get_inputs()} - self.input_dtypes = {x.name: ORT_TYPES_TO_NP_TYPES[x.type] for x in self.session.get_inputs()} - - # run once to initialize CUDA provider - if "CUDAExecutionProvider" in self.session.get_providers(): - self.session.run(None, {k: np.zeros(self.input_shapes[k], dtype=self.input_dtypes[k]) for k in self.input_names}) - print("ready to run onnx model", self.input_shapes, file=sys.stderr) - - def addInput(self, name, buffer): - assert name in self.input_names - self.inputs[name] = buffer - - def setInputBuffer(self, name, buffer): - assert name in self.inputs - self.inputs[name] = buffer - - def getCLBuffer(self, name): - return None - - def execute(self): - inputs = {k: v.view(self.input_dtypes[k]) for k,v in self.inputs.items()} - inputs = {k: v.reshape(self.input_shapes[k]).astype(self.input_dtypes[k]) for k,v in inputs.items()} - outputs = self.session.run(None, inputs) - assert len(outputs) == 1, "Only single model outputs are supported" - self.output[:] = outputs[0] - return self.output diff --git a/sunnypilot/modeld/runners/run.h b/sunnypilot/modeld/runners/run.h deleted file mode 100644 index 84d99fd10f..0000000000 --- a/sunnypilot/modeld/runners/run.h +++ /dev/null @@ -1,4 +0,0 @@ -#pragma once - -#include "sunnypilot/modeld/runners/runmodel.h" -#include "sunnypilot/modeld/runners/snpemodel.h" diff --git a/sunnypilot/modeld/runners/runmodel.h b/sunnypilot/modeld/runners/runmodel.h deleted file mode 100644 index 18cc180cb7..0000000000 --- a/sunnypilot/modeld/runners/runmodel.h +++ /dev/null @@ -1,49 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -#include "common/clutil.h" -#include "common/swaglog.h" - -#define USE_CPU_RUNTIME 0 -#define USE_GPU_RUNTIME 1 -#define USE_DSP_RUNTIME 2 - -struct ModelInput { - const std::string name; - float *buffer; - int size; - - ModelInput(const std::string _name, float *_buffer, int _size) : name(_name), buffer(_buffer), size(_size) {} - virtual void setBuffer(float *_buffer, int _size) { - assert(size == _size || size == 0); - buffer = _buffer; - size = _size; - } -}; - -class RunModel { -public: - std::vector> inputs; - - virtual ~RunModel() {} - virtual void execute() {} - virtual void* getCLBuffer(const std::string name) { return nullptr; } - - virtual void addInput(const std::string name, float *buffer, int size) { - inputs.push_back(std::unique_ptr(new ModelInput(name, buffer, size))); - } - virtual void setInputBuffer(const std::string name, float *buffer, int size) { - for (auto &input : inputs) { - if (name == input->name) { - input->setBuffer(buffer, size); - return; - } - } - LOGE("Tried to update input `%s` but no input with this name exists", name.c_str()); - assert(false); - } -}; diff --git a/sunnypilot/modeld/runners/runmodel.pxd b/sunnypilot/modeld/runners/runmodel.pxd deleted file mode 100644 index b83434473d..0000000000 --- a/sunnypilot/modeld/runners/runmodel.pxd +++ /dev/null @@ -1,14 +0,0 @@ -# distutils: language = c++ - -from libcpp.string cimport string - -cdef extern from "sunnypilot/modeld/runners/runmodel.h": - cdef int USE_CPU_RUNTIME - cdef int USE_GPU_RUNTIME - cdef int USE_DSP_RUNTIME - - cdef cppclass RunModel: - void addInput(string, float*, int) - void setInputBuffer(string, float*, int) - void * getCLBuffer(string) - void execute() diff --git a/sunnypilot/modeld/runners/runmodel_pyx.pxd b/sunnypilot/modeld/runners/runmodel_pyx.pxd deleted file mode 100644 index b6ede7cf37..0000000000 --- a/sunnypilot/modeld/runners/runmodel_pyx.pxd +++ /dev/null @@ -1,6 +0,0 @@ -# distutils: language = c++ - -from .runmodel cimport RunModel as cppRunModel - -cdef class RunModel: - cdef cppRunModel * model diff --git a/sunnypilot/modeld/runners/runmodel_pyx.pyx b/sunnypilot/modeld/runners/runmodel_pyx.pyx deleted file mode 100644 index e224b1e4f2..0000000000 --- a/sunnypilot/modeld/runners/runmodel_pyx.pyx +++ /dev/null @@ -1,37 +0,0 @@ -# distutils: language = c++ -# cython: c_string_encoding=ascii, language_level=3 - -from libcpp.string cimport string - -from .runmodel cimport USE_CPU_RUNTIME, USE_GPU_RUNTIME, USE_DSP_RUNTIME -from sunnypilot.modeld.models.commonmodel_pyx cimport CLMem - -class Runtime: - CPU = USE_CPU_RUNTIME - GPU = USE_GPU_RUNTIME - DSP = USE_DSP_RUNTIME - -cdef class RunModel: - def __dealloc__(self): - del self.model - - def addInput(self, string name, float[:] buffer): - if buffer is not None: - self.model.addInput(name, &buffer[0], len(buffer)) - else: - self.model.addInput(name, NULL, 0) - - def setInputBuffer(self, string name, float[:] buffer): - if buffer is not None: - self.model.setInputBuffer(name, &buffer[0], len(buffer)) - else: - self.model.setInputBuffer(name, NULL, 0) - - def getCLBuffer(self, string name): - cdef void * cl_buf = self.model.getCLBuffer(name) - if not cl_buf: - return None - return CLMem.create(cl_buf) - - def execute(self): - self.model.execute() diff --git a/sunnypilot/modeld/runners/snpemodel.cc b/sunnypilot/modeld/runners/snpemodel.cc deleted file mode 100644 index ce06ba39f7..0000000000 --- a/sunnypilot/modeld/runners/snpemodel.cc +++ /dev/null @@ -1,116 +0,0 @@ -#pragma clang diagnostic ignored "-Wexceptions" - -#include "sunnypilot/modeld/runners/snpemodel.h" - -#include -#include -#include -#include -#include - -#include "common/util.h" -#include "common/timing.h" - -void PrintErrorStringAndExit() { - std::cerr << zdl::DlSystem::getLastErrorString() << std::endl; - std::exit(EXIT_FAILURE); -} - -SNPEModel::SNPEModel(const std::string path, float *_output, size_t _output_size, int runtime, bool _use_tf8, cl_context context) { - output = _output; - output_size = _output_size; - use_tf8 = _use_tf8; - -#ifdef QCOM2 - if (runtime == USE_GPU_RUNTIME) { - snpe_runtime = zdl::DlSystem::Runtime_t::GPU; - } else if (runtime == USE_DSP_RUNTIME) { - snpe_runtime = zdl::DlSystem::Runtime_t::DSP; - } else { - snpe_runtime = zdl::DlSystem::Runtime_t::CPU; - } - assert(zdl::SNPE::SNPEFactory::isRuntimeAvailable(snpe_runtime)); -#endif - model_data = util::read_file(path); - assert(model_data.size() > 0); - - // load model - std::unique_ptr container = zdl::DlContainer::IDlContainer::open((uint8_t*)model_data.data(), model_data.size()); - if (!container) { PrintErrorStringAndExit(); } - LOGW("loaded model with size: %lu", model_data.size()); - - // create model runner - zdl::SNPE::SNPEBuilder snpe_builder(container.get()); - while (!snpe) { -#ifdef QCOM2 - snpe = snpe_builder.setOutputLayers({}) - .setRuntimeProcessor(snpe_runtime) - .setUseUserSuppliedBuffers(true) - .setPerformanceProfile(zdl::DlSystem::PerformanceProfile_t::HIGH_PERFORMANCE) - .build(); -#else - snpe = snpe_builder.setOutputLayers({}) - .setUseUserSuppliedBuffers(true) - .setPerformanceProfile(zdl::DlSystem::PerformanceProfile_t::HIGH_PERFORMANCE) - .build(); -#endif - if (!snpe) std::cerr << zdl::DlSystem::getLastErrorString() << std::endl; - } - - // create output buffer - zdl::DlSystem::UserBufferEncodingFloat ub_encoding_float; - zdl::DlSystem::IUserBufferFactory &ub_factory = zdl::SNPE::SNPEFactory::getUserBufferFactory(); - - const auto &output_tensor_names_opt = snpe->getOutputTensorNames(); - if (!output_tensor_names_opt) throw std::runtime_error("Error obtaining output tensor names"); - const auto &output_tensor_names = *output_tensor_names_opt; - assert(output_tensor_names.size() == 1); - const char *output_tensor_name = output_tensor_names.at(0); - const zdl::DlSystem::TensorShape &buffer_shape = snpe->getInputOutputBufferAttributes(output_tensor_name)->getDims(); - if (output_size != 0) { - assert(output_size == buffer_shape[1]); - } else { - output_size = buffer_shape[1]; - } - std::vector output_strides = {output_size * sizeof(float), sizeof(float)}; - output_buffer = ub_factory.createUserBuffer(output, output_size * sizeof(float), output_strides, &ub_encoding_float); - output_map.add(output_tensor_name, output_buffer.get()); -} - -void SNPEModel::addInput(const std::string name, float *buffer, int size) { - const int idx = inputs.size(); - const auto &input_tensor_names_opt = snpe->getInputTensorNames(); - if (!input_tensor_names_opt) throw std::runtime_error("Error obtaining input tensor names"); - const auto &input_tensor_names = *input_tensor_names_opt; - const char *input_tensor_name = input_tensor_names.at(idx); - const bool input_tf8 = use_tf8 && strcmp(input_tensor_name, "input_img") == 0; // TODO: This is a terrible hack, get rid of this name check both here and in onnx_runner.py - LOGW("adding index %d: %s", idx, input_tensor_name); - - zdl::DlSystem::UserBufferEncodingFloat ub_encoding_float; - zdl::DlSystem::UserBufferEncodingTf8 ub_encoding_tf8(0, 1./255); // network takes 0-1 - zdl::DlSystem::IUserBufferFactory &ub_factory = zdl::SNPE::SNPEFactory::getUserBufferFactory(); - zdl::DlSystem::UserBufferEncoding *input_encoding = input_tf8 ? (zdl::DlSystem::UserBufferEncoding*)&ub_encoding_tf8 : (zdl::DlSystem::UserBufferEncoding*)&ub_encoding_float; - - const auto &buffer_shape_opt = snpe->getInputDimensions(input_tensor_name); - const zdl::DlSystem::TensorShape &buffer_shape = *buffer_shape_opt; - size_t size_of_input = input_tf8 ? sizeof(uint8_t) : sizeof(float); - std::vector strides(buffer_shape.rank()); - strides[strides.size() - 1] = size_of_input; - size_t product = 1; - for (size_t i = 0; i < buffer_shape.rank(); i++) product *= buffer_shape[i]; - size_t stride = strides[strides.size() - 1]; - for (size_t i = buffer_shape.rank() - 1; i > 0; i--) { - stride *= buffer_shape[i]; - strides[i-1] = stride; - } - - auto input_buffer = ub_factory.createUserBuffer(buffer, product*size_of_input, strides, input_encoding); - input_map.add(input_tensor_name, input_buffer.get()); - inputs.push_back(std::unique_ptr(new SNPEModelInput(name, buffer, size, std::move(input_buffer)))); -} - -void SNPEModel::execute() { - if (!snpe->execute(input_map, output_map)) { - PrintErrorStringAndExit(); - } -} diff --git a/sunnypilot/modeld/runners/snpemodel.h b/sunnypilot/modeld/runners/snpemodel.h deleted file mode 100644 index bd76624213..0000000000 --- a/sunnypilot/modeld/runners/snpemodel.h +++ /dev/null @@ -1,52 +0,0 @@ -#pragma once -#pragma clang diagnostic ignored "-Wdeprecated-declarations" - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "sunnypilot/modeld/runners/runmodel.h" - -struct SNPEModelInput : public ModelInput { - std::unique_ptr snpe_buffer; - - SNPEModelInput(const std::string _name, float *_buffer, int _size, std::unique_ptr _snpe_buffer) : ModelInput(_name, _buffer, _size), snpe_buffer(std::move(_snpe_buffer)) {} - void setBuffer(float *_buffer, int _size) { - ModelInput::setBuffer(_buffer, _size); - assert(snpe_buffer->setBufferAddress(_buffer) == true); - } -}; - -class SNPEModel : public RunModel { -public: - SNPEModel(const std::string path, float *_output, size_t _output_size, int runtime, bool use_tf8 = false, cl_context context = NULL); - void addInput(const std::string name, float *buffer, int size); - void execute(); - -private: - std::string model_data; - -#ifdef QCOM2 - zdl::DlSystem::Runtime_t snpe_runtime; -#endif - - // snpe model stuff - std::unique_ptr snpe; - zdl::DlSystem::UserBufferMap input_map; - zdl::DlSystem::UserBufferMap output_map; - std::unique_ptr output_buffer; - - bool use_tf8; - float *output; - size_t output_size; -}; diff --git a/sunnypilot/modeld/runners/snpemodel.pxd b/sunnypilot/modeld/runners/snpemodel.pxd deleted file mode 100644 index f19501d37d..0000000000 --- a/sunnypilot/modeld/runners/snpemodel.pxd +++ /dev/null @@ -1,9 +0,0 @@ -# distutils: language = c++ - -from libcpp.string cimport string - -from msgq.visionipc.visionipc cimport cl_context - -cdef extern from "sunnypilot/modeld/runners/snpemodel.h": - cdef cppclass SNPEModel: - SNPEModel(string, float*, size_t, int, bool, cl_context) diff --git a/sunnypilot/modeld/runners/snpemodel_pyx.pyx b/sunnypilot/modeld/runners/snpemodel_pyx.pyx deleted file mode 100644 index d1f24d1ead..0000000000 --- a/sunnypilot/modeld/runners/snpemodel_pyx.pyx +++ /dev/null @@ -1,17 +0,0 @@ -# distutils: language = c++ -# cython: c_string_encoding=ascii, language_level=3 - -import os -from libcpp cimport bool -from libcpp.string cimport string - -from .snpemodel cimport SNPEModel as cppSNPEModel -from sunnypilot.modeld.models.commonmodel_pyx cimport CLContext -from sunnypilot.modeld.runners.runmodel_pyx cimport RunModel -from sunnypilot.modeld.runners.runmodel cimport RunModel as cppRunModel - -os.environ['ADSP_LIBRARY_PATH'] = "/data/pythonpath/third_party/snpe/dsp/" - -cdef class SNPEModel(RunModel): - def __cinit__(self, string path, float[:] output, int runtime, bool use_tf8, CLContext context): - self.model = new cppSNPEModel(path, &output[0], len(output), runtime, use_tf8, context.context) diff --git a/sunnypilot/modeld/runners/thneedmodel.cc b/sunnypilot/modeld/runners/thneedmodel.cc deleted file mode 100644 index d83fc0a5f9..0000000000 --- a/sunnypilot/modeld/runners/thneedmodel.cc +++ /dev/null @@ -1,58 +0,0 @@ -#include "sunnypilot/modeld/runners/thneedmodel.h" - -#include - -#include "common/swaglog.h" - -ThneedModel::ThneedModel(const std::string path, float *_output, size_t _output_size, int runtime, bool luse_tf8, cl_context context) { - thneed = new Thneed(true, context); - thneed->load(path.c_str()); - thneed->clexec(); - - recorded = false; - output = _output; -} - -void* ThneedModel::getCLBuffer(const std::string name) { - int index = -1; - for (int i = 0; i < inputs.size(); i++) { - if (name == inputs[i]->name) { - index = i; - break; - } - } - - if (index == -1) { - LOGE("Tried to get CL buffer for input `%s` but no input with this name exists", name.c_str()); - assert(false); - } - - if (thneed->input_clmem.size() >= inputs.size()) { - return &thneed->input_clmem[inputs.size() - index - 1]; - } else { - return nullptr; - } -} - -void ThneedModel::execute() { - if (!recorded) { - thneed->record = true; - float *input_buffers[inputs.size()]; - for (int i = 0; i < inputs.size(); i++) { - input_buffers[inputs.size() - i - 1] = inputs[i]->buffer; - } - - thneed->copy_inputs(input_buffers); - thneed->clexec(); - thneed->copy_output(output); - thneed->stop(); - - recorded = true; - } else { - float *input_buffers[inputs.size()]; - for (int i = 0; i < inputs.size(); i++) { - input_buffers[inputs.size() - i - 1] = inputs[i]->buffer; - } - thneed->execute(input_buffers, output); - } -} diff --git a/sunnypilot/modeld/runners/thneedmodel.h b/sunnypilot/modeld/runners/thneedmodel.h deleted file mode 100644 index ecc7207c1f..0000000000 --- a/sunnypilot/modeld/runners/thneedmodel.h +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once - -#include - -#include "sunnypilot/modeld/runners/runmodel.h" -#include "sunnypilot/modeld/thneed/thneed.h" - -class ThneedModel : public RunModel { -public: - ThneedModel(const std::string path, float *_output, size_t _output_size, int runtime, bool use_tf8 = false, cl_context context = NULL); - void *getCLBuffer(const std::string name); - void execute(); -private: - Thneed *thneed = NULL; - bool recorded; - float *output; -}; diff --git a/sunnypilot/modeld/runners/thneedmodel.pxd b/sunnypilot/modeld/runners/thneedmodel.pxd deleted file mode 100644 index ace7443b50..0000000000 --- a/sunnypilot/modeld/runners/thneedmodel.pxd +++ /dev/null @@ -1,9 +0,0 @@ -# distutils: language = c++ - -from libcpp.string cimport string - -from msgq.visionipc.visionipc cimport cl_context - -cdef extern from "sunnypilot/modeld/runners/thneedmodel.h": - cdef cppclass ThneedModel: - ThneedModel(string, float*, size_t, int, bool, cl_context) diff --git a/sunnypilot/modeld/runners/thneedmodel_pyx.pyx b/sunnypilot/modeld/runners/thneedmodel_pyx.pyx deleted file mode 100644 index 49de8344c0..0000000000 --- a/sunnypilot/modeld/runners/thneedmodel_pyx.pyx +++ /dev/null @@ -1,14 +0,0 @@ -# distutils: language = c++ -# cython: c_string_encoding=ascii, language_level=3 - -from libcpp cimport bool -from libcpp.string cimport string - -from .thneedmodel cimport ThneedModel as cppThneedModel -from sunnypilot.modeld.models.commonmodel_pyx cimport CLContext -from sunnypilot.modeld.runners.runmodel_pyx cimport RunModel -from sunnypilot.modeld.runners.runmodel cimport RunModel as cppRunModel - -cdef class ThneedModel(RunModel): - def __cinit__(self, string path, float[:] output, int runtime, bool use_tf8, CLContext context): - self.model = new cppThneedModel(path, &output[0], len(output), runtime, use_tf8, context.context) diff --git a/sunnypilot/modeld/thneed/README b/sunnypilot/modeld/thneed/README deleted file mode 100644 index f3bc66d8fc..0000000000 --- a/sunnypilot/modeld/thneed/README +++ /dev/null @@ -1,8 +0,0 @@ -thneed is an SNPE accelerator. I know SNPE is already an accelerator, but sometimes things need to go even faster.. - -It runs on the local device, and caches a single model run. Then it replays it, but fast. - -thneed slices through abstraction layers like a fish. - -You need a thneed. - diff --git a/sunnypilot/modeld/thneed/clutil_legacy.cc b/sunnypilot/modeld/thneed/clutil_legacy.cc deleted file mode 100644 index 3bf9316432..0000000000 --- a/sunnypilot/modeld/thneed/clutil_legacy.cc +++ /dev/null @@ -1,126 +0,0 @@ -#include "common/clutil.h" - -#include -#include -#include - -#include "common/util.h" -#include "common/swaglog.h" -#include "sunnypilot/modeld/thneed/clutil_legacy.h" - -void cl_print_build_errors(cl_program program, cl_device_id device) { - cl_build_status status; - clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_STATUS, sizeof(status), &status, NULL); - size_t log_size; - clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, 0, NULL, &log_size); - std::string log(log_size, '\0'); - clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, log_size, &log[0], NULL); - - LOGE("build failed; status=%d, log: %s", status, log.c_str()); -} - -cl_program cl_program_from_binary(cl_context ctx, cl_device_id device_id, const uint8_t* binary, size_t length, const char* args) { - cl_program prg = CL_CHECK_ERR(clCreateProgramWithBinary(ctx, 1, &device_id, &length, &binary, NULL, &err)); - if (int err = clBuildProgram(prg, 1, &device_id, args, NULL, NULL); err != 0) { - cl_print_build_errors(prg, device_id); - assert(0); - } - return prg; -} - -// Given a cl code and return a string representation -#define CL_ERR_TO_STR(err) case err: return #err -const char* cl_get_error_string(int err) { - switch (err) { - CL_ERR_TO_STR(CL_SUCCESS); - CL_ERR_TO_STR(CL_DEVICE_NOT_FOUND); - CL_ERR_TO_STR(CL_DEVICE_NOT_AVAILABLE); - CL_ERR_TO_STR(CL_COMPILER_NOT_AVAILABLE); - CL_ERR_TO_STR(CL_MEM_OBJECT_ALLOCATION_FAILURE); - CL_ERR_TO_STR(CL_OUT_OF_RESOURCES); - CL_ERR_TO_STR(CL_OUT_OF_HOST_MEMORY); - CL_ERR_TO_STR(CL_PROFILING_INFO_NOT_AVAILABLE); - CL_ERR_TO_STR(CL_MEM_COPY_OVERLAP); - CL_ERR_TO_STR(CL_IMAGE_FORMAT_MISMATCH); - CL_ERR_TO_STR(CL_IMAGE_FORMAT_NOT_SUPPORTED); - CL_ERR_TO_STR(CL_MAP_FAILURE); - CL_ERR_TO_STR(CL_MISALIGNED_SUB_BUFFER_OFFSET); - CL_ERR_TO_STR(CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST); - CL_ERR_TO_STR(CL_COMPILE_PROGRAM_FAILURE); - CL_ERR_TO_STR(CL_LINKER_NOT_AVAILABLE); - CL_ERR_TO_STR(CL_LINK_PROGRAM_FAILURE); - CL_ERR_TO_STR(CL_DEVICE_PARTITION_FAILED); - CL_ERR_TO_STR(CL_KERNEL_ARG_INFO_NOT_AVAILABLE); - CL_ERR_TO_STR(CL_INVALID_VALUE); - CL_ERR_TO_STR(CL_INVALID_DEVICE_TYPE); - CL_ERR_TO_STR(CL_INVALID_PLATFORM); - CL_ERR_TO_STR(CL_INVALID_DEVICE); - CL_ERR_TO_STR(CL_INVALID_CONTEXT); - CL_ERR_TO_STR(CL_INVALID_QUEUE_PROPERTIES); - CL_ERR_TO_STR(CL_INVALID_COMMAND_QUEUE); - CL_ERR_TO_STR(CL_INVALID_HOST_PTR); - CL_ERR_TO_STR(CL_INVALID_MEM_OBJECT); - CL_ERR_TO_STR(CL_INVALID_IMAGE_FORMAT_DESCRIPTOR); - CL_ERR_TO_STR(CL_INVALID_IMAGE_SIZE); - CL_ERR_TO_STR(CL_INVALID_SAMPLER); - CL_ERR_TO_STR(CL_INVALID_BINARY); - CL_ERR_TO_STR(CL_INVALID_BUILD_OPTIONS); - CL_ERR_TO_STR(CL_INVALID_PROGRAM); - CL_ERR_TO_STR(CL_INVALID_PROGRAM_EXECUTABLE); - CL_ERR_TO_STR(CL_INVALID_KERNEL_NAME); - CL_ERR_TO_STR(CL_INVALID_KERNEL_DEFINITION); - CL_ERR_TO_STR(CL_INVALID_KERNEL); - CL_ERR_TO_STR(CL_INVALID_ARG_INDEX); - CL_ERR_TO_STR(CL_INVALID_ARG_VALUE); - CL_ERR_TO_STR(CL_INVALID_ARG_SIZE); - CL_ERR_TO_STR(CL_INVALID_KERNEL_ARGS); - CL_ERR_TO_STR(CL_INVALID_WORK_DIMENSION); - CL_ERR_TO_STR(CL_INVALID_WORK_GROUP_SIZE); - CL_ERR_TO_STR(CL_INVALID_WORK_ITEM_SIZE); - CL_ERR_TO_STR(CL_INVALID_GLOBAL_OFFSET); - CL_ERR_TO_STR(CL_INVALID_EVENT_WAIT_LIST); - CL_ERR_TO_STR(CL_INVALID_EVENT); - CL_ERR_TO_STR(CL_INVALID_OPERATION); - CL_ERR_TO_STR(CL_INVALID_GL_OBJECT); - CL_ERR_TO_STR(CL_INVALID_BUFFER_SIZE); - CL_ERR_TO_STR(CL_INVALID_MIP_LEVEL); - CL_ERR_TO_STR(CL_INVALID_GLOBAL_WORK_SIZE); - CL_ERR_TO_STR(CL_INVALID_PROPERTY); - CL_ERR_TO_STR(CL_INVALID_IMAGE_DESCRIPTOR); - CL_ERR_TO_STR(CL_INVALID_COMPILER_OPTIONS); - CL_ERR_TO_STR(CL_INVALID_LINKER_OPTIONS); - CL_ERR_TO_STR(CL_INVALID_DEVICE_PARTITION_COUNT); - case -69: return "CL_INVALID_PIPE_SIZE"; - case -70: return "CL_INVALID_DEVICE_QUEUE"; - case -71: return "CL_INVALID_SPEC_ID"; - case -72: return "CL_MAX_SIZE_RESTRICTION_EXCEEDED"; - case -1002: return "CL_INVALID_D3D10_DEVICE_KHR"; - case -1003: return "CL_INVALID_D3D10_RESOURCE_KHR"; - case -1004: return "CL_D3D10_RESOURCE_ALREADY_ACQUIRED_KHR"; - case -1005: return "CL_D3D10_RESOURCE_NOT_ACQUIRED_KHR"; - case -1006: return "CL_INVALID_D3D11_DEVICE_KHR"; - case -1007: return "CL_INVALID_D3D11_RESOURCE_KHR"; - case -1008: return "CL_D3D11_RESOURCE_ALREADY_ACQUIRED_KHR"; - case -1009: return "CL_D3D11_RESOURCE_NOT_ACQUIRED_KHR"; - case -1010: return "CL_INVALID_DX9_MEDIA_ADAPTER_KHR"; - case -1011: return "CL_INVALID_DX9_MEDIA_SURFACE_KHR"; - case -1012: return "CL_DX9_MEDIA_SURFACE_ALREADY_ACQUIRED_KHR"; - case -1013: return "CL_DX9_MEDIA_SURFACE_NOT_ACQUIRED_KHR"; - case -1093: return "CL_INVALID_EGL_OBJECT_KHR"; - case -1092: return "CL_EGL_RESOURCE_NOT_ACQUIRED_KHR"; - case -1001: return "CL_PLATFORM_NOT_FOUND_KHR"; - case -1057: return "CL_DEVICE_PARTITION_FAILED_EXT"; - case -1058: return "CL_INVALID_PARTITION_COUNT_EXT"; - case -1059: return "CL_INVALID_PARTITION_NAME_EXT"; - case -1094: return "CL_INVALID_ACCELERATOR_INTEL"; - case -1095: return "CL_INVALID_ACCELERATOR_TYPE_INTEL"; - case -1096: return "CL_INVALID_ACCELERATOR_DESCRIPTOR_INTEL"; - case -1097: return "CL_ACCELERATOR_TYPE_NOT_SUPPORTED_INTEL"; - case -1000: return "CL_INVALID_GL_SHAREGROUP_REFERENCE_KHR"; - case -1098: return "CL_INVALID_VA_API_MEDIA_ADAPTER_INTEL"; - case -1099: return "CL_INVALID_VA_API_MEDIA_SURFACE_INTEL"; - case -1100: return "CL_VA_API_MEDIA_SURFACE_ALREADY_ACQUIRED_INTEL"; - case -1101: return "CL_VA_API_MEDIA_SURFACE_NOT_ACQUIRED_INTEL"; - default: return "CL_UNKNOWN_ERROR"; - } -} \ No newline at end of file diff --git a/sunnypilot/modeld/thneed/clutil_legacy.h b/sunnypilot/modeld/thneed/clutil_legacy.h deleted file mode 100644 index 8aebdcf1a9..0000000000 --- a/sunnypilot/modeld/thneed/clutil_legacy.h +++ /dev/null @@ -1,13 +0,0 @@ -#pragma once - -#include "common/clutil.h" -#ifdef __APPLE__ -#include -#else -#include -#endif - -#include - -cl_program cl_program_from_binary(cl_context ctx, cl_device_id device_id, const uint8_t* binary, size_t length, const char* args = nullptr); -const char* cl_get_error_string(int err); \ No newline at end of file diff --git a/sunnypilot/modeld/thneed/serialize.cc b/sunnypilot/modeld/thneed/serialize.cc deleted file mode 100644 index 9279a90e0f..0000000000 --- a/sunnypilot/modeld/thneed/serialize.cc +++ /dev/null @@ -1,155 +0,0 @@ -#include -#include - -#include "third_party/json11/json11.hpp" -#include "common/util.h" -#include "common/clutil.h" -#include "common/swaglog.h" -#include "sunnypilot/modeld/thneed/thneed.h" -#include "sunnypilot/modeld/thneed/clutil_legacy.h" -using namespace json11; - -extern map g_program_source; - -void Thneed::load(const char *filename) { - LOGD("Thneed::load: loading from %s\n", filename); - - string buf = util::read_file(filename); - int jsz = *(int *)buf.data(); - string jsonerr; - string jj(buf.data() + sizeof(int), jsz); - Json jdat = Json::parse(jj, jsonerr); - - map real_mem; - real_mem[NULL] = NULL; - - int ptr = sizeof(int)+jsz; - for (auto &obj : jdat["objects"].array_items()) { - auto mobj = obj.object_items(); - int sz = mobj["size"].int_value(); - cl_mem clbuf = NULL; - - if (mobj["buffer_id"].string_value().size() > 0) { - // image buffer must already be allocated - clbuf = real_mem[*(cl_mem*)(mobj["buffer_id"].string_value().data())]; - assert(mobj["needs_load"].bool_value() == false); - } else { - if (mobj["needs_load"].bool_value()) { - clbuf = clCreateBuffer(context, CL_MEM_COPY_HOST_PTR | CL_MEM_READ_WRITE, sz, &buf[ptr], NULL); - if (debug >= 1) printf("loading %p %d @ 0x%X\n", clbuf, sz, ptr); - ptr += sz; - } else { - // TODO: is there a faster way to init zeroed out buffers? - void *host_zeros = calloc(sz, 1); - clbuf = clCreateBuffer(context, CL_MEM_COPY_HOST_PTR | CL_MEM_READ_WRITE, sz, host_zeros, NULL); - free(host_zeros); - } - } - assert(clbuf != NULL); - - if (mobj["arg_type"] == "image2d_t" || mobj["arg_type"] == "image1d_t") { - cl_image_desc desc = {0}; - desc.image_type = (mobj["arg_type"] == "image2d_t") ? CL_MEM_OBJECT_IMAGE2D : CL_MEM_OBJECT_IMAGE1D_BUFFER; - desc.image_width = mobj["width"].int_value(); - desc.image_height = mobj["height"].int_value(); - desc.image_row_pitch = mobj["row_pitch"].int_value(); - assert(sz == desc.image_height*desc.image_row_pitch); -#ifdef QCOM2 - desc.buffer = clbuf; -#else - // TODO: we are creating unused buffers on PC - clReleaseMemObject(clbuf); -#endif - cl_image_format format = {0}; - format.image_channel_order = CL_RGBA; - format.image_channel_data_type = mobj["float32"].bool_value() ? CL_FLOAT : CL_HALF_FLOAT; - - cl_int errcode; - -#ifndef QCOM2 - if (mobj["needs_load"].bool_value()) { - clbuf = clCreateImage(context, CL_MEM_COPY_HOST_PTR | CL_MEM_READ_WRITE, &format, &desc, &buf[ptr-sz], &errcode); - } else { - clbuf = clCreateImage(context, CL_MEM_READ_WRITE, &format, &desc, NULL, &errcode); - } -#else - clbuf = clCreateImage(context, CL_MEM_READ_WRITE, &format, &desc, NULL, &errcode); -#endif - if (clbuf == NULL) { - LOGE("clError: %s create image %zux%zu rp %zu with buffer %p\n", cl_get_error_string(errcode), - desc.image_width, desc.image_height, desc.image_row_pitch, desc.buffer); - } - assert(clbuf != NULL); - } - - real_mem[*(cl_mem*)(mobj["id"].string_value().data())] = clbuf; - } - - map g_programs; - for (const auto &[name, source] : jdat["programs"].object_items()) { - if (debug >= 1) printf("building %s with size %zu\n", name.c_str(), source.string_value().size()); - g_programs[name] = cl_program_from_source(context, device_id, source.string_value()); - } - - for (auto &obj : jdat["inputs"].array_items()) { - auto mobj = obj.object_items(); - int sz = mobj["size"].int_value(); - cl_mem aa = real_mem[*(cl_mem*)(mobj["buffer_id"].string_value().data())]; - input_clmem.push_back(aa); - input_sizes.push_back(sz); - LOGD("Thneed::load: adding input %s with size %d\n", mobj["name"].string_value().data(), sz); - - cl_int cl_err; - void *ret = clEnqueueMapBuffer(command_queue, aa, CL_TRUE, CL_MAP_WRITE, 0, sz, 0, NULL, NULL, &cl_err); - if (cl_err != CL_SUCCESS) LOGE("clError: %s map %p %d\n", cl_get_error_string(cl_err), aa, sz); - assert(cl_err == CL_SUCCESS); - inputs.push_back(ret); - } - - for (auto &obj : jdat["outputs"].array_items()) { - auto mobj = obj.object_items(); - int sz = mobj["size"].int_value(); - LOGD("Thneed::save: adding output with size %d\n", sz); - // TODO: support multiple outputs - output = real_mem[*(cl_mem*)(mobj["buffer_id"].string_value().data())]; - assert(output != NULL); - } - - for (auto &obj : jdat["binaries"].array_items()) { - string name = obj["name"].string_value(); - size_t length = obj["length"].int_value(); - if (debug >= 1) printf("binary %s with size %zu\n", name.c_str(), length); - g_programs[name] = cl_program_from_binary(context, device_id, (const uint8_t*)&buf[ptr], length); - ptr += length; - } - - for (auto &obj : jdat["kernels"].array_items()) { - auto gws = obj["global_work_size"]; - auto lws = obj["local_work_size"]; - auto kk = shared_ptr(new CLQueuedKernel(this)); - - kk->name = obj["name"].string_value(); - kk->program = g_programs[kk->name]; - kk->work_dim = obj["work_dim"].int_value(); - for (int i = 0; i < kk->work_dim; i++) { - kk->global_work_size[i] = gws[i].int_value(); - kk->local_work_size[i] = lws[i].int_value(); - } - kk->num_args = obj["num_args"].int_value(); - for (int i = 0; i < kk->num_args; i++) { - string arg = obj["args"].array_items()[i].string_value(); - int arg_size = obj["args_size"].array_items()[i].int_value(); - kk->args_size.push_back(arg_size); - if (arg_size == 8) { - cl_mem val = *(cl_mem*)(arg.data()); - val = real_mem[val]; - kk->args.push_back(string((char*)&val, sizeof(val))); - } else { - kk->args.push_back(arg); - } - } - kq.push_back(kk); - } - - clFinish(command_queue); -} diff --git a/sunnypilot/modeld/thneed/thneed.h b/sunnypilot/modeld/thneed/thneed.h deleted file mode 100644 index 47e18e0be3..0000000000 --- a/sunnypilot/modeld/thneed/thneed.h +++ /dev/null @@ -1,133 +0,0 @@ -#pragma once - -#ifndef __user -#define __user __attribute__(()) -#endif - -#include -#include -#include -#include -#include - -#include - -#include "third_party/linux/include/msm_kgsl.h" - -using namespace std; - -cl_int thneed_clSetKernelArg(cl_kernel kernel, cl_uint arg_index, size_t arg_size, const void *arg_value); - -namespace json11 { - class Json; -} -class Thneed; - -class GPUMalloc { - public: - GPUMalloc(int size, int fd); - ~GPUMalloc(); - void *alloc(int size); - private: - uint64_t base; - int remaining; -}; - -class CLQueuedKernel { - public: - CLQueuedKernel(Thneed *lthneed) { thneed = lthneed; } - CLQueuedKernel(Thneed *lthneed, - cl_kernel _kernel, - cl_uint _work_dim, - const size_t *_global_work_size, - const size_t *_local_work_size); - cl_int exec(); - void debug_print(bool verbose); - int get_arg_num(const char *search_arg_name); - cl_program program; - string name; - cl_uint num_args; - vector arg_names; - vector arg_types; - vector args; - vector args_size; - cl_kernel kernel = NULL; - json11::Json to_json() const; - - cl_uint work_dim; - size_t global_work_size[3] = {0}; - size_t local_work_size[3] = {0}; - private: - Thneed *thneed; -}; - -class CachedIoctl { - public: - virtual void exec() {} -}; - -class CachedSync: public CachedIoctl { - public: - CachedSync(Thneed *lthneed, string ldata) { thneed = lthneed; data = ldata; } - void exec(); - private: - Thneed *thneed; - string data; -}; - -class CachedCommand: public CachedIoctl { - public: - CachedCommand(Thneed *lthneed, struct kgsl_gpu_command *cmd); - void exec(); - private: - void disassemble(int cmd_index); - struct kgsl_gpu_command cache; - unique_ptr cmds; - unique_ptr objs; - Thneed *thneed; - vector > kq; -}; - -class Thneed { - public: - Thneed(bool do_clinit=false, cl_context _context = NULL); - void stop(); - void execute(float **finputs, float *foutput, bool slow=false); - void wait(); - - vector input_clmem; - vector inputs; - vector input_sizes; - cl_mem output = NULL; - - cl_context context = NULL; - cl_command_queue command_queue; - cl_device_id device_id; - int context_id; - - // protected? - bool record = false; - int debug; - int timestamp; - -#ifdef QCOM2 - unique_ptr ram; - vector > cmds; - int fd; -#endif - - // all CL kernels - void copy_inputs(float **finputs, bool internal=false); - void copy_output(float *foutput); - cl_int clexec(); - vector > kq; - - // pending CL kernels - vector > ckq; - - // loading - void load(const char *filename); - private: - void clinit(); -}; - diff --git a/sunnypilot/modeld/thneed/thneed_common.cc b/sunnypilot/modeld/thneed/thneed_common.cc deleted file mode 100644 index 56fbe70d8f..0000000000 --- a/sunnypilot/modeld/thneed/thneed_common.cc +++ /dev/null @@ -1,216 +0,0 @@ -#include "sunnypilot/modeld/thneed/thneed.h" - -#include -#include -#include - -#include "common/clutil.h" -#include "common/timing.h" - -map, string> g_args; -map, int> g_args_size; -map g_program_source; - -void Thneed::stop() { - //printf("Thneed::stop: recorded %lu commands\n", cmds.size()); - record = false; -} - -void Thneed::clinit() { - device_id = cl_get_device_id(CL_DEVICE_TYPE_DEFAULT); - if (context == NULL) context = CL_CHECK_ERR(clCreateContext(NULL, 1, &device_id, NULL, NULL, &err)); - //cl_command_queue_properties props[3] = {CL_QUEUE_PROPERTIES, CL_QUEUE_PROFILING_ENABLE, 0}; - cl_command_queue_properties props[3] = {CL_QUEUE_PROPERTIES, 0, 0}; - command_queue = CL_CHECK_ERR(clCreateCommandQueueWithProperties(context, device_id, props, &err)); - printf("Thneed::clinit done\n"); -} - -cl_int Thneed::clexec() { - if (debug >= 1) printf("Thneed::clexec: running %lu queued kernels\n", kq.size()); - for (auto &k : kq) { - if (record) ckq.push_back(k); - cl_int ret = k->exec(); - assert(ret == CL_SUCCESS); - } - return clFinish(command_queue); -} - -void Thneed::copy_inputs(float **finputs, bool internal) { - for (int idx = 0; idx < inputs.size(); ++idx) { - if (debug >= 1) printf("copying %lu -- %p -> %p (cl %p)\n", input_sizes[idx], finputs[idx], inputs[idx], input_clmem[idx]); - - if (internal) { - // if it's internal, using memcpy is fine since the buffer sync is cached in the ioctl layer - if (finputs[idx] != NULL) memcpy(inputs[idx], finputs[idx], input_sizes[idx]); - } else { - if (finputs[idx] != NULL) CL_CHECK(clEnqueueWriteBuffer(command_queue, input_clmem[idx], CL_TRUE, 0, input_sizes[idx], finputs[idx], 0, NULL, NULL)); - } - } -} - -void Thneed::copy_output(float *foutput) { - if (output != NULL) { - size_t sz; - clGetMemObjectInfo(output, CL_MEM_SIZE, sizeof(sz), &sz, NULL); - if (debug >= 1) printf("copying %lu for output %p -> %p\n", sz, output, foutput); - CL_CHECK(clEnqueueReadBuffer(command_queue, output, CL_TRUE, 0, sz, foutput, 0, NULL, NULL)); - } else { - printf("CAUTION: model output is NULL, does it have no outputs?\n"); - } -} - -// *********** CLQueuedKernel *********** - -CLQueuedKernel::CLQueuedKernel(Thneed *lthneed, - cl_kernel _kernel, - cl_uint _work_dim, - const size_t *_global_work_size, - const size_t *_local_work_size) { - thneed = lthneed; - kernel = _kernel; - work_dim = _work_dim; - assert(work_dim <= 3); - for (int i = 0; i < work_dim; i++) { - global_work_size[i] = _global_work_size[i]; - local_work_size[i] = _local_work_size[i]; - } - - char _name[0x100]; - clGetKernelInfo(kernel, CL_KERNEL_FUNCTION_NAME, sizeof(_name), _name, NULL); - name = string(_name); - clGetKernelInfo(kernel, CL_KERNEL_NUM_ARGS, sizeof(num_args), &num_args, NULL); - - // get args - for (int i = 0; i < num_args; i++) { - char arg_name[0x100] = {0}; - clGetKernelArgInfo(kernel, i, CL_KERNEL_ARG_NAME, sizeof(arg_name), arg_name, NULL); - arg_names.push_back(string(arg_name)); - clGetKernelArgInfo(kernel, i, CL_KERNEL_ARG_TYPE_NAME, sizeof(arg_name), arg_name, NULL); - arg_types.push_back(string(arg_name)); - - args.push_back(g_args[make_pair(kernel, i)]); - args_size.push_back(g_args_size[make_pair(kernel, i)]); - } - - // get program - clGetKernelInfo(kernel, CL_KERNEL_PROGRAM, sizeof(program), &program, NULL); -} - -int CLQueuedKernel::get_arg_num(const char *search_arg_name) { - for (int i = 0; i < num_args; i++) { - if (arg_names[i] == search_arg_name) return i; - } - printf("failed to find %s in %s\n", search_arg_name, name.c_str()); - assert(false); -} - -cl_int CLQueuedKernel::exec() { - if (kernel == NULL) { - kernel = clCreateKernel(program, name.c_str(), NULL); - arg_names.clear(); - arg_types.clear(); - - for (int j = 0; j < num_args; j++) { - char arg_name[0x100] = {0}; - clGetKernelArgInfo(kernel, j, CL_KERNEL_ARG_NAME, sizeof(arg_name), arg_name, NULL); - arg_names.push_back(string(arg_name)); - clGetKernelArgInfo(kernel, j, CL_KERNEL_ARG_TYPE_NAME, sizeof(arg_name), arg_name, NULL); - arg_types.push_back(string(arg_name)); - - cl_int ret; - if (args[j].size() != 0) { - assert(args[j].size() == args_size[j]); - ret = thneed_clSetKernelArg(kernel, j, args[j].size(), args[j].data()); - } else { - ret = thneed_clSetKernelArg(kernel, j, args_size[j], NULL); - } - assert(ret == CL_SUCCESS); - } - } - - if (thneed->debug >= 1) { - debug_print(thneed->debug >= 2); - } - - return clEnqueueNDRangeKernel(thneed->command_queue, - kernel, work_dim, NULL, global_work_size, local_work_size, 0, NULL, NULL); -} - -void CLQueuedKernel::debug_print(bool verbose) { - printf("%p %56s -- ", kernel, name.c_str()); - for (int i = 0; i < work_dim; i++) { - printf("%4zu ", global_work_size[i]); - } - printf(" -- "); - for (int i = 0; i < work_dim; i++) { - printf("%4zu ", local_work_size[i]); - } - printf("\n"); - - if (verbose) { - for (int i = 0; i < num_args; i++) { - string arg = args[i]; - printf(" %s %s", arg_types[i].c_str(), arg_names[i].c_str()); - void *arg_value = (void*)arg.data(); - int arg_size = arg.size(); - if (arg_size == 0) { - printf(" (size) %d", args_size[i]); - } else if (arg_size == 1) { - printf(" = %d", *((char*)arg_value)); - } else if (arg_size == 2) { - printf(" = %d", *((short*)arg_value)); - } else if (arg_size == 4) { - if (arg_types[i] == "float") { - printf(" = %f", *((float*)arg_value)); - } else { - printf(" = %d", *((int*)arg_value)); - } - } else if (arg_size == 8) { - cl_mem val = (cl_mem)(*((uintptr_t*)arg_value)); - printf(" = %p", val); - if (val != NULL) { - cl_mem_object_type obj_type; - clGetMemObjectInfo(val, CL_MEM_TYPE, sizeof(obj_type), &obj_type, NULL); - if (arg_types[i] == "image2d_t" || arg_types[i] == "image1d_t" || obj_type == CL_MEM_OBJECT_IMAGE2D) { - cl_image_format format; - size_t width, height, depth, array_size, row_pitch, slice_pitch; - cl_mem buf; - clGetImageInfo(val, CL_IMAGE_FORMAT, sizeof(format), &format, NULL); - assert(format.image_channel_order == CL_RGBA); - assert(format.image_channel_data_type == CL_HALF_FLOAT || format.image_channel_data_type == CL_FLOAT); - clGetImageInfo(val, CL_IMAGE_WIDTH, sizeof(width), &width, NULL); - clGetImageInfo(val, CL_IMAGE_HEIGHT, sizeof(height), &height, NULL); - clGetImageInfo(val, CL_IMAGE_ROW_PITCH, sizeof(row_pitch), &row_pitch, NULL); - clGetImageInfo(val, CL_IMAGE_DEPTH, sizeof(depth), &depth, NULL); - clGetImageInfo(val, CL_IMAGE_ARRAY_SIZE, sizeof(array_size), &array_size, NULL); - clGetImageInfo(val, CL_IMAGE_SLICE_PITCH, sizeof(slice_pitch), &slice_pitch, NULL); - assert(depth == 0); - assert(array_size == 0); - assert(slice_pitch == 0); - - clGetImageInfo(val, CL_IMAGE_BUFFER, sizeof(buf), &buf, NULL); - size_t sz = 0; - if (buf != NULL) clGetMemObjectInfo(buf, CL_MEM_SIZE, sizeof(sz), &sz, NULL); - printf(" image %zu x %zu rp %zu @ %p buffer %zu", width, height, row_pitch, buf, sz); - } else { - size_t sz; - clGetMemObjectInfo(val, CL_MEM_SIZE, sizeof(sz), &sz, NULL); - printf(" buffer %zu", sz); - } - } - } - printf("\n"); - } - } -} - -cl_int thneed_clSetKernelArg(cl_kernel kernel, cl_uint arg_index, size_t arg_size, const void *arg_value) { - g_args_size[make_pair(kernel, arg_index)] = arg_size; - if (arg_value != NULL) { - g_args[make_pair(kernel, arg_index)] = string((char*)arg_value, arg_size); - } else { - g_args[make_pair(kernel, arg_index)] = string(""); - } - cl_int ret = clSetKernelArg(kernel, arg_index, arg_size, arg_value); - return ret; -} diff --git a/sunnypilot/modeld/thneed/thneed_pc.cc b/sunnypilot/modeld/thneed/thneed_pc.cc deleted file mode 100644 index 629d0ee359..0000000000 --- a/sunnypilot/modeld/thneed/thneed_pc.cc +++ /dev/null @@ -1,32 +0,0 @@ -#include "sunnypilot/modeld/thneed/thneed.h" - -#include - -#include "common/clutil.h" -#include "common/timing.h" - -Thneed::Thneed(bool do_clinit, cl_context _context) { - context = _context; - if (do_clinit) clinit(); - char *thneed_debug_env = getenv("THNEED_DEBUG"); - debug = (thneed_debug_env != NULL) ? atoi(thneed_debug_env) : 0; -} - -void Thneed::execute(float **finputs, float *foutput, bool slow) { - uint64_t tb, te; - if (debug >= 1) tb = nanos_since_boot(); - - // ****** copy inputs - copy_inputs(finputs); - - // ****** run commands - clexec(); - - // ****** copy outputs - copy_output(foutput); - - if (debug >= 1) { - te = nanos_since_boot(); - printf("model exec in %lu us\n", (te-tb)/1000); - } -} diff --git a/sunnypilot/modeld/thneed/thneed_qcom2.cc b/sunnypilot/modeld/thneed/thneed_qcom2.cc deleted file mode 100644 index b940da1ce1..0000000000 --- a/sunnypilot/modeld/thneed/thneed_qcom2.cc +++ /dev/null @@ -1,258 +0,0 @@ -#include "sunnypilot/modeld/thneed/thneed.h" - -#include -#include - -#include -#include -#include -#include -#include - -#include "common/clutil.h" -#include "common/timing.h" - -Thneed *g_thneed = NULL; -int g_fd = -1; - -void hexdump(uint8_t *d, int len) { - assert((len%4) == 0); - printf(" dumping %p len 0x%x\n", d, len); - for (int i = 0; i < len/4; i++) { - if (i != 0 && (i%0x10) == 0) printf("\n"); - printf("%8x ", d[i]); - } - printf("\n"); -} - -// *********** ioctl interceptor *********** - -extern "C" { - -int (*my_ioctl)(int filedes, unsigned long request, void *argp) = NULL; -#undef ioctl -int ioctl(int filedes, unsigned long request, void *argp) { - request &= 0xFFFFFFFF; // needed on QCOM2 - if (my_ioctl == NULL) my_ioctl = reinterpret_cast(dlsym(RTLD_NEXT, "ioctl")); - Thneed *thneed = g_thneed; - - // save the fd - if (request == IOCTL_KGSL_GPUOBJ_ALLOC) g_fd = filedes; - - // note that this runs always, even without a thneed object - if (request == IOCTL_KGSL_DRAWCTXT_CREATE) { - struct kgsl_drawctxt_create *create = (struct kgsl_drawctxt_create *)argp; - create->flags &= ~KGSL_CONTEXT_PRIORITY_MASK; - create->flags |= 6 << KGSL_CONTEXT_PRIORITY_SHIFT; // priority from 1-15, 1 is max priority - printf("IOCTL_KGSL_DRAWCTXT_CREATE: creating context with flags 0x%x\n", create->flags); - } - - if (thneed != NULL) { - if (request == IOCTL_KGSL_GPU_COMMAND) { - struct kgsl_gpu_command *cmd = (struct kgsl_gpu_command *)argp; - if (thneed->record) { - thneed->timestamp = cmd->timestamp; - thneed->context_id = cmd->context_id; - thneed->cmds.push_back(unique_ptr(new CachedCommand(thneed, cmd))); - } - if (thneed->debug >= 1) { - printf("IOCTL_KGSL_GPU_COMMAND(%2zu): flags: 0x%lx context_id: %u timestamp: %u numcmds: %d numobjs: %d\n", - thneed->cmds.size(), - cmd->flags, - cmd->context_id, cmd->timestamp, cmd->numcmds, cmd->numobjs); - } - } else if (request == IOCTL_KGSL_GPUOBJ_SYNC) { - struct kgsl_gpuobj_sync *cmd = (struct kgsl_gpuobj_sync *)argp; - struct kgsl_gpuobj_sync_obj *objs = (struct kgsl_gpuobj_sync_obj *)(cmd->objs); - - if (thneed->debug >= 2) { - printf("IOCTL_KGSL_GPUOBJ_SYNC count:%d ", cmd->count); - for (int i = 0; i < cmd->count; i++) { - printf(" -- offset:0x%lx len:0x%lx id:%d op:%d ", objs[i].offset, objs[i].length, objs[i].id, objs[i].op); - } - printf("\n"); - } - - if (thneed->record) { - thneed->cmds.push_back(unique_ptr(new - CachedSync(thneed, string((char *)objs, sizeof(struct kgsl_gpuobj_sync_obj)*cmd->count)))); - } - } else if (request == IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID) { - struct kgsl_device_waittimestamp_ctxtid *cmd = (struct kgsl_device_waittimestamp_ctxtid *)argp; - if (thneed->debug >= 1) { - printf("IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID: context_id: %d timestamp: %d timeout: %d\n", - cmd->context_id, cmd->timestamp, cmd->timeout); - } - } else if (request == IOCTL_KGSL_SETPROPERTY) { - if (thneed->debug >= 1) { - struct kgsl_device_getproperty *prop = (struct kgsl_device_getproperty *)argp; - printf("IOCTL_KGSL_SETPROPERTY: 0x%x sizebytes:%zu\n", prop->type, prop->sizebytes); - if (thneed->debug >= 2) { - hexdump((uint8_t *)prop->value, prop->sizebytes); - if (prop->type == KGSL_PROP_PWR_CONSTRAINT) { - struct kgsl_device_constraint *constraint = (struct kgsl_device_constraint *)prop->value; - hexdump((uint8_t *)constraint->data, constraint->size); - } - } - } - } else if (request == IOCTL_KGSL_DRAWCTXT_CREATE || request == IOCTL_KGSL_DRAWCTXT_DESTROY) { - // this happens - } else if (request == IOCTL_KGSL_GPUOBJ_ALLOC || request == IOCTL_KGSL_GPUOBJ_FREE) { - // this happens - } else { - if (thneed->debug >= 1) { - printf("other ioctl %lx\n", request); - } - } - } - - int ret = my_ioctl(filedes, request, argp); - // NOTE: This error message goes into stdout and messes up pyenv - // if (ret != 0) printf("ioctl returned %d with errno %d\n", ret, errno); - return ret; -} - -} - -// *********** GPUMalloc *********** - -GPUMalloc::GPUMalloc(int size, int fd) { - struct kgsl_gpuobj_alloc alloc; - memset(&alloc, 0, sizeof(alloc)); - alloc.size = size; - alloc.flags = 0x10000a00; - ioctl(fd, IOCTL_KGSL_GPUOBJ_ALLOC, &alloc); - void *addr = mmap64(NULL, alloc.mmapsize, 0x3, 0x1, fd, alloc.id*0x1000); - assert(addr != MAP_FAILED); - - base = (uint64_t)addr; - remaining = size; -} - -GPUMalloc::~GPUMalloc() { - // TODO: free the GPU malloced area -} - -void *GPUMalloc::alloc(int size) { - void *ret = (void*)base; - size = (size+0xff) & (~0xFF); - assert(size <= remaining); - remaining -= size; - base += size; - return ret; -} - -// *********** CachedSync, at the ioctl layer *********** - -void CachedSync::exec() { - struct kgsl_gpuobj_sync cmd; - - cmd.objs = (uint64_t)data.data(); - cmd.obj_len = data.length(); - cmd.count = data.length() / sizeof(struct kgsl_gpuobj_sync_obj); - - int ret = ioctl(thneed->fd, IOCTL_KGSL_GPUOBJ_SYNC, &cmd); - assert(ret == 0); -} - -// *********** CachedCommand, at the ioctl layer *********** - -CachedCommand::CachedCommand(Thneed *lthneed, struct kgsl_gpu_command *cmd) { - thneed = lthneed; - assert(cmd->numsyncs == 0); - - memcpy(&cache, cmd, sizeof(cache)); - - if (cmd->numcmds > 0) { - cmds = make_unique(cmd->numcmds); - memcpy(cmds.get(), (void *)cmd->cmdlist, sizeof(struct kgsl_command_object)*cmd->numcmds); - cache.cmdlist = (uint64_t)cmds.get(); - for (int i = 0; i < cmd->numcmds; i++) { - void *nn = thneed->ram->alloc(cmds[i].size); - memcpy(nn, (void*)cmds[i].gpuaddr, cmds[i].size); - cmds[i].gpuaddr = (uint64_t)nn; - } - } - - if (cmd->numobjs > 0) { - objs = make_unique(cmd->numobjs); - memcpy(objs.get(), (void *)cmd->objlist, sizeof(struct kgsl_command_object)*cmd->numobjs); - cache.objlist = (uint64_t)objs.get(); - for (int i = 0; i < cmd->numobjs; i++) { - void *nn = thneed->ram->alloc(objs[i].size); - memset(nn, 0, objs[i].size); - objs[i].gpuaddr = (uint64_t)nn; - } - } - - kq = thneed->ckq; - thneed->ckq.clear(); -} - -void CachedCommand::exec() { - cache.timestamp = ++thneed->timestamp; - int ret = ioctl(thneed->fd, IOCTL_KGSL_GPU_COMMAND, &cache); - - if (thneed->debug >= 1) printf("CachedCommand::exec got %d\n", ret); - - if (thneed->debug >= 2) { - for (auto &it : kq) { - it->debug_print(false); - } - } - - assert(ret == 0); -} - -// *********** Thneed *********** - -Thneed::Thneed(bool do_clinit, cl_context _context) { - // TODO: QCOM2 actually requires a different context - //context = _context; - if (do_clinit) clinit(); - assert(g_fd != -1); - fd = g_fd; - ram = make_unique(0x80000, fd); - timestamp = -1; - g_thneed = this; - char *thneed_debug_env = getenv("THNEED_DEBUG"); - debug = (thneed_debug_env != NULL) ? atoi(thneed_debug_env) : 0; -} - -void Thneed::wait() { - struct kgsl_device_waittimestamp_ctxtid wait; - wait.context_id = context_id; - wait.timestamp = timestamp; - wait.timeout = -1; - - uint64_t tb = nanos_since_boot(); - int wret = ioctl(fd, IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID, &wait); - uint64_t te = nanos_since_boot(); - - if (debug >= 1) printf("wait %d after %lu us\n", wret, (te-tb)/1000); -} - -void Thneed::execute(float **finputs, float *foutput, bool slow) { - uint64_t tb, te; - if (debug >= 1) tb = nanos_since_boot(); - - // ****** copy inputs - copy_inputs(finputs, true); - - // ****** run commands - int i = 0; - for (auto &it : cmds) { - ++i; - if (debug >= 1) printf("run %2d @ %7lu us: ", i, (nanos_since_boot()-tb)/1000); - it->exec(); - if ((i == cmds.size()) || slow) wait(); - } - - // ****** copy outputs - copy_output(foutput); - - if (debug >= 1) { - te = nanos_since_boot(); - printf("model exec in %lu us\n", (te-tb)/1000); - } -} diff --git a/sunnypilot/modeld/transforms/loadyuv.cc b/sunnypilot/modeld/transforms/loadyuv.cc deleted file mode 100644 index f7d571416c..0000000000 --- a/sunnypilot/modeld/transforms/loadyuv.cc +++ /dev/null @@ -1,74 +0,0 @@ -#include "sunnypilot/modeld/transforms/loadyuv.h" - -#include -#include -#include - -void loadyuv_init(LoadYUVState* s, cl_context ctx, cl_device_id device_id, int width, int height) { - memset(s, 0, sizeof(*s)); - - s->width = width; - s->height = height; - - char args[1024]; - snprintf(args, sizeof(args), - "-cl-fast-relaxed-math -cl-denorms-are-zero " - "-DTRANSFORMED_WIDTH=%d -DTRANSFORMED_HEIGHT=%d", - width, height); - cl_program prg = cl_program_from_file(ctx, device_id, LOADYUV_PATH, args); - - s->loadys_krnl = CL_CHECK_ERR(clCreateKernel(prg, "loadys", &err)); - s->loaduv_krnl = CL_CHECK_ERR(clCreateKernel(prg, "loaduv", &err)); - s->copy_krnl = CL_CHECK_ERR(clCreateKernel(prg, "copy", &err)); - - // done with this - CL_CHECK(clReleaseProgram(prg)); -} - -void loadyuv_destroy(LoadYUVState* s) { - CL_CHECK(clReleaseKernel(s->loadys_krnl)); - CL_CHECK(clReleaseKernel(s->loaduv_krnl)); - CL_CHECK(clReleaseKernel(s->copy_krnl)); -} - -void loadyuv_queue(LoadYUVState* s, cl_command_queue q, - cl_mem y_cl, cl_mem u_cl, cl_mem v_cl, - cl_mem out_cl, bool do_shift) { - cl_int global_out_off = 0; - if (do_shift) { - // shift the image in slot 1 to slot 0, then place the new image in slot 1 - global_out_off += (s->width*s->height) + (s->width/2)*(s->height/2)*2; - CL_CHECK(clSetKernelArg(s->copy_krnl, 0, sizeof(cl_mem), &out_cl)); - CL_CHECK(clSetKernelArg(s->copy_krnl, 1, sizeof(cl_int), &global_out_off)); - const size_t copy_work_size = global_out_off/8; - CL_CHECK(clEnqueueNDRangeKernel(q, s->copy_krnl, 1, NULL, - ©_work_size, NULL, 0, 0, NULL)); - } - - CL_CHECK(clSetKernelArg(s->loadys_krnl, 0, sizeof(cl_mem), &y_cl)); - CL_CHECK(clSetKernelArg(s->loadys_krnl, 1, sizeof(cl_mem), &out_cl)); - CL_CHECK(clSetKernelArg(s->loadys_krnl, 2, sizeof(cl_int), &global_out_off)); - - const size_t loadys_work_size = (s->width*s->height)/8; - CL_CHECK(clEnqueueNDRangeKernel(q, s->loadys_krnl, 1, NULL, - &loadys_work_size, NULL, 0, 0, NULL)); - - const size_t loaduv_work_size = ((s->width/2)*(s->height/2))/8; - global_out_off += (s->width*s->height); - - CL_CHECK(clSetKernelArg(s->loaduv_krnl, 0, sizeof(cl_mem), &u_cl)); - CL_CHECK(clSetKernelArg(s->loaduv_krnl, 1, sizeof(cl_mem), &out_cl)); - CL_CHECK(clSetKernelArg(s->loaduv_krnl, 2, sizeof(cl_int), &global_out_off)); - - CL_CHECK(clEnqueueNDRangeKernel(q, s->loaduv_krnl, 1, NULL, - &loaduv_work_size, NULL, 0, 0, NULL)); - - global_out_off += (s->width/2)*(s->height/2); - - CL_CHECK(clSetKernelArg(s->loaduv_krnl, 0, sizeof(cl_mem), &v_cl)); - CL_CHECK(clSetKernelArg(s->loaduv_krnl, 1, sizeof(cl_mem), &out_cl)); - CL_CHECK(clSetKernelArg(s->loaduv_krnl, 2, sizeof(cl_int), &global_out_off)); - - CL_CHECK(clEnqueueNDRangeKernel(q, s->loaduv_krnl, 1, NULL, - &loaduv_work_size, NULL, 0, 0, NULL)); -} diff --git a/sunnypilot/modeld/transforms/loadyuv.cl b/sunnypilot/modeld/transforms/loadyuv.cl deleted file mode 100644 index 7dd3d973a3..0000000000 --- a/sunnypilot/modeld/transforms/loadyuv.cl +++ /dev/null @@ -1,47 +0,0 @@ -#define UV_SIZE ((TRANSFORMED_WIDTH/2)*(TRANSFORMED_HEIGHT/2)) - -__kernel void loadys(__global uchar8 const * const Y, - __global float * out, - int out_offset) -{ - const int gid = get_global_id(0); - const int ois = gid * 8; - const int oy = ois / TRANSFORMED_WIDTH; - const int ox = ois % TRANSFORMED_WIDTH; - - const uchar8 ys = Y[gid]; - const float8 ysf = convert_float8(ys); - - // 02 - // 13 - - __global float* outy0; - __global float* outy1; - if ((oy & 1) == 0) { - outy0 = out + out_offset; //y0 - outy1 = out + out_offset + UV_SIZE*2; //y2 - } else { - outy0 = out + out_offset + UV_SIZE; //y1 - outy1 = out + out_offset + UV_SIZE*3; //y3 - } - - vstore4(ysf.s0246, 0, outy0 + (oy/2) * (TRANSFORMED_WIDTH/2) + ox/2); - vstore4(ysf.s1357, 0, outy1 + (oy/2) * (TRANSFORMED_WIDTH/2) + ox/2); -} - -__kernel void loaduv(__global uchar8 const * const in, - __global float8 * out, - int out_offset) -{ - const int gid = get_global_id(0); - const uchar8 inv = in[gid]; - const float8 outv = convert_float8(inv); - out[gid + out_offset / 8] = outv; -} - -__kernel void copy(__global float8 * inout, - int in_offset) -{ - const int gid = get_global_id(0); - inout[gid] = inout[gid + in_offset / 8]; -} diff --git a/sunnypilot/modeld/transforms/loadyuv.h b/sunnypilot/modeld/transforms/loadyuv.h deleted file mode 100644 index 7d27ef5d46..0000000000 --- a/sunnypilot/modeld/transforms/loadyuv.h +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once - -#include "common/clutil.h" - -typedef struct { - int width, height; - cl_kernel loadys_krnl, loaduv_krnl, copy_krnl; -} LoadYUVState; - -void loadyuv_init(LoadYUVState* s, cl_context ctx, cl_device_id device_id, int width, int height); - -void loadyuv_destroy(LoadYUVState* s); - -void loadyuv_queue(LoadYUVState* s, cl_command_queue q, - cl_mem y_cl, cl_mem u_cl, cl_mem v_cl, - cl_mem out_cl, bool do_shift = false); diff --git a/sunnypilot/modeld/transforms/transform.cc b/sunnypilot/modeld/transforms/transform.cc deleted file mode 100644 index ebab670b53..0000000000 --- a/sunnypilot/modeld/transforms/transform.cc +++ /dev/null @@ -1,97 +0,0 @@ -#include "sunnypilot/modeld/transforms/transform.h" - -#include -#include - -#include "common/clutil.h" - -void transform_init(Transform* s, cl_context ctx, cl_device_id device_id) { - memset(s, 0, sizeof(*s)); - - cl_program prg = cl_program_from_file(ctx, device_id, TRANSFORM_PATH, ""); - s->krnl = CL_CHECK_ERR(clCreateKernel(prg, "warpPerspective", &err)); - // done with this - CL_CHECK(clReleaseProgram(prg)); - - s->m_y_cl = CL_CHECK_ERR(clCreateBuffer(ctx, CL_MEM_READ_WRITE, 3*3*sizeof(float), NULL, &err)); - s->m_uv_cl = CL_CHECK_ERR(clCreateBuffer(ctx, CL_MEM_READ_WRITE, 3*3*sizeof(float), NULL, &err)); -} - -void transform_destroy(Transform* s) { - CL_CHECK(clReleaseMemObject(s->m_y_cl)); - CL_CHECK(clReleaseMemObject(s->m_uv_cl)); - CL_CHECK(clReleaseKernel(s->krnl)); -} - -void transform_queue(Transform* s, - cl_command_queue q, - cl_mem in_yuv, int in_width, int in_height, int in_stride, int in_uv_offset, - cl_mem out_y, cl_mem out_u, cl_mem out_v, - int out_width, int out_height, - const mat3& projection) { - const int zero = 0; - - // sampled using pixel center origin - // (because that's how fastcv and opencv does it) - - mat3 projection_y = projection; - - // in and out uv is half the size of y. - mat3 projection_uv = transform_scale_buffer(projection, 0.5); - - CL_CHECK(clEnqueueWriteBuffer(q, s->m_y_cl, CL_TRUE, 0, 3*3*sizeof(float), (void*)projection_y.v, 0, NULL, NULL)); - CL_CHECK(clEnqueueWriteBuffer(q, s->m_uv_cl, CL_TRUE, 0, 3*3*sizeof(float), (void*)projection_uv.v, 0, NULL, NULL)); - - const int in_y_width = in_width; - const int in_y_height = in_height; - const int in_y_px_stride = 1; - const int in_uv_width = in_width/2; - const int in_uv_height = in_height/2; - const int in_uv_px_stride = 2; - const int in_u_offset = in_uv_offset; - const int in_v_offset = in_uv_offset + 1; - - const int out_y_width = out_width; - const int out_y_height = out_height; - const int out_uv_width = out_width/2; - const int out_uv_height = out_height/2; - - CL_CHECK(clSetKernelArg(s->krnl, 0, sizeof(cl_mem), &in_yuv)); // src - CL_CHECK(clSetKernelArg(s->krnl, 1, sizeof(cl_int), &in_stride)); // src_row_stride - CL_CHECK(clSetKernelArg(s->krnl, 2, sizeof(cl_int), &in_y_px_stride)); // src_px_stride - CL_CHECK(clSetKernelArg(s->krnl, 3, sizeof(cl_int), &zero)); // src_offset - CL_CHECK(clSetKernelArg(s->krnl, 4, sizeof(cl_int), &in_y_height)); // src_rows - CL_CHECK(clSetKernelArg(s->krnl, 5, sizeof(cl_int), &in_y_width)); // src_cols - CL_CHECK(clSetKernelArg(s->krnl, 6, sizeof(cl_mem), &out_y)); // dst - CL_CHECK(clSetKernelArg(s->krnl, 7, sizeof(cl_int), &out_y_width)); // dst_row_stride - CL_CHECK(clSetKernelArg(s->krnl, 8, sizeof(cl_int), &zero)); // dst_offset - CL_CHECK(clSetKernelArg(s->krnl, 9, sizeof(cl_int), &out_y_height)); // dst_rows - CL_CHECK(clSetKernelArg(s->krnl, 10, sizeof(cl_int), &out_y_width)); // dst_cols - CL_CHECK(clSetKernelArg(s->krnl, 11, sizeof(cl_mem), &s->m_y_cl)); // M - - const size_t work_size_y[2] = {(size_t)out_y_width, (size_t)out_y_height}; - - CL_CHECK(clEnqueueNDRangeKernel(q, s->krnl, 2, NULL, - (const size_t*)&work_size_y, NULL, 0, 0, NULL)); - - const size_t work_size_uv[2] = {(size_t)out_uv_width, (size_t)out_uv_height}; - - CL_CHECK(clSetKernelArg(s->krnl, 2, sizeof(cl_int), &in_uv_px_stride)); // src_px_stride - CL_CHECK(clSetKernelArg(s->krnl, 3, sizeof(cl_int), &in_u_offset)); // src_offset - CL_CHECK(clSetKernelArg(s->krnl, 4, sizeof(cl_int), &in_uv_height)); // src_rows - CL_CHECK(clSetKernelArg(s->krnl, 5, sizeof(cl_int), &in_uv_width)); // src_cols - CL_CHECK(clSetKernelArg(s->krnl, 6, sizeof(cl_mem), &out_u)); // dst - CL_CHECK(clSetKernelArg(s->krnl, 7, sizeof(cl_int), &out_uv_width)); // dst_row_stride - CL_CHECK(clSetKernelArg(s->krnl, 8, sizeof(cl_int), &zero)); // dst_offset - CL_CHECK(clSetKernelArg(s->krnl, 9, sizeof(cl_int), &out_uv_height)); // dst_rows - CL_CHECK(clSetKernelArg(s->krnl, 10, sizeof(cl_int), &out_uv_width)); // dst_cols - CL_CHECK(clSetKernelArg(s->krnl, 11, sizeof(cl_mem), &s->m_uv_cl)); // M - - CL_CHECK(clEnqueueNDRangeKernel(q, s->krnl, 2, NULL, - (const size_t*)&work_size_uv, NULL, 0, 0, NULL)); - CL_CHECK(clSetKernelArg(s->krnl, 3, sizeof(cl_int), &in_v_offset)); // src_ofset - CL_CHECK(clSetKernelArg(s->krnl, 6, sizeof(cl_mem), &out_v)); // dst - - CL_CHECK(clEnqueueNDRangeKernel(q, s->krnl, 2, NULL, - (const size_t*)&work_size_uv, NULL, 0, 0, NULL)); -} diff --git a/sunnypilot/modeld/transforms/transform.cl b/sunnypilot/modeld/transforms/transform.cl deleted file mode 100644 index 2ca25920cd..0000000000 --- a/sunnypilot/modeld/transforms/transform.cl +++ /dev/null @@ -1,54 +0,0 @@ -#define INTER_BITS 5 -#define INTER_TAB_SIZE (1 << INTER_BITS) -#define INTER_SCALE 1.f / INTER_TAB_SIZE - -#define INTER_REMAP_COEF_BITS 15 -#define INTER_REMAP_COEF_SCALE (1 << INTER_REMAP_COEF_BITS) - -__kernel void warpPerspective(__global const uchar * src, - int src_row_stride, int src_px_stride, int src_offset, int src_rows, int src_cols, - __global uchar * dst, - int dst_row_stride, int dst_offset, int dst_rows, int dst_cols, - __constant float * M) -{ - int dx = get_global_id(0); - int dy = get_global_id(1); - - if (dx < dst_cols && dy < dst_rows) - { - float X0 = M[0] * dx + M[1] * dy + M[2]; - float Y0 = M[3] * dx + M[4] * dy + M[5]; - float W = M[6] * dx + M[7] * dy + M[8]; - W = W != 0.0f ? INTER_TAB_SIZE / W : 0.0f; - int X = rint(X0 * W), Y = rint(Y0 * W); - - int sx = convert_short_sat(X >> INTER_BITS); - int sy = convert_short_sat(Y >> INTER_BITS); - - short sx_clamp = clamp(sx, 0, src_cols - 1); - short sx_p1_clamp = clamp(sx + 1, 0, src_cols - 1); - short sy_clamp = clamp(sy, 0, src_rows - 1); - short sy_p1_clamp = clamp(sy + 1, 0, src_rows - 1); - int v0 = convert_int(src[mad24(sy_clamp, src_row_stride, src_offset + sx_clamp*src_px_stride)]); - int v1 = convert_int(src[mad24(sy_clamp, src_row_stride, src_offset + sx_p1_clamp*src_px_stride)]); - int v2 = convert_int(src[mad24(sy_p1_clamp, src_row_stride, src_offset + sx_clamp*src_px_stride)]); - int v3 = convert_int(src[mad24(sy_p1_clamp, src_row_stride, src_offset + sx_p1_clamp*src_px_stride)]); - - short ay = (short)(Y & (INTER_TAB_SIZE - 1)); - short ax = (short)(X & (INTER_TAB_SIZE - 1)); - float taby = 1.f/INTER_TAB_SIZE*ay; - float tabx = 1.f/INTER_TAB_SIZE*ax; - - int dst_index = mad24(dy, dst_row_stride, dst_offset + dx); - - int itab0 = convert_short_sat_rte( (1.0f-taby)*(1.0f-tabx) * INTER_REMAP_COEF_SCALE ); - int itab1 = convert_short_sat_rte( (1.0f-taby)*tabx * INTER_REMAP_COEF_SCALE ); - int itab2 = convert_short_sat_rte( taby*(1.0f-tabx) * INTER_REMAP_COEF_SCALE ); - int itab3 = convert_short_sat_rte( taby*tabx * INTER_REMAP_COEF_SCALE ); - - int val = v0 * itab0 + v1 * itab1 + v2 * itab2 + v3 * itab3; - - uchar pix = convert_uchar_sat((val + (1 << (INTER_REMAP_COEF_BITS-1))) >> INTER_REMAP_COEF_BITS); - dst[dst_index] = pix; - } -} diff --git a/sunnypilot/modeld/transforms/transform.h b/sunnypilot/modeld/transforms/transform.h deleted file mode 100644 index 771a7054b3..0000000000 --- a/sunnypilot/modeld/transforms/transform.h +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once - -#define CL_USE_DEPRECATED_OPENCL_1_2_APIS -#ifdef __APPLE__ -#include -#else -#include -#endif - -#include "common/mat.h" - -typedef struct { - cl_kernel krnl; - cl_mem m_y_cl, m_uv_cl; -} Transform; - -void transform_init(Transform* s, cl_context ctx, cl_device_id device_id); - -void transform_destroy(Transform* transform); - -void transform_queue(Transform* s, cl_command_queue q, - cl_mem yuv, int in_width, int in_height, int in_stride, int in_uv_offset, - cl_mem out_y, cl_mem out_u, cl_mem out_v, - int out_width, int out_height, - const mat3& projection); diff --git a/sunnypilot/modeld_v2/.gitignore b/sunnypilot/modeld_v2/.gitignore deleted file mode 100644 index 742d3d1205..0000000000 --- a/sunnypilot/modeld_v2/.gitignore +++ /dev/null @@ -1 +0,0 @@ -*_pyx.cpp diff --git a/sunnypilot/modeld_v2/SConscript b/sunnypilot/modeld_v2/SConscript deleted file mode 100644 index bb4c8d4a50..0000000000 --- a/sunnypilot/modeld_v2/SConscript +++ /dev/null @@ -1,30 +0,0 @@ -import glob - -Import('env', 'envCython', 'arch', 'cereal', 'messaging', 'common', 'gpucommon', 'visionipc', 'transformations') -lenv = env.Clone() -lenvCython = envCython.Clone() - -libs = [cereal, messaging, visionipc, gpucommon, common, 'capnp', 'kj', 'pthread'] -frameworks = [] - -common_src = [ - "models/commonmodel.cc", - "transforms/loadyuv.cc", - "transforms/transform.cc", -] - -# OpenCL is a framework on Mac -if arch == "Darwin": - frameworks += ['OpenCL'] -else: - libs += ['OpenCL'] - -# Set path definitions -for pathdef, fn in {'TRANSFORM': 'transforms/transform.cl', 'LOADYUV': 'transforms/loadyuv.cl'}.items(): - for xenv in (lenv, lenvCython): - xenv['CXXFLAGS'].append(f'-D{pathdef}_PATH=\\"{File(fn).abspath}\\"') - -# Compile cython -cython_libs = envCython["LIBS"] + libs -commonmodel_lib = lenv.Library('commonmodel', common_src) -lenvCython.Program('models/commonmodel_pyx.so', 'models/commonmodel_pyx.pyx', LIBS=[commonmodel_lib, *cython_libs], FRAMEWORKS=frameworks) diff --git a/sunnypilot/modeld_v2/fill_model_msg.py b/sunnypilot/modeld_v2/fill_model_msg.py deleted file mode 100644 index 4d04d6e5ec..0000000000 --- a/sunnypilot/modeld_v2/fill_model_msg.py +++ /dev/null @@ -1,218 +0,0 @@ -import os -import capnp -import numpy as np -from cereal import log -from openpilot.sunnypilot.modeld_v2.constants import ModelConstants, Plan -from openpilot.selfdrive.controls.lib.drive_helpers import get_curvature_from_plan - -SEND_RAW_PRED = os.getenv('SEND_RAW_PRED') - -ConfidenceClass = log.ModelDataV2.ConfidenceClass - - -def get_curvature_from_output(output, vego, lat_action_t, current_generation=None): - if current_generation != 11: - if desired_curv := output.get('desired_curvature'): # If the model outputs the desired curvature, use that directly - return float(desired_curv[0, 0]) - - plan_output = output['plan'][0] - return float(get_curvature_from_plan(plan_output[:, Plan.T_FROM_CURRENT_EULER][:, 2], plan_output[:, Plan.ORIENTATION_RATE][:, 2], - ModelConstants.T_IDXS, vego, lat_action_t)) - - -class PublishState: - def __init__(self): - self.disengage_buffer = np.zeros(ModelConstants.CONFIDENCE_BUFFER_LEN*ModelConstants.DISENGAGE_WIDTH, dtype=np.float32) - self.prev_brake_5ms2_probs = np.zeros(ModelConstants.FCW_5MS2_PROBS_WIDTH, dtype=np.float32) - self.prev_brake_3ms2_probs = np.zeros(ModelConstants.FCW_3MS2_PROBS_WIDTH, dtype=np.float32) - -def fill_xyzt(builder, t, x, y, z, x_std=None, y_std=None, z_std=None): - builder.t = t - builder.x = x.tolist() - builder.y = y.tolist() - builder.z = z.tolist() - if x_std is not None: - builder.xStd = x_std.tolist() - if y_std is not None: - builder.yStd = y_std.tolist() - if z_std is not None: - builder.zStd = z_std.tolist() - -def fill_xyvat(builder, t, x, y, v, a, x_std=None, y_std=None, v_std=None, a_std=None): - builder.t = t - builder.x = x.tolist() - builder.y = y.tolist() - builder.v = v.tolist() - builder.a = a.tolist() - if x_std is not None: - builder.xStd = x_std.tolist() - if y_std is not None: - builder.yStd = y_std.tolist() - if v_std is not None: - builder.vStd = v_std.tolist() - if a_std is not None: - builder.aStd = a_std.tolist() - -def fill_xyz_poly(builder, degree, x, y, z): - xyz = np.stack([x, y, z], axis=1) - coeffs = np.polynomial.polynomial.polyfit(ModelConstants.T_IDXS, xyz, deg=degree) - builder.xCoefficients = coeffs[:, 0].tolist() - builder.yCoefficients = coeffs[:, 1].tolist() - builder.zCoefficients = coeffs[:, 2].tolist() - -def fill_lane_line_meta(builder, lane_lines, lane_line_probs): - builder.leftY = lane_lines[1].y[0] - builder.leftProb = lane_line_probs[1] - builder.rightY = lane_lines[2].y[0] - builder.rightProb = lane_line_probs[2] - -def fill_model_msg(base_msg: capnp._DynamicStructBuilder, extended_msg: capnp._DynamicStructBuilder, - net_output_data: dict[str, np.ndarray], action: log.ModelDataV2.Action, - publish_state: PublishState, vipc_frame_id: int, vipc_frame_id_extra: int, - frame_id: int, frame_drop: float, timestamp_eof: int, model_execution_time: float, - valid: bool, model_meta) -> None: - frame_age = frame_id - vipc_frame_id if frame_id > vipc_frame_id else 0 - frame_drop_perc = frame_drop * 100 - extended_msg.valid = valid - base_msg.valid = valid - - driving_model_data = base_msg.drivingModelData - - driving_model_data.frameId = vipc_frame_id - driving_model_data.frameIdExtra = vipc_frame_id_extra - driving_model_data.frameDropPerc = frame_drop_perc - driving_model_data.modelExecutionTime = model_execution_time - driving_model_data.action = action - - modelV2 = extended_msg.modelV2 - modelV2.frameId = vipc_frame_id - modelV2.frameIdExtra = vipc_frame_id_extra - modelV2.frameAge = frame_age - modelV2.frameDropPerc = frame_drop_perc - modelV2.timestampEof = timestamp_eof - modelV2.modelExecutionTime = model_execution_time - - # plan - fill_xyzt(modelV2.position, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.POSITION].T, *net_output_data['plan_stds'][0,:,Plan.POSITION].T) - fill_xyzt(modelV2.velocity, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.VELOCITY].T) - fill_xyzt(modelV2.acceleration, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.ACCELERATION].T) - fill_xyzt(modelV2.orientation, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.T_FROM_CURRENT_EULER].T) - fill_xyzt(modelV2.orientationRate, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.ORIENTATION_RATE].T) - - # temporal pose - temporal_pose = modelV2.temporalPose - if 'sim_pose' in net_output_data: - temporal_pose.trans = net_output_data['sim_pose'][0,:ModelConstants.POSE_WIDTH//2].tolist() - temporal_pose.transStd = net_output_data['sim_pose_stds'][0,:ModelConstants.POSE_WIDTH//2].tolist() - temporal_pose.rot = net_output_data['sim_pose'][0,ModelConstants.POSE_WIDTH//2:].tolist() - temporal_pose.rotStd = net_output_data['sim_pose_stds'][0,ModelConstants.POSE_WIDTH//2:].tolist() - else: - temporal_pose.trans = net_output_data['plan'][0,0,Plan.VELOCITY].tolist() - temporal_pose.transStd = net_output_data['plan_stds'][0,0,Plan.VELOCITY].tolist() - temporal_pose.rot = net_output_data['plan'][0,0,Plan.ORIENTATION_RATE].tolist() - temporal_pose.rotStd = net_output_data['plan_stds'][0,0,Plan.ORIENTATION_RATE].tolist() - - # poly path - fill_xyz_poly(driving_model_data.path, ModelConstants.POLY_PATH_DEGREE, *net_output_data['plan'][0,:,Plan.POSITION].T) - - # action (includes lateral planning now) - modelV2.action = action - - # times at X_IDXS of edges and lines aren't used - LINE_T_IDXS: list[float] = [] - - # lane lines - modelV2.init('laneLines', 4) - for i in range(4): - lane_line = modelV2.laneLines[i] - fill_xyzt(lane_line, LINE_T_IDXS, np.array(ModelConstants.X_IDXS), net_output_data['lane_lines'][0,i,:,0], net_output_data['lane_lines'][0,i,:,1]) - modelV2.laneLineStds = net_output_data['lane_lines_stds'][0,:,0,0].tolist() - modelV2.laneLineProbs = net_output_data['lane_lines_prob'][0,1::2].tolist() - - fill_lane_line_meta(driving_model_data.laneLineMeta, modelV2.laneLines, modelV2.laneLineProbs) - - # road edges - modelV2.init('roadEdges', 2) - for i in range(2): - road_edge = modelV2.roadEdges[i] - fill_xyzt(road_edge, LINE_T_IDXS, np.array(ModelConstants.X_IDXS), net_output_data['road_edges'][0,i,:,0], net_output_data['road_edges'][0,i,:,1]) - modelV2.roadEdgeStds = net_output_data['road_edges_stds'][0,:,0,0].tolist() - - # leads - modelV2.init('leadsV3', 3) - for i in range(3): - lead = modelV2.leadsV3[i] - fill_xyvat(lead, ModelConstants.LEAD_T_IDXS, *net_output_data['lead'][0,i].T, *net_output_data['lead_stds'][0,i].T) - lead.prob = net_output_data['lead_prob'][0,i].tolist() - lead.probTime = ModelConstants.LEAD_T_OFFSETS[i] - - # meta - meta = modelV2.meta - meta.desireState = net_output_data['desire_state'][0].reshape(-1).tolist() - meta.desirePrediction = net_output_data['desire_pred'][0].reshape(-1).tolist() - meta.engagedProb = net_output_data['meta'][0,model_meta.ENGAGED].item() - meta.init('disengagePredictions') - disengage_predictions = meta.disengagePredictions - disengage_predictions.t = ModelConstants.META_T_IDXS - disengage_predictions.brakeDisengageProbs = net_output_data['meta'][0,model_meta.BRAKE_DISENGAGE].tolist() - disengage_predictions.gasDisengageProbs = net_output_data['meta'][0,model_meta.GAS_DISENGAGE].tolist() - disengage_predictions.steerOverrideProbs = net_output_data['meta'][0,model_meta.STEER_OVERRIDE].tolist() - disengage_predictions.brake3MetersPerSecondSquaredProbs = net_output_data['meta'][0,model_meta.HARD_BRAKE_3].tolist() - disengage_predictions.brake4MetersPerSecondSquaredProbs = net_output_data['meta'][0,model_meta.HARD_BRAKE_4].tolist() - disengage_predictions.brake5MetersPerSecondSquaredProbs = net_output_data['meta'][0,model_meta.HARD_BRAKE_5].tolist() - - if hasattr(model_meta, 'GAS_PRESS') and hasattr(model_meta, 'BRAKE_PRESS'): - disengage_predictions.gasPressProbs = net_output_data['meta'][0,model_meta.GAS_PRESS].tolist() - disengage_predictions.brakePressProbs = net_output_data['meta'][0,model_meta.BRAKE_PRESS].tolist() - - publish_state.prev_brake_5ms2_probs[:-1] = publish_state.prev_brake_5ms2_probs[1:] - publish_state.prev_brake_5ms2_probs[-1] = net_output_data['meta'][0,model_meta.HARD_BRAKE_5][0] - publish_state.prev_brake_3ms2_probs[:-1] = publish_state.prev_brake_3ms2_probs[1:] - publish_state.prev_brake_3ms2_probs[-1] = net_output_data['meta'][0,model_meta.HARD_BRAKE_3][0] - hard_brake_predicted = (publish_state.prev_brake_5ms2_probs > ModelConstants.FCW_THRESHOLDS_5MS2).all() and \ - (publish_state.prev_brake_3ms2_probs > ModelConstants.FCW_THRESHOLDS_3MS2).all() - meta.hardBrakePredicted = hard_brake_predicted.item() - - # confidence - if vipc_frame_id % (2*ModelConstants.MODEL_FREQ) == 0: - # any disengage prob - brake_disengage_probs = net_output_data['meta'][0,model_meta.BRAKE_DISENGAGE] - gas_disengage_probs = net_output_data['meta'][0,model_meta.GAS_DISENGAGE] - steer_override_probs = net_output_data['meta'][0,model_meta.STEER_OVERRIDE] - any_disengage_probs = 1-((1-brake_disengage_probs)*(1-gas_disengage_probs)*(1-steer_override_probs)) - # independent disengage prob for each 2s slice - ind_disengage_probs = np.r_[any_disengage_probs[0], np.diff(any_disengage_probs) / (1 - any_disengage_probs[:-1])] - # rolling buf for 2, 4, 6, 8, 10s - publish_state.disengage_buffer[:-ModelConstants.DISENGAGE_WIDTH] = publish_state.disengage_buffer[ModelConstants.DISENGAGE_WIDTH:] - publish_state.disengage_buffer[-ModelConstants.DISENGAGE_WIDTH:] = ind_disengage_probs - - score = 0. - for i in range(ModelConstants.DISENGAGE_WIDTH): - score += publish_state.disengage_buffer[i*ModelConstants.DISENGAGE_WIDTH+ModelConstants.DISENGAGE_WIDTH-1-i].item() / ModelConstants.DISENGAGE_WIDTH - if score < ModelConstants.RYG_GREEN: - modelV2.confidence = ConfidenceClass.green - elif score < ModelConstants.RYG_YELLOW: - modelV2.confidence = ConfidenceClass.yellow - else: - modelV2.confidence = ConfidenceClass.red - - # raw prediction if enabled - if SEND_RAW_PRED: - modelV2.rawPredictions = net_output_data['raw_pred'].tobytes() - -def fill_pose_msg(msg: capnp._DynamicStructBuilder, net_output_data: dict[str, np.ndarray], - vipc_frame_id: int, vipc_dropped_frames: int, timestamp_eof: int, live_calib_seen: bool) -> None: - msg.valid = live_calib_seen & (vipc_dropped_frames < 1) - cameraOdometry = msg.cameraOdometry - - cameraOdometry.frameId = vipc_frame_id - cameraOdometry.timestampEof = timestamp_eof - - cameraOdometry.trans = net_output_data['pose'][0,:3].tolist() - cameraOdometry.rot = net_output_data['pose'][0,3:].tolist() - cameraOdometry.wideFromDeviceEuler = net_output_data['wide_from_device_euler'][0,:].tolist() - cameraOdometry.roadTransformTrans = net_output_data['road_transform'][0,:3].tolist() - cameraOdometry.transStd = net_output_data['pose_stds'][0,:3].tolist() - cameraOdometry.rotStd = net_output_data['pose_stds'][0,3:].tolist() - cameraOdometry.wideFromDeviceEulerStd = net_output_data['wide_from_device_euler_stds'][0,:].tolist() - cameraOdometry.roadTransformTransStd = net_output_data['road_transform_stds'][0,:3].tolist() diff --git a/sunnypilot/modeld_v2/get_model_metadata.py b/sunnypilot/modeld_v2/get_model_metadata.py deleted file mode 100755 index e0b5adc51b..0000000000 --- a/sunnypilot/modeld_v2/get_model_metadata.py +++ /dev/null @@ -1,40 +0,0 @@ -#!/usr/bin/env python3 -import sys -import pathlib -import onnx -import codecs -import pickle -from typing import Any - - -def get_name_and_shape(value_info:onnx.ValueInfoProto) -> tuple[str, tuple[int,...]]: - shape = tuple([int(dim.dim_value) for dim in value_info.type.tensor_type.shape.dim]) - name = value_info.name - return name, shape - - -def get_metadata_value_by_name(model:onnx.ModelProto, name:str) -> str | Any: - for prop in model.metadata_props: - if prop.key == name: - return prop.value - return None - - -if __name__ == "__main__": - model_path = pathlib.Path(sys.argv[1]) - model = onnx.load(str(model_path)) - output_slices = get_metadata_value_by_name(model, 'output_slices') - assert output_slices is not None, 'output_slices not found in metadata' - - metadata = { - 'model_checkpoint': get_metadata_value_by_name(model, 'model_checkpoint'), - 'output_slices': pickle.loads(codecs.decode(output_slices.encode(), "base64")), - 'input_shapes': dict([get_name_and_shape(x) for x in model.graph.input]), - 'output_shapes': dict([get_name_and_shape(x) for x in model.graph.output]) - } - - metadata_path = model_path.parent / (model_path.stem + '_metadata.pkl') - with open(metadata_path, 'wb') as f: - pickle.dump(metadata, f) - - print(f'saved metadata to {metadata_path}') diff --git a/sunnypilot/modeld_v2/modeld.py b/sunnypilot/modeld_v2/modeld.py deleted file mode 100755 index 5b9c5ef9e5..0000000000 --- a/sunnypilot/modeld_v2/modeld.py +++ /dev/null @@ -1,371 +0,0 @@ -#!/usr/bin/env python3 -import time -import numpy as np -import cereal.messaging as messaging -from cereal import car, log -from setproctitle import setproctitle -from cereal.messaging import PubMaster, SubMaster -from msgq.visionipc import VisionIpcClient, VisionStreamType, VisionBuf -from opendbc.car.car_helpers import get_demo_car_params -from openpilot.common.swaglog import cloudlog -from openpilot.common.params import Params -from openpilot.common.filter_simple import FirstOrderFilter -from openpilot.common.realtime import config_realtime_process, DT_MDL -from openpilot.common.transformations.camera import DEVICE_CAMERAS -from openpilot.common.transformations.model import get_warp_matrix -from openpilot.system import sentry -from openpilot.selfdrive.controls.lib.desire_helper import DesireHelper -from openpilot.selfdrive.controls.lib.drive_helpers import get_accel_from_plan, smooth_value - -from openpilot.sunnypilot.modeld_v2.fill_model_msg import fill_model_msg, fill_pose_msg, PublishState, get_curvature_from_output -from openpilot.sunnypilot.modeld_v2.constants import Plan -from openpilot.sunnypilot.modeld_v2.models.commonmodel_pyx import DrivingModelFrame, CLContext -from openpilot.sunnypilot.modeld_v2.meta_helper import load_meta_constants - -from openpilot.sunnypilot.models.helpers import get_active_bundle -from openpilot.sunnypilot.models.modeld_lagd import ModeldLagd -from openpilot.sunnypilot.models.runners.helpers import get_model_runner - -PROCESS_NAME = "selfdrive.modeld.modeld" - - -class FrameMeta: - frame_id: int = 0 - timestamp_sof: int = 0 - timestamp_eof: int = 0 - - def __init__(self, vipc=None): - if vipc is not None: - self.frame_id, self.timestamp_sof, self.timestamp_eof = vipc.frame_id, vipc.timestamp_sof, vipc.timestamp_eof - - -class ModelState: - frames: dict[str, DrivingModelFrame] - inputs: dict[str, np.ndarray] - prev_desire: np.ndarray # for tracking the rising edge of the pulse - temporal_idxs: slice | np.ndarray - - def __init__(self, context: CLContext): - try: - self.model_runner = get_model_runner() - self.constants = self.model_runner.constants - except Exception as e: - cloudlog.exception(f"Failed to initialize model runner: {str(e)}") - raise - - model_bundle = get_active_bundle() - self.generation = model_bundle.generation - overrides = {override.key: override.value for override in model_bundle.overrides} - - self.LAT_SMOOTH_SECONDS = float(overrides.get('lat', ".2")) - self.LONG_SMOOTH_SECONDS = float(overrides.get('long', ".0")) - self.MIN_LAT_CONTROL_SPEED = 0.3 - - buffer_length = 5 if self.model_runner.is_20hz else 2 - self.frames = {name: DrivingModelFrame(context, buffer_length) for name in self.model_runner.vision_input_names} - self.prev_desire = np.zeros(self.constants.DESIRE_LEN, dtype=np.float32) - - # img buffers are managed in openCL transform code - self.numpy_inputs = {} - - for key, shape in self.model_runner.input_shapes.items(): - if key not in self.frames: # Managed by opencl - self.numpy_inputs[key] = np.zeros(shape, dtype=np.float32) - - if self.model_runner.is_20hz_3d: # split models - self.full_features_buffer = np.zeros((1, self.constants.FULL_HISTORY_BUFFER_LEN, self.constants.FEATURE_LEN), dtype=np.float32) - self.full_desire = np.zeros((1, self.constants.FULL_HISTORY_BUFFER_LEN, self.constants.DESIRE_LEN), dtype=np.float32) - self.full_prev_desired_curv = np.zeros((1, self.constants.FULL_HISTORY_BUFFER_LEN, self.constants.PREV_DESIRED_CURV_LEN), dtype=np.float32) - self.temporal_idxs = slice(-1-(self.constants.TEMPORAL_SKIP*(self.constants.INPUT_HISTORY_BUFFER_LEN-1)), None, self.constants.TEMPORAL_SKIP) - elif self.model_runner.is_20hz and not self.model_runner.is_20hz_3d: - self.full_features_buffer = np.zeros((self.constants.FULL_HISTORY_BUFFER_LEN + 1, self.constants.FEATURE_LEN), dtype=np.float32) - self.full_desire = np.zeros((self.constants.FULL_HISTORY_BUFFER_LEN + 1, self.constants.DESIRE_LEN), dtype=np.float32) - num_elements = self.numpy_inputs['features_buffer'].shape[1] - step_size = int(-100 / num_elements) - self.temporal_idxs = np.arange(step_size, step_size * (num_elements + 1), step_size)[::-1] - self.desire_reshape_dims = (self.numpy_inputs['desire'].shape[0], self.numpy_inputs['desire'].shape[1], -1, - self.numpy_inputs['desire'].shape[2]) - - def run(self, bufs: dict[str, VisionBuf], transforms: dict[str, np.ndarray], - inputs: dict[str, np.ndarray], prepare_only: bool) -> dict[str, np.ndarray] | None: - # Model decides when action is completed, so desire input is just a pulse triggered on rising edge - inputs['desire'][0] = 0 - new_desire = np.where(inputs['desire'] - self.prev_desire > .99, inputs['desire'], 0) - self.prev_desire[:] = inputs['desire'] - - if self.model_runner.is_20hz_3d: # split models - self.full_desire[0,:-1] = self.full_desire[0,1:] - self.full_desire[0,-1] = new_desire - self.numpy_inputs['desire'][:] = self.full_desire.reshape((1, self.constants.INPUT_HISTORY_BUFFER_LEN, self.constants.TEMPORAL_SKIP, -1)).max(axis=2) - elif self.model_runner.is_20hz and not self.model_runner.is_20hz_3d: # 20hz supercombo - self.full_desire[:-1] = self.full_desire[1:] - self.full_desire[-1] = new_desire - self.numpy_inputs['desire'][:] = self.full_desire.reshape(self.desire_reshape_dims).max(axis=2) - else: # not 20hz - length = inputs['desire'].shape[0] - self.numpy_inputs['desire'][0, :-1] = self.numpy_inputs['desire'][0, 1:] - self.numpy_inputs['desire'][0, -1, :length] = new_desire[:length] - - for key in self.numpy_inputs: - if key in inputs and key not in ['desire']: - self.numpy_inputs[key][:] = inputs[key] - - imgs_cl = {name: self.frames[name].prepare(bufs[name], transforms[name].flatten()) for name in self.model_runner.vision_input_names} - - # Prepare inputs using the model runner - self.model_runner.prepare_inputs(imgs_cl, self.numpy_inputs, self.frames) - - if prepare_only: - return None - - # Run model inference - outputs = self.model_runner.run_model() - - if self.model_runner.is_20hz_3d: # split models - self.full_features_buffer[0, :-1] = self.full_features_buffer[0, 1:] - self.full_features_buffer[0, -1] = outputs['hidden_state'][0, :] - self.numpy_inputs['features_buffer'][:] = self.full_features_buffer[0, self.temporal_idxs] - elif self.model_runner.is_20hz and not self.model_runner.is_20hz_3d: # 20hz supercombo - self.full_features_buffer[:-1] = self.full_features_buffer[1:] - self.full_features_buffer[-1] = outputs['hidden_state'][0, :] - self.numpy_inputs['features_buffer'][:] = self.full_features_buffer[self.temporal_idxs] - else: # not 20hz - feature_len = outputs['hidden_state'].shape[1] - self.numpy_inputs['features_buffer'][0, :-1] = self.numpy_inputs['features_buffer'][0, 1:] - self.numpy_inputs['features_buffer'][0, -1, :feature_len] = outputs['hidden_state'][0, :feature_len] - - if "desired_curvature" in outputs: - input_name_prev = None - - if "prev_desired_curvs" in self.numpy_inputs.keys(): - input_name_prev = 'prev_desired_curvs' - elif "prev_desired_curv" in self.numpy_inputs.keys(): - input_name_prev = 'prev_desired_curv' - - if input_name_prev is not None: - self.process_desired_curvature(outputs, input_name_prev) - return outputs - - def process_desired_curvature(self, outputs, input_name_prev): - if self.model_runner.is_20hz_3d: # split models - self.full_prev_desired_curv[0,:-1] = self.full_prev_desired_curv[0,1:] - self.full_prev_desired_curv[0,-1,:] = outputs['desired_curvature'][0, :] - self.numpy_inputs[input_name_prev][:] = self.full_prev_desired_curv[0, self.temporal_idxs] - if self.generation == 11: - self.numpy_inputs[input_name_prev][:] = 0*self.full_prev_desired_curv[0, self.temporal_idxs] - else: - length = outputs['desired_curvature'][0].size - self.numpy_inputs[input_name_prev][0, :-length, 0] = self.numpy_inputs[input_name_prev][0, length:, 0] - self.numpy_inputs[input_name_prev][0, -length:, 0] = outputs['desired_curvature'][0] - - def get_action_from_model(self, model_output: dict[str, np.ndarray], prev_action: log.ModelDataV2.Action, - lat_action_t: float, long_action_t: float, v_ego: float) -> log.ModelDataV2.Action: - plan = model_output['plan'][0] - desired_accel, should_stop = get_accel_from_plan(plan[:, Plan.VELOCITY][:, 0], plan[:, Plan.ACCELERATION][:, 0], self.constants.T_IDXS, - action_t=long_action_t) - desired_accel = smooth_value(desired_accel, prev_action.desiredAcceleration, self.LONG_SMOOTH_SECONDS) - - desired_curvature = get_curvature_from_output(model_output, v_ego, lat_action_t, self.generation) - if v_ego > self.MIN_LAT_CONTROL_SPEED: - desired_curvature = smooth_value(desired_curvature, prev_action.desiredCurvature, self.LAT_SMOOTH_SECONDS) - else: - desired_curvature = prev_action.desiredCurvature - - return log.ModelDataV2.Action(desiredCurvature=float(desired_curvature),desiredAcceleration=float(desired_accel), shouldStop=bool(should_stop)) - - -def main(demo=False): - cloudlog.warning("modeld init") - - sentry.set_tag("daemon", PROCESS_NAME) - cloudlog.bind(daemon=PROCESS_NAME) - setproctitle(PROCESS_NAME) - config_realtime_process(7, 54) - - cloudlog.warning("setting up CL context") - cl_context = CLContext() - cloudlog.warning("CL context ready; loading model") - model = ModelState(cl_context) - cloudlog.warning("models loaded, modeld starting") - - # visionipc clients - while True: - available_streams = VisionIpcClient.available_streams("camerad", block=False) - if available_streams: - use_extra_client = VisionStreamType.VISION_STREAM_WIDE_ROAD in available_streams and VisionStreamType.VISION_STREAM_ROAD in available_streams - main_wide_camera = VisionStreamType.VISION_STREAM_ROAD not in available_streams - break - time.sleep(.1) - - vipc_client_main_stream = VisionStreamType.VISION_STREAM_WIDE_ROAD if main_wide_camera else VisionStreamType.VISION_STREAM_ROAD - vipc_client_main = VisionIpcClient("camerad", vipc_client_main_stream, True, cl_context) - vipc_client_extra = VisionIpcClient("camerad", VisionStreamType.VISION_STREAM_WIDE_ROAD, False, cl_context) - cloudlog.warning(f"vision stream set up, main_wide_camera: {main_wide_camera}, use_extra_client: {use_extra_client}") - - while not vipc_client_main.connect(False): - time.sleep(0.1) - while use_extra_client and not vipc_client_extra.connect(False): - time.sleep(0.1) - - cloudlog.warning(f"connected main cam with buffer size: {vipc_client_main.buffer_len} ({vipc_client_main.width} x {vipc_client_main.height})") - if use_extra_client: - cloudlog.warning(f"connected extra cam with buffer size: {vipc_client_extra.buffer_len} ({vipc_client_extra.width} x {vipc_client_extra.height})") - - # messaging - pm = PubMaster(["modelV2", "drivingModelData", "cameraOdometry"]) - sm = SubMaster(["deviceState", "carState", "roadCameraState", "liveCalibration", "driverMonitoringState", "carControl", "liveDelay"]) - - publish_state = PublishState() - params = Params() - - # setup filter to track dropped frames - frame_dropped_filter = FirstOrderFilter(0., 10., 1. / model.constants.MODEL_FREQ) - frame_id = 0 - last_vipc_frame_id = 0 - run_count = 0 - - model_transform_main = np.zeros((3, 3), dtype=np.float32) - model_transform_extra = np.zeros((3, 3), dtype=np.float32) - live_calib_seen = False - buf_main, buf_extra = None, None - meta_main = FrameMeta() - meta_extra = FrameMeta() - - - if demo: - CP = get_demo_car_params() - else: - CP = messaging.log_from_bytes(params.get("CarParams", block=True), car.CarParams) - cloudlog.info("modeld got CarParams: %s", CP.brand) - - - modeld_lagd = ModeldLagd() - - # TODO Move smooth seconds to action function - long_delay = CP.longitudinalActuatorDelay + model.LONG_SMOOTH_SECONDS - prev_action = log.ModelDataV2.Action() - - DH = DesireHelper() - - while True: - # Keep receiving frames until we are at least 1 frame ahead of previous extra frame - while meta_main.timestamp_sof < meta_extra.timestamp_sof + 25000000: - buf_main = vipc_client_main.recv() - meta_main = FrameMeta(vipc_client_main) - if buf_main is None: - break - - if buf_main is None: - cloudlog.debug("vipc_client_main no frame") - continue - - if use_extra_client: - # Keep receiving extra frames until frame id matches main camera - while True: - buf_extra = vipc_client_extra.recv() - meta_extra = FrameMeta(vipc_client_extra) - if buf_extra is None or meta_main.timestamp_sof < meta_extra.timestamp_sof + 25000000: - break - - if buf_extra is None: - cloudlog.debug("vipc_client_extra no frame") - continue - - if abs(meta_main.timestamp_sof - meta_extra.timestamp_sof) > 10000000: - cloudlog.error(f"frames out of sync! main: {meta_main.frame_id} ({meta_main.timestamp_sof / 1e9:.5f}),\ - extra: {meta_extra.frame_id} ({meta_extra.timestamp_sof / 1e9:.5f})") - - else: - # Use single camera - buf_extra = buf_main - meta_extra = meta_main - - sm.update(0) - desire = DH.desire - is_rhd = sm["driverMonitoringState"].isRHD - frame_id = sm["roadCameraState"].frameId - v_ego = max(sm["carState"].vEgo, 0.) - steer_delay = modeld_lagd.lagd_main(CP, sm, model) - if sm.updated["liveCalibration"] and sm.seen['roadCameraState'] and sm.seen['deviceState']: - device_from_calib_euler = np.array(sm["liveCalibration"].rpyCalib, dtype=np.float32) - dc = DEVICE_CAMERAS[(str(sm['deviceState'].deviceType), str(sm['roadCameraState'].sensor))] - model_transform_main = get_warp_matrix(device_from_calib_euler, dc.ecam.intrinsics if main_wide_camera else dc.fcam.intrinsics, - False).astype(np.float32) - model_transform_extra = get_warp_matrix(device_from_calib_euler, dc.ecam.intrinsics, True).astype(np.float32) - live_calib_seen = True - - traffic_convention = np.zeros(2) - traffic_convention[int(is_rhd)] = 1 - - vec_desire = np.zeros(model.constants.DESIRE_LEN, dtype=np.float32) - if desire >= 0 and desire < model.constants.DESIRE_LEN: - vec_desire[desire] = 1 - - # tracked dropped frames - vipc_dropped_frames = max(0, meta_main.frame_id - last_vipc_frame_id - 1) - frames_dropped = frame_dropped_filter.update(min(vipc_dropped_frames, 10)) - if run_count < 10: # let frame drops warm up - frame_dropped_filter.x = 0. - frames_dropped = 0. - run_count = run_count + 1 - - frame_drop_ratio = frames_dropped / (1 + frames_dropped) - prepare_only = vipc_dropped_frames > 0 - if prepare_only: - cloudlog.error(f"skipping model eval. Dropped {vipc_dropped_frames} frames") - - bufs = {name: buf_extra if 'big' in name else buf_main for name in model.model_runner.vision_input_names} - transforms = {name: model_transform_extra if 'big' in name else model_transform_main for name in model.model_runner.vision_input_names} - inputs:dict[str, np.ndarray] = { - 'desire': vec_desire, - 'traffic_convention': traffic_convention, - } - - if "lateral_control_params" in model.numpy_inputs.keys(): - inputs['lateral_control_params'] = np.array([v_ego, steer_delay], dtype=np.float32) - - mt1 = time.perf_counter() - model_output = model.run(bufs, transforms, inputs, prepare_only) - mt2 = time.perf_counter() - model_execution_time = mt2 - mt1 - - if model_output is not None: - modelv2_send = messaging.new_message('modelV2') - drivingdata_send = messaging.new_message('drivingModelData') - posenet_send = messaging.new_message('cameraOdometry') - - action = model.get_action_from_model(model_output, prev_action, steer_delay + DT_MDL, long_delay + DT_MDL, v_ego) - prev_action = action - fill_model_msg(drivingdata_send, modelv2_send, model_output, action, - publish_state, meta_main.frame_id, meta_extra.frame_id, frame_id, - frame_drop_ratio, meta_main.timestamp_eof, model_execution_time, live_calib_seen, load_meta_constants()) - - desire_state = modelv2_send.modelV2.meta.desireState - l_lane_change_prob = desire_state[log.Desire.laneChangeLeft] - r_lane_change_prob = desire_state[log.Desire.laneChangeRight] - lane_change_prob = l_lane_change_prob + r_lane_change_prob - DH.update(sm['carState'], sm['carControl'].latActive, lane_change_prob) - modelv2_send.modelV2.meta.laneChangeState = DH.lane_change_state - modelv2_send.modelV2.meta.laneChangeDirection = DH.lane_change_direction - drivingdata_send.drivingModelData.meta.laneChangeState = DH.lane_change_state - drivingdata_send.drivingModelData.meta.laneChangeDirection = DH.lane_change_direction - - fill_pose_msg(posenet_send, model_output, meta_main.frame_id, vipc_dropped_frames, meta_main.timestamp_eof, live_calib_seen) - pm.send('modelV2', modelv2_send) - pm.send('drivingModelData', drivingdata_send) - pm.send('cameraOdometry', posenet_send) - last_vipc_frame_id = meta_main.frame_id - - -if __name__ == "__main__": - try: - import argparse - parser = argparse.ArgumentParser() - parser.add_argument('--demo', action='store_true', help='A boolean for demo mode.') - args = parser.parse_args() - main(demo=args.demo) - except KeyboardInterrupt: - cloudlog.warning(f"child {PROCESS_NAME} got SIGINT") - except Exception: - sentry.capture_exception() - raise diff --git a/sunnypilot/modeld_v2/models/README.md b/sunnypilot/modeld_v2/models/README.md deleted file mode 100644 index 9e11ca8255..0000000000 --- a/sunnypilot/modeld_v2/models/README.md +++ /dev/null @@ -1,62 +0,0 @@ -## Neural networks in openpilot -To view the architecture of the ONNX networks, you can use [netron](https://netron.app/) - -## Supercombo -### Supercombo input format (Full size: 799906 x float32) -* **image stream** - * Two consecutive images (256 * 512 * 3 in RGB) recorded at 20 Hz : 393216 = 2 * 6 * 128 * 256 - * Each 256 * 512 image is represented in YUV420 with 6 channels : 6 * 128 * 256 - * Channels 0,1,2,3 represent the full-res Y channel and are represented in numpy as Y[::2, ::2], Y[::2, 1::2], Y[1::2, ::2], and Y[1::2, 1::2] - * Channel 4 represents the half-res U channel - * Channel 5 represents the half-res V channel -* **wide image stream** - * Two consecutive images (256 * 512 * 3 in RGB) recorded at 20 Hz : 393216 = 2 * 6 * 128 * 256 - * Each 256 * 512 image is represented in YUV420 with 6 channels : 6 * 128 * 256 - * Channels 0,1,2,3 represent the full-res Y channel and are represented in numpy as Y[::2, ::2], Y[::2, 1::2], Y[1::2, ::2], and Y[1::2, 1::2] - * Channel 4 represents the half-res U channel - * Channel 5 represents the half-res V channel -* **desire** - * one-hot encoded buffer to command model to execute certain actions, bit needs to be sent for the past 5 seconds (at 20FPS) : 100 * 8 -* **traffic convention** - * one-hot encoded vector to tell model whether traffic is right-hand or left-hand traffic : 2 -* **feature buffer** - * A buffer of intermediate features that gets appended to the current feature to form a 5 seconds temporal context (at 20FPS) : 99 * 512 - - -### Supercombo output format (Full size: XXX x float32) -Read [here](https://github.com/commaai/openpilot/blob/90af436a121164a51da9fa48d093c29f738adf6a/selfdrive/modeld/models/driving.h#L236) for more. - - -## Driver Monitoring Model -* .onnx model can be run with onnx runtimes -* .dlc file is a pre-quantized model and only runs on qualcomm DSPs - -### input format -* single image W = 1440 H = 960 luminance channel (Y) from the planar YUV420 format: - * full input size is 1440 * 960 = 1382400 - * normalized ranging from 0.0 to 1.0 in float32 (onnx runner) or ranging from 0 to 255 in uint8 (snpe runner) -* camera calibration angles (roll, pitch, yaw) from liveCalibration: 3 x float32 inputs - -### output format -* 84 x float32 outputs = 2 + 41 * 2 ([parsing example](https://github.com/commaai/openpilot/blob/22ce4e17ba0d3bfcf37f8255a4dd1dc683fe0c38/selfdrive/modeld/models/dmonitoring.cc#L33)) - * for each person in the front seats (2 * 41) - * face pose: 12 = 6 + 6 - * face orientation [pitch, yaw, roll] in camera frame: 3 - * face position [dx, dy] relative to image center: 2 - * normalized face size: 1 - * standard deviations for above outputs: 6 - * face visible probability: 1 - * eyes: 20 = (8 + 1) + (8 + 1) + 1 + 1 - * eye position and size, and their standard deviations: 8 - * eye visible probability: 1 - * eye closed probability: 1 - * wearing sunglasses probability: 1 - * face occluded probability: 1 - * touching wheel probability: 1 - * paying attention probability: 1 - * (deprecated) distracted probabilities: 2 - * using phone probability: 1 - * distracted probability: 1 - * common outputs 2 - * poor camera vision probability: 1 - * left hand drive probability: 1 diff --git a/sunnypilot/modeld_v2/models/commonmodel.cc b/sunnypilot/modeld_v2/models/commonmodel.cc deleted file mode 100644 index 5cd3a84fcc..0000000000 --- a/sunnypilot/modeld_v2/models/commonmodel.cc +++ /dev/null @@ -1,62 +0,0 @@ -#include "sunnypilot/modeld_v2/models/commonmodel.h" - -#include -#include - -#include "common/clutil.h" - -DrivingModelFrame::DrivingModelFrame(cl_device_id device_id, cl_context context, uint8_t buffer_length) : ModelFrame(device_id, context), buffer_length(buffer_length) { - input_frames = std::make_unique(buf_size); - input_frames_cl = CL_CHECK_ERR(clCreateBuffer(context, CL_MEM_READ_WRITE, buf_size, NULL, &err)); - img_buffer_20hz_cl = CL_CHECK_ERR(clCreateBuffer(context, CL_MEM_READ_WRITE, buffer_length*frame_size_bytes, NULL, &err)); - region.origin = (buffer_length - 1) * frame_size_bytes; - region.size = frame_size_bytes; - last_img_cl = CL_CHECK_ERR(clCreateSubBuffer(img_buffer_20hz_cl, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err)); - // printf("Buffer length: %d, region origin: %lu, region size: %lu\n", buffer_length, region.origin, region.size); - - loadyuv_init(&loadyuv, context, device_id, MODEL_WIDTH, MODEL_HEIGHT); - init_transform(device_id, context, MODEL_WIDTH, MODEL_HEIGHT); -} - -cl_mem* DrivingModelFrame::prepare(cl_mem yuv_cl, int frame_width, int frame_height, int frame_stride, int frame_uv_offset, const mat3& projection) { - run_transform(yuv_cl, MODEL_WIDTH, MODEL_HEIGHT, frame_width, frame_height, frame_stride, frame_uv_offset, projection); - - for (int i = 0; i < (buffer_length - 1); i++) { - CL_CHECK(clEnqueueCopyBuffer(q, img_buffer_20hz_cl, img_buffer_20hz_cl, (i+1)*frame_size_bytes, i*frame_size_bytes, frame_size_bytes, 0, nullptr, nullptr)); - } - loadyuv_queue(&loadyuv, q, y_cl, u_cl, v_cl, last_img_cl); - - copy_queue(&loadyuv, q, img_buffer_20hz_cl, input_frames_cl, 0, 0, frame_size_bytes); - copy_queue(&loadyuv, q, last_img_cl, input_frames_cl, 0, frame_size_bytes, frame_size_bytes); - - // NOTE: Since thneed is using a different command queue, this clFinish is needed to ensure the image is ready. - clFinish(q); - return &input_frames_cl; -} - -DrivingModelFrame::~DrivingModelFrame() { - deinit_transform(); - loadyuv_destroy(&loadyuv); - CL_CHECK(clReleaseMemObject(img_buffer_20hz_cl)); - CL_CHECK(clReleaseMemObject(last_img_cl)); - CL_CHECK(clReleaseCommandQueue(q)); -} - - -MonitoringModelFrame::MonitoringModelFrame(cl_device_id device_id, cl_context context) : ModelFrame(device_id, context) { - input_frames = std::make_unique(buf_size); - input_frame_cl = CL_CHECK_ERR(clCreateBuffer(context, CL_MEM_READ_WRITE, buf_size, NULL, &err)); - - init_transform(device_id, context, MODEL_WIDTH, MODEL_HEIGHT); -} - -cl_mem* MonitoringModelFrame::prepare(cl_mem yuv_cl, int frame_width, int frame_height, int frame_stride, int frame_uv_offset, const mat3& projection) { - run_transform(yuv_cl, MODEL_WIDTH, MODEL_HEIGHT, frame_width, frame_height, frame_stride, frame_uv_offset, projection); - clFinish(q); - return &y_cl; -} - -MonitoringModelFrame::~MonitoringModelFrame() { - deinit_transform(); - CL_CHECK(clReleaseCommandQueue(q)); -} diff --git a/sunnypilot/modeld_v2/models/commonmodel.h b/sunnypilot/modeld_v2/models/commonmodel.h deleted file mode 100644 index 8203e064e0..0000000000 --- a/sunnypilot/modeld_v2/models/commonmodel.h +++ /dev/null @@ -1,97 +0,0 @@ -#pragma once - -#include -#include -#include - -#include - -#define CL_USE_DEPRECATED_OPENCL_1_2_APIS -#ifdef __APPLE__ -#include -#else -#include -#endif - -#include "common/mat.h" -#include "sunnypilot/modeld_v2/transforms/loadyuv.h" -#include "sunnypilot/modeld_v2/transforms/transform.h" - -class ModelFrame { -public: - ModelFrame(cl_device_id device_id, cl_context context) { - q = CL_CHECK_ERR(clCreateCommandQueue(context, device_id, 0, &err)); - } - virtual ~ModelFrame() {} - virtual cl_mem* prepare(cl_mem yuv_cl, int frame_width, int frame_height, int frame_stride, int frame_uv_offset, const mat3& projection) { return NULL; } - uint8_t* buffer_from_cl(cl_mem *in_frames, int buffer_size) { - CL_CHECK(clEnqueueReadBuffer(q, *in_frames, CL_TRUE, 0, buffer_size, input_frames.get(), 0, nullptr, nullptr)); - clFinish(q); - return &input_frames[0]; - } - - int MODEL_WIDTH; - int MODEL_HEIGHT; - int MODEL_FRAME_SIZE; - int buf_size; - -protected: - cl_mem y_cl, u_cl, v_cl; - Transform transform; - cl_command_queue q; - std::unique_ptr input_frames; - - void init_transform(cl_device_id device_id, cl_context context, int model_width, int model_height) { - y_cl = CL_CHECK_ERR(clCreateBuffer(context, CL_MEM_READ_WRITE, model_width * model_height, NULL, &err)); - u_cl = CL_CHECK_ERR(clCreateBuffer(context, CL_MEM_READ_WRITE, (model_width / 2) * (model_height / 2), NULL, &err)); - v_cl = CL_CHECK_ERR(clCreateBuffer(context, CL_MEM_READ_WRITE, (model_width / 2) * (model_height / 2), NULL, &err)); - transform_init(&transform, context, device_id); - } - - void deinit_transform() { - transform_destroy(&transform); - CL_CHECK(clReleaseMemObject(v_cl)); - CL_CHECK(clReleaseMemObject(u_cl)); - CL_CHECK(clReleaseMemObject(y_cl)); - } - - void run_transform(cl_mem yuv_cl, int model_width, int model_height, int frame_width, int frame_height, int frame_stride, int frame_uv_offset, const mat3& projection) { - transform_queue(&transform, q, - yuv_cl, frame_width, frame_height, frame_stride, frame_uv_offset, - y_cl, u_cl, v_cl, model_width, model_height, projection); - } -}; - -class DrivingModelFrame : public ModelFrame { -public: - DrivingModelFrame(cl_device_id device_id, cl_context context, uint8_t buffer_length); - ~DrivingModelFrame(); - cl_mem* prepare(cl_mem yuv_cl, int frame_width, int frame_height, int frame_stride, int frame_uv_offset, const mat3& projection); - - const int MODEL_WIDTH = 512; - const int MODEL_HEIGHT = 256; - const int MODEL_FRAME_SIZE = MODEL_WIDTH * MODEL_HEIGHT * 3 / 2; - const int buf_size = MODEL_FRAME_SIZE * 2; - const size_t frame_size_bytes = MODEL_FRAME_SIZE * sizeof(uint8_t); - const uint8_t buffer_length; - -private: - LoadYUVState loadyuv; - cl_mem img_buffer_20hz_cl, last_img_cl, input_frames_cl; - cl_buffer_region region; -}; - -class MonitoringModelFrame : public ModelFrame { -public: - MonitoringModelFrame(cl_device_id device_id, cl_context context); - ~MonitoringModelFrame(); - cl_mem* prepare(cl_mem yuv_cl, int frame_width, int frame_height, int frame_stride, int frame_uv_offset, const mat3& projection); - - const int MODEL_WIDTH = 1440; - const int MODEL_HEIGHT = 960; - const int MODEL_FRAME_SIZE = MODEL_WIDTH * MODEL_HEIGHT; - const int buf_size = MODEL_FRAME_SIZE; - -private: - cl_mem input_frame_cl; -}; diff --git a/sunnypilot/modeld_v2/models/commonmodel.pxd b/sunnypilot/modeld_v2/models/commonmodel.pxd deleted file mode 100644 index 55023ac4b9..0000000000 --- a/sunnypilot/modeld_v2/models/commonmodel.pxd +++ /dev/null @@ -1,27 +0,0 @@ -# distutils: language = c++ - -from msgq.visionipc.visionipc cimport cl_device_id, cl_context, cl_mem - -cdef extern from "common/mat.h": - cdef struct mat3: - float v[9] - -cdef extern from "common/clutil.h": - cdef unsigned long CL_DEVICE_TYPE_DEFAULT - cl_device_id cl_get_device_id(unsigned long) - cl_context cl_create_context(cl_device_id) - void cl_release_context(cl_context) - -cdef extern from "sunnypilot/modeld_v2/models/commonmodel.h": - cppclass ModelFrame: - int buf_size - unsigned char * buffer_from_cl(cl_mem*, int); - cl_mem * prepare(cl_mem, int, int, int, int, mat3) - - cppclass DrivingModelFrame: - int buf_size - DrivingModelFrame(cl_device_id, cl_context, unsigned char) - - cppclass MonitoringModelFrame: - int buf_size - MonitoringModelFrame(cl_device_id, cl_context) diff --git a/sunnypilot/modeld_v2/models/commonmodel_pyx.pxd b/sunnypilot/modeld_v2/models/commonmodel_pyx.pxd deleted file mode 100644 index 0bb798625b..0000000000 --- a/sunnypilot/modeld_v2/models/commonmodel_pyx.pxd +++ /dev/null @@ -1,13 +0,0 @@ -# distutils: language = c++ - -from msgq.visionipc.visionipc cimport cl_mem -from msgq.visionipc.visionipc_pyx cimport CLContext as BaseCLContext - -cdef class CLContext(BaseCLContext): - pass - -cdef class CLMem: - cdef cl_mem * mem - - @staticmethod - cdef create(void*) diff --git a/sunnypilot/modeld_v2/models/commonmodel_pyx.pyx b/sunnypilot/modeld_v2/models/commonmodel_pyx.pyx deleted file mode 100644 index 78a891f031..0000000000 --- a/sunnypilot/modeld_v2/models/commonmodel_pyx.pyx +++ /dev/null @@ -1,74 +0,0 @@ -# distutils: language = c++ -# cython: c_string_encoding=ascii, language_level=3 - -import numpy as np -cimport numpy as cnp -from libc.string cimport memcpy -from libc.stdint cimport uintptr_t, uint8_t - -from msgq.visionipc.visionipc cimport cl_mem -from msgq.visionipc.visionipc_pyx cimport VisionBuf, CLContext as BaseCLContext -from .commonmodel cimport CL_DEVICE_TYPE_DEFAULT, cl_get_device_id, cl_create_context, cl_release_context -from .commonmodel cimport mat3, ModelFrame as cppModelFrame, DrivingModelFrame as cppDrivingModelFrame, MonitoringModelFrame as cppMonitoringModelFrame - - -cdef class CLContext(BaseCLContext): - def __cinit__(self): - self.device_id = cl_get_device_id(CL_DEVICE_TYPE_DEFAULT) - self.context = cl_create_context(self.device_id) - - def __dealloc__(self): - if self.context: - cl_release_context(self.context) - -cdef class CLMem: - @staticmethod - cdef create(void * cmem): - mem = CLMem() - mem.mem = cmem - return mem - - @property - def mem_address(self): - return (self.mem) - -def cl_from_visionbuf(VisionBuf buf): - return CLMem.create(&buf.buf.buf_cl) - - -cdef class ModelFrame: - cdef cppModelFrame * frame - cdef int buf_size - - def __dealloc__(self): - del self.frame - - def prepare(self, VisionBuf buf, float[:] projection): - cdef mat3 cprojection - memcpy(cprojection.v, &projection[0], 9*sizeof(float)) - cdef cl_mem * data - data = self.frame.prepare(buf.buf.buf_cl, buf.width, buf.height, buf.stride, buf.uv_offset, cprojection) - return CLMem.create(data) - - def buffer_from_cl(self, CLMem in_frames): - cdef unsigned char * data2 - data2 = self.frame.buffer_from_cl(in_frames.mem, self.buf_size) - return np.asarray( data2) - - -cdef class DrivingModelFrame(ModelFrame): - cdef cppDrivingModelFrame * _frame - - def __cinit__(self, CLContext context, int buffer_length=2): - self._frame = new cppDrivingModelFrame(context.device_id, context.context, buffer_length) - self.frame = (self._frame) - self.buf_size = self._frame.buf_size - -cdef class MonitoringModelFrame(ModelFrame): - cdef cppMonitoringModelFrame * _frame - - def __cinit__(self, CLContext context): - self._frame = new cppMonitoringModelFrame(context.device_id, context.context) - self.frame = (self._frame) - self.buf_size = self._frame.buf_size - diff --git a/sunnypilot/modeld_v2/parse_model_outputs.py b/sunnypilot/modeld_v2/parse_model_outputs.py deleted file mode 100644 index c71a146454..0000000000 --- a/sunnypilot/modeld_v2/parse_model_outputs.py +++ /dev/null @@ -1,107 +0,0 @@ -import numpy as np -from openpilot.sunnypilot.modeld_v2.constants import ModelConstants - -def safe_exp(x, out=None): - # -11 is around 10**14, more causes float16 overflow - return np.exp(np.clip(x, -np.inf, 11), out=out) - -def sigmoid(x): - return 1. / (1. + safe_exp(-x)) - -def softmax(x, axis=-1): - x -= np.max(x, axis=axis, keepdims=True) - if x.dtype == np.float32 or x.dtype == np.float64: - safe_exp(x, out=x) - else: - x = safe_exp(x) - x /= np.sum(x, axis=axis, keepdims=True) - return x - -class Parser: - def __init__(self, ignore_missing=False): - self.ignore_missing = ignore_missing - - def check_missing(self, outs, name): - if name not in outs and not self.ignore_missing: - raise ValueError(f"Missing output {name}") - return name not in outs - - def parse_categorical_crossentropy(self, name, outs, out_shape=None): - if self.check_missing(outs, name): - return - raw = outs[name] - if out_shape is not None: - raw = raw.reshape((raw.shape[0],) + out_shape) - outs[name] = softmax(raw, axis=-1) - - def parse_binary_crossentropy(self, name, outs): - if self.check_missing(outs, name): - return - raw = outs[name] - outs[name] = sigmoid(raw) - - def parse_mdn(self, name, outs, in_N=0, out_N=1, out_shape=None): - if self.check_missing(outs, name): - return - raw = outs[name] - raw = raw.reshape((raw.shape[0], max(in_N, 1), -1)) - - n_values = (raw.shape[2] - out_N)//2 - pred_mu = raw[:,:,:n_values] - pred_std = safe_exp(raw[:,:,n_values: 2*n_values]) - - if in_N > 1: - weights = np.zeros((raw.shape[0], in_N, out_N), dtype=raw.dtype) - for i in range(out_N): - weights[:,:,i - out_N] = softmax(raw[:,:,i - out_N], axis=-1) - - if out_N == 1: - for fidx in range(weights.shape[0]): - idxs = np.argsort(weights[fidx][:,0])[::-1] - weights[fidx] = weights[fidx][idxs] - pred_mu[fidx] = pred_mu[fidx][idxs] - pred_std[fidx] = pred_std[fidx][idxs] - full_shape = tuple([raw.shape[0], in_N] + list(out_shape)) - outs[name + '_weights'] = weights - outs[name + '_hypotheses'] = pred_mu.reshape(full_shape) - outs[name + '_stds_hypotheses'] = pred_std.reshape(full_shape) - - pred_mu_final = np.zeros((raw.shape[0], out_N, n_values), dtype=raw.dtype) - pred_std_final = np.zeros((raw.shape[0], out_N, n_values), dtype=raw.dtype) - for fidx in range(weights.shape[0]): - for hidx in range(out_N): - idxs = np.argsort(weights[fidx,:,hidx])[::-1] - pred_mu_final[fidx, hidx] = pred_mu[fidx, idxs[0]] - pred_std_final[fidx, hidx] = pred_std[fidx, idxs[0]] - else: - pred_mu_final = pred_mu - pred_std_final = pred_std - - if out_N > 1: - final_shape = tuple([raw.shape[0], out_N] + list(out_shape)) - else: - final_shape = tuple([raw.shape[0],] + list(out_shape)) - outs[name] = pred_mu_final.reshape(final_shape) - outs[name + '_stds'] = pred_std_final.reshape(final_shape) - - def parse_outputs(self, outs: dict[str, np.ndarray]) -> dict[str, np.ndarray]: - self.parse_mdn('plan', outs, in_N=ModelConstants.PLAN_MHP_N, out_N=ModelConstants.PLAN_MHP_SELECTION, - out_shape=(ModelConstants.IDX_N,ModelConstants.PLAN_WIDTH)) - self.parse_mdn('lane_lines', outs, in_N=0, out_N=0, out_shape=(ModelConstants.NUM_LANE_LINES,ModelConstants.IDX_N,ModelConstants.LANE_LINES_WIDTH)) - self.parse_mdn('road_edges', outs, in_N=0, out_N=0, out_shape=(ModelConstants.NUM_ROAD_EDGES,ModelConstants.IDX_N,ModelConstants.LANE_LINES_WIDTH)) - self.parse_mdn('pose', outs, in_N=0, out_N=0, out_shape=(ModelConstants.POSE_WIDTH,)) - self.parse_mdn('road_transform', outs, in_N=0, out_N=0, out_shape=(ModelConstants.POSE_WIDTH,)) - if 'sim_pose' in outs: - self.parse_mdn('sim_pose', outs, in_N=0, out_N=0, out_shape=(ModelConstants.POSE_WIDTH,)) - self.parse_mdn('wide_from_device_euler', outs, in_N=0, out_N=0, out_shape=(ModelConstants.WIDE_FROM_DEVICE_WIDTH,)) - self.parse_mdn('lead', outs, in_N=ModelConstants.LEAD_MHP_N, out_N=ModelConstants.LEAD_MHP_SELECTION, - out_shape=(ModelConstants.LEAD_TRAJ_LEN,ModelConstants.LEAD_WIDTH)) - if 'lat_planner_solution' in outs: - self.parse_mdn('lat_planner_solution', outs, in_N=0, out_N=0, out_shape=(ModelConstants.IDX_N,ModelConstants.LAT_PLANNER_SOLUTION_WIDTH)) - if 'desired_curvature' in outs: - self.parse_mdn('desired_curvature', outs, in_N=0, out_N=0, out_shape=(ModelConstants.DESIRED_CURV_WIDTH,)) - for k in ['lead_prob', 'lane_lines_prob', 'meta']: - self.parse_binary_crossentropy(k, outs) - self.parse_categorical_crossentropy('desire_state', outs, out_shape=(ModelConstants.DESIRE_PRED_WIDTH,)) - self.parse_categorical_crossentropy('desire_pred', outs, out_shape=(ModelConstants.DESIRE_PRED_LEN,ModelConstants.DESIRE_PRED_WIDTH)) - return outs diff --git a/sunnypilot/modeld_v2/parse_model_outputs_split.py b/sunnypilot/modeld_v2/parse_model_outputs_split.py deleted file mode 100644 index 7fab66e038..0000000000 --- a/sunnypilot/modeld_v2/parse_model_outputs_split.py +++ /dev/null @@ -1,127 +0,0 @@ -import numpy as np -from openpilot.sunnypilot.models.split_model_constants import SplitModelConstants - - -def safe_exp(x, out=None): - # -11 is around 10**14, more causes float16 overflow - return np.exp(np.clip(x, -np.inf, 11), out=out) - - -def sigmoid(x): - return 1. / (1. + safe_exp(-x)) - - -def softmax(x, axis=-1): - x -= np.max(x, axis=axis, keepdims=True) - if x.dtype == np.float32 or x.dtype == np.float64: - safe_exp(x, out=x) - else: - x = safe_exp(x) - x /= np.sum(x, axis=axis, keepdims=True) - return x - - -class Parser: - def __init__(self, ignore_missing=False): - self.ignore_missing = ignore_missing - - def check_missing(self, outs, name): - if name not in outs and not self.ignore_missing: - raise ValueError(f"Missing output {name}") - return name not in outs - - def parse_categorical_crossentropy(self, name, outs, out_shape=None): - if self.check_missing(outs, name): - return - raw = outs[name] - if out_shape is not None: - raw = raw.reshape((raw.shape[0],) + out_shape) - outs[name] = softmax(raw, axis=-1) - - def parse_binary_crossentropy(self, name, outs): - if self.check_missing(outs, name): - return - raw = outs[name] - outs[name] = sigmoid(raw) - - def parse_mdn(self, name, outs, in_N=0, out_N=1, out_shape=None): - if self.check_missing(outs, name): - return - raw = outs[name] - raw = raw.reshape((raw.shape[0], max(in_N, 1), -1)) - - n_values = (raw.shape[2] - out_N)//2 - pred_mu = raw[:,:,:n_values] - pred_std = safe_exp(raw[:,:,n_values: 2*n_values]) - - if in_N > 1: - weights = np.zeros((raw.shape[0], in_N, out_N), dtype=raw.dtype) - for i in range(out_N): - weights[:,:,i - out_N] = softmax(raw[:,:,i - out_N], axis=-1) - - if out_N == 1: - for fidx in range(weights.shape[0]): - idxs = np.argsort(weights[fidx][:,0])[::-1] - weights[fidx] = weights[fidx][idxs] - pred_mu[fidx] = pred_mu[fidx][idxs] - pred_std[fidx] = pred_std[fidx][idxs] - full_shape = tuple([raw.shape[0], in_N] + list(out_shape)) - outs[name + '_weights'] = weights - outs[name + '_hypotheses'] = pred_mu.reshape(full_shape) - outs[name + '_stds_hypotheses'] = pred_std.reshape(full_shape) - - pred_mu_final = np.zeros((raw.shape[0], out_N, n_values), dtype=raw.dtype) - pred_std_final = np.zeros((raw.shape[0], out_N, n_values), dtype=raw.dtype) - for fidx in range(weights.shape[0]): - for hidx in range(out_N): - idxs = np.argsort(weights[fidx,:,hidx])[::-1] - pred_mu_final[fidx, hidx] = pred_mu[fidx, idxs[0]] - pred_std_final[fidx, hidx] = pred_std[fidx, idxs[0]] - else: - pred_mu_final = pred_mu - pred_std_final = pred_std - - if out_N > 1: - final_shape = tuple([raw.shape[0], out_N] + list(out_shape)) - else: - final_shape = tuple([raw.shape[0],] + list(out_shape)) - outs[name] = pred_mu_final.reshape(final_shape) - outs[name + '_stds'] = pred_std_final.reshape(final_shape) - - def split_outputs(self, outs: dict[str, np.ndarray]) -> None: - if 'lane_lines' in outs: - self.parse_mdn('lane_lines', outs, in_N=0, out_N=0, - out_shape=(SplitModelConstants.NUM_LANE_LINES,SplitModelConstants.IDX_N,SplitModelConstants.LANE_LINES_WIDTH)) - self.parse_mdn('road_edges', outs, in_N=0, out_N=0, - out_shape=(SplitModelConstants.NUM_ROAD_EDGES,SplitModelConstants.IDX_N,SplitModelConstants.LANE_LINES_WIDTH)) - self.parse_mdn('lead', outs, in_N=SplitModelConstants.LEAD_MHP_N, out_N=SplitModelConstants.LEAD_MHP_SELECTION, - out_shape=(SplitModelConstants.LEAD_TRAJ_LEN,SplitModelConstants.LEAD_WIDTH)) - if 'sim_pose' in outs: - self.parse_mdn('sim_pose', outs, in_N=0, out_N=0, out_shape=(SplitModelConstants.POSE_WIDTH,)) - for k in ['lead_prob', 'lane_lines_prob']: - self.parse_binary_crossentropy(k, outs) - - def parse_vision_outputs(self, outs: dict[str, np.ndarray]) -> dict[str, np.ndarray]: - self.parse_mdn('pose', outs, in_N=0, out_N=0, out_shape=(SplitModelConstants.POSE_WIDTH,)) - self.parse_mdn('wide_from_device_euler', outs, in_N=0, out_N=0, out_shape=(SplitModelConstants.WIDE_FROM_DEVICE_WIDTH,)) - self.parse_mdn('road_transform', outs, in_N=0, out_N=0, out_shape=(SplitModelConstants.POSE_WIDTH,)) - self.split_outputs(outs) - self.parse_categorical_crossentropy('desire_pred', outs, out_shape=(SplitModelConstants.DESIRE_PRED_LEN,SplitModelConstants.DESIRE_PRED_WIDTH)) - self.parse_binary_crossentropy('meta', outs) - return outs - - def parse_policy_outputs(self, outs: dict[str, np.ndarray]) -> dict[str, np.ndarray]: - self.parse_mdn('plan', outs, in_N=SplitModelConstants.PLAN_MHP_N, out_N=SplitModelConstants.PLAN_MHP_SELECTION, - out_shape=(SplitModelConstants.IDX_N,SplitModelConstants.PLAN_WIDTH)) - self.split_outputs(outs) - if 'lat_planner_solution' in outs: - self.parse_mdn('lat_planner_solution', outs, in_N=0, out_N=0, out_shape=(SplitModelConstants.IDX_N,SplitModelConstants.LAT_PLANNER_SOLUTION_WIDTH)) - if 'desired_curvature' in outs: - self.parse_mdn('desired_curvature', outs, in_N=0, out_N=0, out_shape=(SplitModelConstants.DESIRED_CURV_WIDTH,)) - self.parse_categorical_crossentropy('desire_state', outs, out_shape=(SplitModelConstants.DESIRE_PRED_WIDTH,)) - return outs - - def parse_outputs(self, outs: dict[str, np.ndarray]) -> dict[str, np.ndarray]: - outs = self.parse_vision_outputs(outs) - outs = self.parse_policy_outputs(outs) - return outs diff --git a/sunnypilot/modeld_v2/runners/ort_helpers.py b/sunnypilot/modeld_v2/runners/ort_helpers.py deleted file mode 100644 index 26afb03562..0000000000 --- a/sunnypilot/modeld_v2/runners/ort_helpers.py +++ /dev/null @@ -1,36 +0,0 @@ -import onnx -import onnxruntime as ort -import numpy as np -import itertools - -ORT_TYPES_TO_NP_TYPES = {'tensor(float16)': np.float16, 'tensor(float)': np.float32, 'tensor(uint8)': np.uint8} - -def attributeproto_fp16_to_fp32(attr): - float32_list = np.frombuffer(attr.raw_data, dtype=np.float16) - attr.data_type = 1 - attr.raw_data = float32_list.astype(np.float32).tobytes() - -def convert_fp16_to_fp32(model): - for i in model.graph.initializer: - if i.data_type == 10: - attributeproto_fp16_to_fp32(i) - for i in itertools.chain(model.graph.input, model.graph.output): - if i.type.tensor_type.elem_type == 10: - i.type.tensor_type.elem_type = 1 - for i in model.graph.node: - if i.op_type == 'Cast' and i.attribute[0].i == 10: - i.attribute[0].i = 1 - for a in i.attribute: - if hasattr(a, 't'): - if a.t.data_type == 10: - attributeproto_fp16_to_fp32(a.t) - return model.SerializeToString() - - -def make_onnx_cpu_runner(model_path): - options = ort.SessionOptions() - options.intra_op_num_threads = 4 - options.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL - options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL - model_data = convert_fp16_to_fp32(onnx.load(model_path)) - return ort.InferenceSession(model_data, options, providers=['CPUExecutionProvider']) diff --git a/sunnypilot/modeld_v2/runners/tinygrad_helpers.py b/sunnypilot/modeld_v2/runners/tinygrad_helpers.py deleted file mode 100644 index 776381341c..0000000000 --- a/sunnypilot/modeld_v2/runners/tinygrad_helpers.py +++ /dev/null @@ -1,8 +0,0 @@ - -from tinygrad.tensor import Tensor -from tinygrad.helpers import to_mv - -def qcom_tensor_from_opencl_address(opencl_address, shape, dtype): - cl_buf_desc_ptr = to_mv(opencl_address, 8).cast('Q')[0] - rawbuf_ptr = to_mv(cl_buf_desc_ptr, 0x100).cast('Q')[20] # offset 0xA0 is a raw gpu pointer. - return Tensor.from_blob(rawbuf_ptr, shape, dtype=dtype, device='QCOM') diff --git a/sunnypilot/modeld_v2/tests/dmon_lag/repro.cc b/sunnypilot/modeld_v2/tests/dmon_lag/repro.cc deleted file mode 100644 index c4c1c65cbe..0000000000 --- a/sunnypilot/modeld_v2/tests/dmon_lag/repro.cc +++ /dev/null @@ -1,101 +0,0 @@ -// clang++ -O2 repro.cc && ./a.out - -#include -#include -#include - -#include -#include -#include -#include -#include - -static inline double millis_since_boot() { - struct timespec t; - clock_gettime(CLOCK_BOOTTIME, &t); - return t.tv_sec * 1000.0 + t.tv_nsec * 1e-6; -} - -#define MODEL_WIDTH 320 -#define MODEL_HEIGHT 640 - -// null function still breaks it -#define input_lambda(x) x - -// this is copied from models/dmonitoring.cc, and is the code that triggers the issue -void inner(uint8_t *resized_buf, float *net_input_buf) { - int resized_width = MODEL_WIDTH; - int resized_height = MODEL_HEIGHT; - - // one shot conversion, O(n) anyway - // yuvframe2tensor, normalize - for (int r = 0; r < MODEL_HEIGHT/2; r++) { - for (int c = 0; c < MODEL_WIDTH/2; c++) { - // Y_ul - net_input_buf[(c*MODEL_HEIGHT/2) + r] = input_lambda(resized_buf[(2*r*resized_width) + (2*c)]); - // Y_ur - net_input_buf[(c*MODEL_HEIGHT/2) + r + (2*(MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = input_lambda(resized_buf[(2*r*resized_width) + (2*c+1)]); - // Y_dl - net_input_buf[(c*MODEL_HEIGHT/2) + r + ((MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = input_lambda(resized_buf[(2*r*resized_width+1) + (2*c)]); - // Y_dr - net_input_buf[(c*MODEL_HEIGHT/2) + r + (3*(MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = input_lambda(resized_buf[(2*r*resized_width+1) + (2*c+1)]); - // U - net_input_buf[(c*MODEL_HEIGHT/2) + r + (4*(MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = input_lambda(resized_buf[(resized_width*resized_height) + (r*resized_width/2) + c]); - // V - net_input_buf[(c*MODEL_HEIGHT/2) + r + (5*(MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = input_lambda(resized_buf[(resized_width*resized_height) + ((resized_width/2)*(resized_height/2)) + (r*resized_width/2) + c]); - } - } -} - -float trial() { - int resized_width = MODEL_WIDTH; - int resized_height = MODEL_HEIGHT; - - int yuv_buf_len = (MODEL_WIDTH/2) * (MODEL_HEIGHT/2) * 6; // Y|u|v -> y|y|y|y|u|v - - // allocate the buffers - uint8_t *resized_buf = (uint8_t*)malloc(resized_width*resized_height*3/2); - float *net_input_buf = (float*)malloc(yuv_buf_len*sizeof(float)); - printf("allocate -- %p 0x%x -- %p 0x%lx\n", resized_buf, resized_width*resized_height*3/2, net_input_buf, yuv_buf_len*sizeof(float)); - - // test for bad buffers - static int CNT = 20; - float avg = 0.0; - for (int i = 0; i < CNT; i++) { - double s4 = millis_since_boot(); - inner(resized_buf, net_input_buf); - double s5 = millis_since_boot(); - avg += s5-s4; - } - avg /= CNT; - - // once it's bad, it's reliably bad - if (avg > 10) { - printf("HIT %f\n", avg); - printf("BAD\n"); - - for (int i = 0; i < 200; i++) { - double s4 = millis_since_boot(); - inner(resized_buf, net_input_buf); - double s5 = millis_since_boot(); - printf("%.2f ", s5-s4); - } - printf("\n"); - - exit(0); - } - - // don't free so we get a different buffer each time - //free(resized_buf); - //free(net_input_buf); - - return avg; -} - -int main() { - while (true) { - float ret = trial(); - printf("got %f\n", ret); - } -} - diff --git a/sunnypilot/modeld_v2/tests/test_modeld.py b/sunnypilot/modeld_v2/tests/test_modeld.py deleted file mode 100644 index 6927c9e473..0000000000 --- a/sunnypilot/modeld_v2/tests/test_modeld.py +++ /dev/null @@ -1,102 +0,0 @@ -import numpy as np -import random - -import cereal.messaging as messaging -from msgq.visionipc import VisionIpcServer, VisionStreamType -from opendbc.car.car_helpers import get_demo_car_params -from openpilot.common.params import Params -from openpilot.common.transformations.camera import DEVICE_CAMERAS -from openpilot.common.realtime import DT_MDL -from openpilot.system.manager.process_config import managed_processes -from openpilot.selfdrive.test.process_replay.vision_meta import meta_from_camera_state - -CAM = DEVICE_CAMERAS[("tici", "ar0231")].fcam -IMG = np.zeros(int(CAM.width*CAM.height*(3/2)), dtype=np.uint8) -IMG_BYTES = IMG.flatten().tobytes() - - -class TestModeld: - - def setup_method(self): - self.vipc_server = VisionIpcServer("camerad") - self.vipc_server.create_buffers(VisionStreamType.VISION_STREAM_ROAD, 40, CAM.width, CAM.height) - self.vipc_server.create_buffers(VisionStreamType.VISION_STREAM_DRIVER, 40, CAM.width, CAM.height) - self.vipc_server.create_buffers(VisionStreamType.VISION_STREAM_WIDE_ROAD, 40, CAM.width, CAM.height) - self.vipc_server.start_listener() - Params().put("CarParams", get_demo_car_params().to_bytes()) - - self.sm = messaging.SubMaster(['modelV2', 'cameraOdometry']) - self.pm = messaging.PubMaster(['roadCameraState', 'wideRoadCameraState', 'liveCalibration']) - - managed_processes['modeld'].start() - self.pm.wait_for_readers_to_update("roadCameraState", 10) - - def teardown_method(self): - managed_processes['modeld'].stop() - del self.vipc_server - - def _send_frames(self, frame_id, cams=None): - if cams is None: - cams = ('roadCameraState', 'wideRoadCameraState') - - cs = None - for cam in cams: - msg = messaging.new_message(cam) - cs = getattr(msg, cam) - cs.frameId = frame_id - cs.timestampSof = int((frame_id * DT_MDL) * 1e9) - cs.timestampEof = int(cs.timestampSof + (DT_MDL * 1e9)) - cam_meta = meta_from_camera_state(cam) - - self.pm.send(msg.which(), msg) - self.vipc_server.send(cam_meta.stream, IMG_BYTES, cs.frameId, - cs.timestampSof, cs.timestampEof) - return cs - - def _wait(self): - self.sm.update(5000) - if self.sm['modelV2'].frameId != self.sm['cameraOdometry'].frameId: - self.sm.update(1000) - - def test_modeld(self): - for n in range(1, 500): - cs = self._send_frames(n) - self._wait() - - mdl = self.sm['modelV2'] - assert mdl.frameId == n - assert mdl.frameIdExtra == n - assert mdl.timestampEof == cs.timestampEof - assert mdl.frameAge == 0 - assert mdl.frameDropPerc == 0 - - odo = self.sm['cameraOdometry'] - assert odo.frameId == n - assert odo.timestampEof == cs.timestampEof - - def test_dropped_frames(self): - """ - modeld should only run on consecutive road frames - """ - frame_id = -1 - road_frames = list() - for n in range(1, 50): - if (random.random() < 0.1) and n > 3: - cams = random.choice([(), ('wideRoadCameraState', )]) - self._send_frames(n, cams) - else: - self._send_frames(n) - road_frames.append(n) - self._wait() - - if len(road_frames) < 3 or road_frames[-1] - road_frames[-2] == 1: - frame_id = road_frames[-1] - - mdl = self.sm['modelV2'] - odo = self.sm['cameraOdometry'] - assert mdl.frameId == frame_id - assert mdl.frameIdExtra == frame_id - assert odo.frameId == frame_id - if n != frame_id: - assert not self.sm.updated['modelV2'] - assert not self.sm.updated['cameraOdometry'] diff --git a/sunnypilot/modeld_v2/tests/tf_test/build.sh b/sunnypilot/modeld_v2/tests/tf_test/build.sh deleted file mode 100755 index df1d24761e..0000000000 --- a/sunnypilot/modeld_v2/tests/tf_test/build.sh +++ /dev/null @@ -1,2 +0,0 @@ -#!/usr/bin/env bash -clang++ -I /home/batman/one/external/tensorflow/include/ -L /home/batman/one/external/tensorflow/lib -Wl,-rpath=/home/batman/one/external/tensorflow/lib main.cc -ltensorflow diff --git a/sunnypilot/modeld_v2/tests/tf_test/main.cc b/sunnypilot/modeld_v2/tests/tf_test/main.cc deleted file mode 100644 index b00f7f95e8..0000000000 --- a/sunnypilot/modeld_v2/tests/tf_test/main.cc +++ /dev/null @@ -1,69 +0,0 @@ -#include -#include -#include -#include "tensorflow/c/c_api.h" - -void* read_file(const char* path, size_t* out_len) { - FILE* f = fopen(path, "r"); - if (!f) { - return NULL; - } - fseek(f, 0, SEEK_END); - long f_len = ftell(f); - rewind(f); - - char* buf = (char*)calloc(f_len, 1); - assert(buf); - - size_t num_read = fread(buf, f_len, 1, f); - fclose(f); - - if (num_read != 1) { - free(buf); - return NULL; - } - - if (out_len) { - *out_len = f_len; - } - - return buf; -} - -static void DeallocateBuffer(void* data, size_t) { - free(data); -} - -int main(int argc, char* argv[]) { - TF_Buffer* buf; - TF_Graph* graph; - TF_Status* status; - char *path = argv[1]; - - // load model - { - size_t model_size; - char tmp[1024]; - snprintf(tmp, sizeof(tmp), "%s.pb", path); - printf("loading model %s\n", tmp); - uint8_t *model_data = (uint8_t *)read_file(tmp, &model_size); - buf = TF_NewBuffer(); - buf->data = model_data; - buf->length = model_size; - buf->data_deallocator = DeallocateBuffer; - printf("loaded model of size %d\n", model_size); - } - - // import graph - status = TF_NewStatus(); - graph = TF_NewGraph(); - TF_ImportGraphDefOptions *opts = TF_NewImportGraphDefOptions(); - TF_GraphImportGraphDef(graph, buf, opts, status); - TF_DeleteImportGraphDefOptions(opts); - TF_DeleteBuffer(buf); - if (TF_GetCode(status) != TF_OK) { - printf("FAIL: %s\n", TF_Message(status)); - } else { - printf("SUCCESS\n"); - } -} diff --git a/sunnypilot/modeld_v2/tests/tf_test/pb_loader.py b/sunnypilot/modeld_v2/tests/tf_test/pb_loader.py deleted file mode 100755 index 3e476628eb..0000000000 --- a/sunnypilot/modeld_v2/tests/tf_test/pb_loader.py +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/env python3 -import sys -import tensorflow as tf - -with open(sys.argv[1], "rb") as f: - graph_def = tf.compat.v1.GraphDef() - graph_def.ParseFromString(f.read()) - #tf.io.write_graph(graph_def, '', sys.argv[1]+".try") diff --git a/sunnypilot/modeld_v2/tests/timing/benchmark.py b/sunnypilot/modeld_v2/tests/timing/benchmark.py deleted file mode 100755 index c629ec2fff..0000000000 --- a/sunnypilot/modeld_v2/tests/timing/benchmark.py +++ /dev/null @@ -1,39 +0,0 @@ -#!/usr/bin/env python3 -# type: ignore - -import os -import time -import numpy as np - -import cereal.messaging as messaging -from openpilot.system.manager.process_config import managed_processes - - -N = int(os.getenv("N", "5")) -TIME = int(os.getenv("TIME", "30")) - -if __name__ == "__main__": - sock = messaging.sub_sock('modelV2', conflate=False, timeout=1000) - - execution_times = [] - - for _ in range(N): - os.environ['LOGPRINT'] = 'debug' - managed_processes['modeld'].start() - time.sleep(5) - - t = [] - start = time.monotonic() - while time.monotonic() - start < TIME: - msgs = messaging.drain_sock(sock, wait_for_one=True) - for m in msgs: - t.append(m.modelV2.modelExecutionTime) - - execution_times.append(np.array(t[10:]) * 1000) - managed_processes['modeld'].stop() - - print("\n\n") - print(f"ran modeld {N} times for {TIME}s each") - for _, t in enumerate(execution_times): - print(f"\tavg: {sum(t)/len(t):0.2f}ms, min: {min(t):0.2f}ms, max: {max(t):0.2f}ms") - print("\n\n") diff --git a/sunnypilot/modeld_v2/transforms/loadyuv.cc b/sunnypilot/modeld_v2/transforms/loadyuv.cc deleted file mode 100644 index eb669a5929..0000000000 --- a/sunnypilot/modeld_v2/transforms/loadyuv.cc +++ /dev/null @@ -1,76 +0,0 @@ -#include "sunnypilot/modeld_v2/transforms/loadyuv.h" - -#include -#include -#include - -void loadyuv_init(LoadYUVState* s, cl_context ctx, cl_device_id device_id, int width, int height) { - memset(s, 0, sizeof(*s)); - - s->width = width; - s->height = height; - - char args[1024]; - snprintf(args, sizeof(args), - "-cl-fast-relaxed-math -cl-denorms-are-zero " - "-DTRANSFORMED_WIDTH=%d -DTRANSFORMED_HEIGHT=%d", - width, height); - cl_program prg = cl_program_from_file(ctx, device_id, LOADYUV_PATH, args); - - s->loadys_krnl = CL_CHECK_ERR(clCreateKernel(prg, "loadys", &err)); - s->loaduv_krnl = CL_CHECK_ERR(clCreateKernel(prg, "loaduv", &err)); - s->copy_krnl = CL_CHECK_ERR(clCreateKernel(prg, "copy", &err)); - - // done with this - CL_CHECK(clReleaseProgram(prg)); -} - -void loadyuv_destroy(LoadYUVState* s) { - CL_CHECK(clReleaseKernel(s->loadys_krnl)); - CL_CHECK(clReleaseKernel(s->loaduv_krnl)); - CL_CHECK(clReleaseKernel(s->copy_krnl)); -} - -void loadyuv_queue(LoadYUVState* s, cl_command_queue q, - cl_mem y_cl, cl_mem u_cl, cl_mem v_cl, - cl_mem out_cl) { - cl_int global_out_off = 0; - - CL_CHECK(clSetKernelArg(s->loadys_krnl, 0, sizeof(cl_mem), &y_cl)); - CL_CHECK(clSetKernelArg(s->loadys_krnl, 1, sizeof(cl_mem), &out_cl)); - CL_CHECK(clSetKernelArg(s->loadys_krnl, 2, sizeof(cl_int), &global_out_off)); - - const size_t loadys_work_size = (s->width*s->height)/8; - CL_CHECK(clEnqueueNDRangeKernel(q, s->loadys_krnl, 1, NULL, - &loadys_work_size, NULL, 0, 0, NULL)); - - const size_t loaduv_work_size = ((s->width/2)*(s->height/2))/8; - global_out_off += (s->width*s->height); - - CL_CHECK(clSetKernelArg(s->loaduv_krnl, 0, sizeof(cl_mem), &u_cl)); - CL_CHECK(clSetKernelArg(s->loaduv_krnl, 1, sizeof(cl_mem), &out_cl)); - CL_CHECK(clSetKernelArg(s->loaduv_krnl, 2, sizeof(cl_int), &global_out_off)); - - CL_CHECK(clEnqueueNDRangeKernel(q, s->loaduv_krnl, 1, NULL, - &loaduv_work_size, NULL, 0, 0, NULL)); - - global_out_off += (s->width/2)*(s->height/2); - - CL_CHECK(clSetKernelArg(s->loaduv_krnl, 0, sizeof(cl_mem), &v_cl)); - CL_CHECK(clSetKernelArg(s->loaduv_krnl, 1, sizeof(cl_mem), &out_cl)); - CL_CHECK(clSetKernelArg(s->loaduv_krnl, 2, sizeof(cl_int), &global_out_off)); - - CL_CHECK(clEnqueueNDRangeKernel(q, s->loaduv_krnl, 1, NULL, - &loaduv_work_size, NULL, 0, 0, NULL)); -} - -void copy_queue(LoadYUVState* s, cl_command_queue q, cl_mem src, cl_mem dst, - size_t src_offset, size_t dst_offset, size_t size) { - CL_CHECK(clSetKernelArg(s->copy_krnl, 0, sizeof(cl_mem), &src)); - CL_CHECK(clSetKernelArg(s->copy_krnl, 1, sizeof(cl_mem), &dst)); - CL_CHECK(clSetKernelArg(s->copy_krnl, 2, sizeof(cl_int), &src_offset)); - CL_CHECK(clSetKernelArg(s->copy_krnl, 3, sizeof(cl_int), &dst_offset)); - const size_t copy_work_size = size/8; - CL_CHECK(clEnqueueNDRangeKernel(q, s->copy_krnl, 1, NULL, - ©_work_size, NULL, 0, 0, NULL)); -} \ No newline at end of file diff --git a/sunnypilot/modeld_v2/transforms/loadyuv.cl b/sunnypilot/modeld_v2/transforms/loadyuv.cl deleted file mode 100644 index 970187a6d7..0000000000 --- a/sunnypilot/modeld_v2/transforms/loadyuv.cl +++ /dev/null @@ -1,47 +0,0 @@ -#define UV_SIZE ((TRANSFORMED_WIDTH/2)*(TRANSFORMED_HEIGHT/2)) - -__kernel void loadys(__global uchar8 const * const Y, - __global uchar * out, - int out_offset) -{ - const int gid = get_global_id(0); - const int ois = gid * 8; - const int oy = ois / TRANSFORMED_WIDTH; - const int ox = ois % TRANSFORMED_WIDTH; - - const uchar8 ys = Y[gid]; - - // 02 - // 13 - - __global uchar* outy0; - __global uchar* outy1; - if ((oy & 1) == 0) { - outy0 = out + out_offset; //y0 - outy1 = out + out_offset + UV_SIZE*2; //y2 - } else { - outy0 = out + out_offset + UV_SIZE; //y1 - outy1 = out + out_offset + UV_SIZE*3; //y3 - } - - vstore4(ys.s0246, 0, outy0 + (oy/2) * (TRANSFORMED_WIDTH/2) + ox/2); - vstore4(ys.s1357, 0, outy1 + (oy/2) * (TRANSFORMED_WIDTH/2) + ox/2); -} - -__kernel void loaduv(__global uchar8 const * const in, - __global uchar8 * out, - int out_offset) -{ - const int gid = get_global_id(0); - const uchar8 inv = in[gid]; - out[gid + out_offset / 8] = inv; -} - -__kernel void copy(__global uchar8 * in, - __global uchar8 * out, - int in_offset, - int out_offset) -{ - const int gid = get_global_id(0); - out[gid + out_offset / 8] = in[gid + in_offset / 8]; -} diff --git a/sunnypilot/modeld_v2/transforms/loadyuv.h b/sunnypilot/modeld_v2/transforms/loadyuv.h deleted file mode 100644 index 659059cd25..0000000000 --- a/sunnypilot/modeld_v2/transforms/loadyuv.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once - -#include "common/clutil.h" - -typedef struct { - int width, height; - cl_kernel loadys_krnl, loaduv_krnl, copy_krnl; -} LoadYUVState; - -void loadyuv_init(LoadYUVState* s, cl_context ctx, cl_device_id device_id, int width, int height); - -void loadyuv_destroy(LoadYUVState* s); - -void loadyuv_queue(LoadYUVState* s, cl_command_queue q, - cl_mem y_cl, cl_mem u_cl, cl_mem v_cl, - cl_mem out_cl); - - -void copy_queue(LoadYUVState* s, cl_command_queue q, cl_mem src, cl_mem dst, - size_t src_offset, size_t dst_offset, size_t size); \ No newline at end of file diff --git a/sunnypilot/modeld_v2/transforms/transform.cc b/sunnypilot/modeld_v2/transforms/transform.cc deleted file mode 100644 index adc9bcebf4..0000000000 --- a/sunnypilot/modeld_v2/transforms/transform.cc +++ /dev/null @@ -1,97 +0,0 @@ -#include "sunnypilot/modeld_v2/transforms/transform.h" - -#include -#include - -#include "common/clutil.h" - -void transform_init(Transform* s, cl_context ctx, cl_device_id device_id) { - memset(s, 0, sizeof(*s)); - - cl_program prg = cl_program_from_file(ctx, device_id, TRANSFORM_PATH, ""); - s->krnl = CL_CHECK_ERR(clCreateKernel(prg, "warpPerspective", &err)); - // done with this - CL_CHECK(clReleaseProgram(prg)); - - s->m_y_cl = CL_CHECK_ERR(clCreateBuffer(ctx, CL_MEM_READ_WRITE, 3*3*sizeof(float), NULL, &err)); - s->m_uv_cl = CL_CHECK_ERR(clCreateBuffer(ctx, CL_MEM_READ_WRITE, 3*3*sizeof(float), NULL, &err)); -} - -void transform_destroy(Transform* s) { - CL_CHECK(clReleaseMemObject(s->m_y_cl)); - CL_CHECK(clReleaseMemObject(s->m_uv_cl)); - CL_CHECK(clReleaseKernel(s->krnl)); -} - -void transform_queue(Transform* s, - cl_command_queue q, - cl_mem in_yuv, int in_width, int in_height, int in_stride, int in_uv_offset, - cl_mem out_y, cl_mem out_u, cl_mem out_v, - int out_width, int out_height, - const mat3& projection) { - const int zero = 0; - - // sampled using pixel center origin - // (because that's how fastcv and opencv does it) - - mat3 projection_y = projection; - - // in and out uv is half the size of y. - mat3 projection_uv = transform_scale_buffer(projection, 0.5); - - CL_CHECK(clEnqueueWriteBuffer(q, s->m_y_cl, CL_TRUE, 0, 3*3*sizeof(float), (void*)projection_y.v, 0, NULL, NULL)); - CL_CHECK(clEnqueueWriteBuffer(q, s->m_uv_cl, CL_TRUE, 0, 3*3*sizeof(float), (void*)projection_uv.v, 0, NULL, NULL)); - - const int in_y_width = in_width; - const int in_y_height = in_height; - const int in_y_px_stride = 1; - const int in_uv_width = in_width/2; - const int in_uv_height = in_height/2; - const int in_uv_px_stride = 2; - const int in_u_offset = in_uv_offset; - const int in_v_offset = in_uv_offset + 1; - - const int out_y_width = out_width; - const int out_y_height = out_height; - const int out_uv_width = out_width/2; - const int out_uv_height = out_height/2; - - CL_CHECK(clSetKernelArg(s->krnl, 0, sizeof(cl_mem), &in_yuv)); // src - CL_CHECK(clSetKernelArg(s->krnl, 1, sizeof(cl_int), &in_stride)); // src_row_stride - CL_CHECK(clSetKernelArg(s->krnl, 2, sizeof(cl_int), &in_y_px_stride)); // src_px_stride - CL_CHECK(clSetKernelArg(s->krnl, 3, sizeof(cl_int), &zero)); // src_offset - CL_CHECK(clSetKernelArg(s->krnl, 4, sizeof(cl_int), &in_y_height)); // src_rows - CL_CHECK(clSetKernelArg(s->krnl, 5, sizeof(cl_int), &in_y_width)); // src_cols - CL_CHECK(clSetKernelArg(s->krnl, 6, sizeof(cl_mem), &out_y)); // dst - CL_CHECK(clSetKernelArg(s->krnl, 7, sizeof(cl_int), &out_y_width)); // dst_row_stride - CL_CHECK(clSetKernelArg(s->krnl, 8, sizeof(cl_int), &zero)); // dst_offset - CL_CHECK(clSetKernelArg(s->krnl, 9, sizeof(cl_int), &out_y_height)); // dst_rows - CL_CHECK(clSetKernelArg(s->krnl, 10, sizeof(cl_int), &out_y_width)); // dst_cols - CL_CHECK(clSetKernelArg(s->krnl, 11, sizeof(cl_mem), &s->m_y_cl)); // M - - const size_t work_size_y[2] = {(size_t)out_y_width, (size_t)out_y_height}; - - CL_CHECK(clEnqueueNDRangeKernel(q, s->krnl, 2, NULL, - (const size_t*)&work_size_y, NULL, 0, 0, NULL)); - - const size_t work_size_uv[2] = {(size_t)out_uv_width, (size_t)out_uv_height}; - - CL_CHECK(clSetKernelArg(s->krnl, 2, sizeof(cl_int), &in_uv_px_stride)); // src_px_stride - CL_CHECK(clSetKernelArg(s->krnl, 3, sizeof(cl_int), &in_u_offset)); // src_offset - CL_CHECK(clSetKernelArg(s->krnl, 4, sizeof(cl_int), &in_uv_height)); // src_rows - CL_CHECK(clSetKernelArg(s->krnl, 5, sizeof(cl_int), &in_uv_width)); // src_cols - CL_CHECK(clSetKernelArg(s->krnl, 6, sizeof(cl_mem), &out_u)); // dst - CL_CHECK(clSetKernelArg(s->krnl, 7, sizeof(cl_int), &out_uv_width)); // dst_row_stride - CL_CHECK(clSetKernelArg(s->krnl, 8, sizeof(cl_int), &zero)); // dst_offset - CL_CHECK(clSetKernelArg(s->krnl, 9, sizeof(cl_int), &out_uv_height)); // dst_rows - CL_CHECK(clSetKernelArg(s->krnl, 10, sizeof(cl_int), &out_uv_width)); // dst_cols - CL_CHECK(clSetKernelArg(s->krnl, 11, sizeof(cl_mem), &s->m_uv_cl)); // M - - CL_CHECK(clEnqueueNDRangeKernel(q, s->krnl, 2, NULL, - (const size_t*)&work_size_uv, NULL, 0, 0, NULL)); - CL_CHECK(clSetKernelArg(s->krnl, 3, sizeof(cl_int), &in_v_offset)); // src_ofset - CL_CHECK(clSetKernelArg(s->krnl, 6, sizeof(cl_mem), &out_v)); // dst - - CL_CHECK(clEnqueueNDRangeKernel(q, s->krnl, 2, NULL, - (const size_t*)&work_size_uv, NULL, 0, 0, NULL)); -} diff --git a/sunnypilot/modeld_v2/transforms/transform.cl b/sunnypilot/modeld_v2/transforms/transform.cl deleted file mode 100644 index 2ca25920cd..0000000000 --- a/sunnypilot/modeld_v2/transforms/transform.cl +++ /dev/null @@ -1,54 +0,0 @@ -#define INTER_BITS 5 -#define INTER_TAB_SIZE (1 << INTER_BITS) -#define INTER_SCALE 1.f / INTER_TAB_SIZE - -#define INTER_REMAP_COEF_BITS 15 -#define INTER_REMAP_COEF_SCALE (1 << INTER_REMAP_COEF_BITS) - -__kernel void warpPerspective(__global const uchar * src, - int src_row_stride, int src_px_stride, int src_offset, int src_rows, int src_cols, - __global uchar * dst, - int dst_row_stride, int dst_offset, int dst_rows, int dst_cols, - __constant float * M) -{ - int dx = get_global_id(0); - int dy = get_global_id(1); - - if (dx < dst_cols && dy < dst_rows) - { - float X0 = M[0] * dx + M[1] * dy + M[2]; - float Y0 = M[3] * dx + M[4] * dy + M[5]; - float W = M[6] * dx + M[7] * dy + M[8]; - W = W != 0.0f ? INTER_TAB_SIZE / W : 0.0f; - int X = rint(X0 * W), Y = rint(Y0 * W); - - int sx = convert_short_sat(X >> INTER_BITS); - int sy = convert_short_sat(Y >> INTER_BITS); - - short sx_clamp = clamp(sx, 0, src_cols - 1); - short sx_p1_clamp = clamp(sx + 1, 0, src_cols - 1); - short sy_clamp = clamp(sy, 0, src_rows - 1); - short sy_p1_clamp = clamp(sy + 1, 0, src_rows - 1); - int v0 = convert_int(src[mad24(sy_clamp, src_row_stride, src_offset + sx_clamp*src_px_stride)]); - int v1 = convert_int(src[mad24(sy_clamp, src_row_stride, src_offset + sx_p1_clamp*src_px_stride)]); - int v2 = convert_int(src[mad24(sy_p1_clamp, src_row_stride, src_offset + sx_clamp*src_px_stride)]); - int v3 = convert_int(src[mad24(sy_p1_clamp, src_row_stride, src_offset + sx_p1_clamp*src_px_stride)]); - - short ay = (short)(Y & (INTER_TAB_SIZE - 1)); - short ax = (short)(X & (INTER_TAB_SIZE - 1)); - float taby = 1.f/INTER_TAB_SIZE*ay; - float tabx = 1.f/INTER_TAB_SIZE*ax; - - int dst_index = mad24(dy, dst_row_stride, dst_offset + dx); - - int itab0 = convert_short_sat_rte( (1.0f-taby)*(1.0f-tabx) * INTER_REMAP_COEF_SCALE ); - int itab1 = convert_short_sat_rte( (1.0f-taby)*tabx * INTER_REMAP_COEF_SCALE ); - int itab2 = convert_short_sat_rte( taby*(1.0f-tabx) * INTER_REMAP_COEF_SCALE ); - int itab3 = convert_short_sat_rte( taby*tabx * INTER_REMAP_COEF_SCALE ); - - int val = v0 * itab0 + v1 * itab1 + v2 * itab2 + v3 * itab3; - - uchar pix = convert_uchar_sat((val + (1 << (INTER_REMAP_COEF_BITS-1))) >> INTER_REMAP_COEF_BITS); - dst[dst_index] = pix; - } -} diff --git a/sunnypilot/modeld_v2/transforms/transform.h b/sunnypilot/modeld_v2/transforms/transform.h deleted file mode 100644 index 771a7054b3..0000000000 --- a/sunnypilot/modeld_v2/transforms/transform.h +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once - -#define CL_USE_DEPRECATED_OPENCL_1_2_APIS -#ifdef __APPLE__ -#include -#else -#include -#endif - -#include "common/mat.h" - -typedef struct { - cl_kernel krnl; - cl_mem m_y_cl, m_uv_cl; -} Transform; - -void transform_init(Transform* s, cl_context ctx, cl_device_id device_id); - -void transform_destroy(Transform* transform); - -void transform_queue(Transform* s, cl_command_queue q, - cl_mem yuv, int in_width, int in_height, int in_stride, int in_uv_offset, - cl_mem out_y, cl_mem out_u, cl_mem out_v, - int out_width, int out_height, - const mat3& projection); diff --git a/sunnypilot/models/default_model.py b/sunnypilot/models/default_model.py deleted file mode 100755 index 718c910c5c..0000000000 --- a/sunnypilot/models/default_model.py +++ /dev/null @@ -1,70 +0,0 @@ -import argparse -import os -import hashlib - -from openpilot.common.basedir import BASEDIR - -DEFAULT_MODEL_NAME_PATH = os.path.join(BASEDIR, "common", "model.h") -MODEL_HASH_PATH = os.path.join(BASEDIR, "sunnypilot", "models", "tests", "model_hash") -VISION_ONNX_PATH = os.path.join(BASEDIR, "selfdrive", "modeld", "models", "driving_vision.onnx") -POLICY_ONNX_PATH = os.path.join(BASEDIR, "selfdrive", "modeld", "models", "driving_policy.onnx") - - -def get_file_hash(path: str) -> str: - sha256_hash = hashlib.sha256() - with open(path, "rb") as f: - for byte_block in iter(lambda: f.read(4096), b""): - sha256_hash.update(byte_block) - return sha256_hash.hexdigest() - - -def update_model_hash(): - vision_hash = get_file_hash(VISION_ONNX_PATH) - policy_hash = get_file_hash(POLICY_ONNX_PATH) - - combined_hash = hashlib.sha256((vision_hash + policy_hash).encode()).hexdigest() - - with open(MODEL_HASH_PATH, "w") as f: - f.write(combined_hash) - - print(f"Generated and updated new combined model hash to {MODEL_HASH_PATH}") - - -def get_current_default_model_name(): - print("[GET DEFAULT MODEL NAME]") - with open(DEFAULT_MODEL_NAME_PATH) as f: - name = f.read().split('"')[1] - print(f'Current default model name: "{name}"') - - return name - - -def update_default_model_name(name: str): - print("[CHANGE DEFAULT MODEL NAME]") - with open(DEFAULT_MODEL_NAME_PATH, "w") as f: - f.write(f'#define DEFAULT_MODEL "{name}"\n') - print(f'New default model name: "{name}"') - print("[DONE]") - - -if __name__ == "__main__": - parser = argparse.ArgumentParser(description="Update default model name and hash") - parser.add_argument("--new_name", type=str, help="New default model name") - args = parser.parse_args() - - if not args.new_name: - print("Warning: No new default model name provided. Use --new_name to specify") - print("Default model name and hash will not be updated! (aborted)") - exit(0) - - current_name = get_current_default_model_name() - new_name = f"{args.new_name} (Default)" - if current_name == new_name: - print(f'Proposed default model name: "{new_name}"') - confirm = input("Proposed default model name is the same as the current default model name. Confirm? (y/n): ").upper().strip() - if confirm != "Y": - print("Default model name and hash will not be updated! (aborted)") - exit(0) - - update_default_model_name(new_name) - update_model_hash() diff --git a/sunnypilot/models/helpers.py b/sunnypilot/models/helpers.py deleted file mode 100644 index a614447ceb..0000000000 --- a/sunnypilot/models/helpers.py +++ /dev/null @@ -1,186 +0,0 @@ -""" -Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - -This file is part of sunnypilot and is licensed under the MIT License. -See the LICENSE.md file in the root directory for more details. -""" - -import hashlib -import os -import pickle -import numpy as np -import json - -from openpilot.common.params import Params -from cereal import custom -from openpilot.sunnypilot.modeld.constants import Meta, MetaTombRaider, MetaSimPose -from openpilot.sunnypilot.modeld.runners import ModelRunner -from openpilot.system.hardware import PC -from openpilot.system.hardware.hw import Paths -from pathlib import Path - -CURRENT_SELECTOR_VERSION = 6 -REQUIRED_MIN_SELECTOR_VERSION = 5 - -USE_ONNX = os.getenv('USE_ONNX', PC) - -CUSTOM_MODEL_PATH = Paths.model_root() -METADATA_PATH = Path(__file__).parent / '../models/supercombo_metadata.pkl' - -ModelManager = custom.ModelManagerSP - - -async def verify_file(file_path: str, expected_hash: str) -> bool: - """Verifies file hash against expected hash""" - if not os.path.exists(file_path): - return False - - sha256_hash = hashlib.sha256() - with open(file_path, "rb") as file: - for chunk in iter(lambda: file.read(4096), b""): - sha256_hash.update(chunk) - - return sha256_hash.hexdigest().lower() == expected_hash.lower() - - -def is_bundle_version_compatible(bundle: dict) -> bool: - """ - Checks whether the model bundle is compatible with the current selector version constraints. - - The bundle specifies a `minimum_selector_version`, which defines the minimum selector version - required to load the model. This function ensures that: - - 1. The model is not too old: the bundle must require at least `REQUIRED_MIN_SELECTOR_VERSION`. - 2. The model is not too new: it must support the current selector version (`CURRENT_SELECTOR_VERSION`). - - This allows the selector to enforce both a minimum and maximum range of supported models, - even if a model would otherwise be compatible. - - :param bundle: Dictionary containing `minimum_selector_version`, as defined by the model bundle. - :type bundle: Dict - :return: True if the selector version is within the accepted range for the bundle; otherwise False. - :rtype: Bool - """ - return bool(REQUIRED_MIN_SELECTOR_VERSION <= bundle.get("minimumSelectorVersion", 0) <= CURRENT_SELECTOR_VERSION) - -def get_active_bundle(params: Params = None) -> custom.ModelManagerSP.ModelBundle: - """Gets the active model bundle from cache""" - if params is None: - params = Params() - - try: - if (active_bundle := json.loads(params.get("ModelManager_ActiveBundle") or "{}")) and is_bundle_version_compatible(active_bundle): - return custom.ModelManagerSP.ModelBundle(**active_bundle) - except Exception: - pass - - return None - - -def get_active_model_runner(params: Params = None, force_check=False) -> custom.ModelManagerSP.Runner: - """ - Determines and returns the active model runner type, based on provided parameters. - The function utilizes caching to prevent redundant calculations and checks. - - If the cached "ModelRunnerTypeCache" exists in the provided parameters and `force_check` - is set to False, the cached value is directly returned. Otherwise, the function determines - the runner type based on the active model bundle. If a model bundle containing a drive - model exists, the runner type is derived based on the filename of the drive model. - Finally, it updates the cache with the determined runner type, if needed. - - :param params: The parameter set used to retrieve caching and runner details. If `None`, - a default `Params` instance is created internally. - :type params: Params - :param force_check: A flag indicating whether to bypass cached results and always - re-determine the runner type. Defaults to `False`. - :type force_check: bool - :return: The determined or cached model runner type. - :rtype: custom.ModelManagerSP.Runner - """ - if params is None: - params = Params() - - if (cached_runner_type := params.get("ModelRunnerTypeCache")) and not force_check: - if isinstance(cached_runner_type, str) and cached_runner_type.isdigit(): - return int(cached_runner_type) - - runner_type = custom.ModelManagerSP.Runner.stock - - if active_bundle := get_active_bundle(params): - runner_type = active_bundle.runner.raw - - if cached_runner_type != runner_type: - params.put("ModelRunnerTypeCache", str(int(runner_type))) - - return runner_type - -def _get_model(): - if bundle := get_active_bundle(): - drive_model = next(model for model in bundle.models if model.type == ModelManager.Model.Type.supercombo) - return drive_model - - return None - -def get_model_path(): - if USE_ONNX: - return {ModelRunner.ONNX: Path(__file__).parent / '../models/supercombo.onnx'} - - if model := _get_model(): - return {ModelRunner.THNEED: f"{CUSTOM_MODEL_PATH}/{model.artifact.fileName}"} - - return {ModelRunner.THNEED: Path(__file__).parent / '../models/supercombo.thneed'} - - -def load_metadata(): - metadata_path = METADATA_PATH - - if model := _get_model(): - metadata_path = f"{CUSTOM_MODEL_PATH}/{model.metadata.fileName}" - - with open(metadata_path, 'rb') as f: - return pickle.load(f) - - -def prepare_inputs(model_metadata) -> dict[str, np.ndarray]: - # img buffers are managed in openCL transform code so we don't pass them as inputs - inputs = { - k: np.zeros(v, dtype=np.float32).flatten() - for k, v in model_metadata['input_shapes'].items() - if 'img' not in k - } - - return inputs - - -def load_meta_constants(model_metadata): - """ - Determines and loads the appropriate meta model class based on the metadata provided. The function checks - specific keys and conditions within the provided metadata dictionary to identify the corresponding meta - model class to return. - - :param model_metadata: Dictionary containing metadata about the model. It includes - details such as input shapes, output slices, and other configurations for identifying - metadata-dependent meta model classes. - :type model_metadata: dict - :return: The appropriate meta model class (Meta, MetaSimPose, or MetaTombRaider) - based on the conditions and metadata provided. - :rtype: type - """ - meta = Meta # Default Meta - - if 'sim_pose' in model_metadata['input_shapes'].keys(): - # Meta for models with sim_pose input - meta = MetaSimPose - else: - # Meta for Tomb Raider, it does not include sim_pose input but has the same meta slice as previous models - meta_slice = model_metadata['output_slices']['meta'] - meta_tf_slice = slice(5868, 5921, None) - - if ( - meta_slice.start == meta_tf_slice.start and - meta_slice.stop == meta_tf_slice.stop and - meta_slice.step == meta_tf_slice.step - ): - meta = MetaTombRaider - - return meta diff --git a/sunnypilot/models/manager.py b/sunnypilot/models/manager.py deleted file mode 100644 index 630d6a8d77..0000000000 --- a/sunnypilot/models/manager.py +++ /dev/null @@ -1,194 +0,0 @@ -""" -Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - -This file is part of sunnypilot and is licensed under the MIT License. -See the LICENSE.md file in the root directory for more details. -""" - -import asyncio -import os -import time -import json - -import aiohttp -from openpilot.common.params import Params -from openpilot.common.realtime import Ratekeeper -from openpilot.common.swaglog import cloudlog -from openpilot.system.hardware.hw import Paths - -from cereal import messaging, custom -from sunnypilot.models.fetcher import ModelFetcher -from sunnypilot.models.helpers import verify_file, get_active_bundle - - -class ModelManagerSP: - """Manages model downloads and status reporting""" - - def __init__(self): - self.params = Params() - self.model_fetcher = ModelFetcher(self.params) - self.pm = messaging.PubMaster(["modelManagerSP"]) - self.available_models: list[custom.ModelManagerSP.ModelBundle] = [] - self.selected_bundle: custom.ModelManagerSP.ModelBundle = None - self.active_bundle: custom.ModelManagerSP.ModelBundle = get_active_bundle(self.params) - self._chunk_size = 128 * 1000 # 128 KB chunks - self._download_start_times: dict[str, float] = {} # Track start time per model - - def _calculate_eta(self, filename: str, progress: float) -> int: - """Calculate ETA based on elapsed time and current progress""" - if filename not in self._download_start_times or progress <= 0: - return 60 # Default ETA for new downloads - - elapsed_time = time.monotonic() - self._download_start_times[filename] - if elapsed_time <= 0: - return 60 - - # If we're at X% after Y seconds, we can estimate total time as (Y / X) * 100 - total_estimated_time = (elapsed_time / progress) * 100 - eta = total_estimated_time - elapsed_time - - return max(1, int(eta)) # Return at least 1 second if download is ongoing - - async def _download_file(self, url: str, path: str, model) -> None: - """Downloads a file with progress tracking""" - self._download_start_times[model.fileName] = time.monotonic() - - async with aiohttp.ClientSession() as session: - async with session.get(url) as response: - response.raise_for_status() - total_size = int(response.headers.get("content-length", 0)) - bytes_downloaded = 0 - - with open(path, 'wb') as f: - async for chunk in response.content.iter_chunked(self._chunk_size): # type: bytes - f.write(chunk) - bytes_downloaded += len(chunk) - - if total_size > 0: - progress = (bytes_downloaded / total_size) * 100 - model.downloadProgress.status = custom.ModelManagerSP.DownloadStatus.downloading - model.downloadProgress.progress = progress - model.downloadProgress.eta = self._calculate_eta(model.fileName, progress) - self._report_status() - - # Clean up start time after download completes - del self._download_start_times[model.fileName] - - async def _process_artifact(self, artifact, destination_path: str) -> None: - """Processes a single model download including verification""" - if not artifact.downloadUri.uri: - return None - - url = artifact.downloadUri.uri - expected_hash = artifact.downloadUri.sha256 - filename = artifact.fileName - full_path = os.path.join(destination_path, filename) - - try: - # Check existing file - if os.path.exists(full_path) and await verify_file(full_path, expected_hash): - artifact.downloadProgress.status = custom.ModelManagerSP.DownloadStatus.cached - artifact.downloadProgress.progress = 100 - artifact.downloadProgress.eta = 0 - self._report_status() - return - - # Download and verify - await self._download_file(url, full_path, artifact) - if not await verify_file(full_path, expected_hash): - raise ValueError(f"Hash validation failed for {filename}") - - artifact.downloadProgress.status = custom.ModelManagerSP.DownloadStatus.downloaded - artifact.downloadProgress.eta = 0 - self._report_status() - - except Exception as e: - cloudlog.error(f"Error downloading {filename}: {str(e)}") - if os.path.exists(full_path): - os.remove(full_path) - artifact.downloadProgress.status = custom.ModelManagerSP.DownloadStatus.failed - artifact.downloadProgress.eta = 0 - self.selected_bundle.status = custom.ModelManagerSP.DownloadStatus.failed - self._report_status() - # Clean up start time if it exists - self._download_start_times.pop(artifact.fileName, None) - raise - - async def _process_model(self, model, destination_path: str) -> None: - """Processes a single model download including verification""" - model_artifact = model.artifact - metadata_artifact = model.metadata - - await self._process_artifact(metadata_artifact, destination_path) - await self._process_artifact(model_artifact, destination_path) - - def _report_status(self) -> None: - """Reports current status through messaging system""" - msg = messaging.new_message('modelManagerSP', valid=True) - model_manager_state = msg.modelManagerSP - if self.selected_bundle: - model_manager_state.selectedBundle = self.selected_bundle - - if self.active_bundle: - model_manager_state.activeBundle = self.active_bundle - - model_manager_state.availableBundles = self.available_models - self.pm.send('modelManagerSP', msg) - - async def _download_bundle(self, model_bundle: custom.ModelManagerSP.ModelBundle, destination_path: str) -> None: - """Downloads all models in a bundle""" - self.selected_bundle = model_bundle - self.selected_bundle.status = custom.ModelManagerSP.DownloadStatus.downloading - os.makedirs(destination_path, exist_ok=True) - - try: - tasks = [self._process_model(model, destination_path) for model in self.selected_bundle.models] - await asyncio.gather(*tasks) - self.active_bundle = self.selected_bundle - self.active_bundle.status = custom.ModelManagerSP.DownloadStatus.downloaded - self.params.put("ModelManager_ActiveBundle", json.dumps(self.active_bundle.to_dict())) - self.selected_bundle = None - - except Exception: - self.selected_bundle.status = custom.ModelManagerSP.DownloadStatus.failed - raise - - finally: - self._report_status() - - def download(self, model_bundle: custom.ModelManagerSP.ModelBundle, destination_path: str) -> None: - """Main entry point for downloading a model bundle""" - asyncio.run(self._download_bundle(model_bundle, destination_path)) - - def main_thread(self) -> None: - """Main thread for model management""" - rk = Ratekeeper(1, print_delay_threshold=None) - - while True: - try: - self.available_models = self.model_fetcher.get_available_bundles() - self.active_bundle = get_active_bundle(self.params) - - if index_to_download := self.params.get("ModelManager_DownloadIndex", block=False, encoding="utf-8"): - if model_to_download := next((model for model in self.available_models if model.index == int(index_to_download)), None): - try: - self.download(model_to_download, Paths.model_root()) - except Exception as e: - cloudlog.exception(e) - finally: - self.params.put("ModelManager_DownloadIndex", "") - - self._report_status() - rk.keep_time() - - except Exception as e: - cloudlog.exception(f"Error in main thread: {str(e)}") - rk.keep_time() - - -def main(): - ModelManagerSP().main_thread() - - -if __name__ == "__main__": - main() diff --git a/sunnypilot/models/modeld_lagd.py b/sunnypilot/models/modeld_lagd.py deleted file mode 100644 index 9e538123a8..0000000000 --- a/sunnypilot/models/modeld_lagd.py +++ /dev/null @@ -1,26 +0,0 @@ -""" -Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - -This file is part of sunnypilot and is licensed under the MIT License. -See the LICENSE.md file in the root directory for more details. -""" -from openpilot.common.params import Params -from openpilot.common.swaglog import cloudlog - - -class ModeldLagd: - def __init__(self): - self.params = Params() - - def lagd_main(self, CP, sm, model): - if self.params.get_bool("LagdToggle"): - lateral_delay = sm["liveDelay"].lateralDelay - lat_smooth = model.LAT_SMOOTH_SECONDS - result = lateral_delay + lat_smooth - cloudlog.debug(f"LAGD USING LIVE DELAY: {lateral_delay:.3f} + {lat_smooth:.3f} = {result:.3f}") - return result - steer_actuator_delay = CP.steerActuatorDelay - lat_smooth = model.LAT_SMOOTH_SECONDS - result = (steer_actuator_delay + 0.2) + lat_smooth - cloudlog.debug(f"LAGD USING STEER ACTUATOR: {steer_actuator_delay:.3f} + 0.2 + {lat_smooth:.3f} = {result:.3f}") - return result diff --git a/sunnypilot/models/runners/constants.py b/sunnypilot/models/runners/constants.py deleted file mode 100644 index cbd1fdb376..0000000000 --- a/sunnypilot/models/runners/constants.py +++ /dev/null @@ -1,18 +0,0 @@ -import os -import numpy as np -from openpilot.sunnypilot.modeld_v2.models.commonmodel_pyx import DrivingModelFrame, CLMem -from openpilot.system.hardware.hw import Paths -from cereal import custom - -# Type definitions for clarity -NumpyDict = dict[str, np.ndarray] -ShapeDict = dict[str, tuple[int, ...]] -SliceDict = dict[str, slice] -CLMemDict = dict[str, CLMem] -FrameDict = dict[str, DrivingModelFrame] - -ModelType = custom.ModelManagerSP.Model.Type -Model = custom.ModelManagerSP.Model - -SEND_RAW_PRED = os.getenv('SEND_RAW_PRED') -CUSTOM_MODEL_PATH = Paths.model_root() diff --git a/sunnypilot/models/runners/helpers.py b/sunnypilot/models/runners/helpers.py deleted file mode 100644 index 6a128b340e..0000000000 --- a/sunnypilot/models/runners/helpers.py +++ /dev/null @@ -1,35 +0,0 @@ -from openpilot.sunnypilot.models.helpers import get_active_bundle -from openpilot.sunnypilot.models.runners.model_runner import ModelRunner -from openpilot.sunnypilot.models.runners.tinygrad.tinygrad_runner import TinygradRunner, TinygradSplitRunner -from openpilot.sunnypilot.models.runners.constants import ModelType -from openpilot.system.hardware import TICI - -if not TICI: - from openpilot.sunnypilot.models.runners.onnx.onnx_runner import ONNXRunner - -def get_model_runner() -> ModelRunner: - """ - Factory function to create and return the appropriate ModelRunner instance. - - Selects between ONNXRunner (for non-TICI platforms) and TinygradRunner - (for TICI platforms), choosing TinygradSplitRunner if separate vision/policy - models are detected in the active bundle. - - :return: An instance of a ModelRunner subclass (ONNXRunner, TinygradRunner, or TinygradSplitRunner). - """ - if not TICI: - return ONNXRunner() - - # On TICI platforms, use Tinygrad runners - bundle = get_active_bundle() - if bundle and bundle.models: - model_types = {m.type.raw for m in bundle.models} - # Check if the bundle uses separate vision and policy models - if ModelType.vision in model_types or ModelType.policy in model_types: - return TinygradSplitRunner() - # Otherwise, assume a single model (likely supercombo) - if bundle.models: - return TinygradRunner(bundle.models[0].type.raw) - - # Default fallback to TinygradRunner with the supercombo type if bundle info is missing/incomplete - return TinygradRunner(ModelType.supercombo) diff --git a/sunnypilot/models/runners/onnx/onnx_runner.py b/sunnypilot/models/runners/onnx/onnx_runner.py deleted file mode 100644 index 1ffead4560..0000000000 --- a/sunnypilot/models/runners/onnx/onnx_runner.py +++ /dev/null @@ -1,62 +0,0 @@ -import numpy as np - -from openpilot.sunnypilot.modeld_v2 import MODEL_PATH -from openpilot.sunnypilot.modeld_v2.runners.ort_helpers import make_onnx_cpu_runner, ORT_TYPES_TO_NP_TYPES -from openpilot.sunnypilot.models.runners.constants import ModelType, ShapeDict, CLMemDict, NumpyDict, FrameDict -from openpilot.sunnypilot.models.runners.model_runner import ModelRunner -from openpilot.sunnypilot.modeld_v2.constants import ModelConstants - - -class ONNXRunner(ModelRunner): - """ - A ModelRunner implementation for executing ONNX models using ONNX Runtime CPU. - - Handles loading the ONNX model, preparing inputs as numpy arrays, running - inference, and parsing outputs. This runner is typically used on non-TICI platforms. - """ - def __init__(self): - super().__init__() - # Initialize ONNX Runtime session for the model at MODEL_PATH - self.runner = make_onnx_cpu_runner(MODEL_PATH) - # Map expected input names to numpy dtypes - self.input_to_nptype = { - model_input.name: ORT_TYPES_TO_NP_TYPES[model_input.type] - for model_input in self.runner.get_inputs() - } - # For ONNX, _model_data isn't strictly necessary as shapes/types come from the runner - # However, we might still need output_slices if custom models define them. - # We assume supercombo type for potentially loading output_slices metadata if available. - self._model_data = self.models.get(ModelType.supercombo) - self._constants = ModelConstants # Constants for ONNX models, if needed - - @property - def input_shapes(self) -> ShapeDict: - """Returns the input shapes defined in the ONNX model.""" - # ONNX shapes are derived directly from the model definition via the runner - return {runner_input.name: runner_input.shape for runner_input in self.runner.get_inputs()} - - def prepare_inputs(self, imgs_cl: CLMemDict, numpy_inputs: NumpyDict, frames: FrameDict) -> dict: - """Prepares inputs for the ONNX model as numpy arrays.""" - self.inputs = numpy_inputs # Start with non-image numpy inputs - # Convert image inputs from OpenCL buffers to numpy arrays - for key in imgs_cl: - buffer = frames[key].buffer_from_cl(imgs_cl[key]) - reshaped_buffer = buffer.reshape(self.input_shapes[key]) - self.inputs[key] = reshaped_buffer.astype(dtype=self.input_to_nptype[key]) - return self.inputs - - def _parse_outputs(self, model_outputs: np.ndarray) -> NumpyDict: - """Parses the raw ONNX model outputs using the standard Parser.""" - # Use slicing if metadata is available, otherwise pass raw outputs - if self._model_data is None: - raise ValueError("Model data is not available. Ensure the model is loaded correctly.") - - outputs_to_parse = self._slice_outputs(model_outputs) if self._model_data else {'raw_pred': model_outputs} - result: NumpyDict = self.parser_method_dict[self._model_data.model.type.raw](outputs_to_parse) - return result - - def _run_model(self) -> NumpyDict: - """Runs the ONNX model inference and parses the outputs.""" - # Execute the ONNX Runtime session - outputs = self.runner.run(None, self.inputs)[0].flatten() - return self._parse_outputs(outputs) diff --git a/sunnypilot/models/runners/tinygrad/model_types.py b/sunnypilot/models/runners/tinygrad/model_types.py deleted file mode 100644 index ba388aed93..0000000000 --- a/sunnypilot/models/runners/tinygrad/model_types.py +++ /dev/null @@ -1,59 +0,0 @@ -import os -from abc import ABC - -import numpy as np -from openpilot.sunnypilot.modeld_v2.parse_model_outputs import Parser as CombinedParser -from openpilot.sunnypilot.modeld_v2.parse_model_outputs_split import Parser as SplitParser -from openpilot.sunnypilot.models.runners.constants import ModelType, NumpyDict -from openpilot.sunnypilot.models.runners.model_runner import ModularRunner -from openpilot.system.hardware.hw import Paths - - -SEND_RAW_PRED = os.getenv('SEND_RAW_PRED') -CUSTOM_MODEL_PATH = Paths.model_root() - - -class PolicyTinygrad(ModularRunner, ABC): - """ - A TinygradRunner specialized for policy-only models. - - Uses a SplitParser to handle outputs specific to the policy part of a split model setup. - """ - def __init__(self): - self._policy_parser = SplitParser() - self.parser_method_dict[ModelType.policy] = self._parse_policy_outputs - - def _parse_policy_outputs(self, model_outputs: np.ndarray) -> NumpyDict: - """Parses policy model outputs using SplitParser.""" - result: NumpyDict = self._policy_parser.parse_policy_outputs(self._slice_outputs(model_outputs)) - return result - -class VisionTinygrad(ModularRunner, ABC): - """ - A TinygradRunner specialized for vision-only models. - - Uses a SplitParser to handle outputs specific to the vision part of a split model setup. - """ - def __init__(self): - self._vision_parser = SplitParser() - self.parser_method_dict[ModelType.vision] = self._parse_vision_outputs - - def _parse_vision_outputs(self, model_outputs: np.ndarray) -> NumpyDict: - """Parses vision model outputs using SplitParser.""" - result: NumpyDict = self._vision_parser.parse_vision_outputs(self._slice_outputs(model_outputs)) - return result - -class SupercomboTinygrad(ModularRunner, ABC): - """ - A TinygradRunner specialized for vision-only models. - - Uses a SplitParser to handle outputs specific to the vision part of a split model setup. - """ - def __init__(self): - self._supercombo_parser = CombinedParser() - self.parser_method_dict[ModelType.supercombo] = self._parse_supercombo_outputs - - def _parse_supercombo_outputs(self, model_outputs: np.ndarray) -> NumpyDict: - """Parses vision model outputs using SplitParser.""" - result: NumpyDict = self._supercombo_parser.parse_outputs(self._slice_outputs(model_outputs)) - return result diff --git a/sunnypilot/models/runners/tinygrad/tinygrad_runner.py b/sunnypilot/models/runners/tinygrad/tinygrad_runner.py deleted file mode 100644 index 270890cace..0000000000 --- a/sunnypilot/models/runners/tinygrad/tinygrad_runner.py +++ /dev/null @@ -1,139 +0,0 @@ -import pickle - -import numpy as np -from openpilot.sunnypilot.modeld_v2.runners.tinygrad_helpers import qcom_tensor_from_opencl_address -from openpilot.sunnypilot.models.runners.constants import CLMemDict, FrameDict, NumpyDict, ModelType, ShapeDict, CUSTOM_MODEL_PATH, SliceDict -from openpilot.sunnypilot.models.runners.model_runner import ModelRunner -from openpilot.sunnypilot.models.runners.tinygrad.model_types import PolicyTinygrad, VisionTinygrad, SupercomboTinygrad -from openpilot.system.hardware import TICI -from openpilot.sunnypilot.models.split_model_constants import SplitModelConstants -from openpilot.sunnypilot.modeld_v2.constants import ModelConstants - -from tinygrad.tensor import Tensor - - -class TinygradRunner(ModelRunner, SupercomboTinygrad, PolicyTinygrad, VisionTinygrad): - """ - A ModelRunner implementation for executing Tinygrad models. - - Handles loading Tinygrad model artifacts (.pkl), preparing inputs as Tinygrad - Tensors (potentially using QCOM extensions on TICI), running inference, - and parsing the outputs. - - :param model_type: The type of model (e.g., supercombo) to load and run. - """ - def __init__(self, model_type: int = ModelType.supercombo): - ModelRunner.__init__(self) - SupercomboTinygrad.__init__(self) - PolicyTinygrad.__init__(self) - VisionTinygrad.__init__(self) - self._constants = ModelConstants - self._model_data = self.models.get(model_type) - if not self._model_data or not self._model_data.model: - raise ValueError(f"Model data for type {model_type} not available.") - - artifact_filename = self._model_data.model.artifact.fileName - assert artifact_filename.endswith('_tinygrad.pkl'), \ - f"Invalid model file {artifact_filename} for TinygradRunner" - - model_pkl_path = f"{CUSTOM_MODEL_PATH}/{artifact_filename}" - with open(model_pkl_path, "rb") as f: - try: - # Load the compiled Tinygrad model runner function - self.model_run = pickle.load(f) - except FileNotFoundError as e: - # Provide a helpful error message if the model was built for a different platform - assert "/dev/kgsl-3d0" not in str(e), "Model was built on C3 or C3X, but is being loaded on PC" - raise - - # Map input names to their required dtype and device from the loaded model - self.input_to_dtype = {} - self.input_to_device = {} - for idx, name in enumerate(self.model_run.captured.expected_names): - info = self.model_run.captured.expected_st_vars_dtype_device[idx] - self.input_to_dtype[name] = info[2] # dtype - self.input_to_device[name] = info[3] # device - - @property - def vision_input_names(self) -> list[str]: - """Returns the list of vision input names from the input shapes.""" - return [name for name in self.input_shapes.keys() if 'img' in name] - - def prepare_vision_inputs(self, imgs_cl: CLMemDict, frames: FrameDict): - """Prepares vision (image) inputs as Tinygrad Tensors.""" - for key in imgs_cl: - if TICI and key not in self.inputs: - # On TICI, directly use OpenCL memory address for efficiency via QCOM extensions - self.inputs[key] = qcom_tensor_from_opencl_address(imgs_cl[key].mem_address, self.input_shapes[key], dtype=self.input_to_dtype[key]) - elif not TICI: - # On other platforms, copy data from CL buffer to a numpy array first - shape = frames[key].buffer_from_cl(imgs_cl[key]).reshape(self.input_shapes[key]) - self.inputs[key] = Tensor(shape, device=self.input_to_device[key], dtype=self.input_to_dtype[key]).realize() - - def prepare_policy_inputs(self, numpy_inputs: NumpyDict): - """Prepares non-image (policy) inputs as Tinygrad Tensors.""" - for key, value in numpy_inputs.items(): - self.inputs[key] = Tensor(value, device=self.input_to_device[key], dtype=self.input_to_dtype[key]).realize() - - def prepare_inputs(self, imgs_cl: CLMemDict, numpy_inputs: NumpyDict, frames: FrameDict) -> dict: - """Prepares all vision and policy inputs for the model.""" - self.prepare_vision_inputs(imgs_cl, frames) - self.prepare_policy_inputs(numpy_inputs) - return self.inputs - - def _run_model(self) -> NumpyDict: - """Runs the Tinygrad model inference and parses the outputs.""" - outputs = self.model_run(**self.inputs).numpy().flatten() - return self._parse_outputs(outputs) - - def _parse_outputs(self, model_outputs: np.ndarray) -> NumpyDict: - """Parses the raw model outputs using the standard Parser.""" - if self._model_data is None: - raise ValueError("Model data is not available. Ensure the model is loaded correctly.") - - result: NumpyDict = self.parser_method_dict[self._model_data.model.type.raw](model_outputs) - return result - - -class TinygradSplitRunner(ModelRunner): - """ - A ModelRunner that coordinates separate TinygradVisionRunner and TinygradPolicyRunner instances. - - Manages the execution of split vision and policy models, combining their inputs and outputs. - """ - def __init__(self): - super().__init__() - self.is_20hz_3d = True - self.vision_runner = TinygradRunner(ModelType.vision) - self.policy_runner = TinygradRunner(ModelType.policy) - self._constants = SplitModelConstants - - def _run_model(self) -> NumpyDict: - """Runs both vision and policy models and merges their parsed outputs.""" - policy_output = self.policy_runner.run_model() - vision_output = self.vision_runner.run_model() - return {**policy_output, **vision_output} # Combine results - - @property - def vision_input_names(self) -> list[str]: - """Returns the list of vision input names from the vision runner.""" - return list(self.vision_runner.vision_input_names) - - @property - def input_shapes(self) -> ShapeDict: - """Returns the combined input shapes from both vision and policy models.""" - return {**self.policy_runner.input_shapes, **self.vision_runner.input_shapes} - - @property - def output_slices(self) -> SliceDict: - """Returns the combined output slices from both vision and policy models.""" - return {**self.policy_runner.output_slices, **self.vision_runner.output_slices} - - def prepare_inputs(self, imgs_cl: CLMemDict, numpy_inputs: NumpyDict, frames: FrameDict) -> dict: - """Prepares inputs for both vision and policy models.""" - # Policy inputs only depend on numpy_inputs - self.policy_runner.prepare_policy_inputs(numpy_inputs) - # Vision inputs depend on imgs_cl and frames - self.vision_runner.prepare_vision_inputs(imgs_cl, frames) - # Return combined inputs (though they are stored within respective runners) - return {**self.policy_runner.inputs, **self.vision_runner.inputs} diff --git a/sunnypilot/models/tests/model_hash b/sunnypilot/models/tests/model_hash deleted file mode 100644 index f65c628164..0000000000 --- a/sunnypilot/models/tests/model_hash +++ /dev/null @@ -1 +0,0 @@ -71979b29c4bab3007de1a4265442d79f44c0eaef066af66086dddfc432709b94 \ No newline at end of file diff --git a/sunnypilot/models/tests/test_default_model.py b/sunnypilot/models/tests/test_default_model.py deleted file mode 100644 index 5067dbaf46..0000000000 --- a/sunnypilot/models/tests/test_default_model.py +++ /dev/null @@ -1,15 +0,0 @@ -from openpilot.sunnypilot.models.default_model import get_file_hash, MODEL_HASH_PATH, VISION_ONNX_PATH, POLICY_ONNX_PATH -import hashlib - - -class TestDefaultModel: - def test_compare_onnx_hashes(self): - vision_hash = get_file_hash(VISION_ONNX_PATH) - policy_hash = get_file_hash(POLICY_ONNX_PATH) - - combined_hash = hashlib.sha256((vision_hash + policy_hash).encode()).hexdigest() - - with open(MODEL_HASH_PATH) as f: - current_hash = f.read().strip() - - assert combined_hash == current_hash, "Run sunnypilot/models/default_model.py to update the default model name and hash" diff --git a/sunnypilot/navd/helpers.py b/sunnypilot/navd/helpers.py deleted file mode 100644 index 85894fb2ab..0000000000 --- a/sunnypilot/navd/helpers.py +++ /dev/null @@ -1,189 +0,0 @@ -from __future__ import annotations - -import json -import math -import numpy as np -from typing import Any, cast - -from openpilot.common.conversions import Conversions -from openpilot.common.params import Params - -DIRECTIONS = ('left', 'right', 'straight') -MODIFIABLE_DIRECTIONS = ('left', 'right') - -EARTH_MEAN_RADIUS = 6371007.2 -SPEED_CONVERSIONS = { - 'km/h': Conversions.KPH_TO_MS, - 'mph': Conversions.MPH_TO_MS, -} - - -class Coordinate: - def __init__(self, latitude: float, longitude: float) -> None: - self.latitude = latitude - self.longitude = longitude - self.annotations: dict[str, float] = {} - - @classmethod - def from_mapbox_tuple(cls, t: tuple[float, float]) -> Coordinate: - return cls(t[1], t[0]) - - def as_dict(self) -> dict[str, float]: - return {'latitude': self.latitude, 'longitude': self.longitude} - - def __str__(self) -> str: - return f'Coordinate({self.latitude}, {self.longitude})' - - def __repr__(self) -> str: - return self.__str__() - - def __eq__(self, other) -> bool: - if not isinstance(other, Coordinate): - return False - return (self.latitude == other.latitude) and (self.longitude == other.longitude) - - def __sub__(self, other: Coordinate) -> Coordinate: - return Coordinate(self.latitude - other.latitude, self.longitude - other.longitude) - - def __add__(self, other: Coordinate) -> Coordinate: - return Coordinate(self.latitude + other.latitude, self.longitude + other.longitude) - - def __mul__(self, c: float) -> Coordinate: - return Coordinate(self.latitude * c, self.longitude * c) - - def dot(self, other: Coordinate) -> float: - return self.latitude * other.latitude + self.longitude * other.longitude - - def distance_to(self, other: Coordinate) -> float: - # Haversine formula - dlat = math.radians(other.latitude - self.latitude) - dlon = math.radians(other.longitude - self.longitude) - - haversine_dlat = math.sin(dlat / 2.0) - haversine_dlat *= haversine_dlat - haversine_dlon = math.sin(dlon / 2.0) - haversine_dlon *= haversine_dlon - - y = haversine_dlat \ - + math.cos(math.radians(self.latitude)) \ - * math.cos(math.radians(other.latitude)) \ - * haversine_dlon - x = 2 * math.asin(math.sqrt(y)) - return x * EARTH_MEAN_RADIUS - - -def minimum_distance(a: Coordinate, b: Coordinate, p: Coordinate): - if a.distance_to(b) < 0.01: - return a.distance_to(p) - - ap = p - a - ab = b - a - t = np.clip(ap.dot(ab) / ab.dot(ab), 0.0, 1.0) - projection = a + ab * t - return projection.distance_to(p) - - -def distance_along_geometry(geometry: list[Coordinate], pos: Coordinate) -> float: - if len(geometry) <= 2: - return geometry[0].distance_to(pos) - - # 1. Find segment that is closest to current position - # 2. Total distance is sum of distance to start of closest segment - # + all previous segments - total_distance = 0.0 - total_distance_closest = 0.0 - closest_distance = 1e9 - - for i in range(len(geometry) - 1): - d = minimum_distance(geometry[i], geometry[i + 1], pos) - - if d < closest_distance: - closest_distance = d - total_distance_closest = total_distance + geometry[i].distance_to(pos) - - total_distance += geometry[i].distance_to(geometry[i + 1]) - - return total_distance_closest - - -def coordinate_from_param(param: str, params: Params = None) -> Coordinate | None: - if params is None: - params = Params() - - json_str = params.get(param) - if json_str is None: - return None - - pos = json.loads(json_str) - if 'latitude' not in pos or 'longitude' not in pos: - return None - - return Coordinate(pos['latitude'], pos['longitude']) - - -def string_to_direction(direction: str) -> str: - for d in DIRECTIONS: - if d in direction: - if 'slight' in direction and d in MODIFIABLE_DIRECTIONS: - return 'slight' + d.capitalize() - return d - return 'none' - - -def maxspeed_to_ms(maxspeed: dict[str, str | float]) -> float: - unit = cast(str, maxspeed['unit']) - speed = cast(float, maxspeed['speed']) - return SPEED_CONVERSIONS[unit] * speed - - -def field_valid(dat: dict, field: str) -> bool: - return field in dat and dat[field] is not None - - -def parse_banner_instructions(banners: Any, distance_to_maneuver: float = 0.0) -> dict[str, Any] | None: - if not len(banners): - return None - - instruction = {} - - # A segment can contain multiple banners, find one that we need to show now - current_banner = banners[0] - for banner in banners: - if distance_to_maneuver < banner['distanceAlongGeometry']: - current_banner = banner - - # Only show banner when close enough to maneuver - instruction['showFull'] = distance_to_maneuver < current_banner['distanceAlongGeometry'] - - # Primary - p = current_banner['primary'] - if field_valid(p, 'text'): - instruction['maneuverPrimaryText'] = p['text'] - if field_valid(p, 'type'): - instruction['maneuverType'] = p['type'] - if field_valid(p, 'modifier'): - instruction['maneuverModifier'] = p['modifier'] - - # Secondary - if field_valid(current_banner, 'secondary'): - instruction['maneuverSecondaryText'] = current_banner['secondary']['text'] - - # Lane lines - if field_valid(current_banner, 'sub'): - lanes = [] - for component in current_banner['sub']['components']: - if component['type'] != 'lane': - continue - - lane = { - 'active': component['active'], - 'directions': [string_to_direction(d) for d in component['directions']], - } - - if field_valid(component, 'active_direction'): - lane['activeDirection'] = string_to_direction(component['active_direction']) - - lanes.append(lane) - instruction['lanes'] = lanes - - return instruction diff --git a/sunnypilot/neural_network_data b/sunnypilot/neural_network_data deleted file mode 160000 index b59ab483c8..0000000000 --- a/sunnypilot/neural_network_data +++ /dev/null @@ -1 +0,0 @@ -Subproject commit b59ab483c86cd70d04de91ad878024cd66fe86b6 diff --git a/sunnypilot/selfdrive/car/car_list.json b/sunnypilot/selfdrive/car/car_list.json deleted file mode 120000 index a4ae7b75f9..0000000000 --- a/sunnypilot/selfdrive/car/car_list.json +++ /dev/null @@ -1 +0,0 @@ -../../../opendbc_repo/opendbc/sunnypilot/car/car_list.json \ No newline at end of file diff --git a/sunnypilot/selfdrive/car/car_specific.py b/sunnypilot/selfdrive/car/car_specific.py deleted file mode 100644 index 7e6f300d73..0000000000 --- a/sunnypilot/selfdrive/car/car_specific.py +++ /dev/null @@ -1,45 +0,0 @@ -""" -Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - -This file is part of sunnypilot and is licensed under the MIT License. -See the LICENSE.md file in the root directory for more details. -""" - -from cereal import log, custom -from opendbc.car import structs - -from opendbc.car.chrysler.values import RAM_DT -from openpilot.selfdrive.selfdrived.events import Events -from openpilot.sunnypilot.selfdrive.selfdrived.events import EventsSP - -EventName = log.OnroadEvent.EventName -EventNameSP = custom.OnroadEventSP.EventName -GearShifter = structs.CarState.GearShifter - - -class CarSpecificEventsSP: - def __init__(self, CP: structs.CarParams, params): - self.CP = CP - self.params = params - - self.low_speed_alert = False - - def update(self, CS: structs.CarState, events: Events): - events_sp = EventsSP() - - if self.CP.brand == 'chrysler': - if self.CP.carFingerprint in RAM_DT: - # remove belowSteerSpeed event from CarSpecificEvents as RAM_DT uses a different logic - if events.has(EventName.belowSteerSpeed): - events.remove(EventName.belowSteerSpeed) - - # TODO-SP: use if/elif to have the gear shifter condition takes precedence over the speed condition - # TODO-SP: add 1 m/s hysteresis - if CS.vEgo >= self.CP.minEnableSpeed: - self.low_speed_alert = False - if CS.gearShifter != GearShifter.drive: - self.low_speed_alert = True - if self.low_speed_alert: - events.add(EventName.belowSteerSpeed) - - return events_sp diff --git a/sunnypilot/selfdrive/car/cruise_ext.py b/sunnypilot/selfdrive/car/cruise_ext.py deleted file mode 100644 index 6f0419ed14..0000000000 --- a/sunnypilot/selfdrive/car/cruise_ext.py +++ /dev/null @@ -1,47 +0,0 @@ -""" -Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - -This file is part of sunnypilot and is licensed under the MIT License. -See the LICENSE.md file in the root directory for more details. -""" -import numpy as np - -from cereal import car -from openpilot.common.params import Params - -ButtonType = car.CarState.ButtonEvent.Type - - -class VCruiseHelperSP: - def __init__(self) -> None: - self.params = Params() - - self.custom_acc_enabled = self.params.get_bool("CustomAccIncrementsEnabled") - self.short_increment = self.read_int_param("CustomAccShortPressIncrement", 1) - self.long_increment = self.read_int_param("CustomAccLongPressIncrement", 5) - - def read_int_param(self, key: str, default: int = 0) -> int: - try: - return int(self.params.get(key, encoding='utf8')) - except (ValueError, TypeError): - return default - - def read_custom_set_speed_params(self) -> None: - self.custom_acc_enabled = self.params.get_bool("CustomAccIncrementsEnabled") - self.short_increment = self.read_int_param("CustomAccShortPressIncrement", 1) - self.long_increment = self.read_int_param("CustomAccLongPressIncrement", 5) - - def update_v_cruise_delta(self, long_press: bool, v_cruise_delta: float) -> tuple[bool, float]: - if not self.custom_acc_enabled: - v_cruise_delta = v_cruise_delta * (5 if long_press else 1) - return long_press, v_cruise_delta - - # Apply user-specified multipliers to the base increment - short_increment = np.clip(self.short_increment, 1, 10) - long_increment = np.clip(self.long_increment, 1, 10) - - actual_increment = long_increment if long_press else short_increment - round_to_nearest = actual_increment in (5, 10) - v_cruise_delta = v_cruise_delta * actual_increment - - return round_to_nearest, v_cruise_delta diff --git a/sunnypilot/selfdrive/car/interfaces.py b/sunnypilot/selfdrive/car/interfaces.py deleted file mode 100644 index e2a232a3ef..0000000000 --- a/sunnypilot/selfdrive/car/interfaces.py +++ /dev/null @@ -1,68 +0,0 @@ -""" -Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - -This file is part of sunnypilot and is licensed under the MIT License. -See the LICENSE.md file in the root directory for more details. -""" - -from opendbc.car import structs -from opendbc.car.interfaces import CarInterfaceBase -from opendbc.sunnypilot.car.hyundai.longitudinal.helpers import LongitudinalTuningType -from opendbc.sunnypilot.car.hyundai.values import HyundaiFlagsSP -from openpilot.common.params import Params -from openpilot.common.swaglog import cloudlog -from openpilot.sunnypilot.selfdrive.controls.lib.nnlc.helpers import get_nn_model_path - -import openpilot.system.sentry as sentry - - -def log_fingerprint(CP: structs.CarParams) -> None: - if CP.carFingerprint == "MOCK": - sentry.capture_fingerprint_mock() - else: - sentry.capture_fingerprint(CP.carFingerprint, CP.brand) - - -def _initialize_custom_longitudinal_tuning(CI: CarInterfaceBase, CP: structs.CarParams, CP_SP: structs.CarParamsSP, - params: Params = None) -> None: - if params is None: - params = Params() - - # Hyundai Custom Longitudinal Tuning - if CP.brand == 'hyundai': - hyundai_longitudinal_tuning = int(params.get("HyundaiLongitudinalTuning", encoding="utf8") or 0) - if hyundai_longitudinal_tuning == LongitudinalTuningType.DYNAMIC: - CP_SP.flags |= HyundaiFlagsSP.LONG_TUNING_DYNAMIC.value - if hyundai_longitudinal_tuning == LongitudinalTuningType.PREDICTIVE: - CP_SP.flags |= HyundaiFlagsSP.LONG_TUNING_PREDICTIVE.value - - CP_SP = CI.get_longitudinal_tuning_sp(CP, CP_SP) - - -def _initialize_neural_network_lateral_control(CI: CarInterfaceBase, CP: structs.CarParams, CP_SP: structs.CarParamsSP, - params: Params = None, enabled: bool = False) -> None: - if params is None: - params = Params() - - nnlc_model_path, nnlc_model_name, exact_match = get_nn_model_path(CP) - - if nnlc_model_name == "MOCK": - cloudlog.error({"nnlc event": "car doesn't match any Neural Network model"}) - - if nnlc_model_name != "MOCK" and CP.steerControlType != structs.CarParams.SteerControlType.angle: - enabled = params.get_bool("NeuralNetworkLateralControl") - - if enabled: - CI.configure_torque_tune(CP.carFingerprint, CP.lateralTuning) - - CP_SP.neuralNetworkLateralControl.model.path = nnlc_model_path - CP_SP.neuralNetworkLateralControl.model.name = nnlc_model_name - CP_SP.neuralNetworkLateralControl.fuzzyFingerprint = not exact_match - - -def setup_interfaces(CI: CarInterfaceBase, params: Params = None) -> None: - CP = CI.CP - CP_SP = CI.CP_SP - - _initialize_custom_longitudinal_tuning(CI, CP, CP_SP, params) - _initialize_neural_network_lateral_control(CI, CP, CP_SP, params) diff --git a/sunnypilot/selfdrive/controls/controlsd_ext.py b/sunnypilot/selfdrive/controls/controlsd_ext.py deleted file mode 100644 index 9a7f0cb5fc..0000000000 --- a/sunnypilot/selfdrive/controls/controlsd_ext.py +++ /dev/null @@ -1,67 +0,0 @@ -""" -Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - -This file is part of sunnypilot and is licensed under the MIT License. -See the LICENSE.md file in the root directory for more details. -""" -import cereal.messaging as messaging -from cereal import custom - -from opendbc.car import structs -from openpilot.common.params import Params -from openpilot.common.swaglog import cloudlog -from openpilot.sunnypilot.selfdrive.controls.lib.param_store import ParamStore -from openpilot.sunnypilot.selfdrive.controls.lib.blinker_pause_lateral import BlinkerPauseLateral - - -class ControlsExt: - def __init__(self, CP: structs.CarParams, params: Params): - self.CP = CP - self.params = params - self.blinker_pause_lateral = BlinkerPauseLateral() - self.param_store = ParamStore(self.CP) - self.get_params_sp() - - cloudlog.info("controlsd_ext is waiting for CarParamsSP") - self.CP_SP = messaging.log_from_bytes(params.get("CarParamsSP", block=True), custom.CarParamsSP) - cloudlog.info("controlsd_ext got CarParamsSP") - - self.sm_services_ext = ['selfdriveStateSP'] - self.pm_services_ext = ['carControlSP'] - - def get_params_sp(self) -> None: - self.param_store.update(self.params) - self.blinker_pause_lateral.get_params() - - def get_lat_active(self, sm: messaging.SubMaster) -> bool: - if self.blinker_pause_lateral.update(sm['carState']): - return False - - ss_sp = sm['selfdriveStateSP'] - if ss_sp.mads.available: - return bool(ss_sp.mads.active) - - # MADS not available, use stock state to engage - return bool(sm['selfdriveState'].active) - - def state_control_ext(self, sm: messaging.SubMaster) -> custom.CarControlSP: - CC_SP = custom.CarControlSP.new_message() - - # MADS state - CC_SP.mads = sm['selfdriveStateSP'].mads - - CC_SP.params = self.param_store.publish() - - return CC_SP - - @staticmethod - def publish_ext(CC_SP: custom.CarControlSP, sm: messaging.SubMaster, pm: messaging.PubMaster) -> None: - cc_sp_send = messaging.new_message('carControlSP') - cc_sp_send.valid = sm['carState'].canValid - cc_sp_send.carControlSP = CC_SP - - pm.send('carControlSP', cc_sp_send) - - def run_ext(self, sm: messaging.SubMaster, pm: messaging.PubMaster) -> None: - CC_SP = self.state_control_ext(sm) - self.publish_ext(CC_SP, sm, pm) diff --git a/sunnypilot/selfdrive/controls/lib/blinker_pause_lateral.py b/sunnypilot/selfdrive/controls/lib/blinker_pause_lateral.py deleted file mode 100644 index fb86280358..0000000000 --- a/sunnypilot/selfdrive/controls/lib/blinker_pause_lateral.py +++ /dev/null @@ -1,34 +0,0 @@ -""" -Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - -This file is part of sunnypilot and is licensed under the MIT License. -See the LICENSE.md file in the root directory for more details. -""" -from cereal import car - -from openpilot.common.conversions import Conversions as CV -from openpilot.common.params import Params - - -class BlinkerPauseLateral: - def __init__(self): - self.params = Params() - - self.enabled = self.params.get_bool("BlinkerPauseLateralControl") - self.is_metric = self.params.get_bool("IsMetric") - self.min_speed = 0 - - def get_params(self) -> None: - self.enabled = self.params.get_bool("BlinkerPauseLateralControl") - self.is_metric = self.params.get_bool("IsMetric") - self.min_speed = int(self.params.get("BlinkerMinLateralControlSpeed", encoding='utf8')) - - def update(self, CS: car.CarState) -> bool: - if not self.enabled: - return False - - one_blinker = CS.leftBlinker != CS.rightBlinker - speed_factor = CV.KPH_TO_MS if self.is_metric else CV.MPH_TO_MS - min_speed_ms = self.min_speed * speed_factor - - return bool(one_blinker and CS.vEgo < min_speed_ms) diff --git a/sunnypilot/selfdrive/controls/lib/dec/constants.py b/sunnypilot/selfdrive/controls/lib/dec/constants.py deleted file mode 100644 index 48f4203e93..0000000000 --- a/sunnypilot/selfdrive/controls/lib/dec/constants.py +++ /dev/null @@ -1,25 +0,0 @@ -class WMACConstants: - LEAD_WINDOW_SIZE = 5 - LEAD_PROB = 0.5 - - SLOW_DOWN_WINDOW_SIZE = 5 - SLOW_DOWN_PROB = 0.6 - - SLOW_DOWN_BP = [0., 10., 20., 30., 40., 50., 55., 60.] - SLOW_DOWN_DIST = [25., 38., 55., 75., 95., 115., 130., 150.] - - SLOWNESS_WINDOW_SIZE = 12 - SLOWNESS_PROB = 0.5 - SLOWNESS_CRUISE_OFFSET = 1.05 - - DANGEROUS_TTC_WINDOW_SIZE = 3 - DANGEROUS_TTC = 2.3 - - MPC_FCW_WINDOW_SIZE = 10 - MPC_FCW_PROB = 0.5 - - -class SNG_State: - off = 0 - stopped = 1 - going = 2 diff --git a/sunnypilot/selfdrive/controls/lib/dec/dec.py b/sunnypilot/selfdrive/controls/lib/dec/dec.py deleted file mode 100644 index 812e5cc15f..0000000000 --- a/sunnypilot/selfdrive/controls/lib/dec/dec.py +++ /dev/null @@ -1,390 +0,0 @@ -# The MIT License -# -# Copyright (c) 2019-, Rick Lan, dragonpilot community, and a number of other of contributors. -# -# 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. -# -# Version = 2025-1-18 - -import numpy as np - -from cereal import messaging -from opendbc.car import structs -from numpy import interp -from openpilot.common.params import Params -from openpilot.common.realtime import DT_MDL -from openpilot.sunnypilot.selfdrive.controls.lib.dec.constants import WMACConstants, SNG_State - -# d-e2e, from modeldata.h -TRAJECTORY_SIZE = 33 - -HIGHWAY_CRUISE_KPH = 70 - -STOP_AND_GO_FRAME = 60 - -SET_MODE_TIMEOUT = 10 - -V_ACC_MIN = 9.72 - - -class GenericMovingAverageCalculator: - def __init__(self, window_size): - self.window_size = window_size - self.data = [] - self.total = 0 - - def add_data(self, value: float) -> None: - if len(self.data) == self.window_size: - self.total -= self.data.pop(0) - self.data.append(value) - self.total += value - - def get_moving_average(self) -> float | None: - return None if len(self.data) == 0 else self.total / len(self.data) - - def reset_data(self) -> None: - self.data = [] - self.total = 0 - - -class WeightedMovingAverageCalculator: - def __init__(self, window_size): - self.window_size = window_size - self.data = [] - self.weights = np.linspace(1, 3, window_size) # Linear weights, adjust as needed - - def add_data(self, value: float) -> None: - if len(self.data) == self.window_size: - self.data.pop(0) - self.data.append(value) - - def get_weighted_average(self) -> float | None: - if len(self.data) == 0: - return None - weighted_sum: float = float(np.dot(self.data, self.weights[-len(self.data):])) - weight_total: float = float(np.sum(self.weights[-len(self.data):])) - return weighted_sum / weight_total - - def reset_data(self) -> None: - self.data = [] - - -class DynamicExperimentalController: - def __init__(self, CP: structs.CarParams, mpc, params=None): - self._CP = CP - self._mpc = mpc - self._params = params or Params() - self._enabled: bool = self._params.get_bool("DynamicExperimentalControl") - self._active: bool = False - self._mode: str = 'acc' - self._frame: int = 0 - - # Use weighted moving average for filtering leads - self._lead_gmac = WeightedMovingAverageCalculator(window_size=WMACConstants.LEAD_WINDOW_SIZE) - self._has_lead_filtered = False - self._has_lead_filtered_prev = False - - self._slow_down_gmac = WeightedMovingAverageCalculator(window_size=WMACConstants.SLOW_DOWN_WINDOW_SIZE) - self._has_slow_down: bool = False - self._slow_down_confidence: float = 0.0 - - self._has_blinkers = False - - self._slowness_gmac = WeightedMovingAverageCalculator(window_size=WMACConstants.SLOWNESS_WINDOW_SIZE) - self._has_slowness: bool = False - - self._has_nav_instruction = False - - self._dangerous_ttc_gmac = WeightedMovingAverageCalculator(window_size=WMACConstants.DANGEROUS_TTC_WINDOW_SIZE) - self._has_dangerous_ttc: bool = False - - self._v_ego_kph = 0. - self._v_cruise_kph = 0. - - self._has_lead = False - - self._has_standstill = False - self._has_standstill_prev = False - - self._sng_transit_frame = 0 - self._sng_state = SNG_State.off - - self._mpc_fcw_gmac = WeightedMovingAverageCalculator(window_size=WMACConstants.MPC_FCW_WINDOW_SIZE) - self._has_mpc_fcw: bool = False - self._mpc_fcw_crash_cnt = 0 - - self._set_mode_timeout = 0 - - def _read_params(self) -> None: - if self._frame % int(1. / DT_MDL) == 0: - self._enabled = self._params.get_bool("DynamicExperimentalControl") - - def mode(self) -> str: - return str(self._mode) - - def enabled(self) -> bool: - return self._enabled - - def active(self) -> bool: - return self._active - - @staticmethod - def _anomaly_detection(recent_data: list[float], threshold: float = 2.0, context_check: bool = True) -> bool: - """ - Basic anomaly detection using standard deviation. - """ - if len(recent_data) < 5: - return False - mean: float = float(np.mean(recent_data)) - std_dev: float = float(np.std(recent_data)) - anomaly: bool = bool(recent_data[-1] > mean + threshold * std_dev) - - # Context check to ensure repeated anomaly - if context_check: - return np.count_nonzero(np.array(recent_data) > mean + threshold * std_dev) > 1 - return anomaly - - def _adaptive_slowdown_threshold(self) -> float: - """ - Adapts the slow-down threshold based on vehicle speed and recent behavior. - """ - slowdown_scaling_factor: float = (1.0 + 0.03 * np.log(1 + len(self._slow_down_gmac.data))) - adaptive_threshold: float = float( - interp(self._v_ego_kph, WMACConstants.SLOW_DOWN_BP, WMACConstants.SLOW_DOWN_DIST) * slowdown_scaling_factor - ) - return adaptive_threshold - - def _smoothed_lead_detection(self, lead_prob: float, smoothing_factor: float = 0.2): - """ - Smoothing the lead detection to avoid erratic behavior. - """ - lead_filtering: float = (1 - smoothing_factor) * self._has_lead_filtered + smoothing_factor * lead_prob - return lead_filtering > WMACConstants.LEAD_PROB - - def _adaptive_lead_prob_threshold(self) -> float: - """ - Adapts lead probability threshold based on driving conditions. - """ - if self._v_ego_kph > HIGHWAY_CRUISE_KPH: - return float(WMACConstants.LEAD_PROB + 0.1) # Increase the threshold on highways - return float(WMACConstants.LEAD_PROB) - - def _update_calculations(self, sm: messaging.SubMaster) -> None: - car_state = sm['carState'] - lead_one = sm['radarState'].leadOne - md = sm['modelV2'] - - self._v_ego_kph = car_state.vEgo * 3.6 - self._v_cruise_kph = car_state.vCruise - self._has_lead = lead_one.status - self._has_standstill = car_state.standstill - - # fcw detection - self._mpc_fcw_gmac.add_data(self._mpc_fcw_crash_cnt > 0) - if _mpc_fcw_weighted_average := self._mpc_fcw_gmac.get_weighted_average(): - self._has_mpc_fcw = _mpc_fcw_weighted_average > WMACConstants.MPC_FCW_PROB - else: - self._has_mpc_fcw = False - - # nav enable detection - # self._has_nav_instruction = md.navEnabledDEPRECATED and maneuver_distance / max(car_state.vEgo, 1) < 13 - - # lead detection with smoothing - self._lead_gmac.add_data(lead_one.status) - self._has_lead_filtered = (self._lead_gmac.get_weighted_average() or -1.) > WMACConstants.LEAD_PROB - #lead_prob = self._lead_gmac.get_weighted_average() or 0 - #self._has_lead_filtered = self._smoothed_lead_detection(lead_prob) - - # adaptive slow down detection - adaptive_threshold = self._adaptive_slowdown_threshold() - slow_down_trigger = len(md.orientation.x) == len(md.position.x) == TRAJECTORY_SIZE and md.position.x[TRAJECTORY_SIZE - 1] < adaptive_threshold - self._slow_down_gmac.add_data(slow_down_trigger) - if _has_slow_down_weighted_average := self._slow_down_gmac.get_weighted_average(): - self._has_slow_down = _has_slow_down_weighted_average > WMACConstants.SLOW_DOWN_PROB - self._slow_down_confidence = _has_slow_down_weighted_average # Store confidence level - else: - self._has_slow_down = False - self._slow_down_confidence = 0.0 # No confidence if no slowdown - - # anomaly detection for slow down events - if self._anomaly_detection(self._slow_down_gmac.data): - self._slow_down_confidence *= 0.85 # Reduce confidence - self._has_slow_down = self._slow_down_confidence > WMACConstants.SLOW_DOWN_PROB - - # blinker detection - self._has_blinkers = car_state.leftBlinker or car_state.rightBlinker - - # sng detection - if self._has_standstill: - self._sng_state = SNG_State.stopped - self._sng_transit_frame = 0 - else: - if self._sng_transit_frame == 0: - if self._sng_state == SNG_State.stopped: - self._sng_state = SNG_State.going - self._sng_transit_frame = STOP_AND_GO_FRAME - elif self._sng_state == SNG_State.going: - self._sng_state = SNG_State.off - elif self._sng_transit_frame > 0: - self._sng_transit_frame -= 1 - - # slowness detection - if not self._has_standstill: - self._slowness_gmac.add_data(self._v_ego_kph <= (self._v_cruise_kph * WMACConstants.SLOWNESS_CRUISE_OFFSET)) - if _slowness_weighted_average := self._slowness_gmac.get_weighted_average(): - self._has_slowness = _slowness_weighted_average > WMACConstants.SLOWNESS_PROB - else: - self._has_slowness = False - - # dangerous TTC detection - if not self._has_lead_filtered and self._has_lead_filtered_prev: - self._dangerous_ttc_gmac.reset_data() - self._has_dangerous_ttc = False - - if self._has_lead and car_state.vEgo >= 0.01: - self._dangerous_ttc_gmac.add_data(lead_one.dRel / car_state.vEgo) - - if _dangerous_ttc_weighted_average := self._dangerous_ttc_gmac.get_weighted_average(): - self._has_dangerous_ttc = _dangerous_ttc_weighted_average <= WMACConstants.DANGEROUS_TTC - else: - self._has_dangerous_ttc = False - - # keep prev values - self._has_standstill_prev = self._has_standstill - self._has_lead_filtered_prev = self._has_lead_filtered - - def _radarless_mode(self) -> None: - # when mpc fcw crash prob is high - # use blended to slow down quickly - if self._has_mpc_fcw: - self._set_mode('blended') - return - - # Nav enabled and distance to upcoming turning is 300 or below - # if self._has_nav_instruction: - # self._set_mode('blended') - # return - - # when blinker is on and speed is driving below V_ACC_MIN: blended - # we don't want it to switch mode at higher speed, blended may trigger hard brake - # if self._has_blinkers and self._v_ego_kph < V_ACC_MIN: - # self._set_mode('blended') - # return - - # when at highway cruise and SNG: blended - # ensuring blended mode is used because acc is bad at catching SNG lead car - # especially those who accel very fast and then brake very hard. - # if self._sng_state == SNG_State.going and self._v_cruise_kph >= V_ACC_MIN: - # self._set_mode('blended') - # return - - # when standstill: blended - # in case of lead car suddenly move away under traffic light, acc mode won't brake at traffic light. - if self._has_standstill: - self._set_mode('blended') - return - - # when detecting slow down scenario: blended - # e.g. traffic light, curve, stop sign etc. - if self._has_slow_down: - self._set_mode('blended') - return - - # when detecting lead slow down: blended - # use blended for higher braking capability - if self._has_dangerous_ttc: - self._set_mode('blended') - return - - # car driving at speed lower than set speed: acc - if self._has_slowness: - self._set_mode('acc') - return - - self._set_mode('acc') - - def _radar_mode(self) -> None: - # when mpc fcw crash prob is high - # use blended to slow down quickly - if self._has_mpc_fcw: - self._set_mode('blended') - return - - # If there is a filtered lead, the vehicle is not in standstill, and the lead vehicle's yRel meets the condition, - if self._has_lead_filtered and not self._has_standstill: - self._set_mode('acc') - return - - # when blinker is on and speed is driving below V_ACC_MIN: blended - # we don't want it to switch mode at higher speed, blended may trigger hard brake - # if self._has_blinkers and self._v_ego_kph < V_ACC_MIN: - # self._set_mode('blended') - # return - - # when standstill: blended - # in case of lead car suddenly move away under traffic light, acc mode won't brake at traffic light. - if self._has_standstill: - self._set_mode('blended') - return - - # when detecting slow down scenario: blended - # e.g. traffic light, curve, stop sign etc. - if self._has_slow_down: - self._set_mode('blended') - return - - # car driving at speed lower than set speed: acc - if self._has_slowness: - self._set_mode('acc') - return - - # Nav enabled and distance to upcoming turning is 300 or below - # if self._has_nav_instruction: - # self._set_mode('blended') - # return - - self._set_mode('acc') - - def set_mpc_fcw_crash_cnt(self) -> None: - self._mpc_fcw_crash_cnt = self._mpc.crash_cnt - - def _set_mode(self, mode: str) -> None: - if self._set_mode_timeout == 0: - self._mode = mode - if mode == 'blended': - self._set_mode_timeout = SET_MODE_TIMEOUT - - if self._set_mode_timeout > 0: - self._set_mode_timeout -= 1 - - def update(self, sm: messaging.SubMaster) -> None: - self._read_params() - - self.set_mpc_fcw_crash_cnt() - - self._update_calculations(sm) - - if self._CP.radarUnavailable: - self._radarless_mode() - else: - self._radar_mode() - - self._active = sm['selfdriveState'].experimentalMode and self._enabled - - self._frame += 1 diff --git a/sunnypilot/selfdrive/controls/lib/dec/tests/pytest_dynamic_controller.py b/sunnypilot/selfdrive/controls/lib/dec/tests/pytest_dynamic_controller.py deleted file mode 100644 index d15d88aefe..0000000000 --- a/sunnypilot/selfdrive/controls/lib/dec/tests/pytest_dynamic_controller.py +++ /dev/null @@ -1,248 +0,0 @@ -import pytest -import numpy as np -from openpilot.common.params import Params - -from openpilot.sunnypilot.selfdrive.controls.lib.dec.constants import WMACConstants, SNG_State -from openpilot.sunnypilot.selfdrive.controls.lib.dec.dec import DynamicExperimentalController, TRAJECTORY_SIZE, STOP_AND_GO_FRAME - -class MockInterp: - def __call__(self, x, xp, fp): - return np.interp(x, xp, fp) - -class MockCarState: - def __init__(self, v_ego=0., standstill=False, left_blinker=False, right_blinker=False): - self.vEgo = v_ego - self.standstill = standstill - self.leftBlinker = left_blinker - self.rightBlinker = right_blinker - -class MockLeadOne: - def __init__(self, status=False, d_rel=0): - self.status = status - self.dRel = d_rel - -class MockModelData: - def __init__(self, x_vals=None, positions=None): - self.orientation = type('Orientation', (), {'x': x_vals})() - self.position = type('Position', (), {'x': positions})() - -class MockControlState: - def __init__(self, v_cruise=0): - self.vCruise = v_cruise - -@pytest.fixture -def interp(monkeypatch): - mock_interp = MockInterp() - monkeypatch.setattr('numpy.interp', mock_interp) - return mock_interp - -@pytest.fixture -def controller(interp): - params = Params() - params.put_bool("DynamicExperimentalControl", True) - return DynamicExperimentalController() - -def test_initial_state(controller): - """Test initial state of the controller""" - assert controller._mode == 'acc' - assert not controller._has_lead - assert not controller._has_standstill - assert controller._sng_state == SNG_State.off - assert not controller._has_lead_filtered - assert not controller._has_slow_down - assert not controller._has_dangerous_ttc - assert not controller._has_mpc_fcw - -@pytest.mark.parametrize("has_radar", [True, False], ids=["with_radar", "without_radar"]) -def test_standstill_detection(controller, has_radar): - """Test standstill detection and state transitions""" - car_state = MockCarState(standstill=True) - lead_one = MockLeadOne() - md = MockModelData(x_vals=[0] * TRAJECTORY_SIZE, positions=[150] * TRAJECTORY_SIZE) - controls_state = MockControlState() - - # Test transition to standstill - controller.update(not has_radar, car_state, lead_one, md, controls_state) - assert controller._sng_state == SNG_State.stopped - assert controller.get_mpc_mode() == 'blended' - - # Test transition from standstill to moving - car_state.standstill = False - controller.update(not has_radar, car_state, lead_one, md, controls_state) - assert controller._sng_state == SNG_State.going - - # Test complete transition to normal driving - for _ in range(STOP_AND_GO_FRAME + 1): - controller.update(not has_radar, car_state, lead_one, md, controls_state) - assert controller._sng_state == SNG_State.off - -@pytest.mark.parametrize("has_radar", [True, False], ids=["with_radar", "without_radar"]) -def test_lead_detection(controller, has_radar): - """Test lead vehicle detection and filtering""" - car_state = MockCarState(v_ego=20) # 72 kph - lead_one = MockLeadOne(status=True, d_rel=50) # Safe distance - md = MockModelData(x_vals=[0] * TRAJECTORY_SIZE, positions=[150] * TRAJECTORY_SIZE) - controls_state = MockControlState(v_cruise=72) - - # Let moving average stabilize - for _ in range(WMACConstants.LEAD_WINDOW_SIZE + 1): - controller.update(not has_radar, car_state, lead_one, md, controls_state) - - assert controller._has_lead_filtered - expected_mode = 'acc' if has_radar else 'blended' - assert controller.get_mpc_mode() == expected_mode - - # Test lead loss detection - lead_one.status = False - for _ in range(WMACConstants.LEAD_WINDOW_SIZE + 1): - controller.update(not has_radar, car_state, lead_one, md, controls_state) - - assert not controller._has_lead_filtered - -@pytest.mark.parametrize("has_radar", [True, False], ids=["with_radar", "without_radar"]) -def test_slow_down_detection(controller, has_radar): - """Test slow down detection based on trajectory""" - car_state = MockCarState(v_ego=10/3.6) # 10 kph - lead_one = MockLeadOne() - x_vals = [0] * TRAJECTORY_SIZE - positions = [20] * TRAJECTORY_SIZE # Position within slow down threshold - md = MockModelData(x_vals=x_vals, positions=positions) - controls_state = MockControlState(v_cruise=30) - - # Test slow down detection - for _ in range(WMACConstants.SLOW_DOWN_WINDOW_SIZE + 1): - controller.update(not has_radar, car_state, lead_one, md, controls_state) - - assert controller._has_slow_down - assert controller.get_mpc_mode() == 'blended' - - # Test slow down recovery - positions = [200] * TRAJECTORY_SIZE # Position outside slow down threshold - md = MockModelData(x_vals=x_vals, positions=positions) - for _ in range(WMACConstants.SLOW_DOWN_WINDOW_SIZE + 1): - controller.update(not has_radar, car_state, lead_one, md, controls_state) - - assert not controller._has_slow_down - -@pytest.mark.parametrize("has_radar", [True, False], ids=["with_radar", "without_radar"]) -def test_dangerous_ttc_detection(controller, has_radar): - """Test Time-To-Collision detection and handling""" - car_state = MockCarState(v_ego=10) # 36 kph - lead_one = MockLeadOne(status=True) - md = MockModelData(x_vals=[0] * TRAJECTORY_SIZE, positions=[150] * TRAJECTORY_SIZE) - controls_state = MockControlState(v_cruise=36) - - # First establish normal conditions with lead - lead_one.dRel = 100 # Safe distance - for _ in range(WMACConstants.LEAD_WINDOW_SIZE + 1): # First establish lead detection - controller.update(not has_radar, car_state, lead_one, md, controls_state) - - assert controller._has_lead_filtered # Verify lead is detected - - # Now test dangerous TTC detection - lead_one.dRel = 10 # 10m distance - should trigger dangerous TTC - # TTC = dRel/vEgo = 10/10 = 1s (which is less than DANGEROUS_TTC = 2.3s) - - # Need to update multiple times to allow the weighted average to stabilize - for _ in range(WMACConstants.DANGEROUS_TTC_WINDOW_SIZE * 2): - controller.update(not has_radar, car_state, lead_one, md, controls_state) - - assert controller._has_dangerous_ttc, "TTC of 1s should be considered dangerous" - expected_mode = 'acc' if has_radar else 'blended' - assert controller.get_mpc_mode() == expected_mode, f"Should be in [{expected_mode}] mode with dangerous TTC" - -@pytest.mark.parametrize("has_radar", [True, False], ids=["with_radar", "without_radar"]) -def test_mode_transitions(controller, has_radar): - """Test comprehensive mode transitions under different conditions""" - # Initialize with normal driving conditions - car_state = MockCarState(v_ego=25) # 90 kph - lead_one = MockLeadOne(status=False) - md = MockModelData(x_vals=[0] * TRAJECTORY_SIZE, positions=[200] * TRAJECTORY_SIZE) - controls_state = MockControlState(v_cruise=100) - - def stabilize_filters(): - """Helper to let all moving averages stabilize""" - for _ in range(max(WMACConstants.LEAD_WINDOW_SIZE, WMACConstants.SLOW_DOWN_WINDOW_SIZE, - WMACConstants.DANGEROUS_TTC_WINDOW_SIZE, WMACConstants.MPC_FCW_WINDOW_SIZE) + 1): - controller.update(not has_radar, car_state, lead_one, md, controls_state) - - # Test 1: Normal driving -> ACC mode - stabilize_filters() - assert controller.get_mpc_mode() == 'acc', "Should be in ACC mode under normal driving conditions" - - # Test 2: Standstill -> Blended mode - car_state.standstill = True - controller.update(not has_radar, car_state, lead_one, md, controls_state) - assert controller.get_mpc_mode() == 'blended', "Should be in blended mode during standstill" - - # Test 3: Lead car appears -> ACC mode - car_state = MockCarState(v_ego=20) # Reset car state - lead_one.status = True - lead_one.dRel = 50 # Safe distance - stabilize_filters() - assert not controller._has_dangerous_ttc, "Should not have dangerous TTC" - assert controller.get_mpc_mode() == 'acc', "Should be in ACC mode with safe lead distance" - - # Test 4: Dangerous TTC -> Blended mode - car_state = MockCarState(v_ego=20) # 72 kph - lead_one.status = True - lead_one.dRel = 50 # First establish normal lead detection - - # First establish lead detection - for _ in range(WMACConstants.LEAD_WINDOW_SIZE + 1): - controller.update(not has_radar, car_state, lead_one, md, controls_state) - - assert controller._has_lead_filtered # Verify lead is detected - - # Now create dangerous TTC condition - lead_one.dRel = 20 # This creates a TTC of 1s, well below DANGEROUS_TTC - - for _ in range(WMACConstants.DANGEROUS_TTC_WINDOW_SIZE * 2): - controller.update(not has_radar, car_state, lead_one, md, controls_state) - - assert controller._has_dangerous_ttc, "Should detect dangerous TTC condition" - expected_mode = 'acc' if has_radar else 'blended' - assert controller.get_mpc_mode() == expected_mode, f"Should be in [{expected_mode}] mode with dangerous TTC" - -@pytest.mark.parametrize("has_radar", [True, False], ids=["with_radar", "without_radar"]) -def test_mpc_fcw_handling(controller, has_radar): - """Test MPC FCW crash count handling and mode transitions""" - car_state = MockCarState(v_ego=20) - lead_one = MockLeadOne() - md = MockModelData(x_vals=[0] * TRAJECTORY_SIZE, positions=[150] * TRAJECTORY_SIZE) - controls_state = MockControlState(v_cruise=72) - - # Test FCW activation - controller.set_mpc_fcw_crash_cnt(5) - for _ in range(WMACConstants.MPC_FCW_WINDOW_SIZE + 1): - controller.update(not has_radar, car_state, lead_one, md, controls_state) - - assert controller._has_mpc_fcw - assert controller.get_mpc_mode() == 'blended' - - # Test FCW recovery - controller.set_mpc_fcw_crash_cnt(0) - for _ in range(WMACConstants.MPC_FCW_WINDOW_SIZE + 1): - controller.update(not has_radar, car_state, lead_one, md, controls_state) - - assert not controller._has_mpc_fcw - -def test_radar_unavailable_handling(controller): - """Test behavior transitions between radar available and unavailable states""" - car_state = MockCarState(v_ego=27.78) # 100 kph - lead_one = MockLeadOne(status=True, d_rel=50) - md = MockModelData(x_vals=[0] * TRAJECTORY_SIZE, positions=[150] * TRAJECTORY_SIZE) - controls_state = MockControlState(v_cruise=100) - - # Test with radar available - for _ in range(WMACConstants.LEAD_WINDOW_SIZE + 1): - controller.update(False, car_state, lead_one, md, controls_state) - radar_mode = controller.get_mpc_mode() - - # Test with radar unavailable - for _ in range(WMACConstants.LEAD_WINDOW_SIZE + 1): - controller.update(True, car_state, lead_one, md, controls_state) - radarless_mode = controller.get_mpc_mode() - - assert radar_mode is not None - assert radarless_mode is not None diff --git a/sunnypilot/selfdrive/controls/lib/drive_helpers.py b/sunnypilot/selfdrive/controls/lib/drive_helpers.py deleted file mode 100644 index b0fda7bd8c..0000000000 --- a/sunnypilot/selfdrive/controls/lib/drive_helpers.py +++ /dev/null @@ -1,27 +0,0 @@ -from numpy import clip, interp -from openpilot.common.realtime import DT_MDL -from openpilot.selfdrive.controls.lib.drive_helpers import CONTROL_N, MIN_SPEED, MAX_LATERAL_JERK -from openpilot.sunnypilot.modeld.constants import ModelConstants - - -def get_lag_adjusted_curvature(steer_delay, v_ego, psis, curvatures): - if len(psis) != CONTROL_N: - psis = [0.0]*CONTROL_N - curvatures = [0.0]*CONTROL_N - v_ego = max(MIN_SPEED, v_ego) - - # MPC can plan to turn the wheel and turn back before t_delay. This means - # in high delay cases some corrections never even get commanded. So just use - # psi to calculate a simple linearization of desired curvature - current_curvature_desired = curvatures[0] - psi = interp(steer_delay, ModelConstants.T_IDXS[:CONTROL_N], psis) - average_curvature_desired = psi / (v_ego * steer_delay) - desired_curvature = 2 * average_curvature_desired - current_curvature_desired - - # This is the "desired rate of the setpoint" not an actual desired rate - max_curvature_rate = MAX_LATERAL_JERK / (v_ego**2) # inexact calculation, check https://github.com/commaai/openpilot/pull/24755 - safe_desired_curvature = clip(desired_curvature, - current_curvature_desired - max_curvature_rate * DT_MDL, - current_curvature_desired + max_curvature_rate * DT_MDL) - - return float(safe_desired_curvature) diff --git a/sunnypilot/selfdrive/controls/lib/latcontrol_torque_ext.py b/sunnypilot/selfdrive/controls/lib/latcontrol_torque_ext.py deleted file mode 100644 index fe54f46ca7..0000000000 --- a/sunnypilot/selfdrive/controls/lib/latcontrol_torque_ext.py +++ /dev/null @@ -1,31 +0,0 @@ -""" -Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - -This file is part of sunnypilot and is licensed under the MIT License. -See the LICENSE.md file in the root directory for more details. -""" - -from openpilot.sunnypilot.selfdrive.controls.lib.nnlc.nnlc import NeuralNetworkLateralControl - - -class LatControlTorqueExt(NeuralNetworkLateralControl): - def __init__(self, lac_torque, CP, CP_SP): - super().__init__(lac_torque, CP, CP_SP) - - def update(self, CS, VM, params, ff, pid_log, setpoint, measurement, calibrated_pose, roll_compensation, - desired_lateral_accel, actual_lateral_accel, lateral_accel_deadzone, gravity_adjusted_lateral_accel, - desired_curvature, actual_curvature): - self._ff = ff - self._pid_log = pid_log - self._setpoint = setpoint - self._measurement = measurement - self._lateral_accel_deadzone = lateral_accel_deadzone - self._desired_lateral_accel = desired_lateral_accel - self._actual_lateral_accel = actual_lateral_accel - self._desired_curvature = desired_curvature - self._actual_curvature = actual_curvature - - self.update_calculations(CS, VM, desired_lateral_accel) - self.update_neural_network_feedforward(CS, params, calibrated_pose) - - return self._ff, self._pid_log diff --git a/sunnypilot/selfdrive/controls/lib/longitudinal_planner.py b/sunnypilot/selfdrive/controls/lib/longitudinal_planner.py deleted file mode 100644 index 56f32373d5..0000000000 --- a/sunnypilot/selfdrive/controls/lib/longitudinal_planner.py +++ /dev/null @@ -1,41 +0,0 @@ -""" -Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - -This file is part of sunnypilot and is licensed under the MIT License. -See the LICENSE.md file in the root directory for more details. -""" - -from cereal import messaging, custom -from opendbc.car import structs -from openpilot.sunnypilot.selfdrive.controls.lib.dec.dec import DynamicExperimentalController - -DecState = custom.LongitudinalPlanSP.DynamicExperimentalControl.DynamicExperimentalControlState - - -class LongitudinalPlannerSP: - def __init__(self, CP: structs.CarParams, mpc): - self.dec = DynamicExperimentalController(CP, mpc) - - def get_mpc_mode(self) -> str | None: - if not self.dec.active(): - return None - - return self.dec.mode() - - def update(self, sm: messaging.SubMaster) -> None: - self.dec.update(sm) - - def publish_longitudinal_plan_sp(self, sm: messaging.SubMaster, pm: messaging.PubMaster) -> None: - plan_sp_send = messaging.new_message('longitudinalPlanSP') - - plan_sp_send.valid = sm.all_checks(service_list=['carState', 'controlsState']) - - longitudinalPlanSP = plan_sp_send.longitudinalPlanSP - - # Dynamic Experimental Control - dec = longitudinalPlanSP.dec - dec.state = DecState.blended if self.dec.mode() == 'blended' else DecState.acc - dec.enabled = self.dec.enabled() - dec.active = self.dec.active() - - pm.send('longitudinalPlanSP', plan_sp_send) diff --git a/sunnypilot/selfdrive/controls/lib/nnlc/helpers.py b/sunnypilot/selfdrive/controls/lib/nnlc/helpers.py deleted file mode 100644 index c34fa435c2..0000000000 --- a/sunnypilot/selfdrive/controls/lib/nnlc/helpers.py +++ /dev/null @@ -1,68 +0,0 @@ -""" -Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - -This file is part of sunnypilot and is licensed under the MIT License. -See the LICENSE.md file in the root directory for more details. -""" -import os -import tomllib -from difflib import SequenceMatcher - -from opendbc.car import structs -from openpilot.common.basedir import BASEDIR - -TORQUE_NN_MODEL_PATH = os.path.join(BASEDIR, "sunnypilot", "neural_network_data", "neural_network_lateral_control") -TORQUE_NN_MODEL_SUBSTITUTE_PATH = os.path.join(BASEDIR, "opendbc", "car", "torque_data/substitute.toml") -MOCK_MODEL_PATH = os.path.join(TORQUE_NN_MODEL_PATH, "MOCK.json") - - -def similarity(s1: str, s2: str) -> float: - return SequenceMatcher(None, s1, s2).ratio() - - -def get_nn_model_path(CP: structs.CarParams) -> tuple[str, str, bool]: - car_fingerprint = CP.carFingerprint - eps_fw = str(next((fw.fwVersion for fw in CP.carFw if fw.ecu == "eps"), "")) - - def check_nn_path(_nn_candidate): - _model_path = None - _max_similarity = -1.0 - for f in os.listdir(TORQUE_NN_MODEL_PATH): - if f.endswith(".json"): - model = os.path.splitext(f)[0] - similarity_score = similarity(model, _nn_candidate) - if similarity_score > _max_similarity: - _max_similarity = similarity_score - _model_path = os.path.join(TORQUE_NN_MODEL_PATH, f) - return _model_path, _max_similarity - - if len(eps_fw) > 3: - eps_fw = eps_fw.replace("\\", "") - nn_candidate = f"{car_fingerprint} {eps_fw}" - else: - nn_candidate = car_fingerprint - - model_path, max_similarity = check_nn_path(nn_candidate) - exact_match = max_similarity >= 0.99 - - if car_fingerprint not in model_path or 0.0 <= max_similarity < 0.9: - nn_candidate = car_fingerprint - model_path, max_similarity = check_nn_path(nn_candidate) - exact_match = max_similarity >= 0.99 - - if 0.0 <= max_similarity < 0.9: - with open(TORQUE_NN_MODEL_SUBSTITUTE_PATH, 'rb') as f: - sub = tomllib.load(f) - sub_candidate = sub.get(car_fingerprint, car_fingerprint) - - for candidate in [car_fingerprint, sub_candidate]: - model_path, max_similarity = check_nn_path(candidate) - - exact_match = False - - if CP.steerControlType == structs.CarParams.SteerControlType.angle: - model_path = MOCK_MODEL_PATH - - model_name = os.path.splitext(os.path.basename(model_path))[0] - - return model_path, model_name, exact_match diff --git a/sunnypilot/selfdrive/controls/lib/nnlc/nnlc.py b/sunnypilot/selfdrive/controls/lib/nnlc/nnlc.py deleted file mode 100644 index 2f89594c8f..0000000000 --- a/sunnypilot/selfdrive/controls/lib/nnlc/nnlc.py +++ /dev/null @@ -1,133 +0,0 @@ -""" -Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - -This file is part of sunnypilot and is licensed under the MIT License. -See the LICENSE.md file in the root directory for more details. -""" -from collections import deque -import math -import numpy as np - -from opendbc.car.interfaces import LatControlInputs -from openpilot.common.filter_simple import FirstOrderFilter -from openpilot.common.params import Params -from openpilot.selfdrive.modeld.constants import ModelConstants -from openpilot.sunnypilot.selfdrive.controls.lib.latcontrol_torque_ext_base import LatControlTorqueExtBase, sign -from openpilot.sunnypilot.selfdrive.controls.lib.nnlc.helpers import MOCK_MODEL_PATH -from openpilot.sunnypilot.selfdrive.controls.lib.nnlc.model import NNTorqueModel - -LOW_SPEED_X = [0, 10, 20, 30] -LOW_SPEED_Y = [12, 3, 1, 0] - - -# At a given roll, if pitch magnitude increases, the -# gravitational acceleration component starts pointing -# in the longitudinal direction, decreasing the lateral -# acceleration component. Here we do the same thing -# to the roll value itself, then passed to nnff. -def roll_pitch_adjust(roll, pitch): - return roll * math.cos(pitch) - - -class NeuralNetworkLateralControl(LatControlTorqueExtBase): - def __init__(self, lac_torque, CP, CP_SP): - super().__init__(lac_torque, CP, CP_SP) - self.params = Params() - self.enabled = self.params.get_bool("NeuralNetworkLateralControl") - self.has_nn_model = CP_SP.neuralNetworkLateralControl.model.path != MOCK_MODEL_PATH - - # NN model takes current v_ego, lateral_accel, lat accel/jerk error, roll, and past/future/planned data - # of lat accel and roll - # Past value is computed using previous desired lat accel and observed roll - self.model = NNTorqueModel(CP_SP.neuralNetworkLateralControl.model.path) - - self.pitch = FirstOrderFilter(0.0, 0.5, 0.01) - self.pitch_last = 0.0 - - # setup future time offsets - self.future_times = [0.3, 0.6, 1.0, 1.5] # seconds in the future - self.nn_future_times = [i + self.desired_lat_jerk_time for i in self.future_times] - - # setup past time offsets - self.past_times = [-0.3, -0.2, -0.1] - history_check_frames = [int(abs(i)*100) for i in self.past_times] - self.history_frame_offsets = [history_check_frames[0] - i for i in history_check_frames] - self.lateral_accel_desired_deque = deque(maxlen=history_check_frames[0]) - self.roll_deque = deque(maxlen=history_check_frames[0]) - self.error_deque = deque(maxlen=history_check_frames[0]) - self.past_future_len = len(self.past_times) + len(self.nn_future_times) - - def update_lateral_lag(self, lag): - super().update_lateral_lag(lag) - self.nn_future_times = [t + self.desired_lat_jerk_time for t in self.future_times] - - def update_neural_network_feedforward(self, CS, params, calibrated_pose) -> None: - if not self.enabled or not self.model_valid or not self.has_nn_model: - return - - low_speed_factor = float(np.interp(CS.vEgo, LOW_SPEED_X, LOW_SPEED_Y)) ** 2 - self._setpoint = self._desired_lateral_accel + low_speed_factor * self._desired_curvature - self._measurement = self._actual_lateral_accel + low_speed_factor * self._actual_curvature - - # update past data - roll = params.roll - if calibrated_pose is not None: - pitch = self.pitch.update(calibrated_pose.orientation.pitch) - roll = roll_pitch_adjust(roll, pitch) - self.pitch_last = pitch - self.roll_deque.append(roll) - self.lateral_accel_desired_deque.append(self._desired_lateral_accel) - - # prepare past and future values - # adjust future times to account for longitudinal acceleration - adjusted_future_times = [t + 0.5 * CS.aEgo * (t / max(CS.vEgo, 1.0)) for t in self.nn_future_times] - past_rolls = [self.roll_deque[min(len(self.roll_deque) - 1, i)] for i in self.history_frame_offsets] - future_rolls = [roll_pitch_adjust(np.interp(t, ModelConstants.T_IDXS, self.model_v2.orientation.x) + roll, - np.interp(t, ModelConstants.T_IDXS, self.model_v2.orientation.y) + self.pitch_last) for t in - adjusted_future_times] - past_lateral_accels_desired = [self.lateral_accel_desired_deque[min(len(self.lateral_accel_desired_deque) - 1, i)] - for i in self.history_frame_offsets] - future_planned_lateral_accels = [np.interp(t, ModelConstants.T_IDXS, self.model_v2.acceleration.y) for t in - adjusted_future_times] - - # compute NNFF error response - nnff_setpoint_input = [CS.vEgo, self._setpoint, self.lateral_jerk_setpoint, roll] \ - + [self._setpoint] * self.past_future_len \ - + past_rolls + future_rolls - # past lateral accel error shouldn't count, so use past desired like the setpoint input - nnff_measurement_input = [CS.vEgo, self._measurement, self.lateral_jerk_measurement, roll] \ - + [self._measurement] * self.past_future_len \ - + past_rolls + future_rolls - torque_from_setpoint = self.model.evaluate(nnff_setpoint_input) - torque_from_measurement = self.model.evaluate(nnff_measurement_input) - self._pid_log.error = torque_from_setpoint - torque_from_measurement - - # The "pure" NNLC error response can be too weak for cars whose models were trained - # with a lack of high-magnitude lateral acceleration data, for which the NNLC model - # torque response flattens out at high lateral accelerations. - # This workaround blends in a guaranteed stronger error response only when the - # desired lateral acceleration is high enough to warrant it, by using the lateral acceleration - # error as the input to the NNLC model. This is not ideal, and potentially degrades the NNLC - # accuracy for cars that don't have this issue, but it's necessary until a better NNLC model - # structure is used that doesn't create this issue when high-magnitude data is missing. - error_blend_factor = float(np.interp(abs(self._desired_lateral_accel), [1.0, 2.0], [0.0, 1.0])) - if error_blend_factor > 0.0: # blend in stronger error response when in high lat accel - # NNFF inputs 5+ are optional, and if left out are replaced with 0.0 inside the NNFF class - nnff_error_input = [CS.vEgo, self._setpoint - self._measurement, self.lateral_jerk_setpoint - self.lateral_jerk_measurement, 0.0] - torque_from_error = self.model.evaluate(nnff_error_input) - if sign(self._pid_log.error) == sign(torque_from_error) and abs(self._pid_log.error) < abs(torque_from_error): - self._pid_log.error = self._pid_log.error * (1.0 - error_blend_factor) + torque_from_error * error_blend_factor - - # compute feedforward (same as nn setpoint output) - friction_input = self.update_friction_input(self._setpoint, self._measurement) - nn_input = [CS.vEgo, self._desired_lateral_accel, friction_input, roll] \ - + past_lateral_accels_desired + future_planned_lateral_accels \ - + past_rolls + future_rolls - self._ff = self.model.evaluate(nn_input) - - # apply friction override for cars with low NN friction response - if self.model.friction_override: - self._pid_log.error += self.torque_from_lateral_accel(LatControlInputs(0.0, 0.0, CS.vEgo, CS.aEgo), self.torque_params, - friction_input, - self._lateral_accel_deadzone, friction_compensation=True, - gravity_adjusted=False) diff --git a/sunnypilot/selfdrive/controls/lib/param_store.py b/sunnypilot/selfdrive/controls/lib/param_store.py deleted file mode 100644 index b2701bc010..0000000000 --- a/sunnypilot/selfdrive/controls/lib/param_store.py +++ /dev/null @@ -1,35 +0,0 @@ -""" -Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - -This file is part of sunnypilot and is licensed under the MIT License. -See the LICENSE.md file in the root directory for more details. -""" -import capnp - -from cereal import custom - -from opendbc.car import structs -from openpilot.common.params import Params - - -class ParamStore: - keys: list[str] - values: dict[str, str] - - def __init__(self, CP: structs.CarParams): - universal_params: list[str] = [] - brand_params: list[str] = [] - - self.keys = universal_params + brand_params - self.values = {} - - def update(self, params: Params) -> None: - self.values = {k: params.get(k, encoding='utf8') or "0" for k in self.keys} - - def publish(self) -> list[capnp.lib.capnp._DynamicStructBuilder]: - params_list: list[capnp.lib.capnp._DynamicStructBuilder] = [] - - for k in self.keys: - params_list.append(custom.CarControlSP.Param(key=k, value=self.values[k])) - - return params_list diff --git a/sunnypilot/selfdrive/selfdrived/events.py b/sunnypilot/selfdrive/selfdrived/events.py deleted file mode 100644 index d81345a14e..0000000000 --- a/sunnypilot/selfdrive/selfdrived/events.py +++ /dev/null @@ -1,137 +0,0 @@ -from cereal import log, car, custom -from openpilot.sunnypilot.selfdrive.selfdrived.events_base import EventsBase, Priority, ET, Alert, \ - NoEntryAlert, ImmediateDisableAlert, EngagementAlert, NormalPermanentAlert, AlertCallbackType, wrong_car_mode_alert - - -AlertSize = log.SelfdriveState.AlertSize -AlertStatus = log.SelfdriveState.AlertStatus -VisualAlert = car.CarControl.HUDControl.VisualAlert -AudibleAlert = car.CarControl.HUDControl.AudibleAlert -EventNameSP = custom.OnroadEventSP.EventName - - -# get event name from enum -EVENT_NAME_SP = {v: k for k, v in EventNameSP.schema.enumerants.items()} - - -class EventsSP(EventsBase): - def __init__(self): - super().__init__() - self.event_counters = dict.fromkeys(EVENTS_SP.keys(), 0) - - def get_events_mapping(self) -> dict[int, dict[str, Alert | AlertCallbackType]]: - return EVENTS_SP - - def get_event_name(self, event: int): - return EVENT_NAME_SP[event] - - def get_event_msg_type(self): - return custom.OnroadEventSP.Event - - -EVENTS_SP: dict[int, dict[str, Alert | AlertCallbackType]] = { - # sunnypilot - EventNameSP.lkasEnable: { - ET.ENABLE: EngagementAlert(AudibleAlert.engage), - }, - - EventNameSP.lkasDisable: { - ET.USER_DISABLE: EngagementAlert(AudibleAlert.disengage), - }, - - EventNameSP.manualSteeringRequired: { - ET.USER_DISABLE: Alert( - "Automatic Lane Centering is OFF", - "Manual Steering Required", - AlertStatus.normal, AlertSize.mid, - Priority.LOW, VisualAlert.none, AudibleAlert.disengage, 1.), - }, - - EventNameSP.manualLongitudinalRequired: { - ET.WARNING: Alert( - "Smart/Adaptive Cruise Control: OFF", - "Manual Speed Control Required", - AlertStatus.normal, AlertSize.mid, - Priority.LOW, VisualAlert.none, AudibleAlert.none, 1.), - }, - - EventNameSP.silentLkasEnable: { - ET.ENABLE: EngagementAlert(AudibleAlert.none), - }, - - EventNameSP.silentLkasDisable: { - ET.USER_DISABLE: EngagementAlert(AudibleAlert.none), - }, - - EventNameSP.silentBrakeHold: { - ET.WARNING: EngagementAlert(AudibleAlert.none), - ET.NO_ENTRY: NoEntryAlert("Brake Hold Active"), - }, - - EventNameSP.silentWrongGear: { - ET.WARNING: Alert( - "", - "", - AlertStatus.normal, AlertSize.none, - Priority.LOWEST, VisualAlert.none, AudibleAlert.none, 0.), - ET.NO_ENTRY: Alert( - "Gear not D", - "openpilot Unavailable", - AlertStatus.normal, AlertSize.mid, - Priority.LOW, VisualAlert.none, AudibleAlert.none, 0.), - }, - - EventNameSP.silentReverseGear: { - ET.PERMANENT: Alert( - "Reverse\nGear", - "", - AlertStatus.normal, AlertSize.full, - Priority.LOWEST, VisualAlert.none, AudibleAlert.none, .2, creation_delay=0.5), - ET.NO_ENTRY: NoEntryAlert("Reverse Gear"), - }, - - EventNameSP.silentDoorOpen: { - ET.WARNING: Alert( - "", - "", - AlertStatus.normal, AlertSize.none, - Priority.LOWEST, VisualAlert.none, AudibleAlert.none, 0.), - ET.NO_ENTRY: NoEntryAlert("Door Open"), - }, - - EventNameSP.silentSeatbeltNotLatched: { - ET.WARNING: Alert( - "", - "", - AlertStatus.normal, AlertSize.none, - Priority.LOWEST, VisualAlert.none, AudibleAlert.none, 0.), - ET.NO_ENTRY: NoEntryAlert("Seatbelt Unlatched"), - }, - - EventNameSP.silentParkBrake: { - ET.WARNING: Alert( - "", - "", - AlertStatus.normal, AlertSize.none, - Priority.LOWEST, VisualAlert.none, AudibleAlert.none, 0.), - ET.NO_ENTRY: NoEntryAlert("Parking Brake Engaged"), - }, - - EventNameSP.controlsMismatchLateral: { - ET.IMMEDIATE_DISABLE: ImmediateDisableAlert("Controls Mismatch: Lateral"), - ET.NO_ENTRY: NoEntryAlert("Controls Mismatch: Lateral"), - }, - - EventNameSP.experimentalModeSwitched: { - ET.WARNING: NormalPermanentAlert("Experimental Mode Switched", duration=1.5) - }, - - EventNameSP.wrongCarModeAlertOnly: { - ET.WARNING: wrong_car_mode_alert, - }, - - EventNameSP.pedalPressedAlertOnly: { - ET.WARNING: NoEntryAlert("Pedal Pressed") - } - -} diff --git a/sunnypilot/sunnylink/api.py b/sunnypilot/sunnylink/api.py deleted file mode 100644 index eb9343af9a..0000000000 --- a/sunnypilot/sunnylink/api.py +++ /dev/null @@ -1,158 +0,0 @@ -import json -import os -import random -import time -from datetime import datetime, timedelta -from pathlib import Path - -import jwt -from openpilot.common.api.base import BaseApi -from openpilot.common.params import Params -from openpilot.system.hardware import HARDWARE -from openpilot.system.hardware.hw import Paths - -API_HOST = os.getenv('SUNNYLINK_API_HOST', 'https://stg.api.sunnypilot.ai') -UNREGISTERED_SUNNYLINK_DONGLE_ID = "UnregisteredDevice" -MAX_RETRIES = 6 -CRASH_LOG_DIR = Paths.crash_log_root() - - -class SunnylinkApi(BaseApi): - def __init__(self, dongle_id): - super().__init__(dongle_id, API_HOST) - self.user_agent = "sunnypilot-" - self.spinner = None - self.params = Params() - - def api_get(self, endpoint, method='GET', timeout=10, access_token=None, json=None, **kwargs): - if not self.params.get_bool("SunnylinkEnabled"): - return None - - return super().api_get(endpoint, method, timeout, access_token, json, **kwargs) - - def resume_queued(self, timeout=10, **kwargs): - sunnylinkId, commaId = self._resolve_dongle_ids() - return self.api_get(f"ws/{sunnylinkId}/resume_queued", "POST", timeout, access_token=self.get_token(), **kwargs) - - def get_token(self, expiry_hours=1): - # Add your additional data here - additional_data = {} - return super()._get_token(expiry_hours, **additional_data) - - def _status_update(self, message): - print(message) - if self.spinner: - self.spinner.update(message) - time.sleep(0.5) - - def _resolve_dongle_ids(self): - sunnylink_dongle_id = self.params.get("SunnylinkDongleId", encoding='utf-8') - comma_dongle_id = self.dongle_id or self.params.get("DongleId", encoding='utf-8') - return sunnylink_dongle_id, comma_dongle_id - - def _resolve_imeis(self): - imei1, imei2 = None, None - imei_try = 0 - while imei1 is None and imei2 is None and imei_try < MAX_RETRIES: - try: - imei1, imei2 = HARDWARE.get_imei(0), HARDWARE.get_imei(1) - except Exception: - self._status_update(f"Error getting imei, trying again... [{imei_try + 1}/{MAX_RETRIES}]") - time.sleep(1) - imei_try += 1 - return imei1, imei2 - - def _resolve_serial(self): - return (self.params.get("HardwareSerial", encoding='utf8') - or HARDWARE.get_serial()) - - def register_device(self, spinner=None, timeout=60, verbose=False): - self.spinner = spinner - - sunnylink_dongle_id, comma_dongle_id = self._resolve_dongle_ids() - - if comma_dongle_id is None: - self._status_update("Comma dongle ID not found, deferring sunnylink's registration to comma's registration process.") - return None - - imei1, imei2 = self._resolve_imeis() - serial = self._resolve_serial() - - if sunnylink_dongle_id not in (None, UNREGISTERED_SUNNYLINK_DONGLE_ID): - return sunnylink_dongle_id - - privkey_path = Path(f"{Paths.persist_root()}/comma/id_rsa") - pubkey_path = Path(f"{Paths.persist_root()}/comma/id_rsa.pub") - - start_time = time.monotonic() - successful_registration = False - if not pubkey_path.is_file(): - sunnylink_dongle_id = UNREGISTERED_SUNNYLINK_DONGLE_ID - self._status_update("Public key not found, setting dongle ID to unregistered.") - else: - Params().put("LastSunnylinkPingTime", "0") # Reset the last ping time to 0 if we are trying to register - with pubkey_path.open() as f1, privkey_path.open() as f2: - public_key = f1.read() - private_key = f2.read() - - backoff = 1 - while True: - register_token = jwt.encode({'register': True, 'exp': datetime.utcnow() + timedelta(hours=1)}, private_key, algorithm='RS256') - try: - if verbose or time.monotonic() - start_time < timeout / 2: - self._status_update("Registering device to sunnylink...") - elif time.monotonic() - start_time >= timeout / 2: - self._status_update("Still registering device to sunnylink...") - - resp = self.api_get("v2/pilotauth/", method='POST', timeout=15, imei=imei1, imei2=imei2, serial=serial, - comma_dongle_id=comma_dongle_id, public_key=public_key, register_token=register_token) - - if resp is None: - raise Exception("Unable to register device, request was None") - - if resp.status_code in (409, 412): - timeout = time.monotonic() - start_time # Don't retry if the public key is already in use - key_in_use = "Public key is already in use, is your key unique? Contact your vendor for a new key." - unsafe_key = "Public key is known to not be unique and it's unsafe. Contact your vendor for a new key." - error_message = key_in_use if resp.status_code == 409 else unsafe_key - raise Exception(error_message) - - if resp.status_code != 200: - raise Exception(f"Failed to register with sunnylink. Status code: {resp.status_code}\nData\n:{resp.text}") - - dongleauth = json.loads(resp.text) - sunnylink_dongle_id = dongleauth["device_id"] - if sunnylink_dongle_id: - self._status_update("Device registered successfully.") - successful_registration = True - break - except Exception as e: - if verbose: - self._status_update(f"Waiting {backoff}s before retry, Exception occurred during registration: [{str(e)}]") - - if not os.path.exists(CRASH_LOG_DIR): - os.makedirs(CRASH_LOG_DIR) - - with open(f'{CRASH_LOG_DIR}/error.txt', 'a') as f: - f.write(f"[{datetime.now()}] sunnylink: {str(e)}\n") - - backoff = min(backoff * 2 * (0.5 + random.random()), 60) - time.sleep(backoff) - - if time.monotonic() - start_time > timeout: - self._status_update(f"Giving up on sunnylink's registration after {timeout}s. Will retry on next boot.") - time.sleep(3) - break - - self.params.put("SunnylinkDongleId", sunnylink_dongle_id or UNREGISTERED_SUNNYLINK_DONGLE_ID) - - # Set the last ping time to the current time since we were just talking to the API - last_ping = int(time.monotonic() * 1e9) if successful_registration else start_time - Params().put("LastSunnylinkPingTime", str(last_ping)) - - # Disable sunnylink if registration was not successful - if not successful_registration: - Params().put_bool("SunnylinkEnabled", False) - - self.spinner = None - return sunnylink_dongle_id diff --git a/sunnypilot/sunnylink/athena/sunnylinkd.py b/sunnypilot/sunnylink/athena/sunnylinkd.py deleted file mode 100755 index a675820628..0000000000 --- a/sunnypilot/sunnylink/athena/sunnylinkd.py +++ /dev/null @@ -1,272 +0,0 @@ -#!/usr/bin/env python3 - -from __future__ import annotations - -import base64 -import gzip -import os -import ssl -import threading -import time - -from jsonrpc import dispatcher -from functools import partial -from openpilot.common.params import Params -from openpilot.common.realtime import set_core_affinity -from openpilot.common.swaglog import cloudlog -from openpilot.system.athena.athenad import ws_send, jsonrpc_handler, \ - recv_queue, UploadQueueCache, upload_queue, cur_upload_items, backoff, ws_manage, log_handler, start_local_proxy_shim -from websocket import (ABNF, WebSocket, WebSocketException, WebSocketTimeoutException, - create_connection) - -import cereal.messaging as messaging -from sunnypilot.sunnylink.api import SunnylinkApi -from sunnypilot.sunnylink.utils import sunnylink_need_register, sunnylink_ready - -SUNNYLINK_ATHENA_HOST = os.getenv('SUNNYLINK_ATHENA_HOST', 'wss://ws.stg.api.sunnypilot.ai') -HANDLER_THREADS = int(os.getenv('HANDLER_THREADS', "4")) -LOCAL_PORT_WHITELIST = {8022} -SUNNYLINK_LOG_ATTR_NAME = "user.sunny.upload" -SUNNYLINK_RECONNECT_TIMEOUT_S = 70 # FYI changing this will also would require a change on sidebar.cc -DISALLOW_LOG_UPLOAD = threading.Event() - -params = Params() -sunnylink_dongle_id = params.get("SunnylinkDongleId", encoding='utf-8') -sunnylink_api = SunnylinkApi(sunnylink_dongle_id) - - -def handle_long_poll(ws: WebSocket, exit_event: threading.Event | None) -> None: - cloudlog.info("sunnylinkd.handle_long_poll started") - sm = messaging.SubMaster(['deviceState']) - end_event = threading.Event() - comma_prime_cellular_end_event = threading.Event() - - threads = [ - threading.Thread(target=ws_manage, args=(ws, end_event), name='ws_manage'), - threading.Thread(target=ws_recv, args=(ws, end_event), name='ws_recv'), - threading.Thread(target=ws_send, args=(ws, end_event), name='ws_send'), - threading.Thread(target=ws_ping, args=(ws, end_event), name='ws_ping'), - threading.Thread(target=ws_queue, args=(end_event,), name='ws_queue'), - # threading.Thread(target=upload_handler, args=(end_event,), name='upload_handler'), - # threading.Thread(target=sunny_log_handler, args=(end_event, comma_prime_cellular_end_event), name='log_handler'), - # threading.Thread(target=stat_handler, args=(end_event,), name='stat_handler'), - ] + [ - threading.Thread(target=jsonrpc_handler, args=(end_event, partial(startLocalProxy, end_event),), name=f'worker_{x}') - for x in range(HANDLER_THREADS) - ] - - for thread in threads: - thread.start() - try: - while not end_event.wait(0.1): - if not sunnylink_ready(params): - cloudlog.warning("Exiting sunnylinkd.handle_long_poll as SunnylinkEnabled is False") - break - - sm.update(0) - if exit_event is not None and exit_event.is_set(): - end_event.set() - comma_prime_cellular_end_event.set() - - prime_type = params.get("PrimeType", encoding='utf-8') or 0 - metered = sm['deviceState'].networkMetered - - if DISALLOW_LOG_UPLOAD.is_set() and not comma_prime_cellular_end_event.is_set(): - cloudlog.debug("sunnylinkd.handle_long_poll: DISALLOW_LOG_UPLOAD, setting comma_prime_cellular_end_event") - comma_prime_cellular_end_event.set() - elif metered and int(prime_type) > 2: - cloudlog.debug(f"sunnylinkd.handle_long_poll: PrimeType({prime_type}) > 2 and networkMetered({metered})") - comma_prime_cellular_end_event.set() - elif comma_prime_cellular_end_event.is_set() and not DISALLOW_LOG_UPLOAD.is_set(): - cloudlog.debug( - f"sunnylinkd.handle_long_poll: comma_prime_cellular_end_event is set and not PrimeType({prime_type}) > 2 or not networkMetered({metered})") - comma_prime_cellular_end_event.clear() - finally: - end_event.set() - comma_prime_cellular_end_event.set() - for thread in threads: - cloudlog.debug(f"sunnylinkd athena.joining {thread.name}") - thread.join() - cloudlog.debug(f"sunnylinkd athena.joined {thread.name}") - - -def ws_recv(ws: WebSocket, end_event: threading.Event) -> None: - last_ping = int(time.monotonic() * 1e9) - while not end_event.is_set(): - try: - opcode, data = ws.recv_data(control_frame=True) - if opcode in (ABNF.OPCODE_TEXT, ABNF.OPCODE_BINARY): - if opcode == ABNF.OPCODE_TEXT: - data = data.decode("utf-8") - recv_queue.put_nowait(data) - cloudlog.debug(f"sunnylinkd.ws_recv.recv {data}") - elif opcode in (ABNF.OPCODE_PING, ABNF.OPCODE_PONG): - cloudlog.debug("sunnylinkd.ws_recv.pong") - last_ping = int(time.monotonic() * 1e9) - Params().put("LastSunnylinkPingTime", str(last_ping)) - except WebSocketTimeoutException: - ns_since_last_ping = int(time.monotonic() * 1e9) - last_ping - if ns_since_last_ping > SUNNYLINK_RECONNECT_TIMEOUT_S * 1e9: - cloudlog.exception("sunnylinkd.ws_recv.timeout") - end_event.set() - except Exception: - cloudlog.exception("sunnylinkd.ws_recv.exception") - end_event.set() - - -def ws_ping(ws: WebSocket, end_event: threading.Event) -> None: - ws.ping() # Send the first ping - while not end_event.wait(SUNNYLINK_RECONNECT_TIMEOUT_S * 0.7): # Sleep about 70% before a timeout - try: - ws.ping() - cloudlog.debug("sunnylinkd.ws_recv.ws_ping: Pinging") - except Exception: - cloudlog.exception("sunnylinkd.ws_ping.exception") - end_event.set() - cloudlog.debug("sunnylinkd.ws_ping.end_event is set, exiting ws_ping thread") - - -def ws_queue(end_event: threading.Event) -> None: - resume_requested = False - tries = 0 - - while not end_event.is_set() and not resume_requested: - try: - if not resume_requested: - cloudlog.debug("sunnylinkd.ws_queue.resume_queued") - sunnylink_api.resume_queued(timeout=29) - resume_requested = True - tries = 0 - except Exception: - cloudlog.exception("sunnylinkd.ws_queue.resume_queued.exception") - resume_requested = False - tries += 1 - time.sleep(backoff(tries)) # Wait for the backoff time before the next attempt - - if end_event.is_set(): - cloudlog.debug("end_event is set, exiting ws_queue thread") - elif resume_requested: - cloudlog.debug(f"Resume requested to server after {tries} tries") - else: - cloudlog.error(f"Reached end of ws_queue while end_event is not set and resume_requested is {resume_requested}") - - -def sunny_log_handler(end_event: threading.Event, comma_prime_cellular_end_event: threading.Event) -> None: - while not end_event.wait(0.1): - if not comma_prime_cellular_end_event.is_set(): - log_handler(comma_prime_cellular_end_event, SUNNYLINK_LOG_ATTR_NAME) - comma_prime_cellular_end_event.set() - - -@dispatcher.add_method -def toggleLogUpload(enabled: bool): - DISALLOW_LOG_UPLOAD.clear() if enabled and DISALLOW_LOG_UPLOAD.is_set() else DISALLOW_LOG_UPLOAD.set() - - -@dispatcher.add_method -def getParamsAllKeys() -> list[str]: - keys: list[str] = [k.decode('utf-8') for k in Params().all_keys()] - return keys - - -@dispatcher.add_method -def getParams(params_keys: list[str], compression: bool = False) -> str | dict[str, str]: - try: - params = Params() - params_dict: dict[str, bytes] = {key: params.get(key) or b'' for key in params_keys} - - # Compress the values before encoding to base64 as output from params.get is bytes and same for compression - if compression: - params_dict = {key: gzip.compress(value) for key, value in params_dict.items()} - - # Last step is to encode the values to base64 and decode to utf-8 for JSON serialization - return {key: base64.b64encode(value).decode('utf-8') for key, value in params_dict.items()} - - except Exception as e: - cloudlog.exception("sunnylinkd.getParams.exception", e) - raise - - -@dispatcher.add_method -def saveParams(params_to_update: dict[str, str], compression: bool = False) -> None: - params = Params() - params_dict = {key: base64.b64decode(value) for key, value in params_to_update.items()} - - if compression: - params_dict = {key: gzip.decompress(value) for key, value in params_dict.items()} - - for key, value in params_dict.items(): - try: - params.put(key, value) - except Exception as e: - cloudlog.error(f"sunnylinkd.saveParams.exception {e}") - - -def startLocalProxy(global_end_event: threading.Event, remote_ws_uri: str, local_port: int) -> dict[str, int]: - cloudlog.debug("athena.startLocalProxy.starting") - ws = create_connection( - remote_ws_uri, - header={"Authorization": f"Bearer {sunnylink_api.get_token()}"}, - enable_multithread=True, - sslopt={"cert_reqs": ssl.CERT_NONE} - ) - - return start_local_proxy_shim(global_end_event, local_port, ws) - - -def main(exit_event: threading.Event = None): - try: - set_core_affinity([0, 1, 2, 3]) - except Exception: - cloudlog.exception("failed to set core affinity") - - while sunnylink_need_register(params): - cloudlog.info("Waiting for sunnylink registration to complete") - time.sleep(10) - - UploadQueueCache.initialize(upload_queue) - - ws_uri = f"{SUNNYLINK_ATHENA_HOST}" - conn_start = None - conn_retries = 0 - while (exit_event is None or not exit_event.is_set()) and sunnylink_ready(params): - try: - if conn_start is None: - conn_start = time.monotonic() - - cloudlog.event("sunnylinkd.main.connecting_ws", ws_uri=ws_uri, retries=conn_retries) - ws = create_connection( - ws_uri, - header={"Authorization": f"Bearer {sunnylink_api.get_token()}"}, - enable_multithread=True, - sslopt={"cert_reqs": ssl.CERT_NONE if "localhost" in ws_uri else ssl.CERT_REQUIRED}, - timeout=SUNNYLINK_RECONNECT_TIMEOUT_S, - ) - cloudlog.event("sunnylinkd.main.connected_ws", ws_uri=ws_uri, retries=conn_retries, - duration=time.monotonic() - conn_start) - conn_start = None - - conn_retries = 0 - cur_upload_items.clear() - - handle_long_poll(ws, exit_event) - except (KeyboardInterrupt, SystemExit): - break - except (ConnectionError, TimeoutError, WebSocketException): - conn_retries += 1 - params.remove("LastSunnylinkPingTime") - except Exception: - cloudlog.exception("sunnylinkd.main.exception") - - conn_retries += 1 - params.remove("LastSunnylinkPingTime") - - time.sleep(backoff(conn_retries)) - - if not sunnylink_ready(params): - cloudlog.debug("Reached end of sunnylinkd.main while sunnylink is not ready. Waiting 60s before retrying") - time.sleep(60) - - -if __name__ == "__main__": - main() diff --git a/sunnypilot/sunnylink/backups/manager.py b/sunnypilot/sunnylink/backups/manager.py deleted file mode 100644 index d6408d7ba7..0000000000 --- a/sunnypilot/sunnylink/backups/manager.py +++ /dev/null @@ -1,281 +0,0 @@ -""" -Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - -This file is part of sunnypilot and is licensed under the MIT License. -See the LICENSE.md file in the root directory for more details. -""" - -import base64 -import json -import time -from enum import Enum -from typing import Any - -from openpilot.common.git import get_branch -from openpilot.common.params import Params, ParamKeyType -from openpilot.common.realtime import Ratekeeper -from openpilot.common.swaglog import cloudlog -from openpilot.system.version import get_version - -from cereal import messaging, custom -from sunnypilot.sunnylink.api import SunnylinkApi -from sunnypilot.sunnylink.backups.utils import decrypt_compressed_data, encrypt_compress_data, SnakeCaseEncoder - - -class OperationType(Enum): - BACKUP = "backup" - RESTORE = "restore" - - -class BackupManagerSP: - """Manages device configuration backups to/from sunnylink""" - - def __init__(self): - self.params = Params() - self.device_id = self.params.get("SunnylinkDongleId", encoding="utf8") - self.api = SunnylinkApi(self.device_id) - self.pm = messaging.PubMaster(["backupManagerSP"]) - - # Status tracking - self.backup_status = custom.BackupManagerSP.Status.idle - self.restore_status = custom.BackupManagerSP.Status.idle - - # Unified progress & operation type (only one operation runs at a time) - self.progress = 0.0 - self.operation: OperationType | None = None - - self.last_error = "" - - def _report_status(self) -> None: - """Reports current backup manager state through the messaging system.""" - msg = messaging.new_message('backupManagerSP', valid=True) - backup_state = msg.backupManagerSP - - backup_state.backupStatus = self.backup_status - backup_state.restoreStatus = self.restore_status - # Both progress fields use the unified progress value - backup_state.backupProgress = self.progress - backup_state.restoreProgress = self.progress - backup_state.lastError = self.last_error - - # Optionally, add a field for operation type if supported: - # backup_state.operationType = self.operation.value if self.operation else "none" - - self.pm.send('backupManagerSP', msg) - - def _update_progress(self, progress: float, op_type: OperationType) -> None: - """Updates the unified progress and operation type, then reports status.""" - self.progress = progress - self.operation = op_type - self._report_status() - - def _collect_config_data(self) -> dict[str, Any]: - """Collects configuration data to be backed up.""" - config_data = {} - params_to_backup = [k.decode('utf-8') for k in self.params.all_keys(ParamKeyType.BACKUP)] - for param in params_to_backup: - value = self.params.get(param) - if value is not None: - config_data[param] = base64.b64encode(value).decode('utf-8') - return config_data - - def _get_metadata_value(self, metadata_list, key, default_value=None): - return next((entry.get("value") for entry in metadata_list if entry.get("key") == key), default_value) - - async def create_backup(self) -> bool: - """Creates and uploads a new backup to sunnylink.""" - try: - self.backup_status = custom.BackupManagerSP.Status.inProgress - self._update_progress(0.0, OperationType.BACKUP) - - # Collect configuration data - config_data = self._collect_config_data() - self._update_progress(25.0, OperationType.BACKUP) - - # Serialize and encrypt config data - config_json = json.dumps(config_data) - encrypted_config = encrypt_compress_data(config_json, use_aes_256=True) - self._update_progress(50.0, OperationType.BACKUP) - - backup_info = custom.BackupManagerSP.BackupInfo() - backup_info.deviceId = self.device_id - backup_info.config = encrypted_config - backup_info.isEncrypted = True - backup_info.createdAt = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()) - backup_info.updatedAt = backup_info.createdAt - backup_info.sunnypilotVersion = self._get_current_version() - backup_info.backupMetadata = [ - custom.BackupManagerSP.MetadataEntry(key="creator", value="BackupManagerSP"), - custom.BackupManagerSP.MetadataEntry(key="all_values_encoded", value="True"), - custom.BackupManagerSP.MetadataEntry(key="AES", value="256") - ] - - payload = json.loads(json.dumps(backup_info.to_dict(), cls=SnakeCaseEncoder)) - self._update_progress(75.0, OperationType.BACKUP) - - # Upload to sunnylink - result = self.api.api_get( - f"backup/{self.device_id}", - method='PUT', - access_token=self.api.get_token(), - json=payload - ) - - if result: - self.backup_status = custom.BackupManagerSP.Status.completed - self._update_progress(100.0, OperationType.BACKUP) - else: - self.backup_status = custom.BackupManagerSP.Status.failed - self.last_error = "Failed to upload backup" - self._report_status() - - return bool(self.backup_status == custom.BackupManagerSP.Status.completed) - - except Exception as e: - cloudlog.exception(f"Error creating backup: {str(e)}") - self.backup_status = custom.BackupManagerSP.Status.failed - self.last_error = str(e) - self._report_status() - return False - - async def restore_backup(self, version: int | None = None) -> bool: - """Restores a backup from sunnylink.""" - try: - self.restore_status = custom.BackupManagerSP.Status.inProgress - self._update_progress(0.0, OperationType.RESTORE) - - # Get backup data from API for the specified version - endpoint = f"backup/{self.device_id}" + f"/{version or ''}" + "?api-version=1" - backup_data = self.api.api_get(endpoint, access_token=self.api.get_token()) - if not backup_data: - raise Exception(f"No backup found for device {self.device_id}") - - self._update_progress(25.0, OperationType.RESTORE) - - data = backup_data.json() - backup_metadata = data.get("backup_metadata", []) - encrypted_config = data.get("config", "") - if not encrypted_config: - raise Exception("Empty backup configuration") - self._update_progress(50.0, OperationType.RESTORE) - - # Decrypt config and load data - use_aes_256 = self._get_metadata_value(backup_metadata, "AES", "128") == "256" - config_json = decrypt_compressed_data(encrypted_config, use_aes_256) - if not config_json: - raise Exception("Failed to decrypt backup configuration") - - config_data = json.loads(config_json) - self._update_progress(75.0, OperationType.RESTORE) - - # Apply configuration - all_values_encoded = self._get_metadata_value(backup_metadata, "all_values_encoded", "false") - self._apply_config(config_data, str(all_values_encoded).lower() == "true") - - self.restore_status = custom.BackupManagerSP.Status.completed - self._update_progress(100.0, OperationType.RESTORE) - return True - - except Exception as e: - cloudlog.exception(f"Error restoring backup: {str(e)}") - self.restore_status = custom.BackupManagerSP.Status.failed - self.last_error = str(e) - self._report_status() - return False - - def _apply_config(self, config_data: dict[str, str], all_values_encoded: bool = False) -> None: - """Applies configuration data from a backup, but only for parameters marked as backupable.""" - # Get the current list of parameters that can be backed up - backupable_params = [k.decode('utf-8') for k in self.params.all_keys(ParamKeyType.BACKUP)] - - # Count for logging/reporting - restored_count = 0 - skipped_count = 0 - - for param, encoded_value in config_data.items(): - try: - # Only restore parameters that are currently marked as backupable - if param in backupable_params: - value = base64.b64decode(encoded_value) if all_values_encoded else encoded_value - self.params.put(param, value) - restored_count += 1 - else: - skipped_count += 1 - cloudlog.info(f"Skipped restoring param {param}: not marked for backup in current version") - except Exception as e: - cloudlog.error(f"Failed to restore param {param}: {str(e)}") - - cloudlog.info(f"Restore complete: {restored_count} params restored, {skipped_count} params skipped") - - def _get_current_version(self) -> custom.BackupManagerSP.Version: - """Gets current sunnypilot version information.""" - version_obj = custom.BackupManagerSP.Version() - version_str = get_version() - - version_parts = version_str.split('-') # For when version is like "1.2.3-456" - version_nums = version_parts[0].split('.') - - # Extract build number from hyphen format or as 4th version component - build = 0 - if len(version_parts) > 1 and version_parts[1].isdigit(): - build = int(version_parts[1]) - elif len(version_nums) > 3 and version_nums[3].isdigit(): - build = int(version_nums[3]) - - # Set version components with safer defaults - version_obj.major = int(version_nums[0]) if len(version_nums) > 0 and version_nums[0].isdigit() else 0 - version_obj.minor = int(version_nums[1]) if len(version_nums) > 1 and version_nums[1].isdigit() else 0 - version_obj.patch = int(version_nums[2]) if len(version_nums) > 2 and version_nums[2].isdigit() else 0 - version_obj.build = build - version_obj.branch = get_branch() - - return version_obj - - async def main_thread(self) -> None: - """Main thread for backup management.""" - rk = Ratekeeper(1, print_delay_threshold=None) - reset_progress = False - - while True: - try: - if reset_progress: - self.progress = 100.0 - self.operation = None - self.restore_status = custom.BackupManagerSP.Status.idle - self.backup_status = custom.BackupManagerSP.Status.idle - - # Check for backup command - if self.params.get_bool("BackupManager_CreateBackup"): - try: - await self.create_backup() - reset_progress = True - finally: - self.params.remove("BackupManager_CreateBackup") - - # Check for restore command - restore_version = self.params.get("BackupManager_RestoreVersion", encoding="utf8") - if restore_version: - try: - version = int(restore_version) if restore_version.isdigit() else None - await self.restore_backup(version) - reset_progress = True - finally: - self.params.remove("BackupManager_RestoreVersion") - - self._report_status() - rk.keep_time() - - except Exception as e: - cloudlog.exception(f"Error in backup manager main thread: {str(e)}") - self.last_error = str(e) - self._report_status() - rk.keep_time() - - -def main(): - import asyncio - asyncio.run(BackupManagerSP().main_thread()) - - -if __name__ == "__main__": - main() diff --git a/sunnypilot/sunnylink/backups/utils.py b/sunnypilot/sunnylink/backups/utils.py deleted file mode 100644 index bcf7ea8ebb..0000000000 --- a/sunnypilot/sunnylink/backups/utils.py +++ /dev/null @@ -1,170 +0,0 @@ -""" -Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. - -This file is part of sunnypilot and is licensed under the MIT License. -See the LICENSE.md file in the root directory for more details. -""" - -import base64 -import hashlib -import zlib -import re -import json -from pathlib import Path - -from cryptography.hazmat.backends import default_backend -from cryptography.hazmat.primitives import serialization -from cryptography.hazmat.primitives.asymmetric import rsa - -from sunnypilot.sunnylink.backups.AESCipher import AESCipher -from openpilot.system.hardware.hw import Paths - - -class KeyDerivation: - @staticmethod - def _load_key(file_path: str) -> bytes: - with open(file_path, 'rb') as f: - return f.read() - - @staticmethod - def derive_aes_key_iv_from_rsa(key_path: str, use_aes_256: bool) -> tuple[bytes, bytes]: - rsa_key_pem: bytes = KeyDerivation._load_key(key_path) - key_plain = rsa_key_pem.decode(errors="ignore") - - if "private" in key_plain.lower(): - private_key = serialization.load_pem_private_key(rsa_key_pem, password=None, backend=default_backend()) - if not isinstance(private_key, rsa.RSAPrivateKey): - raise ValueError("Invalid RSA key format: Unable to determine if key is public or private.") - - der_data = private_key.private_bytes( - encoding=serialization.Encoding.DER, - format=serialization.PrivateFormat.TraditionalOpenSSL, - encryption_algorithm=serialization.NoEncryption() - ) - elif "public" in key_plain.lower(): - public_key = serialization.load_pem_public_key(rsa_key_pem, backend=default_backend()) - if not isinstance(public_key, rsa.RSAPublicKey): - raise ValueError("Invalid RSA key format: Unable to determine if key is public or private.") - - der_data = public_key.public_bytes(encoding=serialization.Encoding.DER, format=serialization.PublicFormat.PKCS1) - else: - raise ValueError("Unknown key format: Unable to determine if key is public or private.") - - sha256_hash = hashlib.sha256(der_data).digest() - aes_key = sha256_hash[:32] if use_aes_256 else sha256_hash[:16] - aes_iv = sha256_hash[16:32] - - return aes_key, aes_iv - - -def qUncompress(data): - """ - Decompress data using zlib. - - Args: - data (bytes): Compressed data - - Returns: - bytes: Decompressed data - """ - data_stripped_4 = data[4:] - return zlib.decompress(data_stripped_4) - - -def qCompress(data): - """ - Compress data using zlib. - - Args: - data (bytes): Data to compress - - Returns: - bytes: Compressed data - """ - compressed_data = zlib.compress(data, level=9) - return b"ZLIB" + compressed_data - - -def decrypt_compressed_data(encrypted_base64, use_aes_256=False): - """ - Decrypt and decompress data from base64 string. - - Args: - encrypted_base64 (str): Base64 encoded encrypted data - key_path (str, optional): Path to RSA public key - - Returns: - str: Decrypted and decompressed string - """ - key_path = Path(f"{Paths.persist_root()}/comma/id_rsa") if use_aes_256 else Path(f"{Paths.persist_root()}/comma/id_rsa.pub") - try: - # Decode base64 - encrypted_data = base64.b64decode(encrypted_base64) - - # Decrypt - key, iv = KeyDerivation.derive_aes_key_iv_from_rsa(str(key_path), use_aes_256) - cipher = AESCipher(key, iv) - decrypted_data = cipher.decrypt(encrypted_data) - - # Decompress - decompressed_data = qUncompress(decrypted_data) - - # Decode UTF-8 - result = decompressed_data.decode('utf-8') - return result - except Exception as e: - print(f"Decryption and decompression failed: {e}") - return "" - - -def encrypt_compress_data(text, use_aes_256=True): - """ - Compress and encrypt string data to base64. - - Args: - text (str): Text to compress and encrypt - key_path (str, optional): Path to RSA public key - - Returns: - str: Base64 encoded encrypted data - """ - key_path = Path(f"{Paths.persist_root()}/comma/id_rsa") if use_aes_256 else Path(f"{Paths.persist_root()}/comma/id_rsa.pub") - try: - # Encode to UTF-8 - text_bytes = text.encode('utf-8') - - # Compress - compressed_data = qCompress(text_bytes) - - # Encrypt - key, iv = KeyDerivation.derive_aes_key_iv_from_rsa(str(key_path), use_aes_256) - cipher = AESCipher(key, iv) - encrypted_data = cipher.encrypt(compressed_data) - - # Encode to base64 - result = base64.b64encode(encrypted_data).decode('utf-8') - return result - except Exception as e: - print(f"Compression and encryption failed: {e}") - return "" - - -def camel_to_snake(name): - """Convert camelCase to snake_case.""" - name = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) - return re.sub('([a-z0-9])([A-Z])', r'\1_\2', name).lower() - - -def transform_dict(obj): - """Recursively transform dictionary keys from camelCase to snake_case.""" - if isinstance(obj, dict): - return {camel_to_snake(k): transform_dict(v) for k, v in obj.items()} - elif isinstance(obj, list): - return [transform_dict(item) for item in obj] - return obj - - -class SnakeCaseEncoder(json.JSONEncoder): - def encode(self, obj): - transformed_obj = transform_dict(obj) - return super().encode(transformed_obj) diff --git a/sunnypilot/sunnylink/registration_manager.py b/sunnypilot/sunnylink/registration_manager.py deleted file mode 100755 index 34323c2789..0000000000 --- a/sunnypilot/sunnylink/registration_manager.py +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env python3 -import time - -from openpilot.common.realtime import Ratekeeper -from openpilot.common.swaglog import cloudlog - -from cereal import log, messaging -from sunnypilot.sunnylink.utils import register_sunnylink - -NetworkType = log.DeviceState.NetworkType - - -def main(): - """The main method is expected to be called by the manager when the device boots up.""" - rk = Ratekeeper(.5) - sm = messaging.SubMaster(['deviceState'], poll='deviceState') - while True: - sm.update(1000) - if sm['deviceState'].networkType != NetworkType.none: - break - - cloudlog.info(f"Waiting to become online... {time.monotonic()}") - rk.keep_time() - - register_sunnylink() - - -if __name__ == "__main__": - main() diff --git a/sunnypilot/sunnylink/uploader.py b/sunnypilot/sunnylink/uploader.py deleted file mode 100755 index 69ef2cfd8a..0000000000 --- a/sunnypilot/sunnylink/uploader.py +++ /dev/null @@ -1,310 +0,0 @@ -#!/usr/bin/env python3 -import bz2 -import datetime -import io -import json -import os -import random -import threading -import time -import traceback -from collections.abc import Iterator -from typing import BinaryIO - -import requests -from openpilot.common.params import Params -from openpilot.common.realtime import set_core_affinity -from openpilot.common.swaglog import cloudlog -from openpilot.system.hardware.hw import Paths -from openpilot.system.loggerd.xattr_cache import getxattr, setxattr - -import cereal.messaging as messaging -from cereal import log -from sunnypilot.sunnylink.api import SunnylinkApi - -NetworkType = log.DeviceState.NetworkType -UPLOAD_ATTR_NAME = 'user.sunny.upload' - -UPLOAD_ATTR_VALUE = b'1' - -UPLOAD_QLOG_QCAM_MAX_SIZE = 5 * 1e6 # MB - -allow_sleep = bool(os.getenv("UPLOADER_SLEEP", "1")) -force_wifi = os.getenv("FORCEWIFI") is not None -fake_upload = os.getenv("FAKEUPLOAD") is not None - -OFFROAD_TRANSITION_TIMEOUT = 900. # wait until offroad for 15 minutes before allowing uploads - - -class FakeRequest: - def __init__(self): - self.headers = {"Content-Length": "0"} - - -class FakeResponse: - def __init__(self): - self.status_code = 200 - self.request = FakeRequest() - - -def get_directory_sort(d: str) -> list[str]: - # ensure old format is sorted sooner - o = ["0", ] if d.startswith("2024-") else ["1", ] - return o + [s.rjust(10, '0') for s in d.rsplit('--', 1)] - - -def listdir_by_creation(d: str) -> list[str]: - if not os.path.isdir(d): - return [] - - try: - paths = [f for f in os.listdir(d) if os.path.isdir(os.path.join(d, f))] - paths = sorted(paths, key=get_directory_sort) - return paths - except OSError: - cloudlog.exception("listdir_by_creation failed") - return [] - - -def clear_locks(root: str) -> None: - for logdir in os.listdir(root): - path = os.path.join(root, logdir) - try: - for fname in os.listdir(path): - if fname.endswith(".lock"): - os.unlink(os.path.join(path, fname)) - except OSError: - cloudlog.exception("clear_locks failed") - - -class Uploader: - def __init__(self, dongle_id: str, root: str): - self.dongle_id = dongle_id - self.api = SunnylinkApi(dongle_id) - self.root = root - - self.params = Params() - - # stats for last successfully uploaded file - self.last_filename = "" - - self.immediate_folders = ["crash/", "boot/"] - self.immediate_priority = {"qlog": 0, "qlog.bz2": 0, "qcamera.ts": 1} - - def list_upload_files(self, metered: bool) -> Iterator[tuple[str, str, str]]: - r = self.params.get("AthenadRecentlyViewedRoutes", encoding="utf8") - requested_routes = [] if r is None else r.split(",") - - for logdir in listdir_by_creation(self.root): - path = os.path.join(self.root, logdir) - try: - names = os.listdir(path) - except OSError: - continue - - if any(name.endswith(".lock") for name in names): - continue - - for name in sorted(names, key=lambda n: self.immediate_priority.get(n, 1000)): - key = os.path.join(logdir, name) - fn = os.path.join(path, name) - # skip files already uploaded - try: - ctime = os.path.getctime(fn) - is_uploaded = getxattr(fn, UPLOAD_ATTR_NAME) == UPLOAD_ATTR_VALUE - except OSError: - cloudlog.event("uploader_getxattr_failed", key=key, fn=fn) - # deleter could have deleted, so skip - continue - if is_uploaded: - continue - - # limit uploading on metered connections - if metered: - dt = datetime.timedelta(hours=12) - if logdir in self.immediate_folders and (datetime.datetime.now() - datetime.datetime.fromtimestamp(ctime)) < dt: - continue - - if name == "qcamera.ts" and not any(logdir.startswith(r.split('|')[-1]) for r in requested_routes): - continue - - yield name, key, fn - - def next_file_to_upload(self, metered: bool) -> tuple[str, str, str] | None: - upload_files = list(self.list_upload_files(metered)) - - for name, key, fn in upload_files: - if any(f in fn for f in self.immediate_folders): - return name, key, fn - - return next( - ((name, key, fn) - for name, key, fn in upload_files if name in self.immediate_priority), - None, - ) - - def do_upload(self, key: str, fn: str): - url_resp = self.api.get( - f"device/{self.dongle_id}/upload_url/", - timeout=10, - path=key, - access_token=self.api.get_token(), - ) - if url_resp.status_code == 412: - return url_resp - - url_resp_json = json.loads(url_resp.text) - url = url_resp_json['url'] - headers = url_resp_json['headers'] - cloudlog.debug("sunnylink upload_url %s | Headers: %s", url, headers) - - if fake_upload: - return FakeResponse() - - with open(fn, "rb") as f: - data: BinaryIO - if key.endswith('.bz2') and not fn.endswith('.bz2'): - compressed = bz2.compress(f.read()) - data = io.BytesIO(compressed) - else: - data = f - - return requests.put(url, data=data, headers=headers, timeout=10) - - def upload(self, name: str, key: str, fn: str, network_type: int, metered: bool) -> bool: - try: - sz = os.path.getsize(fn) - except OSError: - cloudlog.exception("upload: getsize failed") - return False - - cloudlog.event("upload_start", key=key, fn=fn, sz=sz, network_type=network_type, metered=metered) - - if sz == 0: - # tag files of 0 size as uploaded - success = True - elif name in self.immediate_priority and sz > UPLOAD_QLOG_QCAM_MAX_SIZE: - cloudlog.event("uploader_too_large", key=key, fn=fn, sz=sz) - success = True - else: - start_time = time.monotonic() - - stat = None - last_exc = None - try: - stat = self.do_upload(key, fn) - except Exception as e: - last_exc = (e, traceback.format_exc()) - - if stat is not None and stat.status_code in (200, 201, 412): - self.last_filename = fn - dt = time.monotonic() - start_time - if stat.status_code == 412: - cloudlog.event("upload_ignored", key=key, fn=fn, sz=sz, network_type=network_type, metered=metered) - else: - content_length = int(stat.request.headers.get("Content-Length", 0)) - speed = (content_length / 1e6) / dt - cloudlog.event("upload_success", key=key, fn=fn, sz=sz, content_length=content_length, - network_type=network_type, metered=metered, speed=speed) - success = True - elif stat is not None: # 401, 403... Not sure why they were up to begin with - success = False - cloudlog.event("upload_failed with content", stat=stat, exc=last_exc, key=key, fn=fn, sz=sz, network_type=network_type, metered=metered, - error=stat.content.decode("utf-8")) - else: - success = False - cloudlog.event("upload_failed", stat=stat, exc=last_exc, key=key, fn=fn, sz=sz, network_type=network_type, metered=metered) - - if success: - # tag file as uploaded - try: - setxattr(fn, UPLOAD_ATTR_NAME, UPLOAD_ATTR_VALUE) - except OSError: - cloudlog.event("uploader_setxattr_failed", exc=last_exc, key=key, fn=fn, sz=sz) - - return success - - def step(self, network_type: int, metered: bool) -> bool | None: - d = self.next_file_to_upload(metered) - if d is None: - return None - - name, key, fn = d - - # qlogs and bootlogs need to be compressed before uploading - if key.endswith(('qlog', 'rlog')) or (key.startswith('boot/') and not key.endswith('.bz2')): - key += ".bz2" - - return self.upload(name, key, fn, network_type, metered) - - -def main(exit_event: threading.Event = None) -> None: - if exit_event is None: - exit_event = threading.Event() - - try: - set_core_affinity([0, 1, 2, 3]) - except Exception: - cloudlog.exception("failed to set core affinity") - - clear_locks(Paths.log_root()) - - params = Params() - dongle_id = params.get("SunnylinkDongleId", encoding='utf8') - - offroad_transition_prev = 0. - offroad_last = False - - if dongle_id is None: - cloudlog.info("uploader missing dongle_id") - raise Exception("uploader can't start without dongle id") - - sm = messaging.SubMaster(['deviceState']) - uploader = Uploader(dongle_id, Paths.log_root()) - - backoff = 0.1 - while not exit_event.is_set(): - sm.update(0) - - offroad = params.get_bool("IsOffroad") - t = time.monotonic() - if offroad and not offroad_last and t > 300.: - offroad_transition_prev = time.monotonic() - offroad_last = offroad - - network_type = NetworkType.wifi if force_wifi else sm['deviceState'].networkType - if network_type == NetworkType.none: - if allow_sleep: - time.sleep(60 if offroad else 5) - continue - - if params.get_bool("DisableOnroadUploads"): - if not offroad or (offroad_transition_prev > 0. and t - offroad_transition_prev < OFFROAD_TRANSITION_TIMEOUT): - if not offroad: - cloudlog.info("not uploading: onroad uploads disabled") - else: - wait_minutes = int(OFFROAD_TRANSITION_TIMEOUT / 60) - time_left = OFFROAD_TRANSITION_TIMEOUT - (t - offroad_transition_prev) - if time_left > 2.0 * 60.0: - time_left_str = f"{int(time_left / 60)} minute(s)" - else: - time_left_str = f"{int(time_left)} seconds(s)" - cloudlog.info(f"not uploading: waiting until offroad for {wait_minutes} minutes; {time_left_str} left") - if allow_sleep: - time.sleep(60) - continue - - success = uploader.step(sm['deviceState'].networkType.raw, sm['deviceState'].networkMetered) - if success is None: - backoff = 60 if offroad else 5 - elif success: - backoff = 0.1 - else: - cloudlog.info("upload backoff %r", backoff) - backoff = min(backoff * 2, 120) - if allow_sleep: - time.sleep(backoff + random.uniform(0, backoff)) - - -if __name__ == "__main__": - main() diff --git a/sunnypilot/sunnylink/utils.py b/sunnypilot/sunnylink/utils.py deleted file mode 100644 index 55b1f6f285..0000000000 --- a/sunnypilot/sunnylink/utils.py +++ /dev/null @@ -1,57 +0,0 @@ -from sunnypilot.sunnylink.api import SunnylinkApi, UNREGISTERED_SUNNYLINK_DONGLE_ID -from openpilot.common.params import Params -from openpilot.system.version import is_prebuilt - - -def get_sunnylink_status(params=None) -> tuple[bool, bool]: - """Get the status of Sunnylink on the device. Returns a tuple of (is_sunnylink_enabled, is_registered).""" - params = params or Params() - is_sunnylink_enabled = params.get_bool("SunnylinkEnabled") - is_registered = params.get("SunnylinkDongleId", encoding='utf-8') not in (None, UNREGISTERED_SUNNYLINK_DONGLE_ID) - return is_sunnylink_enabled, is_registered - - -def sunnylink_ready(params=None) -> bool: - """Check if the device is ready to communicate with Sunnylink. That means it is enabled and registered.""" - params = params or Params() - is_sunnylink_enabled, is_registered = get_sunnylink_status(params) - return is_sunnylink_enabled and is_registered - - -def use_sunnylink_uploader(params) -> bool: - """Check if the device is ready to use Sunnylink and the uploader is enabled.""" - return sunnylink_ready(params) and params.get_bool("EnableSunnylinkUploader") - - -def sunnylink_need_register(params=None) -> bool: - """Check if the device needs to be registered with Sunnylink.""" - params = params or Params() - is_sunnylink_enabled, is_registered = get_sunnylink_status(params) - return is_sunnylink_enabled and not is_registered - - -def register_sunnylink(): - """Register the device with Sunnylink if it is enabled.""" - extra_args = {} - - if not Params().get_bool("SunnylinkEnabled"): - print("Sunnylink is not enabled. Exiting.") - exit(0) - - if not is_prebuilt(): - extra_args = { - "verbose": True, - "timeout": 60 - } - - sunnylink_id = SunnylinkApi(None).register_device(None, **extra_args) - print(f"SunnyLinkId: {sunnylink_id}") - - -def get_api_token(): - """Get the API token for the device.""" - params = Params() - sunnylink_dongle_id = params.get("SunnylinkDongleId", encoding='utf-8') - sunnylink_api = SunnylinkApi(sunnylink_dongle_id) - token = sunnylink_api.get_token() - print(f"API Token: {token}") diff --git a/system/athena/registration.py b/system/athena/registration.py deleted file mode 100755 index fce984c03a..0000000000 --- a/system/athena/registration.py +++ /dev/null @@ -1,106 +0,0 @@ -#!/usr/bin/env python3 -import time -import json -import jwt -from pathlib import Path - -from datetime import datetime, timedelta, UTC -from openpilot.common.api import api_get -from openpilot.common.params import Params -from openpilot.common.spinner import Spinner -from openpilot.selfdrive.selfdrived.alertmanager import set_offroad_alert -from openpilot.system.hardware import HARDWARE, PC -from openpilot.system.hardware.hw import Paths -from openpilot.common.swaglog import cloudlog - - -UNREGISTERED_DONGLE_ID = "UnregisteredDevice" - -def is_registered_device() -> bool: - dongle = Params().get("DongleId", encoding='utf-8') - return dongle not in (None, UNREGISTERED_DONGLE_ID) - - -def register(show_spinner=False) -> str | None: - """ - All devices built since March 2024 come with all - info stored in /persist/. This is kept around - only for devices built before then. - - With a backend update to take serial number instead - of dongle ID to some endpoints, this can be removed - entirely. - """ - params = Params() - - dongle_id: str | None = params.get("DongleId", encoding='utf8') - if dongle_id is None and Path(Paths.persist_root()+"/comma/dongle_id").is_file(): - # not all devices will have this; added early in comma 3X production (2/28/24) - with open(Paths.persist_root()+"/comma/dongle_id") as f: - dongle_id = f.read().strip() - - pubkey = Path(Paths.persist_root()+"/comma/id_rsa.pub") - if not pubkey.is_file(): - dongle_id = UNREGISTERED_DONGLE_ID - cloudlog.warning(f"missing public key: {pubkey}") - elif dongle_id is None: - if show_spinner: - spinner = Spinner() - spinner.update("registering device") - - # Create registration token, in the future, this key will make JWTs directly - with open(Paths.persist_root()+"/comma/id_rsa.pub") as f1, open(Paths.persist_root()+"/comma/id_rsa") as f2: - public_key = f1.read() - private_key = f2.read() - - # Block until we get the imei - serial = HARDWARE.get_serial() - start_time = time.monotonic() - imei1: str | None = None - imei2: str | None = None - while imei1 is None and imei2 is None: - try: - imei1, imei2 = HARDWARE.get_imei(0), HARDWARE.get_imei(1) - except Exception: - cloudlog.exception("Error getting imei, trying again...") - time.sleep(1) - - if time.monotonic() - start_time > 60 and show_spinner: - spinner.update(f"registering device - serial: {serial}, IMEI: ({imei1}, {imei2})") - - backoff = 0 - start_time = time.monotonic() - while True: - try: - register_token = jwt.encode({'register': True, 'exp': datetime.now(UTC).replace(tzinfo=None) + timedelta(hours=1)}, private_key, algorithm='RS256') - cloudlog.info("getting pilotauth") - resp = api_get("v2/pilotauth/", method='POST', timeout=15, - imei=imei1, imei2=imei2, serial=serial, public_key=public_key, register_token=register_token) - - if resp.status_code in (402, 403): - cloudlog.info(f"Unable to register device, got {resp.status_code}") - dongle_id = UNREGISTERED_DONGLE_ID - else: - dongleauth = json.loads(resp.text) - dongle_id = dongleauth["dongle_id"] - break - except Exception: - cloudlog.exception("failed to authenticate") - backoff = min(backoff + 1, 15) - time.sleep(backoff) - - if time.monotonic() - start_time > 60 and show_spinner: - spinner.update(f"registering device - serial: {serial}, IMEI: ({imei1}, {imei2})") - return UNREGISTERED_DONGLE_ID # hotfix to prevent an infinite wait for registration - - if show_spinner: - spinner.close() - - if dongle_id: - params.put("DongleId", dongle_id) - set_offroad_alert("Offroad_UnofficialHardware", (dongle_id == UNREGISTERED_DONGLE_ID) and not PC) - return dongle_id - - -if __name__ == "__main__": - print(register()) diff --git a/system/camerad/SConscript b/system/camerad/SConscript deleted file mode 100644 index fe5cf87b78..0000000000 --- a/system/camerad/SConscript +++ /dev/null @@ -1,11 +0,0 @@ -Import('env', 'arch', 'messaging', 'common', 'gpucommon', 'visionipc') - -libs = [common, 'OpenCL', messaging, visionipc, gpucommon] - -if arch != "Darwin": - camera_obj = env.Object(['cameras/camera_qcom2.cc', 'cameras/camera_common.cc', 'cameras/spectra.cc', - 'cameras/cdm.cc', 'sensors/ar0231.cc', 'sensors/ox03c10.cc', 'sensors/os04c10.cc']) - env.Program('camerad', ['main.cc', camera_obj], LIBS=libs) - -if GetOption("extras") and arch == "x86_64": - env.Program('test/test_ae_gray', ['test/test_ae_gray.cc', camera_obj], LIBS=libs) diff --git a/system/camerad/cameras/bps_blobs.h b/system/camerad/cameras/bps_blobs.h deleted file mode 100644 index 54941b8d76..0000000000 --- a/system/camerad/cameras/bps_blobs.h +++ /dev/null @@ -1,30 +0,0 @@ -#include -#include - - -/* ********************************************************** - THIS FILE IS AUTO-GENERATED, DO NOT EDIT DIRECTLY! - ********************************************************** */ - - -unsigned char bps_cfg[4][768] = { -{ /* placeholder */ }, - {0x3, 0x0, 0x0, 0x0, 0x88, 0x7, 0x0, 0x0, 0xB8, 0x4, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x50, 0xB, 0x0, 0x0, 0xB8, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x14, 0x0, 0x0, 0x0, 0x88, 0x7, 0x0, 0x0, 0xB8, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8, 0x0, 0x0, 0xC0, 0x4, 0x0, 0x0, 0x0, 0x8, 0x0, 0x0, 0x60, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, - {0x3, 0x0, 0x0, 0x0, 0x88, 0x7, 0x0, 0x0, 0xB8, 0x4, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x50, 0xB, 0x0, 0x0, 0xB8, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x14, 0x0, 0x0, 0x0, 0x88, 0x7, 0x0, 0x0, 0xB8, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8, 0x0, 0x0, 0xC0, 0x4, 0x0, 0x0, 0x0, 0x8, 0x0, 0x0, 0x60, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, - {0x3, 0x0, 0x0, 0x0, 0x40, 0x5, 0x0, 0x0, 0xF8, 0x2, 0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xE0, 0x7, 0x0, 0x0, 0xF8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x14, 0x0, 0x0, 0x0, 0x40, 0x5, 0x0, 0x0, 0xF8, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x80, 0x5, 0x0, 0x0, 0x0, 0x3, 0x0, 0x0, 0x80, 0x5, 0x0, 0x0, 0x80, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, -}; - -unsigned char bps_striping_output[4][0x9a0] = { -{ /* placeholder */ }, - {0x5, 0x0, 0x6, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x4, 0x0, 0x0, 0xFF, 0xFF, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x4, 0x0, 0x0, 0xB7, 0x4, 0x0, 0x0, 0xB7, 0x4, 0x0, 0x0, 0x5B, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x4, 0x0, 0x0, 0x5B, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0xB8, 0x4, 0x5C, 0x2, 0x0, 0x0, 0x3, 0x0, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x5, 0x0, 0x0, 0x0, 0x70, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC0, 0x89, 0x23, 0x0, 0x1, 0x0, 0x0, 0x0, 0xCC, 0x5, 0x87, 0x7, 0x0, 0x0, 0x0, 0x0, 0xD0, 0x5, 0x87, 0x7, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0xB, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0xB8, 0x1, 0xDC, 0x0, 0x0, 0x0, 0x3, 0x0, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8, 0x2, 0xA4, 0xFD, 0x50, 0xB1, 0x9, 0x0, 0x8, 0x0, 0x33, 0x0, 0x8, 0x2, 0xA4, 0xFD, 0x50, 0xB1, 0x9, 0x0, 0x8, 0x0, 0x33, 0x0, 0x0, 0x0, 0x0, 0x0, 0x6, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xE, 0x2, 0xA6, 0xFD, 0x68, 0xC0, 0x9, 0x0, 0x8, 0x0, 0x34, 0x0, 0xD0, 0x5, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x1C, 0x8, 0x0, 0x14, 0x4, 0xD3, 0x5, 0x0, 0x0, 0x0, 0x0, 0x18, 0x4, 0xCF, 0x5, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0xB, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0xB8, 0x1, 0xDC, 0x0, 0x0, 0x0, 0x3, 0x0, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x50, 0x0, 0xA4, 0xFD, 0x10, 0xAA, 0x5, 0x0, 0x8, 0x0, 0x33, 0x0, 0x50, 0x0, 0xA4, 0xFD, 0x10, 0xAA, 0x5, 0x0, 0x8, 0x0, 0x33, 0x0, 0x0, 0x0, 0x0, 0x0, 0xA, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x56, 0x0, 0xA6, 0xFD, 0x88, 0xA4, 0x5, 0x0, 0x8, 0x0, 0x34, 0x0, 0x18, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x1C, 0x8, 0x0, 0x5C, 0x2, 0x1B, 0x4, 0x0, 0x0, 0x0, 0x0, 0x60, 0x2, 0x17, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0xB, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0xB8, 0x1, 0xDC, 0x0, 0x0, 0x0, 0x3, 0x0, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x98, 0xFE, 0xA4, 0xFD, 0x50, 0x8B, 0x7, 0x0, 0x8, 0x0, 0x33, 0x0, 0x98, 0xFE, 0xA4, 0xFD, 0x50, 0x8B, 0x7, 0x0, 0x8, 0x0, 0x33, 0x0, 0x0, 0x0, 0x0, 0x0, 0xE, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x9E, 0xFE, 0xA6, 0xFD, 0x28, 0x71, 0x7, 0x0, 0x8, 0x0, 0x34, 0x0, 0x60, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x1C, 0x8, 0x0, 0xC0, 0x0, 0x63, 0x2, 0x0, 0x0, 0x0, 0x0, 0xC4, 0x0, 0x5F, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0xB, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x9B, 0x1, 0x0, 0x0, 0x9B, 0x1, 0x0, 0x0, 0x9B, 0x1, 0x0, 0x0, 0x9B, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x9B, 0x1, 0x0, 0x0, 0x9B, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0x9C, 0x1, 0xCE, 0x0, 0x0, 0x0, 0x3, 0x0, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFC, 0xFC, 0xA4, 0xFD, 0x20, 0xA9, 0xE, 0x0, 0x8, 0x0, 0x33, 0x0, 0xFC, 0xFC, 0xA4, 0xFD, 0x20, 0xA9, 0xE, 0x0, 0x8, 0x0, 0x33, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2, 0xFD, 0xA6, 0xFD, 0xA8, 0x7B, 0xE, 0x0, 0x8, 0x0, 0x34, 0x0, 0xC4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x20, 0x98, 0x7, 0x0, 0x0, 0x0, 0xC7, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0xB, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC3, 0x0, 0x0, 0x0, 0xC3, 0x0, 0x0, 0x0, 0xC3, 0x0, 0x0, 0x0, 0xC3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC3, 0x0, 0x0, 0x0, 0xC3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0xC4, 0x0, 0x62, 0x0, 0x0, 0x0, 0x3, 0x0, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0xF4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x3C, 0xFC, 0xA4, 0xFD, 0x20, 0xBF, 0x13, 0x0, 0x8, 0x0, 0x33, 0x0, 0x3C, 0xFC, 0xA4, 0xFD, 0x20, 0xBF, 0x13, 0x0, 0x8, 0x0, 0x33, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x3E, 0xFC, 0xA6, 0xFD, 0xA8, 0xA6, 0x13, 0x0, 0x8, 0x0, 0x34, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xE0, 0x9C, 0x3, 0x0, 0x20, 0x4, 0x1, 0x0, 0x5D, 0x59, 0xAB, 0x0, 0xC8, 0x8C, 0xFD, 0xF4, 0x3, 0x0, 0x0, 0x0, 0xB8, 0x13, 0xFD, 0xFF, 0xAC, 0x5F, 0x8C, 0xF5, 0x0, 0x20, 0x4E, 0x0, 0xAB, 0xAA, 0xAA, 0xAA, 0x40, 0x69, 0xFD, 0xF4, 0x0, 0x0, 0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x38, 0x6B, 0x8B, 0xF5, 0x11, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x9F, 0x9, 0x0, 0x0, 0xB8, 0x2B, 0x6B, 0x15, 0xC0, 0x6A, 0x8C, 0xF5, 0x0, 0x0, 0x0, 0x0, 0xB8, 0x13, 0xFD, 0xFF, 0x2A, 0x5, 0x1, 0x0, 0xC0, 0x13, 0xFD, 0xFF, 0x2C, 0x14, 0xFD, 0xFF, 0x14, 0x14, 0xFD, 0xFF, 0xCC, 0xE8, 0x89, 0xF5, 0xC0, 0x13, 0xFD, 0xFF, 0x64, 0x6A, 0x8C, 0xF5, 0x3, 0x0, 0x0, 0x0, 0xA0, 0x6B, 0x8B, 0xF5, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x8, 0x69, 0x8C, 0xF5, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC0, 0x6A, 0x8C, 0xF5, 0x8, 0x69, 0x8C, 0xF5, 0xFF, 0xFF, 0xFF, 0xFF, 0xA0, 0x9, 0x0, 0x0, 0xF8, 0xB2, 0xFD, 0xF4, 0x50, 0x35, 0x8C, 0xF5, 0xD0, 0x14, 0xC1, 0xF4, 0x1, 0xD0, 0x3B, 0xF5, 0x64, 0x1F, 0xFD, 0xFF, 0xD0, 0xAD, 0x4, 0xF5, 0x2C, 0x30, 0x1, 0x0, 0x0, 0x10, 0x0, 0x0, 0x2C, 0x0, 0x0, 0x0, 0x14, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x4C, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC, 0x30, 0x1, 0x0, 0xD0, 0x14, 0xC1, 0xF4, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x10, 0x1F, 0xFD, 0xFF, 0x3C, 0x23, 0xFD, 0x34, 0x31, 0x32, 0x31, 0x36, 0xA0, 0x6B, 0x8B, 0xF5, 0x60, 0x14, 0xFD, 0xFF, 0x0, 0x30, 0x1, 0x0, 0x14, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x4C, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x10, 0x1F, 0xFD, 0xFF, 0x3C, 0x23, 0xFD, 0xFF, 0xC0, 0xDC, 0x1, 0xF5, 0x4C, 0x0, 0x0, 0x0, 0x54, 0x14, 0xFD, 0xFF, 0x50, 0x1D, 0x1, 0x0, 0x30, 0x14, 0x1, 0x0, 0x98, 0x1D, 0x1, 0x0, 0x0, 0xA1, 0x0, 0x0, 0x0, 0xA1, 0x0, 0x0, 0x98, 0x1D, 0x1, 0x0, 0x6C, 0x1F, 0xFD, 0xFF, 0x64, 0x1F, 0xFD, 0xFF, 0x68, 0x1F, 0xFD, 0xFF, 0x0, 0x0, 0x0, 0x0}, - {0x5, 0x0, 0x6, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x4, 0x0, 0x0, 0xFF, 0xFF, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x4, 0x0, 0x0, 0xB7, 0x4, 0x0, 0x0, 0xB7, 0x4, 0x0, 0x0, 0x5B, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x4, 0x0, 0x0, 0x5B, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0xB8, 0x4, 0x5C, 0x2, 0x0, 0x0, 0x3, 0x0, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x5, 0x0, 0x0, 0x0, 0x70, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC0, 0x89, 0x23, 0x0, 0x1, 0x0, 0x0, 0x0, 0xCC, 0x5, 0x87, 0x7, 0x0, 0x0, 0x0, 0x0, 0xD0, 0x5, 0x87, 0x7, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0xB, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0xB8, 0x1, 0xDC, 0x0, 0x0, 0x0, 0x3, 0x0, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8, 0x2, 0xA4, 0xFD, 0x50, 0xB1, 0x9, 0x0, 0x8, 0x0, 0x33, 0x0, 0x8, 0x2, 0xA4, 0xFD, 0x50, 0xB1, 0x9, 0x0, 0x8, 0x0, 0x33, 0x0, 0x0, 0x0, 0x0, 0x0, 0x6, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xE, 0x2, 0xA6, 0xFD, 0x68, 0xC0, 0x9, 0x0, 0x8, 0x0, 0x34, 0x0, 0xD0, 0x5, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x1C, 0x8, 0x0, 0x14, 0x4, 0xD3, 0x5, 0x0, 0x0, 0x0, 0x0, 0x18, 0x4, 0xCF, 0x5, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0xB, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0xB8, 0x1, 0xDC, 0x0, 0x0, 0x0, 0x3, 0x0, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x50, 0x0, 0xA4, 0xFD, 0x10, 0xAA, 0x5, 0x0, 0x8, 0x0, 0x33, 0x0, 0x50, 0x0, 0xA4, 0xFD, 0x10, 0xAA, 0x5, 0x0, 0x8, 0x0, 0x33, 0x0, 0x0, 0x0, 0x0, 0x0, 0xA, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x56, 0x0, 0xA6, 0xFD, 0x88, 0xA4, 0x5, 0x0, 0x8, 0x0, 0x34, 0x0, 0x18, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x1C, 0x8, 0x0, 0x5C, 0x2, 0x1B, 0x4, 0x0, 0x0, 0x0, 0x0, 0x60, 0x2, 0x17, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0xB, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0xB8, 0x1, 0xDC, 0x0, 0x0, 0x0, 0x3, 0x0, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x98, 0xFE, 0xA4, 0xFD, 0x50, 0x8B, 0x7, 0x0, 0x8, 0x0, 0x33, 0x0, 0x98, 0xFE, 0xA4, 0xFD, 0x50, 0x8B, 0x7, 0x0, 0x8, 0x0, 0x33, 0x0, 0x0, 0x0, 0x0, 0x0, 0xE, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x9E, 0xFE, 0xA6, 0xFD, 0x28, 0x71, 0x7, 0x0, 0x8, 0x0, 0x34, 0x0, 0x60, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x1C, 0x8, 0x0, 0xC0, 0x0, 0x63, 0x2, 0x0, 0x0, 0x0, 0x0, 0xC4, 0x0, 0x5F, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0xB, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x9B, 0x1, 0x0, 0x0, 0x9B, 0x1, 0x0, 0x0, 0x9B, 0x1, 0x0, 0x0, 0x9B, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x9B, 0x1, 0x0, 0x0, 0x9B, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0x9C, 0x1, 0xCE, 0x0, 0x0, 0x0, 0x3, 0x0, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFC, 0xFC, 0xA4, 0xFD, 0x20, 0xA9, 0xE, 0x0, 0x8, 0x0, 0x33, 0x0, 0xFC, 0xFC, 0xA4, 0xFD, 0x20, 0xA9, 0xE, 0x0, 0x8, 0x0, 0x33, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2, 0xFD, 0xA6, 0xFD, 0xA8, 0x7B, 0xE, 0x0, 0x8, 0x0, 0x34, 0x0, 0xC4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x20, 0x98, 0x7, 0x0, 0x0, 0x0, 0xC7, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0xB, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC3, 0x0, 0x0, 0x0, 0xC3, 0x0, 0x0, 0x0, 0xC3, 0x0, 0x0, 0x0, 0xC3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC3, 0x0, 0x0, 0x0, 0xC3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0xC4, 0x0, 0x62, 0x0, 0x0, 0x0, 0x3, 0x0, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0xF4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x3C, 0xFC, 0xA4, 0xFD, 0x20, 0xBF, 0x13, 0x0, 0x8, 0x0, 0x33, 0x0, 0x3C, 0xFC, 0xA4, 0xFD, 0x20, 0xBF, 0x13, 0x0, 0x8, 0x0, 0x33, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x3E, 0xFC, 0xA6, 0xFD, 0xA8, 0xA6, 0x13, 0x0, 0x8, 0x0, 0x34, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xE0, 0x9C, 0x3, 0x0, 0x20, 0x4, 0x1, 0x0, 0xA0, 0x9, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8, 0x60, 0x5D, 0x1, 0x0, 0x0, 0x0, 0x0, 0x7, 0x0, 0x0, 0x0, 0xFC, 0x57, 0x12, 0xF5, 0x0, 0x0, 0x0, 0x0, 0x0, 0x50, 0x12, 0xF5, 0x0, 0x0, 0x0, 0x0, 0x9F, 0x9, 0x0, 0x0, 0x5E, 0x0, 0x0, 0x0, 0x5F, 0x0, 0x0, 0x0, 0x6E, 0x0, 0x0, 0x0, 0x77, 0x0, 0x0, 0x0, 0x7C, 0x0, 0x0, 0x0, 0x35, 0x1, 0x0, 0x0, 0x26, 0x0, 0x0, 0x0, 0xA4, 0x61, 0x5D, 0x1, 0x58, 0x3, 0x0, 0x0, 0xC0, 0x13, 0xFD, 0xFF, 0x64, 0x6A, 0x8C, 0xF5, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x50, 0x12, 0xF5, 0x9F, 0x9, 0x0, 0x0, 0xA0, 0x9, 0x0, 0x0, 0xFC, 0x57, 0x12, 0xF5, 0x33, 0x1, 0x0, 0x0, 0xD0, 0x14, 0xC1, 0xF4, 0x1, 0xD0, 0x3B, 0xF5, 0x64, 0x1F, 0xFD, 0xFF, 0xD0, 0xAD, 0x4, 0xF5, 0x2C, 0x30, 0x1, 0x0, 0x0, 0x10, 0x0, 0x0, 0x2C, 0x0, 0x0, 0x0, 0x14, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x4C, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x4C, 0x27, 0x5E, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC0, 0x0, 0x0, 0x0, 0x6, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x34, 0x31, 0x32, 0x31, 0x36, 0x10, 0x20, 0xFD, 0xFF, 0x60, 0x14, 0xFD, 0xFF, 0x0, 0x30, 0x1, 0x0, 0xA0, 0x9, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x4C, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x10, 0x1F, 0xFD, 0xFF, 0x3C, 0x23, 0xFD, 0xFF, 0xC0, 0xDC, 0x1, 0xF5, 0x0, 0x30, 0x1, 0x0, 0x54, 0x14, 0xFD, 0xFF, 0x0, 0x0, 0x0, 0x0, 0x30, 0x14, 0x1, 0x0, 0x98, 0x1D, 0x1, 0x0, 0x0, 0xA1, 0x0, 0x0, 0x0, 0xA1, 0x0, 0x0, 0x98, 0x1D, 0x1, 0x0, 0x6C, 0x1F, 0xFD, 0xFF, 0x64, 0x1F, 0xFD, 0xFF, 0x68, 0x1F, 0xFD, 0xFF, 0x0, 0x0, 0x0, 0x0}, - {0x4, 0x0, 0x4, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0xF7, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xF7, 0x2, 0x0, 0x0, 0xFF, 0xFF, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xF7, 0x2, 0x0, 0x0, 0xF7, 0x2, 0x0, 0x0, 0xF7, 0x2, 0x0, 0x0, 0x7B, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xF7, 0x2, 0x0, 0x0, 0x7B, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xF7, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0xF8, 0x2, 0x7C, 0x1, 0x0, 0x0, 0x3, 0x0, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x4, 0x0, 0x2, 0x0, 0x70, 0x1, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x50, 0x0, 0xA4, 0xFD, 0x10, 0xAA, 0x5, 0x0, 0x8, 0x0, 0x33, 0x0, 0x50, 0x0, 0xA4, 0xFD, 0x10, 0xAA, 0x5, 0x0, 0x8, 0x0, 0x33, 0x0, 0x0, 0x0, 0x0, 0x0, 0xA, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x56, 0x0, 0xA6, 0xFD, 0x88, 0xA4, 0x5, 0x0, 0x8, 0x0, 0x34, 0x0, 0x18, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x24, 0x0, 0x0, 0x0, 0x78, 0x14, 0x5E, 0x1, 0xB8, 0x5D, 0x12, 0xF5, 0xDC, 0x3B, 0x12, 0xF5, 0x24, 0x0, 0x0, 0x0, 0xFC, 0xF9, 0x3, 0xF5, 0x0, 0x96, 0xF, 0x0, 0x1, 0x5, 0x0, 0x0, 0x84, 0x3, 0x3F, 0x5, 0x0, 0x0, 0x0, 0x0, 0x88, 0x3, 0x3F, 0x5, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0xB, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0xB8, 0x1, 0xDC, 0x0, 0x0, 0x0, 0x3, 0x0, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xE4, 0x0, 0x84, 0xFE, 0x20, 0xFF, 0x2, 0x0, 0x7, 0x0, 0x38, 0x0, 0xE4, 0x0, 0x84, 0xFE, 0x20, 0xFF, 0x2, 0x0, 0x7, 0x0, 0x38, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xEA, 0x0, 0x86, 0xFE, 0x8, 0x4, 0x3, 0x0, 0x7, 0x0, 0x38, 0x0, 0x88, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x1A, 0x5, 0x0, 0xCC, 0x1, 0x8B, 0x3, 0x0, 0x0, 0x0, 0x0, 0xD0, 0x1, 0x87, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0xB, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0xB7, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0xB8, 0x1, 0xDC, 0x0, 0x0, 0x0, 0x3, 0x0, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2C, 0xFF, 0x84, 0xFE, 0xA0, 0xE3, 0x2, 0x0, 0x7, 0x0, 0x38, 0x0, 0x2C, 0xFF, 0x84, 0xFE, 0xA0, 0xE3, 0x2, 0x0, 0x7, 0x0, 0x38, 0x0, 0x0, 0x0, 0x0, 0x0, 0x6, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x32, 0xFF, 0x86, 0xFE, 0xE8, 0xD3, 0x2, 0x0, 0x7, 0x0, 0x38, 0x0, 0xD0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x1A, 0x5, 0x0, 0xC0, 0x0, 0xD3, 0x1, 0x0, 0x0, 0x0, 0x0, 0xC4, 0x0, 0xCF, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0xB, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB, 0x1, 0x0, 0x0, 0xB, 0x1, 0x0, 0x0, 0xB, 0x1, 0x0, 0x0, 0xB, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xB, 0x1, 0x0, 0x0, 0xB, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0xC, 0x1, 0x86, 0x0, 0x0, 0x0, 0x3, 0x0, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0xF4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x20, 0xFE, 0x84, 0xFE, 0x10, 0xB8, 0x5, 0x0, 0x7, 0x0, 0x38, 0x0, 0x20, 0xFE, 0x84, 0xFE, 0x10, 0xB8, 0x5, 0x0, 0x7, 0x0, 0x38, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x26, 0xFE, 0x86, 0xFE, 0xC8, 0x9B, 0x5, 0x0, 0x7, 0x0, 0x38, 0x0, 0xC4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xA0, 0x1B, 0x3, 0x0, 0x0, 0x0, 0xC7, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0xB, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC3, 0x0, 0x0, 0x0, 0xC3, 0x0, 0x0, 0x0, 0xC3, 0x0, 0x0, 0x0, 0xC3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC3, 0x0, 0x0, 0x0, 0xC3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x1, 0x0, 0xC4, 0x0, 0x62, 0x0, 0x0, 0x0, 0x3, 0x0, 0x2, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0xF5, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x60, 0xFD, 0x84, 0xFE, 0x10, 0x18, 0x9, 0x0, 0x7, 0x0, 0x38, 0x0, 0x60, 0xFD, 0x84, 0xFE, 0x10, 0x18, 0x9, 0x0, 0x7, 0x0, 0x38, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x62, 0xFD, 0x86, 0xFE, 0xA8, 0x7, 0x9, 0x0, 0x7, 0x0, 0x38, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xE0, 0x45, 0x2, 0x0}, -}; - -unsigned char bps_settings[4][684] = { -{ /* placeholder */ }, - {0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, - {0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, - {0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, -}; - diff --git a/system/camerad/cameras/hw.h b/system/camerad/cameras/hw.h deleted file mode 100644 index d299627ce9..0000000000 --- a/system/camerad/cameras/hw.h +++ /dev/null @@ -1,68 +0,0 @@ -#pragma once - -#include "common/util.h" -#include "cereal/gen/cpp/log.capnp.h" -#include "msgq/visionipc/visionipc_server.h" - -#include "media/cam_isp_ife.h" - - -typedef enum { - ISP_RAW_OUTPUT, // raw frame from sensor - ISP_IFE_PROCESSED, // fully processed image through the IFE - ISP_BPS_PROCESSED, // fully processed image through the BPS -} SpectraOutputType; - -// For the comma 3/3X three camera platform - -struct CameraConfig { - int camera_num; - VisionStreamType stream_type; - float focal_len; // millimeters - const char *publish_name; - cereal::FrameData::Builder (cereal::Event::Builder::*init_camera_state)(); - bool enabled; - uint32_t phy; - bool vignetting_correction; - SpectraOutputType output_type; -}; - -// NOTE: to be able to disable road and wide road, we still have to configure the sensor over i2c -// If you don't do this, the strobe GPIO is an output (even in reset it seems!) -const CameraConfig WIDE_ROAD_CAMERA_CONFIG = { - .camera_num = 0, - .stream_type = VISION_STREAM_WIDE_ROAD, - .focal_len = 1.71, - .publish_name = "wideRoadCameraState", - .init_camera_state = &cereal::Event::Builder::initWideRoadCameraState, - .enabled = !getenv("DISABLE_WIDE_ROAD"), - .phy = CAM_ISP_IFE_IN_RES_PHY_0, - .vignetting_correction = false, - .output_type = ISP_IFE_PROCESSED, -}; - -const CameraConfig ROAD_CAMERA_CONFIG = { - .camera_num = 1, - .stream_type = VISION_STREAM_ROAD, - .focal_len = 8.0, - .publish_name = "roadCameraState", - .init_camera_state = &cereal::Event::Builder::initRoadCameraState, - .enabled = !getenv("DISABLE_ROAD"), - .phy = CAM_ISP_IFE_IN_RES_PHY_1, - .vignetting_correction = true, - .output_type = ISP_IFE_PROCESSED, -}; - -const CameraConfig DRIVER_CAMERA_CONFIG = { - .camera_num = 2, - .stream_type = VISION_STREAM_DRIVER, - .focal_len = 1.71, - .publish_name = "driverCameraState", - .init_camera_state = &cereal::Event::Builder::initDriverCameraState, - .enabled = !getenv("DISABLE_DRIVER"), - .phy = CAM_ISP_IFE_IN_RES_PHY_2, - .vignetting_correction = false, - .output_type = ISP_BPS_PROCESSED, -}; - -const CameraConfig ALL_CAMERA_CONFIGS[] = {WIDE_ROAD_CAMERA_CONFIG, ROAD_CAMERA_CONFIG, DRIVER_CAMERA_CONFIG}; diff --git a/system/camerad/sensors/ar0231.cc b/system/camerad/sensors/ar0231.cc deleted file mode 100644 index e4ae29f079..0000000000 --- a/system/camerad/sensors/ar0231.cc +++ /dev/null @@ -1,136 +0,0 @@ -#include -#include - -#include "system/camerad/sensors/sensor.h" - -namespace { - -const size_t AR0231_REGISTERS_HEIGHT = 2; -// TODO: this extra height is universal and doesn't apply per camera -const size_t AR0231_STATS_HEIGHT = 2 + 8; - -const float sensor_analog_gains_AR0231[] = { - 1.0 / 8.0, 2.0 / 8.0, 2.0 / 7.0, 3.0 / 7.0, // 0, 1, 2, 3 - 3.0 / 6.0, 4.0 / 6.0, 4.0 / 5.0, 5.0 / 5.0, // 4, 5, 6, 7 - 5.0 / 4.0, 6.0 / 4.0, 6.0 / 3.0, 7.0 / 3.0, // 8, 9, 10, 11 - 7.0 / 2.0, 8.0 / 2.0, 8.0 / 1.0}; // 12, 13, 14, 15 = bypass - -} // namespace - -AR0231::AR0231() { - image_sensor = cereal::FrameData::ImageSensor::AR0231; - bayer_pattern = CAM_ISP_PATTERN_BAYER_GRGRGR; - pixel_size_mm = 0.003; - data_word = true; - frame_width = 1928; - frame_height = 1208; - frame_stride = (frame_width * 12 / 8) + 4; - extra_height = AR0231_REGISTERS_HEIGHT + AR0231_STATS_HEIGHT; - - registers_offset = 0; - frame_offset = AR0231_REGISTERS_HEIGHT; - stats_offset = AR0231_REGISTERS_HEIGHT + frame_height; - - start_reg_array.assign(std::begin(start_reg_array_ar0231), std::end(start_reg_array_ar0231)); - init_reg_array.assign(std::begin(init_array_ar0231), std::end(init_array_ar0231)); - probe_reg_addr = 0x3000; - probe_expected_data = 0x354; - bits_per_pixel = 12; - mipi_format = CAM_FORMAT_MIPI_RAW_12; - frame_data_type = 0x12; // Changing stats to 0x2C doesn't work, so change pixels to 0x12 instead - mclk_frequency = 19200000; //Hz - - readout_time_ns = 22850000; - - dc_gain_factor = 2.5; - dc_gain_min_weight = 0; - dc_gain_max_weight = 1; - dc_gain_on_grey = 0.2; - dc_gain_off_grey = 0.3; - exposure_time_min = 2; // with HDR, fastest ss - exposure_time_max = 0x0855; // with HDR, slowest ss, 40ms - analog_gain_min_idx = 0x1; // 0.25x - analog_gain_rec_idx = 0x6; // 0.8x - analog_gain_max_idx = 0xD; // 4.0x - analog_gain_cost_delta = 0; - analog_gain_cost_low = 0.1; - analog_gain_cost_high = 5.0; - for (int i = 0; i <= analog_gain_max_idx; i++) { - sensor_analog_gains[i] = sensor_analog_gains_AR0231[i]; - } - min_ev = exposure_time_min * sensor_analog_gains[analog_gain_min_idx]; - max_ev = exposure_time_max * dc_gain_factor * sensor_analog_gains[analog_gain_max_idx]; - target_grey_factor = 1.0; - - black_level = 168; - color_correct_matrix = { - 0x000000af, 0x00000ff9, 0x00000fd8, - 0x00000fbc, 0x000000bb, 0x00000009, - 0x00000fb6, 0x00000fe0, 0x000000ea, - }; - for (int i = 0; i < 65; i++) { - float fx = i / 64.0; - const float gamma_k = 0.75; - const float gamma_b = 0.125; - const float mp = 0.01; // ideally midpoint should be adaptive - const float rk = 9 - 100*mp; - // poly approximation for s curve - fx = (fx > mp) ? - ((rk * (fx-mp) * (1-(gamma_k*mp+gamma_b)) * (1+1/(rk*(1-mp))) / (1+rk*(fx-mp))) + gamma_k*mp + gamma_b) : - ((rk * (fx-mp) * (gamma_k*mp+gamma_b) * (1+1/(rk*mp)) / (1-rk*(fx-mp))) + gamma_k*mp + gamma_b); - gamma_lut_rgb.push_back((uint32_t)(fx*1023.0 + 0.5)); - } - prepare_gamma_lut(); - linearization_lut = { - 0x02000000, 0x02000000, 0x02000000, 0x02000000, - 0x020007ff, 0x020007ff, 0x020007ff, 0x020007ff, - 0x02000bff, 0x02000bff, 0x02000bff, 0x02000bff, - 0x020017ff, 0x020017ff, 0x020017ff, 0x020017ff, - 0x02001bff, 0x02001bff, 0x02001bff, 0x02001bff, - 0x020023ff, 0x020023ff, 0x020023ff, 0x020023ff, - 0x00003fff, 0x00003fff, 0x00003fff, 0x00003fff, - 0x00003fff, 0x00003fff, 0x00003fff, 0x00003fff, - 0x00003fff, 0x00003fff, 0x00003fff, 0x00003fff, - }; - linearization_pts = {0x07ff0bff, 0x17ff1bff, 0x23ff3fff, 0x3fff3fff}; - vignetting_lut = { - 0x00eaa755, 0x00cf2679, 0x00bc05e0, 0x00acc566, 0x00a1450a, 0x009984cc, 0x0095a4ad, 0x009584ac, 0x009944ca, 0x00a0c506, 0x00ac0560, 0x00bb25d9, 0x00ce2671, 0x00e90748, 0x01112889, 0x014a2a51, 0x01984cc2, - 0x00db06d8, 0x00c30618, 0x00afe57f, 0x00a0a505, 0x009524a9, 0x008d646b, 0x0089844c, 0x0089644b, 0x008d2469, 0x0094a4a5, 0x009fe4ff, 0x00af0578, 0x00c20610, 0x00d986cc, 0x00fda7ed, 0x01320990, 0x017aebd7, - 0x00d1868c, 0x00baa5d5, 0x00a7853c, 0x009844c2, 0x008cc466, 0x0085a42d, 0x0083641b, 0x0083641b, 0x0085842c, 0x008c4462, 0x0097a4bd, 0x00a6c536, 0x00b9a5cd, 0x00d06683, 0x00f1678b, 0x01226913, 0x0167ab3d, - 0x00cd0668, 0x00b625b1, 0x00a30518, 0x0093c49e, 0x00884442, 0x00830418, 0x0080e407, 0x0080c406, 0x0082e417, 0x0087c43e, 0x00932499, 0x00a22511, 0x00b525a9, 0x00cbe65f, 0x00eb0758, 0x011a68d3, 0x015daaed, - 0x00cc4662, 0x00b565ab, 0x00a24512, 0x00930498, 0x0087843c, 0x0082a415, 0x00806403, 0x00806403, 0x00828414, 0x00870438, 0x00926493, 0x00a1850c, 0x00b465a3, 0x00cb2659, 0x00ea2751, 0x011928c9, 0x015c2ae1, - 0x00cf667b, 0x00b885c4, 0x00a5652b, 0x009624b1, 0x008aa455, 0x00846423, 0x00822411, 0x00822411, 0x00844422, 0x008a2451, 0x009564ab, 0x00a48524, 0x00b785bc, 0x00ce4672, 0x00ee6773, 0x011e88f4, 0x0162eb17, - 0x00d6c6b6, 0x00bf65fb, 0x00ac4562, 0x009d04e8, 0x0091848c, 0x0089c44e, 0x00862431, 0x00860430, 0x0089844c, 0x00910488, 0x009c64e3, 0x00ab655b, 0x00be65f3, 0x00d566ab, 0x00f847c2, 0x012b2959, 0x01726b93, - 0x00e3e71f, 0x00ca0650, 0x00b705b8, 0x00a7a53d, 0x009c24e1, 0x009484a4, 0x00908484, 0x00908484, 0x009424a1, 0x009bc4de, 0x00a70538, 0x00b625b1, 0x00c90648, 0x00e26713, 0x0108e847, 0x013fe9ff, 0x018bcc5e, - 0x00f807c0, 0x00d966cb, 0x00c5862c, 0x00b625b1, 0x00aaa555, 0x00a30518, 0x009f04f8, 0x009f04f8, 0x00a2a515, 0x00aa2551, 0x00b585ac, 0x00c4a625, 0x00d846c2, 0x00f647b2, 0x0121a90d, 0x015e4af2, 0x01b8cdc6, - 0x011548aa, 0x00f1678b, 0x00d886c4, 0x00c86643, 0x00bce5e7, 0x00b545aa, 0x00b1658b, 0x00b1458a, 0x00b505a8, 0x00bc85e4, 0x00c7c63e, 0x00d786bc, 0x00efe77f, 0x0113489a, 0x0144ea27, 0x01888c44, 0x01fdcfee, - 0x013e49f2, 0x0113e89f, 0x00f5a7ad, 0x00e0c706, 0x00d30698, 0x00cb665b, 0x00c7663b, 0x00c7663b, 0x00cb0658, 0x00d2a695, 0x00dfe6ff, 0x00f467a3, 0x01122891, 0x013be9df, 0x01750ba8, 0x01cfae7d, 0x025912c8, - 0x01766bb3, 0x01446a23, 0x011fc8fe, 0x0105e82f, 0x00f467a3, 0x00e9874c, 0x00e46723, 0x00e44722, 0x00e92749, 0x00f3a79d, 0x0104c826, 0x011e48f2, 0x01424a12, 0x01738b9c, 0x01bf6dfb, 0x023611b0, 0x02ced676, - 0x01cf8e7c, 0x01866c33, 0x015aaad5, 0x013ae9d7, 0x01250928, 0x011768bb, 0x0110a885, 0x01108884, 0x0116e8b7, 0x01242921, 0x0139a9cd, 0x0158eac7, 0x01840c20, 0x01cb0e58, 0x0233719b, 0x02b9d5ce, 0x03645b22, - }; -} - -std::vector AR0231::getExposureRegisters(int exposure_time, int new_exp_g, bool dc_gain_enabled) const { - uint16_t analog_gain_reg = 0xFF00 | (new_exp_g << 4) | new_exp_g; - return { - {0x3366, analog_gain_reg}, - {0x3362, (uint16_t)(dc_gain_enabled ? 0x1 : 0x0)}, - {0x3012, (uint16_t)exposure_time}, - }; -} - -int AR0231::getSlaveAddress(int port) const { - assert(port >= 0 && port <= 2); - return (int[]){0x20, 0x30, 0x20}[port]; -} - -float AR0231::getExposureScore(float desired_ev, int exp_t, int exp_g_idx, float exp_gain, int gain_idx) const { - // Cost of ev diff - float score = std::abs(desired_ev - (exp_t * exp_gain)) * 10; - // Cost of absolute gain - float m = exp_g_idx > analog_gain_rec_idx ? analog_gain_cost_high : analog_gain_cost_low; - score += std::abs(exp_g_idx - (int)analog_gain_rec_idx) * m; - // Cost of changing gain - score += std::abs(exp_g_idx - gain_idx) * (score + 1.0) / 10.0; - return score; -} diff --git a/system/camerad/sensors/ar0231_cl.h b/system/camerad/sensors/ar0231_cl.h deleted file mode 100644 index c79242543b..0000000000 --- a/system/camerad/sensors/ar0231_cl.h +++ /dev/null @@ -1,34 +0,0 @@ -#if SENSOR_ID == 1 - -#define VIGNETTE_PROFILE_8DT0MM - -#define BIT_DEPTH 12 -#define PV_MAX 4096 -#define BLACK_LVL 168 - -float4 normalize_pv(int4 parsed, float vignette_factor) { - float4 pv = (convert_float4(parsed) - BLACK_LVL) / (PV_MAX - BLACK_LVL); - return clamp(pv*vignette_factor, 0.0, 1.0); -} - -float3 color_correct(float3 rgb) { - float3 corrected = rgb.x * (float3)(1.82717181, -0.31231438, 0.07307673); - corrected += rgb.y * (float3)(-0.5743977, 1.36858544, -0.53183455); - corrected += rgb.z * (float3)(-0.25277411, -0.05627105, 1.45875782); - return corrected; -} - -float3 apply_gamma(float3 rgb, int expo_time) { - // tone mapping params - const float gamma_k = 0.75; - const float gamma_b = 0.125; - const float mp = 0.01; // ideally midpoint should be adaptive - const float rk = 9 - 100*mp; - - // poly approximation for s curve - return (rgb > mp) ? - ((rk * (rgb-mp) * (1-(gamma_k*mp+gamma_b)) * (1+1/(rk*(1-mp))) / (1+rk*(rgb-mp))) + gamma_k*mp + gamma_b) : - ((rk * (rgb-mp) * (gamma_k*mp+gamma_b) * (1+1/(rk*mp)) / (1-rk*(rgb-mp))) + gamma_k*mp + gamma_b); -} - -#endif diff --git a/system/camerad/sensors/ar0231_registers.h b/system/camerad/sensors/ar0231_registers.h deleted file mode 100644 index e0872a673a..0000000000 --- a/system/camerad/sensors/ar0231_registers.h +++ /dev/null @@ -1,121 +0,0 @@ -#pragma once - -const struct i2c_random_wr_payload start_reg_array_ar0231[] = {{0x301A, 0x91C}}; -const struct i2c_random_wr_payload stop_reg_array_ar0231[] = {{0x301A, 0x918}}; - -const struct i2c_random_wr_payload init_array_ar0231[] = { - {0x301A, 0x0018}, // RESET_REGISTER - - // **NOTE**: if this is changed, readout_time_ns must be updated in the Sensor config - - // CLOCK Settings - // input clock is 19.2 / 2 * 0x37 = 528 MHz - // pixclk is 528 / 6 = 88 MHz - // full roll time is 1000/(PIXCLK/(LINE_LENGTH_PCK*FRAME_LENGTH_LINES)) = 39.99 ms - // img roll time is 1000/(PIXCLK/(LINE_LENGTH_PCK*Y_OUTPUT_CONTROL)) = 22.85 ms - {0x302A, 0x0006}, // VT_PIX_CLK_DIV - {0x302C, 0x0001}, // VT_SYS_CLK_DIV - {0x302E, 0x0002}, // PRE_PLL_CLK_DIV - {0x3030, 0x0037}, // PLL_MULTIPLIER - {0x3036, 0x000C}, // OP_PIX_CLK_DIV - {0x3038, 0x0001}, // OP_SYS_CLK_DIV - - // FORMAT - {0x3040, 0xC000}, // READ_MODE - {0x3004, 0x0000}, // X_ADDR_START_ - {0x3008, 0x0787}, // X_ADDR_END_ - {0x3002, 0x0000}, // Y_ADDR_START_ - {0x3006, 0x04B7}, // Y_ADDR_END_ - {0x3032, 0x0000}, // SCALING_MODE - {0x30A2, 0x0001}, // X_ODD_INC_ - {0x30A6, 0x0001}, // Y_ODD_INC_ - {0x3402, 0x0788}, // X_OUTPUT_CONTROL - {0x3404, 0x04B8}, // Y_OUTPUT_CONTROL - {0x3064, 0x1982}, // SMIA_TEST - {0x30BA, 0x11F2}, // DIGITAL_CTRL - - // Enable external trigger and disable GPIO outputs - {0x30CE, 0x0120}, // SLAVE_SH_SYNC_MODE | FRAME_START_MODE - {0x340A, 0xE0}, // GPIO3_INPUT_DISABLE | GPIO2_INPUT_DISABLE | GPIO1_INPUT_DISABLE - {0x340C, 0x802}, // GPIO_HIDRV_EN | GPIO0_ISEL=2 - - // Readout timing - {0x300C, 0x0672}, // LINE_LENGTH_PCK (valid for 3-exposure HDR) - {0x300A, 0x0855}, // FRAME_LENGTH_LINES - {0x3042, 0x0000}, // EXTRA_DELAY - - // Readout Settings - {0x31AE, 0x0204}, // SERIAL_FORMAT, 4-lane MIPI - {0x31AC, 0x0C0C}, // DATA_FORMAT_BITS, 12 -> 12 - {0x3342, 0x1212}, // MIPI_F1_PDT_EDT - {0x3346, 0x1212}, // MIPI_F2_PDT_EDT - {0x334A, 0x1212}, // MIPI_F3_PDT_EDT - {0x334E, 0x1212}, // MIPI_F4_PDT_EDT - {0x3344, 0x0011}, // MIPI_F1_VDT_VC - {0x3348, 0x0111}, // MIPI_F2_VDT_VC - {0x334C, 0x0211}, // MIPI_F3_VDT_VC - {0x3350, 0x0311}, // MIPI_F4_VDT_VC - {0x31B0, 0x0053}, // FRAME_PREAMBLE - {0x31B2, 0x003B}, // LINE_PREAMBLE - {0x301A, 0x001C}, // RESET_REGISTER - - // Noise Corrections - {0x3092, 0x0C24}, // ROW_NOISE_CONTROL - {0x337A, 0x0C80}, // DBLC_SCALE0 - {0x3370, 0x03B1}, // DBLC - {0x3044, 0x0400}, // DARK_CONTROL - - // Enable temperature sensor - {0x30B4, 0x0007}, // TEMPSENS0_CTRL_REG - {0x30B8, 0x0007}, // TEMPSENS1_CTRL_REG - - // Enable dead pixel correction using - // the 1D line correction scheme - {0x31E0, 0x0003}, - - // HDR Settings - {0x3082, 0x0004}, // OPERATION_MODE_CTRL - {0x3238, 0x0444}, // EXPOSURE_RATIO - - {0x1008, 0x0361}, // FINE_INTEGRATION_TIME_MIN - {0x100C, 0x0589}, // FINE_INTEGRATION_TIME2_MIN - {0x100E, 0x07B1}, // FINE_INTEGRATION_TIME3_MIN - {0x1010, 0x0139}, // FINE_INTEGRATION_TIME4_MIN - - // TODO: do these have to be lower than LINE_LENGTH_PCK? - {0x3014, 0x08CB}, // FINE_INTEGRATION_TIME_ - {0x321E, 0x0894}, // FINE_INTEGRATION_TIME2 - - {0x31D0, 0x0000}, // COMPANDING, no good in 10 bit? - {0x33DA, 0x0000}, // COMPANDING - {0x318E, 0x0200}, // PRE_HDR_GAIN_EN - - // DLO Settings - {0x3100, 0x4000}, // DLO_CONTROL0 - {0x3280, 0x0CCC}, // T1 G1 - {0x3282, 0x0CCC}, // T1 R - {0x3284, 0x0CCC}, // T1 B - {0x3286, 0x0CCC}, // T1 G2 - {0x3288, 0x0FA0}, // T2 G1 - {0x328A, 0x0FA0}, // T2 R - {0x328C, 0x0FA0}, // T2 B - {0x328E, 0x0FA0}, // T2 G2 - - // Initial Gains - {0x3022, 0x0001}, // GROUPED_PARAMETER_HOLD_ - {0x3366, 0xFF77}, // ANALOG_GAIN (1x) - - {0x3060, 0x3333}, // ANALOG_COLOR_GAIN - - {0x3362, 0x0000}, // DC GAIN - - {0x305A, 0x00F8}, // red gain - {0x3058, 0x0122}, // blue gain - {0x3056, 0x009A}, // g1 gain - {0x305C, 0x009A}, // g2 gain - - {0x3022, 0x0000}, // GROUPED_PARAMETER_HOLD_ - - // Initial Integration Time - {0x3012, 0x0005}, -}; diff --git a/system/camerad/sensors/os04c10_cl.h b/system/camerad/sensors/os04c10_cl.h deleted file mode 100644 index 3b5cf88839..0000000000 --- a/system/camerad/sensors/os04c10_cl.h +++ /dev/null @@ -1,58 +0,0 @@ -#if SENSOR_ID == 3 - -#define BGGR -#define VIGNETTE_PROFILE_4DT6MM - -#define BIT_DEPTH 12 -#define PV_MAX10 1023 -#define PV_MAX12 4095 -#define PV_MAX16 65536 // gamma curve is calibrated to 16bit -#define BLACK_LVL 48 - -float combine_dual_pvs(float lv, float sv, int expo_time) { - float svc = fmax(sv * expo_time, (float)(64 * (PV_MAX10 - BLACK_LVL))); - float svd = sv * fmin(expo_time, 8.0) / 8; - - if (expo_time > 64) { - if (lv < PV_MAX10 - BLACK_LVL) { - return lv / (PV_MAX16 - BLACK_LVL); - } else { - return (svc / 64) / (PV_MAX16 - BLACK_LVL); - } - } else { - if (lv > 32) { - return (lv * 64 / fmax(expo_time, 8.0)) / (PV_MAX16 - BLACK_LVL); - } else { - return svd / (PV_MAX16 - BLACK_LVL); - } - } -} - -float4 normalize_pv_hdr(int4 parsed, int4 short_parsed, float vignette_factor, int expo_time) { - float4 pl = convert_float4(parsed - BLACK_LVL); - float4 ps = convert_float4(short_parsed - BLACK_LVL); - float4 pv; - pv.s0 = combine_dual_pvs(pl.s0, ps.s0, expo_time); - pv.s1 = combine_dual_pvs(pl.s1, ps.s1, expo_time); - pv.s2 = combine_dual_pvs(pl.s2, ps.s2, expo_time); - pv.s3 = combine_dual_pvs(pl.s3, ps.s3, expo_time); - return clamp(pv*vignette_factor, 0.0, 1.0); -} - -float4 normalize_pv(int4 parsed, float vignette_factor) { - float4 pv = (convert_float4(parsed) - BLACK_LVL) / (PV_MAX12 - BLACK_LVL); - return clamp(pv*vignette_factor, 0.0, 1.0); -} - -float3 color_correct(float3 rgb) { - float3 corrected = rgb.x * (float3)(1.55361989, -0.268894615, -0.000593219); - corrected += rgb.y * (float3)(-0.421217301, 1.51883144, -0.69760146); - corrected += rgb.z * (float3)(-0.132402589, -0.249936825, 1.69819468); - return corrected; -} - -float3 apply_gamma(float3 rgb, int expo_time) { - return (10 * rgb) / (1 + 9 * rgb); -} - -#endif diff --git a/system/camerad/sensors/ox03c10_cl.h b/system/camerad/sensors/ox03c10_cl.h deleted file mode 100644 index c8cec7cf8a..0000000000 --- a/system/camerad/sensors/ox03c10_cl.h +++ /dev/null @@ -1,47 +0,0 @@ -#if SENSOR_ID == 2 - -#define VIGNETTE_PROFILE_8DT0MM - -#define BIT_DEPTH 12 -#define BLACK_LVL 64 - -float ox_lut_func(int x) { - if (x < 512) { - return x * 5.94873e-8; - } else if (512 <= x && x < 768) { - return 3.0458e-05 + (x-512) * 1.19913e-7; - } else if (768 <= x && x < 1536) { - return 6.1154e-05 + (x-768) * 2.38493e-7; - } else if (1536 <= x && x < 1792) { - return 0.0002448 + (x-1536) * 9.56930e-7; - } else if (1792 <= x && x < 2048) { - return 0.00048977 + (x-1792) * 1.91441e-6; - } else if (2048 <= x && x < 2304) { - return 0.00097984 + (x-2048) * 3.82937e-6; - } else if (2304 <= x && x < 2560) { - return 0.0019601 + (x-2304) * 7.659055e-6; - } else if (2560 <= x && x < 2816) { - return 0.0039207 + (x-2560) * 1.525e-5; - } else { - return 0.0078421 + (exp((x-2816)/273.0) - 1) * 0.0092421; - } -} - -float4 normalize_pv(int4 parsed, float vignette_factor) { - // PWL - float4 pv = {ox_lut_func(parsed.s0), ox_lut_func(parsed.s1), ox_lut_func(parsed.s2), ox_lut_func(parsed.s3)}; - return clamp(pv*vignette_factor*256.0, 0.0, 1.0); -} - -float3 color_correct(float3 rgb) { - float3 corrected = rgb.x * (float3)(1.5664815, -0.29808738, -0.03973474); - corrected += rgb.y * (float3)(-0.48672447, 1.41914433, -0.40295248); - corrected += rgb.z * (float3)(-0.07975703, -0.12105695, 1.44268722); - return corrected; -} - -float3 apply_gamma(float3 rgb, int expo_time) { - return -0.507089*exp(-12.54124638*rgb) + 0.9655*powr(rgb, 0.5) - 0.472597*rgb + 0.507089; -} - -#endif diff --git a/system/camerad/sensors/sensor.h b/system/camerad/sensors/sensor.h deleted file mode 100644 index d4be3cf036..0000000000 --- a/system/camerad/sensors/sensor.h +++ /dev/null @@ -1,117 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include - -#include "media/cam_isp.h" -#include "media/cam_sensor.h" - -#include "cereal/gen/cpp/log.capnp.h" -#include "system/camerad/sensors/ar0231_registers.h" -#include "system/camerad/sensors/ox03c10_registers.h" -#include "system/camerad/sensors/os04c10_registers.h" - -#define ANALOG_GAIN_MAX_CNT 55 - -class SensorInfo { -public: - SensorInfo() = default; - virtual std::vector getExposureRegisters(int exposure_time, int new_exp_g, bool dc_gain_enabled) const { return {}; } - virtual float getExposureScore(float desired_ev, int exp_t, int exp_g_idx, float exp_gain, int gain_idx) const {return 0; } - virtual int getSlaveAddress(int port) const { assert(0); } - - cereal::FrameData::ImageSensor image_sensor = cereal::FrameData::ImageSensor::UNKNOWN; - float pixel_size_mm; - uint32_t frame_width, frame_height; - uint32_t frame_stride; - uint32_t frame_offset = 0; - uint32_t extra_height = 0; - int out_scale = 1; - int registers_offset = -1; - int stats_offset = -1; - int hdr_offset = -1; - - int exposure_time_min; - int exposure_time_max; - - float dc_gain_factor; - int dc_gain_min_weight; - int dc_gain_max_weight; - float dc_gain_on_grey; - float dc_gain_off_grey; - - float ev_scale = 1.0; - float sensor_analog_gains[ANALOG_GAIN_MAX_CNT]; - int analog_gain_min_idx; - int analog_gain_max_idx; - int analog_gain_rec_idx; - int analog_gain_cost_delta; - float analog_gain_cost_low; - float analog_gain_cost_high; - float target_grey_factor; - float min_ev; - float max_ev; - - bool data_word; - uint32_t probe_reg_addr; - uint32_t probe_expected_data; - std::vector start_reg_array; - std::vector init_reg_array; - - uint32_t bits_per_pixel; - uint32_t bayer_pattern; - uint32_t mipi_format; - uint32_t mclk_frequency; - uint32_t frame_data_type; - - uint32_t readout_time_ns; // used to recover EOF from SOF - - // ISP image processing params - uint32_t black_level; - std::vector color_correct_matrix; // 3x3 - std::vector gamma_lut_rgb; // gamma LUTs are length 64 * sizeof(uint32_t); same for r/g/b here - void prepare_gamma_lut() { - for (int i = 0; i < 64; i++) { - gamma_lut_rgb[i] |= ((uint32_t)(gamma_lut_rgb[i+1] - gamma_lut_rgb[i]) << 10); - } - gamma_lut_rgb.pop_back(); - } - std::vector linearization_lut; // length 36 - std::vector linearization_pts; // length 4 - std::vector vignetting_lut; // length 221 - - const int num() const { - return static_cast(image_sensor); - }; -}; - -class AR0231 : public SensorInfo { -public: - AR0231(); - std::vector getExposureRegisters(int exposure_time, int new_exp_g, bool dc_gain_enabled) const override; - float getExposureScore(float desired_ev, int exp_t, int exp_g_idx, float exp_gain, int gain_idx) const override; - int getSlaveAddress(int port) const override; - -private: - mutable std::map> ar0231_register_lut; -}; - -class OX03C10 : public SensorInfo { -public: - OX03C10(); - std::vector getExposureRegisters(int exposure_time, int new_exp_g, bool dc_gain_enabled) const override; - float getExposureScore(float desired_ev, int exp_t, int exp_g_idx, float exp_gain, int gain_idx) const override; - int getSlaveAddress(int port) const override; -}; - -class OS04C10 : public SensorInfo { -public: - OS04C10(); - void ife_downscale_configure(); - std::vector getExposureRegisters(int exposure_time, int new_exp_g, bool dc_gain_enabled) const override; - float getExposureScore(float desired_ev, int exp_t, int exp_g_idx, float exp_gain, int gain_idx) const override; - int getSlaveAddress(int port) const override; -}; diff --git a/system/camerad/snapshot.py b/system/camerad/snapshot.py deleted file mode 100755 index b3369891d7..0000000000 --- a/system/camerad/snapshot.py +++ /dev/null @@ -1,125 +0,0 @@ -#!/usr/bin/env python3 -import subprocess -import time - -import numpy as np -from PIL import Image - -import cereal.messaging as messaging -from msgq.visionipc import VisionIpcClient, VisionStreamType -from openpilot.common.params import Params -from openpilot.common.realtime import DT_MDL -from openpilot.system.hardware import PC -from openpilot.selfdrive.selfdrived.alertmanager import set_offroad_alert -from openpilot.system.manager.process_config import managed_processes - - -VISION_STREAMS = { - "roadCameraState": VisionStreamType.VISION_STREAM_ROAD, - "driverCameraState": VisionStreamType.VISION_STREAM_DRIVER, - "wideRoadCameraState": VisionStreamType.VISION_STREAM_WIDE_ROAD, -} - - -def jpeg_write(fn, dat): - img = Image.fromarray(dat) - img.save(fn, "JPEG") - - -def yuv_to_rgb(y, u, v): - ul = np.repeat(np.repeat(u, 2).reshape(u.shape[0], y.shape[1]), 2, axis=0).reshape(y.shape) - vl = np.repeat(np.repeat(v, 2).reshape(v.shape[0], y.shape[1]), 2, axis=0).reshape(y.shape) - - yuv = np.dstack((y, ul, vl)).astype(np.int16) - yuv[:, :, 1:] -= 128 - - m = np.array([ - [1.00000, 1.00000, 1.00000], - [0.00000, -0.39465, 2.03211], - [1.13983, -0.58060, 0.00000], - ]) - rgb = np.dot(yuv, m).clip(0, 255) - return rgb.astype(np.uint8) - - -def extract_image(buf): - y = np.array(buf.data[:buf.uv_offset], dtype=np.uint8).reshape((-1, buf.stride))[:buf.height, :buf.width] - u = np.array(buf.data[buf.uv_offset::2], dtype=np.uint8).reshape((-1, buf.stride//2))[:buf.height//2, :buf.width//2] - v = np.array(buf.data[buf.uv_offset+1::2], dtype=np.uint8).reshape((-1, buf.stride//2))[:buf.height//2, :buf.width//2] - - return yuv_to_rgb(y, u, v) - - -def get_snapshots(frame="roadCameraState", front_frame="driverCameraState"): - sockets = [s for s in (frame, front_frame) if s is not None] - sm = messaging.SubMaster(sockets) - vipc_clients = {s: VisionIpcClient("camerad", VISION_STREAMS[s], True) for s in sockets} - - # wait 4 sec from camerad startup for focus and exposure - while sm[sockets[0]].frameId < int(4. / DT_MDL): - sm.update() - - for client in vipc_clients.values(): - client.connect(True) - - # grab images - rear, front = None, None - if frame is not None: - c = vipc_clients[frame] - rear = extract_image(c.recv()) - if front_frame is not None: - c = vipc_clients[front_frame] - front = extract_image(c.recv()) - return rear, front - - -def snapshot(): - params = Params() - - if (not params.get_bool("IsOffroad")) or params.get_bool("IsTakingSnapshot"): - print("Already taking snapshot") - return None, None - - front_camera_allowed = params.get_bool("RecordFront") - params.put_bool("IsTakingSnapshot", True) - set_offroad_alert("Offroad_IsTakingSnapshot", True) - time.sleep(2.0) # Give hardwared time to read the param, or if just started give camerad time to start - - # Check if camerad is already started - try: - subprocess.check_call(["pgrep", "camerad"]) - print("Camerad already running") - params.put_bool("IsTakingSnapshot", False) - params.remove("Offroad_IsTakingSnapshot") - return None, None - except subprocess.CalledProcessError: - pass - - try: - # Allow testing on replay on PC - if not PC: - managed_processes['camerad'].start() - - frame = "wideRoadCameraState" - front_frame = "driverCameraState" if front_camera_allowed else None - rear, front = get_snapshots(frame, front_frame) - finally: - managed_processes['camerad'].stop() - params.put_bool("IsTakingSnapshot", False) - set_offroad_alert("Offroad_IsTakingSnapshot", False) - - if not front_camera_allowed: - front = None - - return rear, front - - -if __name__ == "__main__": - pic, fpic = snapshot() - if pic is not None: - print(pic.shape) - jpeg_write("/tmp/back.jpg", pic) - if fpic is not None: - jpeg_write("/tmp/front.jpg", fpic) - else: - print("Error taking snapshot") diff --git a/system/camerad/test/test_camerad.py b/system/camerad/test/test_camerad.py deleted file mode 100644 index ab76985972..0000000000 --- a/system/camerad/test/test_camerad.py +++ /dev/null @@ -1,98 +0,0 @@ -import os -import time -import pytest -import numpy as np - -import cereal.messaging as messaging -from cereal.services import SERVICE_LIST -from openpilot.system.manager.process_config import managed_processes -from openpilot.tools.lib.log_time_series import msgs_to_time_series - -TEST_TIMESPAN = 10 -CAMERAS = ('roadCameraState', 'driverCameraState', 'wideRoadCameraState') - - -def run_and_log(procs, services, duration): - logs = [] - - try: - for p in procs: - managed_processes[p].start() - socks = [messaging.sub_sock(s, conflate=False, timeout=100) for s in services] - - start_time = time.monotonic() - while time.monotonic() - start_time < duration: - for s in socks: - logs.extend(messaging.drain_sock(s)) - for p in procs: - assert managed_processes[p].proc.is_alive() - finally: - for p in procs: - managed_processes[p].stop() - - return logs - -@pytest.fixture(scope="module") -def logs(): - logs = run_and_log(["camerad", ], CAMERAS, TEST_TIMESPAN) - ts = msgs_to_time_series(logs) - - for cam in CAMERAS: - expected_frames = SERVICE_LIST[cam].frequency * TEST_TIMESPAN - cnt = len(ts[cam]['t']) - assert expected_frames*0.8 < cnt < expected_frames*1.2, f"unexpected frame count {cam}: {expected_frames=}, got {cnt}" - - dts = np.abs(np.diff([ts[cam]['timestampSof']/1e6]) - 1000/SERVICE_LIST[cam].frequency) - assert (dts < 1.0).all(), f"{cam} dts(ms) out of spec: max diff {dts.max()}, 99 percentile {np.percentile(dts, 99)}" - return ts - -@pytest.mark.tici -class TestCamerad: - def test_frame_skips(self, logs): - for c in CAMERAS: - assert set(np.diff(logs[c]['frameId'])) == {1, }, f"{c} has frame skips" - - def test_frame_sync(self, logs): - n = range(len(logs['roadCameraState']['t'][:-10])) - - frame_ids = {i: [logs[cam]['frameId'][i] for cam in CAMERAS] for i in n} - assert all(len(set(v)) == 1 for v in frame_ids.values()), "frame IDs not aligned" - - frame_times = {i: [logs[cam]['timestampSof'][i] for cam in CAMERAS] for i in n} - diffs = {i: (max(ts) - min(ts))/1e6 for i, ts in frame_times.items()} - - laggy_frames = {k: v for k, v in diffs.items() if v > 1.1} - assert len(laggy_frames) == 0, f"Frames not synced properly: {laggy_frames=}" - - def test_sanity_checks(self, logs): - self._sanity_checks(logs) - - def _sanity_checks(self, ts): - for c in CAMERAS: - assert c in ts - assert len(ts[c]['t']) > 20 - - # not a valid request id - assert 0 not in ts[c]['requestId'] - - # should monotonically increase - assert np.all(np.diff(ts[c]['frameId']) >= 1) - assert np.all(np.diff(ts[c]['requestId']) >= 1) - - # EOF > SOF - assert np.all((ts[c]['timestampEof'] - ts[c]['timestampSof']) > 0) - - # logMonoTime > SOF - assert np.all((ts[c]['t'] - ts[c]['timestampSof']/1e9) > 1e-7) - assert np.all((ts[c]['t'] - ts[c]['timestampEof']/1e9) > 1e-7) - - def test_stress_test(self): - os.environ['SPECTRA_ERROR_PROB'] = '0.008' - logs = run_and_log(["camerad", ], CAMERAS, 10) - ts = msgs_to_time_series(logs) - - # we should see some jumps from introduced errors - assert np.max([ np.max(np.diff(ts[c]['frameId'])) for c in CAMERAS ]) > 1 - assert np.max([ np.max(np.diff(ts[c]['requestId'])) for c in CAMERAS ]) > 1 - - self._sanity_checks(ts) diff --git a/system/camerad/test/test_exposure.py b/system/camerad/test/test_exposure.py deleted file mode 100644 index f431c03410..0000000000 --- a/system/camerad/test/test_exposure.py +++ /dev/null @@ -1,51 +0,0 @@ -import time -import numpy as np -import pytest - -from openpilot.selfdrive.test.helpers import with_processes -from openpilot.system.camerad.snapshot import get_snapshots - -TEST_TIME = 45 -REPEAT = 5 - -@pytest.mark.tici -class TestCamerad: - @classmethod - def setup_class(cls): - pass - - def _numpy_rgb2gray(self, im): - ret = np.clip(im[:,:,2] * 0.114 + im[:,:,1] * 0.587 + im[:,:,0] * 0.299, 0, 255).astype(np.uint8) - return ret - - def _is_exposure_okay(self, i, med_mean=None): - if med_mean is None: - med_mean = np.array([[0.2,0.4],[0.2,0.6]]) - h, w = i.shape[:2] - i = i[h//10:9*h//10,w//10:9*w//10] - med_ex, mean_ex = med_mean - i = self._numpy_rgb2gray(i) - i_median = np.median(i) / 255. - i_mean = np.mean(i) / 255. - print([i_median, i_mean]) - return med_ex[0] < i_median < med_ex[1] and mean_ex[0] < i_mean < mean_ex[1] - - @with_processes(['camerad']) - def test_camera_operation(self): - passed = 0 - start = time.time() - while time.time() - start < TEST_TIME and passed < REPEAT: - rpic, dpic = get_snapshots(frame="roadCameraState", front_frame="driverCameraState") - wpic, _ = get_snapshots(frame="wideRoadCameraState") - - res = self._is_exposure_okay(rpic) - res = res and self._is_exposure_okay(dpic) - res = res and self._is_exposure_okay(wpic) - - if passed > 0 and not res: - passed = -passed # fails test if any failure after first sus - break - - passed += int(res) - time.sleep(2) - assert passed >= REPEAT diff --git a/system/hardware/.gitignore b/system/hardware/.gitignore deleted file mode 100644 index 980f09abfa..0000000000 --- a/system/hardware/.gitignore +++ /dev/null @@ -1 +0,0 @@ -eon/rat diff --git a/system/hardware/__init__.py b/system/hardware/__init__.py deleted file mode 100644 index 99079b5ef3..0000000000 --- a/system/hardware/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -import os -from typing import cast - -from openpilot.system.hardware.base import HardwareBase -from openpilot.system.hardware.tici.hardware import Tici -from openpilot.system.hardware.pc.hardware import Pc - -TICI = os.path.isfile('/TICI') -AGNOS = os.path.isfile('/AGNOS') -PC = not TICI - - -if TICI: - HARDWARE = cast(HardwareBase, Tici()) -else: - HARDWARE = cast(HardwareBase, Pc()) diff --git a/system/hardware/base.h b/system/hardware/base.h deleted file mode 100644 index baf0f3c3da..0000000000 --- a/system/hardware/base.h +++ /dev/null @@ -1,40 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -#include "cereal/gen/cpp/log.capnp.h" - -// no-op base hw class -class HardwareNone { -public: - static constexpr float MAX_VOLUME = 0.7; - static constexpr float MIN_VOLUME = 0.2; - - static std::string get_os_version() { return ""; } - static std::string get_name() { return ""; } - static cereal::InitData::DeviceType get_device_type() { return cereal::InitData::DeviceType::UNKNOWN; } - static int get_voltage() { return 0; } - static int get_current() { return 0; } - - static std::string get_serial() { return "cccccc"; } - - static std::map get_init_logs() { - return {}; - } - - static void reboot() {} - static void poweroff() {} - static void set_brightness(int percent) {} - static void set_ir_power(int percentage) {} - static void set_display_power(bool on) {} - - static bool get_ssh_enabled() { return false; } - static void set_ssh_enabled(bool enabled) {} - - static bool PC() { return false; } - static bool TICI() { return false; } - static bool AGNOS() { return false; } -}; diff --git a/system/hardware/base.py b/system/hardware/base.py deleted file mode 100644 index 3506be5145..0000000000 --- a/system/hardware/base.py +++ /dev/null @@ -1,230 +0,0 @@ -import os -from abc import abstractmethod, ABC -from dataclasses import dataclass, fields - -from cereal import log - -NetworkType = log.DeviceState.NetworkType - -class LPAError(RuntimeError): - pass - -class LPAProfileNotFoundError(LPAError): - pass - -@dataclass -class Profile: - iccid: str - nickname: str - enabled: bool - provider: str - -@dataclass -class ThermalZone: - # a zone from /sys/class/thermal/thermal_zone* - name: str # a.k.a type - scale: float = 1000. # scale to get degrees in C - zone_number = -1 - - def read(self) -> float: - if self.zone_number < 0: - for n in os.listdir("/sys/devices/virtual/thermal"): - if not n.startswith("thermal_zone"): - continue - with open(os.path.join("/sys/devices/virtual/thermal", n, "type")) as f: - if f.read().strip() == self.name: - self.zone_number = int(n.removeprefix("thermal_zone")) - break - - try: - with open(f"/sys/devices/virtual/thermal/thermal_zone{self.zone_number}/temp") as f: - return int(f.read()) / self.scale - except FileNotFoundError: - return 0 - -@dataclass -class ThermalConfig: - cpu: list[ThermalZone] | None = None - gpu: list[ThermalZone] | None = None - dsp: ThermalZone | None = None - pmic: list[ThermalZone] | None = None - memory: ThermalZone | None = None - intake: ThermalZone | None = None - exhaust: ThermalZone | None = None - case: ThermalZone | None = None - - def get_msg(self): - ret = {} - for f in fields(ThermalConfig): - v = getattr(self, f.name) - if v is not None: - if isinstance(v, list): - ret[f.name + "TempC"] = [x.read() for x in v] - else: - ret[f.name + "TempC"] = v.read() - return ret - -class LPABase(ABC): - @abstractmethod - def list_profiles(self) -> list[Profile]: - pass - - @abstractmethod - def get_active_profile(self) -> Profile | None: - pass - - @abstractmethod - def delete_profile(self, iccid: str) -> None: - pass - - @abstractmethod - def download_profile(self, qr: str, nickname: str | None = None) -> None: - pass - - @abstractmethod - def nickname_profile(self, iccid: str, nickname: str) -> None: - pass - - @abstractmethod - def switch_profile(self, iccid: str) -> None: - pass - -class HardwareBase(ABC): - @staticmethod - def get_cmdline() -> dict[str, str]: - with open('/proc/cmdline') as f: - cmdline = f.read() - return {kv[0]: kv[1] for kv in [s.split('=') for s in cmdline.split(' ')] if len(kv) == 2} - - @staticmethod - def read_param_file(path, parser, default=0): - try: - with open(path) as f: - return parser(f.read()) - except Exception: - return default - - def booted(self) -> bool: - return True - - @abstractmethod - def reboot(self, reason=None): - pass - - @abstractmethod - def uninstall(self): - pass - - @abstractmethod - def get_os_version(self): - pass - - @abstractmethod - def get_device_type(self): - pass - - @abstractmethod - def get_imei(self, slot) -> str: - pass - - @abstractmethod - def get_serial(self): - pass - - @abstractmethod - def get_network_info(self): - pass - - @abstractmethod - def get_network_type(self): - pass - - @abstractmethod - def get_sim_info(self): - pass - - @abstractmethod - def get_sim_lpa(self) -> LPABase: - pass - - @abstractmethod - def get_network_strength(self, network_type): - pass - - def get_network_metered(self, network_type) -> bool: - return network_type not in (NetworkType.none, NetworkType.wifi, NetworkType.ethernet) - - @staticmethod - def set_bandwidth_limit(upload_speed_kbps: int, download_speed_kbps: int) -> None: - pass - - @abstractmethod - def get_current_power_draw(self): - pass - - @abstractmethod - def get_som_power_draw(self): - pass - - @abstractmethod - def shutdown(self): - pass - - def get_thermal_config(self): - return ThermalConfig() - - def set_display_power(self, on: bool): - pass - - @abstractmethod - def set_screen_brightness(self, percentage): - pass - - @abstractmethod - def get_screen_brightness(self): - pass - - @abstractmethod - def set_power_save(self, powersave_enabled): - pass - - @abstractmethod - def get_gpu_usage_percent(self): - pass - - def get_modem_version(self): - return None - - @abstractmethod - def get_modem_temperatures(self): - pass - - @abstractmethod - def get_nvme_temperatures(self): - pass - - @abstractmethod - def initialize_hardware(self): - pass - - def configure_modem(self): - pass - - def reboot_modem(self): - pass - - @abstractmethod - def get_networks(self): - pass - - def has_internal_panda(self) -> bool: - return False - - def reset_internal_panda(self): - pass - - def recover_internal_panda(self): - pass - - def get_modem_data_usage(self): - return -1, -1 diff --git a/system/hardware/esim.py b/system/hardware/esim.py deleted file mode 100755 index 58ead6593f..0000000000 --- a/system/hardware/esim.py +++ /dev/null @@ -1,45 +0,0 @@ -#!/usr/bin/env python3 - -import argparse -import time -from openpilot.system.hardware import HARDWARE - - -if __name__ == '__main__': - parser = argparse.ArgumentParser(prog='esim.py', description='manage eSIM profiles on your comma device', epilog='comma.ai') - parser.add_argument('--backend', choices=['qmi', 'at'], default='qmi', help='use the specified backend, defaults to qmi') - parser.add_argument('--switch', metavar='iccid', help='switch to profile') - parser.add_argument('--delete', metavar='iccid', help='delete profile (warning: this cannot be undone)') - parser.add_argument('--download', nargs=2, metavar=('qr', 'name'), help='download a profile using QR code (format: LPA:1$rsp.truphone.com$QRF-SPEEDTEST)') - parser.add_argument('--nickname', nargs=2, metavar=('iccid', 'name'), help='update the nickname for a profile') - args = parser.parse_args() - - mutated = False - lpa = HARDWARE.get_sim_lpa() - if args.switch: - lpa.switch_profile(args.switch) - mutated = True - elif args.delete: - confirm = input('are you sure you want to delete this profile? (y/N) ') - if confirm == 'y': - lpa.delete_profile(args.delete) - mutated = True - else: - print('cancelled') - exit(0) - elif args.download: - lpa.download_profile(args.download[0], args.download[1]) - elif args.nickname: - lpa.nickname_profile(args.nickname[0], args.nickname[1]) - else: - parser.print_help() - - if mutated: - HARDWARE.reboot_modem() - # eUICC needs a small delay post-reboot before querying profiles - time.sleep(.5) - - profiles = lpa.list_profiles() - print(f'\n{len(profiles)} profile{"s" if len(profiles) > 1 else ""}:') - for p in profiles: - print(f'- {p.iccid} (nickname: {p.nickname or ""}) (provider: {p.provider}) - {"enabled" if p.enabled else "disabled"}') diff --git a/system/hardware/fan_controller.py b/system/hardware/fan_controller.py deleted file mode 100755 index 7d5bec0509..0000000000 --- a/system/hardware/fan_controller.py +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env python3 -import numpy as np -from abc import ABC, abstractmethod - -from openpilot.common.realtime import DT_HW -from openpilot.common.swaglog import cloudlog -from openpilot.common.pid import PIDController - -class BaseFanController(ABC): - @abstractmethod - def update(self, cur_temp: float, ignition: bool) -> int: - pass - - -class TiciFanController(BaseFanController): - def __init__(self) -> None: - super().__init__() - cloudlog.info("Setting up TICI fan handler") - - self.last_ignition = False - self.controller = PIDController(k_p=0, k_i=4e-3, k_f=1, rate=(1 / DT_HW)) - - def update(self, cur_temp: float, ignition: bool) -> int: - self.controller.neg_limit = -(100 if ignition else 30) - self.controller.pos_limit = -(30 if ignition else 0) - - if ignition != self.last_ignition: - self.controller.reset() - - error = 75 - cur_temp - fan_pwr_out = -int(self.controller.update( - error=error, - feedforward=np.interp(cur_temp, [60.0, 100.0], [0, -100]) - )) - - self.last_ignition = ignition - return fan_pwr_out - diff --git a/system/hardware/hw.h b/system/hardware/hw.h deleted file mode 100644 index d2083a5985..0000000000 --- a/system/hardware/hw.h +++ /dev/null @@ -1,58 +0,0 @@ -#pragma once - -#include - -#include "system/hardware/base.h" -#include "common/util.h" - -#if QCOM2 -#include "system/hardware/tici/hardware.h" -#define Hardware HardwareTici -#else -#include "system/hardware/pc/hardware.h" -#define Hardware HardwarePC -#endif - -namespace Path { - inline std::string openpilot_prefix() { - return util::getenv("OPENPILOT_PREFIX", ""); - } - - inline std::string comma_home() { - return util::getenv("HOME") + "/.comma" + Path::openpilot_prefix(); - } - - inline std::string log_root() { - if (const char *env = getenv("LOG_ROOT")) { - return env; - } - return Hardware::PC() ? Path::comma_home() + "/media/0/realdata" : "/data/media/0/realdata"; - } - - inline std::string params() { - return util::getenv("PARAMS_ROOT", Hardware::PC() ? (Path::comma_home() + "/params") : "/data/params"); - } - - inline std::string rsa_file() { - return Hardware::PC() ? Path::comma_home() + "/persist/comma/id_rsa" : "/persist/comma/id_rsa"; - } - - inline std::string swaglog_ipc() { - return "ipc:///tmp/logmessage" + Path::openpilot_prefix(); - } - - inline std::string download_cache_root() { - if (const char *env = getenv("COMMA_CACHE")) { - return env; - } - return "/tmp/comma_download_cache" + Path::openpilot_prefix() + "/"; - } - - inline std::string shm_path() { - #ifdef __APPLE__ - return"/tmp"; - #else - return "/dev/shm"; - #endif - } -} // namespace Path diff --git a/system/hardware/pc/hardware.h b/system/hardware/pc/hardware.h deleted file mode 100644 index 978dd771c8..0000000000 --- a/system/hardware/pc/hardware.h +++ /dev/null @@ -1,15 +0,0 @@ -#pragma once - -#include - -#include "system/hardware/base.h" - -class HardwarePC : public HardwareNone { -public: - static std::string get_os_version() { return "openpilot for PC"; } - static std::string get_name() { return "pc"; } - static cereal::InitData::DeviceType get_device_type() { return cereal::InitData::DeviceType::PC; } - static bool PC() { return true; } - static bool TICI() { return util::getenv("TICI", 0) == 1; } - static bool AGNOS() { return util::getenv("TICI", 0) == 1; } -}; diff --git a/system/hardware/pc/hardware.py b/system/hardware/pc/hardware.py deleted file mode 100644 index 9a80f10bed..0000000000 --- a/system/hardware/pc/hardware.py +++ /dev/null @@ -1,80 +0,0 @@ -import random - -from cereal import log -from openpilot.system.hardware.base import HardwareBase, LPABase - -NetworkType = log.DeviceState.NetworkType -NetworkStrength = log.DeviceState.NetworkStrength - -class Pc(HardwareBase): - def get_os_version(self): - return None - - def get_device_type(self): - return "pc" - - def reboot(self, reason=None): - print("REBOOT!") - - def uninstall(self): - print("uninstall") - - def get_imei(self, slot): - return f"{random.randint(0, 1 << 32):015d}" - - def get_serial(self): - return "cccccccc" - - def get_network_info(self): - return None - - def get_network_type(self): - return NetworkType.wifi - - def get_sim_info(self): - return { - 'sim_id': '', - 'mcc_mnc': None, - 'network_type': ["Unknown"], - 'sim_state': ["ABSENT"], - 'data_connected': False - } - - def get_sim_lpa(self) -> LPABase: - raise NotImplementedError("SIM LPA not implemented for PC") - - def get_network_strength(self, network_type): - return NetworkStrength.unknown - - def get_current_power_draw(self): - return 0 - - def get_som_power_draw(self): - return 0 - - def shutdown(self): - print("SHUTDOWN!") - - def set_screen_brightness(self, percentage): - pass - - def get_screen_brightness(self): - return 0 - - def set_power_save(self, powersave_enabled): - pass - - def get_gpu_usage_percent(self): - return 0 - - def get_modem_temperatures(self): - return [] - - def get_nvme_temperatures(self): - return [] - - def initialize_hardware(self): - pass - - def get_networks(self): - return None diff --git a/system/hardware/tests/test_fan_controller.py b/system/hardware/tests/test_fan_controller.py deleted file mode 100644 index 002c1edfda..0000000000 --- a/system/hardware/tests/test_fan_controller.py +++ /dev/null @@ -1,50 +0,0 @@ -import pytest - -from openpilot.system.hardware.fan_controller import TiciFanController - -ALL_CONTROLLERS = [TiciFanController] - -def patched_controller(mocker, controller_class): - mocker.patch("os.system", new=mocker.Mock()) - return controller_class() - -class TestFanController: - def wind_up(self, controller, ignition=True): - for _ in range(1000): - controller.update(100, ignition) - - def wind_down(self, controller, ignition=False): - for _ in range(1000): - controller.update(10, ignition) - - @pytest.mark.parametrize("controller_class", ALL_CONTROLLERS) - def test_hot_onroad(self, mocker, controller_class): - controller = patched_controller(mocker, controller_class) - self.wind_up(controller) - assert controller.update(100, True) >= 70 - - @pytest.mark.parametrize("controller_class", ALL_CONTROLLERS) - def test_offroad_limits(self, mocker, controller_class): - controller = patched_controller(mocker, controller_class) - self.wind_up(controller) - assert controller.update(100, False) <= 30 - - @pytest.mark.parametrize("controller_class", ALL_CONTROLLERS) - def test_no_fan_wear(self, mocker, controller_class): - controller = patched_controller(mocker, controller_class) - self.wind_down(controller) - assert controller.update(10, False) == 0 - - @pytest.mark.parametrize("controller_class", ALL_CONTROLLERS) - def test_limited(self, mocker, controller_class): - controller = patched_controller(mocker, controller_class) - self.wind_up(controller, True) - assert controller.update(100, True) == 100 - - @pytest.mark.parametrize("controller_class", ALL_CONTROLLERS) - def test_windup_speed(self, mocker, controller_class): - controller = patched_controller(mocker, controller_class) - self.wind_down(controller, True) - for _ in range(10): - controller.update(90, True) - assert controller.update(90, True) >= 60 diff --git a/system/hardware/tici/agnos.json b/system/hardware/tici/agnos.json deleted file mode 100644 index ec2557422c..0000000000 --- a/system/hardware/tici/agnos.json +++ /dev/null @@ -1,84 +0,0 @@ -[ - { - "name": "xbl", - "url": "https://commadist.azureedge.net/agnosupdate/xbl-6710967ca9701f205d7ab19c3a9b0dd2f547e65b3d96048b7c2b03755aafa0f1.img.xz", - "hash": "6710967ca9701f205d7ab19c3a9b0dd2f547e65b3d96048b7c2b03755aafa0f1", - "hash_raw": "6710967ca9701f205d7ab19c3a9b0dd2f547e65b3d96048b7c2b03755aafa0f1", - "size": 3282256, - "sparse": false, - "full_check": true, - "has_ab": true, - "ondevice_hash": "003a17ab1be68a696f7efe4c9938e8be511d4aacfc2f3211fc896bdc1681d089" - }, - { - "name": "xbl_config", - "url": "https://commadist.azureedge.net/agnosupdate/xbl_config-63922cfbfdf4ab87986c4ba8f3a4df5bf28414b3f71a29ec5947336722215535.img.xz", - "hash": "63922cfbfdf4ab87986c4ba8f3a4df5bf28414b3f71a29ec5947336722215535", - "hash_raw": "63922cfbfdf4ab87986c4ba8f3a4df5bf28414b3f71a29ec5947336722215535", - "size": 98124, - "sparse": false, - "full_check": true, - "has_ab": true, - "ondevice_hash": "2a855dd636cc94718b64bea83a44d0a31741ecaa8f72a63613ff348ec7404091" - }, - { - "name": "abl", - "url": "https://commadist.azureedge.net/agnosupdate/abl-32a2174b5f764e95dfc54cf358ba01752943b1b3b90e626149c3da7d5f1830b6.img.xz", - "hash": "32a2174b5f764e95dfc54cf358ba01752943b1b3b90e626149c3da7d5f1830b6", - "hash_raw": "32a2174b5f764e95dfc54cf358ba01752943b1b3b90e626149c3da7d5f1830b6", - "size": 274432, - "sparse": false, - "full_check": true, - "has_ab": true, - "ondevice_hash": "32a2174b5f764e95dfc54cf358ba01752943b1b3b90e626149c3da7d5f1830b6" - }, - { - "name": "aop", - "url": "https://commadist.azureedge.net/agnosupdate/aop-21370172e590bd4ea907a558bcd6df20dc7a6c7d38b8e62fdde18f4a512ba9e9.img.xz", - "hash": "21370172e590bd4ea907a558bcd6df20dc7a6c7d38b8e62fdde18f4a512ba9e9", - "hash_raw": "21370172e590bd4ea907a558bcd6df20dc7a6c7d38b8e62fdde18f4a512ba9e9", - "size": 184364, - "sparse": false, - "full_check": true, - "has_ab": true, - "ondevice_hash": "c1be2f4aac5b3af49b904b027faec418d05efd7bd5144eb4fdfcba602bcf2180" - }, - { - "name": "devcfg", - "url": "https://commadist.azureedge.net/agnosupdate/devcfg-d7d7e52963bbedbbf8a7e66847579ca106a0a729ce2cf60f4b8d8ea4b535d620.img.xz", - "hash": "d7d7e52963bbedbbf8a7e66847579ca106a0a729ce2cf60f4b8d8ea4b535d620", - "hash_raw": "d7d7e52963bbedbbf8a7e66847579ca106a0a729ce2cf60f4b8d8ea4b535d620", - "size": 40336, - "sparse": false, - "full_check": true, - "has_ab": true, - "ondevice_hash": "17b229668b20305ff8fa3cd5f94716a3aaa1e5bf9d1c24117eff7f2f81ae719f" - }, - { - "name": "boot", - "url": "https://commadist.azureedge.net/agnosupdate/boot-4de8f892dbac3fa3fee1efe68ca76e23e75812e81a6577d00d52e2da1ef624ef.img.xz", - "hash": "4de8f892dbac3fa3fee1efe68ca76e23e75812e81a6577d00d52e2da1ef624ef", - "hash_raw": "4de8f892dbac3fa3fee1efe68ca76e23e75812e81a6577d00d52e2da1ef624ef", - "size": 18479104, - "sparse": false, - "full_check": true, - "has_ab": true, - "ondevice_hash": "8d7094d774faa4e801e36b403a31b53b913b31d086f4dc682d2f64710c557e8a" - }, - { - "name": "system", - "url": "https://commadist.azureedge.net/agnosupdate/system-4bc3951f4aa3f70c53837dc2542d8b0666d37103b353fd81417cc7de1bbebe39.img.xz", - "hash": "cccd7073d067027396f2afd49874729757db0bbbc79853a0bf2938bd356fe164", - "hash_raw": "4bc3951f4aa3f70c53837dc2542d8b0666d37103b353fd81417cc7de1bbebe39", - "size": 5368709120, - "sparse": true, - "full_check": false, - "has_ab": true, - "ondevice_hash": "c7707f16ce7d977748677cc354e250943b4ff6c21b9a19a492053d32397cf9ec", - "alt": { - "hash": "4bc3951f4aa3f70c53837dc2542d8b0666d37103b353fd81417cc7de1bbebe39", - "url": "https://commadist.azureedge.net/agnosupdate/system-4bc3951f4aa3f70c53837dc2542d8b0666d37103b353fd81417cc7de1bbebe39.img", - "size": 5368709120 - } - } -] \ No newline at end of file diff --git a/system/hardware/tici/amplifier.py b/system/hardware/tici/amplifier.py deleted file mode 100755 index f6b29ec0ce..0000000000 --- a/system/hardware/tici/amplifier.py +++ /dev/null @@ -1,158 +0,0 @@ -#!/usr/bin/env python3 -import time -from smbus2 import SMBus -from collections import namedtuple - -# https://datasheets.maximintegrated.com/en/ds/MAX98089.pdf - -AmpConfig = namedtuple('AmpConfig', ['name', 'value', 'register', 'offset', 'mask']) -EQParams = namedtuple('EQParams', ['K', 'k1', 'k2', 'c1', 'c2']) - -def configs_from_eq_params(base, eq_params): - return [ - AmpConfig("K (high)", (eq_params.K >> 8), base, 0, 0xFF), - AmpConfig("K (low)", (eq_params.K & 0xFF), base + 1, 0, 0xFF), - AmpConfig("k1 (high)", (eq_params.k1 >> 8), base + 2, 0, 0xFF), - AmpConfig("k1 (low)", (eq_params.k1 & 0xFF), base + 3, 0, 0xFF), - AmpConfig("k2 (high)", (eq_params.k2 >> 8), base + 4, 0, 0xFF), - AmpConfig("k2 (low)", (eq_params.k2 & 0xFF), base + 5, 0, 0xFF), - AmpConfig("c1 (high)", (eq_params.c1 >> 8), base + 6, 0, 0xFF), - AmpConfig("c1 (low)", (eq_params.c1 & 0xFF), base + 7, 0, 0xFF), - AmpConfig("c2 (high)", (eq_params.c2 >> 8), base + 8, 0, 0xFF), - AmpConfig("c2 (low)", (eq_params.c2 & 0xFF), base + 9, 0, 0xFF), - ] - -BASE_CONFIG = [ - AmpConfig("MCLK prescaler", 0b01, 0x10, 4, 0b00110000), - AmpConfig("PM: enable speakers", 0b11, 0x4D, 4, 0b00110000), - AmpConfig("PM: enable DACs", 0b11, 0x4D, 0, 0b00000011), - AmpConfig("Enable PLL1", 0b1, 0x12, 7, 0b10000000), - AmpConfig("Enable PLL2", 0b1, 0x1A, 7, 0b10000000), - AmpConfig("DAI1: I2S mode", 0b00100, 0x14, 2, 0b01111100), - AmpConfig("DAI2: I2S mode", 0b00100, 0x1C, 2, 0b01111100), - AmpConfig("DAI1 Passband filtering: music mode", 0b1, 0x18, 7, 0b10000000), - AmpConfig("DAI1 voice mode gain (DV1G)", 0b00, 0x2F, 4, 0b00110000), - AmpConfig("DAI1 attenuation (DV1)", 0x0, 0x2F, 0, 0b00001111), - AmpConfig("DAI2 attenuation (DV2)", 0x0, 0x31, 0, 0b00001111), - AmpConfig("DAI2: DC blocking", 0b1, 0x20, 0, 0b00000001), - AmpConfig("DAI2: High sample rate", 0b0, 0x20, 3, 0b00001000), - AmpConfig("ALC enable", 0b1, 0x43, 7, 0b10000000), - AmpConfig("ALC/excursion limiter release time", 0b101, 0x43, 4, 0b01110000), - AmpConfig("ALC multiband enable", 0b1, 0x43, 3, 0b00001000), - AmpConfig("DAI1 EQ enable", 0b0, 0x49, 0, 0b00000001), - AmpConfig("DAI2 EQ clip detection disabled", 0b1, 0x32, 4, 0b00010000), - AmpConfig("DAI2 EQ attenuation", 0x5, 0x32, 0, 0b00001111), - AmpConfig("Excursion limiter upper corner freq", 0b100, 0x41, 4, 0b01110000), - AmpConfig("Excursion limiter lower corner freq", 0b00, 0x41, 0, 0b00000011), - AmpConfig("Excursion limiter threshold", 0b000, 0x42, 0, 0b00001111), - AmpConfig("Distortion limit (THDCLP)", 0x6, 0x46, 4, 0b11110000), - AmpConfig("Distortion limiter release time constant", 0b0, 0x46, 0, 0b00000001), - AmpConfig("Right DAC input mixer: DAI1 left", 0b0, 0x22, 3, 0b00001000), - AmpConfig("Right DAC input mixer: DAI1 right", 0b0, 0x22, 2, 0b00000100), - AmpConfig("Right DAC input mixer: DAI2 left", 0b1, 0x22, 1, 0b00000010), - AmpConfig("Right DAC input mixer: DAI2 right", 0b0, 0x22, 0, 0b00000001), - AmpConfig("DAI1 audio port selector", 0b10, 0x16, 6, 0b11000000), - AmpConfig("DAI2 audio port selector", 0b01, 0x1E, 6, 0b11000000), - AmpConfig("Enable left digital microphone", 0b1, 0x48, 5, 0b00100000), - AmpConfig("Enable right digital microphone", 0b1, 0x48, 4, 0b00010000), - AmpConfig("Enhanced volume smoothing disabled", 0b0, 0x49, 7, 0b10000000), - AmpConfig("Volume adjustment smoothing disabled", 0b0, 0x49, 6, 0b01000000), - AmpConfig("Zero-crossing detection disabled", 0b0, 0x49, 5, 0b00100000), -] - -CONFIGS = { - "tici": [ - AmpConfig("Right speaker output from right DAC", 0b1, 0x2C, 0, 0b11111111), - AmpConfig("Right Speaker Mixer Gain", 0b00, 0x2D, 2, 0b00001100), - AmpConfig("Right speaker output volume", 0x1c, 0x3E, 0, 0b00011111), - AmpConfig("DAI2 EQ enable", 0b1, 0x49, 1, 0b00000010), - - *configs_from_eq_params(0x84, EQParams(0x274F, 0xC0FF, 0x3BF9, 0x0B3C, 0x1656)), - *configs_from_eq_params(0x8E, EQParams(0x1009, 0xC6BF, 0x2952, 0x1C97, 0x30DF)), - *configs_from_eq_params(0x98, EQParams(0x0F75, 0xCBE5, 0x0ED2, 0x2528, 0x3E42)), - *configs_from_eq_params(0xA2, EQParams(0x091F, 0x3D4C, 0xCE11, 0x1266, 0x2807)), - *configs_from_eq_params(0xAC, EQParams(0x0A9E, 0x3F20, 0xE573, 0x0A8B, 0x3A3B)), - ], - "tizi": [ - AmpConfig("Left speaker output from left DAC", 0b1, 0x2B, 0, 0b11111111), - AmpConfig("Right speaker output from right DAC", 0b1, 0x2C, 0, 0b11111111), - AmpConfig("Left Speaker Mixer Gain", 0b00, 0x2D, 0, 0b00000011), - AmpConfig("Right Speaker Mixer Gain", 0b00, 0x2D, 2, 0b00001100), - AmpConfig("Left speaker output volume", 0x17, 0x3D, 0, 0b00011111), - AmpConfig("Right speaker output volume", 0x17, 0x3E, 0, 0b00011111), - - AmpConfig("DAI2 EQ enable", 0b0, 0x49, 1, 0b00000010), - AmpConfig("DAI2: DC blocking", 0b0, 0x20, 0, 0b00000001), - AmpConfig("ALC enable", 0b0, 0x43, 7, 0b10000000), - AmpConfig("DAI2 EQ attenuation", 0x2, 0x32, 0, 0b00001111), - AmpConfig("Excursion limiter upper corner freq", 0b001, 0x41, 4, 0b01110000), - AmpConfig("Excursion limiter threshold", 0b100, 0x42, 0, 0b00001111), - AmpConfig("Distortion limit (THDCLP)", 0x0, 0x46, 4, 0b11110000), - AmpConfig("Distortion limiter release time constant", 0b1, 0x46, 0, 0b00000001), - AmpConfig("Left DAC input mixer: DAI1 left", 0b0, 0x22, 7, 0b10000000), - AmpConfig("Left DAC input mixer: DAI1 right", 0b0, 0x22, 6, 0b01000000), - AmpConfig("Left DAC input mixer: DAI2 left", 0b1, 0x22, 5, 0b00100000), - AmpConfig("Left DAC input mixer: DAI2 right", 0b0, 0x22, 4, 0b00010000), - AmpConfig("Right DAC input mixer: DAI2 left", 0b0, 0x22, 1, 0b00000010), - AmpConfig("Right DAC input mixer: DAI2 right", 0b1, 0x22, 0, 0b00000001), - AmpConfig("Volume adjustment smoothing disabled", 0b1, 0x49, 6, 0b01000000), - ], -} - -class Amplifier: - AMP_I2C_BUS = 0 - AMP_ADDRESS = 0x10 - - def __init__(self, debug=False): - self.debug = debug - - def _get_shutdown_config(self, amp_disabled: bool) -> AmpConfig: - return AmpConfig("Global shutdown", 0b0 if amp_disabled else 0b1, 0x51, 7, 0b10000000) - - def _set_configs(self, configs: list[AmpConfig]) -> None: - with SMBus(self.AMP_I2C_BUS) as bus: - for config in configs: - if self.debug: - print(f"Setting \"{config.name}\" to {config.value}:") - - old_value = bus.read_byte_data(self.AMP_ADDRESS, config.register, force=True) - new_value = (old_value & (~config.mask)) | ((config.value << config.offset) & config.mask) - bus.write_byte_data(self.AMP_ADDRESS, config.register, new_value, force=True) - - if self.debug: - print(f" Changed {hex(config.register)}: {hex(old_value)} -> {hex(new_value)}") - - def set_configs(self, configs: list[AmpConfig]) -> bool: - # retry in case panda is using the amp - tries = 15 - backoff = 0. - for i in range(tries): - try: - self._set_configs(configs) - return True - except OSError: - backoff += 0.1 - time.sleep(backoff) - print(f"Failed to set amp config, {tries - i - 1} retries left") - return False - - def set_global_shutdown(self, amp_disabled: bool) -> bool: - return self.set_configs([self._get_shutdown_config(amp_disabled), ]) - - def initialize_configuration(self, model: str) -> bool: - cfgs = [ - self._get_shutdown_config(True), - *BASE_CONFIG, - *CONFIGS[model], - self._get_shutdown_config(False), - ] - return self.set_configs(cfgs) - - -if __name__ == "__main__": - with open("/sys/firmware/devicetree/base/model") as f: - model = f.read().strip('\x00') - model = model.split('comma ')[-1] - - amp = Amplifier() - amp.initialize_configuration(model) diff --git a/system/hardware/tici/esim.nmconnection b/system/hardware/tici/esim.nmconnection deleted file mode 100644 index 74f6f8e82c..0000000000 --- a/system/hardware/tici/esim.nmconnection +++ /dev/null @@ -1,30 +0,0 @@ -[connection] -id=esim -uuid=fff6553c-3284-4707-a6b1-acc021caaafb -type=gsm -permissions= -autoconnect=true -autoconnect-retries=100 -autoconnect-priority=2 -metered=1 - -[gsm] -apn= -home-only=false -auto-config=true -sim-id= - -[ipv4] -route-metric=1000 -dns-priority=1000 -dns-search= -method=auto - -[ipv6] -ddr-gen-mode=stable-privacy -dns-search= -route-metric=1000 -dns-priority=1000 -method=auto - -[proxy] diff --git a/system/hardware/tici/esim.py b/system/hardware/tici/esim.py deleted file mode 100644 index b489286f50..0000000000 --- a/system/hardware/tici/esim.py +++ /dev/null @@ -1,106 +0,0 @@ -import json -import os -import shutil -import subprocess -from typing import Literal - -from openpilot.system.hardware.base import LPABase, LPAError, LPAProfileNotFoundError, Profile - -class TiciLPA(LPABase): - def __init__(self, interface: Literal['qmi', 'at'] = 'qmi'): - self.env = os.environ.copy() - self.env['LPAC_APDU'] = interface - self.env['QMI_DEVICE'] = '/dev/cdc-wdm0' - self.env['AT_DEVICE'] = '/dev/ttyUSB2' - - self.timeout_sec = 45 - - if shutil.which('lpac') is None: - raise LPAError('lpac not found, must be installed!') - - def list_profiles(self) -> list[Profile]: - msgs = self._invoke('profile', 'list') - self._validate_successful(msgs) - return [Profile( - iccid=p['iccid'], - nickname=p['profileNickname'], - enabled=p['profileState'] == 'enabled', - provider=p['serviceProviderName'] - ) for p in msgs[-1]['payload']['data']] - - def get_active_profile(self) -> Profile | None: - return next((p for p in self.list_profiles() if p.enabled), None) - - def delete_profile(self, iccid: str) -> None: - self._validate_profile_exists(iccid) - latest = self.get_active_profile() - if latest is not None and latest.iccid == iccid: - raise LPAError('cannot delete active profile, switch to another profile first') - self._validate_successful(self._invoke('profile', 'delete', iccid)) - self._process_notifications() - - def download_profile(self, qr: str, nickname: str | None = None) -> None: - msgs = self._invoke('profile', 'download', '-a', qr) - self._validate_successful(msgs) - new_profile = next((m for m in msgs if m['payload']['message'] == 'es8p_meatadata_parse'), None) - if new_profile is None: - raise LPAError('no new profile found') - if nickname: - self.nickname_profile(new_profile['payload']['data']['iccid'], nickname) - self._process_notifications() - - def nickname_profile(self, iccid: str, nickname: str) -> None: - self._validate_profile_exists(iccid) - self._validate_successful(self._invoke('profile', 'nickname', iccid, nickname)) - - def switch_profile(self, iccid: str) -> None: - self._validate_profile_exists(iccid) - latest = self.get_active_profile() - if latest and latest.iccid == iccid: - return - self._validate_successful(self._invoke('profile', 'enable', iccid)) - self._process_notifications() - - def _invoke(self, *cmd: str): - proc = subprocess.Popen(['sudo', '-E', 'lpac'] + list(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=self.env) - try: - out, err = proc.communicate(timeout=self.timeout_sec) - except subprocess.TimeoutExpired as e: - proc.kill() - raise LPAError(f"lpac {cmd} timed out after {self.timeout_sec} seconds") from e - - messages = [] - for line in out.decode().strip().splitlines(): - if line.startswith('{'): - message = json.loads(line) - - # lpac response format validations - assert 'type' in message, 'expected type in message' - assert message['type'] == 'lpa' or message['type'] == 'progress', 'expected lpa or progress message type' - assert 'payload' in message, 'expected payload in message' - assert 'code' in message['payload'], 'expected code in message payload' - assert 'data' in message['payload'], 'expected data in message payload' - - msg_ret_code = message['payload']['code'] - if msg_ret_code != 0: - raise LPAError(f"lpac {' '.join(cmd)} failed with code {msg_ret_code}: <{message['payload']['message']}> {message['payload']['data']}") - - messages.append(message) - - if len(messages) == 0: - raise LPAError(f"lpac {cmd} returned no messages") - - return messages - - def _process_notifications(self) -> None: - """ - Process notifications stored on the eUICC, typically to activate/deactivate the profile with the carrier. - """ - self._validate_successful(self._invoke('notification', 'process', '-a', '-r')) - - def _validate_profile_exists(self, iccid: str) -> None: - if not any(p.iccid == iccid for p in self.list_profiles()): - raise LPAProfileNotFoundError(f'profile {iccid} does not exist') - - def _validate_successful(self, msgs: list[dict]) -> None: - assert msgs[-1]['payload']['message'] == 'success', 'expected success notification' diff --git a/system/hardware/tici/hardware.h b/system/hardware/tici/hardware.h deleted file mode 100644 index 179ef54a9b..0000000000 --- a/system/hardware/tici/hardware.h +++ /dev/null @@ -1,112 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include // for std::clamp - -#include "common/params.h" -#include "common/util.h" -#include "system/hardware/base.h" - -class HardwareTici : public HardwareNone { -public: - static constexpr float MAX_VOLUME = 0.9; - static constexpr float MIN_VOLUME = 0.1; - static bool TICI() { return true; } - static bool AGNOS() { return true; } - static std::string get_os_version() { - return "AGNOS " + util::read_file("/VERSION"); - } - - static std::string get_name() { - std::string model = util::read_file("/sys/firmware/devicetree/base/model"); - return util::strip(model.substr(std::string("comma ").size())); - } - - static cereal::InitData::DeviceType get_device_type() { - static const std::map device_map = { - {"tici", cereal::InitData::DeviceType::TICI}, - {"tizi", cereal::InitData::DeviceType::TIZI}, - {"mici", cereal::InitData::DeviceType::MICI} - }; - auto it = device_map.find(get_name()); - assert(it != device_map.end()); - return it->second; - } - - static int get_voltage() { return std::atoi(util::read_file("/sys/class/hwmon/hwmon1/in1_input").c_str()); } - static int get_current() { return std::atoi(util::read_file("/sys/class/hwmon/hwmon1/curr1_input").c_str()); } - - static std::string get_serial() { - static std::string serial(""); - if (serial.empty()) { - std::ifstream stream("/proc/cmdline"); - std::string cmdline; - std::getline(stream, cmdline); - - auto start = cmdline.find("serialno="); - if (start == std::string::npos) { - serial = "cccccc"; - } else { - auto end = cmdline.find(" ", start + 9); - serial = cmdline.substr(start + 9, end - start - 9); - } - } - return serial; - } - - static void reboot() { std::system("sudo reboot"); } - static void poweroff() { std::system("sudo poweroff"); } - static void set_brightness(int percent) { - float max = std::stof(util::read_file("/sys/class/backlight/panel0-backlight/max_brightness")); - std::ofstream("/sys/class/backlight/panel0-backlight/brightness") << int(percent * (max / 100.0f)) << "\n"; - } - static void set_display_power(bool on) { - std::ofstream("/sys/class/backlight/panel0-backlight/bl_power") << (on ? "0" : "4") << "\n"; - } - - static void set_ir_power(int percent) { - auto device = get_device_type(); - if (device == cereal::InitData::DeviceType::TICI || - device == cereal::InitData::DeviceType::TIZI) { - return; - } - - int value = util::map_val(std::clamp(percent, 0, 100), 0, 100, 0, 255); - std::ofstream("/sys/class/leds/led:switch_2/brightness") << 0 << "\n"; - std::ofstream("/sys/class/leds/led:torch_2/brightness") << value << "\n"; - std::ofstream("/sys/class/leds/led:switch_2/brightness") << value << "\n"; - } - - static std::map get_init_logs() { - std::map ret = { - {"/BUILD", util::read_file("/BUILD")}, - {"lsblk", util::check_output("lsblk -o NAME,SIZE,STATE,VENDOR,MODEL,REV,SERIAL")}, - {"SOM ID", util::read_file("/sys/devices/platform/vendor/vendor:gpio-som-id/som_id")}, - }; - - std::string bs = util::check_output("abctl --boot_slot"); - ret["boot slot"] = bs.substr(0, bs.find_first_of("\n")); - - std::string temp = util::read_file("/dev/disk/by-partlabel/ssd"); - temp.erase(temp.find_last_not_of(std::string("\0\r\n", 3))+1); - ret["boot temp"] = temp; - - // TODO: log something from system and boot - for (std::string part : {"xbl", "abl", "aop", "devcfg", "xbl_config"}) { - for (std::string slot : {"a", "b"}) { - std::string partition = part + "_" + slot; - std::string hash = util::check_output("sha256sum /dev/disk/by-partlabel/" + partition); - ret[partition] = hash.substr(0, hash.find_first_of(" ")); - } - } - - return ret; - } - - static bool get_ssh_enabled() { return Params().getBool("SshEnabled"); } - static void set_ssh_enabled(bool enabled) { Params().putBool("SshEnabled", enabled); } -}; diff --git a/system/hardware/tici/hardware.py b/system/hardware/tici/hardware.py deleted file mode 100644 index 8e4ba722c4..0000000000 --- a/system/hardware/tici/hardware.py +++ /dev/null @@ -1,594 +0,0 @@ -import json -import math -import os -import subprocess -import time -import tempfile -from enum import IntEnum -from functools import cached_property, lru_cache -from pathlib import Path - -from cereal import log -from openpilot.common.util import sudo_read, sudo_write -from openpilot.common.gpio import gpio_set, gpio_init, get_irqs_for_action -from openpilot.system.hardware.base import HardwareBase, LPABase, ThermalConfig, ThermalZone -from openpilot.system.hardware.tici import iwlist -from openpilot.system.hardware.tici.esim import TiciLPA -from openpilot.system.hardware.tici.pins import GPIO -from openpilot.system.hardware.tici.amplifier import Amplifier - -NM = 'org.freedesktop.NetworkManager' -NM_CON_ACT = NM + '.Connection.Active' -NM_DEV = NM + '.Device' -NM_DEV_WL = NM + '.Device.Wireless' -NM_DEV_STATS = NM + '.Device.Statistics' -NM_AP = NM + '.AccessPoint' -DBUS_PROPS = 'org.freedesktop.DBus.Properties' - -MM = 'org.freedesktop.ModemManager1' -MM_MODEM = MM + ".Modem" -MM_MODEM_SIMPLE = MM + ".Modem.Simple" -MM_SIM = MM + ".Sim" - -class MM_MODEM_STATE(IntEnum): - FAILED = -1 - UNKNOWN = 0 - INITIALIZING = 1 - LOCKED = 2 - DISABLED = 3 - DISABLING = 4 - ENABLING = 5 - ENABLED = 6 - SEARCHING = 7 - REGISTERED = 8 - DISCONNECTING = 9 - CONNECTING = 10 - CONNECTED = 11 - -class NMMetered(IntEnum): - NM_METERED_UNKNOWN = 0 - NM_METERED_YES = 1 - NM_METERED_NO = 2 - NM_METERED_GUESS_YES = 3 - NM_METERED_GUESS_NO = 4 - -TIMEOUT = 0.1 -REFRESH_RATE_MS = 1000 - -NetworkType = log.DeviceState.NetworkType -NetworkStrength = log.DeviceState.NetworkStrength - -# https://developer.gnome.org/ModemManager/unstable/ModemManager-Flags-and-Enumerations.html#MMModemAccessTechnology -MM_MODEM_ACCESS_TECHNOLOGY_UMTS = 1 << 5 -MM_MODEM_ACCESS_TECHNOLOGY_LTE = 1 << 14 - - -def affine_irq(val, action): - irqs = get_irqs_for_action(action) - if len(irqs) == 0: - print(f"No IRQs found for '{action}'") - return - - for i in irqs: - sudo_write(str(val), f"/proc/irq/{i}/smp_affinity_list") - -@lru_cache -def get_device_type(): - # lru_cache and cache can cause memory leaks when used in classes - with open("/sys/firmware/devicetree/base/model") as f: - model = f.read().strip('\x00') - return model.split('comma ')[-1] - -class Tici(HardwareBase): - @cached_property - def bus(self): - import dbus - return dbus.SystemBus() - - @cached_property - def nm(self): - return self.bus.get_object(NM, '/org/freedesktop/NetworkManager') - - @property # this should not be cached, in case the modemmanager restarts - def mm(self): - return self.bus.get_object(MM, '/org/freedesktop/ModemManager1') - - @cached_property - def amplifier(self): - if self.get_device_type() == "mici": - return None - return Amplifier() - - def get_os_version(self): - with open("/VERSION") as f: - return f.read().strip() - - def get_device_type(self): - return get_device_type() - - def reboot(self, reason=None): - subprocess.check_output(["sudo", "reboot"]) - - def uninstall(self): - Path("/data/__system_reset__").touch() - os.sync() - self.reboot() - - def get_serial(self): - return self.get_cmdline()['androidboot.serialno'] - - def get_network_type(self): - try: - primary_connection = self.nm.Get(NM, 'PrimaryConnection', dbus_interface=DBUS_PROPS, timeout=TIMEOUT) - primary_connection = self.bus.get_object(NM, primary_connection) - primary_type = primary_connection.Get(NM_CON_ACT, 'Type', dbus_interface=DBUS_PROPS, timeout=TIMEOUT) - - if primary_type == '802-3-ethernet': - return NetworkType.ethernet - elif primary_type == '802-11-wireless': - return NetworkType.wifi - else: - active_connections = self.nm.Get(NM, 'ActiveConnections', dbus_interface=DBUS_PROPS, timeout=TIMEOUT) - for conn in active_connections: - c = self.bus.get_object(NM, conn) - tp = c.Get(NM_CON_ACT, 'Type', dbus_interface=DBUS_PROPS, timeout=TIMEOUT) - if tp == 'gsm': - modem = self.get_modem() - access_t = modem.Get(MM_MODEM, 'AccessTechnologies', dbus_interface=DBUS_PROPS, timeout=TIMEOUT) - if access_t >= MM_MODEM_ACCESS_TECHNOLOGY_LTE: - return NetworkType.cell4G - elif access_t >= MM_MODEM_ACCESS_TECHNOLOGY_UMTS: - return NetworkType.cell3G - else: - return NetworkType.cell2G - except Exception: - pass - - return NetworkType.none - - def get_modem(self): - objects = self.mm.GetManagedObjects(dbus_interface="org.freedesktop.DBus.ObjectManager", timeout=TIMEOUT) - modem_path = list(objects.keys())[0] - return self.bus.get_object(MM, modem_path) - - def get_wlan(self): - wlan_path = self.nm.GetDeviceByIpIface('wlan0', dbus_interface=NM, timeout=TIMEOUT) - return self.bus.get_object(NM, wlan_path) - - def get_wwan(self): - wwan_path = self.nm.GetDeviceByIpIface('wwan0', dbus_interface=NM, timeout=TIMEOUT) - return self.bus.get_object(NM, wwan_path) - - def get_sim_info(self): - modem = self.get_modem() - sim_path = modem.Get(MM_MODEM, 'Sim', dbus_interface=DBUS_PROPS, timeout=TIMEOUT) - - if sim_path == "/": - return { - 'sim_id': '', - 'mcc_mnc': None, - 'network_type': ["Unknown"], - 'sim_state': ["ABSENT"], - 'data_connected': False - } - else: - sim = self.bus.get_object(MM, sim_path) - return { - 'sim_id': str(sim.Get(MM_SIM, 'SimIdentifier', dbus_interface=DBUS_PROPS, timeout=TIMEOUT)), - 'mcc_mnc': str(sim.Get(MM_SIM, 'OperatorIdentifier', dbus_interface=DBUS_PROPS, timeout=TIMEOUT)), - 'network_type': ["Unknown"], - 'sim_state': ["READY"], - 'data_connected': modem.Get(MM_MODEM, 'State', dbus_interface=DBUS_PROPS, timeout=TIMEOUT) == MM_MODEM_STATE.CONNECTED, - } - - def get_sim_lpa(self) -> LPABase: - return TiciLPA() - - def get_imei(self, slot): - if slot != 0: - return "" - - return str(self.get_modem().Get(MM_MODEM, 'EquipmentIdentifier', dbus_interface=DBUS_PROPS, timeout=TIMEOUT)) - - def get_network_info(self): - if self.get_device_type() == "mici": - return None - try: - modem = self.get_modem() - info = modem.Command("AT+QNWINFO", math.ceil(TIMEOUT), dbus_interface=MM_MODEM, timeout=TIMEOUT) - extra = modem.Command('AT+QENG="servingcell"', math.ceil(TIMEOUT), dbus_interface=MM_MODEM, timeout=TIMEOUT) - state = modem.Get(MM_MODEM, 'State', dbus_interface=DBUS_PROPS, timeout=TIMEOUT) - except Exception: - return None - - if info and info.startswith('+QNWINFO: '): - info = info.replace('+QNWINFO: ', '').replace('"', '').split(',') - extra = "" if extra is None else extra.replace('+QENG: "servingcell",', '').replace('"', '') - state = "" if state is None else MM_MODEM_STATE(state).name - - if len(info) != 4: - return None - - technology, operator, band, channel = info - - return({ - 'technology': technology, - 'operator': operator, - 'band': band, - 'channel': int(channel), - 'extra': extra, - 'state': state, - }) - else: - return None - - def parse_strength(self, percentage): - if percentage < 25: - return NetworkStrength.poor - elif percentage < 50: - return NetworkStrength.moderate - elif percentage < 75: - return NetworkStrength.good - else: - return NetworkStrength.great - - def get_network_strength(self, network_type): - network_strength = NetworkStrength.unknown - - try: - if network_type == NetworkType.none: - pass - elif network_type == NetworkType.wifi: - wlan = self.get_wlan() - active_ap_path = wlan.Get(NM_DEV_WL, 'ActiveAccessPoint', dbus_interface=DBUS_PROPS, timeout=TIMEOUT) - if active_ap_path != "/": - active_ap = self.bus.get_object(NM, active_ap_path) - strength = int(active_ap.Get(NM_AP, 'Strength', dbus_interface=DBUS_PROPS, timeout=TIMEOUT)) - network_strength = self.parse_strength(strength) - else: # Cellular - modem = self.get_modem() - strength = int(modem.Get(MM_MODEM, 'SignalQuality', dbus_interface=DBUS_PROPS, timeout=TIMEOUT)[0]) - network_strength = self.parse_strength(strength) - except Exception: - pass - - return network_strength - - def get_network_metered(self, network_type) -> bool: - try: - primary_connection = self.nm.Get(NM, 'PrimaryConnection', dbus_interface=DBUS_PROPS, timeout=TIMEOUT) - primary_connection = self.bus.get_object(NM, primary_connection) - primary_devices = primary_connection.Get(NM_CON_ACT, 'Devices', dbus_interface=DBUS_PROPS, timeout=TIMEOUT) - - for dev in primary_devices: - dev_obj = self.bus.get_object(NM, str(dev)) - metered_prop = dev_obj.Get(NM_DEV, 'Metered', dbus_interface=DBUS_PROPS, timeout=TIMEOUT) - - if network_type == NetworkType.wifi: - if metered_prop in [NMMetered.NM_METERED_YES, NMMetered.NM_METERED_GUESS_YES]: - return True - elif network_type in [NetworkType.cell2G, NetworkType.cell3G, NetworkType.cell4G, NetworkType.cell5G]: - if metered_prop == NMMetered.NM_METERED_NO: - return False - except Exception: - pass - - return super().get_network_metered(network_type) - - def get_modem_version(self): - try: - modem = self.get_modem() - return modem.Get(MM_MODEM, 'Revision', dbus_interface=DBUS_PROPS, timeout=TIMEOUT) - except Exception: - return None - - def get_modem_temperatures(self): - timeout = 0.2 # Default timeout is too short - try: - modem = self.get_modem() - temps = modem.Command("AT+QTEMP", math.ceil(timeout), dbus_interface=MM_MODEM, timeout=timeout) - return list(filter(lambda t: t != 255, map(int, temps.split(' ')[1].split(',')))) - except Exception: - return [] - - def get_nvme_temperatures(self): - ret = [] - try: - out = subprocess.check_output("sudo smartctl -aj /dev/nvme0", shell=True) - dat = json.loads(out) - ret = list(map(int, dat["nvme_smart_health_information_log"]["temperature_sensors"])) - except Exception: - pass - return ret - - def get_current_power_draw(self): - return (self.read_param_file("/sys/class/hwmon/hwmon1/power1_input", int) / 1e6) - - def get_som_power_draw(self): - return (self.read_param_file("/sys/class/power_supply/bms/voltage_now", int) * self.read_param_file("/sys/class/power_supply/bms/current_now", int) / 1e12) - - def shutdown(self): - os.system("sudo poweroff") - - def get_thermal_config(self): - intake, exhaust, case = None, None, None - if self.get_device_type() == "mici": - case = ThermalZone("case") - intake = ThermalZone("intake") - exhaust = ThermalZone("exhaust") - return ThermalConfig(cpu=[ThermalZone(f"cpu{i}-silver-usr") for i in range(4)] + - [ThermalZone(f"cpu{i}-gold-usr") for i in range(4)], - gpu=[ThermalZone("gpu0-usr"), ThermalZone("gpu1-usr")], - dsp=ThermalZone("compute-hvx-usr"), - memory=ThermalZone("ddr-usr"), - pmic=[ThermalZone("pm8998_tz"), ThermalZone("pm8005_tz")], - intake=intake, - exhaust=exhaust, - case=case) - - def set_display_power(self, on): - try: - with open("/sys/class/backlight/panel0-backlight/bl_power", "w") as f: - f.write("0" if on else "4") - except Exception: - pass - - def set_screen_brightness(self, percentage): - try: - with open("/sys/class/backlight/panel0-backlight/max_brightness") as f: - max_brightness = float(f.read().strip()) - - val = int(percentage * (max_brightness / 100.)) - with open("/sys/class/backlight/panel0-backlight/brightness", "w") as f: - f.write(str(val)) - except Exception: - pass - - def get_screen_brightness(self): - try: - with open("/sys/class/backlight/panel0-backlight/max_brightness") as f: - max_brightness = float(f.read().strip()) - - with open("/sys/class/backlight/panel0-backlight/brightness") as f: - return int(float(f.read()) / (max_brightness / 100.)) - except Exception: - return 0 - - def set_power_save(self, powersave_enabled): - # amplifier, 100mW at idle - if self.amplifier is not None: - self.amplifier.set_global_shutdown(amp_disabled=powersave_enabled) - if not powersave_enabled: - self.amplifier.initialize_configuration(self.get_device_type()) - - # *** CPU config *** - - # offline big cluster - for i in range(4, 8): - val = '0' if powersave_enabled else '1' - sudo_write(val, f'/sys/devices/system/cpu/cpu{i}/online') - - for n in ('0', '4'): - if powersave_enabled and n == '4': - continue - gov = 'ondemand' if powersave_enabled else 'performance' - sudo_write(gov, f'/sys/devices/system/cpu/cpufreq/policy{n}/scaling_governor') - - # *** IRQ config *** - - # GPU, modeld core - affine_irq(7, "kgsl-3d0") - - # camerad core - camera_irqs = ("a5", "cci", "cpas_camnoc", "cpas-cdm", "csid", "ife", "csid-lite", "ife-lite") - for n in camera_irqs: - affine_irq(6, n) - - def get_gpu_usage_percent(self): - try: - with open('/sys/class/kgsl/kgsl-3d0/gpubusy') as f: - used, total = f.read().strip().split() - return 100.0 * int(used) / int(total) - except Exception: - return 0 - - def initialize_hardware(self): - if self.amplifier is not None: - self.amplifier.initialize_configuration(self.get_device_type()) - - # Allow hardwared to write engagement status to kmsg - os.system("sudo chmod a+w /dev/kmsg") - - # Ensure fan gpio is enabled so fan runs until shutdown, also turned on at boot by the ABL - gpio_init(GPIO.SOM_ST_IO, True) - gpio_set(GPIO.SOM_ST_IO, 1) - - # *** IRQ config *** - - # mask off big cluster from default affinity - sudo_write("f", "/proc/irq/default_smp_affinity") - - # move these off the default core - affine_irq(1, "msm_drm") # display - affine_irq(1, "msm_vidc") # encoders - affine_irq(1, "i2c_geni") # sensors - - # *** GPU config *** - # https://github.com/commaai/agnos-kernel-sdm845/blob/master/arch/arm64/boot/dts/qcom/sdm845-gpu.dtsi#L216 - sudo_write("0", "/sys/class/kgsl/kgsl-3d0/min_pwrlevel") - sudo_write("0", "/sys/class/kgsl/kgsl-3d0/max_pwrlevel") - sudo_write("1", "/sys/class/kgsl/kgsl-3d0/force_bus_on") - sudo_write("1", "/sys/class/kgsl/kgsl-3d0/force_clk_on") - sudo_write("1", "/sys/class/kgsl/kgsl-3d0/force_rail_on") - sudo_write("1000", "/sys/class/kgsl/kgsl-3d0/idle_timer") - sudo_write("performance", "/sys/class/kgsl/kgsl-3d0/devfreq/governor") - sudo_write("710", "/sys/class/kgsl/kgsl-3d0/max_clock_mhz") - - # setup governors - sudo_write("performance", "/sys/class/devfreq/soc:qcom,cpubw/governor") - sudo_write("performance", "/sys/class/devfreq/soc:qcom,memlat-cpu0/governor") - sudo_write("performance", "/sys/class/devfreq/soc:qcom,memlat-cpu4/governor") - - # *** VIDC (encoder) config *** - sudo_write("N", "/sys/kernel/debug/msm_vidc/clock_scaling") - sudo_write("Y", "/sys/kernel/debug/msm_vidc/disable_thermal_mitigation") - - # pandad core - affine_irq(3, "spi_geni") # SPI - if "tici" in self.get_device_type(): - affine_irq(3, "xhci-hcd:usb3") # aux panda USB (or potentially anything else on USB) - affine_irq(3, "xhci-hcd:usb1") # internal panda USB (also modem) - try: - pid = subprocess.check_output(["pgrep", "-f", "spi0"], encoding='utf8').strip() - subprocess.call(["sudo", "chrt", "-f", "-p", "1", pid]) - subprocess.call(["sudo", "taskset", "-pc", "3", pid]) - except subprocess.CalledProcessException as e: - print(str(e)) - - def configure_modem(self): - sim_id = self.get_sim_info().get('sim_id', '') - - modem = self.get_modem() - try: - manufacturer = str(modem.Get(MM_MODEM, 'Manufacturer', dbus_interface=DBUS_PROPS, timeout=TIMEOUT)) - except Exception: - manufacturer = None - - cmds = [] - - if self.get_device_type() in ("tici", "tizi"): - # clear out old blue prime initial APN - os.system('mmcli -m any --3gpp-set-initial-eps-bearer-settings="apn="') - - cmds += [ - # configure modem as data-centric - 'AT+QNVW=5280,0,"0102000000000000"', - 'AT+QNVFW="/nv/item_files/ims/IMS_enable",00', - 'AT+QNVFW="/nv/item_files/modem/mmode/ue_usage_setting",01', - ] - if self.get_device_type() == "tizi": - # SIM hot swap, not routed on tici - cmds += [ - 'AT+QSIMDET=1,0', - 'AT+QSIMSTAT=1', - ] - elif manufacturer == 'Cavli Inc.': - cmds += [ - 'AT^SIMSWAP=1', # use SIM slot, instead of internal eSIM - 'AT$QCSIMSLEEP=0', # disable SIM sleep - 'AT$QCSIMCFG=SimPowerSave,0', # more sleep disable - - # ethernet config - 'AT$QCPCFG=usbNet,0', - 'AT$QCNETDEVCTL=3,1', - ] - else: - # this modem gets upset with too many AT commands - if sim_id is None or len(sim_id) == 0: - cmds += [ - # SIM sleep disable - 'AT$QCSIMSLEEP=0', - 'AT$QCSIMCFG=SimPowerSave,0', - - # ethernet config - 'AT$QCPCFG=usbNet,1', - ] - - for cmd in cmds: - try: - modem.Command(cmd, math.ceil(TIMEOUT), dbus_interface=MM_MODEM, timeout=TIMEOUT) - except Exception: - pass - - # eSIM prime - dest = "/etc/NetworkManager/system-connections/esim.nmconnection" - if sim_id.startswith('8985235') and not os.path.exists(dest): - with open(Path(__file__).parent/'esim.nmconnection') as f, tempfile.NamedTemporaryFile(mode='w') as tf: - dat = f.read() - dat = dat.replace("sim-id=", f"sim-id={sim_id}") - tf.write(dat) - tf.flush() - - # needs to be root - os.system(f"sudo cp {tf.name} {dest}") - os.system(f"sudo nmcli con load {dest}") - - def get_networks(self): - r = {} - - wlan = iwlist.scan() - if wlan is not None: - r['wlan'] = wlan - - lte_info = self.get_network_info() - if lte_info is not None: - extra = lte_info['extra'] - - # ,"LTE",,,,,,,, - # ,,,,,,, - if 'LTE' in extra: - extra = extra.split(',') - try: - r['lte'] = [{ - "mcc": int(extra[3]), - "mnc": int(extra[4]), - "cid": int(extra[5], 16), - "nmr": [{"pci": int(extra[6]), "earfcn": int(extra[7])}], - }] - except (ValueError, IndexError): - pass - - return r - - def get_modem_data_usage(self): - try: - wwan = self.get_wwan() - - # Ensure refresh rate is set so values don't go stale - refresh_rate = wwan.Get(NM_DEV_STATS, 'RefreshRateMs', dbus_interface=DBUS_PROPS, timeout=TIMEOUT) - if refresh_rate != REFRESH_RATE_MS: - u = type(refresh_rate) - wwan.Set(NM_DEV_STATS, 'RefreshRateMs', u(REFRESH_RATE_MS), dbus_interface=DBUS_PROPS, timeout=TIMEOUT) - - tx = wwan.Get(NM_DEV_STATS, 'TxBytes', dbus_interface=DBUS_PROPS, timeout=TIMEOUT) - rx = wwan.Get(NM_DEV_STATS, 'RxBytes', dbus_interface=DBUS_PROPS, timeout=TIMEOUT) - return int(tx), int(rx) - except Exception: - return -1, -1 - - def has_internal_panda(self): - return True - - def reset_internal_panda(self): - gpio_init(GPIO.STM_RST_N, True) - gpio_init(GPIO.STM_BOOT0, True) - - gpio_set(GPIO.STM_RST_N, 1) - gpio_set(GPIO.STM_BOOT0, 0) - time.sleep(1) - gpio_set(GPIO.STM_RST_N, 0) - - def recover_internal_panda(self): - gpio_init(GPIO.STM_RST_N, True) - gpio_init(GPIO.STM_BOOT0, True) - - gpio_set(GPIO.STM_RST_N, 1) - gpio_set(GPIO.STM_BOOT0, 1) - time.sleep(0.5) - gpio_set(GPIO.STM_RST_N, 0) - time.sleep(0.5) - gpio_set(GPIO.STM_BOOT0, 0) - - def booted(self): - # this normally boots within 8s, but on rare occasions takes 30+s - encoder_state = sudo_read("/sys/kernel/debug/msm_vidc/core0/info") - if "Core state: 0" in encoder_state and (time.monotonic() < 60*2): - return False - return True - -if __name__ == "__main__": - t = Tici() - t.configure_modem() - t.initialize_hardware() - t.set_power_save(False) - print(t.get_sim_info()) diff --git a/system/hardware/tici/iwlist.py b/system/hardware/tici/iwlist.py deleted file mode 100644 index 1e7c428b40..0000000000 --- a/system/hardware/tici/iwlist.py +++ /dev/null @@ -1,35 +0,0 @@ -import subprocess - - -def scan(interface="wlan0"): - result = [] - try: - r = subprocess.check_output(["iwlist", interface, "scan"], encoding='utf8') - - mac = None - for line in r.split('\n'): - if "Address" in line: - # Based on the adapter eithere a percentage or dBm is returned - # Add previous network in case no dBm signal level was seen - if mac is not None: - result.append({"mac": mac}) - mac = None - - mac = line.split(' ')[-1] - elif "dBm" in line: - try: - level = line.split('Signal level=')[1] - rss = int(level.split(' ')[0]) - result.append({"mac": mac, "rss": rss}) - mac = None - except ValueError: - continue - - # Add last network if no dBm was found - if mac is not None: - result.append({"mac": mac}) - - return result - - except Exception: - return None diff --git a/system/hardware/tici/precise_power_measure.py b/system/hardware/tici/precise_power_measure.py deleted file mode 100755 index 52fe0850ab..0000000000 --- a/system/hardware/tici/precise_power_measure.py +++ /dev/null @@ -1,9 +0,0 @@ -#!/usr/bin/env python3 -import numpy as np -from openpilot.system.hardware.tici.power_monitor import sample_power - -if __name__ == '__main__': - print("measuring for 5 seconds") - for _ in range(3): - pwrs = sample_power() - print(f"mean {np.mean(pwrs):.2f} std {np.std(pwrs):.2f}") diff --git a/system/hardware/tici/restart_modem.sh b/system/hardware/tici/restart_modem.sh deleted file mode 100755 index 741dc72050..0000000000 --- a/system/hardware/tici/restart_modem.sh +++ /dev/null @@ -1,18 +0,0 @@ -#!/usr/bin/env bash - -#nmcli connection modify --temporary lte gsm.home-only yes -#nmcli connection modify --temporary lte gsm.auto-config yes -#nmcli connection modify --temporary lte connection.autoconnect-retries 20 -sudo nmcli connection reload - -sudo systemctl stop ModemManager -nmcli con down lte -nmcli con down blue-prime - -# power cycle modem -/usr/comma/lte/lte.sh stop_blocking -/usr/comma/lte/lte.sh start - -sudo systemctl restart NetworkManager -#sudo systemctl restart ModemManager -sudo ModemManager --debug diff --git a/system/hardware/tici/tests/compare_casync_manifest.py b/system/hardware/tici/tests/compare_casync_manifest.py deleted file mode 100755 index 7de66d91d0..0000000000 --- a/system/hardware/tici/tests/compare_casync_manifest.py +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/env python3 -import argparse -import collections -import multiprocessing -import os - -import requests -from tqdm import tqdm - -import openpilot.system.hardware.tici.casync as casync - - -def get_chunk_download_size(chunk): - sha = chunk.sha.hex() - path = os.path.join(remote_url, sha[:4], sha + ".cacnk") - if os.path.isfile(path): - return os.path.getsize(path) - else: - r = requests.head(path, timeout=10) - r.raise_for_status() - return int(r.headers['content-length']) - - -if __name__ == "__main__": - - parser = argparse.ArgumentParser(description='Compute overlap between two casync manifests') - parser.add_argument('frm') - parser.add_argument('to') - args = parser.parse_args() - - frm = casync.parse_caibx(args.frm) - to = casync.parse_caibx(args.to) - remote_url = args.to.replace('.caibx', '') - - most_common = collections.Counter(t.sha for t in to).most_common(1)[0][0] - - frm_dict = casync.build_chunk_dict(frm) - - # Get content-length for each chunk - with multiprocessing.Pool() as pool: - szs = list(tqdm(pool.imap(get_chunk_download_size, to), total=len(to))) - chunk_sizes = {t.sha: sz for (t, sz) in zip(to, szs, strict=True)} - - sources: dict[str, list[int]] = { - 'seed': [], - 'remote_uncompressed': [], - 'remote_compressed': [], - } - - for chunk in to: - # Assume most common chunk is the zero chunk - if chunk.sha == most_common: - continue - - if chunk.sha in frm_dict: - sources['seed'].append(chunk.length) - else: - sources['remote_uncompressed'].append(chunk.length) - sources['remote_compressed'].append(chunk_sizes[chunk.sha]) - - print() - print("Update statistics (excluding zeros)") - print() - print("Download only with no seed:") - print(f" Remote (uncompressed)\t\t{sum(sources['seed'] + sources['remote_uncompressed']) / 1000 / 1000:.2f} MB\tn = {len(to)}") - print(f" Remote (compressed download)\t{sum(chunk_sizes.values()) / 1000 / 1000:.2f} MB\tn = {len(to)}") - print() - print("Upgrade with seed partition:") - print(f" Seed (uncompressed)\t\t{sum(sources['seed']) / 1000 / 1000:.2f} MB\t\t\t\tn = {len(sources['seed'])}") - sz, n = sum(sources['remote_uncompressed']), len(sources['remote_uncompressed']) - print(f" Remote (uncompressed)\t\t{sz / 1000 / 1000:.2f} MB\t(avg {sz / 1000 / 1000 / n:4f} MB)\tn = {n}") - sz, n = sum(sources['remote_compressed']), len(sources['remote_compressed']) - print(f" Remote (compressed download)\t{sz / 1000 / 1000:.2f} MB\t(avg {sz / 1000 / 1000 / n:4f} MB)\tn = {n}") diff --git a/system/hardware/tici/tests/test_esim.py b/system/hardware/tici/tests/test_esim.py deleted file mode 100644 index 6fab931cce..0000000000 --- a/system/hardware/tici/tests/test_esim.py +++ /dev/null @@ -1,51 +0,0 @@ -import pytest - -from openpilot.system.hardware import HARDWARE, TICI -from openpilot.system.hardware.base import LPAProfileNotFoundError - -# https://euicc-manual.osmocom.org/docs/rsp/known-test-profile -# iccid is always the same for the given activation code -TEST_ACTIVATION_CODE = 'LPA:1$rsp.truphone.com$QRF-BETTERROAMING-PMRDGIR2EARDEIT5' -TEST_ICCID = '8944476500001944011' - -TEST_NICKNAME = 'test_profile' - -def cleanup(): - lpa = HARDWARE.get_sim_lpa() - try: - lpa.delete_profile(TEST_ICCID) - except LPAProfileNotFoundError: - pass - lpa.process_notifications() - -class TestEsim: - - @classmethod - def setup_class(cls): - if not TICI: - pytest.skip() - cleanup() - - @classmethod - def teardown_class(cls): - cleanup() - - def test_provision_enable_disable(self): - lpa = HARDWARE.get_sim_lpa() - current_active = lpa.get_active_profile() - - lpa.download_profile(TEST_ACTIVATION_CODE, TEST_NICKNAME) - assert any(p.iccid == TEST_ICCID and p.nickname == TEST_NICKNAME for p in lpa.list_profiles()) - - lpa.enable_profile(TEST_ICCID) - new_active = lpa.get_active_profile() - assert new_active is not None - assert new_active.iccid == TEST_ICCID - assert new_active.nickname == TEST_NICKNAME - - lpa.disable_profile(TEST_ICCID) - new_active = lpa.get_active_profile() - assert new_active is None - - if current_active: - lpa.enable_profile(current_active.iccid) diff --git a/system/hardware/tici/updater b/system/hardware/tici/updater deleted file mode 100755 index 23cdc140f4..0000000000 --- a/system/hardware/tici/updater +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:eba5f44e6a763e1f74d1c718993218adcc72cba4caafe99b595fa701151a4c54 -size 10448792 diff --git a/system/logcatd/.gitignore b/system/logcatd/.gitignore deleted file mode 100644 index c66f7622d9..0000000000 --- a/system/logcatd/.gitignore +++ /dev/null @@ -1 +0,0 @@ -logcatd diff --git a/system/logcatd/SConscript b/system/logcatd/SConscript deleted file mode 100644 index 39c45d1093..0000000000 --- a/system/logcatd/SConscript +++ /dev/null @@ -1,3 +0,0 @@ -Import('env', 'messaging', 'common') - -env.Program('logcatd', 'logcatd_systemd.cc', LIBS=[messaging, common, 'systemd']) diff --git a/system/logcatd/logcatd_systemd.cc b/system/logcatd/logcatd_systemd.cc deleted file mode 100644 index 54b3782132..0000000000 --- a/system/logcatd/logcatd_systemd.cc +++ /dev/null @@ -1,75 +0,0 @@ -#include - -#include -#include -#include -#include - -#include "third_party/json11/json11.hpp" - -#include "cereal/messaging/messaging.h" -#include "common/timing.h" -#include "common/util.h" - -ExitHandler do_exit; -int main(int argc, char *argv[]) { - - PubMaster pm({"androidLog"}); - - sd_journal *journal; - int err = sd_journal_open(&journal, 0); - assert(err >= 0); - err = sd_journal_get_fd(journal); // needed so sd_journal_wait() works properly if files rotate - assert(err >= 0); - err = sd_journal_seek_tail(journal); - assert(err >= 0); - - // workaround for bug https://github.com/systemd/systemd/issues/9934 - // call sd_journal_previous_skip after sd_journal_seek_tail (like journalctl -f does) to makes things work. - sd_journal_previous_skip(journal, 1); - - while (!do_exit) { - err = sd_journal_next(journal); - assert(err >= 0); - - // Wait for new message if we didn't receive anything - if (err == 0) { - err = sd_journal_wait(journal, 1000 * 1000); - assert(err >= 0); - continue; // Try again - } - - uint64_t timestamp = 0; - err = sd_journal_get_realtime_usec(journal, ×tamp); - assert(err >= 0); - - const void *data; - size_t length; - std::map kv; - - SD_JOURNAL_FOREACH_DATA(journal, data, length) { - std::string str((char*)data, length); - - // Split "KEY=VALUE"" on "=" and put in map - std::size_t found = str.find("="); - if (found != std::string::npos) { - kv[str.substr(0, found)] = str.substr(found + 1, std::string::npos); - } - } - - MessageBuilder msg; - - // Build message - auto androidEntry = msg.initEvent().initAndroidLog(); - androidEntry.setTs(timestamp); - androidEntry.setMessage(json11::Json(kv).dump()); - if (kv.count("_PID")) androidEntry.setPid(std::atoi(kv["_PID"].c_str())); - if (kv.count("PRIORITY")) androidEntry.setPriority(std::atoi(kv["PRIORITY"].c_str())); - if (kv.count("SYSLOG_IDENTIFIER")) androidEntry.setTag(kv["SYSLOG_IDENTIFIER"]); - - pm.send("androidLog", msg); - } - - sd_journal_close(journal); - return 0; -} diff --git a/system/loggerd/SConscript b/system/loggerd/SConscript deleted file mode 100644 index cf169f4dc6..0000000000 --- a/system/loggerd/SConscript +++ /dev/null @@ -1,26 +0,0 @@ -Import('env', 'arch', 'messaging', 'common', 'visionipc') - -libs = [common, messaging, visionipc, - 'avformat', 'avcodec', 'avutil', - 'yuv', 'OpenCL', 'pthread', 'zstd'] - -src = ['logger.cc', 'zstd_writer.cc', 'video_writer.cc', 'encoder/encoder.cc', 'encoder/v4l_encoder.cc', 'encoder/jpeg_encoder.cc'] -if arch != "larch64": - src += ['encoder/ffmpeg_encoder.cc'] - -if arch == "Darwin": - # fix OpenCL - del libs[libs.index('OpenCL')] - env['FRAMEWORKS'] = ['OpenCL'] - # exclude v4l - del src[src.index('encoder/v4l_encoder.cc')] - -logger_lib = env.Library('logger', src) -libs.insert(0, logger_lib) - -env.Program('loggerd', ['loggerd.cc'], LIBS=libs) -env.Program('encoderd', ['encoderd.cc'], LIBS=libs + ["jpeg"]) -env.Program('bootlog.cc', LIBS=libs) - -if GetOption('extras'): - env.Program('tests/test_logger', ['tests/test_runner.cc', 'tests/test_logger.cc', 'tests/test_zstd_writer.cc'], LIBS=libs + ['curl', 'crypto']) diff --git a/system/loggerd/config.py b/system/loggerd/config.py deleted file mode 100644 index e1c47c768d..0000000000 --- a/system/loggerd/config.py +++ /dev/null @@ -1,29 +0,0 @@ -import os -from openpilot.system.hardware.hw import Paths - - -CAMERA_FPS = 20 -SEGMENT_LENGTH = 60 - -STATS_DIR_FILE_LIMIT = 10000 -STATS_SOCKET = "ipc:///tmp/stats" -STATS_FLUSH_TIME_S = 60 - -def get_available_percent(default: float) -> float: - try: - statvfs = os.statvfs(Paths.log_root()) - available_percent = 100.0 * statvfs.f_bavail / statvfs.f_blocks - except OSError: - available_percent = default - - return available_percent - - -def get_available_bytes(default: int) -> int: - try: - statvfs = os.statvfs(Paths.log_root()) - available_bytes = statvfs.f_bavail * statvfs.f_frsize - except OSError: - available_bytes = default - - return available_bytes diff --git a/system/loggerd/deleter.py b/system/loggerd/deleter.py deleted file mode 100755 index eb8fd35f21..0000000000 --- a/system/loggerd/deleter.py +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/bin/env python3 -import os -import shutil -import threading -from openpilot.system.hardware.hw import Paths -from openpilot.common.swaglog import cloudlog -from openpilot.system.loggerd.config import get_available_bytes, get_available_percent -from openpilot.system.loggerd.uploader import listdir_by_creation -from openpilot.system.loggerd.xattr_cache import getxattr - -MIN_BYTES = 5 * 1024 * 1024 * 1024 -MIN_PERCENT = 10 - -DELETE_LAST = ['boot', 'crash'] - -PRESERVE_ATTR_NAME = 'user.preserve' -PRESERVE_ATTR_VALUE = b'1' -PRESERVE_COUNT = 5 - - -def has_preserve_xattr(d: str) -> bool: - return getxattr(os.path.join(Paths.log_root(), d), PRESERVE_ATTR_NAME) == PRESERVE_ATTR_VALUE - - -def get_preserved_segments(dirs_by_creation: list[str]) -> set[str]: - # skip deleting most recent N preserved segments (and their prior segment) - preserved = set() - for n, d in enumerate(filter(has_preserve_xattr, reversed(dirs_by_creation))): - if n == PRESERVE_COUNT: - break - date_str, _, seg_str = d.rpartition("--") - - # ignore non-segment directories - if not date_str: - continue - try: - seg_num = int(seg_str) - except ValueError: - continue - - # preserve segment and two prior - for _seg_num in range(max(0, seg_num - 2), seg_num + 1): - preserved.add(f"{date_str}--{_seg_num}") - - return preserved - - -def deleter_thread(exit_event: threading.Event): - while not exit_event.is_set(): - out_of_bytes = get_available_bytes(default=MIN_BYTES + 1) < MIN_BYTES - out_of_percent = get_available_percent(default=MIN_PERCENT + 1) < MIN_PERCENT - - if out_of_percent or out_of_bytes: - dirs = listdir_by_creation(Paths.log_root()) - preserved_dirs = get_preserved_segments(dirs) - - # remove the earliest directory we can - for delete_dir in sorted(dirs, key=lambda d: (d in DELETE_LAST, d in preserved_dirs)): - delete_path = os.path.join(Paths.log_root(), delete_dir) - - if any(name.endswith(".lock") for name in os.listdir(delete_path)): - continue - - try: - cloudlog.info(f"deleting {delete_path}") - shutil.rmtree(delete_path) - break - except OSError: - cloudlog.exception(f"issue deleting {delete_path}") - exit_event.wait(.1) - else: - exit_event.wait(30) - - -def main(): - deleter_thread(threading.Event()) - - -if __name__ == "__main__": - main() diff --git a/system/loggerd/encoder/jpeg_encoder.cc b/system/loggerd/encoder/jpeg_encoder.cc deleted file mode 100644 index 6bb946157c..0000000000 --- a/system/loggerd/encoder/jpeg_encoder.cc +++ /dev/null @@ -1,105 +0,0 @@ -#include "system/loggerd/encoder/jpeg_encoder.h" - -#include -#include - -JpegEncoder::JpegEncoder(const std::string &pusblish_name, int width, int height) - : publish_name(pusblish_name), thumbnail_width(width), thumbnail_height(height) { - yuv_buffer.resize((thumbnail_width * ((thumbnail_height + 15) & ~15) * 3) / 2); - pm = std::make_unique(std::vector{pusblish_name.c_str()}); -} - -JpegEncoder::~JpegEncoder() { - if (out_buffer) { - free(out_buffer); - } -} - -void JpegEncoder::pushThumbnail(VisionBuf *buf, const VisionIpcBufExtra &extra) { - generateThumbnail(buf->y, buf->uv, buf->width, buf->height, buf->stride); - - MessageBuilder msg; - auto thumbnaild = msg.initEvent().initThumbnail(); - thumbnaild.setFrameId(extra.frame_id); - thumbnaild.setTimestampEof(extra.timestamp_eof); - thumbnaild.setThumbnail({out_buffer, out_size}); - - pm->send(publish_name.c_str(), msg); -} - -void JpegEncoder::generateThumbnail(const uint8_t *y_addr, const uint8_t *uv_addr, int width, int height, int stride) { - int downscale = width / thumbnail_width; - assert(downscale * thumbnail_height == height); - - // make the buffer big enough. jpeg_write_raw_data requires 16-pixels aligned height to be used. - uint8_t *y_plane = yuv_buffer.data(); - uint8_t *u_plane = y_plane + thumbnail_width * thumbnail_height; - uint8_t *v_plane = u_plane + (thumbnail_width * thumbnail_height) / 4; - { - // subsampled conversion from nv12 to yuv - for (int hy = 0; hy < thumbnail_height / 2; hy++) { - for (int hx = 0; hx < thumbnail_width / 2; hx++) { - int ix = hx * downscale + (downscale - 1) / 2; - int iy = hy * downscale + (downscale - 1) / 2; - y_plane[(hy * 2 + 0) * thumbnail_width + (hx * 2 + 0)] = y_addr[(iy * 2 + 0) * stride + ix * 2 + 0]; - y_plane[(hy * 2 + 0) * thumbnail_width + (hx * 2 + 1)] = y_addr[(iy * 2 + 0) * stride + ix * 2 + 1]; - y_plane[(hy * 2 + 1) * thumbnail_width + (hx * 2 + 0)] = y_addr[(iy * 2 + 1) * stride + ix * 2 + 0]; - y_plane[(hy * 2 + 1) * thumbnail_width + (hx * 2 + 1)] = y_addr[(iy * 2 + 1) * stride + ix * 2 + 1]; - u_plane[hy * thumbnail_width / 2 + hx] = uv_addr[iy * stride + ix * 2 + 0]; - v_plane[hy * thumbnail_width / 2 + hx] = uv_addr[iy * stride + ix * 2 + 1]; - } - } - } - - compressToJpeg(y_plane, u_plane, v_plane); -} - -void JpegEncoder::compressToJpeg(uint8_t *y_plane, uint8_t *u_plane, uint8_t *v_plane) { - struct jpeg_compress_struct cinfo; - struct jpeg_error_mgr jerr; - cinfo.err = jpeg_std_error(&jerr); - jpeg_create_compress(&cinfo); - - if (out_buffer) { - free(out_buffer); - out_buffer = nullptr; - out_size = 0; - } - jpeg_mem_dest(&cinfo, &out_buffer, &out_size); - - cinfo.image_width = thumbnail_width; - cinfo.image_height = thumbnail_height; - cinfo.input_components = 3; - - jpeg_set_defaults(&cinfo); - jpeg_set_colorspace(&cinfo, JCS_YCbCr); - // configure sampling factors for yuv420. - cinfo.comp_info[0].h_samp_factor = 2; // Y - cinfo.comp_info[0].v_samp_factor = 2; - cinfo.comp_info[1].h_samp_factor = 1; // U - cinfo.comp_info[1].v_samp_factor = 1; - cinfo.comp_info[2].h_samp_factor = 1; // V - cinfo.comp_info[2].v_samp_factor = 1; - cinfo.raw_data_in = TRUE; - - jpeg_set_quality(&cinfo, 50, TRUE); - jpeg_start_compress(&cinfo, TRUE); - - JSAMPROW y[16], u[8], v[8]; - JSAMPARRAY planes[3]{y, u, v}; - - for (int line = 0; line < cinfo.image_height; line += 16) { - for (int i = 0; i < 16; ++i) { - y[i] = y_plane + (line + i) * cinfo.image_width; - if (i % 2 == 0) { - int offset = (cinfo.image_width / 2) * ((i + line) / 2); - u[i / 2] = u_plane + offset; - v[i / 2] = v_plane + offset; - } - } - jpeg_write_raw_data(&cinfo, planes, 16); - } - - jpeg_finish_compress(&cinfo); - jpeg_destroy_compress(&cinfo); -} diff --git a/system/loggerd/encoder/jpeg_encoder.h b/system/loggerd/encoder/jpeg_encoder.h deleted file mode 100644 index af1427c19a..0000000000 --- a/system/loggerd/encoder/jpeg_encoder.h +++ /dev/null @@ -1,32 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include "cereal/messaging/messaging.h" -#include "msgq/visionipc/visionbuf.h" - -class JpegEncoder { -public: - JpegEncoder(const std::string &pusblish_name, int width, int height); - ~JpegEncoder(); - void pushThumbnail(VisionBuf *buf, const VisionIpcBufExtra &extra); - -private: - void generateThumbnail(const uint8_t *y, const uint8_t *uv, int width, int height, int stride); - void compressToJpeg(uint8_t *y_plane, uint8_t *u_plane, uint8_t *v_plane); - - int thumbnail_width; - int thumbnail_height; - std::string publish_name; - std::vector yuv_buffer; - std::unique_ptr pm; - - // JPEG output buffer - unsigned char* out_buffer = nullptr; - unsigned long out_size = 0; -}; diff --git a/system/loggerd/loggerd.h b/system/loggerd/loggerd.h deleted file mode 100644 index 27d2d37fc4..0000000000 --- a/system/loggerd/loggerd.h +++ /dev/null @@ -1,149 +0,0 @@ -#pragma once - -#include - -#include "cereal/messaging/messaging.h" -#include "cereal/services.h" -#include "msgq/visionipc/visionipc_client.h" -#include "system/hardware/hw.h" -#include "common/params.h" -#include "common/swaglog.h" -#include "common/util.h" - -#include "system/loggerd/logger.h" - -constexpr int MAIN_FPS = 20; -const int MAIN_BITRATE = 1e7; -const int LIVESTREAM_BITRATE = 1e6; -const int QCAM_BITRATE = 256000; - -#define NO_CAMERA_PATIENCE 500 // fall back to time-based rotation if all cameras are dead - -#define INIT_ENCODE_FUNCTIONS(encode_type) \ - .get_encode_data_func = &cereal::Event::Reader::get##encode_type##Data, \ - .set_encode_idx_func = &cereal::Event::Builder::set##encode_type##Idx, \ - .init_encode_data_func = &cereal::Event::Builder::init##encode_type##Data - -const bool LOGGERD_TEST = getenv("LOGGERD_TEST"); -const int SEGMENT_LENGTH = LOGGERD_TEST ? atoi(getenv("LOGGERD_SEGMENT_LENGTH")) : 60; - -constexpr char PRESERVE_ATTR_NAME[] = "user.preserve"; -constexpr char PRESERVE_ATTR_VALUE = '1'; -class EncoderInfo { -public: - const char *publish_name; - const char *thumbnail_name = NULL; - const char *filename = NULL; - bool record = true; - int frame_width = -1; - int frame_height = -1; - int fps = MAIN_FPS; - int bitrate = MAIN_BITRATE; - cereal::EncodeIndex::Type encode_type = Hardware::PC() ? cereal::EncodeIndex::Type::BIG_BOX_LOSSLESS - : cereal::EncodeIndex::Type::FULL_H_E_V_C; - ::cereal::EncodeData::Reader (cereal::Event::Reader::*get_encode_data_func)() const; - void (cereal::Event::Builder::*set_encode_idx_func)(::cereal::EncodeIndex::Reader); - cereal::EncodeData::Builder (cereal::Event::Builder::*init_encode_data_func)(); -}; - -class LogCameraInfo { -public: - const char *thread_name; - int fps = MAIN_FPS; - VisionStreamType stream_type; - std::vector encoder_infos; -}; - -const EncoderInfo main_road_encoder_info = { - .publish_name = "roadEncodeData", - .thumbnail_name = "thumbnail", - .filename = "fcamera.hevc", - INIT_ENCODE_FUNCTIONS(RoadEncode), -}; - -const EncoderInfo main_wide_road_encoder_info = { - .publish_name = "wideRoadEncodeData", - .filename = "ecamera.hevc", - INIT_ENCODE_FUNCTIONS(WideRoadEncode), -}; - -const EncoderInfo main_driver_encoder_info = { - .publish_name = "driverEncodeData", - .filename = "dcamera.hevc", - .record = Params().getBool("RecordFront"), - INIT_ENCODE_FUNCTIONS(DriverEncode), -}; - -const EncoderInfo stream_road_encoder_info = { - .publish_name = "livestreamRoadEncodeData", - //.thumbnail_name = "thumbnail", - .encode_type = cereal::EncodeIndex::Type::QCAMERA_H264, - .record = false, - .bitrate = LIVESTREAM_BITRATE, - INIT_ENCODE_FUNCTIONS(LivestreamRoadEncode), -}; - -const EncoderInfo stream_wide_road_encoder_info = { - .publish_name = "livestreamWideRoadEncodeData", - .encode_type = cereal::EncodeIndex::Type::QCAMERA_H264, - .record = false, - .bitrate = LIVESTREAM_BITRATE, - INIT_ENCODE_FUNCTIONS(LivestreamWideRoadEncode), -}; - -const EncoderInfo stream_driver_encoder_info = { - .publish_name = "livestreamDriverEncodeData", - .encode_type = cereal::EncodeIndex::Type::QCAMERA_H264, - .record = false, - .bitrate = LIVESTREAM_BITRATE, - INIT_ENCODE_FUNCTIONS(LivestreamDriverEncode), -}; - -const EncoderInfo qcam_encoder_info = { - .publish_name = "qRoadEncodeData", - .filename = "qcamera.ts", - .bitrate = QCAM_BITRATE, - .encode_type = cereal::EncodeIndex::Type::QCAMERA_H264, - .frame_width = 526, - .frame_height = 330, - INIT_ENCODE_FUNCTIONS(QRoadEncode), -}; - -const LogCameraInfo road_camera_info{ - .thread_name = "road_cam_encoder", - .stream_type = VISION_STREAM_ROAD, - .encoder_infos = {main_road_encoder_info, qcam_encoder_info} -}; - -const LogCameraInfo wide_road_camera_info{ - .thread_name = "wide_road_cam_encoder", - .stream_type = VISION_STREAM_WIDE_ROAD, - .encoder_infos = {main_wide_road_encoder_info} -}; - -const LogCameraInfo driver_camera_info{ - .thread_name = "driver_cam_encoder", - .stream_type = VISION_STREAM_DRIVER, - .encoder_infos = {main_driver_encoder_info} -}; - -const LogCameraInfo stream_road_camera_info{ - .thread_name = "road_cam_encoder", - .stream_type = VISION_STREAM_ROAD, - .encoder_infos = {stream_road_encoder_info} -}; - -const LogCameraInfo stream_wide_road_camera_info{ - .thread_name = "wide_road_cam_encoder", - .stream_type = VISION_STREAM_WIDE_ROAD, - .encoder_infos = {stream_wide_road_encoder_info} -}; - -const LogCameraInfo stream_driver_camera_info{ - .thread_name = "driver_cam_encoder", - .stream_type = VISION_STREAM_DRIVER, - .encoder_infos = {stream_driver_encoder_info} -}; - -const LogCameraInfo cameras_logged[] = {road_camera_info, wide_road_camera_info, driver_camera_info}; -const LogCameraInfo stream_cameras_logged[] = {stream_road_camera_info, stream_wide_road_camera_info, stream_driver_camera_info}; diff --git a/system/loggerd/tests/test_loggerd.py b/system/loggerd/tests/test_loggerd.py deleted file mode 100644 index 179e237a65..0000000000 --- a/system/loggerd/tests/test_loggerd.py +++ /dev/null @@ -1,283 +0,0 @@ -import numpy as np -import os -import re -import random -import string -import subprocess -import time -from collections import defaultdict -from pathlib import Path -import pytest - -import cereal.messaging as messaging -from cereal import log -from cereal.services import SERVICE_LIST -from openpilot.common.basedir import BASEDIR -from openpilot.common.params import Params -from openpilot.common.timeout import Timeout -from openpilot.system.hardware.hw import Paths -from openpilot.system.loggerd.xattr_cache import getxattr -from openpilot.system.loggerd.deleter import PRESERVE_ATTR_NAME, PRESERVE_ATTR_VALUE -from openpilot.system.manager.process_config import managed_processes -from openpilot.system.version import get_version -from openpilot.tools.lib.helpers import RE -from openpilot.tools.lib.logreader import LogReader -from msgq.visionipc import VisionIpcServer, VisionStreamType -from openpilot.common.transformations.camera import DEVICE_CAMERAS - -SentinelType = log.Sentinel.SentinelType - -CEREAL_SERVICES = [f for f in log.Event.schema.union_fields if f in SERVICE_LIST - and SERVICE_LIST[f].should_log and "encode" not in f.lower()] - - -class TestLoggerd: - def _get_latest_log_dir(self): - log_dirs = sorted(Path(Paths.log_root()).iterdir(), key=lambda f: f.stat().st_mtime) - return log_dirs[-1] - - def _get_log_dir(self, x): - for l in x.splitlines(): - for p in l.split(' '): - path = Path(p.strip()) - if path.is_dir(): - return path - return None - - def _get_log_fn(self, x): - for l in x.splitlines(): - for p in l.split(' '): - path = Path(p.strip()) - if path.is_file(): - return path - return None - - def _gen_bootlog(self): - with Timeout(5): - out = subprocess.check_output("./bootlog", cwd=os.path.join(BASEDIR, "system/loggerd"), encoding='utf-8') - - log_fn = self._get_log_fn(out) - - # check existence - assert log_fn is not None - - return log_fn - - def _check_init_data(self, msgs): - msg = msgs[0] - assert msg.which() == 'initData' - - def _check_sentinel(self, msgs, route): - start_type = SentinelType.startOfRoute if route else SentinelType.startOfSegment - assert msgs[1].sentinel.type == start_type - - end_type = SentinelType.endOfRoute if route else SentinelType.endOfSegment - assert msgs[-1].sentinel.type == end_type - - def _publish_random_messages(self, services: list[str]) -> dict[str, list]: - pm = messaging.PubMaster(services) - - managed_processes["loggerd"].start() - for s in services: - assert pm.wait_for_readers_to_update(s, timeout=5) - - sent_msgs = defaultdict(list) - for _ in range(random.randint(2, 10) * 100): - for s in services: - try: - m = messaging.new_message(s) - except Exception: - m = messaging.new_message(s, random.randint(2, 10)) - pm.send(s, m) - sent_msgs[s].append(m) - - for s in services: - assert pm.wait_for_readers_to_update(s, timeout=5) - managed_processes["loggerd"].stop() - - return sent_msgs - - def test_init_data_values(self): - os.environ["CLEAN"] = random.choice(["0", "1"]) - - dongle = ''.join(random.choice(string.printable) for n in range(random.randint(1, 100))) - fake_params = [ - # param, initData field, value - ("DongleId", "dongleId", dongle), - ("GitCommit", "gitCommit", "commit"), - ("GitCommitDate", "gitCommitDate", "date"), - ("GitBranch", "gitBranch", "branch"), - ("GitRemote", "gitRemote", "remote"), - ] - params = Params() - for k, _, v in fake_params: - params.put(k, v) - params.put("AccessToken", "abc") - - lr = list(LogReader(str(self._gen_bootlog()))) - initData = lr[0].initData - - assert initData.dirty != bool(os.environ["CLEAN"]) - assert initData.version == get_version() - - if os.path.isfile("/proc/cmdline"): - with open("/proc/cmdline") as f: - assert list(initData.kernelArgs) == f.read().strip().split(" ") - - with open("/proc/version") as f: - assert initData.kernelVersion == f.read() - - # check params - logged_params = {entry.key: entry.value for entry in initData.params.entries} - expected_params = {k for k, _, __ in fake_params} | {'AccessToken', 'BootCount'} - assert set(logged_params.keys()) == expected_params, set(logged_params.keys()) ^ expected_params - assert logged_params['AccessToken'] == b'', f"DONT_LOG param value was logged: {repr(logged_params['AccessToken'])}" - for param_key, initData_key, v in fake_params: - assert getattr(initData, initData_key) == v - assert logged_params[param_key].decode() == v - - @pytest.mark.skip("FIXME: encoderd sometimes crashes in CI when running with pytest-xdist") - def test_rotation(self): - os.environ["LOGGERD_TEST"] = "1" - Params().put("RecordFront", "1") - - d = DEVICE_CAMERAS[("tici", "ar0231")] - expected_files = {"rlog.zst", "qlog.zst", "qcamera.ts", "fcamera.hevc", "dcamera.hevc", "ecamera.hevc"} - streams = [(VisionStreamType.VISION_STREAM_ROAD, (d.fcam.width, d.fcam.height, 2048*2346, 2048, 2048*1216), "roadCameraState"), - (VisionStreamType.VISION_STREAM_DRIVER, (d.dcam.width, d.dcam.height, 2048*2346, 2048, 2048*1216), "driverCameraState"), - (VisionStreamType.VISION_STREAM_WIDE_ROAD, (d.ecam.width, d.ecam.height, 2048*2346, 2048, 2048*1216), "wideRoadCameraState")] - - pm = messaging.PubMaster(["roadCameraState", "driverCameraState", "wideRoadCameraState"]) - vipc_server = VisionIpcServer("camerad") - for stream_type, frame_spec, _ in streams: - vipc_server.create_buffers_with_sizes(stream_type, 40, *(frame_spec)) - vipc_server.start_listener() - - num_segs = random.randint(2, 5) - length = random.randint(1, 3) - os.environ["LOGGERD_SEGMENT_LENGTH"] = str(length) - managed_processes["loggerd"].start() - managed_processes["encoderd"].start() - assert pm.wait_for_readers_to_update("roadCameraState", timeout=5) - - fps = 20.0 - for n in range(1, int(num_segs*length*fps)+1): - for stream_type, frame_spec, state in streams: - dat = np.empty(frame_spec[2], dtype=np.uint8) - vipc_server.send(stream_type, dat[:].flatten().tobytes(), n, n/fps, n/fps) - - camera_state = messaging.new_message(state) - frame = getattr(camera_state, state) - frame.frameId = n - pm.send(state, camera_state) - - for _, _, state in streams: - assert pm.wait_for_readers_to_update(state, timeout=5, dt=0.001) - - managed_processes["loggerd"].stop() - managed_processes["encoderd"].stop() - - route_path = str(self._get_latest_log_dir()).rsplit("--", 1)[0] - for n in range(num_segs): - p = Path(f"{route_path}--{n}") - logged = {f.name for f in p.iterdir() if f.is_file()} - diff = logged ^ expected_files - assert len(diff) == 0, f"didn't get all expected files. run={_} seg={n} {route_path=}, {diff=}\n{logged=} {expected_files=}" - - def test_bootlog(self): - # generate bootlog with fake launch log - launch_log = ''.join(str(random.choice(string.printable)) for _ in range(100)) - with open("/tmp/launch_log", "w") as f: - f.write(launch_log) - - bootlog_path = self._gen_bootlog() - lr = list(LogReader(str(bootlog_path))) - - # check length - assert len(lr) == 2 # boot + initData - - self._check_init_data(lr) - - # check msgs - bootlog_msgs = [m for m in lr if m.which() == 'boot'] - assert len(bootlog_msgs) == 1 - - # sanity check values - boot = bootlog_msgs.pop().boot - assert abs(boot.wallTimeNanos - time.time_ns()) < 5*1e9 # within 5s - assert boot.launchLog == launch_log - - for fn in ["console-ramoops", "pmsg-ramoops-0"]: - path = Path(os.path.join("/sys/fs/pstore/", fn)) - if path.is_file(): - with open(path, "rb") as f: - expected_val = f.read() - bootlog_val = [e.value for e in boot.pstore.entries if e.key == fn][0] - assert expected_val == bootlog_val - - # next one should increment by one - bl1 = re.match(RE.LOG_ID_V2, bootlog_path.name) - bl2 = re.match(RE.LOG_ID_V2, self._gen_bootlog().name) - assert bl1.group('uid') != bl2.group('uid') - assert int(bl1.group('count')) == 0 and int(bl2.group('count')) == 1 - - def test_qlog(self): - qlog_services = [s for s in CEREAL_SERVICES if SERVICE_LIST[s].decimation is not None] - no_qlog_services = [s for s in CEREAL_SERVICES if SERVICE_LIST[s].decimation is None] - - services = random.sample(qlog_services, random.randint(2, min(10, len(qlog_services)))) + \ - random.sample(no_qlog_services, random.randint(2, min(10, len(no_qlog_services)))) - sent_msgs = self._publish_random_messages(services) - - qlog_path = os.path.join(self._get_latest_log_dir(), "qlog.zst") - lr = list(LogReader(qlog_path)) - - # check initData and sentinel - self._check_init_data(lr) - self._check_sentinel(lr, True) - - recv_msgs = defaultdict(list) - for m in lr: - recv_msgs[m.which()].append(m) - - for s, msgs in sent_msgs.items(): - recv_cnt = len(recv_msgs[s]) - - if s in no_qlog_services: - # check services with no specific decimation aren't in qlog - assert recv_cnt == 0, f"got {recv_cnt} {s} msgs in qlog" - else: - # check logged message count matches decimation - expected_cnt = (len(msgs) - 1) // SERVICE_LIST[s].decimation + 1 - assert recv_cnt == expected_cnt, f"expected {expected_cnt} msgs for {s}, got {recv_cnt}" - - def test_rlog(self): - services = random.sample(CEREAL_SERVICES, random.randint(5, 10)) - sent_msgs = self._publish_random_messages(services) - - lr = list(LogReader(os.path.join(self._get_latest_log_dir(), "rlog.zst"))) - - # check initData and sentinel - self._check_init_data(lr) - self._check_sentinel(lr, True) - - # check all messages were logged and in order - lr = lr[2:-1] # slice off initData and both sentinels - for m in lr: - sent = sent_msgs[m.which()].pop(0) - sent.clear_write_flag() - assert sent.to_bytes() == m.as_builder().to_bytes() - - def test_preserving_flagged_segments(self): - services = set(random.sample(CEREAL_SERVICES, random.randint(5, 10))) | {"userFlag"} - self._publish_random_messages(services) - - segment_dir = self._get_latest_log_dir() - assert getxattr(segment_dir, PRESERVE_ATTR_NAME) == PRESERVE_ATTR_VALUE - - def test_not_preserving_unflagged_segments(self): - services = set(random.sample(CEREAL_SERVICES, random.randint(5, 10))) - {"userFlag"} - self._publish_random_messages(services) - - segment_dir = self._get_latest_log_dir() - assert getxattr(segment_dir, PRESERVE_ATTR_NAME) is None diff --git a/system/loggerd/uploader.py b/system/loggerd/uploader.py deleted file mode 100755 index 6e6df6114e..0000000000 --- a/system/loggerd/uploader.py +++ /dev/null @@ -1,273 +0,0 @@ -#!/usr/bin/env python3 -import json -import os -import random -import requests -import threading -import time -import traceback -import datetime -from collections.abc import Iterator - -from cereal import log -import cereal.messaging as messaging -from openpilot.common.api import Api -from openpilot.common.file_helpers import get_upload_stream -from openpilot.common.params import Params -from openpilot.common.realtime import set_core_affinity -from openpilot.system.hardware.hw import Paths -from openpilot.system.loggerd.xattr_cache import getxattr, setxattr -from openpilot.common.swaglog import cloudlog - -NetworkType = log.DeviceState.NetworkType -UPLOAD_ATTR_NAME = 'user.upload' -UPLOAD_ATTR_VALUE = b'1' - -MAX_UPLOAD_SIZES = { - "qlog": 25*1e6, # can't be too restrictive here since we use qlogs to find - # bugs, including ones that can cause massive log sizes - "qcam": 5*1e6, -} - -allow_sleep = bool(os.getenv("UPLOADER_SLEEP", "1")) -force_wifi = os.getenv("FORCEWIFI") is not None -fake_upload = os.getenv("FAKEUPLOAD") is not None - - -class FakeRequest: - def __init__(self): - self.headers = {"Content-Length": "0"} - - -class FakeResponse: - def __init__(self): - self.status_code = 200 - self.request = FakeRequest() - - -def get_directory_sort(d: str) -> list[str]: - # ensure old format is sorted sooner - o = ["0", ] if d.startswith("2024-") else ["1", ] - return o + [s.rjust(10, '0') for s in d.rsplit('--', 1)] - -def listdir_by_creation(d: str) -> list[str]: - if not os.path.isdir(d): - return [] - - try: - paths = [f for f in os.listdir(d) if os.path.isdir(os.path.join(d, f))] - paths = sorted(paths, key=get_directory_sort) - return paths - except OSError: - cloudlog.exception("listdir_by_creation failed") - return [] - -def clear_locks(root: str) -> None: - for logdir in os.listdir(root): - path = os.path.join(root, logdir) - try: - for fname in os.listdir(path): - if fname.endswith(".lock"): - os.unlink(os.path.join(path, fname)) - except OSError: - cloudlog.exception("clear_locks failed") - - -class Uploader: - def __init__(self, dongle_id: str, root: str): - self.dongle_id = dongle_id - self.api = Api(dongle_id) - self.root = root - - self.params = Params() - - # stats for last successfully uploaded file - self.last_filename = "" - - self.immediate_folders = ["crash/", "boot/"] - self.immediate_priority = {"qlog": 0, "qlog.zst": 0, "qcamera.ts": 1} - - def list_upload_files(self, metered: bool) -> Iterator[tuple[str, str, str]]: - r = self.params.get("AthenadRecentlyViewedRoutes", encoding="utf8") - requested_routes = [] if r is None else [route for route in r.split(",") if route] - - for logdir in listdir_by_creation(self.root): - path = os.path.join(self.root, logdir) - try: - names = os.listdir(path) - except OSError: - continue - - if any(name.endswith(".lock") for name in names): - continue - - for name in sorted(names, key=lambda n: self.immediate_priority.get(n, 1000)): - key = os.path.join(logdir, name) - fn = os.path.join(path, name) - # skip files already uploaded - try: - ctime = os.path.getctime(fn) - is_uploaded = getxattr(fn, UPLOAD_ATTR_NAME) == UPLOAD_ATTR_VALUE - except OSError: - cloudlog.event("uploader_getxattr_failed", key=key, fn=fn) - # deleter could have deleted, so skip - continue - if is_uploaded: - continue - - # limit uploading on metered connections - if metered: - dt = datetime.timedelta(hours=12) - if logdir in self.immediate_folders and (datetime.datetime.now() - datetime.datetime.fromtimestamp(ctime)) < dt: - continue - - if name == "qcamera.ts" and not any(logdir.startswith(r.split('|')[-1]) for r in requested_routes): - continue - - yield name, key, fn - - def next_file_to_upload(self, metered: bool) -> tuple[str, str, str] | None: - upload_files = list(self.list_upload_files(metered)) - - for name, key, fn in upload_files: - if any(f in fn for f in self.immediate_folders): - return name, key, fn - - for name, key, fn in upload_files: - if name in self.immediate_priority: - return name, key, fn - - return None - - def do_upload(self, key: str, fn: str): - url_resp = self.api.get("v1.4/" + self.dongle_id + "/upload_url/", timeout=10, path=key, access_token=self.api.get_token()) - if url_resp.status_code == 412: - return url_resp - - url_resp_json = json.loads(url_resp.text) - url = url_resp_json['url'] - headers = url_resp_json['headers'] - cloudlog.debug("upload_url v1.4 %s %s", url, str(headers)) - - if fake_upload: - return FakeResponse() - - stream = None - try: - compress = key.endswith('.zst') and not fn.endswith('.zst') - stream, _ = get_upload_stream(fn, compress) - response = requests.put(url, data=stream, headers=headers, timeout=10) - return response - finally: - if stream: - stream.close() - - def upload(self, name: str, key: str, fn: str, network_type: int, metered: bool) -> bool: - try: - sz = os.path.getsize(fn) - except OSError: - cloudlog.exception("upload: getsize failed") - return False - - cloudlog.event("upload_start", key=key, fn=fn, sz=sz, network_type=network_type, metered=metered) - - if sz == 0: - # tag files of 0 size as uploaded - success = True - elif name in MAX_UPLOAD_SIZES and sz > MAX_UPLOAD_SIZES[name]: - cloudlog.event("uploader_too_large", key=key, fn=fn, sz=sz) - success = True - else: - start_time = time.monotonic() - - stat = None - last_exc = None - try: - stat = self.do_upload(key, fn) - except Exception as e: - last_exc = (e, traceback.format_exc()) - - if stat is not None and stat.status_code in (200, 201, 401, 403, 412): - self.last_filename = fn - dt = time.monotonic() - start_time - if stat.status_code == 412: - cloudlog.event("upload_ignored", key=key, fn=fn, sz=sz, network_type=network_type, metered=metered) - else: - content_length = int(stat.request.headers.get("Content-Length", 0)) - speed = (content_length / 1e6) / dt - cloudlog.event("upload_success", key=key, fn=fn, sz=sz, content_length=content_length, - network_type=network_type, metered=metered, speed=speed) - success = True - else: - success = False - cloudlog.event("upload_failed", stat=stat, exc=last_exc, key=key, fn=fn, sz=sz, network_type=network_type, metered=metered) - - if success: - # tag file as uploaded - try: - setxattr(fn, UPLOAD_ATTR_NAME, UPLOAD_ATTR_VALUE) - except OSError: - cloudlog.event("uploader_setxattr_failed", exc=last_exc, key=key, fn=fn, sz=sz) - - return success - - - def step(self, network_type: int, metered: bool) -> bool | None: - d = self.next_file_to_upload(metered) - if d is None: - return None - - name, key, fn = d - - # qlogs and bootlogs need to be compressed before uploading - if key.endswith(('qlog', 'rlog')) or (key.startswith('boot/') and not key.endswith('.zst')): - key += ".zst" - - return self.upload(name, key, fn, network_type, metered) - - -def main(exit_event: threading.Event = None) -> None: - if exit_event is None: - exit_event = threading.Event() - - try: - set_core_affinity([0, 1, 2, 3]) - except Exception: - cloudlog.exception("failed to set core affinity") - - clear_locks(Paths.log_root()) - - params = Params() - dongle_id = params.get("DongleId", encoding='utf8') - - if dongle_id is None: - cloudlog.info("uploader missing dongle_id") - raise Exception("uploader can't start without dongle id") - - sm = messaging.SubMaster(['deviceState']) - uploader = Uploader(dongle_id, Paths.log_root()) - - backoff = 0.1 - while not exit_event.is_set(): - sm.update(0) - offroad = params.get_bool("IsOffroad") - network_type = sm['deviceState'].networkType if not force_wifi else NetworkType.wifi - if network_type == NetworkType.none: - if allow_sleep: - time.sleep(60 if offroad else 5) - continue - - success = uploader.step(sm['deviceState'].networkType.raw, sm['deviceState'].networkMetered) - if success is None: - backoff = 60 if offroad else 5 - elif success: - backoff = 0.1 - else: - cloudlog.info("upload backoff %r", backoff) - backoff = min(backoff*2, 120) - if allow_sleep: - time.sleep(backoff + random.uniform(0, backoff)) - - -if __name__ == "__main__": - main() diff --git a/system/loggerd/video_writer.cc b/system/loggerd/video_writer.cc deleted file mode 100644 index 90b5f1af3d..0000000000 --- a/system/loggerd/video_writer.cc +++ /dev/null @@ -1,112 +0,0 @@ -#pragma clang diagnostic ignored "-Wdeprecated-declarations" -#include - -#include "system/loggerd/video_writer.h" -#include "common/swaglog.h" -#include "common/util.h" - -VideoWriter::VideoWriter(const char *path, const char *filename, bool remuxing, int width, int height, int fps, cereal::EncodeIndex::Type codec) - : remuxing(remuxing) { - vid_path = util::string_format("%s/%s", path, filename); - lock_path = util::string_format("%s/%s.lock", path, filename); - - int lock_fd = HANDLE_EINTR(open(lock_path.c_str(), O_RDWR | O_CREAT, 0664)); - assert(lock_fd >= 0); - close(lock_fd); - - LOGD("encoder_open %s remuxing:%d", this->vid_path.c_str(), this->remuxing); - if (this->remuxing) { - bool raw = (codec == cereal::EncodeIndex::Type::BIG_BOX_LOSSLESS); - avformat_alloc_output_context2(&this->ofmt_ctx, NULL, raw ? "matroska" : NULL, this->vid_path.c_str()); - assert(this->ofmt_ctx); - - // set codec correctly. needed? - assert(codec != cereal::EncodeIndex::Type::FULL_H_E_V_C); - const AVCodec *avcodec = avcodec_find_encoder(raw ? AV_CODEC_ID_FFVHUFF : AV_CODEC_ID_H264); - assert(avcodec); - - this->codec_ctx = avcodec_alloc_context3(avcodec); - assert(this->codec_ctx); - this->codec_ctx->width = width; - this->codec_ctx->height = height; - this->codec_ctx->pix_fmt = AV_PIX_FMT_YUV420P; - this->codec_ctx->time_base = (AVRational){ 1, fps }; - - if (codec == cereal::EncodeIndex::Type::BIG_BOX_LOSSLESS) { - // without this, there's just noise - int err = avcodec_open2(this->codec_ctx, avcodec, NULL); - assert(err >= 0); - } - - this->out_stream = avformat_new_stream(this->ofmt_ctx, raw ? avcodec : NULL); - assert(this->out_stream); - - int err = avio_open(&this->ofmt_ctx->pb, this->vid_path.c_str(), AVIO_FLAG_WRITE); - assert(err >= 0); - - } else { - this->of = util::safe_fopen(this->vid_path.c_str(), "wb"); - assert(this->of); - } -} - -void VideoWriter::write(uint8_t *data, int len, long long timestamp, bool codecconfig, bool keyframe) { - if (of && data) { - size_t written = util::safe_fwrite(data, 1, len, of); - if (written != len) { - LOGE("failed to write file.errno=%d", errno); - } - } - - if (remuxing) { - if (codecconfig) { - if (len > 0) { - codec_ctx->extradata = (uint8_t*)av_mallocz(len + AV_INPUT_BUFFER_PADDING_SIZE); - codec_ctx->extradata_size = len; - memcpy(codec_ctx->extradata, data, len); - } - int err = avcodec_parameters_from_context(out_stream->codecpar, codec_ctx); - assert(err >= 0); - err = avformat_write_header(ofmt_ctx, NULL); - assert(err >= 0); - } else { - // input timestamps are in microseconds - AVRational in_timebase = {1, 1000000}; - - AVPacket pkt; - av_init_packet(&pkt); - pkt.data = data; - pkt.size = len; - - enum AVRounding rnd = static_cast(AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX); - pkt.pts = pkt.dts = av_rescale_q_rnd(timestamp, in_timebase, ofmt_ctx->streams[0]->time_base, rnd); - pkt.duration = av_rescale_q(50*1000, in_timebase, ofmt_ctx->streams[0]->time_base); - - if (keyframe) { - pkt.flags |= AV_PKT_FLAG_KEY; - } - - // TODO: can use av_write_frame for non raw? - int err = av_interleaved_write_frame(ofmt_ctx, &pkt); - if (err < 0) { LOGW("ts encoder write issue len: %d ts: %lld", len, timestamp); } - - av_packet_unref(&pkt); - } - } -} - -VideoWriter::~VideoWriter() { - if (this->remuxing) { - int err = av_write_trailer(this->ofmt_ctx); - if (err != 0) LOGE("av_write_trailer failed %d", err); - avcodec_free_context(&this->codec_ctx); - err = avio_closep(&this->ofmt_ctx->pb); - if (err != 0) LOGE("avio_closep failed %d", err); - avformat_free_context(this->ofmt_ctx); - } else { - util::safe_fflush(this->of); - fclose(this->of); - this->of = nullptr; - } - unlink(this->lock_path.c_str()); -} diff --git a/system/loggerd/video_writer.h b/system/loggerd/video_writer.h deleted file mode 100644 index 1aa758b42b..0000000000 --- a/system/loggerd/video_writer.h +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once - -#include - -extern "C" { -#include -#include -} - -#include "cereal/messaging/messaging.h" - -class VideoWriter { -public: - VideoWriter(const char *path, const char *filename, bool remuxing, int width, int height, int fps, cereal::EncodeIndex::Type codec); - void write(uint8_t *data, int len, long long timestamp, bool codecconfig, bool keyframe); - ~VideoWriter(); -private: - std::string vid_path, lock_path; - FILE *of = nullptr; - - AVCodecContext *codec_ctx; - AVFormatContext *ofmt_ctx; - AVStream *out_stream; - bool remuxing; -}; diff --git a/system/loggerd/xattr_cache.py b/system/loggerd/xattr_cache.py deleted file mode 100644 index 39bb172059..0000000000 --- a/system/loggerd/xattr_cache.py +++ /dev/null @@ -1,23 +0,0 @@ -import errno - -import xattr - -_cached_attributes: dict[tuple, bytes | None] = {} - -def getxattr(path: str, attr_name: str) -> bytes | None: - key = (path, attr_name) - if key not in _cached_attributes: - try: - response = xattr.getxattr(path, attr_name) - except OSError as e: - # ENODATA (Linux) or ENOATTR (macOS) means attribute hasn't been set - if e.errno == errno.ENODATA or (hasattr(errno, 'ENOATTR') and e.errno == errno.ENOATTR): - response = None - else: - raise - _cached_attributes[key] = response - return _cached_attributes[key] - -def setxattr(path: str, attr_name: str, attr_value: bytes) -> None: - _cached_attributes.pop((path, attr_name), None) - xattr.setxattr(path, attr_name, attr_value) diff --git a/system/manager/build.py b/system/manager/build.py deleted file mode 100755 index ae130f4b04..0000000000 --- a/system/manager/build.py +++ /dev/null @@ -1,94 +0,0 @@ -#!/usr/bin/env python3 -import os -import subprocess -from pathlib import Path - -# NOTE: Do NOT import anything here that needs be built (e.g. params) -from openpilot.common.basedir import BASEDIR -from openpilot.common.spinner import Spinner -from openpilot.common.text_window import TextWindow -from openpilot.common.swaglog import cloudlog, add_file_handler -from openpilot.system.hardware import HARDWARE, AGNOS -from openpilot.system.version import get_build_metadata - -MAX_CACHE_SIZE = 4e9 if "CI" in os.environ else 2e9 -CACHE_DIR = Path("/data/scons_cache" if AGNOS else "/tmp/scons_cache") - -TOTAL_SCONS_NODES = 3800 -MAX_BUILD_PROGRESS = 100 - -def build(spinner: Spinner, dirty: bool = False, minimal: bool = False) -> None: - env = os.environ.copy() - env['SCONS_PROGRESS'] = "1" - nproc = os.cpu_count() - if nproc is None: - nproc = 2 - - extra_args = ["--minimal"] if minimal else [] - - if AGNOS: - HARDWARE.set_power_save(False) - os.sched_setaffinity(0, range(8)) # ensure we can use the isolcpus cores - - # building with all cores can result in using too - # much memory, so retry with less parallelism - compile_output: list[bytes] = [] - for n in (nproc, nproc/2, 1): - compile_output.clear() - scons: subprocess.Popen = subprocess.Popen(["scons", f"-j{int(n)}", "--cache-populate", *extra_args], cwd=BASEDIR, env=env, stderr=subprocess.PIPE) - assert scons.stderr is not None - - # Read progress from stderr and update spinner - while scons.poll() is None: - try: - line = scons.stderr.readline() - if line is None: - continue - line = line.rstrip() - - prefix = b'progress: ' - if line.startswith(prefix): - i = int(line[len(prefix):]) - spinner.update_progress(MAX_BUILD_PROGRESS * min(1., i / TOTAL_SCONS_NODES), 100.) - elif len(line): - compile_output.append(line) - print(line.decode('utf8', 'replace')) - except Exception: - pass - - if scons.returncode == 0: - break - - if scons.returncode != 0: - # Read remaining output - if scons.stderr is not None: - compile_output += scons.stderr.read().split(b'\n') - - # Build failed log errors - error_s = b"\n".join(compile_output).decode('utf8', 'replace') - add_file_handler(cloudlog) - cloudlog.error("scons build failed\n" + error_s) - - # Show TextWindow - spinner.close() - if not os.getenv("CI"): - with TextWindow("openpilot failed to build\n \n" + error_s) as t: - t.wait_for_exit() - exit(1) - - # enforce max cache size - cache_files = [f for f in CACHE_DIR.rglob('*') if f.is_file()] - cache_files.sort(key=lambda f: f.stat().st_mtime) - cache_size = sum(f.stat().st_size for f in cache_files) - for f in cache_files: - if cache_size < MAX_CACHE_SIZE: - break - cache_size -= f.stat().st_size - f.unlink() - - -if __name__ == "__main__": - spinner = Spinner() - spinner.update_progress(0, 100) - build_metadata = get_build_metadata() - build(spinner, build_metadata.openpilot.is_dirty, minimal = AGNOS) diff --git a/system/manager/helpers.py b/system/manager/helpers.py deleted file mode 100644 index 047d0ac2d6..0000000000 --- a/system/manager/helpers.py +++ /dev/null @@ -1,67 +0,0 @@ -import errno -import fcntl -import os -import sys -import pathlib -import shutil -import signal -import subprocess -import tempfile -import threading - -from openpilot.common.basedir import BASEDIR -from openpilot.common.params import Params - -def unblock_stdout() -> None: - # get a non-blocking stdout - child_pid, child_pty = os.forkpty() - if child_pid != 0: # parent - - # child is in its own process group, manually pass kill signals - signal.signal(signal.SIGINT, lambda signum, frame: os.kill(child_pid, signal.SIGINT)) - signal.signal(signal.SIGTERM, lambda signum, frame: os.kill(child_pid, signal.SIGTERM)) - - fcntl.fcntl(sys.stdout, fcntl.F_SETFL, fcntl.fcntl(sys.stdout, fcntl.F_GETFL) | os.O_NONBLOCK) - - while True: - try: - dat = os.read(child_pty, 4096) - except OSError as e: - if e.errno == errno.EIO: - break - continue - - if not dat: - break - - try: - sys.stdout.write(dat.decode('utf8')) - except (OSError, UnicodeDecodeError): - pass - - # os.wait() returns a tuple with the pid and a 16 bit value - # whose low byte is the signal number and whose high byte is the exit status - exit_status = os.wait()[1] >> 8 - os._exit(exit_status) - - -def write_onroad_params(started, params): - params.put_bool("IsOnroad", started) - params.put_bool("IsOffroad", not started) - - -def save_bootlog(): - # copy current params - tmp = tempfile.mkdtemp() - params_dirname = pathlib.Path(Params().get_param_path()).name - params_dir = os.path.join(tmp, params_dirname) - shutil.copytree(Params().get_param_path(), params_dir, dirs_exist_ok=True) - - def fn(tmpdir): - env = os.environ.copy() - env['PARAMS_COPY_PATH'] = tmpdir - subprocess.call("./bootlog", cwd=os.path.join(BASEDIR, "system/loggerd"), env=env) - shutil.rmtree(tmpdir) - t = threading.Thread(target=fn, args=(tmp, )) - t.daemon = True - t.start() diff --git a/system/manager/manager.py b/system/manager/manager.py deleted file mode 100755 index 5fa802dcbd..0000000000 --- a/system/manager/manager.py +++ /dev/null @@ -1,269 +0,0 @@ -#!/usr/bin/env python3 -import datetime -import os -import signal -import sys -import traceback - -from cereal import log -import cereal.messaging as messaging -import openpilot.system.sentry as sentry -from openpilot.common.params import Params, ParamKeyType -from openpilot.common.text_window import TextWindow -from openpilot.system.hardware import HARDWARE -from openpilot.system.manager.helpers import unblock_stdout, write_onroad_params, save_bootlog -from openpilot.system.manager.process import ensure_running -from openpilot.system.manager.process_config import managed_processes -from openpilot.system.athena.registration import register, UNREGISTERED_DONGLE_ID -from openpilot.common.swaglog import cloudlog, add_file_handler -from openpilot.system.version import get_build_metadata, terms_version, training_version -from openpilot.system.hardware.hw import Paths - -from openpilot.sunnypilot.mapd.mapd_installer import VERSION - - -def manager_init() -> None: - save_bootlog() - - build_metadata = get_build_metadata() - - params = Params() - params.clear_all(ParamKeyType.CLEAR_ON_MANAGER_START) - params.clear_all(ParamKeyType.CLEAR_ON_ONROAD_TRANSITION) - params.clear_all(ParamKeyType.CLEAR_ON_OFFROAD_TRANSITION) - if build_metadata.release_channel: - params.clear_all(ParamKeyType.DEVELOPMENT_ONLY) - - default_params: list[tuple[str, str | bytes]] = [ - ("CompletedTrainingVersion", "0"), - ("DisengageOnAccelerator", "0"), - ("GsmMetered", "1"), - ("HasAcceptedTerms", "0"), - ("LanguageSetting", "main_en"), - ("OpenpilotEnabledToggle", "1"), - ("LongitudinalPersonality", str(log.LongitudinalPersonality.standard)), - ] - - sunnypilot_default_params: list[tuple[str, str | bytes]] = [ - ("AutoLaneChangeTimer", "0"), - ("AutoLaneChangeBsmDelay", "0"), - ("BlindSpot", "0"), - ("BlinkerMinLateralControlSpeed", "20"), # MPH or km/h - ("BlinkerPauseLateralControl", "0"), - ("CustomAccIncrementsEnabled", "0"), - ("CustomAccLongPressIncrement", "5"), - ("CustomAccShortPressIncrement", "1"), - ("DeviceBootMode", "0"), - ("DynamicExperimentalControl", "0"), - ("HyundaiLongitudinalTuning", "0"), - ("LagdToggle", "1"), - ("Mads", "1"), - ("MadsMainCruiseAllowed", "1"), - ("MadsSteeringMode", "0"), - ("MadsUnifiedEngagementMode", "1"), - ("MapdVersion", f"{VERSION}"), - ("MaxTimeOffroad", "1800"), - ("Brightness", "0"), - ("ModelManager_LastSyncTime", "0"), - ("ModelManager_ModelsCache", ""), - ("NeuralNetworkLateralControl", "0"), - ("QuietMode", "0"), - ("EnableHkgTuningAngleSmoothingFactor", "1"), - ("HkgTuningAngleMinTorqueReductionGain", "10"), - ("HkgTuningAngleActiveTorqueReductionGain", "60"), - ("HkgTuningAngleMaxTorqueReductionGain", "100"), - ("HkgTuningOverridingCycles", "17"), - ("HkgAngleLiveTuning", "0"), - ("AdasDrvEcuInterceptorEnabled", "0"), - ] - - # device boot mode - if params.get("DeviceBootMode") == b"1": # start in always offroad mode - params.put_bool("OffroadMode", True) - - if params.get_bool("RecordFrontLock"): - params.put_bool("RecordFront", True) - - # set unset params - for k, v in (default_params + sunnypilot_default_params): - if params.get(k) is None: - params.put(k, v) - - # Create folders needed for msgq - try: - os.mkdir(Paths.shm_path()) - except FileExistsError: - pass - except PermissionError: - print(f"WARNING: failed to make {Paths.shm_path()}") - - # set params - serial = HARDWARE.get_serial() - params.put("Version", build_metadata.openpilot.version) - params.put("TermsVersion", terms_version) - params.put("TrainingVersion", training_version) - params.put("GitCommit", build_metadata.openpilot.git_commit) - params.put("GitCommitDate", build_metadata.openpilot.git_commit_date) - params.put("GitBranch", build_metadata.channel) - params.put("GitRemote", build_metadata.openpilot.git_origin) - params.put_bool("IsTestedBranch", build_metadata.tested_channel) - params.put_bool("IsReleaseBranch", build_metadata.release_channel) - params.put("HardwareSerial", serial) - - # set dongle id - reg_res = register(show_spinner=True) - if reg_res: - dongle_id = reg_res - else: - raise Exception(f"Registration failed for device {serial}") - os.environ['DONGLE_ID'] = dongle_id # Needed for swaglog - os.environ['GIT_ORIGIN'] = build_metadata.openpilot.git_normalized_origin # Needed for swaglog - os.environ['GIT_BRANCH'] = build_metadata.channel # Needed for swaglog - os.environ['GIT_COMMIT'] = build_metadata.openpilot.git_commit # Needed for swaglog - - if not build_metadata.openpilot.is_dirty: - os.environ['CLEAN'] = '1' - - # init logging - sentry.init(sentry.SentryProject.SELFDRIVE) - cloudlog.bind_global(dongle_id=dongle_id, - version=build_metadata.openpilot.version, - origin=build_metadata.openpilot.git_normalized_origin, - branch=build_metadata.channel, - commit=build_metadata.openpilot.git_commit, - dirty=build_metadata.openpilot.is_dirty, - device=HARDWARE.get_device_type()) - - # preimport all processes - for p in managed_processes.values(): - p.prepare() - - -def manager_cleanup() -> None: - # send signals to kill all procs - for p in managed_processes.values(): - p.stop(block=False) - - # ensure all are killed - for p in managed_processes.values(): - p.stop(block=True) - - cloudlog.info("everything is dead") - - -def manager_thread() -> None: - cloudlog.bind(daemon="manager") - cloudlog.info("manager start") - cloudlog.info({"environ": os.environ}) - - params = Params() - - ignore: list[str] = [] - if params.get("DongleId", encoding='utf8') in (None, UNREGISTERED_DONGLE_ID): - ignore += ["manage_athenad", "uploader"] - if os.getenv("NOBOARD") is not None: - ignore.append("pandad") - ignore += [x for x in os.getenv("BLOCK", "").split(",") if len(x) > 0] - - sm = messaging.SubMaster(['deviceState', 'carParams'], poll='deviceState') - pm = messaging.PubMaster(['managerState']) - - write_onroad_params(False, params) - ensure_running(managed_processes.values(), False, params=params, CP=sm['carParams'], not_run=ignore) - - started_prev = False - - while True: - sm.update(1000) - - started = sm['deviceState'].started - - if started and not started_prev: - params.clear_all(ParamKeyType.CLEAR_ON_ONROAD_TRANSITION) - elif not started and started_prev: - params.clear_all(ParamKeyType.CLEAR_ON_OFFROAD_TRANSITION) - - # update onroad params, which drives pandad's safety setter thread - if started != started_prev: - write_onroad_params(started, params) - - started_prev = started - - ensure_running(managed_processes.values(), started, params=params, CP=sm['carParams'], not_run=ignore) - - running = ' '.join("{}{}\u001b[0m".format("\u001b[32m" if p.proc.is_alive() else "\u001b[31m", p.name) - for p in managed_processes.values() if p.proc) - print(running) - cloudlog.debug(running) - - # send managerState - msg = messaging.new_message('managerState', valid=True) - msg.managerState.processes = [p.get_process_state_msg() for p in managed_processes.values()] - pm.send('managerState', msg) - - # Exit main loop when uninstall/shutdown/reboot is needed - shutdown = False - for param in ("DoUninstall", "DoShutdown", "DoReboot"): - if params.get_bool(param): - shutdown = True - params.put("LastManagerExitReason", f"{param} {datetime.datetime.now()}") - cloudlog.warning(f"Shutting down manager - {param} set") - - if shutdown: - break - - -def main() -> None: - manager_init() - if os.getenv("PREPAREONLY") is not None: - return - - # SystemExit on sigterm - signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit(1)) - - try: - manager_thread() - except Exception: - traceback.print_exc() - sentry.capture_exception() - finally: - manager_cleanup() - - params = Params() - if params.get_bool("DoUninstall"): - cloudlog.warning("uninstalling") - HARDWARE.uninstall() - elif params.get_bool("DoReboot"): - cloudlog.warning("reboot") - HARDWARE.reboot() - elif params.get_bool("DoShutdown"): - cloudlog.warning("shutdown") - HARDWARE.shutdown() - - -if __name__ == "__main__": - unblock_stdout() - - try: - main() - except KeyboardInterrupt: - print("got CTRL-C, exiting") - except Exception: - add_file_handler(cloudlog) - cloudlog.exception("Manager failed to start") - - try: - managed_processes['ui'].stop() - except Exception: - pass - - # Show last 3 lines of traceback - error = traceback.format_exc(-3) - error = "Manager failed to start\n\n" + error - with TextWindow(error) as t: - t.wait_for_exit() - - raise - - # manual exit because we are forked - sys.exit(0) diff --git a/system/manager/process.py b/system/manager/process.py deleted file mode 100644 index 0ebddae049..0000000000 --- a/system/manager/process.py +++ /dev/null @@ -1,296 +0,0 @@ -import importlib -import os -import signal -import struct -import time -import subprocess -from collections.abc import Callable, ValuesView -from abc import ABC, abstractmethod -from multiprocessing import Process - -from setproctitle import setproctitle - -from cereal import car, log -import cereal.messaging as messaging -import openpilot.system.sentry as sentry -from openpilot.common.basedir import BASEDIR -from openpilot.common.params import Params -from openpilot.common.swaglog import cloudlog -from openpilot.common.watchdog import WATCHDOG_FN - -ENABLE_WATCHDOG = os.getenv("NO_WATCHDOG") is None - - -def launcher(proc: str, name: str) -> None: - try: - # import the process - mod = importlib.import_module(proc) - - # rename the process - setproctitle(proc) - - # create new context since we forked - messaging.reset_context() - - # add daemon name tag to logs - cloudlog.bind(daemon=name) - sentry.set_tag("daemon", name) - - # exec the process - mod.main() - except KeyboardInterrupt: - cloudlog.warning(f"child {proc} got SIGINT") - except Exception: - # can't install the crash handler because sys.excepthook doesn't play nice - # with threads, so catch it here. - sentry.capture_exception() - raise - - -def nativelauncher(pargs: list[str], cwd: str, name: str) -> None: - os.environ['MANAGER_DAEMON'] = name - - # exec the process - os.chdir(cwd) - os.execvp(pargs[0], pargs) - - -def join_process(process: Process, timeout: float) -> None: - # Process().join(timeout) will hang due to a python 3 bug: https://bugs.python.org/issue28382 - # We have to poll the exitcode instead - t = time.monotonic() - while time.monotonic() - t < timeout and process.exitcode is None: - time.sleep(0.001) - - -class ManagerProcess(ABC): - daemon = False - sigkill = False - should_run: Callable[[bool, Params, car.CarParams], bool] - proc: Process | None = None - enabled = True - name = "" - - last_watchdog_time = 0 - watchdog_max_dt: int | None = None - watchdog_seen = False - shutting_down = False - - @abstractmethod - def prepare(self) -> None: - pass - - @abstractmethod - def start(self) -> None: - pass - - def restart(self) -> None: - self.stop(sig=signal.SIGKILL) - self.start() - - def check_watchdog(self, started: bool) -> None: - if self.watchdog_max_dt is None or self.proc is None: - return - - try: - fn = WATCHDOG_FN + str(self.proc.pid) - with open(fn, "rb") as f: - self.last_watchdog_time = struct.unpack('Q', f.read())[0] - except Exception: - pass - - dt = time.monotonic() - self.last_watchdog_time / 1e9 - - if dt > self.watchdog_max_dt: - if self.watchdog_seen and ENABLE_WATCHDOG: - cloudlog.error(f"Watchdog timeout for {self.name} (exitcode {self.proc.exitcode}) restarting ({started=})") - self.restart() - else: - self.watchdog_seen = True - - def stop(self, retry: bool = True, block: bool = True, sig: signal.Signals = None) -> int | None: - if self.proc is None: - return None - - if self.proc.exitcode is None: - if not self.shutting_down: - cloudlog.info(f"killing {self.name}") - if sig is None: - sig = signal.SIGKILL if self.sigkill else signal.SIGINT - self.signal(sig) - self.shutting_down = True - - if not block: - return None - - join_process(self.proc, 5) - - # If process failed to die send SIGKILL - if self.proc.exitcode is None and retry: - cloudlog.info(f"killing {self.name} with SIGKILL") - self.signal(signal.SIGKILL) - self.proc.join() - - ret = self.proc.exitcode - cloudlog.info(f"{self.name} is dead with {ret}") - - if self.proc.exitcode is not None: - self.shutting_down = False - self.proc = None - - return ret - - def signal(self, sig: int) -> None: - if self.proc is None: - return - - # Don't signal if already exited - if self.proc.exitcode is not None and self.proc.pid is not None: - return - - # Can't signal if we don't have a pid - if self.proc.pid is None: - return - - cloudlog.info(f"sending signal {sig} to {self.name}") - os.kill(self.proc.pid, sig) - - def get_process_state_msg(self): - state = log.ManagerState.ProcessState.new_message() - state.name = self.name - if self.proc: - state.running = self.proc.is_alive() - state.shouldBeRunning = self.proc is not None and not self.shutting_down - state.pid = self.proc.pid or 0 - state.exitCode = self.proc.exitcode or 0 - return state - - -class NativeProcess(ManagerProcess): - def __init__(self, name, cwd, cmdline, should_run, enabled=True, sigkill=False, watchdog_max_dt=None): - self.name = name - self.cwd = cwd - self.cmdline = cmdline - self.should_run = should_run - self.enabled = enabled - self.sigkill = sigkill - self.watchdog_max_dt = watchdog_max_dt - self.launcher = nativelauncher - - def prepare(self) -> None: - pass - - def start(self) -> None: - # In case we only tried a non blocking stop we need to stop it before restarting - if self.shutting_down: - self.stop() - - if self.proc is not None: - return - - cwd = os.path.join(BASEDIR, self.cwd) - cloudlog.info(f"starting process {self.name}") - self.proc = Process(name=self.name, target=self.launcher, args=(self.cmdline, cwd, self.name)) - self.proc.start() - self.watchdog_seen = False - self.shutting_down = False - - -class PythonProcess(ManagerProcess): - def __init__(self, name, module, should_run, enabled=True, sigkill=False, watchdog_max_dt=None): - self.name = name - self.module = module - self.should_run = should_run - self.enabled = enabled - self.sigkill = sigkill - self.watchdog_max_dt = watchdog_max_dt - self.launcher = launcher - - def prepare(self) -> None: - if self.enabled: - cloudlog.info(f"preimporting {self.module}") - importlib.import_module(self.module) - - def start(self) -> None: - # In case we only tried a non blocking stop we need to stop it before restarting - if self.shutting_down: - self.stop() - - if self.proc is not None: - return - - # TODO: this is just a workaround for this tinygrad check: - # https://github.com/tinygrad/tinygrad/blob/ac9c96dae1656dc220ee4acc39cef4dd449aa850/tinygrad/device.py#L26 - name = self.name if "modeld" not in self.name else "MainProcess" - - cloudlog.info(f"starting python {self.module}") - self.proc = Process(name=name, target=self.launcher, args=(self.module, self.name)) - self.proc.start() - self.watchdog_seen = False - self.shutting_down = False - - -class DaemonProcess(ManagerProcess): - """Python process that has to stay running across manager restart. - This is used for athena so you don't lose SSH access when restarting manager.""" - def __init__(self, name, module, param_name, enabled=True): - self.name = name - self.module = module - self.param_name = param_name - self.enabled = enabled - self.params = None - - @staticmethod - def should_run(started, params, CP): - return True - - def prepare(self) -> None: - pass - - def start(self) -> None: - if self.params is None: - self.params = Params() - - pid = self.params.get(self.param_name, encoding='utf-8') - if pid is not None: - try: - os.kill(int(pid), 0) - with open(f'/proc/{pid}/cmdline') as f: - if self.module in f.read(): - # daemon is running - return - except (OSError, FileNotFoundError): - # process is dead - pass - - cloudlog.info(f"starting daemon {self.name}") - proc = subprocess.Popen(['python', '-m', self.module], - stdin=open('/dev/null'), - stdout=open('/dev/null', 'w'), - stderr=open('/dev/null', 'w'), - preexec_fn=os.setpgrp) - - self.params.put(self.param_name, str(proc.pid)) - - def stop(self, retry=True, block=True, sig=None) -> None: - pass - - -def ensure_running(procs: ValuesView[ManagerProcess], started: bool, params=None, CP: car.CarParams=None, - not_run: list[str] | None=None) -> list[ManagerProcess]: - if not_run is None: - not_run = [] - - running = [] - for p in procs: - if p.enabled and p.name not in not_run and p.should_run(started, params, CP): - running.append(p) - else: - p.stop(block=False) - - p.check_watchdog(started) - - for p in running: - p.start() - - return running diff --git a/system/manager/process_config.py b/system/manager/process_config.py deleted file mode 100644 index d5c5a4e3c8..0000000000 --- a/system/manager/process_config.py +++ /dev/null @@ -1,175 +0,0 @@ -import os -import operator -import platform - -from cereal import car, custom -from openpilot.common.params import Params -from openpilot.system.hardware import PC, TICI -from openpilot.system.manager.process import PythonProcess, NativeProcess, DaemonProcess -from openpilot.system.hardware.hw import Paths - -from openpilot.sunnypilot.mapd.mapd_manager import MAPD_PATH - -from sunnypilot.models.helpers import get_active_model_runner -from sunnypilot.sunnylink.utils import sunnylink_need_register, sunnylink_ready, use_sunnylink_uploader - -WEBCAM = os.getenv("USE_WEBCAM") is not None - -def driverview(started: bool, params: Params, CP: car.CarParams) -> bool: - return started or params.get_bool("IsDriverViewEnabled") - -def notcar(started: bool, params: Params, CP: car.CarParams) -> bool: - return started and CP.notCar - -def iscar(started: bool, params: Params, CP: car.CarParams) -> bool: - return started and not CP.notCar - -def logging(started: bool, params: Params, CP: car.CarParams) -> bool: - run = (not CP.notCar) or not params.get_bool("DisableLogging") - return started and run - -def ublox_available() -> bool: - return os.path.exists('/dev/ttyHS0') and not os.path.exists('/persist/comma/use-quectel-gps') - -def ublox(started: bool, params: Params, CP: car.CarParams) -> bool: - use_ublox = ublox_available() - if use_ublox != params.get_bool("UbloxAvailable"): - params.put_bool("UbloxAvailable", use_ublox) - return started and use_ublox - -def joystick(started: bool, params: Params, CP: car.CarParams) -> bool: - return started and params.get_bool("JoystickDebugMode") - -def not_joystick(started: bool, params: Params, CP: car.CarParams) -> bool: - return started and not params.get_bool("JoystickDebugMode") - -def long_maneuver(started: bool, params: Params, CP: car.CarParams) -> bool: - return started and params.get_bool("LongitudinalManeuverMode") - -def not_long_maneuver(started: bool, params: Params, CP: car.CarParams) -> bool: - return started and not params.get_bool("LongitudinalManeuverMode") - -def qcomgps(started: bool, params: Params, CP: car.CarParams) -> bool: - return started and not ublox_available() - -def always_run(started: bool, params: Params, CP: car.CarParams) -> bool: - return True - -def only_onroad(started: bool, params: Params, CP: car.CarParams) -> bool: - return started - -def only_offroad(started: bool, params: Params, CP: car.CarParams) -> bool: - return not started - -def use_github_runner(started, params, CP: car.CarParams) -> bool: - return not PC and params.get_bool("EnableGithubRunner") and not params.get_bool("NetworkMetered") - -def sunnylink_ready_shim(started, params, CP: car.CarParams) -> bool: - """Shim for sunnylink_ready to match the process manager signature.""" - return sunnylink_ready(params) - -def sunnylink_need_register_shim(started, params, CP: car.CarParams) -> bool: - """Shim for sunnylink_need_register to match the process manager signature.""" - return sunnylink_need_register(params) - -def use_sunnylink_uploader_shim(started, params, CP: car.CarParams) -> bool: - """Shim for use_sunnylink_uploader to match the process manager signature.""" - return use_sunnylink_uploader(params) - -def is_snpe_model(started, params, CP: car.CarParams) -> bool: - """Check if the active model runner is SNPE.""" - return bool(get_active_model_runner(params, not started) == custom.ModelManagerSP.Runner.snpe) - -def is_tinygrad_model(started, params, CP: car.CarParams) -> bool: - """Check if the active model runner is SNPE.""" - return bool(get_active_model_runner(params, not started) == custom.ModelManagerSP.Runner.tinygrad) - -def is_stock_model(started, params, CP: car.CarParams) -> bool: - """Check if the active model runner is stock.""" - return bool(get_active_model_runner(params, not started) == custom.ModelManagerSP.Runner.stock) - -def or_(*fns): - return lambda *args: operator.or_(*(fn(*args) for fn in fns)) - -def and_(*fns): - return lambda *args: operator.and_(*(fn(*args) for fn in fns)) - -procs = [ - DaemonProcess("manage_athenad", "system.athena.manage_athenad", "AthenadPid"), - - NativeProcess("loggerd", "system/loggerd", ["./loggerd"], logging), - NativeProcess("encoderd", "system/loggerd", ["./encoderd"], only_onroad), - NativeProcess("stream_encoderd", "system/loggerd", ["./encoderd", "--stream"], notcar), - PythonProcess("logmessaged", "system.logmessaged", always_run), - - NativeProcess("camerad", "system/camerad", ["./camerad"], driverview, enabled=not WEBCAM), - PythonProcess("webcamerad", "tools.webcam.camerad", driverview, enabled=WEBCAM), - NativeProcess("logcatd", "system/logcatd", ["./logcatd"], only_onroad, platform.system() != "Darwin"), - NativeProcess("proclogd", "system/proclogd", ["./proclogd"], only_onroad, platform.system() != "Darwin"), - PythonProcess("micd", "system.micd", iscar), - PythonProcess("timed", "system.timed", always_run, enabled=not PC), - - PythonProcess("modeld", "selfdrive.modeld.modeld", and_(only_onroad, is_stock_model)), - PythonProcess("dmonitoringmodeld", "selfdrive.modeld.dmonitoringmodeld", driverview, enabled=(WEBCAM or not PC)), - - PythonProcess("sensord", "system.sensord.sensord", only_onroad, enabled=not PC), - NativeProcess("ui", "selfdrive/ui", ["./ui"], always_run, watchdog_max_dt=(5 if not PC else None)), - PythonProcess("soundd", "selfdrive.ui.soundd", and_(only_onroad, not_joystick)), - PythonProcess("locationd", "selfdrive.locationd.locationd", only_onroad), - NativeProcess("_pandad", "selfdrive/pandad", ["./pandad"], always_run, enabled=False), - PythonProcess("calibrationd", "selfdrive.locationd.calibrationd", only_onroad), - PythonProcess("torqued", "selfdrive.locationd.torqued", only_onroad), - PythonProcess("controlsd", "selfdrive.controls.controlsd", and_(not_joystick, iscar)), - PythonProcess("joystickd", "tools.joystick.joystickd", or_(joystick, notcar)), - PythonProcess("selfdrived", "selfdrive.selfdrived.selfdrived", only_onroad), - PythonProcess("card", "selfdrive.car.card", only_onroad), - PythonProcess("deleter", "system.loggerd.deleter", always_run), - PythonProcess("dmonitoringd", "selfdrive.monitoring.dmonitoringd", driverview, enabled=(WEBCAM or not PC)), - PythonProcess("qcomgpsd", "system.qcomgpsd.qcomgpsd", qcomgps, enabled=TICI), - PythonProcess("pandad", "selfdrive.pandad.pandad", always_run), - PythonProcess("paramsd", "selfdrive.locationd.paramsd", only_onroad), - PythonProcess("lagd", "selfdrive.locationd.lagd", only_onroad), - NativeProcess("ubloxd", "system/ubloxd", ["./ubloxd"], ublox, enabled=TICI), - PythonProcess("pigeond", "system.ubloxd.pigeond", ublox, enabled=TICI), - PythonProcess("plannerd", "selfdrive.controls.plannerd", not_long_maneuver), - PythonProcess("maneuversd", "tools.longitudinal_maneuvers.maneuversd", long_maneuver), - PythonProcess("radard", "selfdrive.controls.radard", only_onroad), - PythonProcess("hardwared", "system.hardware.hardwared", always_run), - PythonProcess("tombstoned", "system.tombstoned", always_run, enabled=not PC), - PythonProcess("updated", "system.updated.updated", only_offroad, enabled=not PC), - PythonProcess("uploader", "system.loggerd.uploader", always_run), - PythonProcess("statsd", "system.statsd", always_run), - - # debug procs - NativeProcess("bridge", "cereal/messaging", ["./bridge"], notcar), - PythonProcess("webrtcd", "system.webrtc.webrtcd", notcar), - PythonProcess("webjoystick", "tools.bodyteleop.web", notcar), - PythonProcess("joystick", "tools.joystick.joystick_control", and_(joystick, iscar)), - - # sunnylink <3 - DaemonProcess("manage_sunnylinkd", "sunnypilot.sunnylink.athena.manage_sunnylinkd", "SunnylinkdPid"), - PythonProcess("sunnylink_registration_manager", "sunnypilot.sunnylink.registration_manager", sunnylink_need_register_shim), -] - -# sunnypilot -procs += [ - # Models - PythonProcess("models_manager", "sunnypilot.models.manager", only_offroad), - NativeProcess("modeld_snpe", "sunnypilot/modeld", ["./modeld"], and_(only_onroad, is_snpe_model)), - NativeProcess("modeld_tinygrad", "sunnypilot/modeld_v2", ["./modeld"], and_(only_onroad, is_tinygrad_model)), - - # Backup - PythonProcess("backup_manager", "sunnypilot.sunnylink.backups.manager", and_(only_offroad, sunnylink_ready_shim)), - - # mapd - NativeProcess("mapd", Paths.mapd_root(), [MAPD_PATH], always_run), - PythonProcess("mapd_manager", "sunnypilot.mapd.mapd_manager", always_run), -] - -if os.path.exists("./github_runner.sh"): - procs += [NativeProcess("github_runner_start", "system/manager", ["./github_runner.sh", "start"], and_(only_offroad, use_github_runner), sigkill=False)] - -if os.path.exists("../sunnypilot/sunnylink/uploader.py"): - procs += [PythonProcess("sunnylink_uploader", "sunnypilot.sunnylink.uploader", use_sunnylink_uploader_shim)] - -managed_processes = {p.name: p for p in procs} diff --git a/system/proclogd/SConscript b/system/proclogd/SConscript deleted file mode 100644 index 08814d5ccb..0000000000 --- a/system/proclogd/SConscript +++ /dev/null @@ -1,6 +0,0 @@ -Import('env', 'messaging', 'common') -libs = [messaging, 'pthread', common] -env.Program('proclogd', ['main.cc', 'proclog.cc'], LIBS=libs) - -if GetOption('extras'): - env.Program('tests/test_proclog', ['tests/test_proclog.cc', 'proclog.cc'], LIBS=libs) diff --git a/system/proclogd/main.cc b/system/proclogd/main.cc deleted file mode 100644 index 3f8a889eea..0000000000 --- a/system/proclogd/main.cc +++ /dev/null @@ -1,25 +0,0 @@ - -#include - -#include "common/ratekeeper.h" -#include "common/util.h" -#include "system/proclogd/proclog.h" - -ExitHandler do_exit; - -int main(int argc, char **argv) { - setpriority(PRIO_PROCESS, 0, -15); - - RateKeeper rk("proclogd", 0.5); - PubMaster publisher({"procLog"}); - - while (!do_exit) { - MessageBuilder msg; - buildProcLogMessage(msg); - publisher.send("procLog", msg); - - rk.keepTime(); - } - - return 0; -} diff --git a/system/proclogd/proclog.cc b/system/proclogd/proclog.cc deleted file mode 100644 index 09ab4f559e..0000000000 --- a/system/proclogd/proclog.cc +++ /dev/null @@ -1,239 +0,0 @@ -#include "system/proclogd/proclog.h" - -#include - -#include -#include -#include -#include - -#include "common/swaglog.h" -#include "common/util.h" - -namespace Parser { - -// parse /proc/stat -std::vector cpuTimes(std::istream &stream) { - std::vector cpu_times; - std::string line; - // skip the first line for cpu total - std::getline(stream, line); - while (std::getline(stream, line)) { - if (line.compare(0, 3, "cpu") != 0) break; - - CPUTime t = {}; - std::istringstream iss(line); - if (iss.ignore(3) >> t.id >> t.utime >> t.ntime >> t.stime >> t.itime >> t.iowtime >> t.irqtime >> t.sirqtime) - cpu_times.push_back(t); - } - return cpu_times; -} - -// parse /proc/meminfo -std::unordered_map memInfo(std::istream &stream) { - std::unordered_map mem_info; - std::string line, key; - while (std::getline(stream, line)) { - uint64_t val = 0; - std::istringstream iss(line); - if (iss >> key >> val) { - mem_info[key] = val * 1024; - } - } - return mem_info; -} - -// field position (https://man7.org/linux/man-pages/man5/proc.5.html) -enum StatPos { - pid = 1, - state = 3, - ppid = 4, - utime = 14, - stime = 15, - cutime = 16, - cstime = 17, - priority = 18, - nice = 19, - num_threads = 20, - starttime = 22, - vsize = 23, - rss = 24, - processor = 39, - MAX_FIELD = 52, -}; - -// parse /proc/pid/stat -std::optional procStat(std::string stat) { - // To avoid being fooled by names containing a closing paren, scan backwards. - auto open_paren = stat.find('('); - auto close_paren = stat.rfind(')'); - if (open_paren == std::string::npos || close_paren == std::string::npos || open_paren > close_paren) { - return std::nullopt; - } - - std::string name = stat.substr(open_paren + 1, close_paren - open_paren - 1); - // replace space in name with _ - std::replace(&stat[open_paren], &stat[close_paren], ' ', '_'); - std::istringstream iss(stat); - std::vector v{std::istream_iterator(iss), - std::istream_iterator()}; - try { - if (v.size() != StatPos::MAX_FIELD) { - throw std::invalid_argument("stat"); - } - ProcStat p = { - .name = name, - .pid = stoi(v[StatPos::pid - 1]), - .state = v[StatPos::state - 1][0], - .ppid = stoi(v[StatPos::ppid - 1]), - .utime = stoul(v[StatPos::utime - 1]), - .stime = stoul(v[StatPos::stime - 1]), - .cutime = stol(v[StatPos::cutime - 1]), - .cstime = stol(v[StatPos::cstime - 1]), - .priority = stol(v[StatPos::priority - 1]), - .nice = stol(v[StatPos::nice - 1]), - .num_threads = stol(v[StatPos::num_threads - 1]), - .starttime = stoull(v[StatPos::starttime - 1]), - .vms = stoul(v[StatPos::vsize - 1]), - .rss = stol(v[StatPos::rss - 1]), - .processor = stoi(v[StatPos::processor - 1]), - }; - return p; - } catch (const std::invalid_argument &e) { - LOGE("failed to parse procStat (%s) :%s", e.what(), stat.c_str()); - } catch (const std::out_of_range &e) { - LOGE("failed to parse procStat (%s) :%s", e.what(), stat.c_str()); - } - return std::nullopt; -} - -// return list of PIDs from /proc -std::vector pids() { - std::vector ids; - DIR *d = opendir("/proc"); - assert(d); - char *p_end; - struct dirent *de = NULL; - while ((de = readdir(d))) { - if (de->d_type == DT_DIR) { - int pid = strtol(de->d_name, &p_end, 10); - if (p_end == (de->d_name + strlen(de->d_name))) { - ids.push_back(pid); - } - } - } - closedir(d); - return ids; -} - -// null-delimited cmdline arguments to vector -std::vector cmdline(std::istream &stream) { - std::vector ret; - std::string line; - while (std::getline(stream, line, '\0')) { - if (!line.empty()) { - ret.push_back(line); - } - } - return ret; -} - -const ProcCache &getProcExtraInfo(int pid, const std::string &name) { - static std::unordered_map proc_cache; - ProcCache &cache = proc_cache[pid]; - if (cache.pid != pid || cache.name != name) { - cache.pid = pid; - cache.name = name; - std::string proc_path = "/proc/" + std::to_string(pid); - cache.exe = util::readlink(proc_path + "/exe"); - std::ifstream stream(proc_path + "/cmdline"); - cache.cmdline = cmdline(stream); - } - return cache; -} - -} // namespace Parser - -const double jiffy = sysconf(_SC_CLK_TCK); -const size_t page_size = sysconf(_SC_PAGE_SIZE); - -void buildCPUTimes(cereal::ProcLog::Builder &builder) { - std::ifstream stream("/proc/stat"); - std::vector stats = Parser::cpuTimes(stream); - - auto log_cpu_times = builder.initCpuTimes(stats.size()); - for (int i = 0; i < stats.size(); ++i) { - auto l = log_cpu_times[i]; - const CPUTime &r = stats[i]; - l.setCpuNum(r.id); - l.setUser(r.utime / jiffy); - l.setNice(r.ntime / jiffy); - l.setSystem(r.stime / jiffy); - l.setIdle(r.itime / jiffy); - l.setIowait(r.iowtime / jiffy); - l.setIrq(r.irqtime / jiffy); - l.setSoftirq(r.sirqtime / jiffy); - } -} - -void buildMemInfo(cereal::ProcLog::Builder &builder) { - std::ifstream stream("/proc/meminfo"); - auto mem_info = Parser::memInfo(stream); - - auto mem = builder.initMem(); - mem.setTotal(mem_info["MemTotal:"]); - mem.setFree(mem_info["MemFree:"]); - mem.setAvailable(mem_info["MemAvailable:"]); - mem.setBuffers(mem_info["Buffers:"]); - mem.setCached(mem_info["Cached:"]); - mem.setActive(mem_info["Active:"]); - mem.setInactive(mem_info["Inactive:"]); - mem.setShared(mem_info["Shmem:"]); -} - -void buildProcs(cereal::ProcLog::Builder &builder) { - auto pids = Parser::pids(); - std::vector proc_stats; - proc_stats.reserve(pids.size()); - for (int pid : pids) { - std::string path = "/proc/" + std::to_string(pid) + "/stat"; - if (auto stat = Parser::procStat(util::read_file(path))) { - proc_stats.push_back(*stat); - } - } - - auto procs = builder.initProcs(proc_stats.size()); - for (size_t i = 0; i < proc_stats.size(); i++) { - auto l = procs[i]; - const ProcStat &r = proc_stats[i]; - l.setPid(r.pid); - l.setState(r.state); - l.setPpid(r.ppid); - l.setCpuUser(r.utime / jiffy); - l.setCpuSystem(r.stime / jiffy); - l.setCpuChildrenUser(r.cutime / jiffy); - l.setCpuChildrenSystem(r.cstime / jiffy); - l.setPriority(r.priority); - l.setNice(r.nice); - l.setNumThreads(r.num_threads); - l.setStartTime(r.starttime / jiffy); - l.setMemVms(r.vms); - l.setMemRss((uint64_t)r.rss * page_size); - l.setProcessor(r.processor); - l.setName(r.name); - - const ProcCache &extra_info = Parser::getProcExtraInfo(r.pid, r.name); - l.setExe(extra_info.exe); - auto lcmdline = l.initCmdline(extra_info.cmdline.size()); - for (size_t j = 0; j < lcmdline.size(); j++) { - lcmdline.set(j, extra_info.cmdline[j]); - } - } -} - -void buildProcLogMessage(MessageBuilder &msg) { - auto procLog = msg.initEvent().initProcLog(); - buildProcs(procLog); - buildCPUTimes(procLog); - buildMemInfo(procLog); -} diff --git a/system/proclogd/proclog.h b/system/proclogd/proclog.h deleted file mode 100644 index 49f97cdd36..0000000000 --- a/system/proclogd/proclog.h +++ /dev/null @@ -1,40 +0,0 @@ -#include -#include -#include -#include - -#include "cereal/messaging/messaging.h" - -struct CPUTime { - int id; - unsigned long utime, ntime, stime, itime; - unsigned long iowtime, irqtime, sirqtime; -}; - -struct ProcCache { - int pid; - std::string name, exe; - std::vector cmdline; -}; - -struct ProcStat { - int pid, ppid, processor; - char state; - long cutime, cstime, priority, nice, num_threads, rss; - unsigned long utime, stime, vms; - unsigned long long starttime; - std::string name; -}; - -namespace Parser { - -std::vector pids(); -std::optional procStat(std::string stat); -std::vector cmdline(std::istream &stream); -std::vector cpuTimes(std::istream &stream); -std::unordered_map memInfo(std::istream &stream); -const ProcCache &getProcExtraInfo(int pid, const std::string &name); - -}; // namespace Parser - -void buildProcLogMessage(MessageBuilder &msg); diff --git a/system/proclogd/tests/.gitignore b/system/proclogd/tests/.gitignore deleted file mode 100644 index 5230b1598d..0000000000 --- a/system/proclogd/tests/.gitignore +++ /dev/null @@ -1 +0,0 @@ -test_proclog diff --git a/system/proclogd/tests/test_proclog.cc b/system/proclogd/tests/test_proclog.cc deleted file mode 100644 index b86229a499..0000000000 --- a/system/proclogd/tests/test_proclog.cc +++ /dev/null @@ -1,142 +0,0 @@ -#define CATCH_CONFIG_MAIN -#include "catch2/catch.hpp" -#include "common/util.h" -#include "system/proclogd/proclog.h" - -const std::string allowed_states = "RSDTZtWXxKWPI"; - -TEST_CASE("Parser::procStat") { - SECTION("from string") { - const std::string stat_str = - "33012 (code )) S 32978 6620 6620 0 -1 4194368 2042377 0 144 0 24510 11627 0 " - "0 20 0 39 0 53077 830029824 62214 18446744073709551615 94257242783744 94257366235808 " - "140735738643248 0 0 0 0 4098 1073808632 0 0 0 17 2 0 0 2 0 0 94257370858656 94257371248232 " - "94257404952576 140735738648768 140735738648823 140735738648823 140735738650595 0"; - auto stat = Parser::procStat(stat_str); - REQUIRE(stat); - REQUIRE(stat->pid == 33012); - REQUIRE(stat->name == "code )"); - REQUIRE(stat->state == 'S'); - REQUIRE(stat->ppid == 32978); - REQUIRE(stat->utime == 24510); - REQUIRE(stat->stime == 11627); - REQUIRE(stat->cutime == 0); - REQUIRE(stat->cstime == 0); - REQUIRE(stat->priority == 20); - REQUIRE(stat->nice == 0); - REQUIRE(stat->num_threads == 39); - REQUIRE(stat->starttime == 53077); - REQUIRE(stat->vms == 830029824); - REQUIRE(stat->rss == 62214); - REQUIRE(stat->processor == 2); - } - SECTION("all processes") { - std::vector pids = Parser::pids(); - REQUIRE(pids.size() > 1); - for (int pid : pids) { - std::string stat_path = "/proc/" + std::to_string(pid) + "/stat"; - INFO(stat_path); - if (auto stat = Parser::procStat(util::read_file(stat_path))) { - REQUIRE(stat->pid == pid); - REQUIRE(allowed_states.find(stat->state) != std::string::npos); - } else { - REQUIRE(util::file_exists(stat_path) == false); - } - } - } -} - -TEST_CASE("Parser::cpuTimes") { - SECTION("from string") { - std::string stat = - "cpu 0 0 0 0 0 0 0 0 0 0\n" - "cpu0 1 2 3 4 5 6 7 8 9 10\n" - "cpu1 1 2 3 4 5 6 7 8 9 10\n"; - std::istringstream stream(stat); - auto stats = Parser::cpuTimes(stream); - REQUIRE(stats.size() == 2); - for (int i = 0; i < stats.size(); ++i) { - REQUIRE(stats[i].id == i); - REQUIRE(stats[i].utime == 1); - REQUIRE(stats[i].ntime ==2); - REQUIRE(stats[i].stime == 3); - REQUIRE(stats[i].itime == 4); - REQUIRE(stats[i].iowtime == 5); - REQUIRE(stats[i].irqtime == 6); - REQUIRE(stats[i].sirqtime == 7); - } - } - SECTION("all cpus") { - std::istringstream stream(util::read_file("/proc/stat")); - auto stats = Parser::cpuTimes(stream); - REQUIRE(stats.size() == sysconf(_SC_NPROCESSORS_ONLN)); - for (int i = 0; i < stats.size(); ++i) { - REQUIRE(stats[i].id == i); - } - } -} - -TEST_CASE("Parser::memInfo") { - SECTION("from string") { - std::istringstream stream("MemTotal: 1024 kb\nMemFree: 2048 kb\n"); - auto meminfo = Parser::memInfo(stream); - REQUIRE(meminfo["MemTotal:"] == 1024 * 1024); - REQUIRE(meminfo["MemFree:"] == 2048 * 1024); - } - SECTION("from /proc/meminfo") { - std::string require_keys[] = {"MemTotal:", "MemFree:", "MemAvailable:", "Buffers:", "Cached:", "Active:", "Inactive:", "Shmem:"}; - std::istringstream stream(util::read_file("/proc/meminfo")); - auto meminfo = Parser::memInfo(stream); - for (auto &key : require_keys) { - REQUIRE(meminfo.find(key) != meminfo.end()); - REQUIRE(meminfo[key] > 0); - } - } -} - -void test_cmdline(std::string cmdline, const std::vector requires) { - std::stringstream ss; - ss.write(&cmdline[0], cmdline.size()); - auto cmds = Parser::cmdline(ss); - REQUIRE(cmds.size() == requires.size()); - for (int i = 0; i < requires.size(); ++i) { - REQUIRE(cmds[i] == requires[i]); - } -} -TEST_CASE("Parser::cmdline") { - test_cmdline(std::string("a\0b\0c\0", 7), {"a", "b", "c"}); - test_cmdline(std::string("a\0\0c\0", 6), {"a", "c"}); - test_cmdline(std::string("a\0b\0c\0\0\0", 9), {"a", "b", "c"}); -} - -TEST_CASE("buildProcLoggerMessage") { - MessageBuilder msg; - buildProcLogMessage(msg); - - kj::Array buf = capnp::messageToFlatArray(msg); - capnp::FlatArrayMessageReader reader(buf); - auto log = reader.getRoot().getProcLog(); - REQUIRE(log.totalSize().wordCount > 0); - - // test cereal::ProcLog::CPUTimes - auto cpu_times = log.getCpuTimes(); - REQUIRE(cpu_times.size() == sysconf(_SC_NPROCESSORS_ONLN)); - REQUIRE(cpu_times[cpu_times.size() - 1].getCpuNum() == cpu_times.size() - 1); - - // test cereal::ProcLog::Mem - auto mem = log.getMem(); - REQUIRE(mem.getTotal() > 0); - REQUIRE(mem.getShared() > 0); - - // test cereal::ProcLog::Process - auto procs = log.getProcs(); - for (auto p : procs) { - REQUIRE(allowed_states.find(p.getState()) != std::string::npos); - if (p.getPid() == ::getpid()) { - REQUIRE(p.getName() == "test_proclog"); - REQUIRE(p.getState() == 'R'); - REQUIRE_THAT(p.getExe().cStr(), Catch::Matchers::Contains("test_proclog")); - REQUIRE_THAT(p.getCmdline()[0], Catch::Matchers::Contains("test_proclog")); - } - } -} diff --git a/system/qcomgpsd/nmeaport.py b/system/qcomgpsd/nmeaport.py deleted file mode 100644 index 8b9ab51086..0000000000 --- a/system/qcomgpsd/nmeaport.py +++ /dev/null @@ -1,169 +0,0 @@ -import os -import sys -from dataclasses import dataclass, fields -from subprocess import check_output, CalledProcessError -from time import sleep -from typing import NoReturn - -DEBUG = int(os.environ.get("DEBUG", "0")) - -@dataclass -class GnssClockNmeaPort: - # flags bit mask: - # 0x01 = leap_seconds valid - # 0x02 = time_uncertainty_ns valid - # 0x04 = full_bias_ns valid - # 0x08 = bias_ns valid - # 0x10 = bias_uncertainty_ns valid - # 0x20 = drift_nsps valid - # 0x40 = drift_uncertainty_nsps valid - flags: int - leap_seconds: int - time_ns: int - time_uncertainty_ns: int # 1-sigma - full_bias_ns: int - bias_ns: float - bias_uncertainty_ns: float # 1-sigma - drift_nsps: float - drift_uncertainty_nsps: float # 1-sigma - - def __post_init__(self): - for field in fields(self): - val = getattr(self, field.name) - setattr(self, field.name, field.type(val) if val else None) - -@dataclass -class GnssMeasNmeaPort: - messageCount: int - messageNum: int - svCount: int - # constellation enum: - # 1 = GPS - # 2 = SBAS - # 3 = GLONASS - # 4 = QZSS - # 5 = BEIDOU - # 6 = GALILEO - constellation: int - svId: int - flags: int # always zero - time_offset_ns: int - # state bit mask: - # 0x0001 = CODE LOCK - # 0x0002 = BIT SYNC - # 0x0004 = SUBFRAME SYNC - # 0x0008 = TIME OF WEEK DECODED - # 0x0010 = MSEC AMBIGUOUS - # 0x0020 = SYMBOL SYNC - # 0x0040 = GLONASS STRING SYNC - # 0x0080 = GLONASS TIME OF DAY DECODED - # 0x0100 = BEIDOU D2 BIT SYNC - # 0x0200 = BEIDOU D2 SUBFRAME SYNC - # 0x0400 = GALILEO E1BC CODE LOCK - # 0x0800 = GALILEO E1C 2ND CODE LOCK - # 0x1000 = GALILEO E1B PAGE SYNC - # 0x2000 = GALILEO E1B PAGE SYNC - state: int - time_of_week_ns: int - time_of_week_uncertainty_ns: int # 1-sigma - carrier_to_noise_ratio: float - pseudorange_rate: float - pseudorange_rate_uncertainty: float # 1-sigma - - def __post_init__(self): - for field in fields(self): - val = getattr(self, field.name) - setattr(self, field.name, field.type(val) if val else None) - -def nmea_checksum_ok(s): - checksum = 0 - for i, c in enumerate(s[1:]): - if c == "*": - if i != len(s) - 4: # should be 3rd to last character - print("ERROR: NMEA string does not have checksum delimiter in correct location:", s) - return False - break - checksum ^= ord(c) - else: - print("ERROR: NMEA string does not have checksum delimiter:", s) - return False - - return True - -def process_nmea_port_messages(device:str="/dev/ttyUSB1") -> NoReturn: - while True: - try: - with open(device) as nmeaport: - for line in nmeaport: - line = line.strip() - if DEBUG: - print(line) - if not line.startswith("$"): # all NMEA messages start with $ - continue - if not nmea_checksum_ok(line): - continue - - fields = line.split(",") - match fields[0]: - case "$GNCLK": - # fields at end are reserved (not used) - gnss_clock = GnssClockNmeaPort(*fields[1:10]) # type: ignore[arg-type] - print(gnss_clock) - case "$GNMEAS": - # fields at end are reserved (not used) - gnss_meas = GnssMeasNmeaPort(*fields[1:14]) # type: ignore[arg-type] - print(gnss_meas) - except Exception as e: - print(e) - sleep(1) - -def main() -> NoReturn: - from openpilot.common.gpio import gpio_init, gpio_set - from openpilot.system.hardware.tici.pins import GPIO - from openpilot.system.qcomgpsd.qcomgpsd import at_cmd - - try: - check_output(["pidof", "qcomgpsd"]) - print("qcomgpsd is running, please kill openpilot before running this script! (aborted)") - sys.exit(1) - except CalledProcessError as e: - if e.returncode != 1: # 1 == no process found (pandad not running) - raise e - - print("power up antenna ...") - gpio_init(GPIO.GNSS_PWR_EN, True) - gpio_set(GPIO.GNSS_PWR_EN, True) - - if b"+QGPS: 0" not in (at_cmd("AT+QGPS?") or b""): - print("stop location tracking ...") - at_cmd("AT+QGPSEND") - - if b'+QGPSCFG: "outport",usbnmea' not in (at_cmd('AT+QGPSCFG="outport"') or b""): - print("configure outport ...") - at_cmd('AT+QGPSCFG="outport","usbnmea"') # usbnmea = /dev/ttyUSB1 - - if b'+QGPSCFG: "gnssrawdata",3,0' not in (at_cmd('AT+QGPSCFG="gnssrawdata"') or b""): - print("configure gnssrawdata ...") - # AT+QGPSCFG="gnssrawdata",,' - # values: - # 0x01 = GPS - # 0x02 = GLONASS - # 0x04 = BEIDOU - # 0x08 = GALILEO - # 0x10 = QZSS - # values: - # 0 = NMEA port - # 1 = AT port - at_cmd('AT+QGPSCFG="gnssrawdata",3,0') # enable all constellations, output data to NMEA port - print("rebooting ...") - at_cmd('AT+CFUN=1,1') - print("re-run this script when it is back up") - sys.exit(2) - - print("starting location tracking ...") - at_cmd("AT+QGPS=1") - - process_nmea_port_messages() - -if __name__ == "__main__": - main() diff --git a/system/qcomgpsd/tests/test_qcomgpsd.py b/system/qcomgpsd/tests/test_qcomgpsd.py deleted file mode 100644 index 2fc6205ea4..0000000000 --- a/system/qcomgpsd/tests/test_qcomgpsd.py +++ /dev/null @@ -1,119 +0,0 @@ -import os -import pytest -import json -import time -import datetime -import subprocess - -import cereal.messaging as messaging -from openpilot.system.qcomgpsd.qcomgpsd import at_cmd, wait_for_modem -from openpilot.system.manager.process_config import managed_processes - -GOOD_SIGNAL = bool(int(os.getenv("GOOD_SIGNAL", '0'))) - - -@pytest.mark.tici -class TestRawgpsd: - @classmethod - def setup_class(cls): - os.environ['GPS_COLD_START'] = '1' - os.system("sudo systemctl start systemd-resolved") - os.system("sudo systemctl restart ModemManager lte") - wait_for_modem() - - @classmethod - def teardown_class(cls): - managed_processes['qcomgpsd'].stop() - os.system("sudo systemctl restart systemd-resolved") - os.system("sudo systemctl restart ModemManager lte") - - def setup_method(self): - self.sm = messaging.SubMaster(['qcomGnss', 'gpsLocation', 'gnssMeasurements']) - - def teardown_method(self): - managed_processes['qcomgpsd'].stop() - os.system("sudo systemctl restart systemd-resolved") - - def _wait_for_output(self, t): - dt = 0.1 - for _ in range(t*int(1/dt)): - self.sm.update(0) - if self.sm.updated['qcomGnss']: - break - time.sleep(dt) - return self.sm.updated['qcomGnss'] - - def test_no_crash_double_command(self): - at_cmd("AT+QGPSDEL=0") - at_cmd("AT+QGPSDEL=0") - - def test_wait_for_modem(self): - os.system("sudo systemctl stop ModemManager") - managed_processes['qcomgpsd'].start() - assert not self._wait_for_output(5) - - os.system("sudo systemctl restart ModemManager") - assert self._wait_for_output(30) - - def test_startup_time(self, subtests): - for internet in (True, False): - if not internet: - os.system("sudo systemctl stop systemd-resolved") - with subtests.test(internet=internet): - managed_processes['qcomgpsd'].start() - assert self._wait_for_output(7) - managed_processes['qcomgpsd'].stop() - - def test_turns_off_gnss(self, subtests): - for s in (0.1, 1, 5): - with subtests.test(runtime=s): - managed_processes['qcomgpsd'].start() - time.sleep(s) - managed_processes['qcomgpsd'].stop() - - ls = subprocess.check_output("mmcli -m any --location-status --output-json", shell=True, encoding='utf-8') - loc_status = json.loads(ls) - assert set(loc_status['modem']['location']['enabled']) <= {'3gpp-lac-ci'} - - - def check_assistance(self, should_be_loaded): - # after QGPSDEL: '+QGPSXTRADATA: 0,"1980/01/05,19:00:00"' - # after loading: '+QGPSXTRADATA: 10080,"2023/06/24,19:00:00"' - out = at_cmd("AT+QGPSXTRADATA?") - out = out.split("+QGPSXTRADATA:")[1].split("'")[0].strip() - valid_duration, injected_time_str = out.split(",", 1) - if should_be_loaded: - assert valid_duration == "10080" # should be max time - injected_time = datetime.datetime.strptime(injected_time_str.replace("\"", ""), "%Y/%m/%d,%H:%M:%S") - assert abs((datetime.datetime.now(datetime.UTC).replace(tzinfo=None) - injected_time).total_seconds()) < 60*60*12 - else: - valid_duration, injected_time_str = out.split(",", 1) - injected_time_str = injected_time_str.replace('\"', '').replace('\'', '') - assert injected_time_str[:] == '1980/01/05,19:00:00'[:] - assert valid_duration == '0' - - def test_assistance_loading(self): - managed_processes['qcomgpsd'].start() - assert self._wait_for_output(10) - managed_processes['qcomgpsd'].stop() - self.check_assistance(True) - - def test_no_assistance_loading(self): - os.system("sudo systemctl stop systemd-resolved") - - managed_processes['qcomgpsd'].start() - assert self._wait_for_output(10) - managed_processes['qcomgpsd'].stop() - self.check_assistance(False) - - def test_late_assistance_loading(self): - os.system("sudo systemctl stop systemd-resolved") - - managed_processes['qcomgpsd'].start() - self._wait_for_output(17) - assert self.sm.updated['qcomGnss'] - - os.system("sudo systemctl restart systemd-resolved") - time.sleep(15) - managed_processes['qcomgpsd'].stop() - self.check_assistance(True) diff --git a/system/sensord/sensors/mmc5603nj_magn.py b/system/sensord/sensors/mmc5603nj_magn.py deleted file mode 100644 index 255e99eb3e..0000000000 --- a/system/sensord/sensors/mmc5603nj_magn.py +++ /dev/null @@ -1,76 +0,0 @@ -import time - -from cereal import log -from openpilot.system.sensord.sensors.i2c_sensor import Sensor - -# https://www.mouser.com/datasheet/2/821/Memsic_09102019_Datasheet_Rev.B-1635324.pdf - -# Register addresses -REG_ODR = 0x1A -REG_INTERNAL_0 = 0x1B -REG_INTERNAL_1 = 0x1C - -# Control register settings -CMM_FREQ_EN = (1 << 7) -AUTO_SR_EN = (1 << 5) -SET = (1 << 3) -RESET = (1 << 4) - -class MMC5603NJ_Magn(Sensor): - @property - def device_address(self) -> int: - return 0x30 - - def init(self): - self.verify_chip_id(0x39, [0x10, ]) - self.writes(( - (REG_ODR, 0), - - # Set BW to 0b01 for 1-150 Hz operation - (REG_INTERNAL_1, 0b01), - )) - - def _read_data(self, cycle) -> list[float]: - # start measurement - self.write(REG_INTERNAL_0, cycle) - self.wait() - - # read out XYZ - scale = 1.0 / 16384.0 - b = self.read(0x00, 9) - return [ - (self.parse_20bit(b[6], b[1], b[0]) * scale) - 32.0, - (self.parse_20bit(b[7], b[3], b[2]) * scale) - 32.0, - (self.parse_20bit(b[8], b[5], b[4]) * scale) - 32.0, - ] - - def get_event(self, ts: int | None = None) -> log.SensorEventData: - ts = time.monotonic_ns() - - # SET - RESET cycle - xyz = self._read_data(SET) - reset_xyz = self._read_data(RESET) - vals = [*xyz, *reset_xyz] - - event = log.SensorEventData.new_message() - event.timestamp = ts - event.version = 1 - event.sensor = 3 # SENSOR_MAGNETOMETER_UNCALIBRATED - event.type = 14 # SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED - event.source = log.SensorEventData.SensorSource.mmc5603nj - - m = event.init('magneticUncalibrated') - m.v = vals - m.status = int(all(int(v) != -32 for v in vals)) - - return event - - def shutdown(self) -> None: - v = self.read(REG_INTERNAL_0, 1)[0] - self.writes(( - # disable auto-reset of measurements - (REG_INTERNAL_0, (v & (~(CMM_FREQ_EN | AUTO_SR_EN)))), - - # disable continuous mode - (REG_ODR, 0), - )) diff --git a/system/sensord/tests/test_sensord.py b/system/sensord/tests/test_sensord.py deleted file mode 100644 index 1dab652386..0000000000 --- a/system/sensord/tests/test_sensord.py +++ /dev/null @@ -1,232 +0,0 @@ -import os -import pytest -import time -import numpy as np -from collections import namedtuple, defaultdict - -import cereal.messaging as messaging -from cereal import log -from cereal.services import SERVICE_LIST -from openpilot.common.gpio import get_irqs_for_action -from openpilot.common.timeout import Timeout -from openpilot.system.hardware import HARDWARE -from openpilot.system.manager.process_config import managed_processes - -LSM = { - ('lsm6ds3', 'acceleration'), - ('lsm6ds3', 'gyroUncalibrated'), - ('lsm6ds3', 'temperature'), -} -LSM_C = {(x[0]+'trc', x[1]) for x in LSM} - -MMC = { - ('mmc5603nj', 'magneticUncalibrated'), -} - -SENSOR_CONFIGURATIONS: list[set] = { - "mici": [LSM, LSM_C], - "tizi": [MMC | LSM, MMC | LSM_C], - "tici": [LSM, LSM_C, MMC | LSM, MMC | LSM_C], -}.get(HARDWARE.get_device_type(), []) - -Sensor = log.SensorEventData.SensorSource -SensorConfig = namedtuple('SensorConfig', ['type', 'sanity_min', 'sanity_max']) -ALL_SENSORS = { - Sensor.lsm6ds3: { - SensorConfig("acceleration", 5, 15), - SensorConfig("gyroUncalibrated", 0, .2), - SensorConfig("temperature", 0, 60), - }, - - Sensor.lsm6ds3trc: { - SensorConfig("acceleration", 5, 15), - SensorConfig("gyroUncalibrated", 0, .2), - SensorConfig("temperature", 0, 60), - }, - - Sensor.mmc5603nj: { - SensorConfig("magneticUncalibrated", 0, 300), - } -} - - -def get_irq_count(irq: int): - with open(f"/sys/kernel/irq/{irq}/per_cpu_count") as f: - per_cpu = map(int, f.read().split(",")) - return sum(per_cpu) - -def read_sensor_events(duration_sec): - sensor_types = ['accelerometer', 'gyroscope', 'magnetometer', 'accelerometer2', - 'gyroscope2', 'temperatureSensor', 'temperatureSensor2'] - socks = {} - poller = messaging.Poller() - events = defaultdict(list) - for stype in sensor_types: - socks[stype] = messaging.sub_sock(stype, poller=poller, timeout=100) - - # wait for sensors to come up - with Timeout(int(os.environ.get("SENSOR_WAIT", "5")), "sensors didn't come up"): - while len(poller.poll(250)) == 0: - pass - time.sleep(1) - for s in socks.values(): - messaging.drain_sock_raw(s) - - st = time.monotonic() - while time.monotonic() - st < duration_sec: - for s in socks: - events[s] += messaging.drain_sock(socks[s]) - time.sleep(0.1) - - assert sum(map(len, events.values())) != 0, "No sensor events collected!" - - return {k: v for k, v in events.items() if len(v) > 0} - -@pytest.mark.tici -class TestSensord: - @classmethod - def setup_class(cls): - # enable LSM self test - os.environ["LSM_SELF_TEST"] = "1" - - # read initial sensor values every test case can use - os.system("pkill -f \\\\./sensord") - try: - managed_processes["sensord"].start() - cls.sample_secs = int(os.getenv("SAMPLE_SECS", "10")) - cls.events = read_sensor_events(cls.sample_secs) - - # determine sensord's irq - cls.sensord_irq = get_irqs_for_action("sensord")[0] - finally: - # teardown won't run if this doesn't succeed - managed_processes["sensord"].stop() - - @classmethod - def teardown_class(cls): - managed_processes["sensord"].stop() - - def teardown_method(self): - managed_processes["sensord"].stop() - - def test_sensors_present(self): - # verify correct sensors configuration - seen = set() - for etype in self.events: - for measurement in self.events[etype]: - m = getattr(measurement, measurement.which()) - seen.add((str(m.source), m.which())) - - assert seen in SENSOR_CONFIGURATIONS - - def test_lsm6ds3_timing(self, subtests): - # verify measurements are sampled and published at 104Hz - - sensor_t = { - 1: [], # accel - 5: [], # gyro - } - - for measurement in self.events['accelerometer']: - m = getattr(measurement, measurement.which()) - sensor_t[m.sensor].append(m.timestamp) - - for measurement in self.events['gyroscope']: - m = getattr(measurement, measurement.which()) - sensor_t[m.sensor].append(m.timestamp) - - for s, vals in sensor_t.items(): - with subtests.test(sensor=s): - assert len(vals) > 0 - tdiffs = np.diff(vals) / 1e6 # millis - - high_delay_diffs = list(filter(lambda d: d >= 20., tdiffs)) - assert len(high_delay_diffs) < 15, f"Too many large diffs: {high_delay_diffs}" - - avg_diff = sum(tdiffs)/len(tdiffs) - avg_freq = 1. / (avg_diff * 1e-3) - assert 92. < avg_freq < 114., f"avg freq {avg_freq}Hz wrong, expected 104Hz" - - stddev = np.std(tdiffs) - assert stddev < 2.0, f"Standard-dev to big {stddev}" - - def test_sensor_frequency(self, subtests): - for s, msgs in self.events.items(): - with subtests.test(sensor=s): - freq = len(msgs) / self.sample_secs - ef = SERVICE_LIST[s].frequency - assert ef*0.85 <= freq <= ef*1.15 - - def test_logmonottime_timestamp_diff(self): - # ensure diff between the message logMonotime and sample timestamp is small - - tdiffs = list() - for etype in self.events: - for measurement in self.events[etype]: - m = getattr(measurement, measurement.which()) - - # check if gyro and accel timestamps are before logMonoTime - if str(m.source).startswith("lsm6ds3") and m.which() != 'temperature': - err_msg = f"Timestamp after logMonoTime: {m.timestamp} > {measurement.logMonoTime}" - assert m.timestamp < measurement.logMonoTime, err_msg - - # negative values might occur, as non interrupt packages created - # before the sensor is read - tdiffs.append(abs(measurement.logMonoTime - m.timestamp) / 1e6) - - # some sensors have a read procedure that will introduce an expected diff on the order of 20ms - high_delay_diffs = set(filter(lambda d: d >= 25., tdiffs)) - assert len(high_delay_diffs) < 20, f"Too many measurements published: {high_delay_diffs}" - - avg_diff = round(sum(tdiffs)/len(tdiffs), 4) - assert avg_diff < 4, f"Avg packet diff: {avg_diff:.1f}ms" - - def test_sensor_values(self): - sensor_values = dict() - for etype in self.events: - for measurement in self.events[etype]: - m = getattr(measurement, measurement.which()) - key = (m.source.raw, m.which()) - values = getattr(m, m.which()) - - if hasattr(values, 'v'): - values = values.v - values = np.atleast_1d(values) - - if key in sensor_values: - sensor_values[key].append(values) - else: - sensor_values[key] = [values] - - # Sanity check sensor values - for sensor, stype in sensor_values: - for s in ALL_SENSORS[sensor]: - if s.type != stype: - continue - - key = (sensor, s.type) - mean_norm = np.mean(np.linalg.norm(sensor_values[key], axis=1)) - err_msg = f"Sensor '{sensor} {s.type}' failed sanity checks {mean_norm} is not between {s.sanity_min} and {s.sanity_max}" - assert s.sanity_min <= mean_norm <= s.sanity_max, err_msg - - def test_sensor_verify_no_interrupts_after_stop(self): - managed_processes["sensord"].start() - time.sleep(3) - - # read /proc/interrupts to verify interrupts are received - state_one = get_irq_count(self.sensord_irq) - time.sleep(1) - state_two = get_irq_count(self.sensord_irq) - - error_msg = f"no interrupts received after sensord start!\n{state_one} {state_two}" - assert state_one != state_two, error_msg - - managed_processes["sensord"].stop() - time.sleep(1) - - # read /proc/interrupts to verify no more interrupts are received - state_one = get_irq_count(self.sensord_irq) - time.sleep(1) - state_two = get_irq_count(self.sensord_irq) - assert state_one == state_two, "Interrupts received after sensord stop!" - diff --git a/system/statsd.py b/system/statsd.py deleted file mode 100755 index b8a7f2c661..0000000000 --- a/system/statsd.py +++ /dev/null @@ -1,183 +0,0 @@ -#!/usr/bin/env python3 -import os -import zmq -import time -import uuid -from pathlib import Path -from collections import defaultdict -from datetime import datetime, UTC -from typing import NoReturn - -from openpilot.common.params import Params -from cereal.messaging import SubMaster -from openpilot.system.hardware.hw import Paths -from openpilot.common.swaglog import cloudlog -from openpilot.system.hardware import HARDWARE -from openpilot.common.file_helpers import atomic_write_in_dir -from openpilot.system.version import get_build_metadata -from openpilot.system.loggerd.config import STATS_DIR_FILE_LIMIT, STATS_SOCKET, STATS_FLUSH_TIME_S - - -class METRIC_TYPE: - GAUGE = 'g' - SAMPLE = 'sa' - -class StatLog: - def __init__(self): - self.pid = None - self.zctx = None - self.sock = None - - def connect(self) -> None: - self.zctx = zmq.Context() - self.sock = self.zctx.socket(zmq.PUSH) - self.sock.setsockopt(zmq.LINGER, 10) - self.sock.connect(STATS_SOCKET) - self.pid = os.getpid() - - def __del__(self): - if self.sock is not None: - self.sock.close() - if self.zctx is not None: - self.zctx.term() - - def _send(self, metric: str) -> None: - if os.getpid() != self.pid: - self.connect() - - try: - self.sock.send_string(metric, zmq.NOBLOCK) - except zmq.error.Again: - # drop :/ - pass - - def gauge(self, name: str, value: float) -> None: - self._send(f"{name}:{value}|{METRIC_TYPE.GAUGE}") - - # Samples will be recorded in a buffer and at aggregation time, - # statistical properties will be logged (mean, count, percentiles, ...) - def sample(self, name: str, value: float): - self._send(f"{name}:{value}|{METRIC_TYPE.SAMPLE}") - - -def main() -> NoReturn: - dongle_id = Params().get("DongleId", encoding='utf-8') - def get_influxdb_line(measurement: str, value: float | dict[str, float], timestamp: datetime, tags: dict) -> str: - res = f"{measurement}" - for k, v in tags.items(): - res += f",{k}={str(v)}" - res += " " - - if isinstance(value, float): - value = {'value': value} - - for k, v in value.items(): - res += f"{k}={v}," - - res += f"dongle_id=\"{dongle_id}\" {int(timestamp.timestamp() * 1e9)}\n" - return res - - # open statistics socket - ctx = zmq.Context.instance() - sock = ctx.socket(zmq.PULL) - sock.bind(STATS_SOCKET) - - STATS_DIR = Paths.stats_root() - - # initialize stats directory - Path(STATS_DIR).mkdir(parents=True, exist_ok=True) - - build_metadata = get_build_metadata() - - # initialize tags - tags = { - 'started': False, - 'version': build_metadata.openpilot.version, - 'branch': build_metadata.channel, - 'dirty': build_metadata.openpilot.is_dirty, - 'origin': build_metadata.openpilot.git_normalized_origin, - 'deviceType': HARDWARE.get_device_type(), - } - - # subscribe to deviceState for started state - sm = SubMaster(['deviceState']) - - idx = 0 - boot_uid = str(uuid.uuid4())[:8] - last_flush_time = time.monotonic() - gauges = {} - samples: dict[str, list[float]] = defaultdict(list) - try: - while True: - started_prev = sm['deviceState'].started - sm.update() - - # Update metrics - while True: - try: - metric = sock.recv_string(zmq.NOBLOCK) - try: - metric_type = metric.split('|')[1] - metric_name = metric.split(':')[0] - metric_value = float(metric.split('|')[0].split(':')[1]) - - if metric_type == METRIC_TYPE.GAUGE: - gauges[metric_name] = metric_value - elif metric_type == METRIC_TYPE.SAMPLE: - samples[metric_name].append(metric_value) - else: - cloudlog.event("unknown metric type", metric_type=metric_type) - except Exception: - cloudlog.event("malformed metric", metric=metric) - except zmq.error.Again: - break - - # flush when started state changes or after FLUSH_TIME_S - if (time.monotonic() > last_flush_time + STATS_FLUSH_TIME_S) or (sm['deviceState'].started != started_prev): - result = "" - current_time = datetime.now(UTC) - tags['started'] = sm['deviceState'].started - - for key, value in gauges.items(): - result += get_influxdb_line(f"gauge.{key}", value, current_time, tags) - - for key, values in samples.items(): - values.sort() - sample_count = len(values) - sample_sum = sum(values) - - stats = { - 'count': sample_count, - 'min': values[0], - 'max': values[-1], - 'mean': sample_sum / sample_count, - } - for percentile in [0.05, 0.5, 0.95]: - value = values[int(round(percentile * (sample_count - 1)))] - stats[f"p{int(percentile * 100)}"] = value - - result += get_influxdb_line(f"sample.{key}", stats, current_time, tags) - - # clear intermediate data - gauges.clear() - samples.clear() - last_flush_time = time.monotonic() - - # check that we aren't filling up the drive - if len(os.listdir(STATS_DIR)) < STATS_DIR_FILE_LIMIT: - if len(result) > 0: - stats_path = os.path.join(STATS_DIR, f"{boot_uid}_{idx}") - with atomic_write_in_dir(stats_path) as f: - f.write(result) - idx += 1 - else: - cloudlog.error("stats dir full") - finally: - sock.close() - ctx.term() - - -if __name__ == "__main__": - main() -else: - statlog = StatLog() diff --git a/system/ubloxd/.gitignore b/system/ubloxd/.gitignore deleted file mode 100644 index 05263ff67c..0000000000 --- a/system/ubloxd/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -ubloxd -tests/test_glonass_runner diff --git a/system/ubloxd/SConscript b/system/ubloxd/SConscript deleted file mode 100644 index ce09e235e6..0000000000 --- a/system/ubloxd/SConscript +++ /dev/null @@ -1,20 +0,0 @@ -Import('env', 'common', 'messaging') - -loc_libs = [messaging, common, 'kaitai', 'pthread'] - -if GetOption('kaitai'): - generated = Dir('generated').srcnode().abspath - cmd = f"kaitai-struct-compiler --target cpp_stl --outdir {generated} $SOURCES" - env.Command(['generated/ubx.cpp', 'generated/ubx.h'], 'ubx.ksy', cmd) - env.Command(['generated/gps.cpp', 'generated/gps.h'], 'gps.ksy', cmd) - glonass = env.Command(['generated/glonass.cpp', 'generated/glonass.h'], 'glonass.ksy', cmd) - - # kaitai issue: https://github.com/kaitai-io/kaitai_struct/issues/910 - patch = env.Command(None, 'glonass_fix.patch', 'git apply $SOURCES') - env.Depends(patch, glonass) - -glonass_obj = env.Object('generated/glonass.cpp') -env.Program("ubloxd", ["ubloxd.cc", "ublox_msg.cc", "generated/ubx.cpp", "generated/gps.cpp", glonass_obj], LIBS=loc_libs) - -if GetOption('extras'): - env.Program("tests/test_glonass_runner", ['tests/test_glonass_runner.cc', 'tests/test_glonass_kaitai.cc', glonass_obj], LIBS=[loc_libs]) \ No newline at end of file diff --git a/system/ubloxd/generated/glonass.cpp b/system/ubloxd/generated/glonass.cpp deleted file mode 100644 index cd0f96ab68..0000000000 --- a/system/ubloxd/generated/glonass.cpp +++ /dev/null @@ -1,353 +0,0 @@ -// This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild - -#include "glonass.h" - -glonass_t::glonass_t(kaitai::kstream* p__io, kaitai::kstruct* p__parent, glonass_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = this; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void glonass_t::_read() { - m_idle_chip = m__io->read_bits_int_be(1); - m_string_number = m__io->read_bits_int_be(4); - //m__io->align_to_byte(); - switch (string_number()) { - case 4: { - m_data = new string_4_t(m__io, this, m__root); - break; - } - case 1: { - m_data = new string_1_t(m__io, this, m__root); - break; - } - case 3: { - m_data = new string_3_t(m__io, this, m__root); - break; - } - case 5: { - m_data = new string_5_t(m__io, this, m__root); - break; - } - case 2: { - m_data = new string_2_t(m__io, this, m__root); - break; - } - default: { - m_data = new string_non_immediate_t(m__io, this, m__root); - break; - } - } - m_hamming_code = m__io->read_bits_int_be(8); - m_pad_1 = m__io->read_bits_int_be(11); - m_superframe_number = m__io->read_bits_int_be(16); - m_pad_2 = m__io->read_bits_int_be(8); - m_frame_number = m__io->read_bits_int_be(8); -} - -glonass_t::~glonass_t() { - _clean_up(); -} - -void glonass_t::_clean_up() { - if (m_data) { - delete m_data; m_data = 0; - } -} - -glonass_t::string_4_t::string_4_t(kaitai::kstream* p__io, glonass_t* p__parent, glonass_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - f_tau_n = false; - f_delta_tau_n = false; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void glonass_t::string_4_t::_read() { - m_tau_n_sign = m__io->read_bits_int_be(1); - m_tau_n_value = m__io->read_bits_int_be(21); - m_delta_tau_n_sign = m__io->read_bits_int_be(1); - m_delta_tau_n_value = m__io->read_bits_int_be(4); - m_e_n = m__io->read_bits_int_be(5); - m_not_used_1 = m__io->read_bits_int_be(14); - m_p4 = m__io->read_bits_int_be(1); - m_f_t = m__io->read_bits_int_be(4); - m_not_used_2 = m__io->read_bits_int_be(3); - m_n_t = m__io->read_bits_int_be(11); - m_n = m__io->read_bits_int_be(5); - m_m = m__io->read_bits_int_be(2); -} - -glonass_t::string_4_t::~string_4_t() { - _clean_up(); -} - -void glonass_t::string_4_t::_clean_up() { -} - -int32_t glonass_t::string_4_t::tau_n() { - if (f_tau_n) - return m_tau_n; - m_tau_n = ((tau_n_sign()) ? ((tau_n_value() * -1)) : (tau_n_value())); - f_tau_n = true; - return m_tau_n; -} - -int32_t glonass_t::string_4_t::delta_tau_n() { - if (f_delta_tau_n) - return m_delta_tau_n; - m_delta_tau_n = ((delta_tau_n_sign()) ? ((delta_tau_n_value() * -1)) : (delta_tau_n_value())); - f_delta_tau_n = true; - return m_delta_tau_n; -} - -glonass_t::string_non_immediate_t::string_non_immediate_t(kaitai::kstream* p__io, glonass_t* p__parent, glonass_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void glonass_t::string_non_immediate_t::_read() { - m_data_1 = m__io->read_bits_int_be(64); - m_data_2 = m__io->read_bits_int_be(8); -} - -glonass_t::string_non_immediate_t::~string_non_immediate_t() { - _clean_up(); -} - -void glonass_t::string_non_immediate_t::_clean_up() { -} - -glonass_t::string_5_t::string_5_t(kaitai::kstream* p__io, glonass_t* p__parent, glonass_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void glonass_t::string_5_t::_read() { - m_n_a = m__io->read_bits_int_be(11); - m_tau_c = m__io->read_bits_int_be(32); - m_not_used = m__io->read_bits_int_be(1); - m_n_4 = m__io->read_bits_int_be(5); - m_tau_gps = m__io->read_bits_int_be(22); - m_l_n = m__io->read_bits_int_be(1); -} - -glonass_t::string_5_t::~string_5_t() { - _clean_up(); -} - -void glonass_t::string_5_t::_clean_up() { -} - -glonass_t::string_1_t::string_1_t(kaitai::kstream* p__io, glonass_t* p__parent, glonass_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - f_x_vel = false; - f_x_accel = false; - f_x = false; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void glonass_t::string_1_t::_read() { - m_not_used = m__io->read_bits_int_be(2); - m_p1 = m__io->read_bits_int_be(2); - m_t_k = m__io->read_bits_int_be(12); - m_x_vel_sign = m__io->read_bits_int_be(1); - m_x_vel_value = m__io->read_bits_int_be(23); - m_x_accel_sign = m__io->read_bits_int_be(1); - m_x_accel_value = m__io->read_bits_int_be(4); - m_x_sign = m__io->read_bits_int_be(1); - m_x_value = m__io->read_bits_int_be(26); -} - -glonass_t::string_1_t::~string_1_t() { - _clean_up(); -} - -void glonass_t::string_1_t::_clean_up() { -} - -int32_t glonass_t::string_1_t::x_vel() { - if (f_x_vel) - return m_x_vel; - m_x_vel = ((x_vel_sign()) ? ((x_vel_value() * -1)) : (x_vel_value())); - f_x_vel = true; - return m_x_vel; -} - -int32_t glonass_t::string_1_t::x_accel() { - if (f_x_accel) - return m_x_accel; - m_x_accel = ((x_accel_sign()) ? ((x_accel_value() * -1)) : (x_accel_value())); - f_x_accel = true; - return m_x_accel; -} - -int32_t glonass_t::string_1_t::x() { - if (f_x) - return m_x; - m_x = ((x_sign()) ? ((x_value() * -1)) : (x_value())); - f_x = true; - return m_x; -} - -glonass_t::string_2_t::string_2_t(kaitai::kstream* p__io, glonass_t* p__parent, glonass_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - f_y_vel = false; - f_y_accel = false; - f_y = false; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void glonass_t::string_2_t::_read() { - m_b_n = m__io->read_bits_int_be(3); - m_p2 = m__io->read_bits_int_be(1); - m_t_b = m__io->read_bits_int_be(7); - m_not_used = m__io->read_bits_int_be(5); - m_y_vel_sign = m__io->read_bits_int_be(1); - m_y_vel_value = m__io->read_bits_int_be(23); - m_y_accel_sign = m__io->read_bits_int_be(1); - m_y_accel_value = m__io->read_bits_int_be(4); - m_y_sign = m__io->read_bits_int_be(1); - m_y_value = m__io->read_bits_int_be(26); -} - -glonass_t::string_2_t::~string_2_t() { - _clean_up(); -} - -void glonass_t::string_2_t::_clean_up() { -} - -int32_t glonass_t::string_2_t::y_vel() { - if (f_y_vel) - return m_y_vel; - m_y_vel = ((y_vel_sign()) ? ((y_vel_value() * -1)) : (y_vel_value())); - f_y_vel = true; - return m_y_vel; -} - -int32_t glonass_t::string_2_t::y_accel() { - if (f_y_accel) - return m_y_accel; - m_y_accel = ((y_accel_sign()) ? ((y_accel_value() * -1)) : (y_accel_value())); - f_y_accel = true; - return m_y_accel; -} - -int32_t glonass_t::string_2_t::y() { - if (f_y) - return m_y; - m_y = ((y_sign()) ? ((y_value() * -1)) : (y_value())); - f_y = true; - return m_y; -} - -glonass_t::string_3_t::string_3_t(kaitai::kstream* p__io, glonass_t* p__parent, glonass_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - f_gamma_n = false; - f_z_vel = false; - f_z_accel = false; - f_z = false; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void glonass_t::string_3_t::_read() { - m_p3 = m__io->read_bits_int_be(1); - m_gamma_n_sign = m__io->read_bits_int_be(1); - m_gamma_n_value = m__io->read_bits_int_be(10); - m_not_used = m__io->read_bits_int_be(1); - m_p = m__io->read_bits_int_be(2); - m_l_n = m__io->read_bits_int_be(1); - m_z_vel_sign = m__io->read_bits_int_be(1); - m_z_vel_value = m__io->read_bits_int_be(23); - m_z_accel_sign = m__io->read_bits_int_be(1); - m_z_accel_value = m__io->read_bits_int_be(4); - m_z_sign = m__io->read_bits_int_be(1); - m_z_value = m__io->read_bits_int_be(26); -} - -glonass_t::string_3_t::~string_3_t() { - _clean_up(); -} - -void glonass_t::string_3_t::_clean_up() { -} - -int32_t glonass_t::string_3_t::gamma_n() { - if (f_gamma_n) - return m_gamma_n; - m_gamma_n = ((gamma_n_sign()) ? ((gamma_n_value() * -1)) : (gamma_n_value())); - f_gamma_n = true; - return m_gamma_n; -} - -int32_t glonass_t::string_3_t::z_vel() { - if (f_z_vel) - return m_z_vel; - m_z_vel = ((z_vel_sign()) ? ((z_vel_value() * -1)) : (z_vel_value())); - f_z_vel = true; - return m_z_vel; -} - -int32_t glonass_t::string_3_t::z_accel() { - if (f_z_accel) - return m_z_accel; - m_z_accel = ((z_accel_sign()) ? ((z_accel_value() * -1)) : (z_accel_value())); - f_z_accel = true; - return m_z_accel; -} - -int32_t glonass_t::string_3_t::z() { - if (f_z) - return m_z; - m_z = ((z_sign()) ? ((z_value() * -1)) : (z_value())); - f_z = true; - return m_z; -} diff --git a/system/ubloxd/generated/glonass.h b/system/ubloxd/generated/glonass.h deleted file mode 100644 index 19867ba22b..0000000000 --- a/system/ubloxd/generated/glonass.h +++ /dev/null @@ -1,375 +0,0 @@ -#ifndef GLONASS_H_ -#define GLONASS_H_ - -// This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild - -#include "kaitai/kaitaistruct.h" -#include - -#if KAITAI_STRUCT_VERSION < 9000L -#error "Incompatible Kaitai Struct C++/STL API: version 0.9 or later is required" -#endif - -class glonass_t : public kaitai::kstruct { - -public: - class string_4_t; - class string_non_immediate_t; - class string_5_t; - class string_1_t; - class string_2_t; - class string_3_t; - - glonass_t(kaitai::kstream* p__io, kaitai::kstruct* p__parent = 0, glonass_t* p__root = 0); - -private: - void _read(); - void _clean_up(); - -public: - ~glonass_t(); - - class string_4_t : public kaitai::kstruct { - - public: - - string_4_t(kaitai::kstream* p__io, glonass_t* p__parent = 0, glonass_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~string_4_t(); - - private: - bool f_tau_n; - int32_t m_tau_n; - - public: - int32_t tau_n(); - - private: - bool f_delta_tau_n; - int32_t m_delta_tau_n; - - public: - int32_t delta_tau_n(); - - private: - bool m_tau_n_sign; - uint64_t m_tau_n_value; - bool m_delta_tau_n_sign; - uint64_t m_delta_tau_n_value; - uint64_t m_e_n; - uint64_t m_not_used_1; - bool m_p4; - uint64_t m_f_t; - uint64_t m_not_used_2; - uint64_t m_n_t; - uint64_t m_n; - uint64_t m_m; - glonass_t* m__root; - glonass_t* m__parent; - - public: - bool tau_n_sign() const { return m_tau_n_sign; } - uint64_t tau_n_value() const { return m_tau_n_value; } - bool delta_tau_n_sign() const { return m_delta_tau_n_sign; } - uint64_t delta_tau_n_value() const { return m_delta_tau_n_value; } - uint64_t e_n() const { return m_e_n; } - uint64_t not_used_1() const { return m_not_used_1; } - bool p4() const { return m_p4; } - uint64_t f_t() const { return m_f_t; } - uint64_t not_used_2() const { return m_not_used_2; } - uint64_t n_t() const { return m_n_t; } - uint64_t n() const { return m_n; } - uint64_t m() const { return m_m; } - glonass_t* _root() const { return m__root; } - glonass_t* _parent() const { return m__parent; } - }; - - class string_non_immediate_t : public kaitai::kstruct { - - public: - - string_non_immediate_t(kaitai::kstream* p__io, glonass_t* p__parent = 0, glonass_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~string_non_immediate_t(); - - private: - uint64_t m_data_1; - uint64_t m_data_2; - glonass_t* m__root; - glonass_t* m__parent; - - public: - uint64_t data_1() const { return m_data_1; } - uint64_t data_2() const { return m_data_2; } - glonass_t* _root() const { return m__root; } - glonass_t* _parent() const { return m__parent; } - }; - - class string_5_t : public kaitai::kstruct { - - public: - - string_5_t(kaitai::kstream* p__io, glonass_t* p__parent = 0, glonass_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~string_5_t(); - - private: - uint64_t m_n_a; - uint64_t m_tau_c; - bool m_not_used; - uint64_t m_n_4; - uint64_t m_tau_gps; - bool m_l_n; - glonass_t* m__root; - glonass_t* m__parent; - - public: - uint64_t n_a() const { return m_n_a; } - uint64_t tau_c() const { return m_tau_c; } - bool not_used() const { return m_not_used; } - uint64_t n_4() const { return m_n_4; } - uint64_t tau_gps() const { return m_tau_gps; } - bool l_n() const { return m_l_n; } - glonass_t* _root() const { return m__root; } - glonass_t* _parent() const { return m__parent; } - }; - - class string_1_t : public kaitai::kstruct { - - public: - - string_1_t(kaitai::kstream* p__io, glonass_t* p__parent = 0, glonass_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~string_1_t(); - - private: - bool f_x_vel; - int32_t m_x_vel; - - public: - int32_t x_vel(); - - private: - bool f_x_accel; - int32_t m_x_accel; - - public: - int32_t x_accel(); - - private: - bool f_x; - int32_t m_x; - - public: - int32_t x(); - - private: - uint64_t m_not_used; - uint64_t m_p1; - uint64_t m_t_k; - bool m_x_vel_sign; - uint64_t m_x_vel_value; - bool m_x_accel_sign; - uint64_t m_x_accel_value; - bool m_x_sign; - uint64_t m_x_value; - glonass_t* m__root; - glonass_t* m__parent; - - public: - uint64_t not_used() const { return m_not_used; } - uint64_t p1() const { return m_p1; } - uint64_t t_k() const { return m_t_k; } - bool x_vel_sign() const { return m_x_vel_sign; } - uint64_t x_vel_value() const { return m_x_vel_value; } - bool x_accel_sign() const { return m_x_accel_sign; } - uint64_t x_accel_value() const { return m_x_accel_value; } - bool x_sign() const { return m_x_sign; } - uint64_t x_value() const { return m_x_value; } - glonass_t* _root() const { return m__root; } - glonass_t* _parent() const { return m__parent; } - }; - - class string_2_t : public kaitai::kstruct { - - public: - - string_2_t(kaitai::kstream* p__io, glonass_t* p__parent = 0, glonass_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~string_2_t(); - - private: - bool f_y_vel; - int32_t m_y_vel; - - public: - int32_t y_vel(); - - private: - bool f_y_accel; - int32_t m_y_accel; - - public: - int32_t y_accel(); - - private: - bool f_y; - int32_t m_y; - - public: - int32_t y(); - - private: - uint64_t m_b_n; - bool m_p2; - uint64_t m_t_b; - uint64_t m_not_used; - bool m_y_vel_sign; - uint64_t m_y_vel_value; - bool m_y_accel_sign; - uint64_t m_y_accel_value; - bool m_y_sign; - uint64_t m_y_value; - glonass_t* m__root; - glonass_t* m__parent; - - public: - uint64_t b_n() const { return m_b_n; } - bool p2() const { return m_p2; } - uint64_t t_b() const { return m_t_b; } - uint64_t not_used() const { return m_not_used; } - bool y_vel_sign() const { return m_y_vel_sign; } - uint64_t y_vel_value() const { return m_y_vel_value; } - bool y_accel_sign() const { return m_y_accel_sign; } - uint64_t y_accel_value() const { return m_y_accel_value; } - bool y_sign() const { return m_y_sign; } - uint64_t y_value() const { return m_y_value; } - glonass_t* _root() const { return m__root; } - glonass_t* _parent() const { return m__parent; } - }; - - class string_3_t : public kaitai::kstruct { - - public: - - string_3_t(kaitai::kstream* p__io, glonass_t* p__parent = 0, glonass_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~string_3_t(); - - private: - bool f_gamma_n; - int32_t m_gamma_n; - - public: - int32_t gamma_n(); - - private: - bool f_z_vel; - int32_t m_z_vel; - - public: - int32_t z_vel(); - - private: - bool f_z_accel; - int32_t m_z_accel; - - public: - int32_t z_accel(); - - private: - bool f_z; - int32_t m_z; - - public: - int32_t z(); - - private: - bool m_p3; - bool m_gamma_n_sign; - uint64_t m_gamma_n_value; - bool m_not_used; - uint64_t m_p; - bool m_l_n; - bool m_z_vel_sign; - uint64_t m_z_vel_value; - bool m_z_accel_sign; - uint64_t m_z_accel_value; - bool m_z_sign; - uint64_t m_z_value; - glonass_t* m__root; - glonass_t* m__parent; - - public: - bool p3() const { return m_p3; } - bool gamma_n_sign() const { return m_gamma_n_sign; } - uint64_t gamma_n_value() const { return m_gamma_n_value; } - bool not_used() const { return m_not_used; } - uint64_t p() const { return m_p; } - bool l_n() const { return m_l_n; } - bool z_vel_sign() const { return m_z_vel_sign; } - uint64_t z_vel_value() const { return m_z_vel_value; } - bool z_accel_sign() const { return m_z_accel_sign; } - uint64_t z_accel_value() const { return m_z_accel_value; } - bool z_sign() const { return m_z_sign; } - uint64_t z_value() const { return m_z_value; } - glonass_t* _root() const { return m__root; } - glonass_t* _parent() const { return m__parent; } - }; - -private: - bool m_idle_chip; - uint64_t m_string_number; - kaitai::kstruct* m_data; - uint64_t m_hamming_code; - uint64_t m_pad_1; - uint64_t m_superframe_number; - uint64_t m_pad_2; - uint64_t m_frame_number; - glonass_t* m__root; - kaitai::kstruct* m__parent; - -public: - bool idle_chip() const { return m_idle_chip; } - uint64_t string_number() const { return m_string_number; } - kaitai::kstruct* data() const { return m_data; } - uint64_t hamming_code() const { return m_hamming_code; } - uint64_t pad_1() const { return m_pad_1; } - uint64_t superframe_number() const { return m_superframe_number; } - uint64_t pad_2() const { return m_pad_2; } - uint64_t frame_number() const { return m_frame_number; } - glonass_t* _root() const { return m__root; } - kaitai::kstruct* _parent() const { return m__parent; } -}; - -#endif // GLONASS_H_ diff --git a/system/ubloxd/generated/gps.cpp b/system/ubloxd/generated/gps.cpp deleted file mode 100644 index 8e1cb85b95..0000000000 --- a/system/ubloxd/generated/gps.cpp +++ /dev/null @@ -1,325 +0,0 @@ -// This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild - -#include "gps.h" -#include "kaitai/exceptions.h" - -gps_t::gps_t(kaitai::kstream* p__io, kaitai::kstruct* p__parent, gps_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = this; - m_tlm = 0; - m_how = 0; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void gps_t::_read() { - m_tlm = new tlm_t(m__io, this, m__root); - m_how = new how_t(m__io, this, m__root); - n_body = true; - switch (how()->subframe_id()) { - case 1: { - n_body = false; - m_body = new subframe_1_t(m__io, this, m__root); - break; - } - case 2: { - n_body = false; - m_body = new subframe_2_t(m__io, this, m__root); - break; - } - case 3: { - n_body = false; - m_body = new subframe_3_t(m__io, this, m__root); - break; - } - case 4: { - n_body = false; - m_body = new subframe_4_t(m__io, this, m__root); - break; - } - } -} - -gps_t::~gps_t() { - _clean_up(); -} - -void gps_t::_clean_up() { - if (m_tlm) { - delete m_tlm; m_tlm = 0; - } - if (m_how) { - delete m_how; m_how = 0; - } - if (!n_body) { - if (m_body) { - delete m_body; m_body = 0; - } - } -} - -gps_t::subframe_1_t::subframe_1_t(kaitai::kstream* p__io, gps_t* p__parent, gps_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - f_af_0 = false; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void gps_t::subframe_1_t::_read() { - m_week_no = m__io->read_bits_int_be(10); - m_code = m__io->read_bits_int_be(2); - m_sv_accuracy = m__io->read_bits_int_be(4); - m_sv_health = m__io->read_bits_int_be(6); - m_iodc_msb = m__io->read_bits_int_be(2); - m_l2_p_data_flag = m__io->read_bits_int_be(1); - m_reserved1 = m__io->read_bits_int_be(23); - m_reserved2 = m__io->read_bits_int_be(24); - m_reserved3 = m__io->read_bits_int_be(24); - m_reserved4 = m__io->read_bits_int_be(16); - m__io->align_to_byte(); - m_t_gd = m__io->read_s1(); - m_iodc_lsb = m__io->read_u1(); - m_t_oc = m__io->read_u2be(); - m_af_2 = m__io->read_s1(); - m_af_1 = m__io->read_s2be(); - m_af_0_sign = m__io->read_bits_int_be(1); - m_af_0_value = m__io->read_bits_int_be(21); - m_reserved5 = m__io->read_bits_int_be(2); -} - -gps_t::subframe_1_t::~subframe_1_t() { - _clean_up(); -} - -void gps_t::subframe_1_t::_clean_up() { -} - -int32_t gps_t::subframe_1_t::af_0() { - if (f_af_0) - return m_af_0; - m_af_0 = ((af_0_sign()) ? ((af_0_value() - (1 << 21))) : (af_0_value())); - f_af_0 = true; - return m_af_0; -} - -gps_t::subframe_3_t::subframe_3_t(kaitai::kstream* p__io, gps_t* p__parent, gps_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - f_omega_dot = false; - f_idot = false; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void gps_t::subframe_3_t::_read() { - m_c_ic = m__io->read_s2be(); - m_omega_0 = m__io->read_s4be(); - m_c_is = m__io->read_s2be(); - m_i_0 = m__io->read_s4be(); - m_c_rc = m__io->read_s2be(); - m_omega = m__io->read_s4be(); - m_omega_dot_sign = m__io->read_bits_int_be(1); - m_omega_dot_value = m__io->read_bits_int_be(23); - m__io->align_to_byte(); - m_iode = m__io->read_u1(); - m_idot_sign = m__io->read_bits_int_be(1); - m_idot_value = m__io->read_bits_int_be(13); - m_reserved = m__io->read_bits_int_be(2); -} - -gps_t::subframe_3_t::~subframe_3_t() { - _clean_up(); -} - -void gps_t::subframe_3_t::_clean_up() { -} - -int32_t gps_t::subframe_3_t::omega_dot() { - if (f_omega_dot) - return m_omega_dot; - m_omega_dot = ((omega_dot_sign()) ? ((omega_dot_value() - (1 << 23))) : (omega_dot_value())); - f_omega_dot = true; - return m_omega_dot; -} - -int32_t gps_t::subframe_3_t::idot() { - if (f_idot) - return m_idot; - m_idot = ((idot_sign()) ? ((idot_value() - (1 << 13))) : (idot_value())); - f_idot = true; - return m_idot; -} - -gps_t::subframe_4_t::subframe_4_t(kaitai::kstream* p__io, gps_t* p__parent, gps_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void gps_t::subframe_4_t::_read() { - m_data_id = m__io->read_bits_int_be(2); - m_page_id = m__io->read_bits_int_be(6); - m__io->align_to_byte(); - n_body = true; - switch (page_id()) { - case 56: { - n_body = false; - m_body = new ionosphere_data_t(m__io, this, m__root); - break; - } - } -} - -gps_t::subframe_4_t::~subframe_4_t() { - _clean_up(); -} - -void gps_t::subframe_4_t::_clean_up() { - if (!n_body) { - if (m_body) { - delete m_body; m_body = 0; - } - } -} - -gps_t::subframe_4_t::ionosphere_data_t::ionosphere_data_t(kaitai::kstream* p__io, gps_t::subframe_4_t* p__parent, gps_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void gps_t::subframe_4_t::ionosphere_data_t::_read() { - m_a0 = m__io->read_s1(); - m_a1 = m__io->read_s1(); - m_a2 = m__io->read_s1(); - m_a3 = m__io->read_s1(); - m_b0 = m__io->read_s1(); - m_b1 = m__io->read_s1(); - m_b2 = m__io->read_s1(); - m_b3 = m__io->read_s1(); -} - -gps_t::subframe_4_t::ionosphere_data_t::~ionosphere_data_t() { - _clean_up(); -} - -void gps_t::subframe_4_t::ionosphere_data_t::_clean_up() { -} - -gps_t::how_t::how_t(kaitai::kstream* p__io, gps_t* p__parent, gps_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void gps_t::how_t::_read() { - m_tow_count = m__io->read_bits_int_be(17); - m_alert = m__io->read_bits_int_be(1); - m_anti_spoof = m__io->read_bits_int_be(1); - m_subframe_id = m__io->read_bits_int_be(3); - m_reserved = m__io->read_bits_int_be(2); -} - -gps_t::how_t::~how_t() { - _clean_up(); -} - -void gps_t::how_t::_clean_up() { -} - -gps_t::tlm_t::tlm_t(kaitai::kstream* p__io, gps_t* p__parent, gps_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void gps_t::tlm_t::_read() { - m_preamble = m__io->read_bytes(1); - if (!(preamble() == std::string("\x8B", 1))) { - throw kaitai::validation_not_equal_error(std::string("\x8B", 1), preamble(), _io(), std::string("/types/tlm/seq/0")); - } - m_tlm = m__io->read_bits_int_be(14); - m_integrity_status = m__io->read_bits_int_be(1); - m_reserved = m__io->read_bits_int_be(1); -} - -gps_t::tlm_t::~tlm_t() { - _clean_up(); -} - -void gps_t::tlm_t::_clean_up() { -} - -gps_t::subframe_2_t::subframe_2_t(kaitai::kstream* p__io, gps_t* p__parent, gps_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void gps_t::subframe_2_t::_read() { - m_iode = m__io->read_u1(); - m_c_rs = m__io->read_s2be(); - m_delta_n = m__io->read_s2be(); - m_m_0 = m__io->read_s4be(); - m_c_uc = m__io->read_s2be(); - m_e = m__io->read_s4be(); - m_c_us = m__io->read_s2be(); - m_sqrt_a = m__io->read_u4be(); - m_t_oe = m__io->read_u2be(); - m_fit_interval_flag = m__io->read_bits_int_be(1); - m_aoda = m__io->read_bits_int_be(5); - m_reserved = m__io->read_bits_int_be(2); -} - -gps_t::subframe_2_t::~subframe_2_t() { - _clean_up(); -} - -void gps_t::subframe_2_t::_clean_up() { -} diff --git a/system/ubloxd/generated/gps.h b/system/ubloxd/generated/gps.h deleted file mode 100644 index 9dfc5031f5..0000000000 --- a/system/ubloxd/generated/gps.h +++ /dev/null @@ -1,359 +0,0 @@ -#ifndef GPS_H_ -#define GPS_H_ - -// This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild - -#include "kaitai/kaitaistruct.h" -#include - -#if KAITAI_STRUCT_VERSION < 9000L -#error "Incompatible Kaitai Struct C++/STL API: version 0.9 or later is required" -#endif - -class gps_t : public kaitai::kstruct { - -public: - class subframe_1_t; - class subframe_3_t; - class subframe_4_t; - class how_t; - class tlm_t; - class subframe_2_t; - - gps_t(kaitai::kstream* p__io, kaitai::kstruct* p__parent = 0, gps_t* p__root = 0); - -private: - void _read(); - void _clean_up(); - -public: - ~gps_t(); - - class subframe_1_t : public kaitai::kstruct { - - public: - - subframe_1_t(kaitai::kstream* p__io, gps_t* p__parent = 0, gps_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~subframe_1_t(); - - private: - bool f_af_0; - int32_t m_af_0; - - public: - int32_t af_0(); - - private: - uint64_t m_week_no; - uint64_t m_code; - uint64_t m_sv_accuracy; - uint64_t m_sv_health; - uint64_t m_iodc_msb; - bool m_l2_p_data_flag; - uint64_t m_reserved1; - uint64_t m_reserved2; - uint64_t m_reserved3; - uint64_t m_reserved4; - int8_t m_t_gd; - uint8_t m_iodc_lsb; - uint16_t m_t_oc; - int8_t m_af_2; - int16_t m_af_1; - bool m_af_0_sign; - uint64_t m_af_0_value; - uint64_t m_reserved5; - gps_t* m__root; - gps_t* m__parent; - - public: - uint64_t week_no() const { return m_week_no; } - uint64_t code() const { return m_code; } - uint64_t sv_accuracy() const { return m_sv_accuracy; } - uint64_t sv_health() const { return m_sv_health; } - uint64_t iodc_msb() const { return m_iodc_msb; } - bool l2_p_data_flag() const { return m_l2_p_data_flag; } - uint64_t reserved1() const { return m_reserved1; } - uint64_t reserved2() const { return m_reserved2; } - uint64_t reserved3() const { return m_reserved3; } - uint64_t reserved4() const { return m_reserved4; } - int8_t t_gd() const { return m_t_gd; } - uint8_t iodc_lsb() const { return m_iodc_lsb; } - uint16_t t_oc() const { return m_t_oc; } - int8_t af_2() const { return m_af_2; } - int16_t af_1() const { return m_af_1; } - bool af_0_sign() const { return m_af_0_sign; } - uint64_t af_0_value() const { return m_af_0_value; } - uint64_t reserved5() const { return m_reserved5; } - gps_t* _root() const { return m__root; } - gps_t* _parent() const { return m__parent; } - }; - - class subframe_3_t : public kaitai::kstruct { - - public: - - subframe_3_t(kaitai::kstream* p__io, gps_t* p__parent = 0, gps_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~subframe_3_t(); - - private: - bool f_omega_dot; - int32_t m_omega_dot; - - public: - int32_t omega_dot(); - - private: - bool f_idot; - int32_t m_idot; - - public: - int32_t idot(); - - private: - int16_t m_c_ic; - int32_t m_omega_0; - int16_t m_c_is; - int32_t m_i_0; - int16_t m_c_rc; - int32_t m_omega; - bool m_omega_dot_sign; - uint64_t m_omega_dot_value; - uint8_t m_iode; - bool m_idot_sign; - uint64_t m_idot_value; - uint64_t m_reserved; - gps_t* m__root; - gps_t* m__parent; - - public: - int16_t c_ic() const { return m_c_ic; } - int32_t omega_0() const { return m_omega_0; } - int16_t c_is() const { return m_c_is; } - int32_t i_0() const { return m_i_0; } - int16_t c_rc() const { return m_c_rc; } - int32_t omega() const { return m_omega; } - bool omega_dot_sign() const { return m_omega_dot_sign; } - uint64_t omega_dot_value() const { return m_omega_dot_value; } - uint8_t iode() const { return m_iode; } - bool idot_sign() const { return m_idot_sign; } - uint64_t idot_value() const { return m_idot_value; } - uint64_t reserved() const { return m_reserved; } - gps_t* _root() const { return m__root; } - gps_t* _parent() const { return m__parent; } - }; - - class subframe_4_t : public kaitai::kstruct { - - public: - class ionosphere_data_t; - - subframe_4_t(kaitai::kstream* p__io, gps_t* p__parent = 0, gps_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~subframe_4_t(); - - class ionosphere_data_t : public kaitai::kstruct { - - public: - - ionosphere_data_t(kaitai::kstream* p__io, gps_t::subframe_4_t* p__parent = 0, gps_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~ionosphere_data_t(); - - private: - int8_t m_a0; - int8_t m_a1; - int8_t m_a2; - int8_t m_a3; - int8_t m_b0; - int8_t m_b1; - int8_t m_b2; - int8_t m_b3; - gps_t* m__root; - gps_t::subframe_4_t* m__parent; - - public: - int8_t a0() const { return m_a0; } - int8_t a1() const { return m_a1; } - int8_t a2() const { return m_a2; } - int8_t a3() const { return m_a3; } - int8_t b0() const { return m_b0; } - int8_t b1() const { return m_b1; } - int8_t b2() const { return m_b2; } - int8_t b3() const { return m_b3; } - gps_t* _root() const { return m__root; } - gps_t::subframe_4_t* _parent() const { return m__parent; } - }; - - private: - uint64_t m_data_id; - uint64_t m_page_id; - ionosphere_data_t* m_body; - bool n_body; - - public: - bool _is_null_body() { body(); return n_body; }; - - private: - gps_t* m__root; - gps_t* m__parent; - - public: - uint64_t data_id() const { return m_data_id; } - uint64_t page_id() const { return m_page_id; } - ionosphere_data_t* body() const { return m_body; } - gps_t* _root() const { return m__root; } - gps_t* _parent() const { return m__parent; } - }; - - class how_t : public kaitai::kstruct { - - public: - - how_t(kaitai::kstream* p__io, gps_t* p__parent = 0, gps_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~how_t(); - - private: - uint64_t m_tow_count; - bool m_alert; - bool m_anti_spoof; - uint64_t m_subframe_id; - uint64_t m_reserved; - gps_t* m__root; - gps_t* m__parent; - - public: - uint64_t tow_count() const { return m_tow_count; } - bool alert() const { return m_alert; } - bool anti_spoof() const { return m_anti_spoof; } - uint64_t subframe_id() const { return m_subframe_id; } - uint64_t reserved() const { return m_reserved; } - gps_t* _root() const { return m__root; } - gps_t* _parent() const { return m__parent; } - }; - - class tlm_t : public kaitai::kstruct { - - public: - - tlm_t(kaitai::kstream* p__io, gps_t* p__parent = 0, gps_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~tlm_t(); - - private: - std::string m_preamble; - uint64_t m_tlm; - bool m_integrity_status; - bool m_reserved; - gps_t* m__root; - gps_t* m__parent; - - public: - std::string preamble() const { return m_preamble; } - uint64_t tlm() const { return m_tlm; } - bool integrity_status() const { return m_integrity_status; } - bool reserved() const { return m_reserved; } - gps_t* _root() const { return m__root; } - gps_t* _parent() const { return m__parent; } - }; - - class subframe_2_t : public kaitai::kstruct { - - public: - - subframe_2_t(kaitai::kstream* p__io, gps_t* p__parent = 0, gps_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~subframe_2_t(); - - private: - uint8_t m_iode; - int16_t m_c_rs; - int16_t m_delta_n; - int32_t m_m_0; - int16_t m_c_uc; - int32_t m_e; - int16_t m_c_us; - uint32_t m_sqrt_a; - uint16_t m_t_oe; - bool m_fit_interval_flag; - uint64_t m_aoda; - uint64_t m_reserved; - gps_t* m__root; - gps_t* m__parent; - - public: - uint8_t iode() const { return m_iode; } - int16_t c_rs() const { return m_c_rs; } - int16_t delta_n() const { return m_delta_n; } - int32_t m_0() const { return m_m_0; } - int16_t c_uc() const { return m_c_uc; } - int32_t e() const { return m_e; } - int16_t c_us() const { return m_c_us; } - uint32_t sqrt_a() const { return m_sqrt_a; } - uint16_t t_oe() const { return m_t_oe; } - bool fit_interval_flag() const { return m_fit_interval_flag; } - uint64_t aoda() const { return m_aoda; } - uint64_t reserved() const { return m_reserved; } - gps_t* _root() const { return m__root; } - gps_t* _parent() const { return m__parent; } - }; - -private: - tlm_t* m_tlm; - how_t* m_how; - kaitai::kstruct* m_body; - bool n_body; - -public: - bool _is_null_body() { body(); return n_body; }; - -private: - gps_t* m__root; - kaitai::kstruct* m__parent; - -public: - tlm_t* tlm() const { return m_tlm; } - how_t* how() const { return m_how; } - kaitai::kstruct* body() const { return m_body; } - gps_t* _root() const { return m__root; } - kaitai::kstruct* _parent() const { return m__parent; } -}; - -#endif // GPS_H_ diff --git a/system/ubloxd/generated/ubx.cpp b/system/ubloxd/generated/ubx.cpp deleted file mode 100644 index 81b82ccafc..0000000000 --- a/system/ubloxd/generated/ubx.cpp +++ /dev/null @@ -1,424 +0,0 @@ -// This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild - -#include "ubx.h" -#include "kaitai/exceptions.h" - -ubx_t::ubx_t(kaitai::kstream* p__io, kaitai::kstruct* p__parent, ubx_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = this; - f_checksum = false; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void ubx_t::_read() { - m_magic = m__io->read_bytes(2); - if (!(magic() == std::string("\xB5\x62", 2))) { - throw kaitai::validation_not_equal_error(std::string("\xB5\x62", 2), magic(), _io(), std::string("/seq/0")); - } - m_msg_type = m__io->read_u2be(); - m_length = m__io->read_u2le(); - n_body = true; - switch (msg_type()) { - case 2569: { - n_body = false; - m_body = new mon_hw_t(m__io, this, m__root); - break; - } - case 533: { - n_body = false; - m_body = new rxm_rawx_t(m__io, this, m__root); - break; - } - case 531: { - n_body = false; - m_body = new rxm_sfrbx_t(m__io, this, m__root); - break; - } - case 309: { - n_body = false; - m_body = new nav_sat_t(m__io, this, m__root); - break; - } - case 2571: { - n_body = false; - m_body = new mon_hw2_t(m__io, this, m__root); - break; - } - case 263: { - n_body = false; - m_body = new nav_pvt_t(m__io, this, m__root); - break; - } - } -} - -ubx_t::~ubx_t() { - _clean_up(); -} - -void ubx_t::_clean_up() { - if (!n_body) { - if (m_body) { - delete m_body; m_body = 0; - } - } - if (f_checksum) { - } -} - -ubx_t::rxm_rawx_t::rxm_rawx_t(kaitai::kstream* p__io, ubx_t* p__parent, ubx_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - m_meas = 0; - m__raw_meas = 0; - m__io__raw_meas = 0; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void ubx_t::rxm_rawx_t::_read() { - m_rcv_tow = m__io->read_f8le(); - m_week = m__io->read_u2le(); - m_leap_s = m__io->read_s1(); - m_num_meas = m__io->read_u1(); - m_rec_stat = m__io->read_u1(); - m_reserved1 = m__io->read_bytes(3); - m__raw_meas = new std::vector(); - m__io__raw_meas = new std::vector(); - m_meas = new std::vector(); - const int l_meas = num_meas(); - for (int i = 0; i < l_meas; i++) { - m__raw_meas->push_back(m__io->read_bytes(32)); - kaitai::kstream* io__raw_meas = new kaitai::kstream(m__raw_meas->at(m__raw_meas->size() - 1)); - m__io__raw_meas->push_back(io__raw_meas); - m_meas->push_back(new measurement_t(io__raw_meas, this, m__root)); - } -} - -ubx_t::rxm_rawx_t::~rxm_rawx_t() { - _clean_up(); -} - -void ubx_t::rxm_rawx_t::_clean_up() { - if (m__raw_meas) { - delete m__raw_meas; m__raw_meas = 0; - } - if (m__io__raw_meas) { - for (std::vector::iterator it = m__io__raw_meas->begin(); it != m__io__raw_meas->end(); ++it) { - delete *it; - } - delete m__io__raw_meas; m__io__raw_meas = 0; - } - if (m_meas) { - for (std::vector::iterator it = m_meas->begin(); it != m_meas->end(); ++it) { - delete *it; - } - delete m_meas; m_meas = 0; - } -} - -ubx_t::rxm_rawx_t::measurement_t::measurement_t(kaitai::kstream* p__io, ubx_t::rxm_rawx_t* p__parent, ubx_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void ubx_t::rxm_rawx_t::measurement_t::_read() { - m_pr_mes = m__io->read_f8le(); - m_cp_mes = m__io->read_f8le(); - m_do_mes = m__io->read_f4le(); - m_gnss_id = static_cast(m__io->read_u1()); - m_sv_id = m__io->read_u1(); - m_reserved2 = m__io->read_bytes(1); - m_freq_id = m__io->read_u1(); - m_lock_time = m__io->read_u2le(); - m_cno = m__io->read_u1(); - m_pr_stdev = m__io->read_u1(); - m_cp_stdev = m__io->read_u1(); - m_do_stdev = m__io->read_u1(); - m_trk_stat = m__io->read_u1(); - m_reserved3 = m__io->read_bytes(1); -} - -ubx_t::rxm_rawx_t::measurement_t::~measurement_t() { - _clean_up(); -} - -void ubx_t::rxm_rawx_t::measurement_t::_clean_up() { -} - -ubx_t::rxm_sfrbx_t::rxm_sfrbx_t(kaitai::kstream* p__io, ubx_t* p__parent, ubx_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - m_body = 0; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void ubx_t::rxm_sfrbx_t::_read() { - m_gnss_id = static_cast(m__io->read_u1()); - m_sv_id = m__io->read_u1(); - m_reserved1 = m__io->read_bytes(1); - m_freq_id = m__io->read_u1(); - m_num_words = m__io->read_u1(); - m_reserved2 = m__io->read_bytes(1); - m_version = m__io->read_u1(); - m_reserved3 = m__io->read_bytes(1); - m_body = new std::vector(); - const int l_body = num_words(); - for (int i = 0; i < l_body; i++) { - m_body->push_back(m__io->read_u4le()); - } -} - -ubx_t::rxm_sfrbx_t::~rxm_sfrbx_t() { - _clean_up(); -} - -void ubx_t::rxm_sfrbx_t::_clean_up() { - if (m_body) { - delete m_body; m_body = 0; - } -} - -ubx_t::nav_sat_t::nav_sat_t(kaitai::kstream* p__io, ubx_t* p__parent, ubx_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - m_svs = 0; - m__raw_svs = 0; - m__io__raw_svs = 0; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void ubx_t::nav_sat_t::_read() { - m_itow = m__io->read_u4le(); - m_version = m__io->read_u1(); - m_num_svs = m__io->read_u1(); - m_reserved = m__io->read_bytes(2); - m__raw_svs = new std::vector(); - m__io__raw_svs = new std::vector(); - m_svs = new std::vector(); - const int l_svs = num_svs(); - for (int i = 0; i < l_svs; i++) { - m__raw_svs->push_back(m__io->read_bytes(12)); - kaitai::kstream* io__raw_svs = new kaitai::kstream(m__raw_svs->at(m__raw_svs->size() - 1)); - m__io__raw_svs->push_back(io__raw_svs); - m_svs->push_back(new nav_t(io__raw_svs, this, m__root)); - } -} - -ubx_t::nav_sat_t::~nav_sat_t() { - _clean_up(); -} - -void ubx_t::nav_sat_t::_clean_up() { - if (m__raw_svs) { - delete m__raw_svs; m__raw_svs = 0; - } - if (m__io__raw_svs) { - for (std::vector::iterator it = m__io__raw_svs->begin(); it != m__io__raw_svs->end(); ++it) { - delete *it; - } - delete m__io__raw_svs; m__io__raw_svs = 0; - } - if (m_svs) { - for (std::vector::iterator it = m_svs->begin(); it != m_svs->end(); ++it) { - delete *it; - } - delete m_svs; m_svs = 0; - } -} - -ubx_t::nav_sat_t::nav_t::nav_t(kaitai::kstream* p__io, ubx_t::nav_sat_t* p__parent, ubx_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void ubx_t::nav_sat_t::nav_t::_read() { - m_gnss_id = static_cast(m__io->read_u1()); - m_sv_id = m__io->read_u1(); - m_cno = m__io->read_u1(); - m_elev = m__io->read_s1(); - m_azim = m__io->read_s2le(); - m_pr_res = m__io->read_s2le(); - m_flags = m__io->read_u4le(); -} - -ubx_t::nav_sat_t::nav_t::~nav_t() { - _clean_up(); -} - -void ubx_t::nav_sat_t::nav_t::_clean_up() { -} - -ubx_t::nav_pvt_t::nav_pvt_t(kaitai::kstream* p__io, ubx_t* p__parent, ubx_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void ubx_t::nav_pvt_t::_read() { - m_i_tow = m__io->read_u4le(); - m_year = m__io->read_u2le(); - m_month = m__io->read_u1(); - m_day = m__io->read_u1(); - m_hour = m__io->read_u1(); - m_min = m__io->read_u1(); - m_sec = m__io->read_u1(); - m_valid = m__io->read_u1(); - m_t_acc = m__io->read_u4le(); - m_nano = m__io->read_s4le(); - m_fix_type = m__io->read_u1(); - m_flags = m__io->read_u1(); - m_flags2 = m__io->read_u1(); - m_num_sv = m__io->read_u1(); - m_lon = m__io->read_s4le(); - m_lat = m__io->read_s4le(); - m_height = m__io->read_s4le(); - m_h_msl = m__io->read_s4le(); - m_h_acc = m__io->read_u4le(); - m_v_acc = m__io->read_u4le(); - m_vel_n = m__io->read_s4le(); - m_vel_e = m__io->read_s4le(); - m_vel_d = m__io->read_s4le(); - m_g_speed = m__io->read_s4le(); - m_head_mot = m__io->read_s4le(); - m_s_acc = m__io->read_s4le(); - m_head_acc = m__io->read_u4le(); - m_p_dop = m__io->read_u2le(); - m_flags3 = m__io->read_u1(); - m_reserved1 = m__io->read_bytes(5); - m_head_veh = m__io->read_s4le(); - m_mag_dec = m__io->read_s2le(); - m_mag_acc = m__io->read_u2le(); -} - -ubx_t::nav_pvt_t::~nav_pvt_t() { - _clean_up(); -} - -void ubx_t::nav_pvt_t::_clean_up() { -} - -ubx_t::mon_hw2_t::mon_hw2_t(kaitai::kstream* p__io, ubx_t* p__parent, ubx_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void ubx_t::mon_hw2_t::_read() { - m_ofs_i = m__io->read_s1(); - m_mag_i = m__io->read_u1(); - m_ofs_q = m__io->read_s1(); - m_mag_q = m__io->read_u1(); - m_cfg_source = static_cast(m__io->read_u1()); - m_reserved1 = m__io->read_bytes(3); - m_low_lev_cfg = m__io->read_u4le(); - m_reserved2 = m__io->read_bytes(8); - m_post_status = m__io->read_u4le(); - m_reserved3 = m__io->read_bytes(4); -} - -ubx_t::mon_hw2_t::~mon_hw2_t() { - _clean_up(); -} - -void ubx_t::mon_hw2_t::_clean_up() { -} - -ubx_t::mon_hw_t::mon_hw_t(kaitai::kstream* p__io, ubx_t* p__parent, ubx_t* p__root) : kaitai::kstruct(p__io) { - m__parent = p__parent; - m__root = p__root; - - try { - _read(); - } catch(...) { - _clean_up(); - throw; - } -} - -void ubx_t::mon_hw_t::_read() { - m_pin_sel = m__io->read_u4le(); - m_pin_bank = m__io->read_u4le(); - m_pin_dir = m__io->read_u4le(); - m_pin_val = m__io->read_u4le(); - m_noise_per_ms = m__io->read_u2le(); - m_agc_cnt = m__io->read_u2le(); - m_a_status = static_cast(m__io->read_u1()); - m_a_power = static_cast(m__io->read_u1()); - m_flags = m__io->read_u1(); - m_reserved1 = m__io->read_bytes(1); - m_used_mask = m__io->read_u4le(); - m_vp = m__io->read_bytes(17); - m_jam_ind = m__io->read_u1(); - m_reserved2 = m__io->read_bytes(2); - m_pin_irq = m__io->read_u4le(); - m_pull_h = m__io->read_u4le(); - m_pull_l = m__io->read_u4le(); -} - -ubx_t::mon_hw_t::~mon_hw_t() { - _clean_up(); -} - -void ubx_t::mon_hw_t::_clean_up() { -} - -uint16_t ubx_t::checksum() { - if (f_checksum) - return m_checksum; - std::streampos _pos = m__io->pos(); - m__io->seek((length() + 6)); - m_checksum = m__io->read_u2le(); - m__io->seek(_pos); - f_checksum = true; - return m_checksum; -} diff --git a/system/ubloxd/generated/ubx.h b/system/ubloxd/generated/ubx.h deleted file mode 100644 index 022108489f..0000000000 --- a/system/ubloxd/generated/ubx.h +++ /dev/null @@ -1,484 +0,0 @@ -#ifndef UBX_H_ -#define UBX_H_ - -// This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild - -#include "kaitai/kaitaistruct.h" -#include -#include - -#if KAITAI_STRUCT_VERSION < 9000L -#error "Incompatible Kaitai Struct C++/STL API: version 0.9 or later is required" -#endif - -class ubx_t : public kaitai::kstruct { - -public: - class rxm_rawx_t; - class rxm_sfrbx_t; - class nav_sat_t; - class nav_pvt_t; - class mon_hw2_t; - class mon_hw_t; - - enum gnss_type_t { - GNSS_TYPE_GPS = 0, - GNSS_TYPE_SBAS = 1, - GNSS_TYPE_GALILEO = 2, - GNSS_TYPE_BEIDOU = 3, - GNSS_TYPE_IMES = 4, - GNSS_TYPE_QZSS = 5, - GNSS_TYPE_GLONASS = 6 - }; - - ubx_t(kaitai::kstream* p__io, kaitai::kstruct* p__parent = 0, ubx_t* p__root = 0); - -private: - void _read(); - void _clean_up(); - -public: - ~ubx_t(); - - class rxm_rawx_t : public kaitai::kstruct { - - public: - class measurement_t; - - rxm_rawx_t(kaitai::kstream* p__io, ubx_t* p__parent = 0, ubx_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~rxm_rawx_t(); - - class measurement_t : public kaitai::kstruct { - - public: - - measurement_t(kaitai::kstream* p__io, ubx_t::rxm_rawx_t* p__parent = 0, ubx_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~measurement_t(); - - private: - double m_pr_mes; - double m_cp_mes; - float m_do_mes; - gnss_type_t m_gnss_id; - uint8_t m_sv_id; - std::string m_reserved2; - uint8_t m_freq_id; - uint16_t m_lock_time; - uint8_t m_cno; - uint8_t m_pr_stdev; - uint8_t m_cp_stdev; - uint8_t m_do_stdev; - uint8_t m_trk_stat; - std::string m_reserved3; - ubx_t* m__root; - ubx_t::rxm_rawx_t* m__parent; - - public: - double pr_mes() const { return m_pr_mes; } - double cp_mes() const { return m_cp_mes; } - float do_mes() const { return m_do_mes; } - gnss_type_t gnss_id() const { return m_gnss_id; } - uint8_t sv_id() const { return m_sv_id; } - std::string reserved2() const { return m_reserved2; } - uint8_t freq_id() const { return m_freq_id; } - uint16_t lock_time() const { return m_lock_time; } - uint8_t cno() const { return m_cno; } - uint8_t pr_stdev() const { return m_pr_stdev; } - uint8_t cp_stdev() const { return m_cp_stdev; } - uint8_t do_stdev() const { return m_do_stdev; } - uint8_t trk_stat() const { return m_trk_stat; } - std::string reserved3() const { return m_reserved3; } - ubx_t* _root() const { return m__root; } - ubx_t::rxm_rawx_t* _parent() const { return m__parent; } - }; - - private: - double m_rcv_tow; - uint16_t m_week; - int8_t m_leap_s; - uint8_t m_num_meas; - uint8_t m_rec_stat; - std::string m_reserved1; - std::vector* m_meas; - ubx_t* m__root; - ubx_t* m__parent; - std::vector* m__raw_meas; - std::vector* m__io__raw_meas; - - public: - double rcv_tow() const { return m_rcv_tow; } - uint16_t week() const { return m_week; } - int8_t leap_s() const { return m_leap_s; } - uint8_t num_meas() const { return m_num_meas; } - uint8_t rec_stat() const { return m_rec_stat; } - std::string reserved1() const { return m_reserved1; } - std::vector* meas() const { return m_meas; } - ubx_t* _root() const { return m__root; } - ubx_t* _parent() const { return m__parent; } - std::vector* _raw_meas() const { return m__raw_meas; } - std::vector* _io__raw_meas() const { return m__io__raw_meas; } - }; - - class rxm_sfrbx_t : public kaitai::kstruct { - - public: - - rxm_sfrbx_t(kaitai::kstream* p__io, ubx_t* p__parent = 0, ubx_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~rxm_sfrbx_t(); - - private: - gnss_type_t m_gnss_id; - uint8_t m_sv_id; - std::string m_reserved1; - uint8_t m_freq_id; - uint8_t m_num_words; - std::string m_reserved2; - uint8_t m_version; - std::string m_reserved3; - std::vector* m_body; - ubx_t* m__root; - ubx_t* m__parent; - - public: - gnss_type_t gnss_id() const { return m_gnss_id; } - uint8_t sv_id() const { return m_sv_id; } - std::string reserved1() const { return m_reserved1; } - uint8_t freq_id() const { return m_freq_id; } - uint8_t num_words() const { return m_num_words; } - std::string reserved2() const { return m_reserved2; } - uint8_t version() const { return m_version; } - std::string reserved3() const { return m_reserved3; } - std::vector* body() const { return m_body; } - ubx_t* _root() const { return m__root; } - ubx_t* _parent() const { return m__parent; } - }; - - class nav_sat_t : public kaitai::kstruct { - - public: - class nav_t; - - nav_sat_t(kaitai::kstream* p__io, ubx_t* p__parent = 0, ubx_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~nav_sat_t(); - - class nav_t : public kaitai::kstruct { - - public: - - nav_t(kaitai::kstream* p__io, ubx_t::nav_sat_t* p__parent = 0, ubx_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~nav_t(); - - private: - gnss_type_t m_gnss_id; - uint8_t m_sv_id; - uint8_t m_cno; - int8_t m_elev; - int16_t m_azim; - int16_t m_pr_res; - uint32_t m_flags; - ubx_t* m__root; - ubx_t::nav_sat_t* m__parent; - - public: - gnss_type_t gnss_id() const { return m_gnss_id; } - uint8_t sv_id() const { return m_sv_id; } - uint8_t cno() const { return m_cno; } - int8_t elev() const { return m_elev; } - int16_t azim() const { return m_azim; } - int16_t pr_res() const { return m_pr_res; } - uint32_t flags() const { return m_flags; } - ubx_t* _root() const { return m__root; } - ubx_t::nav_sat_t* _parent() const { return m__parent; } - }; - - private: - uint32_t m_itow; - uint8_t m_version; - uint8_t m_num_svs; - std::string m_reserved; - std::vector* m_svs; - ubx_t* m__root; - ubx_t* m__parent; - std::vector* m__raw_svs; - std::vector* m__io__raw_svs; - - public: - uint32_t itow() const { return m_itow; } - uint8_t version() const { return m_version; } - uint8_t num_svs() const { return m_num_svs; } - std::string reserved() const { return m_reserved; } - std::vector* svs() const { return m_svs; } - ubx_t* _root() const { return m__root; } - ubx_t* _parent() const { return m__parent; } - std::vector* _raw_svs() const { return m__raw_svs; } - std::vector* _io__raw_svs() const { return m__io__raw_svs; } - }; - - class nav_pvt_t : public kaitai::kstruct { - - public: - - nav_pvt_t(kaitai::kstream* p__io, ubx_t* p__parent = 0, ubx_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~nav_pvt_t(); - - private: - uint32_t m_i_tow; - uint16_t m_year; - uint8_t m_month; - uint8_t m_day; - uint8_t m_hour; - uint8_t m_min; - uint8_t m_sec; - uint8_t m_valid; - uint32_t m_t_acc; - int32_t m_nano; - uint8_t m_fix_type; - uint8_t m_flags; - uint8_t m_flags2; - uint8_t m_num_sv; - int32_t m_lon; - int32_t m_lat; - int32_t m_height; - int32_t m_h_msl; - uint32_t m_h_acc; - uint32_t m_v_acc; - int32_t m_vel_n; - int32_t m_vel_e; - int32_t m_vel_d; - int32_t m_g_speed; - int32_t m_head_mot; - int32_t m_s_acc; - uint32_t m_head_acc; - uint16_t m_p_dop; - uint8_t m_flags3; - std::string m_reserved1; - int32_t m_head_veh; - int16_t m_mag_dec; - uint16_t m_mag_acc; - ubx_t* m__root; - ubx_t* m__parent; - - public: - uint32_t i_tow() const { return m_i_tow; } - uint16_t year() const { return m_year; } - uint8_t month() const { return m_month; } - uint8_t day() const { return m_day; } - uint8_t hour() const { return m_hour; } - uint8_t min() const { return m_min; } - uint8_t sec() const { return m_sec; } - uint8_t valid() const { return m_valid; } - uint32_t t_acc() const { return m_t_acc; } - int32_t nano() const { return m_nano; } - uint8_t fix_type() const { return m_fix_type; } - uint8_t flags() const { return m_flags; } - uint8_t flags2() const { return m_flags2; } - uint8_t num_sv() const { return m_num_sv; } - int32_t lon() const { return m_lon; } - int32_t lat() const { return m_lat; } - int32_t height() const { return m_height; } - int32_t h_msl() const { return m_h_msl; } - uint32_t h_acc() const { return m_h_acc; } - uint32_t v_acc() const { return m_v_acc; } - int32_t vel_n() const { return m_vel_n; } - int32_t vel_e() const { return m_vel_e; } - int32_t vel_d() const { return m_vel_d; } - int32_t g_speed() const { return m_g_speed; } - int32_t head_mot() const { return m_head_mot; } - int32_t s_acc() const { return m_s_acc; } - uint32_t head_acc() const { return m_head_acc; } - uint16_t p_dop() const { return m_p_dop; } - uint8_t flags3() const { return m_flags3; } - std::string reserved1() const { return m_reserved1; } - int32_t head_veh() const { return m_head_veh; } - int16_t mag_dec() const { return m_mag_dec; } - uint16_t mag_acc() const { return m_mag_acc; } - ubx_t* _root() const { return m__root; } - ubx_t* _parent() const { return m__parent; } - }; - - class mon_hw2_t : public kaitai::kstruct { - - public: - - enum config_source_t { - CONFIG_SOURCE_FLASH = 102, - CONFIG_SOURCE_OTP = 111, - CONFIG_SOURCE_CONFIG_PINS = 112, - CONFIG_SOURCE_ROM = 113 - }; - - mon_hw2_t(kaitai::kstream* p__io, ubx_t* p__parent = 0, ubx_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~mon_hw2_t(); - - private: - int8_t m_ofs_i; - uint8_t m_mag_i; - int8_t m_ofs_q; - uint8_t m_mag_q; - config_source_t m_cfg_source; - std::string m_reserved1; - uint32_t m_low_lev_cfg; - std::string m_reserved2; - uint32_t m_post_status; - std::string m_reserved3; - ubx_t* m__root; - ubx_t* m__parent; - - public: - int8_t ofs_i() const { return m_ofs_i; } - uint8_t mag_i() const { return m_mag_i; } - int8_t ofs_q() const { return m_ofs_q; } - uint8_t mag_q() const { return m_mag_q; } - config_source_t cfg_source() const { return m_cfg_source; } - std::string reserved1() const { return m_reserved1; } - uint32_t low_lev_cfg() const { return m_low_lev_cfg; } - std::string reserved2() const { return m_reserved2; } - uint32_t post_status() const { return m_post_status; } - std::string reserved3() const { return m_reserved3; } - ubx_t* _root() const { return m__root; } - ubx_t* _parent() const { return m__parent; } - }; - - class mon_hw_t : public kaitai::kstruct { - - public: - - enum antenna_status_t { - ANTENNA_STATUS_INIT = 0, - ANTENNA_STATUS_DONTKNOW = 1, - ANTENNA_STATUS_OK = 2, - ANTENNA_STATUS_SHORT = 3, - ANTENNA_STATUS_OPEN = 4 - }; - - enum antenna_power_t { - ANTENNA_POWER_FALSE = 0, - ANTENNA_POWER_TRUE = 1, - ANTENNA_POWER_DONTKNOW = 2 - }; - - mon_hw_t(kaitai::kstream* p__io, ubx_t* p__parent = 0, ubx_t* p__root = 0); - - private: - void _read(); - void _clean_up(); - - public: - ~mon_hw_t(); - - private: - uint32_t m_pin_sel; - uint32_t m_pin_bank; - uint32_t m_pin_dir; - uint32_t m_pin_val; - uint16_t m_noise_per_ms; - uint16_t m_agc_cnt; - antenna_status_t m_a_status; - antenna_power_t m_a_power; - uint8_t m_flags; - std::string m_reserved1; - uint32_t m_used_mask; - std::string m_vp; - uint8_t m_jam_ind; - std::string m_reserved2; - uint32_t m_pin_irq; - uint32_t m_pull_h; - uint32_t m_pull_l; - ubx_t* m__root; - ubx_t* m__parent; - - public: - uint32_t pin_sel() const { return m_pin_sel; } - uint32_t pin_bank() const { return m_pin_bank; } - uint32_t pin_dir() const { return m_pin_dir; } - uint32_t pin_val() const { return m_pin_val; } - uint16_t noise_per_ms() const { return m_noise_per_ms; } - uint16_t agc_cnt() const { return m_agc_cnt; } - antenna_status_t a_status() const { return m_a_status; } - antenna_power_t a_power() const { return m_a_power; } - uint8_t flags() const { return m_flags; } - std::string reserved1() const { return m_reserved1; } - uint32_t used_mask() const { return m_used_mask; } - std::string vp() const { return m_vp; } - uint8_t jam_ind() const { return m_jam_ind; } - std::string reserved2() const { return m_reserved2; } - uint32_t pin_irq() const { return m_pin_irq; } - uint32_t pull_h() const { return m_pull_h; } - uint32_t pull_l() const { return m_pull_l; } - ubx_t* _root() const { return m__root; } - ubx_t* _parent() const { return m__parent; } - }; - -private: - bool f_checksum; - uint16_t m_checksum; - -public: - uint16_t checksum(); - -private: - std::string m_magic; - uint16_t m_msg_type; - uint16_t m_length; - kaitai::kstruct* m_body; - bool n_body; - -public: - bool _is_null_body() { body(); return n_body; }; - -private: - ubx_t* m__root; - kaitai::kstruct* m__parent; - -public: - std::string magic() const { return m_magic; } - uint16_t msg_type() const { return m_msg_type; } - uint16_t length() const { return m_length; } - kaitai::kstruct* body() const { return m_body; } - ubx_t* _root() const { return m__root; } - kaitai::kstruct* _parent() const { return m__parent; } -}; - -#endif // UBX_H_ diff --git a/system/ubloxd/glonass.ksy b/system/ubloxd/glonass.ksy deleted file mode 100644 index be99f6e497..0000000000 --- a/system/ubloxd/glonass.ksy +++ /dev/null @@ -1,176 +0,0 @@ -# http://gauss.gge.unb.ca/GLONASS.ICD.pdf -# some variables are misprinted but good in the old doc -# https://www.unavco.org/help/glossary/docs/ICD_GLONASS_4.0_(1998)_en.pdf -meta: - id: glonass - endian: be - bit-endian: be -seq: - - id: idle_chip - type: b1 - - id: string_number - type: b4 - - id: data - type: - switch-on: string_number - cases: - 1: string_1 - 2: string_2 - 3: string_3 - 4: string_4 - 5: string_5 - _: string_non_immediate - - id: hamming_code - type: b8 - - id: pad_1 - type: b11 - - id: superframe_number - type: b16 - - id: pad_2 - type: b8 - - id: frame_number - type: b8 - -types: - string_1: - seq: - - id: not_used - type: b2 - - id: p1 - type: b2 - - id: t_k - type: b12 - - id: x_vel_sign - type: b1 - - id: x_vel_value - type: b23 - - id: x_accel_sign - type: b1 - - id: x_accel_value - type: b4 - - id: x_sign - type: b1 - - id: x_value - type: b26 - instances: - x_vel: - value: 'x_vel_sign ? (x_vel_value * (-1)) : x_vel_value' - x_accel: - value: 'x_accel_sign ? (x_accel_value * (-1)) : x_accel_value' - x: - value: 'x_sign ? (x_value * (-1)) : x_value' - string_2: - seq: - - id: b_n - type: b3 - - id: p2 - type: b1 - - id: t_b - type: b7 - - id: not_used - type: b5 - - id: y_vel_sign - type: b1 - - id: y_vel_value - type: b23 - - id: y_accel_sign - type: b1 - - id: y_accel_value - type: b4 - - id: y_sign - type: b1 - - id: y_value - type: b26 - instances: - y_vel: - value: 'y_vel_sign ? (y_vel_value * (-1)) : y_vel_value' - y_accel: - value: 'y_accel_sign ? (y_accel_value * (-1)) : y_accel_value' - y: - value: 'y_sign ? (y_value * (-1)) : y_value' - string_3: - seq: - - id: p3 - type: b1 - - id: gamma_n_sign - type: b1 - - id: gamma_n_value - type: b10 - - id: not_used - type: b1 - - id: p - type: b2 - - id: l_n - type: b1 - - id: z_vel_sign - type: b1 - - id: z_vel_value - type: b23 - - id: z_accel_sign - type: b1 - - id: z_accel_value - type: b4 - - id: z_sign - type: b1 - - id: z_value - type: b26 - instances: - gamma_n: - value: 'gamma_n_sign ? (gamma_n_value * (-1)) : gamma_n_value' - z_vel: - value: 'z_vel_sign ? (z_vel_value * (-1)) : z_vel_value' - z_accel: - value: 'z_accel_sign ? (z_accel_value * (-1)) : z_accel_value' - z: - value: 'z_sign ? (z_value * (-1)) : z_value' - string_4: - seq: - - id: tau_n_sign - type: b1 - - id: tau_n_value - type: b21 - - id: delta_tau_n_sign - type: b1 - - id: delta_tau_n_value - type: b4 - - id: e_n - type: b5 - - id: not_used_1 - type: b14 - - id: p4 - type: b1 - - id: f_t - type: b4 - - id: not_used_2 - type: b3 - - id: n_t - type: b11 - - id: n - type: b5 - - id: m - type: b2 - instances: - tau_n: - value: 'tau_n_sign ? (tau_n_value * (-1)) : tau_n_value' - delta_tau_n: - value: 'delta_tau_n_sign ? (delta_tau_n_value * (-1)) : delta_tau_n_value' - string_5: - seq: - - id: n_a - type: b11 - - id: tau_c - type: b32 - - id: not_used - type: b1 - - id: n_4 - type: b5 - - id: tau_gps - type: b22 - - id: l_n - type: b1 - string_non_immediate: - seq: - - id: data_1 - type: b64 - - id: data_2 - type: b8 diff --git a/system/ubloxd/glonass_fix.patch b/system/ubloxd/glonass_fix.patch deleted file mode 100644 index 7eb973a348..0000000000 --- a/system/ubloxd/glonass_fix.patch +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/system/ubloxd/generated/glonass.cpp b/system/ubloxd/generated/glonass.cpp -index 5b17bc327..b5c6aa610 100644 ---- a/system/ubloxd/generated/glonass.cpp -+++ b/system/ubloxd/generated/glonass.cpp -@@ -17,7 +17,7 @@ glonass_t::glonass_t(kaitai::kstream* p__io, kaitai::kstruct* p__parent, glonass - void glonass_t::_read() { - m_idle_chip = m__io->read_bits_int_be(1); - m_string_number = m__io->read_bits_int_be(4); -- m__io->align_to_byte(); -+ //m__io->align_to_byte(); - switch (string_number()) { - case 4: { - m_data = new string_4_t(m__io, this, m__root); diff --git a/system/ubloxd/gps.ksy b/system/ubloxd/gps.ksy deleted file mode 100644 index 893ad1b25b..0000000000 --- a/system/ubloxd/gps.ksy +++ /dev/null @@ -1,189 +0,0 @@ -# https://www.gps.gov/technical/icwg/IS-GPS-200E.pdf -meta: - id: gps - endian: be - bit-endian: be -seq: - - id: tlm - type: tlm - - id: how - type: how - - id: body - type: - switch-on: how.subframe_id - cases: - 1: subframe_1 - 2: subframe_2 - 3: subframe_3 - 4: subframe_4 -types: - tlm: - seq: - - id: preamble - contents: [0x8b] - - id: tlm - type: b14 - - id: integrity_status - type: b1 - - id: reserved - type: b1 - how: - seq: - - id: tow_count - type: b17 - - id: alert - type: b1 - - id: anti_spoof - type: b1 - - id: subframe_id - type: b3 - - id: reserved - type: b2 - subframe_1: - seq: - # Word 3 - - id: week_no - type: b10 - - id: code - type: b2 - - id: sv_accuracy - type: b4 - - id: sv_health - type: b6 - - id: iodc_msb - type: b2 - # Word 4 - - id: l2_p_data_flag - type: b1 - - id: reserved1 - type: b23 - # Word 5 - - id: reserved2 - type: b24 - # Word 6 - - id: reserved3 - type: b24 - # Word 7 - - id: reserved4 - type: b16 - - id: t_gd - type: s1 - # Word 8 - - id: iodc_lsb - type: u1 - - id: t_oc - type: u2 - # Word 9 - - id: af_2 - type: s1 - - id: af_1 - type: s2 - # Word 10 - - id: af_0_sign - type: b1 - - id: af_0_value - type: b21 - - id: reserved5 - type: b2 - instances: - af_0: - value: 'af_0_sign ? (af_0_value - (1 << 21)) : af_0_value' - subframe_2: - seq: - # Word 3 - - id: iode - type: u1 - - id: c_rs - type: s2 - # Word 4 & 5 - - id: delta_n - type: s2 - - id: m_0 - type: s4 - # Word 6 & 7 - - id: c_uc - type: s2 - - id: e - type: s4 - # Word 8 & 9 - - id: c_us - type: s2 - - id: sqrt_a - type: u4 - # Word 10 - - id: t_oe - type: u2 - - id: fit_interval_flag - type: b1 - - id: aoda - type: b5 - - id: reserved - type: b2 - subframe_3: - seq: - # Word 3 & 4 - - id: c_ic - type: s2 - - id: omega_0 - type: s4 - # Word 5 & 6 - - id: c_is - type: s2 - - id: i_0 - type: s4 - # Word 7 & 8 - - id: c_rc - type: s2 - - id: omega - type: s4 - # Word 9 - - id: omega_dot_sign - type: b1 - - id: omega_dot_value - type: b23 - # Word 10 - - id: iode - type: u1 - - id: idot_sign - type: b1 - - id: idot_value - type: b13 - - id: reserved - type: b2 - instances: - omega_dot: - value: 'omega_dot_sign ? (omega_dot_value - (1 << 23)) : omega_dot_value' - idot: - value: 'idot_sign ? (idot_value - (1 << 13)) : idot_value' - subframe_4: - seq: - # Word 3 - - id: data_id - type: b2 - - id: page_id - type: b6 - - id: body - type: - switch-on: page_id - cases: - 56: ionosphere_data - types: - ionosphere_data: - seq: - - id: a0 - type: s1 - - id: a1 - type: s1 - - id: a2 - type: s1 - - id: a3 - type: s1 - - id: b0 - type: s1 - - id: b1 - type: s1 - - id: b2 - type: s1 - - id: b3 - type: s1 - diff --git a/system/ubloxd/tests/print_gps_stats.py b/system/ubloxd/tests/print_gps_stats.py deleted file mode 100755 index 8d190f9ec1..0000000000 --- a/system/ubloxd/tests/print_gps_stats.py +++ /dev/null @@ -1,20 +0,0 @@ -#!/usr/bin/env python3 -import time -import cereal.messaging as messaging - -if __name__ == "__main__": - sm = messaging.SubMaster(['ubloxGnss', 'gpsLocationExternal']) - - while 1: - ug = sm['ubloxGnss'] - gle = sm['gpsLocationExternal'] - - try: - cnos = [] - for m in ug.measurementReport.measurements: - cnos.append(m.cno) - print(f"Sats: {ug.measurementReport.numMeas} Accuracy: {gle.horizontalAccuracy:.2f} m cnos", sorted(cnos)) - except Exception: - pass - sm.update() - time.sleep(0.1) diff --git a/system/ubloxd/tests/test_glonass_kaitai.cc b/system/ubloxd/tests/test_glonass_kaitai.cc deleted file mode 100644 index 96f43742b4..0000000000 --- a/system/ubloxd/tests/test_glonass_kaitai.cc +++ /dev/null @@ -1,360 +0,0 @@ -#include -#include -#include -#include -#include -#include - -#include "catch2/catch.hpp" -#include "system/ubloxd/generated/glonass.h" - -typedef std::vector> string_data; - -#define IDLE_CHIP_IDX 0 -#define STRING_NUMBER_IDX 1 -// string data 1-5 -#define HC_IDX 0 -#define PAD1_IDX 1 -#define SUPERFRAME_IDX 2 -#define PAD2_IDX 3 -#define FRAME_IDX 4 - -// Indexes for string number 1 -#define ST1_NU_IDX 2 -#define ST1_P1_IDX 3 -#define ST1_T_K_IDX 4 -#define ST1_X_VEL_S_IDX 5 -#define ST1_X_VEL_V_IDX 6 -#define ST1_X_ACCEL_S_IDX 7 -#define ST1_X_ACCEL_V_IDX 8 -#define ST1_X_S_IDX 9 -#define ST1_X_V_IDX 10 -#define ST1_HC_OFF 11 - -// Indexes for string number 2 -#define ST2_BN_IDX 2 -#define ST2_P2_IDX 3 -#define ST2_TB_IDX 4 -#define ST2_NU_IDX 5 -#define ST2_Y_VEL_S_IDX 6 -#define ST2_Y_VEL_V_IDX 7 -#define ST2_Y_ACCEL_S_IDX 8 -#define ST2_Y_ACCEL_V_IDX 9 -#define ST2_Y_S_IDX 10 -#define ST2_Y_V_IDX 11 -#define ST2_HC_OFF 12 - -// Indexes for string number 3 -#define ST3_P3_IDX 2 -#define ST3_GAMMA_N_S_IDX 3 -#define ST3_GAMMA_N_V_IDX 4 -#define ST3_NU_1_IDX 5 -#define ST3_P_IDX 6 -#define ST3_L_N_IDX 7 -#define ST3_Z_VEL_S_IDX 8 -#define ST3_Z_VEL_V_IDX 9 -#define ST3_Z_ACCEL_S_IDX 10 -#define ST3_Z_ACCEL_V_IDX 11 -#define ST3_Z_S_IDX 12 -#define ST3_Z_V_IDX 13 -#define ST3_HC_OFF 14 - -// Indexes for string number 4 -#define ST4_TAU_N_S_IDX 2 -#define ST4_TAU_N_V_IDX 3 -#define ST4_DELTA_TAU_N_S_IDX 4 -#define ST4_DELTA_TAU_N_V_IDX 5 -#define ST4_E_N_IDX 6 -#define ST4_NU_1_IDX 7 -#define ST4_P4_IDX 8 -#define ST4_F_T_IDX 9 -#define ST4_NU_2_IDX 10 -#define ST4_N_T_IDX 11 -#define ST4_N_IDX 12 -#define ST4_M_IDX 13 -#define ST4_HC_OFF 14 - -// Indexes for string number 5 -#define ST5_N_A_IDX 2 -#define ST5_TAU_C_IDX 3 -#define ST5_NU_IDX 4 -#define ST5_N_4_IDX 5 -#define ST5_TAU_GPS_IDX 6 -#define ST5_L_N_IDX 7 -#define ST5_HC_OFF 8 - -// Indexes for non immediate -#define ST6_DATA_1_IDX 2 -#define ST6_DATA_2_IDX 3 -#define ST6_HC_OFF 4 - - -std::string generate_inp_data(string_data& data) { - std::string inp_data = ""; - for (auto& [b, v] : data) { - std::string tmp = std::bitset<64>(v).to_string(); - inp_data += tmp.substr(64-b, b); - } - assert(inp_data.size() == 128); - - std::string string_data; - string_data.reserve(16); - for (int i = 0; i < 128; i+=8) { - std::string substr = inp_data.substr(i, 8); - string_data.push_back((uint8_t)std::stoi(substr.c_str(), 0, 2)); - } - - return string_data; -} - -string_data generate_string_data(uint8_t string_number) { - - srand((unsigned)time(0)); - string_data data; // - data.push_back({1, 0}); // idle chip - data.push_back({4, string_number}); // string number - - if (string_number == 1) { - data.push_back({2, 3}); // not_used - data.push_back({2, 1}); // p1 - data.push_back({12, 113}); // t_k - data.push_back({1, rand() & 1}); // x_vel_sign - data.push_back({23, 7122}); // x_vel_value - data.push_back({1, rand() & 1}); // x_accel_sign - data.push_back({4, 3}); // x_accel_value - data.push_back({1, rand() & 1}); // x_sign - data.push_back({26, 33554431}); // x_value - } else if (string_number == 2) { - data.push_back({3, 3}); // b_n - data.push_back({1, 1}); // p2 - data.push_back({7, 123}); // t_b - data.push_back({5, 31}); // not_used - data.push_back({1, rand() & 1}); // y_vel_sign - data.push_back({23, 7422}); // y_vel_value - data.push_back({1, rand() & 1}); // y_accel_sign - data.push_back({4, 3}); // y_accel_value - data.push_back({1, rand() & 1}); // y_sign - data.push_back({26, 67108863}); // y_value - } else if (string_number == 3) { - data.push_back({1, 0}); // p3 - data.push_back({1, 1}); // gamma_n_sign - data.push_back({10, 123}); // gamma_n_value - data.push_back({1, 0}); // not_used - data.push_back({2, 2}); // p - data.push_back({1, 1}); // l_n - data.push_back({1, rand() & 1}); // z_vel_sign - data.push_back({23, 1337}); // z_vel_value - data.push_back({1, rand() & 1}); // z_accel_sign - data.push_back({4, 9}); // z_accel_value - data.push_back({1, rand() & 1}); // z_sign - data.push_back({26, 100023}); // z_value - } else if (string_number == 4) { - data.push_back({1, rand() & 1}); // tau_n_sign - data.push_back({21, 197152}); // tau_n_value - data.push_back({1, rand() & 1}); // delta_tau_n_sign - data.push_back({4, 4}); // delta_tau_n_value - data.push_back({5, 0}); // e_n - data.push_back({14, 2}); // not_used_1 - data.push_back({1, 1}); // p4 - data.push_back({4, 9}); // f_t - data.push_back({3, 3}); // not_used_2 - data.push_back({11, 2047}); // n_t - data.push_back({5, 2}); // n - data.push_back({2, 1}); // m - } else if (string_number == 5) { - data.push_back({11, 2047}); // n_a - data.push_back({32, 4294767295}); // tau_c - data.push_back({1, 0}); // not_used_1 - data.push_back({5, 2}); // n_4 - data.push_back({22, 4114304}); // tau_gps - data.push_back({1, 0}); // l_n - } else { // non-immediate data is not parsed - data.push_back({64, rand()}); // data_1 - data.push_back({8, 6}); // data_2 - } - - data.push_back({8, rand() & 0xFF}); // hamming code - data.push_back({11, rand() & 0x7FF}); // pad - data.push_back({16, rand() & 0xFFFF}); // superframe - data.push_back({8, rand() & 0xFF}); // pad - data.push_back({8, rand() & 0xFF}); // frame - return data; -} - -TEST_CASE("parse_string_number_1"){ - string_data data = generate_string_data(1); - std::string inp_data = generate_inp_data(data); - - kaitai::kstream stream(inp_data); - glonass_t gl_string(&stream); - - REQUIRE(gl_string.idle_chip() == data[IDLE_CHIP_IDX].second); - REQUIRE(gl_string.string_number() == data[STRING_NUMBER_IDX].second); - REQUIRE(gl_string.hamming_code() == data[ST1_HC_OFF + HC_IDX].second); - REQUIRE(gl_string.pad_1() == data[ST1_HC_OFF + PAD1_IDX].second); - REQUIRE(gl_string.superframe_number() == data[ST1_HC_OFF + SUPERFRAME_IDX].second); - REQUIRE(gl_string.pad_2() == data[ST1_HC_OFF + PAD2_IDX].second); - REQUIRE(gl_string.frame_number() == data[ST1_HC_OFF + FRAME_IDX].second); - - kaitai::kstream str1(inp_data); - glonass_t str1_data(&str1); - glonass_t::string_1_t* s1 = static_cast(str1_data.data()); - - REQUIRE(s1->not_used() == data[ST1_NU_IDX].second); - REQUIRE(s1->p1() == data[ST1_P1_IDX].second); - REQUIRE(s1->t_k() == data[ST1_T_K_IDX].second); - - int mul = s1->x_vel_sign() ? (-1) : 1; - REQUIRE(s1->x_vel() == (data[ST1_X_VEL_V_IDX].second * mul)); - mul = s1->x_accel_sign() ? (-1) : 1; - REQUIRE(s1->x_accel() == (data[ST1_X_ACCEL_V_IDX].second * mul)); - mul = s1->x_sign() ? (-1) : 1; - REQUIRE(s1->x() == (data[ST1_X_V_IDX].second * mul)); -} - -TEST_CASE("parse_string_number_2"){ - string_data data = generate_string_data(2); - std::string inp_data = generate_inp_data(data); - - kaitai::kstream stream(inp_data); - glonass_t gl_string(&stream); - - REQUIRE(gl_string.idle_chip() == data[IDLE_CHIP_IDX].second); - REQUIRE(gl_string.string_number() == data[STRING_NUMBER_IDX].second); - REQUIRE(gl_string.hamming_code() == data[ST2_HC_OFF + HC_IDX].second); - REQUIRE(gl_string.pad_1() == data[ST2_HC_OFF + PAD1_IDX].second); - REQUIRE(gl_string.superframe_number() == data[ST2_HC_OFF + SUPERFRAME_IDX].second); - REQUIRE(gl_string.pad_2() == data[ST2_HC_OFF + PAD2_IDX].second); - REQUIRE(gl_string.frame_number() == data[ST2_HC_OFF + FRAME_IDX].second); - - kaitai::kstream str2(inp_data); - glonass_t str2_data(&str2); - glonass_t::string_2_t* s2 = static_cast(str2_data.data()); - - REQUIRE(s2->b_n() == data[ST2_BN_IDX].second); - REQUIRE(s2->not_used() == data[ST2_NU_IDX].second); - REQUIRE(s2->p2() == data[ST2_P2_IDX].second); - REQUIRE(s2->t_b() == data[ST2_TB_IDX].second); - int mul = s2->y_vel_sign() ? (-1) : 1; - REQUIRE(s2->y_vel() == (data[ST2_Y_VEL_V_IDX].second * mul)); - mul = s2->y_accel_sign() ? (-1) : 1; - REQUIRE(s2->y_accel() == (data[ST2_Y_ACCEL_V_IDX].second * mul)); - mul = s2->y_sign() ? (-1) : 1; - REQUIRE(s2->y() == (data[ST2_Y_V_IDX].second * mul)); -} - -TEST_CASE("parse_string_number_3"){ - string_data data = generate_string_data(3); - std::string inp_data = generate_inp_data(data); - - kaitai::kstream stream(inp_data); - glonass_t gl_string(&stream); - - REQUIRE(gl_string.idle_chip() == data[IDLE_CHIP_IDX].second); - REQUIRE(gl_string.string_number() == data[STRING_NUMBER_IDX].second); - REQUIRE(gl_string.hamming_code() == data[ST3_HC_OFF + HC_IDX].second); - REQUIRE(gl_string.pad_1() == data[ST3_HC_OFF + PAD1_IDX].second); - REQUIRE(gl_string.superframe_number() == data[ST3_HC_OFF + SUPERFRAME_IDX].second); - REQUIRE(gl_string.pad_2() == data[ST3_HC_OFF + PAD2_IDX].second); - REQUIRE(gl_string.frame_number() == data[ST3_HC_OFF + FRAME_IDX].second); - - kaitai::kstream str3(inp_data); - glonass_t str3_data(&str3); - glonass_t::string_3_t* s3 = static_cast(str3_data.data()); - - REQUIRE(s3->p3() == data[ST3_P3_IDX].second); - int mul = s3->gamma_n_sign() ? (-1) : 1; - REQUIRE(s3->gamma_n() == (data[ST3_GAMMA_N_V_IDX].second * mul)); - REQUIRE(s3->not_used() == data[ST3_NU_1_IDX].second); - REQUIRE(s3->p() == data[ST3_P_IDX].second); - REQUIRE(s3->l_n() == data[ST3_L_N_IDX].second); - mul = s3->z_vel_sign() ? (-1) : 1; - REQUIRE(s3->z_vel() == (data[ST3_Z_VEL_V_IDX].second * mul)); - mul = s3->z_accel_sign() ? (-1) : 1; - REQUIRE(s3->z_accel() == (data[ST3_Z_ACCEL_V_IDX].second * mul)); - mul = s3->z_sign() ? (-1) : 1; - REQUIRE(s3->z() == (data[ST3_Z_V_IDX].second * mul)); -} - -TEST_CASE("parse_string_number_4"){ - string_data data = generate_string_data(4); - std::string inp_data = generate_inp_data(data); - - kaitai::kstream stream(inp_data); - glonass_t gl_string(&stream); - - REQUIRE(gl_string.idle_chip() == data[IDLE_CHIP_IDX].second); - REQUIRE(gl_string.string_number() == data[STRING_NUMBER_IDX].second); - REQUIRE(gl_string.hamming_code() == data[ST4_HC_OFF + HC_IDX].second); - REQUIRE(gl_string.pad_1() == data[ST4_HC_OFF + PAD1_IDX].second); - REQUIRE(gl_string.superframe_number() == data[ST4_HC_OFF + SUPERFRAME_IDX].second); - REQUIRE(gl_string.pad_2() == data[ST4_HC_OFF + PAD2_IDX].second); - REQUIRE(gl_string.frame_number() == data[ST4_HC_OFF + FRAME_IDX].second); - - kaitai::kstream str4(inp_data); - glonass_t str4_data(&str4); - glonass_t::string_4_t* s4 = static_cast(str4_data.data()); - - int mul = s4->tau_n_sign() ? (-1) : 1; - REQUIRE(s4->tau_n() == (data[ST4_TAU_N_V_IDX].second * mul)); - mul = s4->delta_tau_n_sign() ? (-1) : 1; - REQUIRE(s4->delta_tau_n() == (data[ST4_DELTA_TAU_N_V_IDX].second * mul)); - REQUIRE(s4->e_n() == data[ST4_E_N_IDX].second); - REQUIRE(s4->not_used_1() == data[ST4_NU_1_IDX].second); - REQUIRE(s4->p4() == data[ST4_P4_IDX].second); - REQUIRE(s4->f_t() == data[ST4_F_T_IDX].second); - REQUIRE(s4->not_used_2() == data[ST4_NU_2_IDX].second); - REQUIRE(s4->n_t() == data[ST4_N_T_IDX].second); - REQUIRE(s4->n() == data[ST4_N_IDX].second); - REQUIRE(s4->m() == data[ST4_M_IDX].second); -} - -TEST_CASE("parse_string_number_5"){ - string_data data = generate_string_data(5); - std::string inp_data = generate_inp_data(data); - - kaitai::kstream stream(inp_data); - glonass_t gl_string(&stream); - - REQUIRE(gl_string.idle_chip() == data[IDLE_CHIP_IDX].second); - REQUIRE(gl_string.string_number() == data[STRING_NUMBER_IDX].second); - REQUIRE(gl_string.hamming_code() == data[ST5_HC_OFF + HC_IDX].second); - REQUIRE(gl_string.pad_1() == data[ST5_HC_OFF + PAD1_IDX].second); - REQUIRE(gl_string.superframe_number() == data[ST5_HC_OFF + SUPERFRAME_IDX].second); - REQUIRE(gl_string.pad_2() == data[ST5_HC_OFF + PAD2_IDX].second); - REQUIRE(gl_string.frame_number() == data[ST5_HC_OFF + FRAME_IDX].second); - - kaitai::kstream str5(inp_data); - glonass_t str5_data(&str5); - glonass_t::string_5_t* s5 = static_cast(str5_data.data()); - - REQUIRE(s5->n_a() == data[ST5_N_A_IDX].second); - REQUIRE(s5->tau_c() == data[ST5_TAU_C_IDX].second); - REQUIRE(s5->not_used() == data[ST5_NU_IDX].second); - REQUIRE(s5->n_4() == data[ST5_N_4_IDX].second); - REQUIRE(s5->tau_gps() == data[ST5_TAU_GPS_IDX].second); - REQUIRE(s5->l_n() == data[ST5_L_N_IDX].second); -} - -TEST_CASE("parse_string_number_NI"){ - string_data data = generate_string_data((rand() % 10) + 6); - std::string inp_data = generate_inp_data(data); - - kaitai::kstream stream(inp_data); - glonass_t gl_string(&stream); - - REQUIRE(gl_string.idle_chip() == data[IDLE_CHIP_IDX].second); - REQUIRE(gl_string.string_number() == data[STRING_NUMBER_IDX].second); - REQUIRE(gl_string.hamming_code() == data[ST6_HC_OFF + HC_IDX].second); - REQUIRE(gl_string.pad_1() == data[ST6_HC_OFF + PAD1_IDX].second); - REQUIRE(gl_string.superframe_number() == data[ST6_HC_OFF + SUPERFRAME_IDX].second); - REQUIRE(gl_string.pad_2() == data[ST6_HC_OFF + PAD2_IDX].second); - REQUIRE(gl_string.frame_number() == data[ST6_HC_OFF + FRAME_IDX].second); - - kaitai::kstream strni(inp_data); - glonass_t strni_data(&strni); - glonass_t::string_non_immediate_t* sni = static_cast(strni_data.data()); - - REQUIRE(sni->data_1() == data[ST6_DATA_1_IDX].second); - REQUIRE(sni->data_2() == data[ST6_DATA_2_IDX].second); -} diff --git a/system/ubloxd/tests/test_glonass_runner.cc b/system/ubloxd/tests/test_glonass_runner.cc deleted file mode 100644 index 62bf7476a1..0000000000 --- a/system/ubloxd/tests/test_glonass_runner.cc +++ /dev/null @@ -1,2 +0,0 @@ -#define CATCH_CONFIG_MAIN -#include "catch2/catch.hpp" diff --git a/system/ubloxd/tests/ubloxd.py b/system/ubloxd/tests/ubloxd.py deleted file mode 100755 index c17387114f..0000000000 --- a/system/ubloxd/tests/ubloxd.py +++ /dev/null @@ -1,89 +0,0 @@ -#!/usr/bin/env python3 -# type: ignore - -from openpilot.selfdrive.locationd.test import ublox -import struct - -baudrate = 460800 -rate = 100 # send new data every 100ms - - -def configure_ublox(dev): - # configure ports and solution parameters and rate - dev.configure_port(port=ublox.PORT_USB, inMask=1, outMask=1) # enable only UBX on USB - dev.configure_port(port=0, inMask=0, outMask=0) # disable DDC - - payload = struct.pack(' - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "common/swaglog.h" - -const double gpsPi = 3.1415926535898; -#define UBLOX_MSG_SIZE(hdr) (*(uint16_t *)&hdr[4]) - -inline static bool bit_to_bool(uint8_t val, int shifts) { - return (bool)(val & (1 << shifts)); -} - -inline int UbloxMsgParser::needed_bytes() { - // Msg header incomplete? - if (bytes_in_parse_buf < ublox::UBLOX_HEADER_SIZE) - return ublox::UBLOX_HEADER_SIZE + ublox::UBLOX_CHECKSUM_SIZE - bytes_in_parse_buf; - uint16_t needed = UBLOX_MSG_SIZE(msg_parse_buf) + ublox::UBLOX_HEADER_SIZE + ublox::UBLOX_CHECKSUM_SIZE; - // too much data - if (needed < (uint16_t)bytes_in_parse_buf) - return -1; - return needed - (uint16_t)bytes_in_parse_buf; -} - -inline bool UbloxMsgParser::valid_cheksum() { - uint8_t ck_a = 0, ck_b = 0; - for (int i = 2; i < bytes_in_parse_buf - ublox::UBLOX_CHECKSUM_SIZE; i++) { - ck_a = (ck_a + msg_parse_buf[i]) & 0xFF; - ck_b = (ck_b + ck_a) & 0xFF; - } - if (ck_a != msg_parse_buf[bytes_in_parse_buf - 2]) { - LOGD("Checksum a mismatch: %02X, %02X", ck_a, msg_parse_buf[6]); - return false; - } - if (ck_b != msg_parse_buf[bytes_in_parse_buf - 1]) { - LOGD("Checksum b mismatch: %02X, %02X", ck_b, msg_parse_buf[7]); - return false; - } - return true; -} - -inline bool UbloxMsgParser::valid() { - return bytes_in_parse_buf >= ublox::UBLOX_HEADER_SIZE + ublox::UBLOX_CHECKSUM_SIZE && - needed_bytes() == 0 && valid_cheksum(); -} - -inline bool UbloxMsgParser::valid_so_far() { - if (bytes_in_parse_buf > 0 && msg_parse_buf[0] != ublox::PREAMBLE1) { - return false; - } - if (bytes_in_parse_buf > 1 && msg_parse_buf[1] != ublox::PREAMBLE2) { - return false; - } - if (needed_bytes() == 0 && !valid()) { - return false; - } - return true; -} - -bool UbloxMsgParser::add_data(float log_time, const uint8_t *incoming_data, uint32_t incoming_data_len, size_t &bytes_consumed) { - last_log_time = log_time; - int needed = needed_bytes(); - if (needed > 0) { - bytes_consumed = std::min((uint32_t)needed, incoming_data_len); - // Add data to buffer - memcpy(msg_parse_buf + bytes_in_parse_buf, incoming_data, bytes_consumed); - bytes_in_parse_buf += bytes_consumed; - } else { - bytes_consumed = incoming_data_len; - } - - // Validate msg format, detect invalid header and invalid checksum. - while (!valid_so_far() && bytes_in_parse_buf != 0) { - // Corrupted msg, drop a byte. - bytes_in_parse_buf -= 1; - if (bytes_in_parse_buf > 0) - memmove(&msg_parse_buf[0], &msg_parse_buf[1], bytes_in_parse_buf); - } - - // There is redundant data at the end of buffer, reset the buffer. - if (needed_bytes() == -1) { - bytes_in_parse_buf = 0; - } - return valid(); -} - - -std::pair> UbloxMsgParser::gen_msg() { - std::string dat = data(); - kaitai::kstream stream(dat); - - ubx_t ubx_message(&stream); - auto body = ubx_message.body(); - - switch (ubx_message.msg_type()) { - case 0x0107: - return {"gpsLocationExternal", gen_nav_pvt(static_cast(body))}; - case 0x0213: // UBX-RXM-SFRB (Broadcast Navigation Data Subframe) - return {"ubloxGnss", gen_rxm_sfrbx(static_cast(body))}; - case 0x0215: // UBX-RXM-RAW (Multi-GNSS Raw Measurement Data) - return {"ubloxGnss", gen_rxm_rawx(static_cast(body))}; - case 0x0a09: - return {"ubloxGnss", gen_mon_hw(static_cast(body))}; - case 0x0a0b: - return {"ubloxGnss", gen_mon_hw2(static_cast(body))}; - case 0x0135: - return {"ubloxGnss", gen_nav_sat(static_cast(body))}; - default: - LOGE("Unknown message type %x", ubx_message.msg_type()); - return {"ubloxGnss", kj::Array()}; - } -} - - -kj::Array UbloxMsgParser::gen_nav_pvt(ubx_t::nav_pvt_t *msg) { - MessageBuilder msg_builder; - auto gpsLoc = msg_builder.initEvent().initGpsLocationExternal(); - gpsLoc.setSource(cereal::GpsLocationData::SensorSource::UBLOX); - gpsLoc.setFlags(msg->flags()); - gpsLoc.setHasFix((msg->flags() % 2) == 1); - gpsLoc.setLatitude(msg->lat() * 1e-07); - gpsLoc.setLongitude(msg->lon() * 1e-07); - gpsLoc.setAltitude(msg->height() * 1e-03); - gpsLoc.setSpeed(msg->g_speed() * 1e-03); - gpsLoc.setBearingDeg(msg->head_mot() * 1e-5); - gpsLoc.setHorizontalAccuracy(msg->h_acc() * 1e-03); - gpsLoc.setSatelliteCount(msg->num_sv()); - std::tm timeinfo = std::tm(); - timeinfo.tm_year = msg->year() - 1900; - timeinfo.tm_mon = msg->month() - 1; - timeinfo.tm_mday = msg->day(); - timeinfo.tm_hour = msg->hour(); - timeinfo.tm_min = msg->min(); - timeinfo.tm_sec = msg->sec(); - - std::time_t utc_tt = timegm(&timeinfo); - gpsLoc.setUnixTimestampMillis(utc_tt * 1e+03 + msg->nano() * 1e-06); - float f[] = { msg->vel_n() * 1e-03f, msg->vel_e() * 1e-03f, msg->vel_d() * 1e-03f }; - gpsLoc.setVNED(f); - gpsLoc.setVerticalAccuracy(msg->v_acc() * 1e-03); - gpsLoc.setSpeedAccuracy(msg->s_acc() * 1e-03); - gpsLoc.setBearingAccuracyDeg(msg->head_acc() * 1e-05); - return capnp::messageToFlatArray(msg_builder); -} - -kj::Array UbloxMsgParser::parse_gps_ephemeris(ubx_t::rxm_sfrbx_t *msg) { - // GPS subframes are packed into 10x 4 bytes, each containing 3 actual bytes - // We will first need to separate the data from the padding and parity - auto body = *msg->body(); - assert(body.size() == 10); - - std::string subframe_data; - subframe_data.reserve(30); - for (uint32_t word : body) { - word = word >> 6; // TODO: Verify parity - subframe_data.push_back(word >> 16); - subframe_data.push_back(word >> 8); - subframe_data.push_back(word >> 0); - } - - // Collect subframes in map and parse when we have all the parts - { - kaitai::kstream stream(subframe_data); - gps_t subframe(&stream); - - int subframe_id = subframe.how()->subframe_id(); - if (subframe_id > 3 || subframe_id < 1) { - // don't parse almanac subframes - return kj::Array(); - } - gps_subframes[msg->sv_id()][subframe_id] = subframe_data; - } - - // publish if subframes 1-3 have been collected - if (gps_subframes[msg->sv_id()].size() == 3) { - MessageBuilder msg_builder; - auto eph = msg_builder.initEvent().initUbloxGnss().initEphemeris(); - eph.setSvId(msg->sv_id()); - - int iode_s2 = 0; - int iode_s3 = 0; - int iodc_lsb = 0; - int week; - - // Subframe 1 - { - kaitai::kstream stream(gps_subframes[msg->sv_id()][1]); - gps_t subframe(&stream); - gps_t::subframe_1_t* subframe_1 = static_cast(subframe.body()); - - // Each message is incremented to be greater or equal than week 1877 (2015-12-27). - // To skip this use the current_time argument - week = subframe_1->week_no(); - week += 1024; - if (week < 1877) { - week += 1024; - } - //eph.setGpsWeek(subframe_1->week_no()); - eph.setTgd(subframe_1->t_gd() * pow(2, -31)); - eph.setToc(subframe_1->t_oc() * pow(2, 4)); - eph.setAf2(subframe_1->af_2() * pow(2, -55)); - eph.setAf1(subframe_1->af_1() * pow(2, -43)); - eph.setAf0(subframe_1->af_0() * pow(2, -31)); - eph.setSvHealth(subframe_1->sv_health()); - eph.setTowCount(subframe.how()->tow_count()); - iodc_lsb = subframe_1->iodc_lsb(); - } - - // Subframe 2 - { - kaitai::kstream stream(gps_subframes[msg->sv_id()][2]); - gps_t subframe(&stream); - gps_t::subframe_2_t* subframe_2 = static_cast(subframe.body()); - - // GPS week refers to current week, the ephemeris can be valid for the next - // if toe equals 0, this can be verified by the TOW count if it is within the - // last 2 hours of the week (gps ephemeris valid for 4hours) - if (subframe_2->t_oe() == 0 and subframe.how()->tow_count()*6 >= (SECS_IN_WEEK - 2*SECS_IN_HR)){ - week += 1; - } - eph.setCrs(subframe_2->c_rs() * pow(2, -5)); - eph.setDeltaN(subframe_2->delta_n() * pow(2, -43) * gpsPi); - eph.setM0(subframe_2->m_0() * pow(2, -31) * gpsPi); - eph.setCuc(subframe_2->c_uc() * pow(2, -29)); - eph.setEcc(subframe_2->e() * pow(2, -33)); - eph.setCus(subframe_2->c_us() * pow(2, -29)); - eph.setA(pow(subframe_2->sqrt_a() * pow(2, -19), 2.0)); - eph.setToe(subframe_2->t_oe() * pow(2, 4)); - iode_s2 = subframe_2->iode(); - } - - // Subframe 3 - { - kaitai::kstream stream(gps_subframes[msg->sv_id()][3]); - gps_t subframe(&stream); - gps_t::subframe_3_t* subframe_3 = static_cast(subframe.body()); - - eph.setCic(subframe_3->c_ic() * pow(2, -29)); - eph.setOmega0(subframe_3->omega_0() * pow(2, -31) * gpsPi); - eph.setCis(subframe_3->c_is() * pow(2, -29)); - eph.setI0(subframe_3->i_0() * pow(2, -31) * gpsPi); - eph.setCrc(subframe_3->c_rc() * pow(2, -5)); - eph.setOmega(subframe_3->omega() * pow(2, -31) * gpsPi); - eph.setOmegaDot(subframe_3->omega_dot() * pow(2, -43) * gpsPi); - eph.setIode(subframe_3->iode()); - eph.setIDot(subframe_3->idot() * pow(2, -43) * gpsPi); - iode_s3 = subframe_3->iode(); - } - - eph.setToeWeek(week); - eph.setTocWeek(week); - - gps_subframes[msg->sv_id()].clear(); - if (iodc_lsb != iode_s2 || iodc_lsb != iode_s3) { - // data set cutover, reject ephemeris - return kj::Array(); - } - return capnp::messageToFlatArray(msg_builder); - } - return kj::Array(); -} - -kj::Array UbloxMsgParser::parse_glonass_ephemeris(ubx_t::rxm_sfrbx_t *msg) { - // This parser assumes that no 2 satellites of the same frequency - // can be in view at the same time - auto body = *msg->body(); - assert(body.size() == 4); - { - std::string string_data; - string_data.reserve(16); - for (uint32_t word : body) { - for (int i = 3; i >= 0; i--) - string_data.push_back(word >> 8*i); - } - - kaitai::kstream stream(string_data); - glonass_t gl_string(&stream); - int string_number = gl_string.string_number(); - if (string_number < 1 || string_number > 5 || gl_string.idle_chip()) { - // don't parse non immediate data, idle_chip == 0 - return kj::Array(); - } - - // Check if new string either has same superframe_id or log transmission times make sense - bool superframe_unknown = false; - bool needs_clear = false; - for (int i = 1; i <= 5; i++) { - if (glonass_strings[msg->freq_id()].find(i) == glonass_strings[msg->freq_id()].end()) - continue; - if (glonass_string_superframes[msg->freq_id()][i] == 0 || gl_string.superframe_number() == 0) { - superframe_unknown = true; - } else if (glonass_string_superframes[msg->freq_id()][i] != gl_string.superframe_number()) { - needs_clear = true; - } - // Check if string times add up to being from the same frame - // If superframe is known this is redundant - // Strings are sent 2s apart and frames are 30s apart - if (superframe_unknown && - std::abs((glonass_string_times[msg->freq_id()][i] - 2.0 * i) - (last_log_time - 2.0 * string_number)) > 10) - needs_clear = true; - } - if (needs_clear) { - glonass_strings[msg->freq_id()].clear(); - glonass_string_superframes[msg->freq_id()].clear(); - glonass_string_times[msg->freq_id()].clear(); - } - glonass_strings[msg->freq_id()][string_number] = string_data; - glonass_string_superframes[msg->freq_id()][string_number] = gl_string.superframe_number(); - glonass_string_times[msg->freq_id()][string_number] = last_log_time; - } - if (msg->sv_id() == 255) { - // data can be decoded before identifying the SV number, in this case 255 - // is returned, which means "unknown" (ublox p32) - return kj::Array(); - } - - // publish if strings 1-5 have been collected - if (glonass_strings[msg->freq_id()].size() != 5) { - return kj::Array(); - } - - MessageBuilder msg_builder; - auto eph = msg_builder.initEvent().initUbloxGnss().initGlonassEphemeris(); - eph.setSvId(msg->sv_id()); - eph.setFreqNum(msg->freq_id() - 7); - - uint16_t current_day = 0; - uint16_t tk = 0; - - // string number 1 - { - kaitai::kstream stream(glonass_strings[msg->freq_id()][1]); - glonass_t gl_stream(&stream); - glonass_t::string_1_t* data = static_cast(gl_stream.data()); - - eph.setP1(data->p1()); - tk = data->t_k(); - eph.setTkDEPRECATED(tk); - eph.setXVel(data->x_vel() * pow(2, -20)); - eph.setXAccel(data->x_accel() * pow(2, -30)); - eph.setX(data->x() * pow(2, -11)); - } - - // string number 2 - { - kaitai::kstream stream(glonass_strings[msg->freq_id()][2]); - glonass_t gl_stream(&stream); - glonass_t::string_2_t* data = static_cast(gl_stream.data()); - - eph.setSvHealth(data->b_n()>>2); // MSB indicates health - eph.setP2(data->p2()); - eph.setTb(data->t_b()); - eph.setYVel(data->y_vel() * pow(2, -20)); - eph.setYAccel(data->y_accel() * pow(2, -30)); - eph.setY(data->y() * pow(2, -11)); - } - - // string number 3 - { - kaitai::kstream stream(glonass_strings[msg->freq_id()][3]); - glonass_t gl_stream(&stream); - glonass_t::string_3_t* data = static_cast(gl_stream.data()); - - eph.setP3(data->p3()); - eph.setGammaN(data->gamma_n() * pow(2, -40)); - eph.setSvHealth(eph.getSvHealth() | data->l_n()); - eph.setZVel(data->z_vel() * pow(2, -20)); - eph.setZAccel(data->z_accel() * pow(2, -30)); - eph.setZ(data->z() * pow(2, -11)); - } - - // string number 4 - { - kaitai::kstream stream(glonass_strings[msg->freq_id()][4]); - glonass_t gl_stream(&stream); - glonass_t::string_4_t* data = static_cast(gl_stream.data()); - - current_day = data->n_t(); - eph.setNt(current_day); - eph.setTauN(data->tau_n() * pow(2, -30)); - eph.setDeltaTauN(data->delta_tau_n() * pow(2, -30)); - eph.setAge(data->e_n()); - eph.setP4(data->p4()); - eph.setSvURA(glonass_URA_lookup.at(data->f_t())); - if (msg->sv_id() != data->n()) { - LOGE("SV_ID != SLOT_NUMBER: %d %" PRIu64, msg->sv_id(), data->n()); - } - eph.setSvType(data->m()); - } - - // string number 5 - { - kaitai::kstream stream(glonass_strings[msg->freq_id()][5]); - glonass_t gl_stream(&stream); - glonass_t::string_5_t* data = static_cast(gl_stream.data()); - - // string5 parsing is only needed to get the year, this can be removed and - // the year can be fetched later in laika (note rollovers and leap year) - eph.setN4(data->n_4()); - int tk_seconds = SECS_IN_HR * ((tk>>7) & 0x1F) + SECS_IN_MIN * ((tk>>1) & 0x3F) + (tk & 0x1) * 30; - eph.setTkSeconds(tk_seconds); - } - - glonass_strings[msg->freq_id()].clear(); - return capnp::messageToFlatArray(msg_builder); -} - - -kj::Array UbloxMsgParser::gen_rxm_sfrbx(ubx_t::rxm_sfrbx_t *msg) { - switch (msg->gnss_id()) { - case ubx_t::gnss_type_t::GNSS_TYPE_GPS: - return parse_gps_ephemeris(msg); - case ubx_t::gnss_type_t::GNSS_TYPE_GLONASS: - return parse_glonass_ephemeris(msg); - default: - return kj::Array(); - } -} - -kj::Array UbloxMsgParser::gen_rxm_rawx(ubx_t::rxm_rawx_t *msg) { - MessageBuilder msg_builder; - auto mr = msg_builder.initEvent().initUbloxGnss().initMeasurementReport(); - mr.setRcvTow(msg->rcv_tow()); - mr.setGpsWeek(msg->week()); - mr.setLeapSeconds(msg->leap_s()); - mr.setGpsWeek(msg->week()); - - auto mb = mr.initMeasurements(msg->num_meas()); - auto measurements = *msg->meas(); - for (int8_t i = 0; i < msg->num_meas(); i++) { - mb[i].setSvId(measurements[i]->sv_id()); - mb[i].setPseudorange(measurements[i]->pr_mes()); - mb[i].setCarrierCycles(measurements[i]->cp_mes()); - mb[i].setDoppler(measurements[i]->do_mes()); - mb[i].setGnssId(measurements[i]->gnss_id()); - mb[i].setGlonassFrequencyIndex(measurements[i]->freq_id()); - mb[i].setLocktime(measurements[i]->lock_time()); - mb[i].setCno(measurements[i]->cno()); - mb[i].setPseudorangeStdev(0.01 * (pow(2, (measurements[i]->pr_stdev() & 15)))); // weird scaling, might be wrong - mb[i].setCarrierPhaseStdev(0.004 * (measurements[i]->cp_stdev() & 15)); - mb[i].setDopplerStdev(0.002 * (pow(2, (measurements[i]->do_stdev() & 15)))); // weird scaling, might be wrong - - auto ts = mb[i].initTrackingStatus(); - auto trk_stat = measurements[i]->trk_stat(); - ts.setPseudorangeValid(bit_to_bool(trk_stat, 0)); - ts.setCarrierPhaseValid(bit_to_bool(trk_stat, 1)); - ts.setHalfCycleValid(bit_to_bool(trk_stat, 2)); - ts.setHalfCycleSubtracted(bit_to_bool(trk_stat, 3)); - } - - mr.setNumMeas(msg->num_meas()); - auto rs = mr.initReceiverStatus(); - rs.setLeapSecValid(bit_to_bool(msg->rec_stat(), 0)); - rs.setClkReset(bit_to_bool(msg->rec_stat(), 2)); - return capnp::messageToFlatArray(msg_builder); -} - -kj::Array UbloxMsgParser::gen_nav_sat(ubx_t::nav_sat_t *msg) { - MessageBuilder msg_builder; - auto sr = msg_builder.initEvent().initUbloxGnss().initSatReport(); - sr.setITow(msg->itow()); - - auto svs = sr.initSvs(msg->num_svs()); - auto svs_data = *msg->svs(); - for (int8_t i = 0; i < msg->num_svs(); i++) { - svs[i].setSvId(svs_data[i]->sv_id()); - svs[i].setGnssId(svs_data[i]->gnss_id()); - svs[i].setFlagsBitfield(svs_data[i]->flags()); - svs[i].setCno(svs_data[i]->cno()); - svs[i].setElevationDeg(svs_data[i]->elev()); - svs[i].setAzimuthDeg(svs_data[i]->azim()); - svs[i].setPseudorangeResidual(svs_data[i]->pr_res() * 0.1); - } - - return capnp::messageToFlatArray(msg_builder); -} - -kj::Array UbloxMsgParser::gen_mon_hw(ubx_t::mon_hw_t *msg) { - MessageBuilder msg_builder; - auto hwStatus = msg_builder.initEvent().initUbloxGnss().initHwStatus(); - hwStatus.setNoisePerMS(msg->noise_per_ms()); - hwStatus.setFlags(msg->flags()); - hwStatus.setAgcCnt(msg->agc_cnt()); - hwStatus.setAStatus((cereal::UbloxGnss::HwStatus::AntennaSupervisorState) msg->a_status()); - hwStatus.setAPower((cereal::UbloxGnss::HwStatus::AntennaPowerStatus) msg->a_power()); - hwStatus.setJamInd(msg->jam_ind()); - return capnp::messageToFlatArray(msg_builder); -} - -kj::Array UbloxMsgParser::gen_mon_hw2(ubx_t::mon_hw2_t *msg) { - MessageBuilder msg_builder; - auto hwStatus = msg_builder.initEvent().initUbloxGnss().initHwStatus2(); - hwStatus.setOfsI(msg->ofs_i()); - hwStatus.setMagI(msg->mag_i()); - hwStatus.setOfsQ(msg->ofs_q()); - hwStatus.setMagQ(msg->mag_q()); - - switch (msg->cfg_source()) { - case ubx_t::mon_hw2_t::config_source_t::CONFIG_SOURCE_ROM: - hwStatus.setCfgSource(cereal::UbloxGnss::HwStatus2::ConfigSource::ROM); - break; - case ubx_t::mon_hw2_t::config_source_t::CONFIG_SOURCE_OTP: - hwStatus.setCfgSource(cereal::UbloxGnss::HwStatus2::ConfigSource::OTP); - break; - case ubx_t::mon_hw2_t::config_source_t::CONFIG_SOURCE_CONFIG_PINS: - hwStatus.setCfgSource(cereal::UbloxGnss::HwStatus2::ConfigSource::CONFIGPINS); - break; - case ubx_t::mon_hw2_t::config_source_t::CONFIG_SOURCE_FLASH: - hwStatus.setCfgSource(cereal::UbloxGnss::HwStatus2::ConfigSource::FLASH); - break; - default: - hwStatus.setCfgSource(cereal::UbloxGnss::HwStatus2::ConfigSource::UNDEFINED); - break; - } - - hwStatus.setLowLevCfg(msg->low_lev_cfg()); - hwStatus.setPostStatus(msg->post_status()); - - return capnp::messageToFlatArray(msg_builder); -} diff --git a/system/ubloxd/ublox_msg.h b/system/ubloxd/ublox_msg.h deleted file mode 100644 index d21760edc2..0000000000 --- a/system/ubloxd/ublox_msg.h +++ /dev/null @@ -1,131 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include -#include - -#include "cereal/messaging/messaging.h" -#include "common/util.h" -#include "system/ubloxd/generated/gps.h" -#include "system/ubloxd/generated/glonass.h" -#include "system/ubloxd/generated/ubx.h" - -using namespace std::string_literals; - -const int SECS_IN_MIN = 60; -const int SECS_IN_HR = 60 * SECS_IN_MIN; -const int SECS_IN_DAY = 24 * SECS_IN_HR; -const int SECS_IN_WEEK = 7 * SECS_IN_DAY; - -// protocol constants -namespace ublox { - const uint8_t PREAMBLE1 = 0xb5; - const uint8_t PREAMBLE2 = 0x62; - - const int UBLOX_HEADER_SIZE = 6; - const int UBLOX_CHECKSUM_SIZE = 2; - const int UBLOX_MAX_MSG_SIZE = 65536; - - struct ubx_mga_ini_time_utc_t { - uint8_t type; - uint8_t version; - uint8_t ref; - int8_t leapSecs; - uint16_t year; - uint8_t month; - uint8_t day; - uint8_t hour; - uint8_t minute; - uint8_t second; - uint8_t reserved1; - uint32_t ns; - uint16_t tAccS; - uint16_t reserved2; - uint32_t tAccNs; - } __attribute__((packed)); - - inline std::string ubx_add_checksum(const std::string &msg) { - assert(msg.size() > 2); - - uint8_t ck_a = 0, ck_b = 0; - for (int i = 2; i < msg.size(); i++) { - ck_a = (ck_a + msg[i]) & 0xFF; - ck_b = (ck_b + ck_a) & 0xFF; - } - - std::string r = msg; - r.push_back(ck_a); - r.push_back(ck_b); - return r; - } - - inline std::string build_ubx_mga_ini_time_utc(struct tm time) { - ublox::ubx_mga_ini_time_utc_t payload = { - .type = 0x10, - .version = 0x0, - .ref = 0x0, - .leapSecs = -128, // Unknown - .year = (uint16_t)(1900 + time.tm_year), - .month = (uint8_t)(1 + time.tm_mon), - .day = (uint8_t)time.tm_mday, - .hour = (uint8_t)time.tm_hour, - .minute = (uint8_t)time.tm_min, - .second = (uint8_t)time.tm_sec, - .reserved1 = 0x0, - .ns = 0, - .tAccS = 30, - .reserved2 = 0x0, - .tAccNs = 0, - }; - assert(sizeof(payload) == 24); - - std::string msg = "\xb5\x62\x13\x40\x18\x00"s; - msg += std::string((char*)&payload, sizeof(payload)); - - return ubx_add_checksum(msg); - } -} - -class UbloxMsgParser { - public: - bool add_data(float log_time, const uint8_t *incoming_data, uint32_t incoming_data_len, size_t &bytes_consumed); - inline void reset() {bytes_in_parse_buf = 0;} - inline int needed_bytes(); - inline std::string data() {return std::string((const char*)msg_parse_buf, bytes_in_parse_buf);} - - std::pair> gen_msg(); - kj::Array gen_nav_pvt(ubx_t::nav_pvt_t *msg); - kj::Array gen_rxm_sfrbx(ubx_t::rxm_sfrbx_t *msg); - kj::Array gen_rxm_rawx(ubx_t::rxm_rawx_t *msg); - kj::Array gen_mon_hw(ubx_t::mon_hw_t *msg); - kj::Array gen_mon_hw2(ubx_t::mon_hw2_t *msg); - kj::Array gen_nav_sat(ubx_t::nav_sat_t *msg); - - private: - inline bool valid_cheksum(); - inline bool valid(); - inline bool valid_so_far(); - - kj::Array parse_gps_ephemeris(ubx_t::rxm_sfrbx_t *msg); - kj::Array parse_glonass_ephemeris(ubx_t::rxm_sfrbx_t *msg); - - std::unordered_map> gps_subframes; - - float last_log_time = 0.0; - size_t bytes_in_parse_buf = 0; - uint8_t msg_parse_buf[ublox::UBLOX_HEADER_SIZE + ublox::UBLOX_MAX_MSG_SIZE]; - - // user range accuracy in meters - const std::unordered_map glonass_URA_lookup = - {{ 0, 1}, { 1, 2}, { 2, 2.5}, { 3, 4}, { 4, 5}, {5, 7}, - { 6, 10}, { 7, 12}, { 8, 14}, { 9, 16}, {10, 32}, - {11, 64}, {12, 128}, {13, 256}, {14, 512}, {15, 1024}}; - - std::unordered_map> glonass_strings; - std::unordered_map> glonass_string_times; - std::unordered_map> glonass_string_superframes; -}; diff --git a/system/ubloxd/ubloxd.cc b/system/ubloxd/ubloxd.cc deleted file mode 100644 index 4e7e91f830..0000000000 --- a/system/ubloxd/ubloxd.cc +++ /dev/null @@ -1,62 +0,0 @@ -#include - -#include - -#include "cereal/messaging/messaging.h" -#include "common/swaglog.h" -#include "common/util.h" -#include "system/ubloxd/ublox_msg.h" - -ExitHandler do_exit; -using namespace ublox; - -int main() { - LOGW("starting ubloxd"); - AlignedBuffer aligned_buf; - UbloxMsgParser parser; - - PubMaster pm({"ubloxGnss", "gpsLocationExternal"}); - - std::unique_ptr context(Context::create()); - std::unique_ptr subscriber(SubSocket::create(context.get(), "ubloxRaw")); - assert(subscriber != NULL); - subscriber->setTimeout(100); - - - while (!do_exit) { - std::unique_ptr msg(subscriber->receive()); - if (!msg) { - continue; - } - - capnp::FlatArrayMessageReader cmsg(aligned_buf.align(msg.get())); - cereal::Event::Reader event = cmsg.getRoot(); - auto ubloxRaw = event.getUbloxRaw(); - float log_time = 1e-9 * event.getLogMonoTime(); - - const uint8_t *data = ubloxRaw.begin(); - size_t len = ubloxRaw.size(); - size_t bytes_consumed = 0; - - while (bytes_consumed < len && !do_exit) { - size_t bytes_consumed_this_time = 0U; - if (parser.add_data(log_time, data + bytes_consumed, (uint32_t)(len - bytes_consumed), bytes_consumed_this_time)) { - - try { - auto ublox_msg = parser.gen_msg(); - if (ublox_msg.second.size() > 0) { - auto bytes = ublox_msg.second.asBytes(); - pm.send(ublox_msg.first.c_str(), bytes.begin(), bytes.size()); - } - } catch (const std::exception& e) { - LOGE("Error parsing ublox message %s", e.what()); - } - - parser.reset(); - } - bytes_consumed += bytes_consumed_this_time; - } - } - - return 0; -} diff --git a/system/ubloxd/ubx.ksy b/system/ubloxd/ubx.ksy deleted file mode 100644 index 02c757fe71..0000000000 --- a/system/ubloxd/ubx.ksy +++ /dev/null @@ -1,293 +0,0 @@ -meta: - id: ubx - endian: le -seq: - - id: magic - contents: [0xb5, 0x62] - - id: msg_type - type: u2be - - id: length - type: u2 - - id: body - type: - switch-on: msg_type - cases: - 0x0107: nav_pvt - 0x0213: rxm_sfrbx - 0x0215: rxm_rawx - 0x0a09: mon_hw - 0x0a0b: mon_hw2 - 0x0135: nav_sat -instances: - checksum: - pos: length + 6 - type: u2 - -types: - mon_hw: - seq: - - id: pin_sel - type: u4 - - id: pin_bank - type: u4 - - id: pin_dir - type: u4 - - id: pin_val - type: u4 - - id: noise_per_ms - type: u2 - - id: agc_cnt - type: u2 - - id: a_status - type: u1 - enum: antenna_status - - id: a_power - type: u1 - enum: antenna_power - - id: flags - type: u1 - - id: reserved1 - size: 1 - - id: used_mask - type: u4 - - id: vp - size: 17 - - id: jam_ind - type: u1 - - id: reserved2 - size: 2 - - id: pin_irq - type: u4 - - id: pull_h - type: u4 - - id: pull_l - type: u4 - enums: - antenna_status: - 0: init - 1: dontknow - 2: ok - 3: short - 4: open - antenna_power: - 0: off - 1: on - 2: dontknow - - mon_hw2: - seq: - - id: ofs_i - type: s1 - - id: mag_i - type: u1 - - id: ofs_q - type: s1 - - id: mag_q - type: u1 - - id: cfg_source - type: u1 - enum: config_source - - id: reserved1 - size: 3 - - id: low_lev_cfg - type: u4 - - id: reserved2 - size: 8 - - id: post_status - type: u4 - - id: reserved3 - size: 4 - - enums: - config_source: - 113: rom - 111: otp - 112: config_pins - 102: flash - - rxm_sfrbx: - seq: - - id: gnss_id - type: u1 - enum: gnss_type - - id: sv_id - type: u1 - - id: reserved1 - size: 1 - - id: freq_id - type: u1 - - id: num_words - type: u1 - - id: reserved2 - size: 1 - - id: version - type: u1 - - id: reserved3 - size: 1 - - id: body - type: u4 - repeat: expr - repeat-expr: num_words - - rxm_rawx: - seq: - - id: rcv_tow - type: f8 - - id: week - type: u2 - - id: leap_s - type: s1 - - id: num_meas - type: u1 - - id: rec_stat - type: u1 - - id: reserved1 - size: 3 - - id: meas - type: measurement - size: 32 - repeat: expr - repeat-expr: num_meas - types: - measurement: - seq: - - id: pr_mes - type: f8 - - id: cp_mes - type: f8 - - id: do_mes - type: f4 - - id: gnss_id - type: u1 - enum: gnss_type - - id: sv_id - type: u1 - - id: reserved2 - size: 1 - - id: freq_id - type: u1 - - id: lock_time - type: u2 - - id: cno - type: u1 - - id: pr_stdev - type: u1 - - id: cp_stdev - type: u1 - - id: do_stdev - type: u1 - - id: trk_stat - type: u1 - - id: reserved3 - size: 1 - nav_sat: - seq: - - id: itow - type: u4 - - id: version - type: u1 - - id: num_svs - type: u1 - - id: reserved - size: 2 - - id: svs - type: nav - size: 12 - repeat: expr - repeat-expr: num_svs - types: - nav: - seq: - - id: gnss_id - type: u1 - enum: gnss_type - - id: sv_id - type: u1 - - id: cno - type: u1 - - id: elev - type: s1 - - id: azim - type: s2 - - id: pr_res - type: s2 - - id: flags - type: u4 - - nav_pvt: - seq: - - id: i_tow - type: u4 - - id: year - type: u2 - - id: month - type: u1 - - id: day - type: u1 - - id: hour - type: u1 - - id: min - type: u1 - - id: sec - type: u1 - - id: valid - type: u1 - - id: t_acc - type: u4 - - id: nano - type: s4 - - id: fix_type - type: u1 - - id: flags - type: u1 - - id: flags2 - type: u1 - - id: num_sv - type: u1 - - id: lon - type: s4 - - id: lat - type: s4 - - id: height - type: s4 - - id: h_msl - type: s4 - - id: h_acc - type: u4 - - id: v_acc - type: u4 - - id: vel_n - type: s4 - - id: vel_e - type: s4 - - id: vel_d - type: s4 - - id: g_speed - type: s4 - - id: head_mot - type: s4 - - id: s_acc - type: s4 - - id: head_acc - type: u4 - - id: p_dop - type: u2 - - id: flags3 - type: u1 - - id: reserved1 - size: 5 - - id: head_veh - type: s4 - - id: mag_dec - type: s2 - - id: mag_acc - type: u2 -enums: - gnss_type: - 0: gps - 1: sbas - 2: galileo - 3: beidou - 4: imes - 5: qzss - 6: glonass diff --git a/system/ui/README.md b/system/ui/README.md deleted file mode 100644 index 85d32bfd6c..0000000000 --- a/system/ui/README.md +++ /dev/null @@ -1,10 +0,0 @@ -# ui - -The user interfaces here are built with [raylib](https://www.raylib.com/). - -Quick start: -* set `SHOW_FPS=1` to show the FPS -* set `STRICT_MODE=1` to kill the app if it drops too much below 60fps -* set `SCALE=1.5` to scale the entire UI by 1.5x -* https://www.raylib.com/cheatsheet/cheatsheet.html -* https://electronstudio.github.io/raylib-python-cffi/README.html#quickstart diff --git a/system/ui/lib/application.py b/system/ui/lib/application.py deleted file mode 100644 index 805fdcc71f..0000000000 --- a/system/ui/lib/application.py +++ /dev/null @@ -1,305 +0,0 @@ -import atexit -import cffi -import os -import time -import pyray as rl -from collections.abc import Callable -from dataclasses import dataclass -from enum import IntEnum -from importlib.resources import as_file, files -from openpilot.common.swaglog import cloudlog -from openpilot.system.hardware import HARDWARE - -DEFAULT_FPS = 60 -FPS_LOG_INTERVAL = 5 # Seconds between logging FPS drops -FPS_DROP_THRESHOLD = 0.9 # FPS drop threshold for triggering a warning -FPS_CRITICAL_THRESHOLD = 0.5 # Critical threshold for triggering strict actions - -ENABLE_VSYNC = os.getenv("ENABLE_VSYNC", "1") == "1" -SHOW_FPS = os.getenv("SHOW_FPS") == '1' -STRICT_MODE = os.getenv("STRICT_MODE") == '1' -SCALE = float(os.getenv("SCALE", "1.0")) - -DEFAULT_TEXT_SIZE = 60 -DEFAULT_TEXT_COLOR = rl.WHITE - -ASSETS_DIR = files("openpilot.selfdrive").joinpath("assets") -FONT_DIR = ASSETS_DIR.joinpath("fonts") - - -class FontWeight(IntEnum): - THIN = 0 - EXTRA_LIGHT = 1 - LIGHT = 2 - NORMAL = 3 - MEDIUM = 4 - SEMI_BOLD = 5 - BOLD = 6 - EXTRA_BOLD = 7 - BLACK = 8 - - -@dataclass -class ModalOverlay: - overlay: object = None - callback: Callable | None = None - - -class GuiApplication: - def __init__(self, width: int, height: int): - self._fonts: dict[FontWeight, rl.Font] = {} - self._width = width - self._height = height - self._scale = SCALE - self._scaled_width = int(self._width * self._scale) - self._scaled_height = int(self._height * self._scale) - self._render_texture: rl.RenderTexture | None = None - self._textures: dict[str, rl.Texture] = {} - self._target_fps: int = DEFAULT_FPS - self._last_fps_log_time: float = time.monotonic() - self._window_close_requested = False - self._trace_log_callback = None - self._modal_overlay = ModalOverlay() - - def request_close(self): - self._window_close_requested = True - - def init_window(self, title: str, fps: int = DEFAULT_FPS): - atexit.register(self.close) # Automatically call close() on exit - - HARDWARE.set_display_power(True) - HARDWARE.set_screen_brightness(65) - - self._set_log_callback() - rl.set_trace_log_level(rl.TraceLogLevel.LOG_ALL) - - flags = rl.ConfigFlags.FLAG_MSAA_4X_HINT - if ENABLE_VSYNC: - flags |= rl.ConfigFlags.FLAG_VSYNC_HINT - rl.set_config_flags(flags) - - rl.init_window(self._scaled_width, self._scaled_height, title) - if self._scale != 1.0: - rl.set_mouse_scale(1 / self._scale, 1 / self._scale) - self._render_texture = rl.load_render_texture(self._width, self._height) - rl.set_texture_filter(self._render_texture.texture, rl.TextureFilter.TEXTURE_FILTER_BILINEAR) - rl.set_target_fps(fps) - - self._target_fps = fps - self._set_styles() - self._load_fonts() - - def set_modal_overlay(self, overlay, callback: Callable | None = None): - self._modal_overlay = ModalOverlay(overlay=overlay, callback=callback) - - def texture(self, asset_path: str, width: int, height: int, alpha_premultiply=False, keep_aspect_ratio=True): - cache_key = f"{asset_path}_{width}_{height}_{alpha_premultiply}{keep_aspect_ratio}" - if cache_key in self._textures: - return self._textures[cache_key] - - with as_file(ASSETS_DIR.joinpath(asset_path)) as fspath: - texture_obj = self._load_texture_from_image(fspath.as_posix(), width, height, alpha_premultiply, keep_aspect_ratio) - self._textures[cache_key] = texture_obj - return texture_obj - - def _load_texture_from_image(self, image_path: str, width: int, height: int, alpha_premultiply=False, keep_aspect_ratio=True): - """Load and resize a texture, storing it for later automatic unloading.""" - image = rl.load_image(image_path) - - if alpha_premultiply: - rl.image_alpha_premultiply(image) - - # Resize with aspect ratio preservation if requested - if keep_aspect_ratio: - orig_width = image.width - orig_height = image.height - - scale_width = width / orig_width - scale_height = height / orig_height - - # Calculate new dimensions - scale = min(scale_width, scale_height) - new_width = int(orig_width * scale) - new_height = int(orig_height * scale) - - rl.image_resize(image, new_width, new_height) - else: - rl.image_resize(image, width, height) - - texture = rl.load_texture_from_image(image) - # Set texture filtering to smooth the result - rl.set_texture_filter(texture, rl.TextureFilter.TEXTURE_FILTER_BILINEAR) - - rl.unload_image(image) - return texture - - def close(self): - if not rl.is_window_ready(): - return - - for texture in self._textures.values(): - rl.unload_texture(texture) - self._textures = {} - - for font in self._fonts.values(): - rl.unload_font(font) - self._fonts = {} - - if self._render_texture is not None: - rl.unload_render_texture(self._render_texture) - self._render_texture = None - - rl.close_window() - - def render(self): - try: - while not (self._window_close_requested or rl.window_should_close()): - if self._render_texture: - rl.begin_texture_mode(self._render_texture) - rl.clear_background(rl.BLACK) - else: - rl.begin_drawing() - rl.clear_background(rl.BLACK) - - # Handle modal overlay rendering and input processing - if self._modal_overlay.overlay: - if hasattr(self._modal_overlay.overlay, 'render'): - result = self._modal_overlay.overlay.render(rl.Rectangle(0, 0, self.width, self.height)) - elif callable(self._modal_overlay.overlay): - result = self._modal_overlay.overlay() - else: - raise Exception - - if result >= 0: - # Execute callback with the result and clear the overlay - if self._modal_overlay.callback is not None: - self._modal_overlay.callback(result) - - self._modal_overlay = ModalOverlay() - else: - yield - - if self._render_texture: - rl.end_texture_mode() - rl.begin_drawing() - rl.clear_background(rl.BLACK) - src_rect = rl.Rectangle(0, 0, float(self._width), -float(self._height)) - dst_rect = rl.Rectangle(0, 0, float(self._scaled_width), float(self._scaled_height)) - rl.draw_texture_pro(self._render_texture.texture, src_rect, dst_rect, rl.Vector2(0, 0), 0.0, rl.WHITE) - - if SHOW_FPS: - rl.draw_fps(10, 10) - - rl.end_drawing() - self._monitor_fps() - except KeyboardInterrupt: - pass - - def font(self, font_weight: FontWeight = FontWeight.NORMAL): - return self._fonts[font_weight] - - @property - def width(self): - return self._width - - @property - def height(self): - return self._height - - def _load_fonts(self): - font_files = ( - "Inter-Thin.ttf", - "Inter-ExtraLight.ttf", - "Inter-Light.ttf", - "Inter-Regular.ttf", - "Inter-Medium.ttf", - "Inter-SemiBold.ttf", - "Inter-Bold.ttf", - "Inter-ExtraBold.ttf", - "Inter-Black.ttf", - ) - - # Create a character set from our keyboard layouts - from openpilot.system.ui.widgets.keyboard import KEYBOARD_LAYOUTS - all_chars = set() - for layout in KEYBOARD_LAYOUTS.values(): - all_chars.update(key for row in layout for key in row) - all_chars = "".join(all_chars) - all_chars += "–✓°" - - codepoint_count = rl.ffi.new("int *", 1) - codepoints = rl.load_codepoints(all_chars, codepoint_count) - - for index, font_file in enumerate(font_files): - with as_file(FONT_DIR.joinpath(font_file)) as fspath: - font = rl.load_font_ex(fspath.as_posix(), 200, codepoints, codepoint_count[0]) - rl.set_texture_filter(font.texture, rl.TextureFilter.TEXTURE_FILTER_BILINEAR) - self._fonts[index] = font - - rl.unload_codepoints(codepoints) - rl.gui_set_font(self._fonts[FontWeight.NORMAL]) - - def _set_styles(self): - rl.gui_set_style(rl.GuiControl.DEFAULT, rl.GuiControlProperty.BORDER_WIDTH, 0) - rl.gui_set_style(rl.GuiControl.DEFAULT, rl.GuiDefaultProperty.TEXT_SIZE, DEFAULT_TEXT_SIZE) - rl.gui_set_style(rl.GuiControl.DEFAULT, rl.GuiDefaultProperty.BACKGROUND_COLOR, rl.color_to_int(rl.BLACK)) - rl.gui_set_style(rl.GuiControl.DEFAULT, rl.GuiControlProperty.TEXT_COLOR_NORMAL, rl.color_to_int(DEFAULT_TEXT_COLOR)) - rl.gui_set_style(rl.GuiControl.DEFAULT, rl.GuiControlProperty.BASE_COLOR_NORMAL, rl.color_to_int(rl.Color(50, 50, 50, 255))) - - def _set_log_callback(self): - ffi_libc = cffi.FFI() - ffi_libc.cdef(""" - int vasprintf(char **strp, const char *fmt, void *ap); - void free(void *ptr); - """) - libc = ffi_libc.dlopen(None) - - @rl.ffi.callback("void(int, char *, void *)") - def trace_log_callback(log_level, text, args): - try: - text_addr = int(rl.ffi.cast("uintptr_t", text)) - args_addr = int(rl.ffi.cast("uintptr_t", args)) - text_libc = ffi_libc.cast("char *", text_addr) - args_libc = ffi_libc.cast("void *", args_addr) - - out = ffi_libc.new("char **") - if libc.vasprintf(out, text_libc, args_libc) >= 0 and out[0] != ffi_libc.NULL: - text_str = ffi_libc.string(out[0]).decode("utf-8", "replace") - libc.free(out[0]) - else: - text_str = rl.ffi.string(text).decode("utf-8", "replace") - except Exception as e: - text_str = f"[Log decode error: {e}]" - - if log_level == rl.TraceLogLevel.LOG_ERROR: - cloudlog.error(f"raylib: {text_str}") - elif log_level == rl.TraceLogLevel.LOG_WARNING: - cloudlog.warning(f"raylib: {text_str}") - elif log_level == rl.TraceLogLevel.LOG_INFO: - cloudlog.info(f"raylib: {text_str}") - elif log_level == rl.TraceLogLevel.LOG_DEBUG: - cloudlog.debug(f"raylib: {text_str}") - else: - cloudlog.error(f"raylib: Unknown level {log_level}: {text_str}") - - # Store callback reference - self._trace_log_callback = trace_log_callback - rl.set_trace_log_callback(self._trace_log_callback) - - def _monitor_fps(self): - fps = rl.get_fps() - - # Log FPS drop below threshold at regular intervals - if fps < self._target_fps * FPS_DROP_THRESHOLD: - current_time = time.monotonic() - if current_time - self._last_fps_log_time >= FPS_LOG_INTERVAL: - cloudlog.warning(f"FPS dropped below {self._target_fps}: {fps}") - self._last_fps_log_time = current_time - - # Strict mode: terminate UI if FPS drops too much - if STRICT_MODE and fps < self._target_fps * FPS_CRITICAL_THRESHOLD: - cloudlog.error(f"FPS dropped critically below {fps}. Shutting down UI.") - os._exit(1) - - -gui_app = GuiApplication(2160, 1080) diff --git a/system/ui/lib/button.py b/system/ui/lib/button.py deleted file mode 100644 index 121e7f86fa..0000000000 --- a/system/ui/lib/button.py +++ /dev/null @@ -1,148 +0,0 @@ -import pyray as rl -from enum import IntEnum -from openpilot.system.ui.lib.application import gui_app, FontWeight -from openpilot.system.ui.lib.text_measure import measure_text_cached - - -class ButtonStyle(IntEnum): - NORMAL = 0 # Most common, neutral buttons - PRIMARY = 1 # For main actions - DANGER = 2 # For critical actions, like reboot or delete - TRANSPARENT = 3 # For buttons with transparent background and border - ACTION = 4 - LIST_ACTION = 5 # For list items with action buttons - - -class TextAlignment(IntEnum): - LEFT = 0 - CENTER = 1 - RIGHT = 2 - - -ICON_PADDING = 15 -DEFAULT_BUTTON_FONT_SIZE = 60 -BUTTON_DISABLED_TEXT_COLOR = rl.Color(228, 228, 228, 51) -ACTION_BUTTON_FONT_SIZE = 48 - -BUTTON_TEXT_COLOR = { - ButtonStyle.NORMAL: rl.Color(228, 228, 228, 255), - ButtonStyle.PRIMARY: rl.Color(228, 228, 228, 255), - ButtonStyle.DANGER: rl.Color(228, 228, 228, 255), - ButtonStyle.TRANSPARENT: rl.BLACK, - ButtonStyle.ACTION: rl.Color(0, 0, 0, 255), - ButtonStyle.LIST_ACTION: rl.Color(228, 228, 228, 255), -} - -BUTTON_BACKGROUND_COLORS = { - ButtonStyle.NORMAL: rl.Color(51, 51, 51, 255), - ButtonStyle.PRIMARY: rl.Color(70, 91, 234, 255), - ButtonStyle.DANGER: rl.Color(255, 36, 36, 255), - ButtonStyle.TRANSPARENT: rl.BLACK, - ButtonStyle.ACTION: rl.Color(189, 189, 189, 255), - ButtonStyle.LIST_ACTION: rl.Color(57, 57, 57, 255), -} - -BUTTON_PRESSED_BACKGROUND_COLORS = { - ButtonStyle.NORMAL: rl.Color(74, 74, 74, 255), - ButtonStyle.PRIMARY: rl.Color(48, 73, 244, 255), - ButtonStyle.DANGER: rl.Color(255, 36, 36, 255), - ButtonStyle.TRANSPARENT: rl.BLACK, - ButtonStyle.ACTION: rl.Color(130, 130, 130, 255), - ButtonStyle.LIST_ACTION: rl.Color(74, 74, 74, 74), -} - -_pressed_buttons: set[str] = set() # Track mouse press state globally - - -def gui_button( - rect: rl.Rectangle, - text: str, - font_size: int = DEFAULT_BUTTON_FONT_SIZE, - font_weight: FontWeight = FontWeight.MEDIUM, - button_style: ButtonStyle = ButtonStyle.NORMAL, - is_enabled: bool = True, - border_radius: int = 10, # Corner rounding in pixels - text_alignment: TextAlignment = TextAlignment.CENTER, - text_padding: int = 20, # Padding for left/right alignment - icon=None, -) -> int: - button_id = f"{rect.x}_{rect.y}_{rect.width}_{rect.height}" - result = 0 - - if button_style in (ButtonStyle.PRIMARY, ButtonStyle.DANGER) and not is_enabled: - button_style = ButtonStyle.NORMAL - - if button_style == ButtonStyle.ACTION and font_size == DEFAULT_BUTTON_FONT_SIZE: - font_size = ACTION_BUTTON_FONT_SIZE - - # Set background color based on button type - bg_color = BUTTON_BACKGROUND_COLORS[button_style] - mouse_over = is_enabled and rl.check_collision_point_rec(rl.get_mouse_position(), rect) - is_pressed = button_id in _pressed_buttons - - if mouse_over: - if rl.is_mouse_button_pressed(rl.MouseButton.MOUSE_BUTTON_LEFT): - # Only this button enters pressed state - _pressed_buttons.add(button_id) - is_pressed = True - - # Use pressed color when mouse is down over this button - if is_pressed and rl.is_mouse_button_down(rl.MouseButton.MOUSE_BUTTON_LEFT): - bg_color = BUTTON_PRESSED_BACKGROUND_COLORS[button_style] - - # Handle button click - if rl.is_mouse_button_released(rl.MouseButton.MOUSE_BUTTON_LEFT) and is_pressed: - result = 1 - _pressed_buttons.remove(button_id) - - # Clean up pressed state if mouse is released anywhere - if rl.is_mouse_button_released(rl.MouseButton.MOUSE_BUTTON_LEFT) and button_id in _pressed_buttons: - _pressed_buttons.remove(button_id) - - # Draw the button with rounded corners - roundness = border_radius / (min(rect.width, rect.height) / 2) - if button_style != ButtonStyle.TRANSPARENT: - rl.draw_rectangle_rounded(rect, roundness, 20, bg_color) - else: - rl.draw_rectangle_rounded(rect, roundness, 20, rl.BLACK) - rl.draw_rectangle_rounded_lines_ex(rect, roundness, 20, 2, rl.WHITE) - - # Handle icon and text positioning - font = gui_app.font(font_weight) - text_size = measure_text_cached(font, text, font_size) - text_pos = rl.Vector2(0, rect.y + (rect.height - text_size.y) // 2) # Vertical centering - - # Draw icon if provided - if icon: - icon_y = rect.y + (rect.height - icon.height) / 2 - if text: - if text_alignment == TextAlignment.LEFT: - icon_x = rect.x + text_padding - text_pos.x = icon_x + icon.width + ICON_PADDING - elif text_alignment == TextAlignment.CENTER: - total_width = icon.width + ICON_PADDING + text_size.x - icon_x = rect.x + (rect.width - total_width) / 2 - text_pos.x = icon_x + icon.width + ICON_PADDING - else: # RIGHT - text_pos.x = rect.x + rect.width - text_size.x - text_padding - icon_x = text_pos.x - ICON_PADDING - icon.width - else: - # Center icon when no text - icon_x = rect.x + (rect.width - icon.width) / 2 - - rl.draw_texture_v(icon, rl.Vector2(icon_x, icon_y), rl.WHITE if is_enabled else rl.Color(255, 255, 255, 100)) - else: - # No icon, position text normally - if text_alignment == TextAlignment.LEFT: - text_pos.x = rect.x + text_padding - elif text_alignment == TextAlignment.CENTER: - text_pos.x = rect.x + (rect.width - text_size.x) // 2 - elif text_alignment == TextAlignment.RIGHT: - text_pos.x = rect.x + rect.width - text_size.x - text_padding - - # Draw the button text if any - if text: - color = BUTTON_TEXT_COLOR[button_style] if is_enabled else BUTTON_DISABLED_TEXT_COLOR - rl.draw_text_ex(font, text, text_pos, font_size, 0, color) - - return result diff --git a/system/ui/lib/label.py b/system/ui/lib/label.py deleted file mode 100644 index c3d0e0303a..0000000000 --- a/system/ui/lib/label.py +++ /dev/null @@ -1,78 +0,0 @@ -import pyray as rl -from openpilot.system.ui.lib.application import gui_app, FontWeight, DEFAULT_TEXT_SIZE, DEFAULT_TEXT_COLOR -from openpilot.system.ui.lib.text_measure import measure_text_cached -from openpilot.system.ui.lib.utils import GuiStyleContext - - -def gui_label( - rect: rl.Rectangle, - text: str, - font_size: int = DEFAULT_TEXT_SIZE, - color: rl.Color = DEFAULT_TEXT_COLOR, - font_weight: FontWeight = FontWeight.NORMAL, - alignment: int = rl.GuiTextAlignment.TEXT_ALIGN_LEFT, - alignment_vertical: int = rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE, - elide_right: bool = True -): - font = gui_app.font(font_weight) - text_size = measure_text_cached(font, text, font_size) - display_text = text - - # Elide text to fit within the rectangle - if elide_right and text_size.x > rect.width: - ellipsis = "..." - left, right = 0, len(text) - while left < right: - mid = (left + right) // 2 - candidate = text[:mid] + ellipsis - candidate_size = measure_text_cached(font, candidate, font_size) - if candidate_size.x <= rect.width: - left = mid + 1 - else: - right = mid - display_text = text[: left - 1] + ellipsis if left > 0 else ellipsis - text_size = measure_text_cached(font, display_text, font_size) - - # Calculate horizontal position based on alignment - text_x = rect.x + { - rl.GuiTextAlignment.TEXT_ALIGN_LEFT: 0, - rl.GuiTextAlignment.TEXT_ALIGN_CENTER: (rect.width - text_size.x) / 2, - rl.GuiTextAlignment.TEXT_ALIGN_RIGHT: rect.width - text_size.x, - }.get(alignment, 0) - - # Calculate vertical position based on alignment - text_y = rect.y + { - rl.GuiTextAlignmentVertical.TEXT_ALIGN_TOP: 0, - rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE: (rect.height - text_size.y) / 2, - rl.GuiTextAlignmentVertical.TEXT_ALIGN_BOTTOM: rect.height - text_size.y, - }.get(alignment_vertical, 0) - - # Draw the text in the specified rectangle - rl.draw_text_ex(font, display_text, rl.Vector2(text_x, text_y), font_size, 0, color) - - -def gui_text_box( - rect: rl.Rectangle, - text: str, - font_size: int = DEFAULT_TEXT_SIZE, - color: rl.Color = DEFAULT_TEXT_COLOR, - alignment: int = rl.GuiTextAlignment.TEXT_ALIGN_LEFT, - alignment_vertical: int = rl.GuiTextAlignmentVertical.TEXT_ALIGN_TOP, - font_weight: FontWeight = FontWeight.NORMAL, -): - styles = [ - (rl.GuiControl.DEFAULT, rl.GuiControlProperty.TEXT_COLOR_NORMAL, rl.color_to_int(color)), - (rl.GuiControl.DEFAULT, rl.GuiDefaultProperty.TEXT_SIZE, font_size), - (rl.GuiControl.DEFAULT, rl.GuiDefaultProperty.TEXT_LINE_SPACING, font_size), - (rl.GuiControl.DEFAULT, rl.GuiControlProperty.TEXT_ALIGNMENT, alignment), - (rl.GuiControl.DEFAULT, rl.GuiDefaultProperty.TEXT_ALIGNMENT_VERTICAL, alignment_vertical), - (rl.GuiControl.DEFAULT, rl.GuiDefaultProperty.TEXT_WRAP_MODE, rl.GuiTextWrapMode.TEXT_WRAP_WORD) - ] - if font_weight != FontWeight.NORMAL: - rl.gui_set_font(gui_app.font(font_weight)) - - with GuiStyleContext(styles): - rl.gui_label(rect, text) - - if font_weight != FontWeight.NORMAL: - rl.gui_set_font(gui_app.font(FontWeight.NORMAL)) diff --git a/system/ui/lib/list_view.py b/system/ui/lib/list_view.py deleted file mode 100644 index f5581be23e..0000000000 --- a/system/ui/lib/list_view.py +++ /dev/null @@ -1,368 +0,0 @@ -import os -import pyray as rl -from collections.abc import Callable -from abc import ABC -from openpilot.system.ui.lib.application import gui_app, FontWeight -from openpilot.system.ui.lib.text_measure import measure_text_cached -from openpilot.system.ui.lib.wrap_text import wrap_text -from openpilot.system.ui.lib.button import gui_button, ButtonStyle -from openpilot.system.ui.lib.toggle import Toggle, WIDTH as TOGGLE_WIDTH, HEIGHT as TOGGLE_HEIGHT -from openpilot.system.ui.lib.widget import Widget - -ITEM_BASE_WIDTH = 600 -ITEM_BASE_HEIGHT = 170 -ITEM_PADDING = 20 -ITEM_TEXT_FONT_SIZE = 50 -ITEM_TEXT_COLOR = rl.WHITE -ITEM_DESC_TEXT_COLOR = rl.Color(128, 128, 128, 255) -ITEM_DESC_FONT_SIZE = 40 -ITEM_DESC_V_OFFSET = 140 -RIGHT_ITEM_PADDING = 20 -ICON_SIZE = 80 -BUTTON_WIDTH = 250 -BUTTON_HEIGHT = 100 -BUTTON_BORDER_RADIUS = 50 -BUTTON_FONT_SIZE = 35 -BUTTON_FONT_WEIGHT = FontWeight.MEDIUM - -TEXT_PADDING = 20 - - -def _resolve_value(value, default=""): - if callable(value): - return value() - return value if value is not None else default - - -# Abstract base class for right-side items -class ItemAction(Widget, ABC): - def __init__(self, width: int = BUTTON_HEIGHT, enabled: bool | Callable[[], bool] = True): - super().__init__() - self.set_rect(rl.Rectangle(0, 0, width, 0)) - self._enabled_source = enabled - - @property - def enabled(self): - return _resolve_value(self._enabled_source, False) - - -class ToggleAction(ItemAction): - def __init__(self, initial_state: bool = False, width: int = TOGGLE_WIDTH, enabled: bool | Callable[[], bool] = True): - super().__init__(width, enabled) - self.toggle = Toggle(initial_state=initial_state) - self.state = initial_state - - def set_touch_valid_callback(self, touch_callback: Callable[[], bool]) -> None: - super().set_touch_valid_callback(touch_callback) - self.toggle.set_touch_valid_callback(touch_callback) - - def _render(self, rect: rl.Rectangle) -> bool: - self.toggle.set_enabled(self.enabled) - self.toggle.render(rl.Rectangle(rect.x, rect.y + (rect.height - TOGGLE_HEIGHT) / 2, self._rect.width, TOGGLE_HEIGHT)) - return False - - def set_state(self, state: bool): - self.state = state - self.toggle.set_state(state) - - def get_state(self) -> bool: - return self.state - - -class ButtonAction(ItemAction): - def __init__(self, text: str | Callable[[], str], width: int = BUTTON_WIDTH, enabled: bool | Callable[[], bool] = True): - super().__init__(width, enabled) - self._text_source = text - - @property - def text(self): - return _resolve_value(self._text_source, "Error") - - def _render(self, rect: rl.Rectangle) -> bool: - return gui_button( - rl.Rectangle(rect.x, rect.y + (rect.height - BUTTON_HEIGHT) / 2, BUTTON_WIDTH, BUTTON_HEIGHT), - self.text, - border_radius=BUTTON_BORDER_RADIUS, - font_weight=BUTTON_FONT_WEIGHT, - font_size=BUTTON_FONT_SIZE, - button_style=ButtonStyle.LIST_ACTION, - is_enabled=self.enabled, - ) == 1 - - -class TextAction(ItemAction): - def __init__(self, text: str | Callable[[], str], color: rl.Color = ITEM_TEXT_COLOR, enabled: bool | Callable[[], bool] = True): - self._text_source = text - self.color = color - - self._font = gui_app.font(FontWeight.NORMAL) - initial_text = _resolve_value(text, "") - text_width = measure_text_cached(self._font, initial_text, ITEM_TEXT_FONT_SIZE).x - super().__init__(int(text_width + TEXT_PADDING), enabled) - - @property - def text(self): - return _resolve_value(self._text_source, "Error") - - def _render(self, rect: rl.Rectangle) -> bool: - current_text = self.text - text_size = measure_text_cached(self._font, current_text, ITEM_TEXT_FONT_SIZE) - - text_x = rect.x + (rect.width - text_size.x) / 2 - text_y = rect.y + (rect.height - text_size.y) / 2 - rl.draw_text_ex(self._font, current_text, rl.Vector2(text_x, text_y), ITEM_TEXT_FONT_SIZE, 0, self.color) - return False - - def get_width(self) -> int: - text_width = measure_text_cached(self._font, self.text, ITEM_TEXT_FONT_SIZE).x - return int(text_width + TEXT_PADDING) - - -class DualButtonAction(ItemAction): - def __init__(self, left_text: str, right_text: str, left_callback: Callable = None, - right_callback: Callable = None, enabled: bool | Callable[[], bool] = True): - super().__init__(width=0, enabled=enabled) # Width 0 means use full width - self.left_text, self.right_text = left_text, right_text - self.left_callback, self.right_callback = left_callback, right_callback - - def _render(self, rect: rl.Rectangle) -> bool: - button_spacing = 30 - button_height = 120 - button_width = (rect.width - button_spacing) / 2 - button_y = rect.y + (rect.height - button_height) / 2 - - left_rect = rl.Rectangle(rect.x, button_y, button_width, button_height) - right_rect = rl.Rectangle(rect.x + button_width + button_spacing, button_y, button_width, button_height) - - left_clicked = gui_button(left_rect, self.left_text, button_style=ButtonStyle.LIST_ACTION) == 1 - right_clicked = gui_button(right_rect, self.right_text, button_style=ButtonStyle.DANGER) == 1 - - if left_clicked and self.left_callback: - self.left_callback() - return True - if right_clicked and self.right_callback: - self.right_callback() - return True - return False - - -class MultipleButtonAction(ItemAction): - def __init__(self, buttons: list[str], button_width: int, selected_index: int = 0, callback: Callable = None): - super().__init__(width=len(buttons) * (button_width + 20), enabled=True) - self.buttons = buttons - self.button_width = button_width - self.selected_button = selected_index - self.callback = callback - self._font = gui_app.font(FontWeight.MEDIUM) - - def _render(self, rect: rl.Rectangle) -> bool: - spacing = 20 - button_y = rect.y + (rect.height - BUTTON_HEIGHT) / 2 - clicked = -1 - - for i, text in enumerate(self.buttons): - button_x = rect.x + i * (self.button_width + spacing) - button_rect = rl.Rectangle(button_x, button_y, self.button_width, BUTTON_HEIGHT) - - # Check button state - mouse_pos = rl.get_mouse_position() - is_hovered = rl.check_collision_point_rec(mouse_pos, button_rect) - is_pressed = is_hovered and rl.is_mouse_button_down(rl.MouseButton.MOUSE_BUTTON_LEFT) and self._is_pressed - is_selected = i == self.selected_button - - # Button colors - if is_selected: - bg_color = rl.Color(51, 171, 76, 255) # Green - elif is_pressed: - bg_color = rl.Color(74, 74, 74, 255) # Dark gray - else: - bg_color = rl.Color(57, 57, 57, 255) # Gray - - # Draw button - rl.draw_rectangle_rounded(button_rect, 1.0, 20, bg_color) - - # Draw text - text_size = measure_text_cached(self._font, text, 40) - text_x = button_x + (self.button_width - text_size.x) / 2 - text_y = button_y + (BUTTON_HEIGHT - text_size.y) / 2 - rl.draw_text_ex(self._font, text, rl.Vector2(text_x, text_y), 40, 0, rl.Color(228, 228, 228, 255)) - - # Handle click - if is_hovered and rl.is_mouse_button_released(rl.MouseButton.MOUSE_BUTTON_LEFT) and self._is_pressed: - clicked = i - - if clicked >= 0: - self.selected_button = clicked - if self.callback: - self.callback(clicked) - return True - return False - - -class ListItem(Widget): - def __init__(self, title: str = "", icon: str | None = None, description: str | Callable[[], str] | None = None, - description_visible: bool = False, callback: Callable | None = None, - action_item: ItemAction | None = None): - super().__init__() - self.title = title - self.icon = icon - self.description = description - self.description_visible = description_visible - self.callback = callback - self.action_item = action_item - - self.set_rect(rl.Rectangle(0, 0, ITEM_BASE_WIDTH, ITEM_BASE_HEIGHT)) - self._font = gui_app.font(FontWeight.NORMAL) - - # Cached properties for performance - self._prev_max_width: int = 0 - self._wrapped_description: str | None = None - self._prev_description: str | None = None - self._description_height: float = 0 - - def set_touch_valid_callback(self, touch_callback: Callable[[], bool]) -> None: - super().set_touch_valid_callback(touch_callback) - if self.action_item: - self.action_item.set_touch_valid_callback(touch_callback) - - def set_parent_rect(self, parent_rect: rl.Rectangle): - super().set_parent_rect(parent_rect) - self._rect.width = parent_rect.width - - def _handle_mouse_release(self, mouse_pos: rl.Vector2): - if not self.is_visible: - return - - # Check not in action rect - if self.action_item: - action_rect = self.get_right_item_rect(self._rect) - if rl.check_collision_point_rec(mouse_pos, action_rect): - # Click was on right item, don't toggle description - return - - if self.description: - self.description_visible = not self.description_visible - content_width = self.get_content_width(int(self._rect.width - ITEM_PADDING * 2)) - self._rect.height = self.get_item_height(self._font, content_width) - - def _render(self, _): - if not self.is_visible: - return - - # Don't draw items that are not in parent's viewport - if ((self._rect.y + self.rect.height) <= self._parent_rect.y or - self._rect.y >= (self._parent_rect.y + self._parent_rect.height)): - return - - content_x = self._rect.x + ITEM_PADDING - text_x = content_x - - # Only draw title and icon for items that have them - if self.title: - # Draw icon if present - if self.icon: - icon_texture = gui_app.texture(os.path.join("icons", self.icon), ICON_SIZE, ICON_SIZE) - rl.draw_texture(icon_texture, int(content_x), int(self._rect.y + (ITEM_BASE_HEIGHT - icon_texture.width) // 2), rl.WHITE) - text_x += ICON_SIZE + ITEM_PADDING - - # Draw main text - text_size = measure_text_cached(self._font, self.title, ITEM_TEXT_FONT_SIZE) - item_y = self._rect.y + (ITEM_BASE_HEIGHT - text_size.y) // 2 - rl.draw_text_ex(self._font, self.title, rl.Vector2(text_x, item_y), ITEM_TEXT_FONT_SIZE, 0, ITEM_TEXT_COLOR) - - # Draw description if visible - current_description = self.get_description() - if self.description_visible and current_description and self._wrapped_description: - rl.draw_text_ex( - self._font, - self._wrapped_description, - rl.Vector2(text_x, self._rect.y + ITEM_DESC_V_OFFSET), - ITEM_DESC_FONT_SIZE, - 0, - ITEM_DESC_TEXT_COLOR, - ) - - # Draw right item if present - if self.action_item: - right_rect = self.get_right_item_rect(self._rect) - right_rect.y = self._rect.y - if self.action_item.render(right_rect) and self.action_item.enabled: - # Right item was clicked/activated - if self.callback: - self.callback() - - def get_description(self): - return _resolve_value(self.description, None) - - def get_item_height(self, font: rl.Font, max_width: int) -> float: - if not self.is_visible: - return 0 - - current_description = self.get_description() - if self.description_visible and current_description: - if ( - not self._wrapped_description - or current_description != self._prev_description - or max_width != self._prev_max_width - ): - self._prev_max_width = max_width - self._prev_description = current_description - - wrapped_lines = wrap_text(font, current_description, ITEM_DESC_FONT_SIZE, max_width) - self._wrapped_description = "\n".join(wrapped_lines) - self._description_height = len(wrapped_lines) * ITEM_DESC_FONT_SIZE + 10 - return ITEM_BASE_HEIGHT + self._description_height - (ITEM_BASE_HEIGHT - ITEM_DESC_V_OFFSET) + ITEM_PADDING - return ITEM_BASE_HEIGHT - - def get_content_width(self, total_width: int) -> int: - if self.action_item and self.action_item.rect.width > 0: - return total_width - int(self.action_item.rect.width) - RIGHT_ITEM_PADDING - return total_width - - def get_right_item_rect(self, item_rect: rl.Rectangle) -> rl.Rectangle: - if not self.action_item: - return rl.Rectangle(0, 0, 0, 0) - - right_width = self.action_item.rect.width - if right_width == 0: # Full width action (like DualButtonAction) - return rl.Rectangle(item_rect.x + ITEM_PADDING, item_rect.y, - item_rect.width - (ITEM_PADDING * 2), ITEM_BASE_HEIGHT) - - right_x = item_rect.x + item_rect.width - right_width - right_y = item_rect.y - return rl.Rectangle(right_x, right_y, right_width, ITEM_BASE_HEIGHT) - - -# Factory functions -def simple_item(title: str, callback: Callable | None = None) -> ListItem: - return ListItem(title=title, callback=callback) - - -def toggle_item(title: str, description: str | Callable[[], str] | None = None, initial_state: bool = False, - callback: Callable | None = None, icon: str = "", enabled: bool | Callable[[], bool] = True) -> ListItem: - action = ToggleAction(initial_state=initial_state, enabled=enabled) - return ListItem(title=title, description=description, action_item=action, icon=icon, callback=callback) - - -def button_item(title: str, button_text: str | Callable[[], str], description: str | Callable[[], str] | None = None, - callback: Callable | None = None, enabled: bool | Callable[[], bool] = True) -> ListItem: - action = ButtonAction(text=button_text, enabled=enabled) - return ListItem(title=title, description=description, action_item=action, callback=callback) - - -def text_item(title: str, value: str | Callable[[], str], description: str | Callable[[], str] | None = None, - callback: Callable | None = None, enabled: bool | Callable[[], bool] = True) -> ListItem: - action = TextAction(text=value, color=rl.Color(170, 170, 170, 255), enabled=enabled) - return ListItem(title=title, description=description, action_item=action, callback=callback) - - -def dual_button_item(left_text: str, right_text: str, left_callback: Callable = None, right_callback: Callable = None, - description: str | Callable[[], str] | None = None, enabled: bool | Callable[[], bool] = True) -> ListItem: - action = DualButtonAction(left_text, right_text, left_callback, right_callback, enabled) - return ListItem(title="", description=description, action_item=action) - - -def multiple_button_item(title: str, description: str, buttons: list[str], selected_index: int, - button_width: int = BUTTON_WIDTH, callback: Callable = None, icon: str = ""): - action = MultipleButtonAction(buttons, button_width, selected_index, callback=callback) - return ListItem(title=title, description=description, icon=icon, action_item=action) diff --git a/system/ui/lib/scroll_panel.py b/system/ui/lib/scroll_panel.py deleted file mode 100644 index 32f3b7b575..0000000000 --- a/system/ui/lib/scroll_panel.py +++ /dev/null @@ -1,185 +0,0 @@ -import pyray as rl -from collections import deque -from enum import IntEnum - -# Scroll constants for smooth scrolling behavior -MOUSE_WHEEL_SCROLL_SPEED = 30 -INERTIA_FRICTION = 0.92 # The rate at which the inertia slows down -MIN_VELOCITY = 0.5 # Minimum velocity before stopping the inertia -DRAG_THRESHOLD = 12 # Pixels of movement to consider it a drag, not a click -BOUNCE_FACTOR = 0.2 # Elastic bounce when scrolling past boundaries -BOUNCE_RETURN_SPEED = 0.15 # How quickly it returns from the bounce -MAX_BOUNCE_DISTANCE = 150 # Maximum distance for bounce effect -FLICK_MULTIPLIER = 1.8 # Multiplier for flick gestures -VELOCITY_HISTORY_SIZE = 5 # Track velocity over multiple frames for smoother motion - - -class ScrollState(IntEnum): - IDLE = 0 - DRAGGING_CONTENT = 1 - DRAGGING_SCROLLBAR = 2 - BOUNCING = 3 - - -class GuiScrollPanel: - def __init__(self, show_vertical_scroll_bar: bool = False): - self._scroll_state: ScrollState = ScrollState.IDLE - self._last_mouse_y: float = 0.0 - self._start_mouse_y: float = 0.0 # Track the initial mouse position for drag detection - self._offset = rl.Vector2(0, 0) - self._view = rl.Rectangle(0, 0, 0, 0) - self._show_vertical_scroll_bar: bool = show_vertical_scroll_bar - self._velocity_y = 0.0 # Velocity for inertia - self._is_dragging: bool = False - self._bounce_offset: float = 0.0 - self._velocity_history: deque[float] = deque(maxlen=VELOCITY_HISTORY_SIZE) - self._last_drag_time: float = 0.0 - self._content_rect: rl.Rectangle | None = None - self._bounds_rect: rl.Rectangle | None = None - - def handle_scroll(self, bounds: rl.Rectangle, content: rl.Rectangle) -> rl.Vector2: - # Store rectangles for reference - self._content_rect = content - self._bounds_rect = bounds - - # Calculate time delta - current_time = rl.get_time() - - mouse_pos = rl.get_mouse_position() - max_scroll_y = max(content.height - bounds.height, 0) - - # Start dragging on mouse press - if rl.check_collision_point_rec(mouse_pos, bounds) and rl.is_mouse_button_pressed(rl.MouseButton.MOUSE_BUTTON_LEFT): - if self._scroll_state == ScrollState.IDLE or self._scroll_state == ScrollState.BOUNCING: - self._scroll_state = ScrollState.DRAGGING_CONTENT - if self._show_vertical_scroll_bar: - scrollbar_width = rl.gui_get_style(rl.GuiControl.LISTVIEW, rl.GuiListViewProperty.SCROLLBAR_WIDTH) - scrollbar_x = bounds.x + bounds.width - scrollbar_width - if mouse_pos.x >= scrollbar_x: - self._scroll_state = ScrollState.DRAGGING_SCROLLBAR - - # TODO: hacky - # when clicking while moving, go straight into dragging - self._is_dragging = abs(self._velocity_y) > MIN_VELOCITY - self._last_mouse_y = mouse_pos.y - self._start_mouse_y = mouse_pos.y - self._last_drag_time = current_time - self._velocity_history.clear() - self._velocity_y = 0.0 - self._bounce_offset = 0.0 - - # Handle active dragging - if self._scroll_state == ScrollState.DRAGGING_CONTENT or self._scroll_state == ScrollState.DRAGGING_SCROLLBAR: - if rl.is_mouse_button_down(rl.MouseButton.MOUSE_BUTTON_LEFT): - delta_y = mouse_pos.y - self._last_mouse_y - - # Track velocity for inertia - time_since_last_drag = current_time - self._last_drag_time - if time_since_last_drag > 0: - drag_velocity = delta_y / time_since_last_drag / 60.0 - self._velocity_history.append(drag_velocity) - - self._last_drag_time = current_time - - # Detect actual dragging - total_drag = abs(mouse_pos.y - self._start_mouse_y) - if total_drag > DRAG_THRESHOLD: - self._is_dragging = True - - if self._scroll_state == ScrollState.DRAGGING_CONTENT: - # Add resistance at boundaries - if (self._offset.y > 0 and delta_y > 0) or (self._offset.y < -max_scroll_y and delta_y < 0): - delta_y *= BOUNCE_FACTOR - - self._offset.y += delta_y - elif self._scroll_state == ScrollState.DRAGGING_SCROLLBAR: - scroll_ratio = content.height / bounds.height - self._offset.y -= delta_y * scroll_ratio - - self._last_mouse_y = mouse_pos.y - - elif rl.is_mouse_button_released(rl.MouseButton.MOUSE_BUTTON_LEFT): - # Calculate flick velocity - if self._velocity_history: - total_weight = 0 - weighted_velocity = 0.0 - - for i, v in enumerate(self._velocity_history): - weight = i + 1 - weighted_velocity += v * weight - total_weight += weight - - if total_weight > 0: - avg_velocity = weighted_velocity / total_weight - self._velocity_y = avg_velocity * FLICK_MULTIPLIER - - # Check bounds - if self._offset.y > 0 or self._offset.y < -max_scroll_y: - self._scroll_state = ScrollState.BOUNCING - else: - self._scroll_state = ScrollState.IDLE - - # Handle mouse wheel - wheel_move = rl.get_mouse_wheel_move() - if wheel_move != 0: - self._velocity_y = 0.0 - - if self._show_vertical_scroll_bar: - self._offset.y += wheel_move * (MOUSE_WHEEL_SCROLL_SPEED - 20) - rl.gui_scroll_panel(bounds, rl.ffi.NULL, content, self._offset, self._view) - else: - self._offset.y += wheel_move * MOUSE_WHEEL_SCROLL_SPEED - - if self._offset.y > 0 or self._offset.y < -max_scroll_y: - self._scroll_state = ScrollState.BOUNCING - - # Apply inertia (continue scrolling after mouse release) - if self._scroll_state == ScrollState.IDLE: - if abs(self._velocity_y) > MIN_VELOCITY: - self._offset.y += self._velocity_y - self._velocity_y *= INERTIA_FRICTION - - if self._offset.y > 0 or self._offset.y < -max_scroll_y: - self._scroll_state = ScrollState.BOUNCING - else: - self._velocity_y = 0.0 - - # Handle bouncing effect - elif self._scroll_state == ScrollState.BOUNCING: - target_y = 0.0 - if self._offset.y < -max_scroll_y: - target_y = -max_scroll_y - - distance = target_y - self._offset.y - bounce_step = distance * BOUNCE_RETURN_SPEED - self._offset.y += bounce_step - self._velocity_y *= INERTIA_FRICTION * 0.8 - - if abs(distance) < 0.5 and abs(self._velocity_y) < MIN_VELOCITY: - self._offset.y = target_y - self._velocity_y = 0.0 - self._scroll_state = ScrollState.IDLE - - # Limit bounce distance - if self._scroll_state != ScrollState.DRAGGING_CONTENT: - if self._offset.y > MAX_BOUNCE_DISTANCE: - self._offset.y = MAX_BOUNCE_DISTANCE - elif self._offset.y < -(max_scroll_y + MAX_BOUNCE_DISTANCE): - self._offset.y = -(max_scroll_y + MAX_BOUNCE_DISTANCE) - - return self._offset - - def is_touch_valid(self): - return not self._is_dragging - - def get_normalized_scroll_position(self) -> float: - """Returns the current scroll position as a value from 0.0 to 1.0""" - if not self._content_rect or not self._bounds_rect: - return 0.0 - - max_scroll_y = max(self._content_rect.height - self._bounds_rect.height, 0) - if max_scroll_y == 0: - return 0.0 - - normalized = -self._offset.y / max_scroll_y - return max(0.0, min(1.0, normalized)) diff --git a/system/ui/lib/scroller.py b/system/ui/lib/scroller.py deleted file mode 100644 index 8a10221772..0000000000 --- a/system/ui/lib/scroller.py +++ /dev/null @@ -1,74 +0,0 @@ -import pyray as rl -from openpilot.system.ui.lib.widget import Widget -from openpilot.system.ui.lib.scroll_panel import GuiScrollPanel - -ITEM_SPACING = 40 -LINE_COLOR = rl.GRAY -LINE_PADDING = 40 - - -class LineSeparator(Widget): - def __init__(self, height: int = 1): - super().__init__() - self._rect = rl.Rectangle(0, 0, 0, height) - - def set_parent_rect(self, parent_rect: rl.Rectangle) -> None: - super().set_parent_rect(parent_rect) - self._rect.width = parent_rect.width - - def _render(self, _): - rl.draw_line(int(self._rect.x) + LINE_PADDING, int(self._rect.y), - int(self._rect.x + self._rect.width) - LINE_PADDING * 2, int(self._rect.y), - LINE_COLOR) - - -class Scroller(Widget): - def __init__(self, items: list[Widget], spacing: int = ITEM_SPACING, line_separator: bool = False, pad_end: bool = True): - super().__init__() - self._items: list[Widget] = [] - self._spacing = spacing - self._line_separator = line_separator - self._pad_end = pad_end - - self.scroll_panel = GuiScrollPanel() - - for item in items: - self.add_widget(item) - - def add_widget(self, item: Widget) -> None: - if self._line_separator and len(self._items) > 0: - self._items.append(LineSeparator()) - self._items.append(item) - item.set_touch_valid_callback(self.scroll_panel.is_touch_valid) - - def _render(self, _): - # TODO: don't draw items that are not in the viewport - visible_items = [item for item in self._items if item.is_visible] - content_height = sum(item.rect.height for item in visible_items) + self._spacing * (len(visible_items)) - if not self._pad_end: - content_height -= self._spacing - scroll = self.scroll_panel.handle_scroll(self._rect, rl.Rectangle(0, 0, self._rect.width, content_height)) - - rl.begin_scissor_mode(int(self._rect.x), int(self._rect.y), - int(self._rect.width), int(self._rect.height)) - - cur_height = 0 - for idx, item in enumerate(visible_items): - if not item.is_visible: - continue - - # Nicely lay out items vertically - x = self._rect.x - y = self._rect.y + cur_height + self._spacing * (idx != 0) - cur_height += item.rect.height + self._spacing * (idx != 0) - - # Consider scroll - x += scroll.x - y += scroll.y - - # Update item state - item.set_position(x, y) - item.set_parent_rect(self._rect) - item.render() - - rl.end_scissor_mode() diff --git a/system/ui/lib/shader_polygon.py b/system/ui/lib/shader_polygon.py deleted file mode 100644 index cfde81c554..0000000000 --- a/system/ui/lib/shader_polygon.py +++ /dev/null @@ -1,321 +0,0 @@ -import platform -import pyray as rl -import numpy as np -from typing import Any - -MAX_GRADIENT_COLORS = 15 - -VERSION = """ -#version 300 es -precision highp float; -""" -if platform.system() == "Darwin": - VERSION = """ - #version 330 core - """ - -FRAGMENT_SHADER = VERSION + """ -in vec2 fragTexCoord; -out vec4 finalColor; - -uniform vec2 points[100]; -uniform int pointCount; -uniform vec4 fillColor; -uniform vec2 resolution; - -uniform int useGradient; -uniform vec2 gradientStart; -uniform vec2 gradientEnd; -uniform vec4 gradientColors[15]; -uniform float gradientStops[15]; -uniform int gradientColorCount; - -vec4 getGradientColor(vec2 pos) { - vec2 gradientDir = gradientEnd - gradientStart; - float gradientLength = length(gradientDir); - if (gradientLength < 0.001) return gradientColors[0]; - - vec2 normalizedDir = gradientDir / gradientLength; - float t = clamp(dot(pos - gradientStart, normalizedDir) / gradientLength, 0.0, 1.0); - - if (gradientColorCount <= 1) return gradientColors[0]; - for (int i = 0; i < gradientColorCount - 1; i++) { - if (t >= gradientStops[i] && t <= gradientStops[i+1]) { - float segmentT = (t - gradientStops[i]) / (gradientStops[i+1] - gradientStops[i]); - return mix(gradientColors[i], gradientColors[i+1], segmentT); - } - } - - return gradientColors[gradientColorCount-1]; -} - -bool isPointInsidePolygon(vec2 p) { - if (pointCount < 3) return false; - int crossings = 0; - for (int i = 0, j = pointCount - 1; i < pointCount; j = i++) { - vec2 pi = points[i]; - vec2 pj = points[j]; - if (distance(pi, pj) < 0.001) continue; - if (((pi.y > p.y) != (pj.y > p.y)) && - (p.x < (pj.x - pi.x) * (p.y - pi.y) / (pj.y - pi.y + 0.001) + pi.x)) { - crossings++; - } - } - return (crossings & 1) == 1; -} - -float distanceToEdge(vec2 p) { - float minDist = 1000.0; - - for (int i = 0, j = pointCount - 1; i < pointCount; j = i++) { - vec2 edge0 = points[j]; - vec2 edge1 = points[i]; - - if (distance(edge0, edge1) < 0.0001) continue; - - vec2 v1 = p - edge0; - vec2 v2 = edge1 - edge0; - float l2 = dot(v2, v2); - - if (l2 < 0.0001) { - float dist = length(v1); - minDist = min(minDist, dist); - continue; - } - - float t = clamp(dot(v1, v2) / l2, 0.0, 1.0); - vec2 projection = edge0 + t * v2; - float dist = length(p - projection); - minDist = min(minDist, dist); - } - - return minDist; -} - -void main() { - vec2 pixel = fragTexCoord * resolution; - - // Compute pixel size for anti-aliasing - vec2 pixelGrad = vec2(dFdx(pixel.x), dFdy(pixel.y)); - float pixelSize = length(pixelGrad); - float aaWidth = max(0.5, pixelSize * 1.5); - - bool inside = isPointInsidePolygon(pixel); - if (inside) { - finalColor = useGradient == 1 ? getGradientColor(pixel) : fillColor; - return; - } - - float sd = -distanceToEdge(pixel); - float alpha = smoothstep(-aaWidth, aaWidth, sd); - if (alpha > 0.0){ - vec4 color = useGradient == 1 ? getGradientColor(pixel) : fillColor; - finalColor = vec4(color.rgb, color.a * alpha); - } else { - discard; - } -} -""" - -# Default vertex shader -VERTEX_SHADER = VERSION + """ -in vec3 vertexPosition; -in vec2 vertexTexCoord; -out vec2 fragTexCoord; -uniform mat4 mvp; - -void main() { - fragTexCoord = vertexTexCoord; - gl_Position = mvp * vec4(vertexPosition, 1.0); -} -""" - -UNIFORM_INT = rl.ShaderUniformDataType.SHADER_UNIFORM_INT -UNIFORM_FLOAT = rl.ShaderUniformDataType.SHADER_UNIFORM_FLOAT -UNIFORM_VEC2 = rl.ShaderUniformDataType.SHADER_UNIFORM_VEC2 -UNIFORM_VEC4 = rl.ShaderUniformDataType.SHADER_UNIFORM_VEC4 - - -class ShaderState: - _instance: Any = None - - @classmethod - def get_instance(cls): - if cls._instance is None: - cls._instance = cls() - return cls._instance - - def __init__(self): - if ShaderState._instance is not None: - raise Exception("This class is a singleton. Use get_instance() instead.") - - self.initialized = False - self.shader = None - self.white_texture = None - - # Shader uniform locations - self.locations = { - 'pointCount': None, - 'fillColor': None, - 'resolution': None, - 'points': None, - 'useGradient': None, - 'gradientStart': None, - 'gradientEnd': None, - 'gradientColors': None, - 'gradientStops': None, - 'gradientColorCount': None, - 'mvp': None, - } - - # Pre-allocated FFI objects - self.point_count_ptr = rl.ffi.new("int[]", [0]) - self.resolution_ptr = rl.ffi.new("float[]", [0.0, 0.0]) - self.fill_color_ptr = rl.ffi.new("float[]", [0.0, 0.0, 0.0, 0.0]) - self.use_gradient_ptr = rl.ffi.new("int[]", [0]) - self.gradient_start_ptr = rl.ffi.new("float[]", [0.0, 0.0]) - self.gradient_end_ptr = rl.ffi.new("float[]", [0.0, 0.0]) - self.color_count_ptr = rl.ffi.new("int[]", [0]) - self.gradient_colors_ptr = rl.ffi.new("float[]", MAX_GRADIENT_COLORS * 4) - self.gradient_stops_ptr = rl.ffi.new("float[]", MAX_GRADIENT_COLORS) - - def initialize(self): - if self.initialized: - return - - self.shader = rl.load_shader_from_memory(VERTEX_SHADER, FRAGMENT_SHADER) - - # Create and cache white texture - white_img = rl.gen_image_color(2, 2, rl.WHITE) - self.white_texture = rl.load_texture_from_image(white_img) - rl.set_texture_filter(self.white_texture, rl.TEXTURE_FILTER_BILINEAR) - rl.unload_image(white_img) - - # Cache all uniform locations - for uniform in self.locations.keys(): - self.locations[uniform] = rl.get_shader_location(self.shader, uniform) - - # Setup default MVP matrix - mvp_ptr = rl.ffi.new("float[16]", [1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0]) - rl.set_shader_value_matrix(self.shader, self.locations['mvp'], rl.Matrix(*mvp_ptr)) - - self.initialized = True - - def cleanup(self): - if not self.initialized: - return - - if self.white_texture: - rl.unload_texture(self.white_texture) - self.white_texture = None - - if self.shader: - rl.unload_shader(self.shader) - self.shader = None - - self.initialized = False - - -def _configure_shader_color(state, color, gradient, clipped_rect, original_rect): - use_gradient = 1 if gradient else 0 - state.use_gradient_ptr[0] = use_gradient - rl.set_shader_value(state.shader, state.locations['useGradient'], state.use_gradient_ptr, UNIFORM_INT) - - if use_gradient: - start = np.array(gradient['start']) * np.array([original_rect.width, original_rect.height]) + np.array([original_rect.x, original_rect.y]) - end = np.array(gradient['end']) * np.array([original_rect.width, original_rect.height]) + np.array([original_rect.x, original_rect.y]) - start = start - np.array([clipped_rect.x, clipped_rect.y]) - end = end - np.array([clipped_rect.x, clipped_rect.y]) - state.gradient_start_ptr[0:2] = start.astype(np.float32) - state.gradient_end_ptr[0:2] = end.astype(np.float32) - rl.set_shader_value(state.shader, state.locations['gradientStart'], state.gradient_start_ptr, UNIFORM_VEC2) - rl.set_shader_value(state.shader, state.locations['gradientEnd'], state.gradient_end_ptr, UNIFORM_VEC2) - - colors = gradient['colors'] - color_count = min(len(colors), MAX_GRADIENT_COLORS) - state.color_count_ptr[0] = color_count - for i, c in enumerate(colors[:color_count]): - base_idx = i * 4 - state.gradient_colors_ptr[base_idx:base_idx+4] = [c.r / 255.0, c.g / 255.0, c.b / 255.0, c.a / 255.0] - rl.set_shader_value_v(state.shader, state.locations['gradientColors'], state.gradient_colors_ptr, UNIFORM_VEC4, color_count) - - stops = gradient.get('stops', [i / max(1, color_count - 1) for i in range(color_count)]) - stops = np.clip(stops[:color_count], 0.0, 1.0) - state.gradient_stops_ptr[0:color_count] = stops - rl.set_shader_value_v(state.shader, state.locations['gradientStops'], state.gradient_stops_ptr, UNIFORM_FLOAT, color_count) - rl.set_shader_value(state.shader, state.locations['gradientColorCount'], state.color_count_ptr, UNIFORM_INT) - else: - color = color or rl.WHITE - state.fill_color_ptr[0:4] = [color.r / 255.0, color.g / 255.0, color.b / 255.0, color.a / 255.0] - rl.set_shader_value(state.shader, state.locations['fillColor'], state.fill_color_ptr, UNIFORM_VEC4) - - -def draw_polygon(origin_rect: rl.Rectangle, points: np.ndarray, color=None, gradient=None): - """ - Draw a complex polygon using shader-based even-odd fill rule - - Args: - rect: Rectangle defining the drawing area - points: numpy array of (x,y) points defining the polygon - color: Solid fill color (rl.Color) - gradient: Dict with gradient parameters: - { - 'start': (x1, y1), # Start point (normalized 0-1) - 'end': (x2, y2), # End point (normalized 0-1) - 'colors': [rl.Color], # List of colors at stops - 'stops': [float] # List of positions (0-1) - } - """ - if len(points) < 3: - return - - state = ShaderState.get_instance() - if not state.initialized: - state.initialize() - - # Find bounding box - min_xy = np.min(points, axis=0) - max_xy = np.max(points, axis=0) - clip_x = max(origin_rect.x, min_xy[0]) - clip_y = max(origin_rect.y, min_xy[1]) - clip_right = min(origin_rect.x + origin_rect.width, max_xy[0]) - clip_bottom = min(origin_rect.y + origin_rect.height, max_xy[1]) - - # Check if polygon is completely off-screen - if clip_x >= clip_right or clip_y >= clip_bottom: - return - - clipped_rect = rl.Rectangle(clip_x, clip_y, clip_right - clip_x, clip_bottom - clip_y) - - # Transform points relative to the CLIPPED area - transformed_points = points - np.array([clip_x, clip_y]) - - # Set shader values - state.point_count_ptr[0] = len(transformed_points) - rl.set_shader_value(state.shader, state.locations['pointCount'], state.point_count_ptr, UNIFORM_INT) - - state.resolution_ptr[0:2] = [clipped_rect.width, clipped_rect.height] - rl.set_shader_value(state.shader, state.locations['resolution'], state.resolution_ptr, UNIFORM_VEC2) - - flat_points = np.ascontiguousarray(transformed_points.flatten().astype(np.float32)) - points_ptr = rl.ffi.cast("float *", flat_points.ctypes.data) - rl.set_shader_value_v(state.shader, state.locations['points'], points_ptr, UNIFORM_VEC2, len(transformed_points)) - - _configure_shader_color(state, color, gradient, clipped_rect, origin_rect) - - # Render - rl.begin_shader_mode(state.shader) - rl.draw_texture_pro( - state.white_texture, - rl.Rectangle(0, 0, 2, 2), - clipped_rect, - rl.Vector2(0, 0), - 0.0, - rl.WHITE, - ) - rl.end_shader_mode() - - -def cleanup_shader_resources(): - state = ShaderState.get_instance() - state.cleanup() diff --git a/system/ui/lib/text_measure.py b/system/ui/lib/text_measure.py deleted file mode 100644 index c172f94251..0000000000 --- a/system/ui/lib/text_measure.py +++ /dev/null @@ -1,14 +0,0 @@ -import pyray as rl - -_cache: dict[int, rl.Vector2] = {} - - -def measure_text_cached(font: rl.Font, text: str, font_size: int, spacing: int = 0) -> rl.Vector2: - """Caches text measurements to avoid redundant calculations.""" - key = hash((font.texture.id, text, font_size, spacing)) - if key in _cache: - return _cache[key] - - result = rl.measure_text_ex(font, text, font_size, spacing) # noqa: TID251 - _cache[key] = result - return result diff --git a/system/ui/lib/toggle.py b/system/ui/lib/toggle.py deleted file mode 100644 index 8ed9a655ec..0000000000 --- a/system/ui/lib/toggle.py +++ /dev/null @@ -1,72 +0,0 @@ -import pyray as rl -from openpilot.system.ui.lib.widget import Widget - -ON_COLOR = rl.Color(51, 171, 76, 255) -OFF_COLOR = rl.Color(0x39, 0x39, 0x39, 255) -KNOB_COLOR = rl.WHITE -DISABLED_ON_COLOR = rl.Color(0x22, 0x77, 0x22, 255) # Dark green when disabled + on -DISABLED_OFF_COLOR = rl.Color(0x39, 0x39, 0x39, 255) -DISABLED_KNOB_COLOR = rl.Color(0x88, 0x88, 0x88, 255) -WIDTH, HEIGHT = 160, 80 -BG_HEIGHT = 60 -ANIMATION_SPEED = 8.0 - - -class Toggle(Widget): - def __init__(self, initial_state=False): - super().__init__() - self._state = initial_state - self._enabled = True - self._progress = 1.0 if initial_state else 0.0 - self._target = self._progress - - def set_rect(self, rect: rl.Rectangle): - self._rect = rl.Rectangle(rect.x, rect.y, WIDTH, HEIGHT) - - def _handle_mouse_release(self, mouse_pos: rl.Vector2): - if not self._enabled: - return - - self._state = not self._state - self._target = 1.0 if self._state else 0.0 - - def get_state(self): - return self._state - - def set_state(self, state: bool): - self._state = state - self._target = 1.0 if state else 0.0 - - def set_enabled(self, enabled: bool): - self._enabled = enabled - - def is_enabled(self): - return self._enabled - - def update(self): - if abs(self._progress - self._target) > 0.01: - delta = rl.get_frame_time() * ANIMATION_SPEED - self._progress += delta if self._progress < self._target else -delta - self._progress = max(0.0, min(1.0, self._progress)) - - def _render(self, rect: rl.Rectangle): - self.update() - - if self._enabled: - bg_color = self._blend_color(OFF_COLOR, ON_COLOR, self._progress) - knob_color = KNOB_COLOR - else: - bg_color = self._blend_color(DISABLED_OFF_COLOR, DISABLED_ON_COLOR, self._progress) - knob_color = DISABLED_KNOB_COLOR - - # Draw background - bg_rect = rl.Rectangle(self._rect.x + 5, self._rect.y + 10, WIDTH - 10, BG_HEIGHT) - rl.draw_rectangle_rounded(bg_rect, 1.0, 10, bg_color) - - # Draw knob - knob_x = self._rect.x + HEIGHT / 2 + (WIDTH - HEIGHT) * self._progress - knob_y = self._rect.y + HEIGHT / 2 - rl.draw_circle(int(knob_x), int(knob_y), HEIGHT / 2, knob_color) - - def _blend_color(self, c1, c2, t): - return rl.Color(int(c1.r + (c2.r - c1.r) * t), int(c1.g + (c2.g - c1.g) * t), int(c1.b + (c2.b - c1.b) * t), 255) diff --git a/system/ui/lib/utils.py b/system/ui/lib/utils.py deleted file mode 100644 index 77035d0da0..0000000000 --- a/system/ui/lib/utils.py +++ /dev/null @@ -1,18 +0,0 @@ -import pyray as rl - - -class GuiStyleContext: - def __init__(self, styles: list[tuple[int, int, int]]): - """styles is a list of tuples (control, prop, new_value)""" - self.styles = styles - self.prev_styles: list[tuple[int, int, int]] = [] - - def __enter__(self): - for control, prop, new_value in self.styles: - prev_value = rl.gui_get_style(control, prop) - self.prev_styles.append((control, prop, prev_value)) - rl.gui_set_style(control, prop, new_value) - - def __exit__(self, exc_type, exc_value, traceback): - for control, prop, prev_value in self.prev_styles: - rl.gui_set_style(control, prop, prev_value) diff --git a/system/ui/lib/widget.py b/system/ui/lib/widget.py deleted file mode 100644 index 3539f5594b..0000000000 --- a/system/ui/lib/widget.py +++ /dev/null @@ -1,96 +0,0 @@ -import abc -import pyray as rl -from enum import IntEnum -from collections.abc import Callable - - -class DialogResult(IntEnum): - CANCEL = 0 - CONFIRM = 1 - NO_ACTION = -1 - - -class Widget(abc.ABC): - def __init__(self): - self._rect: rl.Rectangle = rl.Rectangle(0, 0, 0, 0) - self._parent_rect: rl.Rectangle = rl.Rectangle(0, 0, 0, 0) - self._is_pressed = False - self._is_visible: bool | Callable[[], bool] = True - self._touch_valid_callback: Callable[[], bool] | None = None - - def set_touch_valid_callback(self, touch_callback: Callable[[], bool]) -> None: - """Set a callback to determine if the widget can be clicked.""" - self._touch_valid_callback = touch_callback - - def _touch_valid(self) -> bool: - """Check if the widget can be touched.""" - return self._touch_valid_callback() if self._touch_valid_callback else True - - @property - def is_visible(self) -> bool: - return self._is_visible() if callable(self._is_visible) else self._is_visible - - @property - def rect(self) -> rl.Rectangle: - return self._rect - - def set_visible(self, visible: bool | Callable[[], bool]) -> None: - self._is_visible = visible - - def set_rect(self, rect: rl.Rectangle) -> None: - changed = (self._rect.x != rect.x or self._rect.y != rect.y or - self._rect.width != rect.width or self._rect.height != rect.height) - self._rect = rect - if changed: - self._update_layout_rects() - - def set_parent_rect(self, parent_rect: rl.Rectangle) -> None: - """Can be used like size hint in QT""" - self._parent_rect = parent_rect - - def set_position(self, x: float, y: float) -> None: - changed = (self._rect.x != x or self._rect.y != y) - self._rect.x, self._rect.y = x, y - if changed: - self._update_layout_rects() - - def render(self, rect: rl.Rectangle = None) -> bool | int | None: - if rect is not None: - self.set_rect(rect) - - self._update_state() - - if not self.is_visible: - return None - - ret = self._render(self._rect) - - # Keep track of whether mouse down started within the widget's rectangle - mouse_pos = rl.get_mouse_position() - if rl.is_mouse_button_pressed(rl.MouseButton.MOUSE_BUTTON_LEFT) and self._touch_valid(): - if rl.check_collision_point_rec(mouse_pos, self._rect): - self._is_pressed = True - - elif not self._touch_valid(): - self._is_pressed = False - - elif rl.is_mouse_button_released(rl.MouseButton.MOUSE_BUTTON_LEFT): - if self._is_pressed and rl.check_collision_point_rec(mouse_pos, self._rect): - self._handle_mouse_release(mouse_pos) - self._is_pressed = False - - return ret - - @abc.abstractmethod - def _render(self, rect: rl.Rectangle) -> bool | int | None: - """Render the widget within the given rectangle.""" - - def _update_state(self): - """Optionally update the widget's non-layout state. This is called before rendering.""" - - def _update_layout_rects(self) -> None: - """Optionally update any layout rects on Widget rect change.""" - - def _handle_mouse_release(self, mouse_pos: rl.Vector2) -> bool: - """Optionally handle mouse release events.""" - return False diff --git a/system/ui/lib/wifi_manager.py b/system/ui/lib/wifi_manager.py deleted file mode 100644 index dd08b66373..0000000000 --- a/system/ui/lib/wifi_manager.py +++ /dev/null @@ -1,720 +0,0 @@ -import asyncio -import concurrent.futures -import copy -import threading -import time -import uuid -from collections.abc import Callable -from dataclasses import dataclass -from enum import IntEnum -from typing import TypeVar - -from dbus_next.aio import MessageBus -from dbus_next import BusType, Variant, Message -from dbus_next.errors import DBusError -from dbus_next.constants import MessageType - -try: - from openpilot.common.params import Params -except ImportError: - # Params/Cythonized modules are not available in zipapp - Params = None -from openpilot.common.swaglog import cloudlog - -T = TypeVar("T") - -# NetworkManager constants -NM = "org.freedesktop.NetworkManager" -NM_PATH = '/org/freedesktop/NetworkManager' -NM_IFACE = 'org.freedesktop.NetworkManager' -NM_SETTINGS_PATH = '/org/freedesktop/NetworkManager/Settings' -NM_SETTINGS_IFACE = 'org.freedesktop.NetworkManager.Settings' -NM_CONNECTION_IFACE = 'org.freedesktop.NetworkManager.Settings.Connection' -NM_WIRELESS_IFACE = 'org.freedesktop.NetworkManager.Device.Wireless' -NM_PROPERTIES_IFACE = 'org.freedesktop.DBus.Properties' -NM_DEVICE_IFACE = "org.freedesktop.NetworkManager.Device" - -NM_DEVICE_STATE_REASON_SUPPLICANT_DISCONNECT = 8 - -TETHERING_IP_ADDRESS = "192.168.43.1" -DEFAULT_TETHERING_PASSWORD = "12345678" - - -# NetworkManager device states -class NMDeviceState(IntEnum): - DISCONNECTED = 30 - PREPARE = 40 - NEED_AUTH = 60 - IP_CONFIG = 70 - ACTIVATED = 100 - - -class SecurityType(IntEnum): - OPEN = 0 - WPA = 1 - WPA2 = 2 - WPA3 = 3 - UNSUPPORTED = 4 - - -@dataclass -class NetworkInfo: - ssid: str - strength: int - is_connected: bool - security_type: SecurityType - path: str - bssid: str - is_saved: bool = False - # saved_path: str - - -@dataclass -class WifiManagerCallbacks: - need_auth: Callable[[str], None] | None = None - activated: Callable[[], None] | None = None - forgotten: Callable[[str], None] | None = None - networks_updated: Callable[[list[NetworkInfo]], None] | None = None - connection_failed: Callable[[str, str], None] | None = None # Added for error feedback - - -class WifiManager: - def __init__(self, callbacks): - self.callbacks: WifiManagerCallbacks = callbacks - self.networks: list[NetworkInfo] = [] - self.bus: MessageBus = None - self.device_path: str = "" - self.device_proxy = None - self.saved_connections: dict[str, str] = {} - self.active_ap_path: str = "" - self.scan_task: asyncio.Task | None = None - # Set tethering ssid as "weedle" + first 4 characters of a dongle id - self._tethering_ssid = "weedle" - if Params is not None: - dongle_id = Params().get("DongleId", encoding="utf-8") - if dongle_id: - self._tethering_ssid += "-" + dongle_id[:4] - self.running: bool = True - self._current_connection_ssid: str | None = None - - async def connect(self) -> None: - """Connect to the DBus system bus.""" - try: - self.bus = await MessageBus(bus_type=BusType.SYSTEM).connect() - if not await self._find_wifi_device(): - raise ValueError("No Wi-Fi device found") - - await self._setup_signals(self.device_path) - self.active_ap_path = await self.get_active_access_point() - await self.add_tethering_connection(self._tethering_ssid, DEFAULT_TETHERING_PASSWORD) - self.saved_connections = await self._get_saved_connections() - self.scan_task = asyncio.create_task(self._periodic_scan()) - except DBusError as e: - cloudlog.error(f"Failed to connect to DBus: {e}") - raise - except Exception as e: - cloudlog.error(f"Unexpected error during connect: {e}") - raise - - async def shutdown(self) -> None: - self.running = False - if self.scan_task: - self.scan_task.cancel() - try: - await self.scan_task - except asyncio.CancelledError: - pass - if self.bus: - self.bus.disconnect() - - async def _request_scan(self) -> None: - try: - interface = self.device_proxy.get_interface(NM_WIRELESS_IFACE) - await interface.call_request_scan({}) - except DBusError as e: - cloudlog.warning(f"Scan request failed: {str(e)}") - - async def get_active_access_point(self): - try: - props_iface = self.device_proxy.get_interface(NM_PROPERTIES_IFACE) - ap_path = await props_iface.call_get(NM_WIRELESS_IFACE, 'ActiveAccessPoint') - return ap_path.value - except DBusError as e: - cloudlog.error(f"Error fetching active access point: {str(e)}") - return '' - - async def forget_connection(self, ssid: str) -> bool: - path = self.saved_connections.get(ssid) - if not path: - return False - - try: - nm_iface = await self._get_interface(NM, path, NM_CONNECTION_IFACE) - await nm_iface.call_delete() - - if self._current_connection_ssid == ssid: - self._current_connection_ssid = None - - if ssid in self.saved_connections: - del self.saved_connections[ssid] - - for network in self.networks: - if network.ssid == ssid: - network.is_saved = False - network.is_connected = False - break - - # Notify UI of forgotten connection - if self.callbacks.networks_updated: - self.callbacks.networks_updated(copy.deepcopy(self.networks)) - - return True - except DBusError as e: - cloudlog.error(f"Failed to delete connection for SSID: {ssid}. Error: {e}") - return False - - async def activate_connection(self, ssid: str) -> bool: - connection_path = self.saved_connections.get(ssid) - if not connection_path: - return False - try: - nm_iface = await self._get_interface(NM, NM_PATH, NM_IFACE) - await nm_iface.call_activate_connection(connection_path, self.device_path, "/") - return True - except DBusError as e: - cloudlog.error(f"Failed to activate connection {ssid}: {str(e)}") - return False - - async def connect_to_network(self, ssid: str, password: str = None, bssid: str = None, is_hidden: bool = False) -> None: - """Connect to a selected Wi-Fi network.""" - try: - self._current_connection_ssid = ssid - - if ssid in self.saved_connections: - # Forget old connection if new password provided - if password: - await self.forget_connection(ssid) - await asyncio.sleep(0.2) # NetworkManager delay - else: - # Just activate existing connection - await self.activate_connection(ssid) - return - - connection = { - 'connection': { - 'type': Variant('s', '802-11-wireless'), - 'uuid': Variant('s', str(uuid.uuid4())), - 'id': Variant('s', ssid), - 'autoconnect-retries': Variant('i', 0), - }, - '802-11-wireless': { - 'ssid': Variant('ay', ssid.encode('utf-8')), - 'hidden': Variant('b', is_hidden), - 'mode': Variant('s', 'infrastructure'), - }, - 'ipv4': {'method': Variant('s', 'auto')}, - 'ipv6': {'method': Variant('s', 'ignore')}, - } - - if bssid: - connection['802-11-wireless']['bssid'] = Variant('ay', bssid.encode('utf-8')) - - if password: - connection['802-11-wireless-security'] = { - 'key-mgmt': Variant('s', 'wpa-psk'), - 'auth-alg': Variant('s', 'open'), - 'psk': Variant('s', password), - } - - nm_iface = await self._get_interface(NM, NM_PATH, NM_IFACE) - await nm_iface.call_add_and_activate_connection(connection, self.device_path, "/") - except Exception as e: - self._current_connection_ssid = None - cloudlog.error(f"Error connecting to network: {e}") - # Notify UI of failure - if self.callbacks.connection_failed: - self.callbacks.connection_failed(ssid, str(e)) - - def is_saved(self, ssid: str) -> bool: - return ssid in self.saved_connections - - async def _find_wifi_device(self) -> bool: - nm_iface = await self._get_interface(NM, NM_PATH, NM_IFACE) - devices = await nm_iface.get_devices() - - for device_path in devices: - device = await self.bus.introspect(NM, device_path) - device_proxy = self.bus.get_proxy_object(NM, device_path, device) - device_interface = device_proxy.get_interface(NM_DEVICE_IFACE) - device_type = await device_interface.get_device_type() # type: ignore[attr-defined] - if device_type == 2: # Wi-Fi device - self.device_path = device_path - self.device_proxy = device_proxy - return True - - return False - - async def add_tethering_connection(self, ssid: str, password: str = "12345678") -> bool: - """Create a WiFi tethering connection.""" - if len(password) < 8: - print("Tethering password must be at least 8 characters") - return False - - try: - # First, check if a hotspot connection already exists - settings_iface = await self._get_interface(NM, NM_SETTINGS_PATH, NM_SETTINGS_IFACE) - connection_paths = await settings_iface.call_list_connections() - - # Look for an existing hotspot connection - for path in connection_paths: - try: - settings = await self._get_connection_settings(path) - conn_type = settings.get('connection', {}).get('type', Variant('s', '')).value - wifi_mode = settings.get('802-11-wireless', {}).get('mode', Variant('s', '')).value - - if conn_type == '802-11-wireless' and wifi_mode == 'ap': - # Extract the SSID to check - connection_ssid = self._extract_ssid(settings) - if connection_ssid == ssid: - return True - except DBusError: - continue - - connection = { - 'connection': { - 'id': Variant('s', 'Hotspot'), - 'uuid': Variant('s', str(uuid.uuid4())), - 'type': Variant('s', '802-11-wireless'), - 'interface-name': Variant('s', 'wlan0'), - 'autoconnect': Variant('b', False), - }, - '802-11-wireless': { - 'band': Variant('s', 'bg'), - 'mode': Variant('s', 'ap'), - 'ssid': Variant('ay', ssid.encode('utf-8')), - }, - '802-11-wireless-security': { - 'group': Variant('as', ['ccmp']), - 'key-mgmt': Variant('s', 'wpa-psk'), - 'pairwise': Variant('as', ['ccmp']), - 'proto': Variant('as', ['rsn']), - 'psk': Variant('s', password), - }, - 'ipv4': { - 'method': Variant('s', 'shared'), - 'address-data': Variant('aa{sv}', [{'address': Variant('s', TETHERING_IP_ADDRESS), 'prefix': Variant('u', 24)}]), - 'gateway': Variant('s', TETHERING_IP_ADDRESS), - 'never-default': Variant('b', True), - }, - 'ipv6': { - 'method': Variant('s', 'ignore'), - }, - } - - settings_iface = await self._get_interface(NM, NM_SETTINGS_PATH, NM_SETTINGS_IFACE) - new_connection = await settings_iface.call_add_connection(connection) - print(f"Added tethering connection with path: {new_connection}") - return True - except DBusError as e: - print(f"Failed to add tethering connection: {e}") - return False - except Exception as e: - print(f"Unexpected error adding tethering connection: {e}") - return False - - async def get_tethering_password(self) -> str: - """Get the current tethering password.""" - try: - hotspot_path = self.saved_connections.get(self._tethering_ssid) - if hotspot_path: - conn_iface = await self._get_interface(NM, hotspot_path, NM_CONNECTION_IFACE) - secrets = await conn_iface.call_get_secrets('802-11-wireless-security') - if secrets and '802-11-wireless-security' in secrets: - psk = secrets.get('802-11-wireless-security', {}).get('psk', Variant('s', '')).value - return str(psk) if psk is not None else "" - return "" - except DBusError as e: - print(f"Failed to get tethering password: {e}") - return "" - except Exception as e: - print(f"Unexpected error getting tethering password: {e}") - return "" - - async def set_tethering_password(self, password: str) -> bool: - """Set the tethering password.""" - if len(password) < 8: - cloudlog.error("Tethering password must be at least 8 characters") - return False - - try: - hotspot_path = self.saved_connections.get(self._tethering_ssid) - if not hotspot_path: - print("No hotspot connection found") - return False - - # Update the connection settings with new password - settings = await self._get_connection_settings(hotspot_path) - if '802-11-wireless-security' not in settings: - settings['802-11-wireless-security'] = {} - settings['802-11-wireless-security']['psk'] = Variant('s', password) - - # Apply changes - conn_iface = await self._get_interface(NM, hotspot_path, NM_CONNECTION_IFACE) - await conn_iface.call_update(settings) - - # Check if connection is active and restart if needed - is_active = False - nm_iface = await self._get_interface(NM, NM_PATH, NM_IFACE) - active_connections = await nm_iface.get_active_connections() - - for conn_path in active_connections: - props_iface = await self._get_interface(NM, conn_path, NM_PROPERTIES_IFACE) - conn_id_path = await props_iface.call_get('org.freedesktop.NetworkManager.Connection.Active', 'Connection') - if conn_id_path.value == hotspot_path: - is_active = True - await nm_iface.call_deactivate_connection(conn_path) - break - - if is_active: - await nm_iface.call_activate_connection(hotspot_path, self.device_path, "/") - - print("Tethering password updated successfully") - return True - except DBusError as e: - print(f"Failed to set tethering password: {e}") - return False - except Exception as e: - print(f"Unexpected error setting tethering password: {e}") - return False - - async def is_tethering_active(self) -> bool: - """Check if tethering is active for the specified SSID.""" - try: - hotspot_path = self.saved_connections.get(self._tethering_ssid) - if not hotspot_path: - return False - - nm_iface = await self._get_interface(NM, NM_PATH, NM_IFACE) - active_connections = await nm_iface.get_active_connections() - - for conn_path in active_connections: - props_iface = await self._get_interface(NM, conn_path, NM_PROPERTIES_IFACE) - conn_id_path = await props_iface.call_get('org.freedesktop.NetworkManager.Connection.Active', 'Connection') - - if conn_id_path.value == hotspot_path: - return True - - return False - except Exception: - return False - - async def _periodic_scan(self): - while self.running: - try: - await self._request_scan() - await asyncio.sleep(30) - except asyncio.CancelledError: - break - except DBusError as e: - cloudlog.error(f"Scan failed: {e}") - await asyncio.sleep(5) - - async def _setup_signals(self, device_path: str) -> None: - rules = [ - f"type='signal',interface='{NM_PROPERTIES_IFACE}',member='PropertiesChanged',path='{device_path}'", - f"type='signal',interface='{NM_DEVICE_IFACE}',member='StateChanged',path='{device_path}'", - f"type='signal',interface='{NM_SETTINGS_IFACE}',member='NewConnection',path='{NM_SETTINGS_PATH}'", - f"type='signal',interface='{NM_SETTINGS_IFACE}',member='ConnectionRemoved',path='{NM_SETTINGS_PATH}'", - ] - for rule in rules: - await self._add_match_rule(rule) - - # Set up signal handlers - self.device_proxy.get_interface(NM_PROPERTIES_IFACE).on_properties_changed(self._on_properties_changed) - self.device_proxy.get_interface(NM_DEVICE_IFACE).on_state_changed(self._on_state_changed) - - settings_iface = await self._get_interface(NM, NM_SETTINGS_PATH, NM_SETTINGS_IFACE) - settings_iface.on_new_connection(self._on_new_connection) - settings_iface.on_connection_removed(self._on_connection_removed) - - def _on_properties_changed(self, interface: str, changed: dict, invalidated: list): - # print("property changed", interface, changed, invalidated) - if 'LastScan' in changed: - asyncio.create_task(self._refresh_networks()) - elif interface == NM_WIRELESS_IFACE and "ActiveAccessPoint" in changed: - new_ap_path = changed["ActiveAccessPoint"].value - if self.active_ap_path != new_ap_path: - self.active_ap_path = new_ap_path - asyncio.create_task(self._refresh_networks()) - - def _on_state_changed(self, new_state: int, old_state: int, reason: int): - print("State changed", new_state, old_state, reason) - if new_state == NMDeviceState.ACTIVATED: - if self.callbacks.activated: - self.callbacks.activated() - asyncio.create_task(self._refresh_networks()) - self._current_connection_ssid = None - elif new_state in (NMDeviceState.DISCONNECTED, NMDeviceState.NEED_AUTH): - for network in self.networks: - network.is_connected = False - - if new_state == NMDeviceState.NEED_AUTH and reason == NM_DEVICE_STATE_REASON_SUPPLICANT_DISCONNECT and self.callbacks.need_auth: - if self._current_connection_ssid: - self.callbacks.need_auth(self._current_connection_ssid) - else: - # Try to find the network from active_ap_path - for network in self.networks: - if network.path == self.active_ap_path: - self.callbacks.need_auth(network.ssid) - break - else: - # Couldn't identify the network that needs auth - cloudlog.error("Network needs authentication but couldn't identify which one") - - def _on_new_connection(self, path: str) -> None: - """Callback for NewConnection signal.""" - asyncio.create_task(self._add_saved_connection(path)) - - def _on_connection_removed(self, path: str) -> None: - """Callback for ConnectionRemoved signal.""" - for ssid, p in list(self.saved_connections.items()): - if path == p: - del self.saved_connections[ssid] - - if self.callbacks.forgotten: - self.callbacks.forgotten(ssid) - - # Update network list to reflect the removed saved connection - asyncio.create_task(self._refresh_networks()) - break - - async def _add_saved_connection(self, path: str) -> None: - """Add a new saved connection to the dictionary.""" - try: - settings = await self._get_connection_settings(path) - if ssid := self._extract_ssid(settings): - self.saved_connections[ssid] = path - await self._refresh_networks() - except DBusError as e: - cloudlog.error(f"Failed to add connection {path}: {e}") - - def _extract_ssid(self, settings: dict) -> str | None: - """Extract SSID from connection settings.""" - ssid_variant = settings.get('802-11-wireless', {}).get('ssid', Variant('ay', b'')).value - return ''.join(chr(b) for b in ssid_variant) if ssid_variant else None - - async def _add_match_rule(self, rule): - """Add a match rule on the bus.""" - reply = await self.bus.call( - Message( - message_type=MessageType.METHOD_CALL, - destination='org.freedesktop.DBus', - interface="org.freedesktop.DBus", - path='/org/freedesktop/DBus', - member='AddMatch', - signature='s', - body=[rule], - ) - ) - - assert reply.message_type == MessageType.METHOD_RETURN - return reply - - async def _refresh_networks(self): - """Get a list of available networks via NetworkManager.""" - wifi_iface = self.device_proxy.get_interface(NM_WIRELESS_IFACE) - access_points = await wifi_iface.get_access_points() - self.active_ap_path = await self.get_active_access_point() - network_dict = {} - for ap_path in access_points: - try: - props_iface = await self._get_interface(NM, ap_path, NM_PROPERTIES_IFACE) - properties = await props_iface.call_get_all('org.freedesktop.NetworkManager.AccessPoint') - ssid_variant = properties['Ssid'].value - ssid = ''.join(chr(byte) for byte in ssid_variant) - if not ssid: - continue - - bssid = properties.get('HwAddress', Variant('s', '')).value - strength = properties['Strength'].value - flags = properties['Flags'].value - wpa_flags = properties['WpaFlags'].value - rsn_flags = properties['RsnFlags'].value - existing_network = network_dict.get(ssid) - if not existing_network or ((not existing_network.bssid and bssid) or (existing_network.strength < strength)): - network_dict[ssid] = NetworkInfo( - ssid=ssid, - strength=strength, - security_type=self._get_security_type(flags, wpa_flags, rsn_flags), - path=ap_path, - bssid=bssid, - is_connected=self.active_ap_path == ap_path and self._current_connection_ssid != ssid, - is_saved=ssid in self.saved_connections - ) - - except DBusError as e: - cloudlog.error(f"Error fetching networks: {e}") - except Exception as e: - cloudlog.error({e}) - - self.networks = sorted( - network_dict.values(), - key=lambda network: ( - not network.is_connected, - -network.strength, # Higher signal strength first - network.ssid.lower(), - ), - ) - - if self.callbacks.networks_updated: - self.callbacks.networks_updated(copy.deepcopy(self.networks)) - - async def _get_connection_settings(self, path): - """Fetch connection settings for a specific connection path.""" - try: - settings = await self._get_interface(NM, path, NM_CONNECTION_IFACE) - return await settings.call_get_settings() - except DBusError as e: - cloudlog.error(f"Failed to get settings for {path}: {str(e)}") - return {} - - async def _process_chunk(self, paths_chunk): - """Process a chunk of connection paths.""" - tasks = [self._get_connection_settings(path) for path in paths_chunk] - return await asyncio.gather(*tasks, return_exceptions=True) - - async def _get_saved_connections(self) -> dict[str, str]: - try: - settings_iface = await self._get_interface(NM, NM_SETTINGS_PATH, NM_SETTINGS_IFACE) - connection_paths = await settings_iface.call_list_connections() - saved_ssids: dict[str, str] = {} - batch_size = 20 - for i in range(0, len(connection_paths), batch_size): - chunk = connection_paths[i : i + batch_size] - results = await self._process_chunk(chunk) - for path, config in zip(chunk, results, strict=True): - if isinstance(config, dict) and '802-11-wireless' in config: - if ssid := self._extract_ssid(config): - saved_ssids[ssid] = path - return saved_ssids - except DBusError as e: - cloudlog.error(f"Error fetching saved connections: {str(e)}") - return {} - - async def _get_interface(self, bus_name: str, path: str, name: str): - introspection = await self.bus.introspect(bus_name, path) - proxy = self.bus.get_proxy_object(bus_name, path, introspection) - return proxy.get_interface(name) - - def _get_security_type(self, flags: int, wpa_flags: int, rsn_flags: int) -> SecurityType: - """Determine the security type based on flags.""" - if flags == 0 and not (wpa_flags or rsn_flags): - return SecurityType.OPEN - if rsn_flags & 0x200: # SAE (WPA3 Personal) - # TODO: support WPA3 - return SecurityType.UNSUPPORTED - if rsn_flags: # RSN indicates WPA2 or higher - return SecurityType.WPA2 - if wpa_flags: # WPA flags indicate WPA - return SecurityType.WPA - return SecurityType.UNSUPPORTED - - -class WifiManagerWrapper: - def __init__(self): - self._manager: WifiManager | None = None - self._callbacks: WifiManagerCallbacks = WifiManagerCallbacks() - - self._thread = threading.Thread(target=self._run, daemon=True) - self._loop: asyncio.EventLoop | None = None - self._running = False - - def set_callbacks(self, callbacks: WifiManagerCallbacks): - self._callbacks = callbacks - - def start(self) -> None: - if not self._running: - self._thread.start() - while self._thread is not None and not self._running: - time.sleep(0.1) - - def _run(self): - self._loop = asyncio.new_event_loop() - asyncio.set_event_loop(self._loop) - - try: - self._manager = WifiManager(self._callbacks) - self._running = True - self._loop.run_forever() - except Exception as e: - cloudlog.error(f"Error in WifiManagerWrapper thread: {e}") - finally: - if self._loop.is_running(): - self._loop.stop() - self._running = False - - def shutdown(self) -> None: - if self._running: - if self._manager is not None and self._loop: - shutdown_future = asyncio.run_coroutine_threadsafe(self._manager.shutdown(), self._loop) - shutdown_future.result(timeout=3.0) - - if self._loop and self._loop.is_running(): - self._loop.call_soon_threadsafe(self._loop.stop) - if self._thread and self._thread.is_alive(): - self._thread.join(timeout=2.0) - self._running = False - - def is_saved(self, ssid: str) -> bool: - """Check if a network is saved.""" - return self._run_coroutine_sync(lambda manager: manager.is_saved(ssid), default=False) - - def connect(self): - """Connect to DBus and start Wi-Fi scanning.""" - if not self._manager: - return - self._run_coroutine(self._manager.connect()) - - def forget_connection(self, ssid: str): - """Forget a saved Wi-Fi connection.""" - if not self._manager: - return - self._run_coroutine(self._manager.forget_connection(ssid)) - - def activate_connection(self, ssid: str): - """Activate an existing Wi-Fi connection.""" - if not self._manager: - return - self._run_coroutine(self._manager.activate_connection(ssid)) - - def connect_to_network(self, ssid: str, password: str = None, bssid: str = None, is_hidden: bool = False): - """Connect to a Wi-Fi network.""" - if not self._manager: - return - self._run_coroutine(self._manager.connect_to_network(ssid, password, bssid, is_hidden)) - - def _run_coroutine(self, coro): - """Run a coroutine in the async thread.""" - if not self._running or not self._loop: - cloudlog.error("WifiManager thread is not running") - return - asyncio.run_coroutine_threadsafe(coro, self._loop) - - def _run_coroutine_sync(self, func: Callable[[WifiManager], T], default: T) -> T: - """Run a function synchronously in the async thread.""" - if not self._running or not self._loop or not self._manager: - return default - future = concurrent.futures.Future[T]() - - def wrapper(manager: WifiManager) -> None: - try: - future.set_result(func(manager)) - except Exception as e: - future.set_exception(e) - - try: - self._loop.call_soon_threadsafe(wrapper, self._manager) - return future.result(timeout=1.0) - except Exception as e: - cloudlog.error(f"WifiManagerWrapper property access failed: {e}") - return default diff --git a/system/ui/lib/wrap_text.py b/system/ui/lib/wrap_text.py deleted file mode 100644 index 35dc5ac401..0000000000 --- a/system/ui/lib/wrap_text.py +++ /dev/null @@ -1,103 +0,0 @@ -import pyray as rl -from openpilot.system.ui.lib.text_measure import measure_text_cached - - -def _break_long_word(font: rl.Font, word: str, font_size: int, max_width: int) -> list[str]: - if not word: - return [] - - parts = [] - remaining = word - - while remaining: - if measure_text_cached(font, remaining, font_size).x <= max_width: - parts.append(remaining) - break - - # Binary search for the longest substring that fits - left, right = 1, len(remaining) - best_fit = 1 - - while left <= right: - mid = (left + right) // 2 - substring = remaining[:mid] - width = measure_text_cached(font, substring, font_size).x - - if width <= max_width: - best_fit = mid - left = mid + 1 - else: - right = mid - 1 - - # Add the part that fits - parts.append(remaining[:best_fit]) - remaining = remaining[best_fit:] - - return parts - - -def wrap_text(font: rl.Font, text: str, font_size: int, max_width: int) -> list[str]: - if not text or max_width <= 0: - return [] - - # Split text by newlines first to preserve explicit line breaks - paragraphs = text.split('\n') - all_lines: list[str] = [] - - for paragraph in paragraphs: - # Handle empty paragraphs (preserve empty lines) - if not paragraph.strip(): - all_lines.append("") - continue - - # Process each paragraph separately - words = paragraph.split() - if not words: - all_lines.append("") - continue - - lines: list[str] = [] - current_line: list[str] = [] - current_width = 0 - space_width = int(measure_text_cached(font, " ", font_size).x) - - for word in words: - word_width = int(measure_text_cached(font, word, font_size).x) - - # Check if word alone exceeds max width (need to break the word) - if word_width > max_width: - # Finish current line if it has content - if current_line: - lines.append(" ".join(current_line)) - current_line = [] - current_width = 0 - - # Break the long word into parts - lines.extend(_break_long_word(font, word, font_size, max_width)) - continue - - # Calculate width if we add this word - needed_width = current_width - if current_line: # Need space before word - needed_width += space_width - needed_width += word_width - - # Check if word fits on current line - if needed_width <= max_width: - current_line.append(word) - current_width = needed_width - else: - # Start new line with this word - if current_line: - lines.append(" ".join(current_line)) - current_line = [word] - current_width = word_width - - # Add remaining words - if current_line: - lines.append(" ".join(current_line)) - - # Add all lines from this paragraph - all_lines.extend(lines) - - return all_lines diff --git a/system/ui/reset.py b/system/ui/reset.py deleted file mode 100755 index c0dbd1d956..0000000000 --- a/system/ui/reset.py +++ /dev/null @@ -1,124 +0,0 @@ -#!/usr/bin/env python3 -import os -import pyray as rl -import sys -import threading -from enum import IntEnum - -from openpilot.system.hardware import PC -from openpilot.system.ui.lib.application import gui_app, FontWeight -from openpilot.system.ui.lib.button import gui_button, ButtonStyle -from openpilot.system.ui.lib.label import gui_label, gui_text_box -from openpilot.system.ui.lib.widget import Widget - -NVME = "/dev/nvme0n1" -USERDATA = "/dev/disk/by-partlabel/userdata" - - -class ResetMode(IntEnum): - USER_RESET = 0 # user initiated a factory reset from openpilot - RECOVER = 1 # userdata is corrupt for some reason, give a chance to recover - FORMAT = 2 # finish up a factory reset from a tool that doesn't flash an empty partition to userdata - - -class ResetState(IntEnum): - NONE = 0 - CONFIRM = 1 - RESETTING = 2 - FAILED = 3 - - -class Reset(Widget): - def __init__(self, mode): - super().__init__() - self.mode = mode - self.reset_state = ResetState.NONE - - def _do_erase(self): - if PC: - return - - # Best effort to wipe NVME - os.system(f"sudo umount {NVME}") - os.system(f"yes | sudo mkfs.ext4 {NVME}") - - # Removing data and formatting - rm = os.system("sudo rm -rf /data/*") - os.system(f"sudo umount {USERDATA}") - fmt = os.system(f"yes | sudo mkfs.ext4 {USERDATA}") - - if rm == 0 or fmt == 0: - os.system("sudo reboot") - else: - self.reset_state = ResetState.FAILED - - def start_reset(self): - self.reset_state = ResetState.RESETTING - threading.Timer(0.1, self._do_erase).start() - - def _render(self, rect: rl.Rectangle): - label_rect = rl.Rectangle(rect.x + 140, rect.y, rect.width - 280, 100) - gui_label(label_rect, "System Reset", 100, font_weight=FontWeight.BOLD) - - text_rect = rl.Rectangle(rect.x + 140, rect.y + 140, rect.width - 280, rect.height - 90 - 100) - gui_text_box(text_rect, self.get_body_text(), 90) - - button_height = 160 - button_spacing = 50 - button_top = rect.y + rect.height - button_height - button_width = (rect.width - button_spacing) / 2.0 - - if self.reset_state != ResetState.RESETTING: - if self.mode == ResetMode.RECOVER or self.reset_state == ResetState.FAILED: - if gui_button(rl.Rectangle(rect.x, button_top, button_width, button_height), "Reboot"): - os.system("sudo reboot") - elif self.mode == ResetMode.USER_RESET: - if gui_button(rl.Rectangle(rect.x, button_top, button_width, button_height), "Cancel"): - return False - - if self.reset_state != ResetState.FAILED: - if gui_button(rl.Rectangle(rect.x + button_width + 50, button_top, button_width, button_height), - "Confirm", button_style=ButtonStyle.PRIMARY): - self.confirm() - - return True - - def confirm(self): - if self.reset_state == ResetState.CONFIRM: - self.start_reset() - else: - self.reset_state = ResetState.CONFIRM - - def get_body_text(self): - if self.reset_state == ResetState.CONFIRM: - return "Are you sure you want to reset your device?" - if self.reset_state == ResetState.RESETTING: - return "Resetting device...\nThis may take up to a minute." - if self.reset_state == ResetState.FAILED: - return "Reset failed. Reboot to try again." - if self.mode == ResetMode.RECOVER: - return "Unable to mount data partition. Partition may be corrupted. Press confirm to erase and reset your device." - return "System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot." - - -def main(): - mode = ResetMode.USER_RESET - if len(sys.argv) > 1: - if sys.argv[1] == '--recover': - mode = ResetMode.RECOVER - elif sys.argv[1] == "--format": - mode = ResetMode.FORMAT - - gui_app.init_window("System Reset") - reset = Reset(mode) - - if mode == ResetMode.FORMAT: - reset.start_reset() - - for _ in gui_app.render(): - if not reset.render(rl.Rectangle(45, 200, gui_app.width - 90, gui_app.height - 245)): - break - - -if __name__ == "__main__": - main() diff --git a/system/ui/setup.py b/system/ui/setup.py deleted file mode 100755 index 4d9d269480..0000000000 --- a/system/ui/setup.py +++ /dev/null @@ -1,348 +0,0 @@ -#!/usr/bin/env python3 -import os -import re -import threading -import time -import urllib.request -from enum import IntEnum -import pyray as rl - -from cereal import log -from openpilot.system.hardware import HARDWARE -from openpilot.system.ui.lib.application import gui_app, FontWeight -from openpilot.system.ui.lib.button import gui_button, ButtonStyle -from openpilot.system.ui.lib.label import gui_label, gui_text_box -from openpilot.system.ui.lib.widget import Widget -from openpilot.system.ui.widgets.network import WifiManagerUI, WifiManagerWrapper -from openpilot.system.ui.widgets.keyboard import Keyboard - -NetworkType = log.DeviceState.NetworkType - -MARGIN = 50 -TITLE_FONT_SIZE = 116 -TITLE_FONT_WEIGHT = FontWeight.MEDIUM -NEXT_BUTTON_WIDTH = 310 -BODY_FONT_SIZE = 96 -BUTTON_HEIGHT = 160 -BUTTON_SPACING = 50 - -OPENPILOT_URL = "https://openpilot.comma.ai" -USER_AGENT = f"AGNOSSetup-{HARDWARE.get_os_version()}" - - -class SetupState(IntEnum): - LOW_VOLTAGE = 0 - GETTING_STARTED = 1 - NETWORK_SETUP = 2 - SOFTWARE_SELECTION = 3 - CUSTOM_URL = 4 - DOWNLOADING = 5 - DOWNLOAD_FAILED = 6 - - -class Setup(Widget): - def __init__(self): - super().__init__() - self.state = SetupState.GETTING_STARTED - self.network_check_thread = None - self.network_connected = threading.Event() - self.wifi_connected = threading.Event() - self.stop_network_check_thread = threading.Event() - self.failed_url = "" - self.failed_reason = "" - self.download_url = "" - self.download_progress = 0 - self.download_thread = None - self.wifi_manager = WifiManagerWrapper() - self.wifi_ui = WifiManagerUI(self.wifi_manager) - self.keyboard = Keyboard() - self.selected_radio = None - - self.warning = gui_app.texture("icons/warning.png", 150, 150) - self.checkmark = gui_app.texture("icons/circled_check.png", 100, 100) - - try: - with open("/sys/class/hwmon/hwmon1/in1_input") as f: - voltage = float(f.read().strip()) / 1000.0 - if voltage < 7: - self.state = SetupState.LOW_VOLTAGE - except (FileNotFoundError, ValueError): - self.state = SetupState.LOW_VOLTAGE - - def _render(self, rect: rl.Rectangle): - if self.state == SetupState.LOW_VOLTAGE: - self.render_low_voltage(rect) - elif self.state == SetupState.GETTING_STARTED: - self.render_getting_started(rect) - elif self.state == SetupState.NETWORK_SETUP: - self.render_network_setup(rect) - elif self.state == SetupState.SOFTWARE_SELECTION: - self.render_software_selection(rect) - elif self.state == SetupState.CUSTOM_URL: - self.render_custom_url() - elif self.state == SetupState.DOWNLOADING: - self.render_downloading(rect) - elif self.state == SetupState.DOWNLOAD_FAILED: - self.render_download_failed(rect) - - def render_low_voltage(self, rect: rl.Rectangle): - rl.draw_texture(self.warning, int(rect.x + 150), int(rect.y + 110), rl.WHITE) - - title_rect = rl.Rectangle(rect.x + 150, rect.y + 110 + 150 + 100, rect.width - 500 - 150, TITLE_FONT_SIZE) - gui_label(title_rect, "WARNING: Low Voltage", TITLE_FONT_SIZE, rl.Color(255, 89, 79, 255), FontWeight.MEDIUM) - - body_rect = rl.Rectangle(rect.x + 150, rect.y + 110 + 150 + 100 + TITLE_FONT_SIZE + 25, rect.width - 500 - 150, BODY_FONT_SIZE * 3) - gui_text_box(body_rect, "Power your device in a car with a harness or proceed at your own risk.", BODY_FONT_SIZE) - - button_width = (rect.width - MARGIN * 3) / 2 - button_y = rect.height - MARGIN - BUTTON_HEIGHT - - if gui_button(rl.Rectangle(rect.x + MARGIN, button_y, button_width, BUTTON_HEIGHT), "Power off"): - HARDWARE.shutdown() - - if gui_button(rl.Rectangle(rect.x + MARGIN * 2 + button_width, button_y, button_width, BUTTON_HEIGHT), "Continue"): - self.state = SetupState.GETTING_STARTED - - def render_getting_started(self, rect: rl.Rectangle): - title_rect = rl.Rectangle(rect.x + 165, rect.y + 280, rect.width - 265, TITLE_FONT_SIZE) - gui_label(title_rect, "Getting Started", TITLE_FONT_SIZE, font_weight=FontWeight.MEDIUM) - - desc_rect = rl.Rectangle(rect.x + 165, rect.y + 280 + TITLE_FONT_SIZE + 90, rect.width - 500, BODY_FONT_SIZE * 3) - gui_text_box(desc_rect, "Before we get on the road, let's finish installation and cover some details.", BODY_FONT_SIZE) - - btn_rect = rl.Rectangle(rect.width - NEXT_BUTTON_WIDTH, 0, NEXT_BUTTON_WIDTH, rect.height) - - ret = gui_button(btn_rect, "", button_style=ButtonStyle.PRIMARY, border_radius=0) - triangle = gui_app.texture("images/button_continue_triangle.png", 54, int(btn_rect.height)) - rl.draw_texture_v(triangle, rl.Vector2(btn_rect.x + btn_rect.width / 2 - triangle.width / 2, btn_rect.height / 2 - triangle.height / 2), rl.WHITE) - - if ret: - self.state = SetupState.NETWORK_SETUP - self.start_network_check() - - def check_network_connectivity(self): - while not self.stop_network_check_thread.is_set(): - if self.state == SetupState.NETWORK_SETUP: - try: - urllib.request.urlopen(OPENPILOT_URL, timeout=2) - self.network_connected.set() - if HARDWARE.get_network_type() == NetworkType.wifi: - self.wifi_connected.set() - else: - self.wifi_connected.clear() - except Exception: - self.network_connected.clear() - time.sleep(1) - - def start_network_check(self): - if self.network_check_thread is None or not self.network_check_thread.is_alive(): - self.network_check_thread = threading.Thread(target=self.check_network_connectivity, daemon=True) - self.network_check_thread.start() - - def close(self): - if self.network_check_thread is not None: - self.stop_network_check_thread.set() - self.network_check_thread.join() - - def render_network_setup(self, rect: rl.Rectangle): - title_rect = rl.Rectangle(rect.x + MARGIN, rect.y + MARGIN, rect.width - MARGIN * 2, TITLE_FONT_SIZE) - gui_label(title_rect, "Connect to Wi-Fi", TITLE_FONT_SIZE, font_weight=FontWeight.MEDIUM) - - wifi_rect = rl.Rectangle(rect.x + MARGIN, rect.y + TITLE_FONT_SIZE + MARGIN + 25, rect.width - MARGIN * 2, - rect.height - TITLE_FONT_SIZE - 25 - BUTTON_HEIGHT - MARGIN * 3) - rl.draw_rectangle_rounded(wifi_rect, 0.05, 10, rl.Color(51, 51, 51, 255)) - wifi_content_rect = rl.Rectangle(wifi_rect.x + MARGIN, wifi_rect.y, wifi_rect.width - MARGIN * 2, wifi_rect.height) - self.wifi_ui.render(wifi_content_rect) - - button_width = (rect.width - BUTTON_SPACING - MARGIN * 2) / 2 - button_y = rect.height - BUTTON_HEIGHT - MARGIN - - if gui_button(rl.Rectangle(rect.x + MARGIN, button_y, button_width, BUTTON_HEIGHT), "Back"): - self.state = SetupState.GETTING_STARTED - - # Check network connectivity status - continue_enabled = self.network_connected.is_set() - continue_text = ("Continue" if self.wifi_connected.is_set() else "Continue without Wi-Fi") if continue_enabled else "Waiting for internet" - - if gui_button( - rl.Rectangle(rect.x + MARGIN + button_width + BUTTON_SPACING, button_y, button_width, BUTTON_HEIGHT), - continue_text, - button_style=ButtonStyle.PRIMARY if continue_enabled else ButtonStyle.NORMAL, - is_enabled=continue_enabled, - ): - self.state = SetupState.SOFTWARE_SELECTION - self.stop_network_check_thread.set() - - def render_software_selection(self, rect: rl.Rectangle): - title_rect = rl.Rectangle(rect.x + MARGIN, rect.y + MARGIN, rect.width - MARGIN * 2, TITLE_FONT_SIZE) - gui_label(title_rect, "Choose Software to Install", TITLE_FONT_SIZE, font_weight=FontWeight.MEDIUM) - - radio_height = 230 - radio_spacing = 30 - - openpilot_rect = rl.Rectangle(rect.x + MARGIN, rect.y + TITLE_FONT_SIZE + MARGIN * 2, rect.width - MARGIN * 2, radio_height) - openpilot_selected = self.selected_radio == "openpilot" - - rl.draw_rectangle_rounded(openpilot_rect, 0.1, 10, rl.Color(70, 91, 234, 255) if openpilot_selected else rl.Color(79, 79, 79, 255)) - gui_label(rl.Rectangle(openpilot_rect.x + 100, openpilot_rect.y, openpilot_rect.width - 200, radio_height), "openpilot", BODY_FONT_SIZE) - - if openpilot_selected: - checkmark_pos = rl.Vector2(openpilot_rect.x + openpilot_rect.width - 100 - self.checkmark.width, - openpilot_rect.y + radio_height / 2 - self.checkmark.height / 2) - rl.draw_texture_v(self.checkmark, checkmark_pos, rl.WHITE) - - custom_rect = rl.Rectangle(rect.x + MARGIN, rect.y + TITLE_FONT_SIZE + MARGIN * 2 + radio_height + radio_spacing, rect.width - MARGIN * 2, radio_height) - custom_selected = self.selected_radio == "custom" - - rl.draw_rectangle_rounded(custom_rect, 0.1, 10, rl.Color(70, 91, 234, 255) if custom_selected else rl.Color(79, 79, 79, 255)) - gui_label(rl.Rectangle(custom_rect.x + 100, custom_rect.y, custom_rect.width - 200, radio_height), "Custom Software", BODY_FONT_SIZE) - - if custom_selected: - checkmark_pos = rl.Vector2(custom_rect.x + custom_rect.width - 100 - self.checkmark.width, custom_rect.y + radio_height / 2 - self.checkmark.height / 2) - rl.draw_texture_v(self.checkmark, checkmark_pos, rl.WHITE) - - mouse_pos = rl.get_mouse_position() - if rl.is_mouse_button_released(rl.MouseButton.MOUSE_BUTTON_LEFT): - if rl.check_collision_point_rec(mouse_pos, openpilot_rect): - self.selected_radio = "openpilot" - elif rl.check_collision_point_rec(mouse_pos, custom_rect): - self.selected_radio = "custom" - - button_width = (rect.width - BUTTON_SPACING - MARGIN * 2) / 2 - button_y = rect.height - BUTTON_HEIGHT - MARGIN - - if gui_button(rl.Rectangle(rect.x + MARGIN, button_y, button_width, BUTTON_HEIGHT), "Back"): - self.state = SetupState.NETWORK_SETUP - - continue_enabled = self.selected_radio is not None - if gui_button( - rl.Rectangle(rect.x + MARGIN + button_width + BUTTON_SPACING, button_y, button_width, BUTTON_HEIGHT), - "Continue", - button_style=ButtonStyle.PRIMARY, - is_enabled=continue_enabled, - ): - if continue_enabled: - if self.selected_radio == "openpilot": - self.download(OPENPILOT_URL) - else: - self.state = SetupState.CUSTOM_URL - - def render_downloading(self, rect: rl.Rectangle): - title_rect = rl.Rectangle(rect.x, rect.y + rect.height / 2 - TITLE_FONT_SIZE / 2, rect.width, TITLE_FONT_SIZE) - gui_label(title_rect, "Downloading...", TITLE_FONT_SIZE, font_weight=FontWeight.MEDIUM, alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER) - - def render_download_failed(self, rect: rl.Rectangle): - title_rect = rl.Rectangle(rect.x + 117, rect.y + 185, rect.width - 117, TITLE_FONT_SIZE) - gui_label(title_rect, "Download Failed", TITLE_FONT_SIZE, font_weight=FontWeight.MEDIUM) - - url_rect = rl.Rectangle(rect.x + 117, rect.y + 185 + TITLE_FONT_SIZE + 67, rect.width - 117 - 100, 64) - gui_label(url_rect, self.failed_url, 64, font_weight=FontWeight.NORMAL) - - error_rect = rl.Rectangle(rect.x + 117, rect.y + 185 + TITLE_FONT_SIZE + 67 + 64 + 48, - rect.width - 117 - 100, rect.height - 185 + TITLE_FONT_SIZE + 67 + 64 + 48 - BUTTON_HEIGHT - MARGIN * 2) - gui_text_box(error_rect, self.failed_reason, BODY_FONT_SIZE) - - button_width = (rect.width - BUTTON_SPACING - MARGIN * 2) / 2 - button_y = rect.height - BUTTON_HEIGHT - MARGIN - - if gui_button(rl.Rectangle(rect.x + MARGIN, button_y, button_width, BUTTON_HEIGHT), "Reboot device"): - HARDWARE.reboot() - - if gui_button(rl.Rectangle(rect.x + MARGIN + button_width + BUTTON_SPACING, button_y, button_width, BUTTON_HEIGHT), "Start over", - button_style=ButtonStyle.PRIMARY): - self.state = SetupState.GETTING_STARTED - - def render_custom_url(self): - def handle_keyboard_result(result): - # Enter pressed - if result == 1: - url = self.keyboard.text - self.keyboard.clear() - if url: - self.download(url) - - # Cancel pressed - elif result == 0: - self.state = SetupState.SOFTWARE_SELECTION - - self.keyboard.set_title("Enter URL", "for Custom Software") - gui_app.set_modal_overlay(self.keyboard, callback=handle_keyboard_result) - - def download(self, url: str): - # autocomplete incomplete URLs - if re.match("^([^/.]+)/([^/]+)$", url): - url = f"https://installer.comma.ai/{url}" - - self.download_url = url - self.state = SetupState.DOWNLOADING - - self.download_thread = threading.Thread(target=self._download_thread, daemon=True) - self.download_thread.start() - - def _download_thread(self): - try: - import tempfile - - _, tmpfile = tempfile.mkstemp(prefix="installer_") - - headers = {"User-Agent": USER_AGENT, "X-openpilot-serial": HARDWARE.get_serial()} - req = urllib.request.Request(self.download_url, headers=headers) - - with open(tmpfile, 'wb') as f, urllib.request.urlopen(req, timeout=30) as response: - total_size = int(response.headers.get('content-length', 0)) - downloaded = 0 - block_size = 8192 - - while True: - buffer = response.read(block_size) - if not buffer: - break - - downloaded += len(buffer) - f.write(buffer) - - if total_size: - self.download_progress = int(downloaded * 100 / total_size) - - is_elf = False - with open(tmpfile, 'rb') as f: - header = f.read(4) - is_elf = header == b'\x7fELF' - - if not is_elf: - self.download_failed(self.download_url, "No custom software found at this URL.") - return - - os.rename(tmpfile, "/tmp/installer") - os.chmod("/tmp/installer", 0o755) - - with open("/tmp/installer_url", "w") as f: - f.write(self.download_url) - - gui_app.request_close() - - except Exception: - error_msg = "Ensure the entered URL is valid, and the device's internet connection is good." - self.download_failed(self.download_url, error_msg) - - def download_failed(self, url: str, reason: str): - self.failed_url = url - self.failed_reason = reason - self.state = SetupState.DOWNLOAD_FAILED - - -def main(): - try: - gui_app.init_window("Setup") - setup = Setup() - for _ in gui_app.render(): - setup.render(rl.Rectangle(0, 0, gui_app.width, gui_app.height)) - setup.close() - except Exception as e: - print(f"Setup error: {e}") - finally: - gui_app.close() - - -if __name__ == "__main__": - main() diff --git a/system/ui/spinner.py b/system/ui/spinner.py deleted file mode 100755 index 279ddf034d..0000000000 --- a/system/ui/spinner.py +++ /dev/null @@ -1,110 +0,0 @@ -#!/usr/bin/env python3 -import pyray as rl -import select -import sys - -from openpilot.system.ui.lib.application import gui_app -from openpilot.system.ui.lib.text_measure import measure_text_cached -from openpilot.system.ui.lib.widget import Widget -from openpilot.system.ui.text import wrap_text - -from openpilot.system.ui.sunnypilot.lib.application import gui_app_sp - -# Constants -PROGRESS_BAR_WIDTH = 1000 -PROGRESS_BAR_HEIGHT = 20 -DEGREES_PER_SECOND = 360.0 # one full rotation per second -MARGIN_H = 100 -TEXTURE_SIZE = 360 -FONT_SIZE = 96 -LINE_HEIGHT = 104 -DARKGRAY = (55, 55, 55, 255) - - -def clamp(value, min_value, max_value): - return max(min(value, max_value), min_value) - - -class Spinner(Widget): - def __init__(self): - super().__init__() - self._comma_texture = gui_app_sp.sp_texture("images/spinner_sunnypilot.png", TEXTURE_SIZE, TEXTURE_SIZE) - self._spinner_texture = gui_app.texture("images/spinner_track.png", TEXTURE_SIZE, TEXTURE_SIZE, alpha_premultiply=True) - self._rotation = 0.0 - self._progress: int | None = None - self._wrapped_lines: list[str] = [] - - def set_text(self, text: str) -> None: - if text.isdigit(): - self._progress = clamp(int(text), 0, 100) - self._wrapped_lines = [] - else: - self._progress = None - self._wrapped_lines = wrap_text(text, FONT_SIZE, gui_app.width - MARGIN_H) - - def _render(self, rect: rl.Rectangle): - if self._wrapped_lines: - # Calculate total height required for spinner and text - spacing = 50 - total_height = TEXTURE_SIZE + spacing + len(self._wrapped_lines) * LINE_HEIGHT - center_y = (rect.height - total_height) / 2.0 + TEXTURE_SIZE / 2.0 - else: - # Center spinner vertically - spacing = 150 - center_y = rect.height / 2.0 - y_pos = center_y + TEXTURE_SIZE / 2.0 + spacing - - center = rl.Vector2(rect.width / 2.0, center_y) - spinner_origin = rl.Vector2(TEXTURE_SIZE / 2.0, TEXTURE_SIZE / 2.0) - comma_position = rl.Vector2(center.x - TEXTURE_SIZE / 2.0, center.y - TEXTURE_SIZE / 2.0) - - delta_time = rl.get_frame_time() - self._rotation = (self._rotation + DEGREES_PER_SECOND * delta_time) % 360.0 - - # Draw rotating spinner and static comma logo - rl.draw_texture_pro(self._spinner_texture, rl.Rectangle(0, 0, TEXTURE_SIZE, TEXTURE_SIZE), - rl.Rectangle(center.x, center.y, TEXTURE_SIZE, TEXTURE_SIZE), - spinner_origin, self._rotation, rl.WHITE) - rl.draw_texture_v(self._comma_texture, comma_position, rl.WHITE) - - # Display the progress bar or text based on user input - if self._progress is not None: - bar = rl.Rectangle(center.x - PROGRESS_BAR_WIDTH / 2.0, y_pos, PROGRESS_BAR_WIDTH, PROGRESS_BAR_HEIGHT) - rl.draw_rectangle_rounded(bar, 1, 10, DARKGRAY) - - bar.width *= self._progress / 100.0 - rl.draw_rectangle_rounded(bar, 1, 10, rl.WHITE) - elif self._wrapped_lines: - for i, line in enumerate(self._wrapped_lines): - text_size = measure_text_cached(gui_app.font(), line, FONT_SIZE) - rl.draw_text_ex(gui_app.font(), line, rl.Vector2(center.x - text_size.x / 2, y_pos + i * LINE_HEIGHT), - FONT_SIZE, 0.0, rl.WHITE) - - -def _read_stdin(): - """Non-blocking read of available lines from stdin.""" - lines = [] - while True: - rlist, _, _ = select.select([sys.stdin], [], [], 0.0) - if not rlist: - break - line = sys.stdin.readline().strip() - if line == "": - break - lines.append(line) - return lines - - -def main(): - gui_app.init_window("Spinner") - spinner = Spinner() - for _ in gui_app.render(): - text_list = _read_stdin() - if text_list: - spinner.set_text(text_list[-1]) - - spinner.render(rl.Rectangle(0, 0, gui_app.width, gui_app.height)) - - -if __name__ == "__main__": - main() diff --git a/system/ui/sunnypilot/lib/application.py b/system/ui/sunnypilot/lib/application.py deleted file mode 100644 index 10227ce9fd..0000000000 --- a/system/ui/sunnypilot/lib/application.py +++ /dev/null @@ -1,21 +0,0 @@ -from openpilot.system.ui.lib.application import GuiApplication -from importlib.resources import as_file, files - -ASSETS_DIR_SP = files("openpilot.sunnypilot.selfdrive").joinpath("assets") - -class GuiApplicationSP(GuiApplication): - - def __init__(self, width: int, height: int): - super().__init__(width, height) - - def sp_texture(self, asset_path: str, width: int, height: int, alpha_premultiply=False, keep_aspect_ratio=True): - cache_key = f"{asset_path}_{width}_{height}_{alpha_premultiply}{keep_aspect_ratio}" - if cache_key in self._textures: - return self._textures[cache_key] - - with as_file(ASSETS_DIR_SP.joinpath(asset_path)) as fspath: - texture_obj = self._load_texture_from_image(fspath.as_posix(), width, height, alpha_premultiply, keep_aspect_ratio) - self._textures[cache_key] = texture_obj - return texture_obj - -gui_app_sp = GuiApplicationSP(2160, 1080) diff --git a/system/ui/text.py b/system/ui/text.py deleted file mode 100755 index 01a580a12b..0000000000 --- a/system/ui/text.py +++ /dev/null @@ -1,84 +0,0 @@ -#!/usr/bin/env python3 -import re -import sys -import pyray as rl -from openpilot.system.hardware import HARDWARE, PC -from openpilot.system.ui.lib.text_measure import measure_text_cached -from openpilot.system.ui.lib.button import gui_button, ButtonStyle -from openpilot.system.ui.lib.scroll_panel import GuiScrollPanel -from openpilot.system.ui.lib.application import gui_app -from openpilot.system.ui.lib.widget import Widget - -MARGIN = 50 -SPACING = 40 -FONT_SIZE = 72 -LINE_HEIGHT = 80 -BUTTON_SIZE = rl.Vector2(310, 160) - -DEMO_TEXT = """This is a sample text that will be wrapped and scrolled if necessary. - The text is long enough to demonstrate scrolling and word wrapping.""" * 30 - - -def wrap_text(text, font_size, max_width): - lines = [] - font = gui_app.font() - - for paragraph in text.split("\n"): - if not paragraph.strip(): - # Don't add empty lines first, ensuring wrap_text("") returns [] - if lines: - lines.append("") - continue - indent = re.match(r"^\s*", paragraph).group() - current_line = indent - words = re.split(r"(\s+)", paragraph[len(indent):]) - while len(words): - word = words.pop(0) - test_line = current_line + word + (words.pop(0) if words else "") - if measure_text_cached(font, test_line, font_size).x <= max_width: - current_line = test_line - else: - lines.append(current_line) - current_line = word + " " - current_line = current_line.rstrip() - if current_line: - lines.append(current_line) - - return lines - - -class TextWindow(Widget): - def __init__(self, text: str): - super().__init__() - self._textarea_rect = rl.Rectangle(MARGIN, MARGIN, gui_app.width - MARGIN * 2, gui_app.height - MARGIN * 2) - self._wrapped_lines = wrap_text(text, FONT_SIZE, self._textarea_rect.width - 20) - self._content_rect = rl.Rectangle(0, 0, self._textarea_rect.width - 20, len(self._wrapped_lines) * LINE_HEIGHT) - self._scroll_panel = GuiScrollPanel(show_vertical_scroll_bar=True) - self._scroll_panel._offset.y = -max(self._content_rect.height - self._textarea_rect.height, 0) - - def _render(self, rect: rl.Rectangle): - scroll = self._scroll_panel.handle_scroll(self._textarea_rect, self._content_rect) - rl.begin_scissor_mode(int(self._textarea_rect.x), int(self._textarea_rect.y), int(self._textarea_rect.width), int(self._textarea_rect.height)) - for i, line in enumerate(self._wrapped_lines): - position = rl.Vector2(self._textarea_rect.x + scroll.x, self._textarea_rect.y + scroll.y + i * LINE_HEIGHT) - if position.y + LINE_HEIGHT < self._textarea_rect.y or position.y > self._textarea_rect.y + self._textarea_rect.height: - continue - rl.draw_text_ex(gui_app.font(), line, position, FONT_SIZE, 0, rl.WHITE) - rl.end_scissor_mode() - - button_bounds = rl.Rectangle(rect.width - MARGIN - BUTTON_SIZE.x - SPACING, rect.height - MARGIN - BUTTON_SIZE.y, BUTTON_SIZE.x, BUTTON_SIZE.y) - ret = gui_button(button_bounds, "Exit" if PC else "Reboot", button_style=ButtonStyle.TRANSPARENT) - if ret: - if PC: - gui_app.request_close() - else: - HARDWARE.reboot() - return ret - - -if __name__ == "__main__": - text = sys.argv[1] if len(sys.argv) > 1 else DEMO_TEXT - gui_app.init_window("Text Viewer") - text_window = TextWindow(text) - for _ in gui_app.render(): - text_window.render(rl.Rectangle(0, 0, gui_app.width, gui_app.height)) diff --git a/system/ui/updater.py b/system/ui/updater.py deleted file mode 100755 index 3fd60cfb1d..0000000000 --- a/system/ui/updater.py +++ /dev/null @@ -1,170 +0,0 @@ -#!/usr/bin/env python3 -import sys -import subprocess -import threading -import pyray as rl -from enum import IntEnum - -from openpilot.system.hardware import HARDWARE -from openpilot.system.ui.lib.application import gui_app, FontWeight -from openpilot.system.ui.lib.button import gui_button, ButtonStyle -from openpilot.system.ui.lib.label import gui_text_box, gui_label -from openpilot.system.ui.lib.wifi_manager import WifiManagerWrapper -from openpilot.system.ui.lib.widget import Widget -from openpilot.system.ui.widgets.network import WifiManagerUI - -# Constants -MARGIN = 50 -BUTTON_HEIGHT = 160 -BUTTON_WIDTH = 400 -PROGRESS_BAR_HEIGHT = 72 -TITLE_FONT_SIZE = 80 -BODY_FONT_SIZE = 65 -BACKGROUND_COLOR = rl.BLACK -PROGRESS_BG_COLOR = rl.Color(41, 41, 41, 255) -PROGRESS_COLOR = rl.Color(54, 77, 239, 255) - - -class Screen(IntEnum): - PROMPT = 0 - WIFI = 1 - PROGRESS = 2 - - -class Updater(Widget): - def __init__(self, updater_path, manifest_path): - super().__init__() - self.updater = updater_path - self.manifest = manifest_path - self.current_screen = Screen.PROMPT - - self.progress_value = 0 - self.progress_text = "Loading..." - self.show_reboot_button = False - self.process = None - self.update_thread = None - self.wifi_manager = WifiManagerWrapper() - self.wifi_manager_ui = WifiManagerUI(self.wifi_manager) - - def install_update(self): - self.current_screen = Screen.PROGRESS - self.progress_value = 0 - self.progress_text = "Downloading..." - self.show_reboot_button = False - - # Start the update process in a separate thread - self.update_thread = threading.Thread(target=self._run_update_process) - self.update_thread.daemon = True - self.update_thread.start() - - def _run_update_process(self): - # TODO: just import it and run in a thread without a subprocess - cmd = [self.updater, "--swap", self.manifest] - self.process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, - text=True, bufsize=1, universal_newlines=True) - - for line in self.process.stdout: - parts = line.strip().split(":") - if len(parts) == 2: - self.progress_text = parts[0] - try: - self.progress_value = int(float(parts[1])) - except ValueError: - pass - - exit_code = self.process.wait() - if exit_code == 0: - HARDWARE.reboot() - else: - self.progress_text = "Update failed" - self.show_reboot_button = True - - def render_prompt_screen(self, rect: rl.Rectangle): - # Title - title_rect = rl.Rectangle(MARGIN + 50, 250, rect.width - MARGIN * 2 - 100, TITLE_FONT_SIZE) - gui_label(title_rect, "Update Required", TITLE_FONT_SIZE, font_weight=FontWeight.BOLD) - - # Description - desc_text = ("An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. " + - "The download size is approximately 1GB.") - - desc_rect = rl.Rectangle(MARGIN + 50, 250 + TITLE_FONT_SIZE + 75, rect.width - MARGIN * 2 - 100, BODY_FONT_SIZE * 3) - gui_text_box(desc_rect, desc_text, BODY_FONT_SIZE) - - # Buttons at the bottom - button_y = rect.height - MARGIN - BUTTON_HEIGHT - button_width = (rect.width - MARGIN * 3) // 2 - - # WiFi button - wifi_button_rect = rl.Rectangle(MARGIN, button_y, button_width, BUTTON_HEIGHT) - if gui_button(wifi_button_rect, "Connect to Wi-Fi"): - self.current_screen = Screen.WIFI - return # Return to avoid processing other buttons after screen change - - # Install button - install_button_rect = rl.Rectangle(MARGIN * 2 + button_width, button_y, button_width, BUTTON_HEIGHT) - if gui_button(install_button_rect, "Install", button_style=ButtonStyle.PRIMARY): - self.install_update() - return # Return to avoid further processing after action - - def render_wifi_screen(self, rect: rl.Rectangle): - # Draw the Wi-Fi manager UI - wifi_rect = rl.Rectangle(MARGIN + 50, MARGIN, rect.width - MARGIN * 2 - 100, rect.height - MARGIN * 2 - BUTTON_HEIGHT - 20) - self.wifi_manager_ui.render(wifi_rect) - - back_button_rect = rl.Rectangle(MARGIN, rect.height - MARGIN - BUTTON_HEIGHT, BUTTON_WIDTH, BUTTON_HEIGHT) - if gui_button(back_button_rect, "Back"): - self.current_screen = Screen.PROMPT - return # Return to avoid processing other interactions after screen change - - def render_progress_screen(self, rect: rl.Rectangle): - title_rect = rl.Rectangle(MARGIN + 100, 330, rect.width - MARGIN * 2 - 200, 100) - gui_label(title_rect, self.progress_text, 90, font_weight=FontWeight.SEMI_BOLD) - - # Progress bar - bar_rect = rl.Rectangle(MARGIN + 100, 330 + 100 + 100, rect.width - MARGIN * 2 - 200, PROGRESS_BAR_HEIGHT) - rl.draw_rectangle_rounded(bar_rect, 0.5, 10, PROGRESS_BG_COLOR) - - # Calculate the width of the progress chunk - progress_width = (bar_rect.width * self.progress_value) / 100 - if progress_width > 0: - progress_rect = rl.Rectangle(bar_rect.x, bar_rect.y, progress_width, bar_rect.height) - rl.draw_rectangle_rounded(progress_rect, 0.5, 10, PROGRESS_COLOR) - - # Show reboot button if needed - if self.show_reboot_button: - reboot_rect = rl.Rectangle(MARGIN + 100, rect.height - MARGIN - BUTTON_HEIGHT, BUTTON_WIDTH, BUTTON_HEIGHT) - if gui_button(reboot_rect, "Reboot"): - # Return True to signal main loop to exit before rebooting - HARDWARE.reboot() - return - - def _render(self, rect: rl.Rectangle): - if self.current_screen == Screen.PROMPT: - self.render_prompt_screen(rect) - elif self.current_screen == Screen.WIFI: - self.render_wifi_screen(rect) - elif self.current_screen == Screen.PROGRESS: - self.render_progress_screen(rect) - - -def main(): - if len(sys.argv) < 3: - print("Usage: updater.py ") - sys.exit(1) - - updater_path = sys.argv[1] - manifest_path = sys.argv[2] - - try: - gui_app.init_window("System Update") - updater = Updater(updater_path, manifest_path) - for _ in gui_app.render(): - updater.render(rl.Rectangle(0, 0, gui_app.width, gui_app.height)) - finally: - # Make sure we clean up even if there's an error - gui_app.close() - - -if __name__ == "__main__": - main() diff --git a/system/ui/widgets/confirm_dialog.py b/system/ui/widgets/confirm_dialog.py deleted file mode 100644 index 00361905d6..0000000000 --- a/system/ui/widgets/confirm_dialog.py +++ /dev/null @@ -1,68 +0,0 @@ -import pyray as rl -from openpilot.system.ui.lib.application import gui_app, FontWeight -from openpilot.system.ui.lib.button import gui_button, ButtonStyle -from openpilot.system.ui.lib.label import gui_text_box -from openpilot.system.ui.lib.widget import DialogResult - -DIALOG_WIDTH = 1520 -DIALOG_HEIGHT = 600 -BUTTON_HEIGHT = 160 -MARGIN = 50 -TEXT_AREA_HEIGHT_REDUCTION = 200 -BACKGROUND_COLOR = rl.Color(27, 27, 27, 255) - - -def confirm_dialog(message: str, confirm_text: str, cancel_text: str = "Cancel") -> DialogResult: - dialog_x = (gui_app.width - DIALOG_WIDTH) / 2 - dialog_y = (gui_app.height - DIALOG_HEIGHT) / 2 - dialog_rect = rl.Rectangle(dialog_x, dialog_y, DIALOG_WIDTH, DIALOG_HEIGHT) - - # Calculate button positions at the bottom of the dialog - bottom = dialog_rect.y + dialog_rect.height - button_width = (dialog_rect.width - 3 * MARGIN) // 2 - no_button_x = dialog_rect.x + MARGIN - yes_button_x = dialog_rect.x + dialog_rect.width - button_width - MARGIN - button_y = bottom - BUTTON_HEIGHT - MARGIN - no_button = rl.Rectangle(no_button_x, button_y, button_width, BUTTON_HEIGHT) - yes_button = rl.Rectangle(yes_button_x, button_y, button_width, BUTTON_HEIGHT) - - # Draw the dialog background - rl.draw_rectangle_rec(dialog_rect, BACKGROUND_COLOR) - - # Draw the message in the dialog, centered - text_rect = rl.Rectangle(dialog_rect.x + MARGIN, dialog_rect.y, dialog_rect.width - 2 * MARGIN, dialog_rect.height - TEXT_AREA_HEIGHT_REDUCTION) - gui_text_box( - text_rect, - message, - font_size=70, - alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER, - alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE, - font_weight=FontWeight.BOLD, - ) - - # Initialize result; -1 means no action taken yet - result = DialogResult.NO_ACTION - - # Check for keyboard input for accessibility - if rl.is_key_pressed(rl.KeyboardKey.KEY_ENTER): - result = DialogResult.CONFIRM - elif rl.is_key_pressed(rl.KeyboardKey.KEY_ESCAPE): - result = DialogResult.CANCEL - - # Check for button clicks - if cancel_text: - if gui_button(yes_button, confirm_text, button_style=ButtonStyle.PRIMARY): - result = DialogResult.CONFIRM - if gui_button(no_button, cancel_text): - result = DialogResult.CANCEL - else: - centered_button_x = dialog_rect.x + (dialog_rect.width - button_width) / 2 - centered_yes_button = rl.Rectangle(centered_button_x, button_y, button_width, BUTTON_HEIGHT) - if gui_button(centered_yes_button, confirm_text, button_style=ButtonStyle.PRIMARY): - result = DialogResult.CONFIRM - - return result - - -def alert_dialog(message: str, button_text: str = "OK") -> DialogResult: - return confirm_dialog(message, button_text, cancel_text="") diff --git a/system/ui/widgets/html_render.py b/system/ui/widgets/html_render.py deleted file mode 100644 index 07741af456..0000000000 --- a/system/ui/widgets/html_render.py +++ /dev/null @@ -1,194 +0,0 @@ -import re -import pyray as rl -from dataclasses import dataclass -from enum import Enum -from typing import Any -from openpilot.system.ui.lib.application import gui_app, FontWeight -from openpilot.system.ui.lib.wrap_text import wrap_text -from openpilot.system.ui.lib.scroll_panel import GuiScrollPanel -from openpilot.system.ui.lib.widget import Widget, DialogResult -from openpilot.system.ui.lib.button import gui_button, ButtonStyle - - -class ElementType(Enum): - H1 = "h1" - H2 = "h2" - H3 = "h3" - H4 = "h4" - H5 = "h5" - H6 = "h6" - P = "p" - BR = "br" - - -@dataclass -class HtmlElement: - type: ElementType - content: str - font_size: int - font_weight: FontWeight - color: rl.Color - margin_top: int - margin_bottom: int - line_height: float = 1.2 - - -class HtmlRenderer(Widget): - def __init__(self, file_path: str): - self.elements: list[HtmlElement] = [] - self._normal_font = gui_app.font(FontWeight.NORMAL) - self._bold_font = gui_app.font(FontWeight.BOLD) - self._scroll_panel = GuiScrollPanel() - - self.styles: dict[ElementType, dict[str, Any]] = { - ElementType.H1: {"size": 68, "weight": FontWeight.BOLD, "color": rl.BLACK, "margin_top": 20, "margin_bottom": 16}, - ElementType.H2: {"size": 60, "weight": FontWeight.BOLD, "color": rl.BLACK, "margin_top": 24, "margin_bottom": 12}, - ElementType.H3: {"size": 52, "weight": FontWeight.BOLD, "color": rl.BLACK, "margin_top": 20, "margin_bottom": 10}, - ElementType.H4: {"size": 48, "weight": FontWeight.BOLD, "color": rl.BLACK, "margin_top": 16, "margin_bottom": 8}, - ElementType.H5: {"size": 44, "weight": FontWeight.BOLD, "color": rl.BLACK, "margin_top": 12, "margin_bottom": 6}, - ElementType.H6: {"size": 40, "weight": FontWeight.BOLD, "color": rl.BLACK, "margin_top": 10, "margin_bottom": 4}, - ElementType.P: {"size": 38, "weight": FontWeight.NORMAL, "color": rl.Color(40, 40, 40, 255), "margin_top": 8, "margin_bottom": 12}, - ElementType.BR: {"size": 0, "weight": FontWeight.NORMAL, "color": rl.BLACK, "margin_top": 0, "margin_bottom": 12}, - } - - self.parse_html_file(file_path) - - def parse_html_file(self, file_path: str) -> None: - with open(file_path, encoding='utf-8') as file: - content = file.read() - self.parse_html_content(content) - - def parse_html_content(self, html_content: str) -> None: - self.elements.clear() - - # Remove HTML comments - html_content = re.sub(r'', '', html_content, flags=re.DOTALL) - - # Remove DOCTYPE, html, head, body tags but keep their content - html_content = re.sub(r']*>', '', html_content) - html_content = re.sub(r']*>', '', html_content) - - # Find all HTML elements - pattern = r'<(h[1-6]|p)(?:[^>]*)>(.*?)|' - matches = re.finditer(pattern, html_content, re.DOTALL | re.IGNORECASE) - - for match in matches: - if match.group(0).lower().startswith(' tags - self._add_element(ElementType.BR, "") - else: - tag = match.group(1).lower() - content = match.group(2).strip() - - # Clean up content - remove extra whitespace - content = re.sub(r'\s+', ' ', content) - content = content.strip() - - if content: # Only add non-empty elements - element_type = ElementType(tag) - self._add_element(element_type, content) - - def _add_element(self, element_type: ElementType, content: str) -> None: - style = self.styles[element_type] - - element = HtmlElement( - type=element_type, - content=content, - font_size=style["size"], - font_weight=style["weight"], - color=style["color"], - margin_top=style["margin_top"], - margin_bottom=style["margin_bottom"], - ) - - self.elements.append(element) - - def _render(self, rect: rl.Rectangle): - margin = 50 - content_rect = rl.Rectangle(rect.x + margin, rect.y + margin, rect.width - (margin * 2), rect.height - (margin * 2)) - - button_height = 160 - button_spacing = 20 - scrollable_height = content_rect.height - button_height - button_spacing - - scrollable_rect = rl.Rectangle(content_rect.x, content_rect.y, content_rect.width, scrollable_height) - - total_height = self.get_total_height(int(scrollable_rect.width)) - scroll_content_rect = rl.Rectangle(scrollable_rect.x, scrollable_rect.y, scrollable_rect.width, total_height) - scroll_offset = self._scroll_panel.handle_scroll(scrollable_rect, scroll_content_rect) - - rl.begin_scissor_mode(int(scrollable_rect.x), int(scrollable_rect.y), int(scrollable_rect.width), int(scrollable_rect.height)) - self._render_content(scrollable_rect, scroll_offset.y) - rl.end_scissor_mode() - - button_width = (rect.width - 3 * 50) // 3 - button_x = content_rect.x + (content_rect.width - button_width) / 2 - button_y = content_rect.y + content_rect.height - button_height - button_rect = rl.Rectangle(button_x, button_y, button_width, button_height) - if gui_button(button_rect, "OK", button_style=ButtonStyle.PRIMARY) == 1: - return DialogResult.CONFIRM - - return DialogResult.NO_ACTION - - def _render_content(self, rect: rl.Rectangle, scroll_offset: float = 0) -> float: - current_y = rect.y + scroll_offset - padding = 20 - content_width = rect.width - (padding * 2) - - for element in self.elements: - if element.type == ElementType.BR: - current_y += element.margin_bottom - continue - - current_y += element.margin_top - if current_y > rect.y + rect.height: - break - - if element.content: - font = self._get_font(element.font_weight) - wrapped_lines = wrap_text(font, element.content, element.font_size, int(content_width)) - - for line in wrapped_lines: - if current_y < rect.y - element.font_size: - current_y += element.font_size * element.line_height - continue - - if current_y > rect.y + rect.height: - break - - rl.draw_text_ex(font, line, rl.Vector2(rect.x + padding, current_y), element.font_size, 0, rl.WHITE) - - current_y += element.font_size * element.line_height - - # Apply bottom margin - current_y += element.margin_bottom - - return current_y - rect.y - scroll_offset # Return total content height - - def get_total_height(self, content_width: int) -> float: - total_height = 0.0 - padding = 20 - usable_width = content_width - (padding * 2) - - for element in self.elements: - if element.type == ElementType.BR: - total_height += element.margin_bottom - continue - - total_height += element.margin_top - - if element.content: - font = self._get_font(element.font_weight) - wrapped_lines = wrap_text(font, element.content, element.font_size, int(usable_width)) - - for _ in wrapped_lines: - total_height += element.font_size * element.line_height - - total_height += element.margin_bottom - - return total_height - - def _get_font(self, weight: FontWeight): - if weight == FontWeight.BOLD: - return self._bold_font - return self._normal_font diff --git a/system/ui/widgets/keyboard.py b/system/ui/widgets/keyboard.py deleted file mode 100644 index 338706e73d..0000000000 --- a/system/ui/widgets/keyboard.py +++ /dev/null @@ -1,242 +0,0 @@ -import time -from typing import Literal -import pyray as rl -from openpilot.system.ui.lib.application import gui_app, FontWeight -from openpilot.system.ui.lib.button import ButtonStyle, gui_button -from openpilot.system.ui.lib.inputbox import InputBox -from openpilot.system.ui.lib.label import gui_label -from openpilot.system.ui.lib.widget import Widget - -KEY_FONT_SIZE = 96 -DOUBLE_CLICK_THRESHOLD = 0.5 # seconds -DELETE_REPEAT_DELAY = 0.5 -DELETE_REPEAT_INTERVAL = 0.07 - -# Constants for special keys -CONTENT_MARGIN = 50 -BACKSPACE_KEY = "<-" -ENTER_KEY = "->" -SPACE_KEY = " " -SHIFT_INACTIVE_KEY = "SHIFT_OFF" -SHIFT_ACTIVE_KEY = "SHIFT_ON" -CAPS_LOCK_KEY = "CAPS" -NUMERIC_KEY = "123" -SYMBOL_KEY = "#+=" -ABC_KEY = "ABC" - -# Define keyboard layouts as a dictionary for easier access -KEYBOARD_LAYOUTS = { - "lowercase": [ - ["q", "w", "e", "r", "t", "y", "u", "i", "o", "p"], - ["a", "s", "d", "f", "g", "h", "j", "k", "l"], - [SHIFT_INACTIVE_KEY, "z", "x", "c", "v", "b", "n", "m", BACKSPACE_KEY], - [NUMERIC_KEY, "/", "-", SPACE_KEY, ".", ENTER_KEY], - ], - "uppercase": [ - ["Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P"], - ["A", "S", "D", "F", "G", "H", "J", "K", "L"], - [SHIFT_ACTIVE_KEY, "Z", "X", "C", "V", "B", "N", "M", BACKSPACE_KEY], - [NUMERIC_KEY, "/", "-", SPACE_KEY, ".", ENTER_KEY], - ], - "numbers": [ - ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"], - ["-", "/", ":", ";", "(", ")", "$", "&", "@", "\""], - [SYMBOL_KEY, ".", ",", "?", "!", "`", BACKSPACE_KEY], - [ABC_KEY, SPACE_KEY, ".", ENTER_KEY], - ], - "specials": [ - ["[", "]", "{", "}", "#", "%", "^", "*", "+", "="], - ["_", "\\", "|", "~", "<", ">", "€", "£", "¥", "•"], - [NUMERIC_KEY, ".", ",", "?", "!", "'", BACKSPACE_KEY], - [ABC_KEY, SPACE_KEY, ".", ENTER_KEY], - ], -} - - -class Keyboard(Widget): - def __init__(self, max_text_size: int = 255, min_text_size: int = 0, password_mode: bool = False, show_password_toggle: bool = False): - super().__init__() - self._layout_name: Literal["lowercase", "uppercase", "numbers", "specials"] = "lowercase" - self._caps_lock = False - self._last_shift_press_time = 0 - self._title = "" - self._sub_title = "" - - self._max_text_size = max_text_size - self._min_text_size = min_text_size - self._input_box = InputBox(max_text_size) - self._password_mode = password_mode - self._show_password_toggle = show_password_toggle - - # Backspace key repeat tracking - self._backspace_pressed: bool = False - self._backspace_press_time: float = 0.0 - self._backspace_last_repeat: float = 0.0 - - self._eye_open_texture = gui_app.texture("icons/eye_open.png", 81, 54) - self._eye_closed_texture = gui_app.texture("icons/eye_closed.png", 81, 54) - self._key_icons = { - BACKSPACE_KEY: gui_app.texture("icons/backspace.png", 80, 80), - SHIFT_INACTIVE_KEY: gui_app.texture("icons/shift.png", 80, 80), - SHIFT_ACTIVE_KEY: gui_app.texture("icons/shift-fill.png", 80, 80), - CAPS_LOCK_KEY: gui_app.texture("icons/capslock-fill.png", 80, 80), - ENTER_KEY: gui_app.texture("icons/arrow-right.png", 80, 80), - } - - @property - def text(self): - return self._input_box.text - - def clear(self): - self._layout_name = "lowercase" - self._caps_lock = False - self._input_box.clear() - self._backspace_pressed = False - - def set_title(self, title: str, sub_title: str = ""): - self._title = title - self._sub_title = sub_title - - def _render(self, rect: rl.Rectangle): - rect = rl.Rectangle(rect.x + CONTENT_MARGIN, rect.y + CONTENT_MARGIN, rect.width - 2 * CONTENT_MARGIN, rect.height - 2 * CONTENT_MARGIN) - gui_label(rl.Rectangle(rect.x, rect.y, rect.width, 95), self._title, 90, font_weight=FontWeight.BOLD) - gui_label(rl.Rectangle(rect.x, rect.y + 95, rect.width, 60), self._sub_title, 55, font_weight=FontWeight.NORMAL) - if gui_button(rl.Rectangle(rect.x + rect.width - 386, rect.y, 386, 125), "Cancel"): - self.clear() - return 0 - - # Draw input box and password toggle - input_margin = 25 - input_box_rect = rl.Rectangle(rect.x + input_margin, rect.y + 160, rect.width - input_margin, 100) - self._render_input_area(input_box_rect) - - # Process backspace key repeat if it's held down - if not rl.is_mouse_button_down(rl.MouseButton.MOUSE_BUTTON_LEFT): - self._backspace_pressed = False - - if self._backspace_pressed: - current_time = time.monotonic() - time_since_press = current_time - self._backspace_press_time - - # After initial delay, start repeating with shorter intervals - if time_since_press > DELETE_REPEAT_DELAY: - time_since_last_repeat = current_time - self._backspace_last_repeat - if time_since_last_repeat > DELETE_REPEAT_INTERVAL: - self._input_box.delete_char_before_cursor() - self._backspace_last_repeat = current_time - - layout = KEYBOARD_LAYOUTS[self._layout_name] - - h_space, v_space = 15, 15 - row_y_start = rect.y + 300 # Starting Y position for the first row - key_height = (rect.height - 300 - 3 * v_space) / 4 - key_max_width = (rect.width - (len(layout[2]) - 1) * h_space) / len(layout[2]) - - # Iterate over the rows of keys in the current layout - for row, keys in enumerate(layout): - key_width = min((rect.width - (180 if row == 1 else 0) - h_space * (len(keys) - 1)) / len(keys), key_max_width) - start_x = rect.x + (90 if row == 1 else 0) - - for i, key in enumerate(keys): - if i > 0: - start_x += h_space - - new_width = (key_width * 3 + h_space * 2) if key == SPACE_KEY else (key_width * 2 + h_space if key == ENTER_KEY else key_width) - key_rect = rl.Rectangle(start_x, row_y_start + row * (key_height + v_space), new_width, key_height) - start_x += new_width - - is_enabled = key != ENTER_KEY or len(self._input_box.text) >= self._min_text_size - result = -1 - - # Check for backspace key press-and-hold - mouse_pos = rl.get_mouse_position() - mouse_over_key = rl.check_collision_point_rec(mouse_pos, key_rect) - - if key == BACKSPACE_KEY and mouse_over_key: - if rl.is_mouse_button_pressed(rl.MouseButton.MOUSE_BUTTON_LEFT): - self._backspace_pressed = True - self._backspace_press_time = time.monotonic() - self._backspace_last_repeat = time.monotonic() - - if key in self._key_icons: - if key == SHIFT_ACTIVE_KEY and self._caps_lock: - key = CAPS_LOCK_KEY - texture = self._key_icons[key] - result = gui_button(key_rect, "", icon=texture, button_style=ButtonStyle.PRIMARY if key == ENTER_KEY else ButtonStyle.NORMAL, is_enabled=is_enabled) - else: - result = gui_button(key_rect, key, KEY_FONT_SIZE, is_enabled=is_enabled) - - if result: - if key == ENTER_KEY: - return 1 - else: - self.handle_key_press(key) - - return -1 - - def _render_input_area(self, input_rect: rl.Rectangle): - if self._show_password_toggle: - self._input_box.set_password_mode(self._password_mode) - self._input_box.render(rl.Rectangle(input_rect.x, input_rect.y, input_rect.width - 100, input_rect.height)) - - # render eye icon - eye_texture = self._eye_closed_texture if self._password_mode else self._eye_open_texture - - eye_rect = rl.Rectangle(input_rect.x + input_rect.width - 90, input_rect.y, 80, input_rect.height) - eye_x = eye_rect.x + (eye_rect.width - eye_texture.width) / 2 - eye_y = eye_rect.y + (eye_rect.height - eye_texture.height) / 2 - - rl.draw_texture_v(eye_texture, rl.Vector2(eye_x, eye_y), rl.WHITE) - - # Handle click on eye icon - if rl.is_mouse_button_pressed(rl.MouseButton.MOUSE_BUTTON_LEFT) and rl.check_collision_point_rec( - rl.get_mouse_position(), eye_rect - ): - self._password_mode = not self._password_mode - else: - self._input_box.render(input_rect) - - rl.draw_line_ex( - rl.Vector2(input_rect.x, input_rect.y + input_rect.height - 2), - rl.Vector2(input_rect.x + input_rect.width, input_rect.y + input_rect.height - 2), - 3.0, # 3 pixel thickness - rl.Color(189, 189, 189, 255), - ) - - def handle_key_press(self, key): - if key in (CAPS_LOCK_KEY, ABC_KEY): - self._caps_lock = False - self._layout_name = "lowercase" - elif key == SHIFT_INACTIVE_KEY: - self._last_shift_press_time = time.monotonic() - self._layout_name = "uppercase" - elif key == SHIFT_ACTIVE_KEY: - if time.monotonic() - self._last_shift_press_time < DOUBLE_CLICK_THRESHOLD: - self._caps_lock = True - else: - self._layout_name = "lowercase" - elif key == NUMERIC_KEY: - self._layout_name = "numbers" - elif key == SYMBOL_KEY: - self._layout_name = "specials" - elif key == BACKSPACE_KEY: - self._input_box.delete_char_before_cursor() - else: - self._input_box.add_char_at_cursor(key) - if not self._caps_lock and self._layout_name == "uppercase": - self._layout_name = "lowercase" - - -if __name__ == "__main__": - gui_app.init_window("Keyboard") - keyboard = Keyboard(min_text_size=8, show_password_toggle=True) - for _ in gui_app.render(): - keyboard.set_title("Keyboard Input", "Type your text below") - result = keyboard.render(rl.Rectangle(0, 0, gui_app.width, gui_app.height)) - if result == 1: - print(f"You typed: {keyboard.text}") - gui_app.request_close() - elif result == 0: - print("Canceled") - gui_app.request_close() - gui_app.close() diff --git a/system/ui/widgets/network.py b/system/ui/widgets/network.py deleted file mode 100644 index 0613bb1f12..0000000000 --- a/system/ui/widgets/network.py +++ /dev/null @@ -1,250 +0,0 @@ -from dataclasses import dataclass -from threading import Lock -from typing import Literal - -import pyray as rl -from openpilot.system.ui.lib.application import gui_app -from openpilot.system.ui.lib.button import ButtonStyle, gui_button -from openpilot.system.ui.lib.label import gui_label -from openpilot.system.ui.lib.scroll_panel import GuiScrollPanel -from openpilot.system.ui.lib.wifi_manager import NetworkInfo, WifiManagerCallbacks, WifiManagerWrapper, SecurityType -from openpilot.system.ui.widgets.keyboard import Keyboard -from openpilot.system.ui.widgets.confirm_dialog import confirm_dialog -from openpilot.system.ui.lib.widget import Widget - -NM_DEVICE_STATE_NEED_AUTH = 60 -MIN_PASSWORD_LENGTH = 8 -MAX_PASSWORD_LENGTH = 64 -ITEM_HEIGHT = 160 -ICON_SIZE = 50 - -STRENGTH_ICONS = [ - "icons/wifi_strength_low.png", - "icons/wifi_strength_medium.png", - "icons/wifi_strength_high.png", - "icons/wifi_strength_full.png", -] - - -@dataclass -class StateIdle: - action: Literal["idle"] = "idle" - - -@dataclass -class StateConnecting: - network: NetworkInfo - action: Literal["connecting"] = "connecting" - - -@dataclass -class StateNeedsAuth: - network: NetworkInfo - action: Literal["needs_auth"] = "needs_auth" - - -@dataclass -class StateShowForgetConfirm: - network: NetworkInfo - action: Literal["show_forget_confirm"] = "show_forget_confirm" - - -@dataclass -class StateForgetting: - network: NetworkInfo - action: Literal["forgetting"] = "forgetting" - - -UIState = StateIdle | StateConnecting | StateNeedsAuth | StateShowForgetConfirm | StateForgetting - - -class WifiManagerUI(Widget): - def __init__(self, wifi_manager: WifiManagerWrapper): - super().__init__() - self.state: UIState = StateIdle() - self.btn_width: int = 200 - self.scroll_panel = GuiScrollPanel() - self.keyboard = Keyboard(max_text_size=MAX_PASSWORD_LENGTH, min_text_size=MIN_PASSWORD_LENGTH, show_password_toggle=True) - - self._networks: list[NetworkInfo] = [] - self._lock = Lock() - self.wifi_manager = wifi_manager - - self.wifi_manager.set_callbacks( - WifiManagerCallbacks( - need_auth=self._on_need_auth, - activated=self._on_activated, - forgotten=self._on_forgotten, - networks_updated=self._on_network_updated, - connection_failed=self._on_connection_failed - ) - ) - self.wifi_manager.start() - self.wifi_manager.connect() - - def _render(self, rect: rl.Rectangle): - with self._lock: - if not self._networks: - gui_label(rect, "Scanning Wi-Fi networks...", 72, alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER) - return - - match self.state: - case StateNeedsAuth(network): - self.keyboard.set_title("Enter password", f"for {network.ssid}") - gui_app.set_modal_overlay(self.keyboard, lambda result: self._on_password_entered(network, result)) - case StateShowForgetConfirm(network): - gui_app.set_modal_overlay(lambda: confirm_dialog(f'Forget Wi-Fi Network "{network.ssid}"?', "Forget"), - callback=lambda result: self.on_forgot_confirm_finished(network, result)) - case _: - self._draw_network_list(rect) - - def _on_password_entered(self, network: NetworkInfo, result: int): - if result == 1: - password = self.keyboard.text - self.keyboard.clear() - - if len(password) >= MIN_PASSWORD_LENGTH: - self.connect_to_network(network, password) - elif result == 0: - self.state = StateIdle() - - def on_forgot_confirm_finished(self, network, result: int): - if result == 1: - self.forget_network(network) - elif result == 0: - self.state = StateIdle() - - def _draw_network_list(self, rect: rl.Rectangle): - content_rect = rl.Rectangle(rect.x, rect.y, rect.width, len(self._networks) * ITEM_HEIGHT) - offset = self.scroll_panel.handle_scroll(rect, content_rect) - clicked = self.scroll_panel.is_touch_valid() and rl.is_mouse_button_released(rl.MouseButton.MOUSE_BUTTON_LEFT) - - rl.begin_scissor_mode(int(rect.x), int(rect.y), int(rect.width), int(rect.height)) - for i, network in enumerate(self._networks): - y_offset = rect.y + i * ITEM_HEIGHT + offset.y - item_rect = rl.Rectangle(rect.x, y_offset, rect.width, ITEM_HEIGHT) - if not rl.check_collision_recs(item_rect, rect): - continue - - self._draw_network_item(item_rect, network, clicked) - if i < len(self._networks) - 1: - line_y = int(item_rect.y + item_rect.height - 1) - rl.draw_line(int(item_rect.x), int(line_y), int(item_rect.x + item_rect.width), line_y, rl.LIGHTGRAY) - - rl.end_scissor_mode() - - def _draw_network_item(self, rect, network: NetworkInfo, clicked: bool): - spacing = 50 - ssid_rect = rl.Rectangle(rect.x, rect.y, rect.width - self.btn_width * 2, ITEM_HEIGHT) - signal_icon_rect = rl.Rectangle(rect.x + rect.width - ICON_SIZE, rect.y + (ITEM_HEIGHT - ICON_SIZE) / 2, ICON_SIZE, ICON_SIZE) - security_icon_rect = rl.Rectangle(signal_icon_rect.x - spacing - ICON_SIZE, rect.y + (ITEM_HEIGHT - ICON_SIZE) / 2, ICON_SIZE, ICON_SIZE) - - gui_label(ssid_rect, network.ssid, 55) - - status_text = "" - match self.state: - case StateConnecting(network=connecting): - if connecting.ssid == network.ssid: - status_text = "CONNECTING..." - case StateForgetting(network=forgetting): - if forgetting.ssid == network.ssid: - status_text = "FORGETTING..." - - if status_text: - status_text_rect = rl.Rectangle(security_icon_rect.x - 410, rect.y, 410, ITEM_HEIGHT) - gui_label(status_text_rect, status_text, font_size=48, alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER) - else: - # If the network is saved, show the "Forget" button - if network.is_saved: - forget_btn_rect = rl.Rectangle( - security_icon_rect.x - self.btn_width - spacing, - rect.y + (ITEM_HEIGHT - 80) / 2, - self.btn_width, - 80, - ) - if isinstance(self.state, StateIdle) and gui_button(forget_btn_rect, "Forget", button_style=ButtonStyle.ACTION) and clicked: - self.state = StateShowForgetConfirm(network) - - self._draw_status_icon(security_icon_rect, network) - self._draw_signal_strength_icon(signal_icon_rect, network) - - if isinstance(self.state, StateIdle) and rl.check_collision_point_rec(rl.get_mouse_position(), ssid_rect) and clicked: - if not network.is_saved and network.security_type != SecurityType.OPEN: - self.state = StateNeedsAuth(network) - elif not network.is_connected: - self.connect_to_network(network) - - def _draw_status_icon(self, rect, network: NetworkInfo): - """Draw the status icon based on network's connection state""" - icon_file = None - if network.is_connected: - icon_file = "icons/checkmark.png" - elif network.security_type == SecurityType.UNSUPPORTED: - icon_file = "icons/circled_slash.png" - elif network.security_type != SecurityType.OPEN: - icon_file = "icons/lock_closed.png" - - if not icon_file: - return - - texture = gui_app.texture(icon_file, ICON_SIZE, ICON_SIZE) - icon_rect = rl.Vector2(rect.x, rect.y + (ICON_SIZE - texture.height) / 2) - rl.draw_texture_v(texture, icon_rect, rl.WHITE) - - def _draw_signal_strength_icon(self, rect: rl.Rectangle, network: NetworkInfo): - """Draw the Wi-Fi signal strength icon based on network's signal strength""" - strength_level = max(0, min(3, round(network.strength / 33.0))) - rl.draw_texture_v(gui_app.texture(STRENGTH_ICONS[strength_level], ICON_SIZE, ICON_SIZE), rl.Vector2(rect.x, rect.y), rl.WHITE) - - def connect_to_network(self, network: NetworkInfo, password=''): - self.state = StateConnecting(network) - if network.is_saved and not password: - self.wifi_manager.activate_connection(network.ssid) - else: - self.wifi_manager.connect_to_network(network.ssid, password) - - def forget_network(self, network: NetworkInfo): - self.state = StateForgetting(network) - network.is_saved = False - self.wifi_manager.forget_connection(network.ssid) - - def _on_network_updated(self, networks: list[NetworkInfo]): - with self._lock: - self._networks = networks - - def _on_need_auth(self, ssid): - with self._lock: - network = next((n for n in self._networks if n.ssid == ssid), None) - if network: - self.state = StateNeedsAuth(network) - - def _on_activated(self): - with self._lock: - if isinstance(self.state, StateConnecting): - self.state = StateIdle() - - def _on_forgotten(self, ssid): - with self._lock: - if isinstance(self.state, StateForgetting): - self.state = StateIdle() - - def _on_connection_failed(self, ssid: str, error: str): - with self._lock: - if isinstance(self.state, StateConnecting): - self.state = StateIdle() - - -def main(): - gui_app.init_window("Wi-Fi Manager") - wifi_manager = WifiManagerWrapper() - wifi_ui = WifiManagerUI(wifi_manager) - - for _ in gui_app.render(): - wifi_ui.render(rl.Rectangle(50, 50, gui_app.width - 100, gui_app.height - 100)) - - wifi_manager.shutdown() - gui_app.close() - - -if __name__ == "__main__": - main() diff --git a/system/ui/widgets/option_dialog.py b/system/ui/widgets/option_dialog.py deleted file mode 100644 index a2958ee1f4..0000000000 --- a/system/ui/widgets/option_dialog.py +++ /dev/null @@ -1,71 +0,0 @@ -import pyray as rl -from openpilot.system.ui.lib.application import FontWeight -from openpilot.system.ui.lib.button import gui_button, ButtonStyle, TextAlignment -from openpilot.system.ui.lib.label import gui_label -from openpilot.system.ui.lib.scroll_panel import GuiScrollPanel -from openpilot.system.ui.lib.widget import Widget - -# Constants -MARGIN = 50 -TITLE_FONT_SIZE = 70 -ITEM_HEIGHT = 135 -BUTTON_SPACING = 50 -BUTTON_HEIGHT = 160 -ITEM_SPACING = 50 -LIST_ITEM_SPACING = 25 - - -class MultiOptionDialog(Widget): - def __init__(self, title, options, current=""): - super().__init__() - self.title = title - self.options = options - self.current = current - self.selection = current - self.scroll = GuiScrollPanel() - - def _render(self, rect): - dialog_rect = rl.Rectangle(rect.x + MARGIN, rect.y + MARGIN, rect.width - 2 * MARGIN, rect.height - 2 * MARGIN) - rl.draw_rectangle_rounded(dialog_rect, 0.02, 20, rl.Color(30, 30, 30, 255)) - - content_rect = rl.Rectangle(dialog_rect.x + MARGIN, dialog_rect.y + MARGIN, - dialog_rect.width - 2 * MARGIN, dialog_rect.height - 2 * MARGIN) - - gui_label(rl.Rectangle(content_rect.x, content_rect.y, content_rect.width, TITLE_FONT_SIZE), self.title, 70, font_weight=FontWeight.BOLD) - - # Options area - options_y = content_rect.y + TITLE_FONT_SIZE + ITEM_SPACING - options_h = content_rect.height - TITLE_FONT_SIZE - BUTTON_HEIGHT - 2 * ITEM_SPACING - view_rect = rl.Rectangle(content_rect.x, options_y, content_rect.width, options_h) - content_h = len(self.options) * (ITEM_HEIGHT + 10) - list_content_rect = rl.Rectangle(content_rect.x, options_y, content_rect.width, content_h) - - # Scroll and render options - offset = self.scroll.handle_scroll(view_rect, list_content_rect) - valid_click = self.scroll.is_touch_valid() and rl.is_mouse_button_released(rl.MouseButton.MOUSE_BUTTON_LEFT) - - rl.begin_scissor_mode(int(view_rect.x), int(options_y), int(view_rect.width), int(options_h)) - for i, option in enumerate(self.options): - item_y = options_y + i * (ITEM_HEIGHT + LIST_ITEM_SPACING) + offset.y - item_rect = rl.Rectangle(view_rect.x, item_y, view_rect.width, ITEM_HEIGHT) - - if rl.check_collision_recs(item_rect, view_rect): - selected = option == self.selection - style = ButtonStyle.PRIMARY if selected else ButtonStyle.NORMAL - - if gui_button(item_rect, option, button_style=style, text_alignment=TextAlignment.LEFT) and valid_click: - self.selection = option - rl.end_scissor_mode() - - # Buttons - button_y = content_rect.y + content_rect.height - BUTTON_HEIGHT - button_w = (content_rect.width - BUTTON_SPACING) / 2 - - if gui_button(rl.Rectangle(content_rect.x, button_y, button_w, BUTTON_HEIGHT), "Cancel"): - return 0 - - if gui_button(rl.Rectangle(content_rect.x + button_w + BUTTON_SPACING, button_y, button_w, BUTTON_HEIGHT), - "Select", is_enabled=self.selection != self.current, button_style=ButtonStyle.PRIMARY): - return 1 - - return -1 diff --git a/system/updated/casync/casync.py b/system/updated/casync/casync.py deleted file mode 100755 index 7a3303a9e9..0000000000 --- a/system/updated/casync/casync.py +++ /dev/null @@ -1,246 +0,0 @@ -#!/usr/bin/env python3 -import io -import lzma -import os -import pathlib -import struct -import sys -import time -from abc import ABC, abstractmethod -from collections import defaultdict, namedtuple -from collections.abc import Callable -from typing import IO - -import requests -from Crypto.Hash import SHA512 -from openpilot.system.updated.casync import tar -from openpilot.system.updated.casync.common import create_casync_tar_package - -CA_FORMAT_INDEX = 0x96824d9c7b129ff9 -CA_FORMAT_TABLE = 0xe75b9e112f17417d -CA_FORMAT_TABLE_TAIL_MARKER = 0xe75b9e112f17417 -FLAGS = 0xb000000000000000 - -CA_HEADER_LEN = 48 -CA_TABLE_HEADER_LEN = 16 -CA_TABLE_ENTRY_LEN = 40 -CA_TABLE_MIN_LEN = CA_TABLE_HEADER_LEN + CA_TABLE_ENTRY_LEN - -CHUNK_DOWNLOAD_TIMEOUT = 60 -CHUNK_DOWNLOAD_RETRIES = 3 - -CAIBX_DOWNLOAD_TIMEOUT = 120 - -Chunk = namedtuple('Chunk', ['sha', 'offset', 'length']) -ChunkDict = dict[bytes, Chunk] - - -class ChunkReader(ABC): - @abstractmethod - def read(self, chunk: Chunk) -> bytes: - ... - - -class BinaryChunkReader(ChunkReader): - """Reads chunks from a local file""" - def __init__(self, file_like: IO[bytes]) -> None: - super().__init__() - self.f = file_like - - def read(self, chunk: Chunk) -> bytes: - self.f.seek(chunk.offset) - return self.f.read(chunk.length) - - -class FileChunkReader(BinaryChunkReader): - def __init__(self, path: str) -> None: - super().__init__(open(path, 'rb')) - - def __del__(self): - self.f.close() - - -class RemoteChunkReader(ChunkReader): - """Reads lzma compressed chunks from a remote store""" - - def __init__(self, url: str) -> None: - super().__init__() - self.url = url - self.session = requests.Session() - - def read(self, chunk: Chunk) -> bytes: - sha_hex = chunk.sha.hex() - url = os.path.join(self.url, sha_hex[:4], sha_hex + ".cacnk") - - if os.path.isfile(url): - with open(url, 'rb') as f: - contents = f.read() - else: - for i in range(CHUNK_DOWNLOAD_RETRIES): - try: - resp = self.session.get(url, timeout=CHUNK_DOWNLOAD_TIMEOUT) - break - except Exception: - if i == CHUNK_DOWNLOAD_RETRIES - 1: - raise - time.sleep(CHUNK_DOWNLOAD_TIMEOUT) - - resp.raise_for_status() - contents = resp.content - - decompressor = lzma.LZMADecompressor(format=lzma.FORMAT_AUTO) - return decompressor.decompress(contents) - - -class DirectoryTarChunkReader(BinaryChunkReader): - """creates a tar archive of a directory and reads chunks from it""" - - def __init__(self, path: str, cache_file: str) -> None: - create_casync_tar_package(pathlib.Path(path), pathlib.Path(cache_file)) - - self.f = open(cache_file, "rb") - return super().__init__(self.f) - - def __del__(self): - self.f.close() - os.unlink(self.f.name) - - -def parse_caibx(caibx_path: str) -> list[Chunk]: - """Parses the chunks from a caibx file. Can handle both local and remote files. - Returns a list of chunks with hash, offset and length""" - caibx: io.BufferedIOBase - if os.path.isfile(caibx_path): - caibx = open(caibx_path, 'rb') - else: - resp = requests.get(caibx_path, timeout=CAIBX_DOWNLOAD_TIMEOUT) - resp.raise_for_status() - caibx = io.BytesIO(resp.content) - - caibx.seek(0, os.SEEK_END) - caibx_len = caibx.tell() - caibx.seek(0, os.SEEK_SET) - - # Parse header - length, magic, flags, min_size, _, max_size = struct.unpack("= min_size - - chunks.append(Chunk(sha, offset, length)) - offset = new_offset - - caibx.close() - return chunks - - -def build_chunk_dict(chunks: list[Chunk]) -> ChunkDict: - """Turn a list of chunks into a dict for faster lookups based on hash. - Keep first chunk since it's more likely to be already downloaded.""" - r = {} - for c in chunks: - if c.sha not in r: - r[c.sha] = c - return r - - -def extract(target: list[Chunk], - sources: list[tuple[str, ChunkReader, ChunkDict]], - out_path: str, - progress: Callable[[int], None] = None): - stats: dict[str, int] = defaultdict(int) - - mode = 'rb+' if os.path.exists(out_path) else 'wb' - with open(out_path, mode) as out: - for cur_chunk in target: - - # Find source for desired chunk - for name, chunk_reader, store_chunks in sources: - if cur_chunk.sha in store_chunks: - bts = chunk_reader.read(store_chunks[cur_chunk.sha]) - - # Check length - if len(bts) != cur_chunk.length: - continue - - # Check hash - if SHA512.new(bts, truncate="256").digest() != cur_chunk.sha: - continue - - # Write to output - out.seek(cur_chunk.offset) - out.write(bts) - - stats[name] += cur_chunk.length - - if progress is not None: - progress(sum(stats.values())) - - break - else: - raise RuntimeError("Desired chunk not found in provided stores") - - return stats - - -def extract_directory(target: list[Chunk], - sources: list[tuple[str, ChunkReader, ChunkDict]], - out_path: str, - tmp_file: str, - progress: Callable[[int], None] = None): - """extract a directory stored as a casync tar archive""" - - stats = extract(target, sources, tmp_file, progress) - - with open(tmp_file, "rb") as f: - tar.extract_tar_archive(f, pathlib.Path(out_path)) - - return stats - - -def print_stats(stats: dict[str, int]): - total_bytes = sum(stats.values()) - print(f"Total size: {total_bytes / 1024 / 1024:.2f} MB") - for name, total in stats.items(): - print(f" {name}: {total / 1024 / 1024:.2f} MB ({total / total_bytes * 100:.1f}%)") - - -def extract_simple(caibx_path, out_path, store_path): - # (name, callback, chunks) - target = parse_caibx(caibx_path) - sources = [ - # (store_path, RemoteChunkReader(store_path), build_chunk_dict(target)), - (store_path, FileChunkReader(store_path), build_chunk_dict(target)), - ] - - return extract(target, sources, out_path) - - -if __name__ == "__main__": - caibx = sys.argv[1] - out = sys.argv[2] - store = sys.argv[3] - - stats = extract_simple(caibx, out, store) - print_stats(stats) diff --git a/system/updated/casync/common.py b/system/updated/casync/common.py deleted file mode 100644 index 6979f5cb06..0000000000 --- a/system/updated/casync/common.py +++ /dev/null @@ -1,61 +0,0 @@ -import dataclasses -import json -import pathlib -import subprocess - -from openpilot.system.version import BUILD_METADATA_FILENAME, BuildMetadata -from openpilot.system.updated.casync import tar - - -CASYNC_ARGS = ["--with=symlinks", "--with=permissions", "--compression=xz", "--chunk-size=16M"] -CASYNC_FILES = [BUILD_METADATA_FILENAME] - - -def run(cmd): - return subprocess.check_output(cmd) - - -def get_exclude_set(path) -> set[str]: - exclude_set = set(CASYNC_FILES) - - for file in path.rglob("*"): - if file.is_file() or file.is_symlink(): - - while file.resolve() != path.resolve(): - exclude_set.add(str(file.relative_to(path))) - - file = file.parent - - return exclude_set - - -def create_build_metadata_file(path: pathlib.Path, build_metadata: BuildMetadata): - with open(path / BUILD_METADATA_FILENAME, "w") as f: - build_metadata_dict = dataclasses.asdict(build_metadata) - build_metadata_dict["openpilot"].pop("is_dirty") # this is determined at runtime - build_metadata_dict.pop("channel") # channel is unrelated to the build itself - f.write(json.dumps(build_metadata_dict)) - - -def is_not_git(path: pathlib.Path) -> bool: - return ".git" not in path.parts - - -def create_casync_tar_package(target_dir: pathlib.Path, output_path: pathlib.Path): - tar.create_tar_archive(output_path, target_dir, is_not_git) - - -def create_casync_from_file(file: pathlib.Path, output_dir: pathlib.Path, caibx_name: str): - caibx_file = output_dir / f"{caibx_name}.caibx" - run(["casync", "make", *CASYNC_ARGS, caibx_file, str(file)]) - - return caibx_file - - -def create_casync_release(target_dir: pathlib.Path, output_dir: pathlib.Path, caibx_name: str): - tar_file = output_dir / f"{caibx_name}.tar" - create_casync_tar_package(target_dir, tar_file) - caibx_file = create_casync_from_file(tar_file, output_dir, caibx_name) - tar_file.unlink() - digest = run(["casync", "digest", *CASYNC_ARGS, target_dir]).decode("utf-8").strip() - return digest, caibx_file diff --git a/system/updated/casync/tar.py b/system/updated/casync/tar.py deleted file mode 100644 index a5a8238bba..0000000000 --- a/system/updated/casync/tar.py +++ /dev/null @@ -1,39 +0,0 @@ -import pathlib -import tarfile -from typing import IO -from collections.abc import Callable - - -def include_default(_) -> bool: - return True - - -def create_tar_archive(filename: pathlib.Path, directory: pathlib.Path, include: Callable[[pathlib.Path], bool] = include_default): - """Creates a tar archive of a directory""" - - with tarfile.open(filename, 'w') as tar: - for file in sorted(directory.rglob("*"), key=lambda f: f.stat().st_size if f.is_file() else 0, reverse=True): - if not include(file): - continue - relative_path = str(file.relative_to(directory)) - if file.is_symlink(): - info = tarfile.TarInfo(relative_path) - info.type = tarfile.SYMTYPE - info.linkpath = str(file.readlink()) - tar.addfile(info) - - elif file.is_file(): - info = tarfile.TarInfo(relative_path) - info.size = file.stat().st_size - info.type = tarfile.REGTYPE - info.mode = file.stat().st_mode - with file.open('rb') as f: - tar.addfile(info, f) - - -def extract_tar_archive(fh: IO[bytes], directory: pathlib.Path): - """Extracts a tar archive to a directory""" - - tar = tarfile.open(fileobj=fh, mode='r') - tar.extractall(str(directory), filter=lambda info, path: info) - tar.close() diff --git a/system/updated/casync/tests/test_casync.py b/system/updated/casync/tests/test_casync.py deleted file mode 100644 index bc171e7432..0000000000 --- a/system/updated/casync/tests/test_casync.py +++ /dev/null @@ -1,264 +0,0 @@ -import pytest -import os -import pathlib -import tempfile -import subprocess - -from openpilot.system.updated.casync import casync -from openpilot.system.updated.casync import tar - -# dd if=/dev/zero of=/tmp/img.raw bs=1M count=2 -# sudo losetup -f /tmp/img.raw -# losetup -a | grep img.raw -LOOPBACK = os.environ.get('LOOPBACK', None) - - -@pytest.mark.skip("not used yet") -class TestCasync: - @classmethod - def setup_class(cls): - cls.tmpdir = tempfile.TemporaryDirectory() - - # Build example contents - chunk_a = [i % 256 for i in range(1024)] * 512 - chunk_b = [(256 - i) % 256 for i in range(1024)] * 512 - zeroes = [0] * (1024 * 128) - contents = chunk_a + chunk_b + zeroes + chunk_a - - cls.contents = bytes(contents) - - # Write to file - cls.orig_fn = os.path.join(cls.tmpdir.name, 'orig.bin') - with open(cls.orig_fn, 'wb') as f: - f.write(cls.contents) - - # Create casync files - cls.manifest_fn = os.path.join(cls.tmpdir.name, 'orig.caibx') - cls.store_fn = os.path.join(cls.tmpdir.name, 'store') - subprocess.check_output(["casync", "make", "--compression=xz", "--store", cls.store_fn, cls.manifest_fn, cls.orig_fn]) - - target = casync.parse_caibx(cls.manifest_fn) - hashes = [c.sha.hex() for c in target] - - # Ensure we have chunk reuse - assert len(hashes) > len(set(hashes)) - - def setup_method(self): - # Clear target_lo - if LOOPBACK is not None: - self.target_lo = LOOPBACK - with open(self.target_lo, 'wb') as f: - f.write(b"0" * len(self.contents)) - - self.target_fn = os.path.join(self.tmpdir.name, next(tempfile._get_candidate_names())) - self.seed_fn = os.path.join(self.tmpdir.name, next(tempfile._get_candidate_names())) - - def teardown_method(self): - for fn in [self.target_fn, self.seed_fn]: - try: - os.unlink(fn) - except FileNotFoundError: - pass - - def test_simple_extract(self): - target = casync.parse_caibx(self.manifest_fn) - - sources = [('remote', casync.RemoteChunkReader(self.store_fn), casync.build_chunk_dict(target))] - stats = casync.extract(target, sources, self.target_fn) - - with open(self.target_fn, 'rb') as target_f: - assert target_f.read() == self.contents - - assert stats['remote'] == len(self.contents) - - def test_seed(self): - target = casync.parse_caibx(self.manifest_fn) - - # Populate seed with half of the target contents - with open(self.seed_fn, 'wb') as seed_f: - seed_f.write(self.contents[:len(self.contents) // 2]) - - sources = [('seed', casync.FileChunkReader(self.seed_fn), casync.build_chunk_dict(target))] - sources += [('remote', casync.RemoteChunkReader(self.store_fn), casync.build_chunk_dict(target))] - stats = casync.extract(target, sources, self.target_fn) - - with open(self.target_fn, 'rb') as target_f: - assert target_f.read() == self.contents - - assert stats['seed'] > 0 - assert stats['remote'] < len(self.contents) - - def test_already_done(self): - """Test that an already flashed target doesn't download any chunks""" - target = casync.parse_caibx(self.manifest_fn) - - with open(self.target_fn, 'wb') as f: - f.write(self.contents) - - sources = [('target', casync.FileChunkReader(self.target_fn), casync.build_chunk_dict(target))] - sources += [('remote', casync.RemoteChunkReader(self.store_fn), casync.build_chunk_dict(target))] - - stats = casync.extract(target, sources, self.target_fn) - - with open(self.target_fn, 'rb') as f: - assert f.read() == self.contents - - assert stats['target'] == len(self.contents) - - def test_chunk_reuse(self): - """Test that chunks that are reused are only downloaded once""" - target = casync.parse_caibx(self.manifest_fn) - - # Ensure target exists - with open(self.target_fn, 'wb'): - pass - - sources = [('target', casync.FileChunkReader(self.target_fn), casync.build_chunk_dict(target))] - sources += [('remote', casync.RemoteChunkReader(self.store_fn), casync.build_chunk_dict(target))] - - stats = casync.extract(target, sources, self.target_fn) - - with open(self.target_fn, 'rb') as f: - assert f.read() == self.contents - - assert stats['remote'] < len(self.contents) - - @pytest.mark.skipif(not LOOPBACK, reason="requires loopback device") - def test_lo_simple_extract(self): - target = casync.parse_caibx(self.manifest_fn) - sources = [('remote', casync.RemoteChunkReader(self.store_fn), casync.build_chunk_dict(target))] - - stats = casync.extract(target, sources, self.target_lo) - - with open(self.target_lo, 'rb') as target_f: - assert target_f.read(len(self.contents)) == self.contents - - assert stats['remote'] == len(self.contents) - - @pytest.mark.skipif(not LOOPBACK, reason="requires loopback device") - def test_lo_chunk_reuse(self): - """Test that chunks that are reused are only downloaded once""" - target = casync.parse_caibx(self.manifest_fn) - - sources = [('target', casync.FileChunkReader(self.target_lo), casync.build_chunk_dict(target))] - sources += [('remote', casync.RemoteChunkReader(self.store_fn), casync.build_chunk_dict(target))] - - stats = casync.extract(target, sources, self.target_lo) - - with open(self.target_lo, 'rb') as f: - assert f.read(len(self.contents)) == self.contents - - assert stats['remote'] < len(self.contents) - - -@pytest.mark.skip("not used yet") -class TestCasyncDirectory: - """Tests extracting a directory stored as a casync tar archive""" - - NUM_FILES = 16 - - @classmethod - def setup_cache(cls, directory, files=None): - if files is None: - files = range(cls.NUM_FILES) - - chunk_a = [i % 256 for i in range(1024)] * 512 - chunk_b = [(256 - i) % 256 for i in range(1024)] * 512 - zeroes = [0] * (1024 * 128) - cls.contents = chunk_a + chunk_b + zeroes + chunk_a - cls.contents = bytes(cls.contents) - - for i in files: - with open(os.path.join(directory, f"file_{i}.txt"), "wb") as f: - f.write(cls.contents) - - os.symlink(f"file_{i}.txt", os.path.join(directory, f"link_{i}.txt")) - - @classmethod - def setup_class(cls): - cls.tmpdir = tempfile.TemporaryDirectory() - - # Create casync files - cls.manifest_fn = os.path.join(cls.tmpdir.name, 'orig.caibx') - cls.store_fn = os.path.join(cls.tmpdir.name, 'store') - - cls.directory_to_extract = tempfile.TemporaryDirectory() - cls.setup_cache(cls.directory_to_extract.name) - - cls.orig_fn = os.path.join(cls.tmpdir.name, 'orig.tar') - tar.create_tar_archive(cls.orig_fn, pathlib.Path(cls.directory_to_extract.name)) - - subprocess.check_output(["casync", "make", "--compression=xz", "--store", cls.store_fn, cls.manifest_fn, cls.orig_fn]) - - @classmethod - def teardown_class(cls): - cls.tmpdir.cleanup() - cls.directory_to_extract.cleanup() - - def setup_method(self): - self.cache_dir = tempfile.TemporaryDirectory() - self.working_dir = tempfile.TemporaryDirectory() - self.out_dir = tempfile.TemporaryDirectory() - - def teardown_method(self): - self.cache_dir.cleanup() - self.working_dir.cleanup() - self.out_dir.cleanup() - - def run_test(self): - target = casync.parse_caibx(self.manifest_fn) - - cache_filename = os.path.join(self.working_dir.name, "cache.tar") - tmp_filename = os.path.join(self.working_dir.name, "tmp.tar") - - sources = [('cache', casync.DirectoryTarChunkReader(self.cache_dir.name, cache_filename), casync.build_chunk_dict(target))] - sources += [('remote', casync.RemoteChunkReader(self.store_fn), casync.build_chunk_dict(target))] - - stats = casync.extract_directory(target, sources, pathlib.Path(self.out_dir.name), tmp_filename) - - with open(os.path.join(self.out_dir.name, "file_0.txt"), "rb") as f: - assert f.read() == self.contents - - with open(os.path.join(self.out_dir.name, "link_0.txt"), "rb") as f: - assert f.read() == self.contents - assert os.readlink(os.path.join(self.out_dir.name, "link_0.txt")) == "file_0.txt" - - return stats - - def test_no_cache(self): - self.setup_cache(self.cache_dir.name, []) - stats = self.run_test() - assert stats['remote'] > 0 - assert stats['cache'] == 0 - - def test_full_cache(self): - self.setup_cache(self.cache_dir.name, range(self.NUM_FILES)) - stats = self.run_test() - assert stats['remote'] == 0 - assert stats['cache'] > 0 - - def test_one_file_cache(self): - self.setup_cache(self.cache_dir.name, range(1)) - stats = self.run_test() - assert stats['remote'] > 0 - assert stats['cache'] > 0 - assert stats['cache'] < stats['remote'] - - def test_one_file_incorrect_cache(self): - self.setup_cache(self.cache_dir.name, range(self.NUM_FILES)) - with open(os.path.join(self.cache_dir.name, "file_0.txt"), "wb") as f: - f.write(b"1234") - - stats = self.run_test() - assert stats['remote'] > 0 - assert stats['cache'] > 0 - assert stats['cache'] > stats['remote'] - - def test_one_file_missing_cache(self): - self.setup_cache(self.cache_dir.name, range(self.NUM_FILES)) - os.unlink(os.path.join(self.cache_dir.name, "file_12.txt")) - - stats = self.run_test() - assert stats['remote'] > 0 - assert stats['cache'] > 0 - assert stats['cache'] > stats['remote'] diff --git a/system/updated/tests/test_base.py b/system/updated/tests/test_base.py deleted file mode 100644 index 52287c58f9..0000000000 --- a/system/updated/tests/test_base.py +++ /dev/null @@ -1,259 +0,0 @@ -import os -import pathlib -import shutil -import signal -import stat -import subprocess -import tempfile -import time -import pytest - -from openpilot.common.params import Params -from openpilot.system.manager.process import ManagerProcess -from openpilot.selfdrive.test.helpers import processes_context - - -def get_consistent_flag(path: str) -> bool: - consistent_file = pathlib.Path(os.path.join(path, ".overlay_consistent")) - return consistent_file.is_file() - - -def run(args, **kwargs): - return subprocess.check_output(args, **kwargs) - - -def update_release(directory, name, version, agnos_version, release_notes): - with open(directory / "RELEASES.md", "w") as f: - f.write(release_notes) - - (directory / "common").mkdir(exist_ok=True) - - with open(directory / "common" / "version.h", "w") as f: - f.write(f'#define COMMA_VERSION "{version}"') - - launch_env = directory / "launch_env.sh" - with open(launch_env, "w") as f: - f.write(f'export AGNOS_VERSION="{agnos_version}"') - - st = os.stat(launch_env) - os.chmod(launch_env, st.st_mode | stat.S_IEXEC) - - test_symlink = directory / "test_symlink" - if not os.path.exists(str(test_symlink)): - os.symlink("common/version.h", test_symlink) - - -def get_version(path: str) -> str: - with open(os.path.join(path, "common", "version.h")) as f: - return f.read().split('"')[1] - - -@pytest.mark.slow # TODO: can we test overlayfs in GHA? -class TestBaseUpdate: - @classmethod - def setup_class(cls): - if "Base" in cls.__name__: - pytest.skip() - - def setup_method(self): - self.tmpdir = tempfile.mkdtemp() - - run(["sudo", "mount", "-t", "tmpfs", "tmpfs", self.tmpdir]) # overlayfs doesn't work inside of docker unless this is a tmpfs - - self.mock_update_path = pathlib.Path(self.tmpdir) - - self.params = Params() - - self.basedir = self.mock_update_path / "openpilot" - self.basedir.mkdir() - - self.staging_root = self.mock_update_path / "safe_staging" - self.staging_root.mkdir() - - self.remote_dir = self.mock_update_path / "remote" - self.remote_dir.mkdir() - - os.environ["UPDATER_STAGING_ROOT"] = str(self.staging_root) - os.environ["UPDATER_LOCK_FILE"] = str(self.mock_update_path / "safe_staging_overlay.lock") - - self.MOCK_RELEASES = { - "release3": ("0.1.2", "1.2", "0.1.2 release notes"), - "master": ("0.1.3", "1.2", "0.1.3 release notes"), - } - - @pytest.fixture(autouse=True) - def mock_basedir(self, mocker): - mocker.patch("openpilot.common.basedir.BASEDIR", self.basedir) - - def set_target_branch(self, branch): - self.params.put("UpdaterTargetBranch", branch) - - def setup_basedir_release(self, release): - self.params = Params() - self.set_target_branch(release) - - def update_remote_release(self, release): - raise NotImplementedError("") - - def setup_remote_release(self, release): - raise NotImplementedError("") - - def additional_context(self): - raise NotImplementedError("") - - def teardown_method(self): - try: - run(["sudo", "umount", "-l", str(self.staging_root / "merged")]) - run(["sudo", "umount", "-l", self.tmpdir]) - shutil.rmtree(self.tmpdir) - except Exception: - print("cleanup failed...") - - def wait_for_condition(self, condition, timeout=12): - start = time.monotonic() - while True: - waited = time.monotonic() - start - if condition(): - print(f"waited {waited}s for condition ") - return waited - - if waited > timeout: - raise TimeoutError("timed out waiting for condition") - - time.sleep(1) - - def _test_finalized_update(self, branch, version, agnos_version, release_notes): - assert get_version(str(self.staging_root / "finalized")) == version - assert get_consistent_flag(str(self.staging_root / "finalized")) - assert os.access(str(self.staging_root / "finalized" / "launch_env.sh"), os.X_OK) - - with open(self.staging_root / "finalized" / "test_symlink") as f: - assert version in f.read() - -class ParamsBaseUpdateTest(TestBaseUpdate): - def _test_finalized_update(self, branch, version, agnos_version, release_notes): - assert self.params.get("UpdaterNewDescription", encoding="utf-8").startswith(f"{version} / {branch}") - assert self.params.get("UpdaterNewReleaseNotes", encoding="utf-8") == f"{release_notes}\n" - super()._test_finalized_update(branch, version, agnos_version, release_notes) - - def send_check_for_updates_signal(self, updated: ManagerProcess): - updated.signal(signal.SIGUSR1.value) - - def send_download_signal(self, updated: ManagerProcess): - updated.signal(signal.SIGHUP.value) - - def _test_params(self, branch, fetch_available, update_available): - assert self.params.get("UpdaterTargetBranch", encoding="utf-8") == branch - assert self.params.get_bool("UpdaterFetchAvailable") == fetch_available - assert self.params.get_bool("UpdateAvailable") == update_available - - def wait_for_idle(self): - self.wait_for_condition(lambda: self.params.get("UpdaterState", encoding="utf-8") == "idle") - - def wait_for_failed(self): - self.wait_for_condition(lambda: self.params.get("UpdateFailedCount", encoding="utf-8") is not None and \ - int(self.params.get("UpdateFailedCount", encoding="utf-8")) > 0) - - def wait_for_fetch_available(self): - self.wait_for_condition(lambda: self.params.get_bool("UpdaterFetchAvailable")) - - def wait_for_update_available(self): - self.wait_for_condition(lambda: self.params.get_bool("UpdateAvailable")) - - def test_no_update(self): - # Start on release3, ensure we don't fetch any updates - self.setup_remote_release("release3") - self.setup_basedir_release("release3") - - with self.additional_context(), processes_context(["updated"]) as [updated]: - self._test_params("release3", False, False) - self.wait_for_idle() - self._test_params("release3", False, False) - - self.send_check_for_updates_signal(updated) - - self.wait_for_idle() - - self._test_params("release3", False, False) - - def test_new_release(self): - # Start on release3, simulate a release3 commit, ensure we fetch that update properly - self.setup_remote_release("release3") - self.setup_basedir_release("release3") - - with self.additional_context(), processes_context(["updated"]) as [updated]: - self._test_params("release3", False, False) - self.wait_for_idle() - self._test_params("release3", False, False) - - self.MOCK_RELEASES["release3"] = ("0.1.3", "1.2", "0.1.3 release notes") - self.update_remote_release("release3") - - self.send_check_for_updates_signal(updated) - - self.wait_for_fetch_available() - - self._test_params("release3", True, False) - - self.send_download_signal(updated) - - self.wait_for_update_available() - - self._test_params("release3", False, True) - self._test_finalized_update("release3", *self.MOCK_RELEASES["release3"]) - - def test_switch_branches(self): - # Start on release3, request to switch to master manually, ensure we switched - self.setup_remote_release("release3") - self.setup_remote_release("master") - self.setup_basedir_release("release3") - - with self.additional_context(), processes_context(["updated"]) as [updated]: - self._test_params("release3", False, False) - self.wait_for_idle() - self._test_params("release3", False, False) - - self.set_target_branch("master") - self.send_check_for_updates_signal(updated) - - self.wait_for_fetch_available() - - self._test_params("master", True, False) - - self.send_download_signal(updated) - - self.wait_for_update_available() - - self._test_params("master", False, True) - self._test_finalized_update("master", *self.MOCK_RELEASES["master"]) - - def test_agnos_update(self, mocker): - # Start on release3, push an update with an agnos change - self.setup_remote_release("release3") - self.setup_basedir_release("release3") - - with self.additional_context(), processes_context(["updated"]) as [updated]: - mocker.patch("openpilot.system.hardware.AGNOS", "True") - mocker.patch("openpilot.system.hardware.tici.hardware.Tici.get_os_version", "1.2") - mocker.patch("openpilot.system.hardware.tici.agnos.get_target_slot_number") - mocker.patch("openpilot.system.hardware.tici.agnos.flash_agnos_update") - - self._test_params("release3", False, False) - self.wait_for_idle() - self._test_params("release3", False, False) - - self.MOCK_RELEASES["release3"] = ("0.1.3", "1.3", "0.1.3 release notes") - self.update_remote_release("release3") - - self.send_check_for_updates_signal(updated) - - self.wait_for_fetch_available() - - self._test_params("release3", True, False) - - self.send_download_signal(updated) - - self.wait_for_update_available() - - self._test_params("release3", False, True) - self._test_finalized_update("release3", *self.MOCK_RELEASES["release3"]) diff --git a/system/updated/tests/test_git.py b/system/updated/tests/test_git.py deleted file mode 100644 index 5a5a27000b..0000000000 --- a/system/updated/tests/test_git.py +++ /dev/null @@ -1,22 +0,0 @@ -import contextlib -from openpilot.system.updated.tests.test_base import ParamsBaseUpdateTest, run, update_release - - -class TestUpdateDGitStrategy(ParamsBaseUpdateTest): - def update_remote_release(self, release): - update_release(self.remote_dir, release, *self.MOCK_RELEASES[release]) - run(["git", "add", "."], cwd=self.remote_dir) - run(["git", "commit", "-m", f"openpilot release {release}"], cwd=self.remote_dir) - - def setup_remote_release(self, release): - run(["git", "init"], cwd=self.remote_dir) - run(["git", "checkout", "-b", release], cwd=self.remote_dir) - self.update_remote_release(release) - - def setup_basedir_release(self, release): - super().setup_basedir_release(release) - run(["git", "clone", "-b", release, self.remote_dir, self.basedir]) - - @contextlib.contextmanager - def additional_context(self): - yield diff --git a/system/version.py b/system/version.py deleted file mode 100755 index 11c6ced2b7..0000000000 --- a/system/version.py +++ /dev/null @@ -1,185 +0,0 @@ -#!/usr/bin/env python3 -from dataclasses import dataclass -from functools import cache -import json -import os -import pathlib -import subprocess - -from openpilot.common.basedir import BASEDIR -from openpilot.common.swaglog import cloudlog -from openpilot.common.git import get_commit, get_origin, get_branch, get_short_branch, get_commit_date - -RELEASE_SP_BRANCHES = ['release-c3'] -TESTED_SP_BRANCHES = ['staging-c3', 'staging-c3-new'] -MASTER_SP_BRANCHES = ['master', 'master-new'] -RELEASE_BRANCHES = ['release3-staging', 'release3', 'nightly'] + RELEASE_SP_BRANCHES -TESTED_BRANCHES = RELEASE_BRANCHES + ['devel', 'devel-staging', 'nightly-dev'] + TESTED_SP_BRANCHES - -BUILD_METADATA_FILENAME = "build.json" - -training_version: bytes = b"0.2.0" -terms_version: bytes = b"2" - - -def get_version(path: str = BASEDIR) -> str: - with open(os.path.join(path, "common", "version.h")) as _versionf: - version = _versionf.read().split('"')[1] - return version - - -def get_release_notes(path: str = BASEDIR) -> str: - with open(os.path.join(path, "RELEASES.md")) as f: - return f.read().split('\n\n', 1)[0] - - -@cache -def is_prebuilt(path: str = BASEDIR) -> bool: - return os.path.exists(os.path.join(path, 'prebuilt')) - - -@cache -def is_dirty(cwd: str = BASEDIR) -> bool: - origin = get_origin() - branch = get_branch() - if not origin or not branch: - return True - - dirty = False - try: - # Actually check dirty files - if not is_prebuilt(cwd): - # This is needed otherwise touched files might show up as modified - try: - subprocess.check_call(["git", "update-index", "--refresh"], cwd=cwd) - except subprocess.CalledProcessError: - pass - - dirty = (subprocess.call(["git", "diff-index", "--quiet", branch, "--"], cwd=cwd)) != 0 - except subprocess.CalledProcessError: - cloudlog.exception("git subprocess failed while checking dirty") - dirty = True - - return dirty - - -@dataclass -class OpenpilotMetadata: - version: str - release_notes: str - git_commit: str - git_origin: str - git_commit_date: str - build_style: str - is_dirty: bool # whether there are local changes - - @property - def short_version(self) -> str: - return self.version.split('-')[0] - - @property - def comma_remote(self) -> bool: - # note to fork maintainers, this is used for release metrics. please do not - # touch this to get rid of the orange startup alert. there's better ways to do that - return self.git_normalized_origin == "github.com/commaai/openpilot" - - @property - def git_normalized_origin(self) -> str: - return self.git_origin \ - .replace("git@", "", 1) \ - .replace(".git", "", 1) \ - .replace("https://", "", 1) \ - .replace(":", "/", 1) - - -@dataclass -class BuildMetadata: - channel: str - openpilot: OpenpilotMetadata - - @property - def tested_channel(self) -> bool: - return self.channel in TESTED_BRANCHES - - @property - def release_channel(self) -> bool: - return self.channel in RELEASE_BRANCHES - - @property - def canonical(self) -> str: - return f"{self.openpilot.version}-{self.openpilot.git_commit}-{self.openpilot.build_style}" - - @property - def ui_description(self) -> str: - return f"{self.openpilot.version} / {self.openpilot.git_commit[:6]} / {self.channel}" - - @property - def master_channel(self) -> bool: - return self.channel in MASTER_SP_BRANCHES - - @property - def channel_type(self) -> str: - if self.channel.startswith("dev-"): - return "development" - elif self.channel.startswith("staging-"): - return "staging" - elif self.master_channel: - return "master" - elif self.tested_channel: - return "release" - else: - return "feature" - - -def build_metadata_from_dict(build_metadata: dict) -> BuildMetadata: - channel = build_metadata.get("channel", "unknown") - openpilot_metadata = build_metadata.get("openpilot", {}) - version = openpilot_metadata.get("version", "unknown") - release_notes = openpilot_metadata.get("release_notes", "unknown") - git_commit = openpilot_metadata.get("git_commit", "unknown") - git_origin = openpilot_metadata.get("git_origin", "unknown") - git_commit_date = openpilot_metadata.get("git_commit_date", "unknown") - build_style = openpilot_metadata.get("build_style", "unknown") - return BuildMetadata(channel, - OpenpilotMetadata( - version=version, - release_notes=release_notes, - git_commit=git_commit, - git_origin=git_origin, - git_commit_date=git_commit_date, - build_style=build_style, - is_dirty=False)) - - -def get_build_metadata(path: str = BASEDIR) -> BuildMetadata: - build_metadata_path = pathlib.Path(path) / BUILD_METADATA_FILENAME - - if build_metadata_path.exists(): - build_metadata = json.loads(build_metadata_path.read_text()) - return build_metadata_from_dict(build_metadata) - - git_folder = pathlib.Path(path) / ".git" - - if git_folder.exists(): - return BuildMetadata(get_short_branch(path), - OpenpilotMetadata( - version=get_version(path), - release_notes=get_release_notes(path), - git_commit=get_commit(path), - git_origin=get_origin(path), - git_commit_date=get_commit_date(path), - build_style="unknown", - is_dirty=is_dirty(path))) - - cloudlog.exception("unable to get build metadata") - raise Exception("invalid build metadata") - - -if __name__ == "__main__": - from openpilot.common.params import Params - - params = Params() - params.put("TermsVersion", terms_version) - params.put("TrainingVersion", training_version) - - print(get_build_metadata()) diff --git a/system/webrtc/device/audio.py b/system/webrtc/device/audio.py deleted file mode 100644 index 4b22033e03..0000000000 --- a/system/webrtc/device/audio.py +++ /dev/null @@ -1,109 +0,0 @@ -import asyncio -import io - -import aiortc -import av -import numpy as np -import pyaudio - - -class AudioInputStreamTrack(aiortc.mediastreams.AudioStreamTrack): - PYAUDIO_TO_AV_FORMAT_MAP = { - pyaudio.paUInt8: 'u8', - pyaudio.paInt16: 's16', - pyaudio.paInt24: 's24', - pyaudio.paInt32: 's32', - pyaudio.paFloat32: 'flt', - } - - def __init__(self, audio_format: int = pyaudio.paInt16, rate: int = 16000, channels: int = 1, packet_time: float = 0.020, device_index: int = None): - super().__init__() - - self.p = pyaudio.PyAudio() - chunk_size = int(packet_time * rate) - self.stream = self.p.open(format=audio_format, - channels=channels, - rate=rate, - frames_per_buffer=chunk_size, - input=True, - input_device_index=device_index) - self.format = audio_format - self.rate = rate - self.channels = channels - self.packet_time = packet_time - self.chunk_size = chunk_size - self.pts = 0 - - async def recv(self): - mic_data = self.stream.read(self.chunk_size) - mic_array = np.frombuffer(mic_data, dtype=np.int16) - mic_array = np.expand_dims(mic_array, axis=0) - layout = 'stereo' if self.channels > 1 else 'mono' - frame = av.AudioFrame.from_ndarray(mic_array, format=self.PYAUDIO_TO_AV_FORMAT_MAP[self.format], layout=layout) - frame.rate = self.rate - frame.pts = self.pts - self.pts += frame.samples - - return frame - - -class AudioOutputSpeaker: - def __init__(self, audio_format: int = pyaudio.paInt16, rate: int = 48000, channels: int = 2, packet_time: float = 0.2, device_index: int = None): - - chunk_size = int(packet_time * rate) - self.p = pyaudio.PyAudio() - self.buffer = io.BytesIO() - self.channels = channels - self.stream = self.p.open(format=audio_format, - channels=channels, - rate=rate, - frames_per_buffer=chunk_size, - output=True, - output_device_index=device_index, - stream_callback=self.__pyaudio_callback) - self.tracks_and_tasks: list[tuple[aiortc.MediaStreamTrack, asyncio.Task | None]] = [] - - def __pyaudio_callback(self, in_data, frame_count, time_info, status): - if self.buffer.getbuffer().nbytes < frame_count * self.channels * 2: - buff = b'\x00\x00' * frame_count * self.channels - elif self.buffer.getbuffer().nbytes > 115200: # 3x the usual read size - self.buffer.seek(0) - buff = self.buffer.read(frame_count * self.channels * 4) - buff = buff[:frame_count * self.channels * 2] - self.buffer.seek(2) - else: - self.buffer.seek(0) - buff = self.buffer.read(frame_count * self.channels * 2) - self.buffer.seek(2) - return (buff, pyaudio.paContinue) - - async def __consume(self, track): - while True: - try: - frame = await track.recv() - except aiortc.MediaStreamError: - return - - self.buffer.write(bytes(frame.planes[0])) - - def hasTrack(self, track: aiortc.MediaStreamTrack) -> bool: - return any(t == track for t, _ in self.tracks_and_tasks) - - def addTrack(self, track: aiortc.MediaStreamTrack): - if not self.hasTrack(track): - self.tracks_and_tasks.append((track, None)) - - def start(self): - for index, (track, task) in enumerate(self.tracks_and_tasks): - if task is None: - self.tracks_and_tasks[index] = (track, asyncio.create_task(self.__consume(track))) - - def stop(self): - for _, task in self.tracks_and_tasks: - if task is not None: - task.cancel() - - self.tracks_and_tasks = [] - self.stream.stop_stream() - self.stream.close() - self.p.terminate() diff --git a/system/webrtc/device/video.py b/system/webrtc/device/video.py deleted file mode 100644 index 1bca909294..0000000000 --- a/system/webrtc/device/video.py +++ /dev/null @@ -1,43 +0,0 @@ -import asyncio - -import av -from teleoprtc.tracks import TiciVideoStreamTrack - -from cereal import messaging -from openpilot.common.realtime import DT_MDL, DT_DMON - - -class LiveStreamVideoStreamTrack(TiciVideoStreamTrack): - camera_to_sock_mapping = { - "driver": "livestreamDriverEncodeData", - "wideRoad": "livestreamWideRoadEncodeData", - "road": "livestreamRoadEncodeData", - } - - def __init__(self, camera_type: str): - dt = DT_DMON if camera_type == "driver" else DT_MDL - super().__init__(camera_type, dt) - - self._sock = messaging.sub_sock(self.camera_to_sock_mapping[camera_type], conflate=True) - self._pts = 0 - - async def recv(self): - while True: - msg = messaging.recv_one_or_none(self._sock) - if msg is not None: - break - await asyncio.sleep(0.005) - - evta = getattr(msg, msg.which()) - - packet = av.Packet(evta.header + evta.data) - packet.time_base = self._time_base - packet.pts = self._pts - - self.log_debug("track sending frame %s", self._pts) - self._pts += self._dt * self._clock_rate - - return packet - - def codec_preference(self) -> str | None: - return "H264" diff --git a/system/webrtc/tests/test_stream_session.py b/system/webrtc/tests/test_stream_session.py deleted file mode 100644 index 113fa5e7e6..0000000000 --- a/system/webrtc/tests/test_stream_session.py +++ /dev/null @@ -1,101 +0,0 @@ -import asyncio -import json -# for aiortc and its dependencies -import warnings -warnings.filterwarnings("ignore", category=DeprecationWarning) -warnings.filterwarnings("ignore", category=RuntimeWarning) # TODO: remove this when google-crc32c publish a python3.12 wheel - -from aiortc import RTCDataChannel -from aiortc.mediastreams import VIDEO_CLOCK_RATE, VIDEO_TIME_BASE -import capnp -import pyaudio -from cereal import messaging, log - -from openpilot.system.webrtc.webrtcd import CerealOutgoingMessageProxy, CerealIncomingMessageProxy -from openpilot.system.webrtc.device.video import LiveStreamVideoStreamTrack -from openpilot.system.webrtc.device.audio import AudioInputStreamTrack -from openpilot.common.realtime import DT_DMON - - -class TestStreamSession: - def setup_method(self): - self.loop = asyncio.new_event_loop() - - def teardown_method(self): - self.loop.stop() - self.loop.close() - - def test_outgoing_proxy(self, mocker): - test_msg = log.Event.new_message() - test_msg.logMonoTime = 123 - test_msg.valid = True - test_msg.customReservedRawData0 = b"test" - expected_dict = {"type": "customReservedRawData0", "logMonoTime": 123, "valid": True, "data": "test"} - expected_json = json.dumps(expected_dict).encode() - - channel = mocker.Mock(spec=RTCDataChannel) - mocked_submaster = messaging.SubMaster(["customReservedRawData0"]) - def mocked_update(t): - mocked_submaster.update_msgs(0, [test_msg]) - - mocker.patch.object(messaging.SubMaster, "update", side_effect=mocked_update) - proxy = CerealOutgoingMessageProxy(mocked_submaster) - proxy.add_channel(channel) - - proxy.update() - - channel.send.assert_called_once_with(expected_json) - - def test_incoming_proxy(self, mocker): - tested_msgs = [ - {"type": "customReservedRawData0", "data": "test"}, # primitive - {"type": "can", "data": [{"address": 0, "dat": "", "src": 0}]}, # list - {"type": "testJoystick", "data": {"axes": [0, 0], "buttons": [False]}}, # dict - ] - - mocked_pubmaster = mocker.MagicMock(spec=messaging.PubMaster) - - proxy = CerealIncomingMessageProxy(mocked_pubmaster) - - for msg in tested_msgs: - proxy.send(json.dumps(msg).encode()) - - mocked_pubmaster.send.assert_called_once() - mt, md = mocked_pubmaster.send.call_args.args - assert mt == msg["type"] - assert isinstance(md, capnp._DynamicStructBuilder) - assert hasattr(md, msg["type"]) - - mocked_pubmaster.reset_mock() - - def test_livestream_track(self, mocker): - fake_msg = messaging.new_message("livestreamDriverEncodeData") - - config = {"receive.return_value": fake_msg.to_bytes()} - mocker.patch("msgq.SubSocket", spec=True, **config) - track = LiveStreamVideoStreamTrack("driver") - - assert track.id.startswith("driver") - assert track.codec_preference() == "H264" - - for i in range(5): - packet = self.loop.run_until_complete(track.recv()) - assert packet.time_base == VIDEO_TIME_BASE - assert packet.pts == int(i * DT_DMON * VIDEO_CLOCK_RATE) - assert packet.size == 0 - - def test_input_audio_track(self, mocker): - packet_time, rate = 0.02, 16000 - sample_count = int(packet_time * rate) - mocked_stream = mocker.MagicMock(spec=pyaudio.Stream) - mocked_stream.read.return_value = b"\x00" * 2 * sample_count - - config = {"open.side_effect": lambda *args, **kwargs: mocked_stream} - mocker.patch("pyaudio.PyAudio", spec=True, **config) - track = AudioInputStreamTrack(audio_format=pyaudio.paInt16, packet_time=packet_time, rate=rate) - - for i in range(5): - frame = self.loop.run_until_complete(track.recv()) - assert frame.rate == rate - assert frame.samples == sample_count - assert frame.pts == i * sample_count diff --git a/system/webrtc/tests/test_webrtcd.py b/system/webrtc/tests/test_webrtcd.py deleted file mode 100644 index 4fa6d8953f..0000000000 --- a/system/webrtc/tests/test_webrtcd.py +++ /dev/null @@ -1,65 +0,0 @@ -import pytest -import asyncio -import json -# for aiortc and its dependencies -import warnings -warnings.filterwarnings("ignore", category=DeprecationWarning) -warnings.filterwarnings("ignore", category=RuntimeWarning) # TODO: remove this when google-crc32c publish a python3.12 wheel - -from openpilot.system.webrtc.webrtcd import get_stream - -import aiortc -from teleoprtc import WebRTCOfferBuilder -from parameterized import parameterized_class - - -@parameterized_class(("in_services", "out_services"), [ - (["testJoystick"], ["carState"]), - ([], ["carState"]), - (["testJoystick"], []), - ([], []), -]) -@pytest.mark.asyncio -class TestWebrtcdProc: - async def assertCompletesWithTimeout(self, awaitable, timeout=1): - try: - async with asyncio.timeout(timeout): - await awaitable - except TimeoutError: - pytest.fail("Timeout while waiting for awaitable to complete") - - async def test_webrtcd(self, mocker): - mock_request = mocker.MagicMock() - async def connect(offer): - body = {'sdp': offer.sdp, 'cameras': offer.video, 'bridge_services_in': self.in_services, 'bridge_services_out': self.out_services} - mock_request.json.side_effect = mocker.AsyncMock(return_value=body) - response = await get_stream(mock_request) - response_json = json.loads(response.text) - return aiortc.RTCSessionDescription(**response_json) - - builder = WebRTCOfferBuilder(connect) - builder.offer_to_receive_video_stream("road") - builder.offer_to_receive_audio_stream() - if len(self.in_services) > 0 or len(self.out_services) > 0: - builder.add_messaging() - - stream = builder.stream() - - await self.assertCompletesWithTimeout(stream.start()) - await self.assertCompletesWithTimeout(stream.wait_for_connection()) - - assert stream.has_incoming_video_track("road") - assert stream.has_incoming_audio_track() - assert stream.has_messaging_channel() == (len(self.in_services) > 0 or len(self.out_services) > 0) - - video_track, audio_track = stream.get_incoming_video_track("road"), stream.get_incoming_audio_track() - await self.assertCompletesWithTimeout(video_track.recv()) - await self.assertCompletesWithTimeout(audio_track.recv()) - - await self.assertCompletesWithTimeout(stream.stop()) - - # cleanup, very implementation specific, test may break if it changes - assert mock_request.app["streams"].__setitem__.called, "Implementation changed, please update this test" - _, session = mock_request.app["streams"].__setitem__.call_args.args - await self.assertCompletesWithTimeout(session.post_run_cleanup()) - diff --git a/system/webrtc/webrtcd.py b/system/webrtc/webrtcd.py deleted file mode 100755 index fb93e565ff..0000000000 --- a/system/webrtc/webrtcd.py +++ /dev/null @@ -1,277 +0,0 @@ -#!/usr/bin/env python3 - -import argparse -import asyncio -import json -import uuid -import logging -from dataclasses import dataclass, field -from typing import Any, TYPE_CHECKING - -# aiortc and its dependencies have lots of internal warnings :( -import warnings -warnings.filterwarnings("ignore", category=DeprecationWarning) -warnings.filterwarnings("ignore", category=RuntimeWarning) # TODO: remove this when google-crc32c publish a python3.12 wheel - -import capnp -from aiohttp import web -if TYPE_CHECKING: - from aiortc.rtcdatachannel import RTCDataChannel - -from openpilot.system.webrtc.schema import generate_field -from cereal import messaging, log - - -class CerealOutgoingMessageProxy: - def __init__(self, sm: messaging.SubMaster): - self.sm = sm - self.channels: list[RTCDataChannel] = [] - - def add_channel(self, channel: 'RTCDataChannel'): - self.channels.append(channel) - - def to_json(self, msg_content: Any): - if isinstance(msg_content, capnp._DynamicStructReader): - msg_dict = msg_content.to_dict() - elif isinstance(msg_content, capnp._DynamicListReader): - msg_dict = [self.to_json(msg) for msg in msg_content] - elif isinstance(msg_content, bytes): - msg_dict = msg_content.decode() - else: - msg_dict = msg_content - - return msg_dict - - def update(self): - # this is blocking in async context... - self.sm.update(0) - for service, updated in self.sm.updated.items(): - if not updated: - continue - msg_dict = self.to_json(self.sm[service]) - mono_time, valid = self.sm.logMonoTime[service], self.sm.valid[service] - outgoing_msg = {"type": service, "logMonoTime": mono_time, "valid": valid, "data": msg_dict} - encoded_msg = json.dumps(outgoing_msg).encode() - for channel in self.channels: - channel.send(encoded_msg) - - -class CerealIncomingMessageProxy: - def __init__(self, pm: messaging.PubMaster): - self.pm = pm - - def send(self, message: bytes): - msg_json = json.loads(message) - msg_type, msg_data = msg_json["type"], msg_json["data"] - size = None - if not isinstance(msg_data, dict): - size = len(msg_data) - - msg = messaging.new_message(msg_type, size=size) - setattr(msg, msg_type, msg_data) - self.pm.send(msg_type, msg) - - -class CerealProxyRunner: - def __init__(self, proxy: CerealOutgoingMessageProxy): - self.proxy = proxy - self.is_running = False - self.task = None - self.logger = logging.getLogger("webrtcd") - - def start(self): - assert self.task is None - self.task = asyncio.create_task(self.run()) - - def stop(self): - if self.task is None or self.task.done(): - return - self.task.cancel() - self.task = None - - async def run(self): - from aiortc.exceptions import InvalidStateError - - while True: - try: - self.proxy.update() - except InvalidStateError: - self.logger.warning("Cereal outgoing proxy invalid state (connection closed)") - break - except Exception: - self.logger.exception("Cereal outgoing proxy failure") - await asyncio.sleep(0.01) - - -class DynamicPubMaster(messaging.PubMaster): - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self.lock = asyncio.Lock() - - async def add_services_if_needed(self, services): - async with self.lock: - for service in services: - if service not in self.sock: - self.sock[service] = messaging.pub_sock(service) - - -class StreamSession: - shared_pub_master = DynamicPubMaster([]) - - def __init__(self, sdp: str, cameras: list[str], incoming_services: list[str], outgoing_services: list[str], debug_mode: bool = False): - from aiortc.mediastreams import VideoStreamTrack, AudioStreamTrack - from aiortc.contrib.media import MediaBlackhole - from openpilot.system.webrtc.device.video import LiveStreamVideoStreamTrack - from openpilot.system.webrtc.device.audio import AudioInputStreamTrack, AudioOutputSpeaker - from teleoprtc import WebRTCAnswerBuilder - from teleoprtc.info import parse_info_from_offer - - config = parse_info_from_offer(sdp) - builder = WebRTCAnswerBuilder(sdp) - - assert len(cameras) == config.n_expected_camera_tracks, "Incoming stream has misconfigured number of video tracks" - for cam in cameras: - builder.add_video_stream(cam, LiveStreamVideoStreamTrack(cam) if not debug_mode else VideoStreamTrack()) - if config.expected_audio_track: - builder.add_audio_stream(AudioInputStreamTrack() if not debug_mode else AudioStreamTrack()) - if config.incoming_audio_track: - self.audio_output_cls = AudioOutputSpeaker if not debug_mode else MediaBlackhole - builder.offer_to_receive_audio_stream() - - self.stream = builder.stream() - self.identifier = str(uuid.uuid4()) - - self.incoming_bridge: CerealIncomingMessageProxy | None = None - self.incoming_bridge_services = incoming_services - self.outgoing_bridge: CerealOutgoingMessageProxy | None = None - self.outgoing_bridge_runner: CerealProxyRunner | None = None - if len(incoming_services) > 0: - self.incoming_bridge = CerealIncomingMessageProxy(self.shared_pub_master) - if len(outgoing_services) > 0: - self.outgoing_bridge = CerealOutgoingMessageProxy(messaging.SubMaster(outgoing_services)) - self.outgoing_bridge_runner = CerealProxyRunner(self.outgoing_bridge) - - self.audio_output: AudioOutputSpeaker | MediaBlackhole | None = None - self.run_task: asyncio.Task | None = None - self.logger = logging.getLogger("webrtcd") - self.logger.info("New stream session (%s), cameras %s, audio in %s out %s, incoming services %s, outgoing services %s", - self.identifier, cameras, config.incoming_audio_track, config.expected_audio_track, incoming_services, outgoing_services) - - def start(self): - self.run_task = asyncio.create_task(self.run()) - - def stop(self): - if self.run_task.done(): - return - self.run_task.cancel() - self.run_task = None - asyncio.run(self.post_run_cleanup()) - - async def get_answer(self): - return await self.stream.start() - - async def message_handler(self, message: bytes): - assert self.incoming_bridge is not None - try: - self.incoming_bridge.send(message) - except Exception: - self.logger.exception("Cereal incoming proxy failure") - - async def run(self): - try: - await self.stream.wait_for_connection() - if self.stream.has_messaging_channel(): - if self.incoming_bridge is not None: - await self.shared_pub_master.add_services_if_needed(self.incoming_bridge_services) - self.stream.set_message_handler(self.message_handler) - if self.outgoing_bridge_runner is not None: - channel = self.stream.get_messaging_channel() - self.outgoing_bridge_runner.proxy.add_channel(channel) - self.outgoing_bridge_runner.start() - if self.stream.has_incoming_audio_track(): - track = self.stream.get_incoming_audio_track(buffered=False) - self.audio_output = self.audio_output_cls() - self.audio_output.addTrack(track) - self.audio_output.start() - self.logger.info("Stream session (%s) connected", self.identifier) - - await self.stream.wait_for_disconnection() - await self.post_run_cleanup() - - self.logger.info("Stream session (%s) ended", self.identifier) - except Exception: - self.logger.exception("Stream session failure") - - async def post_run_cleanup(self): - await self.stream.stop() - if self.outgoing_bridge is not None: - self.outgoing_bridge_runner.stop() - if self.audio_output: - self.audio_output.stop() - - -@dataclass -class StreamRequestBody: - sdp: str - cameras: list[str] - bridge_services_in: list[str] = field(default_factory=list) - bridge_services_out: list[str] = field(default_factory=list) - - -async def get_stream(request: 'web.Request'): - stream_dict, debug_mode = request.app['streams'], request.app['debug'] - raw_body = await request.json() - body = StreamRequestBody(**raw_body) - - session = StreamSession(body.sdp, body.cameras, body.bridge_services_in, body.bridge_services_out, debug_mode) - answer = await session.get_answer() - session.start() - - stream_dict[session.identifier] = session - - return web.json_response({"sdp": answer.sdp, "type": answer.type}) - - -async def get_schema(request: 'web.Request'): - services = request.query["services"].split(",") - services = [s for s in services if s] - assert all(s in log.Event.schema.fields and not s.endswith("DEPRECATED") for s in services), "Invalid service name" - schema_dict = {s: generate_field(log.Event.schema.fields[s]) for s in services} - return web.json_response(schema_dict) - - -async def on_shutdown(app: 'web.Application'): - for session in app['streams'].values(): - session.stop() - del app['streams'] - - -def webrtcd_thread(host: str, port: int, debug: bool): - logging.basicConfig(level=logging.CRITICAL, handlers=[logging.StreamHandler()]) - logging_level = logging.DEBUG if debug else logging.INFO - logging.getLogger("WebRTCStream").setLevel(logging_level) - logging.getLogger("webrtcd").setLevel(logging_level) - - app = web.Application() - - app['streams'] = dict() - app['debug'] = debug - app.on_shutdown.append(on_shutdown) - app.router.add_post("/stream", get_stream) - app.router.add_get("/schema", get_schema) - - web.run_app(app, host=host, port=port) - - -def main(): - parser = argparse.ArgumentParser(description="WebRTC daemon") - parser.add_argument("--host", type=str, default="0.0.0.0", help="Host to listen on") - parser.add_argument("--port", type=int, default=5001, help="Port to listen on") - parser.add_argument("--debug", action="store_true", help="Enable debug mode") - args = parser.parse_args() - - webrtcd_thread(args.host, args.port, args.debug) - - -if __name__=="__main__": - main() diff --git a/teleoprtc b/teleoprtc deleted file mode 120000 index 3d3dbc8dea..0000000000 --- a/teleoprtc +++ /dev/null @@ -1 +0,0 @@ -teleoprtc_repo/teleoprtc \ No newline at end of file diff --git a/teleoprtc_repo b/teleoprtc_repo index 389815b8ca..c0f813f1c4 160000 --- a/teleoprtc_repo +++ b/teleoprtc_repo @@ -1 +1 @@ -Subproject commit 389815b8ca5302ce7c1504b7841d4eb61a8cd51b +Subproject commit c0f813f1c4f7e2d29bc0ed6a4d2a7b3268511b0f diff --git a/third_party/.gitignore b/third_party/.gitignore deleted file mode 100644 index 0d20b6487c..0000000000 --- a/third_party/.gitignore +++ /dev/null @@ -1 +0,0 @@ -*.pyc diff --git a/third_party/SConscript b/third_party/SConscript deleted file mode 100644 index 507c17c4a5..0000000000 --- a/third_party/SConscript +++ /dev/null @@ -1,4 +0,0 @@ -Import('env') - -env.Library('json11', ['json11/json11.cpp'], CCFLAGS=env['CCFLAGS'] + ['-Wno-unqualified-std-cast-call']) -env.Library('kaitai', ['kaitai/kaitaistream.cpp'], CPPDEFINES=['KS_STR_ENCODING_NONE']) diff --git a/third_party/acados/.gitignore b/third_party/acados/.gitignore deleted file mode 100644 index 68858c62e4..0000000000 --- a/third_party/acados/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -acados_repo/ -lib -!x86_64/ -!larch64/ -!aarch64/ diff --git a/third_party/acados/Darwin/lib/libacados.dylib b/third_party/acados/Darwin/lib/libacados.dylib deleted file mode 100755 index 8cd5a41f14..0000000000 --- a/third_party/acados/Darwin/lib/libacados.dylib +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:620195ff61aaccf9adf00a66b8acf4e9915a0895d0a86f9f51ec952e44fad70a -size 853776 diff --git a/third_party/acados/Darwin/lib/libblasfeo.dylib b/third_party/acados/Darwin/lib/libblasfeo.dylib deleted file mode 100755 index 442a6c736d..0000000000 --- a/third_party/acados/Darwin/lib/libblasfeo.dylib +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:1d9dbeb68b2ac13c884f606a1f6032f399640e0928cecad4c22b700a8d8ae970 -size 2010877 diff --git a/third_party/acados/Darwin/lib/libhpipm.dylib b/third_party/acados/Darwin/lib/libhpipm.dylib deleted file mode 100755 index 019ec8019e..0000000000 --- a/third_party/acados/Darwin/lib/libhpipm.dylib +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:35783dba64c2d5bbe7e4c98ad01accac56b478b1bf874969ab5c31d7495499a2 -size 2290624 diff --git a/third_party/acados/Darwin/lib/libqpOASES_e.3.1.dylib b/third_party/acados/Darwin/lib/libqpOASES_e.3.1.dylib deleted file mode 100755 index caaa8ec775..0000000000 --- a/third_party/acados/Darwin/lib/libqpOASES_e.3.1.dylib +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:f57eea51f4b91deff47fbf599eedc3eafedd395f23465b5fb24b2148fdaa2859 -size 496707 diff --git a/third_party/acados/Darwin/lib/libqpOASES_e.dylib b/third_party/acados/Darwin/lib/libqpOASES_e.dylib deleted file mode 120000 index e3d94c4bc2..0000000000 --- a/third_party/acados/Darwin/lib/libqpOASES_e.dylib +++ /dev/null @@ -1 +0,0 @@ -libqpOASES_e.3.1.dylib \ No newline at end of file diff --git a/third_party/acados/Darwin/t_renderer b/third_party/acados/Darwin/t_renderer deleted file mode 100755 index 83a74ea5a3..0000000000 --- a/third_party/acados/Darwin/t_renderer +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:c6c78791cfdd841da14266c62a6099d0af53cec348051118f1a70518729aa5ba -size 8483768 diff --git a/third_party/acados/aarch64 b/third_party/acados/aarch64 deleted file mode 120000 index 062c65e8d9..0000000000 --- a/third_party/acados/aarch64 +++ /dev/null @@ -1 +0,0 @@ -larch64/ \ No newline at end of file diff --git a/third_party/acados/acados_template/.gitignore b/third_party/acados/acados_template/.gitignore deleted file mode 100644 index 63b741bb9d..0000000000 --- a/third_party/acados/acados_template/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -__pycache__/ - -# Cython intermediates -*_pyx.c -*_pyx.o -*_pyx.so diff --git a/third_party/acados/acados_template/__init__.py b/third_party/acados/acados_template/__init__.py deleted file mode 100644 index bfbe907990..0000000000 --- a/third_party/acados/acados_template/__init__.py +++ /dev/null @@ -1,40 +0,0 @@ -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# 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. -# -# 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.; -# - -from .acados_model import AcadosModel -from .acados_ocp import AcadosOcp, AcadosOcpConstraints, AcadosOcpCost, AcadosOcpDims, AcadosOcpOptions -from .acados_sim import AcadosSim, AcadosSimDims, AcadosSimOpts -from .acados_ocp_solver import AcadosOcpSolver, get_simulink_default_opts, ocp_get_default_cmake_builder -from .acados_sim_solver import AcadosSimSolver, sim_get_default_cmake_builder -from .utils import print_casadi_expression, get_acados_path, get_python_interface_path, \ - get_tera_exec_path, get_tera, check_casadi_version, acados_dae_model_json_dump, \ - casadi_length, make_object_json_dumpable, J_to_idx, get_default_simulink_opts - -from .zoro_description import ZoroDescription, process_zoro_description diff --git a/third_party/acados/acados_template/acados_layout.json b/third_party/acados/acados_template/acados_layout.json deleted file mode 100644 index a1cc5bbdf3..0000000000 --- a/third_party/acados/acados_template/acados_layout.json +++ /dev/null @@ -1,834 +0,0 @@ -{ - "code_export_directory": [ - "str" - ], - "acados_include_path": [ - "str" - ], - "cython_include_dirs": [ - "list" - ], - "json_file": [ - "str" - ], - "shared_lib_ext": [ - "str" - ], - "model": { - "name" : [ - "str" - ], - "dyn_ext_fun_type" : [ - "str" - ], - "dyn_generic_source" : [ - "str" - ], - "dyn_impl_dae_fun" : [ - "str" - ], - "dyn_impl_dae_fun_jac" : [ - "str" - ], - "dyn_impl_dae_jac" : [ - "str" - ], - "dyn_disc_fun_jac_hess" : [ - "str" - ], - "dyn_disc_fun_jac" : [ - "str" - ], - "dyn_disc_fun" : [ - "str" - ], - "gnsf" : { - "nontrivial_f_LO": [ - "int" - ], - "purely_linear": [ - "int" - ] - } - }, - "parameter_values": [ - "ndarray", - [ - "np" - ] - ], - "acados_lib_path": [ - "str" - ], - "problem_class": [ - "str" - ], - "constraints": { - "constr_type": [ - "str" - ], - "constr_type_e": [ - "str" - ], - "lbx": [ - "ndarray", - [ - "nbx" - ] - ], - "lbu": [ - "ndarray", - [ - "nbu" - ] - ], - "ubx": [ - "ndarray", - [ - "nbx" - ] - ], - "ubu": [ - "ndarray", - [ - "nbu" - ] - ], - "idxbx": [ - "ndarray", - [ - "nbx" - ] - ], - "idxbu": [ - "ndarray", - [ - "nbu" - ] - ], - "lbx_e": [ - "ndarray", - [ - "nbx_e" - ] - ], - "ubx_e": [ - "ndarray", - [ - "nbx_e" - ] - ], - "idxbx_e": [ - "ndarray", - [ - "nbx_e" - ] - ], - "lbx_0": [ - "ndarray", - [ - "nbx_0" - ] - ], - "ubx_0": [ - "ndarray", - [ - "nbx_0" - ] - ], - "idxbx_0": [ - "ndarray", - [ - "nbx_0" - ] - ], - "idxbxe_0": [ - "ndarray", - [ - "nbxe_0" - ] - ], - "lg": [ - "ndarray", - [ - "ng" - ] - ], - "ug": [ - "ndarray", - [ - "ng" - ] - ], - "D": [ - "ndarray", - [ - "ng", - "nu" - ] - ], - "C": [ - "ndarray", - [ - "ng", - "nx" - ] - ], - "C_e": [ - "ndarray", - [ - "ng_e", - "nx" - ] - ], - "lg_e": [ - "ndarray", - [ - "ng_e" - ] - ], - "ug_e": [ - "ndarray", - [ - "ng_e" - ] - ], - "lh": [ - "ndarray", - [ - "nh" - ] - ], - "uh": [ - "ndarray", - [ - "nh" - ] - ], - "lh_e": [ - "ndarray", - [ - "nh_e" - ] - ], - "uh_e": [ - "ndarray", - [ - "nh_e" - ] - ], - "lphi": [ - "ndarray", - [ - "nphi" - ] - ], - "uphi": [ - "ndarray", - [ - "nphi" - ] - ], - "lphi_e": [ - "ndarray", - [ - "nphi_e" - ] - ], - "uphi_e": [ - "ndarray", - [ - "nphi_e" - ] - ], - "lsbx": [ - "ndarray", - [ - "nsbx" - ] - ], - "usbx": [ - "ndarray", - [ - "nsbx" - ] - ], - "lsbu": [ - "ndarray", - [ - "nsbu" - ] - ], - "usbu": [ - "ndarray", - [ - "nsbu" - ] - ], - "idxsbx": [ - "ndarray", - [ - "nsbx" - ] - ], - "idxsbu": [ - "ndarray", - [ - "nsbu" - ] - ], - "lsbx_e": [ - "ndarray", - [ - "nsbx_e" - ] - ], - "usbx_e": [ - "ndarray", - [ - "nsbx_e" - ] - ], - "idxsbx_e": [ - "ndarray", - [ - "nsbx_e" - ] - ], - "lsg": [ - "ndarray", - [ - "nsg" - ] - ], - "usg": [ - "ndarray", - [ - "nsg" - ] - ], - "idxsg": [ - "ndarray", - [ - "nsg" - ] - ], - "lsg_e": [ - "ndarray", - [ - "nsg_e" - ] - ], - "usg_e": [ - "ndarray", - [ - "nsg_e" - ] - ], - "idxsg_e": [ - "ndarray", - [ - "nsg_e" - ] - ], - "lsh": [ - "ndarray", - [ - "nsh" - ] - ], - "ush": [ - "ndarray", - [ - "nsh" - ] - ], - "idxsh": [ - "ndarray", - [ - "nsh" - ] - ], - "lsh_e": [ - "ndarray", - [ - "nsh_e" - ] - ], - "ush_e": [ - "ndarray", - [ - "nsh_e" - ] - ], - "idxsh_e": [ - "ndarray", - [ - "nsh_e" - ] - ], - "lsphi": [ - "ndarray", - [ - "nsphi" - ] - ], - "usphi": [ - "ndarray", - [ - "nsphi" - ] - ], - "idxsphi": [ - "ndarray", - [ - "nsphi" - ] - ], - "lsphi_e": [ - "ndarray", - [ - "nsphi_e" - ] - ], - "usphi_e": [ - "ndarray", - [ - "nsphi_e" - ] - ], - "idxsphi_e": [ - "ndarray", - [ - "nsphi_e" - ] - ] - }, - "cost": { - "cost_type_0": [ - "str" - ], - "cost_type": [ - "str" - ], - "cost_type_e": [ - "str" - ], - "cost_ext_fun_type_0": [ - "str" - ], - "cost_ext_fun_type": [ - "str" - ], - "cost_ext_fun_type_e": [ - "str" - ], - "Vu_0": [ - "ndarray", - [ - "ny_0", - "nu" - ] - ], - "Vu": [ - "ndarray", - [ - "ny", - "nu" - ] - ], - "Vx_0": [ - "ndarray", - [ - "ny_0", - "nx" - ] - ], - "Vx": [ - "ndarray", - [ - "ny", - "nx" - ] - ], - "Vx_e": [ - "ndarray", - [ - "ny_e", - "nx" - ] - ], - "Vz_0": [ - "ndarray", - [ - "ny_0", - "nz" - ] - ], - "Vz": [ - "ndarray", - [ - "ny", - "nz" - ] - ], - "W_0": [ - "ndarray", - [ - "ny_0", - "ny_0" - ] - ], - "W": [ - "ndarray", - [ - "ny", - "ny" - ] - ], - "Zl": [ - "ndarray", - [ - "ns" - ] - ], - "Zu": [ - "ndarray", - [ - "ns" - ] - ], - "zl": [ - "ndarray", - [ - "ns" - ] - ], - "zu": [ - "ndarray", - [ - "ns" - ] - ], - "W_e": [ - "ndarray", - [ - "ny_e", - "ny_e" - ] - ], - "yref_0": [ - "ndarray", - [ - "ny_0" - ] - ], - "yref": [ - "ndarray", - [ - "ny" - ] - ], - "yref_e": [ - "ndarray", - [ - "ny_e" - ] - ], - "Zl_e": [ - "ndarray", - [ - "ns_e" - ] - ], - "Zu_e": [ - "ndarray", - [ - "ns_e" - ] - ], - "zl_e": [ - "ndarray", - [ - "ns_e" - ] - ], - "zu_e": [ - "ndarray", - [ - "ns_e" - ] - ] - }, - "dims": { - "N": [ - "int" - ], - "nbu": [ - "int" - ], - "nbx": [ - "int" - ], - "nsbu": [ - "int" - ], - "nsbx": [ - "int" - ], - "nsbx_e": [ - "int" - ], - "nbx_0": [ - "int" - ], - "nbx_e": [ - "int" - ], - "nbxe_0": [ - "int" - ], - "nsg": [ - "int" - ], - "nsg_e": [ - "int" - ], - "nsh": [ - "int" - ], - "nsh_e": [ - "int" - ], - "nsphi": [ - "int" - ], - "nsphi_e": [ - "int" - ], - "ns": [ - "int" - ], - "ns_e": [ - "int" - ], - "ng": [ - "int" - ], - "ng_e": [ - "int" - ], - "np": [ - "int" - ], - "nr": [ - "int" - ], - "nr_e": [ - "int" - ], - "nh": [ - "int" - ], - "nh_e": [ - "int" - ], - "nphi": [ - "int" - ], - "nphi_e": [ - "int" - ], - "nu": [ - "int" - ], - "nx": [ - "int" - ], - "ny": [ - "int" - ], - "ny_0": [ - "int" - ], - "ny_e": [ - "int" - ], - "nz": [ - "int" - ], - "gnsf_nx1": [ - "int" - ], - "gnsf_nz1": [ - "int" - ], - "gnsf_nuhat": [ - "int" - ], - "gnsf_ny": [ - "int" - ], - "gnsf_nout": [ - "int" - ] - }, - "solver_options": { - "time_steps": [ - "ndarray", - [ - "N" - ] - ], - "hessian_approx": [ - "str" - ], - "hpipm_mode": [ - "str" - ], - "regularize_method": [ - "str" - ], - "integrator_type": [ - "str" - ], - "nlp_solver_type": [ - "str" - ], - "collocation_type": [ - "str" - ], - "globalization": [ - "str" - ], - "nlp_solver_step_length": [ - "float" - ], - "levenberg_marquardt": [ - "float" - ], - "qp_solver": [ - "str" - ], - "tf": [ - "float" - ], - "Tsim": [ - "float" - ], - "alpha_min": [ - "float" - ], - "alpha_reduction": [ - "float" - ], - "line_search_use_sufficient_descent": [ - "int" - ], - "globalization_use_SOC": [ - "int" - ], - "full_step_dual": [ - "int" - ], - "eps_sufficient_descent": [ - "float" - ], - "sim_method_num_stages": [ - "ndarray", - [ - "N" - ] - ], - "sim_method_num_steps": [ - "ndarray", - [ - "N" - ] - ], - "sim_method_newton_iter": [ - "int" - ], - "sim_method_newton_tol": [ - "float" - ], - "sim_method_jac_reuse": [ - "ndarray", - [ - "N" - ] - ], - "qp_solver_cond_N": [ - "int" - ], - "qp_solver_warm_start": [ - "int" - ], - "qp_solver_tol_stat": [ - "float" - ], - "qp_solver_tol_eq": [ - "float" - ], - "qp_solver_tol_ineq": [ - "float" - ], - "qp_solver_tol_comp": [ - "float" - ], - "qp_solver_iter_max": [ - "int" - ], - "qp_solver_cond_ric_alg": [ - "int" - ], - "qp_solver_ric_alg": [ - "int" - ], - "nlp_solver_tol_stat": [ - "float" - ], - "nlp_solver_tol_eq": [ - "float" - ], - "nlp_solver_tol_ineq": [ - "float" - ], - "nlp_solver_tol_comp": [ - "float" - ], - "nlp_solver_max_iter": [ - "int" - ], - "nlp_solver_ext_qp_res": [ - "int" - ], - "print_level": [ - "int" - ], - "initialize_t_slacks": [ - "int" - ], - "exact_hess_cost": [ - "int" - ], - "exact_hess_constr": [ - "int" - ], - "exact_hess_dyn": [ - "int" - ], - "ext_cost_num_hess": [ - "int" - ], - "ext_fun_compile_flags": [ - "str" - ], - "model_external_shared_lib_dir": [ - "str" - ], - "model_external_shared_lib_name": [ - "str" - ] - } -} diff --git a/third_party/acados/acados_template/acados_model.py b/third_party/acados/acados_template/acados_model.py deleted file mode 100644 index b7c6945442..0000000000 --- a/third_party/acados/acados_template/acados_model.py +++ /dev/null @@ -1,154 +0,0 @@ -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# 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. -# -# 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.; -# - - -class AcadosModel(): - """ - Class containing all the information to code generate the external CasADi functions - that are needed when creating an acados ocp solver or acados integrator. - Thus, this class contains: - - a) the :py:attr:`name` of the model, - b) all CasADi variables/expressions needed in the CasADi function generation process. - """ - def __init__(self): - ## common for OCP and Integrator - self.name = None - """ - The model name is used for code generation. Type: string. Default: :code:`None` - """ - self.x = None #: CasADi variable describing the state of the system; Default: :code:`None` - self.xdot = None #: CasADi variable describing the derivative of the state wrt time; Default: :code:`None` - self.u = None #: CasADi variable describing the input of the system; Default: :code:`None` - self.z = [] #: CasADi variable describing the algebraic variables of the DAE; Default: :code:`empty` - self.p = [] #: CasADi variable describing parameters of the DAE; Default: :code:`empty` - # dynamics - self.f_impl_expr = None - """ - CasADi expression for the implicit dynamics :math:`f_\\text{impl}(\dot{x}, x, u, z, p) = 0`. - Used if :py:attr:`acados_template.acados_ocp.AcadosOcpOptions.integrator_type` == 'IRK'. - Default: :code:`None` - """ - self.f_expl_expr = None - """ - CasADi expression for the explicit dynamics :math:`\dot{x} = f_\\text{expl}(x, u, p)`. - Used if :py:attr:`acados_template.acados_ocp.AcadosOcpOptions.integrator_type` == 'ERK'. - Default: :code:`None` - """ - self.disc_dyn_expr = None - """ - CasADi expression for the discrete dynamics :math:`x_{+} = f_\\text{disc}(x, u, p)`. - Used if :py:attr:`acados_template.acados_ocp.AcadosOcpOptions.integrator_type` == 'DISCRETE'. - Default: :code:`None` - """ - - self.dyn_ext_fun_type = 'casadi' #: type of external functions for dynamics module; 'casadi' or 'generic'; Default: 'casadi' - self.dyn_generic_source = None #: name of source file for discrete dyanamics; Default: :code:`None` - self.dyn_disc_fun_jac_hess = None #: name of function discrete dyanamics + jacobian and hessian; Default: :code:`None` - self.dyn_disc_fun_jac = None #: name of function discrete dyanamics + jacobian; Default: :code:`None` - self.dyn_disc_fun = None #: name of function discrete dyanamics; Default: :code:`None` - - # for GNSF models - self.gnsf = {'nontrivial_f_LO': 1, 'purely_linear': 0} - """ - dictionary containing information on GNSF structure needed when rendering templates. - Contains integers `nontrivial_f_LO`, `purely_linear`. - """ - - ## for OCP - # constraints - # BGH(default): lh <= h(x, u) <= uh - self.con_h_expr = None #: CasADi expression for the constraint :math:`h`; Default: :code:`None` - # BGP(convex over nonlinear): lphi <= phi(r(x, u)) <= uphi - self.con_phi_expr = None #: CasADi expression for the constraint phi; Default: :code:`None` - self.con_r_expr = None #: CasADi expression for the constraint phi(r); Default: :code:`None` - self.con_r_in_phi = None - # terminal - self.con_h_expr_e = None #: CasADi expression for the terminal constraint :math:`h^e`; Default: :code:`None` - self.con_r_expr_e = None #: CasADi expression for the terminal constraint; Default: :code:`None` - self.con_phi_expr_e = None #: CasADi expression for the terminal constraint; Default: :code:`None` - self.con_r_in_phi_e = None - # cost - self.cost_y_expr = None #: CasADi expression for nonlinear least squares; Default: :code:`None` - self.cost_y_expr_e = None #: CasADi expression for nonlinear least squares, terminal; Default: :code:`None` - self.cost_y_expr_0 = None #: CasADi expression for nonlinear least squares, initial; Default: :code:`None` - self.cost_expr_ext_cost = None #: CasADi expression for external cost; Default: :code:`None` - self.cost_expr_ext_cost_e = None #: CasADi expression for external cost, terminal; Default: :code:`None` - self.cost_expr_ext_cost_0 = None #: CasADi expression for external cost, initial; Default: :code:`None` - self.cost_expr_ext_cost_custom_hess = None #: CasADi expression for custom hessian (only for external cost); Default: :code:`None` - self.cost_expr_ext_cost_custom_hess_e = None #: CasADi expression for custom hessian (only for external cost), terminal; Default: :code:`None` - self.cost_expr_ext_cost_custom_hess_0 = None #: CasADi expression for custom hessian (only for external cost), initial; Default: :code:`None` - - ## CONVEX_OVER_NONLINEAR convex-over-nonlinear cost: psi(y(x, u, p) - y_ref; p) - self.cost_psi_expr_0 = None - """ - CasADi expression for the outer loss function :math:`\psi(r, p)`, initial; Default: :code:`None` - Used if :py:attr:`acados_template.acados_ocp.AcadosOcpOptions.cost_type_0` == 'CONVEX_OVER_NONLINEAR'. - """ - self.cost_psi_expr = None - """ - CasADi expression for the outer loss function :math:`\psi(r, p)`; Default: :code:`None` - Used if :py:attr:`acados_template.acados_ocp.AcadosOcpOptions.cost_type` == 'CONVEX_OVER_NONLINEAR'. - """ - self.cost_psi_expr_e = None - """ - CasADi expression for the outer loss function :math:`\psi(r, p)`, terminal; Default: :code:`None` - Used if :py:attr:`acados_template.acados_ocp.AcadosOcpOptions.cost_type_e` == 'CONVEX_OVER_NONLINEAR'. - """ - self.cost_r_in_psi_expr_0 = None - """ - CasADi expression for the argument :math:`r`; to the outer loss function :math:`\psi(r, p)`, initial; Default: :code:`None` - Used if :py:attr:`acados_template.acados_ocp.AcadosOcpOptions.cost_type_0` == 'CONVEX_OVER_NONLINEAR'. - """ - self.cost_r_in_psi_expr = None - """ - CasADi expression for the argument :math:`r`; to the outer loss function :math:`\psi(r, p)`; Default: :code:`None` - Used if :py:attr:`acados_template.acados_ocp.AcadosOcpOptions.cost_type` == 'CONVEX_OVER_NONLINEAR'. - """ - self.cost_r_in_psi_expr_e = None - """ - CasADi expression for the argument :math:`r`; to the outer loss function :math:`\psi(r, p)`, terminal; Default: :code:`None` - Used if :py:attr:`acados_template.acados_ocp.AcadosOcpOptions.cost_type_e` == 'CONVEX_OVER_NONLINEAR'. - """ - self.cost_conl_custom_outer_hess_0 = None - """ - CasADi expression for the custom hessian of the outer loss function (only for convex-over-nonlinear cost), initial; Default: :code:`None` - Used if :py:attr:`acados_template.acados_ocp.AcadosOcpOptions.cost_type_0` == 'CONVEX_OVER_NONLINEAR'. - """ - self.cost_conl_custom_outer_hess = None - """ - CasADi expression for the custom hessian of the outer loss function (only for convex-over-nonlinear cost); Default: :code:`None` - Used if :py:attr:`acados_template.acados_ocp.AcadosOcpOptions.cost_type` == 'CONVEX_OVER_NONLINEAR'. - """ - self.cost_conl_custom_outer_hess_e = None - """ - CasADi expression for the custom hessian of the outer loss function (only for convex-over-nonlinear cost), terminal; Default: :code:`None` - Used if :py:attr:`acados_template.acados_ocp.AcadosOcpOptions.cost_type_e` == 'CONVEX_OVER_NONLINEAR'. - """ diff --git a/third_party/acados/acados_template/acados_ocp.py b/third_party/acados/acados_template/acados_ocp.py deleted file mode 100644 index ec02822ceb..0000000000 --- a/third_party/acados/acados_template/acados_ocp.py +++ /dev/null @@ -1,3167 +0,0 @@ -# -*- coding: future_fstrings -*- -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# 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. -# -# 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.; -# - -import numpy as np -import os -from .acados_model import AcadosModel -from .utils import get_acados_path, J_to_idx, J_to_idx_slack, get_lib_ext - -class AcadosOcpDims: - """ - Class containing the dimensions of the optimal control problem. - """ - def __init__(self): - self.__nx = None - self.__nu = None - self.__nz = 0 - self.__np = 0 - self.__ny = 0 - self.__ny_e = 0 - self.__ny_0 = 0 - self.__nr = 0 - self.__nr_e = 0 - self.__nh = 0 - self.__nh_e = 0 - self.__nphi = 0 - self.__nphi_e = 0 - self.__nbx = 0 - self.__nbx_0 = 0 - self.__nbx_e = 0 - self.__nbu = 0 - self.__nsbx = 0 - self.__nsbx_e = 0 - self.__nsbu = 0 - self.__nsh = 0 - self.__nsh_e = 0 - self.__nsphi = 0 - self.__nsphi_e = 0 - self.__ns = 0 - self.__ns_e = 0 - self.__ng = 0 - self.__ng_e = 0 - self.__nsg = 0 - self.__nsg_e = 0 - self.__nbxe_0 = None - self.__N = None - - - @property - def nx(self): - """:math:`n_x` - number of states. - Type: int; default: None""" - return self.__nx - - @property - def nz(self): - """:math:`n_z` - number of algebraic variables. - Type: int; default: 0""" - return self.__nz - - @property - def nu(self): - """:math:`n_u` - number of inputs. - Type: int; default: None""" - return self.__nu - - @property - def np(self): - """:math:`n_p` - number of parameters. - Type: int; default: 0""" - return self.__np - - @property - def ny(self): - """:math:`n_y` - number of residuals in Lagrange term. - Type: int; default: 0""" - return self.__ny - - @property - def ny_0(self): - """:math:`n_{y}^0` - number of residuals in Mayer term. - Type: int; default: 0""" - return self.__ny_0 - - @property - def ny_e(self): - """:math:`n_{y}^e` - number of residuals in Mayer term. - Type: int; default: 0""" - return self.__ny_e - - @property - def nr(self): - """:math:`n_{\pi}` - dimension of the image of the inner nonlinear function in positive definite constraints. - Type: int; default: 0""" - return self.__nr - - @property - def nr_e(self): - """:math:`n_{\pi}^e` - dimension of the image of the inner nonlinear function in positive definite constraints. - Type: int; default: 0""" - return self.__nr_e - - @property - def nh(self): - """:math:`n_h` - number of nonlinear constraints. - Type: int; default: 0""" - return self.__nh - - @property - def nh_e(self): - """:math:`n_{h}^e` - number of nonlinear constraints at terminal shooting node N. - Type: int; default: 0""" - return self.__nh_e - - @property - def nphi(self): - """:math:`n_{\phi}` - number of convex-over-nonlinear constraints. - Type: int; default: 0""" - return self.__nphi - - @property - def nphi_e(self): - """:math:`n_{\phi}^e` - number of convex-over-nonlinear constraints at terminal shooting node N. - Type: int; default: 0""" - return self.__nphi_e - - @property - def nbx(self): - """:math:`n_{b_x}` - number of state bounds. - Type: int; default: 0""" - return self.__nbx - - @property - def nbxe_0(self): - """:math:`n_{be_{x0}}` - number of state bounds at initial shooting node that are equalities. - Type: int; default: None""" - return self.__nbxe_0 - - @property - def nbx_0(self): - """:math:`n_{b_{x0}}` - number of state bounds for initial state. - Type: int; default: 0""" - return self.__nbx_0 - - @property - def nbx_e(self): - """:math:`n_{b_x}` - number of state bounds at terminal shooting node N. - Type: int; default: 0""" - return self.__nbx_e - - @property - def nbu(self): - """:math:`n_{b_u}` - number of input bounds. - Type: int; default: 0""" - return self.__nbu - - @property - def nsbx(self): - """:math:`n_{{sb}_x}` - number of soft state bounds. - Type: int; default: 0""" - return self.__nsbx - - @property - def nsbx_e(self): - """:math:`n_{{sb}^e_{x}}` - number of soft state bounds at terminal shooting node N. - Type: int; default: 0""" - return self.__nsbx_e - - @property - def nsbu(self): - """:math:`n_{{sb}_u}` - number of soft input bounds. - Type: int; default: 0""" - return self.__nsbu - - @property - def nsg(self): - """:math:`n_{{sg}}` - number of soft general linear constraints. - Type: int; default: 0""" - return self.__nsg - - @property - def nsg_e(self): - """:math:`n_{{sg}^e}` - number of soft general linear constraints at terminal shooting node N. - Type: int; default: 0""" - return self.__nsg_e - - @property - def nsh(self): - """:math:`n_{{sh}}` - number of soft nonlinear constraints. - Type: int; default: 0""" - return self.__nsh - - @property - def nsh_e(self): - """:math:`n_{{sh}}^e` - number of soft nonlinear constraints at terminal shooting node N. - Type: int; default: 0""" - return self.__nsh_e - - @property - def nsphi(self): - """:math:`n_{{s\phi}}` - number of soft convex-over-nonlinear constraints. - Type: int; default: 0""" - return self.__nsphi - - @property - def nsphi_e(self): - """:math:`n_{{s\phi}^e}` - number of soft convex-over-nonlinear constraints at terminal shooting node N. - Type: int; default: 0""" - return self.__nsphi_e - - @property - def ns(self): - """:math:`n_{s}` - total number of slacks. - Type: int; default: 0""" - return self.__ns - - @property - def ns_e(self): - """:math:`n_{s}^e` - total number of slacks at terminal shooting node N. - Type: int; default: 0""" - return self.__ns_e - - @property - def ng(self): - """:math:`n_{g}` - number of general polytopic constraints. - Type: int; default: 0""" - return self.__ng - - @property - def ng_e(self): - """:math:`n_{g}^e` - number of general polytopic constraints at terminal shooting node N. - Type: int; default: 0""" - return self.__ng_e - - @property - def N(self): - """:math:`N` - prediction horizon. - Type: int; default: None""" - return self.__N - - @nx.setter - def nx(self, nx): - if isinstance(nx, int) and nx > 0: - self.__nx = nx - else: - raise Exception('Invalid nx value, expected positive integer.') - - @nz.setter - def nz(self, nz): - if isinstance(nz, int) and nz > -1: - self.__nz = nz - else: - raise Exception('Invalid nz value, expected nonnegative integer.') - - @nu.setter - def nu(self, nu): - if isinstance(nu, int) and nu > -1: - self.__nu = nu - else: - raise Exception('Invalid nu value, expected nonnegative integer.') - - @np.setter - def np(self, np): - if isinstance(np, int) and np > -1: - self.__np = np - else: - raise Exception('Invalid np value, expected nonnegative integer.') - - @ny_0.setter - def ny_0(self, ny_0): - if isinstance(ny_0, int) and ny_0 > -1: - self.__ny_0 = ny_0 - else: - raise Exception('Invalid ny_0 value, expected nonnegative integer.') - - @ny.setter - def ny(self, ny): - if isinstance(ny, int) and ny > -1: - self.__ny = ny - else: - raise Exception('Invalid ny value, expected nonnegative integer.') - - @ny_e.setter - def ny_e(self, ny_e): - if isinstance(ny_e, int) and ny_e > -1: - self.__ny_e = ny_e - else: - raise Exception('Invalid ny_e value, expected nonnegative integer.') - - @nr.setter - def nr(self, nr): - if isinstance(nr, int) and nr > -1: - self.__nr = nr - else: - raise Exception('Invalid nr value, expected nonnegative integer.') - - @nr_e.setter - def nr_e(self, nr_e): - if isinstance(nr_e, int) and nr_e > -1: - self.__nr_e = nr_e - else: - raise Exception('Invalid nr_e value, expected nonnegative integer.') - - @nh.setter - def nh(self, nh): - if isinstance(nh, int) and nh > -1: - self.__nh = nh - else: - raise Exception('Invalid nh value, expected nonnegative integer.') - - @nh_e.setter - def nh_e(self, nh_e): - if isinstance(nh_e, int) and nh_e > -1: - self.__nh_e = nh_e - else: - raise Exception('Invalid nh_e value, expected nonnegative integer.') - - @nphi.setter - def nphi(self, nphi): - if isinstance(nphi, int) and nphi > -1: - self.__nphi = nphi - else: - raise Exception('Invalid nphi value, expected nonnegative integer.') - - @nphi_e.setter - def nphi_e(self, nphi_e): - if isinstance(nphi_e, int) and nphi_e > -1: - self.__nphi_e = nphi_e - else: - raise Exception('Invalid nphi_e value, expected nonnegative integer.') - - @nbx.setter - def nbx(self, nbx): - if isinstance(nbx, int) and nbx > -1: - self.__nbx = nbx - else: - raise Exception('Invalid nbx value, expected nonnegative integer.') - - @nbxe_0.setter - def nbxe_0(self, nbxe_0): - if isinstance(nbxe_0, int) and nbxe_0 > -1: - self.__nbxe_0 = nbxe_0 - else: - raise Exception('Invalid nbxe_0 value, expected nonnegative integer.') - - @nbx_0.setter - def nbx_0(self, nbx_0): - if isinstance(nbx_0, int) and nbx_0 > -1: - self.__nbx_0 = nbx_0 - else: - raise Exception('Invalid nbx_0 value, expected nonnegative integer.') - - @nbx_e.setter - def nbx_e(self, nbx_e): - if isinstance(nbx_e, int) and nbx_e > -1: - self.__nbx_e = nbx_e - else: - raise Exception('Invalid nbx_e value, expected nonnegative integer.') - - @nbu.setter - def nbu(self, nbu): - if isinstance(nbu, int) and nbu > -1: - self.__nbu = nbu - else: - raise Exception('Invalid nbu value, expected nonnegative integer.') - - @nsbx.setter - def nsbx(self, nsbx): - if isinstance(nsbx, int) and nsbx > -1: - self.__nsbx = nsbx - else: - raise Exception('Invalid nsbx value, expected nonnegative integer.') - - @nsbx_e.setter - def nsbx_e(self, nsbx_e): - if isinstance(nsbx_e, int) and nsbx_e > -1: - self.__nsbx_e = nsbx_e - else: - raise Exception('Invalid nsbx_e value, expected nonnegative integer.') - - @nsbu.setter - def nsbu(self, nsbu): - if isinstance(nsbu, int) and nsbu > -1: - self.__nsbu = nsbu - else: - raise Exception('Invalid nsbu value, expected nonnegative integer.') - - @nsg.setter - def nsg(self, nsg): - if isinstance(nsg, int) and nsg > -1: - self.__nsg = nsg - else: - raise Exception('Invalid nsg value, expected nonnegative integer.') - - @nsg_e.setter - def nsg_e(self, nsg_e): - if isinstance(nsg_e, int) and nsg_e > -1: - self.__nsg_e = nsg_e - else: - raise Exception('Invalid nsg_e value, expected nonnegative integer.') - - @nsh.setter - def nsh(self, nsh): - if isinstance(nsh, int) and nsh > -1: - self.__nsh = nsh - else: - raise Exception('Invalid nsh value, expected nonnegative integer.') - - @nsh_e.setter - def nsh_e(self, nsh_e): - if isinstance(nsh_e, int) and nsh_e > -1: - self.__nsh_e = nsh_e - else: - raise Exception('Invalid nsh_e value, expected nonnegative integer.') - - @nsphi.setter - def nsphi(self, nsphi): - if isinstance(nsphi, int) and nsphi > -1: - self.__nsphi = nsphi - else: - raise Exception('Invalid nsphi value, expected nonnegative integer.') - - @nsphi_e.setter - def nsphi_e(self, nsphi_e): - if isinstance(nsphi_e, int) and nsphi_e > -1: - self.__nsphi_e = nsphi_e - else: - raise Exception('Invalid nsphi_e value, expected nonnegative integer.') - - @ns.setter - def ns(self, ns): - if isinstance(ns, int) and ns > -1: - self.__ns = ns - else: - raise Exception('Invalid ns value, expected nonnegative integer.') - - @ns_e.setter - def ns_e(self, ns_e): - if isinstance(ns_e, int) and ns_e > -1: - self.__ns_e = ns_e - else: - raise Exception('Invalid ns_e value, expected nonnegative integer.') - - @ng.setter - def ng(self, ng): - if isinstance(ng, int) and ng > -1: - self.__ng = ng - else: - raise Exception('Invalid ng value, expected nonnegative integer.') - - @ng_e.setter - def ng_e(self, ng_e): - if isinstance(ng_e, int) and ng_e > -1: - self.__ng_e = ng_e - else: - raise Exception('Invalid ng_e value, expected nonnegative integer.') - - @N.setter - def N(self, N): - if isinstance(N, int) and N > 0: - self.__N = N - else: - raise Exception('Invalid N value, expected positive integer.') - - def set(self, attr, value): - setattr(self, attr, value) - - -class AcadosOcpCost: - """ - Class containing the numerical data of the cost: - - NOTE: all cost terms, except for the terminal one are weighted with the corresponding time step. - This means given the time steps are :math:`\Delta t_0,..., \Delta t_N`, the total cost is given by: - :math:`c_\\text{total} = \Delta t_0 \cdot c_0(x_0, u_0, p_0, z_0) + ... + \Delta t_{N-1} \cdot c_{N-1}(x_0, u_0, p_0, z_0) + c_N(x_N, p_N)`. - - This means the Lagrange cost term is given in continuous time, this makes up for a seeminglessly OCP discretization with a nonuniform time grid. - - In case of LINEAR_LS: - stage cost is - :math:`l(x,u,z) = || V_x \, x + V_u \, u + V_z \, z - y_\\text{ref}||^2_W`, - terminal cost is - :math:`m(x) = || V^e_x \, x - y_\\text{ref}^e||^2_{W^e}` - - In case of NONLINEAR_LS: - stage cost is - :math:`l(x,u,z,p) = || y(x,u,z,p) - y_\\text{ref}||^2_W`, - terminal cost is - :math:`m(x,p) = || y^e(x,p) - y_\\text{ref}^e||^2_{W^e}` - - In case of CONVEX_OVER_NONLINEAR: - stage cost is - :math:`l(x,u,p) = \psi(y(x,u,p) - y_\\text{ref}, p)`, - terminal cost is - :math:`m(x, p) = \psi^e (y^e(x,p) - y_\\text{ref}^e, p)` - """ - def __init__(self): - # initial stage - self.__cost_type_0 = None - self.__W_0 = None - self.__Vx_0 = None - self.__Vu_0 = None - self.__Vz_0 = None - self.__yref_0 = None - self.__cost_ext_fun_type_0 = 'casadi' - # Lagrange term - self.__cost_type = 'LINEAR_LS' # cost type - self.__W = np.zeros((0,0)) - self.__Vx = np.zeros((0,0)) - self.__Vu = np.zeros((0,0)) - self.__Vz = np.zeros((0,0)) - self.__yref = np.array([]) - self.__Zl = np.array([]) - self.__Zu = np.array([]) - self.__zl = np.array([]) - self.__zu = np.array([]) - self.__cost_ext_fun_type = 'casadi' - # Mayer term - self.__cost_type_e = 'LINEAR_LS' - self.__W_e = np.zeros((0,0)) - self.__Vx_e = np.zeros((0,0)) - self.__yref_e = np.array([]) - self.__Zl_e = np.array([]) - self.__Zu_e = np.array([]) - self.__zl_e = np.array([]) - self.__zu_e = np.array([]) - self.__cost_ext_fun_type_e = 'casadi' - - # initial stage - @property - def cost_type_0(self): - """Cost type at initial shooting node (0) - -- string in {EXTERNAL, LINEAR_LS, NONLINEAR_LS, CONVEX_OVER_NONLINEAR} or :code:`None`. - Default: :code:`None`. - - .. note:: Cost at initial stage is the same as for intermediate shooting nodes if not set differently explicitly. - - .. note:: If :py:attr:`cost_type_0` is set to :code:`None` values in :py:attr:`W_0`, :py:attr:`Vx_0`, :py:attr:`Vu_0`, :py:attr:`Vz_0` and :py:attr:`yref_0` are ignored (set to :code:`None`). - """ - return self.__cost_type_0 - - @property - def W_0(self): - """:math:`W_0` - weight matrix at initial shooting node (0). - Default: :code:`None`. - """ - return self.__W_0 - - @property - def Vx_0(self): - """:math:`V_x^0` - x matrix coefficient at initial shooting node (0). - Default: :code:`None`. - """ - return self.__Vx_0 - - @property - def Vu_0(self): - """:math:`V_u^0` - u matrix coefficient at initial shooting node (0). - Default: :code:`None`. - """ - return self.__Vu_0 - - @property - def Vz_0(self): - """:math:`V_z^0` - z matrix coefficient at initial shooting node (0). - Default: :code:`None`. - """ - return self.__Vz_0 - - @property - def yref_0(self): - """:math:`y_\\text{ref}^0` - reference at initial shooting node (0). - Default: :code:`None`. - """ - return self.__yref_0 - - @property - def cost_ext_fun_type_0(self): - """Type of external function for cost at initial shooting node (0) - -- string in {casadi, generic} or :code:`None` - Default: :code:'casadi'. - - .. note:: Cost at initial stage is the same as for intermediate shooting nodes if not set differently explicitly. - """ - return self.__cost_ext_fun_type_0 - - @yref_0.setter - def yref_0(self, yref_0): - if isinstance(yref_0, np.ndarray) and len(yref_0.shape) == 1: - self.__yref_0 = yref_0 - else: - raise Exception('Invalid yref_0 value, expected 1-dimensional numpy array.') - - @W_0.setter - def W_0(self, W_0): - if isinstance(W_0, np.ndarray) and len(W_0.shape) == 2: - self.__W_0 = W_0 - else: - raise Exception('Invalid cost W_0 value. ' \ - + 'Should be 2 dimensional numpy array.') - - @Vx_0.setter - def Vx_0(self, Vx_0): - if isinstance(Vx_0, np.ndarray) and len(Vx_0.shape) == 2: - self.__Vx_0 = Vx_0 - else: - raise Exception('Invalid cost Vx_0 value. ' \ - + 'Should be 2 dimensional numpy array.') - - @Vu_0.setter - def Vu_0(self, Vu_0): - if isinstance(Vu_0, np.ndarray) and len(Vu_0.shape) == 2: - self.__Vu_0 = Vu_0 - else: - raise Exception('Invalid cost Vu_0 value. ' \ - + 'Should be 2 dimensional numpy array.') - - @Vz_0.setter - def Vz_0(self, Vz_0): - if isinstance(Vz_0, np.ndarray) and len(Vz_0.shape) == 2: - self.__Vz_0 = Vz_0 - else: - raise Exception('Invalid cost Vz_0 value. ' \ - + 'Should be 2 dimensional numpy array.') - - @cost_ext_fun_type_0.setter - def cost_ext_fun_type_0(self, cost_ext_fun_type_0): - if cost_ext_fun_type_0 in ['casadi', 'generic']: - self.__cost_ext_fun_type_0 = cost_ext_fun_type_0 - else: - raise Exception('Invalid cost_ext_fun_type_0 value, expected numpy array.') - - # Lagrange term - @property - def cost_type(self): - """ - Cost type at intermediate shooting nodes (1 to N-1) - -- string in {EXTERNAL, LINEAR_LS, NONLINEAR_LS, CONVEX_OVER_NONLINEAR}. - Default: 'LINEAR_LS'. - """ - return self.__cost_type - - @property - def W(self): - """:math:`W` - weight matrix at intermediate shooting nodes (1 to N-1). - Default: :code:`np.zeros((0,0))`. - """ - return self.__W - - @property - def Vx(self): - """:math:`V_x` - x matrix coefficient at intermediate shooting nodes (1 to N-1). - Default: :code:`np.zeros((0,0))`. - """ - return self.__Vx - - @property - def Vu(self): - """:math:`V_u` - u matrix coefficient at intermediate shooting nodes (1 to N-1). - Default: :code:`np.zeros((0,0))`. - """ - return self.__Vu - - @property - def Vz(self): - """:math:`V_z` - z matrix coefficient at intermediate shooting nodes (1 to N-1). - Default: :code:`np.zeros((0,0))`. - """ - return self.__Vz - - @property - def yref(self): - """:math:`y_\\text{ref}` - reference at intermediate shooting nodes (1 to N-1). - Default: :code:`np.array([])`. - """ - return self.__yref - - @property - def Zl(self): - """:math:`Z_l` - diagonal of Hessian wrt lower slack at intermediate shooting nodes (0 to N-1). - Default: :code:`np.array([])`. - """ - return self.__Zl - - @property - def Zu(self): - """:math:`Z_u` - diagonal of Hessian wrt upper slack at intermediate shooting nodes (0 to N-1). - Default: :code:`np.array([])`. - """ - return self.__Zu - - @property - def zl(self): - """:math:`z_l` - gradient wrt lower slack at intermediate shooting nodes (0 to N-1). - Default: :code:`np.array([])`. - """ - return self.__zl - - @property - def zu(self): - """:math:`z_u` - gradient wrt upper slack at intermediate shooting nodes (0 to N-1). - Default: :code:`np.array([])`. - """ - return self.__zu - - @property - def cost_ext_fun_type(self): - """Type of external function for cost at intermediate shooting nodes (1 to N-1). - -- string in {casadi, generic} - Default: :code:'casadi'. - """ - return self.__cost_ext_fun_type - - @cost_type.setter - def cost_type(self, cost_type): - cost_types = ('LINEAR_LS', 'NONLINEAR_LS', 'EXTERNAL', 'CONVEX_OVER_NONLINEAR') - if cost_type in cost_types: - self.__cost_type = cost_type - else: - raise Exception('Invalid cost_type value.') - - @cost_type_0.setter - def cost_type_0(self, cost_type_0): - cost_types = ('LINEAR_LS', 'NONLINEAR_LS', 'EXTERNAL', 'CONVEX_OVER_NONLINEAR') - if cost_type_0 in cost_types: - self.__cost_type_0 = cost_type_0 - else: - raise Exception('Invalid cost_type_0 value.') - - @W.setter - def W(self, W): - if isinstance(W, np.ndarray) and len(W.shape) == 2: - self.__W = W - else: - raise Exception('Invalid cost W value. ' \ - + 'Should be 2 dimensional numpy array.') - - - @Vx.setter - def Vx(self, Vx): - if isinstance(Vx, np.ndarray) and len(Vx.shape) == 2: - self.__Vx = Vx - else: - raise Exception('Invalid cost Vx value. ' \ - + 'Should be 2 dimensional numpy array.') - - @Vu.setter - def Vu(self, Vu): - if isinstance(Vu, np.ndarray) and len(Vu.shape) == 2: - self.__Vu = Vu - else: - raise Exception('Invalid cost Vu value. ' \ - + 'Should be 2 dimensional numpy array.') - - @Vz.setter - def Vz(self, Vz): - if isinstance(Vz, np.ndarray) and len(Vz.shape) == 2: - self.__Vz = Vz - else: - raise Exception('Invalid cost Vz value. ' \ - + 'Should be 2 dimensional numpy array.') - - @yref.setter - def yref(self, yref): - if isinstance(yref, np.ndarray) and len(yref.shape) == 1: - self.__yref = yref - else: - raise Exception('Invalid yref value, expected 1-dimensional numpy array.') - - @Zl.setter - def Zl(self, Zl): - if isinstance(Zl, np.ndarray): - self.__Zl = Zl - else: - raise Exception('Invalid Zl value, expected numpy array.') - - @Zu.setter - def Zu(self, Zu): - if isinstance(Zu, np.ndarray): - self.__Zu = Zu - else: - raise Exception('Invalid Zu value, expected numpy array.') - - @zl.setter - def zl(self, zl): - if isinstance(zl, np.ndarray): - self.__zl = zl - else: - raise Exception('Invalid zl value, expected numpy array.') - - @zu.setter - def zu(self, zu): - if isinstance(zu, np.ndarray): - self.__zu = zu - else: - raise Exception('Invalid zu value, expected numpy array.') - - @cost_ext_fun_type.setter - def cost_ext_fun_type(self, cost_ext_fun_type): - if cost_ext_fun_type in ['casadi', 'generic']: - self.__cost_ext_fun_type = cost_ext_fun_type - else: - raise Exception("Invalid cost_ext_fun_type value, expected one in ['casadi', 'generic'].") - - # Mayer term - @property - def cost_type_e(self): - """ - Cost type at terminal shooting node (N) - -- string in {EXTERNAL, LINEAR_LS, NONLINEAR_LS, CONVEX_OVER_NONLINEAR}. - Default: 'LINEAR_LS'. - """ - return self.__cost_type_e - - @property - def W_e(self): - """:math:`W_e` - weight matrix at terminal shooting node (N). - Default: :code:`np.zeros((0,0))`. - """ - return self.__W_e - - @property - def Vx_e(self): - """:math:`V_x^e` - x matrix coefficient for cost at terminal shooting node (N). - Default: :code:`np.zeros((0,0))`. - """ - return self.__Vx_e - - @property - def yref_e(self): - """:math:`y_\\text{ref}^e` - cost reference at terminal shooting node (N). - Default: :code:`np.array([])`. - """ - return self.__yref_e - - @property - def Zl_e(self): - """:math:`Z_l^e` - diagonal of Hessian wrt lower slack at terminal shooting node (N). - Default: :code:`np.array([])`. - """ - return self.__Zl_e - - @property - def Zu_e(self): - """:math:`Z_u^e` - diagonal of Hessian wrt upper slack at terminal shooting node (N). - Default: :code:`np.array([])`. - """ - return self.__Zu_e - - @property - def zl_e(self): - """:math:`z_l^e` - gradient wrt lower slack at terminal shooting node (N). - Default: :code:`np.array([])`. - """ - return self.__zl_e - - @property - def zu_e(self): - """:math:`z_u^e` - gradient wrt upper slack at terminal shooting node (N). - Default: :code:`np.array([])`. - """ - return self.__zu_e - - @property - def cost_ext_fun_type_e(self): - """Type of external function for cost at terminal shooting node (N). - -- string in {casadi, generic} - Default: :code:'casadi'. - """ - return self.__cost_ext_fun_type_e - - @cost_type_e.setter - def cost_type_e(self, cost_type_e): - cost_types = ('LINEAR_LS', 'NONLINEAR_LS', 'EXTERNAL', 'CONVEX_OVER_NONLINEAR') - - if cost_type_e in cost_types: - self.__cost_type_e = cost_type_e - else: - raise Exception('Invalid cost_type_e value.') - - @W_e.setter - def W_e(self, W_e): - if isinstance(W_e, np.ndarray) and len(W_e.shape) == 2: - self.__W_e = W_e - else: - raise Exception('Invalid cost W_e value. ' \ - + 'Should be 2 dimensional numpy array.') - - @Vx_e.setter - def Vx_e(self, Vx_e): - if isinstance(Vx_e, np.ndarray) and len(Vx_e.shape) == 2: - self.__Vx_e = Vx_e - else: - raise Exception('Invalid cost Vx_e value. ' \ - + 'Should be 2 dimensional numpy array.') - - @yref_e.setter - def yref_e(self, yref_e): - if isinstance(yref_e, np.ndarray) and len(yref_e.shape) == 1: - self.__yref_e = yref_e - else: - raise Exception('Invalid yref_e value, expected 1-dimensional numpy array.') - - @Zl_e.setter - def Zl_e(self, Zl_e): - if isinstance(Zl_e, np.ndarray): - self.__Zl_e = Zl_e - else: - raise Exception('Invalid Zl_e value, expected numpy array.') - - @Zu_e.setter - def Zu_e(self, Zu_e): - if isinstance(Zu_e, np.ndarray): - self.__Zu_e = Zu_e - else: - raise Exception('Invalid Zu_e value, expected numpy array.') - - @zl_e.setter - def zl_e(self, zl_e): - if isinstance(zl_e, np.ndarray): - self.__zl_e = zl_e - else: - raise Exception('Invalid zl_e value, expected numpy array.') - - @zu_e.setter - def zu_e(self, zu_e): - if isinstance(zu_e, np.ndarray): - self.__zu_e = zu_e - else: - raise Exception('Invalid zu_e value, expected numpy array.') - - @cost_ext_fun_type_e.setter - def cost_ext_fun_type_e(self, cost_ext_fun_type_e): - if cost_ext_fun_type_e in ['casadi', 'generic']: - self.__cost_ext_fun_type_e = cost_ext_fun_type_e - else: - raise Exception("Invalid cost_ext_fun_type_e value, expected one in ['casadi', 'generic'].") - - def set(self, attr, value): - setattr(self, attr, value) - - -def print_J_to_idx_note(): - print("NOTE: J* matrix is converted to zero based vector idx* vector, which is returned here.") - - -class AcadosOcpConstraints: - """ - class containing the description of the constraints - """ - def __init__(self): - self.__constr_type = 'BGH' - self.__constr_type_e = 'BGH' - # initial x - self.__lbx_0 = np.array([]) - self.__ubx_0 = np.array([]) - self.__idxbx_0 = np.array([]) - self.__idxbxe_0 = np.array([]) - # state bounds - self.__lbx = np.array([]) - self.__ubx = np.array([]) - self.__idxbx = np.array([]) - # bounds on x at shooting node N - self.__lbx_e = np.array([]) - self.__ubx_e = np.array([]) - self.__idxbx_e = np.array([]) - # bounds on u - self.__lbu = np.array([]) - self.__ubu = np.array([]) - self.__idxbu = np.array([]) - # polytopic constraints - self.__lg = np.array([]) - self.__ug = np.array([]) - self.__D = np.zeros((0,0)) - self.__C = np.zeros((0,0)) - # polytopic constraints at shooting node N - self.__C_e = np.zeros((0,0)) - self.__lg_e = np.array([]) - self.__ug_e = np.array([]) - # nonlinear constraints - self.__lh = np.array([]) - self.__uh = np.array([]) - # nonlinear constraints at shooting node N - self.__uh_e = np.array([]) - self.__lh_e = np.array([]) - # convex-over-nonlinear constraints - self.__lphi = np.array([]) - self.__uphi = np.array([]) - # nonlinear constraints at shooting node N - self.__uphi_e = np.array([]) - self.__lphi_e = np.array([]) - # SLACK BOUNDS - # soft bounds on x - self.__lsbx = np.array([]) - self.__usbx = np.array([]) - self.__idxsbx = np.array([]) - # soft bounds on u - self.__lsbu = np.array([]) - self.__usbu = np.array([]) - self.__idxsbu = np.array([]) - # soft bounds on x at shooting node N - self.__lsbx_e = np.array([]) - self.__usbx_e = np.array([]) - self.__idxsbx_e= np.array([]) - # soft bounds on general linear constraints - self.__lsg = np.array([]) - self.__usg = np.array([]) - self.__idxsg = np.array([]) - # soft bounds on nonlinear constraints - self.__lsh = np.array([]) - self.__ush = np.array([]) - self.__idxsh = np.array([]) - # soft bounds on nonlinear constraints - self.__lsphi = np.array([]) - self.__usphi = np.array([]) - self.__idxsphi = np.array([]) - # soft bounds on general linear constraints at shooting node N - self.__lsg_e = np.array([]) - self.__usg_e = np.array([]) - self.__idxsg_e = np.array([]) - # soft bounds on nonlinear constraints at shooting node N - self.__lsh_e = np.array([]) - self.__ush_e = np.array([]) - self.__idxsh_e = np.array([]) - # soft bounds on nonlinear constraints at shooting node N - self.__lsphi_e = np.array([]) - self.__usphi_e = np.array([]) - self.__idxsphi_e = np.array([]) - - - # types - @property - def constr_type(self): - """Constraints type for shooting nodes (0 to N-1). string in {BGH, BGP}. - Default: BGH; BGP is for convex over nonlinear.""" - return self.__constr_type - - @property - def constr_type_e(self): - """Constraints type for terminal shooting node N. string in {BGH, BGP}. - Default: BGH; BGP is for convex over nonlinear.""" - return self.__constr_type_e - - # initial bounds on x - @property - def lbx_0(self): - """:math:`\\underline{x_0}` - lower bounds on x at initial stage 0. - Type: :code:`np.ndarray`; default: :code:`np.array([])`.""" - return self.__lbx_0 - - @property - def ubx_0(self): - """:math:`\\bar{x_0}` - upper bounds on x at initial stage 0. - Type: :code:`np.ndarray`; default: :code:`np.array([])`""" - return self.__ubx_0 - - @property - def Jbx_0(self): - """:math:`J_{bx,0}` - matrix coefficient for bounds on x at initial stage 0. - Translated internally to :py:attr:`idxbx_0`""" - print_J_to_idx_note() - return self.__idxbx_0 - - @property - def idxbx_0(self): - """Indices of bounds on x at initial stage 0 - -- can be set automatically via x0. - Can be set by using :py:attr:`Jbx_0`. - Type: :code:`np.ndarray`; default: :code:`np.array([])`""" - return self.__idxbx_0 - - @property - def idxbxe_0(self): - """Indices of bounds on x0 that are equalities -- can be set automatically via :py:attr:`x0`. - Type: :code:`np.ndarray`; default: :code:`np.array([])`""" - return self.__idxbxe_0 - - # bounds on x - @property - def lbx(self): - """:math:`\\underline{x}` - lower bounds on x at intermediate shooting nodes (1 to N-1). - Type: :code:`np.ndarray`; default: :code:`np.array([])`""" - return self.__lbx - - @property - def ubx(self): - """:math:`\\bar{x}` - upper bounds on x at intermediate shooting nodes (1 to N-1). - Type: :code:`np.ndarray`; default: :code:`np.array([])`""" - return self.__ubx - - @property - def idxbx(self): - """indices of bounds on x (defines :math:`J_{bx}`) at intermediate shooting nodes (1 to N-1). - Can be set by using :py:attr:`Jbx`. - Type: :code:`np.ndarray`; default: :code:`np.array([])`""" - return self.__idxbx - - @property - def Jbx(self): - """:math:`J_{bx}` - matrix coefficient for bounds on x - at intermediate shooting nodes (1 to N-1). - Translated internally into :py:attr:`idxbx`.""" - print_J_to_idx_note() - return self.__idxbx - - # bounds on x at shooting node N - @property - def lbx_e(self): - """:math:`\\underline{x}^e` - lower bounds on x at terminal shooting node N. - Type: :code:`np.ndarray`; default: :code:`np.array([])`""" - return self.__lbx_e - - @property - def ubx_e(self): - """:math:`\\bar{x}^e` - upper bounds on x at terminal shooting node N. - Type: :code:`np.ndarray`; default: :code:`np.array([])`""" - return self.__ubx_e - - @property - def idxbx_e(self): - """Indices for bounds on x at terminal shooting node N (defines :math:`J_{bx}^e`). - Can be set by using :py:attr:`Jbx_e`. - Type: :code:`np.ndarray`; default: :code:`np.array([])`""" - return self.__idxbx_e - - @property - def Jbx_e(self): - """:math:`J_{bx}^e` matrix coefficient for bounds on x at terminal shooting node N. - Translated internally into :py:attr:`idxbx_e`.""" - print_J_to_idx_note() - return self.__idxbx_e - - # bounds on u - @property - def lbu(self): - """:math:`\\underline{u}` - lower bounds on u at shooting nodes (0 to N-1). - Type: :code:`np.ndarray`; default: :code:`np.array([])` - """ - return self.__lbu - - @property - def ubu(self): - """:math:`\\bar{u}` - upper bounds on u at shooting nodes (0 to N-1). - Type: :code:`np.ndarray`; default: :code:`np.array([])` - """ - return self.__ubu - - @property - def idxbu(self): - """Indices of bounds on u (defines :math:`J_{bu}`) at shooting nodes (0 to N-1). - Can be set by using :py:attr:`Jbu`. - Type: :code:`np.ndarray`; default: :code:`np.array([])` - """ - return self.__idxbu - - @property - def Jbu(self): - """:math:`J_{bu}` - matrix coefficient for bounds on u at shooting nodes (0 to N-1). - Translated internally to :py:attr:`idxbu`. - """ - print_J_to_idx_note() - return self.__idxbu - - # polytopic constraints - @property - def C(self): - """:math:`C` - C matrix in :math:`\\underline{g} \\leq D \, u + C \, x \\leq \\bar{g}` - at shooting nodes (0 to N-1). - Type: :code:`np.ndarray`; default: :code:`np.array((0,0))`. - """ - return self.__C - - @property - def D(self): - """:math:`D` - D matrix in :math:`\\underline{g} \\leq D \, u + C \, x \\leq \\bar{g}` - at shooting nodes (0 to N-1). - Type: :code:`np.ndarray`; default: :code:`np.array((0,0))` - """ - return self.__D - - @property - def lg(self): - """:math:`\\underline{g}` - lower bound for general polytopic inequalities - at shooting nodes (0 to N-1). - Type: :code:`np.ndarray`; default: :code:`np.array([])` - """ - return self.__lg - - @property - def ug(self): - """:math:`\\bar{g}` - upper bound for general polytopic inequalities - at shooting nodes (0 to N-1). - Type: :code:`np.ndarray`; default: :code:`np.array([])`. - """ - return self.__ug - - # polytopic constraints at shooting node N - @property - def C_e(self): - """:math:`C^e` - C matrix at terminal shooting node N. - Type: :code:`np.ndarray`; default: :code:`np.array((0,0))`. - """ - return self.__C_e - - @property - def lg_e(self): - """:math:`\\underline{g}^e` - lower bound on general polytopic inequalities - at terminal shooting node N. - Type: :code:`np.ndarray`; default: :code:`np.array([])`. - """ - return self.__lg_e - - @property - def ug_e(self): - """:math:`\\bar{g}^e` - upper bound on general polytopic inequalities - at terminal shooting node N. - Type: :code:`np.ndarray`; default: :code:`np.array([])`. - """ - return self.__ug_e - - - # nonlinear constraints - @property - def lh(self): - """:math:`\\underline{h}` - lower bound for nonlinear inequalities - at shooting nodes (0 to N-1). - Type: :code:`np.ndarray`; default: :code:`np.array([])`. - """ - return self.__lh - - @property - def uh(self): - """:math:`\\bar{h}` - upper bound for nonlinear inequalities - at shooting nodes (0 to N-1). - Type: :code:`np.ndarray`; default: :code:`np.array([])`. - """ - return self.__uh - - # nonlinear constraints at shooting node N - @property - def lh_e(self): - """:math:`\\underline{h}^e` - lower bound on nonlinear inequalities - at terminal shooting node N. - Type: :code:`np.ndarray`; default: :code:`np.array([])`. - """ - return self.__lh_e - - @property - def uh_e(self): - """:math:`\\bar{h}^e` - upper bound on nonlinear inequalities - at terminal shooting node N. - Type: :code:`np.ndarray`; default: :code:`np.array([])`. - """ - return self.__uh_e - - # convex-over-nonlinear constraints - @property - def lphi(self): - """:math:`\\underline{\phi}` - lower bound for convex-over-nonlinear inequalities - at shooting nodes (0 to N-1). - Type: :code:`np.ndarray`; default: :code:`np.array([])`. - """ - return self.__lphi - - @property - def uphi(self): - """:math:`\\bar{\phi}` - upper bound for convex-over-nonlinear inequalities - at shooting nodes (0 to N-1). - Type: :code:`np.ndarray`; default: :code:`np.array([])`. - """ - return self.__uphi - - # convex-over-nonlinear constraints at shooting node N - @property - def lphi_e(self): - """:math:`\\underline{\phi}^e` - lower bound on convex-over-nonlinear inequalities - at terminal shooting node N. - Type: :code:`np.ndarray`; default: :code:`np.array([])`. - """ - return self.__lphi_e - - @property - def uphi_e(self): - """:math:`\\bar{\phi}^e` - upper bound on convex-over-nonlinear inequalities - at terminal shooting node N. - Type: :code:`np.ndarray`; default: :code:`np.array([])`. - """ - return self.__uphi_e - - - # SLACK bounds - # soft bounds on x - @property - def lsbx(self): - """Lower bounds on slacks corresponding to soft lower bounds on x - at stages (1 to N-1); - not required - zeros by default""" - return self.__lsbx - - @property - def usbx(self): - """Lower bounds on slacks corresponding to soft upper bounds on x - at stages (1 to N-1); - not required - zeros by default""" - return self.__usbx - - @property - def idxsbx(self): - """Indices of soft bounds on x within the indices of bounds on x - at stages (1 to N-1). - Can be set by using :py:attr:`Jsbx`. - Type: :code:`np.ndarray`; default: :code:`np.array([])`""" - return self.__idxsbx - - @property - def Jsbx(self): - """:math:`J_{sbx}` - matrix coefficient for soft bounds on x - at stages (1 to N-1); - Translated internally into :py:attr:`idxsbx`.""" - print_J_to_idx_note() - return self.__idxsbx - - # soft bounds on u - @property - def lsbu(self): - """Lower bounds on slacks corresponding to soft lower bounds on u - at stages (0 to N-1). - Not required - zeros by default.""" - return self.__lsbu - - @property - def usbu(self): - """Lower bounds on slacks corresponding to soft upper bounds on u - at stages (0 to N-1); - not required - zeros by default""" - return self.__usbu - - @property - def idxsbu(self): - """Indices of soft bounds on u within the indices of bounds on u - at stages (0 to N-1). - Can be set by using :py:attr:`Jsbu`. - Type: :code:`np.ndarray`; default: :code:`np.array([])`""" - return self.__idxsbu - - @property - def Jsbu(self): - """:math:`J_{sbu}` - matrix coefficient for soft bounds on u - at stages (0 to N-1); - internally translated into :py:attr:`idxsbu`""" - print_J_to_idx_note() - return self.__idxsbu - - # soft bounds on x at shooting node N - @property - def lsbx_e(self): - """Lower bounds on slacks corresponding to soft lower bounds on x at shooting node N. - Not required - zeros by default""" - return self.__lsbx_e - - @property - def usbx_e(self): - """Lower bounds on slacks corresponding to soft upper bounds on x at shooting node N. - Not required - zeros by default""" - return self.__usbx_e - - @property - def idxsbx_e(self): - """Indices of soft bounds on x at shooting node N, within the indices of bounds on x at terminal shooting node N. - Can be set by using :py:attr:`Jsbx_e`. - Type: :code:`np.ndarray`; default: :code:`np.array([])`""" - return self.__idxsbx_e - - @property - def Jsbx_e(self): - """:math:`J_{sbx}^e` - matrix coefficient for soft bounds on x at terminal shooting node N. - Translated internally to :py:attr:`idxsbx_e`""" - print_J_to_idx_note() - return self.__idxsbx_e - - # soft general linear constraints - @property - def lsg(self): - """Lower bounds on slacks corresponding to soft lower bounds for general linear constraints - at stages (0 to N-1). - Type: :code:`np.ndarray`; default: :code:`np.array([])` - """ - return self.__lsg - - @property - def usg(self): - """Lower bounds on slacks corresponding to soft upper bounds for general linear constraints. - Not required - zeros by default""" - return self.__usg - - @property - def idxsg(self): - """Indices of soft general linear constraints within the indices of general linear constraints. - Can be set by using :py:attr:`Jsg`. - Type: :code:`np.ndarray`; default: :code:`np.array([])`""" - return self.__idxsg - - @property - def Jsg(self): - """:math:`J_{sg}` - matrix coefficient for soft bounds on general linear constraints. - Translated internally to :py:attr:`idxsg`""" - print_J_to_idx_note() - return self.__idxsg - - # soft nonlinear constraints - @property - def lsh(self): - """Lower bounds on slacks corresponding to soft lower bounds for nonlinear constraints. - Not required - zeros by default""" - return self.__lsh - - @property - def ush(self): - """Lower bounds on slacks corresponding to soft upper bounds for nonlinear constraints. - Not required - zeros by default""" - return self.__ush - - @property - def idxsh(self): - """Indices of soft nonlinear constraints within the indices of nonlinear constraints. - Can be set by using :py:attr:`Jbx`. - Type: :code:`np.ndarray`; default: :code:`np.array([])`""" - return self.__idxsh - - @property - def Jsh(self): - """:math:`J_{sh}` - matrix coefficient for soft bounds on nonlinear constraints. - Translated internally to :py:attr:`idxsh`""" - print_J_to_idx_note() - return self.__idxsh - - # soft bounds on convex-over-nonlinear constraints - @property - def lsphi(self): - """Lower bounds on slacks corresponding to soft lower bounds for convex-over-nonlinear constraints. - Not required - zeros by default""" - return self.__lsphi - - @property - def usphi(self): - """Lower bounds on slacks corresponding to soft upper bounds for convex-over-nonlinear constraints. - Not required - zeros by default""" - return self.__usphi - - @property - def idxsphi(self): - """Indices of soft convex-over-nonlinear constraints within the indices of nonlinear constraints. - Can be set by using :py:attr:`Jsphi`. - Type: :code:`np.ndarray`; default: :code:`np.array([])`""" - return self.__idxsphi - - @property - def Jsphi(self): - """:math:`J_{s, \phi}` - matrix coefficient for soft bounds on convex-over-nonlinear constraints. - Translated internally into :py:attr:`idxsphi`.""" - print_J_to_idx_note() - return self.__idxsphi - - - # soft bounds on general linear constraints at shooting node N - @property - def lsg_e(self): - """Lower bounds on slacks corresponding to soft lower bounds for general linear constraints at shooting node N. - Not required - zeros by default""" - return self.__lsg_e - - @property - def usg_e(self): - """Lower bounds on slacks corresponding to soft upper bounds for general linear constraints at shooting node N. - Not required - zeros by default""" - return self.__usg_e - - @property - def idxsg_e(self): - """Indices of soft general linear constraints at shooting node N within the indices of general linear constraints at shooting node N. - Can be set by using :py:attr:`Jsg_e`.""" - return self.__idxsg_e - - @property - def Jsg_e(self): - """:math:`J_{s,h}^e` - matrix coefficient for soft bounds on general linear constraints at terminal shooting node N. - Translated internally to :py:attr:`idxsg_e`""" - print_J_to_idx_note() - return self.__idxsg_e - - - # soft bounds on nonlinear constraints at shooting node N - @property - def lsh_e(self): - """Lower bounds on slacks corresponding to soft lower bounds for nonlinear constraints at terminal shooting node N. - Not required - zeros by default""" - return self.__lsh_e - - @property - def ush_e(self): - """Lower bounds on slacks corresponding to soft upper bounds for nonlinear constraints at terminal shooting node N. - Not required - zeros by default""" - return self.__ush_e - - @property - def idxsh_e(self): - """Indices of soft nonlinear constraints at shooting node N within the indices of nonlinear constraints at terminal shooting node N. - Can be set by using :py:attr:`Jsh_e`.""" - return self.__idxsh_e - - @property - def Jsh_e(self): - """:math:`J_{s,h}^e` - matrix coefficient for soft bounds on nonlinear constraints at terminal shooting node N; fills :py:attr:`idxsh_e`""" - print_J_to_idx_note() - return self.__idxsh_e - - # soft bounds on convex-over-nonlinear constraints at shooting node N - @property - def lsphi_e(self): - """Lower bounds on slacks corresponding to soft lower bounds for convex-over-nonlinear constraints at terminal shooting node N. - Not required - zeros by default""" - return self.__lsphi_e - - @property - def usphi_e(self): - """Lower bounds on slacks corresponding to soft upper bounds for convex-over-nonlinear constraints at terminal shooting node N. - Not required - zeros by default""" - return self.__usphi_e - - @property - def idxsphi_e(self): - """Indices of soft nonlinear constraints at shooting node N within the indices of nonlinear constraints at terminal shooting node N. - Can be set by using :py:attr:`Jsphi_e`. - Type: :code:`np.ndarray`; default: :code:`np.array([])`""" - return self.__idxsphi_e - - @property - def Jsphi_e(self): - """:math:`J_{sh}^e` - matrix coefficient for soft bounds on convex-over-nonlinear constraints at shooting node N. - Translated internally to :py:attr:`idxsphi_e`""" - print_J_to_idx_note() - return self.__idxsphi_e - - @property - def x0(self): - """:math:`x_0 \\in \mathbb{R}^{n_x}` - initial state -- - Translated internally to :py:attr:`idxbx_0`, :py:attr:`lbx_0`, :py:attr:`ubx_0`, :py:attr:`idxbxe_0` """ - print("x0 is converted to lbx_0, ubx_0, idxbx_0") - print("idxbx_0: ", self.__idxbx_0) - print("lbx_0: ", self.__lbx_0) - print("ubx_0: ", self.__ubx_0) - print("idxbxe_0: ", self.__idxbxe_0) - return None - - # SETTERS - @constr_type.setter - def constr_type(self, constr_type): - constr_types = ('BGH', 'BGP') - if constr_type in constr_types: - self.__constr_type = constr_type - else: - raise Exception('Invalid constr_type value. Possible values are:\n\n' \ - + ',\n'.join(constr_types) + '.\n\nYou have: ' + constr_type + '.\n\n') - - @constr_type_e.setter - def constr_type_e(self, constr_type_e): - constr_types = ('BGH', 'BGP') - if constr_type_e in constr_types: - self.__constr_type_e = constr_type_e - else: - raise Exception('Invalid constr_type_e value. Possible values are:\n\n' \ - + ',\n'.join(constr_types) + '.\n\nYou have: ' + constr_type_e + '.\n\n') - - # initial x - @lbx_0.setter - def lbx_0(self, lbx_0): - if isinstance(lbx_0, np.ndarray): - self.__lbx_0 = lbx_0 - else: - raise Exception('Invalid lbx_0 value.') - - @ubx_0.setter - def ubx_0(self, ubx_0): - if isinstance(ubx_0, np.ndarray): - self.__ubx_0 = ubx_0 - else: - raise Exception('Invalid ubx_0 value.') - - @idxbx_0.setter - def idxbx_0(self, idxbx_0): - if isinstance(idxbx_0, np.ndarray): - self.__idxbx_0 = idxbx_0 - else: - raise Exception('Invalid idxbx_0 value.') - - @Jbx_0.setter - def Jbx_0(self, Jbx_0): - if isinstance(Jbx_0, np.ndarray): - self.__idxbx_0 = J_to_idx(Jbx_0) - else: - raise Exception('Invalid Jbx_0 value.') - - @idxbxe_0.setter - def idxbxe_0(self, idxbxe_0): - if isinstance(idxbxe_0, np.ndarray): - self.__idxbxe_0 = idxbxe_0 - else: - raise Exception('Invalid idxbxe_0 value.') - - - @x0.setter - def x0(self, x0): - if isinstance(x0, np.ndarray): - self.__lbx_0 = x0 - self.__ubx_0 = x0 - self.__idxbx_0 = np.arange(x0.size) - self.__idxbxe_0 = np.arange(x0.size) - else: - raise Exception('Invalid x0 value.') - - # bounds on x - @lbx.setter - def lbx(self, lbx): - if isinstance(lbx, np.ndarray): - self.__lbx = lbx - else: - raise Exception('Invalid lbx value.') - - @ubx.setter - def ubx(self, ubx): - if isinstance(ubx, np.ndarray): - self.__ubx = ubx - else: - raise Exception('Invalid ubx value.') - - @idxbx.setter - def idxbx(self, idxbx): - if isinstance(idxbx, np.ndarray): - self.__idxbx = idxbx - else: - raise Exception('Invalid idxbx value.') - - @Jbx.setter - def Jbx(self, Jbx): - if isinstance(Jbx, np.ndarray): - self.__idxbx = J_to_idx(Jbx) - else: - raise Exception('Invalid Jbx value.') - - # bounds on u - @lbu.setter - def lbu(self, lbu): - if isinstance(lbu, np.ndarray): - self.__lbu = lbu - else: - raise Exception('Invalid lbu value.') - - @ubu.setter - def ubu(self, ubu): - if isinstance(ubu, np.ndarray): - self.__ubu = ubu - else: - raise Exception('Invalid ubu value.') - - @idxbu.setter - def idxbu(self, idxbu): - if isinstance(idxbu, np.ndarray): - self.__idxbu = idxbu - else: - raise Exception('Invalid idxbu value.') - - @Jbu.setter - def Jbu(self, Jbu): - if isinstance(Jbu, np.ndarray): - self.__idxbu = J_to_idx(Jbu) - else: - raise Exception('Invalid Jbu value.') - - # bounds on x at shooting node N - @lbx_e.setter - def lbx_e(self, lbx_e): - if isinstance(lbx_e, np.ndarray): - self.__lbx_e = lbx_e - else: - raise Exception('Invalid lbx_e value.') - - @ubx_e.setter - def ubx_e(self, ubx_e): - if isinstance(ubx_e, np.ndarray): - self.__ubx_e = ubx_e - else: - raise Exception('Invalid ubx_e value.') - - @idxbx_e.setter - def idxbx_e(self, idxbx_e): - if isinstance(idxbx_e, np.ndarray): - self.__idxbx_e = idxbx_e - else: - raise Exception('Invalid idxbx_e value.') - - @Jbx_e.setter - def Jbx_e(self, Jbx_e): - if isinstance(Jbx_e, np.ndarray): - self.__idxbx_e = J_to_idx(Jbx_e) - else: - raise Exception('Invalid Jbx_e value.') - - # polytopic constraints - @D.setter - def D(self, D): - if isinstance(D, np.ndarray) and len(D.shape) == 2: - self.__D = D - else: - raise Exception('Invalid constraint D value.' \ - + 'Should be 2 dimensional numpy array.') - - @C.setter - def C(self, C): - if isinstance(C, np.ndarray) and len(C.shape) == 2: - self.__C = C - else: - raise Exception('Invalid constraint C value.' \ - + 'Should be 2 dimensional numpy array.') - - @lg.setter - def lg(self, lg): - if isinstance(lg, np.ndarray): - self.__lg = lg - else: - raise Exception('Invalid lg value.') - - @ug.setter - def ug(self, ug): - if isinstance(ug, np.ndarray): - self.__ug = ug - else: - raise Exception('Invalid ug value.') - - # polytopic constraints at shooting node N - @C_e.setter - def C_e(self, C_e): - if isinstance(C_e, np.ndarray) and len(C_e.shape) == 2: - self.__C_e = C_e - else: - raise Exception('Invalid constraint C_e value.' \ - + 'Should be 2 dimensional numpy array.') - - @lg_e.setter - def lg_e(self, lg_e): - if isinstance(lg_e, np.ndarray): - self.__lg_e = lg_e - else: - raise Exception('Invalid lg_e value.') - - @ug_e.setter - def ug_e(self, ug_e): - if isinstance(ug_e, np.ndarray): - self.__ug_e = ug_e - else: - raise Exception('Invalid ug_e value.') - - # nonlinear constraints - @lh.setter - def lh(self, lh): - if isinstance(lh, np.ndarray): - self.__lh = lh - else: - raise Exception('Invalid lh value.') - - @uh.setter - def uh(self, uh): - if isinstance(uh, np.ndarray): - self.__uh = uh - else: - raise Exception('Invalid uh value.') - - # convex-over-nonlinear constraints - @lphi.setter - def lphi(self, lphi): - if isinstance(lphi, np.ndarray): - self.__lphi = lphi - else: - raise Exception('Invalid lphi value.') - - @uphi.setter - def uphi(self, uphi): - if isinstance(uphi, np.ndarray): - self.__uphi = uphi - else: - raise Exception('Invalid uphi value.') - - # nonlinear constraints at shooting node N - @lh_e.setter - def lh_e(self, lh_e): - if isinstance(lh_e, np.ndarray): - self.__lh_e = lh_e - else: - raise Exception('Invalid lh_e value.') - - @uh_e.setter - def uh_e(self, uh_e): - if isinstance(uh_e, np.ndarray): - self.__uh_e = uh_e - else: - raise Exception('Invalid uh_e value.') - - # convex-over-nonlinear constraints at shooting node N - @lphi_e.setter - def lphi_e(self, lphi_e): - if isinstance(lphi_e, np.ndarray): - self.__lphi_e = lphi_e - else: - raise Exception('Invalid lphi_e value.') - - @uphi_e.setter - def uphi_e(self, uphi_e): - if isinstance(uphi_e, np.ndarray): - self.__uphi_e = uphi_e - else: - raise Exception('Invalid uphi_e value.') - - # SLACK bounds - # soft bounds on x - @lsbx.setter - def lsbx(self, lsbx): - if isinstance(lsbx, np.ndarray): - self.__lsbx = lsbx - else: - raise Exception('Invalid lsbx value.') - - @usbx.setter - def usbx(self, usbx): - if isinstance(usbx, np.ndarray): - self.__usbx = usbx - else: - raise Exception('Invalid usbx value.') - - @idxsbx.setter - def idxsbx(self, idxsbx): - if isinstance(idxsbx, np.ndarray): - self.__idxsbx = idxsbx - else: - raise Exception('Invalid idxsbx value.') - - @Jsbx.setter - def Jsbx(self, Jsbx): - if isinstance(Jsbx, np.ndarray): - self.__idxsbx = J_to_idx_slack(Jsbx) - else: - raise Exception('Invalid Jsbx value, expected numpy array.') - - # soft bounds on u - @lsbu.setter - def lsbu(self, lsbu): - if isinstance(lsbu, np.ndarray): - self.__lsbu = lsbu - else: - raise Exception('Invalid lsbu value.') - - @usbu.setter - def usbu(self, usbu): - if isinstance(usbu, np.ndarray): - self.__usbu = usbu - else: - raise Exception('Invalid usbu value.') - - @idxsbu.setter - def idxsbu(self, idxsbu): - if isinstance(idxsbu, np.ndarray): - self.__idxsbu = idxsbu - else: - raise Exception('Invalid idxsbu value.') - - @Jsbu.setter - def Jsbu(self, Jsbu): - if isinstance(Jsbu, np.ndarray): - self.__idxsbu = J_to_idx_slack(Jsbu) - else: - raise Exception('Invalid Jsbu value.') - - # soft bounds on x at shooting node N - @lsbx_e.setter - def lsbx_e(self, lsbx_e): - if isinstance(lsbx_e, np.ndarray): - self.__lsbx_e = lsbx_e - else: - raise Exception('Invalid lsbx_e value.') - - @usbx_e.setter - def usbx_e(self, usbx_e): - if isinstance(usbx_e, np.ndarray): - self.__usbx_e = usbx_e - else: - raise Exception('Invalid usbx_e value.') - - @idxsbx_e.setter - def idxsbx_e(self, idxsbx_e): - if isinstance(idxsbx_e, np.ndarray): - self.__idxsbx_e = idxsbx_e - else: - raise Exception('Invalid idxsbx_e value.') - - @Jsbx_e.setter - def Jsbx_e(self, Jsbx_e): - if isinstance(Jsbx_e, np.ndarray): - self.__idxsbx_e = J_to_idx_slack(Jsbx_e) - else: - raise Exception('Invalid Jsbx_e value.') - - - # soft bounds on general linear constraints - @lsg.setter - def lsg(self, lsg): - if isinstance(lsg, np.ndarray): - self.__lsg = lsg - else: - raise Exception('Invalid lsg value.') - - @usg.setter - def usg(self, usg): - if isinstance(usg, np.ndarray): - self.__usg = usg - else: - raise Exception('Invalid usg value.') - - @idxsg.setter - def idxsg(self, idxsg): - if isinstance(idxsg, np.ndarray): - self.__idxsg = idxsg - else: - raise Exception('Invalid idxsg value.') - - @Jsg.setter - def Jsg(self, Jsg): - if isinstance(Jsg, np.ndarray): - self.__idxsg = J_to_idx_slack(Jsg) - else: - raise Exception('Invalid Jsg value, expected numpy array.') - - - # soft bounds on nonlinear constraints - @lsh.setter - def lsh(self, lsh): - if isinstance(lsh, np.ndarray): - self.__lsh = lsh - else: - raise Exception('Invalid lsh value.') - - @ush.setter - def ush(self, ush): - if isinstance(ush, np.ndarray): - self.__ush = ush - else: - raise Exception('Invalid ush value.') - - @idxsh.setter - def idxsh(self, idxsh): - if isinstance(idxsh, np.ndarray): - self.__idxsh = idxsh - else: - raise Exception('Invalid idxsh value.') - - - @Jsh.setter - def Jsh(self, Jsh): - if isinstance(Jsh, np.ndarray): - self.__idxsh = J_to_idx_slack(Jsh) - else: - raise Exception('Invalid Jsh value, expected numpy array.') - - # soft bounds on convex-over-nonlinear constraints - @lsphi.setter - def lsphi(self, lsphi): - if isinstance(lsphi, np.ndarray): - self.__lsphi = lsphi - else: - raise Exception('Invalid lsphi value.') - - @usphi.setter - def usphi(self, usphi): - if isinstance(usphi, np.ndarray): - self.__usphi = usphi - else: - raise Exception('Invalid usphi value.') - - @idxsphi.setter - def idxsphi(self, idxsphi): - if isinstance(idxsphi, np.ndarray): - self.__idxsphi = idxsphi - else: - raise Exception('Invalid idxsphi value.') - - @Jsphi.setter - def Jsphi(self, Jsphi): - if isinstance(Jsphi, np.ndarray): - self.__idxsphi = J_to_idx_slack(Jsphi) - else: - raise Exception('Invalid Jsphi value, expected numpy array.') - - # soft bounds on general linear constraints at shooting node N - @lsg_e.setter - def lsg_e(self, lsg_e): - if isinstance(lsg_e, np.ndarray): - self.__lsg_e = lsg_e - else: - raise Exception('Invalid lsg_e value.') - - @usg_e.setter - def usg_e(self, usg_e): - if isinstance(usg_e, np.ndarray): - self.__usg_e = usg_e - else: - raise Exception('Invalid usg_e value.') - - @idxsg_e.setter - def idxsg_e(self, idxsg_e): - if isinstance(idxsg_e, np.ndarray): - self.__idxsg_e = idxsg_e - else: - raise Exception('Invalid idxsg_e value.') - - @Jsg_e.setter - def Jsg_e(self, Jsg_e): - if isinstance(Jsg_e, np.ndarray): - self.__idxsg_e = J_to_idx_slack(Jsg_e) - else: - raise Exception('Invalid Jsg_e value, expected numpy array.') - - # soft bounds on nonlinear constraints at shooting node N - @lsh_e.setter - def lsh_e(self, lsh_e): - if isinstance(lsh_e, np.ndarray): - self.__lsh_e = lsh_e - else: - raise Exception('Invalid lsh_e value.') - - @ush_e.setter - def ush_e(self, ush_e): - if isinstance(ush_e, np.ndarray): - self.__ush_e = ush_e - else: - raise Exception('Invalid ush_e value.') - - @idxsh_e.setter - def idxsh_e(self, idxsh_e): - if isinstance(idxsh_e, np.ndarray): - self.__idxsh_e = idxsh_e - else: - raise Exception('Invalid idxsh_e value.') - - @Jsh_e.setter - def Jsh_e(self, Jsh_e): - if isinstance(Jsh_e, np.ndarray): - self.__idxsh_e = J_to_idx_slack(Jsh_e) - else: - raise Exception('Invalid Jsh_e value, expected numpy array.') - - - # soft bounds on convex-over-nonlinear constraints at shooting node N - @lsphi_e.setter - def lsphi_e(self, lsphi_e): - if isinstance(lsphi_e, np.ndarray): - self.__lsphi_e = lsphi_e - else: - raise Exception('Invalid lsphi_e value.') - - @usphi_e.setter - def usphi_e(self, usphi_e): - if isinstance(usphi_e, np.ndarray): - self.__usphi_e = usphi_e - else: - raise Exception('Invalid usphi_e value.') - - @idxsphi_e.setter - def idxsphi_e(self, idxsphi_e): - if isinstance(idxsphi_e, np.ndarray): - self.__idxsphi_e = idxsphi_e - else: - raise Exception('Invalid idxsphi_e value.') - - @Jsphi_e.setter - def Jsphi_e(self, Jsphi_e): - if isinstance(Jsphi_e, np.ndarray): - self.__idxsphi_e = J_to_idx_slack(Jsphi_e) - else: - raise Exception('Invalid Jsphi_e value.') - - def set(self, attr, value): - setattr(self, attr, value) - - -class AcadosOcpOptions: - """ - class containing the description of the solver options - """ - def __init__(self): - self.__qp_solver = 'PARTIAL_CONDENSING_HPIPM' # qp solver to be used in the NLP solver - self.__hessian_approx = 'GAUSS_NEWTON' # hessian approximation - self.__integrator_type = 'ERK' # integrator type - self.__tf = None # prediction horizon - self.__nlp_solver_type = 'SQP_RTI' # NLP solver - self.__globalization = 'FIXED_STEP' - self.__nlp_solver_step_length = 1.0 # fixed Newton step length - self.__levenberg_marquardt = 0.0 - self.__collocation_type = 'GAUSS_LEGENDRE' - self.__sim_method_num_stages = 4 # number of stages in the integrator - self.__sim_method_num_steps = 1 # number of steps in the integrator - self.__sim_method_newton_iter = 3 # number of Newton iterations in simulation method - self.__sim_method_newton_tol = 0.0 - self.__sim_method_jac_reuse = 0 - self.__qp_solver_tol_stat = None # QP solver stationarity tolerance - self.__qp_solver_tol_eq = None # QP solver equality tolerance - self.__qp_solver_tol_ineq = None # QP solver inequality - self.__qp_solver_tol_comp = None # QP solver complementarity - self.__qp_solver_iter_max = 50 # QP solver max iter - self.__qp_solver_cond_N = None # QP solver: new horizon after partial condensing - self.__qp_solver_warm_start = 0 - self.__qp_solver_cond_ric_alg = 1 - self.__qp_solver_ric_alg = 1 - self.__nlp_solver_tol_stat = 1e-6 # NLP solver stationarity tolerance - self.__nlp_solver_tol_eq = 1e-6 # NLP solver equality tolerance - self.__nlp_solver_tol_ineq = 1e-6 # NLP solver inequality - self.__nlp_solver_tol_comp = 1e-6 # NLP solver complementarity - self.__nlp_solver_max_iter = 100 # NLP solver maximum number of iterations - self.__nlp_solver_ext_qp_res = 0 - self.__Tsim = None # automatically calculated as tf/N - self.__print_level = 0 # print level - self.__initialize_t_slacks = 0 # possible values: 0, 1 - self.__regularize_method = None - self.__time_steps = None - self.__shooting_nodes = None - self.__exact_hess_cost = 1 - self.__exact_hess_dyn = 1 - self.__exact_hess_constr = 1 - self.__ext_cost_num_hess = 0 - self.__alpha_min = 0.05 - self.__alpha_reduction = 0.7 - self.__line_search_use_sufficient_descent = 0 - self.__globalization_use_SOC = 0 - self.__full_step_dual = 0 - self.__eps_sufficient_descent = 1e-4 - self.__hpipm_mode = 'BALANCE' - # TODO: move those out? they are more about generation than about the acados OCP solver. - self.__ext_fun_compile_flags = '-O2' - self.__model_external_shared_lib_dir = None # path to the the .so lib - self.__model_external_shared_lib_name = None # name of the the .so lib - self.__custom_update_filename = '' - self.__custom_update_header_filename = '' - self.__custom_templates = [] - self.__custom_update_copy = True - - @property - def qp_solver(self): - """QP solver to be used in the NLP solver. - String in ('PARTIAL_CONDENSING_HPIPM', 'FULL_CONDENSING_QPOASES', 'FULL_CONDENSING_HPIPM', 'PARTIAL_CONDENSING_QPDUNES', 'PARTIAL_CONDENSING_OSQP', 'FULL_CONDENSING_DAQP'). - Default: 'PARTIAL_CONDENSING_HPIPM'. - """ - return self.__qp_solver - - @property - def ext_fun_compile_flags(self): - """ - String with compiler flags for external function compilation. - Default: '-O2'. - """ - return self.__ext_fun_compile_flags - - - @property - def custom_update_filename(self): - """ - Filename of the custom C function to update solver data and parameters in between solver calls - - This file has to implement the functions - int custom_update_init_function([model.name]_solver_capsule* capsule); - int custom_update_function([model.name]_solver_capsule* capsule); - int custom_update_terminate_function([model.name]_solver_capsule* capsule); - - - Default: ''. - """ - return self.__custom_update_filename - - - @property - def custom_templates(self): - """ - List of tuples of the form: - (input_filename, output_filename) - - Custom templates are render in OCP solver generation. - - Default: []. - """ - return self.__custom_templates - - - @property - def custom_update_header_filename(self): - """ - Header filename of the custom C function to update solver data and parameters in between solver calls - - This file has to declare the custom_update functions and look as follows: - - ``` - // Called at the end of solver creation. - // This is allowed to allocate memory and store the pointer to it into capsule->custom_update_memory. - int custom_update_init_function([model.name]_solver_capsule* capsule); - - // Custom update function that can be called between solver calls - int custom_update_function([model.name]_solver_capsule* capsule, double* data, int data_len); - - // Called just before destroying the solver. - // Responsible to free allocated memory, stored at capsule->custom_update_memory. - int custom_update_terminate_function([model.name]_solver_capsule* capsule); - - Default: ''. - """ - return self.__custom_update_header_filename - - @property - def custom_update_copy(self): - """ - Boolean; - If True, the custom update function files are copied into the `code_export_directory`. - """ - return self.__custom_update_copy - - - @property - def hpipm_mode(self): - """ - Mode of HPIPM to be used, - - String in ('BALANCE', 'SPEED_ABS', 'SPEED', 'ROBUST'). - - Default: 'BALANCE'. - - see https://cdn.syscop.de/publications/Frison2020a.pdf - and the HPIPM code: - https://github.com/giaf/hpipm/blob/master/ocp_qp/x_ocp_qp_ipm.c#L69 - """ - return self.__hpipm_mode - - @property - def hessian_approx(self): - """Hessian approximation. - String in ('GAUSS_NEWTON', 'EXACT'). - Default: 'GAUSS_NEWTON'. - """ - return self.__hessian_approx - - @property - def integrator_type(self): - """ - Integrator type. - String in ('ERK', 'IRK', 'GNSF', 'DISCRETE', 'LIFTED_IRK'). - Default: 'ERK'. - """ - return self.__integrator_type - - @property - def nlp_solver_type(self): - """NLP solver. - String in ('SQP', 'SQP_RTI'). - Default: 'SQP_RTI'. - """ - return self.__nlp_solver_type - - @property - def globalization(self): - """Globalization type. - String in ('FIXED_STEP', 'MERIT_BACKTRACKING'). - Default: 'FIXED_STEP'. - - .. note:: preliminary implementation. - """ - return self.__globalization - - @property - def collocation_type(self): - """Collocation type: relevant for implicit integrators - -- string in {GAUSS_RADAU_IIA, GAUSS_LEGENDRE}. - - Default: GAUSS_LEGENDRE - """ - return self.__collocation_type - - @property - def regularize_method(self): - """Regularization method for the Hessian. - String in ('NO_REGULARIZE', 'MIRROR', 'PROJECT', 'PROJECT_REDUC_HESS', 'CONVEXIFY') or :code:`None`. - - - MIRROR: performs eigenvalue decomposition H = V^T D V and sets D_ii = max(eps, abs(D_ii)) - - PROJECT: performs eigenvalue decomposition H = V^T D V and sets D_ii = max(eps, D_ii) - - CONVEXIFY: Algorithm 6 from Verschueren2017, https://cdn.syscop.de/publications/Verschueren2017.pdf - - PROJECT_REDUC_HESS: experimental - - Note: default eps = 1e-4 - - Default: :code:`None`. - """ - return self.__regularize_method - - @property - def nlp_solver_step_length(self): - """ - Fixed Newton step length. - Type: float > 0. - Default: 1.0. - """ - return self.__nlp_solver_step_length - - @property - def levenberg_marquardt(self): - """ - Factor for LM regularization. - Type: float >= 0 - Default: 0.0. - """ - return self.__levenberg_marquardt - - @property - def sim_method_num_stages(self): - """ - Number of stages in the integrator. - Type: int > 0 or ndarray of ints > 0 of shape (N,). - Default: 4 - """ - return self.__sim_method_num_stages - - @property - def sim_method_num_steps(self): - """ - Number of steps in the integrator. - Type: int > 0 or ndarray of ints > 0 of shape (N,). - Default: 1 - """ - return self.__sim_method_num_steps - - @property - def sim_method_newton_iter(self): - """ - Number of Newton iterations in simulation method. - Type: int > 0 - Default: 3 - """ - return self.__sim_method_newton_iter - - @property - def sim_method_newton_tol(self): - """ - Tolerance of Newton system in simulation method. - Type: float: 0.0 means not used - Default: 0.0 - """ - return self.__sim_method_newton_tol - - @property - def sim_method_jac_reuse(self): - """ - Integer determining if jacobians are reused within integrator or ndarray of ints > 0 of shape (N,). - 0: False (no reuse); 1: True (reuse) - Default: 0 - """ - return self.__sim_method_jac_reuse - - @property - def qp_solver_tol_stat(self): - """ - QP solver stationarity tolerance. - Default: :code:`None` - """ - return self.__qp_solver_tol_stat - - @property - def qp_solver_tol_eq(self): - """ - QP solver equality tolerance. - Default: :code:`None` - """ - return self.__qp_solver_tol_eq - - @property - def qp_solver_tol_ineq(self): - """ - QP solver inequality. - Default: :code:`None` - """ - return self.__qp_solver_tol_ineq - - @property - def qp_solver_tol_comp(self): - """ - QP solver complementarity. - Default: :code:`None` - """ - return self.__qp_solver_tol_comp - - @property - def qp_solver_cond_N(self): - """QP solver: New horizon after partial condensing. - Set to N by default -> no condensing.""" - return self.__qp_solver_cond_N - - @property - def qp_solver_warm_start(self): - """ - QP solver: Warm starting. - 0: no warm start; 1: warm start; 2: hot start. - Default: 0 - """ - return self.__qp_solver_warm_start - - @property - def qp_solver_cond_ric_alg(self): - """ - QP solver: Determines which algorithm is used in HPIPM condensing. - 0: dont factorize hessian in the condensing; 1: factorize. - Default: 1 - """ - return self.__qp_solver_cond_ric_alg - - @property - def qp_solver_ric_alg(self): - """ - QP solver: Determines which algorithm is used in HPIPM OCP QP solver. - 0 classical Riccati, 1 square-root Riccati. - - Note: taken from [HPIPM paper]: - - (a) the classical implementation requires the reduced Hessian with respect to the dynamics - equality constraints to be positive definite, but allows the full-space Hessian to be indefinite) - (b) the square-root implementation, which in order to reduce the flop count employs the Cholesky - factorization of the Riccati recursion matrix, and therefore requires the full-space Hessian to be positive definite - - [HPIPM paper]: HPIPM: a high-performance quadratic programming framework for model predictive control, Frison and Diehl, 2020 - https://cdn.syscop.de/publications/Frison2020a.pdf - - Default: 1 - """ - return self.__qp_solver_ric_alg - - @property - def qp_solver_iter_max(self): - """ - QP solver: maximum number of iterations. - Type: int > 0 - Default: 50 - """ - return self.__qp_solver_iter_max - - @property - def tol(self): - """ - NLP solver tolerance. Sets or gets the max of :py:attr:`nlp_solver_tol_eq`, - :py:attr:`nlp_solver_tol_ineq`, :py:attr:`nlp_solver_tol_comp` - and :py:attr:`nlp_solver_tol_stat`. - """ - return max([self.__nlp_solver_tol_eq, self.__nlp_solver_tol_ineq,\ - self.__nlp_solver_tol_comp, self.__nlp_solver_tol_stat]) - - @property - def qp_tol(self): - """ - QP solver tolerance. - Sets all of the following at once or gets the max of - :py:attr:`qp_solver_tol_eq`, :py:attr:`qp_solver_tol_ineq`, - :py:attr:`qp_solver_tol_comp` and - :py:attr:`qp_solver_tol_stat`. - """ - return max([self.__qp_solver_tol_eq, self.__qp_solver_tol_ineq,\ - self.__qp_solver_tol_comp, self.__qp_solver_tol_stat]) - - @property - def nlp_solver_tol_stat(self): - """ - NLP solver stationarity tolerance. - Type: float > 0 - Default: 1e-6 - """ - return self.__nlp_solver_tol_stat - - @property - def nlp_solver_tol_eq(self): - """NLP solver equality tolerance""" - return self.__nlp_solver_tol_eq - - @property - def alpha_min(self): - """Minimal step size for globalization MERIT_BACKTRACKING, default: 0.05.""" - return self.__alpha_min - - @property - def alpha_reduction(self): - """Step size reduction factor for globalization MERIT_BACKTRACKING, default: 0.7.""" - return self.__alpha_reduction - - @property - def line_search_use_sufficient_descent(self): - """ - Determines if sufficient descent (Armijo) condition is used in line search. - Type: int; 0 or 1; - default: 0. - """ - return self.__line_search_use_sufficient_descent - - @property - def eps_sufficient_descent(self): - """ - Factor for sufficient descent (Armijo) conditon, see line_search_use_sufficient_descent. - Type: float, - default: 1e-4. - """ - return self.__eps_sufficient_descent - - @property - def globalization_use_SOC(self): - """ - Determines if second order correction (SOC) is done when using MERIT_BACKTRACKING. - SOC is done if preliminary line search does not return full step. - Type: int; 0 or 1; - default: 0. - """ - return self.__globalization_use_SOC - - @property - def full_step_dual(self): - """ - Determines if dual variables are updated with full steps (alpha=1.0) when primal variables are updated with smaller step. - Type: int; 0 or 1; - default: 0. - """ - return self.__full_step_dual - - @property - def nlp_solver_tol_ineq(self): - """NLP solver inequality tolerance""" - return self.__nlp_solver_tol_ineq - - @property - def nlp_solver_ext_qp_res(self): - """Determines if residuals of QP are computed externally within NLP solver (for debugging) - - Type: int; 0 or 1; - Default: 0. - """ - return self.__nlp_solver_ext_qp_res - - @property - def nlp_solver_tol_comp(self): - """NLP solver complementarity tolerance""" - return self.__nlp_solver_tol_comp - - @property - def nlp_solver_max_iter(self): - """ - NLP solver maximum number of iterations. - Type: int > 0 - Default: 100 - """ - return self.__nlp_solver_max_iter - - @property - def time_steps(self): - """ - Vector with time steps between the shooting nodes. Set automatically to uniform discretization if :py:attr:`N` and :py:attr:`tf` are provided. - Default: :code:`None` - """ - return self.__time_steps - - @property - def shooting_nodes(self): - """ - Vector with the shooting nodes, time_steps will be computed from it automatically. - Default: :code:`None` - """ - return self.__shooting_nodes - - @property - def tf(self): - """ - Prediction horizon - Type: float > 0 - Default: :code:`None` - """ - return self.__tf - - @property - def Tsim(self): - """ - Time horizon for one integrator step. Automatically calculated as :py:attr:`tf`/:py:attr:`N`. - Default: :code:`None` - """ - return self.__Tsim - - @property - def print_level(self): - """ - Verbosity of printing. - Type: int >= 0 - Default: 0 - """ - return self.__print_level - - @property - def model_external_shared_lib_dir(self): - """Path to the .so lib""" - return self.__model_external_shared_lib_dir - - @property - def model_external_shared_lib_name(self): - """Name of the .so lib""" - return self.__model_external_shared_lib_name - - @property - def exact_hess_constr(self): - """ - Used in case of hessian_approx == 'EXACT'.\n - Can be used to turn off exact hessian contributions from the constraints module. - """ - return self.__exact_hess_constr - - @property - def exact_hess_cost(self): - """ - Used in case of hessian_approx == 'EXACT'.\n - Can be used to turn off exact hessian contributions from the cost module. - """ - return self.__exact_hess_cost - - @property - def exact_hess_dyn(self): - """ - Used in case of hessian_approx == 'EXACT'.\n - Can be used to turn off exact hessian contributions from the dynamics module. - """ - return self.__exact_hess_dyn - - @property - def ext_cost_num_hess(self): - """ - Determines if custom hessian approximation for cost contribution is used (> 0).\n - Or if hessian contribution is evaluated exactly using CasADi external function (=0 - default). - """ - return self.__ext_cost_num_hess - - @qp_solver.setter - def qp_solver(self, qp_solver): - qp_solvers = ('PARTIAL_CONDENSING_HPIPM', \ - 'FULL_CONDENSING_QPOASES', 'FULL_CONDENSING_HPIPM', \ - 'PARTIAL_CONDENSING_QPDUNES', 'PARTIAL_CONDENSING_OSQP', \ - 'FULL_CONDENSING_DAQP') - if qp_solver in qp_solvers: - self.__qp_solver = qp_solver - else: - raise Exception('Invalid qp_solver value. Possible values are:\n\n' \ - + ',\n'.join(qp_solvers) + '.\n\nYou have: ' + qp_solver + '.\n\n') - - @regularize_method.setter - def regularize_method(self, regularize_method): - regularize_methods = ('NO_REGULARIZE', 'MIRROR', 'PROJECT', \ - 'PROJECT_REDUC_HESS', 'CONVEXIFY') - if regularize_method in regularize_methods: - self.__regularize_method = regularize_method - else: - raise Exception('Invalid regularize_method value. Possible values are:\n\n' \ - + ',\n'.join(regularize_methods) + '.\n\nYou have: ' + regularize_method + '.\n\n') - - @collocation_type.setter - def collocation_type(self, collocation_type): - collocation_types = ('GAUSS_RADAU_IIA', 'GAUSS_LEGENDRE') - if collocation_type in collocation_types: - self.__collocation_type = collocation_type - else: - raise Exception('Invalid collocation_type value. Possible values are:\n\n' \ - + ',\n'.join(collocation_types) + '.\n\nYou have: ' + collocation_type + '.\n\n') - - @hpipm_mode.setter - def hpipm_mode(self, hpipm_mode): - hpipm_modes = ('BALANCE', 'SPEED_ABS', 'SPEED', 'ROBUST') - if hpipm_mode in hpipm_modes: - self.__hpipm_mode = hpipm_mode - else: - raise Exception('Invalid hpipm_mode value. Possible values are:\n\n' \ - + ',\n'.join(hpipm_modes) + '.\n\nYou have: ' + hpipm_mode + '.\n\n') - - @ext_fun_compile_flags.setter - def ext_fun_compile_flags(self, ext_fun_compile_flags): - if isinstance(ext_fun_compile_flags, str): - self.__ext_fun_compile_flags = ext_fun_compile_flags - else: - raise Exception('Invalid ext_fun_compile_flags, expected a string.\n') - - - @custom_update_filename.setter - def custom_update_filename(self, custom_update_filename): - if isinstance(custom_update_filename, str): - self.__custom_update_filename = custom_update_filename - else: - raise Exception('Invalid custom_update_filename, expected a string.\n') - - @custom_templates.setter - def custom_templates(self, custom_templates): - if not isinstance(custom_templates, list): - raise Exception('Invalid custom_templates, expected a list.\n') - for tup in custom_templates: - if not isinstance(tup, tuple): - raise Exception('Invalid custom_templates, shoubld be list of tuples.\n') - for s in tup: - if not isinstance(s, str): - raise Exception('Invalid custom_templates, shoubld be list of tuples of strings.\n') - self.__custom_templates = custom_templates - - @custom_update_header_filename.setter - def custom_update_header_filename(self, custom_update_header_filename): - if isinstance(custom_update_header_filename, str): - self.__custom_update_header_filename = custom_update_header_filename - else: - raise Exception('Invalid custom_update_header_filename, expected a string.\n') - - @custom_update_copy.setter - def custom_update_copy(self, custom_update_copy): - if isinstance(custom_update_copy, bool): - self.__custom_update_copy = custom_update_copy - else: - raise Exception('Invalid custom_update_copy, expected a bool.\n') - - @hessian_approx.setter - def hessian_approx(self, hessian_approx): - hessian_approxs = ('GAUSS_NEWTON', 'EXACT') - if hessian_approx in hessian_approxs: - self.__hessian_approx = hessian_approx - else: - raise Exception('Invalid hessian_approx value. Possible values are:\n\n' \ - + ',\n'.join(hessian_approxs) + '.\n\nYou have: ' + hessian_approx + '.\n\n') - - @integrator_type.setter - def integrator_type(self, integrator_type): - integrator_types = ('ERK', 'IRK', 'GNSF', 'DISCRETE', 'LIFTED_IRK') - if integrator_type in integrator_types: - self.__integrator_type = integrator_type - else: - raise Exception('Invalid integrator_type value. Possible values are:\n\n' \ - + ',\n'.join(integrator_types) + '.\n\nYou have: ' + integrator_type + '.\n\n') - - @tf.setter - def tf(self, tf): - self.__tf = tf - - @time_steps.setter - def time_steps(self, time_steps): - if isinstance(time_steps, np.ndarray): - if len(time_steps.shape) == 1: - self.__time_steps = time_steps - else: - raise Exception('Invalid time_steps, expected np.ndarray of shape (N,).') - else: - raise Exception('Invalid time_steps, expected np.ndarray.') - - @shooting_nodes.setter - def shooting_nodes(self, shooting_nodes): - if isinstance(shooting_nodes, np.ndarray): - if len(shooting_nodes.shape) == 1: - self.__shooting_nodes = shooting_nodes - else: - raise Exception('Invalid shooting_nodes, expected np.ndarray of shape (N+1,).') - else: - raise Exception('Invalid shooting_nodes, expected np.ndarray.') - - @Tsim.setter - def Tsim(self, Tsim): - self.__Tsim = Tsim - - @globalization.setter - def globalization(self, globalization): - globalization_types = ('MERIT_BACKTRACKING', 'FIXED_STEP') - if globalization in globalization_types: - self.__globalization = globalization - else: - raise Exception('Invalid globalization value. Possible values are:\n\n' \ - + ',\n'.join(globalization_types) + '.\n\nYou have: ' + globalization + '.\n\n') - - @alpha_min.setter - def alpha_min(self, alpha_min): - self.__alpha_min = alpha_min - - @alpha_reduction.setter - def alpha_reduction(self, alpha_reduction): - self.__alpha_reduction = alpha_reduction - - @line_search_use_sufficient_descent.setter - def line_search_use_sufficient_descent(self, line_search_use_sufficient_descent): - if line_search_use_sufficient_descent in [0, 1]: - self.__line_search_use_sufficient_descent = line_search_use_sufficient_descent - else: - raise Exception(f'Invalid value for line_search_use_sufficient_descent. Possible values are 0, 1, got {line_search_use_sufficient_descent}') - - @globalization_use_SOC.setter - def globalization_use_SOC(self, globalization_use_SOC): - if globalization_use_SOC in [0, 1]: - self.__globalization_use_SOC = globalization_use_SOC - else: - raise Exception(f'Invalid value for globalization_use_SOC. Possible values are 0, 1, got {globalization_use_SOC}') - - @full_step_dual.setter - def full_step_dual(self, full_step_dual): - if full_step_dual in [0, 1]: - self.__full_step_dual = full_step_dual - else: - raise Exception(f'Invalid value for full_step_dual. Possible values are 0, 1, got {full_step_dual}') - - @eps_sufficient_descent.setter - def eps_sufficient_descent(self, eps_sufficient_descent): - if isinstance(eps_sufficient_descent, float) and eps_sufficient_descent > 0: - self.__eps_sufficient_descent = eps_sufficient_descent - else: - raise Exception('Invalid eps_sufficient_descent value. eps_sufficient_descent must be a positive float.') - - @sim_method_num_stages.setter - def sim_method_num_stages(self, sim_method_num_stages): - - # if isinstance(sim_method_num_stages, int): - # self.__sim_method_num_stages = sim_method_num_stages - # else: - # raise Exception('Invalid sim_method_num_stages value. sim_method_num_stages must be an integer.') - - self.__sim_method_num_stages = sim_method_num_stages - - @sim_method_num_steps.setter - def sim_method_num_steps(self, sim_method_num_steps): - - # if isinstance(sim_method_num_steps, int): - # self.__sim_method_num_steps = sim_method_num_steps - # else: - # raise Exception('Invalid sim_method_num_steps value. sim_method_num_steps must be an integer.') - self.__sim_method_num_steps = sim_method_num_steps - - - @sim_method_newton_iter.setter - def sim_method_newton_iter(self, sim_method_newton_iter): - - if isinstance(sim_method_newton_iter, int): - self.__sim_method_newton_iter = sim_method_newton_iter - else: - raise Exception('Invalid sim_method_newton_iter value. sim_method_newton_iter must be an integer.') - - @sim_method_jac_reuse.setter - def sim_method_jac_reuse(self, sim_method_jac_reuse): - # if sim_method_jac_reuse in (True, False): - self.__sim_method_jac_reuse = sim_method_jac_reuse - # else: - # raise Exception('Invalid sim_method_jac_reuse value. sim_method_jac_reuse must be a Boolean.') - - @nlp_solver_type.setter - def nlp_solver_type(self, nlp_solver_type): - nlp_solver_types = ('SQP', 'SQP_RTI') - if nlp_solver_type in nlp_solver_types: - self.__nlp_solver_type = nlp_solver_type - else: - raise Exception('Invalid nlp_solver_type value. Possible values are:\n\n' \ - + ',\n'.join(nlp_solver_types) + '.\n\nYou have: ' + nlp_solver_type + '.\n\n') - - @nlp_solver_step_length.setter - def nlp_solver_step_length(self, nlp_solver_step_length): - if isinstance(nlp_solver_step_length, float) and nlp_solver_step_length > 0: - self.__nlp_solver_step_length = nlp_solver_step_length - else: - raise Exception('Invalid nlp_solver_step_length value. nlp_solver_step_length must be a positive float.') - - @levenberg_marquardt.setter - def levenberg_marquardt(self, levenberg_marquardt): - if isinstance(levenberg_marquardt, float) and levenberg_marquardt >= 0: - self.__levenberg_marquardt = levenberg_marquardt - else: - raise Exception('Invalid levenberg_marquardt value. levenberg_marquardt must be a positive float.') - - @qp_solver_iter_max.setter - def qp_solver_iter_max(self, qp_solver_iter_max): - if isinstance(qp_solver_iter_max, int) and qp_solver_iter_max > 0: - self.__qp_solver_iter_max = qp_solver_iter_max - else: - raise Exception('Invalid qp_solver_iter_max value. qp_solver_iter_max must be a positive int.') - - @qp_solver_ric_alg.setter - def qp_solver_ric_alg(self, qp_solver_ric_alg): - if qp_solver_ric_alg in [0, 1]: - self.__qp_solver_ric_alg = qp_solver_ric_alg - else: - raise Exception(f'Invalid qp_solver_ric_alg value. qp_solver_ric_alg must be in [0, 1], got {qp_solver_ric_alg}.') - - @qp_solver_cond_ric_alg.setter - def qp_solver_cond_ric_alg(self, qp_solver_cond_ric_alg): - if qp_solver_cond_ric_alg in [0, 1]: - self.__qp_solver_cond_ric_alg = qp_solver_cond_ric_alg - else: - raise Exception(f'Invalid qp_solver_cond_ric_alg value. qp_solver_cond_ric_alg must be in [0, 1], got {qp_solver_cond_ric_alg}.') - - - @qp_solver_cond_N.setter - def qp_solver_cond_N(self, qp_solver_cond_N): - if isinstance(qp_solver_cond_N, int) and qp_solver_cond_N >= 0: - self.__qp_solver_cond_N = qp_solver_cond_N - else: - raise Exception('Invalid qp_solver_cond_N value. qp_solver_cond_N must be a positive int.') - - @qp_solver_warm_start.setter - def qp_solver_warm_start(self, qp_solver_warm_start): - if qp_solver_warm_start in [0, 1, 2]: - self.__qp_solver_warm_start = qp_solver_warm_start - else: - raise Exception('Invalid qp_solver_warm_start value. qp_solver_warm_start must be 0 or 1 or 2.') - - @qp_tol.setter - def qp_tol(self, qp_tol): - if isinstance(qp_tol, float) and qp_tol > 0: - self.__qp_solver_tol_eq = qp_tol - self.__qp_solver_tol_ineq = qp_tol - self.__qp_solver_tol_stat = qp_tol - self.__qp_solver_tol_comp = qp_tol - else: - raise Exception('Invalid qp_tol value. qp_tol must be a positive float.') - - @qp_solver_tol_stat.setter - def qp_solver_tol_stat(self, qp_solver_tol_stat): - if isinstance(qp_solver_tol_stat, float) and qp_solver_tol_stat > 0: - self.__qp_solver_tol_stat = qp_solver_tol_stat - else: - raise Exception('Invalid qp_solver_tol_stat value. qp_solver_tol_stat must be a positive float.') - - @qp_solver_tol_eq.setter - def qp_solver_tol_eq(self, qp_solver_tol_eq): - if isinstance(qp_solver_tol_eq, float) and qp_solver_tol_eq > 0: - self.__qp_solver_tol_eq = qp_solver_tol_eq - else: - raise Exception('Invalid qp_solver_tol_eq value. qp_solver_tol_eq must be a positive float.') - - @qp_solver_tol_ineq.setter - def qp_solver_tol_ineq(self, qp_solver_tol_ineq): - if isinstance(qp_solver_tol_ineq, float) and qp_solver_tol_ineq > 0: - self.__qp_solver_tol_ineq = qp_solver_tol_ineq - else: - raise Exception('Invalid qp_solver_tol_ineq value. qp_solver_tol_ineq must be a positive float.') - - @qp_solver_tol_comp.setter - def qp_solver_tol_comp(self, qp_solver_tol_comp): - if isinstance(qp_solver_tol_comp, float) and qp_solver_tol_comp > 0: - self.__qp_solver_tol_comp = qp_solver_tol_comp - else: - raise Exception('Invalid qp_solver_tol_comp value. qp_solver_tol_comp must be a positive float.') - - @tol.setter - def tol(self, tol): - if isinstance(tol, float) and tol > 0: - self.__nlp_solver_tol_eq = tol - self.__nlp_solver_tol_ineq = tol - self.__nlp_solver_tol_stat = tol - self.__nlp_solver_tol_comp = tol - else: - raise Exception('Invalid tol value. tol must be a positive float.') - - @nlp_solver_tol_stat.setter - def nlp_solver_tol_stat(self, nlp_solver_tol_stat): - if isinstance(nlp_solver_tol_stat, float) and nlp_solver_tol_stat > 0: - self.__nlp_solver_tol_stat = nlp_solver_tol_stat - else: - raise Exception('Invalid nlp_solver_tol_stat value. nlp_solver_tol_stat must be a positive float.') - - @nlp_solver_tol_eq.setter - def nlp_solver_tol_eq(self, nlp_solver_tol_eq): - if isinstance(nlp_solver_tol_eq, float) and nlp_solver_tol_eq > 0: - self.__nlp_solver_tol_eq = nlp_solver_tol_eq - else: - raise Exception('Invalid nlp_solver_tol_eq value. nlp_solver_tol_eq must be a positive float.') - - @nlp_solver_tol_ineq.setter - def nlp_solver_tol_ineq(self, nlp_solver_tol_ineq): - if isinstance(nlp_solver_tol_ineq, float) and nlp_solver_tol_ineq > 0: - self.__nlp_solver_tol_ineq = nlp_solver_tol_ineq - else: - raise Exception('Invalid nlp_solver_tol_ineq value. nlp_solver_tol_ineq must be a positive float.') - - @nlp_solver_ext_qp_res.setter - def nlp_solver_ext_qp_res(self, nlp_solver_ext_qp_res): - if nlp_solver_ext_qp_res in [0, 1]: - self.__nlp_solver_ext_qp_res = nlp_solver_ext_qp_res - else: - raise Exception('Invalid nlp_solver_ext_qp_res value. nlp_solver_ext_qp_res must be in [0, 1].') - - @nlp_solver_tol_comp.setter - def nlp_solver_tol_comp(self, nlp_solver_tol_comp): - if isinstance(nlp_solver_tol_comp, float) and nlp_solver_tol_comp > 0: - self.__nlp_solver_tol_comp = nlp_solver_tol_comp - else: - raise Exception('Invalid nlp_solver_tol_comp value. nlp_solver_tol_comp must be a positive float.') - - @nlp_solver_max_iter.setter - def nlp_solver_max_iter(self, nlp_solver_max_iter): - - if isinstance(nlp_solver_max_iter, int) and nlp_solver_max_iter > 0: - self.__nlp_solver_max_iter = nlp_solver_max_iter - else: - raise Exception('Invalid nlp_solver_max_iter value. nlp_solver_max_iter must be a positive int.') - - @print_level.setter - def print_level(self, print_level): - if isinstance(print_level, int) and print_level >= 0: - self.__print_level = print_level - else: - raise Exception('Invalid print_level value. print_level takes one of the values >=0.') - - @model_external_shared_lib_dir.setter - def model_external_shared_lib_dir(self, model_external_shared_lib_dir): - if isinstance(model_external_shared_lib_dir, str) : - self.__model_external_shared_lib_dir = model_external_shared_lib_dir - else: - raise Exception('Invalid model_external_shared_lib_dir value. Str expected.' \ - + '.\n\nYou have: ' + type(model_external_shared_lib_dir) + '.\n\n') - - @model_external_shared_lib_name.setter - def model_external_shared_lib_name(self, model_external_shared_lib_name): - if isinstance(model_external_shared_lib_name, str) : - if model_external_shared_lib_name[-3:] == '.so' : - raise Exception('Invalid model_external_shared_lib_name value. Remove the .so extension.' \ - + '.\n\nYou have: ' + type(model_external_shared_lib_name) + '.\n\n') - else : - self.__model_external_shared_lib_name = model_external_shared_lib_name - else: - raise Exception('Invalid model_external_shared_lib_name value. Str expected.' \ - + '.\n\nYou have: ' + type(model_external_shared_lib_name) + '.\n\n') - - @exact_hess_constr.setter - def exact_hess_constr(self, exact_hess_constr): - if exact_hess_constr in [0, 1]: - self.__exact_hess_constr = exact_hess_constr - else: - raise Exception('Invalid exact_hess_constr value. exact_hess_constr takes one of the values 0, 1.') - - @exact_hess_cost.setter - def exact_hess_cost(self, exact_hess_cost): - if exact_hess_cost in [0, 1]: - self.__exact_hess_cost = exact_hess_cost - else: - raise Exception('Invalid exact_hess_cost value. exact_hess_cost takes one of the values 0, 1.') - - @exact_hess_dyn.setter - def exact_hess_dyn(self, exact_hess_dyn): - if exact_hess_dyn in [0, 1]: - self.__exact_hess_dyn = exact_hess_dyn - else: - raise Exception('Invalid exact_hess_dyn value. exact_hess_dyn takes one of the values 0, 1.') - - @ext_cost_num_hess.setter - def ext_cost_num_hess(self, ext_cost_num_hess): - if ext_cost_num_hess in [0, 1]: - self.__ext_cost_num_hess = ext_cost_num_hess - else: - raise Exception('Invalid ext_cost_num_hess value. ext_cost_num_hess takes one of the values 0, 1.') - - def set(self, attr, value): - setattr(self, attr, value) - - -class AcadosOcp: - """ - Class containing the full description of the optimal control problem. - This object can be used to create an :py:class:`acados_template.acados_ocp_solver.AcadosOcpSolver`. - - The class has the following properties that can be modified to formulate a specific OCP, see below: - - - :py:attr:`dims` of type :py:class:`acados_template.acados_ocp.AcadosOcpDims` - - :py:attr:`model` of type :py:class:`acados_template.acados_model.AcadosModel` - - :py:attr:`cost` of type :py:class:`acados_template.acados_ocp.AcadosOcpCost` - - :py:attr:`constraints` of type :py:class:`acados_template.acados_ocp.AcadosOcpConstraints` - - :py:attr:`solver_options` of type :py:class:`acados_template.acados_ocp.AcadosOcpOptions` - - - :py:attr:`acados_include_path` (set automatically) - - :py:attr:`shared_lib_ext` (set automatically) - - :py:attr:`acados_lib_path` (set automatically) - - :py:attr:`parameter_values` - used to initialize the parameters (can be changed) - """ - def __init__(self, acados_path=''): - """ - Keyword arguments: - acados_path -- path of your acados installation - """ - if acados_path == '': - acados_path = get_acados_path() - - self.dims = AcadosOcpDims() - """Dimension definitions, type :py:class:`acados_template.acados_ocp.AcadosOcpDims`""" - self.model = AcadosModel() - """Model definitions, type :py:class:`acados_template.acados_model.AcadosModel`""" - self.cost = AcadosOcpCost() - """Cost definitions, type :py:class:`acados_template.acados_ocp.AcadosOcpCost`""" - self.constraints = AcadosOcpConstraints() - """Constraints definitions, type :py:class:`acados_template.acados_ocp.AcadosOcpConstraints`""" - self.solver_options = AcadosOcpOptions() - """Solver Options, type :py:class:`acados_template.acados_ocp.AcadosOcpOptions`""" - - self.acados_include_path = os.path.join(acados_path, 'include').replace(os.sep, '/') # the replace part is important on Windows for CMake - """Path to acados include directory (set automatically), type: `string`""" - self.acados_lib_path = os.path.join(acados_path, 'lib').replace(os.sep, '/') # the replace part is important on Windows for CMake - """Path to where acados library is located, type: `string`""" - self.shared_lib_ext = get_lib_ext() - - # get cython paths - from sysconfig import get_paths - self.cython_include_dirs = [np.get_include(), get_paths()['include']] - - self.__parameter_values = np.array([]) - self.__problem_class = 'OCP' - - self.code_export_directory = 'c_generated_code' - """Path to where code will be exported. Default: `c_generated_code`.""" - - @property - def parameter_values(self): - """:math:`p` - initial values for parameter - can be updated stagewise""" - return self.__parameter_values - - @parameter_values.setter - def parameter_values(self, parameter_values): - if isinstance(parameter_values, np.ndarray): - self.__parameter_values = parameter_values - else: - raise Exception('Invalid parameter_values value. ' + - f'Expected numpy array, got {type(parameter_values)}.') - - def set(self, attr, value): - # tokenize string - tokens = attr.split('_', 1) - if len(tokens) > 1: - setter_to_call = getattr(getattr(self, tokens[0]), 'set') - else: - setter_to_call = getattr(self, 'set') - - setter_to_call(tokens[1], value) - - return diff --git a/third_party/acados/acados_template/acados_ocp_solver.py b/third_party/acados/acados_template/acados_ocp_solver.py deleted file mode 100644 index ffc9cf4b0e..0000000000 --- a/third_party/acados/acados_template/acados_ocp_solver.py +++ /dev/null @@ -1,1991 +0,0 @@ -# -*- coding: future_fstrings -*- -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# 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. -# -# 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.; -# - -import sys -import os -import json -import numpy as np -from datetime import datetime -import importlib -import shutil - -from subprocess import DEVNULL, call, STDOUT - -from ctypes import POINTER, cast, CDLL, c_void_p, c_char_p, c_double, c_int, c_int64, byref - -from copy import deepcopy -from pathlib import Path - -from .casadi_function_generation import generate_c_code_explicit_ode, \ - generate_c_code_implicit_ode, generate_c_code_gnsf, generate_c_code_discrete_dynamics, \ - generate_c_code_constraint, generate_c_code_nls_cost, generate_c_code_conl_cost, \ - generate_c_code_external_cost -from .gnsf.detect_gnsf_structure import detect_gnsf_structure -from .acados_ocp import AcadosOcp -from .acados_model import AcadosModel -from .utils import is_column, is_empty, casadi_length, render_template,\ - format_class_dict, make_object_json_dumpable, make_model_consistent,\ - set_up_imported_gnsf_model, get_ocp_nlp_layout, get_python_interface_path, get_lib_ext, check_casadi_version -from .builders import CMakeBuilder - - -def make_ocp_dims_consistent(acados_ocp: AcadosOcp): - dims = acados_ocp.dims - cost = acados_ocp.cost - constraints = acados_ocp.constraints - model = acados_ocp.model - opts = acados_ocp.solver_options - - # nx - if is_column(model.x): - dims.nx = casadi_length(model.x) - else: - raise Exception('model.x should be column vector!') - - # nu - if is_empty(model.u): - dims.nu = 0 - else: - dims.nu = casadi_length(model.u) - - # nz - if is_empty(model.z): - dims.nz = 0 - else: - dims.nz = casadi_length(model.z) - - # np - if is_empty(model.p): - dims.np = 0 - else: - dims.np = casadi_length(model.p) - if acados_ocp.parameter_values.shape[0] != dims.np: - raise Exception('inconsistent dimension np, regarding model.p and parameter_values.' + \ - f'\nGot np = {dims.np}, acados_ocp.parameter_values.shape = {acados_ocp.parameter_values.shape[0]}\n') - - ## cost - # initial stage - if not set, copy fields from path constraints - if cost.cost_type_0 is None: - cost.cost_type_0 = cost.cost_type - cost.W_0 = cost.W - cost.Vx_0 = cost.Vx - cost.Vu_0 = cost.Vu - cost.Vz_0 = cost.Vz - cost.yref_0 = cost.yref - cost.cost_ext_fun_type_0 = cost.cost_ext_fun_type - model.cost_y_expr_0 = model.cost_y_expr - model.cost_expr_ext_cost_0 = model.cost_expr_ext_cost - model.cost_expr_ext_cost_custom_hess_0 = model.cost_expr_ext_cost_custom_hess - - model.cost_psi_expr_0 = model.cost_psi_expr - model.cost_r_in_psi_expr_0 = model.cost_r_in_psi_expr - - if cost.cost_type_0 == 'LINEAR_LS': - ny_0 = cost.W_0.shape[0] - if cost.Vx_0.shape[0] != ny_0 or cost.Vu_0.shape[0] != ny_0: - raise Exception('inconsistent dimension ny_0, regarding W_0, Vx_0, Vu_0.' + \ - f'\nGot W_0[{cost.W_0.shape}], Vx_0[{cost.Vx_0.shape}], Vu_0[{cost.Vu_0.shape}]\n') - if dims.nz != 0 and cost.Vz_0.shape[0] != ny_0: - raise Exception('inconsistent dimension ny_0, regarding W_0, Vx_0, Vu_0, Vz_0.' + \ - f'\nGot W_0[{cost.W_0.shape}], Vx_0[{cost.Vx_0.shape}], Vu_0[{cost.Vu_0.shape}], Vz_0[{cost.Vz_0.shape}]\n') - if cost.Vx_0.shape[1] != dims.nx and ny_0 != 0: - raise Exception('inconsistent dimension: Vx_0 should have nx columns.') - if cost.Vu_0.shape[1] != dims.nu and ny_0 != 0: - raise Exception('inconsistent dimension: Vu_0 should have nu columns.') - if cost.yref_0.shape[0] != ny_0: - raise Exception('inconsistent dimension: regarding W_0, yref_0.' + \ - f'\nGot W_0[{cost.W_0.shape}], yref_0[{cost.yref_0.shape}]\n') - dims.ny_0 = ny_0 - - elif cost.cost_type_0 == 'NONLINEAR_LS': - ny_0 = cost.W_0.shape[0] - if is_empty(model.cost_y_expr_0) and ny_0 != 0: - raise Exception('inconsistent dimension ny_0: regarding W_0, cost_y_expr.') - elif casadi_length(model.cost_y_expr_0) != ny_0: - raise Exception('inconsistent dimension ny_0: regarding W_0, cost_y_expr.') - if cost.yref_0.shape[0] != ny_0: - raise Exception('inconsistent dimension: regarding W_0, yref_0.' + \ - f'\nGot W_0[{cost.W.shape}], yref_0[{cost.yref_0.shape}]\n') - dims.ny_0 = ny_0 - - elif cost.cost_type_0 == 'CONVEX_OVER_NONLINEAR': - if is_empty(model.cost_y_expr_0): - raise Exception('cost_y_expr_0 and/or cost_y_expr not provided.') - ny_0 = casadi_length(model.cost_y_expr_0) - if is_empty(model.cost_r_in_psi_expr_0) or casadi_length(model.cost_r_in_psi_expr_0) != ny_0: - raise Exception('inconsistent dimension ny_0: regarding cost_y_expr_0 and cost_r_in_psi_0.') - if is_empty(model.cost_psi_expr_0) or casadi_length(model.cost_psi_expr_0) != 1: - raise Exception('cost_psi_expr_0 not provided or not scalar-valued.') - if cost.yref_0.shape[0] != ny_0: - raise Exception('inconsistent dimension: regarding yref_0 and cost_y_expr_0, cost_r_in_psi_0.') - dims.ny_0 = ny_0 - - if not (opts.hessian_approx=='EXACT' and opts.exact_hess_cost==False) and opts.hessian_approx != 'GAUSS_NEWTON': - raise Exception("\nWith CONVEX_OVER_NONLINEAR cost type, possible Hessian approximations are:\n" - "GAUSS_NEWTON or EXACT with 'exact_hess_cost' == False.\n") - - elif cost.cost_type_0 == 'EXTERNAL': - if opts.hessian_approx == 'GAUSS_NEWTON' and opts.ext_cost_num_hess == 0 and model.cost_expr_ext_cost_custom_hess_0 is None: - print("\nWARNING: Gauss-Newton Hessian approximation with EXTERNAL cost type not possible!\n" - "got cost_type_0: EXTERNAL, hessian_approx: 'GAUSS_NEWTON.'\n" - "GAUSS_NEWTON hessian is only supported for cost_types [NON]LINEAR_LS.\n" - "If you continue, acados will proceed computing the exact hessian for the cost term.\n" - "Note: There is also the option to use the external cost module with a numerical hessian approximation (see `ext_cost_num_hess`).\n" - "OR the option to provide a symbolic custom hessian approximation (see `cost_expr_ext_cost_custom_hess`).\n") - - # path - if cost.cost_type == 'LINEAR_LS': - ny = cost.W.shape[0] - if cost.Vx.shape[0] != ny or cost.Vu.shape[0] != ny: - raise Exception('inconsistent dimension ny, regarding W, Vx, Vu.' + \ - f'\nGot W[{cost.W.shape}], Vx[{cost.Vx.shape}], Vu[{cost.Vu.shape}]\n') - if dims.nz != 0 and cost.Vz.shape[0] != ny: - raise Exception('inconsistent dimension ny, regarding W, Vx, Vu, Vz.' + \ - f'\nGot W[{cost.W.shape}], Vx[{cost.Vx.shape}], Vu[{cost.Vu.shape}], Vz[{cost.Vz.shape}]\n') - if cost.Vx.shape[1] != dims.nx and ny != 0: - raise Exception('inconsistent dimension: Vx should have nx columns.') - if cost.Vu.shape[1] != dims.nu and ny != 0: - raise Exception('inconsistent dimension: Vu should have nu columns.') - if cost.yref.shape[0] != ny: - raise Exception('inconsistent dimension: regarding W, yref.' + \ - f'\nGot W[{cost.W.shape}], yref[{cost.yref.shape}]\n') - dims.ny = ny - - elif cost.cost_type == 'NONLINEAR_LS': - ny = cost.W.shape[0] - if is_empty(model.cost_y_expr) and ny != 0: - raise Exception('inconsistent dimension ny: regarding W, cost_y_expr.') - elif casadi_length(model.cost_y_expr) != ny: - raise Exception('inconsistent dimension ny: regarding W, cost_y_expr.') - if cost.yref.shape[0] != ny: - raise Exception('inconsistent dimension: regarding W, yref.' + \ - f'\nGot W[{cost.W.shape}], yref[{cost.yref.shape}]\n') - dims.ny = ny - - elif cost.cost_type == 'CONVEX_OVER_NONLINEAR': - if is_empty(model.cost_y_expr): - raise Exception('cost_y_expr and/or cost_y_expr not provided.') - ny = casadi_length(model.cost_y_expr) - if is_empty(model.cost_r_in_psi_expr) or casadi_length(model.cost_r_in_psi_expr) != ny: - raise Exception('inconsistent dimension ny: regarding cost_y_expr and cost_r_in_psi.') - if is_empty(model.cost_psi_expr) or casadi_length(model.cost_psi_expr) != 1: - raise Exception('cost_psi_expr not provided or not scalar-valued.') - if cost.yref.shape[0] != ny: - raise Exception('inconsistent dimension: regarding yref and cost_y_expr, cost_r_in_psi.') - dims.ny = ny - - if not (opts.hessian_approx=='EXACT' and opts.exact_hess_cost==False) and opts.hessian_approx != 'GAUSS_NEWTON': - raise Exception("\nWith CONVEX_OVER_NONLINEAR cost type, possible Hessian approximations are:\n" - "GAUSS_NEWTON or EXACT with 'exact_hess_cost' == False.\n") - - - elif cost.cost_type == 'EXTERNAL': - if opts.hessian_approx == 'GAUSS_NEWTON' and opts.ext_cost_num_hess == 0 and model.cost_expr_ext_cost_custom_hess is None: - print("\nWARNING: Gauss-Newton Hessian approximation with EXTERNAL cost type not possible!\n" - "got cost_type: EXTERNAL, hessian_approx: 'GAUSS_NEWTON.'\n" - "GAUSS_NEWTON hessian is only supported for cost_types [NON]LINEAR_LS.\n" - "If you continue, acados will proceed computing the exact hessian for the cost term.\n" - "Note: There is also the option to use the external cost module with a numerical hessian approximation (see `ext_cost_num_hess`).\n" - "OR the option to provide a symbolic custom hessian approximation (see `cost_expr_ext_cost_custom_hess`).\n") - - # terminal - if cost.cost_type_e == 'LINEAR_LS': - ny_e = cost.W_e.shape[0] - if cost.Vx_e.shape[0] != ny_e: - raise Exception('inconsistent dimension ny_e: regarding W_e, cost_y_expr_e.' + \ - f'\nGot W_e[{cost.W_e.shape}], Vx_e[{cost.Vx_e.shape}]') - if cost.Vx_e.shape[1] != dims.nx and ny_e != 0: - raise Exception('inconsistent dimension: Vx_e should have nx columns.') - if cost.yref_e.shape[0] != ny_e: - raise Exception('inconsistent dimension: regarding W_e, yref_e.') - dims.ny_e = ny_e - - elif cost.cost_type_e == 'NONLINEAR_LS': - ny_e = cost.W_e.shape[0] - if is_empty(model.cost_y_expr_e) and ny_e != 0: - raise Exception('inconsistent dimension ny_e: regarding W_e, cost_y_expr_e.') - elif casadi_length(model.cost_y_expr_e) != ny_e: - raise Exception('inconsistent dimension ny_e: regarding W_e, cost_y_expr_e.') - if cost.yref_e.shape[0] != ny_e: - raise Exception('inconsistent dimension: regarding W_e, yref_e.') - dims.ny_e = ny_e - - elif cost.cost_type_e == 'CONVEX_OVER_NONLINEAR': - if is_empty(model.cost_y_expr_e): - raise Exception('cost_y_expr_e not provided.') - ny_e = casadi_length(model.cost_y_expr_e) - if is_empty(model.cost_r_in_psi_expr_e) or casadi_length(model.cost_r_in_psi_expr_e) != ny_e: - raise Exception('inconsistent dimension ny_e: regarding cost_y_expr_e and cost_r_in_psi_e.') - if is_empty(model.cost_psi_expr_e) or casadi_length(model.cost_psi_expr_e) != 1: - raise Exception('cost_psi_expr_e not provided or not scalar-valued.') - if cost.yref_e.shape[0] != ny_e: - raise Exception('inconsistent dimension: regarding yref_e and cost_y_expr_e, cost_r_in_psi_e.') - dims.ny_e = ny_e - - if not (opts.hessian_approx=='EXACT' and opts.exact_hess_cost==False) and opts.hessian_approx != 'GAUSS_NEWTON': - raise Exception("\nWith CONVEX_OVER_NONLINEAR cost type, possible Hessian approximations are:\n" - "GAUSS_NEWTON or EXACT with 'exact_hess_cost' == False.\n") - - - - elif cost.cost_type_e == 'EXTERNAL': - if opts.hessian_approx == 'GAUSS_NEWTON' and opts.ext_cost_num_hess == 0 and model.cost_expr_ext_cost_custom_hess_e is None: - print("\nWARNING: Gauss-Newton Hessian approximation with EXTERNAL cost type not possible!\n" - "got cost_type_e: EXTERNAL, hessian_approx: 'GAUSS_NEWTON.'\n" - "GAUSS_NEWTON hessian is only supported for cost_types [NON]LINEAR_LS.\n" - "If you continue, acados will proceed computing the exact hessian for the cost term.\n" - "Note: There is also the option to use the external cost module with a numerical hessian approximation (see `ext_cost_num_hess`).\n" - "OR the option to provide a symbolic custom hessian approximation (see `cost_expr_ext_cost_custom_hess`).\n") - - ## constraints - # initial - this_shape = constraints.lbx_0.shape - other_shape = constraints.ubx_0.shape - if not this_shape == other_shape: - raise Exception('lbx_0, ubx_0 have different shapes!') - if not is_column(constraints.lbx_0): - raise Exception('lbx_0, ubx_0 must be column vectors!') - dims.nbx_0 = constraints.lbx_0.size - - if all(constraints.lbx_0 == constraints.ubx_0) and dims.nbx_0 == dims.nx \ - and dims.nbxe_0 is None \ - and (constraints.idxbxe_0.shape == constraints.idxbx_0.shape)\ - and all(constraints.idxbxe_0 == constraints.idxbx_0): - # case: x0 was set: nbx0 are all equlities. - dims.nbxe_0 = dims.nbx_0 - elif constraints.idxbxe_0 is not None: - dims.nbxe_0 = constraints.idxbxe_0.shape[0] - elif dims.nbxe_0 is None: - # case: x0 and idxbxe_0 were not set -> dont assume nbx0 to be equality constraints. - dims.nbxe_0 = 0 - - # path - nbx = constraints.idxbx.shape[0] - if constraints.ubx.shape[0] != nbx or constraints.lbx.shape[0] != nbx: - raise Exception('inconsistent dimension nbx, regarding idxbx, ubx, lbx.') - else: - dims.nbx = nbx - - nbu = constraints.idxbu.shape[0] - if constraints.ubu.shape[0] != nbu or constraints.lbu.shape[0] != nbu: - raise Exception('inconsistent dimension nbu, regarding idxbu, ubu, lbu.') - else: - dims.nbu = nbu - - ng = constraints.lg.shape[0] - if constraints.ug.shape[0] != ng or constraints.C.shape[0] != ng \ - or constraints.D.shape[0] != ng: - raise Exception('inconsistent dimension ng, regarding lg, ug, C, D.') - else: - dims.ng = ng - - if not is_empty(model.con_h_expr): - nh = casadi_length(model.con_h_expr) - else: - nh = 0 - - if constraints.uh.shape[0] != nh or constraints.lh.shape[0] != nh: - raise Exception('inconsistent dimension nh, regarding lh, uh, con_h_expr.') - else: - dims.nh = nh - - if is_empty(model.con_phi_expr): - dims.nphi = 0 - dims.nr = 0 - else: - dims.nphi = casadi_length(model.con_phi_expr) - if is_empty(model.con_r_expr): - raise Exception('convex over nonlinear constraints: con_r_expr but con_phi_expr is nonempty') - else: - dims.nr = casadi_length(model.con_r_expr) - - # terminal - nbx_e = constraints.idxbx_e.shape[0] - if constraints.ubx_e.shape[0] != nbx_e or constraints.lbx_e.shape[0] != nbx_e: - raise Exception('inconsistent dimension nbx_e, regarding idxbx_e, ubx_e, lbx_e.') - else: - dims.nbx_e = nbx_e - - ng_e = constraints.lg_e.shape[0] - if constraints.ug_e.shape[0] != ng_e or constraints.C_e.shape[0] != ng_e: - raise Exception('inconsistent dimension ng_e, regarding_e lg_e, ug_e, C_e.') - else: - dims.ng_e = ng_e - - if not is_empty(model.con_h_expr_e): - nh_e = casadi_length(model.con_h_expr_e) - else: - nh_e = 0 - - if constraints.uh_e.shape[0] != nh_e or constraints.lh_e.shape[0] != nh_e: - raise Exception('inconsistent dimension nh_e, regarding lh_e, uh_e, con_h_expr_e.') - else: - dims.nh_e = nh_e - - if is_empty(model.con_phi_expr_e): - dims.nphi_e = 0 - dims.nr_e = 0 - else: - dims.nphi_e = casadi_length(model.con_phi_expr_e) - if is_empty(model.con_r_expr_e): - raise Exception('convex over nonlinear constraints: con_r_expr_e but con_phi_expr_e is nonempty') - else: - dims.nr_e = casadi_length(model.con_r_expr_e) - - # Slack dimensions - nsbx = constraints.idxsbx.shape[0] - if nsbx > nbx: - raise Exception(f'inconsistent dimension nsbx = {nsbx}. Is greater than nbx = {nbx}.') - if is_empty(constraints.lsbx): - constraints.lsbx = np.zeros((nsbx,)) - elif constraints.lsbx.shape[0] != nsbx: - raise Exception('inconsistent dimension nsbx, regarding idxsbx, lsbx.') - if is_empty(constraints.usbx): - constraints.usbx = np.zeros((nsbx,)) - elif constraints.usbx.shape[0] != nsbx: - raise Exception('inconsistent dimension nsbx, regarding idxsbx, usbx.') - dims.nsbx = nsbx - - nsbu = constraints.idxsbu.shape[0] - if nsbu > nbu: - raise Exception(f'inconsistent dimension nsbu = {nsbu}. Is greater than nbu = {nbu}.') - if is_empty(constraints.lsbu): - constraints.lsbu = np.zeros((nsbu,)) - elif constraints.lsbu.shape[0] != nsbu: - raise Exception('inconsistent dimension nsbu, regarding idxsbu, lsbu.') - if is_empty(constraints.usbu): - constraints.usbu = np.zeros((nsbu,)) - elif constraints.usbu.shape[0] != nsbu: - raise Exception('inconsistent dimension nsbu, regarding idxsbu, usbu.') - dims.nsbu = nsbu - - nsh = constraints.idxsh.shape[0] - if nsh > nh: - raise Exception(f'inconsistent dimension nsh = {nsh}. Is greater than nh = {nh}.') - if is_empty(constraints.lsh): - constraints.lsh = np.zeros((nsh,)) - elif constraints.lsh.shape[0] != nsh: - raise Exception('inconsistent dimension nsh, regarding idxsh, lsh.') - if is_empty(constraints.ush): - constraints.ush = np.zeros((nsh,)) - elif constraints.ush.shape[0] != nsh: - raise Exception('inconsistent dimension nsh, regarding idxsh, ush.') - dims.nsh = nsh - - nsphi = constraints.idxsphi.shape[0] - if nsphi > dims.nphi: - raise Exception(f'inconsistent dimension nsphi = {nsphi}. Is greater than nphi = {dims.nphi}.') - if is_empty(constraints.lsphi): - constraints.lsphi = np.zeros((nsphi,)) - elif constraints.lsphi.shape[0] != nsphi: - raise Exception('inconsistent dimension nsphi, regarding idxsphi, lsphi.') - if is_empty(constraints.usphi): - constraints.usphi = np.zeros((nsphi,)) - elif constraints.usphi.shape[0] != nsphi: - raise Exception('inconsistent dimension nsphi, regarding idxsphi, usphi.') - dims.nsphi = nsphi - - nsg = constraints.idxsg.shape[0] - if nsg > ng: - raise Exception(f'inconsistent dimension nsg = {nsg}. Is greater than ng = {ng}.') - if is_empty(constraints.lsg): - constraints.lsg = np.zeros((nsg,)) - elif constraints.lsg.shape[0] != nsg: - raise Exception('inconsistent dimension nsg, regarding idxsg, lsg.') - if is_empty(constraints.usg): - constraints.usg = np.zeros((nsg,)) - elif constraints.usg.shape[0] != nsg: - raise Exception('inconsistent dimension nsg, regarding idxsg, usg.') - dims.nsg = nsg - - ns = nsbx + nsbu + nsh + nsg + nsphi - wrong_field = "" - if cost.Zl.shape[0] != ns: - wrong_field = "Zl" - dim = cost.Zl.shape[0] - elif cost.Zu.shape[0] != ns: - wrong_field = "Zu" - dim = cost.Zu.shape[0] - elif cost.zl.shape[0] != ns: - wrong_field = "zl" - dim = cost.zl.shape[0] - elif cost.zu.shape[0] != ns: - wrong_field = "zu" - dim = cost.zu.shape[0] - - if wrong_field != "": - raise Exception(f'Inconsistent size for field {wrong_field}, with dimension {dim}, \n\t'\ - + f'Detected ns = {ns} = nsbx + nsbu + nsg + nsh + nsphi.\n\t'\ - + f'With nsbx = {nsbx}, nsbu = {nsbu}, nsg = {nsg}, nsh = {nsh}, nsphi = {nsphi}') - - dims.ns = ns - - nsbx_e = constraints.idxsbx_e.shape[0] - if nsbx_e > nbx_e: - raise Exception(f'inconsistent dimension nsbx_e = {nsbx_e}. Is greater than nbx_e = {nbx_e}.') - if is_empty(constraints.lsbx_e): - constraints.lsbx_e = np.zeros((nsbx_e,)) - elif constraints.lsbx_e.shape[0] != nsbx_e: - raise Exception('inconsistent dimension nsbx_e, regarding idxsbx_e, lsbx_e.') - if is_empty(constraints.usbx_e): - constraints.usbx_e = np.zeros((nsbx_e,)) - elif constraints.usbx_e.shape[0] != nsbx_e: - raise Exception('inconsistent dimension nsbx_e, regarding idxsbx_e, usbx_e.') - dims.nsbx_e = nsbx_e - - nsh_e = constraints.idxsh_e.shape[0] - if nsh_e > nh_e: - raise Exception(f'inconsistent dimension nsh_e = {nsh_e}. Is greater than nh_e = {nh_e}.') - if is_empty(constraints.lsh_e): - constraints.lsh_e = np.zeros((nsh_e,)) - elif constraints.lsh_e.shape[0] != nsh_e: - raise Exception('inconsistent dimension nsh_e, regarding idxsh_e, lsh_e.') - if is_empty(constraints.ush_e): - constraints.ush_e = np.zeros((nsh_e,)) - elif constraints.ush_e.shape[0] != nsh_e: - raise Exception('inconsistent dimension nsh_e, regarding idxsh_e, ush_e.') - dims.nsh_e = nsh_e - - nsg_e = constraints.idxsg_e.shape[0] - if nsg_e > ng_e: - raise Exception(f'inconsistent dimension nsg_e = {nsg_e}. Is greater than ng_e = {ng_e}.') - if is_empty(constraints.lsg_e): - constraints.lsg_e = np.zeros((nsg_e,)) - elif constraints.lsg_e.shape[0] != nsg_e: - raise Exception('inconsistent dimension nsg_e, regarding idxsg_e, lsg_e.') - if is_empty(constraints.usg_e): - constraints.usg_e = np.zeros((nsg_e,)) - elif constraints.usg_e.shape[0] != nsg_e: - raise Exception('inconsistent dimension nsg_e, regarding idxsg_e, usg_e.') - dims.nsg_e = nsg_e - - nsphi_e = constraints.idxsphi_e.shape[0] - if nsphi_e > dims.nphi_e: - raise Exception(f'inconsistent dimension nsphi_e = {nsphi_e}. Is greater than nphi_e = {dims.nphi_e}.') - if is_empty(constraints.lsphi_e): - constraints.lsphi_e = np.zeros((nsphi_e,)) - elif constraints.lsphi_e.shape[0] != nsphi_e: - raise Exception('inconsistent dimension nsphi_e, regarding idxsphi_e, lsphi_e.') - if is_empty(constraints.usphi_e): - constraints.usphi_e = np.zeros((nsphi_e,)) - elif constraints.usphi_e.shape[0] != nsphi_e: - raise Exception('inconsistent dimension nsphi_e, regarding idxsphi_e, usphi_e.') - dims.nsphi_e = nsphi_e - - # terminal - ns_e = nsbx_e + nsh_e + nsg_e + nsphi_e - wrong_field = "" - if cost.Zl_e.shape[0] != ns_e: - wrong_field = "Zl_e" - dim = cost.Zl_e.shape[0] - elif cost.Zu_e.shape[0] != ns_e: - wrong_field = "Zu_e" - dim = cost.Zu_e.shape[0] - elif cost.zl_e.shape[0] != ns_e: - wrong_field = "zl_e" - dim = cost.zl_e.shape[0] - elif cost.zu_e.shape[0] != ns_e: - wrong_field = "zu_e" - dim = cost.zu_e.shape[0] - - if wrong_field != "": - raise Exception(f'Inconsistent size for field {wrong_field}, with dimension {dim}, \n\t'\ - + f'Detected ns_e = {ns_e} = nsbx_e + nsg_e + nsh_e + nsphi_e.\n\t'\ - + f'With nsbx_e = {nsbx_e}, nsg_e = {nsg_e}, nsh_e = {nsh_e}, nsphi_e = {nsphi_e}') - - dims.ns_e = ns_e - - # discretization - if is_empty(opts.time_steps) and is_empty(opts.shooting_nodes): - # uniform discretization - opts.time_steps = opts.tf / dims.N * np.ones((dims.N,)) - - elif not is_empty(opts.shooting_nodes): - if np.shape(opts.shooting_nodes)[0] != dims.N+1: - raise Exception('inconsistent dimension N, regarding shooting_nodes.') - - time_steps = opts.shooting_nodes[1:] - opts.shooting_nodes[0:-1] - # identify constant time_steps: due to numerical reasons the content of time_steps might vary a bit - avg_time_steps = np.average(time_steps) - # criterion for constant time step detection: the min/max difference in values normalized by the average - check_const_time_step = (np.max(time_steps)-np.min(time_steps)) / avg_time_steps - # if the criterion is small, we have a constant time_step - if check_const_time_step < 1e-9: - time_steps[:] = avg_time_steps # if we have a constant time_step: apply the average time_step - - opts.time_steps = time_steps - - elif (not is_empty(opts.time_steps)) and (not is_empty(opts.shooting_nodes)): - Exception('Please provide either time_steps or shooting_nodes for nonuniform discretization') - - tf = np.sum(opts.time_steps) - if (tf - opts.tf) / tf > 1e-15: - raise Exception(f'Inconsistent discretization: {opts.tf}'\ - f' = tf != sum(opts.time_steps) = {tf}.') - - # num_steps - if isinstance(opts.sim_method_num_steps, np.ndarray) and opts.sim_method_num_steps.size == 1: - opts.sim_method_num_steps = opts.sim_method_num_steps.item() - - if isinstance(opts.sim_method_num_steps, (int, float)) and opts.sim_method_num_steps % 1 == 0: - opts.sim_method_num_steps = opts.sim_method_num_steps * np.ones((dims.N,), dtype=np.int64) - elif isinstance(opts.sim_method_num_steps, np.ndarray) and opts.sim_method_num_steps.size == dims.N \ - and np.all(np.equal(np.mod(opts.sim_method_num_steps, 1), 0)): - opts.sim_method_num_steps = np.reshape(opts.sim_method_num_steps, (dims.N,)).astype(np.int64) - else: - raise Exception("Wrong value for sim_method_num_steps. Should be either int or array of ints of shape (N,).") - - # num_stages - if isinstance(opts.sim_method_num_stages, np.ndarray) and opts.sim_method_num_stages.size == 1: - opts.sim_method_num_stages = opts.sim_method_num_stages.item() - - if isinstance(opts.sim_method_num_stages, (int, float)) and opts.sim_method_num_stages % 1 == 0: - opts.sim_method_num_stages = opts.sim_method_num_stages * np.ones((dims.N,), dtype=np.int64) - elif isinstance(opts.sim_method_num_stages, np.ndarray) and opts.sim_method_num_stages.size == dims.N \ - and np.all(np.equal(np.mod(opts.sim_method_num_stages, 1), 0)): - opts.sim_method_num_stages = np.reshape(opts.sim_method_num_stages, (dims.N,)).astype(np.int64) - else: - raise Exception("Wrong value for sim_method_num_stages. Should be either int or array of ints of shape (N,).") - - # jac_reuse - if isinstance(opts.sim_method_jac_reuse, np.ndarray) and opts.sim_method_jac_reuse.size == 1: - opts.sim_method_jac_reuse = opts.sim_method_jac_reuse.item() - - if isinstance(opts.sim_method_jac_reuse, (int, float)) and opts.sim_method_jac_reuse % 1 == 0: - opts.sim_method_jac_reuse = opts.sim_method_jac_reuse * np.ones((dims.N,), dtype=np.int64) - elif isinstance(opts.sim_method_jac_reuse, np.ndarray) and opts.sim_method_jac_reuse.size == dims.N \ - and np.all(np.equal(np.mod(opts.sim_method_jac_reuse, 1), 0)): - opts.sim_method_jac_reuse = np.reshape(opts.sim_method_jac_reuse, (dims.N,)).astype(np.int64) - else: - raise Exception("Wrong value for sim_method_jac_reuse. Should be either int or array of ints of shape (N,).") - - -def get_simulink_default_opts(): - python_interface_path = get_python_interface_path() - abs_path = os.path.join(python_interface_path, 'simulink_default_opts.json') - with open(abs_path , 'r') as f: - simulink_default_opts = json.load(f) - return simulink_default_opts - - -def ocp_formulation_json_dump(acados_ocp, simulink_opts=None, json_file='acados_ocp_nlp.json'): - # Load acados_ocp_nlp structure description - ocp_layout = get_ocp_nlp_layout() - - # Copy input ocp object dictionary - ocp_nlp_dict = dict(deepcopy(acados_ocp).__dict__) - # TODO: maybe make one function with formatting - - for acados_struct, v in ocp_layout.items(): - # skip non dict attributes - if not isinstance(v, dict): - continue - # setattr(ocp_nlp, acados_struct, dict(getattr(acados_ocp, acados_struct).__dict__)) - # Copy ocp object attributes dictionaries - ocp_nlp_dict[acados_struct]=dict(getattr(acados_ocp, acados_struct).__dict__) - - ocp_nlp_dict = format_class_dict(ocp_nlp_dict) - - if simulink_opts is not None: - ocp_nlp_dict['simulink_opts'] = simulink_opts - - with open(json_file, 'w') as f: - json.dump(ocp_nlp_dict, f, default=make_object_json_dumpable, indent=4, sort_keys=True) - - - -def ocp_formulation_json_load(json_file='acados_ocp_nlp.json'): - # Load acados_ocp_nlp structure description - ocp_layout = get_ocp_nlp_layout() - - with open(json_file, 'r') as f: - ocp_nlp_json = json.load(f) - - ocp_nlp_dict = json2dict(ocp_nlp_json, ocp_nlp_json['dims']) - - # Instantiate AcadosOcp object - acados_ocp = AcadosOcp() - - # load class dict - acados_ocp.__dict__ = ocp_nlp_dict - - # load class attributes dict, dims, constraints, etc - for acados_struct, v in ocp_layout.items(): - # skip non dict attributes - if not isinstance(v, dict): - continue - acados_attribute = getattr(acados_ocp, acados_struct) - acados_attribute.__dict__ = ocp_nlp_dict[acados_struct] - setattr(acados_ocp, acados_struct, acados_attribute) - - return acados_ocp - - -def ocp_generate_external_functions(acados_ocp: AcadosOcp, model: AcadosModel): - - model = make_model_consistent(model) - - if acados_ocp.solver_options.hessian_approx == 'EXACT': - opts = dict(generate_hess=1) - else: - opts = dict(generate_hess=0) - - # create code_export_dir, model_dir - code_export_dir = acados_ocp.code_export_directory - opts['code_export_directory'] = code_export_dir - model_dir = os.path.join(code_export_dir, model.name + '_model') - if not os.path.exists(model_dir): - os.makedirs(model_dir) - - check_casadi_version() - # TODO: remove dir gen from all the generate_c_* functions - if acados_ocp.model.dyn_ext_fun_type == 'casadi': - if acados_ocp.solver_options.integrator_type == 'ERK': - generate_c_code_explicit_ode(model, opts) - elif acados_ocp.solver_options.integrator_type == 'IRK': - generate_c_code_implicit_ode(model, opts) - elif acados_ocp.solver_options.integrator_type == 'LIFTED_IRK': - generate_c_code_implicit_ode(model, opts) - elif acados_ocp.solver_options.integrator_type == 'GNSF': - generate_c_code_gnsf(model, opts) - elif acados_ocp.solver_options.integrator_type == 'DISCRETE': - generate_c_code_discrete_dynamics(model, opts) - else: - raise Exception("ocp_generate_external_functions: unknown integrator type.") - else: - target_location = os.path.join(code_export_dir, model_dir, model.dyn_generic_source) - shutil.copyfile(model.dyn_generic_source, target_location) - - if acados_ocp.dims.nphi > 0 or acados_ocp.dims.nh > 0: - generate_c_code_constraint(model, model.name, False, opts) - - if acados_ocp.dims.nphi_e > 0 or acados_ocp.dims.nh_e > 0: - generate_c_code_constraint(model, model.name, True, opts) - - if acados_ocp.cost.cost_type_0 == 'NONLINEAR_LS': - generate_c_code_nls_cost(model, model.name, 'initial', opts) - elif acados_ocp.cost.cost_type_0 == 'CONVEX_OVER_NONLINEAR': - generate_c_code_conl_cost(model, model.name, 'initial', opts) - elif acados_ocp.cost.cost_type_0 == 'EXTERNAL': - generate_c_code_external_cost(model, 'initial', opts) - - if acados_ocp.cost.cost_type == 'NONLINEAR_LS': - generate_c_code_nls_cost(model, model.name, 'path', opts) - elif acados_ocp.cost.cost_type == 'CONVEX_OVER_NONLINEAR': - generate_c_code_conl_cost(model, model.name, 'path', opts) - elif acados_ocp.cost.cost_type == 'EXTERNAL': - generate_c_code_external_cost(model, 'path', opts) - - if acados_ocp.cost.cost_type_e == 'NONLINEAR_LS': - generate_c_code_nls_cost(model, model.name, 'terminal', opts) - elif acados_ocp.cost.cost_type_e == 'CONVEX_OVER_NONLINEAR': - generate_c_code_conl_cost(model, model.name, 'terminal', opts) - elif acados_ocp.cost.cost_type_e == 'EXTERNAL': - generate_c_code_external_cost(model, 'terminal', opts) - - -def ocp_get_default_cmake_builder() -> CMakeBuilder: - """ - If :py:class:`~acados_template.acados_ocp_solver.AcadosOcpSolver` is used with `CMake` this function returns a good first setting. - :return: default :py:class:`~acados_template.builders.CMakeBuilder` - """ - cmake_builder = CMakeBuilder() - cmake_builder.options_on = ['BUILD_ACADOS_OCP_SOLVER_LIB'] - return cmake_builder - - - -def ocp_render_templates(acados_ocp: AcadosOcp, json_file, cmake_builder=None, simulink_opts=None): - - # setting up loader and environment - json_path = os.path.abspath(json_file) - - if not os.path.exists(json_path): - raise Exception(f'Path "{json_path}" not found!') - - # Render templates - template_list = __ocp_get_template_list(acados_ocp, cmake_builder=cmake_builder, simulink_opts=simulink_opts) - for tup in template_list: - if len(tup) > 2: - output_dir = tup[2] - else: - output_dir = acados_ocp.code_export_directory - render_template(tup[0], tup[1], output_dir, json_path) - - # Custom templates - acados_template_path = os.path.dirname(os.path.abspath(__file__)) - custom_template_glob = os.path.join(acados_template_path, 'custom_update_templates', '*') - for tup in acados_ocp.solver_options.custom_templates: - render_template(tup[0], tup[1], acados_ocp.code_export_directory, json_path, template_glob=custom_template_glob) - - return - - - -def __ocp_get_template_list(acados_ocp: AcadosOcp, cmake_builder=None, simulink_opts=None) -> list: - """ - returns a list of tuples in the form: - (input_filename, output_filname) - or - (input_filename, output_filname, output_directory) - """ - name = acados_ocp.model.name - code_export_directory = acados_ocp.code_export_directory - template_list = [] - - template_list.append(('main.in.c', f'main_{name}.c')) - template_list.append(('acados_solver.in.c', f'acados_solver_{name}.c')) - template_list.append(('acados_solver.in.h', f'acados_solver_{name}.h')) - template_list.append(('acados_solver.in.pxd', f'acados_solver.pxd')) - if cmake_builder is not None: - template_list.append(('CMakeLists.in.txt', 'CMakeLists.txt')) - else: - template_list.append(('Makefile.in', 'Makefile')) - - - # sim - template_list.append(('acados_sim_solver.in.c', f'acados_sim_solver_{name}.c')) - template_list.append(('acados_sim_solver.in.h', f'acados_sim_solver_{name}.h')) - template_list.append(('main_sim.in.c', f'main_sim_{name}.c')) - - # model - model_dir = os.path.join(code_export_directory, f'{name}_model') - template_list.append(('model.in.h', f'{name}_model.h', model_dir)) - # constraints - constraints_dir = os.path.join(code_export_directory, f'{name}_constraints') - template_list.append(('constraints.in.h', f'{name}_constraints.h', constraints_dir)) - # cost - cost_dir = os.path.join(code_export_directory, f'{name}_cost') - template_list.append(('cost.in.h', f'{name}_cost.h', cost_dir)) - - # Simulink - if simulink_opts is not None: - template_file = os.path.join('matlab_templates', 'acados_solver_sfun.in.c') - template_list.append((template_file, f'acados_solver_sfunction_{name}.c')) - template_file = os.path.join('matlab_templates', 'acados_solver_sfun.in.c') - template_list.append((template_file, f'make_sfun_{name}.m')) - - return template_list - - -def remove_x0_elimination(acados_ocp): - acados_ocp.constraints.idxbxe_0 = np.zeros((0,)) - acados_ocp.dims.nbxe_0 = 0 - - -class AcadosOcpSolver: - """ - Class to interact with the acados ocp solver C object. - - :param acados_ocp: type :py:class:`~acados_template.acados_ocp.AcadosOcp` - description of the OCP for acados - :param json_file: name for the json file used to render the templated code - default: acados_ocp_nlp.json - :param simulink_opts: Options to configure Simulink S-function blocks, mainly to activate possible Inputs and Outputs - """ - if sys.platform=="win32": - from ctypes import wintypes - from ctypes import WinDLL - dlclose = WinDLL('kernel32', use_last_error=True).FreeLibrary - dlclose.argtypes = [wintypes.HMODULE] - else: - dlclose = CDLL(None).dlclose - dlclose.argtypes = [c_void_p] - - @classmethod - def generate(cls, acados_ocp: AcadosOcp, json_file='acados_ocp_nlp.json', simulink_opts=None, cmake_builder: CMakeBuilder = None): - """ - Generates the code for an acados OCP solver, given the description in acados_ocp. - :param acados_ocp: type AcadosOcp - description of the OCP for acados - :param json_file: name for the json file used to render the templated code - default: `acados_ocp_nlp.json` - :param simulink_opts: Options to configure Simulink S-function blocks, mainly to activate possible inputs and - outputs; default: `None` - :param cmake_builder: type :py:class:`~acados_template.builders.CMakeBuilder` generate a `CMakeLists.txt` and use - the `CMake` pipeline instead of a `Makefile` (`CMake` seems to be the better option in conjunction with - `MS Visual Studio`); default: `None` - """ - model = acados_ocp.model - acados_ocp.code_export_directory = os.path.abspath(acados_ocp.code_export_directory) - - # make dims consistent - make_ocp_dims_consistent(acados_ocp) - - # module dependent post processing - if acados_ocp.solver_options.integrator_type == 'GNSF': - if 'gnsf_model' in acados_ocp.__dict__: - set_up_imported_gnsf_model(acados_ocp) - else: - detect_gnsf_structure(acados_ocp) - - if acados_ocp.solver_options.qp_solver == 'PARTIAL_CONDENSING_QPDUNES': - remove_x0_elimination(acados_ocp) - - # set integrator time automatically - acados_ocp.solver_options.Tsim = acados_ocp.solver_options.time_steps[0] - - # generate external functions - ocp_generate_external_functions(acados_ocp, model) - - # dump to json - acados_ocp.json_file = json_file - ocp_formulation_json_dump(acados_ocp, simulink_opts=simulink_opts, json_file=json_file) - - # render templates - ocp_render_templates(acados_ocp, json_file, cmake_builder=cmake_builder, simulink_opts=simulink_opts) - - # copy custom update function - if acados_ocp.solver_options.custom_update_filename != "" and acados_ocp.solver_options.custom_update_copy: - target_location = os.path.join(acados_ocp.code_export_directory, acados_ocp.solver_options.custom_update_filename) - shutil.copyfile(acados_ocp.solver_options.custom_update_filename, target_location) - if acados_ocp.solver_options.custom_update_header_filename != "" and acados_ocp.solver_options.custom_update_copy: - target_location = os.path.join(acados_ocp.code_export_directory, acados_ocp.solver_options.custom_update_header_filename) - shutil.copyfile(acados_ocp.solver_options.custom_update_header_filename, target_location) - - - @classmethod - def build(cls, code_export_dir, with_cython=False, cmake_builder: CMakeBuilder = None, verbose: bool = True): - """ - Builds the code for an acados OCP solver, that has been generated in code_export_dir - :param code_export_dir: directory in which acados OCP solver has been generated, see generate() - :param with_cython: option indicating if the cython interface is build, default: False. - :param cmake_builder: type :py:class:`~acados_template.builders.CMakeBuilder` generate a `CMakeLists.txt` and use - the `CMake` pipeline instead of a `Makefile` (`CMake` seems to be the better option in conjunction with - `MS Visual Studio`); default: `None` - :param verbose: indicating if build command is printed - """ - code_export_dir = os.path.abspath(code_export_dir) - cwd = os.getcwd() - os.chdir(code_export_dir) - if with_cython: - call( - ['make', 'clean_all'], - stdout=None if verbose else DEVNULL, - stderr=None if verbose else STDOUT - ) - call( - ['make', 'ocp_cython'], - stdout=None if verbose else DEVNULL, - stderr=None if verbose else STDOUT - ) - else: - if cmake_builder is not None: - cmake_builder.exec(code_export_dir) - else: - call( - ['make', 'clean_ocp_shared_lib'], - stdout=None if verbose else DEVNULL, - stderr=None if verbose else STDOUT - ) - call( - ['make', 'ocp_shared_lib'], - stdout=None if verbose else DEVNULL, - stderr=None if verbose else STDOUT - ) - os.chdir(cwd) - - - @classmethod - def create_cython_solver(cls, json_file): - """ - Returns an `AcadosOcpSolverCython` object. - - This is an alternative Cython based Python wrapper to the acados OCP solver in C. - This offers faster interaction with the solver, because getter and setter calls, which include shape checking are done in compiled C code. - - The default wrapper `AcadosOcpSolver` is based on ctypes. - """ - with open(json_file, 'r') as f: - acados_ocp_json = json.load(f) - code_export_directory = acados_ocp_json['code_export_directory'] - - importlib.invalidate_caches() - rel_code_export_directory = os.path.relpath(code_export_directory) - acados_ocp_solver_pyx = importlib.import_module(f'{rel_code_export_directory}.acados_ocp_solver_pyx') - - AcadosOcpSolverCython = getattr(acados_ocp_solver_pyx, 'AcadosOcpSolverCython') - return AcadosOcpSolverCython(acados_ocp_json['model']['name'], - acados_ocp_json['solver_options']['nlp_solver_type'], - acados_ocp_json['dims']['N']) - - - def __init__(self, acados_ocp: AcadosOcp, json_file='acados_ocp_nlp.json', simulink_opts=None, build=True, generate=True, cmake_builder: CMakeBuilder = None, verbose=True): - - self.solver_created = False - if generate: - self.generate(acados_ocp, json_file=json_file, simulink_opts=simulink_opts, cmake_builder=cmake_builder) - - # load json, store options in object - with open(json_file, 'r') as f: - acados_ocp_json = json.load(f) - self.N = acados_ocp_json['dims']['N'] - self.model_name = acados_ocp_json['model']['name'] - self.solver_options = acados_ocp_json['solver_options'] - - acados_lib_path = acados_ocp_json['acados_lib_path'] - code_export_directory = acados_ocp_json['code_export_directory'] - - if build: - self.build(code_export_directory, with_cython=False, cmake_builder=cmake_builder, verbose=verbose) - - # prepare library loading - lib_prefix = 'lib' - lib_ext = get_lib_ext() - if os.name == 'nt': - lib_prefix = '' - - # Load acados library to avoid unloading the library. - # This is necessary if acados was compiled with OpenMP, since the OpenMP threads can't be destroyed. - # Unloading a library which uses OpenMP results in a segfault (on any platform?). - # see [https://stackoverflow.com/questions/34439956/vc-crash-when-freeing-a-dll-built-with-openmp] - # or [https://python.hotexamples.com/examples/_ctypes/-/dlclose/python-dlclose-function-examples.html] - libacados_name = f'{lib_prefix}acados{lib_ext}' - libacados_filepath = os.path.join(acados_lib_path, libacados_name) - self.__acados_lib = CDLL(libacados_filepath) - # find out if acados was compiled with OpenMP - try: - self.__acados_lib_uses_omp = getattr(self.__acados_lib, 'omp_get_thread_num') is not None - except AttributeError as e: - self.__acados_lib_uses_omp = False - if self.__acados_lib_uses_omp: - print('acados was compiled with OpenMP.') - else: - print('acados was compiled without OpenMP.') - libacados_ocp_solver_name = f'{lib_prefix}acados_ocp_solver_{self.model_name}{lib_ext}' - self.shared_lib_name = os.path.join(code_export_directory, libacados_ocp_solver_name) - - # get shared_lib - self.shared_lib = CDLL(self.shared_lib_name) - - # create capsule - getattr(self.shared_lib, f"{self.model_name}_acados_create_capsule").restype = c_void_p - self.capsule = getattr(self.shared_lib, f"{self.model_name}_acados_create_capsule")() - - # create solver - getattr(self.shared_lib, f"{self.model_name}_acados_create").argtypes = [c_void_p] - getattr(self.shared_lib, f"{self.model_name}_acados_create").restype = c_int - assert getattr(self.shared_lib, f"{self.model_name}_acados_create")(self.capsule)==0 - self.solver_created = True - - self.acados_ocp = acados_ocp - - # get pointers solver - self.__get_pointers_solver() - - self.status = 0 - - # gettable fields - self.__qp_dynamics_fields = ['A', 'B', 'b'] - self.__qp_cost_fields = ['Q', 'R', 'S', 'q', 'r'] - self.__qp_constraint_fields = ['C', 'D', 'lg', 'ug', 'lbx', 'ubx', 'lbu', 'ubu'] - - - def __get_pointers_solver(self): - # """ - # Private function to get the pointers for solver - # """ - # get pointers solver - getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_opts").argtypes = [c_void_p] - getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_opts").restype = c_void_p - self.nlp_opts = getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_opts")(self.capsule) - - getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_dims").argtypes = [c_void_p] - getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_dims").restype = c_void_p - self.nlp_dims = getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_dims")(self.capsule) - - getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_config").argtypes = [c_void_p] - getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_config").restype = c_void_p - self.nlp_config = getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_config")(self.capsule) - - getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_out").argtypes = [c_void_p] - getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_out").restype = c_void_p - self.nlp_out = getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_out")(self.capsule) - - getattr(self.shared_lib, f"{self.model_name}_acados_get_sens_out").argtypes = [c_void_p] - getattr(self.shared_lib, f"{self.model_name}_acados_get_sens_out").restype = c_void_p - self.sens_out = getattr(self.shared_lib, f"{self.model_name}_acados_get_sens_out")(self.capsule) - - getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_in").argtypes = [c_void_p] - getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_in").restype = c_void_p - self.nlp_in = getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_in")(self.capsule) - - getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_solver").argtypes = [c_void_p] - getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_solver").restype = c_void_p - self.nlp_solver = getattr(self.shared_lib, f"{self.model_name}_acados_get_nlp_solver")(self.capsule) - - - - def solve_for_x0(self, x0_bar): - """ - Wrapper around `solve()` which sets initial state constraint, solves the OCP, and returns u0. - """ - self.set(0, "lbx", x0_bar) - self.set(0, "ubx", x0_bar) - - status = self.solve() - - if status == 2: - print("Warning: acados_ocp_solver reached maximum iterations.") - elif status != 0: - raise Exception(f'acados acados_ocp_solver returned status {status}') - - u0 = self.get(0, "u") - return u0 - - - def solve(self): - """ - Solve the ocp with current input. - """ - getattr(self.shared_lib, f"{self.model_name}_acados_solve").argtypes = [c_void_p] - getattr(self.shared_lib, f"{self.model_name}_acados_solve").restype = c_int - self.status = getattr(self.shared_lib, f"{self.model_name}_acados_solve")(self.capsule) - - return self.status - - - def custom_update(self, data_: np.ndarray): - """ - A custom function that can be implemented by a user to be called between solver calls. - By default this does nothing. - The idea is to have a convenient wrapper to do complex updates of parameters and numerical data efficiently in C, - in a function that is compiled into the solver library and can be conveniently used in the Python environment. - """ - data = np.ascontiguousarray(data_, dtype=np.float64) - c_data = cast(data.ctypes.data, POINTER(c_double)) - data_len = len(data) - - getattr(self.shared_lib, f"{self.model_name}_acados_custom_update").argtypes = [c_void_p, POINTER(c_double), c_int] - getattr(self.shared_lib, f"{self.model_name}_acados_custom_update").restype = c_int - status = getattr(self.shared_lib, f"{self.model_name}_acados_custom_update")(self.capsule, c_data, data_len) - - return status - - - def reset(self, reset_qp_solver_mem=1): - """ - Sets current iterate to all zeros. - """ - getattr(self.shared_lib, f"{self.model_name}_acados_reset").argtypes = [c_void_p, c_int] - getattr(self.shared_lib, f"{self.model_name}_acados_reset").restype = c_int - getattr(self.shared_lib, f"{self.model_name}_acados_reset")(self.capsule, reset_qp_solver_mem) - - return - - - def set_new_time_steps(self, new_time_steps): - """ - Set new time steps. - Recreates the solver if N changes. - - :param new_time_steps: 1 dimensional np array of new time steps for the solver - - .. note:: This allows for different use-cases: either set a new size of time_steps or a new distribution of - the shooting nodes without changing the number, e.g., to reach a different final time. Both cases - do not require a new code export and compilation. - """ - - # unlikely but still possible - if not self.solver_created: - raise Exception('Solver was not yet created!') - - # check if time steps really changed in value - if np.array_equal(self.solver_options['time_steps'], new_time_steps): - return - - N = new_time_steps.size - new_time_steps_data = cast(new_time_steps.ctypes.data, POINTER(c_double)) - - # check if recreation of acados is necessary (no need to recreate acados if sizes are identical) - if len(self.solver_options['time_steps']) == N: - getattr(self.shared_lib, f"{self.model_name}_acados_update_time_steps").argtypes = [c_void_p, c_int, c_void_p] - getattr(self.shared_lib, f"{self.model_name}_acados_update_time_steps").restype = c_int - assert getattr(self.shared_lib, f"{self.model_name}_acados_update_time_steps")(self.capsule, N, new_time_steps_data) == 0 - else: # recreate the solver with the new time steps - self.solver_created = False - - # delete old memory (analog to __del__) - getattr(self.shared_lib, f"{self.model_name}_acados_free").argtypes = [c_void_p] - getattr(self.shared_lib, f"{self.model_name}_acados_free").restype = c_int - getattr(self.shared_lib, f"{self.model_name}_acados_free")(self.capsule) - - # create solver with new time steps - getattr(self.shared_lib, f"{self.model_name}_acados_create_with_discretization").argtypes = [c_void_p, c_int, c_void_p] - getattr(self.shared_lib, f"{self.model_name}_acados_create_with_discretization").restype = c_int - assert getattr(self.shared_lib, f"{self.model_name}_acados_create_with_discretization")(self.capsule, N, new_time_steps_data) == 0 - - self.solver_created = True - - # get pointers solver - self.__get_pointers_solver() - - # store time_steps, N - self.solver_options['time_steps'] = new_time_steps - self.N = N - self.solver_options['Tsim'] = self.solver_options['time_steps'][0] - - - def update_qp_solver_cond_N(self, qp_solver_cond_N: int): - """ - Recreate solver with new value `qp_solver_cond_N` with a partial condensing QP solver. - This function is relevant for code reuse, i.e., if either `set_new_time_steps(...)` is used or - the influence of a different `qp_solver_cond_N` is studied without code export and compilation. - :param qp_solver_cond_N: new number of condensing stages for the solver - - .. note:: This function can only be used in combination with a partial condensing QP solver. - - .. note:: After `set_new_time_steps(...)` is used and depending on the new number of time steps it might be - necessary to change `qp_solver_cond_N` as well (using this function), i.e., typically - `qp_solver_cond_N < N`. - """ - # unlikely but still possible - if not self.solver_created: - raise Exception('Solver was not yet created!') - if self.N < qp_solver_cond_N: - raise Exception('Setting qp_solver_cond_N to be larger than N does not work!') - if self.solver_options['qp_solver_cond_N'] != qp_solver_cond_N: - self.solver_created = False - - # recreate the solver - fun_name = f'{self.model_name}_acados_update_qp_solver_cond_N' - getattr(self.shared_lib, fun_name).argtypes = [c_void_p, c_int] - getattr(self.shared_lib, fun_name).restype = c_int - assert getattr(self.shared_lib, fun_name)(self.capsule, qp_solver_cond_N) == 0 - - # store the new value - self.solver_options['qp_solver_cond_N'] = qp_solver_cond_N - self.solver_created = True - - # get pointers solver - self.__get_pointers_solver() - - - def eval_param_sens(self, index, stage=0, field="ex"): - """ - Calculate the sensitivity of the curent solution with respect to the initial state component of index - - :param index: integer corresponding to initial state index in range(nx) - """ - - field_ = field - field = field_.encode('utf-8') - - # checks - if not isinstance(index, int): - raise Exception('AcadosOcpSolver.eval_param_sens(): index must be Integer.') - - self.shared_lib.ocp_nlp_dims_get_from_attr.argtypes = [c_void_p, c_void_p, c_void_p, c_int, c_char_p] - self.shared_lib.ocp_nlp_dims_get_from_attr.restype = c_int - nx = self.shared_lib.ocp_nlp_dims_get_from_attr(self.nlp_config, self.nlp_dims, self.nlp_out, 0, "x".encode('utf-8')) - - if index < 0 or index > nx: - raise Exception(f'AcadosOcpSolver.eval_param_sens(): index must be in [0, nx-1], got: {index}.') - - # actual eval_param - self.shared_lib.ocp_nlp_eval_param_sens.argtypes = [c_void_p, c_char_p, c_int, c_int, c_void_p] - self.shared_lib.ocp_nlp_eval_param_sens.restype = None - self.shared_lib.ocp_nlp_eval_param_sens(self.nlp_solver, field, stage, index, self.sens_out) - - return - - - def get(self, stage_, field_): - """ - Get the last solution of the solver: - - :param stage: integer corresponding to shooting node - :param field: string in ['x', 'u', 'z', 'pi', 'lam', 't', 'sl', 'su',] - - .. note:: regarding lam, t: \n - the inequalities are internally organized in the following order: \n - [ lbu lbx lg lh lphi ubu ubx ug uh uphi; \n - lsbu lsbx lsg lsh lsphi usbu usbx usg ush usphi] - - .. note:: pi: multipliers for dynamics equality constraints \n - lam: multipliers for inequalities \n - t: slack variables corresponding to evaluation of all inequalities (at the solution) \n - sl: slack variables of soft lower inequality constraints \n - su: slack variables of soft upper inequality constraints \n - """ - - out_fields = ['x', 'u', 'z', 'pi', 'lam', 't', 'sl', 'su'] - # mem_fields = ['sl', 'su'] - sens_fields = ['sens_u', "sens_x"] - all_fields = out_fields + sens_fields - - field = field_ - - if (field_ not in all_fields): - raise Exception(f'AcadosOcpSolver.get(stage={stage_}, field={field_}): \'{field_}\' is an invalid argument.\ - \n Possible values are {all_fields}.') - - if not isinstance(stage_, int): - raise Exception(f'AcadosOcpSolver.get(stage={stage_}, field={field_}): stage index must be an integer, got type {type(stage_)}.') - - if stage_ < 0 or stage_ > self.N: - raise Exception(f'AcadosOcpSolver.get(stage={stage_}, field={field_}): stage index must be in [0, {self.N}], got: {stage_}.') - - if stage_ == self.N and field_ == 'pi': - raise Exception(f'AcadosOcpSolver.get(stage={stage_}, field={field_}): field \'{field_}\' does not exist at final stage {stage_}.') - - if field_ in sens_fields: - field = field_.replace('sens_', '') - - field = field.encode('utf-8') - - self.shared_lib.ocp_nlp_dims_get_from_attr.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_char_p] - self.shared_lib.ocp_nlp_dims_get_from_attr.restype = c_int - - dims = self.shared_lib.ocp_nlp_dims_get_from_attr(self.nlp_config, \ - self.nlp_dims, self.nlp_out, stage_, field) - - out = np.ascontiguousarray(np.zeros((dims,)), dtype=np.float64) - out_data = cast(out.ctypes.data, POINTER(c_double)) - - if (field_ in out_fields): - self.shared_lib.ocp_nlp_out_get.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] - self.shared_lib.ocp_nlp_out_get(self.nlp_config, \ - self.nlp_dims, self.nlp_out, stage_, field, out_data) - # elif field_ in mem_fields: - # self.shared_lib.ocp_nlp_get_at_stage.argtypes = \ - # [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] - # self.shared_lib.ocp_nlp_get_at_stage(self.nlp_config, \ - # self.nlp_dims, self.nlp_solver, stage_, field, out_data) - elif field_ in sens_fields: - self.shared_lib.ocp_nlp_out_get.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] - self.shared_lib.ocp_nlp_out_get(self.nlp_config, \ - self.nlp_dims, self.sens_out, stage_, field, out_data) - - return out - - - def print_statistics(self): - """ - prints statistics of previous solver run as a table: - - iter: iteration number - - res_stat: stationarity residual - - res_eq: residual wrt equality constraints (dynamics) - - res_ineq: residual wrt inequality constraints (constraints) - - res_comp: residual wrt complementarity conditions - - qp_stat: status of QP solver - - qp_iter: number of QP iterations - - alpha: SQP step size - - qp_res_stat: stationarity residual of the last QP solution - - qp_res_eq: residual wrt equality constraints (dynamics) of the last QP solution - - qp_res_ineq: residual wrt inequality constraints (constraints) of the last QP solution - - qp_res_comp: residual wrt complementarity conditions of the last QP solution - """ - stat = self.get_stats("statistics") - - if self.solver_options['nlp_solver_type'] == 'SQP': - print('\niter\tres_stat\tres_eq\t\tres_ineq\tres_comp\tqp_stat\tqp_iter\talpha') - if stat.shape[0]>8: - print('\tqp_res_stat\tqp_res_eq\tqp_res_ineq\tqp_res_comp') - for jj in range(stat.shape[1]): - print(f'{int(stat[0][jj]):d}\t{stat[1][jj]:e}\t{stat[2][jj]:e}\t{stat[3][jj]:e}\t' + - f'{stat[4][jj]:e}\t{int(stat[5][jj]):d}\t{int(stat[6][jj]):d}\t{stat[7][jj]:e}\t') - if stat.shape[0]>8: - print('\t{:e}\t{:e}\t{:e}\t{:e}'.format( \ - stat[8][jj], stat[9][jj], stat[10][jj], stat[11][jj])) - print('\n') - elif self.solver_options['nlp_solver_type'] == 'SQP_RTI': - print('\niter\tqp_stat\tqp_iter') - if stat.shape[0]>3: - print('\tqp_res_stat\tqp_res_eq\tqp_res_ineq\tqp_res_comp') - for jj in range(stat.shape[1]): - print('{:d}\t{:d}\t{:d}'.format( int(stat[0][jj]), int(stat[1][jj]), int(stat[2][jj]))) - if stat.shape[0]>3: - print('\t{:e}\t{:e}\t{:e}\t{:e}'.format( \ - stat[3][jj], stat[4][jj], stat[5][jj], stat[6][jj])) - print('\n') - - return - - - def store_iterate(self, filename: str = '', overwrite=False): - """ - Stores the current iterate of the ocp solver in a json file. - - :param filename: if not set, use f'{self.model_name}_iterate.json' - :param overwrite: if false and filename exists add timestamp to filename - """ - if filename == '': - filename = f'{self.model_name}_iterate.json' - - if not overwrite: - # append timestamp - if os.path.isfile(filename): - filename = filename[:-5] - filename += datetime.utcnow().strftime('%Y-%m-%d-%H:%M:%S.%f') + '.json' - - # get iterate: - solution = dict() - - lN = len(str(self.N+1)) - for i in range(self.N+1): - i_string = f'{i:0{lN}d}' - solution['x_'+i_string] = self.get(i,'x') - solution['u_'+i_string] = self.get(i,'u') - solution['z_'+i_string] = self.get(i,'z') - solution['lam_'+i_string] = self.get(i,'lam') - solution['t_'+i_string] = self.get(i, 't') - solution['sl_'+i_string] = self.get(i, 'sl') - solution['su_'+i_string] = self.get(i, 'su') - if i < self.N: - solution['pi_'+i_string] = self.get(i,'pi') - - for k in list(solution.keys()): - if len(solution[k]) == 0: - del solution[k] - - # save - with open(filename, 'w') as f: - json.dump(solution, f, default=make_object_json_dumpable, indent=4, sort_keys=True) - print("stored current iterate in ", os.path.join(os.getcwd(), filename)) - - - - def dump_last_qp_to_json(self, filename: str = '', overwrite=False): - """ - Dumps the latest QP data into a json file - - :param filename: if not set, use model_name + timestamp + '.json' - :param overwrite: if false and filename exists add timestamp to filename - """ - if filename == '': - filename = f'{self.model_name}_QP.json' - - if not overwrite: - # append timestamp - if os.path.isfile(filename): - filename = filename[:-5] - filename += datetime.utcnow().strftime('%Y-%m-%d-%H:%M:%S.%f') + '.json' - - # get QP data: - qp_data = dict() - - lN = len(str(self.N+1)) - for field in self.__qp_dynamics_fields: - for i in range(self.N): - qp_data[f'{field}_{i:0{lN}d}'] = self.get_from_qp_in(i,field) - - for field in self.__qp_constraint_fields + self.__qp_cost_fields: - for i in range(self.N+1): - qp_data[f'{field}_{i:0{lN}d}'] = self.get_from_qp_in(i,field) - - # remove empty fields - for k in list(qp_data.keys()): - if len(qp_data[k]) == 0: - del qp_data[k] - - # save - with open(filename, 'w') as f: - json.dump(qp_data, f, default=make_object_json_dumpable, indent=4, sort_keys=True) - print("stored qp from solver memory in ", os.path.join(os.getcwd(), filename)) - - - - def load_iterate(self, filename): - """ - Loads the iterate stored in json file with filename into the ocp solver. - """ - if not os.path.isfile(filename): - raise Exception('load_iterate: failed, file does not exist: ' + os.path.join(os.getcwd(), filename)) - - with open(filename, 'r') as f: - solution = json.load(f) - - print(f"loading iterate {filename}") - for key in solution.keys(): - (field, stage) = key.split('_') - self.set(int(stage), field, np.array(solution[key])) - - - def get_stats(self, field_): - """ - Get the information of the last solver call. - - :param field: string in ['statistics', 'time_tot', 'time_lin', 'time_sim', 'time_sim_ad', 'time_sim_la', 'time_qp', 'time_qp_solver_call', 'time_reg', 'sqp_iter', 'residuals', 'qp_iter', 'alpha'] - - Available fileds: - - time_tot: total CPU time previous call - - time_lin: CPU time for linearization - - time_sim: CPU time for integrator - - time_sim_ad: CPU time for integrator contribution of external function calls - - time_sim_la: CPU time for integrator contribution of linear algebra - - time_qp: CPU time qp solution - - time_qp_solver_call: CPU time inside qp solver (without converting the QP) - - time_qp_xcond: time_glob: CPU time globalization - - time_solution_sensitivities: CPU time for previous call to eval_param_sens - - time_reg: CPU time regularization - - sqp_iter: number of SQP iterations - - qp_iter: vector of QP iterations for last SQP call - - statistics: table with info about last iteration - - stat_m: number of rows in statistics matrix - - stat_n: number of columns in statistics matrix - - residuals: residuals of last iterate - - alpha: step sizes of SQP iterations - """ - - double_fields = ['time_tot', - 'time_lin', - 'time_sim', - 'time_sim_ad', - 'time_sim_la', - 'time_qp', - 'time_qp_solver_call', - 'time_qp_xcond', - 'time_glob', - 'time_solution_sensitivities', - 'time_reg' - ] - fields = double_fields + [ - 'sqp_iter', - 'qp_iter', - 'statistics', - 'stat_m', - 'stat_n', - 'residuals', - 'alpha', - ] - field = field_.encode('utf-8') - - - if field_ in ['sqp_iter', 'stat_m', 'stat_n']: - out = np.ascontiguousarray(np.zeros((1,)), dtype=np.int64) - out_data = cast(out.ctypes.data, POINTER(c_int64)) - self.shared_lib.ocp_nlp_get.argtypes = [c_void_p, c_void_p, c_char_p, c_void_p] - self.shared_lib.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, out_data) - return out - - # TODO: just return double instead of np. - elif field_ in double_fields: - out = np.zeros((1,)) - out_data = cast(out.ctypes.data, POINTER(c_double)) - self.shared_lib.ocp_nlp_get.argtypes = [c_void_p, c_void_p, c_char_p, c_void_p] - self.shared_lib.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, out_data) - return out - - elif field_ == 'statistics': - sqp_iter = self.get_stats("sqp_iter") - stat_m = self.get_stats("stat_m") - stat_n = self.get_stats("stat_n") - min_size = min([stat_m, sqp_iter+1]) - out = np.ascontiguousarray( - np.zeros((stat_n[0]+1, min_size[0])), dtype=np.float64) - out_data = cast(out.ctypes.data, POINTER(c_double)) - self.shared_lib.ocp_nlp_get.argtypes = [c_void_p, c_void_p, c_char_p, c_void_p] - self.shared_lib.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, out_data) - return out - - elif field_ == 'qp_iter': - full_stats = self.get_stats('statistics') - if self.solver_options['nlp_solver_type'] == 'SQP': - return full_stats[6, :] - elif self.solver_options['nlp_solver_type'] == 'SQP_RTI': - return full_stats[2, :] - - elif field_ == 'alpha': - full_stats = self.get_stats('statistics') - if self.solver_options['nlp_solver_type'] == 'SQP': - return full_stats[7, :] - else: # self.solver_options['nlp_solver_type'] == 'SQP_RTI': - raise Exception("alpha values are not available for SQP_RTI") - - elif field_ == 'residuals': - return self.get_residuals() - - else: - raise Exception(f'AcadosOcpSolver.get_stats(): \'{field}\' is not a valid argument.' - + f'\n Possible values are {fields}.') - - - def get_cost(self): - """ - Returns the cost value of the current solution. - """ - # compute cost internally - self.shared_lib.ocp_nlp_eval_cost.argtypes = [c_void_p, c_void_p, c_void_p] - self.shared_lib.ocp_nlp_eval_cost(self.nlp_solver, self.nlp_in, self.nlp_out) - - # create output array - out = np.ascontiguousarray(np.zeros((1,)), dtype=np.float64) - out_data = cast(out.ctypes.data, POINTER(c_double)) - - # call getter - self.shared_lib.ocp_nlp_get.argtypes = [c_void_p, c_void_p, c_char_p, c_void_p] - - field = "cost_value".encode('utf-8') - self.shared_lib.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, out_data) - - return out[0] - - - def get_residuals(self, recompute=False): - """ - Returns an array of the form [res_stat, res_eq, res_ineq, res_comp]. - This residual has to be computed for SQP_RTI solver, since it is not available by default. - - - res_stat: stationarity residual - - res_eq: residual wrt equality constraints (dynamics) - - res_ineq: residual wrt inequality constraints (constraints) - - res_comp: residual wrt complementarity conditions - """ - # compute residuals if RTI - if self.solver_options['nlp_solver_type'] == 'SQP_RTI' or recompute: - self.shared_lib.ocp_nlp_eval_residuals.argtypes = [c_void_p, c_void_p, c_void_p] - self.shared_lib.ocp_nlp_eval_residuals(self.nlp_solver, self.nlp_in, self.nlp_out) - - # create output array - out = np.ascontiguousarray(np.zeros((4, 1)), dtype=np.float64) - out_data = cast(out.ctypes.data, POINTER(c_double)) - - # call getters - self.shared_lib.ocp_nlp_get.argtypes = [c_void_p, c_void_p, c_char_p, c_void_p] - - field = "res_stat".encode('utf-8') - self.shared_lib.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, out_data) - - out_data = cast(out[1].ctypes.data, POINTER(c_double)) - field = "res_eq".encode('utf-8') - self.shared_lib.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, out_data) - - out_data = cast(out[2].ctypes.data, POINTER(c_double)) - field = "res_ineq".encode('utf-8') - self.shared_lib.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, out_data) - - out_data = cast(out[3].ctypes.data, POINTER(c_double)) - field = "res_comp".encode('utf-8') - self.shared_lib.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, out_data) - return out.flatten() - - - # Note: this function should not be used anymore, better use cost_set, constraints_set - def set(self, stage_, field_, value_): - """ - Set numerical data inside the solver. - - :param stage: integer corresponding to shooting node - :param field: string in ['x', 'u', 'pi', 'lam', 't', 'p', 'xdot_guess', 'z_guess'] - - .. note:: regarding lam, t: \n - the inequalities are internally organized in the following order: \n - [ lbu lbx lg lh lphi ubu ubx ug uh uphi; \n - lsbu lsbx lsg lsh lsphi usbu usbx usg ush usphi] - - .. note:: pi: multipliers for dynamics equality constraints \n - lam: multipliers for inequalities \n - t: slack variables corresponding to evaluation of all inequalities (at the solution) \n - sl: slack variables of soft lower inequality constraints \n - su: slack variables of soft upper inequality constraints \n - """ - cost_fields = ['y_ref', 'yref'] - constraints_fields = ['lbx', 'ubx', 'lbu', 'ubu'] - out_fields = ['x', 'u', 'pi', 'lam', 't', 'z', 'sl', 'su'] - mem_fields = ['xdot_guess', 'z_guess'] - - # cast value_ to avoid conversion issues - if isinstance(value_, (float, int)): - value_ = np.array([value_]) - value_ = value_.astype(float) - - field = field_.encode('utf-8') - - stage = c_int(stage_) - - # treat parameters separately - if field_ == 'p': - getattr(self.shared_lib, f"{self.model_name}_acados_update_params").argtypes = [c_void_p, c_int, POINTER(c_double), c_int] - getattr(self.shared_lib, f"{self.model_name}_acados_update_params").restype = c_int - - value_data = cast(value_.ctypes.data, POINTER(c_double)) - - assert getattr(self.shared_lib, f"{self.model_name}_acados_update_params")(self.capsule, stage, value_data, value_.shape[0])==0 - else: - if field_ not in constraints_fields + cost_fields + out_fields + mem_fields: - raise Exception(f"AcadosOcpSolver.set(): '{field}' is not a valid argument.\n" - f" Possible values are {constraints_fields + cost_fields + out_fields + mem_fields + ['p']}.") - - self.shared_lib.ocp_nlp_dims_get_from_attr.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_char_p] - self.shared_lib.ocp_nlp_dims_get_from_attr.restype = c_int - - dims = self.shared_lib.ocp_nlp_dims_get_from_attr(self.nlp_config, \ - self.nlp_dims, self.nlp_out, stage_, field) - - if value_.shape[0] != dims: - msg = f'AcadosOcpSolver.set(): mismatching dimension for field "{field_}" ' - msg += f'with dimension {dims} (you have {value_.shape[0]})' - raise Exception(msg) - - value_data = cast(value_.ctypes.data, POINTER(c_double)) - value_data_p = cast((value_data), c_void_p) - - if field_ in constraints_fields: - self.shared_lib.ocp_nlp_constraints_model_set.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] - self.shared_lib.ocp_nlp_constraints_model_set(self.nlp_config, \ - self.nlp_dims, self.nlp_in, stage, field, value_data_p) - elif field_ in cost_fields: - self.shared_lib.ocp_nlp_cost_model_set.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] - self.shared_lib.ocp_nlp_cost_model_set(self.nlp_config, \ - self.nlp_dims, self.nlp_in, stage, field, value_data_p) - elif field_ in out_fields: - self.shared_lib.ocp_nlp_out_set.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] - self.shared_lib.ocp_nlp_out_set(self.nlp_config, \ - self.nlp_dims, self.nlp_out, stage, field, value_data_p) - elif field_ in mem_fields: - self.shared_lib.ocp_nlp_set.argtypes = \ - [c_void_p, c_void_p, c_int, c_char_p, c_void_p] - self.shared_lib.ocp_nlp_set(self.nlp_config, \ - self.nlp_solver, stage, field, value_data_p) - # also set z_guess, when setting z. - if field_ == 'z': - field = 'z_guess'.encode('utf-8') - self.shared_lib.ocp_nlp_set.argtypes = \ - [c_void_p, c_void_p, c_int, c_char_p, c_void_p] - self.shared_lib.ocp_nlp_set(self.nlp_config, \ - self.nlp_solver, stage, field, value_data_p) - return - - - def cost_set(self, stage_, field_, value_, api='warn'): - """ - Set numerical data in the cost module of the solver. - - :param stage: integer corresponding to shooting node - :param field: string, e.g. 'yref', 'W', 'ext_cost_num_hess', 'zl', 'zu', 'Zl', 'Zu' - :param value: of appropriate size - """ - # cast value_ to avoid conversion issues - if isinstance(value_, (float, int)): - value_ = np.array([value_]) - value_ = value_.astype(float) - - field = field_ - field = field.encode('utf-8') - - stage = c_int(stage_) - self.shared_lib.ocp_nlp_cost_dims_get_from_attr.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_char_p, POINTER(c_int)] - self.shared_lib.ocp_nlp_cost_dims_get_from_attr.restype = c_int - - dims = np.ascontiguousarray(np.zeros((2,)), dtype=np.intc) - dims_data = cast(dims.ctypes.data, POINTER(c_int)) - - self.shared_lib.ocp_nlp_cost_dims_get_from_attr(self.nlp_config, \ - self.nlp_dims, self.nlp_out, stage_, field, dims_data) - - value_shape = value_.shape - if len(value_shape) == 1: - value_shape = (value_shape[0], 0) - - elif len(value_shape) == 2: - if api=='old': - pass - elif api=='warn': - if not np.all(np.ravel(value_, order='F')==np.ravel(value_, order='K')): - raise Exception("Ambiguity in API detected.\n" - "Are you making an acados model from scrach? Add api='new' to cost_set and carry on.\n" - "Are you seeing this error suddenly in previously running code? Read on.\n" - f" You are relying on a now-fixed bug in cost_set for field '{field_}'.\n" + - " acados_template now correctly passes on any matrices to acados in column major format.\n" + - " Two options to fix this error: \n" + - " * Add api='old' to cost_set to restore old incorrect behaviour\n" + - " * Add api='new' to cost_set and remove any unnatural manipulation of the value argument " + - "such as non-mathematical transposes, reshaping, casting to fortran order, etc... " + - "If there is no such manipulation, then you have probably been getting an incorrect solution before.") - # Get elements in column major order - value_ = np.ravel(value_, order='F') - elif api=='new': - # Get elements in column major order - value_ = np.ravel(value_, order='F') - else: - raise Exception("Unknown api: '{}'".format(api)) - - if value_shape != tuple(dims): - raise Exception('AcadosOcpSolver.cost_set(): mismatching dimension' + - f' for field "{field_}" at stage {stage} with dimension {tuple(dims)} (you have {value_shape})') - - value_data = cast(value_.ctypes.data, POINTER(c_double)) - value_data_p = cast((value_data), c_void_p) - - self.shared_lib.ocp_nlp_cost_model_set.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] - self.shared_lib.ocp_nlp_cost_model_set(self.nlp_config, \ - self.nlp_dims, self.nlp_in, stage, field, value_data_p) - - return - - - def constraints_set(self, stage_, field_, value_, api='warn'): - """ - Set numerical data in the constraint module of the solver. - - :param stage: integer corresponding to shooting node - :param field: string in ['lbx', 'ubx', 'lbu', 'ubu', 'lg', 'ug', 'lh', 'uh', 'uphi', 'C', 'D'] - :param value: of appropriate size - """ - # cast value_ to avoid conversion issues - if isinstance(value_, (float, int)): - value_ = np.array([value_]) - value_ = value_.astype(float) - - field = field_ - field = field.encode('utf-8') - - stage = c_int(stage_) - self.shared_lib.ocp_nlp_constraint_dims_get_from_attr.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_char_p, POINTER(c_int)] - self.shared_lib.ocp_nlp_constraint_dims_get_from_attr.restype = c_int - - dims = np.ascontiguousarray(np.zeros((2,)), dtype=np.intc) - dims_data = cast(dims.ctypes.data, POINTER(c_int)) - - self.shared_lib.ocp_nlp_constraint_dims_get_from_attr(self.nlp_config, \ - self.nlp_dims, self.nlp_out, stage_, field, dims_data) - - value_shape = value_.shape - if len(value_shape) == 1: - value_shape = (value_shape[0], 0) - elif len(value_shape) == 2: - if api=='old': - pass - elif api=='warn': - if not np.all(np.ravel(value_, order='F')==np.ravel(value_, order='K')): - raise Exception("Ambiguity in API detected.\n" - "Are you making an acados model from scrach? Add api='new' to constraints_set and carry on.\n" - "Are you seeing this error suddenly in previously running code? Read on.\n" - f" You are relying on a now-fixed bug in constraints_set for field '{field}'.\n" + - " acados_template now correctly passes on any matrices to acados in column major format.\n" + - " Two options to fix this error: \n" + - " * Add api='old' to constraints_set to restore old incorrect behaviour\n" + - " * Add api='new' to constraints_set and remove any unnatural manipulation of the value argument " + - "such as non-mathematical transposes, reshaping, casting to fortran order, etc... " + - "If there is no such manipulation, then you have probably been getting an incorrect solution before.") - # Get elements in column major order - value_ = np.ravel(value_, order='F') - elif api=='new': - # Get elements in column major order - value_ = np.ravel(value_, order='F') - else: - raise Exception(f"Unknown api: '{api}'") - - if value_shape != tuple(dims): - raise Exception(f'AcadosOcpSolver.constraints_set(): mismatching dimension' + - f' for field "{field_}" at stage {stage} with dimension {tuple(dims)} (you have {value_shape})') - - value_data = cast(value_.ctypes.data, POINTER(c_double)) - value_data_p = cast((value_data), c_void_p) - - self.shared_lib.ocp_nlp_constraints_model_set.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] - self.shared_lib.ocp_nlp_constraints_model_set(self.nlp_config, \ - self.nlp_dims, self.nlp_in, stage, field, value_data_p) - - return - - - def get_from_qp_in(self, stage_: int, field_: str): - """ - Get numerical data from the current QP. - - :param stage: integer corresponding to shooting node - :param field: string in ['A', 'B', 'b', 'Q', 'R', 'S', 'q', 'r', 'C', 'D', 'lg', 'ug', 'lbx', 'ubx', 'lbu', 'ubu'] - """ - # idx* should be added too.. - if not isinstance(stage_, int): - raise TypeError("stage should be int") - if stage_ > self.N: - raise Exception("stage should be <= self.N") - if field_ in self.__qp_dynamics_fields and stage_ >= self.N: - raise ValueError(f"dynamics field {field_} not available at terminal stage") - if field_ not in self.__qp_dynamics_fields + self.__qp_cost_fields + self.__qp_constraint_fields: - raise Exception(f"field {field_} not supported.") - - field = field_.encode('utf-8') - stage = c_int(stage_) - - # get dims - self.shared_lib.ocp_nlp_qp_dims_get_from_attr.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_char_p, POINTER(c_int)] - self.shared_lib.ocp_nlp_qp_dims_get_from_attr.restype = c_int - - dims = np.ascontiguousarray(np.zeros((2,)), dtype=np.intc) - dims_data = cast(dims.ctypes.data, POINTER(c_int)) - - self.shared_lib.ocp_nlp_qp_dims_get_from_attr(self.nlp_config, \ - self.nlp_dims, self.nlp_out, stage_, field, dims_data) - - # create output data - out = np.ascontiguousarray(np.zeros((np.prod(dims),)), dtype=np.float64) - out = out.reshape(dims[0], dims[1], order='F') - - out_data = cast(out.ctypes.data, POINTER(c_double)) - out_data_p = cast((out_data), c_void_p) - - # call getter - self.shared_lib.ocp_nlp_get_at_stage.argtypes = \ - [c_void_p, c_void_p, c_void_p, c_int, c_char_p, c_void_p] - self.shared_lib.ocp_nlp_get_at_stage(self.nlp_config, \ - self.nlp_dims, self.nlp_solver, stage, field, out_data_p) - - return out - - - def options_set(self, field_, value_): - """ - Set options of the solver. - - :param field: string, e.g. 'print_level', 'rti_phase', 'initialize_t_slacks', 'step_length', 'alpha_min', 'alpha_reduction', 'qp_warm_start', 'line_search_use_sufficient_descent', 'full_step_dual', 'globalization_use_SOC', 'qp_tol_stat', 'qp_tol_eq', 'qp_tol_ineq', 'qp_tol_comp', 'qp_tau_min', 'qp_mu0' - - :param value: of type int, float, string - - - qp_tol_stat: QP solver tolerance stationarity - - qp_tol_eq: QP solver tolerance equalities - - qp_tol_ineq: QP solver tolerance inequalities - - qp_tol_comp: QP solver tolerance complementarity - - qp_tau_min: for HPIPM QP solvers: minimum value of barrier parameter in HPIPM - - qp_mu0: for HPIPM QP solvers: initial value for complementarity slackness - - warm_start_first_qp: indicates if first QP in SQP is warm_started - """ - int_fields = ['print_level', 'rti_phase', 'initialize_t_slacks', 'qp_warm_start', - 'line_search_use_sufficient_descent', 'full_step_dual', 'globalization_use_SOC', 'warm_start_first_qp'] - double_fields = ['step_length', 'tol_eq', 'tol_stat', 'tol_ineq', 'tol_comp', 'alpha_min', 'alpha_reduction', - 'eps_sufficient_descent', 'qp_tol_stat', 'qp_tol_eq', 'qp_tol_ineq', 'qp_tol_comp', 'qp_tau_min', 'qp_mu0'] - string_fields = ['globalization'] - - # check field availability and type - if field_ in int_fields: - if not isinstance(value_, int): - raise Exception(f'solver option \'{field_}\' must be of type int. You have {type(value_)}.') - else: - value_ctypes = c_int(value_) - - elif field_ in double_fields: - if not isinstance(value_, float): - raise Exception(f'solver option \'{field_}\' must be of type float. You have {type(value_)}.') - else: - value_ctypes = c_double(value_) - - elif field_ in string_fields: - if not isinstance(value_, str): - raise Exception(f'solver option \'{field_}\' must be of type str. You have {type(value_)}.') - else: - value_ctypes = value_.encode('utf-8') - else: - fields = ', '.join(int_fields + double_fields + string_fields) - raise Exception(f'AcadosOcpSolver.options_set() does not support field \'{field_}\'.\n'\ - f' Possible values are {fields}.') - - - if field_ == 'rti_phase': - if value_ < 0 or value_ > 2: - raise Exception('AcadosOcpSolver.options_set(): argument \'rti_phase\' can ' - 'take only values 0, 1, 2 for SQP-RTI-type solvers') - if self.solver_options['nlp_solver_type'] != 'SQP_RTI' and value_ > 0: - raise Exception('AcadosOcpSolver.options_set(): argument \'rti_phase\' can ' - 'take only value 0 for SQP-type solvers') - - # encode - field = field_ - field = field.encode('utf-8') - - # call C interface - if field_ in string_fields: - self.shared_lib.ocp_nlp_solver_opts_set.argtypes = \ - [c_void_p, c_void_p, c_char_p, c_char_p] - self.shared_lib.ocp_nlp_solver_opts_set(self.nlp_config, \ - self.nlp_opts, field, value_ctypes) - else: - self.shared_lib.ocp_nlp_solver_opts_set.argtypes = \ - [c_void_p, c_void_p, c_char_p, c_void_p] - self.shared_lib.ocp_nlp_solver_opts_set(self.nlp_config, \ - self.nlp_opts, field, byref(value_ctypes)) - return - - - def set_params_sparse(self, stage_, idx_values_, param_values_): - """ - set parameters of the solvers external function partially: - Pseudo: solver.param[idx_values_] = param_values_; - Parameters: - :param stage_: integer corresponding to shooting node - :param idx_values_: 0 based np array (or iterable) of integers: indices of parameter to be set - :param param_values_: new parameter values as numpy array - """ - - # if not isinstance(idx_values_, np.ndarray) or not issubclass(type(idx_values_[0]), np.integer): - # raise Exception('idx_values_ must be np.array of integers.') - - if not isinstance(param_values_, np.ndarray): - raise Exception('param_values_ must be np.array.') - elif np.float64 != param_values_.dtype: - raise TypeError('param_values_ must be np.array of float64.') - - if param_values_.shape[0] != len(idx_values_): - raise Exception(f'param_values_ and idx_values_ must be of the same size.' + - f' Got sizes idx {param_values_.shape[0]}, param_values {len(idx_values_)}.') - - if any(idx_values_ >= self.acados_ocp.dims.np): - raise Exception(f'idx_values_ contains value >= np = {self.acados_ocp.dims.np}') - - stage = c_int(stage_) - n_update = c_int(len(param_values_)) - - param_data = cast(param_values_.ctypes.data, POINTER(c_double)) - c_idx_values = np.ascontiguousarray(idx_values_, dtype=np.intc) - idx_data = cast(c_idx_values.ctypes.data, POINTER(c_int)) - - getattr(self.shared_lib, f"{self.model_name}_acados_update_params_sparse").argtypes = \ - [c_void_p, c_int, POINTER(c_int), POINTER(c_double), c_int] - getattr(self.shared_lib, f"{self.model_name}_acados_update_params_sparse").restype = c_int - getattr(self.shared_lib, f"{self.model_name}_acados_update_params_sparse") \ - (self.capsule, stage, idx_data, param_data, n_update) - - def __del__(self): - if self.solver_created: - getattr(self.shared_lib, f"{self.model_name}_acados_free").argtypes = [c_void_p] - getattr(self.shared_lib, f"{self.model_name}_acados_free").restype = c_int - getattr(self.shared_lib, f"{self.model_name}_acados_free")(self.capsule) - - getattr(self.shared_lib, f"{self.model_name}_acados_free_capsule").argtypes = [c_void_p] - getattr(self.shared_lib, f"{self.model_name}_acados_free_capsule").restype = c_int - getattr(self.shared_lib, f"{self.model_name}_acados_free_capsule")(self.capsule) - - try: - self.dlclose(self.shared_lib._handle) - except: - print(f"WARNING: acados Python interface could not close shared_lib handle of AcadosOcpSolver {self.model_name}.\n", - "Attempting to create a new one with the same name will likely result in the old one being used!") - pass diff --git a/third_party/acados/acados_template/acados_ocp_solver_pyx.pyx b/third_party/acados/acados_template/acados_ocp_solver_pyx.pyx deleted file mode 100644 index acd7f02d0a..0000000000 --- a/third_party/acados/acados_template/acados_ocp_solver_pyx.pyx +++ /dev/null @@ -1,795 +0,0 @@ -# -*- coding: future_fstrings -*- -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# 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. -# -# 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.; -# -# cython: language_level=3 -# cython: profile=False -# distutils: language=c - -cimport cython -from libc cimport string - -cimport acados_solver_common -# TODO: make this import more clear? it is not a general solver, but problem specific. -cimport acados_solver - -cimport numpy as cnp - -import os -from datetime import datetime -import numpy as np - - -cdef class AcadosOcpSolverCython: - """ - Class to interact with the acados ocp solver C object. - """ - - cdef acados_solver.nlp_solver_capsule *capsule - cdef void *nlp_opts - cdef acados_solver_common.ocp_nlp_dims *nlp_dims - cdef acados_solver_common.ocp_nlp_config *nlp_config - cdef acados_solver_common.ocp_nlp_out *nlp_out - cdef acados_solver_common.ocp_nlp_out *sens_out - cdef acados_solver_common.ocp_nlp_in *nlp_in - cdef acados_solver_common.ocp_nlp_solver *nlp_solver - - cdef bint solver_created - - cdef str model_name - cdef int N - - cdef str nlp_solver_type - - def __cinit__(self, model_name, nlp_solver_type, N): - - self.solver_created = False - - self.N = N - self.model_name = model_name - self.nlp_solver_type = nlp_solver_type - - # create capsule - self.capsule = acados_solver.acados_create_capsule() - - # create solver - assert acados_solver.acados_create(self.capsule) == 0 - self.solver_created = True - - # get pointers solver - self.__get_pointers_solver() - - - def __get_pointers_solver(self): - """ - Private function to get the pointers for solver - """ - # get pointers solver - self.nlp_opts = acados_solver.acados_get_nlp_opts(self.capsule) - self.nlp_dims = acados_solver.acados_get_nlp_dims(self.capsule) - self.nlp_config = acados_solver.acados_get_nlp_config(self.capsule) - self.nlp_out = acados_solver.acados_get_nlp_out(self.capsule) - self.sens_out = acados_solver.acados_get_sens_out(self.capsule) - self.nlp_in = acados_solver.acados_get_nlp_in(self.capsule) - self.nlp_solver = acados_solver.acados_get_nlp_solver(self.capsule) - - - def solve_for_x0(self, x0_bar): - """ - Wrapper around `solve()` which sets initial state constraint, solves the OCP, and returns u0. - """ - self.set(0, "lbx", x0_bar) - self.set(0, "ubx", x0_bar) - - status = self.solve() - - if status == 2: - print("Warning: acados_ocp_solver reached maximum iterations.") - elif status != 0: - raise Exception(f'acados acados_ocp_solver returned status {status}') - - u0 = self.get(0, "u") - return u0 - - - def solve(self): - """ - Solve the ocp with current input. - """ - return acados_solver.acados_solve(self.capsule) - - - def reset(self, reset_qp_solver_mem=1): - """ - Sets current iterate to all zeros. - """ - return acados_solver.acados_reset(self.capsule, reset_qp_solver_mem) - - - def custom_update(self, data_): - """ - A custom function that can be implemented by a user to be called between solver calls. - By default this does nothing. - The idea is to have a convenient wrapper to do complex updates of parameters and numerical data efficiently in C, - in a function that is compiled into the solver library and can be conveniently used in the Python environment. - """ - data_len = len(data_) - cdef cnp.ndarray[cnp.float64_t, ndim=1] data = np.ascontiguousarray(data_, dtype=np.float64) - - return acados_solver.acados_custom_update(self.capsule, data.data, data_len) - - - def set_new_time_steps(self, new_time_steps): - """ - Set new time steps. - Recreates the solver if N changes. - - :param new_time_steps: 1 dimensional np array of new time steps for the solver - - .. note:: This allows for different use-cases: either set a new size of time-steps or a new distribution of - the shooting nodes without changing the number, e.g., to reach a different final time. Both cases - do not require a new code export and compilation. - """ - - raise NotImplementedError("AcadosOcpSolverCython: does not support set_new_time_steps() since it is only a prototyping feature") - # # unlikely but still possible - # if not self.solver_created: - # raise Exception('Solver was not yet created!') - - # ## check if time steps really changed in value - # # get time steps - # cdef cnp.ndarray[cnp.float64_t, ndim=1] old_time_steps = np.ascontiguousarray(np.zeros((self.N,)), dtype=np.float64) - # assert acados_solver.acados_get_time_steps(self.capsule, self.N, old_time_steps.data) - - # if np.array_equal(old_time_steps, new_time_steps): - # return - - # N = new_time_steps.size - # cdef cnp.ndarray[cnp.float64_t, ndim=1] value = np.ascontiguousarray(new_time_steps, dtype=np.float64) - - # # check if recreation of acados is necessary (no need to recreate acados if sizes are identical) - # if len(old_time_steps) == N: - # assert acados_solver.acados_update_time_steps(self.capsule, N, value.data) == 0 - - # else: # recreate the solver with the new time steps - # self.solver_created = False - - # # delete old memory (analog to __del__) - # acados_solver.acados_free(self.capsule) - - # # create solver with new time steps - # assert acados_solver.acados_create_with_discretization(self.capsule, N, value.data) == 0 - - # self.solver_created = True - - # # get pointers solver - # self.__get_pointers_solver() - - # # store time_steps, N - # self.time_steps = new_time_steps - # self.N = N - - - def update_qp_solver_cond_N(self, qp_solver_cond_N: int): - """ - Recreate solver with new value `qp_solver_cond_N` with a partial condensing QP solver. - This function is relevant for code reuse, i.e., if either `set_new_time_steps(...)` is used or - the influence of a different `qp_solver_cond_N` is studied without code export and compilation. - :param qp_solver_cond_N: new number of condensing stages for the solver - - .. note:: This function can only be used in combination with a partial condensing QP solver. - - .. note:: After `set_new_time_steps(...)` is used and depending on the new number of time steps it might be - necessary to change `qp_solver_cond_N` as well (using this function), i.e., typically - `qp_solver_cond_N < N`. - """ - raise NotImplementedError("AcadosOcpSolverCython: does not support update_qp_solver_cond_N() since it is only a prototyping feature") - - # # unlikely but still possible - # if not self.solver_created: - # raise Exception('Solver was not yet created!') - # if self.N < qp_solver_cond_N: - # raise Exception('Setting qp_solver_cond_N to be larger than N does not work!') - # if self.qp_solver_cond_N != qp_solver_cond_N: - # self.solver_created = False - - # # recreate the solver - # acados_solver.acados_update_qp_solver_cond_N(self.capsule, qp_solver_cond_N) - - # # store the new value - # self.qp_solver_cond_N = qp_solver_cond_N - # self.solver_created = True - - # # get pointers solver - # self.__get_pointers_solver() - - - def eval_param_sens(self, index, stage=0, field="ex"): - """ - Calculate the sensitivity of the curent solution with respect to the initial state component of index - - :param index: integer corresponding to initial state index in range(nx) - """ - - field_ = field - field = field_.encode('utf-8') - - # checks - if not isinstance(index, int): - raise Exception('AcadosOcpSolverCython.eval_param_sens(): index must be Integer.') - - cdef int nx = acados_solver_common.ocp_nlp_dims_get_from_attr(self.nlp_config, self.nlp_dims, self.nlp_out, 0, "x".encode('utf-8')) - - if index < 0 or index > nx: - raise Exception(f'AcadosOcpSolverCython.eval_param_sens(): index must be in [0, nx-1], got: {index}.') - - # actual eval_param - acados_solver_common.ocp_nlp_eval_param_sens(self.nlp_solver, field, stage, index, self.sens_out) - - return - - - def get(self, int stage, str field_): - """ - Get the last solution of the solver: - - :param stage: integer corresponding to shooting node - :param field: string in ['x', 'u', 'z', 'pi', 'lam', 't', 'sl', 'su',] - - .. note:: regarding lam, t: \n - the inequalities are internally organized in the following order: \n - [ lbu lbx lg lh lphi ubu ubx ug uh uphi; \n - lsbu lsbx lsg lsh lsphi usbu usbx usg ush usphi] - - .. note:: pi: multipliers for dynamics equality constraints \n - lam: multipliers for inequalities \n - t: slack variables corresponding to evaluation of all inequalities (at the solution) \n - sl: slack variables of soft lower inequality constraints \n - su: slack variables of soft upper inequality constraints \n - """ - - out_fields = ['x', 'u', 'z', 'pi', 'lam', 't', 'sl', 'su'] - field = field_.encode('utf-8') - - if field_ not in out_fields: - raise Exception('AcadosOcpSolverCython.get(): {} is an invalid argument.\ - \n Possible values are {}.'.format(field_, out_fields)) - - if stage < 0 or stage > self.N: - raise Exception('AcadosOcpSolverCython.get(): stage index must be in [0, N], got: {}.'.format(self.N)) - - if stage == self.N and field_ == 'pi': - raise Exception('AcadosOcpSolverCython.get(): field {} does not exist at final stage {}.'\ - .format(field_, stage)) - - cdef int dims = acados_solver_common.ocp_nlp_dims_get_from_attr(self.nlp_config, - self.nlp_dims, self.nlp_out, stage, field) - - cdef cnp.ndarray[cnp.float64_t, ndim=1] out = np.zeros((dims,)) - acados_solver_common.ocp_nlp_out_get(self.nlp_config, \ - self.nlp_dims, self.nlp_out, stage, field, out.data) - - return out - - - def print_statistics(self): - """ - prints statistics of previous solver run as a table: - - iter: iteration number - - res_stat: stationarity residual - - res_eq: residual wrt equality constraints (dynamics) - - res_ineq: residual wrt inequality constraints (constraints) - - res_comp: residual wrt complementarity conditions - - qp_stat: status of QP solver - - qp_iter: number of QP iterations - - qp_res_stat: stationarity residual of the last QP solution - - qp_res_eq: residual wrt equality constraints (dynamics) of the last QP solution - - qp_res_ineq: residual wrt inequality constraints (constraints) of the last QP solution - - qp_res_comp: residual wrt complementarity conditions of the last QP solution - """ - acados_solver.acados_print_stats(self.capsule) - - - def store_iterate(self, filename='', overwrite=False): - """ - Stores the current iterate of the ocp solver in a json file. - - :param filename: if not set, use model_name + timestamp + '.json' - :param overwrite: if false and filename exists add timestamp to filename - """ - import json - if filename == '': - filename += self.model_name + '_' + 'iterate' + '.json' - - if not overwrite: - # append timestamp - if os.path.isfile(filename): - filename = filename[:-5] - filename += datetime.utcnow().strftime('%Y-%m-%d-%H:%M:%S.%f') + '.json' - - # get iterate: - solution = dict() - - lN = len(str(self.N+1)) - for i in range(self.N+1): - i_string = f'{i:0{lN}d}' - solution['x_'+i_string] = self.get(i,'x') - solution['u_'+i_string] = self.get(i,'u') - solution['z_'+i_string] = self.get(i,'z') - solution['lam_'+i_string] = self.get(i,'lam') - solution['t_'+i_string] = self.get(i, 't') - solution['sl_'+i_string] = self.get(i, 'sl') - solution['su_'+i_string] = self.get(i, 'su') - if i < self.N: - solution['pi_'+i_string] = self.get(i,'pi') - - for k in list(solution.keys()): - if len(solution[k]) == 0: - del solution[k] - - # save - with open(filename, 'w') as f: - json.dump(solution, f, default=lambda x: x.tolist(), indent=4, sort_keys=True) - print("stored current iterate in ", os.path.join(os.getcwd(), filename)) - - - def load_iterate(self, filename): - """ - Loads the iterate stored in json file with filename into the ocp solver. - """ - import json - if not os.path.isfile(filename): - raise Exception('load_iterate: failed, file does not exist: ' + os.path.join(os.getcwd(), filename)) - - with open(filename, 'r') as f: - solution = json.load(f) - - for key in solution.keys(): - (field, stage) = key.split('_') - self.set(int(stage), field, np.array(solution[key])) - - - def get_stats(self, field_): - """ - Get the information of the last solver call. - - :param field: string in ['statistics', 'time_tot', 'time_lin', 'time_sim', 'time_sim_ad', 'time_sim_la', 'time_qp', 'time_qp_solver_call', 'time_reg', 'sqp_iter'] - Available fileds: - - time_tot: total CPU time previous call - - time_lin: CPU time for linearization - - time_sim: CPU time for integrator - - time_sim_ad: CPU time for integrator contribution of external function calls - - time_sim_la: CPU time for integrator contribution of linear algebra - - time_qp: CPU time qp solution - - time_qp_solver_call: CPU time inside qp solver (without converting the QP) - - time_qp_xcond: time_glob: CPU time globalization - - time_solution_sensitivities: CPU time for previous call to eval_param_sens - - time_reg: CPU time regularization - - sqp_iter: number of SQP iterations - - qp_iter: vector of QP iterations for last SQP call - - statistics: table with info about last iteration - - stat_m: number of rows in statistics matrix - - stat_n: number of columns in statistics matrix - - residuals: residuals of last iterate - - alpha: step sizes of SQP iterations - """ - - double_fields = ['time_tot', - 'time_lin', - 'time_sim', - 'time_sim_ad', - 'time_sim_la', - 'time_qp', - 'time_qp_solver_call', - 'time_qp_xcond', - 'time_glob', - 'time_solution_sensitivities', - 'time_reg' - ] - fields = double_fields + [ - 'sqp_iter', - 'qp_iter', - 'statistics', - 'stat_m', - 'stat_n', - 'residuals', - 'alpha', - ] - field = field_.encode('utf-8') - - if field_ in ['sqp_iter', 'stat_m', 'stat_n']: - return self.__get_stat_int(field) - - elif field_ in double_fields: - return self.__get_stat_double(field) - - elif field_ == 'statistics': - sqp_iter = self.get_stats("sqp_iter") - stat_m = self.get_stats("stat_m") - stat_n = self.get_stats("stat_n") - min_size = min([stat_m, sqp_iter+1]) - return self.__get_stat_matrix(field, stat_n+1, min_size) - - elif field_ == 'qp_iter': - full_stats = self.get_stats('statistics') - if self.nlp_solver_type == 'SQP': - return full_stats[6, :] - elif self.nlp_solver_type == 'SQP_RTI': - return full_stats[2, :] - - elif field_ == 'alpha': - full_stats = self.get_stats('statistics') - if self.nlp_solver_type == 'SQP': - return full_stats[7, :] - else: # self.nlp_solver_type == 'SQP_RTI': - raise Exception("alpha values are not available for SQP_RTI") - - elif field_ == 'residuals': - return self.get_residuals() - - else: - raise NotImplementedError("TODO!") - - - def __get_stat_int(self, field): - cdef int out - acados_solver_common.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, &out) - return out - - def __get_stat_double(self, field): - cdef cnp.ndarray[cnp.float64_t, ndim=1] out = np.zeros((1,)) - acados_solver_common.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, out.data) - return out - - def __get_stat_matrix(self, field, n, m): - cdef cnp.ndarray[cnp.float64_t, ndim=2] out_mat = np.ascontiguousarray(np.zeros((n, m)), dtype=np.float64) - acados_solver_common.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, out_mat.data) - return out_mat - - - def get_cost(self): - """ - Returns the cost value of the current solution. - """ - # compute cost internally - acados_solver_common.ocp_nlp_eval_cost(self.nlp_solver, self.nlp_in, self.nlp_out) - - # create output - cdef double out - - # call getter - acados_solver_common.ocp_nlp_get(self.nlp_config, self.nlp_solver, "cost_value", &out) - - return out - - - def get_residuals(self, recompute=False): - """ - Returns an array of the form [res_stat, res_eq, res_ineq, res_comp]. - """ - # compute residuals if RTI - if self.nlp_solver_type == 'SQP_RTI' or recompute: - acados_solver_common.ocp_nlp_eval_residuals(self.nlp_solver, self.nlp_in, self.nlp_out) - - # create output array - cdef cnp.ndarray[cnp.float64_t, ndim=1] out = np.ascontiguousarray(np.zeros((4,), dtype=np.float64)) - cdef double double_value - - field = "res_stat".encode('utf-8') - acados_solver_common.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, &double_value) - out[0] = double_value - - field = "res_eq".encode('utf-8') - acados_solver_common.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, &double_value) - out[1] = double_value - - field = "res_ineq".encode('utf-8') - acados_solver_common.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, &double_value) - out[2] = double_value - - field = "res_comp".encode('utf-8') - acados_solver_common.ocp_nlp_get(self.nlp_config, self.nlp_solver, field, &double_value) - out[3] = double_value - - return out - - - # Note: this function should not be used anymore, better use cost_set, constraints_set - def set(self, int stage, str field_, value_): - - """ - Set numerical data inside the solver. - - :param stage: integer corresponding to shooting node - :param field: string in ['x', 'u', 'pi', 'lam', 't', 'p'] - - .. note:: regarding lam, t: \n - the inequalities are internally organized in the following order: \n - [ lbu lbx lg lh lphi ubu ubx ug uh uphi; \n - lsbu lsbx lsg lsh lsphi usbu usbx usg ush usphi] - - .. note:: pi: multipliers for dynamics equality constraints \n - lam: multipliers for inequalities \n - t: slack variables corresponding to evaluation of all inequalities (at the solution) \n - sl: slack variables of soft lower inequality constraints \n - su: slack variables of soft upper inequality constraints \n - """ - if not isinstance(value_, np.ndarray): - raise Exception(f"set: value must be numpy array, got {type(value_)}.") - cost_fields = ['y_ref', 'yref'] - constraints_fields = ['lbx', 'ubx', 'lbu', 'ubu'] - out_fields = ['x', 'u', 'pi', 'lam', 't', 'z', 'sl', 'su'] - mem_fields = ['xdot_guess', 'z_guess'] - - field = field_.encode('utf-8') - - cdef cnp.ndarray[cnp.float64_t, ndim=1] value = np.ascontiguousarray(value_, dtype=np.float64) - - # treat parameters separately - if field_ == 'p': - assert acados_solver.acados_update_params(self.capsule, stage, value.data, value.shape[0]) == 0 - else: - if field_ not in constraints_fields + cost_fields + out_fields: - raise Exception("AcadosOcpSolverCython.set(): {} is not a valid argument.\ - \nPossible values are {}.".format(field, \ - constraints_fields + cost_fields + out_fields + ['p'])) - - dims = acados_solver_common.ocp_nlp_dims_get_from_attr(self.nlp_config, - self.nlp_dims, self.nlp_out, stage, field) - - if value_.shape[0] != dims: - msg = 'AcadosOcpSolverCython.set(): mismatching dimension for field "{}" '.format(field_) - msg += 'with dimension {} (you have {})'.format(dims, value_.shape[0]) - raise Exception(msg) - - if field_ in constraints_fields: - acados_solver_common.ocp_nlp_constraints_model_set(self.nlp_config, - self.nlp_dims, self.nlp_in, stage, field, value.data) - elif field_ in cost_fields: - acados_solver_common.ocp_nlp_cost_model_set(self.nlp_config, - self.nlp_dims, self.nlp_in, stage, field, value.data) - elif field_ in out_fields: - acados_solver_common.ocp_nlp_out_set(self.nlp_config, - self.nlp_dims, self.nlp_out, stage, field, value.data) - elif field_ in mem_fields: - acados_solver_common.ocp_nlp_set(self.nlp_config, \ - self.nlp_solver, stage, field, value.data) - - if field_ == 'z': - field = 'z_guess'.encode('utf-8') - acados_solver_common.ocp_nlp_set(self.nlp_config, \ - self.nlp_solver, stage, field, value.data) - return - - def cost_set(self, int stage, str field_, value_): - """ - Set numerical data in the cost module of the solver. - - :param stage: integer corresponding to shooting node - :param field: string, e.g. 'yref', 'W', 'ext_cost_num_hess' - :param value: of appropriate size - """ - if not isinstance(value_, np.ndarray): - raise Exception(f"cost_set: value must be numpy array, got {type(value_)}.") - field = field_.encode('utf-8') - - cdef int dims[2] - acados_solver_common.ocp_nlp_cost_dims_get_from_attr(self.nlp_config, \ - self.nlp_dims, self.nlp_out, stage, field, &dims[0]) - - cdef double[::1,:] value - - value_shape = value_.shape - if len(value_shape) == 1: - value_shape = (value_shape[0], 0) - value = np.asfortranarray(value_[None,:]) - - elif len(value_shape) == 2: - # Get elements in column major order - value = np.asfortranarray(value_) - - if value_shape[0] != dims[0] or value_shape[1] != dims[1]: - raise Exception('AcadosOcpSolverCython.cost_set(): mismatching dimension' + - f' for field "{field_}" at stage {stage} with dimension {tuple(dims)} (you have {value_shape})') - - acados_solver_common.ocp_nlp_cost_model_set(self.nlp_config, \ - self.nlp_dims, self.nlp_in, stage, field, &value[0][0]) - - - def constraints_set(self, int stage, str field_, value_): - """ - Set numerical data in the constraint module of the solver. - - :param stage: integer corresponding to shooting node - :param field: string in ['lbx', 'ubx', 'lbu', 'ubu', 'lg', 'ug', 'lh', 'uh', 'uphi', 'C', 'D'] - :param value: of appropriate size - """ - if not isinstance(value_, np.ndarray): - raise Exception(f"constraints_set: value must be numpy array, got {type(value_)}.") - - field = field_.encode('utf-8') - - cdef int dims[2] - acados_solver_common.ocp_nlp_constraint_dims_get_from_attr(self.nlp_config, \ - self.nlp_dims, self.nlp_out, stage, field, &dims[0]) - - cdef double[::1,:] value - - value_shape = value_.shape - if len(value_shape) == 1: - value_shape = (value_shape[0], 0) - value = np.asfortranarray(value_[None,:]) - - elif len(value_shape) == 2: - # Get elements in column major order - value = np.asfortranarray(value_) - - if value_shape != tuple(dims): - raise Exception(f'AcadosOcpSolverCython.constraints_set(): mismatching dimension' + - f' for field "{field_}" at stage {stage} with dimension {tuple(dims)} (you have {value_shape})') - - acados_solver_common.ocp_nlp_constraints_model_set(self.nlp_config, \ - self.nlp_dims, self.nlp_in, stage, field, &value[0][0]) - - return - - - def get_from_qp_in(self, int stage, str field_): - """ - Get numerical data from the dynamics module of the solver: - - :param stage: integer corresponding to shooting node - :param field: string, e.g. 'A' - """ - field = field_.encode('utf-8') - - # get dims - cdef int[2] dims - acados_solver_common.ocp_nlp_qp_dims_get_from_attr(self.nlp_config, self.nlp_dims, self.nlp_out, stage, field, &dims[0]) - - # create output data - cdef cnp.ndarray[cnp.float64_t, ndim=2] out = np.zeros((dims[0], dims[1]), order='F') - - # call getter - acados_solver_common.ocp_nlp_get_at_stage(self.nlp_config, self.nlp_dims, self.nlp_solver, stage, field, out.data) - - return out - - - def options_set(self, str field_, value_): - """ - Set options of the solver. - - :param field: string, e.g. 'print_level', 'rti_phase', 'initialize_t_slacks', 'step_length', 'alpha_min', 'alpha_reduction', 'qp_warm_start', 'line_search_use_sufficient_descent', 'full_step_dual', 'globalization_use_SOC', 'qp_tol_stat', 'qp_tol_eq', 'qp_tol_ineq', 'qp_tol_comp', 'qp_tau_min', 'qp_mu0' - - :param value: of type int, float, string - - - qp_tol_stat: QP solver tolerance stationarity - - qp_tol_eq: QP solver tolerance equalities - - qp_tol_ineq: QP solver tolerance inequalities - - qp_tol_comp: QP solver tolerance complementarity - - qp_tau_min: for HPIPM QP solvers: minimum value of barrier parameter in HPIPM - - qp_mu0: for HPIPM QP solvers: initial value for complementarity slackness - - warm_start_first_qp: indicates if first QP in SQP is warm_started - """ - int_fields = ['print_level', 'rti_phase', 'initialize_t_slacks', 'qp_warm_start', 'line_search_use_sufficient_descent', 'full_step_dual', 'globalization_use_SOC', 'warm_start_first_qp'] - double_fields = ['step_length', 'tol_eq', 'tol_stat', 'tol_ineq', 'tol_comp', 'alpha_min', 'alpha_reduction', 'eps_sufficient_descent', - 'qp_tol_stat', 'qp_tol_eq', 'qp_tol_ineq', 'qp_tol_comp', 'qp_tau_min', 'qp_mu0'] - string_fields = ['globalization'] - - # encode - field = field_.encode('utf-8') - - cdef int int_value - cdef double double_value - cdef unsigned char[::1] string_value - - # check field availability and type - if field_ in int_fields: - if not isinstance(value_, int): - raise Exception('solver option {} must be of type int. You have {}.'.format(field_, type(value_))) - - if field_ == 'rti_phase': - if value_ < 0 or value_ > 2: - raise Exception('AcadosOcpSolverCython.solve(): argument \'rti_phase\' can ' - 'take only values 0, 1, 2 for SQP-RTI-type solvers') - if self.nlp_solver_type != 'SQP_RTI' and value_ > 0: - raise Exception('AcadosOcpSolverCython.solve(): argument \'rti_phase\' can ' - 'take only value 0 for SQP-type solvers') - - int_value = value_ - acados_solver_common.ocp_nlp_solver_opts_set(self.nlp_config, self.nlp_opts, field, &int_value) - - elif field_ in double_fields: - if not isinstance(value_, float): - raise Exception('solver option {} must be of type float. You have {}.'.format(field_, type(value_))) - - double_value = value_ - acados_solver_common.ocp_nlp_solver_opts_set(self.nlp_config, self.nlp_opts, field, &double_value) - - elif field_ in string_fields: - if not isinstance(value_, bytes): - raise Exception('solver option {} must be of type str. You have {}.'.format(field_, type(value_))) - - string_value = value_.encode('utf-8') - acados_solver_common.ocp_nlp_solver_opts_set(self.nlp_config, self.nlp_opts, field, &string_value[0]) - - else: - raise Exception('AcadosOcpSolverCython.options_set() does not support field {}.'\ - '\n Possible values are {}.'.format(field_, ', '.join(int_fields + double_fields + string_fields))) - - - def set_params_sparse(self, int stage, idx_values_, param_values_): - """ - set parameters of the solvers external function partially: - Pseudo: solver.param[idx_values_] = param_values_; - Parameters: - :param stage_: integer corresponding to shooting node - :param idx_values_: 0 based integer array corresponding to parameter indices to be set - :param param_values_: new parameter values as numpy array - """ - - if not isinstance(param_values_, np.ndarray): - raise Exception('param_values_ must be np.array.') - - if param_values_.shape[0] != len(idx_values_): - raise Exception(f'param_values_ and idx_values_ must be of the same size.' + - f' Got sizes idx {param_values_.shape[0]}, param_values {len(idx_values_)}.') - - # n_update = c_int(len(param_values_)) - - # param_data = cast(param_values_.ctypes.data, POINTER(c_double)) - # c_idx_values = np.ascontiguousarray(idx_values_, dtype=np.intc) - # idx_data = cast(c_idx_values.ctypes.data, POINTER(c_int)) - - # getattr(self.shared_lib, f"{self.model_name}_acados_update_params_sparse").argtypes = \ - # [c_void_p, c_int, POINTER(c_int), POINTER(c_double), c_int] - # getattr(self.shared_lib, f"{self.model_name}_acados_update_params_sparse").restype = c_int - # getattr(self.shared_lib, f"{self.model_name}_acados_update_params_sparse") \ - # (self.capsule, stage, idx_data, param_data, n_update) - - cdef cnp.ndarray[cnp.float64_t, ndim=1] value = np.ascontiguousarray(param_values_, dtype=np.float64) - # cdef cnp.ndarray[cnp.intc, ndim=1] idx = np.ascontiguousarray(idx_values_, dtype=np.intc) - - # NOTE: this does throw an error somehow: - # ValueError: Buffer dtype mismatch, expected 'int object' but got 'int' - # cdef cnp.ndarray[cnp.int, ndim=1] idx = np.ascontiguousarray(idx_values_, dtype=np.intc) - - cdef cnp.ndarray[cnp.int32_t, ndim=1] idx = np.ascontiguousarray(idx_values_, dtype=np.int32) - cdef int n_update = value.shape[0] - # print(f"in set_params_sparse Cython n_update {n_update}") - - assert acados_solver.acados_update_params_sparse(self.capsule, stage, idx.data, value.data, n_update) == 0 - return - - - def __del__(self): - if self.solver_created: - acados_solver.acados_free(self.capsule) - acados_solver.acados_free_capsule(self.capsule) diff --git a/third_party/acados/acados_template/acados_sim.py b/third_party/acados/acados_template/acados_sim.py deleted file mode 100644 index c0d6937a49..0000000000 --- a/third_party/acados/acados_template/acados_sim.py +++ /dev/null @@ -1,367 +0,0 @@ -# -*- coding: future_fstrings -*- -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# 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. -# -# 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.; -# - -import numpy as np -import os -from .acados_model import AcadosModel -from .utils import get_acados_path, get_lib_ext - -class AcadosSimDims: - """ - Class containing the dimensions of the model to be simulated. - """ - def __init__(self): - self.__nx = None - self.__nu = None - self.__nz = 0 - self.__np = 0 - - @property - def nx(self): - """:math:`n_x` - number of states. Type: int > 0""" - return self.__nx - - @property - def nz(self): - """:math:`n_z` - number of algebraic variables. Type: int >= 0""" - return self.__nz - - @property - def nu(self): - """:math:`n_u` - number of inputs. Type: int >= 0""" - return self.__nu - - @property - def np(self): - """:math:`n_p` - number of parameters. Type: int >= 0""" - return self.__np - - @nx.setter - def nx(self, nx): - if isinstance(nx, int) and nx > 0: - self.__nx = nx - else: - raise Exception('Invalid nx value, expected positive integer.') - - @nz.setter - def nz(self, nz): - if isinstance(nz, int) and nz > -1: - self.__nz = nz - else: - raise Exception('Invalid nz value, expected nonnegative integer.') - - @nu.setter - def nu(self, nu): - if isinstance(nu, int) and nu > -1: - self.__nu = nu - else: - raise Exception('Invalid nu value, expected nonnegative integer.') - - @np.setter - def np(self, np): - if isinstance(np, int) and np > -1: - self.__np = np - else: - raise Exception('Invalid np value, expected nonnegative integer.') - - def set(self, attr, value): - setattr(self, attr, value) - - -class AcadosSimOpts: - """ - class containing the solver options - """ - def __init__(self): - self.__integrator_type = 'ERK' - self.__collocation_type = 'GAUSS_LEGENDRE' - self.__Tsim = None - # ints - self.__sim_method_num_stages = 1 - self.__sim_method_num_steps = 1 - self.__sim_method_newton_iter = 3 - # doubles - self.__sim_method_newton_tol = 0.0 - # bools - self.__sens_forw = True - self.__sens_adj = False - self.__sens_algebraic = False - self.__sens_hess = False - self.__output_z = True - self.__sim_method_jac_reuse = 0 - self.__ext_fun_compile_flags = '-O2' - - @property - def integrator_type(self): - """Integrator type. Default: 'ERK'.""" - return self.__integrator_type - - @property - def num_stages(self): - """Number of stages in the integrator. Default: 1""" - return self.__sim_method_num_stages - - @property - def num_steps(self): - """Number of steps in the integrator. Default: 1""" - return self.__sim_method_num_steps - - @property - def newton_iter(self): - """Number of Newton iterations in simulation method. Default: 3""" - return self.__sim_method_newton_iter - - @property - def newton_tol(self): - """ - Tolerance for Newton system solved in implicit integrator (IRK, GNSF). - 0.0 means this is not used and exactly newton_iter iterations are carried out. - Default: 0.0 - """ - return self.__sim_method_newton_tol - - @property - def sens_forw(self): - """Boolean determining if forward sensitivities are computed. Default: True""" - return self.__sens_forw - - @property - def sens_adj(self): - """Boolean determining if adjoint sensitivities are computed. Default: False""" - return self.__sens_adj - - @property - def sens_algebraic(self): - """Boolean determining if sensitivities wrt algebraic variables are computed. Default: False""" - return self.__sens_algebraic - - @property - def sens_hess(self): - """Boolean determining if hessians are computed. Default: False""" - return self.__sens_hess - - @property - def output_z(self): - """Boolean determining if values for algebraic variables (corresponding to start of simulation interval) are computed. Default: True""" - return self.__output_z - - @property - def sim_method_jac_reuse(self): - """Integer determining if jacobians are reused (0 or 1). Default: 0""" - return self.__sim_method_jac_reuse - - @property - def T(self): - """Time horizon""" - return self.__Tsim - - @property - def collocation_type(self): - """Collocation type: relevant for implicit integrators - -- string in {GAUSS_RADAU_IIA, GAUSS_LEGENDRE} - - Default: GAUSS_LEGENDRE - """ - return self.__collocation_type - - @property - def ext_fun_compile_flags(self): - """ - String with compiler flags for external function compilation. - Default: '-O2'. - """ - return self.__ext_fun_compile_flags - - @ext_fun_compile_flags.setter - def ext_fun_compile_flags(self, ext_fun_compile_flags): - if isinstance(ext_fun_compile_flags, str): - self.__ext_fun_compile_flags = ext_fun_compile_flags - else: - raise Exception('Invalid ext_fun_compile_flags, expected a string.\n') - - @integrator_type.setter - def integrator_type(self, integrator_type): - integrator_types = ('ERK', 'IRK', 'GNSF') - if integrator_type in integrator_types: - self.__integrator_type = integrator_type - else: - raise Exception('Invalid integrator_type value. Possible values are:\n\n' \ - + ',\n'.join(integrator_types) + '.\n\nYou have: ' + integrator_type + '.\n\n') - - @collocation_type.setter - def collocation_type(self, collocation_type): - collocation_types = ('GAUSS_RADAU_IIA', 'GAUSS_LEGENDRE') - if collocation_type in collocation_types: - self.__collocation_type = collocation_type - else: - raise Exception('Invalid collocation_type value. Possible values are:\n\n' \ - + ',\n'.join(collocation_types) + '.\n\nYou have: ' + collocation_type + '.\n\n') - - @T.setter - def T(self, T): - self.__Tsim = T - - @num_stages.setter - def num_stages(self, num_stages): - if isinstance(num_stages, int): - self.__sim_method_num_stages = num_stages - else: - raise Exception('Invalid num_stages value. num_stages must be an integer.') - - @num_steps.setter - def num_steps(self, num_steps): - if isinstance(num_steps, int): - self.__sim_method_num_steps = num_steps - else: - raise Exception('Invalid num_steps value. num_steps must be an integer.') - - @newton_iter.setter - def newton_iter(self, newton_iter): - if isinstance(newton_iter, int): - self.__sim_method_newton_iter = newton_iter - else: - raise Exception('Invalid newton_iter value. newton_iter must be an integer.') - - @newton_tol.setter - def newton_tol(self, newton_tol): - if isinstance(newton_tol, float): - self.__sim_method_newton_tol = newton_tol - else: - raise Exception('Invalid newton_tol value. newton_tol must be an float.') - - @sens_forw.setter - def sens_forw(self, sens_forw): - if sens_forw in (True, False): - self.__sens_forw = sens_forw - else: - raise Exception('Invalid sens_forw value. sens_forw must be a Boolean.') - - @sens_adj.setter - def sens_adj(self, sens_adj): - if sens_adj in (True, False): - self.__sens_adj = sens_adj - else: - raise Exception('Invalid sens_adj value. sens_adj must be a Boolean.') - - @sens_hess.setter - def sens_hess(self, sens_hess): - if sens_hess in (True, False): - self.__sens_hess = sens_hess - else: - raise Exception('Invalid sens_hess value. sens_hess must be a Boolean.') - - @sens_algebraic.setter - def sens_algebraic(self, sens_algebraic): - if sens_algebraic in (True, False): - self.__sens_algebraic = sens_algebraic - else: - raise Exception('Invalid sens_algebraic value. sens_algebraic must be a Boolean.') - - @output_z.setter - def output_z(self, output_z): - if output_z in (True, False): - self.__output_z = output_z - else: - raise Exception('Invalid output_z value. output_z must be a Boolean.') - - @sim_method_jac_reuse.setter - def sim_method_jac_reuse(self, sim_method_jac_reuse): - if sim_method_jac_reuse in (0, 1): - self.__sim_method_jac_reuse = sim_method_jac_reuse - else: - raise Exception('Invalid sim_method_jac_reuse value. sim_method_jac_reuse must be 0 or 1.') - -class AcadosSim: - """ - The class has the following properties that can be modified to formulate a specific simulation problem, see below: - - :param acados_path: string with the path to acados. It is used to generate the include and lib paths. - - - :py:attr:`dims` of type :py:class:`acados_template.acados_ocp.AcadosSimDims` - are automatically detected from model - - :py:attr:`model` of type :py:class:`acados_template.acados_model.AcadosModel` - - :py:attr:`solver_options` of type :py:class:`acados_template.acados_sim.AcadosSimOpts` - - - :py:attr:`acados_include_path` (set automatically) - - :py:attr:`shared_lib_ext` (set automatically) - - :py:attr:`acados_lib_path` (set automatically) - - :py:attr:`parameter_values` - used to initialize the parameters (can be changed) - - """ - def __init__(self, acados_path=''): - if acados_path == '': - acados_path = get_acados_path() - self.dims = AcadosSimDims() - """Dimension definitions, automatically detected from :py:attr:`model`. Type :py:class:`acados_template.acados_sim.AcadosSimDims`""" - self.model = AcadosModel() - """Model definitions, type :py:class:`acados_template.acados_model.AcadosModel`""" - self.solver_options = AcadosSimOpts() - """Solver Options, type :py:class:`acados_template.acados_sim.AcadosSimOpts`""" - - self.acados_include_path = os.path.join(acados_path, 'include').replace(os.sep, '/') # the replace part is important on Windows for CMake - """Path to acados include directory (set automatically), type: `string`""" - self.acados_lib_path = os.path.join(acados_path, 'lib').replace(os.sep, '/') # the replace part is important on Windows for CMake - """Path to where acados library is located (set automatically), type: `string`""" - - self.code_export_directory = 'c_generated_code' - """Path to where code will be exported. Default: `c_generated_code`.""" - self.shared_lib_ext = get_lib_ext() - - # get cython paths - from sysconfig import get_paths - self.cython_include_dirs = [np.get_include(), get_paths()['include']] - - self.__parameter_values = np.array([]) - self.__problem_class = 'SIM' - - @property - def parameter_values(self): - """:math:`p` - initial values for parameter - can be updated""" - return self.__parameter_values - - @parameter_values.setter - def parameter_values(self, parameter_values): - if isinstance(parameter_values, np.ndarray): - self.__parameter_values = parameter_values - else: - raise Exception('Invalid parameter_values value. ' + - f'Expected numpy array, got {type(parameter_values)}.') - - def set(self, attr, value): - # tokenize string - tokens = attr.split('_', 1) - if len(tokens) > 1: - setter_to_call = getattr(getattr(self, tokens[0]), 'set') - else: - setter_to_call = getattr(self, 'set') - - setter_to_call(tokens[1], value) - - return diff --git a/third_party/acados/acados_template/acados_sim_layout.json b/third_party/acados/acados_template/acados_sim_layout.json deleted file mode 100644 index e3ca4b575b..0000000000 --- a/third_party/acados/acados_template/acados_sim_layout.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "acados_include_path": [ - "str" - ], - "model": { - "name" : [ - "str" - ] - }, - "acados_lib_path": [ - "str" - ], - "dims": { - "np": [ - "int" - ], - "nu": [ - "int" - ], - "nx": [ - "int" - ], - "nz": [ - "int" - ] - }, - "solver_options": { - "integrator_type": [ - "str" - ], - "collocation_type": [ - "str" - ], - "Tsim": [ - "float" - ], - "sim_method_num_stages": [ - "int" - ], - "sim_method_num_steps": [ - "int" - ], - "sim_method_newton_iter": [ - "int" - ], - "sim_method_newton_tol": [ - "float" - ], - "ext_fun_compile_flags": [ - "str" - ] - } -} diff --git a/third_party/acados/acados_template/acados_sim_solver.py b/third_party/acados/acados_template/acados_sim_solver.py deleted file mode 100644 index 612f439eaf..0000000000 --- a/third_party/acados/acados_template/acados_sim_solver.py +++ /dev/null @@ -1,559 +0,0 @@ -# -*- coding: future_fstrings -*- -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# 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. -# -# 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.; -# - -import sys -import os -import json -import importlib - -import numpy as np - -from subprocess import DEVNULL, call, STDOUT - -from ctypes import POINTER, cast, CDLL, c_void_p, c_char_p, c_double, c_int, c_bool, byref -from copy import deepcopy - -from .casadi_function_generation import generate_c_code_implicit_ode, generate_c_code_gnsf, generate_c_code_explicit_ode -from .acados_sim import AcadosSim -from .acados_ocp import AcadosOcp -from .utils import is_column, render_template, format_class_dict, make_object_json_dumpable,\ - make_model_consistent, set_up_imported_gnsf_model, get_python_interface_path, get_lib_ext,\ - casadi_length, is_empty, check_casadi_version -from .builders import CMakeBuilder -from .gnsf.detect_gnsf_structure import detect_gnsf_structure - - - -def make_sim_dims_consistent(acados_sim: AcadosSim): - dims = acados_sim.dims - model = acados_sim.model - # nx - if is_column(model.x): - dims.nx = casadi_length(model.x) - else: - raise Exception('model.x should be column vector!') - - # nu - if is_empty(model.u): - dims.nu = 0 - else: - dims.nu = casadi_length(model.u) - - # nz - if is_empty(model.z): - dims.nz = 0 - else: - dims.nz = casadi_length(model.z) - - # np - if is_empty(model.p): - dims.np = 0 - else: - dims.np = casadi_length(model.p) - if acados_sim.parameter_values.shape[0] != dims.np: - raise Exception('inconsistent dimension np, regarding model.p and parameter_values.' + \ - f'\nGot np = {dims.np}, acados_sim.parameter_values.shape = {acados_sim.parameter_values.shape[0]}\n') - - -def get_sim_layout(): - python_interface_path = get_python_interface_path() - abs_path = os.path.join(python_interface_path, 'acados_sim_layout.json') - with open(abs_path, 'r') as f: - sim_layout = json.load(f) - return sim_layout - - -def sim_formulation_json_dump(acados_sim: AcadosSim, json_file='acados_sim.json'): - # Load acados_sim structure description - sim_layout = get_sim_layout() - - # Copy input sim object dictionary - sim_dict = dict(deepcopy(acados_sim).__dict__) - - for key, v in sim_layout.items(): - # skip non dict attributes - if not isinstance(v, dict): continue - # Copy sim object attributes dictionaries - sim_dict[key]=dict(getattr(acados_sim, key).__dict__) - - sim_json = format_class_dict(sim_dict) - - with open(json_file, 'w') as f: - json.dump(sim_json, f, default=make_object_json_dumpable, indent=4, sort_keys=True) - - -def sim_get_default_cmake_builder() -> CMakeBuilder: - """ - If :py:class:`~acados_template.acados_sim_solver.AcadosSimSolver` is used with `CMake` this function returns a good first setting. - :return: default :py:class:`~acados_template.builders.CMakeBuilder` - """ - cmake_builder = CMakeBuilder() - cmake_builder.options_on = ['BUILD_ACADOS_SIM_SOLVER_LIB'] - return cmake_builder - - -def sim_render_templates(json_file, model_name: str, code_export_dir, cmake_options: CMakeBuilder = None): - # setting up loader and environment - json_path = os.path.join(os.getcwd(), json_file) - - if not os.path.exists(json_path): - raise Exception(f"{json_path} not found!") - - # Render templates - in_file = 'acados_sim_solver.in.c' - out_file = f'acados_sim_solver_{model_name}.c' - render_template(in_file, out_file, code_export_dir, json_path) - - in_file = 'acados_sim_solver.in.h' - out_file = f'acados_sim_solver_{model_name}.h' - render_template(in_file, out_file, code_export_dir, json_path) - - in_file = 'acados_sim_solver.in.pxd' - out_file = f'acados_sim_solver.pxd' - render_template(in_file, out_file, code_export_dir, json_path) - - # Builder - if cmake_options is not None: - in_file = 'CMakeLists.in.txt' - out_file = 'CMakeLists.txt' - render_template(in_file, out_file, code_export_dir, json_path) - else: - in_file = 'Makefile.in' - out_file = 'Makefile' - render_template(in_file, out_file, code_export_dir, json_path) - - in_file = 'main_sim.in.c' - out_file = f'main_sim_{model_name}.c' - render_template(in_file, out_file, code_export_dir, json_path) - - # folder model - model_dir = os.path.join(code_export_dir, model_name + '_model') - - in_file = 'model.in.h' - out_file = f'{model_name}_model.h' - render_template(in_file, out_file, model_dir, json_path) - - -def sim_generate_external_functions(acados_sim: AcadosSim): - model = acados_sim.model - model = make_model_consistent(model) - - integrator_type = acados_sim.solver_options.integrator_type - - opts = dict(generate_hess = acados_sim.solver_options.sens_hess, - code_export_directory = acados_sim.code_export_directory) - - # create code_export_dir, model_dir - code_export_dir = acados_sim.code_export_directory - opts['code_export_directory'] = code_export_dir - model_dir = os.path.join(code_export_dir, model.name + '_model') - if not os.path.exists(model_dir): - os.makedirs(model_dir) - - # generate external functions - check_casadi_version() - if integrator_type == 'ERK': - generate_c_code_explicit_ode(model, opts) - elif integrator_type == 'IRK': - generate_c_code_implicit_ode(model, opts) - elif integrator_type == 'GNSF': - generate_c_code_gnsf(model, opts) - - -class AcadosSimSolver: - """ - Class to interact with the acados integrator C object. - - :param acados_sim: type :py:class:`~acados_template.acados_ocp.AcadosOcp` (takes values to generate an instance :py:class:`~acados_template.acados_sim.AcadosSim`) or :py:class:`~acados_template.acados_sim.AcadosSim` - :param json_file: Default: 'acados_sim.json' - :param build: Default: True - :param cmake_builder: type :py:class:`~acados_template.utils.CMakeBuilder` generate a `CMakeLists.txt` and use - the `CMake` pipeline instead of a `Makefile` (`CMake` seems to be the better option in conjunction with - `MS Visual Studio`); default: `None` - """ - if sys.platform=="win32": - from ctypes import wintypes - from ctypes import WinDLL - dlclose = WinDLL('kernel32', use_last_error=True).FreeLibrary - dlclose.argtypes = [wintypes.HMODULE] - else: - dlclose = CDLL(None).dlclose - dlclose.argtypes = [c_void_p] - - - @classmethod - def generate(cls, acados_sim: AcadosSim, json_file='acados_sim.json', cmake_builder: CMakeBuilder = None): - """ - Generates the code for an acados sim solver, given the description in acados_sim - """ - - acados_sim.code_export_directory = os.path.abspath(acados_sim.code_export_directory) - - # make dims consistent - make_sim_dims_consistent(acados_sim) - - # module dependent post processing - if acados_sim.solver_options.integrator_type == 'GNSF': - if acados_sim.solver_options.sens_hess == True: - raise Exception("AcadosSimSolver: GNSF does not support sens_hess = True.") - if 'gnsf_model' in acados_sim.__dict__: - set_up_imported_gnsf_model(acados_sim) - else: - detect_gnsf_structure(acados_sim) - - # generate external functions - sim_generate_external_functions(acados_sim) - - # dump to json - sim_formulation_json_dump(acados_sim, json_file) - - # render templates - sim_render_templates(json_file, acados_sim.model.name, acados_sim.code_export_directory, cmake_builder) - - - @classmethod - def build(cls, code_export_dir, with_cython=False, cmake_builder: CMakeBuilder = None, verbose: bool = True): - # Compile solver - cwd = os.getcwd() - os.chdir(code_export_dir) - if with_cython: - call( - ['make', 'clean_sim_cython'], - stdout=None if verbose else DEVNULL, - stderr=None if verbose else STDOUT - ) - call( - ['make', 'sim_cython'], - stdout=None if verbose else DEVNULL, - stderr=None if verbose else STDOUT - ) - else: - if cmake_builder is not None: - cmake_builder.exec(code_export_dir, verbose=verbose) - else: - call( - ['make', 'sim_shared_lib'], - stdout=None if verbose else DEVNULL, - stderr=None if verbose else STDOUT - ) - os.chdir(cwd) - - - @classmethod - def create_cython_solver(cls, json_file): - """ - """ - with open(json_file, 'r') as f: - acados_sim_json = json.load(f) - code_export_directory = acados_sim_json['code_export_directory'] - - importlib.invalidate_caches() - rel_code_export_directory = os.path.relpath(code_export_directory) - acados_sim_solver_pyx = importlib.import_module(f'{rel_code_export_directory}.acados_sim_solver_pyx') - - AcadosSimSolverCython = getattr(acados_sim_solver_pyx, 'AcadosSimSolverCython') - return AcadosSimSolverCython(acados_sim_json['model']['name']) - - def __init__(self, acados_sim, json_file='acados_sim.json', generate=True, build=True, cmake_builder: CMakeBuilder = None, verbose: bool = True): - - self.solver_created = False - self.acados_sim = acados_sim - model_name = acados_sim.model.name - self.model_name = model_name - - code_export_dir = os.path.abspath(acados_sim.code_export_directory) - - # reuse existing json and casadi functions, when creating integrator from ocp - if generate and not isinstance(acados_sim, AcadosOcp): - self.generate(acados_sim, json_file=json_file, cmake_builder=cmake_builder) - - if build: - self.build(code_export_dir, cmake_builder=cmake_builder, verbose=True) - - # prepare library loading - lib_prefix = 'lib' - lib_ext = get_lib_ext() - if os.name == 'nt': - lib_prefix = '' - - # Load acados library to avoid unloading the library. - # This is necessary if acados was compiled with OpenMP, since the OpenMP threads can't be destroyed. - # Unloading a library which uses OpenMP results in a segfault (on any platform?). - # see [https://stackoverflow.com/questions/34439956/vc-crash-when-freeing-a-dll-built-with-openmp] - # or [https://python.hotexamples.com/examples/_ctypes/-/dlclose/python-dlclose-function-examples.html] - libacados_name = f'{lib_prefix}acados{lib_ext}' - libacados_filepath = os.path.join(acados_sim.acados_lib_path, libacados_name) - self.__acados_lib = CDLL(libacados_filepath) - # find out if acados was compiled with OpenMP - try: - self.__acados_lib_uses_omp = getattr(self.__acados_lib, 'omp_get_thread_num') is not None - except AttributeError as e: - self.__acados_lib_uses_omp = False - if self.__acados_lib_uses_omp: - print('acados was compiled with OpenMP.') - else: - print('acados was compiled without OpenMP.') - libacados_sim_solver_name = f'{lib_prefix}acados_sim_solver_{self.model_name}{lib_ext}' - self.shared_lib_name = os.path.join(code_export_dir, libacados_sim_solver_name) - - # get shared_lib - self.shared_lib = CDLL(self.shared_lib_name) - - # create capsule - getattr(self.shared_lib, f"{model_name}_acados_sim_solver_create_capsule").restype = c_void_p - self.capsule = getattr(self.shared_lib, f"{model_name}_acados_sim_solver_create_capsule")() - - # create solver - getattr(self.shared_lib, f"{model_name}_acados_sim_create").argtypes = [c_void_p] - getattr(self.shared_lib, f"{model_name}_acados_sim_create").restype = c_int - assert getattr(self.shared_lib, f"{model_name}_acados_sim_create")(self.capsule)==0 - self.solver_created = True - - getattr(self.shared_lib, f"{model_name}_acados_get_sim_opts").argtypes = [c_void_p] - getattr(self.shared_lib, f"{model_name}_acados_get_sim_opts").restype = c_void_p - self.sim_opts = getattr(self.shared_lib, f"{model_name}_acados_get_sim_opts")(self.capsule) - - getattr(self.shared_lib, f"{model_name}_acados_get_sim_dims").argtypes = [c_void_p] - getattr(self.shared_lib, f"{model_name}_acados_get_sim_dims").restype = c_void_p - self.sim_dims = getattr(self.shared_lib, f"{model_name}_acados_get_sim_dims")(self.capsule) - - getattr(self.shared_lib, f"{model_name}_acados_get_sim_config").argtypes = [c_void_p] - getattr(self.shared_lib, f"{model_name}_acados_get_sim_config").restype = c_void_p - self.sim_config = getattr(self.shared_lib, f"{model_name}_acados_get_sim_config")(self.capsule) - - getattr(self.shared_lib, f"{model_name}_acados_get_sim_out").argtypes = [c_void_p] - getattr(self.shared_lib, f"{model_name}_acados_get_sim_out").restype = c_void_p - self.sim_out = getattr(self.shared_lib, f"{model_name}_acados_get_sim_out")(self.capsule) - - getattr(self.shared_lib, f"{model_name}_acados_get_sim_in").argtypes = [c_void_p] - getattr(self.shared_lib, f"{model_name}_acados_get_sim_in").restype = c_void_p - self.sim_in = getattr(self.shared_lib, f"{model_name}_acados_get_sim_in")(self.capsule) - - getattr(self.shared_lib, f"{model_name}_acados_get_sim_solver").argtypes = [c_void_p] - getattr(self.shared_lib, f"{model_name}_acados_get_sim_solver").restype = c_void_p - self.sim_solver = getattr(self.shared_lib, f"{model_name}_acados_get_sim_solver")(self.capsule) - - self.gettable_vectors = ['x', 'u', 'z', 'S_adj'] - self.gettable_matrices = ['S_forw', 'Sx', 'Su', 'S_hess', 'S_algebraic'] - self.gettable_scalars = ['CPUtime', 'time_tot', 'ADtime', 'time_ad', 'LAtime', 'time_la'] - - - def simulate(self, x=None, u=None, z=None, p=None): - """ - Simulate the system forward for the given x, u, z, p and return x_next. - Wrapper around `solve()` taking care of setting/getting inputs/outputs. - """ - if x is not None: - self.set('x', x) - if u is not None: - self.set('u', u) - if z is not None: - self.set('z', z) - if p is not None: - self.set('p', p) - - status = self.solve() - - if status == 2: - print("Warning: acados_sim_solver reached maximum iterations.") - elif status != 0: - raise Exception(f'acados_sim_solver for model {self.model_name} returned status {status}.') - - x_next = self.get('x') - return x_next - - - def solve(self): - """ - Solve the simulation problem with current input. - """ - getattr(self.shared_lib, f"{self.model_name}_acados_sim_solve").argtypes = [c_void_p] - getattr(self.shared_lib, f"{self.model_name}_acados_sim_solve").restype = c_int - - status = getattr(self.shared_lib, f"{self.model_name}_acados_sim_solve")(self.capsule) - return status - - - def get(self, field_): - """ - Get the last solution of the solver. - - :param str field: string in ['x', 'u', 'z', 'S_forw', 'Sx', 'Su', 'S_adj', 'S_hess', 'S_algebraic', 'CPUtime', 'time_tot', 'ADtime', 'time_ad', 'LAtime', 'time_la'] - """ - field = field_.encode('utf-8') - - if field_ in self.gettable_vectors: - # get dims - dims = np.ascontiguousarray(np.zeros((2,)), dtype=np.intc) - dims_data = cast(dims.ctypes.data, POINTER(c_int)) - - self.shared_lib.sim_dims_get_from_attr.argtypes = [c_void_p, c_void_p, c_char_p, POINTER(c_int)] - self.shared_lib.sim_dims_get_from_attr(self.sim_config, self.sim_dims, field, dims_data) - - # allocate array - out = np.ascontiguousarray(np.zeros((dims[0],)), dtype=np.float64) - out_data = cast(out.ctypes.data, POINTER(c_double)) - - self.shared_lib.sim_out_get.argtypes = [c_void_p, c_void_p, c_void_p, c_char_p, c_void_p] - self.shared_lib.sim_out_get(self.sim_config, self.sim_dims, self.sim_out, field, out_data) - - elif field_ in self.gettable_matrices: - # get dims - dims = np.ascontiguousarray(np.zeros((2,)), dtype=np.intc) - dims_data = cast(dims.ctypes.data, POINTER(c_int)) - - self.shared_lib.sim_dims_get_from_attr.argtypes = [c_void_p, c_void_p, c_char_p, POINTER(c_int)] - self.shared_lib.sim_dims_get_from_attr(self.sim_config, self.sim_dims, field, dims_data) - - out = np.zeros((dims[0], dims[1]), order='F') - out_data = cast(out.ctypes.data, POINTER(c_double)) - - self.shared_lib.sim_out_get.argtypes = [c_void_p, c_void_p, c_void_p, c_char_p, c_void_p] - self.shared_lib.sim_out_get(self.sim_config, self.sim_dims, self.sim_out, field, out_data) - - elif field_ in self.gettable_scalars: - scalar = c_double() - scalar_data = byref(scalar) - self.shared_lib.sim_out_get.argtypes = [c_void_p, c_void_p, c_void_p, c_char_p, c_void_p] - self.shared_lib.sim_out_get(self.sim_config, self.sim_dims, self.sim_out, field, scalar_data) - - out = scalar.value - else: - raise Exception(f'AcadosSimSolver.get(): Unknown field {field_},' \ - f' available fields are {", ".join(self.gettable_vectors+self.gettable_matrices)}, {", ".join(self.gettable_scalars)}') - - return out - - - - def set(self, field_: str, value_): - """ - Set numerical data inside the solver. - - :param field: string in ['x', 'u', 'p', 'xdot', 'z', 'seed_adj', 'T'] - :param value: the value with appropriate size. - """ - settable = ['x', 'u', 'p', 'xdot', 'z', 'seed_adj', 'T'] # S_forw - - # TODO: check and throw error here. then remove checks in Cython for speed - # cast value_ to avoid conversion issues - if isinstance(value_, (float, int)): - value_ = np.array([value_]) - - value_ = value_.astype(float) - value_data = cast(value_.ctypes.data, POINTER(c_double)) - value_data_p = cast((value_data), c_void_p) - - field = field_.encode('utf-8') - - # treat parameters separately - if field_ == 'p': - model_name = self.acados_sim.model.name - getattr(self.shared_lib, f"{model_name}_acados_sim_update_params").argtypes = [c_void_p, POINTER(c_double), c_int] - value_data = cast(value_.ctypes.data, POINTER(c_double)) - getattr(self.shared_lib, f"{model_name}_acados_sim_update_params")(self.capsule, value_data, value_.shape[0]) - return - else: - # dimension check - dims = np.ascontiguousarray(np.zeros((2,)), dtype=np.intc) - dims_data = cast(dims.ctypes.data, POINTER(c_int)) - - self.shared_lib.sim_dims_get_from_attr.argtypes = [c_void_p, c_void_p, c_char_p, POINTER(c_int)] - self.shared_lib.sim_dims_get_from_attr(self.sim_config, self.sim_dims, field, dims_data) - - value_ = np.ravel(value_, order='F') - - value_shape = value_.shape - if len(value_shape) == 1: - value_shape = (value_shape[0], 0) - - if value_shape != tuple(dims): - raise Exception(f'AcadosSimSolver.set(): mismatching dimension' \ - f' for field "{field_}" with dimension {tuple(dims)} (you have {value_shape}).') - - # set - if field_ in ['xdot', 'z']: - self.shared_lib.sim_solver_set.argtypes = [c_void_p, c_char_p, c_void_p] - self.shared_lib.sim_solver_set(self.sim_solver, field, value_data_p) - elif field_ in settable: - self.shared_lib.sim_in_set.argtypes = [c_void_p, c_void_p, c_void_p, c_char_p, c_void_p] - self.shared_lib.sim_in_set(self.sim_config, self.sim_dims, self.sim_in, field, value_data_p) - else: - raise Exception(f'AcadosSimSolver.set(): Unknown field {field_},' \ - f' available fields are {", ".join(settable)}') - - return - - - def options_set(self, field_: str, value_: bool): - """ - Set solver options - - :param field: string in ['sens_forw', 'sens_adj', 'sens_hess'] - :param value: Boolean - """ - fields = ['sens_forw', 'sens_adj', 'sens_hess'] - if field_ not in fields: - raise Exception(f"field {field_} not supported. Supported values are {', '.join(fields)}.\n") - - field = field_.encode('utf-8') - value_ctypes = c_bool(value_) - - if not isinstance(value_, bool): - raise TypeError("options_set: expected boolean for value") - - # only allow setting - if getattr(self.acados_sim.solver_options, field_) or value_ == False: - self.shared_lib.sim_opts_set.argtypes = [c_void_p, c_void_p, c_char_p, POINTER(c_bool)] - self.shared_lib.sim_opts_set(self.sim_config, self.sim_opts, field, value_ctypes) - else: - raise RuntimeError(f"Cannot set option {field_} to True, because it was False in original solver options.\n") - - return - - - def __del__(self): - - if self.solver_created: - getattr(self.shared_lib, f"{self.model_name}_acados_sim_free").argtypes = [c_void_p] - getattr(self.shared_lib, f"{self.model_name}_acados_sim_free").restype = c_int - getattr(self.shared_lib, f"{self.model_name}_acados_sim_free")(self.capsule) - - getattr(self.shared_lib, f"{self.model_name}_acados_sim_solver_free_capsule").argtypes = [c_void_p] - getattr(self.shared_lib, f"{self.model_name}_acados_sim_solver_free_capsule").restype = c_int - getattr(self.shared_lib, f"{self.model_name}_acados_sim_solver_free_capsule")(self.capsule) - - try: - self.dlclose(self.shared_lib._handle) - except: - print(f"WARNING: acados Python interface could not close shared_lib handle of AcadosSimSolver {self.model_name}.\n", - "Attempting to create a new one with the same name will likely result in the old one being used!") - pass diff --git a/third_party/acados/acados_template/acados_sim_solver_common.pxd b/third_party/acados/acados_template/acados_sim_solver_common.pxd deleted file mode 100644 index cc6a58efd7..0000000000 --- a/third_party/acados/acados_template/acados_sim_solver_common.pxd +++ /dev/null @@ -1,64 +0,0 @@ -# -*- coding: future_fstrings -*- -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# 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. -# -# 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.; -# - - -cdef extern from "acados/sim/sim_common.h": - ctypedef struct sim_config: - pass - - ctypedef struct sim_opts: - pass - - ctypedef struct sim_in: - pass - - ctypedef struct sim_out: - pass - - -cdef extern from "acados_c/sim_interface.h": - - ctypedef struct sim_plan: - pass - - ctypedef struct sim_solver: - pass - - # out - void sim_out_get(sim_config *config, void *dims, sim_out *out, const char *field, void *value) - int sim_dims_get_from_attr(sim_config *config, void *dims, const char *field, void *dims_data) - - # opts - void sim_opts_set(sim_config *config, void *opts_, const char *field, void *value) - - # get/set - void sim_in_set(sim_config *config, void *dims, sim_in *sim_in, const char *field, void *value) - void sim_solver_set(sim_solver *solver, const char *field, void *value) \ No newline at end of file diff --git a/third_party/acados/acados_template/acados_sim_solver_pyx.pyx b/third_party/acados/acados_template/acados_sim_solver_pyx.pyx deleted file mode 100644 index be400addc7..0000000000 --- a/third_party/acados/acados_template/acados_sim_solver_pyx.pyx +++ /dev/null @@ -1,256 +0,0 @@ -# -*- coding: future_fstrings -*- -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# 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. -# -# 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.; -# -# cython: language_level=3 -# cython: profile=False -# distutils: language=c - -cimport cython -from libc cimport string -# from libc cimport bool as bool_t - -cimport acados_sim_solver_common -cimport acados_sim_solver - -cimport numpy as cnp - -import os -from datetime import datetime -import numpy as np - - -cdef class AcadosSimSolverCython: - """ - Class to interact with the acados sim solver C object. - """ - - cdef acados_sim_solver.sim_solver_capsule *capsule - cdef void *sim_dims - cdef acados_sim_solver_common.sim_opts *sim_opts - cdef acados_sim_solver_common.sim_config *sim_config - cdef acados_sim_solver_common.sim_out *sim_out - cdef acados_sim_solver_common.sim_in *sim_in - cdef acados_sim_solver_common.sim_solver *sim_solver - - cdef bint solver_created - - cdef str model_name - - cdef str sim_solver_type - - cdef list gettable_vectors - cdef list gettable_matrices - cdef list gettable_scalars - - def __cinit__(self, model_name): - - self.solver_created = False - - self.model_name = model_name - - # create capsule - self.capsule = acados_sim_solver.acados_sim_solver_create_capsule() - - # create solver - assert acados_sim_solver.acados_sim_create(self.capsule) == 0 - self.solver_created = True - - # get pointers solver - self.__get_pointers_solver() - - self.gettable_vectors = ['x', 'u', 'z', 'S_adj'] - self.gettable_matrices = ['S_forw', 'Sx', 'Su', 'S_hess', 'S_algebraic'] - self.gettable_scalars = ['CPUtime', 'time_tot', 'ADtime', 'time_ad', 'LAtime', 'time_la'] - - def __get_pointers_solver(self): - """ - Private function to get the pointers for solver - """ - # get pointers solver - self.sim_opts = acados_sim_solver.acados_get_sim_opts(self.capsule) - self.sim_dims = acados_sim_solver.acados_get_sim_dims(self.capsule) - self.sim_config = acados_sim_solver.acados_get_sim_config(self.capsule) - self.sim_out = acados_sim_solver.acados_get_sim_out(self.capsule) - self.sim_in = acados_sim_solver.acados_get_sim_in(self.capsule) - self.sim_solver = acados_sim_solver.acados_get_sim_solver(self.capsule) - - - def simulate(self, x=None, u=None, z=None, p=None): - """ - Simulate the system forward for the given x, u, z, p and return x_next. - Wrapper around `solve()` taking care of setting/getting inputs/outputs. - """ - if x is not None: - self.set('x', x) - if u is not None: - self.set('u', u) - if z is not None: - self.set('z', z) - if p is not None: - self.set('p', p) - - status = self.solve() - - if status == 2: - print("Warning: acados_sim_solver reached maximum iterations.") - elif status != 0: - raise Exception(f'acados_sim_solver for model {self.model_name} returned status {status}.') - - x_next = self.get('x') - return x_next - - - def solve(self): - """ - Solve the sim with current input. - """ - return acados_sim_solver.acados_sim_solve(self.capsule) - - - def get(self, field_): - """ - Get the last solution of the solver. - - :param str field: string in ['x', 'u', 'z', 'S_forw', 'Sx', 'Su', 'S_adj', 'S_hess', 'S_algebraic', 'CPUtime', 'time_tot', 'ADtime', 'time_ad', 'LAtime', 'time_la'] - """ - field = field_.encode('utf-8') - - if field_ in self.gettable_vectors: - return self.__get_vector(field) - elif field_ in self.gettable_matrices: - return self.__get_matrix(field) - elif field_ in self.gettable_scalars: - return self.__get_scalar(field) - else: - raise Exception(f'AcadosSimSolver.get(): Unknown field {field_},' \ - f' available fields are {", ".join(self.gettable.keys())}') - - - def __get_scalar(self, field): - cdef double scalar - acados_sim_solver_common.sim_out_get(self.sim_config, self.sim_dims, self.sim_out, field, &scalar) - return scalar - - - def __get_vector(self, field): - cdef int[2] dims - acados_sim_solver_common.sim_dims_get_from_attr(self.sim_config, self.sim_dims, field, &dims[0]) - # cdef cnp.ndarray[cnp.float64_t, ndim=1] out = np.ascontiguousarray(np.zeros((dims[0],), dtype=np.float64)) - cdef cnp.ndarray[cnp.float64_t, ndim=1] out = np.zeros((dims[0]),) - acados_sim_solver_common.sim_out_get(self.sim_config, self.sim_dims, self.sim_out, field, out.data) - return out - - - def __get_matrix(self, field): - cdef int[2] dims - acados_sim_solver_common.sim_dims_get_from_attr(self.sim_config, self.sim_dims, field, &dims[0]) - cdef cnp.ndarray[cnp.float64_t, ndim=2] out = np.zeros((dims[0], dims[1]), order='F', dtype=np.float64) - acados_sim_solver_common.sim_out_get(self.sim_config, self.sim_dims, self.sim_out, field, out.data) - return out - - - def set(self, field_: str, value_): - """ - Set numerical data inside the solver. - - :param field: string in ['p', 'seed_adj', 'T', 'x', 'u', 'xdot', 'z'] - :param value: the value with appropriate size. - """ - settable = ['seed_adj', 'T', 'x', 'u', 'xdot', 'z', 'p'] # S_forw - - # cast value_ to avoid conversion issues - if isinstance(value_, (float, int)): - value_ = np.array([value_]) - # if len(value_.shape) > 1: - # raise RuntimeError('AcadosSimSolverCython.set(): value_ should be 1 dimensional') - - cdef cnp.ndarray[cnp.float64_t, ndim=1] value = np.ascontiguousarray(value_, dtype=np.float64).flatten() - - field = field_.encode('utf-8') - cdef int[2] dims - - # treat parameters separately - if field_ == 'p': - assert acados_sim_solver.acados_sim_update_params(self.capsule, value.data, value.shape[0]) == 0 - return - else: - acados_sim_solver_common.sim_dims_get_from_attr(self.sim_config, self.sim_dims, field, &dims[0]) - - value_ = np.ravel(value_, order='F') - - value_shape = value_.shape - if len(value_shape) == 1: - value_shape = (value_shape[0], 0) - - if value_shape != tuple(dims): - raise Exception(f'AcadosSimSolverCython.set(): mismatching dimension' \ - f' for field "{field_}" with dimension {tuple(dims)} (you have {value_shape}).') - - # set - if field_ in ['xdot', 'z']: - acados_sim_solver_common.sim_solver_set(self.sim_solver, field, value.data) - elif field_ in settable: - acados_sim_solver_common.sim_in_set(self.sim_config, self.sim_dims, self.sim_in, field, value.data) - else: - raise Exception(f'AcadosSimSolverCython.set(): Unknown field {field_},' \ - f' available fields are {", ".join(settable)}') - - - def options_set(self, field_: str, value_: bool): - """ - Set solver options - - :param field: string in ['sens_forw', 'sens_adj', 'sens_hess'] - :param value: Boolean - """ - fields = ['sens_forw', 'sens_adj', 'sens_hess'] - if field_ not in fields: - raise Exception(f"field {field_} not supported. Supported values are {', '.join(fields)}.\n") - - field = field_.encode('utf-8') - - if not isinstance(value_, bool): - raise TypeError("options_set: expected boolean for value") - - cdef bint bool_value = value_ - acados_sim_solver_common.sim_opts_set(self.sim_config, self.sim_opts, field, &bool_value) - # TODO: only allow setting - # if getattr(self.acados_sim.solver_options, field_) or value_ == False: - # acados_sim_solver_common.sim_opts_set(self.sim_config, self.sim_opts, field, &bool_value) - # else: - # raise RuntimeError(f"Cannot set option {field_} to True, because it was False in original solver options.\n") - - return - - - def __del__(self): - if self.solver_created: - acados_sim_solver.acados_sim_free(self.capsule) - acados_sim_solver.acados_sim_solver_free_capsule(self.capsule) diff --git a/third_party/acados/acados_template/acados_solver_common.pxd b/third_party/acados/acados_template/acados_solver_common.pxd deleted file mode 100644 index c6d59d40a5..0000000000 --- a/third_party/acados/acados_template/acados_solver_common.pxd +++ /dev/null @@ -1,100 +0,0 @@ -# -*- coding: future_fstrings -*- -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# 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. -# -# 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.; -# - - -cdef extern from "acados/ocp_nlp/ocp_nlp_common.h": - ctypedef struct ocp_nlp_config: - pass - - ctypedef struct ocp_nlp_dims: - pass - - ctypedef struct ocp_nlp_in: - pass - - ctypedef struct ocp_nlp_out: - pass - - -cdef extern from "acados_c/ocp_nlp_interface.h": - ctypedef enum ocp_nlp_solver_t: - pass - - ctypedef enum ocp_nlp_cost_t: - pass - - ctypedef enum ocp_nlp_dynamics_t: - pass - - ctypedef enum ocp_nlp_constraints_t: - pass - - ctypedef enum ocp_nlp_reg_t: - pass - - ctypedef struct ocp_nlp_plan: - pass - - ctypedef struct ocp_nlp_solver: - pass - - int ocp_nlp_cost_model_set(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in_, - int start_stage, const char *field, void *value) - int ocp_nlp_constraints_model_set(ocp_nlp_config *config, ocp_nlp_dims *dims, - ocp_nlp_in *in_, int stage, const char *field, void *value) - - # out - void ocp_nlp_out_set(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_out *out, - int stage, const char *field, void *value) - void ocp_nlp_out_get(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_out *out, - int stage, const char *field, void *value) - void ocp_nlp_get_at_stage(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_solver *solver, - int stage, const char *field, void *value) - int ocp_nlp_dims_get_from_attr(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_out *out, - int stage, const char *field) - void ocp_nlp_constraint_dims_get_from_attr(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_out *out, - int stage, const char *field, int *dims_out) - void ocp_nlp_cost_dims_get_from_attr(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_out *out, - int stage, const char *field, int *dims_out) - void ocp_nlp_qp_dims_get_from_attr(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_out *out, - int stage, const char *field, int *dims_out) - - # opts - void ocp_nlp_solver_opts_set(ocp_nlp_config *config, void *opts_, const char *field, void* value) - - # solver - void ocp_nlp_eval_residuals(ocp_nlp_solver *solver, ocp_nlp_in *nlp_in, ocp_nlp_out *nlp_out) - void ocp_nlp_eval_param_sens(ocp_nlp_solver *solver, char *field, int stage, int index, ocp_nlp_out *sens_nlp_out) - void ocp_nlp_eval_cost(ocp_nlp_solver *solver, ocp_nlp_in *nlp_in_, ocp_nlp_out *nlp_out) - - # get/set - void ocp_nlp_get(ocp_nlp_config *config, ocp_nlp_solver *solver, const char *field, void *return_value_) - void ocp_nlp_set(ocp_nlp_config *config, ocp_nlp_solver *solver, int stage, const char *field, void *value) diff --git a/third_party/acados/acados_template/builders.py b/third_party/acados/acados_template/builders.py deleted file mode 100644 index 6f21bfe8cd..0000000000 --- a/third_party/acados/acados_template/builders.py +++ /dev/null @@ -1,131 +0,0 @@ -# -*- coding: future_fstrings -*- -# -# Copyright 2019 Gianluca Frison, Dimitris Kouzoupis, Robin Verschueren, -# Andrea Zanelli, Niels van Duijkeren, Jonathan Frey, Tommaso Sartor, -# Branimir Novoselnik, Rien Quirynen, Rezart Qelibari, Dang Doan, -# Jonas Koenemann, Yutao Chen, Tobias Schöls, Jonas Schlagenhauf, Moritz Diehl -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# 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. -# -# 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.; -# - -import os -import sys -from subprocess import DEVNULL, call, STDOUT - - -class CMakeBuilder: - """ - Class to work with the `CMake` build system. - """ - def __init__(self): - self._source_dir = None # private source directory, this is set to code_export_dir - self.build_dir = 'build' - self._build_dir = None # private build directory, usually rendered to abspath(build_dir) - self.generator = None - """Defines the generator, options can be found via `cmake --help` under 'Generator'. Type: string. Linux default 'Unix Makefiles', Windows 'Visual Studio 15 2017 Win64'; default value: `None`.""" - # set something for Windows - if os.name == 'nt': - self.generator = 'Visual Studio 15 2017 Win64' - self.build_targets = None - """A comma-separated list of the build targets, if `None` then all targets will be build; type: List of strings; default: `None`.""" - self.options_on = None - """List of strings as CMake options which are translated to '-D Opt[0]=ON -D Opt[1]=ON ...'; default: `None`.""" - - # Generate the command string for handling the cmake command. - def get_cmd1_cmake(self): - defines_str = '' - if self.options_on is not None: - defines_arr = [f' -D{opt}=ON' for opt in self.options_on] - defines_str = ' '.join(defines_arr) - generator_str = '' - if self.generator is not None: - generator_str = f' -G"{self.generator}"' - return f'cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX="{self._source_dir}"{defines_str}{generator_str} -Wdev -S"{self._source_dir}" -B"{self._build_dir}"' - - # Generate the command string for handling the build. - def get_cmd2_build(self): - import multiprocessing - cmd = f'cmake --build "{self._build_dir}" --config Release -j{multiprocessing.cpu_count()}' - if self.build_targets is not None: - cmd += f' -t {self.build_targets}' - return cmd - - # Generate the command string for handling the install command. - def get_cmd3_install(self): - return f'cmake --install "{self._build_dir}"' - - def exec(self, code_export_directory, verbose=True): - """ - Execute the compilation using `CMake` with the given settings. - :param code_export_directory: must be the absolute path to the directory where the code was exported to - """ - if(os.path.isabs(code_export_directory) is False): - print(f'(W) the code export directory "{code_export_directory}" is not an absolute path!') - self._source_dir = code_export_directory - self._build_dir = os.path.abspath(self.build_dir) - try: - os.mkdir(self._build_dir) - except FileExistsError as e: - pass - - try: - os.chdir(self._build_dir) - cmd_str = self.get_cmd1_cmake() - print(f'call("{cmd_str})"') - retcode = call( - cmd_str, - shell=True, - stdout=None if verbose else DEVNULL, - stderr=None if verbose else STDOUT - ) - if retcode != 0: - raise RuntimeError(f'CMake command "{cmd_str}" was terminated by signal {retcode}') - cmd_str = self.get_cmd2_build() - print(f'call("{cmd_str}")') - retcode = call( - cmd_str, - shell=True, - stdout=None if verbose else DEVNULL, - stderr=None if verbose else STDOUT - ) - if retcode != 0: - raise RuntimeError(f'Build command "{cmd_str}" was terminated by signal {retcode}') - cmd_str = self.get_cmd3_install() - print(f'call("{cmd_str}")') - retcode = call( - cmd_str, - shell=True, - stdout=None if verbose else DEVNULL, - stderr=None if verbose else STDOUT - ) - if retcode != 0: - raise RuntimeError(f'Install command "{cmd_str}" was terminated by signal {retcode}') - except OSError as e: - print("Execution failed:", e, file=sys.stderr) - except Exception as e: - print("Execution failed:", e, file=sys.stderr) - exit(1) diff --git a/third_party/acados/acados_template/c_templates_tera/CMakeLists.in.txt b/third_party/acados/acados_template/c_templates_tera/CMakeLists.in.txt deleted file mode 100644 index 99bc26f750..0000000000 --- a/third_party/acados/acados_template/c_templates_tera/CMakeLists.in.txt +++ /dev/null @@ -1,397 +0,0 @@ -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# 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. -# -# 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.; -# - -{%- if solver_options.qp_solver %} - {%- set qp_solver = solver_options.qp_solver %} -{%- else %} - {%- set qp_solver = "FULL_CONDENSING_HPIPM" %} -{%- endif %} - -{%- if solver_options.hessian_approx %} - {%- set hessian_approx = solver_options.hessian_approx %} -{%- elif solver_options.sens_hess %} - {%- set hessian_approx = "EXACT" %} -{%- else %} - {%- set hessian_approx = "GAUSS_NEWTON" %} -{%- endif %} - -{%- if constraints.constr_type %} - {%- set constr_type = constraints.constr_type %} -{%- else %} - {%- set constr_type = "NONE" %} -{%- endif %} - -{%- if constraints.constr_type_e %} - {%- set constr_type_e = constraints.constr_type_e %} -{%- else %} - {%- set constr_type_e = "NONE" %} -{%- endif %} - -{%- if cost.cost_type %} - {%- set cost_type = cost.cost_type %} -{%- else %} - {%- set cost_type = "NONE" %} -{%- endif %} - -{%- if cost.cost_type_e %} - {%- set cost_type_e = cost.cost_type_e %} -{%- else %} - {%- set cost_type_e = "NONE" %} -{%- endif %} - -{%- if cost.cost_type_0 %} - {%- set cost_type_0 = cost.cost_type_0 %} -{%- else %} - {%- set cost_type_0 = "NONE" %} -{%- endif %} - -{%- if dims.nh %} - {%- set dims_nh = dims.nh %} -{%- else %} - {%- set dims_nh = 0 %} -{%- endif %} - -{%- if dims.nphi %} - {%- set dims_nphi = dims.nphi %} -{%- else %} - {%- set dims_nphi = 0 %} -{%- endif %} - -{%- if dims.nh_e %} - {%- set dims_nh_e = dims.nh_e %} -{%- else %} - {%- set dims_nh_e = 0 %} -{%- endif %} - -{%- if dims.nphi_e %} - {%- set dims_nphi_e = dims.nphi_e %} -{%- else %} - {%- set dims_nphi_e = 0 %} -{%- endif %} - -{%- if solver_options.model_external_shared_lib_dir %} - {%- set model_external_shared_lib_dir = solver_options.model_external_shared_lib_dir %} -{%- endif %} - -{%- if solver_options.model_external_shared_lib_name %} - {%- set model_external_shared_lib_name = solver_options.model_external_shared_lib_name %} -{%- endif %} - -{#- control operator #} -{%- if os and os == "pc" %} - {%- set control = "&" %} -{%- else %} - {%- set control = ";" %} -{%- endif %} - -{%- if acados_link_libs and os and os == "pc" %}{# acados linking libraries and flags #} - {%- set link_libs = acados_link_libs.qpoases ~ " " ~ acados_link_libs.hpmpc ~ " " ~ acados_link_libs.osqp -%} - {%- set openmp_flag = acados_link_libs.openmp %} -{%- else %} - {%- set openmp_flag = " " %} - {%- if qp_solver == "FULL_CONDENSING_QPOASES" %} - {%- set link_libs = "-lqpOASES_e" %} - {%- elif qp_solver == "FULL_CONDENSING_DAQP" %} - {%- set link_libs = "-ldaqp" %} - {%- else %} - {%- set link_libs = "" %} - {%- endif %} -{%- endif %} - -cmake_minimum_required(VERSION 3.13) - -project({{ model.name }}) - -# build options. -option(BUILD_ACADOS_SOLVER_LIB "Should the solver library acados_solver_{{ model.name }} be build?" OFF) -option(BUILD_ACADOS_OCP_SOLVER_LIB "Should the OCP solver library acados_ocp_solver_{{ model.name }} be build?" OFF) -option(BUILD_EXAMPLE "Should the example main_{{ model.name }} be build?" OFF) -{%- if solver_options.integrator_type != "DISCRETE" %} -option(BUILD_SIM_EXAMPLE "Should the simulation example main_sim_{{ model.name }} be build?" OFF) -option(BUILD_ACADOS_SIM_SOLVER_LIB "Should the simulation solver library acados_sim_solver_{{ model.name }} be build?" OFF) -{%- endif %} - - -if(CMAKE_CXX_COMPILER_ID MATCHES "GNU" AND CMAKE_SYSTEM_NAME MATCHES "Windows") - # MinGW, change to .lib such that mex recognizes it - set(CMAKE_SHARED_LIBRARY_SUFFIX ".lib") - set(CMAKE_SHARED_LIBRARY_PREFIX "") -endif() - - -# object target names -set(MODEL_OBJ model_{{ model.name }}) -set(OCP_OBJ ocp_{{ model.name }}) -set(SIM_OBJ sim_{{ model.name }}) - -# model -set(MODEL_SRC - {%- if model.dyn_ext_fun_type == "casadi" %} -{%- if solver_options.integrator_type == "ERK" %} - {{ model.name }}_model/{{ model.name }}_expl_ode_fun.c - {{ model.name }}_model/{{ model.name }}_expl_vde_forw.c - {{ model.name }}_model/{{ model.name }}_expl_vde_adj.c - {%- if hessian_approx == "EXACT" %} - {{ model.name }}_model/{{ model.name }}_expl_ode_hess.c - {%- endif %} -{%- elif solver_options.integrator_type == "IRK" %} - {{ model.name }}_model/{{ model.name }}_impl_dae_fun.c - {{ model.name }}_model/{{ model.name }}_impl_dae_fun_jac_x_xdot_z.c - {{ model.name }}_model/{{ model.name }}_impl_dae_jac_x_xdot_u_z.c - {%- if hessian_approx == "EXACT" %} - {{ model.name }}_model/{{ model.name }}_impl_dae_hess.c - {%- endif %} -{%- elif solver_options.integrator_type == "LIFTED_IRK" %} - {{ model.name }}_model/{{ model.name }}_impl_dae_fun.c - {{ model.name }}_model/{{ model.name }}_impl_dae_fun_jac_x_xdot_u.c - {%- if hessian_approx == "EXACT" %} - {{ model.name }}_model/{{ model.name }}_impl_dae_hess.c - {%- endif %} -{%- elif solver_options.integrator_type == "GNSF" %} - {% if model.gnsf.purely_linear != 1 %} - {{ model.name }}_model/{{ model.name }}_gnsf_phi_fun.c - {{ model.name }}_model/{{ model.name }}_gnsf_phi_fun_jac_y.c - {{ model.name }}_model/{{ model.name }}_gnsf_phi_jac_y_uhat.c - {% if model.gnsf.nontrivial_f_LO == 1 %} - {{ model.name }}_model/{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz.c - {%- endif %} - {%- endif %} - {{ model.name }}_model/{{ model.name }}_gnsf_get_matrices_fun.c -{%- elif solver_options.integrator_type == "DISCRETE" %} - {{ model.name }}_model/{{ model.name }}_dyn_disc_phi_fun.c - {{ model.name }}_model/{{ model.name }}_dyn_disc_phi_fun_jac.c - {%- if hessian_approx == "EXACT" %} - {{ model.name }}_model/{{ model.name }}_dyn_disc_phi_fun_jac_hess.c - {%- endif %} -{%- endif -%} - {%- else %} - {{ model.name }}_model/{{ model.dyn_generic_source }} - {%- endif %} -) -add_library(${MODEL_OBJ} OBJECT ${MODEL_SRC} ) - -# optimal control problem - mostly CasADi exports -if(${BUILD_ACADOS_SOLVER_LIB} OR ${BUILD_ACADOS_OCP_SOLVER_LIB} OR ${BUILD_EXAMPLE}) - set(OCP_SRC -{%- if constr_type == "BGP" and dims_nphi > 0 %} - {{ model.name }}_constraints/{{ model.name }}_phi_constraint.c -{%- endif %} -{%- if constr_type_e == "BGP" and dims_nphi_e > 0 %} - {{ model.name }}_constraints/{{ model.name }}_phi_e_constraint.c -{%- endif %} - -{%- if constr_type == "BGH" and dims_nh > 0 %} - {{ model.name }}_constraints/{{ model.name }}_constr_h_fun_jac_uxt_zt.c - {{ model.name }}_constraints/{{ model.name }}_constr_h_fun.c - {%- if hessian_approx == "EXACT" %} - {{ model.name }}_constraints/{{ model.name }}_constr_h_fun_jac_uxt_zt_hess.c - {%- endif %} -{%- endif %} - -{%- if constr_type_e == "BGH" and dims_nh_e > 0 %} - {{ model.name }}_constraints/{{ model.name }}_constr_h_e_fun_jac_uxt_zt.c - {{ model.name }}_constraints/{{ model.name }}_constr_h_e_fun.c - {%- if hessian_approx == "EXACT" %} - {{ model.name }}_constraints/{{ model.name }}_constr_h_e_fun_jac_uxt_zt_hess.c - {%- endif %} -{%- endif %} - -{%- if cost_type_0 == "NONLINEAR_LS" %} - {{ model.name }}_cost/{{ model.name }}_cost_y_0_fun.c - {{ model.name }}_cost/{{ model.name }}_cost_y_0_fun_jac_ut_xt.c - {{ model.name }}_cost/{{ model.name }}_cost_y_0_hess.c -{%- elif cost_type_0 == "CONVEX_OVER_NONLINEAR" %} - {{ model.name }}_cost/{{ model.name }}_conl_cost_0_fun.c - {{ model.name }}_cost/{{ model.name }}_conl_cost_0_fun_jac_hess.c -{%- elif cost_type_0 == "EXTERNAL" %} - {%- if cost.cost_ext_fun_type_0 == "casadi" %} - {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_0_fun.c - {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_0_fun_jac.c - {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_0_fun_jac_hess.c - {%- else %} - {{ model.name }}_cost/{{ cost.cost_source_ext_cost_0 }} - {%- endif %} -{%- endif %} -{%- if cost_type == "NONLINEAR_LS" %} - {{ model.name }}_cost/{{ model.name }}_cost_y_fun.c - {{ model.name }}_cost/{{ model.name }}_cost_y_fun_jac_ut_xt.c - {{ model.name }}_cost/{{ model.name }}_cost_y_hess.c -{%- elif cost_type == "CONVEX_OVER_NONLINEAR" %} - {{ model.name }}_cost/{{ model.name }}_conl_cost_fun.c - {{ model.name }}_cost/{{ model.name }}_conl_cost_fun_jac_hess.c -{%- elif cost_type == "EXTERNAL" %} - {%- if cost.cost_ext_fun_type == "casadi" %} - {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_fun.c - {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_fun_jac.c - {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_fun_jac_hess.c - {%- elif cost.cost_source_ext_cost != cost.cost_source_ext_cost_0 %} - {{ model.name }}_cost/{{ cost.cost_source_ext_cost }} - {%- endif %} -{%- endif %} -{%- if cost_type_e == "NONLINEAR_LS" %} - {{ model.name }}_cost/{{ model.name }}_cost_y_e_fun.c - {{ model.name }}_cost/{{ model.name }}_cost_y_e_fun_jac_ut_xt.c - {{ model.name }}_cost/{{ model.name }}_cost_y_e_hess.c -{%- elif cost_type_e == "CONVEX_OVER_NONLINEAR" %} - {{ model.name }}_cost/{{ model.name }}_conl_cost_e_fun.c - {{ model.name }}_cost/{{ model.name }}_conl_cost_e_fun_jac_hess.c -{%- elif cost_type_e == "EXTERNAL" %} - {%- if cost.cost_ext_fun_type_e == "casadi" %} - {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_e_fun.c - {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_e_fun_jac.c - {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_e_fun_jac_hess.c - {%- elif cost.cost_source_ext_cost_e != cost.cost_source_ext_cost_0 %} - {{ model.name }}_cost/{{ cost.cost_source_ext_cost_e }} - {%- endif %} -{%- endif %} - acados_solver_{{ model.name }}.c) - add_library(${OCP_OBJ} OBJECT ${OCP_SRC}) -endif() - -{%- if solver_options.integrator_type != "DISCRETE" %} -# for sim solver -if(${BUILD_ACADOS_SOLVER_LIB} OR ${BUILD_EXAMPLE} - {%- if solver_options.integrator_type != "DISCRETE" %} - OR ${BUILD_SIM_EXAMPLE} OR ${BUILD_ACADOS_SIM_SOLVER_LIB} - {%- endif -%} - ) - set(SIM_SRC acados_sim_solver_{{ model.name }}.c) - add_library(${SIM_OBJ} OBJECT ${SIM_SRC}) -endif() -{%- endif %} - -# for target example -set(EX_SRC main_{{ model.name }}.c) -set(EX_EXE main_{{ model.name }}) - -{%- if model_external_shared_lib_dir and model_external_shared_lib_name %} -set(EXTERNAL_DIR {{ model_external_shared_lib_dir | replace(from="\", to="/") }}) -set(EXTERNAL_LIB {{ model_external_shared_lib_name }}) -{%- else %} -set(EXTERNAL_DIR) -set(EXTERNAL_LIB) -{%- endif %} - -# set some search paths for preprocessor and linker -set(ACADOS_INCLUDE_PATH {{ acados_include_path | replace(from="\", to="/") }} CACHE PATH "Define the path which contains the include directory for acados.") -set(ACADOS_LIB_PATH {{ acados_lib_path | replace(from="\", to="/") }} CACHE PATH "Define the path which contains the lib directory for acados.") - -# c-compiler flags for debugging -set(CMAKE_C_FLAGS_DEBUG "-O0 -ggdb") - -set(CMAKE_C_FLAGS "-fPIC -std=c99 {{ openmp_flag }} -{%- if qp_solver == "FULL_CONDENSING_QPOASES" -%} - -DACADOS_WITH_QPOASES -{%- endif -%} -{%- if qp_solver == "FULL_CONDENSING_DAQP" -%} - -DACADOS_WITH_DAQP -{%- endif -%} -{%- if qp_solver == "PARTIAL_CONDENSING_OSQP" -%} - -DACADOS_WITH_OSQP -{%- endif -%} -{%- if qp_solver == "PARTIAL_CONDENSING_QPDUNES" -%} - -DACADOS_WITH_QPDUNES -{%- endif -%} -") -#-fno-diagnostics-show-line-numbers -g - -include_directories( - ${ACADOS_INCLUDE_PATH} - ${ACADOS_INCLUDE_PATH}/acados - ${ACADOS_INCLUDE_PATH}/blasfeo/include - ${ACADOS_INCLUDE_PATH}/hpipm/include -{%- if qp_solver == "FULL_CONDENSING_QPOASES" %} - ${ACADOS_INCLUDE_PATH}/qpOASES_e/ -{%- endif %} -{%- if qp_solver == "FULL_CONDENSING_DAQP" %} - ${ACADOS_INCLUDE_PATH}/daqp/include -{%- endif %} -) - -# linker flags -link_directories(${ACADOS_LIB_PATH}) - -# link to libraries -if(UNIX) - link_libraries(acados hpipm blasfeo m {{ link_libs }}) -else() - link_libraries(acados hpipm blasfeo {{ link_libs }}) -endif() - -# the targets - -# bundled_shared_lib -if(${BUILD_ACADOS_SOLVER_LIB}) - set(LIB_ACADOS_SOLVER acados_solver_{{ model.name }}) - add_library(${LIB_ACADOS_SOLVER} SHARED $ $ - {%- if solver_options.integrator_type != "DISCRETE" %} - $ - {%- endif -%} - ) - install(TARGETS ${LIB_ACADOS_SOLVER} DESTINATION ${CMAKE_INSTALL_PREFIX}) -endif(${BUILD_ACADOS_SOLVER_LIB}) - -# ocp_shared_lib -if(${BUILD_ACADOS_OCP_SOLVER_LIB}) - set(LIB_ACADOS_OCP_SOLVER acados_ocp_solver_{{ model.name }}) - add_library(${LIB_ACADOS_OCP_SOLVER} SHARED $ $) - # Specify libraries or flags to use when linking a given target and/or its dependents. - target_link_libraries(${LIB_ACADOS_OCP_SOLVER} PRIVATE ${EXTERNAL_LIB}) - target_link_directories(${LIB_ACADOS_OCP_SOLVER} PRIVATE ${EXTERNAL_DIR}) - install(TARGETS ${LIB_ACADOS_OCP_SOLVER} DESTINATION ${CMAKE_INSTALL_PREFIX}) -endif(${BUILD_ACADOS_OCP_SOLVER_LIB}) - -# example -if(${BUILD_EXAMPLE}) - add_executable(${EX_EXE} ${EX_SRC} $ $ - {%- if solver_options.integrator_type != "DISCRETE" %} - $ - {%- endif -%} - ) - install(TARGETS ${EX_EXE} DESTINATION ${CMAKE_INSTALL_PREFIX}) -endif(${BUILD_EXAMPLE}) - -{% if solver_options.integrator_type != "DISCRETE" -%} -# example_sim -if(${BUILD_SIM_EXAMPLE}) - set(EX_SIM_SRC main_sim_{{ model.name }}.c) - set(EX_SIM_EXE main_sim_{{ model.name }}) - add_executable(${EX_SIM_EXE} ${EX_SIM_SRC} $ $) - install(TARGETS ${EX_SIM_EXE} DESTINATION ${CMAKE_INSTALL_PREFIX}) -endif(${BUILD_SIM_EXAMPLE}) - -# sim_shared_lib -if(${BUILD_ACADOS_SIM_SOLVER_LIB}) - set(LIB_ACADOS_SIM_SOLVER acados_sim_solver_{{ model.name }}) - add_library(${LIB_ACADOS_SIM_SOLVER} SHARED $ $) - install(TARGETS ${LIB_ACADOS_SIM_SOLVER} DESTINATION ${CMAKE_INSTALL_PREFIX}) -endif(${BUILD_ACADOS_SIM_SOLVER_LIB}) -{%- endif %} - diff --git a/third_party/acados/acados_template/c_templates_tera/Makefile.in b/third_party/acados/acados_template/c_templates_tera/Makefile.in deleted file mode 100644 index fbefc08e38..0000000000 --- a/third_party/acados/acados_template/c_templates_tera/Makefile.in +++ /dev/null @@ -1,468 +0,0 @@ -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# 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. -# -# 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.; -# - -{%- if solver_options.qp_solver %} - {%- set qp_solver = solver_options.qp_solver %} -{%- else %} - {%- set qp_solver = "FULL_CONDENSING_HPIPM" %} -{%- endif %} - -{%- if solver_options.hessian_approx %} - {%- set hessian_approx = solver_options.hessian_approx %} -{%- elif solver_options.sens_hess %} - {%- set hessian_approx = "EXACT" %} -{%- else %} - {%- set hessian_approx = "GAUSS_NEWTON" %} -{%- endif %} - -{%- if constraints.constr_type %} - {%- set constr_type = constraints.constr_type %} -{%- else %} - {%- set constr_type = "NONE" %} -{%- endif %} - -{%- if constraints.constr_type_e %} - {%- set constr_type_e = constraints.constr_type_e %} -{%- else %} - {%- set constr_type_e = "NONE" %} -{%- endif %} - -{%- if cost.cost_type %} - {%- set cost_type = cost.cost_type %} -{%- else %} - {%- set cost_type = "NONE" %} -{%- endif %} - -{%- if cost.cost_type_e %} - {%- set cost_type_e = cost.cost_type_e %} -{%- else %} - {%- set cost_type_e = "NONE" %} -{%- endif %} - -{%- if cost.cost_type_0 %} - {%- set cost_type_0 = cost.cost_type_0 %} -{%- else %} - {%- set cost_type_0 = "NONE" %} -{%- endif %} - -{%- if dims.nh %} - {%- set dims_nh = dims.nh %} -{%- else %} - {%- set dims_nh = 0 %} -{%- endif %} - -{%- if dims.nphi %} - {%- set dims_nphi = dims.nphi %} -{%- else %} - {%- set dims_nphi = 0 %} -{%- endif %} - -{%- if dims.nh_e %} - {%- set dims_nh_e = dims.nh_e %} -{%- else %} - {%- set dims_nh_e = 0 %} -{%- endif %} - -{%- if dims.nphi_e %} - {%- set dims_nphi_e = dims.nphi_e %} -{%- else %} - {%- set dims_nphi_e = 0 %} -{%- endif %} -{%- if solver_options.model_external_shared_lib_dir %} - {%- set model_external_shared_lib_dir = solver_options.model_external_shared_lib_dir %} -{%- endif %} -{%- if solver_options.model_external_shared_lib_name %} - {%- set model_external_shared_lib_name = solver_options.model_external_shared_lib_name %} -{%- endif %} - -{# control operator #} -{%- if os and os == "pc" %} - {%- set control = "&" %} -{%- else %} - {%- set control = ";" %} -{%- endif %} - -{# acados linking libraries and flags #} -{%- if acados_link_libs and os and os == "pc" %} - {%- set link_libs = acados_link_libs.qpoases ~ " " ~ acados_link_libs.hpmpc ~ " " ~ acados_link_libs.osqp -%} - {%- set openmp_flag = acados_link_libs.openmp %} -{%- else %} - {%- set openmp_flag = " " %} - {%- if qp_solver == "FULL_CONDENSING_QPOASES" %} - {%- set link_libs = "-lqpOASES_e" %} - {%- elif qp_solver == "FULL_CONDENSING_DAQP" %} - {%- set link_libs = "-ldaqp" %} - {%- else %} - {%- set link_libs = "" %} - {%- endif %} -{%- endif %} - -# define sources and use make's implicit rules to generate object files (*.o) - -# model -MODEL_SRC= - {%- if model.dyn_ext_fun_type == "casadi" %} -{%- if solver_options.integrator_type == "ERK" %} -MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_expl_ode_fun.c -MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_expl_vde_forw.c -MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_expl_vde_adj.c - {%- if hessian_approx == "EXACT" %} -MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_expl_ode_hess.c - {%- endif %} -{%- elif solver_options.integrator_type == "IRK" %} -MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_impl_dae_fun.c -MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_impl_dae_fun_jac_x_xdot_z.c -MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_impl_dae_jac_x_xdot_u_z.c - {%- if hessian_approx == "EXACT" %} -MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_impl_dae_hess.c - {%- endif %} -{%- elif solver_options.integrator_type == "LIFTED_IRK" %} -MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_impl_dae_fun.c -MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_impl_dae_fun_jac_x_xdot_u.c - {%- if hessian_approx == "EXACT" %} -MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_impl_dae_hess.c - {%- endif %} -{%- elif solver_options.integrator_type == "GNSF" %} - {% if model.gnsf.purely_linear != 1 %} -MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_gnsf_phi_fun.c -MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_gnsf_phi_fun_jac_y.c -MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_gnsf_phi_jac_y_uhat.c - {% if model.gnsf.nontrivial_f_LO == 1 %} -MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz.c - {%- endif %} - {%- endif %} -MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_gnsf_get_matrices_fun.c -{%- elif solver_options.integrator_type == "DISCRETE" %} -MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_dyn_disc_phi_fun.c -MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_dyn_disc_phi_fun_jac.c - {%- if hessian_approx == "EXACT" %} -MODEL_SRC+= {{ model.name }}_model/{{ model.name }}_dyn_disc_phi_fun_jac_hess.c - {%- endif %} -{%- endif %} - {%- else %} -MODEL_SRC+= {{ model.name }}_model/{{ model.dyn_generic_source }} - {%- endif %} -MODEL_OBJ := $(MODEL_SRC:.c=.o) - -# optimal control problem - mostly CasADi exports -OCP_SRC= -{%- if constr_type == "BGP" and dims_nphi > 0 %} -OCP_SRC+= {{ model.name }}_constraints/{{ model.name }}_phi_constraint.c -{%- endif %} -{%- if constr_type_e == "BGP" and dims_nphi_e > 0 %} -OCP_SRC+= {{ model.name }}_constraints/{{ model.name }}_phi_e_constraint.c -{%- endif %} - -{%- if constr_type == "BGH" and dims_nh > 0 %} -OCP_SRC+= {{ model.name }}_constraints/{{ model.name }}_constr_h_fun_jac_uxt_zt.c -OCP_SRC+= {{ model.name }}_constraints/{{ model.name }}_constr_h_fun.c - {%- if hessian_approx == "EXACT" %} -OCP_SRC+= {{ model.name }}_constraints/{{ model.name }}_constr_h_fun_jac_uxt_zt_hess.c - {%- endif %} -{%- endif %} - -{%- if constr_type_e == "BGH" and dims_nh_e > 0 %} -OCP_SRC+= {{ model.name }}_constraints/{{ model.name }}_constr_h_e_fun_jac_uxt_zt.c -OCP_SRC+= {{ model.name }}_constraints/{{ model.name }}_constr_h_e_fun.c - {%- if hessian_approx == "EXACT" %} -OCP_SRC+= {{ model.name }}_constraints/{{ model.name }}_constr_h_e_fun_jac_uxt_zt_hess.c - {%- endif %} -{%- endif %} - -{%- if cost_type_0 == "NONLINEAR_LS" %} -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_y_0_fun.c -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_y_0_fun_jac_ut_xt.c -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_y_0_hess.c -{%- elif cost_type_0 == "CONVEX_OVER_NONLINEAR" %} -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_conl_cost_0_fun.c -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_conl_cost_0_fun_jac_hess.c -{%- elif cost_type_0 == "EXTERNAL" %} - {%- if cost.cost_ext_fun_type_0 == "casadi" %} -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_0_fun.c -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_0_fun_jac.c -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_0_fun_jac_hess.c - {%- else %} -OCP_SRC+= {{ model.name }}_cost/{{ cost.cost_source_ext_cost_0 }} - {%- endif %} -{%- endif %} -{%- if cost_type == "NONLINEAR_LS" %} -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_y_fun.c -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_y_fun_jac_ut_xt.c -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_y_hess.c -{%- elif cost_type == "CONVEX_OVER_NONLINEAR" %} -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_conl_cost_fun.c -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_conl_cost_fun_jac_hess.c -{%- elif cost_type == "EXTERNAL" %} - {%- if cost.cost_ext_fun_type == "casadi" %} -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_fun.c -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_fun_jac.c -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_fun_jac_hess.c - {%- elif cost.cost_source_ext_cost != cost.cost_source_ext_cost_0 %} -OCP_SRC+= {{ model.name }}_cost/{{ cost.cost_source_ext_cost }} - {%- endif %} -{%- endif %} -{%- if cost_type_e == "NONLINEAR_LS" %} -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_y_e_fun.c -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_y_e_fun_jac_ut_xt.c -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_y_e_hess.c -{%- elif cost_type_e == "CONVEX_OVER_NONLINEAR" %} -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_conl_cost_e_fun.c -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_conl_cost_e_fun_jac_hess.c -{%- elif cost_type_e == "EXTERNAL" %} - {%- if cost.cost_ext_fun_type_e == "casadi" %} -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_e_fun.c -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_e_fun_jac.c -OCP_SRC+= {{ model.name }}_cost/{{ model.name }}_cost_ext_cost_e_fun_jac_hess.c - {%- elif cost.cost_source_ext_cost_e != cost.cost_source_ext_cost_0 %} -OCP_SRC+= {{ model.name }}_cost/{{ cost.cost_source_ext_cost_e }} - {%- endif %} -{%- endif %} -{%- if solver_options.custom_update_filename %} - {%- if solver_options.custom_update_filename != "" %} -OCP_SRC+= {{ solver_options.custom_update_filename }} - {%- endif %} -{%- endif %} - -OCP_SRC+= acados_solver_{{ model.name }}.c -OCP_OBJ := $(OCP_SRC:.c=.o) - -# for sim solver -SIM_SRC= acados_sim_solver_{{ model.name }}.c -SIM_OBJ := $(SIM_SRC:.c=.o) - -# for target example -EX_SRC= main_{{ model.name }}.c -EX_OBJ := $(EX_SRC:.c=.o) -EX_EXE := $(EX_SRC:.c=) - -# for target example_sim -EX_SIM_SRC= main_sim_{{ model.name }}.c -EX_SIM_OBJ := $(EX_SIM_SRC:.c=.o) -EX_SIM_EXE := $(EX_SIM_SRC:.c=) - -# combine model, sim and ocp object files -OBJ= -OBJ+= $(MODEL_OBJ) -{%- if solver_options.integrator_type != "DISCRETE" %} -OBJ+= $(SIM_OBJ) -{%- endif %} -OBJ+= $(OCP_OBJ) - -EXTERNAL_DIR= -EXTERNAL_LIB= - -{%- if model_external_shared_lib_dir and model_external_shared_lib_name %} -EXTERNAL_DIR+= {{ model_external_shared_lib_dir }} -EXTERNAL_LIB+= {{ model_external_shared_lib_name }} -{%- endif %} - -INCLUDE_PATH = {{ acados_include_path }} -LIB_PATH = {{ acados_lib_path }} - -# preprocessor flags for make's implicit rules -{%- if qp_solver == "FULL_CONDENSING_QPOASES" %} -CPPFLAGS += -DACADOS_WITH_QPOASES -{%- endif %} -{%- if qp_solver == "FULL_CONDENSING_DAQP" %} -CPPFLAGS += -DACADOS_WITH_DAQP -{%- endif %} -{%- if qp_solver == "PARTIAL_CONDENSING_OSQP" %} -CPPFLAGS += -DACADOS_WITH_OSQP -{%- endif %} -{%- if qp_solver == "PARTIAL_CONDENSING_QPDUNES" %} -CPPFLAGS += -DACADOS_WITH_QPDUNES -{%- endif %} -CPPFLAGS+= -I$(INCLUDE_PATH) -CPPFLAGS+= -I$(INCLUDE_PATH)/acados -CPPFLAGS+= -I$(INCLUDE_PATH)/blasfeo/include -CPPFLAGS+= -I$(INCLUDE_PATH)/hpipm/include - {%- if qp_solver == "FULL_CONDENSING_QPOASES" %} -CPPFLAGS+= -I $(INCLUDE_PATH)/qpOASES_e/ - {%- endif %} - {%- if qp_solver == "FULL_CONDENSING_DAQP" %} -CPPFLAGS+= -I $(INCLUDE_PATH)/daqp/include - {%- endif %} - -{# c-compiler flags #} -# define the c-compiler flags for make's implicit rules -CFLAGS = -fPIC -std=c99 {{ openmp_flag }} {{ solver_options.ext_fun_compile_flags }}#-fno-diagnostics-show-line-numbers -g -# # Debugging -# CFLAGS += -g3 - -# linker flags -LDFLAGS+= -L$(LIB_PATH) - -# link to libraries -LDLIBS+= -lacados -LDLIBS+= -lhpipm -LDLIBS+= -lblasfeo -LDLIBS+= -lm -LDLIBS+= {{ link_libs }} - -# libraries -LIBACADOS_SOLVER=libacados_solver_{{ model.name }}{{ shared_lib_ext }} -LIBACADOS_OCP_SOLVER=libacados_ocp_solver_{{ model.name }}{{ shared_lib_ext }} -LIBACADOS_SIM_SOLVER=lib$(SIM_SRC:.c={{ shared_lib_ext }}) - -# virtual targets -.PHONY : all clean - -#all: clean example_sim example shared_lib -{% if solver_options.integrator_type == "DISCRETE" -%} -all: clean example -shared_lib: ocp_shared_lib -{%- else %} -all: clean example_sim example -shared_lib: bundled_shared_lib ocp_shared_lib sim_shared_lib -{%- endif %} - -# some linker targets -example: $(EX_OBJ) $(OBJ) - $(CC) $^ -o $(EX_EXE) $(LDFLAGS) $(LDLIBS) - -example_sim: $(EX_SIM_OBJ) $(MODEL_OBJ) $(SIM_OBJ) - $(CC) $^ -o $(EX_SIM_EXE) $(LDFLAGS) $(LDLIBS) - -{% if solver_options.integrator_type != "DISCRETE" -%} -bundled_shared_lib: $(OBJ) - $(CC) -shared $^ -o $(LIBACADOS_SOLVER) $(LDFLAGS) $(LDLIBS) -{%- endif %} - -ocp_shared_lib: $(OCP_OBJ) $(MODEL_OBJ) - $(CC) -shared $^ -o $(LIBACADOS_OCP_SOLVER) $(LDFLAGS) $(LDLIBS) \ - -L$(EXTERNAL_DIR) -l$(EXTERNAL_LIB) - -sim_shared_lib: $(SIM_OBJ) $(MODEL_OBJ) - $(CC) -shared $^ -o $(LIBACADOS_SIM_SOLVER) $(LDFLAGS) $(LDLIBS) - - -# Cython targets -ocp_cython_c: ocp_shared_lib - cython \ - -o acados_ocp_solver_pyx.c \ - -I $(INCLUDE_PATH)/../interfaces/acados_template/acados_template \ - $(INCLUDE_PATH)/../interfaces/acados_template/acados_template/acados_ocp_solver_pyx.pyx \ - -I {{ code_export_directory }} \ - -ocp_cython_o: ocp_cython_c - $(CC) $(ACADOS_FLAGS) -c -O2 \ - -fPIC \ - -o acados_ocp_solver_pyx.o \ - -I $(INCLUDE_PATH)/blasfeo/include/ \ - -I $(INCLUDE_PATH)/hpipm/include/ \ - -I $(INCLUDE_PATH) \ - {%- for path in cython_include_dirs %} - -I {{ path }} \ - {%- endfor %} - acados_ocp_solver_pyx.c \ - -ocp_cython: ocp_cython_o - $(CC) $(ACADOS_FLAGS) -shared \ - -o acados_ocp_solver_pyx{{ shared_lib_ext }} \ - -Wl,-rpath=$(LIB_PATH) \ - acados_ocp_solver_pyx.o \ - $(abspath .)/libacados_ocp_solver_{{ model.name }}{{ shared_lib_ext }} \ - $(LDFLAGS) $(LDLIBS) - -# Sim Cython targets -sim_cython_c: sim_shared_lib - cython \ - -o acados_sim_solver_pyx.c \ - -I $(INCLUDE_PATH)/../interfaces/acados_template/acados_template \ - $(INCLUDE_PATH)/../interfaces/acados_template/acados_template/acados_sim_solver_pyx.pyx \ - -I {{ code_export_directory }} \ - -sim_cython_o: sim_cython_c - $(CC) $(ACADOS_FLAGS) -c -O2 \ - -fPIC \ - -o acados_sim_solver_pyx.o \ - -I $(INCLUDE_PATH)/blasfeo/include/ \ - -I $(INCLUDE_PATH)/hpipm/include/ \ - -I $(INCLUDE_PATH) \ - {%- for path in cython_include_dirs %} - -I {{ path }} \ - {%- endfor %} - acados_sim_solver_pyx.c \ - -sim_cython: sim_cython_o - $(CC) $(ACADOS_FLAGS) -shared \ - -o acados_sim_solver_pyx{{ shared_lib_ext }} \ - -Wl,-rpath=$(LIB_PATH) \ - acados_sim_solver_pyx.o \ - $(abspath .)/libacados_sim_solver_{{ model.name }}{{ shared_lib_ext }} \ - $(LDFLAGS) $(LDLIBS) - -{%- if os and os == "pc" %} - -clean: - del \Q *.o 2>nul - del \Q *{{ shared_lib_ext }} 2>nul - del \Q main_{{ model.name }} 2>nul - -clean_ocp_shared_lib: - del \Q libacados_ocp_solver_{{ model.name }}{{ shared_lib_ext }} 2>nul - del \Q acados_solver_{{ model.name }}.o 2>nul - -clean_ocp_cython: - del \Q libacados_ocp_solver_{{ model.name }}{{ shared_lib_ext }} 2>nul - del \Q acados_solver_{{ model.name }}.o 2>nul - del \Q acados_ocp_solver_pyx{{ shared_lib_ext }} 2>nul - del \Q acados_ocp_solver_pyx.o 2>nul - -clean_sim_cython: - del \Q libacados_sim_solver_{{ model.name }}{{ shared_lib_ext }} 2>nul - del \Q acados_sim_solver_{{ model.name }}.o 2>nul - del \Q acados_sim_solver_pyx{{ shared_lib_ext }} 2>nul - del \Q acados_sim_solver_pyx.o 2>nul - -{%- else %} - -clean: - $(RM) $(OBJ) $(EX_OBJ) $(EX_SIM_OBJ) - $(RM) $(LIBACADOS_SOLVER) $(LIBACADOS_OCP_SOLVER) $(LIBACADOS_SIM_SOLVER) - $(RM) $(EX_EXE) $(EX_SIM_EXE) - -clean_ocp_shared_lib: - $(RM) $(LIBACADOS_OCP_SOLVER) - $(RM) $(OCP_OBJ) - -clean_ocp_cython: - $(RM) libacados_ocp_solver_{{ model.name }}{{ shared_lib_ext }} - $(RM) acados_solver_{{ model.name }}.o - $(RM) acados_ocp_solver_pyx{{ shared_lib_ext }} - $(RM) acados_ocp_solver_pyx.o - -clean_sim_cython: - $(RM) libacados_sim_solver_{{ model.name }}{{ shared_lib_ext }} - $(RM) acados_sim_solver_{{ model.name }}.o - $(RM) acados_sim_solver_pyx{{ shared_lib_ext }} - $(RM) acados_sim_solver_pyx.o - -{%- endif %} diff --git a/third_party/acados/acados_template/c_templates_tera/acados_sim_solver.in.c b/third_party/acados/acados_template/c_templates_tera/acados_sim_solver.in.c deleted file mode 100644 index 0cd098273c..0000000000 --- a/third_party/acados/acados_template/c_templates_tera/acados_sim_solver.in.c +++ /dev/null @@ -1,526 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - -{%- if solver_options.hessian_approx %} - {%- set hessian_approx = solver_options.hessian_approx %} -{%- elif solver_options.sens_hess %} - {%- set hessian_approx = "EXACT" %} -{%- else %} - {%- set hessian_approx = "GAUSS_NEWTON" %} -{%- endif %} -// standard -#include -#include - -// acados -#include "acados_c/external_function_interface.h" -#include "acados_c/sim_interface.h" -#include "acados_c/external_function_interface.h" - -#include "acados/sim/sim_common.h" -#include "acados/utils/external_function_generic.h" -#include "acados/utils/print.h" - - -// example specific -#include "{{ model.name }}_model/{{ model.name }}_model.h" -#include "acados_sim_solver_{{ model.name }}.h" - - -// ** solver data ** - -sim_solver_capsule * {{ model.name }}_acados_sim_solver_create_capsule() -{ - void* capsule_mem = malloc(sizeof(sim_solver_capsule)); - sim_solver_capsule *capsule = (sim_solver_capsule *) capsule_mem; - - return capsule; -} - - -int {{ model.name }}_acados_sim_solver_free_capsule(sim_solver_capsule * capsule) -{ - free(capsule); - return 0; -} - - -int {{ model.name }}_acados_sim_create(sim_solver_capsule * capsule) -{ - // initialize - const int nx = {{ model.name | upper }}_NX; - const int nu = {{ model.name | upper }}_NU; - const int nz = {{ model.name | upper }}_NZ; - const int np = {{ model.name | upper }}_NP; - bool tmp_bool; - - {#// double Tsim = {{ solver_options.tf / dims.N }};#} - double Tsim = {{ solver_options.Tsim }}; - - {% if solver_options.integrator_type == "IRK" %} - capsule->sim_impl_dae_fun = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})); - capsule->sim_impl_dae_fun_jac_x_xdot_z = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})); - capsule->sim_impl_dae_jac_x_xdot_u_z = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})); - - {%- if model.dyn_ext_fun_type == "casadi" %} - // external functions (implicit model) - capsule->sim_impl_dae_fun->casadi_fun = &{{ model.name }}_impl_dae_fun; - capsule->sim_impl_dae_fun->casadi_work = &{{ model.name }}_impl_dae_fun_work; - capsule->sim_impl_dae_fun->casadi_sparsity_in = &{{ model.name }}_impl_dae_fun_sparsity_in; - capsule->sim_impl_dae_fun->casadi_sparsity_out = &{{ model.name }}_impl_dae_fun_sparsity_out; - capsule->sim_impl_dae_fun->casadi_n_in = &{{ model.name }}_impl_dae_fun_n_in; - capsule->sim_impl_dae_fun->casadi_n_out = &{{ model.name }}_impl_dae_fun_n_out; - external_function_param_{{ model.dyn_ext_fun_type }}_create(capsule->sim_impl_dae_fun, np); - - capsule->sim_impl_dae_fun_jac_x_xdot_z->casadi_fun = &{{ model.name }}_impl_dae_fun_jac_x_xdot_z; - capsule->sim_impl_dae_fun_jac_x_xdot_z->casadi_work = &{{ model.name }}_impl_dae_fun_jac_x_xdot_z_work; - capsule->sim_impl_dae_fun_jac_x_xdot_z->casadi_sparsity_in = &{{ model.name }}_impl_dae_fun_jac_x_xdot_z_sparsity_in; - capsule->sim_impl_dae_fun_jac_x_xdot_z->casadi_sparsity_out = &{{ model.name }}_impl_dae_fun_jac_x_xdot_z_sparsity_out; - capsule->sim_impl_dae_fun_jac_x_xdot_z->casadi_n_in = &{{ model.name }}_impl_dae_fun_jac_x_xdot_z_n_in; - capsule->sim_impl_dae_fun_jac_x_xdot_z->casadi_n_out = &{{ model.name }}_impl_dae_fun_jac_x_xdot_z_n_out; - external_function_param_{{ model.dyn_ext_fun_type }}_create(capsule->sim_impl_dae_fun_jac_x_xdot_z, np); - - // external_function_param_{{ model.dyn_ext_fun_type }} impl_dae_jac_x_xdot_u_z; - capsule->sim_impl_dae_jac_x_xdot_u_z->casadi_fun = &{{ model.name }}_impl_dae_jac_x_xdot_u_z; - capsule->sim_impl_dae_jac_x_xdot_u_z->casadi_work = &{{ model.name }}_impl_dae_jac_x_xdot_u_z_work; - capsule->sim_impl_dae_jac_x_xdot_u_z->casadi_sparsity_in = &{{ model.name }}_impl_dae_jac_x_xdot_u_z_sparsity_in; - capsule->sim_impl_dae_jac_x_xdot_u_z->casadi_sparsity_out = &{{ model.name }}_impl_dae_jac_x_xdot_u_z_sparsity_out; - capsule->sim_impl_dae_jac_x_xdot_u_z->casadi_n_in = &{{ model.name }}_impl_dae_jac_x_xdot_u_z_n_in; - capsule->sim_impl_dae_jac_x_xdot_u_z->casadi_n_out = &{{ model.name }}_impl_dae_jac_x_xdot_u_z_n_out; - external_function_param_{{ model.dyn_ext_fun_type }}_create(capsule->sim_impl_dae_jac_x_xdot_u_z, np); - {%- else %} - capsule->sim_impl_dae_fun->fun = &{{ model.dyn_impl_dae_fun }}; - capsule->sim_impl_dae_fun_jac_x_xdot_z->fun = &{{ model.dyn_impl_dae_fun_jac }}; - capsule->sim_impl_dae_jac_x_xdot_u_z->fun = &{{ model.dyn_impl_dae_jac }}; - {%- endif %} - -{%- if hessian_approx == "EXACT" %} - capsule->sim_impl_dae_hess = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})); - // external_function_param_{{ model.dyn_ext_fun_type }} impl_dae_jac_x_xdot_u_z; - capsule->sim_impl_dae_hess->casadi_fun = &{{ model.name }}_impl_dae_hess; - capsule->sim_impl_dae_hess->casadi_work = &{{ model.name }}_impl_dae_hess_work; - capsule->sim_impl_dae_hess->casadi_sparsity_in = &{{ model.name }}_impl_dae_hess_sparsity_in; - capsule->sim_impl_dae_hess->casadi_sparsity_out = &{{ model.name }}_impl_dae_hess_sparsity_out; - capsule->sim_impl_dae_hess->casadi_n_in = &{{ model.name }}_impl_dae_hess_n_in; - capsule->sim_impl_dae_hess->casadi_n_out = &{{ model.name }}_impl_dae_hess_n_out; - external_function_param_{{ model.dyn_ext_fun_type }}_create(capsule->sim_impl_dae_hess, np); -{%- endif %} - - {% elif solver_options.integrator_type == "ERK" %} - // explicit ode - capsule->sim_forw_vde_casadi = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})); - capsule->sim_vde_adj_casadi = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})); - capsule->sim_expl_ode_fun_casadi = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})); - - capsule->sim_forw_vde_casadi->casadi_fun = &{{ model.name }}_expl_vde_forw; - capsule->sim_forw_vde_casadi->casadi_n_in = &{{ model.name }}_expl_vde_forw_n_in; - capsule->sim_forw_vde_casadi->casadi_n_out = &{{ model.name }}_expl_vde_forw_n_out; - capsule->sim_forw_vde_casadi->casadi_sparsity_in = &{{ model.name }}_expl_vde_forw_sparsity_in; - capsule->sim_forw_vde_casadi->casadi_sparsity_out = &{{ model.name }}_expl_vde_forw_sparsity_out; - capsule->sim_forw_vde_casadi->casadi_work = &{{ model.name }}_expl_vde_forw_work; - external_function_param_{{ model.dyn_ext_fun_type }}_create(capsule->sim_forw_vde_casadi, np); - - capsule->sim_vde_adj_casadi->casadi_fun = &{{ model.name }}_expl_vde_adj; - capsule->sim_vde_adj_casadi->casadi_n_in = &{{ model.name }}_expl_vde_adj_n_in; - capsule->sim_vde_adj_casadi->casadi_n_out = &{{ model.name }}_expl_vde_adj_n_out; - capsule->sim_vde_adj_casadi->casadi_sparsity_in = &{{ model.name }}_expl_vde_adj_sparsity_in; - capsule->sim_vde_adj_casadi->casadi_sparsity_out = &{{ model.name }}_expl_vde_adj_sparsity_out; - capsule->sim_vde_adj_casadi->casadi_work = &{{ model.name }}_expl_vde_adj_work; - external_function_param_{{ model.dyn_ext_fun_type }}_create(capsule->sim_vde_adj_casadi, np); - - capsule->sim_expl_ode_fun_casadi->casadi_fun = &{{ model.name }}_expl_ode_fun; - capsule->sim_expl_ode_fun_casadi->casadi_n_in = &{{ model.name }}_expl_ode_fun_n_in; - capsule->sim_expl_ode_fun_casadi->casadi_n_out = &{{ model.name }}_expl_ode_fun_n_out; - capsule->sim_expl_ode_fun_casadi->casadi_sparsity_in = &{{ model.name }}_expl_ode_fun_sparsity_in; - capsule->sim_expl_ode_fun_casadi->casadi_sparsity_out = &{{ model.name }}_expl_ode_fun_sparsity_out; - capsule->sim_expl_ode_fun_casadi->casadi_work = &{{ model.name }}_expl_ode_fun_work; - external_function_param_{{ model.dyn_ext_fun_type }}_create(capsule->sim_expl_ode_fun_casadi, np); - -{%- if hessian_approx == "EXACT" %} - capsule->sim_expl_ode_hess = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})); - // external_function_param_{{ model.dyn_ext_fun_type }} impl_dae_jac_x_xdot_u_z; - capsule->sim_expl_ode_hess->casadi_fun = &{{ model.name }}_expl_ode_hess; - capsule->sim_expl_ode_hess->casadi_work = &{{ model.name }}_expl_ode_hess_work; - capsule->sim_expl_ode_hess->casadi_sparsity_in = &{{ model.name }}_expl_ode_hess_sparsity_in; - capsule->sim_expl_ode_hess->casadi_sparsity_out = &{{ model.name }}_expl_ode_hess_sparsity_out; - capsule->sim_expl_ode_hess->casadi_n_in = &{{ model.name }}_expl_ode_hess_n_in; - capsule->sim_expl_ode_hess->casadi_n_out = &{{ model.name }}_expl_ode_hess_n_out; - external_function_param_{{ model.dyn_ext_fun_type }}_create(capsule->sim_expl_ode_hess, np); -{%- endif %} - - {% elif solver_options.integrator_type == "GNSF" -%} - {% if model.gnsf.purely_linear != 1 %} - capsule->sim_gnsf_phi_fun = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})); - capsule->sim_gnsf_phi_fun_jac_y = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})); - capsule->sim_gnsf_phi_jac_y_uhat = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})); - {% if model.gnsf.nontrivial_f_LO == 1 %} - capsule->sim_gnsf_f_lo_jac_x1_x1dot_u_z = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})); - {%- endif %} - {%- endif %} - capsule->sim_gnsf_get_matrices_fun = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})); - - {% if model.gnsf.purely_linear != 1 %} - capsule->sim_gnsf_phi_fun->casadi_fun = &{{ model.name }}_gnsf_phi_fun; - capsule->sim_gnsf_phi_fun->casadi_n_in = &{{ model.name }}_gnsf_phi_fun_n_in; - capsule->sim_gnsf_phi_fun->casadi_n_out = &{{ model.name }}_gnsf_phi_fun_n_out; - capsule->sim_gnsf_phi_fun->casadi_sparsity_in = &{{ model.name }}_gnsf_phi_fun_sparsity_in; - capsule->sim_gnsf_phi_fun->casadi_sparsity_out = &{{ model.name }}_gnsf_phi_fun_sparsity_out; - capsule->sim_gnsf_phi_fun->casadi_work = &{{ model.name }}_gnsf_phi_fun_work; - external_function_param_{{ model.dyn_ext_fun_type }}_create(capsule->sim_gnsf_phi_fun, np); - - capsule->sim_gnsf_phi_fun_jac_y->casadi_fun = &{{ model.name }}_gnsf_phi_fun_jac_y; - capsule->sim_gnsf_phi_fun_jac_y->casadi_n_in = &{{ model.name }}_gnsf_phi_fun_jac_y_n_in; - capsule->sim_gnsf_phi_fun_jac_y->casadi_n_out = &{{ model.name }}_gnsf_phi_fun_jac_y_n_out; - capsule->sim_gnsf_phi_fun_jac_y->casadi_sparsity_in = &{{ model.name }}_gnsf_phi_fun_jac_y_sparsity_in; - capsule->sim_gnsf_phi_fun_jac_y->casadi_sparsity_out = &{{ model.name }}_gnsf_phi_fun_jac_y_sparsity_out; - capsule->sim_gnsf_phi_fun_jac_y->casadi_work = &{{ model.name }}_gnsf_phi_fun_jac_y_work; - external_function_param_{{ model.dyn_ext_fun_type }}_create(capsule->sim_gnsf_phi_fun_jac_y, np); - - capsule->sim_gnsf_phi_jac_y_uhat->casadi_fun = &{{ model.name }}_gnsf_phi_jac_y_uhat; - capsule->sim_gnsf_phi_jac_y_uhat->casadi_n_in = &{{ model.name }}_gnsf_phi_jac_y_uhat_n_in; - capsule->sim_gnsf_phi_jac_y_uhat->casadi_n_out = &{{ model.name }}_gnsf_phi_jac_y_uhat_n_out; - capsule->sim_gnsf_phi_jac_y_uhat->casadi_sparsity_in = &{{ model.name }}_gnsf_phi_jac_y_uhat_sparsity_in; - capsule->sim_gnsf_phi_jac_y_uhat->casadi_sparsity_out = &{{ model.name }}_gnsf_phi_jac_y_uhat_sparsity_out; - capsule->sim_gnsf_phi_jac_y_uhat->casadi_work = &{{ model.name }}_gnsf_phi_jac_y_uhat_work; - external_function_param_{{ model.dyn_ext_fun_type }}_create(capsule->sim_gnsf_phi_jac_y_uhat, np); - - {% if model.gnsf.nontrivial_f_LO == 1 %} - capsule->sim_gnsf_f_lo_jac_x1_x1dot_u_z->casadi_fun = &{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz; - capsule->sim_gnsf_f_lo_jac_x1_x1dot_u_z->casadi_n_in = &{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_n_in; - capsule->sim_gnsf_f_lo_jac_x1_x1dot_u_z->casadi_n_out = &{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_n_out; - capsule->sim_gnsf_f_lo_jac_x1_x1dot_u_z->casadi_sparsity_in = &{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_sparsity_in; - capsule->sim_gnsf_f_lo_jac_x1_x1dot_u_z->casadi_sparsity_out = &{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_sparsity_out; - capsule->sim_gnsf_f_lo_jac_x1_x1dot_u_z->casadi_work = &{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_work; - external_function_param_{{ model.dyn_ext_fun_type }}_create(capsule->sim_gnsf_f_lo_jac_x1_x1dot_u_z, np); - {%- endif %} - {%- endif %} - - capsule->sim_gnsf_get_matrices_fun->casadi_fun = &{{ model.name }}_gnsf_get_matrices_fun; - capsule->sim_gnsf_get_matrices_fun->casadi_n_in = &{{ model.name }}_gnsf_get_matrices_fun_n_in; - capsule->sim_gnsf_get_matrices_fun->casadi_n_out = &{{ model.name }}_gnsf_get_matrices_fun_n_out; - capsule->sim_gnsf_get_matrices_fun->casadi_sparsity_in = &{{ model.name }}_gnsf_get_matrices_fun_sparsity_in; - capsule->sim_gnsf_get_matrices_fun->casadi_sparsity_out = &{{ model.name }}_gnsf_get_matrices_fun_sparsity_out; - capsule->sim_gnsf_get_matrices_fun->casadi_work = &{{ model.name }}_gnsf_get_matrices_fun_work; - external_function_param_{{ model.dyn_ext_fun_type }}_create(capsule->sim_gnsf_get_matrices_fun, np); - {% endif %} - - // sim plan & config - sim_solver_plan_t plan; - plan.sim_solver = {{ solver_options.integrator_type }}; - - // create correct config based on plan - sim_config * {{ model.name }}_sim_config = sim_config_create(plan); - capsule->acados_sim_config = {{ model.name }}_sim_config; - - // sim dims - void *{{ model.name }}_sim_dims = sim_dims_create({{ model.name }}_sim_config); - capsule->acados_sim_dims = {{ model.name }}_sim_dims; - sim_dims_set({{ model.name }}_sim_config, {{ model.name }}_sim_dims, "nx", &nx); - sim_dims_set({{ model.name }}_sim_config, {{ model.name }}_sim_dims, "nu", &nu); - sim_dims_set({{ model.name }}_sim_config, {{ model.name }}_sim_dims, "nz", &nz); -{% if solver_options.integrator_type == "GNSF" %} - int gnsf_nx1 = {{ dims.gnsf_nx1 }}; - int gnsf_nz1 = {{ dims.gnsf_nz1 }}; - int gnsf_nout = {{ dims.gnsf_nout }}; - int gnsf_ny = {{ dims.gnsf_ny }}; - int gnsf_nuhat = {{ dims.gnsf_nuhat }}; - - sim_dims_set({{ model.name }}_sim_config, {{ model.name }}_sim_dims, "nx1", &gnsf_nx1); - sim_dims_set({{ model.name }}_sim_config, {{ model.name }}_sim_dims, "nz1", &gnsf_nz1); - sim_dims_set({{ model.name }}_sim_config, {{ model.name }}_sim_dims, "nout", &gnsf_nout); - sim_dims_set({{ model.name }}_sim_config, {{ model.name }}_sim_dims, "ny", &gnsf_ny); - sim_dims_set({{ model.name }}_sim_config, {{ model.name }}_sim_dims, "nuhat", &gnsf_nuhat); -{% endif %} - - // sim opts - sim_opts *{{ model.name }}_sim_opts = sim_opts_create({{ model.name }}_sim_config, {{ model.name }}_sim_dims); - capsule->acados_sim_opts = {{ model.name }}_sim_opts; - int tmp_int = {{ solver_options.sim_method_newton_iter }}; - sim_opts_set({{ model.name }}_sim_config, {{ model.name }}_sim_opts, "newton_iter", &tmp_int); - double tmp_double = {{ solver_options.sim_method_newton_tol }}; - sim_opts_set({{ model.name }}_sim_config, {{ model.name }}_sim_opts, "newton_tol", &tmp_double); - sim_collocation_type collocation_type = {{ solver_options.collocation_type }}; - sim_opts_set({{ model.name }}_sim_config, {{ model.name }}_sim_opts, "collocation_type", &collocation_type); - -{% if problem_class == "SIM" %} - tmp_int = {{ solver_options.sim_method_num_stages }}; - sim_opts_set({{ model.name }}_sim_config, {{ model.name }}_sim_opts, "num_stages", &tmp_int); - tmp_int = {{ solver_options.sim_method_num_steps }}; - sim_opts_set({{ model.name }}_sim_config, {{ model.name }}_sim_opts, "num_steps", &tmp_int); - - // options that are not available to AcadosOcpSolver - // (in OCP they will be determined by other options, like exact_hessian) - tmp_bool = {{ solver_options.sens_forw }}; - sim_opts_set({{ model.name }}_sim_config, {{ model.name }}_sim_opts, "sens_forw", &tmp_bool); - tmp_bool = {{ solver_options.sens_adj }}; - sim_opts_set({{ model.name }}_sim_config, {{ model.name }}_sim_opts, "sens_adj", &tmp_bool); - tmp_bool = {{ solver_options.sens_algebraic }}; - sim_opts_set({{ model.name }}_sim_config, {{ model.name }}_sim_opts, "sens_algebraic", &tmp_bool); - tmp_bool = {{ solver_options.sens_hess }}; - sim_opts_set({{ model.name }}_sim_config, {{ model.name }}_sim_opts, "sens_hess", &tmp_bool); - tmp_bool = {{ solver_options.output_z }}; - sim_opts_set({{ model.name }}_sim_config, {{ model.name }}_sim_opts, "output_z", &tmp_bool); - -{% else %} {# num_stages and num_steps of first shooting interval are used #} - tmp_int = {{ solver_options.sim_method_num_stages[0] }}; - sim_opts_set({{ model.name }}_sim_config, {{ model.name }}_sim_opts, "num_stages", &tmp_int); - tmp_int = {{ solver_options.sim_method_num_steps[0] }}; - sim_opts_set({{ model.name }}_sim_config, {{ model.name }}_sim_opts, "num_steps", &tmp_int); - tmp_bool = {{ solver_options.sim_method_jac_reuse[0] }}; - sim_opts_set({{ model.name }}_sim_config, {{ model.name }}_sim_opts, "jac_reuse", &tmp_bool); -{% endif %} - - // sim in / out - sim_in *{{ model.name }}_sim_in = sim_in_create({{ model.name }}_sim_config, {{ model.name }}_sim_dims); - capsule->acados_sim_in = {{ model.name }}_sim_in; - sim_out *{{ model.name }}_sim_out = sim_out_create({{ model.name }}_sim_config, {{ model.name }}_sim_dims); - capsule->acados_sim_out = {{ model.name }}_sim_out; - - sim_in_set({{ model.name }}_sim_config, {{ model.name }}_sim_dims, - {{ model.name }}_sim_in, "T", &Tsim); - - // model functions -{%- if solver_options.integrator_type == "IRK" %} - {{ model.name }}_sim_config->model_set({{ model.name }}_sim_in->model, - "impl_ode_fun", capsule->sim_impl_dae_fun); - {{ model.name }}_sim_config->model_set({{ model.name }}_sim_in->model, - "impl_ode_fun_jac_x_xdot", capsule->sim_impl_dae_fun_jac_x_xdot_z); - {{ model.name }}_sim_config->model_set({{ model.name }}_sim_in->model, - "impl_ode_jac_x_xdot_u", capsule->sim_impl_dae_jac_x_xdot_u_z); -{%- if hessian_approx == "EXACT" %} - {{ model.name }}_sim_config->model_set({{ model.name }}_sim_in->model, - "impl_dae_hess", capsule->sim_impl_dae_hess); -{%- endif %} - -{%- elif solver_options.integrator_type == "ERK" %} - {{ model.name }}_sim_config->model_set({{ model.name }}_sim_in->model, - "expl_vde_forw", capsule->sim_forw_vde_casadi); - {{ model.name }}_sim_config->model_set({{ model.name }}_sim_in->model, - "expl_vde_adj", capsule->sim_vde_adj_casadi); - {{ model.name }}_sim_config->model_set({{ model.name }}_sim_in->model, - "expl_ode_fun", capsule->sim_expl_ode_fun_casadi); -{%- if hessian_approx == "EXACT" %} - {{ model.name }}_sim_config->model_set({{ model.name }}_sim_in->model, - "expl_ode_hess", capsule->sim_expl_ode_hess); -{%- endif %} -{%- elif solver_options.integrator_type == "GNSF" %} - {% if model.gnsf.purely_linear != 1 %} - {{ model.name }}_sim_config->model_set({{ model.name }}_sim_in->model, - "phi_fun", capsule->sim_gnsf_phi_fun); - {{ model.name }}_sim_config->model_set({{ model.name }}_sim_in->model, - "phi_fun_jac_y", capsule->sim_gnsf_phi_fun_jac_y); - {{ model.name }}_sim_config->model_set({{ model.name }}_sim_in->model, - "phi_jac_y_uhat", capsule->sim_gnsf_phi_jac_y_uhat); - {% if model.gnsf.nontrivial_f_LO == 1 %} - {{ model.name }}_sim_config->model_set({{ model.name }}_sim_in->model, - "f_lo_jac_x1_x1dot_u_z", capsule->sim_gnsf_f_lo_jac_x1_x1dot_u_z); - {%- endif %} - {%- endif %} - {{ model.name }}_sim_config->model_set({{ model.name }}_sim_in->model, - "gnsf_get_matrices_fun", capsule->sim_gnsf_get_matrices_fun); -{%- endif %} - - // sim solver - sim_solver *{{ model.name }}_sim_solver = sim_solver_create({{ model.name }}_sim_config, - {{ model.name }}_sim_dims, {{ model.name }}_sim_opts); - capsule->acados_sim_solver = {{ model.name }}_sim_solver; - -{% if dims.np > 0 %} - /* initialize parameter values */ - double* p = calloc(np, sizeof(double)); - {% for item in parameter_values %} - {%- if item != 0 %} - p[{{ loop.index0 }}] = {{ item }}; - {%- endif %} - {%- endfor %} - - {{ model.name }}_acados_sim_update_params(capsule, p, np); - free(p); -{% endif %}{# if dims.np #} - - /* initialize input */ - // x - double x0[{{ dims.nx }}]; - for (int ii = 0; ii < {{ dims.nx }}; ii++) - x0[ii] = 0.0; - - sim_in_set({{ model.name }}_sim_config, {{ model.name }}_sim_dims, - {{ model.name }}_sim_in, "x", x0); - - - // u - double u0[{{ dims.nu }}]; - for (int ii = 0; ii < {{ dims.nu }}; ii++) - u0[ii] = 0.0; - - sim_in_set({{ model.name }}_sim_config, {{ model.name }}_sim_dims, - {{ model.name }}_sim_in, "u", u0); - - // S_forw - double S_forw[{{ dims.nx * (dims.nx + dims.nu) }}]; - for (int ii = 0; ii < {{ dims.nx * (dims.nx + dims.nu) }}; ii++) - S_forw[ii] = 0.0; - for (int ii = 0; ii < {{ dims.nx }}; ii++) - S_forw[ii + ii * {{ dims.nx }} ] = 1.0; - - - sim_in_set({{ model.name }}_sim_config, {{ model.name }}_sim_dims, - {{ model.name }}_sim_in, "S_forw", S_forw); - - int status = sim_precompute({{ model.name }}_sim_solver, {{ model.name }}_sim_in, {{ model.name }}_sim_out); - - return status; -} - - -int {{ model.name }}_acados_sim_solve(sim_solver_capsule *capsule) -{ - // integrate dynamics using acados sim_solver - int status = sim_solve(capsule->acados_sim_solver, - capsule->acados_sim_in, capsule->acados_sim_out); - if (status != 0) - printf("error in {{ model.name }}_acados_sim_solve()! Exiting.\n"); - - return status; -} - - -int {{ model.name }}_acados_sim_free(sim_solver_capsule *capsule) -{ - // free memory - sim_solver_destroy(capsule->acados_sim_solver); - sim_in_destroy(capsule->acados_sim_in); - sim_out_destroy(capsule->acados_sim_out); - sim_opts_destroy(capsule->acados_sim_opts); - sim_dims_destroy(capsule->acados_sim_dims); - sim_config_destroy(capsule->acados_sim_config); - - // free external function -{%- if solver_options.integrator_type == "IRK" %} - external_function_param_{{ model.dyn_ext_fun_type }}_free(capsule->sim_impl_dae_fun); - external_function_param_{{ model.dyn_ext_fun_type }}_free(capsule->sim_impl_dae_fun_jac_x_xdot_z); - external_function_param_{{ model.dyn_ext_fun_type }}_free(capsule->sim_impl_dae_jac_x_xdot_u_z); -{%- if hessian_approx == "EXACT" %} - external_function_param_{{ model.dyn_ext_fun_type }}_free(capsule->sim_impl_dae_hess); -{%- endif %} -{%- elif solver_options.integrator_type == "ERK" %} - external_function_param_{{ model.dyn_ext_fun_type }}_free(capsule->sim_forw_vde_casadi); - external_function_param_{{ model.dyn_ext_fun_type }}_free(capsule->sim_vde_adj_casadi); - external_function_param_{{ model.dyn_ext_fun_type }}_free(capsule->sim_expl_ode_fun_casadi); -{%- if hessian_approx == "EXACT" %} - external_function_param_{{ model.dyn_ext_fun_type }}_free(capsule->sim_expl_ode_hess); -{%- endif %} -{%- elif solver_options.integrator_type == "GNSF" %} - {% if model.gnsf.purely_linear != 1 %} - external_function_param_{{ model.dyn_ext_fun_type }}_free(capsule->sim_gnsf_phi_fun); - external_function_param_{{ model.dyn_ext_fun_type }}_free(capsule->sim_gnsf_phi_fun_jac_y); - external_function_param_{{ model.dyn_ext_fun_type }}_free(capsule->sim_gnsf_phi_jac_y_uhat); - {% if model.gnsf.nontrivial_f_LO == 1 %} - external_function_param_{{ model.dyn_ext_fun_type }}_free(capsule->sim_gnsf_f_lo_jac_x1_x1dot_u_z); - {%- endif %} - {%- endif %} - external_function_param_{{ model.dyn_ext_fun_type }}_free(capsule->sim_gnsf_get_matrices_fun); -{% endif %} - - return 0; -} - - -int {{ model.name }}_acados_sim_update_params(sim_solver_capsule *capsule, double *p, int np) -{ - int status = 0; - int casadi_np = {{ model.name | upper }}_NP; - - if (casadi_np != np) { - printf("{{ model.name }}_acados_sim_update_params: trying to set %i parameters for external functions." - " External function has %i parameters. Exiting.\n", np, casadi_np); - exit(1); - } - -{%- if solver_options.integrator_type == "ERK" %} - capsule->sim_forw_vde_casadi[0].set_param(capsule->sim_forw_vde_casadi, p); - capsule->sim_vde_adj_casadi[0].set_param(capsule->sim_vde_adj_casadi, p); - capsule->sim_expl_ode_fun_casadi[0].set_param(capsule->sim_expl_ode_fun_casadi, p); -{%- if hessian_approx == "EXACT" %} - capsule->sim_expl_ode_hess[0].set_param(capsule->sim_expl_ode_hess, p); -{%- endif %} -{%- elif solver_options.integrator_type == "IRK" %} - capsule->sim_impl_dae_fun[0].set_param(capsule->sim_impl_dae_fun, p); - capsule->sim_impl_dae_fun_jac_x_xdot_z[0].set_param(capsule->sim_impl_dae_fun_jac_x_xdot_z, p); - capsule->sim_impl_dae_jac_x_xdot_u_z[0].set_param(capsule->sim_impl_dae_jac_x_xdot_u_z, p); -{%- if hessian_approx == "EXACT" %} - capsule->sim_impl_dae_hess[0].set_param(capsule->sim_impl_dae_hess, p); -{%- endif %} -{%- elif solver_options.integrator_type == "GNSF" %} - {% if model.gnsf.purely_linear != 1 %} - capsule->sim_gnsf_phi_fun[0].set_param(capsule->sim_gnsf_phi_fun, p); - capsule->sim_gnsf_phi_fun_jac_y[0].set_param(capsule->sim_gnsf_phi_fun_jac_y, p); - capsule->sim_gnsf_phi_jac_y_uhat[0].set_param(capsule->sim_gnsf_phi_jac_y_uhat, p); - {% if model.gnsf.nontrivial_f_LO == 1 %} - capsule->sim_gnsf_f_lo_jac_x1_x1dot_u_z[0].set_param(capsule->sim_gnsf_f_lo_jac_x1_x1dot_u_z, p); - {%- endif %} - {%- endif %} - capsule->sim_gnsf_get_matrices_fun[0].set_param(capsule->sim_gnsf_get_matrices_fun, p); -{% endif %} - - return status; -} - -/* getters pointers to C objects*/ -sim_config * {{ model.name }}_acados_get_sim_config(sim_solver_capsule *capsule) -{ - return capsule->acados_sim_config; -}; - -sim_in * {{ model.name }}_acados_get_sim_in(sim_solver_capsule *capsule) -{ - return capsule->acados_sim_in; -}; - -sim_out * {{ model.name }}_acados_get_sim_out(sim_solver_capsule *capsule) -{ - return capsule->acados_sim_out; -}; - -void * {{ model.name }}_acados_get_sim_dims(sim_solver_capsule *capsule) -{ - return capsule->acados_sim_dims; -}; - -sim_opts * {{ model.name }}_acados_get_sim_opts(sim_solver_capsule *capsule) -{ - return capsule->acados_sim_opts; -}; - -sim_solver * {{ model.name }}_acados_get_sim_solver(sim_solver_capsule *capsule) -{ - return capsule->acados_sim_solver; -}; - diff --git a/third_party/acados/acados_template/c_templates_tera/acados_sim_solver.in.h b/third_party/acados/acados_template/c_templates_tera/acados_sim_solver.in.h deleted file mode 100644 index 59aee62f49..0000000000 --- a/third_party/acados/acados_template/c_templates_tera/acados_sim_solver.in.h +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - -#ifndef ACADOS_SIM_{{ model.name }}_H_ -#define ACADOS_SIM_{{ model.name }}_H_ - -#include "acados_c/sim_interface.h" -#include "acados_c/external_function_interface.h" - -#define {{ model.name | upper }}_NX {{ dims.nx }} -#define {{ model.name | upper }}_NZ {{ dims.nz }} -#define {{ model.name | upper }}_NU {{ dims.nu }} -#define {{ model.name | upper }}_NP {{ dims.np }} - -#ifdef __cplusplus -extern "C" { -#endif - - -// ** capsule for solver data ** -typedef struct sim_solver_capsule -{ - // acados objects - sim_in *acados_sim_in; - sim_out *acados_sim_out; - sim_solver *acados_sim_solver; - sim_opts *acados_sim_opts; - sim_config *acados_sim_config; - void *acados_sim_dims; - - /* external functions */ - // ERK - external_function_param_{{ model.dyn_ext_fun_type }} * sim_forw_vde_casadi; - external_function_param_{{ model.dyn_ext_fun_type }} * sim_vde_adj_casadi; - external_function_param_{{ model.dyn_ext_fun_type }} * sim_expl_ode_fun_casadi; - external_function_param_{{ model.dyn_ext_fun_type }} * sim_expl_ode_hess; - - // IRK - external_function_param_{{ model.dyn_ext_fun_type }} * sim_impl_dae_fun; - external_function_param_{{ model.dyn_ext_fun_type }} * sim_impl_dae_fun_jac_x_xdot_z; - external_function_param_{{ model.dyn_ext_fun_type }} * sim_impl_dae_jac_x_xdot_u_z; - external_function_param_{{ model.dyn_ext_fun_type }} * sim_impl_dae_hess; - - // GNSF - external_function_param_{{ model.dyn_ext_fun_type }} * sim_gnsf_phi_fun; - external_function_param_{{ model.dyn_ext_fun_type }} * sim_gnsf_phi_fun_jac_y; - external_function_param_{{ model.dyn_ext_fun_type }} * sim_gnsf_phi_jac_y_uhat; - external_function_param_{{ model.dyn_ext_fun_type }} * sim_gnsf_f_lo_jac_x1_x1dot_u_z; - external_function_param_{{ model.dyn_ext_fun_type }} * sim_gnsf_get_matrices_fun; - -} sim_solver_capsule; - - -ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_sim_create(sim_solver_capsule *capsule); -ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_sim_solve(sim_solver_capsule *capsule); -ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_sim_free(sim_solver_capsule *capsule); -ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_sim_update_params(sim_solver_capsule *capsule, double *value, int np); - -ACADOS_SYMBOL_EXPORT sim_config * {{ model.name }}_acados_get_sim_config(sim_solver_capsule *capsule); -ACADOS_SYMBOL_EXPORT sim_in * {{ model.name }}_acados_get_sim_in(sim_solver_capsule *capsule); -ACADOS_SYMBOL_EXPORT sim_out * {{ model.name }}_acados_get_sim_out(sim_solver_capsule *capsule); -ACADOS_SYMBOL_EXPORT void * {{ model.name }}_acados_get_sim_dims(sim_solver_capsule *capsule); -ACADOS_SYMBOL_EXPORT sim_opts * {{ model.name }}_acados_get_sim_opts(sim_solver_capsule *capsule); -ACADOS_SYMBOL_EXPORT sim_solver * {{ model.name }}_acados_get_sim_solver(sim_solver_capsule *capsule); - - -ACADOS_SYMBOL_EXPORT sim_solver_capsule * {{ model.name }}_acados_sim_solver_create_capsule(void); -ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_sim_solver_free_capsule(sim_solver_capsule *capsule); - -#ifdef __cplusplus -} -#endif - -#endif // ACADOS_SIM_{{ model.name }}_H_ diff --git a/third_party/acados/acados_template/c_templates_tera/acados_sim_solver.in.pxd b/third_party/acados/acados_template/c_templates_tera/acados_sim_solver.in.pxd deleted file mode 100644 index 153f98d13a..0000000000 --- a/third_party/acados/acados_template/c_templates_tera/acados_sim_solver.in.pxd +++ /dev/null @@ -1,51 +0,0 @@ -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# 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. -# -# 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.; -# - -cimport acados_sim_solver_common - -cdef extern from "acados_sim_solver_{{ model.name }}.h": - ctypedef struct sim_solver_capsule "sim_solver_capsule": - pass - - sim_solver_capsule * acados_sim_solver_create_capsule "{{ model.name }}_acados_sim_solver_create_capsule"() - int acados_sim_solver_free_capsule "{{ model.name }}_acados_sim_solver_free_capsule"(sim_solver_capsule *capsule) - - int acados_sim_create "{{ model.name }}_acados_sim_create"(sim_solver_capsule * capsule) - int acados_sim_solve "{{ model.name }}_acados_sim_solve"(sim_solver_capsule * capsule) - int acados_sim_free "{{ model.name }}_acados_sim_free"(sim_solver_capsule * capsule) - int acados_sim_update_params "{{ model.name }}_acados_sim_update_params"(sim_solver_capsule * capsule, double *value, int np_) - # int acados_sim_update_params_sparse "{{ model.name }}_acados_sim_update_params_sparse"(sim_solver_capsule * capsule, int stage, int *idx, double *p, int n_update) - - acados_sim_solver_common.sim_in *acados_get_sim_in "{{ model.name }}_acados_get_sim_in"(sim_solver_capsule * capsule) - acados_sim_solver_common.sim_out *acados_get_sim_out "{{ model.name }}_acados_get_sim_out"(sim_solver_capsule * capsule) - acados_sim_solver_common.sim_solver *acados_get_sim_solver "{{ model.name }}_acados_get_sim_solver"(sim_solver_capsule * capsule) - acados_sim_solver_common.sim_config *acados_get_sim_config "{{ model.name }}_acados_get_sim_config"(sim_solver_capsule * capsule) - acados_sim_solver_common.sim_opts *acados_get_sim_opts "{{ model.name }}_acados_get_sim_opts"(sim_solver_capsule * capsule) - void *acados_get_sim_dims "{{ model.name }}_acados_get_sim_dims"(sim_solver_capsule * capsule) diff --git a/third_party/acados/acados_template/c_templates_tera/acados_solver.in.c b/third_party/acados/acados_template/c_templates_tera/acados_solver.in.c deleted file mode 100644 index 5e36a53d10..0000000000 --- a/third_party/acados/acados_template/c_templates_tera/acados_solver.in.c +++ /dev/null @@ -1,2741 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - -// standard -#include -#include -#include -// acados -// #include "acados/utils/print.h" -#include "acados_c/ocp_nlp_interface.h" -#include "acados_c/external_function_interface.h" - -// example specific -#include "{{ model.name }}_model/{{ model.name }}_model.h" -#include "{{ model.name }}_constraints/{{ model.name }}_constraints.h" - -{%- if cost.cost_type != "LINEAR_LS" or cost.cost_type_e != "LINEAR_LS" or cost.cost_type_0 != "LINEAR_LS" %} -#include "{{ model.name }}_cost/{{ model.name }}_cost.h" -{%- endif %} - -{%- if not solver_options.custom_update_filename %} - {%- set custom_update_filename = "" %} -{% else %} - {%- set custom_update_filename = solver_options.custom_update_filename %} -{%- endif %} -{%- if not solver_options.custom_update_header_filename %} - {%- set custom_update_header_filename = "" %} -{% else %} - {%- set custom_update_header_filename = solver_options.custom_update_header_filename %} -{%- endif %} -{%- if custom_update_header_filename != "" %} -#include "{{ custom_update_header_filename }}" -{%- endif %} - - -#include "acados_solver_{{ model.name }}.h" - -#define NX {{ model.name | upper }}_NX -#define NZ {{ model.name | upper }}_NZ -#define NU {{ model.name | upper }}_NU -#define NP {{ model.name | upper }}_NP -#define NBX {{ model.name | upper }}_NBX -#define NBX0 {{ model.name | upper }}_NBX0 -#define NBU {{ model.name | upper }}_NBU -#define NSBX {{ model.name | upper }}_NSBX -#define NSBU {{ model.name | upper }}_NSBU -#define NSH {{ model.name | upper }}_NSH -#define NSG {{ model.name | upper }}_NSG -#define NSPHI {{ model.name | upper }}_NSPHI -#define NSHN {{ model.name | upper }}_NSHN -#define NSGN {{ model.name | upper }}_NSGN -#define NSPHIN {{ model.name | upper }}_NSPHIN -#define NSBXN {{ model.name | upper }}_NSBXN -#define NS {{ model.name | upper }}_NS -#define NSN {{ model.name | upper }}_NSN -#define NG {{ model.name | upper }}_NG -#define NBXN {{ model.name | upper }}_NBXN -#define NGN {{ model.name | upper }}_NGN -#define NY0 {{ model.name | upper }}_NY0 -#define NY {{ model.name | upper }}_NY -#define NYN {{ model.name | upper }}_NYN -// #define N {{ model.name | upper }}_N -#define NH {{ model.name | upper }}_NH -#define NPHI {{ model.name | upper }}_NPHI -#define NHN {{ model.name | upper }}_NHN -#define NPHIN {{ model.name | upper }}_NPHIN -#define NR {{ model.name | upper }}_NR - - -// ** solver data ** - -{{ model.name }}_solver_capsule * {{ model.name }}_acados_create_capsule(void) -{ - void* capsule_mem = malloc(sizeof({{ model.name }}_solver_capsule)); - {{ model.name }}_solver_capsule *capsule = ({{ model.name }}_solver_capsule *) capsule_mem; - - return capsule; -} - - -int {{ model.name }}_acados_free_capsule({{ model.name }}_solver_capsule *capsule) -{ - free(capsule); - return 0; -} - - -int {{ model.name }}_acados_create({{ model.name }}_solver_capsule* capsule) -{ - int N_shooting_intervals = {{ model.name | upper }}_N; - double* new_time_steps = NULL; // NULL -> don't alter the code generated time-steps - return {{ model.name }}_acados_create_with_discretization(capsule, N_shooting_intervals, new_time_steps); -} - - -int {{ model.name }}_acados_update_time_steps({{ model.name }}_solver_capsule* capsule, int N, double* new_time_steps) -{ - if (N != capsule->nlp_solver_plan->N) { - fprintf(stderr, "{{ model.name }}_acados_update_time_steps: given number of time steps (= %d) " \ - "differs from the currently allocated number of " \ - "time steps (= %d)!\n" \ - "Please recreate with new discretization and provide a new vector of time_stamps!\n", - N, capsule->nlp_solver_plan->N); - return 1; - } - - ocp_nlp_config * nlp_config = capsule->nlp_config; - ocp_nlp_dims * nlp_dims = capsule->nlp_dims; - ocp_nlp_in * nlp_in = capsule->nlp_in; - - for (int i = 0; i < N; i++) - { - ocp_nlp_in_set(nlp_config, nlp_dims, nlp_in, i, "Ts", &new_time_steps[i]); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "scaling", &new_time_steps[i]); - } - return 0; -} - -/** - * Internal function for {{ model.name }}_acados_create: step 1 - */ -void {{ model.name }}_acados_create_1_set_plan(ocp_nlp_plan_t* nlp_solver_plan, const int N) -{ - assert(N == nlp_solver_plan->N); - - /************************************************ - * plan - ************************************************/ - - {%- if solver_options.nlp_solver_type == "SQP" %} - nlp_solver_plan->nlp_solver = SQP; - {%- else %} - nlp_solver_plan->nlp_solver = SQP_RTI; - {%- endif %} - - nlp_solver_plan->ocp_qp_solver_plan.qp_solver = {{ solver_options.qp_solver }}; - - nlp_solver_plan->nlp_cost[0] = {{ cost.cost_type_0 }}; - for (int i = 1; i < N; i++) - nlp_solver_plan->nlp_cost[i] = {{ cost.cost_type }}; - - nlp_solver_plan->nlp_cost[N] = {{ cost.cost_type_e }}; - - for (int i = 0; i < N; i++) - { - {%- if solver_options.integrator_type == "DISCRETE" %} - nlp_solver_plan->nlp_dynamics[i] = DISCRETE_MODEL; - // discrete dynamics does not need sim solver option, this field is ignored - nlp_solver_plan->sim_solver_plan[i].sim_solver = INVALID_SIM_SOLVER; - {%- else %} - nlp_solver_plan->nlp_dynamics[i] = CONTINUOUS_MODEL; - nlp_solver_plan->sim_solver_plan[i].sim_solver = {{ solver_options.integrator_type }}; - {%- endif %} - } - - for (int i = 0; i < N; i++) - { - {%- if constraints.constr_type == "BGP" %} - nlp_solver_plan->nlp_constraints[i] = BGP; - {%- else -%} - nlp_solver_plan->nlp_constraints[i] = BGH; - {%- endif %} - } - - {%- if constraints.constr_type_e == "BGP" %} - nlp_solver_plan->nlp_constraints[N] = BGP; - {%- else %} - nlp_solver_plan->nlp_constraints[N] = BGH; - {%- endif %} - - {%- if solver_options.regularize_method == "NO_REGULARIZE" %} - nlp_solver_plan->regularization = NO_REGULARIZE; - {%- elif solver_options.regularize_method == "MIRROR" %} - nlp_solver_plan->regularization = MIRROR; - {%- elif solver_options.regularize_method == "PROJECT" %} - nlp_solver_plan->regularization = PROJECT; - {%- elif solver_options.regularize_method == "PROJECT_REDUC_HESS" %} - nlp_solver_plan->regularization = PROJECT_REDUC_HESS; - {%- elif solver_options.regularize_method == "CONVEXIFY" %} - nlp_solver_plan->regularization = CONVEXIFY; - {%- endif %} -} - - -/** - * Internal function for {{ model.name }}_acados_create: step 2 - */ -ocp_nlp_dims* {{ model.name }}_acados_create_2_create_and_set_dimensions({{ model.name }}_solver_capsule* capsule) -{ - ocp_nlp_plan_t* nlp_solver_plan = capsule->nlp_solver_plan; - const int N = nlp_solver_plan->N; - ocp_nlp_config* nlp_config = capsule->nlp_config; - - /************************************************ - * dimensions - ************************************************/ - #define NINTNP1MEMS 17 - int* intNp1mem = (int*)malloc( (N+1)*sizeof(int)*NINTNP1MEMS ); - - int* nx = intNp1mem + (N+1)*0; - int* nu = intNp1mem + (N+1)*1; - int* nbx = intNp1mem + (N+1)*2; - int* nbu = intNp1mem + (N+1)*3; - int* nsbx = intNp1mem + (N+1)*4; - int* nsbu = intNp1mem + (N+1)*5; - int* nsg = intNp1mem + (N+1)*6; - int* nsh = intNp1mem + (N+1)*7; - int* nsphi = intNp1mem + (N+1)*8; - int* ns = intNp1mem + (N+1)*9; - int* ng = intNp1mem + (N+1)*10; - int* nh = intNp1mem + (N+1)*11; - int* nphi = intNp1mem + (N+1)*12; - int* nz = intNp1mem + (N+1)*13; - int* ny = intNp1mem + (N+1)*14; - int* nr = intNp1mem + (N+1)*15; - int* nbxe = intNp1mem + (N+1)*16; - - for (int i = 0; i < N+1; i++) - { - // common - nx[i] = NX; - nu[i] = NU; - nz[i] = NZ; - ns[i] = NS; - // cost - ny[i] = NY; - // constraints - nbx[i] = NBX; - nbu[i] = NBU; - nsbx[i] = NSBX; - nsbu[i] = NSBU; - nsg[i] = NSG; - nsh[i] = NSH; - nsphi[i] = NSPHI; - ng[i] = NG; - nh[i] = NH; - nphi[i] = NPHI; - nr[i] = NR; - nbxe[i] = 0; - } - - // for initial state - nbx[0] = NBX0; - nsbx[0] = 0; - ns[0] = NS - NSBX; - nbxe[0] = {{ dims.nbxe_0 }}; - ny[0] = NY0; - - // terminal - common - nu[N] = 0; - nz[N] = 0; - ns[N] = NSN; - // cost - ny[N] = NYN; - // constraint - nbx[N] = NBXN; - nbu[N] = 0; - ng[N] = NGN; - nh[N] = NHN; - nphi[N] = NPHIN; - nr[N] = {{ dims.nr_e }}; - - nsbx[N] = NSBXN; - nsbu[N] = 0; - nsg[N] = NSGN; - nsh[N] = NSHN; - nsphi[N] = NSPHIN; - - /* create and set ocp_nlp_dims */ - ocp_nlp_dims * nlp_dims = ocp_nlp_dims_create(nlp_config); - - ocp_nlp_dims_set_opt_vars(nlp_config, nlp_dims, "nx", nx); - ocp_nlp_dims_set_opt_vars(nlp_config, nlp_dims, "nu", nu); - ocp_nlp_dims_set_opt_vars(nlp_config, nlp_dims, "nz", nz); - ocp_nlp_dims_set_opt_vars(nlp_config, nlp_dims, "ns", ns); - - for (int i = 0; i <= N; i++) - { - ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nbx", &nbx[i]); - ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nbu", &nbu[i]); - ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nsbx", &nsbx[i]); - ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nsbu", &nsbu[i]); - ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "ng", &ng[i]); - ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nsg", &nsg[i]); - ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nbxe", &nbxe[i]); - } - -{%- if cost.cost_type_0 == "NONLINEAR_LS" or cost.cost_type_0 == "LINEAR_LS" or cost.cost_type_0 == "CONVEX_OVER_NONLINEAR"%} - ocp_nlp_dims_set_cost(nlp_config, nlp_dims, 0, "ny", &ny[0]); -{%- endif %} - -{%- if cost.cost_type == "NONLINEAR_LS" or cost.cost_type == "LINEAR_LS" or cost.cost_type == "CONVEX_OVER_NONLINEAR"%} - for (int i = 1; i < N; i++) - ocp_nlp_dims_set_cost(nlp_config, nlp_dims, i, "ny", &ny[i]); -{%- endif %} - - for (int i = 0; i < N; i++) - { - {%- if constraints.constr_type == "BGH" and dims.nh > 0 %} - ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nh", &nh[i]); - ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nsh", &nsh[i]); - {%- elif constraints.constr_type == "BGP" and dims.nphi > 0 %} - ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nr", &nr[i]); - ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nphi", &nphi[i]); - ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nsphi", &nsphi[i]); - {%- endif %} - } - -{%- if constraints.constr_type_e == "BGH" %} - ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, N, "nh", &nh[N]); - ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, N, "nsh", &nsh[N]); -{%- elif constraints.constr_type_e == "BGP" %} - ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, N, "nr", &nr[N]); - ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, N, "nphi", &nphi[N]); - ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, N, "nsphi", &nsphi[N]); -{%- endif %} -{%- if cost.cost_type_e == "NONLINEAR_LS" or cost.cost_type_e == "LINEAR_LS" or cost.cost_type_e == "CONVEX_OVER_NONLINEAR"%} - ocp_nlp_dims_set_cost(nlp_config, nlp_dims, N, "ny", &ny[N]); -{%- endif %} - free(intNp1mem); - -{%- if solver_options.integrator_type == "GNSF" -%} - // GNSF specific dimensions - int gnsf_nx1 = {{ dims.gnsf_nx1 }}; - int gnsf_nz1 = {{ dims.gnsf_nz1 }}; - int gnsf_nout = {{ dims.gnsf_nout }}; - int gnsf_ny = {{ dims.gnsf_ny }}; - int gnsf_nuhat = {{ dims.gnsf_nuhat }}; - - for (int i = 0; i < N; i++) - { - if (nlp_solver_plan->sim_solver_plan[i].sim_solver == GNSF) - { - ocp_nlp_dims_set_dynamics(nlp_config, nlp_dims, i, "gnsf_nx1", &gnsf_nx1); - ocp_nlp_dims_set_dynamics(nlp_config, nlp_dims, i, "gnsf_nz1", &gnsf_nz1); - ocp_nlp_dims_set_dynamics(nlp_config, nlp_dims, i, "gnsf_nout", &gnsf_nout); - ocp_nlp_dims_set_dynamics(nlp_config, nlp_dims, i, "gnsf_ny", &gnsf_ny); - ocp_nlp_dims_set_dynamics(nlp_config, nlp_dims, i, "gnsf_nuhat", &gnsf_nuhat); - } - } -{%- endif %} -return nlp_dims; -} - - -/** - * Internal function for {{ model.name }}_acados_create: step 3 - */ -void {{ model.name }}_acados_create_3_create_and_set_functions({{ model.name }}_solver_capsule* capsule) -{ - const int N = capsule->nlp_solver_plan->N; - - /************************************************ - * external functions - ************************************************/ - -#define MAP_CASADI_FNC(__CAPSULE_FNC__, __MODEL_BASE_FNC__) do{ \ - capsule->__CAPSULE_FNC__.casadi_fun = & __MODEL_BASE_FNC__ ;\ - capsule->__CAPSULE_FNC__.casadi_n_in = & __MODEL_BASE_FNC__ ## _n_in; \ - capsule->__CAPSULE_FNC__.casadi_n_out = & __MODEL_BASE_FNC__ ## _n_out; \ - capsule->__CAPSULE_FNC__.casadi_sparsity_in = & __MODEL_BASE_FNC__ ## _sparsity_in; \ - capsule->__CAPSULE_FNC__.casadi_sparsity_out = & __MODEL_BASE_FNC__ ## _sparsity_out; \ - capsule->__CAPSULE_FNC__.casadi_work = & __MODEL_BASE_FNC__ ## _work; \ - external_function_param_casadi_create(&capsule->__CAPSULE_FNC__ , {{ dims.np }}); \ - }while(false) - -{% if constraints.constr_type == "BGP" %} - // constraints.constr_type == "BGP" - capsule->phi_constraint = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); - for (int i = 0; i < N; i++) - { - // nonlinear part of convex-composite constraint - MAP_CASADI_FNC(phi_constraint[i], {{ model.name }}_phi_constraint); - } -{%- endif %} - -{%- if constraints.constr_type_e == "BGP" %} - // constraints.constr_type_e == "BGP" - // nonlinear part of convex-composite constraint - MAP_CASADI_FNC(phi_e_constraint, {{ model.name }}_phi_e_constraint); -{%- endif %} - -{%- if constraints.constr_type == "BGH" and dims.nh > 0 %} - // constraints.constr_type == "BGH" and dims.nh > 0 - capsule->nl_constr_h_fun_jac = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); - for (int i = 0; i < N; i++) { - MAP_CASADI_FNC(nl_constr_h_fun_jac[i], {{ model.name }}_constr_h_fun_jac_uxt_zt); - } - capsule->nl_constr_h_fun = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); - for (int i = 0; i < N; i++) { - MAP_CASADI_FNC(nl_constr_h_fun[i], {{ model.name }}_constr_h_fun); - } - {% if solver_options.hessian_approx == "EXACT" %} - capsule->nl_constr_h_fun_jac_hess = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); - for (int i = 0; i < N; i++) { - MAP_CASADI_FNC(nl_constr_h_fun_jac_hess[i], {{ model.name }}_constr_h_fun_jac_uxt_zt_hess); - } - {% endif %} -{% endif %} - -{%- if constraints.constr_type_e == "BGH" and dims.nh_e > 0 %} - MAP_CASADI_FNC(nl_constr_h_e_fun_jac, {{ model.name }}_constr_h_e_fun_jac_uxt_zt); - MAP_CASADI_FNC(nl_constr_h_e_fun, {{ model.name }}_constr_h_e_fun); - - {%- if solver_options.hessian_approx == "EXACT" %} - MAP_CASADI_FNC(nl_constr_h_e_fun_jac_hess, {{ model.name }}_constr_h_e_fun_jac_uxt_zt_hess); - {% endif %} -{%- endif %} - -{% if solver_options.integrator_type == "ERK" %} - // explicit ode - capsule->forw_vde_casadi = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); - for (int i = 0; i < N; i++) { - MAP_CASADI_FNC(forw_vde_casadi[i], {{ model.name }}_expl_vde_forw); - } - - capsule->expl_ode_fun = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); - for (int i = 0; i < N; i++) { - MAP_CASADI_FNC(expl_ode_fun[i], {{ model.name }}_expl_ode_fun); - } - - {%- if solver_options.hessian_approx == "EXACT" %} - capsule->hess_vde_casadi = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); - for (int i = 0; i < N; i++) { - MAP_CASADI_FNC(hess_vde_casadi[i], {{ model.name }}_expl_ode_hess); - } - {%- endif %} - -{% elif solver_options.integrator_type == "IRK" %} - // implicit dae - capsule->impl_dae_fun = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})*N); - for (int i = 0; i < N; i++) { - {%- if model.dyn_ext_fun_type == "casadi" %} - MAP_CASADI_FNC(impl_dae_fun[i], {{ model.name }}_impl_dae_fun); - {%- else %} - capsule->impl_dae_fun[i].fun = &{{ model.dyn_impl_dae_fun }}; - external_function_param_{{ model.dyn_ext_fun_type }}_create(&capsule->impl_dae_fun[i], {{ dims.np }}); - {%- endif %} - } - - capsule->impl_dae_fun_jac_x_xdot_z = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})*N); - for (int i = 0; i < N; i++) { - {%- if model.dyn_ext_fun_type == "casadi" %} - MAP_CASADI_FNC(impl_dae_fun_jac_x_xdot_z[i], {{ model.name }}_impl_dae_fun_jac_x_xdot_z); - {%- else %} - capsule->impl_dae_fun_jac_x_xdot_z[i].fun = &{{ model.dyn_impl_dae_fun_jac }}; - external_function_param_{{ model.dyn_ext_fun_type }}_create(&capsule->impl_dae_fun_jac_x_xdot_z[i], {{ dims.np }}); - {%- endif %} - } - - capsule->impl_dae_jac_x_xdot_u_z = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})*N); - for (int i = 0; i < N; i++) { - {%- if model.dyn_ext_fun_type == "casadi" %} - MAP_CASADI_FNC(impl_dae_jac_x_xdot_u_z[i], {{ model.name }}_impl_dae_jac_x_xdot_u_z); - {%- else %} - capsule->impl_dae_jac_x_xdot_u_z[i].fun = &{{ model.dyn_impl_dae_jac }}; - external_function_param_{{ model.dyn_ext_fun_type }}_create(&capsule->impl_dae_jac_x_xdot_u_z[i], {{ dims.np }}); - {%- endif %} - } - - {%- if solver_options.hessian_approx == "EXACT" %} - capsule->impl_dae_hess = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})*N); - for (int i = 0; i < N; i++) { - MAP_CASADI_FNC(impl_dae_hess[i], {{ model.name }}_impl_dae_hess); - } - {%- endif %} -{% elif solver_options.integrator_type == "LIFTED_IRK" %} - // external functions (implicit model) - capsule->impl_dae_fun = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})*N); - for (int i = 0; i < N; i++) { - MAP_CASADI_FNC(impl_dae_fun[i], {{ model.name }}_impl_dae_fun); - } - - capsule->impl_dae_fun_jac_x_xdot_u = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})*N); - for (int i = 0; i < N; i++) { - MAP_CASADI_FNC(impl_dae_fun_jac_x_xdot_u[i], {{ model.name }}_impl_dae_fun_jac_x_xdot_u); - } - -{% elif solver_options.integrator_type == "GNSF" %} - {% if model.gnsf.purely_linear != 1 %} - capsule->gnsf_phi_fun = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); - for (int i = 0; i < N; i++) { - MAP_CASADI_FNC(gnsf_phi_fun[i], {{ model.name }}_gnsf_phi_fun); - } - - capsule->gnsf_phi_fun_jac_y = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); - for (int i = 0; i < N; i++) { - MAP_CASADI_FNC(gnsf_phi_fun_jac_y[i], {{ model.name }}_gnsf_phi_fun_jac_y); - } - - capsule->gnsf_phi_jac_y_uhat = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); - for (int i = 0; i < N; i++) { - MAP_CASADI_FNC(gnsf_phi_jac_y_uhat[i], {{ model.name }}_gnsf_phi_jac_y_uhat); - } - - {% if model.gnsf.nontrivial_f_LO == 1 %} - capsule->gnsf_f_lo_jac_x1_x1dot_u_z = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); - for (int i = 0; i < N; i++) { - MAP_CASADI_FNC(gnsf_f_lo_jac_x1_x1dot_u_z[i], {{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz); - } - {%- endif %} - {%- endif %} - capsule->gnsf_get_matrices_fun = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); - for (int i = 0; i < N; i++) { - MAP_CASADI_FNC(gnsf_get_matrices_fun[i], {{ model.name }}_gnsf_get_matrices_fun); - } -{% elif solver_options.integrator_type == "DISCRETE" %} - // discrete dynamics - capsule->discr_dyn_phi_fun = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})*N); - for (int i = 0; i < N; i++) - { - {%- if model.dyn_ext_fun_type == "casadi" %} - MAP_CASADI_FNC(discr_dyn_phi_fun[i], {{ model.name }}_dyn_disc_phi_fun); - {%- else %} - capsule->discr_dyn_phi_fun[i].fun = &{{ model.dyn_disc_fun }}; - external_function_param_{{ model.dyn_ext_fun_type }}_create(&capsule->discr_dyn_phi_fun[i], {{ dims.np }}); - {%- endif %} - } - - capsule->discr_dyn_phi_fun_jac_ut_xt = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})*N); - for (int i = 0; i < N; i++) - { - {%- if model.dyn_ext_fun_type == "casadi" %} - MAP_CASADI_FNC(discr_dyn_phi_fun_jac_ut_xt[i], {{ model.name }}_dyn_disc_phi_fun_jac); - {%- else %} - capsule->discr_dyn_phi_fun_jac_ut_xt[i].fun = &{{ model.dyn_disc_fun_jac }}; - external_function_param_{{ model.dyn_ext_fun_type }}_create(&capsule->discr_dyn_phi_fun_jac_ut_xt[i], {{ dims.np }}); - {%- endif %} - } - - {%- if solver_options.hessian_approx == "EXACT" %} - capsule->discr_dyn_phi_fun_jac_ut_xt_hess = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})*N); - for (int i = 0; i < N; i++) - { - {%- if model.dyn_ext_fun_type == "casadi" %} - MAP_CASADI_FNC(discr_dyn_phi_fun_jac_ut_xt_hess[i], {{ model.name }}_dyn_disc_phi_fun_jac_hess); - {%- else %} - capsule->discr_dyn_phi_fun_jac_ut_xt_hess[i].fun = &{{ model.dyn_disc_fun_jac_hess }}; - external_function_param_{{ model.dyn_ext_fun_type }}_create(&capsule->discr_dyn_phi_fun_jac_ut_xt_hess[i], {{ dims.np }}); - {%- endif %} - } - {%- endif %} -{%- endif %} - - -{%- if cost.cost_type_0 == "NONLINEAR_LS" %} - // nonlinear least squares function - MAP_CASADI_FNC(cost_y_0_fun, {{ model.name }}_cost_y_0_fun); - MAP_CASADI_FNC(cost_y_0_fun_jac_ut_xt, {{ model.name }}_cost_y_0_fun_jac_ut_xt); - MAP_CASADI_FNC(cost_y_0_hess, {{ model.name }}_cost_y_0_hess); - -{%- elif cost.cost_type_0 == "CONVEX_OVER_NONLINEAR" %} - // convex-over-nonlinear cost - MAP_CASADI_FNC(conl_cost_0_fun, {{ model.name }}_conl_cost_0_fun); - MAP_CASADI_FNC(conl_cost_0_fun_jac_hess, {{ model.name }}_conl_cost_0_fun_jac_hess); - -{%- elif cost.cost_type_0 == "EXTERNAL" %} - // external cost - {%- if cost.cost_ext_fun_type_0 == "casadi" %} - MAP_CASADI_FNC(ext_cost_0_fun, {{ model.name }}_cost_ext_cost_0_fun); - {%- else %} - capsule->ext_cost_0_fun.fun = &{{ cost.cost_function_ext_cost_0 }}; - external_function_param_{{ cost.cost_ext_fun_type_0 }}_create(&capsule->ext_cost_0_fun, {{ dims.np }}); - {%- endif %} - - // external cost - {%- if cost.cost_ext_fun_type_0 == "casadi" %} - MAP_CASADI_FNC(ext_cost_0_fun_jac, {{ model.name }}_cost_ext_cost_0_fun_jac); - {%- else %} - capsule->ext_cost_0_fun_jac.fun = &{{ cost.cost_function_ext_cost_0 }}; - external_function_param_{{ cost.cost_ext_fun_type_0 }}_create(&capsule->ext_cost_0_fun_jac, {{ dims.np }}); - {%- endif %} - - // external cost - {%- if cost.cost_ext_fun_type_0 == "casadi" %} - MAP_CASADI_FNC(ext_cost_0_fun_jac_hess, {{ model.name }}_cost_ext_cost_0_fun_jac_hess); - {%- else %} - capsule->ext_cost_0_fun_jac_hess.fun = &{{ cost.cost_function_ext_cost_0 }}; - external_function_param_{{ cost.cost_ext_fun_type_0 }}_create(&capsule->ext_cost_0_fun_jac_hess, {{ dims.np }}); - {%- endif %} -{%- endif %} - -{%- if cost.cost_type == "NONLINEAR_LS" %} - // nonlinear least squares cost - capsule->cost_y_fun = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); - for (int i = 0; i < N-1; i++) - { - MAP_CASADI_FNC(cost_y_fun[i], {{ model.name }}_cost_y_fun); - } - - capsule->cost_y_fun_jac_ut_xt = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); - for (int i = 0; i < N-1; i++) - { - MAP_CASADI_FNC(cost_y_fun_jac_ut_xt[i], {{ model.name }}_cost_y_fun_jac_ut_xt); - } - - capsule->cost_y_hess = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); - for (int i = 0; i < N-1; i++) - { - MAP_CASADI_FNC(cost_y_hess[i], {{ model.name }}_cost_y_hess); - } - -{%- elif cost.cost_type_0 == "CONVEX_OVER_NONLINEAR" %} - // convex-over-nonlinear cost - capsule->conl_cost_fun = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); - for (int i = 0; i < N-1; i++) - { - MAP_CASADI_FNC(conl_cost_fun[i], {{ model.name }}_conl_cost_fun); - } - capsule->conl_cost_fun_jac_hess = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); - for (int i = 0; i < N-1; i++) - { - MAP_CASADI_FNC(conl_cost_fun_jac_hess[i], {{ model.name }}_conl_cost_fun_jac_hess); - } - -{%- elif cost.cost_type == "EXTERNAL" %} - // external cost - capsule->ext_cost_fun = (external_function_param_{{ cost.cost_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ cost.cost_ext_fun_type }})*N); - for (int i = 0; i < N-1; i++) - { - {%- if cost.cost_ext_fun_type == "casadi" %} - MAP_CASADI_FNC(ext_cost_fun[i], {{ model.name }}_cost_ext_cost_fun); - {%- else %} - capsule->ext_cost_fun[i].fun = &{{ cost.cost_function_ext_cost }}; - external_function_param_{{ cost.cost_ext_fun_type }}_create(&capsule->ext_cost_fun[i], {{ dims.np }}); - {%- endif %} - } - - capsule->ext_cost_fun_jac = (external_function_param_{{ cost.cost_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ cost.cost_ext_fun_type }})*N); - for (int i = 0; i < N-1; i++) - { - {%- if cost.cost_ext_fun_type == "casadi" %} - MAP_CASADI_FNC(ext_cost_fun_jac[i], {{ model.name }}_cost_ext_cost_fun_jac); - {%- else %} - capsule->ext_cost_fun_jac[i].fun = &{{ cost.cost_function_ext_cost }}; - external_function_param_{{ cost.cost_ext_fun_type }}_create(&capsule->ext_cost_fun_jac[i], {{ dims.np }}); - {%- endif %} - } - - capsule->ext_cost_fun_jac_hess = (external_function_param_{{ cost.cost_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ cost.cost_ext_fun_type }})*N); - for (int i = 0; i < N-1; i++) - { - {%- if cost.cost_ext_fun_type == "casadi" %} - MAP_CASADI_FNC(ext_cost_fun_jac_hess[i], {{ model.name }}_cost_ext_cost_fun_jac_hess); - {%- else %} - capsule->ext_cost_fun_jac_hess[i].fun = &{{ cost.cost_function_ext_cost }}; - external_function_param_{{ cost.cost_ext_fun_type }}_create(&capsule->ext_cost_fun_jac_hess[i], {{ dims.np }}); - {%- endif %} - } -{%- endif %} - -{%- if cost.cost_type_e == "NONLINEAR_LS" %} - // nonlinear least square function - MAP_CASADI_FNC(cost_y_e_fun, {{ model.name }}_cost_y_e_fun); - MAP_CASADI_FNC(cost_y_e_fun_jac_ut_xt, {{ model.name }}_cost_y_e_fun_jac_ut_xt); - MAP_CASADI_FNC(cost_y_e_hess, {{ model.name }}_cost_y_e_hess); - -{%- elif cost.cost_type_e == "CONVEX_OVER_NONLINEAR" %} - // convex-over-nonlinear cost - MAP_CASADI_FNC(conl_cost_e_fun, {{ model.name }}_conl_cost_e_fun); - MAP_CASADI_FNC(conl_cost_e_fun_jac_hess, {{ model.name }}_conl_cost_e_fun_jac_hess); - -{%- elif cost.cost_type_e == "EXTERNAL" %} - // external cost - function - {%- if cost.cost_ext_fun_type_e == "casadi" %} - MAP_CASADI_FNC(ext_cost_e_fun, {{ model.name }}_cost_ext_cost_e_fun); - {% else %} - capsule->ext_cost_e_fun.fun = &{{ cost.cost_function_ext_cost_e }}; - external_function_param_{{ cost.cost_ext_fun_type_e }}_create(&capsule->ext_cost_e_fun, {{ dims.np }}); - {%- endif %} - - // external cost - jacobian - {%- if cost.cost_ext_fun_type_e == "casadi" %} - MAP_CASADI_FNC(ext_cost_e_fun_jac, {{ model.name }}_cost_ext_cost_e_fun_jac); - {%- else %} - capsule->ext_cost_e_fun_jac.fun = &{{ cost.cost_function_ext_cost_e }}; - external_function_param_{{ cost.cost_ext_fun_type_e }}_create(&capsule->ext_cost_e_fun_jac, {{ dims.np }}); - {%- endif %} - - // external cost - hessian - {%- if cost.cost_ext_fun_type_e == "casadi" %} - MAP_CASADI_FNC(ext_cost_e_fun_jac_hess, {{ model.name }}_cost_ext_cost_e_fun_jac_hess); - {%- else %} - capsule->ext_cost_e_fun_jac_hess.fun = &{{ cost.cost_function_ext_cost_e }}; - external_function_param_{{ cost.cost_ext_fun_type_e }}_create(&capsule->ext_cost_e_fun_jac_hess, {{ dims.np }}); - {%- endif %} -{%- endif %} - -#undef MAP_CASADI_FNC -} - - -/** - * Internal function for {{ model.name }}_acados_create: step 4 - */ -void {{ model.name }}_acados_create_4_set_default_parameters({{ model.name }}_solver_capsule* capsule) { -{%- if dims.np > 0 %} - const int N = capsule->nlp_solver_plan->N; - // initialize parameters to nominal value - double* p = calloc(NP, sizeof(double)); - {%- for item in parameter_values %} - {%- if item != 0 %} - p[{{ loop.index0 }}] = {{ item }}; - {%- endif %} - {%- endfor %} - - for (int i = 0; i <= N; i++) { - {{ model.name }}_acados_update_params(capsule, i, p, NP); - } - free(p); -{%- else %} - // no parameters defined -{%- endif %}{# if dims.np #} -} - - -/** - * Internal function for {{ model.name }}_acados_create: step 5 - */ -void {{ model.name }}_acados_create_5_set_nlp_in({{ model.name }}_solver_capsule* capsule, const int N, double* new_time_steps) -{ - assert(N == capsule->nlp_solver_plan->N); - ocp_nlp_config* nlp_config = capsule->nlp_config; - ocp_nlp_dims* nlp_dims = capsule->nlp_dims; - - /************************************************ - * nlp_in - ************************************************/ -// ocp_nlp_in * nlp_in = ocp_nlp_in_create(nlp_config, nlp_dims); -// capsule->nlp_in = nlp_in; - ocp_nlp_in * nlp_in = capsule->nlp_in; - - // set up time_steps - {% set all_equal = true -%} - {%- set val = solver_options.time_steps[0] %} - {%- for j in range(start=1, end=dims.N) %} - {%- if val != solver_options.time_steps[j] %} - {%- set_global all_equal = false %} - {%- break %} - {%- endif %} - {%- endfor %} - - if (new_time_steps) { - {{ model.name }}_acados_update_time_steps(capsule, N, new_time_steps); - } else { - {%- if all_equal == true -%} - // all time_steps are identical - double time_step = {{ solver_options.time_steps[0] }}; - for (int i = 0; i < N; i++) - { - ocp_nlp_in_set(nlp_config, nlp_dims, nlp_in, i, "Ts", &time_step); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "scaling", &time_step); - } - {%- else -%} - // time_steps are different - double* time_steps = malloc(N*sizeof(double)); - {%- for j in range(end=dims.N) %} - time_steps[{{ j }}] = {{ solver_options.time_steps[j] }}; - {%- endfor %} - {{ model.name }}_acados_update_time_steps(capsule, N, time_steps); - free(time_steps); - {%- endif %} - } - - /**** Dynamics ****/ - for (int i = 0; i < N; i++) - { - {%- if solver_options.integrator_type == "ERK" %} - ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "expl_vde_forw", &capsule->forw_vde_casadi[i]); - ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "expl_ode_fun", &capsule->expl_ode_fun[i]); - {%- if solver_options.hessian_approx == "EXACT" %} - ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "expl_ode_hess", &capsule->hess_vde_casadi[i]); - {%- endif %} - {% elif solver_options.integrator_type == "IRK" %} - ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "impl_dae_fun", &capsule->impl_dae_fun[i]); - ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, - "impl_dae_fun_jac_x_xdot_z", &capsule->impl_dae_fun_jac_x_xdot_z[i]); - ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, - "impl_dae_jac_x_xdot_u", &capsule->impl_dae_jac_x_xdot_u_z[i]); - {%- if solver_options.hessian_approx == "EXACT" %} - ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "impl_dae_hess", &capsule->impl_dae_hess[i]); - {%- endif %} - {% elif solver_options.integrator_type == "LIFTED_IRK" %} - ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "impl_dae_fun", &capsule->impl_dae_fun[i]); - ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, - "impl_dae_fun_jac_x_xdot_u", &capsule->impl_dae_fun_jac_x_xdot_u[i]); - {% elif solver_options.integrator_type == "GNSF" %} - {% if model.gnsf.purely_linear != 1 %} - ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "phi_fun", &capsule->gnsf_phi_fun[i]); - ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "phi_fun_jac_y", &capsule->gnsf_phi_fun_jac_y[i]); - ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "phi_jac_y_uhat", &capsule->gnsf_phi_jac_y_uhat[i]); - {% if model.gnsf.nontrivial_f_LO == 1 %} - ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "f_lo_jac_x1_x1dot_u_z", - &capsule->gnsf_f_lo_jac_x1_x1dot_u_z[i]); - {%- endif %} - {%- endif %} - ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "gnsf_get_matrices_fun", - &capsule->gnsf_get_matrices_fun[i]); - {% elif solver_options.integrator_type == "DISCRETE" %} - ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "disc_dyn_fun", &capsule->discr_dyn_phi_fun[i]); - ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "disc_dyn_fun_jac", - &capsule->discr_dyn_phi_fun_jac_ut_xt[i]); - {%- if solver_options.hessian_approx == "EXACT" %} - ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "disc_dyn_fun_jac_hess", - &capsule->discr_dyn_phi_fun_jac_ut_xt_hess[i]); - {%- endif %} - {%- endif %} - } - - /**** Cost ****/ - -{%- if dims.ny_0 == 0 %} -{%- elif cost.cost_type_0 == "NONLINEAR_LS" or cost.cost_type_0 == "LINEAR_LS" or cost.cost_type_0 == "CONVEX_OVER_NONLINEAR" %} - double* yref_0 = calloc(NY0, sizeof(double)); - // change only the non-zero elements: - {%- for j in range(end=dims.ny_0) %} - {%- if cost.yref_0[j] != 0 %} - yref_0[{{ j }}] = {{ cost.yref_0[j] }}; - {%- endif %} - {%- endfor %} - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "yref", yref_0); - free(yref_0); -{%- endif %} - - -{%- if dims.ny == 0 %} -{%- elif cost.cost_type == "NONLINEAR_LS" or cost.cost_type == "LINEAR_LS" or cost.cost_type == "CONVEX_OVER_NONLINEAR" %} - double* yref = calloc(NY, sizeof(double)); - // change only the non-zero elements: - {%- for j in range(end=dims.ny) %} - {%- if cost.yref[j] != 0 %} - yref[{{ j }}] = {{ cost.yref[j] }}; - {%- endif %} - {%- endfor %} - - for (int i = 1; i < N; i++) - { - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "yref", yref); - } - free(yref); -{%- endif %} - - -{%- if dims.ny_e == 0 %} -{%- elif cost.cost_type_e == "NONLINEAR_LS" or cost.cost_type_e == "LINEAR_LS" or cost.cost_type_e == "CONVEX_OVER_NONLINEAR" %} - double* yref_e = calloc(NYN, sizeof(double)); - // change only the non-zero elements: - {%- for j in range(end=dims.ny_e) %} - {%- if cost.yref_e[j] != 0 %} - yref_e[{{ j }}] = {{ cost.yref_e[j] }}; - {%- endif %} - {%- endfor %} - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "yref", yref_e); - free(yref_e); -{%- endif %} - -{%- if dims.ny_0 == 0 %} -{%- elif cost.cost_type_0 == "NONLINEAR_LS" or cost.cost_type_0 == "LINEAR_LS" %} - double* W_0 = calloc(NY0*NY0, sizeof(double)); - // change only the non-zero elements: - {%- for j in range(end=dims.ny_0) %} - {%- for k in range(end=dims.ny_0) %} - {%- if cost.W_0[j][k] != 0 %} - W_0[{{ j }}+(NY0) * {{ k }}] = {{ cost.W_0[j][k] }}; - {%- endif %} - {%- endfor %} - {%- endfor %} - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "W", W_0); - free(W_0); -{%- endif %} - -{%- if dims.ny == 0 %} -{%- elif cost.cost_type == "NONLINEAR_LS" or cost.cost_type == "LINEAR_LS" %} - double* W = calloc(NY*NY, sizeof(double)); - // change only the non-zero elements: - {%- for j in range(end=dims.ny) %} - {%- for k in range(end=dims.ny) %} - {%- if cost.W[j][k] != 0 %} - W[{{ j }}+(NY) * {{ k }}] = {{ cost.W[j][k] }}; - {%- endif %} - {%- endfor %} - {%- endfor %} - - for (int i = 1; i < N; i++) - { - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "W", W); - } - free(W); -{%- endif %} - -{%- if dims.ny_e == 0 %} -{%- elif cost.cost_type_e == "NONLINEAR_LS" or cost.cost_type_e == "LINEAR_LS" %} - double* W_e = calloc(NYN*NYN, sizeof(double)); - // change only the non-zero elements: - {%- for j in range(end=dims.ny_e) %} - {%- for k in range(end=dims.ny_e) %} - {%- if cost.W_e[j][k] != 0 %} - W_e[{{ j }}+(NYN) * {{ k }}] = {{ cost.W_e[j][k] }}; - {%- endif %} - {%- endfor %} - {%- endfor %} - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "W", W_e); - free(W_e); -{%- endif %} - -{%- if dims.ny_0 == 0 %} -{%- elif cost.cost_type_0 == "LINEAR_LS" %} - double* Vx_0 = calloc(NY0*NX, sizeof(double)); - // change only the non-zero elements: - {%- for j in range(end=dims.ny_0) %} - {%- for k in range(end=dims.nx) %} - {%- if cost.Vx_0[j][k] != 0 %} - Vx_0[{{ j }}+(NY0) * {{ k }}] = {{ cost.Vx_0[j][k] }}; - {%- endif %} - {%- endfor %} - {%- endfor %} - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "Vx", Vx_0); - free(Vx_0); - - {%- if dims.nu > 0 %} - double* Vu_0 = calloc(NY0*NU, sizeof(double)); - // change only the non-zero elements: - {%- for j in range(end=dims.ny_0) %} - {%- for k in range(end=dims.nu) %} - {%- if cost.Vu_0[j][k] != 0 %} - Vu_0[{{ j }}+(NY0) * {{ k }}] = {{ cost.Vu_0[j][k] }}; - {%- endif %} - {%- endfor %} - {%- endfor %} - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "Vu", Vu_0); - free(Vu_0); - {%- endif %} - - {%- if dims.nz > 0 %} - double* Vz_0 = calloc(NY0*NZ, sizeof(double)); - // change only the non-zero elements: - {% for j in range(end=dims.ny_0) %} - {%- for k in range(end=dims.nz) %} - {%- if cost.Vz_0[j][k] != 0 %} - Vz_0[{{ j }}+(NY0) * {{ k }}] = {{ cost.Vz_0[j][k] }}; - {%- endif %} - {%- endfor %} - {%- endfor %} - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "Vz", Vz_0); - free(Vz_0); - {%- endif %} -{%- endif %} - -{%- if dims.ny == 0 %} -{%- elif cost.cost_type == "LINEAR_LS" %} - double* Vx = calloc(NY*NX, sizeof(double)); - // change only the non-zero elements: - {%- for j in range(end=dims.ny) %} - {%- for k in range(end=dims.nx) %} - {%- if cost.Vx[j][k] != 0 %} - Vx[{{ j }}+(NY) * {{ k }}] = {{ cost.Vx[j][k] }}; - {%- endif %} - {%- endfor %} - {%- endfor %} - for (int i = 1; i < N; i++) - { - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "Vx", Vx); - } - free(Vx); - - {% if dims.nu > 0 %} - double* Vu = calloc(NY*NU, sizeof(double)); - // change only the non-zero elements: - {% for j in range(end=dims.ny) %} - {%- for k in range(end=dims.nu) %} - {%- if cost.Vu[j][k] != 0 %} - Vu[{{ j }}+(NY) * {{ k }}] = {{ cost.Vu[j][k] }}; - {%- endif %} - {%- endfor %} - {%- endfor %} - - for (int i = 1; i < N; i++) - { - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "Vu", Vu); - } - free(Vu); - {%- endif %} - - {%- if dims.nz > 0 %} - double* Vz = calloc(NY*NZ, sizeof(double)); - // change only the non-zero elements: - {% for j in range(end=dims.ny) %} - {%- for k in range(end=dims.nz) %} - {%- if cost.Vz[j][k] != 0 %} - Vz[{{ j }}+(NY) * {{ k }}] = {{ cost.Vz[j][k] }}; - {%- endif %} - {%- endfor %} - {%- endfor %} - - for (int i = 1; i < N; i++) - { - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "Vz", Vz); - } - free(Vz); - {%- endif %} -{%- endif %}{# LINEAR LS #} - -{%- if dims.ny_e == 0 %} -{%- elif cost.cost_type_e == "LINEAR_LS" %} - double* Vx_e = calloc(NYN*NX, sizeof(double)); - // change only the non-zero elements: - {% for j in range(end=dims.ny_e) %} - {%- for k in range(end=dims.nx) %} - {%- if cost.Vx_e[j][k] != 0 %} - Vx_e[{{ j }}+(NYN) * {{ k }}] = {{ cost.Vx_e[j][k] }}; - {%- endif %} - {%- endfor %} - {%- endfor %} - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "Vx", Vx_e); - free(Vx_e); -{%- endif %} - -{%- if cost.cost_type_0 == "NONLINEAR_LS" %} - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "nls_y_fun", &capsule->cost_y_0_fun); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "nls_y_fun_jac", &capsule->cost_y_0_fun_jac_ut_xt); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "nls_y_hess", &capsule->cost_y_0_hess); -{%- elif cost.cost_type_0 == "CONVEX_OVER_NONLINEAR" %} - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "conl_cost_fun", &capsule->conl_cost_0_fun); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "conl_cost_fun_jac_hess", &capsule->conl_cost_0_fun_jac_hess); -{%- elif cost.cost_type_0 == "EXTERNAL" %} - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "ext_cost_fun", &capsule->ext_cost_0_fun); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "ext_cost_fun_jac", &capsule->ext_cost_0_fun_jac); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "ext_cost_fun_jac_hess", &capsule->ext_cost_0_fun_jac_hess); -{%- endif %} - -{%- if cost.cost_type == "NONLINEAR_LS" %} - for (int i = 1; i < N; i++) - { - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "nls_y_fun", &capsule->cost_y_fun[i-1]); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "nls_y_fun_jac", &capsule->cost_y_fun_jac_ut_xt[i-1]); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "nls_y_hess", &capsule->cost_y_hess[i-1]); - } -{%- elif cost.cost_type == "CONVEX_OVER_NONLINEAR" %} - for (int i = 1; i < N; i++) - { - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "conl_cost_fun", &capsule->conl_cost_fun[i-1]); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "conl_cost_fun_jac_hess", &capsule->conl_cost_fun_jac_hess[i-1]); - } -{%- elif cost.cost_type == "EXTERNAL" %} - for (int i = 1; i < N; i++) - { - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "ext_cost_fun", &capsule->ext_cost_fun[i-1]); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "ext_cost_fun_jac", &capsule->ext_cost_fun_jac[i-1]); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "ext_cost_fun_jac_hess", &capsule->ext_cost_fun_jac_hess[i-1]); - } -{%- endif %} - -{%- if cost.cost_type_e == "NONLINEAR_LS" %} - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "nls_y_fun", &capsule->cost_y_e_fun); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "nls_y_fun_jac", &capsule->cost_y_e_fun_jac_ut_xt); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "nls_y_hess", &capsule->cost_y_e_hess); - -{%- elif cost.cost_type_e == "CONVEX_OVER_NONLINEAR" %} - - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "conl_cost_fun", &capsule->conl_cost_e_fun); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "conl_cost_fun_jac_hess", &capsule->conl_cost_e_fun_jac_hess); - -{%- elif cost.cost_type_e == "EXTERNAL" %} - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "ext_cost_fun", &capsule->ext_cost_e_fun); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "ext_cost_fun_jac", &capsule->ext_cost_e_fun_jac); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "ext_cost_fun_jac_hess", &capsule->ext_cost_e_fun_jac_hess); -{%- endif %} - - -{%- if dims.ns > 0 %} - // slacks - double* zlumem = calloc(4*NS, sizeof(double)); - double* Zl = zlumem+NS*0; - double* Zu = zlumem+NS*1; - double* zl = zlumem+NS*2; - double* zu = zlumem+NS*3; - // change only the non-zero elements: - {%- for j in range(end=dims.ns) %} - {%- if cost.Zl[j] != 0 %} - Zl[{{ j }}] = {{ cost.Zl[j] }}; - {%- endif %} - {%- endfor %} - - {%- for j in range(end=dims.ns) %} - {%- if cost.Zu[j] != 0 %} - Zu[{{ j }}] = {{ cost.Zu[j] }}; - {%- endif %} - {%- endfor %} - - {%- for j in range(end=dims.ns) %} - {%- if cost.zl[j] != 0 %} - zl[{{ j }}] = {{ cost.zl[j] }}; - {%- endif %} - {%- endfor %} - - {%- for j in range(end=dims.ns) %} - {%- if cost.zu[j] != 0 %} - zu[{{ j }}] = {{ cost.zu[j] }}; - {%- endif %} - {%- endfor %} - - for (int i = 0; i < N; i++) - { - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "Zl", Zl); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "Zu", Zu); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "zl", zl); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "zu", zu); - } - free(zlumem); -{%- endif %} - -{% if dims.ns_e > 0 %} - // slacks terminal - double* zluemem = calloc(4*NSN, sizeof(double)); - double* Zl_e = zluemem+NSN*0; - double* Zu_e = zluemem+NSN*1; - double* zl_e = zluemem+NSN*2; - double* zu_e = zluemem+NSN*3; - - // change only the non-zero elements: - {% for j in range(end=dims.ns_e) %} - {%- if cost.Zl_e[j] != 0 %} - Zl_e[{{ j }}] = {{ cost.Zl_e[j] }}; - {%- endif %} - {%- endfor %} - - {% for j in range(end=dims.ns_e) %} - {%- if cost.Zu_e[j] != 0 %} - Zu_e[{{ j }}] = {{ cost.Zu_e[j] }}; - {%- endif %} - {%- endfor %} - - {% for j in range(end=dims.ns_e) %} - {%- if cost.zl_e[j] != 0 %} - zl_e[{{ j }}] = {{ cost.zl_e[j] }}; - {%- endif %} - {%- endfor %} - - {% for j in range(end=dims.ns_e) %} - {%- if cost.zu_e[j] != 0 %} - zu_e[{{ j }}] = {{ cost.zu_e[j] }}; - {%- endif %} - {%- endfor %} - - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "Zl", Zl_e); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "Zu", Zu_e); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "zl", zl_e); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "zu", zu_e); - free(zluemem); -{%- endif %} - - /**** Constraints ****/ - - // bounds for initial stage -{%- if dims.nbx_0 > 0 %} - // x0 - int* idxbx0 = malloc(NBX0 * sizeof(int)); - {%- for i in range(end=dims.nbx_0) %} - idxbx0[{{ i }}] = {{ constraints.idxbx_0[i] }}; - {%- endfor %} - - double* lubx0 = calloc(2*NBX0, sizeof(double)); - double* lbx0 = lubx0; - double* ubx0 = lubx0 + NBX0; - // change only the non-zero elements: - {%- for i in range(end=dims.nbx_0) %} - {%- if constraints.lbx_0[i] != 0 %} - lbx0[{{ i }}] = {{ constraints.lbx_0[i] }}; - {%- endif %} - {%- if constraints.ubx_0[i] != 0 %} - ubx0[{{ i }}] = {{ constraints.ubx_0[i] }}; - {%- endif %} - {%- endfor %} - - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "idxbx", idxbx0); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "lbx", lbx0); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "ubx", ubx0); - free(idxbx0); - free(lubx0); -{%- endif %} - -{%- if dims.nbxe_0 > 0 %} - // idxbxe_0 - int* idxbxe_0 = malloc({{ dims.nbxe_0 }} * sizeof(int)); - {% for i in range(end=dims.nbxe_0) %} - idxbxe_0[{{ i }}] = {{ constraints.idxbxe_0[i] }}; - {%- endfor %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "idxbxe", idxbxe_0); - free(idxbxe_0); -{%- endif %} - - /* constraints that are the same for initial and intermediate */ -{%- if dims.nsbx > 0 %} -{# TODO: introduce nsbx0 & move this block down!! #} - // ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "idxsbx", idxsbx); - // ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "lsbx", lsbx); - // ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "usbx", usbx); - - // soft bounds on x - int* idxsbx = malloc(NSBX * sizeof(int)); - {%- for i in range(end=dims.nsbx) %} - idxsbx[{{ i }}] = {{ constraints.idxsbx[i] }}; - {%- endfor %} - - double* lusbx = calloc(2*NSBX, sizeof(double)); - double* lsbx = lusbx; - double* usbx = lusbx + NSBX; - {%- for i in range(end=dims.nsbx) %} - {%- if constraints.lsbx[i] != 0 %} - lsbx[{{ i }}] = {{ constraints.lsbx[i] }}; - {%- endif %} - {%- if constraints.usbx[i] != 0 %} - usbx[{{ i }}] = {{ constraints.usbx[i] }}; - {%- endif %} - {%- endfor %} - - for (int i = 1; i < N; i++) - { - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "idxsbx", idxsbx); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "lsbx", lsbx); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "usbx", usbx); - } - free(idxsbx); - free(lusbx); -{%- endif %} - - -{%- if dims.nbu > 0 %} - // u - int* idxbu = malloc(NBU * sizeof(int)); - {% for i in range(end=dims.nbu) %} - idxbu[{{ i }}] = {{ constraints.idxbu[i] }}; - {%- endfor %} - double* lubu = calloc(2*NBU, sizeof(double)); - double* lbu = lubu; - double* ubu = lubu + NBU; - {% for i in range(end=dims.nbu) %} - {%- if constraints.lbu[i] != 0 %} - lbu[{{ i }}] = {{ constraints.lbu[i] }}; - {%- endif %} - {%- if constraints.ubu[i] != 0 %} - ubu[{{ i }}] = {{ constraints.ubu[i] }}; - {%- endif %} - {%- endfor %} - - for (int i = 0; i < N; i++) - { - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "idxbu", idxbu); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "lbu", lbu); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "ubu", ubu); - } - free(idxbu); - free(lubu); -{%- endif %} - -{%- if dims.nsbu > 0 %} - // set up soft bounds for u - int* idxsbu = malloc(NSBU * sizeof(int)); - {% for i in range(end=dims.nsbu) %} - idxsbu[{{ i }}] = {{ constraints.idxsbu[i] }}; - {%- endfor %} - double* lusbu = calloc(2*NSBU, sizeof(double)); - double* lsbu = lusbu; - double* usbu = lusbu + NSBU; - {% for i in range(end=dims.nsbu) %} - {%- if constraints.lsbu[i] != 0 %} - lsbu[{{ i }}] = {{ constraints.lsbu[i] }}; - {%- endif %} - {%- if constraints.usbu[i] != 0 %} - usbu[{{ i }}] = {{ constraints.usbu[i] }}; - {%- endif %} - {%- endfor %} - for (int i = 0; i < N; i++) - { - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "idxsbu", idxsbu); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "lsbu", lsbu); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "usbu", usbu); - } - free(idxsbu); - free(lusbu); -{%- endif %} - -{% if dims.nsg > 0 %} - // set up soft bounds for general linear constraints - int* idxsg = malloc(NSG * sizeof(int)); - {% for i in range(end=dims.nsg) %} - idxsg[{{ i }}] = {{ constraints.idxsg[i] }}; - {%- endfor %} - double* lusg = calloc(2*NSG, sizeof(double)); - double* lsg = lusg; - double* usg = lusg + NSG; - {% for i in range(end=dims.nsg) %} - {%- if constraints.lsg[i] != 0 %} - lsg[{{ i }}] = {{ constraints.lsg[i] }}; - {%- endif %} - {%- if constraints.usg[i] != 0 %} - usg[{{ i }}] = {{ constraints.usg[i] }}; - {%- endif %} - {%- endfor %} - - for (int i = 0; i < N; i++) - { - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "idxsg", idxsg); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "lsg", lsg); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "usg", usg); - } - free(idxsg); - free(lusg); -{%- endif %} - -{% if dims.nsh > 0 %} - // set up soft bounds for nonlinear constraints - int* idxsh = malloc(NSH * sizeof(int)); - {% for i in range(end=dims.nsh) %} - idxsh[{{ i }}] = {{ constraints.idxsh[i] }}; - {%- endfor %} - double* lush = calloc(2*NSH, sizeof(double)); - double* lsh = lush; - double* ush = lush + NSH; - {% for i in range(end=dims.nsh) %} - {%- if constraints.lsh[i] != 0 %} - lsh[{{ i }}] = {{ constraints.lsh[i] }}; - {%- endif %} - {%- if constraints.ush[i] != 0 %} - ush[{{ i }}] = {{ constraints.ush[i] }}; - {%- endif %} - {%- endfor %} - - for (int i = 0; i < N; i++) - { - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "idxsh", idxsh); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "lsh", lsh); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "ush", ush); - } - free(idxsh); - free(lush); -{%- endif %} - -{% if dims.nsphi > 0 %} - // set up soft bounds for convex-over-nonlinear constraints - int* idxsphi = malloc(NSPHI * sizeof(int)); - {% for i in range(end=dims.nsphi) %} - idxsphi[{{ i }}] = {{ constraints.idxsphi[i] }}; - {%- endfor %} - double* lusphi = calloc(2*NSPHI, sizeof(double)); - double* lsphi = lusphi; - double* usphi = lusphi + NSPHI; - {% for i in range(end=dims.nsphi) %} - {%- if constraints.lsphi[i] != 0 %} - lsphi[{{ i }}] = {{ constraints.lsphi[i] }}; - {%- endif %} - {%- if constraints.usphi[i] != 0 %} - usphi[{{ i }}] = {{ constraints.usphi[i] }}; - {%- endif %} - {%- endfor %} - - for (int i = 0; i < N; i++) - { - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "idxsphi", idxsphi); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "lsphi", lsphi); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "usphi", usphi); - } - free(idxsphi); - free(lusphi); -{%- endif %} - -{% if dims.nbx > 0 %} - // x - int* idxbx = malloc(NBX * sizeof(int)); - {% for i in range(end=dims.nbx) %} - idxbx[{{ i }}] = {{ constraints.idxbx[i] }}; - {%- endfor %} - double* lubx = calloc(2*NBX, sizeof(double)); - double* lbx = lubx; - double* ubx = lubx + NBX; - {% for i in range(end=dims.nbx) %} - {%- if constraints.lbx[i] != 0 %} - lbx[{{ i }}] = {{ constraints.lbx[i] }}; - {%- endif %} - {%- if constraints.ubx[i] != 0 %} - ubx[{{ i }}] = {{ constraints.ubx[i] }}; - {%- endif %} - {%- endfor %} - - for (int i = 1; i < N; i++) - { - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "idxbx", idxbx); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "lbx", lbx); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "ubx", ubx); - } - free(idxbx); - free(lubx); -{%- endif %} - -{% if dims.ng > 0 %} - // set up general constraints for stage 0 to N-1 - double* D = calloc(NG*NU, sizeof(double)); - double* C = calloc(NG*NX, sizeof(double)); - double* lug = calloc(2*NG, sizeof(double)); - double* lg = lug; - double* ug = lug + NG; - - {% for j in range(end=dims.ng) -%} - {% for k in range(end=dims.nu) %} - {%- if constraints.D[j][k] != 0 %} - D[{{ j }}+NG * {{ k }}] = {{ constraints.D[j][k] }}; - {%- endif %} - {%- endfor %} - {%- endfor %} - - {% for j in range(end=dims.ng) -%} - {% for k in range(end=dims.nx) %} - {%- if constraints.C[j][k] != 0 %} - C[{{ j }}+NG * {{ k }}] = {{ constraints.C[j][k] }}; - {%- endif %} - {%- endfor %} - {%- endfor %} - - {% for i in range(end=dims.ng) %} - {%- if constraints.lg[i] != 0 %} - lg[{{ i }}] = {{ constraints.lg[i] }}; - {%- endif %} - {%- endfor %} - - {% for i in range(end=dims.ng) %} - {%- if constraints.ug[i] != 0 %} - ug[{{ i }}] = {{ constraints.ug[i] }}; - {%- endif %} - {%- endfor %} - - for (int i = 0; i < N; i++) - { - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "D", D); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "C", C); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "lg", lg); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "ug", ug); - } - free(D); - free(C); - free(lug); -{%- endif %} - -{% if dims.nh > 0 %} - // set up nonlinear constraints for stage 0 to N-1 - double* luh = calloc(2*NH, sizeof(double)); - double* lh = luh; - double* uh = luh + NH; - - {% for i in range(end=dims.nh) %} - {%- if constraints.lh[i] != 0 %} - lh[{{ i }}] = {{ constraints.lh[i] }}; - {%- endif %} - {%- endfor %} - - {% for i in range(end=dims.nh) %} - {%- if constraints.uh[i] != 0 %} - uh[{{ i }}] = {{ constraints.uh[i] }}; - {%- endif %} - {%- endfor %} - - for (int i = 0; i < N; i++) - { - // nonlinear constraints for stages 0 to N-1 - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "nl_constr_h_fun_jac", - &capsule->nl_constr_h_fun_jac[i]); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "nl_constr_h_fun", - &capsule->nl_constr_h_fun[i]); - {% if solver_options.hessian_approx == "EXACT" %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, - "nl_constr_h_fun_jac_hess", &capsule->nl_constr_h_fun_jac_hess[i]); - {% endif %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "lh", lh); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "uh", uh); - } - free(luh); -{%- endif %} - -{% if dims.nphi > 0 and constraints.constr_type == "BGP" %} - // set up convex-over-nonlinear constraints for stage 0 to N-1 - double* luphi = calloc(2*NPHI, sizeof(double)); - double* lphi = luphi; - double* uphi = luphi + NPHI; - {% for i in range(end=dims.nphi) %} - {%- if constraints.lphi[i] != 0 %} - lphi[{{ i }}] = {{ constraints.lphi[i] }}; - {%- endif %} - {%- endfor %} - - {% for i in range(end=dims.nphi) %} - {%- if constraints.uphi[i] != 0 %} - uphi[{{ i }}] = {{ constraints.uphi[i] }}; - {%- endif %} - {%- endfor %} - - for (int i = 0; i < N; i++) - { - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, - "nl_constr_phi_o_r_fun_phi_jac_ux_z_phi_hess_r_jac_ux", &capsule->phi_constraint[i]); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "lphi", lphi); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "uphi", uphi); - } - free(luphi); -{%- endif %} - - /* terminal constraints */ -{% if dims.nbx_e > 0 %} - // set up bounds for last stage - // x - int* idxbx_e = malloc(NBXN * sizeof(int)); - {% for i in range(end=dims.nbx_e) %} - idxbx_e[{{ i }}] = {{ constraints.idxbx_e[i] }}; - {%- endfor %} - double* lubx_e = calloc(2*NBXN, sizeof(double)); - double* lbx_e = lubx_e; - double* ubx_e = lubx_e + NBXN; - {% for i in range(end=dims.nbx_e) %} - {%- if constraints.lbx_e[i] != 0 %} - lbx_e[{{ i }}] = {{ constraints.lbx_e[i] }}; - {%- endif %} - {%- if constraints.ubx_e[i] != 0 %} - ubx_e[{{ i }}] = {{ constraints.ubx_e[i] }}; - {%- endif %} - {%- endfor %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "idxbx", idxbx_e); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lbx", lbx_e); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "ubx", ubx_e); - free(idxbx_e); - free(lubx_e); -{%- endif %} - -{% if dims.nsg_e > 0 %} - // set up soft bounds for general linear constraints - int* idxsg_e = calloc(NSGN, sizeof(int)); - {% for i in range(end=dims.nsg_e) %} - idxsg_e[{{ i }}] = {{ constraints.idxsg_e[i] }}; - {%- endfor %} - double* lusg_e = calloc(2*NSGN, sizeof(double)); - double* lsg_e = lusg_e; - double* usg_e = lusg_e + NSGN; - {% for i in range(end=dims.nsg_e) %} - {%- if constraints.lsg_e[i] != 0 %} - lsg_e[{{ i }}] = {{ constraints.lsg_e[i] }}; - {%- endif %} - {%- if constraints.usg_e[i] != 0 %} - usg_e[{{ i }}] = {{ constraints.usg_e[i] }}; - {%- endif %} - {%- endfor %} - - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "idxsg", idxsg_e); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lsg", lsg_e); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "usg", usg_e); - free(idxsg_e); - free(lusg_e); -{%- endif %} - -{% if dims.nsh_e > 0 %} - // set up soft bounds for nonlinear constraints - int* idxsh_e = malloc(NSHN * sizeof(int)); - {% for i in range(end=dims.nsh_e) %} - idxsh_e[{{ i }}] = {{ constraints.idxsh_e[i] }}; - {%- endfor %} - double* lush_e = calloc(2*NSHN, sizeof(double)); - double* lsh_e = lush_e; - double* ush_e = lush_e + NSHN; - {% for i in range(end=dims.nsh_e) %} - {%- if constraints.lsh_e[i] != 0 %} - lsh_e[{{ i }}] = {{ constraints.lsh_e[i] }}; - {%- endif %} - {%- if constraints.ush_e[i] != 0 %} - ush_e[{{ i }}] = {{ constraints.ush_e[i] }}; - {%- endif %} - {%- endfor %} - - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "idxsh", idxsh_e); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lsh", lsh_e); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "ush", ush_e); - free(idxsh_e); - free(lush_e); -{%- endif %} - -{% if dims.nsphi_e > 0 %} - // set up soft bounds for convex-over-nonlinear constraints - int* idxsphi_e = malloc(NSPHIN * sizeof(int)); - {% for i in range(end=dims.nsphi_e) %} - idxsphi_e[{{ i }}] = {{ constraints.idxsphi_e[i] }}; - {%- endfor %} - double* lusphi_e = calloc(2*NSPHIN, sizeof(double)); - double* lsphi_e = lusphi_e; - double* usphi_e = lusphi_e + NSPHIN; - {% for i in range(end=dims.nsphi_e) %} - {%- if constraints.lsphi_e[i] != 0 %} - lsphi_e[{{ i }}] = {{ constraints.lsphi_e[i] }}; - {%- endif %} - {%- if constraints.usphi_e[i] != 0 %} - usphi_e[{{ i }}] = {{ constraints.usphi_e[i] }}; - {%- endif %} - {%- endfor %} - - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "idxsphi", idxsphi_e); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lsphi", lsphi_e); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "usphi", usphi_e); - free(idxsphi_e); - free(lusphi_e); -{%- endif %} - -{% if dims.nsbx_e > 0 %} - // soft bounds on x - int* idxsbx_e = malloc(NSBXN * sizeof(int)); - {% for i in range(end=dims.nsbx_e) %} - idxsbx_e[{{ i }}] = {{ constraints.idxsbx_e[i] }}; - {%- endfor %} - double* lusbx_e = calloc(2*NSBXN, sizeof(double)); - double* lsbx_e = lusbx_e; - double* usbx_e = lusbx_e + NSBXN; - {% for i in range(end=dims.nsbx_e) %} - {%- if constraints.lsbx_e[i] != 0 %} - lsbx_e[{{ i }}] = {{ constraints.lsbx_e[i] }}; - {%- endif %} - {%- if constraints.usbx_e[i] != 0 %} - usbx_e[{{ i }}] = {{ constraints.usbx_e[i] }}; - {%- endif %} - {%- endfor %} - - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "idxsbx", idxsbx_e); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lsbx", lsbx_e); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "usbx", usbx_e); - free(idxsbx_e); - free(lusbx_e); -{% endif %} - -{% if dims.ng_e > 0 %} - // set up general constraints for last stage - double* C_e = calloc(NGN*NX, sizeof(double)); - double* lug_e = calloc(2*NGN, sizeof(double)); - double* lg_e = lug_e; - double* ug_e = lug_e + NGN; - - {% for j in range(end=dims.ng_e) %} - {%- for k in range(end=dims.nx) %} - {%- if constraints.C_e[j][k] != 0 %} - C_e[{{ j }}+NGN * {{ k }}] = {{ constraints.C_e[j][k] }}; - {%- endif %} - {%- endfor %} - {%- endfor %} - - {% for i in range(end=dims.ng_e) %} - {%- if constraints.lg_e[i] != 0 %} - lg_e[{{ i }}] = {{ constraints.lg_e[i] }}; - {%- endif %} - {%- if constraints.ug_e[i] != 0 %} - ug_e[{{ i }}] = {{ constraints.ug_e[i] }}; - {%- endif %} - {%- endfor %} - - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "C", C_e); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lg", lg_e); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "ug", ug_e); - free(C_e); - free(lug_e); -{%- endif %} - -{% if dims.nh_e > 0 %} - // set up nonlinear constraints for last stage - double* luh_e = calloc(2*NHN, sizeof(double)); - double* lh_e = luh_e; - double* uh_e = luh_e + NHN; - {% for i in range(end=dims.nh_e) %} - {%- if constraints.lh_e[i] != 0 %} - lh_e[{{ i }}] = {{ constraints.lh_e[i] }}; - {%- endif %} - {%- endfor %} - - {% for i in range(end=dims.nh_e) %} - {%- if constraints.uh_e[i] != 0 %} - uh_e[{{ i }}] = {{ constraints.uh_e[i] }}; - {%- endif %} - {%- endfor %} - - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "nl_constr_h_fun_jac", &capsule->nl_constr_h_e_fun_jac); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "nl_constr_h_fun", &capsule->nl_constr_h_e_fun); - {% if solver_options.hessian_approx == "EXACT" %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "nl_constr_h_fun_jac_hess", - &capsule->nl_constr_h_e_fun_jac_hess); - {% endif %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lh", lh_e); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "uh", uh_e); - free(luh_e); -{%- endif %} - -{% if dims.nphi_e > 0 and constraints.constr_type_e == "BGP" %} - // set up convex-over-nonlinear constraints for last stage - double* luphi_e = calloc(2*NPHIN, sizeof(double)); - double* lphi_e = luphi_e; - double* uphi_e = luphi_e + NPHIN; - {% for i in range(end=dims.nphi_e) %} - {%- if constraints.lphi_e[i] != 0 %} - lphi_e[{{ i }}] = {{ constraints.lphi_e[i] }}; - {%- endif %} - {%- if constraints.uphi_e[i] != 0 %} - uphi_e[{{ i }}] = {{ constraints.uphi_e[i] }}; - {%- endif %} - {%- endfor %} - - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lphi", lphi_e); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "uphi", uphi_e); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, - "nl_constr_phi_o_r_fun_phi_jac_ux_z_phi_hess_r_jac_ux", &capsule->phi_e_constraint); - free(luphi_e); -{% endif %} -} - - -/** - * Internal function for {{ model.name }}_acados_create: step 6 - */ -void {{ model.name }}_acados_create_6_set_opts({{ model.name }}_solver_capsule* capsule) -{ - const int N = capsule->nlp_solver_plan->N; - ocp_nlp_config* nlp_config = capsule->nlp_config; - void *nlp_opts = capsule->nlp_opts; - - /************************************************ - * opts - ************************************************/ - -{% if solver_options.hessian_approx == "EXACT" %} - int nlp_solver_exact_hessian = 1; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "exact_hess", &nlp_solver_exact_hessian); - - int exact_hess_dyn = {{ solver_options.exact_hess_dyn }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "exact_hess_dyn", &exact_hess_dyn); - - int exact_hess_cost = {{ solver_options.exact_hess_cost }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "exact_hess_cost", &exact_hess_cost); - - int exact_hess_constr = {{ solver_options.exact_hess_constr }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "exact_hess_constr", &exact_hess_constr); -{%- endif -%} - -{%- if solver_options.globalization == "FIXED_STEP" %} - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "globalization", "fixed_step"); -{%- elif solver_options.globalization == "MERIT_BACKTRACKING" %} - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "globalization", "merit_backtracking"); - - double alpha_min = {{ solver_options.alpha_min }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "alpha_min", &alpha_min); - - double alpha_reduction = {{ solver_options.alpha_reduction }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "alpha_reduction", &alpha_reduction); - - int line_search_use_sufficient_descent = {{ solver_options.line_search_use_sufficient_descent }}; - ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "line_search_use_sufficient_descent", &line_search_use_sufficient_descent); - - int globalization_use_SOC = {{ solver_options.globalization_use_SOC }}; - ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "globalization_use_SOC", &globalization_use_SOC); - - double eps_sufficient_descent = {{ solver_options.eps_sufficient_descent }}; - ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "eps_sufficient_descent", &eps_sufficient_descent); -{%- endif -%} - int full_step_dual = {{ solver_options.full_step_dual }}; - ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "full_step_dual", &full_step_dual); - -{%- if dims.nz > 0 %} - // TODO: these options are lower level -> should be encapsulated! maybe through hessian approx option. - bool output_z_val = true; - bool sens_algebraic_val = true; - - for (int i = 0; i < N; i++) - ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, i, "dynamics_output_z", &output_z_val); - for (int i = 0; i < N; i++) - ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, i, "dynamics_sens_algebraic", &sens_algebraic_val); -{%- endif %} - -{%- if solver_options.integrator_type != "DISCRETE" %} - - // set collocation type (relevant for implicit integrators) - sim_collocation_type collocation_type = {{ solver_options.collocation_type }}; - for (int i = 0; i < N; i++) - ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, i, "dynamics_collocation_type", &collocation_type); - - // set up sim_method_num_steps - {%- set all_equal = true %} - {%- set val = solver_options.sim_method_num_steps[0] %} - {%- for j in range(start=1, end=dims.N) %} - {%- if val != solver_options.sim_method_num_steps[j] %} - {%- set_global all_equal = false %} - {%- break %} - {%- endif %} - {%- endfor %} - - {%- if all_equal == true %} - // all sim_method_num_steps are identical - int sim_method_num_steps = {{ solver_options.sim_method_num_steps[0] }}; - for (int i = 0; i < N; i++) - ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, i, "dynamics_num_steps", &sim_method_num_steps); - {%- else %} - // sim_method_num_steps are different - int* sim_method_num_steps = malloc(N*sizeof(int)); - {%- for j in range(end=dims.N) %} - sim_method_num_steps[{{ j }}] = {{ solver_options.sim_method_num_steps[j] }}; - {%- endfor %} - - for (int i = 0; i < N; i++) - ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, i, "dynamics_num_steps", &sim_method_num_steps[i]); - free(sim_method_num_steps); - {%- endif %} - - // set up sim_method_num_stages - {%- set all_equal = true %} - {%- set val = solver_options.sim_method_num_stages[0] %} - {%- for j in range(start=1, end=dims.N) %} - {%- if val != solver_options.sim_method_num_stages[j] %} - {%- set_global all_equal = false %} - {%- break %} - {%- endif %} - {%- endfor %} - - {%- if all_equal == true %} - // all sim_method_num_stages are identical - int sim_method_num_stages = {{ solver_options.sim_method_num_stages[0] }}; - for (int i = 0; i < N; i++) - ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, i, "dynamics_num_stages", &sim_method_num_stages); - {%- else %} - int* sim_method_num_stages = malloc(N*sizeof(int)); - {%- for j in range(end=dims.N) %} - sim_method_num_stages[{{ j }}] = {{ solver_options.sim_method_num_stages[j] }}; - {%- endfor %} - - for (int i = 0; i < N; i++) - ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, i, "dynamics_num_stages", &sim_method_num_stages[i]); - free(sim_method_num_stages); - {%- endif %} - - int newton_iter_val = {{ solver_options.sim_method_newton_iter }}; - for (int i = 0; i < N; i++) - ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, i, "dynamics_newton_iter", &newton_iter_val); - - - // set up sim_method_jac_reuse - {%- set all_equal = true %} - {%- set val = solver_options.sim_method_jac_reuse[0] %} - {%- for j in range(start=1, end=dims.N) %} - {%- if val != solver_options.sim_method_jac_reuse[j] %} - {%- set_global all_equal = false %} - {%- break %} - {%- endif %} - {%- endfor %} - {%- if all_equal == true %} - bool tmp_bool = (bool) {{ solver_options.sim_method_jac_reuse[0] }}; - for (int i = 0; i < N; i++) - ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, i, "dynamics_jac_reuse", &tmp_bool); - {%- else %} - bool* sim_method_jac_reuse = malloc(N*sizeof(bool)); - {%- for j in range(end=dims.N) %} - sim_method_jac_reuse[{{ j }}] = (bool){{ solver_options.sim_method_jac_reuse[j] }}; - {%- endfor %} - - for (int i = 0; i < N; i++) - ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, i, "dynamics_jac_reuse", &sim_method_jac_reuse[i]); - free(sim_method_jac_reuse); - {%- endif %} - -{%- endif %} - - double nlp_solver_step_length = {{ solver_options.nlp_solver_step_length }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "step_length", &nlp_solver_step_length); - - {%- if solver_options.nlp_solver_warm_start_first_qp %} - int nlp_solver_warm_start_first_qp = {{ solver_options.nlp_solver_warm_start_first_qp }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "warm_start_first_qp", &nlp_solver_warm_start_first_qp); - {%- endif %} - - double levenberg_marquardt = {{ solver_options.levenberg_marquardt }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "levenberg_marquardt", &levenberg_marquardt); - - /* options QP solver */ -{%- if solver_options.qp_solver is starting_with("PARTIAL_CONDENSING") %} - int qp_solver_cond_N; - - {% if solver_options.qp_solver_cond_N -%} - const int qp_solver_cond_N_ori = {{ solver_options.qp_solver_cond_N }}; - qp_solver_cond_N = N < qp_solver_cond_N_ori ? N : qp_solver_cond_N_ori; // use the minimum value here - {%- else %} - // NOTE: there is no condensing happening here! - qp_solver_cond_N = N; - {%- endif %} - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "qp_cond_N", &qp_solver_cond_N); -{%- endif %} - - int nlp_solver_ext_qp_res = {{ solver_options.nlp_solver_ext_qp_res }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "ext_qp_res", &nlp_solver_ext_qp_res); - -{%- if solver_options.qp_solver is containing("HPIPM") %} - // set HPIPM mode: should be done before setting other QP solver options - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "qp_hpipm_mode", "{{ solver_options.hpipm_mode }}"); -{%- endif %} - -{% if solver_options.nlp_solver_type == "SQP" %} - // set SQP specific options - double nlp_solver_tol_stat = {{ solver_options.nlp_solver_tol_stat }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "tol_stat", &nlp_solver_tol_stat); - - double nlp_solver_tol_eq = {{ solver_options.nlp_solver_tol_eq }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "tol_eq", &nlp_solver_tol_eq); - - double nlp_solver_tol_ineq = {{ solver_options.nlp_solver_tol_ineq }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "tol_ineq", &nlp_solver_tol_ineq); - - double nlp_solver_tol_comp = {{ solver_options.nlp_solver_tol_comp }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "tol_comp", &nlp_solver_tol_comp); - - int nlp_solver_max_iter = {{ solver_options.nlp_solver_max_iter }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "max_iter", &nlp_solver_max_iter); - - int initialize_t_slacks = {{ solver_options.initialize_t_slacks }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "initialize_t_slacks", &initialize_t_slacks); -{%- endif %} - - int qp_solver_iter_max = {{ solver_options.qp_solver_iter_max }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "qp_iter_max", &qp_solver_iter_max); - -{# NOTE: qp_solver tolerances must be set after NLP ones, since the setter for NLP tolerances sets the QP tolerances to the sam values. #} - {%- if solver_options.qp_solver_tol_stat %} - double qp_solver_tol_stat = {{ solver_options.qp_solver_tol_stat }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "qp_tol_stat", &qp_solver_tol_stat); - {%- endif -%} - - {%- if solver_options.qp_solver_tol_eq %} - double qp_solver_tol_eq = {{ solver_options.qp_solver_tol_eq }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "qp_tol_eq", &qp_solver_tol_eq); - {%- endif -%} - - {%- if solver_options.qp_solver_tol_ineq %} - double qp_solver_tol_ineq = {{ solver_options.qp_solver_tol_ineq }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "qp_tol_ineq", &qp_solver_tol_ineq); - {%- endif -%} - - {%- if solver_options.qp_solver_tol_comp %} - double qp_solver_tol_comp = {{ solver_options.qp_solver_tol_comp }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "qp_tol_comp", &qp_solver_tol_comp); - {%- endif -%} - - {%- if solver_options.qp_solver_warm_start %} - int qp_solver_warm_start = {{ solver_options.qp_solver_warm_start }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "qp_warm_start", &qp_solver_warm_start); - {%- endif -%} - - int print_level = {{ solver_options.print_level }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "print_level", &print_level); - -{%- if solver_options.qp_solver is containing('PARTIAL_CONDENSING') %} - int qp_solver_cond_ric_alg = {{ solver_options.qp_solver_cond_ric_alg }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "qp_cond_ric_alg", &qp_solver_cond_ric_alg); -{% endif %} - -{%- if solver_options.qp_solver == 'PARTIAL_CONDENSING_HPIPM' %} - int qp_solver_ric_alg = {{ solver_options.qp_solver_ric_alg }}; - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "qp_ric_alg", &qp_solver_ric_alg); -{% endif %} - - int ext_cost_num_hess = {{ solver_options.ext_cost_num_hess }}; -{%- if cost.cost_type == "EXTERNAL" %} - for (int i = 0; i < N; i++) - { - ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, i, "cost_numerical_hessian", &ext_cost_num_hess); - } -{%- endif %} -{%- if cost.cost_type_e == "EXTERNAL" %} - ocp_nlp_solver_opts_set_at_stage(nlp_config, nlp_opts, N, "cost_numerical_hessian", &ext_cost_num_hess); -{%- endif %} -} - - -/** - * Internal function for {{ model.name }}_acados_create: step 7 - */ -void {{ model.name }}_acados_create_7_set_nlp_out({{ model.name }}_solver_capsule* capsule) -{ - const int N = capsule->nlp_solver_plan->N; - ocp_nlp_config* nlp_config = capsule->nlp_config; - ocp_nlp_dims* nlp_dims = capsule->nlp_dims; - ocp_nlp_out* nlp_out = capsule->nlp_out; - - // initialize primal solution - double* xu0 = calloc(NX+NU, sizeof(double)); - double* x0 = xu0; -{% if dims.nbx_0 == dims.nx %} - // initialize with x0 - {% for item in constraints.lbx_0 %} - {%- if item != 0 %} - x0[{{ loop.index0 }}] = {{ item }}; - {%- endif %} - {%- endfor %} -{% else %} - // initialize with zeros -{%- endif %} - - double* u0 = xu0 + NX; - - for (int i = 0; i < N; i++) - { - // x0 - ocp_nlp_out_set(nlp_config, nlp_dims, nlp_out, i, "x", x0); - // u0 - ocp_nlp_out_set(nlp_config, nlp_dims, nlp_out, i, "u", u0); - } - ocp_nlp_out_set(nlp_config, nlp_dims, nlp_out, N, "x", x0); - free(xu0); -} - - -/** - * Internal function for {{ model.name }}_acados_create: step 8 - */ -//void {{ model.name }}_acados_create_8_create_solver({{ model.name }}_solver_capsule* capsule) -//{ -// capsule->nlp_solver = ocp_nlp_solver_create(capsule->nlp_config, capsule->nlp_dims, capsule->nlp_opts); -//} - -/** - * Internal function for {{ model.name }}_acados_create: step 9 - */ -int {{ model.name }}_acados_create_9_precompute({{ model.name }}_solver_capsule* capsule) { - int status = ocp_nlp_precompute(capsule->nlp_solver, capsule->nlp_in, capsule->nlp_out); - - if (status != ACADOS_SUCCESS) { - printf("\nocp_nlp_precompute failed!\n\n"); - exit(1); - } - - return status; -} - - -int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_capsule* capsule, int N, double* new_time_steps) -{ - // If N does not match the number of shooting intervals used for code generation, new_time_steps must be given. - if (N != {{ model.name | upper }}_N && !new_time_steps) { - fprintf(stderr, "{{ model.name }}_acados_create_with_discretization: new_time_steps is NULL " \ - "but the number of shooting intervals (= %d) differs from the number of " \ - "shooting intervals (= %d) during code generation! Please provide a new vector of time_stamps!\n", \ - N, {{ model.name | upper }}_N); - return 1; - } - - // number of expected runtime parameters - capsule->nlp_np = NP; - - // 1) create and set nlp_solver_plan; create nlp_config - capsule->nlp_solver_plan = ocp_nlp_plan_create(N); - {{ model.name }}_acados_create_1_set_plan(capsule->nlp_solver_plan, N); - capsule->nlp_config = ocp_nlp_config_create(*capsule->nlp_solver_plan); - - // 3) create and set dimensions - capsule->nlp_dims = {{ model.name }}_acados_create_2_create_and_set_dimensions(capsule); - {{ model.name }}_acados_create_3_create_and_set_functions(capsule); - - // 4) set default parameters in functions - {{ model.name }}_acados_create_4_set_default_parameters(capsule); - - // 5) create and set nlp_in - capsule->nlp_in = ocp_nlp_in_create(capsule->nlp_config, capsule->nlp_dims); - {{ model.name }}_acados_create_5_set_nlp_in(capsule, N, new_time_steps); - - // 6) create and set nlp_opts - capsule->nlp_opts = ocp_nlp_solver_opts_create(capsule->nlp_config, capsule->nlp_dims); - {{ model.name }}_acados_create_6_set_opts(capsule); - - // 7) create and set nlp_out - // 7.1) nlp_out - capsule->nlp_out = ocp_nlp_out_create(capsule->nlp_config, capsule->nlp_dims); - // 7.2) sens_out - capsule->sens_out = ocp_nlp_out_create(capsule->nlp_config, capsule->nlp_dims); - {{ model.name }}_acados_create_7_set_nlp_out(capsule); - - // 8) create solver - capsule->nlp_solver = ocp_nlp_solver_create(capsule->nlp_config, capsule->nlp_dims, capsule->nlp_opts); - //{{ model.name }}_acados_create_8_create_solver(capsule); - - // 9) do precomputations - int status = {{ model.name }}_acados_create_9_precompute(capsule); - - {%- if custom_update_filename != "" %} - // Initialize custom update function - custom_update_init_function(capsule); - {%- endif %} - - return status; -} - -/** - * This function is for updating an already initialized solver with a different number of qp_cond_N. It is useful for code reuse after code export. - */ -int {{ model.name }}_acados_update_qp_solver_cond_N({{ model.name }}_solver_capsule* capsule, int qp_solver_cond_N) -{ -{%- if solver_options.qp_solver is starting_with("PARTIAL_CONDENSING") %} - // 1) destroy solver - ocp_nlp_solver_destroy(capsule->nlp_solver); - - // 2) set new value for "qp_cond_N" - const int N = capsule->nlp_solver_plan->N; - if(qp_solver_cond_N > N) - printf("Warning: qp_solver_cond_N = %d > N = %d\n", qp_solver_cond_N, N); - ocp_nlp_solver_opts_set(capsule->nlp_config, capsule->nlp_opts, "qp_cond_N", &qp_solver_cond_N); - - // 3) continue with the remaining steps from {{ model.name }}_acados_create_with_discretization(...): - // -> 8) create solver - capsule->nlp_solver = ocp_nlp_solver_create(capsule->nlp_config, capsule->nlp_dims, capsule->nlp_opts); - - // -> 9) do precomputations - int status = {{ model.name }}_acados_create_9_precompute(capsule); - return status; -{%- else %} - printf("\nacados_update_qp_solver_cond_N() failed, since no partial condensing solver is used!\n\n"); - // Todo: what is an adequate behavior here? - exit(1); - return -1; -{%- endif %} -} - - -int {{ model.name }}_acados_reset({{ model.name }}_solver_capsule* capsule, int reset_qp_solver_mem) -{ - - // set initialization to all zeros -{# TODO: use guess values / initial state value from json instead?! #} - const int N = capsule->nlp_solver_plan->N; - ocp_nlp_config* nlp_config = capsule->nlp_config; - ocp_nlp_dims* nlp_dims = capsule->nlp_dims; - ocp_nlp_out* nlp_out = capsule->nlp_out; - ocp_nlp_in* nlp_in = capsule->nlp_in; - ocp_nlp_solver* nlp_solver = capsule->nlp_solver; - - double* buffer = calloc(NX+NU+NZ+2*NS+2*NSN+NBX+NBU+NG+NH+NPHI+NBX0+NBXN+NHN+NPHIN+NGN, sizeof(double)); - - for(int i=0; i reset memory - int qp_status; - ocp_nlp_get(capsule->nlp_config, capsule->nlp_solver, "qp_status", &qp_status); - if (reset_qp_solver_mem || (qp_status == 3)) - { - // printf("\nin reset qp_status %d -> resetting QP memory\n", qp_status); - ocp_nlp_solver_reset_qp_memory(nlp_solver, nlp_in, nlp_out); - } -{%- endif %} - - free(buffer); - return 0; -} - - - - -int {{ model.name }}_acados_update_params({{ model.name }}_solver_capsule* capsule, int stage, double *p, int np) -{ - int solver_status = 0; - - int casadi_np = {{ dims.np }}; - if (casadi_np != np) { - printf("acados_update_params: trying to set %i parameters for external functions." - " External function has %i parameters. Exiting.\n", np, casadi_np); - exit(1); - } - - const int N = capsule->nlp_solver_plan->N; - if (stage < N && stage >= 0) - { - {%- if solver_options.integrator_type == "IRK" %} - capsule->impl_dae_fun[stage].set_param(capsule->impl_dae_fun+stage, p); - capsule->impl_dae_fun_jac_x_xdot_z[stage].set_param(capsule->impl_dae_fun_jac_x_xdot_z+stage, p); - capsule->impl_dae_jac_x_xdot_u_z[stage].set_param(capsule->impl_dae_jac_x_xdot_u_z+stage, p); - - {%- if solver_options.hessian_approx == "EXACT" %} - capsule->impl_dae_hess[stage].set_param(capsule->impl_dae_hess+stage, p); - {%- endif %} - {% elif solver_options.integrator_type == "LIFTED_IRK" %} - capsule->impl_dae_fun[stage].set_param(capsule->impl_dae_fun+stage, p); - capsule->impl_dae_fun_jac_x_xdot_u[stage].set_param(capsule->impl_dae_fun_jac_x_xdot_u+stage, p); - {% elif solver_options.integrator_type == "ERK" %} - capsule->forw_vde_casadi[stage].set_param(capsule->forw_vde_casadi+stage, p); - capsule->expl_ode_fun[stage].set_param(capsule->expl_ode_fun+stage, p); - - {%- if solver_options.hessian_approx == "EXACT" %} - capsule->hess_vde_casadi[stage].set_param(capsule->hess_vde_casadi+stage, p); - {%- endif %} - {% elif solver_options.integrator_type == "GNSF" %} - {% if model.gnsf.purely_linear != 1 %} - capsule->gnsf_phi_fun[stage].set_param(capsule->gnsf_phi_fun+stage, p); - capsule->gnsf_phi_fun_jac_y[stage].set_param(capsule->gnsf_phi_fun_jac_y+stage, p); - capsule->gnsf_phi_jac_y_uhat[stage].set_param(capsule->gnsf_phi_jac_y_uhat+stage, p); - {% if model.gnsf.nontrivial_f_LO == 1 %} - capsule->gnsf_f_lo_jac_x1_x1dot_u_z[stage].set_param(capsule->gnsf_f_lo_jac_x1_x1dot_u_z+stage, p); - {%- endif %} - {%- endif %} - {% elif solver_options.integrator_type == "DISCRETE" %} - capsule->discr_dyn_phi_fun[stage].set_param(capsule->discr_dyn_phi_fun+stage, p); - capsule->discr_dyn_phi_fun_jac_ut_xt[stage].set_param(capsule->discr_dyn_phi_fun_jac_ut_xt+stage, p); - {%- if solver_options.hessian_approx == "EXACT" %} - capsule->discr_dyn_phi_fun_jac_ut_xt_hess[stage].set_param(capsule->discr_dyn_phi_fun_jac_ut_xt_hess+stage, p); - {% endif %} - {%- endif %}{# integrator_type #} - - // constraints - {% if constraints.constr_type == "BGP" %} - capsule->phi_constraint[stage].set_param(capsule->phi_constraint+stage, p); - {% elif constraints.constr_type == "BGH" and dims.nh > 0 %} - capsule->nl_constr_h_fun_jac[stage].set_param(capsule->nl_constr_h_fun_jac+stage, p); - capsule->nl_constr_h_fun[stage].set_param(capsule->nl_constr_h_fun+stage, p); - {%- if solver_options.hessian_approx == "EXACT" %} - capsule->nl_constr_h_fun_jac_hess[stage].set_param(capsule->nl_constr_h_fun_jac_hess+stage, p); - {%- endif %} - {%- endif %} - - // cost - if (stage == 0) - { - {%- if cost.cost_type_0 == "NONLINEAR_LS" %} - capsule->cost_y_0_fun.set_param(&capsule->cost_y_0_fun, p); - capsule->cost_y_0_fun_jac_ut_xt.set_param(&capsule->cost_y_0_fun_jac_ut_xt, p); - capsule->cost_y_0_hess.set_param(&capsule->cost_y_0_hess, p); - {%- elif cost.cost_type_0 == "CONVEX_OVER_NONLINEAR" %} - capsule->conl_cost_0_fun.set_param(&capsule->conl_cost_0_fun, p); - capsule->conl_cost_0_fun_jac_hess.set_param(&capsule->conl_cost_0_fun_jac_hess, p); - {%- elif cost.cost_type_0 == "EXTERNAL" %} - capsule->ext_cost_0_fun.set_param(&capsule->ext_cost_0_fun, p); - capsule->ext_cost_0_fun_jac.set_param(&capsule->ext_cost_0_fun_jac, p); - capsule->ext_cost_0_fun_jac_hess.set_param(&capsule->ext_cost_0_fun_jac_hess, p); - {% endif %} - } - else // 0 < stage < N - { - {%- if cost.cost_type == "NONLINEAR_LS" %} - capsule->cost_y_fun[stage-1].set_param(capsule->cost_y_fun+stage-1, p); - capsule->cost_y_fun_jac_ut_xt[stage-1].set_param(capsule->cost_y_fun_jac_ut_xt+stage-1, p); - capsule->cost_y_hess[stage-1].set_param(capsule->cost_y_hess+stage-1, p); - {%- elif cost.cost_type == "CONVEX_OVER_NONLINEAR" %} - capsule->conl_cost_fun[stage-1].set_param(capsule->conl_cost_fun+stage-1, p); - capsule->conl_cost_fun_jac_hess[stage-1].set_param(capsule->conl_cost_fun_jac_hess+stage-1, p); - {%- elif cost.cost_type == "EXTERNAL" %} - capsule->ext_cost_fun[stage-1].set_param(capsule->ext_cost_fun+stage-1, p); - capsule->ext_cost_fun_jac[stage-1].set_param(capsule->ext_cost_fun_jac+stage-1, p); - capsule->ext_cost_fun_jac_hess[stage-1].set_param(capsule->ext_cost_fun_jac_hess+stage-1, p); - {%- endif %} - } - } - - else // stage == N - { - // terminal shooting node has no dynamics - // cost - {%- if cost.cost_type_e == "NONLINEAR_LS" %} - capsule->cost_y_e_fun.set_param(&capsule->cost_y_e_fun, p); - capsule->cost_y_e_fun_jac_ut_xt.set_param(&capsule->cost_y_e_fun_jac_ut_xt, p); - capsule->cost_y_e_hess.set_param(&capsule->cost_y_e_hess, p); - {%- elif cost.cost_type_e == "CONVEX_OVER_NONLINEAR" %} - capsule->conl_cost_e_fun.set_param(&capsule->conl_cost_e_fun, p); - capsule->conl_cost_e_fun_jac_hess.set_param(&capsule->conl_cost_e_fun_jac_hess, p); - {%- elif cost.cost_type_e == "EXTERNAL" %} - capsule->ext_cost_e_fun.set_param(&capsule->ext_cost_e_fun, p); - capsule->ext_cost_e_fun_jac.set_param(&capsule->ext_cost_e_fun_jac, p); - capsule->ext_cost_e_fun_jac_hess.set_param(&capsule->ext_cost_e_fun_jac_hess, p); - {% endif %} - // constraints - {% if constraints.constr_type_e == "BGP" %} - capsule->phi_e_constraint.set_param(&capsule->phi_e_constraint, p); - {% elif constraints.constr_type_e == "BGH" and dims.nh_e > 0 %} - capsule->nl_constr_h_e_fun_jac.set_param(&capsule->nl_constr_h_e_fun_jac, p); - capsule->nl_constr_h_e_fun.set_param(&capsule->nl_constr_h_e_fun, p); - {%- if solver_options.hessian_approx == "EXACT" %} - capsule->nl_constr_h_e_fun_jac_hess.set_param(&capsule->nl_constr_h_e_fun_jac_hess, p); - {%- endif %} - {% endif %} - } - - return solver_status; -} - - -int {{ model.name }}_acados_update_params_sparse({{ model.name }}_solver_capsule * capsule, int stage, int *idx, double *p, int n_update) -{ - int solver_status = 0; - - int casadi_np = {{ dims.np }}; - if (casadi_np < n_update) { - printf("{{ model.name }}_acados_update_params_sparse: trying to set %d parameters for external functions." - " External function has %d parameters. Exiting.\n", n_update, casadi_np); - exit(1); - } - // for (int i = 0; i < n_update; i++) - // { - // if (idx[i] > casadi_np) { - // printf("{{ model.name }}_acados_update_params_sparse: attempt to set parameters with index %d, while" - // " external functions only has %d parameters. Exiting.\n", idx[i], casadi_np); - // exit(1); - // } - // printf("param %d value %e\n", idx[i], p[i]); - // } - -{%- if dims.np > 0 %} - const int N = capsule->nlp_solver_plan->N; - if (stage < N && stage >= 0) - { - {%- if solver_options.integrator_type == "IRK" %} - capsule->impl_dae_fun[stage].set_param_sparse(capsule->impl_dae_fun+stage, n_update, idx, p); - capsule->impl_dae_fun_jac_x_xdot_z[stage].set_param_sparse(capsule->impl_dae_fun_jac_x_xdot_z+stage, n_update, idx, p); - capsule->impl_dae_jac_x_xdot_u_z[stage].set_param_sparse(capsule->impl_dae_jac_x_xdot_u_z+stage, n_update, idx, p); - - {%- if solver_options.hessian_approx == "EXACT" %} - capsule->impl_dae_hess[stage].set_param_sparse(capsule->impl_dae_hess+stage, n_update, idx, p); - {%- endif %} - {% elif solver_options.integrator_type == "LIFTED_IRK" %} - capsule->impl_dae_fun[stage].set_param_sparse(capsule->impl_dae_fun+stage, n_update, idx, p); - capsule->impl_dae_fun_jac_x_xdot_u[stage].set_param_sparse(capsule->impl_dae_fun_jac_x_xdot_u+stage, n_update, idx, p); - {% elif solver_options.integrator_type == "ERK" %} - capsule->forw_vde_casadi[stage].set_param_sparse(capsule->forw_vde_casadi+stage, n_update, idx, p); - capsule->expl_ode_fun[stage].set_param_sparse(capsule->expl_ode_fun+stage, n_update, idx, p); - - {%- if solver_options.hessian_approx == "EXACT" %} - capsule->hess_vde_casadi[stage].set_param_sparse(capsule->hess_vde_casadi+stage, n_update, idx, p); - {%- endif %} - {% elif solver_options.integrator_type == "GNSF" %} - {% if model.gnsf.purely_linear != 1 %} - capsule->gnsf_phi_fun[stage].set_param_sparse(capsule->gnsf_phi_fun+stage, n_update, idx, p); - capsule->gnsf_phi_fun_jac_y[stage].set_param_sparse(capsule->gnsf_phi_fun_jac_y+stage, n_update, idx, p); - capsule->gnsf_phi_jac_y_uhat[stage].set_param_sparse(capsule->gnsf_phi_jac_y_uhat+stage, n_update, idx, p); - {% if model.gnsf.nontrivial_f_LO == 1 %} - capsule->gnsf_f_lo_jac_x1_x1dot_u_z[stage].set_param_sparse(capsule->gnsf_f_lo_jac_x1_x1dot_u_z+stage, n_update, idx, p); - {%- endif %} - {%- endif %} - {% elif solver_options.integrator_type == "DISCRETE" %} - capsule->discr_dyn_phi_fun[stage].set_param_sparse(capsule->discr_dyn_phi_fun+stage, n_update, idx, p); - capsule->discr_dyn_phi_fun_jac_ut_xt[stage].set_param_sparse(capsule->discr_dyn_phi_fun_jac_ut_xt+stage, n_update, idx, p); - {%- if solver_options.hessian_approx == "EXACT" %} - capsule->discr_dyn_phi_fun_jac_ut_xt_hess[stage].set_param_sparse(capsule->discr_dyn_phi_fun_jac_ut_xt_hess+stage, n_update, idx, p); - {% endif %} - {%- endif %}{# integrator_type #} - - // constraints - {% if constraints.constr_type == "BGP" %} - capsule->phi_constraint[stage].set_param_sparse(capsule->phi_constraint+stage, n_update, idx, p); - {% elif constraints.constr_type == "BGH" and dims.nh > 0 %} - capsule->nl_constr_h_fun_jac[stage].set_param_sparse(capsule->nl_constr_h_fun_jac+stage, n_update, idx, p); - capsule->nl_constr_h_fun[stage].set_param_sparse(capsule->nl_constr_h_fun+stage, n_update, idx, p); - {%- if solver_options.hessian_approx == "EXACT" %} - capsule->nl_constr_h_fun_jac_hess[stage].set_param_sparse(capsule->nl_constr_h_fun_jac_hess+stage, n_update, idx, p); - {%- endif %} - {%- endif %} - - // cost - if (stage == 0) - { - {%- if cost.cost_type_0 == "NONLINEAR_LS" %} - capsule->cost_y_0_fun.set_param_sparse(&capsule->cost_y_0_fun, n_update, idx, p); - capsule->cost_y_0_fun_jac_ut_xt.set_param_sparse(&capsule->cost_y_0_fun_jac_ut_xt, n_update, idx, p); - capsule->cost_y_0_hess.set_param_sparse(&capsule->cost_y_0_hess, n_update, idx, p); - {%- elif cost.cost_type_0 == "CONVEX_OVER_NONLINEAR" %} - capsule->conl_cost_0_fun.set_param_sparse(&capsule->conl_cost_0_fun, n_update, idx, p); - capsule->conl_cost_0_fun_jac_hess.set_param_sparse(&capsule->conl_cost_0_fun_jac_hess, n_update, idx, p); - {%- elif cost.cost_type_0 == "EXTERNAL" %} - capsule->ext_cost_0_fun.set_param_sparse(&capsule->ext_cost_0_fun, n_update, idx, p); - capsule->ext_cost_0_fun_jac.set_param_sparse(&capsule->ext_cost_0_fun_jac, n_update, idx, p); - capsule->ext_cost_0_fun_jac_hess.set_param_sparse(&capsule->ext_cost_0_fun_jac_hess, n_update, idx, p); - {% endif %} - } - else // 0 < stage < N - { - {%- if cost.cost_type == "NONLINEAR_LS" %} - capsule->cost_y_fun[stage-1].set_param_sparse(capsule->cost_y_fun+stage-1, n_update, idx, p); - capsule->cost_y_fun_jac_ut_xt[stage-1].set_param_sparse(capsule->cost_y_fun_jac_ut_xt+stage-1, n_update, idx, p); - capsule->cost_y_hess[stage-1].set_param_sparse(capsule->cost_y_hess+stage-1, n_update, idx, p); - {%- elif cost.cost_type == "CONVEX_OVER_NONLINEAR" %} - capsule->conl_cost_fun[stage-1].set_param_sparse(capsule->conl_cost_fun+stage-1, n_update, idx, p); - capsule->conl_cost_fun_jac_hess[stage-1].set_param_sparse(capsule->conl_cost_fun_jac_hess+stage-1, n_update, idx, p); - {%- elif cost.cost_type == "EXTERNAL" %} - capsule->ext_cost_fun[stage-1].set_param_sparse(capsule->ext_cost_fun+stage-1, n_update, idx, p); - capsule->ext_cost_fun_jac[stage-1].set_param_sparse(capsule->ext_cost_fun_jac+stage-1, n_update, idx, p); - capsule->ext_cost_fun_jac_hess[stage-1].set_param_sparse(capsule->ext_cost_fun_jac_hess+stage-1, n_update, idx, p); - {%- endif %} - } - } - - else // stage == N - { - // terminal shooting node has no dynamics - // cost - {%- if cost.cost_type_e == "NONLINEAR_LS" %} - capsule->cost_y_e_fun.set_param_sparse(&capsule->cost_y_e_fun, n_update, idx, p); - capsule->cost_y_e_fun_jac_ut_xt.set_param_sparse(&capsule->cost_y_e_fun_jac_ut_xt, n_update, idx, p); - capsule->cost_y_e_hess.set_param_sparse(&capsule->cost_y_e_hess, n_update, idx, p); - {%- elif cost.cost_type_e == "CONVEX_OVER_NONLINEAR" %} - capsule->conl_cost_e_fun.set_param_sparse(&capsule->conl_cost_e_fun, n_update, idx, p); - capsule->conl_cost_e_fun_jac_hess.set_param_sparse(&capsule->conl_cost_e_fun_jac_hess, n_update, idx, p); - {%- elif cost.cost_type_e == "EXTERNAL" %} - capsule->ext_cost_e_fun.set_param_sparse(&capsule->ext_cost_e_fun, n_update, idx, p); - capsule->ext_cost_e_fun_jac.set_param_sparse(&capsule->ext_cost_e_fun_jac, n_update, idx, p); - capsule->ext_cost_e_fun_jac_hess.set_param_sparse(&capsule->ext_cost_e_fun_jac_hess, n_update, idx, p); - {% endif %} - // constraints - {% if constraints.constr_type_e == "BGP" %} - capsule->phi_e_constraint.set_param_sparse(&capsule->phi_e_constraint, n_update, idx, p); - {% elif constraints.constr_type_e == "BGH" and dims.nh_e > 0 %} - capsule->nl_constr_h_e_fun_jac.set_param_sparse(&capsule->nl_constr_h_e_fun_jac, n_update, idx, p); - capsule->nl_constr_h_e_fun.set_param_sparse(&capsule->nl_constr_h_e_fun, n_update, idx, p); - {%- if solver_options.hessian_approx == "EXACT" %} - capsule->nl_constr_h_e_fun_jac_hess.set_param_sparse(&capsule->nl_constr_h_e_fun_jac_hess, n_update, idx, p); - {%- endif %} - {% endif %} - } -{% endif %}{# if dims.np #} - - return solver_status; -} - -int {{ model.name }}_acados_solve({{ model.name }}_solver_capsule* capsule) -{ - // solve NLP - int solver_status = ocp_nlp_solve(capsule->nlp_solver, capsule->nlp_in, capsule->nlp_out); - - return solver_status; -} - - -int {{ model.name }}_acados_free({{ model.name }}_solver_capsule* capsule) -{ - // before destroying, keep some info - const int N = capsule->nlp_solver_plan->N; - {%- if custom_update_filename != "" %} - custom_update_terminate_function(capsule); - {%- endif %} - // free memory - ocp_nlp_solver_opts_destroy(capsule->nlp_opts); - ocp_nlp_in_destroy(capsule->nlp_in); - ocp_nlp_out_destroy(capsule->nlp_out); - ocp_nlp_out_destroy(capsule->sens_out); - ocp_nlp_solver_destroy(capsule->nlp_solver); - ocp_nlp_dims_destroy(capsule->nlp_dims); - ocp_nlp_config_destroy(capsule->nlp_config); - ocp_nlp_plan_destroy(capsule->nlp_solver_plan); - - /* free external function */ - // dynamics -{%- if solver_options.integrator_type == "IRK" %} - for (int i = 0; i < N; i++) - { - external_function_param_{{ model.dyn_ext_fun_type }}_free(&capsule->impl_dae_fun[i]); - external_function_param_{{ model.dyn_ext_fun_type }}_free(&capsule->impl_dae_fun_jac_x_xdot_z[i]); - external_function_param_{{ model.dyn_ext_fun_type }}_free(&capsule->impl_dae_jac_x_xdot_u_z[i]); - {%- if solver_options.hessian_approx == "EXACT" %} - external_function_param_{{ model.dyn_ext_fun_type }}_free(&capsule->impl_dae_hess[i]); - {%- endif %} - } - free(capsule->impl_dae_fun); - free(capsule->impl_dae_fun_jac_x_xdot_z); - free(capsule->impl_dae_jac_x_xdot_u_z); - {%- if solver_options.hessian_approx == "EXACT" %} - free(capsule->impl_dae_hess); - {%- endif %} - -{%- elif solver_options.integrator_type == "LIFTED_IRK" %} - for (int i = 0; i < N; i++) - { - external_function_param_{{ model.dyn_ext_fun_type }}_free(&capsule->impl_dae_fun[i]); - external_function_param_{{ model.dyn_ext_fun_type }}_free(&capsule->impl_dae_fun_jac_x_xdot_u[i]); - } - free(capsule->impl_dae_fun); - free(capsule->impl_dae_fun_jac_x_xdot_u); - -{%- elif solver_options.integrator_type == "ERK" %} - for (int i = 0; i < N; i++) - { - external_function_param_casadi_free(&capsule->forw_vde_casadi[i]); - external_function_param_casadi_free(&capsule->expl_ode_fun[i]); - {%- if solver_options.hessian_approx == "EXACT" %} - external_function_param_casadi_free(&capsule->hess_vde_casadi[i]); - {%- endif %} - } - free(capsule->forw_vde_casadi); - free(capsule->expl_ode_fun); - {%- if solver_options.hessian_approx == "EXACT" %} - free(capsule->hess_vde_casadi); - {%- endif %} - -{%- elif solver_options.integrator_type == "GNSF" %} - for (int i = 0; i < N; i++) - { - {% if model.gnsf.purely_linear != 1 %} - external_function_param_casadi_free(&capsule->gnsf_phi_fun[i]); - external_function_param_casadi_free(&capsule->gnsf_phi_fun_jac_y[i]); - external_function_param_casadi_free(&capsule->gnsf_phi_jac_y_uhat[i]); - {% if model.gnsf.nontrivial_f_LO == 1 %} - external_function_param_casadi_free(&capsule->gnsf_f_lo_jac_x1_x1dot_u_z[i]); - {%- endif %} - {%- endif %} - external_function_param_casadi_free(&capsule->gnsf_get_matrices_fun[i]); - } - {% if model.gnsf.purely_linear != 1 %} - free(capsule->gnsf_phi_fun); - free(capsule->gnsf_phi_fun_jac_y); - free(capsule->gnsf_phi_jac_y_uhat); - {% if model.gnsf.nontrivial_f_LO == 1 %} - free(capsule->gnsf_f_lo_jac_x1_x1dot_u_z); - {%- endif %} - {%- endif %} - free(capsule->gnsf_get_matrices_fun); -{%- elif solver_options.integrator_type == "DISCRETE" %} - for (int i = 0; i < N; i++) - { - external_function_param_{{ model.dyn_ext_fun_type }}_free(&capsule->discr_dyn_phi_fun[i]); - external_function_param_{{ model.dyn_ext_fun_type }}_free(&capsule->discr_dyn_phi_fun_jac_ut_xt[i]); - {%- if solver_options.hessian_approx == "EXACT" %} - external_function_param_{{ model.dyn_ext_fun_type }}_free(&capsule->discr_dyn_phi_fun_jac_ut_xt_hess[i]); - {%- endif %} - } - free(capsule->discr_dyn_phi_fun); - free(capsule->discr_dyn_phi_fun_jac_ut_xt); - {%- if solver_options.hessian_approx == "EXACT" %} - free(capsule->discr_dyn_phi_fun_jac_ut_xt_hess); - {%- endif %} - -{%- endif %} - - // cost -{%- if cost.cost_type_0 == "NONLINEAR_LS" %} - external_function_param_casadi_free(&capsule->cost_y_0_fun); - external_function_param_casadi_free(&capsule->cost_y_0_fun_jac_ut_xt); - external_function_param_casadi_free(&capsule->cost_y_0_hess); -{%- elif cost.cost_type_0 == "CONVEX_OVER_NONLINEAR" %} - external_function_param_casadi_free(&capsule->conl_cost_0_fun); - external_function_param_casadi_free(&capsule->conl_cost_0_fun_jac_hess); -{%- elif cost.cost_type_0 == "EXTERNAL" %} - external_function_param_{{ cost.cost_ext_fun_type_0 }}_free(&capsule->ext_cost_0_fun); - external_function_param_{{ cost.cost_ext_fun_type_0 }}_free(&capsule->ext_cost_0_fun_jac); - external_function_param_{{ cost.cost_ext_fun_type_0 }}_free(&capsule->ext_cost_0_fun_jac_hess); -{%- endif %} -{%- if cost.cost_type == "NONLINEAR_LS" %} - for (int i = 0; i < N - 1; i++) - { - external_function_param_casadi_free(&capsule->cost_y_fun[i]); - external_function_param_casadi_free(&capsule->cost_y_fun_jac_ut_xt[i]); - external_function_param_casadi_free(&capsule->cost_y_hess[i]); - } - free(capsule->cost_y_fun); - free(capsule->cost_y_fun_jac_ut_xt); - free(capsule->cost_y_hess); -{%- elif cost.cost_type == "CONVEX_OVER_NONLINEAR" %} - for (int i = 0; i < N - 1; i++) - { - external_function_param_casadi_free(&capsule->conl_cost_fun[i]); - external_function_param_casadi_free(&capsule->conl_cost_fun_jac_hess[i]); - } - free(capsule->conl_cost_fun); - free(capsule->conl_cost_fun_jac_hess); -{%- elif cost.cost_type == "EXTERNAL" %} - for (int i = 0; i < N - 1; i++) - { - external_function_param_{{ cost.cost_ext_fun_type }}_free(&capsule->ext_cost_fun[i]); - external_function_param_{{ cost.cost_ext_fun_type }}_free(&capsule->ext_cost_fun_jac[i]); - external_function_param_{{ cost.cost_ext_fun_type }}_free(&capsule->ext_cost_fun_jac_hess[i]); - } - free(capsule->ext_cost_fun); - free(capsule->ext_cost_fun_jac); - free(capsule->ext_cost_fun_jac_hess); -{%- endif %} -{%- if cost.cost_type_e == "NONLINEAR_LS" %} - external_function_param_casadi_free(&capsule->cost_y_e_fun); - external_function_param_casadi_free(&capsule->cost_y_e_fun_jac_ut_xt); - external_function_param_casadi_free(&capsule->cost_y_e_hess); -{%- elif cost.cost_type_e == "CONVEX_OVER_NONLINEAR" %} - external_function_param_casadi_free(&capsule->conl_cost_e_fun); - external_function_param_casadi_free(&capsule->conl_cost_e_fun_jac_hess); -{%- elif cost.cost_type_e == "EXTERNAL" %} - external_function_param_{{ cost.cost_ext_fun_type_e }}_free(&capsule->ext_cost_e_fun); - external_function_param_{{ cost.cost_ext_fun_type_e }}_free(&capsule->ext_cost_e_fun_jac); - external_function_param_{{ cost.cost_ext_fun_type_e }}_free(&capsule->ext_cost_e_fun_jac_hess); -{%- endif %} - - // constraints -{%- if constraints.constr_type == "BGH" and dims.nh > 0 %} - for (int i = 0; i < N; i++) - { - external_function_param_casadi_free(&capsule->nl_constr_h_fun_jac[i]); - external_function_param_casadi_free(&capsule->nl_constr_h_fun[i]); - } - {%- if solver_options.hessian_approx == "EXACT" %} - for (int i = 0; i < N; i++) - { - external_function_param_casadi_free(&capsule->nl_constr_h_fun_jac_hess[i]); - } - {%- endif %} - free(capsule->nl_constr_h_fun_jac); - free(capsule->nl_constr_h_fun); - {%- if solver_options.hessian_approx == "EXACT" %} - free(capsule->nl_constr_h_fun_jac_hess); - {%- endif %} - -{%- elif constraints.constr_type == "BGP" and dims.nphi > 0 %} - for (int i = 0; i < N; i++) - { - external_function_param_casadi_free(&capsule->phi_constraint[i]); - } - free(capsule->phi_constraint); -{%- endif %} - -{%- if constraints.constr_type_e == "BGH" and dims.nh_e > 0 %} - external_function_param_casadi_free(&capsule->nl_constr_h_e_fun_jac); - external_function_param_casadi_free(&capsule->nl_constr_h_e_fun); -{%- if solver_options.hessian_approx == "EXACT" %} - external_function_param_casadi_free(&capsule->nl_constr_h_e_fun_jac_hess); -{%- endif %} -{%- elif constraints.constr_type_e == "BGP" and dims.nphi_e > 0 %} - external_function_param_casadi_free(&capsule->phi_e_constraint); -{%- endif %} - - return 0; -} - - -void {{ model.name }}_acados_print_stats({{ model.name }}_solver_capsule* capsule) -{ - int sqp_iter, stat_m, stat_n, tmp_int; - ocp_nlp_get(capsule->nlp_config, capsule->nlp_solver, "sqp_iter", &sqp_iter); - ocp_nlp_get(capsule->nlp_config, capsule->nlp_solver, "stat_n", &stat_n); - ocp_nlp_get(capsule->nlp_config, capsule->nlp_solver, "stat_m", &stat_m); - - {% set stat_n_max = 12 %} - double stat[{{ solver_options.nlp_solver_max_iter * stat_n_max }}]; - ocp_nlp_get(capsule->nlp_config, capsule->nlp_solver, "statistics", stat); - - int nrow = sqp_iter+1 < stat_m ? sqp_iter+1 : stat_m; - - printf("iter\tres_stat\tres_eq\t\tres_ineq\tres_comp\tqp_stat\tqp_iter\talpha"); - if (stat_n > 8) - printf("\t\tqp_res_stat\tqp_res_eq\tqp_res_ineq\tqp_res_comp"); - printf("\n"); - -{%- if solver_options.nlp_solver_type == "SQP" %} - - for (int i = 0; i < nrow; i++) - { - for (int j = 0; j < stat_n + 1; j++) - { - if (j == 0 || j == 5 || j == 6) - { - tmp_int = (int) stat[i + j * nrow]; - printf("%d\t", tmp_int); - } - else - { - printf("%e\t", stat[i + j * nrow]); - } - } - printf("\n"); - } -{% else %} - printf("iter\tqp_stat\tqp_iter\n"); - for (int i = 0; i < nrow; i++) - { - for (int j = 0; j < stat_n + 1; j++) - { - tmp_int = (int) stat[i + j * nrow]; - printf("%d\t", tmp_int); - } - printf("\n"); - } -{%- endif %} -} - -int {{ model.name }}_acados_custom_update({{ model.name }}_solver_capsule* capsule, double* data, int data_len) -{ -{%- if custom_update_filename == "" %} - (void)capsule; - (void)data; - (void)data_len; - printf("\ndummy function that can be called in between solver calls to update parameters or numerical data efficiently in C.\n"); - printf("nothing set yet..\n"); - return 1; -{% else %} - custom_update_function(capsule, data, data_len); -{%- endif %} -} - - - -ocp_nlp_in *{{ model.name }}_acados_get_nlp_in({{ model.name }}_solver_capsule* capsule) { return capsule->nlp_in; } -ocp_nlp_out *{{ model.name }}_acados_get_nlp_out({{ model.name }}_solver_capsule* capsule) { return capsule->nlp_out; } -ocp_nlp_out *{{ model.name }}_acados_get_sens_out({{ model.name }}_solver_capsule* capsule) { return capsule->sens_out; } -ocp_nlp_solver *{{ model.name }}_acados_get_nlp_solver({{ model.name }}_solver_capsule* capsule) { return capsule->nlp_solver; } -ocp_nlp_config *{{ model.name }}_acados_get_nlp_config({{ model.name }}_solver_capsule* capsule) { return capsule->nlp_config; } -void *{{ model.name }}_acados_get_nlp_opts({{ model.name }}_solver_capsule* capsule) { return capsule->nlp_opts; } -ocp_nlp_dims *{{ model.name }}_acados_get_nlp_dims({{ model.name }}_solver_capsule* capsule) { return capsule->nlp_dims; } -ocp_nlp_plan_t *{{ model.name }}_acados_get_nlp_plan({{ model.name }}_solver_capsule* capsule) { return capsule->nlp_solver_plan; } diff --git a/third_party/acados/acados_template/c_templates_tera/acados_solver.in.h b/third_party/acados/acados_template/c_templates_tera/acados_solver.in.h deleted file mode 100644 index 5cf38aa8c8..0000000000 --- a/third_party/acados/acados_template/c_templates_tera/acados_solver.in.h +++ /dev/null @@ -1,241 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - -#ifndef ACADOS_SOLVER_{{ model.name }}_H_ -#define ACADOS_SOLVER_{{ model.name }}_H_ - -#include "acados/utils/types.h" - -#include "acados_c/ocp_nlp_interface.h" -#include "acados_c/external_function_interface.h" - -#define {{ model.name | upper }}_NX {{ dims.nx }} -#define {{ model.name | upper }}_NZ {{ dims.nz }} -#define {{ model.name | upper }}_NU {{ dims.nu }} -#define {{ model.name | upper }}_NP {{ dims.np }} -#define {{ model.name | upper }}_NBX {{ dims.nbx }} -#define {{ model.name | upper }}_NBX0 {{ dims.nbx_0 }} -#define {{ model.name | upper }}_NBU {{ dims.nbu }} -#define {{ model.name | upper }}_NSBX {{ dims.nsbx }} -#define {{ model.name | upper }}_NSBU {{ dims.nsbu }} -#define {{ model.name | upper }}_NSH {{ dims.nsh }} -#define {{ model.name | upper }}_NSG {{ dims.nsg }} -#define {{ model.name | upper }}_NSPHI {{ dims.nsphi }} -#define {{ model.name | upper }}_NSHN {{ dims.nsh_e }} -#define {{ model.name | upper }}_NSGN {{ dims.nsg_e }} -#define {{ model.name | upper }}_NSPHIN {{ dims.nsphi_e }} -#define {{ model.name | upper }}_NSBXN {{ dims.nsbx_e }} -#define {{ model.name | upper }}_NS {{ dims.ns }} -#define {{ model.name | upper }}_NSN {{ dims.ns_e }} -#define {{ model.name | upper }}_NG {{ dims.ng }} -#define {{ model.name | upper }}_NBXN {{ dims.nbx_e }} -#define {{ model.name | upper }}_NGN {{ dims.ng_e }} -#define {{ model.name | upper }}_NY0 {{ dims.ny_0 }} -#define {{ model.name | upper }}_NY {{ dims.ny }} -#define {{ model.name | upper }}_NYN {{ dims.ny_e }} -#define {{ model.name | upper }}_N {{ dims.N }} -#define {{ model.name | upper }}_NH {{ dims.nh }} -#define {{ model.name | upper }}_NPHI {{ dims.nphi }} -#define {{ model.name | upper }}_NHN {{ dims.nh_e }} -#define {{ model.name | upper }}_NPHIN {{ dims.nphi_e }} -#define {{ model.name | upper }}_NR {{ dims.nr }} - -#ifdef __cplusplus -extern "C" { -#endif - -{%- if not solver_options.custom_update_filename %} - {%- set custom_update_filename = "" %} -{% else %} - {%- set custom_update_filename = solver_options.custom_update_filename %} -{%- endif %} - -// ** capsule for solver data ** -typedef struct {{ model.name }}_solver_capsule -{ - // acados objects - ocp_nlp_in *nlp_in; - ocp_nlp_out *nlp_out; - ocp_nlp_out *sens_out; - ocp_nlp_solver *nlp_solver; - void *nlp_opts; - ocp_nlp_plan_t *nlp_solver_plan; - ocp_nlp_config *nlp_config; - ocp_nlp_dims *nlp_dims; - - // number of expected runtime parameters - unsigned int nlp_np; - - /* external functions */ - // dynamics -{% if solver_options.integrator_type == "ERK" %} - external_function_param_casadi *forw_vde_casadi; - external_function_param_casadi *expl_ode_fun; -{% if solver_options.hessian_approx == "EXACT" %} - external_function_param_casadi *hess_vde_casadi; -{%- endif %} -{% elif solver_options.integrator_type == "IRK" %} - external_function_param_{{ model.dyn_ext_fun_type }} *impl_dae_fun; - external_function_param_{{ model.dyn_ext_fun_type }} *impl_dae_fun_jac_x_xdot_z; - external_function_param_{{ model.dyn_ext_fun_type }} *impl_dae_jac_x_xdot_u_z; -{% if solver_options.hessian_approx == "EXACT" %} - external_function_param_{{ model.dyn_ext_fun_type }} *impl_dae_hess; -{%- endif %} -{% elif solver_options.integrator_type == "LIFTED_IRK" %} - external_function_param_{{ model.dyn_ext_fun_type }} *impl_dae_fun; - external_function_param_{{ model.dyn_ext_fun_type }} *impl_dae_fun_jac_x_xdot_u; -{% elif solver_options.integrator_type == "GNSF" %} - external_function_param_casadi *gnsf_phi_fun; - external_function_param_casadi *gnsf_phi_fun_jac_y; - external_function_param_casadi *gnsf_phi_jac_y_uhat; - external_function_param_casadi *gnsf_f_lo_jac_x1_x1dot_u_z; - external_function_param_casadi *gnsf_get_matrices_fun; -{% elif solver_options.integrator_type == "DISCRETE" %} - external_function_param_{{ model.dyn_ext_fun_type }} *discr_dyn_phi_fun; - external_function_param_{{ model.dyn_ext_fun_type }} *discr_dyn_phi_fun_jac_ut_xt; -{%- if solver_options.hessian_approx == "EXACT" %} - external_function_param_{{ model.dyn_ext_fun_type }} *discr_dyn_phi_fun_jac_ut_xt_hess; -{%- endif %} -{%- endif %} - - - // cost -{% if cost.cost_type == "NONLINEAR_LS" %} - external_function_param_casadi *cost_y_fun; - external_function_param_casadi *cost_y_fun_jac_ut_xt; - external_function_param_casadi *cost_y_hess; -{% elif cost.cost_type == "CONVEX_OVER_NONLINEAR" %} - external_function_param_casadi *conl_cost_fun; - external_function_param_casadi *conl_cost_fun_jac_hess; -{%- elif cost.cost_type == "EXTERNAL" %} - external_function_param_{{ cost.cost_ext_fun_type }} *ext_cost_fun; - external_function_param_{{ cost.cost_ext_fun_type }} *ext_cost_fun_jac; - external_function_param_{{ cost.cost_ext_fun_type }} *ext_cost_fun_jac_hess; -{% endif %} - -{% if cost.cost_type_0 == "NONLINEAR_LS" %} - external_function_param_casadi cost_y_0_fun; - external_function_param_casadi cost_y_0_fun_jac_ut_xt; - external_function_param_casadi cost_y_0_hess; -{% elif cost.cost_type_0 == "CONVEX_OVER_NONLINEAR" %} - external_function_param_casadi conl_cost_0_fun; - external_function_param_casadi conl_cost_0_fun_jac_hess; -{% elif cost.cost_type_0 == "EXTERNAL" %} - external_function_param_{{ cost.cost_ext_fun_type_0 }} ext_cost_0_fun; - external_function_param_{{ cost.cost_ext_fun_type_0 }} ext_cost_0_fun_jac; - external_function_param_{{ cost.cost_ext_fun_type_0 }} ext_cost_0_fun_jac_hess; -{%- endif %} - -{% if cost.cost_type_e == "NONLINEAR_LS" %} - external_function_param_casadi cost_y_e_fun; - external_function_param_casadi cost_y_e_fun_jac_ut_xt; - external_function_param_casadi cost_y_e_hess; -{% elif cost.cost_type_e == "CONVEX_OVER_NONLINEAR" %} - external_function_param_casadi conl_cost_e_fun; - external_function_param_casadi conl_cost_e_fun_jac_hess; -{% elif cost.cost_type_e == "EXTERNAL" %} - external_function_param_{{ cost.cost_ext_fun_type_e }} ext_cost_e_fun; - external_function_param_{{ cost.cost_ext_fun_type_e }} ext_cost_e_fun_jac; - external_function_param_{{ cost.cost_ext_fun_type_e }} ext_cost_e_fun_jac_hess; -{%- endif %} - - // constraints -{%- if constraints.constr_type == "BGP" %} - external_function_param_casadi *phi_constraint; -{% elif constraints.constr_type == "BGH" and dims.nh > 0 %} - external_function_param_casadi *nl_constr_h_fun_jac; - external_function_param_casadi *nl_constr_h_fun; -{%- if solver_options.hessian_approx == "EXACT" %} - external_function_param_casadi *nl_constr_h_fun_jac_hess; -{%- endif %} -{%- endif %} - - -{% if constraints.constr_type_e == "BGP" %} - external_function_param_casadi phi_e_constraint; -{% elif constraints.constr_type_e == "BGH" and dims.nh_e > 0 %} - external_function_param_casadi nl_constr_h_e_fun_jac; - external_function_param_casadi nl_constr_h_e_fun; -{%- if solver_options.hessian_approx == "EXACT" %} - external_function_param_casadi nl_constr_h_e_fun_jac_hess; -{%- endif %} -{%- endif %} - -{%- if custom_update_filename != "" %} - void * custom_update_memory; -{%- endif %} - -} {{ model.name }}_solver_capsule; - -ACADOS_SYMBOL_EXPORT {{ model.name }}_solver_capsule * {{ model.name }}_acados_create_capsule(void); -ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_free_capsule({{ model.name }}_solver_capsule *capsule); - -ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_create({{ model.name }}_solver_capsule * capsule); - -ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_reset({{ model.name }}_solver_capsule* capsule, int reset_qp_solver_mem); - -/** - * Generic version of {{ model.name }}_acados_create which allows to use a different number of shooting intervals than - * the number used for code generation. If new_time_steps=NULL and n_time_steps matches the number used for code - * generation, the time-steps from code generation is used. - */ -ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_capsule * capsule, int n_time_steps, double* new_time_steps); -/** - * Update the time step vector. Number N must be identical to the currently set number of shooting nodes in the - * nlp_solver_plan. Returns 0 if no error occurred and a otherwise a value other than 0. - */ -ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_update_time_steps({{ model.name }}_solver_capsule * capsule, int N, double* new_time_steps); -/** - * This function is used for updating an already initialized solver with a different number of qp_cond_N. - */ -ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_update_qp_solver_cond_N({{ model.name }}_solver_capsule * capsule, int qp_solver_cond_N); -ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_update_params({{ model.name }}_solver_capsule * capsule, int stage, double *value, int np); -ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_update_params_sparse({{ model.name }}_solver_capsule * capsule, int stage, int *idx, double *p, int n_update); - -ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_solve({{ model.name }}_solver_capsule * capsule); -ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_free({{ model.name }}_solver_capsule * capsule); -ACADOS_SYMBOL_EXPORT void {{ model.name }}_acados_print_stats({{ model.name }}_solver_capsule * capsule); -ACADOS_SYMBOL_EXPORT int {{ model.name }}_acados_custom_update({{ model.name }}_solver_capsule* capsule, double* data, int data_len); - - -ACADOS_SYMBOL_EXPORT ocp_nlp_in *{{ model.name }}_acados_get_nlp_in({{ model.name }}_solver_capsule * capsule); -ACADOS_SYMBOL_EXPORT ocp_nlp_out *{{ model.name }}_acados_get_nlp_out({{ model.name }}_solver_capsule * capsule); -ACADOS_SYMBOL_EXPORT ocp_nlp_out *{{ model.name }}_acados_get_sens_out({{ model.name }}_solver_capsule * capsule); -ACADOS_SYMBOL_EXPORT ocp_nlp_solver *{{ model.name }}_acados_get_nlp_solver({{ model.name }}_solver_capsule * capsule); -ACADOS_SYMBOL_EXPORT ocp_nlp_config *{{ model.name }}_acados_get_nlp_config({{ model.name }}_solver_capsule * capsule); -ACADOS_SYMBOL_EXPORT void *{{ model.name }}_acados_get_nlp_opts({{ model.name }}_solver_capsule * capsule); -ACADOS_SYMBOL_EXPORT ocp_nlp_dims *{{ model.name }}_acados_get_nlp_dims({{ model.name }}_solver_capsule * capsule); -ACADOS_SYMBOL_EXPORT ocp_nlp_plan_t *{{ model.name }}_acados_get_nlp_plan({{ model.name }}_solver_capsule * capsule); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_SOLVER_{{ model.name }}_H_ diff --git a/third_party/acados/acados_template/c_templates_tera/acados_solver.in.pxd b/third_party/acados/acados_template/c_templates_tera/acados_solver.in.pxd deleted file mode 100644 index 233e3f79da..0000000000 --- a/third_party/acados/acados_template/c_templates_tera/acados_solver.in.pxd +++ /dev/null @@ -1,62 +0,0 @@ -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# 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. -# -# 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.; -# - -cimport acados_solver_common - -cdef extern from "acados_solver_{{ model.name }}.h": - ctypedef struct nlp_solver_capsule "{{ model.name }}_solver_capsule": - pass - - nlp_solver_capsule * acados_create_capsule "{{ model.name }}_acados_create_capsule"() - int acados_free_capsule "{{ model.name }}_acados_free_capsule"(nlp_solver_capsule *capsule) - - int acados_create "{{ model.name }}_acados_create"(nlp_solver_capsule * capsule) - - int acados_create_with_discretization "{{ model.name }}_acados_create_with_discretization"(nlp_solver_capsule * capsule, int n_time_steps, double* new_time_steps) - int acados_update_time_steps "{{ model.name }}_acados_update_time_steps"(nlp_solver_capsule * capsule, int N, double* new_time_steps) - int acados_update_qp_solver_cond_N "{{ model.name }}_acados_update_qp_solver_cond_N"(nlp_solver_capsule * capsule, int qp_solver_cond_N) - - int acados_update_params "{{ model.name }}_acados_update_params"(nlp_solver_capsule * capsule, int stage, double *value, int np_) - int acados_update_params_sparse "{{ model.name }}_acados_update_params_sparse"(nlp_solver_capsule * capsule, int stage, int *idx, double *p, int n_update) - int acados_solve "{{ model.name }}_acados_solve"(nlp_solver_capsule * capsule) - int acados_reset "{{ model.name }}_acados_reset"(nlp_solver_capsule * capsule, int reset_qp_solver_mem) - int acados_free "{{ model.name }}_acados_free"(nlp_solver_capsule * capsule) - void acados_print_stats "{{ model.name }}_acados_print_stats"(nlp_solver_capsule * capsule) - - int acados_custom_update "{{ model.name }}_acados_custom_update"(nlp_solver_capsule* capsule, double * data, int data_len) - - acados_solver_common.ocp_nlp_in *acados_get_nlp_in "{{ model.name }}_acados_get_nlp_in"(nlp_solver_capsule * capsule) - acados_solver_common.ocp_nlp_out *acados_get_nlp_out "{{ model.name }}_acados_get_nlp_out"(nlp_solver_capsule * capsule) - acados_solver_common.ocp_nlp_out *acados_get_sens_out "{{ model.name }}_acados_get_sens_out"(nlp_solver_capsule * capsule) - acados_solver_common.ocp_nlp_solver *acados_get_nlp_solver "{{ model.name }}_acados_get_nlp_solver"(nlp_solver_capsule * capsule) - acados_solver_common.ocp_nlp_config *acados_get_nlp_config "{{ model.name }}_acados_get_nlp_config"(nlp_solver_capsule * capsule) - void *acados_get_nlp_opts "{{ model.name }}_acados_get_nlp_opts"(nlp_solver_capsule * capsule) - acados_solver_common.ocp_nlp_dims *acados_get_nlp_dims "{{ model.name }}_acados_get_nlp_dims"(nlp_solver_capsule * capsule) - acados_solver_common.ocp_nlp_plan *acados_get_nlp_plan "{{ model.name }}_acados_get_nlp_plan"(nlp_solver_capsule * capsule) diff --git a/third_party/acados/acados_template/c_templates_tera/constraints.in.h b/third_party/acados/acados_template/c_templates_tera/constraints.in.h deleted file mode 100644 index d71ce5cc22..0000000000 --- a/third_party/acados/acados_template/c_templates_tera/constraints.in.h +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - -#ifndef {{ model.name }}_CONSTRAINTS -#define {{ model.name }}_CONSTRAINTS - -#ifdef __cplusplus -extern "C" { -#endif - -{% if dims.nphi > 0 %} -int {{ model.name }}_phi_constraint(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_phi_constraint_work(int *, int *, int *, int *); -const int *{{ model.name }}_phi_constraint_sparsity_in(int); -const int *{{ model.name }}_phi_constraint_sparsity_out(int); -int {{ model.name }}_phi_constraint_n_in(void); -int {{ model.name }}_phi_constraint_n_out(void); -{% endif %} - -{% if dims.nphi_e > 0 %} -int {{ model.name }}_phi_e_constraint(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_phi_e_constraint_work(int *, int *, int *, int *); -const int *{{ model.name }}_phi_e_constraint_sparsity_in(int); -const int *{{ model.name }}_phi_e_constraint_sparsity_out(int); -int {{ model.name }}_phi_e_constraint_n_in(void); -int {{ model.name }}_phi_e_constraint_n_out(void); -{% endif %} - -{% if dims.nh > 0 %} -int {{ model.name }}_constr_h_fun_jac_uxt_zt(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_constr_h_fun_jac_uxt_zt_work(int *, int *, int *, int *); -const int *{{ model.name }}_constr_h_fun_jac_uxt_zt_sparsity_in(int); -const int *{{ model.name }}_constr_h_fun_jac_uxt_zt_sparsity_out(int); -int {{ model.name }}_constr_h_fun_jac_uxt_zt_n_in(void); -int {{ model.name }}_constr_h_fun_jac_uxt_zt_n_out(void); - -int {{ model.name }}_constr_h_fun(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_constr_h_fun_work(int *, int *, int *, int *); -const int *{{ model.name }}_constr_h_fun_sparsity_in(int); -const int *{{ model.name }}_constr_h_fun_sparsity_out(int); -int {{ model.name }}_constr_h_fun_n_in(void); -int {{ model.name }}_constr_h_fun_n_out(void); - -{% if solver_options.hessian_approx == "EXACT" -%} -int {{ model.name }}_constr_h_fun_jac_uxt_zt_hess(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_constr_h_fun_jac_uxt_zt_hess_work(int *, int *, int *, int *); -const int *{{ model.name }}_constr_h_fun_jac_uxt_zt_hess_sparsity_in(int); -const int *{{ model.name }}_constr_h_fun_jac_uxt_zt_hess_sparsity_out(int); -int {{ model.name }}_constr_h_fun_jac_uxt_zt_hess_n_in(void); -int {{ model.name }}_constr_h_fun_jac_uxt_zt_hess_n_out(void); -{% endif %} -{% endif %} - -{% if dims.nh_e > 0 %} -int {{ model.name }}_constr_h_e_fun_jac_uxt_zt(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_constr_h_e_fun_jac_uxt_zt_work(int *, int *, int *, int *); -const int *{{ model.name }}_constr_h_e_fun_jac_uxt_zt_sparsity_in(int); -const int *{{ model.name }}_constr_h_e_fun_jac_uxt_zt_sparsity_out(int); -int {{ model.name }}_constr_h_e_fun_jac_uxt_zt_n_in(void); -int {{ model.name }}_constr_h_e_fun_jac_uxt_zt_n_out(void); - -int {{ model.name }}_constr_h_e_fun(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_constr_h_e_fun_work(int *, int *, int *, int *); -const int *{{ model.name }}_constr_h_e_fun_sparsity_in(int); -const int *{{ model.name }}_constr_h_e_fun_sparsity_out(int); -int {{ model.name }}_constr_h_e_fun_n_in(void); -int {{ model.name }}_constr_h_e_fun_n_out(void); - -{% if solver_options.hessian_approx == "EXACT" -%} -int {{ model.name }}_constr_h_e_fun_jac_uxt_zt_hess(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_constr_h_e_fun_jac_uxt_zt_hess_work(int *, int *, int *, int *); -const int *{{ model.name }}_constr_h_e_fun_jac_uxt_zt_hess_sparsity_in(int); -const int *{{ model.name }}_constr_h_e_fun_jac_uxt_zt_hess_sparsity_out(int); -int {{ model.name }}_constr_h_e_fun_jac_uxt_zt_hess_n_in(void); -int {{ model.name }}_constr_h_e_fun_jac_uxt_zt_hess_n_out(void); -{% endif %} -{% endif %} - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // {{ model.name }}_CONSTRAINTS diff --git a/third_party/acados/acados_template/c_templates_tera/cost.in.h b/third_party/acados/acados_template/c_templates_tera/cost.in.h deleted file mode 100644 index 45eb09c12e..0000000000 --- a/third_party/acados/acados_template/c_templates_tera/cost.in.h +++ /dev/null @@ -1,238 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -#ifndef {{ model.name }}_COST -#define {{ model.name }}_COST - -#ifdef __cplusplus -extern "C" { -#endif - - -// Cost at initial shooting node -{% if cost.cost_type_0 == "NONLINEAR_LS" %} -int {{ model.name }}_cost_y_0_fun(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_cost_y_0_fun_work(int *, int *, int *, int *); -const int *{{ model.name }}_cost_y_0_fun_sparsity_in(int); -const int *{{ model.name }}_cost_y_0_fun_sparsity_out(int); -int {{ model.name }}_cost_y_0_fun_n_in(void); -int {{ model.name }}_cost_y_0_fun_n_out(void); - -int {{ model.name }}_cost_y_0_fun_jac_ut_xt(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_cost_y_0_fun_jac_ut_xt_work(int *, int *, int *, int *); -const int *{{ model.name }}_cost_y_0_fun_jac_ut_xt_sparsity_in(int); -const int *{{ model.name }}_cost_y_0_fun_jac_ut_xt_sparsity_out(int); -int {{ model.name }}_cost_y_0_fun_jac_ut_xt_n_in(void); -int {{ model.name }}_cost_y_0_fun_jac_ut_xt_n_out(void); - -int {{ model.name }}_cost_y_0_hess(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_cost_y_0_hess_work(int *, int *, int *, int *); -const int *{{ model.name }}_cost_y_0_hess_sparsity_in(int); -const int *{{ model.name }}_cost_y_0_hess_sparsity_out(int); -int {{ model.name }}_cost_y_0_hess_n_in(void); -int {{ model.name }}_cost_y_0_hess_n_out(void); -{% elif cost.cost_type_0 == "CONVEX_OVER_NONLINEAR" %} - -int {{ model.name }}_conl_cost_0_fun(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_conl_cost_0_fun_work(int *, int *, int *, int *); -const int *{{ model.name }}_conl_cost_0_fun_sparsity_in(int); -const int *{{ model.name }}_conl_cost_0_fun_sparsity_out(int); -int {{ model.name }}_conl_cost_0_fun_n_in(void); -int {{ model.name }}_conl_cost_0_fun_n_out(void); - -int {{ model.name }}_conl_cost_0_fun_jac_hess(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_conl_cost_0_fun_jac_hess_work(int *, int *, int *, int *); -const int *{{ model.name }}_conl_cost_0_fun_jac_hess_sparsity_in(int); -const int *{{ model.name }}_conl_cost_0_fun_jac_hess_sparsity_out(int); -int {{ model.name }}_conl_cost_0_fun_jac_hess_n_in(void); -int {{ model.name }}_conl_cost_0_fun_jac_hess_n_out(void); - -{% elif cost.cost_type_0 == "EXTERNAL" %} - {%- if cost.cost_ext_fun_type_0 == "casadi" %} -int {{ model.name }}_cost_ext_cost_0_fun(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_cost_ext_cost_0_fun_work(int *, int *, int *, int *); -const int *{{ model.name }}_cost_ext_cost_0_fun_sparsity_in(int); -const int *{{ model.name }}_cost_ext_cost_0_fun_sparsity_out(int); -int {{ model.name }}_cost_ext_cost_0_fun_n_in(void); -int {{ model.name }}_cost_ext_cost_0_fun_n_out(void); - -int {{ model.name }}_cost_ext_cost_0_fun_jac_hess(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_cost_ext_cost_0_fun_jac_hess_work(int *, int *, int *, int *); -const int *{{ model.name }}_cost_ext_cost_0_fun_jac_hess_sparsity_in(int); -const int *{{ model.name }}_cost_ext_cost_0_fun_jac_hess_sparsity_out(int); -int {{ model.name }}_cost_ext_cost_0_fun_jac_hess_n_in(void); -int {{ model.name }}_cost_ext_cost_0_fun_jac_hess_n_out(void); - -int {{ model.name }}_cost_ext_cost_0_fun_jac(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_cost_ext_cost_0_fun_jac_work(int *, int *, int *, int *); -const int *{{ model.name }}_cost_ext_cost_0_fun_jac_sparsity_in(int); -const int *{{ model.name }}_cost_ext_cost_0_fun_jac_sparsity_out(int); -int {{ model.name }}_cost_ext_cost_0_fun_jac_n_in(void); -int {{ model.name }}_cost_ext_cost_0_fun_jac_n_out(void); - {%- else %} -int {{ cost.cost_function_ext_cost_0 }}(void **, void **, void *); - {%- endif %} -{% endif %} - - -// Cost at path shooting node -{% if cost.cost_type == "NONLINEAR_LS" %} -int {{ model.name }}_cost_y_fun(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_cost_y_fun_work(int *, int *, int *, int *); -const int *{{ model.name }}_cost_y_fun_sparsity_in(int); -const int *{{ model.name }}_cost_y_fun_sparsity_out(int); -int {{ model.name }}_cost_y_fun_n_in(void); -int {{ model.name }}_cost_y_fun_n_out(void); - -int {{ model.name }}_cost_y_fun_jac_ut_xt(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_cost_y_fun_jac_ut_xt_work(int *, int *, int *, int *); -const int *{{ model.name }}_cost_y_fun_jac_ut_xt_sparsity_in(int); -const int *{{ model.name }}_cost_y_fun_jac_ut_xt_sparsity_out(int); -int {{ model.name }}_cost_y_fun_jac_ut_xt_n_in(void); -int {{ model.name }}_cost_y_fun_jac_ut_xt_n_out(void); - -int {{ model.name }}_cost_y_hess(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_cost_y_hess_work(int *, int *, int *, int *); -const int *{{ model.name }}_cost_y_hess_sparsity_in(int); -const int *{{ model.name }}_cost_y_hess_sparsity_out(int); -int {{ model.name }}_cost_y_hess_n_in(void); -int {{ model.name }}_cost_y_hess_n_out(void); - -{% elif cost.cost_type == "CONVEX_OVER_NONLINEAR" %} -int {{ model.name }}_conl_cost_fun(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_conl_cost_fun_work(int *, int *, int *, int *); -const int *{{ model.name }}_conl_cost_fun_sparsity_in(int); -const int *{{ model.name }}_conl_cost_fun_sparsity_out(int); -int {{ model.name }}_conl_cost_fun_n_in(void); -int {{ model.name }}_conl_cost_fun_n_out(void); - -int {{ model.name }}_conl_cost_fun_jac_hess(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_conl_cost_fun_jac_hess_work(int *, int *, int *, int *); -const int *{{ model.name }}_conl_cost_fun_jac_hess_sparsity_in(int); -const int *{{ model.name }}_conl_cost_fun_jac_hess_sparsity_out(int); -int {{ model.name }}_conl_cost_fun_jac_hess_n_in(void); -int {{ model.name }}_conl_cost_fun_jac_hess_n_out(void); -{% elif cost.cost_type == "EXTERNAL" %} - {%- if cost.cost_ext_fun_type == "casadi" %} -int {{ model.name }}_cost_ext_cost_fun(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_cost_ext_cost_fun_work(int *, int *, int *, int *); -const int *{{ model.name }}_cost_ext_cost_fun_sparsity_in(int); -const int *{{ model.name }}_cost_ext_cost_fun_sparsity_out(int); -int {{ model.name }}_cost_ext_cost_fun_n_in(void); -int {{ model.name }}_cost_ext_cost_fun_n_out(void); - -int {{ model.name }}_cost_ext_cost_fun_jac_hess(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_cost_ext_cost_fun_jac_hess_work(int *, int *, int *, int *); -const int *{{ model.name }}_cost_ext_cost_fun_jac_hess_sparsity_in(int); -const int *{{ model.name }}_cost_ext_cost_fun_jac_hess_sparsity_out(int); -int {{ model.name }}_cost_ext_cost_fun_jac_hess_n_in(void); -int {{ model.name }}_cost_ext_cost_fun_jac_hess_n_out(void); - -int {{ model.name }}_cost_ext_cost_fun_jac(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_cost_ext_cost_fun_jac_work(int *, int *, int *, int *); -const int *{{ model.name }}_cost_ext_cost_fun_jac_sparsity_in(int); -const int *{{ model.name }}_cost_ext_cost_fun_jac_sparsity_out(int); -int {{ model.name }}_cost_ext_cost_fun_jac_n_in(void); -int {{ model.name }}_cost_ext_cost_fun_jac_n_out(void); - {%- else %} -int {{ cost.cost_function_ext_cost }}(void **, void **, void *); - {%- endif %} -{% endif %} - -// Cost at terminal shooting node -{% if cost.cost_type_e == "NONLINEAR_LS" %} -int {{ model.name }}_cost_y_e_fun(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_cost_y_e_fun_work(int *, int *, int *, int *); -const int *{{ model.name }}_cost_y_e_fun_sparsity_in(int); -const int *{{ model.name }}_cost_y_e_fun_sparsity_out(int); -int {{ model.name }}_cost_y_e_fun_n_in(void); -int {{ model.name }}_cost_y_e_fun_n_out(void); - -int {{ model.name }}_cost_y_e_fun_jac_ut_xt(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_cost_y_e_fun_jac_ut_xt_work(int *, int *, int *, int *); -const int *{{ model.name }}_cost_y_e_fun_jac_ut_xt_sparsity_in(int); -const int *{{ model.name }}_cost_y_e_fun_jac_ut_xt_sparsity_out(int); -int {{ model.name }}_cost_y_e_fun_jac_ut_xt_n_in(void); -int {{ model.name }}_cost_y_e_fun_jac_ut_xt_n_out(void); - -int {{ model.name }}_cost_y_e_hess(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_cost_y_e_hess_work(int *, int *, int *, int *); -const int *{{ model.name }}_cost_y_e_hess_sparsity_in(int); -const int *{{ model.name }}_cost_y_e_hess_sparsity_out(int); -int {{ model.name }}_cost_y_e_hess_n_in(void); -int {{ model.name }}_cost_y_e_hess_n_out(void); -{% elif cost.cost_type_e == "CONVEX_OVER_NONLINEAR" %} -int {{ model.name }}_conl_cost_e_fun(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_conl_cost_e_fun_work(int *, int *, int *, int *); -const int *{{ model.name }}_conl_cost_e_fun_sparsity_in(int); -const int *{{ model.name }}_conl_cost_e_fun_sparsity_out(int); -int {{ model.name }}_conl_cost_e_fun_n_in(void); -int {{ model.name }}_conl_cost_e_fun_n_out(void); - -int {{ model.name }}_conl_cost_e_fun_jac_hess(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_conl_cost_e_fun_jac_hess_work(int *, int *, int *, int *); -const int *{{ model.name }}_conl_cost_e_fun_jac_hess_sparsity_in(int); -const int *{{ model.name }}_conl_cost_e_fun_jac_hess_sparsity_out(int); -int {{ model.name }}_conl_cost_e_fun_jac_hess_n_in(void); -int {{ model.name }}_conl_cost_e_fun_jac_hess_n_out(void); -{% elif cost.cost_type_e == "EXTERNAL" %} - {%- if cost.cost_ext_fun_type_e == "casadi" %} -int {{ model.name }}_cost_ext_cost_e_fun(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_cost_ext_cost_e_fun_work(int *, int *, int *, int *); -const int *{{ model.name }}_cost_ext_cost_e_fun_sparsity_in(int); -const int *{{ model.name }}_cost_ext_cost_e_fun_sparsity_out(int); -int {{ model.name }}_cost_ext_cost_e_fun_n_in(void); -int {{ model.name }}_cost_ext_cost_e_fun_n_out(void); - -int {{ model.name }}_cost_ext_cost_e_fun_jac_hess(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_cost_ext_cost_e_fun_jac_hess_work(int *, int *, int *, int *); -const int *{{ model.name }}_cost_ext_cost_e_fun_jac_hess_sparsity_in(int); -const int *{{ model.name }}_cost_ext_cost_e_fun_jac_hess_sparsity_out(int); -int {{ model.name }}_cost_ext_cost_e_fun_jac_hess_n_in(void); -int {{ model.name }}_cost_ext_cost_e_fun_jac_hess_n_out(void); - -int {{ model.name }}_cost_ext_cost_e_fun_jac(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_cost_ext_cost_e_fun_jac_work(int *, int *, int *, int *); -const int *{{ model.name }}_cost_ext_cost_e_fun_jac_sparsity_in(int); -const int *{{ model.name }}_cost_ext_cost_e_fun_jac_sparsity_out(int); -int {{ model.name }}_cost_ext_cost_e_fun_jac_n_in(void); -int {{ model.name }}_cost_ext_cost_e_fun_jac_n_out(void); - {%- else %} -int {{ cost.cost_function_ext_cost_e }}(void **, void **, void *); - {%- endif %} -{% endif %} - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // {{ model.name }}_COST diff --git a/third_party/acados/acados_template/c_templates_tera/main.in.c b/third_party/acados/acados_template/c_templates_tera/main.in.c deleted file mode 100644 index 92a8b33eac..0000000000 --- a/third_party/acados/acados_template/c_templates_tera/main.in.c +++ /dev/null @@ -1,226 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - -{%- if not solver_options.custom_update_filename %} - {%- set custom_update_filename = "" %} -{% else %} - {%- set custom_update_filename = solver_options.custom_update_filename %} -{%- endif %} - -// standard -#include -#include -// acados -#include "acados/utils/print.h" -#include "acados/utils/math.h" -#include "acados_c/ocp_nlp_interface.h" -#include "acados_c/external_function_interface.h" -#include "acados_solver_{{ model.name }}.h" - -// blasfeo -#include "blasfeo/include/blasfeo_d_aux_ext_dep.h" - -#define NX {{ model.name | upper }}_NX -#define NZ {{ model.name | upper }}_NZ -#define NU {{ model.name | upper }}_NU -#define NP {{ model.name | upper }}_NP -#define NBX {{ model.name | upper }}_NBX -#define NBX0 {{ model.name | upper }}_NBX0 -#define NBU {{ model.name | upper }}_NBU -#define NSBX {{ model.name | upper }}_NSBX -#define NSBU {{ model.name | upper }}_NSBU -#define NSH {{ model.name | upper }}_NSH -#define NSG {{ model.name | upper }}_NSG -#define NSPHI {{ model.name | upper }}_NSPHI -#define NSHN {{ model.name | upper }}_NSHN -#define NSGN {{ model.name | upper }}_NSGN -#define NSPHIN {{ model.name | upper }}_NSPHIN -#define NSBXN {{ model.name | upper }}_NSBXN -#define NS {{ model.name | upper }}_NS -#define NSN {{ model.name | upper }}_NSN -#define NG {{ model.name | upper }}_NG -#define NBXN {{ model.name | upper }}_NBXN -#define NGN {{ model.name | upper }}_NGN -#define NY0 {{ model.name | upper }}_NY0 -#define NY {{ model.name | upper }}_NY -#define NYN {{ model.name | upper }}_NYN -#define NH {{ model.name | upper }}_NH -#define NPHI {{ model.name | upper }}_NPHI -#define NHN {{ model.name | upper }}_NHN -#define NPHIN {{ model.name | upper }}_NPHIN -#define NR {{ model.name | upper }}_NR - - -int main() -{ - - {{ model.name }}_solver_capsule *acados_ocp_capsule = {{ model.name }}_acados_create_capsule(); - // there is an opportunity to change the number of shooting intervals in C without new code generation - int N = {{ model.name | upper }}_N; - // allocate the array and fill it accordingly - double* new_time_steps = NULL; - int status = {{ model.name }}_acados_create_with_discretization(acados_ocp_capsule, N, new_time_steps); - - if (status) - { - printf("{{ model.name }}_acados_create() returned status %d. Exiting.\n", status); - exit(1); - } - - ocp_nlp_config *nlp_config = {{ model.name }}_acados_get_nlp_config(acados_ocp_capsule); - ocp_nlp_dims *nlp_dims = {{ model.name }}_acados_get_nlp_dims(acados_ocp_capsule); - ocp_nlp_in *nlp_in = {{ model.name }}_acados_get_nlp_in(acados_ocp_capsule); - ocp_nlp_out *nlp_out = {{ model.name }}_acados_get_nlp_out(acados_ocp_capsule); - ocp_nlp_solver *nlp_solver = {{ model.name }}_acados_get_nlp_solver(acados_ocp_capsule); - void *nlp_opts = {{ model.name }}_acados_get_nlp_opts(acados_ocp_capsule); - - // initial condition - int idxbx0[NBX0]; - {%- for i in range(end=dims.nbx_0) %} - idxbx0[{{ i }}] = {{ constraints.idxbx_0[i] }}; - {%- endfor %} - - double lbx0[NBX0]; - double ubx0[NBX0]; - {%- for i in range(end=dims.nbx_0) %} - lbx0[{{ i }}] = {{ constraints.lbx_0[i] }}; - ubx0[{{ i }}] = {{ constraints.ubx_0[i] }}; - {%- endfor %} - - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "idxbx", idxbx0); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "lbx", lbx0); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "ubx", ubx0); - - // initialization for state values - double x_init[NX]; - {%- for i in range(end=dims.nx) %} - x_init[{{ i }}] = 0.0; - {%- endfor %} - - // initial value for control input - double u0[NU]; - {%- for i in range(end=dims.nu) %} - u0[{{ i }}] = 0.0; - {%- endfor %} - - - {%- if dims.np > 0 %} - // set parameters - double p[NP]; - {%- for item in parameter_values %} - p[{{ loop.index0 }}] = {{ item }}; - {%- endfor %} - - for (int ii = 0; ii <= N; ii++) - { - {{ model.name }}_acados_update_params(acados_ocp_capsule, ii, p, NP); - } - {% endif %}{# if np > 0 #} - - // prepare evaluation - int NTIMINGS = 1; - double min_time = 1e12; - double kkt_norm_inf; - double elapsed_time; - int sqp_iter; - - double xtraj[NX * (N+1)]; - double utraj[NU * N]; - - - // solve ocp in loop - int rti_phase = 0; - - for (int ii = 0; ii < NTIMINGS; ii++) - { - // initialize solution - for (int i = 0; i < N; i++) - { - ocp_nlp_out_set(nlp_config, nlp_dims, nlp_out, i, "x", x_init); - ocp_nlp_out_set(nlp_config, nlp_dims, nlp_out, i, "u", u0); - } - ocp_nlp_out_set(nlp_config, nlp_dims, nlp_out, N, "x", x_init); - ocp_nlp_solver_opts_set(nlp_config, nlp_opts, "rti_phase", &rti_phase); - status = {{ model.name }}_acados_solve(acados_ocp_capsule); - ocp_nlp_get(nlp_config, nlp_solver, "time_tot", &elapsed_time); - min_time = MIN(elapsed_time, min_time); - } - - /* print solution and statistics */ - for (int ii = 0; ii <= nlp_dims->N; ii++) - ocp_nlp_out_get(nlp_config, nlp_dims, nlp_out, ii, "x", &xtraj[ii*NX]); - for (int ii = 0; ii < nlp_dims->N; ii++) - ocp_nlp_out_get(nlp_config, nlp_dims, nlp_out, ii, "u", &utraj[ii*NU]); - - printf("\n--- xtraj ---\n"); - d_print_exp_tran_mat( NX, N+1, xtraj, NX); - printf("\n--- utraj ---\n"); - d_print_exp_tran_mat( NU, N, utraj, NU ); - // ocp_nlp_out_print(nlp_solver->dims, nlp_out); - - printf("\nsolved ocp %d times, solution printed above\n\n", NTIMINGS); - - if (status == ACADOS_SUCCESS) - { - printf("{{ model.name }}_acados_solve(): SUCCESS!\n"); - } - else - { - printf("{{ model.name }}_acados_solve() failed with status %d.\n", status); - } - - -{%- if custom_update_filename != "" %} - {{ model.name }}_acados_custom_update(acados_ocp_capsule, xtraj, NX*(N+1)); -{%- endif %} - - // get solution - ocp_nlp_out_get(nlp_config, nlp_dims, nlp_out, 0, "kkt_norm_inf", &kkt_norm_inf); - ocp_nlp_get(nlp_config, nlp_solver, "sqp_iter", &sqp_iter); - - {{ model.name }}_acados_print_stats(acados_ocp_capsule); - - printf("\nSolver info:\n"); - printf(" SQP iterations %2d\n minimum time for %d solve %f [ms]\n KKT %e\n", - sqp_iter, NTIMINGS, min_time*1000, kkt_norm_inf); - - // free solver - status = {{ model.name }}_acados_free(acados_ocp_capsule); - if (status) { - printf("{{ model.name }}_acados_free() returned status %d. \n", status); - } - // free solver capsule - status = {{ model.name }}_acados_free_capsule(acados_ocp_capsule); - if (status) { - printf("{{ model.name }}_acados_free_capsule() returned status %d. \n", status); - } - - return status; -} diff --git a/third_party/acados/acados_template/c_templates_tera/main_sim.in.c b/third_party/acados/acados_template/c_templates_tera/main_sim.in.c deleted file mode 100644 index 8960aa0035..0000000000 --- a/third_party/acados/acados_template/c_templates_tera/main_sim.in.c +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -// standard -#include -#include -// acados -#include "acados/utils/print.h" -#include "acados/utils/math.h" -#include "acados_c/sim_interface.h" -#include "acados_sim_solver_{{ model.name }}.h" - -#define NX {{ model.name | upper }}_NX -#define NZ {{ model.name | upper }}_NZ -#define NU {{ model.name | upper }}_NU -#define NP {{ model.name | upper }}_NP - - -int main() -{ - int status = 0; - sim_solver_capsule *capsule = {{ model.name }}_acados_sim_solver_create_capsule(); - status = {{ model.name }}_acados_sim_create(capsule); - - if (status) - { - printf("acados_create() returned status %d. Exiting.\n", status); - exit(1); - } - - sim_config *acados_sim_config = {{ model.name }}_acados_get_sim_config(capsule); - sim_in *acados_sim_in = {{ model.name }}_acados_get_sim_in(capsule); - sim_out *acados_sim_out = {{ model.name }}_acados_get_sim_out(capsule); - void *acados_sim_dims = {{ model.name }}_acados_get_sim_dims(capsule); - - // initial condition - double x_current[NX]; - {%- for i in range(end=dims.nx) %} - x_current[{{ i }}] = 0.0; - {%- endfor %} - - {% if constraints.lbx_0 %} - {%- for i in range(end=dims.nbx_0) %} - x_current[{{ constraints.idxbx_0[i] }}] = {{ constraints.lbx_0[i] }}; - {%- endfor %} - {% if dims.nbx_0 != dims.nx %} - printf("main_sim: NOTE: initial state not fully defined via lbx_0, using 0.0 for indices that are not in idxbx_0."); - {%- endif %} - {% else %} - printf("main_sim: initial state not defined, should be in lbx_0, using zero vector."); - {%- endif %} - - - // initial value for control input - double u0[NU]; - {%- for i in range(end=dims.nu) %} - u0[{{ i }}] = 0.0; - {%- endfor %} - - {%- if dims.np > 0 %} - // set parameters - double p[NP]; - {%- for item in parameter_values %} - p[{{ loop.index0 }}] = {{ item }}; - {%- endfor %} - - {{ model.name }}_acados_sim_update_params(capsule, p, NP); - {% endif %}{# if np > 0 #} - - int n_sim_steps = 3; - // solve ocp in loop - for (int ii = 0; ii < n_sim_steps; ii++) - { - sim_in_set(acados_sim_config, acados_sim_dims, - acados_sim_in, "x", x_current); - status = {{ model.name }}_acados_sim_solve(capsule); - - if (status != ACADOS_SUCCESS) - { - printf("acados_solve() failed with status %d.\n", status); - } - - sim_out_get(acados_sim_config, acados_sim_dims, - acados_sim_out, "x", x_current); - - printf("\nx_current, %d\n", ii); - for (int jj = 0; jj < NX; jj++) - { - printf("%e\n", x_current[jj]); - } - } - - printf("\nPerformed %d simulation steps with acados integrator successfully.\n\n", n_sim_steps); - - // free solver - status = {{ model.name }}_acados_sim_free(capsule); - if (status) { - printf("{{ model.name }}_acados_sim_free() returned status %d. \n", status); - } - - {{ model.name }}_acados_sim_solver_free_capsule(capsule); - - return status; -} diff --git a/third_party/acados/acados_template/c_templates_tera/matlab_templates/acados_mex_create.in.c b/third_party/acados/acados_template/c_templates_tera/matlab_templates/acados_mex_create.in.c deleted file mode 100644 index 24ae94ac2c..0000000000 --- a/third_party/acados/acados_template/c_templates_tera/matlab_templates/acados_mex_create.in.c +++ /dev/null @@ -1,384 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -// standard -#include -#include -#include - -// acados -#include "acados/utils/print.h" -#include "acados_c/ocp_nlp_interface.h" -#include "acados_solver_{{ model.name }}.h" - -// mex -#include "mex.h" - - -void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) -{ - long long *l_ptr; - int status = 0; - - // create solver - {{ model.name }}_solver_capsule *acados_ocp_capsule = {{ model.name }}_acados_create_capsule(); - - status = {{ model.name }}_acados_create(acados_ocp_capsule); - - if (status) - { - mexPrintf("{{ model.name }}_acados_create() returned status %d.\n", status); - } - mexPrintf("{{ model.name }}_acados_create() -> success!\n"); - - // get pointers to nlp solver related objects - ocp_nlp_plan_t *nlp_plan = {{ model.name }}_acados_get_nlp_plan(acados_ocp_capsule); - ocp_nlp_config *nlp_config = {{ model.name }}_acados_get_nlp_config(acados_ocp_capsule); - ocp_nlp_dims *nlp_dims = {{ model.name }}_acados_get_nlp_dims(acados_ocp_capsule); - ocp_nlp_in *nlp_in = {{ model.name }}_acados_get_nlp_in(acados_ocp_capsule); - ocp_nlp_out *nlp_out = {{ model.name }}_acados_get_nlp_out(acados_ocp_capsule); - ocp_nlp_solver *nlp_solver = {{ model.name }}_acados_get_nlp_solver(acados_ocp_capsule); - void *nlp_opts = {{ model.name }}_acados_get_nlp_opts(acados_ocp_capsule); - - // mexPrintf("acados: got pointer to objectes!\n"); - - // field names of output struct - #define FIELDS_OCP 9 - #define FIELDS_EXT_FUN 25 - #define MAX_FIELDS 25 - char *fieldnames[MAX_FIELDS]; - - for (int i = 0; i < MAX_FIELDS; i++) - { - fieldnames[i] = (char*) mxMalloc(50); - } - - memcpy(fieldnames[0],"config",sizeof("config")); - memcpy(fieldnames[1],"dims",sizeof("dims")); - memcpy(fieldnames[2],"opts",sizeof("opts")); - memcpy(fieldnames[3],"in",sizeof("in")); - memcpy(fieldnames[4],"out",sizeof("out")); - memcpy(fieldnames[5],"solver",sizeof("solver")); - memcpy(fieldnames[6],"sens_out",sizeof("sens_out")); - memcpy(fieldnames[7],"plan",sizeof("plan")); - memcpy(fieldnames[8],"capsule",sizeof("capsule")); - - // create output struct - C_ocp - plhs[0] = mxCreateStructMatrix(1, 1, 9, (const char **) fieldnames); - - // MEX: config, dims, opts, in, out, solver, sens_out, plan - // plan - mxArray *plan_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - l_ptr = mxGetData(plan_mat); - l_ptr[0] = (long long) nlp_plan; - mxSetField(plhs[0], 0, "plan", plan_mat); - - // config - mxArray *config_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - l_ptr = mxGetData(config_mat); - l_ptr[0] = (long long) nlp_config; - mxSetField(plhs[0], 0, "config", config_mat); - - // dims - mxArray *dims_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - l_ptr = mxGetData(dims_mat); - l_ptr[0] = (long long) nlp_dims; - mxSetField(plhs[0], 0, "dims", dims_mat); - - // opts - mxArray *opts_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - l_ptr = mxGetData(opts_mat); - l_ptr[0] = (long long) nlp_opts; - mxSetField(plhs[0], 0, "opts", opts_mat); - - // in - mxArray *in_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - l_ptr = mxGetData(in_mat); - l_ptr[0] = (long long) nlp_in; - mxSetField(plhs[0], 0, "in", in_mat); - - // out - mxArray *out_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - l_ptr = mxGetData(out_mat); - l_ptr[0] = (long long) nlp_out; - mxSetField(plhs[0], 0, "out", out_mat); - - // solver - mxArray *solver_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - l_ptr = mxGetData(solver_mat); - l_ptr[0] = (long long) nlp_solver; - mxSetField(plhs[0], 0, "solver", solver_mat); - - // TODO: sens_out not actually implemented in templates.. - // sens_out - mxArray *sens_out_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - l_ptr = mxGetData(sens_out_mat); - l_ptr[0] = (long long) 1; - mxSetField(plhs[0], 0, "sens_out", sens_out_mat); - - // capsule - mxArray *capsule_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - l_ptr = mxGetData(capsule_mat); - l_ptr[0] = (long long) acados_ocp_capsule; - mxSetField(plhs[0], 0, "capsule", capsule_mat); - - /* store external function pointers */ - // dyn - memcpy(fieldnames[0],"expl_ode_fun",sizeof("expl_ode_fun")); - memcpy(fieldnames[1],"forw_vde",sizeof("forw_vde")); - memcpy(fieldnames[2],"hess_vde",sizeof("hess_vde")); - memcpy(fieldnames[3],"impl_dae_fun",sizeof("impl_dae_fun")); - memcpy(fieldnames[4],"impl_dae_fun_jac_x_xdot_z",sizeof("impl_dae_fun_jac_x_xdot_z")); - memcpy(fieldnames[5],"impl_dae_jac_x_xdot_u_z",sizeof("impl_dae_jac_x_xdot_u_z")); - memcpy(fieldnames[6],"impl_dae_hess",sizeof("impl_dae_hess")); - - memcpy(fieldnames[7],"gnsf_phi_fun",sizeof("gnsf_phi_fun")); - memcpy(fieldnames[8],"gnsf_phi_fun_jac_y",sizeof("gnsf_phi_fun_jac_y")); - memcpy(fieldnames[9],"gnsf_phi_jac_y_uhat",sizeof("gnsf_phi_jac_y_uhat")); - memcpy(fieldnames[10],"gnsf_f_lo_jac_x1_x1dot_u_z",sizeof("gnsf_f_lo_jac_x1_x1dot_u_z")); - memcpy(fieldnames[11],"gnsf_get_matrices_fun",sizeof("gnsf_get_matrices_fun")); - - memcpy(fieldnames[12],"disc_phi_fun",sizeof("disc_phi_fun")); - memcpy(fieldnames[13],"disc_phi_fun_jac",sizeof("disc_phi_fun_jac")); - memcpy(fieldnames[14],"disc_phi_fun_jac_hess",sizeof("disc_phi_fun_jac_hess")); - - // cost - memcpy(fieldnames[15],"cost_y_fun",sizeof("cost_y_fun")); - memcpy(fieldnames[16],"cost_y_fun_jac_ut_xt",sizeof("cost_y_fun_jac_ut_xt")); - memcpy(fieldnames[17],"cost_y_hess",sizeof("cost_y_hess")); - memcpy(fieldnames[18],"ext_cost_fun",sizeof("ext_cost_fun")); - memcpy(fieldnames[19],"ext_cost_fun_jac",sizeof("ext_cost_fun_jac")); - memcpy(fieldnames[20],"ext_cost_fun_jac_hess",sizeof("ext_cost_fun_jac_hess")); - - // constraints - memcpy(fieldnames[21],"phi_constraint",sizeof("phi_constraint")); - memcpy(fieldnames[22],"nl_constr_h_fun_jac",sizeof("nl_constr_h_fun_jac")); - memcpy(fieldnames[23],"nl_constr_h_fun",sizeof("nl_constr_h_fun")); - memcpy(fieldnames[24],"nl_constr_h_fun_jac_hess",sizeof("nl_constr_h_fun_jac_hess")); - - - // create output struct - C_ocp_ext_fun - plhs[1] = mxCreateStructMatrix(1, 1, FIELDS_EXT_FUN, (const char **) fieldnames); - - - for (int i = 0; i < FIELDS_EXT_FUN; i++) - { - mxFree( fieldnames[i] ); - } - -/* dynamics */ - mxArray *expl_ode_fun_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - mxArray *forw_vde_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - mxArray *hess_vde_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - mxArray *impl_dae_fun_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - mxArray *impl_dae_fun_jac_x_xdot_z_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - mxArray *impl_dae_jac_x_xdot_u_z_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - mxArray *impl_dae_hess_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - - mxArray *gnsf_phi_fun_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - mxArray *gnsf_phi_fun_jac_y_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - mxArray *gnsf_phi_jac_y_uhat_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - mxArray *gnsf_f_lo_jac_x1_x1dot_u_z_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - mxArray *gnsf_get_matrices_fun_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - - mxArray *disc_phi_fun_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - mxArray *disc_phi_fun_jac_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - mxArray *disc_phi_fun_jac_hess_mat = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); - -{% if solver_options.integrator_type == "ERK" %} - {# TODO: remove _casadi from these names.. #} - l_ptr = mxGetData(forw_vde_mat); - l_ptr[0] = (long long) acados_ocp_capsule->forw_vde_casadi; - l_ptr = mxGetData(expl_ode_fun_mat); - l_ptr[0] = (long long) acados_ocp_capsule->expl_ode_fun; -{% if solver_options.hessian_approx == "EXACT" %} - l_ptr = mxGetData(hess_vde_mat); - l_ptr[0] = (long long) acados_ocp_capsule->hess_vde_casadi; -{%- endif %} -{% elif solver_options.integrator_type == "IRK" %} - l_ptr = mxGetData(impl_dae_fun_mat); - l_ptr[0] = (long long) acados_ocp_capsule->impl_dae_fun; - l_ptr = mxGetData(impl_dae_fun_jac_x_xdot_z_mat); - l_ptr[0] = (long long) acados_ocp_capsule->impl_dae_fun_jac_x_xdot_z; - l_ptr = mxGetData(impl_dae_jac_x_xdot_u_z_mat); - l_ptr[0] = (long long) acados_ocp_capsule->impl_dae_jac_x_xdot_u_z; -{% if solver_options.hessian_approx == "EXACT" %} - l_ptr = mxGetData(impl_dae_hess_mat); - l_ptr[0] = (long long) acados_ocp_capsule->impl_dae_hess; -{%- endif %} -{% elif solver_options.integrator_type == "GNSF" %} - {% if model.gnsf.purely_linear != 1 %} - l_ptr = mxGetData(gnsf_phi_fun_mat); - l_ptr[0] = (long long) acados_ocp_capsule->gnsf_phi_fun; - l_ptr = mxGetData(gnsf_phi_fun_jac_y_mat); - l_ptr[0] = (long long) acados_ocp_capsule->gnsf_phi_fun_jac_y; - l_ptr = mxGetData(gnsf_phi_jac_y_uhat_mat); - l_ptr[0] = (long long) acados_ocp_capsule->gnsf_phi_jac_y_uhat; - {% if model.gnsf.nontrivial_f_LO == 1 %} - l_ptr = mxGetData(gnsf_f_lo_jac_x1_x1dot_u_z_mat); - l_ptr[0] = (long long) acados_ocp_capsule->gnsf_f_lo_jac_x1_x1dot_u_z; - {%- endif %} - {%- endif %} - l_ptr = mxGetData(gnsf_get_matrices_fun_mat); - l_ptr[0] = (long long) acados_ocp_capsule->gnsf_get_matrices_fun; -{% elif solver_options.integrator_type == "DISCRETE" %} - l_ptr = mxGetData(disc_phi_fun_mat); - l_ptr[0] = (long long) acados_ocp_capsule->discr_dyn_phi_fun; - l_ptr = mxGetData(disc_phi_fun_jac_mat); - l_ptr[0] = (long long) acados_ocp_capsule->discr_dyn_phi_fun_jac_ut_xt; -{% if solver_options.hessian_approx == "EXACT" %} - l_ptr = mxGetData(disc_phi_fun_jac_hess_mat); - l_ptr[0] = (long long) acados_ocp_capsule->discr_dyn_phi_fun_jac_ut_xt_hess; -{%- endif %} -{%- endif %} - mxSetField(plhs[1], 0, "expl_ode_fun", expl_ode_fun_mat); - mxSetField(plhs[1], 0, "forw_vde", forw_vde_mat); - mxSetField(plhs[1], 0, "hess_vde", hess_vde_mat); - - mxSetField(plhs[1], 0, "gnsf_phi_fun", gnsf_phi_fun_mat); - mxSetField(plhs[1], 0, "gnsf_phi_fun_jac_y", gnsf_phi_fun_jac_y_mat); - mxSetField(plhs[1], 0, "gnsf_phi_jac_y_uhat", gnsf_phi_jac_y_uhat_mat); - mxSetField(plhs[1], 0, "gnsf_f_lo_jac_x1_x1dot_u_z", gnsf_f_lo_jac_x1_x1dot_u_z_mat); - mxSetField(plhs[1], 0, "gnsf_get_matrices_fun", gnsf_get_matrices_fun_mat); - - mxSetField(plhs[1], 0, "impl_dae_fun", impl_dae_fun_mat); - mxSetField(plhs[1], 0, "impl_dae_fun_jac_x_xdot_z", impl_dae_fun_jac_x_xdot_z_mat); - mxSetField(plhs[1], 0, "impl_dae_jac_x_xdot_u_z", impl_dae_jac_x_xdot_u_z_mat); - mxSetField(plhs[1], 0, "impl_dae_hess", impl_dae_hess_mat); - - mxSetField(plhs[1], 0, "disc_phi_fun", disc_phi_fun_mat); - mxSetField(plhs[1], 0, "disc_phi_fun_jac", disc_phi_fun_jac_mat); - mxSetField(plhs[1], 0, "disc_phi_fun_jac_hess", disc_phi_fun_jac_hess_mat); -/* constaints */ - mxArray *phi_constraint_mat = mxCreateNumericMatrix(1, 2, mxINT64_CLASS, mxREAL); - l_ptr = mxGetData(phi_constraint_mat); -{%- if constraints.constr_type == "BGP" %} - l_ptr[0] = (long long) acados_ocp_capsule->phi_constraint; -{% endif %} -{% if constraints.constr_type_e == "BGP" %} - l_ptr[1] = (long long) &acados_ocp_capsule->phi_e_constraint; -{% endif %} - mxSetField(plhs[1], 0, "phi_constraint", phi_constraint_mat); - - mxArray *nl_constr_h_fun_jac_mat = mxCreateNumericMatrix(1, 2, mxINT64_CLASS, mxREAL); - l_ptr = mxGetData(nl_constr_h_fun_jac_mat); -{% if constraints.constr_type == "BGH" and dims.nh > 0 %} - l_ptr[0] = (long long) acados_ocp_capsule->nl_constr_h_fun_jac; -{% endif %} -{% if constraints.constr_type_e == "BGH" and dims.nh_e > 0 %} - l_ptr[1] = (long long) &acados_ocp_capsule->nl_constr_h_e_fun_jac; -{%- endif %} - mxSetField(plhs[1], 0, "nl_constr_h_fun_jac", nl_constr_h_fun_jac_mat); - - mxArray *nl_constr_h_fun_mat = mxCreateNumericMatrix(1, 2, mxINT64_CLASS, mxREAL); - l_ptr = mxGetData(nl_constr_h_fun_mat); -{% if constraints.constr_type == "BGH" and dims.nh > 0 %} - l_ptr[0] = (long long) acados_ocp_capsule->nl_constr_h_fun; -{% endif %} -{% if constraints.constr_type_e == "BGH" and dims.nh_e > 0 %} - l_ptr[1] = (long long) &acados_ocp_capsule->nl_constr_h_e_fun; -{%- endif %} - mxSetField(plhs[1], 0, "nl_constr_h_fun", nl_constr_h_fun_mat); - - mxArray *nl_constr_h_fun_jac_hess_mat = mxCreateNumericMatrix(1, 2, mxINT64_CLASS, mxREAL); - l_ptr = mxGetData(nl_constr_h_fun_jac_hess_mat); -{% if constraints.constr_type == "BGH" and dims.nh > 0 and solver_options.hessian_approx == "EXACT" %} - l_ptr[0] = (long long) acados_ocp_capsule->nl_constr_h_fun_jac_hess; -{% endif %} -{% if constraints.constr_type_e == "BGH" and dims.nh_e > 0 and solver_options.hessian_approx == "EXACT" %} - l_ptr[1] = (long long) &acados_ocp_capsule->nl_constr_h_e_fun_jac_hess; -{%- endif %} - mxSetField(plhs[1], 0, "nl_constr_h_fun_jac_hess", nl_constr_h_fun_jac_hess_mat); - -/* cost */ - mxArray *cost_y_fun_mat = mxCreateNumericMatrix(1, 2, mxINT64_CLASS, mxREAL); - l_ptr = mxGetData(cost_y_fun_mat); -{% if cost.cost_type == "NONLINEAR_LS" %} - l_ptr[0] = (long long) acados_ocp_capsule->cost_y_fun; -{% endif %} -{% if cost.cost_type_e == "NONLINEAR_LS" %} - l_ptr[1] = (long long) &acados_ocp_capsule->cost_y_e_fun; -{%- endif %} - mxSetField(plhs[1], 0, "cost_y_fun", cost_y_fun_mat); - - mxArray *cost_y_fun_jac_ut_xt_mat = mxCreateNumericMatrix(1, 2, mxINT64_CLASS, mxREAL); - l_ptr = mxGetData(cost_y_fun_jac_ut_xt_mat); -{% if cost.cost_type == "NONLINEAR_LS" %} - l_ptr[0] = (long long) acados_ocp_capsule->cost_y_fun_jac_ut_xt; -{% endif %} -{% if cost.cost_type_e == "NONLINEAR_LS" %} - l_ptr[1] = (long long) &acados_ocp_capsule->cost_y_e_fun_jac_ut_xt; -{%- endif %} - mxSetField(plhs[1], 0, "cost_y_fun_jac_ut_xt", cost_y_fun_jac_ut_xt_mat); - - mxArray *cost_y_hess_mat = mxCreateNumericMatrix(1, 2, mxINT64_CLASS, mxREAL); - l_ptr = mxGetData(cost_y_hess_mat); -{% if cost.cost_type == "NONLINEAR_LS" %} - l_ptr[0] = (long long) acados_ocp_capsule->cost_y_hess; -{% endif %} -{% if cost.cost_type_e == "NONLINEAR_LS" %} - l_ptr[1] = (long long) &acados_ocp_capsule->cost_y_e_hess; -{%- endif %} - mxSetField(plhs[1], 0, "cost_y_hess", cost_y_hess_mat); - - mxArray *ext_cost_fun_mat = mxCreateNumericMatrix(1, 2, mxINT64_CLASS, mxREAL); - l_ptr = mxGetData(ext_cost_fun_mat); -{% if cost.cost_type == "EXTERNAL" %} - l_ptr[0] = (long long) acados_ocp_capsule->ext_cost_fun; -{% endif -%} -{% if cost.cost_type_e == "EXTERNAL" %} - l_ptr[1] = (long long) &acados_ocp_capsule->ext_cost_e_fun; -{%- endif %} - mxSetField(plhs[1], 0, "ext_cost_fun", ext_cost_fun_mat); - - mxArray *ext_cost_fun_jac_mat = mxCreateNumericMatrix(1, 2, mxINT64_CLASS, mxREAL); - l_ptr = mxGetData(ext_cost_fun_jac_mat); -{% if cost.cost_type == "EXTERNAL" %} - l_ptr[0] = (long long) acados_ocp_capsule->ext_cost_fun_jac; -{% endif -%} -{% if cost.cost_type_e == "EXTERNAL" %} - l_ptr[1] = (long long) &acados_ocp_capsule->ext_cost_e_fun_jac; -{%- endif %} - mxSetField(plhs[1], 0, "ext_cost_fun_jac", ext_cost_fun_jac_mat); - - mxArray *ext_cost_fun_jac_hess_mat = mxCreateNumericMatrix(1, 2, mxINT64_CLASS, mxREAL); - l_ptr = mxGetData(ext_cost_fun_jac_hess_mat); -{% if cost.cost_type == "EXTERNAL" %} - l_ptr[0] = (long long) acados_ocp_capsule->ext_cost_fun_jac_hess; -{% endif -%} -{% if cost.cost_type_e == "EXTERNAL" %} - l_ptr[1] = (long long) &acados_ocp_capsule->ext_cost_e_fun_jac_hess; -{%- endif %} - mxSetField(plhs[1], 0, "ext_cost_fun_jac_hess", ext_cost_fun_jac_hess_mat); - - - return; -} diff --git a/third_party/acados/acados_template/c_templates_tera/matlab_templates/acados_mex_free.in.c b/third_party/acados/acados_template/c_templates_tera/matlab_templates/acados_mex_free.in.c deleted file mode 100644 index bd457969b2..0000000000 --- a/third_party/acados/acados_template/c_templates_tera/matlab_templates/acados_mex_free.in.c +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - -// system -#include -#include -#include -// acados -#include "acados_solver_{{ model.name }}.h" - -// mex -#include "mex.h" - - -void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) -{ - int status = 0; - long long *ptr; - - // mexPrintf("\nin mex_acados_free\n"); - const mxArray *C_ocp = prhs[0]; - // capsule - ptr = (long long *) mxGetData( mxGetField( C_ocp, 0, "capsule" ) ); - {{ model.name }}_solver_capsule *capsule = ({{ model.name }}_solver_capsule *) ptr[0]; - - status = {{ model.name }}_acados_free(capsule); - if (status) - { - mexPrintf("{{ model.name }}_acados_free() returned status %d.\n", status); - } - - status = {{ model.name }}_acados_free_capsule(capsule); - if (status) - { - mexPrintf("{{ model.name }}_acados_free_capsule() returned status %d.\n", status); - } - - return; -} - diff --git a/third_party/acados/acados_template/c_templates_tera/matlab_templates/acados_mex_set.in.c b/third_party/acados/acados_template/c_templates_tera/matlab_templates/acados_mex_set.in.c deleted file mode 100644 index 78a308df49..0000000000 --- a/third_party/acados/acados_template/c_templates_tera/matlab_templates/acados_mex_set.in.c +++ /dev/null @@ -1,632 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -// standard -#include -#include -#include - -// acados -#include "acados/utils/print.h" -#include "acados_c/ocp_nlp_interface.h" -#include "acados_solver_{{ model.name }}.h" - -// mex -#include "mex.h" -#include "mex_macros.h" - - -void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) -{ - - long long *ptr; - int acados_size; - mxArray *mex_field; - char fun_name[20] = "ocp_set"; - char buffer [500]; // for error messages - - /* RHS */ - int min_nrhs = 6; - - // C ocp - const mxArray *C_ocp = prhs[2]; - // capsule - ptr = (long long *) mxGetData( mxGetField( C_ocp, 0, "capsule" ) ); - {{ model.name }}_solver_capsule *capsule = ({{ model.name }}_solver_capsule *) ptr[0]; - // plan - ptr = (long long *) mxGetData( mxGetField( C_ocp, 0, "plan" ) ); - ocp_nlp_plan_t *plan = (ocp_nlp_plan_t *) ptr[0]; - // config - ptr = (long long *) mxGetData( mxGetField( C_ocp, 0, "config" ) ); - ocp_nlp_config *config = (ocp_nlp_config *) ptr[0]; - // dims - ptr = (long long *) mxGetData( mxGetField( C_ocp, 0, "dims" ) ); - ocp_nlp_dims *dims = (ocp_nlp_dims *) ptr[0]; - // opts - ptr = (long long *) mxGetData( mxGetField( C_ocp, 0, "opts" ) ); - void *opts = (void *) ptr[0]; - // in - ptr = (long long *) mxGetData( mxGetField( C_ocp, 0, "in" ) ); - ocp_nlp_in *in = (ocp_nlp_in *) ptr[0]; - // out - ptr = (long long *) mxGetData( mxGetField( C_ocp, 0, "out" ) ); - ocp_nlp_out *out = (ocp_nlp_out *) ptr[0]; - // solver - ptr = (long long *) mxGetData( mxGetField( C_ocp, 0, "solver" ) ); - ocp_nlp_solver *solver = (ocp_nlp_solver *) ptr[0]; - - const mxArray *C_ext_fun_pointers = prhs[3]; - // field - char *field = mxArrayToString( prhs[4] ); - // value - double *value = mxGetPr( prhs[5] ); - - // for checks - int matlab_size = (int) mxGetNumberOfElements( prhs[5] ); - int nrow = (int) mxGetM( prhs[5] ); - int ncol = (int) mxGetN( prhs[5] ); - - int N = dims->N; - int nu = dims->nu[0]; - int nx = dims->nx[0]; - - // stage - int s0, se; - if (nrhs==min_nrhs) - { - s0 = 0; - se = N; - } - else if (nrhs==min_nrhs+1) - { - s0 = mxGetScalar( prhs[6] ); - if (s0 > N) - { - sprintf(buffer, "ocp_set: N < specified stage = %d\n", s0); - mexErrMsgTxt(buffer); - } - se = s0 + 1; - } - else - { - sprintf(buffer, "ocp_set: wrong nrhs: %d\n", nrhs); - mexErrMsgTxt(buffer); - } - - /* Set value */ - // constraints - if (!strcmp(field, "constr_x0")) - { - acados_size = nx; - MEX_DIM_CHECK_VEC(fun_name, field, matlab_size, acados_size); - ocp_nlp_constraints_model_set(config, dims, in, 0, "lbx", value); - ocp_nlp_constraints_model_set(config, dims, in, 0, "ubx", value); - } - else if (!strcmp(field, "constr_C")) - { - for (int ii=s0; iinlp_cost[ii] == LINEAR_LS) || (plan->nlp_cost[ii] == NONLINEAR_LS)) - { - acados_size = ocp_nlp_dims_get_from_attr(config, dims, out, ii, "y_ref"); - MEX_DIM_CHECK_VEC(fun_name, field, matlab_size, acados_size); - ocp_nlp_cost_model_set(config, dims, in, ii, "y_ref", value); - } - else - { - MEX_FIELD_NOT_SUPPORTED_FOR_COST_STAGE(fun_name, field, plan->nlp_cost[ii], ii); - } - } - } - else if (!strcmp(field, "cost_y_ref_e")) - { - acados_size = ocp_nlp_dims_get_from_attr(config, dims, out, N, "y_ref"); - MEX_DIM_CHECK_VEC(fun_name, field, matlab_size, acados_size); - ocp_nlp_cost_model_set(config, dims, in, N, "y_ref", value); - } - else if (!strcmp(field, "cost_Vu")) - { - for (int ii=s0; iinlp_cost[ii] == LINEAR_LS) || (plan->nlp_cost[ii] == NONLINEAR_LS)) - { - int ny = ocp_nlp_dims_get_from_attr(config, dims, out, ii, "y_ref"); - int nu = ocp_nlp_dims_get_from_attr(config, dims, out, ii, "u"); - acados_size = ny * nu; - MEX_DIM_CHECK_VEC(fun_name, field, matlab_size, acados_size); - ocp_nlp_cost_model_set(config, dims, in, ii, "Vu", value); - } - else - { - MEX_FIELD_NOT_SUPPORTED_FOR_COST_STAGE(fun_name, field, plan->nlp_cost[ii], ii); - } - } - } - else if (!strcmp(field, "cost_Vx")) - { - for (int ii=s0; iinlp_cost[ii] == LINEAR_LS) || (plan->nlp_cost[ii] == NONLINEAR_LS)) - { - int ny = ocp_nlp_dims_get_from_attr(config, dims, out, ii, "y_ref"); - int nx = ocp_nlp_dims_get_from_attr(config, dims, out, ii, "x"); - acados_size = ny * nx; - MEX_DIM_CHECK_VEC(fun_name, field, matlab_size, acados_size); - ocp_nlp_cost_model_set(config, dims, in, ii, "Vx", value); - } - else - { - MEX_FIELD_NOT_SUPPORTED_FOR_COST_STAGE(fun_name, field, plan->nlp_cost[ii], ii); - } - } - } - else if (!strcmp(field, "cost_W")) - { - for (int ii=s0; iinlp_cost[ii] == LINEAR_LS) || (plan->nlp_cost[ii] == NONLINEAR_LS)) - { - int ny = ocp_nlp_dims_get_from_attr(config, dims, out, s0, "y_ref"); - acados_size = ny * ny; - MEX_DIM_CHECK_VEC(fun_name, field, matlab_size, acados_size); - ocp_nlp_cost_model_set(config, dims, in, ii, "W", value); - } - else - { - MEX_FIELD_NOT_SUPPORTED_FOR_COST_STAGE(fun_name, field, plan->nlp_cost[ii], ii); - } - } - } - else if (!strcmp(field, "cost_Z")) - { - acados_size = ocp_nlp_dims_get_from_attr(config, dims, out, s0, "cost_Z"); - MEX_DIM_CHECK_VEC(fun_name, field, matlab_size, acados_size); - for (int ii=s0; iisim_solver_plan[0]; - sim_solver_t type = sim_plan.sim_solver; - if (type == IRK) - { - int nz = ocp_nlp_dims_get_from_attr(config, dims, out, 0, "z"); - if (nrhs==min_nrhs) - { - acados_size = N*nz; - MEX_DIM_CHECK_VEC(fun_name, field, matlab_size, acados_size); - for (int ii=0; iisim_solver_plan[0]; - sim_solver_t type = sim_plan.sim_solver; - if (type == IRK) - { - int nx = ocp_nlp_dims_get_from_attr(config, dims, out, 0, "x"); - if (nrhs==min_nrhs) - { - acados_size = N*nx; - MEX_DIM_CHECK_VEC(fun_name, field, matlab_size, acados_size); - for (int ii=0; iisim_solver_plan[0]; - sim_solver_t type = sim_plan.sim_solver; - if (type == GNSF) - { - int nout = ocp_nlp_dims_get_from_attr(config, dims, out, 0, "init_gnsf_phi"); - - if (nrhs==min_nrhs) - { - acados_size = N*nout; - MEX_DIM_CHECK_VEC(fun_name, field, matlab_size, acados_size); - for (int ii=0; iinlp_solver == SQP && rti_phase != 0) - { - MEX_FIELD_ONLY_SUPPORTED_FOR_SOLVER(fun_name, field, "sqp_rti") - } - ocp_nlp_solver_opts_set(config, opts, "rti_phase", &rti_phase); - } - else if (!strcmp(field, "qp_warm_start")) - { - acados_size = 1; - MEX_DIM_CHECK_VEC(fun_name, field, matlab_size, acados_size); - int qp_warm_start = (int) value[0]; - ocp_nlp_solver_opts_set(config, opts, "qp_warm_start", &qp_warm_start); - } - else if (!strcmp(field, "warm_start_first_qp")) - { - acados_size = 1; - MEX_DIM_CHECK_VEC(fun_name, field, matlab_size, acados_size); - int warm_start_first_qp = (int) value[0]; - ocp_nlp_solver_opts_set(config, opts, "warm_start_first_qp", &warm_start_first_qp); - } - else if (!strcmp(field, "print_level")) - { - acados_size = 1; - MEX_DIM_CHECK_VEC(fun_name, field, matlab_size, acados_size); - int print_level = (int) value[0]; - ocp_nlp_solver_opts_set(config, opts, "print_level", &print_level); - } - else - { - MEX_FIELD_NOT_SUPPORTED_SUGGEST(fun_name, field, "p, constr_x0,\ - constr_lbx, constr_ubx, constr_C, constr_D, constr_lg, constr_ug, constr_lh, constr_uh,\ - constr_lbu, constr_ubu, cost_y_ref[_e], sl, su, x, xdot, u, pi, lam, z, \ - cost_Vu, cost_Vx, cost_Vz, cost_W, cost_Z, cost_Zl, cost_Zu, cost_z,\ - cost_zl, cost_zu, init_x, init_u, init_z, init_xdot, init_gnsf_phi,\ - init_pi, nlp_solver_max_iter, qp_warm_start, warm_start_first_qp, print_level"); - } - - return; -} - diff --git a/third_party/acados/acados_template/c_templates_tera/matlab_templates/acados_mex_solve.in.c b/third_party/acados/acados_template/c_templates_tera/matlab_templates/acados_mex_solve.in.c deleted file mode 100644 index 300a440cc9..0000000000 --- a/third_party/acados/acados_template/c_templates_tera/matlab_templates/acados_mex_solve.in.c +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - -// system -#include -#include -#include -// acados -#include "acados_solver_{{ model.name }}.h" - -// mex -#include "mex.h" - - - -void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) -{ - // C_ocp - long long *ptr; - const mxArray *C_ocp = prhs[0]; - - // capsule - ptr = (long long *) mxGetData( mxGetField( C_ocp, 0, "capsule" ) ); - {{ model.name }}_solver_capsule *capsule = ({{ model.name }}_solver_capsule *) ptr[0]; - - // solve - {{ model.name }}_acados_solve(capsule); - -} diff --git a/third_party/acados/acados_template/c_templates_tera/matlab_templates/acados_sim_solver_sfun.in.c b/third_party/acados/acados_template/c_templates_tera/matlab_templates/acados_sim_solver_sfun.in.c deleted file mode 100644 index bd73ff69a4..0000000000 --- a/third_party/acados/acados_template/c_templates_tera/matlab_templates/acados_sim_solver_sfun.in.c +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - -#define S_FUNCTION_NAME acados_sim_solver_sfunction_{{ model.name }} -#define S_FUNCTION_LEVEL 2 - -#define MDL_START - -// acados -// #include "acados/utils/print.h" -#include "acados_c/ocp_nlp_interface.h" -#include "acados_c/external_function_interface.h" - -// example specific -#include "{{ model.name }}_model/{{ model.name }}_model.h" -#include "acados_sim_solver_{{ model.name }}.h" - -#include "simstruc.h" - -#define SAMPLINGTIME {{ solver_options.Tsim }} - - -static void mdlInitializeSizes (SimStruct *S) -{ - // specify the number of continuous and discrete states - ssSetNumContStates(S, 0); - ssSetNumDiscStates(S, 0); - - {# compute number of input ports #} - {%- set n_inputs = 1 %} {# x0 #} - {%- if dims.nu > 0 %} {# u0 -#} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif %} - {%- if dims.np > 0 %} {# parameters #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif %} - - // specify the number of input ports - if ( !ssSetNumInputPorts(S, {{ n_inputs }}) ) - return; - - // specify the number of output ports - if ( !ssSetNumOutputPorts(S, 1) ) - return; - - // specify dimension information for the input ports - {%- set i_input = 0 %} - // x0 - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.nx }}); - - {%- if dims.nu > 0 %} - {%- set i_input = i_input + 1 %} - // u0 - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.nu }}); - {%- endif %} - - {%- if dims.np > 0 %} - {%- set i_input = i_input + 1 %} - // parameters - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.np }}); - {%- endif %} - - // specify dimension information for the output ports - ssSetOutputPortVectorDimension(S, 0, {{ dims.nx }} ); // xnext - - // specify the direct feedthrough status - // should be set to 1 for all inputs used in mdlOutputs - {%- for i in range(end=n_inputs) %} - ssSetInputPortDirectFeedThrough(S, {{ i }}, 1); - {%- endfor %} - - // one sample time - ssSetNumSampleTimes(S, 1); -} - - -#if defined(MATLAB_MEX_FILE) - -#define MDL_SET_INPUT_PORT_DIMENSION_INFO -#define MDL_SET_OUTPUT_PORT_DIMENSION_INFO - -static void mdlSetInputPortDimensionInfo(SimStruct *S, int_T port, const DimsInfo_T *dimsInfo) -{ - if ( !ssSetInputPortDimensionInfo(S, port, dimsInfo) ) - return; -} - -static void mdlSetOutputPortDimensionInfo(SimStruct *S, int_T port, const DimsInfo_T *dimsInfo) -{ - if ( !ssSetOutputPortDimensionInfo(S, port, dimsInfo) ) - return; -} - -#endif /* MATLAB_MEX_FILE */ - - -static void mdlInitializeSampleTimes(SimStruct *S) -{ - ssSetSampleTime(S, 0, SAMPLINGTIME); - ssSetOffsetTime(S, 0, 0.0); -} - - -static void mdlStart(SimStruct *S) -{ - sim_solver_capsule *capsule = {{ model.name }}_acados_sim_solver_create_capsule(); - {{ model.name }}_acados_sim_create(capsule); - - ssSetUserData(S, (void*)capsule); -} - -static void mdlOutputs(SimStruct *S, int_T tid) -{ - sim_solver_capsule *capsule = ssGetUserData(S); - - sim_config *acados_sim_config = {{ model.name }}_acados_get_sim_config(capsule); - sim_in *acados_sim_in = {{ model.name }}_acados_get_sim_in(capsule); - sim_out *acados_sim_out = {{ model.name }}_acados_get_sim_out(capsule); - void *acados_sim_dims = {{ model.name }}_acados_get_sim_dims(capsule); - // sim_opts * {{ model.name }}_acados_get_sim_opts(capsule); - // sim_solver * {{ model.name }}_acados_get_sim_solver(capsule); - - InputRealPtrsType in_sign; - {% set input_sizes = [dims.nx, dims.nu, dims.np] %} - - // local buffer - {%- set buffer_size = input_sizes | sort | last %} - real_t buffer[{{ buffer_size }}]; - - - /* go through inputs */ - {%- set i_input = 0 %} - // initial condition - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - for (int i = 0; i < {{ dims.nx }}; i++) - buffer[i] = (double)(*in_sign[i]); - - sim_in_set(acados_sim_config, acados_sim_dims, - acados_sim_in, "x", buffer); - - - // ssPrintf("\nin acados sim:\n"); - // for (int i = 0; i < {{ dims.nx }}; i++) ssPrintf("x0[%d] = %f\n", i, buffer[i]); - // ssPrintf("\n"); - -{% if dims.nu > 0 %} - // control input - u - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - - for (int i = 0; i < {{ dims.nu }}; i++) - buffer[i] = (double)(*in_sign[i]); - - sim_in_set(acados_sim_config, acados_sim_dims, - acados_sim_in, "u", buffer); -{%- endif %} - - -{% if dims.np > 0 %} - // parameters - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - - for (int i = 0; i < {{ dims.np }}; i++) - buffer[i] = (double)(*in_sign[i]); - - // update value of parameters - {{ model.name }}_acados_sim_update_params(capsule, buffer, {{ dims.np }}); -{%- endif %} - - - /* call solver */ - int acados_status = {{ model.name }}_acados_sim_solve(capsule); - - - /* set outputs */ - real_t *out_x = ssGetOutputPortRealSignal(S, 0); - - // get simulated state - sim_out_get(acados_sim_config, acados_sim_dims, acados_sim_out, - "xn", (void *) out_x); - - // ssPrintf("\nacados sim solve: returned %d\n", acados_status); - // for (int i = 0; i < {{ dims.nx }}; i++) ssPrintf("x_sim[%d] = %f\n", i, out_x[i]); - // ssPrintf("\n"); - -} - - -static void mdlTerminate(SimStruct *S) -{ - sim_solver_capsule *capsule = ssGetUserData(S); - - {{ model.name }}_acados_sim_free(capsule); - {{ model.name }}_acados_sim_solver_free_capsule(capsule); -} - - -#ifdef MATLAB_MEX_FILE -#include "simulink.c" -#else -#include "cg_sfun.h" -#endif diff --git a/third_party/acados/acados_template/c_templates_tera/matlab_templates/acados_solver_sfun.in.c b/third_party/acados/acados_template/c_templates_tera/matlab_templates/acados_solver_sfun.in.c deleted file mode 100644 index 3dd248037a..0000000000 --- a/third_party/acados/acados_template/c_templates_tera/matlab_templates/acados_solver_sfun.in.c +++ /dev/null @@ -1,853 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - -#define S_FUNCTION_NAME acados_solver_sfunction_{{ model.name }} -#define S_FUNCTION_LEVEL 2 - -#define MDL_START - -// acados -// #include "acados/utils/print.h" -#include "acados_c/sim_interface.h" -#include "acados_c/external_function_interface.h" - -// example specific -#include "{{ model.name }}_model/{{ model.name }}_model.h" -#include "acados_solver_{{ model.name }}.h" - -#include "simstruc.h" - -{% if simulink_opts.samplingtime == "t0" -%} -#define SAMPLINGTIME {{ solver_options.time_steps[0] }} -{%- elif simulink_opts.samplingtime == "-1" -%} -#define SAMPLINGTIME -1 -{%- else -%} - {{ throw(message = "simulink_opts.samplingtime must be '-1' or 't0', got val") }} -{%- endif %} - -static void mdlInitializeSizes (SimStruct *S) -{ - // specify the number of continuous and discrete states - ssSetNumContStates(S, 0); - ssSetNumDiscStates(S, 0); - - int N = {{ model.name | upper }}_N; - - {%- for key, val in simulink_opts.inputs -%} - {%- if val != 0 and val != 1 -%} - {{ throw(message = "simulink_opts.inputs must be 0 or 1, got val") }} - {%- endif -%} - {%- endfor -%} - - {#- compute number of input ports #} - {%- set n_inputs = 0 -%} - {%- if dims.nbx_0 > 0 and simulink_opts.inputs.lbx_0 -%} {#- lbx_0 #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - {%- if dims.nbx_0 > 0 and simulink_opts.inputs.ubx_0 -%} {#- ubx_0 #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - {%- if dims.np > 0 and simulink_opts.inputs.parameter_traj -%} {#- parameter_traj #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - {%- if dims.ny_0 > 0 and simulink_opts.inputs.y_ref_0 -%} {#- y_ref_0 -#} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - {%- if dims.ny > 0 and dims.N > 1 and simulink_opts.inputs.y_ref -%} {#- y_ref -#} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - {%- if dims.ny_e > 0 and dims.N > 0 and simulink_opts.inputs.y_ref_e -%} {#- y_ref_e #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - {%- if dims.nbx > 0 and dims.N > 1 and simulink_opts.inputs.lbx -%} {#- lbx #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - {%- if dims.nbx > 0 and dims.N > 1 and simulink_opts.inputs.ubx -%} {#- ubx #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - {%- if dims.nbx_e > 0 and dims.N > 0 and simulink_opts.inputs.lbx_e -%} {#- lbx_e #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - {%- if dims.nbx_e > 0 and dims.N > 0 and simulink_opts.inputs.ubx_e -%} {#- ubx_e #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - {%- if dims.nbu > 0 and dims.N > 0 and simulink_opts.inputs.lbu -%} {#- lbu #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - {%- if dims.nbu > 0 and dims.N > 0 and simulink_opts.inputs.ubu -%} {#- ubu #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - {%- if dims.ng > 0 and simulink_opts.inputs.lg -%} {#- lg #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - {%- if dims.ng > 0 and simulink_opts.inputs.ug -%} {#- ug #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - {%- if dims.nh > 0 and simulink_opts.inputs.lh -%} {#- lh #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - {%- if dims.nh > 0 and simulink_opts.inputs.uh -%} {#- uh #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - {%- if dims.nh_e > 0 and simulink_opts.inputs.lh_e -%} {#- lh_e #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - {%- if dims.nh_e > 0 and simulink_opts.inputs.uh_e -%} {#- uh_e #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - - {%- for key, val in simulink_opts.inputs -%} - {%- if val != 0 and val != 1 -%} - {{ throw(message = "simulink_opts.inputs must be 0 or 1, got val") }} - {%- endif -%} - {%- endfor -%} - {%- if dims.ny_0 > 0 and simulink_opts.inputs.cost_W_0 %} {#- cost_W_0 #} - {%- set n_inputs = n_inputs + 1 %} - {%- endif -%} - {%- if dims.ny > 0 and simulink_opts.inputs.cost_W %} {#- cost_W #} - {%- set n_inputs = n_inputs + 1 %} - {%- endif -%} - {%- if dims.ny_e > 0 and simulink_opts.inputs.cost_W_e %} {#- cost_W_e #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - - {%- if simulink_opts.inputs.reset_solver -%} {#- reset_solver #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - - {%- if simulink_opts.inputs.x_init -%} {#- x_init #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - - {%- if simulink_opts.inputs.u_init -%} {#- u_init #} - {%- set n_inputs = n_inputs + 1 -%} - {%- endif -%} - - // specify the number of input ports - if ( !ssSetNumInputPorts(S, {{ n_inputs }}) ) - return; - - // specify the number of output ports - {%- set_global n_outputs = 0 %} - {%- for key, val in simulink_opts.outputs %} - {%- if val == 1 %} - {%- set_global n_outputs = n_outputs + val %} - {%- elif val != 0 %} - {{ throw(message = "simulink_opts.outputs must be 0 or 1, got val") }} - {%- endif %} - {%- endfor %} - if ( !ssSetNumOutputPorts(S, {{ n_outputs }}) ) - return; - - // specify dimension information for the input ports - {%- set i_input = -1 %}{# note here i_input is 0-based #} - {%- if dims.nbx_0 > 0 and simulink_opts.inputs.lbx_0 -%} {#- lbx_0 #} - {%- set i_input = i_input + 1 %} - // lbx_0 - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.nbx_0 }}); - {%- endif %} - {%- if dims.nbx_0 > 0 and simulink_opts.inputs.ubx_0 -%} {#- ubx_0 #} - {%- set i_input = i_input + 1 %} - // ubx_0 - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.nbx_0 }}); - {%- endif %} - - {%- if dims.np > 0 and simulink_opts.inputs.parameter_traj -%} {#- parameter_traj #} - {%- set i_input = i_input + 1 %} - // parameters - ssSetInputPortVectorDimension(S, {{ i_input }}, (N+1) * {{ dims.np }}); - {%- endif %} - - {%- if dims.ny > 0 and simulink_opts.inputs.y_ref_0 %} - {%- set i_input = i_input + 1 %} - // y_ref_0 - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.ny_0 }}); - {%- endif %} - - {%- if dims.ny > 0 and dims.N > 1 and simulink_opts.inputs.y_ref %} - {%- set i_input = i_input + 1 %} - // y_ref - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ (dims.N-1) * dims.ny }}); - {%- endif %} - - {%- if dims.ny_e > 0 and dims.N > 0 and simulink_opts.inputs.y_ref_e %} - {%- set i_input = i_input + 1 %} - // y_ref_e - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.ny_e }}); - {%- endif %} - - {%- if dims.nbx > 0 and dims.N > 1 and simulink_opts.inputs.lbx -%} {#- lbx #} - {%- set i_input = i_input + 1 %} - // lbx - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ (dims.N-1) * dims.nbx }}); - {%- endif %} - {%- if dims.nbx > 0 and dims.N > 1 and simulink_opts.inputs.ubx -%} {#- ubx #} - {%- set i_input = i_input + 1 %} - // ubx - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ (dims.N-1) * dims.nbx }}); - {%- endif %} - - {%- if dims.nbx_e > 0 and dims.N > 0 and simulink_opts.inputs.lbx_e -%} {#- lbx_e #} - {%- set i_input = i_input + 1 %} - // lbx_e - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.nbx_e }}); - {%- endif %} - {%- if dims.nbx_e > 0 and dims.N > 0 and simulink_opts.inputs.ubx_e -%} {#- ubx_e #} - {%- set i_input = i_input + 1 %} - // ubx_e - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.nbx_e }}); - {%- endif %} - - {%- if dims.nbu > 0 and dims.N > 0 and simulink_opts.inputs.lbu -%} {#- lbu #} - {%- set i_input = i_input + 1 %} - // lbu - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.N*dims.nbu }}); - {%- endif -%} - {%- if dims.nbu > 0 and dims.N > 0 and simulink_opts.inputs.ubu -%} {#- ubu #} - {%- set i_input = i_input + 1 %} - // ubu - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.N*dims.nbu }}); - {%- endif -%} - - - {%- if dims.ng > 0 and simulink_opts.inputs.lg -%} {#- lg #} - {%- set i_input = i_input + 1 %} - // lg - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.N*dims.ng }}); - {%- endif -%} - {%- if dims.ng > 0 and simulink_opts.inputs.ug -%} {#- ug #} - {%- set i_input = i_input + 1 %} - // ug - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.N*dims.ng }}); - {%- endif -%} - - {%- if dims.nh > 0 and simulink_opts.inputs.lh -%} {#- lh #} - {%- set i_input = i_input + 1 %} - // lh - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.N*dims.nh }}); - {%- endif -%} - {%- if dims.nh > 0 and simulink_opts.inputs.uh -%} {#- uh #} - {%- set i_input = i_input + 1 %} - // uh - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.N*dims.nh }}); - {%- endif -%} - - {%- if dims.nh_e > 0 and simulink_opts.inputs.lh_e -%} {#- lh_e #} - {%- set i_input = i_input + 1 %} - // lh_e - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.nh_e }}); - {%- endif -%} - {%- if dims.nh_e > 0 and simulink_opts.inputs.uh_e -%} {#- uh_e #} - {%- set i_input = i_input + 1 %} - // uh_e - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.nh_e }}); - {%- endif -%} - - {%- if dims.ny_0 > 0 and simulink_opts.inputs.cost_W_0 %} {#- cost_W_0 #} - {%- set i_input = i_input + 1 %} - // cost_W_0 - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.ny_0 * dims.ny_0 }}); - {%- endif %} - - {%- if dims.ny > 0 and simulink_opts.inputs.cost_W %} {#- cost_W #} - {%- set i_input = i_input + 1 %} - // cost_W - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.ny * dims.ny }}); - {%- endif %} - - {%- if dims.ny_e > 0 and simulink_opts.inputs.cost_W_e %} {#- cost_W_e #} - {%- set i_input = i_input + 1 %} - // cost_W_e - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.ny_e * dims.ny_e }}); - {%- endif %} - - {%- if simulink_opts.inputs.reset_solver -%} {#- reset_solver #} - {%- set i_input = i_input + 1 %} - // reset_solver - ssSetInputPortVectorDimension(S, {{ i_input }}, 1); - {%- endif -%} - - {%- if simulink_opts.inputs.x_init -%} {#- x_init #} - {%- set i_input = i_input + 1 %} - // x_init - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.nx * (dims.N+1) }}); - {%- endif -%} - - {%- if simulink_opts.inputs.u_init -%} {#- u_init #} - {%- set i_input = i_input + 1 %} - // u_init - ssSetInputPortVectorDimension(S, {{ i_input }}, {{ dims.nu * (dims.N) }}); - {%- endif -%} - - /* specify dimension information for the OUTPUT ports */ - {%- set i_output = -1 %}{# note here i_output is 0-based #} - {%- if dims.nu > 0 and simulink_opts.outputs.u0 == 1 %} - {%- set i_output = i_output + 1 %} - ssSetOutputPortVectorDimension(S, {{ i_output }}, {{ dims.nu }} ); - {%- endif %} - - {%- if simulink_opts.outputs.utraj == 1 %} - {%- set i_output = i_output + 1 %} - ssSetOutputPortVectorDimension(S, {{ i_output }}, {{ dims.nu * dims.N }} ); - {%- endif %} - - {%- if simulink_opts.outputs.xtraj == 1 %} - {%- set i_output = i_output + 1 %} - ssSetOutputPortVectorDimension(S, {{ i_output }}, {{ dims.nx * (dims.N+1) }} ); - {%- endif %} - - {%- if simulink_opts.outputs.solver_status == 1 %} - {%- set i_output = i_output + 1 %} - ssSetOutputPortVectorDimension(S, {{ i_output }}, 1 ); - {%- endif %} - - {%- if simulink_opts.outputs.cost_value == 1 %} - {%- set i_output = i_output + 1 %} - ssSetOutputPortVectorDimension(S, {{ i_output }}, 1 ); - {%- endif %} - - {%- if simulink_opts.outputs.KKT_residual == 1 %} - {%- set i_output = i_output + 1 %} - ssSetOutputPortVectorDimension(S, {{ i_output }}, 1 ); - {%- endif %} - - {%- if simulink_opts.outputs.KKT_residuals == 1 %} - {%- set i_output = i_output + 1 %} - ssSetOutputPortVectorDimension(S, {{ i_output }}, 4 ); - {%- endif %} - - {%- if dims.N > 0 and simulink_opts.outputs.x1 == 1 %} - {%- set i_output = i_output + 1 %} - ssSetOutputPortVectorDimension(S, {{ i_output }}, {{ dims.nx }} ); // state at shooting node 1 - {%- endif %} - - {%- if simulink_opts.outputs.CPU_time == 1 %} - {%- set i_output = i_output + 1 %} - ssSetOutputPortVectorDimension(S, {{ i_output }}, 1); - {%- endif %} - - {%- if simulink_opts.outputs.CPU_time_sim == 1 %} - {%- set i_output = i_output + 1 %} - ssSetOutputPortVectorDimension(S, {{ i_output }}, 1); - {%- endif %} - - {%- if simulink_opts.outputs.CPU_time_qp == 1 %} - {%- set i_output = i_output + 1 %} - ssSetOutputPortVectorDimension(S, {{ i_output }}, 1); - {%- endif %} - - {%- if simulink_opts.outputs.CPU_time_lin == 1 %} - {%- set i_output = i_output + 1 %} - ssSetOutputPortVectorDimension(S, {{ i_output }}, 1); - {%- endif %} - - {%- if simulink_opts.outputs.sqp_iter == 1 %} - {%- set i_output = i_output + 1 %} - ssSetOutputPortVectorDimension(S, {{ i_output }}, 1 ); - {%- endif %} - - // specify the direct feedthrough status - // should be set to 1 for all inputs used in mdlOutputs - {%- for i in range(end=n_inputs) %} - ssSetInputPortDirectFeedThrough(S, {{ i }}, 1); - {%- endfor %} - - // one sample time - ssSetNumSampleTimes(S, 1); -} - - -#if defined(MATLAB_MEX_FILE) - -#define MDL_SET_INPUT_PORT_DIMENSION_INFO -#define MDL_SET_OUTPUT_PORT_DIMENSION_INFO - -static void mdlSetInputPortDimensionInfo(SimStruct *S, int_T port, const DimsInfo_T *dimsInfo) -{ - if ( !ssSetInputPortDimensionInfo(S, port, dimsInfo) ) - return; -} - -static void mdlSetOutputPortDimensionInfo(SimStruct *S, int_T port, const DimsInfo_T *dimsInfo) -{ - if ( !ssSetOutputPortDimensionInfo(S, port, dimsInfo) ) - return; -} - -#endif /* MATLAB_MEX_FILE */ - - -static void mdlInitializeSampleTimes(SimStruct *S) -{ - ssSetSampleTime(S, 0, SAMPLINGTIME); - ssSetOffsetTime(S, 0, 0.0); -} - - -static void mdlStart(SimStruct *S) -{ - {{ model.name }}_solver_capsule *capsule = {{ model.name }}_acados_create_capsule(); - {{ model.name }}_acados_create(capsule); - - ssSetUserData(S, (void*)capsule); -} - - -static void mdlOutputs(SimStruct *S, int_T tid) -{ - {{ model.name }}_solver_capsule *capsule = ssGetUserData(S); - ocp_nlp_config *nlp_config = {{ model.name }}_acados_get_nlp_config(capsule); - ocp_nlp_dims *nlp_dims = {{ model.name }}_acados_get_nlp_dims(capsule); - ocp_nlp_in *nlp_in = {{ model.name }}_acados_get_nlp_in(capsule); - ocp_nlp_out *nlp_out = {{ model.name }}_acados_get_nlp_out(capsule); - - InputRealPtrsType in_sign; - - int N = {{ model.name | upper }}_N; - - {%- set buffer_sizes = [dims.nbx_0, dims.np, dims.nbx, dims.nbx_e, dims.nbu, dims.ng, dims.nh, dims.ng_e, dims.nh_e] -%} - - {%- if dims.ny_0 > 0 and simulink_opts.inputs.y_ref_0 %} {# y_ref_0 #} - {%- set buffer_sizes = buffer_sizes | concat(with=(dims.ny_0)) %} - {%- endif %} - {%- if dims.ny > 0 and dims.N > 1 and simulink_opts.inputs.y_ref %} {# y_ref #} - {%- set buffer_sizes = buffer_sizes | concat(with=(dims.ny)) %} - {%- endif %} - {%- if dims.ny_e > 0 and dims.N > 0 and simulink_opts.inputs.y_ref_e %} {# y_ref_e #} - {%- set buffer_sizes = buffer_sizes | concat(with=(dims.ny_e)) %} - {%- endif %} - - {%- if dims.ny_0 > 0 and simulink_opts.inputs.cost_W_0 %} {#- cost_W_0 #} - {%- set buffer_sizes = buffer_sizes | concat(with=(dims.ny_0 * dims.ny_0)) %} - {%- endif %} - {%- if dims.ny > 0 and simulink_opts.inputs.cost_W %} {#- cost_W #} - {%- set buffer_sizes = buffer_sizes | concat(with=(dims.ny * dims.ny)) %} - {%- endif %} - {%- if dims.ny_e > 0 and simulink_opts.inputs.cost_W_e %} {#- cost_W_e #} - {%- set buffer_sizes = buffer_sizes | concat(with=(dims.ny_e * dims.ny_e)) %} - {%- endif %} - - // local buffer - {%- set buffer_size = buffer_sizes | sort | last %} - real_t buffer[{{ buffer_size }}]; - - /* go through inputs */ - {%- set i_input = -1 %} - {%- if dims.nbx_0 > 0 and simulink_opts.inputs.lbx_0 -%} {#- lbx_0 #} - // lbx_0 - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - for (int i = 0; i < {{ dims.nbx_0 }}; i++) - buffer[i] = (double)(*in_sign[i]); - - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "lbx", buffer); - {%- endif %} - - {%- if dims.nbx_0 > 0 and simulink_opts.inputs.ubx_0 -%} {#- ubx_0 #} - // ubx_0 - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - for (int i = 0; i < {{ dims.nbx_0 }}; i++) - buffer[i] = (double)(*in_sign[i]); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "ubx", buffer); - {%- endif %} - - {%- if dims.np > 0 and simulink_opts.inputs.parameter_traj -%} {#- parameter_traj #} - // parameters - stage-variant !!! - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - - // update value of parameters - for (int ii = 0; ii <= N; ii++) - { - for (int jj = 0; jj < {{ dims.np }}; jj++) - buffer[jj] = (double)(*in_sign[ii*{{dims.np}}+jj]); - {{ model.name }}_acados_update_params(capsule, ii, buffer, {{ dims.np }}); - } - {%- endif %} - - {% if dims.ny_0 > 0 and simulink_opts.inputs.y_ref_0 %} - // y_ref_0 - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - - for (int i = 0; i < {{ dims.ny_0 }}; i++) - buffer[i] = (double)(*in_sign[i]); - - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "yref", (void *) buffer); - {%- endif %} - - {% if dims.ny > 0 and dims.N > 1 and simulink_opts.inputs.y_ref %} - // y_ref - for stages 1 to N-1 - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - - for (int ii = 1; ii < N; ii++) - { - for (int jj = 0; jj < {{ dims.ny }}; jj++) - buffer[jj] = (double)(*in_sign[(ii-1)*{{ dims.ny }}+jj]); - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, ii, "yref", (void *) buffer); - } - {%- endif %} - - {% if dims.ny_e > 0 and dims.N > 0 and simulink_opts.inputs.y_ref_e %} - // y_ref_e - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - - for (int i = 0; i < {{ dims.ny_e }}; i++) - buffer[i] = (double)(*in_sign[i]); - - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "yref", (void *) buffer); - {%- endif %} - - {%- if dims.nbx > 0 and dims.N > 1 and simulink_opts.inputs.lbx -%} {#- lbx #} - // lbx - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - for (int ii = 1; ii < N; ii++) - { - for (int jj = 0; jj < {{ dims.nbx }}; jj++) - buffer[jj] = (double)(*in_sign[(ii-1)*{{ dims.nbx }}+jj]); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, ii, "lbx", (void *) buffer); - } - {%- endif %} - {%- if dims.nbx > 0 and dims.N > 1 and simulink_opts.inputs.ubx -%} {#- ubx #} - // ubx - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - for (int ii = 1; ii < N; ii++) - { - for (int jj = 0; jj < {{ dims.nbx }}; jj++) - buffer[jj] = (double)(*in_sign[(ii-1)*{{ dims.nbx }}+jj]); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, ii, "ubx", (void *) buffer); - } - {%- endif %} - - - {%- if dims.nbx_e > 0 and dims.N > 0 and simulink_opts.inputs.lbx_e -%} {#- lbx_e #} - // lbx_e - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - - for (int i = 0; i < {{ dims.nbx_e }}; i++) - buffer[i] = (double)(*in_sign[i]); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lbx", buffer); - {%- endif %} - {%- if dims.nbx_e > 0 and dims.N > 0 and simulink_opts.inputs.ubx_e -%} {#- ubx_e #} - // ubx_e - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - - for (int i = 0; i < {{ dims.nbx_e }}; i++) - buffer[i] = (double)(*in_sign[i]); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "ubx", buffer); - {%- endif %} - - - {%- if dims.nbu > 0 and dims.N > 0 and simulink_opts.inputs.lbu -%} {#- lbu #} - // lbu - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - for (int ii = 0; ii < N; ii++) - { - for (int jj = 0; jj < {{ dims.nbu }}; jj++) - buffer[jj] = (double)(*in_sign[ii*{{ dims.nbu }}+jj]); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, ii, "lbu", (void *) buffer); - } - {%- endif -%} - {%- if dims.nbu > 0 and dims.N > 0 and simulink_opts.inputs.ubu -%} {#- ubu #} - // ubu - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - for (int ii = 0; ii < N; ii++) - { - for (int jj = 0; jj < {{ dims.nbu }}; jj++) - buffer[jj] = (double)(*in_sign[ii*{{ dims.nbu }}+jj]); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, ii, "ubu", (void *) buffer); - } - {%- endif -%} - - {%- if dims.ng > 0 and simulink_opts.inputs.lg -%} {#- lg #} - // lg - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - - for (int ii = 0; ii < N; ii++) - { - for (int jj = 0; jj < {{ dims.ng }}; jj++) - buffer[jj] = (double)(*in_sign[ii*{{ dims.ng }}+jj]); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, ii, "lg", (void *) buffer); - } - {%- endif -%} - {%- if dims.ng > 0 and simulink_opts.inputs.ug -%} {#- ug #} - // ug - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - - for (int ii = 0; ii < N; ii++) - { - for (int jj = 0; jj < {{ dims.ng }}; jj++) - buffer[jj] = (double)(*in_sign[ii*{{ dims.ng }}+jj]); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, ii, "ug", (void *) buffer); - } - {%- endif -%} - - {%- if dims.nh > 0 and simulink_opts.inputs.lh -%} {#- lh #} - // lh - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - - for (int ii = 0; ii < N; ii++) - { - for (int jj = 0; jj < {{ dims.nh }}; jj++) - buffer[jj] = (double)(*in_sign[ii*{{ dims.nh }}+jj]); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, ii, "lh", (void *) buffer); - } - {%- endif -%} - {%- if dims.nh > 0 and simulink_opts.inputs.uh -%} {#- uh #} - // uh - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - - for (int ii = 0; ii < N; ii++) - { - for (int jj = 0; jj < {{ dims.nh }}; jj++) - buffer[jj] = (double)(*in_sign[ii*{{ dims.nh }}+jj]); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, ii, "uh", (void *) buffer); - } - {%- endif -%} - - - {%- if dims.nh_e > 0 and simulink_opts.inputs.lh_e -%} {#- lh_e #} - // lh_e - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - for (int i = 0; i < {{ dims.nh_e }}; i++) - buffer[i] = (double)(*in_sign[i]); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lh", buffer); - {%- endif -%} - {%- if dims.nh_e > 0 and simulink_opts.inputs.uh_e -%} {#- uh_e #} - // uh_e - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - for (int i = 0; i < {{ dims.nh_e }}; i++) - buffer[i] = (double)(*in_sign[i]); - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "uh", buffer); - {%- endif -%} - - {%- if dims.ny_0 > 0 and simulink_opts.inputs.cost_W_0 %} {#- cost_W_0 #} - // cost_W_0 - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - for (int i = 0; i < {{ dims.ny_0 * dims.ny_0 }}; i++) - buffer[i] = (double)(*in_sign[i]); - - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "W", buffer); - {%- endif %} - - {%- if dims.ny > 0 and simulink_opts.inputs.cost_W %} {#- cost_W #} - // cost_W - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - for (int i = 0; i < {{ dims.ny * dims.ny }}; i++) - buffer[i] = (double)(*in_sign[i]); - - for (int ii = 1; ii < N; ii++) - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, ii, "W", buffer); - {%- endif %} - - {%- if dims.ny_e > 0 and simulink_opts.inputs.cost_W_e %} {#- cost_W_e #} - // cost_W_e - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - for (int i = 0; i < {{ dims.ny_e * dims.ny_e }}; i++) - buffer[i] = (double)(*in_sign[i]); - - ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "W", buffer); - {%- endif %} - - {%- if simulink_opts.inputs.reset_solver %} {#- reset_solver #} - // reset_solver - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - double reset = (double)(*in_sign[0]); - if (reset) - { - {{ model.name }}_acados_reset(capsule, 1); - } - {%- endif %} - - {%- if simulink_opts.inputs.x_init %} {#- x_init #} - // x_init - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - for (int ii = 0; ii < {{ dims.N + 1 }}; ii++) - { - for (int jj = 0; jj < {{ dims.nx }}; jj++) - buffer[jj] = (double)(*in_sign[(ii)*{{ dims.nx }}+jj]); - ocp_nlp_out_set(nlp_config, nlp_dims, nlp_out, ii, "x", (void *) buffer); - } - {%- endif %} - - {%- if simulink_opts.inputs.u_init %} {#- u_init #} - // u_init - {%- set i_input = i_input + 1 %} - in_sign = ssGetInputPortRealSignalPtrs(S, {{ i_input }}); - for (int ii = 0; ii < N; ii++) - { - for (int jj = 0; jj < {{ dims.nu }}; jj++) - buffer[jj] = (double)(*in_sign[(ii)*{{ dims.nu }}+jj]); - ocp_nlp_out_set(nlp_config, nlp_dims, nlp_out, ii, "u", (void *) buffer); - } - {%- endif %} - - /* call solver */ - int rti_phase = 0; - ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "rti_phase", &rti_phase); - int acados_status = {{ model.name }}_acados_solve(capsule); - - - /* set outputs */ - // assign pointers to output signals - real_t *out_u0, *out_utraj, *out_xtraj, *out_status, *out_sqp_iter, *out_KKT_res, *out_KKT_residuals, *out_x1, *out_cpu_time, *out_cpu_time_sim, *out_cpu_time_qp, *out_cpu_time_lin, *out_cost_value; - int tmp_int; - - {%- set i_output = -1 -%}{# note here i_output is 0-based #} - {%- if dims.nu > 0 and simulink_opts.outputs.u0 == 1 %} - {%- set i_output = i_output + 1 %} - out_u0 = ssGetOutputPortRealSignal(S, {{ i_output }}); - ocp_nlp_out_get(nlp_config, nlp_dims, nlp_out, 0, "u", (void *) out_u0); - {%- endif %} - - {%- if simulink_opts.outputs.utraj == 1 %} - {%- set i_output = i_output + 1 %} - out_utraj = ssGetOutputPortRealSignal(S, {{ i_output }}); - for (int ii = 0; ii < N; ii++) - ocp_nlp_out_get(nlp_config, nlp_dims, nlp_out, ii, - "u", (void *) (out_utraj + ii * {{ dims.nu }})); - {%- endif %} - - {% if simulink_opts.outputs.xtraj == 1 %} - {%- set i_output = i_output + 1 %} - - out_xtraj = ssGetOutputPortRealSignal(S, {{ i_output }}); - for (int ii = 0; ii < {{ dims.N + 1 }}; ii++) - ocp_nlp_out_get(nlp_config, nlp_dims, nlp_out, ii, - "x", (void *) (out_xtraj + ii * {{ dims.nx }})); - {%- endif %} - - {%- if simulink_opts.outputs.solver_status == 1 %} - {%- set i_output = i_output + 1 %} - out_status = ssGetOutputPortRealSignal(S, {{ i_output }}); - *out_status = (real_t) acados_status; - {%- endif %} - - {%- if simulink_opts.outputs.cost_value == 1 %} - {%- set i_output = i_output + 1 %} - out_cost_value = ssGetOutputPortRealSignal(S, {{ i_output }}); - ocp_nlp_eval_cost(capsule->nlp_solver, nlp_in, nlp_out); - ocp_nlp_get(nlp_config, capsule->nlp_solver, "cost_value", (void *) out_cost_value); - {%- endif %} - - {%- if simulink_opts.outputs.KKT_residual == 1 %} - {%- set i_output = i_output + 1 %} - out_KKT_res = ssGetOutputPortRealSignal(S, {{ i_output }}); - *out_KKT_res = (real_t) nlp_out->inf_norm_res; - {%- endif %} - - {%- if simulink_opts.outputs.KKT_residuals == 1 %} - {%- set i_output = i_output + 1 %} - out_KKT_residuals = ssGetOutputPortRealSignal(S, {{ i_output }}); - - {%- if solver_options.nlp_solver_type == "SQP_RTI" %} - ocp_nlp_eval_residuals(capsule->nlp_solver, nlp_in, nlp_out); - {%- endif %} - ocp_nlp_get(nlp_config, capsule->nlp_solver, "res_stat", (void *) &out_KKT_residuals[0]); - ocp_nlp_get(nlp_config, capsule->nlp_solver, "res_eq", (void *) &out_KKT_residuals[1]); - ocp_nlp_get(nlp_config, capsule->nlp_solver, "res_ineq", (void *) &out_KKT_residuals[2]); - ocp_nlp_get(nlp_config, capsule->nlp_solver, "res_comp", (void *) &out_KKT_residuals[3]); - {%- endif %} - - {%- if dims.N > 0 and simulink_opts.outputs.x1 == 1 %} - {%- set i_output = i_output + 1 %} - out_x1 = ssGetOutputPortRealSignal(S, {{ i_output }}); - ocp_nlp_out_get(nlp_config, nlp_dims, nlp_out, 1, "x", (void *) out_x1); - {%- endif %} - - {%- if simulink_opts.outputs.CPU_time == 1 %} - {%- set i_output = i_output + 1 %} - out_cpu_time = ssGetOutputPortRealSignal(S, {{ i_output }}); - // get solution time - ocp_nlp_get(nlp_config, capsule->nlp_solver, "time_tot", (void *) out_cpu_time); - {%- endif -%} - - {%- if simulink_opts.outputs.CPU_time_sim == 1 %} - {%- set i_output = i_output + 1 %} - out_cpu_time_sim = ssGetOutputPortRealSignal(S, {{ i_output }}); - ocp_nlp_get(nlp_config, capsule->nlp_solver, "time_sim", (void *) out_cpu_time_sim); - {%- endif -%} - - {%- if simulink_opts.outputs.CPU_time_qp == 1 %} - {%- set i_output = i_output + 1 %} - out_cpu_time_qp = ssGetOutputPortRealSignal(S, {{ i_output }}); - ocp_nlp_get(nlp_config, capsule->nlp_solver, "time_qp", (void *) out_cpu_time_qp); - {%- endif -%} - - {%- if simulink_opts.outputs.CPU_time_lin == 1 %} - {%- set i_output = i_output + 1 %} - out_cpu_time_lin = ssGetOutputPortRealSignal(S, {{ i_output }}); - ocp_nlp_get(nlp_config, capsule->nlp_solver, "time_lin", (void *) out_cpu_time_lin); - {%- endif -%} - - {%- if simulink_opts.outputs.sqp_iter == 1 %} - {%- set i_output = i_output + 1 %} - out_sqp_iter = ssGetOutputPortRealSignal(S, {{ i_output }}); - // get sqp iter - ocp_nlp_get(nlp_config, capsule->nlp_solver, "sqp_iter", (void *) &tmp_int); - *out_sqp_iter = (real_t) tmp_int; - {%- endif %} - -} - -static void mdlTerminate(SimStruct *S) -{ - {{ model.name }}_solver_capsule *capsule = ssGetUserData(S); - - {{ model.name }}_acados_free(capsule); - {{ model.name }}_acados_free_capsule(capsule); -} - - -#ifdef MATLAB_MEX_FILE -#include "simulink.c" -#else -#include "cg_sfun.h" -#endif diff --git a/third_party/acados/acados_template/c_templates_tera/matlab_templates/main_mex.in.c b/third_party/acados/acados_template/c_templates_tera/matlab_templates/main_mex.in.c deleted file mode 100644 index 851a3cc04f..0000000000 --- a/third_party/acados/acados_template/c_templates_tera/matlab_templates/main_mex.in.c +++ /dev/null @@ -1,181 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -// standard -#include -#include -// acados -#include "acados/utils/print.h" -#include "acados/utils/math.h" -#include "acados_c/ocp_nlp_interface.h" -#include "acados_solver_{{ model.name }}.h" -// mex -#include "mex.h" - -/* auxilary mex */ -// prints a matrix in column-major format (exponential notation) -void MEX_print_exp_mat(int m, int n, double *A, int lda) -{ - for (int i=0; iN; i++) - { - ocp_nlp_out_set(nlp_config, nlp_dims, nlp_out, i, "x", x_init); - ocp_nlp_out_set(nlp_config, nlp_dims, nlp_out, i, "u", u0); - } - status = {{ model.name }}_acados_solve(); - ocp_nlp_get(nlp_config, nlp_solver, "time_tot", &elapsed_time); - min_time = MIN(elapsed_time, min_time); - } - - /* print solution and statistics */ - for (int ii = 0; ii <= nlp_dims->N; ii++) - ocp_nlp_out_get(nlp_config, nlp_dims, nlp_out, ii, "x", &xtraj[ii*{{ dims.nx }}]); - for (int ii = 0; ii < nlp_dims->N; ii++) - ocp_nlp_out_get(nlp_config, nlp_dims, nlp_out, ii, "u", &utraj[ii*{{ dims.nu }}]); - - mexPrintf("\n--- xtraj ---\n"); - MEX_print_exp_tran_mat( {{ dims.nx }}, {{ dims.N }}+1, xtraj, {{ dims.nx }} ); - mexPrintf("\n--- utraj ---\n"); - MEX_print_exp_tran_mat( {{ dims.nu }}, {{ dims.N }}, utraj, {{ dims.nu }} ); - - mexPrintf("\nsolved ocp %d times, solution printed above\n\n", NTIMINGS); - - if (status == ACADOS_SUCCESS) - mexPrintf("{{ model.name }}_acados_solve(): SUCCESS!\n"); - else - mexPrintf("{{ model.name }}_acados_solve() failed with status %d.\n", status); - - // get solution - ocp_nlp_out_get(nlp_config, nlp_dims, nlp_out, 0, "kkt_norm_inf", &kkt_norm_inf); - ocp_nlp_get(nlp_config, nlp_solver, "sqp_iter", &sqp_iter); - - mexPrintf("\nSolver info:\n"); - mexPrintf(" SQP iterations %2d\n minimum time for 1 solve %f [ms]\n KKT %e\n", - sqp_iter, min_time*1000, kkt_norm_inf); - - // free solver - status = {{ model.name }}_acados_free(); - if (status) - { - mexPrintf("{{ model.name }}_acados_free() returned status %d.\n", status); - } - - return; -} diff --git a/third_party/acados/acados_template/c_templates_tera/matlab_templates/make_main_mex.in.m b/third_party/acados/acados_template/c_templates_tera/matlab_templates/make_main_mex.in.m deleted file mode 100644 index d217948456..0000000000 --- a/third_party/acados/acados_template/c_templates_tera/matlab_templates/make_main_mex.in.m +++ /dev/null @@ -1,103 +0,0 @@ -% -% Copyright (c) The acados authors. -% -% This file is part of acados. -% -% The 2-Clause BSD License -% -% 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. -% -% 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.; - -% - -function make_main_mex_{{ model.name }}() - - opts.output_dir = pwd; - - % get acados folder - acados_folder = getenv('ACADOS_INSTALL_DIR'); - - % set paths - acados_include = ['-I' fullfile(acados_folder, 'include')]; - template_lib_include = ['-l' 'acados_solver_{{ model.name }}']; - template_lib_path = ['-L' fullfile(pwd)]; - - acados_lib_path = ['-L' fullfile(acados_folder, 'lib')]; - external_include = ['-I', fullfile(acados_folder, 'external')]; - blasfeo_include = ['-I', fullfile(acados_folder, 'external', 'blasfeo', 'include')]; - hpipm_include = ['-I', fullfile(acados_folder, 'external', 'hpipm', 'include')]; - - mex_names = { ... - 'main_mex_{{ model.name }}' ... - }; - - mex_files = cell(length(mex_names), 1); - for k=1:length(mex_names) - mex_files{k} = fullfile([mex_names{k}, '.c']); - end - - %% octave C flags - if is_octave() - if ~exist(fullfile(opts.output_dir, 'cflags_octave.txt'), 'file') - diary(fullfile(opts.output_dir, 'cflags_octave.txt')); - diary on - mkoctfile -p CFLAGS - diary off - input_file = fopen(fullfile(opts.output_dir, 'cflags_octave.txt'), 'r'); - cflags_tmp = fscanf(input_file, '%[^\n]s'); - fclose(input_file); - if ~ismac() - cflags_tmp = [cflags_tmp, ' -std=c99 -fopenmp']; - else - cflags_tmp = [cflags_tmp, ' -std=c99']; - end - input_file = fopen(fullfile(opts.output_dir, 'cflags_octave.txt'), 'w'); - fprintf(input_file, '%s', cflags_tmp); - fclose(input_file); - end - % read cflags from file - input_file = fopen(fullfile(opts.output_dir, 'cflags_octave.txt'), 'r'); - cflags_tmp = fscanf(input_file, '%[^\n]s'); - fclose(input_file); - setenv('CFLAGS', cflags_tmp); - end - - %% compile mex - for ii=1:length(mex_files) - disp(['compiling ', mex_files{ii}]) - if is_octave() - % mkoctfile -p CFLAGS - mex(acados_include, template_lib_include, external_include, blasfeo_include, hpipm_include,... - acados_lib_path, template_lib_path, '-lacados', '-lhpipm', '-lblasfeo', mex_files{ii}) - else - if ismac() - FLAGS = 'CFLAGS=$CFLAGS -std=c99'; - else - FLAGS = 'CFLAGS=$CFLAGS -std=c99 -fopenmp'; - end - mex(FLAGS, acados_include, template_lib_include, external_include, blasfeo_include, hpipm_include,... - acados_lib_path, template_lib_path, '-lacados', '-lhpipm', '-lblasfeo', mex_files{ii}) - end - end - - -end \ No newline at end of file diff --git a/third_party/acados/acados_template/c_templates_tera/matlab_templates/make_mex.in.m b/third_party/acados/acados_template/c_templates_tera/matlab_templates/make_mex.in.m deleted file mode 100644 index 5e35827137..0000000000 --- a/third_party/acados/acados_template/c_templates_tera/matlab_templates/make_mex.in.m +++ /dev/null @@ -1,127 +0,0 @@ -% -% Copyright (c) The acados authors. -% -% This file is part of acados. -% -% The 2-Clause BSD License -% -% 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. -% -% 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.; - -% - -function make_mex_{{ model.name }}() - - opts.output_dir = pwd; - - % get acados folder - acados_folder = getenv('ACADOS_INSTALL_DIR'); - - % set paths - acados_include = ['-I' fullfile(acados_folder, 'include')]; - template_lib_include = ['-l' 'acados_ocp_solver_{{ model.name }}']; - template_lib_path = ['-L' fullfile(pwd)]; - - acados_lib_path = ['-L' fullfile(acados_folder, 'lib')]; - external_include = ['-I', fullfile(acados_folder, 'external')]; - blasfeo_include = ['-I', fullfile(acados_folder, 'external', 'blasfeo', 'include')]; - hpipm_include = ['-I', fullfile(acados_folder, 'external', 'hpipm', 'include')]; - - % load linking information of compiled acados - link_libs_core_filename = fullfile(acados_folder, 'lib', 'link_libs.json'); - addpath(fullfile(acados_folder, 'external', 'jsonlab')); - link_libs = loadjson(link_libs_core_filename); - - % add necessary link instructs - acados_lib_extra = {}; - lib_names = fieldnames(link_libs); - for idx = 1 : numel(lib_names) - lib_name = lib_names{idx}; - link_arg = link_libs.(lib_name); - if ~isempty(link_arg) - acados_lib_extra = [acados_lib_extra, link_arg]; - end - end - - - mex_include = ['-I', fullfile(acados_folder, 'interfaces', 'acados_matlab_octave')]; - - mex_names = { ... - 'acados_mex_create_{{ model.name }}' ... - 'acados_mex_free_{{ model.name }}' ... - 'acados_mex_solve_{{ model.name }}' ... - 'acados_mex_set_{{ model.name }}' ... - }; - - mex_files = cell(length(mex_names), 1); - for k=1:length(mex_names) - mex_files{k} = fullfile([mex_names{k}, '.c']); - end - - %% octave C flags - if is_octave() - if ~exist(fullfile(opts.output_dir, 'cflags_octave.txt'), 'file') - diary(fullfile(opts.output_dir, 'cflags_octave.txt')); - diary on - mkoctfile -p CFLAGS - diary off - input_file = fopen(fullfile(opts.output_dir, 'cflags_octave.txt'), 'r'); - cflags_tmp = fscanf(input_file, '%[^\n]s'); - fclose(input_file); - if ~ismac() - cflags_tmp = [cflags_tmp, ' -std=c99 -fopenmp']; - else - cflags_tmp = [cflags_tmp, ' -std=c99']; - end - input_file = fopen(fullfile(opts.output_dir, 'cflags_octave.txt'), 'w'); - fprintf(input_file, '%s', cflags_tmp); - fclose(input_file); - end - % read cflags from file - input_file = fopen(fullfile(opts.output_dir, 'cflags_octave.txt'), 'r'); - cflags_tmp = fscanf(input_file, '%[^\n]s'); - fclose(input_file); - setenv('CFLAGS', cflags_tmp); - end - - %% compile mex - for ii=1:length(mex_files) - disp(['compiling ', mex_files{ii}]) - if is_octave() - % mkoctfile -p CFLAGS - mex(acados_include, template_lib_include, external_include, blasfeo_include, hpipm_include,... - template_lib_path, mex_include, acados_lib_path, '-lacados', '-lhpipm', '-lblasfeo',... - acados_lib_extra{:}, mex_files{ii}) - else - if ismac() - FLAGS = 'CFLAGS=$CFLAGS -std=c99'; - else - FLAGS = 'CFLAGS=$CFLAGS -std=c99 -fopenmp'; - end - mex(FLAGS, acados_include, template_lib_include, external_include, blasfeo_include, hpipm_include,... - template_lib_path, mex_include, acados_lib_path, '-lacados', '-lhpipm', '-lblasfeo',... - acados_lib_extra{:}, mex_files{ii}) - end - end - - -end \ No newline at end of file diff --git a/third_party/acados/acados_template/c_templates_tera/matlab_templates/make_sfun.in.m b/third_party/acados/acados_template/c_templates_tera/matlab_templates/make_sfun.in.m deleted file mode 100644 index 5d74c523f8..0000000000 --- a/third_party/acados/acados_template/c_templates_tera/matlab_templates/make_sfun.in.m +++ /dev/null @@ -1,432 +0,0 @@ -% -% Copyright (c) The acados authors. -% -% This file is part of acados. -% -% The 2-Clause BSD License -% -% 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. -% -% 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.; - -% - -SOURCES = { ... - {%- if solver_options.integrator_type == 'ERK' %} - '{{ model.name }}_model/{{ model.name }}_expl_ode_fun.c', ... - '{{ model.name }}_model/{{ model.name }}_expl_vde_forw.c',... - {%- if solver_options.hessian_approx == 'EXACT' %} - '{{ model.name }}_model/{{ model.name }}_expl_ode_hess.c',... - {%- endif %} - {%- elif solver_options.integrator_type == "IRK" %} - '{{ model.name }}_model/{{ model.name }}_impl_dae_fun.c', ... - '{{ model.name }}_model/{{ model.name }}_impl_dae_fun_jac_x_xdot_z.c', ... - '{{ model.name }}_model/{{ model.name }}_impl_dae_jac_x_xdot_u_z.c', ... - {%- if solver_options.hessian_approx == 'EXACT' %} - '{{ model.name }}_model/{{ model.name }}_impl_dae_hess.c',... - {%- endif %} - {%- elif solver_options.integrator_type == "GNSF" %} - {% if model.gnsf.purely_linear != 1 %} - '{{ model.name }}_model/{{ model.name }}_gnsf_phi_fun.c',... - '{{ model.name }}_model/{{ model.name }}_gnsf_phi_fun_jac_y.c',... - '{{ model.name }}_model/{{ model.name }}_gnsf_phi_jac_y_uhat.c',... - {% if model.gnsf.nontrivial_f_LO == 1 %} - '{{ model.name }}_model/{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz.c',... - {%- endif %} - {%- endif %} - '{{ model.name }}_model/{{ model.name }}_gnsf_get_matrices_fun.c',... - {%- elif solver_options.integrator_type == "DISCRETE" %} - '{{ model.name }}_model/{{ model.name }}_dyn_disc_phi_fun.c',... - '{{ model.name }}_model/{{ model.name }}_dyn_disc_phi_fun_jac.c',... - {%- if solver_options.hessian_approx == "EXACT" %} - '{{ model.name }}_model/{{ model.name }}_dyn_disc_phi_fun_jac_hess.c',... - {%- endif %} - {%- endif %} - {%- if cost.cost_type_0 == "NONLINEAR_LS" %} - '{{ model.name }}_cost/{{ model.name }}_cost_y_0_fun.c',... - '{{ model.name }}_cost/{{ model.name }}_cost_y_0_fun_jac_ut_xt.c',... - '{{ model.name }}_cost/{{ model.name }}_cost_y_0_hess.c',... - {%- elif cost.cost_type_0 == "EXTERNAL" %} - '{{ model.name }}_cost/{{ model.name }}_cost_ext_cost_0_fun.c',... - '{{ model.name }}_cost/{{ model.name }}_cost_ext_cost_0_fun_jac.c',... - '{{ model.name }}_cost/{{ model.name }}_cost_ext_cost_0_fun_jac_hess.c',... - {%- endif %} - - {%- if cost.cost_type == "NONLINEAR_LS" %} - '{{ model.name }}_cost/{{ model.name }}_cost_y_fun.c',... - '{{ model.name }}_cost/{{ model.name }}_cost_y_fun_jac_ut_xt.c',... - '{{ model.name }}_cost/{{ model.name }}_cost_y_hess.c',... - {%- elif cost.cost_type == "EXTERNAL" %} - '{{ model.name }}_cost/{{ model.name }}_cost_ext_cost_fun.c',... - '{{ model.name }}_cost/{{ model.name }}_cost_ext_cost_fun_jac.c',... - '{{ model.name }}_cost/{{ model.name }}_cost_ext_cost_fun_jac_hess.c',... - {%- endif %} - {%- if cost.cost_type_e == "NONLINEAR_LS" %} - '{{ model.name }}_cost/{{ model.name }}_cost_y_e_fun.c',... - '{{ model.name }}_cost/{{ model.name }}_cost_y_e_fun_jac_ut_xt.c',... - '{{ model.name }}_cost/{{ model.name }}_cost_y_e_hess.c',... - {%- elif cost.cost_type_e == "EXTERNAL" %} - '{{ model.name }}_cost/{{ model.name }}_cost_ext_cost_e_fun.c',... - '{{ model.name }}_cost/{{ model.name }}_cost_ext_cost_e_fun_jac.c',... - '{{ model.name }}_cost/{{ model.name }}_cost_ext_cost_e_fun_jac_hess.c',... - {%- endif %} - {%- if constraints.constr_type == "BGH" and dims.nh > 0 %} - '{{ model.name }}_constraints/{{ model.name }}_constr_h_fun.c', ... - '{{ model.name }}_constraints/{{ model.name }}_constr_h_fun_jac_uxt_zt_hess.c', ... - '{{ model.name }}_constraints/{{ model.name }}_constr_h_fun_jac_uxt_zt.c', ... - {%- elif constraints.constr_type == "BGP" and dims.nphi > 0 %} - '{{ model.name }}_constraints/{{ model.name }}_phi_constraint.c', ... - {%- endif %} - {%- if constraints.constr_type_e == "BGH" and dims.nh_e > 0 %} - '{{ model.name }}_constraints/{{ model.name }}_constr_h_e_fun.c', ... - '{{ model.name }}_constraints/{{ model.name }}_constr_h_e_fun_jac_uxt_zt_hess.c', ... - '{{ model.name }}_constraints/{{ model.name }}_constr_h_e_fun_jac_uxt_zt.c', ... - {%- elif constraints.constr_type_e == "BGP" and dims.nphi_e > 0 %} - '{{ model.name }}_constraints/{{ model.name }}_phi_e_constraint.c', ... - {%- endif %} - 'acados_solver_sfunction_{{ model.name }}.c', ... - 'acados_solver_{{ model.name }}.c' - }; - -INC_PATH = '{{ acados_include_path }}'; - -INCS = {['-I', fullfile(INC_PATH, 'blasfeo', 'include')], ... - ['-I', fullfile(INC_PATH, 'hpipm', 'include')], ... - ['-I', fullfile(INC_PATH, 'acados')], ... - ['-I', fullfile(INC_PATH)]}; - -{% if solver_options.qp_solver is containing("QPOASES") %} -INCS{end+1} = ['-I', fullfile(INC_PATH, 'qpOASES_e')]; -{% endif %} - -CFLAGS = 'CFLAGS=$CFLAGS'; -LDFLAGS = 'LDFLAGS=$LDFLAGS'; -COMPFLAGS = 'COMPFLAGS=$COMPFLAGS'; -COMPDEFINES = 'COMPDEFINES=$COMPDEFINES'; - -{% if solver_options.qp_solver is containing("QPOASES") %} -CFLAGS = [ CFLAGS, ' -DACADOS_WITH_QPOASES ' ]; -COMPDEFINES = [ COMPDEFINES, ' -DACADOS_WITH_QPOASES ' ]; -{%- elif solver_options.qp_solver is containing("OSQP") %} -CFLAGS = [ CFLAGS, ' -DACADOS_WITH_OSQP ' ]; -COMPDEFINES = [ COMPDEFINES, ' -DACADOS_WITH_OSQP ' ]; -{%- elif solver_options.qp_solver is containing("QPDUNES") %} -CFLAGS = [ CFLAGS, ' -DACADOS_WITH_QPDUNES ' ]; -COMPDEFINES = [ COMPDEFINES, ' -DACADOS_WITH_QPDUNES ' ]; -{%- elif solver_options.qp_solver is containing("DAQP") %} -CFLAGS = [ CFLAGS, ' -DACADOS_WITH_DAQP' ]; -COMPDEFINES = [ COMPDEFINES, ' -DACADOS_WITH_DAQP' ]; -{%- elif solver_options.qp_solver is containing("HPMPC") %} -CFLAGS = [ CFLAGS, ' -DACADOS_WITH_HPMPC ' ]; -COMPDEFINES = [ COMPDEFINES, ' -DACADOS_WITH_HPMPC ' ]; -{% endif %} - -LIB_PATH = ['-L', fullfile('{{ acados_lib_path }}')]; - -LIBS = {'-lacados', '-lhpipm', '-lblasfeo'}; - -% acados linking libraries and flags -{%- if acados_link_libs and os and os == "pc" %} -LDFLAGS = [LDFLAGS ' {{ acados_link_libs.openmp }}']; -COMPFLAGS = [COMPFLAGS ' {{ acados_link_libs.openmp }}']; -LIBS{end+1} = '{{ acados_link_libs.qpoases }}'; -LIBS{end+1} = '{{ acados_link_libs.hpmpc }}'; -LIBS{end+1} = '{{ acados_link_libs.osqp }}'; -{%- else %} - {% if solver_options.qp_solver is containing("QPOASES") %} -LIBS{end+1} = '-lqpOASES_e'; - {% endif %} - {% if solver_options.qp_solver is containing("DAQP") %} -LIBS{end+1} = '-ldaqp'; - {% endif %} -{%- endif %} - - -try - % mex('-v', '-O', CFLAGS, LDFLAGS, COMPFLAGS, COMPDEFINES, INCS{:}, ... - mex('-O', CFLAGS, LDFLAGS, COMPFLAGS, COMPDEFINES, INCS{:}, ... - LIB_PATH, LIBS{:}, SOURCES{:}, ... - '-output', 'acados_solver_sfunction_{{ model.name }}' ); -catch exception - disp('make_sfun failed with the following exception:') - disp(exception); - disp('Try adding -v to the mex command above to get more information.') - keyboard -end - -fprintf( [ '\n\nSuccessfully created sfunction:\nacados_solver_sfunction_{{ model.name }}', '.', ... - eval('mexext')] ); - - -%% print note on usage of s-function, and create I/O port names vectors -fprintf('\n\nNote: Usage of Sfunction is as follows:\n') -input_note = 'Inputs are:\n'; -i_in = 1; - -global sfun_input_names -sfun_input_names = {}; - -{%- if dims.nbx_0 > 0 and simulink_opts.inputs.lbx_0 -%} {#- lbx_0 #} -input_note = strcat(input_note, num2str(i_in), ') lbx_0 - lower bound on x for stage 0,',... - ' size [{{ dims.nbx_0 }}]\n '); -sfun_input_names = [sfun_input_names; 'lbx_0 [{{ dims.nbx_0 }}]']; -i_in = i_in + 1; -{%- endif %} - -{%- if dims.nbx_0 > 0 and simulink_opts.inputs.ubx_0 -%} {#- ubx_0 #} -input_note = strcat(input_note, num2str(i_in), ') ubx_0 - upper bound on x for stage 0,',... - ' size [{{ dims.nbx_0 }}]\n '); -sfun_input_names = [sfun_input_names; 'ubx_0 [{{ dims.nbx_0 }}]']; -i_in = i_in + 1; -{%- endif %} - -{%- if dims.np > 0 and simulink_opts.inputs.parameter_traj -%} {#- parameter_traj #} -input_note = strcat(input_note, num2str(i_in), ') parameters - concatenated for all shooting nodes 0 to N,',... - ' size [{{ (dims.N+1)*dims.np }}]\n '); -sfun_input_names = [sfun_input_names; 'parameter_traj [{{ (dims.N+1)*dims.np }}]']; -i_in = i_in + 1; -{%- endif %} - -{%- if dims.ny_0 > 0 and simulink_opts.inputs.y_ref_0 %} -input_note = strcat(input_note, num2str(i_in), ') y_ref_0, size [{{ dims.ny_0 }}]\n '); -sfun_input_names = [sfun_input_names; 'y_ref_0 [{{ dims.ny_0 }}]']; -i_in = i_in + 1; -{%- endif %} - -{%- if dims.ny > 0 and dims.N > 1 and simulink_opts.inputs.y_ref %} -input_note = strcat(input_note, num2str(i_in), ') y_ref - concatenated for shooting nodes 1 to N-1,',... - ' size [{{ (dims.N-1) * dims.ny }}]\n '); -sfun_input_names = [sfun_input_names; 'y_ref [{{ (dims.N-1) * dims.ny }}]']; -i_in = i_in + 1; -{%- endif %} - -{%- if dims.ny_e > 0 and dims.N > 0 and simulink_opts.inputs.y_ref_e %} -input_note = strcat(input_note, num2str(i_in), ') y_ref_e, size [{{ dims.ny_e }}]\n '); -sfun_input_names = [sfun_input_names; 'y_ref_e [{{ dims.ny_e }}]']; -i_in = i_in + 1; -{%- endif %} - -{%- if dims.nbx > 0 and dims.N > 1 and simulink_opts.inputs.lbx -%} {#- lbx #} -input_note = strcat(input_note, num2str(i_in), ') lbx for shooting nodes 1 to N-1, size [{{ (dims.N-1) * dims.nbx }}]\n '); -sfun_input_names = [sfun_input_names; 'lbx [{{ (dims.N-1) * dims.nbx }}]']; -i_in = i_in + 1; -{%- endif %} -{%- if dims.nbx > 0 and dims.N > 1 and simulink_opts.inputs.ubx -%} {#- ubx #} -input_note = strcat(input_note, num2str(i_in), ') ubx for shooting nodes 1 to N-1, size [{{ (dims.N-1) * dims.nbx }}]\n '); -sfun_input_names = [sfun_input_names; 'ubx [{{ (dims.N-1) * dims.nbx }}]']; -i_in = i_in + 1; -{%- endif %} - - -{%- if dims.nbx_e > 0 and dims.N > 0 and simulink_opts.inputs.lbx_e -%} {#- lbx_e #} -input_note = strcat(input_note, num2str(i_in), ') lbx_e (lbx at shooting node N), size [{{ dims.nbx_e }}]\n '); -sfun_input_names = [sfun_input_names; 'lbx_e [{{ dims.nbx_e }}]']; -i_in = i_in + 1; -{%- endif %} -{%- if dims.nbx_e > 0 and dims.N > 0 and simulink_opts.inputs.ubx_e -%} {#- ubx_e #} -input_note = strcat(input_note, num2str(i_in), ') ubx_e (ubx at shooting node N), size [{{ dims.nbx_e }}]\n '); -sfun_input_names = [sfun_input_names; 'ubx_e [{{ dims.nbx_e }}]']; -i_in = i_in + 1; -{%- endif %} - -{%- if dims.nbu > 0 and dims.N > 0 and simulink_opts.inputs.lbu -%} {#- lbu #} -input_note = strcat(input_note, num2str(i_in), ') lbu for shooting nodes 0 to N-1, size [{{ dims.N*dims.nbu }}]\n '); -sfun_input_names = [sfun_input_names; 'lbu [{{ dims.N*dims.nbu }}]']; -i_in = i_in + 1; -{%- endif -%} -{%- if dims.nbu > 0 and dims.N > 0 and simulink_opts.inputs.ubu -%} {#- ubu #} -input_note = strcat(input_note, num2str(i_in), ') ubu for shooting nodes 0 to N-1, size [{{ dims.N*dims.nbu }}]\n '); -sfun_input_names = [sfun_input_names; 'ubu [{{ dims.N*dims.nbu }}]']; -i_in = i_in + 1; -{%- endif -%} - -{%- if dims.ng > 0 and simulink_opts.inputs.lg -%} {#- lg #} -input_note = strcat(input_note, num2str(i_in), ') lg for shooting nodes 0 to N-1, size [{{ dims.N*dims.ng }}]\n '); -sfun_input_names = [sfun_input_names; 'lg [{{ dims.N*dims.ng }}]']; -i_in = i_in + 1; -{%- endif %} -{%- if dims.ng > 0 and simulink_opts.inputs.ug -%} {#- ug #} -input_note = strcat(input_note, num2str(i_in), ') ug for shooting nodes 0 to N-1, size [{{ dims.N*dims.ng }}]\n '); -sfun_input_names = [sfun_input_names; 'ug [{{ dims.N*dims.ng }}]']; -i_in = i_in + 1; -{%- endif %} - -{%- if dims.nh > 0 and simulink_opts.inputs.lh -%} {#- lh #} -input_note = strcat(input_note, num2str(i_in), ') lh for shooting nodes 0 to N-1, size [{{ dims.N*dims.nh }}]\n '); -sfun_input_names = [sfun_input_names; 'lh [{{ dims.N*dims.nh }}]']; -i_in = i_in + 1; -{%- endif %} -{%- if dims.nh > 0 and simulink_opts.inputs.uh -%} {#- uh #} -input_note = strcat(input_note, num2str(i_in), ') uh for shooting nodes 0 to N-1, size [{{ dims.N*dims.nh }}]\n '); -sfun_input_names = [sfun_input_names; 'uh [{{ dims.N*dims.nh }}]']; -i_in = i_in + 1; -{%- endif %} - -{%- if dims.nh_e > 0 and simulink_opts.inputs.lh_e -%} {#- lh_e #} -input_note = strcat(input_note, num2str(i_in), ') lh_e, size [{{ dims.nh_e }}]\n '); -sfun_input_names = [sfun_input_names; 'lh_e [{{ dims.nh_e }}]']; -i_in = i_in + 1; -{%- endif %} -{%- if dims.nh_e > 0 and simulink_opts.inputs.uh_e -%} {#- uh_e #} -input_note = strcat(input_note, num2str(i_in), ') uh_e, size [{{ dims.nh_e }}]\n '); -sfun_input_names = [sfun_input_names; 'uh_e [{{ dims.nh_e }}]']; -i_in = i_in + 1; -{%- endif %} - -{%- if dims.ny_0 > 0 and simulink_opts.inputs.cost_W_0 %} {#- cost_W_0 #} -input_note = strcat(input_note, num2str(i_in), ') cost_W_0 in column-major format, size [{{ dims.ny_0 * dims.ny_0 }}]\n '); -sfun_input_names = [sfun_input_names; 'cost_W_0 [{{ dims.ny_0 * dims.ny_0 }}]']; -i_in = i_in + 1; -{%- endif %} - -{%- if dims.ny > 0 and simulink_opts.inputs.cost_W %} {#- cost_W #} -input_note = strcat(input_note, num2str(i_in), ') cost_W in column-major format, that is set for all intermediate shooting nodes: 1 to N-1, size [{{ dims.ny * dims.ny }}]\n '); -sfun_input_names = [sfun_input_names; 'cost_W [{{ dims.ny * dims.ny }}]']; -i_in = i_in + 1; -{%- endif %} - -{%- if dims.ny_e > 0 and simulink_opts.inputs.cost_W_e %} {#- cost_W_e #} -input_note = strcat(input_note, num2str(i_in), ') cost_W_e in column-major format, size [{{ dims.ny_e * dims.ny_e }}]\n '); -sfun_input_names = [sfun_input_names; 'cost_W_e [{{ dims.ny_e * dims.ny_e }}]']; -i_in = i_in + 1; -{%- endif %} - -{%- if simulink_opts.inputs.reset_solver %} {#- reset_solver #} -input_note = strcat(input_note, num2str(i_in), ') reset_solver determines if iterate is set to all zeros before other initializations (x_init, u_init) are set and before solver is called, size [1]\n '); -sfun_input_names = [sfun_input_names; 'reset_solver [1]']; -i_in = i_in + 1; -{%- endif %} - -{%- if simulink_opts.inputs.x_init %} {#- x_init #} -input_note = strcat(input_note, num2str(i_in), ') initialization of x for all shooting nodes, size [{{ dims.nx * (dims.N+1) }}]\n '); -sfun_input_names = [sfun_input_names; 'x_init [{{ dims.nx * (dims.N+1) }}]']; -i_in = i_in + 1; -{%- endif %} - -{%- if simulink_opts.inputs.u_init %} {#- u_init #} -input_note = strcat(input_note, num2str(i_in), ') initialization of u for shooting nodes 0 to N-1, size [{{ dims.nu * (dims.N) }}]\n '); -sfun_input_names = [sfun_input_names; 'u_init [{{ dims.nu * (dims.N) }}]']; -i_in = i_in + 1; -{%- endif %} - -fprintf(input_note) - -disp(' ') - -output_note = 'Outputs are:\n'; -i_out = 0; - -global sfun_output_names -sfun_output_names = {}; - -{%- if dims.nu > 0 and simulink_opts.outputs.u0 == 1 %} -i_out = i_out + 1; -output_note = strcat(output_note, num2str(i_out), ') u0, control input at node 0, size [{{ dims.nu }}]\n '); -sfun_output_names = [sfun_output_names; 'u0 [{{ dims.nu }}]']; -{%- endif %} - -{%- if simulink_opts.outputs.utraj == 1 %} -i_out = i_out + 1; -output_note = strcat(output_note, num2str(i_out), ') utraj, control input concatenated for nodes 0 to N-1, size [{{ dims.nu * dims.N }}]\n '); -sfun_output_names = [sfun_output_names; 'utraj [{{ dims.nu * dims.N }}]']; -{%- endif %} - -{%- if simulink_opts.outputs.xtraj == 1 %} -i_out = i_out + 1; -output_note = strcat(output_note, num2str(i_out), ') xtraj, state concatenated for nodes 0 to N, size [{{ dims.nx * (dims.N + 1) }}]\n '); -sfun_output_names = [sfun_output_names; 'xtraj [{{ dims.nx * (dims.N + 1) }}]']; -{%- endif %} - -{%- if simulink_opts.outputs.solver_status == 1 %} -i_out = i_out + 1; -output_note = strcat(output_note, num2str(i_out), ') acados solver status (0 = SUCCESS)\n '); -sfun_output_names = [sfun_output_names; 'solver_status']; -{%- endif %} - -{%- if simulink_opts.outputs.cost_value == 1 %} -i_out = i_out + 1; -output_note = strcat(output_note, num2str(i_out), ') cost function value\n '); -sfun_output_names = [sfun_output_names; 'cost_value']; -{%- endif %} - - -{%- if simulink_opts.outputs.KKT_residual == 1 %} -i_out = i_out + 1; -output_note = strcat(output_note, num2str(i_out), ') KKT residual\n '); -sfun_output_names = [sfun_output_names; 'KKT_residual']; -{%- endif %} - -{%- if simulink_opts.outputs.KKT_residuals == 1 %} -i_out = i_out + 1; -output_note = strcat(output_note, num2str(i_out), ') KKT residuals, size [4] (stat, eq, ineq, comp)\n '); -sfun_output_names = [sfun_output_names; 'KKT_residuals [4]']; -{%- endif %} - -{%- if dims.N > 0 and simulink_opts.outputs.x1 == 1 %} -i_out = i_out + 1; -output_note = strcat(output_note, num2str(i_out), ') x1, state at node 1\n '); -sfun_output_names = [sfun_output_names; 'x1']; -{%- endif %} - -{%- if simulink_opts.outputs.CPU_time == 1 %} -i_out = i_out + 1; -output_note = strcat(output_note, num2str(i_out), ') CPU time\n '); -sfun_output_names = [sfun_output_names; 'CPU_time']; -{%- endif %} - -{%- if simulink_opts.outputs.CPU_time_sim == 1 %} -i_out = i_out + 1; -output_note = strcat(output_note, num2str(i_out), ') CPU time integrator\n '); -sfun_output_names = [sfun_output_names; 'CPU_time_sim']; -{%- endif %} - -{%- if simulink_opts.outputs.CPU_time_qp == 1 %} -i_out = i_out + 1; -output_note = strcat(output_note, num2str(i_out), ') CPU time QP solution\n '); -sfun_output_names = [sfun_output_names; 'CPU_time_qp']; -{%- endif %} - -{%- if simulink_opts.outputs.CPU_time_lin == 1 %} -i_out = i_out + 1; -output_note = strcat(output_note, num2str(i_out), ') CPU time linearization (including integrator)\n '); -sfun_output_names = [sfun_output_names; 'CPU_time_lin']; -{%- endif %} - -{%- if simulink_opts.outputs.sqp_iter == 1 %} -i_out = i_out + 1; -output_note = strcat(output_note, num2str(i_out), ') SQP iterations\n '); -sfun_output_names = [sfun_output_names; 'sqp_iter']; -{%- endif %} - -fprintf(output_note) - -% The mask drawing command is: -% --- -% global sfun_input_names sfun_output_names -% for i = 1:length(sfun_input_names) -% port_label('input', i, sfun_input_names{i}) -% end -% for i = 1:length(sfun_output_names) -% port_label('output', i, sfun_output_names{i}) -% end -% --- -% It can be used by copying it in sfunction/Mask/Edit mask/Icon drawing commands -% (you can access it wirth ctrl+M on the s-function) \ No newline at end of file diff --git a/third_party/acados/acados_template/c_templates_tera/matlab_templates/make_sfun_sim.in.m b/third_party/acados/acados_template/c_templates_tera/matlab_templates/make_sfun_sim.in.m deleted file mode 100644 index e4c32a8c19..0000000000 --- a/third_party/acados/acados_template/c_templates_tera/matlab_templates/make_sfun_sim.in.m +++ /dev/null @@ -1,137 +0,0 @@ -% -% Copyright (c) The acados authors. -% -% This file is part of acados. -% -% The 2-Clause BSD License -% -% 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. -% -% 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.; - -% - -SOURCES = [ 'acados_sim_solver_sfunction_{{ model.name }}.c ', ... - 'acados_sim_solver_{{ model.name }}.c ', ... - {%- if solver_options.integrator_type == 'ERK' %} - '{{ model.name }}_model/{{ model.name }}_expl_ode_fun.c ',... - '{{ model.name }}_model/{{ model.name }}_expl_vde_forw.c ',... - '{{ model.name }}_model/{{ model.name }}_expl_vde_adj.c ',... - {%- if solver_options.hessian_approx == 'EXACT' %} - '{{ model.name }}_model/{{ model.name }}_expl_ode_hess.c ',... - {%- endif %} - {%- elif solver_options.integrator_type == "IRK" %} - '{{ model.name }}_model/{{ model.name }}_impl_dae_fun.c ', ... - '{{ model.name }}_model/{{ model.name }}_impl_dae_fun_jac_x_xdot_z.c ', ... - '{{ model.name }}_model/{{ model.name }}_impl_dae_jac_x_xdot_u_z.c ', ... - {%- if solver_options.hessian_approx == 'EXACT' %} - '{{ model.name }}_model/{{ model.name }}_impl_dae_hess.c ',... - {%- endif %} - {%- elif solver_options.integrator_type == "GNSF" %} - {%- if model.gnsf.purely_linear != 1 %} - '{{ model.name }}_model/{{ model.name }}_gnsf_phi_fun.c ',... - '{{ model.name }}_model/{{ model.name }}_gnsf_phi_fun_jac_y.c ',... - '{{ model.name }}_model/{{ model.name }}_gnsf_phi_jac_y_uhat.c ',... - {%- if model.gnsf.nontrivial_f_LO == 1 %} - '{{ model.name }}_model/{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz.c ',... - {%- endif %} - {%- endif %} - '{{ model.name }}_model/{{ model.name }}_gnsf_get_matrices_fun.c ',... - {%- endif %} - ]; - -INC_PATH = '{{ acados_include_path }}'; - -INCS = [ ' -I', fullfile(INC_PATH, 'blasfeo', 'include'), ... - ' -I', fullfile(INC_PATH, 'hpipm', 'include'), ... - ' -I', INC_PATH, ' -I', fullfile(INC_PATH, 'acados'), ' ']; - -CFLAGS = ' -O'; - -LIB_PATH = '{{ acados_lib_path }}'; - -LIBS = '-lacados -lblasfeo -lhpipm'; - -try - % eval( [ 'mex -v -output acados_sim_solver_sfunction_{{ model.name }} ', ... - eval( [ 'mex -output acados_sim_solver_sfunction_{{ model.name }} ', ... - CFLAGS, INCS, ' ', SOURCES, ' -L', LIB_PATH, ' ', LIBS ]); - -catch exception - disp('make_sfun failed with the following exception:') - disp(exception); - disp('Try adding -v to the mex command above to get more information.') - keyboard -end - - -fprintf( [ '\n\nSuccessfully created sfunction:\nacados_sim_solver_sfunction_{{ model.name }}', '.', ... - eval('mexext')] ); - - -global sfun_sim_input_names -sfun_sim_input_names = {}; - -%% print note on usage of s-function -fprintf('\n\nNote: Usage of Sfunction is as follows:\n') -input_note = 'Inputs are:\n1) x0, initial state, size [{{ dims.nx }}]\n '; -i_in = 2; -sfun_sim_input_names = [sfun_sim_input_names; 'x0 [{{ dims.nx }}]']; - -{%- if dims.nu > 0 %} -input_note = strcat(input_note, num2str(i_in), ') u, size [{{ dims.nu }}]\n '); -i_in = i_in + 1; -sfun_sim_input_names = [sfun_sim_input_names; 'u [{{ dims.nu }}]']; -{%- endif %} - -{%- if dims.np > 0 %} -input_note = strcat(input_note, num2str(i_in), ') parameters, size [{{ dims.np }}]\n '); -i_in = i_in + 1; -sfun_sim_input_names = [sfun_sim_input_names; 'p [{{ dims.np }}]']; -{%- endif %} - - -fprintf(input_note) - -disp(' ') - -global sfun_sim_output_names -sfun_sim_output_names = {}; - -output_note = strcat('Outputs are:\n', ... - '1) x1 - simulated state, size [{{ dims.nx }}]\n'); -sfun_sim_output_names = [sfun_sim_output_names; 'x1 [{{ dims.nx }}]']; - -fprintf(output_note) - - -% The mask drawing command is: -% --- -% global sfun_sim_input_names sfun_sim_output_names -% for i = 1:length(sfun_sim_input_names) -% port_label('input', i, sfun_sim_input_names{i}) -% end -% for i = 1:length(sfun_sim_output_names) -% port_label('output', i, sfun_sim_output_names{i}) -% end -% --- -% It can be used by copying it in sfunction/Mask/Edit mask/Icon drawing commands -% (you can access it wirth ctrl+M on the s-function) \ No newline at end of file diff --git a/third_party/acados/acados_template/c_templates_tera/matlab_templates/mex_solver.in.m b/third_party/acados/acados_template/c_templates_tera/matlab_templates/mex_solver.in.m deleted file mode 100644 index 3743212830..0000000000 --- a/third_party/acados/acados_template/c_templates_tera/matlab_templates/mex_solver.in.m +++ /dev/null @@ -1,270 +0,0 @@ -% -% Copyright (c) The acados authors. -% -% This file is part of acados. -% -% The 2-Clause BSD License -% -% 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. -% -% 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.; - -% - -classdef {{ model.name }}_mex_solver < handle - - properties - C_ocp - C_ocp_ext_fun - cost_ext_fun_type - cost_ext_fun_type_e - N - name - code_gen_dir - end % properties - - - - methods - - % constructor - function obj = {{ model.name }}_mex_solver() - make_mex_{{ model.name }}(); - [obj.C_ocp, obj.C_ocp_ext_fun] = acados_mex_create_{{ model.name }}(); - % to have path to destructor when changing directory - addpath('.') - obj.cost_ext_fun_type = '{{ cost.cost_ext_fun_type }}'; - obj.cost_ext_fun_type_e = '{{ cost.cost_ext_fun_type_e }}'; - obj.N = {{ dims.N }}; - obj.name = '{{ model.name }}'; - obj.code_gen_dir = pwd(); - end - - % destructor - function delete(obj) - disp("delete template..."); - return_dir = pwd(); - cd(obj.code_gen_dir); - if ~isempty(obj.C_ocp) - acados_mex_free_{{ model.name }}(obj.C_ocp); - end - cd(return_dir); - disp("done."); - end - - % solve - function solve(obj) - acados_mex_solve_{{ model.name }}(obj.C_ocp); - end - - % set -- borrowed from MEX interface - function set(varargin) - obj = varargin{1}; - field = varargin{2}; - value = varargin{3}; - if ~isa(field, 'char') - error('field must be a char vector, use '' '''); - end - if nargin==3 - acados_mex_set_{{ model.name }}(obj.cost_ext_fun_type, obj.cost_ext_fun_type_e, obj.C_ocp, obj.C_ocp_ext_fun, field, value); - elseif nargin==4 - stage = varargin{4}; - acados_mex_set_{{ model.name }}(obj.cost_ext_fun_type, obj.cost_ext_fun_type_e, obj.C_ocp, obj.C_ocp_ext_fun, field, value, stage); - else - disp('acados_ocp.set: wrong number of input arguments (2 or 3 allowed)'); - end - end - - function value = get_cost(obj) - value = ocp_get_cost(obj.C_ocp); - end - - % get -- borrowed from MEX interface - function value = get(varargin) - % usage: - % obj.get(field, value, [stage]) - obj = varargin{1}; - field = varargin{2}; - if any(strfind('sens', field)) - error('field sens* (sensitivities of optimal solution) not yet supported for templated MEX.') - end - if ~isa(field, 'char') - error('field must be a char vector, use '' '''); - end - - if nargin==2 - value = ocp_get(obj.C_ocp, field); - elseif nargin==3 - stage = varargin{3}; - value = ocp_get(obj.C_ocp, field, stage); - else - disp('acados_ocp.get: wrong number of input arguments (1 or 2 allowed)'); - end - end - - - function [] = store_iterate(varargin) - %%% Stores the current iterate of the ocp solver in a json file. - %%% param1: filename: if not set, use model_name + timestamp + '.json' - %%% param2: overwrite: if false and filename exists add timestamp to filename - - obj = varargin{1}; - filename = ''; - overwrite = false; - - if nargin>=2 - filename = varargin{2}; - if ~isa(filename, 'char') - error('filename must be a char vector, use '' '''); - end - end - - if nargin==3 - overwrite = varargin{3}; - end - - if nargin > 3 - disp('acados_ocp.get: wrong number of input arguments (1 or 2 allowed)'); - end - - if strcmp(filename,'') - filename = [obj.name '_iterate.json']; - end - if ~overwrite - % append timestamp - if exist(filename, 'file') - filename = filename(1:end-5); - filename = [filename '_' datestr(now,'yyyy-mm-dd-HH:MM:SS') '.json']; - end - end - filename = fullfile(pwd, filename); - - % get iterate: - solution = struct(); - for i=0:obj.N - solution.(['x_' num2str(i)]) = obj.get('x', i); - solution.(['lam_' num2str(i)]) = obj.get('lam', i); - solution.(['t_' num2str(i)]) = obj.get('t', i); - solution.(['sl_' num2str(i)]) = obj.get('sl', i); - solution.(['su_' num2str(i)]) = obj.get('su', i); - end - for i=0:obj.N-1 - solution.(['z_' num2str(i)]) = obj.get('z', i); - solution.(['u_' num2str(i)]) = obj.get('u', i); - solution.(['pi_' num2str(i)]) = obj.get('pi', i); - end - - acados_folder = getenv('ACADOS_INSTALL_DIR'); - addpath(fullfile(acados_folder, 'external', 'jsonlab')); - savejson('', solution, filename); - - json_string = savejson('', solution, 'ForceRootName', 0); - - fid = fopen(filename, 'w'); - if fid == -1, error('store_iterate: Cannot create JSON file'); end - fwrite(fid, json_string, 'char'); - fclose(fid); - - disp(['stored current iterate in ' filename]); - end - - - function [] = load_iterate(obj, filename) - %%% Loads the iterate stored in json file with filename into the ocp solver. - acados_folder = getenv('ACADOS_INSTALL_DIR'); - addpath(fullfile(acados_folder, 'external', 'jsonlab')); - filename = fullfile(pwd, filename); - - if ~exist(filename, 'file') - error(['load_iterate: failed, file does not exist: ' filename]) - end - - solution = loadjson(filename); - keys = fieldnames(solution); - - for k = 1:numel(keys) - key = keys{k}; - key_parts = strsplit(key, '_'); - field = key_parts{1}; - stage = key_parts{2}; - - val = solution.(key); - - % check if array is empty (can happen for z) - if numel(val) > 0 - obj.set(field, val, str2num(stage)) - end - end - end - - - % print - function print(varargin) - if nargin < 2 - field = 'stat'; - else - field = varargin{2}; - end - - obj = varargin{1}; - - if strcmp(field, 'stat') - stat = obj.get('stat'); - {%- if solver_options.nlp_solver_type == "SQP" %} - fprintf('\niter\tres_stat\tres_eq\t\tres_ineq\tres_comp\tqp_stat\tqp_iter\talpha'); - if size(stat,2)>8 - fprintf('\tqp_res_stat\tqp_res_eq\tqp_res_ineq\tqp_res_comp'); - end - fprintf('\n'); - for jj=1:size(stat,1) - fprintf('%d\t%e\t%e\t%e\t%e\t%d\t%d\t%e', stat(jj,1), stat(jj,2), stat(jj,3), stat(jj,4), stat(jj,5), stat(jj,6), stat(jj,7), stat(jj, 8)); - if size(stat,2)>8 - fprintf('\t%e\t%e\t%e\t%e', stat(jj,9), stat(jj,10), stat(jj,11), stat(jj,12)); - end - fprintf('\n'); - end - fprintf('\n'); - {%- else %} - fprintf('\niter\tqp_status\tqp_iter'); - if size(stat,2)>3 - fprintf('\tqp_res_stat\tqp_res_eq\tqp_res_ineq\tqp_res_comp'); - end - fprintf('\n'); - for jj=1:size(stat,1) - fprintf('%d\t%d\t\t%d', stat(jj,1), stat(jj,2), stat(jj,3)); - if size(stat,2)>3 - fprintf('\t%e\t%e\t%e\t%e', stat(jj,4), stat(jj,5), stat(jj,6), stat(jj,7)); - end - fprintf('\n'); - end - {% endif %} - - else - fprintf('unsupported field in function print of acados_ocp.print, got %s', field); - keyboard - end - - end - - end % methods - -end % class - diff --git a/third_party/acados/acados_template/c_templates_tera/model.in.h b/third_party/acados/acados_template/c_templates_tera/model.in.h deleted file mode 100644 index e5059df9ff..0000000000 --- a/third_party/acados/acados_template/c_templates_tera/model.in.h +++ /dev/null @@ -1,218 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - -#ifndef {{ model.name }}_MODEL -#define {{ model.name }}_MODEL - -#ifdef __cplusplus -extern "C" { -#endif - -{%- if solver_options.hessian_approx %} - {%- set hessian_approx = solver_options.hessian_approx %} -{%- elif solver_options.sens_hess %} - {%- set hessian_approx = "EXACT" %} -{%- else %} - {%- set hessian_approx = "GAUSS_NEWTON" %} -{%- endif %} - -{% if solver_options.integrator_type == "IRK" or solver_options.integrator_type == "LIFTED_IRK" %} - {% if model.dyn_ext_fun_type == "casadi" %} -// implicit ODE: function -int {{ model.name }}_impl_dae_fun(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_impl_dae_fun_work(int *, int *, int *, int *); -const int *{{ model.name }}_impl_dae_fun_sparsity_in(int); -const int *{{ model.name }}_impl_dae_fun_sparsity_out(int); -int {{ model.name }}_impl_dae_fun_n_in(void); -int {{ model.name }}_impl_dae_fun_n_out(void); - -// implicit ODE: function + jacobians -int {{ model.name }}_impl_dae_fun_jac_x_xdot_z(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_impl_dae_fun_jac_x_xdot_z_work(int *, int *, int *, int *); -const int *{{ model.name }}_impl_dae_fun_jac_x_xdot_z_sparsity_in(int); -const int *{{ model.name }}_impl_dae_fun_jac_x_xdot_z_sparsity_out(int); -int {{ model.name }}_impl_dae_fun_jac_x_xdot_z_n_in(void); -int {{ model.name }}_impl_dae_fun_jac_x_xdot_z_n_out(void); - -// implicit ODE: jacobians only -int {{ model.name }}_impl_dae_jac_x_xdot_u_z(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_impl_dae_jac_x_xdot_u_z_work(int *, int *, int *, int *); -const int *{{ model.name }}_impl_dae_jac_x_xdot_u_z_sparsity_in(int); -const int *{{ model.name }}_impl_dae_jac_x_xdot_u_z_sparsity_out(int); -int {{ model.name }}_impl_dae_jac_x_xdot_u_z_n_in(void); -int {{ model.name }}_impl_dae_jac_x_xdot_u_z_n_out(void); - -// implicit ODE - for lifted_irk -int {{ model.name }}_impl_dae_fun_jac_x_xdot_u(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_impl_dae_fun_jac_x_xdot_u_work(int *, int *, int *, int *); -const int *{{ model.name }}_impl_dae_fun_jac_x_xdot_u_sparsity_in(int); -const int *{{ model.name }}_impl_dae_fun_jac_x_xdot_u_sparsity_out(int); -int {{ model.name }}_impl_dae_fun_jac_x_xdot_u_n_in(void); -int {{ model.name }}_impl_dae_fun_jac_x_xdot_u_n_out(void); - - {%- if hessian_approx == "EXACT" %} -// implicit ODE - hessian -int {{ model.name }}_impl_dae_hess(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_impl_dae_hess_work(int *, int *, int *, int *); -const int *{{ model.name }}_impl_dae_hess_sparsity_in(int); -const int *{{ model.name }}_impl_dae_hess_sparsity_out(int); -int {{ model.name }}_impl_dae_hess_n_in(void); -int {{ model.name }}_impl_dae_hess_n_out(void); - {% endif %} - {% else %}{# ext_fun_type #} - {%- if hessian_approx == "EXACT" %} -int {{ model.dyn_impl_dae_hess }}(void **, void **, void *); - {% endif %} -int {{ model.dyn_impl_dae_fun_jac }}(void **, void **, void *); -int {{ model.dyn_impl_dae_jac }}(void **, void **, void *); -int {{ model.dyn_impl_dae_fun }}(void **, void **, void *); - {% endif %}{# ext_fun_type #} - -{% elif solver_options.integrator_type == "GNSF" %} -/* GNSF Functions */ - {% if model.gnsf.purely_linear != 1 %} -// phi_fun -int {{ model.name }}_gnsf_phi_fun(const double** arg, double** res, int* iw, double* w, void *mem); -int {{ model.name }}_gnsf_phi_fun_work(int *, int *, int *, int *); -const int *{{ model.name }}_gnsf_phi_fun_sparsity_in(int); -const int *{{ model.name }}_gnsf_phi_fun_sparsity_out(int); -int {{ model.name }}_gnsf_phi_fun_n_in(void); -int {{ model.name }}_gnsf_phi_fun_n_out(void); - -// phi_fun_jac_y -int {{ model.name }}_gnsf_phi_fun_jac_y(const double** arg, double** res, int* iw, double* w, void *mem); -int {{ model.name }}_gnsf_phi_fun_jac_y_work(int *, int *, int *, int *); -const int *{{ model.name }}_gnsf_phi_fun_jac_y_sparsity_in(int); -const int *{{ model.name }}_gnsf_phi_fun_jac_y_sparsity_out(int); -int {{ model.name }}_gnsf_phi_fun_jac_y_n_in(void); -int {{ model.name }}_gnsf_phi_fun_jac_y_n_out(void); - -// phi_jac_y_uhat -int {{ model.name }}_gnsf_phi_jac_y_uhat(const double** arg, double** res, int* iw, double* w, void *mem); -int {{ model.name }}_gnsf_phi_jac_y_uhat_work(int *, int *, int *, int *); -const int *{{ model.name }}_gnsf_phi_jac_y_uhat_sparsity_in(int); -const int *{{ model.name }}_gnsf_phi_jac_y_uhat_sparsity_out(int); -int {{ model.name }}_gnsf_phi_jac_y_uhat_n_in(void); -int {{ model.name }}_gnsf_phi_jac_y_uhat_n_out(void); - {% if model.gnsf.nontrivial_f_LO == 1 %} -// f_lo_fun_jac_x1k1uz -int {{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz(const double** arg, double** res, int* iw, double* w, void *mem); -int {{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_work(int *, int *, int *, int *); -const int *{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_sparsity_in(int); -const int *{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_sparsity_out(int); -int {{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_n_in(void); -int {{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_n_out(void); - {%- endif %} - {%- endif %} -// used to import model matrices -int {{ model.name }}_gnsf_get_matrices_fun(const double** arg, double** res, int* iw, double* w, void *mem); -int {{ model.name }}_gnsf_get_matrices_fun_work(int *, int *, int *, int *); -const int *{{ model.name }}_gnsf_get_matrices_fun_sparsity_in(int); -const int *{{ model.name }}_gnsf_get_matrices_fun_sparsity_out(int); -int {{ model.name }}_gnsf_get_matrices_fun_n_in(void); -int {{ model.name }}_gnsf_get_matrices_fun_n_out(void); - -{% elif solver_options.integrator_type == "ERK" %} -/* explicit ODE */ - -// explicit ODE -int {{ model.name }}_expl_ode_fun(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_expl_ode_fun_work(int *, int *, int *, int *); -const int *{{ model.name }}_expl_ode_fun_sparsity_in(int); -const int *{{ model.name }}_expl_ode_fun_sparsity_out(int); -int {{ model.name }}_expl_ode_fun_n_in(void); -int {{ model.name }}_expl_ode_fun_n_out(void); - -// explicit forward VDE -int {{ model.name }}_expl_vde_forw(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_expl_vde_forw_work(int *, int *, int *, int *); -const int *{{ model.name }}_expl_vde_forw_sparsity_in(int); -const int *{{ model.name }}_expl_vde_forw_sparsity_out(int); -int {{ model.name }}_expl_vde_forw_n_in(void); -int {{ model.name }}_expl_vde_forw_n_out(void); - -// explicit adjoint VDE -int {{ model.name }}_expl_vde_adj(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_expl_vde_adj_work(int *, int *, int *, int *); -const int *{{ model.name }}_expl_vde_adj_sparsity_in(int); -const int *{{ model.name }}_expl_vde_adj_sparsity_out(int); -int {{ model.name }}_expl_vde_adj_n_in(void); -int {{ model.name }}_expl_vde_adj_n_out(void); - -{%- if hessian_approx == "EXACT" %} -int {{ model.name }}_expl_ode_hess(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_expl_ode_hess_work(int *, int *, int *, int *); -const int *{{ model.name }}_expl_ode_hess_sparsity_in(int); -const int *{{ model.name }}_expl_ode_hess_sparsity_out(int); -int {{ model.name }}_expl_ode_hess_n_in(void); -int {{ model.name }}_expl_ode_hess_n_out(void); -{%- endif %} - -{% elif solver_options.integrator_type == "DISCRETE" %} - -{% if model.dyn_ext_fun_type == "casadi" %} -int {{ model.name }}_dyn_disc_phi_fun(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_dyn_disc_phi_fun_work(int *, int *, int *, int *); -const int *{{ model.name }}_dyn_disc_phi_fun_sparsity_in(int); -const int *{{ model.name }}_dyn_disc_phi_fun_sparsity_out(int); -int {{ model.name }}_dyn_disc_phi_fun_n_in(void); -int {{ model.name }}_dyn_disc_phi_fun_n_out(void); - -int {{ model.name }}_dyn_disc_phi_fun_jac(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_dyn_disc_phi_fun_jac_work(int *, int *, int *, int *); -const int *{{ model.name }}_dyn_disc_phi_fun_jac_sparsity_in(int); -const int *{{ model.name }}_dyn_disc_phi_fun_jac_sparsity_out(int); -int {{ model.name }}_dyn_disc_phi_fun_jac_n_in(void); -int {{ model.name }}_dyn_disc_phi_fun_jac_n_out(void); - -{%- if hessian_approx == "EXACT" %} -int {{ model.name }}_dyn_disc_phi_fun_jac_hess(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem); -int {{ model.name }}_dyn_disc_phi_fun_jac_hess_work(int *, int *, int *, int *); -const int *{{ model.name }}_dyn_disc_phi_fun_jac_hess_sparsity_in(int); -const int *{{ model.name }}_dyn_disc_phi_fun_jac_hess_sparsity_out(int); -int {{ model.name }}_dyn_disc_phi_fun_jac_hess_n_in(void); -int {{ model.name }}_dyn_disc_phi_fun_jac_hess_n_out(void); -{%- endif %} -{% else %} - {%- if hessian_approx == "EXACT" %} -int {{ model.dyn_disc_fun_jac_hess }}(void **, void **, void *); - {% endif %} -int {{ model.dyn_disc_fun_jac }}(void **, void **, void *); -int {{ model.dyn_disc_fun }}(void **, void **, void *); -{% endif %} - - -{% endif %} - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // {{ model.name }}_MODEL diff --git a/third_party/acados/acados_template/casadi_function_generation.py b/third_party/acados/acados_template/casadi_function_generation.py deleted file mode 100644 index 6373a2809d..0000000000 --- a/third_party/acados/acados_template/casadi_function_generation.py +++ /dev/null @@ -1,708 +0,0 @@ -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# 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. -# -# 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.; -# - -import os -import casadi as ca -from .utils import is_empty, casadi_length - - -def get_casadi_symbol(x): - if isinstance(x, ca.MX): - return ca.MX.sym - elif isinstance(x, ca.SX): - return ca.SX.sym - else: - raise TypeError("Expected casadi SX or MX.") - -################ -# Dynamics -################ - - -def generate_c_code_discrete_dynamics( model, opts ): - - casadi_codegen_opts = dict(mex=False, casadi_int='int', casadi_real='double') - - # load model - x = model.x - u = model.u - p = model.p - phi = model.disc_dyn_expr - model_name = model.name - nx = casadi_length(x) - - symbol = get_casadi_symbol(x) - # assume nx1 = nx !!! - lam = symbol('lam', nx, 1) - - # generate jacobians - ux = ca.vertcat(u,x) - jac_ux = ca.jacobian(phi, ux) - # generate adjoint - adj_ux = ca.jtimes(phi, ux, lam, True) - # generate hessian - hess_ux = ca.jacobian(adj_ux, ux) - - # change directory - cwd = os.getcwd() - model_dir = os.path.abspath(os.path.join(opts["code_export_directory"], f'{model_name}_model')) - if not os.path.exists(model_dir): - os.makedirs(model_dir) - os.chdir(model_dir) - - # set up & generate ca.Functions - fun_name = model_name + '_dyn_disc_phi_fun' - phi_fun = ca.Function(fun_name, [x, u, p], [phi]) - phi_fun.generate(fun_name, casadi_codegen_opts) - - fun_name = model_name + '_dyn_disc_phi_fun_jac' - phi_fun_jac_ut_xt = ca.Function(fun_name, [x, u, p], [phi, jac_ux.T]) - phi_fun_jac_ut_xt.generate(fun_name, casadi_codegen_opts) - - fun_name = model_name + '_dyn_disc_phi_fun_jac_hess' - phi_fun_jac_ut_xt_hess = ca.Function(fun_name, [x, u, lam, p], [phi, jac_ux.T, hess_ux]) - phi_fun_jac_ut_xt_hess.generate(fun_name, casadi_codegen_opts) - - os.chdir(cwd) - return - - - -def generate_c_code_explicit_ode( model, opts ): - - casadi_codegen_opts = dict(mex=False, casadi_int='int', casadi_real='double') - - generate_hess = opts["generate_hess"] - - # load model - x = model.x - u = model.u - p = model.p - f_expl = model.f_expl_expr - model_name = model.name - - ## get model dimensions - nx = x.size()[0] - nu = u.size()[0] - - symbol = get_casadi_symbol(x) - - ## set up functions to be exported - Sx = symbol('Sx', nx, nx) - Sp = symbol('Sp', nx, nu) - lambdaX = symbol('lambdaX', nx, 1) - - fun_name = model_name + '_expl_ode_fun' - - ## Set up functions - expl_ode_fun = ca.Function(fun_name, [x, u, p], [f_expl]) - - vdeX = ca.jtimes(f_expl,x,Sx) - vdeP = ca.jacobian(f_expl,u) + ca.jtimes(f_expl,x,Sp) - - fun_name = model_name + '_expl_vde_forw' - - expl_vde_forw = ca.Function(fun_name, [x, Sx, Sp, u, p], [f_expl, vdeX, vdeP]) - - adj = ca.jtimes(f_expl, ca.vertcat(x, u), lambdaX, True) - - fun_name = model_name + '_expl_vde_adj' - expl_vde_adj = ca.Function(fun_name, [x, lambdaX, u, p], [adj]) - - if generate_hess: - S_forw = ca.vertcat(ca.horzcat(Sx, Sp), ca.horzcat(ca.DM.zeros(nu,nx), ca.DM.eye(nu))) - hess = ca.mtimes(ca.transpose(S_forw),ca.jtimes(adj, ca.vertcat(x,u), S_forw)) - hess2 = [] - for j in range(nx+nu): - for i in range(j,nx+nu): - hess2 = ca.vertcat(hess2, hess[i,j]) - - fun_name = model_name + '_expl_ode_hess' - expl_ode_hess = ca.Function(fun_name, [x, Sx, Sp, lambdaX, u, p], [adj, hess2]) - - # change directory - cwd = os.getcwd() - model_dir = os.path.abspath(os.path.join(opts["code_export_directory"], f'{model_name}_model')) - if not os.path.exists(model_dir): - os.makedirs(model_dir) - os.chdir(model_dir) - - # generate C code - fun_name = model_name + '_expl_ode_fun' - expl_ode_fun.generate(fun_name, casadi_codegen_opts) - - fun_name = model_name + '_expl_vde_forw' - expl_vde_forw.generate(fun_name, casadi_codegen_opts) - - fun_name = model_name + '_expl_vde_adj' - expl_vde_adj.generate(fun_name, casadi_codegen_opts) - - if generate_hess: - fun_name = model_name + '_expl_ode_hess' - expl_ode_hess.generate(fun_name, casadi_codegen_opts) - os.chdir(cwd) - - return - - -def generate_c_code_implicit_ode( model, opts ): - - casadi_codegen_opts = dict(mex=False, casadi_int='int', casadi_real='double') - - # load model - x = model.x - xdot = model.xdot - u = model.u - z = model.z - p = model.p - f_impl = model.f_impl_expr - model_name = model.name - - # get model dimensions - nx = casadi_length(x) - nz = casadi_length(z) - - # generate jacobians - jac_x = ca.jacobian(f_impl, x) - jac_xdot = ca.jacobian(f_impl, xdot) - jac_u = ca.jacobian(f_impl, u) - jac_z = ca.jacobian(f_impl, z) - - # Set up functions - p = model.p - fun_name = model_name + '_impl_dae_fun' - impl_dae_fun = ca.Function(fun_name, [x, xdot, u, z, p], [f_impl]) - - fun_name = model_name + '_impl_dae_fun_jac_x_xdot_z' - impl_dae_fun_jac_x_xdot_z = ca.Function(fun_name, [x, xdot, u, z, p], [f_impl, jac_x, jac_xdot, jac_z]) - - fun_name = model_name + '_impl_dae_fun_jac_x_xdot_u_z' - impl_dae_fun_jac_x_xdot_u_z = ca.Function(fun_name, [x, xdot, u, z, p], [f_impl, jac_x, jac_xdot, jac_u, jac_z]) - - fun_name = model_name + '_impl_dae_fun_jac_x_xdot_u' - impl_dae_fun_jac_x_xdot_u = ca.Function(fun_name, [x, xdot, u, z, p], [f_impl, jac_x, jac_xdot, jac_u]) - - fun_name = model_name + '_impl_dae_jac_x_xdot_u_z' - impl_dae_jac_x_xdot_u_z = ca.Function(fun_name, [x, xdot, u, z, p], [jac_x, jac_xdot, jac_u, jac_z]) - - if opts["generate_hess"]: - x_xdot_z_u = ca.vertcat(x, xdot, z, u) - symbol = get_casadi_symbol(x) - multiplier = symbol('multiplier', nx + nz) - ADJ = ca.jtimes(f_impl, x_xdot_z_u, multiplier, True) - HESS = ca.jacobian(ADJ, x_xdot_z_u) - fun_name = model_name + '_impl_dae_hess' - impl_dae_hess = ca.Function(fun_name, [x, xdot, u, z, multiplier, p], [HESS]) - - # change directory - cwd = os.getcwd() - model_dir = os.path.abspath(os.path.join(opts["code_export_directory"], f'{model_name}_model')) - if not os.path.exists(model_dir): - os.makedirs(model_dir) - os.chdir(model_dir) - - # generate C code - fun_name = model_name + '_impl_dae_fun' - impl_dae_fun.generate(fun_name, casadi_codegen_opts) - - fun_name = model_name + '_impl_dae_fun_jac_x_xdot_z' - impl_dae_fun_jac_x_xdot_z.generate(fun_name, casadi_codegen_opts) - - fun_name = model_name + '_impl_dae_jac_x_xdot_u_z' - impl_dae_jac_x_xdot_u_z.generate(fun_name, casadi_codegen_opts) - - fun_name = model_name + '_impl_dae_fun_jac_x_xdot_u_z' - impl_dae_fun_jac_x_xdot_u_z.generate(fun_name, casadi_codegen_opts) - - fun_name = model_name + '_impl_dae_fun_jac_x_xdot_u' - impl_dae_fun_jac_x_xdot_u.generate(fun_name, casadi_codegen_opts) - - if opts["generate_hess"]: - fun_name = model_name + '_impl_dae_hess' - impl_dae_hess.generate(fun_name, casadi_codegen_opts) - - os.chdir(cwd) - return - - -def generate_c_code_gnsf( model, opts ): - - casadi_codegen_opts = dict(mex=False, casadi_int='int', casadi_real='double') - - model_name = model.name - - # set up directory - cwd = os.getcwd() - model_dir = os.path.abspath(os.path.join(opts["code_export_directory"], f'{model_name}_model')) - if not os.path.exists(model_dir): - os.makedirs(model_dir) - os.chdir(model_dir) - - # obtain gnsf dimensions - get_matrices_fun = model.get_matrices_fun - phi_fun = model.phi_fun - - size_gnsf_A = get_matrices_fun.size_out(0) - gnsf_nx1 = size_gnsf_A[1] - gnsf_nz1 = size_gnsf_A[0] - size_gnsf_A[1] - gnsf_nuhat = max(phi_fun.size_in(1)) - gnsf_ny = max(phi_fun.size_in(0)) - gnsf_nout = max(phi_fun.size_out(0)) - - # set up expressions - # if the model uses ca.MX because of cost/constraints - # the DAE can be exported as ca.SX -> detect GNSF in Matlab - # -> evaluated ca.SX GNSF functions with ca.MX. - u = model.u - symbol = get_casadi_symbol(u) - - y = symbol("y", gnsf_ny, 1) - uhat = symbol("uhat", gnsf_nuhat, 1) - p = model.p - x1 = symbol("gnsf_x1", gnsf_nx1, 1) - x1dot = symbol("gnsf_x1dot", gnsf_nx1, 1) - z1 = symbol("gnsf_z1", gnsf_nz1, 1) - dummy = symbol("gnsf_dummy", 1, 1) - empty_var = symbol("gnsf_empty_var", 0, 0) - - ## generate C code - fun_name = model_name + '_gnsf_phi_fun' - phi_fun_ = ca.Function(fun_name, [y, uhat, p], [phi_fun(y, uhat, p)]) - phi_fun_.generate(fun_name, casadi_codegen_opts) - - fun_name = model_name + '_gnsf_phi_fun_jac_y' - phi_fun_jac_y = model.phi_fun_jac_y - phi_fun_jac_y_ = ca.Function(fun_name, [y, uhat, p], phi_fun_jac_y(y, uhat, p)) - phi_fun_jac_y_.generate(fun_name, casadi_codegen_opts) - - fun_name = model_name + '_gnsf_phi_jac_y_uhat' - phi_jac_y_uhat = model.phi_jac_y_uhat - phi_jac_y_uhat_ = ca.Function(fun_name, [y, uhat, p], phi_jac_y_uhat(y, uhat, p)) - phi_jac_y_uhat_.generate(fun_name, casadi_codegen_opts) - - fun_name = model_name + '_gnsf_f_lo_fun_jac_x1k1uz' - f_lo_fun_jac_x1k1uz = model.f_lo_fun_jac_x1k1uz - f_lo_fun_jac_x1k1uz_eval = f_lo_fun_jac_x1k1uz(x1, x1dot, z1, u, p) - - # avoid codegeneration issue - if not isinstance(f_lo_fun_jac_x1k1uz_eval, tuple) and is_empty(f_lo_fun_jac_x1k1uz_eval): - f_lo_fun_jac_x1k1uz_eval = [empty_var] - - f_lo_fun_jac_x1k1uz_ = ca.Function(fun_name, [x1, x1dot, z1, u, p], - f_lo_fun_jac_x1k1uz_eval) - f_lo_fun_jac_x1k1uz_.generate(fun_name, casadi_codegen_opts) - - fun_name = model_name + '_gnsf_get_matrices_fun' - get_matrices_fun_ = ca.Function(fun_name, [dummy], get_matrices_fun(1)) - get_matrices_fun_.generate(fun_name, casadi_codegen_opts) - - # remove fields for json dump - del model.phi_fun - del model.phi_fun_jac_y - del model.phi_jac_y_uhat - del model.f_lo_fun_jac_x1k1uz - del model.get_matrices_fun - - os.chdir(cwd) - - return - - -################ -# Cost -################ - -def generate_c_code_external_cost(model, stage_type, opts): - - casadi_codegen_opts = dict(mex=False, casadi_int='int', casadi_real='double') - - x = model.x - p = model.p - u = model.u - z = model.z - symbol = get_casadi_symbol(x) - - if stage_type == 'terminal': - suffix_name = "_cost_ext_cost_e_fun" - suffix_name_hess = "_cost_ext_cost_e_fun_jac_hess" - suffix_name_jac = "_cost_ext_cost_e_fun_jac" - ext_cost = model.cost_expr_ext_cost_e - custom_hess = model.cost_expr_ext_cost_custom_hess_e - # Last stage cannot depend on u and z - u = symbol("u", 0, 0) - z = symbol("z", 0, 0) - - elif stage_type == 'path': - suffix_name = "_cost_ext_cost_fun" - suffix_name_hess = "_cost_ext_cost_fun_jac_hess" - suffix_name_jac = "_cost_ext_cost_fun_jac" - ext_cost = model.cost_expr_ext_cost - custom_hess = model.cost_expr_ext_cost_custom_hess - - elif stage_type == 'initial': - suffix_name = "_cost_ext_cost_0_fun" - suffix_name_hess = "_cost_ext_cost_0_fun_jac_hess" - suffix_name_jac = "_cost_ext_cost_0_fun_jac" - ext_cost = model.cost_expr_ext_cost_0 - custom_hess = model.cost_expr_ext_cost_custom_hess_0 - - nunx = x.shape[0] + u.shape[0] - - # set up functions to be exported - fun_name = model.name + suffix_name - fun_name_hess = model.name + suffix_name_hess - fun_name_jac = model.name + suffix_name_jac - - # generate expression for full gradient and Hessian - hess_uxz, grad_uxz = ca.hessian(ext_cost, ca.vertcat(u, x, z)) - - hess_ux = hess_uxz[:nunx, :nunx] - hess_z = hess_uxz[nunx:, nunx:] - hess_z_ux = hess_uxz[nunx:, :nunx] - - if custom_hess is not None: - hess_ux = custom_hess - - ext_cost_fun = ca.Function(fun_name, [x, u, z, p], [ext_cost]) - - ext_cost_fun_jac_hess = ca.Function( - fun_name_hess, [x, u, z, p], [ext_cost, grad_uxz, hess_ux, hess_z, hess_z_ux] - ) - ext_cost_fun_jac = ca.Function( - fun_name_jac, [x, u, z, p], [ext_cost, grad_uxz] - ) - - # change directory - cwd = os.getcwd() - cost_dir = os.path.abspath(os.path.join(opts["code_export_directory"], f'{model.name}_cost')) - if not os.path.exists(cost_dir): - os.makedirs(cost_dir) - os.chdir(cost_dir) - - ext_cost_fun.generate(fun_name, casadi_codegen_opts) - ext_cost_fun_jac_hess.generate(fun_name_hess, casadi_codegen_opts) - ext_cost_fun_jac.generate(fun_name_jac, casadi_codegen_opts) - - os.chdir(cwd) - return - - -def generate_c_code_nls_cost( model, cost_name, stage_type, opts ): - - casadi_codegen_opts = dict(mex=False, casadi_int='int', casadi_real='double') - - x = model.x - z = model.z - p = model.p - u = model.u - - symbol = get_casadi_symbol(x) - - if stage_type == 'terminal': - middle_name = '_cost_y_e' - u = symbol('u', 0, 0) - y_expr = model.cost_y_expr_e - - elif stage_type == 'initial': - middle_name = '_cost_y_0' - y_expr = model.cost_y_expr_0 - - elif stage_type == 'path': - middle_name = '_cost_y' - y_expr = model.cost_y_expr - - # change directory - cwd = os.getcwd() - cost_dir = os.path.abspath(os.path.join(opts["code_export_directory"], f'{model.name}_cost')) - if not os.path.exists(cost_dir): - os.makedirs(cost_dir) - os.chdir(cost_dir) - - # set up expressions - cost_jac_expr = ca.transpose(ca.jacobian(y_expr, ca.vertcat(u, x))) - dy_dz = ca.jacobian(y_expr, z) - ny = casadi_length(y_expr) - - y = symbol('y', ny, 1) - - y_adj = ca.jtimes(y_expr, ca.vertcat(u, x), y, True) - y_hess = ca.jacobian(y_adj, ca.vertcat(u, x)) - - ## generate C code - suffix_name = '_fun' - fun_name = cost_name + middle_name + suffix_name - y_fun = ca.Function( fun_name, [x, u, z, p], [ y_expr ]) - y_fun.generate( fun_name, casadi_codegen_opts ) - - suffix_name = '_fun_jac_ut_xt' - fun_name = cost_name + middle_name + suffix_name - y_fun_jac_ut_xt = ca.Function(fun_name, [x, u, z, p], [ y_expr, cost_jac_expr, dy_dz ]) - y_fun_jac_ut_xt.generate( fun_name, casadi_codegen_opts ) - - suffix_name = '_hess' - fun_name = cost_name + middle_name + suffix_name - y_hess = ca.Function(fun_name, [x, u, z, y, p], [ y_hess ]) - y_hess.generate( fun_name, casadi_codegen_opts ) - - os.chdir(cwd) - - return - - - -def generate_c_code_conl_cost(model, cost_name, stage_type, opts): - - casadi_codegen_opts = dict(mex=False, casadi_int='int', casadi_real='double') - - x = model.x - z = model.z - p = model.p - - symbol = get_casadi_symbol(x) - - if stage_type == 'terminal': - u = symbol('u', 0, 0) - - yref = model.cost_r_in_psi_expr_e - inner_expr = model.cost_y_expr_e - yref - outer_expr = model.cost_psi_expr_e - res_expr = model.cost_r_in_psi_expr_e - - suffix_name_fun = '_conl_cost_e_fun' - suffix_name_fun_jac_hess = '_conl_cost_e_fun_jac_hess' - - custom_hess = model.cost_conl_custom_outer_hess_e - - elif stage_type == 'initial': - u = model.u - - yref = model.cost_r_in_psi_expr_0 - inner_expr = model.cost_y_expr_0 - yref - outer_expr = model.cost_psi_expr_0 - res_expr = model.cost_r_in_psi_expr_0 - - suffix_name_fun = '_conl_cost_0_fun' - suffix_name_fun_jac_hess = '_conl_cost_0_fun_jac_hess' - - custom_hess = model.cost_conl_custom_outer_hess_0 - - elif stage_type == 'path': - u = model.u - - yref = model.cost_r_in_psi_expr - inner_expr = model.cost_y_expr - yref - outer_expr = model.cost_psi_expr - res_expr = model.cost_r_in_psi_expr - - suffix_name_fun = '_conl_cost_fun' - suffix_name_fun_jac_hess = '_conl_cost_fun_jac_hess' - - custom_hess = model.cost_conl_custom_outer_hess - - # set up function names - fun_name_cost_fun = model.name + suffix_name_fun - fun_name_cost_fun_jac_hess = model.name + suffix_name_fun_jac_hess - - # set up functions to be exported - outer_loss_fun = ca.Function('psi', [res_expr, p], [outer_expr]) - cost_expr = outer_loss_fun(inner_expr, p) - - outer_loss_grad_fun = ca.Function('outer_loss_grad', [res_expr, p], [ca.jacobian(outer_expr, res_expr).T]) - - if custom_hess is None: - outer_hess_fun = ca.Function('inner_hess', [res_expr, p], [ca.hessian(outer_loss_fun(res_expr, p), res_expr)[0]]) - else: - outer_hess_fun = ca.Function('inner_hess', [res_expr, p], [custom_hess]) - - Jt_ux_expr = ca.jacobian(inner_expr, ca.vertcat(u, x)).T - Jt_z_expr = ca.jacobian(inner_expr, z).T - - cost_fun = ca.Function( - fun_name_cost_fun, - [x, u, z, yref, p], - [cost_expr]) - - cost_fun_jac_hess = ca.Function( - fun_name_cost_fun_jac_hess, - [x, u, z, yref, p], - [cost_expr, outer_loss_grad_fun(inner_expr, p), Jt_ux_expr, Jt_z_expr, outer_hess_fun(inner_expr, p)] - ) - # change directory - cwd = os.getcwd() - cost_dir = os.path.abspath(os.path.join(opts["code_export_directory"], f'{model.name}_cost')) - if not os.path.exists(cost_dir): - os.makedirs(cost_dir) - os.chdir(cost_dir) - - # generate C code - cost_fun.generate(fun_name_cost_fun, casadi_codegen_opts) - cost_fun_jac_hess.generate(fun_name_cost_fun_jac_hess, casadi_codegen_opts) - - os.chdir(cwd) - - return - - -################ -# Constraints -################ -def generate_c_code_constraint( model, con_name, is_terminal, opts ): - - casadi_codegen_opts = dict(mex=False, casadi_int='int', casadi_real='double') - - # load constraint variables and expression - x = model.x - p = model.p - - symbol = get_casadi_symbol(x) - - if is_terminal: - con_h_expr = model.con_h_expr_e - con_phi_expr = model.con_phi_expr_e - # create dummy u, z - u = symbol('u', 0, 0) - z = symbol('z', 0, 0) - else: - con_h_expr = model.con_h_expr - con_phi_expr = model.con_phi_expr - u = model.u - z = model.z - - if (not is_empty(con_h_expr)) and (not is_empty(con_phi_expr)): - raise Exception("acados: you can either have constraint_h, or constraint_phi, not both.") - - if (is_empty(con_h_expr) and is_empty(con_phi_expr)): - # both empty -> nothing to generate - return - - if is_empty(con_h_expr): - constr_type = 'BGP' - else: - constr_type = 'BGH' - - if is_empty(p): - p = symbol('p', 0, 0) - - if is_empty(z): - z = symbol('z', 0, 0) - - if not (is_empty(con_h_expr)) and opts['generate_hess']: - # multipliers for hessian - nh = casadi_length(con_h_expr) - lam_h = symbol('lam_h', nh, 1) - - # set up & change directory - cwd = os.getcwd() - constraints_dir = os.path.abspath(os.path.join(opts["code_export_directory"], f'{model.name}_constraints')) - if not os.path.exists(constraints_dir): - os.makedirs(constraints_dir) - os.chdir(constraints_dir) - - # export casadi functions - if constr_type == 'BGH': - if is_terminal: - fun_name = con_name + '_constr_h_e_fun_jac_uxt_zt' - else: - fun_name = con_name + '_constr_h_fun_jac_uxt_zt' - - jac_ux_t = ca.transpose(ca.jacobian(con_h_expr, ca.vertcat(u,x))) - jac_z_t = ca.jacobian(con_h_expr, z) - constraint_fun_jac_tran = ca.Function(fun_name, [x, u, z, p], \ - [con_h_expr, jac_ux_t, jac_z_t]) - - constraint_fun_jac_tran.generate(fun_name, casadi_codegen_opts) - if opts['generate_hess']: - - if is_terminal: - fun_name = con_name + '_constr_h_e_fun_jac_uxt_zt_hess' - else: - fun_name = con_name + '_constr_h_fun_jac_uxt_zt_hess' - - # adjoint - adj_ux = ca.jtimes(con_h_expr, ca.vertcat(u, x), lam_h, True) - # hessian - hess_ux = ca.jacobian(adj_ux, ca.vertcat(u, x)) - - adj_z = ca.jtimes(con_h_expr, z, lam_h, True) - hess_z = ca.jacobian(adj_z, z) - - # set up functions - constraint_fun_jac_tran_hess = \ - ca.Function(fun_name, [x, u, lam_h, z, p], \ - [con_h_expr, jac_ux_t, hess_ux, jac_z_t, hess_z]) - - # generate C code - constraint_fun_jac_tran_hess.generate(fun_name, casadi_codegen_opts) - - if is_terminal: - fun_name = con_name + '_constr_h_e_fun' - else: - fun_name = con_name + '_constr_h_fun' - h_fun = ca.Function(fun_name, [x, u, z, p], [con_h_expr]) - h_fun.generate(fun_name, casadi_codegen_opts) - - else: # BGP constraint - if is_terminal: - fun_name = con_name + '_phi_e_constraint' - r = model.con_r_in_phi_e - con_r_expr = model.con_r_expr_e - else: - fun_name = con_name + '_phi_constraint' - r = model.con_r_in_phi - con_r_expr = model.con_r_expr - - nphi = casadi_length(con_phi_expr) - con_phi_expr_x_u_z = ca.substitute(con_phi_expr, r, con_r_expr) - phi_jac_u = ca.jacobian(con_phi_expr_x_u_z, u) - phi_jac_x = ca.jacobian(con_phi_expr_x_u_z, x) - phi_jac_z = ca.jacobian(con_phi_expr_x_u_z, z) - - hess = ca.hessian(con_phi_expr[0], r)[0] - for i in range(1, nphi): - hess = ca.vertcat(hess, ca.hessian(con_phi_expr[i], r)[0]) - - r_jac_u = ca.jacobian(con_r_expr, u) - r_jac_x = ca.jacobian(con_r_expr, x) - - constraint_phi = \ - ca.Function(fun_name, [x, u, z, p], \ - [con_phi_expr_x_u_z, \ - ca.vertcat(ca.transpose(phi_jac_u), ca.transpose(phi_jac_x)), \ - ca.transpose(phi_jac_z), \ - hess, - ca.vertcat(ca.transpose(r_jac_u), ca.transpose(r_jac_x))]) - - constraint_phi.generate(fun_name, casadi_codegen_opts) - - # change directory back - os.chdir(cwd) - - return - diff --git a/third_party/acados/acados_template/custom_update_templates/custom_update_function_zoro_template.in.c b/third_party/acados/acados_template/custom_update_templates/custom_update_function_zoro_template.in.c deleted file mode 100644 index b39ff2e23b..0000000000 --- a/third_party/acados/acados_template/custom_update_templates/custom_update_function_zoro_template.in.c +++ /dev/null @@ -1,819 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - -// This is a template based custom_update function -#include -#include -#include -#include - -#include "custom_update_function.h" -#include "acados_solver_{{ model.name }}.h" -#include "acados_c/ocp_nlp_interface.h" -#include "acados/utils/mem.h" - -#include "blasfeo/include/blasfeo_d_aux_ext_dep.h" -#include "blasfeo/include/blasfeo_d_blasfeo_api.h" - - -typedef struct custom_memory -{ - // covariance matrics - struct blasfeo_dmat *uncertainty_matrix_buffer; // shape = (N+1, nx, nx) - // covariance matrix of the additive disturbance - struct blasfeo_dmat W_mat; // shape = (nw, nw) - struct blasfeo_dmat unc_jac_G_mat; // shape = (nx, nw) - struct blasfeo_dmat temp_GW_mat; // shape = (nx, nw) - struct blasfeo_dmat GWG_mat; // shape = (nx, nx) - // sensitivity matrices - struct blasfeo_dmat A_mat; // shape = (nx, nx) - struct blasfeo_dmat B_mat; // shape = (nx, nu) - // matrix in linear constraints - struct blasfeo_dmat Cg_mat; // shape = (ng, nx) - struct blasfeo_dmat Dg_mat; // shape = (ng, nu) - struct blasfeo_dmat Cg_e_mat; // shape = (ng_e, nx) - struct blasfeo_dmat dummy_Dgh_e_mat; // shape = (ngh_e_max, nu) - // matrix in nonlinear constraints - struct blasfeo_dmat Ch_mat; // shape = (nh, nx) - struct blasfeo_dmat Dh_mat; // shape = (nh, nu) - struct blasfeo_dmat Ch_e_mat; // shape = (nh_e, nx) - // feedback gain matrix - struct blasfeo_dmat K_mat; // shape = (nu, nx) - // AK = A - B@K - struct blasfeo_dmat AK_mat; // shape = (nx, nx) - // A@P_k - struct blasfeo_dmat temp_AP_mat; // shape = (nx, nx) - // K@P_k, K@P_k@K^T - struct blasfeo_dmat temp_KP_mat; // shape = (nu, nx) - struct blasfeo_dmat temp_KPK_mat; // shape = (nu, nu) - // C + D @ K, (C + D @ K) @ P_k - struct blasfeo_dmat temp_CaDK_mat; // shape = (ngh_me_max, nx) - struct blasfeo_dmat temp_CaDKmP_mat; // shape = (ngh_me_max, nx) - struct blasfeo_dmat temp_beta_mat; // shape = (ngh_me_max, ngh_me_max) - - double *d_A_mat; // shape = (nx, nx) - double *d_B_mat; // shape = (nx, nu) - double *d_Cg_mat; // shape = (ng, nx) - double *d_Dg_mat; // shape = (ng, nu) - double *d_Cg_e_mat; // shape = (ng_e, nx) - double *d_Cgh_mat; // shape = (ng+nh, nx) - double *d_Dgh_mat; // shape = (ng+nh, nu) - double *d_Cgh_e_mat; // shape = (ng_e+nh_e, nx) - double *d_state_vec; - // upper and lower bounds on state variables - double *d_lbx; // shape = (nbx,) - double *d_ubx; // shape = (nbx,) - double *d_lbx_e; // shape = (nbx_e,) - double *d_ubx_e; // shape = (nbx_e,) - // tightened upper and lower bounds on state variables - double *d_lbx_tightened; // shape = (nbx,) - double *d_ubx_tightened; // shape = (nbx,) - double *d_lbx_e_tightened; // shape = (nbx_e,) - double *d_ubx_e_tightened; // shape = (nbx_e,) - // upper and lower bounds on control inputs - double *d_lbu; // shape = (nbu,) - double *d_ubu; // shape = (nbu,) - // tightened upper and lower bounds on control inputs - double *d_lbu_tightened; // shape = (nbu,) - double *d_ubu_tightened; // shape = (nbu,) - // upper and lower bounds on polytopic constraints - double *d_lg; // shape = (ng,) - double *d_ug; // shape = (ng,) - double *d_lg_e; // shape = (ng_e,) - double *d_ug_e; // shape = (ng_e,) - // tightened lower bounds on polytopic constraints - double *d_lg_tightened; // shape = (ng,) - double *d_ug_tightened; // shape = (ng,) - double *d_lg_e_tightened; // shape = (ng_e,) - double *d_ug_e_tightened; // shape = (ng_e,) - // upper and lower bounds on nonlinear constraints - double *d_lh; // shape = (nh,) - double *d_uh; // shape = (nh,) - double *d_lh_e; // shape = (nh_e,) - double *d_uh_e; // shape = (nh_e,) - // tightened upper and lower bounds on nonlinear constraints - double *d_lh_tightened; // shape = (nh,) - double *d_uh_tightened; // shape = (nh,) - double *d_lh_e_tightened; // shape = (nh_e,) - double *d_uh_e_tightened; // shape = (nh_e,) - - int *idxbx; // shape = (nbx,) - int *idxbu; // shape = (nbu,) - int *idxbx_e; // shape = (nbx_e,) - - void *raw_memory; // Pointer to allocated memory, to be used for freeing -} custom_memory; - -static int int_max(int num1, int num2) -{ - return (num1 > num2 ) ? num1 : num2; -} - - -static int custom_memory_calculate_size(ocp_nlp_config *nlp_config, ocp_nlp_dims *nlp_dims) -{ - int N = nlp_dims->N; - int nx = {{ dims.nx }}; - int nu = {{ dims.nu }}; - int nw = {{ zoro_description.nw }}; - - int ng = {{ dims.ng }}; - int nh = {{ dims.nh }}; - int nbx = {{ dims.nbx }}; - int nbu = {{ dims.nbu }}; - - int ng_e = {{ dims.ng_e }}; - int nh_e = {{ dims.nh_e }}; - int ngh_e_max = int_max(ng_e, nh_e); - int ngh_me_max = int_max(ngh_e_max, int_max(ng, nh)); - int nbx_e = {{ dims.nbx_e }}; - - assert({{zoro_description.nlbx_t}} <= nbx); - assert({{zoro_description.nubx_t}} <= nbx); - assert({{zoro_description.nlbu_t}} <= nbu); - assert({{zoro_description.nubu_t}} <= nbu); - assert({{zoro_description.nlg_t}} <= ng); - assert({{zoro_description.nug_t}} <= ng); - assert({{zoro_description.nlh_t}} <= nh); - assert({{zoro_description.nuh_t}} <= nh); - assert({{zoro_description.nlbx_e_t}} <= nbx_e); - assert({{zoro_description.nubx_e_t}} <= nbx_e); - assert({{zoro_description.nlg_e_t}} <= ng_e); - assert({{zoro_description.nug_e_t}} <= ng_e); - assert({{zoro_description.nlh_e_t}} <= nh_e); - assert({{zoro_description.nuh_e_t}} <= nh_e); - - acados_size_t size = sizeof(custom_memory); - size += nbx * sizeof(int); - /* blasfeo structs */ - size += (N + 1) * sizeof(struct blasfeo_dmat); - /* blasfeo mem: mat */ - size += (N + 1) * blasfeo_memsize_dmat(nx, nx); // uncertainty_matrix_buffer - size += blasfeo_memsize_dmat(nw, nw); // W_mat - size += 2 * blasfeo_memsize_dmat(nx, nw); // unc_jac_G_mat, temp_GW_mat - size += 4 * blasfeo_memsize_dmat(nx, nx); // GWG_mat, A_mat, AK_mat, temp_AP_mat - size += blasfeo_memsize_dmat(nx, nu); // B_mat - size += 2 * blasfeo_memsize_dmat(nu, nx); // K_mat, temp_KP_mat - size += blasfeo_memsize_dmat(nu, nu); // temp_KPK_mat - size += blasfeo_memsize_dmat(ng, nx); // Cg_mat - size += blasfeo_memsize_dmat(ng, nu); // Dg_mat - size += blasfeo_memsize_dmat(ng_e, nx); // Cg_e_mat - size += blasfeo_memsize_dmat(ngh_e_max, nu); // dummy_Dgh_e_mat - size += blasfeo_memsize_dmat(nh, nx); // Ch_mat - size += blasfeo_memsize_dmat(nh, nu); // Dh_mat - size += blasfeo_memsize_dmat(nh_e, nx); // Ch_e_mat - size += 2 * blasfeo_memsize_dmat(ngh_me_max, nx); // temp_CaDK_mat, temp_CaDKmP_mat - size += blasfeo_memsize_dmat(ngh_me_max, ngh_me_max); // temp_beta_mat - /* blasfeo mem: vec */ - /* Arrays */ - size += nx*nx *sizeof(double); // d_A_mat - size += nx*nu *sizeof(double); // d_B_mat - size += (ng + ng_e) * nx * sizeof(double); // d_Cg_mat, d_Cg_e_mat - size += (ng) * nu * sizeof(double); // d_Dg_mat - size += (nh + nh_e + ng + ng_e) * nx * sizeof(double); // d_Cgh_mat, d_Cgh_e_mat - size += (nh + ng) * nu * sizeof(double); // d_Dgh_mat - // d_state_vec - size += nx *sizeof(double); - // constraints and tightened constraints - size += 4 * (nbx + nbu + ng + nh)*sizeof(double); - size += 4 * (nbx_e + ng_e + nh_e)*sizeof(double); - size += (nbx + nbu + nbx_e)*sizeof(int); // idxbx, idxbu, idxbx_e - - size += 1 * 8; // initial alignment - make_int_multiple_of(64, &size); - size += 1 * 64; - - return size; -} - - -static custom_memory *custom_memory_assign(ocp_nlp_config *nlp_config, ocp_nlp_dims *nlp_dims, void *raw_memory) -{ - int N = nlp_dims->N; - int nx = {{ dims.nx }}; - int nu = {{ dims.nu }}; - int nw = {{ zoro_description.nw }}; - - int ng = {{ dims.ng }}; - int nh = {{ dims.nh }}; - int nbx = {{ dims.nbx }}; - int nbu = {{ dims.nbu }}; - - int ng_e = {{ dims.ng_e }}; - int nh_e = {{ dims.nh_e }}; - int ngh_e_max = int_max(ng_e, nh_e); - int ngh_me_max = int_max(ngh_e_max, int_max(ng, nh)); - int nbx_e = {{ dims.nbx_e }}; - - char *c_ptr = (char *) raw_memory; - custom_memory *mem = (custom_memory *) c_ptr; - c_ptr += sizeof(custom_memory); - - align_char_to(8, &c_ptr); - assign_and_advance_blasfeo_dmat_structs(N+1, &mem->uncertainty_matrix_buffer, &c_ptr); - - align_char_to(64, &c_ptr); - - for (int ii = 0; ii <= N; ii++) - { - assign_and_advance_blasfeo_dmat_mem(nx, nx, &mem->uncertainty_matrix_buffer[ii], &c_ptr); - } - // Disturbance Dynamics - assign_and_advance_blasfeo_dmat_mem(nw, nw, &mem->W_mat, &c_ptr); - assign_and_advance_blasfeo_dmat_mem(nx, nw, &mem->unc_jac_G_mat, &c_ptr); - assign_and_advance_blasfeo_dmat_mem(nx, nw, &mem->temp_GW_mat, &c_ptr); - assign_and_advance_blasfeo_dmat_mem(nx, nx, &mem->GWG_mat, &c_ptr); - // System Dynamics - assign_and_advance_blasfeo_dmat_mem(nx, nx, &mem->A_mat, &c_ptr); - assign_and_advance_blasfeo_dmat_mem(nx, nu, &mem->B_mat, &c_ptr); - assign_and_advance_blasfeo_dmat_mem(ng, nx, &mem->Cg_mat, &c_ptr); - assign_and_advance_blasfeo_dmat_mem(ng, nu, &mem->Dg_mat, &c_ptr); - assign_and_advance_blasfeo_dmat_mem(ng_e, nx, &mem->Cg_e_mat, &c_ptr); - assign_and_advance_blasfeo_dmat_mem(ngh_e_max, nu, &mem->dummy_Dgh_e_mat, &c_ptr); - assign_and_advance_blasfeo_dmat_mem(nh, nx, &mem->Ch_mat, &c_ptr); - assign_and_advance_blasfeo_dmat_mem(nh, nu, &mem->Dh_mat, &c_ptr); - assign_and_advance_blasfeo_dmat_mem(nh_e, nx, &mem->Ch_e_mat, &c_ptr); - assign_and_advance_blasfeo_dmat_mem(nu, nx, &mem->K_mat, &c_ptr); - assign_and_advance_blasfeo_dmat_mem(nx, nx, &mem->AK_mat, &c_ptr); - assign_and_advance_blasfeo_dmat_mem(nx, nx, &mem->temp_AP_mat, &c_ptr); - assign_and_advance_blasfeo_dmat_mem(nu, nx, &mem->temp_KP_mat, &c_ptr); - assign_and_advance_blasfeo_dmat_mem(nu, nu, &mem->temp_KPK_mat, &c_ptr); - assign_and_advance_blasfeo_dmat_mem(ngh_me_max, nx, &mem->temp_CaDK_mat, &c_ptr); - assign_and_advance_blasfeo_dmat_mem(ngh_me_max, nx, &mem->temp_CaDKmP_mat, &c_ptr); - assign_and_advance_blasfeo_dmat_mem(ngh_me_max, ngh_me_max, &mem->temp_beta_mat, &c_ptr); - - assign_and_advance_double(nx*nx, &mem->d_A_mat, &c_ptr); - assign_and_advance_double(nx*nu, &mem->d_B_mat, &c_ptr); - assign_and_advance_double(ng*nx, &mem->d_Cg_mat, &c_ptr); - assign_and_advance_double(ng*nu, &mem->d_Dg_mat, &c_ptr); - assign_and_advance_double(ng_e*nx, &mem->d_Cg_e_mat, &c_ptr); - assign_and_advance_double((ng + nh)*nx, &mem->d_Cgh_mat, &c_ptr); - assign_and_advance_double((ng + nh)*nu, &mem->d_Dgh_mat, &c_ptr); - assign_and_advance_double((ng_e + nh_e)*nx, &mem->d_Cgh_e_mat, &c_ptr); - assign_and_advance_double(nx, &mem->d_state_vec, &c_ptr); - assign_and_advance_double(nbx, &mem->d_lbx, &c_ptr); - assign_and_advance_double(nbx, &mem->d_ubx, &c_ptr); - assign_and_advance_double(nbx_e, &mem->d_lbx_e, &c_ptr); - assign_and_advance_double(nbx_e, &mem->d_ubx_e, &c_ptr); - assign_and_advance_double(nbx, &mem->d_lbx_tightened, &c_ptr); - assign_and_advance_double(nbx, &mem->d_ubx_tightened, &c_ptr); - assign_and_advance_double(nbx_e, &mem->d_lbx_e_tightened, &c_ptr); - assign_and_advance_double(nbx_e, &mem->d_ubx_e_tightened, &c_ptr); - assign_and_advance_double(nbu, &mem->d_lbu, &c_ptr); - assign_and_advance_double(nbu, &mem->d_ubu, &c_ptr); - assign_and_advance_double(nbu, &mem->d_lbu_tightened, &c_ptr); - assign_and_advance_double(nbu, &mem->d_ubu_tightened, &c_ptr); - assign_and_advance_double(ng, &mem->d_lg, &c_ptr); - assign_and_advance_double(ng, &mem->d_ug, &c_ptr); - assign_and_advance_double(ng_e, &mem->d_lg_e, &c_ptr); - assign_and_advance_double(ng_e, &mem->d_ug_e, &c_ptr); - assign_and_advance_double(ng, &mem->d_lg_tightened, &c_ptr); - assign_and_advance_double(ng, &mem->d_ug_tightened, &c_ptr); - assign_and_advance_double(ng_e, &mem->d_lg_e_tightened, &c_ptr); - assign_and_advance_double(ng_e, &mem->d_ug_e_tightened, &c_ptr); - assign_and_advance_double(nh, &mem->d_lh, &c_ptr); - assign_and_advance_double(nh, &mem->d_uh, &c_ptr); - assign_and_advance_double(nh_e, &mem->d_lh_e, &c_ptr); - assign_and_advance_double(nh_e, &mem->d_uh_e, &c_ptr); - assign_and_advance_double(nh, &mem->d_lh_tightened, &c_ptr); - assign_and_advance_double(nh, &mem->d_uh_tightened, &c_ptr); - assign_and_advance_double(nh_e, &mem->d_lh_e_tightened, &c_ptr); - assign_and_advance_double(nh_e, &mem->d_uh_e_tightened, &c_ptr); - - assign_and_advance_int(nbx, &mem->idxbx, &c_ptr); - assign_and_advance_int(nbu, &mem->idxbu, &c_ptr); - assign_and_advance_int(nbx_e, &mem->idxbx_e, &c_ptr); - - assert((char *) raw_memory + custom_memory_calculate_size(nlp_config, nlp_dims) >= c_ptr); - mem->raw_memory = raw_memory; - - return mem; -} - - - -static void *custom_memory_create({{ model.name }}_solver_capsule* capsule) -{ - printf("\nin custom_memory_create_function\n"); - - ocp_nlp_dims *nlp_dims = {{ model.name }}_acados_get_nlp_dims(capsule); - ocp_nlp_config *nlp_config = {{ model.name }}_acados_get_nlp_config(capsule); - acados_size_t bytes = custom_memory_calculate_size(nlp_config, nlp_dims); - - void *ptr = acados_calloc(1, bytes); - - custom_memory *custom_mem = custom_memory_assign(nlp_config, nlp_dims, ptr); - custom_mem->raw_memory = ptr; - - return custom_mem; -} - - -static void custom_val_init_function(ocp_nlp_dims *nlp_dims, ocp_nlp_in *nlp_in, ocp_nlp_solver *nlp_solver, custom_memory *custom_mem) -{ - int N = nlp_dims->N; - int nx = {{ dims.nx }}; - int nu = {{ dims.nu }}; - int nw = {{ zoro_description.nw }}; - - int ng = {{ dims.ng }}; - int nh = {{ dims.nh }}; - int nbx = {{ dims.nbx }}; - int nbu = {{ dims.nbu }}; - - int ng_e = {{ dims.ng_e }}; - int nh_e = {{ dims.nh_e }}; - int ngh_e_max = int_max(ng_e, nh_e); - int nbx_e = {{ dims.nbx_e }}; - - /* Get the state constraint bounds */ - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, 1, "idxbx", custom_mem->idxbx); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, N, "idxbx", custom_mem->idxbx_e); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, 1, "lbx", custom_mem->d_lbx); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, 1, "ubx", custom_mem->d_ubx); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, N, "lbx", custom_mem->d_lbx_e); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, N, "ubx", custom_mem->d_ubx_e); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, 1, "idxbu", custom_mem->idxbu); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, 1, "lbu", custom_mem->d_lbu); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, 1, "ubu", custom_mem->d_ubu); - // Get the Jacobians and the bounds of the linear constraints - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, 1, "lg", custom_mem->d_lg); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, 1, "ug", custom_mem->d_ug); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, N, "lg", custom_mem->d_lg_e); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, N, "ug", custom_mem->d_ug_e); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, 1, "C", custom_mem->d_Cg_mat); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, 1, "D", custom_mem->d_Dg_mat); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, N, "C", custom_mem->d_Cg_e_mat); - blasfeo_pack_dmat(ng, nx, custom_mem->d_Cg_mat, ng, &custom_mem->Cg_mat, 0, 0); - blasfeo_pack_dmat(ng, nu, custom_mem->d_Dg_mat, ng, &custom_mem->Dg_mat, 0, 0); - blasfeo_pack_dmat(ng_e, nx, custom_mem->d_Cg_e_mat, ng_e, &custom_mem->Cg_e_mat, 0, 0); - blasfeo_dgese(ngh_e_max, nu, 0., &custom_mem->dummy_Dgh_e_mat, 0, 0); //fill with zeros - // NOTE: fixed lower and upper bounds of nonlinear constraints - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, 1, "lh", custom_mem->d_lh); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, 1, "uh", custom_mem->d_uh); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, N, "lh", custom_mem->d_lh_e); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, N, "uh", custom_mem->d_uh_e); - - /* Initilize tightened constraints*/ - // NOTE: tightened constraints are only initialized once - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, 1, "lbx", custom_mem->d_lbx_tightened); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, 1, "ubx", custom_mem->d_ubx_tightened); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, N, "lbx", custom_mem->d_lbx_e_tightened); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, N, "ubx", custom_mem->d_ubx_e_tightened); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, 1, "lbu", custom_mem->d_lbu_tightened); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, 1, "ubu", custom_mem->d_ubu_tightened); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, 1, "lg", custom_mem->d_lg_tightened); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, 1, "ug", custom_mem->d_ug_tightened); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, N, "lg", custom_mem->d_lg_e_tightened); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, N, "ug", custom_mem->d_ug_e_tightened); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, 1, "lh", custom_mem->d_lh_tightened); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, 1, "uh", custom_mem->d_uh_tightened); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, N, "lh", custom_mem->d_lh_e_tightened); - ocp_nlp_constraints_model_get(nlp_solver->config, nlp_dims, nlp_in, N, "uh", custom_mem->d_uh_e_tightened); - - /* Initialize the W matrix */ - // blasfeo_dgese(nw, nw, 0., &custom_mem->W_mat, 0, 0); -{%- for ir in range(end=zoro_description.nw) %} - {%- for ic in range(end=zoro_description.nw) %} - blasfeo_dgein1({{zoro_description.W_mat[ir][ic]}}, &custom_mem->W_mat, {{ir}}, {{ic}}); - {%- endfor %} -{%- endfor %} - -{%- for ir in range(end=dims.nx) %} - {%- for ic in range(end=zoro_description.nw) %} - blasfeo_dgein1({{zoro_description.unc_jac_G_mat[ir][ic]}}, &custom_mem->unc_jac_G_mat, {{ir}}, {{ic}}); - {%- endfor %} -{%- endfor %} - - // NOTE: if G is changing this is not in init! - // temp_GW_mat = unc_jac_G_mat * W_mat - blasfeo_dgemm_nn(nx, nw, nw, 1.0, &custom_mem->unc_jac_G_mat, 0, 0, - &custom_mem->W_mat, 0, 0, 0.0, - &custom_mem->temp_GW_mat, 0, 0, &custom_mem->temp_GW_mat, 0, 0); - // GWG_mat = temp_GW_mat * unc_jac_G_mat^T - blasfeo_dgemm_nt(nx, nx, nw, 1.0, &custom_mem->temp_GW_mat, 0, 0, - &custom_mem->unc_jac_G_mat, 0, 0, 0.0, - &custom_mem->GWG_mat, 0, 0, &custom_mem->GWG_mat, 0, 0); - - /* Initialize the uncertainty_matrix_buffer[0] */ -{%- for ir in range(end=dims.nx) %} - {%- for ic in range(end=dims.nx) %} - blasfeo_dgein1({{zoro_description.P0_mat[ir][ic]}}, &custom_mem->uncertainty_matrix_buffer[0], {{ir}}, {{ic}}); - {%- endfor %} -{%- endfor %} - - /* Initialize the feedback gain matrix */ -{%- for ir in range(end=dims.nu) %} - {%- for ic in range(end=dims.nx) %} - blasfeo_dgein1({{zoro_description.fdbk_K_mat[ir][ic]}}, &custom_mem->K_mat, {{ir}}, {{ic}}); - {%- endfor %} -{%- endfor %} -} - - -int custom_update_init_function({{ model.name }}_solver_capsule* capsule) -{ - capsule->custom_update_memory = custom_memory_create(capsule); - ocp_nlp_in *nlp_in = {{ model.name }}_acados_get_nlp_in(capsule); - - ocp_nlp_dims *nlp_dims = {{ model.name }}_acados_get_nlp_dims(capsule); - ocp_nlp_solver *nlp_solver = {{ model.name }}_acados_get_nlp_solver(capsule); - custom_val_init_function(nlp_dims, nlp_in, nlp_solver, capsule->custom_update_memory); - return 1; -} - -static void compute_gh_beta(struct blasfeo_dmat* K_mat, struct blasfeo_dmat* C_mat, - struct blasfeo_dmat* D_mat, struct blasfeo_dmat* CaDK_mat, - struct blasfeo_dmat* CaDKmP_mat, struct blasfeo_dmat* beta_mat, - struct blasfeo_dmat* P_mat, - int n_cstr, int nx, int nu) -{ - // (C+DK)@P@(C^T+K^TD^T) - // CaDK_mat = C_mat + D_mat @ K_mat - blasfeo_dgemm_nn(n_cstr, nx, nu, 1.0, D_mat, 0, 0, - K_mat, 0, 0, 1.0, - C_mat, 0, 0, CaDK_mat, 0, 0); - // CaDKmP_mat = CaDK_mat @ P_mat - blasfeo_dgemm_nn(n_cstr, nx, nx, 1.0, CaDK_mat, 0, 0, - P_mat, 0, 0, 0.0, - CaDKmP_mat, 0, 0, CaDKmP_mat, 0, 0); - // beta_mat = CaDKmP_mat @ CaDK_mat^T - blasfeo_dgemm_nt(n_cstr, n_cstr, nx, 1.0, CaDKmP_mat, 0, 0, - CaDK_mat, 0, 0, 0.0, - beta_mat, 0, 0, beta_mat, 0, 0); -} - -static void compute_KPK(struct blasfeo_dmat* K_mat, struct blasfeo_dmat* temp_KP_mat, - struct blasfeo_dmat* temp_KPK_mat, struct blasfeo_dmat* P_mat, - int nx, int nu) -{ - // K @ P_k @ K^T - // temp_KP_mat = K_mat @ P_mat - blasfeo_dgemm_nn(nu, nx, nx, 1.0, K_mat, 0, 0, - P_mat, 0, 0, 0.0, - temp_KP_mat, 0, 0, temp_KP_mat, 0, 0); - // temp_KPK_mat = temp_KP_mat @ K_mat^T - blasfeo_dgemm_nt(nu, nu, nx, 1.0, temp_KP_mat, 0, 0, - K_mat, 0, 0, 0.0, - temp_KPK_mat, 0, 0, temp_KPK_mat, 0, 0); -} - -static void compute_next_P_matrix(struct blasfeo_dmat* P_mat, struct blasfeo_dmat* P_next_mat, - struct blasfeo_dmat* A_mat, struct blasfeo_dmat* B_mat, - struct blasfeo_dmat* K_mat, struct blasfeo_dmat* W_mat, - struct blasfeo_dmat* AK_mat, struct blasfeo_dmat* temp_AP_mat, int nx, int nu) -{ - // AK_mat = -B@K + A - blasfeo_dgemm_nn(nx, nx, nu, -1.0, B_mat, 0, 0, K_mat, 0, 0, - 1.0, A_mat, 0, 0, AK_mat, 0, 0); - // temp_AP_mat = AK_mat @ P_k - blasfeo_dgemm_nn(nx, nx, nx, 1.0, AK_mat, 0, 0, - P_mat, 0, 0, 0.0, - temp_AP_mat, 0, 0, temp_AP_mat, 0, 0); - // P_{k+1} = temp_AP_mat @ AK_mat^T + GWG_mat - blasfeo_dgemm_nt(nx, nx, nx, 1.0, temp_AP_mat, 0, 0, - AK_mat, 0, 0, 1.0, - W_mat, 0, 0, P_next_mat, 0, 0); -} - -static void reset_P0_matrix(ocp_nlp_dims *nlp_dims, struct blasfeo_dmat* P_mat, double* data) -{ - int nx = nlp_dims->nx[0]; - blasfeo_pack_dmat(nx, nx, data, nx, P_mat, 0, 0); -} - -static void uncertainty_propagate_and_update(ocp_nlp_solver *solver, ocp_nlp_in *nlp_in, ocp_nlp_out *nlp_out, custom_memory *custom_mem) -{ - ocp_nlp_config *nlp_config = solver->config; - ocp_nlp_dims *nlp_dims = solver->dims; - - int N = nlp_dims->N; - int nx = nlp_dims->nx[0]; - int nu = nlp_dims->nu[0]; - int nx_sqr = nx*nx; - int nbx = {{ dims.nbx }}; - int nbu = {{ dims.nbu }}; - int ng = {{ dims.ng }}; - int nh = {{ dims.nh }}; - int ng_e = {{ dims.ng_e }}; - int nh_e = {{ dims.nh_e }}; - int nbx_e = {{ dims.nbx_e }}; - double backoff_scaling_gamma = {{ zoro_description.backoff_scaling_gamma }}; - - // First Stage - // NOTE: lbx_0 and ubx_0 should not be tightened. - // NOTE: lg_0 and ug_0 are not tightened. - // NOTE: lh_0 and uh_0 are not tightened. -{%- if zoro_description.nlbu_t + zoro_description.nubu_t > 0 %} - compute_KPK(&custom_mem->K_mat, &custom_mem->temp_KP_mat, - &custom_mem->temp_KPK_mat, &(custom_mem->uncertainty_matrix_buffer[0]), nx, nu); - -{%- if zoro_description.nlbu_t > 0 %} - // backoff lbu - {%- for it in zoro_description.idx_lbu_t %} - custom_mem->d_lbu_tightened[{{it}}] - = custom_mem->d_lbu[{{it}}] - + backoff_scaling_gamma * sqrt(blasfeo_dgeex1(&custom_mem->temp_KPK_mat, - custom_mem->idxbu[{{it}}],custom_mem->idxbu[{{it}}])); - {%- endfor %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "lbu", custom_mem->d_lbu_tightened); -{%- endif %} -{%- if zoro_description.nubu_t > 0 %} - // backoff ubu - {%- for it in zoro_description.idx_ubu_t %} - custom_mem->d_ubu_tightened[{{it}}] - = custom_mem->d_ubu[{{it}}] - - backoff_scaling_gamma * sqrt(blasfeo_dgeex1(&custom_mem->temp_KPK_mat, - custom_mem->idxbu[{{it}}],custom_mem->idxbu[{{it}}])); - {%- endfor %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "ubu", custom_mem->d_ubu_tightened); -{%- endif %} -{%- endif %} - // Middle Stages - // constraint tightening: for next stage based on dynamics of ii stage - // P[ii+1] = (A-B@K) @ P[ii] @ (A-B@K).T + G@W@G.T - for (int ii = 0; ii < N-1; ii++) - { - // get and pack: A, B - ocp_nlp_get_at_stage(nlp_config, nlp_dims, solver, ii, "A", custom_mem->d_A_mat); - blasfeo_pack_dmat(nx, nx, custom_mem->d_A_mat, nx, &custom_mem->A_mat, 0, 0); - ocp_nlp_get_at_stage(nlp_config, nlp_dims, solver, ii, "B", custom_mem->d_B_mat); - blasfeo_pack_dmat(nx, nu, custom_mem->d_B_mat, nx, &custom_mem->B_mat, 0, 0); - - compute_next_P_matrix(&(custom_mem->uncertainty_matrix_buffer[ii]), - &(custom_mem->uncertainty_matrix_buffer[ii+1]), - &custom_mem->A_mat, &custom_mem->B_mat, - &custom_mem->K_mat, &custom_mem->GWG_mat, - &custom_mem->AK_mat, &custom_mem->temp_AP_mat, nx, nu); - - // state constraints -{%- if zoro_description.nlbx_t + zoro_description.nubx_t> 0 %} - {%- if zoro_description.nlbx_t > 0 %} - // lbx - {%- for it in zoro_description.idx_lbx_t %} - custom_mem->d_lbx_tightened[{{it}}] - = custom_mem->d_lbx[{{it}}] - + backoff_scaling_gamma * sqrt(blasfeo_dgeex1(&custom_mem->uncertainty_matrix_buffer[ii+1], - custom_mem->idxbx[{{it}}],custom_mem->idxbx[{{it}}])); - {%- endfor %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, ii+1, "lbx", custom_mem->d_lbx_tightened); - {%- endif %} - {% if zoro_description.nubx_t > 0 %} - // ubx - {%- for it in zoro_description.idx_ubx_t %} - custom_mem->d_ubx_tightened[{{it}}] = custom_mem->d_ubx[{{it}}] - - backoff_scaling_gamma * sqrt(blasfeo_dgeex1(&custom_mem->uncertainty_matrix_buffer[ii+1], - custom_mem->idxbx[{{it}}],custom_mem->idxbx[{{it}}])); - {%- endfor %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, ii+1, "ubx", custom_mem->d_ubx_tightened); - {%- endif %} -{%- endif %} - -{%- if zoro_description.nlbu_t + zoro_description.nubu_t > 0 %} - // input constraints - compute_KPK(&custom_mem->K_mat, &custom_mem->temp_KP_mat, - &custom_mem->temp_KPK_mat, &(custom_mem->uncertainty_matrix_buffer[ii+1]), nx, nu); - - {%- if zoro_description.nlbu_t > 0 %} - {%- for it in zoro_description.idx_lbu_t %} - custom_mem->d_lbu_tightened[{{it}}] = custom_mem->d_lbu[{{it}}] - + backoff_scaling_gamma * sqrt(blasfeo_dgeex1(&custom_mem->temp_KPK_mat, - custom_mem->idxbu[{{it}}], custom_mem->idxbu[{{it}}])); - {%- endfor %} - - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, ii+1, "lbu", custom_mem->d_lbu_tightened); - {%- endif %} - {%- if zoro_description.nubu_t > 0 %} - {%- for it in zoro_description.idx_ubu_t %} - custom_mem->d_ubu_tightened[{{it}}] = custom_mem->d_ubu[{{it}}] - - backoff_scaling_gamma * sqrt(blasfeo_dgeex1(&custom_mem->temp_KPK_mat, - custom_mem->idxbu[{{it}}], custom_mem->idxbu[{{it}}])); - {%- endfor %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, ii+1, "ubu", custom_mem->d_ubu_tightened); - {%- endif %} -{%- endif %} - -{%- if zoro_description.nlg_t + zoro_description.nug_t > 0 %} - // Linear constraints: g - compute_gh_beta(&custom_mem->K_mat, &custom_mem->Cg_mat, - &custom_mem->Dg_mat, &custom_mem->temp_CaDK_mat, - &custom_mem->temp_CaDKmP_mat, &custom_mem->temp_beta_mat, - &custom_mem->uncertainty_matrix_buffer[ii+1], ng, nx, nu); - - {%- if zoro_description.nlg_t > 0 %} - {%- for it in zoro_description.idx_lg_t %} - custom_mem->d_lg_tightened[{{it}}] - = custom_mem->d_lg[{{it}}] - + backoff_scaling_gamma * sqrt(blasfeo_dgeex1(&custom_mem->temp_beta_mat, {{it}}, {{it}})); - {%- endfor %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, ii+1, "lg", custom_mem->d_lg_tightened); - {%- endif %} - {%- if zoro_description.nug_t > 0 %} - {%- for it in zoro_description.idx_ug_t %} - custom_mem->d_ug_tightened[{{it}}] - = custom_mem->d_ug[{{it}}] - - backoff_scaling_gamma * sqrt(blasfeo_dgeex1(&custom_mem->temp_beta_mat, {{it}}, {{it}})); - {%- endfor %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, ii+1, "ug", custom_mem->d_ug_tightened); - {%- endif %} -{%- endif %} - - -{%- if zoro_description.nlh_t + zoro_description.nuh_t > 0 %} - // nonlinear constraints: h - // Get C_{k+1} and D_{k+1} - ocp_nlp_get_at_stage(solver->config, nlp_dims, solver, ii+1, "C", custom_mem->d_Cgh_mat); - ocp_nlp_get_at_stage(solver->config, nlp_dims, solver, ii+1, "D", custom_mem->d_Dgh_mat); - // NOTE: the d_Cgh_mat is column-major, the first ng rows are the Jacobians of the linear constraints - blasfeo_pack_dmat(nh, nx, custom_mem->d_Cgh_mat+ng, ng+nh, &custom_mem->Ch_mat, 0, 0); - blasfeo_pack_dmat(nh, nu, custom_mem->d_Dgh_mat+ng, ng+nh, &custom_mem->Dh_mat, 0, 0); - - compute_gh_beta(&custom_mem->K_mat, &custom_mem->Ch_mat, - &custom_mem->Dh_mat, &custom_mem->temp_CaDK_mat, - &custom_mem->temp_CaDKmP_mat, &custom_mem->temp_beta_mat, - &custom_mem->uncertainty_matrix_buffer[ii+1], nh, nx, nu); - - {%- if zoro_description.nlh_t > 0 %} - {%- for it in zoro_description.idx_lh_t %} - custom_mem->d_lh_tightened[{{it}}] - = custom_mem->d_lh[{{it}}] - + backoff_scaling_gamma * sqrt(blasfeo_dgeex1(&custom_mem->temp_beta_mat, {{it}}, {{it}})); - {%- endfor %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, ii+1, "lh", custom_mem->d_lh_tightened); - {%- endif %} - {%- if zoro_description.nuh_t > 0 %} - {%- for it in zoro_description.idx_uh_t %} - custom_mem->d_uh_tightened[{{it}}] = custom_mem->d_uh[{{it}}] - - backoff_scaling_gamma * sqrt(blasfeo_dgeex1(&custom_mem->temp_beta_mat, {{it}}, {{it}})); - {%- endfor %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, ii+1, "uh", custom_mem->d_uh_tightened); - {%- endif %} -{%- endif %} - } - - // Last stage - // get and pack: A, B - ocp_nlp_get_at_stage(nlp_config, nlp_dims, solver, N-1, "A", custom_mem->d_A_mat); - blasfeo_pack_dmat(nx, nx, custom_mem->d_A_mat, nx, &custom_mem->A_mat, 0, 0); - ocp_nlp_get_at_stage(nlp_config, nlp_dims, solver, N-1, "B", custom_mem->d_B_mat); - blasfeo_pack_dmat(nx, nu, custom_mem->d_B_mat, nx, &custom_mem->B_mat, 0, 0); - // AK_mat = -B*K + A - compute_next_P_matrix(&(custom_mem->uncertainty_matrix_buffer[N-1]), - &(custom_mem->uncertainty_matrix_buffer[N]), - &custom_mem->A_mat, &custom_mem->B_mat, - &custom_mem->K_mat, &custom_mem->GWG_mat, - &custom_mem->AK_mat, &custom_mem->temp_AP_mat, nx, nu); - - // state constraints nlbx_e_t -{%- if zoro_description.nlbx_e_t + zoro_description.nubx_e_t> 0 %} -{%- if zoro_description.nlbx_e_t > 0 %} - // lbx_e - {%- for it in zoro_description.idx_lbx_e_t %} - custom_mem->d_lbx_e_tightened[{{it}}] - = custom_mem->d_lbx_e[{{it}}] - + backoff_scaling_gamma * sqrt(blasfeo_dgeex1(&custom_mem->uncertainty_matrix_buffer[N], - custom_mem->idxbx_e[{{it}}],custom_mem->idxbx_e[{{it}}])); - {%- endfor %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lbx", custom_mem->d_lbx_e_tightened); -{%- endif %} -{% if zoro_description.nubx_e_t > 0 %} - // ubx_e - {%- for it in zoro_description.idx_ubx_e_t %} - custom_mem->d_ubx_e_tightened[{{it}}] = custom_mem->d_ubx_e[{{it}}] - - backoff_scaling_gamma * sqrt(blasfeo_dgeex1(&custom_mem->uncertainty_matrix_buffer[N], - custom_mem->idxbx_e[{{it}}],custom_mem->idxbx_e[{{it}}])); - {%- endfor %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "ubx", custom_mem->d_ubx_e_tightened); -{%- endif %} -{%- endif %} - -{%- if zoro_description.nlg_e_t + zoro_description.nug_e_t > 0 %} - // Linear constraints: g - compute_gh_beta(&custom_mem->K_mat, &custom_mem->Cg_mat, - &custom_mem->dummy_Dgh_e_mat, &custom_mem->temp_CaDK_mat, - &custom_mem->temp_CaDKmP_mat, &custom_mem->temp_beta_mat, - &custom_mem->uncertainty_matrix_buffer[N], ng, nx, nu); - -{%- if zoro_description.nlg_e_t > 0 %} - {%- for it in zoro_description.idx_lg_e_t %} - custom_mem->d_lg_e_tightened[{{it}}] - = custom_mem->d_lg_e[{{it}}] - + backoff_scaling_gamma * sqrt(blasfeo_dgeex1(&custom_mem->temp_beta_mat, {{it}}, {{it}})); - {%- endfor %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lg", custom_mem->d_lg_e_tightened); -{%- endif %} -{%- if zoro_description.nug_e_t > 0 %} - {%- for it in zoro_description.idx_ug_e_t %} - custom_mem->d_ug_e_tightened[{{it}}] - = custom_mem->d_ug_e[{{it}}] - - backoff_scaling_gamma * sqrt(blasfeo_dgeex1(&custom_mem->temp_beta_mat, {{it}}, {{it}})); - {%- endfor %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "ug", custom_mem->d_ug_e_tightened); -{%- endif %} -{%- endif %} - - -{%- if zoro_description.nlh_e_t + zoro_description.nuh_e_t > 0 %} - // nonlinear constraints: h - // Get C_{k+1} and D_{k+1} - ocp_nlp_get_at_stage(solver->config, nlp_dims, solver, N, "C", custom_mem->d_Cgh_mat); - // NOTE: the d_Cgh_mat is column-major, the first ng rows are the Jacobians of the linear constraints - blasfeo_pack_dmat(nh, nx, custom_mem->d_Cgh_mat+ng, ng+nh, &custom_mem->Ch_mat, 0, 0); - - compute_gh_beta(&custom_mem->K_mat, &custom_mem->Ch_mat, - &custom_mem->dummy_Dgh_e_mat, &custom_mem->temp_CaDK_mat, - &custom_mem->temp_CaDKmP_mat, &custom_mem->temp_beta_mat, - &custom_mem->uncertainty_matrix_buffer[N], nh, nx, nu); - - {%- if zoro_description.nlh_e_t > 0 %} - {%- for it in zoro_description.idx_lh_e_t %} - custom_mem->d_lh_e_tightened[{{it}}] - = custom_mem->d_lh_e[{{it}}] - + backoff_scaling_gamma * sqrt(blasfeo_dgeex1(&custom_mem->temp_beta_mat, {{it}}, {{it}})); - {%- endfor %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lh", custom_mem->d_lh_e_tightened); - {%- endif %} - {%- if zoro_description.nuh_e_t > 0 %} - {%- for it in zoro_description.idx_uh_e_t %} - custom_mem->d_uh_e_tightened[{{it}}] = custom_mem->d_uh_e[{{it}}] - - backoff_scaling_gamma * sqrt(blasfeo_dgeex1(&custom_mem->temp_beta_mat, {{it}}, {{it}})); - {%- endfor %} - ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "uh", custom_mem->d_uh_e_tightened); - {%- endif %} -{%- endif %} - -} - - -int custom_update_function({{ model.name }}_solver_capsule* capsule, double* data, int data_len) -{ - custom_memory *custom_mem = (custom_memory *) capsule->custom_update_memory; - ocp_nlp_config *nlp_config = {{ model.name }}_acados_get_nlp_config(capsule); - ocp_nlp_dims *nlp_dims = {{ model.name }}_acados_get_nlp_dims(capsule); - ocp_nlp_in *nlp_in = {{ model.name }}_acados_get_nlp_in(capsule); - ocp_nlp_out *nlp_out = {{ model.name }}_acados_get_nlp_out(capsule); - ocp_nlp_solver *nlp_solver = {{ model.name }}_acados_get_nlp_solver(capsule); - void *nlp_opts = {{ model.name }}_acados_get_nlp_opts(capsule); - - if (data_len > 0) - { - reset_P0_matrix(nlp_dims, &custom_mem->uncertainty_matrix_buffer[0], data); - } - uncertainty_propagate_and_update(nlp_solver, nlp_in, nlp_out, custom_mem); - - return 1; -} - - -int custom_update_terminate_function({{ model.name }}_solver_capsule* capsule) -{ - custom_memory *mem = capsule->custom_update_memory; - - free(mem->raw_memory); - return 1; -} - -// useful prints for debugging - -/* -printf("A_mat:\n"); -blasfeo_print_exp_dmat(nx, nx, &custom_mem->A_mat, 0, 0); -printf("B_mat:\n"); -blasfeo_print_exp_dmat(nx, nu, &custom_mem->B_mat, 0, 0); -printf("K_mat:\n"); -blasfeo_print_exp_dmat(nu, nx, &custom_mem->K_mat, 0, 0); -printf("AK_mat:\n"); -blasfeo_print_exp_dmat(nx, nx, &custom_mem->AK_mat, 0, 0); -printf("temp_AP_mat:\n"); -blasfeo_print_exp_dmat(nx, nx, &custom_mem->temp_AP_mat, 0, 0); -printf("W_mat:\n"); -blasfeo_print_exp_dmat(nx, nx, &custom_mem->W_mat, 0, 0); -printf("P_k+1:\n"); -blasfeo_print_exp_dmat(nx, nx, &(custom_mem->uncertainty_matrix_buffer[ii+1]), 0, 0);*/ \ No newline at end of file diff --git a/third_party/acados/acados_template/custom_update_templates/custom_update_function_zoro_template.in.h b/third_party/acados/acados_template/custom_update_templates/custom_update_function_zoro_template.in.h deleted file mode 100644 index 9611ea210c..0000000000 --- a/third_party/acados/acados_template/custom_update_templates/custom_update_function_zoro_template.in.h +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - -#include "acados_solver_{{ model.name }}.h" - -// Called at the end of solver creation. -// This is allowed to allocate memory and store the pointer to it into capsule->custom_update_memory. -int custom_update_init_function({{ model.name }}_solver_capsule* capsule); - - -// Custom update function that can be called between solver calls -int custom_update_function({{ model.name }}_solver_capsule* capsule, double* data, int data_len); - - -// Called just before destroying the solver. -// Responsible to free allocated memory, stored at capsule->custom_update_memory. -int custom_update_terminate_function({{ model.name }}_solver_capsule* capsule); diff --git a/third_party/acados/acados_template/gnsf/check_reformulation.py b/third_party/acados/acados_template/gnsf/check_reformulation.py deleted file mode 100644 index 2bdfbbc336..0000000000 --- a/third_party/acados/acados_template/gnsf/check_reformulation.py +++ /dev/null @@ -1,216 +0,0 @@ -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# 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. -# -# 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.; -# - -from acados_template.utils import casadi_length -from casadi import * -import numpy as np - - -def check_reformulation(model, gnsf, print_info): - - ## Description: - # this function takes the implicit ODE/ index-1 DAE and a gnsf structure - # to evaluate both models at num_eval random points x0, x0dot, z0, u0 - # if for all points the relative error is <= TOL, the function will return:: - # 1, otherwise it will give an error. - - TOL = 1e-14 - num_eval = 10 - - # get dimensions - nx = gnsf["nx"] - nu = gnsf["nu"] - nz = gnsf["nz"] - nx1 = gnsf["nx1"] - nx2 = gnsf["nx2"] - nz1 = gnsf["nz1"] - nz2 = gnsf["nz2"] - n_out = gnsf["n_out"] - - # get model matrices - A = gnsf["A"] - B = gnsf["B"] - C = gnsf["C"] - E = gnsf["E"] - c = gnsf["c"] - - L_x = gnsf["L_x"] - L_xdot = gnsf["L_xdot"] - L_z = gnsf["L_z"] - L_u = gnsf["L_u"] - - A_LO = gnsf["A_LO"] - E_LO = gnsf["E_LO"] - B_LO = gnsf["B_LO"] - c_LO = gnsf["c_LO"] - - I_x1 = range(nx1) - I_x2 = range(nx1, nx) - - I_z1 = range(nz1) - I_z2 = range(nz1, nz) - - idx_perm_f = gnsf["idx_perm_f"] - - # get casadi variables - x = gnsf["x"] - xdot = gnsf["xdot"] - z = gnsf["z"] - u = gnsf["u"] - y = gnsf["y"] - uhat = gnsf["uhat"] - p = gnsf["p"] - - # create functions - impl_dae_fun = Function("impl_dae_fun", [x, xdot, u, z, p], [model.f_impl_expr]) - phi_fun = Function("phi_fun", [y, uhat, p], [gnsf["phi_expr"]]) - f_lo_fun = Function( - "f_lo_fun", [x[range(nx1)], xdot[range(nx1)], z, u, p], [gnsf["f_lo_expr"]] - ) - - # print(gnsf) - # print(gnsf["n_out"]) - - for i_check in range(num_eval): - # generate random values - x0 = np.random.rand(nx, 1) - x0dot = np.random.rand(nx, 1) - z0 = np.random.rand(nz, 1) - u0 = np.random.rand(nu, 1) - - if gnsf["ny"] > 0: - y0 = L_x @ x0[I_x1] + L_xdot @ x0dot[I_x1] + L_z @ z0[I_z1] - else: - y0 = [] - if gnsf["nuhat"] > 0: - uhat0 = L_u @ u0 - else: - uhat0 = [] - - # eval functions - p0 = np.random.rand(gnsf["np"], 1) - f_impl_val = impl_dae_fun(x0, x0dot, u0, z0, p0).full() - phi_val = phi_fun(y0, uhat0, p0) - f_lo_val = f_lo_fun(x0[I_x1], x0dot[I_x1], z0[I_z1], u0, p0) - - f_impl_val = f_impl_val[idx_perm_f] - # eval gnsf - if n_out > 0: - C_phi = C @ phi_val - else: - C_phi = np.zeros((nx1 + nz1, 1)) - try: - gnsf_val1 = ( - A @ x0[I_x1] + B @ u0 + C_phi + c - E @ vertcat(x0dot[I_x1], z0[I_z1]) - ) - # gnsf_1 = (A @ x[I_x1] + B @ u + C_phi + c - E @ vertcat(xdot[I_x1], z[I_z1])) - except: - import pdb - - pdb.set_trace() - - if nx2 > 0: # eval LOS: - gnsf_val2 = ( - A_LO @ x0[I_x2] - + B_LO @ u0 - + c_LO - + f_lo_val - - E_LO @ vertcat(x0dot[I_x2], z0[I_z2]) - ) - gnsf_val = vertcat(gnsf_val1, gnsf_val2).full() - else: - gnsf_val = gnsf_val1.full() - # compute error and check - rel_error = np.linalg.norm(f_impl_val - gnsf_val) / np.linalg.norm(f_impl_val) - - if rel_error > TOL: - print("transcription failed rel_error > TOL") - print("you are in debug mode now: import pdb; pdb.set_trace()") - abs_error = gnsf_val - f_impl_val - # T = table(f_impl_val, gnsf_val, abs_error) - # print(T) - print("abs_error:", abs_error) - # error('transcription failed rel_error > TOL') - # check = 0 - import pdb - - pdb.set_trace() - if print_info: - print(" ") - print("model reformulation checked: relative error <= TOL = ", str(TOL)) - print(" ") - check = 1 - ## helpful for debugging: - # # use in calling function and compare - # # compare f_impl(i) with gnsf_val1(i) - # - - # nx = gnsf['nx'] - # nu = gnsf['nu'] - # nz = gnsf['nz'] - # nx1 = gnsf['nx1'] - # nx2 = gnsf['nx2'] - # - # A = gnsf['A'] - # B = gnsf['B'] - # C = gnsf['C'] - # E = gnsf['E'] - # c = gnsf['c'] - # - # L_x = gnsf['L_x'] - # L_z = gnsf['L_z'] - # L_xdot = gnsf['L_xdot'] - # L_u = gnsf['L_u'] - # - # A_LO = gnsf['A_LO'] - # - # x0 = rand(nx, 1) - # x0dot = rand(nx, 1) - # z0 = rand(nz, 1) - # u0 = rand(nu, 1) - # I_x1 = range(nx1) - # I_x2 = nx1+range(nx) - # - # y0 = L_x @ x0[I_x1] + L_xdot @ x0dot[I_x1] + L_z @ z0 - # uhat0 = L_u @ u0 - # - # gnsf_val1 = (A @ x[I_x1] + B @ u + # C @ phi_current + c) - E @ [xdot[I_x1] z] - # gnsf_val1 = gnsf_val1.simplify() - # - # # gnsf_val2 = A_LO @ x[I_x2] + gnsf['f_lo_fun'](x[I_x1], xdot[I_x1], z, u) - xdot[I_x2] - # gnsf_val2 = A_LO @ x[I_x2] + gnsf['f_lo_fun'](x[I_x1], xdot[I_x1], z, u) - xdot[I_x2] - # - # - # gnsf_val = [gnsf_val1 gnsf_val2] - # gnsf_val = gnsf_val.simplify() - # dyn_expr_f = dyn_expr_f.simplify() - # import pdb; pdb.set_trace() - - return check diff --git a/third_party/acados/acados_template/gnsf/detect_affine_terms_reduce_nonlinearity.py b/third_party/acados/acados_template/gnsf/detect_affine_terms_reduce_nonlinearity.py deleted file mode 100644 index ebf1f373a4..0000000000 --- a/third_party/acados/acados_template/gnsf/detect_affine_terms_reduce_nonlinearity.py +++ /dev/null @@ -1,278 +0,0 @@ -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# 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. -# -# 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.; -# - -from casadi import * -from .check_reformulation import check_reformulation -from .determine_input_nonlinearity_function import determine_input_nonlinearity_function -from ..utils import casadi_length, print_casadi_expression - - -def detect_affine_terms_reduce_nonlinearity(gnsf, acados_ocp, print_info): - - ## Description - # this function takes a gnsf structure with trivial model matrices (A, B, - # E, c are zeros, and C is eye). - # It detects all affine linear terms and sets up an equivalent model in the - # GNSF structure, where all affine linear terms are modeled through the - # matrices A, B, E, c and the linear output system (LOS) is empty. - # NOTE: model is just taken as an argument to check equivalence of the - # models within the function. - - model = acados_ocp.model - if print_info: - print(" ") - print("====================================================================") - print(" ") - print("============ Detect affine-linear dependencies ==================") - print(" ") - print("====================================================================") - print(" ") - # symbolics - x = gnsf["x"] - xdot = gnsf["xdot"] - u = gnsf["u"] - z = gnsf["z"] - - # dimensions - nx = gnsf["nx"] - nu = gnsf["nu"] - nz = gnsf["nz"] - - ny_old = gnsf["ny"] - nuhat_old = gnsf["nuhat"] - - ## Represent all affine dependencies through the model matrices A, B, E, c - ## determine A - n_nodes_current = n_nodes(gnsf["phi_expr"]) - - for ii in range(casadi_length(gnsf["phi_expr"])): - fii = gnsf["phi_expr"][ii] - for ix in range(nx): - var = x[ix] - varname = var.name - # symbolic jacobian of fii w.r.t. xi - jac_fii_xi = jacobian(fii, var) - if jac_fii_xi.is_constant(): - # jacobian value - jac_fii_xi_fun = Function("jac_fii_xi_fun", [x[1]], [jac_fii_xi]) - # x[1] as input just to have a scalar input and call the function as follows: - gnsf["A"][ii, ix] = jac_fii_xi_fun(0).full() - else: - gnsf["A"][ii, ix] = 0 - if print_info: - print( - "phi(", - str(ii), - ") is nonlinear in x(", - str(ix), - ") = ", - varname, - ) - print(fii) - print("-----------------------------------------------------") - f_next = gnsf["phi_expr"] - gnsf["A"] @ x - f_next = simplify(f_next) - n_nodes_next = n_nodes(f_next) - - if print_info: - print("\n") - print(f"determined matrix A:") - print(gnsf["A"]) - print(f"reduced nonlinearity from {n_nodes_current} to {n_nodes_next} nodes") - # assert(n_nodes_current >= n_nodes_next,'n_nodes_current >= n_nodes_next FAILED') - gnsf["phi_expr"] = f_next - - check_reformulation(model, gnsf, print_info) - - ## determine B - n_nodes_current = n_nodes(gnsf["phi_expr"]) - - for ii in range(casadi_length(gnsf["phi_expr"])): - fii = gnsf["phi_expr"][ii] - for iu in range(nu): - var = u[iu] - varname = var.name - # symbolic jacobian of fii w.r.t. ui - jac_fii_ui = jacobian(fii, var) - if jac_fii_ui.is_constant(): # i.e. hessian is structural zero: - # jacobian value - jac_fii_ui_fun = Function("jac_fii_ui_fun", [x[1]], [jac_fii_ui]) - gnsf["B"][ii, iu] = jac_fii_ui_fun(0).full() - else: - gnsf["B"][ii, iu] = 0 - if print_info: - print(f"phi({ii}) is nonlinear in u(", str(iu), ") = ", varname) - print(fii) - print("-----------------------------------------------------") - f_next = gnsf["phi_expr"] - gnsf["B"] @ u - f_next = simplify(f_next) - n_nodes_next = n_nodes(f_next) - - if print_info: - print("\n") - print(f"determined matrix B:") - print(gnsf["B"]) - print(f"reduced nonlinearity from {n_nodes_current} to {n_nodes_next} nodes") - - gnsf["phi_expr"] = f_next - - check_reformulation(model, gnsf, print_info) - - ## determine E - n_nodes_current = n_nodes(gnsf["phi_expr"]) - k = vertcat(xdot, z) - - for ii in range(casadi_length(gnsf["phi_expr"])): - fii = gnsf["phi_expr"][ii] - for ik in range(casadi_length(k)): - # symbolic jacobian of fii w.r.t. ui - var = k[ik] - varname = var.name - jac_fii_ki = jacobian(fii, var) - if jac_fii_ki.is_constant(): - # jacobian value - jac_fii_ki_fun = Function("jac_fii_ki_fun", [x[1]], [jac_fii_ki]) - gnsf["E"][ii, ik] = -jac_fii_ki_fun(0).full() - else: - gnsf["E"][ii, ik] = 0 - if print_info: - print(f"phi( {ii}) is nonlinear in xdot_z({ik}) = ", varname) - print(fii) - print("-----------------------------------------------------") - f_next = gnsf["phi_expr"] + gnsf["E"] @ k - f_next = simplify(f_next) - n_nodes_next = n_nodes(f_next) - - if print_info: - print("\n") - print(f"determined matrix E:") - print(gnsf["E"]) - print(f"reduced nonlinearity from {n_nodes_current} to {n_nodes_next} nodes") - - gnsf["phi_expr"] = f_next - check_reformulation(model, gnsf, print_info) - - ## determine constant term c - - n_nodes_current = n_nodes(gnsf["phi_expr"]) - for ii in range(casadi_length(gnsf["phi_expr"])): - fii = gnsf["phi_expr"][ii] - if fii.is_constant(): - # function value goes into c - fii_fun = Function("fii_fun", [x[1]], [fii]) - gnsf["c"][ii] = fii_fun(0).full() - else: - gnsf["c"][ii] = 0 - if print_info: - print(f"phi(", str(ii), ") is NOT constant") - print(fii) - print("-----------------------------------------------------") - gnsf["phi_expr"] = gnsf["phi_expr"] - gnsf["c"] - gnsf["phi_expr"] = simplify(gnsf["phi_expr"]) - n_nodes_next = n_nodes(gnsf["phi_expr"]) - - if print_info: - print("\n") - print(f"determined vector c:") - print(gnsf["c"]) - print(f"reduced nonlinearity from {n_nodes_current} to {n_nodes_next} nodes") - - check_reformulation(model, gnsf, print_info) - - ## determine nonlinearity & corresponding matrix C - ## Reduce dimension of phi - n_nodes_current = n_nodes(gnsf["phi_expr"]) - ind_non_zero = [] - for ii in range(casadi_length(gnsf["phi_expr"])): - fii = gnsf["phi_expr"][ii] - fii = simplify(fii) - if not fii.is_zero(): - ind_non_zero = list(set.union(set(ind_non_zero), set([ii]))) - gnsf["phi_expr"] = gnsf["phi_expr"][ind_non_zero] - - # C - gnsf["C"] = np.zeros((nx + nz, len(ind_non_zero))) - for ii in range(len(ind_non_zero)): - gnsf["C"][ind_non_zero[ii], ii] = 1 - gnsf = determine_input_nonlinearity_function(gnsf) - n_nodes_next = n_nodes(gnsf["phi_expr"]) - - if print_info: - print(" ") - print("determined matrix C:") - print(gnsf["C"]) - print( - "---------------------------------------------------------------------------------" - ) - print( - "------------- Success: Affine linear terms detected -----------------------------" - ) - print( - "---------------------------------------------------------------------------------" - ) - print( - f'reduced nonlinearity dimension n_out from {nx+nz} to {gnsf["n_out"]}' - ) - print(f"reduced nonlinearity from {n_nodes_current} to {n_nodes_next} nodes") - print(" ") - print("phi now reads as:") - print_casadi_expression(gnsf["phi_expr"]) - - ## determine input of nonlinearity function - check_reformulation(model, gnsf, print_info) - - gnsf["ny"] = casadi_length(gnsf["y"]) - gnsf["nuhat"] = casadi_length(gnsf["uhat"]) - - if print_info: - print( - "-----------------------------------------------------------------------------------" - ) - print(" ") - print( - f"reduced input ny of phi from ", - str(ny_old), - " to ", - str(gnsf["ny"]), - ) - print( - f"reduced input nuhat of phi from ", - str(nuhat_old), - " to ", - str(gnsf["nuhat"]), - ) - print( - "-----------------------------------------------------------------------------------" - ) - - # if print_info: - # print(f"gnsf: {gnsf}") - - return gnsf diff --git a/third_party/acados/acados_template/gnsf/detect_gnsf_structure.py b/third_party/acados/acados_template/gnsf/detect_gnsf_structure.py deleted file mode 100644 index 24ffe643b8..0000000000 --- a/third_party/acados/acados_template/gnsf/detect_gnsf_structure.py +++ /dev/null @@ -1,240 +0,0 @@ -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# 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. -# -# 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.; -# -# Author: Jonathan Frey: jonathanpaulfrey(at)gmail.com - -from casadi import Function, jacobian, SX, vertcat, horzcat - -from .determine_trivial_gnsf_transcription import determine_trivial_gnsf_transcription -from .detect_affine_terms_reduce_nonlinearity import ( - detect_affine_terms_reduce_nonlinearity, -) -from .reformulate_with_LOS import reformulate_with_LOS -from .reformulate_with_invertible_E_mat import reformulate_with_invertible_E_mat -from .structure_detection_print_summary import structure_detection_print_summary -from .check_reformulation import check_reformulation - - -def detect_gnsf_structure(acados_ocp, transcribe_opts=None): - - ## Description - # This function takes a CasADi implicit ODE or index-1 DAE model "model" - # consisting of a CasADi expression f_impl in the symbolic CasADi - # variables x, xdot, u, z, (and possibly parameters p), which are also part - # of the model, as well as a model name. - # It will create a struct "gnsf" containing all information needed to use - # it with the gnsf integrator in acados. - # Additionally it will create the struct "reordered_model" which contains - # the permuted state vector and permuted f_impl, in which additionally some - # functions, which were made part of the linear output system of the gnsf, - # have changed signs. - - # Options: transcribe_opts is a Matlab struct consisting of booleans: - # print_info: if extensive information on how the model is processed - # is printed to the console. - # generate_gnsf_model: if the neccessary C functions to simulate the gnsf - # model with the acados implementation of the GNSF exploiting - # integrator should be generated. - # generate_gnsf_model: if the neccessary C functions to simulate the - # reordered model with the acados implementation of the IRK - # integrator should be generated. - # check_E_invertibility: if the transcription method should check if the - # assumption that the main blocks of the matrix gnsf.E are invertible - # holds. If not, the method will try to reformulate the gnsf model - # with a different model, such that the assumption holds. - - # acados_root_dir = getenv('ACADOS_INSTALL_DIR') - - ## load transcribe_opts - if transcribe_opts is None: - print("WARNING: GNSF structure detection called without transcribe_opts") - print(" using default settings") - print("") - transcribe_opts = dict() - - if "print_info" in transcribe_opts: - print_info = transcribe_opts["print_info"] - else: - print_info = 1 - print("print_info option was not set - default is true") - - if "detect_LOS" in transcribe_opts: - detect_LOS = transcribe_opts["detect_LOS"] - else: - detect_LOS = 1 - if print_info: - print("detect_LOS option was not set - default is true") - - if "check_E_invertibility" in transcribe_opts: - check_E_invertibility = transcribe_opts["check_E_invertibility"] - else: - check_E_invertibility = 1 - if print_info: - print("check_E_invertibility option was not set - default is true") - - ## Reformulate implicit index-1 DAE into GNSF form - # (Generalized nonlinear static feedback) - gnsf = determine_trivial_gnsf_transcription(acados_ocp, print_info) - gnsf = detect_affine_terms_reduce_nonlinearity(gnsf, acados_ocp, print_info) - - if detect_LOS: - gnsf = reformulate_with_LOS(acados_ocp, gnsf, print_info) - - if check_E_invertibility: - gnsf = reformulate_with_invertible_E_mat(gnsf, acados_ocp, print_info) - - # detect purely linear model - if gnsf["nx1"] == 0 and gnsf["nz1"] == 0 and gnsf["nontrivial_f_LO"] == 0: - gnsf["purely_linear"] = 1 - else: - gnsf["purely_linear"] = 0 - - structure_detection_print_summary(gnsf, acados_ocp) - check_reformulation(acados_ocp.model, gnsf, print_info) - - ## copy relevant fields from gnsf to model - acados_ocp.model.get_matrices_fun = Function() - dummy = acados_ocp.model.x[0] - model_name = acados_ocp.model.name - - get_matrices_fun = Function( - f"{model_name}_gnsf_get_matrices_fun", - [dummy], - [ - gnsf["A"], - gnsf["B"], - gnsf["C"], - gnsf["E"], - gnsf["L_x"], - gnsf["L_xdot"], - gnsf["L_z"], - gnsf["L_u"], - gnsf["A_LO"], - gnsf["c"], - gnsf["E_LO"], - gnsf["B_LO"], - gnsf["nontrivial_f_LO"], - gnsf["purely_linear"], - gnsf["ipiv_x"] + 1, - gnsf["ipiv_z"] + 1, - gnsf["c_LO"], - ], - ) - - phi = gnsf["phi_expr"] - y = gnsf["y"] - uhat = gnsf["uhat"] - p = gnsf["p"] - - jac_phi_y = jacobian(phi, y) - jac_phi_uhat = jacobian(phi, uhat) - - phi_fun = Function(f"{model_name}_gnsf_phi_fun", [y, uhat, p], [phi]) - acados_ocp.model.phi_fun = phi_fun - acados_ocp.model.phi_fun_jac_y = Function( - f"{model_name}_gnsf_phi_fun_jac_y", [y, uhat, p], [phi, jac_phi_y] - ) - acados_ocp.model.phi_jac_y_uhat = Function( - f"{model_name}_gnsf_phi_jac_y_uhat", [y, uhat, p], [jac_phi_y, jac_phi_uhat] - ) - - x1 = acados_ocp.model.x[gnsf["idx_perm_x"][: gnsf["nx1"]]] - x1dot = acados_ocp.model.xdot[gnsf["idx_perm_x"][: gnsf["nx1"]]] - if gnsf["nz1"] > 0: - z1 = acados_ocp.model.z[gnsf["idx_perm_z"][: gnsf["nz1"]]] - else: - z1 = SX.sym("z1", 0, 0) - f_lo = gnsf["f_lo_expr"] - u = acados_ocp.model.u - acados_ocp.model.f_lo_fun_jac_x1k1uz = Function( - f"{model_name}_gnsf_f_lo_fun_jac_x1k1uz", - [x1, x1dot, z1, u, p], - [ - f_lo, - horzcat( - jacobian(f_lo, x1), - jacobian(f_lo, x1dot), - jacobian(f_lo, u), - jacobian(f_lo, z1), - ), - ], - ) - - acados_ocp.model.get_matrices_fun = get_matrices_fun - - size_gnsf_A = gnsf["A"].shape - acados_ocp.dims.gnsf_nx1 = size_gnsf_A[1] - acados_ocp.dims.gnsf_nz1 = size_gnsf_A[0] - size_gnsf_A[1] - acados_ocp.dims.gnsf_nuhat = max(phi_fun.size_in(1)) - acados_ocp.dims.gnsf_ny = max(phi_fun.size_in(0)) - acados_ocp.dims.gnsf_nout = max(phi_fun.size_out(0)) - - # # dim - # model['dim_gnsf_nx1'] = gnsf['nx1'] - # model['dim_gnsf_nx2'] = gnsf['nx2'] - # model['dim_gnsf_nz1'] = gnsf['nz1'] - # model['dim_gnsf_nz2'] = gnsf['nz2'] - # model['dim_gnsf_nuhat'] = gnsf['nuhat'] - # model['dim_gnsf_ny'] = gnsf['ny'] - # model['dim_gnsf_nout'] = gnsf['n_out'] - - # # sym - # model['sym_gnsf_y'] = gnsf['y'] - # model['sym_gnsf_uhat'] = gnsf['uhat'] - - # # data - # model['dyn_gnsf_A'] = gnsf['A'] - # model['dyn_gnsf_A_LO'] = gnsf['A_LO'] - # model['dyn_gnsf_B'] = gnsf['B'] - # model['dyn_gnsf_B_LO'] = gnsf['B_LO'] - # model['dyn_gnsf_E'] = gnsf['E'] - # model['dyn_gnsf_E_LO'] = gnsf['E_LO'] - # model['dyn_gnsf_C'] = gnsf['C'] - # model['dyn_gnsf_c'] = gnsf['c'] - # model['dyn_gnsf_c_LO'] = gnsf['c_LO'] - # model['dyn_gnsf_L_x'] = gnsf['L_x'] - # model['dyn_gnsf_L_xdot'] = gnsf['L_xdot'] - # model['dyn_gnsf_L_z'] = gnsf['L_z'] - # model['dyn_gnsf_L_u'] = gnsf['L_u'] - # model['dyn_gnsf_idx_perm_x'] = gnsf['idx_perm_x'] - # model['dyn_gnsf_ipiv_x'] = gnsf['ipiv_x'] - # model['dyn_gnsf_idx_perm_z'] = gnsf['idx_perm_z'] - # model['dyn_gnsf_ipiv_z'] = gnsf['ipiv_z'] - # model['dyn_gnsf_idx_perm_f'] = gnsf['idx_perm_f'] - # model['dyn_gnsf_ipiv_f'] = gnsf['ipiv_f'] - - # # flags - # model['dyn_gnsf_nontrivial_f_LO'] = gnsf['nontrivial_f_LO'] - # model['dyn_gnsf_purely_linear'] = gnsf['purely_linear'] - - # # casadi expr - # model['dyn_gnsf_expr_phi'] = gnsf['phi_expr'] - # model['dyn_gnsf_expr_f_lo'] = gnsf['f_lo_expr'] - - return acados_ocp diff --git a/third_party/acados/acados_template/gnsf/determine_input_nonlinearity_function.py b/third_party/acados/acados_template/gnsf/determine_input_nonlinearity_function.py deleted file mode 100644 index 94aa001c79..0000000000 --- a/third_party/acados/acados_template/gnsf/determine_input_nonlinearity_function.py +++ /dev/null @@ -1,110 +0,0 @@ -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# 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. -# -# 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.; -# -# Author: Jonathan Frey: jonathanpaulfrey(at)gmail.com - -from casadi import * -from ..utils import casadi_length, is_empty - - -def determine_input_nonlinearity_function(gnsf): - - ## Description - # this function takes a structure gnsf and updates the matrices L_x, - # L_xdot, L_z, L_u and CasADi vectors y, uhat of this structure as follows: - - # given a CasADi expression phi_expr, which may depend on the variables - # (x1, x1dot, z, u), this function determines a vector y (uhat) consisting - # of all components of (x1, x1dot, z) (respectively u) that enter phi_expr. - # Additionally matrices L_x, L_xdot, L_z, L_u are determined such that - # y = L_x * x + L_xdot * xdot + L_z * z - # uhat = L_u * u - # Furthermore the dimensions ny, nuhat, n_out are updated - - ## y - y = SX.sym('y', 0, 0) - # components of x1 - for ii in range(gnsf["nx1"]): - if which_depends(gnsf["phi_expr"], gnsf["x"][ii])[0]: - y = vertcat(y, gnsf["x"][ii]) - # else: - # x[ii] is not part of y - # components of x1dot - for ii in range(gnsf["nx1"]): - if which_depends(gnsf["phi_expr"], gnsf["xdot"][ii])[0]: - print(gnsf["phi_expr"], "depends on", gnsf["xdot"][ii]) - y = vertcat(y, gnsf["xdot"][ii]) - # else: - # xdot[ii] is not part of y - # components of z - for ii in range(gnsf["nz1"]): - if which_depends(gnsf["phi_expr"], gnsf["z"][ii])[0]: - y = vertcat(y, gnsf["z"][ii]) - # else: - # z[ii] is not part of y - ## uhat - uhat = SX.sym('uhat', 0, 0) - # components of u - for ii in range(gnsf["nu"]): - if which_depends(gnsf["phi_expr"], gnsf["u"][ii])[0]: - uhat = vertcat(uhat, gnsf["u"][ii]) - # else: - # u[ii] is not part of uhat - ## generate gnsf['phi_expr_fun'] - # linear input matrices - if is_empty(y): - gnsf["L_x"] = [] - gnsf["L_xdot"] = [] - gnsf["L_u"] = [] - gnsf["L_z"] = [] - else: - dummy = SX.sym("dummy_input", 0) - L_x_fun = Function( - "L_x_fun", [dummy], [jacobian(y, gnsf["x"][range(gnsf["nx1"])])] - ) - L_xdot_fun = Function( - "L_xdot_fun", [dummy], [jacobian(y, gnsf["xdot"][range(gnsf["nx1"])])] - ) - L_z_fun = Function( - "L_z_fun", [dummy], [jacobian(y, gnsf["z"][range(gnsf["nz1"])])] - ) - L_u_fun = Function("L_u_fun", [dummy], [jacobian(uhat, gnsf["u"])]) - - gnsf["L_x"] = L_x_fun(0).full() - gnsf["L_xdot"] = L_xdot_fun(0).full() - gnsf["L_u"] = L_u_fun(0).full() - gnsf["L_z"] = L_z_fun(0).full() - gnsf["y"] = y - gnsf["uhat"] = uhat - - gnsf["ny"] = casadi_length(y) - gnsf["nuhat"] = casadi_length(uhat) - gnsf["n_out"] = casadi_length(gnsf["phi_expr"]) - - return gnsf diff --git a/third_party/acados/acados_template/gnsf/determine_trivial_gnsf_transcription.py b/third_party/acados/acados_template/gnsf/determine_trivial_gnsf_transcription.py deleted file mode 100644 index 23c2440537..0000000000 --- a/third_party/acados/acados_template/gnsf/determine_trivial_gnsf_transcription.py +++ /dev/null @@ -1,155 +0,0 @@ -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# 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. -# -# 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.; -# - -from casadi import * -import numpy as np -from ..utils import casadi_length, idx_perm_to_ipiv -from .determine_input_nonlinearity_function import determine_input_nonlinearity_function -from .check_reformulation import check_reformulation - - -def determine_trivial_gnsf_transcription(acados_ocp, print_info): - ## Description - # this function takes a model of an implicit ODE/ index-1 DAE and sets up - # an equivalent model in the GNSF structure, with empty linear output - # system and trivial model matrices, i.e. A, B, E, c are zeros, and C is - # eye. - no structure is exploited - - model = acados_ocp.model - # initial print - print("*****************************************************************") - print(" ") - print(f"****** Restructuring {model.name} model ***********") - print(" ") - print("*****************************************************************") - - # load model - f_impl_expr = model.f_impl_expr - - model_name_prefix = model.name - - # x - x = model.x - nx = acados_ocp.dims.nx - # check type - if isinstance(x[0], SX): - isSX = True - else: - print("GNSF detection only works for SX CasADi type!!!") - import pdb - - pdb.set_trace() - # xdot - xdot = model.xdot - # u - nu = acados_ocp.dims.nu - if nu == 0: - u = SX.sym("u", 0, 0) - else: - u = model.u - - nz = acados_ocp.dims.nz - if nz == 0: - z = SX.sym("z", 0, 0) - else: - z = model.z - - p = model.p - nparam = acados_ocp.dims.np - - # avoid SX of size 0x1 - if casadi_length(u) == 0: - u = SX.sym("u", 0, 0) - nu = 0 - ## initialize gnsf struct - # dimensions - gnsf = {"nx": nx, "nu": nu, "nz": nz, "np": nparam} - gnsf["nx1"] = nx - gnsf["nx2"] = 0 - gnsf["nz1"] = nz - gnsf["nz2"] = 0 - gnsf["nuhat"] = nu - gnsf["ny"] = 2 * nx + nz - - gnsf["phi_expr"] = f_impl_expr - gnsf["A"] = np.zeros((nx + nz, nx)) - gnsf["B"] = np.zeros((nx + nz, nu)) - gnsf["E"] = np.zeros((nx + nz, nx + nz)) - gnsf["c"] = np.zeros((nx + nz, 1)) - gnsf["C"] = np.eye(nx + nz) - gnsf["name"] = model_name_prefix - - gnsf["x"] = x - gnsf["xdot"] = xdot - gnsf["z"] = z - gnsf["u"] = u - gnsf["p"] = p - - gnsf = determine_input_nonlinearity_function(gnsf) - - gnsf["A_LO"] = [] - gnsf["E_LO"] = [] - gnsf["B_LO"] = [] - gnsf["c_LO"] = [] - gnsf["f_lo_expr"] = [] - - # permutation - gnsf["idx_perm_x"] = range(nx) # matlab-style) - gnsf["ipiv_x"] = idx_perm_to_ipiv(gnsf["idx_perm_x"]) # blasfeo-style - gnsf["idx_perm_z"] = range(nz) - gnsf["ipiv_z"] = idx_perm_to_ipiv(gnsf["idx_perm_z"]) - gnsf["idx_perm_f"] = range((nx + nz)) - gnsf["ipiv_f"] = idx_perm_to_ipiv(gnsf["idx_perm_f"]) - - gnsf["nontrivial_f_LO"] = 0 - - check_reformulation(model, gnsf, print_info) - if print_info: - print(f"Success: Set up equivalent GNSF model with trivial matrices") - print(" ") - if print_info: - print( - "-----------------------------------------------------------------------------------" - ) - print(" ") - print( - "reduced input ny of phi from ", - str(2 * nx + nz), - " to ", - str(gnsf["ny"]), - ) - print( - "reduced input nuhat of phi from ", str(nu), " to ", str(gnsf["nuhat"]) - ) - print(" ") - print( - "-----------------------------------------------------------------------------------" - ) - return gnsf diff --git a/third_party/acados/acados_template/gnsf/matlab to python.md b/third_party/acados/acados_template/gnsf/matlab to python.md deleted file mode 100644 index 53a0ed971e..0000000000 --- a/third_party/acados/acados_template/gnsf/matlab to python.md +++ /dev/null @@ -1,43 +0,0 @@ -# matlab to python - -% -> # - -; -> - -from casadi import * --> -from casadi import * - - -print\('(.*)'\) -print('$1') - -print\(\['(.*)'\]\) -print(f'$1') - -keyboard -import pdb; pdb.set_trace() - - -range((([^))]*)) -range($1) - -\s*end --> -nothing - - -if (.*) -if $1: - -else -else: - -num2str -str - -for ([a-z_]*) = -for $1 in - -length\( -len( \ No newline at end of file diff --git a/third_party/acados/acados_template/gnsf/reformulate_with_LOS.py b/third_party/acados/acados_template/gnsf/reformulate_with_LOS.py deleted file mode 100644 index 297a56556c..0000000000 --- a/third_party/acados/acados_template/gnsf/reformulate_with_LOS.py +++ /dev/null @@ -1,394 +0,0 @@ -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# 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. -# -# 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.; -# -# Author: Jonathan Frey: jonathanpaulfrey(at)gmail.com - -from .determine_input_nonlinearity_function import determine_input_nonlinearity_function -from .check_reformulation import check_reformulation -from casadi import * -from ..utils import casadi_length, idx_perm_to_ipiv, is_empty - - -def reformulate_with_LOS(acados_ocp, gnsf, print_info): - - ## Description: - # This function takes an intitial transcription of the implicit ODE model - # "model" into "gnsf" and reformulates "gnsf" with a linear output system - # (LOS), containing as many states of the model as possible. - # Therefore it might be that the state vector and the implicit function - # vector have to be reordered. This reordered model is part of the output, - # namely reordered_model. - - ## import CasADi and load models - model = acados_ocp.model - - # symbolics - x = gnsf["x"] - xdot = gnsf["xdot"] - u = gnsf["u"] - z = gnsf["z"] - - # dimensions - nx = gnsf["nx"] - nz = gnsf["nz"] - - # get model matrices - A = gnsf["A"] - B = gnsf["B"] - C = gnsf["C"] - E = gnsf["E"] - c = gnsf["c"] - - A_LO = gnsf["A_LO"] - - y = gnsf["y"] - - phi_old = gnsf["phi_expr"] - - if print_info: - print(" ") - print("=================================================================") - print(" ") - print("================ Detect Linear Output System ===============") - print(" ") - print("=================================================================") - print(" ") - ## build initial I_x1 and I_x2_candidates - # I_xrange( all components of x for which either xii or xdot_ii enters y): - # I_LOS_candidates: the remaining components - - I_nsf_components = set() - I_LOS_candidates = set() - - if gnsf["ny"] > 0: - for ii in range(nx): - if which_depends(y, x[ii])[0] or which_depends(y, xdot[ii])[0]: - # i.e. xii or xiidot are part of y, and enter phi_expr - if print_info: - print(f"x_{ii} is part of x1") - I_nsf_components = set.union(I_nsf_components, set([ii])) - else: - # i.e. neither xii nor xiidot are part of y, i.e. enter phi_expr - I_LOS_candidates = set.union(I_LOS_candidates, set([ii])) - if print_info: - print(" ") - for ii in range(nz): - if which_depends(y, z[ii])[0]: - # i.e. xii or xiidot are part of y, and enter phi_expr - if print_info: - print(f"z_{ii} is part of x1") - I_nsf_components = set.union(I_nsf_components, set([ii + nx])) - else: - # i.e. neither xii nor xiidot are part of y, i.e. enter phi_expr - I_LOS_candidates = set.union(I_LOS_candidates, set([ii + nx])) - else: - I_LOS_candidates = set(range((nx + nz))) - if print_info: - print(" ") - print(f"I_LOS_candidates {I_LOS_candidates}") - new_nsf_components = I_nsf_components - I_nsf_eq = set([]) - unsorted_dyn = set(range(nx + nz)) - xdot_z = vertcat(xdot, z) - - ## determine components of Linear Output System - # determine maximal index set I_x2 - # such that the components x(I_x2) can be written as a LOS - Eq_map = [] - while True: - ## find equations corresponding to new_nsf_components - for ii in new_nsf_components: - current_var = xdot_z[ii] - var_name = current_var.name - - # print( unsorted_dyn) - # print("np.nonzero(E[:,ii])[0]",np.nonzero(E[:,ii])[0]) - I_eq = set.intersection(set(np.nonzero(E[:, ii])[0]), unsorted_dyn) - if len(I_eq) == 1: - i_eq = I_eq.pop() - if print_info: - print(f"component {i_eq} is associated with state {ii}") - elif len(I_eq) > 1: # x_ii_dot occurs in more than 1 eq linearly - # find the equation with least linear dependencies on - # I_LOS_cancidates - number_of_eq = 0 - candidate_dependencies = np.zeros(len(I_eq), 1) - I_x2_candidates = set.intersection(I_LOS_candidates, set(range(nx))) - for eq in I_eq: - depending_candidates = set.union( - np.nonzero(E[eq, I_LOS_candidates])[0], - np.nonzero(A[eq, I_x2_candidates])[0], - ) - candidate_dependencies[number_of_eq] = +len(depending_candidates) - number_of_eq += 1 - number_of_eq = np.argmin(candidate_dependencies) - i_eq = I_eq[number_of_eq] - else: ## x_ii_dot does not occur linearly in any of the unsorted dynamics - for j in unsorted_dyn: - phi_eq_j = gnsf["phi_expr"][np.nonzero(C[j, :])[0]] - if which_depends(phi_eq_j, xdot_z(ii))[0]: - I_eq = set.union(I_eq, j) - if is_empty(I_eq): - I_eq = unsorted_dyn - # find the equation with least linear dependencies on I_LOS_cancidates - number_of_eq = 0 - candidate_dependencies = np.zeros(len(I_eq), 1) - I_x2_candidates = set.intersection(I_LOS_candidates, set(range(nx))) - for eq in I_eq: - depending_candidates = set.union( - np.nonzero(E[eq, I_LOS_candidates])[0], - np.nonzero(A[eq, I_x2_candidates])[0], - ) - candidate_dependencies[number_of_eq] = +len(depending_candidates) - number_of_eq += 1 - number_of_eq = np.argmin(candidate_dependencies) - i_eq = I_eq[number_of_eq] - ## add 1 * [xdot,z](ii) to both sides of i_eq - if print_info: - print( - "adding 1 * ", - var_name, - " to both sides of equation ", - i_eq, - ".", - ) - gnsf["E"][i_eq, ii] = 1 - i_phi = np.nonzero(gnsf["C"][i_eq, :]) - if is_empty(i_phi): - i_phi = len(gnsf["phi_expr"]) + 1 - gnsf["C"][i_eq, i_phi] = 1 # add column to C with 1 entry - gnsf["phi_expr"] = vertcat(gnsf["phi_expr"], 0) - gnsf["phi_expr"][i_phi] = ( - gnsf["phi_expr"](i_phi) - + gnsf["E"][i_eq, ii] / gnsf["C"][i_eq, i_phi] * xdot_z[ii] - ) - if print_info: - print( - "detected equation ", - i_eq, - " to correspond to variable ", - var_name, - ) - I_nsf_eq = set.union(I_nsf_eq, {i_eq}) - # remove i_eq from unsorted_dyn - unsorted_dyn.remove(i_eq) - Eq_map.append([ii, i_eq]) - - ## add components to I_x1 - for eq in I_nsf_eq: - I_linear_dependence = set.union( - set(np.nonzero(A[eq, :])[0]), set(np.nonzero(E[eq, :])[0]) - ) - I_nsf_components = set.union(I_linear_dependence, I_nsf_components) - # I_nsf_components = I_nsf_components[:] - - new_nsf_components = set.intersection(I_LOS_candidates, I_nsf_components) - if is_empty(new_nsf_components): - if print_info: - print("new_nsf_components is empty") - break - # remove new_nsf_components from candidates - I_LOS_candidates = set.difference(I_LOS_candidates, new_nsf_components) - if not is_empty(Eq_map): - # [~, new_eq_order] = sort(Eq_map(1,:)) - # I_nsf_eq = Eq_map(2, new_eq_order ) - for count, m in enumerate(Eq_map): - m.append(count) - sorted(Eq_map, key=lambda x: x[1]) - new_eq_order = [m[2] for m in Eq_map] - Eq_map = [Eq_map[i] for i in new_eq_order] - I_nsf_eq = [m[1] for m in Eq_map] - - else: - I_nsf_eq = [] - - I_LOS_components = I_LOS_candidates - I_LOS_eq = sorted(set.difference(set(range(nx + nz)), I_nsf_eq)) - I_nsf_eq = sorted(I_nsf_eq) - - I_x1 = set.intersection(I_nsf_components, set(range(nx))) - I_z1 = set.intersection(I_nsf_components, set(range(nx, nx + nz))) - I_z1 = set([i - nx for i in I_z1]) - - I_x2 = set.intersection(I_LOS_components, set(range(nx))) - I_z2 = set.intersection(I_LOS_components, set(range(nx, nx + nz))) - I_z2 = set([i - nx for i in I_z2]) - - if print_info: - print(f"I_x1 {I_x1}, I_x2 {I_x2}") - - ## permute x, xdot - if is_empty(I_x1): - x1 = [] - x1dot = [] - else: - x1 = x[list(I_x1)] - x1dot = xdot[list(I_x1)] - if is_empty(I_x2): - x2 = [] - x2dot = [] - else: - x2 = x[list(I_x2)] - x2dot = xdot[list(I_x2)] - if is_empty(I_z1): - z1 = [] - else: - z1 = z(I_z1) - if is_empty(I_z2): - z2 = [] - else: - z2 = z[list(I_z2)] - - I_x1 = sorted(I_x1) - I_x2 = sorted(I_x2) - I_z1 = sorted(I_z1) - I_z2 = sorted(I_z2) - gnsf["xdot"] = vertcat(x1dot, x2dot) - gnsf["x"] = vertcat(x1, x2) - gnsf["z"] = vertcat(z1, z2) - gnsf["nx1"] = len(I_x1) - gnsf["nx2"] = len(I_x2) - gnsf["nz1"] = len(I_z1) - gnsf["nz2"] = len(I_z2) - - # store permutations - gnsf["idx_perm_x"] = I_x1 + I_x2 - gnsf["ipiv_x"] = idx_perm_to_ipiv(gnsf["idx_perm_x"]) - gnsf["idx_perm_z"] = I_z1 + I_z2 - gnsf["ipiv_z"] = idx_perm_to_ipiv(gnsf["idx_perm_z"]) - gnsf["idx_perm_f"] = I_nsf_eq + I_LOS_eq - gnsf["ipiv_f"] = idx_perm_to_ipiv(gnsf["idx_perm_f"]) - - f_LO = SX.sym("f_LO", 0, 0) - - ## rewrite I_LOS_eq as LOS - if gnsf["n_out"] == 0: - C_phi = np.zeros(gnsf["nx"] + gnsf["nz"], 1) - else: - C_phi = C @ phi_old - if gnsf["nx1"] == 0: - Ax1 = np.zeros(gnsf["nx"] + gnsf["nz"], 1) - else: - Ax1 = A[:, sorted(I_x1)] @ x1 - if gnsf["nx1"] + gnsf["nz1"] == 0: - lhs_nsf = np.zeros(gnsf["nx"] + gnsf["nz"], 1) - else: - lhs_nsf = E[:, sorted(I_nsf_components)] @ vertcat(x1, z1) - n_LO = len(I_LOS_eq) - B_LO = np.zeros((n_LO, gnsf["nu"])) - A_LO = np.zeros((gnsf["nx2"] + gnsf["nz2"], gnsf["nx2"])) - E_LO = np.zeros((n_LO, n_LO)) - c_LO = np.zeros((n_LO, 1)) - - I_LOS_eq = list(I_LOS_eq) - for eq in I_LOS_eq: - i_LO = I_LOS_eq.index(eq) - f_LO = vertcat(f_LO, Ax1[eq] + C_phi[eq] - lhs_nsf[eq]) - print(f"eq {eq} I_LOS_components {I_LOS_components}, i_LO {i_LO}, f_LO {f_LO}") - E_LO[i_LO, :] = E[eq, sorted(I_LOS_components)] - A_LO[i_LO, :] = A[eq, I_x2] - c_LO[i_LO, :] = c[eq] - B_LO[i_LO, :] = B[eq, :] - if casadi_length(f_LO) == 0: - f_LO = SX.zeros((gnsf["nx2"] + gnsf["nz2"], 1)) - f_LO = simplify(f_LO) - gnsf["A_LO"] = A_LO - gnsf["E_LO"] = E_LO - gnsf["B_LO"] = B_LO - gnsf["c_LO"] = c_LO - gnsf["f_lo_expr"] = f_LO - - ## remove I_LOS_eq from NSF type system - gnsf["A"] = gnsf["A"][np.ix_(sorted(I_nsf_eq), sorted(I_x1))] - gnsf["B"] = gnsf["B"][sorted(I_nsf_eq), :] - gnsf["C"] = gnsf["C"][sorted(I_nsf_eq), :] - gnsf["E"] = gnsf["E"][np.ix_(sorted(I_nsf_eq), sorted(I_nsf_components))] - gnsf["c"] = gnsf["c"][sorted(I_nsf_eq), :] - - ## reduce phi, C - I_nonzero = [] - for ii in range(gnsf["C"].shape[1]): # n_colums of C: - print(f"ii {ii}") - if not all(gnsf["C"][:, ii] == 0): # if column ~= 0 - I_nonzero.append(ii) - gnsf["C"] = gnsf["C"][:, I_nonzero] - gnsf["phi_expr"] = gnsf["phi_expr"][I_nonzero] - - gnsf = determine_input_nonlinearity_function(gnsf) - - check_reformulation(model, gnsf, print_info) - - gnsf["nontrivial_f_LO"] = 0 - if not is_empty(gnsf["f_lo_expr"]): - for ii in range(casadi_length(gnsf["f_lo_expr"])): - fii = gnsf["f_lo_expr"][ii] - if not fii.is_zero(): - gnsf["nontrivial_f_LO"] = 1 - if not gnsf["nontrivial_f_LO"] and print_info: - print("f_LO is fully trivial (== 0)") - check_reformulation(model, gnsf, print_info) - - if print_info: - print("") - print( - "---------------------------------------------------------------------------------" - ) - print( - "------------- Success: Linear Output System (LOS) detected ----------------------" - ) - print( - "---------------------------------------------------------------------------------" - ) - print("") - print( - "==>> moved ", - gnsf["nx2"], - "differential states and ", - gnsf["nz2"], - " algebraic variables to the Linear Output System", - ) - print( - "==>> recuced output dimension of phi from ", - casadi_length(phi_old), - " to ", - casadi_length(gnsf["phi_expr"]), - ) - print(" ") - print("Matrices defining the LOS read as") - print(" ") - print("E_LO =") - print(gnsf["E_LO"]) - print("A_LO =") - print(gnsf["A_LO"]) - print("B_LO =") - print(gnsf["B_LO"]) - print("c_LO =") - print(gnsf["c_LO"]) - - return gnsf diff --git a/third_party/acados/acados_template/gnsf/reformulate_with_invertible_E_mat.py b/third_party/acados/acados_template/gnsf/reformulate_with_invertible_E_mat.py deleted file mode 100644 index 21ab8ebfd5..0000000000 --- a/third_party/acados/acados_template/gnsf/reformulate_with_invertible_E_mat.py +++ /dev/null @@ -1,167 +0,0 @@ -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# 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. -# -# 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.; -# -# Author: Jonathan Frey: jonathanpaulfrey(at)gmail.com - -from casadi import * -from .determine_input_nonlinearity_function import determine_input_nonlinearity_function -from .check_reformulation import check_reformulation - - -def reformulate_with_invertible_E_mat(gnsf, model, print_info): - ## Description - # this function checks that the necessary condition to apply the gnsf - # structure exploiting integrator to a model, namely that the matrices E11, - # E22 are invertible holds. - # if this is not the case, it will make these matrices invertible and add: - # corresponding terms, to the term C * phi, such that the obtained model is - # still equivalent - - # check invertibility of E11, E22 and reformulate if needed: - ind_11 = range(gnsf["nx1"]) - ind_22 = range(gnsf["nx1"], gnsf["nx1"] + gnsf["nz1"]) - - if print_info: - print(" ") - print("----------------------------------------------------") - print("checking rank of E11 and E22") - print("----------------------------------------------------") - ## check if E11, E22 are invertible: - z_check = False - if gnsf["nz1"] > 0: - z_check = ( - np.linalg.matrix_rank(gnsf["E"][np.ix_(ind_22, ind_22)]) != gnsf["nz1"] - ) - - if ( - np.linalg.matrix_rank(gnsf["E"][np.ix_(ind_11, ind_11)]) != gnsf["nx1"] - or z_check - ): - # print warning (always) - print(f"the rank of E11 or E22 is not full after the reformulation") - print("") - print( - f"the script will try to reformulate the model with an invertible matrix instead" - ) - print( - f"NOTE: this feature is based on a heuristic, it should be used with care!!!" - ) - - ## load models - xdot = gnsf["xdot"] - z = gnsf["z"] - - # # GNSF - # get dimensions - nx1 = gnsf["nx1"] - x1dot = xdot[range(nx1)] - - k = vertcat(x1dot, z) - for i in [1, 2]: - if i == 1: - ind = range(gnsf["nx1"]) - else: - ind = range(gnsf["nx1"], gnsf["nx1"] + gnsf["nz1"]) - mat = gnsf["E"][np.ix_(ind, ind)] - import pdb - - pdb.set_trace() - while np.linalg.matrix_rank(mat) < len(ind): - # import pdb; pdb.set_trace() - if print_info: - print(" ") - print(f"the rank of E", str(i), str(i), " is not full") - print( - f"the algorithm will try to reformulate the model with an invertible matrix instead" - ) - print( - f"NOTE: this feature is not super stable and might need more testing!!!!!!" - ) - for sub_max in ind: - sub_ind = range(min(ind), sub_max) - # regard the submatrix mat(sub_ind, sub_ind) - sub_mat = gnsf["E"][sub_ind, sub_ind] - if np.linalg.matrix_rank(sub_mat) < len(sub_ind): - # reformulate the model by adding a 1 to last diagonal - # element and changing rhs respectively. - gnsf["E"][sub_max, sub_max] = gnsf["E"][sub_max, sub_max] + 1 - # this means adding the term 1 * k(sub_max) to the sub_max - # row of the l.h.s - if len(np.nonzero(gnsf["C"][sub_max, :])[0]) == 0: - # if isempty(find(gnsf['C'](sub_max,:), 1)): - # add new nonlinearity entry - gnsf["C"][sub_max, gnsf["n_out"] + 1] = 1 - gnsf["phi_expr"] = vertcat(gnsf["phi_expr"], k[sub_max]) - else: - ind_f = np.nonzero(gnsf["C"][sub_max, :])[0] - if len(ind_f) != 1: - raise Exception("C is assumed to be a selection matrix") - else: - ind_f = ind_f[0] - # add term to corresponding nonlinearity entry - # note: herbey we assume that C is a selection matrix, - # i.e. gnsf['phi_expr'](ind_f) is only entering one equation - - gnsf["phi_expr"][ind_f] = ( - gnsf["phi_expr"][ind_f] - + k[sub_max] / gnsf["C"][sub_max, ind_f] - ) - gnsf = determine_input_nonlinearity_function(gnsf) - check_reformulation(model, gnsf, print_info) - print("successfully reformulated the model with invertible matrices E11, E22") - else: - if print_info: - print(" ") - print( - "the rank of both E11 and E22 is naturally full after the reformulation " - ) - print("==> model reformulation finished") - print(" ") - if (gnsf['nx2'] > 0 or gnsf['nz2'] > 0) and det(gnsf["E_LO"]) == 0: - print( - "_______________________________________________________________________________________________________" - ) - print(" ") - print("TAKE CARE ") - print("E_LO matrix is NOT regular after automatic transcription!") - print("->> this means the model CANNOT be used with the gnsf integrator") - print( - "->> it probably means that one entry (of xdot or z) that was moved to the linear output type system" - ) - print(" does not appear in the model at all (zero column in E_LO)") - print(" OR: the columns of E_LO are linearly dependent ") - print(" ") - print( - " SOLUTIONs: a) go through your model & check equations the method wanted to move to LOS" - ) - print(" b) deactivate the detect_LOS option") - print( - "_______________________________________________________________________________________________________" - ) - return gnsf diff --git a/third_party/acados/acados_template/gnsf/structure_detection_print_summary.py b/third_party/acados/acados_template/gnsf/structure_detection_print_summary.py deleted file mode 100644 index db2d18758e..0000000000 --- a/third_party/acados/acados_template/gnsf/structure_detection_print_summary.py +++ /dev/null @@ -1,174 +0,0 @@ -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# 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. -# -# 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.; -# -# Author: Jonathan Frey: jonathanpaulfrey(at)gmail.com - -from casadi import n_nodes -import numpy as np - - -def structure_detection_print_summary(gnsf, acados_ocp): - - ## Description - # this function prints the most important info after determining a GNSF - # reformulation of the implicit model "initial_model" into "gnsf", which is - # equivalent to the "reordered_model". - model = acados_ocp.model - # # GNSF - # get dimensions - nx = gnsf["nx"] - nu = gnsf["nu"] - nz = gnsf["nz"] - - nx1 = gnsf["nx1"] - nx2 = gnsf["nx2"] - - nz1 = gnsf["nz1"] - nz2 = gnsf["nz2"] - - # np = gnsf['np'] - n_out = gnsf["n_out"] - ny = gnsf["ny"] - nuhat = gnsf["nuhat"] - - # - f_impl_expr = model.f_impl_expr - n_nodes_initial = n_nodes(model.f_impl_expr) - # x_old = model.x - # f_impl_old = model.f_impl_expr - - x = gnsf["x"] - z = gnsf["z"] - - phi_current = gnsf["phi_expr"] - - ## PRINT SUMMARY -- STRUCHTRE DETECTION - print(" ") - print( - "*********************************************************************************************" - ) - print(" ") - print( - "****************** SUCCESS: GNSF STRUCTURE DETECTION COMPLETE !!! ***************" - ) - print(" ") - print( - "*********************************************************************************************" - ) - print(" ") - print( - f"========================= STRUCTURE DETECTION SUMMARY ====================================" - ) - print(" ") - print("-------- Nonlinear Static Feedback type system --------") - print(" ") - print(" successfully transcribed dynamic system model into GNSF structure ") - print(" ") - print( - "reduced dimension of nonlinearity phi from ", - str(nx + nz), - " to ", - str(gnsf["n_out"]), - ) - print(" ") - print( - "reduced input dimension of nonlinearity phi from ", - 2 * nx + nz + nu, - " to ", - gnsf["ny"] + gnsf["nuhat"], - ) - print(" ") - print(f"reduced number of nodes in CasADi expression of nonlinearity phi from {n_nodes_initial} to {n_nodes(phi_current)}\n") - print("----------- Linear Output System (LOS) ---------------") - if nx2 + nz2 > 0: - print(" ") - print(f"introduced Linear Output System of size ", str(nx2 + nz2)) - print(" ") - if nx2 > 0: - print("consisting of the states:") - print(" ") - print(x[range(nx1, nx)]) - print(" ") - if nz2 > 0: - print("and algebraic variables:") - print(" ") - print(z[range(nz1, nz)]) - print(" ") - if gnsf["purely_linear"] == 1: - print(" ") - print("Model is fully linear!") - print(" ") - if not all(gnsf["idx_perm_x"] == np.array(range(nx))): - print(" ") - print( - "--------------------------------------------------------------------------------------------------" - ) - print( - "NOTE: permuted differential state vector x, such that x_gnsf = x(idx_perm_x) with idx_perm_x =" - ) - print(" ") - print(gnsf["idx_perm_x"]) - if nz != 0 and not all(gnsf["idx_perm_z"] == np.array(range(nz))): - print(" ") - print( - "--------------------------------------------------------------------------------------------------" - ) - print( - "NOTE: permuted algebraic state vector z, such that z_gnsf = z(idx_perm_z) with idx_perm_z =" - ) - print(" ") - print(gnsf["idx_perm_z"]) - if not all(gnsf["idx_perm_f"] == np.array(range(nx + nz))): - print(" ") - print( - "--------------------------------------------------------------------------------------------------" - ) - print( - "NOTE: permuted rhs expression vector f, such that f_gnsf = f(idx_perm_f) with idx_perm_f =" - ) - print(" ") - print(gnsf["idx_perm_f"]) - ## print GNSF dimensions - print( - "--------------------------------------------------------------------------------------------------------" - ) - print(" ") - print("The dimensions of the GNSF reformulated model read as:") - print(" ") - # T_dim = table(nx, nu, nz, np, nx1, nz1, n_out, ny, nuhat) - # print( T_dim ) - print(f"nx ", {nx}) - print(f"nu ", {nu}) - print(f"nz ", {nz}) - # print(f"np ", {np}) - print(f"nx1 ", {nx1}) - print(f"nz1 ", {nz1}) - print(f"n_out ", {n_out}) - print(f"ny ", {ny}) - print(f"nuhat ", {nuhat}) diff --git a/third_party/acados/acados_template/simulink_default_opts.json b/third_party/acados/acados_template/simulink_default_opts.json deleted file mode 100644 index 5d178fef85..0000000000 --- a/third_party/acados/acados_template/simulink_default_opts.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "outputs": { - "u0": 1, - "utraj": 0, - "xtraj": 0, - "solver_status": 1, - "cost_value": 0, - "KKT_residual": 1, - "KKT_residuals": 0, - "x1": 1, - "CPU_time": 1, - "CPU_time_sim": 0, - "CPU_time_qp": 0, - "CPU_time_lin": 0, - "sqp_iter": 1 - }, - "inputs": { - "lbx_0": 1, - "ubx_0": 1, - "parameter_traj": 1, - "y_ref_0": 1, - "y_ref": 1, - "y_ref_e": 1, - "lbx": 1, - "ubx": 1, - "lbx_e": 1, - "ubx_e": 1, - "lbu": 1, - "ubu": 1, - "lg": 1, - "ug": 1, - "lh": 1, - "uh": 1, - "lh_e": 1, - "uh_e": 1, - "cost_W_0": 0, - "cost_W": 0, - "cost_W_e": 0, - "reset_solver": 0, - "x_init": 0, - "u_init": 0 - }, - "samplingtime": "t0" -} diff --git a/third_party/acados/acados_template/utils.py b/third_party/acados/acados_template/utils.py deleted file mode 100644 index d6f6c02f84..0000000000 --- a/third_party/acados/acados_template/utils.py +++ /dev/null @@ -1,435 +0,0 @@ -# -*- coding: future_fstrings -*- -# -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# 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. -# -# 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.; -# - -import os, sys, json -import urllib.request -import shutil -import numpy as np -from casadi import SX, MX, DM, Function, CasadiMeta - -ALLOWED_CASADI_VERSIONS = ('3.5.6', '3.5.5', '3.5.4', '3.5.3', '3.5.2', '3.5.1', '3.4.5', '3.4.0') - -TERA_VERSION = "0.0.34" - -PLATFORM2TERA = { - "linux": "linux", - "darwin": "osx", - "win32": "windows" -} - - -def get_acados_path(): - ACADOS_PATH = os.environ.get('ACADOS_SOURCE_DIR') - if not ACADOS_PATH: - acados_template_path = os.path.dirname(os.path.abspath(__file__)) - acados_path = os.path.join(acados_template_path, '..','..','..') - ACADOS_PATH = os.path.realpath(acados_path) - msg = 'Warning: Did not find environment variable ACADOS_SOURCE_DIR, ' - msg += 'guessed ACADOS_PATH to be {}.\n'.format(ACADOS_PATH) - msg += 'Please export ACADOS_SOURCE_DIR to avoid this warning.' - print(msg) - return ACADOS_PATH - - -def get_python_interface_path(): - ACADOS_PYTHON_INTERFACE_PATH = os.environ.get('ACADOS_PYTHON_INTERFACE_PATH') - if not ACADOS_PYTHON_INTERFACE_PATH: - acados_path = get_acados_path() - ACADOS_PYTHON_INTERFACE_PATH = os.path.join(acados_path, 'interfaces', 'acados_template', 'acados_template') - return ACADOS_PYTHON_INTERFACE_PATH - - -def get_tera_exec_path(): - TERA_PATH = os.environ.get('TERA_PATH') - if not TERA_PATH: - TERA_PATH = os.path.join(get_acados_path(), 'bin', 't_renderer') - if os.name == 'nt': - TERA_PATH += '.exe' - return TERA_PATH - - -def check_casadi_version(): - casadi_version = CasadiMeta.version() - if casadi_version in ALLOWED_CASADI_VERSIONS: - return - else: - msg = 'Warning: Please note that the following versions of CasADi are ' - msg += 'officially supported: {}.\n '.format(" or ".join(ALLOWED_CASADI_VERSIONS)) - msg += 'If there is an incompatibility with the CasADi generated code, ' - msg += 'please consider changing your CasADi version.\n' - msg += 'Version {} currently in use.'.format(casadi_version) - print(msg) - - -def is_column(x): - if isinstance(x, np.ndarray): - if x.ndim == 1: - return True - elif x.ndim == 2 and x.shape[1] == 1: - return True - else: - return False - elif isinstance(x, (MX, SX, DM)): - if x.shape[1] == 1: - return True - elif x.shape[0] == 0 and x.shape[1] == 0: - return True - else: - return False - elif x == None or x == []: - return False - else: - raise Exception("is_column expects one of the following types: np.ndarray, casadi.MX, casadi.SX." - + " Got: " + str(type(x))) - - -def is_empty(x): - if isinstance(x, (MX, SX, DM)): - return x.is_empty() - elif isinstance(x, np.ndarray): - if np.prod(x.shape) == 0: - return True - else: - return False - elif x == None: - return True - elif isinstance(x, (set, list)): - if len(x)==0: - return True - else: - return False - else: - raise Exception("is_empty expects one of the following types: casadi.MX, casadi.SX, " - + "None, numpy array empty list, set. Got: " + str(type(x))) - - -def casadi_length(x): - if isinstance(x, (MX, SX, DM)): - return int(np.prod(x.shape)) - else: - raise Exception("casadi_length expects one of the following types: casadi.MX, casadi.SX." - + " Got: " + str(type(x))) - - -def make_model_consistent(model): - x = model.x - xdot = model.xdot - u = model.u - z = model.z - p = model.p - - if isinstance(x, MX): - symbol = MX.sym - elif isinstance(x, SX): - symbol = SX.sym - else: - raise Exception("model.x must be casadi.SX or casadi.MX, got {}".format(type(x))) - - if is_empty(p): - model.p = symbol('p', 0, 0) - - if is_empty(z): - model.z = symbol('z', 0, 0) - - return model - -def get_lib_ext(): - lib_ext = '.so' - if sys.platform == 'darwin': - lib_ext = '.dylib' - elif os.name == 'nt': - lib_ext = '' - - return lib_ext - -def get_tera(): - tera_path = get_tera_exec_path() - acados_path = get_acados_path() - - if os.path.exists(tera_path) and os.access(tera_path, os.X_OK): - return tera_path - - repo_url = "https://github.com/acados/tera_renderer/releases" - url = "{}/download/v{}/t_renderer-v{}-{}".format( - repo_url, TERA_VERSION, TERA_VERSION, PLATFORM2TERA[sys.platform]) - - manual_install = 'For manual installation follow these instructions:\n' - manual_install += '1 Download binaries from {}\n'.format(url) - manual_install += '2 Copy them in {}/bin\n'.format(acados_path) - manual_install += '3 Strip the version and platform from the binaries: ' - manual_install += 'as t_renderer-v0.0.34-X -> t_renderer)\n' - manual_install += '4 Enable execution privilege on the file "t_renderer" with:\n' - manual_install += '"chmod +x {}"\n\n'.format(tera_path) - - msg = "\n" - msg += 'Tera template render executable not found, ' - msg += 'while looking in path:\n{}\n'.format(tera_path) - msg += 'In order to be able to render the templates, ' - msg += 'you need to download the tera renderer binaries from:\n' - msg += '{}\n\n'.format(repo_url) - msg += 'Do you wish to set up Tera renderer automatically?\n' - msg += 'y/N? (press y to download tera or any key for manual installation)\n' - - if input(msg) == 'y': - print("Dowloading {}".format(url)) - with urllib.request.urlopen(url) as response, open(tera_path, 'wb') as out_file: - shutil.copyfileobj(response, out_file) - print("Successfully downloaded t_renderer.") - os.chmod(tera_path, 0o755) - return tera_path - - msg_cancel = "\nYou cancelled automatic download.\n\n" - msg_cancel += manual_install - msg_cancel += "Once installed re-run your script.\n\n" - print(msg_cancel) - - sys.exit(1) - - -def render_template(in_file, out_file, output_dir, json_path, template_glob=None): - - acados_path = os.path.dirname(os.path.abspath(__file__)) - if template_glob is None: - template_glob = os.path.join(acados_path, 'c_templates_tera', '**', '*') - cwd = os.getcwd() - - if not os.path.exists(output_dir): - os.makedirs(output_dir) - os.chdir(output_dir) - - tera_path = get_tera() - - # call tera as system cmd - os_cmd = f"{tera_path} '{template_glob}' '{in_file}' '{json_path}' '{out_file}'" - # Windows cmd.exe can not cope with '...', so use "..." instead: - if os.name == 'nt': - os_cmd = os_cmd.replace('\'', '\"') - - status = os.system(os_cmd) - if (status != 0): - raise Exception(f'Rendering of {in_file} failed!\n\nAttempted to execute OS command:\n{os_cmd}\n\n') - - os.chdir(cwd) - - -## Conversion functions -def make_object_json_dumpable(input): - if isinstance(input, (np.ndarray)): - return input.tolist() - elif isinstance(input, (SX)): - return input.serialize() - elif isinstance(input, (MX)): - # NOTE: MX expressions can not be serialized, only Functions. - return input.__str__() - elif isinstance(input, (DM)): - return input.full() - else: - raise TypeError(f"Cannot make input of type {type(input)} dumpable.") - - -def format_class_dict(d): - """ - removes the __ artifact from class to dict conversion - """ - out = {} - for k, v in d.items(): - if isinstance(v, dict): - v = format_class_dict(v) - - out_key = k.split('__', 1)[-1] - out[k.replace(k, out_key)] = v - return out - - -def get_ocp_nlp_layout() -> dict: - python_interface_path = get_python_interface_path() - abs_path = os.path.join(python_interface_path, 'acados_layout.json') - with open(abs_path, 'r') as f: - ocp_nlp_layout = json.load(f) - return ocp_nlp_layout - - -def get_default_simulink_opts() -> dict: - python_interface_path = get_python_interface_path() - abs_path = os.path.join(python_interface_path, 'simulink_default_opts.json') - with open(abs_path, 'r') as f: - simulink_opts = json.load(f) - return simulink_opts - - -def J_to_idx(J): - nrows = J.shape[0] - idx = np.zeros((nrows, )) - for i in range(nrows): - this_idx = np.nonzero(J[i,:])[0] - if len(this_idx) != 1: - raise Exception('Invalid J matrix structure detected, ' \ - 'must contain one nonzero element per row.') - if this_idx.size > 0 and J[i,this_idx[0]] != 1: - raise Exception('J matrices can only contain 1s.') - idx[i] = this_idx[0] - return idx - - -def J_to_idx_slack(J): - nrows = J.shape[0] - ncol = J.shape[1] - idx = np.zeros((ncol, )) - i_idx = 0 - for i in range(nrows): - this_idx = np.nonzero(J[i,:])[0] - if len(this_idx) == 1: - idx[i_idx] = i - i_idx = i_idx + 1 - elif len(this_idx) > 1: - raise Exception('J_to_idx_slack: Invalid J matrix. ' \ - 'Found more than one nonzero in row ' + str(i)) - if this_idx.size > 0 and J[i,this_idx[0]] != 1: - raise Exception('J_to_idx_slack: J matrices can only contain 1s, ' \ - 'got J(' + str(i) + ', ' + str(this_idx[0]) + ') = ' + str(J[i,this_idx[0]]) ) - if not i_idx == ncol: - raise Exception('J_to_idx_slack: J must contain a 1 in every column!') - return idx - - -def acados_dae_model_json_dump(model): - - # load model - x = model.x - xdot = model.xdot - u = model.u - z = model.z - p = model.p - - f_impl = model.f_impl_expr - model_name = model.name - - # create struct with impl_dae_fun, casadi_version - fun_name = model_name + '_impl_dae_fun' - impl_dae_fun = Function(fun_name, [x, xdot, u, z, p], [f_impl]) - - casadi_version = CasadiMeta.version() - str_impl_dae_fun = impl_dae_fun.serialize() - - dae_dict = {"str_impl_dae_fun": str_impl_dae_fun, "casadi_version": casadi_version} - - # dump - json_file = model_name + '_acados_dae.json' - with open(json_file, 'w') as f: - json.dump(dae_dict, f, default=make_object_json_dumpable, indent=4, sort_keys=True) - print("dumped ", model_name, " dae to file:", json_file, "\n") - - -def set_up_imported_gnsf_model(acados_ocp): - - gnsf = acados_ocp.gnsf_model - - # check CasADi version - # dump_casadi_version = gnsf['casadi_version'] - # casadi_version = CasadiMeta.version() - - # if not casadi_version == dump_casadi_version: - # print("WARNING: GNSF model was dumped with another CasADi version.\n" - # + "This might yield errors. Please use the same version for compatibility, serialize version: " - # + dump_casadi_version + " current Python CasADi verison: " + casadi_version) - # input("Press any key to attempt to continue...") - - # load model - phi_fun = Function.deserialize(gnsf['phi_fun']) - phi_fun_jac_y = Function.deserialize(gnsf['phi_fun_jac_y']) - phi_jac_y_uhat = Function.deserialize(gnsf['phi_jac_y_uhat']) - get_matrices_fun = Function.deserialize(gnsf['get_matrices_fun']) - - # obtain gnsf dimensions - size_gnsf_A = get_matrices_fun.size_out(0) - acados_ocp.dims.gnsf_nx1 = size_gnsf_A[1] - acados_ocp.dims.gnsf_nz1 = size_gnsf_A[0] - size_gnsf_A[1] - acados_ocp.dims.gnsf_nuhat = max(phi_fun.size_in(1)) - acados_ocp.dims.gnsf_ny = max(phi_fun.size_in(0)) - acados_ocp.dims.gnsf_nout = max(phi_fun.size_out(0)) - - # save gnsf functions in model - acados_ocp.model.phi_fun = phi_fun - acados_ocp.model.phi_fun_jac_y = phi_fun_jac_y - acados_ocp.model.phi_jac_y_uhat = phi_jac_y_uhat - acados_ocp.model.get_matrices_fun = get_matrices_fun - - # get_matrices_fun = Function([model_name,'_gnsf_get_matrices_fun'], {dummy},... - # {A, B, C, E, L_x, L_xdot, L_z, L_u, A_LO, c, E_LO, B_LO,... - # nontrivial_f_LO, purely_linear, ipiv_x, ipiv_z, c_LO}); - get_matrices_out = get_matrices_fun(0) - acados_ocp.model.gnsf['nontrivial_f_LO'] = int(get_matrices_out[12]) - acados_ocp.model.gnsf['purely_linear'] = int(get_matrices_out[13]) - - if "f_lo_fun_jac_x1k1uz" in gnsf: - f_lo_fun_jac_x1k1uz = Function.deserialize(gnsf['f_lo_fun_jac_x1k1uz']) - acados_ocp.model.f_lo_fun_jac_x1k1uz = f_lo_fun_jac_x1k1uz - else: - dummy_var_x1 = SX.sym('dummy_var_x1', acados_ocp.dims.gnsf_nx1) - dummy_var_x1dot = SX.sym('dummy_var_x1dot', acados_ocp.dims.gnsf_nx1) - dummy_var_z1 = SX.sym('dummy_var_z1', acados_ocp.dims.gnsf_nz1) - dummy_var_u = SX.sym('dummy_var_z1', acados_ocp.dims.nu) - dummy_var_p = SX.sym('dummy_var_z1', acados_ocp.dims.np) - empty_var = SX.sym('empty_var', 0, 0) - - empty_fun = Function('empty_fun', \ - [dummy_var_x1, dummy_var_x1dot, dummy_var_z1, dummy_var_u, dummy_var_p], - [empty_var]) - acados_ocp.model.f_lo_fun_jac_x1k1uz = empty_fun - - del acados_ocp.gnsf_model - - -def idx_perm_to_ipiv(idx_perm): - n = len(idx_perm) - vec = list(range(n)) - ipiv = np.zeros(n) - - print(n, idx_perm) - # import pdb; pdb.set_trace() - for ii in range(n): - idx0 = idx_perm[ii] - for jj in range(ii,n): - if vec[jj]==idx0: - idx1 = jj - break - tmp = vec[ii] - vec[ii] = vec[idx1] - vec[idx1] = tmp - ipiv[ii] = idx1 - - ipiv = ipiv-1 # C 0-based indexing - return ipiv - - -def print_casadi_expression(f): - for ii in range(casadi_length(f)): - print(f[ii,:]) diff --git a/third_party/acados/acados_template/zoro_description.py b/third_party/acados/acados_template/zoro_description.py deleted file mode 100644 index 4d795c1502..0000000000 --- a/third_party/acados/acados_template/zoro_description.py +++ /dev/null @@ -1,78 +0,0 @@ -# Copyright (c) The acados authors. -# -# This file is part of acados. -# -# The 2-Clause BSD License -# -# 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. -# -# 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.; - -from dataclasses import dataclass, field -import numpy as np - - -@dataclass -class ZoroDescription: - """ - Zero-Order Robust Optimization scheme. - - For advanced users. - """ - backoff_scaling_gamma: float = 1.0 - fdbk_K_mat: np.ndarray = None - unc_jac_G_mat: np.ndarray = None # default: an identity matrix - P0_mat: np.ndarray = None - W_mat: np.ndarray = None - idx_lbx_t: list = field(default_factory=list) - idx_ubx_t: list = field(default_factory=list) - idx_lbx_e_t: list = field(default_factory=list) - idx_ubx_e_t: list = field(default_factory=list) - idx_lbu_t: list = field(default_factory=list) - idx_ubu_t: list = field(default_factory=list) - idx_lg_t: list = field(default_factory=list) - idx_ug_t: list = field(default_factory=list) - idx_lg_e_t: list = field(default_factory=list) - idx_ug_e_t: list = field(default_factory=list) - idx_lh_t: list = field(default_factory=list) - idx_uh_t: list = field(default_factory=list) - idx_lh_e_t: list = field(default_factory=list) - idx_uh_e_t: list = field(default_factory=list) - -def process_zoro_description(zoro_description: ZoroDescription): - zoro_description.nw, _ = zoro_description.W_mat.shape - if zoro_description.unc_jac_G_mat is None: - zoro_description.unc_jac_G_mat = np.eye(zoro_description.nw) - zoro_description.nlbx_t = len(zoro_description.idx_lbx_t) - zoro_description.nubx_t = len(zoro_description.idx_ubx_t) - zoro_description.nlbx_e_t = len(zoro_description.idx_lbx_e_t) - zoro_description.nubx_e_t = len(zoro_description.idx_ubx_e_t) - zoro_description.nlbu_t = len(zoro_description.idx_lbu_t) - zoro_description.nubu_t = len(zoro_description.idx_ubu_t) - zoro_description.nlg_t = len(zoro_description.idx_lg_t) - zoro_description.nug_t = len(zoro_description.idx_ug_t) - zoro_description.nlg_e_t = len(zoro_description.idx_lg_e_t) - zoro_description.nug_e_t = len(zoro_description.idx_ug_e_t) - zoro_description.nlh_t = len(zoro_description.idx_lh_t) - zoro_description.nuh_t = len(zoro_description.idx_uh_t) - zoro_description.nlh_e_t = len(zoro_description.idx_lh_e_t) - zoro_description.nuh_e_t = len(zoro_description.idx_uh_e_t) - return zoro_description.__dict__ diff --git a/third_party/acados/build.sh b/third_party/acados/build.sh deleted file mode 100755 index b45c167b16..0000000000 --- a/third_party/acados/build.sh +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env bash -set -e - -DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null && pwd)" - -ARCHNAME="x86_64" -BLAS_TARGET="X64_AUTOMATIC" -if [ -f /TICI ]; then - ARCHNAME="larch64" - BLAS_TARGET="ARMV8A_ARM_CORTEX_A57" -fi - -ACADOS_FLAGS="-DACADOS_WITH_QPOASES=ON -UBLASFEO_TARGET -DBLASFEO_TARGET=$BLAS_TARGET" - -if [[ "$OSTYPE" == "darwin"* ]]; then - ACADOS_FLAGS="$ACADOS_FLAGS -DCMAKE_OSX_ARCHITECTURES=arm64;x86_64 -DCMAKE_MACOSX_RPATH=1" - ARCHNAME="Darwin" -fi - -if [ ! -d acados_repo/ ]; then - git clone https://github.com/acados/acados.git $DIR/acados_repo - # git clone https://github.com/commaai/acados.git $DIR/acados_repo -fi -cd acados_repo -git fetch --all -git checkout 8af9b0ad180940ef611884574a0b27a43504311d # v0.2.2 -git submodule update --depth=1 --recursive --init - -# build -mkdir -p build -cd build -cmake $ACADOS_FLAGS .. -make -j20 install - -INSTALL_DIR="$DIR/$ARCHNAME" -rm -rf $INSTALL_DIR -mkdir -p $INSTALL_DIR - -rm $DIR/acados_repo/lib/*.json - -rm -rf $DIR/include $DIR/acados_template -cp -r $DIR/acados_repo/include $DIR -cp -r $DIR/acados_repo/lib $INSTALL_DIR -cp -r $DIR/acados_repo/interfaces/acados_template/acados_template $DIR/ -#pip3 install -e $DIR/acados/interfaces/acados_template - -# build tera -cd $DIR/acados_repo/interfaces/acados_template/tera_renderer/ -if [[ "$OSTYPE" == "darwin"* ]]; then - cargo build --verbose --release --target aarch64-apple-darwin - cargo build --verbose --release --target x86_64-apple-darwin - lipo -create -output target/release/t_renderer target/x86_64-apple-darwin/release/t_renderer target/aarch64-apple-darwin/release/t_renderer -else - cargo build --verbose --release -fi -cp target/release/t_renderer $INSTALL_DIR/ diff --git a/third_party/acados/include/acados/dense_qp/dense_qp_common.h b/third_party/acados/include/acados/dense_qp/dense_qp_common.h deleted file mode 100644 index 2a9a974f99..0000000000 --- a/third_party/acados/include/acados/dense_qp/dense_qp_common.h +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -#ifndef ACADOS_DENSE_QP_DENSE_QP_COMMON_H_ -#define ACADOS_DENSE_QP_DENSE_QP_COMMON_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// hpipm -#include "hpipm/include/hpipm_d_dense_qp.h" -#include "hpipm/include/hpipm_d_dense_qp_res.h" -#include "hpipm/include/hpipm_d_dense_qp_sol.h" -// acados -#include "acados/utils/types.h" - -typedef struct d_dense_qp_dim dense_qp_dims; -typedef struct d_dense_qp dense_qp_in; -typedef struct d_dense_qp_sol dense_qp_out; -typedef struct d_dense_qp_res dense_qp_res; -typedef struct d_dense_qp_res_ws dense_qp_res_ws; - - - -#ifndef QP_SOLVER_CONFIG_ -#define QP_SOLVER_CONFIG_ -typedef struct -{ - void (*dims_set)(void *config_, void *dims_, const char *field, const int* value); - acados_size_t (*opts_calculate_size)(void *config, void *dims); - void *(*opts_assign)(void *config, void *dims, void *raw_memory); - void (*opts_initialize_default)(void *config, void *dims, void *args); - void (*opts_update)(void *config, void *dims, void *args); - void (*opts_set)(void *config_, void *opts_, const char *field, void* value); - acados_size_t (*memory_calculate_size)(void *config, void *dims, void *args); - void *(*memory_assign)(void *config, void *dims, void *args, void *raw_memory); - void (*memory_get)(void *config_, void *mem_, const char *field, void* value); - acados_size_t (*workspace_calculate_size)(void *config, void *dims, void *args); - int (*evaluate)(void *config, void *qp_in, void *qp_out, void *args, void *mem, void *work); - void (*eval_sens)(void *config, void *qp_in, void *qp_out, void *opts, void *mem, void *work); -} qp_solver_config; -#endif - - - -#ifndef QP_INFO_ -#define QP_INFO_ -typedef struct -{ - double solve_QP_time; - double condensing_time; - double interface_time; - double total_time; - int num_iter; - int t_computed; -} qp_info; -#endif - - - -/* config */ -// -acados_size_t dense_qp_solver_config_calculate_size(); -// -qp_solver_config *dense_qp_solver_config_assign(void *raw_memory); - -/* dims */ -// -acados_size_t dense_qp_dims_calculate_size(); -// -dense_qp_dims *dense_qp_dims_assign(void *raw_memory); -// -void dense_qp_dims_set(void *config_, void *dims_, const char *field, const int* value); -// - -/* in */ -// -acados_size_t dense_qp_in_calculate_size(dense_qp_dims *dims); -// -dense_qp_in *dense_qp_in_assign(dense_qp_dims *dims, void *raw_memory); - -/* out */ -// -acados_size_t dense_qp_out_calculate_size(dense_qp_dims *dims); -// -dense_qp_out *dense_qp_out_assign(dense_qp_dims *dims, void *raw_memory); -// -void dense_qp_out_get(dense_qp_out *out, const char *field, void *value); - -/* res */ -// -acados_size_t dense_qp_res_calculate_size(dense_qp_dims *dims); -// -dense_qp_res *dense_qp_res_assign(dense_qp_dims *dims, void *raw_memory); -// -acados_size_t dense_qp_res_workspace_calculate_size(dense_qp_dims *dims); -// -dense_qp_res_ws *dense_qp_res_workspace_assign(dense_qp_dims *dims, void *raw_memory); -// -void dense_qp_compute_t(dense_qp_in *qp_in, dense_qp_out *qp_out); -// -void dense_qp_res_compute(dense_qp_in *qp_in, dense_qp_out *qp_out, dense_qp_res *qp_res, dense_qp_res_ws *res_ws); -// -void dense_qp_res_compute_nrm_inf(dense_qp_res *qp_res, double res[4]); - -/* misc */ -// -void dense_qp_stack_slacks_dims(dense_qp_dims *in, dense_qp_dims *out); -// -void dense_qp_stack_slacks(dense_qp_in *in, dense_qp_in *out); -// -void dense_qp_unstack_slacks(dense_qp_out *in, dense_qp_in *qp_out, dense_qp_out *out); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_DENSE_QP_DENSE_QP_COMMON_H_ diff --git a/third_party/acados/include/acados/dense_qp/dense_qp_daqp.h b/third_party/acados/include/acados/dense_qp/dense_qp_daqp.h deleted file mode 100644 index b262089b4f..0000000000 --- a/third_party/acados/include/acados/dense_qp/dense_qp_daqp.h +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -#ifndef ACADOS_DENSE_QP_DENSE_QP_DAQP_H_ -#define ACADOS_DENSE_QP_DENSE_QP_DAQP_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// blasfeo -#include "blasfeo/include/blasfeo_common.h" - -// daqp -#include "daqp/include/types.h" - -// acados -#include "acados/dense_qp/dense_qp_common.h" -#include "acados/utils/types.h" - - -typedef struct dense_qp_daqp_opts_ -{ - DAQPSettings* daqp_opts; - int warm_start; -} dense_qp_daqp_opts; - - -typedef struct dense_qp_daqp_memory_ -{ - double* lb_tmp; - double* ub_tmp; - int* idxb; - int* idxv_to_idxb; - int* idxs; - int* idxdaqp_to_idxs; - - double* Zl; - double* Zu; - double* zl; - double* zu; - double* d_ls; - double* d_us; - - double time_qp_solver_call; - int iter; - DAQPWorkspace * daqp_work; - -} dense_qp_daqp_memory; - -// opts -acados_size_t dense_qp_daqp_opts_calculate_size(void *config, dense_qp_dims *dims); -// -void *dense_qp_daqp_opts_assign(void *config, dense_qp_dims *dims, void *raw_memory); -// -void dense_qp_daqp_opts_initialize_default(void *config, dense_qp_dims *dims, void *opts_); -// -void dense_qp_daqp_opts_update(void *config, dense_qp_dims *dims, void *opts_); -// -// memory -acados_size_t dense_qp_daqp_workspace_calculate_size(void *config, dense_qp_dims *dims, void *opts_); -// -void *dense_qp_daqp_workspace_assign(void *config, dense_qp_dims *dims, void *raw_memory); -// -acados_size_t dense_qp_daqp_memory_calculate_size(void *config, dense_qp_dims *dims, void *opts_); -// -void *dense_qp_daqp_memory_assign(void *config, dense_qp_dims *dims, void *opts_, void *raw_memory); -// -// functions -int dense_qp_daqp(void *config, dense_qp_in *qp_in, dense_qp_out *qp_out, void *opts_, void *memory_, void *work_); -// -void dense_qp_daqp_eval_sens(void *config_, void *qp_in, void *qp_out, void *opts_, void *mem_, void *work_); -// -void dense_qp_daqp_memory_reset(void *config_, void *qp_in, void *qp_out, void *opts_, void *mem_, void *work_); -// -void dense_qp_daqp_config_initialize_default(void *config_); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_DENSE_QP_DENSE_QP_DAQP_H_ diff --git a/third_party/acados/include/acados/dense_qp/dense_qp_hpipm.h b/third_party/acados/include/acados/dense_qp/dense_qp_hpipm.h deleted file mode 100644 index 136279d666..0000000000 --- a/third_party/acados/include/acados/dense_qp/dense_qp_hpipm.h +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -#ifndef ACADOS_DENSE_QP_DENSE_QP_HPIPM_H_ -#define ACADOS_DENSE_QP_DENSE_QP_HPIPM_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// hpipm -#include "hpipm/include/hpipm_d_dense_qp.h" -#include "hpipm/include/hpipm_d_dense_qp_ipm.h" -#include "hpipm/include/hpipm_d_dense_qp_sol.h" -// acados -#include "acados/dense_qp/dense_qp_common.h" -#include "acados/utils/types.h" - - - -typedef struct dense_qp_hpipm_opts_ -{ - struct d_dense_qp_ipm_arg *hpipm_opts; -} dense_qp_hpipm_opts; - - - -typedef struct dense_qp_hpipm_memory_ -{ - struct d_dense_qp_ipm_ws *hpipm_workspace; - double time_qp_solver_call; - int iter; - -} dense_qp_hpipm_memory; - - - -// -acados_size_t dense_qp_hpipm_opts_calculate_size(void *config, void *dims); -// -void *dense_qp_hpipm_opts_assign(void *config, void *dims, void *raw_memory); -// -void dense_qp_hpipm_opts_initialize_default(void *config, void *dims, void *opts_); -// -void dense_qp_hpipm_opts_update(void *config, void *dims, void *opts_); -// -acados_size_t dense_qp_hpipm_calculate_memory_size(void *dims, void *opts_); -// -void *dense_qp_hpipm_assign_memory(void *dims, void *opts_, void *raw_memory); -// -acados_size_t dense_qp_hpipm_calculate_workspace_size(void *dims, void *opts_); -// -int dense_qp_hpipm(void *config, void *qp_in, void *qp_out, void *opts_, void *mem_, void *work_); -// -void dense_qp_hpipm_eval_sens(void *config_, void *qp_in, void *qp_out, void *opts_, void *mem_, void *work_); -// -void dense_qp_hpipm_config_initialize_default(void *config_); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_DENSE_QP_DENSE_QP_HPIPM_H_ diff --git a/third_party/acados/include/acados/dense_qp/dense_qp_ooqp.h b/third_party/acados/include/acados/dense_qp/dense_qp_ooqp.h deleted file mode 100644 index d051cb15f7..0000000000 --- a/third_party/acados/include/acados/dense_qp/dense_qp_ooqp.h +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -#ifndef ACADOS_DENSE_QP_DENSE_QP_OOQP_H_ -#define ACADOS_DENSE_QP_DENSE_QP_OOQP_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "acados/dense_qp/dense_qp_common.h" -#include "acados/utils/types.h" - -enum dense_qp_ooqp_termination_code -{ - DENSE_SUCCESSFUL_TERMINATION = 0, - DENSE_NOT_FINISHED, - DENSE_MAX_ITS_EXCEEDED, - DENSE_INFEASIBLE, - DENSE_UNKNOWN -}; - -typedef struct dense_qp_ooqp_opts_ -{ - int printLevel; - int useDiagonalWeights; // TODO(dimitris): implement option - int fixHessian; - int fixDynamics; - int fixInequalities; -} dense_qp_ooqp_opts; - -typedef struct dense_qp_ooqp_workspace_ -{ - double *x; - double *gamma; - double *phi; - double *y; - double *z; - double *lambda; - double *pi; - double objectiveValue; -} dense_qp_ooqp_workspace; - -typedef struct dense_qp_ooqp_memory_ -{ - int firstRun; - int nx; - int my; - int mz; - double *c; - double *dQ; - double *xlow; - char *ixlow; - double *xupp; - char *ixupp; - double *dA; - double *bA; - double *dC; - double *clow; - char *iclow; - double *cupp; - char *icupp; - double time_qp_solver_call; - int iter; - -} dense_qp_ooqp_memory; - -// -acados_size_t dense_qp_ooqp_opts_calculate_size(void *config_, dense_qp_dims *dims); -// -void *dense_qp_ooqp_opts_assign(void *config_, dense_qp_dims *dims, void *raw_memory); -// -void dense_qp_ooqp_opts_initialize_default(void *config_, dense_qp_dims *dims, void *opts_); -// -void dense_qp_ooqp_opts_update(void *config_, dense_qp_dims *dims, void *opts_); -// -acados_size_t dense_qp_ooqp_memory_calculate_size(void *config_, dense_qp_dims *dims, void *opts_); -// -void *dense_qp_ooqp_memory_assign(void *config_, dense_qp_dims *dims, void *opts_, - void *raw_memory); -// -acados_size_t dense_qp_ooqp_workspace_calculate_size(void *config_, dense_qp_dims *dims, void *opts_); -// -int dense_qp_ooqp(void *config_, dense_qp_in *qp_in, dense_qp_out *qp_out, void *opts_, - void *memory_, void *work_); -// -void dense_qp_ooqp_destroy(void *mem_, void *work); -// -void dense_qp_ooqp_eval_sens(void *config_, void *qp_in, void *qp_out, void *opts_, void *mem_, void *work_); -// -void dense_qp_ooqp_config_initialize_default(void *config_); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_DENSE_QP_DENSE_QP_OOQP_H_ diff --git a/third_party/acados/include/acados/dense_qp/dense_qp_qore.h b/third_party/acados/include/acados/dense_qp/dense_qp_qore.h deleted file mode 100644 index 392e472918..0000000000 --- a/third_party/acados/include/acados/dense_qp/dense_qp_qore.h +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -#ifndef ACADOS_DENSE_QP_DENSE_QP_QORE_H_ -#define ACADOS_DENSE_QP_DENSE_QP_QORE_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// qore -#include "qore/QPSOLVER_DENSE/include/qpsolver_dense.h" -// acados -#include "acados/dense_qp/dense_qp_common.h" -#include "acados/utils/types.h" - -typedef struct dense_qp_qore_opts_ -{ - int nsmax; // maximum size of Schur complement - int print_freq; // print frequency, - // prtfreq < 0: disable printing; - // prtfreq == 0: print on each call and include working set changes; - // prtfreq > 0: print on every prtfreq seconds, but do not include working set - // changes; - int warm_start; // warm start with updated matrices H and C - int warm_strategy; // 0: ramp-up from zero homotopy; 1: setup homotopy from the previous - // solution - int hot_start; // hot start with unchanged matrices H and C - int max_iter; // maximum number of iterations - int compute_t; // compute t in qp_out (to have correct residuals in NLP) -} dense_qp_qore_opts; - -typedef struct dense_qp_qore_memory_ -{ - double *H; - double *HH; - double *g; - double *gg; - double *Zl; - double *Zu; - double *zl; - double *zu; - double *A; - double *b; - double *C; - double *CC; - double *Ct; - double *CCt; - double *d_lb0; - double *d_ub0; - double *d_lb; - double *d_ub; - double *d_lg; - double *d_ug; - double *d_ls; - double *d_us; - double *lb; - double *ub; - int *idxb; - int *idxb_stacked; - int *idxs; - double *prim_sol; - double *dual_sol; - QoreProblemDense *QP; - int num_iter; - dense_qp_in *qp_stacked; - double time_qp_solver_call; - int iter; - -} dense_qp_qore_memory; - -acados_size_t dense_qp_qore_opts_calculate_size(void *config, dense_qp_dims *dims); -// -void *dense_qp_qore_opts_assign(void *config, dense_qp_dims *dims, void *raw_memory); -// -void dense_qp_qore_opts_initialize_default(void *config, dense_qp_dims *dims, void *opts_); -// -void dense_qp_qore_opts_update(void *config, dense_qp_dims *dims, void *opts_); -// -acados_size_t dense_qp_qore_memory_calculate_size(void *config, dense_qp_dims *dims, void *opts_); -// -void *dense_qp_qore_memory_assign(void *config, dense_qp_dims *dims, void *opts_, void *raw_memory); -// -acados_size_t dense_qp_qore_workspace_calculate_size(void *config, dense_qp_dims *dims, void *opts_); -// -int dense_qp_qore(void *config, dense_qp_in *qp_in, dense_qp_out *qp_out, void *opts_, void *memory_, void *work_); -// -void dense_qp_qore_eval_sens(void *config_, void *qp_in, void *qp_out, void *opts_, void *mem_, void *work_); -// -void dense_qp_qore_config_initialize_default(void *config); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_DENSE_QP_DENSE_QP_QORE_H_ diff --git a/third_party/acados/include/acados/dense_qp/dense_qp_qpoases.h b/third_party/acados/include/acados/dense_qp/dense_qp_qpoases.h deleted file mode 100644 index 0e13d3ef64..0000000000 --- a/third_party/acados/include/acados/dense_qp/dense_qp_qpoases.h +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -#ifndef ACADOS_DENSE_QP_DENSE_QP_QPOASES_H_ -#define ACADOS_DENSE_QP_DENSE_QP_QPOASES_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// blasfeo -#include "blasfeo/include/blasfeo_common.h" - -// acados -#include "acados/dense_qp/dense_qp_common.h" -#include "acados/utils/types.h" - -typedef struct dense_qp_qpoases_opts_ -{ - double max_cputime; // maximum cpu time in seconds - int max_nwsr; // maximum number of working set recalculations - int warm_start; // warm start with dual_sol in memory - int use_precomputed_cholesky; - int hotstart; // this option requires constant data matrices! (eg linear MPC, inexact schemes - // with frozen sensitivities) - int set_acado_opts; // use same options as in acado code generation - int compute_t; // compute t in qp_out (to have correct residuals in NLP) - double tolerance; // terminationTolerance -} dense_qp_qpoases_opts; - -typedef struct dense_qp_qpoases_memory_ -{ - double *H; - double *HH; - double *R; - double *g; - double *gg; - double *Zl; - double *Zu; - double *zl; - double *zu; - double *A; - double *b; - double *d_lb0; - double *d_ub0; - double *d_lb; - double *d_ub; - double *C; - double *CC; - double *d_lg0; - double *d_ug0; - double *d_lg; - double *d_ug; - double *d_ls; - double *d_us; - int *idxb; - int *idxb_stacked; - int *idxs; - double *prim_sol; - double *dual_sol; - void *QPB; // NOTE(giaf): cast to QProblemB to use - void *QP; // NOTE(giaf): cast to QProblem to use - double cputime; // cputime of qpoases - int nwsr; // performed number of working set recalculations - int first_it; // to be used with hotstart - dense_qp_in *qp_stacked; - double time_qp_solver_call; // equal to cputime - int iter; - -} dense_qp_qpoases_memory; - -acados_size_t dense_qp_qpoases_opts_calculate_size(void *config, dense_qp_dims *dims); -// -void *dense_qp_qpoases_opts_assign(void *config, dense_qp_dims *dims, void *raw_memory); -// -void dense_qp_qpoases_opts_initialize_default(void *config, dense_qp_dims *dims, void *opts_); -// -void dense_qp_qpoases_opts_update(void *config, dense_qp_dims *dims, void *opts_); -// -acados_size_t dense_qp_qpoases__memorycalculate_size(void *config, dense_qp_dims *dims, void *opts_); -// -void *dense_qp_qpoases_memory_assign(void *config, dense_qp_dims *dims, void *opts_, void *raw_memory); -// -acados_size_t dense_qp_qpoases_workspace_calculate_size(void *config, dense_qp_dims *dims, void *opts_); -// -int dense_qp_qpoases(void *config, dense_qp_in *qp_in, dense_qp_out *qp_out, void *opts_, void *memory_, void *work_); -// -void dense_qp_qpoases_eval_sens(void *config_, void *qp_in, void *qp_out, void *opts_, void *mem_, void *work_); -// -void dense_qp_qpoases_memory_reset(void *config_, void *qp_in, void *qp_out, void *opts_, void *mem_, void *work_); -// -void dense_qp_qpoases_config_initialize_default(void *config_); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_DENSE_QP_DENSE_QP_QPOASES_H_ diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_common.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_common.h deleted file mode 100644 index ba97db9768..0000000000 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_common.h +++ /dev/null @@ -1,446 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - - -/// \defgroup ocp_nlp ocp_nlp -/// @{ -/// @} - -/// \defgroup ocp_nlp_solver ocp_nlp_solver -/// @{ -/// @} - -/// \ingroup ocp_nlp -/// @{ - -/// \ingroup ocp_nlp_solver -/// @{ - -/// \defgroup ocp_nlp_common ocp_nlp_common -/// @{ - -#ifndef ACADOS_OCP_NLP_OCP_NLP_COMMON_H_ -#define ACADOS_OCP_NLP_OCP_NLP_COMMON_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "acados/ocp_nlp/ocp_nlp_constraints_common.h" -#include "acados/ocp_nlp/ocp_nlp_cost_common.h" -#include "acados/ocp_nlp/ocp_nlp_dynamics_common.h" -#include "acados/ocp_nlp/ocp_nlp_reg_common.h" -#include "acados/ocp_qp/ocp_qp_common.h" -#include "acados/ocp_qp/ocp_qp_xcond_solver.h" -#include "acados/sim/sim_common.h" -#include "acados/utils/external_function_generic.h" -#include "acados/utils/types.h" - - - -/************************************************ - * config - ************************************************/ - -typedef struct ocp_nlp_config -{ - int N; // number of stages - - // solver-specific implementations of memory management functions - acados_size_t (*opts_calculate_size)(void *config, void *dims); - void *(*opts_assign)(void *config, void *dims, void *raw_memory); - void (*opts_initialize_default)(void *config, void *dims, void *opts_); - void (*opts_update)(void *config, void *dims, void *opts_); - acados_size_t (*memory_calculate_size)(void *config, void *dims, void *opts_); - void *(*memory_assign)(void *config, void *dims, void *opts_, void *raw_memory); - acados_size_t (*workspace_calculate_size)(void *config, void *dims, void *opts_); - void (*opts_set)(void *config_, void *opts_, const char *field, void* value); - void (*opts_set_at_stage)(void *config_, void *opts_, size_t stage, const char *field, void* value); - // evaluate solver // TODO rename into solve - int (*evaluate)(void *config, void *dims, void *nlp_in, void *nlp_out, void *opts_, void *mem, void *work); - void (*eval_param_sens)(void *config, void *dims, void *opts_, void *mem, void *work, - char *field, int stage, int index, void *sens_nlp_out); - // prepare memory - int (*precompute)(void *config, void *dims, void *nlp_in, void *nlp_out, void *opts_, void *mem, void *work); - void (*memory_reset_qp_solver)(void *config, void *dims, void *nlp_in, void *nlp_out, void *opts_, void *mem, void *work); - // initalize this struct with default values - void (*config_initialize_default)(void *config); - // general getter - void (*get)(void *config_, void *dims, void *mem_, const char *field, void *return_value_); - void (*opts_get)(void *config_, void *dims, void *opts_, const char *field, void *return_value_); - void (*work_get)(void *config_, void *dims, void *work_, const char *field, void *return_value_); - // config structs of submodules - ocp_qp_xcond_solver_config *qp_solver; // TODO rename xcond_solver - ocp_nlp_dynamics_config **dynamics; - ocp_nlp_cost_config **cost; - ocp_nlp_constraints_config **constraints; - ocp_nlp_reg_config *regularize; - -} ocp_nlp_config; - -// -acados_size_t ocp_nlp_config_calculate_size(int N); -// -ocp_nlp_config *ocp_nlp_config_assign(int N, void *raw_memory); - - - -/************************************************ - * dims - ************************************************/ - -/// Structure to store dimensions/number of variables. -typedef struct ocp_nlp_dims -{ - void **cost; - void **dynamics; - void **constraints; - ocp_qp_xcond_solver_dims *qp_solver; // xcond solver instead ?? - ocp_nlp_reg_dims *regularize; - - int *nv; // number of primal variables (states+controls+slacks) - int *nx; // number of differential states - int *nu; // number of inputs - int *ni; // number of two-sided inequality constraints: nb+ng+nh+ns - int *nz; // number of algebraic variables - int *ns; // number of slack variables - int N; // number of shooting nodes - - void *raw_memory; // Pointer to allocated memory, to be used for freeing -} ocp_nlp_dims; - -// -acados_size_t ocp_nlp_dims_calculate_size(void *config); -// -ocp_nlp_dims *ocp_nlp_dims_assign(void *config, void *raw_memory); - -/// Sets the dimension of optimization variables -/// (states, constrols, algebraic variables, slack variables). -/// -/// \param config_ The configuration struct. -/// \param dims_ The dimension struct. -/// \param field The type of optimization variables, either nx, nu, nz, or ns. -/// \param value_array Number of variables for each stage. -void ocp_nlp_dims_set_opt_vars(void *config_, void *dims_, - const char *field, const void* value_array); - -/// Sets the dimensions of constraints functions for a stage -/// (bounds on states, bounds on controls, equality constraints, -/// inequality constraints). -/// -/// \param config_ The configuration struct. -/// \param dims_ The dimension struct. -/// \param stage Stage number. -/// \param field The type of constraint/bound, either nbx, nbu, ng, or nh. -/// \param value_field Number of constraints/bounds for the given stage. -void ocp_nlp_dims_set_constraints(void *config_, void *dims_, int stage, - const char *field, const void* value_field); - -/// Sets the dimensions of the cost terms for a stage. -/// -/// \param config_ The configuration struct. -/// \param dims_ The dimension struct. -/// \param stage Stage number. -/// \param field Type of cost term, can be eiter ny. -/// \param value_field Number of cost terms/residuals for the given stage. -void ocp_nlp_dims_set_cost(void *config_, void *dims_, int stage, const char *field, - const void* value_field); - -/// Sets the dimensions of the dynamics for a stage. -/// -/// \param config_ The configuration struct. -/// \param dims_ The dimension struct. -/// \param stage Stage number. -/// \param field TBD -/// \param value TBD -void ocp_nlp_dims_set_dynamics(void *config_, void *dims_, int stage, const char *field, - const void* value); - -/************************************************ - * Inputs - ************************************************/ - -/// Struct for storing the inputs of an OCP NLP solver -typedef struct ocp_nlp_in -{ - /// Length of sampling intervals/timesteps. - double *Ts; - - /// Pointers to cost functions (TBC). - void **cost; - - /// Pointers to dynamics functions (TBC). - void **dynamics; - - /// Pointers to constraints functions (TBC). - void **constraints; - - /// Pointer to allocated memory, to be used for freeing. - void *raw_memory; - -} ocp_nlp_in; - -// -acados_size_t ocp_nlp_in_calculate_size_self(int N); -// -acados_size_t ocp_nlp_in_calculate_size(ocp_nlp_config *config, ocp_nlp_dims *dims); -// -ocp_nlp_in *ocp_nlp_in_assign_self(int N, void *raw_memory); -// -ocp_nlp_in *ocp_nlp_in_assign(ocp_nlp_config *config, ocp_nlp_dims *dims, void *raw_memory); - - -/************************************************ - * out - ************************************************/ - -typedef struct ocp_nlp_out -{ - struct blasfeo_dvec *ux; // NOTE: this contains [u; x; s_l; s_u]! - rename to uxs? - struct blasfeo_dvec *z; // algebraic vairables - struct blasfeo_dvec *pi; // multipliers for dynamics - struct blasfeo_dvec *lam; // inequality mulitpliers - struct blasfeo_dvec *t; // slack variables corresponding to evaluation of all inequalities (at the solution) - - // NOTE: the inequalities are internally organized in the following order: - // [ lbu lbx lg lh lphi ubu ubx ug uh uphi; lsbu lsbx lsg lsh lsphi usbu usbx usg ush usphi] - double inf_norm_res; - - void *raw_memory; // Pointer to allocated memory, to be used for freeing - -} ocp_nlp_out; - -// -acados_size_t ocp_nlp_out_calculate_size(ocp_nlp_config *config, ocp_nlp_dims *dims); -// -ocp_nlp_out *ocp_nlp_out_assign(ocp_nlp_config *config, ocp_nlp_dims *dims, - void *raw_memory); - - - -/************************************************ - * options - ************************************************/ - -/// Globalization types -typedef enum -{ - FIXED_STEP, - MERIT_BACKTRACKING, -} ocp_nlp_globalization_t; - -typedef struct ocp_nlp_opts -{ - ocp_qp_xcond_solver_opts *qp_solver_opts; // xcond solver opts instead ??? - void *regularize; - void **dynamics; // dynamics_opts - void **cost; // cost_opts - void **constraints; // constraints_opts - double step_length; // step length in case of FIXED_STEP - double levenberg_marquardt; // LM factor to be added to the hessian before regularization - int reuse_workspace; - int num_threads; - int print_level; - - // TODO: move to separate struct? - ocp_nlp_globalization_t globalization; - int full_step_dual; - int line_search_use_sufficient_descent; - int globalization_use_SOC; - double alpha_min; - double alpha_reduction; - double eps_sufficient_descent; -} ocp_nlp_opts; - -// -acados_size_t ocp_nlp_opts_calculate_size(void *config, void *dims); -// -void *ocp_nlp_opts_assign(void *config, void *dims, void *raw_memory); -// -void ocp_nlp_opts_initialize_default(void *config, void *dims, void *opts); -// -void ocp_nlp_opts_update(void *config, void *dims, void *opts); -// -void ocp_nlp_opts_set(void *config_, void *opts_, const char *field, void* value); -// -void ocp_nlp_opts_set_at_stage(void *config, void *opts, int stage, const char *field, void *value); - - -/************************************************ - * residuals - ************************************************/ - -typedef struct ocp_nlp_res -{ - struct blasfeo_dvec *res_stat; // stationarity - struct blasfeo_dvec *res_eq; // dynamics - struct blasfeo_dvec *res_ineq; // inequality constraints - struct blasfeo_dvec *res_comp; // complementarity - struct blasfeo_dvec tmp; // tmp - double inf_norm_res_stat; - double inf_norm_res_eq; - double inf_norm_res_ineq; - double inf_norm_res_comp; - acados_size_t memsize; -} ocp_nlp_res; - -// -acados_size_t ocp_nlp_res_calculate_size(ocp_nlp_dims *dims); -// -ocp_nlp_res *ocp_nlp_res_assign(ocp_nlp_dims *dims, void *raw_memory); -// -void ocp_nlp_res_get_inf_norm(ocp_nlp_res *res, double *out); - -/************************************************ - * memory - ************************************************/ - -typedef struct ocp_nlp_memory -{ -// void *qp_solver_mem; // xcond solver mem instead ??? - ocp_qp_xcond_solver_memory *qp_solver_mem; // xcond solver mem instead ??? - void *regularize_mem; - void **dynamics; // dynamics memory - void **cost; // cost memory - void **constraints; // constraints memory - - // residuals - ocp_nlp_res *nlp_res; - - // qp in & out - ocp_qp_in *qp_in; - ocp_qp_out *qp_out; - // QP stuff not entering the qp_in struct - struct blasfeo_dmat *dzduxt; // dzdux transposed - struct blasfeo_dvec *z_alg; // z_alg, output algebraic variables - - struct blasfeo_dvec *cost_grad; - struct blasfeo_dvec *ineq_fun; - struct blasfeo_dvec *ineq_adj; - struct blasfeo_dvec *dyn_fun; - struct blasfeo_dvec *dyn_adj; - - double cost_value; - - bool *set_sim_guess; // indicate if there is new explicitly provided guess for integration variables - struct blasfeo_dvec *sim_guess; - - int *sqp_iter; // pointer to iteration number - -} ocp_nlp_memory; - -// -acados_size_t ocp_nlp_memory_calculate_size(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_opts *opts); -// -ocp_nlp_memory *ocp_nlp_memory_assign(ocp_nlp_config *config, ocp_nlp_dims *dims, - ocp_nlp_opts *opts, void *raw_memory); - - - -/************************************************ - * workspace - ************************************************/ - -typedef struct ocp_nlp_workspace -{ - - void *qp_work; - void **dynamics; // dynamics_workspace - void **cost; // cost_workspace - void **constraints; // constraints_workspace - - // for globalization: -> move to module?! - ocp_nlp_out *tmp_nlp_out; - ocp_nlp_out *weight_merit_fun; - struct blasfeo_dvec tmp_nxu; - struct blasfeo_dvec tmp_ni; - struct blasfeo_dvec dxnext_dy; - -} ocp_nlp_workspace; - -// -acados_size_t ocp_nlp_workspace_calculate_size(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_opts *opts); -// -ocp_nlp_workspace *ocp_nlp_workspace_assign(ocp_nlp_config *config, ocp_nlp_dims *dims, - ocp_nlp_opts *opts, ocp_nlp_memory *mem, void *raw_memory); - - - -/************************************************ - * function - ************************************************/ - -void ocp_nlp_alias_memory_to_submodules(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, - ocp_nlp_out *out, ocp_nlp_opts *opts, ocp_nlp_memory *mem, ocp_nlp_workspace *work); -// -void ocp_nlp_initialize_submodules(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, - ocp_nlp_out *out, ocp_nlp_opts *opts, ocp_nlp_memory *mem, ocp_nlp_workspace *work); -// -void ocp_nlp_approximate_qp_matrices(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, - ocp_nlp_out *out, ocp_nlp_opts *opts, ocp_nlp_memory *mem, ocp_nlp_workspace *work); -// -void ocp_nlp_approximate_qp_vectors_sqp(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, - ocp_nlp_out *out, ocp_nlp_opts *opts, ocp_nlp_memory *mem, ocp_nlp_workspace *work); -// -void ocp_nlp_embed_initial_value(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, - ocp_nlp_out *out, ocp_nlp_opts *opts, ocp_nlp_memory *mem, ocp_nlp_workspace *work); -// -void ocp_nlp_update_variables_sqp(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, - ocp_nlp_out *out, ocp_nlp_opts *opts, ocp_nlp_memory *mem, ocp_nlp_workspace *work, double alpha); -// -int ocp_nlp_precompute_common(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, - ocp_nlp_out *out, ocp_nlp_opts *opts, ocp_nlp_memory *mem, ocp_nlp_workspace *work); -// -double ocp_nlp_line_search(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, - ocp_nlp_out *out, ocp_nlp_opts *opts, ocp_nlp_memory *mem, ocp_nlp_workspace *work, - int check_early_termination); -// -double ocp_nlp_evaluate_merit_fun(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, - ocp_nlp_out *out, ocp_nlp_opts *opts, ocp_nlp_memory *mem, ocp_nlp_workspace *work); -// -void ocp_nlp_initialize_t_slacks(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, - ocp_nlp_out *out, ocp_nlp_opts *opts, ocp_nlp_memory *mem, ocp_nlp_workspace *work); -// -void ocp_nlp_res_compute(ocp_nlp_dims *dims, ocp_nlp_in *in, ocp_nlp_out *out, - ocp_nlp_res *res, ocp_nlp_memory *mem); -// -void ocp_nlp_cost_compute(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, - ocp_nlp_out *out, ocp_nlp_opts *opts, ocp_nlp_memory *mem, ocp_nlp_workspace *work); - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_NLP_OCP_NLP_COMMON_H_ -/// @} -/// @} -/// @} diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_constraints_bgh.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_constraints_bgh.h deleted file mode 100644 index 9dbf16f6dc..0000000000 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_constraints_bgh.h +++ /dev/null @@ -1,238 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -/// \addtogroup ocp_nlp -/// @{ -/// \addtogroup ocp_nlp_constraints -/// @{ - -#ifndef ACADOS_OCP_NLP_OCP_NLP_CONSTRAINTS_BGH_H_ -#define ACADOS_OCP_NLP_OCP_NLP_CONSTRAINTS_BGH_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// acados -#include "acados/ocp_qp/ocp_qp_common.h" -#include "acados/ocp_nlp/ocp_nlp_constraints_common.h" -#include "acados/utils/external_function_generic.h" -#include "acados/utils/types.h" - - - -/************************************************ - * dims - ************************************************/ - -typedef struct -{ - int nx; - int nu; - int nz; - int nb; // nbx + nbu - int nbu; // number of input box constraints - int nbx; // number of state box constraints - int ng; // number of general linear constraints - int nh; // number of nonlinear path constraints - int ns; // nsbu + nsbx + nsg + nsh - int nsbu; // number of softened input bounds - int nsbx; // number of softened state bounds - int nsg; // number of softened general linear constraints - int nsh; // number of softened nonlinear constraints - int nbue; // number of input box constraints which are equality - int nbxe; // number of state box constraints which are equality - int nge; // number of general linear constraints which are equality - int nhe; // number of nonlinear path constraints which are equality -} ocp_nlp_constraints_bgh_dims; - -// -acados_size_t ocp_nlp_constraints_bgh_dims_calculate_size(void *config); -// -void *ocp_nlp_constraints_bgh_dims_assign(void *config, void *raw_memory); -// -void ocp_nlp_constraints_bgh_dims_get(void *config_, void *dims_, const char *field, int* value); -// -void ocp_nlp_constraints_bgh_dims_set(void *config_, void *dims_, - const char *field, const int* value); - - -/************************************************ - * model - ************************************************/ - -typedef struct -{ - int *idxb; - int *idxs; - int *idxe; - struct blasfeo_dvec d; // gathers bounds - struct blasfeo_dmat DCt; // general linear constraint matrix - // lg <= [D, C] * [u; x] <= ug - external_function_generic *nl_constr_h_fun; // nonlinear: lh <= h(x,u) <= uh - external_function_generic *nl_constr_h_fun_jac; // nonlinear: lh <= h(x,u) <= uh - external_function_generic *nl_constr_h_fun_jac_hess; // nonlinear: lh <= h(x,u) <= uh -} ocp_nlp_constraints_bgh_model; - -// -acados_size_t ocp_nlp_constraints_bgh_model_calculate_size(void *config, void *dims); -// -void *ocp_nlp_constraints_bgh_model_assign(void *config, void *dims, void *raw_memory); -// -int ocp_nlp_constraints_bgh_model_set(void *config_, void *dims_, - void *model_, const char *field, void *value); - -// -void ocp_nlp_constraints_bgh_model_get(void *config_, void *dims_, - void *model_, const char *field, void *value); - - -/************************************************ - * options - ************************************************/ - -typedef struct -{ - int compute_adj; - int compute_hess; -} ocp_nlp_constraints_bgh_opts; - -// -acados_size_t ocp_nlp_constraints_bgh_opts_calculate_size(void *config, void *dims); -// -void *ocp_nlp_constraints_bgh_opts_assign(void *config, void *dims, void *raw_memory); -// -void ocp_nlp_constraints_bgh_opts_initialize_default(void *config, void *dims, void *opts); -// -void ocp_nlp_constraints_bgh_opts_update(void *config, void *dims, void *opts); -// -void ocp_nlp_constraints_bgh_opts_set(void *config, void *opts, char *field, void *value); - - - -/************************************************ - * memory - ************************************************/ - -typedef struct -{ - struct blasfeo_dvec fun; - struct blasfeo_dvec adj; - struct blasfeo_dvec *ux; // pointer to ux in nlp_out - struct blasfeo_dvec *tmp_ux; // pointer to ux in tmp_nlp_out - struct blasfeo_dvec *lam; // pointer to lam in nlp_out - struct blasfeo_dvec *tmp_lam;// pointer to lam in tmp_nlp_out - struct blasfeo_dvec *z_alg; // pointer to z_alg in ocp_nlp memory - struct blasfeo_dmat *DCt; // pointer to DCt in qp_in - struct blasfeo_dmat *RSQrq; // pointer to RSQrq in qp_in - struct blasfeo_dmat *dzduxt; // pointer to dzduxt in ocp_nlp memory - int *idxb; // pointer to idxb[ii] in qp_in - int *idxs_rev; // pointer to idxs_rev[ii] in qp_in - int *idxe; // pointer to idxe[ii] in qp_in -} ocp_nlp_constraints_bgh_memory; - -// -acados_size_t ocp_nlp_constraints_bgh_memory_calculate_size(void *config, void *dims, void *opts); -// -void *ocp_nlp_constraints_bgh_memory_assign(void *config, void *dims, void *opts, void *raw_memory); -// -struct blasfeo_dvec *ocp_nlp_constraints_bgh_memory_get_fun_ptr(void *memory_); -// -struct blasfeo_dvec *ocp_nlp_constraints_bgh_memory_get_adj_ptr(void *memory_); -// -void ocp_nlp_constraints_bgh_memory_set_ux_ptr(struct blasfeo_dvec *ux, void *memory_); -// -void ocp_nlp_constraints_bgh_memory_set_tmp_ux_ptr(struct blasfeo_dvec *tmp_ux, void *memory_); -// -void ocp_nlp_constraints_bgh_memory_set_lam_ptr(struct blasfeo_dvec *lam, void *memory_); -// -void ocp_nlp_constraints_bgh_memory_set_tmp_lam_ptr(struct blasfeo_dvec *tmp_lam, void *memory_); -// -void ocp_nlp_constraints_bgh_memory_set_DCt_ptr(struct blasfeo_dmat *DCt, void *memory); -// -void ocp_nlp_constraints_bgh_memory_set_RSQrq_ptr(struct blasfeo_dmat *RSQrq, void *memory_); -// -void ocp_nlp_constraints_bgh_memory_set_z_alg_ptr(struct blasfeo_dvec *z_alg, void *memory_); -// -void ocp_nlp_constraints_bgh_memory_set_dzduxt_ptr(struct blasfeo_dmat *dzduxt, void *memory_); -// -void ocp_nlp_constraints_bgh_memory_set_idxb_ptr(int *idxb, void *memory_); -// -void ocp_nlp_constraints_bgh_memory_set_idxs_rev_ptr(int *idxs_rev, void *memory_); -// -void ocp_nlp_constraints_bgh_memory_set_idxe_ptr(int *idxe, void *memory_); - - - -/************************************************ - * workspace - ************************************************/ - -typedef struct -{ - struct blasfeo_dmat tmp_nv_nv; - struct blasfeo_dmat tmp_nz_nh; - struct blasfeo_dmat tmp_nv_nh; - struct blasfeo_dmat tmp_nz_nv; - struct blasfeo_dmat hess_z; - struct blasfeo_dvec tmp_ni; - struct blasfeo_dvec tmp_nh; -} ocp_nlp_constraints_bgh_workspace; - -// -acados_size_t ocp_nlp_constraints_bgh_workspace_calculate_size(void *config, void *dims, void *opts); - -/* functions */ - -// -void ocp_nlp_constraints_bgh_config_initialize_default(void *config); -// -void ocp_nlp_constraints_bgh_initialize(void *config, void *dims, void *model, void *opts, - void *mem, void *work); -// -void ocp_nlp_constraints_bgh_update_qp_matrices(void *config_, void *dims, void *model_, - void *opts_, void *memory_, void *work_); - -// -void ocp_nlp_constraints_bgh_compute_fun(void *config_, void *dims, void *model_, - void *opts_, void *memory_, void *work_); -// -void ocp_nlp_constraints_bgh_bounds_update(void *config_, void *dims, void *model_, - void *opts_, void *memory_, void *work_); - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_NLP_OCP_NLP_CONSTRAINTS_BGH_H_ -/// @} -/// @} diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_constraints_bgp.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_constraints_bgp.h deleted file mode 100644 index eb05edf7a6..0000000000 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_constraints_bgp.h +++ /dev/null @@ -1,218 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -/// \addtogroup ocp_nlp -/// @{ -/// \addtogroup ocp_nlp_constraints -/// @{ - -#ifndef ACADOS_OCP_NLP_OCP_NLP_CONSTRAINTS_BGP_H_ -#define ACADOS_OCP_NLP_OCP_NLP_CONSTRAINTS_BGP_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// acados -#include "acados/ocp_qp/ocp_qp_common.h" -#include "acados/ocp_nlp/ocp_nlp_constraints_common.h" -#include "acados/utils/external_function_generic.h" -#include "acados/utils/types.h" - - - -/* dims */ - -typedef struct -{ - int nx; - int nu; - int nz; - int nb; // nbx + nbu - int nbu; - int nbx; - int ng; // number of general linear constraints - int nphi; // dimension of convex outer part - int ns; // nsbu + nsbx + nsg + nsphi - int nsbu; // number of softened input bounds - int nsbx; // number of softened state bounds - int nsg; // number of softened general linear constraints - int nsphi; // number of softened nonlinear constraints - int nr; // dimension of nonlinear function in convex_over_nonlinear constraint - int nbue; // number of input box constraints which are equality - int nbxe; // number of state box constraints which are equality - int nge; // number of general linear constraints which are equality - int nphie; // number of nonlinear path constraints which are equality -} ocp_nlp_constraints_bgp_dims; - -// -acados_size_t ocp_nlp_constraints_bgp_dims_calculate_size(void *config); -// -void *ocp_nlp_constraints_bgp_dims_assign(void *config, void *raw_memory); -// -void ocp_nlp_constraints_bgp_dims_get(void *config_, void *dims_, const char *field, int* value); - - -/* model */ - -typedef struct -{ - // ocp_nlp_constraints_bgp_dims *dims; - int *idxb; - int *idxs; - int *idxe; - struct blasfeo_dvec d; - struct blasfeo_dmat DCt; - external_function_generic *nl_constr_phi_o_r_fun_phi_jac_ux_z_phi_hess_r_jac_ux; - external_function_generic *nl_constr_phi_o_r_fun; - external_function_generic *nl_constr_r_fun_jac; -} ocp_nlp_constraints_bgp_model; - -// -acados_size_t ocp_nlp_constraints_bgp_calculate_size(void *config, void *dims); -// -void *ocp_nlp_constraints_bgp_assign(void *config, void *dims, void *raw_memory); -// -int ocp_nlp_constraints_bgp_model_set(void *config_, void *dims_, - void *model_, const char *field, void *value); -// -void ocp_nlp_constraints_bgp_model_get(void *config_, void *dims_, - void *model_, const char *field, void *value); - -/* options */ - -typedef struct -{ - int compute_adj; - int compute_hess; -} ocp_nlp_constraints_bgp_opts; - -// -acados_size_t ocp_nlp_constraints_bgp_opts_calculate_size(void *config, void *dims); -// -void *ocp_nlp_constraints_bgp_opts_assign(void *config, void *dims, void *raw_memory); -// -void ocp_nlp_constraints_bgp_opts_initialize_default(void *config, void *dims, void *opts); -// -void ocp_nlp_constraints_bgp_opts_update(void *config, void *dims, void *opts); -// -void ocp_nlp_constraints_bgp_opts_set(void *config, void *opts, char *field, void *value); - -/* memory */ - -typedef struct -{ - struct blasfeo_dvec fun; - struct blasfeo_dvec adj; - struct blasfeo_dvec *ux; // pointer to ux in nlp_out - struct blasfeo_dvec *tmp_ux; // pointer to ux in tmp_nlp_out - struct blasfeo_dvec *lam; // pointer to lam in nlp_out - struct blasfeo_dvec *tmp_lam;// pointer to lam in tmp_nlp_out - struct blasfeo_dvec *z_alg; // pointer to z_alg in ocp_nlp memory - struct blasfeo_dmat *DCt; // pointer to DCt in qp_in - struct blasfeo_dmat *RSQrq; // pointer to RSQrq in qp_in - struct blasfeo_dmat *dzduxt; // pointer to dzduxt in ocp_nlp memory - int *idxb; // pointer to idxb[ii] in qp_in - int *idxs_rev; // pointer to idxs_rev[ii] in qp_in - int *idxe; // pointer to idxe[ii] in qp_in -} ocp_nlp_constraints_bgp_memory; - -// -acados_size_t ocp_nlp_constraints_bgp_memory_calculate_size(void *config, void *dims, void *opts); -// -void *ocp_nlp_constraints_bgp_memory_assign(void *config, void *dims, void *opts, - void *raw_memory); -// -struct blasfeo_dvec *ocp_nlp_constraints_bgp_memory_get_fun_ptr(void *memory_); -// -struct blasfeo_dvec *ocp_nlp_constraints_bgp_memory_get_adj_ptr(void *memory_); -// -void ocp_nlp_constraints_bgp_memory_set_ux_ptr(struct blasfeo_dvec *ux, void *memory_); -// -void ocp_nlp_constraints_bgp_memory_set_tmp_ux_ptr(struct blasfeo_dvec *tmp_ux, void *memory_); -// -void ocp_nlp_constraints_bgp_memory_set_lam_ptr(struct blasfeo_dvec *lam, void *memory_); -// -void ocp_nlp_constraints_bgp_memory_set_tmp_lam_ptr(struct blasfeo_dvec *tmp_lam, void *memory_); -// -void ocp_nlp_constraints_bgp_memory_set_DCt_ptr(struct blasfeo_dmat *DCt, void *memory); -// -void ocp_nlp_constraints_bgp_memory_set_z_alg_ptr(struct blasfeo_dvec *z_alg, void *memory_); -// -void ocp_nlp_constraints_bgp_memory_set_dzduxt_ptr(struct blasfeo_dmat *dzduxt, void *memory_); -// -void ocp_nlp_constraints_bgp_memory_set_idxb_ptr(int *idxb, void *memory_); -// -void ocp_nlp_constraints_bgp_memory_set_idxs_rev_ptr(int *idxs_rev, void *memory_); -// -void ocp_nlp_constraints_bgh_memory_set_idxe_ptr(int *idxe, void *memory_); - -/* workspace */ - -typedef struct -{ - struct blasfeo_dvec tmp_ni; - struct blasfeo_dmat jac_r_ux_tran; - struct blasfeo_dmat tmp_nr_nphi_nr; - struct blasfeo_dmat tmp_nv_nr; - struct blasfeo_dmat tmp_nv_nphi; - struct blasfeo_dmat tmp_nz_nphi; -} ocp_nlp_constraints_bgp_workspace; - -// -acados_size_t ocp_nlp_constraints_bgp_workspace_calculate_size(void *config, void *dims, void *opts); - -/* functions */ - -// -void ocp_nlp_constraints_bgp_config_initialize_default(void *config); -// -void ocp_nlp_constraints_bgp_initialize(void *config, void *dims, void *model, - void *opts, void *mem, void *work); -// -void ocp_nlp_constraints_bgp_update_qp_matrices(void *config_, void *dims, - void *model_, void *opts_, void *memory_, void *work_); -// -void ocp_nlp_constraints_bgp_compute_fun(void *config_, void *dims, - void *model_, void *opts_, void *memory_, void *work_); -// -void ocp_nlp_constraints_bgp_bounds_update(void *config_, void *dims, void *model_, - void *opts_, void *memory_, void *work_); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_NLP_OCP_NLP_CONSTRAINTS_BGP_H_ -/// @} -/// @} diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_constraints_common.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_constraints_common.h deleted file mode 100644 index bb73c468de..0000000000 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_constraints_common.h +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -/// \ingroup ocp_nlp -/// @{ - -/// \defgroup ocp_nlp_constraints ocp_nlp_constraints -/// @{ - -#ifndef ACADOS_OCP_NLP_OCP_NLP_CONSTRAINTS_COMMON_H_ -#define ACADOS_OCP_NLP_OCP_NLP_CONSTRAINTS_COMMON_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// acados -#include "acados/ocp_qp/ocp_qp_common.h" -#include "acados/utils/external_function_generic.h" -#include "acados/utils/types.h" - - - -/************************************************ - * config - ************************************************/ - -typedef struct -{ - acados_size_t (*dims_calculate_size)(void *config); - void *(*dims_assign)(void *config, void *raw_memory); - acados_size_t (*model_calculate_size)(void *config, void *dims); - void *(*model_assign)(void *config, void *dims, void *raw_memory); - int (*model_set)(void *config_, void *dims_, void *model_, const char *field, void *value); - void (*model_get)(void *config_, void *dims_, void *model_, const char *field, void *value); - acados_size_t (*opts_calculate_size)(void *config, void *dims); - void *(*opts_assign)(void *config, void *dims, void *raw_memory); - void (*opts_initialize_default)(void *config, void *dims, void *opts); - void (*opts_update)(void *config, void *dims, void *opts); - void (*opts_set)(void *config, void *opts, char *field, void *value); - acados_size_t (*memory_calculate_size)(void *config, void *dims, void *opts); - struct blasfeo_dvec *(*memory_get_fun_ptr)(void *memory); - struct blasfeo_dvec *(*memory_get_adj_ptr)(void *memory); - void (*memory_set_ux_ptr)(struct blasfeo_dvec *ux, void *memory); - void (*memory_set_tmp_ux_ptr)(struct blasfeo_dvec *tmp_ux, void *memory); - void (*memory_set_lam_ptr)(struct blasfeo_dvec *lam, void *memory); - void (*memory_set_tmp_lam_ptr)(struct blasfeo_dvec *tmp_lam, void *memory); - void (*memory_set_DCt_ptr)(struct blasfeo_dmat *DCt, void *memory); - void (*memory_set_RSQrq_ptr)(struct blasfeo_dmat *RSQrq, void *memory); - void (*memory_set_z_alg_ptr)(struct blasfeo_dvec *z_alg, void *memory); - void (*memory_set_dzdux_tran_ptr)(struct blasfeo_dmat *dzduxt, void *memory); - void (*memory_set_idxb_ptr)(int *idxb, void *memory); - void (*memory_set_idxs_rev_ptr)(int *idxs_rev, void *memory); - void (*memory_set_idxe_ptr)(int *idxe, void *memory); - void *(*memory_assign)(void *config, void *dims, void *opts, void *raw_memory); - acados_size_t (*workspace_calculate_size)(void *config, void *dims, void *opts); - void (*initialize)(void *config, void *dims, void *model, void *opts, void *mem, void *work); - void (*update_qp_matrices)(void *config, void *dims, void *model, void *opts, void *mem, void *work); - void (*compute_fun)(void *config, void *dims, void *model, void *opts, void *mem, void *work); - void (*bounds_update)(void *config, void *dims, void *model, void *opts, void *mem, void *work); - void (*config_initialize_default)(void *config); - // dimension setters - void (*dims_set)(void *config_, void *dims_, const char *field, const int *value); - void (*dims_get)(void *config_, void *dims_, const char *field, int* value); -} ocp_nlp_constraints_config; - -// -acados_size_t ocp_nlp_constraints_config_calculate_size(); -// -ocp_nlp_constraints_config *ocp_nlp_constraints_config_assign(void *raw_memory); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_NLP_OCP_NLP_CONSTRAINTS_COMMON_H_ -/// @} -/// @} diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_cost_common.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_cost_common.h deleted file mode 100644 index eb40564036..0000000000 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_cost_common.h +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -/// -/// \defgroup ocp_nlp_cost ocp_nlp_cost -/// - -/// \addtogroup ocp_nlp_cost ocp_nlp_cost -/// @{ -/// \addtogroup ocp_nlp_cost_common ocp_nlp_cost_common -/// @{ - -#ifndef ACADOS_OCP_NLP_OCP_NLP_COST_COMMON_H_ -#define ACADOS_OCP_NLP_OCP_NLP_COST_COMMON_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// acados -#include "acados/utils/external_function_generic.h" -#include "acados/utils/types.h" - - - -/************************************************ - * config - ************************************************/ - -typedef struct -{ - acados_size_t (*dims_calculate_size)(void *config); - void *(*dims_assign)(void *config, void *raw_memory); - void (*dims_set)(void *config_, void *dims_, const char *field, int *value); - void (*dims_get)(void *config_, void *dims_, const char *field, int *value); - acados_size_t (*model_calculate_size)(void *config, void *dims); - void *(*model_assign)(void *config, void *dims, void *raw_memory); - int (*model_set)(void *config_, void *dims_, void *model_, const char *field, void *value_); - acados_size_t (*opts_calculate_size)(void *config, void *dims); - void *(*opts_assign)(void *config, void *dims, void *raw_memory); - void (*opts_initialize_default)(void *config, void *dims, void *opts); - void (*opts_update)(void *config, void *dims, void *opts); - void (*opts_set)(void *config, void *opts, const char *field, void *value); - acados_size_t (*memory_calculate_size)(void *config, void *dims, void *opts); - double *(*memory_get_fun_ptr)(void *memory); - struct blasfeo_dvec *(*memory_get_grad_ptr)(void *memory); - void (*memory_set_ux_ptr)(struct blasfeo_dvec *ux, void *memory); - void (*memory_set_tmp_ux_ptr)(struct blasfeo_dvec *tmp_ux, void *memory); - void (*memory_set_z_alg_ptr)(struct blasfeo_dvec *z_alg, void *memory); - void (*memory_set_dzdux_tran_ptr)(struct blasfeo_dmat *dzdux, void *memory); - void (*memory_set_RSQrq_ptr)(struct blasfeo_dmat *RSQrq, void *memory); - void (*memory_set_Z_ptr)(struct blasfeo_dvec *Z, void *memory); - void *(*memory_assign)(void *config, void *dims, void *opts, void *raw_memory); - acados_size_t (*workspace_calculate_size)(void *config, void *dims, void *opts); - void (*initialize)(void *config_, void *dims, void *model_, void *opts_, void *mem_, void *work_); - - // computes the function value, gradient and hessian (approximation) of the cost function - void (*update_qp_matrices)(void *config_, void *dims, void *model_, void *opts_, void *mem_, void *work_); - // computes the cost function value (intended for globalization) - void (*compute_fun)(void *config_, void *dims, void *model_, void *opts_, void *mem_, void *work_); - void (*config_initialize_default)(void *config); - void (*precompute)(void *config_, void *dims_, void *model_, void *opts_, void *memory_, void *work_); - -} ocp_nlp_cost_config; - -// -acados_size_t ocp_nlp_cost_config_calculate_size(); -// -ocp_nlp_cost_config *ocp_nlp_cost_config_assign(void *raw_memory); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_NLP_OCP_NLP_COST_COMMON_H_ -/// @} -/// @} diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_cost_conl.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_cost_conl.h deleted file mode 100644 index 2eb3f5d127..0000000000 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_cost_conl.h +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -/// \addtogroup ocp_nlp -/// @{ -/// \addtogroup ocp_nlp_cost ocp_nlp_cost -/// @{ -/// \addtogroup ocp_nlp_cost_conl ocp_nlp_cost_conl -/// \brief This module implements convex-over-nonlinear costs of the form -/// \f$\min_{x,u,z} \psi(y(x,u,z,p) - y_{\text{ref}}, p)\f$, - - -#ifndef ACADOS_OCP_NLP_OCP_NLP_COST_CONL_H_ -#define ACADOS_OCP_NLP_OCP_NLP_COST_CONL_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// blasfeo -#include "blasfeo/include/blasfeo_common.h" - -// acados -#include "acados/ocp_nlp/ocp_nlp_cost_common.h" -#include "acados/utils/external_function_generic.h" -#include "acados/utils/types.h" - - - -/************************************************ - * dims - ************************************************/ - -typedef struct -{ - int nx; // number of states - int nz; // number of algebraic variables - int nu; // number of inputs - int ny; // number of outputs - int ns; // number of slacks -} ocp_nlp_cost_conl_dims; - -// -acados_size_t ocp_nlp_cost_conl_dims_calculate_size(void *config); -// -void *ocp_nlp_cost_conl_dims_assign(void *config, void *raw_memory); -// -void ocp_nlp_cost_conl_dims_initialize(void *config, void *dims, int nx, int nu, int ny, int ns, int nz); -// -void ocp_nlp_cost_conl_dims_set(void *config_, void *dims_, const char *field, int* value); -// -void ocp_nlp_cost_conl_dims_get(void *config_, void *dims_, const char *field, int* value); - - - -/************************************************ - * model - ************************************************/ - -typedef struct -{ - // slack penalty has the form z^T * s + .5 * s^T * Z * s - external_function_generic *conl_cost_fun; - external_function_generic *conl_cost_fun_jac_hess; - struct blasfeo_dvec y_ref; - struct blasfeo_dvec Z; // diagonal Hessian of slacks as vector - struct blasfeo_dvec z; // gradient of slacks as vector - double scaling; -} ocp_nlp_cost_conl_model; - -// -acados_size_t ocp_nlp_cost_conl_model_calculate_size(void *config, void *dims); -// -void *ocp_nlp_cost_conl_model_assign(void *config, void *dims, void *raw_memory); -// -int ocp_nlp_cost_conl_model_set(void *config_, void *dims_, void *model_, const char *field, void *value_); - - - -/************************************************ - * options - ************************************************/ - -typedef struct -{ - bool gauss_newton_hess; // dummy options, we always use a gauss-newton hessian -} ocp_nlp_cost_conl_opts; - -// -acados_size_t ocp_nlp_cost_conl_opts_calculate_size(void *config, void *dims); -// -void *ocp_nlp_cost_conl_opts_assign(void *config, void *dims, void *raw_memory); -// -void ocp_nlp_cost_conl_opts_initialize_default(void *config, void *dims, void *opts); -// -void ocp_nlp_cost_conl_opts_update(void *config, void *dims, void *opts); -// -void ocp_nlp_cost_conl_opts_set(void *config, void *opts, const char *field, void *value); - - - -/************************************************ - * memory - ************************************************/ -typedef struct -{ - struct blasfeo_dvec grad; // gradient of cost function - struct blasfeo_dvec *ux; // pointer to ux in nlp_out - struct blasfeo_dvec *tmp_ux; // pointer to ux in tmp_nlp_out - struct blasfeo_dmat *RSQrq; // pointer to RSQrq in qp_in - struct blasfeo_dvec *Z; // pointer to Z in qp_in - struct blasfeo_dvec *z_alg; ///< pointer to z in sim_out - struct blasfeo_dmat *dzdux_tran; ///< pointer to sensitivity of a wrt ux in sim_out - double fun; ///< value of the cost function -} ocp_nlp_cost_conl_memory; - -// -acados_size_t ocp_nlp_cost_conl_memory_calculate_size(void *config, void *dims, void *opts); -// -void *ocp_nlp_cost_conl_memory_assign(void *config, void *dims, void *opts, void *raw_memory); -// -double *ocp_nlp_cost_conl_memory_get_fun_ptr(void *memory_); -// -struct blasfeo_dvec *ocp_nlp_cost_conl_memory_get_grad_ptr(void *memory_); -// -void ocp_nlp_cost_conl_memory_set_RSQrq_ptr(struct blasfeo_dmat *RSQrq, void *memory); -// -void ocp_nlp_cost_conl_memory_set_Z_ptr(struct blasfeo_dvec *Z, void *memory); -// -void ocp_nlp_cost_conl_memory_set_ux_ptr(struct blasfeo_dvec *ux, void *memory_); -// -void ocp_nlp_cost_conl_memory_set_tmp_ux_ptr(struct blasfeo_dvec *tmp_ux, void *memory_); -// -void ocp_nlp_cost_conl_memory_set_z_alg_ptr(struct blasfeo_dvec *z_alg, void *memory_); -// -void ocp_nlp_cost_conl_memory_set_dzdux_tran_ptr(struct blasfeo_dmat *dzdux_tran, void *memory_); - -/************************************************ - * workspace - ************************************************/ - -typedef struct -{ - struct blasfeo_dmat W; // hessian of outer loss function - struct blasfeo_dmat W_chol; // cholesky factor of hessian of outer loss function - struct blasfeo_dmat Jt_ux; // jacobian of inner residual function - struct blasfeo_dmat Jt_ux_tilde; // jacobian of inner residual function plus gradient contribution of algebraic variables - struct blasfeo_dmat Jt_z; // jacobian of inner residual function wrt algebraic variables - struct blasfeo_dmat tmp_nv_ny; - struct blasfeo_dvec tmp_ny; - struct blasfeo_dvec tmp_2ns; -} ocp_nlp_cost_conl_workspace; - -// -acados_size_t ocp_nlp_cost_conl_workspace_calculate_size(void *config, void *dims, void *opts); - -/************************************************ - * functions - ************************************************/ - -// -void ocp_nlp_cost_conl_precompute(void *config_, void *dims_, void *model_, void *opts_, void *memory_, void *work_); -// -void ocp_nlp_cost_conl_config_initialize_default(void *config); -// -void ocp_nlp_cost_conl_initialize(void *config_, void *dims, void *model_, void *opts_, void *mem_, void *work_); -// -void ocp_nlp_cost_conl_update_qp_matrices(void *config_, void *dims, void *model_, void *opts_, void *memory_, void *work_); -// -void ocp_nlp_cost_conl_compute_fun(void *config_, void *dims, void *model_, void *opts_, void *memory_, void *work_); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_NLP_OCP_NLP_COST_CONL_H_ -/// @} -/// @} -/// @} diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_cost_external.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_cost_external.h deleted file mode 100644 index 78958270de..0000000000 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_cost_external.h +++ /dev/null @@ -1,187 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -#ifndef ACADOS_OCP_NLP_OCP_NLP_COST_EXTERNAL_H_ -#define ACADOS_OCP_NLP_OCP_NLP_COST_EXTERNAL_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// blasfeo -#include "blasfeo/include/blasfeo_common.h" - -// acados -#include "acados/ocp_nlp/ocp_nlp_cost_common.h" -#include "acados/utils/external_function_generic.h" -#include "acados/utils/types.h" - -/************************************************ - * dims - ************************************************/ - -typedef struct -{ - int nx; // number of states - int nz; // number of algebraic variables - int nu; // number of inputs - int ns; // number of slacks -} ocp_nlp_cost_external_dims; - -// -acados_size_t ocp_nlp_cost_external_dims_calculate_size(void *config); -// -void *ocp_nlp_cost_external_dims_assign(void *config, void *raw_memory); -// -void ocp_nlp_cost_external_dims_set(void *config_, void *dims_, const char *field, int* value); -// -void ocp_nlp_cost_external_dims_get(void *config_, void *dims_, const char *field, int* value); - -/************************************************ - * model - ************************************************/ - -typedef struct -{ - external_function_generic *ext_cost_fun; // function - external_function_generic *ext_cost_fun_jac_hess; // function, gradient and hessian - external_function_generic *ext_cost_fun_jac; // function, gradient - struct blasfeo_dvec Z; - struct blasfeo_dvec z; - struct blasfeo_dmat numerical_hessian; // custom hessian approximation - double scaling; -} ocp_nlp_cost_external_model; - -// -acados_size_t ocp_nlp_cost_external_model_calculate_size(void *config, void *dims); -// -void *ocp_nlp_cost_external_model_assign(void *config, void *dims, void *raw_memory); - - - -/************************************************ - * options - ************************************************/ - -typedef struct -{ - int use_numerical_hessian; // > 0 indicating custom hessian is used instead of CasADi evaluation -} ocp_nlp_cost_external_opts; - -// -acados_size_t ocp_nlp_cost_external_opts_calculate_size(void *config, void *dims); -// -void *ocp_nlp_cost_external_opts_assign(void *config, void *dims, void *raw_memory); -// -void ocp_nlp_cost_external_opts_initialize_default(void *config, void *dims, void *opts); -// -void ocp_nlp_cost_external_opts_update(void *config, void *dims, void *opts); -// -void ocp_nlp_cost_external_opts_set(void *config, void *opts, const char *field, void *value); - - - -/************************************************ - * memory - ************************************************/ - -typedef struct -{ - struct blasfeo_dvec grad; // gradient of cost function - struct blasfeo_dvec *ux; // pointer to ux in nlp_out - struct blasfeo_dvec *tmp_ux; // pointer to tmp_ux in nlp_out - struct blasfeo_dmat *RSQrq; // pointer to RSQrq in qp_in - struct blasfeo_dvec *Z; // pointer to Z in qp_in - struct blasfeo_dvec *z_alg; ///< pointer to z in sim_out - struct blasfeo_dmat *dzdux_tran; ///< pointer to sensitivity of a wrt ux in sim_out - double fun; ///< value of the cost function -} ocp_nlp_cost_external_memory; - -// -acados_size_t ocp_nlp_cost_external_memory_calculate_size(void *config, void *dims, void *opts); -// -void *ocp_nlp_cost_external_memory_assign(void *config, void *dims, void *opts, void *raw_memory); -// -double *ocp_nlp_cost_external_memory_get_fun_ptr(void *memory_); -// -struct blasfeo_dvec *ocp_nlp_cost_external_memory_get_grad_ptr(void *memory_); -// -void ocp_nlp_cost_external_memory_set_RSQrq_ptr(struct blasfeo_dmat *RSQrq, void *memory); -// -void ocp_nlp_cost_ls_memory_set_Z_ptr(struct blasfeo_dvec *Z, void *memory); -// -void ocp_nlp_cost_external_memory_set_ux_ptr(struct blasfeo_dvec *ux, void *memory_); -// -void ocp_nlp_cost_external_memory_set_tmp_ux_ptr(struct blasfeo_dvec *tmp_ux, void *memory_); -// -void ocp_nlp_cost_external_memory_set_z_alg_ptr(struct blasfeo_dvec *z_alg, void *memory_); -// -void ocp_nlp_cost_external_memory_set_dzdux_tran_ptr(struct blasfeo_dmat *dzdux_tran, void *memory_); - -/************************************************ - * workspace - ************************************************/ - -typedef struct -{ - struct blasfeo_dmat tmp_nunx_nunx; - struct blasfeo_dmat tmp_nz_nz; - struct blasfeo_dmat tmp_nz_nunx; - struct blasfeo_dvec tmp_nunxnz; - struct blasfeo_dvec tmp_2ns; // temporary vector of dimension 2*ns -} ocp_nlp_cost_external_workspace; - -// -acados_size_t ocp_nlp_cost_external_workspace_calculate_size(void *config, void *dims, void *opts); - -/************************************************ - * functions - ************************************************/ - -// -void ocp_nlp_cost_external_precompute(void *config_, void *dims_, void *model_, void *opts_, void *memory_, void *work_); -// -void ocp_nlp_cost_external_config_initialize_default(void *config); -// -void ocp_nlp_cost_external_initialize(void *config_, void *dims, void *model_, - void *opts_, void *mem_, void *work_); -// -void ocp_nlp_cost_external_update_qp_matrices(void *config_, void *dims, void *model_, - void *opts_, void *memory_, void *work_); -// -void ocp_nlp_cost_external_compute_fun(void *config_, void *dims, void *model_, - void *opts_, void *memory_, void *work_); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_NLP_OCP_NLP_COST_EXTERNAL_H_ diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_cost_ls.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_cost_ls.h deleted file mode 100644 index 801e9a5b87..0000000000 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_cost_ls.h +++ /dev/null @@ -1,243 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -/// \addtogroup ocp_nlp -/// @{ -/// \addtogroup ocp_nlp_cost ocp_nlp_cost -/// @{ -/// \addtogroup ocp_nlp_cost_ls ocp_nlp_cost_ls -/// \brief This module implements linear-least squares costs of the form -/// \f$\min_{x,u,z} \| V_x x + V_u u + V_z z - y_{\text{ref}}\|_W^2\f$. -/// @{ - - - -#ifndef ACADOS_OCP_NLP_OCP_NLP_COST_LS_H_ -#define ACADOS_OCP_NLP_OCP_NLP_COST_LS_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// blasfeo -#include "blasfeo/include/blasfeo_common.h" - -// acados -#include "acados/ocp_nlp/ocp_nlp_cost_common.h" -#include "acados/utils/external_function_generic.h" -#include "acados/utils/types.h" - - -//////////////////////////////////////////////////////////////////////////////// -// dims // -//////////////////////////////////////////////////////////////////////////////// - -typedef struct -{ - int nx; // number of states - int nz; // number of algebraic variables - int nu; // number of inputs - int ny; // number of outputs - int ns; // number of slacks -} ocp_nlp_cost_ls_dims; - - -/// Calculate the size of the ocp_nlp_cost_ls_dims struct -/// -/// \param[in] config_ structure containing configuration of ocp_nlp_cost -/// module -/// \param[out] [] -/// \return \c size of ocp_nlp_dims struct -acados_size_t ocp_nlp_cost_ls_dims_calculate_size(void *config); - - -/// Assign memory pointed to by raw_memory to ocp_nlp-cost_ls dims struct -/// -/// \param[in] config structure containing configuration of ocp_nlp_cost -/// module -/// \param[in] raw_memory pointer to memory location -/// \param[out] [] -/// \return dims -void *ocp_nlp_cost_ls_dims_assign(void *config, void *raw_memory); -// -void ocp_nlp_cost_ls_dims_set(void *config_, void *dims_, const char *field, int* value); -// -void ocp_nlp_cost_ls_dims_get(void *config_, void *dims_, const char *field, int* value); - - -//////////////////////////////////////////////////////////////////////////////// -// model // -//////////////////////////////////////////////////////////////////////////////// - - -/// structure containing the data describing the linear least-square cost -typedef struct -{ - // slack penalty has the form z^T * s + .5 * s^T * Z * s - struct blasfeo_dmat Cyt; ///< output matrix: Cy * [u,x] = y; in transposed form - struct blasfeo_dmat Vz; ///< Vz in ls cost Vx*x + Vu*u + Vz*z - struct blasfeo_dmat W; ///< ls norm corresponding to this matrix - struct blasfeo_dvec y_ref; ///< yref - struct blasfeo_dvec Z; ///< diagonal Hessian of slacks as vector (lower and upper) - struct blasfeo_dvec z; ///< gradient of slacks as vector (lower and upper) - double scaling; - int W_changed; ///< flag indicating whether W has changed and needs to be refactorized - int Cyt_or_scaling_changed; ///< flag indicating whether Cyt or scaling has changed and Hessian needs to be recomputed -} ocp_nlp_cost_ls_model; - -// -acados_size_t ocp_nlp_cost_ls_model_calculate_size(void *config, void *dims); -// -void *ocp_nlp_cost_ls_model_assign(void *config, void *dims, void *raw_memory); -// -int ocp_nlp_cost_ls_model_set(void *config_, void *dims_, void *model_, - const char *field, void *value_); - - - -//////////////////////////////////////////////////////////////////////////////// -// options // -//////////////////////////////////////////////////////////////////////////////// - - - -typedef struct -{ - int dummy; // struct can't be void -} ocp_nlp_cost_ls_opts; - -// -acados_size_t ocp_nlp_cost_ls_opts_calculate_size(void *config, void *dims); -// -void *ocp_nlp_cost_ls_opts_assign(void *config, void *dims, void *raw_memory); -// -void ocp_nlp_cost_ls_opts_initialize_default(void *config, void *dims, void *opts); -// -void ocp_nlp_cost_ls_opts_update(void *config, void *dims, void *opts); -// -void ocp_nlp_cost_ls_opts_set(void *config, void *opts, const char *field, void *value); - - - -//////////////////////////////////////////////////////////////////////////////// -// memory // -//////////////////////////////////////////////////////////////////////////////// - - - -/// structure containing the memory associated with cost_ls component -/// of the ocp_nlp module -typedef struct -{ - struct blasfeo_dmat hess; ///< hessian of cost function - struct blasfeo_dmat W_chol; ///< cholesky factor of weight matrix - struct blasfeo_dvec res; ///< ls residual r(x) - struct blasfeo_dvec grad; ///< gradient of cost function - struct blasfeo_dvec *ux; ///< pointer to ux in nlp_out - struct blasfeo_dvec *tmp_ux; ///< pointer to ux in tmp_nlp_out - struct blasfeo_dvec *z_alg; ///< pointer to z in sim_out - struct blasfeo_dmat *dzdux_tran; ///< pointer to sensitivity of a wrt ux in sim_out - struct blasfeo_dmat *RSQrq; ///< pointer to RSQrq in qp_in - struct blasfeo_dvec *Z; ///< pointer to Z in qp_in - double fun; ///< value of the cost function -} ocp_nlp_cost_ls_memory; - -// -acados_size_t ocp_nlp_cost_ls_memory_calculate_size(void *config, void *dims, void *opts); -// -void *ocp_nlp_cost_ls_memory_assign(void *config, void *dims, void *opts, void *raw_memory); -// -double *ocp_nlp_cost_ls_memory_get_fun_ptr(void *memory_); -// -struct blasfeo_dvec *ocp_nlp_cost_ls_memory_get_grad_ptr(void *memory_); -// -void ocp_nlp_cost_ls_memory_set_RSQrq_ptr(struct blasfeo_dmat *RSQrq, void *memory); -// -void ocp_nlp_cost_ls_memory_set_Z_ptr(struct blasfeo_dvec *Z, void *memory); -// -void ocp_nlp_cost_ls_memory_set_ux_ptr(struct blasfeo_dvec *ux, void *memory_); -// -void ocp_nlp_cost_ls_memory_set_tmp_ux_ptr(struct blasfeo_dvec *tmp_ux, void *memory_); -// -void ocp_nlp_cost_ls_memory_set_z_alg_ptr(struct blasfeo_dvec *z_alg, void *memory_); -// -void ocp_nlp_cost_ls_memory_set_dzdux_tran_ptr(struct blasfeo_dmat *dzdux_tran, void *memory_); - - - -//////////////////////////////////////////////////////////////////////////////// -// workspace // -//////////////////////////////////////////////////////////////////////////////// - - - -typedef struct -{ - struct blasfeo_dmat tmp_nv_ny; // temporary matrix of dimensions nv, ny - struct blasfeo_dmat Cyt_tilde; // updated Cyt (after z elimination) - struct blasfeo_dmat dzdux_tran; // derivatives of z wrt u and x (tran) - struct blasfeo_dvec tmp_ny; // temporary vector of dimension ny - struct blasfeo_dvec tmp_2ns; // temporary vector of dimension ny - struct blasfeo_dvec tmp_nz; // temporary vector of dimension nz - struct blasfeo_dvec y_ref_tilde; // updated y_ref (after z elimination) -} ocp_nlp_cost_ls_workspace; - -// -acados_size_t ocp_nlp_cost_ls_workspace_calculate_size(void *config, void *dims, void *opts); - - - -//////////////////////////////////////////////////////////////////////////////// -// functions // -//////////////////////////////////////////////////////////////////////////////// - - -// computations that are done once when solver is created -void ocp_nlp_cost_ls_precompute(void *config_, void *dims_, void *model_, void *opts_, void *memory_, void *work_); -// -void ocp_nlp_cost_ls_config_initialize_default(void *config); -// -void ocp_nlp_cost_ls_initialize(void *config_, void *dims, void *model_, void *opts_, - void *mem_, void *work_); -// -void ocp_nlp_cost_ls_update_qp_matrices(void *config_, void *dims, void *model_, - void *opts_, void *memory_, void *work_); -// -void ocp_nlp_cost_ls_compute_fun(void *config_, void *dims, void *model_, void *opts_, void *memory_, void *work_); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_NLP_OCP_NLP_COST_LS_H_ -/// @} -/// @} -/// @} diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_cost_nls.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_cost_nls.h deleted file mode 100644 index 5ec68cf580..0000000000 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_cost_nls.h +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -/// \addtogroup ocp_nlp -/// @{ -/// \addtogroup ocp_nlp_cost ocp_nlp_cost -/// @{ -/// \addtogroup ocp_nlp_cost_nls ocp_nlp_cost_nls -/// \brief This module implements nonlinear-least squares costs of the form -/// \f$\min_{x,u,z} \| y(x,u,z,p) - y_{\text{ref}} \|_W^2\f$, - -#ifndef ACADOS_OCP_NLP_OCP_NLP_COST_NLS_H_ -#define ACADOS_OCP_NLP_OCP_NLP_COST_NLS_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// blasfeo -#include "blasfeo/include/blasfeo_common.h" - -// acados -#include "acados/ocp_nlp/ocp_nlp_cost_common.h" -#include "acados/utils/external_function_generic.h" -#include "acados/utils/types.h" - - - -/************************************************ - * dims - ************************************************/ - -typedef struct -{ - int nx; // number of states - int nz; // number of algebraic variables - int nu; // number of inputs - int ny; // number of outputs - int ns; // number of slacks -} ocp_nlp_cost_nls_dims; - -// -acados_size_t ocp_nlp_cost_nls_dims_calculate_size(void *config); -// -void *ocp_nlp_cost_nls_dims_assign(void *config, void *raw_memory); -// -void ocp_nlp_cost_nls_dims_set(void *config_, void *dims_, const char *field, int* value); -// -void ocp_nlp_cost_nls_dims_get(void *config_, void *dims_, const char *field, int* value); - - - -/************************************************ - * model - ************************************************/ - -typedef struct -{ - // nonliner function nls_y(x,u) replaces Cy * [x,u] in ls_cost - // slack penalty has the form z^T * s + .5 * s^T * Z * s - external_function_generic *nls_y_fun; // evaluation of nls function - external_function_generic *nls_y_fun_jac; // evaluation nls function and jacobian - external_function_generic *nls_y_hess; // hessian*seeds of nls residuals - struct blasfeo_dmat W; // - struct blasfeo_dvec y_ref; - struct blasfeo_dvec Z; // diagonal Hessian of slacks as vector - struct blasfeo_dvec z; // gradient of slacks as vector - double scaling; - int W_changed; ///< flag indicating whether W has changed and needs to be refactorized -} ocp_nlp_cost_nls_model; - -// -acados_size_t ocp_nlp_cost_nls_model_calculate_size(void *config, void *dims); -// -void *ocp_nlp_cost_nls_model_assign(void *config, void *dims, void *raw_memory); -// -int ocp_nlp_cost_nls_model_set(void *config_, void *dims_, void *model_, const char *field, void *value_); - - - -/************************************************ - * options - ************************************************/ - -typedef struct -{ - bool gauss_newton_hess; // gauss-newton hessian approximation -} ocp_nlp_cost_nls_opts; - -// -acados_size_t ocp_nlp_cost_nls_opts_calculate_size(void *config, void *dims); -// -void *ocp_nlp_cost_nls_opts_assign(void *config, void *dims, void *raw_memory); -// -void ocp_nlp_cost_nls_opts_initialize_default(void *config, void *dims, void *opts); -// -void ocp_nlp_cost_nls_opts_update(void *config, void *dims, void *opts); -// -void ocp_nlp_cost_nls_opts_set(void *config, void *opts, const char *field, void *value); - - - -/************************************************ - * memory - ************************************************/ - -typedef struct -{ - struct blasfeo_dmat W_chol; // cholesky factor of weight matrix - struct blasfeo_dmat Jt; // jacobian of nls fun - struct blasfeo_dvec res; // nls residual r(x) - struct blasfeo_dvec grad; // gradient of cost function - struct blasfeo_dvec *ux; // pointer to ux in nlp_out - struct blasfeo_dvec *tmp_ux; // pointer to ux in tmp_nlp_out - struct blasfeo_dmat *RSQrq; // pointer to RSQrq in qp_in - struct blasfeo_dvec *Z; // pointer to Z in qp_in - struct blasfeo_dvec *z_alg; ///< pointer to z in sim_out - struct blasfeo_dmat *dzdux_tran; ///< pointer to sensitivity of a wrt ux in sim_out - double fun; ///< value of the cost function -} ocp_nlp_cost_nls_memory; - -// -acados_size_t ocp_nlp_cost_nls_memory_calculate_size(void *config, void *dims, void *opts); -// -void *ocp_nlp_cost_nls_memory_assign(void *config, void *dims, void *opts, void *raw_memory); -// -double *ocp_nlp_cost_nls_memory_get_fun_ptr(void *memory_); -// -struct blasfeo_dvec *ocp_nlp_cost_nls_memory_get_grad_ptr(void *memory_); -// -void ocp_nlp_cost_nls_memory_set_RSQrq_ptr(struct blasfeo_dmat *RSQrq, void *memory); -// -void ocp_nlp_cost_nls_memory_set_Z_ptr(struct blasfeo_dvec *Z, void *memory); -// -void ocp_nlp_cost_nls_memory_set_ux_ptr(struct blasfeo_dvec *ux, void *memory_); -// -void ocp_nlp_cost_nls_memory_set_tmp_ux_ptr(struct blasfeo_dvec *tmp_ux, void *memory_); -// -void ocp_nlp_cost_nls_memory_set_z_alg_ptr(struct blasfeo_dvec *z_alg, void *memory_); -// -void ocp_nlp_cost_nls_memory_set_dzdux_tran_ptr(struct blasfeo_dmat *dzdux_tran, void *memory_); - -/************************************************ - * workspace - ************************************************/ - -typedef struct -{ - struct blasfeo_dmat tmp_nv_ny; - struct blasfeo_dmat tmp_nv_nv; - struct blasfeo_dmat Vz; - struct blasfeo_dmat Cyt_tilde; - struct blasfeo_dvec tmp_ny; - struct blasfeo_dvec tmp_2ns; - struct blasfeo_dvec tmp_nz; -} ocp_nlp_cost_nls_workspace; - -// -acados_size_t ocp_nlp_cost_nls_workspace_calculate_size(void *config, void *dims, void *opts); - -/************************************************ - * functions - ************************************************/ - -// -void ocp_nlp_cost_nls_precompute(void *config_, void *dims_, void *model_, void *opts_, void *memory_, void *work_); -// -void ocp_nlp_cost_nls_config_initialize_default(void *config); -// -void ocp_nlp_cost_nls_initialize(void *config_, void *dims, void *model_, void *opts_, void *mem_, void *work_); -// -void ocp_nlp_cost_nls_update_qp_matrices(void *config_, void *dims, void *model_, void *opts_, void *memory_, void *work_); -// -void ocp_nlp_cost_nls_compute_fun(void *config_, void *dims, void *model_, void *opts_, void *memory_, void *work_); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_NLP_OCP_NLP_COST_NLS_H_ -/// @} -/// @} -/// @} diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_dynamics_common.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_dynamics_common.h deleted file mode 100644 index 43fe71b12f..0000000000 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_dynamics_common.h +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -/// \ingroup ocp_nlp -/// @{ - -/// \defgroup ocp_nlp_dynamics ocp_nlp_dynamics -/// @{ - -#ifndef ACADOS_OCP_NLP_OCP_NLP_DYNAMICS_COMMON_H_ -#define ACADOS_OCP_NLP_OCP_NLP_DYNAMICS_COMMON_H_ - -#ifdef __cplusplus -extern "C" { -#endif - - - -// blasfeo -#include "blasfeo/include/blasfeo_common.h" - -// acados -#include "acados/sim/sim_common.h" -#include "acados/utils/external_function_generic.h" -#include "acados/utils/types.h" - - - -/************************************************ - * config - ************************************************/ - -typedef struct -{ - void (*config_initialize_default)(void *config); - sim_config *sim_solver; - /* dims */ - acados_size_t (*dims_calculate_size)(void *config); - void *(*dims_assign)(void *config, void *raw_memory); - void (*dims_set)(void *config_, void *dims_, const char *field, int *value); - void (*dims_get)(void *config_, void *dims_, const char *field, int* value); - /* model */ - acados_size_t (*model_calculate_size)(void *config, void *dims); - void *(*model_assign)(void *config, void *dims, void *raw_memory); - void (*model_set)(void *config_, void *dims_, void *model_, const char *field, void *value_); - /* opts */ - acados_size_t (*opts_calculate_size)(void *config, void *dims); - void *(*opts_assign)(void *config, void *dims, void *raw_memory); - void (*opts_initialize_default)(void *config, void *dims, void *opts); - void (*opts_set)(void *config_, void *opts_, const char *field, void *value); - void (*opts_update)(void *config, void *dims, void *opts); - /* memory */ - acados_size_t (*memory_calculate_size)(void *config, void *dims, void *opts); - void *(*memory_assign)(void *config, void *dims, void *opts, void *raw_memory); - // get shooting node gap x_next(x_n, u_n) - x_{n+1} - struct blasfeo_dvec *(*memory_get_fun_ptr)(void *memory_); - struct blasfeo_dvec *(*memory_get_adj_ptr)(void *memory_); - void (*memory_set_ux_ptr)(struct blasfeo_dvec *ux, void *memory_); - void (*memory_set_tmp_ux_ptr)(struct blasfeo_dvec *tmp_ux, void *memory_); - void (*memory_set_ux1_ptr)(struct blasfeo_dvec *ux1, void *memory_); - void (*memory_set_tmp_ux1_ptr)(struct blasfeo_dvec *tmp_ux1, void *memory_); - void (*memory_set_pi_ptr)(struct blasfeo_dvec *pi, void *memory_); - void (*memory_set_tmp_pi_ptr)(struct blasfeo_dvec *tmp_pi, void *memory_); - void (*memory_set_BAbt_ptr)(struct blasfeo_dmat *BAbt, void *memory_); - void (*memory_set_RSQrq_ptr)(struct blasfeo_dmat *RSQrq, void *memory_); - void (*memory_set_dzduxt_ptr)(struct blasfeo_dmat *mat, void *memory_); - void (*memory_set_sim_guess_ptr)(struct blasfeo_dvec *vec, bool *bool_ptr, void *memory_); - void (*memory_set_z_alg_ptr)(struct blasfeo_dvec *vec, void *memory_); - void (*memory_get)(void *config, void *dims, void *mem, const char *field, void* value); - /* workspace */ - acados_size_t (*workspace_calculate_size)(void *config, void *dims, void *opts); - void (*initialize)(void *config_, void *dims, void *model_, void *opts_, void *mem_, void *work_); - void (*update_qp_matrices)(void *config_, void *dims, void *model_, void *opts_, void *mem_, void *work_); - void (*compute_fun)(void *config_, void *dims, void *model_, void *opts_, void *mem_, void *work_); - int (*precompute)(void *config_, void *dims, void *model_, void *opts_, void *mem_, void *work_); -} ocp_nlp_dynamics_config; - -// -acados_size_t ocp_nlp_dynamics_config_calculate_size(); -// -ocp_nlp_dynamics_config *ocp_nlp_dynamics_config_assign(void *raw_memory); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_NLP_OCP_NLP_DYNAMICS_COMMON_H_ -/// @} -/// @} diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_dynamics_cont.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_dynamics_cont.h deleted file mode 100644 index 3afdc9f4ed..0000000000 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_dynamics_cont.h +++ /dev/null @@ -1,209 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -/// \addtogroup ocp_nlp -/// @{ -/// \addtogroup ocp_nlp_dynamics -/// @{ - -#ifndef ACADOS_OCP_NLP_OCP_NLP_DYNAMICS_CONT_H_ -#define ACADOS_OCP_NLP_OCP_NLP_DYNAMICS_CONT_H_ - -#ifdef __cplusplus -extern "C" { -#endif - - - -// blasfeo -#include "blasfeo/include/blasfeo_common.h" - -// acados -#include "acados/ocp_nlp/ocp_nlp_dynamics_common.h" -#include "acados/utils/external_function_generic.h" -#include "acados/utils/types.h" -#include "acados_c/sim_interface.h" - - - -/************************************************ - * dims - ************************************************/ - -typedef struct -{ - void *sim; - int nx; // number of states at the current stage - int nz; // number of algebraic states at the current stage - int nu; // number of inputs at the current stage - int nx1; // number of states at the next stage - int nu1; // number of inputes at the next stage -} ocp_nlp_dynamics_cont_dims; - -// -acados_size_t ocp_nlp_dynamics_cont_dims_calculate_size(void *config); -// -void *ocp_nlp_dynamics_cont_dims_assign(void *config, void *raw_memory); -// -void ocp_nlp_dynamics_cont_dims_set(void *config_, void *dims_, const char *field, int* value); - -/************************************************ - * options - ************************************************/ - -typedef struct -{ - void *sim_solver; - int compute_adj; - int compute_hess; -} ocp_nlp_dynamics_cont_opts; - -// -acados_size_t ocp_nlp_dynamics_cont_opts_calculate_size(void *config, void *dims); -// -void *ocp_nlp_dynamics_cont_opts_assign(void *config, void *dims, void *raw_memory); -// -void ocp_nlp_dynamics_cont_opts_initialize_default(void *config, void *dims, void *opts); -// -void ocp_nlp_dynamics_cont_opts_update(void *config, void *dims, void *opts); -// -void ocp_nlp_dynamics_cont_opts_set(void *config, void *opts, const char *field, void* value); - - - -/************************************************ - * memory - ************************************************/ - -typedef struct -{ - struct blasfeo_dvec fun; - struct blasfeo_dvec adj; - struct blasfeo_dvec *ux; // pointer to ux in nlp_out at current stage - struct blasfeo_dvec *tmp_ux; // pointer to ux in tmp_nlp_out at current stage - struct blasfeo_dvec *ux1; // pointer to ux in nlp_out at next stage - struct blasfeo_dvec *tmp_ux1; // pointer to ux in tmp_nlp_out at next stage - struct blasfeo_dvec *pi; // pointer to pi in nlp_out at current stage - struct blasfeo_dvec *tmp_pi; // pointer to pi in tmp_nlp_out at current stage - struct blasfeo_dmat *BAbt; // pointer to BAbt in qp_in - struct blasfeo_dmat *RSQrq; // pointer to RSQrq in qp_in - struct blasfeo_dvec *z_alg; // pointer to output z at t = 0 - bool *set_sim_guess; // indicate if initialization for integrator is set from outside - struct blasfeo_dvec *sim_guess; // initializations for integrator - // struct blasfeo_dvec *z; // pointer to (input) z in nlp_out at current stage - struct blasfeo_dmat *dzduxt; // pointer to dzdux transposed - void *sim_solver; // sim solver memory -} ocp_nlp_dynamics_cont_memory; - -// -acados_size_t ocp_nlp_dynamics_cont_memory_calculate_size(void *config, void *dims, void *opts); -// -void *ocp_nlp_dynamics_cont_memory_assign(void *config, void *dims, void *opts, void *raw_memory); -// -struct blasfeo_dvec *ocp_nlp_dynamics_cont_memory_get_fun_ptr(void *memory); -// -struct blasfeo_dvec *ocp_nlp_dynamics_cont_memory_get_adj_ptr(void *memory); -// -void ocp_nlp_dynamics_cont_memory_set_ux_ptr(struct blasfeo_dvec *ux, void *memory); -// -void ocp_nlp_dynamics_cont_memory_set_tmp_ux_ptr(struct blasfeo_dvec *tmp_ux, void *memory); -// -void ocp_nlp_dynamics_cont_memory_set_ux1_ptr(struct blasfeo_dvec *ux1, void *memory); -// -void ocp_nlp_dynamics_cont_memory_set_tmp_ux1_ptr(struct blasfeo_dvec *tmp_ux1, void *memory); -// -void ocp_nlp_dynamics_cont_memory_set_pi_ptr(struct blasfeo_dvec *pi, void *memory); -// -void ocp_nlp_dynamics_cont_memory_set_tmp_pi_ptr(struct blasfeo_dvec *tmp_pi, void *memory); -// -void ocp_nlp_dynamics_cont_memory_set_BAbt_ptr(struct blasfeo_dmat *BAbt, void *memory); - - - -/************************************************ - * workspace - ************************************************/ - -typedef struct -{ - struct blasfeo_dmat hess; - sim_in *sim_in; - sim_out *sim_out; - void *sim_solver; // sim solver workspace -} ocp_nlp_dynamics_cont_workspace; - -acados_size_t ocp_nlp_dynamics_cont_workspace_calculate_size(void *config, void *dims, void *opts); - - - -/************************************************ - * model - ************************************************/ - -typedef struct -{ - void *sim_model; - // double *state_transition; // TODO - double T; // simulation time -} ocp_nlp_dynamics_cont_model; - -// -acados_size_t ocp_nlp_dynamics_cont_model_calculate_size(void *config, void *dims); -// -void *ocp_nlp_dynamics_cont_model_assign(void *config, void *dims, void *raw_memory); -// -void ocp_nlp_dynamics_cont_model_set(void *config_, void *dims_, void *model_, const char *field, void *value); - - - -/************************************************ - * functions - ************************************************/ - -// -void ocp_nlp_dynamics_cont_config_initialize_default(void *config); -// -void ocp_nlp_dynamics_cont_initialize(void *config_, void *dims, void *model_, void *opts, void *mem, void *work_); -// -void ocp_nlp_dynamics_cont_update_qp_matrices(void *config_, void *dims, void *model_, void *opts, void *mem, void *work_); -// -void ocp_nlp_dynamics_cont_compute_fun(void *config_, void *dims, void *model_, void *opts, void *mem, void *work_); -// -int ocp_nlp_dynamics_cont_precompute(void *config_, void *dims, void *model_, void *opts_, void *mem_, void *work_); - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_NLP_OCP_NLP_DYNAMICS_CONT_H_ -/// @} -/// @} diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_dynamics_disc.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_dynamics_disc.h deleted file mode 100644 index 6ea26a7010..0000000000 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_dynamics_disc.h +++ /dev/null @@ -1,192 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -/// \addtogroup ocp_nlp -/// @{ -/// \addtogroup ocp_nlp_dynamics -/// @{ - -#ifndef ACADOS_OCP_NLP_OCP_NLP_DYNAMICS_DISC_H_ -#define ACADOS_OCP_NLP_OCP_NLP_DYNAMICS_DISC_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// blasfeo -#include "blasfeo/include/blasfeo_common.h" - -// acados -#include "acados/ocp_nlp/ocp_nlp_dynamics_common.h" -#include "acados/utils/external_function_generic.h" -#include "acados/utils/types.h" - -/************************************************ - * dims - ************************************************/ - -typedef struct -{ - int nx; // number of states at the current stage - int nu; // number of inputs at the current stage - int nx1; // number of states at the next stage - int nu1; // number of inputes at the next stage -} ocp_nlp_dynamics_disc_dims; - -// -acados_size_t ocp_nlp_dynamics_disc_dims_calculate_size(void *config); -// -void *ocp_nlp_dynamics_disc_dims_assign(void *config, void *raw_memory); -// -void ocp_nlp_dynamics_disc_dims_set(void *config_, void *dims_, const char *dim, int* value); - - -/************************************************ - * options - ************************************************/ - -typedef struct -{ - int compute_adj; - int compute_hess; -} ocp_nlp_dynamics_disc_opts; - -// -acados_size_t ocp_nlp_dynamics_disc_opts_calculate_size(void *config, void *dims); -// -void *ocp_nlp_dynamics_disc_opts_assign(void *config, void *dims, void *raw_memory); -// -void ocp_nlp_dynamics_disc_opts_initialize_default(void *config, void *dims, void *opts); -// -void ocp_nlp_dynamics_disc_opts_update(void *config, void *dims, void *opts); -// -int ocp_nlp_dynamics_disc_precompute(void *config_, void *dims, void *model_, void *opts_, - void *mem_, void *work_); - - -/************************************************ - * memory - ************************************************/ - -typedef struct -{ - struct blasfeo_dvec fun; - struct blasfeo_dvec adj; - struct blasfeo_dvec *ux; // pointer to ux in nlp_out at current stage - struct blasfeo_dvec *tmp_ux; // pointer to ux in tmp_nlp_out at current stage - struct blasfeo_dvec *ux1; // pointer to ux in nlp_out at next stage - struct blasfeo_dvec *tmp_ux1;// pointer to ux in tmp_nlp_out at next stage - struct blasfeo_dvec *pi; // pointer to pi in nlp_out at current stage - struct blasfeo_dvec *tmp_pi; // pointer to pi in tmp_nlp_out at current stage - struct blasfeo_dmat *BAbt; // pointer to BAbt in qp_in - struct blasfeo_dmat *RSQrq; // pointer to RSQrq in qp_in -} ocp_nlp_dynamics_disc_memory; - -// -acados_size_t ocp_nlp_dynamics_disc_memory_calculate_size(void *config, void *dims, void *opts); -// -void *ocp_nlp_dynamics_disc_memory_assign(void *config, void *dims, void *opts, void *raw_memory); -// -struct blasfeo_dvec *ocp_nlp_dynamics_disc_memory_get_fun_ptr(void *memory); -// -struct blasfeo_dvec *ocp_nlp_dynamics_disc_memory_get_adj_ptr(void *memory); -// -void ocp_nlp_dynamics_disc_memory_set_ux_ptr(struct blasfeo_dvec *ux, void *memory); -// -void ocp_nlp_dynamics_disc_memory_set_tmp_ux_ptr(struct blasfeo_dvec *tmp_ux, void *memory); -// -void ocp_nlp_dynamics_disc_memory_set_ux1_ptr(struct blasfeo_dvec *ux1, void *memory); -// -void ocp_nlp_dynamics_disc_memory_set_tmp_ux1_ptr(struct blasfeo_dvec *tmp_ux1, void *memory); -// -void ocp_nlp_dynamics_disc_memory_set_pi_ptr(struct blasfeo_dvec *pi, void *memory); -// -void ocp_nlp_dynamics_disc_memory_set_tmp_pi_ptr(struct blasfeo_dvec *tmp_pi, void *memory); -// -void ocp_nlp_dynamics_disc_memory_set_BAbt_ptr(struct blasfeo_dmat *BAbt, void *memory); - - - -/************************************************ - * workspace - ************************************************/ - -typedef struct -{ - struct blasfeo_dmat tmp_nv_nv; -} ocp_nlp_dynamics_disc_workspace; - -acados_size_t ocp_nlp_dynamics_disc_workspace_calculate_size(void *config, void *dims, void *opts); - - - -/************************************************ - * model - ************************************************/ - -typedef struct -{ - external_function_generic *disc_dyn_fun; - external_function_generic *disc_dyn_fun_jac; - external_function_generic *disc_dyn_fun_jac_hess; -} ocp_nlp_dynamics_disc_model; - -// -acados_size_t ocp_nlp_dynamics_disc_model_calculate_size(void *config, void *dims); -// -void *ocp_nlp_dynamics_disc_model_assign(void *config, void *dims, void *raw_memory); -// -void ocp_nlp_dynamics_disc_model_set(void *config_, void *dims_, void *model_, const char *field, void *value); - - - -/************************************************ - * functions - ************************************************/ - -// -void ocp_nlp_dynamics_disc_config_initialize_default(void *config); -// -void ocp_nlp_dynamics_disc_initialize(void *config_, void *dims, void *model_, void *opts, void *mem, void *work_); -// -void ocp_nlp_dynamics_disc_update_qp_matrices(void *config_, void *dims, void *model_, void *opts, void *mem, void *work_); -// -void ocp_nlp_dynamics_disc_compute_fun(void *config_, void *dims, void *model_, void *opts, void *mem, void *work_); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_NLP_OCP_NLP_DYNAMICS_DISC_H_ -/// @} -/// @} diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_reg_common.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_reg_common.h deleted file mode 100644 index 9388f3fd24..0000000000 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_reg_common.h +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -/// \ingroup ocp_nlp -/// @{ - -/// \defgroup ocp_nlp_reg ocp_nlp_reg -/// @{ - -#ifndef ACADOS_OCP_NLP_OCP_NLP_REG_COMMON_H_ -#define ACADOS_OCP_NLP_OCP_NLP_REG_COMMON_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "acados/ocp_qp/ocp_qp_common.h" - - - -/* dims */ - -//typedef ocp_qp_dims ocp_nlp_reg_dims; -typedef struct -{ - int *nx; - int *nu; - int *nbu; - int *nbx; - int *ng; - int N; -} ocp_nlp_reg_dims; - -// -acados_size_t ocp_nlp_reg_dims_calculate_size(int N); -// -ocp_nlp_reg_dims *ocp_nlp_reg_dims_assign(int N, void *raw_memory); -// -void ocp_nlp_reg_dims_set(void *config_, ocp_nlp_reg_dims *dims, int stage, char *field, int* value); - - - -/* config */ - -typedef struct -{ - /* dims */ - acados_size_t (*dims_calculate_size)(int N); - ocp_nlp_reg_dims *(*dims_assign)(int N, void *raw_memory); - void (*dims_set)(void *config, ocp_nlp_reg_dims *dims, int stage, char *field, int *value); - /* opts */ - acados_size_t (*opts_calculate_size)(void); - void *(*opts_assign)(void *raw_memory); - void (*opts_initialize_default)(void *config, ocp_nlp_reg_dims *dims, void *opts); - void (*opts_set)(void *config, ocp_nlp_reg_dims *dims, void *opts, char *field, void* value); - /* memory */ - acados_size_t (*memory_calculate_size)(void *config, ocp_nlp_reg_dims *dims, void *opts); - void *(*memory_assign)(void *config, ocp_nlp_reg_dims *dims, void *opts, void *raw_memory); - void (*memory_set)(void *config, ocp_nlp_reg_dims *dims, void *memory, char *field, void* value); - void (*memory_set_RSQrq_ptr)(ocp_nlp_reg_dims *dims, struct blasfeo_dmat *mat, void *memory); - void (*memory_set_rq_ptr)(ocp_nlp_reg_dims *dims, struct blasfeo_dvec *vec, void *memory); - void (*memory_set_BAbt_ptr)(ocp_nlp_reg_dims *dims, struct blasfeo_dmat *mat, void *memory); - void (*memory_set_b_ptr)(ocp_nlp_reg_dims *dims, struct blasfeo_dvec *vec, void *memory); - void (*memory_set_idxb_ptr)(ocp_nlp_reg_dims *dims, int **idxb, void *memory); - void (*memory_set_DCt_ptr)(ocp_nlp_reg_dims *dims, struct blasfeo_dmat *mat, void *memory); - void (*memory_set_ux_ptr)(ocp_nlp_reg_dims *dims, struct blasfeo_dvec *vec, void *memory); - void (*memory_set_pi_ptr)(ocp_nlp_reg_dims *dims, struct blasfeo_dvec *vec, void *memory); - void (*memory_set_lam_ptr)(ocp_nlp_reg_dims *dims, struct blasfeo_dvec *vec, void *memory); - /* functions */ - void (*regularize_hessian)(void *config, ocp_nlp_reg_dims *dims, void *opts, void *memory); - void (*correct_dual_sol)(void *config, ocp_nlp_reg_dims *dims, void *opts, void *memory); -} ocp_nlp_reg_config; - -// -acados_size_t ocp_nlp_reg_config_calculate_size(void); -// -void *ocp_nlp_reg_config_assign(void *raw_memory); - - - -/* regularization help functions */ -void acados_reconstruct_A(int dim, double *A, double *V, double *d); -void acados_mirror(int dim, double *A, double *V, double *d, double *e, double epsilon); -void acados_project(int dim, double *A, double *V, double *d, double *e, double epsilon); - - - -#ifdef __cplusplus -} -#endif - -#endif // ACADOS_OCP_NLP_OCP_NLP_REG_COMMON_H_ -/// @} -/// @} diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_reg_convexify.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_reg_convexify.h deleted file mode 100644 index cb523525e1..0000000000 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_reg_convexify.h +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -/// \addtogroup ocp_nlp -/// @{ -/// \addtogroup ocp_nlp_reg -/// @{ - -#ifndef ACADOS_OCP_NLP_OCP_NLP_REG_CONVEXIFY_H_ -#define ACADOS_OCP_NLP_OCP_NLP_REG_CONVEXIFY_H_ - -#ifdef __cplusplus -extern "C" { -#endif - - - -// blasfeo -#include "blasfeo/include/blasfeo_common.h" - -// acados -#include "acados/ocp_nlp/ocp_nlp_reg_common.h" - - - -/************************************************ - * dims - ************************************************/ - -// use the functions in ocp_nlp_reg_common - -/************************************************ - * options - ************************************************/ - -typedef struct -{ - double delta; - double epsilon; -// double gamma; // 0.0 -} ocp_nlp_reg_convexify_opts; - -// -acados_size_t ocp_nlp_reg_convexify_opts_calculate_size(void); -// -void *ocp_nlp_reg_convexify_opts_assign(void *raw_memory); -// -void ocp_nlp_reg_convexify_opts_initialize_default(void *config_, ocp_nlp_reg_dims *dims, void *opts_); -// -void ocp_nlp_reg_convexify_opts_set(void *config_, ocp_nlp_reg_dims *dims, void *opts_, char *field, void* value); - - - -/************************************************ - * memory - ************************************************/ - -typedef struct { - double *R; - double *V; // TODO move to workspace - double *d; // TODO move to workspace - double *e; // TODO move to workspace - double *reg_hess; // TODO move to workspace - - struct blasfeo_dmat Q_tilde; - struct blasfeo_dmat Q_bar; - struct blasfeo_dmat BAQ; - struct blasfeo_dmat L; - struct blasfeo_dmat delta_eye; - struct blasfeo_dmat St_copy; - - struct blasfeo_dmat *original_RSQrq; - struct blasfeo_dmat tmp_RSQ; - - struct blasfeo_dvec tmp_nuxM; - struct blasfeo_dvec tmp_nbgM; - -// struct blasfeo_dvec grad; -// struct blasfeo_dvec b2; - - // giaf's - struct blasfeo_dmat **RSQrq; // pointer to RSQrq in qp_in - struct blasfeo_dvec **rq; // pointer to rq in qp_in - struct blasfeo_dmat **BAbt; // pointer to BAbt in qp_in - struct blasfeo_dvec **b; // pointer to b in qp_in - struct blasfeo_dmat **DCt; // pointer to DCt in qp_in - struct blasfeo_dvec **ux; // pointer to ux in qp_out - struct blasfeo_dvec **pi; // pointer to pi in qp_out - struct blasfeo_dvec **lam; // pointer to lam in qp_out - int **idxb; // pointer to idxb in qp_in - -} ocp_nlp_reg_convexify_memory; - -// -acados_size_t ocp_nlp_reg_convexify_calculate_memory_size(void *config, ocp_nlp_reg_dims *dims, void *opts); -// -void *ocp_nlp_reg_convexify_assign_memory(void *config, ocp_nlp_reg_dims *dims, void *opts, void *raw_memory); - -/************************************************ - * workspace - ************************************************/ - - // TODO - -/************************************************ - * functions - ************************************************/ - -// -void ocp_nlp_reg_convexify_config_initialize_default(ocp_nlp_reg_config *config); - -#ifdef __cplusplus -} -#endif - -#endif // ACADOS_OCP_NLP_OCP_NLP_REG_CONVEXIFY_H_ -/// @} -/// @} diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_reg_mirror.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_reg_mirror.h deleted file mode 100644 index 84a023cb69..0000000000 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_reg_mirror.h +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -/// \addtogroup ocp_nlp -/// @{ -/// \addtogroup ocp_nlp_reg -/// @{ - -#ifndef ACADOS_OCP_NLP_OCP_NLP_REG_MIRROR_H_ -#define ACADOS_OCP_NLP_OCP_NLP_REG_MIRROR_H_ - -#ifdef __cplusplus -extern "C" { -#endif - - - -// blasfeo -#include "blasfeo/include/blasfeo_common.h" - -// acados -#include "acados/ocp_nlp/ocp_nlp_reg_common.h" - - - -/************************************************ - * dims - ************************************************/ - -// use the functions in ocp_nlp_reg_common - -/************************************************ - * options - ************************************************/ - -typedef struct -{ - double epsilon; -} ocp_nlp_reg_mirror_opts; - -// -acados_size_t ocp_nlp_reg_mirror_opts_calculate_size(void); -// -void *ocp_nlp_reg_mirror_opts_assign(void *raw_memory); -// -void ocp_nlp_reg_mirror_opts_initialize_default(void *config_, ocp_nlp_reg_dims *dims, void *opts_); -// -void ocp_nlp_reg_mirror_opts_set(void *config_, ocp_nlp_reg_dims *dims, void *opts_, char *field, void* value); - - - -/************************************************ - * memory - ************************************************/ - -typedef struct -{ - double *reg_hess; // TODO move to workspace - double *V; // TODO move to workspace - double *d; // TODO move to workspace - double *e; // TODO move to workspace - - // giaf's - struct blasfeo_dmat **RSQrq; // pointer to RSQrq in qp_in -} ocp_nlp_reg_mirror_memory; - -// -acados_size_t ocp_nlp_reg_mirror_memory_calculate_size(void *config, ocp_nlp_reg_dims *dims, void *opts); -// -void *ocp_nlp_reg_mirror_memory_assign(void *config, ocp_nlp_reg_dims *dims, void *opts, void *raw_memory); - -/************************************************ - * workspace - ************************************************/ - - // TODO - -/************************************************ - * functions - ************************************************/ - -// -void ocp_nlp_reg_mirror_config_initialize_default(ocp_nlp_reg_config *config); - - - -#ifdef __cplusplus -} -#endif - -#endif // ACADOS_OCP_NLP_OCP_NLP_REG_MIRROR_H_ -/// @} -/// @} diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_reg_noreg.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_reg_noreg.h deleted file mode 100644 index b571f3bac1..0000000000 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_reg_noreg.h +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -/// \addtogroup ocp_nlp -/// @{ -/// \addtogroup ocp_nlp_reg -/// @{ - -#ifndef ACADOS_OCP_NLP_OCP_NLP_REG_NOREG_H_ -#define ACADOS_OCP_NLP_OCP_NLP_REG_NOREG_H_ - -#ifdef __cplusplus -extern "C" { -#endif - - - -// blasfeo -#include "blasfeo/include/blasfeo_common.h" - -// acados -#include "acados/ocp_nlp/ocp_nlp_reg_common.h" - - - -/************************************************ - * dims - ************************************************/ - -// use the functions in ocp_nlp_reg_common - - -/************************************************ - * options - ************************************************/ - -// -acados_size_t ocp_nlp_reg_noreg_opts_calculate_size(void); -// -void *ocp_nlp_reg_noreg_opts_assign(void *raw_memory); -// -void ocp_nlp_reg_noreg_opts_initialize_default(void *config_, ocp_nlp_reg_dims *dims, void *opts_); -// -void ocp_nlp_reg_noreg_opts_set(void *config_, ocp_nlp_reg_dims *dims, void *opts_, char *field, void* value); - - - -/************************************************ - * memory - ************************************************/ -// -acados_size_t ocp_nlp_reg_noreg_memory_calculate_size(void *config, ocp_nlp_reg_dims *dims, void *opts); -// -void *ocp_nlp_reg_noreg_memory_assign(void *config, ocp_nlp_reg_dims *dims, void *opts, void *raw_memory); - -/************************************************ - * workspace - ************************************************/ - -// not needed - -/************************************************ - * functions - ************************************************/ - -// -void ocp_nlp_reg_noreg_config_initialize_default(ocp_nlp_reg_config *config); - - - -#ifdef __cplusplus -} -#endif - -#endif // ACADOS_OCP_NLP_OCP_NLP_REG_NOREG_H_ - -/// @} -/// @} diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_reg_project.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_reg_project.h deleted file mode 100644 index 682ea206dc..0000000000 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_reg_project.h +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -/// \addtogroup ocp_nlp -/// @{ -/// \addtogroup ocp_nlp_reg -/// @{ - -#ifndef ACADOS_OCP_NLP_OCP_NLP_REG_PROJECT_H_ -#define ACADOS_OCP_NLP_OCP_NLP_REG_PROJECT_H_ - -#ifdef __cplusplus -extern "C" { -#endif - - - -// blasfeo -#include "blasfeo/include/blasfeo_common.h" - -// acados -#include "acados/ocp_nlp/ocp_nlp_reg_common.h" - - - -/************************************************ - * dims - ************************************************/ - -// use the functions in ocp_nlp_reg_common - -/************************************************ - * options - ************************************************/ - -typedef struct -{ - double epsilon; -} ocp_nlp_reg_project_opts; - -// -acados_size_t ocp_nlp_reg_project_opts_calculate_size(void); -// -void *ocp_nlp_reg_project_opts_assign(void *raw_memory); -// -void ocp_nlp_reg_project_opts_initialize_default(void *config_, ocp_nlp_reg_dims *dims, void *opts_); -// -void ocp_nlp_reg_project_opts_set(void *config_, ocp_nlp_reg_dims *dims, void *opts_, char *field, void* value); - - - -/************************************************ - * memory - ************************************************/ - -typedef struct -{ - double *reg_hess; // TODO move to workspace - double *V; // TODO move to workspace - double *d; // TODO move to workspace - double *e; // TODO move to workspace - - // giaf's - struct blasfeo_dmat **RSQrq; // pointer to RSQrq in qp_in -} ocp_nlp_reg_project_memory; - -// -acados_size_t ocp_nlp_reg_project_memory_calculate_size(void *config, ocp_nlp_reg_dims *dims, void *opts); -// -void *ocp_nlp_reg_project_memory_assign(void *config, ocp_nlp_reg_dims *dims, void *opts, void *raw_memory); - -/************************************************ - * workspace - ************************************************/ - - // TODO - -/************************************************ - * functions - ************************************************/ - -// -void ocp_nlp_reg_project_config_initialize_default(ocp_nlp_reg_config *config); - - - -#ifdef __cplusplus -} -#endif - -#endif // ACADOS_OCP_NLP_OCP_NLP_REG_PROJECT_H_ -/// @} -/// @} diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_reg_project_reduc_hess.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_reg_project_reduc_hess.h deleted file mode 100644 index 7e12952c15..0000000000 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_reg_project_reduc_hess.h +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -/// \addtogroup ocp_nlp -/// @{ -/// \addtogroup ocp_nlp_reg -/// @{ - -#ifndef ACADOS_OCP_NLP_OCP_NLP_REG_PROJECT_REDUC_HESS_H_ -#define ACADOS_OCP_NLP_OCP_NLP_REG_PROJECT_REDUC_HESS_H_ - -#ifdef __cplusplus -extern "C" { -#endif - - - -// blasfeo -#include "blasfeo/include/blasfeo_common.h" - -// acados -#include "acados/ocp_nlp/ocp_nlp_reg_common.h" - - - -/************************************************ - * dims - ************************************************/ - -// use the functions in ocp_nlp_reg_common - -/************************************************ - * options - ************************************************/ - -typedef struct -{ - double thr_eig; - double min_eig; - double min_pivot; - int pivoting; -} ocp_nlp_reg_project_reduc_hess_opts; - -// -acados_size_t ocp_nlp_reg_project_reduc_hess_opts_calculate_size(void); -// -void *ocp_nlp_reg_project_reduc_hess_opts_assign(void *raw_memory); -// -void ocp_nlp_reg_project_reduc_hess_opts_initialize_default(void *config_, ocp_nlp_reg_dims *dims, void *opts_); -// -void ocp_nlp_reg_project_reduc_hess_opts_set(void *config_, ocp_nlp_reg_dims *dims, void *opts_, char *field, void* value); - - - -/************************************************ - * memory - ************************************************/ - -typedef struct -{ - double *reg_hess; // TODO move to workspace - double *V; // TODO move to workspace - double *d; // TODO move to workspace - double *e; // TODO move to workspace - - // giaf's - struct blasfeo_dmat L; // TODO move to workspace - struct blasfeo_dmat L2; // TODO move to workspace - struct blasfeo_dmat L3; // TODO move to workspace - struct blasfeo_dmat Ls; // TODO move to workspace - struct blasfeo_dmat P; // TODO move to workspace - struct blasfeo_dmat AL; // TODO move to workspace - - struct blasfeo_dmat **RSQrq; // pointer to RSQrq in qp_in - struct blasfeo_dmat **BAbt; // pointer to RSQrq in qp_in -} ocp_nlp_reg_project_reduc_hess_memory; - -// -acados_size_t ocp_nlp_reg_project_reduc_hess_memory_calculate_size(void *config, ocp_nlp_reg_dims *dims, void *opts); -// -void *ocp_nlp_reg_project_reduc_hess_memory_assign(void *config, ocp_nlp_reg_dims *dims, void *opts, void *raw_memory); - -/************************************************ - * workspace - ************************************************/ - - // TODO - -/************************************************ - * functions - ************************************************/ - -// -void ocp_nlp_reg_project_reduc_hess_config_initialize_default(ocp_nlp_reg_config *config); - - - -#ifdef __cplusplus -} -#endif - -#endif // ACADOS_OCP_NLP_OCP_NLP_REG_PROJECT_REDUC_HESS_H_ -/// @} -/// @} diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_sqp.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_sqp.h deleted file mode 100644 index fdb96417f9..0000000000 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_sqp.h +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -/// \addtogroup ocp_nlp -/// @{ -/// \addtogroup ocp_nlp_solver -/// @{ -/// \addtogroup ocp_nlp_sqp ocp_nlp_sqp -/// @{ - -#ifndef ACADOS_OCP_NLP_OCP_NLP_SQP_H_ -#define ACADOS_OCP_NLP_OCP_NLP_SQP_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// acados -#include "acados/ocp_nlp/ocp_nlp_common.h" -#include "acados/utils/types.h" - - - -/************************************************ - * options - ************************************************/ - -typedef struct -{ - ocp_nlp_opts *nlp_opts; - double tol_stat; // exit tolerance on stationarity condition - double tol_eq; // exit tolerance on equality constraints - double tol_ineq; // exit tolerance on inequality constraints - double tol_comp; // exit tolerance on complementarity condition - int max_iter; - int ext_qp_res; // compute external QP residuals (i.e. at SQP level) at each SQP iteration (for debugging) - int qp_warm_start; // qp_warm_start in all but the first sqp iterations - bool warm_start_first_qp; // to set qp_warm_start in first iteration - int rti_phase; // only phase 0 at the moment - int initialize_t_slacks; // 0-false or 1-true - -} ocp_nlp_sqp_opts; - -// -acados_size_t ocp_nlp_sqp_opts_calculate_size(void *config, void *dims); -// -void *ocp_nlp_sqp_opts_assign(void *config, void *dims, void *raw_memory); -// -void ocp_nlp_sqp_opts_initialize_default(void *config, void *dims, void *opts); -// -void ocp_nlp_sqp_opts_update(void *config, void *dims, void *opts); -// -void ocp_nlp_sqp_opts_set(void *config_, void *opts_, const char *field, void* value); -// -void ocp_nlp_sqp_opts_set_at_stage(void *config_, void *opts_, size_t stage, const char *field, void* value); - - - -/************************************************ - * memory - ************************************************/ - -typedef struct -{ - // nlp memory - ocp_nlp_memory *nlp_mem; - - double time_qp_sol; - double time_qp_solver_call; - double time_qp_xcond; - double time_lin; - double time_reg; - double time_tot; - double time_glob; - double time_sim; - double time_sim_la; - double time_sim_ad; - double time_solution_sensitivities; - - // statistics - double *stat; - int stat_m; - int stat_n; - - int status; - int sqp_iter; - -} ocp_nlp_sqp_memory; - -// -acados_size_t ocp_nlp_sqp_memory_calculate_size(void *config, void *dims, void *opts_); -// -void *ocp_nlp_sqp_memory_assign(void *config, void *dims, void *opts_, void *raw_memory); -// -void ocp_nlp_sqp_memory_reset_qp_solver(void *config_, void *dims_, void *nlp_in_, void *nlp_out_, - void *opts_, void *mem_, void *work_); - - -/************************************************ - * workspace - ************************************************/ - -typedef struct -{ - ocp_nlp_workspace *nlp_work; - - // temp QP in & out (to be used as workspace in param sens) - ocp_qp_in *tmp_qp_in; - ocp_qp_out *tmp_qp_out; - - // qp residuals - ocp_qp_res *qp_res; - ocp_qp_res_ws *qp_res_ws; - -} ocp_nlp_sqp_workspace; - -// -acados_size_t ocp_nlp_sqp_workspace_calculate_size(void *config, void *dims, void *opts_); - - - -/************************************************ - * functions - ************************************************/ - -// -int ocp_nlp_sqp(void *config, void *dims, void *nlp_in, void *nlp_out, - void *args, void *mem, void *work_); -// -void ocp_nlp_sqp_config_initialize_default(void *config_); -// -int ocp_nlp_sqp_precompute(void *config_, void *dims_, void *nlp_in_, void *nlp_out_, - void *opts_, void *mem_, void *work_); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_NLP_OCP_NLP_SQP_H_ -/// @} -/// @} -/// @} diff --git a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_sqp_rti.h b/third_party/acados/include/acados/ocp_nlp/ocp_nlp_sqp_rti.h deleted file mode 100644 index 364d0f4717..0000000000 --- a/third_party/acados/include/acados/ocp_nlp/ocp_nlp_sqp_rti.h +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -/// \addtogroup ocp_nlp -/// @{ -/// \addtogroup ocp_nlp_solver -/// @{ -/// \addtogroup ocp_nlp_sqp_rti ocp_nlp_sqp_rti -/// @{ - -#ifndef ACADOS_OCP_NLP_OCP_NLP_SQP_RTI_H_ -#define ACADOS_OCP_NLP_OCP_NLP_SQP_RTI_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// acados -#include "acados/ocp_nlp/ocp_nlp_common.h" -#include "acados/utils/types.h" - - - -/************************************************ - * options - ************************************************/ - -typedef struct -{ - ocp_nlp_opts *nlp_opts; - int compute_dual_sol; - int ext_qp_res; // compute external QP residuals (i.e. at SQP level) at each SQP iteration (for debugging) - int qp_warm_start; // NOTE: this is not actually setting the warm_start! Just for compatibility with sqp. - bool warm_start_first_qp; // to set qp_warm_start in first iteration - int rti_phase; // phase of RTI. Possible values 1 (preparation), 2 (feedback) 0 (both) - -} ocp_nlp_sqp_rti_opts; - -// -acados_size_t ocp_nlp_sqp_rti_opts_calculate_size(void *config_, void *dims_); -// -void *ocp_nlp_sqp_rti_opts_assign(void *config_, void *dims_, void *raw_memory); -// -void ocp_nlp_sqp_rti_opts_initialize_default(void *config_, void *dims_, void *opts_); -// -void ocp_nlp_sqp_rti_opts_update(void *config_, void *dims_, void *opts_); -// -void ocp_nlp_sqp_rti_opts_set(void *config_, void *opts_, const char *field, void* value); -// -void ocp_nlp_sqp_rti_opts_set_at_stage(void *config_, void *opts_, size_t stage, - const char *field, void* value); - - - -/************************************************ - * memory - ************************************************/ - -typedef struct -{ - // nlp memory - ocp_nlp_memory *nlp_mem; - - double time_qp_sol; - double time_qp_solver_call; - double time_qp_xcond; - double time_lin; - double time_reg; - double time_tot; - double time_glob; - double time_solution_sensitivities; - - // statistics - double *stat; - int stat_m; - int stat_n; - - int status; - -} ocp_nlp_sqp_rti_memory; - -// -acados_size_t ocp_nlp_sqp_rti_memory_calculate_size(void *config_, void *dims_, void *opts_); -// -void *ocp_nlp_sqp_rti_memory_assign(void *config_, void *dims_, void *opts_, - void *raw_memory); - - - -/************************************************ - * workspace - ************************************************/ - -typedef struct -{ - ocp_nlp_workspace *nlp_work; - - // temp QP in & out (to be used as workspace in param sens) - ocp_qp_in *tmp_qp_in; - ocp_qp_out *tmp_qp_out; - - // qp residuals - ocp_qp_res *qp_res; - ocp_qp_res_ws *qp_res_ws; - - -} ocp_nlp_sqp_rti_workspace; - -// -acados_size_t ocp_nlp_sqp_rti_workspace_calculate_size(void *config_, void *dims_, void *opts_); - - - -/************************************************ - * functions - ************************************************/ -// -int ocp_nlp_sqp_rti(void *config_, void *dims_, void *nlp_in_, void *nlp_out_, - void *opts_, void *mem_, void *work_); -// -void ocp_nlp_sqp_rti_config_initialize_default(void *config_); -// -int ocp_nlp_sqp_rti_precompute(void *config_, void *dims_, - void *nlp_in_, void *nlp_out_, void *opts_, void *mem_, void *work_); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_NLP_OCP_NLP_SQP_RTI_H_ -/// @} -/// @} -/// @} diff --git a/third_party/acados/include/acados/ocp_qp/ocp_qp_common.h b/third_party/acados/include/acados/ocp_qp/ocp_qp_common.h deleted file mode 100644 index d1a45635e4..0000000000 --- a/third_party/acados/include/acados/ocp_qp/ocp_qp_common.h +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -#ifndef ACADOS_OCP_QP_OCP_QP_COMMON_H_ -#define ACADOS_OCP_QP_OCP_QP_COMMON_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// hpipm -#include "hpipm/include/hpipm_d_ocp_qp.h" -#include "hpipm/include/hpipm_d_ocp_qp_dim.h" -#include "hpipm/include/hpipm_d_ocp_qp_res.h" -#include "hpipm/include/hpipm_d_ocp_qp_sol.h" -// acados -#include "acados/utils/types.h" - - - -typedef struct d_ocp_qp_dim ocp_qp_dims; -typedef struct d_ocp_qp ocp_qp_in; -typedef struct d_ocp_qp_sol ocp_qp_out; -typedef struct d_ocp_qp_res ocp_qp_res; -typedef struct d_ocp_qp_res_ws ocp_qp_res_ws; - - - -#ifndef QP_SOLVER_CONFIG_ -#define QP_SOLVER_CONFIG_ -typedef struct -{ - void (*dims_set)(void *config_, void *dims_, int stage, const char *field, int* value); - acados_size_t (*opts_calculate_size)(void *config, void *dims); - void *(*opts_assign)(void *config, void *dims, void *raw_memory); - void (*opts_initialize_default)(void *config, void *dims, void *opts); - void (*opts_update)(void *config, void *dims, void *opts); - void (*opts_set)(void *config_, void *opts_, const char *field, void* value); - acados_size_t (*memory_calculate_size)(void *config, void *dims, void *opts); - void *(*memory_assign)(void *config, void *dims, void *opts, void *raw_memory); - void (*memory_get)(void *config_, void *mem_, const char *field, void* value); - acados_size_t (*workspace_calculate_size)(void *config, void *dims, void *opts); - int (*evaluate)(void *config, void *qp_in, void *qp_out, void *opts, void *mem, void *work); - void (*memory_reset)(void *config, void *qp_in, void *qp_out, void *opts, void *mem, void *work); - void (*eval_sens)(void *config, void *qp_in, void *qp_out, void *opts, void *mem, void *work); -} qp_solver_config; -#endif - - - -typedef struct -{ - acados_size_t (*dims_calculate_size)(void *config, int N); - void *(*dims_assign)(void *config, int N, void *raw_memory); - void (*dims_set)(void *config, void *dims_, int stage, const char *field, int* value); - void (*dims_get)(void *config, void *dims, const char *field, void* value); - // TODO add config everywhere !!!!! - acados_size_t (*opts_calculate_size)(void *dims); - void *(*opts_assign)(void *dims, void *raw_memory); - void (*opts_initialize_default)(void *dims, void *opts); - void (*opts_update)(void *dims, void *opts); - void (*opts_set)(void *opts_, const char *field, void* value); - acados_size_t (*memory_calculate_size)(void *dims, void *opts); - void *(*memory_assign)(void *dims, void *opts, void *raw_memory); - void (*memory_get)(void *config, void *mem, const char *field, void* value); - acados_size_t (*workspace_calculate_size)(void *dims, void *opts); - int (*condensing)(void *qp_in, void *qp_out, void *opts, void *mem, void *work); - int (*condensing_rhs)(void *qp_in, void *qp_out, void *opts, void *mem, void *work); - int (*expansion)(void *qp_in, void *qp_out, void *opts, void *mem, void *work); -} ocp_qp_xcond_config; - - - -/// Struct containing metrics of the qp solver. -#ifndef QP_INFO_ -#define QP_INFO_ -typedef struct -{ - double solve_QP_time; - double condensing_time; - double interface_time; - double total_time; - int num_iter; - int t_computed; -} qp_info; -#endif - - - -/* config */ -// -acados_size_t ocp_qp_solver_config_calculate_size(); -// -qp_solver_config *ocp_qp_solver_config_assign(void *raw_memory); -// -acados_size_t ocp_qp_condensing_config_calculate_size(); -// -ocp_qp_xcond_config *ocp_qp_condensing_config_assign(void *raw_memory); - - -/* dims */ -// -acados_size_t ocp_qp_dims_calculate_size(int N); -// -ocp_qp_dims *ocp_qp_dims_assign(int N, void *raw_memory); -// -void ocp_qp_dims_set(void *config_, void *dims, int stage, const char *field, int* value); -// -void ocp_qp_dims_get(void *config_, void *dims, int stage, const char *field, int* value); - - -/* in */ -// -acados_size_t ocp_qp_in_calculate_size(ocp_qp_dims *dims); -// -ocp_qp_in *ocp_qp_in_assign(ocp_qp_dims *dims, void *raw_memory); - - -/* out */ -// -acados_size_t ocp_qp_out_calculate_size(ocp_qp_dims *dims); -// -ocp_qp_out *ocp_qp_out_assign(ocp_qp_dims *dims, void *raw_memory); - -/* res */ -// -acados_size_t ocp_qp_res_calculate_size(ocp_qp_dims *dims); -// -ocp_qp_res *ocp_qp_res_assign(ocp_qp_dims *dims, void *raw_memory); -// -acados_size_t ocp_qp_res_workspace_calculate_size(ocp_qp_dims *dims); -// -ocp_qp_res_ws *ocp_qp_res_workspace_assign(ocp_qp_dims *dims, void *raw_memory); -// -void ocp_qp_res_compute(ocp_qp_in *qp_in, ocp_qp_out *qp_out, ocp_qp_res *qp_res, ocp_qp_res_ws *res_ws); -// -void ocp_qp_res_compute_nrm_inf(ocp_qp_res *qp_res, double res[4]); - - -/* misc */ -// -void ocp_qp_stack_slacks_dims(ocp_qp_dims *in, ocp_qp_dims *out); -// -void ocp_qp_stack_slacks(ocp_qp_in *in, ocp_qp_in *out); -// -void ocp_qp_compute_t(ocp_qp_in *qp_in, ocp_qp_out *qp_out); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_QP_OCP_QP_COMMON_H_ diff --git a/third_party/acados/include/acados/ocp_qp/ocp_qp_common_frontend.h b/third_party/acados/include/acados/ocp_qp/ocp_qp_common_frontend.h deleted file mode 100644 index f65f602c15..0000000000 --- a/third_party/acados/include/acados/ocp_qp/ocp_qp_common_frontend.h +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -#ifndef ACADOS_OCP_QP_OCP_QP_COMMON_FRONTEND_H_ -#define ACADOS_OCP_QP_OCP_QP_COMMON_FRONTEND_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "acados/ocp_qp/ocp_qp_common.h" - -typedef struct -{ - int N; - int *nx; - int *nu; - int *nb; - int *nc; - double **A; - double **B; - double **b; - double **Q; - double **S; - double **R; - double **q; - double **r; - int **idxb; - double **lb; - double **ub; - double **Cx; - double **Cu; - double **lc; - double **uc; -} colmaj_ocp_qp_in; - -typedef struct -{ - double **x; - double **u; - double **pi; - double **lam; -} colmaj_ocp_qp_out; - -typedef struct -{ - double **res_r; - double **res_q; - double **res_ls; - double **res_us; - double **res_b; - double **res_d_lb; - double **res_d_ub; - double **res_d_lg; - double **res_d_ug; - double **res_d_ls; - double **res_d_us; - double **res_m_lb; - double **res_m_ub; - double **res_m_lg; - double **res_m_ug; - double **res_m_ls; - double **res_m_us; - double res_nrm_inf[4]; -} colmaj_ocp_qp_res; - -// -acados_size_t colmaj_ocp_qp_in_calculate_size(ocp_qp_dims *dims); -// -char *assign_colmaj_ocp_qp_in(ocp_qp_dims *dims, colmaj_ocp_qp_in **qp_in, void *ptr); -// -acados_size_t colmaj_ocp_qp_out_calculate_size(ocp_qp_dims *dims); -// -char *assign_colmaj_ocp_qp_out(ocp_qp_dims *dims, colmaj_ocp_qp_out **qp_out, void *ptr); -// -acados_size_t colmaj_ocp_qp_res_calculate_size(ocp_qp_dims *dims); -// -char *assign_colmaj_ocp_qp_res(ocp_qp_dims *dims, colmaj_ocp_qp_res **qp_res, void *ptr); -// -void convert_colmaj_to_ocp_qp_in(colmaj_ocp_qp_in *cm_qp_in, ocp_qp_in *qp_in); -// -void convert_ocp_qp_out_to_colmaj(ocp_qp_out *qp_out, colmaj_ocp_qp_out *cm_qp_out); -// -void convert_ocp_qp_res_to_colmaj(ocp_qp_res *qp_res, colmaj_ocp_qp_res *cm_qp_res); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_QP_OCP_QP_COMMON_FRONTEND_H_ diff --git a/third_party/acados/include/acados/ocp_qp/ocp_qp_full_condensing.h b/third_party/acados/include/acados/ocp_qp/ocp_qp_full_condensing.h deleted file mode 100644 index d23e658b48..0000000000 --- a/third_party/acados/include/acados/ocp_qp/ocp_qp_full_condensing.h +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -#ifndef ACADOS_OCP_QP_OCP_QP_FULL_CONDENSING_H_ -#define ACADOS_OCP_QP_OCP_QP_FULL_CONDENSING_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// hpipm -#include "hpipm/include/hpipm_d_ocp_qp_red.h" -// acados -#include "acados/dense_qp/dense_qp_common.h" -#include "acados/ocp_qp/ocp_qp_common.h" -#include "acados/utils/types.h" - - - -typedef struct -{ - ocp_qp_dims *orig_dims; - ocp_qp_dims *red_dims; // dims of reduced qp - dense_qp_dims *fcond_dims; -} ocp_qp_full_condensing_dims; - - - -typedef struct ocp_qp_full_condensing_opts_ -{ - struct d_cond_qp_arg *hpipm_cond_opts; - struct d_ocp_qp_reduce_eq_dof_arg *hpipm_red_opts; -// dense_qp_dims *fcond_dims; // TODO(all): move to dims - int cond_hess; // 0 cond only rhs, 1 cond hess + rhs - int expand_dual_sol; // 0 primal sol only, 1 primal + dual sol - int ric_alg; - int mem_qp_in; // allocate qp_in in memory -} ocp_qp_full_condensing_opts; - - - -typedef struct ocp_qp_full_condensing_memory_ -{ - struct d_cond_qp_ws *hpipm_cond_work; - struct d_ocp_qp_reduce_eq_dof_ws *hpipm_red_work; - // in memory - dense_qp_in *fcond_qp_in; - dense_qp_out *fcond_qp_out; - ocp_qp_in *red_qp; // reduced qp - ocp_qp_out *red_sol; // reduced qp sol - // only pointer - ocp_qp_in *ptr_qp_in; - qp_info *qp_out_info; // info in fcond_qp_in - double time_qp_xcond; -} ocp_qp_full_condensing_memory; - - - -// -acados_size_t ocp_qp_full_condensing_opts_calculate_size(void *dims); -// -void *ocp_qp_full_condensing_opts_assign(void *dims, void *raw_memory); -// -void ocp_qp_full_condensing_opts_initialize_default(void *dims, void *opts_); -// -void ocp_qp_full_condensing_opts_update(void *dims, void *opts_); -// -void ocp_qp_full_condensing_opts_set(void *opts_, const char *field, void* value); -// -acados_size_t ocp_qp_full_condensing_memory_calculate_size(void *dims, void *opts_); -// -void *ocp_qp_full_condensing_memory_assign(void *dims, void *opts_, void *raw_memory); -// -acados_size_t ocp_qp_full_condensing_workspace_calculate_size(void *dims, void *opts_); -// -int ocp_qp_full_condensing(void *in, void *out, void *opts, void *mem, void *work); -// -int ocp_qp_full_expansion(void *in, void *out, void *opts, void *mem, void *work); -// -void ocp_qp_full_condensing_config_initialize_default(void *config_); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_QP_OCP_QP_FULL_CONDENSING_H_ diff --git a/third_party/acados/include/acados/ocp_qp/ocp_qp_hpipm.h b/third_party/acados/include/acados/ocp_qp/ocp_qp_hpipm.h deleted file mode 100644 index 261606b842..0000000000 --- a/third_party/acados/include/acados/ocp_qp/ocp_qp_hpipm.h +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -#ifndef ACADOS_OCP_QP_OCP_QP_HPIPM_H_ -#define ACADOS_OCP_QP_OCP_QP_HPIPM_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// hpipm -#include "hpipm/include/hpipm_d_ocp_qp_ipm.h" -// acados -#include "acados/ocp_qp/ocp_qp_common.h" -#include "acados/utils/types.h" - - - -// struct of arguments to the solver -// TODO(roversch): why not make this a typedef of the underlying struct? -typedef struct ocp_qp_hpipm_opts_ -{ - struct d_ocp_qp_ipm_arg *hpipm_opts; -} ocp_qp_hpipm_opts; - - - -// TODO(roversch): why not make this a typedef of the underlying struct? -// struct of the solver memory -typedef struct ocp_qp_hpipm_memory_ -{ - struct d_ocp_qp_ipm_ws *hpipm_workspace; - double time_qp_solver_call; - int iter; - int status; - -} ocp_qp_hpipm_memory; - - - -// -acados_size_t ocp_qp_hpipm_opts_calculate_size(void *config, void *dims); -// -void *ocp_qp_hpipm_opts_assign(void *config, void *dims, void *raw_memory); -// -void ocp_qp_hpipm_opts_initialize_default(void *config, void *dims, void *opts_); -// -void ocp_qp_hpipm_opts_update(void *config, void *dims, void *opts_); -// -void ocp_qp_hpipm_opts_set(void *config_, void *opts_, const char *field, void *value); -// -acados_size_t ocp_qp_hpipm_memory_calculate_size(void *config, void *dims, void *opts_); -// -void *ocp_qp_hpipm_memory_assign(void *config, void *dims, void *opts_, void *raw_memory); -// -acados_size_t ocp_qp_hpipm_workspace_calculate_size(void *config, void *dims, void *opts_); -// -int ocp_qp_hpipm(void *config, void *qp_in, void *qp_out, void *opts_, void *mem_, void *work_); -// -void ocp_qp_hpipm_memory_reset(void *config_, void *qp_in_, void *qp_out_, void *opts_, void *mem_, void *work_); -// -void ocp_qp_hpipm_eval_sens(void *config, void *qp_in, void *qp_out, void *opts_, void *mem_, void *work_); -// -void ocp_qp_hpipm_config_initialize_default(void *config); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_QP_OCP_QP_HPIPM_H_ diff --git a/third_party/acados/include/acados/ocp_qp/ocp_qp_hpmpc.h b/third_party/acados/include/acados/ocp_qp/ocp_qp_hpmpc.h deleted file mode 100644 index 8db53a279d..0000000000 --- a/third_party/acados/include/acados/ocp_qp/ocp_qp_hpmpc.h +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -#ifndef ACADOS_OCP_QP_OCP_QP_HPMPC_H_ -#define ACADOS_OCP_QP_OCP_QP_HPMPC_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "acados/ocp_qp/ocp_qp_common.h" -#include "acados/utils/types.h" - -typedef enum hpmpc_options_t_ { HPMPC_DEFAULT_ARGUMENTS } hpmpc_options_t; - -typedef struct ocp_qp_hpmpc_opts_ -{ - double tol; - int max_iter; - double mu0; - double alpha_min; - int warm_start; - int N2; // horizion length of the partially condensed problem - - // partial tightening - double sigma_mu; - int N; - int M; -} ocp_qp_hpmpc_opts; - -// struct of the solver memory -typedef struct ocp_qp_hpmpc_memory_ -{ - struct blasfeo_dvec *hpi; - double *stats; - - // workspace - void *hpmpc_work; // raw workspace - - // partial tightening-specific (init of extra variables) - struct blasfeo_dvec *lam0; - struct blasfeo_dvec *ux0; - struct blasfeo_dvec *pi0; - struct blasfeo_dvec *t0; - - // 2. workspace - struct blasfeo_dmat *hsL; - struct blasfeo_dmat *hsric_work_mat; - struct blasfeo_dmat sLxM; - struct blasfeo_dmat sPpM; - - struct blasfeo_dvec *hsQx; - struct blasfeo_dvec *hsqx; - struct blasfeo_dvec *hstinv; - struct blasfeo_dvec *hsrq; - struct blasfeo_dvec *hsdux; - - struct blasfeo_dvec *hsdlam; - struct blasfeo_dvec *hsdt; - struct blasfeo_dvec *hsdpi; - struct blasfeo_dvec *hslamt; - - struct blasfeo_dvec *hsPb; - - void *work_ric; - - int out_iter; - - double time_qp_solver_call; - int iter; - int status; - -} ocp_qp_hpmpc_memory; - -acados_size_t ocp_qp_hpmpc_opts_calculate_size(void *config_, ocp_qp_dims *dims); -// -void *ocp_qp_hpmpc_opts_assign(void *config_, ocp_qp_dims *dims, void *raw_memory); -// -void ocp_qp_hpmpc_opts_initialize_default(void *config_, ocp_qp_dims *dims, void *opts_); -// -void ocp_qp_hpmpc_opts_update(void *config_, ocp_qp_dims *dims, void *opts_); -// -acados_size_t ocp_qp_hpmpc_memory_calculate_size(void *config_, ocp_qp_dims *dims, void *opts_); -// -void *ocp_qp_hpmpc_memory_assign(void *config_, ocp_qp_dims *dims, void *opts_, void *raw_memory); -// -acados_size_t ocp_qp_hpmpc_workspace_calculate_size(void *config_, ocp_qp_dims *dims, void *opts_); -// -int ocp_qp_hpmpc(void *config_, void *qp_in, void *qp_out, void *opts_, void *mem_, void *work_); -// -void ocp_qp_hpmpc_eval_sens(void *config_, void *qp_in, void *qp_out, void *opts_, void *mem_, void *work_); -// -void ocp_qp_hpmpc_config_initialize_default(void *config_); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_QP_OCP_QP_HPMPC_H_ diff --git a/third_party/acados/include/acados/ocp_qp/ocp_qp_ooqp.h b/third_party/acados/include/acados/ocp_qp/ocp_qp_ooqp.h deleted file mode 100644 index a535503f21..0000000000 --- a/third_party/acados/include/acados/ocp_qp/ocp_qp_ooqp.h +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -#ifndef ACADOS_OCP_QP_OCP_QP_OOQP_H_ -#define ACADOS_OCP_QP_OCP_QP_OOQP_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "acados/ocp_qp/ocp_qp_common.h" -#include "acados/utils/types.h" - -enum ocp_qp_ooqp_termination_code -{ - SPARSE_SUCCESSFUL_TERMINATION = 0, - SPARSE_NOT_FINISHED, - SPARSE_MAX_ITS_EXCEEDED, - SPARSE_INFEASIBLE, - SPARSE_UNKNOWN -}; - -typedef struct ocp_qp_ooqp_opts_ -{ - int printLevel; - int useDiagonalWeights; // TODO(dimitris): implement option - int fixHessian; - int fixHessianSparsity; - int fixDynamics; - int fixDynamicsSparsity; - int fixInequalities; - int fixInequalitiesSparsity; -} ocp_qp_ooqp_opts; - -typedef struct ocp_qp_ooqp_workspace_ -{ - double *x; - double *gamma; - double *phi; - double *y; - double *z; - double *lambda; - double *pi; - double objectiveValue; - int *tmpInt; // temporary vector to sort indicies sparse matrices - double *tmpReal; // temporary vector to sort data of sparse matrices - // int ierr; -} ocp_qp_ooqp_workspace; - -typedef struct ocp_qp_ooqp_memory_ -{ - int firstRun; - double *c; - int nx; - int *irowQ; - int nnzQ; - int *jcolQ; - int *orderQ; - double *dQ; - double *xlow; - char *ixlow; - double *xupp; - char *ixupp; - int *irowA; - int nnzA; - int *jcolA; - int *orderA; - double *dA; - double *bA; - int my; - int *irowC; - int nnzC; - int *jcolC; - int *orderC; - double *dC; - double *clow; - int mz; - char *iclow; - double *cupp; - char *icupp; - int nnz; // max(nnzQ, nnzA, nnzC) - double time_qp_solver_call; - int iter; - int status; - -} ocp_qp_ooqp_memory; - -// -acados_size_t ocp_qp_ooqp_opts_calculate_size(void *config_, ocp_qp_dims *dims); -// -void *ocp_qp_ooqp_opts_assign(void *config_, ocp_qp_dims *dims, void *raw_memory); -// -void ocp_qp_ooqp_opts_initialize_default(void *config_, ocp_qp_dims *dims, void *opts_); -// -void ocp_qp_ooqp_opts_update(void *config_, ocp_qp_dims *dims, void *opts_); -// -acados_size_t ocp_qp_ooqp_memory_calculate_size(void *config_, ocp_qp_dims *dims, void *opts_); -// -void *ocp_qp_ooqp_memory_assign(void *config_, ocp_qp_dims *dims, void *opts_, void *raw_memory); -// -acados_size_t ocp_qp_ooqp_workspace_calculate_size(void *config_, ocp_qp_dims *dims, void *opts_); -// -int ocp_qp_ooqp(void *config_, ocp_qp_in *qp_in, ocp_qp_out *qp_out, void *opts_, void *memory_, - void *work_); -// -void ocp_qp_ooqp_destroy(void *mem_, void *work); -// -void ocp_qp_ooqp_eval_sens(void *config_, void *qp_in, void *qp_out, void *opts_, void *mem_, void *work_); -// -void ocp_qp_ooqp_config_initialize_default(void *config_); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_QP_OCP_QP_OOQP_H_ diff --git a/third_party/acados/include/acados/ocp_qp/ocp_qp_osqp.h b/third_party/acados/include/acados/ocp_qp/ocp_qp_osqp.h deleted file mode 100644 index 51df1b1cd6..0000000000 --- a/third_party/acados/include/acados/ocp_qp/ocp_qp_osqp.h +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -#ifndef ACADOS_OCP_QP_OCP_QP_OSQP_H_ -#define ACADOS_OCP_QP_OCP_QP_OSQP_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// osqp -#include "osqp/include/types.h" - -// acados -#include "acados/ocp_qp/ocp_qp_common.h" -#include "acados/utils/types.h" - -typedef struct ocp_qp_osqp_opts_ -{ - OSQPSettings *osqp_opts; -} ocp_qp_osqp_opts; - - -typedef struct ocp_qp_osqp_memory_ -{ - c_int first_run; - - c_float *q; - c_float *l; - c_float *u; - - c_int P_nnzmax; - c_int *P_i; - c_int *P_p; - c_float *P_x; - - c_int A_nnzmax; - c_int *A_i; - c_int *A_p; - c_float *A_x; - - OSQPData *osqp_data; - OSQPWorkspace *osqp_work; - - double time_qp_solver_call; - int iter; - int status; - -} ocp_qp_osqp_memory; - -acados_size_t ocp_qp_osqp_opts_calculate_size(void *config, void *dims); -// -void *ocp_qp_osqp_opts_assign(void *config, void *dims, void *raw_memory); -// -void ocp_qp_osqp_opts_initialize_default(void *config, void *dims, void *opts_); -// -void ocp_qp_osqp_opts_update(void *config, void *dims, void *opts_); -// -acados_size_t ocp_qp_osqp_memory_calculate_size(void *config, void *dims, void *opts_); -// -void *ocp_qp_osqp_memory_assign(void *config, void *dims, void *opts_, void *raw_memory); -// -acados_size_t ocp_qp_osqp_workspace_calculate_size(void *config, void *dims, void *opts_); -// -int ocp_qp_osqp(void *config, void *qp_in, void *qp_out, void *opts_, void *mem_, void *work_); -// -void ocp_qp_osqp_eval_sens(void *config_, void *qp_in, void *qp_out, void *opts_, void *mem_, void *work_); -// -void ocp_qp_osqp_config_initialize_default(void *config); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_QP_OCP_QP_OSQP_H_ diff --git a/third_party/acados/include/acados/ocp_qp/ocp_qp_partial_condensing.h b/third_party/acados/include/acados/ocp_qp/ocp_qp_partial_condensing.h deleted file mode 100644 index 844f6048fe..0000000000 --- a/third_party/acados/include/acados/ocp_qp/ocp_qp_partial_condensing.h +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -#ifndef ACADOS_OCP_QP_OCP_QP_PARTIAL_CONDENSING_H_ -#define ACADOS_OCP_QP_OCP_QP_PARTIAL_CONDENSING_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// hpipm -#include "hpipm/include/hpipm_d_ocp_qp_red.h" -// acados -#include "acados/ocp_qp/ocp_qp_common.h" - - - -typedef struct -{ - ocp_qp_dims *orig_dims; - ocp_qp_dims *red_dims; // dims of reduced qp - ocp_qp_dims *pcond_dims; - int *block_size; - int N2; - int N2_bkp; -} ocp_qp_partial_condensing_dims; - - - -typedef struct ocp_qp_partial_condensing_opts_ -{ - struct d_part_cond_qp_arg *hpipm_pcond_opts; - struct d_ocp_qp_reduce_eq_dof_arg *hpipm_red_opts; -// ocp_qp_dims *pcond_dims; // TODO(all): move to dims -// int *block_size; - int N2; - int N2_bkp; -// int expand_dual_sol; // 0 primal sol only, 1 primal + dual sol - int ric_alg; - int mem_qp_in; // allocate qp_in in memory -} ocp_qp_partial_condensing_opts; - - - -typedef struct ocp_qp_partial_condensing_memory_ -{ - struct d_part_cond_qp_ws *hpipm_pcond_work; - struct d_ocp_qp_reduce_eq_dof_ws *hpipm_red_work; - // in memory - ocp_qp_in *pcond_qp_in; - ocp_qp_out *pcond_qp_out; - ocp_qp_in *red_qp; // reduced qp - ocp_qp_out *red_sol; // reduced qp sol - // only pointer - ocp_qp_in *ptr_qp_in; - ocp_qp_in *ptr_pcond_qp_in; - qp_info *qp_out_info; // info in pcond_qp_in - double time_qp_xcond; -} ocp_qp_partial_condensing_memory; - - - -// -acados_size_t ocp_qp_partial_condensing_opts_calculate_size(void *dims); -// -void *ocp_qp_partial_condensing_opts_assign(void *dims, void *raw_memory); -// -void ocp_qp_partial_condensing_opts_initialize_default(void *dims, void *opts_); -// -void ocp_qp_partial_condensing_opts_update(void *dims, void *opts_); -// -void ocp_qp_partial_condensing_opts_set(void *opts_, const char *field, void* value); -// -acados_size_t ocp_qp_partial_condensing_memory_calculate_size(void *dims, void *opts_); -// -void *ocp_qp_partial_condensing_memory_assign(void *dims, void *opts, void *raw_memory); -// -acados_size_t ocp_qp_partial_condensing_workspace_calculate_size(void *dims, void *opts_); -// -int ocp_qp_partial_condensing(void *in, void *out, void *opts, void *mem, void *work); -// -int ocp_qp_partial_expansion(void *in, void *out, void *opts, void *mem, void *work); -// -void ocp_qp_partial_condensing_config_initialize_default(void *config_); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_QP_OCP_QP_PARTIAL_CONDENSING_H_ diff --git a/third_party/acados/include/acados/ocp_qp/ocp_qp_qpdunes.h b/third_party/acados/include/acados/ocp_qp/ocp_qp_qpdunes.h deleted file mode 100644 index 3b875caeb5..0000000000 --- a/third_party/acados/include/acados/ocp_qp/ocp_qp_qpdunes.h +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -#ifndef ACADOS_OCP_QP_OCP_QP_QPDUNES_H_ -#define ACADOS_OCP_QP_OCP_QP_QPDUNES_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "qpDUNES.h" - -#include "acados/ocp_qp/ocp_qp_common.h" -#include "acados/utils/types.h" - -typedef enum qpdunes_options_t_ { - QPDUNES_DEFAULT_ARGUMENTS, - QPDUNES_LINEAR_MPC, // TODO(dimitris): partly implemented - QPDUNES_NONLINEAR_MPC, // TODO(dimitris): not implemented yet - QPDUNES_ACADO_SETTINGS -} qpdunes_options_t; - -typedef enum { QPDUNES_WITH_QPOASES, QPDUNES_WITH_CLIPPING } qpdunes_stage_qp_solver_t; - -typedef struct ocp_qp_qpdunes_opts_ -{ - qpOptions_t options; - qpdunes_stage_qp_solver_t stageQpSolver; - int warmstart; // warmstart = 0: all multipliers set to zero, warmstart = 1: use previous mult. - bool isLinearMPC; -} ocp_qp_qpdunes_opts; - -typedef struct ocp_qp_qpdunes_memory_ -{ - int firstRun; - int nx; - int nu; - int nz; - int nDmax; // max(dims->ng) - qpData_t qpData; - double time_qp_solver_call; - int iter; - int status; - -} ocp_qp_qpdunes_memory; - -typedef struct ocp_qp_qpdunes_workspace_ -{ - double *H; - double *Q; - double *R; - double *S; - double *g; - double *ABt; - double *b; - double *Ct; - double *lc; - double *uc; - double *zLow; - double *zUpp; -} ocp_qp_qpdunes_workspace; - -// -acados_size_t ocp_qp_qpdunes_opts_calculate_size(void *config_, ocp_qp_dims *dims); -// -void *ocp_qp_qpdunes_opts_assign(void *config_, ocp_qp_dims *dims, void *raw_memory); -// -void ocp_qp_qpdunes_opts_initialize_default(void *config_, ocp_qp_dims *dims, void *opts_); -// -void ocp_qp_qpdunes_opts_update(void *config_, ocp_qp_dims *dims, void *opts_); -// -acados_size_t ocp_qp_qpdunes_memory_calculate_size(void *config_, ocp_qp_dims *dims, void *opts_); -// -void *ocp_qp_qpdunes_memory_assign(void *config_, ocp_qp_dims *dims, void *opts_, void *raw_memory); -// -acados_size_t ocp_qp_qpdunes_workspace_calculate_size(void *config_, ocp_qp_dims *dims, void *opts_); -// -int ocp_qp_qpdunes(void *config_, ocp_qp_in *qp_in, ocp_qp_out *qp_out, void *opts_, void *memory_, - void *work_); -// -void ocp_qp_qpdunes_free_memory(void *mem_); -// -void ocp_qp_qpdunes_eval_sens(void *config_, void *qp_in, void *qp_out, void *opts_, void *mem_, void *work_); -// -void ocp_qp_qpdunes_config_initialize_default(void *config_); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_QP_OCP_QP_QPDUNES_H_ diff --git a/third_party/acados/include/acados/ocp_qp/ocp_qp_xcond_solver.h b/third_party/acados/include/acados/ocp_qp/ocp_qp_xcond_solver.h deleted file mode 100644 index a78bc65bb9..0000000000 --- a/third_party/acados/include/acados/ocp_qp/ocp_qp_xcond_solver.h +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -#ifndef ACADOS_OCP_QP_OCP_QP_PARTIAL_CONDENSING_SOLVER_H_ -#define ACADOS_OCP_QP_OCP_QP_PARTIAL_CONDENSING_SOLVER_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// acados -#include "acados/ocp_qp/ocp_qp_common.h" -#include "acados/utils/types.h" - - - -typedef struct -{ - ocp_qp_dims *orig_dims; - void *xcond_dims; -} ocp_qp_xcond_solver_dims; - - - -typedef struct ocp_qp_xcond_solver_opts_ -{ - void *xcond_opts; - void *qp_solver_opts; -} ocp_qp_xcond_solver_opts; - - - -typedef struct ocp_qp_xcond_solver_memory_ -{ - void *xcond_memory; - void *solver_memory; - void *xcond_qp_in; - void *xcond_qp_out; -} ocp_qp_xcond_solver_memory; - - - -typedef struct ocp_qp_xcond_solver_workspace_ -{ - void *xcond_work; - void *qp_solver_work; -} ocp_qp_xcond_solver_workspace; - - - -typedef struct -{ - acados_size_t (*dims_calculate_size)(void *config, int N); - ocp_qp_xcond_solver_dims *(*dims_assign)(void *config, int N, void *raw_memory); - void (*dims_set)(void *config_, ocp_qp_xcond_solver_dims *dims, int stage, const char *field, int* value); - void (*dims_get)(void *config_, ocp_qp_xcond_solver_dims *dims, int stage, const char *field, int* value); - acados_size_t (*opts_calculate_size)(void *config, ocp_qp_xcond_solver_dims *dims); - void *(*opts_assign)(void *config, ocp_qp_xcond_solver_dims *dims, void *raw_memory); - void (*opts_initialize_default)(void *config, ocp_qp_xcond_solver_dims *dims, void *opts); - void (*opts_update)(void *config, ocp_qp_xcond_solver_dims *dims, void *opts); - void (*opts_set)(void *config_, void *opts_, const char *field, void* value); - acados_size_t (*memory_calculate_size)(void *config, ocp_qp_xcond_solver_dims *dims, void *opts); - void *(*memory_assign)(void *config, ocp_qp_xcond_solver_dims *dims, void *opts, void *raw_memory); - void (*memory_get)(void *config_, void *mem_, const char *field, void* value); - void (*memory_reset)(void *config, ocp_qp_xcond_solver_dims *dims, ocp_qp_in *qp_in, ocp_qp_out *qp_out, void *opts, void *mem, void *work); - acados_size_t (*workspace_calculate_size)(void *config, ocp_qp_xcond_solver_dims *dims, void *opts); - int (*evaluate)(void *config, ocp_qp_xcond_solver_dims *dims, ocp_qp_in *qp_in, ocp_qp_out *qp_out, void *opts, void *mem, void *work); - void (*eval_sens)(void *config, ocp_qp_xcond_solver_dims *dims, ocp_qp_in *param_qp_in, ocp_qp_out *sens_qp_out, void *opts, void *mem, void *work); - qp_solver_config *qp_solver; // either ocp_qp_solver or dense_solver - ocp_qp_xcond_config *xcond; -} ocp_qp_xcond_solver_config; // pcond - partial condensing or fcond - full condensing - - - -/* config */ -// -acados_size_t ocp_qp_xcond_solver_config_calculate_size(); -// -ocp_qp_xcond_solver_config *ocp_qp_xcond_solver_config_assign(void *raw_memory); - -/* dims */ -// -acados_size_t ocp_qp_xcond_solver_dims_calculate_size(void *config, int N); -// -ocp_qp_xcond_solver_dims *ocp_qp_xcond_solver_dims_assign(void *config, int N, void *raw_memory); -// -void ocp_qp_xcond_solver_dims_set_(void *config, ocp_qp_xcond_solver_dims *dims, int stage, const char *field, int* value); - -/* opts */ -// -acados_size_t ocp_qp_xcond_solver_opts_calculate_size(void *config, ocp_qp_xcond_solver_dims *dims); -// -void *ocp_qp_xcond_solver_opts_assign(void *config, ocp_qp_xcond_solver_dims *dims, void *raw_memory); -// -void ocp_qp_xcond_solver_opts_initialize_default(void *config, ocp_qp_xcond_solver_dims *dims, void *opts_); -// -void ocp_qp_xcond_solver_opts_update(void *config, ocp_qp_xcond_solver_dims *dims, void *opts_); -// -void ocp_qp_xcond_solver_opts_set_(void *config_, void *opts_, const char *field, void* value); - -/* memory */ -// -acados_size_t ocp_qp_xcond_solver_memory_calculate_size(void *config, ocp_qp_xcond_solver_dims *dims, void *opts_); -// -void *ocp_qp_xcond_solver_memory_assign(void *config, ocp_qp_xcond_solver_dims *dims, void *opts_, void *raw_memory); - -/* workspace */ -// -acados_size_t ocp_qp_xcond_solver_workspace_calculate_size(void *config, ocp_qp_xcond_solver_dims *dims, void *opts_); - -/* config */ -// -int ocp_qp_xcond_solver(void *config, ocp_qp_xcond_solver_dims *dims, ocp_qp_in *qp_in, ocp_qp_out *qp_out, void *opts_, void *mem_, void *work_); - -// -void ocp_qp_xcond_solver_config_initialize_default(void *config_); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_OCP_QP_OCP_QP_PARTIAL_CONDENSING_SOLVER_H_ diff --git a/third_party/acados/include/acados/sim/sim_collocation_utils.h b/third_party/acados/include/acados/sim/sim_collocation_utils.h deleted file mode 100644 index 045d165cbc..0000000000 --- a/third_party/acados/include/acados/sim/sim_collocation_utils.h +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -#ifndef ACADOS_SIM_SIM_COLLOCATION_UTILS_H_ -#define ACADOS_SIM_SIM_COLLOCATION_UTILS_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "acados/utils/types.h" - - - -// enum Newton_type_collocation -// { -// exact = 0, -// simplified_in, -// simplified_inis -// }; - - - -// typedef struct -// { -// enum Newton_type_collocation type; -// double *eig; -// double *low_tria; -// bool single; -// bool freeze; - -// double *transf1; -// double *transf2; - -// double *transf1_T; -// double *transf2_T; -// } Newton_scheme; - - -typedef enum -{ - GAUSS_LEGENDRE, - GAUSS_RADAU_IIA, -} sim_collocation_type; - - -// -// acados_size_t gauss_legendre_nodes_work_calculate_size(int ns); -// -// void gauss_legendre_nodes(int ns, double *nodes, void *raw_memory); -// -// acados_size_t gauss_simplified_work_calculate_size(int ns); -// // -// void gauss_simplified(int ns, Newton_scheme *scheme, void *work); -// -acados_size_t butcher_tableau_work_calculate_size(int ns); -// -// void calculate_butcher_tableau_from_nodes(int ns, double *nodes, double *b, double *A, void *work); -// -void calculate_butcher_tableau(int ns, sim_collocation_type collocation_type, double *c_vec, - double *b_vec, double *A_mat, void *work); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_SIM_SIM_COLLOCATION_UTILS_H_ diff --git a/third_party/acados/include/acados/sim/sim_common.h b/third_party/acados/include/acados/sim/sim_common.h deleted file mode 100644 index c4bbd6ed2b..0000000000 --- a/third_party/acados/include/acados/sim/sim_common.h +++ /dev/null @@ -1,221 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -#ifndef ACADOS_SIM_SIM_COMMON_H_ -#define ACADOS_SIM_SIM_COMMON_H_ - -#include - -#include "acados/sim/sim_collocation_utils.h" -#include "acados/utils/timing.h" -#include "acados/utils/types.h" - -#include "acados/utils/external_function_generic.h" - -// maximum number of integration stages -#define NS_MAX 15 - - - -typedef enum -{ - // ERK and LIFTED_ERK - EXPL_ODE_FUN, - EXPL_ODE_HES, // wrt x and u ??? - EXPL_VDE_FOR, - EXPL_VDE_ADJ, - // IRK - IMPL_ODE_FUN, - IMPL_ODE_FUN_JAC_X_XDOT, - IMPL_ODE_JAC_X_XDOT_U, - IMPL_ODE_FUN_JAC_X_XDOT_U, - IMPL_ODE_HESS, - // gnsf - PHI_FUN, - PHI_FUN_JAC_Y, - PHI_JAC_Y_UHAT, - LO_FUN, - GET_GNSF_MATRICES -} sim_function_t; - - - -typedef struct -{ - void *dims; - - double *x; // x[NX] - initial state value for simulation - double *u; // u[NU] - control - constant over simulation time - - double *S_forw; // forward seed [Sx, Su] - double *S_adj; // backward seed - - bool identity_seed; // indicating if S_forw = [eye(nx), zeros(nx x nu)] - - void *model; - - double T; // simulation time - -} sim_in; - - - -typedef struct -{ - double CPUtime; // in seconds - double LAtime; // in seconds - double ADtime; // in seconds - -} sim_info; - - - -typedef struct -{ - double *xn; // xn[NX] - double *S_forw; // S_forw[NX*(NX+NU)] - double *S_adj; // - double *S_hess; // - - double *zn; // z - algebraic variables - reported at start of simulation interval - double *S_algebraic; // sensitivities of reported value of algebraic variables w.r.t. - // initial stat & control (x_n,u) - - double *grad; // gradient correction - - sim_info *info; - -} sim_out; - - - -typedef struct -{ - int ns; // number of integration stages - - int num_steps; - int num_forw_sens; - - int tableau_size; // check that is consistent with ns - // only update when butcher tableau is changed - // kind of private -> no setter! - double *A_mat; - double *c_vec; - double *b_vec; - - bool sens_forw; - bool sens_adj; - bool sens_hess; - - bool output_z; // 1 -- if zn should be computed - bool sens_algebraic; // 1 -- if S_algebraic should be computed - bool exact_z_output; // 1 -- if z, S_algebraic should be computed exactly, extra Newton iterations - sim_collocation_type collocation_type; - - // for explicit integrators: newton_iter == 0 && scheme == NULL - // && jac_reuse=false - int newton_iter; - bool jac_reuse; - // Newton_scheme *scheme; - - double newton_tol; // optinally used in implicit integrators - - // workspace - void *work; - -} sim_opts; - - - -typedef struct -{ - int (*evaluate)(void *config_, sim_in *in, sim_out *out, void *opts, void *mem, void *work); - int (*precompute)(void *config_, sim_in *in, sim_out *out, void *opts, void *mem, void *work); - // opts - acados_size_t (*opts_calculate_size)(void *config_, void *dims); - void *(*opts_assign)(void *config_, void *dims, void *raw_memory); - void (*opts_initialize_default)(void *config_, void *dims, void *opts); - void (*opts_update)(void *config_, void *dims, void *opts); - void (*opts_set)(void *config_, void *opts_, const char *field, void *value); - void (*opts_get)(void *config_, void *opts_, const char *field, void *value); - // mem - acados_size_t (*memory_calculate_size)(void *config, void *dims, void *opts); - void *(*memory_assign)(void *config, void *dims, void *opts, void *raw_memory); - int (*memory_set)(void *config, void *dims, void *mem, const char *field, void *value); - int (*memory_set_to_zero)(void *config, void *dims, void *opts, void *mem, const char *field); - void (*memory_get)(void *config, void *dims, void *mem, const char *field, void *value); - // work - acados_size_t (*workspace_calculate_size)(void *config, void *dims, void *opts); - // model - acados_size_t (*model_calculate_size)(void *config, void *dims); - void *(*model_assign)(void *config, void *dims, void *raw_memory); - int (*model_set)(void *model, const char *field, void *value); - // config - void (*config_initialize_default)(void *config); - // dims - acados_size_t (*dims_calculate_size)(); - void *(*dims_assign)(void *config, void *raw_memory); - void (*dims_set)(void *config, void *dims, const char *field, const int *value); - void (*dims_get)(void *config, void *dims, const char *field, int *value); - -} sim_config; - - - -/* config */ -// -acados_size_t sim_config_calculate_size(); -// -sim_config *sim_config_assign(void *raw_memory); - -/* in */ -// -acados_size_t sim_in_calculate_size(void *config, void *dims); -// -sim_in *sim_in_assign(void *config, void *dims, void *raw_memory); -// -int sim_in_set_(void *config_, void *dims_, sim_in *in, const char *field, void *value); - -/* out */ -// -acados_size_t sim_out_calculate_size(void *config, void *dims); -// -sim_out *sim_out_assign(void *config, void *dims, void *raw_memory); -// -int sim_out_get_(void *config, void *dims, sim_out *out, const char *field, void *value); - -/* opts */ -// -void sim_opts_set_(sim_opts *opts, const char *field, void *value); -// -void sim_opts_get_(sim_config *config, sim_opts *opts, const char *field, void *value); - -#endif // ACADOS_SIM_SIM_COMMON_H_ diff --git a/third_party/acados/include/acados/sim/sim_erk_integrator.h b/third_party/acados/include/acados/sim/sim_erk_integrator.h deleted file mode 100644 index fd46cb4d99..0000000000 --- a/third_party/acados/include/acados/sim/sim_erk_integrator.h +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -#ifndef ACADOS_SIM_SIM_ERK_INTEGRATOR_H_ -#define ACADOS_SIM_SIM_ERK_INTEGRATOR_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "acados/sim/sim_common.h" -#include "acados/utils/types.h" - - - -typedef struct -{ - int nx; - int nu; - int nz; -} sim_erk_dims; - - - -typedef struct -{ - /* external functions */ - // explicit ode - external_function_generic *expl_ode_fun; - // hessian explicit ode - external_function_generic *expl_ode_hes; - // forward explicit vde - external_function_generic *expl_vde_for; - // adjoint explicit vde - external_function_generic *expl_vde_adj; - -} erk_model; - - - -typedef struct -{ - // memory - double time_sim; - double time_ad; - double time_la; - - // workspace structs -} sim_erk_memory; - - - -typedef struct -{ - // workspace mem - double *rhs_forw_in; // x + S + p - - double *K_traj; // (stages*nX) or (steps*stages*nX) for adj - double *out_forw_traj; // S or (steps+1)*nX for adj - - double *rhs_adj_in; - double *out_adj_tmp; - double *adj_traj; - -} sim_erk_workspace; - - - -// dims -acados_size_t sim_erk_dims_calculate_size(); -void *sim_erk_dims_assign(void *config_, void *raw_memory); -void sim_erk_dims_set(void *config_, void *dims_, const char *field, const int* value); -void sim_erk_dims_get(void *config_, void *dims_, const char *field, int* value); - -// model -acados_size_t sim_erk_model_calculate_size(void *config, void *dims); -void *sim_erk_model_assign(void *config, void *dims, void *raw_memory); -int sim_erk_model_set(void *model, const char *field, void *value); - -// opts -acados_size_t sim_erk_opts_calculate_size(void *config, void *dims); -// -void sim_erk_opts_update(void *config_, void *dims, void *opts_); -// -void *sim_erk_opts_assign(void *config, void *dims, void *raw_memory); -// -void sim_erk_opts_initialize_default(void *config, void *dims, void *opts_); -// -void sim_erk_opts_set(void *config_, void *opts_, const char *field, void *value); - - -// memory -acados_size_t sim_erk_memory_calculate_size(void *config, void *dims, void *opts_); -// -void *sim_erk_memory_assign(void *config, void *dims, void *opts_, void *raw_memory); -// -int sim_erk_memory_set(void *config_, void *dims_, void *mem_, const char *field, void *value); - - -// workspace -acados_size_t sim_erk_workspace_calculate_size(void *config, void *dims, void *opts_); - -// -int sim_erk(void *config, sim_in *in, sim_out *out, void *opts_, void *mem_, void *work_); -// -void sim_erk_config_initialize_default(void *config); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_SIM_SIM_ERK_INTEGRATOR_H_ diff --git a/third_party/acados/include/acados/sim/sim_gnsf.h b/third_party/acados/include/acados/sim/sim_gnsf.h deleted file mode 100644 index 404532a732..0000000000 --- a/third_party/acados/include/acados/sim/sim_gnsf.h +++ /dev/null @@ -1,364 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -#ifndef ACADOS_SIM_SIM_GNSF_H_ -#define ACADOS_SIM_SIM_GNSF_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include - -#include "acados/utils/timing.h" -#include "acados/utils/types.h" -#include "acados/sim/sim_common.h" - -#include "blasfeo/include/blasfeo_common.h" -// #include "blasfeo/include/blasfeo_d_aux.h" -// #include "blasfeo/include/blasfeo_d_aux_ext_dep.h" -// #include "blasfeo/include/blasfeo_d_blas.h" -// #include "blasfeo/include/blasfeo_d_kernel.h" -// #include "blasfeo/include/blasfeo_i_aux_ext_dep.h" -// #include "blasfeo/include/blasfeo_target.h" - -/* -GNSF - Generalized Nonlinear Static Feedback Model -has the following form -https://github.com/acados/acados/files/3359595/gnsf_structure_blo.pdf - -Details on the algorithm can be found in master thesis of Jonathan Frey, -which presents a slightly different format without the terms B_LO, c_LO. -https://github.com/acados/acados/files/2318322/gnsf_structure.pdf -https://cdn.syscop.de/publications/Frey2018.pdf -https://cdn.syscop.de/publications/Frey2019.pdf -*/ - -typedef struct -{ - int nx; // total number of differential states - int nu; // total number of inputs - int nz; // total number of algebraic states - int nx1; // number of differential states in NSF part - int nz1; // number of algebraic states in NSF part - int n_out; // output dimension of phi - int ny; // dimension of first input of phi - int nuhat; // dimension of second input of phi - -} sim_gnsf_dims; - - - -typedef struct -{ - /* external functions */ - // phi: nonlinearity function - external_function_generic *phi_fun; - external_function_generic *phi_fun_jac_y; - external_function_generic *phi_jac_y_uhat; - - // f_lo: linear output function - external_function_generic *f_lo_fun_jac_x1_x1dot_u_z; - - // to import model matrices - external_function_generic *get_gnsf_matrices; - - // flag indicating, if model defining matrices are imported via external (casadi) function, - // [default]: true -> auto; - bool auto_import_gnsf; - - // booleans from structure detection - bool nontrivial_f_LO; // indicates if f_LO is constant zero function - bool fully_linear; // indicates if model is fully linear LOS - - /* model defining matrices */ - // TODO: add setters to set manually - double *A; - double *B; - double *C; - double *E; - - double *L_x; - double *L_xdot; - double *L_z; - double *L_u; - - double *A_LO; - double *B_LO; - double *E_LO; - - /* constant vector */ - double *c; - double *c_LO; - - // permutation vector - to have GNSF order of x, z within sim_gnsf only - int *ipiv_x; - int *ipiv_z; - - double *ipiv_x_double; - double *ipiv_z_double; - -} gnsf_model; - - - -// pre_workspace - workspace used in the precomputation phase -typedef struct -{ - struct blasfeo_dmat E11; - struct blasfeo_dmat E12; - struct blasfeo_dmat E21; - struct blasfeo_dmat E22; - - struct blasfeo_dmat A1; - struct blasfeo_dmat A2; - struct blasfeo_dmat B1; - struct blasfeo_dmat B2; - struct blasfeo_dmat C1; - struct blasfeo_dmat C2; - - struct blasfeo_dmat AA1; - struct blasfeo_dmat AA2; - struct blasfeo_dmat BB1; - struct blasfeo_dmat BB2; - struct blasfeo_dmat CC1; - struct blasfeo_dmat CC2; - struct blasfeo_dmat DD1; - struct blasfeo_dmat DD2; - struct blasfeo_dmat EE1; - struct blasfeo_dmat EE2; - - struct blasfeo_dmat QQ1; - - struct blasfeo_dmat LLZ; - struct blasfeo_dmat LLx; - struct blasfeo_dmat LLK; - - int *ipivEE1; // index of pivot vector - int *ipivEE2; - int *ipivQQ1; - - // for algebraic sensitivity propagation - struct blasfeo_dmat Q1; - - // for constant term in NSF - struct blasfeo_dvec cc1; - struct blasfeo_dvec cc2; - -} gnsf_pre_workspace; - - - -// workspace -typedef struct -{ - double *Z_work; // used to perform computations to get out->zn - - int *ipiv; // index of pivot vector - - struct blasfeo_dvec *vv_traj; - struct blasfeo_dvec *yy_traj; - struct blasfeo_dmat *f_LO_jac_traj; - - struct blasfeo_dvec K2_val; - struct blasfeo_dvec x0_traj; - struct blasfeo_dvec res_val; - struct blasfeo_dvec u0; - struct blasfeo_dvec lambda; - struct blasfeo_dvec lambda_old; - - struct blasfeo_dvec yyu; - struct blasfeo_dvec yyss; - - struct blasfeo_dvec K1_val; - struct blasfeo_dvec f_LO_val; - struct blasfeo_dvec x1_stage_val; - struct blasfeo_dvec Z1_val; - - struct blasfeo_dvec K1u; - struct blasfeo_dvec Zu; - struct blasfeo_dvec ALOtimesx02; - struct blasfeo_dvec BLOtimesu0; - - struct blasfeo_dvec uhat; - - struct blasfeo_dmat J_r_vv; - struct blasfeo_dmat J_r_x1u; - - struct blasfeo_dmat dK1_dx1; - struct blasfeo_dmat dK1_du; - struct blasfeo_dmat dZ_dx1; - struct blasfeo_dmat dZ_du; - struct blasfeo_dmat J_G2_K1; - - struct blasfeo_dmat dK2_dx1; - struct blasfeo_dmat dK2_dvv; - struct blasfeo_dmat dxf_dwn; - struct blasfeo_dmat S_forw_new; - struct blasfeo_dmat S_algebraic_aux; - - struct blasfeo_dmat dPsi_dvv; - struct blasfeo_dmat dPsi_dx; - struct blasfeo_dmat dPsi_du; - - struct blasfeo_dmat dPHI_dyuhat; - struct blasfeo_dvec z0; - - // memory only available if (opts->sens_algebraic) - // struct blasfeo_dvec y_one_stage; - // struct blasfeo_dvec x0dot_1; - // struct blasfeo_dmat dz10_dx1u; // (nz1) * (nx1+nu); - // struct blasfeo_dmat dr0_dvv0; // (n_out * n_out) - // struct blasfeo_dmat f_LO_jac0; // (nx2+nz2) * (2*nx1 + nz1 + nu) - // struct blasfeo_dmat sens_z2_rhs; // (nx2 + nz2) * (nx1 + nu) - // int *ipiv_vv0; - -} gnsf_workspace; - - - -// memory -typedef struct -{ - bool first_call; - - // simulation time for one step - double dt; - - // (scaled) butcher table - double *A_dt; - double *b_dt; - double *c_butcher; - - // value used to initialize integration variables - corresponding to value of phi - double *phi_guess; // n_out - - struct blasfeo_dmat S_forw; - struct blasfeo_dmat S_algebraic; - - // precomputed matrices - struct blasfeo_dmat KKv; - struct blasfeo_dmat KKx; - struct blasfeo_dmat KKu; - - struct blasfeo_dmat YYv; - struct blasfeo_dmat YYx; - struct blasfeo_dmat YYu; - - struct blasfeo_dmat ZZv; - struct blasfeo_dmat ZZx; - struct blasfeo_dmat ZZu; - - struct blasfeo_dmat ALO; - struct blasfeo_dmat BLO; - struct blasfeo_dmat M2_LU; - int *ipivM2; - - struct blasfeo_dmat dK2_dx2; - struct blasfeo_dmat dK2_du; - struct blasfeo_dmat dx2f_dx2u; - - struct blasfeo_dmat Lu; - - // precomputed vectors for constant term in NSF - struct blasfeo_dvec KK0; - struct blasfeo_dvec YY0; - struct blasfeo_dvec ZZ0; - - // for algebraic sensitivities only; - // struct blasfeo_dmat *Z0x; - // struct blasfeo_dmat *Z0u; - // struct blasfeo_dmat *Z0v; - - // struct blasfeo_dmat *Y0x; - // struct blasfeo_dmat *Y0u; - // struct blasfeo_dmat *Y0v; - - // struct blasfeo_dmat *K0x; - // struct blasfeo_dmat *K0u; - // struct blasfeo_dmat *K0v; - - // struct blasfeo_dmat *ELO_LU; - // int *ipiv_ELO; - // struct blasfeo_dmat *ELO_inv_ALO; - - // struct blasfeo_dmat *Lx; - // struct blasfeo_dmat *Lxdot; - // struct blasfeo_dmat *Lz; - - double time_sim; - double time_ad; - double time_la; - -} sim_gnsf_memory; - - - -// gnsf dims -acados_size_t sim_gnsf_dims_calculate_size(); -void *sim_gnsf_dims_assign(void *config_, void *raw_memory); - -// get & set functions -void sim_gnsf_dims_set(void *config_, void *dims_, const char *field, const int *value); -void sim_gnsf_dims_get(void *config_, void *dims_, const char *field, int* value); - -// opts -acados_size_t sim_gnsf_opts_calculate_size(void *config, void *dims); -void *sim_gnsf_opts_assign(void *config, void *dims, void *raw_memory); -void sim_gnsf_opts_initialize_default(void *config, void *dims, void *opts_); -void sim_gnsf_opts_update(void *config_, void *dims, void *opts_); -void sim_gnsf_opts_set(void *config_, void *opts_, const char *field, void *value); - -// model -acados_size_t sim_gnsf_model_calculate_size(void *config, void *dims_); -void *sim_gnsf_model_assign(void *config, void *dims_, void *raw_memory); -int sim_gnsf_model_set(void *model_, const char *field, void *value); - -// precomputation -int sim_gnsf_precompute(void *config_, sim_in *in, sim_out *out, void *opts_, void *mem_, - void *work_); - -// workspace & memory -acados_size_t sim_gnsf_workspace_calculate_size(void *config, void *dims_, void *args); -acados_size_t sim_gnsf_memory_calculate_size(void *config, void *dims_, void *opts_); -void *sim_gnsf_memory_assign(void *config, void *dims_, void *opts_, void *raw_memory); - -// interface -void sim_gnsf_config_initialize_default(void *config_); - -// integrator -int sim_gnsf(void *config, sim_in *in, sim_out *out, void *opts, void *mem_, void *work_); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_SIM_SIM_GNSF_H_ diff --git a/third_party/acados/include/acados/sim/sim_irk_integrator.h b/third_party/acados/include/acados/sim/sim_irk_integrator.h deleted file mode 100644 index 5090aa0bb5..0000000000 --- a/third_party/acados/include/acados/sim/sim_irk_integrator.h +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -#ifndef ACADOS_SIM_SIM_IRK_INTEGRATOR_H_ -#define ACADOS_SIM_SIM_IRK_INTEGRATOR_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "acados/sim/sim_common.h" -#include "acados/utils/types.h" - -#include "blasfeo/include/blasfeo_common.h" - -typedef struct -{ - int nx; - int nu; - int nz; - -} sim_irk_dims; - - - -typedef struct -{ - /* external functions */ - // implicit fun - can either be fully implicit ode or dae - // - i.e. dae has z as additional last argument & nz > 0 - external_function_generic *impl_ode_fun; - // implicit ode & jac_x & jax_xdot & jac_z - external_function_generic *impl_ode_fun_jac_x_xdot_z; - // jax_x & jac_xdot & jac_u & jac_z of implicit ode - external_function_generic *impl_ode_jac_x_xdot_u_z; - // hessian of implicit ode: - external_function_generic *impl_ode_hess; -} irk_model; - - - -typedef struct -{ - struct blasfeo_dvec *rG; // residuals of G (nx*ns) - struct blasfeo_dvec *K; // internal K variables ((nx+nz)*ns) - struct blasfeo_dvec *xt; // temporary x - struct blasfeo_dvec *xn; // x at each integration step - struct blasfeo_dvec xtdot; // temporary xdot - - struct blasfeo_dvec *lambda; // adjoint sensitivities (nx + nu) - struct blasfeo_dvec *lambdaK; // auxiliary variable ((nx+nz)*ns) for adjoint propagation - - struct blasfeo_dmat df_dx; // temporary Jacobian of ode w.r.t x (nx+nz, nx) - struct blasfeo_dmat df_dxdot; // temporary Jacobian of ode w.r.t xdot (nx+nz, nx) - struct blasfeo_dmat df_du; // temporary Jacobian of ode w.r.t u (nx+nz, nu) - struct blasfeo_dmat df_dz; // temporary Jacobian of ode w.r.t z (nx+nz, nu) - - /* NOTE: the memory allocation corresponding to the following fields is CONDITIONAL */ - - // only allocated if (opts->sens_algebraic || opts->output_z) - int *ipiv_one_stage; // index of pivot vector (nx + nz) - double *Z_work; // used to perform computations to get out->zn (ns) - - // df_dxdotz, dk0_dxu, only allocated if (opts->sens_algebraic && opts->exact_z_output) - // used for algebraic sensitivity generation - struct blasfeo_dmat df_dxdotz; // temporary Jacobian of ode w.r.t. xdot,z (nx+nz, nx+nz); - struct blasfeo_dmat dk0_dxu; // intermediate result, (nx+nz, nx+nu) - - // dK_dxu: if (!opts->sens_hess) - single blasfeo_dmat that is reused - // if ( opts->sens_hess) - array of (num_steps) blasfeo_dmat - // to store intermediate results - struct blasfeo_dmat *dK_dxu; // jacobian of (K,Z) over x and u ((nx+nz)*ns, nx+nu); - - // S_forw: if (!opts->sens_hess) - single blasfeo_dmat that is reused - // if ( opts->sens_hess) - array of (num_steps + 1) blasfeo_dmat - // to store intermediate results - struct blasfeo_dmat *S_forw; // forward sensitivities (nx, nx+nu) - - // dG_dxu: if (!opts->sens_hess) - single blasfeo_dmat that is reused - // if ( opts->sens_hess) - array of blasfeo_dmat to store intermediate results - struct blasfeo_dmat *dG_dxu; // jacobian of G over x and u ((nx+nz)*ns, nx+nu) - - // dG_dK: if (!opts->sens_hess) - single blasfeo_dmat that is reused - // if ( opts->sens_hess) - array of blasfeo_dmat to store intermediate results - struct blasfeo_dmat *dG_dK; // jacobian of G over K ((nx+nz)*ns, (nx+nz)*ns) - - // ipiv: index of pivot vector - // if (!opts->sens_hess) - array (ns * (nx + nz)) that is reused - // if ( opts->sens_hess) - array (ns * (nx + nz)) * num_steps, to store all - // pivot vectors for dG_dxu - int *ipiv; // index of pivot vector - - // xn_traj, K_traj only available if( opts->sens_adj || opts->sens_hess ) - struct blasfeo_dvec *xn_traj; // xn trajectory - struct blasfeo_dvec *K_traj; // K trajectory - - /* the following variables are only available if (opts->sens_hess) */ - // For Hessian propagation - struct blasfeo_dmat Hess; // temporary Hessian (nx + nu, nx + nu) - // output of impl_ode_hess - struct blasfeo_dmat f_hess; // size: (nx + nu, nx + nu) - struct blasfeo_dmat dxkzu_dw0; // size (2*nx + nu + nz) x (nx + nu) - struct blasfeo_dmat tmp_dxkzu_dw0; // size (2*nx + nu + nz) x (nx + nu) - -} sim_irk_workspace; - - -typedef struct -{ - double *xdot; // xdot[NX] - initialization for state derivatives k within the integrator - double *z; // z[NZ] - initialization for algebraic variables z - - double time_sim; - double time_ad; - double time_la; -} sim_irk_memory; - - -// get & set functions -void sim_irk_dims_set(void *config_, void *dims_, const char *field, const int *value); -void sim_irk_dims_get(void *config_, void *dims_, const char *field, int* value); - -// dims -acados_size_t sim_irk_dims_calculate_size(); -void *sim_irk_dims_assign(void *config_, void *raw_memory); - -// model -acados_size_t sim_irk_model_calculate_size(void *config, void *dims); -void *sim_irk_model_assign(void *config, void *dims, void *raw_memory); -int sim_irk_model_set(void *model, const char *field, void *value); - -// opts -acados_size_t sim_irk_opts_calculate_size(void *config, void *dims); -void *sim_irk_opts_assign(void *config, void *dims, void *raw_memory); -void sim_irk_opts_initialize_default(void *config, void *dims, void *opts_); -void sim_irk_opts_update(void *config_, void *dims, void *opts_); -void sim_irk_opts_set(void *config_, void *opts_, const char *field, void *value); - -// memory -acados_size_t sim_irk_memory_calculate_size(void *config, void *dims, void *opts_); -void *sim_irk_memory_assign(void *config, void *dims, void *opts_, void *raw_memory); -int sim_irk_memory_set(void *config_, void *dims_, void *mem_, const char *field, void *value); - -// workspace -acados_size_t sim_irk_workspace_calculate_size(void *config, void *dims, void *opts_); -void sim_irk_config_initialize_default(void *config); - -// main -int sim_irk(void *config, sim_in *in, sim_out *out, void *opts_, void *mem_, void *work_); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_SIM_SIM_IRK_INTEGRATOR_H_ diff --git a/third_party/acados/include/acados/sim/sim_lifted_irk_integrator.h b/third_party/acados/include/acados/sim/sim_lifted_irk_integrator.h deleted file mode 100644 index e60bb80ebf..0000000000 --- a/third_party/acados/include/acados/sim/sim_lifted_irk_integrator.h +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -#ifndef ACADOS_SIM_SIM_LIFTED_IRK_INTEGRATOR_H_ -#define ACADOS_SIM_SIM_LIFTED_IRK_INTEGRATOR_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "acados/sim/sim_common.h" -#include "acados/utils/types.h" - -typedef struct -{ - int nx; - int nu; - int nz; -} sim_lifted_irk_dims; - - - -typedef struct -{ - /* external functions */ - // implicit ode - external_function_generic *impl_ode_fun; - // implicit ode & jax_x & jac_xdot & jac_u implicit ode - external_function_generic *impl_ode_fun_jac_x_xdot_u; - -} lifted_irk_model; - - - -typedef struct -{ - - struct blasfeo_dmat *J_temp_x; // temporary Jacobian of ode w.r.t x (nx, nx) - struct blasfeo_dmat *J_temp_xdot; // temporary Jacobian of ode w.r.t xdot (nx, nx) - struct blasfeo_dmat *J_temp_u; // temporary Jacobian of ode w.r.t u (nx, nu) - - struct blasfeo_dvec *rG; // residuals of G (nx*ns) - struct blasfeo_dvec *xt; // temporary x - struct blasfeo_dvec *xn; // x at each integration step (for evaluations) - struct blasfeo_dvec *xn_out; // x at each integration step (output) - struct blasfeo_dvec *dxn; // dx at each integration step - struct blasfeo_dvec *w; // stacked x and u - - int *ipiv; // index of pivot vector - -} sim_lifted_irk_workspace; - - - -typedef struct -{ - // memory for lifted integrators - struct blasfeo_dmat *S_forw; // forward sensitivities - struct blasfeo_dmat *JGK; // jacobian of G over K (nx*ns, nx*ns) - struct blasfeo_dmat *JGf; // jacobian of G over x and u (nx*ns, nx+nu); - struct blasfeo_dmat *JKf; // jacobian of K over x and u (nx*ns, nx+nu); - - struct blasfeo_dvec *K; // internal variables (nx*ns) - struct blasfeo_dvec *x; // states (nx) -- for expansion step - struct blasfeo_dvec *u; // controls (nu) -- for expansion step - - int update_sens; - // int init_K; - - double time_sim; - double time_ad; - double time_la; - -} sim_lifted_irk_memory; - - - -/* dims */ -void sim_lifted_irk_dims_set(void *config_, void *dims_, const char *field, const int *value); -void sim_lifted_irk_dims_get(void *config_, void *dims_, const char *field, int* value); - -acados_size_t sim_lifted_irk_dims_calculate_size(); -// -void *sim_lifted_irk_dims_assign(void* config_, void *raw_memory); - -/* model */ -// -acados_size_t sim_lifted_irk_model_calculate_size(void *config, void *dims); -// -void *sim_lifted_irk_model_assign(void *config, void *dims, void *raw_memory); -// -int sim_lifted_irk_model_set(void *model_, const char *field, void *value); - -/* opts */ -// -acados_size_t sim_lifted_irk_opts_calculate_size(void *config, void *dims); -// -void *sim_lifted_irk_opts_assign(void *config, void *dims, void *raw_memory); -// -void sim_lifted_irk_opts_initialize_default(void *config, void *dims, void *opts_); -// -void sim_lifted_irk_opts_update(void *config_, void *dims, void *opts_); -// -void sim_lifted_irk_opts_set(void *config_, void *opts_, const char *field, void *value); - -/* memory */ -// -acados_size_t sim_lifted_irk_memory_calculate_size(void *config, void *dims, void *opts_); -// -void *sim_lifted_irk_memory_assign(void *config, void *dims, void *opts_, void *raw_memory); - -/* workspace */ -// -acados_size_t sim_lifted_irk_workspace_calculate_size(void *config, void *dims, void *opts_); -// -void sim_lifted_irk_config_initialize_default(void *config); - -/* solver */ -// -int sim_lifted_irk(void *config, sim_in *in, sim_out *out, void *opts_, - void *mem_, void *work_); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_SIM_SIM_LIFTED_IRK_INTEGRATOR_H_ diff --git a/third_party/acados/include/acados/utils/external_function_generic.h b/third_party/acados/include/acados/utils/external_function_generic.h deleted file mode 100644 index 1e68dc155d..0000000000 --- a/third_party/acados/include/acados/utils/external_function_generic.h +++ /dev/null @@ -1,242 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -#ifndef ACADOS_UTILS_EXTERNAL_FUNCTION_GENERIC_H_ -#define ACADOS_UTILS_EXTERNAL_FUNCTION_GENERIC_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "acados/utils/types.h" - -/************************************************ - * generic external function - ************************************************/ - -// type of arguments -typedef enum { - COLMAJ, - BLASFEO_DMAT, - BLASFEO_DVEC, - COLMAJ_ARGS, - BLASFEO_DMAT_ARGS, - BLASFEO_DVEC_ARGS, - IGNORE_ARGUMENT -} ext_fun_arg_t; - -struct colmaj_args -{ - double *A; - int lda; -}; - -struct blasfeo_dmat_args -{ - struct blasfeo_dmat *A; - int ai; - int aj; -}; - -struct blasfeo_dvec_args -{ - struct blasfeo_dvec *x; - int xi; -}; - -// prototype of an external function -typedef struct -{ - // public members (have to be before private ones) - void (*evaluate)(void *, ext_fun_arg_t *, void **, ext_fun_arg_t *, void **); - // private members - // ..... -} external_function_generic; - - - -/************************************************ - * generic external parametric function - ************************************************/ - -// prototype of a parametric external function -typedef struct -{ - // public members for core (have to be before private ones) - void (*evaluate)(void *, ext_fun_arg_t *, void **, ext_fun_arg_t *, void **); - // public members for interfaces - void (*get_nparam)(void *, int *); - void (*set_param)(void *, double *); - void (*set_param_sparse)(void *, int n_update, int *idx, double *); - // private members - void *ptr_ext_mem; // pointer to external memory - int (*fun)(void **, void **, void *); - double *p; // parameters - int np; // number of parameters - // ..... -} external_function_param_generic; - -// -acados_size_t external_function_param_generic_struct_size(); -// -void external_function_param_generic_set_fun(external_function_param_generic *fun, void *value); -// -acados_size_t external_function_param_generic_calculate_size(external_function_param_generic *fun, int np); -// -void external_function_param_generic_assign(external_function_param_generic *fun, void *mem); -// -void external_function_param_generic_wrapper(void *self, ext_fun_arg_t *type_in, void **in, ext_fun_arg_t *type_out, void **out); -// -void external_function_param_generic_get_nparam(void *self, int *np); -// -void external_function_param_generic_set_param(void *self, double *p); - - -/************************************************ - * casadi external function - ************************************************/ - -typedef struct -{ - // public members (have to be the same as in the prototype, and before the private ones) - void (*evaluate)(void *, ext_fun_arg_t *, void **, ext_fun_arg_t *, void **); - // private members - void *ptr_ext_mem; // pointer to external memory - int (*casadi_fun)(const double **, double **, int *, double *, void *); - int (*casadi_work)(int *, int *, int *, int *); - const int *(*casadi_sparsity_in)(int); - const int *(*casadi_sparsity_out)(int); - int (*casadi_n_in)(void); - int (*casadi_n_out)(void); - double **args; - double **res; - double *w; - int *iw; - int *args_size; // size of args[i] - int *res_size; // size of res[i] - int args_num; // number of args arrays - int args_size_tot; // total size of args arrays - int res_num; // number of res arrays - int res_size_tot; // total size of res arrays - int in_num; // number of input arrays - int out_num; // number of output arrays - int iw_size; // number of ints for worksapce - int w_size; // number of doubles for workspace -} external_function_casadi; - -// -acados_size_t external_function_casadi_struct_size(); -// -void external_function_casadi_set_fun(external_function_casadi *fun, void *value); -// -void external_function_casadi_set_work(external_function_casadi *fun, void *value); -// -void external_function_casadi_set_sparsity_in(external_function_casadi *fun, void *value); -// -void external_function_casadi_set_sparsity_out(external_function_casadi *fun, void *value); -// -void external_function_casadi_set_n_in(external_function_casadi *fun, void *value); -// -void external_function_casadi_set_n_out(external_function_casadi *fun, void *value); -// -acados_size_t external_function_casadi_calculate_size(external_function_casadi *fun); -// -void external_function_casadi_assign(external_function_casadi *fun, void *mem); -// -void external_function_casadi_wrapper(void *self, ext_fun_arg_t *type_in, void **in, - ext_fun_arg_t *type_out, void **out); - -/************************************************ - * casadi external parametric function - ************************************************/ - -typedef struct -{ - // public members for core (have to be the same as in the prototype, and before the private ones) - void (*evaluate)(void *, ext_fun_arg_t *, void **, ext_fun_arg_t *, void **); - // public members for interfaces - void (*get_nparam)(void *, int *); - void (*set_param)(void *, double *); - void (*set_param_sparse)(void *, int n_update, int *idx, double *); - // private members - void *ptr_ext_mem; // pointer to external memory - int (*casadi_fun)(const double **, double **, int *, double *, void *); - int (*casadi_work)(int *, int *, int *, int *); - const int *(*casadi_sparsity_in)(int); - const int *(*casadi_sparsity_out)(int); - int (*casadi_n_in)(void); - int (*casadi_n_out)(void); - double **args; - double **res; - double *w; - int *iw; - int *args_size; // size of args[i] - int *res_size; // size of res[i] - int args_num; // number of args arrays - int args_size_tot; // total size of args arrays - int res_num; // number of res arrays - int res_size_tot; // total size of res arrays - int in_num; // number of input arrays - int out_num; // number of output arrays - int iw_size; // number of ints for worksapce - int w_size; // number of doubles for workspace - int np; // number of parameters -} external_function_param_casadi; - -// -acados_size_t external_function_param_casadi_struct_size(); -// -void external_function_param_casadi_set_fun(external_function_param_casadi *fun, void *value); -// -void external_function_param_casadi_set_work(external_function_param_casadi *fun, void *value); -// -void external_function_param_casadi_set_sparsity_in(external_function_param_casadi *fun, void *value); -// -void external_function_param_casadi_set_sparsity_out(external_function_param_casadi *fun, void *value); -// -void external_function_param_casadi_set_n_in(external_function_param_casadi *fun, void *value); -// -void external_function_param_casadi_set_n_out(external_function_param_casadi *fun, void *value); -// -acados_size_t external_function_param_casadi_calculate_size(external_function_param_casadi *fun, int np); -// -void external_function_param_casadi_assign(external_function_param_casadi *fun, void *mem); -// -void external_function_param_casadi_wrapper(void *self, ext_fun_arg_t *type_in, void **in, - ext_fun_arg_t *type_out, void **out); -// -void external_function_param_casadi_get_nparam(void *self, int *np); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_UTILS_EXTERNAL_FUNCTION_GENERIC_H_ diff --git a/third_party/acados/include/acados/utils/math.h b/third_party/acados/include/acados/utils/math.h deleted file mode 100644 index 7156a82084..0000000000 --- a/third_party/acados/include/acados/utils/math.h +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - -#ifndef ACADOS_UTILS_MATH_H_ -#define ACADOS_UTILS_MATH_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "acados/utils/types.h" - -#if defined(__MABX2__) -double fmax(double a, double b); -int isnan(double x); -#endif - -#define MIN(a,b) (((a)<(b))?(a):(b)) -#define MAX(a,b) (((a)>(b))?(a):(b)) - -void dgemm_nn_3l(int m, int n, int k, double *A, int lda, double *B, int ldb, double *C, int ldc); -// void dgemv_n_3l(int m, int n, double *A, int lda, double *x, double *y); -// void dgemv_t_3l(int m, int n, double *A, int lda, double *x, double *y); -// void dcopy_3l(int n, double *x, int incx, double *y, int incy); -void daxpy_3l(int n, double da, double *dx, double *dy); -void dscal_3l(int n, double da, double *dx); -double twonormv(int n, double *ptrv); - -/* copies a matrix into another matrix */ -void dmcopy(int row, int col, double *ptrA, int lda, double *ptrB, int ldb); - -/* solution of a system of linear equations */ -void dgesv_3l(int n, int nrhs, double *A, int lda, int *ipiv, double *B, int ldb, int *info); - -/* matrix exponential */ -void expm(int row, double *A); - -int idamax_3l(int n, double *x); - -void dswap_3l(int n, double *x, int incx, double *y, int incy); - -void dger_3l(int m, int n, double alpha, double *x, int incx, double *y, int incy, double *A, - int lda); - -void dgetf2_3l(int m, int n, double *A, int lda, int *ipiv, int *info); - -void dlaswp_3l(int n, double *A, int lda, int k1, int k2, int *ipiv); - -void dtrsm_l_l_n_u_3l(int m, int n, double *A, int lda, double *B, int ldb); - -void dgetrs_3l(int n, int nrhs, double *A, int lda, int *ipiv, double *B, int ldb); - -void dgesv_3l(int n, int nrhs, double *A, int lda, int *ipiv, double *B, int ldb, int *info); - -double onenorm(int row, int col, double *ptrA); - -// double twonormv(int n, double *ptrv); - -void padeapprox(int m, int row, double *A); - -void expm(int row, double *A); - -// void d_compute_qp_size_ocp2dense_rev(int N, int *nx, int *nu, int *nb, int **hidxb, int *ng, -// int *nvd, int *ned, int *nbd, int *ngd); - -void acados_eigen_decomposition(int dim, double *A, double *V, double *d, double *e); - -double minimum_of_doubles(double *x, int n); - -void neville_algorithm(double xx, int n, double *x, double *Q, double *out); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_UTILS_MATH_H_ diff --git a/third_party/acados/include/acados/utils/mem.h b/third_party/acados/include/acados/utils/mem.h deleted file mode 100644 index 681a371e36..0000000000 --- a/third_party/acados/include/acados/utils/mem.h +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -#ifndef ACADOS_UTILS_MEM_H_ -#define ACADOS_UTILS_MEM_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include -#include - -#include "types.h" - -// blasfeo -#include "blasfeo/include/blasfeo_d_aux.h" -#include "blasfeo/include/blasfeo_d_aux_ext_dep.h" - -// TODO(dimitris): probably does not belong here -typedef struct -{ - int (*fun)(void *); - acados_size_t (*calculate_args_size)(void *); - void *(*assign_args)(void *); - void (*initialize_default_args)(void *); - acados_size_t (*calculate_memory_size)(void *); - void *(*assign_memory)(void *); - acados_size_t (*calculate_workspace_size)(void *); -} module_solver; - -// make int counter of memory multiple of a number (typically 8 or 64) -void make_int_multiple_of(acados_size_t num, acados_size_t *size); - -// align char pointer to number (typically 8 for pointers and doubles, -// 64 for blasfeo structs) and return offset -int align_char_to(int num, char **c_ptr); - -// switch between malloc and calloc (for valgrinding) -void *acados_malloc(size_t nitems, acados_size_t size); - -// uses always calloc -void *acados_calloc(size_t nitems, acados_size_t size); - -// allocate vector of pointers to vectors of doubles and advance pointer -void assign_and_advance_double_ptrs(int n, double ***v, char **ptr); - -// allocate vector of pointers to vectors of ints and advance pointer -void assign_and_advance_int_ptrs(int n, int ***v, char **ptr); - -// allocate vector of pointers to strvecs and advance pointer -void assign_and_advance_blasfeo_dvec_structs(int n, struct blasfeo_dvec **sv, char **ptr); - -// allocate vector of pointers to strmats and advance pointer -void assign_and_advance_blasfeo_dmat_structs(int n, struct blasfeo_dmat **sm, char **ptr); - -// allocate vector of pointers to vector of pointers to strmats and advance pointer -void assign_and_advance_blasfeo_dmat_ptrs(int n, struct blasfeo_dmat ***sm, char **ptr); - -// allocate vector of chars and advance pointer -void assign_and_advance_char(int n, char **v, char **ptr); - -// allocate vector of ints and advance pointer -void assign_and_advance_int(int n, int **v, char **ptr); - -// allocate vector of bools and advance pointer -void assign_and_advance_bool(int n, bool **v, char **ptr); - -// allocate vector of doubles and advance pointer -void assign_and_advance_double(int n, double **v, char **ptr); - -// allocate strvec and advance pointer -void assign_and_advance_blasfeo_dvec_mem(int n, struct blasfeo_dvec *sv, char **ptr); - -// allocate strmat and advance pointer -void assign_and_advance_blasfeo_dmat_mem(int m, int n, struct blasfeo_dmat *sA, char **ptr); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_UTILS_MEM_H_ diff --git a/third_party/acados/include/acados/utils/print.h b/third_party/acados/include/acados/utils/print.h deleted file mode 100644 index 824d3cee22..0000000000 --- a/third_party/acados/include/acados/utils/print.h +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -#ifndef ACADOS_UTILS_PRINT_H_ -#define ACADOS_UTILS_PRINT_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "acados/dense_qp/dense_qp_common.h" -#include "acados/ocp_nlp/ocp_nlp_common.h" -#include "acados/ocp_qp/ocp_qp_common.h" -#include "acados/ocp_qp/ocp_qp_common_frontend.h" -#include "acados/utils/types.h" - -// void print_matrix(char *file_name, const real_t *matrix, const int_t nrows, const int_t ncols); - -// void print_matrix_name(char *file_name, char *name, const real_t *matrix, const int_t nrows, -// const int_t ncols); - -// void print_int_matrix(char *file_name, const int_t *matrix, const int_t nrows, const int_t ncols); - -// void print_array(char *file_name, real_t *array, int_t size); - -// void print_int_array(char *file_name, const int_t *array, int_t size); - -void read_matrix(const char *file_name, real_t *array, const int_t nrows, const int_t ncols); - -void write_double_vector_to_txt(real_t *vec, int_t n, const char *fname); - -// ocp nlp -// TODO(andrea): inconsistent naming -void ocp_nlp_dims_print(ocp_nlp_dims *dims); -// TODO(andrea): inconsistent naming -void ocp_nlp_out_print(ocp_nlp_dims *dims, ocp_nlp_out *nlp_out); -// TODO(andrea): inconsistent naming -void ocp_nlp_res_print(ocp_nlp_dims *dims, ocp_nlp_res *nlp_res); - -// ocp qp -// TODO: move printing routines below that print qp structures to HPIPM! -void print_ocp_qp_dims(ocp_qp_dims *dims); - -// void print_dense_qp_dims(dense_qp_dims *dims); - -void print_ocp_qp_in(ocp_qp_in *qp_in); - -void print_ocp_qp_in_to_file(FILE *file, ocp_qp_in *qp_in); - -void print_ocp_qp_out(ocp_qp_out *qp_out); - -void print_ocp_qp_out_to_file(FILE *file, ocp_qp_out *qp_out); - -void print_ocp_qp_res(ocp_qp_res *qp_res); - -void print_dense_qp_in(dense_qp_in *qp_in); -// void print_ocp_qp_in_to_string(char string_out[], ocp_qp_in *qp_in); - -// void print_ocp_qp_out_to_string(char string_out[], ocp_qp_out *qp_out); - -// void print_colmaj_ocp_qp_in(colmaj_ocp_qp_in *qp); - -// void print_colmaj_ocp_qp_in_to_file(colmaj_ocp_qp_in *qp); - -// void print_colmaj_ocp_qp_out(char *filename, colmaj_ocp_qp_in *qp, colmaj_ocp_qp_out *out); - -void print_qp_info(qp_info *info); - -// void acados_warning(char warning_string[]); - -// void acados_error(char error_string[]); - -// void acados_not_implemented(char feature_string[]); - -// blasfeo -// void print_blasfeo_target(); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_UTILS_PRINT_H_ diff --git a/third_party/acados/include/acados/utils/strsep.h b/third_party/acados/include/acados/utils/strsep.h deleted file mode 100644 index 62bdfb4891..0000000000 --- a/third_party/acados/include/acados/utils/strsep.h +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -#ifndef ACADOS_UTILS_STRSEP_H_ -#define ACADOS_UTILS_STRSEP_H_ - -#ifdef __cplusplus -#include -#define STD(x) std::x -namespace std -{ -#else -#include -#define STD(x) x -#endif - -char* strsep_acados(char** stringp, const char* delim) -{ - char* result; - - if ((stringp == NULL) || (*stringp == NULL)) return NULL; - - result = *stringp; - - while (**stringp && !STD(strchr)(delim, **stringp)) ++*stringp; - - if (**stringp) - *(*stringp)++ = '\0'; - else - *stringp = NULL; - - return result; -} - -#ifdef __cplusplus -} // namespace std -#endif - -#undef STD - -#endif // ACADOS_UTILS_STRSEP_H_ diff --git a/third_party/acados/include/acados/utils/timing.h b/third_party/acados/include/acados/utils/timing.h deleted file mode 100644 index b0955932da..0000000000 --- a/third_party/acados/include/acados/utils/timing.h +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -#ifndef ACADOS_UTILS_TIMING_H_ -#define ACADOS_UTILS_TIMING_H_ - -#include "acados/utils/types.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef MEASURE_TIMINGS -#if (defined _WIN32 || defined _WIN64) && !(defined __MINGW32__ || defined __MINGW64__) - -/* Use Windows QueryPerformanceCounter for timing. */ -#include - -/** A structure for keeping internal timer data. */ -typedef struct acados_timer_ -{ - LARGE_INTEGER tic; - LARGE_INTEGER toc; - LARGE_INTEGER freq; -} acados_timer; - -#elif defined(__APPLE__) - -#include - -/** A structure for keeping internal timer data. */ -typedef struct acados_timer_ -{ - uint64_t tic; - uint64_t toc; - mach_timebase_info_data_t tinfo; -} acados_timer; - -#elif defined(__MABX2__) - -#include - -typedef struct acados_timer_ -{ - double time; -} acados_timer; - -#else - -/* Use POSIX clock_gettime() for timing on non-Windows machines. */ -#include - -#if (__STDC_VERSION__ >= 199901L) && !(defined __MINGW32__ || defined __MINGW64__) // C99 Mode - -#include -#include - -typedef struct acados_timer_ -{ - struct timeval tic; - struct timeval toc; -} acados_timer; - -#else // ANSI C Mode - -/** A structure for keeping internal timer data. */ -typedef struct acados_timer_ -{ - struct timespec tic; - struct timespec toc; -} acados_timer; - -#endif // __STDC_VERSION__ >= 199901L - -#endif // (defined _WIN32 || defined _WIN64) - -#else - -// Dummy type when timings are off -typedef real_t acados_timer; - -#endif // MEASURE_TIMINGS - -/** A function for measurement of the current time. */ -void acados_tic(acados_timer* t); - -/** A function which returns the elapsed time. */ -real_t acados_toc(acados_timer* t); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_UTILS_TIMING_H_ diff --git a/third_party/acados/include/acados/utils/types.h b/third_party/acados/include/acados/utils/types.h deleted file mode 100644 index a27ef9e552..0000000000 --- a/third_party/acados/include/acados/utils/types.h +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -#ifndef ACADOS_UTILS_TYPES_H_ -#define ACADOS_UTILS_TYPES_H_ - -/* Symbol visibility in DLLs */ -#ifndef ACADOS_SYMBOL_EXPORT - #if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) - #if defined(STATIC_LINKED) - #define ACADOS_SYMBOL_EXPORT - #else - #define ACADOS_SYMBOL_EXPORT __declspec(dllexport) - #endif - #elif defined(__GNUC__) && ((__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) - #define ACADOS_SYMBOL_EXPORT __attribute__ ((visibility ("default"))) - #else - #define ACADOS_SYMBOL_EXPORT - #endif -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -#include -#include - -#define MAX_STR_LEN 256 -#define ACADOS_EPS 1e-12 -#define ACADOS_NEG_INFTY -1.0e9 -#define ACADOS_POS_INFTY +1.0e9 -#define UNUSED(x) ((void)(x)) - - - -typedef double real_t; -typedef int int_t; -typedef size_t acados_size_t; - - -typedef int (*casadi_function_t)(const double** arg, double** res, int* iw, double* w, void* mem); - - - -// enum of return values -enum return_values -{ - ACADOS_SUCCESS, - ACADOS_NAN_DETECTED, - ACADOS_MAXITER, - ACADOS_MINSTEP, - ACADOS_QP_FAILURE, - ACADOS_READY, -}; - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // ACADOS_UTILS_TYPES_H_ diff --git a/third_party/acados/include/acados_c/condensing_interface.h b/third_party/acados/include/acados_c/condensing_interface.h deleted file mode 100644 index b4302078d6..0000000000 --- a/third_party/acados/include/acados_c/condensing_interface.h +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -#ifndef INTERFACES_ACADOS_C_CONDENSING_INTERFACE_H_ -#define INTERFACES_ACADOS_C_CONDENSING_INTERFACE_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "acados/ocp_qp/ocp_qp_full_condensing.h" -#include "acados/ocp_qp/ocp_qp_partial_condensing.h" - -typedef enum { - PARTIAL_CONDENSING, - FULL_CONDENSING, -} condensing_t; - -typedef struct -{ - condensing_t condensing_type; -} condensing_plan; - -typedef struct -{ - ocp_qp_xcond_config *config; - void *dims; - void *opts; - void *mem; - void *work; -} condensing_module; - -ocp_qp_xcond_config *ocp_qp_condensing_config_create(condensing_plan *plan); -// -void *ocp_qp_condensing_opts_create(ocp_qp_xcond_config *config, void *dims_); -// -acados_size_t ocp_qp_condensing_calculate_size(ocp_qp_xcond_config *config, void *dims_, void *opts_); -// -condensing_module *ocp_qp_condensing_assign(ocp_qp_xcond_config *config, void *dims_, - void *opts_, void *raw_memory); -// -condensing_module *ocp_qp_condensing_create(ocp_qp_xcond_config *config, void *dims_, - void *opts_); -// -int ocp_qp_condense(condensing_module *module, void *qp_in, void *qp_out); -// -int ocp_qp_expand(condensing_module *module, void *qp_in, void *qp_out); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // INTERFACES_ACADOS_C_CONDENSING_INTERFACE_H_ diff --git a/third_party/acados/include/acados_c/dense_qp_interface.h b/third_party/acados/include/acados_c/dense_qp_interface.h deleted file mode 100644 index b3af4bf682..0000000000 --- a/third_party/acados/include/acados_c/dense_qp_interface.h +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -#ifndef INTERFACES_ACADOS_C_DENSE_QP_INTERFACE_H_ -#define INTERFACES_ACADOS_C_DENSE_QP_INTERFACE_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "acados/dense_qp/dense_qp_common.h" - -typedef enum { DENSE_QP_HPIPM, DENSE_QP_QORE, DENSE_QP_QPOASES, DENSE_QP_OOQP, DENSE_QP_DAQP } dense_qp_solver_t; - -typedef struct -{ - dense_qp_solver_t qp_solver; -} dense_qp_solver_plan; - -typedef struct -{ - qp_solver_config *config; - void *dims; - void *opts; - void *mem; - void *work; -} dense_qp_solver; - -qp_solver_config *dense_qp_config_create(dense_qp_solver_plan *plan); -// -dense_qp_dims *dense_qp_dims_create(); -// -dense_qp_in *dense_qp_in_create(qp_solver_config *config, dense_qp_dims *dims); -// -dense_qp_out *dense_qp_out_create(qp_solver_config *config, dense_qp_dims *dims); -// -void *dense_qp_opts_create(qp_solver_config *config, dense_qp_dims *dims); -// -acados_size_t dense_qp_calculate_size(qp_solver_config *config, dense_qp_dims *dims, void *opts_); -// -dense_qp_solver *dense_qp_assign(qp_solver_config *config, dense_qp_dims *dims, void *opts_, - void *raw_memory); -// -dense_qp_solver *dense_qp_create(qp_solver_config *config, dense_qp_dims *dims, void *opts_); -// -int dense_qp_solve(dense_qp_solver *solver, dense_qp_in *qp_in, dense_qp_out *qp_out); -// -void dense_qp_inf_norm_residuals(dense_qp_dims *dims, dense_qp_in *qp_in, dense_qp_out *qp_out, - double *res); -// -bool dense_qp_set_field_double_array(const char *field, double *arr, dense_qp_in *qp_in); -// -bool dense_qp_set_field_int_array(const char *field, int *arr, dense_qp_in *qp_in); -// -bool dense_qp_get_field_double_array(const char *field, dense_qp_in *qp_in, double *arr); -// -bool dense_qp_get_field_int_array(const char *field, dense_qp_in *qp_in, int *arr); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // INTERFACES_ACADOS_C_DENSE_QP_INTERFACE_H_ diff --git a/third_party/acados/include/acados_c/external_function_interface.h b/third_party/acados/include/acados_c/external_function_interface.h deleted file mode 100644 index d4f52db850..0000000000 --- a/third_party/acados/include/acados_c/external_function_interface.h +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -#ifndef INTERFACES_ACADOS_C_EXTERNAL_FUNCTION_INTERFACE_H_ -#define INTERFACES_ACADOS_C_EXTERNAL_FUNCTION_INTERFACE_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "acados/utils/external_function_generic.h" - - - -/************************************************ - * generic external parametric function - ************************************************/ - -// -void external_function_param_generic_create(external_function_param_generic *fun, int np); -// -void external_function_param_generic_free(external_function_param_generic *fun); - - - -/************************************************ - * casadi external function - ************************************************/ - -// -void external_function_casadi_create(external_function_casadi *fun); -// -void external_function_casadi_free(external_function_casadi *fun); -// -void external_function_casadi_create_array(int size, external_function_casadi *funs); -// -void external_function_casadi_free_array(int size, external_function_casadi *funs); - - - -/************************************************ - * casadi external parametric function - ************************************************/ - -// -void external_function_param_casadi_create(external_function_param_casadi *fun, int np); -// -void external_function_param_casadi_free(external_function_param_casadi *fun); -// -void external_function_param_casadi_create_array(int size, external_function_param_casadi *funs, - int np); -// -void external_function_param_casadi_free_array(int size, external_function_param_casadi *funs); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // INTERFACES_ACADOS_C_EXTERNAL_FUNCTION_INTERFACE_H_ diff --git a/third_party/acados/include/acados_c/ocp_nlp_interface.h b/third_party/acados/include/acados_c/ocp_nlp_interface.h deleted file mode 100644 index dd3e596f8b..0000000000 --- a/third_party/acados/include/acados_c/ocp_nlp_interface.h +++ /dev/null @@ -1,428 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -#ifndef INTERFACES_ACADOS_C_OCP_NLP_INTERFACE_H_ -#define INTERFACES_ACADOS_C_OCP_NLP_INTERFACE_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// acados -#include "acados/ocp_nlp/ocp_nlp_common.h" -#include "acados/ocp_nlp/ocp_nlp_constraints_bgh.h" -#include "acados/sim/sim_erk_integrator.h" -#include "acados/sim/sim_irk_integrator.h" -#include "acados/sim/sim_lifted_irk_integrator.h" -#include "acados/sim/sim_gnsf.h" -#include "acados/utils/types.h" -// acados_c -#include "acados_c/ocp_qp_interface.h" -#include "acados_c/sim_interface.h" - - -/// Solution methods for optimal control problems. -typedef enum -{ - SQP, - SQP_RTI, - INVALID_NLP_SOLVER, -} ocp_nlp_solver_t; - - -/// Types of the cost function. -typedef enum -{ - LINEAR_LS, - NONLINEAR_LS, - CONVEX_OVER_NONLINEAR, - EXTERNAL, - INVALID_COST, -} ocp_nlp_cost_t; - - -/// Types of the system dynamics, discrete or continuous time. -typedef enum -{ - CONTINUOUS_MODEL, - DISCRETE_MODEL, - INVALID_DYNAMICS, -} ocp_nlp_dynamics_t; - - -/// Constraint types -typedef enum -{ - /// Comprises simple bounds, polytopic constraints, - /// general non-linear constraints. - BGH, - - /// Comprises simple bounds, polytopic constraints, - /// general non-linear constraints, and positive definite constraints. - BGP, - - INVALID_CONSTRAINT, -} ocp_nlp_constraints_t; - - -/// Regularization types -typedef enum -{ - NO_REGULARIZE, - MIRROR, - PROJECT, - PROJECT_REDUC_HESS, - CONVEXIFY, - INVALID_REGULARIZE, -} ocp_nlp_reg_t; - - -/// Structure to store the configuration of a non-linear program -typedef struct ocp_nlp_plan_t -{ - /// QP solver configuration. - ocp_qp_solver_plan_t ocp_qp_solver_plan; - - /// Simulation solver configuration for each stage. - sim_solver_plan_t *sim_solver_plan; - - /// Nlp solver type. - ocp_nlp_solver_t nlp_solver; - - /// Regularization type, defaults to no regularization. - ocp_nlp_reg_t regularization; - - /// Cost type for each stage. - ocp_nlp_cost_t *nlp_cost; - - /// Dynamics type for each stage. - ocp_nlp_dynamics_t *nlp_dynamics; - - /// Constraints type for each stage. - ocp_nlp_constraints_t *nlp_constraints; - - /// Horizon length. - int N; - -} ocp_nlp_plan_t; - - -/// Structure to store the state/configuration for the non-linear programming solver -typedef struct ocp_nlp_solver -{ - ocp_nlp_config *config; - void *dims; - void *opts; - void *mem; - void *work; -} ocp_nlp_solver; - - -/// Constructs an empty plan struct (user nlp configuration), all fields are set to a -/// default/invalid state. -/// -/// \param N Horizon length -ACADOS_SYMBOL_EXPORT ocp_nlp_plan_t *ocp_nlp_plan_create(int N); - -/// Destructor for plan struct, frees memory. -/// -/// \param plan_ The plan struct to destroy. -ACADOS_SYMBOL_EXPORT void ocp_nlp_plan_destroy(void* plan_); - - -/// Constructs an nlp configuration struct from a plan. -/// -/// \param plan The plan (user nlp configuration). -ACADOS_SYMBOL_EXPORT ocp_nlp_config *ocp_nlp_config_create(ocp_nlp_plan_t plan); - -/// Desctructor of the nlp configuration. -/// -/// \param config_ The configuration struct. -ACADOS_SYMBOL_EXPORT void ocp_nlp_config_destroy(void *config_); - - -/// Constructs an struct that contains the dimensions of the variables. -/// -/// \param config_ The configuration struct. -ACADOS_SYMBOL_EXPORT ocp_nlp_dims *ocp_nlp_dims_create(void *config_); - -/// Destructor of The dimension struct. -/// -/// \param dims_ The dimension struct. -ACADOS_SYMBOL_EXPORT void ocp_nlp_dims_destroy(void *dims_); - - -/// Constructs an input struct for a non-linear programs. -/// -/// \param config The configuration struct. -/// \param dims The dimension struct. -ACADOS_SYMBOL_EXPORT ocp_nlp_in *ocp_nlp_in_create(ocp_nlp_config *config, ocp_nlp_dims *dims); - -/// Destructor of the inputs struct. -/// -/// \param in The inputs struct. -ACADOS_SYMBOL_EXPORT void ocp_nlp_in_destroy(void *in); - - -/// Sets the sampling times for the given stage. -/// -/// \param config The configuration struct. -/// \param dims The dimension struct. -/// \param in The inputs struct. -/// \param stage Stage number. -/// \param field Has to be "Ts" (TBC other options). -/// \param value The sampling times (floating point). -ACADOS_SYMBOL_EXPORT void ocp_nlp_in_set(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, int stage, - const char *field, void *value); - -/// -// void ocp_nlp_in_get(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, int stage, -// const char *field, void *value); - -/// Sets the function pointers to the dynamics functions for the given stage. -/// -/// \param config The configuration struct. -/// \param dims The dimension struct. -/// \param in The inputs struct. -/// \param stage Stage number. -/// \param fun_type The name of the function type, either impl_ode_fun, -/// impl_ode_fun_jac_x_xdot, impl_ode_jac_x_xdot_u (TBC) -/// \param fun_ptr Function pointer to the dynamics function. -ACADOS_SYMBOL_EXPORT int ocp_nlp_dynamics_model_set(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, - int stage, const char *fun_type, void *fun_ptr); - - -/// Sets the function pointers to the cost functions for the given stage. -/// -/// \param config The configuration struct. -/// \param dims The dimension struct. -/// \param in The inputs struct. -/// \param stage Stage number. -/// \param field The name of the field, either nls_res_jac, -/// y_ref, W (others TBC) -/// \param value Cost values. -ACADOS_SYMBOL_EXPORT int ocp_nlp_cost_model_set(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, - int stage, const char *field, void *value); - - -/// Sets the function pointers to the constraints functions for the given stage. -/// -/// \param config The configuration struct. -/// \param dims The dimension struct. -/// \param in The inputs struct. -/// \param stage Stage number. -/// \param field The name of the field, either lb, ub (others TBC) -/// \param value Constraints function or values. -ACADOS_SYMBOL_EXPORT int ocp_nlp_constraints_model_set(ocp_nlp_config *config, ocp_nlp_dims *dims, - ocp_nlp_in *in, int stage, const char *field, void *value); - -/// -ACADOS_SYMBOL_EXPORT void ocp_nlp_constraints_model_get(ocp_nlp_config *config, ocp_nlp_dims *dims, - ocp_nlp_in *in, int stage, const char *field, void *value); - -/* out */ - -/// Constructs an output struct for the non-linear program. -/// -/// \param config The configuration struct. -/// \param dims The dimension struct. -ACADOS_SYMBOL_EXPORT ocp_nlp_out *ocp_nlp_out_create(ocp_nlp_config *config, ocp_nlp_dims *dims); - -/// Destructor of the output struct. -/// -/// \param out The output struct. -ACADOS_SYMBOL_EXPORT void ocp_nlp_out_destroy(void *out); - - -/// Sets fields in the output struct of an nlp solver, used to initialize the solver. -/// -/// \param config The configuration struct. -/// \param dims The dimension struct. -/// \param out The output struct. -/// \param stage Stage number. -/// \param field The name of the field, either x, u, pi. -/// \param value Initialization values. -ACADOS_SYMBOL_EXPORT void ocp_nlp_out_set(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_out *out, - int stage, const char *field, void *value); - - -/// Gets values of fields in the output struct of an nlp solver. -/// -/// \param config The configuration struct. -/// \param dims The dimension struct. -/// \param out The output struct. -/// \param stage Stage number. -/// \param field The name of the field, either x, u, z, pi. -/// \param value Pointer to the output memory. -ACADOS_SYMBOL_EXPORT void ocp_nlp_out_get(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_out *out, - int stage, const char *field, void *value); - -// -ACADOS_SYMBOL_EXPORT void ocp_nlp_get_at_stage(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_solver *solver, - int stage, const char *field, void *value); - -// TODO(andrea): remove this once/if the MATLAB interface uses the new setters below? -ACADOS_SYMBOL_EXPORT int ocp_nlp_dims_get_from_attr(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_out *out, - int stage, const char *field); - -ACADOS_SYMBOL_EXPORT void ocp_nlp_constraint_dims_get_from_attr(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_out *out, - int stage, const char *field, int *dims_out); - -ACADOS_SYMBOL_EXPORT void ocp_nlp_cost_dims_get_from_attr(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_out *out, - int stage, const char *field, int *dims_out); - -ACADOS_SYMBOL_EXPORT void ocp_nlp_qp_dims_get_from_attr(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_out *out, - int stage, const char *field, int *dims_out); - -/* opts */ - -/// Creates an options struct for the non-linear program. -/// -/// \param config The configuration struct. -/// \param dims The dimension struct. -ACADOS_SYMBOL_EXPORT void *ocp_nlp_solver_opts_create(ocp_nlp_config *config, ocp_nlp_dims *dims); - -/// Destructor of the options. -/// -/// \param opts The options struct. -ACADOS_SYMBOL_EXPORT void ocp_nlp_solver_opts_destroy(void *opts); - -/// Sets an option. -/// -/// \param config The configuration struct. -/// \param opts_ The options struct. -/// \param field Name of the option. -/// \param value Value of the option. -ACADOS_SYMBOL_EXPORT void ocp_nlp_solver_opts_set(ocp_nlp_config *config, void *opts_, const char *field, void* value); - - -// ACADOS_SYMBOL_EXPORT void ocp_nlp_solver_opts_get(ocp_nlp_config *config, void *opts_, const char *field, void* value); - - -ACADOS_SYMBOL_EXPORT void ocp_nlp_solver_opts_set_at_stage(ocp_nlp_config *config, void *opts_, int stage, const char *field, void* value); - - -/// TBC -/// Updates the options. -/// -/// \param config The configuration struct. -/// \param dims The dimension struct. -/// \param opts_ The options struct. -ACADOS_SYMBOL_EXPORT void ocp_nlp_solver_opts_update(ocp_nlp_config *config, ocp_nlp_dims *dims, void *opts_); - - -/* solver */ - -/// Creates an ocp solver. -/// -/// \param config The configuration struct. -/// \param dims The dimension struct. -/// \param opts_ The options struct. -/// \return The solver. -ACADOS_SYMBOL_EXPORT ocp_nlp_solver *ocp_nlp_solver_create(ocp_nlp_config *config, ocp_nlp_dims *dims, void *opts_); - -/// Destructor of the solver. -/// -/// \param solver The solver struct. -ACADOS_SYMBOL_EXPORT void ocp_nlp_solver_destroy(void *solver); - -/// Solves the optimal control problem. Call ocp_nlp_precompute before -/// calling this functions (TBC). -/// -/// \param solver The solver struct. -/// \param nlp_in The inputs struct. -/// \param nlp_out The output struct. -ACADOS_SYMBOL_EXPORT int ocp_nlp_solve(ocp_nlp_solver *solver, ocp_nlp_in *nlp_in, ocp_nlp_out *nlp_out); - - - -/// Resets the memory of the QP solver -/// -/// \param solver The solver struct. -/// \param nlp_in The inputs struct. -/// \param nlp_out The output struct. -ACADOS_SYMBOL_EXPORT void ocp_nlp_solver_reset_qp_memory(ocp_nlp_solver *solver, ocp_nlp_in *nlp_in, ocp_nlp_out *nlp_out); - - -/// Performs precomputations for the solver. Needs to be called before -/// ocl_nlp_solve (TBC). -/// -/// \param solver The solver struct. -/// \param nlp_in The inputs struct. -/// \param nlp_out The output struct. -ACADOS_SYMBOL_EXPORT int ocp_nlp_precompute(ocp_nlp_solver *solver, ocp_nlp_in *nlp_in, ocp_nlp_out *nlp_out); - - -/// Computes cost function value. -/// -/// \param solver The solver struct. -/// \param nlp_in The inputs struct. -/// \param nlp_out The output struct. -ACADOS_SYMBOL_EXPORT void ocp_nlp_eval_cost(ocp_nlp_solver *solver, ocp_nlp_in *nlp_in, ocp_nlp_out *nlp_out); - - -/// Computes the residuals. -/// -/// \param solver The solver struct. -/// \param nlp_in The inputs struct. -/// \param nlp_out The output struct. -ACADOS_SYMBOL_EXPORT void ocp_nlp_eval_residuals(ocp_nlp_solver *solver, ocp_nlp_in *nlp_in, ocp_nlp_out *nlp_out); - - -// -ACADOS_SYMBOL_EXPORT void ocp_nlp_eval_param_sens(ocp_nlp_solver *solver, char *field, int stage, int index, ocp_nlp_out *sens_nlp_out); - -/* get */ -/// \param config The configuration struct. -/// \param solver The solver struct. -/// \param field Supports "sqp_iter", "status", "nlp_res", "time_tot", ... -/// \param return_value_ Pointer to the output memory. -ACADOS_SYMBOL_EXPORT void ocp_nlp_get(ocp_nlp_config *config, ocp_nlp_solver *solver, - const char *field, void *return_value_); - -/* set */ -/// Sets the initial guesses for the integrator for the given stage. -/// -/// \param config The configuration struct. -/// \param solver The ocp_nlp_solver struct. -/// \param stage Stage number. -/// \param field Supports "z_guess", "xdot_guess" (IRK), "phi_guess" (GNSF-IRK) -/// \param value The initial guess for the algebraic variables in the integrator (if continuous model is used). -ACADOS_SYMBOL_EXPORT void ocp_nlp_set(ocp_nlp_config *config, ocp_nlp_solver *solver, - int stage, const char *field, void *value); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // INTERFACES_ACADOS_C_OCP_NLP_INTERFACE_H_ diff --git a/third_party/acados/include/acados_c/ocp_qp_interface.h b/third_party/acados/include/acados_c/ocp_qp_interface.h deleted file mode 100644 index 3dc3f1a532..0000000000 --- a/third_party/acados/include/acados_c/ocp_qp_interface.h +++ /dev/null @@ -1,263 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -#ifndef INTERFACES_ACADOS_C_OCP_QP_INTERFACE_H_ -#define INTERFACES_ACADOS_C_OCP_QP_INTERFACE_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "acados/ocp_qp/ocp_qp_common.h" -#include "acados/ocp_qp/ocp_qp_xcond_solver.h" - - -/// QP solver types (Enumeration). -/// -/// Full list of fields: -/// PARTIAL_CONDENSING_HPIPM -/// PARTIAL_CONDENSING_HPMPC -/// PARTIAL_CONDENSING_OOQP -/// PARTIAL_CONDENSING_OSQP -/// PARTIAL_CONDENSING_QPDUNES -/// FULL_CONDENSING_HPIPM -/// FULL_CONDENSING_QPOASES -/// FULL_CONDENSING_QORE -/// FULL_CONDENSING_OOQP -/// INVALID_QP_SOLVER -/// -/// Note: In this enumeration the partial condensing solvers have to be -/// specified before the full condensing solvers. -typedef enum { - PARTIAL_CONDENSING_HPIPM, -#ifdef ACADOS_WITH_HPMPC - PARTIAL_CONDENSING_HPMPC, -#else - PARTIAL_CONDENSING_HPMPC_NOT_AVAILABLE, -#endif -#ifdef ACADOS_WITH_OOQP - PARTIAL_CONDENSING_OOQP, -#else - PARTIAL_CONDENSING_OOQP_NOT_AVAILABLE, -#endif -#ifdef ACADOS_WITH_OSQP - PARTIAL_CONDENSING_OSQP, -#else - PARTIAL_CONDENSING_OSQP_NOT_AVAILABLE, -#endif -#ifdef ACADOS_WITH_QPDUNES - PARTIAL_CONDENSING_QPDUNES, -#else - PARTIAL_CONDENSING_QPDUNES_NOT_AVAILABLE, -#endif - FULL_CONDENSING_HPIPM, -#ifdef ACADOS_WITH_QPOASES - FULL_CONDENSING_QPOASES, -#else - FULL_CONDENSING_QPOASES_NOT_AVAILABLE, -#endif -#ifdef ACADOS_WITH_DAQP - FULL_CONDENSING_DAQP, -#else - FULL_CONDENSING_DAQP_NOT_AVAILABLE, -#endif -#ifdef ACADOS_WITH_QORE - FULL_CONDENSING_QORE, -#else - FULL_CONDENSING_QORE_NOT_AVAILABLE, -#endif -#ifdef ACADOS_WITH_OOQP - FULL_CONDENSING_OOQP, -#else - FULL_CONDENSING_OOQP_NOT_AVAILABLE, -#endif - INVALID_QP_SOLVER, -} ocp_qp_solver_t; - - -/// Struct containing qp solver -typedef struct -{ - ocp_qp_solver_t qp_solver; -} ocp_qp_solver_plan_t; - - -/// Linear ocp configuration. -typedef struct -{ - ocp_qp_xcond_solver_config *config; - ocp_qp_xcond_solver_dims *dims; - void *opts; - void *mem; - void *work; -} ocp_qp_solver; - - -/// Initializes the qp solver configuration. -/// TBC should this be private/static - no, used in ocp_nlp -void ocp_qp_xcond_solver_config_initialize_from_plan( - ocp_qp_solver_t solver_name, ocp_qp_xcond_solver_config *solver_config); - -/// Constructs a qp solver config and Initializes with default values. -/// -/// \param plan The qp solver plan struct. -ocp_qp_xcond_solver_config *ocp_qp_xcond_solver_config_create(ocp_qp_solver_plan_t plan); - -/// Destructor for config struct, frees memory. -/// -/// \param config The config object to destroy. -void ocp_qp_xcond_solver_config_free(ocp_qp_xcond_solver_config *config); - - -/// Constructs a struct that contains the dimensions for the variables of the qp. -/// -/// \param N The number of variables. -ocp_qp_dims *ocp_qp_dims_create(int N); - -/// Destructor of The dimension struct. -/// -/// \param dims The dimension struct. -void ocp_qp_dims_free(void *dims); - -// -ocp_qp_xcond_solver_dims *ocp_qp_xcond_solver_dims_create(ocp_qp_xcond_solver_config *config, int N); -// -ocp_qp_xcond_solver_dims *ocp_qp_xcond_solver_dims_create_from_ocp_qp_dims( - ocp_qp_xcond_solver_config *config, ocp_qp_dims *dims); -// -void ocp_qp_xcond_solver_dims_free(ocp_qp_xcond_solver_dims *dims_); - -void ocp_qp_xcond_solver_dims_set(void *config_, ocp_qp_xcond_solver_dims *dims, - int stage, const char *field, int* value); - - -/// Constructs an input object for the qp. -/// -/// \param dims The dimension struct. -ocp_qp_in *ocp_qp_in_create(ocp_qp_dims *dims); - - -void ocp_qp_in_set(ocp_qp_xcond_solver_config *config, ocp_qp_in *in, - int stage, char *field, void *value); - -/// Destructor of the inputs struct. -/// -/// \param in_ The inputs struct. -void ocp_qp_in_free(void *in_); - - -/// Constructs an outputs object for the qp. -/// -/// \param dims The dimension struct. -ocp_qp_out *ocp_qp_out_create(ocp_qp_dims *dims); - -/// Destructor of the output struct. -/// -/// \param out_ The output struct. -void ocp_qp_out_free(void *out_); - - -/// Getter of output struct -void ocp_qp_out_get(ocp_qp_out *out, const char *field, void *value); - - -/// Constructs an options object for the qp. -/// -/// \param config The configuration struct. -/// \param dims The dimension struct. -void *ocp_qp_xcond_solver_opts_create(ocp_qp_xcond_solver_config *config, - ocp_qp_xcond_solver_dims *dims); - -/// Destructor of the options struct. -/// -/// \param opts The options struct to destroy. -void ocp_qp_xcond_solver_opts_free(ocp_qp_xcond_solver_opts *opts); - - -/// Setter of the options struct. -/// -/// \param opts The options struct. -void ocp_qp_xcond_solver_opts_set(ocp_qp_xcond_solver_config *config, - ocp_qp_xcond_solver_opts *opts, const char *field, void* value); - -/// TBC Should be private/static? -acados_size_t ocp_qp_calculate_size(ocp_qp_xcond_solver_config *config, ocp_qp_xcond_solver_dims *dims, void *opts_); - - -/// TBC Reserves memory? TBC Should this be private? -/// -/// \param config The configuration struct. -/// \param dims The dimension struct. -/// \param opts_ The options struct. -/// \param raw_memory Pointer to raw memory to assign to qp solver. -ocp_qp_solver *ocp_qp_assign(ocp_qp_xcond_solver_config *config, ocp_qp_xcond_solver_dims *dims, - void *opts_, void *raw_memory); - -/// Creates a qp solver. Reserves memory. -/// -/// \param config The configuration struct. -/// \param dims The dimension struct. -/// \param opts_ The options struct. -ocp_qp_solver *ocp_qp_create(ocp_qp_xcond_solver_config *config, - ocp_qp_xcond_solver_dims *dims, void *opts_); - - -/// Destroys a qp solver. Frees memory. -/// -/// \param solver The qp solver -void ocp_qp_solver_destroy(ocp_qp_solver *solver); - -void ocp_qp_x_cond_solver_free(ocp_qp_xcond_solver_config *config, - ocp_qp_xcond_solver_dims *dims, void *opts_); - - -/// Solves the qp. -/// -/// \param solver The solver. -/// \param qp_in The inputs struct. -/// \param qp_out The output struct. -int ocp_qp_solve(ocp_qp_solver *solver, ocp_qp_in *qp_in, ocp_qp_out *qp_out); - - -/// Calculates the infinity norm of the residuals. -/// -/// \param dims The dimension struct. -/// \param qp_in The inputs struct. -/// \param qp_out The output struct. -/// \param res Output array for the residuals. -void ocp_qp_inf_norm_residuals(ocp_qp_dims *dims, ocp_qp_in *qp_in, ocp_qp_out *qp_out, - double *res); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // INTERFACES_ACADOS_C_OCP_QP_INTERFACE_H_ diff --git a/third_party/acados/include/acados_c/sim_interface.h b/third_party/acados/include/acados_c/sim_interface.h deleted file mode 100644 index 09a05d6995..0000000000 --- a/third_party/acados/include/acados_c/sim_interface.h +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright (c) The acados authors. - * - * This file is part of acados. - * - * The 2-Clause BSD License - * - * 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. - * - * 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.; - */ - - -#ifndef INTERFACES_ACADOS_C_SIM_INTERFACE_H_ -#define INTERFACES_ACADOS_C_SIM_INTERFACE_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "acados/sim/sim_common.h" - - - -typedef enum -{ - ERK, - IRK, - GNSF, - LIFTED_IRK, - INVALID_SIM_SOLVER, -} sim_solver_t; - - - -typedef struct -{ - sim_solver_t sim_solver; -} sim_solver_plan_t; - - - -typedef struct -{ - sim_config *config; - void *dims; - void *opts; - void *mem; - void *work; -} sim_solver; - - - -/* config */ -// -ACADOS_SYMBOL_EXPORT sim_config *sim_config_create(sim_solver_plan_t plan); -// -ACADOS_SYMBOL_EXPORT void sim_config_destroy(void *config); - -/* dims */ -// -ACADOS_SYMBOL_EXPORT void *sim_dims_create(void *config_); -// -ACADOS_SYMBOL_EXPORT void sim_dims_destroy(void *dims); -// -ACADOS_SYMBOL_EXPORT void sim_dims_set(sim_config *config, void *dims, const char *field, const int* value); -// -ACADOS_SYMBOL_EXPORT void sim_dims_get(sim_config *config, void *dims, const char *field, int* value); -// -ACADOS_SYMBOL_EXPORT void sim_dims_get_from_attr(sim_config *config, void *dims, const char *field, int *dims_out); - -/* in */ -// -ACADOS_SYMBOL_EXPORT sim_in *sim_in_create(sim_config *config, void *dims); -// -ACADOS_SYMBOL_EXPORT void sim_in_destroy(void *out); -// -ACADOS_SYMBOL_EXPORT int sim_in_set(void *config_, void *dims_, sim_in *in, const char *field, void *value); - - -/* out */ -// -ACADOS_SYMBOL_EXPORT sim_out *sim_out_create(sim_config *config, void *dims); -// -ACADOS_SYMBOL_EXPORT void sim_out_destroy(void *out); -// -ACADOS_SYMBOL_EXPORT int sim_out_get(void *config, void *dims, sim_out *out, const char *field, void *value); - -/* opts */ -// -ACADOS_SYMBOL_EXPORT void *sim_opts_create(sim_config *config, void *dims); -// -ACADOS_SYMBOL_EXPORT void sim_opts_destroy(void *opts); -// -ACADOS_SYMBOL_EXPORT void sim_opts_set(sim_config *config, void *opts, const char *field, void *value); -// -ACADOS_SYMBOL_EXPORT void sim_opts_get(sim_config *config, void *opts, const char *field, void *value); - -/* solver */ -// -ACADOS_SYMBOL_EXPORT acados_size_t sim_calculate_size(sim_config *config, void *dims, void *opts_); -// -ACADOS_SYMBOL_EXPORT sim_solver *sim_assign(sim_config *config, void *dims, void *opts_, void *raw_memory); -// -ACADOS_SYMBOL_EXPORT sim_solver *sim_solver_create(sim_config *config, void *dims, void *opts_); -// -ACADOS_SYMBOL_EXPORT void sim_solver_destroy(void *solver); -// -ACADOS_SYMBOL_EXPORT int sim_solve(sim_solver *solver, sim_in *in, sim_out *out); -// -ACADOS_SYMBOL_EXPORT int sim_precompute(sim_solver *solver, sim_in *in, sim_out *out); -// -ACADOS_SYMBOL_EXPORT int sim_solver_set(sim_solver *solver, const char *field, void *value); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // INTERFACES_ACADOS_C_SIM_INTERFACE_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo.h b/third_party/acados/include/blasfeo/include/blasfeo.h deleted file mode 100644 index c854918193..0000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo.h +++ /dev/null @@ -1,52 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#include "blasfeo_processor_features.h" -#include "blasfeo_target.h" -#include "blasfeo_block_size.h" -#include "blasfeo_stdlib.h" -#include "blasfeo_common.h" -#include "blasfeo_d_aux.h" -#include "blasfeo_d_aux_ext_dep.h" -#include "blasfeo_d_kernel.h" -#include "blasfeo_d_blas.h" -#include "blasfeo_s_aux.h" -#include "blasfeo_s_aux_ext_dep.h" -#include "blasfeo_s_kernel.h" -#include "blasfeo_s_blas.h" -#include "blasfeo_i_aux_ext_dep.h" -#include "blasfeo_v_aux_ext_dep.h" -#include "blasfeo_timing.h" -#include "blasfeo_memory.h" diff --git a/third_party/acados/include/blasfeo/include/blasfeo_block_size.h b/third_party/acados/include/blasfeo/include/blasfeo_block_size.h deleted file mode 100644 index 5d0907a61c..0000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_block_size.h +++ /dev/null @@ -1,447 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_BLOCK_SIZE_H_ -#define BLASFEO_BLOCK_SIZE_H_ - - - -#define D_EL_SIZE 8 // double precision -#define S_EL_SIZE 4 // single precision - - - -#if defined( TARGET_X64_INTEL_SKYLAKE_X ) -// common -#define CACHE_LINE_SIZE 64 // data cache size: 64 bytes -#define L1_CACHE_SIZE (32*1024) // L1 data cache size: 32 kB, 8-way -#define L2_CACHE_SIZE (256*1024) //(1024*1024) // L2 data cache size: 1 MB ; DTLB1 64*4 kB = 256 kB -#define LLC_CACHE_SIZE (6*1024*1024) //(8*1024*1024) // LLC cache size: 8 MB ; TLB 1536*4 kB = 6 MB -// double -#define D_PS 8 // panel size -#define D_PLD 8 // 4 // GCD of panel length -#define D_M_KERNEL 24 // max kernel size -#define D_N_KERNEL 8 // max kernel size -#define D_KC 128 //256 // 192 -#define D_NC 144 //72 //96 //72 // 120 // 512 -#define D_MC 2400 // 6000 -// single -#define S_PS 16 // panel size -#define S_PLD 4 // GCD of panel length TODO probably 16 when writing assebly -#define S_M_KERNEL 32 // max kernel size -#define S_N_KERNEL 8 // max kernel size -#define S_KC 128 //256 -#define S_NC 128 //144 -#define S_MC 3000 - -#elif defined( TARGET_X64_INTEL_HASWELL ) -// common -#define CACHE_LINE_SIZE 64 // data cache size: 64 bytes -#define L1_CACHE_SIZE (32*1024) // L1 data cache size: 32 kB, 8-way -#define L2_CACHE_SIZE (256*1024) // L2 data cache size: 256 kB ; DTLB1 64*4 kB = 256 kB -#define LLC_CACHE_SIZE (6*1024*1024) // LLC cache size: 6 MB ; TLB 1024*4 kB = 4 MB -// double -#define D_PS 4 // panel size -#define D_PLD 4 // 2 // GCD of panel length -#define D_M_KERNEL 12 // max kernel size -#define D_N_KERNEL 8 // max kernel size -#define D_KC 256 // 192 -#define D_NC 64 //96 //72 // 120 // 512 -#define D_MC 1500 -// single -#define S_PS 8 // panel size -#define S_PLD 4 // 2 // GCD of panel length -#define S_M_KERNEL 24 // max kernel size -#define S_N_KERNEL 8 // max kernel size -#define S_KC 256 -#define S_NC 144 -#define S_MC 3000 - -#elif defined( TARGET_X64_INTEL_SANDY_BRIDGE ) -// common -#define CACHE_LINE_SIZE 64 // data cache size: 64 bytes -#define L1_CACHE_SIZE (32*1024) // L1 data cache size: 32 kB, 8-way -#define L2_CACHE_SIZE (256*1024) // L2 data cache size: 256 kB ; DTLB1 64*4 kB = 256 kB -#define LLC_CACHE_SIZE (4*1024*1024) // LLC cache size: 4 MB ; TLB 1024*4 kB = 4 MB -// double -#define D_PS 4 // panel size -#define D_PLD 4 // 2 // GCD of panel length -#define D_M_KERNEL 8 // max kernel size -#define D_N_KERNEL 4 // max kernel size -#define D_KC 256 //320 //256 //320 -#define D_NC 72 //64 //72 //60 // 120 -#define D_MC 1000 // 800 -// single -#define S_PS 8 // panel size -#define S_PLD 4 // 2 // GCD of panel length -#define S_M_KERNEL 16 // max kernel size -#define S_N_KERNEL 8 // max kernel size -#define S_KC 256 -#define S_NC 144 -#define S_MC 2000 - -#elif defined( TARGET_X64_INTEL_CORE ) -// common -#define CACHE_LINE_SIZE 64 -#define L1_CACHE_SIZE (32*1024) // L1 data cache size: 32 kB -// double -#define D_PS 4 // panel size -#define D_PLD 4 // 2 // GCD of panel length -#define D_M_KERNEL 4 // max kernel size -#define D_N_KERNEL 4 // max kernel size -#define D_KC 256 -#define D_NC 128 // TODO these are just dummy -#define D_MC 3000 // TODO these are just dummy -// single -#define S_PS 4 -#define S_PLD 4 //2 -#define S_M_KERNEL 4 // max kernel size -#define S_N_KERNEL 4 // max kernel size -#define S_KC 256 -#define S_NC 128 // TODO these are just dummy -#define S_MC 3000 // TODO these are just dummy - -#elif defined( TARGET_X64_AMD_BULLDOZER ) -// common -#define CACHE_LINE_SIZE 64 -#define L1_CACHE_SIZE (32*1024) // L1 data cache size: 32 kB -// double -#define D_PS 4 // panel size -#define D_PLD 4 // 2 // GCD of panel length -#define D_M_KERNEL 4 // max kernel size -#define D_N_KERNEL 4 // max kernel size -#define D_KC 256 -#define D_NC 128 // TODO these are just dummy -#define D_MC 3000 // TODO these are just dummy -// single -#define S_PS 4 -#define S_PLD 4 //2 -#define S_M_KERNEL 4 // max kernel size -#define S_N_KERNEL 4 // max kernel size -#define S_KC 256 -#define S_NC 128 // TODO these are just dummy -#define S_MC 3000 // TODO these are just dummy - - -#elif defined( TARGET_X86_AMD_JAGUAR ) -// common -#define CACHE_LINE_SIZE 64 -#define L1_CACHE_SIZE (32*1024) // L1 data cache size: 32 kB -// double -#define D_PS 4 // panel size -#define D_PLD 4 // 2 // GCD of panel length -#define D_M_KERNEL 4 // max kernel size -#define D_N_KERNEL 4 // max kernel size -#define D_KC 256 -#define D_NC 128 // TODO these are just dummy -#define D_MC 3000 // TODO these are just dummy -// single -#define S_PS 4 -#define S_PLD 4 //2 -#define S_M_KERNEL 4 // max kernel size -#define S_N_KERNEL 4 // max kernel size -#define S_KC 256 -#define S_NC 128 // TODO these are just dummy -#define S_MC 3000 // TODO these are just dummy - - -#elif defined( TARGET_X86_AMD_BARCELONA ) -// common -#define CACHE_LINE_SIZE 64 -#define L1_CACHE_SIZE (32*1024) // L1 data cache size: 32 kB -// double -#define D_PS 4 // panel size -#define D_PLD 4 // 2 // GCD of panel length -#define D_M_KERNEL 4 // max kernel size -#define D_N_KERNEL 4 // max kernel size -#define D_KC 256 -#define D_NC 128 // TODO these are just dummy -#define D_MC 3000 // TODO these are just dummy -// single -#define S_PS 4 -#define S_PLD 4 //2 -#define S_M_KERNEL 4 // max kernel size -#define S_N_KERNEL 4 // max kernel size -#define S_KC 256 -#define S_NC 128 // TODO these are just dummy -#define S_MC 3000 // TODO these are just dummy - - -#elif defined(TARGET_ARMV8A_APPLE_M1) -// common -#define CACHE_LINE_SIZE 64 -#define L1_CACHE_SIZE (128*1024) // L1 data cache size (big cores): 64 kB, ?-way ; DTLB1 ? -#define LLC_CACHE_SIZE (12*1024*1024) // LLC (L2) cache size (big cores): 12 MB -// double -#define D_PS 4 // panel size -#define D_PLD 4 // 2 // GCD of panel length -#define D_M_KERNEL 8 // max kernel size -#define D_N_KERNEL 4 // max kernel size -#define D_KC 512 //256 -#define D_NC 128 //256 -#define D_MC 6000 -// single -#define S_PS 4 -#define S_PLD 4 //2 -#define S_M_KERNEL 8 // max kernel size -#define S_N_KERNEL 8 // max kernel size -#define S_KC 512 -#define S_NC 256 -#define S_MC 6000 - - -#elif defined(TARGET_ARMV8A_ARM_CORTEX_A76) -// common -#define CACHE_LINE_SIZE 64 -#define L1_CACHE_SIZE (64*1024) // L1 data cache size: 64 kB, 4-way ; DTLB1 48*4 kB = 192 kB -#define LLC_CACHE_SIZE (1*1024*1024) // LLC cache size: 1 MB -// double -#define D_PS 4 // panel size -#define D_PLD 4 // 2 // GCD of panel length -#define D_M_KERNEL 8 // max kernel size -#define D_N_KERNEL 4 // max kernel size -#define D_KC 512 //256 -#define D_NC 128 //256 -#define D_MC 6000 -// single -#define S_PS 4 -#define S_PLD 4 //2 -#define S_M_KERNEL 8 // max kernel size -#define S_N_KERNEL 8 // max kernel size -#define S_KC 512 -#define S_NC 256 -#define S_MC 6000 - - -#elif defined(TARGET_ARMV8A_ARM_CORTEX_A73) -// common -#define CACHE_LINE_SIZE 64 -#define L1_CACHE_SIZE (32*1024) // L1 data cache size: 32 (64?) kB, 4-way, seen as 8-(16-)way ; DTLB1 48*4 kB = 192 kB -#define LLC_CACHE_SIZE (1*1024*1024) // LLC cache size: 1 MB -// double -#define D_PS 4 // panel size -#define D_PLD 4 // 2 // GCD of panel length -#define D_M_KERNEL 8 // max kernel size -#define D_N_KERNEL 4 // max kernel size -#define D_KC 320 -#define D_NC 256 -#define D_MC 6000 -// single -#define S_PS 4 -#define S_PLD 4 //2 -#define S_M_KERNEL 8 // max kernel size -#define S_N_KERNEL 8 // max kernel size -#define S_KC 256 -#define S_NC 128 // TODO these are just dummy -#define S_MC 3000 // TODO these are just dummy - - -#elif defined(TARGET_ARMV8A_ARM_CORTEX_A57) -// common -#define CACHE_LINE_SIZE 64 -#define L1_CACHE_SIZE (32*1024) // L1 data cache size: 32 kB, 2-way ; DTLB1 32*4 kB = 128 kB -#define LLC_CACHE_SIZE (1*1024*1024) // LLC cache size: 1 MB // 2 MB ??? -// double -#define D_PS 4 // panel size -#define D_PLD 4 // 2 // GCD of panel length -#define D_M_KERNEL 8 // max kernel size -#define D_N_KERNEL 4 // max kernel size -#define D_KC 128 //224 //256 //192 -#define D_NC 72 //40 //36 //48 -#define D_MC (4*192) //512 //488 //600 -// single -#define S_PS 4 -#define S_PLD 4 //2 -#define S_M_KERNEL 8 // max kernel size -#define S_N_KERNEL 8 // max kernel size -#define S_KC 256 -#define S_NC 128 // TODO these are just dummy -#define S_MC 3000 // TODO these are just dummy - - -#elif defined(TARGET_ARMV8A_ARM_CORTEX_A55) -// common -#define CACHE_LINE_SIZE 64 -#define L1_CACHE_SIZE (32*1024) // L1 data cache size: 32 kB, 4-way ; DTLB1 16*4 kB = 64 kB -#define LLC_CACHE_SIZE (512*1024) // LLC cache size: 512 kB -// double -#define D_PS 4 // panel size -#define D_PLD 4 // 2 // GCD of panel length -#define D_M_KERNEL 12 // max kernel size -#define D_N_KERNEL 4 // max kernel size -#define D_KC 224 -#define D_NC 160 -#define D_MC 6000 -// single -#define S_PS 4 -#define S_PLD 4 //2 -#define S_M_KERNEL 8 // max kernel size -#define S_N_KERNEL 8 // max kernel size -#define S_KC 256 -#define S_NC 128 // TODO these are just dummy -#define S_MC 3000 // TODO these are just dummy - - -#elif defined(TARGET_ARMV8A_ARM_CORTEX_A53) -// common -#define CACHE_LINE_SIZE 64 -#define L1_CACHE_SIZE (32*1024) // L1 data cache size: 32 kB, 4-way ??? ; DTLB1 10*4 kB = 40 kB -#define LLC_CACHE_SIZE (256*1024) // LLC cache size: 256 kB -// double -#define D_PS 4 // panel size -#define D_PLD 4 // 2 // GCD of panel length -#define D_M_KERNEL 12 // max kernel size -#define D_N_KERNEL 4 // max kernel size -#define D_KC 160 -#define D_NC 128 -#define D_MC 6000 -// single -#define S_PS 4 -#define S_PLD 4 //2 -#define S_M_KERNEL 8 // max kernel size -#define S_N_KERNEL 8 // max kernel size -#define S_KC 256 -#define S_NC 128 // TODO these are just dummy -#define S_MC 3000 // TODO these are just dummy - - -#elif defined( TARGET_ARMV7A_ARM_CORTEX_A15 ) -// common -#define CACHE_LINE_SIZE 64 -#define L1_CACHE_SIZE (32*1024) // L1 data cache size: 32 kB -// double -#define D_PS 4 // panel size -#define D_PLD 4 // 2 // GCD of panel length -#define D_M_KERNEL 4 // max kernel size -#define D_N_KERNEL 4 // max kernel size -#define D_KC 256 -#define D_NC 128 // TODO these are just dummy -#define D_MC 3000 // TODO these are just dummy -// single -#define S_PS 4 -#define S_PLD 4 //2 -#define S_M_KERNEL 4 // max kernel size -#define S_N_KERNEL 4 // max kernel size -#define S_KC 256 -#define S_NC 128 // TODO these are just dummy -#define S_MC 3000 // TODO these are just dummy - - -#elif defined( TARGET_ARMV7A_ARM_CORTEX_A7 ) -// common -#define CACHE_LINE_SIZE 64 -#define L1_CACHE_SIZE (32*1024) // L1 data cache size: 32 kB -// double -#define D_PS 4 // panel size -#define D_PLD 4 // 2 // GCD of panel length -#define D_M_KERNEL 4 // max kernel size -#define D_N_KERNEL 4 // max kernel size -#define D_KC 256 -#define D_NC 128 // TODO these are just dummy -#define D_MC 3000 // TODO these are just dummy -// single -#define S_PS 4 -#define S_PLD 4 //2 -#define S_M_KERNEL 4 // max kernel size -#define S_N_KERNEL 4 // max kernel size -#define S_KC 256 -#define S_NC 128 // TODO these are just dummy -#define S_MC 3000 // TODO these are just dummy - - -#elif defined( TARGET_ARMV7A_ARM_CORTEX_A9 ) -// common -#define CACHE_LINE_SIZE 32 -#define L1_CACHE_SIZE (32*1024) // L1 data cache size: 32 kB -// double -#define D_PS 4 // panel size -#define D_PLD 4 // 2 // GCD of panel length -#define D_M_KERNEL 4 // max kernel size -#define D_N_KERNEL 4 // max kernel size -#define D_KC 256 -#define D_NC 128 // TODO these are just dummy -#define D_MC 3000 // TODO these are just dummy -// single -#define S_PS 4 -#define S_PLD 4 //2 -#define S_M_KERNEL 4 // max kernel size -#define S_N_KERNEL 4 // max kernel size -#define S_KC 256 -#define S_NC 128 // TODO these are just dummy -#define S_MC 3000 // TODO these are just dummy - - -#elif defined( TARGET_GENERIC ) -// common -#define CACHE_LINE_SIZE 64 -#define L1_CACHE_SIZE (32*1024) // L1 data cache size: 32 kB -// double -#define D_PS 4 // panel size -#define D_PLD 4 // 2 // GCD of panel length -#define D_M_KERNEL 4 // max kernel size -#define D_N_KERNEL 4 // max kernel size -#define D_KC 256 -#define D_NC 128 // TODO these are just dummy -#define D_MC 3000 // TODO these are just dummy - -// single -#define S_PS 4 -#define S_PLD 4 //2 -#define S_M_KERNEL 4 // max kernel size -#define S_N_KERNEL 4 // max kernel size -#define S_KC 256 -#define S_NC 128 // TODO these are just dummy -#define S_MC 3000 // TODO these are just dummy - - -#else -#error "Unknown architecture" -#endif - - - -#define D_CACHE_LINE_EL (CACHE_LINE_SIZE/D_EL_SIZE) -#define D_L1_CACHE_EL (L1_CACHE_SIZE/D_EL_SIZE) -#define D_L2_CACHE_EL (L2_CACHE_SIZE/D_EL_SIZE) -#define D_LLC_CACHE_EL (LLC_CACHE_SIZE/D_EL_SIZE) - -#define S_CACHE_LINE_EL (CACHE_LINE_SIZE/S_EL_SIZE) -#define S_L1_CACHE_EL (L1_CACHE_SIZE/S_EL_SIZE) -#define S_L2_CACHE_EL (L2_CACHE_SIZE/S_EL_SIZE) -#define S_LLC_CACHE_EL (LLC_CACHE_SIZE/S_EL_SIZE) - - - -#endif // BLASFEO_BLOCK_SIZE_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_common.h b/third_party/acados/include/blasfeo/include/blasfeo_common.h deleted file mode 100644 index 03b6c36d84..0000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_common.h +++ /dev/null @@ -1,274 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_COMMON_H_ -#define BLASFEO_COMMON_H_ - - - -#include "blasfeo_target.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -#if defined(__GNUC__) || defined(__clang__) || defined(__INTEL_COMPILER) || defined(__ICL) || defined(__ICC) || defined(__INTEL_LLVM_COMPILER) -#define ALIGNED(VEC, BYTES) VEC __attribute__ ((aligned ( BYTES ))) -#elif defined (_MSC_VER) -#define ALIGNED(VEC, BYTES) __declspec(align( BYTES )) VEC -#else -#define ALIGNED(VEC, BYTES) VEC -#endif - - - - -#if ( defined(LA_HIGH_PERFORMANCE) & defined(MF_PANELMAJ) ) | ( defined(LA_REFERENCE) & defined(MF_PANELMAJ) ) - -#include "blasfeo_block_size.h" - -// matrix structure -struct blasfeo_dmat - { - double *mem; // pointer to passed chunk of memory - double *pA; // pointer to a pm*pn array of doubles, the first is aligned to cache line size - double *dA; // pointer to a min(m,n) (or max???) array of doubles - int m; // rows - int n; // cols - int pm; // packed number or rows - int cn; // packed number or cols - int use_dA; // flag to tell if dA can be used - int memsize; // size of needed memory - }; - -struct blasfeo_smat - { - float *mem; // pointer to passed chunk of memory - float *pA; // pointer to a pm*pn array of floats, the first is aligned to cache line size - float *dA; // pointer to a min(m,n) (or max???) array of floats - int m; // rows - int n; // cols - int pm; // packed number or rows - int cn; // packed number or cols - int use_dA; // flag to tell if dA can be used - int memsize; // size of needed memory - }; - -// vector structure -struct blasfeo_dvec - { - double *mem; // pointer to passed chunk of memory - double *pa; // pointer to a pm array of doubles, the first is aligned to cache line size - int m; // size - int pm; // packed size - int memsize; // size of needed memory - }; - -struct blasfeo_svec - { - float *mem; // pointer to passed chunk of memory - float *pa; // pointer to a pm array of floats, the first is aligned to cache line size - int m; // size - int pm; // packed size - int memsize; // size of needed memory - }; - -#define BLASFEO_DMATEL(sA,ai,aj) ((sA)->pA[((ai)-((ai)&(D_PS-1)))*(sA)->cn+(aj)*D_PS+((ai)&(D_PS-1))]) -#define BLASFEO_SMATEL(sA,ai,aj) ((sA)->pA[((ai)-((ai)&(S_PS-1)))*(sA)->cn+(aj)*S_PS+((ai)&(S_PS-1))]) -#define BLASFEO_DVECEL(sa,ai) ((sa)->pa[ai]) -#define BLASFEO_SVECEL(sa,ai) ((sa)->pa[ai]) - -#elif ( defined(LA_HIGH_PERFORMANCE) & defined(MF_COLMAJ) ) | ( defined(LA_REFERENCE) & defined(MF_COLMAJ) ) | defined(LA_EXTERNAL_BLAS_WRAPPER) - -// matrix structure -struct blasfeo_dmat - { - double *mem; // pointer to passed chunk of memory - double *pA; // pointer to a m*n array of doubles - double *dA; // pointer to a min(m,n) (or max???) array of doubles - int m; // rows - int n; // cols - int use_dA; // flag to tell if dA can be used - int memsize; // size of needed memory - }; - -struct blasfeo_smat - { - float *mem; // pointer to passed chunk of memory - float *pA; // pointer to a m*n array of floats - float *dA; // pointer to a min(m,n) (or max???) array of floats - int m; // rows - int n; // cols - int use_dA; // flag to tell if dA can be used - int memsize; // size of needed memory - }; - -// vector structure -struct blasfeo_dvec - { - double *mem; // pointer to passed chunk of memory - double *pa; // pointer to a m array of doubles, the first is aligned to cache line size - int m; // size - int memsize; // size of needed memory - }; - -struct blasfeo_svec - { - float *mem; // pointer to passed chunk of memory - float *pa; // pointer to a m array of floats, the first is aligned to cache line size - int m; // size - int memsize; // size of needed memory - }; - -#define BLASFEO_DMATEL(sA,ai,aj) ((sA)->pA[(ai)+(aj)*(sA)->m]) -#define BLASFEO_SMATEL(sA,ai,aj) ((sA)->pA[(ai)+(aj)*(sA)->m]) -#define BLASFEO_DVECEL(sa,ai) ((sa)->pa[ai]) -#define BLASFEO_SVECEL(sa,ai) ((sa)->pa[ai]) - -#else - -#error : wrong LA or MF choice - -#endif - - - -// Explicitly panel-major matrix structure -struct blasfeo_pm_dmat - { - double *mem; // pointer to passed chunk of memory - double *pA; // pointer to a pm*pn array of doubles, the first is aligned to cache line size - double *dA; // pointer to a min(m,n) (or max???) array of doubles - int m; // rows - int n; // cols - int pm; // packed number or rows - int cn; // packed number or cols - int use_dA; // flag to tell if dA can be used - int ps; // panel size - int memsize; // size of needed memory - }; - -struct blasfeo_pm_smat - { - float *mem; // pointer to passed chunk of memory - float *pA; // pointer to a pm*pn array of floats, the first is aligned to cache line size - float *dA; // pointer to a min(m,n) (or max???) array of floats - int m; // rows - int n; // cols - int pm; // packed number or rows - int cn; // packed number or cols - int use_dA; // flag to tell if dA can be used - int ps; // panel size - int memsize; // size of needed memory - }; - -struct blasfeo_pm_dvec - { - double *mem; // pointer to passed chunk of memory - double *pa; // pointer to a pm array of doubles, the first is aligned to cache line size - int m; // size - int pm; // packed size - int memsize; // size of needed memory - }; - -struct blasfeo_pm_svec - { - float *mem; // pointer to passed chunk of memory - float *pa; // pointer to a pm array of floats, the first is aligned to cache line size - int m; // size - int pm; // packed size - int memsize; // size of needed memory - }; - -// Explicitly column-major matrix structure -struct blasfeo_cm_dmat - { - double *mem; // pointer to passed chunk of memory - double *pA; // pointer to a m*n array of doubles - double *dA; // pointer to a min(m,n) (or max???) array of doubles - int m; // rows - int n; // cols - int use_dA; // flag to tell if dA can be used - int memsize; // size of needed memory - }; - -struct blasfeo_cm_smat - { - float *mem; // pointer to passed chunk of memory - float *pA; // pointer to a m*n array of floats - float *dA; // pointer to a min(m,n) (or max???) array of floats - int m; // rows - int n; // cols - int use_dA; // flag to tell if dA can be used - int memsize; // size of needed memory - }; - -struct blasfeo_cm_dvec - { - double *mem; // pointer to passed chunk of memory - double *pa; // pointer to a m array of doubles, the first is aligned to cache line size - int m; // size - int memsize; // size of needed memory - }; - -struct blasfeo_cm_svec - { - float *mem; // pointer to passed chunk of memory - float *pa; // pointer to a m array of floats, the first is aligned to cache line size - int m; // size - int memsize; // size of needed memory - }; - - -#define BLASFEO_PM_DMATEL(sA,ai,aj) ((sA)->pA[((ai)-((ai)&((sA)->ps-1)))*(sA)->cn+(aj)*((sA)->ps)+((ai)&((sA)->ps-1))]) -#define BLASFEO_PM_SMATEL(sA,ai,aj) ((sA)->pA[((ai)-((ai)&((sA)->ps-1)))*(sA)->cn+(aj)*((sA)->ps)+((ai)&((sA)->ps-1))]) -#define BLASFEO_PM_DVECEL(sa,ai) ((sa)->pa[ai]) -#define BLASFEO_PM_SVECEL(sa,ai) ((sa)->pa[ai]) -#define BLASFEO_CM_DMATEL(sA,ai,aj) ((sA)->pA[(ai)+(aj)*(sA)->m]) -#define BLASFEO_CM_SMATEL(sA,ai,aj) ((sA)->pA[(ai)+(aj)*(sA)->m]) -#define BLASFEO_CM_DVECEL(sa,ai) ((sa)->pa[ai]) -#define BLASFEO_CM_SVECEL(sa,ai) ((sa)->pa[ai]) - - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_COMMON_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_d_aux.h b/third_party/acados/include/blasfeo/include/blasfeo_d_aux.h deleted file mode 100644 index a6d6119c6c..0000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_d_aux.h +++ /dev/null @@ -1,255 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -/* - * auxiliary algebra operations header - * - * include/blasfeo_aux_lib*.h - * - */ - -#ifndef BLASFEO_D_AUX_H_ -#define BLASFEO_D_AUX_H_ - - - -#include - -#include "blasfeo_common.h" -#include "blasfeo_d_aux_old.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - -// --- memory size calculations -// -// returns the memory size (in bytes) needed for a dmat -size_t blasfeo_memsize_dmat(int m, int n); -// returns the memory size (in bytes) needed for the diagonal of a dmat -size_t blasfeo_memsize_diag_dmat(int m, int n); -// returns the memory size (in bytes) needed for a dvec -size_t blasfeo_memsize_dvec(int m); - -// --- creation -// -// create a strmat for a matrix of size m*n by using memory passed by a pointer (pointer is not updated) -void blasfeo_create_dmat(int m, int n, struct blasfeo_dmat *sA, void *memory); -// create a strvec for a vector of size m by using memory passed by a pointer (pointer is not updated) -void blasfeo_create_dvec(int m, struct blasfeo_dvec *sA, void *memory); - -// --- packing -// pack the column-major matrix A into the matrix struct B -void blasfeo_pack_dmat(int m, int n, double *A, int lda, struct blasfeo_dmat *sB, int bi, int bj); -// pack the lower-triangular column-major matrix A into the matrix struct B -void blasfeo_pack_l_dmat(int m, int n, double *A, int lda, struct blasfeo_dmat *sB, int bi, int bj); -// pack the upper-triangular column-major matrix A into the matrix struct B -void blasfeo_pack_u_dmat(int m, int n, double *A, int lda, struct blasfeo_dmat *sB, int bi, int bj); -// transpose and pack the column-major matrix A into the matrix struct B -void blasfeo_pack_tran_dmat(int m, int n, double *A, int lda, struct blasfeo_dmat *sB, int bi, int bj); -// pack the vector x into the vector structure y -void blasfeo_pack_dvec(int m, double *x, int xi, struct blasfeo_dvec *sy, int yi); -// unpack the matrix structure A into the column-major matrix B -void blasfeo_unpack_dmat(int m, int n, struct blasfeo_dmat *sA, int ai, int aj, double *B, int ldb); -// transpose and unpack the matrix structure A into the column-major matrix B -void blasfeo_unpack_tran_dmat(int m, int n, struct blasfeo_dmat *sA, int ai, int aj, double *B, int ldb); -// pack the vector structure x into the vector y -void blasfeo_unpack_dvec(int m, struct blasfeo_dvec *sx, int xi, double *y, int yi); - -// --- cast -// -//void d_cast_mat2strmat(double *A, struct blasfeo_dmat *sA); // TODO -//void d_cast_diag_mat2strmat(double *dA, struct blasfeo_dmat *sA); // TODO -//void d_cast_vec2vecmat(double *a, struct blasfeo_dvec *sx); // TODO - - -// ge -// --- insert/extract -// -// sA[ai, aj] <= a -void blasfeo_dgein1(double a, struct blasfeo_dmat *sA, int ai, int aj); -// <= sA[ai, aj] -double blasfeo_dgeex1(struct blasfeo_dmat *sA, int ai, int aj); - -// --- set -// A <= alpha -void blasfeo_dgese(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj); - -// --- copy / scale -// B <= A -void blasfeo_dgecp(int m, int n, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj); -// A <= alpha*A -void blasfeo_dgesc(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj); -// B <= alpha*A -void blasfeo_dgecpsc(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj); -// B <= A, A lower triangular -void blasfeo_dtrcp_l(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj); -void blasfeo_dtrcpsc_l(int m, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj); -void blasfeo_dtrsc_l(int m, double alpha, struct blasfeo_dmat *sA, int ai, int aj); - -// --- sum -// B <= B + alpha*A -void blasfeo_dgead(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj); -// y <= y + alpha*x -void blasfeo_dvecad(int m, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi); - -// --- traspositions -// B <= A' -void blasfeo_dgetr(int m, int n, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj); -// B <= A', A lower triangular -void blasfeo_dtrtr_l(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj); -// B <= A', A upper triangular -void blasfeo_dtrtr_u(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj); - -// dia -// diag(A) += alpha -void blasfeo_ddiare(int kmax, double alpha, struct blasfeo_dmat *sA, int ai, int aj); -// diag(A) <= alpha*x -void blasfeo_ddiain(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dmat *sA, int ai, int aj); -// diag(A)[idx] <= alpha*x -void blasfeo_ddiain_sp(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, int *idx, struct blasfeo_dmat *sD, int di, int dj); -// x <= diag(A) -void blasfeo_ddiaex(int kmax, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi); -// x <= diag(A)[idx] -void blasfeo_ddiaex_sp(int kmax, double alpha, int *idx, struct blasfeo_dmat *sD, int di, int dj, struct blasfeo_dvec *sx, int xi); -// diag(A) += alpha*x -void blasfeo_ddiaad(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dmat *sA, int ai, int aj); -// diag(A)[idx] += alpha*x -void blasfeo_ddiaad_sp(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, int *idx, struct blasfeo_dmat *sD, int di, int dj); -// diag(A)[idx] = y + alpha*x -void blasfeo_ddiaadin_sp(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi, int *idx, struct blasfeo_dmat *sD, int di, int dj); - -// row -void blasfeo_drowin(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dmat *sA, int ai, int aj); -void blasfeo_drowex(int kmax, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi); -void blasfeo_drowad(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dmat *sA, int ai, int aj); -void blasfeo_drowad_sp(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, int *idx, struct blasfeo_dmat *sD, int di, int dj); -void blasfeo_drowsw(int kmax, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sC, int ci, int cj); -void blasfeo_drowpe(int kmax, int *ipiv, struct blasfeo_dmat *sA); -void blasfeo_drowpei(int kmax, int *ipiv, struct blasfeo_dmat *sA); - -// col -void blasfeo_dcolex(int kmax, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi); -void blasfeo_dcolin(int kmax, struct blasfeo_dvec *sx, int xi, struct blasfeo_dmat *sA, int ai, int aj); -void blasfeo_dcolad(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dmat *sA, int ai, int aj); -void blasfeo_dcolsc(int kmax, double alpha, struct blasfeo_dmat *sA, int ai, int aj); -void blasfeo_dcolsw(int kmax, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sC, int ci, int cj); -void blasfeo_dcolpe(int kmax, int *ipiv, struct blasfeo_dmat *sA); -void blasfeo_dcolpei(int kmax, int *ipiv, struct blasfeo_dmat *sA); - -// vec -// a <= alpha -void blasfeo_dvecse(int m, double alpha, struct blasfeo_dvec *sx, int xi); -// sx[xi] <= a -void blasfeo_dvecin1(double a, struct blasfeo_dvec *sx, int xi); -// <= sx[xi] -double blasfeo_dvecex1(struct blasfeo_dvec *sx, int xi); -// y <= x -void blasfeo_dveccp(int m, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi); -// x <= alpha*x -void blasfeo_dvecsc(int m, double alpha, struct blasfeo_dvec *sx, int xi); -// y <= alpha*x -void blasfeo_dveccpsc(int m, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi); -// z[idx] += alpha * x -void blasfeo_dvecad_sp(int m, double alpha, struct blasfeo_dvec *sx, int xi, int *idx, struct blasfeo_dvec *sz, int zi); -// z[idx] <= alpha * x -void blasfeo_dvecin_sp(int m, double alpha, struct blasfeo_dvec *sx, int xi, int *idx, struct blasfeo_dvec *sz, int zi); -// z <= alpha * x[idx] -void blasfeo_dvecex_sp(int m, double alpha, int *idx, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z += alpha * x[idx] -void blasfeo_dvecexad_sp(int m, double alpha, int *idx, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); - -void blasfeo_dveccl(int m, - struct blasfeo_dvec *sxm, int xim, struct blasfeo_dvec *sx, int xi, - struct blasfeo_dvec *sxp, int xip, struct blasfeo_dvec *sz, int zi); - -void blasfeo_dveccl_mask(int m, - struct blasfeo_dvec *sxm, int xim, struct blasfeo_dvec *sx, int xi, - struct blasfeo_dvec *sxp, int xip, struct blasfeo_dvec *sz, int zi, - struct blasfeo_dvec *sm, int mi); - -void blasfeo_dvecze(int m, struct blasfeo_dvec *sm, int mi, struct blasfeo_dvec *sv, int vi, struct blasfeo_dvec *se, int ei); -void blasfeo_dvecnrm_inf(int m, struct blasfeo_dvec *sx, int xi, double *ptr_norm); -void blasfeo_dvecnrm_2(int m, struct blasfeo_dvec *sx, int xi, double *ptr_norm); -void blasfeo_dvecpe(int kmax, int *ipiv, struct blasfeo_dvec *sx, int xi); -void blasfeo_dvecpei(int kmax, int *ipiv, struct blasfeo_dvec *sx, int xi); - - - - - -/* -* Explicitly panel-major matrix format -*/ - -// returns the memory size (in bytes) needed for a dmat -size_t blasfeo_pm_memsize_dmat(int ps, int m, int n); -// create a strmat for a matrix of size m*n by using memory passed by a pointer (pointer is not updated) -void blasfeo_pm_create_dmat(int ps, int m, int n, struct blasfeo_pm_dmat *sA, void *memory); -// print -void blasfeo_pm_print_dmat(int m, int n, struct blasfeo_pm_dmat *sA, int ai, int aj); - - - -/* -* Explicitly panel-major matrix format -*/ - -// returns the memory size (in bytes) needed for a dmat -size_t blasfeo_cm_memsize_dmat(int m, int n); -// create a strmat for a matrix of size m*n by using memory passed by a pointer (pointer is not updated) -void blasfeo_cm_create_dmat(int m, int n, struct blasfeo_pm_dmat *sA, void *memory); - - - -// -// BLAS API helper functions -// - -#if ( defined(BLAS_API) & defined(MF_PANELMAJ) ) -// aux -void blasfeo_cm_dgetr(int m, int n, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj); -#endif - - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_D_AUX_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_d_aux_ext_dep.h b/third_party/acados/include/blasfeo/include/blasfeo_d_aux_ext_dep.h deleted file mode 100644 index bee9e986f1..0000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_d_aux_ext_dep.h +++ /dev/null @@ -1,145 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -/* - * auxiliary algebra operation external dependancies header - * - * include/blasfeo_d_aux_ext_dep.h - * - * - dynamic memory allocation - * - print - * - */ - -#ifndef BLASFEO_D_AUX_EXT_DEP_H_ -#define BLASFEO_D_AUX_EXT_DEP_H_ - - - -#include - - - -#include "blasfeo_common.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -#ifdef EXT_DEP - -/* column-major matrices */ - -// dynamically allocate row*col doubles of memory and set accordingly a pointer to double; set allocated memory to zero -void d_zeros(double **pA, int row, int col); -// dynamically allocate row*col doubles of memory aligned to 64-byte boundaries and set accordingly a pointer to double; set allocated memory to zero -void d_zeros_align(double **pA, int row, int col); -// dynamically allocate size bytes of memory aligned to 64-byte boundaries and set accordingly a pointer to double; set allocated memory to zero -void d_zeros_align_bytes(double **pA, int size); -// free the memory allocated by d_zeros -void d_free(double *pA); -// free the memory allocated by d_zeros_align or d_zeros_align_bytes -void d_free_align(double *pA); -// print a column-major matrix -void d_print_mat(int m, int n, double *A, int lda); -// print the transposed of a column-major matrix -void d_print_tran_mat(int row, int col, double *A, int lda); -// print to file a column-major matrix -void d_print_to_file_mat(FILE *file, int row, int col, double *A, int lda); -// print to file a column-major matrix in exponential format -void d_print_to_file_exp_mat(FILE *file, int row, int col, double *A, int lda); -// print to string a column-major matrix -void d_print_to_string_mat(char **buf_out, int row, int col, double *A, int lda); -// print to file the transposed of a column-major matrix -void d_print_tran_to_file_mat(FILE *file, int row, int col, double *A, int lda); -// print to file the transposed of a column-major matrix in exponential format -void d_print_tran_to_file_exp_mat(FILE *file, int row, int col, double *A, int lda); -// print in exponential notation a column-major matrix -void d_print_exp_mat(int m, int n, double *A, int lda); -// print in exponential notation the transposed of a column-major matrix -void d_print_exp_tran_mat(int row, int col, double *A, int lda); - -/* strmat and strvec */ - -// create a strmat for a matrix of size m*n by dynamically allocating memory -void blasfeo_allocate_dmat(int m, int n, struct blasfeo_dmat *sA); -// create a strvec for a vector of size m by dynamically allocating memory -void blasfeo_allocate_dvec(int m, struct blasfeo_dvec *sa); -// free the memory allocated by blasfeo_allocate_dmat -void blasfeo_free_dmat(struct blasfeo_dmat *sA); -// free the memory allocated by blasfeo_allocate_dvec -void blasfeo_free_dvec(struct blasfeo_dvec *sa); -// print a strmat -void blasfeo_print_dmat(int m, int n, struct blasfeo_dmat *sA, int ai, int aj); -// print in exponential notation a strmat -void blasfeo_print_exp_dmat(int m, int n, struct blasfeo_dmat *sA, int ai, int aj); -// print to file a strmat -void blasfeo_print_to_file_dmat(FILE *file, int m, int n, struct blasfeo_dmat *sA, int ai, int aj); -// print to file a strmat in exponential format -void blasfeo_print_to_file_exp_dmat(FILE *file, int m, int n, struct blasfeo_dmat *sA, int ai, int aj); -// print to string a strmat -void blasfeo_print_to_string_dmat(char **buf_out, int m, int n, struct blasfeo_dmat *sA, int ai, int aj); -// print the transposed of a strmat -void blasfeo_print_tran_dmat(int m, int n, struct blasfeo_dmat *sA, int ai, int aj); -// print a strvec -void blasfeo_print_dvec(int m, struct blasfeo_dvec *sa, int ai); -// print in exponential notation a strvec -void blasfeo_print_exp_dvec(int m, struct blasfeo_dvec *sa, int ai); -// print to file a strvec -void blasfeo_print_to_file_dvec(FILE *file, int m, struct blasfeo_dvec *sa, int ai); -// print to string a strvec -void blasfeo_print_to_string_dvec(char **buf_out, int m, struct blasfeo_dvec *sa, int ai); -// print the transposed of a strvec -void blasfeo_print_tran_dvec(int m, struct blasfeo_dvec *sa, int ai); -// print in exponential notation the transposed of a strvec -void blasfeo_print_exp_tran_dvec(int m, struct blasfeo_dvec *sa, int ai); -// print to file the transposed of a strvec -void blasfeo_print_to_file_tran_dvec(FILE *file, int m, struct blasfeo_dvec *sa, int ai); -// print to string the transposed of a strvec -void blasfeo_print_to_string_tran_dvec(char **buf_out, int m, struct blasfeo_dvec *sa, int ai); - -#endif // EXT_DEP - - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_D_AUX_EXT_DEP_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_d_aux_ext_dep_ref.h b/third_party/acados/include/blasfeo/include/blasfeo_d_aux_ext_dep_ref.h deleted file mode 100644 index 81b811f032..0000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_d_aux_ext_dep_ref.h +++ /dev/null @@ -1,84 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -/* - * auxiliary algebra operation external dependancies header - * - * include/blasfeo_d_aux_ext_dep.h - * - * - dynamic memory allocation - * - print - * - */ - -#ifndef BLASFEO_D_AUX_EXT_DEP_REF_H_ -#define BLASFEO_D_AUX_EXT_DEP_REF_H_ - - -#include - -#include "blasfeo_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - -// expose reference BLASFEO for testing -// see blasfeo_d_aux_exp_dep.h for help - -void blasfeo_print_dmat_ref(int m, int n, struct blasfeo_dmat_ref *sA, int ai, int aj); -void blasfeo_allocate_dmat_ref(int m, int n, struct blasfeo_dmat_ref *sA); -void blasfeo_allocate_dvec_ref(int m, struct blasfeo_dvec_ref *sa); -void blasfeo_free_dmat_ref(struct blasfeo_dmat_ref *sA); -void blasfeo_free_dvec_ref(struct blasfeo_dvec_ref *sa); -void blasfeo_print_dmat_ref(int m, int n, struct blasfeo_dmat_ref *sA, int ai, int aj); -void blasfeo_print_exp_dmat_ref(int m, int n, struct blasfeo_dmat_ref *sA, int ai, int aj); -void blasfeo_print_to_file_dmat_ref(FILE *file, int m, int n, struct blasfeo_dmat_ref *sA, int ai, int aj); -void blasfeo_print_to_file_exp_dmat_ref(FILE *file, int m, int n, struct blasfeo_dmat_ref *sA, int ai, int aj); -void blasfeo_print_to_string_dmat_ref(char **buf_out, int m, int n, struct blasfeo_dmat_ref *sA, int ai, int aj); -void blasfeo_print_dvec(int m, struct blasfeo_dvec *sa, int ai); -void blasfeo_print_exp_dvec(int m, struct blasfeo_dvec *sa, int ai); -void blasfeo_print_to_file_dvec(FILE *file, int m, struct blasfeo_dvec *sa, int ai); -void blasfeo_print_to_string_dvec(char **buf_out, int m, struct blasfeo_dvec *sa, int ai); -void blasfeo_print_tran_dvec(int m, struct blasfeo_dvec *sa, int ai); -void blasfeo_print_exp_tran_dvec(int m, struct blasfeo_dvec *sa, int ai); -void blasfeo_print_to_file_tran_dvec(FILE *file, int m, struct blasfeo_dvec *sa, int ai); -void blasfeo_print_to_string_tran_dvec(char **buf_out, int m, struct blasfeo_dvec *sa, int ai); - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_D_AUX_EXT_DEP_REF_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_d_aux_old.h b/third_party/acados/include/blasfeo/include/blasfeo_d_aux_old.h deleted file mode 100644 index 3a1847a6a0..0000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_d_aux_old.h +++ /dev/null @@ -1,75 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -/* - * ----------- TOMOVE - * - * expecting column major matrices - * - */ - -#include "blasfeo_common.h" - - -void dtrcp_l_lib(int m, double alpha, int offsetA, double *A, int sda, int offsetB, double *B, int sdb); -void dgead_lib(int m, int n, double alpha, int offsetA, double *A, int sda, int offsetB, double *B, int sdb); -// TODO remove ??? -void ddiain_sqrt_lib(int kmax, double *x, int offset, double *pD, int sdd); -// TODO ddiaad1 -void ddiareg_lib(int kmax, double reg, int offset, double *pD, int sdd); - - -void dgetr_lib(int m, int n, double alpha, int offsetA, double *pA, int sda, int offsetC, double *pC, int sdc); -void dtrtr_l_lib(int m, double alpha, int offsetA, double *pA, int sda, int offsetC, double *pC, int sdc); -void dtrtr_u_lib(int m, double alpha, int offsetA, double *pA, int sda, int offsetC, double *pC, int sdc); -void ddiaex_lib(int kmax, double alpha, int offset, double *pD, int sdd, double *x); -void ddiaad_lib(int kmax, double alpha, double *x, int offset, double *pD, int sdd); -void ddiain_libsp(int kmax, int *idx, double alpha, double *x, double *pD, int sdd); -void ddiaex_libsp(int kmax, int *idx, double alpha, double *pD, int sdd, double *x); -void ddiaad_libsp(int kmax, int *idx, double alpha, double *x, double *pD, int sdd); -void ddiaadin_libsp(int kmax, int *idx, double alpha, double *x, double *y, double *pD, int sdd); -void drowin_lib(int kmax, double alpha, double *x, double *pD); -void drowex_lib(int kmax, double alpha, double *pD, double *x); -void drowad_lib(int kmax, double alpha, double *x, double *pD); -void drowin_libsp(int kmax, double alpha, int *idx, double *x, double *pD); -void drowad_libsp(int kmax, int *idx, double alpha, double *x, double *pD); -void drowadin_libsp(int kmax, int *idx, double alpha, double *x, double *y, double *pD); -void dcolin_lib(int kmax, double *x, int offset, double *pD, int sdd); -void dcolad_lib(int kmax, double alpha, double *x, int offset, double *pD, int sdd); -void dcolin_libsp(int kmax, int *idx, double *x, double *pD, int sdd); -void dcolad_libsp(int kmax, double alpha, int *idx, double *x, double *pD, int sdd); -void dcolsw_lib(int kmax, int offsetA, double *pA, int sda, int offsetC, double *pC, int sdc); -void dvecin_libsp(int kmax, int *idx, double *x, double *y); -void dvecad_libsp(int kmax, int *idx, double alpha, double *x, double *y); diff --git a/third_party/acados/include/blasfeo/include/blasfeo_d_aux_ref.h b/third_party/acados/include/blasfeo/include/blasfeo_d_aux_ref.h deleted file mode 100644 index 1e007fa89e..0000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_d_aux_ref.h +++ /dev/null @@ -1,208 +0,0 @@ - -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_D_AUX_REF_H_ -#define BLASFEO_D_AUX_REF_H_ - - - -#include - -#include "blasfeo_common.h" -#include "blasfeo_d_aux_old.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - -// --- memory calculations -// -// returns the memory size (in bytes) needed for a dmat -size_t blasfeo_ref_memsize_dmat(int m, int n); -// returns the memory size (in bytes) needed for the diagonal of a dmat -size_t blasfeo_ref_memsize_diag_dmat(int m, int n); -// returns the memory size (in bytes) needed for a dvec -size_t blasfeo_ref_memsize_dvec(int m); - -// --- creation -// -// create a strmat for a matrix of size m*n by using memory passed by a pointer (pointer is not updated) -void blasfeo_ref_create_dmat(int m, int n, struct blasfeo_dmat *sA, void *memory); -// create a strvec for a vector of size m by using memory passed by a pointer (pointer is not updated) -void blasfeo_ref_create_dvec(int m, struct blasfeo_dvec *sA, void *memory); - -// --- packing -// pack the column-major matrix A into the matrix struct B -void blasfeo_ref_pack_dmat(int m, int n, double *A, int lda, struct blasfeo_dmat *sB, int bi, int bj); -// pack the lower-triangular column-major matrix A into the matrix struct B -void blasfeo_ref_pack_l_dmat(int m, int n, double *A, int lda, struct blasfeo_dmat *sB, int bi, int bj); -// pack the upper-triangular column-major matrix A into the matrix struct B -void blasfeo_ref_pack_u_dmat(int m, int n, double *A, int lda, struct blasfeo_dmat *sB, int bi, int bj); -// transpose and pack the column-major matrix A into the matrix struct B -void blasfeo_ref_pack_tran_dmat(int m, int n, double *A, int lda, struct blasfeo_dmat *sB, int bi, int bj); -// pack the vector x into the vector structure y -void blasfeo_ref_pack_dvec(int m, double *x, int xi, struct blasfeo_dvec *sy, int yi); -// unpack the matrix structure A into the column-major matrix B -void blasfeo_ref_unpack_dmat(int m, int n, struct blasfeo_dmat *sA, int ai, int aj, double *B, int ldb); -// transpose and unpack the matrix structure A into the column-major matrix B -void blasfeo_ref_unpack_tran_dmat(int m, int n, struct blasfeo_dmat *sA, int ai, int aj, double *B, int ldb); -// pack the vector structure x into the vector y -void blasfeo_ref_unpack_dvec(int m, struct blasfeo_dvec *sx, int xi, double *y, int yi); - -// --- cast -// -void ref_d_cast_mat2strmat(double *A, struct blasfeo_dmat *sA); // TODO -void ref_d_cast_diag_mat2strmat(double *dA, struct blasfeo_dmat *sA); // TODO -void ref_d_cast_vec2vecmat(double *a, struct blasfeo_dvec *sx); // TODO - - -// ge -// --- insert/extract -// -// sA[ai, aj] <= a -void blasfeo_ref_dgein1(double a, struct blasfeo_dmat *sA, int ai, int aj); -// <= sA[ai, aj] -double blasfeo_ref_dgeex1(struct blasfeo_dmat *sA, int ai, int aj); - -// --- set -// A <= alpha -void blasfeo_ref_dgese(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj); - -// --- copy / scale -// B <= A -void blasfeo_ref_dgecp(int m, int n, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj); -// A <= alpha*A -void blasfeo_ref_dgesc(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj); -// B <= alpha*A -void blasfeo_ref_dgecpsc(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj); -// B <= A, A lower triangular -void blasfeo_ref_dtrcp_l(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj); -void blasfeo_ref_dtrcpsc_l(int m, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj); -void blasfeo_ref_dtrsc_l(int m, double alpha, struct blasfeo_dmat *sA, int ai, int aj); - -// --- sum -// B <= B + alpha*A -void blasfeo_ref_dgead(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sC, int yi, int cj); -// y <= y + alpha*x -void blasfeo_ref_dvecad(int m, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi); - -// --- traspositions -// B <= A' -void blasfeo_ref_dgetr(int m, int n, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj); -// B <= A', A lower triangular -void blasfeo_ref_dtrtr_l(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj); -// B <= A', A upper triangular -void blasfeo_ref_dtrtr_u(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj); - -// dia -// diag(A) += alpha -void blasfeo_ref_ddiare(int kmax, double alpha, struct blasfeo_dmat *sA, int ai, int aj); -// diag(A) <= alpha*x -void blasfeo_ref_ddiain(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dmat *sA, int ai, int aj); -// diag(A)[idx] <= alpha*x -void blasfeo_ref_ddiain_sp(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, int *idx, struct blasfeo_dmat *sD, int di, int dj); -// x <= diag(A) -void blasfeo_ref_ddiaex(int kmax, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi); -// x <= diag(A)[idx] -void blasfeo_ref_ddiaex_sp(int kmax, double alpha, int *idx, struct blasfeo_dmat *sD, int di, int dj, struct blasfeo_dvec *sx, int xi); -// diag(A) += alpha*x -void blasfeo_ref_ddiaad(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dmat *sA, int ai, int aj); -// diag(A)[idx] += alpha*x -void blasfeo_ref_ddiaad_sp(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, int *idx, struct blasfeo_dmat *sD, int di, int dj); -// diag(A)[idx] = y + alpha*x -void blasfeo_ref_ddiaadin_sp(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi, int *idx, struct blasfeo_dmat *sD, int di, int dj); - -// row -void blasfeo_ref_drowin(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dmat *sA, int ai, int aj); -void blasfeo_ref_drowex(int kmax, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi); -void blasfeo_ref_drowad(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dmat *sA, int ai, int aj); -void blasfeo_ref_drowad_sp(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, int *idx, struct blasfeo_dmat *sD, int di, int dj); -void blasfeo_ref_drowsw(int kmax, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sC, int ci, int cj); -void blasfeo_ref_drowpe(int kmax, int *ipiv, struct blasfeo_dmat *sA); -void blasfeo_ref_drowpei(int kmax, int *ipiv, struct blasfeo_dmat *sA); - -// col -void blasfeo_ref_dcolex(int kmax, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi); -void blasfeo_ref_dcolin(int kmax, struct blasfeo_dvec *sx, int xi, struct blasfeo_dmat *sA, int ai, int aj); -void blasfeo_ref_dcolad(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dmat *sA, int ai, int aj); -void blasfeo_ref_dcolsc(int kmax, double alpha, struct blasfeo_dmat *sA, int ai, int aj); -void blasfeo_ref_dcolsw(int kmax, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sC, int ci, int cj); -void blasfeo_ref_dcolpe(int kmax, int *ipiv, struct blasfeo_dmat *sA); -void blasfeo_ref_dcolpei(int kmax, int *ipiv, struct blasfeo_dmat *sA); - -// vec -// a <= alpha -void blasfeo_ref_dvecse(int m, double alpha, struct blasfeo_dvec *sx, int xi); -// sx[xi] <= a -void blasfeo_ref_dvecin1(double a, struct blasfeo_dvec *sx, int xi); -// <= sx[xi] -double blasfeo_ref_dvecex1(struct blasfeo_dvec *sx, int xi); -// y <= x -void blasfeo_ref_dveccp(int m, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi); -// x <= alpha*x -void blasfeo_ref_dvecsc(int m, double alpha, struct blasfeo_dvec *sx, int xi); -// y <= alpha*x -void blasfeo_ref_dveccpsc(int m, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi); -void blasfeo_ref_dvecad_sp(int m, double alpha, struct blasfeo_dvec *sx, int xi, int *idx, struct blasfeo_dvec *sz, int zi); -void blasfeo_ref_dvecin_sp(int m, double alpha, struct blasfeo_dvec *sx, int xi, int *idx, struct blasfeo_dvec *sz, int zi); -void blasfeo_ref_dvecex_sp(int m, double alpha, int *idx, struct blasfeo_dvec *sx, int x, struct blasfeo_dvec *sz, int zi); -// z += alpha * x[idx] -void blasfeo_ref_dvecexad_sp(int m, double alpha, int *idx, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); - -void blasfeo_ref_dveccl(int m, - struct blasfeo_dvec *sxm, int xim, struct blasfeo_dvec *sx, int xi, - struct blasfeo_dvec *sxp, int xip, struct blasfeo_dvec *sz, int zi); - -void blasfeo_ref_dveccl_mask(int m, - struct blasfeo_dvec *sxm, int xim, struct blasfeo_dvec *sx, int xi, - struct blasfeo_dvec *sxp, int xip, struct blasfeo_dvec *sz, int zi, - struct blasfeo_dvec *sm, int mi); - -void blasfeo_ref_dvecze(int m, struct blasfeo_dvec *sm, int mi, struct blasfeo_dvec *sv, int vi, struct blasfeo_dvec *se, int ei); -void blasfeo_ref_dvecnrm_inf(int m, struct blasfeo_dvec *sx, int xi, double *ptr_norm); -void blasfeo_ref_dvecpe(int kmax, int *ipiv, struct blasfeo_dvec *sx, int xi); -void blasfeo_ref_dvecpei(int kmax, int *ipiv, struct blasfeo_dvec *sx, int xi); - - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_D_AUX_REF_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_d_aux_test.h b/third_party/acados/include/blasfeo/include/blasfeo_d_aux_test.h deleted file mode 100644 index 1c61635f3f..0000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_d_aux_test.h +++ /dev/null @@ -1,226 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -/* - * auxiliary algebra operations header - * - * include/blasfeo_aux_lib*.h - * - */ - -#ifndef BLASFEO_D_AUX_TEST_H_ -#define BLASFEO_D_AUX_TEST_H_ - -#include "blasfeo_common.h" - - -#ifdef __cplusplus -extern "C" { -#endif - -// --- memory calculations -int test_blasfeo_memsize_dmat(int m, int n); -int test_blasfeo_memsize_diag_dmat(int m, int n); -int test_blasfeo_memsize_dvec(int m); - -// --- creation -void test_blasfeo_create_dmat(int m, int n, struct blasfeo_dmat *sA, void *memory); -void test_blasfeo_create_dvec(int m, struct blasfeo_dvec *sA, void *memory); - -// --- conversion -void test_blasfeo_pack_dmat(int m, int n, double *A, int lda, struct blasfeo_dmat *sA, int ai, int aj); -void test_blasfeo_pack_dvec(int m, double *x, int xi, struct blasfeo_dvec *sa, int ai); -void test_blasfeo_pack_tran_dmat(int m, int n, double *A, int lda, struct blasfeo_dmat *sA, int ai, int aj); -void test_blasfeo_unpack_dmat(int m, int n, struct blasfeo_dmat *sA, int ai, int aj, double *A, int lda); -void test_blasfeo_unpack_dvec(int m, struct blasfeo_dvec *sa, int ai, double *x, int xi); -void test_blasfeo_unpack_tran_dmat(int m, int n, struct blasfeo_dmat *sA, int ai, int aj, double *A, int lda); - -// --- cast -void test_d_cast_mat2strmat(double *A, struct blasfeo_dmat *sA); -void test_d_cast_diag_mat2strmat(double *dA, struct blasfeo_dmat *sA); -void test_d_cast_vec2vecmat(double *a, struct blasfeo_dvec *sa); - -// ------ copy / scale - -// B <= A -void test_blasfeo_dgecp(int m, int n, - struct blasfeo_dmat *sA, int ai, int aj, - struct blasfeo_dmat *sB, int bi, int bj); - -// A <= alpha*A -void test_blasfeo_dgesc(int m, int n, - double alpha, - struct blasfeo_dmat *sA, int ai, int aj); - -// B <= alpha*A -void test_blasfeo_dgecpsc(int m, int n, - double alpha, - struct blasfeo_dmat *sA, int ai, int aj, - struct blasfeo_dmat *sB, int bi, int bj); - -// // --- insert/extract -// // -// // <= sA[ai, aj] -// void test_blasfeo_dgein1(double a, struct blasfeo_dmat *sA, int ai, int aj); -// // <= sA[ai, aj] -// double blasfeo_dgeex1(struct blasfeo_dmat *sA, int ai, int aj); -// // sx[xi] <= a -// void test_blasfeo_dvecin1(double a, struct blasfeo_dvec *sx, int xi); -// // <= sx[xi] -// double blasfeo_dvecex1(struct blasfeo_dvec *sx, int xi); -// // A <= alpha - -// // --- set -// void test_blasfeo_dgese(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj); -// // a <= alpha -// void test_blasfeo_dvecse(int m, double alpha, struct blasfeo_dvec *sx, int xi); -// // B <= A - - -// // --- vector -// // y <= x -// void test_blasfeo_dveccp(int m, struct blasfeo_dvec *sa, int ai, struct blasfeo_dvec *sc, int ci); -// // x <= alpha*x -// void test_blasfeo_dvecsc(int m, double alpha, struct blasfeo_dvec *sa, int ai); -// // TODO -// // x <= alpha*x -// void test_blasfeo_dveccpsc(int m, double alpha, struct blasfeo_dvec *sa, int ai, struct blasfeo_dvec *sc, int ci); - - -// // B <= A, A lower triangular -// void test_blasfeo_dtrcp_l(int m, -// struct blasfeo_dmat *sA, int ai, int aj, -// struct blasfeo_dmat *sB, int bi, int bj); - -// void test_blasfeo_dtrcpsc_l(int m, double alpha, -// struct blasfeo_dmat *sA, int ai, int aj, -// struct blasfeo_dmat *sB, int bi, int bj); - -// void test_blasfeo_dtrsc_l(int m, double alpha, -// struct blasfeo_dmat *sA, int ai, int aj); - - -// // B <= B + alpha*A -// void test_blasfeo_dgead(int m, int n, double alpha, -// struct blasfeo_dmat *sA, int ai, int aj, -// struct blasfeo_dmat *sC, int ci, int cj); - -// // y <= y + alpha*x -// void test_blasfeo_dvecad(int m, double alpha, -// struct blasfeo_dvec *sa, int ai, -// struct blasfeo_dvec *sc, int ci); - -// // --- traspositions -// void test_dgetr_lib(int m, int n, double alpha, int offsetA, double *pA, int sda, int offsetC, double *pC, int sdc); -// void test_blasfeo_dgetr(int m, int n, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sC, int ci, int cj); -// void test_dtrtr_l_lib(int m, double alpha, int offsetA, double *pA, int sda, int offsetC, double *pC, int sdc); -// void test_blasfeo_dtrtr_l(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sC, int ci, int cj); -// void test_dtrtr_u_lib(int m, double alpha, int offsetA, double *pA, int sda, int offsetC, double *pC, int sdc); -// void test_blasfeo_dtrtr_u(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sC, int ci, int cj); -// void test_blasfeo_ddiare(int kmax, double alpha, struct blasfeo_dmat *sA, int ai, int aj); -// void test_blasfeo_ddiain(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dmat *sA, int ai, int aj); -// void test_ddiaex_lib(int kmax, double alpha, int offset, double *pD, int sdd, double *x); -// void test_ddiaad_lib(int kmax, double alpha, double *x, int offset, double *pD, int sdd); -// void test_ddiain_libsp(int kmax, int *idx, double alpha, double *x, double *pD, int sdd); -// void test_blasfeo_ddiain_sp(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, int *idx, struct blasfeo_dmat *sD, int di, int dj); -// void test_ddiaex_libsp(int kmax, int *idx, double alpha, double *pD, int sdd, double *x); -// void test_blasfeo_ddiaex(int kmax, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi); -// void test_blasfeo_ddiaex_sp(int kmax, double alpha, int *idx, struct blasfeo_dmat *sD, int di, int dj, struct blasfeo_dvec *sx, int xi); -// void test_blasfeo_ddiaad(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dmat *sA, int ai, int aj); -// void test_ddiaad_libsp(int kmax, int *idx, double alpha, double *x, double *pD, int sdd); -// void test_blasfeo_ddiaad_sp(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, int *idx, struct blasfeo_dmat *sD, int di, int dj); -// void test_ddiaadin_libsp(int kmax, int *idx, double alpha, double *x, double *y, double *pD, int sdd); -// void test_blasfeo_ddiaadin_sp(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi, int *idx, struct blasfeo_dmat *sD, int di, int dj); -// void test_drowin_lib(int kmax, double alpha, double *x, double *pD); -// void test_blasfeo_drowin(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dmat *sA, int ai, int aj); -// void test_drowex_lib(int kmax, double alpha, double *pD, double *x); -// void test_blasfeo_drowex(int kmax, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi); -// void test_drowad_lib(int kmax, double alpha, double *x, double *pD); -// void test_blasfeo_drowad(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dmat *sA, int ai, int aj); -// void test_drowin_libsp(int kmax, double alpha, int *idx, double *x, double *pD); -// void test_drowad_libsp(int kmax, int *idx, double alpha, double *x, double *pD); -// void test_blasfeo_drowad_sp(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, int *idx, struct blasfeo_dmat *sD, int di, int dj); -// void test_drowadin_libsp(int kmax, int *idx, double alpha, double *x, double *y, double *pD); -// void test_drowsw_lib(int kmax, double *pA, double *pC); -// void test_blasfeo_drowsw(int kmax, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sC, int ci, int cj); -// void test_blasfeo_drowpe(int kmax, int *ipiv, struct blasfeo_dmat *sA); -// void test_blasfeo_dcolex(int kmax, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi); -// void test_dcolin_lib(int kmax, double *x, int offset, double *pD, int sdd); -// void test_blasfeo_dcolin(int kmax, struct blasfeo_dvec *sx, int xi, struct blasfeo_dmat *sA, int ai, int aj); -// void test_dcolad_lib(int kmax, double alpha, double *x, int offset, double *pD, int sdd); -// void test_dcolin_libsp(int kmax, int *idx, double *x, double *pD, int sdd); -// void test_dcolad_libsp(int kmax, double alpha, int *idx, double *x, double *pD, int sdd); -// void test_dcolsw_lib(int kmax, int offsetA, double *pA, int sda, int offsetC, double *pC, int sdc); -// void test_blasfeo_dcolsw(int kmax, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sC, int ci, int cj); -// void test_blasfeo_dcolpe(int kmax, int *ipiv, struct blasfeo_dmat *sA); -// void test_dvecin_libsp(int kmax, int *idx, double *x, double *y); -// void test_dvecad_libsp(int kmax, int *idx, double alpha, double *x, double *y); -// void test_blasfeo_dvecad_sp(int m, double alpha, struct blasfeo_dvec *sx, int xi, int *idx, struct blasfeo_dvec *sz, int zi); -// void test_blasfeo_dvecin_sp(int m, double alpha, struct blasfeo_dvec *sx, int xi, int *idx, struct blasfeo_dvec *sz, int zi); -// void test_blasfeo_dvecex_sp(int m, double alpha, int *idx, struct blasfeo_dvec *sx, int x, struct blasfeo_dvec *sz, int zi); -// void test_blasfeo_dveccl(int m, struct blasfeo_dvec *sxm, int xim, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sxp, int xip, struct blasfeo_dvec *sz, int zi); -// void test_blasfeo_dveccl_mask(int m, struct blasfeo_dvec *sxm, int xim, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sxp, int xip, struct blasfeo_dvec *sz, int zi, struct blasfeo_dvec *sm, int mi); -// void test_blasfeo_dvecze(int m, struct blasfeo_dvec *sm, int mi, struct blasfeo_dvec *sv, int vi, struct blasfeo_dvec *se, int ei); -// void test_blasfeo_dvecnrm_inf(int m, struct blasfeo_dvec *sx, int xi, double *ptr_norm); -// void test_blasfeo_dvecpe(int kmax, int *ipiv, struct blasfeo_dvec *sx, int xi); -// void test_blasfeo_dvecpei(int kmax, int *ipiv, struct blasfeo_dvec *sx, int xi); - -// ext_dep - -void test_blasfeo_allocate_dmat(int m, int n, struct blasfeo_dmat *sA); -void test_blasfeo_allocate_dvec(int m, struct blasfeo_dvec *sa); - -void test_blasfeo_free_dmat(struct blasfeo_dmat *sA); -void test_blasfeo_free_dvec(struct blasfeo_dvec *sa); - -void test_blasfeo_print_dmat(int m, int n, struct blasfeo_dmat *sA, int ai, int aj); -void test_blasfeo_print_dvec(int m, struct blasfeo_dvec *sa, int ai); -void test_blasfeo_print_tran_dvec(int m, struct blasfeo_dvec *sa, int ai); - -void test_blasfeo_print_to_file_dmat(FILE *file, int m, int n, struct blasfeo_dmat *sA, int ai, int aj); -void test_blasfeo_print_to_file_dvec(FILE *file, int m, struct blasfeo_dvec *sa, int ai); -void test_blasfeo_print_to_file_tran_dvec(FILE *file, int m, struct blasfeo_dvec *sa, int ai); - -void test_blasfeo_print_exp_dmat(int m, int n, struct blasfeo_dmat *sA, int ai, int aj); -void test_blasfeo_print_exp_dvec(int m, struct blasfeo_dvec *sa, int ai); -void test_blasfeo_print_exp_tran_dvec(int m, struct blasfeo_dvec *sa, int ai); - - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_D_AUX_TEST_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_d_blas.h b/third_party/acados/include/blasfeo/include/blasfeo_d_blas.h deleted file mode 100644 index ea8d006731..0000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_d_blas.h +++ /dev/null @@ -1,46 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_D_BLAS_H_ -#define BLASFEO_D_BLAS_H_ - - - -#include "blasfeo_d_blasfeo_api.h" -#include "blasfeo_d_blas_api.h" - - - -#endif // BLASFEO_D_BLAS_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_d_blas_api.h b/third_party/acados/include/blasfeo/include/blasfeo_d_blas_api.h deleted file mode 100644 index 2eab1e4094..0000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_d_blas_api.h +++ /dev/null @@ -1,281 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef BLASFEO_D_BLAS_API_H_ -#define BLASFEO_D_BLAS_API_H_ - - - -#include "blasfeo_target.h" - - - -#ifdef BLAS_API -#ifdef CBLAS_API -#ifndef BLASFEO_CBLAS_ENUM -#define BLASFEO_CBLAS_ENUM -#ifdef FORTRAN_BLAS_API -#ifndef CBLAS_H -enum CBLAS_LAYOUT {CblasRowMajor=101, CblasColMajor=102}; -enum CBLAS_TRANSPOSE {CblasNoTrans=111, CblasTrans=112, CblasConjTrans=113}; -enum CBLAS_UPLO {CblasUpper=121, CblasLower=122}; -enum CBLAS_DIAG {CblasNonUnit=131, CblasUnit=132}; -enum CBLAS_SIDE {CblasLeft=141, CblasRight=142}; -#define CBLAS_ORDER CBLAS_LAYOUT /* this for backward compatibility with CBLAS_ORDER */ -#endif // CBLAS_H -#else // FORTRAN_BLAS_API -enum BLASFEO_CBLAS_LAYOUT {BlasfeoCblasRowMajor=101, BlasfeoCblasColMajor=102}; -enum BLASFEO_CBLAS_TRANSPOSE {BlasfeoCblasNoTrans=111, BlasfeoCblasTrans=112, BlasfeoCblasConjTrans=113}; -enum BLASFEO_CBLAS_UPLO {BlasfeoCblasUpper=121, BlasfeoCblasLower=122}; -enum BLASFEO_CBLAS_DIAG {BlasfeoCblasNonUnit=131, BlasfeoCblasUnit=132}; -enum BLASFEO_CBLAS_SIDE {BlasfeoCblasLeft=141, BlasfeoCblasRight=142}; -#define BLASFEO_CBLAS_ORDER BLASFEO_CBLAS_LAYOUT /* this for backward compatibility with BLASFEO_CBLAS_ORDER */ -#endif // FORTRAN_BLAS_API -#endif // BLASFEO_CBLAS_ENUM -#endif // CBLAS_API -#endif // BLAS_API - - -#ifdef __cplusplus -extern "C" { -#endif - - - -#ifdef BLAS_API - - - -#ifdef FORTRAN_BLAS_API - - - -// BLAS 1 -// -void daxpy_(int *n, double *alpha, double *x, int *incx, double *y, int *incy); -// -void dcopy_(int *n, double *x, int *incx, double *y, int *incy); -// -double ddot_(int *n, double *x, int *incx, double *y, int *incy); - -// BLAS 2 -// -void dgemv_(char *tran, int *m, int *n, double *alpha, double *A, int *lda, double *x, int *incx, double *beta, double *y, int *incy); -// -void dsymv_(char *uplo, int *n, double *alpha, double *A, int *lda, double *x, int *incx, double *beta, double *y, int *incy); -// -void dger_(int *m, int *n, double *alpha, double *x, int *incx, double *y, int *incy, double *A, int *lda); - -// BLAS 3 -// -void dgemm_(char *ta, char *tb, int *m, int *n, int *k, double *alpha, double *A, int *lda, double *B, int *ldb, double *beta, double *C, int *ldc); -// -void dsyrk_(char *uplo, char *ta, int *m, int *k, double *alpha, double *A, int *lda, double *beta, double *C, int *ldc); -// -void dtrmm_(char *side, char *uplo, char *transa, char *diag, int *m, int *n, double *alpha, double *A, int *lda, double *B, int *ldb); -// -void dtrsm_(char *side, char *uplo, char *transa, char *diag, int *m, int *n, double *alpha, double *A, int *lda, double *B, int *ldb); -// -void dsyr2k_(char *uplo, char *ta, int *m, int *k, double *alpha, double *A, int *lda, double *B, int *ldb, double *beta, double *C, int *ldc); - - - -// LAPACK -// -void dgesv_(int *m, int *n, double *A, int *lda, int *ipiv, double *B, int *ldb, int *info); -// -void dgetrf_(int *m, int *n, double *A, int *lda, int *ipiv, int *info); -// -void dgetrf_np_(int *m, int *n, double *A, int *lda, int *info); -// -void dgetrs_(char *trans, int *m, int *n, double *A, int *lda, int *ipiv, double *B, int *ldb, int *info); -// -void dlaswp_(int *n, double *A, int *lda, int *k1, int *k2, int *ipiv, int *incx); -// -void dposv_(char *uplo, int *m, int *n, double *A, int *lda, double *B, int *ldb, int *info); -// -void dpotrf_(char *uplo, int *m, double *A, int *lda, int *info); -// -void dpotrs_(char *uplo, int *m, int *n, double *A, int *lda, double *B, int *ldb, int *info); -// -void dtrtrs_(char *uplo, char *trans, char *diag, int *m, int *n, double *A, int *lda, double *B, int *ldb, int *info); - - - -// aux -void dgetr_(int *m, int *n, double *A, int *lda, double *B, int *ldb); - - - -#ifdef CBLAS_API - - - -// CBLAS 1 -// -void cblas_daxpy(const int N, const double alpha, const double *X, const int incX, double *Y, const int incY); -// -void cblas_dswap(const int N, double *X, const int incX, double *Y, const int incY); -// -void cblas_dcopy(const int N, const double *X, const int incX, double *Y, const int incY); - -// CBLAS 2 -// -void cblas_dgemv(const enum CBLAS_LAYOUT layout, const enum CBLAS_TRANSPOSE TransA, const int M, const int N, const int K, const double alpha, const double *A, const int lda, const double *X, const int incX, const double beta, double *Y, const int incY); - -// CBLAS 3 -// -void cblas_dgemm(const enum CBLAS_LAYOUT layout, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, const int M, const int N, const int K, const double alpha, const double *A, const int lda, const double *B, const int ldb, const double beta, double *C, const int ldc); -// -void cblas_dsyrk(const enum CBLAS_LAYOUT layout, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE Trans, const int N, const int K, const double alpha, const double *A, const int lda, const double beta, double *C, const int ldc); -// -void cblas_dtrmm(const enum CBLAS_LAYOUT layout, const enum CBLAS_SIDE Side, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int M, const int N, const double alpha, const double *A, const int lda, double *B, const int ldb); -// -void cblas_dtrsm(const enum CBLAS_LAYOUT layout, const enum CBLAS_SIDE Side, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int M, const int N, const double alpha, const double *A, const int lda, double *B, const int ldb); - - - -#endif // CBLAS_API - - - -#else // BLASFEO_API - - - -// BLAS 1 -// -void blasfeo_blas_daxpy(int *n, double *alpha, double *x, int *incx, double *y, int *incy); -// -double blasfeo_blas_ddot(int *n, double *x, int *incx, double *y, int *incy); -// -void blasfeo_blas_dcopy(int *n, double *x, int *incx, double *y, int *incy); - -// BLAS 2 -// -void blasfeo_blas_dgemv(char *trans, int *m, int *n, double *alpha, double *A, int *lda, double *x, int *incx, double *beta, double *y, int *incy); -// -void blasfeo_blas_dsymv(char *uplo, int *n, double *alpha, double *A, int *lda, double *x, int *incx, double *beta, double *y, int *incy); -// -void blasfeo_blas_dger(int *m, int *n, double *alpha, double *x, int *incx, double *y, int *incy, double *A, int *lda); - -// BLAS 3 -// -void blasfeo_blas_dgemm(char *ta, char *tb, int *m, int *n, int *k, double *alpha, double *A, int *lda, double *B, int *ldb, double *beta, double *C, int *ldc); -// -void blasfeo_blas_dsyrk(char *uplo, char *ta, int *m, int *k, double *alpha, double *A, int *lda, double *beta, double *C, int *ldc); -// -void blasfeo_blas_dtrmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, double *alpha, double *A, int *lda, double *B, int *ldb); -// -void blasfeo_blas_dtrsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, double *alpha, double *A, int *lda, double *B, int *ldb); -// -void blasfeo_blas_dsyr2k(char *uplo, char *ta, int *m, int *k, double *alpha, double *A, int *lda, double *B, int *ldb, double *beta, double *C, int *ldc); - - - -// LAPACK -// -void blasfeo_lapack_dgesv(int *m, int *n, double *A, int *lda, int *ipiv, double *B, int *ldb, int *info); -// -void blasfeo_lapack_dgetrf(int *m, int *n, double *A, int *lda, int *ipiv, int *info); -// -void blasfeo_lapack_dgetrf_np(int *m, int *n, double *A, int *lda, int *info); -// -void blasfeo_lapack_dgetrs(char *trans, int *m, int *n, double *A, int *lda, int *ipiv, double *B, int *ldb, int *info); -// -void blasfeo_lapack_dlaswp(int *n, double *A, int *lda, int *k1, int *k2, int *ipiv, int *incx); -// -void blasfeo_lapack_dposv(char *uplo, int *m, int *n, double *A, int *lda, double *B, int *ldb, int *info); -// -void blasfeo_lapack_dpotrf(char *uplo, int *m, double *A, int *lda, int *info); -// -void blasfeo_lapack_dpotrs(char *uplo, int *m, int *n, double *A, int *lda, double *B, int *ldb, int *info); -// -void blasfeo_lapack_dtrtrs(char *uplo, char *trans, char *diag, int *m, int *n, double *A, int *lda, double *B, int *ldb, int *info); - - - -// aux -void blasfeo_blas_dgetr(int *m, int *n, double *A, int *lda, double *B, int *ldb); - - - -#ifdef CBLAS_API - - - -// CBLAS 1 -// -void blasfeo_cblas_daxpy(const int N, const double alpha, const double *X, const int incX, double *Y, const int incY); -// -void blasfeo_cblas_dswap(const int N, double *X, const int incX, double *Y, const int incY); -// -void blasfeo_cblas_dcopy(const int N, const double *X, const int incX, double *Y, const int incY); - -// CBLAS 2 -// -void blasfeo_cblas_dgemv(const enum BLASFEO_CBLAS_LAYOUT layout, const enum BLASFEO_CBLAS_TRANSPOSE TransA, const int M, const int N, const double alpha, const double *A, const int lda, const double *X, const int incX, const double beta, double *Y, const int incY); - -// CBLAS 3 -// -void blasfeo_cblas_dgemm(const enum BLASFEO_CBLAS_LAYOUT layout, const enum BLASFEO_CBLAS_TRANSPOSE TransA, const enum BLASFEO_CBLAS_TRANSPOSE TransB, const int M, const int N, const int K, const double alpha, const double *A, const int lda, const double *B, const int ldb, const double beta, double *C, const int ldc); -// -void blasfeo_cblas_dsyrk(const enum BLASFEO_CBLAS_LAYOUT layout, const enum BLASFEO_CBLAS_UPLO Uplo, const enum BLASFEO_CBLAS_TRANSPOSE Trans, const int N, const int K, const double alpha, const double *A, const int lda, const double beta, double *C, const int ldc); -// -void blasfeo_cblas_dtrmm(const enum BLASFEO_CBLAS_LAYOUT layout, const enum BLASFEO_CBLAS_SIDE Side, const enum BLASFEO_CBLAS_UPLO Uplo, const enum BLASFEO_CBLAS_TRANSPOSE TransA, const enum BLASFEO_CBLAS_DIAG Diag, const int M, const int N, const double alpha, const double *A, const int lda, double *B, const int ldb); -// -void blasfeo_cblas_dtrsm(const enum BLASFEO_CBLAS_LAYOUT layout, const enum BLASFEO_CBLAS_SIDE Side, const enum BLASFEO_CBLAS_UPLO Uplo, const enum BLASFEO_CBLAS_TRANSPOSE TransA, const enum BLASFEO_CBLAS_DIAG Diag, const int M, const int N, const double alpha, const double *A, const int lda, double *B, const int ldb); - - - -#endif // CBLAS_API - - - -#endif // BLASFEO_API - - - -#endif // BLAS_API - - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_D_BLAS_API_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_d_blasfeo_api.h b/third_party/acados/include/blasfeo/include/blasfeo_d_blasfeo_api.h deleted file mode 100644 index 88bb3fce22..0000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_d_blasfeo_api.h +++ /dev/null @@ -1,364 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_D_BLASFEO_API_H_ -#define BLASFEO_D_BLASFEO_API_H_ - - - -#include "blasfeo_common.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -// level 1 BLAS -// - -// z = y + alpha*x -// z[zi:zi+n] = alpha*x[xi:xi+n] + y[yi:yi+n] -// NB: Different arguments semantic compare to equivalent standard BLAS routine -void blasfeo_daxpy(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); -// z = beta*y + alpha*x -void blasfeo_daxpby(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, double beta, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); -// z = x .* y -void blasfeo_dvecmul(int m, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); -// z += x .* y -void blasfeo_dvecmulacc(int m, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); -// z = x .* y, return sum(z) = x^T * y -double blasfeo_dvecmuldot(int m, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); -// return x^T * y -double blasfeo_ddot(int m, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi); -// construct givens plane rotation -void blasfeo_drotg(double a, double b, double *c, double *s); -// apply plane rotation [a b] [c -s; s; c] to the aj0 and aj1 columns of A at row index ai -void blasfeo_dcolrot(int m, struct blasfeo_dmat *sA, int ai, int aj0, int aj1, double c, double s); -// apply plane rotation [c s; -s c] [a; b] to the ai0 and ai1 rows of A at column index aj -void blasfeo_drowrot(int m, struct blasfeo_dmat *sA, int ai0, int ai1, int aj, double c, double s); - - - -// -// level 2 BLAS -// - -// dense - -// z <= beta * y + alpha * A * x -void blasfeo_dgemv_n(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, double beta, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); -// z <= beta * y + alpha * A^T * x -void blasfeo_dgemv_t(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, double beta, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); -// z <= inv( A ) * x, A (m)x(n) -void blasfeo_dtrsv_lnn_mn(int m, int n, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= inv( A^T ) * x, A (m)x(n) -void blasfeo_dtrsv_ltn_mn(int m, int n, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= inv( A ) * x, A (m)x(m) lower, not_transposed, not_unit -void blasfeo_dtrsv_lnn(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= inv( A ) * x, A (m)x(m) lower, not_transposed, unit -void blasfeo_dtrsv_lnu(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= inv( A^T ) * x, A (m)x(m) lower, transposed, not_unit -void blasfeo_dtrsv_ltn(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= inv( A^T ) * x, A (m)x(m) lower, transposed, unit -void blasfeo_dtrsv_ltu(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= inv( A^T ) * x, A (m)x(m) upper, not_transposed, not_unit -void blasfeo_dtrsv_unn(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= inv( A^T ) * x, A (m)x(m) upper, transposed, not_unit -void blasfeo_dtrsv_utn(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= A * x ; A lower triangular -void blasfeo_dtrmv_lnn(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= A * x ; A lower triangular, unit diagonal -void blasfeo_dtrmv_lnu(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= A^T * x ; A lower triangular -void blasfeo_dtrmv_ltn(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= A^T * x ; A lower triangular, unit diagonal -void blasfeo_dtrmv_ltu(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= beta * y + alpha * A * x ; A upper triangular -void blasfeo_dtrmv_unn(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= A^T * x ; A upper triangular -void blasfeo_dtrmv_utn(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z_n <= beta_n * y_n + alpha_n * A * x_n -// z_t <= beta_t * y_t + alpha_t * A^T * x_t -void blasfeo_dgemv_nt(int m, int n, double alpha_n, double alpha_t, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx_n, int xi_n, struct blasfeo_dvec *sx_t, int xi_t, double beta_n, double beta_t, struct blasfeo_dvec *sy_n, int yi_n, struct blasfeo_dvec *sy_t, int yi_t, struct blasfeo_dvec *sz_n, int zi_n, struct blasfeo_dvec *sz_t, int zi_t); -// z <= beta * y + alpha * A * x, where A is symmetric and only the lower triangular patr of A is accessed -void blasfeo_dsymv_l(int m, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, double beta, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); -void blasfeo_dsymv_l_mn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, double beta, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); -// z <= beta * y + alpha * A * x, where A is symmetric and only the upper triangular patr of A is accessed -void blasfeo_dsymv_u(int m, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, double beta, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); -// D = C + alpha * x * y^T -void blasfeo_dger(int m, int n, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); - -// diagonal - -// z <= beta * y + alpha * A * x, A diagonal -void blasfeo_dgemv_d(int m, double alpha, struct blasfeo_dvec *sA, int ai, struct blasfeo_dvec *sx, int xi, double beta, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); - - - -// -// level 3 BLAS -// - -// dense - -// D <= beta * C + alpha * A * B -void blasfeo_dgemm_nn(int m, int n, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A * B^T -void blasfeo_dgemm_nt(int m, int n, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B -void blasfeo_dgemm_tn(int m, int n, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B^T -void blasfeo_dgemm_tt(int m, int n, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A * B^T ; C, D lower triangular -void blasfeo_dsyrk_ln(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -void blasfeo_dsyrk_ln_mn(int m, int n, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -#if ( defined(LA_HIGH_PERFORMANCE) & defined(MF_COLMAJ) ) -void blasfeo_dsyrk3_ln(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -#endif -// D <= beta * C + alpha * A^T * B ; C, D lower triangular -void blasfeo_dsyrk_lt(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -#if ( defined(LA_HIGH_PERFORMANCE) & defined(MF_COLMAJ) ) -void blasfeo_dsyrk3_lt(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -#endif -// D <= beta * C + alpha * A * B^T ; C, D upper triangular -void blasfeo_dsyrk_un(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -#if ( defined(LA_HIGH_PERFORMANCE) & defined(MF_COLMAJ) ) -void blasfeo_dsyrk3_un(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -#endif -// D <= beta * C + alpha * A^T * B ; C, D upper triangular -void blasfeo_dsyrk_ut(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -#if ( defined(LA_HIGH_PERFORMANCE) & defined(MF_COLMAJ) ) -void blasfeo_dsyrk3_ut(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -#endif -// D <= alpha * A * B ; A lower triangular -void blasfeo_dtrmm_llnn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A * B ; A lower triangular -void blasfeo_dtrmm_llnu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^T * B ; A lower triangular -void blasfeo_dtrmm_lltn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^T * B ; A lower triangular -void blasfeo_dtrmm_lltu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A * B ; A upper triangular -void blasfeo_dtrmm_lunn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A * B ; A upper triangular -void blasfeo_dtrmm_lunu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^T * B ; A upper triangular -void blasfeo_dtrmm_lutn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^T * B ; A upper triangular -void blasfeo_dtrmm_lutu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A ; A lower triangular -void blasfeo_dtrmm_rlnn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A ; A lower triangular -void blasfeo_dtrmm_rlnu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^T ; A lower triangular -void blasfeo_dtrmm_rltn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^T ; A lower triangular -void blasfeo_dtrmm_rltu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A ; A upper triangular -void blasfeo_dtrmm_runn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A ; A upper triangular -void blasfeo_dtrmm_runu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^T ; A upper triangular -void blasfeo_dtrmm_rutn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^T ; A upper triangular -void blasfeo_dtrmm_rutu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^{-1} * B , with A lower triangular employint explicit inverse of diagonal -// D <= alpha * A^{-1} * B , with A lower triangular employing explicit inverse of diagonal -void blasfeo_dtrsm_llnn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^{-1} * B , with A lower triangular with unit diagonal -void blasfeo_dtrsm_llnu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^{-T} * B , with A lower triangular employing explicit inverse of diagonal -void blasfeo_dtrsm_lltn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^{-T} * B , with A lower triangular with unit diagonal -void blasfeo_dtrsm_lltu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^{-1} * B , with A upper triangular employing explicit inverse of diagonal -void blasfeo_dtrsm_lunn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^{-1} * B , with A upper triangular with unit diagonal -void blasfeo_dtrsm_lunu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^{-T} * B , with A upper triangular employing explicit inverse of diagonal -void blasfeo_dtrsm_lutn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^{-T} * B , with A upper triangular with unit diagonal -void blasfeo_dtrsm_lutu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^{-1} , with A lower triangular employing explicit inverse of diagonal -void blasfeo_dtrsm_rlnn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^{-1} , with A lower triangular with unit diagonal -void blasfeo_dtrsm_rlnu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^{-T} , with A lower triangular employing explicit inverse of diagonal -void blasfeo_dtrsm_rltn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^{-T} , with A lower triangular with unit diagonal -void blasfeo_dtrsm_rltu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^{-1} , with A upper triangular employing explicit inverse of diagonal -void blasfeo_dtrsm_runn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^{-1} , with A upper triangular with unit diagonal -void blasfeo_dtrsm_runu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^{-T} , with A upper triangular employing explicit inverse of diagonal -void blasfeo_dtrsm_rutn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^{-T} , with A upper triangular with unit diagonal -void blasfeo_dtrsm_rutu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A * B^T + alpha * B * A^T; C, D lower triangular -void blasfeo_dsyr2k_ln(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B + alpha * B^T * A; C, D lower triangular -void blasfeo_dsyr2k_lt(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A * B^T + alpha * B * A^T; C, D upper triangular -void blasfeo_dsyr2k_un(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B + alpha * B^T * A; C, D upper triangular -void blasfeo_dsyr2k_ut(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); - -// diagonal - -// D <= alpha * A * B + beta * C, with A diagonal (stored as strvec) -void dgemm_diag_left_lib(int m, int n, double alpha, double *dA, double *pB, int sdb, double beta, double *pC, int sdc, double *pD, int sdd); -void blasfeo_dgemm_dn(int m, int n, double alpha, struct blasfeo_dvec *sA, int ai, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A * B + beta * C, with B diagonal (stored as strvec) -void blasfeo_dgemm_nd(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sB, int bi, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); - - - -// -// LAPACK -// - -// D <= chol( C ) ; C, D lower triangular -void blasfeo_dpotrf_l(int m, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -void blasfeo_dpotrf_l_mn(int m, int n, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= chol( C ) ; C, D upper triangular -void blasfeo_dpotrf_u(int m, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= chol( C + A * B' ) ; C, D lower triangular -// D <= chol( C + A * B^T ) ; C, D lower triangular -void blasfeo_dsyrk_dpotrf_ln(int m, int k, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -void blasfeo_dsyrk_dpotrf_ln_mn(int m, int n, int k, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= lu( C ) ; no pivoting -void blasfeo_dgetrf_np(int m, int n, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= lu( C ) ; row pivoting -void blasfeo_dgetrf_rp(int m, int n, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj, int *ipiv); -// D <= qr( C ) -int blasfeo_dgeqrf_worksize(int m, int n); // in bytes -void blasfeo_dgeqrf(int m, int n, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj, void *work); -// D <= Q factor, where C is the output of the LQ factorization -int blasfeo_dorglq_worksize(int m, int n, int k); // in bytes -void blasfeo_dorglq(int m, int n, int k, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj, void *work); -// D <= lq( C ) -void blasfeo_dgelqf(int m, int n, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj, void *work); -int blasfeo_dgelqf_worksize(int m, int n); // in bytes -// D <= lq( C ), positive diagonal elements -void blasfeo_dgelqf_pd(int m, int n, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj, void *work); -// [L, A] <= lq( [L, A] ), positive diagonal elements, array of matrices, with -// L lower triangular, of size (m)x(m) -// A full, of size (m)x(n1) -void blasfeo_dgelqf_pd_la(int m, int n1, struct blasfeo_dmat *sL, int li, int lj, struct blasfeo_dmat *sA, int ai, int aj, void *work); -// [L, L, A] <= lq( [L, L, A] ), positive diagonal elements, array of matrices, with: -// L lower triangular, of size (m)x(m) -// A full, of size (m)x(n1) -void blasfeo_dgelqf_pd_lla(int m, int n1, struct blasfeo_dmat *sL0, int l0i, int l0j, struct blasfeo_dmat *sL1, int l1i, int l1j, struct blasfeo_dmat *sA, int ai, int aj, void *work); - - - -// -// BLAS API helper functions -// - -#if ( defined(BLAS_API) & defined(MF_PANELMAJ) ) -// BLAS 3 -void blasfeo_cm_dgemm_nn(int m, int n, int k, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, double beta, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dgemm_nt(int m, int n, int k, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, double beta, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dgemm_tn(int m, int n, int k, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, double beta, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dgemm_tt(int m, int n, int k, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, double beta, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dsyrk_ln(int m, int k, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, double beta, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dsyrk_lt(int m, int k, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, double beta, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dsyrk_un(int m, int k, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, double beta, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dsyrk_ut(int m, int k, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, double beta, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dsyrk3_ln(int m, int k, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, double beta, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dsyrk3_lt(int m, int k, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, double beta, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dsyrk3_un(int m, int k, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, double beta, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dsyrk3_ut(int m, int k, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, double beta, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrsm_llnn(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrsm_llnu(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrsm_lltn(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrsm_lltu(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrsm_lunn(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrsm_lunu(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrsm_lutn(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrsm_lutu(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrsm_rlnn(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrsm_rlnu(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrsm_rltn(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrsm_rltu(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrsm_runn(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrsm_runu(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrsm_rutn(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrsm_rutu(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrmm_llnn(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrmm_llnu(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrmm_lltn(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrmm_lltu(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrmm_lunn(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrmm_lunu(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrmm_lutn(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrmm_lutu(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrmm_rlnn(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrmm_rlnu(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrmm_rltn(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrmm_rltu(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrmm_runn(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrmm_runu(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrmm_rutn(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dtrmm_rutu(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dsyr2k_ln(int m, int k, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, double beta, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dsyr2k_lt(int m, int k, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, double beta, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dsyr2k_un(int m, int k, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, double beta, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dsyr2k_ut(int m, int k, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dmat *sB, int bi, int bj, double beta, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); -// BLAS 2 -void blasfeo_cm_dgemv_n(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dvec *sx, int xi, double beta, struct blasfeo_cm_dvec *sy, int yi, struct blasfeo_cm_dvec *sz, int zi); -void blasfeo_cm_dgemv_t(int m, int n, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dvec *sx, int xi, double beta, struct blasfeo_cm_dvec *sy, int yi, struct blasfeo_cm_dvec *sz, int zi); -void blasfeo_cm_dsymv_l(int m, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dvec *sx, int xi, double beta, struct blasfeo_cm_dvec *sy, int yi, struct blasfeo_cm_dvec *sz, int zi); -void blasfeo_cm_dsymv_u(int m, double alpha, struct blasfeo_cm_dmat *sA, int ai, int aj, struct blasfeo_cm_dvec *sx, int xi, double beta, struct blasfeo_cm_dvec *sy, int yi, struct blasfeo_cm_dvec *sz, int zi); -void blasfeo_cm_dger(int m, int n, double alpha, struct blasfeo_cm_dvec *sx, int xi, struct blasfeo_cm_dvec *sy, int yi, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); -// LAPACK -void blasfeo_cm_dpotrf_l(int m, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dpotrf_u(int m, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj); -void blasfeo_cm_dgetrf_rp(int m, int n, struct blasfeo_cm_dmat *sC, int ci, int cj, struct blasfeo_cm_dmat *sD, int di, int dj, int *ipiv); -#endif - - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_D_BLASFEO_API_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_d_blasfeo_api_ref.h b/third_party/acados/include/blasfeo/include/blasfeo_d_blasfeo_api_ref.h deleted file mode 100644 index 141a1f0f06..0000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_d_blasfeo_api_ref.h +++ /dev/null @@ -1,147 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_D_BLASFEO_API_REF_H_ -#define BLASFEO_D_BLASFEO_API_REF_H_ - -#include "blasfeo_common.h" - - -#ifdef __cplusplus -extern "C" { -#endif - - -// expose reference BLASFEO for testing - -// --- level 1 - -void blasfeo_daxpy_ref(int kmax, double alpha, struct blasfeo_dvec_ref *sx, int xi, struct blasfeo_dvec_ref *sy, int yi, struct blasfeo_dvec_ref *sz, int zi); -void blasfeo_daxpby_ref(int kmax, double alpha, struct blasfeo_dvec_ref *sx, int xi, double beta, struct blasfeo_dvec_ref *sy, int yi, struct blasfeo_dvec_ref *sz, int zi); -void blasfeo_dvecmul_ref(int m, struct blasfeo_dvec_ref *sx, int xi, struct blasfeo_dvec_ref *sy, int yi, struct blasfeo_dvec_ref *sz, int zi); -void blasfeo_dvecmulacc_ref(int m, struct blasfeo_dvec_ref *sx, int xi, struct blasfeo_dvec_ref *sy, int yi, struct blasfeo_dvec_ref *sz, int zi); -double blasfeo_dvecmuldot_ref(int m, struct blasfeo_dvec_ref *sx, int xi, struct blasfeo_dvec_ref *sy, int yi, struct blasfeo_dvec_ref *sz, int zi); -double blasfeo_ddot_ref(int m, struct blasfeo_dvec_ref *sx, int xi, struct blasfeo_dvec_ref *sy, int yi); -void blasfeo_drotg_ref(double a, double b, double *c, double *s); -void blasfeo_dcolrot_ref(int m, struct blasfeo_dmat_ref *sA, int ai, int aj0, int aj1, double c, double s); -void blasfeo_drowrot_ref(int m, struct blasfeo_dmat_ref *sA, int ai0, int ai1, int aj, double c, double s); - - -// --- level 2 - -// dense -void blasfeo_dgemv_n_ref(int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dvec_ref *sx, int xi, double beta, struct blasfeo_dvec_ref *sy, int yi, struct blasfeo_dvec_ref *sz, int zi); -void blasfeo_dgemv_t_ref(int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dvec_ref *sx, int xi, double beta, struct blasfeo_dvec_ref *sy, int yi, struct blasfeo_dvec_ref *sz, int zi); -void blasfeo_dtrsv_lnn_mn_ref(int m, int n, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dvec_ref *sx, int xi, struct blasfeo_dvec_ref *sz, int zi); -void blasfeo_dtrsv_ltn_mn_ref(int m, int n, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dvec_ref *sx, int xi, struct blasfeo_dvec_ref *sz, int zi); -void blasfeo_dtrsv_lnn_ref(int m, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dvec_ref *sx, int xi, struct blasfeo_dvec_ref *sz, int zi); -void blasfeo_dtrsv_lnu_ref(int m, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dvec_ref *sx, int xi, struct blasfeo_dvec_ref *sz, int zi); -void blasfeo_dtrsv_ltn_ref(int m, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dvec_ref *sx, int xi, struct blasfeo_dvec_ref *sz, int zi); -void blasfeo_dtrsv_ltu_ref(int m, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dvec_ref *sx, int xi, struct blasfeo_dvec_ref *sz, int zi); -void blasfeo_dtrsv_unn_ref(int m, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dvec_ref *sx, int xi, struct blasfeo_dvec_ref *sz, int zi); -void blasfeo_dtrsv_utn_ref(int m, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dvec_ref *sx, int xi, struct blasfeo_dvec_ref *sz, int zi); -void blasfeo_dtrmv_unn_ref(int m, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dvec_ref *sx, int xi, struct blasfeo_dvec_ref *sz, int zi); -void blasfeo_dtrmv_utn_ref(int m, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dvec_ref *sx, int xi, struct blasfeo_dvec_ref *sz, int zi); -void blasfeo_dtrmv_lnn_ref(int m, int n, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dvec_ref *sx, int xi, struct blasfeo_dvec_ref *sz, int zi); -void blasfeo_dtrmv_ltn_ref(int m, int n, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dvec_ref *sx, int xi, struct blasfeo_dvec_ref *sz, int zi); -void blasfeo_dtrmv_lnu_ref(int m, int n, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dvec_ref *sx, int xi, struct blasfeo_dvec_ref *sz, int zi); -void blasfeo_dtrmv_ltu_ref(int m, int n, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dvec_ref *sx, int xi, struct blasfeo_dvec_ref *sz, int zi); -void blasfeo_dgemv_nt_ref(int m, int n, double alpha_n, double alpha_t, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dvec_ref *sx_n, int xi_n, struct blasfeo_dvec_ref *sx_t, int xi_t, double beta_n, double beta_t, struct blasfeo_dvec_ref *sy_n, int yi_n, struct blasfeo_dvec_ref *sy_t, int yi_t, struct blasfeo_dvec_ref *sz_n, int zi_n, struct blasfeo_dvec_ref *sz_t, int zi_t); -void blasfeo_dsymv_l_ref(int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dvec_ref *sx, int xi, double beta, struct blasfeo_dvec_ref *sy, int yi, struct blasfeo_dvec_ref *sz, int zi); - -// diagonal -void blasfeo_dgemv_d_ref(int m, double alpha, struct blasfeo_dvec_ref *sA, int ai, struct blasfeo_dvec_ref *sx, int xi, double beta, struct blasfeo_dvec_ref *sy, int yi, struct blasfeo_dvec_ref *sz, int zi); - - -// --- level 3 - -// dense -void blasfeo_dgemm_nn_ref( int m, int n, int k, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, double beta, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dgemm_nt_ref( int m, int n, int k, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, double beta, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dgemm_tn_ref(int m, int n, int k, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, double beta, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dgemm_tt_ref(int m, int n, int k, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, double beta, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj); - -void blasfeo_dsyrk_ln_mn_ref( int m, int n, int k, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, double beta, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dsyrk_ln_ref( int m, int k, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, double beta, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dsyrk_lt_ref( int m, int k, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, double beta, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dsyrk_un_ref( int m, int k, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, double beta, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dsyrk_ut_ref( int m, int k, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, double beta, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj); - -void blasfeo_dtrmm_rutn_ref( int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dtrmm_rlnn_ref( int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, struct blasfeo_dmat_ref *sD, int di, int dj); - -void blasfeo_dtrsm_lunu_ref( int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dtrsm_lunn_ref( int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dtrsm_lutu_ref( int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dtrsm_lutn_ref( int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dtrsm_llnu_ref( int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dtrsm_llnn_ref( int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dtrsm_lltu_ref( int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dtrsm_lltn_ref( int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dtrsm_runu_ref( int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dtrsm_runn_ref( int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dtrsm_rutu_ref( int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dtrsm_rutn_ref( int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dtrsm_rlnu_ref( int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dtrsm_rlnn_ref( int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dtrsm_rltu_ref( int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dtrsm_rltn_ref( int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, struct blasfeo_dmat_ref *sD, int di, int dj); - -// diagonal -void dgemm_diag_left_lib_ref(int m, int n, double alpha, double *dA, double *pB, int sdb, double beta, double *pC, int sdc, double *pD, int sdd); -void blasfeo_dgemm_dn_ref(int m, int n, double alpha, struct blasfeo_dvec_ref *sA, int ai, struct blasfeo_dmat_ref *sB, int bi, int bj, double beta, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dgemm_nd_ref(int m, int n, double alpha, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dvec_ref *sB, int bi, double beta, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj); - -// --- lapack - -void blasfeo_dgetrf_nopivot_ref(int m, int n, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dgetrf_rowpivot_ref(int m, int n, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj, int *ipiv); -void blasfeo_dpotrf_l_ref(int m, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dpotrf_l_mn_ref(int m, int n, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dsyrk_dpotrf_ln_ref(int m, int k, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dsyrk_dpotrf_ln_mn_ref(int m, int n, int k, struct blasfeo_dmat_ref *sA, int ai, int aj, struct blasfeo_dmat_ref *sB, int bi, int bj, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dgetrf_nopivot_ref(int m, int n, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj); -void blasfeo_dgetrf_rowpivot_ref(int m, int n, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj, int *ipiv); -void blasfeo_dgeqrf_ref(int m, int n, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj, void *work); -void blasfeo_dgelqf_ref(int m, int n, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj, void *work); -void blasfeo_dgelqf_pd_ref(int m, int n, struct blasfeo_dmat_ref *sC, int ci, int cj, struct blasfeo_dmat_ref *sD, int di, int dj, void *work); -void blasfeo_dgelqf_pd_la_ref(int m, int n1, struct blasfeo_dmat_ref *sL, int li, int lj, struct blasfeo_dmat_ref *sA, int ai, int aj, void *work); -void blasfeo_dgelqf_pd_lla_ref(int m, int n1, struct blasfeo_dmat_ref *sL0, int l0i, int l0j, struct blasfeo_dmat_ref *sL1, int l1i, int l1j, struct blasfeo_dmat_ref *sA, int ai, int aj, void *work); - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_D_BLASFEO_API_REF_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_d_blasfeo_hp_api.h b/third_party/acados/include/blasfeo/include/blasfeo_d_blasfeo_hp_api.h deleted file mode 100644 index 405733f13e..0000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_d_blasfeo_hp_api.h +++ /dev/null @@ -1,84 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_D_BLASFEO_HP_API_H_ -#define BLASFEO_D_BLASFEO_HP_API_H_ - - - -#include "blasfeo_common.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -// level 3 BLAS -// - -// dense - - -// D <= beta * C + alpha * A^T * B -void blasfeo_hp_dgemm_tn(int m, int n, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A * B^T; C, D lower triangular -void blasfeo_hp_dsyrk_ln(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A * A^T ; C, D lower triangular -void blasfeo_hp_dsyrk3_ln(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^{-T} , with A lower triangular -void blasfeo_hp_dtrsm_rltn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); - - -// -// level 2 BLAS -// - -// dense - -// z <= beta * y + alpha * A * x -void blasfeo_hp_dgemv_n(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, double beta, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); - - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_D_BLASFEO_HP_API_H_ - diff --git a/third_party/acados/include/blasfeo/include/blasfeo_d_blasfeo_ref_api.h b/third_party/acados/include/blasfeo/include/blasfeo_d_blasfeo_ref_api.h deleted file mode 100644 index 1a8b22c67e..0000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_d_blasfeo_ref_api.h +++ /dev/null @@ -1,283 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_D_BLASFEO_REF_API_H_ -#define BLASFEO_D_BLASFEO_REF_API_H_ - - - -#include "blasfeo_common.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -// level 1 BLAS -// - -// z = y + alpha*x -// z[zi:zi+n] = alpha*x[xi:xi+n] + y[yi:yi+n] -// NB: Different arguments semantic compare to equivalent standard BLAS routine -void blasfeo_ref_daxpy(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); -// z = beta*y + alpha*x -void blasfeo_ref_daxpby(int kmax, double alpha, struct blasfeo_dvec *sx, int xi, double beta, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); -// z = x .* y -void blasfeo_ref_dvecmul(int m, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); -// z += x .* y -void blasfeo_ref_dvecmulacc(int m, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); -// z = x .* y, return sum(z) = x^T * y -double blasfeo_ref_dvecmuldot(int m, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); -// return x^T * y -double blasfeo_ref_ddot(int m, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi); -// construct givens plane rotation -void blasfeo_ref_drotg(double a, double b, double *c, double *s); -// apply plane rotation [a b] [c -s; s; c] to the aj0 and aj1 columns of A at row index ai -void blasfeo_ref_dcolrot(int m, struct blasfeo_dmat *sA, int ai, int aj0, int aj1, double c, double s); -// apply plane rotation [c s; -s c] [a; b] to the ai0 and ai1 rows of A at column index aj -void blasfeo_ref_drowrot(int m, struct blasfeo_dmat *sA, int ai0, int ai1, int aj, double c, double s); - - - -// -// level 2 BLAS -// - -// dense - -// z <= beta * y + alpha * A * x -void blasfeo_ref_dgemv_n(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, double beta, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); -// z <= beta * y + alpha * A' * x -void blasfeo_ref_dgemv_t(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, double beta, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); -// z <= inv( A ) * x, A (m)x(n) -void blasfeo_ref_dtrsv_lnn_mn(int m, int n, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= inv( A' ) * x, A (m)x(n) -void blasfeo_ref_dtrsv_ltn_mn(int m, int n, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= inv( A ) * x, A (m)x(m) lower, not_transposed, not_unit -void blasfeo_ref_dtrsv_lnn(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= inv( A ) * x, A (m)x(m) lower, not_transposed, unit -void blasfeo_ref_dtrsv_lnu(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= inv( A' ) * x, A (m)x(m) lower, transposed, not_unit -void blasfeo_ref_dtrsv_ltn(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= inv( A' ) * x, A (m)x(m) lower, transposed, unit -void blasfeo_ref_dtrsv_ltu(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= inv( A' ) * x, A (m)x(m) upper, not_transposed, not_unit -void blasfeo_ref_dtrsv_unn(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= inv( A' ) * x, A (m)x(m) upper, transposed, not_unit -void blasfeo_ref_dtrsv_utn(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= A * x ; A lower triangular -void blasfeo_ref_dtrmv_lnn(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= A * x ; A lower triangular, unit diagonal -void blasfeo_ref_dtrmv_lnu(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= A' * x ; A lower triangular -void blasfeo_ref_dtrmv_ltn(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= A' * x ; A lower triangular, unit diagonal -void blasfeo_ref_dtrmv_ltu(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= beta * y + alpha * A * x ; A upper triangular -void blasfeo_ref_dtrmv_unn(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z <= A' * x ; A upper triangular -void blasfeo_ref_dtrmv_utn(int m, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sz, int zi); -// z_n <= beta_n * y_n + alpha_n * A * x_n -// z_t <= beta_t * y_t + alpha_t * A' * x_t -void blasfeo_ref_dgemv_nt(int m, int n, double alpha_n, double alpha_t, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx_n, int xi_n, struct blasfeo_dvec *sx_t, int xi_t, double beta_n, double beta_t, struct blasfeo_dvec *sy_n, int yi_n, struct blasfeo_dvec *sy_t, int yi_t, struct blasfeo_dvec *sz_n, int zi_n, struct blasfeo_dvec *sz_t, int zi_t); -// z <= beta * y + alpha * A * x, where A is symmetric and only the lower triangular patr of A is accessed -void blasfeo_ref_dsymv_l(int m, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, double beta, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); -void blasfeo_ref_dsymv_l_mn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, double beta, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); -// z <= beta * y + alpha * A * x, where A is symmetric and only the upper triangular patr of A is accessed -void blasfeo_ref_dsymv_u(int m, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sx, int xi, double beta, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); -// D = C + alpha * x * y^T -void blasfeo_ref_dger(int m, int n, double alpha, struct blasfeo_dvec *sx, int xi, struct blasfeo_dvec *sy, int yi, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); - -// diagonal - -// z <= beta * y + alpha * A * x, A diagonal -void blasfeo_ref_dgemv_d(int m, double alpha, struct blasfeo_dvec *sA, int ai, struct blasfeo_dvec *sx, int xi, double beta, struct blasfeo_dvec *sy, int yi, struct blasfeo_dvec *sz, int zi); - - - -// -// level 3 BLAS -// - -// dense - -// D <= beta * C + alpha * A * B -void blasfeo_ref_dgemm_nn(int m, int n, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A * B^T -void blasfeo_ref_dgemm_nt(int m, int n, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B -void blasfeo_ref_dgemm_tn(int m, int n, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B^T -void blasfeo_ref_dgemm_tt(int m, int n, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A * B^T ; C, D lower triangular -void blasfeo_ref_dsyrk_ln(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -void blasfeo_ref_dsyrk_ln_mn(int m, int n, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B ; C, D lower triangular -void blasfeo_ref_dsyrk_lt(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A * B^T ; C, D upper triangular -void blasfeo_ref_dsyrk_un(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B ; C, D upper triangular -void blasfeo_ref_dsyrk_ut(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A * B ; A lower triangular -void blasfeo_ref_dtrmm_llnn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A * B ; A lower triangular -void blasfeo_ref_dtrmm_llnu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^T * B ; A lower triangular -void blasfeo_ref_dtrmm_lltn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^T * B ; A lower triangular -void blasfeo_ref_dtrmm_lltu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A * B ; A upper triangular -void blasfeo_ref_dtrmm_lunn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A * B ; A upper triangular -void blasfeo_ref_dtrmm_lunu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^T * B ; A upper triangular -void blasfeo_ref_dtrmm_lutn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^T * B ; A upper triangular -void blasfeo_ref_dtrmm_lutu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A ; A lower triangular -void blasfeo_ref_dtrmm_rlnn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A ; A lower triangular -void blasfeo_ref_dtrmm_rlnu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^T ; A lower triangular -void blasfeo_ref_dtrmm_rltn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^T ; A lower triangular -void blasfeo_ref_dtrmm_rltu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A ; A upper triangular -void blasfeo_ref_dtrmm_runn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A ; A upper triangular -void blasfeo_ref_dtrmm_runu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^T ; A upper triangular -void blasfeo_ref_dtrmm_rutn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^T ; A upper triangular -void blasfeo_ref_dtrmm_rutu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^{-1} * B , with A lower triangular employint explicit inverse of diagonal -void blasfeo_ref_dtrsm_llnn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^{-1} * B , with A lower triangular with unit diagonal -void blasfeo_ref_dtrsm_llnu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^{-T} * B , with A lower triangular employint explicit inverse of diagonal -void blasfeo_ref_dtrsm_lltn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^{-T} * B , with A lower triangular with unit diagonal -void blasfeo_ref_dtrsm_lltu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^{-1} * B , with A upper triangular employing explicit inverse of diagonal -void blasfeo_ref_dtrsm_lunn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^{-1} * B , with A upper triangular withunit diagonal -void blasfeo_ref_dtrsm_lunu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^{-T} * B , with A upper triangular employing explicit inverse of diagonal -void blasfeo_ref_dtrsm_lutn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A^{-T} * B , with A upper triangular withunit diagonal -void blasfeo_ref_dtrsm_lutu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^{-1} , with A lower triangular employing explicit inverse of diagonal -void blasfeo_ref_dtrsm_rlnn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^{-1} , with A lower triangular with unit diagonal -void blasfeo_ref_dtrsm_rlnu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^{-T} , with A lower triangular employing explicit inverse of diagonal -void blasfeo_ref_dtrsm_rltn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^{-T} , with A lower triangular with unit diagonal -void blasfeo_ref_dtrsm_rltu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^{-1} , with A upper triangular employing explicit inverse of diagonal -void blasfeo_ref_dtrsm_runn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^{-1} , with A upper triangular with unit diagonal -void blasfeo_ref_dtrsm_runu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^{-T} , with A upper triangular employing explicit inverse of diagonal -void blasfeo_ref_dtrsm_rutn(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * B * A^{-T} , with A upper triangular with unit diagonal -void blasfeo_ref_dtrsm_rutu(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A * B^T + alpha * B * A^T ; C, D lower triangular -void blasfeo_ref_dsyr2k_ln(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B + alpha * B^T * A ; C, D lower triangular -void blasfeo_ref_dsyr2k_lt(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A * B^T + alpha * B * A^T ; C, D upper triangular -void blasfeo_ref_dsyr2k_un(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B + alpha * B^T * A ; C, D upper triangular -void blasfeo_ref_dsyr2k_ut(int m, int k, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); - -// diagonal - -// D <= alpha * A * B + beta * C, with A diagonal (stored as strvec) -void dgemm_diag_left_lib(int m, int n, double alpha, double *dA, double *pB, int sdb, double beta, double *pC, int sdc, double *pD, int sdd); -void blasfeo_ref_dgemm_dn(int m, int n, double alpha, struct blasfeo_dvec *sA, int ai, struct blasfeo_dmat *sB, int bi, int bj, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= alpha * A * B + beta * C, with B diagonal (stored as strvec) -void blasfeo_ref_dgemm_nd(int m, int n, double alpha, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dvec *sB, int bi, double beta, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); - - - -// -// LAPACK -// - -// D <= chol( C ) ; C, D lower triangular -void blasfeo_ref_dpotrf_l(int m, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -void blasfeo_ref_dpotrf_l_mn(int m, int n, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= chol( C ) ; C, D upper triangular -void blasfeo_ref_dpotrf_u(int m, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= chol( C + A * B' ) ; C, D lower triangular -void blasfeo_ref_dsyrk_dpotrf_ln(int m, int k, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -void blasfeo_ref_dsyrk_dpotrf_ln_mn(int m, int n, int k, struct blasfeo_dmat *sA, int ai, int aj, struct blasfeo_dmat *sB, int bi, int bj, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= lu( C ) ; no pivoting -void blasfeo_ref_dgetrf_np(int m, int n, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj); -// D <= lu( C ) ; row pivoting -void blasfeo_ref_dgetrf_rp(int m, int n, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj, int *ipiv); -// D <= qr( C ) -int blasfeo_ref_dgeqrf_worksize(int m, int n); // in bytes -void blasfeo_ref_dgeqrf(int m, int n, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj, void *work); -// D <= Q factor, where C is the output of the LQ factorization -int blasfeo_ref_dorglq_worksize(int m, int n, int k); // in bytes -void blasfeo_ref_dorglq(int m, int n, int k, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj, void *work); -// D <= lq( C ) -void blasfeo_ref_dgelqf(int m, int n, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj, void *work); -int blasfeo_ref_dgelqf_worksize(int m, int n); // in bytes -// D <= lq( C ), positive diagonal elements -void blasfeo_ref_dgelqf_pd(int m, int n, struct blasfeo_dmat *sC, int ci, int cj, struct blasfeo_dmat *sD, int di, int dj, void *work); -// [L, A] <= lq( [L, A] ), positive diagonal elements, array of matrices, with -// L lower triangular, of size (m)x(m) -// A full, of size (m)x(n1) -void blasfeo_ref_dgelqf_pd_la(int m, int n1, struct blasfeo_dmat *sL, int li, int lj, struct blasfeo_dmat *sA, int ai, int aj, void *work); -// [L, L, A] <= lq( [L, L, A] ), positive diagonal elements, array of matrices, with: -// L lower triangular, of size (m)x(m) -// A full, of size (m)x(n1) -void blasfeo_ref_dgelqf_pd_lla(int m, int n1, struct blasfeo_dmat *sL0, int l0i, int l0j, struct blasfeo_dmat *sL1, int l1i, int l1j, struct blasfeo_dmat *sA, int ai, int aj, void *work); - - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_D_BLASFEO_REF_API_H_ - diff --git a/third_party/acados/include/blasfeo/include/blasfeo_d_kernel.h b/third_party/acados/include/blasfeo/include/blasfeo_d_kernel.h deleted file mode 100644 index d20ac38bbd..0000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_d_kernel.h +++ /dev/null @@ -1,1321 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_D_KERNEL_H_ -#define BLASFEO_D_KERNEL_H_ - - - -#include "blasfeo_target.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// utils -void blasfeo_align_2MB(void *ptr, void **ptr_align); -void blasfeo_align_4096_byte(void *ptr, void **ptr_align); -void blasfeo_align_64_byte(void *ptr, void **ptr_align); - - -// -// lib8 -// - -// 24x8 -void kernel_dgemm_nt_24x8_lib8(int k, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dgemm_nt_24x8_vs_lib8(int k, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, int m1, int n1); // -void kernel_dtrsm_nt_rl_inv_24x8_lib8(int k, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E); // -void kernel_dpotrf_nt_l_24x8_lib8(int k, double *A, int sda, double *B, double *C, int sdc, double *D, int sdd, double *inv_diag_D); -void kernel_dpotrf_nt_l_24x8_vs_lib8(int k, double *A, int sda, double *B, double *C, int sdc, double *D, int sdd, double *inv_diag_D, int m1, int n1); -void kernel_dtrsm_nt_rl_inv_24x8_vs_lib8(int k, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E, int m1, int n1); // -void kernel_dgemm_dtrsm_nt_rl_inv_24x8_lib8(int kp, double *Ap, int sdap, double *Bp, int km_, double *Am, int sdam, double *Bm, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E); -void kernel_dgemm_dtrsm_nt_rl_inv_24x8_vs_lib8(int kp, double *Ap, int sdap, double *Bp, int km_, double *Am, int sdam, double *Bm, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E, int m1, int n1); -void kernel_dsyrk_dpotrf_nt_l_24x8_lib8(int kp, double *Ap, int sdap, double *Bp, int km_, double *Am, int sdam, double *Bm, double *C, int sdc, double *D, int sdd, double *inv_diag_D); -void kernel_dsyrk_dpotrf_nt_l_24x8_vs_lib8(int kp, double *Ap, int sdap, double *Bp, int km_, double *Am, int sdam, double *Bm, double *C, int sdc, double *D, int sdd, double *inv_diag_D, int m1, int n1); -void kernel_dlarfb8_rn_24_lib8(int kmax, double *pV, double *pT, double *pD, int sdd); -// 16x8 -void kernel_dgemm_nt_16x8_lib8(int k, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dgemm_nt_16x8_vs_lib8(int k, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, int m1, int n1); // -void kernel_dgemm_nt_16x8_gen_lib8(int k, double *alpha, double *A, int sda, double *B, double *beta, int offC, double *C, int sdc, int offD, double *D, int sdd, int m0, int m1, int n0, int n1); // -void kernel_dgemm_nn_16x8_lib8(int k, double *alpha, double *A, int sda, int offB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dgemm_nn_16x8_vs_lib8(int k, double *alpha, double *A, int sda, int offB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, int m1, int n1); // -void kernel_dgemm_nn_16x8_gen_lib8(int k, double *alpha, double *A, int sda, int offB, double *B, int sdb, double *beta, int offC, double *C, int sdc, int offD, double *D, int sdd, int m0, int m1, int n0, int n1); // -void kernel_dsyrk_nt_l_16x8_lib8(int k, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dsyrk_nt_l_16x8_vs_lib8(int k, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, int m1, int n1); // -void kernel_dsyrk_nt_l_16x8_gen_lib8(int k, double *alpha, double *A, int sda, double *B, double *beta, int offC, double *C, int sdc, int offD, double *D, int sdd, int m0, int m1, int n0, int n1); // -void kernel_dtrmm_nn_rl_16x8_lib8(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *D, int sdd); -void kernel_dtrmm_nn_rl_16x8_vs_lib8(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *D, int sdd, int m1, int n1); -void kernel_dtrmm_nn_rl_16x8_gen_lib8(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, int offD, double *D, int sdd, int m0, int m1, int n0, int n1); -void kernel_dtrsm_nt_rl_inv_16x8_lib8(int k, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E); // -void kernel_dtrsm_nt_rl_inv_16x8_vs_lib8(int k, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E, int m1, int n1); // -void kernel_dpotrf_nt_l_16x8_lib8(int k, double *A, int sda, double *B, double *C, int sdc, double *D, int sdd, double *inv_diag_D); -void kernel_dpotrf_nt_l_16x8_vs_lib8(int k, double *A, int sda, double *B, double *C, int sdc, double *D, int sdd, double *inv_diag_D, int m1, int n1); -void kernel_dgemm_dtrsm_nt_rl_inv_16x8_lib8(int kp, double *Ap, int sdap, double *Bp, int km_, double *Am, int sdam, double *Bm, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E); -void kernel_dgemm_dtrsm_nt_rl_inv_16x8_vs_lib8(int kp, double *Ap, int sdap, double *Bp, int km_, double *Am, int sdam, double *Bm, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E, int m1, int n1); -void kernel_dsyrk_dpotrf_nt_l_16x8_lib8(int kp, double *Ap, int sdap, double *Bp, int km_, double *Am, int sdam, double *Bm, double *C, int sdc, double *D, int sdd, double *inv_diag_D); -void kernel_dsyrk_dpotrf_nt_l_16x8_vs_lib8(int kp, double *Ap, int sdap, double *Bp, int km_, double *Am, int sdam, double *Bm, double *C, int sdc, double *D, int sdd, double *inv_diag_D, int m1, int n1); -void kernel_dlarfb8_rn_16_lib8(int kmax, double *pV, double *pT, double *pD, int sdd); -void kernel_dlarfb8_rn_la_16_lib8(int n1, double *pVA, double *pT, double *pD, int sdd, double *pA, int sda); -void kernel_dlarfb8_rn_lla_16_lib8(int n0, int n1, double *pVL, double *pVA, double *pT, double *pD, int sdd, double *pL, int sdl, double *pA, int sda); -// 8x16 -void kernel_dgemm_tt_8x16_lib8(int k, double *alpha, int offA, double *A, int sda, double *B, int sdb, double *beta, double *C, double *D); // -void kernel_dgemm_tt_8x16_vs_lib8(int k, double *alpha, int offA, double *A, int sda, double *B, int sdb, double *beta, double *C, double *D, int m1, int n1); // -void kernel_dgemm_tt_8x16_gen_lib8(int k, double *alpha, int offA, double *A, int sda, double *B, int sdb, double *beta, int offC, double *C, int sdc, int offD, double *D, int sdd, int m0, int m1, int n0, int n1); // -void kernel_dgemm_nt_8x16_lib8(int k, double *alpha, double *A, double *B, int sdb, double *beta, double *C, double *D); // -void kernel_dgemm_nt_8x16_vs_lib8(int k, double *alpha, double *A, double *B, int sdb, double *beta, double *C, double *D, int m1, int n1); // -// 8x8 -void kernel_dgemm_nt_8x8_lib8(int k, double *alpha, double *A, double *B, double *beta, double *C, double *D); // -void kernel_dgemm_nt_8x8_vs_lib8(int k, double *alpha, double *A, double *B, double *beta, double *C, double *D, int m1, int n1); // -void kernel_dgemm_nt_8x8_gen_lib8(int k, double *alpha, double *A, double *B, double *beta, int offC, double *C, int sdc, int offD, double *D, int sdd, int m0, int m1, int n0, int n1); // -void kernel_dgemm_nn_8x8_lib8(int k, double *alpha, double *A, int offB, double *B, int sdb, double *beta, double *C, double *D); // -void kernel_dgemm_nn_8x8_vs_lib8(int k, double *alpha, double *A, int offB, double *B, int sdb, double *beta, double *C, double *D, int m1, int n1); // -void kernel_dgemm_nn_8x8_gen_lib8(int k, double *alpha, double *A, int offB, double *B, int sdb, double *beta, int offC, double *C, int sdc, int offD, double *D, int sdd, int m0, int m1, int n0, int n1); // -void kernel_dgemm_tt_8x8_lib8(int k, double *alpha, int offA, double *A, int sda, double *B, double *beta, double *C, double *D); // -void kernel_dgemm_tt_8x8_vs_lib8(int k, double *alpha, int offA, double *A, int sda, double *B, double *beta, double *C, double *D, int m1, int n1); // -void kernel_dgemm_tt_8x8_gen_lib8(int k, double *alpha, int offA, double *A, int sda, double *B, double *beta, int offc, double *C, int sdc, int offD, double *D, int sdd, int m0, int m1, int n0, int n1); // -void kernel_dsyrk_nt_l_8x8_lib8(int k, double *alpha, double *A, double *B, double *beta, double *C, double *D); // -void kernel_dsyrk_nt_l_8x8_vs_lib8(int k, double *alpha, double *A, double *B, double *beta, double *C, double *D, int m1, int n1); // -void kernel_dsyrk_nt_l_8x8_gen_lib8(int k, double *alpha, double *A, double *B, double *beta, int offC, double *C, int sdc, int offD, double *D, int sdd, int m0, int m1, int n0, int n1); // -void kernel_dtrmm_nn_rl_8x8_lib8(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *D); -void kernel_dtrmm_nn_rl_8x8_vs_lib8(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *D, int m1, int n1); -void kernel_dtrmm_nn_rl_8x8_gen_lib8(int k, double *alpha, double *A, int offsetB, double *B, int sdb, int offD, double *D, int sdd, int m0, int m1, int n0, int n1); -void kernel_dtrsm_nt_rl_inv_8x8_lib8(int k, double *A, double *B, double *beta, double *C, double *D, double *E, double *inv_diag_E); -void kernel_dtrsm_nt_rl_inv_8x8_vs_lib8(int k, double *A, double *B, double *beta, double *C, double *D, double *E, double *inv_diag_E, int m1, int n1); -void kernel_dpotrf_nt_l_8x8_lib8(int k, double *A, double *B, double *C, double *D, double *inv_diag_D); -void kernel_dpotrf_nt_l_8x8_vs_lib8(int k, double *A, double *B, double *C, double *D, double *inv_diag_D, int m1, int n1); -void kernel_dgemm_dtrsm_nt_rl_inv_8x8_lib8(int kp, double *Ap, double *Bp, int km_, double *Am, double *Bm, double *C, double *D, double *E, double *inv_diag_E); -void kernel_dgemm_dtrsm_nt_rl_inv_8x8_vs_lib8(int kp, double *Ap, double *Bp, int km_, double *Am, double *Bm, double *C, double *D, double *E, double *inv_diag_E, int m1, int n1); -void kernel_dsyrk_dpotrf_nt_l_8x8_lib8(int kp, double *Ap, double *Bp, int km_, double *Am, double *Bm, double *C, double *D, double *inv_diag_D); -void kernel_dsyrk_dpotrf_nt_l_8x8_vs_lib8(int kp, double *Ap, double *Bp, int km_, double *Am, double *Bm, double *C, double *D, double *inv_diag_D, int m1, int n1); -void kernel_dgelqf_vs_lib8(int m, int n, int k, int offD, double *pD, int sdd, double *dD); -void kernel_dgelqf_pd_vs_lib8(int m, int n, int k, int offD, double *pD, int sdd, double *dD); -void kernel_dgelqf_8_lib8(int kmax, double *pD, double *dD); -void kernel_dgelqf_pd_8_lib8(int kmax, double *pD, double *dD); -void kernel_dlarft_8_lib8(int kmax, double *pD, double *dD, double *pT); -void kernel_dlarfb8_rn_8_lib8(int kmax, double *pV, double *pT, double *pD); -void kernel_dlarfb8_rn_8_vs_lib8(int kmax, double *pV, double *pT, double *pD, int m1); -void kernel_dlarfb8_rn_1_lib8(int kmax, double *pV, double *pT, double *pD); -void kernel_dgelqf_dlarft8_8_lib8(int kmax, double *pD, double *dD, double *pT); -void kernel_dgelqf_pd_dlarft8_8_lib8(int kmax, double *pD, double *dD, double *pT); -void kernel_dgelqf_pd_la_vs_lib8(int m, int n1, int k, int offD, double *pD, int sdd, double *dD, int offA, double *pA, int sda); -void kernel_dgelqf_pd_la_dlarft8_8_lib8(int kmax, double *pD, double *dD, double *pA, double *pT); -void kernel_dlarft_la_8_lib8(int n1, double *dD, double *pA, double *pT); -void kernel_dlarfb8_rn_la_8_lib8(int n1, double *pVA, double *pT, double *pD, double *pA); -void kernel_dlarfb8_rn_la_8_vs_lib8(int n1, double *pVA, double *pT, double *pD, double *pA, int m1); -void kernel_dlarfb8_rn_la_1_lib8(int n1, double *pVA, double *pT, double *pD, double *pA); -void kernel_dgelqf_pd_lla_vs_lib8(int m, int n0, int n1, int k, int offD, double *pD, int sdd, double *dD, int offL, double *pL, int sdl, int offA, double *pA, int sda); -void kernel_dgelqf_pd_lla_dlarft8_8_lib8(int n0, int n1, double *pD, double *dD, double *pL, double *pA, double *pT); -void kernel_dlarft_lla_8_lib8(int n0, int n1, double *dD, double *pL, double *pA, double *pT); -void kernel_dlarfb8_rn_lla_8_lib8(int n0, int n1, double *pVL, double *pVA, double *pT, double *pD, double *pL, double *pA); -void kernel_dlarfb8_rn_lla_8_vs_lib8(int n0, int n1, double *pVL, double *pVA, double *pT, double *pD, double *pL, double *pA, int m1); -void kernel_dlarfb8_rn_lla_1_lib8(int n0, int n1, double *pVL, double *pVA, double *pT, double *pD, double *pL, double *pA); - -// panel copy / pack -// 24 -void kernel_dpack_nn_24_lib8(int kmax, double *A, int lda, double *C, int sdc); -void kernel_dpack_nn_24_vs_lib8(int kmax, double *A, int lda, double *C, int sdc, int m1); -// 16 -void kernel_dpacp_nn_16_lib8(int kmax, int offsetA, double *A, int sda, double *B, int sdb); -void kernel_dpacp_nn_16_vs_lib8(int kmax, int offsetA, double *A, int sda, double *B, int sdb, int m1); -void kernel_dpack_nn_16_lib8(int kmax, double *A, int lda, double *C, int sdc); -void kernel_dpack_nn_16_vs_lib8(int kmax, double *A, int lda, double *C, int sdc, int m1); -// 8 -void kernel_dpacp_nn_8_lib8(int kmax, int offsetA, double *A, int sda, double *B); -void kernel_dpacp_nn_8_vs_lib8(int kmax, int offsetA, double *A, int sda, double *B, int m1); -void kernel_dpacp_tn_8_lib8(int kmax, int offsetA, double *A, int sda, double *B); -void kernel_dpacp_tn_8_vs_lib8(int kmax, int offsetA, double *A, int sda, double *B, int m1); -void kernel_dpacp_l_nn_8_lib8(int kmax, int offsetA, double *A, int sda, double *B); -void kernel_dpacp_l_nn_8_vs_lib8(int kmax, int offsetA, double *A, int sda, double *B, int m1); -void kernel_dpacp_l_tn_8_lib8(int kmax, int offsetA, double *A, int sda, double *B); -void kernel_dpacp_l_tn_8_vs_lib8(int kmax, int offsetA, double *A, int sda, double *B, int m1); -void kernel_dpaad_nn_8_lib8(int kmax, double *alpha, int offsetA, double *A, int sda, double *B); -void kernel_dpaad_nn_8_vs_lib8(int kmax, double *alpha, int offsetA, double *A, int sda, double *B, int m1); -void kernel_dpack_nn_8_lib8(int kmax, double *A, int lda, double *C); -void kernel_dpack_nn_8_vs_lib8(int kmax, double *A, int lda, double *C, int m1); -void kernel_dpack_tn_8_lib8(int kmax, double *A, int lda, double *C); -void kernel_dpack_tn_8_vs_lib8(int kmax, double *A, int lda, double *C, int m1); -// 4 -void kernel_dpack_tt_4_lib8(int kmax, double *A, int lda, double *C, int sdc); // TODO offsetC -void kernel_dpack_tt_4_vs_lib8(int kmax, double *A, int lda, double *C, int sdc, int m1); // TODO offsetC - -// level 2 BLAS -// 16 -void kernel_dgemv_n_16_lib8(int k, double *alpha, double *A, int sda, double *x, double *beta, double *y, double *z); -// 8 -void kernel_dgemv_n_8_lib8(int k, double *alpha, double *A, double *x, double *beta, double *y, double *z); -void kernel_dgemv_n_8_vs_lib8(int k, double *alpha, double *A, double *x, double *beta, double *y, double *z, int m1); -//void kernel_dgemv_n_8_gen_lib8(int k, double *alpha, double *A, double *x, double *beta, double *y, double *z, int m0, int m1); -void kernel_dgemv_n_8_gen_lib8(int k, double *alpha, int offsetA, double *A, double *x, double *beta, double *y, double *z, int m1); -void kernel_dgemv_t_8_lib8(int k, double *alpha, int offsetA, double *A, int sda, double *x, double *beta, double *y, double *z); -void kernel_dgemv_t_8_vs_lib8(int k, double *alpha, int offsetA, double *A, int sda, double *x, double *beta, double *y, double *z, int n1); -void kernel_dgemv_nt_8_lib8(int kmax, double *alpha_n, double *alpha_t, int offsetA, double *A, int sda, double *x_n, double *x_t, double *beta_t, double *y_t, double *z_n, double *z_t); -void kernel_dgemv_nt_8_vs_lib8(int kmax, double *alpha_n, double *alpha_t, int offsetA, double *A, int sda, double *x_n, double *x_t, double *beta_t, double *y_t, double *z_n, double *z_t, int n1); -void kernel_dsymv_l_8_lib8(int kmax, double *alpha, double *A, int sda, double *x, double *z); -void kernel_dsymv_l_8_vs_lib8(int kmax, double *alpha, double *A, int sda, double *x, double *z, int n1); -void kernel_dsymv_l_8_gen_lib8(int kmax, double *alpha, int offsetA, double *A, int sda, double *x, double *z, int n1); -void kernel_dtrmv_n_ln_8_lib8(int k, double *A, double *x, double *z); -void kernel_dtrmv_n_ln_8_vs_lib8(int k, double *A, double *x, double *z, int m1); -void kernel_dtrmv_n_ln_8_gen_lib8(int k, int offsetA, double *A, double *x, double *z, int m1); -void kernel_dtrmv_t_ln_8_lib8(int k, double *A, int sda, double *x, double *z); -void kernel_dtrmv_t_ln_8_vs_lib8(int k, double *A, int sda, double *x, double *z, int n1); -void kernel_dtrmv_t_ln_8_gen_lib8(int k, int offsetA, double *A, int sda, double *x, double *z, int n1); -void kernel_dtrsv_n_l_inv_8_lib8(int k, double *A, double *inv_diag_A, double *x, double *z); -void kernel_dtrsv_n_l_inv_8_vs_lib8(int k, double *A, double *inv_diag_A, double *x, double *z, int m1, int n1); -void kernel_dtrsv_t_l_inv_8_lib8(int k, double *A, int sda, double *inv_diag_A, double *x, double *z); -void kernel_dtrsv_t_l_inv_8_vs_lib8(int k, double *A, int sda, double *inv_diag_A, double *x, double *z, int m1, int n1); - - - -// -// lib4 -// - -// level 2 BLAS -// 12 -void kernel_dgemv_n_12_lib4(int k, double *alpha, double *A, int sda, double *x, double *beta, double *y, double *z); -void kernel_dgemv_t_12_lib4(int k, double *alpha, int offsetA, double *A, int sda, double *x, double *beta, double *y, double *z); -// 8 -void kernel_dgemv_n_8_lib4(int k, double *alpha, double *A, int sda, double *x, double *beta, double *y, double *z); -void kernel_dgemv_t_8_lib4(int k, double *alpha, int offsetA, double *A, int sda, double *x, double *beta, double *y, double *z); -void kernel_dtrmv_un_8_lib4(int k, double *A, int sda, double *x, double *z); -// 4 -void kernel_dgemv_n_4_lib4(int k, double *alpha, double *A, double *x, double *beta, double *y, double *z); -void kernel_dgemv_n_4_vs_lib4(int k, double *alpha, double *A, double *x, double *beta, double *y, double *z, int k1); -void kernel_dgemv_n_4_gen_lib4(int kmax, double *alpha, double *A, double *x, double *beta, double *y, double *z, int k0, int k1); -void kernel_dgemv_t_4_lib4(int k, double *alpha, int offsetA, double *A, int sda, double *x, double *beta, double *y, double *z); -void kernel_dgemv_t_4_vs_lib4(int k, double *alpha, int offsetA, double *A, int sda, double *x, double *beta, double *y, double *z, int k1); -void kernel_dtrsv_ln_inv_4_lib4(int k, double *A, double *inv_diag_A, double *x, double *y, double *z); -void kernel_dtrsv_ln_inv_4_vs_lib4(int k, double *A, double *inv_diag_A, double *x, double *y, double *z, int km, int kn); -void kernel_dtrsv_lt_inv_4_lib4(int k, double *A, int sda, double *inv_diag_A, double *x, double *y, double *z); -void kernel_dtrsv_lt_inv_3_lib4(int k, double *A, int sda, double *inv_diag_A, double *x, double *y, double *z); -void kernel_dtrsv_lt_inv_2_lib4(int k, double *A, int sda, double *inv_diag_A, double *x, double *y, double *z); -void kernel_dtrsv_lt_inv_1_lib4(int k, double *A, int sda, double *inv_diag_A, double *x, double *y, double *z); -void kernel_dtrsv_lt_one_4_lib4(int k, double *A, int sda, double *x, double *y, double *z); -void kernel_dtrsv_lt_one_3_lib4(int k, double *A, int sda, double *x, double *y, double *z); -void kernel_dtrsv_lt_one_2_lib4(int k, double *A, int sda, double *x, double *y, double *z); -void kernel_dtrsv_lt_one_1_lib4(int k, double *A, int sda, double *x, double *y, double *z); -void kernel_dtrsv_ln_one_4_vs_lib4(int kmax, double *A, double *x, double *y, double *z, int km, int kn); -void kernel_dtrsv_ln_one_4_lib4(int kmax, double *A, double *x, double *y, double *z); -void kernel_dtrsv_un_inv_4_lib4(int kmax, double *A, double *inv_diag_A, double *x, double *y, double *z); -void kernel_dtrsv_ut_inv_4_lib4(int kmax, double *A, int sda, double *inv_diag_A, double *x, double *y, double *z); -void kernel_dtrsv_ut_inv_4_vs_lib4(int kmax, double *A, int sda, double *inv_diag_A, double *x, double *y, double *z, int m1, int n1); -void kernel_dtrmv_un_4_lib4(int k, double *A, double *x, double *z); -void kernel_dtrmv_ut_4_lib4(int k, double *A, int sda, double *x, double *z); -void kernel_dtrmv_ut_4_vs_lib4(int k, double *A, int sda, double *x, double *z, int km); -void kernel_dgemv_nt_6_lib4(int kmax, double *alpha_n, double *alpha_t, double *A, int sda, double *x_n, double *x_t, double *beta_t, double *y_t, double *z_n, double *z_t); -void kernel_dgemv_nt_4_lib4(int kmax, double *alpha_n, double *alpha_t, double *A, int sda, double *x_n, double *x_t, double *beta_t, double *y_t, double *z_n, double *z_t); -void kernel_dgemv_nt_4_vs_lib4(int kmax, double *alpha_n, double *alpha_t, double *A, int sda, double *x_n, double *x_t, double *beta_t, double *y_t, double *z_n, double *z_t, int km); -void kernel_dsymv_l_4_lib4(int kmax, double *alpha, double *A, int sda, double *x, double *z); -void kernel_dsymv_l_4_gen_lib4(int kmax, double *alpha, int offA, double *A, int sda, double *x, double *z, int km); - - - -// level 3 BLAS -// 12x4 -void kernel_dgemm_nt_12x4_lib4(int k, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dgemm_nt_12x4_vs_lib4(int k, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, int km, int kn); // -void kernel_dgemm_nt_12x4_gen_lib4(int k, double *alpha, double *A, int sda, double *B, double *beta, int offsetC, double *C, int sdc, int offsetD, double *D, int sdd, int m0, int m1, int k0, int k1); -void kernel_dgemm_nn_12x4_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dgemm_nn_12x4_vs_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, int km, int kn); // -void kernel_dgemm_nn_12x4_gen_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, int offsetC, double *C, int sdc, int offsetD, double *D, int sdd, int m0, int m1, int n0, int n1); // -void kernel_dgemm_tt_12x4_lib4(int k, double *alpha, int offsetA, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dgemm_tt_12x4_vs_lib4(int k, double *alpha, int offsetA, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, int m1, int n1); // -void kernel_dsyrk_nn_u_12x4_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dsyrk_nn_u_12x4_vs_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, int m1, int n1); // -void kernel_dsyrk_nt_l_12x4_lib4(int k, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dsyrk_nt_l_12x4_vs_lib4(int k, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, int km, int kn); // -void kernel_dtrmm_nt_ru_12x4_lib4(int k, double *alpha, double *A, int sda, double *B, double *D, int sdd); // -void kernel_dtrmm_nt_ru_12x4_vs_lib4(int k, double *alpha, double *A, int sda, double *B, double *D, int sdd, int km, int kn); // -void kernel_dtrmm_nn_rl_12x4_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *D, int sdd); -void kernel_dtrmm_nn_rl_12x4_vs_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *D, int sdd, int km, int kn); -void kernel_dtrsm_nt_rl_inv_12x4_lib4(int k, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E); -void kernel_dtrsm_nt_rl_inv_12x4_vs_lib4(int k, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E, int km, int kn); -void kernel_dtrsm_nt_rl_one_12x4_lib4(int k, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, double *E); -void kernel_dtrsm_nt_rl_one_12x4_vs_lib4(int k, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, double *E, int km, int kn); -void kernel_dtrsm_nt_ru_inv_12x4_lib4(int k, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E); -void kernel_dtrsm_nt_ru_inv_12x4_vs_lib4(int k, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E, int km, int kn); -void kernel_dtrsm_nt_ru_one_12x4_lib4(int k, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, double *E); -void kernel_dtrsm_nt_ru_one_12x4_vs_lib4(int k, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, double *E, int km, int kn); -void kernel_dtrsm_nn_ru_inv_12x4_lib4(int k, double *A, int sda, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E); -void kernel_dtrsm_nn_ru_inv_12x4_vs_lib4(int k, double *A, int sda, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E, int km, int kn); -void kernel_dtrsm_nn_ll_inv_12x4_lib4(int k, double *A, int sda, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int sde, double *inv_diag_E); -void kernel_dtrsm_nn_ll_inv_12x4_vs_lib4(int k, double *A, int sda, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int sde, double *inv_diag_E, int km, int kn); -void kernel_dtrsm_nn_ll_one_12x4_lib4(int k, double *A, int sda, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int sde); -void kernel_dtrsm_nn_ll_one_12x4_vs_lib4(int k, double *A, int sda, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int sde, int km, int kn); -void kernel_dtrsm_nn_lu_inv_12x4_lib4(int kmax, double *A, int sda, double *B, int sdb, double *C, int sdc, double *D, int sdd, double *E, int sde, double *inv_diag_E); -void kernel_dtrsm_nn_lu_inv_12x4_vs_lib4(int kmax, double *A, int sda, double *B, int sdb, double *C, int sdc, double *D, int sdd, double *E, int sde, double *inv_diag_E, int km, int kn); -// 4x12 -void kernel_dgemm_nt_4x12_lib4(int k, double *alpha, double *A, double *B, int sdb, double *beta, double *C, double *D); // -void kernel_dgemm_nt_4x12_vs_lib4(int k, double *alpha, double *A, double *B, int sdb, double *beta, double *C, double *D, int km, int kn); // -void kernel_dgemm_nn_4x12_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *beta, double *C, double *D); // -void kernel_dgemm_nn_4x12_vs_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *beta, double *C, double *D, int m1, int n1); // -void kernel_dgemm_tt_4x12_lib4(int k, double *alpha, int offsetA, double *A, int sda, double *B, int sdb, double *beta, double *C, double *D); // -void kernel_dgemm_tt_4x12_vs_lib4(int k, double *alpha, int offsetA, double *A, int sda, double *B, int sdb, double *beta, double *C, double *D, int m1, int n1); // -void kernel_dgemm_tt_4x12_gen_lib4(int k, double *alpha, int offsetA, double *A, int sda, double *B, int sdb, double *beta, int offsetC, double *C, int sdc, int offsetD, double *D, int sdd, int m0, int m1, int n0, int n1); // -void kernel_dtrsm_nt_rl_inv_4x12_lib4(int k, double *A, double *B, int sdb, double *C, double *D, double *E, int sed, double *inv_diag_E); -void kernel_dtrsm_nt_rl_inv_4x12_vs_lib4(int k, double *A, double *B, int sdb, double *C, double *D, double *E, int sed, double *inv_diag_E, int km, int kn); -// 8x8 -void kernel_dgemm_nt_8x8l_lib4(int k, double *alpha, double *A, int sda, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd); // computes [A00 *; A10 A11] -void kernel_dgemm_nt_8x8u_lib4(int k, double *alpha, double *A, int sda, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd); // computes [A00 *; A10 A11] -void kernel_dgemm_nt_8x8l_vs_lib4(int k, double *alpha, double *A, int sda, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, int km, int kn); // computes [A00 *; A10 A11] -void kernel_dgemm_nt_8x8u_vs_lib4(int k, double *alpha, double *A, int sda, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, int km, int kn); // computes [A00 *; A10 A11] -void kernel_dsyrk_nn_u_8x8_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dsyrk_nn_u_8x8_vs_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, int m1, int n1); // -void kernel_dsyrk_nt_l_8x8_lib4(int k, double *alpha, double *A, int sda, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd); // computes [L00 *; A10 L11] -void kernel_dsyrk_nt_l_8x8_vs_lib4(int k, double *alpha, double *A, int sda, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, int km, int kn); // computes [L00 *; A10 L11] -void kernel_dtrsm_nt_rl_inv_8x8l_lib4(int k, double *A, int sda, double *B, int sdb, double *C, int sdc, double *D, int sdd, double *E, int sed, double *inv_diag_E); -void kernel_dtrsm_nt_rl_inv_8x8l_vs_lib4(int k, double *A, int sda, double *B, int sdb, double *C, int sdc, double *D, int sdd, double *E, int sed, double *inv_diag_E, int km, int kn); -void kernel_dtrsm_nt_rl_inv_8x8u_lib4(int k, double *A, int sda, double *B, int sdb, double *C, int sdc, double *D, int sdd, double *E, int sed, double *inv_diag_E); -void kernel_dtrsm_nt_rl_inv_8x8u_vs_lib4(int k, double *A, int sda, double *B, int sdb, double *C, int sdc, double *D, int sdd, double *E, int sed, double *inv_diag_E, int km, int kn); -// 8x4 -void kernel_dgemm_nt_8x4_lib4(int k, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dgemm_nt_8x4_vs_lib4(int k, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, int km, int kn); // -void kernel_dgemm_nt_8x4_gen_lib4(int k, double *alpha, double *A, int sda, double *B, double *beta, int offsetC, double *C, int sdc, int offsetD, double *D, int sdd, int m0, int m1, int k0, int k1); -void kernel_dgemm_nn_8x4_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dgemm_nn_8x4_vs_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, int m1, int n1); // -void kernel_dgemm_nn_8x4_gen_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, int offsetC, double *C, int sdc, int offsetD, double *D, int sdd, int m0, int m1, int n0, int n1); // -void kernel_dgemm_tt_8x4_lib4(int k, double *alpha, int offsetA, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dgemm_tt_8x4_vs_lib4(int k, double *alpha, int offsetA, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, int m1, int n1); // -void kernel_dsyrk_nn_u_8x4_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dsyrk_nn_u_8x4_vs_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, int m1, int n1); // -void kernel_dsyrk_nt_l_8x4_lib4(int k, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dsyrk_nt_l_8x4_vs_lib4(int k, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, int km, int kn); // -void kernel_dsyrk_nt_l_8x4_gen_lib4(int k, double *alpha, double *A, int sda, double *B, double *beta, int offsetC, double *C, int sdc, int offsetD, double *D, int sdd, int m0, int m1, int k0, int k1); -void kernel_dtrmm_nt_ru_8x4_lib4(int k, double *alpha, double *A, int sda, double *B, double *D, int sdd); // -void kernel_dtrmm_nt_ru_8x4_vs_lib4(int k, double *alpha, double *A, int sda, double *B, double *D, int sdd, int km, int kn); // -void kernel_dtrmm_nn_rl_8x4_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *D, int sdd); -void kernel_dtrmm_nn_rl_8x4_vs_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *D, int sdd, int km, int kn); -void kernel_dtrmm_nn_rl_8x4_gen_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, int offsetD, double *D, int sdd, int m0, int m1, int n0, int n1); -void kernel_dtrsm_nt_rl_inv_8x4_vs_lib4(int k, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E, int km, int kn); -void kernel_dtrsm_nt_rl_inv_8x4_lib4(int k, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E); -void kernel_dtrsm_nt_rl_one_8x4_lib4(int k, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, double *E); -void kernel_dtrsm_nt_rl_one_8x4_vs_lib4(int k, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, double *E, int km, int kn); -void kernel_dtrsm_nt_ru_inv_8x4_lib4(int k, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E); -void kernel_dtrsm_nt_ru_inv_8x4_vs_lib4(int k, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E, int km, int kn); -void kernel_dtrsm_nt_ru_one_8x4_lib4(int k, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, double *E); -void kernel_dtrsm_nt_ru_one_8x4_vs_lib4(int k, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd, double *E, int km, int kn); -void kernel_dtrsm_nn_ru_inv_8x4_lib4(int k, double *A, int sda, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E); -void kernel_dtrsm_nn_ru_inv_8x4_vs_lib4(int k, double *A, int sda, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E, int km, int kn); -void kernel_dtrsm_nn_ll_inv_8x4_lib4(int k, double *A, int sda, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int sde, double *inv_diag_E); -void kernel_dtrsm_nn_ll_inv_8x4_vs_lib4(int k, double *A, int sda, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int sde, double *inv_diag_E, int km, int kn); -void kernel_dtrsm_nn_ll_one_8x4_lib4(int k, double *A, int sda, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int sde); -void kernel_dtrsm_nn_ll_one_8x4_vs_lib4(int k, double *A, int sda, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int sde, int km, int kn); -void kernel_dtrsm_nn_lu_inv_8x4_lib4(int kmax, double *A, int sda, double *B, int sdb, double *C, int sdc, double *D, int sdd, double *E, int sde, double *inv_diag_E); -void kernel_dtrsm_nn_lu_inv_8x4_vs_lib4(int kmax, double *A, int sda, double *B, int sdb, double *C, int sdc, double *D, int sdd, double *E, int sde, double *inv_diag_E, int km, int kn); -// 4x8 -void kernel_dgemm_nt_4x8_lib4(int k, double *alpha, double *A, double *B, int sdb, double *beta, double *C, double *D); // -void kernel_dgemm_nt_4x8_vs_lib4(int k, double *alpha, double *A, double *B, int sdb, double *beta, double *C, double *D, int km, int kn); // -void kernel_dgemm_nn_4x8_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *beta, double *C, double *D); // -void kernel_dgemm_nn_4x8_vs_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *beta, double *C, double *D, int m1, int n1); // -void kernel_dgemm_tt_4x8_lib4(int k, double *alpha, int offsetA, double *A, int sda, double *B, int sdb, double *beta, double *C, double *D); // -void kernel_dgemm_tt_4x8_vs_lib4(int k, double *alpha, int offsetA, double *A, int sda, double *B, int sdb, double *beta, double *C, double *D, int m1, int n1); // -void kernel_dgemm_tt_4x8_gen_lib4(int k, double *alpha, int offsetA, double *A, int sda, double *B, int sdb, double *beta, int offsetC, double *C, int sdc, int offsetD, double *D, int sdd, int m0, int m1, int n0, int n1); // -void kernel_dtrsm_nt_rl_inv_4x8_lib4(int k, double *A, double *B, int sdb, double *C, double *D, double *E, int sed, double *inv_diag_E); -void kernel_dtrsm_nt_rl_inv_4x8_vs_lib4(int k, double *A, double *B, int sdb, double *C, double *D, double *E, int sed, double *inv_diag_E, int km, int kn); -// 8x2 -void kernel_dgemm_nn_8x2_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dgemm_nn_8x2_vs_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, int m1, int n1); // -// 2x8 -void kernel_dgemm_nn_2x8_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *beta, double *C, double *D); // -void kernel_dgemm_nn_2x8_vs_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *beta, double *C, double *D, int m1, int n1); // -// 10xX -void kernel_dgemm_nn_10x4_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dgemm_nn_10x4_vs_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, int m1, int n1); // -void kernel_dgemm_nn_10x2_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dgemm_nn_10x2_vs_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, int m1, int n1); // -// 6xX -void kernel_dgemm_nn_8x6_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dgemm_nn_8x6_vs_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, int m1, int n1); // -void kernel_dgemm_nn_6x8_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dgemm_nn_6x8_vs_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, int m1, int n1); // -void kernel_dgemm_nn_6x6_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dgemm_nn_6x6_vs_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, int m1, int n1); // -void kernel_dgemm_nn_6x4_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dgemm_nn_6x4_vs_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, int m1, int n1); // -void kernel_dgemm_nn_6x2_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd); // -void kernel_dgemm_nn_6x2_vs_lib4(int k, double *alpha, double *A, int sda, int offsetB, double *B, int sdb, double *beta, double *C, int sdc, double *D, int sdd, int m1, int n1); // -// 4x4 -void kernel_dgemm_nt_4x4_lib4(int k, double *alpha, double *A, double *B, double *beta, double *C, double *D); // -void kernel_dgemm_nt_4x4_vs_lib4(int k, double *alpha, double *A, double *B, double *beta, double *C, double *D, int km, int kn); // -void kernel_dgemm_nt_4x4_gen_lib4(int k, double *alpha, double *A, double *B, double *beta, int offsetC, double *C, int sdc, int offsetD, double *D, int sdd, int m0, int m1, int n0, int n1); -void kernel_dgemm_nn_4x4_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *beta, double *C, double *D); // -void kernel_dgemm_nn_4x4_vs_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *beta, double *C, double *D, int m1, int n1); // -void kernel_dgemm_nn_4x4_gen_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *beta, int offsetC, double *C, int sdc, int offsetD, double *D, int sdd, int m0, int m1, int n0, int n1); // -void kernel_dgemm_tt_4x4_lib4(int k, double *alpha, int offsetA, double *A, int sda, double *B, double *beta, double *C, double *D); // -void kernel_dgemm_tt_4x4_vs_lib4(int k, double *alpha, int offsetA, double *A, int sda, double *B, double *beta, double *C, double *D, int m1, int n1); // -void kernel_dgemm_tt_4x4_gen_lib4(int k, double *alpha, int offsetA, double *A, int sda, double *B, double *beta, int offsetC, double *C, int sdc, int offsetD, double *D, int sdd, int m0, int m1, int n0, int n1); // -void kernel_dsyrk_nn_u_4x4_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *beta, double *C, double *D); // -void kernel_dsyrk_nn_u_4x4_vs_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *beta, double *C, double *D, int m1, int n1); // -void kernel_dsyrk_nt_l_4x4_lib4(int k, double *alpha, double *A, double *B, double *beta, double *C, double *D); // -void kernel_dsyrk_nt_l_4x4_vs_lib4(int k, double *alpha, double *A, double *B, double *beta, double *C, double *D, int km, int kn); // -void kernel_dsyrk_nt_l_4x4_gen_lib4(int k, double *alpha, double *A, double *B, double *beta, int offsetC, double *C, int sdc, int offsetD, double *D, int sdd, int m0, int m1, int n0, int n1); -void kernel_dsyrk_nt_u_4x4_lib4(int k, double *alpha, double *A, double *B, double *beta, double *C, double *D); // -void kernel_dsyrk_nt_u_4x4_vs_lib4(int k, double *alpha, double *A, double *B, double *beta, double *C, double *D, int km, int kn); // -void kernel_dsyrk_nt_u_4x4_gen_lib4(int k, double *alpha, double *A, double *B, double *beta, int offsetC, double *C, int sdc, int offsetD, double *D, int sdd, int m0, int m1, int n0, int n1); -void kernel_dtrmm_nt_ru_4x4_lib4(int k, double *alpha, double *A, double *B, double *D); // -void kernel_dtrmm_nt_ru_4x4_vs_lib4(int k, double *alpha, double *A, double *B, double *D, int km, int kn); // -void kernel_dtrmm_nn_rl_4x4_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *D); -void kernel_dtrmm_nn_rl_4x4_vs_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *D, int m1, int n1); -void kernel_dtrmm_nn_rl_4x4_gen_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, int offsetD, double *D, int sdd, int m0, int m1, int n0, int n1); -void kernel_dtrsm_nt_rl_inv_4x4_lib4(int k, double *A, double *B, double *beta, double *C, double *D, double *E, double *inv_diag_E); -void kernel_dtrsm_nt_rl_inv_4x4_vs_lib4(int k, double *A, double *B, double *beta, double *C, double *D, double *E, double *inv_diag_E, int km, int kn); -void kernel_dtrsm_nt_rl_one_4x4_lib4(int k, double *A, double *B, double *beta, double *C, double *D, double *E); -void kernel_dtrsm_nt_rl_one_4x4_vs_lib4(int k, double *A, double *B, double *beta, double *C, double *D, double *E, int km, int kn); -void kernel_dtrsm_nt_ru_inv_4x4_lib4(int k, double *A, double *B, double *beta, double *C, double *D, double *E, double *inv_diag_E); -void kernel_dtrsm_nt_ru_inv_4x4_vs_lib4(int k, double *A, double *B, double *beta, double *C, double *D, double *E, double *inv_diag_E, int km, int kn); -void kernel_dtrsm_nt_ru_one_4x4_lib4(int k, double *A, double *B, double *beta, double *C, double *D, double *E); -void kernel_dtrsm_nt_ru_one_4x4_vs_lib4(int k, double *A, double *B, double *beta, double *C, double *D, double *E, int km, int kn); -void kernel_dtrsm_nn_ru_inv_4x4_lib4(int k, double *A, double *B, int sdb, double *beta, double *C, double *D, double *E, double *inv_diag_E); -void kernel_dtrsm_nn_ru_inv_4x4_vs_lib4(int k, double *A, double *B, int sdb, double *beta, double *C, double *D, double *E, double *inv_diag_E, int km, int kn); -void kernel_dtrsm_nn_ll_inv_4x4_lib4(int k, double *A, double *B, int sdb, double *beta, double *C, double *D, double *E, double *inv_diag_E); -void kernel_dtrsm_nn_ll_inv_4x4_vs_lib4(int k, double *A, double *B, int sdb, double *beta, double *C, double *D, double *E, double *inv_diag_E, int km, int kn); -void kernel_dtrsm_nn_ll_one_4x4_lib4(int k, double *A, double *B, int sdb, double *beta, double *C, double *D, double *E); -void kernel_dtrsm_nn_ll_one_4x4_vs_lib4(int k, double *A, double *B, int sdb, double *beta, double *C, double *D, double *E, int km, int kn); -void kernel_dtrsm_nn_lu_inv_4x4_lib4(int kmax, double *A, double *B, int sdb, double *C, double *D, double *E, double *inv_diag_E); -void kernel_dtrsm_nn_lu_inv_4x4_vs_lib4(int kmax, double *A, double *B, int sdb, double *C, double *D, double *E, double *inv_diag_E, int km, int kn); -void kernel_dtrsm_nn_lu_one_4x4_lib4(int kmax, double *A, double *B, int sdb, double *C, double *D, double *E); -void kernel_dtrsm_nn_lu_one_4x4_vs_lib4(int kmax, double *A, double *B, int sdb, double *C, double *D, double *E, int km, int kn); -// 4x2 -void kernel_dgemm_nn_4x2_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *beta, double *C, double *D); // -void kernel_dgemm_nn_4x2_vs_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *beta, double *C, double *D, int m1, int n1); // -void kernel_dgemm_nt_4x2_lib4(int k, double *alpha, double *A, double *B, double *beta, double *C, double *D); -void kernel_dgemm_nt_4x2_vs_lib4(int k, double *alpha, double *A, double *B, double *beta, double *C, double *D, int m1, int n1); -void kernel_dsyrk_nt_l_4x2_lib4(int k, double *alpha, double *A, double *B, double *beta, double *C, double *D); // -void kernel_dsyrk_nt_l_4x2_vs_lib4(int k, double *alpha, double *A, double *B, double *beta, double *C, double *D, int km, int kn); // -void kernel_dtrmm_nn_rl_4x2_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *D); -void kernel_dtrmm_nn_rl_4x2_vs_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *D, int m1, int n1); -void kernel_dtrsm_nt_rl_inv_4x2_lib4(int k, double *A, double *B, double *beta, double *C, double *D, double *E, double *inv_diag_E); -void kernel_dtrsm_nt_rl_inv_4x2_vs_lib4(int k, double *A, double *B, double *beta, double *C, double *D, double *E, double *inv_diag_E, int km, int kn); -// 2x4 -void kernel_dgemm_nn_2x4_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *beta, double *C, double *D); // -void kernel_dgemm_nn_2x4_vs_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *beta, double *C, double *D, int m1, int n1); // -// 2x2 -void kernel_dgemm_nn_2x2_lib4(int k, double *alpha, double *A, int offsetB, double *B, int sdb, double *beta, double *C, double *D); // -void kernel_dsyrk_nt_l_2x2_lib4(int k, double *alpha, double *A, double *B, double *beta, double *C, double *D); // -void kernel_dsyrk_nt_l_2x2_vs_lib4(int k, double *alpha, double *A, double *B, double *beta, double *C, double *D, int km, int kn); // -// diag -void kernel_dgemm_diag_right_4_a0_lib4(int kmax, double *alpha, double *A, int sda, double *B, double *D, int sdd); -void kernel_dgemm_diag_right_4_lib4(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd); -void kernel_dgemm_diag_right_3_lib4(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd); -void kernel_dgemm_diag_right_2_lib4(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd); -void kernel_dgemm_diag_right_1_lib4(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int sdd); -void kernel_dgemm_diag_left_4_a0_lib4(int kmax, double *alpha, double *A, double *B, double *D); -void kernel_dgemm_diag_left_4_lib4(int kmax, double *alpha, double *A, double *B, double *beta, double *C, double *D); -void kernel_dgemm_diag_left_3_lib4(int kmax, double *alpha, double *A, double *B, double *beta, double *C, double *D); -void kernel_dgemm_diag_left_2_lib4(int kmax, double *alpha, double *A, double *B, double *beta, double *C, double *D); -void kernel_dgemm_diag_left_1_lib4(int kmax, double *alpha, double *A, double *B, double *beta, double *C, double *D); -// low rank update -void kernel_dger4_sub_12r_lib4(int k, double *A, int sda, double *B, double *C, int sdc); -void kernel_dger4_sub_12r_vs_lib4(int k, double *A, int sda, double *B, double *C, int sdc, int km); -void kernel_dger4_sub_8r_lib4(int k, double *A, int sda, double *B, double *C, int sdc); -void kernel_dger4_sub_8r_vs_lib4(int k, double *A, int sda, double *B, double *C, int sdc, int km); -void kernel_dger4_sub_4r_lib4(int n, double *A, double *B, double *C); -void kernel_dger4_sub_4r_vs_lib4(int n, double *A, double *B, double *C, int km); - - - -// LAPACK -// 12x4 -void kernel_dpotrf_nt_l_12x4_lib4(int k, double *A, int sda, double *B, double *C, int sdc, double *D, int sdd, double *inv_diag_D); -void kernel_dpotrf_nt_l_12x4_vs_lib4(int k, double *A, int sda, double *B, double *C, int sdc, double *D, int sdd, double *inv_diag_D, int km, int kn); -void kernel_dgetrf_nn_l_12x4_lib4(int k, double *A, int sda, double *B, int sdb, double *C, int sdc, double *D, int sdd, double *inv_diag_D); -void kernel_dgetrf_nn_l_12x4_vs_lib4(int k, double *A, int sda, double *B, int sdb, double *C, int sdc, double *D, int sdd, double *inv_diag_D, int km, int kn); -void kernel_dgetrf_nn_m_12x4_lib4(int k, double *A, int sda, double *B, int sdb, double *C, int sdc, double *D, int sdd, double *inv_diag_D); -void kernel_dgetrf_nn_m_12x4_vs_lib4(int k, double *A, int sda, double *B, int sdb, double *C, int sdc, double *D, int sdd, double *inv_diag_D, int km, int kn); -void kernel_dgetrf_nn_r_12x4_lib4(int k, double *A, int sda, double *B, int sdb, double *C, int sdc, double *D, int sdd, double *inv_diag_D); -void kernel_dgetrf_nn_r_12x4_vs_lib4(int k, double *A, int sda, double *B, int sdb, double *C, int sdc, double *D, int sdd, double *inv_diag_D, int km, int kn); -void kernel_dgetrf_nt_l_12x4_lib4(int k, double *A, int sda, double *B, double *C, int sdc, double *D, int sdd, double *inv_diag_D); -void kernel_dgetrf_nt_l_12x4_vs_lib4(int k, double *A, int sda, double *B, double *C, int sdc, double *D, int sdd, double *inv_diag_D, int km, int kn); -void kernel_dgetrf_nt_m_12x4_lib4(int k, double *A, int sda, double *B, double *C, int sdc, double *D, int sdd, double *inv_diag_D); -void kernel_dgetrf_nt_m_12x4_vs_lib4(int k, double *A, int sda, double *B, double *C, int sdc, double *D, int sdd, double *inv_diag_D, int km, int kn); -void kernel_dgetrf_nt_r_12x4_lib4(int k, double *A, int sda, double *B, double *C, int sdc, double *D, int sdd, double *inv_diag_D); -void kernel_dgetrf_nt_r_12x4_vs_lib4(int k, double *A, int sda, double *B, double *C, int sdc, double *D, int sdd, double *inv_diag_D, int km, int kn); -// 8x8 -void kernel_dpotrf_nt_l_8x8_lib4(int k, double *A, int sda, double *B, int sdb, double *C, int sdc, double *D, int sdd, double *inv_diag_D); -void kernel_dpotrf_nt_l_8x8_vs_lib4(int k, double *A, int sda, double *B, int sdb, double *C, int sdc, double *D, int sdd, double *inv_diag_D, int km, int kn); -// 8x4 -void kernel_dpotrf_nt_l_8x4_lib4(int k, double *A, int sda, double *B, double *C, int sdc, double *D, int sdd, double *inv_diag_D); -void kernel_dpotrf_nt_l_8x4_vs_lib4(int k, double *A, int sda, double *B, double *C, int sdc, double *D, int sdd, double *inv_diag_D, int km, int kn); -void kernel_dgetrf_nn_l_8x4_lib4(int k, double *A, int sda, double *B, int sdb, double *C, int sdc, double *D, int sdd, double *inv_diag_D); -void kernel_dgetrf_nn_l_8x4_vs_lib4(int k, double *A, int sda, double *B, int sdb, double *C, int sdc, double *D, int sdd, double *inv_diag_D, int km, int kn); -void kernel_dgetrf_nn_r_8x4_lib4(int k, double *A, int sda, double *B, int sdb, double *C, int sdc, double *D, int sdd, double *inv_diag_D); -void kernel_dgetrf_nn_r_8x4_vs_lib4(int k, double *A, int sda, double *B, int sdb, double *C, int sdc, double *D, int sdd, double *inv_diag_D, int km, int kn); -void kernel_dgetrf_nt_l_8x4_lib4(int k, double *A, int sda, double *B, double *C, int sdc, double *D, int sdd, double *inv_diag_D); -void kernel_dgetrf_nt_l_8x4_vs_lib4(int k, double *A, int sda, double *B, double *C, int sdc, double *D, int sdd, double *inv_diag_D, int km, int kn); -void kernel_dgetrf_nt_r_8x4_lib4(int k, double *A, int sda, double *B, double *C, int sdc, double *D, int sdd, double *inv_diag_D); -void kernel_dgetrf_nt_r_8x4_vs_lib4(int k, double *A, int sda, double *B, double *C, int sdc, double *D, int sdd, double *inv_diag_D, int km, int kn); -// 4x4 -void kernel_dpotrf_nt_l_4x4_lib4(int k, double *A, double *B, double *C, double *D, double *inv_diag_D); -void kernel_dpotrf_nt_l_4x4_vs_lib4(int k, double *A, double *B, double *C, double *D, double *inv_diag_D, int km, int kn); -#if defined(TARGET_X64_INTEL_SANDY_BRIDGE) -void kernel_dlauum_nt_4x4_lib4(int k, double *alpha, double *A, double *B, double *beta, double *C, double *D); // -void kernel_dlauum_nt_4x4_vs_lib4(int k, double *alpha, double *A, double *B, double *beta, double *C, double *D, int km, int kn); // -#endif -void kernel_dgetrf_nn_4x4_lib4(int k, double *A, double *B, int sdb, double *C, double *D, double *inv_diag_D); -void kernel_dgetrf_nn_4x4_vs_lib4(int k, double *A, double *B, int sdb, double *C, double *D, double *inv_diag_D, int km, int kn); -void kernel_dgetrf_nt_4x4_lib4(int k, double *A, double *B, double *C, double *D, double *inv_diag_D); -void kernel_dgetrf_nt_4x4_vs_lib4(int k, double *A, double *B, double *C, double *D, double *inv_diag_D, int km, int kn); -void kernel_dgeqrf_4_lib4(int m, double *pD, int sdd, double *dD); -void kernel_dgeqrf_vs_lib4(int m, int n, int k, int offD, double *pD, int sdd, double *dD); -void kernel_dlarf_4_lib4(int m, int n, double *pV, int sdv, double *tau, double *pC, int sdc); // rank-4 reflector -void kernel_dlarf_t_4_lib4(int m, int n, double *pD, int sdd, double *pVt, double *dD, double *pC0, int sdc, double *pW); -void kernel_dgelqf_4_lib4(int n, double *pD, double *dD); -void kernel_dgelqf_vs_lib4(int m, int n, int k, int offD, double *pD, int sdd, double *dD); -void kernel_dlarft_4_lib4(int kmax, double *pD, double *dD, double *pT); -void kernel_dlarft_3_lib4(int kmax, double *pD, double *dD, double *pT); -void kernel_dlarft_2_lib4(int kmax, double *pD, double *dD, double *pT); -void kernel_dlarft_1_lib4(int kmax, double *pD, double *dD, double *pT); -void kernel_dgelqf_dlarft12_12_lib4(int n, double *pD, int sdd, double *dD, double *pT); -void kernel_dgelqf_dlarft4_12_lib4(int n, double *pD, int sdd, double *dD, double *pT); -void kernel_dgelqf_dlarft4_8_lib4(int n, double *pD, int sdd, double *dD, double *pT); -void kernel_dgelqf_dlarft4_4_lib4(int n, double *pD, double *dD, double *pT); -void kernel_dlarfb12_rn_12_lib4(int kmax, double *pV, int sdd, double *pT, double *pD, double *pK); -void kernel_dlarfb12_rn_4_lib4(int kmax, double *pV, int sdd, double *pT, double *pD, double *pK, int km); -void kernel_dlarfb4_rn_12_lib4(int kmax, double *pV, double *pT, double *pD, int sdd); -void kernel_dlarfb4_rn_8_lib4(int kmax, double *pV, double *pT, double *pD, int sdd); -void kernel_dlarfb4_rn_4_lib4(int kmax, double *pV, double *pT, double *pD); -void kernel_dlarfb3_rn_4_lib4(int kmax, double *pV, double *pT, double *pD); -void kernel_dlarfb2_rn_4_lib4(int kmax, double *pV, double *pT, double *pD); -void kernel_dlarfb1_rn_4_lib4(int kmax, double *pV, double *pT, double *pD); -void kernel_dlarfb4_rn_1_lib4(int kmax, double *pV, double *pT, double *pD); -void kernel_dlarfb3_rn_1_lib4(int kmax, double *pV, double *pT, double *pD); -void kernel_dlarfb2_rn_1_lib4(int kmax, double *pV, double *pT, double *pD); -void kernel_dlarfb1_rn_1_lib4(int kmax, double *pV, double *pT, double *pD); -void kernel_dlarfb4_rt_4_lib4(int kmax, double *pV, double *pT, double *pD); -void kernel_dlarfb3_rt_4_lib4(int kmax, double *pV, double *pT, double *pD); -void kernel_dlarfb2_rt_4_lib4(int kmax, double *pV, double *pT, double *pD); -void kernel_dlarfb1_rt_4_lib4(int kmax, double *pV, double *pT, double *pD); -void kernel_dlarfb4_rt_1_lib4(int kmax, double *pV, double *pT, double *pD); -void kernel_dlarfb3_rt_1_lib4(int kmax, double *pV, double *pT, double *pD); -void kernel_dlarfb2_rt_1_lib4(int kmax, double *pV, double *pT, double *pD); -void kernel_dlarfb1_rt_1_lib4(int kmax, double *pV, double *pT, double *pD); -void kernel_dgelqf_pd_dlarft12_12_lib4(int n, double *pD, int sdd, double *dD, double *pT); -void kernel_dgelqf_pd_dlarft4_8_lib4(int n, double *pD, int sdd, double *dD, double *pT); -void kernel_dgelqf_pd_dlarft4_4_lib4(int n, double *pD, double *dD, double *pT); -void kernel_dgelqf_pd_4_lib4(int n, double *pD, double *dD); -void kernel_dgelqf_pd_vs_lib4(int m, int n, int k, int offD, double *pD, int sdd, double *dD); -void kernel_dgelqf_pd_la_vs_lib4(int m, int n1, int k, int offD, double *pD, int sdd, double *dD, int offA, double *pA, int sda); -void kernel_dlarft_4_la_lib4(int n1, double *dD, double *pA, double *pT); -void kernel_dlarfb4_rn_12_la_lib4(int n1, double *pVA, double *pT, double *pD, int sdd, double *pA, int sda); -void kernel_dlarfb4_rn_8_la_lib4(int n1, double *pVA, double *pT, double *pD, int sdd, double *pA, int sda); -void kernel_dlarfb4_rn_4_la_lib4(int n1, double *pVA, double *pT, double *pD, double *pA); -void kernel_dlarfb4_rn_1_la_lib4(int n1, double *pVA, double *pT, double *pD, double *pA); -void kernel_dgelqf_pd_lla_vs_lib4(int m, int n0, int n1, int k, int offD, double *pD, int sdd, double *dD, int offL, double *pL, int sdl, int offA, double *pA, int sda); -void kernel_dlarft_4_lla_lib4(int n0, int n1, double *dD, double *pL, double *pA, double *pT); -void kernel_dlarfb4_rn_12_lla_lib4(int n0, int n1, double *pVL, double *pVA, double *pT, double *pD, int sdd, double *pL, int sdl, double *pA, int sda); -void kernel_dlarfb4_rn_8_lla_lib4(int n0, int n1, double *pVL, double *pVA, double *pT, double *pD, int sdd, double *pL, int sdl, double *pA, int sda); -void kernel_dlarfb4_rn_4_lla_lib4(int n0, int n1, double *pVL, double *pVA, double *pT, double *pD, double *pL, double *pA); -void kernel_dlarfb4_rn_1_lla_lib4(int n0, int n1, double *pVL, double *pVA, double *pT, double *pD, double *pL, double *pA); -// 4x2 -void kernel_dpotrf_nt_l_4x2_lib4(int k, double *A, double *B, double *C, double *D, double *inv_diag_D); -void kernel_dpotrf_nt_l_4x2_vs_lib4(int k, double *A, double *B, double *C, double *D, double *inv_diag_D, int km, int kn); -// 2x2 -void kernel_dpotrf_nt_l_2x2_lib4(int k, double *A, double *B, double *C, double *D, double *inv_diag_D); -void kernel_dpotrf_nt_l_2x2_vs_lib4(int k, double *A, double *B, double *C, double *D, double *inv_diag_D, int km, int kn); -// 12 -void kernel_dgetrf_pivot_12_lib4(int m, double *pA, int sda, double *inv_diag_A, int* ipiv); -void kernel_dgetrf_pivot_12_vs_lib4(int m, double *pA, int sda, double *inv_diag_A, int* ipiv, int n); -// 8 -void kernel_dgetrf_pivot_8_lib4(int m, double *pA, int sda, double *inv_diag_A, int* ipiv); -void kernel_dgetrf_pivot_8_vs_lib4(int m, double *pA, int sda, double *inv_diag_A, int* ipiv, int n); -// 4 -void kernel_dgetrf_pivot_4_lib4(int m, double *pA, int sda, double *inv_diag_A, int* ipiv); -void kernel_dgetrf_pivot_4_vs_lib4(int m, double *pA, int sda, double *inv_diag_A, int* ipiv, int n1); -// vector -void kernel_drowsw_lib4(int kmax, double *pA, double *pC); - - - -// merged routines -// 12x4 -void kernel_dgemm_dtrsm_nt_rl_inv_12x4_lib4(int kp, double *Ap, int sdap, double *Bp, int km_, double *Am, int sdam, double *Bm, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E); -void kernel_dgemm_dtrsm_nt_rl_inv_12x4_vs_lib4(int kp, double *Ap, int sdap, double *Bp, int km_, double *Am, int sdam, double *Bm, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E, int km, int kn); -void kernel_dsyrk_dpotrf_nt_l_12x4_lib4(int kp, double *Ap, int sdap, double *Bp, int km_, double *Am, int sdam, double *Bm, double *C, int sdc, double *D, int sdd, double *inv_diag_D); -void kernel_dsyrk_dpotrf_nt_l_12x4_vs_lib4(int kp, double *Ap, int sdap, double *Bp, int km_, double *Am, int sdam, double *Bm, double *C, int sdc, double *D, int sdd, double *inv_diag_D, int km, int kn); -// 4x12 -void kernel_dgemm_dtrsm_nt_rl_inv_4x12_vs_lib4(int kp, double *Ap, double *Bp, int sdbp, int km_, double *Am, double *Bm, int sdbm, double *C, double *D, double *E, int sde, double *inv_diag_E, int km, int kn); -// 8x8 -void kernel_dsyrk_dpotrf_nt_l_8x8_lib4(int kp, double *Ap, int sdap, double *Bp, int sdbp, int km_, double *Am, int sdam, double *Bm, int sdbm, double *C, int sdc, double *D, int sdd, double *inv_diag_D); -void kernel_dsyrk_dpotrf_nt_l_8x8_vs_lib4(int kp, double *Ap, int sdap, double *Bp, int sdbp, int km_, double *Am, int sdam, double *Bm, int sdbm, double *C, int sdc, double *D, int sdd, double *inv_diag_D, int km, int kn); -void kernel_dgemm_dtrsm_nt_rl_inv_8x8l_vs_lib4(int kp, double *Ap, int sdap, double *Bp, int sdb, int km_, double *Am, int sdam, double *Bm, int sdbm, double *C, int sdc, double *D, int sdd, double *E, int sde, double *inv_diag_E, int km, int kn); -void kernel_dgemm_dtrsm_nt_rl_inv_8x8u_vs_lib4(int kp, double *Ap, int sdap, double *Bp, int sdb, int km_, double *Am, int sdam, double *Bm, int sdbm, double *C, int sdc, double *D, int sdd, double *E, int sde, double *inv_diag_E, int km, int kn); -// 8x4 -void kernel_dgemm_dtrsm_nt_rl_inv_8x4_lib4(int kp, double *Ap, int sdap, double *Bp, int km_, double *Am, int sdam, double *Bm, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E); -void kernel_dgemm_dtrsm_nt_rl_inv_8x4_vs_lib4(int kp, double *Ap, int sdap, double *Bp, int km_, double *Am, int sdam, double *Bm, double *C, int sdc, double *D, int sdd, double *E, double *inv_diag_E, int km, int kn); -void kernel_dsyrk_dpotrf_nt_l_8x4_lib4(int kp, double *Ap, int sdap, double *Bp, int km_, double *Am, int sdam, double *Bm, double *C, int sdc, double *D, int sdd, double *inv_diag_D); -void kernel_dsyrk_dpotrf_nt_l_8x4_vs_lib4(int kp, double *Ap, int sdap, double *Bp, int km_, double *Am, int sdam, double *Bm, double *C, int sdc, double *D, int sdd, double *inv_diag_D, int km, int kn); -// 4x8 -void kernel_dgemm_dtrsm_nt_rl_inv_4x8_vs_lib4(int kp, double *Ap, double *Bp, int sdbp, int km_, double *Am, double *Bm, int sdbm, double *C, double *D, double *E, int sde, double *inv_diag_E, int km, int kn); -// 4x4 -void kernel_dgemm_dtrsm_nt_rl_inv_4x4_lib4(int kp, double *Ap, double *Bp, int km_, double *Am, double *Bm, double *C, double *D, double *E, double *inv_diag_E); -void kernel_dgemm_dtrsm_nt_rl_inv_4x4_vs_lib4(int kp, double *Ap, double *Bp, int km_, double *Am, double *Bm, double *C, double *D, double *E, double *inv_diag_E, int km, int kn); -void kernel_dsyrk_dpotrf_nt_l_4x4_lib4(int kp, double *Ap, double *Bp, int km_, double *Am, double *Bm, double *C, double *D, double *inv_diag_D); -void kernel_dsyrk_dpotrf_nt_l_4x4_vs_lib4(int kp, double *Ap, double *Bp, int km_, double *Am, double *Bm, double *C, double *D, double *inv_diag_D, int km, int kn); -// 4x2 -void kernel_dgemm_dtrsm_nt_rl_inv_4x2_lib4(int kp, double *Ap, double *Bp, int km_, double *Am, double *Bm, double *C, double *D, double *E, double *inv_diag_E); -void kernel_dgemm_dtrsm_nt_rl_inv_4x2_vs_lib4(int kp, double *Ap, double *Bp, int km_, double *Am, double *Bm, double *C, double *D, double *E, double *inv_diag_E, int km, int kn); -void kernel_dsyrk_dpotrf_nt_l_4x2_lib4(int kp, double *Ap, double *Bp, int km_, double *Am, double *Bm, double *C, double *D, double *inv_diag_D); -void kernel_dsyrk_dpotrf_nt_l_4x2_vs_lib4(int kp, double *Ap, double *Bp, int km_, double *Am, double *Bm, double *C, double *D, double *inv_diag_D, int km, int kn); -// 2x2 -void kernel_dsyrk_dpotrf_nt_l_2x2_lib4(int kp, double *Ap, double *Bp, int km_, double *Am, double *Bm, double *C, double *D, double *inv_diag_D); -void kernel_dsyrk_dpotrf_nt_l_2x2_vs_lib4(int kp, double *Ap, double *Bp, int km_, double *Am, double *Bm, double *C, double *D, double *inv_diag_D, int km, int kn); - -/* - * - * Auxiliary routines - * - * cpsc copy and scale, scale - * cp copy - * add - * set and scale - * transpose and scale - * set and scale - * - */ - -// copy and scale -void kernel_dgecpsc_8_0_lib4(int tri, int kmax, double alpha, double *A0, int sda, double *B, int sdb); -void kernel_dgecpsc_8_1_lib4(int tri, int kmax, double alpha, double *A0, int sda, double *B, int sdb); -void kernel_dgecpsc_8_2_lib4(int tri, int kmax, double alpha, double *A0, int sda, double *B, int sdb); -void kernel_dgecpsc_8_3_lib4(int tri, int kmax, double alpha, double *A0, int sda, double *B, int sdb); - -void kernel_dgecpsc_4_0_lib4(int tri, int kmax, double alpha, double *A, double *B); -void kernel_dgecpsc_4_1_lib4(int tri, int kmax, double alpha, double *A0, int sda, double *B); -void kernel_dgecpsc_4_2_lib4(int tri, int kmax, double alpha, double *A0, int sda, double *B); -void kernel_dgecpsc_4_3_lib4(int tri, int kmax, double alpha, double *A0, int sda, double *B); - -void kernel_dgecpsc_3_0_lib4(int tri, int kmax, double alpha, double *A, double *B); -void kernel_dgecpsc_3_2_lib4(int tri, int kmax, double alpha, double *A0, int sda, double *B); -void kernel_dgecpsc_3_3_lib4(int tri, int kmax, double alpha, double *A0, int sda, double *B); - -void kernel_dgecpsc_2_0_lib4(int tri, int kmax, double alpha, double *A, double *B); -void kernel_dgecpsc_2_3_lib4(int tri, int kmax, double alpha, double *A0, int sda, double *B); - -void kernel_dgecpsc_1_0_lib4(int tri, int kmax, double alpha, double *A, double *B); - -// copy only -void kernel_dgecp_8_0_lib4(int tri, int kmax, double *A, int sda, double *B, int sdb); - -void kernel_dgecp_4_0_lib4(int tri, int kmax, double *A, double *B); - -// add -void kernel_dgead_8_0_lib4(int kmax, double alpha, double *A0, int sda, double *B, int sdb); -void kernel_dgead_8_1_lib4(int kmax, double alpha, double *A0, int sda, double *B, int sdb); -void kernel_dgead_8_2_lib4(int kmax, double alpha, double *A0, int sda, double *B, int sdb); -void kernel_dgead_8_3_lib4(int kmax, double alpha, double *A0, int sda, double *B, int sdb); -void kernel_dgead_4_0_lib4(int kmax, double alpha, double *A, double *B); -void kernel_dgead_4_1_lib4(int kmax, double alpha, double *A0, int sda, double *B); -void kernel_dgead_4_2_lib4(int kmax, double alpha, double *A0, int sda, double *B); -void kernel_dgead_4_3_lib4(int kmax, double alpha, double *A0, int sda, double *B); -void kernel_dgead_3_0_lib4(int kmax, double alpha, double *A, double *B); -void kernel_dgead_3_2_lib4(int kmax, double alpha, double *A0, int sda, double *B); -void kernel_dgead_3_3_lib4(int kmax, double alpha, double *A0, int sda, double *B); -void kernel_dgead_2_0_lib4(int kmax, double alpha, double *A, double *B); -void kernel_dgead_2_3_lib4(int kmax, double alpha, double *A0, int sda, double *B); -void kernel_dgead_1_0_lib4(int kmax, double alpha, double *A, double *B); - -// set -void kernel_dgeset_4_lib4(int kmax, double alpha, double *A); -void kernel_dtrset_4_lib4(int kmax, double alpha, double *A); - -// traspose -void kernel_dgetr_8_lib4(int tri, int kmax, int kna, double alpha, double *A, int sda, double *C, int sdc); -void kernel_dgetr_4_lib4(int tri, int kmax, int kna, double alpha, double *A, double *C, int sdc); -void kernel_dgetr_3_lib4(int tri, int kmax, int kna, double alpha, double *A, double *C, int sdc); -void kernel_dgetr_2_lib4(int tri, int kmax, int kna, double alpha, double *A, double *C, int sdc); -void kernel_dgetr_1_lib4(int tri, int kmax, int kna, double alpha, double *A, double *C, int sdc); -void kernel_dgetr_4_0_lib4(int m, double *A, int sda, double *B); - - - -// pack -// 12 -void kernel_dpack_nn_12_lib4(int kmax, double *A, int lda, double *B, int sdb); -void kernel_dpack_nn_12_vs_lib4(int kmax, double *A, int lda, double *B, int sdb, int m1); -void kernel_dpack_tt_12_lib4(int kmax, double *A, int lda, double *B, int sdb); -// 8 -void kernel_dpack_nn_8_lib4(int kmax, double *A, int lda, double *B, int sdb); -void kernel_dpack_nn_8_vs_lib4(int kmax, double *A, int lda, double *B, int sdb, int m1); -void kernel_dpack_tt_8_lib4(int kmax, double *A, int lda, double *B, int sdb); -// 4 -void kernel_dpack_nn_4_lib4(int kmax, double *A, int lda, double *B); -void kernel_dpack_nn_4_vs_lib4(int kmax, double *A, int lda, double *B, int m1); -void kernel_dpack_tn_4_p0_lib4(int kmax, double *A, int lda, double *B); -void kernel_dpack_tn_4_lib4(int kmax, double *A, int lda, double *B); -void kernel_dpack_tn_4_vs_lib4(int kmax, double *A, int lda, double *B, int m1); -void kernel_dpack_tt_4_lib4(int kmax, double *A, int lda, double *B, int sdb); -void kernel_dpack_tt_4_vs_lib4(int kmax, double *A, int lda, double *B, int sdb, int m1); -// unpack -// 12 -void kernel_dunpack_nn_12_lib4(int kmax, double *A, int sda, double *B, int ldb); -void kernel_dunpack_nn_12_vs_lib4(int kmax, double *A, int sda, double *B, int ldb, int m1); -void kernel_dunpack_tt_12_lib4(int kmax, double *A, int sda, double *B, int ldb); -// 8 -void kernel_dunpack_nn_8_lib4(int kmax, double *A, int sda, double *B, int ldb); -void kernel_dunpack_nn_8_vs_lib4(int kmax, double *A, int sda, double *B, int ldb, int m1); -void kernel_dunpack_tt_8_lib4(int kmax, double *A, int sda, double *B, int ldb); -// 4 -void kernel_dunpack_nn_4_lib4(int kmax, double *A, double *B, int ldb); -void kernel_dunpack_nn_4_vs_lib4(int kmax, double *A, double *B, int ldb, int m1); -void kernel_dunpack_nt_4_lib4(int kmax, double *A, double *B, int ldb); -void kernel_dunpack_nt_4_vs_lib4(int kmax, double *A, double *B, int ldb, int m1); -void kernel_dunpack_tt_4_lib4(int kmax, double *A, int sda, double *B, int ldb); - -// panel copy -// 12 -void kernel_dpacp_nn_12_lib4(int kmax, int offsetA, double *A, int sda, double *B, int sdb); -void kernel_dpacp_nn_12_vs_lib4(int kmax, int offsetA, double *A, int sda, double *B, int sdb, int m1); -// 8 -void kernel_dpacp_nn_8_lib4(int kmax, int offsetA, double *A, int sda, double *B, int sdb); -void kernel_dpacp_nn_8_vs_lib4(int kmax, int offsetA, double *A, int sda, double *B, int sdb, int m1); -// 4 -void kernel_dpacp_nt_4_lib4(int kmax, double *A, int offsetB, double *B, int sdb); -void kernel_dpacp_tn_4_lib4(int kmax, int offsetA, double *A, int sda, double *B); -void kernel_dpacp_nn_4_lib4(int kmax, int offsetA, double *A, int sda, double *B); -void kernel_dpacp_nn_4_vs_lib4(int kmax, int offsetA, double *A, int sda, double *B, int m1); - - - -/************************************************ -* BLAS API kernels -************************************************/ - -//#if defined(BLAS_API) - -// A, B panel-major bs=4; C, D column-major -// 12x4 -void kernel_dgemm_nt_12x4_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_12x4_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_nt_12x4_p0_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *A_p, double *B_p); -void kernel_dsyrk_nt_l_12x4_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dsyrk_nt_l_12x4_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dsyrk_nt_u_12x4_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dsyrk_nt_u_12x4_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dger2k_nt_12x4_lib44cc(int kmax, double *alpha, double *A0, int sda0, double *B0, double *A1, int sda1, double *B1, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dger2k_nt_12x4_vs_lib44cc(int kmax, double *alpha, double *A0, int sda0, double *B0, double *A1, int sda1, double *B1, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dsyr2k_nt_l_12x4_lib44cc(int kmax, double *alpha, double *A0, int sda0, double *B0, double *A1, int sda1, double *B1, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dsyr2k_nt_l_12x4_vs_lib44cc(int kmax, double *alpha, double *A0, int sda0, double *B0, double *A1, int sda1, double *B1, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_12x4_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_rl_12x4_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_one_12x4_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_rl_one_12x4_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_12x4_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nt_ru_12x4_vs_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_12x4_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_ru_12x4_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_one_12x4_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_ru_one_12x4_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrsm_nt_ll_inv_12x4_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, int sde, double *inv_diag_E); -void kernel_dtrsm_nt_ll_inv_12x4_vs_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, int sde, double *inv_diag_E, int km, int kn); -void kernel_dtrsm_nt_rl_inv_12x4_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *dE); -void kernel_dtrsm_nt_rl_inv_12x4_vs_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *dE, int m1, int n1); -void kernel_dtrsm_nt_rl_inv_12x4_lib44ccc(int kmax, double *A, int sda, double *B, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE); -void kernel_dtrsm_nt_rl_inv_12x4_vs_lib44ccc(int kmax, double *A, int sda, double *B, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nt_rl_one_12x4_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E); -void kernel_dtrsm_nt_rl_one_12x4_vs_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, int m1, int n1); -void kernel_dtrsm_nt_ru_inv_12x4_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *dE); -void kernel_dtrsm_nt_ru_inv_12x4_vs_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *dE, int m1, int n1); -void kernel_dtrsm_nt_ru_one_12x4_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E); -void kernel_dtrsm_nt_ru_one_12x4_vs_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, int m1, int n1); -void kernel_dpotrf_nt_l_12x4_lib44cc(int kmax, double *A, int sda, double *B, double *C, int ldc, double *D, int ldd, double *dD); -void kernel_dpotrf_nt_l_12x4_vs_lib44cc(int kmax, double *A, int sda, double *B, double *C, int ldc, double *D, int ldd, double *dD, int m1, int n1); -// 4x12 -void kernel_dgemm_nt_4x12_lib44cc(int kmax, double *alpha, double *A, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_4x12_vs_lib44cc(int kmax, double *alpha, double *A, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_nt_4x12_p0_vs_lib44cc(int kmax, double *alpha, double *A, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1, double *A_p, double *B_p); -void kernel_dtrmm_nt_rl_4x12_tran_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nt_rl_4x12_tran_vs_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_one_4x12_tran_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nt_rl_one_4x12_tran_vs_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_4x12_tran_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nt_ru_4x12_tran_vs_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_one_4x12_tran_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nt_ru_one_4x12_tran_vs_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -// 8x8 -void kernel_dsyrk_nt_l_8x8_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dsyrk_nt_l_8x8_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dsyrk_nt_u_8x8_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dsyrk_nt_u_8x8_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dger2k_nt_8x8_lib44cc(int kmax, double *alpha, double *A0, int sda0, double *B0, int sdb0, double *A1, int sda1, double *B1, int sdb1, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dger2k_nt_8x8_vs_lib44cc(int kmax, double *alpha, double *A0, int sda0, double *B0, int sdb0, double *A1, int sda1, double *B1, int sdb1, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dsyr2k_nt_l_8x8_lib44cc(int kmax, double *alpha, double *A0, int sda0, double *B0, int sdb0, double *A1, int sda1, double *B1, int sdb1, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dsyr2k_nt_l_8x8_vs_lib44cc(int kmax, double *alpha, double *A0, int sda0, double *B0, int sdb0, double *A1, int sda1, double *B1, int sdb1, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dpotrf_nt_l_8x8_lib44cc(int kmax, double *A, int sda, double *B, int sdb, double *C, int ldc, double *D, int ldd, double *dD); -void kernel_dpotrf_nt_l_8x8_vs_lib44cc(int kmax, double *A, int sda, double *B, int sdb, double *C, int ldc, double *D, int ldd, double *dD, int m1, int n1); -// 8x4 -void kernel_dgemm_nt_8x4_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_8x4_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_nt_8x4_p0_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *A_p, double *B_p); -void kernel_dgemm_nt_8x4_p_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *A_p); -void kernel_dsyrk_nt_l_8x4_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dsyrk_nt_l_8x4_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dsyrk_nt_u_8x4_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dsyrk_nt_u_8x4_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dger2k_nt_8x4_lib44cc(int kmax, double *alpha, double *A0, int sda0, double *B0, double *A1, int sda1, double *B1, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dger2k_nt_8x4_vs_lib44cc(int kmax, double *alpha, double *A0, int sda0, double *B0, double *A1, int sda1, double *B1, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dsyr2k_nt_l_8x4_lib44cc(int kmax, double *alpha, double *A0, int sda0, double *B0, double *A1, int sda1, double *B1, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dsyr2k_nt_l_8x4_vs_lib44cc(int kmax, double *alpha, double *A0, int sda0, double *B0, double *A1, int sda1, double *B1, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_8x4_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_rl_8x4_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_one_8x4_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_rl_one_8x4_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_8x4_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nt_ru_8x4_vs_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_8x4_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_ru_8x4_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_one_8x4_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_ru_one_8x4_vs_lib44cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrsm_nt_ll_inv_8x4_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, int sde, double *inv_diag_E); -void kernel_dtrsm_nt_ll_inv_8x4_vs_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, int sde, double *inv_diag_E, int km, int kn); -void kernel_dtrsm_nt_rl_inv_8x4_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *dE); -void kernel_dtrsm_nt_rl_inv_8x4_vs_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *dE, int m1, int n1); -void kernel_dtrsm_nt_rl_inv_8x4_lib44ccc(int kmax, double *A, int sda, double *B, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE); -void kernel_dtrsm_nt_rl_inv_8x4_vs_lib44ccc(int kmax, double *A, int sda, double *B, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nt_rl_one_8x4_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E); -void kernel_dtrsm_nt_rl_one_8x4_vs_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, int m1, int n1); -void kernel_dtrsm_nt_ru_inv_8x4_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *dE); -void kernel_dtrsm_nt_ru_inv_8x4_vs_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *dE, int m1, int n1); -void kernel_dtrsm_nt_ru_one_8x4_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E); -void kernel_dtrsm_nt_ru_one_8x4_vs_lib44cc4(int kmax, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, int m1, int n1); -void kernel_dpotrf_nt_l_8x4_lib44cc(int kmax, double *A, int sda, double *B, double *C, int ldc, double *D, int ldd, double *dD); -void kernel_dpotrf_nt_l_8x4_vs_lib44cc(int kmax, double *A, int sda, double *B, double *C, int ldc, double *D, int ldd, double *dD, int m1, int n1); -// 4x8 -void kernel_dgemm_nt_4x8_lib44cc(int kmax, double *alpha, double *A, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_4x8_vs_lib44cc(int kmax, double *alpha, double *A, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_4x8_tran_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nt_rl_4x8_tran_vs_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_one_4x8_tran_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nt_rl_one_4x8_tran_vs_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_4x8_tran_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nt_ru_4x8_tran_vs_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_one_4x8_tran_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nt_ru_one_4x8_tran_vs_lib444c(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -// 4x4 -void kernel_dgemm_nt_4x4_lib44cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_4x4_vs_lib44cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dsyrk_nt_l_4x4_lib44cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dsyrk_nt_l_4x4_vs_lib44cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dsyrk_nt_u_4x4_lib44cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dsyrk_nt_u_4x4_vs_lib44cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dger2k_nt_4x4_lib44cc(int kmax, double *alpha, double *A0, double *B0, double *A1, double *B1, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dger2k_nt_4x4_vs_lib44cc(int kmax, double *alpha, double *A0, double *B0, double *A1, double *B1, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dsyr2k_nt_l_4x4_lib44cc(int kmax, double *alpha, double *A0, double *B0, double *A1, double *B1, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dsyr2k_nt_l_4x4_vs_lib44cc(int kmax, double *alpha, double *A0, double *B0, double *A1, double *B1, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_4x4_lib44cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_rl_4x4_vs_lib44cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_4x4_tran_lib444c(int kmax, double *alpha, double *A, double *B, double *beta, double *C, double *D, int ldd); -void kernel_dtrmm_nt_rl_4x4_tran_vs_lib444c(int kmax, double *alpha, double *A, double *B, double *beta, double *C, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_one_4x4_lib44cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_rl_one_4x4_vs_lib44cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_one_4x4_tran_lib444c(int kmax, double *alpha, double *A, double *B, double *beta, double *C, double *D, int ldd); -void kernel_dtrmm_nt_rl_one_4x4_tran_vs_lib444c(int kmax, double *alpha, double *A, double *B, double *beta, double *C, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_4x4_lib444c(int kmax, double *alpha, double *A, double *B, double *beta, double *C, double *D, int ldd); -void kernel_dtrmm_nt_ru_4x4_vs_lib444c(int kmax, double *alpha, double *A, double *B, double *beta, double *C, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_4x4_lib44cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_ru_4x4_vs_lib44cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_4x4_tran_lib444c(int kmax, double *alpha, double *A, double *B, double *beta, double *C, double *D, int ldd); -void kernel_dtrmm_nt_ru_4x4_tran_vs_lib444c(int kmax, double *alpha, double *A, double *B, double *beta, double *C, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_one_4x4_lib44cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_ru_one_4x4_vs_lib44cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_one_4x4_tran_lib444c(int kmax, double *alpha, double *A, double *B, double *beta, double *C, double *D, int ldd); -void kernel_dtrmm_nt_ru_one_4x4_tran_vs_lib444c(int kmax, double *alpha, double *A, double *B, double *beta, double *C, double *D, int ldd, int m1, int n1); -void kernel_dtrsm_nt_ll_inv_4x4_lib44cc4(int kmax, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *inv_diag_E); -void kernel_dtrsm_nt_ll_inv_4x4_vs_lib44cc4(int kmax, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *inv_diag_E, int km, int kn); -void kernel_dtrsm_nt_rl_inv_4x4_lib44cc4(int kmax, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *dE); -void kernel_dtrsm_nt_rl_inv_4x4_vs_lib44cc4(int kmax, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *dE, int m1, int n1); -void kernel_dtrsm_nt_rl_inv_4x4_lib44ccc(int kmax, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE); -void kernel_dtrsm_nt_rl_inv_4x4_vs_lib44ccc(int kmax, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nt_rl_one_4x4_lib44cc4(int kmax, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E); -void kernel_dtrsm_nt_rl_one_4x4_vs_lib44cc4(int kmax, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, int m1, int n1); -void kernel_dtrsm_nt_ru_inv_4x4_lib44cc4(int kmax, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *dE); -void kernel_dtrsm_nt_ru_inv_4x4_vs_lib44cc4(int kmax, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *dE, int m1, int n1); -void kernel_dtrsm_nt_ru_one_4x4_lib44cc4(int kmax, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E); -void kernel_dtrsm_nt_ru_one_4x4_vs_lib44cc4(int kmax, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, double *E, int m1, int n1); -void kernel_dpotrf_nt_l_4x4_lib44cc(int kmax, double *A, double *B, double *C, int ldc, double *D, int ldd, double *dD); -void kernel_dpotrf_nt_l_4x4_vs_lib44cc(int kmax, double *A, double *B, double *C, int ldc, double *D, int ldd, double *dD, int m1, int n1); -// 4x2 -void kernel_dgemm_nt_4x2_lib44cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd); - -// A panel-major bs=4; B, C, D column-major -// 12x4 -void kernel_dgemm_nn_12x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nn_12x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_nt_12x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_12x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dsyrk_nt_l_12x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dsyrk_nt_l_12x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dger2k_nt_12x4_lib4ccc(int kmax, double *alpha, double *A0, int sda0, double *B0, int ldb0, double *A1, int sda1, double *B1, int ldb1, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dger2k_nt_12x4_vs_lib4ccc(int kmax, double *alpha, double *A0, int sda0, double *B0, int ldb0, double *A1, int sda1, double *B1, int ldb1, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_rl_12x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nn_rl_12x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_rl_one_12x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nn_rl_one_12x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_ru_12x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nn_ru_12x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_ru_one_12x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nn_ru_one_12x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_12x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_rl_12x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_one_12x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_rl_one_12x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_12x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_ru_12x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_one_12x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_ru_one_12x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrsm_nn_ll_inv_12x4_lib4ccc4(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int sde, double *inv_diag_E); -void kernel_dtrsm_nn_ll_inv_12x4_vs_lib4ccc4(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int sde, double *inv_diag_E, int km, int kn); -void kernel_dtrsm_nn_ll_one_12x4_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde); -void kernel_dtrsm_nn_ll_one_12x4_vs_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nn_rl_inv_12x4_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE); -void kernel_dtrsm_nn_rl_inv_12x4_vs_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nn_rl_one_12x4_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde); -void kernel_dtrsm_nn_rl_one_12x4_vs_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nt_rl_inv_12x4_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE); -void kernel_dtrsm_nt_rl_inv_12x4_vs_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nt_rl_one_12x4_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde); -void kernel_dtrsm_nt_rl_one_12x4_vs_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nn_ru_inv_12x4_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE); -void kernel_dtrsm_nn_ru_inv_12x4_vs_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nn_ru_one_12x4_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde); -void kernel_dtrsm_nn_ru_one_12x4_vs_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nt_ru_inv_12x4_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE); -void kernel_dtrsm_nt_ru_inv_12x4_vs_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nt_ru_one_12x4_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde); -void kernel_dtrsm_nt_ru_one_12x4_vs_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, int m1, int n1); -void kernel_dgetrf_nn_l_12x4_lib4ccc(int kmax, double *A, int sda, double *B, int ldb, double *C, int ldc, double *D, int ldd, double *diag); -void kernel_dgetrf_nn_l_12x4_vs_lib4ccc(int kmax, double *A, int sda, double *B, int ldb, double *C, int ldc, double *D, int ldd, double *diag, int m1, int n1); -void kernel_dgetrf_nn_m_12x4_lib4ccc(int kmax, double *A, int sda, double *B, int ldb, double *C, int ldc, double *D, int ldd, double *diag); -void kernel_dgetrf_nn_m_12x4_vs_lib4ccc(int kmax, double *A, int sda, double *B, int ldb, double *C, int ldc, double *D, int ldd, double *diag, int m1, int n1); -void kernel_dgetrf_nn_r_12x4_lib4ccc(int kmax, double *A, int sda, double *B, int ldb, double *C, int ldc, double *D, int ldd, double *diag); -void kernel_dgetrf_nn_r_12x4_vs_lib4ccc(int kmax, double *A, int sda, double *B, int ldb, double *C, int ldc, double *D, int ldd, double *diag, int m1, int n1); -// 4x12 -void kernel_dgemm_nn_4x12_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nn_4x12_vs_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_nt_4x12_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_4x12_vs_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_rl_4x12_tran_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nn_rl_4x12_tran_vs_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_rl_one_4x12_tran_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nn_rl_one_4x12_tran_vs_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_ru_4x12_tran_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nn_ru_4x12_tran_vs_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_ru_one_4x12_tran_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nn_ru_one_4x12_tran_vs_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_4x12_tran_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nt_rl_4x12_tran_vs_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_one_4x12_tran_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nt_rl_one_4x12_tran_vs_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_4x12_tran_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nt_ru_4x12_tran_vs_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_one_4x12_tran_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nt_ru_one_4x12_tran_vs_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -// 8x4 -void kernel_dgemm_nn_8x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nn_8x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_nt_8x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_8x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dsyrk_nt_l_8x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dsyrk_nt_l_8x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dger2k_nt_8x4_lib4ccc(int kmax, double *alpha, double *A0, int sda0, double *B0, int ldb0, double *A1, int sda1, double *B1, int ldb1, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dger2k_nt_8x4_vs_lib4ccc(int kmax, double *alpha, double *A0, int sda0, double *B0, int ldb0, double *A1, int sda1, double *B1, int ldb1, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_rl_8x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nn_rl_8x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_rl_one_8x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nn_rl_one_8x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_ru_8x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nn_ru_8x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_ru_one_8x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nn_ru_one_8x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_8x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_rl_8x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_one_8x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_rl_one_8x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_8x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_ru_8x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_one_8x4_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_ru_one_8x4_vs_lib4ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrsm_nn_ll_inv_8x4_lib4ccc4(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int sde, double *inv_diag_E); -void kernel_dtrsm_nn_ll_inv_8x4_vs_lib4ccc4(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int sde, double *inv_diag_E, int km, int kn); -void kernel_dtrsm_nn_ll_one_8x4_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde); -void kernel_dtrsm_nn_ll_one_8x4_vs_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nn_rl_inv_8x4_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE); -void kernel_dtrsm_nn_rl_inv_8x4_vs_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nn_rl_one_8x4_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde); -void kernel_dtrsm_nn_rl_one_8x4_vs_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nt_rl_inv_8x4_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE); -void kernel_dtrsm_nt_rl_inv_8x4_vs_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nt_rl_one_8x4_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde); -void kernel_dtrsm_nt_rl_one_8x4_vs_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nn_ru_inv_8x4_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE); -void kernel_dtrsm_nn_ru_inv_8x4_vs_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nn_ru_one_8x4_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde); -void kernel_dtrsm_nn_ru_one_8x4_vs_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nt_ru_inv_8x4_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE); -void kernel_dtrsm_nt_ru_inv_8x4_vs_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nt_ru_one_8x4_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde); -void kernel_dtrsm_nt_ru_one_8x4_vs_lib4cccc(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, int m1, int n1); -void kernel_dgetrf_nn_l_8x4_lib4ccc(int kmax, double *A, int sda, double *B, int ldb, double *C, int ldc, double *D, int ldd, double *diag); -void kernel_dgetrf_nn_l_8x4_vs_lib4ccc(int kmax, double *A, int sda, double *B, int ldb, double *C, int ldc, double *D, int ldd, double *diag, int m1, int n1); -void kernel_dgetrf_nn_r_8x4_lib4ccc(int kmax, double *A, int sda, double *B, int ldb, double *C, int ldc, double *D, int ldd, double *diag); -void kernel_dgetrf_nn_r_8x4_vs_lib4ccc(int kmax, double *A, int sda, double *B, int ldb, double *C, int ldc, double *D, int ldd, double *diag, int m1, int n1); -// 4x8 -void kernel_dgemm_nn_4x8_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nn_4x8_vs_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_nt_4x8_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_4x8_vs_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_rl_4x8_tran_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nn_rl_4x8_tran_vs_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_rl_one_4x8_tran_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nn_rl_one_4x8_tran_vs_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_ru_4x8_tran_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nn_ru_4x8_tran_vs_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_ru_one_4x8_tran_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nn_ru_one_4x8_tran_vs_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_4x8_tran_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nt_rl_4x8_tran_vs_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_one_4x8_tran_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nt_rl_one_4x8_tran_vs_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_4x8_tran_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nt_ru_4x8_tran_vs_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_one_4x8_tran_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd); -void kernel_dtrmm_nt_ru_one_4x8_tran_vs_lib4c4c(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int ldd, int m1, int n1); -// 4x4 -void kernel_dgemm_nn_4x4_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nn_4x4_vs_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_nt_4x4_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_4x4_vs_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dsyrk_nt_l_4x4_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dsyrk_nt_l_4x4_vs_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dger2k_nt_4x4_lib4ccc(int kmax, double *alpha, double *A0, double *B0, int ldb0, double *A1, double *B1, int ldb1, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dger2k_nt_4x4_vs_lib4ccc(int kmax, double *alpha, double *A0, double *B0, int ldb0, double *A1, double *B1, int ldb1, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_rl_4x4_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nn_rl_4x4_vs_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_rl_4x4_tran_lib4c4c(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, double *D, int ldd); -void kernel_dtrmm_nn_rl_4x4_tran_vs_lib4c4c(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_rl_one_4x4_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nn_rl_one_4x4_vs_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_rl_one_4x4_tran_lib4c4c(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, double *D, int ldd); -void kernel_dtrmm_nn_rl_one_4x4_tran_vs_lib4c4c(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_ru_4x4_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nn_ru_4x4_vs_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_ru_4x4_tran_lib4c4c(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, double *D, int ldd); -void kernel_dtrmm_nn_ru_4x4_tran_vs_lib4c4c(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_ru_one_4x4_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nn_ru_one_4x4_vs_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nn_ru_one_4x4_tran_lib4c4c(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, double *D, int ldd); -void kernel_dtrmm_nn_ru_one_4x4_tran_vs_lib4c4c(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_4x4_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_rl_4x4_vs_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_4x4_tran_lib4c4c(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, double *D, int ldd); -void kernel_dtrmm_nt_rl_4x4_tran_vs_lib4c4c(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_one_4x4_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_rl_one_4x4_vs_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_rl_one_4x4_tran_lib4c4c(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, double *D, int ldd); -void kernel_dtrmm_nt_rl_one_4x4_tran_vs_lib4c4c(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_4x4_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_ru_4x4_vs_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_4x4_tran_lib4c4c(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, double *D, int ldd); -void kernel_dtrmm_nt_ru_4x4_tran_vs_lib4c4c(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_one_4x4_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dtrmm_nt_ru_one_4x4_vs_lib4ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dtrmm_nt_ru_one_4x4_tran_lib4c4c(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, double *D, int ldd); -void kernel_dtrmm_nt_ru_one_4x4_tran_vs_lib4c4c(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, double *D, int ldd, int m1, int n1); -void kernel_dtrsm_nn_ll_inv_4x4_lib4ccc4(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *inv_diag_E); -void kernel_dtrsm_nn_ll_inv_4x4_vs_lib4ccc4(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, double *inv_diag_E, int km, int kn); -void kernel_dtrsm_nn_ll_one_4x4_lib4cccc(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde); -void kernel_dtrsm_nn_ll_one_4x4_vs_lib4cccc(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nn_rl_inv_4x4_lib4cccc(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE); -void kernel_dtrsm_nn_rl_inv_4x4_vs_lib4cccc(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nn_rl_one_4x4_lib4cccc(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde); -void kernel_dtrsm_nn_rl_one_4x4_vs_lib4cccc(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nt_rl_inv_4x4_lib4cccc(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE); -void kernel_dtrsm_nt_rl_inv_4x4_vs_lib4cccc(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nt_rl_one_4x4_lib4cccc(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde); -void kernel_dtrsm_nt_rl_one_4x4_vs_lib4cccc(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nn_ru_inv_4x4_lib4cccc(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE); -void kernel_dtrsm_nn_ru_inv_4x4_vs_lib4cccc(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nn_ru_one_4x4_lib4cccc(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde); -void kernel_dtrsm_nn_ru_one_4x4_vs_lib4cccc(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nt_ru_inv_4x4_lib4cccc(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE); -void kernel_dtrsm_nt_ru_inv_4x4_vs_lib4cccc(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nt_ru_one_4x4_lib4cccc(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde); -void kernel_dtrsm_nt_ru_one_4x4_vs_lib4cccc(int kmax, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, double *E, int lde, int m1, int n1); -void kernel_dgetrf_nn_4x4_lib4ccc(int kmax, double *A, double *B, int ldb, double *C, int ldc, double *D, int ldd, double *diag); -void kernel_dgetrf_nn_4x4_vs_lib4ccc(int kmax, double *A, double *B, int ldb, double *C, int ldc, double *D, int ldd, double *diag, int m1, int n1); - -// B panel-major bs=4; A, C, D column-major -// 12x4 -void kernel_dgemm_nt_12x4_libc4cc(int kmax, double *alpha, double *A, int lda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_12x4_vs_libc4cc(int kmax, double *alpha, double *A, int lda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_tt_12x4_libc4cc(int kmax, double *alpha, double *A, int lda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_tt_12x4_vs_libc4cc(int kmax, double *alpha, double *A, int lda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -// 4x12 -void kernel_dgemm_nt_4x12_libc4cc(int kmax, double *alpha, double *A, int lda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_4x12_vs_libc4cc(int kmax, double *alpha, double *A, int lda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_tt_4x12_libc4cc(int kmax, double *alpha, double *A, int lda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_tt_4x12_vs_libc4cc(int kmax, double *alpha, double *A, int lda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -// 8x4 -void kernel_dgemm_nt_8x4_libc4cc(int kmax, double *alpha, double *A, int lda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_8x4_vs_libc4cc(int kmax, double *alpha, double *A, int lda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_tt_8x4_libc4cc(int kmax, double *alpha, double *A, int lda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_tt_8x4_vs_libc4cc(int kmax, double *alpha, double *A, int lda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -// 4x8 -void kernel_dgemm_nt_4x8_libc4cc(int kmax, double *alpha, double *A, int lda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_4x8_vs_libc4cc(int kmax, double *alpha, double *A, int lda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_tt_4x8_libc4cc(int kmax, double *alpha, double *A, int lda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_tt_4x8_vs_libc4cc(int kmax, double *alpha, double *A, int lda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -// 4x4 -void kernel_dgemm_nt_4x4_libc4cc(int kmax, double *alpha, double *A, int lda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_4x4_vs_libc4cc(int kmax, double *alpha, double *A, int lda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_tt_4x4_libc4cc(int kmax, double *alpha, double *A, int lda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_tt_4x4_vs_libc4cc(int kmax, double *alpha, double *A, int lda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); - -// A, C, D panel-major; B, E column-major -// TODO merge with above -// 12x4 -void kernel_dtrsm_nn_rl_inv_12x4_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, double *dE); -void kernel_dtrsm_nn_rl_inv_12x4_vs_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nn_rl_one_12x4_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde); -void kernel_dtrsm_nn_rl_one_12x4_vs_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nn_ru_inv_12x4_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, double *dE); -void kernel_dtrsm_nn_ru_inv_12x4_vs_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nn_ru_one_12x4_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde); -void kernel_dtrsm_nn_ru_one_12x4_vs_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nt_rl_inv_12x4_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, double *dE); -void kernel_dtrsm_nt_rl_inv_12x4_vs_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nt_rl_one_12x4_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde); -void kernel_dtrsm_nt_rl_one_12x4_vs_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nt_ru_inv_12x4_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, double *dE); -void kernel_dtrsm_nt_ru_inv_12x4_vs_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nt_ru_one_12x4_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde); -void kernel_dtrsm_nt_ru_one_12x4_vs_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, int m1, int n1); -// 8x4 -void kernel_dtrsm_nn_rl_inv_8x4_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, double *dE); -void kernel_dtrsm_nn_rl_inv_8x4_vs_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nn_rl_one_8x4_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde); -void kernel_dtrsm_nn_rl_one_8x4_vs_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nn_ru_inv_8x4_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, double *dE); -void kernel_dtrsm_nn_ru_inv_8x4_vs_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nn_ru_one_8x4_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde); -void kernel_dtrsm_nn_ru_one_8x4_vs_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nt_rl_inv_8x4_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, double *dE); -void kernel_dtrsm_nt_rl_inv_8x4_vs_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nt_rl_one_8x4_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde); -void kernel_dtrsm_nt_rl_one_8x4_vs_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nt_ru_inv_8x4_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, double *dE); -void kernel_dtrsm_nt_ru_inv_8x4_vs_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nt_ru_one_8x4_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde); -void kernel_dtrsm_nt_ru_one_8x4_vs_lib4c44c(int kmax, double *A, int sda, double *B, int ldb, double *beta, double *C, int sdc, double *D, int sdd, double *E, int lde, int m1, int n1); -// 4x4 -void kernel_dtrsm_nn_rl_inv_4x4_lib4c44c(int kmax, double *A, double *B, int ldb, double *beta, double *C, double *D, double *E, int lde, double *dE); -void kernel_dtrsm_nn_rl_inv_4x4_vs_lib4c44c(int kmax, double *A, double *B, int ldb, double *beta, double *C, double *D, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nn_rl_one_4x4_lib4c44c(int kmax, double *A, double *B, int ldb, double *beta, double *C, double *D, double *E, int lde); -void kernel_dtrsm_nn_rl_one_4x4_vs_lib4c44c(int kmax, double *A, double *B, int ldb, double *beta, double *C, double *D, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nn_ru_inv_4x4_lib4c44c(int kmax, double *A, double *B, int ldb, double *beta, double *C, double *D, double *E, int lde, double *dE); -void kernel_dtrsm_nn_ru_inv_4x4_vs_lib4c44c(int kmax, double *A, double *B, int ldb, double *beta, double *C, double *D, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nn_ru_one_4x4_lib4c44c(int kmax, double *A, double *B, int ldb, double *beta, double *C, double *D, double *E, int lde); -void kernel_dtrsm_nn_ru_one_4x4_vs_lib4c44c(int kmax, double *A, double *B, int ldb, double *beta, double *C, double *D, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nt_rl_inv_4x4_lib4c44c(int kmax, double *A, double *B, int ldb, double *beta, double *C, double *D, double *E, int lde, double *dE); -void kernel_dtrsm_nt_rl_inv_4x4_vs_lib4c44c(int kmax, double *A, double *B, int ldb, double *beta, double *C, double *D, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nt_rl_one_4x4_lib4c44c(int kmax, double *A, double *B, int ldb, double *beta, double *C, double *D, double *E, int lde); -void kernel_dtrsm_nt_rl_one_4x4_vs_lib4c44c(int kmax, double *A, double *B, int ldb, double *beta, double *C, double *D, double *E, int lde, int m1, int n1); -void kernel_dtrsm_nt_ru_inv_4x4_lib4c44c(int kmax, double *A, double *B, int ldb, double *beta, double *C, double *D, double *E, int lde, double *dE); -void kernel_dtrsm_nt_ru_inv_4x4_vs_lib4c44c(int kmax, double *A, double *B, int ldb, double *beta, double *C, double *D, double *E, int lde, double *dE, int m1, int n1); -void kernel_dtrsm_nt_ru_one_4x4_lib4c44c(int kmax, double *A, double *B, int ldb, double *beta, double *C, double *D, double *E, int lde); -void kernel_dtrsm_nt_ru_one_4x4_vs_lib4c44c(int kmax, double *A, double *B, int ldb, double *beta, double *C, double *D, double *E, int lde, int m1, int n1); - -// A, B, C, D column-major -// 12x4 -void kernel_dgemm_nn_12x4_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nn_12x4_vs_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_nt_12x4_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_12x4_vs_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_tt_12x4_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_tt_12x4_vs_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -// 4x12 -void kernel_dgemm_nn_4x12_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nn_4x12_vs_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_nt_4x12_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_4x12_vs_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_tt_4x12_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_tt_4x12_vs_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -// 8x4 -void kernel_dgemm_nn_8x4_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nn_8x4_vs_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_nt_8x4_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_8x4_vs_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_tt_8x4_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_tt_8x4_vs_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -// 4x8 -void kernel_dgemm_nn_4x8_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nn_4x8_vs_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_nt_4x8_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_4x8_vs_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_tt_4x8_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_tt_4x8_vs_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -// 4x4 -void kernel_dgemm_nn_4x4_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nn_4x4_vs_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_nt_4x4_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_4x4_vs_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_tt_4x4_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_tt_4x4_vs_libcccc(int kmax, double *alpha, double *A, int lda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); - -// A column-major -// 12 -void kernel_dgetrf_pivot_12_lib(int m, double *pA, int lda, double *inv_diag_A, int* ipiv); -void kernel_dgetrf_pivot_12_vs_lib(int m, double *pA, int lda, double *inv_diag_A, int* ipiv, int n); -// 8 -void kernel_dgetrf_pivot_8_lib(int m, double *pA, int lda, double *inv_diag_A, int* ipiv); -void kernel_dgetrf_pivot_8_vs_lib(int m, double *pA, int lda, double *inv_diag_A, int* ipiv, int n); -// 4 -void kernel_dgetrf_pivot_4_lib(int m, double *pA, int lda, double *inv_diag_A, int* ipiv); -void kernel_dgetrf_pivot_4_vs_lib(int m, double *pA, int lda, double *inv_diag_A, int* ipiv, int n); - -// vector -void kernel_ddot_11_lib(int n, double *x, double *y, double *res); -void kernel_daxpy_11_lib(int n, double *alpha, double *x, double *y); -void kernel_drowsw_lib(int kmax, double *pA, int lda, double *pC, int ldc); - -//#endif // BLAS_API - - - -// larger kernels -// 12 -void kernel_dgemm_nt_12xn_p0_lib44cc(int n, int k, double *alpha, double *A, int sda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, double *A_p, double *B_p); -void kernel_dgemm_nt_12xn_pl_lib44cc(int n, int k, double *alpha, double *A, int sda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, double *A_p, double *B_p); -void kernel_dgemm_nt_mx12_p0_lib44cc(int m, int k, double *alpha, double *A, int sda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, double *A_p, double *B_p); -// 8 -void kernel_dgemm_nt_8xn_p0_lib44cc(int n, int k, double *alpha, double *A, int sda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, double *A_p, double *B_p); - - - -// A, B panel-major bs=8; C, D column-major -// 24x8 -void kernel_dgemm_nt_24x8_lib88cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_24x8_vs_lib88cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -// 16x8 -void kernel_dgemm_nt_16x8_lib88cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_16x8_vs_lib88cc(int kmax, double *alpha, double *A, int sda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -// 8x8 -void kernel_dgemm_nt_8x8_lib88cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_8x8_vs_lib88cc(int kmax, double *alpha, double *A, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); - -// A, panel-major bs=8; B, C, D column-major -// 24x8 -void kernel_dgemm_nt_24x8_lib8ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_24x8_vs_lib8ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_nn_24x8_lib8ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nn_24x8_vs_lib8ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -// 16x8 -void kernel_dgemm_nt_16x8_lib8ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_16x8_vs_lib8ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_nn_16x8_lib8ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nn_16x8_vs_lib8ccc(int kmax, double *alpha, double *A, int sda, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -// 8x8 -void kernel_dgemm_nt_8x8_lib8ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_8x8_vs_lib8ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_nn_8x8_lib8ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nn_8x8_vs_lib8ccc(int kmax, double *alpha, double *A, double *B, int ldb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); - -// B, panel-major bs=8; A, C, D column-major -// 8x24 -void kernel_dgemm_nt_8x24_libc8cc(int kmax, double *alpha, double *A, int lda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_8x24_vs_libc8cc(int kmax, double *alpha, double *A, int lda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_tt_8x24_libc8cc(int kmax, double *alpha, double *A, int lda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_tt_8x24_vs_libc8cc(int kmax, double *alpha, double *A, int lda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -// 8x16 -void kernel_dgemm_nt_8x16_libc8cc(int kmax, double *alpha, double *A, int lda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_8x16_vs_libc8cc(int kmax, double *alpha, double *A, int lda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_tt_8x16_libc8cc(int kmax, double *alpha, double *A, int lda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_tt_8x16_vs_libc8cc(int kmax, double *alpha, double *A, int lda, double *B, int sdb, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -// 8x8 -void kernel_dgemm_nt_8x8_libc8cc(int kmax, double *alpha, double *A, int lda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_nt_8x8_vs_libc8cc(int kmax, double *alpha, double *A, int lda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); -void kernel_dgemm_tt_8x8_libc8cc(int kmax, double *alpha, double *A, int lda, double *B, double *beta, double *C, int ldc, double *D, int ldd); -void kernel_dgemm_tt_8x8_vs_libc8cc(int kmax, double *alpha, double *A, int lda, double *B, double *beta, double *C, int ldc, double *D, int ldd, int m1, int n1); - - -// level 2 BLAS -void kernel_dgemv_n_4_libc(int kmax, double *alpha, double *A, int lda, double *x, double *z); -void kernel_dgemv_n_4_vs_libc(int kmax, double *alpha, double *A, int lda, double *x, double *z, int km); -void kernel_dgemv_t_4_libc(int kmax, double *alpha, double *A, int lda, double *x, double *beta, double *y, double *z); -void kernel_dgemv_t_4_vs_libc(int kmax, double *alpha, double *A, int lda, double *x, double *beta, double *y, double *z, int km); -void kernel_dsymv_l_4_libc(int kmax, double *alpha, double *A, int lda, double *x, double *z); -void kernel_dsymv_l_4_vs_libc(int kmax, double *alpha, double *A, int lda, double *x, double *z, int km); -void kernel_dsymv_u_4_libc(int kmax, double *alpha, double *A, int lda, double *x, double *z); -void kernel_dsymv_u_4_vs_libc(int kmax, double *alpha, double *A, int lda, double *x, double *z, int km); -void kernel_dger_4_libc(int kmax, double *alpha, double *x, double *y, double *C, int ldc, double *D, int ldd); -void kernel_dger_4_vs_libc(int kmax, double *alpha, double *x, double *y, double *C, int ldc, double *D, int ldd, int km); - - - -// aux -void kernel_dvecld_inc1(int kmax, double *x); -void kernel_dveccp_inc1(int kmax, double *x, double *y); - -//void kernel_dgetr_nt_8_p0_lib(int kmax, double *A, int lda, double *C, int ldc, double *Ap, double *Bp); -//void kernel_dgetr_nt_8_lib(int kmax, double *A, int lda, double *C, int ldc); -//void kernel_dgetr_nt_4_lib(int kmax, double *A, int lda, double *C, int ldc); -void kernel_dgetr_tn_8_p0_lib(int kmax, double *A, int lda, double *C, int ldc, double *Ap, double *Bp); -void kernel_dgetr_tn_8_lib(int kmax, double *A, int lda, double *C, int ldc); -void kernel_dgetr_tn_4_lib(int kmax, double *A, int lda, double *C, int ldc); -void kernel_dgetr_tn_4_vs_lib(int kmax, double *A, int lda, double *C, int ldc, int m1); - - -// building blocks for blocked algorithms -// -void blasfeo_hp_dgemm_nt_m2(int m, int n, int k, double alpha, double *pA, int sda, double *pB, int sdb, double beta, double *C, int ldc, double *D, int ldd); -void blasfeo_hp_dgemm_nt_n2(int m, int n, int k, double alpha, double *pA, int sda, double *pB, int sdb, double beta, double *C, int ldc, double *D, int ldd); -// -void kernel_dpack_buffer_fn(int m, int n, double *A, int lda, double *pA, int sda); -void kernel_dpack_buffer_ft(int m, int n, double *A, int lda, double *pA, int sda); -void kernel_dpack_buffer_ln(int m, double *A, int lda, double *pA, int sda); -void kernel_dpack_buffer_lt(int m, double *A, int lda, double *pA, int sda); -void kernel_dpack_buffer_ut(int m, double *A, int lda, double *pA, int sda); - - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_D_KERNEL_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_i_aux_ext_dep.h b/third_party/acados/include/blasfeo/include/blasfeo_i_aux_ext_dep.h deleted file mode 100644 index 74c3fb5c0a..0000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_i_aux_ext_dep.h +++ /dev/null @@ -1,69 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_I_AUX_EXT_DEP_H_ -#define BLASFEO_I_AUX_EXT_DEP_H_ - - - -#include "blasfeo_target.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -#ifdef EXT_DEP - -// i_aux_extern_depend_lib -void int_zeros(int **pA, int row, int col); -void int_zeros_align(int **pA, int row, int col); -void int_free(int *pA); -void int_free_align(int *pA); -void int_print_mat(int row, int col, int *A, int lda); -int int_print_to_string_mat(char **buf_out, int row, int col, int *A, int lda); - -#endif // EXT_DEP - - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_I_AUX_EXT_DEP_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_m_aux.h b/third_party/acados/include/blasfeo/include/blasfeo_m_aux.h deleted file mode 100644 index 6248853e29..0000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_m_aux.h +++ /dev/null @@ -1,57 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_M_AUX_H_ -#define BLASFEO_M_AUX_H_ - -#include "blasfeo_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - - - -void blasfeo_cvt_d2s_vec(int m, struct blasfeo_dvec *vd, int vdi, struct blasfeo_svec *vs, int vsi); -void blasfeo_cvt_s2d_vec(int m, struct blasfeo_svec *vs, int vsi, struct blasfeo_dvec *vd, int vdi); -void blasfeo_cvt_d2s_mat(int m, int n, struct blasfeo_dmat *Md, int mid, int nid, struct blasfeo_smat *Ms, int mis, int nis); -void blasfeo_cvt_s2d_mat(int m, int n, struct blasfeo_smat *Ms, int mis, int nis, struct blasfeo_dmat *Md, int mid, int nid); - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_M_AUX_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_memory.h b/third_party/acados/include/blasfeo/include/blasfeo_memory.h deleted file mode 100644 index da4e7fa090..0000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_memory.h +++ /dev/null @@ -1,62 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2020 by Gianluca Frison. * -* All rights reserved. * -* * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - -#ifndef BLASFEO_MEMORY_H_ -#define BLASFEO_MEMORY_H_ - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -int blasfeo_is_init(); -// -void blasfeo_init(); -// -void blasfeo_quit(); -// -void *blasfeo_get_buffer(); - - - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_MEMORY_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_naming.h b/third_party/acados/include/blasfeo/include/blasfeo_naming.h deleted file mode 100644 index c289443b17..0000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_naming.h +++ /dev/null @@ -1,77 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - -/* - * ----------- Naming conventions - * - * (precision)(data) - * - * 1) d(double) - * s(single) - * - * 2) ge(general) - * tr(triangular) - * vec(vector) - * row(row) - * col(column) - * dia(diagonal) - * - * 3) se(set) - * cp(copy) - * sc(scale) - * ad(add) - * tr(transpose) - * in(insert) - * ex(extract) - * pe(premute) - * sw(swap) - * - * f(factorization) - * - * lqf(LQ factorization) - * qrf (factorization) - * trf (LU factorization using partial pivoting with row interchanges.) - * - * 4) _l(lower) / _u(upper) - * _lib8 (hp implementation, 8 rows kernel) - * _lib4 (hp implementation, 4 rows kernel) - * _lib0 (hp interface with reference implentation) - * _lib (reference implementation) - * _libref (reference implementation with dedicated namespace) - * - * 5) _sp(sparse) - * _exp(exponential format) - */ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_processor_features.h b/third_party/acados/include/blasfeo/include/blasfeo_processor_features.h deleted file mode 100644 index 67a0a4da04..0000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_processor_features.h +++ /dev/null @@ -1,88 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Ian McInerney * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_PROCESSOR_FEATURES_H_ -#define BLASFEO_PROCESSOR_FEATURES_H_ - -/** - * Flags to indicate the different processor features - */ -//enum -//{ -// // x86-64 CPU features -// BLASFEO_PROCESSOR_FEATURE_AVX = 0x0001, /// AVX instruction set -// BLASFEO_PROCESSOR_FEATURE_AVX2 = 0x0002, /// AVX2 instruction set -// BLASFEO_PROCESSOR_FEATURE_FMA = 0x0004, /// FMA instruction set -// BLASFEO_PROCESSOR_FEATURE_SSE3 = 0x0008, /// SSE3 instruction set -// -// // ARM CPU features -// BLASFEO_PROCESSOR_FEATURE_VFPv3 = 0x0100, /// VFPv3 instruction set -// BLASFEO_PROCESSOR_FEATURE_NEON = 0x0100, /// NEON instruction set -// BLASFEO_PROCESSOR_FEATURE_VFPv4 = 0x0100, /// VFPv4 instruction set -// BLASFEO_PROCESSOR_FEATURE_NEONv2 = 0x0100, /// NEONv2 instruction set -//} BLASFEO_PROCESSOR_FEATURES; - -/** - * Test the features that this processor provides against what the library was compiled with. - * - * @param features - Pointer to an integer to store the supported feature set (using the flags in the BLASFEO_PROCESSOR_FEATURES enum) - * @return 0 if current processor doesn't support all features required for this library, 1 otherwise - */ -int blasfeo_processor_cpu_features( int* features ); - -/** - * Test the features that this processor provides against what the library was compiled with. - * - * @param features - Pointer to an integer to store the supported feature set (using the flags in the BLASFEO_PROCESSOR_FEATURES enum) - * @return 0 if current processor doesn't support all features required for this library, 1 otherwise - */ -void blasfeo_processor_library_features( int* features ); - -/** - * Create a string listing the features the current processor supports. - * - * @param features - Flags from the BLASFEO_PROCESSOR_FEATURES enum indicating the features supported - * @param featureString - Character array to store the feature string in - */ -void blasfeo_processor_feature_string( int features, char* featureString ); - -/** - * Get a string listing the processor features that this library version needs to run. - * - * @param featureString - Character array to store the feature string in - */ -void blasfeo_processor_library_string( char* featureString ); - -#endif // BLASFEO_PROCESSOR_FEATURES_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_s_aux.h b/third_party/acados/include/blasfeo/include/blasfeo_s_aux.h deleted file mode 100644 index f43f5e83ce..0000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_s_aux.h +++ /dev/null @@ -1,168 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_S_AUX_H_ -#define BLASFEO_S_AUX_H_ - - - -#include - -#include "blasfeo_s_aux_old.h" -#include "blasfeo_common.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - -/************************************************ -* d_aux_lib.c -************************************************/ - -// returns the memory size (in bytes) needed for a smat -size_t blasfeo_memsize_smat(int m, int n); -size_t blasfeo_memsize_smat_ps(int ps, int m, int n); -// returns the memory size (in bytes) needed for the diagonal of a smat -size_t blasfeo_memsize_diag_smat(int m, int n); -// returns the memory size (in bytes) needed for a svec -size_t blasfeo_memsize_svec(int m); -// create a strmat for a matrix of size m*n by using memory passed by a pointer (pointer is not updated) -void blasfeo_create_smat(int m, int n, struct blasfeo_smat *sA, void *memory); -void blasfeo_create_smat_ps(int ps, int m, int n, struct blasfeo_smat *sA, void *memory); -// create a strvec for a vector of size m by using memory passed by a pointer (pointer is not updated) -void blasfeo_create_svec(int m, struct blasfeo_svec *sA, void *memory); -void blasfeo_pack_smat(int m, int n, float *A, int lda, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_pack_l_smat(int m, int n, float *A, int lda, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_pack_u_smat(int m, int n, float *A, int lda, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_pack_tran_smat(int m, int n, float *A, int lda, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_pack_svec(int m, float *x, int xi, struct blasfeo_svec *sa, int ai); -void blasfeo_unpack_smat(int m, int n, struct blasfeo_smat *sA, int ai, int aj, float *A, int lda); -void blasfeo_unpack_tran_smat(int m, int n, struct blasfeo_smat *sA, int ai, int aj, float *A, int lda); -void blasfeo_unpack_svec(int m, struct blasfeo_svec *sa, int ai, float *x, int xi); -//void s_cast_mat2strmat(float *A, struct blasfeo_smat *sA); -//void s_cast_diag_mat2strmat(float *dA, struct blasfeo_smat *sA); -//void s_cast_vec2vecmat(float *a, struct blasfeo_svec *sa); - -// ge -void blasfeo_sgese(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_sgecpsc(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -void blasfeo_sgecp(int m, int n, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -void blasfeo_sgesc(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_sgein1(float a, struct blasfeo_smat *sA, int ai, int aj); -float blasfeo_sgeex1(struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_sgead(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -void blasfeo_sgetr(int m, int n, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -// tr -void blasfeo_strcp_l(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -void blasfeo_strtr_l(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -void blasfeo_strtr_u(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -// dia -void blasfeo_sdiare(int kmax, float alpha, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_sdiaex(int kmax, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi); -void blasfeo_sdiain(int kmax, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_sdiain_sp(int kmax, float alpha, struct blasfeo_svec *sx, int xi, int *idx, struct blasfeo_smat *sD, int di, int dj); -void blasfeo_sdiaex_sp(int kmax, float alpha, int *idx, struct blasfeo_smat *sD, int di, int dj, struct blasfeo_svec *sx, int xi); -void blasfeo_sdiaad(int kmax, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_sdiaad_sp(int kmax, float alpha, struct blasfeo_svec *sx, int xi, int *idx, struct blasfeo_smat *sD, int di, int dj); -void blasfeo_sdiaadin_sp(int kmax, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sy, int yi, int *idx, struct blasfeo_smat *sD, int di, int dj); -// row -void blasfeo_srowin(int kmax, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_srowex(int kmax, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi); -void blasfeo_srowad(int kmax, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_srowad_sp(int kmax, float alpha, struct blasfeo_svec *sx, int xi, int *idx, struct blasfeo_smat *sD, int di, int dj); -void blasfeo_srowsw(int kmax, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -void blasfeo_srowpe(int kmax, int *ipiv, struct blasfeo_smat *sA); -void blasfeo_srowpei(int kmax, int *ipiv, struct blasfeo_smat *sA); -// col -void blasfeo_scolex(int kmax, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi); -void blasfeo_scolin(int kmax, struct blasfeo_svec *sx, int xi, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_scolad(int kmax, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_scolsc(int kmax, float alpha, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_scolsw(int kmax, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -void blasfeo_scolpe(int kmax, int *ipiv, struct blasfeo_smat *sA); -void blasfeo_scolpei(int kmax, int *ipiv, struct blasfeo_smat *sA); -// vec -void blasfeo_svecse(int m, float alpha, struct blasfeo_svec *sx, int xi); -void blasfeo_sveccp(int m, struct blasfeo_svec *sa, int ai, struct blasfeo_svec *sc, int ci); -void blasfeo_svecsc(int m, float alpha, struct blasfeo_svec *sa, int ai); -void blasfeo_sveccpsc(int m, float alpha, struct blasfeo_svec *sa, int ai, struct blasfeo_svec *sc, int ci); -void blasfeo_svecad(int m, float alpha, struct blasfeo_svec *sa, int ai, struct blasfeo_svec *sc, int ci); -void blasfeo_svecin1(float a, struct blasfeo_svec *sx, int xi); -float blasfeo_svecex1(struct blasfeo_svec *sx, int xi); -void blasfeo_svecad_sp(int m, float alpha, struct blasfeo_svec *sx, int xi, int *idx, struct blasfeo_svec *sz, int zi); -void blasfeo_svecin_sp(int m, float alpha, struct blasfeo_svec *sx, int xi, int *idx, struct blasfeo_svec *sz, int zi); -void blasfeo_svecex_sp(int m, float alpha, int *idx, struct blasfeo_svec *sx, int x, struct blasfeo_svec *sz, int zi); -// z += alpha * x[idx] -void blasfeo_svecexad_sp(int m, double alpha, int *idx, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -void blasfeo_sveccl(int m, struct blasfeo_svec *sxm, int xim, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sxp, int xip, struct blasfeo_svec *sz, int zi); -void blasfeo_sveccl_mask(int m, struct blasfeo_svec *sxm, int xim, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sxp, int xip, struct blasfeo_svec *sz, int zi, struct blasfeo_svec *sm, int mi); -void blasfeo_svecze(int m, struct blasfeo_svec *sm, int mi, struct blasfeo_svec *sv, int vi, struct blasfeo_svec *se, int ei); -void blasfeo_svecnrm_inf(int m, struct blasfeo_svec *sx, int xi, float *ptr_norm); -void blasfeo_svecnrm_2(int m, struct blasfeo_svec *sx, int xi, float *ptr_norm); -void blasfeo_svecpe(int kmax, int *ipiv, struct blasfeo_svec *sx, int xi); -void blasfeo_svecpei(int kmax, int *ipiv, struct blasfeo_svec *sx, int xi); - - - -/* -* Explicitly panel-major matrix format -*/ - -// returns the memory size (in bytes) needed for a dmat -size_t blasfeo_pm_memsize_smat(int ps, int m, int n); -// create a strmat for a matrix of size m*n by using memory passed by a pointer (pointer is not updated) -void blasfeo_pm_create_smat(int ps, int m, int n, struct blasfeo_pm_smat *sA, void *memory); - - - -/* -* Explicitly column-major matrix format -*/ - -// returns the memory size (in bytes) needed for a dmat -size_t blasfeo_cm_memsize_smat(int m, int n); -// create a strmat for a matrix of size m*n by using memory passed by a pointer (pointer is not updated) -void blasfeo_cm_create_smat(int m, int n, struct blasfeo_pm_smat *sA, void *memory); - - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_S_AUX_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_s_aux_ext_dep.h b/third_party/acados/include/blasfeo/include/blasfeo_s_aux_ext_dep.h deleted file mode 100644 index 5209d20d37..0000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_s_aux_ext_dep.h +++ /dev/null @@ -1,141 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_S_AUX_EXT_DEP_H_ -#define BLASFEO_S_AUX_EXT_DEP_H_ - - - -#include - - - -#include "blasfeo_common.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -#ifdef EXT_DEP - -/************************************************ -* s_aux_extern_depend_lib.c -************************************************/ - -/* column-major matrices */ - -// dynamically allocate row*col floats of memory and set accordingly a pointer to float; set allocated memory to zero -void s_zeros(float **pA, int row, int col); -// dynamically allocate row*col floats of memory aligned to 64-byte boundaries and set accordingly a pointer to float; set allocated memory to zero -void s_zeros_align(float **pA, int row, int col); -// dynamically allocate size bytes of memory aligned to 64-byte boundaries and set accordingly a pointer to float; set allocated memory to zero -void s_zeros_align_bytes(float **pA, int size); -// free the memory allocated by d_zeros -void s_free(float *pA); -// free the memory allocated by d_zeros_align or d_zeros_align_bytes -void s_free_align(float *pA); -// print a column-major matrix -void s_print_mat(int m, int n, float *A, int lda); -// print the transposed of a column-major matrix -void s_print_tran_mat(int row, int col, float *A, int lda); -// print to file a column-major matrix -void s_print_to_file_mat(FILE *file, int row, int col, float *A, int lda); -// print to file a column-major matrix in exponential format -void s_print_to_file_exp_mat(FILE *file, int row, int col, float *A, int lda); -// print to string a column-major matrix -void s_print_to_string_mat(char **buf_out, int row, int col, float *A, int lda); -// print to file the transposed of a column-major matrix -void s_print_tran_to_file_mat(FILE *file, int row, int col, float *A, int lda); -// print to file the transposed of a column-major matrix in exponential format -void s_print_tran_to_file_exp_mat(FILE *file, int row, int col, float *A, int lda); -// print in exponential notation a column-major matrix -void s_print_exp_mat(int m, int n, float *A, int lda); -// print in exponential notation the transposed of a column-major matrix -void s_print_exp_tran_mat(int row, int col, float *A, int lda); - -/* strmat and strvec */ - -// create a strmat for a matrix of size m*n by dynamically allocating memory -void blasfeo_allocate_smat(int m, int n, struct blasfeo_smat *sA); -// create a strvec for a vector of size m by dynamically allocating memory -void blasfeo_allocate_svec(int m, struct blasfeo_svec *sa); -// free the memory allocated by blasfeo_allocate_dmat -void blasfeo_free_smat(struct blasfeo_smat *sA); -// free the memory allocated by blasfeo_allocate_dvec -void blasfeo_free_svec(struct blasfeo_svec *sa); -// print a strmat -void blasfeo_print_smat(int m, int n, struct blasfeo_smat *sA, int ai, int aj); -// print in exponential notation a strmat -void blasfeo_print_exp_smat(int m, int n, struct blasfeo_smat *sA, int ai, int aj); -// print to file a strmat -void blasfeo_print_to_file_smat(FILE *file, int m, int n, struct blasfeo_smat *sA, int ai, int aj); -// print to file a strmat in exponential format -void blasfeo_print_to_file_exp_smat(FILE *file, int m, int n, struct blasfeo_smat *sA, int ai, int aj); -// print to string a strmat -void blasfeo_print_to_string_smat(char **buf_out, int m, int n, struct blasfeo_smat *sA, int ai, int aj); -// print the transpose of a strmat -void blasfeo_print_tran_smat(int m, int n, struct blasfeo_smat *sA, int ai, int aj); -// print a strvec -void blasfeo_print_svec(int m, struct blasfeo_svec *sa, int ai); -// print in exponential notation a strvec -void blasfeo_print_exp_svec(int m, struct blasfeo_svec *sa, int ai); -// print to file a strvec -void blasfeo_print_to_file_svec(FILE *file, int m, struct blasfeo_svec *sa, int ai); -// print to string a strvec -void blasfeo_print_to_string_svec(char **buf_out, int m, struct blasfeo_svec *sa, int ai); -// print the transposed of a strvec -void blasfeo_print_tran_svec(int m, struct blasfeo_svec *sa, int ai); -// print in exponential notation the transposed of a strvec -void blasfeo_print_exp_tran_svec(int m, struct blasfeo_svec *sa, int ai); -// print to file the transposed of a strvec -void blasfeo_print_to_file_tran_svec(FILE *file, int m, struct blasfeo_svec *sa, int ai); -// print to string the transposed of a strvec -void blasfeo_print_to_string_tran_svec(char **buf_out, int m, struct blasfeo_svec *sa, int ai); - -#endif // EXT_DEP - - - -#ifdef __cplusplus -} -#endif - - - -#endif // BLASFEO_S_AUX_EXT_DEP_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_s_aux_ext_dep_ref.h b/third_party/acados/include/blasfeo/include/blasfeo_s_aux_ext_dep_ref.h deleted file mode 100644 index 6640e20a40..0000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_s_aux_ext_dep_ref.h +++ /dev/null @@ -1,82 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_S_AUX_EXT_DEP_REF_H_ -#define BLASFEO_S_AUX_EXT_DEP_REF_H_ - -#if defined(EXT_DEP) - - - -#include - -#include "blasfeo_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - -// expose reference BLASFEO for testing -// see blasfeo_s_aux_exp_dep.h for help - -void blasfeo_print_smat_ref(int m, int n, struct blasfeo_smat_ref *sA, int ai, int aj); -void blasfeo_allocate_smat_ref(int m, int n, struct blasfeo_smat_ref *sA); -void blasfeo_allocate_svec_ref(int m, struct blasfeo_svec_ref *sa); -void blasfeo_free_smat_ref(struct blasfeo_smat_ref *sA); -void blasfeo_free_svec_ref(struct blasfeo_svec_ref *sa); -void blasfeo_print_smat_ref(int m, int n, struct blasfeo_smat_ref *sA, int ai, int aj); -void blasfeo_print_exp_smat_ref(int m, int n, struct blasfeo_smat_ref *sA, int ai, int aj); -void blasfeo_print_to_file_smat_ref(FILE *file, int m, int n, struct blasfeo_smat_ref *sA, int ai, int aj); -void blasfeo_print_to_file_exp_smat_ref(FILE *file, int m, int n, struct blasfeo_smat_ref *sA, int ai, int aj); -void blasfeo_print_to_string_smat_ref(char **buf_out, int m, int n, struct blasfeo_smat_ref *sA, int ai, int aj); -void blasfeo_print_svec(int m, struct blasfeo_svec *sa, int ai); -void blasfeo_print_exp_svec(int m, struct blasfeo_svec *sa, int ai); -void blasfeo_print_to_file_svec(FILE *file, int m, struct blasfeo_svec *sa, int ai); -void blasfeo_print_to_string_svec(char **buf_out, int m, struct blasfeo_svec *sa, int ai); -void blasfeo_print_tran_svec(int m, struct blasfeo_svec *sa, int ai); -void blasfeo_print_exp_tran_svec(int m, struct blasfeo_svec *sa, int ai); -void blasfeo_print_to_file_tran_svec(FILE *file, int m, struct blasfeo_svec *sa, int ai); -void blasfeo_print_to_string_tran_svec(char **buf_out, int m, struct blasfeo_svec *sa, int ai); - - -#ifdef __cplusplus -} -#endif - - - -#endif // EXT_DEP - -#endif // BLASFEO_S_AUX_EXT_DEP_REF_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_s_aux_old.h b/third_party/acados/include/blasfeo/include/blasfeo_s_aux_old.h deleted file mode 100644 index 5c6db37bab..0000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_s_aux_old.h +++ /dev/null @@ -1,64 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -// TODO remove -// -void strcp_l_lib(int m, float alpha, int offsetA, float *A, int sda, int offsetB, float *B, int sdb); -void sgead_lib(int m, int n, float alpha, int offsetA, float *A, int sda, int offsetB, float *B, int sdb); -void sgetr_lib(int m, int n, float alpha, int offsetA, float *pA, int sda, int offsetC, float *pC, int sdc); -void strtr_l_lib(int m, float alpha, int offsetA, float *pA, int sda, int offsetC, float *pC, int sdc); -void strtr_u_lib(int m, float alpha, int offsetA, float *pA, int sda, int offsetC, float *pC, int sdc); -void sdiareg_lib(int kmax, float reg, int offset, float *pD, int sdd); -void sdiain_sqrt_lib(int kmax, float *x, int offset, float *pD, int sdd); -void sdiaex_lib(int kmax, float alpha, int offset, float *pD, int sdd, float *x); -void sdiaad_lib(int kmax, float alpha, float *x, int offset, float *pD, int sdd); -void sdiain_libsp(int kmax, int *idx, float alpha, float *x, float *pD, int sdd); -void sdiaex_libsp(int kmax, int *idx, float alpha, float *pD, int sdd, float *x); -void sdiaad_libsp(int kmax, int *idx, float alpha, float *x, float *pD, int sdd); -void sdiaadin_libsp(int kmax, int *idx, float alpha, float *x, float *y, float *pD, int sdd); -void srowin_lib(int kmax, float alpha, float *x, float *pD); -void srowex_lib(int kmax, float alpha, float *pD, float *x); -void srowad_lib(int kmax, float alpha, float *x, float *pD); -void srowin_libsp(int kmax, float alpha, int *idx, float *x, float *pD); -void srowad_libsp(int kmax, int *idx, float alpha, float *x, float *pD); -void srowadin_libsp(int kmax, int *idx, float alpha, float *x, float *y, float *pD); -void srowsw_lib(int kmax, float *pA, float *pC); -void scolin_lib(int kmax, float *x, int offset, float *pD, int sdd); -void scolad_lib(int kmax, float alpha, float *x, int offset, float *pD, int sdd); -void scolin_libsp(int kmax, int *idx, float *x, float *pD, int sdd); -void scolad_libsp(int kmax, float alpha, int *idx, float *x, float *pD, int sdd); -void scolsw_lib(int kmax, int offsetA, float *pA, int sda, int offsetC, float *pC, int sdc); -void svecin_libsp(int kmax, int *idx, float *x, float *y); -void svecad_libsp(int kmax, int *idx, float alpha, float *x, float *y); diff --git a/third_party/acados/include/blasfeo/include/blasfeo_s_aux_ref.h b/third_party/acados/include/blasfeo/include/blasfeo_s_aux_ref.h deleted file mode 100644 index 998e1d8999..0000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_s_aux_ref.h +++ /dev/null @@ -1,147 +0,0 @@ - -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_S_AUX_REF_H_ -#define BLASFEO_S_AUX_REF_H_ - - - -#include - -#include "blasfeo_s_aux_old.h" -#include "blasfeo_common.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - -/************************************************ -* d_aux_lib.c -************************************************/ - -// returns the memory size (in bytes) needed for a smat -size_t blasfeo_ref_memsize_smat(int m, int n); -size_t blasfeo_ref_memsize_smat_ps(int ps, int m, int n); -// returns the memory size (in bytes) needed for the diagonal of a smat -size_t blasfeo_ref_memsize_diag_smat(int m, int n); -// returns the memory size (in bytes) needed for a svec -size_t blasfeo_ref_memsize_svec(int m); -// create a strmat for a matrix of size m*n by using memory passed by a pointer (pointer is not updated) -void blasfeo_ref_create_smat(int m, int n, struct blasfeo_smat *sA, void *memory); -void blasfeo_ref_create_smat_ps(int ps, int m, int n, struct blasfeo_smat *sA, void *memory); -// create a strvec for a vector of size m by using memory passed by a pointer (pointer is not updated) -void blasfeo_ref_create_svec(int m, struct blasfeo_svec *sA, void *memory); -void blasfeo_ref_pack_smat(int m, int n, float *A, int lda, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_ref_pack_l_smat(int m, int n, float *A, int lda, struct blasfeo_smat *sB, int bi, int bj); -void blasfeo_ref_pack_l_smat(int m, int n, float *A, int lda, struct blasfeo_smat *sB, int bi, int bj); -void blasfeo_ref_pack_tran_smat(int m, int n, float *A, int lda, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_ref_pack_svec(int m, float *x, int xi, struct blasfeo_svec *sa, int ai); -void blasfeo_ref_unpack_smat(int m, int n, struct blasfeo_smat *sA, int ai, int aj, float *A, int lda); -void blasfeo_ref_unpack_tran_smat(int m, int n, struct blasfeo_smat *sA, int ai, int aj, float *A, int lda); -void blasfeo_ref_unpack_svec(int m, struct blasfeo_svec *sa, int ai, float *x, int xi); -void ref_s_cast_mat2strmat(float *A, struct blasfeo_smat *sA); -void ref_s_cast_diag_mat2strmat(float *dA, struct blasfeo_smat *sA); -void ref_s_cast_vec2vecmat(float *a, struct blasfeo_svec *sa); - -// ge -void blasfeo_ref_sgese(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_ref_sgecpsc(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -void blasfeo_ref_sgecp(int m, int n, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -void blasfeo_ref_sgesc(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_ref_sgein1(float a, struct blasfeo_smat *sA, int ai, int aj); -float blasfeo_ref_sgeex1(struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_ref_sgead(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -void blasfeo_ref_sgetr(int m, int n, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -// tr -void blasfeo_ref_strcp_l(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -void blasfeo_ref_strtr_l(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -void blasfeo_ref_strtr_u(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -// dia -void blasfeo_ref_sdiare(int kmax, float alpha, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_ref_sdiaex(int kmax, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi); -void blasfeo_ref_sdiain(int kmax, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_ref_sdiain_sp(int kmax, float alpha, struct blasfeo_svec *sx, int xi, int *idx, struct blasfeo_smat *sD, int di, int dj); -void blasfeo_ref_sdiaex_sp(int kmax, float alpha, int *idx, struct blasfeo_smat *sD, int di, int dj, struct blasfeo_svec *sx, int xi); -void blasfeo_ref_sdiaad(int kmax, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_ref_sdiaad_sp(int kmax, float alpha, struct blasfeo_svec *sx, int xi, int *idx, struct blasfeo_smat *sD, int di, int dj); -void blasfeo_ref_sdiaadin_sp(int kmax, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sy, int yi, int *idx, struct blasfeo_smat *sD, int di, int dj); -// row -void blasfeo_ref_srowin(int kmax, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_ref_srowex(int kmax, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi); -void blasfeo_ref_srowad(int kmax, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_ref_srowad_sp(int kmax, float alpha, struct blasfeo_svec *sx, int xi, int *idx, struct blasfeo_smat *sD, int di, int dj); -void blasfeo_ref_srowsw(int kmax, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -void blasfeo_ref_srowpe(int kmax, int *ipiv, struct blasfeo_smat *sA); -void blasfeo_ref_srowpei(int kmax, int *ipiv, struct blasfeo_smat *sA); -// col -void blasfeo_ref_scolex(int kmax, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi); -void blasfeo_ref_scolin(int kmax, struct blasfeo_svec *sx, int xi, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_ref_scolad(int kmax, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_ref_scolsc(int kmax, float alpha, struct blasfeo_smat *sA, int ai, int aj); -void blasfeo_ref_scolsw(int kmax, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -void blasfeo_ref_scolpe(int kmax, int *ipiv, struct blasfeo_smat *sA); -void blasfeo_ref_scolpei(int kmax, int *ipiv, struct blasfeo_smat *sA); -// vec -void blasfeo_ref_svecse(int m, float alpha, struct blasfeo_svec *sx, int xi); -void blasfeo_ref_sveccp(int m, struct blasfeo_svec *sa, int ai, struct blasfeo_svec *sc, int ci); -void blasfeo_ref_svecsc(int m, float alpha, struct blasfeo_svec *sa, int ai); -void blasfeo_ref_sveccpsc(int m, float alpha, struct blasfeo_svec *sa, int ai, struct blasfeo_svec *sc, int ci); -void blasfeo_ref_svecad(int m, float alpha, struct blasfeo_svec *sa, int ai, struct blasfeo_svec *sc, int ci); -void blasfeo_ref_svecin1(float a, struct blasfeo_svec *sx, int xi); -float blasfeo_ref_svecex1(struct blasfeo_svec *sx, int xi); -void blasfeo_ref_svecad_sp(int m, float alpha, struct blasfeo_svec *sx, int xi, int *idx, struct blasfeo_svec *sz, int zi); -void blasfeo_ref_svecin_sp(int m, float alpha, struct blasfeo_svec *sx, int xi, int *idx, struct blasfeo_svec *sz, int zi); -void blasfeo_ref_svecex_sp(int m, float alpha, int *idx, struct blasfeo_svec *sx, int x, struct blasfeo_svec *sz, int zi); -// z += alpha * x[idx] -void blasfeo_ref_svecexad_sp(int m, double alpha, int *idx, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -void blasfeo_ref_sveccl(int m, struct blasfeo_svec *sxm, int xim, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sxp, int xip, struct blasfeo_svec *sz, int zi); -void blasfeo_ref_sveccl_mask(int m, struct blasfeo_svec *sxm, int xim, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sxp, int xip, struct blasfeo_svec *sz, int zi, struct blasfeo_svec *sm, int mi); -void blasfeo_ref_svecze(int m, struct blasfeo_svec *sm, int mi, struct blasfeo_svec *sv, int vi, struct blasfeo_svec *se, int ei); -void blasfeo_ref_svecnrm_inf(int m, struct blasfeo_svec *sx, int xi, float *ptr_norm); -void blasfeo_ref_svecpe(int kmax, int *ipiv, struct blasfeo_svec *sx, int xi); -void blasfeo_ref_svecpei(int kmax, int *ipiv, struct blasfeo_svec *sx, int xi); - - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_S_AUX_REF_H_ - diff --git a/third_party/acados/include/blasfeo/include/blasfeo_s_aux_test.h b/third_party/acados/include/blasfeo/include/blasfeo_s_aux_test.h deleted file mode 100644 index 08d9a14a6a..0000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_s_aux_test.h +++ /dev/null @@ -1,177 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_S_AUX_TEST_H_ -#define BLASFEO_S_AUX_TEST_H_ - -#include - -#include "blasfeo_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - - - -/************************************************ -* d_aux_lib.c -************************************************/ - -int test_blasfeo_memsize_smat(int m, int n); -int test_blasfeo_memsize_diag_smat(int m, int n); -int test_blasfeo_memsize_svec(int m); - -void test_blasfeo_create_smat(int m, int n, struct blasfeo_smat *sA, void *memory); -void test_blasfeo_create_svec(int m, struct blasfeo_svec *sA, void *memory); - -void test_blasfeo_pack_smat(int m, int n, float *A, int lda, struct blasfeo_smat *sA, int ai, int aj); -void test_blasfeo_pack_svec(int m, float *x, int xi, struct blasfeo_svec *sa, int ai); -void test_blasfeo_pack_tran_smat(int m, int n, float *A, int lda, struct blasfeo_smat *sA, int ai, int aj); -void test_blasfeo_unpack_smat(int m, int n, struct blasfeo_smat *sA, int ai, int aj, float *A, int lda); -void test_blasfeo_unpack_svec(int m, struct blasfeo_svec *sa, int ai, float *x, int xi); -void test_blasfeo_unpack_tran_smat(int m, int n, struct blasfeo_smat *sA, int ai, int aj, float *A, int lda); - -void test_s_cast_mat2strmat(float *A, struct blasfeo_smat *sA); -void test_s_cast_diag_mat2strmat(float *dA, struct blasfeo_smat *sA); -void test_s_cast_vec2vecmat(float *a, struct blasfeo_svec *sa); -// copy and scale -void test_blasfeo_sgecpsc(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -void test_blasfeo_sgecp(int m, int n, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -void test_blasfeo_sgesc(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj); - -// void test_blasfeo_sgein1(float a, struct blasfeo_smat *sA, int ai, int aj); -// float test_blasfeo_sgeex1(struct blasfeo_smat *sA, int ai, int aj); -// void test_blasfeo_svecin1(float a, struct blasfeo_svec *sx, int xi); -// float test_blasfeo_svecex1(struct blasfeo_svec *sx, int xi); - -// // A <= alpha -// void test_blasfeo_sgese(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj); -// // a <= alpha -// void test_blasfeo_svecse(int m, float alpha, struct blasfeo_svec *sx, int xi); - - -// void test_blasfeo_sveccp(int m, struct blasfeo_svec *sa, int ai, struct blasfeo_svec *sc, int ci); -// void test_blasfeo_svecsc(int m, float alpha, struct blasfeo_svec *sa, int ai); - -// void test_strcp_l_lib(int m, float alpha, int offsetA, float *A, int sda, int offsetB, float *B, int sdb); -// void test_blasfeo_strcp_l(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); - -// void test_sgead_lib(int m, int n, float alpha, int offsetA, float *A, int sda, int offsetB, float *B, int sdb); -// void test_blasfeo_sgead(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -// void test_blasfeo_svecad(int m, float alpha, struct blasfeo_svec *sa, int ai, struct blasfeo_svec *sc, int ci); - -// void test_sgetr_lib(int m, int n, float alpha, int offsetA, float *pA, int sda, int offsetC, float *pC, int sdc); -// void test_blasfeo_sgetr(int m, int n, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); - -// void test_strtr_l_lib(int m, float alpha, int offsetA, float *pA, int sda, int offsetC, float *pC, int sdc); -// void test_blasfeo_strtr_l(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -// void test_strtr_u_lib(int m, float alpha, int offsetA, float *pA, int sda, int offsetC, float *pC, int sdc); -// void test_blasfeo_strtr_u(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); - -// void test_sdiareg_lib(int kmax, float reg, int offset, float *pD, int sdd); -// void test_blasfeo_sdiaex(int kmax, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi); -// void test_blasfeo_sdiain(int kmax, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_smat *sA, int ai, int aj); -// void test_sdiain_sqrt_lib(int kmax, float *x, int offset, float *pD, int sdd); -// void test_sdiaex_lib(int kmax, float alpha, int offset, float *pD, int sdd, float *x); -// void test_sdiaad_lib(int kmax, float alpha, float *x, int offset, float *pD, int sdd); -// void test_sdiain_libsp(int kmax, int *idx, float alpha, float *x, float *pD, int sdd); -// void test_blasfeo_sdiain_sp(int kmax, float alpha, struct blasfeo_svec *sx, int xi, int *idx, struct blasfeo_smat *sD, int di, int dj); -// void test_sdiaex_libsp(int kmax, int *idx, float alpha, float *pD, int sdd, float *x); -// void test_blasfeo_sdiaex_sp(int kmax, float alpha, int *idx, struct blasfeo_smat *sD, int di, int dj, struct blasfeo_svec *sx, int xi); -// void test_blasfeo_sdiaad(int kmax, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_smat *sA, int ai, int aj); -// void test_sdiaad_libsp(int kmax, int *idx, float alpha, float *x, float *pD, int sdd); -// void test_blasfeo_sdiaad_sp(int kmax, float alpha, struct blasfeo_svec *sx, int xi, int *idx, struct blasfeo_smat *sD, int di, int dj); -// void test_sdiaadin_libsp(int kmax, int *idx, float alpha, float *x, float *y, float *pD, int sdd); -// void test_blasfeo_sdiaadin_sp(int kmax, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sy, int yi, int *idx, struct blasfeo_smat *sD, int di, int dj); -// void test_srowin_lib(int kmax, float alpha, float *x, float *pD); -// void test_blasfeo_srowin(int kmax, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_smat *sA, int ai, int aj); -// void test_srowex_lib(int kmax, float alpha, float *pD, float *x); -// void test_blasfeo_srowex(int kmax, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi); -// void test_srowad_lib(int kmax, float alpha, float *x, float *pD); -// void test_blasfeo_srowad(int kmax, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_smat *sA, int ai, int aj); -// void test_srowin_libsp(int kmax, float alpha, int *idx, float *x, float *pD); -// void test_srowad_libsp(int kmax, int *idx, float alpha, float *x, float *pD); -// void test_blasfeo_srowad_sp(int kmax, float alpha, struct blasfeo_svec *sx, int xi, int *idx, struct blasfeo_smat *sD, int di, int dj); -// void test_srowadin_libsp(int kmax, int *idx, float alpha, float *x, float *y, float *pD); -// void test_srowsw_lib(int kmax, float *pA, float *pC); -// void test_blasfeo_srowsw(int kmax, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -// void test_blasfeo_srowpe(int kmax, int *ipiv, struct blasfeo_smat *sA); -// void test_scolin_lib(int kmax, float *x, int offset, float *pD, int sdd); -// void test_blasfeo_scolin(int kmax, struct blasfeo_svec *sx, int xi, struct blasfeo_smat *sA, int ai, int aj); -// void test_scolad_lib(int kmax, float alpha, float *x, int offset, float *pD, int sdd); -// void test_scolin_libsp(int kmax, int *idx, float *x, float *pD, int sdd); -// void test_scolad_libsp(int kmax, float alpha, int *idx, float *x, float *pD, int sdd); -// void test_scolsw_lib(int kmax, int offsetA, float *pA, int sda, int offsetC, float *pC, int sdc); -// void test_blasfeo_scolsw(int kmax, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sC, int ci, int cj); -// void test_blasfeo_scolpe(int kmax, int *ipiv, struct blasfeo_smat *sA); -// void test_svecin_libsp(int kmax, int *idx, float *x, float *y); -// void test_svecad_libsp(int kmax, int *idx, float alpha, float *x, float *y); -// void test_blasfeo_svecad_sp(int m, float alpha, struct blasfeo_svec *sx, int xi, int *idx, struct blasfeo_svec *sz, int zi); -// void test_blasfeo_svecin_sp(int m, float alpha, struct blasfeo_svec *sx, int xi, int *idx, struct blasfeo_svec *sz, int zi); -// void test_blasfeo_svecex_sp(int m, float alpha, int *idx, struct blasfeo_svec *sx, int x, struct blasfeo_svec *sz, int zi); -// void test_blasfeo_sveccl(int m, struct blasfeo_svec *sxm, int xim, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sxp, int xip, struct blasfeo_svec *sz, int zi); -// void test_blasfeo_sveccl_mask(int m, struct blasfeo_svec *sxm, int xim, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sxp, int xip, struct blasfeo_svec *sz, int zi, struct blasfeo_svec *sm, int mi); -// void test_blasfeo_svecze(int m, struct blasfeo_svec *sm, int mi, struct blasfeo_svec *sv, int vi, struct blasfeo_svec *se, int ei); -// void test_blasfeo_svecnrm_inf(int m, struct blasfeo_svec *sx, int xi, float *ptr_norm); -// void test_blasfeo_svecpe(int kmax, int *ipiv, struct blasfeo_svec *sx, int xi); - - -// ext_dep - -void test_blasfeo_allocate_smat(int m, int n, struct blasfeo_smat *sA); -void test_blasfeo_allocate_svec(int m, struct blasfeo_svec *sa); - -void test_blasfeo_free_smat(struct blasfeo_smat *sA); -void test_blasfeo_free_svec(struct blasfeo_svec *sa); - -void test_blasfeo_print_smat(int m, int n, struct blasfeo_smat *sA, int ai, int aj); -void test_blasfeo_print_svec(int m, struct blasfeo_svec *sa, int ai); -void test_blasfeo_print_tran_svec(int m, struct blasfeo_svec *sa, int ai); - -void test_blasfeo_print_to_file_smat(FILE *file, int m, int n, struct blasfeo_smat *sA, int ai, int aj); -void test_blasfeo_print_to_file_svec(FILE *file, int m, struct blasfeo_svec *sa, int ai); -void test_blasfeo_print_to_file_tran_svec(FILE *file, int m, struct blasfeo_svec *sa, int ai); - -void test_blasfeo_print_exp_smat(int m, int n, struct blasfeo_smat *sA, int ai, int aj); -void test_blasfeo_print_exp_svec(int m, struct blasfeo_svec *sa, int ai); -void test_blasfeo_print_exp_tran_svec(int m, struct blasfeo_svec *sa, int ai); - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_S_AUX_TEST_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_s_blas.h b/third_party/acados/include/blasfeo/include/blasfeo_s_blas.h deleted file mode 100644 index 200f1f51b1..0000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_s_blas.h +++ /dev/null @@ -1,46 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_S_BLAS_H_ -#define BLASFEO_S_BLAS_H_ - - - -#include "blasfeo_s_blasfeo_api.h" -#include "blasfeo_s_blas_api.h" - - - -#endif // BLASFEO_S_BLAS_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_s_blas_api.h b/third_party/acados/include/blasfeo/include/blasfeo_s_blas_api.h deleted file mode 100644 index cf2b3e0a2d..0000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_s_blas_api.h +++ /dev/null @@ -1,182 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef BLASFEO_S_BLAS_API_H_ -#define BLASFEO_S_BLAS_API_H_ - - - -#include "blasfeo_target.h" - - - -#ifdef BLAS_API -#ifdef CBLAS_API -#ifndef BLASFEO_CBLAS_ENUM -#define BLASFEO_CBLAS_ENUM -#ifdef FORTRAN_BLAS_API -#ifndef CBLAS_H -enum CBLAS_ORDER {CblasRowMajor=101, CblasColMajor=102}; -enum CBLAS_TRANSPOSE {CblasNoTrans=111, CblasTrans=112, CblasConjTrans=113}; -enum CBLAS_UPLO {CblasUpper=121, CblasLower=122}; -enum CBLAS_DIAG {CblasNonUnit=131, CblasUnit=132}; -enum CBLAS_SIDE {CblasLeft=141, CblasRight=142}; -#endif // CBLAS_H -#else // FORTRAN_BLAS_API -enum BLASFEO_CBLAS_ORDER {CblasRowMajor=101, CblasColMajor=102}; -enum BLASFEO_CBLAS_TRANSPOSE {CblasNoTrans=111, CblasTrans=112, CblasConjTrans=113}; -enum BLASFEO_CBLAS_UPLO {CblasUpper=121, CblasLower=122}; -enum BLASFEO_CBLAS_DIAG {CblasNonUnit=131, CblasUnit=132}; -enum BLASFEO_CBLAS_SIDE {CblasLeft=141, CblasRight=142}; -#endif // FORTRAN_BLAS_API -#endif // BLASFEO_CBLAS_ENUM -#endif // CBLAS_API -#endif // BLAS_API - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -#ifdef BLAS_API - - - -#ifdef FORTRAN_BLAS_API - - - -// BLAS 1 -// -void saxpy_(int *n, float *alpha, float *x, int *incx, float *y, int *incy); -// -float sdot_(int *n, float *x, int *incx, float *y, int *incy); - -// BLAS 3 -// -void sgemm_(char *ta, char *tb, int *m, int *n, int *k, float *alpha, float *A, int *lda, float *B, int *ldb, float *beta, float *C, int *ldc); -// -void strsm_(char *side, char *uplo, char *transa, char *diag, int *m, int *n, float *alpha, float *A, int *lda, float *B, int *ldb); - - - -// LAPACK -// -void spotrf_(char *uplo, int *m, float *A, int *lda, int *info); - - - -#ifdef CBLAS_API - - - -// CBLAS 1 -// -void cblas_saxpy(const int N, const float alpha, const float *X, const int incX, float *Y, const int incY); - -// CBLAS 3 -// -void cblas_sgemm(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, const int M, const int N, const int K, const float alpha, const float *A, const int lda, const float *B, const int ldb, const float beta, float *C, const int ldc); -// -void cblas_strsm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int M, const int N, const float alpha, const float *A, const int lda, float *B, const int ldb); - - - -#endif // CBLAS_API - - - -#else // BLASFEO_API - - - -// BLAS 1 -// -void blasfeo_blas_saxpy(int *n, float *alpha, float *x, int *incx, float *y, int *incy); -// -float blasfeo_blas_sdot(int *n, float *x, int *incx, float *y, int *incy); - -// BLAS 3 -// -void blasfeo_blas_sgemm(char *ta, char *tb, int *m, int *n, int *k, float *alpha, float *A, int *lda, float *B, int *ldb, float *beta, float *C, int *ldc); -// -void blasfeo_blas_strsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, float *alpha, float *A, int *lda, float *B, int *ldb); - - - -// LAPACK -// -void blasfeo_lapack_spotrf(char *uplo, int *m, float *A, int *lda, int *info); - - - -#ifdef CBLAS_API - - - -// CBLAS 1 -// -void blasfeo_cblas_saxpy(const int N, const float alpha, const float *X, const int incX, float *Y, const int incY); - -// CBLAS 3 -// -void blasfeo_cblas_sgemm(const enum BLASFEO_CBLAS_ORDER Order, const enum BLASFEO_CBLAS_TRANSPOSE TransA, const enum BLASFEO_CBLAS_TRANSPOSE TransB, const int M, const int N, const int K, const float alpha, const float *A, const int lda, const float *B, const int ldb, const float beta, float *C, const int ldc); -// -void blasfeo_cblas_strsm(const enum BLASFEO_CBLAS_ORDER Order, const enum BLASFEO_CBLAS_SIDE Side, const enum BLASFEO_CBLAS_UPLO Uplo, const enum BLASFEO_CBLAS_TRANSPOSE TransA, const enum BLASFEO_CBLAS_DIAG Diag, const int M, const int N, const float alpha, const float *A, const int lda, float *B, const int ldb); - - - -#endif // CBLAS_API - - - -#endif // BLASFEO_API - - - -#endif // BLAS_API - - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_S_BLAS_API_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_s_blasfeo_api.h b/third_party/acados/include/blasfeo/include/blasfeo_s_blasfeo_api.h deleted file mode 100644 index 8b98104735..0000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_s_blasfeo_api.h +++ /dev/null @@ -1,284 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_S_BLASFEO_API_H_ -#define BLASFEO_S_BLASFEO_API_H_ - - - -#include "blasfeo_common.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - -// -// level 1 BLAS -// - -// z = y + alpha*x -void blasfeo_saxpy(int kmax, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); -// z = beta*y + alpha*x -void blasfeo_saxpby(int kmax, float alpha, struct blasfeo_svec *sx, int xi, float beta, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); -// z = x .* y -void blasfeo_svecmul(int m, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); -// z += x .* y -void blasfeo_svecmulacc(int m, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); -// z = x .* y, return sum(z) = x^T * y -float blasfeo_svecmuldot(int m, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); -// return x^T * y -float blasfeo_sdot(int m, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sy, int yi); -// construct givens plane rotation -void blasfeo_srotg(float a, float b, float *c, float *s); -// apply plane rotation [a b] [c -s; s; c] to the aj0 and aj1 columns of A at row index ai -void blasfeo_scolrot(int m, struct blasfeo_smat *sA, int ai, int aj0, int aj1, float c, float s); -// apply plane rotation [c s; -s c] [a; b] to the ai0 and ai1 rows of A at column index aj -void blasfeo_srowrot(int m, struct blasfeo_smat *sA, int ai0, int ai1, int aj, float c, float s); - - - -// -// level 2 BLAS -// - -// dense - -// z <= beta * y + alpha * A * x -void blasfeo_sgemv_n(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, float beta, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); -// z <= beta * y + alpha * A' * x -void blasfeo_sgemv_t(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, float beta, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); -// z <= inv( A ) * x, A (m)x(n) -void blasfeo_strsv_lnn_mn(int m, int n, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= inv( A' ) * x, A (m)x(n) -void blasfeo_strsv_ltn_mn(int m, int n, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= inv( A ) * x, A (m)x(m) lower, not_transposed, not_unit -void blasfeo_strsv_lnn(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= inv( A ) * x, A (m)x(m) lower, not_transposed, unit -void blasfeo_strsv_lnu(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= inv( A' ) * x, A (m)x(m) lower, transposed, not_unit -void blasfeo_strsv_ltn(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= inv( A' ) * x, A (m)x(m) lower, transposed, unit -void blasfeo_strsv_ltu(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= inv( A' ) * x, A (m)x(m) upper, not_transposed, not_unit -void blasfeo_strsv_unn(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= inv( A' ) * x, A (m)x(m) upper, transposed, not_unit -void blasfeo_strsv_utn(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= A * x ; A lower triangular -void blasfeo_strmv_lnn(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= A * x ; A lower triangular, unit diagonal -void blasfeo_strmv_lnu(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= A' * x ; A lower triangular -void blasfeo_strmv_ltn(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= A' * x ; A lower triangular, unit diagonal -void blasfeo_strmv_ltu(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= beta * y + alpha * A * x ; A upper triangular -void blasfeo_strmv_unn(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= A' * x ; A upper triangular -void blasfeo_strmv_utn(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z_n <= beta_n * y_n + alpha_n * A * x_n -// z_t <= beta_t * y_t + alpha_t * A' * x_t -void blasfeo_sgemv_nt(int m, int n, float alpha_n, float alpha_t, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx_n, int xi_n, struct blasfeo_svec *sx_t, int xi_t, float beta_n, float beta_t, struct blasfeo_svec *sy_n, int yi_n, struct blasfeo_svec *sy_t, int yi_t, struct blasfeo_svec *sz_n, int zi_n, struct blasfeo_svec *sz_t, int zi_t); -// z <= beta * y + alpha * A * x, where A is symmetric and only the lower triangular patr of A is accessed -void blasfeo_ssymv_l(int m, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, float beta, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); -void blasfeo_ssymv_l_mn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, float beta, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); -// z <= beta * y + alpha * A * x, where A is symmetric and only the upper triangular patr of A is accessed -void blasfeo_ssymv_u(int m, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, float beta, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); -// D = C + alpha * x * y^T -void blasfeo_sger(int m, int n, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sy, int yi, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); - -// diagonal - -// z <= beta * y + alpha * A * x, A diagonal -void blasfeo_sgemv_d(int m, float alpha, struct blasfeo_svec *sA, int ai, struct blasfeo_svec *sx, int xi, float beta, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); - - - -// -// level 3 BLAS -// - -// dense - -// D <= beta * C + alpha * A * B -void blasfeo_sgemm_nn(int m, int n, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A * B^T -void blasfeo_sgemm_nt(int m, int n, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B -void blasfeo_sgemm_tn(int m, int n, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B -void blasfeo_sgemm_tt(int m, int n, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A * B^T ; C, D lower triangular -void blasfeo_ssyrk_ln(int m, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -void blasfeo_ssyrk_ln_mn(int m, int n, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B ; C, D lower triangular -void blasfeo_ssyrk_lt(int m, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A * B^T ; C, D upper triangular -void blasfeo_ssyrk_un(int m, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B ; C, D upper triangular -void blasfeo_ssyrk_ut(int m, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * B * A^T ; B upper triangular -void blasfeo_strmm_rutn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * B * A ; A lower triangular -void blasfeo_strmm_rlnn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * A^{-1} * B , with A lower triangular employint explicit inverse of diagonal -void blasfeo_strsm_llnn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * A^{-1} * B , with A lower triangular with unit diagonal -void blasfeo_strsm_llnu(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * A^{-T} * B , with A lower triangular employint explicit inverse of diagonal -void blasfeo_strsm_lltn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * A^{-T} * B , with A lower triangular with unit diagonal -void blasfeo_strsm_lltu(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * A^{-1} * B , with A upper triangular employing explicit inverse of diagonal -void blasfeo_strsm_lunn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * A^{-1} * B , with A upper triangular withunit diagonal -void blasfeo_strsm_lunu(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * A^{-T} * B , with A upper triangular employing explicit inverse of diagonal -void blasfeo_strsm_lutn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * A^{-T} * B , with A upper triangular withunit diagonal -void blasfeo_strsm_lutu(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * B * A^{-1} , with A lower triangular employing explicit inverse of diagonal -void blasfeo_strsm_rlnn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * B * A^{-1} , with A lower triangular with unit diagonal -void blasfeo_strsm_rlnu(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * B * A^{-T} , with A lower triangular employing explicit inverse of diagonal -void blasfeo_strsm_rltn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * B * A^{-T} , with A lower triangular with unit diagonal -void blasfeo_strsm_rltu(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * B * A^{-1} , with A upper triangular employing explicit inverse of diagonal -void blasfeo_strsm_runn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * B * A^{-1} , with A upper triangular with unit diagonal -void blasfeo_strsm_runu(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * B * A^{-T} , with A upper triangular employing explicit inverse of diagonal -void blasfeo_strsm_rutn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * B * A^{-T} , with A upper triangular with unit diagonal -void blasfeo_strsm_rutu(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A * B^T + alpha * B * A^T; C, D lower triangular -void blasfeo_ssyr2k_ln(int m, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B + alpha * B^T * A; C, D lower triangular -void blasfeo_ssyr2k_lt(int m, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A * B^T + alpha * B * A^T; C, D upper triangular -void blasfeo_ssyr2k_un(int m, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B + alpha * B^T * A; C, D upper triangular -void blasfeo_ssyr2k_ut(int m, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); - -// diagonal - -// D <= alpha * A * B + beta * C, with A diagonal (stored as strvec) -void sgemm_diag_left_ib(int m, int n, float alpha, float *dA, float *pB, int sdb, float beta, float *pC, int sdc, float *pD, int sdd); -void blasfeo_sgemm_dn(int m, int n, float alpha, struct blasfeo_svec *sA, int ai, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * A * B + beta * C, with B diagonal (stored as strvec) -void blasfeo_sgemm_nd(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sB, int bi, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); - - - -// -// LAPACK -// - -// D <= chol( C ) ; C, D lower triangular -void blasfeo_spotrf_l(int m, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -void blasfeo_spotrf_l_mn(int m, int n, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= chol( C ) ; C, D upper triangular -void blasfeo_spotrf_u(int m, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= chol( C + A * B' ) ; C, D lower triangular -void blasfeo_ssyrk_spotrf_ln(int m, int k, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -void blasfeo_ssyrk_spotrf_ln_mn(int m, int n, int k, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= lu( C ) ; no pivoting -void blasfeo_sgetrf_np(int m, int n, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= lu( C ) ; row pivoting -void blasfeo_sgetrf_rp(int m, int n, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj, int *ipiv); -// D <= qr( C ) -void blasfeo_sgeqrf(int m, int n, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj, void *work); -int blasfeo_sgeqrf_worksize(int m, int n); // in bytes -// D <= Q factor, where C is the output of the LQ factorization -int blasfeo_sorglq_worksize(int m, int n, int k); // in bytes -void blasfeo_sorglq(int m, int n, int k, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj, void *work); -// D <= lq( C ) -void blasfeo_sgelqf(int m, int n, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj, void *work); -int blasfeo_sgelqf_worksize(int m, int n); // in bytes -// D <= lq( C ), positive diagonal elements -void blasfeo_sgelqf_pd(int m, int n, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj, void *work); -// [L, A] <= lq( [L, A] ), positive diagonal elements, array of matrices, with -// L lower triangular, of size (m)x(m) -// A full, of size (m)x(n1) -void blasfeo_sgelqf_pd_la(int m, int n1, struct blasfeo_smat *sL, int li, int lj, struct blasfeo_smat *sA, int ai, int aj, void *work); -// [L, L, A] <= lq( [L, L, A] ), positive diagonal elements, array of matrices, with: -// L lower triangular, of size (m)x(m) -// A full, of size (m)x(n1) -void blasfeo_sgelqf_pd_lla(int m, int n1, struct blasfeo_smat *sL0, int l0i, int l0j, struct blasfeo_smat *sL1, int l1i, int l1j, struct blasfeo_smat *sA, int ai, int aj, void *work); - - - - -// -// BLAS API helper functions -// - -#if ( defined(BLAS_API) & defined(MF_PANELMAJ) ) -// BLAS 3 -void blasfeo_cm_sgemm_nn(int m, int n, int k, float alpha, struct blasfeo_cm_smat *sA, int ai, int aj, struct blasfeo_cm_smat *sB, int bi, int bj, float beta, struct blasfeo_cm_smat *sC, int ci, int cj, struct blasfeo_cm_smat *sD, int di, int dj); -void blasfeo_cm_sgemm_nt(int m, int n, int k, float alpha, struct blasfeo_cm_smat *sA, int ai, int aj, struct blasfeo_cm_smat *sB, int bi, int bj, float beta, struct blasfeo_cm_smat *sC, int ci, int cj, struct blasfeo_cm_smat *sD, int di, int dj); -void blasfeo_cm_sgemm_tn(int m, int n, int k, float alpha, struct blasfeo_cm_smat *sA, int ai, int aj, struct blasfeo_cm_smat *sB, int bi, int bj, float beta, struct blasfeo_cm_smat *sC, int ci, int cj, struct blasfeo_cm_smat *sD, int di, int dj); -void blasfeo_cm_sgemm_tt(int m, int n, int k, float alpha, struct blasfeo_cm_smat *sA, int ai, int aj, struct blasfeo_cm_smat *sB, int bi, int bj, float beta, struct blasfeo_cm_smat *sC, int ci, int cj, struct blasfeo_cm_smat *sD, int di, int dj); -void blasfeo_cm_strsm_llnn(int m, int n, float alpha, struct blasfeo_cm_smat *sA, int ai, int aj, struct blasfeo_cm_smat *sB, int bi, int bj, struct blasfeo_cm_smat *sD, int di, int dj); -void blasfeo_cm_strsm_llnu(int m, int n, float alpha, struct blasfeo_cm_smat *sA, int ai, int aj, struct blasfeo_cm_smat *sB, int bi, int bj, struct blasfeo_cm_smat *sD, int di, int dj); -void blasfeo_cm_strsm_lltn(int m, int n, float alpha, struct blasfeo_cm_smat *sA, int ai, int aj, struct blasfeo_cm_smat *sB, int bi, int bj, struct blasfeo_cm_smat *sD, int di, int dj); -void blasfeo_cm_strsm_lltu(int m, int n, float alpha, struct blasfeo_cm_smat *sA, int ai, int aj, struct blasfeo_cm_smat *sB, int bi, int bj, struct blasfeo_cm_smat *sD, int di, int dj); -void blasfeo_cm_strsm_lunn(int m, int n, float alpha, struct blasfeo_cm_smat *sA, int ai, int aj, struct blasfeo_cm_smat *sB, int bi, int bj, struct blasfeo_cm_smat *sD, int di, int dj); -void blasfeo_cm_strsm_lunu(int m, int n, float alpha, struct blasfeo_cm_smat *sA, int ai, int aj, struct blasfeo_cm_smat *sB, int bi, int bj, struct blasfeo_cm_smat *sD, int di, int dj); -void blasfeo_cm_strsm_lutn(int m, int n, float alpha, struct blasfeo_cm_smat *sA, int ai, int aj, struct blasfeo_cm_smat *sB, int bi, int bj, struct blasfeo_cm_smat *sD, int di, int dj); -void blasfeo_cm_strsm_lutu(int m, int n, float alpha, struct blasfeo_cm_smat *sA, int ai, int aj, struct blasfeo_cm_smat *sB, int bi, int bj, struct blasfeo_cm_smat *sD, int di, int dj); -void blasfeo_cm_strsm_rlnn(int m, int n, float alpha, struct blasfeo_cm_smat *sA, int ai, int aj, struct blasfeo_cm_smat *sB, int bi, int bj, struct blasfeo_cm_smat *sD, int di, int dj); -void blasfeo_cm_strsm_rlnu(int m, int n, float alpha, struct blasfeo_cm_smat *sA, int ai, int aj, struct blasfeo_cm_smat *sB, int bi, int bj, struct blasfeo_cm_smat *sD, int di, int dj); -void blasfeo_cm_strsm_rltn(int m, int n, float alpha, struct blasfeo_cm_smat *sA, int ai, int aj, struct blasfeo_cm_smat *sB, int bi, int bj, struct blasfeo_cm_smat *sD, int di, int dj); -void blasfeo_cm_strsm_rltu(int m, int n, float alpha, struct blasfeo_cm_smat *sA, int ai, int aj, struct blasfeo_cm_smat *sB, int bi, int bj, struct blasfeo_cm_smat *sD, int di, int dj); -void blasfeo_cm_strsm_runn(int m, int n, float alpha, struct blasfeo_cm_smat *sA, int ai, int aj, struct blasfeo_cm_smat *sB, int bi, int bj, struct blasfeo_cm_smat *sD, int di, int dj); -void blasfeo_cm_strsm_runu(int m, int n, float alpha, struct blasfeo_cm_smat *sA, int ai, int aj, struct blasfeo_cm_smat *sB, int bi, int bj, struct blasfeo_cm_smat *sD, int di, int dj); -void blasfeo_cm_strsm_rutn(int m, int n, float alpha, struct blasfeo_cm_smat *sA, int ai, int aj, struct blasfeo_cm_smat *sB, int bi, int bj, struct blasfeo_cm_smat *sD, int di, int dj); -void blasfeo_cm_strsm_rutu(int m, int n, float alpha, struct blasfeo_cm_smat *sA, int ai, int aj, struct blasfeo_cm_smat *sB, int bi, int bj, struct blasfeo_cm_smat *sD, int di, int dj); -// LAPACK -void blasfeo_cm_spotrf_l(int m, struct blasfeo_cm_smat *sC, int ci, int cj, struct blasfeo_cm_smat *sD, int di, int dj); -void blasfeo_cm_spotrf_u(int m, struct blasfeo_cm_smat *sC, int ci, int cj, struct blasfeo_cm_smat *sD, int di, int dj); -#endif - - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_S_BLASFEO_API_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_s_blasfeo_api_ref.h b/third_party/acados/include/blasfeo/include/blasfeo_s_blasfeo_api_ref.h deleted file mode 100644 index f429a79dc3..0000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_s_blasfeo_api_ref.h +++ /dev/null @@ -1,135 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_S_BLASFEO_API_REF_H_ -#define BLASFEO_S_BLASFEO_API_REF_H_ - -#include "blasfeo_common.h" - - -#ifdef __cplusplus -extern "C" { -#endif - - -// expose reference BLASFEO for testing - -// --- level 1 - -void blasfeo_saxpy_ref(int kmax, float alpha, struct blasfeo_svec_ref *sx, int xi, struct blasfeo_svec_ref *sy, int yi, struct blasfeo_svec_ref *sz, int zi); -void blasfeo_saxpby_ref(int kmax, float alpha, struct blasfeo_svec_ref *sx, int xi, float beta, struct blasfeo_svec_ref *sy, int yi, struct blasfeo_svec_ref *sz, int zi); -void blasfeo_svecmul_ref(int m, struct blasfeo_svec_ref *sx, int xi, struct blasfeo_svec_ref *sy, int yi, struct blasfeo_svec_ref *sz, int zi); -void blasfeo_svecmulacc_ref(int m, struct blasfeo_svec_ref *sx, int xi, struct blasfeo_svec_ref *sy, int yi, struct blasfeo_svec_ref *sz, int zi); -float blasfeo_svecmuldot_ref(int m, struct blasfeo_svec_ref *sx, int xi, struct blasfeo_svec_ref *sy, int yi, struct blasfeo_svec_ref *sz, int zi); -float blasfeo_sdot_ref(int m, struct blasfeo_svec_ref *sx, int xi, struct blasfeo_svec_ref *sy, int yi); -void blasfeo_srotg_ref(float a, float b, float *c, float *s); -void blasfeo_scolrot_ref(int m, struct blasfeo_smat_ref *sA, int ai, int aj0, int aj1, float c, float s); -void blasfeo_srowrot_ref(int m, struct blasfeo_smat_ref *sA, int ai0, int ai1, int aj, float c, float s); - - -// --- level 2 - -// dense -void blasfeo_sgemv_n_ref(int m, int n, float alpha, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_svec_ref *sx, int xi, float beta, struct blasfeo_svec_ref *sy, int yi, struct blasfeo_svec_ref *sz, int zi); -void blasfeo_sgemv_t_ref(int m, int n, float alpha, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_svec_ref *sx, int xi, float beta, struct blasfeo_svec_ref *sy, int yi, struct blasfeo_svec_ref *sz, int zi); -void blasfeo_strsv_lnn_mn_ref(int m, int n, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_svec_ref *sx, int xi, struct blasfeo_svec_ref *sz, int zi); -void blasfeo_strsv_ltn_mn_ref(int m, int n, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_svec_ref *sx, int xi, struct blasfeo_svec_ref *sz, int zi); -void blasfeo_strsv_lnn_ref(int m, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_svec_ref *sx, int xi, struct blasfeo_svec_ref *sz, int zi); -void blasfeo_strsv_lnu_ref(int m, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_svec_ref *sx, int xi, struct blasfeo_svec_ref *sz, int zi); -void blasfeo_strsv_ltn_ref(int m, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_svec_ref *sx, int xi, struct blasfeo_svec_ref *sz, int zi); -void blasfeo_strsv_ltu_ref(int m, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_svec_ref *sx, int xi, struct blasfeo_svec_ref *sz, int zi); -void blasfeo_strsv_unn_ref(int m, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_svec_ref *sx, int xi, struct blasfeo_svec_ref *sz, int zi); -void blasfeo_strsv_utn_ref(int m, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_svec_ref *sx, int xi, struct blasfeo_svec_ref *sz, int zi); -void blasfeo_strmv_unn_ref(int m, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_svec_ref *sx, int xi, struct blasfeo_svec_ref *sz, int zi); -void blasfeo_strmv_utn_ref(int m, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_svec_ref *sx, int xi, struct blasfeo_svec_ref *sz, int zi); -void blasfeo_strmv_lnn_ref(int m, int n, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_svec_ref *sx, int xi, struct blasfeo_svec_ref *sz, int zi); -void blasfeo_strmv_ltn_ref(int m, int n, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_svec_ref *sx, int xi, struct blasfeo_svec_ref *sz, int zi); -void blasfeo_strmv_lnu_ref(int m, int n, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_svec_ref *sx, int xi, struct blasfeo_svec_ref *sz, int zi); -void blasfeo_strmv_ltu_ref(int m, int n, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_svec_ref *sx, int xi, struct blasfeo_svec_ref *sz, int zi); -void blasfeo_sgemv_nt_ref(int m, int n, float alpha_n, float alpha_t, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_svec_ref *sx_n, int xi_n, struct blasfeo_svec_ref *sx_t, int xi_t, float beta_n, float beta_t, struct blasfeo_svec_ref *sy_n, int yi_n, struct blasfeo_svec_ref *sy_t, int yi_t, struct blasfeo_svec_ref *sz_n, int zi_n, struct blasfeo_svec_ref *sz_t, int zi_t); -void blasfeo_ssymv_l_ref(int m, int n, float alpha, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_svec_ref *sx, int xi, float beta, struct blasfeo_svec_ref *sy, int yi, struct blasfeo_svec_ref *sz, int zi); - -// diagonal -void blasfeo_sgemv_d_ref(int m, float alpha, struct blasfeo_svec_ref *sA, int ai, struct blasfeo_svec_ref *sx, int xi, float beta, struct blasfeo_svec_ref *sy, int yi, struct blasfeo_svec_ref *sz, int zi); - - -// --- level 3 - -// dense -void blasfeo_sgemm_nn_ref( int m, int n, int k, float alpha, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_smat_ref *sB, int bi, int bj, float beta, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj); -void blasfeo_sgemm_nt_ref( int m, int n, int k, float alpha, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_smat_ref *sB, int bi, int bj, float beta, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj); -void blasfeo_sgemm_tn_ref(int m, int n, int k, float alpha, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_smat_ref *sB, int bi, int bj, float beta, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj); -void blasfeo_sgemm_tt_ref(int m, int n, int k, float alpha, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_smat_ref *sB, int bi, int bj, float beta, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj); - -void blasfeo_ssyrk_ln_mn_ref( int m, int n, int k, float alpha, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_smat_ref *sB, int bi, int bj, float beta, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj); -void blasfeo_ssyrk_ln_ref( int m, int k, float alpha, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_smat_ref *sB, int bi, int bj, float beta, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj); -void blasfeo_ssyrk_lt_ref( int m, int k, float alpha, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_smat_ref *sB, int bi, int bj, float beta, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj); -void blasfeo_ssyrk_un_ref( int m, int k, float alpha, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_smat_ref *sB, int bi, int bj, float beta, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj); -void blasfeo_ssyrk_ut_ref( int m, int k, float alpha, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_smat_ref *sB, int bi, int bj, float beta, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj); - -void blasfeo_strmm_rutn_ref( int m, int n, float alpha, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_smat_ref *sB, int bi, int bj, struct blasfeo_smat_ref *sD, int di, int dj); -void blasfeo_strmm_rlnn_ref( int m, int n, float alpha, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_smat_ref *sB, int bi, int bj, struct blasfeo_smat_ref *sD, int di, int dj); -void blasfeo_strsm_rltn_ref( int m, int n, float alpha, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_smat_ref *sB, int bi, int bj, struct blasfeo_smat_ref *sD, int di, int dj); -void blasfeo_strsm_rltu_ref( int m, int n, float alpha, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_smat_ref *sB, int bi, int bj, struct blasfeo_smat_ref *sD, int di, int dj); -void blasfeo_strsm_rutn_ref( int m, int n, float alpha, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_smat_ref *sB, int bi, int bj, struct blasfeo_smat_ref *sD, int di, int dj); -void blasfeo_strsm_llnu_ref( int m, int n, float alpha, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_smat_ref *sB, int bi, int bj, struct blasfeo_smat_ref *sD, int di, int dj); -void blasfeo_strsm_lunn_ref( int m, int n, float alpha, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_smat_ref *sB, int bi, int bj, struct blasfeo_smat_ref *sD, int di, int dj); - -// diagonal -void dgemm_diag_left_lib_ref(int m, int n, float alpha, float *dA, float *pB, int sdb, float beta, float *pC, int sdc, float *pD, int sdd); -void blasfeo_sgemm_dn_ref(int m, int n, float alpha, struct blasfeo_svec_ref *sA, int ai, struct blasfeo_smat_ref *sB, int bi, int bj, float beta, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj); -void blasfeo_sgemm_nd_ref(int m, int n, float alpha, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_svec_ref *sB, int bi, float beta, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj); - -// --- lapack - -void blasfeo_sgetrf_nopivot_ref(int m, int n, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj); -void blasfeo_sgetrf_rowpivot_ref(int m, int n, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj, int *ipiv); -void blasfeo_spotrf_l_ref(int m, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj); -void blasfeo_spotrf_l_mn_ref(int m, int n, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj); -void blasfeo_ssyrk_dpotrf_ln_ref(int m, int k, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_smat_ref *sB, int bi, int bj, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj); -void blasfeo_ssyrk_dpotrf_ln_mn_ref(int m, int n, int k, struct blasfeo_smat_ref *sA, int ai, int aj, struct blasfeo_smat_ref *sB, int bi, int bj, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj); -void blasfeo_sgetrf_nopivot_ref(int m, int n, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj); -void blasfeo_sgetrf_rowpivot_ref(int m, int n, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj, int *ipiv); -void blasfeo_sgeqrf_ref(int m, int n, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj, void *work); -void blasfeo_sgelqf_ref(int m, int n, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj, void *work); -void blasfeo_sgelqf_pd_ref(int m, int n, struct blasfeo_smat_ref *sC, int ci, int cj, struct blasfeo_smat_ref *sD, int di, int dj, void *work); -void blasfeo_sgelqf_pd_la_ref(int m, int n1, struct blasfeo_smat_ref *sL, int li, int lj, struct blasfeo_smat_ref *sA, int ai, int aj, void *work); -void blasfeo_sgelqf_pd_lla_ref(int m, int n1, struct blasfeo_smat_ref *sL0, int l0i, int l0j, struct blasfeo_smat_ref *sL1, int l1i, int l1j, struct blasfeo_smat_ref *sA, int ai, int aj, void *work); - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_S_BLASFEO_API_REF_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_s_blasfeo_ref_api.h b/third_party/acados/include/blasfeo/include/blasfeo_s_blasfeo_ref_api.h deleted file mode 100644 index 17cb179695..0000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_s_blasfeo_ref_api.h +++ /dev/null @@ -1,252 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_S_BLASFEO_REF_API_H_ -#define BLASFEO_S_BLASFEO_REF_API_H_ - - - -#include "blasfeo_common.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - -// -// level 1 BLAS -// - -// z = y + alpha*x -void blasfeo_ref_saxpy(int kmax, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); -// z = beta*y + alpha*x -void blasfeo_ref_saxpby(int kmax, float alpha, struct blasfeo_svec *sx, int xi, float beta, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); -// z = x .* y -void blasfeo_ref_svecmul(int m, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); -// z += x .* y -void blasfeo_ref_svecmulacc(int m, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); -// z = x .* y, return sum(z) = x^T * y -float blasfeo_ref_svecmuldot(int m, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); -// return x^T * y -float blasfeo_ref_sdot(int m, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sy, int yi); -// construct givens plane rotation -void blasfeo_ref_srotg(float a, float b, float *c, float *s); -// apply plane rotation [a b] [c -s; s; c] to the aj0 and aj1 columns of A at row index ai -void blasfeo_ref_scolrot(int m, struct blasfeo_smat *sA, int ai, int aj0, int aj1, float c, float s); -// apply plane rotation [c s; -s c] [a; b] to the ai0 and ai1 rows of A at column index aj -void blasfeo_ref_srowrot(int m, struct blasfeo_smat *sA, int ai0, int ai1, int aj, float c, float s); - - - -// -// level 2 BLAS -// - -// dense - -// z <= beta * y + alpha * A * x -void blasfeo_ref_sgemv_n(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, float beta, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); -// z <= beta * y + alpha * A' * x -void blasfeo_ref_sgemv_t(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, float beta, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); -// z <= inv( A ) * x, A (m)x(n) -void blasfeo_ref_strsv_lnn_mn(int m, int n, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= inv( A' ) * x, A (m)x(n) -void blasfeo_ref_strsv_ltn_mn(int m, int n, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= inv( A ) * x, A (m)x(m) lower, not_transposed, not_unit -void blasfeo_ref_strsv_lnn(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= inv( A ) * x, A (m)x(m) lower, not_transposed, unit -void blasfeo_ref_strsv_lnu(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= inv( A' ) * x, A (m)x(m) lower, transposed, not_unit -void blasfeo_ref_strsv_ltn(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= inv( A' ) * x, A (m)x(m) lower, transposed, unit -void blasfeo_ref_strsv_ltu(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= inv( A' ) * x, A (m)x(m) upper, not_transposed, not_unit -void blasfeo_ref_strsv_unn(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= inv( A' ) * x, A (m)x(m) upper, transposed, not_unit -void blasfeo_ref_strsv_utn(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= A * x ; A lower triangular -void blasfeo_ref_strmv_lnn(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= A * x ; A lower triangular, unit diagonal -void blasfeo_ref_strmv_lnu(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= A' * x ; A lower triangular -void blasfeo_ref_strmv_ltn(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= A' * x ; A lower triangular, unit diagonal -void blasfeo_ref_strmv_ltu(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= beta * y + alpha * A * x ; A upper triangular -void blasfeo_ref_strmv_unn(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z <= A' * x ; A upper triangular -void blasfeo_ref_strmv_utn(int m, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sz, int zi); -// z_n <= beta_n * y_n + alpha_n * A * x_n -// z_t <= beta_t * y_t + alpha_t * A' * x_t -void blasfeo_ref_sgemv_nt(int m, int n, float alpha_n, float alpha_t, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx_n, int xi_n, struct blasfeo_svec *sx_t, int xi_t, float beta_n, float beta_t, struct blasfeo_svec *sy_n, int yi_n, struct blasfeo_svec *sy_t, int yi_t, struct blasfeo_svec *sz_n, int zi_n, struct blasfeo_svec *sz_t, int zi_t); -// z <= beta * y + alpha * A * x, where A is symmetric and only the lower triangular patr of A is accessed -void blasfeo_ref_ssymv_l(int m, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, float beta, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); -void blasfeo_ref_ssymv_l_mn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, float beta, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); -// z <= beta * y + alpha * A * x, where A is symmetric and only the upper triangular patr of A is accessed -void blasfeo_ref_ssymv_u(int m, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sx, int xi, float beta, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); -// D = C + alpha * x * y^T -void blasfeo_ref_sger(int m, int n, float alpha, struct blasfeo_svec *sx, int xi, struct blasfeo_svec *sy, int yi, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); - -// diagonal - -// z <= beta * y + alpha * A * x, A diagonal -void blasfeo_ref_sgemv_d(int m, float alpha, struct blasfeo_svec *sA, int ai, struct blasfeo_svec *sx, int xi, float beta, struct blasfeo_svec *sy, int yi, struct blasfeo_svec *sz, int zi); - - - -// -// level 3 BLAS -// - -// dense - -// D <= beta * C + alpha * A * B -void blasfeo_ref_sgemm_nn(int m, int n, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A * B^T -void blasfeo_ref_sgemm_nt(int m, int n, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B -void blasfeo_ref_sgemm_tn(int m, int n, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B -void blasfeo_ref_sgemm_tt(int m, int n, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A * B^T ; C, D lower triangular -void blasfeo_ref_ssyrk_ln(int m, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -void blasfeo_ref_ssyrk_ln_mn(int m, int n, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B ; C, D lower triangular -void blasfeo_ref_ssyrk_lt(int m, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A * B^T ; C, D upper triangular -void blasfeo_ref_ssyrk_un(int m, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B ; C, D upper triangular -void blasfeo_ref_ssyrk_ut(int m, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * B * A^T ; B upper triangular -void blasfeo_ref_strmm_rutn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * B * A ; A lower triangular -void blasfeo_ref_strmm_rlnn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * A^{-1} * B , with A lower triangular employint explicit inverse of diagonal -void blasfeo_ref_strsm_llnn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * A^{-1} * B , with A lower triangular with unit diagonal -void blasfeo_ref_strsm_llnu(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * A^{-T} * B , with A lower triangular employint explicit inverse of diagonal -void blasfeo_ref_strsm_lltn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * A^{-T} * B , with A lower triangular with unit diagonal -void blasfeo_ref_strsm_lltu(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * A^{-1} * B , with A upper triangular employing explicit inverse of diagonal -void blasfeo_ref_strsm_lunn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * A^{-1} * B , with A upper triangular withunit diagonal -void blasfeo_ref_strsm_lunu(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * A^{-T} * B , with A upper triangular employing explicit inverse of diagonal -void blasfeo_ref_strsm_lutn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * A^{-T} * B , with A upper triangular withunit diagonal -void blasfeo_ref_strsm_lutu(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * B * A^{-1} , with A lower triangular employing explicit inverse of diagonal -void blasfeo_ref_strsm_rlnn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * B * A^{-1} , with A lower triangular with unit diagonal -void blasfeo_ref_strsm_rlnu(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * B * A^{-T} , with A lower triangular employing explicit inverse of diagonal -void blasfeo_ref_strsm_rltn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * B * A^{-T} , with A lower triangular with unit diagonal -void blasfeo_ref_strsm_rltu(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * B * A^{-1} , with A upper triangular employing explicit inverse of diagonal -void blasfeo_ref_strsm_runn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * B * A^{-1} , with A upper triangular with unit diagonal -void blasfeo_ref_strsm_runu(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * B * A^{-T} , with A upper triangular employing explicit inverse of diagonal -void blasfeo_ref_strsm_rutn(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * B * A^{-T} , with A upper triangular with unit diagonal -void blasfeo_ref_strsm_rutu(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A * B^T + alpha * B * A^T ; C, D lower triangular -void blasfeo_ref_ssyr2k_ln(int m, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B + alpha * B^T * A ; C, D lower triangular -void blasfeo_ref_ssyr2k_lt(int m, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A * B^T + alpha * B * A^T ; C, D upper triangular -void blasfeo_ref_ssyr2k_un(int m, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= beta * C + alpha * A^T * B + alpha * B^T * A ; C, D upper triangular -void blasfeo_ref_ssyr2k_ut(int m, int k, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); - -// diagonal - -// D <= alpha * A * B + beta * C, with A diagonal (stored as strvec) -void sgemm_diag_left_ib(int m, int n, float alpha, float *dA, float *pB, int sdb, float beta, float *pC, int sdc, float *pD, int sdd); -void blasfeo_ref_sgemm_dn(int m, int n, float alpha, struct blasfeo_svec *sA, int ai, struct blasfeo_smat *sB, int bi, int bj, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= alpha * A * B + beta * C, with B diagonal (stored as strvec) -void blasfeo_ref_sgemm_nd(int m, int n, float alpha, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_svec *sB, int bi, float beta, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); - - - -// -// LAPACK -// - -// D <= chol( C ) ; C, D lower triangular -void blasfeo_ref_spotrf_l(int m, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -void blasfeo_ref_spotrf_l_mn(int m, int n, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= chol( C ) ; C, D upper triangular -void blasfeo_ref_spotrf_u(int m, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= chol( C + A * B' ) ; C, D lower triangular -void blasfeo_ref_ssyrk_spotrf_ln(int m, int k, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -void blasfeo_ref_ssyrk_spotrf_ln_mn(int m, int n, int k, struct blasfeo_smat *sA, int ai, int aj, struct blasfeo_smat *sB, int bi, int bj, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= lu( C ) ; no pivoting -void blasfeo_ref_sgetrf_np(int m, int n, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj); -// D <= lu( C ) ; row pivoting -void blasfeo_ref_sgetrf_rp(int m, int n, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj, int *ipiv); -// D <= qr( C ) -void blasfeo_ref_sgeqrf(int m, int n, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj, void *work); -int blasfeo_ref_sgeqrf_worksize(int m, int n); // in bytes -// D <= Q factor, where C is the output of the LQ factorization -int blasfeo_ref_sorglq_worksize(int m, int n, int k); // in bytes -void blasfeo_ref_sorglq(int m, int n, int k, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj, void *work); -// D <= lq( C ) -void blasfeo_ref_sgelqf(int m, int n, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj, void *work); -int blasfeo_ref_sgelqf_worksize(int m, int n); // in bytes -// D <= lq( C ), positive diagonal elements -void blasfeo_ref_sgelqf_pd(int m, int n, struct blasfeo_smat *sC, int ci, int cj, struct blasfeo_smat *sD, int di, int dj, void *work); -// [L, A] <= lq( [L, A] ), positive diagonal elements, array of matrices, with -// L lower triangular, of size (m)x(m) -// A full, of size (m)x(n1) -void blasfeo_ref_sgelqf_pd_la(int m, int n1, struct blasfeo_smat *sL, int li, int lj, struct blasfeo_smat *sA, int ai, int aj, void *work); -// [L, L, A] <= lq( [L, L, A] ), positive diagonal elements, array of matrices, with: -// L lower triangular, of size (m)x(m) -// A full, of size (m)x(n1) -void blasfeo_ref_sgelqf_pd_lla(int m, int n1, struct blasfeo_smat *sL0, int l0i, int l0j, struct blasfeo_smat *sL1, int l1i, int l1j, struct blasfeo_smat *sA, int ai, int aj, void *work); - - - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_S_BLASFEO_REF_API_H_ - diff --git a/third_party/acados/include/blasfeo/include/blasfeo_s_kernel.h b/third_party/acados/include/blasfeo/include/blasfeo_s_kernel.h deleted file mode 100644 index 99d2b28c82..0000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_s_kernel.h +++ /dev/null @@ -1,692 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_S_KERNEL_H_ -#define BLASFEO_S_KERNEL_H_ - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// utils -void blasfeo_align_2MB(void *ptr, void **ptr_align); -void blasfeo_align_4096_byte(void *ptr, void **ptr_align); -void blasfeo_align_64_byte(void *ptr, void **ptr_align); - - - -// -// lib8 -// - -// 24x4 -void kernel_sgemm_nt_24x4_lib8(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd); -void kernel_sgemm_nt_24x4_vs_lib8(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd, int km, int kn); -void kernel_sgemm_nt_24x4_gen_lib8(int k, float *alpha, float *A, int sda, float *B, float *beta, int offsetC, float *C, int sdc, int offsetD, float *D, int sdd, int m0, int m1, int n0, int n1); -void kernel_sgemm_nn_24x4_lib8(int k, float *alpha, float *A, int sda, int offsetB, float *B, int sdb, float *beta, float *C, int sdc, float *D, int sdd); -void kernel_sgemm_nn_24x4_vs_lib8(int k, float *alpha, float *A, int sda, int offsetB, float *B, int sdb, float *beta, float *C, int sdc, float *D, int sdd, int km, int kn); -void kernel_sgemm_nn_24x4_gen_lib8(int k, float *alpha, float *A, int sda, int offsetB, float *B, int sdb, float *beta, int offsetC, float *C, int sdc, int offsetD, float *D, int sdd, int m0, int m1, int n0, int n1); -void kernel_ssyrk_nt_l_24x4_lib8(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd); -void kernel_ssyrk_nt_l_24x4_vs_lib8(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd, int km, int kn); -void kernel_ssyrk_nt_l_20x4_lib8(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd); -void kernel_ssyrk_nt_l_20x4_vs_lib8(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd, int km, int kn); -void kernel_spotrf_nt_l_24x4_lib8(int k, float *A, int sda, float *B, float *C, int sdc, float *D, int sdd, float *inv_diag_D); -void kernel_spotrf_nt_l_24x4_vs_lib8(int k, float *A, int sda, float *B, float *C, int sdc, float *D, int sdd, float *inv_diag_D, int km, int kn); -void kernel_spotrf_nt_l_20x4_lib8(int k, float *A, int sda, float *B, float *C, int sdc, float *D, int sdd, float *inv_diag_D); -void kernel_spotrf_nt_l_20x4_vs_lib8(int k, float *A, int sda, float *B, float *C, int sdc, float *D, int sdd, float *inv_diag_D, int km, int kn); -void kernel_strsm_nt_rl_inv_24x4_lib8(int k, float *A, int sda, float *B, float *C, int sdc, float *D, int sdd, float *E, float *inv_diag_E); -void kernel_strsm_nt_rl_inv_24x4_vs_lib8(int k, float *A, int sda, float *B, float *C, int sdc, float *D, int sdd, float *E, float *inv_diag_E, int km, int kn); -void kernel_sgemm_strsm_nt_rl_inv_24x4_lib8(int kp, float *Ap, int sdap, float *Bp, int km_, float *Am, int sdam, float *Bm, float *C, int sdc, float *D, int sdd, float *E, float *inv_diag_E); -void kernel_sgemm_strsm_nt_rl_inv_24x4_vs_lib8(int kp, float *Ap, int sdap, float *Bp, int km_, float *Am, int sdam, float *Bm, float *C, int sdc, float *D, int sdd, float *E, float *inv_diag_E, int km, int kn); -void kernel_ssyrk_spotrf_nt_l_20x4_vs_lib8(int kp, float *Ap, int sdap, float *Bp, int km_, float *Am, int sdam, float *Bm, float *C, int sdc, float *D, int sdd, float *inv_diag_D, int km, int kn); -void kernel_ssyrk_spotrf_nt_l_20x4_lib8(int kp, float *Ap, int sdap, float *Bp, int km_, float *Am, int sdam, float *Bm, float *C, int sdc, float *D, int sdd, float *inv_diag_D); -void kernel_ssyrk_spotrf_nt_l_24x4_vs_lib8(int kp, float *Ap, int sdap, float *Bp, int km_, float *Am, int sdam, float *Bm, float *C, int sdc, float *D, int sdd, float *inv_diag_D, int km, int kn); -void kernel_ssyrk_spotrf_nt_l_24x4_lib8(int kp, float *Ap, int sdap, float *Bp, int km_, float *Am, int sdam, float *Bm, float *C, int sdc, float *D, int sdd, float *inv_diag_D); -void kernel_strmm_nn_rl_24x4_lib8(int k, float *alpha, float *A, int sda, int offsetB, float *B, int sdb, float *D, int sdd); -void kernel_strmm_nn_rl_24x4_vs_lib8(int k, float *alpha, float *A, int sda, int offsetB, float *B, int sdb, float *D, int sdd, int km, int kn); - -// 16x8 -void kernel_sgemm_nt_16x8_lib8(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd, float *spil); - -// 16x4 -void kernel_sgemm_nt_16x4_lib8(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd); -void kernel_sgemm_nt_16x4_vs_lib8(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd, int km, int kn); -void kernel_sgemm_nt_16x4_gen_lib8(int k, float *alpha, float *A, int sda, float *B, float *beta, int offsetC, float *C, int sdc, int offsetD, float *D, int sdd, int m0, int m1, int n0, int n1); -void kernel_sgemm_nn_16x4_lib8(int k, float *alpha, float *A, int sda, int offsetB, float *B, int sdb, float *beta, float *C, int sdc, float *D, int sdd); -void kernel_sgemm_nn_16x4_vs_lib8(int k, float *alpha, float *A, int sda, int offsetB, float *B, int sdb, float *beta, float *C, int sdc, float *D, int sdd, int km, int kn); -void kernel_sgemm_nn_16x4_gen_lib8(int k, float *alpha, float *A, int sda, int offsetB, float *B, int sdb, float *beta, int offsetC, float *C, int sdc, int offsetD, float *D, int sdd, int m0, int m1, int n0, int n1); -void kernel_ssyrk_nt_l_16x4_lib8(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd); -void kernel_ssyrk_nt_l_16x4_vs_lib8(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd, int km, int kn); -void kernel_ssyrk_nt_l_12x4_lib8(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd); -void kernel_ssyrk_nt_l_12x4_vs_lib8(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd, int km, int kn); -void kernel_spotrf_nt_l_16x4_lib8(int k, float *A, int sda, float *B, float *C, int sdc, float *D, int sdd, float *inv_diag_D); -void kernel_spotrf_nt_l_16x4_vs_lib8(int k, float *A, int sda, float *B, float *C, int sdc, float *D, int sdd, float *inv_diag_D, int km, int kn); -void kernel_spotrf_nt_l_12x4_lib8(int k, float *A, int sda, float *B, float *C, int sdc, float *D, int sdd, float *inv_diag_D); -void kernel_spotrf_nt_l_12x4_vs_lib8(int k, float *A, int sda, float *B, float *C, int sdc, float *D, int sdd, float *inv_diag_D, int km, int kn); -void kernel_strsm_nt_rl_inv_16x4_lib8(int k, float *A, int sda, float *B, float *C, int sdc, float *D, int sdd, float *E, float *inv_diag_E); -void kernel_strsm_nt_rl_inv_16x4_vs_lib8(int k, float *A, int sda, float *B, float *C, int sdc, float *D, int sdd, float *E, float *inv_diag_E, int km, int kn); -void kernel_sgemm_strsm_nt_rl_inv_16x4_lib8(int kp, float *Ap, int sdap, float *Bp, int km_, float *Am, int sdam, float *Bm, float *C, int sdc, float *D, int sdd, float *E, float *inv_diag_E); -void kernel_sgemm_strsm_nt_rl_inv_16x4_vs_lib8(int kp, float *Ap, int sdap, float *Bp, int km_, float *Am, int sdam, float *Bm, float *C, int sdc, float *D, int sdd, float *E, float *inv_diag_E, int km, int kn); -void kernel_ssyrk_spotrf_nt_l_12x4_vs_lib8(int kp, float *Ap, int sdap, float *Bp, int km_, float *Am, int sdam, float *Bm, float *C, int sdc, float *D, int sdd, float *inv_diag_D, int km, int kn); -void kernel_ssyrk_spotrf_nt_l_12x4_lib8(int kp, float *Ap, int sdap, float *Bp, int km_, float *Am, int sdam, float *Bm, float *C, int sdc, float *D, int sdd, float *inv_diag_D); -void kernel_ssyrk_spotrf_nt_l_16x4_vs_lib8(int kp, float *Ap, int sdap, float *Bp, int km_, float *Am, int sdam, float *Bm, float *C, int sdc, float *D, int sdd, float *inv_diag_D, int km, int kn); -void kernel_ssyrk_spotrf_nt_l_16x4_lib8(int kp, float *Ap, int sdap, float *Bp, int km_, float *Am, int sdam, float *Bm, float *C, int sdc, float *D, int sdd, float *inv_diag_D); -void kernel_strmm_nn_rl_16x4_lib8(int k, float *alpha, float *A, int sda, int offsetB, float *B, int sdb, float *D, int sdd); -void kernel_strmm_nn_rl_16x4_vs_lib8(int k, float *alpha, float *A, int sda, int offsetB, float *B, int sdb, float *D, int sdd, int km, int kn); -void kernel_strmm_nn_rl_16x4_gen_lib8(int k, float *alpha, float *A, int sda, int offsetB, float *B, int sdb, int offsetD, float *D, int sdd, int m0, int m1, int n0, int n1); - -// 8x8 -void kernel_sgemm_nt_8x8_lib8(int k, float *alpha, float *A, float *B, float *beta, float *C, float *D); -void kernel_sgemm_nt_8x8_vs_lib8(int k, float *alpha, float *A, float *B, float *beta, float *C, float *D, int km, int kn); -void kernel_sgemm_nt_8x8_gen_lib8(int k, float *alpha, float *A, float *B, float *beta, int offsetC, float *C, int sdc, int offsetD, float *D, int sdd, int m0, int m1, int n0, int n1); -void kernel_sgemm_nn_8x8_lib8(int k, float *alpha, float *A, int offsetB, float *B, int sdb, float *beta, float *C, float *D); -void kernel_sgemm_nn_8x8_vs_lib8(int k, float *alpha, float *A, int offsetB, float *B, int sdb, float *beta, float *C, float *D, int km, int kn); -void kernel_sgemm_nn_8x8_gen_lib8(int k, float *alpha, float *A, int offsetB, float *B, int sdb, float *beta, int offsetC, float *C, int sdc, int offsetD, float *D, int sdd, int m0, int m1, int n0, int n1); -void kernel_ssyrk_nt_l_8x8_lib8(int k, float *alpha, float *A, float *B, float *beta, float *C, float *D); -void kernel_ssyrk_nt_l_8x8_vs_lib8(int k, float *alpha, float *A, float *B, float *beta, float *C, float *D, int km, int kn); -void kernel_spotrf_nt_l_8x8_lib8(int k, float *A, float *B, float *C, float *D, float *inv_diag_D); -void kernel_spotrf_nt_l_8x8_vs_lib8(int k, float *A, float *B, float *C, float *D, float *inv_diag_D, int km, int kn); -void kernel_strsm_nt_rl_inv_8x8_lib8(int k, float *A, float *B, float *C, float *D, float *E, float *inv_diag_E); -void kernel_strsm_nt_rl_inv_8x8_vs_lib8(int k, float *A, float *B, float *C, float *D, float *E, float *inv_diag_E, int km, int kn); -void kernel_sgemm_strsm_nt_rl_inv_8x8_lib8(int kp, float *Ap, float *Bp, int km_, float *Am, float *Bm, float *C, float *D, float *E, float *inv_diag_E); -void kernel_sgemm_strsm_nt_rl_inv_8x8_vs_lib8(int kp, float *Ap, float *Bp, int km_, float *Am, float *Bm, float *C, float *D, float *E, float *inv_diag_E, int km, int kn); -void kernel_ssyrk_spotrf_nt_l_8x8_vs_lib8(int kp, float *Ap, float *Bp, int km_, float *Am, float *Bm, float *C, float *D, float *inv_diag_D, int km, int kn); -void kernel_ssyrk_spotrf_nt_l_8x8_lib8(int kp, float *Ap, float *Bp, int km_, float *Am, float *Bm, float *C, float *D, float *inv_diag_D); - -// 8x4 -void kernel_sgemm_nt_8x4_lib8(int k, float *alpha, float *A, float *B, float *beta, float *C, float *D); -void kernel_sgemm_nt_8x4_vs_lib8(int k, float *alpha, float *A, float *B, float *beta, float *C, float *D, int km, int kn); -void kernel_sgemm_nt_8x4_gen_lib8(int k, float *alpha, float *A, float *B, float *beta, int offsetC, float *C, int sdc, int offsetD, float *D, int sdd, int m0, int m1, int n0, int n1); -void kernel_sgemm_nn_8x4_lib8(int k, float *alpha, float *A, int offsetB, float *B, int sdb, float *beta, float *C, float *D); -void kernel_sgemm_nn_8x4_vs_lib8(int k, float *alpha, float *A, int offsetB, float *B, int sdb, float *beta, float *C, float *D, int km, int kn); -void kernel_sgemm_nn_8x4_gen_lib8(int k, float *alpha, float *A, int offsetB, float *B, int sdb, float *beta, int offsetC, float *C, int sdc, int offsetD, float *D, int sdd, int m0, int m1, int n0, int n1); -//void kernel_ssyrk_nt_l_8x4_lib8(int k, float *alpha, float *A, float *B, float *beta, float *C, float *D); -void kernel_ssyrk_nt_l_8x4_vs_lib8(int k, float *alpha, float *A, float *B, float *beta, float *C, float *D, int km, int kn); -void kernel_spotrf_nt_l_8x4_lib8(int k, float *A, float *B, float *C, float *D, float *inv_diag_D); -void kernel_spotrf_nt_l_8x4_vs_lib8(int k, float *A, float *B, float *C, float *D, float *inv_diag_D, int km, int kn); -void kernel_strsm_nt_rl_inv_8x4_lib8(int k, float *A, float *B, float *C, float *D, float *E, float *inv_diag_E); -void kernel_strsm_nt_rl_inv_8x4_vs_lib8(int k, float *A, float *B, float *C, float *D, float *E, float *inv_diag_E, int km, int kn); -void kernel_sgemm_strsm_nt_rl_inv_8x4_lib8(int kp, float *Ap, float *Bp, int km_, float *Am, float *Bm, float *C, float *D, float *E, float *inv_diag_E); -void kernel_sgemm_strsm_nt_rl_inv_8x4_vs_lib8(int kp, float *Ap, float *Bp, int km_, float *Am, float *Bm, float *C, float *D, float *E, float *inv_diag_E, int km, int kn); -void kernel_ssyrk_spotrf_nt_l_8x4_vs_lib8(int kp, float *Ap, float *Bp, int km_, float *Am, float *Bm, float *C, float *D, float *inv_diag_D, int km, int kn); -void kernel_ssyrk_spotrf_nt_l_8x4_lib8(int kp, float *Ap, float *Bp, int km_, float *Am, float *Bm, float *C, float *D, float *inv_diag_D); -void kernel_strmm_nn_rl_8x4_lib8(int k, float *alpha, float *A, int offsetB, float *B, int sdb, float *D); -void kernel_strmm_nn_rl_8x4_vs_lib8(int k, float *alpha, float *A, int offsetB, float *B, int sdb, float *D, int km, int kn); -void kernel_strmm_nn_rl_8x4_gen_lib8(int k, float *alpha, float *A, int offsetB, float *B, int sdb, int offsetD, float *D, int sdd, int m0, int m1, int n0, int n1); -void kernel_strmm_nt_ru_8x4_lib8(int k, float *alpha, float *A, float *B, float *D); -void kernel_strmm_nt_ru_8x4_vs_lib8(int k, float *alpha, float *A, float *B, float *D, int km, int kn); - -// 4x8 -void kernel_sgemm_nt_4x8_lib8(int k, float *alpha, float *A, float *B, float *beta, float *C, float *D); -void kernel_sgemm_nt_4x8_vs_lib8(int k, float *alpha, float *A, float *B, float *beta, float *C, float *D, int km, int kn); -void kernel_sgemm_nt_4x8_gen_lib8(int k, float *alpha, float *A, float *B, float *beta, int offsetC, float *C, int sdc, int offsetD, float *D, int sdd, int m0, int m1, int n0, int n1); -void kernel_strsm_nt_rl_inv_4x8_lib8(int k, float *A, float *B, float *C, float *D, float *E, float *inv_diag_E); -void kernel_strsm_nt_rl_inv_4x8_vs_lib8(int k, float *A, float *B, float *C, float *D, float *E, float *inv_diag_E, int km, int kn); - -// 8 -void kernel_sgemv_n_8_lib8(int k, float *alpha, float *A, float *x, float *beta, float *y, float *z); -void kernel_sgemv_n_8_vs_lib8(int k, float *alpha, float *A, float *x, float *beta, float *y, float *z, int k1); -void kernel_sgemv_n_8_gen_lib8(int kmax, float *alpha, float *A, float *x, float *beta, float *y, float *z, int k0, int k1); -void kernel_sgemv_t_8_lib8(int k, float *alpha, int offsetA, float *A, int sda, float *x, float *beta, float *y, float *z); -void kernel_sgemv_t_8_vs_lib8(int k, float *alpha, int offsetA, float *A, int sda, float *x, float *beta, float *y, float *z, int k1); -void kernel_sgemv_t_4_lib8(int k, float *alpha, int offsetA, float *A, int sda, float *x, float *beta, float *y, float *z); -void kernel_sgemv_t_4_vs_lib8(int k, float *alpha, int offsetA, float *A, int sda, float *x, float *beta, float *y, float *z, int k1); -void kernel_strsv_ln_inv_8_lib8(int k, float *A, float *inv_diag_A, float *x, float *y, float *z); -void kernel_strsv_ln_inv_8_vs_lib8(int k, float *A, float *inv_diag_A, float *x, float *y, float *z, int km, int kn); -void kernel_strsv_lt_inv_8_lib8(int k, float *A, int sda, float *inv_diag_A, float *x, float *y, float *z); -void kernel_strsv_lt_inv_8_vs_lib8(int k, float *A, int sda, float *inv_diag_A, float *x, float *y, float *z, int km, int kn); -void kernel_sgemv_nt_4_lib8(int kmax, float *alpha_n, float *alpha_t, float *A, int sda, float *x_n, float *x_t, float *beta_t, float *y_t, float *z_n, float *z_t); -void kernel_sgemv_nt_4_vs_lib8(int kmax, float *alpha_n, float *alpha_t, float *A, int sda, float *x_n, float *x_t, float *beta_t, float *y_t, float *z_n, float *z_t, int km); -void kernel_ssymv_l_4l_lib8(int kmax, float *alpha, float *A, int sda, float *x, float *z); -void kernel_ssymv_l_4r_lib8(int kmax, float *alpha, float *A, int sda, float *x, float *z); -void kernel_ssymv_l_4l_gen_lib8(int kmax, float *alpha, int offA, float *A, int sda, float *x, float *z, int km); -void kernel_ssymv_l_4r_gen_lib8(int kmax, float *alpha, int offA, float *A, int sda, float *x, float *z, int km); - -// -------- aux - -// ---- copy - -// lib4 -// -void kernel_sgecpsc_4_0_lib4(int kmax, float *alpha, float *A, float *B); -void kernel_sgecp_4_0_lib4(int kmax, float *A, float *B); - -void kernel_sgecpsc_4_1_lib4(int kmax, float *alpha, float *A0, int sda, float *B); -void kernel_sgecp_4_1_lib4(int kmax, float *A0, int sda, float *B); -void kernel_sgecpsc_4_2_lib4(int kmax, float *alpha, float *A0, int sda, float *B); -void kernel_sgecp_4_2_lib4(int kmax, float *A0, int sda, float *B); -void kernel_sgecpsc_4_3_lib4(int kmax, float *alpha, float *A0, int sda, float *B); -void kernel_sgecp_4_3_lib4(int kmax, float *A0, int sda, float *B); - -void kernel_sgecpsc_3_0_lib4(int kmax, float *alpha, float *A, float *B); -void kernel_sgecp_3_0_lib4(int kmax, float *A, float *B); -void kernel_sgecpsc_3_2_lib4(int kmax, float *alpha, float *A0, int sda, float *B); -void kernel_sgecp_3_2_lib4(int kmax, float *A0, int sda, float *B); -void kernel_sgecpsc_3_3_lib4(int kmax, float *alpha, float *A0, int sda, float *B); -void kernel_sgecp_3_3_lib4(int kmax, float *A0, int sda, float *B); - -void kernel_sgecpsc_2_0_lib4(int kmax, float *alpha, float *A, float *B); -void kernel_sgecp_2_0_lib4(int kmax, float *A, float *B); -void kernel_sgecpsc_2_3_lib4(int kmax, float *alpha, float *A0, int sda, float *B); -void kernel_sgecp_2_3_lib4(int kmax, float *A0, int sda, float *B); - -void kernel_sgecpsc_1_0_lib4(int kmax, float *alpha, float *A, float *B); -void kernel_sgecp_1_0_lib4(int kmax, float *A, float *B); - -// lib8 -// -void kernel_sgecp_8_0_lib8(int m, float *A, float *B); -void kernel_sgecp_8_0_gen_lib8(int m, float *A, float *B, int m1); -void kernel_sgecp_8_0_gen_u_lib8(int m, float *A, float *B, int m1); - -void kernel_sgesc_8_0_lib8(int m, float *alpha, float *A); -void kernel_sgesc_8_0_gen_lib8(int m, float *alpha, float *A, int m1); -void kernel_sgesc_8_0_gen_u_lib8(int m, float *alpha, float *A, int m1); - -void kernel_sgecpsc_8_0_lib8(int m, float *alpha, float *A, float *B); -void kernel_sgecpsc_8_0_gen_lib8(int m, float *alpha, float *A, float *B, int m1); -void kernel_sgecpsc_8_0_gen_u_lib8(int m, float *alpha, float *A, float *B, int m1); - -void kernel_sgecp_8_1_lib8(int m, float *A, int sda, float *B); -void kernel_sgecp_8_1_gen_lib8(int m, float *A, int sda, float *B, int m1); -void kernel_sgecpsc_8_1_lib8(int m, float *alpha, float *A, int sda, float *B); -void kernel_sgecpsc_8_1_gen_lib8(int m, float *alpha, float *A, int sda, float *B, int m1); - -void kernel_sgecp_8_2_lib8(int m, float *A, int sda, float *B); -void kernel_sgecp_8_2_gen_lib8(int m, float *A, int sda, float *B, int m1); -void kernel_sgecpsc_8_2_lib8(int m, float *alpha, float *A, int sda, float *B); -void kernel_sgecpsc_8_2_gen_lib8(int m, float *alpha, float *A, int sda, float *B, int m1); - -void kernel_sgecp_8_3_lib8(int m, float *A, int sda, float *B); -void kernel_sgecp_8_3_gen_lib8(int m, float *A, int sda, float *B, int m1); -void kernel_sgecpsc_8_3_lib8(int m, float *alpha, float *A, int sda, float *B); -void kernel_sgecpsc_8_3_gen_lib8(int m, float *alpha, float *A, int sda, float *B, int m1); - -void kernel_sgecp_8_4_lib8(int m, float *A, int sda, float *B); -void kernel_sgecp_8_4_gen_lib8(int m, float *A, int sda, float *B, int m1); -void kernel_sgecpsc_8_4_lib8(int m, float *alpha, float *A, int sda, float *B); -void kernel_sgecpsc_8_4_gen_lib8(int m, float *alpha, float *A, int sda, float *B, int m1); - -void kernel_sgecp_8_5_lib8(int m, float *A, int sda, float *B); -void kernel_sgecp_8_5_gen_lib8(int m, float *A, int sda, float *B, int m1); -void kernel_sgecpsc_8_5_lib8(int m, float *alpha, float *A, int sda, float *B); -void kernel_sgecpsc_8_5_gen_lib8(int m, float *alpha, float *A, int sda, float *B, int m1); - -void kernel_sgecp_8_6_lib8(int m, float *A, int sda, float *B); -void kernel_sgecp_8_6_gen_lib8(int m, float *A, int sda, float *B, int m1); -void kernel_sgecpsc_8_6_lib8(int m, float *alpha, float *A, int sda, float *B); -void kernel_sgecpsc_8_6_gen_lib8(int m, float *alpha, float *A, int sda, float *B, int m1); - -void kernel_sgecp_8_7_lib8(int m, float *A, int sda, float *B); -void kernel_sgecp_8_7_gen_lib8(int m, float *A, int sda, float *B, int m1); -void kernel_sgecpsc_8_7_lib8(int m, float *alpha, float *A, int sda, float *B); -void kernel_sgecpsc_8_7_gen_lib8(int m, float *alpha, float *A, int sda, float *B, int m1); - -// transpose -// -void kernel_sgetr_8_0_lib8(int m, float *A, int sda, float *B); -void kernel_sgetr_8_0_gen_lib8(int m, float *A, int sda, float *B, int m1); -void kernel_sgetr_8_1_lib8(int m, float *A, int sda, float *B); -void kernel_sgetr_8_1_gen_lib8(int m, float *A, int sda, float *B, int m1); -void kernel_sgetr_8_2_lib8(int m, float *A, int sda, float *B); -void kernel_sgetr_8_2_gen_lib8(int m, float *A, int sda, float *B, int m1); -void kernel_sgetr_8_3_lib8(int m, float *A, int sda, float *B); -void kernel_sgetr_8_3_gen_lib8(int m, float *A, int sda, float *B, int m1); -void kernel_sgetr_8_4_lib8(int m, float *A, int sda, float *B); -void kernel_sgetr_8_4_gen_lib8(int m, float *A, int sda, float *B, int m1); -void kernel_sgetr_8_5_lib8(int m, float *A, int sda, float *B); -void kernel_sgetr_8_5_gen_lib8(int m, float *A, int sda, float *B, int m1); -void kernel_sgetr_8_6_lib8(int m, float *A, int sda, float *B); -void kernel_sgetr_8_6_gen_lib8(int m, float *A, int sda, float *B, int m1); -void kernel_sgetr_8_7_lib8(int m, float *A, int sda, float *B); -void kernel_sgetr_8_7_gen_lib8(int m, float *A, int sda, float *B, int m1); - -// add -// -void kernel_sgead_8_0_lib8(int m, float *alpha, float *A, float *B); -void kernel_sgead_8_0_gen_lib8(int m, float *alpha, float *A, float *B, int m1); -void kernel_sgead_8_1_lib8(int m, float *alpha, float *A, int sda, float *B); -void kernel_sgead_8_1_gen_lib8(int m, float *alpha, float *A, int sda, float *B, int m1); -void kernel_sgead_8_2_lib8(int m, float *alpha, float *A, int sda, float *B); -void kernel_sgead_8_2_gen_lib8(int m, float *alpha, float *A, int sda, float *B, int m1); -void kernel_sgead_8_3_lib8(int m, float *alpha, float *A, int sda, float *B); -void kernel_sgead_8_3_gen_lib8(int m, float *alpha, float *A, int sda, float *B, int m1); -void kernel_sgead_8_4_lib8(int m, float *alpha, float *A, int sda, float *B); -void kernel_sgead_8_4_gen_lib8(int m, float *alpha, float *A, int sda, float *B, int m1); -void kernel_sgead_8_5_lib8(int m, float *alpha, float *A, int sda, float *B); -void kernel_sgead_8_5_gen_lib8(int m, float *alpha, float *A, int sda, float *B, int m1); -void kernel_sgead_8_6_lib8(int m, float *alpha, float *A, int sda, float *B); -void kernel_sgead_8_6_gen_lib8(int m, float *alpha, float *A, int sda, float *B, int m1); -void kernel_sgead_8_7_lib8(int m, float *alpha, float *A, int sda, float *B); -void kernel_sgead_8_7_gen_lib8(int m, float *alpha, float *A, int sda, float *B, int m1); - - -// -// lib4 -// - - - -// level 2 BLAS -// 4 -void kernel_sgemv_n_4_lib4(int k, float *alpha, float *A, float *x, float *beta, float *y, float *z); -void kernel_sgemv_n_4_vs_lib4(int k, float *alpha, float *A, float *x, float *beta, float *y, float *z, int k1); -void kernel_sgemv_n_4_gen_lib4(int kmax, float *alpha, float *A, float *x, float *beta, float *y, float *z, int k0, int k1); -void kernel_sgemv_t_4_lib4(int k, float *alpha, int offsetA, float *A, int sda, float *x, float *beta, float *y, float *z); -void kernel_sgemv_t_4_vs_lib4(int k, float *alpha, int offsetA, float *A, int sda, float *x, float *beta, float *y, float *z, int k1); -void kernel_strsv_ln_inv_4_lib4(int k, float *A, float *inv_diag_A, float *x, float *y, float *z); -void kernel_strsv_ln_inv_4_vs_lib4(int k, float *A, float *inv_diag_A, float *x, float *y, float *z, int km, int kn); -void kernel_strsv_lt_inv_4_lib4(int k, float *A, int sda, float *inv_diag_A, float *x, float *y, float *z); -void kernel_strsv_lt_inv_3_lib4(int k, float *A, int sda, float *inv_diag_A, float *x, float *y, float *z); -void kernel_strsv_lt_inv_2_lib4(int k, float *A, int sda, float *inv_diag_A, float *x, float *y, float *z); -void kernel_strsv_lt_inv_1_lib4(int k, float *A, int sda, float *inv_diag_A, float *x, float *y, float *z); -void kernel_strmv_un_4_lib4(int k, float *A, float *x, float *z); -void kernel_strmv_ut_4_lib4(int k, float *A, int sda, float *x, float *z); -void kernel_strmv_ut_4_vs_lib4(int k, float *A, int sda, float *x, float *z, int km); -void kernel_sgemv_nt_6_lib4(int kmax, float *alpha_n, float *alpha_t, float *A, int sda, float *x_n, float *x_t, float *beta_t, float *y_t, float *z_n, float *z_t); -void kernel_sgemv_nt_4_lib4(int kmax, float *alpha_n, float *alpha_t, float *A, int sda, float *x_n, float *x_t, float *beta_t, float *y_t, float *z_n, float *z_t); -void kernel_sgemv_nt_4_vs_lib4(int kmax, float *alpha_n, float *alpha_t, float *A, int sda, float *x_n, float *x_t, float *beta_t, float *y_t, float *z_n, float *z_t, int km); -void kernel_ssymv_l_4_lib4(int kmax, float *alpha, float *A, int sda, float *x_n, float *z_n); -void kernel_ssymv_l_4_gen_lib4(int kmax, float *alpha, int offA, float *A, int sda, float *x_n, float *z_n, int km); - - - -// level 3 BLAS -// 12x4 -void kernel_sgemm_nt_16x4_lib4(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd); // -void kernel_sgemm_nt_16x4_vs_lib4(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd, int m1, int n1); // -void kernel_strsm_nt_rl_inv_16x4_lib4(int k, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd, float *E, float *inv_diag_E); -void kernel_strsm_nt_rl_inv_16x4_vs_lib4(int k, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd, float *E, float *inv_diag_E, int m1, int n1); -// 12x4 -void kernel_sgemm_nt_12x4_lib4(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd); // -void kernel_sgemm_nt_12x4_vs_lib4(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd, int m1, int n1); // -void kernel_strsm_nt_rl_inv_12x4_lib4(int k, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd, float *E, float *inv_diag_E); -void kernel_strsm_nt_rl_inv_12x4_vs_lib4(int k, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd, float *E, float *inv_diag_E, int m1, int n1); -// 8x8 -void kernel_sgemm_nt_8x8_lib4(int k, float *alpha, float *A, int sda, float *B, int sdb, float *beta, float *C, int sdc, float *D, int sdd); // -void kernel_sgemm_nt_8x8_vs_lib4(int k, float *alpha, float *A, int sda, float *B, int sdb, float *beta, float *C, int sdc, float *D, int sdd, int m1, int n1); // -void kernel_sgemm_nn_8x8_lib4(int k, float *alpha, float *A, int sda, int offsetB, float *B, int sdb, float *beta, float *C, int sdc, float *D, int sdd); // -void kernel_sgemm_nn_8x8_vs_lib4(int k, float *alpha, float *A, int sda, int offsetB, float *B, int sdb, float *beta, float *C, int sdc, float *D, int sdd, int m1, int n1); // -// 8x4 -void kernel_sgemm_nt_8x4_lib4(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd); // -void kernel_sgemm_nt_8x4_vs_lib4(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd, int m1, int n1); // -void kernel_sgemm_nn_8x4_lib4(int k, float *alpha, float *A, int sda, int offsetB, float *B, int sdb, float *beta, float *C, int sdc, float *D, int sdd); // -void kernel_sgemm_nn_8x4_vs_lib4(int k, float *alpha, float *A, int sda, int offsetB, float *B, int sdb, float *beta, float *C, int sdc, float *D, int sdd, int m1, int n1); // -void kernel_ssyrk_nt_l_8x4_lib4(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd); // -void kernel_ssyrk_nt_l_8x4_vs_lib4(int k, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd, int km, int kn); // -void kernel_strsm_nt_rl_inv_8x4_lib4(int k, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd, float *E, float *inv_diag_E); -void kernel_strsm_nt_rl_inv_8x4_vs_lib4(int k, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd, float *E, float *inv_diag_E, int m1, int n1); -// 4x4 -void kernel_sgemm_nt_4x4_lib4(int k, float *alpha, float *A, float *B, float *beta, float *C, float *D); // -void kernel_sgemm_nt_4x4_vs_lib4(int k, float *alpha, float *A, float *B, float *beta, float *C, float *D, int km, int kn); // -void kernel_sgemm_nt_4x4_gen_lib4(int k, float *alpha, float *A, float *B, float *beta, int offsetC, float *C, int sdc, int offsetD, float *D, int sdd, int m0, int m1, int k0, int k1); -void kernel_sgemm_nn_4x4_lib4(int k, float *alpha, float *A, int offsetB, float *B, int sdb, float *beta, float *C, float *D); // -void kernel_sgemm_nn_4x4_vs_lib4(int k, float *alpha, float *A, int offsetB, float *B, int sdb, float *beta, float *C, float *D, int km, int kn); // -void kernel_sgemm_nn_4x4_gen_lib4(int k, float *alpha, float *A, int offsetB, float *B, int sdb, float *beta, int offsetC, float *C, int sdc, int offsetD, float *D, int sdd, int m0, int m1, int n0, int n1); // -void kernel_ssyrk_nt_l_4x4_lib4(int k, float *alpha, float *A, float *B, float *beta, float *C, float *D); // -void kernel_ssyrk_nt_l_4x4_vs_lib4(int k, float *alpha, float *A, float *B, float *beta, float *C, float *D, int km, int kn); // -void kernel_ssyrk_nt_l_4x4_gen_lib4(int k, float *alpha, float *A, float *B, float *beta, int offsetC, float *C, int sdc, int offsetD, float *D, int sdd, int m0, int m1, int n0, int n1); -void kernel_strmm_nt_ru_4x4_lib4(int k, float *alpha, float *A, float *B, float *D); // -void kernel_strmm_nt_ru_4x4_vs_lib4(int k, float *alpha, float *A, float *B, float *D, int km, int kn); // -void kernel_strmm_nn_rl_4x4_lib4(int k, float *alpha, float *A, int offsetB, float *B, int sdb, float *D); -void kernel_strmm_nn_rl_4x4_gen_lib4(int k, float *alpha, float *A, int offsetB, float *B, int sdb, int offsetD, float *D, int sdd, int m0, int m1, int n0, int n1); -void kernel_strsm_nt_rl_inv_4x4_lib4(int k, float *A, float *B, float *beta, float *C, float *D, float *E, float *inv_diag_E); -void kernel_strsm_nt_rl_inv_4x4_vs_lib4(int k, float *A, float *B, float *beta, float *C, float *D, float *E, float *inv_diag_E, int km, int kn); -void kernel_strsm_nt_rl_one_4x4_lib4(int k, float *A, float *B, float *beta, float *C, float *D, float *E); -void kernel_strsm_nt_rl_one_4x4_vs_lib4(int k, float *A, float *B, float *beta, float *C, float *D, float *E, int km, int kn); -void kernel_strsm_nt_ru_inv_4x4_lib4(int k, float *A, float *B, float *beta, float *C, float *D, float *E, float *inv_diag_E); -void kernel_strsm_nt_ru_inv_4x4_vs_lib4(int k, float *A, float *B, float *beta, float *C, float *D, float *E, float *inv_diag_E, int km, int kn); -void kernel_strsm_nt_ru_one_4x4_lib4(int k, float *A, float *B, float *beta, float *C, float *D, float *E); -void kernel_strsm_nt_ru_one_4x4_vs_lib4(int k, float *A, float *B, float *beta, float *C, float *D, float *E, int km, int kn); -void kernel_strsm_nn_ru_inv_4x4_lib4(int k, float *A, float *B, int sdb, float *beta, float *C, float *D, float *E, float *inv_diag_E); -void kernel_strsm_nn_ru_inv_4x4_vs_lib4(int k, float *A, float *B, int sdb, float *beta, float *C, float *D, float *E, float *inv_diag_E, int km, int kn); -void kernel_strsm_nn_ll_one_4x4_lib4(int k, float *A, float *B, int sdb, float *C, float *D, float *E); -void kernel_strsm_nn_ll_one_4x4_vs_lib4(int k, float *A, float *B, int sdb, float *C, float *D, float *E, int km, int kn); -void kernel_strsm_nn_lu_inv_4x4_lib4(int kmax, float *A, float *B, int sdb, float *C, float *D, float *E, float *inv_diag_E); -void kernel_strsm_nn_lu_inv_4x4_vs_lib4(int kmax, float *A, float *B, int sdb, float *C, float *D, float *E, float *inv_diag_E, int km, int kn); -// diag -void kernel_sgemm_diag_right_4_a0_lib4(int kmax, float *alpha, float *A, int sda, float *B, float *D, int sdd); -void kernel_sgemm_diag_right_4_lib4(int kmax, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd); -void kernel_sgemm_diag_right_3_lib4(int kmax, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd); -void kernel_sgemm_diag_right_2_lib4(int kmax, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd); -void kernel_sgemm_diag_right_1_lib4(int kmax, float *alpha, float *A, int sda, float *B, float *beta, float *C, int sdc, float *D, int sdd); -void kernel_sgemm_diag_left_4_a0_lib4(int kmax, float *alpha, float *A, float *B, float *D); -void kernel_sgemm_diag_left_4_lib4(int kmax, float *alpha, float *A, float *B, float *beta, float *C, float *D); -void kernel_sgemm_diag_left_3_lib4(int kmax, float *alpha, float *A, float *B, float *beta, float *C, float *D); -void kernel_sgemm_diag_left_2_lib4(int kmax, float *alpha, float *A, float *B, float *beta, float *C, float *D); -void kernel_sgemm_diag_left_1_lib4(int kmax, float *alpha, float *A, float *B, float *beta, float *C, float *D); - - - -// LAPACK -// 16x4 -void kernel_spotrf_nt_l_16x4_lib4(int k, float *A, int sda, float *B, float *C, int sdc, float *D, int sdd, float *inv_diag_D); -void kernel_spotrf_nt_l_16x4_vs_lib4(int k, float *A, int sda, float *B, float *C, int sdc, float *D, int sdd, float *inv_diag_D, int m1, int n1); -// 12x4 -void kernel_spotrf_nt_l_12x4_lib4(int k, float *A, int sda, float *B, float *C, int sdc, float *D, int sdd, float *inv_diag_D); -void kernel_spotrf_nt_l_12x4_vs_lib4(int k, float *A, int sda, float *B, float *C, int sdc, float *D, int sdd, float *inv_diag_D, int m1, int n1); -// 8x4 -void kernel_spotrf_nt_l_8x4_lib4(int k, float *A, int sda, float *B, float *C, int sdc, float *D, int sdd, float *inv_diag_D); -void kernel_spotrf_nt_l_8x4_vs_lib4(int k, float *A, int sda, float *B, float *C, int sdc, float *D, int sdd, float *inv_diag_D, int m1, int n1); -// 4x4 -void kernel_spotrf_nt_l_4x4_lib4(int k, float *A, float *B, float *C, float *D, float *inv_diag_D); -void kernel_spotrf_nt_l_4x4_vs_lib4(int k, float *A, float *B, float *C, float *D, float *inv_diag_D, int km, int kn); -void kernel_sgetrf_nn_4x4_lib4(int k, float *A, float *B, int sdb, float *C, float *D, float *inv_diag_D); -void kernel_sgetrf_nn_4x4_vs_lib4(int k, float *A, float *B, int sdb, float *C, float *D, float *inv_diag_D, int km, int kn); -void kernel_sgetrf_pivot_4_lib4(int m, float *pA, int sda, float *inv_diag_A, int* ipiv); -void kernel_sgetrf_pivot_4_vs_lib4(int m, int n, float *pA, int sda, float *inv_diag_A, int* ipiv); - - - -// merged routines -// 4x4 -void kernel_sgemm_strsm_nt_rl_inv_4x4_lib4(int kp, float *Ap, float *Bp, int km_, float *Am, float *Bm, float *C, float *D, float *E, float *inv_diag_E); -void kernel_sgemm_strsm_nt_rl_inv_4x4_vs_lib4(int kp, float *Ap, float *Bp, int km_, float *Am, float *Bm, float *C, float *D, float *E, float *inv_diag_E, int km, int kn); -void kernel_ssyrk_spotrf_nt_l_4x4_vs_lib4(int kp, float *Ap, float *Bp, int km_, float *Am, float *Bm, float *C, float *D, float *inv_diag_D, int km, int kn); -void kernel_ssyrk_spotrf_nt_l_4x4_lib4(int kp, float *Ap, float *Bp, int km_, float *Am, float *Bm, float *C, float *D, float *inv_diag_D); - - - -// auxiliary routines -void kernel_strcp_l_4_0_lib4(int kmax, float *A, float *B); -void kernel_strcp_l_4_1_lib4(int kmax, float *A0, int sda, float *B); -void kernel_strcp_l_4_2_lib4(int kmax, float *A0, int sda, float *B); -void kernel_strcp_l_4_3_lib4(int kmax, float *A0, int sda, float *B); -void kernel_strcp_l_3_0_lib4(int kmax, float *A, float *B); -void kernel_strcp_l_3_2_lib4(int kmax, float *A0, int sda, float *B); -void kernel_strcp_l_3_3_lib4(int kmax, float *A0, int sda, float *B); -void kernel_strcp_l_2_0_lib4(int kmax, float *A, float *B); -void kernel_strcp_l_2_3_lib4(int kmax, float *A0, int sda, float *B); -void kernel_strcp_l_1_0_lib4(int kmax, float *A, float *B); -void kernel_sgead_4_0_lib4(int kmax, float *alpha, float *A, float *B); -void kernel_sgead_4_1_lib4(int kmax, float *alpha, float *A0, int sda, float *B); -void kernel_sgead_4_2_lib4(int kmax, float *alpha, float *A0, int sda, float *B); -void kernel_sgead_4_3_lib4(int kmax, float *alpha, float *A0, int sda, float *B); -void kernel_sgead_3_0_lib4(int kmax, float *alpha, float *A, float *B); -void kernel_sgead_3_2_lib4(int kmax, float *alpha, float *A0, int sda, float *B); -void kernel_sgead_3_3_lib4(int kmax, float *alpha, float *A0, int sda, float *B); -void kernel_sgead_2_0_lib4(int kmax, float *alpha, float *A, float *B); -void kernel_sgead_2_3_lib4(int kmax, float *alpha, float *A0, int sda, float *B); -void kernel_sgead_1_0_lib4(int kmax, float *alpha, float *A, float *B); -// TODO -void kernel_sgeset_4_lib4(int kmax, float alpha, float *A); -void kernel_strset_4_lib4(int kmax, float alpha, float *A); -void kernel_sgetr_4_lib4(int tri, int kmax, int kna, float alpha, float *A, float *C, int sdc); -void kernel_sgetr_3_lib4(int tri, int kmax, int kna, float alpha, float *A, float *C, int sdc); -void kernel_sgetr_2_lib4(int tri, int kmax, int kna, float alpha, float *A, float *C, int sdc); -void kernel_sgetr_1_lib4(int tri, int kmax, int kna, float alpha, float *A, float *C, int sdc); - - - -// pack -// 24 lib 8 -void kernel_spack_nn_24_lib8(int kmax, float *A, int lda, float *B, int sdb); -void kernel_spack_nn_24_vs_lib8(int kmax, float *A, int lda, float *B, int sdb, int m1); -// 16 lib 8 -void kernel_spack_nn_16_lib8(int kmax, float *A, int lda, float *B, int sdb); -void kernel_spack_nn_16_vs_lib8(int kmax, float *A, int lda, float *B, int sdb, int m1); -// 8 lib 8 -void kernel_spack_nn_8_lib8(int kmax, float *A, int lda, float *B); -void kernel_spack_nn_8_vs_lib8(int kmax, float *A, int lda, float *B, int m1); -void kernel_spack_tn_8_lib8(int kmax, float *A, int lda, float *B); -void kernel_spack_tn_8_vs_lib8(int kmax, float *A, int lda, float *B, int m1); -void kernel_spack_tt_8_lib8(int kmax, float *A, int lda, float *B, int sdb); -void kernel_spack_tt_8_vs_lib8(int kmax, float *A, int lda, float *B, int sdb, int m1); -// 8 lib 4 -void kernel_spack_nn_8_lib4(int kmax, float *A, int lda, float *B, int sdb); -void kernel_spack_nn_8_vs_lib4(int kmax, float *A, int lda, float *B, int sdb, int m1); -//void kernel_spack_tt_8_lib4(int kmax, float *A, int lda, float *B, int sdb); -// 4 -void kernel_spack_nn_4_lib4(int kmax, float *A, int lda, float *B); -void kernel_spack_nn_4_vs_lib4(int kmax, float *A, int lda, float *B, int m1); -void kernel_spack_tn_4_lib4(int kmax, float *A, int lda, float *B); -void kernel_spack_tn_4_vs_lib4(int kmax, float *A, int lda, float *B, int m1); -void kernel_spack_tt_4_lib4(int kmax, float *A, int lda, float *B, int sdb); -void kernel_spack_tt_4_vs_lib4(int kmax, float *A, int lda, float *B, int sdb, int m1); -// unpack -// 8 -void kernel_sunpack_nn_8_lib4(int kmax, float *A, int sda, float *B, int ldb); -void kernel_sunpack_nn_8_vs_lib4(int kmax, float *A, int sda, float *B, int ldb, int m1); -//void kernel_sunpack_tt_8_lib4(int kmax, float *A, int sda, float *B, int ldb); -// 4 -void kernel_sunpack_nn_4_lib4(int kmax, float *A, float *B, int ldb); -void kernel_sunpack_nn_4_vs_lib4(int kmax, float *A, float *B, int ldb, int m1); -void kernel_sunpack_nt_4_lib4(int kmax, float *A, float *B, int ldb); -void kernel_sunpack_nt_4_vs_lib4(int kmax, float *A, float *B, int ldb, int m1); -void kernel_sunpack_tt_4_lib4(int kmax, float *A, int sda, float *B, int ldb); - -// panel copy -// 4 -void kernel_spacp_nt_4_lib4(int kmax, float *A, int offsetB, float *B, int sdb); -void kernel_spacp_tn_4_lib4(int kmax, int offsetA, float *A, int sda, float *B); -void kernel_spacp_nn_4_lib4(int kmax, int offsetA, float *A, int sda, float *B); -void kernel_spacp_nn_4_vs_lib4(int kmax, int offsetA, float *A, int sda, float *B, int m1); - - - -/************************************************ -* BLAS API kernels -************************************************/ - -//#if defined(BLAS_API) - -// A, B panel-major bs=8; C, D column-major -// 24x4 -void kernel_sgemm_nt_24x4_lib88cc(int kmax, float *alpha, float *A, int sda, float *B, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_24x4_vs_lib88cc(int kmax, float *alpha, float *A, int sda, float *B, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -// 16x4 -void kernel_sgemm_nt_16x4_lib88cc(int kmax, float *alpha, float *A, int sda, float *B, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_16x4_vs_lib88cc(int kmax, float *alpha, float *A, int sda, float *B, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -// 8x8 -void kernel_sgemm_nt_8x8_lib88cc(int kmax, float *alpha, float *A, float *B, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_8x8_vs_lib88cc(int kmax, float *alpha, float *A, float *B, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -void kernel_spotrf_nt_l_8x8_lib88cc(int kmax, float *A, float *B, float *C, int ldc, float *D, int ldd, float *dD); -void kernel_spotrf_nt_l_8x8_vs_lib88cc(int kmax, float *A, float *B, float *C, int ldc, float *D, int ldd, float *dD, int m1, int n1); -void kernel_strsm_nt_rl_inv_8x8_lib88ccc(int kmax, float *A, float *B, float *C, int ldc, float *D, int ldd, float *E, int lde, float *dE); -void kernel_strsm_nt_rl_inv_8x8_vs_lib88ccc(int kmax, float *A, float *B, float *C, int ldc, float *D, int ldd, float *E, int lde, float *dE, int m1, int n1); -// 8x4 -void kernel_sgemm_nt_8x4_lib88cc(int kmax, float *alpha, float *A, float *B, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_8x4_vs_lib88cc(int kmax, float *alpha, float *A, float *B, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); - -// A, B panel-major bs=4; C, D column-major -// 8x8 -void kernel_sgemm_nt_8x8_lib44cc(int kmax, float *alpha, float *A, int sda, float *B, int sdb, float *beta, float *C, int ldc, float *D, int ldd); -// 8x4 -void kernel_sgemm_nt_8x4_lib44cc(int kmax, float *alpha, float *A, int sda, float *B, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_8x4_vs_lib44cc(int kmax, float *alpha, float *A, int sda, float *B, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -void kernel_spotrf_nt_l_8x4_lib44cc(int kmax, float *A, int sda, float *B, float *C, int ldc, float *D, int ldd, float *dD); -void kernel_strsm_nt_rl_inv_8x4_lib44ccc(int kmax, float *A, int sda, float *B, float *beta, float *C, int ldc, float *D, int ldd, float *E, int lde, float *dE); -void kernel_strsm_nt_rl_inv_8x4_vs_lib44ccc(int kmax, float *A, int sda, float *B, float *beta, float *C, int ldc, float *D, int ldd, float *E, int lde, float *dE, int m1, int n1); -// 4x4 -void kernel_sgemm_nt_4x4_lib44cc(int kmax, float *alpha, float *A, float *B, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_4x4_vs_lib44cc(int kmax, float *alpha, float *A, float *B, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -void kernel_strsm_nt_rl_inv_4x4_lib44cc4(int kmax, float *A, float *B, float *beta, float *C, int ldc, float *D, int ldd, float *E, float *dE); -void kernel_strsm_nt_rl_inv_4x4_vs_lib44cc4(int kmax, float *A, float *B, float *beta, float *C, int ldc, float *D, int ldd, float *E, float *dE, int m1, int n1); -void kernel_strsm_nt_rl_inv_4x4_lib44ccc(int kmax, float *A, float *B, float *beta, float *C, int ldc, float *D, int ldd, float *E, int lde, float *dE); -void kernel_strsm_nt_rl_inv_4x4_vs_lib44ccc(int kmax, float *A, float *B, float *beta, float *C, int ldc, float *D, int ldd, float *E, int lde, float *dE, int m1, int n1); -void kernel_strsm_nt_rl_one_4x4_lib44cc4(int kmax, float *A, float *B, float *beta, float *C, int ldc, float *D, int ldd, float *E); -void kernel_strsm_nt_rl_one_4x4_vs_lib44cc4(int kmax, float *A, float *B, float *beta, float *C, int ldc, float *D, int ldd, float *E, int m1, int n1); -void kernel_strsm_nt_ru_inv_4x4_lib44cc4(int kmax, float *A, float *B, float *beta, float *C, int ldc, float *D, int ldd, float *E, float *dE); -void kernel_strsm_nt_ru_inv_4x4_vs_lib44cc4(int kmax, float *A, float *B, float *beta, float *C, int ldc, float *D, int ldd, float *E, float *dE, int m1, int n1); -void kernel_strsm_nt_ru_one_4x4_lib44cc4(int kmax, float *A, float *B, float *beta, float *C, int ldc, float *D, int ldd, float *E); -void kernel_strsm_nt_ru_one_4x4_vs_lib44cc4(int kmax, float *A, float *B, float *beta, float *C, int ldc, float *D, int ldd, float *E, int m1, int n1); -void kernel_spotrf_nt_l_4x4_lib44cc(int kmax, float *A, float *B, float *C, int ldc, float *D, int ldd, float *dD); -void kernel_spotrf_nt_l_4x4_vs_lib44cc(int kmax, float *A, float *B, float *C, int ldc, float *D, int ldd, float *dD, int m1, int n1); - -// B panel-major bs=8; A, C, D column-major -// 4x24 -void kernel_sgemm_nt_4x24_libc8cc(int kmax, float *alpha, float *A, int lda, float *B, int sdb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_4x24_vs_libc8cc(int kmax, float *alpha, float *A, int lda, float *B, int sdb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -void kernel_sgemm_tt_4x24_libc8cc(int kmax, float *alpha, float *A, int lda, float *B, int sdb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_tt_4x24_vs_libc8cc(int kmax, float *alpha, float *A, int lda, float *B, int sdb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -// 4x16 -void kernel_sgemm_nt_4x16_libc8cc(int kmax, float *alpha, float *A, int lda, float *B, int sdb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_4x16_vs_libc8cc(int kmax, float *alpha, float *A, int lda, float *B, int sdb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -void kernel_sgemm_tt_4x16_libc8cc(int kmax, float *alpha, float *A, int lda, float *B, int sdb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_tt_4x16_vs_libc8cc(int kmax, float *alpha, float *A, int lda, float *B, int sdb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -// 8x8 -void kernel_sgemm_nt_8x8_libc8cc(int kmax, float *alpha, float *A, int lda, float *B, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_8x8_vs_libc8cc(int kmax, float *alpha, float *A, int lda, float *B, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -void kernel_sgemm_tt_8x8_libc8cc(int kmax, float *alpha, float *A, int lda, float *B, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_tt_8x8_vs_libc8cc(int kmax, float *alpha, float *A, int lda, float *B, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -// 4x8 -void kernel_sgemm_nt_4x8_libc8cc(int kmax, float *alpha, float *A, int lda, float *B, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_4x8_vs_libc8cc(int kmax, float *alpha, float *A, int lda, float *B, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -void kernel_sgemm_tt_4x8_libc8cc(int kmax, float *alpha, float *A, int lda, float *B, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_tt_4x8_vs_libc8cc(int kmax, float *alpha, float *A, int lda, float *B, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); - -// B panel-major bs=4; A, C, D column-major -// 8x8 -void kernel_sgemm_nt_8x8_libc4cc(int kmax, float *alpha, float *A, int lda, float *B, int sdb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_8x8_vs_libc4cc(int kmax, float *alpha, float *A, int lda, float *B, int sdb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -void kernel_sgemm_tt_8x8_libc4cc(int kmax, float *alpha, float *A, int lda, float *B, int sdb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_tt_8x8_vs_libc4cc(int kmax, float *alpha, float *A, int lda, float *B, int sdb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -// 4x8 -void kernel_sgemm_nt_4x8_libc4cc(int kmax, float *alpha, float *A, int lda, float *B, int sdb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_4x8_vs_libc4cc(int kmax, float *alpha, float *A, int lda, float *B, int sdb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -void kernel_sgemm_tt_4x8_libc4cc(int kmax, float *alpha, float *A, int lda, float *B, int sdb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_tt_4x8_vs_libc4cc(int kmax, float *alpha, float *A, int lda, float *B, int sdb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -// 4x4 -void kernel_sgemm_nt_4x4_libc4cc(int kmax, float *alpha, float *A, int lda, float *B, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_4x4_vs_libc4cc(int kmax, float *alpha, float *A, int lda, float *B, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -void kernel_sgemm_tt_4x4_libc4cc(int kmax, float *alpha, float *A, int lda, float *B, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_tt_4x4_vs_libc4cc(int kmax, float *alpha, float *A, int lda, float *B, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); - -// A panel-major bs=8; B, C, D column-major -// 24x4 -void kernel_sgemm_nn_24x4_lib8ccc(int kmax, float *alpha, float *A, int lda, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nn_24x4_vs_lib8ccc(int kmax, float *alpha, float *A, int lda, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -void kernel_sgemm_nt_24x4_lib8ccc(int kmax, float *alpha, float *A, int lda, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_24x4_vs_lib8ccc(int kmax, float *alpha, float *A, int lda, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -// 16x4 -void kernel_sgemm_nn_16x4_lib8ccc(int kmax, float *alpha, float *A, int lda, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nn_16x4_vs_lib8ccc(int kmax, float *alpha, float *A, int lda, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -void kernel_sgemm_nt_16x4_lib8ccc(int kmax, float *alpha, float *A, int lda, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_16x4_vs_lib8ccc(int kmax, float *alpha, float *A, int lda, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -// 8x8 -void kernel_sgemm_nn_8x8_lib8ccc(int kmax, float *alpha, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nn_8x8_vs_lib8ccc(int kmax, float *alpha, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -void kernel_sgemm_nt_8x8_lib8ccc(int kmax, float *alpha, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_8x8_vs_lib8ccc(int kmax, float *alpha, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -// 8x4 -void kernel_sgemm_nn_8x4_lib8ccc(int kmax, float *alpha, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nn_8x4_vs_lib8ccc(int kmax, float *alpha, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -void kernel_sgemm_nt_8x4_lib8ccc(int kmax, float *alpha, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_8x4_vs_lib8ccc(int kmax, float *alpha, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); - -// A panel-major bs=4; B, C, D column-major -// 8x8 -void kernel_sgemm_nn_8x8_lib4ccc(int kmax, float *alpha, float *A, int sda, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_8x8_lib4ccc(int kmax, float *alpha, float *A, int sda, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd); -// 8x4 -void kernel_sgemm_nn_8x4_lib4ccc(int kmax, float *alpha, float *A, int sda, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nn_8x4_vs_lib4ccc(int kmax, float *alpha, float *A, int sda, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -void kernel_sgemm_nt_8x4_lib4ccc(int kmax, float *alpha, float *A, int sda, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_8x4_vs_lib4ccc(int kmax, float *alpha, float *A, int sda, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -// 4x4 -void kernel_sgemm_nn_4x4_lib4ccc(int kmax, float *alpha, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nn_4x4_vs_lib4ccc(int kmax, float *alpha, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -void kernel_sgemm_nt_4x4_lib4ccc(int kmax, float *alpha, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_4x4_vs_lib4ccc(int kmax, float *alpha, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -void kernel_strsm_nn_rl_inv_4x4_lib4cccc(int kmax, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, float *E, int lde, float *dE); -void kernel_strsm_nn_rl_inv_4x4_vs_lib4cccc(int kmax, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, float *E, int lde, float *dE, int m1, int n1); -void kernel_strsm_nn_rl_one_4x4_lib4cccc(int kmax, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, float *E, int lde); -void kernel_strsm_nn_rl_one_4x4_vs_lib4cccc(int kmax, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, float *E, int lde, int m1, int n1); -void kernel_strsm_nt_rl_inv_4x4_lib4cccc(int kmax, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, float *E, int lde, float *dE); -void kernel_strsm_nt_rl_inv_4x4_vs_lib4cccc(int kmax, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, float *E, int lde, float *dE, int m1, int n1); -void kernel_strsm_nt_rl_one_4x4_lib4cccc(int kmax, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, float *E, int lde); -void kernel_strsm_nt_rl_one_4x4_vs_lib4cccc(int kmax, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, float *E, int lde, int m1, int n1); -void kernel_strsm_nn_ru_inv_4x4_lib4cccc(int kmax, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, float *E, int lde, float *dE); -void kernel_strsm_nn_ru_inv_4x4_vs_lib4cccc(int kmax, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, float *E, int lde, float *dE, int m1, int n1); -void kernel_strsm_nn_ru_one_4x4_lib4cccc(int kmax, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, float *E, int lde); -void kernel_strsm_nn_ru_one_4x4_vs_lib4cccc(int kmax, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, float *E, int lde, int m1, int n1); -void kernel_strsm_nt_ru_inv_4x4_lib4cccc(int kmax, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, float *E, int lde, float *dE); -void kernel_strsm_nt_ru_inv_4x4_vs_lib4cccc(int kmax, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, float *E, int lde, float *dE, int m1, int n1); -void kernel_strsm_nt_ru_one_4x4_lib4cccc(int kmax, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, float *E, int lde); -void kernel_strsm_nt_ru_one_4x4_vs_lib4cccc(int kmax, float *A, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, float *E, int lde, int m1, int n1); - -// A, C, D panel-major; B, E column-major -// TODO merge with above -// 4x4 -void kernel_strsm_nn_rl_inv_4x4_lib4c44c(int kmax, float *A, float *B, int ldb, float *beta, float *C, float *D, float *E, int lde, float *dE); -void kernel_strsm_nn_rl_inv_4x4_vs_lib4c44c(int kmax, float *A, float *B, int ldb, float *beta, float *C, float *D, float *E, int lde, float *dE, int m1, int n1); -void kernel_strsm_nn_rl_one_4x4_lib4c44c(int kmax, float *A, float *B, int ldb, float *beta, float *C, float *D, float *E, int lde); -void kernel_strsm_nn_rl_one_4x4_vs_lib4c44c(int kmax, float *A, float *B, int ldb, float *beta, float *C, float *D, float *E, int lde, int m1, int n1); -void kernel_strsm_nn_ru_inv_4x4_lib4c44c(int kmax, float *A, float *B, int ldb, float *beta, float *C, float *D, float *E, int lde, float *dE); -void kernel_strsm_nn_ru_inv_4x4_vs_lib4c44c(int kmax, float *A, float *B, int ldb, float *beta, float *C, float *D, float *E, int lde, float *dE, int m1, int n1); -void kernel_strsm_nn_ru_one_4x4_lib4c44c(int kmax, float *A, float *B, int ldb, float *beta, float *C, float *D, float *E, int lde); -void kernel_strsm_nn_ru_one_4x4_vs_lib4c44c(int kmax, float *A, float *B, int ldb, float *beta, float *C, float *D, float *E, int lde, int m1, int n1); -void kernel_strsm_nt_rl_inv_4x4_lib4c44c(int kmax, float *A, float *B, int ldb, float *beta, float *C, float *D, float *E, int lde, float *dE); -void kernel_strsm_nt_rl_inv_4x4_vs_lib4c44c(int kmax, float *A, float *B, int ldb, float *beta, float *C, float *D, float *E, int lde, float *dE, int m1, int n1); -void kernel_strsm_nt_rl_one_4x4_lib4c44c(int kmax, float *A, float *B, int ldb, float *beta, float *C, float *D, float *E, int lde); -void kernel_strsm_nt_rl_one_4x4_vs_lib4c44c(int kmax, float *A, float *B, int ldb, float *beta, float *C, float *D, float *E, int lde, int m1, int n1); -void kernel_strsm_nt_ru_inv_4x4_lib4c44c(int kmax, float *A, float *B, int ldb, float *beta, float *C, float *D, float *E, int lde, float *dE); -void kernel_strsm_nt_ru_inv_4x4_vs_lib4c44c(int kmax, float *A, float *B, int ldb, float *beta, float *C, float *D, float *E, int lde, float *dE, int m1, int n1); -void kernel_strsm_nt_ru_one_4x4_lib4c44c(int kmax, float *A, float *B, int ldb, float *beta, float *C, float *D, float *E, int lde); -void kernel_strsm_nt_ru_one_4x4_vs_lib4c44c(int kmax, float *A, float *B, int ldb, float *beta, float *C, float *D, float *E, int lde, int m1, int n1); - -// A, B, C, D column-major -void kernel_sgemm_nn_4x4_libcccc(int kmax, float *alpha, float *A, int lda, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nn_4x4_vs_libcccc(int kmax, float *alpha, float *A, int lda, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -void kernel_sgemm_nt_4x4_libcccc(int kmax, float *alpha, float *A, int lda, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_nt_4x4_vs_libcccc(int kmax, float *alpha, float *A, int lda, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); -void kernel_sgemm_tt_4x4_libcccc(int kmax, float *alpha, float *A, int lda, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd); -void kernel_sgemm_tt_4x4_vs_libcccc(int kmax, float *alpha, float *A, int lda, float *B, int ldb, float *beta, float *C, int ldc, float *D, int ldd, int m1, int n1); - -// vector -void kernel_sdot_11_lib(int n, float *x, float *y, float *res); -void kernel_saxpy_11_lib(int n, float *alpha, float *x, float *y); - - -//#endif // BLAS_API - - - -// larger kernels -// 24 -void kernel_sgemm_nt_24xn_p0_lib88cc(int n, int k, float *alpha, float *A, int sda, float *B, int sdb, float *beta, float *C, int ldc, float *D, int ldd, float *A_p, float *B_p); - - - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_S_KERNEL_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_stdlib.h b/third_party/acados/include/blasfeo/include/blasfeo_stdlib.h deleted file mode 100644 index 9bd248b1d4..0000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_stdlib.h +++ /dev/null @@ -1,62 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_STDLIB_H_ -#define BLASFEO_STDLIB_H_ - -#ifdef __cplusplus -extern "C" { -#endif - - - -#include - -// -void blasfeo_malloc(void **ptr, size_t size); -// -void blasfeo_malloc_align(void **ptr, size_t size); -// -void blasfeo_free(void *ptr); -// -void blasfeo_free_align(void *ptr); - - - -#ifdef __cplusplus -} -#endif - -#endif // BLASFEO_STDLIB_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_target.h b/third_party/acados/include/blasfeo/include/blasfeo_target.h deleted file mode 100644 index 51f617a649..0000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_target.h +++ /dev/null @@ -1,73 +0,0 @@ -#ifndef TARGET_X64_INTEL_HASWELL -#define TARGET_X64_INTEL_HASWELL -#endif - -#ifndef TARGET_NEED_FEATURE_AVX2 -#define TARGET_NEED_FEATURE_AVX2 1 -#endif - -#ifndef TARGET_NEED_FEATURE_FMA -#define TARGET_NEED_FEATURE_FMA 1 -#endif - -#ifndef TARGET_NEED_FEATURE_SSE3 -/* #undef TARGET_NEED_FEATURE_SSE3 */ -#endif - -#ifndef TARGET_NEED_FEATURE_AVX -/* #undef TARGET_NEED_FEATURE_AVX */ -#endif - -#ifndef TARGET_NEED_FEATURE_VFPv3 -/* #undef TARGET_NEED_FEATURE_VFPv3 */ -#endif - -#ifndef TARGET_NEED_FEATURE_NEON -/* #undef TARGET_NEED_FEATURE_NEON */ -#endif - -#ifndef TARGET_NEED_FEATURE_VFPv4 -/* #undef TARGET_NEED_FEATURE_VFPv4 */ -#endif - -#ifndef TARGET_NEED_FEATURE_NEONv2 -/* #undef TARGET_NEED_FEATURE_NEONv2 */ -#endif - -#ifndef LA_HIGH_PERFORMANCE -#define LA_HIGH_PERFORMANCE -#endif - -#ifndef MF_PANELMAJ -#define MF_PANELMAJ -#endif - -#ifndef EXT_DEP -#define ON 1 -#define OFF 0 -#if ON==ON -#define EXT_DEP -#endif -#undef ON -#undef OFF -#endif - -#ifndef BLAS_API -#define ON 1 -#define OFF 0 -#if OFF==ON -#define BLAS_API -#endif -#undef ON -#undef OFF -#endif - -#ifndef FORTRAN_BLAS_API -#define ON 1 -#define OFF 0 -#if OFF==ON -#define FORTRAN_BLAS_API -#endif -#undef ON -#undef OFF -#endif diff --git a/third_party/acados/include/blasfeo/include/blasfeo_timing.h b/third_party/acados/include/blasfeo/include/blasfeo_timing.h deleted file mode 100644 index 5671b888fe..0000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_timing.h +++ /dev/null @@ -1,114 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_TIMING_H_ -#define BLASFEO_TIMING_H_ - -//#include - -#if (defined _WIN32 || defined _WIN64) && !(defined __MINGW32__ || defined __MINGW64__) - - /* Use Windows QueryPerformanceCounter for timing. */ - #include - - /** A structure for keeping internal timer data. */ - typedef struct blasfeo_timer_ { - LARGE_INTEGER tic; - LARGE_INTEGER toc; - LARGE_INTEGER freq; - } blasfeo_timer; - -#elif(defined __APPLE__) - - #include - - /** A structure for keeping internal timer data. */ - typedef struct blasfeo_timer_ { - uint64_t tic; - uint64_t toc; - mach_timebase_info_data_t tinfo; - } blasfeo_timer; - -#elif(defined __DSPACE__) - - #include - - typedef struct blasfeo_timer_ { - double time; - } blasfeo_timer; - -#elif(defined __XILINX_NONE_ELF__ || defined __XILINX_ULTRASCALE_NONE_ELF_JAILHOUSE__) - - #include "xtime_l.h" - - typedef struct blasfeo_timer_ { - uint64_t tic; - uint64_t toc; - } blasfeo_timer; - -#else - - /* Use POSIX clock_gettime() for timing on non-Windows machines. */ - #include - - #if __STDC_VERSION__ >= 199901L // C99 Mode - - #include - #include - - typedef struct blasfeo_timer_ { - struct timeval tic; - struct timeval toc; - } blasfeo_timer; - - #else // ANSI C Mode - - /** A structure for keeping internal timer data. */ - typedef struct blasfeo_timer_ { - struct timespec tic; - struct timespec toc; - } blasfeo_timer; - - #endif // __STDC_VERSION__ >= 199901L - -#endif // (defined _WIN32 || defined _WIN64) - -/** A function for measurement of the current time. */ -void blasfeo_tic(blasfeo_timer* t); - -/** A function which returns the elapsed time. */ -double blasfeo_toc(blasfeo_timer* t); - -#endif // BLASFEO_TIMING_H_ diff --git a/third_party/acados/include/blasfeo/include/blasfeo_v_aux_ext_dep.h b/third_party/acados/include/blasfeo/include/blasfeo_v_aux_ext_dep.h deleted file mode 100644 index 1598551185..0000000000 --- a/third_party/acados/include/blasfeo/include/blasfeo_v_aux_ext_dep.h +++ /dev/null @@ -1,83 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef BLASFEO_V_AUX_EXT_DEP_H_ -#define BLASFEO_V_AUX_EXT_DEP_H_ - - - -#include "blasfeo_target.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -/************************************************ -* d_aux_extern_depend_lib.c -************************************************/ - -#ifdef EXT_DEP - -void v_zeros(void **ptrA, int size); -// dynamically allocate size bytes of memory aligned to 64-byte boundaries and set accordingly a pointer to void; set allocated memory to zero -void v_zeros_align(void **ptrA, int size); -// free the memory allocated by v_zeros -void v_free(void *ptrA); -// free the memory allocated by v_zeros_aligned -void v_free_align(void *ptrA); -// dynamically allocate size bytes of memory and set accordingly a pointer to char; set allocated memory to zero -void c_zeros(char **ptrA, int size); -// dynamically allocate size bytes of memory aligned to 64-byte boundaries and set accordingly a pointer to char; set allocated memory to zero -void c_zeros_align(char **ptrA, int size); -// free the memory allocated by c_zeros -void c_free(char *ptrA); -// free the memory allocated by c_zeros_aligned -void c_free_align(char *ptrA); - -#endif // EXT_DEP - - - -#ifdef __cplusplus -} -#endif - - - -#endif // BLASFEO_V_AUX_EXT_DEP_H_ diff --git a/third_party/acados/include/blasfeo/include/d_blas.h b/third_party/acados/include/blasfeo/include/d_blas.h deleted file mode 100644 index ffd2578da3..0000000000 --- a/third_party/acados/include/blasfeo/include/d_blas.h +++ /dev/null @@ -1,78 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifdef __cplusplus -extern "C" { -#endif - - - -// headers to reference BLAS and LAPACK routines employed in BLASFEO WR - -// level 1 -double ddot_(int *m, double *x, int *incx, double *y, int *incy); -void dcopy_(int *m, double *x, int *incx, double *y, int *incy); -void daxpy_(int *m, double *alpha, double *x, int *incx, double *y, int *incy); -void dscal_(int *m, double *alpha, double *x, int *incx); -void drot_(int *m, double *x, int *incx, double *y, int *incy, double *c, double *s); -void drotg_(double *a, double *b, double *c, double *s); - -// level 2 -void dgemv_(char *ta, int *m, int *n, double *alpha, double *A, int *lda, double *x, int *incx, double *beta, double *y, int *incy); -void dsymv_(char *uplo, int *m, double *alpha, double *A, int *lda, double *x, int *incx, double *beta, double *y, int *incy); -void dtrmv_(char *uplo, char *trans, char *diag, int *n, double *A, int *lda, double *x, int *incx); -void dtrsv_(char *uplo, char *trans, char *diag, int *n, double *A, int *lda, double *x, int *incx); -void dger_(int *m, int *n, double *alpha, double *x, int *incx, double *y, int *incy, double *A, int *lda); - -// level 3 -void dgemm_(char *ta, char *tb, int *m, int *n, int *k, double *alpha, double *A, int *lda, double *B, int *ldb, double *beta, double *C, int *ldc); -void dsyrk_(char *uplo, char *trans, int *n, int *k, double *alpha, double *A, int *lda, double *beta, double *C, int *ldc); -void dtrmm_(char *side, char *uplo, char *trans, char *diag, int *m, int *n, double *alpha, double *A, int *lda, double *B, int *ldb); -void dtrsm_(char *side, char *uplo, char *trans, char *diag, int *m, int *n, double *alpha, double *A, int *lda, double *B, int *ldb); -void dsyr2k_(char *uplo, char *trans, int *n, int *k, double *alpha, double *A, int *lda, double *B, int *ldb, double *beta, double *C, int *ldc); - -// lapack -void dpotrf_(char *uplo, int *m, double *A, int *lda, int *info); -void dgetrf_(int *m, int *n, double *A, int *lda, int *ipiv, int *info); -void dgeqrf_(int *m, int *n, double *A, int *lda, double *tau, double *work, int *lwork, int *info); -void dgeqr2_(int *m, int *n, double *A, int *lda, double *tau, double *work, int *info); -void dgelqf_(int *m, int *n, double *A, int *lda, double *tau, double *work, int *lwork, int *info); -void dorglq_(int *m, int *n, int *k, double *A, int *lda, double *tau, double *work, int *lwork, int *info); - - - -#ifdef __cplusplus -} -#endif diff --git a/third_party/acados/include/blasfeo/include/d_blas_64.h b/third_party/acados/include/blasfeo/include/d_blas_64.h deleted file mode 100644 index 4f40d00dfb..0000000000 --- a/third_party/acados/include/blasfeo/include/d_blas_64.h +++ /dev/null @@ -1,73 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifdef __cplusplus -extern "C" { -#endif - - - -// headers to reference BLAS and LAPACK routines employed in BLASFEO WR - -// level 1 -double ddot_(long long *m, double *x, long long *incx, double *y, long long *incy); -void dcopy_(long long *m, double *x, long long *incx, double *y, long long *incy); -void daxpy_(long long *m, double *alpha, double *x, long long *incx, double *y, long long *incy); -void dscal_(long long *m, double *alpha, double *x, long long *incx); - -// level 2 -void dgemv_(char *ta, long long *m, long long *n, double *alpha, double *A, long long *lda, double *x, long long *incx, double *beta, double *y, long long *incy); -void dsymv_(char *uplo, long long *m, double *alpha, double *A, long long *lda, double *x, long long *incx, double *beta, double *y, long long *incy); -void dtrmv_(char *uplo, char *trans, char *diag, long long *n, double *A, long long *lda, double *x, long long *incx); -void dtrsv_(char *uplo, char *trans, char *diag, long long *n, double *A, long long *lda, double *x, long long *incx); -void dger_(long long *m, long long *n, double *alpha, double *x, long long *incx, double *y, long long *incy, double *A, long long *lda); - -// level 3 -void dgemm_(char *ta, char *tb, long long *m, long long *n, long long *k, double *alpha, double *A, long long *lda, double *B, long long *ldb, double *beta, double *C, long long *ldc); -void dsyrk_(char *uplo, char *trans, long long *n, long long *k, double *alpha, double *A, long long *lda, double *beta, double *C, long long *ldc); -void dtrmm_(char *side, char *uplo, char *trans, char *diag, long long *m, long long *n, double *alpha, double *A, long long *lda, double *B, long long *ldb); -void dtrsm_(char *side, char *uplo, char *trans, char *diag, long long *m, long long *n, double *alpha, double *A, long long *lda, double *B, long long *ldb); - -// lapack -void dpotrf_(char *uplo, long long *m, double *A, long long *lda, long long *info); -void dgetrf_(long long *m, long long *n, double *A, long long *lda, long long *ipiv, long long *info); -void dgeqrf_(long long *m, long long *n, double *A, long long *lda, double *tau, double *work, long long *lwork, long long *info); -void dgeqr2_(long long *m, long long *n, double *A, long long *lda, double *tau, double *work, long long *info); - - - -#ifdef __cplusplus -} -#endif diff --git a/third_party/acados/include/blasfeo/include/s_blas.h b/third_party/acados/include/blasfeo/include/s_blas.h deleted file mode 100644 index 3b299ce64c..0000000000 --- a/third_party/acados/include/blasfeo/include/s_blas.h +++ /dev/null @@ -1,78 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifdef __cplusplus -extern "C" { -#endif - - - -// headers to reference BLAS and LAPACK routines employed in BLASFEO WR - -// level 1 -float sdot_(int *m, float *x, int *incx, float *y, int *incy); -void scopy_(int *m, float *x, int *incx, float *y, int *incy); -void saxpy_(int *m, float *alpha, float *x, int *incx, float *y, int *incy); -void sscal_(int *m, float *alpha, float *x, int *incx); -void srot_(int *m, float *x, int *incx, float *y, int *incy, float *c, float *s); -void srotg_(float *a, float *b, float *c, float *s); - -// level 2 -void sgemv_(char *ta, int *m, int *n, float *alpha, float *A, int *lda, float *x, int *incx, float *beta, float *y, int *incy); -void ssymv_(char *uplo, int *m, float *alpha, float *A, int *lda, float *x, int *incx, float *beta, float *y, int *incy); -void strmv_(char *uplo, char *trans, char *diag, int *n, float *A, int *lda, float *x, int *incx); -void strsv_(char *uplo, char *trans, char *diag, int *n, float *A, int *lda, float *x, int *incx); -void sger_(int *m, int *n, float *alpha, float *x, int *incx, float *y, int *incy, float *A, int *lda); - -// level 3 -void sgemm_(char *ta, char *tb, int *m, int *n, int *k, float *alpha, float *A, int *lda, float *B, int *ldb, float *beta, float *C, int *ldc); -void ssyrk_(char *uplo, char *trans, int *n, int *k, float *alpha, float *A, int *lda, float *beta, float *C, int *ldc); -void strmm_(char *side, char *uplo, char *transa, char *diag, int *m, int *n, float *alpha, float *A, int *lda, float *B, int *ldb); -void strsm_(char *side, char *uplo, char *transa, char *diag, int *m, int *n, float *alpha, float *A, int *lda, float *B, int *ldb); -void ssyr2k_(char *uplo, char *trans, int *n, int *k, float *alpha, float *A, int *lda, float *B, int *ldb, float *beta, float *C, int *ldc); - -// lapack -void spotrf_(char *uplo, int *m, float *A, int *lda, int *info); -void sgetrf_(int *m, int *n, float *A, int *lda, int *ipiv, int *info); -void sgeqrf_(int *m, int *n, float *A, int *lda, float *tau, float *work, int *lwork, int *info); -void sgeqr2_(int *m, int *n, float *A, int *lda, float *tau, float *work, int *info); -void sgelqf_(int *m, int *n, float *A, int *lda, float *tau, float *work, int *lwork, int *info); -void sorglq_(int *m, int *n, int *k, float *A, int *lda, float *tau, float *work, int *lwork, int *info); - - - -#ifdef __cplusplus -} -#endif diff --git a/third_party/acados/include/blasfeo/include/s_blas_64.h b/third_party/acados/include/blasfeo/include/s_blas_64.h deleted file mode 100644 index b9efab6c23..0000000000 --- a/third_party/acados/include/blasfeo/include/s_blas_64.h +++ /dev/null @@ -1,73 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of BLASFEO. * -* * -* BLASFEO -- BLAS For Embedded Optimization. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifdef __cplusplus -extern "C" { -#endif - - - -// headers to reference BLAS and LAPACK routines employed in BLASFEO WR - -// level 1 -float sdot_(long long *m, float *x, long long *incx, float *y, long long *incy); -void scopy_(long long *m, float *x, long long *incx, float *y, long long *incy); -void saxpy_(long long *m, float *alpha, float *x, long long *incx, float *y, long long *incy); -void sscal_(long long *m, float *alpha, float *x, long long *incx); - -// level 2 -void sgemv_(char *ta, long long *m, long long *n, float *alpha, float *A, long long *lda, float *x, long long *incx, float *beta, float *y, long long *incy); -void ssymv_(char *uplo, long long *m, float *alpha, float *A, long long *lda, float *x, long long *incx, float *beta, float *y, long long *incy); -void strmv_(char *uplo, char *trans, char *diag, long long *n, float *A, long long *lda, float *x, long long *incx); -void strsv_(char *uplo, char *trans, char *diag, long long *n, float *A, long long *lda, float *x, long long *incx); -void sger_(long long *m, long long *n, float *alpha, float *x, long long *incx, float *y, long long *incy, float *A, long long *lda); - -// level 3 -void sgemm_(char *ta, char *tb, long long *m, long long *n, long long *k, float *alpha, float *A, long long *lda, float *B, long long *ldb, float *beta, float *C, long long *ldc); -void ssyrk_(char *uplo, char *trans, long long *n, long long *k, float *alpha, float *A, long long *lda, float *beta, float *C, long long *ldc); -void strmm_(char *side, char *uplo, char *transa, char *diag, long long *m, long long *n, float *alpha, float *A, long long *lda, float *B, long long *ldb); -void strsm_(char *side, char *uplo, char *transa, char *diag, long long *m, long long *n, float *alpha, float *A, long long *lda, float *B, long long *ldb); - -// lapack -void spotrf_(char *uplo, long long *m, float *A, long long *lda, long long *info); -void sgetrf_(long long *m, long long *n, float *A, long long *lda, long long *ipiv, long long *info); -void sgeqrf_(long long *m, long long *n, float *A, long long *lda, float *tau, float *work, long long *lwork, long long *info); -void sgeqr2_(long long *m, long long *n, float *A, long long *lda, float *tau, float *work, long long *info); - - - -#ifdef __cplusplus -} -#endif diff --git a/third_party/acados/include/hpipm/include/hpipm_aux_mem.h b/third_party/acados/include/hpipm/include/hpipm_aux_mem.h deleted file mode 100644 index 7bd3d7e8bc..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_aux_mem.h +++ /dev/null @@ -1,52 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_AUX_MEM_H_ -#define HPIPM_AUX_MEM_H_ - -#include "hpipm_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - -void hpipm_zero_memset(hpipm_size_t memsize, void *mem); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // HPIPM_AUX_MEM_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_aux_string.h b/third_party/acados/include/hpipm/include/hpipm_aux_string.h deleted file mode 100644 index 804cba5dc1..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_aux_string.h +++ /dev/null @@ -1,50 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_AUX_STRING_H_ -#define HPIPM_AUX_STRING_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#define MAX_STR_LEN 5 -int hpipm_strcmp(char *str1, char *str2); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // HPIPM_AUX_STRING_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_common.h b/third_party/acados/include/hpipm/include/hpipm_common.h deleted file mode 100644 index 0cc96a7b50..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_common.h +++ /dev/null @@ -1,76 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_COMMON_H_ -#define HPIPM_COMMON_H_ - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -typedef size_t hpipm_size_t; - -enum hpipm_mode - { - SPEED_ABS, // focus on speed, absolute IPM formulation - SPEED, // focus on speed, relative IPM formulation - BALANCE, // balanced mode, relative IPM formulation - ROBUST, // focus on robustness, relative IPM formulation - }; - -enum hpipm_status - { - SUCCESS, // found solution satisfying accuracy tolerance - MAX_ITER, // maximum iteration number reached - MIN_STEP, // minimum step length reached - NAN_SOL, // NaN in solution detected - INCONS_EQ, // unconsistent equality constraints - }; - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_COMMON_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_cast_qcqp.h b/third_party/acados/include/hpipm/include/hpipm_d_cast_qcqp.h deleted file mode 100644 index 0e4c41f221..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_cast_qcqp.h +++ /dev/null @@ -1,71 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_D_CAST_QCQP_H_ -#define HPIPM_D_CAST_QCQP_H_ - - - -#include -#include - -#include "hpipm_d_dense_qcqp.h" -#include "hpipm_d_dense_qcqp_sol.h" -#include "hpipm_d_ocp_qcqp.h" -#include "hpipm_d_ocp_qcqp_dim.h" -#include "hpipm_d_ocp_qcqp_sol.h" - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -void d_cast_qcqp_compute_dim(struct d_ocp_qcqp_dim *ocp_dim, struct d_dense_qcqp_dim *dense_dim); -// -void d_cast_qcqp_cond(struct d_ocp_qcqp *ocp_qp, struct d_dense_qcqp *dense_qp); - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_D_CAST_QCQP_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_cond.h b/third_party/acados/include/hpipm/include/hpipm_d_cond.h deleted file mode 100644 index 5900a2ab10..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_cond.h +++ /dev/null @@ -1,135 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_D_COND_H_ -#define HPIPM_D_COND_H_ - - - -#include -#include - -#include "hpipm_d_dense_qp.h" -#include "hpipm_d_dense_qp_sol.h" -#include "hpipm_d_ocp_qp.h" -#include "hpipm_d_ocp_qp_dim.h" -#include "hpipm_d_ocp_qp_sol.h" - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_cond_qp_arg - { - int cond_last_stage; // condense last stage - int cond_alg; // condensing algorithm: 0 N2-nx3, 1 N3-nx2 - int comp_prim_sol; // primal solution (v) - int comp_dual_sol_eq; // dual solution equality constr (pi) - int comp_dual_sol_ineq; // dual solution inequality constr (lam t) - int square_root_alg; // square root algorithm (faster but requires RSQ>0) - hpipm_size_t memsize; - }; - - - -struct d_cond_qp_ws - { - struct blasfeo_dmat *Gamma; - struct blasfeo_dmat *GammaQ; - struct blasfeo_dmat *L; - struct blasfeo_dmat *Lx; - struct blasfeo_dmat *AL; - struct blasfeo_dvec *Gammab; - struct blasfeo_dvec *l; - struct blasfeo_dvec *tmp_nbgM; - struct blasfeo_dvec *tmp_nuxM; - int bs; // block size - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_cond_qp_arg_memsize(); -// -void d_cond_qp_arg_create(struct d_cond_qp_arg *cond_arg, void *mem); -// -void d_cond_qp_arg_set_default(struct d_cond_qp_arg *cond_arg); -// condensing algorithm: 0 N2-nx3, 1 N3-nx2 -void d_cond_qp_arg_set_cond_alg(int cond_alg, struct d_cond_qp_arg *cond_arg); -// set riccati-like algorithm: 0 classical, 1 square-root -void d_cond_qp_arg_set_ric_alg(int ric_alg, struct d_cond_qp_arg *cond_arg); -// condense last stage: 0 last stage disregarded, 1 last stage condensed too -void d_cond_qp_arg_set_cond_last_stage(int cond_last_stage, struct d_cond_qp_arg *cond_arg); -// -void d_cond_qp_arg_set_comp_prim_sol(int value, struct d_cond_qp_arg *cond_arg); -// -void d_cond_qp_arg_set_comp_dual_sol_eq(int value, struct d_cond_qp_arg *cond_arg); -// -void d_cond_qp_arg_set_comp_dual_sol_ineq(int value, struct d_cond_qp_arg *cond_arg); - -// -void d_cond_qp_compute_dim(struct d_ocp_qp_dim *ocp_dim, struct d_dense_qp_dim *dense_dim); -// -hpipm_size_t d_cond_qp_ws_memsize(struct d_ocp_qp_dim *ocp_dim, struct d_cond_qp_arg *cond_arg); -// -void d_cond_qp_ws_create(struct d_ocp_qp_dim *ocp_dim, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws, void *mem); -// -void d_cond_qp_cond(struct d_ocp_qp *ocp_qp, struct d_dense_qp *dense_qp, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws); -// -void d_cond_qp_cond_lhs(struct d_ocp_qp *ocp_qp, struct d_dense_qp *dense_qp, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws); -// -void d_cond_qp_cond_rhs(struct d_ocp_qp *ocp_qp, struct d_dense_qp *dense_qp, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws); -// -void d_cond_qp_expand_sol(struct d_ocp_qp *ocp_qp, struct d_dense_qp_sol *dense_qp_sol, struct d_ocp_qp_sol *ocp_qp_sol, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws); -// TODO remove -void d_cond_qp_expand_primal_sol(struct d_ocp_qp *ocp_qp, struct d_dense_qp_sol *dense_qp_sol, struct d_ocp_qp_sol *ocp_qp_sol, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws); - -// -void d_cond_qp_update(int *idxc, struct d_ocp_qp *ocp_qp, struct d_dense_qp *dense_qp, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_D_COND_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_cond_aux.h b/third_party/acados/include/hpipm/include/hpipm_d_cond_aux.h deleted file mode 100644 index 73afba3c7e..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_cond_aux.h +++ /dev/null @@ -1,92 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_D_COND_AUX_H_ -#define HPIPM_D_COND_AUX_H_ - - - -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -void d_cond_BAbt(struct d_ocp_qp *ocp_qp, struct blasfeo_dmat *BAbt2, struct blasfeo_dvec *b, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws); -// -void d_cond_BAt(struct d_ocp_qp *ocp_qp, struct blasfeo_dmat *BAbt2, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws); -// -void d_cond_b(struct d_ocp_qp *ocp_qp, struct blasfeo_dvec *b, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws); -// -void d_cond_RSQrq(struct d_ocp_qp *ocp_qp, struct blasfeo_dmat *RSQrq2, struct blasfeo_dvec *rq, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws); -// -void d_cond_RSQ(struct d_ocp_qp *ocp_qp, struct blasfeo_dmat *RSQrq2, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws); -// -void d_cond_rq(struct d_ocp_qp *ocp_qp, struct blasfeo_dvec *rq, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws); -// -void d_cond_DCtd(struct d_ocp_qp *ocp_qp, int *idxb2, struct blasfeo_dmat *DCt2, struct blasfeo_dvec *d2, struct blasfeo_dvec *d_mask2, int *idxs_rev2, struct blasfeo_dvec *Z2, struct blasfeo_dvec *z, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws); -// -void d_cond_DCt(struct d_ocp_qp *ocp_qp, int *idxb2, struct blasfeo_dmat *DCt2, int *idxs_rev2, struct blasfeo_dvec *Z2, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws); -// -void d_cond_d(struct d_ocp_qp *ocp_qp, struct blasfeo_dvec *d2, struct blasfeo_dvec *d_mask2, struct blasfeo_dvec *z, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws); -// -void d_expand_sol(struct d_ocp_qp *ocp_qp, struct d_dense_qp_sol *dense_qp_sol, struct d_ocp_qp_sol *ocp_qp_so, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws); -// -void d_expand_primal_sol(struct d_ocp_qp *ocp_qp, struct d_dense_qp_sol *dense_qp_sol, struct d_ocp_qp_sol *ocp_qp_so, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws); - -// -void d_update_cond_BAbt(int *idxc, struct d_ocp_qp *ocp_qp, struct blasfeo_dmat *BAbt2, struct blasfeo_dvec *b, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws); -// -void d_update_cond_RSQrq_N2nx3(int *idxc, struct d_ocp_qp *ocp_qp, struct blasfeo_dmat *RSQrq2, struct blasfeo_dvec *rq, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws); -// -void d_update_cond_DCtd(int *idxc, struct d_ocp_qp *ocp_qp, int *idxb2, struct blasfeo_dmat *DCt2, struct blasfeo_dvec *d2, int *idxs2, struct blasfeo_dvec *Z2, struct blasfeo_dvec *z, struct d_cond_qp_arg *cond_arg, struct d_cond_qp_ws *cond_ws); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_D_COND_AUX_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_cond_qcqp.h b/third_party/acados/include/hpipm/include/hpipm_d_cond_qcqp.h deleted file mode 100644 index 266567bb8d..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_cond_qcqp.h +++ /dev/null @@ -1,129 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_D_COND_QCQP_H_ -#define HPIPM_D_COND_QCQP_H_ - - - -#include -#include - -#include "hpipm_d_dense_qcqp.h" -#include "hpipm_d_dense_qcqp_sol.h" -#include "hpipm_d_ocp_qcqp.h" -#include "hpipm_d_ocp_qcqp_dim.h" -#include "hpipm_d_ocp_qcqp_sol.h" - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_cond_qcqp_arg - { - struct d_cond_qp_arg *qp_arg; - int cond_last_stage; // condense last stage -// int cond_variant; // TODO - int comp_prim_sol; // primal solution (v) - int comp_dual_sol_eq; // dual solution equality constr (pi) - int comp_dual_sol_ineq; // dual solution equality constr (lam t) - int square_root_alg; // square root algorithm (faster but requires RSQ>0) - hpipm_size_t memsize; - }; - - - -struct d_cond_qcqp_ws - { - struct d_cond_qp_ws *qp_ws; - struct blasfeo_dmat *hess_array; // TODO remove - struct blasfeo_dmat *zero_hess; // TODO remove - struct blasfeo_dvec *grad_array; // TODO remove - struct blasfeo_dvec *zero_grad; // TODO remove - struct blasfeo_dvec *tmp_nvc; - struct blasfeo_dvec *tmp_nuxM; - struct blasfeo_dmat *GammaQ; - struct blasfeo_dmat *tmp_DCt; - struct blasfeo_dmat *tmp_nuM_nxM; -// struct blasfeo_dvec *d_qp; -// struct blasfeo_dvec *d_mask_qp; - hpipm_size_t memsize; - }; - - -// -hpipm_size_t d_cond_qcqp_arg_memsize(); -// -void d_cond_qcqp_arg_create(struct d_cond_qcqp_arg *cond_arg, void *mem); -// -void d_cond_qcqp_arg_set_default(struct d_cond_qcqp_arg *cond_arg); -// set riccati-like algorithm: 0 classical, 1 square-root -void d_cond_qcqp_arg_set_ric_alg(int ric_alg, struct d_cond_qcqp_arg *cond_arg); -// condense last stage: 0 last stage disregarded, 1 last stage condensed too -void d_cond_qcqp_arg_set_cond_last_stage(int cond_last_stage, struct d_cond_qcqp_arg *cond_arg); - -// -void d_cond_qcqp_compute_dim(struct d_ocp_qcqp_dim *ocp_dim, struct d_dense_qcqp_dim *dense_dim); -// -hpipm_size_t d_cond_qcqp_ws_memsize(struct d_ocp_qcqp_dim *ocp_dim, struct d_cond_qcqp_arg *cond_arg); -// -void d_cond_qcqp_ws_create(struct d_ocp_qcqp_dim *ocp_dim, struct d_cond_qcqp_arg *cond_arg, struct d_cond_qcqp_ws *cond_ws, void *mem); -// -void d_cond_qcqp_qc(struct d_ocp_qcqp *ocp_qp, struct blasfeo_dmat *Hq2, int *Hq_nzero2, struct blasfeo_dmat *Ct2, struct blasfeo_dvec *d2, struct d_cond_qcqp_arg *cond_arg, struct d_cond_qcqp_ws *cond_ws); -// -void d_cond_qcqp_qc_lhs(struct d_ocp_qcqp *ocp_qp, struct blasfeo_dmat *Hq2, int *Hq_nzero2, struct blasfeo_dmat *Ct2, struct d_cond_qcqp_arg *cond_arg, struct d_cond_qcqp_ws *cond_ws); -// -void d_cond_qcqp_qc_rhs(struct d_ocp_qcqp *ocp_qp, struct blasfeo_dvec *d2, struct d_cond_qcqp_arg *cond_arg, struct d_cond_qcqp_ws *cond_ws); -// -void d_cond_qcqp_cond(struct d_ocp_qcqp *ocp_qp, struct d_dense_qcqp *dense_qp, struct d_cond_qcqp_arg *cond_arg, struct d_cond_qcqp_ws *cond_ws); -// -void d_cond_qcqp_cond_rhs(struct d_ocp_qcqp *ocp_qp, struct d_dense_qcqp *dense_qp, struct d_cond_qcqp_arg *cond_arg, struct d_cond_qcqp_ws *cond_ws); -// -void d_cond_qcqp_cond_lhs(struct d_ocp_qcqp *ocp_qp, struct d_dense_qcqp *dense_qp, struct d_cond_qcqp_arg *cond_arg, struct d_cond_qcqp_ws *cond_ws); -// -void d_cond_qcqp_expand_sol(struct d_ocp_qcqp *ocp_qp, struct d_dense_qcqp_sol *dense_qp_sol, struct d_ocp_qcqp_sol *ocp_qp_sol, struct d_cond_qcqp_arg *cond_arg, struct d_cond_qcqp_ws *cond_ws); - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_D_COND_QCQP_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_core_qp_ipm.h b/third_party/acados/include/hpipm/include/hpipm_d_core_qp_ipm.h deleted file mode 100644 index f39d9a9b50..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_core_qp_ipm.h +++ /dev/null @@ -1,101 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_CORE_QP_IPM_ -#define HPIPM_D_CORE_QP_IPM_ - -#include "hpipm_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - -struct d_core_qp_ipm_workspace - { - double *v; // primal variables - double *pi; // equality constraints multipliers - double *lam; // inequality constraints multipliers - double *t; // inequality constraints slacks - double *t_inv; // inverse of t - double *v_bkp; // backup of primal variables - double *pi_bkp; // backup of equality constraints multipliers - double *lam_bkp; // backup of inequality constraints multipliers - double *t_bkp; // backup of inequality constraints slacks - double *dv; // step in v - double *dpi; // step in pi - double *dlam; // step in lam - double *dt; // step in t - double *res_g; // q-residuals - double *res_b; // b-residuals - double *res_d; // d-residuals - double *res_m; // m-residuals - double *res_m_bkp; // m-residuals - double *Gamma; // Hessian update - double *gamma; // gradient update - double alpha; // step length - double alpha_prim; // step length - double alpha_dual; // step length - double sigma; // centering XXX - double mu; // duality measuere - double mu_aff; // affine duality measuere - double nc_inv; // 1.0/nc, where nc is the total number of inequality constraints - double nc_mask_inv; // 1.0/nc_mask - double lam_min; // min value in lam vector - double t_min; // min value in t vector - double t_min_inv; // inverse of min value in t vector - double tau_min; // min value of barrier parameter - int nv; // number of primal variables - int ne; // number of equality constraints - int nc; // (twice the) number of (two-sided) inequality constraints - int nc_mask; // total number of ineq constr after masking - int split_step; // use different step for primal and dual variables - int t_lam_min; // clip t and lam also in solution, or only in Gamma computation - hpipm_size_t memsize; // memory size (in bytes) of workspace - }; - - - -// -hpipm_size_t d_memsize_core_qp_ipm(int nv, int ne, int nc); -// -void d_create_core_qp_ipm(int nv, int ne, int nc, struct d_core_qp_ipm_workspace *workspace, void *mem); -// -void d_core_qp_ipm(struct d_core_qp_ipm_workspace *workspace); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // HPIPM_D_CORE_QP_IPM_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_core_qp_ipm_aux.h b/third_party/acados/include/hpipm/include/hpipm_d_core_qp_ipm_aux.h deleted file mode 100644 index 30cc824bad..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_core_qp_ipm_aux.h +++ /dev/null @@ -1,68 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_CORE_QP_IPM_AUX_ -#define HPIPM_S_CORE_QP_IPM_AUX_ - -#ifdef __cplusplus -extern "C" { -#endif - -// -void d_compute_Gamma_gamma_qp(double *res_d, double *res_m, struct d_core_qp_ipm_workspace *rws); -// -void d_compute_gamma_qp(double *res_d, double *res_m, struct d_core_qp_ipm_workspace *rws); -// -void d_compute_lam_t_qp(double *res_d, double *res_m, double *dlam, double *dt, struct d_core_qp_ipm_workspace *rws); -// -void d_compute_alpha_qp(struct d_core_qp_ipm_workspace *rws); -// -void d_update_var_qp(struct d_core_qp_ipm_workspace *rws); -// -void d_compute_mu_aff_qp(struct d_core_qp_ipm_workspace *rws); -// -void d_backup_res_m(struct d_core_qp_ipm_workspace *rws); -// -void d_compute_centering_correction_qp(struct d_core_qp_ipm_workspace *rws); -// -void d_compute_centering_qp(struct d_core_qp_ipm_workspace *rws); -// -void d_compute_tau_min_qp(struct d_core_qp_ipm_workspace *rws); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // HPIPM_S_CORE_QP_IPM_AUX_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_dense_qcqp.h b/third_party/acados/include/hpipm/include/hpipm_d_dense_qcqp.h deleted file mode 100644 index 3da5716493..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_dense_qcqp.h +++ /dev/null @@ -1,199 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_D_DENSE_QCQP_H_ -#define HPIPM_D_DENSE_QCQP_H_ - - - -#include -#include - -#include "hpipm_d_dense_qcqp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_dense_qcqp - { - struct d_dense_qcqp_dim *dim; - struct blasfeo_dmat *Hv; // hessian of cost & vector work space - struct blasfeo_dmat *A; // equality constraint matrix - struct blasfeo_dmat *Ct; // inequality constraints matrix - struct blasfeo_dmat *Hq; // hessians of quadratic constraints - struct blasfeo_dvec *gz; // gradient of cost & gradient of slacks - struct blasfeo_dvec *b; // equality constraint vector - struct blasfeo_dvec *d; // inequality constraints vector - struct blasfeo_dvec *d_mask; // inequality constraints mask vector - struct blasfeo_dvec *m; // rhs of complementarity condition - struct blasfeo_dvec *Z; // (diagonal) hessian of slacks - int *idxb; // indices of box constrained variables within [u; x] - int *idxs_rev; // index of soft constraints (reverse storage) - int *Hq_nzero; // for each int, the last 3 bits ...abc, {a,b,c}=0 => {R,S,Q}=0 - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -hpipm_size_t d_dense_qcqp_memsize(struct d_dense_qcqp_dim *dim); -// -void d_dense_qcqp_create(struct d_dense_qcqp_dim *dim, struct d_dense_qcqp *qp, void *memory); - -// -void d_dense_qcqp_set(char *field, void *value, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_H(double *H, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_g(double *g, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_A(double *A, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_b(double *b, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_idxb(int *idxb, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_lb(double *lb, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_lb_mask(double *lb, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_ub(double *ub, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_ub_mask(double *ub, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_C(double *C, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_lg(double *lg, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_lg_mask(double *lg, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_ug(double *ug, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_ug_mask(double *ug, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_Hq(double *Hq, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_gq(double *gq, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_uq(double *uq, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_uq_mask(double *uq, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_idxs(int *idxs, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_idxs_rev(int *idxs_rev, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_Zl(double *Zl, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_Zu(double *Zu, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_zl(double *zl, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_zu(double *zu, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_ls(double *ls, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_ls_mask(double *ls, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_us(double *us, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_set_us_mask(double *us, struct d_dense_qcqp *qp); - -// getters (COLMAJ) - -void d_dense_qcqp_get_H(struct d_dense_qcqp *qp, double *H); -// -void d_dense_qcqp_get_g(struct d_dense_qcqp *qp, double *g); -// -void d_dense_qcqp_get_A(struct d_dense_qcqp *qp, double *A); -// -void d_dense_qcqp_get_b(struct d_dense_qcqp *qp, double *b); -// -void d_dense_qcqp_get_idxb(struct d_dense_qcqp *qp, int *idxb); -// -void d_dense_qcqp_get_lb(struct d_dense_qcqp *qp, double *lb); -// -void d_dense_qcqp_get_lb_mask(struct d_dense_qcqp *qp, double *lb); -// -void d_dense_qcqp_get_ub(struct d_dense_qcqp *qp, double *ub); -// -void d_dense_qcqp_get_ub_mask(struct d_dense_qcqp *qp, double *ub); -// -void d_dense_qcqp_get_C(struct d_dense_qcqp *qp, double *C); -// -void d_dense_qcqp_get_lg(struct d_dense_qcqp *qp, double *lg); -// -void d_dense_qcqp_get_lg_mask(struct d_dense_qcqp *qp, double *lg); -// -void d_dense_qcqp_get_ug(struct d_dense_qcqp *qp, double *ug); -// -void d_dense_qcqp_get_ug_mask(struct d_dense_qcqp *qp, double *ug); -// -void d_dense_qcqp_get_idxs(struct d_dense_qcqp *qp, int *idxs); -// -void d_dense_qcqp_get_idxs_rev(struct d_dense_qcqp *qp, int *idxs_rev); -// -void d_dense_qcqp_get_Zl(struct d_dense_qcqp *qp, double *Zl); -// -void d_dense_qcqp_get_Zu(struct d_dense_qcqp *qp, double *Zu); -// -void d_dense_qcqp_get_zl(struct d_dense_qcqp *qp, double *zl); -// -void d_dense_qcqp_get_zu(struct d_dense_qcqp *qp, double *zu); -// -void d_dense_qcqp_get_ls(struct d_dense_qcqp *qp, double *ls); -// -void d_dense_qcqp_get_ls_mask(struct d_dense_qcqp *qp, double *ls); -// -void d_dense_qcqp_get_us(struct d_dense_qcqp *qp, double *us); -// -void d_dense_qcqp_get_us_mask(struct d_dense_qcqp *qp, double *us); - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_D_DENSE_QCQP_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_dense_qcqp_dim.h b/third_party/acados/include/hpipm/include/hpipm_d_dense_qcqp_dim.h deleted file mode 100644 index fa8c574a1e..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_dense_qcqp_dim.h +++ /dev/null @@ -1,98 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_DENSE_QCQP_DIM_H_ -#define HPIPM_D_DENSE_QCQP_DIM_H_ - -#include "hpipm_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_dense_qcqp_dim - { - struct d_dense_qp_dim *qp_dim; // dim of qp approximation - int nv; // number of variables - int ne; // number of equality constraints - int nb; // number of box constraints - int ng; // number of general constraints - int nq; // number of quadratic constraints - int nsb; // number of softened box constraints - int nsg; // number of softened general constraints - int nsq; // number of softened quadratic constraints - int ns; // number of softened constraints (nsb+nsg+nsq) TODO number of slacks - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_dense_qcqp_dim_memsize(); -// -void d_dense_qcqp_dim_create(struct d_dense_qcqp_dim *dim, void *memory); -// -void d_dense_qcqp_dim_set(char *field_name, int value, struct d_dense_qcqp_dim *dim); -// -void d_dense_qcqp_dim_set_nv(int value, struct d_dense_qcqp_dim *dim); -// -void d_dense_qcqp_dim_set_ne(int value, struct d_dense_qcqp_dim *dim); -// -void d_dense_qcqp_dim_set_nb(int value, struct d_dense_qcqp_dim *dim); -// -void d_dense_qcqp_dim_set_ng(int value, struct d_dense_qcqp_dim *dim); -// -void d_dense_qcqp_dim_set_nq(int value, struct d_dense_qcqp_dim *dim); -// -void d_dense_qcqp_dim_set_nsb(int value, struct d_dense_qcqp_dim *dim); -// -void d_dense_qcqp_dim_set_nsg(int value, struct d_dense_qcqp_dim *dim); -// -void d_dense_qcqp_dim_set_nsq(int value, struct d_dense_qcqp_dim *dim); -// -void d_dense_qcqp_dim_set_ns(int value, struct d_dense_qcqp_dim *dim); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_D_DENSE_QCQP_DIM_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_dense_qcqp_ipm.h b/third_party/acados/include/hpipm/include/hpipm_d_dense_qcqp_ipm.h deleted file mode 100644 index fa3f98fa79..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_dense_qcqp_ipm.h +++ /dev/null @@ -1,193 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_D_DENSE_QCQP_IPM_H_ -#define HPIPM_D_DENSE_QCQP_IPM_H_ - - - -#include -#include - -#include -#include -#include -#include -#include - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_dense_qcqp_ipm_arg - { - struct d_dense_qp_ipm_arg *qp_arg; - double mu0; // initial value for duality measure - double alpha_min; // exit cond on step length - double res_g_max; // exit cond on inf norm of residuals - double res_b_max; // exit cond on inf norm of residuals - double res_d_max; // exit cond on inf norm of residuals - double res_m_max; // exit cond on inf norm of residuals - double reg_prim; // reg of primal hessian - double reg_dual; // reg of dual hessian - double lam_min; // min value in lam vector - double t_min; // min value in t vector - int iter_max; // exit cond in iter number - int stat_max; // iterations saved in stat - int pred_corr; // Mehrotra's predictor-corrector IPM algirthm - int cond_pred_corr; // conditional Mehrotra's predictor-corrector - int scale; // scale hessian - int itref_pred_max; // max number of iterative refinement steps for predictor step - int itref_corr_max; // max number of iterative refinement steps for corrector step - int warm_start; // 0 no warm start, 1 warm start primal sol, 2 warm start primal and dual sol - int lq_fact; // 0 syrk+potrf, 1 mix, 2 lq - int abs_form; // absolute IPM formulation - int comp_res_exit; // compute residuals on exit (only for abs_form==1) - int comp_res_pred; // compute residuals of prediction - int split_step; // use different step for primal and dual variables - int t_lam_min; // clip t and lam: 0 no, 1 in Gamma computation, 2 in solution - int mode; - hpipm_size_t memsize; - }; - - - -struct d_dense_qcqp_ipm_ws - { - struct d_dense_qp_ipm_ws *qp_ws; - struct d_dense_qp *qp; - struct d_dense_qp_sol *qp_sol; - struct d_dense_qcqp_res_ws *qcqp_res_ws; - struct d_dense_qcqp_res *qcqp_res; - struct blasfeo_dvec *tmp_nv; - int iter; // iteration number - int status; - hpipm_size_t memsize; // memory size (in bytes) of workspace - }; - - - -// -hpipm_size_t d_dense_qcqp_ipm_arg_memsize(struct d_dense_qcqp_dim *dim); -// -void d_dense_qcqp_ipm_arg_create(struct d_dense_qcqp_dim *dim, struct d_dense_qcqp_ipm_arg *arg, void *mem); -// -void d_dense_qcqp_ipm_arg_set_default(enum hpipm_mode mode, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_ipm_arg_set(char *field, void *value, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_ipm_arg_set_iter_max(int *iter_max, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_ipm_arg_set_alpha_min(double *alpha_min, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_ipm_arg_set_mu0(double *mu0, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_ipm_arg_set_tol_stat(double *tol_stat, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_ipm_arg_set_tol_eq(double *tol_eq, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_ipm_arg_set_tol_ineq(double *tol_ineq, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_ipm_arg_set_tol_comp(double *tol_comp, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_ipm_arg_set_reg_prim(double *reg, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_ipm_arg_set_reg_dual(double *reg, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_ipm_arg_set_warm_start(int *warm_start, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_ipm_arg_set_pred_corr(int *pred_corr, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_ipm_arg_set_cond_pred_corr(int *cond_pred_corr, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_ipm_arg_set_comp_res_pred(int *comp_res_pred, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_ipm_arg_set_comp_res_exit(int *comp_res_exit, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_ipm_arg_set_lam_min(double *value, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_ipm_arg_set_t_min(double *value, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_ipm_arg_set_split_step(int *value, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_ipm_arg_set_t_lam_min(int *value, struct d_dense_qcqp_ipm_arg *arg); - -// -hpipm_size_t d_dense_qcqp_ipm_ws_memsize(struct d_dense_qcqp_dim *qp_dim, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_ipm_ws_create(struct d_dense_qcqp_dim *qp_dim, struct d_dense_qcqp_ipm_arg *arg, struct d_dense_qcqp_ipm_ws *ws, void *mem); -// -void d_dense_qcqp_ipm_get(char *field, struct d_dense_qcqp_ipm_ws *ws, void *value); -// -void d_dense_qcqp_ipm_get_status(struct d_dense_qcqp_ipm_ws *ws, int *status); -// -void d_dense_qcqp_ipm_get_iter(struct d_dense_qcqp_ipm_ws *ws, int *iter); -// -void d_dense_qcqp_ipm_get_max_res_stat(struct d_dense_qcqp_ipm_ws *ws, double *res_stat); -// -void d_dense_qcqp_ipm_get_max_res_eq(struct d_dense_qcqp_ipm_ws *ws, double *res_eq); -// -void d_dense_qcqp_ipm_get_max_res_ineq(struct d_dense_qcqp_ipm_ws *ws, double *res_ineq); -// -void d_dense_qcqp_ipm_get_max_res_comp(struct d_dense_qcqp_ipm_ws *ws, double *res_comp); -// -void d_dense_qcqp_ipm_get_stat(struct d_dense_qcqp_ipm_ws *ws, double **stat); -// -void d_dense_qcqp_ipm_get_stat_m(struct d_dense_qcqp_ipm_ws *ws, int *stat_m); -// -void d_dense_qcqp_init_var(struct d_dense_qcqp *qp, struct d_dense_qcqp_sol *qp_sol, struct d_dense_qcqp_ipm_arg *arg, struct d_dense_qcqp_ipm_ws *ws); -// -void d_dense_qcqp_ipm_solve(struct d_dense_qcqp *qp, struct d_dense_qcqp_sol *qp_sol, struct d_dense_qcqp_ipm_arg *arg, struct d_dense_qcqp_ipm_ws *ws); -#if 0 -// -void d_dense_qcqp_ipm_predict(struct d_dense_qcqp *qp, struct d_dense_qcqp_sol *qp_sol, struct d_dense_qcqp_ipm_arg *arg, struct d_dense_qcqp_ipm_ws *ws); -// -void d_dense_qcqp_ipm_sens(struct d_dense_qcqp *qp, struct d_dense_qcqp_sol *qp_sol, struct d_dense_qcqp_ipm_arg *arg, struct d_dense_qcqp_ipm_ws *ws); -#endif - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_D_DENSE_QCQP_IPM_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_dense_qcqp_res.h b/third_party/acados/include/hpipm/include/hpipm_d_dense_qcqp_res.h deleted file mode 100644 index a76f16215e..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_dense_qcqp_res.h +++ /dev/null @@ -1,107 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_DENSE_QCQP_RES_H_ -#define HPIPM_D_DENSE_QCQP_RES_H_ - - - -#include -#include - -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_dense_qcqp_res - { - struct d_dense_qcqp_dim *dim; - struct blasfeo_dvec *res_g; // q-residuals - struct blasfeo_dvec *res_b; // b-residuals - struct blasfeo_dvec *res_d; // d-residuals - struct blasfeo_dvec *res_m; // m-residuals - double res_max[4]; // infinity norm of residuals - double res_mu; // mu-residual - hpipm_size_t memsize; - }; - - - -struct d_dense_qcqp_res_ws - { - struct blasfeo_dvec *tmp_nv; // work space of size nv - struct blasfeo_dvec *tmp_nbgq; // work space of size nbM+ngM+nqM - struct blasfeo_dvec *tmp_ns; // work space of size nsM - struct blasfeo_dvec *q_fun; // value for evaluation of quadr constr - struct blasfeo_dvec *q_adj; // value for adjoint of quadr constr - int use_q_fun; // reuse cached value for evaluation of quadr constr - int use_q_adj; // reuse cached value for adjoint of quadr constr - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_dense_qcqp_res_memsize(struct d_dense_qcqp_dim *dim); -// -void d_dense_qcqp_res_create(struct d_dense_qcqp_dim *dim, struct d_dense_qcqp_res *res, void *mem); -// -hpipm_size_t d_dense_qcqp_res_ws_memsize(struct d_dense_qcqp_dim *dim); -// -void d_dense_qcqp_res_ws_create(struct d_dense_qcqp_dim *dim, struct d_dense_qcqp_res_ws *workspace, void *mem); -// -void d_dense_qcqp_res_compute(struct d_dense_qcqp *qp, struct d_dense_qcqp_sol *qp_sol, struct d_dense_qcqp_res *res, struct d_dense_qcqp_res_ws *ws); -// -void d_dense_qcqp_res_compute_inf_norm(struct d_dense_qcqp_res *res); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - -#endif // HPIPM_D_DENSE_QCQP_RES_H_ - - - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_dense_qcqp_sol.h b/third_party/acados/include/hpipm/include/hpipm_d_dense_qcqp_sol.h deleted file mode 100644 index 6c697a8e69..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_dense_qcqp_sol.h +++ /dev/null @@ -1,85 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_D_DENSE_QCQP_SOL_H_ -#define HPIPM_D_DENSE_QCQP_SOL_H_ - - - -#include -#include - -#include "hpipm_d_dense_qcqp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_dense_qcqp_sol - { - struct d_dense_qcqp_dim *dim; - struct blasfeo_dvec *v; - struct blasfeo_dvec *pi; - struct blasfeo_dvec *lam; - struct blasfeo_dvec *t; - void *misc; - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_dense_qcqp_sol_memsize(struct d_dense_qcqp_dim *dim); -// -void d_dense_qcqp_sol_create(struct d_dense_qcqp_dim *dim, struct d_dense_qcqp_sol *qp_sol, void *memory); -// -void d_dense_qcqp_sol_get_v(struct d_dense_qcqp_sol *qp_sol, double *v); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_D_DENSE_QCQP_SOL_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_dense_qcqp_utils.h b/third_party/acados/include/hpipm/include/hpipm_d_dense_qcqp_utils.h deleted file mode 100644 index a34218bae4..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_dense_qcqp_utils.h +++ /dev/null @@ -1,82 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_DENSE_QCQP_UTILS_H_ -#define HPIPM_D_DENSE_QCQP_UTILS_H_ - - - -#include -#include - -#include "hpipm_d_dense_qcqp_dim.h" -#include "hpipm_d_dense_qcqp.h" -#include "hpipm_d_dense_qcqp_sol.h" -//#include "hpipm_d_dense_qcqp_ipm.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -void d_dense_qcqp_dim_print(struct d_dense_qcqp_dim *qp_dim); -// -//void d_dense_qcqp_dim_codegen(char *file_name, char *mode, struct d_dense_qcqp_dim *qp_dim); -// -void d_dense_qcqp_print(struct d_dense_qcqp_dim *qp_dim, struct d_dense_qcqp *qp); -// -//void d_dense_qcqp_codegen(char *file_name, char *mode, struct d_dense_qcqp_dim *qp_dim, struct d_dense_qcqp *qp); -// -void d_dense_qcqp_sol_print(struct d_dense_qcqp_dim *qp_dim, struct d_dense_qcqp_sol *dense_qcqp_sol); -// -//void d_dense_qcqp_ipm_arg_codegen(char *file_name, char *mode, struct d_dense_qcqp_dim *qp_dim, struct d_dense_qcqp_ipm_arg *arg); -// -void d_dense_qcqp_res_print(struct d_dense_qcqp_dim *qp_dim, struct d_dense_qcqp_res *dense_qcqp_res); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_D_DENSE_QCQP_UTILS_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_dense_qp.h b/third_party/acados/include/hpipm/include/hpipm_d_dense_qp.h deleted file mode 100644 index 02fba5a922..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_dense_qp.h +++ /dev/null @@ -1,207 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_D_DENSE_QP_H_ -#define HPIPM_D_DENSE_QP_H_ - - - -#include -#include - -#include "hpipm_d_dense_qp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_dense_qp - { - struct d_dense_qp_dim *dim; - struct blasfeo_dmat *Hv; // hessian of cost & vector work space - struct blasfeo_dmat *A; // equality constraint matrix - struct blasfeo_dmat *Ct; // inequality constraints matrix - struct blasfeo_dvec *gz; // gradient of cost & gradient of slacks - struct blasfeo_dvec *b; // equality constraint vector - struct blasfeo_dvec *d; // inequality constraints vector - struct blasfeo_dvec *d_mask; // inequality constraints mask vector - struct blasfeo_dvec *m; // rhs of complementarity condition - struct blasfeo_dvec *Z; // (diagonal) hessian of slacks - int *idxb; // indices of box constrained variables within [u; x] - int *idxs_rev; // index of soft constraints (reverse storage) - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -hpipm_size_t d_dense_qp_memsize(struct d_dense_qp_dim *dim); -// -void d_dense_qp_create(struct d_dense_qp_dim *dim, struct d_dense_qp *qp, void *memory); - -// setters - colmaj -// -void d_dense_qp_set_all(double *H, double *g, double *A, double *b, int *idxb, double *d_lb, double *d_ub, double *C, double *d_lg, double *d_ug, double *Zl, double *Zu, double *zl, double *zu, int *idxs, double *d_ls, double *d_us, struct d_dense_qp *qp); -// -void d_dense_qp_get_all(struct d_dense_qp *qp, double *H, double *g, double *A, double *b, int *idxb, double *d_lb, double *d_ub, double *C, double *d_lg, double *d_ug, double *Zl, double *Zu, double *zl, double *zu, int *idxs, double *d_ls, double *d_us); -// -void d_dense_qp_set(char *field, void *value, struct d_dense_qp *qp); -// -void d_dense_qp_set_H(double *H, struct d_dense_qp *qp); -// -void d_dense_qp_set_g(double *g, struct d_dense_qp *qp); -// -void d_dense_qp_set_A(double *A, struct d_dense_qp *qp); -// -void d_dense_qp_set_b(double *b, struct d_dense_qp *qp); -// -void d_dense_qp_set_idxb(int *idxb, struct d_dense_qp *qp); -// -void d_dense_qp_set_Jb(double *Jb, struct d_dense_qp *qp); -// -void d_dense_qp_set_lb(double *lb, struct d_dense_qp *qp); -// -void d_dense_qp_set_lb_mask(double *lb, struct d_dense_qp *qp); -// -void d_dense_qp_set_ub(double *ub, struct d_dense_qp *qp); -// -void d_dense_qp_set_ub_mask(double *ub, struct d_dense_qp *qp); -// -void d_dense_qp_set_C(double *C, struct d_dense_qp *qp); -// -void d_dense_qp_set_lg(double *lg, struct d_dense_qp *qp); -// -void d_dense_qp_set_lg_mask(double *lg, struct d_dense_qp *qp); -// -void d_dense_qp_set_ug(double *ug, struct d_dense_qp *qp); -// -void d_dense_qp_set_ug_mask(double *ug, struct d_dense_qp *qp); -// -void d_dense_qp_set_idxs(int *idxs, struct d_dense_qp *qp); -// -void d_dense_qp_set_idxs_rev(int *idxs_rev, struct d_dense_qp *qp); -// -void d_dense_qp_set_Jsb(double *Jsb, struct d_dense_qp *qp); -// -void d_dense_qp_set_Jsg(double *Jsg, struct d_dense_qp *qp); -// -void d_dense_qp_set_Zl(double *Zl, struct d_dense_qp *qp); -// -void d_dense_qp_set_Zu(double *Zu, struct d_dense_qp *qp); -// -void d_dense_qp_set_zl(double *zl, struct d_dense_qp *qp); -// -void d_dense_qp_set_zu(double *zu, struct d_dense_qp *qp); -// -void d_dense_qp_set_ls(double *ls, struct d_dense_qp *qp); -// -void d_dense_qp_set_ls_mask(double *ls, struct d_dense_qp *qp); -// -void d_dense_qp_set_us(double *us, struct d_dense_qp *qp); -// -void d_dense_qp_set_us_mask(double *us, struct d_dense_qp *qp); - -// getters - colmaj -// -void d_dense_qp_get_H(struct d_dense_qp *qp, double *H); -// -void d_dense_qp_get_g(struct d_dense_qp *qp, double *g); -// -void d_dense_qp_get_A(struct d_dense_qp *qp, double *A); -// -void d_dense_qp_get_b(struct d_dense_qp *qp, double *b); -// -void d_dense_qp_get_idxb(struct d_dense_qp *qp, int *idxb); -// -void d_dense_qp_get_lb(struct d_dense_qp *qp, double *lb); -// -void d_dense_qp_get_lb_mask(struct d_dense_qp *qp, double *lb); -// -void d_dense_qp_get_ub(struct d_dense_qp *qp, double *ub); -// -void d_dense_qp_get_ub_mask(struct d_dense_qp *qp, double *ub); -// -void d_dense_qp_get_C(struct d_dense_qp *qp, double *C); -// -void d_dense_qp_get_lg(struct d_dense_qp *qp, double *lg); -// -void d_dense_qp_get_lg_mask(struct d_dense_qp *qp, double *lg); -// -void d_dense_qp_get_ug(struct d_dense_qp *qp, double *ug); -// -void d_dense_qp_get_ug_mask(struct d_dense_qp *qp, double *ug); -// -void d_dense_qp_get_idxs(struct d_dense_qp *qp, int *idxs); -// -void d_dense_qp_get_idxs_rev(struct d_dense_qp *qp, int *idxs_rev); -// -void d_dense_qp_get_Zl(struct d_dense_qp *qp, double *Zl); -// -void d_dense_qp_get_Zu(struct d_dense_qp *qp, double *Zu); -// -void d_dense_qp_get_zl(struct d_dense_qp *qp, double *zl); -// -void d_dense_qp_get_zu(struct d_dense_qp *qp, double *zu); -// -void d_dense_qp_get_ls(struct d_dense_qp *qp, double *ls); -// -void d_dense_qp_get_ls_mask(struct d_dense_qp *qp, double *ls); -// -void d_dense_qp_get_us(struct d_dense_qp *qp, double *us); -// -void d_dense_qp_get_us_mask(struct d_dense_qp *qp, double *us); - -// setters - rowmaj -// -void d_dense_qp_set_all_rowmaj(double *H, double *g, double *A, double *b, int *idxb, double *d_lb, double *d_ub, double *C, double *d_lg, double *d_ug, double *Zl, double *Zu, double *zl, double *zu, int *idxs, double *d_ls, double *d_us, struct d_dense_qp *qp); - -// getters - rowmaj -// -void d_dense_qp_get_all_rowmaj(struct d_dense_qp *qp, double *H, double *g, double *A, double *b, int *idxb, double *d_lb, double *d_ub, double *C, double *d_lg, double *d_ug, double *Zl, double *Zu, double *zl, double *zu, int *idxs, double *d_ls, double *d_us); - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_D_DENSE_QP_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_dense_qp_dim.h b/third_party/acados/include/hpipm/include/hpipm_d_dense_qp_dim.h deleted file mode 100644 index 98a551f312..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_dense_qp_dim.h +++ /dev/null @@ -1,92 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_DENSE_QP_DIM_H_ -#define HPIPM_D_DENSE_QP_DIM_H_ - -#include "hpipm_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_dense_qp_dim - { - int nv; // number of variables - int ne; // number of equality constraints - int nb; // number of box constraints - int ng; // number of general constraints - int nsb; // number of softened box constraints - int nsg; // number of softened general constraints - int ns; // number of softened constraints (nsb+nsg) - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_dense_qp_dim_memsize(); -// -void d_dense_qp_dim_create(struct d_dense_qp_dim *qp_dim, void *memory); -// -void d_dense_qp_dim_set_all(int nv, int ne, int nb, int ng, int nsb, int nsg, struct d_dense_qp_dim *dim); -// -void d_dense_qp_dim_set(char *field_name, int value, struct d_dense_qp_dim *dim); -// -void d_dense_qp_dim_set_nv(int value, struct d_dense_qp_dim *dim); -// -void d_dense_qp_dim_set_ne(int value, struct d_dense_qp_dim *dim); -// -void d_dense_qp_dim_set_nb(int value, struct d_dense_qp_dim *dim); -// -void d_dense_qp_dim_set_ng(int value, struct d_dense_qp_dim *dim); -// -void d_dense_qp_dim_set_nsb(int value, struct d_dense_qp_dim *dim); -// -void d_dense_qp_dim_set_nsg(int value, struct d_dense_qp_dim *dim); -// -void d_dense_qp_dim_set_ns(int value, struct d_dense_qp_dim *dim); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_D_DENSE_QP_DIM_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_dense_qp_ipm.h b/third_party/acados/include/hpipm/include/hpipm_d_dense_qp_ipm.h deleted file mode 100644 index e6e5d5d9b5..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_dense_qp_ipm.h +++ /dev/null @@ -1,260 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_D_DENSE_QP_IPM_H_ -#define HPIPM_D_DENSE_QP_IPM_H_ - - - -#include -#include - -#include -#include -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_dense_qp_ipm_arg - { - double mu0; // initial value for duality measure - double alpha_min; // exit cond on step length - double res_g_max; // exit cond on inf norm of residuals - double res_b_max; // exit cond on inf norm of residuals - double res_d_max; // exit cond on inf norm of residuals - double res_m_max; // exit cond on inf norm of residuals - double reg_prim; // reg of primal hessian - double reg_dual; // reg of dual hessian - double lam_min; // min value in lam vector - double t_min; // min value in t vector - double tau_min; // min value of barrier parameter - int iter_max; // exit cond in iter number - int stat_max; // iterations saved in stat - int pred_corr; // Mehrotra's predictor-corrector IPM algirthm - int cond_pred_corr; // conditional Mehrotra's predictor-corrector - int scale; // scale hessian - int itref_pred_max; // max number of iterative refinement steps for predictor step - int itref_corr_max; // max number of iterative refinement steps for corrector step - int warm_start; // 0 no warm start, 1 warm start primal sol, 2 warm start primal and dual sol - int lq_fact; // 0 syrk+potrf, 1 mix, 2 lq - int abs_form; // absolute IPM formulation - int comp_res_exit; // compute residuals on exit (only for abs_form==1) - int comp_res_pred; // compute residuals of prediction - int kkt_fact_alg; // 0 null-space, 1 schur-complement - int remove_lin_dep_eq; // 0 do not, 1 do check and remove linearly dependent equality constraints - int compute_obj; // compute obj on exit - int split_step; // use different steps for primal and dual variables - int t_lam_min; // clip t and lam: 0 no, 1 in Gamma computation, 2 in solution - int mode; - hpipm_size_t memsize; - }; - - - -struct d_dense_qp_ipm_ws - { - struct d_core_qp_ipm_workspace *core_workspace; - struct d_dense_qp_res_ws *res_ws; - struct d_dense_qp_sol *sol_step; - struct d_dense_qp_sol *sol_itref; - struct d_dense_qp *qp_step; - struct d_dense_qp *qp_itref; - struct d_dense_qp_res *res; - struct d_dense_qp_res *res_itref; - struct d_dense_qp_res *res_step; - struct blasfeo_dvec *Gamma; // - struct blasfeo_dvec *gamma; // - struct blasfeo_dvec *Zs_inv; // - struct blasfeo_dmat *Lv; // - struct blasfeo_dmat *AL; // - struct blasfeo_dmat *Le; // - struct blasfeo_dmat *Ctx; // - struct blasfeo_dvec *lv; // - struct blasfeo_dvec *sv; // scale for Lv - struct blasfeo_dvec *se; // scale for Le - struct blasfeo_dvec *tmp_nbg; // work space of size nb+ng - struct blasfeo_dvec *tmp_ns; // work space of size ns - struct blasfeo_dmat *lq0; - struct blasfeo_dmat *lq1; - struct blasfeo_dvec *tmp_m; - struct blasfeo_dmat *A_LQ; - struct blasfeo_dmat *A_Q; - struct blasfeo_dmat *Zt; - struct blasfeo_dmat *ZtH; - struct blasfeo_dmat *ZtHZ; - struct blasfeo_dvec *xy; - struct blasfeo_dvec *Yxy; - struct blasfeo_dvec *xz; - struct blasfeo_dvec *tmp_nv; - struct blasfeo_dvec *tmp_2ns; - struct blasfeo_dvec *tmp_nv2ns; - struct blasfeo_dmat *A_li; // A of linearly independent equality constraints - struct blasfeo_dvec *b_li; // b of linearly independent equality constraints - struct blasfeo_dmat *A_bkp; // pointer to backup A - struct blasfeo_dvec *b_bkp; // pointer to backup b - struct blasfeo_dmat *Ab_LU; - double *stat; // convergence statistics - int *ipiv_v; - int *ipiv_e; - int *ipiv_e1; - void *lq_work0; - void *lq_work1; - void *lq_work_null; - void *orglq_work_null; - int iter; // iteration number - int stat_max; // iterations saved in stat - int stat_m; // numer of recorded stat per ipm iter - int scale; - int use_hess_fact; - int use_A_fact; - int status; - int lq_fact; // cache from arg - int mask_constr; // use constr mask - int ne_li; // number of linearly independent equality constraints - int ne_bkp; // ne backup - hpipm_size_t memsize; // memory size (in bytes) of workspace - }; - - - -// -hpipm_size_t d_dense_qp_ipm_arg_memsize(struct d_dense_qp_dim *dim); -// -void d_dense_qp_ipm_arg_create(struct d_dense_qp_dim *dim, struct d_dense_qp_ipm_arg *arg, void *mem); -// -void d_dense_qp_ipm_arg_set_default(enum hpipm_mode mode, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set(char *field, void *value, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_iter_max(int *iter_max, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_alpha_min(double *alpha_min, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_mu0(double *mu0, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_tol_stat(double *tol_stat, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_tol_eq(double *tol_eq, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_tol_ineq(double *tol_ineq, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_tol_comp(double *tol_comp, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_reg_prim(double *reg, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_reg_dual(double *reg, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_warm_start(int *warm_start, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_pred_corr(int *pred_corr, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_cond_pred_corr(int *cond_pred_corr, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_comp_res_pred(int *comp_res_pred, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_comp_res_exit(int *comp_res_exit, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_lam_min(double *value, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_t_min(double *value, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_tau_min(double *value, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_kkt_fact_alg(int *value, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_remove_lin_dep_eq(int *value, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_compute_obj(int *value, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_arg_set_t_lam_min(int *value, struct d_dense_qp_ipm_arg *arg); - -// -void d_dense_qp_ipm_arg_set_split_step(int *value, struct d_dense_qp_ipm_arg *arg); - -// -hpipm_size_t d_dense_qp_ipm_ws_memsize(struct d_dense_qp_dim *qp_dim, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_ipm_ws_create(struct d_dense_qp_dim *qp_dim, struct d_dense_qp_ipm_arg *arg, struct d_dense_qp_ipm_ws *ws, void *mem); -// -void d_dense_qp_ipm_get(char *field, struct d_dense_qp_ipm_ws *ws, void *value); -// -void d_dense_qp_ipm_get_status(struct d_dense_qp_ipm_ws *ws, int *status); -// -void d_dense_qp_ipm_get_iter(struct d_dense_qp_ipm_ws *ws, int *iter); -// -void d_dense_qp_ipm_get_max_res_stat(struct d_dense_qp_ipm_ws *ws, double *res_stat); -// -void d_dense_qp_ipm_get_max_res_eq(struct d_dense_qp_ipm_ws *ws, double *res_eq); -// -void d_dense_qp_ipm_get_max_res_ineq(struct d_dense_qp_ipm_ws *ws, double *res_ineq); -// -void d_dense_qp_ipm_get_max_res_comp(struct d_dense_qp_ipm_ws *ws, double *res_comp); -// -void d_dense_qp_ipm_get_stat(struct d_dense_qp_ipm_ws *ws, double **stat); -// -void d_dense_qp_ipm_get_stat_m(struct d_dense_qp_ipm_ws *ws, int *stat_m); -// -void d_dense_qp_init_var(struct d_dense_qp *qp, struct d_dense_qp_sol *qp_sol, struct d_dense_qp_ipm_arg *arg, struct d_dense_qp_ipm_ws *ws); -// -void d_dense_qp_ipm_abs_step(int kk, struct d_dense_qp *qp, struct d_dense_qp_sol *qp_sol, struct d_dense_qp_ipm_arg *arg, struct d_dense_qp_ipm_ws *ws); -// -void d_dense_qp_ipm_delta_step(int kk, struct d_dense_qp *qp, struct d_dense_qp_sol *qp_sol, struct d_dense_qp_ipm_arg *arg, struct d_dense_qp_ipm_ws *ws); -// -void d_dense_qp_ipm_solve(struct d_dense_qp *qp, struct d_dense_qp_sol *qp_sol, struct d_dense_qp_ipm_arg *arg, struct d_dense_qp_ipm_ws *ws); -// -void d_dense_qp_ipm_predict(struct d_dense_qp *qp, struct d_dense_qp_sol *qp_sol, struct d_dense_qp_ipm_arg *arg, struct d_dense_qp_ipm_ws *ws); -// -void d_dense_qp_ipm_sens(struct d_dense_qp *qp, struct d_dense_qp_sol *qp_sol, struct d_dense_qp_ipm_arg *arg, struct d_dense_qp_ipm_ws *ws); -// -void d_dense_qp_compute_step_length(struct d_dense_qp *qp, struct d_dense_qp_sol *qp_sol, struct d_dense_qp_ipm_arg *arg, struct d_dense_qp_ipm_ws *ws); - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_D_DENSE_QP_IPM_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_dense_qp_kkt.h b/third_party/acados/include/hpipm/include/hpipm_d_dense_qp_kkt.h deleted file mode 100644 index 6d05779f4b..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_dense_qp_kkt.h +++ /dev/null @@ -1,72 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_D_DENSE_QP_KKT_H_ -#define HPIPM_D_DENSE_QP_KKT_H_ - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -void d_fact_solve_kkt_unconstr_dense_qp(struct d_dense_qp *qp, struct d_dense_qp_sol *qp_sol, struct d_dense_qp_ipm_arg *arg, struct d_dense_qp_ipm_ws *ws); -// -void d_fact_solve_kkt_step_dense_qp(struct d_dense_qp *qp, struct d_dense_qp_sol *qp_sol, struct d_dense_qp_ipm_arg *arg, struct d_dense_qp_ipm_ws *ws); -// -void d_fact_lq_solve_kkt_step_dense_qp(struct d_dense_qp *qp, struct d_dense_qp_sol *qp_sol, struct d_dense_qp_ipm_arg *arg, struct d_dense_qp_ipm_ws *ws); -// -void d_solve_kkt_step_dense_qp(struct d_dense_qp *qp, struct d_dense_qp_sol *qp_sol, struct d_dense_qp_ipm_arg *arg, struct d_dense_qp_ipm_ws *ws); -// -void d_dense_qp_remove_lin_dep_eq(struct d_dense_qp *qp, struct d_dense_qp_ipm_arg *arg, struct d_dense_qp_ipm_ws *ws); -// -void d_dense_qp_restore_lin_dep_eq(struct d_dense_qp *qp, struct d_dense_qp_ipm_arg *arg, struct d_dense_qp_ipm_ws *ws); -// -void d_dense_qp_compute_obj(struct d_dense_qp *qp, struct d_dense_qp_sol *qp_sol, struct d_dense_qp_ipm_arg *arg, struct d_dense_qp_ipm_ws *ws); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_D_DENSE_QP_KKT_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_dense_qp_res.h b/third_party/acados/include/hpipm/include/hpipm_d_dense_qp_res.h deleted file mode 100644 index 7c2023257a..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_dense_qp_res.h +++ /dev/null @@ -1,105 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_DENSE_QP_RES_H_ -#define HPIPM_D_DENSE_QP_RES_H_ - - - -#include -#include - -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_dense_qp_res - { - struct d_dense_qp_dim *dim; - struct blasfeo_dvec *res_g; // q-residuals - struct blasfeo_dvec *res_b; // b-residuals - struct blasfeo_dvec *res_d; // d-residuals - struct blasfeo_dvec *res_m; // m-residuals - double res_max[4]; // max of residuals - double res_mu; // mu-residual - hpipm_size_t memsize; - }; - - - -struct d_dense_qp_res_ws - { - struct blasfeo_dvec *tmp_nbg; // work space of size nbM+ngM - struct blasfeo_dvec *tmp_ns; // work space of size nsM - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_dense_qp_res_memsize(struct d_dense_qp_dim *dim); -// -void d_dense_qp_res_create(struct d_dense_qp_dim *dim, struct d_dense_qp_res *res, void *mem); -// -hpipm_size_t d_dense_qp_res_ws_memsize(struct d_dense_qp_dim *dim); -// -void d_dense_qp_res_ws_create(struct d_dense_qp_dim *dim, struct d_dense_qp_res_ws *workspace, void *mem); -// -void d_dense_qp_res_compute(struct d_dense_qp *qp, struct d_dense_qp_sol *qp_sol, struct d_dense_qp_res *res, struct d_dense_qp_res_ws *ws); -// -void d_dense_qp_res_compute_lin(struct d_dense_qp *qp, struct d_dense_qp_sol *qp_sol, struct d_dense_qp_sol *qp_step, struct d_dense_qp_res *res, struct d_dense_qp_res_ws *ws); -// -void d_dense_qp_res_compute_inf_norm(struct d_dense_qp_res *res); -// -void d_dense_qp_res_get_all(struct d_dense_qp_res *res, double *res_g, double *res_ls, double *res_us, double *res_b, double *res_d_lb, double *res_d_ub, double *res_d_lg, double *res_d_ug, double *res_d_ls, double *res_d_us, double *res_m_lb, double *res_m_ub, double *res_m_lg, double *res_m_ug, double *res_m_ls, double *res_m_us); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - -#endif // HPIPM_D_DENSE_QP_RES_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_dense_qp_sol.h b/third_party/acados/include/hpipm/include/hpipm_d_dense_qp_sol.h deleted file mode 100644 index aaa3fdb0e4..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_dense_qp_sol.h +++ /dev/null @@ -1,94 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_D_DENSE_QP_SOL_H_ -#define HPIPM_D_DENSE_QP_SOL_H_ - - - -#include -#include - -#include "hpipm_d_dense_qp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_dense_qp_sol - { - struct d_dense_qp_dim *dim; - struct blasfeo_dvec *v; - struct blasfeo_dvec *pi; - struct blasfeo_dvec *lam; - struct blasfeo_dvec *t; - void *misc; - double obj; - int valid_obj; - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_dense_qp_sol_memsize(struct d_dense_qp_dim *dim); -// -void d_dense_qp_sol_create(struct d_dense_qp_dim *dim, struct d_dense_qp_sol *qp_sol, void *memory); -// -void d_dense_qp_sol_get_all(struct d_dense_qp_sol *qp_sol, double *v, double *ls, double *us, double *pi, double *lam_lb, double *lam_ub, double *lam_lg, double *lam_ug, double *lam_ls, double *lam_us); -// -void d_dense_qp_sol_get(char *field, struct d_dense_qp_sol *sol, void *value); -// -void d_dense_qp_sol_get_v(struct d_dense_qp_sol *sol, double *v); -// -void d_dense_qp_sol_get_valid_obj(struct d_dense_qp_sol *sol, int *valid_obj); -// -void d_dense_qp_sol_get_obj(struct d_dense_qp_sol *sol, double *obj); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_D_DENSE_QP_SOL_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_dense_qp_utils.h b/third_party/acados/include/hpipm/include/hpipm_d_dense_qp_utils.h deleted file mode 100644 index ccb77aaca3..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_dense_qp_utils.h +++ /dev/null @@ -1,83 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_DENSE_QP_UTILS_H_ -#define HPIPM_D_DENSE_QP_UTILS_H_ - - - -#include -#include - -#include "hpipm_d_dense_qp_dim.h" -#include "hpipm_d_dense_qp.h" -#include "hpipm_d_dense_qp_sol.h" -#include "hpipm_d_dense_qp_ipm.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -void d_dense_qp_dim_print(struct d_dense_qp_dim *qp_dim); -// -//void d_dense_qp_dim_codegen(char *file_name, char *mode, struct d_dense_qp_dim *qp_dim); -// -void d_dense_qp_print(struct d_dense_qp_dim *qp_dim, struct d_dense_qp *qp); -// -//void d_dense_qp_codegen(char *file_name, char *mode, struct d_dense_qp_dim *qp_dim, struct d_dense_qp *qp); -// -void d_dense_qp_sol_print(struct d_dense_qp_dim *qp_dim, struct d_dense_qp_sol *dense_qp_sol); -// -//void d_dense_qp_ipm_arg_codegen(char *file_name, char *mode, struct d_dense_qp_dim *qp_dim, struct d_dense_qp_ipm_arg *arg); -// -void d_dense_qp_res_print(struct d_dense_qp_dim *qp_dim, struct d_dense_qp_res *dense_qp_res); -// -void d_dense_qp_arg_print(struct d_dense_qp_dim *qp_dim, struct d_dense_qp_ipm_arg *qp_ipm_arg); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_D_DENSE_QP_UTILS_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qcqp.h b/third_party/acados/include/hpipm/include/hpipm_d_ocp_qcqp.h deleted file mode 100644 index 240c9b04be..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qcqp.h +++ /dev/null @@ -1,303 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_OCP_QCQP_H_ -#define HPIPM_D_OCP_QCQP_H_ - - - -#include -#include - -#include "hpipm_d_ocp_qcqp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_ocp_qcqp - { - struct d_ocp_qcqp_dim *dim; - struct blasfeo_dmat *BAbt; // dynamics matrix & vector work space - struct blasfeo_dmat *RSQrq; // hessian of cost & vector work space - struct blasfeo_dmat *DCt; // inequality constraints matrix - struct blasfeo_dmat **Hq; // hessians of quadratic constraints - struct blasfeo_dvec *b; // dynamics vector - struct blasfeo_dvec *rqz; // gradient of cost & gradient of slacks - struct blasfeo_dvec *d; // inequality constraints vector - struct blasfeo_dvec *d_mask; // inequality constraints mask vector - struct blasfeo_dvec *m; // rhs of complementarity condition - struct blasfeo_dvec *Z; // (diagonal) hessian of slacks - int **idxb; // indices of box constrained variables within [u; x] - int **idxs_rev; // index of soft constraints (reverse storage) - int **Hq_nzero; // for each int, the last 3 bits ...abc, {a,b,c}=0 => {R,S,Q}=0 - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -hpipm_size_t d_ocp_qcqp_strsize(); -// -hpipm_size_t d_ocp_qcqp_memsize(struct d_ocp_qcqp_dim *dim); -// -void d_ocp_qcqp_create(struct d_ocp_qcqp_dim *dim, struct d_ocp_qcqp *qp, void *memory); -// -void d_ocp_qcqp_copy_all(struct d_ocp_qcqp *qp_orig, struct d_ocp_qcqp *qp_dest); - -// setters -// -void d_ocp_qcqp_set_all_zero(struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_rhs_zero(struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set(char *field_name, int stage, void *value, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_el(char *field_name, int stage, int index, void *value, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_A(int stage, double *mat, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_B(int stage, double *mat, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_b(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_Q(int stage, double *mat, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_S(int stage, double *mat, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_R(int stage, double *mat, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_q(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_r(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_lb(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_lb_mask(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_ub(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_ub_mask(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_lbx(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_lbx_mask(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_el_lbx(int stage, int index, double *elem, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_ubx(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_ubx_mask(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_el_ubx(int stage, int index, double *elem, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_lbu(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_lbu_mask(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_ubu(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_ubu_mask(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_idxb(int stage, int *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_idxbx(int stage, int *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_Jbx(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_idxbu(int stage, int *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_Jbu(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_C(int stage, double *mat, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_D(int stage, double *mat, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_lg(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_lg_mask(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_ug(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_ug_mask(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_Qq(int stage, double *mat, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_Sq(int stage, double *mat, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_Rq(int stage, double *mat, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_qq(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_rq(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_uq(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_uq_mask(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_Zl(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_Zu(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_zl(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_zu(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_lls(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_lls_mask(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_lus(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_lus_mask(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_idxs(int stage, int *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_idxs_rev(int stage, int *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_Jsbu(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_Jsbx(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_Jsg(int stage, double *vec, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_set_Jsq(int stage, double *vec, struct d_ocp_qcqp *qp); - -// getters -// -void d_ocp_qcqp_get(char *field, int stage, struct d_ocp_qcqp *qp, void *value); -// -void d_ocp_qcqp_get_A(int stage, struct d_ocp_qcqp *qp, double *mat); -// -void d_ocp_qcqp_get_B(int stage, struct d_ocp_qcqp *qp, double *mat); -// -void d_ocp_qcqp_get_b(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_Q(int stage, struct d_ocp_qcqp *qp, double *mat); -// -void d_ocp_qcqp_get_S(int stage, struct d_ocp_qcqp *qp, double *mat); -// -void d_ocp_qcqp_get_R(int stage, struct d_ocp_qcqp *qp, double *mat); -// -void d_ocp_qcqp_get_q(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_r(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_ub(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_ub_mask(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_lb(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_lb_mask(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_lbx(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_lbx_mask(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_ubx(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_ubx_mask(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_lbu(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_lbu_mask(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_ubu(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_ubu_mask(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_idxb(int stage, struct d_ocp_qcqp *qp, int *vec); -// -//void d_ocp_qcqp_get_idxbx(int stage, struct d_ocp_qcqp *qp, int *vec); -// -//void d_ocp_qcqp_get_Jbx(int stage, struct d_ocp_qcqp *qp, double *vec); -// -//void d_ocp_qcqp_get_idxbu(int stage, struct d_ocp_qcqp *qp, int *vec); -// -//void d_ocp_qcqp_get_Jbu(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_C(int stage, struct d_ocp_qcqp *qp, double *mat); -// -void d_ocp_qcqp_get_D(int stage, struct d_ocp_qcqp *qp, double *mat); -// -void d_ocp_qcqp_get_lg(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_lg_mask(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_ug(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_ug_mask(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_Zl(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_Zu(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_zl(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_zu(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_lls(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_lls_mask(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_lus(int stage, struct d_ocp_qcqp *qp, double *vec); -// -void d_ocp_qcqp_get_lus_mask(int stage, struct d_ocp_qcqp *qp, double *vec); -// XXX only valid if there is one slack per softed constraint !!! -void d_ocp_qcqp_get_idxs(int stage, struct d_ocp_qcqp *qp, int *vec); -// -void d_ocp_qcqp_get_idxs_rev(int stage, struct d_ocp_qcqp *qp, int *vec); -// -//void d_ocp_qcqp_get_Jsbu(int stage, struct d_ocp_qcqp *qp, float *vec); -// -//void d_ocp_qcqp_get_Jsbx(int stage, struct d_ocp_qcqp *qp, float *vec); -// -//void d_ocp_qcqp_get_Jsg(int stage, struct d_ocp_qcqp *qp, float *vec); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_D_OCP_QCQP_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qcqp_dim.h b/third_party/acados/include/hpipm/include/hpipm_d_ocp_qcqp_dim.h deleted file mode 100644 index 268628a2b2..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qcqp_dim.h +++ /dev/null @@ -1,118 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_OCP_QCQP_DIM_H_ -#define HPIPM_D_OCP_QCQP_DIM_H_ - -#include "hpipm_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_ocp_qcqp_dim - { - struct d_ocp_qp_dim *qp_dim; // dim of qp approximation - int *nx; // number of states - int *nu; // number of inputs - int *nb; // number of box constraints - int *nbx; // number of (two-sided) state box constraints - int *nbu; // number of (two-sided) input box constraints - int *ng; // number of (two-sided) general constraints - int *nq; // number of (upper) quadratic constraints - int *ns; // number of soft constraints - int *nsbx; // number of (two-sided) soft state box constraints - int *nsbu; // number of (two-sided) soft input box constraints - int *nsg; // number of (two-sided) soft general constraints - int *nsq; // number of (upper) soft quadratic constraints - int N; // horizon length - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_ocp_qcqp_dim_strsize(); -// -hpipm_size_t d_ocp_qcqp_dim_memsize(int N); -// -void d_ocp_qcqp_dim_create(int N, struct d_ocp_qcqp_dim *qp_dim, void *memory); -// -void d_ocp_qcqp_dim_copy_all(struct d_ocp_qcqp_dim *dim_orig, struct d_ocp_qcqp_dim *dim_dest); -// -void d_ocp_qcqp_dim_set(char *field, int stage, int value, struct d_ocp_qcqp_dim *dim); -// -void d_ocp_qcqp_dim_set_nx(int stage, int value, struct d_ocp_qcqp_dim *dim); -// -void d_ocp_qcqp_dim_set_nu(int stage, int value, struct d_ocp_qcqp_dim *dim); -// -void d_ocp_qcqp_dim_set_nbx(int stage, int value, struct d_ocp_qcqp_dim *dim); -// -void d_ocp_qcqp_dim_set_nbu(int stage, int value, struct d_ocp_qcqp_dim *dim); -// -void d_ocp_qcqp_dim_set_ng(int stage, int value, struct d_ocp_qcqp_dim *dim); -// -void d_ocp_qcqp_dim_set_nq(int stage, int value, struct d_ocp_qcqp_dim *dim); -// -void d_ocp_qcqp_dim_set_ns(int stage, int value, struct d_ocp_qcqp_dim *dim); -// -void d_ocp_qcqp_dim_set_nsbx(int stage, int value, struct d_ocp_qcqp_dim *dim); -// -void d_ocp_qcqp_dim_set_nsbu(int stage, int value, struct d_ocp_qcqp_dim *dim); -// -void d_ocp_qcqp_dim_set_nsg(int stage, int value, struct d_ocp_qcqp_dim *dim); -// -void d_ocp_qcqp_dim_set_nsq(int stage, int value, struct d_ocp_qcqp_dim *dim); -// -void d_ocp_qcqp_dim_get(struct d_ocp_qcqp_dim *dim, char *field, int stage, int *value); -// -void d_ocp_qcqp_dim_get_N(struct d_ocp_qcqp_dim *dim, int *value); -// -void d_ocp_qcqp_dim_get_nx(struct d_ocp_qcqp_dim *dim, int stage, int *value); -// -void d_ocp_qcqp_dim_get_nu(struct d_ocp_qcqp_dim *dim, int stage, int *value); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_D_OCP_QCQP_DIM_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qcqp_ipm.h b/third_party/acados/include/hpipm/include/hpipm_d_ocp_qcqp_ipm.h deleted file mode 100644 index 99f2329dcc..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qcqp_ipm.h +++ /dev/null @@ -1,190 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_OCP_QCQP_IPM_H_ -#define HPIPM_D_OCP_QCQP_IPM_H_ - - - -#include -#include - -#include -#include -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_ocp_qcqp_ipm_arg - { - struct d_ocp_qp_ipm_arg *qp_arg; - double mu0; // initial value for complementarity slackness - double alpha_min; // exit cond on step length - double res_g_max; // exit cond on inf norm of residuals - double res_b_max; // exit cond on inf norm of residuals - double res_d_max; // exit cond on inf norm of residuals - double res_m_max; // exit cond on inf norm of residuals - double reg_prim; // reg of primal hessian - double lam_min; // min value in lam vector - double t_min; // min value in t vector - int iter_max; // exit cond in iter number - int stat_max; // iterations saved in stat - int pred_corr; // use Mehrotra's predictor-corrector IPM algirthm - int cond_pred_corr; // conditional Mehrotra's predictor-corrector - int itref_pred_max; // max number of iterative refinement steps for predictor step - int itref_corr_max; // max number of iterative refinement steps for corrector step - int warm_start; // 0 no warm start, 1 warm start primal sol, 2 warm start primal and dual sol - int square_root_alg; // 0 classical Riccati, 1 square-root Riccati - int lq_fact; // 0 syrk+potrf, 1 mix, 2 lq (for square_root_alg==1) - int abs_form; // absolute IPM formulation - int comp_dual_sol_eq; // dual solution of equality constrains (only for abs_form==1) - int comp_res_exit; // compute residuals on exit (only for abs_form==1 and comp_dual_sol_eq==1) - int comp_res_pred; // compute residuals of prediction - int split_step; // use different step for primal and dual variables - int t_lam_min; // clip t and lam: 0 no, 1 in Gamma computation, 2 in solution - int mode; - hpipm_size_t memsize; - }; - - - -struct d_ocp_qcqp_ipm_ws - { - struct d_ocp_qp_ipm_ws *qp_ws; - struct d_ocp_qp *qp; - struct d_ocp_qp_sol *qp_sol; - struct d_ocp_qcqp_res_ws *qcqp_res_ws; - struct d_ocp_qcqp_res *qcqp_res; - struct blasfeo_dvec *tmp_nuxM; - int iter; // iteration number - int status; - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_ocp_qcqp_ipm_arg_strsize(); -// -hpipm_size_t d_ocp_qcqp_ipm_arg_memsize(struct d_ocp_qcqp_dim *ocp_dim); -// -void d_ocp_qcqp_ipm_arg_create(struct d_ocp_qcqp_dim *ocp_dim, struct d_ocp_qcqp_ipm_arg *arg, void *mem); -// -void d_ocp_qcqp_ipm_arg_set_default(enum hpipm_mode mode, struct d_ocp_qcqp_ipm_arg *arg); -// -void d_ocp_qcqp_ipm_arg_set(char *field, void *value, struct d_ocp_qcqp_ipm_arg *arg); -// set maximum number of iterations -void d_ocp_qcqp_ipm_arg_set_iter_max(int *value, struct d_ocp_qcqp_ipm_arg *arg); -// set minimum step lenght -void d_ocp_qcqp_ipm_arg_set_alpha_min(double *value, struct d_ocp_qcqp_ipm_arg *arg); -// set initial value of barrier parameter -void d_ocp_qcqp_ipm_arg_set_mu0(double *value, struct d_ocp_qcqp_ipm_arg *arg); -// set exit tolerance on stationarity condition -void d_ocp_qcqp_ipm_arg_set_tol_stat(double *value, struct d_ocp_qcqp_ipm_arg *arg); -// set exit tolerance on equality constr -void d_ocp_qcqp_ipm_arg_set_tol_eq(double *value, struct d_ocp_qcqp_ipm_arg *arg); -// set exit tolerance on inequality constr -void d_ocp_qcqp_ipm_arg_set_tol_ineq(double *value, struct d_ocp_qcqp_ipm_arg *arg); -// set exit tolerance on complementarity condition -void d_ocp_qcqp_ipm_arg_set_tol_comp(double *value, struct d_ocp_qcqp_ipm_arg *arg); -// set regularization of primal variables -void d_ocp_qcqp_ipm_arg_set_reg_prim(double *value, struct d_ocp_qcqp_ipm_arg *arg); -// set warm start: 0 no warm start, 1 primal var -void d_ocp_qcqp_ipm_arg_set_warm_start(int *value, struct d_ocp_qcqp_ipm_arg *arg); -// Mehrotra's predictor-corrector IPM algorithm: 0 no predictor-corrector, 1 use predictor-corrector -void d_ocp_qcqp_ipm_arg_set_pred_corr(int *value, struct d_ocp_qcqp_ipm_arg *arg); -// conditional predictor-corrector: 0 no conditinal predictor-corrector, 1 conditional predictor-corrector -void d_ocp_qcqp_ipm_arg_set_cond_pred_corr(int *value, struct d_ocp_qcqp_ipm_arg *arg); -// set riccati algorithm: 0 classic, 1 square-root -void d_ocp_qcqp_ipm_arg_set_ric_alg(int *value, struct d_ocp_qcqp_ipm_arg *arg); -// compute residuals after solution -void d_ocp_qcqp_ipm_arg_set_comp_res_exit(int *value, struct d_ocp_qcqp_ipm_arg *arg); -// compute residuals of prediction -void d_ocp_qcqp_ipm_arg_set_comp_res_pred(int *value, struct d_ocp_qcqp_ipm_arg *arg); -// min value of lam in the solution -void d_ocp_qcqp_ipm_arg_set_lam_min(double *value, struct d_ocp_qcqp_ipm_arg *arg); -// min value of t in the solution -void d_ocp_qcqp_ipm_arg_set_t_min(double *value, struct d_ocp_qcqp_ipm_arg *arg); -// use different step for primal and dual variables -void d_ocp_qcqp_ipm_arg_set_split_step(int *value, struct d_ocp_qcqp_ipm_arg *arg); -// clip t and lam: 0 no, 1 in Gamma computation, 2 in solution -void d_ocp_qcqp_ipm_arg_set_t_lam_min(int *value, struct d_ocp_qcqp_ipm_arg *arg); - -// -hpipm_size_t d_ocp_qcqp_ipm_ws_strsize(); -// -hpipm_size_t d_ocp_qcqp_ipm_ws_memsize(struct d_ocp_qcqp_dim *ocp_dim, struct d_ocp_qcqp_ipm_arg *arg); -// -void d_ocp_qcqp_ipm_ws_create(struct d_ocp_qcqp_dim *ocp_dim, struct d_ocp_qcqp_ipm_arg *arg, struct d_ocp_qcqp_ipm_ws *ws, void *mem); -// -void d_ocp_qcqp_ipm_get(char *field, struct d_ocp_qcqp_ipm_ws *ws, void *value); -// -void d_ocp_qcqp_ipm_get_status(struct d_ocp_qcqp_ipm_ws *ws, int *status); -// -void d_ocp_qcqp_ipm_get_iter(struct d_ocp_qcqp_ipm_ws *ws, int *iter); -// -void d_ocp_qcqp_ipm_get_max_res_stat(struct d_ocp_qcqp_ipm_ws *ws, double *res_stat); -// -void d_ocp_qcqp_ipm_get_max_res_eq(struct d_ocp_qcqp_ipm_ws *ws, double *res_eq); -// -void d_ocp_qcqp_ipm_get_max_res_ineq(struct d_ocp_qcqp_ipm_ws *ws, double *res_ineq); -// -void d_ocp_qcqp_ipm_get_max_res_comp(struct d_ocp_qcqp_ipm_ws *ws, double *res_comp); -// -void d_ocp_qcqp_ipm_get_stat(struct d_ocp_qcqp_ipm_ws *ws, double **stat); -// -void d_ocp_qcqp_ipm_get_stat_m(struct d_ocp_qcqp_ipm_ws *ws, int *stat_m); -// -void d_ocp_qcqp_init_var(struct d_ocp_qcqp *qp, struct d_ocp_qcqp_sol *qp_sol, struct d_ocp_qcqp_ipm_arg *arg, struct d_ocp_qcqp_ipm_ws *ws); -// -void d_ocp_qcqp_ipm_solve(struct d_ocp_qcqp *qp, struct d_ocp_qcqp_sol *qp_sol, struct d_ocp_qcqp_ipm_arg *arg, struct d_ocp_qcqp_ipm_ws *ws); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - -#endif // HPIPM_D_OCP_QCQP_IPM_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qcqp_res.h b/third_party/acados/include/hpipm/include/hpipm_d_ocp_qcqp_res.h deleted file mode 100644 index 077f134677..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qcqp_res.h +++ /dev/null @@ -1,114 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_OCP_QCQP_RES_H_ -#define HPIPM_D_OCP_QCQP_RES_H_ - - - -#include -#include - -#include -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_ocp_qcqp_res - { - struct d_ocp_qcqp_dim *dim; - struct blasfeo_dvec *res_g; // q-residuals - struct blasfeo_dvec *res_b; // b-residuals - struct blasfeo_dvec *res_d; // d-residuals - struct blasfeo_dvec *res_m; // m-residuals - double res_max[4]; // max of residuals - double res_mu; // mu-residual - hpipm_size_t memsize; - }; - - - -struct d_ocp_qcqp_res_ws - { - struct blasfeo_dvec *tmp_nuxM; // work space of size nuM+nxM - struct blasfeo_dvec *tmp_nbgqM; // work space of size nbM+ngM+nqM - struct blasfeo_dvec *tmp_nsM; // work space of size nsM - struct blasfeo_dvec *q_fun; // value for evaluation of quadr constr - struct blasfeo_dvec *q_adj; // value for adjoint of quadr constr - int use_q_fun; // reuse cached value for evaluation of quadr constr - int use_q_adj; // reuse cached value for adjoint of quadr constr - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_ocp_qcqp_res_memsize(struct d_ocp_qcqp_dim *ocp_dim); -// -void d_ocp_qcqp_res_create(struct d_ocp_qcqp_dim *ocp_dim, struct d_ocp_qcqp_res *res, void *mem); -// -hpipm_size_t d_ocp_qcqp_res_ws_memsize(struct d_ocp_qcqp_dim *ocp_dim); -// -void d_ocp_qcqp_res_ws_create(struct d_ocp_qcqp_dim *ocp_dim, struct d_ocp_qcqp_res_ws *workspace, void *mem); -// -void d_ocp_qcqp_res_compute(struct d_ocp_qcqp *qp, struct d_ocp_qcqp_sol *qp_sol, struct d_ocp_qcqp_res *res, struct d_ocp_qcqp_res_ws *ws); -// -void d_ocp_qcqp_res_compute_inf_norm(struct d_ocp_qcqp_res *res); -// -void d_ocp_qcqp_res_get_max_res_stat(struct d_ocp_qcqp_res *res, double *value); -// -void d_ocp_qcqp_res_get_max_res_eq(struct d_ocp_qcqp_res *res, double *value); -// -void d_ocp_qcqp_res_get_max_res_ineq(struct d_ocp_qcqp_res *res, double *value); -// -void d_ocp_qcqp_res_get_max_res_comp(struct d_ocp_qcqp_res *res, double *value); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - -#endif // HPIPM_D_OCP_QCQP_RES_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qcqp_sol.h b/third_party/acados/include/hpipm/include/hpipm_d_ocp_qcqp_sol.h deleted file mode 100644 index 68adbfce2d..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qcqp_sol.h +++ /dev/null @@ -1,114 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_OCP_QCQP_SOL_H_ -#define HPIPM_D_OCP_QCQP_SOL_H_ - - - -#include -#include - -#include "hpipm_d_ocp_qcqp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_ocp_qcqp_sol - { - struct d_ocp_qcqp_dim *dim; - struct blasfeo_dvec *ux; - struct blasfeo_dvec *pi; - struct blasfeo_dvec *lam; - struct blasfeo_dvec *t; - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -hpipm_size_t d_ocp_qcqp_sol_strsize(); -// -hpipm_size_t d_ocp_qcqp_sol_memsize(struct d_ocp_qcqp_dim *dim); -// -void d_ocp_qcqp_sol_create(struct d_ocp_qcqp_dim *dim, struct d_ocp_qcqp_sol *qp_sol, void *memory); -// -void d_ocp_qcqp_sol_copy_all(struct d_ocp_qcqp_sol *qp_sol_orig, struct d_ocp_qcqp_sol *qp_sol_dest); -// -void d_ocp_qcqp_sol_get(char *field, int stage, struct d_ocp_qcqp_sol *qp_sol, double *vec); -// -void d_ocp_qcqp_sol_get_u(int stage, struct d_ocp_qcqp_sol *qp_sol, double *vec); -// -void d_ocp_qcqp_sol_get_x(int stage, struct d_ocp_qcqp_sol *qp_sol, double *vec); -// -void d_ocp_qcqp_sol_get_sl(int stage, struct d_ocp_qcqp_sol *qp_sol, double *vec); -// -void d_ocp_qcqp_sol_get_su(int stage, struct d_ocp_qcqp_sol *qp_sol, double *vec); -// -void d_ocp_qcqp_sol_get_pi(int stage, struct d_ocp_qcqp_sol *qp_sol, double *vec); -// -void d_ocp_qcqp_sol_get_lam_lb(int stage, struct d_ocp_qcqp_sol *qp_sol, double *vec); -// -void d_ocp_qcqp_sol_get_lam_ub(int stage, struct d_ocp_qcqp_sol *qp_sol, double *vec); -// -void d_ocp_qcqp_sol_get_lam_lg(int stage, struct d_ocp_qcqp_sol *qp_sol, double *vec); -// -void d_ocp_qcqp_sol_get_lam_ug(int stage, struct d_ocp_qcqp_sol *qp_sol, double *vec); -// -void d_ocp_qcqp_sol_set(char *field, int stage, double *vec, struct d_ocp_qcqp_sol *qp_sol); -// -void d_ocp_qcqp_sol_set_u(int stage, double *vec, struct d_ocp_qcqp_sol *qp_sol); -// -void d_ocp_qcqp_sol_set_x(int stage, double *vec, struct d_ocp_qcqp_sol *qp_sol); -// -void d_ocp_qcqp_sol_set_sl(int stage, double *vec, struct d_ocp_qcqp_sol *qp_sol); -// -void d_ocp_qcqp_sol_set_su(int stage, double *vec, struct d_ocp_qcqp_sol *qp_sol); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_D_OCP_QCQP_SOL_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qcqp_utils.h b/third_party/acados/include/hpipm/include/hpipm_d_ocp_qcqp_utils.h deleted file mode 100644 index 00248f1dbe..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qcqp_utils.h +++ /dev/null @@ -1,81 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_OCP_QCQP_UTILS_H_ -#define HPIPM_D_OCP_QCQP_UTILS_H_ - - - -#include -#include - -#include "hpipm_d_ocp_qcqp_dim.h" -#include "hpipm_d_ocp_qp.h" -#include "hpipm_d_ocp_qcqp_sol.h" -#include "hpipm_d_ocp_qcqp_ipm.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -void d_ocp_qcqp_dim_print(struct d_ocp_qcqp_dim *qcqp_dim); -// -void d_ocp_qcqp_dim_codegen(char *file_name, char *mode, struct d_ocp_qcqp_dim *qcqp_dim); -// -void d_ocp_qcqp_print(struct d_ocp_qcqp_dim *qcqp_dim, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_codegen(char *file_name, char *mode, struct d_ocp_qcqp_dim *qcqp_dim, struct d_ocp_qcqp *qp); -// -void d_ocp_qcqp_sol_print(struct d_ocp_qcqp_dim *qcqp_dim, struct d_ocp_qcqp_sol *ocp_qcqp_sol); -// -void d_ocp_qcqp_ipm_arg_codegen(char *file_name, char *mode, struct d_ocp_qcqp_dim *qcqp_dim, struct d_ocp_qcqp_ipm_arg *arg); -// -void d_ocp_qcqp_res_print(struct d_ocp_qcqp_dim *qcqp_dim, struct d_ocp_qcqp_res *ocp_qcqp_res); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_D_OCP_QCQP_UTILS_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp.h b/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp.h deleted file mode 100644 index ca26cdba34..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp.h +++ /dev/null @@ -1,306 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_OCP_QP_H_ -#define HPIPM_D_OCP_QP_H_ - - - -#include -#include - -#include "hpipm_d_ocp_qp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_ocp_qp - { - struct d_ocp_qp_dim *dim; - struct blasfeo_dmat *BAbt; // dynamics matrix & vector work space - struct blasfeo_dmat *RSQrq; // hessian of cost & vector work space - struct blasfeo_dmat *DCt; // inequality constraints matrix - struct blasfeo_dvec *b; // dynamics vector - struct blasfeo_dvec *rqz; // gradient of cost & gradient of slacks - struct blasfeo_dvec *d; // inequality constraints vector - struct blasfeo_dvec *d_mask; // inequality constraints mask vector - struct blasfeo_dvec *m; // rhs of complementarity condition - struct blasfeo_dvec *Z; // (diagonal) hessian of slacks - int **idxb; // indices of box constrained variables within [u; x] - int **idxs_rev; // index of soft constraints (reverse storage) - int **idxe; // indices of constraints within [bu, bx, g] that are equalities, subset of [0, ..., nbu+nbx+ng-1] - int *diag_H_flag; // flag the fact that Hessian is diagonal - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -hpipm_size_t d_ocp_qp_strsize(); -// -hpipm_size_t d_ocp_qp_memsize(struct d_ocp_qp_dim *dim); -// -void d_ocp_qp_create(struct d_ocp_qp_dim *dim, struct d_ocp_qp *qp, void *memory); -// -void d_ocp_qp_copy_all(struct d_ocp_qp *qp_orig, struct d_ocp_qp *qp_dest); - -// setters -// -void d_ocp_qp_set_all_zero(struct d_ocp_qp *qp); -// -void d_ocp_qp_set_rhs_zero(struct d_ocp_qp *qp); -// -void d_ocp_qp_set_all(double **A, double **B, double **b, double **Q, double **S, double **R, double **q, double **r, int **idxbx, double **lbx, double **ubx, int **idxbu, double **lbu, double **ubu, double **C, double **D, double **lg, double **ug, double **Zl, double **Zu, double **zl, double **zu, int **idxs, double **ls, double **us, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_all_rowmaj(double **A, double **B, double **b, double **Q, double **S, double **R, double **q, double **r, int **idxbx, double **lbx, double **ubx, int **idxbu, double **lbu, double **ubu, double **C, double **D, double **lg, double **ug, double **Zl, double **Zu, double **zl, double **zu, int **idxs, double **ls, double **us, struct d_ocp_qp *qp); -// -void d_ocp_qp_set(char *field_name, int stage, void *value, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_el(char *field_name, int stage, int index, void *value, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_A(int stage, double *mat, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_B(int stage, double *mat, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_b(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_Q(int stage, double *mat, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_S(int stage, double *mat, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_R(int stage, double *mat, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_q(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_r(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_lb(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_lb_mask(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_ub(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_ub_mask(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_lbx(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_lbx_mask(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_el_lbx(int stage, int index, double *elem, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_ubx(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_ubx_mask(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_el_ubx(int stage, int index, double *elem, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_lbu(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_lbu_mask(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_ubu(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_ubu_mask(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_idxb(int stage, int *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_idxbx(int stage, int *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_Jbx(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_idxbu(int stage, int *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_Jbu(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_C(int stage, double *mat, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_D(int stage, double *mat, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_lg(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_lg_mask(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_ug(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_ug_mask(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_Zl(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_Zu(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_zl(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_zu(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_lls(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_lls_mask(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_lus(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_lus_mask(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_idxs(int stage, int *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_idxs_rev(int stage, int *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_Jsbu(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_Jsbx(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_Jsg(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_idxe(int stage, int *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_idxbxe(int stage, int *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_idxbue(int stage, int *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_idxge(int stage, int *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_Jbxe(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_Jbue(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_Jge(int stage, double *vec, struct d_ocp_qp *qp); -// -void d_ocp_qp_set_diag_H_flag(int stage, int *value, struct d_ocp_qp *qp); - -// getters -// -void d_ocp_qp_get(char *field, int stage, struct d_ocp_qp *qp, void *value); -// -void d_ocp_qp_get_A(int stage, struct d_ocp_qp *qp, double *mat); -// -void d_ocp_qp_get_B(int stage, struct d_ocp_qp *qp, double *mat); -// -void d_ocp_qp_get_b(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_Q(int stage, struct d_ocp_qp *qp, double *mat); -// -void d_ocp_qp_get_S(int stage, struct d_ocp_qp *qp, double *mat); -// -void d_ocp_qp_get_R(int stage, struct d_ocp_qp *qp, double *mat); -// -void d_ocp_qp_get_q(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_r(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_ub(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_ub_mask(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_lb(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_lb_mask(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_lbx(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_lbx_mask(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_ubx(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_ubx_mask(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_lbu(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_lbu_mask(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_ubu(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_ubu_mask(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_idxb(int stage, struct d_ocp_qp *qp, int *vec); -// -//void d_ocp_qp_get_idxbx(int stage, struct d_ocp_qp *qp, int *vec); -// -//void d_ocp_qp_get_Jbx(int stage, struct d_ocp_qp *qp, double *vec); -// -//void d_ocp_qp_get_idxbu(int stage, struct d_ocp_qp *qp, int *vec); -// -//void d_ocp_qp_get_Jbu(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_C(int stage, struct d_ocp_qp *qp, double *mat); -// -void d_ocp_qp_get_D(int stage, struct d_ocp_qp *qp, double *mat); -// -void d_ocp_qp_get_lg(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_lg_mask(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_ug(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_ug_mask(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_Zl(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_Zu(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_zl(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_zu(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_lls(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_lls_mask(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_lus(int stage, struct d_ocp_qp *qp, double *vec); -// -void d_ocp_qp_get_lus_mask(int stage, struct d_ocp_qp *qp, double *vec); -// XXX only valid if there is one slack per softed constraint !!! -void d_ocp_qp_get_idxs(int stage, struct d_ocp_qp *qp, int *vec); -// -void d_ocp_qp_get_idxs_rev(int stage, struct d_ocp_qp *qp, int *vec); -// -//void d_ocp_qp_get_Jsbu(int stage, struct d_ocp_qp *qp, float *vec); -// -//void d_ocp_qp_get_Jsbx(int stage, struct d_ocp_qp *qp, float *vec); -// -//void d_ocp_qp_get_Jsg(int stage, struct d_ocp_qp *qp, float *vec); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_D_OCP_QP_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_dim.h b/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_dim.h deleted file mode 100644 index dcfb801d31..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_dim.h +++ /dev/null @@ -1,142 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_OCP_QP_DIM_H_ -#define HPIPM_D_OCP_QP_DIM_H_ - -#include "hpipm_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_ocp_qp_dim - { - int *nx; // number of states - int *nu; // number of inputs - int *nb; // number of box constraints - int *nbx; // number of state box constraints - int *nbu; // number of input box constraints - int *ng; // number of general constraints - int *ns; // number of soft constraints - int *nsbx; // number of soft state box constraints - int *nsbu; // number of soft input box constraints - int *nsg; // number of soft general constraints - int *nbxe; // number of state box constraints which are equality - int *nbue; // number of input box constraints which are equality - int *nge; // number of general constraints which are equality - int N; // horizon length - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_ocp_qp_dim_strsize(); -// -hpipm_size_t d_ocp_qp_dim_memsize(int N); -// -void d_ocp_qp_dim_create(int N, struct d_ocp_qp_dim *qp_dim, void *memory); -// -void d_ocp_qp_dim_copy_all(struct d_ocp_qp_dim *dim_orig, struct d_ocp_qp_dim *dim_dest); -// -void d_ocp_qp_dim_set_all(int *nx, int *nu, int *nbx, int *nbu, int *ng, int *nsbx, int *nsbu, int *nsg, struct d_ocp_qp_dim *dim); -// -void d_ocp_qp_dim_set(char *field, int stage, int value, struct d_ocp_qp_dim *dim); -// -void d_ocp_qp_dim_set_nx(int stage, int value, struct d_ocp_qp_dim *dim); -// -void d_ocp_qp_dim_set_nu(int stage, int value, struct d_ocp_qp_dim *dim); -// -void d_ocp_qp_dim_set_nbx(int stage, int value, struct d_ocp_qp_dim *dim); -// -void d_ocp_qp_dim_set_nbu(int stage, int value, struct d_ocp_qp_dim *dim); -// -void d_ocp_qp_dim_set_ng(int stage, int value, struct d_ocp_qp_dim *dim); -// -void d_ocp_qp_dim_set_ns(int stage, int value, struct d_ocp_qp_dim *dim); -// -void d_ocp_qp_dim_set_nsbx(int stage, int value, struct d_ocp_qp_dim *dim); -// -void d_ocp_qp_dim_set_nsbu(int stage, int value, struct d_ocp_qp_dim *dim); -// -void d_ocp_qp_dim_set_nsg(int stage, int value, struct d_ocp_qp_dim *dim); -// -void d_ocp_qp_dim_set_nbxe(int stage, int value, struct d_ocp_qp_dim *dim); -// -void d_ocp_qp_dim_set_nbue(int stage, int value, struct d_ocp_qp_dim *dim); -// -void d_ocp_qp_dim_set_nge(int stage, int value, struct d_ocp_qp_dim *dim); -// -void d_ocp_qp_dim_get(struct d_ocp_qp_dim *dim, char *field, int stage, int *value); -// -void d_ocp_qp_dim_get_N(struct d_ocp_qp_dim *dim, int *value); -// -void d_ocp_qp_dim_get_nx(struct d_ocp_qp_dim *dim, int stage, int *value); -// -void d_ocp_qp_dim_get_nu(struct d_ocp_qp_dim *dim, int stage, int *value); -// -void d_ocp_qp_dim_get_nbx(struct d_ocp_qp_dim *dim, int stage, int *value); -// -void d_ocp_qp_dim_get_nbu(struct d_ocp_qp_dim *dim, int stage, int *value); -// -void d_ocp_qp_dim_get_ng(struct d_ocp_qp_dim *dim, int stage, int *value); -// -void d_ocp_qp_dim_get_ns(struct d_ocp_qp_dim *dim, int stage, int *value); -// -void d_ocp_qp_dim_get_nsbx(struct d_ocp_qp_dim *dim, int stage, int *value); -// -void d_ocp_qp_dim_get_nsbu(struct d_ocp_qp_dim *dim, int stage, int *value); -// -void d_ocp_qp_dim_get_nsg(struct d_ocp_qp_dim *dim, int stage, int *value); -// -void d_ocp_qp_dim_get_nbxe(struct d_ocp_qp_dim *dim, int stage, int *value); -// -void d_ocp_qp_dim_get_nbue(struct d_ocp_qp_dim *dim, int stage, int *value); -// -void d_ocp_qp_dim_get_nge(struct d_ocp_qp_dim *dim, int stage, int *value); - - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_D_OCP_QP_DIM_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_ipm.h b/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_ipm.h deleted file mode 100644 index d2a2833f22..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_ipm.h +++ /dev/null @@ -1,250 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_OCP_QP_IPM_H_ -#define HPIPM_D_OCP_QP_IPM_H_ - - - -#include -#include - -#include -#include -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_ocp_qp_ipm_arg - { - double mu0; // initial value for complementarity slackness - double alpha_min; // exit cond on step length - double res_g_max; // exit cond on inf norm of residuals - double res_b_max; // exit cond on inf norm of residuals - double res_d_max; // exit cond on inf norm of residuals - double res_m_max; // exit cond on inf norm of residuals - double reg_prim; // reg of primal hessian - double lam_min; // min value in lam vector - double t_min; // min value in t vector - double tau_min; // min value of barrier parameter - int iter_max; // exit cond in iter number - int stat_max; // iterations saved in stat - int pred_corr; // use Mehrotra's predictor-corrector IPM algirthm - int cond_pred_corr; // conditional Mehrotra's predictor-corrector - int itref_pred_max; // max number of iterative refinement steps for predictor step - int itref_corr_max; // max number of iterative refinement steps for corrector step - int warm_start; // 0 no warm start, 1 warm start primal sol, 2 warm start primal and dual sol - int square_root_alg; // 0 classical Riccati, 1 square-root Riccati - int lq_fact; // 0 syrk+potrf, 1 mix, 2 lq (for square_root_alg==1) - int abs_form; // absolute IPM formulation - int comp_dual_sol_eq; // dual solution of equality constraints (only for abs_form==1) - int comp_res_exit; // compute residuals on exit (only for abs_form==1 and comp_dual_sol_eq==1) - int comp_res_pred; // compute residuals of prediction - int split_step; // use different steps for primal and dual variables - int var_init_scheme; // variables initialization scheme - int t_lam_min; // clip t and lam: 0 no, 1 in Gamma computation, 2 in solution - int mode; - hpipm_size_t memsize; - }; - - - -struct d_ocp_qp_ipm_ws - { - double qp_res[4]; // infinity norm of residuals - struct d_core_qp_ipm_workspace *core_workspace; - struct d_ocp_qp_dim *dim; // cache dim - struct d_ocp_qp_res_ws *res_workspace; - struct d_ocp_qp_sol *sol_step; - struct d_ocp_qp_sol *sol_itref; - struct d_ocp_qp *qp_step; - struct d_ocp_qp *qp_itref; - struct d_ocp_qp_res *res_itref; - struct d_ocp_qp_res *res; - struct blasfeo_dvec *Gamma; // hessian update - struct blasfeo_dvec *gamma; // hessian update - struct blasfeo_dvec *tmp_nuxM; // work space of size nxM - struct blasfeo_dvec *tmp_nbgM; // work space of size nbM+ngM - struct blasfeo_dvec *tmp_nsM; // work space of size nsM - struct blasfeo_dvec *Pb; // Pb - struct blasfeo_dvec *Zs_inv; - struct blasfeo_dvec *tmp_m; - struct blasfeo_dvec *l; // cache linear part for _get_ric_xxx - struct blasfeo_dmat *L; - struct blasfeo_dmat *Ls; - struct blasfeo_dmat *P; - struct blasfeo_dmat *Lh; - struct blasfeo_dmat *AL; - struct blasfeo_dmat *lq0; - struct blasfeo_dmat *tmp_nxM_nxM; - double *stat; // convergence statistics - int *use_hess_fact; - void *lq_work0; - int iter; // iteration number - int stat_max; // iterations saved in stat - int stat_m; // number of recorded stat per IPM iter - int use_Pb; - int status; // solver status - int square_root_alg; // cache from arg - int lq_fact; // cache from arg - int mask_constr; // use constr mask - int valid_ric_vec; // meaningful riccati vectors - int valid_ric_p; // form of riccati p: 0 p*inv(L), 1 p - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_ocp_qp_ipm_arg_strsize(); -// -hpipm_size_t d_ocp_qp_ipm_arg_memsize(struct d_ocp_qp_dim *ocp_dim); -// -void d_ocp_qp_ipm_arg_create(struct d_ocp_qp_dim *ocp_dim, struct d_ocp_qp_ipm_arg *arg, void *mem); -// -void d_ocp_qp_ipm_arg_set_default(enum hpipm_mode mode, struct d_ocp_qp_ipm_arg *arg); -// -void d_ocp_qp_ipm_arg_set(char *field, void *value, struct d_ocp_qp_ipm_arg *arg); -// set maximum number of iterations -void d_ocp_qp_ipm_arg_set_iter_max(int *iter_max, struct d_ocp_qp_ipm_arg *arg); -// set minimum step lenght -void d_ocp_qp_ipm_arg_set_alpha_min(double *alpha_min, struct d_ocp_qp_ipm_arg *arg); -// set initial value of barrier parameter -void d_ocp_qp_ipm_arg_set_mu0(double *mu0, struct d_ocp_qp_ipm_arg *arg); -// set exit tolerance on stationarity condition -void d_ocp_qp_ipm_arg_set_tol_stat(double *tol_stat, struct d_ocp_qp_ipm_arg *arg); -// set exit tolerance on equality constr -void d_ocp_qp_ipm_arg_set_tol_eq(double *tol_eq, struct d_ocp_qp_ipm_arg *arg); -// set exit tolerance on inequality constr -void d_ocp_qp_ipm_arg_set_tol_ineq(double *tol_ineq, struct d_ocp_qp_ipm_arg *arg); -// set exit tolerance on complementarity condition -void d_ocp_qp_ipm_arg_set_tol_comp(double *tol_comp, struct d_ocp_qp_ipm_arg *arg); -// set regularization of primal variables -void d_ocp_qp_ipm_arg_set_reg_prim(double *tol_comp, struct d_ocp_qp_ipm_arg *arg); -// set warm start: 0 no warm start, 1 primal var -void d_ocp_qp_ipm_arg_set_warm_start(int *warm_start, struct d_ocp_qp_ipm_arg *arg); -// Mehrotra's predictor-corrector IPM algorithm: 0 no predictor-corrector, 1 use predictor-corrector -void d_ocp_qp_ipm_arg_set_pred_corr(int *pred_corr, struct d_ocp_qp_ipm_arg *arg); -// conditional predictor-corrector: 0 no conditinal predictor-corrector, 1 conditional predictor-corrector -void d_ocp_qp_ipm_arg_set_cond_pred_corr(int *value, struct d_ocp_qp_ipm_arg *arg); -// set riccati algorithm: 0 classic, 1 square-root -void d_ocp_qp_ipm_arg_set_ric_alg(int *value, struct d_ocp_qp_ipm_arg *arg); -// dual solution of equality constraints (only for abs_form==1) -void d_ocp_qp_ipm_arg_set_comp_dual_sol_eq(int *value, struct d_ocp_qp_ipm_arg *arg); -// compute residuals after solution -void d_ocp_qp_ipm_arg_set_comp_res_exit(int *value, struct d_ocp_qp_ipm_arg *arg); -// compute residuals of prediction -void d_ocp_qp_ipm_arg_set_comp_res_pred(int *value, struct d_ocp_qp_ipm_arg *arg); -// min value of lam in the solution -void d_ocp_qp_ipm_arg_set_lam_min(double *value, struct d_ocp_qp_ipm_arg *arg); -// min value of t in the solution -void d_ocp_qp_ipm_arg_set_t_min(double *value, struct d_ocp_qp_ipm_arg *arg); -// min value of tau in the solution -void d_ocp_qp_ipm_arg_set_tau_min(double *value, struct d_ocp_qp_ipm_arg *arg); -// set split step: 0 same step, 1 different step for primal and dual variables -void d_ocp_qp_ipm_arg_set_split_step(int *value, struct d_ocp_qp_ipm_arg *arg); -// variables initialization scheme -void d_ocp_qp_ipm_arg_set_var_init_scheme(int *value, struct d_ocp_qp_ipm_arg *arg); -// clip t and lam: 0 no, 1 in Gamma computation, 2 in solution -void d_ocp_qp_ipm_arg_set_t_lam_min(int *value, struct d_ocp_qp_ipm_arg *arg); - -// -hpipm_size_t d_ocp_qp_ipm_ws_strsize(); -// -hpipm_size_t d_ocp_qp_ipm_ws_memsize(struct d_ocp_qp_dim *ocp_dim, struct d_ocp_qp_ipm_arg *arg); -// -void d_ocp_qp_ipm_ws_create(struct d_ocp_qp_dim *ocp_dim, struct d_ocp_qp_ipm_arg *arg, struct d_ocp_qp_ipm_ws *ws, void *mem); -// -void d_ocp_qp_ipm_get(char *field, struct d_ocp_qp_ipm_ws *ws, void *value); -// -void d_ocp_qp_ipm_get_status(struct d_ocp_qp_ipm_ws *ws, int *status); -// -void d_ocp_qp_ipm_get_iter(struct d_ocp_qp_ipm_ws *ws, int *iter); -// -void d_ocp_qp_ipm_get_max_res_stat(struct d_ocp_qp_ipm_ws *ws, double *res_stat); -// -void d_ocp_qp_ipm_get_max_res_eq(struct d_ocp_qp_ipm_ws *ws, double *res_eq); -// -void d_ocp_qp_ipm_get_max_res_ineq(struct d_ocp_qp_ipm_ws *ws, double *res_ineq); -// -void d_ocp_qp_ipm_get_max_res_comp(struct d_ocp_qp_ipm_ws *ws, double *res_comp); -// -void d_ocp_qp_ipm_get_stat(struct d_ocp_qp_ipm_ws *ws, double **stat); -// -void d_ocp_qp_ipm_get_stat_m(struct d_ocp_qp_ipm_ws *ws, int *stat_m); -// -void d_ocp_qp_ipm_get_ric_Lr(struct d_ocp_qp *qp, struct d_ocp_qp_ipm_arg *arg, struct d_ocp_qp_ipm_ws *ws, int stage, double *Lr); -// -void d_ocp_qp_ipm_get_ric_Ls(struct d_ocp_qp *qp, struct d_ocp_qp_ipm_arg *arg, struct d_ocp_qp_ipm_ws *ws, int stage, double *Ls); -// -void d_ocp_qp_ipm_get_ric_P(struct d_ocp_qp *qp, struct d_ocp_qp_ipm_arg *arg, struct d_ocp_qp_ipm_ws *ws, int stage, double *P); -// -void d_ocp_qp_ipm_get_ric_lr(struct d_ocp_qp *qp, struct d_ocp_qp_ipm_arg *arg, struct d_ocp_qp_ipm_ws *ws, int stage, double *lr); -// -void d_ocp_qp_ipm_get_ric_p(struct d_ocp_qp *qp, struct d_ocp_qp_ipm_arg *arg, struct d_ocp_qp_ipm_ws *ws, int stage, double *p); -// feedback control gain in the form u = K x + k -void d_ocp_qp_ipm_get_ric_K(struct d_ocp_qp *qp, struct d_ocp_qp_ipm_arg *arg, struct d_ocp_qp_ipm_ws *ws, int stage, double *K); -// feedback control gain in the form u = K x + k -void d_ocp_qp_ipm_get_ric_k(struct d_ocp_qp *qp, struct d_ocp_qp_ipm_arg *arg, struct d_ocp_qp_ipm_ws *ws, int stage, double *k); -// -void d_ocp_qp_init_var(struct d_ocp_qp *qp, struct d_ocp_qp_sol *qp_sol, struct d_ocp_qp_ipm_arg *arg, struct d_ocp_qp_ipm_ws *ws); -// -void d_ocp_qp_ipm_abs_step(int kk, struct d_ocp_qp *qp, struct d_ocp_qp_sol *qp_sol, struct d_ocp_qp_ipm_arg *arg, struct d_ocp_qp_ipm_ws *ws); -// -void d_ocp_qp_ipm_delta_step(int kk, struct d_ocp_qp *qp, struct d_ocp_qp_sol *qp_sol, struct d_ocp_qp_ipm_arg *arg, struct d_ocp_qp_ipm_ws *ws); -// -void d_ocp_qp_ipm_solve(struct d_ocp_qp *qp, struct d_ocp_qp_sol *qp_sol, struct d_ocp_qp_ipm_arg *arg, struct d_ocp_qp_ipm_ws *ws); -// -void d_ocp_qp_ipm_predict(struct d_ocp_qp *qp, struct d_ocp_qp_sol *qp_sol, struct d_ocp_qp_ipm_arg *arg, struct d_ocp_qp_ipm_ws *ws); -// -void d_ocp_qp_ipm_sens(struct d_ocp_qp *qp, struct d_ocp_qp_sol *qp_sol, struct d_ocp_qp_ipm_arg *arg, struct d_ocp_qp_ipm_ws *ws); - - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - -#endif // HPIPM_D_OCP_QP_IPM_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_kkt.h b/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_kkt.h deleted file mode 100644 index 19dcec32ca..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_kkt.h +++ /dev/null @@ -1,66 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_OCP_QP_KKT_H_ -#define HPIPM_D_OCP_QP_KKT_H_ - -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - -// -void d_ocp_qp_fact_solve_kkt_unconstr(struct d_ocp_qp *qp, struct d_ocp_qp_sol *qp_sol, struct d_ocp_qp_ipm_arg *arg, struct d_ocp_qp_ipm_ws *ws); -// -void d_ocp_qp_fact_solve_kkt_step(struct d_ocp_qp *qp, struct d_ocp_qp_sol *qp_sol, struct d_ocp_qp_ipm_arg *arg, struct d_ocp_qp_ipm_ws *ws); -// -void d_ocp_qp_fact_lq_solve_kkt_step(struct d_ocp_qp *qp, struct d_ocp_qp_sol *qp_sol, struct d_ocp_qp_ipm_arg *arg, struct d_ocp_qp_ipm_ws *ws); -// -void d_ocp_qp_solve_kkt_step(struct d_ocp_qp *qp, struct d_ocp_qp_sol *qp_sol, struct d_ocp_qp_ipm_arg *arg, struct d_ocp_qp_ipm_ws *ws); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - -#endif // HPIPM_D_OCP_QP_KKT_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_red.h b/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_red.h deleted file mode 100644 index f0482b0444..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_red.h +++ /dev/null @@ -1,117 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_OCP_QP_RED_H_ -#define HPIPM_D_OCP_QP_RED_H_ - - - -#include -#include - -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_ocp_qp_reduce_eq_dof_arg - { - double lam_min; - double t_min; - int alias_unchanged; // do not keep copy unchanged stage - int comp_prim_sol; // primal solution (v) - int comp_dual_sol_eq; // dual solution equality constr (pi) - int comp_dual_sol_ineq; // dual solution inequality constr (lam t) - hpipm_size_t memsize; // memory size in bytes - }; - - - -struct d_ocp_qp_reduce_eq_dof_ws - { - struct blasfeo_dvec *tmp_nuxM; - struct blasfeo_dvec *tmp_nbgM; - int *e_imask_ux; - int *e_imask_d; - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -void d_ocp_qp_dim_reduce_eq_dof(struct d_ocp_qp_dim *dim, struct d_ocp_qp_dim *dim_red); -// -hpipm_size_t d_ocp_qp_reduce_eq_dof_arg_memsize(); -// -void d_ocp_qp_reduce_eq_dof_arg_create(struct d_ocp_qp_reduce_eq_dof_arg *arg, void *mem); -// -void d_ocp_qp_reduce_eq_dof_arg_set_default(struct d_ocp_qp_reduce_eq_dof_arg *arg); -// -void d_ocp_qp_reduce_eq_dof_arg_set_alias_unchanged(struct d_ocp_qp_reduce_eq_dof_arg *arg, int value); -// -void d_ocp_qp_reduce_eq_dof_arg_set_comp_prim_sol(struct d_ocp_qp_reduce_eq_dof_arg *arg, int value); -// -void d_ocp_qp_reduce_eq_dof_arg_set_comp_dual_sol_eq(struct d_ocp_qp_reduce_eq_dof_arg *arg, int value); -// -void d_ocp_qp_reduce_eq_dof_arg_set_comp_dual_sol_ineq(struct d_ocp_qp_reduce_eq_dof_arg *arg, int value); -// -hpipm_size_t d_ocp_qp_reduce_eq_dof_ws_memsize(struct d_ocp_qp_dim *dim); -// -void d_ocp_qp_reduce_eq_dof_ws_create(struct d_ocp_qp_dim *dim, struct d_ocp_qp_reduce_eq_dof_ws *work, void *mem); -// -void d_ocp_qp_reduce_eq_dof(struct d_ocp_qp *qp, struct d_ocp_qp *qp_red, struct d_ocp_qp_reduce_eq_dof_arg *arg, struct d_ocp_qp_reduce_eq_dof_ws *work); -// -void d_ocp_qp_reduce_eq_dof_lhs(struct d_ocp_qp *qp, struct d_ocp_qp *qp_red, struct d_ocp_qp_reduce_eq_dof_arg *arg, struct d_ocp_qp_reduce_eq_dof_ws *work); -// -void d_ocp_qp_reduce_eq_dof_rhs(struct d_ocp_qp *qp, struct d_ocp_qp *qp_red, struct d_ocp_qp_reduce_eq_dof_arg *arg, struct d_ocp_qp_reduce_eq_dof_ws *work); -// -void d_ocp_qp_restore_eq_dof(struct d_ocp_qp *qp, struct d_ocp_qp_sol *qp_sol_red, struct d_ocp_qp_sol *qp_sol, struct d_ocp_qp_reduce_eq_dof_arg *arg, struct d_ocp_qp_reduce_eq_dof_ws *work); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_D_OCP_QP_RED_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_res.h b/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_res.h deleted file mode 100644 index 061c5729cd..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_res.h +++ /dev/null @@ -1,112 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_OCP_QP_RES_H_ -#define HPIPM_D_OCP_QP_RES_H_ - - - -#include -#include - -#include -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_ocp_qp_res - { - struct d_ocp_qp_dim *dim; - struct blasfeo_dvec *res_g; // q-residuals - struct blasfeo_dvec *res_b; // b-residuals - struct blasfeo_dvec *res_d; // d-residuals - struct blasfeo_dvec *res_m; // m-residuals - double res_max[4]; // max of residuals - double res_mu; // mu-residual - hpipm_size_t memsize; - }; - - - -struct d_ocp_qp_res_ws - { - struct blasfeo_dvec *tmp_nbgM; // work space of size nbM+ngM - struct blasfeo_dvec *tmp_nsM; // work space of size nsM - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_ocp_qp_res_memsize(struct d_ocp_qp_dim *ocp_dim); -// -void d_ocp_qp_res_create(struct d_ocp_qp_dim *ocp_dim, struct d_ocp_qp_res *res, void *mem); -// -hpipm_size_t d_ocp_qp_res_ws_memsize(struct d_ocp_qp_dim *ocp_dim); -// -void d_ocp_qp_res_ws_create(struct d_ocp_qp_dim *ocp_dim, struct d_ocp_qp_res_ws *workspace, void *mem); -// -void d_ocp_qp_res_compute(struct d_ocp_qp *qp, struct d_ocp_qp_sol *qp_sol, struct d_ocp_qp_res *res, struct d_ocp_qp_res_ws *ws); -// -void d_ocp_qp_res_compute_lin(struct d_ocp_qp *qp, struct d_ocp_qp_sol *qp_sol, struct d_ocp_qp_sol *qp_step, struct d_ocp_qp_res *res, struct d_ocp_qp_res_ws *ws); -// -void d_ocp_qp_res_compute_inf_norm(struct d_ocp_qp_res *res); -// -void d_ocp_qp_res_get_all(struct d_ocp_qp_res *res, double **res_r, double **res_q, double **res_ls, double **res_us, double **res_b, double **res_d_lb, double **res_d_ub, double **res_d_lg, double **res_d_ug, double **res_d_ls, double **res_d_us, double **res_m_lb, double **res_m_ub, double **res_m_lg, double **res_m_ug, double **res_m_ls, double **res_m_us); -// -void d_ocp_qp_res_get_max_res_stat(struct d_ocp_qp_res *res, double *value); -// -void d_ocp_qp_res_get_max_res_eq(struct d_ocp_qp_res *res, double *value); -// -void d_ocp_qp_res_get_max_res_ineq(struct d_ocp_qp_res *res, double *value); -// -void d_ocp_qp_res_get_max_res_comp(struct d_ocp_qp_res *res, double *value); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - -#endif // HPIPM_D_OCP_QP_RES_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_sol.h b/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_sol.h deleted file mode 100644 index eb91f3a7b1..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_sol.h +++ /dev/null @@ -1,128 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_OCP_QP_SOL_H_ -#define HPIPM_D_OCP_QP_SOL_H_ - - - -#include -#include - -#include "hpipm_d_ocp_qp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_ocp_qp_sol - { - struct d_ocp_qp_dim *dim; - struct blasfeo_dvec *ux; - struct blasfeo_dvec *pi; - struct blasfeo_dvec *lam; - struct blasfeo_dvec *t; - void *misc; - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -hpipm_size_t d_ocp_qp_sol_strsize(); -// -hpipm_size_t d_ocp_qp_sol_memsize(struct d_ocp_qp_dim *dim); -// -void d_ocp_qp_sol_create(struct d_ocp_qp_dim *dim, struct d_ocp_qp_sol *qp_sol, void *memory); -// -void d_ocp_qp_sol_copy_all(struct d_ocp_qp_sol *qp_sol_orig, struct d_ocp_qp_sol *qp_sol_dest); -// -void d_ocp_qp_sol_get_all(struct d_ocp_qp_sol *qp_sol, double **u, double **x, double **ls, double **us, double **pi, double **lam_lb, double **lam_ub, double **lam_lg, double **lam_ug, double **lam_ls, double **lam_us); -// -void d_ocp_qp_sol_get_all_rowmaj(struct d_ocp_qp_sol *qp_sol, double **u, double **x, double **ls, double **us, double **pi, double **lam_lb, double **lam_ub, double **lam_lg, double **lam_ug, double **lam_ls, double **lam_us); -// -void d_ocp_qp_sol_set_all(double **u, double **x, double **ls, double **us, double **pi, double **lam_lb, double **lam_ub, double **lam_lg, double **lam_ug, double **lam_ls, double **lam_us, struct d_ocp_qp_sol *qp_sol); -// -void d_ocp_qp_sol_get(char *field, int stage, struct d_ocp_qp_sol *qp_sol, double *vec); -// -void d_ocp_qp_sol_get_u(int stage, struct d_ocp_qp_sol *qp_sol, double *vec); -// -void d_ocp_qp_sol_get_x(int stage, struct d_ocp_qp_sol *qp_sol, double *vec); -// -void d_ocp_qp_sol_get_sl(int stage, struct d_ocp_qp_sol *qp_sol, double *vec); -// -void d_ocp_qp_sol_get_su(int stage, struct d_ocp_qp_sol *qp_sol, double *vec); -// -void d_ocp_qp_sol_get_pi(int stage, struct d_ocp_qp_sol *qp_sol, double *vec); -// -void d_ocp_qp_sol_get_lam_lb(int stage, struct d_ocp_qp_sol *qp_sol, double *vec); -// -void d_ocp_qp_sol_get_lam_lbu(int stage, struct d_ocp_qp_sol *qp_sol, double *vec); -// -void d_ocp_qp_sol_get_lam_lbx(int stage, struct d_ocp_qp_sol *qp_sol, double *vec); -// -void d_ocp_qp_sol_get_lam_ub(int stage, struct d_ocp_qp_sol *qp_sol, double *vec); -// -void d_ocp_qp_sol_get_lam_ubu(int stage, struct d_ocp_qp_sol *qp_sol, double *vec); -// -void d_ocp_qp_sol_get_lam_ubx(int stage, struct d_ocp_qp_sol *qp_sol, double *vec); -// -void d_ocp_qp_sol_get_lam_lg(int stage, struct d_ocp_qp_sol *qp_sol, double *vec); -// -void d_ocp_qp_sol_get_lam_ug(int stage, struct d_ocp_qp_sol *qp_sol, double *vec); -// -void d_ocp_qp_sol_set(char *field, int stage, double *vec, struct d_ocp_qp_sol *qp_sol); -// -void d_ocp_qp_sol_set_u(int stage, double *vec, struct d_ocp_qp_sol *qp_sol); -// -void d_ocp_qp_sol_set_x(int stage, double *vec, struct d_ocp_qp_sol *qp_sol); -// -void d_ocp_qp_sol_set_sl(int stage, double *vec, struct d_ocp_qp_sol *qp_sol); -// -void d_ocp_qp_sol_set_su(int stage, double *vec, struct d_ocp_qp_sol *qp_sol); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_D_OCP_QP_SOL_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_utils.h b/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_utils.h deleted file mode 100644 index 217e9d94ae..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_ocp_qp_utils.h +++ /dev/null @@ -1,82 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_OCP_QP_UTILS_H_ -#define HPIPM_D_OCP_QP_UTILS_H_ - - - -#include -#include - -#include "hpipm_d_ocp_qp_dim.h" -#include "hpipm_d_ocp_qp.h" -#include "hpipm_d_ocp_qp_sol.h" -#include "hpipm_d_ocp_qp_ipm.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -void d_ocp_qp_dim_print(struct d_ocp_qp_dim *qp_dim); -// -void d_ocp_qp_dim_codegen(char *file_name, char *mode, struct d_ocp_qp_dim *qp_dim); -// -void d_ocp_qp_print(struct d_ocp_qp_dim *qp_dim, struct d_ocp_qp *qp); -// -void d_ocp_qp_codegen(char *file_name, char *mode, struct d_ocp_qp_dim *qp_dim, struct d_ocp_qp *qp); -// -void d_ocp_qp_sol_print(struct d_ocp_qp_dim *qp_dim, struct d_ocp_qp_sol *ocp_qp_sol); -// -void d_ocp_qp_ipm_arg_print(struct d_ocp_qp_dim *qp_dim, struct d_ocp_qp_ipm_arg *arg); -// -void d_ocp_qp_ipm_arg_codegen(char *file_name, char *mode, struct d_ocp_qp_dim *qp_dim, struct d_ocp_qp_ipm_arg *arg); -// -void d_ocp_qp_res_print(struct d_ocp_qp_dim *qp_dim, struct d_ocp_qp_res *ocp_qp_res); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_D_OCP_QP_UTILS_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_part_cond.h b/third_party/acados/include/hpipm/include/hpipm_d_part_cond.h deleted file mode 100644 index 1c5f785035..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_part_cond.h +++ /dev/null @@ -1,115 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_D_PART_COND_H_ -#define HPIPM_D_PART_COND_H_ - - - -#include -#include - -#include "hpipm_common.h" -#include "hpipm_d_cond.h" - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_part_cond_qp_arg - { - struct d_cond_qp_arg *cond_arg; - int N2; - hpipm_size_t memsize; - }; - - - -struct d_part_cond_qp_ws - { - struct d_cond_qp_ws *cond_workspace; - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_part_cond_qp_arg_memsize(int N2); -// -void d_part_cond_qp_arg_create(int N2, struct d_part_cond_qp_arg *cond_arg, void *mem); -// -void d_part_cond_qp_arg_set_default(struct d_part_cond_qp_arg *cond_arg); -// set riccati-like algorithm: 0 classical, 1 squre-root -void d_part_cond_qp_arg_set_ric_alg(int ric_alg, struct d_part_cond_qp_arg *cond_arg); -// -void d_part_cond_qp_arg_set_comp_prim_sol(int value, struct d_part_cond_qp_arg *cond_arg); -// -void d_part_cond_qp_arg_set_comp_dual_sol_eq(int value, struct d_part_cond_qp_arg *cond_arg); -// -void d_part_cond_qp_arg_set_comp_dual_sol_ineq(int value, struct d_part_cond_qp_arg *cond_arg); - -// -void d_part_cond_qp_compute_block_size(int N, int N2, int *block_size); -// -void d_part_cond_qp_compute_dim(struct d_ocp_qp_dim *ocp_dim, int *block_size, struct d_ocp_qp_dim *part_dense_dim); -// -hpipm_size_t d_part_cond_qp_ws_memsize(struct d_ocp_qp_dim *ocp_dim, int *block_size, struct d_ocp_qp_dim *part_dense_dim, struct d_part_cond_qp_arg *cond_arg); -// -void d_part_cond_qp_ws_create(struct d_ocp_qp_dim *ocp_dim, int *block_size, struct d_ocp_qp_dim *part_dense_dim, struct d_part_cond_qp_arg *cond_arg, struct d_part_cond_qp_ws *cond_ws, void *mem); -// -void d_part_cond_qp_cond(struct d_ocp_qp *ocp_qp, struct d_ocp_qp *part_dense_qp, struct d_part_cond_qp_arg *cond_arg, struct d_part_cond_qp_ws *cond_ws); -// -void d_part_cond_qp_cond_lhs(struct d_ocp_qp *ocp_qp, struct d_ocp_qp *part_dense_qp, struct d_part_cond_qp_arg *cond_arg, struct d_part_cond_qp_ws *cond_ws); -// -void d_part_cond_qp_cond_rhs(struct d_ocp_qp *ocp_qp, struct d_ocp_qp *part_dense_qp, struct d_part_cond_qp_arg *cond_arg, struct d_part_cond_qp_ws *cond_ws); -// -void d_part_cond_qp_expand_sol(struct d_ocp_qp *ocp_qp, struct d_ocp_qp *part_dense_qp, struct d_ocp_qp_sol *part_dense_qp_sol, struct d_ocp_qp_sol *ocp_qp_sol, struct d_part_cond_qp_arg *cond_arg, struct d_part_cond_qp_ws *cond_ws); - -// -void d_part_cond_qp_update(int *idxc, struct d_ocp_qp *ocp_qp, struct d_ocp_qp *part_dense_qp, struct d_part_cond_qp_arg *cond_arg, struct d_part_cond_qp_ws *cond_ws); - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_D_PART_COND_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_part_cond_qcqp.h b/third_party/acados/include/hpipm/include/hpipm_d_part_cond_qcqp.h deleted file mode 100644 index 2d6624e5bb..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_part_cond_qcqp.h +++ /dev/null @@ -1,106 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_D_PART_COND_QCQP_H_ -#define HPIPM_D_PART_COND_QCQP_H_ - - - -#include -#include - -#include "hpipm_d_cond_qcqp.h" - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_part_cond_qcqp_arg - { - struct d_cond_qcqp_arg *cond_arg; - int N2; - hpipm_size_t memsize; - }; - - - -struct d_part_cond_qcqp_ws - { - struct d_cond_qcqp_ws *cond_ws; - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_part_cond_qcqp_arg_memsize(int N2); -// -void d_part_cond_qcqp_arg_create(int N2, struct d_part_cond_qcqp_arg *cond_arg, void *mem); -// -void d_part_cond_qcqp_arg_set_default(struct d_part_cond_qcqp_arg *cond_arg); -// set riccati-like algorithm: 0 classical, 1 squre-root -void d_part_cond_qcqp_arg_set_ric_alg(int ric_alg, struct d_part_cond_qcqp_arg *cond_arg); - -// -void d_part_cond_qcqp_compute_block_size(int N, int N2, int *block_size); -// -void d_part_cond_qcqp_compute_dim(struct d_ocp_qcqp_dim *ocp_dim, int *block_size, struct d_ocp_qcqp_dim *part_dense_dim); -// -hpipm_size_t d_part_cond_qcqp_ws_memsize(struct d_ocp_qcqp_dim *ocp_dim, int *block_size, struct d_ocp_qcqp_dim *part_dense_dim, struct d_part_cond_qcqp_arg *cond_arg); -// -void d_part_cond_qcqp_ws_create(struct d_ocp_qcqp_dim *ocp_dim, int *block_size, struct d_ocp_qcqp_dim *part_dense_dim, struct d_part_cond_qcqp_arg *cond_arg, struct d_part_cond_qcqp_ws *cond_ws, void *mem); -// -void d_part_cond_qcqp_cond(struct d_ocp_qcqp *ocp_qp, struct d_ocp_qcqp *part_dense_qp, struct d_part_cond_qcqp_arg *cond_arg, struct d_part_cond_qcqp_ws *cond_ws); -// -void d_part_cond_qcqp_cond_lhs(struct d_ocp_qcqp *ocp_qp, struct d_ocp_qcqp *part_dense_qp, struct d_part_cond_qcqp_arg *cond_arg, struct d_part_cond_qcqp_ws *cond_ws); -// -void d_part_cond_qcqp_cond_rhs(struct d_ocp_qcqp *ocp_qp, struct d_ocp_qcqp *part_dense_qp, struct d_part_cond_qcqp_arg *cond_arg, struct d_part_cond_qcqp_ws *cond_ws); -// -void d_part_cond_qcqp_expand_sol(struct d_ocp_qcqp *ocp_qp, struct d_ocp_qcqp *part_dense_qp, struct d_ocp_qcqp_sol *part_dense_qp_sol, struct d_ocp_qcqp_sol *ocp_qp_sol, struct d_part_cond_qcqp_arg *cond_arg, struct d_part_cond_qcqp_ws *cond_ws); - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_D_PART_COND_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_sim_erk.h b/third_party/acados/include/hpipm/include/hpipm_d_sim_erk.h deleted file mode 100644 index 320b66bb28..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_sim_erk.h +++ /dev/null @@ -1,122 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_SIM_ERK_H_ -#define HPIPM_D_SIM_ERK_H_ - -#include "hpipm_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - -struct d_sim_erk_arg - { - struct d_sim_rk_data *rk_data; // integrator data - double h; // step size - int steps; // number of steps -// int for_sens; // compute adjoint sensitivities -// int adj_sens; // compute adjoint sensitivities - hpipm_size_t memsize; - }; - - - -struct d_sim_erk_ws - { - void (*ode)(int t, double *x, double *p, void *ode_args, double *xdot); // function pointer to ode - void (*vde_for)(int t, double *x, double *p, void *ode_args, double *xdot); // function pointer to forward vde - void (*vde_adj)(int t, double *adj_in, void *ode_args, double *adj_out); // function pointer to adjoint vde - void *ode_args; // pointer to ode args - struct d_sim_erk_arg *erk_arg; // erk arg - double *K; // internal variables - double *x_for; // states and forward sensitivities - double *x_traj; // states at all steps - double *l; // adjoint sensitivities - double *p; // parameter - double *x_tmp; // temporary states and forward sensitivities - double *adj_in; - double *adj_tmp; - int nx; // number of states - int np; // number of parameters - int nf; // number of forward sensitivities - int na; // number of adjoint sensitivities - int nf_max; // max number of forward sensitivities - int na_max; // max number of adjoint sensitivities - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_sim_erk_arg_memsize(); -// -void d_sim_erk_arg_create(struct d_sim_erk_arg *erk_arg, void *mem); -// -void d_sim_erk_arg_set_all(struct d_sim_rk_data *rk_data, double h, int steps, struct d_sim_erk_arg *erk_arg); - -// -hpipm_size_t d_sim_erk_ws_memsize(struct d_sim_erk_arg *erk_arg, int nx, int np, int nf_max, int na_max); -// -void d_sim_erk_ws_create(struct d_sim_erk_arg *erk_arg, int nx, int np, int nf_max, int na_max, struct d_sim_erk_ws *work, void *memory); -// -void d_sim_erk_ws_set_all(int nf, int na, double *x, double *fs, double *bs, double *p, void (*ode)(int t, double *x, double *p, void *ode_args, double *xdot), void (*vde_for)(int t, double *x, double *p, void *ode_args, double *xdot), void (*vde_adj)(int t, double *adj_in, void *ode_args, double *adj_out), void *ode_args, struct d_sim_erk_ws *work); -// number of directions for forward sensitivities -void d_sim_erk_ws_set_nf(int *nf, struct d_sim_erk_ws *work); -// parameters (e.g. inputs) -void d_sim_erk_ws_set_p(double *p, struct d_sim_erk_ws *work); -// state -void d_sim_erk_ws_set_x(double *x, struct d_sim_erk_ws *work); -// forward sensitivities -void d_sim_erk_ws_set_fs(double *fs, struct d_sim_erk_ws *work); -// ode funtion -void d_sim_erk_ws_set_ode(void (*ode)(int t, double *x, double *p, void *ode_args, double *xdot), struct d_sim_erk_ws *work); -// forward vde function -void d_sim_erk_ws_set_vde_for(void (*ode)(int t, double *x, double *p, void *ode_args, double *xdot), struct d_sim_erk_ws *work); -// ode_args, passed straight to the ode/vde_for/vde_adj functions -void d_sim_erk_ws_set_ode_args(void *ode_args, struct d_sim_erk_ws *work); -// state -void d_sim_erk_ws_get_x(struct d_sim_erk_ws *work, double *x); -// forward sensitivities -void d_sim_erk_ws_get_fs(struct d_sim_erk_ws *work, double *fs); -// -void d_sim_erk_solve(struct d_sim_erk_arg *arg, struct d_sim_erk_ws *work); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // HPIPM_D_SIM_ERK_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_sim_rk.h b/third_party/acados/include/hpipm/include/hpipm_d_sim_rk.h deleted file mode 100644 index a50dcbb491..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_sim_rk.h +++ /dev/null @@ -1,71 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_SIM_RK_H_ -#define HPIPM_D_SIM_RK_H_ - -#include "hpipm_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - -struct d_sim_rk_data - { - double *A_rk; // A in butcher tableau - double *B_rk; // b in butcher tableau - double *C_rk; // c in butcher tableau - int expl; // erk vs irk - int ns; // number of stages - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_sim_rk_data_memsize(int ns); -// -void d_sim_rk_data_create(int ns, struct d_sim_rk_data *rk_data, void *memory); -// -void d_sim_rk_data_init_default(char *field, struct d_sim_rk_data *rk_data); -// -void d_sim_rk_data_set_all(int expl, double *A_rk, double *B_rk, double *C_rk, struct d_sim_rk_data *rk_data); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // HPIPM_D_SIM_RK_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qcqp.h b/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qcqp.h deleted file mode 100644 index f36b51a064..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qcqp.h +++ /dev/null @@ -1,213 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_TREE_OCP_QCQP_H_ -#define HPIPM_D_TREE_OCP_QCQP_H_ - - - -#include -#include - -#include "hpipm_common.h" -#include "hpipm_d_tree_ocp_qcqp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_tree_ocp_qcqp - { - struct d_tree_ocp_qcqp_dim *dim; - struct blasfeo_dmat *BAbt; // Nn-1 - struct blasfeo_dmat *RSQrq; // Nn - struct blasfeo_dmat *DCt; // Nn - struct blasfeo_dmat **Hq; // Nn - struct blasfeo_dvec *b; // Nn-1 - struct blasfeo_dvec *rqz; // Nn - struct blasfeo_dvec *d; // Nn - struct blasfeo_dvec *d_mask; // Nn - struct blasfeo_dvec *m; // Nn - struct blasfeo_dvec *Z; // Nn - int **idxb; // indices of box constrained variables within [u; x] // Nn - int **idxs_rev; // index of soft constraints - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -hpipm_size_t d_tree_ocp_qcqp_memsize(struct d_tree_ocp_qcqp_dim *dim); -// -void d_tree_ocp_qcqp_create(struct d_tree_ocp_qcqp_dim *dim, struct d_tree_ocp_qcqp *qp, void *memory); -// -void d_tree_ocp_qcqp_set_all(double **A, double **B, double **b, double **Q, double **S, double **R, double **q, double **r, int **idxb, double **d_lb, double **d_ub, double **C, double **D, double **d_lg, double **d_ug, double **Zl, double **Zu, double **zl, double **zu, int **idxs, double **d_ls, double **d_us, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set(char *field_name, int node_edge, void *value, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_A(int edge, double *mat, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_B(int edge, double *mat, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_b(int edge, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_Q(int node, double *mat, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_S(int node, double *mat, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_R(int node, double *mat, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_q(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_r(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_lb(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_lb_mask(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_ub(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_ub_mask(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_lbx(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_lbx_mask(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_ubx(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_ubx_mask(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_lbu(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_lbu_mask(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_ubu(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_ubu_mask(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_idxb(int node, int *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_idxbx(int node, int *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_Jbx(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_idxbu(int node, int *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_Jbu(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_C(int node, double *mat, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_D(int node, double *mat, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_lg(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_lg_mask(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_ug(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_ug_mask(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_Qq(int node, double *mat, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_Sq(int node, double *mat, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_Rq(int node, double *mat, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_qq(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_rq(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_uq(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_uq_mask(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_Zl(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_Zu(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_zl(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_zu(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_lls(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_lls_mask(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_lus(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_lus_mask(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_idxs(int node, int *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_idxs_rev(int node, int *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_Jsbu(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_Jsbx(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_Jsg(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_set_Jsq(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -//void d_tree_ocp_qcqp_set_idxe(int node, int *vec, struct d_tree_ocp_qcqp *qp); -// -//void d_tree_ocp_qcqp_set_idxbxe(int node, int *vec, struct d_tree_ocp_qcqp *qp); -// -//void d_tree_ocp_qcqp_set_idxbue(int node, int *vec, struct d_tree_ocp_qcqp *qp); -// -//void d_tree_ocp_qcqp_set_idxge(int node, int *vec, struct d_tree_ocp_qcqp *qp); -// -//void d_tree_ocp_qcqp_set_Jbxe(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -//void d_tree_ocp_qcqp_set_Jbue(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -//void d_tree_ocp_qcqp_set_Jge(int node, double *vec, struct d_tree_ocp_qcqp *qp); -// -//void d_tree_ocp_qcqp_set_diag_H_flag(int node, int *value, struct d_tree_ocp_qcqp *qp); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_D_TREE_OCP_QCQP_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qcqp_dim.h b/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qcqp_dim.h deleted file mode 100644 index 257b82b252..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qcqp_dim.h +++ /dev/null @@ -1,117 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_TREE_OCP_QCQP_DIM_H_ -#define HPIPM_D_TREE_OCP_QCQP_DIM_H_ - -#include "hpipm_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_tree_ocp_qcqp_dim - { - struct d_tree_ocp_qp_dim *qp_dim; // dim of qp approximation - struct tree *ttree; // tree describing node conndection - int *nx; // number of states // Nn - int *nu; // number of inputs // Nn - int *nb; // number of box constraints // Nn - int *nbx; // number of state box constraints // Nn - int *nbu; // number of input box constraints // Nn - int *ng; // number of general constraints // Nn - int *nq; // number of (upper) quadratic constraints - int *ns; // number of soft constraints // Nn - int *nsbx; // number of soft state box constraints - int *nsbu; // number of soft input box constraints - int *nsg; // number of soft general constraints - int *nsq; // number of (upper) soft quadratic constraints - int Nn; // number of nodes - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_tree_ocp_qcqp_dim_strsize(); -// -hpipm_size_t d_tree_ocp_qcqp_dim_memsize(int Nn); -// -void d_tree_ocp_qcqp_dim_create(int Nn, struct d_tree_ocp_qcqp_dim *qp_dim, void *memory); -// -void d_tree_ocp_qcqp_dim_set_tree(struct tree *ttree, struct d_tree_ocp_qcqp_dim *dim); -// -void d_tree_ocp_qcqp_dim_set(char *field, int stage, int value, struct d_tree_ocp_qcqp_dim *dim); -// -void d_tree_ocp_qcqp_dim_set_nx(int stage, int value, struct d_tree_ocp_qcqp_dim *dim); -// -void d_tree_ocp_qcqp_dim_set_nu(int stage, int value, struct d_tree_ocp_qcqp_dim *dim); -// -void d_tree_ocp_qcqp_dim_set_nbx(int stage, int value, struct d_tree_ocp_qcqp_dim *dim); -// -void d_tree_ocp_qcqp_dim_set_nbu(int stage, int value, struct d_tree_ocp_qcqp_dim *dim); -// -void d_tree_ocp_qcqp_dim_set_ng(int stage, int value, struct d_tree_ocp_qcqp_dim *dim); -// -void d_tree_ocp_qcqp_dim_set_nq(int stage, int value, struct d_tree_ocp_qcqp_dim *dim); -// -void d_tree_ocp_qcqp_dim_set_ns(int stage, int value, struct d_tree_ocp_qcqp_dim *dim); -// -void d_tree_ocp_qcqp_dim_set_nsbx(int stage, int value, struct d_tree_ocp_qcqp_dim *dim); -// -void d_tree_ocp_qcqp_dim_set_nsbu(int stage, int value, struct d_tree_ocp_qcqp_dim *dim); -// -void d_tree_ocp_qcqp_dim_set_nsg(int stage, int value, struct d_tree_ocp_qcqp_dim *dim); -// -void d_tree_ocp_qcqp_dim_set_nsq(int stage, int value, struct d_tree_ocp_qcqp_dim *dim); -// -//void d_tree_ocp_qcqp_dim_set_nbxe(int stage, int value, struct d_tree_ocp_qcqp_dim *dim); -// -//void d_tree_ocp_qcqp_dim_set_nbue(int stage, int value, struct d_tree_ocp_qcqp_dim *dim); -// -//void d_tree_ocp_qcqp_dim_set_nge(int stage, int value, struct d_tree_ocp_qcqp_dim *dim); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_D_TREE_OCP_QCQP_DIM_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qcqp_ipm.h b/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qcqp_ipm.h deleted file mode 100644 index 4a0fed1067..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qcqp_ipm.h +++ /dev/null @@ -1,191 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_TREE_OCP_QCQP_IPM_H_ -#define HPIPM_D_TREE_OCP_QCQP_IPM_H_ - - - -#include -#include - -#include -#include -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_tree_ocp_qcqp_ipm_arg - { - struct d_tree_ocp_qp_ipm_arg *qp_arg; - double mu0; // initial value for complementarity slackness - double alpha_min; // exit cond on step length - double res_g_max; // exit cond on inf norm of residuals - double res_b_max; // exit cond on inf norm of residuals - double res_d_max; // exit cond on inf norm of residuals - double res_m_max; // exit cond on inf norm of residuals - double reg_prim; // reg of primal hessian - double lam_min; // min value in lam vector - double t_min; // min value in t vector - int iter_max; // exit cond in iter number - int stat_max; // iterations saved in stat - int pred_corr; // use Mehrotra's predictor-corrector IPM algirthm - int cond_pred_corr; // conditional Mehrotra's predictor-corrector - int itref_pred_max; // max number of iterative refinement steps for predictor step - int itref_corr_max; // max number of iterative refinement steps for corrector step - int warm_start; // 0 no warm start, 1 warm start primal sol, 2 warm start primal and dual sol -// int square_root_alg; // 0 classical Riccati, 1 square-root Riccati - int lq_fact; // 0 syrk+potrf, 1 mix, 2 lq (for square_root_alg==1) - int abs_form; // absolute IPM formulation - int comp_dual_sol_eq; // dual solution of equality constrains (only for abs_form==1) - int comp_res_exit; // compute residuals on exit (only for abs_form==1 and comp_dual_sol_eq==1) -// int comp_res_pred; // compute residuals of prediction - int split_step; // use different step for primal and dual variables - int t_lam_min; // clip t and lam: 0 no, 1 in Gamma computation, 2 in solution - int mode; - hpipm_size_t memsize; - }; - - - -struct d_tree_ocp_qcqp_ipm_ws - { - struct d_tree_ocp_qp_ipm_ws *qp_ws; - struct d_tree_ocp_qp *qp; - struct d_tree_ocp_qp_sol *qp_sol; - struct d_tree_ocp_qcqp_res_ws *qcqp_res_ws; - struct d_tree_ocp_qcqp_res *qcqp_res; - struct blasfeo_dvec *tmp_nuxM; - int iter; // iteration number - int status; - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_tree_ocp_qcqp_ipm_arg_strsize(); -// -hpipm_size_t d_tree_ocp_qcqp_ipm_arg_memsize(struct d_tree_ocp_qcqp_dim *ocp_dim); -// -void d_tree_ocp_qcqp_ipm_arg_create(struct d_tree_ocp_qcqp_dim *ocp_dim, struct d_tree_ocp_qcqp_ipm_arg *arg, void *mem); -// -void d_tree_ocp_qcqp_ipm_arg_set_default(enum hpipm_mode mode, struct d_tree_ocp_qcqp_ipm_arg *arg); -// -void d_tree_ocp_qcqp_ipm_arg_set(char *field, void *value, struct d_tree_ocp_qcqp_ipm_arg *arg); -// set maximum number of iterations -void d_tree_ocp_qcqp_ipm_arg_set_iter_max(int *value, struct d_tree_ocp_qcqp_ipm_arg *arg); -// set minimum step lenght -void d_tree_ocp_qcqp_ipm_arg_set_alpha_min(double *value, struct d_tree_ocp_qcqp_ipm_arg *arg); -// set initial value of barrier parameter -void d_tree_ocp_qcqp_ipm_arg_set_mu0(double *value, struct d_tree_ocp_qcqp_ipm_arg *arg); -// set exit tolerance on stationarity condition -void d_tree_ocp_qcqp_ipm_arg_set_tol_stat(double *value, struct d_tree_ocp_qcqp_ipm_arg *arg); -// set exit tolerance on equality constr -void d_tree_ocp_qcqp_ipm_arg_set_tol_eq(double *value, struct d_tree_ocp_qcqp_ipm_arg *arg); -// set exit tolerance on inequality constr -void d_tree_ocp_qcqp_ipm_arg_set_tol_ineq(double *value, struct d_tree_ocp_qcqp_ipm_arg *arg); -// set exit tolerance on complementarity condition -void d_tree_ocp_qcqp_ipm_arg_set_tol_comp(double *value, struct d_tree_ocp_qcqp_ipm_arg *arg); -// set regularization of primal variables -void d_tree_ocp_qcqp_ipm_arg_set_reg_prim(double *value, struct d_tree_ocp_qcqp_ipm_arg *arg); -// set warm start: 0 no warm start, 1 primal var -void d_tree_ocp_qcqp_ipm_arg_set_warm_start(int *value, struct d_tree_ocp_qcqp_ipm_arg *arg); -// Mehrotra's predictor-corrector IPM algorithm: 0 no predictor-corrector, 1 use predictor-corrector -void d_tree_ocp_qcqp_ipm_arg_set_pred_corr(int *value, struct d_tree_ocp_qcqp_ipm_arg *arg); -// conditional predictor-corrector: 0 no conditinal predictor-corrector, 1 conditional predictor-corrector -void d_tree_ocp_qcqp_ipm_arg_set_cond_pred_corr(int *value, struct d_tree_ocp_qcqp_ipm_arg *arg); -// set riccati algorithm: 0 classic, 1 square-root -//void d_tree_ocp_qcqp_ipm_arg_set_ric_alg(int *value, struct d_tree_ocp_qcqp_ipm_arg *arg); -// compute residuals after solution -void d_tree_ocp_qcqp_ipm_arg_set_comp_res_exit(int *value, struct d_tree_ocp_qcqp_ipm_arg *arg); -// compute residuals of prediction -//void d_tree_ocp_qcqp_ipm_arg_set_comp_res_pred(int *value, struct d_tree_ocp_qcqp_ipm_arg *arg); -// min value of lam in the solution -void d_tree_ocp_qcqp_ipm_arg_set_lam_min(double *value, struct d_tree_ocp_qcqp_ipm_arg *arg); -// min value of t in the solution -void d_tree_ocp_qcqp_ipm_arg_set_t_min(double *value, struct d_tree_ocp_qcqp_ipm_arg *arg); -// use different step for primal and dual variables -void d_tree_ocp_qcqp_ipm_arg_set_split_step(int *value, struct d_tree_ocp_qcqp_ipm_arg *arg); -// clip t and lam: 0 no, 1 in Gamma computation, 2 in solution -void d_tree_ocp_qcqp_ipm_arg_set_t_lam_min(int *value, struct d_tree_ocp_qcqp_ipm_arg *arg); - -// -hpipm_size_t d_tree_ocp_qcqp_ipm_ws_strsize(); -// -hpipm_size_t d_tree_ocp_qcqp_ipm_ws_memsize(struct d_tree_ocp_qcqp_dim *ocp_dim, struct d_tree_ocp_qcqp_ipm_arg *arg); -// -void d_tree_ocp_qcqp_ipm_ws_create(struct d_tree_ocp_qcqp_dim *ocp_dim, struct d_tree_ocp_qcqp_ipm_arg *arg, struct d_tree_ocp_qcqp_ipm_ws *ws, void *mem); -// -void d_tree_ocp_qcqp_ipm_get(char *field, struct d_tree_ocp_qcqp_ipm_ws *ws, void *value); -// -void d_tree_ocp_qcqp_ipm_get_status(struct d_tree_ocp_qcqp_ipm_ws *ws, int *status); -// -void d_tree_ocp_qcqp_ipm_get_iter(struct d_tree_ocp_qcqp_ipm_ws *ws, int *iter); -// -void d_tree_ocp_qcqp_ipm_get_max_res_stat(struct d_tree_ocp_qcqp_ipm_ws *ws, double *res_stat); -// -void d_tree_ocp_qcqp_ipm_get_max_res_eq(struct d_tree_ocp_qcqp_ipm_ws *ws, double *res_eq); -// -void d_tree_ocp_qcqp_ipm_get_max_res_ineq(struct d_tree_ocp_qcqp_ipm_ws *ws, double *res_ineq); -// -void d_tree_ocp_qcqp_ipm_get_max_res_comp(struct d_tree_ocp_qcqp_ipm_ws *ws, double *res_comp); -// -void d_tree_ocp_qcqp_ipm_get_stat(struct d_tree_ocp_qcqp_ipm_ws *ws, double **stat); -// -void d_tree_ocp_qcqp_ipm_get_stat_m(struct d_tree_ocp_qcqp_ipm_ws *ws, int *stat_m); -// -void d_tree_ocp_qcqp_init_var(struct d_tree_ocp_qcqp *qp, struct d_tree_ocp_qcqp_sol *qp_sol, struct d_tree_ocp_qcqp_ipm_arg *arg, struct d_tree_ocp_qcqp_ipm_ws *ws); -// -void d_tree_ocp_qcqp_ipm_solve(struct d_tree_ocp_qcqp *qp, struct d_tree_ocp_qcqp_sol *qp_sol, struct d_tree_ocp_qcqp_ipm_arg *arg, struct d_tree_ocp_qcqp_ipm_ws *ws); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - -#endif // HPIPM_D_TREE_OCP_QCQP_IPM_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qcqp_res.h b/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qcqp_res.h deleted file mode 100644 index 69eebb1ba4..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qcqp_res.h +++ /dev/null @@ -1,108 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_TREE_OCP_QCQP_RES_H_ -#define HPIPM_D_TREE_OCP_QCQP_RES_H_ - - - -#include -#include - -#include -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_tree_ocp_qcqp_res - { - struct d_tree_ocp_qcqp_dim *dim; - struct blasfeo_dvec *res_g; // q-residuals - struct blasfeo_dvec *res_b; // b-residuals - struct blasfeo_dvec *res_d; // d-residuals - struct blasfeo_dvec *res_m; // m-residuals - double res_max[4]; // max of residuals - double res_mu; // mu-residual - hpipm_size_t memsize; - }; - - - -struct d_tree_ocp_qcqp_res_ws - { - struct blasfeo_dvec *tmp_nuxM; // work space of size nuM+nxM - struct blasfeo_dvec *tmp_nbgqM; // work space of size nbM+ngM+nqM - struct blasfeo_dvec *tmp_nsM; // work space of size nsM - struct blasfeo_dvec *q_fun; // value for evaluation of quadr constr - struct blasfeo_dvec *q_adj; // value for adjoint of quadr constr - int use_q_fun; // reuse cached value for evaluation of quadr constr - int use_q_adj; // reuse cached value for adjoint of quadr constr - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_tree_ocp_qcqp_res_memsize(struct d_tree_ocp_qcqp_dim *ocp_dim); -// -void d_tree_ocp_qcqp_res_create(struct d_tree_ocp_qcqp_dim *ocp_dim, struct d_tree_ocp_qcqp_res *res, void *mem); -// -hpipm_size_t d_tree_ocp_qcqp_res_ws_memsize(struct d_tree_ocp_qcqp_dim *ocp_dim); -// -void d_tree_ocp_qcqp_res_ws_create(struct d_tree_ocp_qcqp_dim *ocp_dim, struct d_tree_ocp_qcqp_res_ws *ws, void *mem); -// -void d_tree_ocp_qcqp_res_compute(struct d_tree_ocp_qcqp *qp, struct d_tree_ocp_qcqp_sol *qp_sol, struct d_tree_ocp_qcqp_res *res, struct d_tree_ocp_qcqp_res_ws *ws); -// -void d_tree_ocp_qcqp_res_compute_inf_norm(struct d_tree_ocp_qcqp_res *res); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - -#endif // HPIPM_D_TREE_OCP_QCQP_RES_H_ - - - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qcqp_sol.h b/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qcqp_sol.h deleted file mode 100644 index cde8de5c51..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qcqp_sol.h +++ /dev/null @@ -1,99 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_TREE_OCP_QCQP_SOL_H_ -#define HPIPM_D_TREE_OCP_QCQP_SOL_H_ - - - -#include -#include - -#include "hpipm_d_tree_ocp_qcqp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - -struct d_tree_ocp_qcqp_sol - { - struct d_tree_ocp_qcqp_dim *dim; - struct blasfeo_dvec *ux; - struct blasfeo_dvec *pi; - struct blasfeo_dvec *lam; - struct blasfeo_dvec *t; - void *misc; - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -hpipm_size_t d_tree_ocp_qcqp_sol_memsize(struct d_tree_ocp_qcqp_dim *dim); -// -void d_tree_ocp_qcqp_sol_create(struct d_tree_ocp_qcqp_dim *dim, struct d_tree_ocp_qcqp_sol *qp_sol, void *memory); -// -void d_tree_ocp_qcqp_sol_get(char *field, int node_edge, struct d_tree_ocp_qcqp_sol *qp_sol, double *vec); -// -void d_tree_ocp_qcqp_sol_get_u(int node, struct d_tree_ocp_qcqp_sol *qp_sol, double *vec); -// -void d_tree_ocp_qcqp_sol_get_x(int node, struct d_tree_ocp_qcqp_sol *qp_sol, double *vec); -// -void d_tree_ocp_qcqp_sol_get_sl(int node, struct d_tree_ocp_qcqp_sol *qp_sol, double *vec); -// -void d_tree_ocp_qcqp_sol_get_su(int node, struct d_tree_ocp_qcqp_sol *qp_sol, double *vec); -// -void d_tree_ocp_qcqp_sol_get_pi(int edge, struct d_tree_ocp_qcqp_sol *qp_sol, double *vec); -// -void d_tree_ocp_qcqp_sol_get_lam_lb(int node, struct d_tree_ocp_qcqp_sol *qp_sol, double *vec); -// -void d_tree_ocp_qcqp_sol_get_lam_ub(int node, struct d_tree_ocp_qcqp_sol *qp_sol, double *vec); -// -void d_tree_ocp_qcqp_sol_get_lam_lg(int node, struct d_tree_ocp_qcqp_sol *qp_sol, double *vec); -// -void d_tree_ocp_qcqp_sol_get_lam_ug(int node, struct d_tree_ocp_qcqp_sol *qp_sol, double *vec); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_D_TREE_OCP_QCQP_SOL_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qcqp_utils.h b/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qcqp_utils.h deleted file mode 100644 index 5ef04fcf66..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qcqp_utils.h +++ /dev/null @@ -1,84 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_TREE_OCP_QP_UTILS_H_ -#define HPIPM_D_TREE_OCP_QP_UTILS_H_ - - - -#include -#include - -#include "hpipm_d_tree_ocp_qcqp_dim.h" -#include "hpipm_d_tree_ocp_qcqp.h" -#include "hpipm_d_tree_ocp_qcqp_sol.h" -#include "hpipm_d_tree_ocp_qcqp_ipm.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -void d_tree_ocp_qcqp_dim_print(struct d_tree_ocp_qcqp_dim *qp_dim); -// -//void d_tree_ocp_qcqp_dim_codegen(char *file_name, char *mode, struct d_tree_ocp_qcqp_dim *qp_dim); -// -void d_tree_ocp_qcqp_print(struct d_tree_ocp_qcqp_dim *qp_dim, struct d_tree_ocp_qcqp *qp); -// -//void d_tree_ocp_qcqp_codegen(char *file_name, char *mode, struct d_tree_ocp_qcqp_dim *qp_dim, struct d_tree_ocp_qcqp *qp); -// -void d_tree_ocp_qcqp_sol_print(struct d_tree_ocp_qcqp_dim *qp_dim, struct d_tree_ocp_qcqp_sol *ocp_qcqp_sol); -// -void d_tree_ocp_qcqp_ipm_arg_print(struct d_tree_ocp_qcqp_dim *qp_dim, struct d_tree_ocp_qcqp_ipm_arg *arg); -// -//void d_tree_ocp_qcqp_ipm_arg_codegen(char *file_name, char *mode, struct d_tree_ocp_qcqp_dim *qp_dim, struct d_tree_ocp_qcqp_ipm_arg *arg); -// -void d_tree_ocp_qcqp_res_print(struct d_tree_ocp_qcqp_dim *qp_dim, struct d_tree_ocp_qcqp_res *ocp_qcqp_res); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_D_TREE_OCP_QP_UTILS_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp.h b/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp.h deleted file mode 100644 index 1666ad7c71..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp.h +++ /dev/null @@ -1,195 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_TREE_OCP_QP_H_ -#define HPIPM_D_TREE_OCP_QP_H_ - - - -#include -#include - -#include "hpipm_d_tree_ocp_qp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_tree_ocp_qp - { - struct d_tree_ocp_qp_dim *dim; - struct blasfeo_dmat *BAbt; // Nn-1 - struct blasfeo_dmat *RSQrq; // Nn - struct blasfeo_dmat *DCt; // Nn - struct blasfeo_dvec *b; // Nn-1 - struct blasfeo_dvec *rqz; // Nn - struct blasfeo_dvec *d; // Nn - struct blasfeo_dvec *d_mask; // Nn - struct blasfeo_dvec *m; // Nn - struct blasfeo_dvec *Z; // Nn - int **idxb; // indices of box constrained variables within [u; x] // Nn -// int **idxs; // index of soft constraints - int **idxs_rev; // index of soft constraints - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -hpipm_size_t d_tree_ocp_qp_memsize(struct d_tree_ocp_qp_dim *dim); -// -void d_tree_ocp_qp_create(struct d_tree_ocp_qp_dim *dim, struct d_tree_ocp_qp *qp, void *memory); -// -void d_tree_ocp_qp_set_all(double **A, double **B, double **b, double **Q, double **S, double **R, double **q, double **r, int **idxb, double **d_lb, double **d_ub, double **C, double **D, double **d_lg, double **d_ug, double **Zl, double **Zu, double **zl, double **zu, int **idxs, double **d_ls, double **d_us, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set(char *field_name, int node_edge, void *value, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_A(int edge, double *mat, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_B(int edge, double *mat, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_b(int edge, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_Q(int node, double *mat, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_S(int node, double *mat, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_R(int node, double *mat, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_q(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_r(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_lb(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_lb_mask(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_ub(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_ub_mask(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_lbx(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_lbx_mask(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_ubx(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_ubx_mask(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_lbu(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_lbu_mask(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_ubu(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_ubu_mask(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_idxb(int node, int *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_idxbx(int node, int *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_Jbx(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_idxbu(int node, int *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_Jbu(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_C(int node, double *mat, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_D(int node, double *mat, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_lg(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_lg_mask(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_ug(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_ug_mask(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_Zl(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_Zu(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_zl(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_zu(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_lls(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_lls_mask(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_lus(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_lus_mask(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_idxs(int node, int *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_idxs_rev(int node, int *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_Jsbu(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_Jsbx(int node, double *vec, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_set_Jsg(int node, double *vec, struct d_tree_ocp_qp *qp); -// -//void d_tree_ocp_qp_set_idxe(int node, int *vec, struct d_tree_ocp_qp *qp); -// -//void d_tree_ocp_qp_set_idxbxe(int node, int *vec, struct d_tree_ocp_qp *qp); -// -//void d_tree_ocp_qp_set_idxbue(int node, int *vec, struct d_tree_ocp_qp *qp); -// -//void d_tree_ocp_qp_set_idxge(int node, int *vec, struct d_tree_ocp_qp *qp); -// -//void d_tree_ocp_qp_set_Jbxe(int node, double *vec, struct d_tree_ocp_qp *qp); -// -//void d_tree_ocp_qp_set_Jbue(int node, double *vec, struct d_tree_ocp_qp *qp); -// -//void d_tree_ocp_qp_set_Jge(int node, double *vec, struct d_tree_ocp_qp *qp); -// -//void d_tree_ocp_qp_set_diag_H_flag(int node, int *value, struct d_tree_ocp_qp *qp); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_D_TREE_OCP_QP_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp_dim.h b/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp_dim.h deleted file mode 100644 index 659b664594..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp_dim.h +++ /dev/null @@ -1,111 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_TREE_OCP_QP_DIM_H_ -#define HPIPM_D_TREE_OCP_QP_DIM_H_ - -#include "hpipm_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_tree_ocp_qp_dim - { - struct tree *ttree; // tree describing node conndection - int *nx; // number of states // Nn - int *nu; // number of inputs // Nn - int *nb; // number of box constraints // Nn - int *nbx; // number of state box constraints // Nn - int *nbu; // number of input box constraints // Nn - int *ng; // number of general constraints // Nn - int *ns; // number of soft constraints // Nn - int *nsbx; // number of soft state box constraints - int *nsbu; // number of soft input box constraints - int *nsg; // number of soft general constraints - int Nn; // number of nodes - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_tree_ocp_qp_dim_strsize(); -// -hpipm_size_t d_tree_ocp_qp_dim_memsize(int Nn); -// -void d_tree_ocp_qp_dim_create(int Nn, struct d_tree_ocp_qp_dim *qp_dim, void *memory); -// -void d_tree_ocp_qp_dim_set_all(struct tree *ttree, int *nx, int *nu, int *nbx, int *nbu, int *ng, int *nsbx, int *nsbu, int *nsg, struct d_tree_ocp_qp_dim *dim); -// -void d_tree_ocp_qp_dim_set_tree(struct tree *ttree, struct d_tree_ocp_qp_dim *dim); -// -void d_tree_ocp_qp_dim_set(char *field, int stage, int value, struct d_tree_ocp_qp_dim *dim); -// -void d_tree_ocp_qp_dim_set_nx(int stage, int value, struct d_tree_ocp_qp_dim *dim); -// -void d_tree_ocp_qp_dim_set_nu(int stage, int value, struct d_tree_ocp_qp_dim *dim); -// -void d_tree_ocp_qp_dim_set_nbx(int stage, int value, struct d_tree_ocp_qp_dim *dim); -// -void d_tree_ocp_qp_dim_set_nbu(int stage, int value, struct d_tree_ocp_qp_dim *dim); -// -void d_tree_ocp_qp_dim_set_ng(int stage, int value, struct d_tree_ocp_qp_dim *dim); -// -void d_tree_ocp_qp_dim_set_ns(int stage, int value, struct d_tree_ocp_qp_dim *dim); -// -void d_tree_ocp_qp_dim_set_nsbx(int stage, int value, struct d_tree_ocp_qp_dim *dim); -// -void d_tree_ocp_qp_dim_set_nsbu(int stage, int value, struct d_tree_ocp_qp_dim *dim); -// -void d_tree_ocp_qp_dim_set_nsg(int stage, int value, struct d_tree_ocp_qp_dim *dim); -// -void d_tree_ocp_qp_dim_set_nbxe(int stage, int value, struct d_tree_ocp_qp_dim *dim); -// -void d_tree_ocp_qp_dim_set_nbue(int stage, int value, struct d_tree_ocp_qp_dim *dim); -// -void d_tree_ocp_qp_dim_set_nge(int stage, int value, struct d_tree_ocp_qp_dim *dim); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_D_TREE_OCP_QP_DIM_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp_ipm.h b/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp_ipm.h deleted file mode 100644 index fb634208ce..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp_ipm.h +++ /dev/null @@ -1,209 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_D_TREE_OCP_QP_IPM_H_ -#define HPIPM_D_TREE_OCP_QP_IPM_H_ - - - -#include -#include - -#include -#include -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_tree_ocp_qp_ipm_arg - { - double mu0; // initial value for duality measure - double alpha_min; // exit cond on step length - double res_g_max; // exit cond on inf norm of residuals - double res_b_max; // exit cond on inf norm of residuals - double res_d_max; // exit cond on inf norm of residuals - double res_m_max; // exit cond on inf norm of residuals - double reg_prim; // reg of primal hessian - double lam_min; // min value in lam vector - double t_min; // min value in t vector - double tau_min; // min value of barrier parameter - int iter_max; // exit cond in iter number - int stat_max; // iterations saved in stat - int pred_corr; // use Mehrotra's predictor-corrector IPM algirthm - int cond_pred_corr; // conditional Mehrotra's predictor-corrector - int itref_pred_max; // max number of iterative refinement steps for predictor step - int itref_corr_max; // max number of iterative refinement steps for corrector step - int warm_start; // 0 no warm start, 1 warm start primal sol, 2 warm start primal and dual sol - int lq_fact; // 0 syrk+potrf, 1 mix, 2 lq - int abs_form; // absolute IPM formulation - int comp_dual_sol_eq; // dual solution (only for abs_form==1) - int comp_res_exit; // compute residuals on exit (only for abs_form==1 and comp_dual_sol==1) - int split_step; // use different steps for primal and dual variables - int t_lam_min; // clip t and lam: 0 no, 1 in Gamma computation, 2 in solution - int mode; - hpipm_size_t memsize; - }; - - - -struct d_tree_ocp_qp_ipm_ws - { - struct d_core_qp_ipm_workspace *core_workspace; - struct d_tree_ocp_qp_res_ws *res_workspace; - struct d_tree_ocp_qp_sol *sol_step; - struct d_tree_ocp_qp_sol *sol_itref; - struct d_tree_ocp_qp *qp_step; - struct d_tree_ocp_qp *qp_itref; - struct d_tree_ocp_qp_res *res_itref; - struct d_tree_ocp_qp_res *res; - struct blasfeo_dvec *Gamma; // hessian update - struct blasfeo_dvec *gamma; // hessian update - struct blasfeo_dvec *tmp_nxM; // work space of size nxM - struct blasfeo_dvec *tmp_nbgM; // work space of size nbgM - struct blasfeo_dvec *tmp_nsM; // work space of size nsM - struct blasfeo_dvec *Pb; // Pb - struct blasfeo_dvec *Zs_inv; - struct blasfeo_dmat *L; - struct blasfeo_dmat *Lh; - struct blasfeo_dmat *AL; - struct blasfeo_dmat *lq0; - struct blasfeo_dvec *tmp_m; - double *stat; // convergence statistics - int *use_hess_fact; - void *lq_work0; - double qp_res[4]; // infinity norm of residuals - int iter; // iteration number - int stat_max; // iterations saved in stat - int stat_m; // number of recorded stat per IPM iter - int use_Pb; - int status; // solver status - int lq_fact; // cache from arg - int mask_constr; // use constr mask - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_tree_ocp_qp_ipm_arg_memsize(struct d_tree_ocp_qp_dim *dim); -// -void d_tree_ocp_qp_ipm_arg_create(struct d_tree_ocp_qp_dim *dim, struct d_tree_ocp_qp_ipm_arg *arg, void *mem); -// -void d_tree_ocp_qp_ipm_arg_set_default(enum hpipm_mode mode, struct d_tree_ocp_qp_ipm_arg *arg); -// -void d_tree_ocp_qp_ipm_arg_set_iter_max(int *iter_max, struct d_tree_ocp_qp_ipm_arg *arg); -// -void d_tree_ocp_qp_ipm_arg_set_alpha_min(double *alpha_min, struct d_tree_ocp_qp_ipm_arg *arg); -// -void d_tree_ocp_qp_ipm_arg_set_mu0(double *mu0, struct d_tree_ocp_qp_ipm_arg *arg); -// -void d_tree_ocp_qp_ipm_arg_set_tol_stat(double *tol_stat, struct d_tree_ocp_qp_ipm_arg *arg); -// -void d_tree_ocp_qp_ipm_arg_set_tol_eq(double *tol_eq, struct d_tree_ocp_qp_ipm_arg *arg); -// -void d_tree_ocp_qp_ipm_arg_set_tol_ineq(double *tol_ineq, struct d_tree_ocp_qp_ipm_arg *arg); -// -void d_tree_ocp_qp_ipm_arg_set_tol_comp(double *tol_comp, struct d_tree_ocp_qp_ipm_arg *arg); -// -void d_tree_ocp_qp_ipm_arg_set_reg_prim(double *reg, struct d_tree_ocp_qp_ipm_arg *arg); -// -void d_tree_ocp_qp_ipm_arg_set_warm_start(int *warm_start, struct d_tree_ocp_qp_ipm_arg *arg); -// -void d_tree_ocp_qp_ipm_arg_set_pred_corr(int *pred_corr, struct d_tree_ocp_qp_ipm_arg *arg); -// -void d_tree_ocp_qp_ipm_arg_set_cond_pred_corr(int *value, struct d_tree_ocp_qp_ipm_arg *arg); -// -void d_tree_ocp_qp_ipm_arg_set_comp_dual_sol_eq(int *value, struct d_tree_ocp_qp_ipm_arg *arg); -// -void d_tree_ocp_qp_ipm_arg_set_comp_res_exit(int *value, struct d_tree_ocp_qp_ipm_arg *arg); -// -void d_tree_ocp_qp_ipm_arg_set_lam_min(double *value, struct d_tree_ocp_qp_ipm_arg *arg); -// -void d_tree_ocp_qp_ipm_arg_set_t_min(double *value, struct d_tree_ocp_qp_ipm_arg *arg); -// -void d_tree_ocp_qp_ipm_arg_set_tau_min(double *value, struct d_tree_ocp_qp_ipm_arg *arg); -// -void d_tree_ocp_qp_ipm_arg_set_split_step(int *value, struct d_tree_ocp_qp_ipm_arg *arg); -// -void d_tree_ocp_qp_ipm_arg_set_t_lam_min(int *value, struct d_tree_ocp_qp_ipm_arg *arg); - -// -hpipm_size_t d_tree_ocp_qp_ipm_ws_memsize(struct d_tree_ocp_qp_dim *dim, struct d_tree_ocp_qp_ipm_arg *arg); -// -void d_tree_ocp_qp_ipm_ws_create(struct d_tree_ocp_qp_dim *dim, struct d_tree_ocp_qp_ipm_arg *arg, struct d_tree_ocp_qp_ipm_ws *ws, void *mem); -// -void d_tree_ocp_qp_ipm_get_status(struct d_tree_ocp_qp_ipm_ws *ws, int *status); -// -void d_tree_ocp_qp_ipm_get_iter(struct d_tree_ocp_qp_ipm_ws *ws, int *iter); -// -void d_tree_ocp_qp_ipm_get_max_res_stat(struct d_tree_ocp_qp_ipm_ws *ws, double *res_stat); -// -void d_tree_ocp_qp_ipm_get_max_res_eq(struct d_tree_ocp_qp_ipm_ws *ws, double *res_eq); -// -void d_tree_ocp_qp_ipm_get_max_res_ineq(struct d_tree_ocp_qp_ipm_ws *ws, double *res_ineq); -// -void d_tree_ocp_qp_ipm_get_max_res_comp(struct d_tree_ocp_qp_ipm_ws *ws, double *res_comp); -// -void d_tree_ocp_qp_ipm_get_stat(struct d_tree_ocp_qp_ipm_ws *ws, double **stat); -// -void d_tree_ocp_qp_ipm_get_stat_m(struct d_tree_ocp_qp_ipm_ws *ws, int *stat_m); -// -void d_tree_ocp_qp_init_var(struct d_tree_ocp_qp *qp, struct d_tree_ocp_qp_sol *qp_sol, struct d_tree_ocp_qp_ipm_arg *arg, struct d_tree_ocp_qp_ipm_ws *ws); -// -void d_tree_ocp_qp_ipm_abs_step(int kk, struct d_tree_ocp_qp *qp, struct d_tree_ocp_qp_sol *qp_sol, struct d_tree_ocp_qp_ipm_arg *arg, struct d_tree_ocp_qp_ipm_ws *ws); -// -void d_tree_ocp_qp_ipm_delta_step(int kk, struct d_tree_ocp_qp *qp, struct d_tree_ocp_qp_sol *qp_sol, struct d_tree_ocp_qp_ipm_arg *arg, struct d_tree_ocp_qp_ipm_ws *ws); -// -void d_tree_ocp_qp_ipm_solve(struct d_tree_ocp_qp *qp, struct d_tree_ocp_qp_sol *qp_sol, struct d_tree_ocp_qp_ipm_arg *arg, struct d_tree_ocp_qp_ipm_ws *ws); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_D_TREE_OCP_QP_IPM_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp_kkt.h b/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp_kkt.h deleted file mode 100644 index 4afd52fe4b..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp_kkt.h +++ /dev/null @@ -1,52 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifdef __cplusplus -extern "C" { -#endif - - -// -void d_tree_ocp_qp_fact_solve_kkt_unconstr(struct d_tree_ocp_qp *qp, struct d_tree_ocp_qp_sol *qp_sol, struct d_tree_ocp_qp_ipm_arg *arg, struct d_tree_ocp_qp_ipm_ws *ws); -// -void d_tree_ocp_qp_fact_solve_kkt_step(struct d_tree_ocp_qp *qp, struct d_tree_ocp_qp_sol *qp_sol, struct d_tree_ocp_qp_ipm_arg *arg, struct d_tree_ocp_qp_ipm_ws *ws); -// -void d_tree_ocp_qp_fact_lq_solve_kkt_step(struct d_tree_ocp_qp *qp, struct d_tree_ocp_qp_sol *qp_sol, struct d_tree_ocp_qp_ipm_arg *arg, struct d_tree_ocp_qp_ipm_ws *ws); -// -void d_tree_ocp_qp_solve_kkt_step(struct d_tree_ocp_qp *qp, struct d_tree_ocp_qp_sol *qp_sol, struct d_tree_ocp_qp_ipm_arg *arg, struct d_tree_ocp_qp_ipm_ws *ws); - -#ifdef __cplusplus -} /* extern "C" */ -#endif diff --git a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp_res.h b/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp_res.h deleted file mode 100644 index fe499080ea..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp_res.h +++ /dev/null @@ -1,106 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_TREE_OCP_QP_RES_H_ -#define HPIPM_D_TREE_OCP_QP_RES_H_ - - - -#include -#include - -#include -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct d_tree_ocp_qp_res - { - struct d_tree_ocp_qp_dim *dim; - struct blasfeo_dvec *res_g; // q-residuals - struct blasfeo_dvec *res_b; // b-residuals - struct blasfeo_dvec *res_d; // d-residuals - struct blasfeo_dvec *res_m; // m-residuals - double res_max[4]; // max of residuals - double res_mu; // mu-residual - hpipm_size_t memsize; - }; - - - -struct d_tree_ocp_qp_res_ws - { - struct blasfeo_dvec *tmp_nbgM; // work space of size nbM+ngM - struct blasfeo_dvec *tmp_nsM; // work space of size nsM - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t d_tree_ocp_qp_res_memsize(struct d_tree_ocp_qp_dim *ocp_dim); -// -void d_tree_ocp_qp_res_create(struct d_tree_ocp_qp_dim *ocp_dim, struct d_tree_ocp_qp_res *res, void *mem); -// -hpipm_size_t d_tree_ocp_qp_res_ws_memsize(struct d_tree_ocp_qp_dim *ocp_dim); -// -void d_tree_ocp_qp_res_ws_create(struct d_tree_ocp_qp_dim *ocp_dim, struct d_tree_ocp_qp_res_ws *ws, void *mem); -// -void d_tree_ocp_qp_res_get_all(struct d_tree_ocp_qp_res *res, double **res_r, double **res_q, double **res_ls, double **res_us, double **res_b, double **res_d_lb, double **res_d_ub, double **res_d_lg, double **res_d_ug, double **res_d_ls, double **res_d_us, double **res_m_lb, double **res_m_ub, double **res_m_lg, double **res_m_ug, double **res_m_ls, double **res_m_us); -// -void d_tree_ocp_qp_res_compute(struct d_tree_ocp_qp *qp, struct d_tree_ocp_qp_sol *qp_sol, struct d_tree_ocp_qp_res *res, struct d_tree_ocp_qp_res_ws *ws); -// -void d_tree_ocp_qp_res_compute_lin(struct d_tree_ocp_qp *qp, struct d_tree_ocp_qp_sol *qp_sol, struct d_tree_ocp_qp_sol *qp_step, struct d_tree_ocp_qp_res *res, struct d_tree_ocp_qp_res_ws *ws); -// -void d_tree_ocp_qp_res_compute_inf_norm(struct d_tree_ocp_qp_res *res); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - -#endif // HPIPM_D_TREE_OCP_QP_RES_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp_sol.h b/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp_sol.h deleted file mode 100644 index 343d5e8ca6..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp_sol.h +++ /dev/null @@ -1,100 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_TREE_OCP_QP_SOL_H_ -#define HPIPM_D_TREE_OCP_QP_SOL_H_ - - - -#include -#include - -#include "hpipm_d_tree_ocp_qp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - -struct d_tree_ocp_qp_sol - { - struct d_tree_ocp_qp_dim *dim; - struct blasfeo_dvec *ux; - struct blasfeo_dvec *pi; - struct blasfeo_dvec *lam; - struct blasfeo_dvec *t; - void *misc; - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -hpipm_size_t d_tree_ocp_qp_sol_memsize(struct d_tree_ocp_qp_dim *dim); -// -void d_tree_ocp_qp_sol_create(struct d_tree_ocp_qp_dim *dim, struct d_tree_ocp_qp_sol *qp_sol, void *memory); -// -void d_tree_ocp_qp_sol_get_all(struct d_tree_ocp_qp *qp, struct d_tree_ocp_qp_sol *qp_sol, double **u, double **x, double **ls, double **us, double **pi, double **lam_lb, double **lam_ub, double **lam_lg, double **lam_ug, double **lam_ls, double **lam_us); -// -void d_tree_ocp_qp_sol_get(char *field, int node_edge, struct d_tree_ocp_qp_sol *qp_sol, double *vec); -// -void d_tree_ocp_qp_sol_get_u(int node, struct d_tree_ocp_qp_sol *qp_sol, double *vec); -// -void d_tree_ocp_qp_sol_get_x(int node, struct d_tree_ocp_qp_sol *qp_sol, double *vec); -// -void d_tree_ocp_qp_sol_get_sl(int node, struct d_tree_ocp_qp_sol *qp_sol, double *vec); -// -void d_tree_ocp_qp_sol_get_su(int node, struct d_tree_ocp_qp_sol *qp_sol, double *vec); -// -void d_tree_ocp_qp_sol_get_pi(int edge, struct d_tree_ocp_qp_sol *qp_sol, double *vec); -// -void d_tree_ocp_qp_sol_get_lam_lb(int node, struct d_tree_ocp_qp_sol *qp_sol, double *vec); -// -void d_tree_ocp_qp_sol_get_lam_ub(int node, struct d_tree_ocp_qp_sol *qp_sol, double *vec); -// -void d_tree_ocp_qp_sol_get_lam_lg(int node, struct d_tree_ocp_qp_sol *qp_sol, double *vec); -// -void d_tree_ocp_qp_sol_get_lam_ug(int node, struct d_tree_ocp_qp_sol *qp_sol, double *vec); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_D_TREE_OCP_QP_SOL_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp_utils.h b/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp_utils.h deleted file mode 100644 index b689fdc0fa..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_d_tree_ocp_qp_utils.h +++ /dev/null @@ -1,83 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_D_TREE_OCP_QP_UTILS_H_ -#define HPIPM_D_TREE_OCP_QP_UTILS_H_ - - - -#include -#include - -#include "hpipm_d_tree_ocp_qp_dim.h" -#include "hpipm_d_tree_ocp_qp.h" -#include "hpipm_d_tree_ocp_qp_sol.h" -#include "hpipm_d_tree_ocp_qp_ipm.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -void d_tree_ocp_qp_dim_print(struct d_tree_ocp_qp_dim *qp_dim); -// -//void d_tree_ocp_qp_dim_codegen(char *file_name, char *mode, struct d_tree_ocp_qp_dim *qp_dim); -// -void d_tree_ocp_qp_print(struct d_tree_ocp_qp_dim *qp_dim, struct d_tree_ocp_qp *qp); -// -//void d_tree_ocp_qp_codegen(char *file_name, char *mode, struct d_tree_ocp_qp_dim *qp_dim, struct d_tree_ocp_qp *qp); -// -void d_tree_ocp_qp_sol_print(struct d_tree_ocp_qp_dim *qp_dim, struct d_tree_ocp_qp_sol *ocp_qp_sol); -// -void d_tree_ocp_qp_ipm_arg_print(struct d_tree_ocp_qp_dim *qp_dim, struct d_tree_ocp_qp_ipm_arg *arg); -// -//void d_tree_ocp_qp_ipm_arg_codegen(char *file_name, char *mode, struct d_tree_ocp_qp_dim *qp_dim, struct d_tree_ocp_qp_ipm_arg *arg); -// -void d_tree_ocp_qp_res_print(struct d_tree_ocp_qp_dim *qp_dim, struct d_tree_ocp_qp_res *ocp_qp_res); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_D_TREE_OCP_QP_UTILS_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_m_dense_qp.h b/third_party/acados/include/hpipm/include/hpipm_m_dense_qp.h deleted file mode 100644 index 8bc101003e..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_m_dense_qp.h +++ /dev/null @@ -1,68 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - - -#ifndef HPIPM_M_DENSE_QP_H_ -#define HPIPM_M_DENSE_QP_H_ - - - -#include -#include - -#include "hpipm_d_dense_qp.h" -#include "hpipm_s_dense_qp.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -void cvt_d2s_dense_qp(struct d_dense_qp *qpd, struct s_dense_qp *qps); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_M_DENSE_QP_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_m_dense_qp_dim.h b/third_party/acados/include/hpipm/include/hpipm_m_dense_qp_dim.h deleted file mode 100644 index 4610321b97..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_m_dense_qp_dim.h +++ /dev/null @@ -1,68 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - - -#ifndef HPIPM_M_DENSE_QP_DIM_H_ -#define HPIPM_M_DENSE_QP_DIM_H_ - - - -#include -#include - -#include "hpipm_d_dense_qp_dim.h" -#include "hpipm_s_dense_qp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -void cvt_d2s_dense_qp_dim(struct d_dense_qp_dim *qpd, struct s_dense_qp_dim *qps); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_M_DENSE_QP_DIM_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_m_ocp_qp.h b/third_party/acados/include/hpipm/include/hpipm_m_ocp_qp.h deleted file mode 100644 index 95c3dad1aa..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_m_ocp_qp.h +++ /dev/null @@ -1,49 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -void m_cvt_d_ocp_qp_to_s_ocp_qp(struct d_ocp_qp *d_qp, struct s_ocp_qp *s_qp); - -#ifdef __cplusplus -} /* extern "C" */ -#endif diff --git a/third_party/acados/include/hpipm/include/hpipm_m_ocp_qp_ipm_hard.h b/third_party/acados/include/hpipm/include/hpipm_m_ocp_qp_ipm_hard.h deleted file mode 100644 index 1c44acee2e..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_m_ocp_qp_ipm_hard.h +++ /dev/null @@ -1,115 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - - -struct m_ipm_hard_ocp_qp_workspace - { - struct d_ipm_hard_core_qp_workspace *core_workspace; - struct blasfeo_dvec *dux; - struct blasfeo_dvec *dpi; - struct blasfeo_dvec *dt_lb; - struct blasfeo_dvec *dt_lg; - struct blasfeo_svec *sdux; // XXX - struct blasfeo_svec *sdpi; // XXX - struct blasfeo_dvec *res_g; // q-residuals - struct blasfeo_dvec *res_b; // b-residuals - struct blasfeo_dvec *res_d; // d-residuals XXX remove ??? - struct blasfeo_dvec *res_d_lb; // d-residuals - struct blasfeo_dvec *res_d_ub; // d-residuals - struct blasfeo_dvec *res_d_lg; // d-residuals - struct blasfeo_dvec *res_d_ug; // d-residuals - struct blasfeo_dvec *res_m; // m-residuals - struct blasfeo_dvec *res_m_lb; // m-residuals - struct blasfeo_dvec *res_m_ub; // m-residuals - struct blasfeo_dvec *res_m_lg; // m-residuals - struct blasfeo_dvec *res_m_ug; // m-residuals - struct blasfeo_svec *sres_g; // q-residuals // XXX - struct blasfeo_svec *sres_b; // b-residuals // XXX - struct blasfeo_dvec *Qx_lb; // hessian update - struct blasfeo_dvec *Qx_lg; // hessian update - struct blasfeo_dvec *qx_lb; // gradient update - struct blasfeo_dvec *qx_lg; // gradient update - struct blasfeo_svec *sQx_lb; // hessian update // XXX - struct blasfeo_svec *sQx_lg; // hessian update // XXX - struct blasfeo_svec *sqx_lb; // gradient update // XXX - struct blasfeo_svec *sqx_lg; // gradient update // XXX - struct blasfeo_dvec *tmp_nbM; // work space of size nbM - struct blasfeo_svec *tmp_nxM; // work space of size nxM // XXX - struct blasfeo_dvec *tmp_ngM; // work space of size ngM - struct blasfeo_svec *Pb; // Pb // XXX - struct blasfeo_smat *L; // XXX - struct blasfeo_smat *AL; // XXX - struct blasfeo_svec *sSx; // scaling - struct blasfeo_svec *sSi; // scaling inverted - double *stat; // convergence statistics - double res_mu; // mu-residual - int iter; // iteration number - int compute_Pb; - int scale; - }; - - - -struct m_ipm_hard_ocp_qp_arg - { - double alpha_min; // exit cond on step length - double mu_max; // exit cond on duality measure - double mu0; // initial value for duality measure - int iter_max; // exit cond in iter number - }; - - - -// -hpipm_size_t m_memsize_ipm_hard_ocp_qp(struct d_ocp_qp *d_qp, struct s_ocp_qp *s_qp, struct m_ipm_hard_ocp_qp_arg *arg); -// -void m_create_ipm_hard_ocp_qp(struct d_ocp_qp *d_qp, struct s_ocp_qp *s_qp, struct m_ipm_hard_ocp_qp_arg *arg, struct m_ipm_hard_ocp_qp_workspace *ws, void *mem); -// -void m_solve_ipm_hard_ocp_qp(struct d_ocp_qp *d_qp, struct s_ocp_qp *s_qp, struct d_ocp_qp_sol *qp_sol, struct m_ipm_hard_ocp_qp_workspace *ws); -// -void m_solve_ipm2_hard_ocp_qp(struct d_ocp_qp *d_qp, struct s_ocp_qp *s_qp, struct d_ocp_qp_sol *qp_sol, struct m_ipm_hard_ocp_qp_workspace *ws); - -#ifdef __cplusplus -} /* extern "C" */ -#endif diff --git a/third_party/acados/include/hpipm/include/hpipm_m_ocp_qp_kkt.h b/third_party/acados/include/hpipm/include/hpipm_m_ocp_qp_kkt.h deleted file mode 100644 index 032fe95b1f..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_m_ocp_qp_kkt.h +++ /dev/null @@ -1,45 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifdef __cplusplus -extern "C" { -#endif - -void m_fact_solve_kkt_step_hard_ocp_qp(struct d_ocp_qp *d_qp, struct s_ocp_qp *s_qp, struct m_ipm_hard_ocp_qp_workspace *ws); -void m_solve_kkt_step_hard_ocp_qp(struct d_ocp_qp *d_qp, struct s_ocp_qp *s_qp, struct m_ipm_hard_ocp_qp_workspace *ws); - -#ifdef __cplusplus -} /* extern "C" */ -#endif diff --git a/third_party/acados/include/hpipm/include/hpipm_s_cast_qcqp.h b/third_party/acados/include/hpipm/include/hpipm_s_cast_qcqp.h deleted file mode 100644 index ba01ecb3bd..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_cast_qcqp.h +++ /dev/null @@ -1,72 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_S_CAST_QCQP_H_ -#define HPIPM_S_CAST_QCQP_H_ - - - -#include -#include - -#include "hpipm_s_dense_qcqp.h" -#include "hpipm_s_dense_qcqp_sol.h" -#include "hpipm_s_ocp_qcqp.h" -#include "hpipm_s_ocp_qcqp_dim.h" -#include "hpipm_s_ocp_qcqp_sol.h" - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -void s_cast_qcqp_compute_dim(struct s_ocp_qcqp_dim *ocp_dim, struct s_dense_qcqp_dim *dense_dim); -// -void s_cast_qcqp_cond(struct s_ocp_qcqp *ocp_qp, struct s_dense_qcqp *dense_qp); - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_CAST_QCQP_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_cond.h b/third_party/acados/include/hpipm/include/hpipm_s_cond.h deleted file mode 100644 index 30116798b7..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_cond.h +++ /dev/null @@ -1,137 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_S_COND_H_ -#define HPIPM_S_COND_H_ - - - -#include -#include - -#include "hpipm_s_dense_qp.h" -#include "hpipm_s_dense_qp_sol.h" -#include "hpipm_s_ocp_qp.h" -#include "hpipm_s_ocp_qp_dim.h" -#include "hpipm_s_ocp_qp_sol.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_cond_qp_arg - { - int cond_last_stage; // condense last stage - int cond_alg; // condensing algorithm: 0 N2-nx3, 1 N3-nx2 - int comp_prim_sol; // primal solution (v) - int comp_dual_sol_eq; // dual solution equality constr (pi) - int comp_dual_sol_ineq; // dual solution inequality constr (lam t) - int square_root_alg; // square root algorithm (faster but requires RSQ>0) - hpipm_size_t memsize; - }; - - - -struct s_cond_qp_ws - { - struct blasfeo_smat *Gamma; - struct blasfeo_smat *GammaQ; - struct blasfeo_smat *L; - struct blasfeo_smat *Lx; - struct blasfeo_smat *AL; - struct blasfeo_svec *Gammab; - struct blasfeo_svec *l; - struct blasfeo_svec *tmp_nbgM; - struct blasfeo_svec *tmp_nuxM; - int bs; // block size - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_cond_qp_arg_memsize(); -// -void s_cond_qp_arg_create(struct s_cond_qp_arg *cond_arg, void *mem); -// -void s_cond_qp_arg_set_default(struct s_cond_qp_arg *cond_arg); -// condensing algorithm: 0 N2-nx3, 1 N3-nx2 -void s_cond_qp_arg_set_cond_alg(int cond_alg, struct s_cond_qp_arg *cond_arg); -// set riccati-like algorithm: 0 classical, 1 square-root -void s_cond_qp_arg_set_ric_alg(int ric_alg, struct s_cond_qp_arg *cond_arg); -// condense last stage: 0 last stage disregarded, 1 last stage condensed too -void s_cond_qp_arg_set_cond_last_stage(int cond_last_stage, struct s_cond_qp_arg *cond_arg); -// -void s_cond_qp_arg_set_comp_prim_sol(int value, struct s_cond_qp_arg *cond_arg); -// -void s_cond_qp_arg_set_comp_dual_sol_eq(int value, struct s_cond_qp_arg *cond_arg); -// -void s_cond_qp_arg_set_comp_dual_sol_ineq(int value, struct s_cond_qp_arg *cond_arg); - -// -void s_cond_qp_compute_dim(struct s_ocp_qp_dim *ocp_dim, struct s_dense_qp_dim *dense_dim); -// -hpipm_size_t s_cond_qp_ws_memsize(struct s_ocp_qp_dim *ocp_dim, struct s_cond_qp_arg *cond_arg); -// -void s_cond_qp_ws_create(struct s_ocp_qp_dim *ocp_dim, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws, void *mem); -// -void s_cond_qp_cond(struct s_ocp_qp *ocp_qp, struct s_dense_qp *dense_qp, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws); -// -void s_cond_qp_cond_lhs(struct s_ocp_qp *ocp_qp, struct s_dense_qp *dense_qp, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws); -// -void s_cond_qp_cond_rhs(struct s_ocp_qp *ocp_qp, struct s_dense_qp *dense_qp, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws); -// -void s_cond_qp_expand_sol(struct s_ocp_qp *ocp_qp, struct s_dense_qp_sol *dense_qp_sol, struct s_ocp_qp_sol *ocp_qp_sol, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws); -// TODO remove -void s_cond_qp_expand_primal_sol(struct s_ocp_qp *ocp_qp, struct s_dense_qp_sol *dense_qp_sol, struct s_ocp_qp_sol *ocp_qp_sol, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws); - -// -void s_cond_qp_update(int *idxc, struct s_ocp_qp *ocp_qp, struct s_dense_qp *dense_qp, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_COND_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_s_cond_aux.h b/third_party/acados/include/hpipm/include/hpipm_s_cond_aux.h deleted file mode 100644 index 003472ab9f..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_cond_aux.h +++ /dev/null @@ -1,92 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_S_COND_AUX_H_ -#define HPIPM_S_COND_AUX_H_ - - - -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -void s_cond_BAbt(struct s_ocp_qp *ocp_qp, struct blasfeo_smat *BAbt2, struct blasfeo_svec *b2, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws); -// -void s_cond_BAt(struct s_ocp_qp *ocp_qp, struct blasfeo_smat *BAbt2, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws); -// -void s_cond_b(struct s_ocp_qp *ocp_qp, struct blasfeo_svec *b2, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws); -// -void s_cond_RSQrq(struct s_ocp_qp *ocp_qp, struct blasfeo_smat *RSQrq2, struct blasfeo_svec *rq2, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws); -// -void s_cond_RSQ(struct s_ocp_qp *ocp_qp, struct blasfeo_smat *RSQrq2, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws); -// -void s_cond_rq(struct s_ocp_qp *ocp_qp, struct blasfeo_svec *rq2, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws); -// -void s_cond_DCtd(struct s_ocp_qp *ocp_qp, int *idxb2, struct blasfeo_smat *DCt2, struct blasfeo_svec *d2, struct blasfeo_svec *d_mask2, int *idxs_rev2, struct blasfeo_svec *Z2, struct blasfeo_svec *z2, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws); -// -void s_cond_DCt(struct s_ocp_qp *ocp_qp, int *idxb2, struct blasfeo_smat *DCt2, int *idxs_rev2, struct blasfeo_svec *Z2, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws); -// -void s_cond_d(struct s_ocp_qp *ocp_qp, struct blasfeo_svec *d2, struct blasfeo_svec *d_mask2, struct blasfeo_svec *z2, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws); -// -void s_expand_sol(struct s_ocp_qp *ocp_qp, struct s_dense_qp_sol *dense_qp_sol, struct s_ocp_qp_sol *ocp_qp_sol, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws); -// -void s_expand_primal_sol(struct s_ocp_qp *ocp_qp, struct s_dense_qp_sol *dense_qp_sol, struct s_ocp_qp_sol *ocp_qp_sol, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws); - -// -void s_update_cond_BAbt(int *idxc, struct s_ocp_qp *ocp_qp, struct blasfeo_smat *BAbt2, struct blasfeo_svec *b2, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws); -// -void s_update_cond_RSQrq_N2nx3(int *idxc, struct s_ocp_qp *ocp_qp, struct blasfeo_smat *RSQrq2, struct blasfeo_svec *rq2, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws); -// -void s_update_cond_DCtd(int *idxc, struct s_ocp_qp *ocp_qp, int *idxb2, struct blasfeo_smat *DCt2, struct blasfeo_svec *d2, int *idxs2, struct blasfeo_svec *Z2, struct blasfeo_svec *z2, struct s_cond_qp_arg *cond_arg, struct s_cond_qp_ws *cond_ws); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_COND_AUX_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_s_cond_qcqp.h b/third_party/acados/include/hpipm/include/hpipm_s_cond_qcqp.h deleted file mode 100644 index c36678abd5..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_cond_qcqp.h +++ /dev/null @@ -1,130 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_S_COND_QCQP_H_ -#define HPIPM_S_COND_QCQP_H_ - - - -#include -#include - -#include "hpipm_s_dense_qcqp.h" -#include "hpipm_s_dense_qcqp_sol.h" -#include "hpipm_s_ocp_qcqp.h" -#include "hpipm_s_ocp_qcqp_dim.h" -#include "hpipm_s_ocp_qcqp_sol.h" - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_cond_qcqp_arg - { - struct s_cond_qp_arg *qp_arg; - int cond_last_stage; // condense last stage -// int cond_variant; // TODO - int comp_prim_sol; // primal solution (v) - int comp_dual_sol_eq; // dual solution equality constr (pi) - int comp_dual_sol_ineq; // dual solution equality constr (lam t) - int square_root_alg; // square root algorithm (faster but requires RSQ>0) - hpipm_size_t memsize; - }; - - - -struct s_cond_qcqp_ws - { - struct s_cond_qp_ws *qp_ws; - struct blasfeo_smat *hess_array; // TODO remove - struct blasfeo_smat *zero_hess; // TODO remove - struct blasfeo_svec *zero_grad; // TODO remove - struct blasfeo_svec *grad_array; // TODO remove - struct blasfeo_svec *tmp_nvc; - struct blasfeo_svec *tmp_nuxM; - struct blasfeo_smat *GammaQ; - struct blasfeo_smat *tmp_DCt; - struct blasfeo_smat *tmp_nuM_nxM; -// struct blasfeo_svec *d_qp; -// struct blasfeo_svec *d_mask_qp; - hpipm_size_t memsize; - }; - - -// -hpipm_size_t s_cond_qcqp_arg_memsize(); -// -void s_cond_qcqp_arg_create(struct s_cond_qcqp_arg *cond_arg, void *mem); -// -void s_cond_qcqp_arg_set_default(struct s_cond_qcqp_arg *cond_arg); -// set riccati-like algorithm: 0 classical, 1 square-root -void s_cond_qcqp_arg_set_ric_alg(int ric_alg, struct s_cond_qcqp_arg *cond_arg); -// condense last stage: 0 last stage disregarded, 1 last stage condensed too -void s_cond_qcqp_arg_set_cond_last_stage(int cond_last_stage, struct s_cond_qcqp_arg *cond_arg); - -// -void s_cond_qcqp_compute_dim(struct s_ocp_qcqp_dim *ocp_dim, struct s_dense_qcqp_dim *dense_dim); -// -hpipm_size_t s_cond_qcqp_ws_memsize(struct s_ocp_qcqp_dim *ocp_dim, struct s_cond_qcqp_arg *cond_arg); -// -void s_cond_qcqp_ws_create(struct s_ocp_qcqp_dim *ocp_dim, struct s_cond_qcqp_arg *cond_arg, struct s_cond_qcqp_ws *cond_ws, void *mem); -// -void s_cond_qcqp_qc(struct s_ocp_qcqp *ocp_qp, struct blasfeo_smat *Hq2, int *Hq_nzero2, struct blasfeo_smat *Ct2, struct blasfeo_svec *d2, struct s_cond_qcqp_arg *cond_arg, struct s_cond_qcqp_ws *cond_ws); -// -void s_cond_qcqp_qc_lhs(struct s_ocp_qcqp *ocp_qp, struct blasfeo_smat *Hq2, int *Hq_nzero2, struct blasfeo_smat *Ct2, struct s_cond_qcqp_arg *cond_arg, struct s_cond_qcqp_ws *cond_ws); -// -void s_cond_qcqp_qc_rhs(struct s_ocp_qcqp *ocp_qp, struct blasfeo_svec *d2, struct s_cond_qcqp_arg *cond_arg, struct s_cond_qcqp_ws *cond_ws); -// -void s_cond_qcqp_cond(struct s_ocp_qcqp *ocp_qp, struct s_dense_qcqp *dense_qp, struct s_cond_qcqp_arg *cond_arg, struct s_cond_qcqp_ws *cond_ws); -// -void s_cond_qcqp_cond_rhs(struct s_ocp_qcqp *ocp_qp, struct s_dense_qcqp *dense_qp, struct s_cond_qcqp_arg *cond_arg, struct s_cond_qcqp_ws *cond_ws); -// -void s_cond_qcqp_cond_lhs(struct s_ocp_qcqp *ocp_qp, struct s_dense_qcqp *dense_qp, struct s_cond_qcqp_arg *cond_arg, struct s_cond_qcqp_ws *cond_ws); -// -void s_cond_qcqp_expand_sol(struct s_ocp_qcqp *ocp_qp, struct s_dense_qcqp_sol *dense_qp_sol, struct s_ocp_qcqp_sol *ocp_qp_sol, struct s_cond_qcqp_arg *cond_arg, struct s_cond_qcqp_ws *cond_ws); - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_COND_QCQP_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_core_qp_ipm.h b/third_party/acados/include/hpipm/include/hpipm_s_core_qp_ipm.h deleted file mode 100644 index 480392c7d9..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_core_qp_ipm.h +++ /dev/null @@ -1,101 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_CORE_QP_IPM_ -#define HPIPM_S_CORE_QP_IPM_ - -#include "hpipm_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - -struct s_core_qp_ipm_workspace - { - float *v; // primal variables - float *pi; // equality constraints multipliers - float *lam; // inequality constraints multipliers - float *t; // inequality constraints slacks - float *t_inv; // inverse of t - float *v_bkp; // backup of primal variables - float *pi_bkp; // backup of equality constraints multipliers - float *lam_bkp; // backup of inequality constraints multipliers - float *t_bkp; // backup of inequality constraints slacks - float *dv; // step in v - float *dpi; // step in pi - float *dlam; // step in lam - float *dt; // step in t - float *res_g; // q-residuals - float *res_b; // b-residuals - float *res_d; // d-residuals - float *res_m; // m-residuals - float *res_m_bkp; // m-residuals - float *Gamma; // Hessian update - float *gamma; // gradient update - float alpha_prim; // step length - float alpha_dual; // step length - float alpha; // step length - float sigma; // centering XXX - float mu; // duality measuere - float mu_aff; // affine duality measuere - float nc_inv; // 1.0/nc, where nc is the total number of constraints - float nc_mask_inv; // 1.0/nc_mask - float lam_min; // min value in lam vector - float t_min; // min value in t vector - float t_min_inv; // inverse of min value in t vector - float tau_min; // min value of barrier parameter - int nv; // number of primal variables - int ne; // number of equality constraints - int nc; // (twice the) number of (two-sided) inequality constraints - int nc_mask; // total number of ineq constr after masking - int split_step; // use different step for primal and dual variables - int t_lam_min; // clip t and lam also in solution, or only in Gamma computation - hpipm_size_t memsize; // memory size (in bytes) of workspace - }; - - - -// -hpipm_size_t s_memsize_core_qp_ipm(int nv, int ne, int nc); -// -void s_create_core_qp_ipm(int nv, int ne, int nc, struct s_core_qp_ipm_workspace *workspace, void *mem); -// -void s_core_qp_ipm(struct s_core_qp_ipm_workspace *workspace); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // HPIPM_S_CORE_QP_IPM_ diff --git a/third_party/acados/include/hpipm/include/hpipm_s_core_qp_ipm_aux.h b/third_party/acados/include/hpipm/include/hpipm_s_core_qp_ipm_aux.h deleted file mode 100644 index 1ac3d7ede9..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_core_qp_ipm_aux.h +++ /dev/null @@ -1,68 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_CORE_QP_IPM_AUX_ -#define HPIPM_S_CORE_QP_IPM_AUX_ - -#ifdef __cplusplus -extern "C" { -#endif - -// -void s_compute_Gamma_gamma_qp(float *res_d, float *res_m, struct s_core_qp_ipm_workspace *rws); -// -void s_compute_gamma_qp(float *res_d, float *res_m, struct s_core_qp_ipm_workspace *rws); -// -void s_compute_lam_t_qp(float *res_d, float *res_m, float *dlam, float *dt, struct s_core_qp_ipm_workspace *rws); -// -void s_compute_alpha_qp(struct s_core_qp_ipm_workspace *rws); -// -void s_update_var_qp(struct s_core_qp_ipm_workspace *rws); -// -void s_compute_mu_aff_qp(struct s_core_qp_ipm_workspace *rws); -// -void s_backup_res_m(struct s_core_qp_ipm_workspace *rws); -// -void s_compute_centering_correction_qp(struct s_core_qp_ipm_workspace *rws); -// -void s_compute_centering_qp(struct s_core_qp_ipm_workspace *rws); -// -void s_compute_tau_min_qp(struct s_core_qp_ipm_workspace *rws); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // HPIPM_S_CORE_QP_IPM_AUX_ diff --git a/third_party/acados/include/hpipm/include/hpipm_s_dense_qcqp.h b/third_party/acados/include/hpipm/include/hpipm_s_dense_qcqp.h deleted file mode 100644 index d03c065375..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_dense_qcqp.h +++ /dev/null @@ -1,200 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_S_DENSE_QCQP_H_ -#define HPIPM_S_DENSE_QCQP_H_ - - - -#include -#include - -#include "hpipm_s_dense_qcqp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_dense_qcqp - { - struct s_dense_qcqp_dim *dim; - struct blasfeo_smat *Hv; // hessian of cost & vector work space - struct blasfeo_smat *A; // equality constraint matrix - struct blasfeo_smat *Ct; // inequality constraints matrix - struct blasfeo_smat *Hq; // hessians of quadratic constraints - struct blasfeo_svec *gz; // gradient of cost & gradient of slacks - struct blasfeo_svec *b; // equality constraint vector - struct blasfeo_svec *d; // inequality constraints vector - struct blasfeo_svec *d_mask; // inequality constraints mask vector - struct blasfeo_svec *m; // rhs of complementarity condition - struct blasfeo_svec *Z; // (diagonal) hessian of slacks - int *idxb; // indices of box constrained variables within [u; x] - int *idxs_rev; // index of soft constraints (reverse storage) - int *Hq_nzero; // for each int, the last 3 bits ...abc, {a,b,c}=0 => {R,S,Q}=0 - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -hpipm_size_t s_dense_qcqp_memsize(struct s_dense_qcqp_dim *dim); -// -void s_dense_qcqp_create(struct s_dense_qcqp_dim *dim, struct s_dense_qcqp *qp, void *memory); - -// -void s_dense_qcqp_set(char *field, void *value, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_H(float *H, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_g(float *g, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_A(float *A, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_b(float *b, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_idxb(int *idxb, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_lb(float *lb, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_lb_mask(float *lb, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_ub(float *ub, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_ub_mask(float *ub, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_C(float *C, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_lg(float *lg, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_lg_mask(float *lg, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_ug(float *ug, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_ug_mask(float *ug, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_Hq(float *Hq, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_gq(float *gq, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_uq(float *uq, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_uq_mask(float *uq, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_idxs(int *idxs, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_idxs_rev(int *idxs_rev, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_Zl(float *Zl, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_Zu(float *Zu, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_zl(float *zl, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_zu(float *zu, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_ls(float *ls, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_ls_mask(float *ls, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_us(float *us, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_set_us_mask(float *us, struct s_dense_qcqp *qp); - -// getters (COLMAJ) - -void s_dense_qcqp_get_H(struct s_dense_qcqp *qp, float *H); -// -void s_dense_qcqp_get_g(struct s_dense_qcqp *qp, float *g); -// -void s_dense_qcqp_get_A(struct s_dense_qcqp *qp, float *A); -// -void s_dense_qcqp_get_b(struct s_dense_qcqp *qp, float *b); -// -void s_dense_qcqp_get_idxb(struct s_dense_qcqp *qp, int *idxb); -// -void s_dense_qcqp_get_lb(struct s_dense_qcqp *qp, float *lb); -// -void s_dense_qcqp_get_lb_mask(struct s_dense_qcqp *qp, float *lb); -// -void s_dense_qcqp_get_ub(struct s_dense_qcqp *qp, float *ub); -// -void s_dense_qcqp_get_ub_mask(struct s_dense_qcqp *qp, float *ub); -// -void s_dense_qcqp_get_C(struct s_dense_qcqp *qp, float *C); -// -void s_dense_qcqp_get_lg(struct s_dense_qcqp *qp, float *lg); -// -void s_dense_qcqp_get_lg_mask(struct s_dense_qcqp *qp, float *lg); -// -void s_dense_qcqp_get_ug(struct s_dense_qcqp *qp, float *ug); -// -void s_dense_qcqp_get_ug_mask(struct s_dense_qcqp *qp, float *ug); -// -void s_dense_qcqp_get_idxs(struct s_dense_qcqp *qp, int *idxs); -// -void s_dense_qcqp_get_idxs_rev(struct s_dense_qcqp *qp, int *idxs_rev); -// -void s_dense_qcqp_get_Zl(struct s_dense_qcqp *qp, float *Zl); -// -void s_dense_qcqp_get_Zu(struct s_dense_qcqp *qp, float *Zu); -// -void s_dense_qcqp_get_zl(struct s_dense_qcqp *qp, float *zl); -// -void s_dense_qcqp_get_zu(struct s_dense_qcqp *qp, float *zu); -// -void s_dense_qcqp_get_ls(struct s_dense_qcqp *qp, float *ls); -// -void s_dense_qcqp_get_ls_mask(struct s_dense_qcqp *qp, float *ls); -// -void s_dense_qcqp_get_us(struct s_dense_qcqp *qp, float *us); -// -void s_dense_qcqp_get_us_mask(struct s_dense_qcqp *qp, float *us); - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_DENSE_QCQP_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_dense_qcqp_dim.h b/third_party/acados/include/hpipm/include/hpipm_s_dense_qcqp_dim.h deleted file mode 100644 index 04908c2c3a..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_dense_qcqp_dim.h +++ /dev/null @@ -1,99 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_DENSE_QCQP_DIM_H_ -#define HPIPM_S_DENSE_QCQP_DIM_H_ - -#include "hpipm_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_dense_qcqp_dim - { - struct s_dense_qp_dim *qp_dim; // dim of qp approximation - int nv; // number of variables - int ne; // number of equality constraints - int nb; // number of box constraints - int ng; // number of general constraints - int nq; // number of quadratic constraints - int nsb; // number of softened box constraints - int nsg; // number of softened general constraints - int nsq; // number of softened quadratic constraints - int ns; // number of softened constraints (nsb+nsg+nsq) TODO number of slacks - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_dense_qcqp_dim_memsize(); -// -void s_dense_qcqp_dim_create(struct s_dense_qcqp_dim *dim, void *memory); -// -void s_dense_qcqp_dim_set(char *fiels_name, int value, struct s_dense_qcqp_dim *dim); -// -void s_dense_qcqp_dim_set_nv(int value, struct s_dense_qcqp_dim *dim); -// -void s_dense_qcqp_dim_set_ne(int value, struct s_dense_qcqp_dim *dim); -// -void s_dense_qcqp_dim_set_nb(int value, struct s_dense_qcqp_dim *dim); -// -void s_dense_qcqp_dim_set_ng(int value, struct s_dense_qcqp_dim *dim); -// -void s_dense_qcqp_dim_set_nq(int value, struct s_dense_qcqp_dim *dim); -// -void s_dense_qcqp_dim_set_nsb(int value, struct s_dense_qcqp_dim *dim); -// -void s_dense_qcqp_dim_set_nsg(int value, struct s_dense_qcqp_dim *dim); -// -void s_dense_qcqp_dim_set_nsq(int value, struct s_dense_qcqp_dim *dim); -// -void s_dense_qcqp_dim_set_ns(int value, struct s_dense_qcqp_dim *dim); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_S_DENSE_QCQP_DIM_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_dense_qcqp_ipm.h b/third_party/acados/include/hpipm/include/hpipm_s_dense_qcqp_ipm.h deleted file mode 100644 index 8f85768ee3..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_dense_qcqp_ipm.h +++ /dev/null @@ -1,204 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_S_DENSE_QCQP_IPM_H_ -#define HPIPM_S_DENSE_QCQP_IPM_H_ - - - -#include -#include - -#include -#include -#include -#include -#include - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_dense_qcqp_ipm_arg - { - struct s_dense_qp_ipm_arg *qp_arg; - float mu0; // initial value for duality measure - float alpha_min; // exit cond on step length - float res_g_max; // exit cond on inf norm of residuals - float res_b_max; // exit cond on inf norm of residuals - float res_d_max; // exit cond on inf norm of residuals - float res_m_max; // exit cond on inf norm of residuals - float reg_prim; // reg of primal hessian - float reg_dual; // reg of dual hessian - float lam_min; // min value in lam vector - float t_min; // min value in t vector - int iter_max; // exit cond in iter number - int stat_max; // iterations saved in stat - int pred_corr; // Mehrotra's predictor-corrector IPM algirthm - int cond_pred_corr; // conditional Mehrotra's predictor-corrector - int scale; // scale hessian - int itref_pred_max; // max number of iterative refinement steps for predictor step - int itref_corr_max; // max number of iterative refinement steps for corrector step - int warm_start; // 0 no warm start, 1 warm start primal sol, 2 warm start primal and dual sol - int lq_fact; // 0 syrk+potrf, 1 mix, 2 lq - int abs_form; // absolute IPM formulation - int comp_res_exit; // compute residuals on exit (only for abs_form==1) - int comp_res_pred; // compute residuals of prediction - int split_step; // use different step for primal and dual variables - int t_lam_min; // clip t and lam: 0 no, 1 in Gamma computation, 2 in solution - int mode; - hpipm_size_t memsize; - }; - - - -struct s_dense_qcqp_ipm_ws - { -// float qp_res[4]; // infinity norm of residuals - struct s_dense_qp_ipm_ws *qp_ws; - struct s_dense_qp *qp; - struct s_dense_qp_sol *qp_sol; - struct s_dense_qcqp_res_ws *qcqp_res_ws; - struct s_dense_qcqp_res *qcqp_res; - struct blasfeo_svec *tmp_nv; -// float *stat; // convergence statistics -// void *lq_work0; -// void *lq_work1; - int iter; // iteration number -// int stat_max; // iterations saved in stat -// int stat_m; // numer of recorded stat per ipm iter -// int scale; -// int use_hess_fact; - int status; - hpipm_size_t memsize; // memory size (in bytes) of workspace - }; - - - -// -hpipm_size_t s_dense_qcqp_ipm_arg_memsize(struct s_dense_qcqp_dim *dim); -// -void s_dense_qcqp_ipm_arg_create(struct s_dense_qcqp_dim *dim, struct s_dense_qcqp_ipm_arg *arg, void *mem); -// -void s_dense_qcqp_ipm_arg_set_default(enum hpipm_mode mode, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_ipm_arg_set(char *field, void *value, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_ipm_arg_set_iter_max(int *iter_max, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_ipm_arg_set_alpha_min(float *alpha_min, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_ipm_arg_set_mu0(float *mu0, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_ipm_arg_set_tol_stat(float *tol_stat, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_ipm_arg_set_tol_eq(float *tol_eq, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_ipm_arg_set_tol_ineq(float *tol_ineq, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_ipm_arg_set_tol_comp(float *tol_comp, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_ipm_arg_set_reg_prim(float *reg, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_ipm_arg_set_reg_dual(float *reg, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_ipm_arg_set_warm_start(int *warm_start, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_ipm_arg_set_pred_corr(int *pred_corr, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_ipm_arg_set_cond_pred_corr(int *cond_pred_corr, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_ipm_arg_set_comp_res_pred(int *comp_res_pred, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_ipm_arg_set_comp_res_exit(int *comp_res_exit, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_ipm_arg_set_lam_min(float *value, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_ipm_arg_set_t_min(float *value, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_ipm_arg_set_split_step(int *value, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_ipm_arg_set_t_lam_min(int *value, struct s_dense_qcqp_ipm_arg *arg); - -// -hpipm_size_t s_dense_qcqp_ipm_ws_memsize(struct s_dense_qcqp_dim *qp_dim, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_ipm_ws_create(struct s_dense_qcqp_dim *qp_dim, struct s_dense_qcqp_ipm_arg *arg, struct s_dense_qcqp_ipm_ws *ws, void *mem); -// -void s_dense_qcqp_ipm_get(char *field, struct s_dense_qcqp_ipm_ws *ws, void *value); -// -void s_dense_qcqp_ipm_get_status(struct s_dense_qcqp_ipm_ws *ws, int *status); -// -void s_dense_qcqp_ipm_get_iter(struct s_dense_qcqp_ipm_ws *ws, int *iter); -// -void s_dense_qcqp_ipm_get_max_res_stat(struct s_dense_qcqp_ipm_ws *ws, float *res_stat); -// -void s_dense_qcqp_ipm_get_max_res_eq(struct s_dense_qcqp_ipm_ws *ws, float *res_eq); -// -void s_dense_qcqp_ipm_get_max_res_ineq(struct s_dense_qcqp_ipm_ws *ws, float *res_ineq); -// -void s_dense_qcqp_ipm_get_max_res_comp(struct s_dense_qcqp_ipm_ws *ws, float *res_comp); -// -void s_dense_qcqp_ipm_get_stat(struct s_dense_qcqp_ipm_ws *ws, float **stat); -// -void s_dense_qcqp_ipm_get_stat_m(struct s_dense_qcqp_ipm_ws *ws, int *stat_m); -#if 0 -// -void s_dense_qcqp_init_var(struct s_dense_qcqp *qp, struct s_dense_qcqp_sol *qp_sol, struct s_dense_qcqp_ipm_arg *arg, struct s_dense_qcqp_ipm_ws *ws); -#endif -// -void s_dense_qcqp_ipm_solve(struct s_dense_qcqp *qp, struct s_dense_qcqp_sol *qp_sol, struct s_dense_qcqp_ipm_arg *arg, struct s_dense_qcqp_ipm_ws *ws); -#if 0 -// -void s_dense_qcqp_ipm_predict(struct s_dense_qcqp *qp, struct s_dense_qcqp_sol *qp_sol, struct s_dense_qcqp_ipm_arg *arg, struct s_dense_qcqp_ipm_ws *ws); -// -void s_dense_qcqp_ipm_sens(struct s_dense_qcqp *qp, struct s_dense_qcqp_sol *qp_sol, struct s_dense_qcqp_ipm_arg *arg, struct s_dense_qcqp_ipm_ws *ws); -#endif - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_DENSE_QCQP_IPM_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_dense_qcqp_res.h b/third_party/acados/include/hpipm/include/hpipm_s_dense_qcqp_res.h deleted file mode 100644 index 779658cc8f..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_dense_qcqp_res.h +++ /dev/null @@ -1,108 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_DENSE_QCQP_RES_H_ -#define HPIPM_S_DENSE_QCQP_RES_H_ - - - -#include -#include - -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_dense_qcqp_res - { - struct s_dense_qcqp_dim *dim; - struct blasfeo_svec *res_g; // q-residuals - struct blasfeo_svec *res_b; // b-residuals - struct blasfeo_svec *res_d; // d-residuals - struct blasfeo_svec *res_m; // m-residuals - float res_max[4]; // infinity norm of residuals - float res_mu; // mu-residual - hpipm_size_t memsize; - }; - - - -struct s_dense_qcqp_res_ws - { - struct blasfeo_svec *tmp_nv; // work space of size nv - struct blasfeo_svec *tmp_nbgq; // work space of size nbM+ngM+nqM - struct blasfeo_svec *tmp_ns; // work space of size nsM - struct blasfeo_svec *q_fun; // value for evaluation of quadr constr - struct blasfeo_svec *q_adj; // value for adjoint of quadr constr - int use_q_fun; // reuse cached value for evaluation of quadr constr - int use_q_adj; // reuse cached value for adjoint of quadr constr - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_dense_qcqp_res_memsize(struct s_dense_qcqp_dim *dim); -// -void s_dense_qcqp_res_create(struct s_dense_qcqp_dim *dim, struct s_dense_qcqp_res *res, void *mem); -// -hpipm_size_t s_dense_qcqp_res_ws_memsize(struct s_dense_qcqp_dim *dim); -// -void s_dense_qcqp_res_ws_create(struct s_dense_qcqp_dim *dim, struct s_dense_qcqp_res_ws *workspace, void *mem); -// -void s_dense_qcqp_res_compute(struct s_dense_qcqp *qp, struct s_dense_qcqp_sol *qp_sol, struct s_dense_qcqp_res *res, struct s_dense_qcqp_res_ws *ws); -// -void s_dense_qcqp_res_compute_inf_norm(struct s_dense_qcqp_res *res); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - -#endif // HPIPM_S_DENSE_QCQP_RES_H_ - - - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_dense_qcqp_sol.h b/third_party/acados/include/hpipm/include/hpipm_s_dense_qcqp_sol.h deleted file mode 100644 index 197a690e52..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_dense_qcqp_sol.h +++ /dev/null @@ -1,86 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_S_DENSE_QCQP_SOL_H_ -#define HPIPM_S_DENSE_QCQP_SOL_H_ - - - -#include -#include - -#include "hpipm_s_dense_qcqp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_dense_qcqp_sol - { - struct s_dense_qcqp_dim *dim; - struct blasfeo_svec *v; - struct blasfeo_svec *pi; - struct blasfeo_svec *lam; - struct blasfeo_svec *t; - void *misc; - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_dense_qcqp_sol_memsize(struct s_dense_qcqp_dim *dim); -// -void s_dense_qcqp_sol_create(struct s_dense_qcqp_dim *dim, struct s_dense_qcqp_sol *qp_sol, void *memory); -// -void s_dense_qcqp_sol_get_v(struct s_dense_qcqp_sol *qp_sol, float *v); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_DENSE_QCQP_SOL_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_dense_qcqp_utils.h b/third_party/acados/include/hpipm/include/hpipm_s_dense_qcqp_utils.h deleted file mode 100644 index 4f5aae26eb..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_dense_qcqp_utils.h +++ /dev/null @@ -1,83 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_DENSE_QCQP_UTILS_H_ -#define HPIPM_S_DENSE_QCQP_UTILS_H_ - - - -#include -#include - -#include "hpipm_s_dense_qcqp_dim.h" -#include "hpipm_s_dense_qcqp.h" -#include "hpipm_s_dense_qcqp_sol.h" -//#include "hpipm_s_dense_qcqp_ipm.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -void s_dense_qcqp_dim_print(struct s_dense_qcqp_dim *qp_dim); -// -//void s_dense_qcqp_dim_codegen(char *file_name, char *mode, struct s_dense_qcqp_dim *qp_dim); -// -void s_dense_qcqp_print(struct s_dense_qcqp_dim *qp_dim, struct s_dense_qcqp *qp); -// -//void s_dense_qcqp_codegen(char *file_name, char *mode, struct s_dense_qcqp_dim *qp_dim, struct s_dense_qcqp *qp); -// -void s_dense_qcqp_sol_print(struct s_dense_qcqp_dim *qp_dim, struct s_dense_qcqp_sol *dense_qcqp_sol); -// -//void s_dense_qcqp_ipm_arg_codegen(char *file_name, char *mode, struct s_dense_qcqp_dim *qp_dim, struct s_dense_qcqp_ipm_arg *arg); -// -void s_dense_qcqp_res_print(struct s_dense_qcqp_dim *qp_dim, struct s_dense_qcqp_res *dense_qcqp_res); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_S_DENSE_QCQP_UTILS_H_ - - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_dense_qp.h b/third_party/acados/include/hpipm/include/hpipm_s_dense_qp.h deleted file mode 100644 index 3c2517fe1b..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_dense_qp.h +++ /dev/null @@ -1,207 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_S_DENSE_QP_H_ -#define HPIPM_S_DENSE_QP_H_ - - - -#include -#include - -#include "hpipm_s_dense_qp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_dense_qp - { - struct s_dense_qp_dim *dim; - struct blasfeo_smat *Hv; // hessian & gradient - struct blasfeo_smat *A; // dynamics matrix - struct blasfeo_smat *Ct; // constraints matrix - struct blasfeo_svec *gz; // gradient & gradient of slacks - struct blasfeo_svec *b; // dynamics vector - struct blasfeo_svec *d; // constraints vector - struct blasfeo_svec *d_mask; // inequality constraints mask vector - struct blasfeo_svec *m; // rhs of complementarity condition - struct blasfeo_svec *Z; // (diagonal) hessian of slacks - int *idxb; // indices of box constrained variables within [u; x] - int *idxs_rev; // index of soft constraints (reverse storage) - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -hpipm_size_t s_dense_qp_memsize(struct s_dense_qp_dim *dim); -// -void s_dense_qp_create(struct s_dense_qp_dim *dim, struct s_dense_qp *qp, void *memory); - -// setters - colmaj -// -void s_dense_qp_set_all(float *H, float *g, float *A, float *b, int *idxb, float *d_lb, float *d_ub, float *C, float *d_lg, float *d_ug, float *Zl, float *Zu, float *zl, float *zu, int *idxs, float *d_ls, float *d_us, struct s_dense_qp *qp); -// -void s_dense_qp_get_all(struct s_dense_qp *qp, float *H, float *g, float *A, float *b, int *idxb, float *d_lb, float *d_ub, float *C, float *d_lg, float *d_ug, float *Zl, float *Zu, float *zl, float *zu, int *idxs, float *d_ls, float *d_us); -// -void s_dense_qp_set(char *field, void *value, struct s_dense_qp *qp); -// -void s_dense_qp_set_H(float *H, struct s_dense_qp *qp); -// -void s_dense_qp_set_g(float *g, struct s_dense_qp *qp); -// -void s_dense_qp_set_A(float *A, struct s_dense_qp *qp); -// -void s_dense_qp_set_b(float *b, struct s_dense_qp *qp); -// -void s_dense_qp_set_idxb(int *idxb, struct s_dense_qp *qp); -// -void s_dense_qp_set_Jb(float *Jb, struct s_dense_qp *qp); -// -void s_dense_qp_set_lb(float *lb, struct s_dense_qp *qp); -// -void s_dense_qp_set_lb_mask(float *lb, struct s_dense_qp *qp); -// -void s_dense_qp_set_ub(float *ub, struct s_dense_qp *qp); -// -void s_dense_qp_set_ub_mask(float *ub, struct s_dense_qp *qp); -// -void s_dense_qp_set_C(float *C, struct s_dense_qp *qp); -// -void s_dense_qp_set_lg(float *lg, struct s_dense_qp *qp); -// -void s_dense_qp_set_lg_mask(float *lg, struct s_dense_qp *qp); -// -void s_dense_qp_set_ug(float *ug, struct s_dense_qp *qp); -// -void s_dense_qp_set_ug_mask(float *ug, struct s_dense_qp *qp); -// -void s_dense_qp_set_idxs(int *idxs, struct s_dense_qp *qp); -// -void s_dense_qp_set_idxs_rev(int *idxs_rev, struct s_dense_qp *qp); -// -void s_dense_qp_set_Jsb(float *Jsb, struct s_dense_qp *qp); -// -void s_dense_qp_set_Jsg(float *Jsg, struct s_dense_qp *qp); -// -void s_dense_qp_set_Zl(float *Zl, struct s_dense_qp *qp); -// -void s_dense_qp_set_Zu(float *Zu, struct s_dense_qp *qp); -// -void s_dense_qp_set_zl(float *zl, struct s_dense_qp *qp); -// -void s_dense_qp_set_zu(float *zu, struct s_dense_qp *qp); -// -void s_dense_qp_set_ls(float *ls, struct s_dense_qp *qp); -// -void s_dense_qp_set_ls_mask(float *ls, struct s_dense_qp *qp); -// -void s_dense_qp_set_us(float *us, struct s_dense_qp *qp); -// -void s_dense_qp_set_us_mask(float *us, struct s_dense_qp *qp); - -// getters - colmaj -// -void s_dense_qp_get_H(struct s_dense_qp *qp, float *H); -// -void s_dense_qp_get_g(struct s_dense_qp *qp, float *g); -// -void s_dense_qp_get_A(struct s_dense_qp *qp, float *A); -// -void s_dense_qp_get_b(struct s_dense_qp *qp, float *b); -// -void s_dense_qp_get_idxb(struct s_dense_qp *qp, int *idxb); -// -void s_dense_qp_get_lb(struct s_dense_qp *qp, float *lb); -// -void s_dense_qp_get_lb_mask(struct s_dense_qp *qp, float *lb); -// -void s_dense_qp_get_ub(struct s_dense_qp *qp, float *ub); -// -void s_dense_qp_get_ub_mask(struct s_dense_qp *qp, float *ub); -// -void s_dense_qp_get_C(struct s_dense_qp *qp, float *C); -// -void s_dense_qp_get_lg(struct s_dense_qp *qp, float *lg); -// -void s_dense_qp_get_lg_mask(struct s_dense_qp *qp, float *lg); -// -void s_dense_qp_get_ug(struct s_dense_qp *qp, float *ug); -// -void s_dense_qp_get_ug_mask(struct s_dense_qp *qp, float *ug); -// -void s_dense_qp_get_idxs(struct s_dense_qp *qp, int *idxs); -// -void s_dense_qp_get_idxs_rev(struct s_dense_qp *qp, int *idxs_rev); -// -void s_dense_qp_get_Zl(struct s_dense_qp *qp, float *Zl); -// -void s_dense_qp_get_Zu(struct s_dense_qp *qp, float *Zu); -// -void s_dense_qp_get_zl(struct s_dense_qp *qp, float *zl); -// -void s_dense_qp_get_zu(struct s_dense_qp *qp, float *zu); -// -void s_dense_qp_get_ls(struct s_dense_qp *qp, float *ls); -// -void s_dense_qp_get_ls_mask(struct s_dense_qp *qp, float *ls); -// -void s_dense_qp_get_us(struct s_dense_qp *qp, float *us); -// -void s_dense_qp_get_us_mask(struct s_dense_qp *qp, float *us); - -// setters - rowmaj -// -void s_dense_qp_set_all_rowmaj(float *H, float *g, float *A, float *b, int *idxb, float *d_lb, float *d_ub, float *C, float *d_lg, float *d_ug, float *Zl, float *Zu, float *zl, float *zu, int *idxs, float *d_ls, float *d_us, struct s_dense_qp *qp); - -// getters - rowmaj -// -void s_dense_qp_get_all_rowmaj(struct s_dense_qp *qp, float *H, float *g, float *A, float *b, int *idxb, float *d_lb, float *d_ub, float *C, float *d_lg, float *d_ug, float *Zl, float *Zu, float *zl, float *zu, int *idxs, float *d_ls, float *d_us); - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_DENSE_QP_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_s_dense_qp_dim.h b/third_party/acados/include/hpipm/include/hpipm_s_dense_qp_dim.h deleted file mode 100644 index b979d24432..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_dense_qp_dim.h +++ /dev/null @@ -1,94 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_DENSE_QP_DIM_H_ -#define HPIPM_S_DENSE_QP_DIM_H_ - -#include "hpipm_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_dense_qp_dim - { - int nv; // number of variables - int ne; // number of equality constraints - int nb; // number of box constraints - int ng; // number of general constraints - int nsb; // number of softened box constraints - int nsg; // number of softened general constraints - int ns; // number of softened constraints (nsb+nsg) - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_dense_qp_dim_memsize(); -// -void s_dense_qp_dim_create(struct s_dense_qp_dim *qp_dim, void *memory); -// -void s_dense_qp_dim_set_all(int nv, int ne, int nb, int ng, int nsb, int nsg, struct s_dense_qp_dim *dim); -// -void s_dense_qp_dim_set(char *fiels_name, int value, struct s_dense_qp_dim *dim); -// -void s_dense_qp_dim_set_nv(int value, struct s_dense_qp_dim *dim); -// -void s_dense_qp_dim_set_ne(int value, struct s_dense_qp_dim *dim); -// -void s_dense_qp_dim_set_nb(int value, struct s_dense_qp_dim *dim); -// -void s_dense_qp_dim_set_ng(int value, struct s_dense_qp_dim *dim); -// -void s_dense_qp_dim_set_nsb(int value, struct s_dense_qp_dim *dim); -// -void s_dense_qp_dim_set_nsg(int value, struct s_dense_qp_dim *dim); -// -void s_dense_qp_dim_set_ns(int value, struct s_dense_qp_dim *dim); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_S_DENSE_QP_DIM_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_dense_qp_ipm.h b/third_party/acados/include/hpipm/include/hpipm_s_dense_qp_ipm.h deleted file mode 100644 index f2d56d4529..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_dense_qp_ipm.h +++ /dev/null @@ -1,260 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_S_DENSE_QP_IPM_H_ -#define HPIPM_S_DENSE_QP_IPM_H_ - - - -#include -#include - -#include -#include -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_dense_qp_ipm_arg - { - float mu0; // initial value for duality measure - float alpha_min; // exit cond on step length - float res_g_max; // exit cond on inf norm of residuals - float res_b_max; // exit cond on inf norm of residuals - float res_d_max; // exit cond on inf norm of residuals - float res_m_max; // exit cond on inf norm of residuals - float reg_prim; // reg of primal hessian - float reg_dual; // reg of dual hessian - float lam_min; // min value in lam vector - float t_min; // min value in t vector - float tau_min; // min value of barrier parameter - int iter_max; // exit cond in iter number - int stat_max; // iterations saved in stat - int pred_corr; // Mehrotra's predictor-corrector IPM algirthm - int cond_pred_corr; // conditional Mehrotra's predictor-corrector - int scale; // scale hessian - int itref_pred_max; // max number of iterative refinement steps for predictor step - int itref_corr_max; // max number of iterative refinement steps for corrector step - int warm_start; // 0 no warm start, 1 warm start primal sol, 2 warm start primal and dual sol - int lq_fact; // 0 syrk+potrf, 1 mix, 2 lq - int abs_form; // absolute IPM formulation - int comp_res_exit; // compute residuals on exit (only for abs_form==1) - int comp_res_pred; // compute residuals of prediction - int kkt_fact_alg; // 0 null-space, 1 schur-complement - int remove_lin_dep_eq; // 0 do not, 1 do check and remove linearly dependent equality constraints - int compute_obj; // compute obj on exit - int split_step; // use different steps for primal and dual variables - int t_lam_min; // clip t and lam: 0 no, 1 in Gamma computation, 2 in solution - int mode; - hpipm_size_t memsize; - }; - - - -struct s_dense_qp_ipm_ws - { - struct s_core_qp_ipm_workspace *core_workspace; - struct s_dense_qp_res_ws *res_ws; - struct s_dense_qp_sol *sol_step; - struct s_dense_qp_sol *sol_itref; - struct s_dense_qp *qp_step; - struct s_dense_qp *qp_itref; - struct s_dense_qp_res *res; - struct s_dense_qp_res *res_itref; - struct s_dense_qp_res *res_step; - struct blasfeo_svec *Gamma; // - struct blasfeo_svec *gamma; // - struct blasfeo_svec *Zs_inv; // - struct blasfeo_smat *Lv; // - struct blasfeo_smat *AL; // - struct blasfeo_smat *Le; // - struct blasfeo_smat *Ctx; // - struct blasfeo_svec *lv; // - struct blasfeo_svec *sv; // scale for Lv - struct blasfeo_svec *se; // scale for Le - struct blasfeo_svec *tmp_nbg; // work space of size nb+ng - struct blasfeo_svec *tmp_ns; // work space of size ns - struct blasfeo_smat *lq0; - struct blasfeo_smat *lq1; - struct blasfeo_svec *tmp_m; - struct blasfeo_smat *A_LQ; - struct blasfeo_smat *A_Q; - struct blasfeo_smat *Zt; - struct blasfeo_smat *ZtH; - struct blasfeo_smat *ZtHZ; - struct blasfeo_svec *xy; - struct blasfeo_svec *Yxy; - struct blasfeo_svec *xz; - struct blasfeo_svec *tmp_nv; - struct blasfeo_svec *tmp_2ns; - struct blasfeo_svec *tmp_nv2ns; - struct blasfeo_smat *A_li; // A of linearly independent equality constraints - struct blasfeo_svec *b_li; // b of linearly independent equality constraints - struct blasfeo_smat *A_bkp; // pointer to backup A - struct blasfeo_svec *b_bkp; // pointer to backup b - struct blasfeo_smat *Ab_LU; - float *stat; // convergence statistics - int *ipiv_v; - int *ipiv_e; - int *ipiv_e1; - void *lq_work0; - void *lq_work1; - void *lq_work_null; - void *orglq_work_null; - int iter; // iteration number - int stat_max; // iterations saved in stat - int stat_m; // numer of recorded stat per ipm iter - int scale; - int use_hess_fact; - int use_A_fact; - int status; - int lq_fact; // cache from arg - int mask_constr; // use constr mask - int ne_li; // number of linearly independent equality constraints - int ne_bkp; // ne backup - hpipm_size_t memsize; // memory size (in bytes) of workspace - }; - - - -// -hpipm_size_t s_dense_qp_ipm_arg_memsize(struct s_dense_qp_dim *qp_dim); -// -void s_dense_qp_ipm_arg_create(struct s_dense_qp_dim *qp_dim, struct s_dense_qp_ipm_arg *arg, void *mem); -// -void s_dense_qp_ipm_arg_set_default(enum hpipm_mode mode, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set(char *field, void *value, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_iter_max(int *iter_max, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_alpha_min(float *alpha_min, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_mu0(float *mu0, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_tol_stat(float *tol_stat, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_tol_eq(float *tol_eq, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_tol_ineq(float *tol_ineq, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_tol_comp(float *tol_comp, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_reg_prim(float *reg, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_reg_dual(float *reg, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_warm_start(int *warm_start, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_pred_corr(int *pred_corr, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_cond_pred_corr(int *cond_pred_corr, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_comp_res_pred(int *comp_res_pred, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_comp_res_exit(int *comp_res_exit, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_lam_min(float *value, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_t_min(float *value, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_tau_min(float *value, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_kkt_fact_alg(int *value, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_remove_lin_dep_eq(int *value, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_compute_obj(int *value, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_split_step(int *value, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_arg_set_t_lam_min(int *value, struct s_dense_qp_ipm_arg *arg); - -// -hpipm_size_t s_dense_qp_ipm_ws_memsize(struct s_dense_qp_dim *qp_dim, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_ipm_ws_create(struct s_dense_qp_dim *qp_dim, struct s_dense_qp_ipm_arg *arg, struct s_dense_qp_ipm_ws *ws, void *mem); -// -void s_dense_qp_ipm_get(char *field, struct s_dense_qp_ipm_ws *ws, void *value); -// -void s_dense_qp_ipm_get_status(struct s_dense_qp_ipm_ws *ws, int *status); -// -void s_dense_qp_ipm_get_iter(struct s_dense_qp_ipm_ws *ws, int *iter); -// -void s_dense_qp_ipm_get_max_res_stat(struct s_dense_qp_ipm_ws *ws, float *res_stat); -// -void s_dense_qp_ipm_get_max_res_eq(struct s_dense_qp_ipm_ws *ws, float *res_eq); -// -void s_dense_qp_ipm_get_max_res_ineq(struct s_dense_qp_ipm_ws *ws, float *res_ineq); -// -void s_dense_qp_ipm_get_max_res_comp(struct s_dense_qp_ipm_ws *ws, float *res_comp); -// -void s_dense_qp_ipm_get_stat(struct s_dense_qp_ipm_ws *ws, float **stat); -// -void s_dense_qp_ipm_get_stat_m(struct s_dense_qp_ipm_ws *ws, int *stat_m); -// -void s_dense_qp_init_var(struct s_dense_qp *qp, struct s_dense_qp_sol *qp_sol, struct s_dense_qp_ipm_arg *arg, struct s_dense_qp_ipm_ws *ws); -// -void s_dense_qp_ipm_abs_step(int kk, struct s_dense_qp *qp, struct s_dense_qp_sol *qp_sol, struct s_dense_qp_ipm_arg *arg, struct s_dense_qp_ipm_ws *ws); -// -void s_dense_qp_ipm_delta_step(int kk, struct s_dense_qp *qp, struct s_dense_qp_sol *qp_sol, struct s_dense_qp_ipm_arg *arg, struct s_dense_qp_ipm_ws *ws); -// -void s_dense_qp_ipm_solve(struct s_dense_qp *qp, struct s_dense_qp_sol *qp_sol, struct s_dense_qp_ipm_arg *arg, struct s_dense_qp_ipm_ws *ws); -// -void s_dense_qp_ipm_predict(struct s_dense_qp *qp, struct s_dense_qp_sol *qp_sol, struct s_dense_qp_ipm_arg *arg, struct s_dense_qp_ipm_ws *ws); -// -void s_dense_qp_ipm_sens(struct s_dense_qp *qp, struct s_dense_qp_sol *qp_sol, struct s_dense_qp_ipm_arg *arg, struct s_dense_qp_ipm_ws *ws); -// -void s_dense_qp_compute_step_length(struct s_dense_qp *qp, struct s_dense_qp_sol *qp_sol, struct s_dense_qp_ipm_arg *arg, struct s_dense_qp_ipm_ws *ws); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_DENSE_QP_IPM_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_s_dense_qp_kkt.h b/third_party/acados/include/hpipm/include/hpipm_s_dense_qp_kkt.h deleted file mode 100644 index 260dc0ab21..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_dense_qp_kkt.h +++ /dev/null @@ -1,72 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_S_DENSE_QP_KKT_H_ -#define HPIPM_S_DENSE_QP_KKT_H_ - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -void s_fact_solve_kkt_unconstr_dense_qp(struct s_dense_qp *qp, struct s_dense_qp_sol *qp_sol, struct s_dense_qp_ipm_arg *arg, struct s_dense_qp_ipm_ws *ws); -// -void s_fact_solve_kkt_step_dense_qp(struct s_dense_qp *qp, struct s_dense_qp_sol *qp_sol, struct s_dense_qp_ipm_arg *arg, struct s_dense_qp_ipm_ws *ws); -// -void s_fact_lq_solve_kkt_step_dense_qp(struct s_dense_qp *qp, struct s_dense_qp_sol *qp_sol, struct s_dense_qp_ipm_arg *arg, struct s_dense_qp_ipm_ws *ws); -// -void s_solve_kkt_step_dense_qp(struct s_dense_qp *qp, struct s_dense_qp_sol *qp_sol, struct s_dense_qp_ipm_arg *arg, struct s_dense_qp_ipm_ws *ws); -// -void s_dense_qp_remove_lin_dep_eq(struct s_dense_qp *qp, struct s_dense_qp_ipm_arg *arg, struct s_dense_qp_ipm_ws *ws); -// -void s_dense_qp_restore_lin_dep_eq(struct s_dense_qp *qp, struct s_dense_qp_ipm_arg *arg, struct s_dense_qp_ipm_ws *ws); -// -void s_dense_qp_compute_obj(struct s_dense_qp *qp, struct s_dense_qp_sol *qp_sol, struct s_dense_qp_ipm_arg *arg, struct s_dense_qp_ipm_ws *ws); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_DENSE_QP_KKT_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_s_dense_qp_res.h b/third_party/acados/include/hpipm/include/hpipm_s_dense_qp_res.h deleted file mode 100644 index 06b609c537..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_dense_qp_res.h +++ /dev/null @@ -1,106 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_DENSE_QP_RES_H_ -#define HPIPM_S_DENSE_QP_RES_H_ - - - -#include -#include - -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_dense_qp_res - { - struct s_dense_qp_dim *dim; - struct blasfeo_svec *res_g; // q-residuals - struct blasfeo_svec *res_b; // b-residuals - struct blasfeo_svec *res_d; // d-residuals - struct blasfeo_svec *res_m; // m-residuals - float res_max[4]; // max of residuals - float res_mu; // mu-residual - hpipm_size_t memsize; - }; - - - -struct s_dense_qp_res_ws - { - struct blasfeo_svec *tmp_nbg; // work space of size nbM+ngM - struct blasfeo_svec *tmp_ns; // work space of size nsM - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_dense_qp_res_memsize(struct s_dense_qp_dim *dim); -// -void s_dense_qp_res_create(struct s_dense_qp_dim *dim, struct s_dense_qp_res *res, void *mem); -// -hpipm_size_t s_dense_qp_res_ws_memsize(struct s_dense_qp_dim *dim); -// -void s_dense_qp_res_ws_create(struct s_dense_qp_dim *dim, struct s_dense_qp_res_ws *workspace, void *mem); -// -void s_dense_qp_res_compute(struct s_dense_qp *qp, struct s_dense_qp_sol *qp_sol, struct s_dense_qp_res *res, struct s_dense_qp_res_ws *ws); -// -void s_dense_qp_res_compute_lin(struct s_dense_qp *qp, struct s_dense_qp_sol *qp_sol, struct s_dense_qp_sol *qp_step, struct s_dense_qp_res *res, struct s_dense_qp_res_ws *ws); -// -void s_dense_qp_res_compute_inf_norm(struct s_dense_qp_res *res); -// -void s_dense_qp_res_get_all(struct s_dense_qp_res *res, float *res_g, float *res_ls, float *res_us, float *res_b, float *res_d_lb, float *res_d_ub, float *res_d_lg, float *res_d_ug, float *res_d_ls, float *res_d_us, float *res_m_lb, float *res_m_ub, float *res_m_lg, float *res_m_ug, float *res_m_ls, float *res_m_us); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - -#endif // HPIPM_D_DENSE_QP_RES_H_ - - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_dense_qp_sol.h b/third_party/acados/include/hpipm/include/hpipm_s_dense_qp_sol.h deleted file mode 100644 index 1f40076378..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_dense_qp_sol.h +++ /dev/null @@ -1,94 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_S_DENSE_QP_SOL_H_ -#define HPIPM_S_DENSE_QP_SOL_H_ - - - -#include -#include - -#include "hpipm_s_dense_qp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_dense_qp_sol - { - struct s_dense_qp_dim *dim; - struct blasfeo_svec *v; - struct blasfeo_svec *pi; - struct blasfeo_svec *lam; - struct blasfeo_svec *t; - void *misc; - float obj; - int valid_obj; - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_dense_qp_sol_memsize(struct s_dense_qp_dim *dim); -// -void s_dense_qp_sol_create(struct s_dense_qp_dim *dim, struct s_dense_qp_sol *qp_sol, void *memory); -// -void s_dense_qp_sol_get_all(struct s_dense_qp_sol *qp_sol, float *v, float *ls, float *us, float *pi, float *lam_lb, float *lam_ub, float *lam_lg, float *lam_ug, float *lam_ls, float *lam_us); -// -void s_dense_qp_sol_get(char *field, struct s_dense_qp_sol *sol, void *value); -// -void s_dense_qp_sol_get_v(struct s_dense_qp_sol *sol, float *v); -// -void s_dense_qp_sol_get_valid_obj(struct s_dense_qp_sol *sol, int *valid_obj); -// -void s_dense_qp_sol_get_obj(struct s_dense_qp_sol *sol, float *obj); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_DENSE_QP_SOL_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_s_dense_qp_utils.h b/third_party/acados/include/hpipm/include/hpipm_s_dense_qp_utils.h deleted file mode 100644 index 3dd93259a5..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_dense_qp_utils.h +++ /dev/null @@ -1,84 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_DENSE_QP_UTILS_H_ -#define HPIPM_S_DENSE_QP_UTILS_H_ - - - -#include -#include - -#include "hpipm_s_dense_qp_dim.h" -#include "hpipm_s_dense_qp.h" -#include "hpipm_s_dense_qp_sol.h" -#include "hpipm_s_dense_qp_ipm.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -void s_dense_qp_dim_print(struct s_dense_qp_dim *qp_dim); -// -//void s_dense_qp_dim_codegen(char *file_name, char *mode, struct s_dense_qp_dim *qp_dim); -// -void s_dense_qp_print(struct s_dense_qp_dim *qp_dim, struct s_dense_qp *qp); -// -//void s_dense_qp_codegen(char *file_name, char *mode, struct s_dense_qp_dim *qp_dim, struct s_dense_qp *qp); -// -void s_dense_qp_sol_print(struct s_dense_qp_dim *qp_dim, struct s_dense_qp_sol *dense_qp_sol); -// -//void s_dense_qp_ipm_arg_codegen(char *file_name, char *mode, struct s_dense_qp_dim *qp_dim, struct s_dense_qp_ipm_arg *arg); -// -void s_dense_qp_res_print(struct s_dense_qp_dim *qp_dim, struct s_dense_qp_res *dense_qp_res); -// -void s_dense_qp_arg_print(struct s_dense_qp_dim *qp_dim, struct s_dense_qp_ipm_arg *qp_ipm_arg); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_S_DENSE_QP_UTILS_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qcqp.h b/third_party/acados/include/hpipm/include/hpipm_s_ocp_qcqp.h deleted file mode 100644 index b90b2ac633..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qcqp.h +++ /dev/null @@ -1,303 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_OCP_QCQP_H_ -#define HPIPM_S_OCP_QCQP_H_ - - - -#include -#include - -#include "hpipm_s_ocp_qcqp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_ocp_qcqp - { - struct s_ocp_qcqp_dim *dim; - struct blasfeo_smat *BAbt; // dynamics matrix & vector work space - struct blasfeo_smat *RSQrq; // hessian of cost & vector work space - struct blasfeo_smat *DCt; // inequality constraints matrix - struct blasfeo_smat **Hq; // hessians of quadratic constraints - struct blasfeo_svec *b; // dynamics vector - struct blasfeo_svec *rqz; // gradient of cost & gradient of slacks - struct blasfeo_svec *d; // inequality constraints vector - struct blasfeo_svec *d_mask; // inequality constraints mask vector - struct blasfeo_svec *m; // rhs of complementarity condition - struct blasfeo_svec *Z; // (diagonal) hessian of slacks - int **idxb; // indices of box constrained variables within [u; x] - int **idxs_rev; // index of soft constraints (reverse storage) - int **Hq_nzero; // for each int, the last 3 bits ...abc, {a,b,c}=0 => {R,S,Q}=0 - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -hpipm_size_t s_ocp_qcqp_strsize(); -// -hpipm_size_t s_ocp_qcqp_memsize(struct s_ocp_qcqp_dim *dim); -// -void s_ocp_qcqp_create(struct s_ocp_qcqp_dim *dim, struct s_ocp_qcqp *qp, void *memory); -// -void s_ocp_qcqp_copy_all(struct s_ocp_qcqp *qp_orig, struct s_ocp_qcqp *qp_dest); - -// setters -// -void s_ocp_qcqp_set_all_zero(struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_rhs_zero(struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set(char *fiels_name, int stage, void *value, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_el(char *fiels_name, int stage, int index, void *value, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_A(int stage, float *mat, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_B(int stage, float *mat, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_b(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_Q(int stage, float *mat, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_S(int stage, float *mat, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_R(int stage, float *mat, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_q(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_r(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_lb(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_lb_mask(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_ub(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_ub_mask(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_lbx(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_lbx_mask(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_el_lbx(int stage, int index, float *elem, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_ubx(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_ubx_mask(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_el_ubx(int stage, int index, float *elem, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_lbu(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_lbu_mask(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_ubu(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_ubu_mask(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_idxb(int stage, int *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_idxbx(int stage, int *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_Jbx(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_idxbu(int stage, int *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_Jbu(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_C(int stage, float *mat, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_D(int stage, float *mat, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_lg(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_lg_mask(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_ug(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_ug_mask(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_Qq(int stage, float *mat, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_Sq(int stage, float *mat, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_Rq(int stage, float *mat, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_qq(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_rq(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_uq(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_uq_mask(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_Zl(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_Zu(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_zl(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_zu(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_lls(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_lls_mask(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_lus(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_lus_mask(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_idxs(int stage, int *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_idxs_rev(int stage, int *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_Jsbu(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_Jsbx(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_Jsg(int stage, float *vec, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_set_Jsq(int stage, float *vec, struct s_ocp_qcqp *qp); - -// getters -// -void s_ocp_qcqp_get(char *field, int stage, struct s_ocp_qcqp *qp, void *value); -// -void s_ocp_qcqp_get_A(int stage, struct s_ocp_qcqp *qp, float *mat); -// -void s_ocp_qcqp_get_B(int stage, struct s_ocp_qcqp *qp, float *mat); -// -void s_ocp_qcqp_get_b(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_Q(int stage, struct s_ocp_qcqp *qp, float *mat); -// -void s_ocp_qcqp_get_S(int stage, struct s_ocp_qcqp *qp, float *mat); -// -void s_ocp_qcqp_get_R(int stage, struct s_ocp_qcqp *qp, float *mat); -// -void s_ocp_qcqp_get_q(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_r(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_ub(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_ub_mask(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_lb(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_lb_mask(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_lbx(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_lbx_mask(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_ubx(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_ubx_mask(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_lbu(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_lbu_mask(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_ubu(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_ubu_mask(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_idxb(int stage, struct s_ocp_qcqp *qp, int *vec); -// -//void s_ocp_qcqp_get_idxbx(int stage, struct s_ocp_qcqp *qp, int *vec); -// -//void s_ocp_qcqp_get_Jbx(int stage, struct s_ocp_qcqp *qp, float *vec); -// -//void s_ocp_qcqp_get_idxbu(int stage, struct s_ocp_qcqp *qp, int *vec); -// -//void s_ocp_qcqp_get_Jbu(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_C(int stage, struct s_ocp_qcqp *qp, float *mat); -// -void s_ocp_qcqp_get_D(int stage, struct s_ocp_qcqp *qp, float *mat); -// -void s_ocp_qcqp_get_lg(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_lg_mask(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_ug(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_ug_mask(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_Zl(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_Zu(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_zl(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_zu(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_lls(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_lls_mask(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_lus(int stage, struct s_ocp_qcqp *qp, float *vec); -// -void s_ocp_qcqp_get_lus_mask(int stage, struct s_ocp_qcqp *qp, float *vec); -// XXX only valid if there is one slack per softed constraint !!! -void s_ocp_qcqp_get_idxs(int stage, struct s_ocp_qcqp *qp, int *vec); -// -void s_ocp_qcqp_get_idxs_rev(int stage, struct s_ocp_qcqp *qp, int *vec); -// -//void s_ocp_qcqp_get_Jsbu(int stage, struct s_ocp_qcqp *qp, float *vec); -// -//void s_ocp_qcqp_get_Jsbx(int stage, struct s_ocp_qcqp *qp, float *vec); -// -//void s_ocp_qcqp_get_Jsg(int stage, struct s_ocp_qcqp *qp, float *vec); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_OCP_QCQP_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qcqp_dim.h b/third_party/acados/include/hpipm/include/hpipm_s_ocp_qcqp_dim.h deleted file mode 100644 index c09903f074..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qcqp_dim.h +++ /dev/null @@ -1,119 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_OCP_QCQP_DIM_H_ -#define HPIPM_S_OCP_QCQP_DIM_H_ - -#include "hpipm_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_ocp_qcqp_dim - { - struct s_ocp_qp_dim *qp_dim; // dim of qp approximation - int *nx; // number of states - int *nu; // number of inputs - int *nb; // number of box constraints - int *nbx; // number of (two-sided) state box constraints - int *nbu; // number of (two-sided) input box constraints - int *ng; // number of (two-sided) general constraints - int *nq; // number of (upper) quadratic constraints - int *ns; // number of soft constraints - int *nsbx; // number of (two-sided) soft state box constraints - int *nsbu; // number of (two-sided) soft input box constraints - int *nsg; // number of (two-sided) soft general constraints - int *nsq; // number of (upper) soft quadratic constraints - int N; // horizon length - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_ocp_qcqp_dim_strsize(); -// -hpipm_size_t s_ocp_qcqp_dim_memsize(int N); -// -void s_ocp_qcqp_dim_create(int N, struct s_ocp_qcqp_dim *qp_dim, void *memory); -// -void s_ocp_qcqp_dim_copy_all(struct s_ocp_qcqp_dim *dim_orig, struct s_ocp_qcqp_dim *dim_dest); -// -void s_ocp_qcqp_dim_set(char *field, int stage, int value, struct s_ocp_qcqp_dim *dim); -// -void s_ocp_qcqp_dim_set_nx(int stage, int value, struct s_ocp_qcqp_dim *dim); -// -void s_ocp_qcqp_dim_set_nu(int stage, int value, struct s_ocp_qcqp_dim *dim); -// -void s_ocp_qcqp_dim_set_nbx(int stage, int value, struct s_ocp_qcqp_dim *dim); -// -void s_ocp_qcqp_dim_set_nbu(int stage, int value, struct s_ocp_qcqp_dim *dim); -// -void s_ocp_qcqp_dim_set_ng(int stage, int value, struct s_ocp_qcqp_dim *dim); -// -void s_ocp_qcqp_dim_set_nq(int stage, int value, struct s_ocp_qcqp_dim *dim); -// -void s_ocp_qcqp_dim_set_ns(int stage, int value, struct s_ocp_qcqp_dim *dim); -// -void s_ocp_qcqp_dim_set_nsbx(int stage, int value, struct s_ocp_qcqp_dim *dim); -// -void s_ocp_qcqp_dim_set_nsbu(int stage, int value, struct s_ocp_qcqp_dim *dim); -// -void s_ocp_qcqp_dim_set_nsg(int stage, int value, struct s_ocp_qcqp_dim *dim); -// -void s_ocp_qcqp_dim_set_nsq(int stage, int value, struct s_ocp_qcqp_dim *dim); -// -void s_ocp_qcqp_dim_get(struct s_ocp_qcqp_dim *dim, char *field, int stage, int *value); -// -void s_ocp_qcqp_dim_get_N(struct s_ocp_qcqp_dim *dim, int *value); -// -void s_ocp_qcqp_dim_get_nx(struct s_ocp_qcqp_dim *dim, int stage, int *value); -// -void s_ocp_qcqp_dim_get_nu(struct s_ocp_qcqp_dim *dim, int stage, int *value); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_S_OCP_QCQP_DIM_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qcqp_ipm.h b/third_party/acados/include/hpipm/include/hpipm_s_ocp_qcqp_ipm.h deleted file mode 100644 index c14fc1c9fd..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qcqp_ipm.h +++ /dev/null @@ -1,191 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_OCP_QCQP_IPM_H_ -#define HPIPM_S_OCP_QCQP_IPM_H_ - - - -#include -#include - -#include -#include -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_ocp_qcqp_ipm_arg - { - struct s_ocp_qp_ipm_arg *qp_arg; - float mu0; // initial value for complementarity slackness - float alpha_min; // exit cond on step length - float res_g_max; // exit cond on inf norm of residuals - float res_b_max; // exit cond on inf norm of residuals - float res_d_max; // exit cond on inf norm of residuals - float res_m_max; // exit cond on inf norm of residuals - float reg_prim; // reg of primal hessian - float lam_min; // min value in lam vector - float t_min; // min value in t vector - int iter_max; // exit cond in iter number - int stat_max; // iterations saved in stat - int pred_corr; // use Mehrotra's predictor-corrector IPM algirthm - int cond_pred_corr; // conditional Mehrotra's predictor-corrector - int itref_pred_max; // max number of iterative refinement steps for predictor step - int itref_corr_max; // max number of iterative refinement steps for corrector step - int warm_start; // 0 no warm start, 1 warm start primal sol, 2 warm start primal and dual sol - int square_root_alg; // 0 classical Riccati, 1 square-root Riccati - int lq_fact; // 0 syrk+potrf, 1 mix, 2 lq (for square_root_alg==1) - int abs_form; // absolute IPM formulation - int comp_dual_sol_eq; // dual solution of equality constraints (only for abs_form==1) - int comp_res_exit; // compute residuals on exit (only for abs_form==1 and comp_dual_sol_eq==1) - int comp_res_pred; // compute residuals of prediction - int split_step; // use different step for primal and dual variables - int t_lam_min; // clip t and lam: 0 no, 1 in Gamma computation, 2 in solution - int mode; - hpipm_size_t memsize; - }; - - - -struct s_ocp_qcqp_ipm_ws - { - struct s_ocp_qp_ipm_ws *qp_ws; - struct s_ocp_qp *qp; - struct s_ocp_qp_sol *qp_sol; - struct s_ocp_qcqp_res_ws *qcqp_res_ws; - struct s_ocp_qcqp_res *qcqp_res; - struct blasfeo_svec *tmp_nuxM; - int iter; // iteration number - int status; - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_ocp_qcqp_ipm_arg_strsize(); -// -hpipm_size_t s_ocp_qcqp_ipm_arg_memsize(struct s_ocp_qcqp_dim *ocp_dim); -// -void s_ocp_qcqp_ipm_arg_create(struct s_ocp_qcqp_dim *ocp_dim, struct s_ocp_qcqp_ipm_arg *arg, void *mem); -// -void s_ocp_qcqp_ipm_arg_set_default(enum hpipm_mode mode, struct s_ocp_qcqp_ipm_arg *arg); -// -void s_ocp_qcqp_ipm_arg_set(char *field, void *value, struct s_ocp_qcqp_ipm_arg *arg); -// set maximum number of iterations -void s_ocp_qcqp_ipm_arg_set_iter_max(int *value, struct s_ocp_qcqp_ipm_arg *arg); -// set minimum step lenght -void s_ocp_qcqp_ipm_arg_set_alpha_min(float *value, struct s_ocp_qcqp_ipm_arg *arg); -// set initial value of barrier parameter -void s_ocp_qcqp_ipm_arg_set_mu0(float *value, struct s_ocp_qcqp_ipm_arg *arg); -// set exit tolerance on stationarity condition -void s_ocp_qcqp_ipm_arg_set_tol_stat(float *value, struct s_ocp_qcqp_ipm_arg *arg); -// set exit tolerance on equality constr -void s_ocp_qcqp_ipm_arg_set_tol_eq(float *value, struct s_ocp_qcqp_ipm_arg *arg); -// set exit tolerance on inequality constr -void s_ocp_qcqp_ipm_arg_set_tol_ineq(float *value, struct s_ocp_qcqp_ipm_arg *arg); -// set exit tolerance on complementarity condition -void s_ocp_qcqp_ipm_arg_set_tol_comp(float *value, struct s_ocp_qcqp_ipm_arg *arg); -// set regularization of primal variables -void s_ocp_qcqp_ipm_arg_set_reg_prim(float *value, struct s_ocp_qcqp_ipm_arg *arg); -// set warm start: 0 no warm start, 1 primal var -void s_ocp_qcqp_ipm_arg_set_warm_start(int *value, struct s_ocp_qcqp_ipm_arg *arg); -// Mehrotra's predictor-corrector IPM algorithm: 0 no predictor-corrector, 1 use predictor-corrector -void s_ocp_qcqp_ipm_arg_set_pred_corr(int *value, struct s_ocp_qcqp_ipm_arg *arg); -// conditional predictor-corrector: 0 no conditinal predictor-corrector, 1 conditional predictor-corrector -void s_ocp_qcqp_ipm_arg_set_cond_pred_corr(int *value, struct s_ocp_qcqp_ipm_arg *arg); -// set riccati algorithm: 0 classic, 1 square-root -void s_ocp_qcqp_ipm_arg_set_ric_alg(int *value, struct s_ocp_qcqp_ipm_arg *arg); -// compute residuals after solution -void s_ocp_qcqp_ipm_arg_set_comp_res_exit(int *value, struct s_ocp_qcqp_ipm_arg *arg); -// compute residuals of prediction -void s_ocp_qcqp_ipm_arg_set_comp_res_pred(int *value, struct s_ocp_qcqp_ipm_arg *arg); -// min value of lam in the solution -void s_ocp_qcqp_ipm_arg_set_lam_min(float *value, struct s_ocp_qcqp_ipm_arg *arg); -// min value of t in the solution -void s_ocp_qcqp_ipm_arg_set_t_min(float *value, struct s_ocp_qcqp_ipm_arg *arg); -// use different step for primal and dual variables -void s_ocp_qcqp_ipm_arg_set_split_step(int *value, struct s_ocp_qcqp_ipm_arg *arg); -// clip t and lam: 0 no, 1 in Gamma computation, 2 in solution -void s_ocp_qcqp_ipm_arg_set_t_lam_min(int *value, struct s_ocp_qcqp_ipm_arg *arg); - -// -hpipm_size_t s_ocp_qcqp_ipm_ws_strsize(); -// -hpipm_size_t s_ocp_qcqp_ipm_ws_memsize(struct s_ocp_qcqp_dim *ocp_dim, struct s_ocp_qcqp_ipm_arg *arg); -// -void s_ocp_qcqp_ipm_ws_create(struct s_ocp_qcqp_dim *ocp_dim, struct s_ocp_qcqp_ipm_arg *arg, struct s_ocp_qcqp_ipm_ws *ws, void *mem); -// -void s_ocp_qcqp_ipm_get(char *field, struct s_ocp_qcqp_ipm_ws *ws, void *value); -// -void s_ocp_qcqp_ipm_get_status(struct s_ocp_qcqp_ipm_ws *ws, int *status); -// -void s_ocp_qcqp_ipm_get_iter(struct s_ocp_qcqp_ipm_ws *ws, int *iter); -// -void s_ocp_qcqp_ipm_get_max_res_stat(struct s_ocp_qcqp_ipm_ws *ws, float *res_stat); -// -void s_ocp_qcqp_ipm_get_max_res_eq(struct s_ocp_qcqp_ipm_ws *ws, float *res_eq); -// -void s_ocp_qcqp_ipm_get_max_res_ineq(struct s_ocp_qcqp_ipm_ws *ws, float *res_ineq); -// -void s_ocp_qcqp_ipm_get_max_res_comp(struct s_ocp_qcqp_ipm_ws *ws, float *res_comp); -// -void s_ocp_qcqp_ipm_get_stat(struct s_ocp_qcqp_ipm_ws *ws, float **stat); -// -void s_ocp_qcqp_ipm_get_stat_m(struct s_ocp_qcqp_ipm_ws *ws, int *stat_m); -// -void s_ocp_qcqp_init_var(struct s_ocp_qcqp *qp, struct s_ocp_qcqp_sol *qp_sol, struct s_ocp_qcqp_ipm_arg *arg, struct s_ocp_qcqp_ipm_ws *ws); -// -void s_ocp_qcqp_ipm_solve(struct s_ocp_qcqp *qp, struct s_ocp_qcqp_sol *qp_sol, struct s_ocp_qcqp_ipm_arg *arg, struct s_ocp_qcqp_ipm_ws *ws); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - -#endif // HPIPM_S_OCP_QCQP_IPM_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qcqp_res.h b/third_party/acados/include/hpipm/include/hpipm_s_ocp_qcqp_res.h deleted file mode 100644 index 1ceeec93b7..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qcqp_res.h +++ /dev/null @@ -1,115 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_OCP_QCQP_RES_H_ -#define HPIPM_S_OCP_QCQP_RES_H_ - - - -#include -#include - -#include -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_ocp_qcqp_res - { - struct s_ocp_qcqp_dim *dim; - struct blasfeo_svec *res_g; // q-residuals - struct blasfeo_svec *res_b; // b-residuals - struct blasfeo_svec *res_d; // d-residuals - struct blasfeo_svec *res_m; // m-residuals - float res_max[4]; // max of residuals - float res_mu; // mu-residual - hpipm_size_t memsize; - }; - - - -struct s_ocp_qcqp_res_ws - { - struct blasfeo_svec *tmp_nuxM; // work space of size nuM+nxM - struct blasfeo_svec *tmp_nbgqM; // work space of size nbM+ngM+nqM - struct blasfeo_svec *tmp_nsM; // work space of size nsM - struct blasfeo_svec *q_fun; // value for evaluation of quadr constr - struct blasfeo_svec *q_adj; // value for adjoint of quadr constr - int use_q_fun; // reuse cached value for evaluation of quadr constr - int use_q_adj; // reuse cached value for adjoint of quadr constr - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_ocp_qcqp_res_memsize(struct s_ocp_qcqp_dim *ocp_dim); -// -void s_ocp_qcqp_res_create(struct s_ocp_qcqp_dim *ocp_dim, struct s_ocp_qcqp_res *res, void *mem); -// -hpipm_size_t s_ocp_qcqp_res_ws_memsize(struct s_ocp_qcqp_dim *ocp_dim); -// -void s_ocp_qcqp_res_ws_create(struct s_ocp_qcqp_dim *ocp_dim, struct s_ocp_qcqp_res_ws *workspace, void *mem); -// -void s_ocp_qcqp_res_compute(struct s_ocp_qcqp *qp, struct s_ocp_qcqp_sol *qp_sol, struct s_ocp_qcqp_res *res, struct s_ocp_qcqp_res_ws *ws); -// -void s_ocp_qcqp_res_compute_inf_norm(struct s_ocp_qcqp_res *res); -// -void s_ocp_qcqp_res_get_max_res_stat(struct s_ocp_qcqp_res *res, float *value); -// -void s_ocp_qcqp_res_get_max_res_eq(struct s_ocp_qcqp_res *res, float *value); -// -void s_ocp_qcqp_res_get_max_res_ineq(struct s_ocp_qcqp_res *res, float *value); -// -void s_ocp_qcqp_res_get_max_res_comp(struct s_ocp_qcqp_res *res, float *value); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - -#endif // HPIPM_S_OCP_QCQP_RES_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qcqp_sol.h b/third_party/acados/include/hpipm/include/hpipm_s_ocp_qcqp_sol.h deleted file mode 100644 index 3d58022cc9..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qcqp_sol.h +++ /dev/null @@ -1,115 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_OCP_QCQP_SOL_H_ -#define HPIPM_S_OCP_QCQP_SOL_H_ - - - -#include -#include - -#include "hpipm_s_ocp_qcqp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_ocp_qcqp_sol - { - struct s_ocp_qcqp_dim *dim; - struct blasfeo_svec *ux; - struct blasfeo_svec *pi; - struct blasfeo_svec *lam; - struct blasfeo_svec *t; - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -hpipm_size_t s_ocp_qcqp_sol_strsize(); -// -hpipm_size_t s_ocp_qcqp_sol_memsize(struct s_ocp_qcqp_dim *dim); -// -void s_ocp_qcqp_sol_create(struct s_ocp_qcqp_dim *dim, struct s_ocp_qcqp_sol *qp_sol, void *memory); -// -void s_ocp_qcqp_sol_copy_all(struct s_ocp_qcqp_sol *qp_sol_orig, struct s_ocp_qcqp_sol *qp_sol_dest); -// -void s_ocp_qcqp_sol_get(char *field, int stage, struct s_ocp_qcqp_sol *qp_sol, float *vec); -// -void s_ocp_qcqp_sol_get_u(int stage, struct s_ocp_qcqp_sol *qp_sol, float *vec); -// -void s_ocp_qcqp_sol_get_x(int stage, struct s_ocp_qcqp_sol *qp_sol, float *vec); -// -void s_ocp_qcqp_sol_get_sl(int stage, struct s_ocp_qcqp_sol *qp_sol, float *vec); -// -void s_ocp_qcqp_sol_get_su(int stage, struct s_ocp_qcqp_sol *qp_sol, float *vec); -// -void s_ocp_qcqp_sol_get_pi(int stage, struct s_ocp_qcqp_sol *qp_sol, float *vec); -// -void s_ocp_qcqp_sol_get_lam_lb(int stage, struct s_ocp_qcqp_sol *qp_sol, float *vec); -// -void s_ocp_qcqp_sol_get_lam_ub(int stage, struct s_ocp_qcqp_sol *qp_sol, float *vec); -// -void s_ocp_qcqp_sol_get_lam_lg(int stage, struct s_ocp_qcqp_sol *qp_sol, float *vec); -// -void s_ocp_qcqp_sol_get_lam_ug(int stage, struct s_ocp_qcqp_sol *qp_sol, float *vec); -// -void s_ocp_qcqp_sol_set(char *field, int stage, float *vec, struct s_ocp_qcqp_sol *qp_sol); -// -void s_ocp_qcqp_sol_set_u(int stage, float *vec, struct s_ocp_qcqp_sol *qp_sol); -// -void s_ocp_qcqp_sol_set_x(int stage, float *vec, struct s_ocp_qcqp_sol *qp_sol); -// -void s_ocp_qcqp_sol_set_sl(int stage, float *vec, struct s_ocp_qcqp_sol *qp_sol); -// -void s_ocp_qcqp_sol_set_su(int stage, float *vec, struct s_ocp_qcqp_sol *qp_sol); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_S_OCP_QCQP_SOL_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qcqp_utils.h b/third_party/acados/include/hpipm/include/hpipm_s_ocp_qcqp_utils.h deleted file mode 100644 index d64e3aabe7..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qcqp_utils.h +++ /dev/null @@ -1,82 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_OCP_QCQP_UTILS_H_ -#define HPIPM_S_OCP_QCQP_UTILS_H_ - - - -#include -#include - -#include "hpipm_s_ocp_qcqp_dim.h" -#include "hpipm_s_ocp_qp.h" -#include "hpipm_s_ocp_qcqp_sol.h" -#include "hpipm_s_ocp_qcqp_ipm.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -void s_ocp_qcqp_dim_print(struct s_ocp_qcqp_dim *qcqp_dim); -// -void s_ocp_qcqp_dim_codegen(char *file_name, char *mode, struct s_ocp_qcqp_dim *qcqp_dim); -// -void s_ocp_qcqp_print(struct s_ocp_qcqp_dim *qcqp_dim, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_codegen(char *file_name, char *mode, struct s_ocp_qcqp_dim *qcqp_dim, struct s_ocp_qcqp *qp); -// -void s_ocp_qcqp_sol_print(struct s_ocp_qcqp_dim *qcqp_dim, struct s_ocp_qcqp_sol *ocp_qcqp_sol); -// -void s_ocp_qcqp_ipm_arg_codegen(char *file_name, char *mode, struct s_ocp_qcqp_dim *qcqp_dim, struct s_ocp_qcqp_ipm_arg *arg); -// -void s_ocp_qcqp_res_print(struct s_ocp_qcqp_dim *qcqp_dim, struct s_ocp_qcqp_res *ocp_qcqp_res); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_S_OCP_QCQP_UTILS_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp.h b/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp.h deleted file mode 100644 index b49191f192..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp.h +++ /dev/null @@ -1,306 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_OCP_QP_H_ -#define HPIPM_S_OCP_QP_H_ - - - -#include -#include - -#include "hpipm_s_ocp_qp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_ocp_qp - { - struct s_ocp_qp_dim *dim; - struct blasfeo_smat *BAbt; // dynamics matrix & vector work space - struct blasfeo_smat *RSQrq; // hessian of cost & vector work space - struct blasfeo_smat *DCt; // inequality constraints matrix - struct blasfeo_svec *b; // dynamics vector - struct blasfeo_svec *rqz; // gradient of cost & gradient of slacks - struct blasfeo_svec *d; // inequality constraints vector - struct blasfeo_svec *d_mask; // inequality constraints mask vector - struct blasfeo_svec *m; // rhs of complementarity condition - struct blasfeo_svec *Z; // (diagonal) hessian of slacks - int **idxb; // indices of box constrained variables within [u; x] - int **idxs_rev; // index of soft constraints (reverse storage) - int **idxe; // indices of constraints within [bu, bx, g] that are equalities, subset of [0, ..., nbu+nbx+ng-1] - int *diag_H_flag; // flag the fact that Hessian is diagonal - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -hpipm_size_t s_ocp_qp_strsize(); -// -hpipm_size_t s_ocp_qp_memsize(struct s_ocp_qp_dim *dim); -// -void s_ocp_qp_create(struct s_ocp_qp_dim *dim, struct s_ocp_qp *qp, void *memory); -// -void s_ocp_qp_copy_all(struct s_ocp_qp *qp_orig, struct s_ocp_qp *qp_dest); - -// setters -// -void s_ocp_qp_set_all_zero(struct s_ocp_qp *qp); -// -void s_ocp_qp_set_rhs_zero(struct s_ocp_qp *qp); -// -void s_ocp_qp_set_all(float **A, float **B, float **b, float **Q, float **S, float **R, float **q, float **r, int **idxbx, float **lbx, float **ubx, int **idxbu, float **lbu, float **ubu, float **C, float **D, float **lg, float **ug, float **Zl, float **Zu, float **zl, float **zu, int **idxs, float **ls, float **us, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_all_rowmaj(float **A, float **B, float **b, float **Q, float **S, float **R, float **q, float **r, int **idxbx, float **lbx, float **ubx, int **idxbu, float **lbu, float **ubu, float **C, float **D, float **lg, float **ug, float **Zl, float **Zu, float **zl, float **zu, int **idxs, float **ls, float **us, struct s_ocp_qp *qp); -// -void s_ocp_qp_set(char *fiels_name, int stage, void *value, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_el(char *fiels_name, int stage, int index, void *value, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_A(int stage, float *mat, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_B(int stage, float *mat, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_b(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_Q(int stage, float *mat, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_S(int stage, float *mat, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_R(int stage, float *mat, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_q(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_r(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_lb(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_lb_mask(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_ub(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_ub_mask(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_lbx(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_lbx_mask(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_el_lbx(int stage, int index, float *elem, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_ubx(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_ubx_mask(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_el_ubx(int stage, int index, float *elem, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_lbu(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_lbu_mask(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_ubu(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_ubu_mask(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_idxb(int stage, int *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_idxbx(int stage, int *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_Jbx(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_idxbu(int stage, int *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_Jbu(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_C(int stage, float *mat, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_D(int stage, float *mat, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_lg(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_lg_mask(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_ug(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_ug_mask(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_Zl(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_Zu(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_zl(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_zu(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_lls(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_lls_mask(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_lus(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_lus_mask(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_idxs(int stage, int *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_idxs_rev(int stage, int *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_Jsbu(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_Jsbx(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_Jsg(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_idxe(int stage, int *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_idxbxe(int stage, int *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_idxbue(int stage, int *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_idxge(int stage, int *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_Jbxe(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_Jbue(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_Jge(int stage, float *vec, struct s_ocp_qp *qp); -// -void s_ocp_qp_set_diag_H_flag(int stage, int *value, struct s_ocp_qp *qp); - -// getters -// -void s_ocp_qp_get(char *field, int stage, struct s_ocp_qp *qp, void *value); -// -void s_ocp_qp_get_A(int stage, struct s_ocp_qp *qp, float *mat); -// -void s_ocp_qp_get_B(int stage, struct s_ocp_qp *qp, float *mat); -// -void s_ocp_qp_get_b(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_Q(int stage, struct s_ocp_qp *qp, float *mat); -// -void s_ocp_qp_get_S(int stage, struct s_ocp_qp *qp, float *mat); -// -void s_ocp_qp_get_R(int stage, struct s_ocp_qp *qp, float *mat); -// -void s_ocp_qp_get_q(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_r(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_ub(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_ub_mask(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_lb(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_lb_mask(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_lbx(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_lbx_mask(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_ubx(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_ubx_mask(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_lbu(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_lbu_mask(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_ubu(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_ubu_mask(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_idxb(int stage, struct s_ocp_qp *qp, int *vec); -// -//void s_ocp_qp_get_idxbx(int stage, struct s_ocp_qp *qp, int *vec); -// -//void s_ocp_qp_get_Jbx(int stage, struct s_ocp_qp *qp, float *vec); -// -//void s_ocp_qp_get_idxbu(int stage, struct s_ocp_qp *qp, int *vec); -// -//void s_ocp_qp_get_Jbu(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_C(int stage, struct s_ocp_qp *qp, float *mat); -// -void s_ocp_qp_get_D(int stage, struct s_ocp_qp *qp, float *mat); -// -void s_ocp_qp_get_lg(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_lg_mask(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_ug(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_ug_mask(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_Zl(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_Zu(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_zl(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_zu(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_lls(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_lls_mask(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_lus(int stage, struct s_ocp_qp *qp, float *vec); -// -void s_ocp_qp_get_lus_mask(int stage, struct s_ocp_qp *qp, float *vec); -// XXX only valid if there is one slack per softed constraint !!! -void s_ocp_qp_get_idxs(int stage, struct s_ocp_qp *qp, int *vec); -// -void s_ocp_qp_get_idxs_rev(int stage, struct s_ocp_qp *qp, int *vec); -// -//void s_ocp_qp_get_Jsbu(int stage, struct s_ocp_qp *qp, float *vec); -// -//void s_ocp_qp_get_Jsbx(int stage, struct s_ocp_qp *qp, float *vec); -// -//void s_ocp_qp_get_Jsg(int stage, struct s_ocp_qp *qp, float *vec); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_OCP_QP_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_dim.h b/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_dim.h deleted file mode 100644 index bce80243b3..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_dim.h +++ /dev/null @@ -1,141 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_OCP_QP_DIM_H_ -#define HPIPM_S_OCP_QP_DIM_H_ - -#include "hpipm_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_ocp_qp_dim - { - int *nx; // number of states - int *nu; // number of inputs - int *nb; // number of box constraints - int *nbx; // number of state box constraints - int *nbu; // number of input box constraints - int *ng; // number of general constraints - int *ns; // number of soft constraints - int *nsbx; // number of soft state box constraints - int *nsbu; // number of soft input box constraints - int *nsg; // number of soft general constraints - int *nbxe; // number of state box constraints which are equality - int *nbue; // number of input box constraints which are equality - int *nge; // number of general constraints which are equality - int N; // horizon length - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_ocp_qp_dim_strsize(); -// -hpipm_size_t s_ocp_qp_dim_memsize(int N); -// -void s_ocp_qp_dim_create(int N, struct s_ocp_qp_dim *qp_dim, void *memory); -// -void s_ocp_qp_dim_copy_all(struct s_ocp_qp_dim *dim_orig, struct s_ocp_qp_dim *dim_dest); -// -void s_ocp_qp_dim_set_all(int *nx, int *nu, int *nbx, int *nbu, int *ng, int *nsbx, int *nsbu, int *nsg, struct s_ocp_qp_dim *dim); -// -void s_ocp_qp_dim_set(char *field, int stage, int value, struct s_ocp_qp_dim *dim); -// -void s_ocp_qp_dim_set_nx(int stage, int value, struct s_ocp_qp_dim *dim); -// -void s_ocp_qp_dim_set_nu(int stage, int value, struct s_ocp_qp_dim *dim); -// -void s_ocp_qp_dim_set_nbx(int stage, int value, struct s_ocp_qp_dim *dim); -// -void s_ocp_qp_dim_set_nbu(int stage, int value, struct s_ocp_qp_dim *dim); -// -void s_ocp_qp_dim_set_ng(int stage, int value, struct s_ocp_qp_dim *dim); -// -void s_ocp_qp_dim_set_ns(int stage, int value, struct s_ocp_qp_dim *dim); -// -void s_ocp_qp_dim_set_nsbx(int stage, int value, struct s_ocp_qp_dim *dim); -// -void s_ocp_qp_dim_set_nsbu(int stage, int value, struct s_ocp_qp_dim *dim); -// -void s_ocp_qp_dim_set_nsg(int stage, int value, struct s_ocp_qp_dim *dim); -// -void s_ocp_qp_dim_set_nbxe(int stage, int value, struct s_ocp_qp_dim *dim); -// -void s_ocp_qp_dim_set_nbue(int stage, int value, struct s_ocp_qp_dim *dim); -// -void s_ocp_qp_dim_set_nge(int stage, int value, struct s_ocp_qp_dim *dim); -// -void s_ocp_qp_dim_get(struct s_ocp_qp_dim *dim, char *field, int stage, int *value); -// -void s_ocp_qp_dim_get_N(struct s_ocp_qp_dim *dim, int *value); -// -void s_ocp_qp_dim_get_nx(struct s_ocp_qp_dim *dim, int stage, int *value); -// -void s_ocp_qp_dim_get_nu(struct s_ocp_qp_dim *dim, int stage, int *value); -// -void s_ocp_qp_dim_get_nbx(struct s_ocp_qp_dim *dim, int stage, int *value); -// -void s_ocp_qp_dim_get_nbu(struct s_ocp_qp_dim *dim, int stage, int *value); -// -void s_ocp_qp_dim_get_ng(struct s_ocp_qp_dim *dim, int stage, int *value); -// -void s_ocp_qp_dim_get_ns(struct s_ocp_qp_dim *dim, int stage, int *value); -// -void s_ocp_qp_dim_get_nsbx(struct s_ocp_qp_dim *dim, int stage, int *value); -// -void s_ocp_qp_dim_get_nsbu(struct s_ocp_qp_dim *dim, int stage, int *value); -// -void s_ocp_qp_dim_get_nsg(struct s_ocp_qp_dim *dim, int stage, int *value); -// -void s_ocp_qp_dim_get_nbxe(struct s_ocp_qp_dim *dim, int stage, int *value); -// -void s_ocp_qp_dim_get_nbue(struct s_ocp_qp_dim *dim, int stage, int *value); -// -void s_ocp_qp_dim_get_nge(struct s_ocp_qp_dim *dim, int stage, int *value); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_S_OCP_QP_DIM_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_ipm.h b/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_ipm.h deleted file mode 100644 index 11f3c47be6..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_ipm.h +++ /dev/null @@ -1,250 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_OCP_QP_IPM_H_ -#define HPIPM_S_OCP_QP_IPM_H_ - - - -#include -#include - -#include -#include -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_ocp_qp_ipm_arg - { - float mu0; // initial value for complementarity slackness - float alpha_min; // exit cond on step length - float res_g_max; // exit cond on inf norm of residuals - float res_b_max; // exit cond on inf norm of residuals - float res_d_max; // exit cond on inf norm of residuals - float res_m_max; // exit cond on inf norm of residuals - float reg_prim; // reg of primal hessian - float lam_min; // min value in lam vector - float t_min; // min value in t vector - float tau_min; // min value of barrier parameter - int iter_max; // exit cond in iter number - int stat_max; // iterations saved in stat - int pred_corr; // use Mehrotra's predictor-corrector IPM algirthm - int cond_pred_corr; // conditional Mehrotra's predictor-corrector - int itref_pred_max; // max number of iterative refinement steps for predictor step - int itref_corr_max; // max number of iterative refinement steps for corrector step - int warm_start; // 0 no warm start, 1 warm start primal sol, 2 warm start primal and dual sol - int square_root_alg; // 0 classical Riccati, 1 square-root Riccati - int lq_fact; // 0 syrk+potrf, 1 mix, 2 lq (for square_root_alg==1) - int abs_form; // absolute IPM formulation - int comp_dual_sol_eq; // dual solution of equality constraints (only for abs_form==1) - int comp_res_exit; // compute residuals on exit (only for abs_form==1 and comp_dual_sol_eq==1) - int comp_res_pred; // compute residuals of prediction - int split_step; // use different steps for primal and dual variables - int var_init_scheme; // variables initialization scheme - int t_lam_min; // clip t and lam: 0 no, 1 in Gamma computation, 2 in solution - int mode; - hpipm_size_t memsize; - }; - - - -struct s_ocp_qp_ipm_ws - { - struct s_core_qp_ipm_workspace *core_workspace; - struct s_ocp_qp_res_ws *res_workspace; - struct s_ocp_qp_dim *dim; // cache dim - struct s_ocp_qp_sol *sol_step; - struct s_ocp_qp_sol *sol_itref; - struct s_ocp_qp *qp_step; - struct s_ocp_qp *qp_itref; - struct s_ocp_qp_res *res; - struct s_ocp_qp_res *res_itref; - struct blasfeo_svec *Gamma; // hessian update - struct blasfeo_svec *gamma; // hessian update - struct blasfeo_svec *tmp_nuxM; // work space of size nxM - struct blasfeo_svec *tmp_nbgM; // work space of size nbM+ngM - struct blasfeo_svec *tmp_nsM; // work space of size nsM - struct blasfeo_svec *Pb; // Pb - struct blasfeo_svec *Zs_inv; - struct blasfeo_svec *tmp_m; - struct blasfeo_svec *l; // cache linear part for _get_ric_xxx - struct blasfeo_smat *L; - struct blasfeo_smat *Ls; - struct blasfeo_smat *P; - struct blasfeo_smat *Lh; - struct blasfeo_smat *AL; - struct blasfeo_smat *lq0; - struct blasfeo_smat *tmp_nxM_nxM; - float *stat; // convergence statistics - int *use_hess_fact; - void *lq_work0; - float qp_res[4]; // infinity norm of residuals - int iter; // iteration number - int stat_max; // iterations saved in stat - int stat_m; // number of recorded stat per IPM iter - int use_Pb; - int status; // solver status - int square_root_alg; // cache from arg - int lq_fact; // cache from arg - int mask_constr; // use constr mask - int valid_ric_vec; // meaningful riccati vectors - int valid_ric_p; // form of riccati p: 0 p*inv(L), 1 p - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_ocp_qp_ipm_arg_strsize(); -// -hpipm_size_t s_ocp_qp_ipm_arg_memsize(struct s_ocp_qp_dim *ocp_dim); -// -void s_ocp_qp_ipm_arg_create(struct s_ocp_qp_dim *ocp_dim, struct s_ocp_qp_ipm_arg *arg, void *mem); -// -void s_ocp_qp_ipm_arg_set_default(enum hpipm_mode mode, struct s_ocp_qp_ipm_arg *arg); -// -void s_ocp_qp_ipm_arg_set(char *field, void *value, struct s_ocp_qp_ipm_arg *arg); -// set maximum number of iterations -void s_ocp_qp_ipm_arg_set_iter_max(int *iter_max, struct s_ocp_qp_ipm_arg *arg); -// set minimum step lenght -void s_ocp_qp_ipm_arg_set_alpha_min(float *alpha_min, struct s_ocp_qp_ipm_arg *arg); -// set initial value of barrier parameter -void s_ocp_qp_ipm_arg_set_mu0(float *mu0, struct s_ocp_qp_ipm_arg *arg); -// set exit tolerance on stationarity condition -void s_ocp_qp_ipm_arg_set_tol_stat(float *tol_stat, struct s_ocp_qp_ipm_arg *arg); -// set exit tolerance on equality constr -void s_ocp_qp_ipm_arg_set_tol_eq(float *tol_eq, struct s_ocp_qp_ipm_arg *arg); -// set exit tolerance on inequality constr -void s_ocp_qp_ipm_arg_set_tol_ineq(float *tol_ineq, struct s_ocp_qp_ipm_arg *arg); -// set exit tolerance on complementarity condition -void s_ocp_qp_ipm_arg_set_tol_comp(float *tol_comp, struct s_ocp_qp_ipm_arg *arg); -// set regularization of primal variables -void s_ocp_qp_ipm_arg_set_reg_prim(float *tol_comp, struct s_ocp_qp_ipm_arg *arg); -// set warm start: 0 no warm start, 1 primal var -void s_ocp_qp_ipm_arg_set_warm_start(int *warm_start, struct s_ocp_qp_ipm_arg *arg); -// Mehrotra's predictor-corrector IPM algorithm: 0 no predictor-corrector, 1 use predictor-corrector -void s_ocp_qp_ipm_arg_set_pred_corr(int *pred_corr, struct s_ocp_qp_ipm_arg *arg); -// conditional predictor-corrector: 0 no conditinal predictor-corrector, 1 conditional predictor-corrector -void s_ocp_qp_ipm_arg_set_cond_pred_corr(int *value, struct s_ocp_qp_ipm_arg *arg); -// set riccati algorithm: 0 classic, 1 square-root -void s_ocp_qp_ipm_arg_set_ric_alg(int *alg, struct s_ocp_qp_ipm_arg *arg); -// dual solution of equality constraints (only for abs_form==1) -void s_ocp_qp_ipm_arg_set_comp_dual_sol_eq(int *value, struct s_ocp_qp_ipm_arg *arg); -// compute residuals after solution -void s_ocp_qp_ipm_arg_set_comp_res_exit(int *value, struct s_ocp_qp_ipm_arg *arg); -// compute residuals of prediction -void s_ocp_qp_ipm_arg_set_comp_res_pred(int *alg, struct s_ocp_qp_ipm_arg *arg); -// min value of lam in the solution -void s_ocp_qp_ipm_arg_set_lam_min(float *value, struct s_ocp_qp_ipm_arg *arg); -// min value of t in the solution -void s_ocp_qp_ipm_arg_set_t_min(float *value, struct s_ocp_qp_ipm_arg *arg); -// min value of tau in the solution -void s_ocp_qp_ipm_arg_set_tau_min(float *value, struct s_ocp_qp_ipm_arg *arg); -// set split step: 0 same step, 1 different step for primal and dual variables -void s_ocp_qp_ipm_arg_set_split_step(int *value, struct s_ocp_qp_ipm_arg *arg); -// variables initialization scheme -void s_ocp_qp_ipm_arg_set_var_init_scheme(int *value, struct s_ocp_qp_ipm_arg *arg); -// clip t and lam: 0 no, 1 in Gamma computation, 2 in solution -void s_ocp_qp_ipm_arg_set_t_lam_min(int *value, struct s_ocp_qp_ipm_arg *arg); - -// -hpipm_size_t s_ocp_qp_ipm_ws_strsize(); -// -hpipm_size_t s_ocp_qp_ipm_ws_memsize(struct s_ocp_qp_dim *ocp_dim, struct s_ocp_qp_ipm_arg *arg); -// -void s_ocp_qp_ipm_ws_create(struct s_ocp_qp_dim *ocp_dim, struct s_ocp_qp_ipm_arg *arg, struct s_ocp_qp_ipm_ws *ws, void *mem); -// -void s_ocp_qp_ipm_get(char *field, struct s_ocp_qp_ipm_ws *ws, void *value); -// -void s_ocp_qp_ipm_get_status(struct s_ocp_qp_ipm_ws *ws, int *status); -// -void s_ocp_qp_ipm_get_iter(struct s_ocp_qp_ipm_ws *ws, int *iter); -// -void s_ocp_qp_ipm_get_max_res_stat(struct s_ocp_qp_ipm_ws *ws, float *res_stat); -// -void s_ocp_qp_ipm_get_max_res_eq(struct s_ocp_qp_ipm_ws *ws, float *res_eq); -// -void s_ocp_qp_ipm_get_max_res_ineq(struct s_ocp_qp_ipm_ws *ws, float *res_ineq); -// -void s_ocp_qp_ipm_get_max_res_comp(struct s_ocp_qp_ipm_ws *ws, float *res_comp); -// -void s_ocp_qp_ipm_get_stat(struct s_ocp_qp_ipm_ws *ws, float **stat); -// -void s_ocp_qp_ipm_get_stat_m(struct s_ocp_qp_ipm_ws *ws, int *stat_m); -// -void s_ocp_qp_ipm_get_ric_Lr(struct s_ocp_qp *qp, struct s_ocp_qp_ipm_arg *arg, struct s_ocp_qp_ipm_ws *ws, int stage, float *Lr); -// -void s_ocp_qp_ipm_get_ric_Ls(struct s_ocp_qp *qp, struct s_ocp_qp_ipm_arg *arg, struct s_ocp_qp_ipm_ws *ws, int stage, float *Ls); -// -void s_ocp_qp_ipm_get_ric_P(struct s_ocp_qp *qp, struct s_ocp_qp_ipm_arg *arg, struct s_ocp_qp_ipm_ws *ws, int stage, float *P); -// -void s_ocp_qp_ipm_get_ric_lr(struct s_ocp_qp *qp, struct s_ocp_qp_ipm_arg *arg, struct s_ocp_qp_ipm_ws *ws, int stage, float *lr); -// -void s_ocp_qp_ipm_get_ric_p(struct s_ocp_qp *qp, struct s_ocp_qp_ipm_arg *arg, struct s_ocp_qp_ipm_ws *ws, int stage, float *p); -// feedback control gain in the form u = K x + k -void s_ocp_qp_ipm_get_ric_K(struct s_ocp_qp *qp, struct s_ocp_qp_ipm_arg *arg, struct s_ocp_qp_ipm_ws *ws, int stage, float *K); -// feedback control gain in the form u = K x + k -void s_ocp_qp_ipm_get_ric_k(struct s_ocp_qp *qp, struct s_ocp_qp_ipm_arg *arg, struct s_ocp_qp_ipm_ws *ws, int stage, float *k); -// -void s_ocp_qp_init_var(struct s_ocp_qp *qp, struct s_ocp_qp_sol *qp_sol, struct s_ocp_qp_ipm_arg *arg, struct s_ocp_qp_ipm_ws *ws); -// -void s_ocp_qp_ipm_abs_step(int kk, struct s_ocp_qp *qp, struct s_ocp_qp_sol *qp_sol, struct s_ocp_qp_ipm_arg *arg, struct s_ocp_qp_ipm_ws *ws); -// -void s_ocp_qp_ipm_delta_step(int kk, struct s_ocp_qp *qp, struct s_ocp_qp_sol *qp_sol, struct s_ocp_qp_ipm_arg *arg, struct s_ocp_qp_ipm_ws *ws); -// -void s_ocp_qp_ipm_solve(struct s_ocp_qp *qp, struct s_ocp_qp_sol *qp_sol, struct s_ocp_qp_ipm_arg *arg, struct s_ocp_qp_ipm_ws *ws); -// -void s_ocp_qp_ipm_predict(struct s_ocp_qp *qp, struct s_ocp_qp_sol *qp_sol, struct s_ocp_qp_ipm_arg *arg, struct s_ocp_qp_ipm_ws *ws); -// -void s_ocp_qp_ipm_sens(struct s_ocp_qp *qp, struct s_ocp_qp_sol *qp_sol, struct s_ocp_qp_ipm_arg *arg, struct s_ocp_qp_ipm_ws *ws); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_OCP_QP_IPM_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_kkt.h b/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_kkt.h deleted file mode 100644 index 3eb1f4aae8..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_kkt.h +++ /dev/null @@ -1,66 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - -#ifndef HPIPM_S_OCP_QP_KKT_H_ -#define HPIPM_S_OCP_QP_KKT_H_ - -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - -// -void s_ocp_qp_fact_solve_kkt_unconstr(struct s_ocp_qp *qp, struct s_ocp_qp_sol *qp_sol, struct s_ocp_qp_ipm_arg *arg, struct s_ocp_qp_ipm_ws *ws); -// -void s_ocp_qp_fact_solve_kkt_step(struct s_ocp_qp *qp, struct s_ocp_qp_sol *qp_sol, struct s_ocp_qp_ipm_arg *arg, struct s_ocp_qp_ipm_ws *ws); -// -void s_ocp_qp_fact_lq_solve_kkt_step(struct s_ocp_qp *qp, struct s_ocp_qp_sol *qp_sol, struct s_ocp_qp_ipm_arg *arg, struct s_ocp_qp_ipm_ws *ws); -// -void s_ocp_qp_solve_kkt_step(struct s_ocp_qp *qp, struct s_ocp_qp_sol *qp_sol, struct s_ocp_qp_ipm_arg *arg, struct s_ocp_qp_ipm_ws *ws); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - -#endif // HPIPM_S_OCP_QP_KKT_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_red.h b/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_red.h deleted file mode 100644 index 5a7b3b0703..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_red.h +++ /dev/null @@ -1,118 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_OCP_QP_RED_H_ -#define HPIPM_S_OCP_QP_RED_H_ - - - -#include -#include - -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_ocp_qp_reduce_eq_dof_arg - { - float lam_min; - float t_min; - int alias_unchanged; // do not keep copy unchanged stage - int comp_prim_sol; // primal solution (v) - int comp_dual_sol_eq; // dual solution equality constr (pi) - int comp_dual_sol_ineq; // dual solution inequality constr (lam t) - hpipm_size_t memsize; // memory size in bytes - }; - - - -struct s_ocp_qp_reduce_eq_dof_ws - { - struct blasfeo_svec *tmp_nuxM; - struct blasfeo_svec *tmp_nbgM; - int *e_imask_ux; - int *e_imask_d; - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -void s_ocp_qp_dim_reduce_eq_dof(struct s_ocp_qp_dim *dim, struct s_ocp_qp_dim *dim_red); -// -hpipm_size_t s_ocp_qp_reduce_eq_dof_arg_memsize(); -// -void s_ocp_qp_reduce_eq_dof_arg_create(struct s_ocp_qp_reduce_eq_dof_arg *arg, void *mem); -// -void s_ocp_qp_reduce_eq_dof_arg_set_default(struct s_ocp_qp_reduce_eq_dof_arg *arg); -// -void s_ocp_qp_reduce_eq_dof_arg_set_alias_unchanged(struct s_ocp_qp_reduce_eq_dof_arg *arg, int value); -// -void s_ocp_qp_reduce_eq_dof_arg_set_comp_prim_sol(struct s_ocp_qp_reduce_eq_dof_arg *arg, int value); -// -void s_ocp_qp_reduce_eq_dof_arg_set_comp_dual_sol_eq(struct s_ocp_qp_reduce_eq_dof_arg *arg, int value); -// -void s_ocp_qp_reduce_eq_dof_arg_set_comp_dual_sol_ineq(struct s_ocp_qp_reduce_eq_dof_arg *arg, int value); -// -hpipm_size_t s_ocp_qp_reduce_eq_dof_ws_memsize(struct s_ocp_qp_dim *dim); -// -void s_ocp_qp_reduce_eq_dof_ws_create(struct s_ocp_qp_dim *dim, struct s_ocp_qp_reduce_eq_dof_ws *work, void *mem); -// -void s_ocp_qp_reduce_eq_dof(struct s_ocp_qp *qp, struct s_ocp_qp *qp_red, struct s_ocp_qp_reduce_eq_dof_arg *arg, struct s_ocp_qp_reduce_eq_dof_ws *work); -// -void s_ocp_qp_reduce_eq_dof_lhs(struct s_ocp_qp *qp, struct s_ocp_qp *qp_red, struct s_ocp_qp_reduce_eq_dof_arg *arg, struct s_ocp_qp_reduce_eq_dof_ws *work); -// -void s_ocp_qp_reduce_eq_dof_rhs(struct s_ocp_qp *qp, struct s_ocp_qp *qp_red, struct s_ocp_qp_reduce_eq_dof_arg *arg, struct s_ocp_qp_reduce_eq_dof_ws *work); -// -void s_ocp_qp_restore_eq_dof(struct s_ocp_qp *qp, struct s_ocp_qp_sol *qp_sol_red, struct s_ocp_qp_sol *qp_sol, struct s_ocp_qp_reduce_eq_dof_arg *arg, struct s_ocp_qp_reduce_eq_dof_ws *work); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_S_OCP_QP_RED_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_res.h b/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_res.h deleted file mode 100644 index 821585da65..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_res.h +++ /dev/null @@ -1,114 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_OCP_QP_RES_H_ -#define HPIPM_S_OCP_QP_RES_H_ - - - -#include -#include - -#include -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_ocp_qp_res - { - struct s_ocp_qp_dim *dim; - struct blasfeo_svec *res_g; // q-residuals - struct blasfeo_svec *res_b; // b-residuals - struct blasfeo_svec *res_d; // d-residuals - struct blasfeo_svec *res_m; // m-residuals - float res_max[4]; // max of residuals - float res_mu; // mu-residual - hpipm_size_t memsize; - }; - - - -struct s_ocp_qp_res_ws - { - struct blasfeo_svec *tmp_nbgM; // work space of size nbM+ngM - struct blasfeo_svec *tmp_nsM; // work space of size nsM - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_ocp_qp_res_memsize(struct s_ocp_qp_dim *ocp_dim); -// -void s_ocp_qp_res_create(struct s_ocp_qp_dim *ocp_dim, struct s_ocp_qp_res *res, void *mem); -// -hpipm_size_t s_ocp_qp_res_ws_memsize(struct s_ocp_qp_dim *ocp_dim); -// -void s_ocp_qp_res_ws_create(struct s_ocp_qp_dim *ocp_dim, struct s_ocp_qp_res_ws *workspace, void *mem); -// -void s_ocp_qp_res_compute(struct s_ocp_qp *qp, struct s_ocp_qp_sol *qp_sol, struct s_ocp_qp_res *res, struct s_ocp_qp_res_ws *ws); -// -void s_ocp_qp_res_compute_lin(struct s_ocp_qp *qp, struct s_ocp_qp_sol *qp_sol, struct s_ocp_qp_sol *qp_step, struct s_ocp_qp_res *res, struct s_ocp_qp_res_ws *ws); -// -void s_ocp_qp_res_compute_inf_norm(struct s_ocp_qp_res *res); -// -void s_ocp_qp_res_get_all(struct s_ocp_qp_res *res, float **res_r, float **res_q, float **res_ls, float **res_us, float **res_b, float **res_d_lb, float **res_d_ub, float **res_d_lg, float **res_d_ug, float **res_d_ls, float **res_d_us, float **res_m_lb, float **res_m_ub, float **res_m_lg, float **res_m_ug, float **res_m_ls, float **res_m_us); -// -void s_ocp_qp_res_get_max_res_stat(struct s_ocp_qp_res *res, float *value); -// -void s_ocp_qp_res_get_max_res_eq(struct s_ocp_qp_res *res, float *value); -// -void s_ocp_qp_res_get_max_res_ineq(struct s_ocp_qp_res *res, float *value); -// -void s_ocp_qp_res_get_max_res_comp(struct s_ocp_qp_res *res, float *value); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - -#endif // HPIPM_S_OCP_QP_RES_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_sol.h b/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_sol.h deleted file mode 100644 index 94dfa0d003..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_sol.h +++ /dev/null @@ -1,128 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_OCP_QP_SOL_H_ -#define HPIPM_S_OCP_QP_SOL_H_ - - - -#include -#include - -#include "hpipm_s_ocp_qp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_ocp_qp_sol - { - struct s_ocp_qp_dim *dim; - struct blasfeo_svec *ux; - struct blasfeo_svec *pi; - struct blasfeo_svec *lam; - struct blasfeo_svec *t; - void *misc; - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -hpipm_size_t s_ocp_qp_sol_strsize(); -// -hpipm_size_t s_ocp_qp_sol_memsize(struct s_ocp_qp_dim *dim); -// -void s_ocp_qp_sol_create(struct s_ocp_qp_dim *dim, struct s_ocp_qp_sol *qp_sol, void *memory); -// -void s_ocp_qp_sol_copy_all(struct s_ocp_qp_sol *qp_sol_orig, struct s_ocp_qp_sol *qp_sol_dest); -// -void s_qp_sol_get_all(struct s_ocp_qp_sol *qp_sol, float **u, float **x, float **ls, float **us, float **pi, float **lam_lb, float **lam_ub, float **lam_lg, float **lam_ug, float **lam_ls, float **lam_us); -// -void s_qp_sol_get_all_rowmaj(struct s_ocp_qp_sol *qp_sol, float **u, float **x, float **ls, float **us, float **pi, float **lam_lb, float **lam_ub, float **lam_lg, float **lam_ug, float **lam_ls, float **lam_us); -// -void s_ocp_qp_sol_set_all(float **u, float **x, float **ls, float **us, float **pi, float **lam_lb, float **lam_ub, float **lam_lg, float **lam_ug, float **lam_ls, float **lam_us, struct s_ocp_qp_sol *qp_sol); -// -void s_ocp_qp_sol_get(char *field, int stage, struct s_ocp_qp_sol *qp_sol, float *vec); -// -void s_ocp_qp_sol_get_u(int stage, struct s_ocp_qp_sol *qp_sol, float *vec); -// -void s_ocp_qp_sol_get_x(int stage, struct s_ocp_qp_sol *qp_sol, float *vec); -// -void s_ocp_qp_sol_get_sl(int stage, struct s_ocp_qp_sol *qp_sol, float *vec); -// -void s_ocp_qp_sol_get_su(int stage, struct s_ocp_qp_sol *qp_sol, float *vec); -// -void s_ocp_qp_sol_get_pi(int stage, struct s_ocp_qp_sol *qp_sol, float *vec); -// -void s_ocp_qp_sol_get_lam_lb(int stage, struct s_ocp_qp_sol *qp_sol, float *vec); -// -void s_ocp_qp_sol_get_lam_lbu(int stage, struct s_ocp_qp_sol *qp_sol, float *vec); -// -void s_ocp_qp_sol_get_lam_lbx(int stage, struct s_ocp_qp_sol *qp_sol, float *vec); -// -void s_ocp_qp_sol_get_lam_ub(int stage, struct s_ocp_qp_sol *qp_sol, float *vec); -// -void s_ocp_qp_sol_get_lam_ubu(int stage, struct s_ocp_qp_sol *qp_sol, float *vec); -// -void s_ocp_qp_sol_get_lam_ubx(int stage, struct s_ocp_qp_sol *qp_sol, float *vec); -// -void s_ocp_qp_sol_get_lam_lg(int stage, struct s_ocp_qp_sol *qp_sol, float *vec); -// -void s_ocp_qp_sol_get_lam_ug(int stage, struct s_ocp_qp_sol *qp_sol, float *vec); -// -void s_ocp_qp_sol_set(char *field, int stage, float *vec, struct s_ocp_qp_sol *qp_sol); -// -void s_ocp_qp_sol_set_u(int stage, float *vec, struct s_ocp_qp_sol *qp_sol); -// -void s_ocp_qp_sol_set_x(int stage, float *vec, struct s_ocp_qp_sol *qp_sol); -// -void s_ocp_qp_sol_set_sl(int stage, float *vec, struct s_ocp_qp_sol *qp_sol); -// -void s_ocp_qp_sol_set_su(int stage, float *vec, struct s_ocp_qp_sol *qp_sol); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_OCP_QP_SOL_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_utils.h b/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_utils.h deleted file mode 100644 index a4f832a5ea..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_ocp_qp_utils.h +++ /dev/null @@ -1,83 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_OCP_QP_UTILS_H_ -#define HPIPM_S_OCP_QP_UTILS_H_ - - - -#include -#include - -#include "hpipm_s_ocp_qp_dim.h" -#include "hpipm_s_ocp_qp.h" -#include "hpipm_s_ocp_qp_sol.h" -#include "hpipm_s_ocp_qp_ipm.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -void s_ocp_qp_dim_print(struct s_ocp_qp_dim *qp_dim); -// -void s_ocp_qp_dim_codegen(char *file_name, char *mode, struct s_ocp_qp_dim *qp_dim); -// -void s_ocp_qp_print(struct s_ocp_qp_dim *qp_dim, struct s_ocp_qp *qp); -// -void s_ocp_qp_codegen(char *file_name, char *mode, struct s_ocp_qp_dim *qp_dim, struct s_ocp_qp *qp); -// -void s_ocp_qp_sol_print(struct s_ocp_qp_dim *qp_dim, struct s_ocp_qp_sol *ocp_qp_sol); -// -void s_ocp_qp_ipm_arg_print(struct s_ocp_qp_dim *qp_dim, struct s_ocp_qp_ipm_arg *arg); -// -void s_ocp_qp_ipm_arg_codegen(char *file_name, char *mode, struct s_ocp_qp_dim *qp_dim, struct s_ocp_qp_ipm_arg *arg); -// -void s_ocp_qp_res_print(struct s_ocp_qp_dim *qp_dim, struct s_ocp_qp_res *ocp_qp_res); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_D_OCP_QP_UTILS_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_part_cond.h b/third_party/acados/include/hpipm/include/hpipm_s_part_cond.h deleted file mode 100644 index e40511e69f..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_part_cond.h +++ /dev/null @@ -1,115 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_S_PART_COND_H_ -#define HPIPM_S_PART_COND_H_ - - - -#include -#include - -#include "hpipm_s_cond.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_part_cond_qp_arg - { - struct s_cond_qp_arg *cond_arg; - int N2; - hpipm_size_t memsize; - }; - - - -struct s_part_cond_qp_ws - { - struct s_cond_qp_ws *cond_workspace; - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_part_cond_qp_arg_memsize(int N2); -// -void s_part_cond_qp_arg_create(int N2, struct s_part_cond_qp_arg *cond_arg, void *mem); -// -void s_part_cond_qp_arg_set_default(struct s_part_cond_qp_arg *cond_arg); -// set riccati-like algorithm: 0 classical, 1 squre-root -void s_part_cond_qp_arg_set_ric_alg(int ric_alg, struct s_part_cond_qp_arg *cond_arg); -// -void s_part_cond_qp_arg_set_comp_prim_sol(int value, struct s_part_cond_qp_arg *cond_arg); -// -void s_part_cond_qp_arg_set_comp_dual_sol_eq(int value, struct s_part_cond_qp_arg *cond_arg); -// -void s_part_cond_qp_arg_set_comp_dual_sol_ineq(int value, struct s_part_cond_qp_arg *cond_arg); - -// -void s_part_cond_qp_compute_block_size(int N, int N2, int *block_size); -// -void s_part_cond_qp_compute_dim(struct s_ocp_qp_dim *ocp_dim, int *block_size, struct s_ocp_qp_dim *part_dense_dim); -// -hpipm_size_t s_part_cond_qp_ws_memsize(struct s_ocp_qp_dim *ocp_dim, int *block_size, struct s_ocp_qp_dim *part_dense_dim, struct s_part_cond_qp_arg *cond_arg); -// -void s_part_cond_qp_ws_create(struct s_ocp_qp_dim *ocp_dim, int *block_size, struct s_ocp_qp_dim *part_dense_dim, struct s_part_cond_qp_arg *cond_arg, struct s_part_cond_qp_ws *cond_ws, void *mem); -// -void s_part_cond_qp_cond(struct s_ocp_qp *ocp_qp, struct s_ocp_qp *part_dense_qp, struct s_part_cond_qp_arg *cond_arg, struct s_part_cond_qp_ws *cond_ws); -// -void s_part_cond_qp_cond_lhs(struct s_ocp_qp *ocp_qp, struct s_ocp_qp *part_dense_qp, struct s_part_cond_qp_arg *cond_arg, struct s_part_cond_qp_ws *cond_ws); -// -void s_part_cond_qp_cond_rhs(struct s_ocp_qp *ocp_qp, struct s_ocp_qp *part_dense_qp, struct s_part_cond_qp_arg *cond_arg, struct s_part_cond_qp_ws *cond_ws); -// -void s_part_cond_qp_expand_sol(struct s_ocp_qp *ocp_qp, struct s_ocp_qp *part_dense_qp, struct s_ocp_qp_sol *part_dense_qp_sol, struct s_ocp_qp_sol *ocp_qp_sol, struct s_part_cond_qp_arg *cond_arg, struct s_part_cond_qp_ws *cond_ws); - -// -void s_part_cond_qp_update(int *idxc, struct s_ocp_qp *ocp_qp, struct s_ocp_qp *part_dense_qp, struct s_part_cond_qp_arg *cond_arg, struct s_part_cond_qp_ws *cond_ws); - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_PART_COND_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_s_part_cond_qcqp.h b/third_party/acados/include/hpipm/include/hpipm_s_part_cond_qcqp.h deleted file mode 100644 index 311f7000bf..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_part_cond_qcqp.h +++ /dev/null @@ -1,107 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_S_PART_COND_QCQP_H_ -#define HPIPM_S_PART_COND_QCQP_H_ - - - -#include -#include - -#include "hpipm_s_cond_qcqp.h" - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_part_cond_qcqp_arg - { - struct s_cond_qcqp_arg *cond_arg; - int N2; - hpipm_size_t memsize; - }; - - - -struct s_part_cond_qcqp_ws - { - struct s_cond_qcqp_ws *cond_ws; - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_part_cond_qcqp_arg_memsize(int N2); -// -void s_part_cond_qcqp_arg_create(int N2, struct s_part_cond_qcqp_arg *cond_arg, void *mem); -// -void s_part_cond_qcqp_arg_set_default(struct s_part_cond_qcqp_arg *cond_arg); -// set riccati-like algorithm: 0 classical, 1 squre-root -void s_part_cond_qcqp_arg_set_ric_alg(int ric_alg, struct s_part_cond_qcqp_arg *cond_arg); - -// -void s_part_cond_qcqp_compute_block_size(int N, int N2, int *block_size); -// -void s_part_cond_qcqp_compute_dim(struct s_ocp_qcqp_dim *ocp_dim, int *block_size, struct s_ocp_qcqp_dim *part_dense_dim); -// -hpipm_size_t s_part_cond_qcqp_ws_memsize(struct s_ocp_qcqp_dim *ocp_dim, int *block_size, struct s_ocp_qcqp_dim *part_dense_dim, struct s_part_cond_qcqp_arg *cond_arg); -// -void s_part_cond_qcqp_ws_create(struct s_ocp_qcqp_dim *ocp_dim, int *block_size, struct s_ocp_qcqp_dim *part_dense_dim, struct s_part_cond_qcqp_arg *cond_arg, struct s_part_cond_qcqp_ws *cond_ws, void *mem); -// -void s_part_cond_qcqp_cond(struct s_ocp_qcqp *ocp_qp, struct s_ocp_qcqp *part_dense_qp, struct s_part_cond_qcqp_arg *cond_arg, struct s_part_cond_qcqp_ws *cond_ws); -// -void s_part_cond_qcqp_cond_lhs(struct s_ocp_qcqp *ocp_qp, struct s_ocp_qcqp *part_dense_qp, struct s_part_cond_qcqp_arg *cond_arg, struct s_part_cond_qcqp_ws *cond_ws); -// -void s_part_cond_qcqp_cond_rhs(struct s_ocp_qcqp *ocp_qp, struct s_ocp_qcqp *part_dense_qp, struct s_part_cond_qcqp_arg *cond_arg, struct s_part_cond_qcqp_ws *cond_ws); -// -void s_part_cond_qcqp_expand_sol(struct s_ocp_qcqp *ocp_qp, struct s_ocp_qcqp *part_dense_qp, struct s_ocp_qcqp_sol *part_dense_qp_sol, struct s_ocp_qcqp_sol *ocp_qp_sol, struct s_part_cond_qcqp_arg *cond_arg, struct s_part_cond_qcqp_ws *cond_ws); - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_D_PART_COND_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_sim_erk.h b/third_party/acados/include/hpipm/include/hpipm_s_sim_erk.h deleted file mode 100644 index 1a05ad1a28..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_sim_erk.h +++ /dev/null @@ -1,121 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_SIM_ERK_H_ -#define HPIPM_S_SIM_ERK_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -struct s_sim_erk_arg - { - struct s_sim_rk_data *rk_data; // integrator data - float h; // step size - int steps; // number of steps -// int for_sens; // compute adjoint sensitivities -// int adj_sens; // compute adjoint sensitivities - hpipm_size_t memsize; - }; - - - -struct s_sim_erk_ws - { - void (*ode)(int t, float *x, float *p, void *ode_args, float *xdot); // function pointer to ode - void (*vde_for)(int t, float *x, float *p, void *ode_args, float *xdot); // function pointer to forward vde - void (*vde_adj)(int t, float *adj_in, void *ode_args, float *adj_out); // function pointer to adjoint vde - void *ode_args; // pointer to ode args - struct s_sim_erk_arg *erk_arg; // erk arg - float *K; // internal variables - float *x_for; // states and forward sensitivities - float *x_traj; // states at all steps - float *l; // adjoint sensitivities - float *p; // parameter - float *x_tmp; // temporary states and forward sensitivities - float *adj_in; - float *adj_tmp; - int nx; // number of states - int np; // number of parameters - int nf; // number of forward sensitivities - int na; // number of adjoint sensitivities - int nf_max; // max number of forward sensitivities - int na_max; // max number of adjoint sensitivities - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_sim_erk_arg_memsize(); -// -void s_sim_erk_arg_create(struct s_sim_erk_arg *erk_arg, void *mem); -// -void s_sim_erk_arg_set_all(struct s_sim_rk_data *rk_data, float h, int steps, struct s_sim_erk_arg *erk_arg); - -// -hpipm_size_t s_sim_erk_ws_memsize(struct s_sim_erk_arg *erk_arg, int nx, int np, int nf_max, int na_max); -// -void s_sim_erk_ws_create(struct s_sim_erk_arg *erk_arg, int nx, int np, int nf_max, int na_max, struct s_sim_erk_ws *work, void *memory); -// -void s_sim_erk_ws_set_all(int nf, int na, float *x, float *fs, float *bs, float *p, void (*ode)(int t, float *x, float *p, void *ode_args, float *xdot), void (*vde_for)(int t, float *x, float *p, void *ode_args, float *xdot), void (*vde_adj)(int t, float *adj_in, void *ode_args, float *adj_out), void *ode_args, struct s_sim_erk_ws *work); -// number of directions for forward sensitivities -void s_sim_erk_ws_set_nf(int *nf, struct s_sim_erk_ws *work); -// parameters (e.g. inputs) -void s_sim_erk_ws_set_p(float *p, struct s_sim_erk_ws *work); -// state -void s_sim_erk_ws_set_x(float *x, struct s_sim_erk_ws *work); -// forward sensitivities -void s_sim_erk_ws_set_fs(float *fs, struct s_sim_erk_ws *work); -// ode funtion -void s_sim_erk_ws_set_ode(void (*ode)(int t, float *x, float *p, void *ode_args, float *xdot), struct s_sim_erk_ws *work); -// forward vde function -void s_sim_erk_ws_set_vde_for(void (*ode)(int t, float *x, float *p, void *ode_args, float *xdot), struct s_sim_erk_ws *work); -// ode_args, passed straight to the ode/vde_for/vde_adj functions -void s_sim_erk_ws_set_ode_args(void *ode_args, struct s_sim_erk_ws *work); -// state -void s_sim_erk_ws_get_x(struct s_sim_erk_ws *work, float *x); -// forward sensitivities -void s_sim_erk_ws_get_fs(struct s_sim_erk_ws *work, float *fs); -// -void s_sim_erk_solve(struct s_sim_erk_arg *arg, struct s_sim_erk_ws *work); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // HPIPM_D_SIM_ERK_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_sim_rk.h b/third_party/acados/include/hpipm/include/hpipm_s_sim_rk.h deleted file mode 100644 index 53acd71498..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_sim_rk.h +++ /dev/null @@ -1,72 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_SIM_RK_H_ -#define HPIPM_S_SIM_RK_H_ - -#include "hpipm_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - -struct s_sim_rk_data - { - float *A_rk; // A in butcher tableau - float *B_rk; // b in butcher tableau - float *C_rk; // c in butcher tableau - int expl; // erk vs irk - int ns; // number of stages - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_sim_rk_data_memsize(int ns); -// -void s_sim_rk_data_create(int ns, struct s_sim_rk_data *rk_data, void *memory); -// -void s_sim_rk_data_init_default(char *field, struct s_sim_rk_data *rk_data); -// -void s_sim_rk_data_set_all(int expl, float *A_rk, float *B_rk, float *C_rk, struct s_sim_rk_data *rk_data); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // HPIPM_S_SIM_RK_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qcqp.h b/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qcqp.h deleted file mode 100644 index 450e992624..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qcqp.h +++ /dev/null @@ -1,213 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_TREE_OCP_QCQP_H_ -#define HPIPM_S_TREE_OCP_QCQP_H_ - - - -#include -#include - -#include "hpipm_s_tree_ocp_qcqp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_tree_ocp_qcqp - { - struct s_tree_ocp_qcqp_dim *dim; - struct blasfeo_smat *BAbt; // Nn-1 - struct blasfeo_smat *RSQrq; // Nn - struct blasfeo_smat *DCt; // Nn - struct blasfeo_smat **Hq; // Nn - struct blasfeo_svec *b; // Nn-1 - struct blasfeo_svec *rqz; // Nn - struct blasfeo_svec *d; // Nn - struct blasfeo_svec *d_mask; // Nn - struct blasfeo_svec *m; // Nn - struct blasfeo_svec *Z; // Nn - int **idxb; // indices of box constrained variables within [u; x] // Nn - int **idxs_rev; // index of soft constraints - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -hpipm_size_t s_tree_ocp_qcqp_memsize(struct s_tree_ocp_qcqp_dim *dim); -// -void s_tree_ocp_qcqp_create(struct s_tree_ocp_qcqp_dim *dim, struct s_tree_ocp_qcqp *qp, void *memory); -// -void s_tree_ocp_qcqp_set_all(float **A, float **B, float **b, float **Q, float **S, float **R, float **q, float **r, int **idxb, float **d_lb, float **d_ub, float **C, float **D, float **d_lg, float **d_ug, float **Zl, float **Zu, float **zl, float **zu, int **idxs, float **d_ls, float **d_us, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set(char *field_name, int node_edge, void *value, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_A(int edge, float *mat, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_B(int edge, float *mat, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_b(int edge, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_Q(int node, float *mat, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_S(int node, float *mat, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_R(int node, float *mat, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_q(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_r(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_lb(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_lb_mask(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_ub(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_ub_mask(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_lbx(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_lbx_mask(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_ubx(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_ubx_mask(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_lbu(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_lbu_mask(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_ubu(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_ubu_mask(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_idxb(int node, int *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_idxbx(int node, int *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_Jbx(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_idxbu(int node, int *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_Jbu(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_C(int node, float *mat, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_D(int node, float *mat, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_lg(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_lg_mask(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_ug(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_ug_mask(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_Qq(int node, float *mat, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_Sq(int node, float *mat, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_Rq(int node, float *mat, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_qq(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_rq(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_uq(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_uq_mask(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_Zl(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_Zu(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_zl(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_zu(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_lls(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_lls_mask(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_lus(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_lus_mask(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_idxs(int node, int *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_idxs_rev(int node, int *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_Jsbu(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_Jsbx(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_Jsg(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_set_Jsq(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -//void s_tree_ocp_qcqp_set_idxe(int node, int *vec, struct s_tree_ocp_qcqp *qp); -// -//void s_tree_ocp_qcqp_set_idxbxe(int node, int *vec, struct s_tree_ocp_qcqp *qp); -// -//void s_tree_ocp_qcqp_set_idxbue(int node, int *vec, struct s_tree_ocp_qcqp *qp); -// -//void s_tree_ocp_qcqp_set_idxge(int node, int *vec, struct s_tree_ocp_qcqp *qp); -// -//void s_tree_ocp_qcqp_set_Jbxe(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -//void s_tree_ocp_qcqp_set_Jbue(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -//void s_tree_ocp_qcqp_set_Jge(int node, float *vec, struct s_tree_ocp_qcqp *qp); -// -//void s_tree_ocp_qcqp_set_diag_H_flag(int node, int *value, struct s_tree_ocp_qcqp *qp); - - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_TREE_OCP_QCQP_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qcqp_dim.h b/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qcqp_dim.h deleted file mode 100644 index 7a49d51995..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qcqp_dim.h +++ /dev/null @@ -1,118 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_TREE_OCP_QCQP_DIM_H_ -#define HPIPM_S_TREE_OCP_QCQP_DIM_H_ - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_tree_ocp_qcqp_dim - { - struct s_tree_ocp_qp_dim *qp_dim; // dim of qp approximation - struct tree *ttree; // tree describing node conndection - int *nx; // number of states // Nn - int *nu; // number of inputs // Nn - int *nb; // number of box constraints // Nn - int *nbx; // number of state box constraints // Nn - int *nbu; // number of input box constraints // Nn - int *ng; // number of general constraints // Nn - int *nq; // number of (upper) quadratic constraints - int *ns; // number of soft constraints // Nn - int *nsbx; // number of soft state box constraints - int *nsbu; // number of soft input box constraints - int *nsg; // number of soft general constraints - int *nsq; // number of (upper) soft quadratic constraints - int Nn; // number of nodes - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_tree_ocp_qcqp_dim_strsize(); -// -hpipm_size_t s_tree_ocp_qcqp_dim_memsize(int Nn); -// -void s_tree_ocp_qcqp_dim_create(int Nn, struct s_tree_ocp_qcqp_dim *qp_dim, void *memory); -// -void s_tree_ocp_qcqp_dim_set_tree(struct tree *ttree, struct s_tree_ocp_qcqp_dim *dim); -// -void s_tree_ocp_qcqp_dim_set(char *field, int stage, int value, struct s_tree_ocp_qcqp_dim *dim); -// -void s_tree_ocp_qcqp_dim_set_nx(int stage, int value, struct s_tree_ocp_qcqp_dim *dim); -// -void s_tree_ocp_qcqp_dim_set_nu(int stage, int value, struct s_tree_ocp_qcqp_dim *dim); -// -void s_tree_ocp_qcqp_dim_set_nbx(int stage, int value, struct s_tree_ocp_qcqp_dim *dim); -// -void s_tree_ocp_qcqp_dim_set_nbu(int stage, int value, struct s_tree_ocp_qcqp_dim *dim); -// -void s_tree_ocp_qcqp_dim_set_ng(int stage, int value, struct s_tree_ocp_qcqp_dim *dim); -// -void s_tree_ocp_qcqp_dim_set_nq(int stage, int value, struct s_tree_ocp_qcqp_dim *dim); -// -void s_tree_ocp_qcqp_dim_set_ns(int stage, int value, struct s_tree_ocp_qcqp_dim *dim); -// -void s_tree_ocp_qcqp_dim_set_nsbx(int stage, int value, struct s_tree_ocp_qcqp_dim *dim); -// -void s_tree_ocp_qcqp_dim_set_nsbu(int stage, int value, struct s_tree_ocp_qcqp_dim *dim); -// -void s_tree_ocp_qcqp_dim_set_nsg(int stage, int value, struct s_tree_ocp_qcqp_dim *dim); -// -void s_tree_ocp_qcqp_dim_set_nsq(int stage, int value, struct s_tree_ocp_qcqp_dim *dim); -// -//void s_tree_ocp_qcqp_dim_set_nbxe(int stage, int value, struct s_tree_ocp_qcqp_dim *dim); -// -//void s_tree_ocp_qcqp_dim_set_nbue(int stage, int value, struct s_tree_ocp_qcqp_dim *dim); -// -//void s_tree_ocp_qcqp_dim_set_nge(int stage, int value, struct s_tree_ocp_qcqp_dim *dim); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_S_TREE_OCP_QCQP_DIM_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qcqp_ipm.h b/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qcqp_ipm.h deleted file mode 100644 index 69d65914c5..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qcqp_ipm.h +++ /dev/null @@ -1,192 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_TREE_OCP_QCQP_IPM_H_ -#define HPIPM_S_TREE_OCP_QCQP_IPM_H_ - - - -#include -#include - -#include -#include -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_tree_ocp_qcqp_ipm_arg - { - struct s_tree_ocp_qp_ipm_arg *qp_arg; - float mu0; // initial value for complementarity slackness - float alpha_min; // exit cond on step length - float res_g_max; // exit cond on inf norm of residuals - float res_b_max; // exit cond on inf norm of residuals - float res_d_max; // exit cond on inf norm of residuals - float res_m_max; // exit cond on inf norm of residuals - float reg_prim; // reg of primal hessian - float lam_min; // min value in lam vector - float t_min; // min value in t vector - int iter_max; // exit cond in iter number - int stat_max; // iterations saved in stat - int pred_corr; // use Mehrotra's predictor-corrector IPM algirthm - int cond_pred_corr; // conditional Mehrotra's predictor-corrector - int itref_pred_max; // max number of iterative refinement steps for predictor step - int itref_corr_max; // max number of iterative refinement steps for corrector step - int warm_start; // 0 no warm start, 1 warm start primal sol, 2 warm start primal and dual sol -// int square_root_alg; // 0 classical Riccati, 1 square-root Riccati - int lq_fact; // 0 syrk+potrf, 1 mix, 2 lq (for square_root_alg==1) - int abs_form; // absolute IPM formulation - int comp_dual_sol_eq; // dual solution of equality constraints (only for abs_form==1) - int comp_res_exit; // compute residuals on exit (only for abs_form==1 and comp_dual_sol_eq==1) -// int comp_res_pred; // compute residuals of prediction - int split_step; // use different step for primal and dual variables - int t_lam_min; // clip t and lam: 0 no, 1 in Gamma computation, 2 in solution - int mode; - hpipm_size_t memsize; - }; - - - -struct s_tree_ocp_qcqp_ipm_ws - { - struct s_tree_ocp_qp_ipm_ws *qp_ws; - struct s_tree_ocp_qp *qp; - struct s_tree_ocp_qp_sol *qp_sol; - struct s_tree_ocp_qcqp_res_ws *qcqp_res_ws; - struct s_tree_ocp_qcqp_res *qcqp_res; - struct blasfeo_svec *tmp_nuxM; - int iter; // iteration number - int status; - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_tree_ocp_qcqp_ipm_arg_strsize(); -// -hpipm_size_t s_tree_ocp_qcqp_ipm_arg_memsize(struct s_tree_ocp_qcqp_dim *ocp_dim); -// -void s_tree_ocp_qcqp_ipm_arg_create(struct s_tree_ocp_qcqp_dim *ocp_dim, struct s_tree_ocp_qcqp_ipm_arg *arg, void *mem); -// -void s_tree_ocp_qcqp_ipm_arg_set_default(enum hpipm_mode mode, struct s_tree_ocp_qcqp_ipm_arg *arg); -// -void s_tree_ocp_qcqp_ipm_arg_set(char *field, void *value, struct s_tree_ocp_qcqp_ipm_arg *arg); -// set maximum number of iterations -void s_tree_ocp_qcqp_ipm_arg_set_iter_max(int *value, struct s_tree_ocp_qcqp_ipm_arg *arg); -// set minimum step lenght -void s_tree_ocp_qcqp_ipm_arg_set_alpha_min(float *value, struct s_tree_ocp_qcqp_ipm_arg *arg); -// set initial value of barrier parameter -void s_tree_ocp_qcqp_ipm_arg_set_mu0(float *value, struct s_tree_ocp_qcqp_ipm_arg *arg); -// set exit tolerance on stationarity condition -void s_tree_ocp_qcqp_ipm_arg_set_tol_stat(float *value, struct s_tree_ocp_qcqp_ipm_arg *arg); -// set exit tolerance on equality constr -void s_tree_ocp_qcqp_ipm_arg_set_tol_eq(float *value, struct s_tree_ocp_qcqp_ipm_arg *arg); -// set exit tolerance on inequality constr -void s_tree_ocp_qcqp_ipm_arg_set_tol_ineq(float *value, struct s_tree_ocp_qcqp_ipm_arg *arg); -// set exit tolerance on complementarity condition -void s_tree_ocp_qcqp_ipm_arg_set_tol_comp(float *value, struct s_tree_ocp_qcqp_ipm_arg *arg); -// set regularization of primal variables -void s_tree_ocp_qcqp_ipm_arg_set_reg_prim(float *value, struct s_tree_ocp_qcqp_ipm_arg *arg); -// set warm start: 0 no warm start, 1 primal var -void s_tree_ocp_qcqp_ipm_arg_set_warm_start(int *value, struct s_tree_ocp_qcqp_ipm_arg *arg); -// Mehrotra's predictor-corrector IPM algorithm: 0 no predictor-corrector, 1 use predictor-corrector -void s_tree_ocp_qcqp_ipm_arg_set_pred_corr(int *value, struct s_tree_ocp_qcqp_ipm_arg *arg); -// conditional predictor-corrector: 0 no conditinal predictor-corrector, 1 conditional predictor-corrector -void s_tree_ocp_qcqp_ipm_arg_set_cond_pred_corr(int *value, struct s_tree_ocp_qcqp_ipm_arg *arg); -// set riccati algorithm: 0 classic, 1 square-root -//void s_tree_ocp_qcqp_ipm_arg_set_ric_alg(int *value, struct s_tree_ocp_qcqp_ipm_arg *arg); -// compute residuals after solution -void s_tree_ocp_qcqp_ipm_arg_set_comp_res_exit(int *value, struct s_tree_ocp_qcqp_ipm_arg *arg); -// compute residuals of prediction -//void s_tree_ocp_qcqp_ipm_arg_set_comp_res_pred(int *value, struct s_tree_ocp_qcqp_ipm_arg *arg); -// min value of lam in the solution -void s_tree_ocp_qcqp_ipm_arg_set_lam_min(float *value, struct s_tree_ocp_qcqp_ipm_arg *arg); -// min value of t in the solution -void s_tree_ocp_qcqp_ipm_arg_set_t_min(float *value, struct s_tree_ocp_qcqp_ipm_arg *arg); -// use different step for primal and dual variables -void s_tree_ocp_qcqp_ipm_arg_set_split_step(int *value, struct s_tree_ocp_qcqp_ipm_arg *arg); -// clip t and lam: 0 no, 1 in Gamma computation, 2 in solution -void s_tree_ocp_qcqp_ipm_arg_set_t_lam_min(int *value, struct s_tree_ocp_qcqp_ipm_arg *arg); - -// -hpipm_size_t s_tree_ocp_qcqp_ipm_ws_strsize(); -// -hpipm_size_t s_tree_ocp_qcqp_ipm_ws_memsize(struct s_tree_ocp_qcqp_dim *ocp_dim, struct s_tree_ocp_qcqp_ipm_arg *arg); -// -void s_tree_ocp_qcqp_ipm_ws_create(struct s_tree_ocp_qcqp_dim *ocp_dim, struct s_tree_ocp_qcqp_ipm_arg *arg, struct s_tree_ocp_qcqp_ipm_ws *ws, void *mem); -// -void s_tree_ocp_qcqp_ipm_get(char *field, struct s_tree_ocp_qcqp_ipm_ws *ws, void *value); -// -void s_tree_ocp_qcqp_ipm_get_status(struct s_tree_ocp_qcqp_ipm_ws *ws, int *status); -// -void s_tree_ocp_qcqp_ipm_get_iter(struct s_tree_ocp_qcqp_ipm_ws *ws, int *iter); -// -void s_tree_ocp_qcqp_ipm_get_max_res_stat(struct s_tree_ocp_qcqp_ipm_ws *ws, float *res_stat); -// -void s_tree_ocp_qcqp_ipm_get_max_res_eq(struct s_tree_ocp_qcqp_ipm_ws *ws, float *res_eq); -// -void s_tree_ocp_qcqp_ipm_get_max_res_ineq(struct s_tree_ocp_qcqp_ipm_ws *ws, float *res_ineq); -// -void s_tree_ocp_qcqp_ipm_get_max_res_comp(struct s_tree_ocp_qcqp_ipm_ws *ws, float *res_comp); -// -void s_tree_ocp_qcqp_ipm_get_stat(struct s_tree_ocp_qcqp_ipm_ws *ws, float **stat); -// -void s_tree_ocp_qcqp_ipm_get_stat_m(struct s_tree_ocp_qcqp_ipm_ws *ws, int *stat_m); -// -void s_tree_ocp_qcqp_init_var(struct s_tree_ocp_qcqp *qp, struct s_tree_ocp_qcqp_sol *qp_sol, struct s_tree_ocp_qcqp_ipm_arg *arg, struct s_tree_ocp_qcqp_ipm_ws *ws); -// -void s_tree_ocp_qcqp_ipm_solve(struct s_tree_ocp_qcqp *qp, struct s_tree_ocp_qcqp_sol *qp_sol, struct s_tree_ocp_qcqp_ipm_arg *arg, struct s_tree_ocp_qcqp_ipm_ws *ws); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - -#endif // HPIPM_S_TREE_OCP_QCQP_IPM_H_ - - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qcqp_res.h b/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qcqp_res.h deleted file mode 100644 index d0d84a6f23..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qcqp_res.h +++ /dev/null @@ -1,109 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_TREE_OCP_QCQP_RES_H_ -#define HPIPM_S_TREE_OCP_QCQP_RES_H_ - - - -#include -#include - -#include -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_tree_ocp_qcqp_res - { - struct s_tree_ocp_qcqp_dim *dim; - struct blasfeo_svec *res_g; // q-residuals - struct blasfeo_svec *res_b; // b-residuals - struct blasfeo_svec *res_d; // d-residuals - struct blasfeo_svec *res_m; // m-residuals - float res_max[4]; // max of residuals - float res_mu; // mu-residual - hpipm_size_t memsize; - }; - - - -struct s_tree_ocp_qcqp_res_ws - { - struct blasfeo_svec *tmp_nuxM; // work space of size nuM+nxM - struct blasfeo_svec *tmp_nbgqM; // work space of size nbM+ngM+nqM - struct blasfeo_svec *tmp_nsM; // work space of size nsM - struct blasfeo_svec *q_fun; // value for evaluation of quadr constr - struct blasfeo_svec *q_adj; // value for adjoint of quadr constr - int use_q_fun; // reuse cached value for evaluation of quadr constr - int use_q_adj; // reuse cached value for adjoint of quadr constr - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_tree_ocp_qcqp_res_memsize(struct s_tree_ocp_qcqp_dim *ocp_dim); -// -void s_tree_ocp_qcqp_res_create(struct s_tree_ocp_qcqp_dim *ocp_dim, struct s_tree_ocp_qcqp_res *res, void *mem); -// -hpipm_size_t s_tree_ocp_qcqp_res_ws_memsize(struct s_tree_ocp_qcqp_dim *ocp_dim); -// -void s_tree_ocp_qcqp_res_ws_create(struct s_tree_ocp_qcqp_dim *ocp_dim, struct s_tree_ocp_qcqp_res_ws *ws, void *mem); -// -void s_tree_ocp_qcqp_res_compute(struct s_tree_ocp_qcqp *qp, struct s_tree_ocp_qcqp_sol *qp_sol, struct s_tree_ocp_qcqp_res *res, struct s_tree_ocp_qcqp_res_ws *ws); -// -void s_tree_ocp_qcqp_res_compute_inf_norm(struct s_tree_ocp_qcqp_res *res); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - -#endif // HPIPM_S_TREE_OCP_QCQP_RES_H_ - - - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qcqp_sol.h b/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qcqp_sol.h deleted file mode 100644 index 47f038c6b3..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qcqp_sol.h +++ /dev/null @@ -1,97 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_TREE_OCP_QCQP_SOL_H_ -#define HPIPM_S_TREE_OCP_QCQP_SOL_H_ - - - -#include -#include - -#include "hpipm_s_tree_ocp_qcqp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - -struct s_tree_ocp_qcqp_sol - { - struct s_tree_ocp_qcqp_dim *dim; - struct blasfeo_svec *ux; - struct blasfeo_svec *pi; - struct blasfeo_svec *lam; - struct blasfeo_svec *t; - void *misc; - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -hpipm_size_t s_tree_ocp_qcqp_sol_memsize(struct s_tree_ocp_qcqp_dim *dim); -// -void s_tree_ocp_qcqp_sol_create(struct s_tree_ocp_qcqp_dim *dim, struct s_tree_ocp_qcqp_sol *qp_sol, void *memory); -// -void s_tree_ocp_qcqp_sol_get_u(int node, struct s_tree_ocp_qcqp_sol *qp_sol, float *vec); -// -void s_tree_ocp_qcqp_sol_get_x(int node, struct s_tree_ocp_qcqp_sol *qp_sol, float *vec); -// -void s_tree_ocp_qcqp_sol_get_sl(int node, struct s_tree_ocp_qcqp_sol *qp_sol, float *vec); -// -void s_tree_ocp_qcqp_sol_get_su(int node, struct s_tree_ocp_qcqp_sol *qp_sol, float *vec); -// -void s_tree_ocp_qcqp_sol_get_pi(int edge, struct s_tree_ocp_qcqp_sol *qp_sol, float *vec); -// -void s_tree_ocp_qcqp_sol_get_lam_lb(int node, struct s_tree_ocp_qcqp_sol *qp_sol, float *vec); -// -void s_tree_ocp_qcqp_sol_get_lam_ub(int node, struct s_tree_ocp_qcqp_sol *qp_sol, float *vec); -// -void s_tree_ocp_qcqp_sol_get_lam_lg(int node, struct s_tree_ocp_qcqp_sol *qp_sol, float *vec); -// -void s_tree_ocp_qcqp_sol_get_lam_ug(int node, struct s_tree_ocp_qcqp_sol *qp_sol, float *vec); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_TREE_OCP_QCQP_SOL_H_ - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qcqp_utils.h b/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qcqp_utils.h deleted file mode 100644 index 79528de1ce..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qcqp_utils.h +++ /dev/null @@ -1,85 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_TREE_OCP_QCQP_UTILS_H_ -#define HPIPM_S_TREE_OCP_QCQP_UTILS_H_ - - - -#include -#include - -#include "hpipm_s_tree_ocp_qcqp_dim.h" -#include "hpipm_s_tree_ocp_qcqp.h" -#include "hpipm_s_tree_ocp_qcqp_sol.h" -#include "hpipm_s_tree_ocp_qcqp_ipm.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -void s_tree_ocp_qcqp_dim_print(struct s_tree_ocp_qcqp_dim *qp_dim); -// -//void s_tree_ocp_qcqp_dim_codegen(char *file_name, char *mode, struct s_tree_ocp_qcqp_dim *qp_dim); -// -void s_tree_ocp_qcqp_print(struct s_tree_ocp_qcqp_dim *qp_dim, struct s_tree_ocp_qcqp *qp); -// -//void s_tree_ocp_qcqp_codegen(char *file_name, char *mode, struct s_tree_ocp_qcqp_dim *qp_dim, struct s_tree_ocp_qcqp *qp); -// -void s_tree_ocp_qcqp_sol_print(struct s_tree_ocp_qcqp_dim *qp_dim, struct s_tree_ocp_qcqp_sol *ocp_qcqp_sol); -// -void s_tree_ocp_qcqp_ipm_arg_print(struct s_tree_ocp_qcqp_dim *qp_dim, struct s_tree_ocp_qcqp_ipm_arg *arg); -// -//void s_tree_ocp_qcqp_ipm_arg_codegen(char *file_name, char *mode, struct s_tree_ocp_qcqp_dim *qp_dim, struct s_tree_ocp_qcqp_ipm_arg *arg); -// -void s_tree_ocp_qcqp_res_print(struct s_tree_ocp_qcqp_dim *qp_dim, struct s_tree_ocp_qcqp_res *ocp_qcqp_res); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_S_TREE_OCP_QCQP_UTILS_H_ - - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp.h b/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp.h deleted file mode 100644 index 722b930b9a..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp.h +++ /dev/null @@ -1,196 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_TREE_OCP_QP_H_ -#define HPIPM_S_TREE_OCP_QP_H_ - - - -#include -#include - -#include "hpipm_s_tree_ocp_qp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_tree_ocp_qp - { - struct s_tree_ocp_qp_dim *dim; - struct blasfeo_smat *BAbt; // Nn-1 - struct blasfeo_smat *RSQrq; // Nn - struct blasfeo_smat *DCt; // Nn - struct blasfeo_svec *b; // Nn-1 - struct blasfeo_svec *rqz; // Nn - struct blasfeo_svec *d; // Nn - struct blasfeo_svec *d_mask; // Nn - struct blasfeo_svec *m; // Nn - struct blasfeo_svec *Z; // Nn - int **idxb; // indices of box constrained variables within [u; x] // Nn -// int **idxs; // index of soft constraints - int **idxs_rev; // index of soft constraints - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -hpipm_size_t s_tree_ocp_qp_memsize(struct s_tree_ocp_qp_dim *dim); -// -void s_tree_ocp_qp_create(struct s_tree_ocp_qp_dim *dim, struct s_tree_ocp_qp *qp, void *memory); -// -void s_tree_ocp_qp_set_all(float **A, float **B, float **b, float **Q, float **S, float **R, float **q, float **r, int **idxb, float **d_lb, float **d_ub, float **C, float **D, float **d_lg, float **d_ug, float **Zl, float **Zu, float **zl, float **zu, int **idxs, float **d_ls, float **d_us, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set(char *field_name, int node_edge, void *value, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_A(int edge, float *mat, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_B(int edge, float *mat, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_b(int edge, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_Q(int node, float *mat, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_S(int node, float *mat, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_R(int node, float *mat, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_q(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_r(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_lb(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_lb_mask(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_ub(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_ub_mask(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_lbx(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_lbx_mask(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_ubx(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_ubx_mask(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_lbu(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_lbu_mask(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_ubu(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_ubu_mask(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_idxb(int node, int *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_idxbx(int node, int *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_Jbx(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_idxbu(int node, int *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_Jbu(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_C(int node, float *mat, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_D(int node, float *mat, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_lg(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_lg_mask(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_ug(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_ug_mask(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_Zl(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_Zu(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_zl(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_zu(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_lls(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_lls_mask(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_lus(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_lus_mask(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_idxs(int node, int *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_idxs_rev(int node, int *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_Jsbu(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_Jsbx(int node, float *vec, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_set_Jsg(int node, float *vec, struct s_tree_ocp_qp *qp); -// -//void s_tree_ocp_qp_set_idxe(int node, int *vec, struct s_tree_ocp_qp *qp); -// -//void s_tree_ocp_qp_set_idxbxe(int node, int *vec, struct s_tree_ocp_qp *qp); -// -//void s_tree_ocp_qp_set_idxbue(int node, int *vec, struct s_tree_ocp_qp *qp); -// -//void s_tree_ocp_qp_set_idxge(int node, int *vec, struct s_tree_ocp_qp *qp); -// -//void s_tree_ocp_qp_set_Jbxe(int node, float *vec, struct s_tree_ocp_qp *qp); -// -//void s_tree_ocp_qp_set_Jbue(int node, float *vec, struct s_tree_ocp_qp *qp); -// -//void s_tree_ocp_qp_set_Jge(int node, float *vec, struct s_tree_ocp_qp *qp); -// -//void s_tree_ocp_qp_set_diag_H_flag(int node, int *value, struct s_tree_ocp_qp *qp); - - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_TREE_OCP_QP_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp_dim.h b/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp_dim.h deleted file mode 100644 index 90df57182b..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp_dim.h +++ /dev/null @@ -1,111 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_TREE_OCP_QP_DIM_H_ -#define HPIPM_S_TREE_OCP_QP_DIM_H_ - -#include "hpipm_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_tree_ocp_qp_dim - { - struct tree *ttree; // tree describing node conndection - int *nx; // number of states // Nn - int *nu; // number of inputs // Nn - int *nb; // number of box constraints // Nn - int *nbx; // number of state box constraints // Nn - int *nbu; // number of input box constraints // Nn - int *ng; // number of general constraints // Nn - int *ns; // number of soft constraints // Nn - int *nsbx; // number of soft state box constraints - int *nsbu; // number of soft input box constraints - int *nsg; // number of soft general constraints - int Nn; // number of nodes - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_tree_ocp_qp_dim_strsize(); -// -hpipm_size_t s_tree_ocp_qp_dim_memsize(int Nn); -// -void s_tree_ocp_qp_dim_create(int Nn, struct s_tree_ocp_qp_dim *qp_dim, void *memory); -// -void s_tree_ocp_qp_dim_set_all(struct tree *ttree, int *nx, int *nu, int *nbx, int *nbu, int *ng, int *nsbx, int *nsbu, int *nsg, struct s_tree_ocp_qp_dim *dim); -// -void s_tree_ocp_qp_dim_set_tree(struct tree *ttree, struct s_tree_ocp_qp_dim *dim); -// -void s_tree_ocp_qp_dim_set(char *field, int stage, int value, struct s_tree_ocp_qp_dim *dim); -// -void s_tree_ocp_qp_dim_set_nx(int stage, int value, struct s_tree_ocp_qp_dim *dim); -// -void s_tree_ocp_qp_dim_set_nu(int stage, int value, struct s_tree_ocp_qp_dim *dim); -// -void s_tree_ocp_qp_dim_set_nbx(int stage, int value, struct s_tree_ocp_qp_dim *dim); -// -void s_tree_ocp_qp_dim_set_nbu(int stage, int value, struct s_tree_ocp_qp_dim *dim); -// -void s_tree_ocp_qp_dim_set_ng(int stage, int value, struct s_tree_ocp_qp_dim *dim); -// -void s_tree_ocp_qp_dim_set_ns(int stage, int value, struct s_tree_ocp_qp_dim *dim); -// -void s_tree_ocp_qp_dim_set_nsbx(int stage, int value, struct s_tree_ocp_qp_dim *dim); -// -void s_tree_ocp_qp_dim_set_nsbu(int stage, int value, struct s_tree_ocp_qp_dim *dim); -// -void s_tree_ocp_qp_dim_set_nsg(int stage, int value, struct s_tree_ocp_qp_dim *dim); -// -void s_tree_ocp_qp_dim_set_nbxe(int stage, int value, struct s_tree_ocp_qp_dim *dim); -// -void s_tree_ocp_qp_dim_set_nbue(int stage, int value, struct s_tree_ocp_qp_dim *dim); -// -void s_tree_ocp_qp_dim_set_nge(int stage, int value, struct s_tree_ocp_qp_dim *dim); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_S_TREE_OCP_QP_DIM_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp_ipm.h b/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp_ipm.h deleted file mode 100644 index f8c26d3173..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp_ipm.h +++ /dev/null @@ -1,208 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - - -#ifndef HPIPM_S_TREE_OCP_QP_IPM_H_ -#define HPIPM_S_TREE_OCP_QP_IPM_H_ - - - -#include -#include - -#include -#include -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_tree_ocp_qp_ipm_arg - { - float mu0; // initial value for duality measure - float alpha_min; // exit cond on step length - float res_g_max; // exit cond on inf norm of residuals - float res_b_max; // exit cond on inf norm of residuals - float res_d_max; // exit cond on inf norm of residuals - float res_m_max; // exit cond on inf norm of residuals - float reg_prim; // reg of primal hessian - float lam_min; // min value in lam vector - float t_min; // min value in t vector - float tau_min; // min value of barrier parameter - int iter_max; // exit cond in iter number - int stat_max; // iterations saved in stat - int stat_m; // number of recorded stat per IPM iter - int pred_corr; // use Mehrotra's predictor-corrector IPM algirthm - int cond_pred_corr; // conditional Mehrotra's predictor-corrector - int itref_pred_max; // max number of iterative refinement steps for predictor step - int itref_corr_max; // max number of iterative refinement steps for corrector step - int warm_start; // 0 no warm start, 1 warm start primal sol, 2 warm start primal and dual sol - int lq_fact; // 0 syrk+potrf, 1 mix, 2 lq - int abs_form; // absolute IPM formulation - int comp_dual_sol_eq; // dual solution (only for abs_form==1) - int comp_res_exit; // compute residuals on exit (only for abs_form==1 and comp_dual_sol==1) - int split_step; // use different steps for primal and dual variables - int t_lam_min; // clip t and lam: 0 no, 1 in Gamma computation, 2 in solution - int mode; - hpipm_size_t memsize; - }; - - - -struct s_tree_ocp_qp_ipm_ws - { - struct s_core_qp_ipm_workspace *core_workspace; - struct s_tree_ocp_qp_res_ws *res_workspace; - struct s_tree_ocp_qp_sol *sol_step; - struct s_tree_ocp_qp_sol *sol_itref; - struct s_tree_ocp_qp *qp_step; - struct s_tree_ocp_qp *qp_itref; - struct s_tree_ocp_qp_res *res_itref; - struct s_tree_ocp_qp_res *res; - struct blasfeo_svec *Gamma; // hessian update - struct blasfeo_svec *gamma; // hessian update - struct blasfeo_svec *tmp_nxM; // work space of size nxM - struct blasfeo_svec *tmp_nbgM; // work space of size nbgM - struct blasfeo_svec *tmp_nsM; // work space of size nsM - struct blasfeo_svec *Pb; // Pb - struct blasfeo_svec *Zs_inv; - struct blasfeo_smat *L; - struct blasfeo_smat *Lh; - struct blasfeo_smat *AL; - struct blasfeo_smat *lq0; - struct blasfeo_svec *tmp_m; - float *stat; // convergence statistics - int *use_hess_fact; - void *lq_work0; - float qp_res[4]; // infinity norm of residuals - int iter; // iteration number - int stat_max; // iterations saved in stat - int stat_m; // number of recorded stat per IPM iter - int use_Pb; - int status; // solver status - int lq_fact; // cache from arg - int mask_constr; // use constr mask - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_tree_ocp_qp_ipm_arg_memsize(struct s_tree_ocp_qp_dim *dim); -// -void s_tree_ocp_qp_ipm_arg_create(struct s_tree_ocp_qp_dim *dim, struct s_tree_ocp_qp_ipm_arg *arg, void *mem); -// -void s_tree_ocp_qp_ipm_arg_set_default(enum hpipm_mode mode, struct s_tree_ocp_qp_ipm_arg *arg); -// -void s_tree_ocp_qp_ipm_arg_set_iter_max(int *iter_max, struct s_tree_ocp_qp_ipm_arg *arg); -// -void s_tree_ocp_qp_ipm_arg_set_alpha_min(float *alpha_min, struct s_tree_ocp_qp_ipm_arg *arg); -// -void s_tree_ocp_qp_ipm_arg_set_mu0(float *mu0, struct s_tree_ocp_qp_ipm_arg *arg); -// -void s_tree_ocp_qp_ipm_arg_set_tol_stat(float *tol_stat, struct s_tree_ocp_qp_ipm_arg *arg); -// -void s_tree_ocp_qp_ipm_arg_set_tol_eq(float *tol_eq, struct s_tree_ocp_qp_ipm_arg *arg); -// -void s_tree_ocp_qp_ipm_arg_set_tol_ineq(float *tol_ineq, struct s_tree_ocp_qp_ipm_arg *arg); -// -void s_tree_ocp_qp_ipm_arg_set_tol_comp(float *tol_comp, struct s_tree_ocp_qp_ipm_arg *arg); -// -void s_tree_ocp_qp_ipm_arg_set_reg_prim(float *reg, struct s_tree_ocp_qp_ipm_arg *arg); -// -void s_tree_ocp_qp_ipm_arg_set_warm_start(int *warm_start, struct s_tree_ocp_qp_ipm_arg *arg); -// -void s_tree_ocp_qp_ipm_arg_set_pred_corr(int *pred_corr, struct s_tree_ocp_qp_ipm_arg *arg); -// -void s_tree_ocp_qp_ipm_arg_set_cond_pred_corr(int *value, struct s_tree_ocp_qp_ipm_arg *arg); -// -void s_tree_ocp_qp_ipm_arg_set_comp_dual_sol_eq(int *value, struct s_tree_ocp_qp_ipm_arg *arg); -// -void s_tree_ocp_qp_ipm_arg_set_comp_res_exit(int *value, struct s_tree_ocp_qp_ipm_arg *arg); -// -void s_tree_ocp_qp_ipm_arg_set_lam_min(float *value, struct s_tree_ocp_qp_ipm_arg *arg); -// -void s_tree_ocp_qp_ipm_arg_set_t_min(float *value, struct s_tree_ocp_qp_ipm_arg *arg); -// -void s_tree_ocp_qp_ipm_arg_set_tau_min(float *value, struct s_tree_ocp_qp_ipm_arg *arg); -// -void s_tree_ocp_qp_ipm_arg_set_split_step(int *value, struct s_tree_ocp_qp_ipm_arg *arg); -// -void s_tree_ocp_qp_ipm_arg_set_t_lam_min(int *value, struct s_tree_ocp_qp_ipm_arg *arg); - -// -hpipm_size_t s_tree_ocp_qp_ipm_ws_memsize(struct s_tree_ocp_qp_dim *dim, struct s_tree_ocp_qp_ipm_arg *arg); -// -void s_tree_ocp_qp_ipm_ws_create(struct s_tree_ocp_qp_dim *dim, struct s_tree_ocp_qp_ipm_arg *arg, struct s_tree_ocp_qp_ipm_ws *ws, void *mem); -// -void s_tree_ocp_qp_ipm_get_status(struct s_tree_ocp_qp_ipm_ws *ws, int *status); -// -void s_tree_ocp_qp_ipm_get_iter(struct s_tree_ocp_qp_ipm_ws *ws, int *iter); -// -void s_tree_ocp_qp_ipm_get_max_res_stat(struct s_tree_ocp_qp_ipm_ws *ws, float *res_stat); -// -void s_tree_ocp_qp_ipm_get_max_res_eq(struct s_tree_ocp_qp_ipm_ws *ws, float *res_eq); -// -void s_tree_ocp_qp_ipm_get_max_res_ineq(struct s_tree_ocp_qp_ipm_ws *ws, float *res_ineq); -// -void s_tree_ocp_qp_ipm_get_max_res_comp(struct s_tree_ocp_qp_ipm_ws *ws, float *res_comp); -// -void s_tree_ocp_qp_ipm_get_stat(struct s_tree_ocp_qp_ipm_ws *ws, float **stat); -// -void s_tree_ocp_qp_ipm_get_stat_m(struct s_tree_ocp_qp_ipm_ws *ws, int *stat_m); -// -void s_tree_ocp_qp_init_var(struct s_tree_ocp_qp *qp, struct s_tree_ocp_qp_sol *qp_sol, struct s_tree_ocp_qp_ipm_arg *arg, struct s_tree_ocp_qp_ipm_ws *ws); -// -void s_tree_ocp_qp_ipm_abs_step(int kk, struct s_tree_ocp_qp *qp, struct s_tree_ocp_qp_sol *qp_sol, struct s_tree_ocp_qp_ipm_arg *arg, struct s_tree_ocp_qp_ipm_ws *ws); -// -void s_tree_ocp_qp_ipm_delta_step(int kk, struct s_tree_ocp_qp *qp, struct s_tree_ocp_qp_sol *qp_sol, struct s_tree_ocp_qp_ipm_arg *arg, struct s_tree_ocp_qp_ipm_ws *ws); -// -void s_tree_ocp_qp_ipm_solve(struct s_tree_ocp_qp *qp, struct s_tree_ocp_qp_sol *qp_sol, struct s_tree_ocp_qp_ipm_arg *arg, struct s_tree_ocp_qp_ipm_ws *ws); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_TREE_OCP_QP_IPM_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp_kkt.h b/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp_kkt.h deleted file mode 100644 index bcf7354783..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp_kkt.h +++ /dev/null @@ -1,54 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - -#ifdef __cplusplus -extern "C" { -#endif - -// -void s_tree_ocp_qp_fact_solve_kkt_unconstr(struct s_tree_ocp_qp *qp, struct s_tree_ocp_qp_sol *qp_sol, struct s_tree_ocp_qp_ipm_arg *arg, struct s_tree_ocp_qp_ipm_ws *ws); -// -void s_tree_ocp_qp_fact_solve_kkt_step(struct s_tree_ocp_qp *qp, struct s_tree_ocp_qp_sol *qp_sol, struct s_tree_ocp_qp_ipm_arg *arg, struct s_tree_ocp_qp_ipm_ws *ws); -// -void s_tree_ocp_qp_fact_lq_solve_kkt_step(struct s_tree_ocp_qp *qp, struct s_tree_ocp_qp_sol *qp_sol, struct s_tree_ocp_qp_ipm_arg *arg, struct s_tree_ocp_qp_ipm_ws *ws); -// -void s_tree_ocp_qp_solve_kkt_step(struct s_tree_ocp_qp *qp, struct s_tree_ocp_qp_sol *qp_sol, struct s_tree_ocp_qp_ipm_arg *arg, struct s_tree_ocp_qp_ipm_ws *ws); - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp_res.h b/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp_res.h deleted file mode 100644 index 5c6797204f..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp_res.h +++ /dev/null @@ -1,107 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_TREE_OCP_QP_RES_H_ -#define HPIPM_S_TREE_OCP_QP_RES_H_ - - - -#include -#include - -#include -#include -#include -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct s_tree_ocp_qp_res - { - struct s_tree_ocp_qp_dim *dim; - struct blasfeo_svec *res_g; // q-residuals - struct blasfeo_svec *res_b; // b-residuals - struct blasfeo_svec *res_d; // d-residuals - struct blasfeo_svec *res_m; // m-residuals - float res_max[4]; // max of residuals - float res_mu; // mu-residual - hpipm_size_t memsize; - }; - - - -struct s_tree_ocp_qp_res_ws - { - struct blasfeo_svec *tmp_nbgM; // work space of size nbM+ngM - struct blasfeo_svec *tmp_nsM; // work space of size nsM - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t s_tree_ocp_qp_res_memsize(struct s_tree_ocp_qp_dim *ocp_dim); -// -void s_tree_ocp_qp_res_create(struct s_tree_ocp_qp_dim *ocp_dim, struct s_tree_ocp_qp_res *res, void *mem); -// -hpipm_size_t s_tree_ocp_qp_res_ws_memsize(struct s_tree_ocp_qp_dim *ocp_dim); -// -void s_tree_ocp_qp_res_ws_create(struct s_tree_ocp_qp_dim *ocp_dim, struct s_tree_ocp_qp_res_ws *ws, void *mem); -// -void s_tree_ocp_qp_res_get_all(struct s_tree_ocp_qp_res *res, float **res_r, float **res_q, float **res_ls, float **res_us, float **res_b, float **res_d_lb, float **res_d_ub, float **res_d_lg, float **res_d_ug, float **res_d_ls, float **res_d_us, float **res_m_lb, float **res_m_ub, float **res_m_lg, float **res_m_ug, float **res_m_ls, float **res_m_us); -// -void s_tree_ocp_qp_res_compute(struct s_tree_ocp_qp *qp, struct s_tree_ocp_qp_sol *qp_sol, struct s_tree_ocp_qp_res *res, struct s_tree_ocp_qp_res_ws *ws); -// -void s_tree_ocp_qp_res_compute_lin(struct s_tree_ocp_qp *qp, struct s_tree_ocp_qp_sol *qp_sol, struct s_tree_ocp_qp_sol *qp_step, struct s_tree_ocp_qp_res *res, struct s_tree_ocp_qp_res_ws *ws); -// -void s_tree_ocp_qp_res_compute_inf_norm(struct s_tree_ocp_qp_res *res); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - -#endif // HPIPM_S_TREE_OCP_QP_RES_H_ - - - diff --git a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp_sol.h b/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp_sol.h deleted file mode 100644 index 71e887675b..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp_sol.h +++ /dev/null @@ -1,98 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_TREE_OCP_QP_SOL_H_ -#define HPIPM_S_TREE_OCP_QP_SOL_H_ - - - -#include -#include - -#include "hpipm_s_tree_ocp_qp_dim.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - -struct s_tree_ocp_qp_sol - { - struct s_tree_ocp_qp_dim *dim; - struct blasfeo_svec *ux; - struct blasfeo_svec *pi; - struct blasfeo_svec *lam; - struct blasfeo_svec *t; - void *misc; - hpipm_size_t memsize; // memory size in bytes - }; - - - -// -hpipm_size_t s_tree_ocp_qp_sol_memsize(struct s_tree_ocp_qp_dim *dim); -// -void s_tree_ocp_qp_sol_create(struct s_tree_ocp_qp_dim *dim, struct s_tree_ocp_qp_sol *qp_sol, void *memory); -// -void s_tree_ocp_qp_sol_get_all(struct s_tree_ocp_qp *qp, struct s_tree_ocp_qp_sol *qp_sol, float **u, float **x, float **ls, float **us, float **pi, float **lam_lb, float **lam_ub, float **lam_lg, float **lam_ug, float **lam_ls, float **lam_us); -// -void s_tree_ocp_qp_sol_get_u(int node, struct s_tree_ocp_qp_sol *qp_sol, float *vec); -// -void s_tree_ocp_qp_sol_get_x(int node, struct s_tree_ocp_qp_sol *qp_sol, float *vec); -// -void s_tree_ocp_qp_sol_get_sl(int node, struct s_tree_ocp_qp_sol *qp_sol, float *vec); -// -void s_tree_ocp_qp_sol_get_su(int node, struct s_tree_ocp_qp_sol *qp_sol, float *vec); -// -void s_tree_ocp_qp_sol_get_pi(int edge, struct s_tree_ocp_qp_sol *qp_sol, float *vec); -// -void s_tree_ocp_qp_sol_get_lam_lb(int node, struct s_tree_ocp_qp_sol *qp_sol, float *vec); -// -void s_tree_ocp_qp_sol_get_lam_ub(int node, struct s_tree_ocp_qp_sol *qp_sol, float *vec); -// -void s_tree_ocp_qp_sol_get_lam_lg(int node, struct s_tree_ocp_qp_sol *qp_sol, float *vec); -// -void s_tree_ocp_qp_sol_get_lam_ug(int node, struct s_tree_ocp_qp_sol *qp_sol, float *vec); - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - - - -#endif // HPIPM_S_TREE_OCP_QP_SOL_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp_utils.h b/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp_utils.h deleted file mode 100644 index ec1747568f..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_s_tree_ocp_qp_utils.h +++ /dev/null @@ -1,84 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_S_TREE_OCP_QP_UTILS_H_ -#define HPIPM_S_TREE_OCP_QP_UTILS_H_ - - - -#include -#include - -#include "hpipm_s_tree_ocp_qp_dim.h" -#include "hpipm_s_tree_ocp_qp.h" -#include "hpipm_s_tree_ocp_qp_sol.h" -#include "hpipm_s_tree_ocp_qp_ipm.h" - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -// -void s_tree_ocp_qp_dim_print(struct s_tree_ocp_qp_dim *qp_dim); -// -//void s_tree_ocp_qp_dim_codegen(char *file_name, char *mode, struct s_tree_ocp_qp_dim *qp_dim); -// -void s_tree_ocp_qp_print(struct s_tree_ocp_qp_dim *qp_dim, struct s_tree_ocp_qp *qp); -// -//void s_tree_ocp_qp_codegen(char *file_name, char *mode, struct s_tree_ocp_qp_dim *qp_dim, struct s_tree_ocp_qp *qp); -// -void s_tree_ocp_qp_sol_print(struct s_tree_ocp_qp_dim *qp_dim, struct s_tree_ocp_qp_sol *ocp_qp_sol); -// -void s_tree_ocp_qp_ipm_arg_print(struct s_tree_ocp_qp_dim *qp_dim, struct s_tree_ocp_qp_ipm_arg *arg); -// -//void s_tree_ocp_qp_ipm_arg_codegen(char *file_name, char *mode, struct s_tree_ocp_qp_dim *qp_dim, struct s_tree_ocp_qp_ipm_arg *arg); -// -void s_tree_ocp_qp_res_print(struct s_tree_ocp_qp_dim *qp_dim, struct s_tree_ocp_qp_res *ocp_qp_res); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - - -#endif // HPIPM_S_TREE_OCP_QP_UTILS_H_ - - diff --git a/third_party/acados/include/hpipm/include/hpipm_scenario_tree.h b/third_party/acados/include/hpipm/include/hpipm_scenario_tree.h deleted file mode 100644 index a3c77a670a..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_scenario_tree.h +++ /dev/null @@ -1,70 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_SCENARIO_TREE_H_ -#define HPIPM_SCENARIO_TREE_H_ - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct sctree - { - struct node *root; // pointer to root - int *kids; // pointer to array of kids - int Nn; // numer of nodes - int md; // number of realizations - int Nr; // robust horizion - int Nh; // control horizion - hpipm_size_t memsize; - }; - - - -// -hpipm_size_t sctree_memsize(int md, int Nr, int Nh); -// -void sctree_create(int md, int Nr, int Nh, struct sctree *st, void *memory); -// -void sctree_cast_to_tree(struct sctree *st, struct tree *tt); - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // HPIPM_SCENARIO_TREE_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_timing.h b/third_party/acados/include/hpipm/include/hpipm_timing.h deleted file mode 100644 index bd0f2dbcb3..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_timing.h +++ /dev/null @@ -1,67 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - -#ifndef HPIPM_TIMING_H_ -#define HPIPM_TIMING_H_ - - - -#include - - - -#ifdef __cplusplus -extern "C" { -#endif - - - -typedef blasfeo_timer hpipm_timer; - - - -// -void hpipm_tic(hpipm_timer *t); -// -double hpipm_toc(hpipm_timer *t); - - - -#ifdef __cplusplus -} // #extern "C" -#endif - - -#endif // HPIPM_TIMING_H_ diff --git a/third_party/acados/include/hpipm/include/hpipm_tree.h b/third_party/acados/include/hpipm/include/hpipm_tree.h deleted file mode 100644 index f9d69ecddd..0000000000 --- a/third_party/acados/include/hpipm/include/hpipm_tree.h +++ /dev/null @@ -1,76 +0,0 @@ -/************************************************************************************************** -* * -* This file is part of HPIPM. * -* * -* HPIPM -- High-Performance Interior Point Method. * -* Copyright (C) 2019 by Gianluca Frison. * -* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * -* All rights reserved. * -* * -* The 2-Clause BSD License * -* * -* 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. * -* * -* 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 OWNER 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. * -* * -* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * -* * -**************************************************************************************************/ - - -#ifndef HPIPM_TREE_H_ -#define HPIPM_TREE_H_ - -#include "hpipm_common.h" - -#ifdef __cplusplus -extern "C" { -#endif - - - -struct node - { - int *kids; // 64 bits - int idx; // 32 bits - int dad; // 32 bits - int nkids; // 32 bits - int stage; // 32 bits - int real; // 32 bits - int idxkid; // 32 bits // XXX needed ??? - // total 256 bits - }; - - - -struct tree - { - struct node *root; // pointer to root - int *kids; // pointer to array of kids - int Nn; // numer of nodes - hpipm_size_t memsize; - }; - - - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // HPIPM_TREE_H_ diff --git a/third_party/acados/include/qpOASES_e/Bounds.h b/third_party/acados/include/qpOASES_e/Bounds.h deleted file mode 100644 index 4e41c1d163..0000000000 --- a/third_party/acados/include/qpOASES_e/Bounds.h +++ /dev/null @@ -1,543 +0,0 @@ -/* - * This file is part of qpOASES. - * - * qpOASES -- An Implementation of the Online Active Set Strategy. - * Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka, - * Christian Kirches et al. All rights reserved. - * - * qpOASES is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * qpOASES is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with qpOASES; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/** - * \file include/qpOASES_e/Bounds.h - * \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches - * \version 3.1embedded - * \date 2007-2015 - * - * Declaration of the Bounds class designed to manage working sets of - * bounds within a QProblem. - */ - - -#ifndef QPOASES_BOUNDS_H -#define QPOASES_BOUNDS_H - - -#include - - -BEGIN_NAMESPACE_QPOASES - - -/** - * \brief Manages working sets of bounds (= box constraints). - * - * This class manages working sets of bounds (= box constraints) - * by storing index sets and other status information. - * - * \author Hans Joachim Ferreau - * \version 3.1embedded - * \date 2007-2015 - */ -typedef struct -{ - Indexlist *freee; /**< Index list of free variables. */ - Indexlist *fixed; /**< Index list of fixed variables. */ - - Indexlist *shiftedFreee; /**< Memory for shifting free variables. */ - Indexlist *shiftedFixed; /**< Memory for shifting fixed variables. */ - - Indexlist *rotatedFreee; /**< Memory for rotating free variables. */ - Indexlist *rotatedFixed; /**< Memory for rotating fixed variables. */ - - SubjectToType *type; /**< Type of bounds. */ - SubjectToStatus *status; /**< Status of bounds. */ - - SubjectToType *typeTmp; /**< Temp memory for type of bounds. */ - SubjectToStatus *statusTmp; /**< Temp memory for status of bounds. */ - - BooleanType noLower; /**< This flag indicates if there is no lower bound on any variable. */ - BooleanType noUpper; /**< This flag indicates if there is no upper bound on any variable. */ - - int n; /**< Total number of bounds. */ -} Bounds; - -int Bounds_calculateMemorySize( int n); - -char *Bounds_assignMemory(int n, Bounds **mem, void *raw_memory); - -Bounds *Bounds_createMemory( int n ); - -/** Constructor which takes the number of bounds. */ -void BoundsCON( Bounds* _THIS, - int _n /**< Number of bounds. */ - ); - -/** Copies all members from given rhs object. - * \return SUCCESSFUL_RETURN */ -void BoundsCPY( Bounds* FROM, - Bounds* TO - ); - - -/** Initialises object with given number of bounds. - * \return SUCCESSFUL_RETURN \n - RET_INVALID_ARGUMENTS */ -returnValue Bounds_init( Bounds* _THIS, - int _n /**< Number of bounds. */ - ); - - -/** Initially adds number of a new (i.e. not yet in the list) bound to - * given index set. - * \return SUCCESSFUL_RETURN \n - RET_SETUP_BOUND_FAILED \n - RET_INDEX_OUT_OF_BOUNDS \n - RET_INVALID_ARGUMENTS */ -returnValue Bounds_setupBound( Bounds* _THIS, - int number, /**< Number of new bound. */ - SubjectToStatus _status /**< Status of new bound. */ - ); - -/** Initially adds all numbers of new (i.e. not yet in the list) bounds to - * to the index set of free bounds; the order depends on the SujectToType - * of each index. - * \return SUCCESSFUL_RETURN \n - RET_SETUP_BOUND_FAILED */ -returnValue Bounds_setupAllFree( Bounds* _THIS - ); - -/** Initially adds all numbers of new (i.e. not yet in the list) bounds to - * to the index set of fixed bounds (on their lower bounds); - * the order depends on the SujectToType of each index. - * \return SUCCESSFUL_RETURN \n - RET_SETUP_BOUND_FAILED */ -returnValue Bounds_setupAllLower( Bounds* _THIS - ); - -/** Initially adds all numbers of new (i.e. not yet in the list) bounds to - * to the index set of fixed bounds (on their upper bounds); - * the order depends on the SujectToType of each index. - * \return SUCCESSFUL_RETURN \n - RET_SETUP_BOUND_FAILED */ -returnValue Bounds_setupAllUpper( Bounds* _THIS - ); - - -/** Moves index of a bound from index list of fixed to that of free bounds. - * \return SUCCESSFUL_RETURN \n - RET_MOVING_BOUND_FAILED \n - RET_INDEX_OUT_OF_BOUNDS */ -returnValue Bounds_moveFixedToFree( Bounds* _THIS, - int number /**< Number of bound to be freed. */ - ); - -/** Moves index of a bound from index list of free to that of fixed bounds. - * \return SUCCESSFUL_RETURN \n - RET_MOVING_BOUND_FAILED \n - RET_INDEX_OUT_OF_BOUNDS */ -returnValue Bounds_moveFreeToFixed( Bounds* _THIS, - int number, /**< Number of bound to be fixed. */ - SubjectToStatus _status /**< Status of bound to be fixed. */ - ); - -/** Flip fixed bound. - * \return SUCCESSFUL_RETURN \n - RET_MOVING_BOUND_FAILED \n - RET_INDEX_OUT_OF_BOUNDS */ -returnValue Bounds_flipFixed( Bounds* _THIS, - int number - ); - -/** Swaps the indices of two free bounds within the index set. - * \return SUCCESSFUL_RETURN \n - RET_SWAPINDEX_FAILED */ -returnValue Bounds_swapFree( Bounds* _THIS, - int number1, /**< Number of first bound. */ - int number2 /**< Number of second bound. */ - ); - - -/** Returns number of variables. - * \return Number of variables. */ -static inline int Bounds_getNV( Bounds* _THIS - ); - -/** Returns number of implicitly fixed variables. - * \return Number of implicitly fixed variables. */ -static inline int Bounds_getNFV( Bounds* _THIS - ); - -/** Returns number of bounded (but possibly free) variables. - * \return Number of bounded (but possibly free) variables. */ -static inline int Bounds_getNBV( Bounds* _THIS - ); - -/** Returns number of unbounded variables. - * \return Number of unbounded variables. */ -static inline int Bounds_getNUV( Bounds* _THIS - ); - -/** Returns number of free variables. - * \return Number of free variables. */ -static inline int Bounds_getNFR( Bounds* _THIS - ); - -/** Returns number of fixed variables. - * \return Number of fixed variables. */ -static inline int Bounds_getNFX( Bounds* _THIS - ); - - -/** Returns a pointer to free variables index list. - * \return Pointer to free variables index list. */ -static inline Indexlist* Bounds_getFree( Bounds* _THIS - ); - -/** Returns a pointer to fixed variables index list. - * \return Pointer to fixed variables index list. */ -static inline Indexlist* Bounds_getFixed( Bounds* _THIS - ); - - -/** Returns number of bounds with given SubjectTo type. - * \return Number of bounds with given type. */ -static inline int Bounds_getNumberOfType( Bounds* _THIS, - SubjectToType _type /**< Type of bound. */ - ); - - -/** Returns type of bound. - * \return Type of bound \n - RET_INDEX_OUT_OF_BOUNDS */ -static inline SubjectToType Bounds_getType( Bounds* _THIS, - int i /**< Number of bound. */ - ); - -/** Returns status of bound. - * \return Status of bound \n - ST_UNDEFINED */ -static inline SubjectToStatus Bounds_getStatus( Bounds* _THIS, - int i /**< Number of bound. */ - ); - - -/** Sets type of bound. - * \return SUCCESSFUL_RETURN \n - RET_INDEX_OUT_OF_BOUNDS */ -static inline returnValue Bounds_setType( Bounds* _THIS, - int i, /**< Number of bound. */ - SubjectToType value /**< Type of bound. */ - ); - -/** Sets status of bound. - * \return SUCCESSFUL_RETURN \n - RET_INDEX_OUT_OF_BOUNDS */ -static inline returnValue Bounds_setStatus( Bounds* _THIS, - int i, /**< Number of bound. */ - SubjectToStatus value /**< Status of bound. */ - ); - - -/** Sets status of lower bounds. */ -static inline void Bounds_setNoLower( Bounds* _THIS, - BooleanType _status /**< Status of lower bounds. */ - ); - -/** Sets status of upper bounds. */ -static inline void Bounds_setNoUpper( Bounds* _THIS, - BooleanType _status /**< Status of upper bounds. */ - ); - - -/** Returns status of lower bounds. - * \return BT_TRUE if there is no lower bound on any variable. */ -static inline BooleanType Bounds_hasNoLower( Bounds* _THIS - ); - -/** Returns status of upper bounds. - * \return BT_TRUE if there is no upper bound on any variable. */ -static inline BooleanType Bounds_hasNoUpper( Bounds* _THIS - ); - - -/** Shifts forward type and status of all bounds by a given - * offset. This offset has to lie within the range [0,n/2] and has to - * be an integer divisor of the total number of bounds n. - * Type and status of the first \ bounds is thrown away, - * type and status of the last \ bounds is doubled, - * e.g. for offset = 2: \n - * shift( {b1,b2,b3,b4,b5,b6} ) = {b3,b4,b5,b6,b5,b6} - * \return SUCCESSFUL_RETURN \n - RET_INDEX_OUT_OF_BOUNDS \n - RET_INVALID_ARGUMENTS \n - RET_SHIFTING_FAILED */ -returnValue Bounds_shift( Bounds* _THIS, - int offset /**< Shift offset within the range [0,n/2] and integer divisor of n. */ - ); - -/** Rotates forward type and status of all bounds by a given - * offset. This offset has to lie within the range [0,n]. - * Example for offset = 2: \n - * rotate( {b1,b2,b3,b4,b5,b6} ) = {b3,b4,b5,b6,b1,b2} - * \return SUCCESSFUL_RETURN \n - RET_INDEX_OUT_OF_BOUNDS \n - RET_ROTATING_FAILED */ -returnValue Bounds_rotate( Bounds* _THIS, - int offset /**< Rotation offset within the range [0,n]. */ - ); - - -/** Prints information on bounds object - * (in particular, lists of free and fixed bounds. - * \return SUCCESSFUL_RETURN \n - RET_INDEXLIST_CORRUPTED */ -returnValue Bounds_print( Bounds* _THIS - ); - - -/** Initially adds all numbers of new (i.e. not yet in the list) bounds to - * to the index set corresponding to the desired status; - * the order depends on the SujectToType of each index. - * \return SUCCESSFUL_RETURN \n - RET_SETUP_BOUND_FAILED */ -returnValue Bounds_setupAll( Bounds* _THIS, - SubjectToStatus _status /**< Desired initial status for all bounds. */ - ); - - -/** Adds the index of a new bound to index set. - * \return SUCCESSFUL_RETURN \n - RET_ADDINDEX_FAILED \n - RET_INVALID_ARGUMENTS */ -returnValue Bounds_addIndex( Bounds* _THIS, - Indexlist* const indexlist, /**< Index list to which the new index shall be added. */ - int newnumber, /**< Number of new bound. */ - SubjectToStatus newstatus /**< Status of new bound. */ - ); - -/** Removes the index of a bound from index set. - * \return SUCCESSFUL_RETURN \n - RET_REMOVEINDEX_FAILED \n - RET_INVALID_ARGUMENTS */ -returnValue Bounds_removeIndex( Bounds* _THIS, - Indexlist* const indexlist, /**< Index list from which the new index shall be removed. */ - int removenumber /**< Number of bound to be removed. */ - ); - -/** Swaps the indices of two constraints or bounds within the index set. - * \return SUCCESSFUL_RETURN \n - RET_SWAPINDEX_FAILED \n - RET_INVALID_ARGUMENTS */ -returnValue Bounds_swapIndex( Bounds* _THIS, - Indexlist* const indexlist, /**< Index list in which the indices shold be swapped. */ - int number1, /**< Number of first bound. */ - int number2 /**< Number of second bound. */ - ); - - - -/* - * g e t N u m b e r O f T y p e - */ -static inline int Bounds_getNumberOfType( Bounds* _THIS, SubjectToType _type ) -{ - int i; - int numberOfType = 0; - - if ( _THIS->type != 0 ) - { - for( i=0; i<_THIS->n; ++i ) - if ( _THIS->type[i] == _type ) - ++numberOfType; - } - - return numberOfType; -} - - -/* - * g e t T y p e - */ -static inline SubjectToType Bounds_getType( Bounds* _THIS, int i ) -{ - if ( ( i >= 0 ) && ( i < _THIS->n ) ) - return _THIS->type[i]; - - return ST_UNKNOWN; -} - - -/* - * g e t S t a t u s - */ -static inline SubjectToStatus Bounds_getStatus( Bounds* _THIS, int i ) -{ - if ( ( i >= 0 ) && ( i < _THIS->n ) ) - return _THIS->status[i]; - - return ST_UNDEFINED; -} - - -/* - * s e t T y p e - */ -static inline returnValue Bounds_setType( Bounds* _THIS, int i, SubjectToType value ) -{ - if ( ( i >= 0 ) && ( i < _THIS->n ) ) - { - _THIS->type[i] = value; - return SUCCESSFUL_RETURN; - } - else - return THROWERROR( RET_INDEX_OUT_OF_BOUNDS ); -} - - -/* - * s e t S t a t u s - */ -static inline returnValue Bounds_setStatus( Bounds* _THIS, int i, SubjectToStatus value ) -{ - if ( ( i >= 0 ) && ( i < _THIS->n ) ) - { - _THIS->status[i] = value; - return SUCCESSFUL_RETURN; - } - else - return THROWERROR( RET_INDEX_OUT_OF_BOUNDS ); -} - - -/* - * s e t N o L o w e r - */ -static inline void Bounds_setNoLower( Bounds* _THIS, BooleanType _status ) -{ - _THIS->noLower = _status; -} - - -/* - * s e t N o U p p e r - */ -static inline void Bounds_setNoUpper( Bounds* _THIS, BooleanType _status ) -{ - _THIS->noUpper = _status; -} - - -/* - * h a s N o L o w e r - */ -static inline BooleanType Bounds_hasNoLower( Bounds* _THIS ) -{ - return _THIS->noLower; -} - - -/* - * h a s N o U p p p e r - */ -static inline BooleanType Bounds_hasNoUpper( Bounds* _THIS ) -{ - return _THIS->noUpper; -} - - - -/* - * g e t N V - */ -static inline int Bounds_getNV( Bounds* _THIS ) -{ - return _THIS->n; -} - - -/* - * g e t N F V - */ -static inline int Bounds_getNFV( Bounds* _THIS ) -{ - return Bounds_getNumberOfType( _THIS,ST_EQUALITY ); -} - - -/* - * g e t N B V - */ -static inline int Bounds_getNBV( Bounds* _THIS ) -{ - return Bounds_getNumberOfType( _THIS,ST_BOUNDED ); -} - - -/* - * g e t N U V - */ -static inline int Bounds_getNUV( Bounds* _THIS ) -{ - return Bounds_getNumberOfType( _THIS,ST_UNBOUNDED ); -} - - -/* - * g e t N F R - */ -static inline int Bounds_getNFR( Bounds* _THIS ) -{ - return Indexlist_getLength( _THIS->freee ); -} - - -/* - * g e t N F X - */ -static inline int Bounds_getNFX( Bounds* _THIS ) -{ - return Indexlist_getLength( _THIS->fixed ); -} - - -/* - * g e t F r e e - */ -static inline Indexlist* Bounds_getFree( Bounds* _THIS ) -{ - return _THIS->freee; -} - - -/* - * g e t F i x e d - */ -static inline Indexlist* Bounds_getFixed( Bounds* _THIS ) -{ - return _THIS->fixed; -} - - -END_NAMESPACE_QPOASES - -#endif /* QPOASES_BOUNDS_H */ - - -/* - * end of file - */ diff --git a/third_party/acados/include/qpOASES_e/Constants.h b/third_party/acados/include/qpOASES_e/Constants.h deleted file mode 100644 index 13c777d75b..0000000000 --- a/third_party/acados/include/qpOASES_e/Constants.h +++ /dev/null @@ -1,134 +0,0 @@ -/* - * This file is part of qpOASES. - * - * qpOASES -- An Implementation of the Online Active Set Strategy. - * Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka, - * Christian Kirches et al. All rights reserved. - * - * qpOASES is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * qpOASES is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with qpOASES; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/** - * \file include/qpOASES_e/Constants.h - * \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches - * \version 3.1embedded - * \date 2007-2015 - * - * Definition of all global constants. - */ - - -#ifndef QPOASES_CONSTANTS_H -#define QPOASES_CONSTANTS_H - - -#include - -#ifdef __CODE_GENERATION__ - - #define CONVERTTOSTRINGAUX(x) #x - #define CONVERTTOSTRING(x) CONVERTTOSTRINGAUX(x) - - #ifndef QPOASES_CUSTOM_INTERFACE - #include "acado_qpoases3_interface.h" - #else - #include CONVERTTOSTRING(QPOASES_CUSTOM_INTERFACE) - #endif - -#endif - - -BEGIN_NAMESPACE_QPOASES - - -#ifndef __EXTERNAL_DIMENSIONS__ - - /*#define QPOASES_NVMAX 50 - #define QPOASES_NCMAX 100*/ - #define QPOASES_NVMAX 287 - #define QPOASES_NCMAX 709 - -#endif /* __EXTERNAL_DIMENSIONS__ */ - - -/** Maximum number of variables within a QP formulation. - * Note: this value has to be positive! */ -#define NVMAX QPOASES_NVMAX - -/** Maximum number of constraints within a QP formulation. - * Note: this value has to be positive! */ -#define NCMAX QPOASES_NCMAX - -#if ( QPOASES_NVMAX > QPOASES_NCMAX ) -#define NVCMAX QPOASES_NVMAX -#else -#define NVCMAX QPOASES_NCMAX -#endif - -#if ( QPOASES_NVMAX > QPOASES_NCMAX ) -#define NVCMIN QPOASES_NCMAX -#else -#define NVCMIN QPOASES_NVMAX -#endif - - -/** Maximum number of QPs in a sequence solved by means of the OQP interface. - * Note: this value has to be positive! */ -#define NQPMAX 1000 - - -/** Numerical value of machine precision (min eps, s.t. 1+eps > 1). - * Note: this value has to be positive! */ -#ifndef __CODE_GENERATION__ - - #ifdef __USE_SINGLE_PRECISION__ - static const real_t QPOASES_EPS = 1.193e-07; - #else - static const real_t QPOASES_EPS = 2.221e-16; - #endif /* __USE_SINGLE_PRECISION__ */ - -#endif /* __CODE_GENERATION__ */ - - -/** Numerical value of zero (for situations in which it would be - * unreasonable to compare with 0.0). - * Note: this value has to be positive! */ -static const real_t QPOASES_ZERO = 1.0e-25; - -/** Numerical value of infinity (e.g. for non-existing bounds). - * Note: this value has to be positive! */ -static const real_t QPOASES_INFTY = 1.0e20; - -/** Tolerance to used for isEqual, isZero etc. - * Note: this value has to be positive! */ -static const real_t QPOASES_TOL = 1.0e-25; - - -/** Maximum number of characters within a string. - * Note: this value should be at least 41! */ -#define QPOASES_MAX_STRING_LENGTH 160 - - -END_NAMESPACE_QPOASES - - -#endif /* QPOASES_CONSTANTS_H */ - - -/* - * end of file - */ diff --git a/third_party/acados/include/qpOASES_e/ConstraintProduct.h b/third_party/acados/include/qpOASES_e/ConstraintProduct.h deleted file mode 100644 index eb5400c6cb..0000000000 --- a/third_party/acados/include/qpOASES_e/ConstraintProduct.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - * This file is part of qpOASES. - * - * qpOASES -- An Implementation of the Online Active Set Strategy. - * Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka, - * Christian Kirches et al. All rights reserved. - * - * qpOASES is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * qpOASES is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with qpOASES; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/** - * \file include/qpOASES_e/ConstraintProduct.h - * \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches (thanks to D. Kwame Minde Kufoalor) - * \version 3.1embedded - * \date 2009-2015 - * - * Declaration of the ConstraintProduct interface which allows to specify a - * user-defined function for evaluating the constraint product at the - * current iterate to speed-up QP solution in case of a specially structured - * constraint matrix. - */ - - - -#ifndef QPOASES_CONSTRAINT_PRODUCT_H -#define QPOASES_CONSTRAINT_PRODUCT_H - - -BEGIN_NAMESPACE_QPOASES - - -/** - * \brief Interface for specifying user-defined evaluations of constraint products. - * - * An interface which allows to specify a user-defined function for evaluating the - * constraint product at the current iterate to speed-up QP solution in case - * of a specially structured constraint matrix. - * - * \author Hans Joachim Ferreau (thanks to Kwame Minde Kufoalor) - * \version 3.1embedded - * \date 2009-2015 - */ -typedef int(*ConstraintProduct)( int, const real_t* const, real_t* const ); - - -END_NAMESPACE_QPOASES - -#endif /* QPOASES_CONSTRAINT_PRODUCT_H */ diff --git a/third_party/acados/include/qpOASES_e/Constraints.h b/third_party/acados/include/qpOASES_e/Constraints.h deleted file mode 100644 index 8aca10d5d9..0000000000 --- a/third_party/acados/include/qpOASES_e/Constraints.h +++ /dev/null @@ -1,535 +0,0 @@ -/* - * This file is part of qpOASES. - * - * qpOASES -- An Implementation of the Online Active Set Strategy. - * Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka, - * Christian Kirches et al. All rights reserved. - * - * qpOASES is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * qpOASES is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with qpOASES; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/** - * \file include/qpOASES_e/Constraints.h - * \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches - * \version 3.1embedded - * \date 2007-2015 - * - * Declaration of the Constraints class designed to manage working sets of - * constraints within a QProblem. - */ - - -#ifndef QPOASES_CONSTRAINTS_H -#define QPOASES_CONSTRAINTS_H - - -#include - - -BEGIN_NAMESPACE_QPOASES - - -/** - * \brief Manages working sets of constraints. - * - * This class manages working sets of constraints by storing - * index sets and other status information. - * - * \author Hans Joachim Ferreau - * \version 3.1embedded - * \date 2007-2015 - */ -typedef struct -{ - Indexlist *active; /**< Index list of active constraints. */ - Indexlist *inactive; /**< Index list of inactive constraints. */ - - Indexlist *shiftedActive; /**< Memory for shifting active constraints. */ - Indexlist *shiftedInactive; /**< Memory for shifting inactive constraints. */ - - Indexlist *rotatedActive; /**< Memory for rotating active constraints. */ - Indexlist *rotatedInactive; /**< Memory for rotating inactive constraints. */ - - SubjectToType *type; /**< Type of constraints. */ - SubjectToStatus *status; /**< Status of constraints. */ - - SubjectToType *typeTmp; /**< Temp memory for type of constraints. */ - SubjectToStatus *statusTmp; /**< Temp memory for status of constraints. */ - - BooleanType noLower; /**< This flag indicates if there is no lower bound on any variable. */ - BooleanType noUpper; /**< This flag indicates if there is no upper bound on any variable. */ - - int n; /**< Total number of constraints. */ -} Constraints; - -int Constraints_calculateMemorySize( int n); - -char *Constraints_assignMemory(int n, Constraints **mem, void *raw_memory); - -Constraints *Constraints_createMemory( int n ); - -/** Constructor which takes the number of constraints. */ -void ConstraintsCON( Constraints* _THIS, - int _n /**< Number of constraints. */ - ); - -/** Copies all members from given rhs object. - * \return SUCCESSFUL_RETURN */ -void ConstraintsCPY( Constraints* FROM, - Constraints* TO - ); - - -/** Initialises object with given number of constraints. - * \return SUCCESSFUL_RETURN \n - RET_INVALID_ARGUMENTS */ -returnValue Constraints_init( Constraints* _THIS, - int _n /**< Number of constraints. */ - ); - - -/** Initially adds number of a new (i.e. not yet in the list) constraint to - * a given index set. - * \return SUCCESSFUL_RETURN \n - RET_SETUP_CONSTRAINT_FAILED \n - RET_INDEX_OUT_OF_BOUNDS \n - RET_INVALID_ARGUMENTS */ -returnValue Constraints_setupConstraint( Constraints* _THIS, - int number, /**< Number of new constraint. */ - SubjectToStatus _status /**< Status of new constraint. */ - ); - -/** Initially adds all enabled numbers of new (i.e. not yet in the list) constraints to - * to the index set of inactive constraints; the order depends on the SujectToType - * of each index. Only disabled constraints are added to index set of disabled constraints! - * \return SUCCESSFUL_RETURN \n - RET_SETUP_CONSTRAINT_FAILED */ -returnValue Constraints_setupAllInactive( Constraints* _THIS - ); - -/** Initially adds all enabled numbers of new (i.e. not yet in the list) constraints to - * to the index set of active constraints (on their lower bounds); the order depends on the SujectToType - * of each index. Only disabled constraints are added to index set of disabled constraints! - * \return SUCCESSFUL_RETURN \n - RET_SETUP_CONSTRAINT_FAILED */ -returnValue Constraints_setupAllLower( Constraints* _THIS - ); - -/** Initially adds all enabled numbers of new (i.e. not yet in the list) constraints to - * to the index set of active constraints (on their upper bounds); the order depends on the SujectToType - * of each index. Only disabled constraints are added to index set of disabled constraints! - * \return SUCCESSFUL_RETURN \n - RET_SETUP_CONSTRAINT_FAILED */ -returnValue Constraints_setupAllUpper( Constraints* _THIS - ); - - -/** Moves index of a constraint from index list of active to that of inactive constraints. - * \return SUCCESSFUL_RETURN \n - RET_MOVING_CONSTRAINT_FAILED */ -returnValue Constraints_moveActiveToInactive( Constraints* _THIS, - int number /**< Number of constraint to become inactive. */ - ); - -/** Moves index of a constraint from index list of inactive to that of active constraints. - * \return SUCCESSFUL_RETURN \n - RET_MOVING_CONSTRAINT_FAILED */ -returnValue Constraints_moveInactiveToActive( Constraints* _THIS, - int number, /**< Number of constraint to become active. */ - SubjectToStatus _status /**< Status of constraint to become active. */ - ); - -/** Flip fixed constraint. - * \return SUCCESSFUL_RETURN \n - RET_MOVING_CONSTRAINT_FAILED \n - RET_INDEX_OUT_OF_BOUNDS */ -returnValue Constraints_flipFixed( Constraints* _THIS, - int number - ); - - -/** Returns the number of constraints. - * \return Number of constraints. */ -static inline int Constraints_getNC( Constraints* _THIS - ); - -/** Returns the number of implicit equality constraints. - * \return Number of implicit equality constraints. */ -static inline int Constraints_getNEC( Constraints* _THIS - ); - -/** Returns the number of "real" inequality constraints. - * \return Number of "real" inequality constraints. */ -static inline int Constraints_getNIC( Constraints* _THIS - ); - -/** Returns the number of unbounded constraints (i.e. without any bounds). - * \return Number of unbounded constraints (i.e. without any bounds). */ -static inline int Constraints_getNUC( Constraints* _THIS - ); - -/** Returns the number of active constraints. - * \return Number of active constraints. */ -static inline int Constraints_getNAC( Constraints* _THIS - ); - -/** Returns the number of inactive constraints. - * \return Number of inactive constraints. */ -static inline int Constraints_getNIAC( Constraints* _THIS - ); - - -/** Returns a pointer to active constraints index list. - * \return Pointer to active constraints index list. */ -static inline Indexlist* Constraints_getActive( Constraints* _THIS - ); - -/** Returns a pointer to inactive constraints index list. - * \return Pointer to inactive constraints index list. */ -static inline Indexlist* Constraints_getInactive( Constraints* _THIS - ); - - -/** Returns number of constraints with given SubjectTo type. - * \return Number of constraints with given type. */ -static inline int Constraints_getNumberOfType( Constraints* _THIS, - SubjectToType _type /**< Type of constraints' bound. */ - ); - - -/** Returns type of constraints' bound. - * \return Type of constraints' bound \n - RET_INDEX_OUT_OF_BOUNDS */ -static inline SubjectToType Constraints_getType( Constraints* _THIS, - int i /**< Number of constraints' bound. */ - ); - -/** Returns status of constraints' bound. - * \return Status of constraints' bound \n - ST_UNDEFINED */ -static inline SubjectToStatus Constraints_getStatus( Constraints* _THIS, - int i /**< Number of constraints' bound. */ - ); - - -/** Sets type of constraints' bound. - * \return SUCCESSFUL_RETURN \n - RET_INDEX_OUT_OF_BOUNDS */ -static inline returnValue Constraints_setType( Constraints* _THIS, - int i, /**< Number of constraints' bound. */ - SubjectToType value /**< Type of constraints' bound. */ - ); - -/** Sets status of constraints' bound. - * \return SUCCESSFUL_RETURN \n - RET_INDEX_OUT_OF_BOUNDS */ -static inline returnValue Constraints_setStatus( Constraints* _THIS, - int i, /**< Number of constraints' bound. */ - SubjectToStatus value /**< Status of constraints' bound. */ - ); - - -/** Sets status of lower constraints' bounds. */ -static inline void Constraints_setNoLower( Constraints* _THIS, - BooleanType _status /**< Status of lower constraints' bounds. */ - ); - -/** Sets status of upper constraints' bounds. */ -static inline void Constraints_setNoUpper( Constraints* _THIS, - BooleanType _status /**< Status of upper constraints' bounds. */ - ); - - -/** Returns status of lower constraints' bounds. - * \return BT_TRUE if there is no lower constraints' bound on any variable. */ -static inline BooleanType Constraints_hasNoLower( Constraints* _THIS - ); - -/** Returns status of upper bounds. - * \return BT_TRUE if there is no upper constraints' bound on any variable. */ -static inline BooleanType Constraints_hasNoUpper( Constraints* _THIS - ); - - -/** Shifts forward type and status of all constraints by a given - * offset. This offset has to lie within the range [0,n/2] and has to - * be an integer divisor of the total number of constraints n. - * Type and status of the first \ constraints is thrown away, - * type and status of the last \ constraints is doubled, - * e.g. for offset = 2: \n - * shift( {c/b1,c/b2,c/b3,c/b4,c/b5,c/b6} ) = {c/b3,c/b4,c/b5,c/b6,c/b5,c/b6} - * \return SUCCESSFUL_RETURN \n - RET_INDEX_OUT_OF_BOUNDS \n - RET_INVALID_ARGUMENTS \n - RET_SHIFTING_FAILED */ -returnValue Constraints_shift( Constraints* _THIS, - int offset /**< Shift offset within the range [0,n/2] and integer divisor of n. */ - ); - -/** Rotates forward type and status of all constraints by a given - * offset. This offset has to lie within the range [0,n]. - * Example for offset = 2: \n - * rotate( {c1,c2,c3,c4,c5,c6} ) = {c3,c4,c5,c6,c1,c2} - * \return SUCCESSFUL_RETURN \n - RET_INDEX_OUT_OF_BOUNDS \n - RET_ROTATING_FAILED */ -returnValue Constraints_rotate( Constraints* _THIS, - int offset /**< Rotation offset within the range [0,n]. */ - ); - - -/** Prints information on constraints object - * (in particular, lists of inactive and active constraints. - * \return SUCCESSFUL_RETURN \n - RET_INDEXLIST_CORRUPTED */ -returnValue Constraints_print( Constraints* _THIS - ); - - -/** Initially adds all numbers of new (i.e. not yet in the list) bounds to - * to the index set corresponding to the desired status; - * the order depends on the SujectToType of each index. - * \return SUCCESSFUL_RETURN \n - RET_SETUP_CONSTRAINT_FAILED */ -returnValue Constraints_setupAll( Constraints* _THIS, - SubjectToStatus _status /**< Desired initial status for all bounds. */ - ); - - -/** Adds the index of a new constraint to index set. - * \return SUCCESSFUL_RETURN \n - RET_ADDINDEX_FAILED \n - RET_INVALID_ARGUMENTS */ -returnValue Constraints_addIndex( Constraints* _THIS, - Indexlist* const indexlist, /**< Index list to which the new index shall be added. */ - int newnumber, /**< Number of new constraint. */ - SubjectToStatus newstatus /**< Status of new constraint. */ - ); - -/** Removes the index of a constraint from index set. - * \return SUCCESSFUL_RETURN \n - RET_REMOVEINDEX_FAILED \n - RET_INVALID_ARGUMENTS */ -returnValue Constraints_removeIndex( Constraints* _THIS, - Indexlist* const indexlist, /**< Index list from which the new index shall be removed. */ - int removenumber /**< Number of constraint to be removed. */ - ); - -/** Swaps the indices of two constraints or bounds within the index set. - * \return SUCCESSFUL_RETURN \n - RET_SWAPINDEX_FAILED \n - RET_INVALID_ARGUMENTS */ -returnValue Constraints_swapIndex( Constraints* _THIS, - Indexlist* const indexlist, /**< Index list in which the indices shold be swapped. */ - int number1, /**< Number of first constraint. */ - int number2 /**< Number of second constraint. */ - ); - - - -/* - * g e t N u m b e r O f T y p e - */ -static inline int Constraints_getNumberOfType( Constraints* _THIS, SubjectToType _type ) -{ - int i; - int numberOfType = 0; - - if ( _THIS->type != 0 ) - { - for( i=0; i<_THIS->n; ++i ) - if ( _THIS->type[i] == _type ) - ++numberOfType; - } - - return numberOfType; -} - - -/* - * g e t T y p e - */ -static inline SubjectToType Constraints_getType( Constraints* _THIS, int i ) -{ - if ( ( i >= 0 ) && ( i < _THIS->n ) ) - return _THIS->type[i]; - - return ST_UNKNOWN; -} - - -/* - * g e t S t a t u s - */ -static inline SubjectToStatus Constraints_getStatus( Constraints* _THIS, int i ) -{ - if ( ( i >= 0 ) && ( i < _THIS->n ) ) - return _THIS->status[i]; - - return ST_UNDEFINED; -} - - -/* - * s e t T y p e - */ -static inline returnValue Constraints_setType( Constraints* _THIS, int i, SubjectToType value ) -{ - if ( ( i >= 0 ) && ( i < _THIS->n ) ) - { - _THIS->type[i] = value; - return SUCCESSFUL_RETURN; - } - else - return THROWERROR( RET_INDEX_OUT_OF_BOUNDS ); -} - - -/* - * s e t S t a t u s - */ -static inline returnValue Constraints_setStatus( Constraints* _THIS, int i, SubjectToStatus value ) -{ - if ( ( i >= 0 ) && ( i < _THIS->n ) ) - { - _THIS->status[i] = value; - return SUCCESSFUL_RETURN; - } - else - return THROWERROR( RET_INDEX_OUT_OF_BOUNDS ); -} - - -/* - * s e t N o L o w e r - */ -static inline void Constraints_setNoLower( Constraints* _THIS, BooleanType _status ) -{ - _THIS->noLower = _status; -} - - -/* - * s e t N o U p p e r - */ -static inline void Constraints_setNoUpper( Constraints* _THIS, BooleanType _status ) -{ - _THIS->noUpper = _status; -} - - -/* - * h a s N o L o w e r - */ -static inline BooleanType Constraints_hasNoLower( Constraints* _THIS ) -{ - return _THIS->noLower; -} - - -/* - * h a s N o U p p p e r - */ -static inline BooleanType Constraints_hasNoUpper( Constraints* _THIS ) -{ - return _THIS->noUpper; -} - - - -/* - * g e t N C - */ -static inline int Constraints_getNC( Constraints* _THIS ) -{ - return _THIS->n; -} - - -/* - * g e t N E C - */ -static inline int Constraints_getNEC( Constraints* _THIS ) -{ - return Constraints_getNumberOfType( _THIS,ST_EQUALITY ); -} - - -/* - * g e t N I C - */ -static inline int Constraints_getNIC( Constraints* _THIS ) -{ - return Constraints_getNumberOfType( _THIS,ST_BOUNDED ); -} - - -/* - * g e t N U C - */ -static inline int Constraints_getNUC( Constraints* _THIS ) -{ - return Constraints_getNumberOfType( _THIS,ST_UNBOUNDED ); -} - - -/* - * g e t N A C - */ -static inline int Constraints_getNAC( Constraints* _THIS ) -{ - return Indexlist_getLength( _THIS->active ); -} - - -/* - * g e t N I A C - */ -static inline int Constraints_getNIAC( Constraints* _THIS ) -{ - return Indexlist_getLength( _THIS->inactive ); -} - - - -/* - * g e t A c t i v e - */ -static inline Indexlist* Constraints_getActive( Constraints* _THIS ) -{ - return _THIS->active; -} - - -/* - * g e t I n a c t i v e - */ -static inline Indexlist* Constraints_getInactive( Constraints* _THIS ) -{ - return _THIS->inactive; -} - - -END_NAMESPACE_QPOASES - - -#endif /* QPOASES_CONSTRAINTS_H */ - - -/* - * end of file - */ diff --git a/third_party/acados/include/qpOASES_e/Flipper.h b/third_party/acados/include/qpOASES_e/Flipper.h deleted file mode 100644 index 63526a30f3..0000000000 --- a/third_party/acados/include/qpOASES_e/Flipper.h +++ /dev/null @@ -1,129 +0,0 @@ -/* - * This file is part of qpOASES. - * - * qpOASES -- An Implementation of the Online Active Set Strategy. - * Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka, - * Christian Kirches et al. All rights reserved. - * - * qpOASES is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * qpOASES is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with qpOASES; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/** - * \file include/qpOASES_e/Flipper.h - * \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches - * \version 3.1embedded - * \date 2007-2015 - * - * Declaration of the Options class designed to manage user-specified - * options for solving a QProblem. - */ - - -#ifndef QPOASES_FLIPPER_H -#define QPOASES_FLIPPER_H - - -#include -#include - - -BEGIN_NAMESPACE_QPOASES - - -/** - * \brief Auxiliary class for storing a copy of the current matrix factorisations. - * - * This auxiliary class stores a copy of the current matrix factorisations. It - * is used by the classe QProblemB and QProblem in case flipping bounds are enabled. - * - * \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches - * \version 3.1embedded - * \date 2007-2015 - */ -typedef struct -{ - Bounds *bounds; /**< Data structure for problem's bounds. */ - Constraints *constraints; /**< Data structure for problem's constraints. */ - - real_t *R; /**< Cholesky factor of H (i.e. H = R^T*R). */ - real_t *Q; /**< Orthonormal quadratic matrix, A = [0 T]*Q'. */ - real_t *T; /**< Reverse triangular matrix, A = [0 T]*Q'. */ - - unsigned int nV; /**< Number of variables. */ - unsigned int nC; /**< Number of constraints. */ -} Flipper; - -int Flipper_calculateMemorySize( unsigned int nV, unsigned int nC ); - -char *Flipper_assignMemory( unsigned int nV, unsigned int nC, Flipper **mem, void *raw_memory ); - -Flipper *Flipper_createMemory( unsigned int nV, unsigned int nC ); - -/** Constructor which takes the number of bounds and constraints. */ -void FlipperCON( Flipper* _THIS, - unsigned int _nV, /**< Number of bounds. */ - unsigned int _nC /**< Number of constraints. */ - ); - -/** Copy constructor (deep copy). */ -void FlipperCPY( Flipper* FROM, - Flipper* TO - ); - -/** Initialises object with given number of bounds and constraints. - * \return SUCCESSFUL_RETURN \n - RET_INVALID_ARGUMENTS */ -returnValue Flipper_init( Flipper* _THIS, - unsigned int _nV, /**< Number of bounds. */ - unsigned int _nC /**< Number of constraints. */ - ); - - -/** Copies current values to non-null arguments (assumed to be allocated with consistent size). - * \return SUCCESSFUL_RETURN */ -returnValue Flipper_get( Flipper* _THIS, - Bounds* const _bounds, /**< Pointer to new bounds. */ - real_t* const R, /**< New matrix R. */ - Constraints* const _constraints, /**< Pointer to new constraints. */ - real_t* const _Q, /**< New matrix Q. */ - real_t* const _T /**< New matrix T. */ - ); - -/** Assigns new values to non-null arguments. - * \return SUCCESSFUL_RETURN */ -returnValue Flipper_set( Flipper* _THIS, - const Bounds* const _bounds, /**< Pointer to new bounds. */ - const real_t* const _R, /**< New matrix R. */ - const Constraints* const _constraints, /**< Pointer to new constraints. */ - const real_t* const _Q, /**< New matrix Q. */ - const real_t* const _T /**< New matrix T. */ - ); - -/** Returns dimension of matrix T. - * \return Dimension of matrix T. */ -unsigned int Flipper_getDimT( Flipper* _THIS ); - - -END_NAMESPACE_QPOASES - - -#endif /* QPOASES_FLIPPER_H */ - - -/* - * end of file - */ diff --git a/third_party/acados/include/qpOASES_e/Indexlist.h b/third_party/acados/include/qpOASES_e/Indexlist.h deleted file mode 100644 index 02d259d63d..0000000000 --- a/third_party/acados/include/qpOASES_e/Indexlist.h +++ /dev/null @@ -1,221 +0,0 @@ -/* - * This file is part of qpOASES. - * - * qpOASES -- An Implementation of the Online Active Set Strategy. - * Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka, - * Christian Kirches et al. All rights reserved. - * - * qpOASES is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * qpOASES is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with qpOASES; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/** - * \file include/qpOASES_e/Indexlist.h - * \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches - * \version 3.1embedded - * \date 2007-2015 - * - * Declaration of the Indexlist class designed to manage index lists of - * constraints and bounds within a SubjectTo object. - */ - - -#ifndef QPOASES_INDEXLIST_H -#define QPOASES_INDEXLIST_H - - -#include - - -BEGIN_NAMESPACE_QPOASES - - -/** - * \brief Stores and manages index lists. - * - * This class manages index lists of active/inactive bounds/constraints. - * - * \author Hans Joachim Ferreau - * \version 3.1embedded - * \date 2007-2015 - */ -typedef struct -{ - int *number; /**< Array to store numbers of constraints or bounds. */ - int *iSort; /**< Index list to sort vector \a number */ - - int length; /**< Length of index list. */ - int first; /**< Physical index of first element. */ - int last; /**< Physical index of last element. */ - int lastusedindex; /**< Physical index of last entry in index list. */ - int physicallength; /**< Physical length of index list. */ -} Indexlist; - -int Indexlist_calculateMemorySize( int n); - -char *Indexlist_assignMemory(int n, Indexlist **mem, void *raw_memory); - -Indexlist *Indexlist_createMemory( int n ); - -/** Constructor which takes the desired physical length of the index list. */ -void IndexlistCON( Indexlist* _THIS, - int n /**< Physical length of index list. */ - ); - -/** Copies all members from given rhs object. - * \return SUCCESSFUL_RETURN */ -void IndexlistCPY( Indexlist* FROM, - Indexlist* TO - ); - -/** Initialises index list of desired physical length. - * \return SUCCESSFUL_RETURN \n - RET_INVALID_ARGUMENTS */ -returnValue Indexlist_init( Indexlist* _THIS, - int n /**< Physical length of index list. */ - ); - -/** Creates an array of all numbers within the index set in correct order. - * \return SUCCESSFUL_RETURN \n - RET_INDEXLIST_CORRUPTED */ -returnValue Indexlist_getNumberArray( Indexlist* _THIS, - int** const numberarray /**< Output: Array of numbers (NULL on error). */ - ); - -/** Creates an array of all numbers within the index set in correct order. - * \return SUCCESSFUL_RETURN \n - RET_INDEXLIST_CORRUPTED */ -returnValue Indexlist_getISortArray( Indexlist* _THIS, - int** const iSortArray /**< Output: iSort Array. */ - ); - - -/** Determines the index within the index list at which a given number is stored. - * \return >= 0: Index of given number. \n - -1: Number not found. */ -int Indexlist_getIndex( Indexlist* _THIS, - int givennumber /**< Number whose index shall be determined. */ - ); - -/** Returns the number stored at a given physical index. - * \return >= 0: Number stored at given physical index. \n - -RET_INDEXLIST_OUTOFBOUNDS */ -static inline int Indexlist_getNumber( Indexlist* _THIS, - int physicalindex /**< Physical index of the number to be returned. */ - ); - - -/** Returns the current length of the index list. - * \return Current length of the index list. */ -static inline int Indexlist_getLength( Indexlist* _THIS - ); - -/** Returns last number within the index list. - * \return Last number within the index list. */ -static inline int Indexlist_getLastNumber( Indexlist* _THIS - ); - - -/** Adds number to index list. - * \return SUCCESSFUL_RETURN \n - RET_INDEXLIST_MUST_BE_REORDERD \n - RET_INDEXLIST_EXCEEDS_MAX_LENGTH */ -returnValue Indexlist_addNumber( Indexlist* _THIS, - int addnumber /**< Number to be added. */ - ); - -/** Removes number from index list. - * \return SUCCESSFUL_RETURN */ -returnValue Indexlist_removeNumber( Indexlist* _THIS, - int removenumber /**< Number to be removed. */ - ); - -/** Swaps two numbers within index list. - * \return SUCCESSFUL_RETURN */ -returnValue Indexlist_swapNumbers( Indexlist* _THIS, - int number1, /**< First number for swapping. */ - int number2 /**< Second number for swapping. */ - ); - -/** Determines if a given number is contained in the index set. - * \return BT_TRUE iff number is contain in the index set */ -static inline BooleanType Indexlist_isMember( Indexlist* _THIS, - int _number /**< Number to be tested for membership. */ - ); - - -/** Find first index j between -1 and length in sorted list of indices - * iSort such that numbers[iSort[j]] <= i < numbers[iSort[j+1]]. Uses - * bisection. - * \return j. */ -int Indexlist_findInsert( Indexlist* _THIS, - int i - ); - - - -/* - * g e t N u m b e r - */ -static inline int Indexlist_getNumber( Indexlist* _THIS, int physicalindex ) -{ - /* consistency check */ - if ( ( physicalindex < 0 ) || ( physicalindex > _THIS->length ) ) - return -RET_INDEXLIST_OUTOFBOUNDS; - - return _THIS->number[physicalindex]; -} - - -/* - * g e t L e n g t h - */ -static inline int Indexlist_getLength( Indexlist* _THIS ) -{ - return _THIS->length; -} - - -/* - * g e t L a s t N u m b e r - */ -static inline int Indexlist_getLastNumber( Indexlist* _THIS ) -{ - return _THIS->number[_THIS->length-1]; -} - - -/* - * g e t L a s t N u m b e r - */ -static inline BooleanType Indexlist_isMember( Indexlist* _THIS, int _number ) -{ - if ( Indexlist_getIndex( _THIS,_number ) >= 0 ) - return BT_TRUE; - else - return BT_FALSE; -} - - -END_NAMESPACE_QPOASES - - -#endif /* QPOASES_INDEXLIST_H */ - - -/* - * end of file - */ diff --git a/third_party/acados/include/qpOASES_e/Matrices.h b/third_party/acados/include/qpOASES_e/Matrices.h deleted file mode 100644 index e2a46b3a9d..0000000000 --- a/third_party/acados/include/qpOASES_e/Matrices.h +++ /dev/null @@ -1,287 +0,0 @@ -/* - * This file is part of qpOASES. - * - * qpOASES -- An Implementation of the Online Active Set Strategy. - * Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka, - * Christian Kirches et al. All rights reserved. - * - * qpOASES is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * qpOASES is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with qpOASES; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/** - * \file include/qpOASES_e/Matrices.h - * \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches - * \version 3.1embedded - * \date 2009-2015 - * - * Various matrix classes: Abstract base matrix class, dense and sparse matrices, - * including symmetry exploiting specializations. - */ - - - -#ifndef QPOASES_MATRICES_H -#define QPOASES_MATRICES_H - -#ifdef __USE_SINGLE_PRECISION__ - - // single precision - #define GEMM sgemm_ - #define GEMV sgemv_ -// #define SYR ssyr_ -// #define SYR2 ssyr2_ - #define POTRF spotrf_ - -#else - - // double precision - #define GEMM dgemm_ - #define GEMV dgemv_ -// #define SYR dsyr_ -// #define SYR2 dsyr2_ - #define POTRF dpotrf_ - -#endif /* __USE_SINGLE_PRECISION__ */ - - -#ifdef EXTERNAL_BLAS - // double precision - void dgemm_(char *ta, char *tb, int *m, int *n, int *k, double *alpha, double *A, int *lda, double *B, int ldb, double *beta, double *C, int *ldc); - void dgemv_(char *ta, int *m, int *n, double *alpha, double *A, int *lda, double *x, int *incx, double *beta, double *y, int *incy); - void dpotrf_(char *uplo, int *m, double *A, int *lda, int *info); - // single precision - void sgemm_(char *ta, char *tb, int *m, int *n, int *k, float *alpha, float *A, int *lda, float *B, int ldb, float *beta, float *C, int *ldc); - void sgemv_(char *ta, int *m, int *n, float *alpha, float *A, int *lda, float *x, int *incx, float *beta, float *y, int *incy); - void spotrf_(char *uplo, int *m, float *A, int *lda, int *info); -#else - /** Performs one of the matrix-matrix operation in double precision. */ - void dgemm_ ( const char*, const char*, const unsigned long*, const unsigned long*, const unsigned long*, - const double*, const double*, const unsigned long*, const double*, const unsigned long*, - const double*, double*, const unsigned long* ); - /** Performs one of the matrix-matrix operation in single precision. */ - void sgemm_ ( const char*, const char*, const unsigned long*, const unsigned long*, const unsigned long*, - const float*, const float*, const unsigned long*, const float*, const unsigned long*, - const float*, float*, const unsigned long* ); - - /** Calculates the Cholesky factorization of a real symmetric positive definite matrix in double precision. */ - void dpotrf_ ( const char *, const unsigned long *, double *, const unsigned long *, long * ); - /** Calculates the Cholesky factorization of a real symmetric positive definite matrix in single precision. */ - void spotrf_ ( const char *, const unsigned long *, float *, const unsigned long *, long * ); - -#endif - - /** Performs a symmetric rank 1 operation in double precision. */ -// void dsyr_ ( const char *, const unsigned long *, const double *, const double *, -// const unsigned long *, double *, const unsigned long *); - /** Performs a symmetric rank 1 operation in single precision. */ -// void ssyr_ ( const char *, const unsigned long *, const float *, const float *, -// const unsigned long *, float *, const unsigned long *); - - /** Performs a symmetric rank 2 operation in double precision. */ -// void dsyr2_ ( const char *, const unsigned long *, const double *, const double *, -// const unsigned long *, const double *, const unsigned long *, double *, const unsigned long *); - /** Performs a symmetric rank 2 operation in single precision. */ -// void ssyr2_ ( const char *, const unsigned long *, const float *, const float *, -// const unsigned long *, const float *, const unsigned long *, float *, const unsigned long *); - - -#include - - -BEGIN_NAMESPACE_QPOASES - - -/** - * \brief Interfaces matrix-vector operations tailored to general dense matrices. - * - * Dense matrix class (row major format). - * - * \author Andreas Potschka, Christian Kirches, Hans Joachim Ferreau - * \version 3.1embedded - * \date 2011-2015 - */ -typedef struct -{ - real_t *val; /**< Vector of entries. */ - int nRows; /**< Number of rows. */ - int nCols; /**< Number of columns. */ - int leaDim; /**< Leading dimension. */ -} DenseMatrix; - -int DenseMatrix_calculateMemorySize( int m, int n ); - -char *DenseMatrix_assignMemory( int m, int n, DenseMatrix **mem, void *raw_memory ); - -DenseMatrix *DenseMatrix_createMemory( int m, int n ); - -/** Constructor from vector of values. - * Caution: Data pointer must be valid throughout lifetime - */ -void DenseMatrixCON( DenseMatrix* _THIS, - int m, /**< Number of rows. */ - int n, /**< Number of columns. */ - int lD, /**< Leading dimension. */ - real_t *v /**< Values. */ - ); - -void DenseMatrixCPY( DenseMatrix* FROM, - DenseMatrix* TO - ); - - -/** Frees all internal memory. */ -void DenseMatrix_free( DenseMatrix* _THIS ); - -/** Constructor from vector of values. - * Caution: Data pointer must be valid throughout lifetime - */ -returnValue DenseMatrix_init( DenseMatrix* _THIS, - int m, /**< Number of rows. */ - int n, /**< Number of columns. */ - int lD, /**< Leading dimension. */ - real_t *v /**< Values. */ - ); - - -/** Returns i-th diagonal entry. - * \return i-th diagonal entry */ -real_t DenseMatrix_diag( DenseMatrix* _THIS, - int i /**< Index. */ - ); - -/** Checks whether matrix is square and diagonal. - * \return BT_TRUE iff matrix is square and diagonal; \n - * BT_FALSE otherwise. */ -BooleanType DenseMatrix_isDiag( DenseMatrix* _THIS ); - -/** Get the N-norm of the matrix - * \return N-norm of the matrix - */ -real_t DenseMatrix_getNorm( DenseMatrix* _THIS, - int type /**< Norm type, 1: one-norm, 2: Euclidean norm. */ - ); - -/** Get the N-norm of a row - * \return N-norm of row \a rNum - */ -real_t DenseMatrix_getRowNorm( DenseMatrix* _THIS, - int rNum, /**< Row number. */ - int type /**< Norm type, 1: one-norm, 2: Euclidean norm. */ - ); - -/** Retrieve indexed entries of matrix row multiplied by alpha. - * \return SUCCESSFUL_RETURN */ -returnValue DenseMatrix_getRow( DenseMatrix* _THIS, - int rNum, /**< Row number. */ - const Indexlist* const icols, /**< Index list specifying columns. */ - real_t alpha, /**< Scalar factor. */ - real_t *row /**< Output row vector. */ - ); - -/** Retrieve indexed entries of matrix column multiplied by alpha. - * \return SUCCESSFUL_RETURN */ - returnValue DenseMatrix_getCol( DenseMatrix* _THIS, - int cNum, /**< Column number. */ - const Indexlist* const irows, /**< Index list specifying rows. */ - real_t alpha, /**< Scalar factor. */ - real_t *col /**< Output column vector. */ - ); - -/** Evaluate Y=alpha*A*X + beta*Y. - * \return SUCCESSFUL_RETURN. */ -returnValue DenseMatrix_times( DenseMatrix* _THIS, - int xN, /**< Number of vectors to multiply. */ - real_t alpha, /**< Scalar factor for matrix vector product. */ - const real_t *x, /**< Input vector to be multiplied. */ - int xLD, /**< Leading dimension of input x. */ - real_t beta, /**< Scalar factor for y. */ - real_t *y, /**< Output vector of results. */ - int yLD /**< Leading dimension of output y. */ - ); - -/** Evaluate Y=alpha*A'*X + beta*Y. - * \return SUCCESSFUL_RETURN. */ -returnValue DenseMatrix_transTimes( DenseMatrix* _THIS, - int xN, /**< Number of vectors to multiply. */ - real_t alpha, /**< Scalar factor for matrix vector product. */ - const real_t *x, /**< Input vector to be multiplied. */ - int xLD, /**< Leading dimension of input x. */ - real_t beta, /**< Scalar factor for y. */ - real_t *y, /**< Output vector of results. */ - int yLD /**< Leading dimension of output y. */ - ); - -/** Evaluate matrix vector product with submatrix given by Indexlist. - * \return SUCCESSFUL_RETURN */ - returnValue DenseMatrix_subTimes( DenseMatrix* _THIS, - const Indexlist* const irows, /**< Index list specifying rows. */ - const Indexlist* const icols, /**< Index list specifying columns. */ - int xN, /**< Number of vectors to multiply. */ - real_t alpha, /**< Scalar factor for matrix vector product. */ - const real_t *x, /**< Input vector to be multiplied. */ - int xLD, /**< Leading dimension of input x. */ - real_t beta, /**< Scalar factor for y. */ - real_t *y, /**< Output vector of results. */ - int yLD, /**< Leading dimension of output y. */ - BooleanType yCompr /**< Compressed storage for y. */ - ); - -/** Evaluate matrix transpose vector product. - * \return SUCCESSFUL_RETURN */ -returnValue DenseMatrix_subTransTimes( DenseMatrix* _THIS, - const Indexlist* const irows, /**< Index list specifying rows. */ - const Indexlist* const icols, /**< Index list specifying columns. */ - int xN, /**< Number of vectors to multiply. */ - real_t alpha, /**< Scalar factor for matrix vector product. */ - const real_t *x, /**< Input vector to be multiplied. */ - int xLD, /**< Leading dimension of input x. */ - real_t beta, /**< Scalar factor for y. */ - real_t *y, /**< Output vector of results. */ - int yLD /**< Leading dimension of output y. */ - ); - -/** Adds given offset to diagonal of matrix. - * \return SUCCESSFUL_RETURN \n - RET_NO_DIAGONAL_AVAILABLE */ -returnValue DenseMatrix_addToDiag( DenseMatrix* _THIS, - real_t alpha /**< Diagonal offset. */ - ); - -/** Prints matrix to screen. - * \return SUCCESSFUL_RETURN */ -returnValue DenseMatrix_print( DenseMatrix* _THIS - ); - -static inline real_t* DenseMatrix_getVal( DenseMatrix* _THIS ) { return _THIS->val; } - -/** Compute bilinear form y = x'*H*x using submatrix given by index list. - * \return SUCCESSFUL_RETURN */ -returnValue DenseMatrix_bilinear( DenseMatrix* _THIS, - const Indexlist* const icols, /**< Index list specifying columns of x. */ - int xN, /**< Number of vectors to multiply. */ - const real_t *x, /**< Input vector to be multiplied (uncompressed). */ - int xLD, /**< Leading dimension of input x. */ - real_t *y, /**< Output vector of results (compressed). */ - int yLD /**< Leading dimension of output y. */ - ); - - - -END_NAMESPACE_QPOASES - - -#endif /* QPOASES_MATRICES_H */ diff --git a/third_party/acados/include/qpOASES_e/MessageHandling.h b/third_party/acados/include/qpOASES_e/MessageHandling.h deleted file mode 100644 index fe5524948a..0000000000 --- a/third_party/acados/include/qpOASES_e/MessageHandling.h +++ /dev/null @@ -1,544 +0,0 @@ -/* - * This file is part of qpOASES. - * - * qpOASES -- An Implementation of the Online Active Set Strategy. - * Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka, - * Christian Kirches et al. All rights reserved. - * - * qpOASES is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * qpOASES is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with qpOASES; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/** - * \file include/qpOASES_e/MessageHandling.h - * \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches (thanks to Leonard Wirsching) - * \version 3.1embedded - * \date 2007-2015 - * - * Declaration of the MessageHandling class including global return values. - */ - - -#ifndef QPOASES_MESSAGEHANDLING_H -#define QPOASES_MESSAGEHANDLING_H - - -#include -#include -#include -#include - -#include - - -BEGIN_NAMESPACE_QPOASES - - -/** Default file to display messages. */ -#define stdFile stderr - - -/** - * \brief Defines all symbols for global return values. - * - * The enumeration returnValueType defines all symbols for global return values. - * Important: All return values are assumed to be nonnegative! - * - * \author Hans Joachim Ferreau - */ -typedef enum -{ -TERMINAL_LIST_ELEMENT = -1, /**< Terminal list element, internal usage only! */ -/* miscellaneous */ -SUCCESSFUL_RETURN = 0, /**< Successful return. */ -RET_DIV_BY_ZERO, /**< Division by zero. */ -RET_INDEX_OUT_OF_BOUNDS, /**< Index out of bounds. */ -RET_INVALID_ARGUMENTS, /**< At least one of the arguments is invalid. */ -RET_ERROR_UNDEFINED, /**< Error number undefined. */ -RET_WARNING_UNDEFINED, /**< Warning number undefined. */ -RET_INFO_UNDEFINED, /**< Info number undefined. */ -RET_EWI_UNDEFINED, /**< Error/warning/info number undefined. */ -RET_AVAILABLE_WITH_LINUX_ONLY, /**< This function is available under Linux only. */ -RET_UNKNOWN_BUG, /**< The error occurred is not yet known. */ -RET_PRINTLEVEL_CHANGED, /**< Print level changed. (10) */ -RET_NOT_YET_IMPLEMENTED, /**< Requested function is not yet implemented in this version of qpOASES. */ -/* Indexlist */ -RET_INDEXLIST_MUST_BE_REORDERD, /**< Index list has to be reordered. */ -RET_INDEXLIST_EXCEEDS_MAX_LENGTH, /**< Index list exceeds its maximal physical length. */ -RET_INDEXLIST_CORRUPTED, /**< Index list corrupted. */ -RET_INDEXLIST_OUTOFBOUNDS, /**< Physical index is out of bounds. */ -RET_INDEXLIST_ADD_FAILED, /**< Adding indices from another index set failed. */ -RET_INDEXLIST_INTERSECT_FAILED, /**< Intersection with another index set failed. */ -/* SubjectTo / Bounds / Constraints */ -RET_INDEX_ALREADY_OF_DESIRED_STATUS, /**< Index is already of desired status. (18) */ -RET_ADDINDEX_FAILED, /**< Adding index to index set failed. */ -RET_REMOVEINDEX_FAILED, /**< Removing index from index set failed. (20) */ -RET_SWAPINDEX_FAILED, /**< Cannot swap between different indexsets. */ -RET_NOTHING_TO_DO, /**< Nothing to do. */ -RET_SETUP_BOUND_FAILED, /**< Setting up bound index failed. */ -RET_SETUP_CONSTRAINT_FAILED, /**< Setting up constraint index failed. */ -RET_MOVING_BOUND_FAILED, /**< Moving bound between index sets failed. */ -RET_MOVING_CONSTRAINT_FAILED, /**< Moving constraint between index sets failed. */ -RET_SHIFTING_FAILED, /**< Shifting of bounds/constraints failed. */ -RET_ROTATING_FAILED, /**< Rotating of bounds/constraints failed. */ -/* QProblem */ -RET_QPOBJECT_NOT_SETUP, /**< The QP object has not been setup correctly, use another constructor. */ -RET_QP_ALREADY_INITIALISED, /**< QProblem has already been initialised. (30) */ -RET_NO_INIT_WITH_STANDARD_SOLVER, /**< Initialisation via extern QP solver is not yet implemented. */ -RET_RESET_FAILED, /**< Reset failed. */ -RET_INIT_FAILED, /**< Initialisation failed. */ -RET_INIT_FAILED_TQ, /**< Initialisation failed due to TQ factorisation. */ -RET_INIT_FAILED_CHOLESKY, /**< Initialisation failed due to Cholesky decomposition. */ -RET_INIT_FAILED_HOTSTART, /**< Initialisation failed! QP could not be solved! */ -RET_INIT_FAILED_INFEASIBILITY, /**< Initial QP could not be solved due to infeasibility! */ -RET_INIT_FAILED_UNBOUNDEDNESS, /**< Initial QP could not be solved due to unboundedness! */ -RET_INIT_FAILED_REGULARISATION, /**< Initialisation failed as Hessian matrix could not be regularised. */ -RET_INIT_SUCCESSFUL, /**< Initialisation done. (40) */ -RET_OBTAINING_WORKINGSET_FAILED, /**< Failed to obtain working set for auxiliary QP. */ -RET_SETUP_WORKINGSET_FAILED, /**< Failed to setup working set for auxiliary QP. */ -RET_SETUP_AUXILIARYQP_FAILED, /**< Failed to setup auxiliary QP for initialised homotopy. */ -RET_NO_CHOLESKY_WITH_INITIAL_GUESS, /**< Externally computed Cholesky factor cannot be combined with an initial guess. */ -RET_NO_EXTERN_SOLVER, /**< No extern QP solver available. */ -RET_QP_UNBOUNDED, /**< QP is unbounded. */ -RET_QP_INFEASIBLE, /**< QP is infeasible. */ -RET_QP_NOT_SOLVED, /**< Problems occurred while solving QP with standard solver. */ -RET_QP_SOLVED, /**< QP successfully solved. */ -RET_UNABLE_TO_SOLVE_QP, /**< Problems occurred while solving QP. (50) */ -RET_INITIALISATION_STARTED, /**< Starting problem initialisation... */ -RET_HOTSTART_FAILED, /**< Unable to perform homotopy due to internal error. */ -RET_HOTSTART_FAILED_TO_INIT, /**< Unable to initialise problem. */ -RET_HOTSTART_FAILED_AS_QP_NOT_INITIALISED, /**< Unable to perform homotopy as previous QP is not solved. */ -RET_ITERATION_STARTED, /**< Iteration... */ -RET_SHIFT_DETERMINATION_FAILED, /**< Determination of shift of the QP data failed. */ -RET_STEPDIRECTION_DETERMINATION_FAILED, /**< Determination of step direction failed. */ -RET_STEPLENGTH_DETERMINATION_FAILED, /**< Determination of step direction failed. */ -RET_OPTIMAL_SOLUTION_FOUND, /**< Optimal solution of neighbouring QP found. */ -RET_HOMOTOPY_STEP_FAILED, /**< Unable to perform homotopy step. (60) */ -RET_HOTSTART_STOPPED_INFEASIBILITY, /**< Premature homotopy termination because QP is infeasible. */ -RET_HOTSTART_STOPPED_UNBOUNDEDNESS, /**< Premature homotopy termination because QP is unbounded. */ -RET_WORKINGSET_UPDATE_FAILED, /**< Unable to update working sets according to initial guesses. */ -RET_MAX_NWSR_REACHED, /**< Maximum number of working set recalculations performed. */ -RET_CONSTRAINTS_NOT_SPECIFIED, /**< Problem does comprise constraints! You also have to specify new constraints' bounds. */ -RET_INVALID_FACTORISATION_FLAG, /**< Invalid factorisation flag. */ -RET_UNABLE_TO_SAVE_QPDATA, /**< Unable to save QP data. */ -RET_STEPDIRECTION_FAILED_TQ, /**< Abnormal termination due to TQ factorisation. */ -RET_STEPDIRECTION_FAILED_CHOLESKY, /**< Abnormal termination due to Cholesky factorisation. */ -RET_CYCLING_DETECTED, /**< Cycling detected. (70) */ -RET_CYCLING_NOT_RESOLVED, /**< Cycling cannot be resolved, QP probably infeasible. */ -RET_CYCLING_RESOLVED, /**< Cycling probably resolved. */ -RET_STEPSIZE, /**< For displaying performed stepsize. */ -RET_STEPSIZE_NONPOSITIVE, /**< For displaying non-positive stepsize. */ -RET_SETUPSUBJECTTOTYPE_FAILED, /**< Setup of SubjectToTypes failed. */ -RET_ADDCONSTRAINT_FAILED, /**< Addition of constraint to working set failed. */ -RET_ADDCONSTRAINT_FAILED_INFEASIBILITY, /**< Addition of constraint to working set failed (due to QP infeasibility). */ -RET_ADDBOUND_FAILED, /**< Addition of bound to working set failed. */ -RET_ADDBOUND_FAILED_INFEASIBILITY, /**< Addition of bound to working set failed (due to QP infeasibility). */ -RET_REMOVECONSTRAINT_FAILED, /**< Removal of constraint from working set failed. (80) */ -RET_REMOVEBOUND_FAILED, /**< Removal of bound from working set failed. */ -RET_REMOVE_FROM_ACTIVESET, /**< Removing from active set... */ -RET_ADD_TO_ACTIVESET, /**< Adding to active set... */ -RET_REMOVE_FROM_ACTIVESET_FAILED, /**< Removing from active set failed. */ -RET_ADD_TO_ACTIVESET_FAILED, /**< Adding to active set failed. */ -RET_CONSTRAINT_ALREADY_ACTIVE, /**< Constraint is already active. */ -RET_ALL_CONSTRAINTS_ACTIVE, /**< All constraints are active, no further constraint can be added. */ -RET_LINEARLY_DEPENDENT, /**< New bound/constraint is linearly dependent. */ -RET_LINEARLY_INDEPENDENT, /**< New bound/constraint is linearly independent. */ -RET_LI_RESOLVED, /**< Linear independence of active constraint matrix successfully resolved. (90) */ -RET_ENSURELI_FAILED, /**< Failed to ensure linear independence of active constraint matrix. */ -RET_ENSURELI_FAILED_TQ, /**< Abnormal termination due to TQ factorisation. */ -RET_ENSURELI_FAILED_NOINDEX, /**< QP is infeasible. */ -RET_ENSURELI_FAILED_CYCLING, /**< QP is infeasible. */ -RET_BOUND_ALREADY_ACTIVE, /**< Bound is already active. */ -RET_ALL_BOUNDS_ACTIVE, /**< All bounds are active, no further bound can be added. */ -RET_CONSTRAINT_NOT_ACTIVE, /**< Constraint is not active. */ -RET_BOUND_NOT_ACTIVE, /**< Bound is not active. */ -RET_HESSIAN_NOT_SPD, /**< Projected Hessian matrix not positive definite. */ -RET_HESSIAN_INDEFINITE, /**< Hessian matrix is indefinite. (100) */ -RET_MATRIX_SHIFT_FAILED, /**< Unable to update matrices or to transform vectors. */ -RET_MATRIX_FACTORISATION_FAILED, /**< Unable to calculate new matrix factorisations. */ -RET_PRINT_ITERATION_FAILED, /**< Unable to print information on current iteration. */ -RET_NO_GLOBAL_MESSAGE_OUTPUTFILE, /**< No global message output file initialised. */ -RET_DISABLECONSTRAINTS_FAILED, /**< Unable to disbable constraints. */ -RET_ENABLECONSTRAINTS_FAILED, /**< Unable to enbable constraints. */ -RET_ALREADY_ENABLED, /**< Bound or constraint is already enabled. */ -RET_ALREADY_DISABLED, /**< Bound or constraint is already disabled. */ -RET_NO_HESSIAN_SPECIFIED, /**< No Hessian matrix has been specified. */ -RET_USING_REGULARISATION, /**< Using regularisation as Hessian matrix is not positive definite. (110) */ -RET_EPS_MUST_BE_POSITVE, /**< Eps for regularisation must be sufficiently positive. */ -RET_REGSTEPS_MUST_BE_POSITVE, /**< Maximum number of regularisation steps must be non-negative. */ -RET_HESSIAN_ALREADY_REGULARISED, /**< Hessian has been already regularised. */ -RET_CANNOT_REGULARISE_IDENTITY, /**< Identity Hessian matrix cannot be regularised. */ -RET_CANNOT_REGULARISE_SPARSE, /**< Sparse matrix cannot be regularised as diagonal entry is missing. */ -RET_NO_REGSTEP_NWSR, /**< No additional regularisation step could be performed due to limits. */ -RET_FEWER_REGSTEPS_NWSR, /**< Fewer additional regularisation steps have been performed due to limits. */ -RET_CHOLESKY_OF_ZERO_HESSIAN, /**< Cholesky decomposition of (unregularised) zero Hessian matrix. */ -RET_ZERO_HESSIAN_ASSUMED, /**< Zero Hessian matrix assumed as null pointer passed without specifying hessianType. */ -RET_CONSTRAINTS_ARE_NOT_SCALED, /**< (no longer in use) (120) */ -RET_INITIAL_BOUNDS_STATUS_NYI, /**< (no longer in use) */ -RET_ERROR_IN_CONSTRAINTPRODUCT, /**< Error in user-defined constraint product function. */ -RET_FIX_BOUNDS_FOR_LP, /**< All initial bounds must be fixed when solving an (unregularised) LP. */ -RET_USE_REGULARISATION_FOR_LP, /**< Set options.enableRegularisation=BT_TRUE for solving LPs. */ -/* SQProblem */ -RET_UPDATEMATRICES_FAILED, /**< Unable to update QP matrices. */ -RET_UPDATEMATRICES_FAILED_AS_QP_NOT_SOLVED, /**< Unable to update matrices as previous QP is not solved. */ -/* Utils */ -RET_UNABLE_TO_OPEN_FILE, /**< Unable to open file. */ -RET_UNABLE_TO_WRITE_FILE, /**< Unable to write into file. */ -RET_UNABLE_TO_READ_FILE, /**< Unable to read from file. */ -RET_FILEDATA_INCONSISTENT, /**< File contains inconsistent data. (130) */ -/* Options */ -RET_OPTIONS_ADJUSTED, /**< Options needed to be adjusted for consistency reasons. */ -/* SolutionAnalysis */ -RET_UNABLE_TO_ANALYSE_QPROBLEM, /**< Unable to analyse (S)QProblem(B) object. */ -/* Benchmark */ -RET_NWSR_SET_TO_ONE, /**< Maximum number of working set changes was set to 1. */ -RET_UNABLE_TO_READ_BENCHMARK, /**< Unable to read benchmark data. */ -RET_BENCHMARK_ABORTED, /**< Benchmark aborted. */ -RET_INITIAL_QP_SOLVED, /**< Initial QP solved. */ -RET_QP_SOLUTION_STARTED, /**< Solving QP... */ -RET_BENCHMARK_SUCCESSFUL, /**< Benchmark terminated successfully. */ -/* Sparse matrices */ -RET_NO_DIAGONAL_AVAILABLE, /**< Sparse matrix does not have entries on full diagonal. */ -RET_DIAGONAL_NOT_INITIALISED, /**< Diagonal data of sparse matrix has not been initialised. (140) */ -/* Dropping of infeasible constraints */ -RET_ENSURELI_DROPPED, /**< Linear independence resolved by dropping blocking constraint. */ -/* Simple exitflags */ -RET_SIMPLE_STATUS_P1, /**< QP problem could not be solved within given number of iterations. */ -RET_SIMPLE_STATUS_P0, /**< QP problem solved. */ -RET_SIMPLE_STATUS_M1, /**< QP problem could not be solved due to an internal error. */ -RET_SIMPLE_STATUS_M2, /**< QP problem is infeasible (and thus could not be solved). */ -RET_SIMPLE_STATUS_M3 /**< QP problem is unbounded (and thus could not be solved). (146) */ -} returnValue; - - -/** - * \brief Data structure for entries in global message list. - * - * Data structure for entries in global message list. - * - * \author Hans Joachim Ferreau - * \version 3.1embedded - * \date 2007-2015 - */ -typedef struct -{ - returnValue key; /**< Global return value. */ - const char* data; /**< Corresponding message. */ - VisibilityStatus globalVisibilityStatus; /**< Determines if message can be printed. - * If this value is set to VS_HIDDEN, no message is printed! */ -} ReturnValueList; - - - -/** - * \brief Handles all kind of error messages, warnings and other information. - * - * This class handles all kinds of messages (errors, warnings, infos) initiated - * by qpOASES modules and stores the corresponding global preferences. - * - * \author Hans Joachim Ferreau (thanks to Leonard Wirsching) - * \version 3.1embedded - * \date 2007-2015 - */ -typedef struct -{ - VisibilityStatus errorVisibility; /**< Error messages visible? */ - VisibilityStatus warningVisibility; /**< Warning messages visible? */ - VisibilityStatus infoVisibility; /**< Info messages visible? */ - - FILE* outputFile; /**< Output file for messages. */ - - int errorCount; /**< Counts number of errors (for nicer output only). */ -} MessageHandling; - - - -/** Constructor which takes the desired output file and desired visibility states. */ -void MessageHandlingCON( MessageHandling* _THIS, - FILE* _outputFile, /**< Output file. */ - VisibilityStatus _errorVisibility, /**< Visibility status for error messages. */ - VisibilityStatus _warningVisibility,/**< Visibility status for warning messages. */ - VisibilityStatus _infoVisibility /**< Visibility status for info messages. */ - ); - -void MessageHandlingCPY( MessageHandling* FROM, - MessageHandling* TO - ); - - -/** Prints an error message(a simplified macro THROWERROR is also provided). \n - * Errors are definied as abnormal events which cause an immediate termination of the current (sub) function. - * Errors of a sub function should be commented by the calling function by means of a warning message - * (if this error does not cause an error of the calling function, either)! - * \return Error number returned by sub function call - */ -returnValue MessageHandling_throwError( MessageHandling* _THIS, - returnValue Enumber, /**< Error number returned by sub function call. */ - const char* additionaltext, /**< Additional error text (0, if none). */ - const char* functionname, /**< Name of function which caused the error. */ - const char* filename, /**< Name of file which caused the error. */ - const unsigned long linenumber, /**< Number of line which caused the error.incompatible binary file */ - VisibilityStatus localVisibilityStatus /**< Determines (locally) if error message can be printed to stderr. - * If GLOBAL visibility status of the message is set to VS_HIDDEN, - * no message is printed, anyway! */ - ); - -/** Prints a warning message (a simplified macro THROWWARNING is also provided). - * Warnings are definied as abnormal events which does NOT cause an immediate termination of the current (sub) function. - * \return Warning number returned by sub function call - */ -returnValue MessageHandling_throwWarning( MessageHandling* _THIS, - returnValue Wnumber, /**< Warning number returned by sub function call. */ - const char* additionaltext, /**< Additional warning text (0, if none). */ - const char* functionname, /**< Name of function which caused the warning. */ - const char* filename, /**< Name of file which caused the warning. */ - const unsigned long linenumber, /**< Number of line which caused the warning. */ - VisibilityStatus localVisibilityStatus /**< Determines (locally) if warning message can be printed to stderr. - * If GLOBAL visibility status of the message is set to VS_HIDDEN, - * no message is printed, anyway! */ - ); - -/** Prints a info message (a simplified macro THROWINFO is also provided). - * \return Info number returned by sub function call - */ -returnValue MessageHandling_throwInfo( MessageHandling* _THIS, - returnValue Inumber, /**< Info number returned by sub function call. */ - const char* additionaltext, /**< Additional warning text (0, if none). */ - const char* functionname, /**< Name of function which submitted the info. */ - const char* filename, /**< Name of file which submitted the info. */ - const unsigned long linenumber, /**< Number of line which submitted the info. */ - VisibilityStatus localVisibilityStatus /**< Determines (locally) if info message can be printed to stderr. - * If GLOBAL visibility status of the message is set to VS_HIDDEN, - * no message is printed, anyway! */ - ); - - -/** Resets all preferences to default values. - * \return SUCCESSFUL_RETURN */ -returnValue MessageHandling_reset( MessageHandling* _THIS ); - - -/** Prints a complete list of all messages to output file. - * \return SUCCESSFUL_RETURN */ -returnValue MessageHandling_listAllMessages( MessageHandling* _THIS ); - - -/** Returns visibility status for error messages. - * \return Visibility status for error messages. */ -static inline VisibilityStatus MessageHandling_getErrorVisibilityStatus( MessageHandling* _THIS ); - -/** Returns visibility status for warning messages. - * \return Visibility status for warning messages. */ -static inline VisibilityStatus MessageHandling_getWarningVisibilityStatus( MessageHandling* _THIS ); - -/** Returns visibility status for info messages. - * \return Visibility status for info messages. */ -static inline VisibilityStatus MessageHandling_getInfoVisibilityStatus( MessageHandling* _THIS ); - -/** Returns pointer to output file. - * \return Pointer to output file. */ -static inline FILE* MessageHandling_getOutputFile( MessageHandling* _THIS ); - -/** Returns error count value. - * \return Error count value. */ -static inline int MessageHandling_getErrorCount( MessageHandling* _THIS ); - - -/** Changes visibility status for error messages. */ -static inline void MessageHandling_setErrorVisibilityStatus( MessageHandling* _THIS, - VisibilityStatus _errorVisibility /**< New visibility status for error messages. */ - ); - -/** Changes visibility status for warning messages. */ -static inline void MessageHandling_setWarningVisibilityStatus( MessageHandling* _THIS, - VisibilityStatus _warningVisibility /**< New visibility status for warning messages. */ - ); - -/** Changes visibility status for info messages. */ -static inline void MessageHandling_setInfoVisibilityStatus( MessageHandling* _THIS, - VisibilityStatus _infoVisibility /**< New visibility status for info messages. */ - ); - -/** Changes output file for messages. */ -static inline void MessageHandling_setOutputFile( MessageHandling* _THIS, - FILE* _outputFile /**< New output file for messages. */ - ); - -/** Changes error count. - * \return SUCCESSFUL_RETURN \n - * RET_INVALID_ARGUMENT */ -static inline returnValue MessageHandling_setErrorCount( MessageHandling* _THIS, - int _errorCount /**< New error count value. */ - ); - -/** Provides message text corresponding to given \a returnValue. - * \return String containing message text. */ -const char* MessageHandling_getErrorCodeMessage( MessageHandling* _THIS, - const returnValue _returnValue - ); - - -returnValue MessageHandling_throwMessage( MessageHandling* _THIS, - returnValue RETnumber, /**< Error/warning/info number returned by sub function call. */ - const char* additionaltext, /**< Additional warning text (0, if none). */ - const char* functionname, /**< Name of function which caused the error/warning/info. */ - const char* filename, /**< Name of file which caused the error/warning/info. */ - const unsigned long linenumber, /**< Number of line which caused the error/warning/info. */ - VisibilityStatus localVisibilityStatus, /**< Determines (locally) if info message can be printed to stderr. - * If GLOBAL visibility status of the message is set to VS_HIDDEN, - * no message is printed, anyway! */ - const char* RETstring /**< Leading string of error/warning/info message. */ - ); - - -#ifndef __FILE__ - /** Ensures that __FILE__ macro is defined. */ - #define __FILE__ 0 -#endif - -#ifndef __LINE__ - /** Ensures that __LINE__ macro is defined. */ - #define __LINE__ 0 -#endif - -/** Define __FUNC__ macro providing current function for debugging. */ -/*#define __FUNC__ 0*/ -#define __FUNC__ ("(no function name provided)") -/*#define __FUNC__ __func__*/ -/*#define __FUNC__ __FUNCTION__*/ - - -/** Short version of throwError with default values, only returnValue is needed */ -#define THROWERROR(retval) ( MessageHandling_throwError( qpOASES_getGlobalMessageHandler(),(retval),0,__FUNC__,__FILE__,__LINE__,VS_VISIBLE) ) - -/** Short version of throwWarning with default values, only returnValue is needed */ -#define THROWWARNING(retval) ( MessageHandling_throwWarning( qpOASES_getGlobalMessageHandler(),(retval),0,__FUNC__,__FILE__,__LINE__,VS_VISIBLE) ) - -/** Short version of throwInfo with default values, only returnValue is needed */ -#define THROWINFO(retval) ( MessageHandling_throwInfo( qpOASES_getGlobalMessageHandler(),(retval),0,__FUNC__,__FILE__,__LINE__,VS_VISIBLE) ) - - -/** Returns a pointer to global message handler. - * \return Pointer to global message handler. - */ -MessageHandling* qpOASES_getGlobalMessageHandler( ); - - -/* - * g e t E r r o r V i s i b i l i t y S t a t u s - */ -static inline VisibilityStatus MessageHandling_getErrorVisibilityStatus( MessageHandling* _THIS ) -{ - return _THIS->errorVisibility; -} - - -/* - * g e t W a r n i n g V i s i b i l i t y S t a t u s - */ -static inline VisibilityStatus MessageHandling_getWarningVisibilityStatus( MessageHandling* _THIS ) -{ - return _THIS->warningVisibility; -} - - -/* - * g e t I n f o V i s i b i l i t y S t a t u s - */ -static inline VisibilityStatus MessageHandling_getInfoVisibilityStatus( MessageHandling* _THIS ) -{ - return _THIS->infoVisibility; -} - - -/* - * g e t O u t p u t F i l e - */ -static inline FILE* MessageHandling_getOutputFile( MessageHandling* _THIS ) -{ - return _THIS->outputFile; -} - - -/* - * g e t E r r o r C o u n t - */ -static inline int MessageHandling_getErrorCount( MessageHandling* _THIS ) -{ - return _THIS->errorCount; -} - - -/* - * s e t E r r o r V i s i b i l i t y S t a t u s - */ -static inline void MessageHandling_setErrorVisibilityStatus( MessageHandling* _THIS, VisibilityStatus _errorVisibility ) -{ - _THIS->errorVisibility = _errorVisibility; -} - - -/* - * s e t W a r n i n g V i s i b i l i t y S t a t u s - */ -static inline void MessageHandling_setWarningVisibilityStatus( MessageHandling* _THIS, VisibilityStatus _warningVisibility ) -{ - _THIS->warningVisibility = _warningVisibility; -} - - -/* - * s e t I n f o V i s i b i l i t y S t a t u s - */ -static inline void MessageHandling_setInfoVisibilityStatus( MessageHandling* _THIS, VisibilityStatus _infoVisibility ) -{ - _THIS->infoVisibility = _infoVisibility; -} - - -/* - * s e t O u t p u t F i l e - */ -static inline void MessageHandling_setOutputFile( MessageHandling* _THIS, FILE* _outputFile ) -{ - _THIS->outputFile = _outputFile; -} - - -/* - * s e t E r r o r C o u n t - */ -static inline returnValue MessageHandling_setErrorCount( MessageHandling* _THIS, int _errorCount ) -{ - if ( _errorCount >= 0 ) - { - _THIS->errorCount = _errorCount; - return SUCCESSFUL_RETURN; - } - else - return RET_INVALID_ARGUMENTS; -} - - -END_NAMESPACE_QPOASES - - -#endif /* QPOASES_MESSAGEHANDLING_H */ - - -/* - * end of file - */ diff --git a/third_party/acados/include/qpOASES_e/Options.h b/third_party/acados/include/qpOASES_e/Options.h deleted file mode 100644 index ca8086d2cc..0000000000 --- a/third_party/acados/include/qpOASES_e/Options.h +++ /dev/null @@ -1,153 +0,0 @@ -/* - * This file is part of qpOASES. - * - * qpOASES -- An Implementation of the Online Active Set Strategy. - * Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka, - * Christian Kirches et al. All rights reserved. - * - * qpOASES is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * qpOASES is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with qpOASES; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/** - * \file include/qpOASES_e/Options.h - * \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches - * \version 3.1embedded - * \date 2007-2015 - * - * Declaration of the Options class designed to manage user-specified - * options for solving a QProblem. - */ - - -#ifndef QPOASES_OPTIONS_H -#define QPOASES_OPTIONS_H - - -#include - - -BEGIN_NAMESPACE_QPOASES - - -/** - * \brief Manages all user-specified options for solving QPs. - * - * This class manages all user-specified options used for solving - * quadratic programs. - * - * \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches - * \version 3.1embedded - * \date 2007-2015 - */ -typedef struct -{ - PrintLevel printLevel; /**< Print level. */ - - BooleanType enableRamping; /**< Specifies whether ramping shall be enabled or not. */ - BooleanType enableFarBounds; /**< Specifies whether far bounds shall be used or not. */ - BooleanType enableFlippingBounds; /**< Specifies whether flipping bounds shall be used or not. */ - BooleanType enableRegularisation; /**< Specifies whether Hessian matrix shall be regularised in case semi-definiteness is detected. */ - BooleanType enableFullLITests; /**< Specifies whether condition-hardened LI test shall be used or not. */ - BooleanType enableNZCTests; /**< Specifies whether nonzero curvature tests shall be used. */ - int enableDriftCorrection; /**< Specifies the frequency of drift corrections (0 = off). */ - int enableCholeskyRefactorisation; /**< Specifies the frequency of full refactorisation of proj. Hessian (otherwise updates). */ - BooleanType enableEqualities; /**< Specifies whether equalities shall be always treated as active constraints. */ - - real_t terminationTolerance; /**< Termination tolerance. */ - real_t boundTolerance; /**< Lower/upper (constraints') bound tolerance (an inequality constraint whose lower and upper bounds differ by less is regarded to be an equality constraint). */ - real_t boundRelaxation; /**< Offset for relaxing (constraints') bounds at beginning of an initial homotopy. It is also as initial value for far bounds. */ - real_t epsNum; /**< Numerator tolerance for ratio tests. */ - real_t epsDen; /**< Denominator tolerance for ratio tests. */ - real_t maxPrimalJump; /**< Maximum allowed jump in primal variables in nonzero curvature tests. */ - real_t maxDualJump; /**< Maximum allowed jump in dual variables in linear independence tests. */ - - real_t initialRamping; /**< Start value for Ramping Strategy. */ - real_t finalRamping; /**< Final value for Ramping Strategy. */ - real_t initialFarBounds; /**< Initial size of Far Bounds. */ - real_t growFarBounds; /**< Factor to grow Far Bounds. */ - SubjectToStatus initialStatusBounds; /**< Initial status of bounds at first iteration. */ - real_t epsFlipping; /**< Tolerance of squared Cholesky diagonal factor which triggers flipping bound. */ - int numRegularisationSteps; /**< Maximum number of successive regularisation steps. */ - real_t epsRegularisation; /**< Scaling factor of identity matrix used for Hessian regularisation. */ - int numRefinementSteps; /**< Maximum number of iterative refinement steps. */ - real_t epsIterRef; /**< Early termination tolerance for iterative refinement. */ - real_t epsLITests; /**< Tolerance for linear independence tests. */ - real_t epsNZCTests; /**< Tolerance for nonzero curvature tests. */ - - BooleanType enableDropInfeasibles; /**< ... */ - int dropBoundPriority; /**< ... */ - int dropEqConPriority; /**< ... */ - int dropIneqConPriority; /**< ... */ -} Options; - - -void OptionsCON( Options* _THIS - ); - -/** Copies all members from given rhs object. - * \return SUCCESSFUL_RETURN */ -void OptionsCPY( Options* FROM, - Options* TO - ); - - -/** Sets all options to default values. - * \return SUCCESSFUL_RETURN */ -returnValue Options_setToDefault( Options* _THIS - ); - -/** Sets all options to values resulting in maximum reliabilty. - * \return SUCCESSFUL_RETURN */ -returnValue Options_setToReliable( Options* _THIS - ); - -/** Sets all options to values resulting in minimum solution time. - * \return SUCCESSFUL_RETURN */ -returnValue Options_setToMPC( Options* _THIS - ); - -/** Same as setToMPC( ), for ensuring backwards compatibility. - * \return SUCCESSFUL_RETURN */ -returnValue Options_setToFast( Options* _THIS - ); - - -/** Ensures that all options have consistent values by automatically - * adjusting inconsistent ones. - * Note: This routine cannot (and does not try to) ensure that values - * are set to reasonable values that make the QP solution work! - * \return SUCCESSFUL_RETURN \n - * RET_OPTIONS_ADJUSTED */ -returnValue Options_ensureConsistency( Options* _THIS - ); - - -/** Prints values of all options. - * \return SUCCESSFUL_RETURN */ -returnValue Options_print( Options* _THIS - ); - - -END_NAMESPACE_QPOASES - - -#endif /* QPOASES_OPTIONS_H */ - - -/* - * end of file - */ diff --git a/third_party/acados/include/qpOASES_e/QProblem.h b/third_party/acados/include/qpOASES_e/QProblem.h deleted file mode 100644 index 91a4a6f396..0000000000 --- a/third_party/acados/include/qpOASES_e/QProblem.h +++ /dev/null @@ -1,2369 +0,0 @@ -/* - * This file is part of qpOASES. - * - * qpOASES -- An Implementation of the Online Active Set Strategy. - * Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka, - * Christian Kirches et al. All rights reserved. - * - * qpOASES is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * qpOASES is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with qpOASES; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/** - * \file include/qpOASES_e/QProblem.h - * \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches - * \version 3.1embedded - * \date 2007-2015 - * - * Declaration of the QProblem class which is able to use the newly - * developed online active set strategy for parametric quadratic programming. - */ - - - -#ifndef QPOASES_QPROBLEM_H -#define QPOASES_QPROBLEM_H - - -#include -#include -#include -#include -#include -#include - - -BEGIN_NAMESPACE_QPOASES - -typedef struct { - Bounds *auxiliaryBounds; - Constraints *auxiliaryConstraints; - - real_t *ub_new_far; - real_t *lb_new_far; - real_t *ubA_new_far; - real_t *lbA_new_far; - - real_t *g_new; - real_t *lb_new; - real_t *ub_new; - real_t *lbA_new; - real_t *ubA_new; - - real_t *g_new2; - real_t *lb_new2; - real_t *ub_new2; - real_t *lbA_new2; - real_t *ubA_new2; - - real_t *delta_xFX5; - real_t *delta_xFR5; - real_t *delta_yAC5; - real_t *delta_yFX5; - - real_t *Hx; - - real_t *_H; - - real_t *g_original; - real_t *lb_original; - real_t *ub_original; - real_t *lbA_original; - real_t *ubA_original; - - real_t *delta_xFR; - real_t *delta_xFX; - real_t *delta_yAC; - real_t *delta_yFX; - real_t *delta_g; - real_t *delta_lb; - real_t *delta_ub; - real_t *delta_lbA; - real_t *delta_ubA; - - real_t *gMod; - - real_t *aFR; - real_t *wZ; - - real_t *delta_g2; - real_t *delta_xFX2; - real_t *delta_xFR2; - real_t *delta_yAC2; - real_t *delta_yFX2; - real_t *nul; - real_t *Arow; - - real_t *xiC; - real_t *xiC_TMP; - real_t *xiB; - real_t *Arow2; - real_t *num; - - real_t *w; - real_t *tmp; - - real_t *delta_g3; - real_t *delta_xFX3; - real_t *delta_xFR3; - real_t *delta_yAC3; - real_t *delta_yFX3; - real_t *nul2; - - real_t *xiC2; - real_t *xiC_TMP2; - real_t *xiB2; - real_t *num2; - - real_t *Hz; - real_t *z; - real_t *ZHz; - real_t *r; - - real_t *tmp2; - real_t *Hz2; - real_t *z2; - real_t *r2; - real_t *rhs; - - real_t *delta_xFX4; - real_t *delta_xFR4; - real_t *delta_yAC4; - real_t *delta_yFX4; - real_t *nul3; - real_t *ek; - real_t *x_W; - real_t *As; - real_t *Ax_W; - - real_t *num3; - real_t *den; - real_t *delta_Ax_l; - real_t *delta_Ax_u; - real_t *delta_Ax; - real_t *delta_x; - - real_t *_A; - - real_t *grad; - real_t *AX; -} QProblem_ws; - -int QProblem_ws_calculateMemorySize( unsigned int nV, unsigned int nC ); - -char *QProblem_ws_assignMemory( unsigned int nV, unsigned int nC, QProblem_ws **mem, void *raw_memory ); - -QProblem_ws *QProblem_ws_createMemory( unsigned int nV, unsigned int nC ); - -/** - * \brief Implements the online active set strategy for QPs with general constraints. - * - * A class for setting up and solving quadratic programs. The main feature is - * the possibily to use the newly developed online active set strategy for - * parametric quadratic programming. - * - * \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches - * \version 3.1embedded - * \date 2007-2015 - */ -typedef struct -{ - QProblem_ws *ws; /**< Workspace */ - Bounds *bounds; /**< Data structure for problem's bounds. */ - Constraints *constraints; /**< Data structure for problem's constraints. */ - Flipper *flipper; /**< Struct for making a temporary copy of the matrix factorisations. */ - - DenseMatrix* H; /**< Hessian matrix pointer. */ - DenseMatrix* A; /**< Constraint matrix pointer. */ - - Options options; /**< Struct containing all user-defined options for solving QPs. */ - TabularOutput tabularOutput; /**< Struct storing information for tabular output (printLevel == PL_TABULAR). */ - - real_t *g; /**< Gradient. */ - - real_t *lb; /**< Lower bound vector (on variables). */ - real_t *ub; /**< Upper bound vector (on variables). */ - real_t *lbA; /**< Lower constraints' bound vector. */ - real_t *ubA; /**< Upper constraints' bound vector. */ - - real_t *R; /**< Cholesky factor of H (i.e. H = R^T*R). */ - - real_t *T; /**< Reverse triangular matrix, A = [0 T]*Q'. */ - real_t *Q; /**< Orthonormal quadratic matrix, A = [0 T]*Q'. */ - - real_t *Ax; /**< Stores the current A*x \n - * (for increased efficiency only). */ - real_t *Ax_l; /**< Stores the current distance to lower constraints' bounds A*x-lbA \n - * (for increased efficiency only). */ - real_t *Ax_u; /**< Stores the current distance to lower constraints' bounds ubA-A*x \n - * (for increased efficiency only). */ - - real_t *x; /**< Primal solution vector. */ - real_t *y; /**< Dual solution vector. */ - - real_t *delta_xFR_TMP; /**< Temporary for determineStepDirection */ - real_t *tempA; /**< Temporary for determineStepDirection. */ - real_t *tempB; /**< Temporary for determineStepDirection. */ - real_t *ZFR_delta_xFRz; /**< Temporary for determineStepDirection. */ - real_t *delta_xFRy; /**< Temporary for determineStepDirection. */ - real_t *delta_xFRz; /**< Temporary for determineStepDirection. */ - real_t *delta_yAC_TMP; /**< Temporary for determineStepDirection. */ - - ConstraintProduct constraintProduct; /**< Pointer to user-defined constraint product function. */ - - real_t tau; /**< Last homotopy step length. */ - real_t regVal; /**< Holds the offset used to regularise Hessian matrix (zero by default). */ - - real_t ramp0; /**< Start value for Ramping Strategy. */ - real_t ramp1; /**< Final value for Ramping Strategy. */ - - QProblemStatus status; /**< Current status of the solution process. */ - HessianType hessianType; /**< Type of Hessian matrix. */ - - BooleanType haveCholesky; /**< Flag indicating whether Cholesky decomposition has already been setup. */ - BooleanType infeasible; /**< QP infeasible? */ - BooleanType unbounded; /**< QP unbounded? */ - - int rampOffset; /**< Offset index for Ramping. */ - unsigned int count; /**< Counts the number of hotstart function calls (internal usage only!). */ - - int sizeT; /**< Matrix T is stored in a (sizeT x sizeT) array. */ -} QProblem; - -int QProblem_calculateMemorySize( unsigned int nV, unsigned int nC ); - -char *QProblem_assignMemory( unsigned int nV, unsigned int nC, QProblem **mem, void *raw_memory ); - -QProblem *QProblem_createMemory( unsigned int nV, unsigned int nC ); - - -/** Constructor which takes the QP dimension and Hessian type - * information. If the Hessian is the zero (i.e. HST_ZERO) or the - * identity matrix (i.e. HST_IDENTITY), respectively, no memory - * is allocated for it and a NULL pointer can be passed for it - * to the init() functions. */ -void QProblemCON( QProblem* _THIS, - int _nV, /**< Number of variables. */ - int _nC, /**< Number of constraints. */ - HessianType _hessianType /**< Type of Hessian matrix. */ - ); - -/** Copies all members from given rhs object. - * \return SUCCESSFUL_RETURN */ -void QProblemCPY( QProblem* FROM, - QProblem* TO - ); - - -/** Clears all data structures of QProblem except for QP data. - * \return SUCCESSFUL_RETURN \n - RET_RESET_FAILED */ -returnValue QProblem_reset( QProblem* _THIS ); - - -/** Initialises a QP problem with given QP data and tries to solve it - * using at most nWSR iterations. - * - * Note: This function internally calls solveInitialQP for initialisation! - * - * \return SUCCESSFUL_RETURN \n - RET_INIT_FAILED \n - RET_INIT_FAILED_CHOLESKY \n - RET_INIT_FAILED_TQ \n - RET_INIT_FAILED_HOTSTART \n - RET_INIT_FAILED_INFEASIBILITY \n - RET_INIT_FAILED_UNBOUNDEDNESS \n - RET_MAX_NWSR_REACHED \n - RET_INVALID_ARGUMENTS */ -returnValue QProblem_initM( QProblem* _THIS, - DenseMatrix *_H, /**< Hessian matrix. */ - const real_t* const _g, /**< Gradient vector. */ - DenseMatrix *_A, /**< Constraint matrix. */ - const real_t* const _lb, /**< Lower bound vector (on variables). \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const _ub, /**< Upper bound vector (on variables). \n - If no upper bounds exist, a NULL pointer can be passed. */ - const real_t* const _lbA, /**< Lower constraints' bound vector. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - const real_t* const _ubA, /**< Upper constraints' bound vector. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations when using initial homotopy. - Output: Number of performed working set recalculations. */ - real_t* const cputime /**< Input: Maximum CPU time allowed for QP initialisation. \n - Output: CPU time spent for QP initialisation (if pointer passed). */ - ); - - -/** Initialises a QP problem with given QP data and tries to solve it - * using at most nWSR iterations. - * - * Note: This function internally calls solveInitialQP for initialisation! - * - * \return SUCCESSFUL_RETURN \n - RET_INIT_FAILED \n - RET_INIT_FAILED_CHOLESKY \n - RET_INIT_FAILED_TQ \n - RET_INIT_FAILED_HOTSTART \n - RET_INIT_FAILED_INFEASIBILITY \n - RET_INIT_FAILED_UNBOUNDEDNESS \n - RET_MAX_NWSR_REACHED \n - RET_INVALID_ARGUMENTS */ -returnValue QProblem_init( QProblem* _THIS, - real_t* const _H, /**< Hessian matrix. \n - If Hessian matrix is trivial, a NULL pointer can be passed. */ - const real_t* const _g, /**< Gradient vector. */ - real_t* const _A, /**< Constraint matrix. */ - const real_t* const _lb, /**< Lower bound vector (on variables). \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const _ub, /**< Upper bound vector (on variables). \n - If no upper bounds exist, a NULL pointer can be passed. */ - const real_t* const _lbA, /**< Lower constraints' bound vector. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - const real_t* const _ubA, /**< Upper constraints' bound vector. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations when using initial homotopy. - Output: Number of performed working set recalculations. */ - real_t* const cputime /**< Input: Maximum CPU time allowed for QP initialisation. \n - Output: CPU time spent for QP initialisation (if pointer passed). */ - ); - -/** Initialises a QP problem with given QP data to be read from files and tries to solve it - * using at most nWSR iterations. - * - * Note: This function internally calls solveInitialQP for initialisation! - * - * \return SUCCESSFUL_RETURN \n - RET_INIT_FAILED \n - RET_INIT_FAILED_CHOLESKY \n - RET_INIT_FAILED_TQ \n - RET_INIT_FAILED_HOTSTART \n - RET_INIT_FAILED_INFEASIBILITY \n - RET_INIT_FAILED_UNBOUNDEDNESS \n - RET_MAX_NWSR_REACHED \n - RET_UNABLE_TO_READ_FILE */ -returnValue QProblem_initF( QProblem* _THIS, - const char* const H_file, /**< Name of file where Hessian matrix is stored. \n - If Hessian matrix is trivial, a NULL pointer can be passed. */ - const char* const g_file, /**< Name of file where gradient vector is stored. */ - const char* const A_file, /**< Name of file where constraint matrix is stored. */ - const char* const lb_file, /**< Name of file where lower bound vector. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const char* const ub_file, /**< Name of file where upper bound vector. \n - If no upper bounds exist, a NULL pointer can be passed. */ - const char* const lbA_file, /**< Name of file where lower constraints' bound vector. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - const char* const ubA_file, /**< Name of file where upper constraints' bound vector. \n - If no upper constraints' bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations when using initial homotopy. - Output: Number of performed working set recalculations. */ - real_t* const cputime /**< Input: Maximum CPU time allowed for QP initialisation. \n - Output: CPU time spent for QP initialisation (if pointer passed). */ - ); - -/** Initialises a QP problem with given QP data and tries to solve it - * using at most nWSR iterations. Depending on the parameter constellation it: \n - * 1. 0, 0, 0 : starts with xOpt = 0, yOpt = 0 and gB/gC empty (or all implicit equality bounds), \n - * 2. xOpt, 0, 0 : starts with xOpt, yOpt = 0 and obtain gB/gC by "clipping", \n - * 3. 0, yOpt, 0 : starts with xOpt = 0, yOpt and obtain gB/gC from yOpt != 0, \n - * 4. 0, 0, gB/gC: starts with xOpt = 0, yOpt = 0 and gB/gC, \n - * 5. xOpt, yOpt, 0 : starts with xOpt, yOpt and obtain gB/gC from yOpt != 0, \n - * 6. xOpt, 0, gB/gC: starts with xOpt, yOpt = 0 and gB/gC, \n - * 7. xOpt, yOpt, gB/gC: starts with xOpt, yOpt and gB/gC (assume them to be consistent!) - * - * Note: This function internally calls solveInitialQP for initialisation! - * - * \return SUCCESSFUL_RETURN \n - RET_INIT_FAILED \n - RET_INIT_FAILED_CHOLESKY \n - RET_INIT_FAILED_TQ \n - RET_INIT_FAILED_HOTSTART \n - RET_INIT_FAILED_INFEASIBILITY \n - RET_INIT_FAILED_UNBOUNDEDNESS \n - RET_MAX_NWSR_REACHED \n - RET_INVALID_ARGUMENTS */ -returnValue QProblem_initMW( QProblem* _THIS, - DenseMatrix *_H, /**< Hessian matrix. \n - If Hessian matrix is trivial, a NULL pointer can be passed. */ - const real_t* const _g, /**< Gradient vector. */ - DenseMatrix *_A, /**< Constraint matrix. */ - const real_t* const _lb, /**< Lower bound vector (on variables). \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const _ub, /**< Upper bound vector (on variables). \n - If no upper bounds exist, a NULL pointer can be passed. */ - const real_t* const _lbA, /**< Lower constraints' bound vector. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - const real_t* const _ubA, /**< Upper constraints' bound vector. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations when using initial homotopy. - * Output: Number of performed working set recalculations. */ - real_t* const cputime, /**< Input: Maximum CPU time allowed for QP initialisation. \n - Output: CPU time spent for QP initialisation. */ - const real_t* const xOpt, /**< Optimal primal solution vector. \n - (If a null pointer is passed, the old primal solution is kept!) */ - const real_t* const yOpt, /**< Optimal dual solution vector. \n - (If a null pointer is passed, the old dual solution is kept!) */ - Bounds* const guessedBounds, /**< Optimal working set of bounds for solution (xOpt,yOpt). */ - Constraints* const guessedConstraints, /**< Optimal working set of constraints for solution (xOpt,yOpt). */ - const real_t* const _R /**< Pre-computed (upper triangular) Cholesky factor of Hessian matrix. - The Cholesky factor must be stored in a real_t array of size nV*nV - in row-major format. Note: Only used if xOpt/yOpt and gB are NULL! \n - (If a null pointer is passed, Cholesky decomposition is computed internally!) */ - ); - -/** Initialises a QP problem with given QP data and tries to solve it - * using at most nWSR iterations. Depending on the parameter constellation it: \n - * 1. 0, 0, 0 : starts with xOpt = 0, yOpt = 0 and gB/gC empty (or all implicit equality bounds), \n - * 2. xOpt, 0, 0 : starts with xOpt, yOpt = 0 and obtain gB/gC by "clipping", \n - * 3. 0, yOpt, 0 : starts with xOpt = 0, yOpt and obtain gB/gC from yOpt != 0, \n - * 4. 0, 0, gB/gC: starts with xOpt = 0, yOpt = 0 and gB/gC, \n - * 5. xOpt, yOpt, 0 : starts with xOpt, yOpt and obtain gB/gC from yOpt != 0, \n - * 6. xOpt, 0, gB/gC: starts with xOpt, yOpt = 0 and gB/gC, \n - * 7. xOpt, yOpt, gB/gC: starts with xOpt, yOpt and gB/gC (assume them to be consistent!) - * - * Note: This function internally calls solveInitialQP for initialisation! - * - * \return SUCCESSFUL_RETURN \n - RET_INIT_FAILED \n - RET_INIT_FAILED_CHOLESKY \n - RET_INIT_FAILED_TQ \n - RET_INIT_FAILED_HOTSTART \n - RET_INIT_FAILED_INFEASIBILITY \n - RET_INIT_FAILED_UNBOUNDEDNESS \n - RET_MAX_NWSR_REACHED \n - RET_INVALID_ARGUMENTS */ -returnValue QProblem_initW( QProblem* _THIS, - real_t* const _H, /**< Hessian matrix. \n - If Hessian matrix is trivial, a NULL pointer can be passed. */ - const real_t* const _g, /**< Gradient vector. */ - real_t* const _A, /**< Constraint matrix. */ - const real_t* const _lb, /**< Lower bound vector (on variables). \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const _ub, /**< Upper bound vector (on variables). \n - If no upper bounds exist, a NULL pointer can be passed. */ - const real_t* const _lbA, /**< Lower constraints' bound vector. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - const real_t* const _ubA, /**< Upper constraints' bound vector. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations when using initial homotopy. - * Output: Number of performed working set recalculations. */ - real_t* const cputime, /**< Input: Maximum CPU time allowed for QP initialisation. \n - Output: CPU time spent for QP initialisation. */ - const real_t* const xOpt, /**< Optimal primal solution vector. \n - (If a null pointer is passed, the old primal solution is kept!) */ - const real_t* const yOpt, /**< Optimal dual solution vector. \n - (If a null pointer is passed, the old dual solution is kept!) */ - Bounds* const guessedBounds, /**< Optimal working set of bounds for solution (xOpt,yOpt). */ - Constraints* const guessedConstraints, /**< Optimal working set of constraints for solution (xOpt,yOpt). */ - const real_t* const _R /**< Pre-computed (upper triangular) Cholesky factor of Hessian matrix. - The Cholesky factor must be stored in a real_t array of size nV*nV - in row-major format. Note: Only used if xOpt/yOpt and gB are NULL! \n - (If a null pointer is passed, Cholesky decomposition is computed internally!) */ - ); - -/** Initialises a QP problem with given QP data to be ream from files and tries to solve it - * using at most nWSR iterations. Depending on the parameter constellation it: \n - * 1. 0, 0, 0 : starts with xOpt = 0, yOpt = 0 and gB/gC empty (or all implicit equality bounds), \n - * 2. xOpt, 0, 0 : starts with xOpt, yOpt = 0 and obtain gB/gC by "clipping", \n - * 3. 0, yOpt, 0 : starts with xOpt = 0, yOpt and obtain gB/gC from yOpt != 0, \n - * 4. 0, 0, gB/gC: starts with xOpt = 0, yOpt = 0 and gB/gC, \n - * 5. xOpt, yOpt, 0 : starts with xOpt, yOpt and obtain gB/gC from yOpt != 0, \n - * 6. xOpt, 0, gB/gC: starts with xOpt, yOpt = 0 and gB/gC, \n - * 7. xOpt, yOpt, gB/gC: starts with xOpt, yOpt and gB/gC (assume them to be consistent!) - * - * Note: This function internally calls solveInitialQP for initialisation! - * - * \return SUCCESSFUL_RETURN \n - RET_INIT_FAILED \n - RET_INIT_FAILED_CHOLESKY \n - RET_INIT_FAILED_TQ \n - RET_INIT_FAILED_HOTSTART \n - RET_INIT_FAILED_INFEASIBILITY \n - RET_INIT_FAILED_UNBOUNDEDNESS \n - RET_MAX_NWSR_REACHED \n - RET_UNABLE_TO_READ_FILE */ -returnValue QProblem_initFW( QProblem* _THIS, - const char* const H_file, /**< Name of file where Hessian matrix is stored. \n - If Hessian matrix is trivial, a NULL pointer can be passed. */ - const char* const g_file, /**< Name of file where gradient vector is stored. */ - const char* const A_file, /**< Name of file where constraint matrix is stored. */ - const char* const lb_file, /**< Name of file where lower bound vector. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const char* const ub_file, /**< Name of file where upper bound vector. \n - If no upper bounds exist, a NULL pointer can be passed. */ - const char* const lbA_file, /**< Name of file where lower constraints' bound vector. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - const char* const ubA_file, /**< Name of file where upper constraints' bound vector. \n - If no upper constraints' bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations when using initial homotopy. - Output: Number of performed working set recalculations. */ - real_t* const cputime, /**< Input: Maximum CPU time allowed for QP initialisation. \n - Output: CPU time spent for QP initialisation. */ - const real_t* const xOpt, /**< Optimal primal solution vector. \n - (If a null pointer is passed, the old primal solution is kept!) */ - const real_t* const yOpt, /**< Optimal dual solution vector. \n - (If a null pointer is passed, the old dual solution is kept!) */ - Bounds* const guessedBounds, /**< Optimal working set of bounds for solution (xOpt,yOpt). */ - Constraints* const guessedConstraints, /**< Optimal working set of constraints for solution (xOpt,yOpt). */ - const char* const R_file /**< Pre-computed (upper triangular) Cholesky factor of Hessian matrix. - The Cholesky factor must be stored in a real_t array of size nV*nV - in row-major format. Note: Only used if xOpt/yOpt and gB are NULL! \n - (If a null pointer is passed, Cholesky decomposition is computed internally!) */ - ); - -/** Solves an initialised QP sequence using the online active set strategy. - * QP solution is started from previous solution. - * - * Note: This function internally calls solveQP/solveRegularisedQP - * for solving an initialised QP! - * - * \return SUCCESSFUL_RETURN \n - RET_MAX_NWSR_REACHED \n - RET_HOTSTART_FAILED_AS_QP_NOT_INITIALISED \n - RET_HOTSTART_FAILED \n - RET_SHIFT_DETERMINATION_FAILED \n - RET_STEPDIRECTION_DETERMINATION_FAILED \n - RET_STEPLENGTH_DETERMINATION_FAILED \n - RET_HOMOTOPY_STEP_FAILED \n - RET_HOTSTART_STOPPED_INFEASIBILITY \n - RET_HOTSTART_STOPPED_UNBOUNDEDNESS */ -returnValue QProblem_hotstart( QProblem* _THIS, - const real_t* const g_new, /**< Gradient of neighbouring QP to be solved. */ - const real_t* const lb_new, /**< Lower bounds of neighbouring QP to be solved. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const ub_new, /**< Upper bounds of neighbouring QP to be solved. \n - If no upper bounds exist, a NULL pointer can be passed. */ - const real_t* const lbA_new, /**< Lower constraints' bounds of neighbouring QP to be solved. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - const real_t* const ubA_new, /**< Upper constraints' bounds of neighbouring QP to be solved. \n - If no upper constraints' bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations; \n - Output: Number of performed working set recalculations. */ - real_t* const cputime /**< Input: Maximum CPU time allowed for QP solution. \n - Output: CPU time spent for QP solution (or to perform nWSR iterations). */ - ); - -/** Solves an initialised QP sequence using the online active set strategy, - * where QP data is read from files. QP solution is started from previous solution. - * - * Note: This function internally calls solveQP/solveRegularisedQP - * for solving an initialised QP! - * - * \return SUCCESSFUL_RETURN \n - RET_MAX_NWSR_REACHED \n - RET_HOTSTART_FAILED_AS_QP_NOT_INITIALISED \n - RET_HOTSTART_FAILED \n - RET_SHIFT_DETERMINATION_FAILED \n - RET_STEPDIRECTION_DETERMINATION_FAILED \n - RET_STEPLENGTH_DETERMINATION_FAILED \n - RET_HOMOTOPY_STEP_FAILED \n - RET_HOTSTART_STOPPED_INFEASIBILITY \n - RET_HOTSTART_STOPPED_UNBOUNDEDNESS \n - RET_UNABLE_TO_READ_FILE \n - RET_INVALID_ARGUMENTS */ -returnValue QProblem_hotstartF( QProblem* _THIS, - const char* const g_file, /**< Name of file where gradient, of neighbouring QP to be solved, is stored. */ - const char* const lb_file, /**< Name of file where lower bounds, of neighbouring QP to be solved, is stored. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const char* const ub_file, /**< Name of file where upper bounds, of neighbouring QP to be solved, is stored. \n - If no upper bounds exist, a NULL pointer can be passed. */ - const char* const lbA_file, /**< Name of file where lower constraints' bounds, of neighbouring QP to be solved, is stored. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - const char* const ubA_file, /**< Name of file where upper constraints' bounds, of neighbouring QP to be solved, is stored. \n - If no upper constraints' bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations; \n - Output: Number of performed working set recalculations. */ - real_t* const cputime /**< Input: Maximum CPU time allowed for QP solution. \n - Output: CPU time spent for QP solution (or to perform nWSR iterations). */ - ); - -/** Solves an initialised QP sequence using the online active set strategy. - * By default, QP solution is started from previous solution. If a guess - * for the working set is provided, an initialised homotopy is performed. - * - * Note: This function internally calls solveQP/solveRegularisedQP - * for solving an initialised QP! - * - * \return SUCCESSFUL_RETURN \n - RET_MAX_NWSR_REACHED \n - RET_HOTSTART_FAILED_AS_QP_NOT_INITIALISED \n - RET_HOTSTART_FAILED \n - RET_SHIFT_DETERMINATION_FAILED \n - RET_STEPDIRECTION_DETERMINATION_FAILED \n - RET_STEPLENGTH_DETERMINATION_FAILED \n - RET_HOMOTOPY_STEP_FAILED \n - RET_HOTSTART_STOPPED_INFEASIBILITY \n - RET_HOTSTART_STOPPED_UNBOUNDEDNESS \n - RET_SETUP_AUXILIARYQP_FAILED */ -returnValue QProblem_hotstartW( QProblem* _THIS, - const real_t* const g_new, /**< Gradient of neighbouring QP to be solved. */ - const real_t* const lb_new, /**< Lower bounds of neighbouring QP to be solved. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const ub_new, /**< Upper bounds of neighbouring QP to be solved. \n - If no upper bounds exist, a NULL pointer can be passed. */ - const real_t* const lbA_new, /**< Lower constraints' bounds of neighbouring QP to be solved. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - const real_t* const ubA_new, /**< Upper constraints' bounds of neighbouring QP to be solved. \n - If no upper constraints' bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations; \n - Output: Number of performed working set recalculations. */ - real_t* const cputime, /**< Input: Maximum CPU time allowed for QP solution. \n - Output: CPU time spent for QP solution (or to perform nWSR iterations). */ - Bounds* const guessedBounds, /**< Optimal working set of bounds for solution (xOpt,yOpt). \n - (If a null pointer is passed, the previous working set of bounds is kept!) */ - Constraints* const guessedConstraints /**< Optimal working set of constraints for solution (xOpt,yOpt). \n - (If a null pointer is passed, the previous working set of constraints is kept!) */ - ); - -/** Solves an initialised QP sequence using the online active set strategy, - * where QP data is read from files. - * By default, QP solution is started from previous solution. If a guess - * for the working set is provided, an initialised homotopy is performed. - * - * Note: This function internally calls solveQP/solveRegularisedQP - * for solving an initialised QP! - * - * \return SUCCESSFUL_RETURN \n - RET_MAX_NWSR_REACHED \n - RET_HOTSTART_FAILED_AS_QP_NOT_INITIALISED \n - RET_HOTSTART_FAILED \n - RET_SHIFT_DETERMINATION_FAILED \n - RET_STEPDIRECTION_DETERMINATION_FAILED \n - RET_STEPLENGTH_DETERMINATION_FAILED \n - RET_HOMOTOPY_STEP_FAILED \n - RET_HOTSTART_STOPPED_INFEASIBILITY \n - RET_HOTSTART_STOPPED_UNBOUNDEDNESS \n - RET_SETUP_AUXILIARYQP_FAILED \n - RET_UNABLE_TO_READ_FILE \n - RET_INVALID_ARGUMENTS */ -returnValue QProblem_hotstartFW( QProblem* _THIS, - const char* const g_file, /**< Name of file where gradient, of neighbouring QP to be solved, is stored. */ - const char* const lb_file, /**< Name of file where lower bounds, of neighbouring QP to be solved, is stored. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const char* const ub_file, /**< Name of file where upper bounds, of neighbouring QP to be solved, is stored. \n - If no upper bounds exist, a NULL pointer can be passed. */ - const char* const lbA_file, /**< Name of file where lower constraints' bounds, of neighbouring QP to be solved, is stored. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - const char* const ubA_file, /**< Name of file where upper constraints' bounds, of neighbouring QP to be solved, is stored. \n - If no upper constraints' bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations; \n - Output: Number of performed working set recalculations. */ - real_t* const cputime, /**< Input: Maximum CPU time allowed for QP solution. \n - Output: CPU time spent for QP solution (or to perform nWSR iterations). */ - Bounds* const guessedBounds, /**< Optimal working set of bounds for solution (xOpt,yOpt). \n - (If a null pointer is passed, the previous working set of bounds is kept!) */ - Constraints* const guessedConstraints /**< Optimal working set of constraints for solution (xOpt,yOpt). \n - (If a null pointer is passed, the previous working set of constraints is kept!) */ - ); - - -/** Solves using the current working set - * \return SUCCESSFUL_RETURN \n - * RET_STEPDIRECTION_FAILED_TQ \n - * RET_STEPDIRECTION_FAILED_CHOLESKY \n - * RET_INVALID_ARGUMENTS */ -returnValue QProblem_solveCurrentEQP ( QProblem* _THIS, - const int n_rhs, /**< Number of consecutive right hand sides */ - const real_t* g_in, /**< Gradient of neighbouring QP to be solved. */ - const real_t* lb_in, /**< Lower bounds of neighbouring QP to be solved. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* ub_in, /**< Upper bounds of neighbouring QP to be solved. \n - If no upper bounds exist, a NULL pointer can be passed. */ - const real_t* lbA_in, /**< Lower constraints' bounds of neighbouring QP to be solved. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - const real_t* ubA_in, /**< Upper constraints' bounds of neighbouring QP to be solved. \n */ - real_t* x_out, /**< Output: Primal solution */ - real_t* y_out /**< Output: Dual solution */ - ); - - - -/** Returns current constraints object of the QP (deep copy). - * \return SUCCESSFUL_RETURN \n - RET_QPOBJECT_NOT_SETUP */ -static inline returnValue QProblem_getConstraints( QProblem* _THIS, - Constraints* _constraints /** Output: Constraints object. */ - ); - - -/** Returns the number of constraints. - * \return Number of constraints. */ -static inline int QProblem_getNC( QProblem* _THIS ); - -/** Returns the number of (implicitly defined) equality constraints. - * \return Number of (implicitly defined) equality constraints. */ -static inline int QProblem_getNEC( QProblem* _THIS ); - -/** Returns the number of active constraints. - * \return Number of active constraints. */ -static inline int QProblem_getNAC( QProblem* _THIS ); - -/** Returns the number of inactive constraints. - * \return Number of inactive constraints. */ -static inline int QProblem_getNIAC( QProblem* _THIS ); - -/** Returns the dimension of null space. - * \return Dimension of null space. */ -int QProblem_getNZ( QProblem* _THIS ); - - -/** Returns the dual solution vector (deep copy). - * \return SUCCESSFUL_RETURN \n - RET_QP_NOT_SOLVED */ -returnValue QProblem_getDualSolution( QProblem* _THIS, - real_t* const yOpt /**< Output: Dual solution vector (if QP has been solved). */ - ); - - -/** Defines user-defined routine for calculating the constraint product A*x - * \return SUCCESSFUL_RETURN \n */ -returnValue QProblem_setConstraintProduct( QProblem* _THIS, - ConstraintProduct _constraintProduct - ); - - -/** Prints concise list of properties of the current QP. - * \return SUCCESSFUL_RETURN \n */ -returnValue QProblem_printProperties( QProblem* _THIS ); - - - -/** Writes a vector with the state of the working set -* \return SUCCESSFUL_RETURN */ -returnValue QProblem_getWorkingSet( QProblem* _THIS, - real_t* workingSet /** Output: array containing state of the working set. */ - ); - -/** Writes a vector with the state of the working set of bounds - * \return SUCCESSFUL_RETURN \n - * RET_INVALID_ARGUMENTS */ -returnValue QProblem_getWorkingSetBounds( QProblem* _THIS, - real_t* workingSetB /** Output: array containing state of the working set of bounds. */ - ); - -/** Writes a vector with the state of the working set of constraints - * \return SUCCESSFUL_RETURN \n - * RET_INVALID_ARGUMENTS */ -returnValue QProblem_getWorkingSetConstraints( QProblem* _THIS, - real_t* workingSetC /** Output: array containing state of the working set of constraints. */ - ); - - -/** Returns current bounds object of the QP (deep copy). - * \return SUCCESSFUL_RETURN \n - RET_QPOBJECT_NOT_SETUP */ -static inline returnValue QProblem_getBounds( QProblem* _THIS, - Bounds* _bounds /** Output: Bounds object. */ - ); - - -/** Returns the number of variables. - * \return Number of variables. */ -static inline int QProblem_getNV( QProblem* _THIS ); - -/** Returns the number of free variables. - * \return Number of free variables. */ -static inline int QProblem_getNFR( QProblem* _THIS ); - -/** Returns the number of fixed variables. - * \return Number of fixed variables. */ -static inline int QProblem_getNFX( QProblem* _THIS ); - -/** Returns the number of implicitly fixed variables. - * \return Number of implicitly fixed variables. */ -static inline int QProblem_getNFV( QProblem* _THIS ); - - -/** Returns the optimal objective function value. - * \return finite value: Optimal objective function value (QP was solved) \n - +infinity: QP was not yet solved */ -real_t QProblem_getObjVal( QProblem* _THIS ); - -/** Returns the objective function value at an arbitrary point x. - * \return Objective function value at point x */ -real_t QProblem_getObjValX( QProblem* _THIS, - const real_t* const _x /**< Point at which the objective function shall be evaluated. */ - ); - -/** Returns the primal solution vector. - * \return SUCCESSFUL_RETURN \n - RET_QP_NOT_SOLVED */ -returnValue QProblem_getPrimalSolution( QProblem* _THIS, - real_t* const xOpt /**< Output: Primal solution vector (if QP has been solved). */ - ); - - -/** Returns status of the solution process. - * \return Status of solution process. */ -static inline QProblemStatus QProblem_getStatus( QProblem* _THIS ); - - -/** Returns if the QProblem object is initialised. - * \return BT_TRUE: QProblem initialised \n - BT_FALSE: QProblem not initialised */ -static inline BooleanType QProblem_isInitialised( QProblem* _THIS ); - -/** Returns if the QP has been solved. - * \return BT_TRUE: QProblem solved \n - BT_FALSE: QProblem not solved */ -static inline BooleanType QProblem_isSolved( QProblem* _THIS ); - -/** Returns if the QP is infeasible. - * \return BT_TRUE: QP infeasible \n - BT_FALSE: QP feasible (or not known to be infeasible!) */ -static inline BooleanType QProblem_isInfeasible( QProblem* _THIS ); - -/** Returns if the QP is unbounded. - * \return BT_TRUE: QP unbounded \n - BT_FALSE: QP unbounded (or not known to be unbounded!) */ -static inline BooleanType QProblem_isUnbounded( QProblem* _THIS ); - - -/** Returns Hessian type flag (type is not determined due to _THIS call!). - * \return Hessian type. */ -static inline HessianType QProblem_getHessianType( QProblem* _THIS ); - -/** Changes the print level. - * \return SUCCESSFUL_RETURN */ -static inline returnValue QProblem_setHessianType( QProblem* _THIS, - HessianType _hessianType /**< New Hessian type. */ - ); - -/** Returns if the QP has been internally regularised. - * \return BT_TRUE: Hessian is internally regularised for QP solution \n - BT_FALSE: No internal Hessian regularisation is used for QP solution */ -static inline BooleanType QProblem_usingRegularisation( QProblem* _THIS ); - -/** Returns current options struct. - * \return Current options struct. */ -static inline Options QProblem_getOptions( QProblem* _THIS ); - -/** Overrides current options with given ones. - * \return SUCCESSFUL_RETURN */ -static inline returnValue QProblem_setOptions( QProblem* _THIS, - Options _options /**< New options. */ - ); - -/** Returns the print level. - * \return Print level. */ -static inline PrintLevel QProblem_getPrintLevel( QProblem* _THIS ); - -/** Changes the print level. - * \return SUCCESSFUL_RETURN */ -returnValue QProblem_setPrintLevel( QProblem* _THIS, - PrintLevel _printlevel /**< New print level. */ - ); - - -/** Returns the current number of QP problems solved. - * \return Number of QP problems solved. */ -static inline unsigned int QProblem_getCount( QProblem* _THIS ); - -/** Resets QP problem counter (to zero). - * \return SUCCESSFUL_RETURN. */ -static inline returnValue QProblem_resetCounter( QProblem* _THIS ); - - -/** Prints a list of all options and their current values. - * \return SUCCESSFUL_RETURN \n */ -returnValue QProblem_printOptions( QProblem* _THIS ); - - -/** Solves a QProblem whose QP data is assumed to be stored in the member variables. - * A guess for its primal/dual optimal solution vectors and the corresponding - * working sets of bounds and constraints can be provided. - * Note: This function is internally called by all init functions! - * \return SUCCESSFUL_RETURN \n - RET_INIT_FAILED \n - RET_INIT_FAILED_CHOLESKY \n - RET_INIT_FAILED_TQ \n - RET_INIT_FAILED_HOTSTART \n - RET_INIT_FAILED_INFEASIBILITY \n - RET_INIT_FAILED_UNBOUNDEDNESS \n - RET_MAX_NWSR_REACHED */ -returnValue QProblem_solveInitialQP( QProblem* _THIS, - const real_t* const xOpt, /**< Optimal primal solution vector.*/ - const real_t* const yOpt, /**< Optimal dual solution vector. */ - Bounds* const guessedBounds, /**< Optimal working set of bounds for solution (xOpt,yOpt). */ - Constraints* const guessedConstraints, /**< Optimal working set of constraints for solution (xOpt,yOpt). */ - const real_t* const _R, /**< Pre-computed (upper triangular) Cholesky factor of Hessian matrix. */ - int* nWSR, /**< Input: Maximum number of working set recalculations; \n - * Output: Number of performed working set recalculations. */ - real_t* const cputime /**< Input: Maximum CPU time allowed for QP solution. \n - * Output: CPU time spent for QP solution (or to perform nWSR iterations). */ - ); - -/** Solves QProblem using online active set strategy. - * Note: This function is internally called by all hotstart functions! - * \return SUCCESSFUL_RETURN \n - RET_MAX_NWSR_REACHED \n - RET_HOTSTART_FAILED_AS_QP_NOT_INITIALISED \n - RET_HOTSTART_FAILED \n - RET_SHIFT_DETERMINATION_FAILED \n - RET_STEPDIRECTION_DETERMINATION_FAILED \n - RET_STEPLENGTH_DETERMINATION_FAILED \n - RET_HOMOTOPY_STEP_FAILED \n - RET_HOTSTART_STOPPED_INFEASIBILITY \n - RET_HOTSTART_STOPPED_UNBOUNDEDNESS */ -returnValue QProblem_solveQP( QProblem* _THIS, - const real_t* const g_new, /**< Gradient of neighbouring QP to be solved. */ - const real_t* const lb_new, /**< Lower bounds of neighbouring QP to be solved. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const ub_new, /**< Upper bounds of neighbouring QP to be solved. \n - If no upper bounds exist, a NULL pointer can be passed. */ - const real_t* const lbA_new, /**< Lower constraints' bounds of neighbouring QP to be solved. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - const real_t* const ubA_new, /**< Upper constraints' bounds of neighbouring QP to be solved. \n - If no upper constraints' bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations; \n - Output: Number of performed working set recalculations. */ - real_t* const cputime, /**< Input: Maximum CPU time allowed for QP solution. \n - Output: CPU time spent for QP solution (or to perform nWSR iterations). */ - int nWSRperformed, /**< Number of working set recalculations already performed to solve - this QP within previous solveQP() calls. This number is - always zero, except for successive calls from solveRegularisedQP() - or when using the far bound strategy. */ - BooleanType isFirstCall /**< Indicating whether this is the first call for current QP. */ - ); - - -/** Solves QProblem using online active set strategy. - * Note: This function is internally called by all hotstart functions! - * \return SUCCESSFUL_RETURN \n - RET_MAX_NWSR_REACHED \n - RET_HOTSTART_FAILED_AS_QP_NOT_INITIALISED \n - RET_HOTSTART_FAILED \n - RET_SHIFT_DETERMINATION_FAILED \n - RET_STEPDIRECTION_DETERMINATION_FAILED \n - RET_STEPLENGTH_DETERMINATION_FAILED \n - RET_HOMOTOPY_STEP_FAILED \n - RET_HOTSTART_STOPPED_INFEASIBILITY \n - RET_HOTSTART_STOPPED_UNBOUNDEDNESS */ -returnValue QProblem_solveRegularisedQP( QProblem* _THIS, - const real_t* const g_new, /**< Gradient of neighbouring QP to be solved. */ - const real_t* const lb_new, /**< Lower bounds of neighbouring QP to be solved. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const ub_new, /**< Upper bounds of neighbouring QP to be solved. \n - If no upper bounds exist, a NULL pointer can be passed. */ - const real_t* const lbA_new, /**< Lower constraints' bounds of neighbouring QP to be solved. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - const real_t* const ubA_new, /**< Upper constraints' bounds of neighbouring QP to be solved. \n - If no upper constraints' bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations; \n - Output: Number of performed working set recalculations. */ - real_t* const cputime, /**< Input: Maximum CPU time allowed for QP solution. \n - Output: CPU time spent for QP solution (or to perform nWSR iterations). */ - int nWSRperformed, /**< Number of working set recalculations already performed to solve - this QP within previous solveRegularisedQP() calls. This number is - always zero, except for successive calls when using the far bound strategy. */ - BooleanType isFirstCall /**< Indicating whether this is the first call for current QP. */ - ); - - -/** Determines type of existing constraints and bounds (i.e. implicitly fixed, unbounded etc.). - * \return SUCCESSFUL_RETURN \n - RET_SETUPSUBJECTTOTYPE_FAILED */ -returnValue QProblem_setupSubjectToType( QProblem* _THIS ); - -/** Determines type of new constraints and bounds (i.e. implicitly fixed, unbounded etc.). - * \return SUCCESSFUL_RETURN \n - RET_SETUPSUBJECTTOTYPE_FAILED */ -returnValue QProblem_setupSubjectToTypeNew( QProblem* _THIS, - const real_t* const lb_new, /**< New lower bounds. */ - const real_t* const ub_new, /**< New upper bounds. */ - const real_t* const lbA_new, /**< New lower constraints' bounds. */ - const real_t* const ubA_new /**< New upper constraints' bounds. */ - ); - -/** Computes the Cholesky decomposition of the projected Hessian (i.e. R^T*R = Z^T*H*Z). - * Note: If Hessian turns out not to be positive definite, the Hessian type - * is set to HST_SEMIDEF accordingly. - * \return SUCCESSFUL_RETURN \n - * RET_HESSIAN_NOT_SPD \n - * RET_INDEXLIST_CORRUPTED */ -returnValue QProblem_computeProjectedCholesky( QProblem* _THIS ); - -/** Computes initial Cholesky decomposition of the projected Hessian making - * use of the function setupCholeskyDecomposition() or setupCholeskyDecompositionProjected(). - * \return SUCCESSFUL_RETURN \n - * RET_HESSIAN_NOT_SPD \n - * RET_INDEXLIST_CORRUPTED */ -returnValue QProblem_setupInitialCholesky( QProblem* _THIS ); - -/** Initialises TQ factorisation of A (i.e. A*Q = [0 T]) if NO constraint is active. - * \return SUCCESSFUL_RETURN \n - RET_INDEXLIST_CORRUPTED */ -returnValue QProblem_setupTQfactorisation( QProblem* _THIS ); - - -/** Obtains the desired working set for the auxiliary initial QP in - * accordance with the user specifications - * (assumes that member AX has already been initialised!) - * \return SUCCESSFUL_RETURN \n - RET_OBTAINING_WORKINGSET_FAILED \n - RET_INVALID_ARGUMENTS */ -returnValue QProblem_obtainAuxiliaryWorkingSet( QProblem* _THIS, - const real_t* const xOpt, /**< Optimal primal solution vector. - * If a NULL pointer is passed, all entries are assumed to be zero. */ - const real_t* const yOpt, /**< Optimal dual solution vector. - * If a NULL pointer is passed, all entries are assumed to be zero. */ - Bounds* const guessedBounds, /**< Guessed working set of bounds for solution (xOpt,yOpt). */ - Constraints* const guessedConstraints, /**< Guessed working set for solution (xOpt,yOpt). */ - Bounds* auxiliaryBounds, /**< Input: Allocated bound object. \n - * Ouput: Working set of constraints for auxiliary QP. */ - Constraints* auxiliaryConstraints /**< Input: Allocated bound object. \n - * Ouput: Working set for auxiliary QP. */ - ); - -/** Sets up bound and constraints data structures according to auxiliaryBounds/Constraints. - * (If the working set shall be setup afresh, make sure that - * bounds and constraints data structure have been resetted - * and the TQ factorisation has been initialised!) - * \return SUCCESSFUL_RETURN \n - RET_SETUP_WORKINGSET_FAILED \n - RET_INVALID_ARGUMENTS \n - RET_UNKNOWN_BUG */ -returnValue QProblem_setupAuxiliaryWorkingSet( QProblem* _THIS, - Bounds* const auxiliaryBounds, /**< Working set of bounds for auxiliary QP. */ - Constraints* const auxiliaryConstraints, /**< Working set of constraints for auxiliary QP. */ - BooleanType setupAfresh /**< Flag indicating if given working set shall be - * setup afresh or by updating the current one. */ - ); - -/** Sets up the optimal primal/dual solution of the auxiliary initial QP. - * \return SUCCESSFUL_RETURN */ -returnValue QProblem_setupAuxiliaryQPsolution( QProblem* _THIS, - const real_t* const xOpt, /**< Optimal primal solution vector. - * If a NULL pointer is passed, all entries are set to zero. */ - const real_t* const yOpt /**< Optimal dual solution vector. - * If a NULL pointer is passed, all entries are set to zero. */ - ); - -/** Sets up gradient of the auxiliary initial QP for given - * optimal primal/dual solution and given initial working set - * (assumes that members X, Y and BOUNDS, CONSTRAINTS have already been initialised!). - * \return SUCCESSFUL_RETURN */ -returnValue QProblem_setupAuxiliaryQPgradient( QProblem* _THIS ); - -/** Sets up (constraints') bounds of the auxiliary initial QP for given - * optimal primal/dual solution and given initial working set - * (assumes that members X, Y and BOUNDS, CONSTRAINTS have already been initialised!). - * \return SUCCESSFUL_RETURN \n - RET_UNKNOWN_BUG */ -returnValue QProblem_setupAuxiliaryQPbounds( QProblem* _THIS, - Bounds* const auxiliaryBounds, /**< Working set of bounds for auxiliary QP. */ - Constraints* const auxiliaryConstraints, /**< Working set of constraints for auxiliary QP. */ - BooleanType useRelaxation /**< Flag indicating if inactive (constraints') bounds shall be relaxed. */ - ); - - -/** Adds a constraint to active set. - * \return SUCCESSFUL_RETURN \n - RET_ADDCONSTRAINT_FAILED \n - RET_ADDCONSTRAINT_FAILED_INFEASIBILITY \n - RET_ENSURELI_FAILED */ -returnValue QProblem_addConstraint( QProblem* _THIS, - int number, /**< Number of constraint to be added to active set. */ - SubjectToStatus C_status, /**< Status of new active constraint. */ - BooleanType updateCholesky, /**< Flag indicating if Cholesky decomposition shall be updated. */ - BooleanType ensureLI /**< Ensure linear independence by exchange rules by default. */ - ); - -/** Checks if new active constraint to be added is linearly dependent from - * from row of the active constraints matrix. - * \return RET_LINEARLY_DEPENDENT \n - RET_LINEARLY_INDEPENDENT \n - RET_INDEXLIST_CORRUPTED */ -returnValue QProblem_addConstraint_checkLI( QProblem* _THIS, - int number /**< Number of constraint to be added to active set. */ - ); - -/** Ensures linear independence of constraint matrix when a new constraint is added. - * To _THIS end a bound or constraint is removed simultaneously if necessary. - * \return SUCCESSFUL_RETURN \n - RET_LI_RESOLVED \n - RET_ENSURELI_FAILED \n - RET_ENSURELI_FAILED_TQ \n - RET_ENSURELI_FAILED_NOINDEX \n - RET_REMOVE_FROM_ACTIVESET */ -returnValue QProblem_addConstraint_ensureLI( QProblem* _THIS, - int number, /**< Number of constraint to be added to active set. */ - SubjectToStatus C_status /**< Status of new active bound. */ - ); - -/** Adds a bound to active set. - * \return SUCCESSFUL_RETURN \n - RET_ADDBOUND_FAILED \n - RET_ADDBOUND_FAILED_INFEASIBILITY \n - RET_ENSURELI_FAILED */ -returnValue QProblem_addBound( QProblem* _THIS, - int number, /**< Number of bound to be added to active set. */ - SubjectToStatus B_status, /**< Status of new active bound. */ - BooleanType updateCholesky, /**< Flag indicating if Cholesky decomposition shall be updated. */ - BooleanType ensureLI /**< Ensure linear independence by exchange rules by default. */ - ); - -/** Checks if new active bound to be added is linearly dependent from - * from row of the active constraints matrix. - * \return RET_LINEARLY_DEPENDENT \n - RET_LINEARLY_INDEPENDENT */ -returnValue QProblem_addBound_checkLI( QProblem* _THIS, - int number /**< Number of bound to be added to active set. */ - ); - -/** Ensures linear independence of constraint matrix when a new bound is added. - * To _THIS end a bound or constraint is removed simultaneously if necessary. - * \return SUCCESSFUL_RETURN \n - RET_LI_RESOLVED \n - RET_ENSURELI_FAILED \n - RET_ENSURELI_FAILED_TQ \n - RET_ENSURELI_FAILED_NOINDEX \n - RET_REMOVE_FROM_ACTIVESET */ -returnValue QProblem_addBound_ensureLI( QProblem* _THIS, - int number, /**< Number of bound to be added to active set. */ - SubjectToStatus B_status /**< Status of new active bound. */ - ); - -/** Removes a constraint from active set. - * \return SUCCESSFUL_RETURN \n - RET_CONSTRAINT_NOT_ACTIVE \n - RET_REMOVECONSTRAINT_FAILED \n - RET_HESSIAN_NOT_SPD */ -returnValue QProblem_removeConstraint( QProblem* _THIS, - int number, /**< Number of constraint to be removed from active set. */ - BooleanType updateCholesky, /**< Flag indicating if Cholesky decomposition shall be updated. */ - BooleanType allowFlipping, /**< Flag indicating if flipping bounds are allowed. */ - BooleanType ensureNZC /**< Flag indicating if non-zero curvature is ensured by exchange rules. */ - ); - -/** Removes a bounds from active set. - * \return SUCCESSFUL_RETURN \n - RET_BOUND_NOT_ACTIVE \n - RET_HESSIAN_NOT_SPD \n - RET_REMOVEBOUND_FAILED */ -returnValue QProblem_removeBound( QProblem* _THIS, - int number, /**< Number of bound to be removed from active set. */ - BooleanType updateCholesky, /**< Flag indicating if Cholesky decomposition shall be updated. */ - BooleanType allowFlipping, /**< Flag indicating if flipping bounds are allowed. */ - BooleanType ensureNZC /**< Flag indicating if non-zero curvature is ensured by exchange rules. */ - ); - - -/** Performs robustified ratio test yield the maximum possible step length - * along the homotopy path. - * \return SUCCESSFUL_RETURN */ -returnValue QProblem_performPlainRatioTest( QProblem* _THIS, - int nIdx, /**< Number of ratios to be checked. */ - const int* const idxList, /**< Array containing the indices of all ratios to be checked. */ - const real_t* const num, /**< Array containing all numerators for performing the ratio test. */ - const real_t* const den, /**< Array containing all denominators for performing the ratio test. */ - real_t epsNum, /**< Numerator tolerance. */ - real_t epsDen, /**< Denominator tolerance. */ - real_t* t, /**< Output: Maximum possible step length along the homotopy path. */ - int* BC_idx /**< Output: Index of blocking constraint. */ - ); - - -/** Ensure non-zero curvature by primal jump. - * \return SUCCESSFUL_RETURN \n - * RET_HOTSTART_STOPPED_UNBOUNDEDNESS */ -returnValue QProblem_ensureNonzeroCurvature( QProblem* _THIS, - BooleanType removeBoundNotConstraint, /**< SubjectTo to be removed is a bound. */ - int remIdx, /**< Index of bound/constraint to be removed. */ - BooleanType* exchangeHappened, /**< Output: Exchange was necessary to ensure. */ - BooleanType* addBoundNotConstraint, /**< SubjectTo to be added is a bound. */ - int* addIdx, /**< Index of bound/constraint to be added. */ - SubjectToStatus* addStatus /**< Status of bound/constraint to be added. */ - ); - - -/** Solves the system Ta = b or T^Ta = b where T is a reverse upper triangular matrix. - * \return SUCCESSFUL_RETURN \n - RET_DIV_BY_ZERO */ -returnValue QProblem_backsolveT( QProblem* _THIS, - const real_t* const b, /**< Right hand side vector. */ - BooleanType transposed, /**< Indicates if the transposed system shall be solved. */ - real_t* const a /**< Output: Solution vector */ - ); - - -/** Determines step direction of the shift of the QP data. - * \return SUCCESSFUL_RETURN */ -returnValue QProblem_determineDataShift( QProblem* _THIS, - const real_t* const g_new, /**< New gradient vector. */ - const real_t* const lbA_new, /**< New lower constraints' bounds. */ - const real_t* const ubA_new, /**< New upper constraints' bounds. */ - const real_t* const lb_new, /**< New lower bounds. */ - const real_t* const ub_new, /**< New upper bounds. */ - real_t* const delta_g, /**< Output: Step direction of gradient vector. */ - real_t* const delta_lbA, /**< Output: Step direction of lower constraints' bounds. */ - real_t* const delta_ubA, /**< Output: Step direction of upper constraints' bounds. */ - real_t* const delta_lb, /**< Output: Step direction of lower bounds. */ - real_t* const delta_ub, /**< Output: Step direction of upper bounds. */ - BooleanType* Delta_bC_isZero, /**< Output: Indicates if active constraints' bounds are to be shifted. */ - BooleanType* Delta_bB_isZero /**< Output: Indicates if active bounds are to be shifted. */ - ); - -/** Determines step direction of the homotopy path. - * \return SUCCESSFUL_RETURN \n - RET_STEPDIRECTION_FAILED_TQ \n - RET_STEPDIRECTION_FAILED_CHOLESKY */ -returnValue QProblem_determineStepDirection( QProblem* _THIS, - const real_t* const delta_g, /**< Step direction of gradient vector. */ - const real_t* const delta_lbA, /**< Step direction of lower constraints' bounds. */ - const real_t* const delta_ubA, /**< Step direction of upper constraints' bounds. */ - const real_t* const delta_lb, /**< Step direction of lower bounds. */ - const real_t* const delta_ub, /**< Step direction of upper bounds. */ - BooleanType Delta_bC_isZero, /**< Indicates if active constraints' bounds are to be shifted. */ - BooleanType Delta_bB_isZero, /**< Indicates if active bounds are to be shifted. */ - real_t* const delta_xFX, /**< Output: Primal homotopy step direction of fixed variables. */ - real_t* const delta_xFR, /**< Output: Primal homotopy step direction of free variables. */ - real_t* const delta_yAC, /**< Output: Dual homotopy step direction of active constraints' multiplier. */ - real_t* const delta_yFX /**< Output: Dual homotopy step direction of fixed variables' multiplier. */ - ); - -/** Determines the maximum possible step length along the homotopy path - * and performs _THIS step (without changing working set). - * \return SUCCESSFUL_RETURN \n - * RET_ERROR_IN_CONSTRAINTPRODUCT \n - * RET_QP_INFEASIBLE */ -returnValue QProblem_performStep( QProblem* _THIS, - const real_t* const delta_g, /**< Step direction of gradient. */ - const real_t* const delta_lbA, /**< Step direction of lower constraints' bounds. */ - const real_t* const delta_ubA, /**< Step direction of upper constraints' bounds. */ - const real_t* const delta_lb, /**< Step direction of lower bounds. */ - const real_t* const delta_ub, /**< Step direction of upper bounds. */ - const real_t* const delta_xFX, /**< Primal homotopy step direction of fixed variables. */ - const real_t* const delta_xFR, /**< Primal homotopy step direction of free variables. */ - const real_t* const delta_yAC, /**< Dual homotopy step direction of active constraints' multiplier. */ - const real_t* const delta_yFX, /**< Dual homotopy step direction of fixed variables' multiplier. */ - int* BC_idx, /**< Output: Index of blocking constraint. */ - SubjectToStatus* BC_status, /**< Output: Status of blocking constraint. */ - BooleanType* BC_isBound /**< Output: Indicates if blocking constraint is a bound. */ - ); - -/** Updates the active set. - * \return SUCCESSFUL_RETURN \n - RET_REMOVE_FROM_ACTIVESET_FAILED \n - RET_ADD_TO_ACTIVESET_FAILED */ -returnValue QProblem_changeActiveSet( QProblem* _THIS, - int BC_idx, /**< Index of blocking constraint. */ - SubjectToStatus BC_status, /**< Status of blocking constraint. */ - BooleanType BC_isBound /**< Indicates if blocking constraint is a bound. */ - ); - - -/** Compute relative length of homotopy in data space for termination - * criterion. - * \return Relative length in data space. */ -real_t QProblem_getRelativeHomotopyLength( QProblem* _THIS, - const real_t* const g_new, /**< Final gradient. */ - const real_t* const lb_new, /**< Final lower variable bounds. */ - const real_t* const ub_new, /**< Final upper variable bounds. */ - const real_t* const lbA_new, /**< Final lower constraint bounds. */ - const real_t* const ubA_new /**< Final upper constraint bounds. */ - ); - - -/** Ramping Strategy to avoid ties. Modifies homotopy start without - * changing current active set. - * \return SUCCESSFUL_RETURN */ -returnValue QProblem_performRamping( QProblem* _THIS ); - - -/** ... */ -returnValue QProblem_updateFarBounds( QProblem* _THIS, - real_t curFarBound, /**< ... */ - int nRamp, /**< ... */ - const real_t* const lb_new, /**< ... */ - real_t* const lb_new_far, /**< ... */ - const real_t* const ub_new, /**< ... */ - real_t* const ub_new_far, /**< ... */ - const real_t* const lbA_new, /**< ... */ - real_t* const lbA_new_far, /**< ... */ - const real_t* const ubA_new, /**< ... */ - real_t* const ubA_new_far /**< ... */ - ); - -/** ... */ -returnValue QProblemBCPY_updateFarBounds( QProblem* _THIS, - real_t curFarBound, /**< ... */ - int nRamp, /**< ... */ - const real_t* const lb_new, /**< ... */ - real_t* const lb_new_far, /**< ... */ - const real_t* const ub_new, /**< ... */ - real_t* const ub_new_far /**< ... */ - ); - - - -/** Performs robustified ratio test yield the maximum possible step length - * along the homotopy path. - * \return SUCCESSFUL_RETURN */ -returnValue QProblem_performRatioTestC( QProblem* _THIS, - int nIdx, /**< Number of ratios to be checked. */ - const int* const idxList, /**< Array containing the indices of all ratios to be checked. */ - Constraints* const subjectTo, /**< Constraint object corresponding to ratios to be checked. */ - const real_t* const num, /**< Array containing all numerators for performing the ratio test. */ - const real_t* const den, /**< Array containing all denominators for performing the ratio test. */ - real_t epsNum, /**< Numerator tolerance. */ - real_t epsDen, /**< Denominator tolerance. */ - real_t* t, /**< Output: Maximum possible step length along the homotopy path. */ - int* BC_idx /**< Output: Index of blocking constraint. */ - ); - - -/** Drift correction at end of each active set iteration - * \return SUCCESSFUL_RETURN */ -returnValue QProblem_performDriftCorrection( QProblem* _THIS ); - - -/** Updates QP vectors, working sets and internal data structures in order to - start from an optimal solution corresponding to initial guesses of the working - set for bounds and constraints. - * \return SUCCESSFUL_RETURN \n - * RET_SETUP_AUXILIARYQP_FAILED \n - RET_INVALID_ARGUMENTS */ -returnValue QProblem_setupAuxiliaryQP( QProblem* _THIS, - Bounds* const guessedBounds, /**< Initial guess for working set of bounds. */ - Constraints* const guessedConstraints /**< Initial guess for working set of constraints. */ - ); - -/** Determines if it is more efficient to refactorise the matrices when - * hotstarting or not (i.e. better to update the existing factorisations). - * \return BT_TRUE iff matrices shall be refactorised afresh - */ -BooleanType QProblem_shallRefactorise( QProblem* _THIS, - Bounds* const guessedBounds, /**< Guessed new working set of bounds. */ - Constraints* const guessedConstraints /**< Guessed new working set of constraints. */ - ); - -/** Setups internal QP data. - * \return SUCCESSFUL_RETURN \n - RET_INVALID_ARGUMENTS \n - RET_UNKNONW_BUG */ -returnValue QProblem_setupQPdataM( QProblem* _THIS, - DenseMatrix *_H, /**< Hessian matrix. \n - If Hessian matrix is trivial,a NULL pointer can be passed. */ - const real_t* const _g, /**< Gradient vector. */ - DenseMatrix *_A, /**< Constraint matrix. */ - const real_t* const _lb, /**< Lower bound vector (on variables). \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const _ub, /**< Upper bound vector (on variables). \n - If no upper bounds exist, a NULL pointer can be passed. */ - const real_t* const _lbA, /**< Lower constraints' bound vector. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - const real_t* const _ubA /**< Upper constraints' bound vector. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - ); - - -/** Sets up dense internal QP data. If the current Hessian is trivial - * (i.e. HST_ZERO or HST_IDENTITY) but a non-trivial one is given, - * memory for Hessian is allocated and it is set to the given one. - * \return SUCCESSFUL_RETURN \n - RET_INVALID_ARGUMENTS \n - RET_UNKNONW_BUG */ -returnValue QProblem_setupQPdata( QProblem* _THIS, - real_t* const _H, /**< Hessian matrix. \n - If Hessian matrix is trivial,a NULL pointer can be passed. */ - const real_t* const _g, /**< Gradient vector. */ - real_t* const _A, /**< Constraint matrix. */ - const real_t* const _lb, /**< Lower bound vector (on variables). \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const _ub, /**< Upper bound vector (on variables). \n - If no upper bounds exist, a NULL pointer can be passed. */ - const real_t* const _lbA, /**< Lower constraints' bound vector. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - const real_t* const _ubA /**< Upper constraints' bound vector. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - ); - -/** Sets up internal QP data by loading it from files. If the current Hessian - * is trivial (i.e. HST_ZERO or HST_IDENTITY) but a non-trivial one is given, - * memory for Hessian is allocated and it is set to the given one. - * \return SUCCESSFUL_RETURN \n - RET_UNABLE_TO_OPEN_FILE \n - RET_UNABLE_TO_READ_FILE \n - RET_INVALID_ARGUMENTS \n - RET_UNKNONW_BUG */ -returnValue QProblem_setupQPdataFromFile( QProblem* _THIS, - const char* const H_file, /**< Name of file where Hessian matrix, of neighbouring QP to be solved, is stored. \n - If Hessian matrix is trivial,a NULL pointer can be passed. */ - const char* const g_file, /**< Name of file where gradient, of neighbouring QP to be solved, is stored. */ - const char* const A_file, /**< Name of file where constraint matrix, of neighbouring QP to be solved, is stored. */ - const char* const lb_file, /**< Name of file where lower bounds, of neighbouring QP to be solved, is stored. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const char* const ub_file, /**< Name of file where upper bounds, of neighbouring QP to be solved, is stored. \n - If no upper bounds exist, a NULL pointer can be passed. */ - const char* const lbA_file, /**< Name of file where lower constraints' bounds, of neighbouring QP to be solved, is stored. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - const char* const ubA_file /**< Name of file where upper constraints' bounds, of neighbouring QP to be solved, is stored. \n - If no upper constraints' bounds exist, a NULL pointer can be passed. */ - ); - -/** Loads new QP vectors from files (internal members are not affected!). - * \return SUCCESSFUL_RETURN \n - RET_UNABLE_TO_OPEN_FILE \n - RET_UNABLE_TO_READ_FILE \n - RET_INVALID_ARGUMENTS */ -returnValue QProblem_loadQPvectorsFromFile( QProblem* _THIS, - const char* const g_file, /**< Name of file where gradient, of neighbouring QP to be solved, is stored. */ - const char* const lb_file, /**< Name of file where lower bounds, of neighbouring QP to be solved, is stored. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const char* const ub_file, /**< Name of file where upper bounds, of neighbouring QP to be solved, is stored. \n - If no upper bounds exist, a NULL pointer can be passed. */ - const char* const lbA_file, /**< Name of file where lower constraints' bounds, of neighbouring QP to be solved, is stored. \n - If no lower constraints' bounds exist, a NULL pointer can be passed. */ - const char* const ubA_file, /**< Name of file where upper constraints' bounds, of neighbouring QP to be solved, is stored. \n - If no upper constraints' bounds exist, a NULL pointer can be passed. */ - real_t* const g_new, /**< Output: Gradient of neighbouring QP to be solved. */ - real_t* const lb_new, /**< Output: Lower bounds of neighbouring QP to be solved */ - real_t* const ub_new, /**< Output: Upper bounds of neighbouring QP to be solved */ - real_t* const lbA_new, /**< Output: Lower constraints' bounds of neighbouring QP to be solved */ - real_t* const ubA_new /**< Output: Upper constraints' bounds of neighbouring QP to be solved */ - ); - - -/** Prints concise information on the current iteration. - * \return SUCCESSFUL_RETURN \n */ -returnValue QProblem_printIteration( QProblem* _THIS, - int iter, /**< Number of current iteration. */ - int BC_idx, /**< Index of blocking constraint. */ - SubjectToStatus BC_status, /**< Status of blocking constraint. */ - BooleanType BC_isBound, /**< Indicates if blocking constraint is a bound. */ - real_t homotopyLength, /**< Current homotopy distance. */ - BooleanType isFirstCall /**< Indicating whether this is the first call for current QP. */ - ); - - -/** Sets constraint matrix of the QP. \n - Note: Also internal vector Ax is recomputed! - * \return SUCCESSFUL_RETURN \n - * RET_INVALID_ARGUMENTS */ -static inline returnValue QProblem_setAM( QProblem* _THIS, - DenseMatrix *A_new /**< New constraint matrix. */ - ); - -/** Sets dense constraint matrix of the QP. \n - Note: Also internal vector Ax is recomputed! - * \return SUCCESSFUL_RETURN \n - * RET_INVALID_ARGUMENTS */ -static inline returnValue QProblem_setA( QProblem* _THIS, - real_t* const A_new /**< New dense constraint matrix (with correct dimension!). */ - ); - - -/** Sets constraints' lower bound vector of the QP. - * \return SUCCESSFUL_RETURN \n - * RET_QPOBJECT_NOT_SETUP */ -static inline returnValue QProblem_setLBA( QProblem* _THIS, - const real_t* const lbA_new /**< New constraints' lower bound vector (with correct dimension!). */ - ); - -/** Changes single entry of lower constraints' bound vector of the QP. - * \return SUCCESSFUL_RETURN \n - * RET_QPOBJECT_NOT_SETUP \n - * RET_INDEX_OUT_OF_BOUNDS */ -static inline returnValue QProblem_setLBAn( QProblem* _THIS, - int number, /**< Number of entry to be changed. */ - real_t value /**< New value for entry of lower constraints' bound vector (with correct dimension!). */ - ); - -/** Sets constraints' upper bound vector of the QP. - * \return SUCCESSFUL_RETURN \n - * RET_QPOBJECT_NOT_SETUP */ -static inline returnValue QProblem_setUBA( QProblem* _THIS, - const real_t* const ubA_new /**< New constraints' upper bound vector (with correct dimension!). */ - ); - -/** Changes single entry of upper constraints' bound vector of the QP. - * \return SUCCESSFUL_RETURN \n - * RET_QPOBJECT_NOT_SETUP \n - * RET_INDEX_OUT_OF_BOUNDS */ -static inline returnValue QProblem_setUBAn( QProblem* _THIS, - int number, /**< Number of entry to be changed. */ - real_t value /**< New value for entry of upper constraints' bound vector (with correct dimension!). */ - ); - - -/** Decides if lower bounds are smaller than upper bounds - * - * \return SUCCESSFUL_RETURN \n - * RET_QP_INFEASIBLE */ -returnValue QProblem_areBoundsConsistent( QProblem* _THIS, - const real_t* const lb, /**< Vector of lower bounds*/ - const real_t* const ub, /**< Vector of upper bounds*/ - const real_t* const lbA, /**< Vector of lower constraints*/ - const real_t* const ubA /**< Vector of upper constraints*/ - ); - - -/** Drops the blocking bound/constraint that led to infeasibility, or finds another - * bound/constraint to drop according to drop priorities. - * \return SUCCESSFUL_RETURN \n - */ -returnValue QProblem_dropInfeasibles ( QProblem* _THIS, - int BC_number, /**< Number of the bound or constraint to be added */ - SubjectToStatus BC_status, /**< New status of the bound or constraint to be added */ - BooleanType BC_isBound, /**< Whether a bound or a constraint is to be added */ - real_t *xiB, - real_t *xiC - ); - - -/** If Hessian type has been set by the user, nothing is done. - * Otherwise the Hessian type is set to HST_IDENTITY, HST_ZERO, or - * HST_POSDEF (default), respectively. - * \return SUCCESSFUL_RETURN \n - RET_HESSIAN_INDEFINITE */ -returnValue QProblem_determineHessianType( QProblem* _THIS ); - -/** Computes the Cholesky decomposition of the (simply projected) Hessian - * (i.e. R^T*R = Z^T*H*Z). It only works in the case where Z is a simple - * projection matrix! - * Note: If Hessian turns out not to be positive definite, the Hessian type - * is set to HST_SEMIDEF accordingly. - * \return SUCCESSFUL_RETURN \n - * RET_HESSIAN_NOT_SPD \n - * RET_INDEXLIST_CORRUPTED */ -returnValue QProblemBCPY_computeCholesky( QProblem* _THIS ); - -/** Obtains the desired working set for the auxiliary initial QP in - * accordance with the user specifications - * \return SUCCESSFUL_RETURN \n - RET_OBTAINING_WORKINGSET_FAILED \n - RET_INVALID_ARGUMENTS */ -returnValue QProblemBCPY_obtainAuxiliaryWorkingSet( QProblem* _THIS, - const real_t* const xOpt, /**< Optimal primal solution vector. - * If a NULL pointer is passed, all entries are assumed to be zero. */ - const real_t* const yOpt, /**< Optimal dual solution vector. - * If a NULL pointer is passed, all entries are assumed to be zero. */ - Bounds* const guessedBounds, /**< Guessed working set for solution (xOpt,yOpt). */ - Bounds* auxiliaryBounds /**< Input: Allocated bound object. \n - * Output: Working set for auxiliary QP. */ - ); - - -/** Solves the system Ra = b or R^Ta = b where R is an upper triangular matrix. - * \return SUCCESSFUL_RETURN \n - RET_DIV_BY_ZERO */ -returnValue QProblem_backsolveR( QProblem* _THIS, - const real_t* const b, /**< Right hand side vector. */ - BooleanType transposed, /**< Indicates if the transposed system shall be solved. */ - real_t* const a /**< Output: Solution vector */ - ); - -/** Solves the system Ra = b or R^Ta = b where R is an upper triangular matrix. \n - * Special variant for the case that _THIS function is called from within "removeBound()". - * \return SUCCESSFUL_RETURN \n - RET_DIV_BY_ZERO */ -returnValue QProblem_backsolveRrem( QProblem* _THIS, - const real_t* const b, /**< Right hand side vector. */ - BooleanType transposed, /**< Indicates if the transposed system shall be solved. */ - BooleanType removingBound, /**< Indicates if function is called from "removeBound()". */ - real_t* const a /**< Output: Solution vector */ - ); - - -/** Determines step direction of the shift of the QP data. - * \return SUCCESSFUL_RETURN */ -returnValue QProblemBCPY_determineDataShift( QProblem* _THIS, - const real_t* const g_new, /**< New gradient vector. */ - const real_t* const lb_new, /**< New lower bounds. */ - const real_t* const ub_new, /**< New upper bounds. */ - real_t* const delta_g, /**< Output: Step direction of gradient vector. */ - real_t* const delta_lb, /**< Output: Step direction of lower bounds. */ - real_t* const delta_ub, /**< Output: Step direction of upper bounds. */ - BooleanType* Delta_bB_isZero /**< Output: Indicates if active bounds are to be shifted. */ - ); - - -/** Sets up internal QP data. - * \return SUCCESSFUL_RETURN \n - RET_INVALID_ARGUMENTS */ -returnValue QProblemBCPY_setupQPdataM( QProblem* _THIS, - DenseMatrix *_H, /**< Hessian matrix.*/ - const real_t* const _g, /**< Gradient vector. */ - const real_t* const _lb, /**< Lower bounds (on variables). \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const _ub /**< Upper bounds (on variables). \n - If no upper bounds exist, a NULL pointer can be passed. */ - ); - -/** Sets up internal QP data. If the current Hessian is trivial - * (i.e. HST_ZERO or HST_IDENTITY) but a non-trivial one is given, - * memory for Hessian is allocated and it is set to the given one. - * \return SUCCESSFUL_RETURN \n - RET_INVALID_ARGUMENTS \n - RET_NO_HESSIAN_SPECIFIED */ -returnValue QProblemBCPY_setupQPdata( QProblem* _THIS, - real_t* const _H, /**< Hessian matrix. \n - If Hessian matrix is trivial,a NULL pointer can be passed. */ - const real_t* const _g, /**< Gradient vector. */ - const real_t* const _lb, /**< Lower bounds (on variables). \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const _ub /**< Upper bounds (on variables). \n - If no upper bounds exist, a NULL pointer can be passed. */ - ); - -/** Sets up internal QP data by loading it from files. If the current Hessian - * is trivial (i.e. HST_ZERO or HST_IDENTITY) but a non-trivial one is given, - * memory for Hessian is allocated and it is set to the given one. - * \return SUCCESSFUL_RETURN \n - RET_UNABLE_TO_OPEN_FILE \n - RET_UNABLE_TO_READ_FILE \n - RET_INVALID_ARGUMENTS \n - RET_NO_HESSIAN_SPECIFIED */ -returnValue QProblemBCPY_setupQPdataFromFile( QProblem* _THIS, - const char* const H_file, /**< Name of file where Hessian matrix, of neighbouring QP to be solved, is stored. \n - If Hessian matrix is trivial,a NULL pointer can be passed. */ - const char* const g_file, /**< Name of file where gradient, of neighbouring QP to be solved, is stored. */ - const char* const lb_file, /**< Name of file where lower bounds, of neighbouring QP to be solved, is stored. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const char* const ub_file /**< Name of file where upper bounds, of neighbouring QP to be solved, is stored. \n - If no upper bounds exist, a NULL pointer can be passed. */ - ); - -/** Loads new QP vectors from files (internal members are not affected!). - * \return SUCCESSFUL_RETURN \n - RET_UNABLE_TO_OPEN_FILE \n - RET_UNABLE_TO_READ_FILE \n - RET_INVALID_ARGUMENTS */ -returnValue QProblemBCPY_loadQPvectorsFromFile( QProblem* _THIS, - const char* const g_file, /**< Name of file where gradient, of neighbouring QP to be solved, is stored. */ - const char* const lb_file, /**< Name of file where lower bounds, of neighbouring QP to be solved, is stored. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const char* const ub_file, /**< Name of file where upper bounds, of neighbouring QP to be solved, is stored. \n - If no upper bounds exist, a NULL pointer can be passed. */ - real_t* const g_new, /**< Output: Gradient of neighbouring QP to be solved. */ - real_t* const lb_new, /**< Output: Lower bounds of neighbouring QP to be solved */ - real_t* const ub_new /**< Output: Upper bounds of neighbouring QP to be solved */ - ); - - -/** Sets internal infeasibility flag and throws given error in case the far bound - * strategy is not enabled (as QP might actually not be infeasible in _THIS case). - * \return RET_HOTSTART_STOPPED_INFEASIBILITY \n - RET_ENSURELI_FAILED_CYCLING \n - RET_ENSURELI_FAILED_NOINDEX */ -returnValue QProblem_setInfeasibilityFlag( QProblem* _THIS, - returnValue returnvalue, /**< Returnvalue to be tunneled. */ - BooleanType doThrowError /**< Flag forcing to throw an error. */ - ); - - -/** Determines if next QP iteration can be performed within given CPU time limit. - * \return BT_TRUE: CPU time limit is exceeded, stop QP solution. \n - BT_FALSE: Sufficient CPU time for next QP iteration. */ -BooleanType QProblem_isCPUtimeLimitExceeded( QProblem* _THIS, - const real_t* const cputime, /**< Maximum CPU time allowed for QP solution. */ - real_t starttime, /**< Start time of current QP solution. */ - int nWSR /**< Number of working set recalculations performed so far. */ - ); - - -/** Regularise Hessian matrix by adding a scaled identity matrix to it. - * \return SUCCESSFUL_RETURN \n - RET_HESSIAN_ALREADY_REGULARISED */ -returnValue QProblem_regulariseHessian( QProblem* _THIS ); - - -/** Sets Hessian matrix of the QP. - * \return SUCCESSFUL_RETURN */ -static inline returnValue QProblem_setHM( QProblem* _THIS, - DenseMatrix* H_new /**< New Hessian matrix. */ - ); - -/** Sets dense Hessian matrix of the QP. - * If a null pointer is passed and - * a) hessianType is HST_IDENTITY, nothing is done, - * b) hessianType is not HST_IDENTITY, Hessian matrix is set to zero. - * \return SUCCESSFUL_RETURN */ -static inline returnValue QProblem_setH( QProblem* _THIS, - real_t* const H_new /**< New dense Hessian matrix (with correct dimension!). */ - ); - -/** Changes gradient vector of the QP. - * \return SUCCESSFUL_RETURN \n - * RET_INVALID_ARGUMENTS */ -static inline returnValue QProblem_setG( QProblem* _THIS, - const real_t* const g_new /**< New gradient vector (with correct dimension!). */ - ); - -/** Changes lower bound vector of the QP. - * \return SUCCESSFUL_RETURN \n - * RET_INVALID_ARGUMENTS */ -static inline returnValue QProblem_setLB( QProblem* _THIS, - const real_t* const lb_new /**< New lower bound vector (with correct dimension!). */ - ); - -/** Changes single entry of lower bound vector of the QP. - * \return SUCCESSFUL_RETURN \n - RET_INDEX_OUT_OF_BOUNDS */ -static inline returnValue QProblem_setLBn( QProblem* _THIS, - int number, /**< Number of entry to be changed. */ - real_t value /**< New value for entry of lower bound vector. */ - ); - -/** Changes upper bound vector of the QP. - * \return SUCCESSFUL_RETURN \n - * RET_INVALID_ARGUMENTS */ -static inline returnValue QProblem_setUB( QProblem* _THIS, - const real_t* const ub_new /**< New upper bound vector (with correct dimension!). */ - ); - -/** Changes single entry of upper bound vector of the QP. - * \return SUCCESSFUL_RETURN \n - RET_INDEX_OUT_OF_BOUNDS */ -static inline returnValue QProblem_setUBn( QProblem* _THIS, - int number, /**< Number of entry to be changed. */ - real_t value /**< New value for entry of upper bound vector. */ - ); - - - -/** Compute relative length of homotopy in data space for termination - * criterion. - * \return Relative length in data space. */ -real_t QProblemBCPY_getRelativeHomotopyLength( QProblem* _THIS, - const real_t* const g_new, /**< Final gradient. */ - const real_t* const lb_new, /**< Final lower variable bounds. */ - const real_t* const ub_new /**< Final upper variable bounds. */ - ); - - - -/** Performs robustified ratio test yield the maximum possible step length - * along the homotopy path. - * \return SUCCESSFUL_RETURN */ -returnValue QProblem_performRatioTestB( QProblem* _THIS, - int nIdx, /**< Number of ratios to be checked. */ - const int* const idxList, /**< Array containing the indices of all ratios to be checked. */ - Bounds* const subjectTo, /**< Bound object corresponding to ratios to be checked. */ - const real_t* const num, /**< Array containing all numerators for performing the ratio test. */ - const real_t* const den, /**< Array containing all denominators for performing the ratio test. */ - real_t epsNum, /**< Numerator tolerance. */ - real_t epsDen, /**< Denominator tolerance. */ - real_t* t, /**< Output: Maximum possible step length along the homotopy path. */ - int* BC_idx /**< Output: Index of blocking constraint. */ - ); - -/** Checks whether given ratio is blocking, i.e. limits the maximum step length - * along the homotopy path to a value lower than given one. - * \return SUCCESSFUL_RETURN */ -static inline BooleanType QProblem_isBlocking( QProblem* _THIS, - real_t num, /**< Numerator for performing the ratio test. */ - real_t den, /**< Denominator for performing the ratio test. */ - real_t epsNum, /**< Numerator tolerance. */ - real_t epsDen, /**< Denominator tolerance. */ - real_t* t /**< Input: Current maximum step length along the homotopy path, - * Output: Updated maximum possible step length along the homotopy path. */ - ); - - -/** ... - * \return SUCCESSFUL_RETURN \n - RET_UNABLE_TO_OPEN_FILE */ -returnValue QProblem_writeQpDataIntoMatFile( QProblem* _THIS, - const char* const filename /**< Mat file name. */ - ); - -/** ... -* \return SUCCESSFUL_RETURN \n - RET_UNABLE_TO_OPEN_FILE */ -returnValue QProblem_writeQpWorkspaceIntoMatFile( QProblem* _THIS, - const char* const filename /**< Mat file name. */ - ); - - -/* - * g e t B o u n d s - */ -static inline returnValue QProblem_getBounds( QProblem* _THIS, Bounds* _bounds ) -{ - int nV = QProblem_getNV( _THIS ); - - if ( nV == 0 ) - return THROWERROR( RET_QPOBJECT_NOT_SETUP ); - - _bounds = _THIS->bounds; - - return SUCCESSFUL_RETURN; -} - - -/* - * g e t N V - */ -static inline int QProblem_getNV( QProblem* _THIS ) -{ - return Bounds_getNV( _THIS->bounds ); -} - - -/* - * g e t N F R - */ -static inline int QProblem_getNFR( QProblem* _THIS ) -{ - return Bounds_getNFR( _THIS->bounds ); -} - - -/* - * g e t N F X - */ -static inline int QProblem_getNFX( QProblem* _THIS ) -{ - return Bounds_getNFX( _THIS->bounds ); -} - - -/* - * g e t N F V - */ -static inline int QProblem_getNFV( QProblem* _THIS ) -{ - return Bounds_getNFV( _THIS->bounds ); -} - - -/* - * g e t S t a t u s - */ -static inline QProblemStatus QProblem_getStatus( QProblem* _THIS ) -{ - return _THIS->status; -} - - -/* - * i s I n i t i a l i s e d - */ -static inline BooleanType QProblem_isInitialised( QProblem* _THIS ) -{ - if ( _THIS->status == QPS_NOTINITIALISED ) - return BT_FALSE; - else - return BT_TRUE; -} - - -/* - * i s S o l v e d - */ -static inline BooleanType QProblem_isSolved( QProblem* _THIS ) -{ - if ( _THIS->status == QPS_SOLVED ) - return BT_TRUE; - else - return BT_FALSE; -} - - -/* - * i s I n f e a s i b l e - */ -static inline BooleanType QProblem_isInfeasible( QProblem* _THIS ) -{ - return _THIS->infeasible; -} - - -/* - * i s U n b o u n d e d - */ -static inline BooleanType QProblem_isUnbounded( QProblem* _THIS ) -{ - return _THIS->unbounded; -} - - -/* - * g e t H e s s i a n T y p e - */ -static inline HessianType QProblem_getHessianType( QProblem* _THIS ) -{ - return _THIS->hessianType; -} - - -/* - * s e t H e s s i a n T y p e - */ -static inline returnValue QProblem_setHessianType( QProblem* _THIS, HessianType _hessianType ) -{ - _THIS->hessianType = _hessianType; - return SUCCESSFUL_RETURN; -} - - -/* - * u s i n g R e g u l a r i s a t i o n - */ -static inline BooleanType QProblem_usingRegularisation( QProblem* _THIS ) -{ - if ( _THIS->regVal > QPOASES_ZERO ) - return BT_TRUE; - else - return BT_FALSE; -} - - -/* - * g e t O p t i o n s - */ -static inline Options QProblem_getOptions( QProblem* _THIS ) -{ - return _THIS->options; -} - - -/* - * s e t O p t i o n s - */ -static inline returnValue QProblem_setOptions( QProblem* _THIS, - Options _options - ) -{ - OptionsCPY( &_options,&(_THIS->options) ); - Options_ensureConsistency( &(_THIS->options) ); - - QProblem_setPrintLevel( _THIS,_THIS->options.printLevel ); - - return SUCCESSFUL_RETURN; -} - - -/* - * g e t P r i n t L e v e l - */ -static inline PrintLevel QProblem_getPrintLevel( QProblem* _THIS ) -{ - return _THIS->options.printLevel; -} - - -/* - * g e t C o u n t - */ -static inline unsigned int QProblem_getCount( QProblem* _THIS ) -{ - return _THIS->count; -} - - -/* - * r e s e t C o u n t e r - */ -static inline returnValue QProblem_resetCounter( QProblem* _THIS ) -{ - _THIS->count = 0; - return SUCCESSFUL_RETURN; -} - - - -/***************************************************************************** - * P R O T E C T E D * - *****************************************************************************/ - - -/* - * s e t H - */ -static inline returnValue QProblem_setHM( QProblem* _THIS, DenseMatrix* H_new ) -{ - if ( H_new == 0 ) - return QProblem_setH( _THIS,(real_t*)0 ); - else - return QProblem_setH( _THIS,DenseMatrix_getVal(H_new) ); -} - - -/* - * s e t H - */ -static inline returnValue QProblem_setH( QProblem* _THIS, real_t* const H_new ) -{ - /* if null pointer is passed, Hessian is set to zero matrix - * (or stays identity matrix) */ - if ( H_new == 0 ) - { - if ( _THIS->hessianType == HST_IDENTITY ) - return SUCCESSFUL_RETURN; - - _THIS->hessianType = HST_ZERO; - - _THIS->H = 0; - } - else - { - DenseMatrixCON( _THIS->H,QProblem_getNV( _THIS ),QProblem_getNV( _THIS ),QProblem_getNV( _THIS ),H_new ); - } - - return SUCCESSFUL_RETURN; -} - - -/* - * s e t G - */ -static inline returnValue QProblem_setG( QProblem* _THIS, const real_t* const g_new ) -{ - unsigned int nV = (unsigned int)QProblem_getNV( _THIS ); - - if ( nV == 0 ) - return THROWERROR( RET_QPOBJECT_NOT_SETUP ); - - if ( g_new == 0 ) - return THROWERROR( RET_INVALID_ARGUMENTS ); - - memcpy( _THIS->g,g_new,nV*sizeof(real_t) ); - - return SUCCESSFUL_RETURN; -} - - -/* - * s e t L B - */ -static inline returnValue QProblem_setLB( QProblem* _THIS, const real_t* const lb_new ) -{ - unsigned int i; - unsigned int nV = (unsigned int)QProblem_getNV( _THIS ); - - if ( nV == 0 ) - return THROWERROR( RET_QPOBJECT_NOT_SETUP ); - - if ( lb_new != 0 ) - { - memcpy( _THIS->lb,lb_new,nV*sizeof(real_t) ); - } - else - { - /* if no lower bounds are specified, set them to -infinity */ - for( i=0; ilb[i] = -QPOASES_INFTY; - } - - return SUCCESSFUL_RETURN; -} - - -/* - * s e t L B - */ -static inline returnValue QProblem_setLBn( QProblem* _THIS, int number, real_t value ) -{ - int nV = QProblem_getNV( _THIS ); - - if ( nV == 0 ) - return THROWERROR( RET_QPOBJECT_NOT_SETUP ); - - if ( ( number >= 0 ) && ( number < nV ) ) - { - _THIS->lb[number] = value; - return SUCCESSFUL_RETURN; - } - else - { - return THROWERROR( RET_INDEX_OUT_OF_BOUNDS ); - } -} - - -/* - * s e t U B - */ -static inline returnValue QProblem_setUB( QProblem* _THIS, const real_t* const ub_new ) -{ - unsigned int i; - unsigned int nV = (unsigned int)QProblem_getNV( _THIS ); - - if ( nV == 0 ) - return THROWERROR( RET_QPOBJECT_NOT_SETUP ); - - if ( ub_new != 0 ) - { - memcpy( _THIS->ub,ub_new,nV*sizeof(real_t) ); - } - else - { - /* if no upper bounds are specified, set them to infinity */ - for( i=0; iub[i] = QPOASES_INFTY; - } - - return SUCCESSFUL_RETURN; -} - - -/* - * s e t U B - */ -static inline returnValue QProblem_setUBn( QProblem* _THIS, int number, real_t value ) -{ - int nV = QProblem_getNV( _THIS ); - - if ( nV == 0 ) - return THROWERROR( RET_QPOBJECT_NOT_SETUP ); - - if ( ( number >= 0 ) && ( number < nV ) ) - { - _THIS->ub[number] = value; - - return SUCCESSFUL_RETURN; - } - else - { - return THROWERROR( RET_INDEX_OUT_OF_BOUNDS ); - } -} - - - -/* - * i s B l o c k i n g - */ -static inline BooleanType QProblem_isBlocking( QProblem* _THIS, - real_t num, - real_t den, - real_t epsNum, - real_t epsDen, - real_t* t - ) -{ - if ( ( den >= epsDen ) && ( num >= epsNum ) ) - { - if ( num < (*t)*den ) - return BT_TRUE; - } - - return BT_FALSE; -} - - - -/* - * g e t C o n s t r a i n t s - */ -static inline returnValue QProblem_getConstraints( QProblem* _THIS, Constraints* _constraints ) -{ - int nV = QProblem_getNV( _THIS ); - - if ( nV == 0 ) - return THROWERROR( RET_QPOBJECT_NOT_SETUP ); - - ConstraintsCPY( _THIS->constraints,_constraints ); - - return SUCCESSFUL_RETURN; -} - - - -/* - * g e t N C - */ -static inline int QProblem_getNC( QProblem* _THIS ) -{ - return Constraints_getNC( _THIS->constraints ); -} - - -/* - * g e t N E C - */ -static inline int QProblem_getNEC( QProblem* _THIS ) -{ - return Constraints_getNEC( _THIS->constraints ); -} - - -/* - * g e t N A C - */ -static inline int QProblem_getNAC( QProblem* _THIS ) -{ - return Constraints_getNAC( _THIS->constraints ); -} - - -/* - * g e t N I A C - */ -static inline int QProblem_getNIAC( QProblem* _THIS ) -{ - return Constraints_getNIAC( _THIS->constraints ); -} - - - -/***************************************************************************** - * P R O T E C T E D * - *****************************************************************************/ - - -/* - * s e t A - */ -static inline returnValue QProblem_setAM( QProblem* _THIS, DenseMatrix *A_new ) -{ - if ( A_new == 0 ) - return QProblem_setA( _THIS,(real_t*)0 ); - else - return QProblem_setA( _THIS,DenseMatrix_getVal(A_new) ); -} - - -/* - * s e t A - */ -static inline returnValue QProblem_setA( QProblem* _THIS, real_t* const A_new ) -{ - int j; - int nV = QProblem_getNV( _THIS ); - int nC = QProblem_getNC( _THIS ); - - if ( nV == 0 ) - return THROWERROR( RET_QPOBJECT_NOT_SETUP ); - - if ( A_new == 0 ) - return THROWERROR( RET_INVALID_ARGUMENTS ); - - DenseMatrixCON( _THIS->A,QProblem_getNC( _THIS ),QProblem_getNV( _THIS ),QProblem_getNV( _THIS ),A_new ); - - DenseMatrix_times( _THIS->A,1, 1.0, _THIS->x, nV, 0.0, _THIS->Ax, nC); - - for( j=0; jAx_u[j] = _THIS->ubA[j] - _THIS->Ax[j]; - _THIS->Ax_l[j] = _THIS->Ax[j] - _THIS->lbA[j]; - - /* (ckirches) disable constraints with empty rows */ - if ( qpOASES_isZero( DenseMatrix_getRowNorm( _THIS->A,j,2 ),QPOASES_ZERO ) == BT_TRUE ) - Constraints_setType( _THIS->constraints,j,ST_DISABLED ); - } - - return SUCCESSFUL_RETURN; -} - - -/* - * s e t L B A - */ -static inline returnValue QProblem_setLBA( QProblem* _THIS, const real_t* const lbA_new ) -{ - unsigned int i; - unsigned int nV = (unsigned int)QProblem_getNV( _THIS ); - unsigned int nC = (unsigned int)QProblem_getNC( _THIS ); - - if ( nV == 0 ) - return THROWERROR( RET_QPOBJECT_NOT_SETUP ); - - if ( lbA_new != 0 ) - { - memcpy( _THIS->lbA,lbA_new,nC*sizeof(real_t) ); - } - else - { - /* if no lower constraints' bounds are specified, set them to -infinity */ - for( i=0; ilbA[i] = -QPOASES_INFTY; - } - - return SUCCESSFUL_RETURN; -} - - -/* - * s e t L B A - */ -static inline returnValue QProblem_setLBAn( QProblem* _THIS, int number, real_t value ) -{ - int nV = QProblem_getNV( _THIS ); - int nC = QProblem_getNC( _THIS ); - - if ( nV == 0 ) - return THROWERROR( RET_QPOBJECT_NOT_SETUP ); - - if ( ( number >= 0 ) && ( number < nC ) ) - { - _THIS->lbA[number] = value; - return SUCCESSFUL_RETURN; - } - else - return THROWERROR( RET_INDEX_OUT_OF_BOUNDS ); -} - - -/* - * s e t U B A - */ -static inline returnValue QProblem_setUBA( QProblem* _THIS, const real_t* const ubA_new ) -{ - unsigned int i; - unsigned int nV = (unsigned int)QProblem_getNV( _THIS ); - unsigned int nC = (unsigned int)QProblem_getNC( _THIS ); - - if ( nV == 0 ) - return THROWERROR( RET_QPOBJECT_NOT_SETUP ); - - if ( ubA_new != 0 ) - { - memcpy( _THIS->ubA,ubA_new,nC*sizeof(real_t) ); - } - else - { - /* if no upper constraints' bounds are specified, set them to infinity */ - for( i=0; iubA[i] = QPOASES_INFTY; - } - - return SUCCESSFUL_RETURN; -} - - -/* - * s e t U B A - */ -static inline returnValue QProblem_setUBAn( QProblem* _THIS, int number, real_t value ) -{ - int nV = QProblem_getNV( _THIS ); - int nC = QProblem_getNC( _THIS ); - - if ( nV == 0 ) - return THROWERROR( RET_QPOBJECT_NOT_SETUP ); - - if ( ( number >= 0 ) && ( number < nC ) ) - { - _THIS->ubA[number] = value; - return SUCCESSFUL_RETURN; - } - else - return THROWERROR( RET_INDEX_OUT_OF_BOUNDS ); -} - - -END_NAMESPACE_QPOASES - - -#endif /* QPOASES_QPROBLEM_H */ - - -/* - * end of file - */ diff --git a/third_party/acados/include/qpOASES_e/QProblemB.h b/third_party/acados/include/qpOASES_e/QProblemB.h deleted file mode 100644 index ee5157dda7..0000000000 --- a/third_party/acados/include/qpOASES_e/QProblemB.h +++ /dev/null @@ -1,1641 +0,0 @@ -/* - * This file is part of qpOASES. - * - * qpOASES -- An Implementation of the Online Active Set Strategy. - * Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka, - * Christian Kirches et al. All rights reserved. - * - * qpOASES is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * qpOASES is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with qpOASES; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/** - * \file include/qpOASES_e/QProblemB.h - * \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches - * \version 3.1embedded - * \date 2007-2015 - * - * Declaration of the QProblemB class which is able to use the newly - * developed online active set strategy for parametric quadratic programming - * for problems with (simple) bounds only. - */ - - - -#ifndef QPOASES_QPROBLEMB_H -#define QPOASES_QPROBLEMB_H - - -#include -#include -#include -#include - - -BEGIN_NAMESPACE_QPOASES - -typedef struct { - Bounds *emptyBounds; - Bounds *auxiliaryBounds; - - real_t *ub_new_far; - real_t *lb_new_far; - - real_t *g_new; - real_t *lb_new; - real_t *ub_new; - - real_t *g_new2; - real_t *lb_new2; - real_t *ub_new2; - - real_t *Hx; - - real_t *_H; - - real_t *g_original; - real_t *lb_original; - real_t *ub_original; - - real_t *delta_xFR; - real_t *delta_xFX; - real_t *delta_yFX; - real_t *delta_g; - real_t *delta_lb; - real_t *delta_ub; - - real_t *gMod; - - real_t *num; - real_t *den; - - real_t *rhs; - real_t *r; -} QProblemB_ws; - -int QProblemB_ws_calculateMemorySize( unsigned int nV ); - -char *QProblemB_ws_assignMemory( unsigned int nV, QProblemB_ws **mem, void *raw_memory ); - -QProblemB_ws *QProblemB_ws_createMemory( unsigned int nV ); - - -/** - * \brief Implements the online active set strategy for box-constrained QPs. - * - * Class for setting up and solving quadratic programs with bounds (= box constraints) only. - * The main feature is the possibility to use the newly developed online active set strategy - * for parametric quadratic programming. - * - * \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches - * \version 3.1embedded - * \date 2007-2015 - */ -typedef struct -{ - QProblemB_ws *ws; - Bounds *bounds; /**< Data structure for problem's bounds. */ - Flipper *flipper; /**< Struct for making a temporary copy of the matrix factorisations. */ - - DenseMatrix* H; /**< Hessian matrix pointer. */ - - Options options; /**< Struct containing all user-defined options for solving QPs. */ - TabularOutput tabularOutput; /**< Struct storing information for tabular output (printLevel == PL_TABULAR). */ - - real_t *g; /**< Gradient. */ - real_t *lb; /**< Lower bound vector (on variables). */ - real_t *ub; /**< Upper bound vector (on variables). */ - - real_t *R; /**< Cholesky factor of H (i.e. H = R^T*R). */ - - real_t *x; /**< Primal solution vector. */ - real_t *y; /**< Dual solution vector. */ - - real_t *delta_xFR_TMP; /**< Temporary for determineStepDirection */ - - real_t tau; /**< Last homotopy step length. */ - real_t regVal; /**< Holds the offset used to regularise Hessian matrix (zero by default). */ - - real_t ramp0; /**< Start value for Ramping Strategy. */ - real_t ramp1; /**< Final value for Ramping Strategy. */ - - QProblemStatus status; /**< Current status of the solution process. */ - HessianType hessianType; /**< Type of Hessian matrix. */ - - BooleanType haveCholesky; /**< Flag indicating whether Cholesky decomposition has already been setup. */ - BooleanType infeasible; /**< QP infeasible? */ - BooleanType unbounded; /**< QP unbounded? */ - - int rampOffset; /**< Offset index for Ramping. */ - unsigned int count; /**< Counts the number of hotstart function calls (internal usage only!). */ -} QProblemB; - -int QProblemB_calculateMemorySize( unsigned int nV ); - -char *QProblemB_assignMemory( unsigned int nV, QProblemB **mem, void *raw_memory ); - -QProblemB *QProblemB_createMemory( unsigned int nV ); - - -/** Constructor which takes the QP dimension and Hessian type - * information. If the Hessian is the zero (i.e. HST_ZERO) or the - * identity matrix (i.e. HST_IDENTITY), respectively, no memory - * is allocated for it and a NULL pointer can be passed for it - * to the init() functions. */ -void QProblemBCON( QProblemB* _THIS, - int _nV, /**< Number of variables. */ - HessianType _hessianType /**< Type of Hessian matrix. */ - ); - -void QProblemBCPY( QProblemB* FROM, - QProblemB* TO - ); - - -/** Clears all data structures of QProblemB except for QP data. - * \return SUCCESSFUL_RETURN \n - RET_RESET_FAILED */ -returnValue QProblemB_reset( QProblemB* _THIS ); - - -/** Initialises a simply bounded QP problem with given QP data and tries to solve it - * using at most nWSR iterations. - * - * Note: This function internally calls solveInitialQP for initialisation! - * - * \return SUCCESSFUL_RETURN \n - RET_INIT_FAILED \n - RET_INIT_FAILED_CHOLESKY \n - RET_INIT_FAILED_HOTSTART \n - RET_INIT_FAILED_INFEASIBILITY \n - RET_INIT_FAILED_UNBOUNDEDNESS \n - RET_MAX_NWSR_REACHED \n - RET_INVALID_ARGUMENTS */ -returnValue QProblemB_initM( QProblemB* _THIS, - DenseMatrix *_H, /**< Hessian matrix. */ - const real_t* const _g, /**< Gradient vector. */ - const real_t* const _lb, /**< Lower bounds (on variables). \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const _ub, /**< Upper bounds (on variables). \n - If no upper bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations when using initial homotopy. \n - Output: Number of performed working set recalculations. */ - real_t* const cputime /**< Input: Maximum CPU time allowed for QP initialisation. \n - Output: CPU time spent for QP initialisation (if pointer passed). */ - ); - -/** Initialises a simply bounded QP problem with given QP data and tries to solve it - * using at most nWSR iterations. - * - * Note: This function internally calls solveInitialQP for initialisation! - * - * \return SUCCESSFUL_RETURN \n - RET_INIT_FAILED \n - RET_INIT_FAILED_CHOLESKY \n - RET_INIT_FAILED_HOTSTART \n - RET_INIT_FAILED_INFEASIBILITY \n - RET_INIT_FAILED_UNBOUNDEDNESS \n - RET_MAX_NWSR_REACHED \n - RET_INVALID_ARGUMENTS */ -returnValue QProblemB_init( QProblemB* _THIS, - real_t* const _H, /**< Hessian matrix. \n - If Hessian matrix is trivial, a NULL pointer can be passed. */ - const real_t* const _g, /**< Gradient vector. */ - const real_t* const _lb, /**< Lower bounds (on variables). \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const _ub, /**< Upper bounds (on variables). \n - If no upper bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations when using initial homotopy. \n - Output: Number of performed working set recalculations. */ - real_t* const cputime /**< Input: Maximum CPU time allowed for QP initialisation. \n - Output: CPU time spent for QP initialisation (if pointer passed). */ - ); - -/** Initialises a simply bounded QP problem with given QP data to be read from files and solves it - * using at most nWSR iterations. - * - * Note: This function internally calls solveInitialQP for initialisation! - * - * \return SUCCESSFUL_RETURN \n - RET_INIT_FAILED \n - RET_INIT_FAILED_CHOLESKY \n - RET_INIT_FAILED_HOTSTART \n - RET_INIT_FAILED_INFEASIBILITY \n - RET_INIT_FAILED_UNBOUNDEDNESS \n - RET_MAX_NWSR_REACHED \n - RET_UNABLE_TO_READ_FILE */ -returnValue QProblemB_initF( QProblemB* _THIS, - const char* const H_file, /**< Name of file where Hessian matrix is stored. \n - If Hessian matrix is trivial, a NULL pointer can be passed. */ - const char* const g_file, /**< Name of file where gradient vector is stored. */ - const char* const lb_file, /**< Name of file where lower bound vector. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const char* const ub_file, /**< Name of file where upper bound vector. \n - If no upper bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations when using initial homotopy. \n - Output: Number of performed working set recalculations. */ - real_t* const cputime /**< Input: Maximum CPU time allowed for QP initialisation. \n - Output: CPU time spent for QP initialisation (if pointer passed). */ - ); - -/** Initialises a simply bounded QP problem with given QP data and tries to solve it - * using at most nWSR iterations. Depending on the parameter constellation it: \n - * 1. 0, 0, 0 : starts with xOpt = 0, yOpt = 0 and gB empty (or all implicit equality bounds), \n - * 2. xOpt, 0, 0 : starts with xOpt, yOpt = 0 and obtain gB by "clipping", \n - * 3. 0, yOpt, 0 : starts with xOpt = 0, yOpt and obtain gB from yOpt != 0, \n - * 4. 0, 0, gB: starts with xOpt = 0, yOpt = 0 and gB, \n - * 5. xOpt, yOpt, 0 : starts with xOpt, yOpt and obtain gB from yOpt != 0, \n - * 6. xOpt, 0, gB: starts with xOpt, yOpt = 0 and gB, \n - * 7. xOpt, yOpt, gB: starts with xOpt, yOpt and gB (assume them to be consistent!) - * - * Note: This function internally calls solveInitialQP for initialisation! - * - * \return SUCCESSFUL_RETURN \n - RET_INIT_FAILED \n - RET_INIT_FAILED_CHOLESKY \n - RET_INIT_FAILED_HOTSTART \n - RET_INIT_FAILED_INFEASIBILITY \n - RET_INIT_FAILED_UNBOUNDEDNESS \n - RET_MAX_NWSR_REACHED \n - RET_INVALID_ARGUMENTS */ -returnValue QProblemB_initMW( QProblemB* _THIS, - DenseMatrix *_H, /**< Hessian matrix. */ - const real_t* const _g, /**< Gradient vector. */ - const real_t* const _lb, /**< Lower bounds (on variables). \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const _ub, /**< Upper bounds (on variables). \n - If no upper bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations when using initial homotopy. \n - Output: Number of performed working set recalculations. */ - real_t* const cputime, /**< Input: Maximum CPU time allowed for QP initialisation. \n - Output: CPU time spent for QP initialisation. */ - const real_t* const xOpt, /**< Optimal primal solution vector. A NULL pointer can be passed. \n - (If a null pointer is passed, the old primal solution is kept!) */ - const real_t* const yOpt, /**< Optimal dual solution vector. A NULL pointer can be passed. \n - (If a null pointer is passed, the old dual solution is kept!) */ - Bounds* const guessedBounds, /**< Optimal working set of bounds for solution (xOpt,yOpt). \n - (If a null pointer is passed, all bounds are assumed inactive!) */ - const real_t* const _R /**< Pre-computed (upper triangular) Cholesky factor of Hessian matrix. - The Cholesky factor must be stored in a real_t array of size nV*nV - in row-major format. Note: Only used if xOpt/yOpt and gB are NULL! \n - (If a null pointer is passed, Cholesky decomposition is computed internally!) */ - ); - -/** Initialises a simply bounded QP problem with given QP data and tries to solve it - * using at most nWSR iterations. Depending on the parameter constellation it: \n - * 1. 0, 0, 0 : starts with xOpt = 0, yOpt = 0 and gB empty (or all implicit equality bounds), \n - * 2. xOpt, 0, 0 : starts with xOpt, yOpt = 0 and obtain gB by "clipping", \n - * 3. 0, yOpt, 0 : starts with xOpt = 0, yOpt and obtain gB from yOpt != 0, \n - * 4. 0, 0, gB: starts with xOpt = 0, yOpt = 0 and gB, \n - * 5. xOpt, yOpt, 0 : starts with xOpt, yOpt and obtain gB from yOpt != 0, \n - * 6. xOpt, 0, gB: starts with xOpt, yOpt = 0 and gB, \n - * 7. xOpt, yOpt, gB: starts with xOpt, yOpt and gB (assume them to be consistent!) - * - * Note: This function internally calls solveInitialQP for initialisation! - * - * \return SUCCESSFUL_RETURN \n - RET_INIT_FAILED \n - RET_INIT_FAILED_CHOLESKY \n - RET_INIT_FAILED_HOTSTART \n - RET_INIT_FAILED_INFEASIBILITY \n - RET_INIT_FAILED_UNBOUNDEDNESS \n - RET_MAX_NWSR_REACHED \n - RET_INVALID_ARGUMENTS */ -returnValue QProblemB_initW( QProblemB* _THIS, - real_t* const _H, /**< Hessian matrix. \n - If Hessian matrix is trivial, a NULL pointer can be passed. */ - const real_t* const _g, /**< Gradient vector. */ - const real_t* const _lb, /**< Lower bounds (on variables). \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const _ub, /**< Upper bounds (on variables). \n - If no upper bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations when using initial homotopy. \n - Output: Number of performed working set recalculations. */ - real_t* const cputime, /**< Input: Maximum CPU time allowed for QP initialisation. \n - Output: CPU time spent for QP initialisation. */ - const real_t* const xOpt, /**< Optimal primal solution vector. A NULL pointer can be passed. \n - (If a null pointer is passed, the old primal solution is kept!) */ - const real_t* const yOpt, /**< Optimal dual solution vector. A NULL pointer can be passed. \n - (If a null pointer is passed, the old dual solution is kept!) */ - Bounds* const guessedBounds, /**< Optimal working set of bounds for solution (xOpt,yOpt). \n - (If a null pointer is passed, all bounds are assumed inactive!) */ - const real_t* const _R /**< Pre-computed (upper triangular) Cholesky factor of Hessian matrix. - The Cholesky factor must be stored in a real_t array of size nV*nV - in row-major format. Note: Only used if xOpt/yOpt and gB are NULL! \n - (If a null pointer is passed, Cholesky decomposition is computed internally!) */ - ); - -/** Initialises a simply bounded QP problem with given QP data to be read from files and solves it - * using at most nWSR iterations. Depending on the parameter constellation it: \n - * 1. 0, 0, 0 : starts with xOpt = 0, yOpt = 0 and gB empty (or all implicit equality bounds), \n - * 2. xOpt, 0, 0 : starts with xOpt, yOpt = 0 and obtain gB by "clipping", \n - * 3. 0, yOpt, 0 : starts with xOpt = 0, yOpt and obtain gB from yOpt != 0, \n - * 4. 0, 0, gB: starts with xOpt = 0, yOpt = 0 and gB, \n - * 5. xOpt, yOpt, 0 : starts with xOpt, yOpt and obtain gB from yOpt != 0, \n - * 6. xOpt, 0, gB: starts with xOpt, yOpt = 0 and gB, \n - * 7. xOpt, yOpt, gB: starts with xOpt, yOpt and gB (assume them to be consistent!) - * - * Note: This function internally calls solveInitialQP for initialisation! - * - * \return SUCCESSFUL_RETURN \n - RET_INIT_FAILED \n - RET_INIT_FAILED_CHOLESKY \n - RET_INIT_FAILED_HOTSTART \n - RET_INIT_FAILED_INFEASIBILITY \n - RET_INIT_FAILED_UNBOUNDEDNESS \n - RET_MAX_NWSR_REACHED \n - RET_UNABLE_TO_READ_FILE */ -returnValue QProblemB_initFW( QProblemB* _THIS, - const char* const H_file, /**< Name of file where Hessian matrix is stored. \n - If Hessian matrix is trivial, a NULL pointer can be passed. */ - const char* const g_file, /**< Name of file where gradient vector is stored. */ - const char* const lb_file, /**< Name of file where lower bound vector. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const char* const ub_file, /**< Name of file where upper bound vector. \n - If no upper bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations when using initial homotopy. \n - Output: Number of performed working set recalculations. */ - real_t* const cputime, /**< Input: Maximum CPU time allowed for QP initialisation. \n - Output: CPU time spent for QP initialisation. */ - const real_t* const xOpt, /**< Optimal primal solution vector. A NULL pointer can be passed. \n - (If a null pointer is passed, the old primal solution is kept!) */ - const real_t* const yOpt, /**< Optimal dual solution vector. A NULL pointer can be passed. \n - (If a null pointer is passed, the old dual solution is kept!) */ - Bounds* const guessedBounds, /**< Optimal working set of bounds for solution (xOpt,yOpt). \n - (If a null pointer is passed, all bounds are assumed inactive!) */ - const char* const R_file /**< Name of the file where a pre-computed (upper triangular) Cholesky factor - of the Hessian matrix is stored. \n - (If a null pointer is passed, Cholesky decomposition is computed internally!) */ - ); - - -/** Solves an initialised QP sequence using the online active set strategy. - * By default, QP solution is started from previous solution. - * - * Note: This function internally calls solveQP/solveRegularisedQP - * for solving an initialised QP! - * - * \return SUCCESSFUL_RETURN \n - RET_MAX_NWSR_REACHED \n - RET_HOTSTART_FAILED_AS_QP_NOT_INITIALISED \n - RET_HOTSTART_FAILED \n - RET_SHIFT_DETERMINATION_FAILED \n - RET_STEPDIRECTION_DETERMINATION_FAILED \n - RET_STEPLENGTH_DETERMINATION_FAILED \n - RET_HOMOTOPY_STEP_FAILED \n - RET_HOTSTART_STOPPED_INFEASIBILITY \n - RET_HOTSTART_STOPPED_UNBOUNDEDNESS */ -returnValue QProblemB_hotstart( QProblemB* _THIS, - const real_t* const g_new, /**< Gradient of neighbouring QP to be solved. */ - const real_t* const lb_new, /**< Lower bounds of neighbouring QP to be solved. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const ub_new, /**< Upper bounds of neighbouring QP to be solved. \n - If no upper bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations; \n - Output: Number of performed working set recalculations. */ - real_t* const cputime /**< Input: Maximum CPU time allowed for QP solution. \n - Output: CPU time spent for QP solution (or to perform nWSR iterations). */ - ); - -/** Solves an initialised QP sequence using the online active set strategy, - * where QP data is read from files. QP solution is started from previous solution. - * - * Note: This function internally calls solveQP/solveRegularisedQP - * for solving an initialised QP! - * - * \return SUCCESSFUL_RETURN \n - RET_MAX_NWSR_REACHED \n - RET_HOTSTART_FAILED_AS_QP_NOT_INITIALISED \n - RET_HOTSTART_FAILED \n - RET_SHIFT_DETERMINATION_FAILED \n - RET_STEPDIRECTION_DETERMINATION_FAILED \n - RET_STEPLENGTH_DETERMINATION_FAILED \n - RET_HOMOTOPY_STEP_FAILED \n - RET_HOTSTART_STOPPED_INFEASIBILITY \n - RET_HOTSTART_STOPPED_UNBOUNDEDNESS \n - RET_UNABLE_TO_READ_FILE \n - RET_INVALID_ARGUMENTS */ -returnValue QProblemB_hotstartF( QProblemB* _THIS, - const char* const g_file, /**< Name of file where gradient, of neighbouring QP to be solved, is stored. */ - const char* const lb_file, /**< Name of file where lower bounds, of neighbouring QP to be solved, is stored. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const char* const ub_file, /**< Name of file where upper bounds, of neighbouring QP to be solved, is stored. \n - If no upper bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations; \n - Output: Number of performed working set recalculations. */ - real_t* const cputime /**< Input: Maximum CPU time allowed for QP solution. \n - Output: CPU time spent for QP solution (or to perform nWSR iterations). */ - ); - -/** Solves an initialised QP sequence using the online active set strategy. - * By default, QP solution is started from previous solution. If a guess - * for the working set is provided, an initialised homotopy is performed. - * - * Note: This function internally calls solveQP/solveRegularisedQP - * for solving an initialised QP! - * - * \return SUCCESSFUL_RETURN \n - RET_MAX_NWSR_REACHED \n - RET_HOTSTART_FAILED_AS_QP_NOT_INITIALISED \n - RET_HOTSTART_FAILED \n - RET_SHIFT_DETERMINATION_FAILED \n - RET_STEPDIRECTION_DETERMINATION_FAILED \n - RET_STEPLENGTH_DETERMINATION_FAILED \n - RET_HOMOTOPY_STEP_FAILED \n - RET_HOTSTART_STOPPED_INFEASIBILITY \n - RET_HOTSTART_STOPPED_UNBOUNDEDNESS \n - RET_SETUP_AUXILIARYQP_FAILED */ -returnValue QProblemB_hotstartW( QProblemB* _THIS, - const real_t* const g_new, /**< Gradient of neighbouring QP to be solved. */ - const real_t* const lb_new, /**< Lower bounds of neighbouring QP to be solved. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const ub_new, /**< Upper bounds of neighbouring QP to be solved. \n - If no upper bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations; \n - Output: Number of performed working set recalculations. */ - real_t* const cputime, /**< Input: Maximum CPU time allowed for QP solution. \n - Output: CPU time spent for QP solution (or to perform nWSR iterations). */ - Bounds* const guessedBounds /**< Optimal working set of bounds for solution (xOpt,yOpt). \n - (If a null pointer is passed, the previous working set is kept!) */ - ); - -/** Solves an initialised QP sequence using the online active set strategy, - * where QP data is read from files. - * By default, QP solution is started from previous solution. If a guess - * for the working set is provided, an initialised homotopy is performed. - * - * Note: This function internally calls solveQP/solveRegularisedQP - * for solving an initialised QP! - * - * \return SUCCESSFUL_RETURN \n - RET_MAX_NWSR_REACHED \n - RET_HOTSTART_FAILED_AS_QP_NOT_INITIALISED \n - RET_HOTSTART_FAILED \n - RET_SHIFT_DETERMINATION_FAILED \n - RET_STEPDIRECTION_DETERMINATION_FAILED \n - RET_STEPLENGTH_DETERMINATION_FAILED \n - RET_HOMOTOPY_STEP_FAILED \n - RET_HOTSTART_STOPPED_INFEASIBILITY \n - RET_HOTSTART_STOPPED_UNBOUNDEDNESS \n - RET_UNABLE_TO_READ_FILE \n - RET_INVALID_ARGUMENTS \n - RET_SETUP_AUXILIARYQP_FAILED */ -returnValue QProblemB_hotstartFW( QProblemB* _THIS, - const char* const g_file, /**< Name of file where gradient, of neighbouring QP to be solved, is stored. */ - const char* const lb_file, /**< Name of file where lower bounds, of neighbouring QP to be solved, is stored. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const char* const ub_file, /**< Name of file where upper bounds, of neighbouring QP to be solved, is stored. \n - If no upper bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations; \n - Output: Number of performed working set recalculations. */ - real_t* const cputime, /**< Input: Maximum CPU time allowed for QP solution. \n - Output: CPU time spent for QP solution (or to perform nWSR iterations). */ - Bounds* const guessedBounds /**< Optimal working set of bounds for solution (xOpt,yOpt). \n - (If a null pointer is passed, the previous working set is kept!) */ - ); - - -/** Writes a vector with the state of the working set - * \return SUCCESSFUL_RETURN \n - * RET_INVALID_ARGUMENTS */ -returnValue QProblemB_getWorkingSet( QProblemB* _THIS, - real_t* workingSet /** Output: array containing state of the working set. */ - ); - -/** Writes a vector with the state of the working set of bounds - * \return SUCCESSFUL_RETURN \n - * RET_INVALID_ARGUMENTS */ -returnValue QProblemB_getWorkingSetBounds( QProblemB* _THIS, - real_t* workingSetB /** Output: array containing state of the working set of bounds. */ - ); - -/** Writes a vector with the state of the working set of constraints - * \return SUCCESSFUL_RETURN \n - * RET_INVALID_ARGUMENTS */ -returnValue QProblemB_getWorkingSetConstraints( QProblemB* _THIS, - real_t* workingSetC /** Output: array containing state of the working set of constraints. */ - ); - - -/** Returns current bounds object of the QP (deep copy). - * \return SUCCESSFUL_RETURN \n - RET_QPOBJECT_NOT_SETUP */ -static inline returnValue QProblemB_getBounds( QProblemB* _THIS, - Bounds* _bounds /** Output: Bounds object. */ - ); - - -/** Returns the number of variables. - * \return Number of variables. */ -static inline int QProblemB_getNV( QProblemB* _THIS ); - -/** Returns the number of free variables. - * \return Number of free variables. */ -static inline int QProblemB_getNFR( QProblemB* _THIS ); - -/** Returns the number of fixed variables. - * \return Number of fixed variables. */ -static inline int QProblemB_getNFX( QProblemB* _THIS ); - -/** Returns the number of implicitly fixed variables. - * \return Number of implicitly fixed variables. */ -static inline int QProblemB_getNFV( QProblemB* _THIS ); - -/** Returns the dimension of null space. - * \return Dimension of null space. */ -int QProblemB_getNZ( QProblemB* _THIS ); - - -/** Returns the optimal objective function value. - * \return finite value: Optimal objective function value (QP was solved) \n - +infinity: QP was not yet solved */ -real_t QProblemB_getObjVal( QProblemB* _THIS ); - -/** Returns the objective function value at an arbitrary point x. - * \return Objective function value at point x */ -real_t QProblemB_getObjValX( QProblemB* _THIS, - const real_t* const _x /**< Point at which the objective function shall be evaluated. */ - ); - -/** Returns the primal solution vector. - * \return SUCCESSFUL_RETURN \n - RET_QP_NOT_SOLVED */ -returnValue QProblemB_getPrimalSolution( QProblemB* _THIS, - real_t* const xOpt /**< Output: Primal solution vector (if QP has been solved). */ - ); - -/** Returns the dual solution vector. - * \return SUCCESSFUL_RETURN \n - RET_QP_NOT_SOLVED */ -returnValue QProblemB_getDualSolution( QProblemB* _THIS, - real_t* const yOpt /**< Output: Dual solution vector (if QP has been solved). */ - ); - - -/** Returns status of the solution process. - * \return Status of solution process. */ -static inline QProblemStatus QProblemB_getStatus( QProblemB* _THIS ); - - -/** Returns if the QProblem object is initialised. - * \return BT_TRUE: QProblemB initialised \n - BT_FALSE: QProblemB not initialised */ -static inline BooleanType QProblemB_isInitialised( QProblemB* _THIS ); - -/** Returns if the QP has been solved. - * \return BT_TRUE: QProblemB solved \n - BT_FALSE: QProblemB not solved */ -static inline BooleanType QProblemB_isSolved( QProblemB* _THIS ); - -/** Returns if the QP is infeasible. - * \return BT_TRUE: QP infeasible \n - BT_FALSE: QP feasible (or not known to be infeasible!) */ -static inline BooleanType QProblemB_isInfeasible( QProblemB* _THIS ); - -/** Returns if the QP is unbounded. - * \return BT_TRUE: QP unbounded \n - BT_FALSE: QP unbounded (or not known to be unbounded!) */ -static inline BooleanType QProblemB_isUnbounded( QProblemB* _THIS ); - - -/** Returns Hessian type flag (type is not determined due to _THIS call!). - * \return Hessian type. */ -static inline HessianType QProblemB_getHessianType( QProblemB* _THIS ); - -/** Changes the print level. - * \return SUCCESSFUL_RETURN */ -static inline returnValue QProblemB_setHessianType( QProblemB* _THIS, - HessianType _hessianType /**< New Hessian type. */ - ); - -/** Returns if the QP has been internally regularised. - * \return BT_TRUE: Hessian is internally regularised for QP solution \n - BT_FALSE: No internal Hessian regularisation is used for QP solution */ -static inline BooleanType QProblemB_usingRegularisation( QProblemB* _THIS ); - -/** Returns current options struct. - * \return Current options struct. */ -static inline Options QProblemB_getOptions( QProblemB* _THIS ); - -/** Overrides current options with given ones. - * \return SUCCESSFUL_RETURN */ -static inline returnValue QProblemB_setOptions( QProblemB* _THIS, - Options _options /**< New options. */ - ); - -/** Returns the print level. - * \return Print level. */ -static inline PrintLevel QProblemB_getPrintLevel( QProblemB* _THIS ); - -/** Changes the print level. - * \return SUCCESSFUL_RETURN */ -returnValue QProblemB_setPrintLevel( QProblemB* _THIS, - PrintLevel _printlevel /**< New print level. */ - ); - -/** Returns the current number of QP problems solved. - * \return Number of QP problems solved. */ -static inline unsigned int QProblemB_getCount( QProblemB* _THIS ); - -/** Resets QP problem counter (to zero). - * \return SUCCESSFUL_RETURN. */ -static inline returnValue QProblemB_resetCounter( QProblemB* _THIS ); - - -/** Prints concise list of properties of the current QP. - * \return SUCCESSFUL_RETURN \n */ -returnValue QProblemB_printProperties( QProblemB* _THIS ); - -/** Prints a list of all options and their current values. - * \return SUCCESSFUL_RETURN \n */ -returnValue QProblemB_printOptions( QProblemB* _THIS ); - - -/** If Hessian type has been set by the user, nothing is done. - * Otherwise the Hessian type is set to HST_IDENTITY, HST_ZERO, or - * HST_POSDEF (default), respectively. - * \return SUCCESSFUL_RETURN \n - RET_HESSIAN_INDEFINITE */ -returnValue QProblemB_determineHessianType( QProblemB* _THIS ); - -/** Determines type of existing constraints and bounds (i.e. implicitly fixed, unbounded etc.). - * \return SUCCESSFUL_RETURN \n - RET_SETUPSUBJECTTOTYPE_FAILED */ -returnValue QProblemB_setupSubjectToType( QProblemB* _THIS ); - -/** Determines type of new constraints and bounds (i.e. implicitly fixed, unbounded etc.). - * \return SUCCESSFUL_RETURN \n - RET_SETUPSUBJECTTOTYPE_FAILED */ -returnValue QProblemB_setupSubjectToTypeNew( QProblemB* _THIS, - const real_t* const lb_new, /**< New lower bounds. */ - const real_t* const ub_new /**< New upper bounds. */ - ); - -/** Computes the Cholesky decomposition of the (simply projected) Hessian - * (i.e. R^T*R = Z^T*H*Z). It only works in the case where Z is a simple - * projection matrix! - * Note: If Hessian turns out not to be positive definite, the Hessian type - * is set to HST_SEMIDEF accordingly. - * \return SUCCESSFUL_RETURN \n - * RET_HESSIAN_NOT_SPD \n - * RET_INDEXLIST_CORRUPTED */ -returnValue QProblemB_computeCholesky( QProblemB* _THIS ); - -/** Computes initial Cholesky decomposition of the projected Hessian making - * use of the function setupCholeskyDecomposition() or setupCholeskyDecompositionProjected(). - * \return SUCCESSFUL_RETURN \n - * RET_HESSIAN_NOT_SPD \n - * RET_INDEXLIST_CORRUPTED */ -returnValue QProblemB_setupInitialCholesky( QProblemB* _THIS ); - - -/** Obtains the desired working set for the auxiliary initial QP in - * accordance with the user specifications - * \return SUCCESSFUL_RETURN \n - RET_OBTAINING_WORKINGSET_FAILED \n - RET_INVALID_ARGUMENTS */ -returnValue QProblemB_obtainAuxiliaryWorkingSet( QProblemB* _THIS, - const real_t* const xOpt, /**< Optimal primal solution vector. - * If a NULL pointer is passed, all entries are assumed to be zero. */ - const real_t* const yOpt, /**< Optimal dual solution vector. - * If a NULL pointer is passed, all entries are assumed to be zero. */ - Bounds* const guessedBounds, /**< Guessed working set for solution (xOpt,yOpt). */ - Bounds* auxiliaryBounds /**< Input: Allocated bound object. \n - * Ouput: Working set for auxiliary QP. */ - ); - -/** Decides if lower bounds are smaller than upper bounds - * - * \return SUCCESSFUL_RETURN \n - * RET_QP_INFEASIBLE */ -returnValue QProblemB_areBoundsConsistent( QProblemB* _THIS, - const real_t* const lb, /**< Vector of lower bounds*/ - const real_t* const ub /**< Vector of upper bounds*/ - ); - -/** Solves the system Ra = b or R^Ta = b where R is an upper triangular matrix. - * \return SUCCESSFUL_RETURN \n - RET_DIV_BY_ZERO */ -returnValue QProblemB_backsolveR( QProblemB* _THIS, - const real_t* const b, /**< Right hand side vector. */ - BooleanType transposed, /**< Indicates if the transposed system shall be solved. */ - real_t* const a /**< Output: Solution vector */ - ); - -/** Solves the system Ra = b or R^Ta = b where R is an upper triangular matrix. \n - * Special variant for the case that _THIS function is called from within "removeBound()". - * \return SUCCESSFUL_RETURN \n - RET_DIV_BY_ZERO */ -returnValue QProblemB_backsolveRrem( QProblemB* _THIS, - const real_t* const b, /**< Right hand side vector. */ - BooleanType transposed, /**< Indicates if the transposed system shall be solved. */ - BooleanType removingBound, /**< Indicates if function is called from "removeBound()". */ - real_t* const a /**< Output: Solution vector */ - ); - - -/** Determines step direction of the shift of the QP data. - * \return SUCCESSFUL_RETURN */ -returnValue QProblemB_determineDataShift( QProblemB* _THIS, - const real_t* const g_new, /**< New gradient vector. */ - const real_t* const lb_new, /**< New lower bounds. */ - const real_t* const ub_new, /**< New upper bounds. */ - real_t* const delta_g, /**< Output: Step direction of gradient vector. */ - real_t* const delta_lb, /**< Output: Step direction of lower bounds. */ - real_t* const delta_ub, /**< Output: Step direction of upper bounds. */ - BooleanType* Delta_bB_isZero/**< Output: Indicates if active bounds are to be shifted. */ - ); - - -/** Sets up internal QP data. - * \return SUCCESSFUL_RETURN \n - RET_INVALID_ARGUMENTS */ -returnValue QProblemB_setupQPdataM( QProblemB* _THIS, - DenseMatrix *_H, /**< Hessian matrix.*/ - const real_t* const _g, /**< Gradient vector. */ - const real_t* const _lb, /**< Lower bounds (on variables). \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const _ub /**< Upper bounds (on variables). \n - If no upper bounds exist, a NULL pointer can be passed. */ - ); - -/** Sets up internal QP data. If the current Hessian is trivial - * (i.e. HST_ZERO or HST_IDENTITY) but a non-trivial one is given, - * memory for Hessian is allocated and it is set to the given one. - * \return SUCCESSFUL_RETURN \n - RET_INVALID_ARGUMENTS \n - RET_NO_HESSIAN_SPECIFIED */ -returnValue QProblemB_setupQPdata( QProblemB* _THIS, - real_t* const _H, /**< Hessian matrix. \n - If Hessian matrix is trivial,a NULL pointer can be passed. */ - const real_t* const _g, /**< Gradient vector. */ - const real_t* const _lb, /**< Lower bounds (on variables). \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const _ub /**< Upper bounds (on variables). \n - If no upper bounds exist, a NULL pointer can be passed. */ - ); - -/** Sets up internal QP data by loading it from files. If the current Hessian - * is trivial (i.e. HST_ZERO or HST_IDENTITY) but a non-trivial one is given, - * memory for Hessian is allocated and it is set to the given one. - * \return SUCCESSFUL_RETURN \n - RET_UNABLE_TO_OPEN_FILE \n - RET_UNABLE_TO_READ_FILE \n - RET_INVALID_ARGUMENTS \n - RET_NO_HESSIAN_SPECIFIED */ -returnValue QProblemB_setupQPdataFromFile( QProblemB* _THIS, - const char* const H_file, /**< Name of file where Hessian matrix, of neighbouring QP to be solved, is stored. \n - If Hessian matrix is trivial,a NULL pointer can be passed. */ - const char* const g_file, /**< Name of file where gradient, of neighbouring QP to be solved, is stored. */ - const char* const lb_file, /**< Name of file where lower bounds, of neighbouring QP to be solved, is stored. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const char* const ub_file /**< Name of file where upper bounds, of neighbouring QP to be solved, is stored. \n - If no upper bounds exist, a NULL pointer can be passed. */ - ); - -/** Loads new QP vectors from files (internal members are not affected!). - * \return SUCCESSFUL_RETURN \n - RET_UNABLE_TO_OPEN_FILE \n - RET_UNABLE_TO_READ_FILE \n - RET_INVALID_ARGUMENTS */ -returnValue QProblemB_loadQPvectorsFromFile( QProblemB* _THIS, - const char* const g_file, /**< Name of file where gradient, of neighbouring QP to be solved, is stored. */ - const char* const lb_file, /**< Name of file where lower bounds, of neighbouring QP to be solved, is stored. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const char* const ub_file, /**< Name of file where upper bounds, of neighbouring QP to be solved, is stored. \n - If no upper bounds exist, a NULL pointer can be passed. */ - real_t* const g_new, /**< Output: Gradient of neighbouring QP to be solved. */ - real_t* const lb_new, /**< Output: Lower bounds of neighbouring QP to be solved */ - real_t* const ub_new /**< Output: Upper bounds of neighbouring QP to be solved */ - ); - - -/** Sets internal infeasibility flag and throws given error in case the far bound - * strategy is not enabled (as QP might actually not be infeasible in _THIS case). - * \return RET_HOTSTART_STOPPED_INFEASIBILITY \n - RET_ENSURELI_FAILED_CYCLING \n - RET_ENSURELI_FAILED_NOINDEX */ -returnValue QProblemB_setInfeasibilityFlag( QProblemB* _THIS, - returnValue returnvalue, /**< Returnvalue to be tunneled. */ - BooleanType doThrowError /**< Flag forcing to throw an error. */ - ); - - -/** Determines if next QP iteration can be performed within given CPU time limit. - * \return BT_TRUE: CPU time limit is exceeded, stop QP solution. \n - BT_FALSE: Sufficient CPU time for next QP iteration. */ -BooleanType QProblemB_isCPUtimeLimitExceeded( QProblemB* _THIS, - const real_t* const cputime, /**< Maximum CPU time allowed for QP solution. */ - real_t starttime, /**< Start time of current QP solution. */ - int nWSR /**< Number of working set recalculations performed so far. */ - ); - - -/** Regularise Hessian matrix by adding a scaled identity matrix to it. - * \return SUCCESSFUL_RETURN \n - RET_HESSIAN_ALREADY_REGULARISED */ -returnValue QProblemB_regulariseHessian( QProblemB* _THIS ); - - -/** Sets Hessian matrix of the QP. - * \return SUCCESSFUL_RETURN */ -static inline returnValue QProblemB_setHM( QProblemB* _THIS, - DenseMatrix* H_new /**< New Hessian matrix. */ - ); - -/** Sets dense Hessian matrix of the QP. - * If a null pointer is passed and - * a) hessianType is HST_IDENTITY, nothing is done, - * b) hessianType is not HST_IDENTITY, Hessian matrix is set to zero. - * \return SUCCESSFUL_RETURN */ -static inline returnValue QProblemB_setH( QProblemB* _THIS, - real_t* const H_new /**< New dense Hessian matrix (with correct dimension!). */ - ); - -/** Changes gradient vector of the QP. - * \return SUCCESSFUL_RETURN \n - * RET_INVALID_ARGUMENTS */ -static inline returnValue QProblemB_setG( QProblemB* _THIS, - const real_t* const g_new /**< New gradient vector (with correct dimension!). */ - ); - -/** Changes lower bound vector of the QP. - * \return SUCCESSFUL_RETURN \n - * RET_QPOBJECT_NOT_SETUP */ -static inline returnValue QProblemB_setLB( QProblemB* _THIS, - const real_t* const lb_new /**< New lower bound vector (with correct dimension!). */ - ); - -/** Changes single entry of lower bound vector of the QP. - * \return SUCCESSFUL_RETURN \n - * RET_QPOBJECT_NOT_SETUP \n - * RET_INDEX_OUT_OF_BOUNDS */ -static inline returnValue QProblemB_setLBn( QProblemB* _THIS, - int number, /**< Number of entry to be changed. */ - real_t value /**< New value for entry of lower bound vector. */ - ); - -/** Changes upper bound vector of the QP. - * \return SUCCESSFUL_RETURN \n - * RET_QPOBJECT_NOT_SETUP */ -static inline returnValue QProblemB_setUB( QProblemB* _THIS, - const real_t* const ub_new /**< New upper bound vector (with correct dimension!). */ - ); - -/** Changes single entry of upper bound vector of the QP. - * \return SUCCESSFUL_RETURN \n - * RET_QPOBJECT_NOT_SETUP \n - * RET_INDEX_OUT_OF_BOUNDS */ -static inline returnValue QProblemB_setUBn( QProblemB* _THIS, - int number, /**< Number of entry to be changed. */ - real_t value /**< New value for entry of upper bound vector. */ - ); - - -/** Computes parameters for the Givens matrix G for which [x,y]*G = [z,0] - * \return SUCCESSFUL_RETURN */ -static inline void QProblemB_computeGivens( real_t xold, /**< Matrix entry to be normalised. */ - real_t yold, /**< Matrix entry to be annihilated. */ - real_t* xnew, /**< Output: Normalised matrix entry. */ - real_t* ynew, /**< Output: Annihilated matrix entry. */ - real_t* c, /**< Output: Cosine entry of Givens matrix. */ - real_t* s /**< Output: Sine entry of Givens matrix. */ - ); - -/** Applies Givens matrix determined by c and s (cf. computeGivens). - * \return SUCCESSFUL_RETURN */ -static inline void QProblemB_applyGivens( real_t c, /**< Cosine entry of Givens matrix. */ - real_t s, /**< Sine entry of Givens matrix. */ - real_t nu, /**< Further factor: s/(1+c). */ - real_t xold, /**< Matrix entry to be transformed corresponding to - * the normalised entry of the original matrix. */ - real_t yold, /**< Matrix entry to be transformed corresponding to - * the annihilated entry of the original matrix. */ - real_t* xnew, /**< Output: Transformed matrix entry corresponding to - * the normalised entry of the original matrix. */ - real_t* ynew /**< Output: Transformed matrix entry corresponding to - * the annihilated entry of the original matrix. */ - ); - - - -/** Compute relative length of homotopy in data space for termination - * criterion. - * \return Relative length in data space. */ -real_t QProblemB_getRelativeHomotopyLength( QProblemB* _THIS, - const real_t* const g_new, /**< Final gradient. */ - const real_t* const lb_new, /**< Final lower variable bounds. */ - const real_t* const ub_new /**< Final upper variable bounds. */ - ); - -/** Ramping Strategy to avoid ties. Modifies homotopy start without - * changing current active set. - * \return SUCCESSFUL_RETURN */ -returnValue QProblemB_performRamping( QProblemB* _THIS ); - - -/** ... */ -returnValue QProblemB_updateFarBounds( QProblemB* _THIS, - real_t curFarBound, /**< ... */ - int nRamp, /**< ... */ - const real_t* const lb_new, /**< ... */ - real_t* const lb_new_far, /**< ... */ - const real_t* const ub_new, /**< ... */ - real_t* const ub_new_far /**< ... */ - ); - - - -/** Performs robustified ratio test yield the maximum possible step length - * along the homotopy path. - * \return SUCCESSFUL_RETURN */ -returnValue QProblemB_performRatioTestB( QProblemB* _THIS, - int nIdx, /**< Number of ratios to be checked. */ - const int* const idxList, /**< Array containing the indices of all ratios to be checked. */ - Bounds* const subjectTo, /**< Bound object corresponding to ratios to be checked. */ - const real_t* const num, /**< Array containing all numerators for performing the ratio test. */ - const real_t* const den, /**< Array containing all denominators for performing the ratio test. */ - real_t epsNum, /**< Numerator tolerance. */ - real_t epsDen, /**< Denominator tolerance. */ - real_t* t, /**< Output: Maximum possible step length along the homotopy path. */ - int* BC_idx /**< Output: Index of blocking constraint. */ - ); - -/** Checks whether given ratio is blocking, i.e. limits the maximum step length - * along the homotopy path to a value lower than given one. - * \return SUCCESSFUL_RETURN */ -static inline BooleanType QProblemB_isBlocking( QProblemB* _THIS, - real_t num, /**< Numerator for performing the ratio test. */ - real_t den, /**< Denominator for performing the ratio test. */ - real_t epsNum, /**< Numerator tolerance. */ - real_t epsDen, /**< Denominator tolerance. */ - real_t* t /**< Input: Current maximum step length along the homotopy path, - * Output: Updated maximum possible step length along the homotopy path. */ - ); - - -/** Solves a QProblemB whose QP data is assumed to be stored in the member variables. - * A guess for its primal/dual optimal solution vectors and the corresponding - * optimal working set can be provided. - * Note: This function is internally called by all init functions! - * \return SUCCESSFUL_RETURN \n - RET_INIT_FAILED \n - RET_INIT_FAILED_CHOLESKY \n - RET_INIT_FAILED_HOTSTART \n - RET_INIT_FAILED_INFEASIBILITY \n - RET_INIT_FAILED_UNBOUNDEDNESS \n - RET_MAX_NWSR_REACHED */ -returnValue QProblemB_solveInitialQP( QProblemB* _THIS, - const real_t* const xOpt, /**< Optimal primal solution vector.*/ - const real_t* const yOpt, /**< Optimal dual solution vector. */ - Bounds* const guessedBounds, /**< Optimal working set of bounds for solution (xOpt,yOpt). */ - const real_t* const _R, /**< Pre-computed (upper triangular) Cholesky factor of Hessian matrix. */ - int* nWSR, /**< Input: Maximum number of working set recalculations; \n - * Output: Number of performed working set recalculations. */ - real_t* const cputime /**< Input: Maximum CPU time allowed for QP solution. \n - * Output: CPU time spent for QP solution (or to perform nWSR iterations). */ - ); - -/** Solves an initialised QProblemB using online active set strategy. - * Note: This function is internally called by all hotstart functions! - * \return SUCCESSFUL_RETURN \n - RET_MAX_NWSR_REACHED \n - RET_HOTSTART_FAILED_AS_QP_NOT_INITIALISED \n - RET_HOTSTART_FAILED \n - RET_SHIFT_DETERMINATION_FAILED \n - RET_STEPDIRECTION_DETERMINATION_FAILED \n - RET_STEPLENGTH_DETERMINATION_FAILED \n - RET_HOMOTOPY_STEP_FAILED \n - RET_HOTSTART_STOPPED_INFEASIBILITY \n - RET_HOTSTART_STOPPED_UNBOUNDEDNESS */ -returnValue QProblemB_solveQP( QProblemB* _THIS, - const real_t* const g_new, /**< Gradient of neighbouring QP to be solved. */ - const real_t* const lb_new, /**< Lower bounds of neighbouring QP to be solved. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const ub_new, /**< Upper bounds of neighbouring QP to be solved. \n - If no upper bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations; \n - Output: Number of performed working set recalculations. */ - real_t* const cputime, /**< Input: Maximum CPU time allowed for QP solution. \n - Output: CPU time spent for QP solution (or to perform nWSR iterations). */ - int nWSRperformed, /**< Number of working set recalculations already performed to solve - this QP within previous solveQP() calls. This number is - always zero, except for successive calls from solveRegularisedQP() - or when using the far bound strategy. */ - BooleanType isFirstCall /**< Indicating whether this is the first call for current QP. */ - ); - - -/** Solves an initialised QProblemB using online active set strategy. - * Note: This function is internally called by all hotstart functions! - * \return SUCCESSFUL_RETURN \n - RET_MAX_NWSR_REACHED \n - RET_HOTSTART_FAILED_AS_QP_NOT_INITIALISED \n - RET_HOTSTART_FAILED \n - RET_SHIFT_DETERMINATION_FAILED \n - RET_STEPDIRECTION_DETERMINATION_FAILED \n - RET_STEPLENGTH_DETERMINATION_FAILED \n - RET_HOMOTOPY_STEP_FAILED \n - RET_HOTSTART_STOPPED_INFEASIBILITY \n - RET_HOTSTART_STOPPED_UNBOUNDEDNESS */ -returnValue QProblemB_solveRegularisedQP( QProblemB* _THIS, - const real_t* const g_new, /**< Gradient of neighbouring QP to be solved. */ - const real_t* const lb_new, /**< Lower bounds of neighbouring QP to be solved. \n - If no lower bounds exist, a NULL pointer can be passed. */ - const real_t* const ub_new, /**< Upper bounds of neighbouring QP to be solved. \n - If no upper bounds exist, a NULL pointer can be passed. */ - int* nWSR, /**< Input: Maximum number of working set recalculations; \n - Output: Number of performed working set recalculations. */ - real_t* const cputime, /**< Input: Maximum CPU time allowed for QP solution. \n - Output: CPU time spent for QP solution (or to perform nWSR iterations). */ - int nWSRperformed, /**< Number of working set recalculations already performed to solve - this QP within previous solveRegularisedQP() calls. This number is - always zero, except for successive calls when using the far bound strategy. */ - BooleanType isFirstCall /**< Indicating whether this is the first call for current QP. */ - ); - - -/** Sets up bound data structure according to auxiliaryBounds. - * (If the working set shall be setup afresh, make sure that - * bounds data structure has been resetted!) - * \return SUCCESSFUL_RETURN \n - RET_SETUP_WORKINGSET_FAILED \n - RET_INVALID_ARGUMENTS \n - RET_UNKNOWN_BUG */ -returnValue QProblemB_setupAuxiliaryWorkingSet( QProblemB* _THIS, - Bounds* const auxiliaryBounds, /**< Working set for auxiliary QP. */ - BooleanType setupAfresh /**< Flag indicating if given working set shall be - * setup afresh or by updating the current one. */ - ); - -/** Sets up the optimal primal/dual solution of the auxiliary initial QP. - * \return SUCCESSFUL_RETURN */ -returnValue QProblemB_setupAuxiliaryQPsolution( QProblemB* _THIS, - const real_t* const xOpt, /**< Optimal primal solution vector. - * If a NULL pointer is passed, all entries are set to zero. */ - const real_t* const yOpt /**< Optimal dual solution vector. - * If a NULL pointer is passed, all entries are set to zero. */ - ); - -/** Sets up gradient of the auxiliary initial QP for given - * optimal primal/dual solution and given initial working set - * (assumes that members X, Y and BOUNDS have already been (ialised!). - * \return SUCCESSFUL_RETURN */ -returnValue QProblemB_setupAuxiliaryQPgradient( QProblemB* _THIS ); - -/** Sets up bounds of the auxiliary initial QP for given - * optimal primal/dual solution and given initial working set - * (assumes that members X, Y and BOUNDS have already been initialised!). - * \return SUCCESSFUL_RETURN \n - RET_UNKNOWN_BUG */ -returnValue QProblemB_setupAuxiliaryQPbounds( QProblemB* _THIS, - BooleanType useRelaxation /**< Flag indicating if inactive bounds shall be relaxed. */ - ); - - -/** Updates QP vectors, working sets and internal data structures in order to - start from an optimal solution corresponding to initial guesses of the working - set for bounds - * \return SUCCESSFUL_RETURN \n - * RET_SETUP_AUXILIARYQP_FAILED */ -returnValue QProblemB_setupAuxiliaryQP( QProblemB* _THIS, - Bounds* const guessedBounds /**< Initial guess for working set of bounds. */ - ); - -/** Determines step direction of the homotopy path. - * \return SUCCESSFUL_RETURN \n - RET_STEPDIRECTION_FAILED_CHOLESKY */ -returnValue QProblemB_determineStepDirection( QProblemB* _THIS, - const real_t* const delta_g, /**< Step direction of gradient vector. */ - const real_t* const delta_lb, /**< Step direction of lower bounds. */ - const real_t* const delta_ub, /**< Step direction of upper bounds. */ - BooleanType Delta_bB_isZero, /**< Indicates if active bounds are to be shifted. */ - real_t* const delta_xFX, /**< Output: Primal homotopy step direction of fixed variables. */ - real_t* const delta_xFR, /**< Output: Primal homotopy step direction of free variables. */ - real_t* const delta_yFX /**< Output: Dual homotopy step direction of fixed variables' multiplier. */ - ); - -/** Determines the maximum possible step length along the homotopy path - * and performs _THIS step (without changing working set). - * \return SUCCESSFUL_RETURN \n - * RET_QP_INFEASIBLE \n - */ -returnValue QProblemB_performStep( QProblemB* _THIS, - const real_t* const delta_g, /**< Step direction of gradient. */ - const real_t* const delta_lb, /**< Step direction of lower bounds. */ - const real_t* const delta_ub, /**< Step direction of upper bounds. */ - const real_t* const delta_xFX, /**< Primal homotopy step direction of fixed variables. */ - const real_t* const delta_xFR, /**< Primal homotopy step direction of free variables. */ - const real_t* const delta_yFX, /**< Dual homotopy step direction of fixed variables' multiplier. */ - int* BC_idx, /**< Output: Index of blocking constraint. */ - SubjectToStatus* BC_status /**< Output: Status of blocking constraint. */ - ); - -/** Updates active set. - * \return SUCCESSFUL_RETURN \n - RET_REMOVE_FROM_ACTIVESET_FAILED \n - RET_ADD_TO_ACTIVESET_FAILED */ -returnValue QProblemB_changeActiveSet( QProblemB* _THIS, - int BC_idx, /**< Index of blocking constraint. */ - SubjectToStatus BC_status /**< Status of blocking constraint. */ - ); - -/** Drift correction at end of each active set iteration - * \return SUCCESSFUL_RETURN */ -returnValue QProblemB_performDriftCorrection( QProblemB* _THIS ); - -/** Determines if it is more efficient to refactorise the matrices when - * hotstarting or not (i.e. better to update the existing factorisations). - * \return BT_TRUE iff matrices shall be refactorised afresh - */ -BooleanType QProblemB_shallRefactorise( QProblemB* _THIS, - Bounds* const guessedBounds /**< Guessed new working set. */ - ); - - -/** Adds a bound to active set (specialised version for the case where no constraints exist). - * \return SUCCESSFUL_RETURN \n - RET_ADDBOUND_FAILED */ -returnValue QProblemB_addBound( QProblemB* _THIS, - int number, /**< Number of bound to be added to active set. */ - SubjectToStatus B_status, /**< Status of new active bound. */ - BooleanType updateCholesky /**< Flag indicating if Cholesky decomposition shall be updated. */ - ); - -/** Removes a bounds from active set (specialised version for the case where no constraints exist). - * \return SUCCESSFUL_RETURN \n - RET_HESSIAN_NOT_SPD \n - RET_REMOVEBOUND_FAILED */ -returnValue QProblemB_removeBound( QProblemB* _THIS, - int number, /**< Number of bound to be removed from active set. */ - BooleanType updateCholesky /**< Flag indicating if Cholesky decomposition shall be updated. */ - ); - - -/** Prints concise information on the current iteration. - * \return SUCCESSFUL_RETURN \n */ -returnValue QProblemB_printIteration( QProblemB* _THIS, - int iter, /**< Number of current iteration. */ - int BC_idx, /**< Index of blocking bound. */ - SubjectToStatus BC_status, /**< Status of blocking bound. */ - real_t homotopyLength, /**< Current homotopy distance. */ - BooleanType isFirstCall /**< Indicating whether this is the first call for current QP. */ - ); - - - -/* - * g e t B o u n d s - */ -static inline returnValue QProblemB_getBounds( QProblemB* _THIS, Bounds* _bounds ) -{ - int nV = QProblemB_getNV( _THIS ); - - if ( nV == 0 ) - return THROWERROR( RET_QPOBJECT_NOT_SETUP ); - - _bounds = _THIS->bounds; - - return SUCCESSFUL_RETURN; -} - - -/* - * g e t N V - */ -static inline int QProblemB_getNV( QProblemB* _THIS ) -{ - return Bounds_getNV( _THIS->bounds ); -} - - -/* - * g e t N F R - */ -static inline int QProblemB_getNFR( QProblemB* _THIS ) -{ - return Bounds_getNFR( _THIS->bounds ); -} - - -/* - * g e t N F X - */ -static inline int QProblemB_getNFX( QProblemB* _THIS ) -{ - return Bounds_getNFX( _THIS->bounds ); -} - - -/* - * g e t N F V - */ -static inline int QProblemB_getNFV( QProblemB* _THIS ) -{ - return Bounds_getNFV( _THIS->bounds ); -} - - -/* - * g e t S t a t u s - */ -static inline QProblemStatus QProblemB_getStatus( QProblemB* _THIS ) -{ - return _THIS->status; -} - - -/* - * i s I n i t i a l i s e d - */ -static inline BooleanType QProblemB_isInitialised( QProblemB* _THIS ) -{ - if ( _THIS->status == QPS_NOTINITIALISED ) - return BT_FALSE; - else - return BT_TRUE; -} - - -/* - * i s S o l v e d - */ -static inline BooleanType QProblemB_isSolved( QProblemB* _THIS ) -{ - if ( _THIS->status == QPS_SOLVED ) - return BT_TRUE; - else - return BT_FALSE; -} - - -/* - * i s I n f e a s i b l e - */ -static inline BooleanType QProblemB_isInfeasible( QProblemB* _THIS ) -{ - return _THIS->infeasible; -} - - -/* - * i s U n b o u n d e d - */ -static inline BooleanType QProblemB_isUnbounded( QProblemB* _THIS ) -{ - return _THIS->unbounded; -} - - -/* - * g e t H e s s i a n T y p e - */ -static inline HessianType QProblemB_getHessianType( QProblemB* _THIS ) -{ - return _THIS->hessianType; -} - - -/* - * s e t H e s s i a n T y p e - */ -static inline returnValue QProblemB_setHessianType( QProblemB* _THIS, HessianType _hessianType ) -{ - _THIS->hessianType = _hessianType; - return SUCCESSFUL_RETURN; -} - - -/* - * u s i n g R e g u l a r i s a t i o n - */ -static inline BooleanType QProblemB_usingRegularisation( QProblemB* _THIS ) -{ - if ( _THIS->regVal > QPOASES_ZERO ) - return BT_TRUE; - else - return BT_FALSE; -} - - -/* - * g e t O p t i o n s - */ -static inline Options QProblemB_getOptions( QProblemB* _THIS ) -{ - return _THIS->options; -} - - -/* - * s e t O p t i o n s - */ -static inline returnValue QProblemB_setOptions( QProblemB* _THIS, - Options _options - ) -{ - OptionsCPY( &_options,&(_THIS->options) ); - Options_ensureConsistency( &(_THIS->options) ); - - QProblemB_setPrintLevel( _THIS,_THIS->options.printLevel ); - - return SUCCESSFUL_RETURN; -} - - -/* - * g e t P r i n t L e v e l - */ -static inline PrintLevel QProblemB_getPrintLevel( QProblemB* _THIS ) -{ - return _THIS->options.printLevel; -} - - - -/* - * g e t C o u n t - */ -static inline unsigned int QProblemB_getCount( QProblemB* _THIS ) -{ - return _THIS->count; -} - - -/* - * r e s e t C o u n t e r - */ -static inline returnValue QProblemB_resetCounter( QProblemB* _THIS ) -{ - _THIS->count = 0; - return SUCCESSFUL_RETURN; -} - - - -/***************************************************************************** - * P R O T E C T E D * - *****************************************************************************/ - - -/* - * s e t H - */ -static inline returnValue QProblemB_setHM( QProblemB* _THIS, DenseMatrix* H_new ) -{ - if ( H_new == 0 ) - return QProblemB_setH( _THIS,(real_t*)0 ); - else - return QProblemB_setH( _THIS,DenseMatrix_getVal(H_new) ); -} - - -/* - * s e t H - */ -static inline returnValue QProblemB_setH( QProblemB* _THIS, real_t* const H_new ) -{ - /* if null pointer is passed, Hessian is set to zero matrix - * (or stays identity matrix) */ - if ( H_new == 0 ) - { - if ( _THIS->hessianType == HST_IDENTITY ) - return SUCCESSFUL_RETURN; - - _THIS->hessianType = HST_ZERO; - - _THIS->H = 0; - } - else - { - DenseMatrixCON( _THIS->H,QProblemB_getNV( _THIS ),QProblemB_getNV( _THIS ),QProblemB_getNV( _THIS ),H_new ); - } - - return SUCCESSFUL_RETURN; -} - - -/* - * s e t G - */ -static inline returnValue QProblemB_setG( QProblemB* _THIS, const real_t* const g_new ) -{ - unsigned int nV = (unsigned int)QProblemB_getNV( _THIS ); - - if ( nV == 0 ) - return THROWERROR( RET_QPOBJECT_NOT_SETUP ); - - if ( g_new == 0 ) - return THROWERROR( RET_INVALID_ARGUMENTS ); - - memcpy( _THIS->g,g_new,nV*sizeof(real_t) ); - - return SUCCESSFUL_RETURN; -} - - -/* - * s e t L B - */ -static inline returnValue QProblemB_setLB( QProblemB* _THIS, const real_t* const lb_new ) -{ - unsigned int i; - unsigned int nV = (unsigned int)QProblemB_getNV( _THIS ); - - if ( nV == 0 ) - return THROWERROR( RET_QPOBJECT_NOT_SETUP ); - - if ( lb_new != 0 ) - { - memcpy( _THIS->lb,lb_new,nV*sizeof(real_t) ); - } - else - { - /* if no lower bounds are specified, set them to -infinity */ - for( i=0; ilb[i] = -QPOASES_INFTY; - } - - return SUCCESSFUL_RETURN; -} - - -/* - * s e t L B - */ -static inline returnValue QProblemB_setLBn( QProblemB* _THIS, int number, real_t value ) -{ - int nV = QProblemB_getNV( _THIS ); - - if ( nV == 0 ) - return THROWERROR( RET_QPOBJECT_NOT_SETUP ); - - if ( ( number >= 0 ) && ( number < nV ) ) - { - _THIS->lb[number] = value; - return SUCCESSFUL_RETURN; - } - else - { - return THROWERROR( RET_INDEX_OUT_OF_BOUNDS ); - } -} - - -/* - * s e t U B - */ -static inline returnValue QProblemB_setUB( QProblemB* _THIS, const real_t* const ub_new ) -{ - unsigned int i; - unsigned int nV = (unsigned int)QProblemB_getNV( _THIS ); - - if ( nV == 0 ) - return THROWERROR( RET_QPOBJECT_NOT_SETUP ); - - if ( ub_new != 0 ) - { - memcpy( _THIS->ub,ub_new,nV*sizeof(real_t) ); - } - else - { - /* if no upper bounds are specified, set them to infinity */ - for( i=0; iub[i] = QPOASES_INFTY; - } - - return SUCCESSFUL_RETURN; -} - - -/* - * s e t U B - */ -static inline returnValue QProblemB_setUBn( QProblemB* _THIS, int number, real_t value ) -{ - int nV = QProblemB_getNV( _THIS ); - - if ( nV == 0 ) - return THROWERROR( RET_QPOBJECT_NOT_SETUP ); - - if ( ( number >= 0 ) && ( number < nV ) ) - { - _THIS->ub[number] = value; - - return SUCCESSFUL_RETURN; - } - else - { - return THROWERROR( RET_INDEX_OUT_OF_BOUNDS ); - } -} - - -/* - * c o m p u t e G i v e n s - */ -static inline void QProblemB_computeGivens( real_t xold, real_t yold, - real_t* xnew, real_t* ynew, real_t* c, real_t* s - ) -{ - real_t t, mu; - - if ( fabs( yold ) <= QPOASES_ZERO ) - { - *c = 1.0; - *s = 0.0; - - *xnew = xold; - *ynew = yold; - } - else - { - mu = fabs( xold ); - if ( fabs( yold ) > mu ) - mu = fabs( yold ); - - t = mu * sqrt( (xold/mu)*(xold/mu) + (yold/mu)*(yold/mu) ); - - if ( xold < 0.0 ) - t = -t; - - *c = xold/t; - *s = yold/t; - *xnew = t; - *ynew = 0.0; - } - - return; -} - - -/* - * a p p l y G i v e n s - */ -static inline void QProblemB_applyGivens( real_t c, real_t s, real_t nu, real_t xold, real_t yold, - real_t* xnew, real_t* ynew - ) -{ - #ifdef __USE_THREE_MULTS_GIVENS__ - - /* Givens plane rotation requiring only three multiplications, - * cf. Hammarling, S.: A note on modifications to the givens plane rotation. - * J. Inst. Maths Applics, 13:215-218, 1974. */ - *xnew = xold*c + yold*s; - *ynew = (*xnew+xold)*nu - yold; - - #else - - /* Usual Givens plane rotation requiring four multiplications. */ - *xnew = c*xold + s*yold; - *ynew = -s*xold + c*yold; - - #endif - - return; -} - - -/* - * i s B l o c k i n g - */ -static inline BooleanType QProblemB_isBlocking( QProblemB* _THIS, - real_t num, - real_t den, - real_t epsNum, - real_t epsDen, - real_t* t - ) -{ - if ( ( den >= epsDen ) && ( num >= epsNum ) ) - { - if ( num < (*t)*den ) - return BT_TRUE; - } - - return BT_FALSE; -} - - -END_NAMESPACE_QPOASES - - -#endif /* QPOASES_QPROBLEMB_H */ - - -/* - * end of file - */ diff --git a/third_party/acados/include/qpOASES_e/Types.h b/third_party/acados/include/qpOASES_e/Types.h deleted file mode 100644 index fc042aed82..0000000000 --- a/third_party/acados/include/qpOASES_e/Types.h +++ /dev/null @@ -1,310 +0,0 @@ -/* - * This file is part of qpOASES. - * - * qpOASES -- An Implementation of the Online Active Set Strategy. - * Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka, - * Christian Kirches et al. All rights reserved. - * - * qpOASES is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * qpOASES is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with qpOASES; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/** - * \file include/qpOASES_e/Types.h - * \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches - * \version 3.1embedded - * \date 2007-2015 - * - * Declaration of all non-built-in types (except for classes). - */ - - -#ifndef QPOASES_TYPES_H -#define QPOASES_TYPES_H - -#ifdef USE_ACADOS_TYPES -#include "acados/utils/types.h" -#endif - -/* If your compiler does not support the snprintf() function, - * uncomment the following line and try to compile again. */ -/* #define __NO_SNPRINTF__ */ - - -/* Uncomment the following line for setting the __DSPACE__ flag. */ -/* #define __DSPACE__ */ - -/* Uncomment the following line for setting the __XPCTARGET__ flag. */ -/* #define __XPCTARGET__ */ - - -/* Uncomment the following line for setting the __NO_FMATH__ flag. */ -/* #define __NO_FMATH__ */ - -/* Uncomment the following line to enable debug information. */ -/* #define __DEBUG__ */ - -/* Uncomment the following line to enable suppress any kind of console output. */ -/* #define __SUPPRESSANYOUTPUT__ */ - - -/** Forces to always include all implicitly fixed bounds and all equality constraints - * into the initial working set when setting up an auxiliary QP. */ -#define __ALWAYS_INITIALISE_WITH_ALL_EQUALITIES__ - -/* Uncomment the following line to activate the use of an alternative Givens - * plane rotation requiring only three multiplications. */ -/* #define __USE_THREE_MULTS_GIVENS__ */ - -/* Uncomment the following line to activate the use of single precision arithmetic. */ -/* #define __USE_SINGLE_PRECISION__ */ - -/* The inline keyword is skipped by default as it is not part of the C90 standard. - * However, by uncommenting the following line, use of the inline keyword can be enforced. */ -/* #define __USE_INLINE__ */ - - -/* Work-around for Borland BCC 5.5 compiler. */ -#ifdef __BORLANDC__ -#if __BORLANDC__ < 0x0561 - #define __STDC__ 1 -#endif -#endif - - -/* Work-around for Microsoft compilers. */ -#ifdef _MSC_VER - #define __NO_SNPRINTF__ - #pragma warning( disable : 4061 4100 4250 4514 4996 ) -#endif - - -/* Apply pre-processor settings when using qpOASES within auto-generated code. */ -#ifdef __CODE_GENERATION__ - #define __NO_COPYRIGHT__ - #define __EXTERNAL_DIMENSIONS__ -#endif /* __CODE_GENERATION__ */ - - -/* Avoid using static variables declaration within functions. */ -#ifdef __NO_STATIC__ - #define myStatic -#else - #define myStatic static -#endif /* __NO_STATIC__ */ - - -/* Skip inline keyword if not specified otherwise. */ -#ifndef __USE_INLINE__ - #define inline -#endif - - -/* Avoid any printing on embedded platforms. */ -#if defined(__DSPACE__) || defined(__XPCTARGET__) - #define __SUPPRESSANYOUTPUT__ - #define __NO_SNPRINTF__ -#endif - - -#ifdef __NO_SNPRINTF__ - #if (!defined(_MSC_VER)) || defined(__DSPACE__) || defined(__XPCTARGET__) - /* If snprintf is not available, provide an empty implementation... */ - int snprintf( char* s, size_t n, const char* format, ... ); - #else - /* ... or substitute snprintf by _snprintf for Microsoft compilers. */ - #define snprintf _snprintf - #endif -#endif /* __NO_SNPRINTF__ */ - - -/** Macro for switching on/off the beginning of the qpOASES namespace definition. */ -#define BEGIN_NAMESPACE_QPOASES - -/** Macro for switching on/off the end of the qpOASES namespace definition. */ -#define END_NAMESPACE_QPOASES - -/** Macro for switching on/off the use of the qpOASES namespace. */ -#define USING_NAMESPACE_QPOASES - -/** Macro for switching on/off references to the qpOASES namespace. */ -#define REFER_NAMESPACE_QPOASES /*::*/ - - -/** Macro for accessing the Cholesky factor R. */ -#define RR( I,J ) _THIS->R[(I)+nV*(J)] - -/** Macro for accessing the orthonormal matrix Q of the QT factorisation. */ -#define QQ( I,J ) _THIS->Q[(I)+nV*(J)] - -/** Macro for accessing the triangular matrix T of the QT factorisation. */ -#define TT( I,J ) _THIS->T[(I)*nVC_min+(J)] - - - -BEGIN_NAMESPACE_QPOASES - - -/** Defines real_t for facilitating switching between double and float. */ - -#ifndef USE_ACADOS_TYPES -#ifndef __CODE_GENERATION__ - - #ifdef __USE_SINGLE_PRECISION__ - typedef float real_t; - #else - typedef double real_t; - #endif /* __USE_SINGLE_PRECISION__ */ - -#endif /* __CODE_GENERATION__ */ -#endif /* USE_ACADOS_TYPES */ - -/** Summarises all possible logical values. */ -typedef enum -{ - BT_FALSE = 0, /**< Logical value for "false". */ - BT_TRUE /**< Logical value for "true". */ -} BooleanType; - - -/** Summarises all possible print levels. Print levels are used to describe - * the desired amount of output during runtime of qpOASES. */ -typedef enum -{ - PL_DEBUG_ITER = -2, /**< Full tabular debugging output. */ - PL_TABULAR, /**< Tabular output. */ - PL_NONE, /**< No output. */ - PL_LOW, /**< Print error messages only. */ - PL_MEDIUM, /**< Print error and warning messages as well as concise info messages. */ - PL_HIGH /**< Print all messages with full details. */ -} PrintLevel; - - -/** Defines visibility status of a message. */ -typedef enum -{ - VS_HIDDEN, /**< Message not visible. */ - VS_VISIBLE /**< Message visible. */ -} VisibilityStatus; - - -/** Summarises all possible states of the (S)QProblem(B) object during the -solution process of a QP sequence. */ -typedef enum -{ - QPS_NOTINITIALISED, /**< QProblem object is freshly instantiated or reset. */ - QPS_PREPARINGAUXILIARYQP, /**< An auxiliary problem is currently setup, either at the very beginning - * via an initial homotopy or after changing the QP matrices. */ - QPS_AUXILIARYQPSOLVED, /**< An auxilary problem was solved, either at the very beginning - * via an initial homotopy or after changing the QP matrices. */ - QPS_PERFORMINGHOMOTOPY, /**< A homotopy according to the main idea of the online active - * set strategy is performed. */ - QPS_HOMOTOPYQPSOLVED, /**< An intermediate QP along the homotopy path was solved. */ - QPS_SOLVED /**< The solution of the actual QP was found. */ -} QProblemStatus; - - -/** Summarises all possible types of the QP's Hessian matrix. */ -typedef enum -{ - HST_ZERO, /**< Hessian is zero matrix (i.e. LP formulation). */ - HST_IDENTITY, /**< Hessian is identity matrix. */ - HST_POSDEF, /**< Hessian is (strictly) positive definite. */ - HST_POSDEF_NULLSPACE, /**< Hessian is positive definite on null space of active bounds/constraints. */ - HST_SEMIDEF, /**< Hessian is positive semi-definite. */ - HST_INDEF, /**< Hessian is indefinite. */ - HST_UNKNOWN /**< Hessian type is unknown. */ -} HessianType; - - -/** Summarises all possible types of bounds and constraints. */ -typedef enum -{ - ST_UNBOUNDED, /**< Bound/constraint is unbounded. */ - ST_BOUNDED, /**< Bound/constraint is bounded but not fixed. */ - ST_EQUALITY, /**< Bound/constraint is fixed (implicit equality bound/constraint). */ - ST_DISABLED, /**< Bound/constraint is disabled (i.e. ignored when solving QP). */ - ST_UNKNOWN /**< Type of bound/constraint unknown. */ -} SubjectToType; - - -/** Summarises all possible states of bounds and constraints. */ -typedef enum -{ - ST_LOWER = -1, /**< Bound/constraint is at its lower bound. */ - ST_INACTIVE, /**< Bound/constraint is inactive. */ - ST_UPPER, /**< Bound/constraint is at its upper bound. */ - ST_INFEASIBLE_LOWER, /**< (to be documented) */ - ST_INFEASIBLE_UPPER, /**< (to be documented) */ - ST_UNDEFINED /**< Status of bound/constraint undefined. */ -} SubjectToStatus; - - -/** - * \brief Stores internal information for tabular (debugging) output. - * - * Struct storing internal information for tabular (debugging) output - * when using the (S)QProblem(B) objects. - * - * \author Hans Joachim Ferreau - * \version 3.1embedded - * \date 2013-2015 - */ -typedef struct -{ - int idxAddB; /**< Index of bound that has been added to working set. */ - int idxRemB; /**< Index of bound that has been removed from working set. */ - int idxAddC; /**< Index of constraint that has been added to working set. */ - int idxRemC; /**< Index of constraint that has been removed from working set. */ - int excAddB; /**< Flag indicating whether a bound has been added to working set to keep a regular projected Hessian. */ - int excRemB; /**< Flag indicating whether a bound has been removed from working set to keep a regular projected Hessian. */ - int excAddC; /**< Flag indicating whether a constraint has been added to working set to keep a regular projected Hessian. */ - int excRemC; /**< Flag indicating whether a constraint has been removed from working set to keep a regular projected Hessian. */ -} TabularOutput; - -/** - * \brief Struct containing the variable header for mat file. - * - * Struct storing the header of a variable to be stored in - * Matlab's binary format (using the outdated Level 4 variant - * for simplictiy). - * - * Note, this code snippet has been inspired from the document - * "Matlab(R) MAT-file Format, R2013b" by MathWorks - * - * \author Hans Joachim Ferreau - * \version 3.1embedded - * \date 2013-2015 - */ -typedef struct -{ - long numericFormat; /**< Flag indicating numerical format. */ - long nRows; /**< Number of rows. */ - long nCols; /**< Number of rows. */ - long imaginaryPart; /**< (to be documented) */ - long nCharName; /**< Number of character in name. */ -} MatMatrixHeader; - - -END_NAMESPACE_QPOASES - - -#endif /* QPOASES_TYPES_H */ - - -/* - * end of file - */ diff --git a/third_party/acados/include/qpOASES_e/UnitTesting.h b/third_party/acados/include/qpOASES_e/UnitTesting.h deleted file mode 100644 index dbff201039..0000000000 --- a/third_party/acados/include/qpOASES_e/UnitTesting.h +++ /dev/null @@ -1,79 +0,0 @@ -/* - * This file is part of qpOASES. - * - * qpOASES -- An Implementation of the Online Active Set Strategy. - * Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka, - * Christian Kirches et al. All rights reserved. - * - * qpOASES is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * qpOASES is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with qpOASES; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/** - * \file include/qpOASES_e/UnitTesting.h - * \author Hans Joachim Ferreau - * \version 3.1embedded - * \date 2014-2015 - * - * Definition of auxiliary functions/macros for unit testing. - */ - - -#ifndef QPOASES_UNIT_TESTING_H -#define QPOASES_UNIT_TESTING_H - - -#ifndef TEST_TOL_FACTOR -#define TEST_TOL_FACTOR 1 -#endif - - -/** Return value for tests that passed. */ -#define TEST_PASSED 0 - -/** Return value for tests that failed. */ -#define TEST_FAILED 1 - -/** Return value for tests that could not run due to missing external data. */ -#define TEST_DATA_NOT_FOUND 99 - - -/** Macro verifying that two numerical values are equal in order to pass unit test. */ -#define QPOASES_TEST_FOR_EQUAL( x,y ) if ( REFER_NAMESPACE_QPOASES isEqual( (x),(y) ) == BT_FALSE ) { return TEST_FAILED; } - -/** Macro verifying that two numerical values are close to each other in order to pass unit test. */ -#define QPOASES_TEST_FOR_NEAR( x,y ) if ( REFER_NAMESPACE_QPOASES getAbs((x)-(y)) / REFER_NAMESPACE_QPOASES getMax( 1.0,REFER_NAMESPACE_QPOASES getAbs(x) ) >= 1e-10 ) { return TEST_FAILED; } - -/** Macro verifying that first quantity is lower or equal than second one in order to pass unit test. */ -#define QPOASES_TEST_FOR_TOL( x,tol ) if ( (x) > (tol)*(TEST_TOL_FACTOR) ) { return TEST_FAILED; } - -/** Macro verifying that a logical expression holds in order to pass unit test. */ -#define QPOASES_TEST_FOR_TRUE( x ) if ( (x) == 0 ) { return TEST_FAILED; } - - - -BEGIN_NAMESPACE_QPOASES - - -END_NAMESPACE_QPOASES - - -#endif /* QPOASES_UNIT_TESTING_H */ - - -/* - * end of file - */ diff --git a/third_party/acados/include/qpOASES_e/Utils.h b/third_party/acados/include/qpOASES_e/Utils.h deleted file mode 100644 index 75e45a56a0..0000000000 --- a/third_party/acados/include/qpOASES_e/Utils.h +++ /dev/null @@ -1,500 +0,0 @@ -/* - * This file is part of qpOASES. - * - * qpOASES -- An Implementation of the Online Active Set Strategy. - * Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka, - * Christian Kirches et al. All rights reserved. - * - * qpOASES is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * qpOASES is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with qpOASES; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/** - * \file include/qpOASES_e/Utils.h - * \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches - * \version 3.1embedded - * \date 2007-2015 - * - * Declaration of some utilities for working with the different QProblem classes. - */ - - -#ifndef QPOASES_UTILS_H -#define QPOASES_UTILS_H - -#include - - -BEGIN_NAMESPACE_QPOASES - - -/** Prints a vector. - * \return SUCCESSFUL_RETURN */ -returnValue qpOASES_printV( const real_t* const v, /**< Vector to be printed. */ - int n /**< Length of vector. */ - ); - -/** Prints a permuted vector. - * \return SUCCESSFUL_RETURN */ -returnValue qpOASES_printPV( const real_t* const v, /**< Vector to be printed. */ - int n, /**< Length of vector. */ - const int* const V_idx /**< Pemutation vector. */ - ); - -/** Prints a named vector. - * \return SUCCESSFUL_RETURN */ -returnValue qpOASES_printNV( const real_t* const v, /**< Vector to be printed. */ - int n, /**< Length of vector. */ - const char* name /** Name of vector. */ - ); - -/** Prints a matrix. - * \return SUCCESSFUL_RETURN */ -returnValue qpOASES_printM( const real_t* const M, /**< Matrix to be printed. */ - int nrow, /**< Row number of matrix. */ - int ncol /**< Column number of matrix. */ - ); - -/** Prints a permuted matrix. - * \return SUCCESSFUL_RETURN */ -returnValue qpOASES_printPM( const real_t* const M, /**< Matrix to be printed. */ - int nrow, /**< Row number of matrix. */ - int ncol , /**< Column number of matrix. */ - const int* const ROW_idx, /**< Row pemutation vector. */ - const int* const COL_idx /**< Column pemutation vector. */ - ); - -/** Prints a named matrix. - * \return SUCCESSFUL_RETURN */ -returnValue qpOASES_printNM( const real_t* const M, /**< Matrix to be printed. */ - int nrow, /**< Row number of matrix. */ - int ncol, /**< Column number of matrix. */ - const char* name /** Name of matrix. */ - ); - -/** Prints an index array. - * \return SUCCESSFUL_RETURN */ -returnValue qpOASES_printI( const int* const _index, /**< Index array to be printed. */ - int n /**< Length of index array. */ - ); - -/** Prints a named index array. - * \return SUCCESSFUL_RETURN */ -returnValue qpOASES_printNI( const int* const _index, /**< Index array to be printed. */ - int n, /**< Length of index array. */ - const char* name /**< Name of index array. */ - ); - - -/** Prints a string to desired output target (useful also for MATLAB output!). - * \return SUCCESSFUL_RETURN */ -returnValue qpOASES_myPrintf( const char* s /**< String to be written. */ - ); - - -/** Prints qpOASES copyright notice. - * \return SUCCESSFUL_RETURN */ -returnValue qpOASES_printCopyrightNotice( ); - - -/** Reads a real_t matrix from file. - * \return SUCCESSFUL_RETURN \n - RET_UNABLE_TO_OPEN_FILE \n - RET_UNABLE_TO_READ_FILE */ -returnValue qpOASES_readFromFileM( real_t* data, /**< Matrix to be read from file. */ - int nrow, /**< Row number of matrix. */ - int ncol, /**< Column number of matrix. */ - const char* datafilename /**< Data file name. */ - ); - -/** Reads a real_t vector from file. - * \return SUCCESSFUL_RETURN \n - RET_UNABLE_TO_OPEN_FILE \n - RET_UNABLE_TO_READ_FILE */ -returnValue qpOASES_readFromFileV( real_t* data, /**< Vector to be read from file. */ - int n, /**< Length of vector. */ - const char* datafilename /**< Data file name. */ - ); - -/** Reads an integer (column) vector from file. - * \return SUCCESSFUL_RETURN \n - RET_UNABLE_TO_OPEN_FILE \n - RET_UNABLE_TO_READ_FILE */ -returnValue qpOASES_readFromFileI( int* data, /**< Vector to be read from file. */ - int n, /**< Length of vector. */ - const char* datafilename /**< Data file name. */ - ); - - -/** Writes a real_t matrix into a file. - * \return SUCCESSFUL_RETURN \n - RET_UNABLE_TO_OPEN_FILE */ -returnValue qpOASES_writeIntoFileM( const real_t* const data, /**< Matrix to be written into file. */ - int nrow, /**< Row number of matrix. */ - int ncol, /**< Column number of matrix. */ - const char* datafilename, /**< Data file name. */ - BooleanType append /**< Indicates if data shall be appended if the file already exists (otherwise it is overwritten). */ - ); - -/** Writes a real_t vector into a file. - * \return SUCCESSFUL_RETURN \n - RET_UNABLE_TO_OPEN_FILE */ -returnValue qpOASES_writeIntoFileV( const real_t* const data, /**< Vector to be written into file. */ - int n, /**< Length of vector. */ - const char* datafilename, /**< Data file name. */ - BooleanType append /**< Indicates if data shall be appended if the file already exists (otherwise it is overwritten). */ - ); - -/** Writes an integer (column) vector into a file. - * \return SUCCESSFUL_RETURN \n - RET_UNABLE_TO_OPEN_FILE */ -returnValue qpOASES_writeIntoFileI( const int* const integer, /**< Integer vector to be written into file. */ - int n, /**< Length of vector. */ - const char* datafilename, /**< Data file name. */ - BooleanType append /**< Indicates if integer shall be appended if the file already exists (otherwise it is overwritten). */ - ); - -/** Writes a real_t matrix/vector into a Matlab binary file. - * \return SUCCESSFUL_RETURN \n - RET_INVALID_ARGUMENTS - RET_UNABLE_TO_WRITE_FILE */ -returnValue qpOASES_writeIntoMatFile( FILE* const matFile, /**< Pointer to Matlab binary file. */ - const real_t* const data, /**< Data to be written into file. */ - int nRows, /**< Row number of matrix. */ - int nCols, /**< Column number of matrix. */ - const char* name /**< Matlab name of matrix/vector to be stored. */ - ); - -/** Writes in integer matrix/vector into a Matlab binary file. - * \return SUCCESSFUL_RETURN \n - RET_INVALID_ARGUMENTS - RET_UNABLE_TO_WRITE_FILE */ -returnValue qpOASES_writeIntoMatFileI( FILE* const matFile, /**< Pointer to Matlab binary file. */ - const int* const data, /**< Data to be written into file. */ - int nRows, /**< Row number of matrix. */ - int nCols, /**< Column number of matrix. */ - const char* name /**< Matlab name of matrix/vector to be stored. */ - ); - - -/** Returns the current system time. - * \return current system time */ -real_t qpOASES_getCPUtime( ); - - -/** Returns the N-norm of a vector. - * \return >= 0.0: successful */ -real_t qpOASES_getNorm( const real_t* const v, /**< Vector. */ - int n, /**< Vector's dimension. */ - int type /**< Norm type, 1: one-norm, 2: Euclidean norm. */ - ); - -/** Tests whether two real-valued arguments are (numerically) equal. - * \return BT_TRUE: arguments differ not more than TOL \n - BT_FALSE: arguments differ more than TOL */ -static inline BooleanType qpOASES_isEqual( real_t x, /**< First real number. */ - real_t y, /**< Second real number. */ - real_t TOL /**< Tolerance for comparison. */ - ); - - -/** Tests whether a real-valued argument is (numerically) zero. - * \return BT_TRUE: argument differs from 0.0 not more than TOL \n - BT_FALSE: argument differs from 0.0 more than TOL */ -static inline BooleanType qpOASES_isZero( real_t x, /**< Real number. */ - real_t TOL /**< Tolerance for comparison. */ - ); - - -/** Returns sign of a real-valued argument. - * \return 1.0: argument is non-negative \n - -1.0: argument is negative */ -static inline real_t qpOASES_getSign( real_t arg /**< real-valued argument whose sign is to be determined. */ - ); - - -/** Returns maximum of two integers. - * \return Maximum of two integers */ -static inline int qpOASES_getMaxI( int x, /**< First integer. */ - int y /**< Second integer. */ - ); - - -/** Returns minimum of two integers. - * \return Minimum of two integers */ -static inline int qpOASES_getMinI( int x, /**< First integer. */ - int y /**< Second integer. */ - ); - - -/** Returns maximum of two reals. - * \return Maximum of two reals */ -static inline real_t qpOASES_getMax( real_t x, /**< First real number. */ - real_t y /**< Second real number. */ - ); - - -/** Returns minimum of two reals. - * \return Minimum of two reals */ -static inline real_t qpOASES_getMin( real_t x, /**< First real number. */ - real_t y /**< Second real number. */ - ); - - -/** Returns the absolute value of a real_t-valued argument. - * \return Absolute value of a real_t-valued argument */ -static inline real_t qpOASES_getAbs( real_t x /**< real_t-valued argument. */ - ); - -/** Returns the square-root of a real number. - * \return Square-root of a real number */ -static inline real_t qpOASES_getSqrt( real_t x /**< Non-negative real number. */ - ); - - -/** Computes the maximum violation of the KKT optimality conditions - * of given iterate for given QP data. */ -returnValue qpOASES_getKktViolation( int nV, /**< Number of variables. */ - int nC, /**< Number of constraints. */ - const real_t* const H, /**< Hessian matrix (may be NULL if Hessian is zero or identity matrix). */ - const real_t* const g, /**< Gradient vector. */ - const real_t* const A, /**< Constraint matrix. */ - const real_t* const lb, /**< Lower bound vector (on variables). */ - const real_t* const ub, /**< Upper bound vector (on variables). */ - const real_t* const lbA, /**< Lower constraints' bound vector. */ - const real_t* const ubA, /**< Upper constraints' bound vector. */ - const real_t* const x, /**< Primal trial vector. */ - const real_t* const y, /**< Dual trial vector. */ - real_t* const _stat, /**< Output: maximum value of stationarity condition residual. */ - real_t* const feas, /**< Output: maximum value of primal feasibility violation. */ - real_t* const cmpl /**< Output: maximum value of complementarity residual. */ - ); - -/** Computes the maximum violation of the KKT optimality conditions - * of given iterate for given QP data. */ -returnValue qpOASES_getKktViolationSB( int nV, /**< Number of variables. */ - const real_t* const H, /**< Hessian matrix (may be NULL if Hessian is zero or identity matrix). */ - const real_t* const g, /**< Gradient vector. */ - const real_t* const lb, /**< Lower bound vector (on variables). */ - const real_t* const ub, /**< Upper bound vector (on variables). */ - const real_t* const x, /**< Primal trial vector. */ - const real_t* const y, /**< Dual trial vector. */ - real_t* const _stat, /**< Output: maximum value of stationarity condition residual. */ - real_t* const feas, /**< Output: maximum value of primal feasibility violation. */ - real_t* const cmpl /**< Output: maximum value of complementarity residual. */ - ); - - -/** Writes a value of BooleanType into a string. - * \return SUCCESSFUL_RETURN */ -returnValue qpOASES_convertBooleanTypeToString( BooleanType value, /**< Value to be written. */ - char* const string /**< Input: String of sufficient size, \n - Output: String containing value. */ - ); - -/** Writes a value of SubjectToStatus into a string. - * \return SUCCESSFUL_RETURN */ -returnValue qpOASES_convertSubjectToStatusToString( SubjectToStatus value, /**< Value to be written. */ - char* const string /**< Input: String of sufficient size, \n - Output: String containing value. */ - ); - -/** Writes a value of PrintLevel into a string. - * \return SUCCESSFUL_RETURN */ -returnValue qpOASES_convertPrintLevelToString( PrintLevel value, /**< Value to be written. */ - char* const string /**< Input: String of sufficient size, \n - Output: String containing value. */ - ); - - -/** Converts a returnValue from an QProblem(B) object into a more - * simple status flag. - * - * \return 0: QP problem solved - * 1: QP could not be solved within given number of iterations - * -1: QP could not be solved due to an internal error - * -2: QP is infeasible (and thus could not be solved) - * -3: QP is unbounded (and thus could not be solved) - */ -int qpOASES_getSimpleStatus( returnValue returnvalue, /**< ReturnValue to be analysed. */ - BooleanType doPrintStatus /**< Flag indicating whether simple status shall be printed to screen. */ - ); - -/** Normalises QP constraints. - * \return SUCCESSFUL_RETURN \n - * RET_INVALID_ARGUMENTS */ -returnValue qpOASES_normaliseConstraints( int nV, /**< Number of variables. */ - int nC, /**< Number of constraints. */ - real_t* A, /**< Input: Constraint matrix, \n - Output: Normalised constraint matrix. */ - real_t* lbA, /**< Input: Constraints' lower bound vector, \n - Output: Normalised constraints' lower bound vector. */ - real_t* ubA, /**< Input: Constraints' upper bound vector, \n - Output: Normalised constraints' upper bound vector. */ - int type /**< Norm type, 1: one-norm, 2: Euclidean norm. */ - ); - - -#ifdef __DEBUG__ -/** Writes matrix with given dimension into specified file. */ -void gdb_printmat( const char *fname, /**< File name. */ - real_t *M, /**< Matrix to be written. */ - int n, /**< Number of rows. */ - int m, /**< Number of columns. */ - int ldim /**< Leading dimension. */ - ); -#endif /* __DEBUG__ */ - - -#if defined(__DSPACE__) || defined(__XPCTARGET__) -void __cxa_pure_virtual( void ); -#endif /* __DSPACE__ || __XPCTARGET__*/ - - - -/* - * i s E q u a l - */ -static inline BooleanType qpOASES_isEqual( real_t x, - real_t y, - real_t TOL - ) -{ - if ( qpOASES_getAbs(x-y) <= TOL ) - return BT_TRUE; - else - return BT_FALSE; -} - - -/* - * i s Z e r o - */ -static inline BooleanType qpOASES_isZero( real_t x, - real_t TOL - ) -{ - if ( qpOASES_getAbs(x) <= TOL ) - return BT_TRUE; - else - return BT_FALSE; -} - - -/* - * g e t S i g n - */ -static inline real_t qpOASES_getSign( real_t arg - ) -{ - if ( arg >= 0.0 ) - return 1.0; - else - return -1.0; -} - - - -/* - * g e t M a x - */ -static inline int qpOASES_getMaxI( int x, - int y - ) -{ - return (yx) ? x : y; -} - - -/* - * g e t M a x - */ -static inline real_t qpOASES_getMax( real_t x, - real_t y - ) -{ - #ifdef __NO_FMATH__ - return (yx) ? x : y; - #else - return (y>x) ? x : y; - /*return fmin(x,y); seems to be slower */ - #endif -} - - -/* - * g e t A b s - */ -static inline real_t qpOASES_getAbs( real_t x - ) -{ - #ifdef __NO_FMATH__ - return (x>=0.0) ? x : -x; - #else - return fabs(x); - #endif -} - -/* - * g e t S q r t - */ -static inline real_t qpOASES_getSqrt( real_t x - ) -{ - #ifdef __NO_FMATH__ - return sqrt(x); /* put your custom sqrt-replacement here */ - #else - return sqrt(x); - #endif -} - - -END_NAMESPACE_QPOASES - - -#endif /* QPOASES_UTILS_H */ - - -/* - * end of file - */ diff --git a/third_party/acados/include/qpOASES_e/extras/OQPinterface.h b/third_party/acados/include/qpOASES_e/extras/OQPinterface.h deleted file mode 100644 index da59ea9db6..0000000000 --- a/third_party/acados/include/qpOASES_e/extras/OQPinterface.h +++ /dev/null @@ -1,227 +0,0 @@ -/* - * This file is part of qpOASES. - * - * qpOASES -- An Implementation of the Online Active Set Strategy. - * Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka, - * Christian Kirches et al. All rights reserved. - * - * qpOASES is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * qpOASES is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with qpOASES; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/** - * \file include/qpOASES_e/extras/OQPinterface.h - * \author Hans Joachim Ferreau, Andreas Potschka, Christian Kirches - * \version 3.1embedded - * \date 2007-2015 - * - * Declaration of an interface comprising several utility functions - * for solving test problems from the Online QP Benchmark Collection - * (This collection is no longer maintained, see - * http://www.qpOASES.org/onlineQP for a backup). - */ - - -#ifndef QPOASES_OQPINTERFACE_H -#define QPOASES_OQPINTERFACE_H - - -#include -#include - -#include -#include - - -BEGIN_NAMESPACE_QPOASES - -typedef struct { - QProblem *qp; - - DenseMatrix *H; - DenseMatrix *A; - - real_t *x; - real_t *y; -} OQPbenchmark_ws; - -int OQPbenchmark_ws_calculateMemorySize( unsigned int nV, unsigned int nC ); - -char *OQPbenchmark_ws_assignMemory( unsigned int nV, unsigned int nC, OQPbenchmark_ws **mem, void *raw_memory ); - -OQPbenchmark_ws *OQPbenchmark_ws_createMemory( unsigned int nV, unsigned int nC ); - -typedef struct { - QProblemB *qp; - - DenseMatrix *H; - - real_t *x; - real_t *y; -} OQPbenchmarkB_ws; - -int OQPbenchmarkB_ws_calculateMemorySize( unsigned int nV ); - -char *OQPbenchmarkB_ws_assignMemory( unsigned int nV, OQPbenchmarkB_ws **mem, void *raw_memory ); - -OQPbenchmarkB_ws *OQPbenchmarkB_ws_createMemory( unsigned int nV ); - -typedef struct { - OQPbenchmark_ws *qp_ws; - OQPbenchmarkB_ws *qpB_ws; - - real_t *H; - real_t *g; - real_t *A; - real_t *lb; - real_t *ub; - real_t *lbA; - real_t *ubA; -} OQPinterface_ws; - -int OQPinterface_ws_calculateMemorySize( unsigned int nV, unsigned int nC, unsigned int nQP ); - -char *OQPinterface_ws_assignMemory( unsigned int nV, unsigned int nC, unsigned int nQP, OQPinterface_ws **mem, void *raw_memory ); - -OQPinterface_ws *OQPinterface_ws_createMemory( unsigned int nV, unsigned int nC, unsigned int nQP ); - -/** Reads dimensions of an Online QP Benchmark problem from file. - * \return SUCCESSFUL_RETURN \n - RET_UNABLE_TO_READ_FILE \n - RET_FILEDATA_INCONSISTENT */ -returnValue readOQPdimensions( const char* path, /**< Full path of the data files (without trailing slash!). */ - int* nQP, /**< Output: Number of QPs. */ - int* nV, /**< Output: Number of variables. */ - int* nC, /**< Output: Number of constraints. */ - int* nEC /**< Output: Number of equality constraints. */ - ); - -/** Reads data of an Online QP Benchmark problem from file. - * This function allocates the required memory for all data; after successfully calling it, - * you have to free this memory yourself! - * \return SUCCESSFUL_RETURN \n - RET_INVALID_ARGUMENTS \n - RET_UNABLE_TO_READ_FILE \n - RET_FILEDATA_INCONSISTENT */ -returnValue readOQPdata( const char* path, /**< Full path of the data files (without trailing slash!). */ - int* nQP, /**< Output: Number of QPs. */ - int* nV, /**< Output: Number of variables. */ - int* nC, /**< Output: Number of constraints. */ - int* nEC, /**< Output: Number of equality constraints. */ - real_t* H, /**< Output: Hessian matrix. */ - real_t* g, /**< Output: Sequence of gradient vectors. */ - real_t* A, /**< Output: Constraint matrix. */ - real_t* lb, /**< Output: Sequence of lower bound vectors (on variables). */ - real_t* ub, /**< Output: Sequence of upper bound vectors (on variables). */ - real_t* lbA, /**< Output: Sequence of lower constraints' bound vectors. */ - real_t* ubA, /**< Output: Sequence of upper constraints' bound vectors. */ - real_t* xOpt, /**< Output: Sequence of primal solution vectors - * (not read if a null pointer is passed). */ - real_t* yOpt, /**< Output: Sequence of dual solution vectors - * (not read if a null pointer is passed). */ - real_t* objOpt /**< Output: Sequence of optimal objective function values - * (not read if a null pointer is passed). */ - ); - - -/** Solves an Online QP Benchmark problem as specified by the arguments. - * The maximum deviations from the given optimal solution as well as the - * maximum CPU time to solve each QP are determined. - * \return SUCCESSFUL_RETURN \n - RET_BENCHMARK_ABORTED */ -returnValue solveOQPbenchmark( int nQP, /**< Number of QPs. */ - int nV, /**< Number of variables. */ - int nC, /**< Number of constraints. */ - int nEC, /**< Number of equality constraints. */ - real_t* _H, /**< Hessian matrix. */ - const real_t* const g, /**< Sequence of gradient vectors. */ - real_t* _A, /**< Constraint matrix. */ - const real_t* const lb, /**< Sequence of lower bound vectors (on variables). */ - const real_t* const ub, /**< Sequence of upper bound vectors (on variables). */ - const real_t* const lbA, /**< Sequence of lower constraints' bound vectors. */ - const real_t* const ubA, /**< Sequence of upper constraints' bound vectors. */ - BooleanType isSparse, /**< Shall convert matrices to sparse format before solution? */ - BooleanType useHotstarts, /**< Shall QP solution be hotstarted? */ - const Options* options, /**< QP solver options to be used while solving benchmark problems. */ - int maxAllowedNWSR, /**< Maximum number of working set recalculations to be performed. */ - real_t* maxNWSR, /**< Output: Maximum number of performed working set recalculations. */ - real_t* avgNWSR, /**< Output: Average number of performed working set recalculations. */ - real_t* maxCPUtime, /**< Output: Maximum CPU time required for solving each QP. */ - real_t* avgCPUtime, /**< Output: Average CPU time required for solving each QP. */ - real_t* maxStationarity, /**< Output: Maximum residual of stationarity condition. */ - real_t* maxFeasibility, /**< Output: Maximum residual of primal feasibility condition. */ - real_t* maxComplementarity, /**< Output: Maximum residual of complementarity condition. */ - OQPbenchmark_ws *work /**< Workspace. */ - ); - -/** Solves an Online QP Benchmark problem (without constraints) as specified - * by the arguments. The maximum deviations from the given optimal solution - * as well as the maximum CPU time to solve each QP are determined. - * \return SUCCESSFUL_RETURN \n - RET_BENCHMARK_ABORTED */ -returnValue solveOQPbenchmarkB( int nQP, /**< Number of QPs. */ - int nV, /**< Number of variables. */ - real_t* _H, /**< Hessian matrix. */ - const real_t* const g, /**< Sequence of gradient vectors. */ - const real_t* const lb, /**< Sequence of lower bound vectors (on variables). */ - const real_t* const ub, /**< Sequence of upper bound vectors (on variables). */ - BooleanType isSparse, /**< Shall convert matrices to sparse format before solution? */ - BooleanType useHotstarts, /**< Shall QP solution be hotstarted? */ - const Options* options, /**< QP solver options to be used while solving benchmark problems. */ - int maxAllowedNWSR, /**< Maximum number of working set recalculations to be performed. */ - real_t* maxNWSR, /**< Output: Maximum number of performed working set recalculations. */ - real_t* avgNWSR, /**< Output: Average number of performed working set recalculations. */ - real_t* maxCPUtime, /**< Output: Maximum CPU time required for solving each QP. */ - real_t* avgCPUtime, /**< Output: Average CPU time required for solving each QP. */ - real_t* maxStationarity, /**< Output: Maximum residual of stationarity condition. */ - real_t* maxFeasibility, /**< Output: Maximum residual of primal feasibility condition. */ - real_t* maxComplementarity, /**< Output: Maximum residual of complementarity condition. */ - OQPbenchmarkB_ws *work /**< Workspace. */ - ); - - -/** Runs an Online QP Benchmark problem and determines the maximum - * violation of the KKT optimality conditions as well as the - * maximum and average number of iterations and CPU time to solve - * each QP. - * - * \return SUCCESSFUL_RETURN \n - RET_UNABLE_TO_READ_BENCHMARK \n - RET_BENCHMARK_ABORTED */ -returnValue runOQPbenchmark( const char* path, /**< Full path of the benchmark files (without trailing slash!). */ - BooleanType isSparse, /**< Shall convert matrices to sparse format before solution? */ - BooleanType useHotstarts, /**< Shall QP solution be hotstarted? */ - const Options* options, /**< QP solver options to be used while solving benchmark problems. */ - int maxAllowedNWSR, /**< Maximum number of working set recalculations to be performed. */ - real_t* maxNWSR, /**< Output: Maximum number of performed working set recalculations. */ - real_t* avgNWSR, /**< Output: Average number of performed working set recalculations. */ - real_t* maxCPUtime, /**< Output: Maximum CPU time required for solving each QP. */ - real_t* avgCPUtime, /**< Output: Average CPU time required for solving each QP. */ - real_t* maxStationarity, /**< Output: Maximum residual of stationarity condition. */ - real_t* maxFeasibility, /**< Output: Maximum residual of primal feasibility condition. */ - real_t* maxComplementarity, /**< Output: Maximum residual of complementarity condition. */ - OQPinterface_ws* work /**< Workspace. */ - ); - -END_NAMESPACE_QPOASES - - -#endif /* QPOASES_OQPINTERFACE_H */ - - -/* - * end of file - */ diff --git a/third_party/acados/larch64/lib/libacados.so b/third_party/acados/larch64/lib/libacados.so deleted file mode 100644 index a081e31ab1..0000000000 --- a/third_party/acados/larch64/lib/libacados.so +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:091ed10ea2b52866b826ef6867b3413d6fd61af66fcedf3d932c9adf3fb329de -size 512912 diff --git a/third_party/acados/larch64/lib/libblasfeo.so b/third_party/acados/larch64/lib/libblasfeo.so deleted file mode 100644 index e2191897a1..0000000000 --- a/third_party/acados/larch64/lib/libblasfeo.so +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:d40b25de85318c8349c9894a3cbeaa713efae4158d8cc2c5c77af9f1bfbbb28e -size 1150320 diff --git a/third_party/acados/larch64/lib/libhpipm.so b/third_party/acados/larch64/lib/libhpipm.so deleted file mode 100644 index 002eda375a..0000000000 --- a/third_party/acados/larch64/lib/libhpipm.so +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:91b9276e74c7d7750288d76087d586ed27932939bc7bca2ad1494b6558fc43e3 -size 1367352 diff --git a/third_party/acados/larch64/lib/libqpOASES_e.so b/third_party/acados/larch64/lib/libqpOASES_e.so deleted file mode 120000 index 14048625a1..0000000000 --- a/third_party/acados/larch64/lib/libqpOASES_e.so +++ /dev/null @@ -1 +0,0 @@ -libqpOASES_e.so.3.1 \ No newline at end of file diff --git a/third_party/acados/larch64/lib/libqpOASES_e.so.3.1 b/third_party/acados/larch64/lib/libqpOASES_e.so.3.1 deleted file mode 100644 index d64e40ec60..0000000000 --- a/third_party/acados/larch64/lib/libqpOASES_e.so.3.1 +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:c0a84042e5315af18e6e33b9b9c5e96573248e41ff165657eb9d83da4da2889f -size 223152 diff --git a/third_party/acados/larch64/t_renderer b/third_party/acados/larch64/t_renderer deleted file mode 100755 index f9e7d16601..0000000000 --- a/third_party/acados/larch64/t_renderer +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4660fe00e03e29d90459ac2fd46a6e10982577d0ba558b9f05e5712df66814b4 -size 17915048 diff --git a/third_party/acados/x86_64/lib/libacados.so b/third_party/acados/x86_64/lib/libacados.so deleted file mode 100644 index 4e80f7c76b..0000000000 --- a/third_party/acados/x86_64/lib/libacados.so +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:821ce18f417d211c4845b60482d465b809f90dc7d04f023d652d8221e87679b1 -size 553544 diff --git a/third_party/acados/x86_64/lib/libblasfeo.so b/third_party/acados/x86_64/lib/libblasfeo.so deleted file mode 100644 index 26d5a3dbe9..0000000000 --- a/third_party/acados/x86_64/lib/libblasfeo.so +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:3feea7927d004064bbc5a13c3287467669ce801cb0a3c616cf9e089816da5a0b -size 2155088 diff --git a/third_party/acados/x86_64/lib/libhpipm.so b/third_party/acados/x86_64/lib/libhpipm.so deleted file mode 100644 index 40e2e4e7d4..0000000000 --- a/third_party/acados/x86_64/lib/libhpipm.so +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:a042716f515913786581dff39799eb71fc66caddfa18b1c9f0d54f00c1568fd2 -size 1572648 diff --git a/third_party/acados/x86_64/lib/libqpOASES_e.so b/third_party/acados/x86_64/lib/libqpOASES_e.so deleted file mode 120000 index 14048625a1..0000000000 --- a/third_party/acados/x86_64/lib/libqpOASES_e.so +++ /dev/null @@ -1 +0,0 @@ -libqpOASES_e.so.3.1 \ No newline at end of file diff --git a/third_party/acados/x86_64/lib/libqpOASES_e.so.3.1 b/third_party/acados/x86_64/lib/libqpOASES_e.so.3.1 deleted file mode 100644 index cf5e550faa..0000000000 --- a/third_party/acados/x86_64/lib/libqpOASES_e.so.3.1 +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:a6abea4815e3f03cff06fe8a9602e97f9acf102f18f803571460a94595b93be4 -size 262824 diff --git a/third_party/acados/x86_64/t_renderer b/third_party/acados/x86_64/t_renderer deleted file mode 100755 index e995a209b7..0000000000 --- a/third_party/acados/x86_64/t_renderer +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:7a360d4b53826b91ada3358156d44a14d497bdd8ace88707fd4b386ed6d194c7 -size 17503920 diff --git a/third_party/bootstrap/.gitignore b/third_party/bootstrap/.gitignore deleted file mode 100644 index ac06c0cf85..0000000000 --- a/third_party/bootstrap/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/icons/ diff --git a/third_party/bootstrap/bootstrap-icons.svg b/third_party/bootstrap/bootstrap-icons.svg deleted file mode 100644 index 692a27ea55..0000000000 --- a/third_party/bootstrap/bootstrap-icons.svg +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:d7ecfaac355e51c9b95319fdf4681cf4c423109fd477e961af588b92607a76da -size 1087239 diff --git a/third_party/bootstrap/pull.sh b/third_party/bootstrap/pull.sh deleted file mode 100755 index 0b03b4db9e..0000000000 --- a/third_party/bootstrap/pull.sh +++ /dev/null @@ -1,14 +0,0 @@ -#!/bin/bash -set -e - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )" -cd $DIR - -if [ ! -d icons/ ]; then - git clone https://github.com/twbs/icons/ -fi - -cd icons -git fetch --all -git checkout d5aa187483a1b0b186f87adcfa8576350d970d98 -cp bootstrap-icons.svg ../ diff --git a/third_party/catch2/include/catch2/catch.hpp b/third_party/catch2/include/catch2/catch.hpp deleted file mode 100644 index 6a31e5b0ca..0000000000 --- a/third_party/catch2/include/catch2/catch.hpp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:27da57c7a06d09be8dd81fab7246b79e7892b6ae7e4e49ba8631f1d5a955e3fc -size 657276 diff --git a/third_party/catch2/include/catch2/catch_reporter_automake.hpp b/third_party/catch2/include/catch2/catch_reporter_automake.hpp deleted file mode 100644 index dbebe97516..0000000000 --- a/third_party/catch2/include/catch2/catch_reporter_automake.hpp +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Created by Justin R. Wilson on 2/19/2017. - * Copyright 2017 Justin R. Wilson. All rights reserved. - * - * Distributed under the Boost Software License, Version 1.0. (See accompanying - * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - */ -#ifndef TWOBLUECUBES_CATCH_REPORTER_AUTOMAKE_HPP_INCLUDED -#define TWOBLUECUBES_CATCH_REPORTER_AUTOMAKE_HPP_INCLUDED - -// Don't #include any Catch headers here - we can assume they are already -// included before this header. -// This is not good practice in general but is necessary in this case so this -// file can be distributed as a single header that works with the main -// Catch single header. - -namespace Catch { - - struct AutomakeReporter : StreamingReporterBase { - AutomakeReporter( ReporterConfig const& _config ) - : StreamingReporterBase( _config ) - {} - - ~AutomakeReporter() override; - - static std::string getDescription() { - return "Reports test results in the format of Automake .trs files"; - } - - void assertionStarting( AssertionInfo const& ) override {} - - bool assertionEnded( AssertionStats const& /*_assertionStats*/ ) override { return true; } - - void testCaseEnded( TestCaseStats const& _testCaseStats ) override { - // Possible values to emit are PASS, XFAIL, SKIP, FAIL, XPASS and ERROR. - stream << ":test-result: "; - if (_testCaseStats.totals.assertions.allPassed()) { - stream << "PASS"; - } else if (_testCaseStats.totals.assertions.allOk()) { - stream << "XFAIL"; - } else { - stream << "FAIL"; - } - stream << ' ' << _testCaseStats.testInfo.name << '\n'; - StreamingReporterBase::testCaseEnded( _testCaseStats ); - } - - void skipTest( TestCaseInfo const& testInfo ) override { - stream << ":test-result: SKIP " << testInfo.name << '\n'; - } - - }; - -#ifdef CATCH_IMPL - AutomakeReporter::~AutomakeReporter() {} -#endif - - CATCH_REGISTER_REPORTER( "automake", AutomakeReporter) - -} // end namespace Catch - -#endif // TWOBLUECUBES_CATCH_REPORTER_AUTOMAKE_HPP_INCLUDED diff --git a/third_party/catch2/include/catch2/catch_reporter_sonarqube.hpp b/third_party/catch2/include/catch2/catch_reporter_sonarqube.hpp deleted file mode 100644 index bf7d9299a5..0000000000 --- a/third_party/catch2/include/catch2/catch_reporter_sonarqube.hpp +++ /dev/null @@ -1,181 +0,0 @@ -/* - * Created by Daniel Garcia on 2018-12-04. - * Copyright Social Point SL. All rights reserved. - * - * Distributed under the Boost Software License, Version 1.0. (See accompanying - * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - */ -#ifndef CATCH_REPORTER_SONARQUBE_HPP_INCLUDED -#define CATCH_REPORTER_SONARQUBE_HPP_INCLUDED - - -// Don't #include any Catch headers here - we can assume they are already -// included before this header. -// This is not good practice in general but is necessary in this case so this -// file can be distributed as a single header that works with the main -// Catch single header. - -#include - -namespace Catch { - - struct SonarQubeReporter : CumulativeReporterBase { - - SonarQubeReporter(ReporterConfig const& config) - : CumulativeReporterBase(config) - , xml(config.stream()) { - m_reporterPrefs.shouldRedirectStdOut = true; - m_reporterPrefs.shouldReportAllAssertions = true; - } - - ~SonarQubeReporter() override; - - static std::string getDescription() { - return "Reports test results in the Generic Test Data SonarQube XML format"; - } - - static std::set getSupportedVerbosities() { - return { Verbosity::Normal }; - } - - void noMatchingTestCases(std::string const& /*spec*/) override {} - - void testRunStarting(TestRunInfo const& testRunInfo) override { - CumulativeReporterBase::testRunStarting(testRunInfo); - xml.startElement("testExecutions"); - xml.writeAttribute("version", "1"); - } - - void testGroupEnded(TestGroupStats const& testGroupStats) override { - CumulativeReporterBase::testGroupEnded(testGroupStats); - writeGroup(*m_testGroups.back()); - } - - void testRunEndedCumulative() override { - xml.endElement(); - } - - void writeGroup(TestGroupNode const& groupNode) { - std::map testsPerFile; - for(auto const& child : groupNode.children) - testsPerFile[child->value.testInfo.lineInfo.file].push_back(child); - - for(auto const& kv : testsPerFile) - writeTestFile(kv.first.c_str(), kv.second); - } - - void writeTestFile(const char* filename, TestGroupNode::ChildNodes const& testCaseNodes) { - XmlWriter::ScopedElement e = xml.scopedElement("file"); - xml.writeAttribute("path", filename); - - for(auto const& child : testCaseNodes) - writeTestCase(*child); - } - - void writeTestCase(TestCaseNode const& testCaseNode) { - // All test cases have exactly one section - which represents the - // test case itself. That section may have 0-n nested sections - assert(testCaseNode.children.size() == 1); - SectionNode const& rootSection = *testCaseNode.children.front(); - writeSection("", rootSection, testCaseNode.value.testInfo.okToFail()); - } - - void writeSection(std::string const& rootName, SectionNode const& sectionNode, bool okToFail) { - std::string name = trim(sectionNode.stats.sectionInfo.name); - if(!rootName.empty()) - name = rootName + '/' + name; - - if(!sectionNode.assertions.empty() || !sectionNode.stdOut.empty() || !sectionNode.stdErr.empty()) { - XmlWriter::ScopedElement e = xml.scopedElement("testCase"); - xml.writeAttribute("name", name); - xml.writeAttribute("duration", static_cast(sectionNode.stats.durationInSeconds * 1000)); - - writeAssertions(sectionNode, okToFail); - } - - for(auto const& childNode : sectionNode.childSections) - writeSection(name, *childNode, okToFail); - } - - void writeAssertions(SectionNode const& sectionNode, bool okToFail) { - for(auto const& assertion : sectionNode.assertions) - writeAssertion( assertion, okToFail); - } - - void writeAssertion(AssertionStats const& stats, bool okToFail) { - AssertionResult const& result = stats.assertionResult; - if(!result.isOk()) { - std::string elementName; - if(okToFail) { - elementName = "skipped"; - } - else { - switch(result.getResultType()) { - case ResultWas::ThrewException: - case ResultWas::FatalErrorCondition: - elementName = "error"; - break; - case ResultWas::ExplicitFailure: - elementName = "failure"; - break; - case ResultWas::ExpressionFailed: - elementName = "failure"; - break; - case ResultWas::DidntThrowException: - elementName = "failure"; - break; - - // We should never see these here: - case ResultWas::Info: - case ResultWas::Warning: - case ResultWas::Ok: - case ResultWas::Unknown: - case ResultWas::FailureBit: - case ResultWas::Exception: - elementName = "internalError"; - break; - } - } - - XmlWriter::ScopedElement e = xml.scopedElement(elementName); - - ReusableStringStream messageRss; - messageRss << result.getTestMacroName() << "(" << result.getExpression() << ")"; - xml.writeAttribute("message", messageRss.str()); - - ReusableStringStream textRss; - if (stats.totals.assertions.total() > 0) { - textRss << "FAILED:\n"; - if (result.hasExpression()) { - textRss << "\t" << result.getExpressionInMacro() << "\n"; - } - if (result.hasExpandedExpression()) { - textRss << "with expansion:\n\t" << result.getExpandedExpression() << "\n"; - } - } - - if(!result.getMessage().empty()) - textRss << result.getMessage() << "\n"; - - for(auto const& msg : stats.infoMessages) - if(msg.type == ResultWas::Info) - textRss << msg.message << "\n"; - - textRss << "at " << result.getSourceInfo(); - xml.writeText(textRss.str(), XmlFormatting::Newline); - } - } - - private: - XmlWriter xml; - }; - -#ifdef CATCH_IMPL - SonarQubeReporter::~SonarQubeReporter() {} -#endif - - CATCH_REGISTER_REPORTER( "sonarqube", SonarQubeReporter ) - -} // end namespace Catch - -#endif // CATCH_REPORTER_SONARQUBE_HPP_INCLUDED \ No newline at end of file diff --git a/third_party/catch2/include/catch2/catch_reporter_tap.hpp b/third_party/catch2/include/catch2/catch_reporter_tap.hpp deleted file mode 100644 index 5ac8524ce7..0000000000 --- a/third_party/catch2/include/catch2/catch_reporter_tap.hpp +++ /dev/null @@ -1,254 +0,0 @@ -/* - * Created by Colton Wolkins on 2015-08-15. - * Copyright 2015 Martin Moene. All rights reserved. - * - * Distributed under the Boost Software License, Version 1.0. (See accompanying - * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - */ -#ifndef TWOBLUECUBES_CATCH_REPORTER_TAP_HPP_INCLUDED -#define TWOBLUECUBES_CATCH_REPORTER_TAP_HPP_INCLUDED - - -// Don't #include any Catch headers here - we can assume they are already -// included before this header. -// This is not good practice in general but is necessary in this case so this -// file can be distributed as a single header that works with the main -// Catch single header. - -#include - -namespace Catch { - - struct TAPReporter : StreamingReporterBase { - - using StreamingReporterBase::StreamingReporterBase; - - TAPReporter( ReporterConfig const& config ): - StreamingReporterBase( config ) { - m_reporterPrefs.shouldReportAllAssertions = true; - } - - ~TAPReporter() override; - - static std::string getDescription() { - return "Reports test results in TAP format, suitable for test harnesses"; - } - - void noMatchingTestCases( std::string const& spec ) override { - stream << "# No test cases matched '" << spec << "'" << std::endl; - } - - void assertionStarting( AssertionInfo const& ) override {} - - bool assertionEnded( AssertionStats const& _assertionStats ) override { - ++counter; - - stream << "# " << currentTestCaseInfo->name << std::endl; - AssertionPrinter printer( stream, _assertionStats, counter ); - printer.print(); - - stream << std::endl; - return true; - } - - void testRunEnded( TestRunStats const& _testRunStats ) override { - printTotals( _testRunStats.totals ); - stream << "\n" << std::endl; - StreamingReporterBase::testRunEnded( _testRunStats ); - } - - private: - std::size_t counter = 0; - class AssertionPrinter { - public: - AssertionPrinter& operator= ( AssertionPrinter const& ) = delete; - AssertionPrinter( AssertionPrinter const& ) = delete; - AssertionPrinter( std::ostream& _stream, AssertionStats const& _stats, std::size_t _counter ) - : stream( _stream ) - , result( _stats.assertionResult ) - , messages( _stats.infoMessages ) - , itMessage( _stats.infoMessages.begin() ) - , printInfoMessages( true ) - , counter(_counter) - {} - - void print() { - itMessage = messages.begin(); - - switch( result.getResultType() ) { - case ResultWas::Ok: - printResultType( passedString() ); - printOriginalExpression(); - printReconstructedExpression(); - if ( ! result.hasExpression() ) - printRemainingMessages( Colour::None ); - else - printRemainingMessages(); - break; - case ResultWas::ExpressionFailed: - if (result.isOk()) { - printResultType(passedString()); - } else { - printResultType(failedString()); - } - printOriginalExpression(); - printReconstructedExpression(); - if (result.isOk()) { - printIssue(" # TODO"); - } - printRemainingMessages(); - break; - case ResultWas::ThrewException: - printResultType( failedString() ); - printIssue( "unexpected exception with message:" ); - printMessage(); - printExpressionWas(); - printRemainingMessages(); - break; - case ResultWas::FatalErrorCondition: - printResultType( failedString() ); - printIssue( "fatal error condition with message:" ); - printMessage(); - printExpressionWas(); - printRemainingMessages(); - break; - case ResultWas::DidntThrowException: - printResultType( failedString() ); - printIssue( "expected exception, got none" ); - printExpressionWas(); - printRemainingMessages(); - break; - case ResultWas::Info: - printResultType( "info" ); - printMessage(); - printRemainingMessages(); - break; - case ResultWas::Warning: - printResultType( "warning" ); - printMessage(); - printRemainingMessages(); - break; - case ResultWas::ExplicitFailure: - printResultType( failedString() ); - printIssue( "explicitly" ); - printRemainingMessages( Colour::None ); - break; - // These cases are here to prevent compiler warnings - case ResultWas::Unknown: - case ResultWas::FailureBit: - case ResultWas::Exception: - printResultType( "** internal error **" ); - break; - } - } - - private: - static Colour::Code dimColour() { return Colour::FileName; } - - static const char* failedString() { return "not ok"; } - static const char* passedString() { return "ok"; } - - void printSourceInfo() const { - Colour colourGuard( dimColour() ); - stream << result.getSourceInfo() << ":"; - } - - void printResultType( std::string const& passOrFail ) const { - if( !passOrFail.empty() ) { - stream << passOrFail << ' ' << counter << " -"; - } - } - - void printIssue( std::string const& issue ) const { - stream << " " << issue; - } - - void printExpressionWas() { - if( result.hasExpression() ) { - stream << ";"; - { - Colour colour( dimColour() ); - stream << " expression was:"; - } - printOriginalExpression(); - } - } - - void printOriginalExpression() const { - if( result.hasExpression() ) { - stream << " " << result.getExpression(); - } - } - - void printReconstructedExpression() const { - if( result.hasExpandedExpression() ) { - { - Colour colour( dimColour() ); - stream << " for: "; - } - std::string expr = result.getExpandedExpression(); - std::replace( expr.begin(), expr.end(), '\n', ' '); - stream << expr; - } - } - - void printMessage() { - if ( itMessage != messages.end() ) { - stream << " '" << itMessage->message << "'"; - ++itMessage; - } - } - - void printRemainingMessages( Colour::Code colour = dimColour() ) { - if (itMessage == messages.end()) { - return; - } - - const auto itEnd = messages.cend(); - const auto N = static_cast( std::distance( itMessage, itEnd ) ); - - { - Colour colourGuard( colour ); - stream << " with " << pluralise( N, "message" ) << ":"; - } - - while( itMessage != itEnd ) { - // If this assertion is a warning ignore any INFO messages - if( printInfoMessages || itMessage->type != ResultWas::Info ) { - stream << " '" << itMessage->message << "'"; - if ( ++itMessage != itEnd ) { - Colour colourGuard( dimColour() ); - stream << " and"; - } - continue; - } - ++itMessage; - } - } - - private: - std::ostream& stream; - AssertionResult const& result; - std::vector messages; - std::vector::const_iterator itMessage; - bool printInfoMessages; - std::size_t counter; - }; - - void printTotals( const Totals& totals ) const { - stream << "1.." << totals.assertions.total(); - if( totals.testCases.total() == 0 ) { - stream << " # Skipped: No tests ran."; - } - } - }; - -#ifdef CATCH_IMPL - TAPReporter::~TAPReporter() {} -#endif - - CATCH_REGISTER_REPORTER( "tap", TAPReporter ) - -} // end namespace Catch - -#endif // TWOBLUECUBES_CATCH_REPORTER_TAP_HPP_INCLUDED diff --git a/third_party/catch2/include/catch2/catch_reporter_teamcity.hpp b/third_party/catch2/include/catch2/catch_reporter_teamcity.hpp deleted file mode 100644 index 47b7e4aac3..0000000000 --- a/third_party/catch2/include/catch2/catch_reporter_teamcity.hpp +++ /dev/null @@ -1,219 +0,0 @@ -/* - * Created by Phil Nash on 19th December 2014 - * Copyright 2014 Two Blue Cubes Ltd. All rights reserved. - * - * Distributed under the Boost Software License, Version 1.0. (See accompanying - * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - */ -#ifndef TWOBLUECUBES_CATCH_REPORTER_TEAMCITY_HPP_INCLUDED -#define TWOBLUECUBES_CATCH_REPORTER_TEAMCITY_HPP_INCLUDED - -// Don't #include any Catch headers here - we can assume they are already -// included before this header. -// This is not good practice in general but is necessary in this case so this -// file can be distributed as a single header that works with the main -// Catch single header. - -#include - -#ifdef __clang__ -# pragma clang diagnostic push -# pragma clang diagnostic ignored "-Wpadded" -#endif - -namespace Catch { - - struct TeamCityReporter : StreamingReporterBase { - TeamCityReporter( ReporterConfig const& _config ) - : StreamingReporterBase( _config ) - { - m_reporterPrefs.shouldRedirectStdOut = true; - } - - static std::string escape( std::string const& str ) { - std::string escaped = str; - replaceInPlace( escaped, "|", "||" ); - replaceInPlace( escaped, "'", "|'" ); - replaceInPlace( escaped, "\n", "|n" ); - replaceInPlace( escaped, "\r", "|r" ); - replaceInPlace( escaped, "[", "|[" ); - replaceInPlace( escaped, "]", "|]" ); - return escaped; - } - ~TeamCityReporter() override; - - static std::string getDescription() { - return "Reports test results as TeamCity service messages"; - } - - void skipTest( TestCaseInfo const& /* testInfo */ ) override { - } - - void noMatchingTestCases( std::string const& /* spec */ ) override {} - - void testGroupStarting( GroupInfo const& groupInfo ) override { - StreamingReporterBase::testGroupStarting( groupInfo ); - stream << "##teamcity[testSuiteStarted name='" - << escape( groupInfo.name ) << "']\n"; - } - void testGroupEnded( TestGroupStats const& testGroupStats ) override { - StreamingReporterBase::testGroupEnded( testGroupStats ); - stream << "##teamcity[testSuiteFinished name='" - << escape( testGroupStats.groupInfo.name ) << "']\n"; - } - - - void assertionStarting( AssertionInfo const& ) override {} - - bool assertionEnded( AssertionStats const& assertionStats ) override { - AssertionResult const& result = assertionStats.assertionResult; - if( !result.isOk() ) { - - ReusableStringStream msg; - if( !m_headerPrintedForThisSection ) - printSectionHeader( msg.get() ); - m_headerPrintedForThisSection = true; - - msg << result.getSourceInfo() << "\n"; - - switch( result.getResultType() ) { - case ResultWas::ExpressionFailed: - msg << "expression failed"; - break; - case ResultWas::ThrewException: - msg << "unexpected exception"; - break; - case ResultWas::FatalErrorCondition: - msg << "fatal error condition"; - break; - case ResultWas::DidntThrowException: - msg << "no exception was thrown where one was expected"; - break; - case ResultWas::ExplicitFailure: - msg << "explicit failure"; - break; - - // We shouldn't get here because of the isOk() test - case ResultWas::Ok: - case ResultWas::Info: - case ResultWas::Warning: - CATCH_ERROR( "Internal error in TeamCity reporter" ); - // These cases are here to prevent compiler warnings - case ResultWas::Unknown: - case ResultWas::FailureBit: - case ResultWas::Exception: - CATCH_ERROR( "Not implemented" ); - } - if( assertionStats.infoMessages.size() == 1 ) - msg << " with message:"; - if( assertionStats.infoMessages.size() > 1 ) - msg << " with messages:"; - for( auto const& messageInfo : assertionStats.infoMessages ) - msg << "\n \"" << messageInfo.message << "\""; - - - if( result.hasExpression() ) { - msg << - "\n " << result.getExpressionInMacro() << "\n" - "with expansion:\n" << - " " << result.getExpandedExpression() << "\n"; - } - - if( currentTestCaseInfo->okToFail() ) { - msg << "- failure ignore as test marked as 'ok to fail'\n"; - stream << "##teamcity[testIgnored" - << " name='" << escape( currentTestCaseInfo->name )<< "'" - << " message='" << escape( msg.str() ) << "'" - << "]\n"; - } - else { - stream << "##teamcity[testFailed" - << " name='" << escape( currentTestCaseInfo->name )<< "'" - << " message='" << escape( msg.str() ) << "'" - << "]\n"; - } - } - stream.flush(); - return true; - } - - void sectionStarting( SectionInfo const& sectionInfo ) override { - m_headerPrintedForThisSection = false; - StreamingReporterBase::sectionStarting( sectionInfo ); - } - - void testCaseStarting( TestCaseInfo const& testInfo ) override { - m_testTimer.start(); - StreamingReporterBase::testCaseStarting( testInfo ); - stream << "##teamcity[testStarted name='" - << escape( testInfo.name ) << "']\n"; - stream.flush(); - } - - void testCaseEnded( TestCaseStats const& testCaseStats ) override { - StreamingReporterBase::testCaseEnded( testCaseStats ); - if( !testCaseStats.stdOut.empty() ) - stream << "##teamcity[testStdOut name='" - << escape( testCaseStats.testInfo.name ) - << "' out='" << escape( testCaseStats.stdOut ) << "']\n"; - if( !testCaseStats.stdErr.empty() ) - stream << "##teamcity[testStdErr name='" - << escape( testCaseStats.testInfo.name ) - << "' out='" << escape( testCaseStats.stdErr ) << "']\n"; - stream << "##teamcity[testFinished name='" - << escape( testCaseStats.testInfo.name ) << "' duration='" - << m_testTimer.getElapsedMilliseconds() << "']\n"; - stream.flush(); - } - - private: - void printSectionHeader( std::ostream& os ) { - assert( !m_sectionStack.empty() ); - - if( m_sectionStack.size() > 1 ) { - os << getLineOfChars<'-'>() << "\n"; - - std::vector::const_iterator - it = m_sectionStack.begin()+1, // Skip first section (test case) - itEnd = m_sectionStack.end(); - for( ; it != itEnd; ++it ) - printHeaderString( os, it->name ); - os << getLineOfChars<'-'>() << "\n"; - } - - SourceLineInfo lineInfo = m_sectionStack.front().lineInfo; - - os << lineInfo << "\n"; - os << getLineOfChars<'.'>() << "\n\n"; - } - - // if string has a : in first line will set indent to follow it on - // subsequent lines - static void printHeaderString( std::ostream& os, std::string const& _string, std::size_t indent = 0 ) { - std::size_t i = _string.find( ": " ); - if( i != std::string::npos ) - i+=2; - else - i = 0; - os << Column( _string ) - .indent( indent+i) - .initialIndent( indent ) << "\n"; - } - private: - bool m_headerPrintedForThisSection = false; - Timer m_testTimer; - }; - -#ifdef CATCH_IMPL - TeamCityReporter::~TeamCityReporter() {} -#endif - - CATCH_REGISTER_REPORTER( "teamcity", TeamCityReporter ) - -} // end namespace Catch - -#ifdef __clang__ -# pragma clang diagnostic pop -#endif - -#endif // TWOBLUECUBES_CATCH_REPORTER_TEAMCITY_HPP_INCLUDED diff --git a/third_party/json11/json11.cpp b/third_party/json11/json11.cpp deleted file mode 100644 index bc4045f07d..0000000000 --- a/third_party/json11/json11.cpp +++ /dev/null @@ -1,784 +0,0 @@ -/* Copyright (c) 2013 Dropbox, Inc. - * - * 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. - */ - -#include "json11.hpp" -#include -#include -#include -#include -#include - -namespace json11 { - -static const int max_depth = 200; - -using std::string; -using std::vector; -using std::map; -using std::make_shared; -using std::initializer_list; -using std::move; - -/* Helper for representing null - just a do-nothing struct, plus comparison - * operators so the helpers in JsonValue work. We can't use nullptr_t because - * it may not be orderable. - */ -struct NullStruct { - bool operator==(NullStruct) const { return true; } - bool operator<(NullStruct) const { return false; } -}; - -/* * * * * * * * * * * * * * * * * * * * - * Serialization - */ - -static void dump(NullStruct, string &out) { - out += "null"; -} - -static void dump(double value, string &out) { - if (std::isfinite(value)) { - char buf[32]; - snprintf(buf, sizeof buf, "%.17g", value); - out += buf; - } else { - out += "null"; - } -} - -static void dump(int value, string &out) { - char buf[32]; - snprintf(buf, sizeof buf, "%d", value); - out += buf; -} - -static void dump(bool value, string &out) { - out += value ? "true" : "false"; -} - -static void dump(const string &value, string &out) { - out += '"'; - for (size_t i = 0; i < value.length(); i++) { - const char ch = value[i]; - if (ch == '\\') { - out += "\\\\"; - } else if (ch == '"') { - out += "\\\""; - } else if (ch == '\b') { - out += "\\b"; - } else if (ch == '\f') { - out += "\\f"; - } else if (ch == '\n') { - out += "\\n"; - } else if (ch == '\r') { - out += "\\r"; - } else if (ch == '\t') { - out += "\\t"; - } else if (static_cast(ch) <= 0x1f) { - char buf[8]; - snprintf(buf, sizeof buf, "\\u%04x", ch); - out += buf; - } else if (static_cast(ch) == 0xe2 && static_cast(value[i+1]) == 0x80 - && static_cast(value[i+2]) == 0xa8) { - out += "\\u2028"; - i += 2; - } else if (static_cast(ch) == 0xe2 && static_cast(value[i+1]) == 0x80 - && static_cast(value[i+2]) == 0xa9) { - out += "\\u2029"; - i += 2; - } else { - out += ch; - } - } - out += '"'; -} - -static void dump(const Json::array &values, string &out) { - bool first = true; - out += "["; - for (const auto &value : values) { - if (!first) - out += ", "; - value.dump(out); - first = false; - } - out += "]"; -} - -static void dump(const Json::object &values, string &out) { - bool first = true; - out += "{"; - for (const auto &kv : values) { - if (!first) - out += ", "; - dump(kv.first, out); - out += ": "; - kv.second.dump(out); - first = false; - } - out += "}"; -} - -void Json::dump(string &out) const { - m_ptr->dump(out); -} - -/* * * * * * * * * * * * * * * * * * * * - * Value wrappers - */ - -template -class Value : public JsonValue { -protected: - - // Constructors - explicit Value(const T &value) : m_value(value) {} - explicit Value(T &&value) : m_value(move(value)) {} - - // Get type tag - Json::Type type() const override { - return tag; - } - - // Comparisons - bool equals(const JsonValue * other) const override { - return m_value == static_cast *>(other)->m_value; - } - bool less(const JsonValue * other) const override { - return m_value < static_cast *>(other)->m_value; - } - - const T m_value; - void dump(string &out) const override { json11::dump(m_value, out); } -}; - -class JsonDouble final : public Value { - double number_value() const override { return m_value; } - int int_value() const override { return static_cast(m_value); } - bool equals(const JsonValue * other) const override { return m_value == other->number_value(); } - bool less(const JsonValue * other) const override { return m_value < other->number_value(); } -public: - explicit JsonDouble(double value) : Value(value) {} -}; - -class JsonInt final : public Value { - double number_value() const override { return m_value; } - int int_value() const override { return m_value; } - bool equals(const JsonValue * other) const override { return m_value == other->number_value(); } - bool less(const JsonValue * other) const override { return m_value < other->number_value(); } -public: - explicit JsonInt(int value) : Value(value) {} -}; - -class JsonBoolean final : public Value { - bool bool_value() const override { return m_value; } -public: - explicit JsonBoolean(bool value) : Value(value) {} -}; - -class JsonString final : public Value { - const string &string_value() const override { return m_value; } -public: - explicit JsonString(const string &value) : Value(value) {} - explicit JsonString(string &&value) : Value(move(value)) {} -}; - -class JsonArray final : public Value { - const Json::array &array_items() const override { return m_value; } - const Json & operator[](size_t i) const override; -public: - explicit JsonArray(const Json::array &value) : Value(value) {} - explicit JsonArray(Json::array &&value) : Value(move(value)) {} -}; - -class JsonObject final : public Value { - const Json::object &object_items() const override { return m_value; } - const Json & operator[](const string &key) const override; -public: - explicit JsonObject(const Json::object &value) : Value(value) {} - explicit JsonObject(Json::object &&value) : Value(move(value)) {} -}; - -class JsonNull final : public Value { -public: - JsonNull() : Value({}) {} -}; - -/* * * * * * * * * * * * * * * * * * * * - * Static globals - static-init-safe - */ -struct Statics { - const std::shared_ptr null = make_shared(); - const std::shared_ptr t = make_shared(true); - const std::shared_ptr f = make_shared(false); - const string empty_string; - const vector empty_vector; - const map empty_map; - Statics() {} -}; - -static const Statics & statics() { - static const Statics s {}; - return s; -} - -static const Json & static_null() { - // This has to be separate, not in Statics, because Json() accesses statics().null. - static const Json json_null; - return json_null; -} - -/* * * * * * * * * * * * * * * * * * * * - * Constructors - */ - -Json::Json() noexcept : m_ptr(statics().null) {} -Json::Json(std::nullptr_t) noexcept : m_ptr(statics().null) {} -Json::Json(double value) : m_ptr(make_shared(value)) {} -Json::Json(int value) : m_ptr(make_shared(value)) {} -Json::Json(bool value) : m_ptr(value ? statics().t : statics().f) {} -Json::Json(const string &value) : m_ptr(make_shared(value)) {} -Json::Json(string &&value) : m_ptr(make_shared(move(value))) {} -Json::Json(const char * value) : m_ptr(make_shared(value)) {} -Json::Json(const Json::array &values) : m_ptr(make_shared(values)) {} -Json::Json(Json::array &&values) : m_ptr(make_shared(move(values))) {} -Json::Json(const Json::object &values) : m_ptr(make_shared(values)) {} -Json::Json(Json::object &&values) : m_ptr(make_shared(move(values))) {} - -/* * * * * * * * * * * * * * * * * * * * - * Accessors - */ - -Json::Type Json::type() const { return m_ptr->type(); } -double Json::number_value() const { return m_ptr->number_value(); } -int Json::int_value() const { return m_ptr->int_value(); } -bool Json::bool_value() const { return m_ptr->bool_value(); } -const string & Json::string_value() const { return m_ptr->string_value(); } -const vector & Json::array_items() const { return m_ptr->array_items(); } -const map & Json::object_items() const { return m_ptr->object_items(); } -const Json & Json::operator[] (size_t i) const { return (*m_ptr)[i]; } -const Json & Json::operator[] (const string &key) const { return (*m_ptr)[key]; } - -double JsonValue::number_value() const { return 0; } -int JsonValue::int_value() const { return 0; } -bool JsonValue::bool_value() const { return false; } -const string & JsonValue::string_value() const { return statics().empty_string; } -const vector & JsonValue::array_items() const { return statics().empty_vector; } -const map & JsonValue::object_items() const { return statics().empty_map; } -const Json & JsonValue::operator[] (size_t) const { return static_null(); } -const Json & JsonValue::operator[] (const string &) const { return static_null(); } - -const Json & JsonObject::operator[] (const string &key) const { - auto iter = m_value.find(key); - return (iter == m_value.end()) ? static_null() : iter->second; -} -const Json & JsonArray::operator[] (size_t i) const { - if (i >= m_value.size()) return static_null(); - else return m_value[i]; -} - -/* * * * * * * * * * * * * * * * * * * * - * Comparison - */ - -bool Json::operator== (const Json &other) const { - if (m_ptr->type() != other.m_ptr->type()) - return false; - - return m_ptr->equals(other.m_ptr.get()); -} - -bool Json::operator< (const Json &other) const { - if (m_ptr->type() != other.m_ptr->type()) - return m_ptr->type() < other.m_ptr->type(); - - return m_ptr->less(other.m_ptr.get()); -} - -/* * * * * * * * * * * * * * * * * * * * - * Parsing - */ - -/* esc(c) - * - * Format char c suitable for printing in an error message. - */ -static inline string esc(char c) { - char buf[12]; - if (static_cast(c) >= 0x20 && static_cast(c) <= 0x7f) { - snprintf(buf, sizeof buf, "'%c' (%d)", c, c); - } else { - snprintf(buf, sizeof buf, "(%d)", c); - } - return string(buf); -} - -static inline bool in_range(long x, long lower, long upper) { - return (x >= lower && x <= upper); -} - -namespace { -/* JsonParser - * - * Object that tracks all state of an in-progress parse. - */ -struct JsonParser final { - - /* State - */ - const string &str; - size_t i; - string &err; - bool failed; - const JsonParse strategy; - - /* fail(msg, err_ret = Json()) - * - * Mark this parse as failed. - */ - Json fail(string &&msg) { - return fail(move(msg), Json()); - } - - template - T fail(string &&msg, const T err_ret) { - if (!failed) - err = std::move(msg); - failed = true; - return err_ret; - } - - /* consume_whitespace() - * - * Advance until the current character is non-whitespace. - */ - void consume_whitespace() { - while (str[i] == ' ' || str[i] == '\r' || str[i] == '\n' || str[i] == '\t') - i++; - } - - /* consume_comment() - * - * Advance comments (c-style inline and multiline). - */ - bool consume_comment() { - bool comment_found = false; - if (str[i] == '/') { - i++; - if (i == str.size()) - return fail("unexpected end of input after start of comment", false); - if (str[i] == '/') { // inline comment - i++; - // advance until next line, or end of input - while (i < str.size() && str[i] != '\n') { - i++; - } - comment_found = true; - } - else if (str[i] == '*') { // multiline comment - i++; - if (i > str.size()-2) - return fail("unexpected end of input inside multi-line comment", false); - // advance until closing tokens - while (!(str[i] == '*' && str[i+1] == '/')) { - i++; - if (i > str.size()-2) - return fail( - "unexpected end of input inside multi-line comment", false); - } - i += 2; - comment_found = true; - } - else - return fail("malformed comment", false); - } - return comment_found; - } - - /* consume_garbage() - * - * Advance until the current character is non-whitespace and non-comment. - */ - void consume_garbage() { - consume_whitespace(); - if(strategy == JsonParse::COMMENTS) { - bool comment_found = false; - do { - comment_found = consume_comment(); - if (failed) return; - consume_whitespace(); - } - while(comment_found); - } - } - - /* get_next_token() - * - * Return the next non-whitespace character. If the end of the input is reached, - * flag an error and return 0. - */ - char get_next_token() { - consume_garbage(); - if (failed) return (char)0; - if (i == str.size()) - return fail("unexpected end of input", (char)0); - - return str[i++]; - } - - /* encode_utf8(pt, out) - * - * Encode pt as UTF-8 and add it to out. - */ - void encode_utf8(long pt, string & out) { - if (pt < 0) - return; - - if (pt < 0x80) { - out += static_cast(pt); - } else if (pt < 0x800) { - out += static_cast((pt >> 6) | 0xC0); - out += static_cast((pt & 0x3F) | 0x80); - } else if (pt < 0x10000) { - out += static_cast((pt >> 12) | 0xE0); - out += static_cast(((pt >> 6) & 0x3F) | 0x80); - out += static_cast((pt & 0x3F) | 0x80); - } else { - out += static_cast((pt >> 18) | 0xF0); - out += static_cast(((pt >> 12) & 0x3F) | 0x80); - out += static_cast(((pt >> 6) & 0x3F) | 0x80); - out += static_cast((pt & 0x3F) | 0x80); - } - } - - /* parse_string() - * - * Parse a string, starting at the current position. - */ - string parse_string() { - string out; - long last_escaped_codepoint = -1; - while (true) { - if (i == str.size()) - return fail("unexpected end of input in string", ""); - - char ch = str[i++]; - - if (ch == '"') { - encode_utf8(last_escaped_codepoint, out); - return out; - } - - if (in_range(ch, 0, 0x1f)) - return fail("unescaped " + esc(ch) + " in string", ""); - - // The usual case: non-escaped characters - if (ch != '\\') { - encode_utf8(last_escaped_codepoint, out); - last_escaped_codepoint = -1; - out += ch; - continue; - } - - // Handle escapes - if (i == str.size()) - return fail("unexpected end of input in string", ""); - - ch = str[i++]; - - if (ch == 'u') { - // Extract 4-byte escape sequence - string esc = str.substr(i, 4); - // Explicitly check length of the substring. The following loop - // relies on std::string returning the terminating NUL when - // accessing str[length]. Checking here reduces brittleness. - if (esc.length() < 4) { - return fail("bad \\u escape: " + esc, ""); - } - for (size_t j = 0; j < 4; j++) { - if (!in_range(esc[j], 'a', 'f') && !in_range(esc[j], 'A', 'F') - && !in_range(esc[j], '0', '9')) - return fail("bad \\u escape: " + esc, ""); - } - - long codepoint = strtol(esc.data(), nullptr, 16); - - // JSON specifies that characters outside the BMP shall be encoded as a pair - // of 4-hex-digit \u escapes encoding their surrogate pair components. Check - // whether we're in the middle of such a beast: the previous codepoint was an - // escaped lead (high) surrogate, and this is a trail (low) surrogate. - if (in_range(last_escaped_codepoint, 0xD800, 0xDBFF) - && in_range(codepoint, 0xDC00, 0xDFFF)) { - // Reassemble the two surrogate pairs into one astral-plane character, per - // the UTF-16 algorithm. - encode_utf8((((last_escaped_codepoint - 0xD800) << 10) - | (codepoint - 0xDC00)) + 0x10000, out); - last_escaped_codepoint = -1; - } else { - encode_utf8(last_escaped_codepoint, out); - last_escaped_codepoint = codepoint; - } - - i += 4; - continue; - } - - encode_utf8(last_escaped_codepoint, out); - last_escaped_codepoint = -1; - - if (ch == 'b') { - out += '\b'; - } else if (ch == 'f') { - out += '\f'; - } else if (ch == 'n') { - out += '\n'; - } else if (ch == 'r') { - out += '\r'; - } else if (ch == 't') { - out += '\t'; - } else if (ch == '"' || ch == '\\' || ch == '/') { - out += ch; - } else { - return fail("invalid escape character " + esc(ch), ""); - } - } - } - - /* parse_number() - * - * Parse a double. - */ - Json parse_number() { - size_t start_pos = i; - - if (str[i] == '-') - i++; - - // Integer part - if (str[i] == '0') { - i++; - if (in_range(str[i], '0', '9')) - return fail("leading 0s not permitted in numbers"); - } else if (in_range(str[i], '1', '9')) { - i++; - while (in_range(str[i], '0', '9')) - i++; - } else { - return fail("invalid " + esc(str[i]) + " in number"); - } - - if (str[i] != '.' && str[i] != 'e' && str[i] != 'E' - && (i - start_pos) <= static_cast(std::numeric_limits::digits10)) { - return std::atoi(str.c_str() + start_pos); - } - - // Decimal part - if (str[i] == '.') { - i++; - if (!in_range(str[i], '0', '9')) - return fail("at least one digit required in fractional part"); - - while (in_range(str[i], '0', '9')) - i++; - } - - // Exponent part - if (str[i] == 'e' || str[i] == 'E') { - i++; - - if (str[i] == '+' || str[i] == '-') - i++; - - if (!in_range(str[i], '0', '9')) - return fail("at least one digit required in exponent"); - - while (in_range(str[i], '0', '9')) - i++; - } - - return std::strtod(str.c_str() + start_pos, nullptr); - } - - /* expect(str, res) - * - * Expect that 'str' starts at the character that was just read. If it does, advance - * the input and return res. If not, flag an error. - */ - Json expect(const string &expected, Json res) { - assert(i != 0); - i--; - if (str.compare(i, expected.length(), expected) == 0) { - i += expected.length(); - return res; - } else { - return fail("parse error: expected " + expected + ", got " + str.substr(i, expected.length())); - } - } - - /* parse_json() - * - * Parse a JSON object. - */ - Json parse_json(int depth) { - if (depth > max_depth) { - return fail("exceeded maximum nesting depth"); - } - - char ch = get_next_token(); - if (failed) - return Json(); - - if (ch == '-' || (ch >= '0' && ch <= '9')) { - i--; - return parse_number(); - } - - if (ch == 't') - return expect("true", true); - - if (ch == 'f') - return expect("false", false); - - if (ch == 'n') - return expect("null", Json()); - - if (ch == '"') - return parse_string(); - - if (ch == '{') { - map data; - ch = get_next_token(); - if (ch == '}') - return data; - - while (1) { - if (ch != '"') - return fail("expected '\"' in object, got " + esc(ch)); - - string key = parse_string(); - if (failed) - return Json(); - - ch = get_next_token(); - if (ch != ':') - return fail("expected ':' in object, got " + esc(ch)); - - data[std::move(key)] = parse_json(depth + 1); - if (failed) - return Json(); - - ch = get_next_token(); - if (ch == '}') - break; - if (ch != ',') - return fail("expected ',' in object, got " + esc(ch)); - - ch = get_next_token(); - } - return data; - } - - if (ch == '[') { - vector data; - ch = get_next_token(); - if (ch == ']') - return data; - - while (1) { - i--; - data.push_back(parse_json(depth + 1)); - if (failed) - return Json(); - - ch = get_next_token(); - if (ch == ']') - break; - if (ch != ',') - return fail("expected ',' in list, got " + esc(ch)); - - ch = get_next_token(); - (void)ch; - } - return data; - } - - return fail("expected value, got " + esc(ch)); - } -}; -}//namespace { - -Json Json::parse(const string &in, string &err, JsonParse strategy) { - JsonParser parser { in, 0, err, false, strategy }; - Json result = parser.parse_json(0); - - // Check for any trailing garbage - parser.consume_garbage(); - if (parser.failed) - return Json(); - if (parser.i != in.size()) - return parser.fail("unexpected trailing " + esc(in[parser.i])); - - return result; -} - -// Documented in json11.hpp -vector Json::parse_multi(const string &in, - std::string::size_type &parser_stop_pos, - string &err, - JsonParse strategy) { - JsonParser parser { in, 0, err, false, strategy }; - parser_stop_pos = 0; - vector json_vec; - while (parser.i != in.size() && !parser.failed) { - json_vec.push_back(parser.parse_json(0)); - if (parser.failed) - break; - - // Check for another object - parser.consume_garbage(); - if (parser.failed) - break; - parser_stop_pos = parser.i; - } - return json_vec; -} - -/* * * * * * * * * * * * * * * * * * * * - * Shape-checking - */ - -bool Json::has_shape(const shape & types, string & err) const { - if (!is_object()) { - err = "expected JSON object, got " + dump(); - return false; - } - - for (auto & item : types) { - if ((*this)[item.first].type() != item.second) { - err = "bad type for " + item.first + " in " + dump(); - return false; - } - } - - return true; -} - -} // namespace json11 diff --git a/third_party/json11/json11.hpp b/third_party/json11/json11.hpp deleted file mode 100644 index 5202ef9323..0000000000 --- a/third_party/json11/json11.hpp +++ /dev/null @@ -1,232 +0,0 @@ -/* json11 - * - * json11 is a tiny JSON library for C++11, providing JSON parsing and serialization. - * - * The core object provided by the library is json11::Json. A Json object represents any JSON - * value: null, bool, number (int or double), string (std::string), array (std::vector), or - * object (std::map). - * - * Json objects act like values: they can be assigned, copied, moved, compared for equality or - * order, etc. There are also helper methods Json::dump, to serialize a Json to a string, and - * Json::parse (static) to parse a std::string as a Json object. - * - * Internally, the various types of Json object are represented by the JsonValue class - * hierarchy. - * - * A note on numbers - JSON specifies the syntax of number formatting but not its semantics, - * so some JSON implementations distinguish between integers and floating-point numbers, while - * some don't. In json11, we choose the latter. Because some JSON implementations (namely - * Javascript itself) treat all numbers as the same type, distinguishing the two leads - * to JSON that will be *silently* changed by a round-trip through those implementations. - * Dangerous! To avoid that risk, json11 stores all numbers as double internally, but also - * provides integer helpers. - * - * Fortunately, double-precision IEEE754 ('double') can precisely store any integer in the - * range +/-2^53, which includes every 'int' on most systems. (Timestamps often use int64 - * or long long to avoid the Y2038K problem; a double storing microseconds since some epoch - * will be exact for +/- 275 years.) - */ - -/* Copyright (c) 2013 Dropbox, Inc. - * - * 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. - */ - -#pragma once - -#include -#include -#include -#include -#include - -#ifdef _MSC_VER - #if _MSC_VER <= 1800 // VS 2013 - #ifndef noexcept - #define noexcept throw() - #endif - - #ifndef snprintf - #define snprintf _snprintf_s - #endif - #endif -#endif - -namespace json11 { - -enum JsonParse { - STANDARD, COMMENTS -}; - -class JsonValue; - -class Json final { -public: - // Types - enum Type { - NUL, NUMBER, BOOL, STRING, ARRAY, OBJECT - }; - - // Array and object typedefs - typedef std::vector array; - typedef std::map object; - - // Constructors for the various types of JSON value. - Json() noexcept; // NUL - Json(std::nullptr_t) noexcept; // NUL - Json(double value); // NUMBER - Json(int value); // NUMBER - Json(bool value); // BOOL - Json(const std::string &value); // STRING - Json(std::string &&value); // STRING - Json(const char * value); // STRING - Json(const array &values); // ARRAY - Json(array &&values); // ARRAY - Json(const object &values); // OBJECT - Json(object &&values); // OBJECT - - // Implicit constructor: anything with a to_json() function. - template - Json(const T & t) : Json(t.to_json()) {} - - // Implicit constructor: map-like objects (std::map, std::unordered_map, etc) - template ::value - && std::is_constructible::value, - int>::type = 0> - Json(const M & m) : Json(object(m.begin(), m.end())) {} - - // Implicit constructor: vector-like objects (std::list, std::vector, std::set, etc) - template ::value, - int>::type = 0> - Json(const V & v) : Json(array(v.begin(), v.end())) {} - - // This prevents Json(some_pointer) from accidentally producing a bool. Use - // Json(bool(some_pointer)) if that behavior is desired. - Json(void *) = delete; - - // Accessors - Type type() const; - - bool is_null() const { return type() == NUL; } - bool is_number() const { return type() == NUMBER; } - bool is_bool() const { return type() == BOOL; } - bool is_string() const { return type() == STRING; } - bool is_array() const { return type() == ARRAY; } - bool is_object() const { return type() == OBJECT; } - - // Return the enclosed value if this is a number, 0 otherwise. Note that json11 does not - // distinguish between integer and non-integer numbers - number_value() and int_value() - // can both be applied to a NUMBER-typed object. - double number_value() const; - int int_value() const; - - // Return the enclosed value if this is a boolean, false otherwise. - bool bool_value() const; - // Return the enclosed string if this is a string, "" otherwise. - const std::string &string_value() const; - // Return the enclosed std::vector if this is an array, or an empty vector otherwise. - const array &array_items() const; - // Return the enclosed std::map if this is an object, or an empty map otherwise. - const object &object_items() const; - - // Return a reference to arr[i] if this is an array, Json() otherwise. - const Json & operator[](size_t i) const; - // Return a reference to obj[key] if this is an object, Json() otherwise. - const Json & operator[](const std::string &key) const; - - // Serialize. - void dump(std::string &out) const; - std::string dump() const { - std::string out; - dump(out); - return out; - } - - // Parse. If parse fails, return Json() and assign an error message to err. - static Json parse(const std::string & in, - std::string & err, - JsonParse strategy = JsonParse::STANDARD); - static Json parse(const char * in, - std::string & err, - JsonParse strategy = JsonParse::STANDARD) { - if (in) { - return parse(std::string(in), err, strategy); - } else { - err = "null input"; - return nullptr; - } - } - // Parse multiple objects, concatenated or separated by whitespace - static std::vector parse_multi( - const std::string & in, - std::string::size_type & parser_stop_pos, - std::string & err, - JsonParse strategy = JsonParse::STANDARD); - - static inline std::vector parse_multi( - const std::string & in, - std::string & err, - JsonParse strategy = JsonParse::STANDARD) { - std::string::size_type parser_stop_pos; - return parse_multi(in, parser_stop_pos, err, strategy); - } - - bool operator== (const Json &rhs) const; - bool operator< (const Json &rhs) const; - bool operator!= (const Json &rhs) const { return !(*this == rhs); } - bool operator<= (const Json &rhs) const { return !(rhs < *this); } - bool operator> (const Json &rhs) const { return (rhs < *this); } - bool operator>= (const Json &rhs) const { return !(*this < rhs); } - - /* has_shape(types, err) - * - * Return true if this is a JSON object and, for each item in types, has a field of - * the given type. If not, return false and set err to a descriptive message. - */ - typedef std::initializer_list> shape; - bool has_shape(const shape & types, std::string & err) const; - -private: - std::shared_ptr m_ptr; -}; - -// Internal class hierarchy - JsonValue objects are not exposed to users of this API. -class JsonValue { -protected: - friend class Json; - friend class JsonInt; - friend class JsonDouble; - virtual Json::Type type() const = 0; - virtual bool equals(const JsonValue * other) const = 0; - virtual bool less(const JsonValue * other) const = 0; - virtual void dump(std::string &out) const = 0; - virtual double number_value() const; - virtual int int_value() const; - virtual bool bool_value() const; - virtual const std::string &string_value() const; - virtual const Json::array &array_items() const; - virtual const Json &operator[](size_t i) const; - virtual const Json::object &object_items() const; - virtual const Json &operator[](const std::string &key) const; - virtual ~JsonValue() {} -}; - -} // namespace json11 diff --git a/third_party/kaitai/custom_decoder.h b/third_party/kaitai/custom_decoder.h deleted file mode 100644 index 6da7f5fd23..0000000000 --- a/third_party/kaitai/custom_decoder.h +++ /dev/null @@ -1,16 +0,0 @@ -#ifndef KAITAI_CUSTOM_DECODER_H -#define KAITAI_CUSTOM_DECODER_H - -#include - -namespace kaitai { - -class custom_decoder { -public: - virtual ~custom_decoder() {}; - virtual std::string decode(std::string src) = 0; -}; - -} - -#endif diff --git a/third_party/kaitai/exceptions.h b/third_party/kaitai/exceptions.h deleted file mode 100644 index 5c09c4672b..0000000000 --- a/third_party/kaitai/exceptions.h +++ /dev/null @@ -1,189 +0,0 @@ -#ifndef KAITAI_EXCEPTIONS_H -#define KAITAI_EXCEPTIONS_H - -#include - -#include -#include - -// We need to use "noexcept" in virtual destructor of our exceptions -// subclasses. Different compilers have different ideas on how to -// achieve that: C++98 compilers prefer `throw()`, C++11 and later -// use `noexcept`. We define KS_NOEXCEPT macro for that. - -#if __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1900) -#define KS_NOEXCEPT noexcept -#else -#define KS_NOEXCEPT throw() -#endif - -namespace kaitai { - -/** - * Common ancestor for all error originating from Kaitai Struct usage. - * Stores KSY source path, pointing to an element supposedly guilty of - * an error. - */ -class kstruct_error: public std::runtime_error { -public: - kstruct_error(const std::string what, const std::string src_path): - std::runtime_error(src_path + ": " + what), - m_src_path(src_path) - { - } - - virtual ~kstruct_error() KS_NOEXCEPT {}; - -protected: - const std::string m_src_path; -}; - -/** - * Error that occurs when default endianness should be decided with - * a switch, but nothing matches (although using endianness expression - * implies that there should be some positive result). - */ -class undecided_endianness_error: public kstruct_error { -public: - undecided_endianness_error(const std::string src_path): - kstruct_error("unable to decide on endianness for a type", src_path) - { - } - - virtual ~undecided_endianness_error() KS_NOEXCEPT {}; -}; - -/** - * Common ancestor for all validation failures. Stores pointer to - * KaitaiStream IO object which was involved in an error. - */ -class validation_failed_error: public kstruct_error { -public: - validation_failed_error(const std::string what, kstream* io, const std::string src_path): - kstruct_error("at pos " + kstream::to_string(static_cast(io->pos())) + ": validation failed: " + what, src_path), - m_io(io) - { - } - -// "at pos #{io.pos}: validation failed: #{msg}" - - virtual ~validation_failed_error() KS_NOEXCEPT {}; - -protected: - kstream* m_io; -}; - -/** - * Signals validation failure: we required "actual" value to be equal to - * "expected", but it turned out that it's not. - */ -template -class validation_not_equal_error: public validation_failed_error { -public: - validation_not_equal_error(const T& expected, const T& actual, kstream* io, const std::string src_path): - validation_failed_error("not equal", io, src_path), - m_expected(expected), - m_actual(actual) - { - } - - // "not equal, expected #{expected.inspect}, but got #{actual.inspect}" - - virtual ~validation_not_equal_error() KS_NOEXCEPT {}; - -protected: - const T& m_expected; - const T& m_actual; -}; - -/** - * Signals validation failure: we required "actual" value to be greater - * than or equal to "min", but it turned out that it's not. - */ -template -class validation_less_than_error: public validation_failed_error { -public: - validation_less_than_error(const T& min, const T& actual, kstream* io, const std::string src_path): - validation_failed_error("not in range", io, src_path), - m_min(min), - m_actual(actual) - { - } - - // "not in range, min #{min.inspect}, but got #{actual.inspect}" - - virtual ~validation_less_than_error() KS_NOEXCEPT {}; - -protected: - const T& m_min; - const T& m_actual; -}; - -/** - * Signals validation failure: we required "actual" value to be less - * than or equal to "max", but it turned out that it's not. - */ -template -class validation_greater_than_error: public validation_failed_error { -public: - validation_greater_than_error(const T& max, const T& actual, kstream* io, const std::string src_path): - validation_failed_error("not in range", io, src_path), - m_max(max), - m_actual(actual) - { - } - - // "not in range, max #{max.inspect}, but got #{actual.inspect}" - - virtual ~validation_greater_than_error() KS_NOEXCEPT {}; - -protected: - const T& m_max; - const T& m_actual; -}; - -/** - * Signals validation failure: we required "actual" value to be from - * the list, but it turned out that it's not. - */ -template -class validation_not_any_of_error: public validation_failed_error { -public: - validation_not_any_of_error(const T& actual, kstream* io, const std::string src_path): - validation_failed_error("not any of the list", io, src_path), - m_actual(actual) - { - } - - // "not any of the list, got #{actual.inspect}" - - virtual ~validation_not_any_of_error() KS_NOEXCEPT {}; - -protected: - const T& m_actual; -}; - -/** - * Signals validation failure: we required "actual" value to match - * the expression, but it turned out that it doesn't. - */ -template -class validation_expr_error: public validation_failed_error { -public: - validation_expr_error(const T& actual, kstream* io, const std::string src_path): - validation_failed_error("not matching the expression", io, src_path), - m_actual(actual) - { - } - - // "not matching the expression, got #{actual.inspect}" - - virtual ~validation_expr_error() KS_NOEXCEPT {}; - -protected: - const T& m_actual; -}; - -} - -#endif diff --git a/third_party/kaitai/kaitaistream.cpp b/third_party/kaitai/kaitaistream.cpp deleted file mode 100644 index d82ddb7e82..0000000000 --- a/third_party/kaitai/kaitaistream.cpp +++ /dev/null @@ -1,689 +0,0 @@ -#include - -#if defined(__APPLE__) -#include -#include -#define bswap_16(x) OSSwapInt16(x) -#define bswap_32(x) OSSwapInt32(x) -#define bswap_64(x) OSSwapInt64(x) -#define __BYTE_ORDER BYTE_ORDER -#define __BIG_ENDIAN BIG_ENDIAN -#define __LITTLE_ENDIAN LITTLE_ENDIAN -#elif defined(_MSC_VER) // !__APPLE__ -#include -#define __LITTLE_ENDIAN 1234 -#define __BIG_ENDIAN 4321 -#define __BYTE_ORDER __LITTLE_ENDIAN -#define bswap_16(x) _byteswap_ushort(x) -#define bswap_32(x) _byteswap_ulong(x) -#define bswap_64(x) _byteswap_uint64(x) -#else // !__APPLE__ or !_MSC_VER -#include -#include -#endif - -#include -#include -#include - -kaitai::kstream::kstream(std::istream* io) { - m_io = io; - init(); -} - -kaitai::kstream::kstream(std::string& data): m_io_str(data) { - m_io = &m_io_str; - init(); -} - -void kaitai::kstream::init() { - exceptions_enable(); - align_to_byte(); -} - -void kaitai::kstream::close() { - // m_io->close(); -} - -void kaitai::kstream::exceptions_enable() const { - m_io->exceptions( - std::istream::eofbit | - std::istream::failbit | - std::istream::badbit - ); -} - -// ======================================================================== -// Stream positioning -// ======================================================================== - -bool kaitai::kstream::is_eof() const { - if (m_bits_left > 0) { - return false; - } - char t; - m_io->exceptions( - std::istream::badbit - ); - m_io->get(t); - if (m_io->eof()) { - m_io->clear(); - exceptions_enable(); - return true; - } else { - m_io->unget(); - exceptions_enable(); - return false; - } -} - -void kaitai::kstream::seek(uint64_t pos) { - m_io->seekg(pos); -} - -uint64_t kaitai::kstream::pos() { - return m_io->tellg(); -} - -uint64_t kaitai::kstream::size() { - std::iostream::pos_type cur_pos = m_io->tellg(); - m_io->seekg(0, std::ios::end); - std::iostream::pos_type len = m_io->tellg(); - m_io->seekg(cur_pos); - return len; -} - -// ======================================================================== -// Integer numbers -// ======================================================================== - -// ------------------------------------------------------------------------ -// Signed -// ------------------------------------------------------------------------ - -int8_t kaitai::kstream::read_s1() { - char t; - m_io->get(t); - return t; -} - -// ........................................................................ -// Big-endian -// ........................................................................ - -int16_t kaitai::kstream::read_s2be() { - int16_t t; - m_io->read(reinterpret_cast(&t), 2); -#if __BYTE_ORDER == __LITTLE_ENDIAN - t = bswap_16(t); -#endif - return t; -} - -int32_t kaitai::kstream::read_s4be() { - int32_t t; - m_io->read(reinterpret_cast(&t), 4); -#if __BYTE_ORDER == __LITTLE_ENDIAN - t = bswap_32(t); -#endif - return t; -} - -int64_t kaitai::kstream::read_s8be() { - int64_t t; - m_io->read(reinterpret_cast(&t), 8); -#if __BYTE_ORDER == __LITTLE_ENDIAN - t = bswap_64(t); -#endif - return t; -} - -// ........................................................................ -// Little-endian -// ........................................................................ - -int16_t kaitai::kstream::read_s2le() { - int16_t t; - m_io->read(reinterpret_cast(&t), 2); -#if __BYTE_ORDER == __BIG_ENDIAN - t = bswap_16(t); -#endif - return t; -} - -int32_t kaitai::kstream::read_s4le() { - int32_t t; - m_io->read(reinterpret_cast(&t), 4); -#if __BYTE_ORDER == __BIG_ENDIAN - t = bswap_32(t); -#endif - return t; -} - -int64_t kaitai::kstream::read_s8le() { - int64_t t; - m_io->read(reinterpret_cast(&t), 8); -#if __BYTE_ORDER == __BIG_ENDIAN - t = bswap_64(t); -#endif - return t; -} - -// ------------------------------------------------------------------------ -// Unsigned -// ------------------------------------------------------------------------ - -uint8_t kaitai::kstream::read_u1() { - char t; - m_io->get(t); - return t; -} - -// ........................................................................ -// Big-endian -// ........................................................................ - -uint16_t kaitai::kstream::read_u2be() { - uint16_t t; - m_io->read(reinterpret_cast(&t), 2); -#if __BYTE_ORDER == __LITTLE_ENDIAN - t = bswap_16(t); -#endif - return t; -} - -uint32_t kaitai::kstream::read_u4be() { - uint32_t t; - m_io->read(reinterpret_cast(&t), 4); -#if __BYTE_ORDER == __LITTLE_ENDIAN - t = bswap_32(t); -#endif - return t; -} - -uint64_t kaitai::kstream::read_u8be() { - uint64_t t; - m_io->read(reinterpret_cast(&t), 8); -#if __BYTE_ORDER == __LITTLE_ENDIAN - t = bswap_64(t); -#endif - return t; -} - -// ........................................................................ -// Little-endian -// ........................................................................ - -uint16_t kaitai::kstream::read_u2le() { - uint16_t t; - m_io->read(reinterpret_cast(&t), 2); -#if __BYTE_ORDER == __BIG_ENDIAN - t = bswap_16(t); -#endif - return t; -} - -uint32_t kaitai::kstream::read_u4le() { - uint32_t t; - m_io->read(reinterpret_cast(&t), 4); -#if __BYTE_ORDER == __BIG_ENDIAN - t = bswap_32(t); -#endif - return t; -} - -uint64_t kaitai::kstream::read_u8le() { - uint64_t t; - m_io->read(reinterpret_cast(&t), 8); -#if __BYTE_ORDER == __BIG_ENDIAN - t = bswap_64(t); -#endif - return t; -} - -// ======================================================================== -// Floating point numbers -// ======================================================================== - -// ........................................................................ -// Big-endian -// ........................................................................ - -float kaitai::kstream::read_f4be() { - uint32_t t; - m_io->read(reinterpret_cast(&t), 4); -#if __BYTE_ORDER == __LITTLE_ENDIAN - t = bswap_32(t); -#endif - return reinterpret_cast(t); -} - -double kaitai::kstream::read_f8be() { - uint64_t t; - m_io->read(reinterpret_cast(&t), 8); -#if __BYTE_ORDER == __LITTLE_ENDIAN - t = bswap_64(t); -#endif - return reinterpret_cast(t); -} - -// ........................................................................ -// Little-endian -// ........................................................................ - -float kaitai::kstream::read_f4le() { - uint32_t t; - m_io->read(reinterpret_cast(&t), 4); -#if __BYTE_ORDER == __BIG_ENDIAN - t = bswap_32(t); -#endif - return reinterpret_cast(t); -} - -double kaitai::kstream::read_f8le() { - uint64_t t; - m_io->read(reinterpret_cast(&t), 8); -#if __BYTE_ORDER == __BIG_ENDIAN - t = bswap_64(t); -#endif - return reinterpret_cast(t); -} - -// ======================================================================== -// Unaligned bit values -// ======================================================================== - -void kaitai::kstream::align_to_byte() { - m_bits_left = 0; - m_bits = 0; -} - -uint64_t kaitai::kstream::read_bits_int_be(int n) { - int bits_needed = n - m_bits_left; - if (bits_needed > 0) { - // 1 bit => 1 byte - // 8 bits => 1 byte - // 9 bits => 2 bytes - int bytes_needed = ((bits_needed - 1) / 8) + 1; - if (bytes_needed > 8) - throw std::runtime_error("read_bits_int: more than 8 bytes requested"); - char buf[8]; - m_io->read(buf, bytes_needed); - for (int i = 0; i < bytes_needed; i++) { - uint8_t b = buf[i]; - m_bits <<= 8; - m_bits |= b; - m_bits_left += 8; - } - } - - // raw mask with required number of 1s, starting from lowest bit - uint64_t mask = get_mask_ones(n); - // shift mask to align with highest bits available in @bits - int shift_bits = m_bits_left - n; - mask <<= shift_bits; - // derive reading result - uint64_t res = (m_bits & mask) >> shift_bits; - // clear top bits that we've just read => AND with 1s - m_bits_left -= n; - mask = get_mask_ones(m_bits_left); - m_bits &= mask; - - return res; -} - -// Deprecated, use read_bits_int_be() instead. -uint64_t kaitai::kstream::read_bits_int(int n) { - return read_bits_int_be(n); -} - -uint64_t kaitai::kstream::read_bits_int_le(int n) { - int bits_needed = n - m_bits_left; - if (bits_needed > 0) { - // 1 bit => 1 byte - // 8 bits => 1 byte - // 9 bits => 2 bytes - int bytes_needed = ((bits_needed - 1) / 8) + 1; - if (bytes_needed > 8) - throw std::runtime_error("read_bits_int_le: more than 8 bytes requested"); - char buf[8]; - m_io->read(buf, bytes_needed); - for (int i = 0; i < bytes_needed; i++) { - uint8_t b = buf[i]; - m_bits |= (static_cast(b) << m_bits_left); - m_bits_left += 8; - } - } - - // raw mask with required number of 1s, starting from lowest bit - uint64_t mask = get_mask_ones(n); - // derive reading result - uint64_t res = m_bits & mask; - // remove bottom bits that we've just read by shifting - m_bits >>= n; - m_bits_left -= n; - - return res; -} - -uint64_t kaitai::kstream::get_mask_ones(int n) { - if (n == 64) { - return 0xFFFFFFFFFFFFFFFF; - } else { - return ((uint64_t) 1 << n) - 1; - } -} - -// ======================================================================== -// Byte arrays -// ======================================================================== - -std::string kaitai::kstream::read_bytes(std::streamsize len) { - std::vector result(len); - - // NOTE: streamsize type is signed, negative values are only *supposed* to not be used. - // http://en.cppreference.com/w/cpp/io/streamsize - if (len < 0) { - throw std::runtime_error("read_bytes: requested a negative amount"); - } - - if (len > 0) { - m_io->read(&result[0], len); - } - - return std::string(result.begin(), result.end()); -} - -std::string kaitai::kstream::read_bytes_full() { - std::iostream::pos_type p1 = m_io->tellg(); - m_io->seekg(0, std::ios::end); - std::iostream::pos_type p2 = m_io->tellg(); - size_t len = p2 - p1; - - // Note: this requires a std::string to be backed with a - // contiguous buffer. Officially, it's a only requirement since - // C++11 (C++98 and C++03 didn't have this requirement), but all - // major implementations had contiguous buffers anyway. - std::string result(len, ' '); - m_io->seekg(p1); - m_io->read(&result[0], len); - - return result; -} - -std::string kaitai::kstream::read_bytes_term(char term, bool include, bool consume, bool eos_error) { - std::string result; - std::getline(*m_io, result, term); - if (m_io->eof()) { - // encountered EOF - if (eos_error) { - throw std::runtime_error("read_bytes_term: encountered EOF"); - } - } else { - // encountered terminator - if (include) - result.push_back(term); - if (!consume) - m_io->unget(); - } - return result; -} - -std::string kaitai::kstream::ensure_fixed_contents(std::string expected) { - std::string actual = read_bytes(expected.length()); - - if (actual != expected) { - // NOTE: I think printing it outright is not best idea, it could contain non-ascii charactes like backspace and beeps and whatnot. It would be better to print hexlified version, and also to redirect it to stderr. - throw std::runtime_error("ensure_fixed_contents: actual data does not match expected data"); - } - - return actual; -} - -std::string kaitai::kstream::bytes_strip_right(std::string src, char pad_byte) { - std::size_t new_len = src.length(); - - while (new_len > 0 && src[new_len - 1] == pad_byte) - new_len--; - - return src.substr(0, new_len); -} - -std::string kaitai::kstream::bytes_terminate(std::string src, char term, bool include) { - std::size_t new_len = 0; - std::size_t max_len = src.length(); - - while (new_len < max_len && src[new_len] != term) - new_len++; - - if (include && new_len < max_len) - new_len++; - - return src.substr(0, new_len); -} - -// ======================================================================== -// Byte array processing -// ======================================================================== - -std::string kaitai::kstream::process_xor_one(std::string data, uint8_t key) { - size_t len = data.length(); - std::string result(len, ' '); - - for (size_t i = 0; i < len; i++) - result[i] = data[i] ^ key; - - return result; -} - -std::string kaitai::kstream::process_xor_many(std::string data, std::string key) { - size_t len = data.length(); - size_t kl = key.length(); - std::string result(len, ' '); - - size_t ki = 0; - for (size_t i = 0; i < len; i++) { - result[i] = data[i] ^ key[ki]; - ki++; - if (ki >= kl) - ki = 0; - } - - return result; -} - -std::string kaitai::kstream::process_rotate_left(std::string data, int amount) { - size_t len = data.length(); - std::string result(len, ' '); - - for (size_t i = 0; i < len; i++) { - uint8_t bits = data[i]; - result[i] = (bits << amount) | (bits >> (8 - amount)); - } - - return result; -} - -#ifdef KS_ZLIB -#include - -std::string kaitai::kstream::process_zlib(std::string data) { - int ret; - - unsigned char *src_ptr = reinterpret_cast(&data[0]); - std::stringstream dst_strm; - - z_stream strm; - strm.zalloc = Z_NULL; - strm.zfree = Z_NULL; - strm.opaque = Z_NULL; - - ret = inflateInit(&strm); - if (ret != Z_OK) - throw std::runtime_error("process_zlib: inflateInit error"); - - strm.next_in = src_ptr; - strm.avail_in = data.length(); - - unsigned char outbuffer[ZLIB_BUF_SIZE]; - std::string outstring; - - // get the decompressed bytes blockwise using repeated calls to inflate - do { - strm.next_out = reinterpret_cast(outbuffer); - strm.avail_out = sizeof(outbuffer); - - ret = inflate(&strm, 0); - - if (outstring.size() < strm.total_out) - outstring.append(reinterpret_cast(outbuffer), strm.total_out - outstring.size()); - } while (ret == Z_OK); - - if (ret != Z_STREAM_END) { // an error occurred that was not EOF - std::ostringstream exc_msg; - exc_msg << "process_zlib: error #" << ret << "): " << strm.msg; - throw std::runtime_error(exc_msg.str()); - } - - if (inflateEnd(&strm) != Z_OK) - throw std::runtime_error("process_zlib: inflateEnd error"); - - return outstring; -} -#endif - -// ======================================================================== -// Misc utility methods -// ======================================================================== - -int kaitai::kstream::mod(int a, int b) { - if (b <= 0) - throw std::invalid_argument("mod: divisor b <= 0"); - int r = a % b; - if (r < 0) - r += b; - return r; -} - -#include -std::string kaitai::kstream::to_string(int val) { - // if int is 32 bits, "-2147483648" is the longest string representation - // => 11 chars + zero => 12 chars - // if int is 64 bits, "-9223372036854775808" is the longest - // => 20 chars + zero => 21 chars - char buf[25]; - int got_len = snprintf(buf, sizeof(buf), "%d", val); - - // should never happen, but check nonetheless - if (got_len > sizeof(buf)) - throw std::invalid_argument("to_string: integer is longer than string buffer"); - - return std::string(buf); -} - -#include -std::string kaitai::kstream::reverse(std::string val) { - std::reverse(val.begin(), val.end()); - - return val; -} - -uint8_t kaitai::kstream::byte_array_min(const std::string val) { - uint8_t min = 0xff; // UINT8_MAX - std::string::const_iterator end = val.end(); - for (std::string::const_iterator it = val.begin(); it != end; ++it) { - uint8_t cur = static_cast(*it); - if (cur < min) { - min = cur; - } - } - return min; -} - -uint8_t kaitai::kstream::byte_array_max(const std::string val) { - uint8_t max = 0; // UINT8_MIN - std::string::const_iterator end = val.end(); - for (std::string::const_iterator it = val.begin(); it != end; ++it) { - uint8_t cur = static_cast(*it); - if (cur > max) { - max = cur; - } - } - return max; -} - -// ======================================================================== -// Other internal methods -// ======================================================================== - -#ifndef KS_STR_DEFAULT_ENCODING -#define KS_STR_DEFAULT_ENCODING "UTF-8" -#endif - -#ifdef KS_STR_ENCODING_ICONV - -#include -#include -#include - -std::string kaitai::kstream::bytes_to_str(std::string src, std::string src_enc) { - iconv_t cd = iconv_open(KS_STR_DEFAULT_ENCODING, src_enc.c_str()); - - if (cd == (iconv_t) -1) { - if (errno == EINVAL) { - throw std::runtime_error("bytes_to_str: invalid encoding pair conversion requested"); - } else { - throw std::runtime_error("bytes_to_str: error opening iconv"); - } - } - - size_t src_len = src.length(); - size_t src_left = src_len; - - // Start with a buffer length of double the source length. - size_t dst_len = src_len * 2; - std::string dst(dst_len, ' '); - size_t dst_left = dst_len; - - char *src_ptr = &src[0]; - char *dst_ptr = &dst[0]; - - while (true) { - size_t res = iconv(cd, &src_ptr, &src_left, &dst_ptr, &dst_left); - - if (res == (size_t) -1) { - if (errno == E2BIG) { - // dst buffer is not enough to accomodate whole string - // enlarge the buffer and try again - size_t dst_used = dst_len - dst_left; - dst_left += dst_len; - dst_len += dst_len; - dst.resize(dst_len); - - // dst.resize might have allocated destination buffer in another area - // of memory, thus our previous pointer "dst" will be invalid; re-point - // it using "dst_used". - dst_ptr = &dst[dst_used]; - } else { - throw std::runtime_error("bytes_to_str: iconv error"); - } - } else { - // conversion successful - dst.resize(dst_len - dst_left); - break; - } - } - - if (iconv_close(cd) != 0) { - throw std::runtime_error("bytes_to_str: iconv close error"); - } - - return dst; -} -#elif defined(KS_STR_ENCODING_NONE) -std::string kaitai::kstream::bytes_to_str(std::string src, std::string src_enc) { - return src; -} -#else -#error Need to decide how to handle strings: please define one of: KS_STR_ENCODING_ICONV, KS_STR_ENCODING_NONE -#endif diff --git a/third_party/kaitai/kaitaistream.h b/third_party/kaitai/kaitaistream.h deleted file mode 100644 index e7f4c6ce34..0000000000 --- a/third_party/kaitai/kaitaistream.h +++ /dev/null @@ -1,268 +0,0 @@ -#ifndef KAITAI_STREAM_H -#define KAITAI_STREAM_H - -// Kaitai Struct runtime API version: x.y.z = 'xxxyyyzzz' decimal -#define KAITAI_STRUCT_VERSION 9000L - -#include -#include -#include -#include - -namespace kaitai { - -/** - * Kaitai Stream class (kaitai::kstream) is an implementation of - * Kaitai Struct stream API - * for C++/STL. It's implemented as a wrapper over generic STL std::istream. - * - * It provides a wide variety of simple methods to read (parse) binary - * representations of primitive types, such as integer and floating - * point numbers, byte arrays and strings, and also provides stream - * positioning / navigation methods with unified cross-language and - * cross-toolkit semantics. - * - * Typically, end users won't access Kaitai Stream class manually, but would - * describe a binary structure format using .ksy language and then would use - * Kaitai Struct compiler to generate source code in desired target language. - * That code, in turn, would use this class and API to do the actual parsing - * job. - */ -class kstream { -public: - /** - * Constructs new Kaitai Stream object, wrapping a given std::istream. - * \param io istream object to use for this Kaitai Stream - */ - kstream(std::istream* io); - - /** - * Constructs new Kaitai Stream object, wrapping a given in-memory data - * buffer. - * \param data data buffer to use for this Kaitai Stream - */ - kstream(std::string& data); - - void close(); - - /** @name Stream positioning */ - //@{ - /** - * Check if stream pointer is at the end of stream. Note that the semantics - * are different from traditional STL semantics: one does *not* need to do a - * read (which will fail) after the actual end of the stream to trigger EOF - * flag, which can be accessed after that read. It is sufficient to just be - * at the end of the stream for this method to return true. - * \return "true" if we are located at the end of the stream. - */ - bool is_eof() const; - - /** - * Set stream pointer to designated position. - * \param pos new position (offset in bytes from the beginning of the stream) - */ - void seek(uint64_t pos); - - /** - * Get current position of a stream pointer. - * \return pointer position, number of bytes from the beginning of the stream - */ - uint64_t pos(); - - /** - * Get total size of the stream in bytes. - * \return size of the stream in bytes - */ - uint64_t size(); - //@} - - /** @name Integer numbers */ - //@{ - - // ------------------------------------------------------------------------ - // Signed - // ------------------------------------------------------------------------ - - int8_t read_s1(); - - // ........................................................................ - // Big-endian - // ........................................................................ - - int16_t read_s2be(); - int32_t read_s4be(); - int64_t read_s8be(); - - // ........................................................................ - // Little-endian - // ........................................................................ - - int16_t read_s2le(); - int32_t read_s4le(); - int64_t read_s8le(); - - // ------------------------------------------------------------------------ - // Unsigned - // ------------------------------------------------------------------------ - - uint8_t read_u1(); - - // ........................................................................ - // Big-endian - // ........................................................................ - - uint16_t read_u2be(); - uint32_t read_u4be(); - uint64_t read_u8be(); - - // ........................................................................ - // Little-endian - // ........................................................................ - - uint16_t read_u2le(); - uint32_t read_u4le(); - uint64_t read_u8le(); - - //@} - - /** @name Floating point numbers */ - //@{ - - // ........................................................................ - // Big-endian - // ........................................................................ - - float read_f4be(); - double read_f8be(); - - // ........................................................................ - // Little-endian - // ........................................................................ - - float read_f4le(); - double read_f8le(); - - //@} - - /** @name Unaligned bit values */ - //@{ - - void align_to_byte(); - uint64_t read_bits_int_be(int n); - uint64_t read_bits_int(int n); - uint64_t read_bits_int_le(int n); - - //@} - - /** @name Byte arrays */ - //@{ - - std::string read_bytes(std::streamsize len); - std::string read_bytes_full(); - std::string read_bytes_term(char term, bool include, bool consume, bool eos_error); - std::string ensure_fixed_contents(std::string expected); - - static std::string bytes_strip_right(std::string src, char pad_byte); - static std::string bytes_terminate(std::string src, char term, bool include); - static std::string bytes_to_str(std::string src, std::string src_enc); - - //@} - - /** @name Byte array processing */ - //@{ - - /** - * Performs a XOR processing with given data, XORing every byte of input with a single - * given value. - * @param data data to process - * @param key value to XOR with - * @return processed data - */ - static std::string process_xor_one(std::string data, uint8_t key); - - /** - * Performs a XOR processing with given data, XORing every byte of input with a key - * array, repeating key array many times, if necessary (i.e. if data array is longer - * than key array). - * @param data data to process - * @param key array of bytes to XOR with - * @return processed data - */ - static std::string process_xor_many(std::string data, std::string key); - - /** - * Performs a circular left rotation shift for a given buffer by a given amount of bits, - * using groups of 1 bytes each time. Right circular rotation should be performed - * using this procedure with corrected amount. - * @param data source data to process - * @param amount number of bits to shift by - * @return copy of source array with requested shift applied - */ - static std::string process_rotate_left(std::string data, int amount); - -#ifdef KS_ZLIB - /** - * Performs an unpacking ("inflation") of zlib-compressed data with usual zlib headers. - * @param data data to unpack - * @return unpacked data - * @throws IOException - */ - static std::string process_zlib(std::string data); -#endif - - //@} - - /** - * Performs modulo operation between two integers: dividend `a` - * and divisor `b`. Divisor `b` is expected to be positive. The - * result is always 0 <= x <= b - 1. - */ - static int mod(int a, int b); - - /** - * Converts given integer `val` to a decimal string representation. - * Should be used in place of std::to_string() (which is available only - * since C++11) in older C++ implementations. - */ - static std::string to_string(int val); - - /** - * Reverses given string `val`, so that the first character becomes the - * last and the last one becomes the first. This should be used to avoid - * the need of local variables at the caller. - */ - static std::string reverse(std::string val); - - /** - * Finds the minimal byte in a byte array, treating bytes as - * unsigned values. - * @param val byte array to scan - * @return minimal byte in byte array as integer - */ - static uint8_t byte_array_min(const std::string val); - - /** - * Finds the maximal byte in a byte array, treating bytes as - * unsigned values. - * @param val byte array to scan - * @return maximal byte in byte array as integer - */ - static uint8_t byte_array_max(const std::string val); - -private: - std::istream* m_io; - std::istringstream m_io_str; - int m_bits_left; - uint64_t m_bits; - - void init(); - void exceptions_enable() const; - - static uint64_t get_mask_ones(int n); - - static const int ZLIB_BUF_SIZE = 128 * 1024; -}; - -} - -#endif diff --git a/third_party/kaitai/kaitaistruct.h b/third_party/kaitai/kaitaistruct.h deleted file mode 100644 index 8172ede6c9..0000000000 --- a/third_party/kaitai/kaitaistruct.h +++ /dev/null @@ -1,20 +0,0 @@ -#ifndef KAITAI_STRUCT_H -#define KAITAI_STRUCT_H - -#include - -namespace kaitai { - -class kstruct { -public: - kstruct(kstream *_io) { m__io = _io; } - virtual ~kstruct() {} -protected: - kstream *m__io; -public: - kstream *_io() { return m__io; } -}; - -} - -#endif diff --git a/third_party/libyuv/.gitignore b/third_party/libyuv/.gitignore deleted file mode 100644 index 450712e47d..0000000000 --- a/third_party/libyuv/.gitignore +++ /dev/null @@ -1 +0,0 @@ -libyuv/ diff --git a/third_party/libyuv/Darwin/lib/libyuv.a b/third_party/libyuv/Darwin/lib/libyuv.a deleted file mode 100644 index b72979ef19..0000000000 --- a/third_party/libyuv/Darwin/lib/libyuv.a +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:497e01c39e1629a89afa730341fe066c2e926966c5f050003e7fde2ce46d9da3 -size 863648 diff --git a/third_party/libyuv/LICENSE b/third_party/libyuv/LICENSE deleted file mode 100644 index c911747a6b..0000000000 --- a/third_party/libyuv/LICENSE +++ /dev/null @@ -1,29 +0,0 @@ -Copyright 2011 The LibYuv Project Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the - distribution. - - * Neither the name of Google 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/third_party/libyuv/aarch64 b/third_party/libyuv/aarch64 deleted file mode 120000 index 062c65e8d9..0000000000 --- a/third_party/libyuv/aarch64 +++ /dev/null @@ -1 +0,0 @@ -larch64/ \ No newline at end of file diff --git a/third_party/libyuv/build.sh b/third_party/libyuv/build.sh deleted file mode 100755 index b960f60ef5..0000000000 --- a/third_party/libyuv/build.sh +++ /dev/null @@ -1,39 +0,0 @@ -#!/usr/bin/env bash -set -e - -DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null && pwd)" - -ARCHNAME=$(uname -m) -if [ -f /TICI ]; then - ARCHNAME="larch64" -fi - -if [[ "$OSTYPE" == "darwin"* ]]; then - ARCHNAME="Darwin" -fi - -cd $DIR -if [ ! -d libyuv ]; then - git clone --single-branch https://chromium.googlesource.com/libyuv/libyuv -fi - -cd libyuv -git checkout 4a14cb2e81235ecd656e799aecaaf139db8ce4a2 - -# build -cmake . -make -j$(nproc) - -INSTALL_DIR="$DIR/$ARCHNAME" -rm -rf $INSTALL_DIR -mkdir -p $INSTALL_DIR - -rm -rf $DIR/include -mkdir -p $INSTALL_DIR/lib -cp $DIR/libyuv/libyuv.a $INSTALL_DIR/lib -cp -r $DIR/libyuv/include $DIR - -## To create universal binary on Darwin: -## ``` -## lipo -create -output Darwin/libyuv.a path-to-x64/libyuv.a path-to-arm64/libyuv.a -## ``` diff --git a/third_party/libyuv/include/libyuv.h b/third_party/libyuv/include/libyuv.h deleted file mode 100644 index aeffd5ef7a..0000000000 --- a/third_party/libyuv/include/libyuv.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2011 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef INCLUDE_LIBYUV_H_ -#define INCLUDE_LIBYUV_H_ - -#include "libyuv/basic_types.h" -#include "libyuv/compare.h" -#include "libyuv/convert.h" -#include "libyuv/convert_argb.h" -#include "libyuv/convert_from.h" -#include "libyuv/convert_from_argb.h" -#include "libyuv/cpu_id.h" -#include "libyuv/mjpeg_decoder.h" -#include "libyuv/planar_functions.h" -#include "libyuv/rotate.h" -#include "libyuv/rotate_argb.h" -#include "libyuv/row.h" -#include "libyuv/scale.h" -#include "libyuv/scale_argb.h" -#include "libyuv/scale_row.h" -#include "libyuv/version.h" -#include "libyuv/video_common.h" - -#endif // INCLUDE_LIBYUV_H_ diff --git a/third_party/libyuv/include/libyuv/basic_types.h b/third_party/libyuv/include/libyuv/basic_types.h deleted file mode 100644 index 5b760ee0d4..0000000000 --- a/third_party/libyuv/include/libyuv/basic_types.h +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright 2011 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef INCLUDE_LIBYUV_BASIC_TYPES_H_ -#define INCLUDE_LIBYUV_BASIC_TYPES_H_ - -#include // for NULL, size_t - -#if defined(_MSC_VER) && (_MSC_VER < 1600) -#include // for uintptr_t on x86 -#else -#include // for uintptr_t -#endif - -#ifndef GG_LONGLONG -#ifndef INT_TYPES_DEFINED -#define INT_TYPES_DEFINED -#ifdef COMPILER_MSVC -typedef unsigned __int64 uint64; -typedef __int64 int64; -#ifndef INT64_C -#define INT64_C(x) x ## I64 -#endif -#ifndef UINT64_C -#define UINT64_C(x) x ## UI64 -#endif -#define INT64_F "I64" -#else // COMPILER_MSVC -#if defined(__LP64__) && !defined(__OpenBSD__) && !defined(__APPLE__) -typedef unsigned long uint64; // NOLINT -typedef long int64; // NOLINT -#ifndef INT64_C -#define INT64_C(x) x ## L -#endif -#ifndef UINT64_C -#define UINT64_C(x) x ## UL -#endif -#define INT64_F "l" -#else // defined(__LP64__) && !defined(__OpenBSD__) && !defined(__APPLE__) -typedef unsigned long long uint64; // NOLINT -typedef long long int64; // NOLINT -#ifndef INT64_C -#define INT64_C(x) x ## LL -#endif -#ifndef UINT64_C -#define UINT64_C(x) x ## ULL -#endif -#define INT64_F "ll" -#endif // __LP64__ -#endif // COMPILER_MSVC -typedef unsigned int uint32; -typedef int int32; -typedef unsigned short uint16; // NOLINT -typedef short int16; // NOLINT -typedef unsigned char uint8; -typedef signed char int8; -#endif // INT_TYPES_DEFINED -#endif // GG_LONGLONG - -// Detect compiler is for x86 or x64. -#if defined(__x86_64__) || defined(_M_X64) || \ - defined(__i386__) || defined(_M_IX86) -#define CPU_X86 1 -#endif -// Detect compiler is for ARM. -#if defined(__arm__) || defined(_M_ARM) -#define CPU_ARM 1 -#endif - -#ifndef ALIGNP -#ifdef __cplusplus -#define ALIGNP(p, t) \ - (reinterpret_cast(((reinterpret_cast(p) + \ - ((t) - 1)) & ~((t) - 1)))) -#else -#define ALIGNP(p, t) \ - ((uint8*)((((uintptr_t)(p) + ((t) - 1)) & ~((t) - 1)))) /* NOLINT */ -#endif -#endif - -#if !defined(LIBYUV_API) -#if defined(_WIN32) || defined(__CYGWIN__) -#if defined(LIBYUV_BUILDING_SHARED_LIBRARY) -#define LIBYUV_API __declspec(dllexport) -#elif defined(LIBYUV_USING_SHARED_LIBRARY) -#define LIBYUV_API __declspec(dllimport) -#else -#define LIBYUV_API -#endif // LIBYUV_BUILDING_SHARED_LIBRARY -#elif defined(__GNUC__) && (__GNUC__ >= 4) && !defined(__APPLE__) && \ - (defined(LIBYUV_BUILDING_SHARED_LIBRARY) || \ - defined(LIBYUV_USING_SHARED_LIBRARY)) -#define LIBYUV_API __attribute__ ((visibility ("default"))) -#else -#define LIBYUV_API -#endif // __GNUC__ -#endif // LIBYUV_API - -#define LIBYUV_BOOL int -#define LIBYUV_FALSE 0 -#define LIBYUV_TRUE 1 - -// Visual C x86 or GCC little endian. -#if defined(__x86_64__) || defined(_M_X64) || \ - defined(__i386__) || defined(_M_IX86) || \ - defined(__arm__) || defined(_M_ARM) || \ - (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) -#define LIBYUV_LITTLE_ENDIAN -#endif - -#endif // INCLUDE_LIBYUV_BASIC_TYPES_H_ diff --git a/third_party/libyuv/include/libyuv/compare.h b/third_party/libyuv/include/libyuv/compare.h deleted file mode 100644 index 550712de6e..0000000000 --- a/third_party/libyuv/include/libyuv/compare.h +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2011 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef INCLUDE_LIBYUV_COMPARE_H_ -#define INCLUDE_LIBYUV_COMPARE_H_ - -#include "libyuv/basic_types.h" - -#ifdef __cplusplus -namespace libyuv { -extern "C" { -#endif - -// Compute a hash for specified memory. Seed of 5381 recommended. -LIBYUV_API -uint32 HashDjb2(const uint8* src, uint64 count, uint32 seed); - -// Scan an opaque argb image and return fourcc based on alpha offset. -// Returns FOURCC_ARGB, FOURCC_BGRA, or 0 if unknown. -LIBYUV_API -uint32 ARGBDetect(const uint8* argb, int stride_argb, int width, int height); - -// Sum Square Error - used to compute Mean Square Error or PSNR. -LIBYUV_API -uint64 ComputeSumSquareError(const uint8* src_a, - const uint8* src_b, int count); - -LIBYUV_API -uint64 ComputeSumSquareErrorPlane(const uint8* src_a, int stride_a, - const uint8* src_b, int stride_b, - int width, int height); - -static const int kMaxPsnr = 128; - -LIBYUV_API -double SumSquareErrorToPsnr(uint64 sse, uint64 count); - -LIBYUV_API -double CalcFramePsnr(const uint8* src_a, int stride_a, - const uint8* src_b, int stride_b, - int width, int height); - -LIBYUV_API -double I420Psnr(const uint8* src_y_a, int stride_y_a, - const uint8* src_u_a, int stride_u_a, - const uint8* src_v_a, int stride_v_a, - const uint8* src_y_b, int stride_y_b, - const uint8* src_u_b, int stride_u_b, - const uint8* src_v_b, int stride_v_b, - int width, int height); - -LIBYUV_API -double CalcFrameSsim(const uint8* src_a, int stride_a, - const uint8* src_b, int stride_b, - int width, int height); - -LIBYUV_API -double I420Ssim(const uint8* src_y_a, int stride_y_a, - const uint8* src_u_a, int stride_u_a, - const uint8* src_v_a, int stride_v_a, - const uint8* src_y_b, int stride_y_b, - const uint8* src_u_b, int stride_u_b, - const uint8* src_v_b, int stride_v_b, - int width, int height); - -#ifdef __cplusplus -} // extern "C" -} // namespace libyuv -#endif - -#endif // INCLUDE_LIBYUV_COMPARE_H_ diff --git a/third_party/libyuv/include/libyuv/compare_row.h b/third_party/libyuv/include/libyuv/compare_row.h deleted file mode 100644 index 781cad3e65..0000000000 --- a/third_party/libyuv/include/libyuv/compare_row.h +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright 2013 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef INCLUDE_LIBYUV_COMPARE_ROW_H_ -#define INCLUDE_LIBYUV_COMPARE_ROW_H_ - -#include "libyuv/basic_types.h" - -#ifdef __cplusplus -namespace libyuv { -extern "C" { -#endif - -#if defined(__pnacl__) || defined(__CLR_VER) || \ - (defined(__i386__) && !defined(__SSE2__)) -#define LIBYUV_DISABLE_X86 -#endif -// MemorySanitizer does not support assembly code yet. http://crbug.com/344505 -#if defined(__has_feature) -#if __has_feature(memory_sanitizer) -#define LIBYUV_DISABLE_X86 -#endif -#endif - -// Visual C 2012 required for AVX2. -#if defined(_M_IX86) && !defined(__clang__) && \ - defined(_MSC_VER) && _MSC_VER >= 1700 -#define VISUALC_HAS_AVX2 1 -#endif // VisualStudio >= 2012 - -// clang >= 3.4.0 required for AVX2. -#if defined(__clang__) && (defined(__x86_64__) || defined(__i386__)) -#if (__clang_major__ > 3) || (__clang_major__ == 3 && (__clang_minor__ >= 4)) -#define CLANG_HAS_AVX2 1 -#endif // clang >= 3.4 -#endif // __clang__ - -#if !defined(LIBYUV_DISABLE_X86) && \ - defined(_M_IX86) && (defined(VISUALC_HAS_AVX2) || defined(CLANG_HAS_AVX2)) -#define HAS_HASHDJB2_AVX2 -#endif - -// The following are available for Visual C and GCC: -#if !defined(LIBYUV_DISABLE_X86) && \ - (defined(__x86_64__) || (defined(__i386__) || defined(_M_IX86))) -#define HAS_HASHDJB2_SSE41 -#define HAS_SUMSQUAREERROR_SSE2 -#endif - -// The following are available for Visual C and clangcl 32 bit: -#if !defined(LIBYUV_DISABLE_X86) && defined(_M_IX86) && \ - (defined(VISUALC_HAS_AVX2) || defined(CLANG_HAS_AVX2)) -#define HAS_HASHDJB2_AVX2 -#define HAS_SUMSQUAREERROR_AVX2 -#endif - -// The following are available for Neon: -#if !defined(LIBYUV_DISABLE_NEON) && \ - (defined(__ARM_NEON__) || defined(LIBYUV_NEON) || defined(__aarch64__)) -#define HAS_SUMSQUAREERROR_NEON -#endif - -uint32 SumSquareError_C(const uint8* src_a, const uint8* src_b, int count); -uint32 SumSquareError_SSE2(const uint8* src_a, const uint8* src_b, int count); -uint32 SumSquareError_AVX2(const uint8* src_a, const uint8* src_b, int count); -uint32 SumSquareError_NEON(const uint8* src_a, const uint8* src_b, int count); - -uint32 HashDjb2_C(const uint8* src, int count, uint32 seed); -uint32 HashDjb2_SSE41(const uint8* src, int count, uint32 seed); -uint32 HashDjb2_AVX2(const uint8* src, int count, uint32 seed); - -#ifdef __cplusplus -} // extern "C" -} // namespace libyuv -#endif - -#endif // INCLUDE_LIBYUV_COMPARE_ROW_H_ diff --git a/third_party/libyuv/include/libyuv/convert.h b/third_party/libyuv/include/libyuv/convert.h deleted file mode 100644 index d44485847b..0000000000 --- a/third_party/libyuv/include/libyuv/convert.h +++ /dev/null @@ -1,259 +0,0 @@ -/* - * Copyright 2011 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef INCLUDE_LIBYUV_CONVERT_H_ -#define INCLUDE_LIBYUV_CONVERT_H_ - -#include "libyuv/basic_types.h" - -#include "libyuv/rotate.h" // For enum RotationMode. - -// TODO(fbarchard): fix WebRTC source to include following libyuv headers: -#include "libyuv/convert_argb.h" // For WebRTC I420ToARGB. b/620 -#include "libyuv/convert_from.h" // For WebRTC ConvertFromI420. b/620 -#include "libyuv/planar_functions.h" // For WebRTC I420Rect, CopyPlane. b/618 - -#ifdef __cplusplus -namespace libyuv { -extern "C" { -#endif - -// Convert I444 to I420. -LIBYUV_API -int I444ToI420(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Convert I422 to I420. -LIBYUV_API -int I422ToI420(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Convert I411 to I420. -LIBYUV_API -int I411ToI420(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Copy I420 to I420. -#define I420ToI420 I420Copy -LIBYUV_API -int I420Copy(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Convert I400 (grey) to I420. -LIBYUV_API -int I400ToI420(const uint8* src_y, int src_stride_y, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -#define J400ToJ420 I400ToI420 - -// Convert NV12 to I420. -LIBYUV_API -int NV12ToI420(const uint8* src_y, int src_stride_y, - const uint8* src_uv, int src_stride_uv, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Convert NV21 to I420. -LIBYUV_API -int NV21ToI420(const uint8* src_y, int src_stride_y, - const uint8* src_vu, int src_stride_vu, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Convert YUY2 to I420. -LIBYUV_API -int YUY2ToI420(const uint8* src_yuy2, int src_stride_yuy2, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Convert UYVY to I420. -LIBYUV_API -int UYVYToI420(const uint8* src_uyvy, int src_stride_uyvy, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Convert M420 to I420. -LIBYUV_API -int M420ToI420(const uint8* src_m420, int src_stride_m420, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Convert Android420 to I420. -LIBYUV_API -int Android420ToI420(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - int pixel_stride_uv, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// ARGB little endian (bgra in memory) to I420. -LIBYUV_API -int ARGBToI420(const uint8* src_frame, int src_stride_frame, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// BGRA little endian (argb in memory) to I420. -LIBYUV_API -int BGRAToI420(const uint8* src_frame, int src_stride_frame, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// ABGR little endian (rgba in memory) to I420. -LIBYUV_API -int ABGRToI420(const uint8* src_frame, int src_stride_frame, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// RGBA little endian (abgr in memory) to I420. -LIBYUV_API -int RGBAToI420(const uint8* src_frame, int src_stride_frame, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// RGB little endian (bgr in memory) to I420. -LIBYUV_API -int RGB24ToI420(const uint8* src_frame, int src_stride_frame, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// RGB big endian (rgb in memory) to I420. -LIBYUV_API -int RAWToI420(const uint8* src_frame, int src_stride_frame, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// RGB16 (RGBP fourcc) little endian to I420. -LIBYUV_API -int RGB565ToI420(const uint8* src_frame, int src_stride_frame, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// RGB15 (RGBO fourcc) little endian to I420. -LIBYUV_API -int ARGB1555ToI420(const uint8* src_frame, int src_stride_frame, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// RGB12 (R444 fourcc) little endian to I420. -LIBYUV_API -int ARGB4444ToI420(const uint8* src_frame, int src_stride_frame, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -#ifdef HAVE_JPEG -// src_width/height provided by capture. -// dst_width/height for clipping determine final size. -LIBYUV_API -int MJPGToI420(const uint8* sample, size_t sample_size, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int src_width, int src_height, - int dst_width, int dst_height); - -// Query size of MJPG in pixels. -LIBYUV_API -int MJPGSize(const uint8* sample, size_t sample_size, - int* width, int* height); -#endif - -// Convert camera sample to I420 with cropping, rotation and vertical flip. -// "src_size" is needed to parse MJPG. -// "dst_stride_y" number of bytes in a row of the dst_y plane. -// Normally this would be the same as dst_width, with recommended alignment -// to 16 bytes for better efficiency. -// If rotation of 90 or 270 is used, stride is affected. The caller should -// allocate the I420 buffer according to rotation. -// "dst_stride_u" number of bytes in a row of the dst_u plane. -// Normally this would be the same as (dst_width + 1) / 2, with -// recommended alignment to 16 bytes for better efficiency. -// If rotation of 90 or 270 is used, stride is affected. -// "crop_x" and "crop_y" are starting position for cropping. -// To center, crop_x = (src_width - dst_width) / 2 -// crop_y = (src_height - dst_height) / 2 -// "src_width" / "src_height" is size of src_frame in pixels. -// "src_height" can be negative indicating a vertically flipped image source. -// "crop_width" / "crop_height" is the size to crop the src to. -// Must be less than or equal to src_width/src_height -// Cropping parameters are pre-rotation. -// "rotation" can be 0, 90, 180 or 270. -// "format" is a fourcc. ie 'I420', 'YUY2' -// Returns 0 for successful; -1 for invalid parameter. Non-zero for failure. -LIBYUV_API -int ConvertToI420(const uint8* src_frame, size_t src_size, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int crop_x, int crop_y, - int src_width, int src_height, - int crop_width, int crop_height, - enum RotationMode rotation, - uint32 format); - -#ifdef __cplusplus -} // extern "C" -} // namespace libyuv -#endif - -#endif // INCLUDE_LIBYUV_CONVERT_H_ diff --git a/third_party/libyuv/include/libyuv/convert_argb.h b/third_party/libyuv/include/libyuv/convert_argb.h deleted file mode 100644 index dc03ac8d5d..0000000000 --- a/third_party/libyuv/include/libyuv/convert_argb.h +++ /dev/null @@ -1,319 +0,0 @@ -/* - * Copyright 2012 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef INCLUDE_LIBYUV_CONVERT_ARGB_H_ -#define INCLUDE_LIBYUV_CONVERT_ARGB_H_ - -#include "libyuv/basic_types.h" - -#include "libyuv/rotate.h" // For enum RotationMode. - -// TODO(fbarchard): This set of functions should exactly match convert.h -// TODO(fbarchard): Add tests. Create random content of right size and convert -// with C vs Opt and or to I420 and compare. -// TODO(fbarchard): Some of these functions lack parameter setting. - -#ifdef __cplusplus -namespace libyuv { -extern "C" { -#endif - -// Alias. -#define ARGBToARGB ARGBCopy - -// Copy ARGB to ARGB. -LIBYUV_API -int ARGBCopy(const uint8* src_argb, int src_stride_argb, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Convert I420 to ARGB. -LIBYUV_API -int I420ToARGB(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Duplicate prototype for function in convert_from.h for remoting. -LIBYUV_API -int I420ToABGR(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Convert I422 to ARGB. -LIBYUV_API -int I422ToARGB(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Convert I444 to ARGB. -LIBYUV_API -int I444ToARGB(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Convert J444 to ARGB. -LIBYUV_API -int J444ToARGB(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Convert I444 to ABGR. -LIBYUV_API -int I444ToABGR(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_abgr, int dst_stride_abgr, - int width, int height); - -// Convert I411 to ARGB. -LIBYUV_API -int I411ToARGB(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Convert I420 with Alpha to preattenuated ARGB. -LIBYUV_API -int I420AlphaToARGB(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - const uint8* src_a, int src_stride_a, - uint8* dst_argb, int dst_stride_argb, - int width, int height, int attenuate); - -// Convert I420 with Alpha to preattenuated ABGR. -LIBYUV_API -int I420AlphaToABGR(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - const uint8* src_a, int src_stride_a, - uint8* dst_abgr, int dst_stride_abgr, - int width, int height, int attenuate); - -// Convert I400 (grey) to ARGB. Reverse of ARGBToI400. -LIBYUV_API -int I400ToARGB(const uint8* src_y, int src_stride_y, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Convert J400 (jpeg grey) to ARGB. -LIBYUV_API -int J400ToARGB(const uint8* src_y, int src_stride_y, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Alias. -#define YToARGB I400ToARGB - -// Convert NV12 to ARGB. -LIBYUV_API -int NV12ToARGB(const uint8* src_y, int src_stride_y, - const uint8* src_uv, int src_stride_uv, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Convert NV21 to ARGB. -LIBYUV_API -int NV21ToARGB(const uint8* src_y, int src_stride_y, - const uint8* src_vu, int src_stride_vu, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Convert M420 to ARGB. -LIBYUV_API -int M420ToARGB(const uint8* src_m420, int src_stride_m420, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Convert YUY2 to ARGB. -LIBYUV_API -int YUY2ToARGB(const uint8* src_yuy2, int src_stride_yuy2, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Convert UYVY to ARGB. -LIBYUV_API -int UYVYToARGB(const uint8* src_uyvy, int src_stride_uyvy, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Convert J420 to ARGB. -LIBYUV_API -int J420ToARGB(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Convert J422 to ARGB. -LIBYUV_API -int J422ToARGB(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Convert J420 to ABGR. -LIBYUV_API -int J420ToABGR(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_abgr, int dst_stride_abgr, - int width, int height); - -// Convert J422 to ABGR. -LIBYUV_API -int J422ToABGR(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_abgr, int dst_stride_abgr, - int width, int height); - -// Convert H420 to ARGB. -LIBYUV_API -int H420ToARGB(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Convert H422 to ARGB. -LIBYUV_API -int H422ToARGB(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Convert H420 to ABGR. -LIBYUV_API -int H420ToABGR(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_abgr, int dst_stride_abgr, - int width, int height); - -// Convert H422 to ABGR. -LIBYUV_API -int H422ToABGR(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_abgr, int dst_stride_abgr, - int width, int height); - -// BGRA little endian (argb in memory) to ARGB. -LIBYUV_API -int BGRAToARGB(const uint8* src_frame, int src_stride_frame, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// ABGR little endian (rgba in memory) to ARGB. -LIBYUV_API -int ABGRToARGB(const uint8* src_frame, int src_stride_frame, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// RGBA little endian (abgr in memory) to ARGB. -LIBYUV_API -int RGBAToARGB(const uint8* src_frame, int src_stride_frame, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Deprecated function name. -#define BG24ToARGB RGB24ToARGB - -// RGB little endian (bgr in memory) to ARGB. -LIBYUV_API -int RGB24ToARGB(const uint8* src_frame, int src_stride_frame, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// RGB big endian (rgb in memory) to ARGB. -LIBYUV_API -int RAWToARGB(const uint8* src_frame, int src_stride_frame, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// RGB16 (RGBP fourcc) little endian to ARGB. -LIBYUV_API -int RGB565ToARGB(const uint8* src_frame, int src_stride_frame, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// RGB15 (RGBO fourcc) little endian to ARGB. -LIBYUV_API -int ARGB1555ToARGB(const uint8* src_frame, int src_stride_frame, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// RGB12 (R444 fourcc) little endian to ARGB. -LIBYUV_API -int ARGB4444ToARGB(const uint8* src_frame, int src_stride_frame, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -#ifdef HAVE_JPEG -// src_width/height provided by capture -// dst_width/height for clipping determine final size. -LIBYUV_API -int MJPGToARGB(const uint8* sample, size_t sample_size, - uint8* dst_argb, int dst_stride_argb, - int src_width, int src_height, - int dst_width, int dst_height); -#endif - -// Convert camera sample to ARGB with cropping, rotation and vertical flip. -// "src_size" is needed to parse MJPG. -// "dst_stride_argb" number of bytes in a row of the dst_argb plane. -// Normally this would be the same as dst_width, with recommended alignment -// to 16 bytes for better efficiency. -// If rotation of 90 or 270 is used, stride is affected. The caller should -// allocate the I420 buffer according to rotation. -// "dst_stride_u" number of bytes in a row of the dst_u plane. -// Normally this would be the same as (dst_width + 1) / 2, with -// recommended alignment to 16 bytes for better efficiency. -// If rotation of 90 or 270 is used, stride is affected. -// "crop_x" and "crop_y" are starting position for cropping. -// To center, crop_x = (src_width - dst_width) / 2 -// crop_y = (src_height - dst_height) / 2 -// "src_width" / "src_height" is size of src_frame in pixels. -// "src_height" can be negative indicating a vertically flipped image source. -// "crop_width" / "crop_height" is the size to crop the src to. -// Must be less than or equal to src_width/src_height -// Cropping parameters are pre-rotation. -// "rotation" can be 0, 90, 180 or 270. -// "format" is a fourcc. ie 'I420', 'YUY2' -// Returns 0 for successful; -1 for invalid parameter. Non-zero for failure. -LIBYUV_API -int ConvertToARGB(const uint8* src_frame, size_t src_size, - uint8* dst_argb, int dst_stride_argb, - int crop_x, int crop_y, - int src_width, int src_height, - int crop_width, int crop_height, - enum RotationMode rotation, - uint32 format); - -#ifdef __cplusplus -} // extern "C" -} // namespace libyuv -#endif - -#endif // INCLUDE_LIBYUV_CONVERT_ARGB_H_ diff --git a/third_party/libyuv/include/libyuv/convert_from.h b/third_party/libyuv/include/libyuv/convert_from.h deleted file mode 100644 index 59c40474f1..0000000000 --- a/third_party/libyuv/include/libyuv/convert_from.h +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Copyright 2011 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef INCLUDE_LIBYUV_CONVERT_FROM_H_ -#define INCLUDE_LIBYUV_CONVERT_FROM_H_ - -#include "libyuv/basic_types.h" -#include "libyuv/rotate.h" - -#ifdef __cplusplus -namespace libyuv { -extern "C" { -#endif - -// See Also convert.h for conversions from formats to I420. - -// I420Copy in convert to I420ToI420. - -LIBYUV_API -int I420ToI422(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -LIBYUV_API -int I420ToI444(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -LIBYUV_API -int I420ToI411(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Copy to I400. Source can be I420, I422, I444, I400, NV12 or NV21. -LIBYUV_API -int I400Copy(const uint8* src_y, int src_stride_y, - uint8* dst_y, int dst_stride_y, - int width, int height); - -LIBYUV_API -int I420ToNV12(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_y, int dst_stride_y, - uint8* dst_uv, int dst_stride_uv, - int width, int height); - -LIBYUV_API -int I420ToNV21(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_y, int dst_stride_y, - uint8* dst_vu, int dst_stride_vu, - int width, int height); - -LIBYUV_API -int I420ToYUY2(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_frame, int dst_stride_frame, - int width, int height); - -LIBYUV_API -int I420ToUYVY(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_frame, int dst_stride_frame, - int width, int height); - -LIBYUV_API -int I420ToARGB(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -LIBYUV_API -int I420ToBGRA(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -LIBYUV_API -int I420ToABGR(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -LIBYUV_API -int I420ToRGBA(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_rgba, int dst_stride_rgba, - int width, int height); - -LIBYUV_API -int I420ToRGB24(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_frame, int dst_stride_frame, - int width, int height); - -LIBYUV_API -int I420ToRAW(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_frame, int dst_stride_frame, - int width, int height); - -LIBYUV_API -int I420ToRGB565(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_frame, int dst_stride_frame, - int width, int height); - -// Convert I420 To RGB565 with 4x4 dither matrix (16 bytes). -// Values in dither matrix from 0 to 7 recommended. -// The order of the dither matrix is first byte is upper left. - -LIBYUV_API -int I420ToRGB565Dither(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_frame, int dst_stride_frame, - const uint8* dither4x4, int width, int height); - -LIBYUV_API -int I420ToARGB1555(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_frame, int dst_stride_frame, - int width, int height); - -LIBYUV_API -int I420ToARGB4444(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_frame, int dst_stride_frame, - int width, int height); - -// Convert I420 to specified format. -// "dst_sample_stride" is bytes in a row for the destination. Pass 0 if the -// buffer has contiguous rows. Can be negative. A multiple of 16 is optimal. -LIBYUV_API -int ConvertFromI420(const uint8* y, int y_stride, - const uint8* u, int u_stride, - const uint8* v, int v_stride, - uint8* dst_sample, int dst_sample_stride, - int width, int height, - uint32 format); - -#ifdef __cplusplus -} // extern "C" -} // namespace libyuv -#endif - -#endif // INCLUDE_LIBYUV_CONVERT_FROM_H_ diff --git a/third_party/libyuv/include/libyuv/convert_from_argb.h b/third_party/libyuv/include/libyuv/convert_from_argb.h deleted file mode 100644 index 8d7f02f8c4..0000000000 --- a/third_party/libyuv/include/libyuv/convert_from_argb.h +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Copyright 2012 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef INCLUDE_LIBYUV_CONVERT_FROM_ARGB_H_ -#define INCLUDE_LIBYUV_CONVERT_FROM_ARGB_H_ - -#include "libyuv/basic_types.h" - -#ifdef __cplusplus -namespace libyuv { -extern "C" { -#endif - -// Copy ARGB to ARGB. -#define ARGBToARGB ARGBCopy -LIBYUV_API -int ARGBCopy(const uint8* src_argb, int src_stride_argb, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Convert ARGB To BGRA. -LIBYUV_API -int ARGBToBGRA(const uint8* src_argb, int src_stride_argb, - uint8* dst_bgra, int dst_stride_bgra, - int width, int height); - -// Convert ARGB To ABGR. -LIBYUV_API -int ARGBToABGR(const uint8* src_argb, int src_stride_argb, - uint8* dst_abgr, int dst_stride_abgr, - int width, int height); - -// Convert ARGB To RGBA. -LIBYUV_API -int ARGBToRGBA(const uint8* src_argb, int src_stride_argb, - uint8* dst_rgba, int dst_stride_rgba, - int width, int height); - -// Convert ARGB To RGB24. -LIBYUV_API -int ARGBToRGB24(const uint8* src_argb, int src_stride_argb, - uint8* dst_rgb24, int dst_stride_rgb24, - int width, int height); - -// Convert ARGB To RAW. -LIBYUV_API -int ARGBToRAW(const uint8* src_argb, int src_stride_argb, - uint8* dst_rgb, int dst_stride_rgb, - int width, int height); - -// Convert ARGB To RGB565. -LIBYUV_API -int ARGBToRGB565(const uint8* src_argb, int src_stride_argb, - uint8* dst_rgb565, int dst_stride_rgb565, - int width, int height); - -// Convert ARGB To RGB565 with 4x4 dither matrix (16 bytes). -// Values in dither matrix from 0 to 7 recommended. -// The order of the dither matrix is first byte is upper left. -// TODO(fbarchard): Consider pointer to 2d array for dither4x4. -// const uint8(*dither)[4][4]; -LIBYUV_API -int ARGBToRGB565Dither(const uint8* src_argb, int src_stride_argb, - uint8* dst_rgb565, int dst_stride_rgb565, - const uint8* dither4x4, int width, int height); - -// Convert ARGB To ARGB1555. -LIBYUV_API -int ARGBToARGB1555(const uint8* src_argb, int src_stride_argb, - uint8* dst_argb1555, int dst_stride_argb1555, - int width, int height); - -// Convert ARGB To ARGB4444. -LIBYUV_API -int ARGBToARGB4444(const uint8* src_argb, int src_stride_argb, - uint8* dst_argb4444, int dst_stride_argb4444, - int width, int height); - -// Convert ARGB To I444. -LIBYUV_API -int ARGBToI444(const uint8* src_argb, int src_stride_argb, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Convert ARGB To I422. -LIBYUV_API -int ARGBToI422(const uint8* src_argb, int src_stride_argb, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Convert ARGB To I420. (also in convert.h) -LIBYUV_API -int ARGBToI420(const uint8* src_argb, int src_stride_argb, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Convert ARGB to J420. (JPeg full range I420). -LIBYUV_API -int ARGBToJ420(const uint8* src_argb, int src_stride_argb, - uint8* dst_yj, int dst_stride_yj, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Convert ARGB to J422. -LIBYUV_API -int ARGBToJ422(const uint8* src_argb, int src_stride_argb, - uint8* dst_yj, int dst_stride_yj, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Convert ARGB To I411. -LIBYUV_API -int ARGBToI411(const uint8* src_argb, int src_stride_argb, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Convert ARGB to J400. (JPeg full range). -LIBYUV_API -int ARGBToJ400(const uint8* src_argb, int src_stride_argb, - uint8* dst_yj, int dst_stride_yj, - int width, int height); - -// Convert ARGB to I400. -LIBYUV_API -int ARGBToI400(const uint8* src_argb, int src_stride_argb, - uint8* dst_y, int dst_stride_y, - int width, int height); - -// Convert ARGB to G. (Reverse of J400toARGB, which replicates G back to ARGB) -LIBYUV_API -int ARGBToG(const uint8* src_argb, int src_stride_argb, - uint8* dst_g, int dst_stride_g, - int width, int height); - -// Convert ARGB To NV12. -LIBYUV_API -int ARGBToNV12(const uint8* src_argb, int src_stride_argb, - uint8* dst_y, int dst_stride_y, - uint8* dst_uv, int dst_stride_uv, - int width, int height); - -// Convert ARGB To NV21. -LIBYUV_API -int ARGBToNV21(const uint8* src_argb, int src_stride_argb, - uint8* dst_y, int dst_stride_y, - uint8* dst_vu, int dst_stride_vu, - int width, int height); - -// Convert ARGB To NV21. -LIBYUV_API -int ARGBToNV21(const uint8* src_argb, int src_stride_argb, - uint8* dst_y, int dst_stride_y, - uint8* dst_vu, int dst_stride_vu, - int width, int height); - -// Convert ARGB To YUY2. -LIBYUV_API -int ARGBToYUY2(const uint8* src_argb, int src_stride_argb, - uint8* dst_yuy2, int dst_stride_yuy2, - int width, int height); - -// Convert ARGB To UYVY. -LIBYUV_API -int ARGBToUYVY(const uint8* src_argb, int src_stride_argb, - uint8* dst_uyvy, int dst_stride_uyvy, - int width, int height); - -#ifdef __cplusplus -} // extern "C" -} // namespace libyuv -#endif - -#endif // INCLUDE_LIBYUV_CONVERT_FROM_ARGB_H_ diff --git a/third_party/libyuv/include/libyuv/cpu_id.h b/third_party/libyuv/include/libyuv/cpu_id.h deleted file mode 100644 index 7c6c9aeb00..0000000000 --- a/third_party/libyuv/include/libyuv/cpu_id.h +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright 2011 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef INCLUDE_LIBYUV_CPU_ID_H_ -#define INCLUDE_LIBYUV_CPU_ID_H_ - -#include "libyuv/basic_types.h" - -#ifdef __cplusplus -namespace libyuv { -extern "C" { -#endif - -// Internal flag to indicate cpuid requires initialization. -static const int kCpuInitialized = 0x1; - -// These flags are only valid on ARM processors. -static const int kCpuHasARM = 0x2; -static const int kCpuHasNEON = 0x4; -// 0x8 reserved for future ARM flag. - -// These flags are only valid on x86 processors. -static const int kCpuHasX86 = 0x10; -static const int kCpuHasSSE2 = 0x20; -static const int kCpuHasSSSE3 = 0x40; -static const int kCpuHasSSE41 = 0x80; -static const int kCpuHasSSE42 = 0x100; -static const int kCpuHasAVX = 0x200; -static const int kCpuHasAVX2 = 0x400; -static const int kCpuHasERMS = 0x800; -static const int kCpuHasFMA3 = 0x1000; -static const int kCpuHasAVX3 = 0x2000; -// 0x2000, 0x4000, 0x8000 reserved for future X86 flags. - -// These flags are only valid on MIPS processors. -static const int kCpuHasMIPS = 0x10000; -static const int kCpuHasDSPR2 = 0x20000; -static const int kCpuHasMSA = 0x40000; - -// Internal function used to auto-init. -LIBYUV_API -int InitCpuFlags(void); - -// Internal function for parsing /proc/cpuinfo. -LIBYUV_API -int ArmCpuCaps(const char* cpuinfo_name); - -// Detect CPU has SSE2 etc. -// Test_flag parameter should be one of kCpuHas constants above. -// returns non-zero if instruction set is detected -static __inline int TestCpuFlag(int test_flag) { - LIBYUV_API extern int cpu_info_; - return (!cpu_info_ ? InitCpuFlags() : cpu_info_) & test_flag; -} - -// For testing, allow CPU flags to be disabled. -// ie MaskCpuFlags(~kCpuHasSSSE3) to disable SSSE3. -// MaskCpuFlags(-1) to enable all cpu specific optimizations. -// MaskCpuFlags(1) to disable all cpu specific optimizations. -LIBYUV_API -void MaskCpuFlags(int enable_flags); - -// Low level cpuid for X86. Returns zeros on other CPUs. -// eax is the info type that you want. -// ecx is typically the cpu number, and should normally be zero. -LIBYUV_API -void CpuId(uint32 eax, uint32 ecx, uint32* cpu_info); - -#ifdef __cplusplus -} // extern "C" -} // namespace libyuv -#endif - -#endif // INCLUDE_LIBYUV_CPU_ID_H_ diff --git a/third_party/libyuv/include/libyuv/macros_msa.h b/third_party/libyuv/include/libyuv/macros_msa.h deleted file mode 100644 index 92ed21c385..0000000000 --- a/third_party/libyuv/include/libyuv/macros_msa.h +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright 2016 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef INCLUDE_LIBYUV_MACROS_MSA_H_ -#define INCLUDE_LIBYUV_MACROS_MSA_H_ - -#if !defined(LIBYUV_DISABLE_MSA) && defined(__mips_msa) -#include -#include - -#define LD_B(RTYPE, psrc) *((RTYPE*)(psrc)) /* NOLINT */ -#define LD_UB(...) LD_B(v16u8, __VA_ARGS__) - -#define ST_B(RTYPE, in, pdst) *((RTYPE*)(pdst)) = (in) /* NOLINT */ -#define ST_UB(...) ST_B(v16u8, __VA_ARGS__) - -/* Description : Load two vectors with 16 'byte' sized elements - Arguments : Inputs - psrc, stride - Outputs - out0, out1 - Return Type - as per RTYPE - Details : Load 16 byte elements in 'out0' from (psrc) - Load 16 byte elements in 'out1' from (psrc + stride) -*/ -#define LD_B2(RTYPE, psrc, stride, out0, out1) { \ - out0 = LD_B(RTYPE, (psrc)); \ - out1 = LD_B(RTYPE, (psrc) + stride); \ -} -#define LD_UB2(...) LD_B2(v16u8, __VA_ARGS__) - -#define LD_B4(RTYPE, psrc, stride, out0, out1, out2, out3) { \ - LD_B2(RTYPE, (psrc), stride, out0, out1); \ - LD_B2(RTYPE, (psrc) + 2 * stride , stride, out2, out3); \ -} -#define LD_UB4(...) LD_B4(v16u8, __VA_ARGS__) - -/* Description : Store two vectors with stride each having 16 'byte' sized - elements - Arguments : Inputs - in0, in1, pdst, stride - Details : Store 16 byte elements from 'in0' to (pdst) - Store 16 byte elements from 'in1' to (pdst + stride) -*/ -#define ST_B2(RTYPE, in0, in1, pdst, stride) { \ - ST_B(RTYPE, in0, (pdst)); \ - ST_B(RTYPE, in1, (pdst) + stride); \ -} -#define ST_UB2(...) ST_B2(v16u8, __VA_ARGS__) -# -#define ST_B4(RTYPE, in0, in1, in2, in3, pdst, stride) { \ - ST_B2(RTYPE, in0, in1, (pdst), stride); \ - ST_B2(RTYPE, in2, in3, (pdst) + 2 * stride, stride); \ -} -#define ST_UB4(...) ST_B4(v16u8, __VA_ARGS__) -# -/* Description : Shuffle byte vector elements as per mask vector - Arguments : Inputs - in0, in1, in2, in3, mask0, mask1 - Outputs - out0, out1 - Return Type - as per RTYPE - Details : Byte elements from 'in0' & 'in1' are copied selectively to - 'out0' as per control vector 'mask0' -*/ -#define VSHF_B2(RTYPE, in0, in1, in2, in3, mask0, mask1, out0, out1) { \ - out0 = (RTYPE) __msa_vshf_b((v16i8) mask0, (v16i8) in1, (v16i8) in0); \ - out1 = (RTYPE) __msa_vshf_b((v16i8) mask1, (v16i8) in3, (v16i8) in2); \ -} -#define VSHF_B2_UB(...) VSHF_B2(v16u8, __VA_ARGS__) - -#endif /* !defined(LIBYUV_DISABLE_MSA) && defined(__mips_msa) */ - -#endif // INCLUDE_LIBYUV_MACROS_MSA_H_ diff --git a/third_party/libyuv/include/libyuv/mjpeg_decoder.h b/third_party/libyuv/include/libyuv/mjpeg_decoder.h deleted file mode 100644 index 4975bae5b7..0000000000 --- a/third_party/libyuv/include/libyuv/mjpeg_decoder.h +++ /dev/null @@ -1,192 +0,0 @@ -/* - * Copyright 2012 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef INCLUDE_LIBYUV_MJPEG_DECODER_H_ -#define INCLUDE_LIBYUV_MJPEG_DECODER_H_ - -#include "libyuv/basic_types.h" - -#ifdef __cplusplus -// NOTE: For a simplified public API use convert.h MJPGToI420(). - -struct jpeg_common_struct; -struct jpeg_decompress_struct; -struct jpeg_source_mgr; - -namespace libyuv { - -#ifdef __cplusplus -extern "C" { -#endif - -LIBYUV_BOOL ValidateJpeg(const uint8* sample, size_t sample_size); - -#ifdef __cplusplus -} // extern "C" -#endif - -static const uint32 kUnknownDataSize = 0xFFFFFFFF; - -enum JpegSubsamplingType { - kJpegYuv420, - kJpegYuv422, - kJpegYuv411, - kJpegYuv444, - kJpegYuv400, - kJpegUnknown -}; - -struct Buffer { - const uint8* data; - int len; -}; - -struct BufferVector { - Buffer* buffers; - int len; - int pos; -}; - -struct SetJmpErrorMgr; - -// MJPEG ("Motion JPEG") is a pseudo-standard video codec where the frames are -// simply independent JPEG images with a fixed huffman table (which is omitted). -// It is rarely used in video transmission, but is common as a camera capture -// format, especially in Logitech devices. This class implements a decoder for -// MJPEG frames. -// -// See http://tools.ietf.org/html/rfc2435 -class LIBYUV_API MJpegDecoder { - public: - typedef void (*CallbackFunction)(void* opaque, - const uint8* const* data, - const int* strides, - int rows); - - static const int kColorSpaceUnknown; - static const int kColorSpaceGrayscale; - static const int kColorSpaceRgb; - static const int kColorSpaceYCbCr; - static const int kColorSpaceCMYK; - static const int kColorSpaceYCCK; - - MJpegDecoder(); - ~MJpegDecoder(); - - // Loads a new frame, reads its headers, and determines the uncompressed - // image format. - // Returns LIBYUV_TRUE if image looks valid and format is supported. - // If return value is LIBYUV_TRUE, then the values for all the following - // getters are populated. - // src_len is the size of the compressed mjpeg frame in bytes. - LIBYUV_BOOL LoadFrame(const uint8* src, size_t src_len); - - // Returns width of the last loaded frame in pixels. - int GetWidth(); - - // Returns height of the last loaded frame in pixels. - int GetHeight(); - - // Returns format of the last loaded frame. The return value is one of the - // kColorSpace* constants. - int GetColorSpace(); - - // Number of color components in the color space. - int GetNumComponents(); - - // Sample factors of the n-th component. - int GetHorizSampFactor(int component); - - int GetVertSampFactor(int component); - - int GetHorizSubSampFactor(int component); - - int GetVertSubSampFactor(int component); - - // Public for testability. - int GetImageScanlinesPerImcuRow(); - - // Public for testability. - int GetComponentScanlinesPerImcuRow(int component); - - // Width of a component in bytes. - int GetComponentWidth(int component); - - // Height of a component. - int GetComponentHeight(int component); - - // Width of a component in bytes with padding for DCTSIZE. Public for testing. - int GetComponentStride(int component); - - // Size of a component in bytes. - int GetComponentSize(int component); - - // Call this after LoadFrame() if you decide you don't want to decode it - // after all. - LIBYUV_BOOL UnloadFrame(); - - // Decodes the entire image into a one-buffer-per-color-component format. - // dst_width must match exactly. dst_height must be <= to image height; if - // less, the image is cropped. "planes" must have size equal to at least - // GetNumComponents() and they must point to non-overlapping buffers of size - // at least GetComponentSize(i). The pointers in planes are incremented - // to point to after the end of the written data. - // TODO(fbarchard): Add dst_x, dst_y to allow specific rect to be decoded. - LIBYUV_BOOL DecodeToBuffers(uint8** planes, int dst_width, int dst_height); - - // Decodes the entire image and passes the data via repeated calls to a - // callback function. Each call will get the data for a whole number of - // image scanlines. - // TODO(fbarchard): Add dst_x, dst_y to allow specific rect to be decoded. - LIBYUV_BOOL DecodeToCallback(CallbackFunction fn, void* opaque, - int dst_width, int dst_height); - - // The helper function which recognizes the jpeg sub-sampling type. - static JpegSubsamplingType JpegSubsamplingTypeHelper( - int* subsample_x, int* subsample_y, int number_of_components); - - private: - void AllocOutputBuffers(int num_outbufs); - void DestroyOutputBuffers(); - - LIBYUV_BOOL StartDecode(); - LIBYUV_BOOL FinishDecode(); - - void SetScanlinePointers(uint8** data); - LIBYUV_BOOL DecodeImcuRow(); - - int GetComponentScanlinePadding(int component); - - // A buffer holding the input data for a frame. - Buffer buf_; - BufferVector buf_vec_; - - jpeg_decompress_struct* decompress_struct_; - jpeg_source_mgr* source_mgr_; - SetJmpErrorMgr* error_mgr_; - - // LIBYUV_TRUE iff at least one component has scanline padding. (i.e., - // GetComponentScanlinePadding() != 0.) - LIBYUV_BOOL has_scanline_padding_; - - // Temporaries used to point to scanline outputs. - int num_outbufs_; // Outermost size of all arrays below. - uint8*** scanlines_; - int* scanlines_sizes_; - // Temporary buffer used for decoding when we can't decode directly to the - // output buffers. Large enough for just one iMCU row. - uint8** databuf_; - int* databuf_strides_; -}; - -} // namespace libyuv - -#endif // __cplusplus -#endif // INCLUDE_LIBYUV_MJPEG_DECODER_H_ diff --git a/third_party/libyuv/include/libyuv/planar_functions.h b/third_party/libyuv/include/libyuv/planar_functions.h deleted file mode 100644 index 1b57b29261..0000000000 --- a/third_party/libyuv/include/libyuv/planar_functions.h +++ /dev/null @@ -1,529 +0,0 @@ -/* - * Copyright 2011 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef INCLUDE_LIBYUV_PLANAR_FUNCTIONS_H_ -#define INCLUDE_LIBYUV_PLANAR_FUNCTIONS_H_ - -#include "libyuv/basic_types.h" - -// TODO(fbarchard): Remove the following headers includes. -#include "libyuv/convert.h" -#include "libyuv/convert_argb.h" - -#ifdef __cplusplus -namespace libyuv { -extern "C" { -#endif - -// Copy a plane of data. -LIBYUV_API -void CopyPlane(const uint8* src_y, int src_stride_y, - uint8* dst_y, int dst_stride_y, - int width, int height); - -LIBYUV_API -void CopyPlane_16(const uint16* src_y, int src_stride_y, - uint16* dst_y, int dst_stride_y, - int width, int height); - -// Set a plane of data to a 32 bit value. -LIBYUV_API -void SetPlane(uint8* dst_y, int dst_stride_y, - int width, int height, - uint32 value); - -// Split interleaved UV plane into separate U and V planes. -LIBYUV_API -void SplitUVPlane(const uint8* src_uv, int src_stride_uv, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Merge separate U and V planes into one interleaved UV plane. -LIBYUV_API -void MergeUVPlane(const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_uv, int dst_stride_uv, - int width, int height); - -// Copy I400. Supports inverting. -LIBYUV_API -int I400ToI400(const uint8* src_y, int src_stride_y, - uint8* dst_y, int dst_stride_y, - int width, int height); - -#define J400ToJ400 I400ToI400 - -// Copy I422 to I422. -#define I422ToI422 I422Copy -LIBYUV_API -int I422Copy(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Copy I444 to I444. -#define I444ToI444 I444Copy -LIBYUV_API -int I444Copy(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Convert YUY2 to I422. -LIBYUV_API -int YUY2ToI422(const uint8* src_yuy2, int src_stride_yuy2, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Convert UYVY to I422. -LIBYUV_API -int UYVYToI422(const uint8* src_uyvy, int src_stride_uyvy, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -LIBYUV_API -int YUY2ToNV12(const uint8* src_yuy2, int src_stride_yuy2, - uint8* dst_y, int dst_stride_y, - uint8* dst_uv, int dst_stride_uv, - int width, int height); - -LIBYUV_API -int UYVYToNV12(const uint8* src_uyvy, int src_stride_uyvy, - uint8* dst_y, int dst_stride_y, - uint8* dst_uv, int dst_stride_uv, - int width, int height); - -// Convert I420 to I400. (calls CopyPlane ignoring u/v). -LIBYUV_API -int I420ToI400(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_y, int dst_stride_y, - int width, int height); - -// Alias -#define J420ToJ400 I420ToI400 -#define I420ToI420Mirror I420Mirror - -// I420 mirror. -LIBYUV_API -int I420Mirror(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Alias -#define I400ToI400Mirror I400Mirror - -// I400 mirror. A single plane is mirrored horizontally. -// Pass negative height to achieve 180 degree rotation. -LIBYUV_API -int I400Mirror(const uint8* src_y, int src_stride_y, - uint8* dst_y, int dst_stride_y, - int width, int height); - -// Alias -#define ARGBToARGBMirror ARGBMirror - -// ARGB mirror. -LIBYUV_API -int ARGBMirror(const uint8* src_argb, int src_stride_argb, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Convert NV12 to RGB565. -LIBYUV_API -int NV12ToRGB565(const uint8* src_y, int src_stride_y, - const uint8* src_uv, int src_stride_uv, - uint8* dst_rgb565, int dst_stride_rgb565, - int width, int height); - -// I422ToARGB is in convert_argb.h -// Convert I422 to BGRA. -LIBYUV_API -int I422ToBGRA(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_bgra, int dst_stride_bgra, - int width, int height); - -// Convert I422 to ABGR. -LIBYUV_API -int I422ToABGR(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_abgr, int dst_stride_abgr, - int width, int height); - -// Convert I422 to RGBA. -LIBYUV_API -int I422ToRGBA(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_rgba, int dst_stride_rgba, - int width, int height); - -// Alias -#define RGB24ToRAW RAWToRGB24 - -LIBYUV_API -int RAWToRGB24(const uint8* src_raw, int src_stride_raw, - uint8* dst_rgb24, int dst_stride_rgb24, - int width, int height); - -// Draw a rectangle into I420. -LIBYUV_API -int I420Rect(uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int x, int y, int width, int height, - int value_y, int value_u, int value_v); - -// Draw a rectangle into ARGB. -LIBYUV_API -int ARGBRect(uint8* dst_argb, int dst_stride_argb, - int x, int y, int width, int height, uint32 value); - -// Convert ARGB to gray scale ARGB. -LIBYUV_API -int ARGBGrayTo(const uint8* src_argb, int src_stride_argb, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Make a rectangle of ARGB gray scale. -LIBYUV_API -int ARGBGray(uint8* dst_argb, int dst_stride_argb, - int x, int y, int width, int height); - -// Make a rectangle of ARGB Sepia tone. -LIBYUV_API -int ARGBSepia(uint8* dst_argb, int dst_stride_argb, - int x, int y, int width, int height); - -// Apply a matrix rotation to each ARGB pixel. -// matrix_argb is 4 signed ARGB values. -128 to 127 representing -2 to 2. -// The first 4 coefficients apply to B, G, R, A and produce B of the output. -// The next 4 coefficients apply to B, G, R, A and produce G of the output. -// The next 4 coefficients apply to B, G, R, A and produce R of the output. -// The last 4 coefficients apply to B, G, R, A and produce A of the output. -LIBYUV_API -int ARGBColorMatrix(const uint8* src_argb, int src_stride_argb, - uint8* dst_argb, int dst_stride_argb, - const int8* matrix_argb, - int width, int height); - -// Deprecated. Use ARGBColorMatrix instead. -// Apply a matrix rotation to each ARGB pixel. -// matrix_argb is 3 signed ARGB values. -128 to 127 representing -1 to 1. -// The first 4 coefficients apply to B, G, R, A and produce B of the output. -// The next 4 coefficients apply to B, G, R, A and produce G of the output. -// The last 4 coefficients apply to B, G, R, A and produce R of the output. -LIBYUV_API -int RGBColorMatrix(uint8* dst_argb, int dst_stride_argb, - const int8* matrix_rgb, - int x, int y, int width, int height); - -// Apply a color table each ARGB pixel. -// Table contains 256 ARGB values. -LIBYUV_API -int ARGBColorTable(uint8* dst_argb, int dst_stride_argb, - const uint8* table_argb, - int x, int y, int width, int height); - -// Apply a color table each ARGB pixel but preserve destination alpha. -// Table contains 256 ARGB values. -LIBYUV_API -int RGBColorTable(uint8* dst_argb, int dst_stride_argb, - const uint8* table_argb, - int x, int y, int width, int height); - -// Apply a luma/color table each ARGB pixel but preserve destination alpha. -// Table contains 32768 values indexed by [Y][C] where 7 it 7 bit luma from -// RGB (YJ style) and C is an 8 bit color component (R, G or B). -LIBYUV_API -int ARGBLumaColorTable(const uint8* src_argb, int src_stride_argb, - uint8* dst_argb, int dst_stride_argb, - const uint8* luma_rgb_table, - int width, int height); - -// Apply a 3 term polynomial to ARGB values. -// poly points to a 4x4 matrix. The first row is constants. The 2nd row is -// coefficients for b, g, r and a. The 3rd row is coefficients for b squared, -// g squared, r squared and a squared. The 4rd row is coefficients for b to -// the 3, g to the 3, r to the 3 and a to the 3. The values are summed and -// result clamped to 0 to 255. -// A polynomial approximation can be dirived using software such as 'R'. - -LIBYUV_API -int ARGBPolynomial(const uint8* src_argb, int src_stride_argb, - uint8* dst_argb, int dst_stride_argb, - const float* poly, - int width, int height); - -// Convert plane of 16 bit shorts to half floats. -// Source values are multiplied by scale before storing as half float. -LIBYUV_API -int HalfFloatPlane(const uint16* src_y, int src_stride_y, - uint16* dst_y, int dst_stride_y, - float scale, - int width, int height); - -// Quantize a rectangle of ARGB. Alpha unaffected. -// scale is a 16 bit fractional fixed point scaler between 0 and 65535. -// interval_size should be a value between 1 and 255. -// interval_offset should be a value between 0 and 255. -LIBYUV_API -int ARGBQuantize(uint8* dst_argb, int dst_stride_argb, - int scale, int interval_size, int interval_offset, - int x, int y, int width, int height); - -// Copy ARGB to ARGB. -LIBYUV_API -int ARGBCopy(const uint8* src_argb, int src_stride_argb, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Copy Alpha channel of ARGB to alpha of ARGB. -LIBYUV_API -int ARGBCopyAlpha(const uint8* src_argb, int src_stride_argb, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Extract the alpha channel from ARGB. -LIBYUV_API -int ARGBExtractAlpha(const uint8* src_argb, int src_stride_argb, - uint8* dst_a, int dst_stride_a, - int width, int height); - -// Copy Y channel to Alpha of ARGB. -LIBYUV_API -int ARGBCopyYToAlpha(const uint8* src_y, int src_stride_y, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -typedef void (*ARGBBlendRow)(const uint8* src_argb0, const uint8* src_argb1, - uint8* dst_argb, int width); - -// Get function to Alpha Blend ARGB pixels and store to destination. -LIBYUV_API -ARGBBlendRow GetARGBBlend(); - -// Alpha Blend ARGB images and store to destination. -// Source is pre-multiplied by alpha using ARGBAttenuate. -// Alpha of destination is set to 255. -LIBYUV_API -int ARGBBlend(const uint8* src_argb0, int src_stride_argb0, - const uint8* src_argb1, int src_stride_argb1, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Alpha Blend plane and store to destination. -// Source is not pre-multiplied by alpha. -LIBYUV_API -int BlendPlane(const uint8* src_y0, int src_stride_y0, - const uint8* src_y1, int src_stride_y1, - const uint8* alpha, int alpha_stride, - uint8* dst_y, int dst_stride_y, - int width, int height); - -// Alpha Blend YUV images and store to destination. -// Source is not pre-multiplied by alpha. -// Alpha is full width x height and subsampled to half size to apply to UV. -LIBYUV_API -int I420Blend(const uint8* src_y0, int src_stride_y0, - const uint8* src_u0, int src_stride_u0, - const uint8* src_v0, int src_stride_v0, - const uint8* src_y1, int src_stride_y1, - const uint8* src_u1, int src_stride_u1, - const uint8* src_v1, int src_stride_v1, - const uint8* alpha, int alpha_stride, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height); - -// Multiply ARGB image by ARGB image. Shifted down by 8. Saturates to 255. -LIBYUV_API -int ARGBMultiply(const uint8* src_argb0, int src_stride_argb0, - const uint8* src_argb1, int src_stride_argb1, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Add ARGB image with ARGB image. Saturates to 255. -LIBYUV_API -int ARGBAdd(const uint8* src_argb0, int src_stride_argb0, - const uint8* src_argb1, int src_stride_argb1, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Subtract ARGB image (argb1) from ARGB image (argb0). Saturates to 0. -LIBYUV_API -int ARGBSubtract(const uint8* src_argb0, int src_stride_argb0, - const uint8* src_argb1, int src_stride_argb1, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Convert I422 to YUY2. -LIBYUV_API -int I422ToYUY2(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_frame, int dst_stride_frame, - int width, int height); - -// Convert I422 to UYVY. -LIBYUV_API -int I422ToUYVY(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_frame, int dst_stride_frame, - int width, int height); - -// Convert unattentuated ARGB to preattenuated ARGB. -LIBYUV_API -int ARGBAttenuate(const uint8* src_argb, int src_stride_argb, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Convert preattentuated ARGB to unattenuated ARGB. -LIBYUV_API -int ARGBUnattenuate(const uint8* src_argb, int src_stride_argb, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Internal function - do not call directly. -// Computes table of cumulative sum for image where the value is the sum -// of all values above and to the left of the entry. Used by ARGBBlur. -LIBYUV_API -int ARGBComputeCumulativeSum(const uint8* src_argb, int src_stride_argb, - int32* dst_cumsum, int dst_stride32_cumsum, - int width, int height); - -// Blur ARGB image. -// dst_cumsum table of width * (height + 1) * 16 bytes aligned to -// 16 byte boundary. -// dst_stride32_cumsum is number of ints in a row (width * 4). -// radius is number of pixels around the center. e.g. 1 = 3x3. 2=5x5. -// Blur is optimized for radius of 5 (11x11) or less. -LIBYUV_API -int ARGBBlur(const uint8* src_argb, int src_stride_argb, - uint8* dst_argb, int dst_stride_argb, - int32* dst_cumsum, int dst_stride32_cumsum, - int width, int height, int radius); - -// Multiply ARGB image by ARGB value. -LIBYUV_API -int ARGBShade(const uint8* src_argb, int src_stride_argb, - uint8* dst_argb, int dst_stride_argb, - int width, int height, uint32 value); - -// Interpolate between two images using specified amount of interpolation -// (0 to 255) and store to destination. -// 'interpolation' is specified as 8 bit fraction where 0 means 100% src0 -// and 255 means 1% src0 and 99% src1. -LIBYUV_API -int InterpolatePlane(const uint8* src0, int src_stride0, - const uint8* src1, int src_stride1, - uint8* dst, int dst_stride, - int width, int height, int interpolation); - -// Interpolate between two ARGB images using specified amount of interpolation -// Internally calls InterpolatePlane with width * 4 (bpp). -LIBYUV_API -int ARGBInterpolate(const uint8* src_argb0, int src_stride_argb0, - const uint8* src_argb1, int src_stride_argb1, - uint8* dst_argb, int dst_stride_argb, - int width, int height, int interpolation); - -// Interpolate between two YUV images using specified amount of interpolation -// Internally calls InterpolatePlane on each plane where the U and V planes -// are half width and half height. -LIBYUV_API -int I420Interpolate(const uint8* src0_y, int src0_stride_y, - const uint8* src0_u, int src0_stride_u, - const uint8* src0_v, int src0_stride_v, - const uint8* src1_y, int src1_stride_y, - const uint8* src1_u, int src1_stride_u, - const uint8* src1_v, int src1_stride_v, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int width, int height, int interpolation); - -#if defined(__pnacl__) || defined(__CLR_VER) || \ - (defined(__i386__) && !defined(__SSE2__)) -#define LIBYUV_DISABLE_X86 -#endif -// MemorySanitizer does not support assembly code yet. http://crbug.com/344505 -#if defined(__has_feature) -#if __has_feature(memory_sanitizer) -#define LIBYUV_DISABLE_X86 -#endif -#endif -// The following are available on all x86 platforms: -#if !defined(LIBYUV_DISABLE_X86) && \ - (defined(_M_IX86) || defined(__x86_64__) || defined(__i386__)) -#define HAS_ARGBAFFINEROW_SSE2 -#endif - -// Row function for copying pixels from a source with a slope to a row -// of destination. Useful for scaling, rotation, mirror, texture mapping. -LIBYUV_API -void ARGBAffineRow_C(const uint8* src_argb, int src_argb_stride, - uint8* dst_argb, const float* uv_dudv, int width); -LIBYUV_API -void ARGBAffineRow_SSE2(const uint8* src_argb, int src_argb_stride, - uint8* dst_argb, const float* uv_dudv, int width); - -// Shuffle ARGB channel order. e.g. BGRA to ARGB. -// shuffler is 16 bytes and must be aligned. -LIBYUV_API -int ARGBShuffle(const uint8* src_bgra, int src_stride_bgra, - uint8* dst_argb, int dst_stride_argb, - const uint8* shuffler, int width, int height); - -// Sobel ARGB effect with planar output. -LIBYUV_API -int ARGBSobelToPlane(const uint8* src_argb, int src_stride_argb, - uint8* dst_y, int dst_stride_y, - int width, int height); - -// Sobel ARGB effect. -LIBYUV_API -int ARGBSobel(const uint8* src_argb, int src_stride_argb, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -// Sobel ARGB effect w/ Sobel X, Sobel, Sobel Y in ARGB. -LIBYUV_API -int ARGBSobelXY(const uint8* src_argb, int src_stride_argb, - uint8* dst_argb, int dst_stride_argb, - int width, int height); - -#ifdef __cplusplus -} // extern "C" -} // namespace libyuv -#endif - -#endif // INCLUDE_LIBYUV_PLANAR_FUNCTIONS_H_ diff --git a/third_party/libyuv/include/libyuv/rotate.h b/third_party/libyuv/include/libyuv/rotate.h deleted file mode 100644 index 8a2da9a5aa..0000000000 --- a/third_party/libyuv/include/libyuv/rotate.h +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright 2011 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef INCLUDE_LIBYUV_ROTATE_H_ -#define INCLUDE_LIBYUV_ROTATE_H_ - -#include "libyuv/basic_types.h" - -#ifdef __cplusplus -namespace libyuv { -extern "C" { -#endif - -// Supported rotation. -typedef enum RotationMode { - kRotate0 = 0, // No rotation. - kRotate90 = 90, // Rotate 90 degrees clockwise. - kRotate180 = 180, // Rotate 180 degrees. - kRotate270 = 270, // Rotate 270 degrees clockwise. - - // Deprecated. - kRotateNone = 0, - kRotateClockwise = 90, - kRotateCounterClockwise = 270, -} RotationModeEnum; - -// Rotate I420 frame. -LIBYUV_API -int I420Rotate(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int src_width, int src_height, enum RotationMode mode); - -// Rotate NV12 input and store in I420. -LIBYUV_API -int NV12ToI420Rotate(const uint8* src_y, int src_stride_y, - const uint8* src_uv, int src_stride_uv, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int src_width, int src_height, enum RotationMode mode); - -// Rotate a plane by 0, 90, 180, or 270. -LIBYUV_API -int RotatePlane(const uint8* src, int src_stride, - uint8* dst, int dst_stride, - int src_width, int src_height, enum RotationMode mode); - -// Rotate planes by 90, 180, 270. Deprecated. -LIBYUV_API -void RotatePlane90(const uint8* src, int src_stride, - uint8* dst, int dst_stride, - int width, int height); - -LIBYUV_API -void RotatePlane180(const uint8* src, int src_stride, - uint8* dst, int dst_stride, - int width, int height); - -LIBYUV_API -void RotatePlane270(const uint8* src, int src_stride, - uint8* dst, int dst_stride, - int width, int height); - -LIBYUV_API -void RotateUV90(const uint8* src, int src_stride, - uint8* dst_a, int dst_stride_a, - uint8* dst_b, int dst_stride_b, - int width, int height); - -// Rotations for when U and V are interleaved. -// These functions take one input pointer and -// split the data into two buffers while -// rotating them. Deprecated. -LIBYUV_API -void RotateUV180(const uint8* src, int src_stride, - uint8* dst_a, int dst_stride_a, - uint8* dst_b, int dst_stride_b, - int width, int height); - -LIBYUV_API -void RotateUV270(const uint8* src, int src_stride, - uint8* dst_a, int dst_stride_a, - uint8* dst_b, int dst_stride_b, - int width, int height); - -// The 90 and 270 functions are based on transposes. -// Doing a transpose with reversing the read/write -// order will result in a rotation by +- 90 degrees. -// Deprecated. -LIBYUV_API -void TransposePlane(const uint8* src, int src_stride, - uint8* dst, int dst_stride, - int width, int height); - -LIBYUV_API -void TransposeUV(const uint8* src, int src_stride, - uint8* dst_a, int dst_stride_a, - uint8* dst_b, int dst_stride_b, - int width, int height); - -#ifdef __cplusplus -} // extern "C" -} // namespace libyuv -#endif - -#endif // INCLUDE_LIBYUV_ROTATE_H_ diff --git a/third_party/libyuv/include/libyuv/rotate_argb.h b/third_party/libyuv/include/libyuv/rotate_argb.h deleted file mode 100644 index 21fe7e1807..0000000000 --- a/third_party/libyuv/include/libyuv/rotate_argb.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright 2012 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef INCLUDE_LIBYUV_ROTATE_ARGB_H_ -#define INCLUDE_LIBYUV_ROTATE_ARGB_H_ - -#include "libyuv/basic_types.h" -#include "libyuv/rotate.h" // For RotationMode. - -#ifdef __cplusplus -namespace libyuv { -extern "C" { -#endif - -// Rotate ARGB frame -LIBYUV_API -int ARGBRotate(const uint8* src_argb, int src_stride_argb, - uint8* dst_argb, int dst_stride_argb, - int src_width, int src_height, enum RotationMode mode); - -#ifdef __cplusplus -} // extern "C" -} // namespace libyuv -#endif - -#endif // INCLUDE_LIBYUV_ROTATE_ARGB_H_ diff --git a/third_party/libyuv/include/libyuv/rotate_row.h b/third_party/libyuv/include/libyuv/rotate_row.h deleted file mode 100644 index 6abd201677..0000000000 --- a/third_party/libyuv/include/libyuv/rotate_row.h +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright 2013 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef INCLUDE_LIBYUV_ROTATE_ROW_H_ -#define INCLUDE_LIBYUV_ROTATE_ROW_H_ - -#include "libyuv/basic_types.h" - -#ifdef __cplusplus -namespace libyuv { -extern "C" { -#endif - -#if defined(__pnacl__) || defined(__CLR_VER) || \ - (defined(__i386__) && !defined(__SSE2__)) -#define LIBYUV_DISABLE_X86 -#endif -// MemorySanitizer does not support assembly code yet. http://crbug.com/344505 -#if defined(__has_feature) -#if __has_feature(memory_sanitizer) -#define LIBYUV_DISABLE_X86 -#endif -#endif -// The following are available for Visual C and clangcl 32 bit: -#if !defined(LIBYUV_DISABLE_X86) && defined(_M_IX86) -#define HAS_TRANSPOSEWX8_SSSE3 -#define HAS_TRANSPOSEUVWX8_SSE2 -#endif - -// The following are available for GCC 32 or 64 bit but not NaCL for 64 bit: -#if !defined(LIBYUV_DISABLE_X86) && \ - (defined(__i386__) || (defined(__x86_64__) && !defined(__native_client__))) -#define HAS_TRANSPOSEWX8_SSSE3 -#endif - -// The following are available for 64 bit GCC but not NaCL: -#if !defined(LIBYUV_DISABLE_X86) && !defined(__native_client__) && \ - defined(__x86_64__) -#define HAS_TRANSPOSEWX8_FAST_SSSE3 -#define HAS_TRANSPOSEUVWX8_SSE2 -#endif - -#if !defined(LIBYUV_DISABLE_NEON) && !defined(__native_client__) && \ - (defined(__ARM_NEON__) || defined(LIBYUV_NEON) || defined(__aarch64__)) -#define HAS_TRANSPOSEWX8_NEON -#define HAS_TRANSPOSEUVWX8_NEON -#endif - -#if !defined(LIBYUV_DISABLE_MIPS) && !defined(__native_client__) && \ - defined(__mips__) && \ - defined(__mips_dsp) && (__mips_dsp_rev >= 2) -#define HAS_TRANSPOSEWX8_DSPR2 -#define HAS_TRANSPOSEUVWX8_DSPR2 -#endif // defined(__mips__) - -void TransposeWxH_C(const uint8* src, int src_stride, - uint8* dst, int dst_stride, int width, int height); - -void TransposeWx8_C(const uint8* src, int src_stride, - uint8* dst, int dst_stride, int width); -void TransposeWx8_NEON(const uint8* src, int src_stride, - uint8* dst, int dst_stride, int width); -void TransposeWx8_SSSE3(const uint8* src, int src_stride, - uint8* dst, int dst_stride, int width); -void TransposeWx8_Fast_SSSE3(const uint8* src, int src_stride, - uint8* dst, int dst_stride, int width); -void TransposeWx8_DSPR2(const uint8* src, int src_stride, - uint8* dst, int dst_stride, int width); -void TransposeWx8_Fast_DSPR2(const uint8* src, int src_stride, - uint8* dst, int dst_stride, int width); - -void TransposeWx8_Any_NEON(const uint8* src, int src_stride, - uint8* dst, int dst_stride, int width); -void TransposeWx8_Any_SSSE3(const uint8* src, int src_stride, - uint8* dst, int dst_stride, int width); -void TransposeWx8_Fast_Any_SSSE3(const uint8* src, int src_stride, - uint8* dst, int dst_stride, int width); -void TransposeWx8_Any_DSPR2(const uint8* src, int src_stride, - uint8* dst, int dst_stride, int width); - -void TransposeUVWxH_C(const uint8* src, int src_stride, - uint8* dst_a, int dst_stride_a, - uint8* dst_b, int dst_stride_b, - int width, int height); - -void TransposeUVWx8_C(const uint8* src, int src_stride, - uint8* dst_a, int dst_stride_a, - uint8* dst_b, int dst_stride_b, int width); -void TransposeUVWx8_SSE2(const uint8* src, int src_stride, - uint8* dst_a, int dst_stride_a, - uint8* dst_b, int dst_stride_b, int width); -void TransposeUVWx8_NEON(const uint8* src, int src_stride, - uint8* dst_a, int dst_stride_a, - uint8* dst_b, int dst_stride_b, int width); -void TransposeUVWx8_DSPR2(const uint8* src, int src_stride, - uint8* dst_a, int dst_stride_a, - uint8* dst_b, int dst_stride_b, int width); - -void TransposeUVWx8_Any_SSE2(const uint8* src, int src_stride, - uint8* dst_a, int dst_stride_a, - uint8* dst_b, int dst_stride_b, int width); -void TransposeUVWx8_Any_NEON(const uint8* src, int src_stride, - uint8* dst_a, int dst_stride_a, - uint8* dst_b, int dst_stride_b, int width); -void TransposeUVWx8_Any_DSPR2(const uint8* src, int src_stride, - uint8* dst_a, int dst_stride_a, - uint8* dst_b, int dst_stride_b, int width); - -#ifdef __cplusplus -} // extern "C" -} // namespace libyuv -#endif - -#endif // INCLUDE_LIBYUV_ROTATE_ROW_H_ diff --git a/third_party/libyuv/include/libyuv/row.h b/third_party/libyuv/include/libyuv/row.h deleted file mode 100644 index b810221ec7..0000000000 --- a/third_party/libyuv/include/libyuv/row.h +++ /dev/null @@ -1,1963 +0,0 @@ -/* - * Copyright 2011 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef INCLUDE_LIBYUV_ROW_H_ -#define INCLUDE_LIBYUV_ROW_H_ - -#include // For malloc. - -#include "libyuv/basic_types.h" - -#ifdef __cplusplus -namespace libyuv { -extern "C" { -#endif - -#define IS_ALIGNED(p, a) (!((uintptr_t)(p) & ((a) - 1))) - -#define align_buffer_64(var, size) \ - uint8* var##_mem = (uint8*)(malloc((size) + 63)); /* NOLINT */ \ - uint8* var = (uint8*)(((intptr_t)(var##_mem) + 63) & ~63) /* NOLINT */ - -#define free_aligned_buffer_64(var) \ - free(var##_mem); \ - var = 0 - -#if defined(__pnacl__) || defined(__CLR_VER) || \ - (defined(__i386__) && !defined(__SSE2__)) -#define LIBYUV_DISABLE_X86 -#endif -// MemorySanitizer does not support assembly code yet. http://crbug.com/344505 -#if defined(__has_feature) -#if __has_feature(memory_sanitizer) -#define LIBYUV_DISABLE_X86 -#endif -#endif -// True if compiling for SSSE3 as a requirement. -#if defined(__SSSE3__) || (defined(_M_IX86_FP) && (_M_IX86_FP >= 3)) -#define LIBYUV_SSSE3_ONLY -#endif - -#if defined(__native_client__) -#define LIBYUV_DISABLE_NEON -#endif -// clang >= 3.5.0 required for Arm64. -#if defined(__clang__) && defined(__aarch64__) && !defined(LIBYUV_DISABLE_NEON) -#if (__clang_major__ < 3) || (__clang_major__ == 3 && (__clang_minor__ < 5)) -#define LIBYUV_DISABLE_NEON -#endif // clang >= 3.5 -#endif // __clang__ - -// GCC >= 4.7.0 required for AVX2. -#if defined(__GNUC__) && (defined(__x86_64__) || defined(__i386__)) -#if (__GNUC__ > 4) || (__GNUC__ == 4 && (__GNUC_MINOR__ >= 7)) -#define GCC_HAS_AVX2 1 -#endif // GNUC >= 4.7 -#endif // __GNUC__ - -// clang >= 3.4.0 required for AVX2. -#if defined(__clang__) && (defined(__x86_64__) || defined(__i386__)) -#if (__clang_major__ > 3) || (__clang_major__ == 3 && (__clang_minor__ >= 4)) -#define CLANG_HAS_AVX2 1 -#endif // clang >= 3.4 -#endif // __clang__ - -// Visual C 2012 required for AVX2. -#if defined(_M_IX86) && !defined(__clang__) && \ - defined(_MSC_VER) && _MSC_VER >= 1700 -#define VISUALC_HAS_AVX2 1 -#endif // VisualStudio >= 2012 - -// The following are available on all x86 platforms: -#if !defined(LIBYUV_DISABLE_X86) && \ - (defined(_M_IX86) || defined(__x86_64__) || defined(__i386__)) -// Conversions: -#define HAS_ABGRTOUVROW_SSSE3 -#define HAS_ABGRTOYROW_SSSE3 -#define HAS_ARGB1555TOARGBROW_SSE2 -#define HAS_ARGB4444TOARGBROW_SSE2 -#define HAS_ARGBSETROW_X86 -#define HAS_ARGBSHUFFLEROW_SSE2 -#define HAS_ARGBSHUFFLEROW_SSSE3 -#define HAS_ARGBTOARGB1555ROW_SSE2 -#define HAS_ARGBTOARGB4444ROW_SSE2 -#define HAS_ARGBTORAWROW_SSSE3 -#define HAS_ARGBTORGB24ROW_SSSE3 -#define HAS_ARGBTORGB565DITHERROW_SSE2 -#define HAS_ARGBTORGB565ROW_SSE2 -#define HAS_ARGBTOUV444ROW_SSSE3 -#define HAS_ARGBTOUVJROW_SSSE3 -#define HAS_ARGBTOUVROW_SSSE3 -#define HAS_ARGBTOYJROW_SSSE3 -#define HAS_ARGBTOYROW_SSSE3 -#define HAS_ARGBEXTRACTALPHAROW_SSE2 -#define HAS_BGRATOUVROW_SSSE3 -#define HAS_BGRATOYROW_SSSE3 -#define HAS_COPYROW_ERMS -#define HAS_COPYROW_SSE2 -#define HAS_H422TOARGBROW_SSSE3 -#define HAS_I400TOARGBROW_SSE2 -#define HAS_I422TOARGB1555ROW_SSSE3 -#define HAS_I422TOARGB4444ROW_SSSE3 -#define HAS_I422TOARGBROW_SSSE3 -#define HAS_I422TORGB24ROW_SSSE3 -#define HAS_I422TORGB565ROW_SSSE3 -#define HAS_I422TORGBAROW_SSSE3 -#define HAS_I422TOUYVYROW_SSE2 -#define HAS_I422TOYUY2ROW_SSE2 -#define HAS_I444TOARGBROW_SSSE3 -#define HAS_J400TOARGBROW_SSE2 -#define HAS_J422TOARGBROW_SSSE3 -#define HAS_MERGEUVROW_SSE2 -#define HAS_MIRRORROW_SSSE3 -#define HAS_MIRRORUVROW_SSSE3 -#define HAS_NV12TOARGBROW_SSSE3 -#define HAS_NV12TORGB565ROW_SSSE3 -#define HAS_NV21TOARGBROW_SSSE3 -#define HAS_RAWTOARGBROW_SSSE3 -#define HAS_RAWTORGB24ROW_SSSE3 -#define HAS_RAWTOYROW_SSSE3 -#define HAS_RGB24TOARGBROW_SSSE3 -#define HAS_RGB24TOYROW_SSSE3 -#define HAS_RGB565TOARGBROW_SSE2 -#define HAS_RGBATOUVROW_SSSE3 -#define HAS_RGBATOYROW_SSSE3 -#define HAS_SETROW_ERMS -#define HAS_SETROW_X86 -#define HAS_SPLITUVROW_SSE2 -#define HAS_UYVYTOARGBROW_SSSE3 -#define HAS_UYVYTOUV422ROW_SSE2 -#define HAS_UYVYTOUVROW_SSE2 -#define HAS_UYVYTOYROW_SSE2 -#define HAS_YUY2TOARGBROW_SSSE3 -#define HAS_YUY2TOUV422ROW_SSE2 -#define HAS_YUY2TOUVROW_SSE2 -#define HAS_YUY2TOYROW_SSE2 - -// Effects: -#define HAS_ARGBADDROW_SSE2 -#define HAS_ARGBAFFINEROW_SSE2 -#define HAS_ARGBATTENUATEROW_SSSE3 -#define HAS_ARGBBLENDROW_SSSE3 -#define HAS_ARGBCOLORMATRIXROW_SSSE3 -#define HAS_ARGBCOLORTABLEROW_X86 -#define HAS_ARGBCOPYALPHAROW_SSE2 -#define HAS_ARGBCOPYYTOALPHAROW_SSE2 -#define HAS_ARGBGRAYROW_SSSE3 -#define HAS_ARGBLUMACOLORTABLEROW_SSSE3 -#define HAS_ARGBMIRRORROW_SSE2 -#define HAS_ARGBMULTIPLYROW_SSE2 -#define HAS_ARGBPOLYNOMIALROW_SSE2 -#define HAS_ARGBQUANTIZEROW_SSE2 -#define HAS_ARGBSEPIAROW_SSSE3 -#define HAS_ARGBSHADEROW_SSE2 -#define HAS_ARGBSUBTRACTROW_SSE2 -#define HAS_ARGBUNATTENUATEROW_SSE2 -#define HAS_BLENDPLANEROW_SSSE3 -#define HAS_COMPUTECUMULATIVESUMROW_SSE2 -#define HAS_CUMULATIVESUMTOAVERAGEROW_SSE2 -#define HAS_INTERPOLATEROW_SSSE3 -#define HAS_RGBCOLORTABLEROW_X86 -#define HAS_SOBELROW_SSE2 -#define HAS_SOBELTOPLANEROW_SSE2 -#define HAS_SOBELXROW_SSE2 -#define HAS_SOBELXYROW_SSE2 -#define HAS_SOBELYROW_SSE2 - -// The following functions fail on gcc/clang 32 bit with fpic and framepointer. -// caveat: clangcl uses row_win.cc which works. -#if defined(NDEBUG) || !(defined(_DEBUG) && defined(__i386__)) || \ - !defined(__i386__) || defined(_MSC_VER) -// TODO(fbarchard): fix build error on x86 debug -// https://code.google.com/p/libyuv/issues/detail?id=524 -#define HAS_I411TOARGBROW_SSSE3 -// TODO(fbarchard): fix build error on android_full_debug=1 -// https://code.google.com/p/libyuv/issues/detail?id=517 -#define HAS_I422ALPHATOARGBROW_SSSE3 -#endif -#endif - -// The following are available on all x86 platforms, but -// require VS2012, clang 3.4 or gcc 4.7. -// The code supports NaCL but requires a new compiler and validator. -#if !defined(LIBYUV_DISABLE_X86) && (defined(VISUALC_HAS_AVX2) || \ - defined(CLANG_HAS_AVX2) || defined(GCC_HAS_AVX2)) -#define HAS_ARGBCOPYALPHAROW_AVX2 -#define HAS_ARGBCOPYYTOALPHAROW_AVX2 -#define HAS_ARGBMIRRORROW_AVX2 -#define HAS_ARGBPOLYNOMIALROW_AVX2 -#define HAS_ARGBSHUFFLEROW_AVX2 -#define HAS_ARGBTORGB565DITHERROW_AVX2 -#define HAS_ARGBTOUVJROW_AVX2 -#define HAS_ARGBTOUVROW_AVX2 -#define HAS_ARGBTOYJROW_AVX2 -#define HAS_ARGBTOYROW_AVX2 -#define HAS_COPYROW_AVX -#define HAS_H422TOARGBROW_AVX2 -#define HAS_I400TOARGBROW_AVX2 -#if !(defined(_DEBUG) && defined(__i386__)) -// TODO(fbarchard): fix build error on android_full_debug=1 -// https://code.google.com/p/libyuv/issues/detail?id=517 -#define HAS_I422ALPHATOARGBROW_AVX2 -#endif -#define HAS_I411TOARGBROW_AVX2 -#define HAS_I422TOARGB1555ROW_AVX2 -#define HAS_I422TOARGB4444ROW_AVX2 -#define HAS_I422TOARGBROW_AVX2 -#define HAS_I422TORGB24ROW_AVX2 -#define HAS_I422TORGB565ROW_AVX2 -#define HAS_I422TORGBAROW_AVX2 -#define HAS_I444TOARGBROW_AVX2 -#define HAS_INTERPOLATEROW_AVX2 -#define HAS_J422TOARGBROW_AVX2 -#define HAS_MERGEUVROW_AVX2 -#define HAS_MIRRORROW_AVX2 -#define HAS_NV12TOARGBROW_AVX2 -#define HAS_NV12TORGB565ROW_AVX2 -#define HAS_NV21TOARGBROW_AVX2 -#define HAS_SPLITUVROW_AVX2 -#define HAS_UYVYTOARGBROW_AVX2 -#define HAS_UYVYTOUV422ROW_AVX2 -#define HAS_UYVYTOUVROW_AVX2 -#define HAS_UYVYTOYROW_AVX2 -#define HAS_YUY2TOARGBROW_AVX2 -#define HAS_YUY2TOUV422ROW_AVX2 -#define HAS_YUY2TOUVROW_AVX2 -#define HAS_YUY2TOYROW_AVX2 -#define HAS_HALFFLOATROW_AVX2 - -// Effects: -#define HAS_ARGBADDROW_AVX2 -#define HAS_ARGBATTENUATEROW_AVX2 -#define HAS_ARGBMULTIPLYROW_AVX2 -#define HAS_ARGBSUBTRACTROW_AVX2 -#define HAS_ARGBUNATTENUATEROW_AVX2 -#define HAS_BLENDPLANEROW_AVX2 -#endif - -// The following are available for AVX2 Visual C and clangcl 32 bit: -// TODO(fbarchard): Port to gcc. -#if !defined(LIBYUV_DISABLE_X86) && defined(_M_IX86) && \ - (defined(VISUALC_HAS_AVX2) || defined(CLANG_HAS_AVX2)) -#define HAS_ARGB1555TOARGBROW_AVX2 -#define HAS_ARGB4444TOARGBROW_AVX2 -#define HAS_ARGBTOARGB1555ROW_AVX2 -#define HAS_ARGBTOARGB4444ROW_AVX2 -#define HAS_ARGBTORGB565ROW_AVX2 -#define HAS_J400TOARGBROW_AVX2 -#define HAS_RGB565TOARGBROW_AVX2 -#endif - -// The following are also available on x64 Visual C. -#if !defined(LIBYUV_DISABLE_X86) && defined(_MSC_VER) && defined(_M_X64) && \ - (!defined(__clang__) || defined(__SSSE3__)) -#define HAS_I422ALPHATOARGBROW_SSSE3 -#define HAS_I422TOARGBROW_SSSE3 -#endif - -// The following are available on gcc x86 platforms: -// TODO(fbarchard): Port to Visual C. -#if !defined(LIBYUV_DISABLE_X86) && \ - (defined(__x86_64__) || (defined(__i386__) && !defined(_MSC_VER))) -#define HAS_HALFFLOATROW_SSE2 -#endif - -// The following are available on Neon platforms: -#if !defined(LIBYUV_DISABLE_NEON) && \ - (defined(__aarch64__) || defined(__ARM_NEON__) || defined(LIBYUV_NEON)) -#define HAS_ABGRTOUVROW_NEON -#define HAS_ABGRTOYROW_NEON -#define HAS_ARGB1555TOARGBROW_NEON -#define HAS_ARGB1555TOUVROW_NEON -#define HAS_ARGB1555TOYROW_NEON -#define HAS_ARGB4444TOARGBROW_NEON -#define HAS_ARGB4444TOUVROW_NEON -#define HAS_ARGB4444TOYROW_NEON -#define HAS_ARGBSETROW_NEON -#define HAS_ARGBTOARGB1555ROW_NEON -#define HAS_ARGBTOARGB4444ROW_NEON -#define HAS_ARGBTORAWROW_NEON -#define HAS_ARGBTORGB24ROW_NEON -#define HAS_ARGBTORGB565DITHERROW_NEON -#define HAS_ARGBTORGB565ROW_NEON -#define HAS_ARGBTOUV411ROW_NEON -#define HAS_ARGBTOUV444ROW_NEON -#define HAS_ARGBTOUVJROW_NEON -#define HAS_ARGBTOUVROW_NEON -#define HAS_ARGBTOYJROW_NEON -#define HAS_ARGBTOYROW_NEON -#define HAS_ARGBEXTRACTALPHAROW_NEON -#define HAS_BGRATOUVROW_NEON -#define HAS_BGRATOYROW_NEON -#define HAS_COPYROW_NEON -#define HAS_I400TOARGBROW_NEON -#define HAS_I411TOARGBROW_NEON -#define HAS_I422ALPHATOARGBROW_NEON -#define HAS_I422TOARGB1555ROW_NEON -#define HAS_I422TOARGB4444ROW_NEON -#define HAS_I422TOARGBROW_NEON -#define HAS_I422TORGB24ROW_NEON -#define HAS_I422TORGB565ROW_NEON -#define HAS_I422TORGBAROW_NEON -#define HAS_I422TOUYVYROW_NEON -#define HAS_I422TOYUY2ROW_NEON -#define HAS_I444TOARGBROW_NEON -#define HAS_J400TOARGBROW_NEON -#define HAS_MERGEUVROW_NEON -#define HAS_MIRRORROW_NEON -#define HAS_MIRRORUVROW_NEON -#define HAS_NV12TOARGBROW_NEON -#define HAS_NV12TORGB565ROW_NEON -#define HAS_NV21TOARGBROW_NEON -#define HAS_RAWTOARGBROW_NEON -#define HAS_RAWTORGB24ROW_NEON -#define HAS_RAWTOUVROW_NEON -#define HAS_RAWTOYROW_NEON -#define HAS_RGB24TOARGBROW_NEON -#define HAS_RGB24TOUVROW_NEON -#define HAS_RGB24TOYROW_NEON -#define HAS_RGB565TOARGBROW_NEON -#define HAS_RGB565TOUVROW_NEON -#define HAS_RGB565TOYROW_NEON -#define HAS_RGBATOUVROW_NEON -#define HAS_RGBATOYROW_NEON -#define HAS_SETROW_NEON -#define HAS_SPLITUVROW_NEON -#define HAS_UYVYTOARGBROW_NEON -#define HAS_UYVYTOUV422ROW_NEON -#define HAS_UYVYTOUVROW_NEON -#define HAS_UYVYTOYROW_NEON -#define HAS_YUY2TOARGBROW_NEON -#define HAS_YUY2TOUV422ROW_NEON -#define HAS_YUY2TOUVROW_NEON -#define HAS_YUY2TOYROW_NEON - -// Effects: -#define HAS_ARGBADDROW_NEON -#define HAS_ARGBATTENUATEROW_NEON -#define HAS_ARGBBLENDROW_NEON -#define HAS_ARGBCOLORMATRIXROW_NEON -#define HAS_ARGBGRAYROW_NEON -#define HAS_ARGBMIRRORROW_NEON -#define HAS_ARGBMULTIPLYROW_NEON -#define HAS_ARGBQUANTIZEROW_NEON -#define HAS_ARGBSEPIAROW_NEON -#define HAS_ARGBSHADEROW_NEON -#define HAS_ARGBSHUFFLEROW_NEON -#define HAS_ARGBSUBTRACTROW_NEON -#define HAS_INTERPOLATEROW_NEON -#define HAS_SOBELROW_NEON -#define HAS_SOBELTOPLANEROW_NEON -#define HAS_SOBELXROW_NEON -#define HAS_SOBELXYROW_NEON -#define HAS_SOBELYROW_NEON -#endif - -// The following are available on Mips platforms: -#if !defined(LIBYUV_DISABLE_MIPS) && defined(__mips__) && \ - (_MIPS_SIM == _MIPS_SIM_ABI32) && (__mips_isa_rev < 6) -#define HAS_COPYROW_MIPS -#if defined(__mips_dsp) && (__mips_dsp_rev >= 2) -#define HAS_I422TOARGBROW_DSPR2 -#define HAS_INTERPOLATEROW_DSPR2 -#define HAS_MIRRORROW_DSPR2 -#define HAS_MIRRORUVROW_DSPR2 -#define HAS_SPLITUVROW_DSPR2 -#endif -#endif - -#if !defined(LIBYUV_DISABLE_MSA) && defined(__mips_msa) -#define HAS_MIRRORROW_MSA -#define HAS_ARGBMIRRORROW_MSA -#endif - -#if defined(_MSC_VER) && !defined(__CLR_VER) && !defined(__clang__) -#if defined(VISUALC_HAS_AVX2) -#define SIMD_ALIGNED(var) __declspec(align(32)) var -#else -#define SIMD_ALIGNED(var) __declspec(align(16)) var -#endif -typedef __declspec(align(16)) int16 vec16[8]; -typedef __declspec(align(16)) int32 vec32[4]; -typedef __declspec(align(16)) int8 vec8[16]; -typedef __declspec(align(16)) uint16 uvec16[8]; -typedef __declspec(align(16)) uint32 uvec32[4]; -typedef __declspec(align(16)) uint8 uvec8[16]; -typedef __declspec(align(32)) int16 lvec16[16]; -typedef __declspec(align(32)) int32 lvec32[8]; -typedef __declspec(align(32)) int8 lvec8[32]; -typedef __declspec(align(32)) uint16 ulvec16[16]; -typedef __declspec(align(32)) uint32 ulvec32[8]; -typedef __declspec(align(32)) uint8 ulvec8[32]; -#elif !defined(__pnacl__) && (defined(__GNUC__) || defined(__clang__)) -// Caveat GCC 4.2 to 4.7 have a known issue using vectors with const. -#if defined(CLANG_HAS_AVX2) || defined(GCC_HAS_AVX2) -#define SIMD_ALIGNED(var) var __attribute__((aligned(32))) -#else -#define SIMD_ALIGNED(var) var __attribute__((aligned(16))) -#endif -typedef int16 __attribute__((vector_size(16))) vec16; -typedef int32 __attribute__((vector_size(16))) vec32; -typedef int8 __attribute__((vector_size(16))) vec8; -typedef uint16 __attribute__((vector_size(16))) uvec16; -typedef uint32 __attribute__((vector_size(16))) uvec32; -typedef uint8 __attribute__((vector_size(16))) uvec8; -typedef int16 __attribute__((vector_size(32))) lvec16; -typedef int32 __attribute__((vector_size(32))) lvec32; -typedef int8 __attribute__((vector_size(32))) lvec8; -typedef uint16 __attribute__((vector_size(32))) ulvec16; -typedef uint32 __attribute__((vector_size(32))) ulvec32; -typedef uint8 __attribute__((vector_size(32))) ulvec8; -#else -#define SIMD_ALIGNED(var) var -typedef int16 vec16[8]; -typedef int32 vec32[4]; -typedef int8 vec8[16]; -typedef uint16 uvec16[8]; -typedef uint32 uvec32[4]; -typedef uint8 uvec8[16]; -typedef int16 lvec16[16]; -typedef int32 lvec32[8]; -typedef int8 lvec8[32]; -typedef uint16 ulvec16[16]; -typedef uint32 ulvec32[8]; -typedef uint8 ulvec8[32]; -#endif - -#if defined(__aarch64__) -// This struct is for Arm64 color conversion. -struct YuvConstants { - uvec16 kUVToRB; - uvec16 kUVToRB2; - uvec16 kUVToG; - uvec16 kUVToG2; - vec16 kUVBiasBGR; - vec32 kYToRgb; -}; -#elif defined(__arm__) -// This struct is for ArmV7 color conversion. -struct YuvConstants { - uvec8 kUVToRB; - uvec8 kUVToG; - vec16 kUVBiasBGR; - vec32 kYToRgb; -}; -#else -// This struct is for Intel color conversion. -struct YuvConstants { - int8 kUVToB[32]; - int8 kUVToG[32]; - int8 kUVToR[32]; - int16 kUVBiasB[16]; - int16 kUVBiasG[16]; - int16 kUVBiasR[16]; - int16 kYToRgb[16]; -}; - -// Offsets into YuvConstants structure -#define KUVTOB 0 -#define KUVTOG 32 -#define KUVTOR 64 -#define KUVBIASB 96 -#define KUVBIASG 128 -#define KUVBIASR 160 -#define KYTORGB 192 -#endif - -// Conversion matrix for YUV to RGB -extern const struct YuvConstants SIMD_ALIGNED(kYuvI601Constants); // BT.601 -extern const struct YuvConstants SIMD_ALIGNED(kYuvJPEGConstants); // JPeg -extern const struct YuvConstants SIMD_ALIGNED(kYuvH709Constants); // BT.709 - -// Conversion matrix for YVU to BGR -extern const struct YuvConstants SIMD_ALIGNED(kYvuI601Constants); // BT.601 -extern const struct YuvConstants SIMD_ALIGNED(kYvuJPEGConstants); // JPeg -extern const struct YuvConstants SIMD_ALIGNED(kYvuH709Constants); // BT.709 - -#if defined(__APPLE__) || defined(__x86_64__) || defined(__llvm__) -#define OMITFP -#else -#define OMITFP __attribute__((optimize("omit-frame-pointer"))) -#endif - -// NaCL macros for GCC x86 and x64. -#if defined(__native_client__) -#define LABELALIGN ".p2align 5\n" -#else -#define LABELALIGN -#endif -#if defined(__native_client__) && defined(__x86_64__) -// r14 is used for MEMOP macros. -#define NACL_R14 "r14", -#define BUNDLELOCK ".bundle_lock\n" -#define BUNDLEUNLOCK ".bundle_unlock\n" -#define MEMACCESS(base) "%%nacl:(%%r15,%q" #base ")" -#define MEMACCESS2(offset, base) "%%nacl:" #offset "(%%r15,%q" #base ")" -#define MEMLEA(offset, base) #offset "(%q" #base ")" -#define MEMLEA3(offset, index, scale) \ - #offset "(,%q" #index "," #scale ")" -#define MEMLEA4(offset, base, index, scale) \ - #offset "(%q" #base ",%q" #index "," #scale ")" -#define MEMMOVESTRING(s, d) "%%nacl:(%q" #s "),%%nacl:(%q" #d "), %%r15" -#define MEMSTORESTRING(reg, d) "%%" #reg ",%%nacl:(%q" #d "), %%r15" -#define MEMOPREG(opcode, offset, base, index, scale, reg) \ - BUNDLELOCK \ - "lea " #offset "(%q" #base ",%q" #index "," #scale "),%%r14d\n" \ - #opcode " (%%r15,%%r14),%%" #reg "\n" \ - BUNDLEUNLOCK -#define MEMOPMEM(opcode, reg, offset, base, index, scale) \ - BUNDLELOCK \ - "lea " #offset "(%q" #base ",%q" #index "," #scale "),%%r14d\n" \ - #opcode " %%" #reg ",(%%r15,%%r14)\n" \ - BUNDLEUNLOCK -#define MEMOPARG(opcode, offset, base, index, scale, arg) \ - BUNDLELOCK \ - "lea " #offset "(%q" #base ",%q" #index "," #scale "),%%r14d\n" \ - #opcode " (%%r15,%%r14),%" #arg "\n" \ - BUNDLEUNLOCK -#define VMEMOPREG(opcode, offset, base, index, scale, reg1, reg2) \ - BUNDLELOCK \ - "lea " #offset "(%q" #base ",%q" #index "," #scale "),%%r14d\n" \ - #opcode " (%%r15,%%r14),%%" #reg1 ",%%" #reg2 "\n" \ - BUNDLEUNLOCK -#define VEXTOPMEM(op, sel, reg, offset, base, index, scale) \ - BUNDLELOCK \ - "lea " #offset "(%q" #base ",%q" #index "," #scale "),%%r14d\n" \ - #op " $" #sel ",%%" #reg ",(%%r15,%%r14)\n" \ - BUNDLEUNLOCK -#else // defined(__native_client__) && defined(__x86_64__) -#define NACL_R14 -#define BUNDLEALIGN -#define MEMACCESS(base) "(%" #base ")" -#define MEMACCESS2(offset, base) #offset "(%" #base ")" -#define MEMLEA(offset, base) #offset "(%" #base ")" -#define MEMLEA3(offset, index, scale) \ - #offset "(,%" #index "," #scale ")" -#define MEMLEA4(offset, base, index, scale) \ - #offset "(%" #base ",%" #index "," #scale ")" -#define MEMMOVESTRING(s, d) -#define MEMSTORESTRING(reg, d) -#define MEMOPREG(opcode, offset, base, index, scale, reg) \ - #opcode " " #offset "(%" #base ",%" #index "," #scale "),%%" #reg "\n" -#define MEMOPMEM(opcode, reg, offset, base, index, scale) \ - #opcode " %%" #reg ","#offset "(%" #base ",%" #index "," #scale ")\n" -#define MEMOPARG(opcode, offset, base, index, scale, arg) \ - #opcode " " #offset "(%" #base ",%" #index "," #scale "),%" #arg "\n" -#define VMEMOPREG(opcode, offset, base, index, scale, reg1, reg2) \ - #opcode " " #offset "(%" #base ",%" #index "," #scale "),%%" #reg1 ",%%" \ - #reg2 "\n" -#define VEXTOPMEM(op, sel, reg, offset, base, index, scale) \ - #op " $" #sel ",%%" #reg ","#offset "(%" #base ",%" #index "," #scale ")\n" -#endif // defined(__native_client__) && defined(__x86_64__) - -#if defined(__arm__) || defined(__aarch64__) -#undef MEMACCESS -#if defined(__native_client__) -#define MEMACCESS(base) ".p2align 3\nbic %" #base ", #0xc0000000\n" -#else -#define MEMACCESS(base) -#endif -#endif - -void I444ToARGBRow_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGBRow_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422AlphaToARGBRow_NEON(const uint8* y_buf, - const uint8* u_buf, - const uint8* v_buf, - const uint8* a_buf, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGBRow_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I411ToARGBRow_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGBARow_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_rgba, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGB24Row_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_rgb24, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGB565Row_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_rgb565, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGB1555Row_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb1555, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGB4444Row_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb4444, - const struct YuvConstants* yuvconstants, - int width); -void NV12ToARGBRow_NEON(const uint8* src_y, - const uint8* src_uv, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void NV12ToRGB565Row_NEON(const uint8* src_y, - const uint8* src_uv, - uint8* dst_rgb565, - const struct YuvConstants* yuvconstants, - int width); -void NV21ToARGBRow_NEON(const uint8* src_y, - const uint8* src_vu, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void YUY2ToARGBRow_NEON(const uint8* src_yuy2, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void UYVYToARGBRow_NEON(const uint8* src_uyvy, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); - -void ARGBToYRow_AVX2(const uint8* src_argb, uint8* dst_y, int width); -void ARGBToYRow_Any_AVX2(const uint8* src_argb, uint8* dst_y, int width); -void ARGBToYRow_SSSE3(const uint8* src_argb, uint8* dst_y, int width); -void ARGBToYJRow_AVX2(const uint8* src_argb, uint8* dst_y, int width); -void ARGBToYJRow_Any_AVX2(const uint8* src_argb, uint8* dst_y, int width); -void ARGBToYJRow_SSSE3(const uint8* src_argb, uint8* dst_y, int width); -void BGRAToYRow_SSSE3(const uint8* src_bgra, uint8* dst_y, int width); -void ABGRToYRow_SSSE3(const uint8* src_abgr, uint8* dst_y, int width); -void RGBAToYRow_SSSE3(const uint8* src_rgba, uint8* dst_y, int width); -void RGB24ToYRow_SSSE3(const uint8* src_rgb24, uint8* dst_y, int width); -void RAWToYRow_SSSE3(const uint8* src_raw, uint8* dst_y, int width); -void ARGBToYRow_NEON(const uint8* src_argb, uint8* dst_y, int width); -void ARGBToYJRow_NEON(const uint8* src_argb, uint8* dst_y, int width); -void ARGBToUV444Row_NEON(const uint8* src_argb, uint8* dst_u, uint8* dst_v, - int width); -void ARGBToUV411Row_NEON(const uint8* src_argb, uint8* dst_u, uint8* dst_v, - int width); -void ARGBToUVRow_NEON(const uint8* src_argb, int src_stride_argb, - uint8* dst_u, uint8* dst_v, int width); -void ARGBToUVJRow_NEON(const uint8* src_argb, int src_stride_argb, - uint8* dst_u, uint8* dst_v, int width); -void BGRAToUVRow_NEON(const uint8* src_bgra, int src_stride_bgra, - uint8* dst_u, uint8* dst_v, int width); -void ABGRToUVRow_NEON(const uint8* src_abgr, int src_stride_abgr, - uint8* dst_u, uint8* dst_v, int width); -void RGBAToUVRow_NEON(const uint8* src_rgba, int src_stride_rgba, - uint8* dst_u, uint8* dst_v, int width); -void RGB24ToUVRow_NEON(const uint8* src_rgb24, int src_stride_rgb24, - uint8* dst_u, uint8* dst_v, int width); -void RAWToUVRow_NEON(const uint8* src_raw, int src_stride_raw, - uint8* dst_u, uint8* dst_v, int width); -void RGB565ToUVRow_NEON(const uint8* src_rgb565, int src_stride_rgb565, - uint8* dst_u, uint8* dst_v, int width); -void ARGB1555ToUVRow_NEON(const uint8* src_argb1555, int src_stride_argb1555, - uint8* dst_u, uint8* dst_v, int width); -void ARGB4444ToUVRow_NEON(const uint8* src_argb4444, int src_stride_argb4444, - uint8* dst_u, uint8* dst_v, int width); -void BGRAToYRow_NEON(const uint8* src_bgra, uint8* dst_y, int width); -void ABGRToYRow_NEON(const uint8* src_abgr, uint8* dst_y, int width); -void RGBAToYRow_NEON(const uint8* src_rgba, uint8* dst_y, int width); -void RGB24ToYRow_NEON(const uint8* src_rgb24, uint8* dst_y, int width); -void RAWToYRow_NEON(const uint8* src_raw, uint8* dst_y, int width); -void RGB565ToYRow_NEON(const uint8* src_rgb565, uint8* dst_y, int width); -void ARGB1555ToYRow_NEON(const uint8* src_argb1555, uint8* dst_y, int width); -void ARGB4444ToYRow_NEON(const uint8* src_argb4444, uint8* dst_y, int width); -void ARGBToYRow_C(const uint8* src_argb, uint8* dst_y, int width); -void ARGBToYJRow_C(const uint8* src_argb, uint8* dst_y, int width); -void BGRAToYRow_C(const uint8* src_bgra, uint8* dst_y, int width); -void ABGRToYRow_C(const uint8* src_abgr, uint8* dst_y, int width); -void RGBAToYRow_C(const uint8* src_rgba, uint8* dst_y, int width); -void RGB24ToYRow_C(const uint8* src_rgb24, uint8* dst_y, int width); -void RAWToYRow_C(const uint8* src_raw, uint8* dst_y, int width); -void RGB565ToYRow_C(const uint8* src_rgb565, uint8* dst_y, int width); -void ARGB1555ToYRow_C(const uint8* src_argb1555, uint8* dst_y, int width); -void ARGB4444ToYRow_C(const uint8* src_argb4444, uint8* dst_y, int width); -void ARGBToYRow_Any_SSSE3(const uint8* src_argb, uint8* dst_y, int width); -void ARGBToYJRow_Any_SSSE3(const uint8* src_argb, uint8* dst_y, int width); -void BGRAToYRow_Any_SSSE3(const uint8* src_bgra, uint8* dst_y, int width); -void ABGRToYRow_Any_SSSE3(const uint8* src_abgr, uint8* dst_y, int width); -void RGBAToYRow_Any_SSSE3(const uint8* src_rgba, uint8* dst_y, int width); -void RGB24ToYRow_Any_SSSE3(const uint8* src_rgb24, uint8* dst_y, int width); -void RAWToYRow_Any_SSSE3(const uint8* src_raw, uint8* dst_y, int width); -void ARGBToYRow_Any_NEON(const uint8* src_argb, uint8* dst_y, int width); -void ARGBToYJRow_Any_NEON(const uint8* src_argb, uint8* dst_y, int width); -void BGRAToYRow_Any_NEON(const uint8* src_bgra, uint8* dst_y, int width); -void ABGRToYRow_Any_NEON(const uint8* src_abgr, uint8* dst_y, int width); -void RGBAToYRow_Any_NEON(const uint8* src_rgba, uint8* dst_y, int width); -void RGB24ToYRow_Any_NEON(const uint8* src_rgb24, uint8* dst_y, int width); -void RAWToYRow_Any_NEON(const uint8* src_raw, uint8* dst_y, int width); -void RGB565ToYRow_Any_NEON(const uint8* src_rgb565, uint8* dst_y, int width); -void ARGB1555ToYRow_Any_NEON(const uint8* src_argb1555, uint8* dst_y, - int width); -void ARGB4444ToYRow_Any_NEON(const uint8* src_argb4444, uint8* dst_y, - int width); - -void ARGBToUVRow_AVX2(const uint8* src_argb, int src_stride_argb, - uint8* dst_u, uint8* dst_v, int width); -void ARGBToUVJRow_AVX2(const uint8* src_argb, int src_stride_argb, - uint8* dst_u, uint8* dst_v, int width); -void ARGBToUVRow_SSSE3(const uint8* src_argb, int src_stride_argb, - uint8* dst_u, uint8* dst_v, int width); -void ARGBToUVJRow_SSSE3(const uint8* src_argb, int src_stride_argb, - uint8* dst_u, uint8* dst_v, int width); -void BGRAToUVRow_SSSE3(const uint8* src_bgra, int src_stride_bgra, - uint8* dst_u, uint8* dst_v, int width); -void ABGRToUVRow_SSSE3(const uint8* src_abgr, int src_stride_abgr, - uint8* dst_u, uint8* dst_v, int width); -void RGBAToUVRow_SSSE3(const uint8* src_rgba, int src_stride_rgba, - uint8* dst_u, uint8* dst_v, int width); -void ARGBToUVRow_Any_AVX2(const uint8* src_argb, int src_stride_argb, - uint8* dst_u, uint8* dst_v, int width); -void ARGBToUVJRow_Any_AVX2(const uint8* src_argb, int src_stride_argb, - uint8* dst_u, uint8* dst_v, int width); -void ARGBToUVRow_Any_SSSE3(const uint8* src_argb, int src_stride_argb, - uint8* dst_u, uint8* dst_v, int width); -void ARGBToUVJRow_Any_SSSE3(const uint8* src_argb, int src_stride_argb, - uint8* dst_u, uint8* dst_v, int width); -void BGRAToUVRow_Any_SSSE3(const uint8* src_bgra, int src_stride_bgra, - uint8* dst_u, uint8* dst_v, int width); -void ABGRToUVRow_Any_SSSE3(const uint8* src_abgr, int src_stride_abgr, - uint8* dst_u, uint8* dst_v, int width); -void RGBAToUVRow_Any_SSSE3(const uint8* src_rgba, int src_stride_rgba, - uint8* dst_u, uint8* dst_v, int width); -void ARGBToUV444Row_Any_NEON(const uint8* src_argb, uint8* dst_u, uint8* dst_v, - int width); -void ARGBToUV411Row_Any_NEON(const uint8* src_argb, uint8* dst_u, uint8* dst_v, - int width); -void ARGBToUVRow_Any_NEON(const uint8* src_argb, int src_stride_argb, - uint8* dst_u, uint8* dst_v, int width); -void ARGBToUVJRow_Any_NEON(const uint8* src_argb, int src_stride_argb, - uint8* dst_u, uint8* dst_v, int width); -void BGRAToUVRow_Any_NEON(const uint8* src_bgra, int src_stride_bgra, - uint8* dst_u, uint8* dst_v, int width); -void ABGRToUVRow_Any_NEON(const uint8* src_abgr, int src_stride_abgr, - uint8* dst_u, uint8* dst_v, int width); -void RGBAToUVRow_Any_NEON(const uint8* src_rgba, int src_stride_rgba, - uint8* dst_u, uint8* dst_v, int width); -void RGB24ToUVRow_Any_NEON(const uint8* src_rgb24, int src_stride_rgb24, - uint8* dst_u, uint8* dst_v, int width); -void RAWToUVRow_Any_NEON(const uint8* src_raw, int src_stride_raw, - uint8* dst_u, uint8* dst_v, int width); -void RGB565ToUVRow_Any_NEON(const uint8* src_rgb565, int src_stride_rgb565, - uint8* dst_u, uint8* dst_v, int width); -void ARGB1555ToUVRow_Any_NEON(const uint8* src_argb1555, - int src_stride_argb1555, - uint8* dst_u, uint8* dst_v, int width); -void ARGB4444ToUVRow_Any_NEON(const uint8* src_argb4444, - int src_stride_argb4444, - uint8* dst_u, uint8* dst_v, int width); -void ARGBToUVRow_C(const uint8* src_argb, int src_stride_argb, - uint8* dst_u, uint8* dst_v, int width); -void ARGBToUVJRow_C(const uint8* src_argb, int src_stride_argb, - uint8* dst_u, uint8* dst_v, int width); -void BGRAToUVRow_C(const uint8* src_bgra, int src_stride_bgra, - uint8* dst_u, uint8* dst_v, int width); -void ABGRToUVRow_C(const uint8* src_abgr, int src_stride_abgr, - uint8* dst_u, uint8* dst_v, int width); -void RGBAToUVRow_C(const uint8* src_rgba, int src_stride_rgba, - uint8* dst_u, uint8* dst_v, int width); -void RGB24ToUVRow_C(const uint8* src_rgb24, int src_stride_rgb24, - uint8* dst_u, uint8* dst_v, int width); -void RAWToUVRow_C(const uint8* src_raw, int src_stride_raw, - uint8* dst_u, uint8* dst_v, int width); -void RGB565ToUVRow_C(const uint8* src_rgb565, int src_stride_rgb565, - uint8* dst_u, uint8* dst_v, int width); -void ARGB1555ToUVRow_C(const uint8* src_argb1555, int src_stride_argb1555, - uint8* dst_u, uint8* dst_v, int width); -void ARGB4444ToUVRow_C(const uint8* src_argb4444, int src_stride_argb4444, - uint8* dst_u, uint8* dst_v, int width); - -void ARGBToUV444Row_SSSE3(const uint8* src_argb, - uint8* dst_u, uint8* dst_v, int width); -void ARGBToUV444Row_Any_SSSE3(const uint8* src_argb, - uint8* dst_u, uint8* dst_v, int width); - -void ARGBToUV444Row_C(const uint8* src_argb, - uint8* dst_u, uint8* dst_v, int width); -void ARGBToUV411Row_C(const uint8* src_argb, - uint8* dst_u, uint8* dst_v, int width); - -void MirrorRow_AVX2(const uint8* src, uint8* dst, int width); -void MirrorRow_SSSE3(const uint8* src, uint8* dst, int width); -void MirrorRow_NEON(const uint8* src, uint8* dst, int width); -void MirrorRow_DSPR2(const uint8* src, uint8* dst, int width); -void MirrorRow_MSA(const uint8* src, uint8* dst, int width); -void MirrorRow_C(const uint8* src, uint8* dst, int width); -void MirrorRow_Any_AVX2(const uint8* src, uint8* dst, int width); -void MirrorRow_Any_SSSE3(const uint8* src, uint8* dst, int width); -void MirrorRow_Any_SSE2(const uint8* src, uint8* dst, int width); -void MirrorRow_Any_NEON(const uint8* src, uint8* dst, int width); -void MirrorRow_Any_MSA(const uint8* src, uint8* dst, int width); - -void MirrorUVRow_SSSE3(const uint8* src_uv, uint8* dst_u, uint8* dst_v, - int width); -void MirrorUVRow_NEON(const uint8* src_uv, uint8* dst_u, uint8* dst_v, - int width); -void MirrorUVRow_DSPR2(const uint8* src_uv, uint8* dst_u, uint8* dst_v, - int width); -void MirrorUVRow_C(const uint8* src_uv, uint8* dst_u, uint8* dst_v, int width); - -void ARGBMirrorRow_AVX2(const uint8* src, uint8* dst, int width); -void ARGBMirrorRow_SSE2(const uint8* src, uint8* dst, int width); -void ARGBMirrorRow_NEON(const uint8* src, uint8* dst, int width); -void ARGBMirrorRow_MSA(const uint8* src, uint8* dst, int width); -void ARGBMirrorRow_C(const uint8* src, uint8* dst, int width); -void ARGBMirrorRow_Any_AVX2(const uint8* src, uint8* dst, int width); -void ARGBMirrorRow_Any_SSE2(const uint8* src, uint8* dst, int width); -void ARGBMirrorRow_Any_NEON(const uint8* src, uint8* dst, int width); -void ARGBMirrorRow_Any_MSA(const uint8* src, uint8* dst, int width); - -void SplitUVRow_C(const uint8* src_uv, uint8* dst_u, uint8* dst_v, int width); -void SplitUVRow_SSE2(const uint8* src_uv, uint8* dst_u, uint8* dst_v, - int width); -void SplitUVRow_AVX2(const uint8* src_uv, uint8* dst_u, uint8* dst_v, - int width); -void SplitUVRow_NEON(const uint8* src_uv, uint8* dst_u, uint8* dst_v, - int width); -void SplitUVRow_DSPR2(const uint8* src_uv, uint8* dst_u, uint8* dst_v, - int width); -void SplitUVRow_Any_SSE2(const uint8* src_uv, uint8* dst_u, uint8* dst_v, - int width); -void SplitUVRow_Any_AVX2(const uint8* src_uv, uint8* dst_u, uint8* dst_v, - int width); -void SplitUVRow_Any_NEON(const uint8* src_uv, uint8* dst_u, uint8* dst_v, - int width); -void SplitUVRow_Any_DSPR2(const uint8* src_uv, uint8* dst_u, uint8* dst_v, - int width); - -void MergeUVRow_C(const uint8* src_u, const uint8* src_v, uint8* dst_uv, - int width); -void MergeUVRow_SSE2(const uint8* src_u, const uint8* src_v, uint8* dst_uv, - int width); -void MergeUVRow_AVX2(const uint8* src_u, const uint8* src_v, uint8* dst_uv, - int width); -void MergeUVRow_NEON(const uint8* src_u, const uint8* src_v, uint8* dst_uv, - int width); -void MergeUVRow_Any_SSE2(const uint8* src_u, const uint8* src_v, uint8* dst_uv, - int width); -void MergeUVRow_Any_AVX2(const uint8* src_u, const uint8* src_v, uint8* dst_uv, - int width); -void MergeUVRow_Any_NEON(const uint8* src_u, const uint8* src_v, uint8* dst_uv, - int width); - -void CopyRow_SSE2(const uint8* src, uint8* dst, int count); -void CopyRow_AVX(const uint8* src, uint8* dst, int count); -void CopyRow_ERMS(const uint8* src, uint8* dst, int count); -void CopyRow_NEON(const uint8* src, uint8* dst, int count); -void CopyRow_MIPS(const uint8* src, uint8* dst, int count); -void CopyRow_C(const uint8* src, uint8* dst, int count); -void CopyRow_Any_SSE2(const uint8* src, uint8* dst, int count); -void CopyRow_Any_AVX(const uint8* src, uint8* dst, int count); -void CopyRow_Any_NEON(const uint8* src, uint8* dst, int count); - -void CopyRow_16_C(const uint16* src, uint16* dst, int count); - -void ARGBCopyAlphaRow_C(const uint8* src_argb, uint8* dst_argb, int width); -void ARGBCopyAlphaRow_SSE2(const uint8* src_argb, uint8* dst_argb, int width); -void ARGBCopyAlphaRow_AVX2(const uint8* src_argb, uint8* dst_argb, int width); -void ARGBCopyAlphaRow_Any_SSE2(const uint8* src_argb, uint8* dst_argb, - int width); -void ARGBCopyAlphaRow_Any_AVX2(const uint8* src_argb, uint8* dst_argb, - int width); - -void ARGBExtractAlphaRow_C(const uint8* src_argb, uint8* dst_a, int width); -void ARGBExtractAlphaRow_SSE2(const uint8* src_argb, uint8* dst_a, int width); -void ARGBExtractAlphaRow_NEON(const uint8* src_argb, uint8* dst_a, int width); -void ARGBExtractAlphaRow_Any_SSE2(const uint8* src_argb, uint8* dst_a, - int width); -void ARGBExtractAlphaRow_Any_NEON(const uint8* src_argb, uint8* dst_a, - int width); - -void ARGBCopyYToAlphaRow_C(const uint8* src_y, uint8* dst_argb, int width); -void ARGBCopyYToAlphaRow_SSE2(const uint8* src_y, uint8* dst_argb, int width); -void ARGBCopyYToAlphaRow_AVX2(const uint8* src_y, uint8* dst_argb, int width); -void ARGBCopyYToAlphaRow_Any_SSE2(const uint8* src_y, uint8* dst_argb, - int width); -void ARGBCopyYToAlphaRow_Any_AVX2(const uint8* src_y, uint8* dst_argb, - int width); - -void SetRow_C(uint8* dst, uint8 v8, int count); -void SetRow_X86(uint8* dst, uint8 v8, int count); -void SetRow_ERMS(uint8* dst, uint8 v8, int count); -void SetRow_NEON(uint8* dst, uint8 v8, int count); -void SetRow_Any_X86(uint8* dst, uint8 v8, int count); -void SetRow_Any_NEON(uint8* dst, uint8 v8, int count); - -void ARGBSetRow_C(uint8* dst_argb, uint32 v32, int count); -void ARGBSetRow_X86(uint8* dst_argb, uint32 v32, int count); -void ARGBSetRow_NEON(uint8* dst_argb, uint32 v32, int count); -void ARGBSetRow_Any_NEON(uint8* dst_argb, uint32 v32, int count); - -// ARGBShufflers for BGRAToARGB etc. -void ARGBShuffleRow_C(const uint8* src_argb, uint8* dst_argb, - const uint8* shuffler, int width); -void ARGBShuffleRow_SSE2(const uint8* src_argb, uint8* dst_argb, - const uint8* shuffler, int width); -void ARGBShuffleRow_SSSE3(const uint8* src_argb, uint8* dst_argb, - const uint8* shuffler, int width); -void ARGBShuffleRow_AVX2(const uint8* src_argb, uint8* dst_argb, - const uint8* shuffler, int width); -void ARGBShuffleRow_NEON(const uint8* src_argb, uint8* dst_argb, - const uint8* shuffler, int width); -void ARGBShuffleRow_Any_SSE2(const uint8* src_argb, uint8* dst_argb, - const uint8* shuffler, int width); -void ARGBShuffleRow_Any_SSSE3(const uint8* src_argb, uint8* dst_argb, - const uint8* shuffler, int width); -void ARGBShuffleRow_Any_AVX2(const uint8* src_argb, uint8* dst_argb, - const uint8* shuffler, int width); -void ARGBShuffleRow_Any_NEON(const uint8* src_argb, uint8* dst_argb, - const uint8* shuffler, int width); - -void RGB24ToARGBRow_SSSE3(const uint8* src_rgb24, uint8* dst_argb, int width); -void RAWToARGBRow_SSSE3(const uint8* src_raw, uint8* dst_argb, int width); -void RAWToRGB24Row_SSSE3(const uint8* src_raw, uint8* dst_rgb24, int width); -void RGB565ToARGBRow_SSE2(const uint8* src_rgb565, uint8* dst_argb, int width); -void ARGB1555ToARGBRow_SSE2(const uint8* src_argb1555, uint8* dst_argb, - int width); -void ARGB4444ToARGBRow_SSE2(const uint8* src_argb4444, uint8* dst_argb, - int width); -void RGB565ToARGBRow_AVX2(const uint8* src_rgb565, uint8* dst_argb, int width); -void ARGB1555ToARGBRow_AVX2(const uint8* src_argb1555, uint8* dst_argb, - int width); -void ARGB4444ToARGBRow_AVX2(const uint8* src_argb4444, uint8* dst_argb, - int width); - -void RGB24ToARGBRow_NEON(const uint8* src_rgb24, uint8* dst_argb, int width); -void RAWToARGBRow_NEON(const uint8* src_raw, uint8* dst_argb, int width); -void RAWToRGB24Row_NEON(const uint8* src_raw, uint8* dst_rgb24, int width); -void RGB565ToARGBRow_NEON(const uint8* src_rgb565, uint8* dst_argb, int width); -void ARGB1555ToARGBRow_NEON(const uint8* src_argb1555, uint8* dst_argb, - int width); -void ARGB4444ToARGBRow_NEON(const uint8* src_argb4444, uint8* dst_argb, - int width); -void RGB24ToARGBRow_C(const uint8* src_rgb24, uint8* dst_argb, int width); -void RAWToARGBRow_C(const uint8* src_raw, uint8* dst_argb, int width); -void RAWToRGB24Row_C(const uint8* src_raw, uint8* dst_rgb24, int width); -void RGB565ToARGBRow_C(const uint8* src_rgb, uint8* dst_argb, int width); -void ARGB1555ToARGBRow_C(const uint8* src_argb, uint8* dst_argb, int width); -void ARGB4444ToARGBRow_C(const uint8* src_argb, uint8* dst_argb, int width); -void RGB24ToARGBRow_Any_SSSE3(const uint8* src_rgb24, uint8* dst_argb, - int width); -void RAWToARGBRow_Any_SSSE3(const uint8* src_raw, uint8* dst_argb, int width); -void RAWToRGB24Row_Any_SSSE3(const uint8* src_raw, uint8* dst_rgb24, int width); - -void RGB565ToARGBRow_Any_SSE2(const uint8* src_rgb565, uint8* dst_argb, - int width); -void ARGB1555ToARGBRow_Any_SSE2(const uint8* src_argb1555, uint8* dst_argb, - int width); -void ARGB4444ToARGBRow_Any_SSE2(const uint8* src_argb4444, uint8* dst_argb, - int width); -void RGB565ToARGBRow_Any_AVX2(const uint8* src_rgb565, uint8* dst_argb, - int width); -void ARGB1555ToARGBRow_Any_AVX2(const uint8* src_argb1555, uint8* dst_argb, - int width); -void ARGB4444ToARGBRow_Any_AVX2(const uint8* src_argb4444, uint8* dst_argb, - int width); - -void RGB24ToARGBRow_Any_NEON(const uint8* src_rgb24, uint8* dst_argb, - int width); -void RAWToARGBRow_Any_NEON(const uint8* src_raw, uint8* dst_argb, int width); -void RAWToRGB24Row_Any_NEON(const uint8* src_raw, uint8* dst_rgb24, int width); -void RGB565ToARGBRow_Any_NEON(const uint8* src_rgb565, uint8* dst_argb, - int width); -void ARGB1555ToARGBRow_Any_NEON(const uint8* src_argb1555, uint8* dst_argb, - int width); -void ARGB4444ToARGBRow_Any_NEON(const uint8* src_argb4444, uint8* dst_argb, - int width); - -void ARGBToRGB24Row_SSSE3(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToRAWRow_SSSE3(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToRGB565Row_SSE2(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToARGB1555Row_SSE2(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToARGB4444Row_SSE2(const uint8* src_argb, uint8* dst_rgb, int width); - -void ARGBToRGB565DitherRow_C(const uint8* src_argb, uint8* dst_rgb, - const uint32 dither4, int width); -void ARGBToRGB565DitherRow_SSE2(const uint8* src_argb, uint8* dst_rgb, - const uint32 dither4, int width); -void ARGBToRGB565DitherRow_AVX2(const uint8* src_argb, uint8* dst_rgb, - const uint32 dither4, int width); - -void ARGBToRGB565Row_AVX2(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToARGB1555Row_AVX2(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToARGB4444Row_AVX2(const uint8* src_argb, uint8* dst_rgb, int width); - -void ARGBToRGB24Row_NEON(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToRAWRow_NEON(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToRGB565Row_NEON(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToARGB1555Row_NEON(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToARGB4444Row_NEON(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToRGB565DitherRow_NEON(const uint8* src_argb, uint8* dst_rgb, - const uint32 dither4, int width); - -void ARGBToRGBARow_C(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToRGB24Row_C(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToRAWRow_C(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToRGB565Row_C(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToARGB1555Row_C(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToARGB4444Row_C(const uint8* src_argb, uint8* dst_rgb, int width); - -void J400ToARGBRow_SSE2(const uint8* src_y, uint8* dst_argb, int width); -void J400ToARGBRow_AVX2(const uint8* src_y, uint8* dst_argb, int width); -void J400ToARGBRow_NEON(const uint8* src_y, uint8* dst_argb, int width); -void J400ToARGBRow_C(const uint8* src_y, uint8* dst_argb, int width); -void J400ToARGBRow_Any_SSE2(const uint8* src_y, uint8* dst_argb, int width); -void J400ToARGBRow_Any_AVX2(const uint8* src_y, uint8* dst_argb, int width); -void J400ToARGBRow_Any_NEON(const uint8* src_y, uint8* dst_argb, int width); - -void I444ToARGBRow_C(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGBRow_C(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGBRow_C(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422AlphaToARGBRow_C(const uint8* y_buf, - const uint8* u_buf, - const uint8* v_buf, - const uint8* a_buf, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I411ToARGBRow_C(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void NV12ToARGBRow_C(const uint8* src_y, - const uint8* src_uv, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void NV12ToRGB565Row_C(const uint8* src_y, - const uint8* src_uv, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void NV21ToARGBRow_C(const uint8* src_y, - const uint8* src_uv, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void YUY2ToARGBRow_C(const uint8* src_yuy2, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void UYVYToARGBRow_C(const uint8* src_uyvy, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGBARow_C(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_rgba, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGB24Row_C(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_rgb24, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGB4444Row_C(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb4444, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGB1555Row_C(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb4444, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGB565Row_C(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_rgb565, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGBRow_AVX2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGBRow_AVX2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGBARow_AVX2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I444ToARGBRow_SSSE3(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I444ToARGBRow_AVX2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I444ToARGBRow_SSSE3(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I444ToARGBRow_AVX2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGBRow_SSSE3(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422AlphaToARGBRow_SSSE3(const uint8* y_buf, - const uint8* u_buf, - const uint8* v_buf, - const uint8* a_buf, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422AlphaToARGBRow_AVX2(const uint8* y_buf, - const uint8* u_buf, - const uint8* v_buf, - const uint8* a_buf, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGBRow_SSSE3(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I411ToARGBRow_SSSE3(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I411ToARGBRow_AVX2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void NV12ToARGBRow_SSSE3(const uint8* src_y, - const uint8* src_uv, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void NV12ToARGBRow_AVX2(const uint8* src_y, - const uint8* src_uv, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void NV12ToRGB565Row_SSSE3(const uint8* src_y, - const uint8* src_uv, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void NV12ToRGB565Row_AVX2(const uint8* src_y, - const uint8* src_uv, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void NV21ToARGBRow_SSSE3(const uint8* src_y, - const uint8* src_uv, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void NV21ToARGBRow_AVX2(const uint8* src_y, - const uint8* src_uv, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void YUY2ToARGBRow_SSSE3(const uint8* src_yuy2, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void UYVYToARGBRow_SSSE3(const uint8* src_uyvy, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void YUY2ToARGBRow_AVX2(const uint8* src_yuy2, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void UYVYToARGBRow_AVX2(const uint8* src_uyvy, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGBARow_SSSE3(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_rgba, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGB4444Row_SSSE3(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGB4444Row_AVX2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGB1555Row_SSSE3(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGB1555Row_AVX2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGB565Row_SSSE3(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGB565Row_AVX2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGB24Row_SSSE3(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_rgb24, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGB24Row_AVX2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_rgb24, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGBRow_Any_AVX2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGBARow_Any_AVX2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I444ToARGBRow_Any_SSSE3(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I444ToARGBRow_Any_AVX2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGBRow_Any_SSSE3(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422AlphaToARGBRow_Any_SSSE3(const uint8* y_buf, - const uint8* u_buf, - const uint8* v_buf, - const uint8* a_buf, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422AlphaToARGBRow_Any_AVX2(const uint8* y_buf, - const uint8* u_buf, - const uint8* v_buf, - const uint8* a_buf, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I411ToARGBRow_Any_SSSE3(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I411ToARGBRow_Any_AVX2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void NV12ToARGBRow_Any_SSSE3(const uint8* src_y, - const uint8* src_uv, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void NV12ToARGBRow_Any_AVX2(const uint8* src_y, - const uint8* src_uv, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void NV21ToARGBRow_Any_SSSE3(const uint8* src_y, - const uint8* src_vu, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void NV21ToARGBRow_Any_AVX2(const uint8* src_y, - const uint8* src_vu, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void NV12ToRGB565Row_Any_SSSE3(const uint8* src_y, - const uint8* src_uv, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void NV12ToRGB565Row_Any_AVX2(const uint8* src_y, - const uint8* src_uv, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void YUY2ToARGBRow_Any_SSSE3(const uint8* src_yuy2, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void UYVYToARGBRow_Any_SSSE3(const uint8* src_uyvy, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void YUY2ToARGBRow_Any_AVX2(const uint8* src_yuy2, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void UYVYToARGBRow_Any_AVX2(const uint8* src_uyvy, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGBARow_Any_SSSE3(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_rgba, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGB4444Row_Any_SSSE3(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_rgba, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGB4444Row_Any_AVX2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_rgba, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGB1555Row_Any_SSSE3(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_rgba, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGB1555Row_Any_AVX2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_rgba, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGB565Row_Any_SSSE3(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_rgba, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGB565Row_Any_AVX2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_rgba, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGB24Row_Any_SSSE3(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGB24Row_Any_AVX2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); - -void I400ToARGBRow_C(const uint8* src_y, uint8* dst_argb, int width); -void I400ToARGBRow_SSE2(const uint8* src_y, uint8* dst_argb, int width); -void I400ToARGBRow_AVX2(const uint8* src_y, uint8* dst_argb, int width); -void I400ToARGBRow_NEON(const uint8* src_y, uint8* dst_argb, int width); -void I400ToARGBRow_Any_SSE2(const uint8* src_y, uint8* dst_argb, int width); -void I400ToARGBRow_Any_AVX2(const uint8* src_y, uint8* dst_argb, int width); -void I400ToARGBRow_Any_NEON(const uint8* src_y, uint8* dst_argb, int width); - -// ARGB preattenuated alpha blend. -void ARGBBlendRow_SSSE3(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); -void ARGBBlendRow_NEON(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); -void ARGBBlendRow_C(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); - -// Unattenuated planar alpha blend. -void BlendPlaneRow_SSSE3(const uint8* src0, const uint8* src1, - const uint8* alpha, uint8* dst, int width); -void BlendPlaneRow_Any_SSSE3(const uint8* src0, const uint8* src1, - const uint8* alpha, uint8* dst, int width); -void BlendPlaneRow_AVX2(const uint8* src0, const uint8* src1, - const uint8* alpha, uint8* dst, int width); -void BlendPlaneRow_Any_AVX2(const uint8* src0, const uint8* src1, - const uint8* alpha, uint8* dst, int width); -void BlendPlaneRow_C(const uint8* src0, const uint8* src1, - const uint8* alpha, uint8* dst, int width); - -// ARGB multiply images. Same API as Blend, but these require -// pointer and width alignment for SSE2. -void ARGBMultiplyRow_C(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); -void ARGBMultiplyRow_SSE2(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); -void ARGBMultiplyRow_Any_SSE2(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); -void ARGBMultiplyRow_AVX2(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); -void ARGBMultiplyRow_Any_AVX2(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); -void ARGBMultiplyRow_NEON(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); -void ARGBMultiplyRow_Any_NEON(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); - -// ARGB add images. -void ARGBAddRow_C(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); -void ARGBAddRow_SSE2(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); -void ARGBAddRow_Any_SSE2(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); -void ARGBAddRow_AVX2(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); -void ARGBAddRow_Any_AVX2(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); -void ARGBAddRow_NEON(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); -void ARGBAddRow_Any_NEON(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); - -// ARGB subtract images. Same API as Blend, but these require -// pointer and width alignment for SSE2. -void ARGBSubtractRow_C(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); -void ARGBSubtractRow_SSE2(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); -void ARGBSubtractRow_Any_SSE2(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); -void ARGBSubtractRow_AVX2(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); -void ARGBSubtractRow_Any_AVX2(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); -void ARGBSubtractRow_NEON(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); -void ARGBSubtractRow_Any_NEON(const uint8* src_argb, const uint8* src_argb1, - uint8* dst_argb, int width); - -void ARGBToRGB24Row_Any_SSSE3(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToRAWRow_Any_SSSE3(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToRGB565Row_Any_SSE2(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToARGB1555Row_Any_SSE2(const uint8* src_argb, uint8* dst_rgb, - int width); -void ARGBToARGB4444Row_Any_SSE2(const uint8* src_argb, uint8* dst_rgb, - int width); - -void ARGBToRGB565DitherRow_Any_SSE2(const uint8* src_argb, uint8* dst_rgb, - const uint32 dither4, int width); -void ARGBToRGB565DitherRow_Any_AVX2(const uint8* src_argb, uint8* dst_rgb, - const uint32 dither4, int width); - -void ARGBToRGB565Row_Any_AVX2(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToARGB1555Row_Any_AVX2(const uint8* src_argb, uint8* dst_rgb, - int width); -void ARGBToARGB4444Row_Any_AVX2(const uint8* src_argb, uint8* dst_rgb, - int width); - -void ARGBToRGB24Row_Any_NEON(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToRAWRow_Any_NEON(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToRGB565Row_Any_NEON(const uint8* src_argb, uint8* dst_rgb, int width); -void ARGBToARGB1555Row_Any_NEON(const uint8* src_argb, uint8* dst_rgb, - int width); -void ARGBToARGB4444Row_Any_NEON(const uint8* src_argb, uint8* dst_rgb, - int width); -void ARGBToRGB565DitherRow_Any_NEON(const uint8* src_argb, uint8* dst_rgb, - const uint32 dither4, int width); - -void I444ToARGBRow_Any_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGBRow_Any_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422AlphaToARGBRow_Any_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - const uint8* src_a, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I411ToARGBRow_Any_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGBARow_Any_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGB24Row_Any_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGB4444Row_Any_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGB1555Row_Any_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToRGB565Row_Any_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void NV12ToARGBRow_Any_NEON(const uint8* src_y, - const uint8* src_uv, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void NV21ToARGBRow_Any_NEON(const uint8* src_y, - const uint8* src_vu, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void NV12ToRGB565Row_Any_NEON(const uint8* src_y, - const uint8* src_uv, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void YUY2ToARGBRow_Any_NEON(const uint8* src_yuy2, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void UYVYToARGBRow_Any_NEON(const uint8* src_uyvy, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGBRow_DSPR2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); -void I422ToARGBRow_DSPR2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_argb, - const struct YuvConstants* yuvconstants, - int width); - -void YUY2ToYRow_AVX2(const uint8* src_yuy2, uint8* dst_y, int width); -void YUY2ToUVRow_AVX2(const uint8* src_yuy2, int stride_yuy2, - uint8* dst_u, uint8* dst_v, int width); -void YUY2ToUV422Row_AVX2(const uint8* src_yuy2, - uint8* dst_u, uint8* dst_v, int width); -void YUY2ToYRow_SSE2(const uint8* src_yuy2, uint8* dst_y, int width); -void YUY2ToUVRow_SSE2(const uint8* src_yuy2, int stride_yuy2, - uint8* dst_u, uint8* dst_v, int width); -void YUY2ToUV422Row_SSE2(const uint8* src_yuy2, - uint8* dst_u, uint8* dst_v, int width); -void YUY2ToYRow_NEON(const uint8* src_yuy2, uint8* dst_y, int width); -void YUY2ToUVRow_NEON(const uint8* src_yuy2, int stride_yuy2, - uint8* dst_u, uint8* dst_v, int width); -void YUY2ToUV422Row_NEON(const uint8* src_yuy2, - uint8* dst_u, uint8* dst_v, int width); -void YUY2ToYRow_C(const uint8* src_yuy2, uint8* dst_y, int width); -void YUY2ToUVRow_C(const uint8* src_yuy2, int stride_yuy2, - uint8* dst_u, uint8* dst_v, int width); -void YUY2ToUV422Row_C(const uint8* src_yuy2, - uint8* dst_u, uint8* dst_v, int width); -void YUY2ToYRow_Any_AVX2(const uint8* src_yuy2, uint8* dst_y, int width); -void YUY2ToUVRow_Any_AVX2(const uint8* src_yuy2, int stride_yuy2, - uint8* dst_u, uint8* dst_v, int width); -void YUY2ToUV422Row_Any_AVX2(const uint8* src_yuy2, - uint8* dst_u, uint8* dst_v, int width); -void YUY2ToYRow_Any_SSE2(const uint8* src_yuy2, uint8* dst_y, int width); -void YUY2ToUVRow_Any_SSE2(const uint8* src_yuy2, int stride_yuy2, - uint8* dst_u, uint8* dst_v, int width); -void YUY2ToUV422Row_Any_SSE2(const uint8* src_yuy2, - uint8* dst_u, uint8* dst_v, int width); -void YUY2ToYRow_Any_NEON(const uint8* src_yuy2, uint8* dst_y, int width); -void YUY2ToUVRow_Any_NEON(const uint8* src_yuy2, int stride_yuy2, - uint8* dst_u, uint8* dst_v, int width); -void YUY2ToUV422Row_Any_NEON(const uint8* src_yuy2, - uint8* dst_u, uint8* dst_v, int width); -void UYVYToYRow_AVX2(const uint8* src_uyvy, uint8* dst_y, int width); -void UYVYToUVRow_AVX2(const uint8* src_uyvy, int stride_uyvy, - uint8* dst_u, uint8* dst_v, int width); -void UYVYToUV422Row_AVX2(const uint8* src_uyvy, - uint8* dst_u, uint8* dst_v, int width); -void UYVYToYRow_SSE2(const uint8* src_uyvy, uint8* dst_y, int width); -void UYVYToUVRow_SSE2(const uint8* src_uyvy, int stride_uyvy, - uint8* dst_u, uint8* dst_v, int width); -void UYVYToUV422Row_SSE2(const uint8* src_uyvy, - uint8* dst_u, uint8* dst_v, int width); -void UYVYToYRow_AVX2(const uint8* src_uyvy, uint8* dst_y, int width); -void UYVYToUVRow_AVX2(const uint8* src_uyvy, int stride_uyvy, - uint8* dst_u, uint8* dst_v, int width); -void UYVYToUV422Row_AVX2(const uint8* src_uyvy, - uint8* dst_u, uint8* dst_v, int width); -void UYVYToYRow_NEON(const uint8* src_uyvy, uint8* dst_y, int width); -void UYVYToUVRow_NEON(const uint8* src_uyvy, int stride_uyvy, - uint8* dst_u, uint8* dst_v, int width); -void UYVYToUV422Row_NEON(const uint8* src_uyvy, - uint8* dst_u, uint8* dst_v, int width); - -void UYVYToYRow_C(const uint8* src_uyvy, uint8* dst_y, int width); -void UYVYToUVRow_C(const uint8* src_uyvy, int stride_uyvy, - uint8* dst_u, uint8* dst_v, int width); -void UYVYToUV422Row_C(const uint8* src_uyvy, - uint8* dst_u, uint8* dst_v, int width); -void UYVYToYRow_Any_AVX2(const uint8* src_uyvy, uint8* dst_y, int width); -void UYVYToUVRow_Any_AVX2(const uint8* src_uyvy, int stride_uyvy, - uint8* dst_u, uint8* dst_v, int width); -void UYVYToUV422Row_Any_AVX2(const uint8* src_uyvy, - uint8* dst_u, uint8* dst_v, int width); -void UYVYToYRow_Any_SSE2(const uint8* src_uyvy, uint8* dst_y, int width); -void UYVYToUVRow_Any_SSE2(const uint8* src_uyvy, int stride_uyvy, - uint8* dst_u, uint8* dst_v, int width); -void UYVYToUV422Row_Any_SSE2(const uint8* src_uyvy, - uint8* dst_u, uint8* dst_v, int width); -void UYVYToYRow_Any_NEON(const uint8* src_uyvy, uint8* dst_y, int width); -void UYVYToUVRow_Any_NEON(const uint8* src_uyvy, int stride_uyvy, - uint8* dst_u, uint8* dst_v, int width); -void UYVYToUV422Row_Any_NEON(const uint8* src_uyvy, - uint8* dst_u, uint8* dst_v, int width); - -void I422ToYUY2Row_C(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_yuy2, int width); -void I422ToUYVYRow_C(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_uyvy, int width); -void I422ToYUY2Row_SSE2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_yuy2, int width); -void I422ToUYVYRow_SSE2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_uyvy, int width); -void I422ToYUY2Row_Any_SSE2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_yuy2, int width); -void I422ToUYVYRow_Any_SSE2(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_uyvy, int width); -void I422ToYUY2Row_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_yuy2, int width); -void I422ToUYVYRow_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_uyvy, int width); -void I422ToYUY2Row_Any_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_yuy2, int width); -void I422ToUYVYRow_Any_NEON(const uint8* src_y, - const uint8* src_u, - const uint8* src_v, - uint8* dst_uyvy, int width); - -// Effects related row functions. -void ARGBAttenuateRow_C(const uint8* src_argb, uint8* dst_argb, int width); -void ARGBAttenuateRow_SSSE3(const uint8* src_argb, uint8* dst_argb, int width); -void ARGBAttenuateRow_AVX2(const uint8* src_argb, uint8* dst_argb, int width); -void ARGBAttenuateRow_NEON(const uint8* src_argb, uint8* dst_argb, int width); -void ARGBAttenuateRow_Any_SSE2(const uint8* src_argb, uint8* dst_argb, - int width); -void ARGBAttenuateRow_Any_SSSE3(const uint8* src_argb, uint8* dst_argb, - int width); -void ARGBAttenuateRow_Any_AVX2(const uint8* src_argb, uint8* dst_argb, - int width); -void ARGBAttenuateRow_Any_NEON(const uint8* src_argb, uint8* dst_argb, - int width); - -// Inverse table for unattenuate, shared by C and SSE2. -extern const uint32 fixed_invtbl8[256]; -void ARGBUnattenuateRow_C(const uint8* src_argb, uint8* dst_argb, int width); -void ARGBUnattenuateRow_SSE2(const uint8* src_argb, uint8* dst_argb, int width); -void ARGBUnattenuateRow_AVX2(const uint8* src_argb, uint8* dst_argb, int width); -void ARGBUnattenuateRow_Any_SSE2(const uint8* src_argb, uint8* dst_argb, - int width); -void ARGBUnattenuateRow_Any_AVX2(const uint8* src_argb, uint8* dst_argb, - int width); - -void ARGBGrayRow_C(const uint8* src_argb, uint8* dst_argb, int width); -void ARGBGrayRow_SSSE3(const uint8* src_argb, uint8* dst_argb, int width); -void ARGBGrayRow_NEON(const uint8* src_argb, uint8* dst_argb, int width); - -void ARGBSepiaRow_C(uint8* dst_argb, int width); -void ARGBSepiaRow_SSSE3(uint8* dst_argb, int width); -void ARGBSepiaRow_NEON(uint8* dst_argb, int width); - -void ARGBColorMatrixRow_C(const uint8* src_argb, uint8* dst_argb, - const int8* matrix_argb, int width); -void ARGBColorMatrixRow_SSSE3(const uint8* src_argb, uint8* dst_argb, - const int8* matrix_argb, int width); -void ARGBColorMatrixRow_NEON(const uint8* src_argb, uint8* dst_argb, - const int8* matrix_argb, int width); - -void ARGBColorTableRow_C(uint8* dst_argb, const uint8* table_argb, int width); -void ARGBColorTableRow_X86(uint8* dst_argb, const uint8* table_argb, int width); - -void RGBColorTableRow_C(uint8* dst_argb, const uint8* table_argb, int width); -void RGBColorTableRow_X86(uint8* dst_argb, const uint8* table_argb, int width); - -void ARGBQuantizeRow_C(uint8* dst_argb, int scale, int interval_size, - int interval_offset, int width); -void ARGBQuantizeRow_SSE2(uint8* dst_argb, int scale, int interval_size, - int interval_offset, int width); -void ARGBQuantizeRow_NEON(uint8* dst_argb, int scale, int interval_size, - int interval_offset, int width); - -void ARGBShadeRow_C(const uint8* src_argb, uint8* dst_argb, int width, - uint32 value); -void ARGBShadeRow_SSE2(const uint8* src_argb, uint8* dst_argb, int width, - uint32 value); -void ARGBShadeRow_NEON(const uint8* src_argb, uint8* dst_argb, int width, - uint32 value); - -// Used for blur. -void CumulativeSumToAverageRow_SSE2(const int32* topleft, const int32* botleft, - int width, int area, uint8* dst, int count); -void ComputeCumulativeSumRow_SSE2(const uint8* row, int32* cumsum, - const int32* previous_cumsum, int width); - -void CumulativeSumToAverageRow_C(const int32* topleft, const int32* botleft, - int width, int area, uint8* dst, int count); -void ComputeCumulativeSumRow_C(const uint8* row, int32* cumsum, - const int32* previous_cumsum, int width); - -LIBYUV_API -void ARGBAffineRow_C(const uint8* src_argb, int src_argb_stride, - uint8* dst_argb, const float* uv_dudv, int width); -LIBYUV_API -void ARGBAffineRow_SSE2(const uint8* src_argb, int src_argb_stride, - uint8* dst_argb, const float* uv_dudv, int width); - -// Used for I420Scale, ARGBScale, and ARGBInterpolate. -void InterpolateRow_C(uint8* dst_ptr, const uint8* src_ptr, - ptrdiff_t src_stride_ptr, - int width, int source_y_fraction); -void InterpolateRow_SSSE3(uint8* dst_ptr, const uint8* src_ptr, - ptrdiff_t src_stride_ptr, int width, - int source_y_fraction); -void InterpolateRow_AVX2(uint8* dst_ptr, const uint8* src_ptr, - ptrdiff_t src_stride_ptr, int width, - int source_y_fraction); -void InterpolateRow_NEON(uint8* dst_ptr, const uint8* src_ptr, - ptrdiff_t src_stride_ptr, int width, - int source_y_fraction); -void InterpolateRow_DSPR2(uint8* dst_ptr, const uint8* src_ptr, - ptrdiff_t src_stride_ptr, int width, - int source_y_fraction); -void InterpolateRow_Any_NEON(uint8* dst_ptr, const uint8* src_ptr, - ptrdiff_t src_stride_ptr, int width, - int source_y_fraction); -void InterpolateRow_Any_SSSE3(uint8* dst_ptr, const uint8* src_ptr, - ptrdiff_t src_stride_ptr, int width, - int source_y_fraction); -void InterpolateRow_Any_AVX2(uint8* dst_ptr, const uint8* src_ptr, - ptrdiff_t src_stride_ptr, int width, - int source_y_fraction); -void InterpolateRow_Any_DSPR2(uint8* dst_ptr, const uint8* src_ptr, - ptrdiff_t src_stride_ptr, int width, - int source_y_fraction); - -void InterpolateRow_16_C(uint16* dst_ptr, const uint16* src_ptr, - ptrdiff_t src_stride_ptr, - int width, int source_y_fraction); - -// Sobel images. -void SobelXRow_C(const uint8* src_y0, const uint8* src_y1, const uint8* src_y2, - uint8* dst_sobelx, int width); -void SobelXRow_SSE2(const uint8* src_y0, const uint8* src_y1, - const uint8* src_y2, uint8* dst_sobelx, int width); -void SobelXRow_NEON(const uint8* src_y0, const uint8* src_y1, - const uint8* src_y2, uint8* dst_sobelx, int width); -void SobelYRow_C(const uint8* src_y0, const uint8* src_y1, - uint8* dst_sobely, int width); -void SobelYRow_SSE2(const uint8* src_y0, const uint8* src_y1, - uint8* dst_sobely, int width); -void SobelYRow_NEON(const uint8* src_y0, const uint8* src_y1, - uint8* dst_sobely, int width); -void SobelRow_C(const uint8* src_sobelx, const uint8* src_sobely, - uint8* dst_argb, int width); -void SobelRow_SSE2(const uint8* src_sobelx, const uint8* src_sobely, - uint8* dst_argb, int width); -void SobelRow_NEON(const uint8* src_sobelx, const uint8* src_sobely, - uint8* dst_argb, int width); -void SobelToPlaneRow_C(const uint8* src_sobelx, const uint8* src_sobely, - uint8* dst_y, int width); -void SobelToPlaneRow_SSE2(const uint8* src_sobelx, const uint8* src_sobely, - uint8* dst_y, int width); -void SobelToPlaneRow_NEON(const uint8* src_sobelx, const uint8* src_sobely, - uint8* dst_y, int width); -void SobelXYRow_C(const uint8* src_sobelx, const uint8* src_sobely, - uint8* dst_argb, int width); -void SobelXYRow_SSE2(const uint8* src_sobelx, const uint8* src_sobely, - uint8* dst_argb, int width); -void SobelXYRow_NEON(const uint8* src_sobelx, const uint8* src_sobely, - uint8* dst_argb, int width); -void SobelRow_Any_SSE2(const uint8* src_sobelx, const uint8* src_sobely, - uint8* dst_argb, int width); -void SobelRow_Any_NEON(const uint8* src_sobelx, const uint8* src_sobely, - uint8* dst_argb, int width); -void SobelToPlaneRow_Any_SSE2(const uint8* src_sobelx, const uint8* src_sobely, - uint8* dst_y, int width); -void SobelToPlaneRow_Any_NEON(const uint8* src_sobelx, const uint8* src_sobely, - uint8* dst_y, int width); -void SobelXYRow_Any_SSE2(const uint8* src_sobelx, const uint8* src_sobely, - uint8* dst_argb, int width); -void SobelXYRow_Any_NEON(const uint8* src_sobelx, const uint8* src_sobely, - uint8* dst_argb, int width); - -void ARGBPolynomialRow_C(const uint8* src_argb, - uint8* dst_argb, const float* poly, - int width); -void ARGBPolynomialRow_SSE2(const uint8* src_argb, - uint8* dst_argb, const float* poly, - int width); -void ARGBPolynomialRow_AVX2(const uint8* src_argb, - uint8* dst_argb, const float* poly, - int width); - -// Scale and convert to half float. -void HalfFloatRow_C(const uint16* src, uint16* dst, float scale, int width); -void HalfFloatRow_AVX2(const uint16* src, uint16* dst, float scale, int width); -void HalfFloatRow_Any_AVX2(const uint16* src, uint16* dst, float scale, - int width); -void HalfFloatRow_SSE2(const uint16* src, uint16* dst, float scale, int width); -void HalfFloatRow_Any_SSE2(const uint16* src, uint16* dst, float scale, - int width); - -void ARGBLumaColorTableRow_C(const uint8* src_argb, uint8* dst_argb, int width, - const uint8* luma, uint32 lumacoeff); -void ARGBLumaColorTableRow_SSSE3(const uint8* src_argb, uint8* dst_argb, - int width, - const uint8* luma, uint32 lumacoeff); - -#ifdef __cplusplus -} // extern "C" -} // namespace libyuv -#endif - -#endif // INCLUDE_LIBYUV_ROW_H_ diff --git a/third_party/libyuv/include/libyuv/scale.h b/third_party/libyuv/include/libyuv/scale.h deleted file mode 100644 index ae14694598..0000000000 --- a/third_party/libyuv/include/libyuv/scale.h +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright 2011 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef INCLUDE_LIBYUV_SCALE_H_ -#define INCLUDE_LIBYUV_SCALE_H_ - -#include "libyuv/basic_types.h" - -#ifdef __cplusplus -namespace libyuv { -extern "C" { -#endif - -// Supported filtering. -typedef enum FilterMode { - kFilterNone = 0, // Point sample; Fastest. - kFilterLinear = 1, // Filter horizontally only. - kFilterBilinear = 2, // Faster than box, but lower quality scaling down. - kFilterBox = 3 // Highest quality. -} FilterModeEnum; - -// Scale a YUV plane. -LIBYUV_API -void ScalePlane(const uint8* src, int src_stride, - int src_width, int src_height, - uint8* dst, int dst_stride, - int dst_width, int dst_height, - enum FilterMode filtering); - -LIBYUV_API -void ScalePlane_16(const uint16* src, int src_stride, - int src_width, int src_height, - uint16* dst, int dst_stride, - int dst_width, int dst_height, - enum FilterMode filtering); - -// Scales a YUV 4:2:0 image from the src width and height to the -// dst width and height. -// If filtering is kFilterNone, a simple nearest-neighbor algorithm is -// used. This produces basic (blocky) quality at the fastest speed. -// If filtering is kFilterBilinear, interpolation is used to produce a better -// quality image, at the expense of speed. -// If filtering is kFilterBox, averaging is used to produce ever better -// quality image, at further expense of speed. -// Returns 0 if successful. - -LIBYUV_API -int I420Scale(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - int src_width, int src_height, - uint8* dst_y, int dst_stride_y, - uint8* dst_u, int dst_stride_u, - uint8* dst_v, int dst_stride_v, - int dst_width, int dst_height, - enum FilterMode filtering); - -LIBYUV_API -int I420Scale_16(const uint16* src_y, int src_stride_y, - const uint16* src_u, int src_stride_u, - const uint16* src_v, int src_stride_v, - int src_width, int src_height, - uint16* dst_y, int dst_stride_y, - uint16* dst_u, int dst_stride_u, - uint16* dst_v, int dst_stride_v, - int dst_width, int dst_height, - enum FilterMode filtering); - -#ifdef __cplusplus -// Legacy API. Deprecated. -LIBYUV_API -int Scale(const uint8* src_y, const uint8* src_u, const uint8* src_v, - int src_stride_y, int src_stride_u, int src_stride_v, - int src_width, int src_height, - uint8* dst_y, uint8* dst_u, uint8* dst_v, - int dst_stride_y, int dst_stride_u, int dst_stride_v, - int dst_width, int dst_height, - LIBYUV_BOOL interpolate); - -// Legacy API. Deprecated. -LIBYUV_API -int ScaleOffset(const uint8* src_i420, int src_width, int src_height, - uint8* dst_i420, int dst_width, int dst_height, int dst_yoffset, - LIBYUV_BOOL interpolate); - -// For testing, allow disabling of specialized scalers. -LIBYUV_API -void SetUseReferenceImpl(LIBYUV_BOOL use); -#endif // __cplusplus - -#ifdef __cplusplus -} // extern "C" -} // namespace libyuv -#endif - -#endif // INCLUDE_LIBYUV_SCALE_H_ diff --git a/third_party/libyuv/include/libyuv/scale_argb.h b/third_party/libyuv/include/libyuv/scale_argb.h deleted file mode 100644 index 35cd191c0f..0000000000 --- a/third_party/libyuv/include/libyuv/scale_argb.h +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright 2012 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef INCLUDE_LIBYUV_SCALE_ARGB_H_ -#define INCLUDE_LIBYUV_SCALE_ARGB_H_ - -#include "libyuv/basic_types.h" -#include "libyuv/scale.h" // For FilterMode - -#ifdef __cplusplus -namespace libyuv { -extern "C" { -#endif - -LIBYUV_API -int ARGBScale(const uint8* src_argb, int src_stride_argb, - int src_width, int src_height, - uint8* dst_argb, int dst_stride_argb, - int dst_width, int dst_height, - enum FilterMode filtering); - -// Clipped scale takes destination rectangle coordinates for clip values. -LIBYUV_API -int ARGBScaleClip(const uint8* src_argb, int src_stride_argb, - int src_width, int src_height, - uint8* dst_argb, int dst_stride_argb, - int dst_width, int dst_height, - int clip_x, int clip_y, int clip_width, int clip_height, - enum FilterMode filtering); - -// Scale with YUV conversion to ARGB and clipping. -LIBYUV_API -int YUVToARGBScaleClip(const uint8* src_y, int src_stride_y, - const uint8* src_u, int src_stride_u, - const uint8* src_v, int src_stride_v, - uint32 src_fourcc, - int src_width, int src_height, - uint8* dst_argb, int dst_stride_argb, - uint32 dst_fourcc, - int dst_width, int dst_height, - int clip_x, int clip_y, int clip_width, int clip_height, - enum FilterMode filtering); - -#ifdef __cplusplus -} // extern "C" -} // namespace libyuv -#endif - -#endif // INCLUDE_LIBYUV_SCALE_ARGB_H_ diff --git a/third_party/libyuv/include/libyuv/scale_row.h b/third_party/libyuv/include/libyuv/scale_row.h deleted file mode 100644 index 791fbf7d05..0000000000 --- a/third_party/libyuv/include/libyuv/scale_row.h +++ /dev/null @@ -1,503 +0,0 @@ -/* - * Copyright 2013 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef INCLUDE_LIBYUV_SCALE_ROW_H_ -#define INCLUDE_LIBYUV_SCALE_ROW_H_ - -#include "libyuv/basic_types.h" -#include "libyuv/scale.h" - -#ifdef __cplusplus -namespace libyuv { -extern "C" { -#endif - -#if defined(__pnacl__) || defined(__CLR_VER) || \ - (defined(__i386__) && !defined(__SSE2__)) -#define LIBYUV_DISABLE_X86 -#endif -// MemorySanitizer does not support assembly code yet. http://crbug.com/344505 -#if defined(__has_feature) -#if __has_feature(memory_sanitizer) -#define LIBYUV_DISABLE_X86 -#endif -#endif - -// GCC >= 4.7.0 required for AVX2. -#if defined(__GNUC__) && (defined(__x86_64__) || defined(__i386__)) -#if (__GNUC__ > 4) || (__GNUC__ == 4 && (__GNUC_MINOR__ >= 7)) -#define GCC_HAS_AVX2 1 -#endif // GNUC >= 4.7 -#endif // __GNUC__ - -// clang >= 3.4.0 required for AVX2. -#if defined(__clang__) && (defined(__x86_64__) || defined(__i386__)) -#if (__clang_major__ > 3) || (__clang_major__ == 3 && (__clang_minor__ >= 4)) -#define CLANG_HAS_AVX2 1 -#endif // clang >= 3.4 -#endif // __clang__ - -// Visual C 2012 required for AVX2. -#if defined(_M_IX86) && !defined(__clang__) && \ - defined(_MSC_VER) && _MSC_VER >= 1700 -#define VISUALC_HAS_AVX2 1 -#endif // VisualStudio >= 2012 - -// The following are available on all x86 platforms: -#if !defined(LIBYUV_DISABLE_X86) && \ - (defined(_M_IX86) || defined(__x86_64__) || defined(__i386__)) -#define HAS_FIXEDDIV1_X86 -#define HAS_FIXEDDIV_X86 -#define HAS_SCALEARGBCOLS_SSE2 -#define HAS_SCALEARGBCOLSUP2_SSE2 -#define HAS_SCALEARGBFILTERCOLS_SSSE3 -#define HAS_SCALEARGBROWDOWN2_SSE2 -#define HAS_SCALEARGBROWDOWNEVEN_SSE2 -#define HAS_SCALECOLSUP2_SSE2 -#define HAS_SCALEFILTERCOLS_SSSE3 -#define HAS_SCALEROWDOWN2_SSSE3 -#define HAS_SCALEROWDOWN34_SSSE3 -#define HAS_SCALEROWDOWN38_SSSE3 -#define HAS_SCALEROWDOWN4_SSSE3 -#define HAS_SCALEADDROW_SSE2 -#endif - -// The following are available on all x86 platforms, but -// require VS2012, clang 3.4 or gcc 4.7. -// The code supports NaCL but requires a new compiler and validator. -#if !defined(LIBYUV_DISABLE_X86) && (defined(VISUALC_HAS_AVX2) || \ - defined(CLANG_HAS_AVX2) || defined(GCC_HAS_AVX2)) -#define HAS_SCALEADDROW_AVX2 -#define HAS_SCALEROWDOWN2_AVX2 -#define HAS_SCALEROWDOWN4_AVX2 -#endif - -// The following are available on Neon platforms: -#if !defined(LIBYUV_DISABLE_NEON) && !defined(__native_client__) && \ - (defined(__ARM_NEON__) || defined(LIBYUV_NEON) || defined(__aarch64__)) -#define HAS_SCALEARGBCOLS_NEON -#define HAS_SCALEARGBROWDOWN2_NEON -#define HAS_SCALEARGBROWDOWNEVEN_NEON -#define HAS_SCALEFILTERCOLS_NEON -#define HAS_SCALEROWDOWN2_NEON -#define HAS_SCALEROWDOWN34_NEON -#define HAS_SCALEROWDOWN38_NEON -#define HAS_SCALEROWDOWN4_NEON -#define HAS_SCALEARGBFILTERCOLS_NEON -#endif - -// The following are available on Mips platforms: -#if !defined(LIBYUV_DISABLE_MIPS) && !defined(__native_client__) && \ - defined(__mips__) && defined(__mips_dsp) && (__mips_dsp_rev >= 2) -#define HAS_SCALEROWDOWN2_DSPR2 -#define HAS_SCALEROWDOWN4_DSPR2 -#define HAS_SCALEROWDOWN34_DSPR2 -#define HAS_SCALEROWDOWN38_DSPR2 -#endif - -// Scale ARGB vertically with bilinear interpolation. -void ScalePlaneVertical(int src_height, - int dst_width, int dst_height, - int src_stride, int dst_stride, - const uint8* src_argb, uint8* dst_argb, - int x, int y, int dy, - int bpp, enum FilterMode filtering); - -void ScalePlaneVertical_16(int src_height, - int dst_width, int dst_height, - int src_stride, int dst_stride, - const uint16* src_argb, uint16* dst_argb, - int x, int y, int dy, - int wpp, enum FilterMode filtering); - -// Simplify the filtering based on scale factors. -enum FilterMode ScaleFilterReduce(int src_width, int src_height, - int dst_width, int dst_height, - enum FilterMode filtering); - -// Divide num by div and return as 16.16 fixed point result. -int FixedDiv_C(int num, int div); -int FixedDiv_X86(int num, int div); -// Divide num - 1 by div - 1 and return as 16.16 fixed point result. -int FixedDiv1_C(int num, int div); -int FixedDiv1_X86(int num, int div); -#ifdef HAS_FIXEDDIV_X86 -#define FixedDiv FixedDiv_X86 -#define FixedDiv1 FixedDiv1_X86 -#else -#define FixedDiv FixedDiv_C -#define FixedDiv1 FixedDiv1_C -#endif - -// Compute slope values for stepping. -void ScaleSlope(int src_width, int src_height, - int dst_width, int dst_height, - enum FilterMode filtering, - int* x, int* y, int* dx, int* dy); - -void ScaleRowDown2_C(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleRowDown2_16_C(const uint16* src_ptr, ptrdiff_t src_stride, - uint16* dst, int dst_width); -void ScaleRowDown2Linear_C(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleRowDown2Linear_16_C(const uint16* src_ptr, ptrdiff_t src_stride, - uint16* dst, int dst_width); -void ScaleRowDown2Box_C(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleRowDown2Box_Odd_C(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleRowDown2Box_16_C(const uint16* src_ptr, ptrdiff_t src_stride, - uint16* dst, int dst_width); -void ScaleRowDown4_C(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleRowDown4_16_C(const uint16* src_ptr, ptrdiff_t src_stride, - uint16* dst, int dst_width); -void ScaleRowDown4Box_C(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleRowDown4Box_16_C(const uint16* src_ptr, ptrdiff_t src_stride, - uint16* dst, int dst_width); -void ScaleRowDown34_C(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleRowDown34_16_C(const uint16* src_ptr, ptrdiff_t src_stride, - uint16* dst, int dst_width); -void ScaleRowDown34_0_Box_C(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* d, int dst_width); -void ScaleRowDown34_0_Box_16_C(const uint16* src_ptr, ptrdiff_t src_stride, - uint16* d, int dst_width); -void ScaleRowDown34_1_Box_C(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* d, int dst_width); -void ScaleRowDown34_1_Box_16_C(const uint16* src_ptr, ptrdiff_t src_stride, - uint16* d, int dst_width); -void ScaleCols_C(uint8* dst_ptr, const uint8* src_ptr, - int dst_width, int x, int dx); -void ScaleCols_16_C(uint16* dst_ptr, const uint16* src_ptr, - int dst_width, int x, int dx); -void ScaleColsUp2_C(uint8* dst_ptr, const uint8* src_ptr, - int dst_width, int, int); -void ScaleColsUp2_16_C(uint16* dst_ptr, const uint16* src_ptr, - int dst_width, int, int); -void ScaleFilterCols_C(uint8* dst_ptr, const uint8* src_ptr, - int dst_width, int x, int dx); -void ScaleFilterCols_16_C(uint16* dst_ptr, const uint16* src_ptr, - int dst_width, int x, int dx); -void ScaleFilterCols64_C(uint8* dst_ptr, const uint8* src_ptr, - int dst_width, int x, int dx); -void ScaleFilterCols64_16_C(uint16* dst_ptr, const uint16* src_ptr, - int dst_width, int x, int dx); -void ScaleRowDown38_C(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleRowDown38_16_C(const uint16* src_ptr, ptrdiff_t src_stride, - uint16* dst, int dst_width); -void ScaleRowDown38_3_Box_C(const uint8* src_ptr, - ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown38_3_Box_16_C(const uint16* src_ptr, - ptrdiff_t src_stride, - uint16* dst_ptr, int dst_width); -void ScaleRowDown38_2_Box_C(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown38_2_Box_16_C(const uint16* src_ptr, ptrdiff_t src_stride, - uint16* dst_ptr, int dst_width); -void ScaleAddRow_C(const uint8* src_ptr, uint16* dst_ptr, int src_width); -void ScaleAddRow_16_C(const uint16* src_ptr, uint32* dst_ptr, int src_width); -void ScaleARGBRowDown2_C(const uint8* src_argb, - ptrdiff_t src_stride, - uint8* dst_argb, int dst_width); -void ScaleARGBRowDown2Linear_C(const uint8* src_argb, - ptrdiff_t src_stride, - uint8* dst_argb, int dst_width); -void ScaleARGBRowDown2Box_C(const uint8* src_argb, ptrdiff_t src_stride, - uint8* dst_argb, int dst_width); -void ScaleARGBRowDownEven_C(const uint8* src_argb, ptrdiff_t src_stride, - int src_stepx, - uint8* dst_argb, int dst_width); -void ScaleARGBRowDownEvenBox_C(const uint8* src_argb, - ptrdiff_t src_stride, - int src_stepx, - uint8* dst_argb, int dst_width); -void ScaleARGBCols_C(uint8* dst_argb, const uint8* src_argb, - int dst_width, int x, int dx); -void ScaleARGBCols64_C(uint8* dst_argb, const uint8* src_argb, - int dst_width, int x, int dx); -void ScaleARGBColsUp2_C(uint8* dst_argb, const uint8* src_argb, - int dst_width, int, int); -void ScaleARGBFilterCols_C(uint8* dst_argb, const uint8* src_argb, - int dst_width, int x, int dx); -void ScaleARGBFilterCols64_C(uint8* dst_argb, const uint8* src_argb, - int dst_width, int x, int dx); - -// Specialized scalers for x86. -void ScaleRowDown2_SSSE3(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown2Linear_SSSE3(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown2Box_SSSE3(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown2_AVX2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown2Linear_AVX2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown2Box_AVX2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown4_SSSE3(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown4Box_SSSE3(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown4_AVX2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown4Box_AVX2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); - -void ScaleRowDown34_SSSE3(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown34_1_Box_SSSE3(const uint8* src_ptr, - ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown34_0_Box_SSSE3(const uint8* src_ptr, - ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown38_SSSE3(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown38_3_Box_SSSE3(const uint8* src_ptr, - ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown38_2_Box_SSSE3(const uint8* src_ptr, - ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown2_Any_SSSE3(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown2Linear_Any_SSSE3(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown2Box_Any_SSSE3(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown2Box_Odd_SSSE3(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown2_Any_AVX2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown2Linear_Any_AVX2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown2Box_Any_AVX2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown2Box_Odd_AVX2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown4_Any_SSSE3(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown4Box_Any_SSSE3(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown4_Any_AVX2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown4Box_Any_AVX2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); - -void ScaleRowDown34_Any_SSSE3(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown34_1_Box_Any_SSSE3(const uint8* src_ptr, - ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown34_0_Box_Any_SSSE3(const uint8* src_ptr, - ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown38_Any_SSSE3(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown38_3_Box_Any_SSSE3(const uint8* src_ptr, - ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown38_2_Box_Any_SSSE3(const uint8* src_ptr, - ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); - -void ScaleAddRow_SSE2(const uint8* src_ptr, uint16* dst_ptr, int src_width); -void ScaleAddRow_AVX2(const uint8* src_ptr, uint16* dst_ptr, int src_width); -void ScaleAddRow_Any_SSE2(const uint8* src_ptr, uint16* dst_ptr, int src_width); -void ScaleAddRow_Any_AVX2(const uint8* src_ptr, uint16* dst_ptr, int src_width); - -void ScaleFilterCols_SSSE3(uint8* dst_ptr, const uint8* src_ptr, - int dst_width, int x, int dx); -void ScaleColsUp2_SSE2(uint8* dst_ptr, const uint8* src_ptr, - int dst_width, int x, int dx); - - -// ARGB Column functions -void ScaleARGBCols_SSE2(uint8* dst_argb, const uint8* src_argb, - int dst_width, int x, int dx); -void ScaleARGBFilterCols_SSSE3(uint8* dst_argb, const uint8* src_argb, - int dst_width, int x, int dx); -void ScaleARGBColsUp2_SSE2(uint8* dst_argb, const uint8* src_argb, - int dst_width, int x, int dx); -void ScaleARGBFilterCols_NEON(uint8* dst_argb, const uint8* src_argb, - int dst_width, int x, int dx); -void ScaleARGBCols_NEON(uint8* dst_argb, const uint8* src_argb, - int dst_width, int x, int dx); -void ScaleARGBFilterCols_Any_NEON(uint8* dst_argb, const uint8* src_argb, - int dst_width, int x, int dx); -void ScaleARGBCols_Any_NEON(uint8* dst_argb, const uint8* src_argb, - int dst_width, int x, int dx); - -// ARGB Row functions -void ScaleARGBRowDown2_SSE2(const uint8* src_argb, ptrdiff_t src_stride, - uint8* dst_argb, int dst_width); -void ScaleARGBRowDown2Linear_SSE2(const uint8* src_argb, ptrdiff_t src_stride, - uint8* dst_argb, int dst_width); -void ScaleARGBRowDown2Box_SSE2(const uint8* src_argb, ptrdiff_t src_stride, - uint8* dst_argb, int dst_width); -void ScaleARGBRowDown2_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleARGBRowDown2Linear_NEON(const uint8* src_argb, ptrdiff_t src_stride, - uint8* dst_argb, int dst_width); -void ScaleARGBRowDown2Box_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleARGBRowDown2_Any_SSE2(const uint8* src_argb, ptrdiff_t src_stride, - uint8* dst_argb, int dst_width); -void ScaleARGBRowDown2Linear_Any_SSE2(const uint8* src_argb, - ptrdiff_t src_stride, - uint8* dst_argb, int dst_width); -void ScaleARGBRowDown2Box_Any_SSE2(const uint8* src_argb, ptrdiff_t src_stride, - uint8* dst_argb, int dst_width); -void ScaleARGBRowDown2_Any_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleARGBRowDown2Linear_Any_NEON(const uint8* src_argb, - ptrdiff_t src_stride, - uint8* dst_argb, int dst_width); -void ScaleARGBRowDown2Box_Any_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); - -void ScaleARGBRowDownEven_SSE2(const uint8* src_argb, ptrdiff_t src_stride, - int src_stepx, uint8* dst_argb, int dst_width); -void ScaleARGBRowDownEvenBox_SSE2(const uint8* src_argb, ptrdiff_t src_stride, - int src_stepx, - uint8* dst_argb, int dst_width); -void ScaleARGBRowDownEven_NEON(const uint8* src_argb, ptrdiff_t src_stride, - int src_stepx, - uint8* dst_argb, int dst_width); -void ScaleARGBRowDownEvenBox_NEON(const uint8* src_argb, ptrdiff_t src_stride, - int src_stepx, - uint8* dst_argb, int dst_width); -void ScaleARGBRowDownEven_Any_SSE2(const uint8* src_argb, ptrdiff_t src_stride, - int src_stepx, - uint8* dst_argb, int dst_width); -void ScaleARGBRowDownEvenBox_Any_SSE2(const uint8* src_argb, - ptrdiff_t src_stride, - int src_stepx, - uint8* dst_argb, int dst_width); -void ScaleARGBRowDownEven_Any_NEON(const uint8* src_argb, ptrdiff_t src_stride, - int src_stepx, - uint8* dst_argb, int dst_width); -void ScaleARGBRowDownEvenBox_Any_NEON(const uint8* src_argb, - ptrdiff_t src_stride, - int src_stepx, - uint8* dst_argb, int dst_width); - -// ScaleRowDown2Box also used by planar functions -// NEON downscalers with interpolation. - -// Note - not static due to reuse in convert for 444 to 420. -void ScaleRowDown2_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleRowDown2Linear_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleRowDown2Box_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); - -void ScaleRowDown4_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown4Box_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); - -// Down scale from 4 to 3 pixels. Use the neon multilane read/write -// to load up the every 4th pixel into a 4 different registers. -// Point samples 32 pixels to 24 pixels. -void ScaleRowDown34_NEON(const uint8* src_ptr, - ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown34_0_Box_NEON(const uint8* src_ptr, - ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown34_1_Box_NEON(const uint8* src_ptr, - ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); - -// 32 -> 12 -void ScaleRowDown38_NEON(const uint8* src_ptr, - ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -// 32x3 -> 12x1 -void ScaleRowDown38_3_Box_NEON(const uint8* src_ptr, - ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -// 32x2 -> 12x1 -void ScaleRowDown38_2_Box_NEON(const uint8* src_ptr, - ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); - -void ScaleRowDown2_Any_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleRowDown2Linear_Any_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleRowDown2Box_Any_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleRowDown2Box_Odd_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleRowDown4_Any_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown4Box_Any_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown34_Any_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown34_0_Box_Any_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown34_1_Box_Any_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -// 32 -> 12 -void ScaleRowDown38_Any_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -// 32x3 -> 12x1 -void ScaleRowDown38_3_Box_Any_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -// 32x2 -> 12x1 -void ScaleRowDown38_2_Box_Any_NEON(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); - -void ScaleAddRow_NEON(const uint8* src_ptr, uint16* dst_ptr, int src_width); -void ScaleAddRow_Any_NEON(const uint8* src_ptr, uint16* dst_ptr, int src_width); - -void ScaleFilterCols_NEON(uint8* dst_ptr, const uint8* src_ptr, - int dst_width, int x, int dx); - -void ScaleFilterCols_Any_NEON(uint8* dst_ptr, const uint8* src_ptr, - int dst_width, int x, int dx); - -void ScaleRowDown2_DSPR2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleRowDown2Box_DSPR2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleRowDown4_DSPR2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleRowDown4Box_DSPR2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleRowDown34_DSPR2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleRowDown34_0_Box_DSPR2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* d, int dst_width); -void ScaleRowDown34_1_Box_DSPR2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* d, int dst_width); -void ScaleRowDown38_DSPR2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst, int dst_width); -void ScaleRowDown38_2_Box_DSPR2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); -void ScaleRowDown38_3_Box_DSPR2(const uint8* src_ptr, ptrdiff_t src_stride, - uint8* dst_ptr, int dst_width); - -#ifdef __cplusplus -} // extern "C" -} // namespace libyuv -#endif - -#endif // INCLUDE_LIBYUV_SCALE_ROW_H_ diff --git a/third_party/libyuv/include/libyuv/version.h b/third_party/libyuv/include/libyuv/version.h deleted file mode 100644 index 3a8f6337ca..0000000000 --- a/third_party/libyuv/include/libyuv/version.h +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright 2012 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -#ifndef INCLUDE_LIBYUV_VERSION_H_ -#define INCLUDE_LIBYUV_VERSION_H_ - -#define LIBYUV_VERSION 1622 - -#endif // INCLUDE_LIBYUV_VERSION_H_ diff --git a/third_party/libyuv/include/libyuv/video_common.h b/third_party/libyuv/include/libyuv/video_common.h deleted file mode 100644 index cb425426a2..0000000000 --- a/third_party/libyuv/include/libyuv/video_common.h +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Copyright 2011 The LibYuv Project Authors. All rights reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. An additional intellectual property rights grant can be found - * in the file PATENTS. All contributing project authors may - * be found in the AUTHORS file in the root of the source tree. - */ - -// Common definitions for video, including fourcc and VideoFormat. - -#ifndef INCLUDE_LIBYUV_VIDEO_COMMON_H_ -#define INCLUDE_LIBYUV_VIDEO_COMMON_H_ - -#include "libyuv/basic_types.h" - -#ifdef __cplusplus -namespace libyuv { -extern "C" { -#endif - -////////////////////////////////////////////////////////////////////////////// -// Definition of FourCC codes -////////////////////////////////////////////////////////////////////////////// - -// Convert four characters to a FourCC code. -// Needs to be a macro otherwise the OS X compiler complains when the kFormat* -// constants are used in a switch. -#ifdef __cplusplus -#define FOURCC(a, b, c, d) ( \ - (static_cast(a)) | (static_cast(b) << 8) | \ - (static_cast(c) << 16) | (static_cast(d) << 24)) -#else -#define FOURCC(a, b, c, d) ( \ - ((uint32)(a)) | ((uint32)(b) << 8) | /* NOLINT */ \ - ((uint32)(c) << 16) | ((uint32)(d) << 24)) /* NOLINT */ -#endif - -// Some pages discussing FourCC codes: -// http://www.fourcc.org/yuv.php -// http://v4l2spec.bytesex.org/spec/book1.htm -// http://developer.apple.com/quicktime/icefloe/dispatch020.html -// http://msdn.microsoft.com/library/windows/desktop/dd206750.aspx#nv12 -// http://people.xiph.org/~xiphmont/containers/nut/nut4cc.txt - -// FourCC codes grouped according to implementation efficiency. -// Primary formats should convert in 1 efficient step. -// Secondary formats are converted in 2 steps. -// Auxilliary formats call primary converters. -enum FourCC { - // 9 Primary YUV formats: 5 planar, 2 biplanar, 2 packed. - FOURCC_I420 = FOURCC('I', '4', '2', '0'), - FOURCC_I422 = FOURCC('I', '4', '2', '2'), - FOURCC_I444 = FOURCC('I', '4', '4', '4'), - FOURCC_I411 = FOURCC('I', '4', '1', '1'), - FOURCC_I400 = FOURCC('I', '4', '0', '0'), - FOURCC_NV21 = FOURCC('N', 'V', '2', '1'), - FOURCC_NV12 = FOURCC('N', 'V', '1', '2'), - FOURCC_YUY2 = FOURCC('Y', 'U', 'Y', '2'), - FOURCC_UYVY = FOURCC('U', 'Y', 'V', 'Y'), - - // 2 Secondary YUV formats: row biplanar. - FOURCC_M420 = FOURCC('M', '4', '2', '0'), - FOURCC_Q420 = FOURCC('Q', '4', '2', '0'), // deprecated. - - // 9 Primary RGB formats: 4 32 bpp, 2 24 bpp, 3 16 bpp. - FOURCC_ARGB = FOURCC('A', 'R', 'G', 'B'), - FOURCC_BGRA = FOURCC('B', 'G', 'R', 'A'), - FOURCC_ABGR = FOURCC('A', 'B', 'G', 'R'), - FOURCC_24BG = FOURCC('2', '4', 'B', 'G'), - FOURCC_RAW = FOURCC('r', 'a', 'w', ' '), - FOURCC_RGBA = FOURCC('R', 'G', 'B', 'A'), - FOURCC_RGBP = FOURCC('R', 'G', 'B', 'P'), // rgb565 LE. - FOURCC_RGBO = FOURCC('R', 'G', 'B', 'O'), // argb1555 LE. - FOURCC_R444 = FOURCC('R', '4', '4', '4'), // argb4444 LE. - - // 4 Secondary RGB formats: 4 Bayer Patterns. deprecated. - FOURCC_RGGB = FOURCC('R', 'G', 'G', 'B'), - FOURCC_BGGR = FOURCC('B', 'G', 'G', 'R'), - FOURCC_GRBG = FOURCC('G', 'R', 'B', 'G'), - FOURCC_GBRG = FOURCC('G', 'B', 'R', 'G'), - - // 1 Primary Compressed YUV format. - FOURCC_MJPG = FOURCC('M', 'J', 'P', 'G'), - - // 5 Auxiliary YUV variations: 3 with U and V planes are swapped, 1 Alias. - FOURCC_YV12 = FOURCC('Y', 'V', '1', '2'), - FOURCC_YV16 = FOURCC('Y', 'V', '1', '6'), - FOURCC_YV24 = FOURCC('Y', 'V', '2', '4'), - FOURCC_YU12 = FOURCC('Y', 'U', '1', '2'), // Linux version of I420. - FOURCC_J420 = FOURCC('J', '4', '2', '0'), - FOURCC_J400 = FOURCC('J', '4', '0', '0'), // unofficial fourcc - FOURCC_H420 = FOURCC('H', '4', '2', '0'), // unofficial fourcc - - // 14 Auxiliary aliases. CanonicalFourCC() maps these to canonical fourcc. - FOURCC_IYUV = FOURCC('I', 'Y', 'U', 'V'), // Alias for I420. - FOURCC_YU16 = FOURCC('Y', 'U', '1', '6'), // Alias for I422. - FOURCC_YU24 = FOURCC('Y', 'U', '2', '4'), // Alias for I444. - FOURCC_YUYV = FOURCC('Y', 'U', 'Y', 'V'), // Alias for YUY2. - FOURCC_YUVS = FOURCC('y', 'u', 'v', 's'), // Alias for YUY2 on Mac. - FOURCC_HDYC = FOURCC('H', 'D', 'Y', 'C'), // Alias for UYVY. - FOURCC_2VUY = FOURCC('2', 'v', 'u', 'y'), // Alias for UYVY on Mac. - FOURCC_JPEG = FOURCC('J', 'P', 'E', 'G'), // Alias for MJPG. - FOURCC_DMB1 = FOURCC('d', 'm', 'b', '1'), // Alias for MJPG on Mac. - FOURCC_BA81 = FOURCC('B', 'A', '8', '1'), // Alias for BGGR. - FOURCC_RGB3 = FOURCC('R', 'G', 'B', '3'), // Alias for RAW. - FOURCC_BGR3 = FOURCC('B', 'G', 'R', '3'), // Alias for 24BG. - FOURCC_CM32 = FOURCC(0, 0, 0, 32), // Alias for BGRA kCMPixelFormat_32ARGB - FOURCC_CM24 = FOURCC(0, 0, 0, 24), // Alias for RAW kCMPixelFormat_24RGB - FOURCC_L555 = FOURCC('L', '5', '5', '5'), // Alias for RGBO. - FOURCC_L565 = FOURCC('L', '5', '6', '5'), // Alias for RGBP. - FOURCC_5551 = FOURCC('5', '5', '5', '1'), // Alias for RGBO. - - // 1 Auxiliary compressed YUV format set aside for capturer. - FOURCC_H264 = FOURCC('H', '2', '6', '4'), - - // Match any fourcc. - FOURCC_ANY = -1, -}; - -enum FourCCBpp { - // Canonical fourcc codes used in our code. - FOURCC_BPP_I420 = 12, - FOURCC_BPP_I422 = 16, - FOURCC_BPP_I444 = 24, - FOURCC_BPP_I411 = 12, - FOURCC_BPP_I400 = 8, - FOURCC_BPP_NV21 = 12, - FOURCC_BPP_NV12 = 12, - FOURCC_BPP_YUY2 = 16, - FOURCC_BPP_UYVY = 16, - FOURCC_BPP_M420 = 12, - FOURCC_BPP_Q420 = 12, - FOURCC_BPP_ARGB = 32, - FOURCC_BPP_BGRA = 32, - FOURCC_BPP_ABGR = 32, - FOURCC_BPP_RGBA = 32, - FOURCC_BPP_24BG = 24, - FOURCC_BPP_RAW = 24, - FOURCC_BPP_RGBP = 16, - FOURCC_BPP_RGBO = 16, - FOURCC_BPP_R444 = 16, - FOURCC_BPP_RGGB = 8, - FOURCC_BPP_BGGR = 8, - FOURCC_BPP_GRBG = 8, - FOURCC_BPP_GBRG = 8, - FOURCC_BPP_YV12 = 12, - FOURCC_BPP_YV16 = 16, - FOURCC_BPP_YV24 = 24, - FOURCC_BPP_YU12 = 12, - FOURCC_BPP_J420 = 12, - FOURCC_BPP_J400 = 8, - FOURCC_BPP_H420 = 12, - FOURCC_BPP_MJPG = 0, // 0 means unknown. - FOURCC_BPP_H264 = 0, - FOURCC_BPP_IYUV = 12, - FOURCC_BPP_YU16 = 16, - FOURCC_BPP_YU24 = 24, - FOURCC_BPP_YUYV = 16, - FOURCC_BPP_YUVS = 16, - FOURCC_BPP_HDYC = 16, - FOURCC_BPP_2VUY = 16, - FOURCC_BPP_JPEG = 1, - FOURCC_BPP_DMB1 = 1, - FOURCC_BPP_BA81 = 8, - FOURCC_BPP_RGB3 = 24, - FOURCC_BPP_BGR3 = 24, - FOURCC_BPP_CM32 = 32, - FOURCC_BPP_CM24 = 24, - - // Match any fourcc. - FOURCC_BPP_ANY = 0, // 0 means unknown. -}; - -// Converts fourcc aliases into canonical ones. -LIBYUV_API uint32 CanonicalFourCC(uint32 fourcc); - -#ifdef __cplusplus -} // extern "C" -} // namespace libyuv -#endif - -#endif // INCLUDE_LIBYUV_VIDEO_COMMON_H_ diff --git a/third_party/libyuv/larch64/lib/libyuv.a b/third_party/libyuv/larch64/lib/libyuv.a deleted file mode 100644 index 1c91250231..0000000000 --- a/third_party/libyuv/larch64/lib/libyuv.a +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:320bef5a75a62dd2731a496040921d5000f1ed237ae70fd7aeb6c010a1534363 -size 462482 diff --git a/third_party/libyuv/x86_64/include b/third_party/libyuv/x86_64/include deleted file mode 120000 index f5030fe889..0000000000 --- a/third_party/libyuv/x86_64/include +++ /dev/null @@ -1 +0,0 @@ -../include \ No newline at end of file diff --git a/third_party/libyuv/x86_64/lib/libyuv.a b/third_party/libyuv/x86_64/lib/libyuv.a deleted file mode 100644 index 8915f167dc..0000000000 --- a/third_party/libyuv/x86_64/lib/libyuv.a +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e21a3bd8df01cf4ce5461e7bf6654239196036c3f829255145265c7bf31a791d -size 511974 diff --git a/third_party/linux/include/linux/ion.h b/third_party/linux/include/linux/ion.h deleted file mode 100644 index 7b5b031f57..0000000000 --- a/third_party/linux/include/linux/ion.h +++ /dev/null @@ -1,78 +0,0 @@ -/**************************************************************************** - **************************************************************************** - *** - *** This header was automatically generated from a Linux kernel header - *** of the same name, to make information necessary for userspace to - *** call into the kernel available to libc. It contains only constants, - *** structures, and macros generated from the original header, and thus, - *** contains no copyrightable information. - *** - *** To edit the content of this header, modify the corresponding - *** source file (e.g. under external/kernel-headers/original/) then - *** run bionic/libc/kernel/tools/update_all.py - *** - *** Any manual change here will be lost the next time this script will - *** be run. You've been warned! - *** - **************************************************************************** - ****************************************************************************/ -#ifndef _UAPI_LINUX_ION_H -#define _UAPI_LINUX_ION_H -#include -#include -typedef int ion_user_handle_t; -enum ion_heap_type { - ION_HEAP_TYPE_SYSTEM, - ION_HEAP_TYPE_SYSTEM_CONTIG, - ION_HEAP_TYPE_CARVEOUT, - ION_HEAP_TYPE_CHUNK, - ION_HEAP_TYPE_DMA, - ION_HEAP_TYPE_CUSTOM, -}; -#define ION_NUM_HEAP_IDS (sizeof(unsigned int) * 8) -#define ION_FLAG_CACHED 1 -#define ION_FLAG_CACHED_NEEDS_SYNC 2 -struct ion_allocation_data { - size_t len; - size_t align; - unsigned int heap_id_mask; - unsigned int flags; - ion_user_handle_t handle; -}; -struct ion_fd_data { - ion_user_handle_t handle; - int fd; -}; -struct ion_handle_data { - ion_user_handle_t handle; -}; -struct ion_custom_data { - unsigned int cmd; - unsigned long arg; -}; -#define MAX_HEAP_NAME 32 -struct ion_heap_data { - char name[MAX_HEAP_NAME]; - __u32 type; - __u32 heap_id; - __u32 reserved0; - __u32 reserved1; - __u32 reserved2; -}; -struct ion_heap_query { - __u32 cnt; - __u32 reserved0; - __u64 heaps; - __u32 reserved1; - __u32 reserved2; -}; -#define ION_IOC_MAGIC 'I' -#define ION_IOC_ALLOC _IOWR(ION_IOC_MAGIC, 0, struct ion_allocation_data) -#define ION_IOC_FREE _IOWR(ION_IOC_MAGIC, 1, struct ion_handle_data) -#define ION_IOC_MAP _IOWR(ION_IOC_MAGIC, 2, struct ion_fd_data) -#define ION_IOC_SHARE _IOWR(ION_IOC_MAGIC, 4, struct ion_fd_data) -#define ION_IOC_IMPORT _IOWR(ION_IOC_MAGIC, 5, struct ion_fd_data) -#define ION_IOC_SYNC _IOWR(ION_IOC_MAGIC, 7, struct ion_fd_data) -#define ION_IOC_CUSTOM _IOWR(ION_IOC_MAGIC, 6, struct ion_custom_data) -#define ION_IOC_HEAP_QUERY _IOWR(ION_IOC_MAGIC, 8, struct ion_heap_query) -#endif diff --git a/third_party/linux/include/media/cam_cpas.h b/third_party/linux/include/media/cam_cpas.h deleted file mode 100644 index c5cbac82e7..0000000000 --- a/third_party/linux/include/media/cam_cpas.h +++ /dev/null @@ -1,25 +0,0 @@ -#ifndef __UAPI_CAM_CPAS_H__ -#define __UAPI_CAM_CPAS_H__ - -#include "cam_defs.h" - -#define CAM_FAMILY_CAMERA_SS 1 -#define CAM_FAMILY_CPAS_SS 2 - -/** - * struct cam_cpas_query_cap - CPAS query device capability payload - * - * @camera_family : Camera family type - * @reserved : Reserved field for alignment - * @camera_version : Camera platform version - * @cpas_version : Camera CPAS version within camera platform - * - */ -struct cam_cpas_query_cap { - uint32_t camera_family; - uint32_t reserved; - struct cam_hw_version camera_version; - struct cam_hw_version cpas_version; -}; - -#endif /* __UAPI_CAM_CPAS_H__ */ diff --git a/third_party/linux/include/media/cam_defs.h b/third_party/linux/include/media/cam_defs.h deleted file mode 100644 index e006463d2a..0000000000 --- a/third_party/linux/include/media/cam_defs.h +++ /dev/null @@ -1,477 +0,0 @@ -#ifndef __UAPI_CAM_DEFS_H__ -#define __UAPI_CAM_DEFS_H__ - -#include -#include -#include - - -/* camera op codes */ -#define CAM_COMMON_OPCODE_BASE 0x100 -#define CAM_QUERY_CAP (CAM_COMMON_OPCODE_BASE + 0x1) -#define CAM_ACQUIRE_DEV (CAM_COMMON_OPCODE_BASE + 0x2) -#define CAM_START_DEV (CAM_COMMON_OPCODE_BASE + 0x3) -#define CAM_STOP_DEV (CAM_COMMON_OPCODE_BASE + 0x4) -#define CAM_CONFIG_DEV (CAM_COMMON_OPCODE_BASE + 0x5) -#define CAM_RELEASE_DEV (CAM_COMMON_OPCODE_BASE + 0x6) -#define CAM_SD_SHUTDOWN (CAM_COMMON_OPCODE_BASE + 0x7) -#define CAM_FLUSH_REQ (CAM_COMMON_OPCODE_BASE + 0x8) -#define CAM_COMMON_OPCODE_MAX (CAM_COMMON_OPCODE_BASE + 0x9) - -#define CAM_EXT_OPCODE_BASE 0x200 -#define CAM_CONFIG_DEV_EXTERNAL (CAM_EXT_OPCODE_BASE + 0x1) - -/* camera handle type */ -#define CAM_HANDLE_USER_POINTER 1 -#define CAM_HANDLE_MEM_HANDLE 2 - -/* Generic Blob CmdBuffer header properties */ -#define CAM_GENERIC_BLOB_CMDBUFFER_SIZE_MASK 0xFFFFFF00 -#define CAM_GENERIC_BLOB_CMDBUFFER_SIZE_SHIFT 8 -#define CAM_GENERIC_BLOB_CMDBUFFER_TYPE_MASK 0xFF -#define CAM_GENERIC_BLOB_CMDBUFFER_TYPE_SHIFT 0 - -/* Command Buffer Types */ -#define CAM_CMD_BUF_DMI 0x1 -#define CAM_CMD_BUF_DMI16 0x2 -#define CAM_CMD_BUF_DMI32 0x3 -#define CAM_CMD_BUF_DMI64 0x4 -#define CAM_CMD_BUF_DIRECT 0x5 -#define CAM_CMD_BUF_INDIRECT 0x6 -#define CAM_CMD_BUF_I2C 0x7 -#define CAM_CMD_BUF_FW 0x8 -#define CAM_CMD_BUF_GENERIC 0x9 -#define CAM_CMD_BUF_LEGACY 0xA - -/** - * enum flush_type_t - Identifies the various flush types - * - * @CAM_FLUSH_TYPE_REQ: Flush specific request - * @CAM_FLUSH_TYPE_ALL: Flush all requests belonging to a context - * @CAM_FLUSH_TYPE_MAX: Max enum to validate flush type - * - */ -enum flush_type_t { - CAM_FLUSH_TYPE_REQ, - CAM_FLUSH_TYPE_ALL, - CAM_FLUSH_TYPE_MAX -}; - -/** - * struct cam_control - Structure used by ioctl control for camera - * - * @op_code: This is the op code for camera control - * @size: Control command size - * @handle_type: User pointer or shared memory handle - * @reserved: Reserved field for 64 bit alignment - * @handle: Control command payload - */ -struct cam_control { - uint32_t op_code; - uint32_t size; - uint32_t handle_type; - uint32_t reserved; - uint64_t handle; -}; - -/* camera IOCTL */ -#define VIDIOC_CAM_CONTROL \ - _IOWR('V', BASE_VIDIOC_PRIVATE, struct cam_control) - -/** - * struct cam_hw_version - Structure for HW version of camera devices - * - * @major : Hardware version major - * @minor : Hardware version minor - * @incr : Hardware version increment - * @reserved : Reserved for 64 bit aligngment - */ -struct cam_hw_version { - uint32_t major; - uint32_t minor; - uint32_t incr; - uint32_t reserved; -}; - -/** - * struct cam_iommu_handle - Structure for IOMMU handles of camera hw devices - * - * @non_secure: Device Non Secure IOMMU handle - * @secure: Device Secure IOMMU handle - * - */ -struct cam_iommu_handle { - int32_t non_secure; - int32_t secure; -}; - -/* camera secure mode */ -#define CAM_SECURE_MODE_NON_SECURE 0 -#define CAM_SECURE_MODE_SECURE 1 - -/* Camera Format Type */ -#define CAM_FORMAT_BASE 0 -#define CAM_FORMAT_MIPI_RAW_6 1 -#define CAM_FORMAT_MIPI_RAW_8 2 -#define CAM_FORMAT_MIPI_RAW_10 3 -#define CAM_FORMAT_MIPI_RAW_12 4 -#define CAM_FORMAT_MIPI_RAW_14 5 -#define CAM_FORMAT_MIPI_RAW_16 6 -#define CAM_FORMAT_MIPI_RAW_20 7 -#define CAM_FORMAT_QTI_RAW_8 8 -#define CAM_FORMAT_QTI_RAW_10 9 -#define CAM_FORMAT_QTI_RAW_12 10 -#define CAM_FORMAT_QTI_RAW_14 11 -#define CAM_FORMAT_PLAIN8 12 -#define CAM_FORMAT_PLAIN16_8 13 -#define CAM_FORMAT_PLAIN16_10 14 -#define CAM_FORMAT_PLAIN16_12 15 -#define CAM_FORMAT_PLAIN16_14 16 -#define CAM_FORMAT_PLAIN16_16 17 -#define CAM_FORMAT_PLAIN32_20 18 -#define CAM_FORMAT_PLAIN64 19 -#define CAM_FORMAT_PLAIN128 20 -#define CAM_FORMAT_ARGB 21 -#define CAM_FORMAT_ARGB_10 22 -#define CAM_FORMAT_ARGB_12 23 -#define CAM_FORMAT_ARGB_14 24 -#define CAM_FORMAT_DPCM_10_6_10 25 -#define CAM_FORMAT_DPCM_10_8_10 26 -#define CAM_FORMAT_DPCM_12_6_12 27 -#define CAM_FORMAT_DPCM_12_8_12 28 -#define CAM_FORMAT_DPCM_14_8_14 29 -#define CAM_FORMAT_DPCM_14_10_14 30 -#define CAM_FORMAT_NV21 31 -#define CAM_FORMAT_NV12 32 -#define CAM_FORMAT_TP10 33 -#define CAM_FORMAT_YUV422 34 -#define CAM_FORMAT_PD8 35 -#define CAM_FORMAT_PD10 36 -#define CAM_FORMAT_UBWC_NV12 37 -#define CAM_FORMAT_UBWC_NV12_4R 38 -#define CAM_FORMAT_UBWC_TP10 39 -#define CAM_FORMAT_UBWC_P010 40 -#define CAM_FORMAT_PLAIN8_SWAP 41 -#define CAM_FORMAT_PLAIN8_10 42 -#define CAM_FORMAT_PLAIN8_10_SWAP 43 -#define CAM_FORMAT_YV12 44 -#define CAM_FORMAT_Y_ONLY 45 -#define CAM_FORMAT_MAX 46 - -/* camera rotaion */ -#define CAM_ROTATE_CW_0_DEGREE 0 -#define CAM_ROTATE_CW_90_DEGREE 1 -#define CAM_RORATE_CW_180_DEGREE 2 -#define CAM_ROTATE_CW_270_DEGREE 3 - -/* camera Color Space */ -#define CAM_COLOR_SPACE_BASE 0 -#define CAM_COLOR_SPACE_BT601_FULL 1 -#define CAM_COLOR_SPACE_BT601625 2 -#define CAM_COLOR_SPACE_BT601525 3 -#define CAM_COLOR_SPACE_BT709 4 -#define CAM_COLOR_SPACE_DEPTH 5 -#define CAM_COLOR_SPACE_MAX 6 - -/* camera buffer direction */ -#define CAM_BUF_INPUT 1 -#define CAM_BUF_OUTPUT 2 -#define CAM_BUF_IN_OUT 3 - -/* camera packet device Type */ -#define CAM_PACKET_DEV_BASE 0 -#define CAM_PACKET_DEV_IMG_SENSOR 1 -#define CAM_PACKET_DEV_ACTUATOR 2 -#define CAM_PACKET_DEV_COMPANION 3 -#define CAM_PACKET_DEV_EEPOM 4 -#define CAM_PACKET_DEV_CSIPHY 5 -#define CAM_PACKET_DEV_OIS 6 -#define CAM_PACKET_DEV_FLASH 7 -#define CAM_PACKET_DEV_FD 8 -#define CAM_PACKET_DEV_JPEG_ENC 9 -#define CAM_PACKET_DEV_JPEG_DEC 10 -#define CAM_PACKET_DEV_VFE 11 -#define CAM_PACKET_DEV_CPP 12 -#define CAM_PACKET_DEV_CSID 13 -#define CAM_PACKET_DEV_ISPIF 14 -#define CAM_PACKET_DEV_IFE 15 -#define CAM_PACKET_DEV_ICP 16 -#define CAM_PACKET_DEV_LRME 17 -#define CAM_PACKET_DEV_MAX 18 - - -/* constants */ -#define CAM_PACKET_MAX_PLANES 3 - -/** - * struct cam_plane_cfg - Plane configuration info - * - * @width: Plane width in pixels - * @height: Plane height in lines - * @plane_stride: Plane stride in pixel - * @slice_height: Slice height in line (not used by ISP) - * @meta_stride: UBWC metadata stride - * @meta_size: UBWC metadata plane size - * @meta_offset: UBWC metadata offset - * @packer_config: UBWC packer config - * @mode_config: UBWC mode config - * @tile_config: UBWC tile config - * @h_init: UBWC horizontal initial coordinate in pixels - * @v_init: UBWC vertical initial coordinate in lines - * - */ -struct cam_plane_cfg { - uint32_t width; - uint32_t height; - uint32_t plane_stride; - uint32_t slice_height; - uint32_t meta_stride; - uint32_t meta_size; - uint32_t meta_offset; - uint32_t packer_config; - uint32_t mode_config; - uint32_t tile_config; - uint32_t h_init; - uint32_t v_init; -}; - -/** - * struct cam_cmd_buf_desc - Command buffer descriptor - * - * @mem_handle: Command buffer handle - * @offset: Command start offset - * @size: Size of the command buffer in bytes - * @length: Used memory in command buffer in bytes - * @type: Type of the command buffer - * @meta_data: Data type for private command buffer - * Between UMD and KMD - * - */ -struct cam_cmd_buf_desc { - int32_t mem_handle; - uint32_t offset; - uint32_t size; - uint32_t length; - uint32_t type; - uint32_t meta_data; -}; - -/** - * struct cam_buf_io_cfg - Buffer io configuration for buffers - * - * @mem_handle: Mem_handle array for the buffers. - * @offsets: Offsets for each planes in the buffer - * @planes: Per plane information - * @width: Main plane width in pixel - * @height: Main plane height in lines - * @format: Format of the buffer - * @color_space: Color space for the buffer - * @color_pattern: Color pattern in the buffer - * @bpp: Bit per pixel - * @rotation: Rotation information for the buffer - * @resource_type: Resource type associated with the buffer - * @fence: Fence handle - * @early_fence: Fence handle for early signal - * @aux_cmd_buf: An auxiliary command buffer that may be - * used for programming the IO - * @direction: Direction of the config - * @batch_size: Batch size in HFR mode - * @subsample_pattern: Subsample pattern. Used in HFR mode. It - * should be consistent with batchSize and - * CAMIF programming. - * @subsample_period: Subsample period. Used in HFR mode. It - * should be consistent with batchSize and - * CAMIF programming. - * @framedrop_pattern: Framedrop pattern - * @framedrop_period: Framedrop period - * @flag: Flags for extra information - * @direction: Buffer direction: input or output - * @padding: Padding for the structure - * - */ -struct cam_buf_io_cfg { - int32_t mem_handle[CAM_PACKET_MAX_PLANES]; - uint32_t offsets[CAM_PACKET_MAX_PLANES]; - struct cam_plane_cfg planes[CAM_PACKET_MAX_PLANES]; - uint32_t format; - uint32_t color_space; - uint32_t color_pattern; - uint32_t bpp; - uint32_t rotation; - uint32_t resource_type; - int32_t fence; - int32_t early_fence; - struct cam_cmd_buf_desc aux_cmd_buf; - uint32_t direction; - uint32_t batch_size; - uint32_t subsample_pattern; - uint32_t subsample_period; - uint32_t framedrop_pattern; - uint32_t framedrop_period; - uint32_t flag; - uint32_t padding; -}; - -/** - * struct cam_packet_header - Camera packet header - * - * @op_code: Camera packet opcode - * @size: Size of the camera packet in bytes - * @request_id: Request id for this camera packet - * @flags: Flags for the camera packet - * @padding: Padding - * - */ -struct cam_packet_header { - uint32_t op_code; - uint32_t size; - uint64_t request_id; - uint32_t flags; - uint32_t padding; -}; - -/** - * struct cam_patch_desc - Patch structure - * - * @dst_buf_hdl: Memory handle for the dest buffer - * @dst_offset: Offset byte in the dest buffer - * @src_buf_hdl: Memory handle for the source buffer - * @src_offset: Offset byte in the source buffer - * - */ -struct cam_patch_desc { - int32_t dst_buf_hdl; - uint32_t dst_offset; - int32_t src_buf_hdl; - uint32_t src_offset; -}; - -/** - * struct cam_packet - Camera packet structure - * - * @header: Camera packet header - * @cmd_buf_offset: Command buffer start offset - * @num_cmd_buf: Number of the command buffer in the packet - * @io_config_offset: Buffer io configuration start offset - * @num_io_configs: Number of the buffer io configurations - * @patch_offset: Patch offset for the patch structure - * @num_patches: Number of the patch structure - * @kmd_cmd_buf_index: Command buffer index which contains extra - * space for the KMD buffer - * @kmd_cmd_buf_offset: Offset from the beginning of the command - * buffer for KMD usage. - * @payload: Camera packet payload - * - */ -struct cam_packet { - struct cam_packet_header header; - uint32_t cmd_buf_offset; - uint32_t num_cmd_buf; - uint32_t io_configs_offset; - uint32_t num_io_configs; - uint32_t patch_offset; - uint32_t num_patches; - uint32_t kmd_cmd_buf_index; - uint32_t kmd_cmd_buf_offset; - uint64_t payload[1]; - -}; - -/** - * struct cam_release_dev_cmd - Control payload for release devices - * - * @session_handle: Session handle for the release - * @dev_handle: Device handle for the release - */ -struct cam_release_dev_cmd { - int32_t session_handle; - int32_t dev_handle; -}; - -/** - * struct cam_start_stop_dev_cmd - Control payload for start/stop device - * - * @session_handle: Session handle for the start/stop command - * @dev_handle: Device handle for the start/stop command - * - */ -struct cam_start_stop_dev_cmd { - int32_t session_handle; - int32_t dev_handle; -}; - -/** - * struct cam_config_dev_cmd - Command payload for configure device - * - * @session_handle: Session handle for the command - * @dev_handle: Device handle for the command - * @offset: Offset byte in the packet handle. - * @packet_handle: Packet memory handle for the actual packet: - * struct cam_packet. - * - */ -struct cam_config_dev_cmd { - int32_t session_handle; - int32_t dev_handle; - uint64_t offset; - uint64_t packet_handle; -}; - -/** - * struct cam_query_cap_cmd - Payload for query device capability - * - * @size: Handle size - * @handle_type: User pointer or shared memory handle - * @caps_handle: Device specific query command payload - * - */ -struct cam_query_cap_cmd { - uint32_t size; - uint32_t handle_type; - uint64_t caps_handle; -}; - -/** - * struct cam_acquire_dev_cmd - Control payload for acquire devices - * - * @session_handle: Session handle for the acquire command - * @dev_handle: Device handle to be returned - * @handle_type: Resource handle type: - * 1 = user pointer, 2 = mem handle - * @num_resources: Number of the resources to be acquired - * @resources_hdl: Resource handle that refers to the actual - * resource array. Each item in this - * array is device specific resource structure - * - */ -struct cam_acquire_dev_cmd { - int32_t session_handle; - int32_t dev_handle; - uint32_t handle_type; - uint32_t num_resources; - uint64_t resource_hdl; -}; - -/** - * struct cam_flush_dev_cmd - Control payload for flush devices - * - * @version: Version - * @session_handle: Session handle for the acquire command - * @dev_handle: Device handle to be returned - * @flush_type: Flush type: - * 0 = flush specific request - * 1 = flush all - * @reserved: Reserved for 64 bit aligngment - * @req_id: Request id that needs to cancel - * - */ -struct cam_flush_dev_cmd { - uint64_t version; - int32_t session_handle; - int32_t dev_handle; - uint32_t flush_type; - uint32_t reserved; - int64_t req_id; -}; - -#endif /* __UAPI_CAM_DEFS_H__ */ diff --git a/third_party/linux/include/media/cam_fd.h b/third_party/linux/include/media/cam_fd.h deleted file mode 100644 index 8feb6e4da8..0000000000 --- a/third_party/linux/include/media/cam_fd.h +++ /dev/null @@ -1,127 +0,0 @@ -#ifndef __UAPI_CAM_FD_H__ -#define __UAPI_CAM_FD_H__ - -#include "cam_defs.h" - -#define CAM_FD_MAX_FACES 35 -#define CAM_FD_RAW_RESULT_ENTRIES 512 - -/* FD Op Codes */ -#define CAM_PACKET_OPCODES_FD_FRAME_UPDATE 0x0 - -/* FD Command Buffer identifiers */ -#define CAM_FD_CMD_BUFFER_ID_GENERIC 0x0 -#define CAM_FD_CMD_BUFFER_ID_CDM 0x1 -#define CAM_FD_CMD_BUFFER_ID_MAX 0x2 - -/* FD Blob types */ -#define CAM_FD_BLOB_TYPE_SOC_CLOCK_BW_REQUEST 0x0 -#define CAM_FD_BLOB_TYPE_RAW_RESULTS_REQUIRED 0x1 - -/* FD Resource IDs */ -#define CAM_FD_INPUT_PORT_ID_IMAGE 0x0 -#define CAM_FD_INPUT_PORT_ID_MAX 0x1 - -#define CAM_FD_OUTPUT_PORT_ID_RESULTS 0x0 -#define CAM_FD_OUTPUT_PORT_ID_RAW_RESULTS 0x1 -#define CAM_FD_OUTPUT_PORT_ID_WORK_BUFFER 0x2 -#define CAM_FD_OUTPUT_PORT_ID_MAX 0x3 - -/** - * struct cam_fd_soc_clock_bw_request - SOC clock, bandwidth request info - * - * @clock_rate : Clock rate required while processing frame - * @bandwidth : Bandwidth required while processing frame - * @reserved : Reserved for future use - */ -struct cam_fd_soc_clock_bw_request { - uint64_t clock_rate; - uint64_t bandwidth; - uint64_t reserved[4]; -}; - -/** - * struct cam_fd_face - Face properties - * - * @prop1 : Property 1 of face - * @prop2 : Property 2 of face - * @prop3 : Property 3 of face - * @prop4 : Property 4 of face - * - * Do not change this layout, this is inline with how HW writes - * these values directly when the buffer is programmed to HW - */ -struct cam_fd_face { - uint32_t prop1; - uint32_t prop2; - uint32_t prop3; - uint32_t prop4; -}; - -/** - * struct cam_fd_results - FD results layout - * - * @faces : Array of faces with face properties - * @face_count : Number of faces detected - * @reserved : Reserved for alignment - * - * Do not change this layout, this is inline with how HW writes - * these values directly when the buffer is programmed to HW - */ -struct cam_fd_results { - struct cam_fd_face faces[CAM_FD_MAX_FACES]; - uint32_t face_count; - uint32_t reserved[3]; -}; - -/** - * struct cam_fd_hw_caps - Face properties - * - * @core_version : FD core version - * @wrapper_version : FD wrapper version - * @raw_results_available : Whether raw results are available on this HW - * @supported_modes : Modes supported by this HW. - * @reserved : Reserved for future use - */ -struct cam_fd_hw_caps { - struct cam_hw_version core_version; - struct cam_hw_version wrapper_version; - uint32_t raw_results_available; - uint32_t supported_modes; - uint64_t reserved; -}; - -/** - * struct cam_fd_query_cap_cmd - FD Query capabilities information - * - * @device_iommu : FD IOMMU handles - * @cdm_iommu : CDM iommu handles - * @hw_caps : FD HW capabilities - * @reserved : Reserved for alignment - */ -struct cam_fd_query_cap_cmd { - struct cam_iommu_handle device_iommu; - struct cam_iommu_handle cdm_iommu; - struct cam_fd_hw_caps hw_caps; - uint64_t reserved; -}; - -/** - * struct cam_fd_acquire_dev_info - FD acquire device information - * - * @clk_bw_request : SOC clock, bandwidth request - * @priority : Priority for this acquire - * @mode : Mode in which to run FD HW. - * @get_raw_results : Whether this acquire needs face raw results - * while frame processing - * @reserved : Reserved field for 64 bit alignment - */ -struct cam_fd_acquire_dev_info { - struct cam_fd_soc_clock_bw_request clk_bw_request; - uint32_t priority; - uint32_t mode; - uint32_t get_raw_results; - uint32_t reserved[13]; -}; - -#endif /* __UAPI_CAM_FD_H__ */ diff --git a/third_party/linux/include/media/cam_icp.h b/third_party/linux/include/media/cam_icp.h deleted file mode 100644 index 680d05b630..0000000000 --- a/third_party/linux/include/media/cam_icp.h +++ /dev/null @@ -1,179 +0,0 @@ -#ifndef __UAPI_CAM_ICP_H__ -#define __UAPI_CAM_ICP_H__ - -#include "cam_defs.h" - -/* icp, ipe, bps, cdm(ipe/bps) are used in querycap */ -#define CAM_ICP_DEV_TYPE_A5 1 -#define CAM_ICP_DEV_TYPE_IPE 2 -#define CAM_ICP_DEV_TYPE_BPS 3 -#define CAM_ICP_DEV_TYPE_IPE_CDM 4 -#define CAM_ICP_DEV_TYPE_BPS_CDM 5 -#define CAM_ICP_DEV_TYPE_MAX 5 - -/* definitions needed for icp aquire device */ -#define CAM_ICP_RES_TYPE_BPS 1 -#define CAM_ICP_RES_TYPE_IPE_RT 2 -#define CAM_ICP_RES_TYPE_IPE 3 -#define CAM_ICP_RES_TYPE_MAX 4 - -/* packet opcode types */ -#define CAM_ICP_OPCODE_IPE_UPDATE 0 -#define CAM_ICP_OPCODE_BPS_UPDATE 1 - -/* IPE input port resource type */ -#define CAM_ICP_IPE_INPUT_IMAGE_FULL 0x0 -#define CAM_ICP_IPE_INPUT_IMAGE_DS4 0x1 -#define CAM_ICP_IPE_INPUT_IMAGE_DS16 0x2 -#define CAM_ICP_IPE_INPUT_IMAGE_DS64 0x3 -#define CAM_ICP_IPE_INPUT_IMAGE_FULL_REF 0x4 -#define CAM_ICP_IPE_INPUT_IMAGE_DS4_REF 0x5 -#define CAM_ICP_IPE_INPUT_IMAGE_DS16_REF 0x6 -#define CAM_ICP_IPE_INPUT_IMAGE_DS64_REF 0x7 - -/* IPE output port resource type */ -#define CAM_ICP_IPE_OUTPUT_IMAGE_DISPLAY 0x8 -#define CAM_ICP_IPE_OUTPUT_IMAGE_VIDEO 0x9 -#define CAM_ICP_IPE_OUTPUT_IMAGE_FULL_REF 0xA -#define CAM_ICP_IPE_OUTPUT_IMAGE_DS4_REF 0xB -#define CAM_ICP_IPE_OUTPUT_IMAGE_DS16_REF 0xC -#define CAM_ICP_IPE_OUTPUT_IMAGE_DS64_REF 0xD - -#define CAM_ICP_IPE_IMAGE_MAX 0xE - -/* BPS input port resource type */ -#define CAM_ICP_BPS_INPUT_IMAGE 0x0 - -/* BPS output port resource type */ -#define CAM_ICP_BPS_OUTPUT_IMAGE_FULL 0x1 -#define CAM_ICP_BPS_OUTPUT_IMAGE_DS4 0x2 -#define CAM_ICP_BPS_OUTPUT_IMAGE_DS16 0x3 -#define CAM_ICP_BPS_OUTPUT_IMAGE_DS64 0x4 -#define CAM_ICP_BPS_OUTPUT_IMAGE_STATS_BG 0x5 -#define CAM_ICP_BPS_OUTPUT_IMAGE_STATS_BHIST 0x6 -#define CAM_ICP_BPS_OUTPUT_IMAGE_REG1 0x7 -#define CAM_ICP_BPS_OUTPUT_IMAGE_REG2 0x8 - -#define CAM_ICP_BPS_IO_IMAGES_MAX 0x9 - -/* Command meta types */ -#define CAM_ICP_CMD_META_GENERIC_BLOB 0x1 - -/* Generic blob types */ -#define CAM_ICP_CMD_GENERIC_BLOB_CLK 0x1 -#define CAM_ICP_CMD_GENERIC_BLOB_CFG_IO 0x2 - -/** - * struct cam_icp_clk_bw_request - * - * @budget_ns: Time required to process frame - * @frame_cycles: Frame cycles needed to process the frame - * @rt_flag: Flag to indicate real time stream - * @uncompressed_bw: Bandwidth required to process frame - * @compressed_bw: Compressed bandwidth to process frame - */ -struct cam_icp_clk_bw_request { - uint64_t budget_ns; - uint32_t frame_cycles; - uint32_t rt_flag; - uint64_t uncompressed_bw; - uint64_t compressed_bw; -}; - -/** - * struct cam_icp_dev_ver - Device information for particular hw type - * - * This is used to get device version info of - * ICP, IPE, BPS and CDM related IPE and BPS from firmware - * and use this info in CAM_QUERY_CAP IOCTL - * - * @dev_type: hardware type for the cap info(icp, ipe, bps, cdm(ipe/bps)) - * @reserved: reserved field - * @hw_ver: major, minor and incr values of a device version - */ -struct cam_icp_dev_ver { - uint32_t dev_type; - uint32_t reserved; - struct cam_hw_version hw_ver; -}; - -/** - * struct cam_icp_ver - ICP version info - * - * This strcuture is used for fw and api version - * this is used to get firmware version and api version from firmware - * and use this info in CAM_QUERY_CAP IOCTL - * - * @major: FW version major - * @minor: FW version minor - * @revision: FW version increment - */ -struct cam_icp_ver { - uint32_t major; - uint32_t minor; - uint32_t revision; - uint32_t reserved; -}; - -/** - * struct cam_icp_query_cap_cmd - ICP query device capability payload - * - * @dev_iommu_handle: icp iommu handles for secure/non secure modes - * @cdm_iommu_handle: iommu handles for secure/non secure modes - * @fw_version: firmware version info - * @api_version: api version info - * @num_ipe: number of ipes - * @num_bps: number of bps - * @dev_ver: returned device capability array - */ -struct cam_icp_query_cap_cmd { - struct cam_iommu_handle dev_iommu_handle; - struct cam_iommu_handle cdm_iommu_handle; - struct cam_icp_ver fw_version; - struct cam_icp_ver api_version; - uint32_t num_ipe; - uint32_t num_bps; - struct cam_icp_dev_ver dev_ver[CAM_ICP_DEV_TYPE_MAX]; -}; - -/** - * struct cam_icp_res_info - ICP output resource info - * - * @format: format of the resource - * @width: width in pixels - * @height: height in lines - * @fps: fps - */ -struct cam_icp_res_info { - uint32_t format; - uint32_t width; - uint32_t height; - uint32_t fps; -}; - -/** - * struct cam_icp_acquire_dev_info - An ICP device info - * - * @scratch_mem_size: Output param - size of scratch memory - * @dev_type: device type (IPE_RT/IPE_NON_RT/BPS) - * @io_config_cmd_size: size of IO config command - * @io_config_cmd_handle: IO config command for each acquire - * @secure_mode: camera mode (secure/non secure) - * @chain_info: chaining info of FW device handles - * @in_res: resource info used for clock and bandwidth calculation - * @num_out_res: number of output resources - * @out_res: output resource - */ -struct cam_icp_acquire_dev_info { - uint32_t scratch_mem_size; - uint32_t dev_type; - uint32_t io_config_cmd_size; - int32_t io_config_cmd_handle; - uint32_t secure_mode; - int32_t chain_info; - struct cam_icp_res_info in_res; - uint32_t num_out_res; - struct cam_icp_res_info out_res[1]; -} __attribute__((__packed__)); - -#endif /* __UAPI_CAM_ICP_H__ */ diff --git a/third_party/linux/include/media/cam_isp.h b/third_party/linux/include/media/cam_isp.h deleted file mode 100644 index 266840d38c..0000000000 --- a/third_party/linux/include/media/cam_isp.h +++ /dev/null @@ -1,379 +0,0 @@ -#ifndef __UAPI_CAM_ISP_H__ -#define __UAPI_CAM_ISP_H__ - -#include "cam_defs.h" -#include "cam_isp_vfe.h" -#include "cam_isp_ife.h" - - -/* ISP driver name */ -#define CAM_ISP_DEV_NAME "cam-isp" - -/* HW type */ -#define CAM_ISP_HW_BASE 0 -#define CAM_ISP_HW_CSID 1 -#define CAM_ISP_HW_VFE 2 -#define CAM_ISP_HW_IFE 3 -#define CAM_ISP_HW_ISPIF 4 -#define CAM_ISP_HW_MAX 5 - -/* Color Pattern */ -#define CAM_ISP_PATTERN_BAYER_RGRGRG 0 -#define CAM_ISP_PATTERN_BAYER_GRGRGR 1 -#define CAM_ISP_PATTERN_BAYER_BGBGBG 2 -#define CAM_ISP_PATTERN_BAYER_GBGBGB 3 -#define CAM_ISP_PATTERN_YUV_YCBYCR 4 -#define CAM_ISP_PATTERN_YUV_YCRYCB 5 -#define CAM_ISP_PATTERN_YUV_CBYCRY 6 -#define CAM_ISP_PATTERN_YUV_CRYCBY 7 -#define CAM_ISP_PATTERN_MAX 8 - -/* Usage Type */ -#define CAM_ISP_RES_USAGE_SINGLE 0 -#define CAM_ISP_RES_USAGE_DUAL 1 -#define CAM_ISP_RES_USAGE_MAX 2 - -/* Resource ID */ -#define CAM_ISP_RES_ID_PORT 0 -#define CAM_ISP_RES_ID_CLK 1 -#define CAM_ISP_RES_ID_MAX 2 - -/* Resource Type - Type of resource for the resource id - * defined in cam_isp_vfe.h, cam_isp_ife.h - */ - -/* Lane Type in input resource for Port */ -#define CAM_ISP_LANE_TYPE_DPHY 0 -#define CAM_ISP_LANE_TYPE_CPHY 1 -#define CAM_ISP_LANE_TYPE_MAX 2 - -/* ISP Resurce Composite Group ID */ -#define CAM_ISP_RES_COMP_GROUP_NONE 0 -#define CAM_ISP_RES_COMP_GROUP_ID_0 1 -#define CAM_ISP_RES_COMP_GROUP_ID_1 2 -#define CAM_ISP_RES_COMP_GROUP_ID_2 3 -#define CAM_ISP_RES_COMP_GROUP_ID_3 4 -#define CAM_ISP_RES_COMP_GROUP_ID_4 5 -#define CAM_ISP_RES_COMP_GROUP_ID_5 6 -#define CAM_ISP_RES_COMP_GROUP_ID_MAX 6 - -/* ISP packet opcode for ISP */ -#define CAM_ISP_PACKET_OP_BASE 0 -#define CAM_ISP_PACKET_INIT_DEV 1 -#define CAM_ISP_PACKET_UPDATE_DEV 2 -#define CAM_ISP_PACKET_OP_MAX 3 - -/* ISP packet meta_data type for command buffer */ -#define CAM_ISP_PACKET_META_BASE 0 -#define CAM_ISP_PACKET_META_LEFT 1 -#define CAM_ISP_PACKET_META_RIGHT 2 -#define CAM_ISP_PACKET_META_COMMON 3 -#define CAM_ISP_PACKET_META_DMI_LEFT 4 -#define CAM_ISP_PACKET_META_DMI_RIGHT 5 -#define CAM_ISP_PACKET_META_DMI_COMMON 6 -#define CAM_ISP_PACKET_META_CLOCK 7 -#define CAM_ISP_PACKET_META_CSID 8 -#define CAM_ISP_PACKET_META_DUAL_CONFIG 9 -#define CAM_ISP_PACKET_META_GENERIC_BLOB_LEFT 10 -#define CAM_ISP_PACKET_META_GENERIC_BLOB_RIGHT 11 -#define CAM_ISP_PACKET_META_GENERIC_BLOB_COMMON 12 - -/* DSP mode */ -#define CAM_ISP_DSP_MODE_NONE 0 -#define CAM_ISP_DSP_MODE_ONE_WAY 1 -#define CAM_ISP_DSP_MODE_ROUND 2 - -/* ISP Generic Cmd Buffer Blob types */ -#define CAM_ISP_GENERIC_BLOB_TYPE_HFR_CONFIG 0 -#define CAM_ISP_GENERIC_BLOB_TYPE_CLOCK_CONFIG 1 -#define CAM_ISP_GENERIC_BLOB_TYPE_BW_CONFIG 2 - -/* Query devices */ -/** - * struct cam_isp_dev_cap_info - A cap info for particular hw type - * - * @hw_type: Hardware type for the cap info - * @reserved: reserved field for alignment - * @hw_version: Hardware version - * - */ -struct cam_isp_dev_cap_info { - uint32_t hw_type; - uint32_t reserved; - struct cam_hw_version hw_version; -}; - -/** - * struct cam_isp_query_cap_cmd - ISP query device capability payload - * - * @device_iommu: returned iommu handles for device - * @cdm_iommu: returned iommu handles for cdm - * @num_dev: returned number of device capabilities - * @reserved: reserved field for alignment - * @dev_caps: returned device capability array - * - */ -struct cam_isp_query_cap_cmd { - struct cam_iommu_handle device_iommu; - struct cam_iommu_handle cdm_iommu; - int32_t num_dev; - uint32_t reserved; - struct cam_isp_dev_cap_info dev_caps[CAM_ISP_HW_MAX]; -}; - -/* Acquire Device */ -/** - * struct cam_isp_out_port_info - An output port resource info - * - * @res_type: output resource type defined in file - * cam_isp_vfe.h or cam_isp_ife.h - * @format: output format of the resource - * @wdith: output width in pixels - * @height: output height in lines - * @comp_grp_id: composite group id for the resource. - * @split_point: split point in pixels for the dual VFE. - * @secure_mode: flag to tell if output should be run in secure - * mode or not. See cam_defs.h for definition - * @reserved: reserved field for alignment - * - */ -struct cam_isp_out_port_info { - uint32_t res_type; - uint32_t format; - uint32_t width; - uint32_t height; - uint32_t comp_grp_id; - uint32_t split_point; - uint32_t secure_mode; - uint32_t reserved; -}; - -/** - * struct cam_isp_in_port_info - An input port resource info - * - * @res_type: input resource type define in file - * cam_isp_vfe.h or cam_isp_ife.h - * @lane_type: lane type: c-phy or d-phy. - * @lane_num: active lane number - * @lane_cfg: lane configurations: 4 bits per lane - * @vc: input virtual channel number - * @dt: input data type number - * @format: input format - * @test_pattern: test pattern for the testgen - * @usage_type: whether dual vfe is required - * @left_start: left input start offset in pixels - * @left_stop: left input stop offset in pixels - * @left_width: left input width in pixels - * @right_start: right input start offset in pixels. - * Only for Dual VFE - * @right_stop: right input stop offset in pixels. - * Only for Dual VFE - * @right_width: right input width in pixels. - * Only for dual VFE - * @line_start: top of the line number - * @line_stop: bottome of the line number - * @height: input height in lines - * @pixel_clk; sensor output clock - * @batch_size: batch size for HFR mode - * @dsp_mode: DSP stream mode (Defines as CAM_ISP_DSP_MODE_*) - * @hbi_cnt: HBI count for the camif input - * @reserved: Reserved field for alignment - * @num_out_res: number of the output resource associated - * @data: payload that contains the output resources - * - */ -struct cam_isp_in_port_info { - uint32_t res_type; - uint32_t lane_type; - uint32_t lane_num; - uint32_t lane_cfg; - uint32_t vc; - uint32_t dt; - uint32_t format; - uint32_t test_pattern; - uint32_t usage_type; - uint32_t left_start; - uint32_t left_stop; - uint32_t left_width; - uint32_t right_start; - uint32_t right_stop; - uint32_t right_width; - uint32_t line_start; - uint32_t line_stop; - uint32_t height; - uint32_t pixel_clk; - uint32_t batch_size; - uint32_t dsp_mode; - uint32_t hbi_cnt; - uint32_t custom_csid; - uint32_t reserved; - uint32_t num_out_res; - struct cam_isp_out_port_info data[1]; -}; - -/** - * struct cam_isp_resource - A resource bundle - * - * @resoruce_id: resource id for the resource bundle - * @length: length of the while resource blob - * @handle_type: type of the resource handle - * @reserved: reserved field for alignment - * @res_hdl: resource handle that points to the - * resource array; - * - */ -struct cam_isp_resource { - uint32_t resource_id; - uint32_t length; - uint32_t handle_type; - uint32_t reserved; - uint64_t res_hdl; -}; - -/** - * struct cam_isp_port_hfr_config - HFR configuration for this port - * - * @resource_type: Resource type - * @subsample_pattern: Subsample pattern. Used in HFR mode. It - * should be consistent with batchSize and - * CAMIF programming. - * @subsample_period: Subsample period. Used in HFR mode. It - * should be consistent with batchSize and - * CAMIF programming. - * @framedrop_pattern: Framedrop pattern - * @framedrop_period: Framedrop period - * @reserved: Reserved for alignment - */ -struct cam_isp_port_hfr_config { - uint32_t resource_type; - uint32_t subsample_pattern; - uint32_t subsample_period; - uint32_t framedrop_pattern; - uint32_t framedrop_period; - uint32_t reserved; -} __attribute__((packed)); - -/** - * struct cam_isp_resource_hfr_config - Resource HFR configuration - * - * @num_ports: Number of ports - * @reserved: Reserved for alignment - * @port_hfr_config: HFR configuration for each IO port - */ -struct cam_isp_resource_hfr_config { - uint32_t num_ports; - uint32_t reserved; - struct cam_isp_port_hfr_config port_hfr_config[1]; -} __attribute__((packed)); - -/** - * struct cam_isp_dual_split_params - dual isp spilt parameters - * - * @split_point: Split point information x, where (0 < x < width) - * left ISP's input ends at x + righ padding and - * Right ISP's input starts at x - left padding - * @right_padding: Padding added past the split point for left - * ISP's input - * @left_padding: Padding added before split point for right - * ISP's input - * @reserved: Reserved filed for alignment - * - */ -struct cam_isp_dual_split_params { - uint32_t split_point; - uint32_t right_padding; - uint32_t left_padding; - uint32_t reserved; -}; - -/** - * struct cam_isp_dual_stripe_config - stripe config per bus client - * - * @offset: Start horizontal offset relative to - * output buffer - * In UBWC mode, this value indicates the H_INIT - * value in pixel - * @width: Width of the stripe in bytes - * @tileconfig Ubwc meta tile config. Contain the partial - * tile info - * @port_id: port id of ISP output - * - */ -struct cam_isp_dual_stripe_config { - uint32_t offset; - uint32_t width; - uint32_t tileconfig; - uint32_t port_id; -}; - -/** - * struct cam_isp_dual_config - dual isp configuration - * - * @num_ports Number of isp output ports - * @reserved Reserved field for alignment - * @split_params: Inpput split parameters - * @stripes: Stripe information - * - */ -struct cam_isp_dual_config { - uint32_t num_ports; - uint32_t reserved; - struct cam_isp_dual_split_params split_params; - struct cam_isp_dual_stripe_config stripes[1]; -} __attribute__((packed)); - -/** - * struct cam_isp_clock_config - Clock configuration - * - * @usage_type: Usage type (Single/Dual) - * @num_rdi: Number of RDI votes - * @left_pix_hz: Pixel Clock for Left ISP - * @right_pix_hz: Pixel Clock for Right ISP, valid only if Dual - * @rdi_hz: RDI Clock. ISP clock will be max of RDI and - * PIX clocks. For a particular context which ISP - * HW the RDI is allocated to is not known to UMD. - * Hence pass the clock and let KMD decide. - */ -struct cam_isp_clock_config { - uint32_t usage_type; - uint32_t num_rdi; - uint64_t left_pix_hz; - uint64_t right_pix_hz; - uint64_t rdi_hz[1]; -} __attribute__((packed)); - -/** - * struct cam_isp_bw_vote - Bandwidth vote information - * - * @resource_id: Resource ID - * @reserved: Reserved field for alignment - * @cam_bw_bps: Bandwidth vote for CAMNOC - * @ext_bw_bps: Bandwidth vote for path-to-DDR after CAMNOC - */ - -struct cam_isp_bw_vote { - uint32_t resource_id; - uint32_t reserved; - uint64_t cam_bw_bps; - uint64_t ext_bw_bps; -} __attribute__((packed)); - -/** - * struct cam_isp_bw_config - Bandwidth configuration - * - * @usage_type: Usage type (Single/Dual) - * @num_rdi: Number of RDI votes - * @left_pix_vote: Bandwidth vote for left ISP - * @right_pix_vote: Bandwidth vote for right ISP - * @rdi_vote: RDI bandwidth requirements - */ - -struct cam_isp_bw_config { - uint32_t usage_type; - uint32_t num_rdi; - struct cam_isp_bw_vote left_pix_vote; - struct cam_isp_bw_vote right_pix_vote; - struct cam_isp_bw_vote rdi_vote[1]; -} __attribute__((packed)); - -#endif /* __UAPI_CAM_ISP_H__ */ diff --git a/third_party/linux/include/media/cam_isp_ife.h b/third_party/linux/include/media/cam_isp_ife.h deleted file mode 100644 index f5e72813fc..0000000000 --- a/third_party/linux/include/media/cam_isp_ife.h +++ /dev/null @@ -1,39 +0,0 @@ -#ifndef __UAPI_CAM_ISP_IFE_H__ -#define __UAPI_CAM_ISP_IFE_H__ - -/* IFE output port resource type (global unique)*/ -#define CAM_ISP_IFE_OUT_RES_BASE 0x3000 - -#define CAM_ISP_IFE_OUT_RES_FULL (CAM_ISP_IFE_OUT_RES_BASE + 0) -#define CAM_ISP_IFE_OUT_RES_DS4 (CAM_ISP_IFE_OUT_RES_BASE + 1) -#define CAM_ISP_IFE_OUT_RES_DS16 (CAM_ISP_IFE_OUT_RES_BASE + 2) -#define CAM_ISP_IFE_OUT_RES_RAW_DUMP (CAM_ISP_IFE_OUT_RES_BASE + 3) -#define CAM_ISP_IFE_OUT_RES_FD (CAM_ISP_IFE_OUT_RES_BASE + 4) -#define CAM_ISP_IFE_OUT_RES_PDAF (CAM_ISP_IFE_OUT_RES_BASE + 5) -#define CAM_ISP_IFE_OUT_RES_RDI_0 (CAM_ISP_IFE_OUT_RES_BASE + 6) -#define CAM_ISP_IFE_OUT_RES_RDI_1 (CAM_ISP_IFE_OUT_RES_BASE + 7) -#define CAM_ISP_IFE_OUT_RES_RDI_2 (CAM_ISP_IFE_OUT_RES_BASE + 8) -#define CAM_ISP_IFE_OUT_RES_RDI_3 (CAM_ISP_IFE_OUT_RES_BASE + 9) -#define CAM_ISP_IFE_OUT_RES_STATS_HDR_BE (CAM_ISP_IFE_OUT_RES_BASE + 10) -#define CAM_ISP_IFE_OUT_RES_STATS_HDR_BHIST (CAM_ISP_IFE_OUT_RES_BASE + 11) -#define CAM_ISP_IFE_OUT_RES_STATS_TL_BG (CAM_ISP_IFE_OUT_RES_BASE + 12) -#define CAM_ISP_IFE_OUT_RES_STATS_BF (CAM_ISP_IFE_OUT_RES_BASE + 13) -#define CAM_ISP_IFE_OUT_RES_STATS_AWB_BG (CAM_ISP_IFE_OUT_RES_BASE + 14) -#define CAM_ISP_IFE_OUT_RES_STATS_BHIST (CAM_ISP_IFE_OUT_RES_BASE + 15) -#define CAM_ISP_IFE_OUT_RES_STATS_RS (CAM_ISP_IFE_OUT_RES_BASE + 16) -#define CAM_ISP_IFE_OUT_RES_STATS_CS (CAM_ISP_IFE_OUT_RES_BASE + 17) -#define CAM_ISP_IFE_OUT_RES_STATS_IHIST (CAM_ISP_IFE_OUT_RES_BASE + 18) -#define CAM_ISP_IFE_OUT_RES_MAX (CAM_ISP_IFE_OUT_RES_BASE + 19) - - -/* IFE input port resource type (global unique) */ -#define CAM_ISP_IFE_IN_RES_BASE 0x4000 - -#define CAM_ISP_IFE_IN_RES_TPG (CAM_ISP_IFE_IN_RES_BASE + 0) -#define CAM_ISP_IFE_IN_RES_PHY_0 (CAM_ISP_IFE_IN_RES_BASE + 1) -#define CAM_ISP_IFE_IN_RES_PHY_1 (CAM_ISP_IFE_IN_RES_BASE + 2) -#define CAM_ISP_IFE_IN_RES_PHY_2 (CAM_ISP_IFE_IN_RES_BASE + 3) -#define CAM_ISP_IFE_IN_RES_PHY_3 (CAM_ISP_IFE_IN_RES_BASE + 4) -#define CAM_ISP_IFE_IN_RES_MAX (CAM_ISP_IFE_IN_RES_BASE + 5) - -#endif /* __UAPI_CAM_ISP_IFE_H__ */ diff --git a/third_party/linux/include/media/cam_isp_vfe.h b/third_party/linux/include/media/cam_isp_vfe.h deleted file mode 100644 index e48db2f98d..0000000000 --- a/third_party/linux/include/media/cam_isp_vfe.h +++ /dev/null @@ -1,44 +0,0 @@ -#ifndef __UAPI_CAM_ISP_VFE_H__ -#define __UAPI_CAM_ISP_VFE_H__ - -/* VFE output port resource type (global unique) */ -#define CAM_ISP_VFE_OUT_RES_BASE 0x1000 - -#define CAM_ISP_VFE_OUT_RES_ENC (CAM_ISP_VFE_OUT_RES_BASE + 0) -#define CAM_ISP_VFE_OUT_RES_VIEW (CAM_ISP_VFE_OUT_RES_BASE + 1) -#define CAM_ISP_VFE_OUT_RES_VID (CAM_ISP_VFE_OUT_RES_BASE + 2) -#define CAM_ISP_VFE_OUT_RES_RDI_0 (CAM_ISP_VFE_OUT_RES_BASE + 3) -#define CAM_ISP_VFE_OUT_RES_RDI_1 (CAM_ISP_VFE_OUT_RES_BASE + 4) -#define CAM_ISP_VFE_OUT_RES_RDI_2 (CAM_ISP_VFE_OUT_RES_BASE + 5) -#define CAM_ISP_VFE_OUT_RES_RDI_3 (CAM_ISP_VFE_OUT_RES_BASE + 6) -#define CAM_ISP_VFE_OUT_RES_STATS_AEC (CAM_ISP_VFE_OUT_RES_BASE + 7) -#define CAM_ISP_VFE_OUT_RES_STATS_AF (CAM_ISP_VFE_OUT_RES_BASE + 8) -#define CAM_ISP_VFE_OUT_RES_STATS_AWB (CAM_ISP_VFE_OUT_RES_BASE + 9) -#define CAM_ISP_VFE_OUT_RES_STATS_RS (CAM_ISP_VFE_OUT_RES_BASE + 10) -#define CAM_ISP_VFE_OUT_RES_STATS_CS (CAM_ISP_VFE_OUT_RES_BASE + 11) -#define CAM_ISP_VFE_OUT_RES_STATS_IHIST (CAM_ISP_VFE_OUT_RES_BASE + 12) -#define CAM_ISP_VFE_OUT_RES_STATS_SKIN (CAM_ISP_VFE_OUT_RES_BASE + 13) -#define CAM_ISP_VFE_OUT_RES_STATS_BG (CAM_ISP_VFE_OUT_RES_BASE + 14) -#define CAM_ISP_VFE_OUT_RES_STATS_BF (CAM_ISP_VFE_OUT_RES_BASE + 15) -#define CAM_ISP_VFE_OUT_RES_STATS_BE (CAM_ISP_VFE_OUT_RES_BASE + 16) -#define CAM_ISP_VFE_OUT_RES_STATS_BHIST (CAM_ISP_VFE_OUT_RES_BASE + 17) -#define CAM_ISP_VFE_OUT_RES_STATS_BF_SCALE (CAM_ISP_VFE_OUT_RES_BASE + 18) -#define CAM_ISP_VFE_OUT_RES_STATS_HDR_BE (CAM_ISP_VFE_OUT_RES_BASE + 19) -#define CAM_ISP_VFE_OUT_RES_STATS_HDR_BHIST (CAM_ISP_VFE_OUT_RES_BASE + 20) -#define CAM_ISP_VFE_OUT_RES_STATS_AEC_BG (CAM_ISP_VFE_OUT_RES_BASE + 21) -#define CAM_ISP_VFE_OUT_RES_CAMIF_RAW (CAM_ISP_VFE_OUT_RES_BASE + 22) -#define CAM_ISP_VFE_OUT_RES_IDEAL_RAW (CAM_ISP_VFE_OUT_RES_BASE + 23) -#define CAM_ISP_VFE_OUT_RES_MAX (CAM_ISP_VFE_OUT_RES_BASE + 24) - -/* VFE input port_ resource type (global unique) */ -#define CAM_ISP_VFE_IN_RES_BASE 0x2000 - -#define CAM_ISP_VFE_IN_RES_TPG (CAM_ISP_VFE_IN_RES_BASE + 0) -#define CAM_ISP_VFE_IN_RES_PHY_0 (CAM_ISP_VFE_IN_RES_BASE + 1) -#define CAM_ISP_VFE_IN_RES_PHY_1 (CAM_ISP_VFE_IN_RES_BASE + 2) -#define CAM_ISP_VFE_IN_RES_PHY_2 (CAM_ISP_VFE_IN_RES_BASE + 3) -#define CAM_ISP_VFE_IN_RES_PHY_3 (CAM_ISP_VFE_IN_RES_BASE + 4) -#define CAM_ISP_VFE_IN_RES_FE (CAM_ISP_VFE_IN_RES_BASE + 5) -#define CAM_ISP_VFE_IN_RES_MAX (CAM_ISP_VFE_IN_RES_BASE + 6) - -#endif /* __UAPI_CAM_ISP_VFE_H__ */ diff --git a/third_party/linux/include/media/cam_jpeg.h b/third_party/linux/include/media/cam_jpeg.h deleted file mode 100644 index f3082f3bfe..0000000000 --- a/third_party/linux/include/media/cam_jpeg.h +++ /dev/null @@ -1,117 +0,0 @@ -#ifndef __UAPI_CAM_JPEG_H__ -#define __UAPI_CAM_JPEG_H__ - -#include "cam_defs.h" - -/* enc, dma, cdm(enc/dma) are used in querycap */ -#define CAM_JPEG_DEV_TYPE_ENC 0 -#define CAM_JPEG_DEV_TYPE_DMA 1 -#define CAM_JPEG_DEV_TYPE_MAX 2 - -#define CAM_JPEG_NUM_DEV_PER_RES_MAX 1 - -/* definitions needed for jpeg aquire device */ -#define CAM_JPEG_RES_TYPE_ENC 0 -#define CAM_JPEG_RES_TYPE_DMA 1 -#define CAM_JPEG_RES_TYPE_MAX 2 - -/* packet opcode types */ -#define CAM_JPEG_OPCODE_ENC_UPDATE 0 -#define CAM_JPEG_OPCODE_DMA_UPDATE 1 - -/* ENC input port resource type */ -#define CAM_JPEG_ENC_INPUT_IMAGE 0x0 - -/* ENC output port resource type */ -#define CAM_JPEG_ENC_OUTPUT_IMAGE 0x1 - -#define CAM_JPEG_ENC_IO_IMAGES_MAX 0x2 - -/* DMA input port resource type */ -#define CAM_JPEG_DMA_INPUT_IMAGE 0x0 - -/* DMA output port resource type */ -#define CAM_JPEG_DMA_OUTPUT_IMAGE 0x1 - -#define CAM_JPEG_DMA_IO_IMAGES_MAX 0x2 - -#define CAM_JPEG_IMAGE_MAX 0x2 - -/** - * struct cam_jpeg_dev_ver - Device information for particular hw type - * - * This is used to get device version info of JPEG ENC, JPEG DMA - * from hardware and use this info in CAM_QUERY_CAP IOCTL - * - * @size : Size of struct passed - * @dev_type: Hardware type for the cap info(jpeg enc, jpeg dma) - * @hw_ver: Major, minor and incr values of a device version - */ -struct cam_jpeg_dev_ver { - uint32_t size; - uint32_t dev_type; - struct cam_hw_version hw_ver; -}; - -/** - * struct cam_jpeg_query_cap_cmd - JPEG query device capability payload - * - * @dev_iommu_handle: Jpeg iommu handles for secure/non secure - * modes - * @cdm_iommu_handle: Iommu handles for secure/non secure modes - * @num_enc: Number of encoder - * @num_dma: Number of dma - * @dev_ver: Returned device capability array - */ -struct cam_jpeg_query_cap_cmd { - struct cam_iommu_handle dev_iommu_handle; - struct cam_iommu_handle cdm_iommu_handle; - uint32_t num_enc; - uint32_t num_dma; - struct cam_jpeg_dev_ver dev_ver[CAM_JPEG_DEV_TYPE_MAX]; -}; - -/** - * struct cam_jpeg_res_info - JPEG output resource info - * - * @format: Format of the resource - * @width: Width in pixels - * @height: Height in lines - * @fps: Fps - */ -struct cam_jpeg_res_info { - uint32_t format; - uint32_t width; - uint32_t height; - uint32_t fps; -}; - -/** - * struct cam_jpeg_acquire_dev_info - An JPEG device info - * - * @dev_type: Device type (ENC/DMA) - * @reserved: Reserved Bytes - * @in_res: In resource info - * @in_res: Iut resource info - */ -struct cam_jpeg_acquire_dev_info { - uint32_t dev_type; - uint32_t reserved; - struct cam_jpeg_res_info in_res; - struct cam_jpeg_res_info out_res; -}; - -/** - * struct cam_jpeg_config_inout_param_info - JPEG Config time - * input output params - * - * @clk_index: Input Param- clock selection index.(-1 default) - * @output_size: Output Param - jpeg encode/dma output size in - * bytes - */ -struct cam_jpeg_config_inout_param_info { - int32_t clk_index; - int32_t output_size; -}; - -#endif /* __UAPI_CAM_JPEG_H__ */ diff --git a/third_party/linux/include/media/cam_lrme.h b/third_party/linux/include/media/cam_lrme.h deleted file mode 100644 index 97d957835e..0000000000 --- a/third_party/linux/include/media/cam_lrme.h +++ /dev/null @@ -1,65 +0,0 @@ -#ifndef __UAPI_CAM_LRME_H__ -#define __UAPI_CAM_LRME_H__ - -#include "cam_defs.h" - -/* LRME Resource Types */ - -enum CAM_LRME_IO_TYPE { - CAM_LRME_IO_TYPE_TAR, - CAM_LRME_IO_TYPE_REF, - CAM_LRME_IO_TYPE_RES, - CAM_LRME_IO_TYPE_DS2, -}; - -#define CAM_LRME_INPUT_PORT_TYPE_TAR (1 << 0) -#define CAM_LRME_INPUT_PORT_TYPE_REF (1 << 1) - -#define CAM_LRME_OUTPUT_PORT_TYPE_DS2 (1 << 0) -#define CAM_LRME_OUTPUT_PORT_TYPE_RES (1 << 1) - -#define CAM_LRME_DEV_MAX 1 - - -struct cam_lrme_hw_version { - uint32_t gen; - uint32_t rev; - uint32_t step; -}; - -struct cam_lrme_dev_cap { - struct cam_lrme_hw_version clc_hw_version; - struct cam_lrme_hw_version bus_rd_hw_version; - struct cam_lrme_hw_version bus_wr_hw_version; - struct cam_lrme_hw_version top_hw_version; - struct cam_lrme_hw_version top_titan_version; -}; - -/** - * struct cam_lrme_query_cap_cmd - LRME query device capability payload - * - * @dev_iommu_handle: LRME iommu handles for secure/non secure - * modes - * @cdm_iommu_handle: Iommu handles for secure/non secure modes - * @num_devices: number of hardware devices - * @dev_caps: Returned device capability array - */ -struct cam_lrme_query_cap_cmd { - struct cam_iommu_handle device_iommu; - struct cam_iommu_handle cdm_iommu; - uint32_t num_devices; - struct cam_lrme_dev_cap dev_caps[CAM_LRME_DEV_MAX]; -}; - -struct cam_lrme_soc_info { - uint64_t clock_rate; - uint64_t bandwidth; - uint64_t reserved[4]; -}; - -struct cam_lrme_acquire_args { - struct cam_lrme_soc_info lrme_soc_info; -}; - -#endif /* __UAPI_CAM_LRME_H__ */ - diff --git a/third_party/linux/include/media/cam_req_mgr.h b/third_party/linux/include/media/cam_req_mgr.h deleted file mode 100644 index ae65649964..0000000000 --- a/third_party/linux/include/media/cam_req_mgr.h +++ /dev/null @@ -1,436 +0,0 @@ -#ifndef __UAPI_LINUX_CAM_REQ_MGR_H -#define __UAPI_LINUX_CAM_REQ_MGR_H - -#include -#include -#include -#include -#include - -#define CAM_REQ_MGR_VNODE_NAME "cam-req-mgr-devnode" - -#define CAM_DEVICE_TYPE_BASE (MEDIA_ENT_F_OLD_BASE) -#define CAM_VNODE_DEVICE_TYPE (CAM_DEVICE_TYPE_BASE) -#define CAM_SENSOR_DEVICE_TYPE (CAM_DEVICE_TYPE_BASE + 1) -#define CAM_IFE_DEVICE_TYPE (CAM_DEVICE_TYPE_BASE + 2) -#define CAM_ICP_DEVICE_TYPE (CAM_DEVICE_TYPE_BASE + 3) -#define CAM_LRME_DEVICE_TYPE (CAM_DEVICE_TYPE_BASE + 4) -#define CAM_JPEG_DEVICE_TYPE (CAM_DEVICE_TYPE_BASE + 5) -#define CAM_FD_DEVICE_TYPE (CAM_DEVICE_TYPE_BASE + 6) -#define CAM_CPAS_DEVICE_TYPE (CAM_DEVICE_TYPE_BASE + 7) -#define CAM_CSIPHY_DEVICE_TYPE (CAM_DEVICE_TYPE_BASE + 8) -#define CAM_ACTUATOR_DEVICE_TYPE (CAM_DEVICE_TYPE_BASE + 9) -#define CAM_CCI_DEVICE_TYPE (CAM_DEVICE_TYPE_BASE + 10) -#define CAM_FLASH_DEVICE_TYPE (CAM_DEVICE_TYPE_BASE + 11) -#define CAM_EEPROM_DEVICE_TYPE (CAM_DEVICE_TYPE_BASE + 12) -#define CAM_OIS_DEVICE_TYPE (CAM_DEVICE_TYPE_BASE + 13) - -/* cam_req_mgr hdl info */ -#define CAM_REQ_MGR_HDL_IDX_POS 8 -#define CAM_REQ_MGR_HDL_IDX_MASK ((1 << CAM_REQ_MGR_HDL_IDX_POS) - 1) -#define CAM_REQ_MGR_GET_HDL_IDX(hdl) (hdl & CAM_REQ_MGR_HDL_IDX_MASK) - -/** - * Max handles supported by cam_req_mgr - * It includes both session and device handles - */ -#define CAM_REQ_MGR_MAX_HANDLES 64 -#define MAX_LINKS_PER_SESSION 2 - -/* V4L event type which user space will subscribe to */ -#define V4L_EVENT_CAM_REQ_MGR_EVENT (V4L2_EVENT_PRIVATE_START + 0) - -/* Specific event ids to get notified in user space */ -#define V4L_EVENT_CAM_REQ_MGR_SOF 0 -#define V4L_EVENT_CAM_REQ_MGR_ERROR 1 -#define V4L_EVENT_CAM_REQ_MGR_SOF_BOOT_TS 2 - -/* SOF Event status */ -#define CAM_REQ_MGR_SOF_EVENT_SUCCESS 0 -#define CAM_REQ_MGR_SOF_EVENT_ERROR 1 - -/* Link control operations */ -#define CAM_REQ_MGR_LINK_ACTIVATE 0 -#define CAM_REQ_MGR_LINK_DEACTIVATE 1 - -/** - * Request Manager : flush_type - * @CAM_REQ_MGR_FLUSH_TYPE_ALL: Req mgr will remove all the pending - * requests from input/processing queue. - * @CAM_REQ_MGR_FLUSH_TYPE_CANCEL_REQ: Req mgr will remove only particular - * request id from input/processing queue. - * @CAM_REQ_MGR_FLUSH_TYPE_MAX: Max number of the flush type - * @opcode: CAM_REQ_MGR_FLUSH_REQ - */ -#define CAM_REQ_MGR_FLUSH_TYPE_ALL 0 -#define CAM_REQ_MGR_FLUSH_TYPE_CANCEL_REQ 1 -#define CAM_REQ_MGR_FLUSH_TYPE_MAX 2 - -/** - * Request Manager : Sync Mode type - * @CAM_REQ_MGR_SYNC_MODE_NO_SYNC: Req mgr will apply non-sync mode for this - * request. - * @CAM_REQ_MGR_SYNC_MODE_SYNC: Req mgr will apply sync mode for this request. - */ -#define CAM_REQ_MGR_SYNC_MODE_NO_SYNC 0 -#define CAM_REQ_MGR_SYNC_MODE_SYNC 1 - -/** - * struct cam_req_mgr_event_data - * @session_hdl: session handle - * @link_hdl: link handle - * @frame_id: frame id - * @reserved: reserved for 64 bit aligngment - * @req_id: request id - * @tv_sec: timestamp in seconds - * @tv_usec: timestamp in micro seconds - */ -struct cam_req_mgr_event_data { - int32_t session_hdl; - int32_t link_hdl; - int32_t frame_id; - int32_t reserved; - int64_t req_id; - uint64_t tv_sec; - uint64_t tv_usec; -}; - -/** - * struct cam_req_mgr_session_info - * @session_hdl: In/Output param - session_handle - * @opcode1: CAM_REQ_MGR_CREATE_SESSION - * @opcode2: CAM_REQ_MGR_DESTROY_SESSION - */ -struct cam_req_mgr_session_info { - int32_t session_hdl; - int32_t reserved; -}; - -/** - * struct cam_req_mgr_link_info - * @session_hdl: Input param - Identifier for CSL session - * @num_devices: Input Param - Num of devices to be linked - * @dev_hdls: Input param - List of device handles to be linked - * @link_hdl: Output Param -Identifier for link - * @opcode: CAM_REQ_MGR_LINK - */ -struct cam_req_mgr_link_info { - int32_t session_hdl; - uint32_t num_devices; - int32_t dev_hdls[CAM_REQ_MGR_MAX_HANDLES]; - int32_t link_hdl; -}; - -/** - * struct cam_req_mgr_unlink_info - * @session_hdl: input param - session handle - * @link_hdl: input param - link handle - * @opcode: CAM_REQ_MGR_UNLINK - */ -struct cam_req_mgr_unlink_info { - int32_t session_hdl; - int32_t link_hdl; -}; - -/** - * struct cam_req_mgr_flush_info - * @brief: User can tell drivers to flush a particular request id or - * flush all requests from its pending processing queue. Flush is a - * blocking call and driver shall ensure all requests are flushed - * before returning. - * @session_hdl: Input param - Identifier for CSL session - * @link_hdl: Input Param -Identifier for link - * @flush_type: User can cancel a particular req id or can flush - * all requests in queue - * @reserved: reserved for 64 bit aligngment - * @req_id: field is valid only if flush type is cancel request - * for flush all this field value is not considered. - * @opcode: CAM_REQ_MGR_FLUSH_REQ - */ -struct cam_req_mgr_flush_info { - int32_t session_hdl; - int32_t link_hdl; - uint32_t flush_type; - uint32_t reserved; - int64_t req_id; -}; - -/** struct cam_req_mgr_sched_info - * @session_hdl: Input param - Identifier for CSL session - * @link_hdl: Input Param -Identifier for link - * inluding itself. - * @bubble_enable: Input Param - Cam req mgr will do bubble recovery if this - * flag is set. - * @sync_mode: Type of Sync mode for this request - * @req_id: Input Param - Request Id from which all requests will be flushed - */ -struct cam_req_mgr_sched_request { - int32_t session_hdl; - int32_t link_hdl; - int32_t bubble_enable; - int32_t sync_mode; - int64_t req_id; -}; - -/** - * struct cam_req_mgr_sync_mode - * @session_hdl: Input param - Identifier for CSL session - * @sync_mode: Input Param - Type of sync mode - * @num_links: Input Param - Num of links in sync mode (Valid only - * when sync_mode is one of SYNC enabled modes) - * @link_hdls: Input Param - Array of link handles to be in sync mode - * (Valid only when sync_mode is one of SYNC - * enabled modes) - * @master_link_hdl: Input Param - To dictate which link's SOF drives system - * (Valid only when sync_mode is one of SYNC - * enabled modes) - * - * @opcode: CAM_REQ_MGR_SYNC_MODE - */ -struct cam_req_mgr_sync_mode { - int32_t session_hdl; - int32_t sync_mode; - int32_t num_links; - int32_t link_hdls[MAX_LINKS_PER_SESSION]; - int32_t master_link_hdl; - int32_t reserved; -}; - -/** - * struct cam_req_mgr_link_control - * @ops: Link operations: activate/deactive - * @session_hdl: Input param - Identifier for CSL session - * @num_links: Input Param - Num of links - * @reserved: reserved field - * @link_hdls: Input Param - Links to be activated/deactivated - * - * @opcode: CAM_REQ_MGR_LINK_CONTROL - */ -struct cam_req_mgr_link_control { - int32_t ops; - int32_t session_hdl; - int32_t num_links; - int32_t reserved; - int32_t link_hdls[MAX_LINKS_PER_SESSION]; -}; - -/** - * cam_req_mgr specific opcode ids - */ -#define CAM_REQ_MGR_CREATE_DEV_NODES (CAM_COMMON_OPCODE_MAX + 1) -#define CAM_REQ_MGR_CREATE_SESSION (CAM_COMMON_OPCODE_MAX + 2) -#define CAM_REQ_MGR_DESTROY_SESSION (CAM_COMMON_OPCODE_MAX + 3) -#define CAM_REQ_MGR_LINK (CAM_COMMON_OPCODE_MAX + 4) -#define CAM_REQ_MGR_UNLINK (CAM_COMMON_OPCODE_MAX + 5) -#define CAM_REQ_MGR_SCHED_REQ (CAM_COMMON_OPCODE_MAX + 6) -#define CAM_REQ_MGR_FLUSH_REQ (CAM_COMMON_OPCODE_MAX + 7) -#define CAM_REQ_MGR_SYNC_MODE (CAM_COMMON_OPCODE_MAX + 8) -#define CAM_REQ_MGR_ALLOC_BUF (CAM_COMMON_OPCODE_MAX + 9) -#define CAM_REQ_MGR_MAP_BUF (CAM_COMMON_OPCODE_MAX + 10) -#define CAM_REQ_MGR_RELEASE_BUF (CAM_COMMON_OPCODE_MAX + 11) -#define CAM_REQ_MGR_CACHE_OPS (CAM_COMMON_OPCODE_MAX + 12) -#define CAM_REQ_MGR_LINK_CONTROL (CAM_COMMON_OPCODE_MAX + 13) -/* end of cam_req_mgr opcodes */ - -#define CAM_MEM_FLAG_HW_READ_WRITE (1<<0) -#define CAM_MEM_FLAG_HW_READ_ONLY (1<<1) -#define CAM_MEM_FLAG_HW_WRITE_ONLY (1<<2) -#define CAM_MEM_FLAG_KMD_ACCESS (1<<3) -#define CAM_MEM_FLAG_UMD_ACCESS (1<<4) -#define CAM_MEM_FLAG_PROTECTED_MODE (1<<5) -#define CAM_MEM_FLAG_CMD_BUF_TYPE (1<<6) -#define CAM_MEM_FLAG_PIXEL_BUF_TYPE (1<<7) -#define CAM_MEM_FLAG_STATS_BUF_TYPE (1<<8) -#define CAM_MEM_FLAG_PACKET_BUF_TYPE (1<<9) -#define CAM_MEM_FLAG_CACHE (1<<10) -#define CAM_MEM_FLAG_HW_SHARED_ACCESS (1<<11) - -#define CAM_MEM_MMU_MAX_HANDLE 16 - -/* Maximum allowed buffers in existence */ -#define CAM_MEM_BUFQ_MAX 1024 - -#define CAM_MEM_MGR_SECURE_BIT_POS 15 -#define CAM_MEM_MGR_HDL_IDX_SIZE 15 -#define CAM_MEM_MGR_HDL_FD_SIZE 16 -#define CAM_MEM_MGR_HDL_IDX_END_POS 16 -#define CAM_MEM_MGR_HDL_FD_END_POS 32 - -#define CAM_MEM_MGR_HDL_IDX_MASK ((1 << CAM_MEM_MGR_HDL_IDX_SIZE) - 1) - -#define GET_MEM_HANDLE(idx, fd) \ - ((idx & CAM_MEM_MGR_HDL_IDX_MASK) | \ - (fd << (CAM_MEM_MGR_HDL_FD_END_POS - CAM_MEM_MGR_HDL_FD_SIZE))) \ - -#define GET_FD_FROM_HANDLE(hdl) \ - (hdl >> (CAM_MEM_MGR_HDL_FD_END_POS - CAM_MEM_MGR_HDL_FD_SIZE)) \ - -#define CAM_MEM_MGR_GET_HDL_IDX(hdl) (hdl & CAM_MEM_MGR_HDL_IDX_MASK) - -#define CAM_MEM_MGR_SET_SECURE_HDL(hdl, flag) \ - ((flag) ? (hdl |= (1 << CAM_MEM_MGR_SECURE_BIT_POS)) : \ - ((hdl) &= ~(1 << CAM_MEM_MGR_SECURE_BIT_POS))) - -#define CAM_MEM_MGR_IS_SECURE_HDL(hdl) \ - (((hdl) & \ - (1<> CAM_MEM_MGR_SECURE_BIT_POS) - -/** - * memory allocation type - */ -#define CAM_MEM_DMA_NONE 0 -#define CAM_MEM_DMA_BIDIRECTIONAL 1 -#define CAM_MEM_DMA_TO_DEVICE 2 -#define CAM_MEM_DMA_FROM_DEVICE 3 - - -/** - * memory cache operation - */ -#define CAM_MEM_CLEAN_CACHE 1 -#define CAM_MEM_INV_CACHE 2 -#define CAM_MEM_CLEAN_INV_CACHE 3 - - -/** - * struct cam_mem_alloc_out_params - * @buf_handle: buffer handle - * @fd: output buffer file descriptor - * @vaddr: virtual address pointer - */ -struct cam_mem_alloc_out_params { - uint32_t buf_handle; - int32_t fd; - uint64_t vaddr; -}; - -/** - * struct cam_mem_map_out_params - * @buf_handle: buffer handle - * @reserved: reserved for future - * @vaddr: virtual address pointer - */ -struct cam_mem_map_out_params { - uint32_t buf_handle; - uint32_t reserved; - uint64_t vaddr; -}; - -/** - * struct cam_mem_mgr_alloc_cmd - * @len: size of buffer to allocate - * @align: alignment of the buffer - * @mmu_hdls: array of mmu handles - * @num_hdl: number of handles - * @flags: flags of the buffer - * @out: out params - */ -/* CAM_REQ_MGR_ALLOC_BUF */ -struct cam_mem_mgr_alloc_cmd { - uint64_t len; - uint64_t align; - int32_t mmu_hdls[CAM_MEM_MMU_MAX_HANDLE]; - uint32_t num_hdl; - uint32_t flags; - struct cam_mem_alloc_out_params out; -}; - -/** - * struct cam_mem_mgr_map_cmd - * @mmu_hdls: array of mmu handles - * @num_hdl: number of handles - * @flags: flags of the buffer - * @fd: output buffer file descriptor - * @reserved: reserved field - * @out: out params - */ - -/* CAM_REQ_MGR_MAP_BUF */ -struct cam_mem_mgr_map_cmd { - int32_t mmu_hdls[CAM_MEM_MMU_MAX_HANDLE]; - uint32_t num_hdl; - uint32_t flags; - int32_t fd; - uint32_t reserved; - struct cam_mem_map_out_params out; -}; - -/** - * struct cam_mem_mgr_map_cmd - * @buf_handle: buffer handle - * @reserved: reserved field - */ -/* CAM_REQ_MGR_RELEASE_BUF */ -struct cam_mem_mgr_release_cmd { - int32_t buf_handle; - uint32_t reserved; -}; - -/** - * struct cam_mem_mgr_map_cmd - * @buf_handle: buffer handle - * @ops: cache operations - */ -/* CAM_REQ_MGR_CACHE_OPS */ -struct cam_mem_cache_ops_cmd { - int32_t buf_handle; - uint32_t mem_cache_ops; -}; - -/** - * Request Manager : error message type - * @CAM_REQ_MGR_ERROR_TYPE_DEVICE: Device error message, fatal to session - * @CAM_REQ_MGR_ERROR_TYPE_REQUEST: Error on a single request, not fatal - * @CAM_REQ_MGR_ERROR_TYPE_BUFFER: Buffer was not filled, not fatal - */ -#define CAM_REQ_MGR_ERROR_TYPE_DEVICE 0 -#define CAM_REQ_MGR_ERROR_TYPE_REQUEST 1 -#define CAM_REQ_MGR_ERROR_TYPE_BUFFER 2 - -/** - * struct cam_req_mgr_error_msg - * @error_type: type of error - * @request_id: request id of frame - * @device_hdl: device handle - * @linke_hdl: link_hdl - * @resource_size: size of the resource - */ -struct cam_req_mgr_error_msg { - uint32_t error_type; - uint32_t request_id; - int32_t device_hdl; - int32_t link_hdl; - uint64_t resource_size; -}; - -/** - * struct cam_req_mgr_frame_msg - * @request_id: request id of the frame - * @frame_id: frame id of the frame - * @timestamp: timestamp of the frame - * @link_hdl: link handle associated with this message - * @sof_status: sof status success or fail - */ -struct cam_req_mgr_frame_msg { - uint64_t request_id; - uint64_t frame_id; - uint64_t timestamp; - int32_t link_hdl; - uint32_t sof_status; -}; - -/** - * struct cam_req_mgr_message - * @session_hdl: session to which the frame belongs to - * @reserved: reserved field - * @u: union which can either be error or frame message - */ -struct cam_req_mgr_message { - int32_t session_hdl; - int32_t reserved; - union { - struct cam_req_mgr_error_msg err_msg; - struct cam_req_mgr_frame_msg frame_msg; - } u; -}; -#endif /* __UAPI_LINUX_CAM_REQ_MGR_H */ diff --git a/third_party/linux/include/media/cam_sensor.h b/third_party/linux/include/media/cam_sensor.h deleted file mode 100644 index f5af6047f5..0000000000 --- a/third_party/linux/include/media/cam_sensor.h +++ /dev/null @@ -1,477 +0,0 @@ -#ifndef __UAPI_CAM_SENSOR_H__ -#define __UAPI_CAM_SENSOR_H__ - -#include -#include -#include - -#define CAM_SENSOR_PROBE_CMD (CAM_COMMON_OPCODE_MAX + 1) -#define CAM_FLASH_MAX_LED_TRIGGERS 3 -#define MAX_OIS_NAME_SIZE 32 -#define CAM_CSIPHY_SECURE_MODE_ENABLED 1 -/** - * struct cam_sensor_query_cap - capabilities info for sensor - * - * @slot_info : Indicates about the slotId or cell Index - * @secure_camera : Camera is in secure/Non-secure mode - * @pos_pitch : Sensor position pitch - * @pos_roll : Sensor position roll - * @pos_yaw : Sensor position yaw - * @actuator_slot_id : Actuator slot id which connected to sensor - * @eeprom_slot_id : EEPROM slot id which connected to sensor - * @ois_slot_id : OIS slot id which connected to sensor - * @flash_slot_id : Flash slot id which connected to sensor - * @csiphy_slot_id : CSIphy slot id which connected to sensor - * - */ -struct cam_sensor_query_cap { - uint32_t slot_info; - uint32_t secure_camera; - uint32_t pos_pitch; - uint32_t pos_roll; - uint32_t pos_yaw; - uint32_t actuator_slot_id; - uint32_t eeprom_slot_id; - uint32_t ois_slot_id; - uint32_t flash_slot_id; - uint32_t csiphy_slot_id; -} __attribute__((packed)); - -/** - * struct cam_csiphy_query_cap - capabilities info for csiphy - * - * @slot_info : Indicates about the slotId or cell Index - * @version : CSIphy version - * @clk lane : Of the 5 lanes, informs lane configured - * as clock lane - * @reserved - */ -struct cam_csiphy_query_cap { - uint32_t slot_info; - uint32_t version; - uint32_t clk_lane; - uint32_t reserved; -} __attribute__((packed)); - -/** - * struct cam_actuator_query_cap - capabilities info for actuator - * - * @slot_info : Indicates about the slotId or cell Index - * @reserved - */ -struct cam_actuator_query_cap { - uint32_t slot_info; - uint32_t reserved; -} __attribute__((packed)); - -/** - * struct cam_eeprom_query_cap_t - capabilities info for eeprom - * - * @slot_info : Indicates about the slotId or cell Index - * @eeprom_kernel_probe : Indicates about the kernel or userspace probe - */ -struct cam_eeprom_query_cap_t { - uint32_t slot_info; - uint16_t eeprom_kernel_probe; - uint16_t reserved; -} __attribute__((packed)); - -/** - * struct cam_ois_query_cap_t - capabilities info for ois - * - * @slot_info : Indicates about the slotId or cell Index - */ -struct cam_ois_query_cap_t { - uint32_t slot_info; - uint16_t reserved; -} __attribute__((packed)); - -/** - * struct cam_cmd_i2c_info - Contains slave I2C related info - * - * @slave_addr : Slave address - * @i2c_freq_mode : 4 bits are used for I2c freq mode - * @cmd_type : Explains type of command - */ -struct cam_cmd_i2c_info { - uint16_t slave_addr; - uint8_t i2c_freq_mode; - uint8_t cmd_type; -} __attribute__((packed)); - -/** - * struct cam_ois_opcode - Contains OIS opcode - * - * @prog : OIS FW prog register address - * @coeff : OIS FW coeff register address - * @pheripheral : OIS pheripheral - * @memory : OIS memory - */ -struct cam_ois_opcode { - uint32_t prog; - uint32_t coeff; - uint32_t pheripheral; - uint32_t memory; -} __attribute__((packed)); - -/** - * struct cam_cmd_ois_info - Contains OIS slave info - * - * @slave_addr : OIS i2c slave address - * @i2c_freq_mode : i2c frequency mode - * @cmd_type : Explains type of command - * @ois_fw_flag : indicates if fw is present or not - * @is_ois_calib : indicates the calibration data is available - * @ois_name : OIS name - * @opcode : opcode - */ -struct cam_cmd_ois_info { - uint16_t slave_addr; - uint8_t i2c_freq_mode; - uint8_t cmd_type; - uint8_t ois_fw_flag; - uint8_t is_ois_calib; - char ois_name[MAX_OIS_NAME_SIZE]; - struct cam_ois_opcode opcode; -} __attribute__((packed)); - -/** - * struct cam_cmd_probe - Contains sensor slave info - * - * @data_type : Slave register data type - * @addr_type : Slave register address type - * @op_code : Don't Care - * @cmd_type : Explains type of command - * @reg_addr : Slave register address - * @expected_data : Data expected at slave register address - * @data_mask : Data mask if only few bits are valid - * @camera_id : Indicates the slot to which camera - * needs to be probed - * @reserved - */ -struct cam_cmd_probe { - uint8_t data_type; - uint8_t addr_type; - uint8_t op_code; - uint8_t cmd_type; - uint32_t reg_addr; - uint32_t expected_data; - uint32_t data_mask; - uint16_t camera_id; - uint16_t reserved; -} __attribute__((packed)); - -/** - * struct cam_power_settings - Contains sensor power setting info - * - * @power_seq_type : Type of power sequence - * @reserved - * @config_val_low : Lower 32 bit value configuration value - * @config_val_high : Higher 32 bit value configuration value - * - */ -struct cam_power_settings { - uint16_t power_seq_type; - uint16_t reserved; - uint32_t config_val_low; - uint32_t config_val_high; -} __attribute__((packed)); - -/** - * struct cam_cmd_power - Explains about the power settings - * - * @count : Number of power settings follows - * @reserved - * @cmd_type : Explains type of command - * @power_settings : Contains power setting info - */ -struct cam_cmd_power { - uint16_t count; - uint8_t reserved; - uint8_t cmd_type; - struct cam_power_settings power_settings[1]; -} __attribute__((packed)); - -/** - * struct i2c_rdwr_header - header of READ/WRITE I2C command - * - * @ count : Number of registers / data / reg-data pairs - * @ op_code : Operation code - * @ cmd_type : Command buffer type - * @ data_type : I2C data type - * @ addr_type : I2C address type - * @ reserved - */ -struct i2c_rdwr_header { - uint16_t count; - uint8_t op_code; - uint8_t cmd_type; - uint8_t data_type; - uint8_t addr_type; - uint16_t reserved; -} __attribute__((packed)); - -/** - * struct i2c_random_wr_payload - payload for I2C random write - * - * @ reg_addr : Register address - * @ reg_data : Register data - * - */ -struct i2c_random_wr_payload { - uint32_t reg_addr; - uint32_t reg_data; -} __attribute__((packed)); - -/** - * struct cam_cmd_i2c_random_wr - I2C random write command - * @ header : header of READ/WRITE I2C command - * @ random_wr_payload : payload for I2C random write - */ -struct cam_cmd_i2c_random_wr { - struct i2c_rdwr_header header; - struct i2c_random_wr_payload random_wr_payload[1]; -} __attribute__((packed)); - -/** - * struct cam_cmd_read - I2C read command - * @ reg_data : Register data - * @ reserved - */ -struct cam_cmd_read { - uint32_t reg_data; - uint32_t reserved; -} __attribute__((packed)); - -/** - * struct cam_cmd_i2c_continuous_wr - I2C continuous write command - * @ header : header of READ/WRITE I2C command - * @ reg_addr : Register address - * @ data_read : I2C read command - */ -struct cam_cmd_i2c_continuous_wr { - struct i2c_rdwr_header header; - uint32_t reg_addr; - struct cam_cmd_read data_read[1]; -} __attribute__((packed)); - -/** - * struct cam_cmd_i2c_random_rd - I2C random read command - * @ header : header of READ/WRITE I2C command - * @ data_read : I2C read command - */ -struct cam_cmd_i2c_random_rd { - struct i2c_rdwr_header header; - struct cam_cmd_read data_read[1]; -} __attribute__((packed)); - -/** - * struct cam_cmd_i2c_continuous_rd - I2C continuous continuous read command - * @ header : header of READ/WRITE I2C command - * @ reg_addr : Register address - * - */ -struct cam_cmd_i2c_continuous_rd { - struct i2c_rdwr_header header; - uint32_t reg_addr; -} __attribute__((packed)); - -/** - * struct cam_cmd_conditional_wait - Conditional wait command - * @data_type : Data type - * @addr_type : Address type - * @op_code : Opcode - * @cmd_type : Explains type of command - * @timeout : Timeout for retries - * @reserved - * @reg_addr : Register Address - * @reg_data : Register data - * @data_mask : Data mask if only few bits are valid - * @camera_id : Indicates the slot to which camera - * needs to be probed - * - */ -struct cam_cmd_conditional_wait { - uint8_t data_type; - uint8_t addr_type; - uint8_t op_code; - uint8_t cmd_type; - uint16_t timeout; - uint16_t reserved; - uint32_t reg_addr; - uint32_t reg_data; - uint32_t data_mask; -} __attribute__((packed)); - -/** - * struct cam_cmd_unconditional_wait - Un-conditional wait command - * @delay : Delay - * @op_code : Opcode - * @cmd_type : Explains type of command - */ -struct cam_cmd_unconditional_wait { - int16_t delay; - uint8_t op_code; - uint8_t cmd_type; -} __attribute__((packed)); - -/** - * cam_csiphy_info: Provides cmdbuffer structre - * @lane_mask : Lane mask details - * @lane_assign : Lane sensor will be using - * @csiphy_3phase : Total number of lanes - * @combo_mode : Info regarding combo_mode is enable / disable - * @lane_cnt : Total number of lanes - * @secure_mode : Secure mode flag to enable / disable - * @3phase : Details whether 3Phase / 2Phase operation - * @settle_time : Settling time in ms - * @data_rate : Data rate - * - */ -struct cam_csiphy_info { - uint16_t lane_mask; - uint16_t lane_assign; - uint8_t csiphy_3phase; - uint8_t combo_mode; - uint8_t lane_cnt; - uint8_t secure_mode; - uint64_t settle_time; - uint64_t data_rate; -} __attribute__((packed)); - -/** - * cam_csiphy_acquire_dev_info : Information needed for - * csiphy at the time of acquire - * @combo_mode : Indicates the device mode of operation - * @reserved - * - */ -struct cam_csiphy_acquire_dev_info { - uint32_t combo_mode; - uint32_t reserved; -} __attribute__((packed)); - -/** - * cam_sensor_acquire_dev : Updates sensor acuire cmd - * @device_handle : Updates device handle - * @session_handle : Session handle for acquiring device - * @handle_type : Resource handle type - * @reserved - * @info_handle : Handle to additional info - * needed for sensor sub modules - * - */ -struct cam_sensor_acquire_dev { - uint32_t session_handle; - uint32_t device_handle; - uint32_t handle_type; - uint32_t reserved; - uint64_t info_handle; -} __attribute__((packed)); - -/** - * cam_sensor_streamon_dev : StreamOn command for the sensor - * @session_handle : Session handle for acquiring device - * @device_handle : Updates device handle - * @handle_type : Resource handle type - * @reserved - * @info_handle : Information Needed at the time of streamOn - * - */ -struct cam_sensor_streamon_dev { - uint32_t session_handle; - uint32_t device_handle; - uint32_t handle_type; - uint32_t reserved; - uint64_t info_handle; -} __attribute__((packed)); - -/** - * struct cam_flash_init : Init command for the flash - * @flash_type : flash hw type - * @reserved - * @cmd_type : command buffer type - */ -struct cam_flash_init { - uint8_t flash_type; - uint16_t reserved; - uint8_t cmd_type; -} __attribute__((packed)); - -/** - * struct cam_flash_set_rer : RedEyeReduction command buffer - * - * @count : Number of flash leds - * @opcode : Command buffer opcode - * CAM_FLASH_FIRE_RER - * @cmd_type : command buffer operation type - * @num_iteration : Number of led turn on/off sequence - * @reserved - * @led_on_delay_ms : flash led turn on time in ms - * @led_off_delay_ms : flash led turn off time in ms - * @led_current_ma : flash led current in ma - * - */ -struct cam_flash_set_rer { - uint16_t count; - uint8_t opcode; - uint8_t cmd_type; - uint16_t num_iteration; - uint16_t reserved; - uint32_t led_on_delay_ms; - uint32_t led_off_delay_ms; - uint32_t led_current_ma[CAM_FLASH_MAX_LED_TRIGGERS]; -} __attribute__((packed)); - -/** - * struct cam_flash_set_on_off : led turn on/off command buffer - * - * @count : Number of Flash leds - * @opcode : command buffer opcodes - * CAM_FLASH_FIRE_LOW - * CAM_FLASH_FIRE_HIGH - * CAM_FLASH_OFF - * @cmd_type : command buffer operation type - * @led_current_ma : flash led current in ma - * - */ -struct cam_flash_set_on_off { - uint16_t count; - uint8_t opcode; - uint8_t cmd_type; - uint32_t led_current_ma[CAM_FLASH_MAX_LED_TRIGGERS]; -} __attribute__((packed)); - -/** - * struct cam_flash_query_curr : query current command buffer - * - * @reserved - * @opcode : command buffer opcode - * @cmd_type : command buffer operation type - * @query_current_ma : battery current in ma - * - */ -struct cam_flash_query_curr { - uint16_t reserved; - uint8_t opcode; - uint8_t cmd_type; - uint32_t query_current_ma; -} __attribute__ ((packed)); - -/** - * struct cam_flash_query_cap : capabilities info for flash - * - * @slot_info : Indicates about the slotId or cell Index - * @max_current_flash : max supported current for flash - * @max_duration_flash : max flash turn on duration - * @max_current_torch : max supported current for torch - * - */ -struct cam_flash_query_cap_info { - uint32_t slot_info; - uint32_t max_current_flash[CAM_FLASH_MAX_LED_TRIGGERS]; - uint32_t max_duration_flash[CAM_FLASH_MAX_LED_TRIGGERS]; - uint32_t max_current_torch[CAM_FLASH_MAX_LED_TRIGGERS]; -} __attribute__ ((packed)); - -#endif diff --git a/third_party/linux/include/media/cam_sensor_cmn_header.h b/third_party/linux/include/media/cam_sensor_cmn_header.h deleted file mode 100644 index 24617b39bd..0000000000 --- a/third_party/linux/include/media/cam_sensor_cmn_header.h +++ /dev/null @@ -1,391 +0,0 @@ -/* Copyright (c) 2017-2018, The Linux Foundation. All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2 and - * only version 2 as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - */ - -#ifndef _CAM_SENSOR_CMN_HEADER_ -#define _CAM_SENSOR_CMN_HEADER_ - -#include -#include -#include - -#define MAX_REGULATOR 5 -#define MAX_POWER_CONFIG 12 - -#define MAX_PER_FRAME_ARRAY 32 -#define BATCH_SIZE_MAX 16 - -#define CAM_SENSOR_NAME "cam-sensor" -#define CAM_ACTUATOR_NAME "cam-actuator" -#define CAM_CSIPHY_NAME "cam-csiphy" -#define CAM_FLASH_NAME "cam-flash" -#define CAM_EEPROM_NAME "cam-eeprom" -#define CAM_OIS_NAME "cam-ois" - -#define MAX_SYSTEM_PIPELINE_DELAY 2 - -#define CAM_PKT_NOP_OPCODE 127 - -enum camera_sensor_cmd_type { - CAMERA_SENSOR_CMD_TYPE_INVALID, - CAMERA_SENSOR_CMD_TYPE_PROBE, - CAMERA_SENSOR_CMD_TYPE_PWR_UP, - CAMERA_SENSOR_CMD_TYPE_PWR_DOWN, - CAMERA_SENSOR_CMD_TYPE_I2C_INFO, - CAMERA_SENSOR_CMD_TYPE_I2C_RNDM_WR, - CAMERA_SENSOR_CMD_TYPE_I2C_RNDM_RD, - CAMERA_SENSOR_CMD_TYPE_I2C_CONT_WR, - CAMERA_SENSOR_CMD_TYPE_I2C_CONT_RD, - CAMERA_SENSOR_CMD_TYPE_WAIT, - CAMERA_SENSOR_FLASH_CMD_TYPE_INIT_INFO, - CAMERA_SENSOR_FLASH_CMD_TYPE_FIRE, - CAMERA_SENSOR_FLASH_CMD_TYPE_RER, - CAMERA_SENSOR_FLASH_CMD_TYPE_QUERYCURR, - CAMERA_SENSOR_FLASH_CMD_TYPE_WIDGET, - CAMERA_SENSOR_CMD_TYPE_RD_DATA, - CAMERA_SENSOR_FLASH_CMD_TYPE_INIT_FIRE, - CAMERA_SENSOR_CMD_TYPE_MAX, -}; - -enum camera_sensor_i2c_op_code { - CAMERA_SENSOR_I2C_OP_INVALID, - CAMERA_SENSOR_I2C_OP_RNDM_WR, - CAMERA_SENSOR_I2C_OP_RNDM_WR_VERF, - CAMERA_SENSOR_I2C_OP_CONT_WR_BRST, - CAMERA_SENSOR_I2C_OP_CONT_WR_BRST_VERF, - CAMERA_SENSOR_I2C_OP_CONT_WR_SEQN, - CAMERA_SENSOR_I2C_OP_CONT_WR_SEQN_VERF, - CAMERA_SENSOR_I2C_OP_MAX, -}; - -enum camera_sensor_wait_op_code { - CAMERA_SENSOR_WAIT_OP_INVALID, - CAMERA_SENSOR_WAIT_OP_COND, - CAMERA_SENSOR_WAIT_OP_HW_UCND, - CAMERA_SENSOR_WAIT_OP_SW_UCND, - CAMERA_SENSOR_WAIT_OP_MAX, -}; - -enum camera_flash_opcode { - CAMERA_SENSOR_FLASH_OP_INVALID, - CAMERA_SENSOR_FLASH_OP_OFF, - CAMERA_SENSOR_FLASH_OP_FIRELOW, - CAMERA_SENSOR_FLASH_OP_FIREHIGH, - CAMERA_SENSOR_FLASH_OP_MAX, -}; - -enum camera_sensor_i2c_type { - CAMERA_SENSOR_I2C_TYPE_INVALID, - CAMERA_SENSOR_I2C_TYPE_BYTE, - CAMERA_SENSOR_I2C_TYPE_WORD, - CAMERA_SENSOR_I2C_TYPE_3B, - CAMERA_SENSOR_I2C_TYPE_DWORD, - CAMERA_SENSOR_I2C_TYPE_MAX, -}; - -enum i2c_freq_mode { - I2C_STANDARD_MODE, - I2C_FAST_MODE, - I2C_CUSTOM_MODE, - I2C_FAST_PLUS_MODE, - I2C_MAX_MODES, -}; - -enum position_roll { - ROLL_0 = 0, - ROLL_90 = 90, - ROLL_180 = 180, - ROLL_270 = 270, - ROLL_INVALID = 360, -}; - -enum position_yaw { - FRONT_CAMERA_YAW = 0, - REAR_CAMERA_YAW = 180, - INVALID_YAW = 360, -}; - -enum position_pitch { - LEVEL_PITCH = 0, - INVALID_PITCH = 360, -}; - -enum sensor_sub_module { - SUB_MODULE_SENSOR, - SUB_MODULE_ACTUATOR, - SUB_MODULE_EEPROM, - SUB_MODULE_LED_FLASH, - SUB_MODULE_CSID, - SUB_MODULE_CSIPHY, - SUB_MODULE_OIS, - SUB_MODULE_EXT, - SUB_MODULE_MAX, -}; - -enum msm_camera_power_seq_type { - SENSOR_MCLK, - SENSOR_VANA, - SENSOR_VDIG, - SENSOR_VIO, - SENSOR_VAF, - SENSOR_VAF_PWDM, - SENSOR_CUSTOM_REG1, - SENSOR_CUSTOM_REG2, - SENSOR_RESET, - SENSOR_STANDBY, - SENSOR_CUSTOM_GPIO1, - SENSOR_CUSTOM_GPIO2, - SENSOR_SEQ_TYPE_MAX, -}; - -enum cam_sensor_packet_opcodes { - CAM_SENSOR_PACKET_OPCODE_SENSOR_STREAMON, - CAM_SENSOR_PACKET_OPCODE_SENSOR_UPDATE, - CAM_SENSOR_PACKET_OPCODE_SENSOR_INITIAL_CONFIG, - CAM_SENSOR_PACKET_OPCODE_SENSOR_PROBE, - CAM_SENSOR_PACKET_OPCODE_SENSOR_CONFIG, - CAM_SENSOR_PACKET_OPCODE_SENSOR_STREAMOFF, - CAM_SENSOR_PACKET_OPCODE_SENSOR_NOP = 127 -}; - -enum cam_actuator_packet_opcodes { - CAM_ACTUATOR_PACKET_OPCODE_INIT, - CAM_ACTUATOR_PACKET_AUTO_MOVE_LENS, - CAM_ACTUATOR_PACKET_MANUAL_MOVE_LENS -}; - -enum cam_eeprom_packet_opcodes { - CAM_EEPROM_PACKET_OPCODE_INIT -}; - -enum cam_ois_packet_opcodes { - CAM_OIS_PACKET_OPCODE_INIT, - CAM_OIS_PACKET_OPCODE_OIS_CONTROL -}; - -enum msm_bus_perf_setting { - S_INIT, - S_PREVIEW, - S_VIDEO, - S_CAPTURE, - S_ZSL, - S_STEREO_VIDEO, - S_STEREO_CAPTURE, - S_DEFAULT, - S_LIVESHOT, - S_DUAL, - S_EXIT -}; - -enum msm_camera_device_type_t { - MSM_CAMERA_I2C_DEVICE, - MSM_CAMERA_PLATFORM_DEVICE, - MSM_CAMERA_SPI_DEVICE, -}; - -enum cam_flash_device_type { - CAMERA_FLASH_DEVICE_TYPE_PMIC = 0, - CAMERA_FLASH_DEVICE_TYPE_I2C, - CAMERA_FLASH_DEVICE_TYPE_GPIO, -}; - -enum cci_i2c_master_t { - MASTER_0, - MASTER_1, - MASTER_MAX, -}; - -enum camera_vreg_type { - VREG_TYPE_DEFAULT, - VREG_TYPE_CUSTOM, -}; - -enum cam_sensor_i2c_cmd_type { - CAM_SENSOR_I2C_WRITE_RANDOM, - CAM_SENSOR_I2C_WRITE_BURST, - CAM_SENSOR_I2C_WRITE_SEQ, - CAM_SENSOR_I2C_READ, - CAM_SENSOR_I2C_POLL -}; - -struct common_header { - uint16_t first_word; - uint8_t third_byte; - uint8_t cmd_type; -}; - -struct camera_vreg_t { - const char *reg_name; - int min_voltage; - int max_voltage; - int op_mode; - uint32_t delay; - const char *custom_vreg_name; - enum camera_vreg_type type; -}; - -struct msm_camera_gpio_num_info { - uint16_t gpio_num[SENSOR_SEQ_TYPE_MAX]; - uint8_t valid[SENSOR_SEQ_TYPE_MAX]; -}; - -struct msm_cam_clk_info { - const char *clk_name; - long clk_rate; - uint32_t delay; -}; - -struct msm_pinctrl_info { - struct pinctrl *pinctrl; - struct pinctrl_state *gpio_state_active; - struct pinctrl_state *gpio_state_suspend; - bool use_pinctrl; -}; - -struct cam_sensor_i2c_reg_array { - uint32_t reg_addr; - uint32_t reg_data; - uint32_t delay; - uint32_t data_mask; -}; - -struct cam_sensor_i2c_reg_setting { - struct cam_sensor_i2c_reg_array *reg_setting; - unsigned short size; - enum camera_sensor_i2c_type addr_type; - enum camera_sensor_i2c_type data_type; - unsigned short delay; -}; - -/*struct i2c_settings_list { - struct cam_sensor_i2c_reg_setting i2c_settings; - enum cam_sensor_i2c_cmd_type op_code; - struct list_head list; -}; - -struct i2c_settings_array { - struct list_head list_head; - int32_t is_settings_valid; - int64_t request_id; -}; - -struct i2c_data_settings { - struct i2c_settings_array init_settings; - struct i2c_settings_array config_settings; - struct i2c_settings_array streamon_settings; - struct i2c_settings_array streamoff_settings; - struct i2c_settings_array *per_frame; -};*/ - -struct cam_sensor_power_ctrl_t { - struct device *dev; - struct cam_sensor_power_setting *power_setting; - uint16_t power_setting_size; - struct cam_sensor_power_setting *power_down_setting; - uint16_t power_down_setting_size; - struct msm_camera_gpio_num_info *gpio_num_info; - struct msm_pinctrl_info pinctrl_info; - uint8_t cam_pinctrl_status; -}; - -struct cam_camera_slave_info { - uint16_t sensor_slave_addr; - uint16_t sensor_id_reg_addr; - uint16_t sensor_id; - uint16_t sensor_id_mask; -}; - -struct msm_sensor_init_params { - int modes_supported; - unsigned int sensor_mount_angle; -}; - -enum msm_sensor_camera_id_t { - CAMERA_0, - CAMERA_1, - CAMERA_2, - CAMERA_3, - CAMERA_4, - CAMERA_5, - CAMERA_6, - MAX_CAMERAS, -}; - -struct msm_sensor_id_info_t { - unsigned short sensor_id_reg_addr; - unsigned short sensor_id; - unsigned short sensor_id_mask; -}; - -enum msm_sensor_output_format_t { - MSM_SENSOR_BAYER, - MSM_SENSOR_YCBCR, - MSM_SENSOR_META, -}; - -struct cam_sensor_power_setting { - enum msm_camera_power_seq_type seq_type; - unsigned short seq_val; - long config_val; - unsigned short delay; - void *data[10]; -}; - -struct cam_sensor_board_info { - struct cam_camera_slave_info slave_info; - int32_t sensor_mount_angle; - int32_t secure_mode; - int modes_supported; - int32_t pos_roll; - int32_t pos_yaw; - int32_t pos_pitch; - int32_t subdev_id[SUB_MODULE_MAX]; - int32_t subdev_intf[SUB_MODULE_MAX]; - const char *misc_regulator; - struct cam_sensor_power_ctrl_t power_info; -}; - -enum msm_camera_vreg_name_t { - CAM_VDIG, - CAM_VIO, - CAM_VANA, - CAM_VAF, - CAM_V_CUSTOM1, - CAM_V_CUSTOM2, - CAM_VREG_MAX, -}; - -struct msm_camera_gpio_conf { - void *cam_gpiomux_conf_tbl; - uint8_t cam_gpiomux_conf_tbl_size; - struct gpio *cam_gpio_common_tbl; - uint8_t cam_gpio_common_tbl_size; - struct gpio *cam_gpio_req_tbl; - uint8_t cam_gpio_req_tbl_size; - uint32_t gpio_no_mux; - uint32_t *camera_off_table; - uint8_t camera_off_table_size; - uint32_t *camera_on_table; - uint8_t camera_on_table_size; - struct msm_camera_gpio_num_info *gpio_num_info; -}; - -/*for tof camera Begin*/ -enum EEPROM_DATA_OP_T{ - EEPROM_DEFAULT_DATA = 0, - EEPROM_INIT_DATA, - EEPROM_CONFIG_DATA, - EEPROM_STREAMON_DATA, - EEPROM_STREAMOFF_DATA, - EEPROM_OTHER_DATA, -}; -/*for tof camera End*/ -#endif /* _CAM_SENSOR_CMN_HEADER_ */ diff --git a/third_party/linux/include/media/cam_sync.h b/third_party/linux/include/media/cam_sync.h deleted file mode 100644 index 4a8781fc82..0000000000 --- a/third_party/linux/include/media/cam_sync.h +++ /dev/null @@ -1,134 +0,0 @@ -#ifndef __UAPI_CAM_SYNC_H__ -#define __UAPI_CAM_SYNC_H__ - -#include -#include -#include -#include - -#define CAM_SYNC_DEVICE_NAME "cam_sync_device" - -/* V4L event which user space will subscribe to */ -#define CAM_SYNC_V4L_EVENT (V4L2_EVENT_PRIVATE_START + 0) - -/* Specific event ids to get notified in user space */ -#define CAM_SYNC_V4L_EVENT_ID_CB_TRIG 0 - -/* Size of opaque payload sent to kernel for safekeeping until signal time */ -#define CAM_SYNC_USER_PAYLOAD_SIZE 2 - -/* Device type for sync device needed for device discovery */ -#define CAM_SYNC_DEVICE_TYPE (MEDIA_ENT_F_OLD_BASE) - -#define CAM_SYNC_GET_PAYLOAD_PTR(ev, type) \ - (type *)((char *)ev.u.data + sizeof(struct cam_sync_ev_header)) - -#define CAM_SYNC_GET_HEADER_PTR(ev) \ - ((struct cam_sync_ev_header *)ev.u.data) - -#define CAM_SYNC_STATE_INVALID 0 -#define CAM_SYNC_STATE_ACTIVE 1 -#define CAM_SYNC_STATE_SIGNALED_SUCCESS 2 -#define CAM_SYNC_STATE_SIGNALED_ERROR 3 - -/** - * struct cam_sync_ev_header - Event header for sync event notification - * - * @sync_obj: Sync object - * @status: Status of the object - */ -struct cam_sync_ev_header { - int32_t sync_obj; - int32_t status; -}; - -/** - * struct cam_sync_info - Sync object creation information - * - * @name: Optional string representation of the sync object - * @sync_obj: Sync object returned after creation in kernel - */ -struct cam_sync_info { - char name[64]; - int32_t sync_obj; -}; - -/** - * struct cam_sync_signal - Sync object signaling struct - * - * @sync_obj: Sync object to be signaled - * @sync_state: State of the sync object to which it should be signaled - */ -struct cam_sync_signal { - int32_t sync_obj; - uint32_t sync_state; -}; - -/** - * struct cam_sync_merge - Merge information for sync objects - * - * @sync_objs: Pointer to sync objects - * @num_objs: Number of objects in the array - * @merged: Merged sync object - */ -struct cam_sync_merge { - __u64 sync_objs; - uint32_t num_objs; - int32_t merged; -}; - -/** - * struct cam_sync_userpayload_info - Payload info from user space - * - * @sync_obj: Sync object for which payload has to be registered for - * @reserved: Reserved - * @payload: Pointer to user payload - */ -struct cam_sync_userpayload_info { - int32_t sync_obj; - uint32_t reserved; - __u64 payload[CAM_SYNC_USER_PAYLOAD_SIZE]; -}; - -/** - * struct cam_sync_wait - Sync object wait information - * - * @sync_obj: Sync object to wait on - * @reserved: Reserved - * @timeout_ms: Timeout in milliseconds - */ -struct cam_sync_wait { - int32_t sync_obj; - uint32_t reserved; - uint64_t timeout_ms; -}; - -/** - * struct cam_private_ioctl_arg - Sync driver ioctl argument - * - * @id: IOCTL command id - * @size: Size of command payload - * @result: Result of command execution - * @reserved: Reserved - * @ioctl_ptr: Pointer to user data - */ -struct cam_private_ioctl_arg { - __u32 id; - __u32 size; - __u32 result; - __u32 reserved; - __u64 ioctl_ptr; -}; - -#define CAM_PRIVATE_IOCTL_CMD \ - _IOWR('V', BASE_VIDIOC_PRIVATE, struct cam_private_ioctl_arg) - -#define CAM_SYNC_CREATE 0 -#define CAM_SYNC_DESTROY 1 -#define CAM_SYNC_SIGNAL 2 -#define CAM_SYNC_MERGE 3 -#define CAM_SYNC_REGISTER_PAYLOAD 4 -#define CAM_SYNC_DEREGISTER_PAYLOAD 5 -#define CAM_SYNC_WAIT 6 - -#endif /* __UAPI_CAM_SYNC_H__ */ diff --git a/third_party/linux/include/msm_cam_sensor.h b/third_party/linux/include/msm_cam_sensor.h deleted file mode 100644 index c75d1fd527..0000000000 --- a/third_party/linux/include/msm_cam_sensor.h +++ /dev/null @@ -1,829 +0,0 @@ -#ifndef __LINUX_MSM_CAM_SENSOR_H -#define __LINUX_MSM_CAM_SENSOR_H - -#ifdef MSM_CAMERA_BIONIC -#include -#endif - -//#include -#include "msm_camsensor_sdk.h" - -#include -#include -#ifdef CONFIG_COMPAT -#include -#endif - -#define I2C_SEQ_REG_SETTING_MAX 5 - -#define MSM_SENSOR_MCLK_8HZ 8000000 -#define MSM_SENSOR_MCLK_16HZ 16000000 -#define MSM_SENSOR_MCLK_24HZ 24000000 - -#define MAX_SENSOR_NAME 32 -#define MAX_ACTUATOR_AF_TOTAL_STEPS 1024 - -#define MAX_OIS_MOD_NAME_SIZE 32 -#define MAX_OIS_NAME_SIZE 32 -#define MAX_OIS_REG_SETTINGS 800 - -#define MOVE_NEAR 0 -#define MOVE_FAR 1 - -#define MSM_ACTUATOR_MOVE_SIGNED_FAR -1 -#define MSM_ACTUATOR_MOVE_SIGNED_NEAR 1 - -#define MAX_ACTUATOR_REGION 5 - -#define MAX_EEPROM_NAME 32 - -#define MAX_AF_ITERATIONS 3 -#define MAX_NUMBER_OF_STEPS 47 -#define MAX_REGULATOR 5 - -#define MSM_V4L2_PIX_FMT_META v4l2_fourcc('M', 'E', 'T', 'A') /* META */ -#define MSM_V4L2_PIX_FMT_SBGGR14 v4l2_fourcc('B', 'G', '1', '4') - /* 14 BGBG.. GRGR.. */ -#define MSM_V4L2_PIX_FMT_SGBRG14 v4l2_fourcc('G', 'B', '1', '4') - /* 14 GBGB.. RGRG.. */ -#define MSM_V4L2_PIX_FMT_SGRBG14 v4l2_fourcc('B', 'A', '1', '4') - /* 14 GRGR.. BGBG.. */ -#define MSM_V4L2_PIX_FMT_SRGGB14 v4l2_fourcc('R', 'G', '1', '4') - /* 14 RGRG.. GBGB.. */ - -enum flash_type { - LED_FLASH = 1, - STROBE_FLASH, - GPIO_FLASH -}; - -enum msm_sensor_resolution_t { - MSM_SENSOR_RES_FULL, - MSM_SENSOR_RES_QTR, - MSM_SENSOR_RES_2, - MSM_SENSOR_RES_3, - MSM_SENSOR_RES_4, - MSM_SENSOR_RES_5, - MSM_SENSOR_RES_6, - MSM_SENSOR_RES_7, - MSM_SENSOR_INVALID_RES, -}; - -enum msm_camera_stream_type_t { - MSM_CAMERA_STREAM_PREVIEW, - MSM_CAMERA_STREAM_SNAPSHOT, - MSM_CAMERA_STREAM_VIDEO, - MSM_CAMERA_STREAM_INVALID, -}; - -enum sensor_sub_module_t { - SUB_MODULE_SENSOR, - SUB_MODULE_CHROMATIX, - SUB_MODULE_ACTUATOR, - SUB_MODULE_EEPROM, - SUB_MODULE_LED_FLASH, - SUB_MODULE_STROBE_FLASH, - SUB_MODULE_CSID, - SUB_MODULE_CSID_3D, - SUB_MODULE_CSIPHY, - SUB_MODULE_CSIPHY_3D, - SUB_MODULE_OIS, - SUB_MODULE_EXT, - SUB_MODULE_MAX, -}; - -enum { - MSM_CAMERA_EFFECT_MODE_OFF, - MSM_CAMERA_EFFECT_MODE_MONO, - MSM_CAMERA_EFFECT_MODE_NEGATIVE, - MSM_CAMERA_EFFECT_MODE_SOLARIZE, - MSM_CAMERA_EFFECT_MODE_SEPIA, - MSM_CAMERA_EFFECT_MODE_POSTERIZE, - MSM_CAMERA_EFFECT_MODE_WHITEBOARD, - MSM_CAMERA_EFFECT_MODE_BLACKBOARD, - MSM_CAMERA_EFFECT_MODE_AQUA, - MSM_CAMERA_EFFECT_MODE_EMBOSS, - MSM_CAMERA_EFFECT_MODE_SKETCH, - MSM_CAMERA_EFFECT_MODE_NEON, - MSM_CAMERA_EFFECT_MODE_MAX -}; - -enum { - MSM_CAMERA_WB_MODE_AUTO, - MSM_CAMERA_WB_MODE_CUSTOM, - MSM_CAMERA_WB_MODE_INCANDESCENT, - MSM_CAMERA_WB_MODE_FLUORESCENT, - MSM_CAMERA_WB_MODE_WARM_FLUORESCENT, - MSM_CAMERA_WB_MODE_DAYLIGHT, - MSM_CAMERA_WB_MODE_CLOUDY_DAYLIGHT, - MSM_CAMERA_WB_MODE_TWILIGHT, - MSM_CAMERA_WB_MODE_SHADE, - MSM_CAMERA_WB_MODE_OFF, - MSM_CAMERA_WB_MODE_MAX -}; - -enum { - MSM_CAMERA_SCENE_MODE_OFF, - MSM_CAMERA_SCENE_MODE_AUTO, - MSM_CAMERA_SCENE_MODE_LANDSCAPE, - MSM_CAMERA_SCENE_MODE_SNOW, - MSM_CAMERA_SCENE_MODE_BEACH, - MSM_CAMERA_SCENE_MODE_SUNSET, - MSM_CAMERA_SCENE_MODE_NIGHT, - MSM_CAMERA_SCENE_MODE_PORTRAIT, - MSM_CAMERA_SCENE_MODE_BACKLIGHT, - MSM_CAMERA_SCENE_MODE_SPORTS, - MSM_CAMERA_SCENE_MODE_ANTISHAKE, - MSM_CAMERA_SCENE_MODE_FLOWERS, - MSM_CAMERA_SCENE_MODE_CANDLELIGHT, - MSM_CAMERA_SCENE_MODE_FIREWORKS, - MSM_CAMERA_SCENE_MODE_PARTY, - MSM_CAMERA_SCENE_MODE_NIGHT_PORTRAIT, - MSM_CAMERA_SCENE_MODE_THEATRE, - MSM_CAMERA_SCENE_MODE_ACTION, - MSM_CAMERA_SCENE_MODE_AR, - MSM_CAMERA_SCENE_MODE_FACE_PRIORITY, - MSM_CAMERA_SCENE_MODE_BARCODE, - MSM_CAMERA_SCENE_MODE_HDR, - MSM_CAMERA_SCENE_MODE_MAX -}; - -enum csid_cfg_type_t { - CSID_INIT, - CSID_CFG, - CSID_TESTMODE_CFG, - CSID_RELEASE, -}; - -enum csiphy_cfg_type_t { - CSIPHY_INIT, - CSIPHY_CFG, - CSIPHY_RELEASE, -}; - -enum camera_vreg_type { - VREG_TYPE_DEFAULT, - VREG_TYPE_CUSTOM, -}; - -enum sensor_af_t { - SENSOR_AF_FOCUSSED, - SENSOR_AF_NOT_FOCUSSED, -}; - -enum cci_i2c_master_t { - MASTER_0, - MASTER_1, - MASTER_MAX, -}; - -struct msm_camera_i2c_array_write_config { - struct msm_camera_i2c_reg_setting conf_array; - uint16_t slave_addr; -}; - -struct msm_camera_i2c_read_config { - uint16_t slave_addr; - uint16_t reg_addr; - enum msm_camera_i2c_reg_addr_type addr_type; - enum msm_camera_i2c_data_type data_type; - uint16_t data; -}; - -struct msm_camera_csi2_params { - struct msm_camera_csid_params csid_params; - struct msm_camera_csiphy_params csiphy_params; - uint8_t csi_clk_scale_enable; -}; - -struct msm_camera_csi_lane_params { - uint16_t csi_lane_assign; - uint16_t csi_lane_mask; -}; - -struct csi_lane_params_t { - uint16_t csi_lane_assign; - uint8_t csi_lane_mask; - uint8_t csi_if; - int8_t csid_core[2]; - uint8_t csi_phy_sel; -}; - -struct msm_sensor_info_t { - char sensor_name[MAX_SENSOR_NAME]; - uint32_t session_id; - int32_t subdev_id[SUB_MODULE_MAX]; - int32_t subdev_intf[SUB_MODULE_MAX]; - uint8_t is_mount_angle_valid; - uint32_t sensor_mount_angle; - int modes_supported; - enum camb_position_t position; -}; - -struct camera_vreg_t { - const char *reg_name; - int min_voltage; - int max_voltage; - int op_mode; - uint32_t delay; - const char *custom_vreg_name; - enum camera_vreg_type type; -}; - -struct sensorb_cfg_data { - int cfgtype; - union { - struct msm_sensor_info_t sensor_info; - struct msm_sensor_init_params sensor_init_params; - void *setting; - struct msm_sensor_i2c_sync_params sensor_i2c_sync_params; - } cfg; -}; - -struct csid_cfg_data { - enum csid_cfg_type_t cfgtype; - union { - uint32_t csid_version; - struct msm_camera_csid_params *csid_params; - struct msm_camera_csid_testmode_parms *csid_testmode_params; - } cfg; -}; - -struct csiphy_cfg_data { - enum csiphy_cfg_type_t cfgtype; - union { - struct msm_camera_csiphy_params *csiphy_params; - struct msm_camera_csi_lane_params *csi_lane_params; - } cfg; -}; - -enum eeprom_cfg_type_t { - CFG_EEPROM_GET_INFO, - CFG_EEPROM_GET_CAL_DATA, - CFG_EEPROM_READ_CAL_DATA, - CFG_EEPROM_WRITE_DATA, - CFG_EEPROM_GET_MM_INFO, - CFG_EEPROM_INIT, -}; - -struct eeprom_get_t { - uint32_t num_bytes; -}; - -struct eeprom_read_t { - uint8_t *dbuffer; - uint32_t num_bytes; -}; - -struct eeprom_write_t { - uint8_t *dbuffer; - uint32_t num_bytes; -}; - -struct eeprom_get_cmm_t { - uint32_t cmm_support; - uint32_t cmm_compression; - uint32_t cmm_size; -}; - -struct msm_eeprom_info_t { - struct msm_sensor_power_setting_array *power_setting_array; - enum i2c_freq_mode_t i2c_freq_mode; - struct msm_eeprom_memory_map_array *mem_map_array; -}; - -struct msm_eeprom_cfg_data { - enum eeprom_cfg_type_t cfgtype; - uint8_t is_supported; - union { - char eeprom_name[MAX_SENSOR_NAME]; - struct eeprom_get_t get_data; - struct eeprom_read_t read_data; - struct eeprom_write_t write_data; - struct eeprom_get_cmm_t get_cmm_data; - struct msm_eeprom_info_t eeprom_info; - } cfg; -}; - -#ifdef CONFIG_COMPAT -struct msm_sensor_power_setting32 { - enum msm_sensor_power_seq_type_t seq_type; - uint16_t seq_val; - compat_uint_t config_val; - uint16_t delay; - compat_uptr_t data[10]; -}; - -struct msm_sensor_power_setting_array32 { - struct msm_sensor_power_setting32 power_setting_a[MAX_POWER_CONFIG]; - compat_uptr_t power_setting; - uint16_t size; - struct msm_sensor_power_setting32 - power_down_setting_a[MAX_POWER_CONFIG]; - compat_uptr_t power_down_setting; - uint16_t size_down; -}; - -struct msm_camera_sensor_slave_info32 { - char sensor_name[32]; - char eeprom_name[32]; - char actuator_name[32]; - char ois_name[32]; - char flash_name[32]; - enum msm_sensor_camera_id_t camera_id; - uint16_t slave_addr; - enum i2c_freq_mode_t i2c_freq_mode; - enum msm_camera_i2c_reg_addr_type addr_type; - struct msm_sensor_id_info_t sensor_id_info; - struct msm_sensor_power_setting_array32 power_setting_array; - uint8_t is_init_params_valid; - struct msm_sensor_init_params sensor_init_params; - enum msm_sensor_output_format_t output_format; -}; - -struct msm_camera_csid_lut_params32 { - uint8_t num_cid; - struct msm_camera_csid_vc_cfg vc_cfg_a[MAX_CID]; - compat_uptr_t vc_cfg[MAX_CID]; -}; - -struct msm_camera_csid_params32 { - uint8_t lane_cnt; - uint16_t lane_assign; - uint8_t phy_sel; - uint32_t csi_clk; - struct msm_camera_csid_lut_params32 lut_params; - uint8_t csi_3p_sel; -}; - -struct msm_camera_csi2_params32 { - struct msm_camera_csid_params32 csid_params; - struct msm_camera_csiphy_params csiphy_params; - uint8_t csi_clk_scale_enable; -}; - -struct csid_cfg_data32 { - enum csid_cfg_type_t cfgtype; - union { - uint32_t csid_version; - compat_uptr_t csid_params; - compat_uptr_t csid_testmode_params; - } cfg; -}; - -struct eeprom_read_t32 { - compat_uptr_t dbuffer; - uint32_t num_bytes; -}; - -struct eeprom_write_t32 { - compat_uptr_t dbuffer; - uint32_t num_bytes; -}; - -struct msm_eeprom_info_t32 { - compat_uptr_t power_setting_array; - enum i2c_freq_mode_t i2c_freq_mode; - compat_uptr_t mem_map_array; -}; - -struct msm_eeprom_cfg_data32 { - enum eeprom_cfg_type_t cfgtype; - uint8_t is_supported; - union { - char eeprom_name[MAX_SENSOR_NAME]; - struct eeprom_get_t get_data; - struct eeprom_read_t32 read_data; - struct eeprom_write_t32 write_data; - struct msm_eeprom_info_t32 eeprom_info; - } cfg; -}; - -struct msm_camera_i2c_seq_reg_setting32 { - compat_uptr_t reg_setting; - uint16_t size; - enum msm_camera_i2c_reg_addr_type addr_type; - uint16_t delay; -}; -#endif - -enum msm_sensor_cfg_type_t { - CFG_SET_SLAVE_INFO, - CFG_SLAVE_READ_I2C, - CFG_WRITE_I2C_ARRAY, - CFG_SLAVE_WRITE_I2C_ARRAY, - CFG_WRITE_I2C_SEQ_ARRAY, - CFG_POWER_UP, - CFG_POWER_DOWN, - CFG_SET_STOP_STREAM_SETTING, - CFG_GET_SENSOR_INFO, - CFG_GET_SENSOR_INIT_PARAMS, - CFG_SET_INIT_SETTING, - CFG_SET_RESOLUTION, - CFG_SET_STOP_STREAM, - CFG_SET_START_STREAM, - CFG_SET_SATURATION, - CFG_SET_CONTRAST, - CFG_SET_SHARPNESS, - CFG_SET_ISO, - CFG_SET_EXPOSURE_COMPENSATION, - CFG_SET_ANTIBANDING, - CFG_SET_BESTSHOT_MODE, - CFG_SET_EFFECT, - CFG_SET_WHITE_BALANCE, - CFG_SET_AUTOFOCUS, - CFG_CANCEL_AUTOFOCUS, - CFG_SET_STREAM_TYPE, - CFG_SET_I2C_SYNC_PARAM, - CFG_WRITE_I2C_ARRAY_ASYNC, - CFG_WRITE_I2C_ARRAY_SYNC, - CFG_WRITE_I2C_ARRAY_SYNC_BLOCK, -}; - -enum msm_actuator_cfg_type_t { - CFG_GET_ACTUATOR_INFO, - CFG_SET_ACTUATOR_INFO, - CFG_SET_DEFAULT_FOCUS, - CFG_MOVE_FOCUS, - CFG_SET_POSITION, - CFG_ACTUATOR_POWERDOWN, - CFG_ACTUATOR_POWERUP, - CFG_ACTUATOR_INIT, -}; - -enum msm_ois_cfg_type_t { - CFG_OIS_INIT, - CFG_OIS_POWERDOWN, - CFG_OIS_POWERUP, - CFG_OIS_CONTROL, - CFG_OIS_I2C_WRITE_SEQ_TABLE, -}; - -enum msm_ois_i2c_operation { - MSM_OIS_WRITE = 0, - MSM_OIS_POLL, -}; - -struct reg_settings_ois_t { - uint16_t reg_addr; - enum msm_camera_i2c_reg_addr_type addr_type; - uint32_t reg_data; - enum msm_camera_i2c_data_type data_type; - enum msm_ois_i2c_operation i2c_operation; - uint32_t delay; -#define OIS_REG_DATA_SEQ_MAX 128 - unsigned char reg_data_seq[OIS_REG_DATA_SEQ_MAX]; - uint32_t reg_data_seq_size; -}; - -struct msm_ois_params_t { - uint16_t data_size; - uint16_t setting_size; - uint32_t i2c_addr; - enum i2c_freq_mode_t i2c_freq_mode; - enum msm_camera_i2c_reg_addr_type i2c_addr_type; - enum msm_camera_i2c_data_type i2c_data_type; - struct reg_settings_ois_t *settings; -}; - -struct msm_ois_set_info_t { - struct msm_ois_params_t ois_params; -}; - -struct msm_actuator_move_params_t { - int8_t dir; - int8_t sign_dir; - int16_t dest_step_pos; - int32_t num_steps; - uint16_t curr_lens_pos; - struct damping_params_t *ringing_params; -}; - -struct msm_actuator_tuning_params_t { - int16_t initial_code; - uint16_t pwd_step; - uint16_t region_size; - uint32_t total_steps; - struct region_params_t *region_params; -}; - -struct park_lens_data_t { - uint32_t damping_step; - uint32_t damping_delay; - uint32_t hw_params; - uint32_t max_step; -}; - -struct msm_actuator_params_t { - enum actuator_type act_type; - uint8_t reg_tbl_size; - uint16_t data_size; - uint16_t init_setting_size; - uint32_t i2c_addr; - enum i2c_freq_mode_t i2c_freq_mode; - enum msm_actuator_addr_type i2c_addr_type; - enum msm_actuator_data_type i2c_data_type; - struct msm_actuator_reg_params_t *reg_tbl_params; - struct reg_settings_t *init_settings; - struct park_lens_data_t park_lens; -}; - -struct msm_actuator_set_info_t { - struct msm_actuator_params_t actuator_params; - struct msm_actuator_tuning_params_t af_tuning_params; -}; - -struct msm_actuator_get_info_t { - uint32_t focal_length_num; - uint32_t focal_length_den; - uint32_t f_number_num; - uint32_t f_number_den; - uint32_t f_pix_num; - uint32_t f_pix_den; - uint32_t total_f_dist_num; - uint32_t total_f_dist_den; - uint32_t hor_view_angle_num; - uint32_t hor_view_angle_den; - uint32_t ver_view_angle_num; - uint32_t ver_view_angle_den; -}; - -enum af_camera_name { - ACTUATOR_MAIN_CAM_0, - ACTUATOR_MAIN_CAM_1, - ACTUATOR_MAIN_CAM_2, - ACTUATOR_MAIN_CAM_3, - ACTUATOR_MAIN_CAM_4, - ACTUATOR_MAIN_CAM_5, - ACTUATOR_WEB_CAM_0, - ACTUATOR_WEB_CAM_1, - ACTUATOR_WEB_CAM_2, -}; - -struct msm_ois_cfg_data { - int cfgtype; - union { - struct msm_ois_set_info_t set_info; - struct msm_camera_i2c_seq_reg_setting *settings; - } cfg; -}; - -struct msm_actuator_set_position_t { - uint16_t number_of_steps; - uint32_t hw_params; - uint16_t pos[MAX_NUMBER_OF_STEPS]; - uint16_t delay[MAX_NUMBER_OF_STEPS]; -}; - -struct msm_actuator_cfg_data { - int cfgtype; - uint8_t is_af_supported; - union { - struct msm_actuator_move_params_t move; - struct msm_actuator_set_info_t set_info; - struct msm_actuator_get_info_t get_info; - struct msm_actuator_set_position_t setpos; - enum af_camera_name cam_name; - } cfg; -}; - -enum msm_camera_led_config_t { - MSM_CAMERA_LED_OFF, - MSM_CAMERA_LED_LOW, - MSM_CAMERA_LED_HIGH, - MSM_CAMERA_LED_INIT, - MSM_CAMERA_LED_RELEASE, -}; - -struct msm_camera_led_cfg_t { - enum msm_camera_led_config_t cfgtype; - int32_t torch_current[MAX_LED_TRIGGERS]; - int32_t flash_current[MAX_LED_TRIGGERS]; - int32_t flash_duration[MAX_LED_TRIGGERS]; -}; - -struct msm_flash_init_info_t { - enum msm_flash_driver_type flash_driver_type; - uint32_t slave_addr; - enum i2c_freq_mode_t i2c_freq_mode; - struct msm_sensor_power_setting_array *power_setting_array; - struct msm_camera_i2c_reg_setting_array *settings; -}; - -struct msm_flash_cfg_data_t { - enum msm_flash_cfg_type_t cfg_type; - int32_t flash_current[MAX_LED_TRIGGERS]; - int32_t flash_duration[MAX_LED_TRIGGERS]; - union { - struct msm_flash_init_info_t *flash_init_info; - struct msm_camera_i2c_reg_setting_array *settings; - } cfg; -}; - -/* sensor init structures and enums */ -enum msm_sensor_init_cfg_type_t { - CFG_SINIT_PROBE, - CFG_SINIT_PROBE_DONE, - CFG_SINIT_PROBE_WAIT_DONE, -}; - -struct sensor_init_cfg_data { - enum msm_sensor_init_cfg_type_t cfgtype; - struct msm_sensor_info_t probed_info; - char entity_name[MAX_SENSOR_NAME]; - union { - void *setting; - } cfg; -}; - -#define VIDIOC_MSM_SENSOR_CFG \ - _IOWR('V', BASE_VIDIOC_PRIVATE + 1, struct sensorb_cfg_data) - -#define VIDIOC_MSM_SENSOR_RELEASE \ - _IO('V', BASE_VIDIOC_PRIVATE + 2) - -#define VIDIOC_MSM_SENSOR_GET_SUBDEV_ID \ - _IOWR('V', BASE_VIDIOC_PRIVATE + 3, uint32_t) - -#define VIDIOC_MSM_CSIPHY_IO_CFG \ - _IOWR('V', BASE_VIDIOC_PRIVATE + 4, struct csiphy_cfg_data) - -#define VIDIOC_MSM_CSID_IO_CFG \ - _IOWR('V', BASE_VIDIOC_PRIVATE + 5, struct csid_cfg_data) - -#define VIDIOC_MSM_ACTUATOR_CFG \ - _IOWR('V', BASE_VIDIOC_PRIVATE + 6, struct msm_actuator_cfg_data) - -#define VIDIOC_MSM_FLASH_LED_DATA_CFG \ - _IOWR('V', BASE_VIDIOC_PRIVATE + 7, struct msm_camera_led_cfg_t) - -#define VIDIOC_MSM_EEPROM_CFG \ - _IOWR('V', BASE_VIDIOC_PRIVATE + 8, struct msm_eeprom_cfg_data) - -#define VIDIOC_MSM_SENSOR_GET_AF_STATUS \ - _IOWR('V', BASE_VIDIOC_PRIVATE + 9, uint32_t) - -#define VIDIOC_MSM_SENSOR_INIT_CFG \ - _IOWR('V', BASE_VIDIOC_PRIVATE + 10, struct sensor_init_cfg_data) - -#define VIDIOC_MSM_OIS_CFG \ - _IOWR('V', BASE_VIDIOC_PRIVATE + 11, struct msm_ois_cfg_data) - -#define VIDIOC_MSM_FLASH_CFG \ - _IOWR('V', BASE_VIDIOC_PRIVATE + 13, struct msm_flash_cfg_data_t) - -#ifdef CONFIG_COMPAT -struct msm_camera_i2c_reg_setting32 { - compat_uptr_t reg_setting; - uint16_t size; - enum msm_camera_i2c_reg_addr_type addr_type; - enum msm_camera_i2c_data_type data_type; - uint16_t delay; -}; - -struct msm_camera_i2c_array_write_config32 { - struct msm_camera_i2c_reg_setting32 conf_array; - uint16_t slave_addr; -}; - -struct msm_actuator_tuning_params_t32 { - int16_t initial_code; - uint16_t pwd_step; - uint16_t region_size; - uint32_t total_steps; - compat_uptr_t region_params; -}; - -struct msm_actuator_params_t32 { - enum actuator_type act_type; - uint8_t reg_tbl_size; - uint16_t data_size; - uint16_t init_setting_size; - uint32_t i2c_addr; - enum i2c_freq_mode_t i2c_freq_mode; - enum msm_actuator_addr_type i2c_addr_type; - enum msm_actuator_data_type i2c_data_type; - compat_uptr_t reg_tbl_params; - compat_uptr_t init_settings; - struct park_lens_data_t park_lens; -}; - -struct msm_actuator_set_info_t32 { - struct msm_actuator_params_t32 actuator_params; - struct msm_actuator_tuning_params_t32 af_tuning_params; -}; - -struct sensor_init_cfg_data32 { - enum msm_sensor_init_cfg_type_t cfgtype; - struct msm_sensor_info_t probed_info; - char entity_name[MAX_SENSOR_NAME]; - union { - compat_uptr_t setting; - } cfg; -}; - -struct msm_actuator_move_params_t32 { - int8_t dir; - int8_t sign_dir; - int16_t dest_step_pos; - int32_t num_steps; - uint16_t curr_lens_pos; - compat_uptr_t ringing_params; -}; - -struct msm_actuator_cfg_data32 { - int cfgtype; - uint8_t is_af_supported; - union { - struct msm_actuator_move_params_t32 move; - struct msm_actuator_set_info_t32 set_info; - struct msm_actuator_get_info_t get_info; - struct msm_actuator_set_position_t setpos; - enum af_camera_name cam_name; - } cfg; -}; - -struct csiphy_cfg_data32 { - enum csiphy_cfg_type_t cfgtype; - union { - compat_uptr_t csiphy_params; - compat_uptr_t csi_lane_params; - } cfg; -}; - -struct sensorb_cfg_data32 { - int cfgtype; - union { - struct msm_sensor_info_t sensor_info; - struct msm_sensor_init_params sensor_init_params; - compat_uptr_t setting; - struct msm_sensor_i2c_sync_params sensor_i2c_sync_params; - } cfg; -}; - -struct msm_ois_params_t32 { - uint16_t data_size; - uint16_t setting_size; - uint32_t i2c_addr; - enum i2c_freq_mode_t i2c_freq_mode; - enum msm_camera_i2c_reg_addr_type i2c_addr_type; - enum msm_camera_i2c_data_type i2c_data_type; - compat_uptr_t settings; -}; - -struct msm_ois_set_info_t32 { - struct msm_ois_params_t32 ois_params; -}; - -struct msm_ois_cfg_data32 { - int cfgtype; - union { - struct msm_ois_set_info_t32 set_info; - compat_uptr_t settings; - } cfg; -}; - -struct msm_flash_init_info_t32 { - enum msm_flash_driver_type flash_driver_type; - uint32_t slave_addr; - enum i2c_freq_mode_t i2c_freq_mode; - compat_uptr_t power_setting_array; - compat_uptr_t settings; -}; - -struct msm_flash_cfg_data_t32 { - enum msm_flash_cfg_type_t cfg_type; - int32_t flash_current[MAX_LED_TRIGGERS]; - int32_t flash_duration[MAX_LED_TRIGGERS]; - union { - compat_uptr_t flash_init_info; - compat_uptr_t settings; - } cfg; -}; - -#define VIDIOC_MSM_ACTUATOR_CFG32 \ - _IOWR('V', BASE_VIDIOC_PRIVATE + 6, struct msm_actuator_cfg_data32) - -#define VIDIOC_MSM_SENSOR_INIT_CFG32 \ - _IOWR('V', BASE_VIDIOC_PRIVATE + 10, struct sensor_init_cfg_data32) - -#define VIDIOC_MSM_CSIPHY_IO_CFG32 \ - _IOWR('V', BASE_VIDIOC_PRIVATE + 4, struct csiphy_cfg_data32) - -#define VIDIOC_MSM_SENSOR_CFG32 \ - _IOWR('V', BASE_VIDIOC_PRIVATE + 1, struct sensorb_cfg_data32) - -#define VIDIOC_MSM_EEPROM_CFG32 \ - _IOWR('V', BASE_VIDIOC_PRIVATE + 8, struct msm_eeprom_cfg_data32) - -#define VIDIOC_MSM_OIS_CFG32 \ - _IOWR('V', BASE_VIDIOC_PRIVATE + 11, struct msm_ois_cfg_data32) - -#define VIDIOC_MSM_CSID_IO_CFG32 \ - _IOWR('V', BASE_VIDIOC_PRIVATE + 5, struct csid_cfg_data32) - -#define VIDIOC_MSM_FLASH_CFG32 \ - _IOWR('V', BASE_VIDIOC_PRIVATE + 13, struct msm_flash_cfg_data_t32) -#endif - -#endif /* __LINUX_MSM_CAM_SENSOR_H */ diff --git a/third_party/linux/include/msm_camsensor_sdk.h b/third_party/linux/include/msm_camsensor_sdk.h deleted file mode 100644 index 62a4da253c..0000000000 --- a/third_party/linux/include/msm_camsensor_sdk.h +++ /dev/null @@ -1,386 +0,0 @@ -#ifndef __LINUX_MSM_CAMSENSOR_SDK_H -#define __LINUX_MSM_CAMSENSOR_SDK_H - -#define KVERSION 0x1 - -#define MAX_POWER_CONFIG 12 -#define GPIO_OUT_LOW (0 << 1) -#define GPIO_OUT_HIGH (1 << 1) -#define CSI_EMBED_DATA 0x12 -#define CSI_RESERVED_DATA_0 0x13 -#define CSI_YUV422_8 0x1E -#define CSI_RAW8 0x2A -#define CSI_RAW10 0x2B -#define CSI_RAW12 0x2C -#define CSI_DECODE_6BIT 0 -#define CSI_DECODE_8BIT 1 -#define CSI_DECODE_10BIT 2 -#define CSI_DECODE_12BIT 3 -#define CSI_DECODE_DPCM_10_8_10 5 -#define MAX_CID 16 -#define I2C_SEQ_REG_DATA_MAX 1024 -#define I2C_REG_DATA_MAX (8*1024) - -#define MSM_V4L2_PIX_FMT_META v4l2_fourcc('M', 'E', 'T', 'A') /* META */ -#define MSM_V4L2_PIX_FMT_SBGGR14 v4l2_fourcc('B', 'G', '1', '4') - /* 14 BGBG.. GRGR.. */ -#define MSM_V4L2_PIX_FMT_SGBRG14 v4l2_fourcc('G', 'B', '1', '4') - /* 14 GBGB.. RGRG.. */ -#define MSM_V4L2_PIX_FMT_SGRBG14 v4l2_fourcc('B', 'A', '1', '4') - /* 14 GRGR.. BGBG.. */ -#define MSM_V4L2_PIX_FMT_SRGGB14 v4l2_fourcc('R', 'G', '1', '4') - /* 14 RGRG.. GBGB.. */ - -#define MAX_ACTUATOR_REG_TBL_SIZE 8 -#define MAX_ACTUATOR_REGION 5 -#define NUM_ACTUATOR_DIR 2 -#define MAX_ACTUATOR_SCENARIO 8 -#define MAX_ACT_MOD_NAME_SIZE 32 -#define MAX_ACT_NAME_SIZE 32 -#define MAX_ACTUATOR_INIT_SET 120 -#define MAX_I2C_REG_SET 12 - -#define MAX_LED_TRIGGERS 3 - -#define MSM_EEPROM_MEMORY_MAP_MAX_SIZE 80 -#define MSM_EEPROM_MAX_MEM_MAP_CNT 8 - -enum msm_sensor_camera_id_t { - CAMERA_0, - CAMERA_1, - CAMERA_2, - CAMERA_3, - MAX_CAMERAS, -}; - -enum i2c_freq_mode_t { - I2C_STANDARD_MODE, - I2C_FAST_MODE, - I2C_CUSTOM_MODE, - I2C_FAST_PLUS_MODE, - I2C_MAX_MODES, -}; - -enum camb_position_t { - BACK_CAMERA_B, - FRONT_CAMERA_B, - AUX_CAMERA_B = 0x100, - INVALID_CAMERA_B, -}; - -enum msm_sensor_power_seq_type_t { - SENSOR_CLK, - SENSOR_GPIO, - SENSOR_VREG, - SENSOR_I2C_MUX, - SENSOR_I2C, -}; - -enum msm_camera_i2c_reg_addr_type { - MSM_CAMERA_I2C_BYTE_ADDR = 1, - MSM_CAMERA_I2C_WORD_ADDR, - MSM_CAMERA_I2C_3B_ADDR, - MSM_CAMERA_I2C_ADDR_TYPE_MAX, -}; - -enum msm_camera_i2c_data_type { - MSM_CAMERA_I2C_BYTE_DATA = 1, - MSM_CAMERA_I2C_WORD_DATA, - MSM_CAMERA_I2C_DWORD_DATA, - MSM_CAMERA_I2C_SET_BYTE_MASK, - MSM_CAMERA_I2C_UNSET_BYTE_MASK, - MSM_CAMERA_I2C_SET_WORD_MASK, - MSM_CAMERA_I2C_UNSET_WORD_MASK, - MSM_CAMERA_I2C_SET_BYTE_WRITE_MASK_DATA, - MSM_CAMERA_I2C_SEQ_DATA, - MSM_CAMERA_I2C_DATA_TYPE_MAX, -}; - -enum msm_sensor_power_seq_gpio_t { - SENSOR_GPIO_RESET, - SENSOR_GPIO_STANDBY, - SENSOR_GPIO_AF_PWDM, - SENSOR_GPIO_VIO, - SENSOR_GPIO_VANA, - SENSOR_GPIO_VDIG, - SENSOR_GPIO_VAF, - SENSOR_GPIO_FL_EN, - SENSOR_GPIO_FL_NOW, - SENSOR_GPIO_FL_RESET, - SENSOR_GPIO_CUSTOM1, - SENSOR_GPIO_CUSTOM2, - SENSOR_GPIO_MAX, -}; - -enum msm_camera_vreg_name_t { - CAM_VDIG, - CAM_VIO, - CAM_VANA, - CAM_VAF, - CAM_V_CUSTOM1, - CAM_V_CUSTOM2, - CAM_VREG_MAX, -}; - -enum msm_sensor_clk_type_t { - SENSOR_CAM_MCLK, - SENSOR_CAM_CLK, - SENSOR_CAM_CLK_MAX, -}; - -enum camerab_mode_t { - CAMERA_MODE_2D_B = (1<<0), - CAMERA_MODE_3D_B = (1<<1), - CAMERA_MODE_INVALID = (1<<2), -}; - -enum msm_actuator_data_type { - MSM_ACTUATOR_BYTE_DATA = 1, - MSM_ACTUATOR_WORD_DATA, -}; - -enum msm_actuator_addr_type { - MSM_ACTUATOR_BYTE_ADDR = 1, - MSM_ACTUATOR_WORD_ADDR, -}; - -enum msm_actuator_write_type { - MSM_ACTUATOR_WRITE_HW_DAMP, - MSM_ACTUATOR_WRITE_DAC, - MSM_ACTUATOR_WRITE, - MSM_ACTUATOR_WRITE_DIR_REG, - MSM_ACTUATOR_POLL, - MSM_ACTUATOR_READ_WRITE, -}; - -enum msm_actuator_i2c_operation { - MSM_ACT_WRITE = 0, - MSM_ACT_POLL, -}; - -enum actuator_type { - ACTUATOR_VCM, - ACTUATOR_PIEZO, - ACTUATOR_HVCM, - ACTUATOR_BIVCM, -}; - -enum msm_flash_driver_type { - FLASH_DRIVER_PMIC, - FLASH_DRIVER_I2C, - FLASH_DRIVER_GPIO, - FLASH_DRIVER_DEFAULT -}; - -enum msm_flash_cfg_type_t { - CFG_FLASH_INIT, - CFG_FLASH_RELEASE, - CFG_FLASH_OFF, - CFG_FLASH_LOW, - CFG_FLASH_HIGH, -}; - -enum msm_sensor_output_format_t { - MSM_SENSOR_BAYER, - MSM_SENSOR_YCBCR, - MSM_SENSOR_META, -}; - -struct msm_sensor_power_setting { - enum msm_sensor_power_seq_type_t seq_type; - unsigned short seq_val; - long config_val; - unsigned short delay; - void *data[10]; -}; - -struct msm_sensor_power_setting_array { - struct msm_sensor_power_setting power_setting_a[MAX_POWER_CONFIG]; - struct msm_sensor_power_setting *power_setting; - unsigned short size; - struct msm_sensor_power_setting power_down_setting_a[MAX_POWER_CONFIG]; - struct msm_sensor_power_setting *power_down_setting; - unsigned short size_down; -}; - -enum msm_camera_i2c_operation { - MSM_CAM_WRITE = 0, - MSM_CAM_POLL, - MSM_CAM_READ, -}; - -struct msm_sensor_i2c_sync_params { - unsigned int cid; - int csid; - unsigned short line; - unsigned short delay; -}; - -struct msm_camera_reg_settings_t { - uint16_t reg_addr; - enum msm_camera_i2c_reg_addr_type addr_type; - uint16_t reg_data; - enum msm_camera_i2c_data_type data_type; - enum msm_camera_i2c_operation i2c_operation; - uint16_t delay; -}; - -struct msm_eeprom_mem_map_t { - int slave_addr; - struct msm_camera_reg_settings_t - mem_settings[MSM_EEPROM_MEMORY_MAP_MAX_SIZE]; - int memory_map_size; -}; - -struct msm_eeprom_memory_map_array { - struct msm_eeprom_mem_map_t memory_map[MSM_EEPROM_MAX_MEM_MAP_CNT]; - uint32_t msm_size_of_max_mappings; -}; - -struct msm_sensor_init_params { - /* mask of modes supported: 2D, 3D */ - int modes_supported; - /* sensor position: front, back */ - enum camb_position_t position; - /* sensor mount angle */ - unsigned int sensor_mount_angle; -}; - -struct msm_sensor_id_info_t { - unsigned short sensor_id_reg_addr; - unsigned short sensor_id; - unsigned short sensor_id_mask; - // added in LeEco - unsigned char module_id; - unsigned char vcm_id; -}; - -struct msm_camera_sensor_slave_info { - char sensor_name[32]; - char eeprom_name[32]; - char actuator_name[32]; - char ois_name[32]; - char flash_name[32]; - enum msm_sensor_camera_id_t camera_id; - unsigned short slave_addr; - enum i2c_freq_mode_t i2c_freq_mode; - enum msm_camera_i2c_reg_addr_type addr_type; - struct msm_sensor_id_info_t sensor_id_info; - struct msm_sensor_power_setting_array power_setting_array; - unsigned char is_init_params_valid; - struct msm_sensor_init_params sensor_init_params; - enum msm_sensor_output_format_t output_format; -}; - -struct msm_camera_i2c_reg_array { - unsigned short reg_addr; - unsigned short reg_data; - unsigned int delay; -}; - -struct msm_camera_i2c_reg_setting { - struct msm_camera_i2c_reg_array *reg_setting; - unsigned short size; - enum msm_camera_i2c_reg_addr_type addr_type; - enum msm_camera_i2c_data_type data_type; - unsigned short delay; -}; - -struct msm_camera_csid_vc_cfg { - unsigned char cid; - unsigned char dt; - unsigned char decode_format; -}; - -struct msm_camera_csid_lut_params { - unsigned char num_cid; - struct msm_camera_csid_vc_cfg vc_cfg_a[MAX_CID]; - struct msm_camera_csid_vc_cfg *vc_cfg[MAX_CID]; -}; - -struct msm_camera_csid_params { - unsigned char lane_cnt; - unsigned short lane_assign; - unsigned char phy_sel; - unsigned int csi_clk; - struct msm_camera_csid_lut_params lut_params; - unsigned char csi_3p_sel; -}; - -struct msm_camera_csid_testmode_parms { - unsigned int num_bytes_per_line; - unsigned int num_lines; - unsigned int h_blanking_count; - unsigned int v_blanking_count; - unsigned int payload_mode; -}; - -struct msm_camera_csiphy_params { - unsigned char lane_cnt; - unsigned char settle_cnt; - unsigned short lane_mask; - unsigned char combo_mode; - unsigned char csid_core; - unsigned int csiphy_clk; - unsigned char csi_3phase; -}; - -struct msm_camera_i2c_seq_reg_array { - unsigned short reg_addr; - unsigned char reg_data[I2C_SEQ_REG_DATA_MAX]; - unsigned short reg_data_size; -}; - -struct msm_camera_i2c_seq_reg_setting { - struct msm_camera_i2c_seq_reg_array *reg_setting; - unsigned short size; - enum msm_camera_i2c_reg_addr_type addr_type; - unsigned short delay; -}; - -struct msm_actuator_reg_params_t { - enum msm_actuator_write_type reg_write_type; - unsigned int hw_mask; - unsigned short reg_addr; - unsigned short hw_shift; - unsigned short data_shift; - unsigned short data_type; - unsigned short addr_type; - unsigned short reg_data; - unsigned short delay; -}; - - -struct damping_params_t { - unsigned int damping_step; - unsigned int damping_delay; - unsigned int hw_params; -}; - -struct region_params_t { - /* [0] = ForwardDirection Macro boundary - [1] = ReverseDirection Inf boundary - */ - unsigned short step_bound[2]; - unsigned short code_per_step; - /* qvalue for converting float type numbers to integer format */ - unsigned int qvalue; -}; - -struct reg_settings_t { - unsigned short reg_addr; - enum msm_actuator_addr_type addr_type; - unsigned short reg_data; - enum msm_actuator_data_type data_type; - enum msm_actuator_i2c_operation i2c_operation; - unsigned int delay; -}; - -struct msm_camera_i2c_reg_setting_array { - struct msm_camera_i2c_reg_array reg_setting_a[MAX_I2C_REG_SET]; - unsigned short size; - enum msm_camera_i2c_reg_addr_type addr_type; - enum msm_camera_i2c_data_type data_type; - unsigned short delay; -}; -#endif /* __LINUX_MSM_CAM_SENSOR_H */ diff --git a/third_party/linux/include/msm_ion.h b/third_party/linux/include/msm_ion.h deleted file mode 100644 index d5caed5eb3..0000000000 --- a/third_party/linux/include/msm_ion.h +++ /dev/null @@ -1,211 +0,0 @@ -#ifndef _UAPI_MSM_ION_H -#define _UAPI_MSM_ION_H - -#include - -enum msm_ion_heap_types { - ION_HEAP_TYPE_MSM_START = ION_HEAP_TYPE_CUSTOM + 1, - ION_HEAP_TYPE_SECURE_DMA = ION_HEAP_TYPE_MSM_START, - ION_HEAP_TYPE_SYSTEM_SECURE, - ION_HEAP_TYPE_HYP_CMA, - /* - * if you add a heap type here you should also add it to - * heap_types_info[] in msm_ion.c - */ -}; - -/** - * These are the only ids that should be used for Ion heap ids. - * The ids listed are the order in which allocation will be attempted - * if specified. Don't swap the order of heap ids unless you know what - * you are doing! - * Id's are spaced by purpose to allow new Id's to be inserted in-between (for - * possible fallbacks) - */ - -enum ion_heap_ids { - INVALID_HEAP_ID = -1, - ION_CP_MM_HEAP_ID = 8, - ION_SECURE_HEAP_ID = 9, - ION_SECURE_DISPLAY_HEAP_ID = 10, - ION_CP_MFC_HEAP_ID = 12, - ION_CP_WB_HEAP_ID = 16, /* 8660 only */ - ION_CAMERA_HEAP_ID = 20, /* 8660 only */ - ION_SYSTEM_CONTIG_HEAP_ID = 21, - ION_ADSP_HEAP_ID = 22, - ION_PIL1_HEAP_ID = 23, /* Currently used for other PIL images */ - ION_SF_HEAP_ID = 24, - ION_SYSTEM_HEAP_ID = 25, - ION_PIL2_HEAP_ID = 26, /* Currently used for modem firmware images */ - ION_QSECOM_HEAP_ID = 27, - ION_AUDIO_HEAP_ID = 28, - - ION_MM_FIRMWARE_HEAP_ID = 29, - - ION_HEAP_ID_RESERVED = 31 /** Bit reserved for ION_FLAG_SECURE flag */ -}; - -/* - * The IOMMU heap is deprecated! Here are some aliases for backwards - * compatibility: - */ -#define ION_IOMMU_HEAP_ID ION_SYSTEM_HEAP_ID -#define ION_HEAP_TYPE_IOMMU ION_HEAP_TYPE_SYSTEM - -enum ion_fixed_position { - NOT_FIXED, - FIXED_LOW, - FIXED_MIDDLE, - FIXED_HIGH, -}; - -enum cp_mem_usage { - VIDEO_BITSTREAM = 0x1, - VIDEO_PIXEL = 0x2, - VIDEO_NONPIXEL = 0x3, - DISPLAY_SECURE_CP_USAGE = 0x4, - CAMERA_SECURE_CP_USAGE = 0x5, - MAX_USAGE = 0x6, - UNKNOWN = 0x7FFFFFFF, -}; - -/** - * Flags to be used when allocating from the secure heap for - * content protection - */ -#define ION_FLAG_CP_TOUCH (1 << 17) -#define ION_FLAG_CP_BITSTREAM (1 << 18) -#define ION_FLAG_CP_PIXEL (1 << 19) -#define ION_FLAG_CP_NON_PIXEL (1 << 20) -#define ION_FLAG_CP_CAMERA (1 << 21) -#define ION_FLAG_CP_HLOS (1 << 22) -#define ION_FLAG_CP_HLOS_FREE (1 << 23) -#define ION_FLAG_CP_SEC_DISPLAY (1 << 25) -#define ION_FLAG_CP_APP (1 << 26) - -/** - * Flag to allow non continguous allocation of memory from secure - * heap - */ -#define ION_FLAG_ALLOW_NON_CONTIG (1 << 24) - -/** - * Flag to use when allocating to indicate that a heap is secure. - */ -#define ION_FLAG_SECURE (1 << ION_HEAP_ID_RESERVED) - -/** - * Flag for clients to force contiguous memort allocation - * - * Use of this flag is carefully monitored! - */ -#define ION_FLAG_FORCE_CONTIGUOUS (1 << 30) - -/* - * Used in conjunction with heap which pool memory to force an allocation - * to come from the page allocator directly instead of from the pool allocation - */ -#define ION_FLAG_POOL_FORCE_ALLOC (1 << 16) - - -#define ION_FLAG_POOL_PREFETCH (1 << 27) - -/** -* Deprecated! Please use the corresponding ION_FLAG_* -*/ -#define ION_SECURE ION_FLAG_SECURE -#define ION_FORCE_CONTIGUOUS ION_FLAG_FORCE_CONTIGUOUS - -/** - * Macro should be used with ion_heap_ids defined above. - */ -#define ION_HEAP(bit) (1 << (bit)) - -#define ION_ADSP_HEAP_NAME "adsp" -#define ION_SYSTEM_HEAP_NAME "system" -#define ION_VMALLOC_HEAP_NAME ION_SYSTEM_HEAP_NAME -#define ION_KMALLOC_HEAP_NAME "kmalloc" -#define ION_AUDIO_HEAP_NAME "audio" -#define ION_SF_HEAP_NAME "sf" -#define ION_MM_HEAP_NAME "mm" -#define ION_CAMERA_HEAP_NAME "camera_preview" -#define ION_IOMMU_HEAP_NAME "iommu" -#define ION_MFC_HEAP_NAME "mfc" -#define ION_WB_HEAP_NAME "wb" -#define ION_MM_FIRMWARE_HEAP_NAME "mm_fw" -#define ION_PIL1_HEAP_NAME "pil_1" -#define ION_PIL2_HEAP_NAME "pil_2" -#define ION_QSECOM_HEAP_NAME "qsecom" -#define ION_SECURE_HEAP_NAME "secure_heap" -#define ION_SECURE_DISPLAY_HEAP_NAME "secure_display" - -#define ION_SET_CACHED(__cache) (__cache | ION_FLAG_CACHED) -#define ION_SET_UNCACHED(__cache) (__cache & ~ION_FLAG_CACHED) - -#define ION_IS_CACHED(__flags) ((__flags) & ION_FLAG_CACHED) - -/* struct ion_flush_data - data passed to ion for flushing caches - * - * @handle: handle with data to flush - * @fd: fd to flush - * @vaddr: userspace virtual address mapped with mmap - * @offset: offset into the handle to flush - * @length: length of handle to flush - * - * Performs cache operations on the handle. If p is the start address - * of the handle, p + offset through p + offset + length will have - * the cache operations performed - */ -struct ion_flush_data { - ion_user_handle_t handle; - int fd; - void *vaddr; - unsigned int offset; - unsigned int length; -}; - -struct ion_prefetch_regions { - unsigned int vmid; - size_t *sizes; - unsigned int nr_sizes; -}; - -struct ion_prefetch_data { - int heap_id; - unsigned long len; - /* Is unsigned long bad? 32bit compiler vs 64 bit compiler*/ - struct ion_prefetch_regions *regions; - unsigned int nr_regions; -}; - -#define ION_IOC_MSM_MAGIC 'M' - -/** - * DOC: ION_IOC_CLEAN_CACHES - clean the caches - * - * Clean the caches of the handle specified. - */ -#define ION_IOC_CLEAN_CACHES _IOWR(ION_IOC_MSM_MAGIC, 0, \ - struct ion_flush_data) -/** - * DOC: ION_IOC_INV_CACHES - invalidate the caches - * - * Invalidate the caches of the handle specified. - */ -#define ION_IOC_INV_CACHES _IOWR(ION_IOC_MSM_MAGIC, 1, \ - struct ion_flush_data) -/** - * DOC: ION_IOC_CLEAN_INV_CACHES - clean and invalidate the caches - * - * Clean and invalidate the caches of the handle specified. - */ -#define ION_IOC_CLEAN_INV_CACHES _IOWR(ION_IOC_MSM_MAGIC, 2, \ - struct ion_flush_data) - -#define ION_IOC_PREFETCH _IOWR(ION_IOC_MSM_MAGIC, 3, \ - struct ion_prefetch_data) - -#define ION_IOC_DRAIN _IOWR(ION_IOC_MSM_MAGIC, 4, \ - struct ion_prefetch_data) - -#endif diff --git a/third_party/linux/include/msm_kgsl.h b/third_party/linux/include/msm_kgsl.h deleted file mode 100644 index 93582eb066..0000000000 --- a/third_party/linux/include/msm_kgsl.h +++ /dev/null @@ -1,1449 +0,0 @@ -#ifndef _UAPI_MSM_KGSL_H -#define _UAPI_MSM_KGSL_H - -#include -#include - -/* - * The KGSL version has proven not to be very useful in userspace if features - * are cherry picked into other trees out of order so it is frozen as of 3.14. - * It is left here for backwards compatabilty and as a reminder that - * software releases are never linear. Also, I like pie. - */ - -#define KGSL_VERSION_MAJOR 3 -#define KGSL_VERSION_MINOR 14 - -/* - * We have traditionally mixed context and issueibcmds / command batch flags - * together into a big flag stew. This worked fine until we started adding a - * lot more command batch flags and we started running out of bits. Turns out - * we have a bit of room in the context type / priority mask that we could use - * for command batches, but that means we need to split out the flags into two - * coherent sets. - * - * If any future definitions are for both context and cmdbatch add both defines - * and link the cmdbatch to the context define as we do below. Otherwise feel - * free to add exclusive bits to either set. - */ - -/* --- context flags --- */ -#define KGSL_CONTEXT_SAVE_GMEM 0x00000001 -#define KGSL_CONTEXT_NO_GMEM_ALLOC 0x00000002 -/* This is a cmdbatch exclusive flag - use the CMDBATCH equivalent instead */ -#define KGSL_CONTEXT_SUBMIT_IB_LIST 0x00000004 -#define KGSL_CONTEXT_CTX_SWITCH 0x00000008 -#define KGSL_CONTEXT_PREAMBLE 0x00000010 -#define KGSL_CONTEXT_TRASH_STATE 0x00000020 -#define KGSL_CONTEXT_PER_CONTEXT_TS 0x00000040 -#define KGSL_CONTEXT_USER_GENERATED_TS 0x00000080 -/* This is a cmdbatch exclusive flag - use the CMDBATCH equivalent instead */ -#define KGSL_CONTEXT_END_OF_FRAME 0x00000100 -#define KGSL_CONTEXT_NO_FAULT_TOLERANCE 0x00000200 -/* This is a cmdbatch exclusive flag - use the CMDBATCH equivalent instead */ -#define KGSL_CONTEXT_SYNC 0x00000400 -#define KGSL_CONTEXT_PWR_CONSTRAINT 0x00000800 - -#define KGSL_CONTEXT_PRIORITY_MASK 0x0000F000 -#define KGSL_CONTEXT_PRIORITY_SHIFT 12 -#define KGSL_CONTEXT_PRIORITY_UNDEF 0 - -#define KGSL_CONTEXT_IFH_NOP 0x00010000 -#define KGSL_CONTEXT_SECURE 0x00020000 - -#define KGSL_CONTEXT_PREEMPT_STYLE_MASK 0x0E000000 -#define KGSL_CONTEXT_PREEMPT_STYLE_SHIFT 25 -#define KGSL_CONTEXT_PREEMPT_STYLE_DEFAULT 0x0 -#define KGSL_CONTEXT_PREEMPT_STYLE_RINGBUFFER 0x1 -#define KGSL_CONTEXT_PREEMPT_STYLE_FINEGRAIN 0x2 - -#define KGSL_CONTEXT_TYPE_MASK 0x01F00000 -#define KGSL_CONTEXT_TYPE_SHIFT 20 -#define KGSL_CONTEXT_TYPE_ANY 0 -#define KGSL_CONTEXT_TYPE_GL 1 -#define KGSL_CONTEXT_TYPE_CL 2 -#define KGSL_CONTEXT_TYPE_C2D 3 -#define KGSL_CONTEXT_TYPE_RS 4 -#define KGSL_CONTEXT_TYPE_UNKNOWN 0x1E - -#define KGSL_CONTEXT_INVALID 0xffffffff - -/* - * --- command batch flags --- - * The bits that are linked to a KGSL_CONTEXT equivalent are either legacy - * definitions or bits that are valid for both contexts and cmdbatches. To be - * safe the other 8 bits that are still available in the context field should be - * omitted here in case we need to share - the other bits are available for - * cmdbatch only flags as needed - */ -#define KGSL_CMDBATCH_MEMLIST 0x00000001 -#define KGSL_CMDBATCH_MARKER 0x00000002 -#define KGSL_CMDBATCH_SUBMIT_IB_LIST KGSL_CONTEXT_SUBMIT_IB_LIST /* 0x004 */ -#define KGSL_CMDBATCH_CTX_SWITCH KGSL_CONTEXT_CTX_SWITCH /* 0x008 */ -#define KGSL_CMDBATCH_PROFILING 0x00000010 -#define KGSL_CMDBATCH_PROFILING_KTIME 0x00000020 -#define KGSL_CMDBATCH_END_OF_FRAME KGSL_CONTEXT_END_OF_FRAME /* 0x100 */ -#define KGSL_CMDBATCH_SYNC KGSL_CONTEXT_SYNC /* 0x400 */ -#define KGSL_CMDBATCH_PWR_CONSTRAINT KGSL_CONTEXT_PWR_CONSTRAINT /* 0x800 */ - -/* - * Reserve bits [16:19] and bits [28:31] for possible bits shared between - * contexts and command batches. Update this comment as new flags are added. - */ - -/* - * gpu_command_object flags - these flags communicate the type of command or - * memory object being submitted for a GPU command - */ - -/* Flags for GPU command objects */ -#define KGSL_CMDLIST_IB 0x00000001U -#define KGSL_CMDLIST_CTXTSWITCH_PREAMBLE 0x00000002U -#define KGSL_CMDLIST_IB_PREAMBLE 0x00000004U - -/* Flags for GPU command memory objects */ -#define KGSL_OBJLIST_MEMOBJ 0x00000008U -#define KGSL_OBJLIST_PROFILE 0x00000010U - -/* Flags for GPU command sync points */ -#define KGSL_CMD_SYNCPOINT_TYPE_TIMESTAMP 0 -#define KGSL_CMD_SYNCPOINT_TYPE_FENCE 1 - -/* --- Memory allocation flags --- */ - -/* General allocation hints */ -#define KGSL_MEMFLAGS_SECURE 0x00000008ULL -#define KGSL_MEMFLAGS_GPUREADONLY 0x01000000U -#define KGSL_MEMFLAGS_GPUWRITEONLY 0x02000000U -#define KGSL_MEMFLAGS_FORCE_32BIT 0x100000000ULL - -/* Memory caching hints */ -#define KGSL_CACHEMODE_MASK 0x0C000000U -#define KGSL_CACHEMODE_SHIFT 26 - -#define KGSL_CACHEMODE_WRITECOMBINE 0 -#define KGSL_CACHEMODE_UNCACHED 1 -#define KGSL_CACHEMODE_WRITETHROUGH 2 -#define KGSL_CACHEMODE_WRITEBACK 3 - -#define KGSL_MEMFLAGS_USE_CPU_MAP 0x10000000ULL - -/* Memory types for which allocations are made */ -#define KGSL_MEMTYPE_MASK 0x0000FF00 -#define KGSL_MEMTYPE_SHIFT 8 - -#define KGSL_MEMTYPE_OBJECTANY 0 -#define KGSL_MEMTYPE_FRAMEBUFFER 1 -#define KGSL_MEMTYPE_RENDERBUFFER 2 -#define KGSL_MEMTYPE_ARRAYBUFFER 3 -#define KGSL_MEMTYPE_ELEMENTARRAYBUFFER 4 -#define KGSL_MEMTYPE_VERTEXARRAYBUFFER 5 -#define KGSL_MEMTYPE_TEXTURE 6 -#define KGSL_MEMTYPE_SURFACE 7 -#define KGSL_MEMTYPE_EGL_SURFACE 8 -#define KGSL_MEMTYPE_GL 9 -#define KGSL_MEMTYPE_CL 10 -#define KGSL_MEMTYPE_CL_BUFFER_MAP 11 -#define KGSL_MEMTYPE_CL_BUFFER_NOMAP 12 -#define KGSL_MEMTYPE_CL_IMAGE_MAP 13 -#define KGSL_MEMTYPE_CL_IMAGE_NOMAP 14 -#define KGSL_MEMTYPE_CL_KERNEL_STACK 15 -#define KGSL_MEMTYPE_COMMAND 16 -#define KGSL_MEMTYPE_2D 17 -#define KGSL_MEMTYPE_EGL_IMAGE 18 -#define KGSL_MEMTYPE_EGL_SHADOW 19 -#define KGSL_MEMTYPE_MULTISAMPLE 20 -#define KGSL_MEMTYPE_KERNEL 255 - -/* - * Alignment hint, passed as the power of 2 exponent. - * i.e 4k (2^12) would be 12, 64k (2^16)would be 16. - */ -#define KGSL_MEMALIGN_MASK 0x00FF0000 -#define KGSL_MEMALIGN_SHIFT 16 - -enum kgsl_user_mem_type { - KGSL_USER_MEM_TYPE_PMEM = 0x00000000, - KGSL_USER_MEM_TYPE_ASHMEM = 0x00000001, - KGSL_USER_MEM_TYPE_ADDR = 0x00000002, - KGSL_USER_MEM_TYPE_ION = 0x00000003, - /* - * ION type is retained for backwards compatibilty but Ion buffers are - * dma-bufs so try to use that naming if we can - */ - KGSL_USER_MEM_TYPE_DMABUF = 0x00000003, - KGSL_USER_MEM_TYPE_MAX = 0x00000007, -}; -#define KGSL_MEMFLAGS_USERMEM_MASK 0x000000e0 -#define KGSL_MEMFLAGS_USERMEM_SHIFT 5 - -/* - * Unfortunately, enum kgsl_user_mem_type starts at 0 which does not - * leave a good value for allocated memory. In the flags we use - * 0 to indicate allocated memory and thus need to add 1 to the enum - * values. - */ -#define KGSL_USERMEM_FLAG(x) (((x) + 1) << KGSL_MEMFLAGS_USERMEM_SHIFT) - -#define KGSL_MEMFLAGS_NOT_USERMEM 0 -#define KGSL_MEMFLAGS_USERMEM_PMEM KGSL_USERMEM_FLAG(KGSL_USER_MEM_TYPE_PMEM) -#define KGSL_MEMFLAGS_USERMEM_ASHMEM \ - KGSL_USERMEM_FLAG(KGSL_USER_MEM_TYPE_ASHMEM) -#define KGSL_MEMFLAGS_USERMEM_ADDR KGSL_USERMEM_FLAG(KGSL_USER_MEM_TYPE_ADDR) -#define KGSL_MEMFLAGS_USERMEM_ION KGSL_USERMEM_FLAG(KGSL_USER_MEM_TYPE_ION) - -/* --- generic KGSL flag values --- */ - -#define KGSL_FLAGS_NORMALMODE 0x00000000 -#define KGSL_FLAGS_SAFEMODE 0x00000001 -#define KGSL_FLAGS_INITIALIZED0 0x00000002 -#define KGSL_FLAGS_INITIALIZED 0x00000004 -#define KGSL_FLAGS_STARTED 0x00000008 -#define KGSL_FLAGS_ACTIVE 0x00000010 -#define KGSL_FLAGS_RESERVED0 0x00000020 -#define KGSL_FLAGS_RESERVED1 0x00000040 -#define KGSL_FLAGS_RESERVED2 0x00000080 -#define KGSL_FLAGS_SOFT_RESET 0x00000100 -#define KGSL_FLAGS_PER_CONTEXT_TIMESTAMPS 0x00000200 - -/* Server Side Sync Timeout in milliseconds */ -#define KGSL_SYNCOBJ_SERVER_TIMEOUT 2000 - -/* - * Reset status values for context - */ -enum kgsl_ctx_reset_stat { - KGSL_CTX_STAT_NO_ERROR = 0x00000000, - KGSL_CTX_STAT_GUILTY_CONTEXT_RESET_EXT = 0x00000001, - KGSL_CTX_STAT_INNOCENT_CONTEXT_RESET_EXT = 0x00000002, - KGSL_CTX_STAT_UNKNOWN_CONTEXT_RESET_EXT = 0x00000003 -}; - -#define KGSL_CONVERT_TO_MBPS(val) \ - (val*1000*1000U) - -/* device id */ -enum kgsl_deviceid { - KGSL_DEVICE_3D0 = 0x00000000, - KGSL_DEVICE_MAX -}; - -struct kgsl_devinfo { - - unsigned int device_id; - /* chip revision id - * coreid:8 majorrev:8 minorrev:8 patch:8 - */ - unsigned int chip_id; - unsigned int mmu_enabled; - unsigned long gmem_gpubaseaddr; - /* - * This field contains the adreno revision - * number 200, 205, 220, etc... - */ - unsigned int gpu_id; - size_t gmem_sizebytes; -}; - -/* - * struct kgsl_devmemstore - this structure defines the region of memory - * that can be mmap()ed from this driver. The timestamp fields are volatile - * because they are written by the GPU - * @soptimestamp: Start of pipeline timestamp written by GPU before the - * commands in concern are processed - * @sbz: Unused, kept for 8 byte alignment - * @eoptimestamp: End of pipeline timestamp written by GPU after the - * commands in concern are processed - * @sbz2: Unused, kept for 8 byte alignment - * @preempted: Indicates if the context was preempted - * @sbz3: Unused, kept for 8 byte alignment - * @ref_wait_ts: Timestamp on which to generate interrupt, unused now. - * @sbz4: Unused, kept for 8 byte alignment - * @current_context: The current context the GPU is working on - * @sbz5: Unused, kept for 8 byte alignment - */ -struct kgsl_devmemstore { - volatile unsigned int soptimestamp; - unsigned int sbz; - volatile unsigned int eoptimestamp; - unsigned int sbz2; - volatile unsigned int preempted; - unsigned int sbz3; - volatile unsigned int ref_wait_ts; - unsigned int sbz4; - unsigned int current_context; - unsigned int sbz5; -}; - -#define KGSL_MEMSTORE_OFFSET(ctxt_id, field) \ - ((ctxt_id)*sizeof(struct kgsl_devmemstore) + \ - offsetof(struct kgsl_devmemstore, field)) - -/* timestamp id*/ -enum kgsl_timestamp_type { - KGSL_TIMESTAMP_CONSUMED = 0x00000001, /* start-of-pipeline timestamp */ - KGSL_TIMESTAMP_RETIRED = 0x00000002, /* end-of-pipeline timestamp*/ - KGSL_TIMESTAMP_QUEUED = 0x00000003, -}; - -/* property types - used with kgsl_device_getproperty */ -#define KGSL_PROP_DEVICE_INFO 0x1 -#define KGSL_PROP_DEVICE_SHADOW 0x2 -#define KGSL_PROP_DEVICE_POWER 0x3 -#define KGSL_PROP_SHMEM 0x4 -#define KGSL_PROP_SHMEM_APERTURES 0x5 -#define KGSL_PROP_MMU_ENABLE 0x6 -#define KGSL_PROP_INTERRUPT_WAITS 0x7 -#define KGSL_PROP_VERSION 0x8 -#define KGSL_PROP_GPU_RESET_STAT 0x9 -#define KGSL_PROP_PWRCTRL 0xE -#define KGSL_PROP_PWR_CONSTRAINT 0x12 -#define KGSL_PROP_UCHE_GMEM_VADDR 0x13 -#define KGSL_PROP_SP_GENERIC_MEM 0x14 -#define KGSL_PROP_UCODE_VERSION 0x15 -#define KGSL_PROP_GPMU_VERSION 0x16 -#define KGSL_PROP_DEVICE_BITNESS 0x18 - -struct kgsl_shadowprop { - unsigned long gpuaddr; - size_t size; - unsigned int flags; /* contains KGSL_FLAGS_ values */ -}; - -struct kgsl_version { - unsigned int drv_major; - unsigned int drv_minor; - unsigned int dev_major; - unsigned int dev_minor; -}; - -struct kgsl_sp_generic_mem { - uint64_t local; - uint64_t pvt; -}; - -struct kgsl_ucode_version { - unsigned int pfp; - unsigned int pm4; -}; - -struct kgsl_gpmu_version { - unsigned int major; - unsigned int minor; - unsigned int features; -}; - -/* Performance counter groups */ - -#define KGSL_PERFCOUNTER_GROUP_CP 0x0 -#define KGSL_PERFCOUNTER_GROUP_RBBM 0x1 -#define KGSL_PERFCOUNTER_GROUP_PC 0x2 -#define KGSL_PERFCOUNTER_GROUP_VFD 0x3 -#define KGSL_PERFCOUNTER_GROUP_HLSQ 0x4 -#define KGSL_PERFCOUNTER_GROUP_VPC 0x5 -#define KGSL_PERFCOUNTER_GROUP_TSE 0x6 -#define KGSL_PERFCOUNTER_GROUP_RAS 0x7 -#define KGSL_PERFCOUNTER_GROUP_UCHE 0x8 -#define KGSL_PERFCOUNTER_GROUP_TP 0x9 -#define KGSL_PERFCOUNTER_GROUP_SP 0xA -#define KGSL_PERFCOUNTER_GROUP_RB 0xB -#define KGSL_PERFCOUNTER_GROUP_PWR 0xC -#define KGSL_PERFCOUNTER_GROUP_VBIF 0xD -#define KGSL_PERFCOUNTER_GROUP_VBIF_PWR 0xE -#define KGSL_PERFCOUNTER_GROUP_MH 0xF -#define KGSL_PERFCOUNTER_GROUP_PA_SU 0x10 -#define KGSL_PERFCOUNTER_GROUP_SQ 0x11 -#define KGSL_PERFCOUNTER_GROUP_SX 0x12 -#define KGSL_PERFCOUNTER_GROUP_TCF 0x13 -#define KGSL_PERFCOUNTER_GROUP_TCM 0x14 -#define KGSL_PERFCOUNTER_GROUP_TCR 0x15 -#define KGSL_PERFCOUNTER_GROUP_L2 0x16 -#define KGSL_PERFCOUNTER_GROUP_VSC 0x17 -#define KGSL_PERFCOUNTER_GROUP_CCU 0x18 -#define KGSL_PERFCOUNTER_GROUP_LRZ 0x19 -#define KGSL_PERFCOUNTER_GROUP_CMP 0x1A -#define KGSL_PERFCOUNTER_GROUP_ALWAYSON 0x1B -#define KGSL_PERFCOUNTER_GROUP_SP_PWR 0x1C -#define KGSL_PERFCOUNTER_GROUP_TP_PWR 0x1D -#define KGSL_PERFCOUNTER_GROUP_RB_PWR 0x1E -#define KGSL_PERFCOUNTER_GROUP_CCU_PWR 0x1F -#define KGSL_PERFCOUNTER_GROUP_UCHE_PWR 0x20 -#define KGSL_PERFCOUNTER_GROUP_CP_PWR 0x21 -#define KGSL_PERFCOUNTER_GROUP_GPMU_PWR 0x22 -#define KGSL_PERFCOUNTER_GROUP_ALWAYSON_PWR 0x23 -#define KGSL_PERFCOUNTER_GROUP_MAX 0x24 - -#define KGSL_PERFCOUNTER_NOT_USED 0xFFFFFFFF -#define KGSL_PERFCOUNTER_BROKEN 0xFFFFFFFE - -/* structure holds list of ibs */ -struct kgsl_ibdesc { - unsigned long gpuaddr; - unsigned long __pad; - size_t sizedwords; - unsigned int ctrl; -}; - -/** - * struct kgsl_cmdbatch_profiling_buffer - * @wall_clock_s: Ringbuffer submission time (seconds). - * If KGSL_CMDBATCH_PROFILING_KTIME is set, time is provided - * in kernel clocks, otherwise wall clock time is used. - * @wall_clock_ns: Ringbuffer submission time (nanoseconds). - * If KGSL_CMDBATCH_PROFILING_KTIME is set time is provided - * in kernel clocks, otherwise wall clock time is used. - * @gpu_ticks_queued: GPU ticks at ringbuffer submission - * @gpu_ticks_submitted: GPU ticks when starting cmdbatch execution - * @gpu_ticks_retired: GPU ticks when finishing cmdbatch execution - * - * This structure defines the profiling buffer used to measure cmdbatch - * execution time - */ -struct kgsl_cmdbatch_profiling_buffer { - uint64_t wall_clock_s; - uint64_t wall_clock_ns; - uint64_t gpu_ticks_queued; - uint64_t gpu_ticks_submitted; - uint64_t gpu_ticks_retired; -}; - -/* ioctls */ -#define KGSL_IOC_TYPE 0x09 - -/* get misc info about the GPU - type should be a value from enum kgsl_property_type - value points to a structure that varies based on type - sizebytes is sizeof() that structure - for KGSL_PROP_DEVICE_INFO, use struct kgsl_devinfo - this structure contaings hardware versioning info. - for KGSL_PROP_DEVICE_SHADOW, use struct kgsl_shadowprop - this is used to find mmap() offset and sizes for mapping - struct kgsl_memstore into userspace. -*/ -struct kgsl_device_getproperty { - unsigned int type; - void __user *value; - size_t sizebytes; -}; - -#define IOCTL_KGSL_DEVICE_GETPROPERTY \ - _IOWR(KGSL_IOC_TYPE, 0x2, struct kgsl_device_getproperty) - -/* IOCTL_KGSL_DEVICE_READ (0x3) - removed 03/2012 - */ - -/* block until the GPU has executed past a given timestamp - * timeout is in milliseconds. - */ -struct kgsl_device_waittimestamp { - unsigned int timestamp; - unsigned int timeout; -}; - -#define IOCTL_KGSL_DEVICE_WAITTIMESTAMP \ - _IOW(KGSL_IOC_TYPE, 0x6, struct kgsl_device_waittimestamp) - -struct kgsl_device_waittimestamp_ctxtid { - unsigned int context_id; - unsigned int timestamp; - unsigned int timeout; -}; - -#define IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID \ - _IOW(KGSL_IOC_TYPE, 0x7, struct kgsl_device_waittimestamp_ctxtid) - -/* DEPRECATED: issue indirect commands to the GPU. - * drawctxt_id must have been created with IOCTL_KGSL_DRAWCTXT_CREATE - * ibaddr and sizedwords must specify a subset of a buffer created - * with IOCTL_KGSL_SHAREDMEM_FROM_PMEM - * flags may be a mask of KGSL_CONTEXT_ values - * timestamp is a returned counter value which can be passed to - * other ioctls to determine when the commands have been executed by - * the GPU. - * - * This fucntion is deprecated - consider using IOCTL_KGSL_SUBMIT_COMMANDS - * instead - */ -struct kgsl_ringbuffer_issueibcmds { - unsigned int drawctxt_id; - unsigned long ibdesc_addr; - unsigned int numibs; - unsigned int timestamp; /*output param */ - unsigned int flags; -}; - -#define IOCTL_KGSL_RINGBUFFER_ISSUEIBCMDS \ - _IOWR(KGSL_IOC_TYPE, 0x10, struct kgsl_ringbuffer_issueibcmds) - -/* read the most recently executed timestamp value - * type should be a value from enum kgsl_timestamp_type - */ -struct kgsl_cmdstream_readtimestamp { - unsigned int type; - unsigned int timestamp; /*output param */ -}; - -#define IOCTL_KGSL_CMDSTREAM_READTIMESTAMP_OLD \ - _IOR(KGSL_IOC_TYPE, 0x11, struct kgsl_cmdstream_readtimestamp) - -#define IOCTL_KGSL_CMDSTREAM_READTIMESTAMP \ - _IOWR(KGSL_IOC_TYPE, 0x11, struct kgsl_cmdstream_readtimestamp) - -/* free memory when the GPU reaches a given timestamp. - * gpuaddr specify a memory region created by a - * IOCTL_KGSL_SHAREDMEM_FROM_PMEM call - * type should be a value from enum kgsl_timestamp_type - */ -struct kgsl_cmdstream_freememontimestamp { - unsigned long gpuaddr; - unsigned int type; - unsigned int timestamp; -}; - -#define IOCTL_KGSL_CMDSTREAM_FREEMEMONTIMESTAMP \ - _IOW(KGSL_IOC_TYPE, 0x12, struct kgsl_cmdstream_freememontimestamp) - -/* Previous versions of this header had incorrectly defined - IOCTL_KGSL_CMDSTREAM_FREEMEMONTIMESTAMP as a read-only ioctl instead - of a write only ioctl. To ensure binary compatability, the following - #define will be used to intercept the incorrect ioctl -*/ - -#define IOCTL_KGSL_CMDSTREAM_FREEMEMONTIMESTAMP_OLD \ - _IOR(KGSL_IOC_TYPE, 0x12, struct kgsl_cmdstream_freememontimestamp) - -/* create a draw context, which is used to preserve GPU state. - * The flags field may contain a mask KGSL_CONTEXT_* values - */ -struct kgsl_drawctxt_create { - unsigned int flags; - unsigned int drawctxt_id; /*output param */ -}; - -#define IOCTL_KGSL_DRAWCTXT_CREATE \ - _IOWR(KGSL_IOC_TYPE, 0x13, struct kgsl_drawctxt_create) - -/* destroy a draw context */ -struct kgsl_drawctxt_destroy { - unsigned int drawctxt_id; -}; - -#define IOCTL_KGSL_DRAWCTXT_DESTROY \ - _IOW(KGSL_IOC_TYPE, 0x14, struct kgsl_drawctxt_destroy) - -/* add a block of pmem, fb, ashmem or user allocated address - * into the GPU address space */ -struct kgsl_map_user_mem { - int fd; - unsigned long gpuaddr; /*output param */ - size_t len; - size_t offset; - unsigned long hostptr; /*input param */ - enum kgsl_user_mem_type memtype; - unsigned int flags; -}; - -#define IOCTL_KGSL_MAP_USER_MEM \ - _IOWR(KGSL_IOC_TYPE, 0x15, struct kgsl_map_user_mem) - -struct kgsl_cmdstream_readtimestamp_ctxtid { - unsigned int context_id; - unsigned int type; - unsigned int timestamp; /*output param */ -}; - -#define IOCTL_KGSL_CMDSTREAM_READTIMESTAMP_CTXTID \ - _IOWR(KGSL_IOC_TYPE, 0x16, struct kgsl_cmdstream_readtimestamp_ctxtid) - -struct kgsl_cmdstream_freememontimestamp_ctxtid { - unsigned int context_id; - unsigned long gpuaddr; - unsigned int type; - unsigned int timestamp; -}; - -#define IOCTL_KGSL_CMDSTREAM_FREEMEMONTIMESTAMP_CTXTID \ - _IOW(KGSL_IOC_TYPE, 0x17, \ - struct kgsl_cmdstream_freememontimestamp_ctxtid) - -/* add a block of pmem or fb into the GPU address space */ -struct kgsl_sharedmem_from_pmem { - int pmem_fd; - unsigned long gpuaddr; /*output param */ - unsigned int len; - unsigned int offset; -}; - -#define IOCTL_KGSL_SHAREDMEM_FROM_PMEM \ - _IOWR(KGSL_IOC_TYPE, 0x20, struct kgsl_sharedmem_from_pmem) - -/* remove memory from the GPU's address space */ -struct kgsl_sharedmem_free { - unsigned long gpuaddr; -}; - -#define IOCTL_KGSL_SHAREDMEM_FREE \ - _IOW(KGSL_IOC_TYPE, 0x21, struct kgsl_sharedmem_free) - -struct kgsl_cff_user_event { - unsigned char cff_opcode; - unsigned int op1; - unsigned int op2; - unsigned int op3; - unsigned int op4; - unsigned int op5; - unsigned int __pad[2]; -}; - -#define IOCTL_KGSL_CFF_USER_EVENT \ - _IOW(KGSL_IOC_TYPE, 0x31, struct kgsl_cff_user_event) - -struct kgsl_gmem_desc { - unsigned int x; - unsigned int y; - unsigned int width; - unsigned int height; - unsigned int pitch; -}; - -struct kgsl_buffer_desc { - void *hostptr; - unsigned long gpuaddr; - int size; - unsigned int format; - unsigned int pitch; - unsigned int enabled; -}; - -struct kgsl_bind_gmem_shadow { - unsigned int drawctxt_id; - struct kgsl_gmem_desc gmem_desc; - unsigned int shadow_x; - unsigned int shadow_y; - struct kgsl_buffer_desc shadow_buffer; - unsigned int buffer_id; -}; - -#define IOCTL_KGSL_DRAWCTXT_BIND_GMEM_SHADOW \ - _IOW(KGSL_IOC_TYPE, 0x22, struct kgsl_bind_gmem_shadow) - -/* add a block of memory into the GPU address space */ - -/* - * IOCTL_KGSL_SHAREDMEM_FROM_VMALLOC deprecated 09/2012 - * use IOCTL_KGSL_GPUMEM_ALLOC instead - */ - -struct kgsl_sharedmem_from_vmalloc { - unsigned long gpuaddr; /*output param */ - unsigned int hostptr; - unsigned int flags; -}; - -#define IOCTL_KGSL_SHAREDMEM_FROM_VMALLOC \ - _IOWR(KGSL_IOC_TYPE, 0x23, struct kgsl_sharedmem_from_vmalloc) - -/* - * This is being deprecated in favor of IOCTL_KGSL_GPUMEM_CACHE_SYNC which - * supports both directions (flush and invalidate). This code will still - * work, but by definition it will do a flush of the cache which might not be - * what you want to have happen on a buffer following a GPU operation. It is - * safer to go with IOCTL_KGSL_GPUMEM_CACHE_SYNC - */ - -#define IOCTL_KGSL_SHAREDMEM_FLUSH_CACHE \ - _IOW(KGSL_IOC_TYPE, 0x24, struct kgsl_sharedmem_free) - -struct kgsl_drawctxt_set_bin_base_offset { - unsigned int drawctxt_id; - unsigned int offset; -}; - -#define IOCTL_KGSL_DRAWCTXT_SET_BIN_BASE_OFFSET \ - _IOW(KGSL_IOC_TYPE, 0x25, struct kgsl_drawctxt_set_bin_base_offset) - -enum kgsl_cmdwindow_type { - KGSL_CMDWINDOW_MIN = 0x00000000, - KGSL_CMDWINDOW_2D = 0x00000000, - KGSL_CMDWINDOW_3D = 0x00000001, /* legacy */ - KGSL_CMDWINDOW_MMU = 0x00000002, - KGSL_CMDWINDOW_ARBITER = 0x000000FF, - KGSL_CMDWINDOW_MAX = 0x000000FF, -}; - -/* write to the command window */ -struct kgsl_cmdwindow_write { - enum kgsl_cmdwindow_type target; - unsigned int addr; - unsigned int data; -}; - -#define IOCTL_KGSL_CMDWINDOW_WRITE \ - _IOW(KGSL_IOC_TYPE, 0x2e, struct kgsl_cmdwindow_write) - -struct kgsl_gpumem_alloc { - unsigned long gpuaddr; /* output param */ - size_t size; - unsigned int flags; -}; - -#define IOCTL_KGSL_GPUMEM_ALLOC \ - _IOWR(KGSL_IOC_TYPE, 0x2f, struct kgsl_gpumem_alloc) - -struct kgsl_cff_syncmem { - unsigned long gpuaddr; - size_t len; - unsigned int __pad[2]; /* For future binary compatibility */ -}; - -#define IOCTL_KGSL_CFF_SYNCMEM \ - _IOW(KGSL_IOC_TYPE, 0x30, struct kgsl_cff_syncmem) - -/* - * A timestamp event allows the user space to register an action following an - * expired timestamp. Note IOCTL_KGSL_TIMESTAMP_EVENT has been redefined to - * _IOWR to support fences which need to return a fd for the priv parameter. - */ - -struct kgsl_timestamp_event { - int type; /* Type of event (see list below) */ - unsigned int timestamp; /* Timestamp to trigger event on */ - unsigned int context_id; /* Context for the timestamp */ - void __user *priv; /* Pointer to the event specific blob */ - size_t len; /* Size of the event specific blob */ -}; - -#define IOCTL_KGSL_TIMESTAMP_EVENT_OLD \ - _IOW(KGSL_IOC_TYPE, 0x31, struct kgsl_timestamp_event) - -/* A genlock timestamp event releases an existing lock on timestamp expire */ - -#define KGSL_TIMESTAMP_EVENT_GENLOCK 1 - -struct kgsl_timestamp_event_genlock { - int handle; /* Handle of the genlock lock to release */ -}; - -/* A fence timestamp event releases an existing lock on timestamp expire */ - -#define KGSL_TIMESTAMP_EVENT_FENCE 2 - -struct kgsl_timestamp_event_fence { - int fence_fd; /* Fence to signal */ -}; - -/* - * Set a property within the kernel. Uses the same structure as - * IOCTL_KGSL_GETPROPERTY - */ - -#define IOCTL_KGSL_SETPROPERTY \ - _IOW(KGSL_IOC_TYPE, 0x32, struct kgsl_device_getproperty) - -#define IOCTL_KGSL_TIMESTAMP_EVENT \ - _IOWR(KGSL_IOC_TYPE, 0x33, struct kgsl_timestamp_event) - -/** - * struct kgsl_gpumem_alloc_id - argument to IOCTL_KGSL_GPUMEM_ALLOC_ID - * @id: returned id value for this allocation. - * @flags: mask of KGSL_MEM* values requested and actual flags on return. - * @size: requested size of the allocation and actual size on return. - * @mmapsize: returned size to pass to mmap() which may be larger than 'size' - * @gpuaddr: returned GPU address for the allocation - * - * Allocate memory for access by the GPU. The flags and size fields are echoed - * back by the kernel, so that the caller can know if the request was - * adjusted. - * - * Supported flags: - * KGSL_MEMFLAGS_GPUREADONLY: the GPU will be unable to write to the buffer - * KGSL_MEMTYPE*: usage hint for debugging aid - * KGSL_MEMALIGN*: alignment hint, may be ignored or adjusted by the kernel. - * KGSL_MEMFLAGS_USE_CPU_MAP: If set on call and return, the returned GPU - * address will be 0. Calling mmap() will set the GPU address. - */ -struct kgsl_gpumem_alloc_id { - unsigned int id; - unsigned int flags; - size_t size; - size_t mmapsize; - unsigned long gpuaddr; -/* private: reserved for future use*/ - unsigned long __pad[2]; -}; - -#define IOCTL_KGSL_GPUMEM_ALLOC_ID \ - _IOWR(KGSL_IOC_TYPE, 0x34, struct kgsl_gpumem_alloc_id) - -/** - * struct kgsl_gpumem_free_id - argument to IOCTL_KGSL_GPUMEM_FREE_ID - * @id: GPU allocation id to free - * - * Free an allocation by id, in case a GPU address has not been assigned or - * is unknown. Freeing an allocation by id with this ioctl or by GPU address - * with IOCTL_KGSL_SHAREDMEM_FREE are equivalent. - */ -struct kgsl_gpumem_free_id { - unsigned int id; -/* private: reserved for future use*/ - unsigned int __pad; -}; - -#define IOCTL_KGSL_GPUMEM_FREE_ID \ - _IOWR(KGSL_IOC_TYPE, 0x35, struct kgsl_gpumem_free_id) - -/** - * struct kgsl_gpumem_get_info - argument to IOCTL_KGSL_GPUMEM_GET_INFO - * @gpuaddr: GPU address to query. Also set on return. - * @id: GPU allocation id to query. Also set on return. - * @flags: returned mask of KGSL_MEM* values. - * @size: returned size of the allocation. - * @mmapsize: returned size to pass mmap(), which may be larger than 'size' - * @useraddr: returned address of the userspace mapping for this buffer - * - * This ioctl allows querying of all user visible attributes of an existing - * allocation, by either the GPU address or the id returned by a previous - * call to IOCTL_KGSL_GPUMEM_ALLOC_ID. Legacy allocation ioctls may not - * return all attributes so this ioctl can be used to look them up if needed. - * - */ -struct kgsl_gpumem_get_info { - unsigned long gpuaddr; - unsigned int id; - unsigned int flags; - size_t size; - size_t mmapsize; - unsigned long useraddr; -/* private: reserved for future use*/ - unsigned long __pad[4]; -}; - -#define IOCTL_KGSL_GPUMEM_GET_INFO\ - _IOWR(KGSL_IOC_TYPE, 0x36, struct kgsl_gpumem_get_info) - -/** - * struct kgsl_gpumem_sync_cache - argument to IOCTL_KGSL_GPUMEM_SYNC_CACHE - * @gpuaddr: GPU address of the buffer to sync. - * @id: id of the buffer to sync. Either gpuaddr or id is sufficient. - * @op: a mask of KGSL_GPUMEM_CACHE_* values - * @offset: offset into the buffer - * @length: number of bytes starting from offset to perform - * the cache operation on - * - * Sync the L2 cache for memory headed to and from the GPU - this replaces - * KGSL_SHAREDMEM_FLUSH_CACHE since it can handle cache management for both - * directions - * - */ -struct kgsl_gpumem_sync_cache { - unsigned long gpuaddr; - unsigned int id; - unsigned int op; - size_t offset; - size_t length; -}; - -#define KGSL_GPUMEM_CACHE_CLEAN (1 << 0) -#define KGSL_GPUMEM_CACHE_TO_GPU KGSL_GPUMEM_CACHE_CLEAN - -#define KGSL_GPUMEM_CACHE_INV (1 << 1) -#define KGSL_GPUMEM_CACHE_FROM_GPU KGSL_GPUMEM_CACHE_INV - -#define KGSL_GPUMEM_CACHE_FLUSH \ - (KGSL_GPUMEM_CACHE_CLEAN | KGSL_GPUMEM_CACHE_INV) - -/* Flag to ensure backwards compatibility of kgsl_gpumem_sync_cache struct */ -#define KGSL_GPUMEM_CACHE_RANGE (1 << 31U) - -#define IOCTL_KGSL_GPUMEM_SYNC_CACHE \ - _IOW(KGSL_IOC_TYPE, 0x37, struct kgsl_gpumem_sync_cache) - -/** - * struct kgsl_perfcounter_get - argument to IOCTL_KGSL_PERFCOUNTER_GET - * @groupid: Performance counter group ID - * @countable: Countable to select within the group - * @offset: Return offset of the reserved LO counter - * @offset_hi: Return offset of the reserved HI counter - * - * Get an available performance counter from a specified groupid. The offset - * of the performance counter will be returned after successfully assigning - * the countable to the counter for the specified group. An error will be - * returned and an offset of 0 if the groupid is invalid or there are no - * more counters left. After successfully getting a perfcounter, the user - * must call kgsl_perfcounter_put(groupid, contable) when finished with - * the perfcounter to clear up perfcounter resources. - * - */ -struct kgsl_perfcounter_get { - unsigned int groupid; - unsigned int countable; - unsigned int offset; - unsigned int offset_hi; -/* private: reserved for future use */ - unsigned int __pad; /* For future binary compatibility */ -}; - -#define IOCTL_KGSL_PERFCOUNTER_GET \ - _IOWR(KGSL_IOC_TYPE, 0x38, struct kgsl_perfcounter_get) - -/** - * struct kgsl_perfcounter_put - argument to IOCTL_KGSL_PERFCOUNTER_PUT - * @groupid: Performance counter group ID - * @countable: Countable to release within the group - * - * Put an allocated performance counter to allow others to have access to the - * resource that was previously taken. This is only to be called after - * successfully getting a performance counter from kgsl_perfcounter_get(). - * - */ -struct kgsl_perfcounter_put { - unsigned int groupid; - unsigned int countable; -/* private: reserved for future use */ - unsigned int __pad[2]; /* For future binary compatibility */ -}; - -#define IOCTL_KGSL_PERFCOUNTER_PUT \ - _IOW(KGSL_IOC_TYPE, 0x39, struct kgsl_perfcounter_put) - -/** - * struct kgsl_perfcounter_query - argument to IOCTL_KGSL_PERFCOUNTER_QUERY - * @groupid: Performance counter group ID - * @countable: Return active countables array - * @size: Size of active countables array - * @max_counters: Return total number counters for the group ID - * - * Query the available performance counters given a groupid. The array - * *countables is used to return the current active countables in counters. - * The size of the array is passed in so the kernel will only write at most - * size or counter->size for the group id. The total number of available - * counters for the group ID is returned in max_counters. - * If the array or size passed in are invalid, then only the maximum number - * of counters will be returned, no data will be written to *countables. - * If the groupid is invalid an error code will be returned. - * - */ -struct kgsl_perfcounter_query { - unsigned int groupid; - /* Array to return the current countable for up to size counters */ - unsigned int __user *countables; - unsigned int count; - unsigned int max_counters; -/* private: reserved for future use */ - unsigned int __pad[2]; /* For future binary compatibility */ -}; - -#define IOCTL_KGSL_PERFCOUNTER_QUERY \ - _IOWR(KGSL_IOC_TYPE, 0x3A, struct kgsl_perfcounter_query) - -/** - * struct kgsl_perfcounter_query - argument to IOCTL_KGSL_PERFCOUNTER_QUERY - * @groupid: Performance counter group IDs - * @countable: Performance counter countable IDs - * @value: Return performance counter reads - * @size: Size of all arrays (groupid/countable pair and return value) - * - * Read in the current value of a performance counter given by the groupid - * and countable. - * - */ - -struct kgsl_perfcounter_read_group { - unsigned int groupid; - unsigned int countable; - unsigned long long value; -}; - -struct kgsl_perfcounter_read { - struct kgsl_perfcounter_read_group __user *reads; - unsigned int count; -/* private: reserved for future use */ - unsigned int __pad[2]; /* For future binary compatibility */ -}; - -#define IOCTL_KGSL_PERFCOUNTER_READ \ - _IOWR(KGSL_IOC_TYPE, 0x3B, struct kgsl_perfcounter_read) -/* - * struct kgsl_gpumem_sync_cache_bulk - argument to - * IOCTL_KGSL_GPUMEM_SYNC_CACHE_BULK - * @id_list: list of GPU buffer ids of the buffers to sync - * @count: number of GPU buffer ids in id_list - * @op: a mask of KGSL_GPUMEM_CACHE_* values - * - * Sync the cache for memory headed to and from the GPU. Certain - * optimizations can be made on the cache operation based on the total - * size of the working set of memory to be managed. - */ -struct kgsl_gpumem_sync_cache_bulk { - unsigned int __user *id_list; - unsigned int count; - unsigned int op; -/* private: reserved for future use */ - unsigned int __pad[2]; /* For future binary compatibility */ -}; - -#define IOCTL_KGSL_GPUMEM_SYNC_CACHE_BULK \ - _IOWR(KGSL_IOC_TYPE, 0x3C, struct kgsl_gpumem_sync_cache_bulk) - -/* - * struct kgsl_cmd_syncpoint_timestamp - * @context_id: ID of a KGSL context - * @timestamp: GPU timestamp - * - * This structure defines a syncpoint comprising a context/timestamp pair. A - * list of these may be passed by IOCTL_KGSL_SUBMIT_COMMANDS to define - * dependencies that must be met before the command can be submitted to the - * hardware - */ -struct kgsl_cmd_syncpoint_timestamp { - unsigned int context_id; - unsigned int timestamp; -}; - -struct kgsl_cmd_syncpoint_fence { - int fd; -}; - -/** - * struct kgsl_cmd_syncpoint - Define a sync point for a command batch - * @type: type of sync point defined here - * @priv: Pointer to the type specific buffer - * @size: Size of the type specific buffer - * - * This structure contains pointers defining a specific command sync point. - * The pointer and size should point to a type appropriate structure. - */ -struct kgsl_cmd_syncpoint { - int type; - void __user *priv; - size_t size; -}; - -/* Flag to indicate that the cmdlist may contain memlists */ -#define KGSL_IBDESC_MEMLIST 0x1 - -/* Flag to point out the cmdbatch profiling buffer in the memlist */ -#define KGSL_IBDESC_PROFILING_BUFFER 0x2 - -/** - * struct kgsl_submit_commands - Argument to IOCTL_KGSL_SUBMIT_COMMANDS - * @context_id: KGSL context ID that owns the commands - * @flags: - * @cmdlist: User pointer to a list of kgsl_ibdesc structures - * @numcmds: Number of commands listed in cmdlist - * @synclist: User pointer to a list of kgsl_cmd_syncpoint structures - * @numsyncs: Number of sync points listed in synclist - * @timestamp: On entry the a user defined timestamp, on exist the timestamp - * assigned to the command batch - * - * This structure specifies a command to send to the GPU hardware. This is - * similar to kgsl_issueibcmds expect that it doesn't support the legacy way to - * submit IB lists and it adds sync points to block the IB until the - * dependencies are satisified. This entry point is the new and preferred way - * to submit commands to the GPU. The memory list can be used to specify all - * memory that is referrenced in the current set of commands. - */ - -struct kgsl_submit_commands { - unsigned int context_id; - unsigned int flags; - struct kgsl_ibdesc __user *cmdlist; - unsigned int numcmds; - struct kgsl_cmd_syncpoint __user *synclist; - unsigned int numsyncs; - unsigned int timestamp; -/* private: reserved for future use */ - unsigned int __pad[4]; -}; - -#define IOCTL_KGSL_SUBMIT_COMMANDS \ - _IOWR(KGSL_IOC_TYPE, 0x3D, struct kgsl_submit_commands) - -/** - * struct kgsl_device_constraint - device constraint argument - * @context_id: KGSL context ID - * @type: type of constraint i.e pwrlevel/none - * @data: constraint data - * @size: size of the constraint data - */ -struct kgsl_device_constraint { - unsigned int type; - unsigned int context_id; - void __user *data; - size_t size; -}; - -/* Constraint Type*/ -#define KGSL_CONSTRAINT_NONE 0 -#define KGSL_CONSTRAINT_PWRLEVEL 1 - -/* PWRLEVEL constraint level*/ -/* set to min frequency */ -#define KGSL_CONSTRAINT_PWR_MIN 0 -/* set to max frequency */ -#define KGSL_CONSTRAINT_PWR_MAX 1 - -struct kgsl_device_constraint_pwrlevel { - unsigned int level; -}; - -/** - * struct kgsl_syncsource_create - Argument to IOCTL_KGSL_SYNCSOURCE_CREATE - * @id: returned id for the syncsource that was created. - * - * This ioctl creates a userspace sync timeline. - */ - -struct kgsl_syncsource_create { - unsigned int id; -/* private: reserved for future use */ - unsigned int __pad[3]; -}; - -#define IOCTL_KGSL_SYNCSOURCE_CREATE \ - _IOWR(KGSL_IOC_TYPE, 0x40, struct kgsl_syncsource_create) - -/** - * struct kgsl_syncsource_destroy - Argument to IOCTL_KGSL_SYNCSOURCE_DESTROY - * @id: syncsource id to destroy - * - * This ioctl creates a userspace sync timeline. - */ - -struct kgsl_syncsource_destroy { - unsigned int id; -/* private: reserved for future use */ - unsigned int __pad[3]; -}; - -#define IOCTL_KGSL_SYNCSOURCE_DESTROY \ - _IOWR(KGSL_IOC_TYPE, 0x41, struct kgsl_syncsource_destroy) - -/** - * struct kgsl_syncsource_create_fence - Argument to - * IOCTL_KGSL_SYNCSOURCE_CREATE_FENCE - * @id: syncsource id - * @fence_fd: returned sync_fence fd - * - * Create a fence that may be signaled by userspace by calling - * IOCTL_KGSL_SYNCSOURCE_SIGNAL_FENCE. There are no order dependencies between - * these fences. - */ -struct kgsl_syncsource_create_fence { - unsigned int id; - int fence_fd; -/* private: reserved for future use */ - unsigned int __pad[4]; -}; - -/** - * struct kgsl_syncsource_signal_fence - Argument to - * IOCTL_KGSL_SYNCSOURCE_SIGNAL_FENCE - * @id: syncsource id - * @fence_fd: sync_fence fd to signal - * - * Signal a fence that was created by a IOCTL_KGSL_SYNCSOURCE_CREATE_FENCE - * call using the same syncsource id. This allows a fence to be shared - * to other processes but only signaled by the process owning the fd - * used to create the fence. - */ -#define IOCTL_KGSL_SYNCSOURCE_CREATE_FENCE \ - _IOWR(KGSL_IOC_TYPE, 0x42, struct kgsl_syncsource_create_fence) - -struct kgsl_syncsource_signal_fence { - unsigned int id; - int fence_fd; -/* private: reserved for future use */ - unsigned int __pad[4]; -}; - -#define IOCTL_KGSL_SYNCSOURCE_SIGNAL_FENCE \ - _IOWR(KGSL_IOC_TYPE, 0x43, struct kgsl_syncsource_signal_fence) - -/** - * struct kgsl_cff_sync_gpuobj - Argument to IOCTL_KGSL_CFF_SYNC_GPUOBJ - * @offset: Offset into the GPU object to sync - * @length: Number of bytes to sync - * @id: ID of the GPU object to sync - */ -struct kgsl_cff_sync_gpuobj { - uint64_t offset; - uint64_t length; - unsigned int id; -}; - -#define IOCTL_KGSL_CFF_SYNC_GPUOBJ \ - _IOW(KGSL_IOC_TYPE, 0x44, struct kgsl_cff_sync_gpuobj) - -/** - * struct kgsl_gpuobj_alloc - Argument to IOCTL_KGSL_GPUOBJ_ALLOC - * @size: Size in bytes of the object to allocate - * @flags: mask of KGSL_MEMFLAG_* bits - * @va_len: Size in bytes of the virtual region to allocate - * @mmapsize: Returns the mmap() size of the object - * @id: Returns the GPU object ID of the new object - * @metadata_len: Length of the metdata to copy from the user - * @metadata: Pointer to the user specified metadata to store for the object - */ -struct kgsl_gpuobj_alloc { - uint64_t size; - uint64_t flags; - uint64_t va_len; - uint64_t mmapsize; - unsigned int id; - unsigned int metadata_len; - uint64_t metadata; -}; - -/* Let the user know that this header supports the gpuobj metadata */ -#define KGSL_GPUOBJ_ALLOC_METADATA_MAX 64 - -#define IOCTL_KGSL_GPUOBJ_ALLOC \ - _IOWR(KGSL_IOC_TYPE, 0x45, struct kgsl_gpuobj_alloc) - -/** - * struct kgsl_gpuobj_free - Argument to IOCTL_KGLS_GPUOBJ_FREE - * @flags: Mask of: KGSL_GUPOBJ_FREE_ON_EVENT - * @priv: Pointer to the private object if KGSL_GPUOBJ_FREE_ON_EVENT is - * specified - * @id: ID of the GPU object to free - * @type: If KGSL_GPUOBJ_FREE_ON_EVENT is specified, the type of asynchronous - * event to free on - * @len: Length of the data passed in priv - */ -struct kgsl_gpuobj_free { - uint64_t flags; - uint64_t __user priv; - unsigned int id; - unsigned int type; - unsigned int len; -}; - -#define KGSL_GPUOBJ_FREE_ON_EVENT 1 - -#define KGSL_GPU_EVENT_TIMESTAMP 1 -#define KGSL_GPU_EVENT_FENCE 2 - -/** - * struct kgsl_gpu_event_timestamp - Specifies a timestamp event to free a GPU - * object on - * @context_id: ID of the timestamp event to wait for - * @timestamp: Timestamp of the timestamp event to wait for - */ -struct kgsl_gpu_event_timestamp { - unsigned int context_id; - unsigned int timestamp; -}; - -/** - * struct kgsl_gpu_event_fence - Specifies a fence ID to to free a GPU object on - * @fd: File descriptor for the fence - */ -struct kgsl_gpu_event_fence { - int fd; -}; - -#define IOCTL_KGSL_GPUOBJ_FREE \ - _IOW(KGSL_IOC_TYPE, 0x46, struct kgsl_gpuobj_free) - -/** - * struct kgsl_gpuobj_info - argument to IOCTL_KGSL_GPUOBJ_INFO - * @gpuaddr: GPU address of the object - * @flags: Current flags for the object - * @size: Size of the object - * @va_len: VA size of the object - * @va_addr: Virtual address of the object (if it is mapped) - * id - GPU object ID of the object to query - */ -struct kgsl_gpuobj_info { - uint64_t gpuaddr; - uint64_t flags; - uint64_t size; - uint64_t va_len; - uint64_t va_addr; - unsigned int id; -}; - -#define IOCTL_KGSL_GPUOBJ_INFO \ - _IOWR(KGSL_IOC_TYPE, 0x47, struct kgsl_gpuobj_info) - -/** - * struct kgsl_gpuobj_import - argument to IOCTL_KGSL_GPUOBJ_IMPORT - * @priv: Pointer to the private data for the import type - * @priv_len: Length of the private data - * @flags: Mask of KGSL_MEMFLAG_ flags - * @type: Type of the import (KGSL_USER_MEM_TYPE_*) - * @id: Returns the ID of the new GPU object - */ -struct kgsl_gpuobj_import { - uint64_t __user priv; - uint64_t priv_len; - uint64_t flags; - unsigned int type; - unsigned int id; -}; - -/** - * struct kgsl_gpuobj_import_dma_buf - import a dmabuf object - * @fd: File descriptor for the dma-buf object - */ -struct kgsl_gpuobj_import_dma_buf { - int fd; -}; - -/** - * struct kgsl_gpuobj_import_useraddr - import an object based on a useraddr - * @virtaddr: Virtual address of the object to import - */ -struct kgsl_gpuobj_import_useraddr { - uint64_t virtaddr; -}; - -#define IOCTL_KGSL_GPUOBJ_IMPORT \ - _IOWR(KGSL_IOC_TYPE, 0x48, struct kgsl_gpuobj_import) - -/** - * struct kgsl_gpuobj_sync_obj - Individual GPU object to sync - * @offset: Offset within the GPU object to sync - * @length: Number of bytes to sync - * @id: ID of the GPU object to sync - * @op: Cache operation to execute - */ - -struct kgsl_gpuobj_sync_obj { - uint64_t offset; - uint64_t length; - unsigned int id; - unsigned int op; -}; - -/** - * struct kgsl_gpuobj_sync - Argument for IOCTL_KGSL_GPUOBJ_SYNC - * @objs: Pointer to an array of kgsl_gpuobj_sync_obj structs - * @obj_len: Size of each item in the array - * @count: Number of items in the array - */ - -struct kgsl_gpuobj_sync { - uint64_t __user objs; - unsigned int obj_len; - unsigned int count; -}; - -#define IOCTL_KGSL_GPUOBJ_SYNC \ - _IOW(KGSL_IOC_TYPE, 0x49, struct kgsl_gpuobj_sync) - -/** - * struct kgsl_command_object - GPU command object - * @offset: GPU address offset of the object - * @gpuaddr: GPU address of the object - * @size: Size of the object - * @flags: Current flags for the object - * @id - GPU command object ID - */ -struct kgsl_command_object { - uint64_t offset; - uint64_t gpuaddr; - uint64_t size; - unsigned int flags; - unsigned int id; -}; - -/** - * struct kgsl_command_syncpoint - GPU syncpoint object - * @priv: Pointer to the type specific buffer - * @size: Size of the type specific buffer - * @type: type of sync point defined here - */ -struct kgsl_command_syncpoint { - uint64_t __user priv; - uint64_t size; - unsigned int type; -}; - -/** - * struct kgsl_command_object - Argument for IOCTL_KGSL_GPU_COMMAND - * @flags: Current flags for the object - * @cmdlist: List of kgsl_command_objects for submission - * @cmd_size: Size of kgsl_command_objects structure - * @numcmds: Number of kgsl_command_objects in command list - * @objlist: List of kgsl_command_objects for tracking - * @obj_size: Size of kgsl_command_objects structure - * @numobjs: Number of kgsl_command_objects in object list - * @synclist: List of kgsl_command_syncpoints - * @sync_size: Size of kgsl_command_syncpoint structure - * @numsyncs: Number of kgsl_command_syncpoints in syncpoint list - * @context_id: Context ID submittin ghte kgsl_gpu_command - * @timestamp: Timestamp for the submitted commands - */ -struct kgsl_gpu_command { - uint64_t flags; - uint64_t __user cmdlist; - unsigned int cmdsize; - unsigned int numcmds; - uint64_t __user objlist; - unsigned int objsize; - unsigned int numobjs; - uint64_t __user synclist; - unsigned int syncsize; - unsigned int numsyncs; - unsigned int context_id; - unsigned int timestamp; -}; - -#define IOCTL_KGSL_GPU_COMMAND \ - _IOWR(KGSL_IOC_TYPE, 0x4A, struct kgsl_gpu_command) - -/** - * struct kgsl_preemption_counters_query - argument to - * IOCTL_KGSL_PREEMPTIONCOUNTER_QUERY - * @counters: Return preemption counters array - * @size_user: Size allocated by userspace - * @size_priority_level: Size of preemption counters for each - * priority level - * @max_priority_level: Return max number of priority levels - * - * Query the available preemption counters. The array counters - * is used to return preemption counters. The size of the array - * is passed in so the kernel will only write at most size_user - * or max available preemption counters. The total number of - * preemption counters is returned in max_priority_level. If the - * array or size passed in are invalid, then an error is - * returned back. - */ -struct kgsl_preemption_counters_query { - uint64_t __user counters; - unsigned int size_user; - unsigned int size_priority_level; - unsigned int max_priority_level; -}; - -#define IOCTL_KGSL_PREEMPTIONCOUNTER_QUERY \ - _IOWR(KGSL_IOC_TYPE, 0x4B, struct kgsl_preemption_counters_query) - -/** - * struct kgsl_gpuobj_set_info - argument for IOCTL_KGSL_GPUOBJ_SET_INFO - * @flags: Flags to indicate which paramaters to change - * @metadata: If KGSL_GPUOBJ_SET_INFO_METADATA is set, a pointer to the new - * metadata - * @id: GPU memory object ID to change - * @metadata_len: If KGSL_GPUOBJ_SET_INFO_METADATA is set, the length of the - * new metadata string - * @type: If KGSL_GPUOBJ_SET_INFO_TYPE is set, the new type of the memory object - */ - -#define KGSL_GPUOBJ_SET_INFO_METADATA (1 << 0) -#define KGSL_GPUOBJ_SET_INFO_TYPE (1 << 1) - -struct kgsl_gpuobj_set_info { - uint64_t flags; - uint64_t metadata; - unsigned int id; - unsigned int metadata_len; - unsigned int type; -}; - -#define IOCTL_KGSL_GPUOBJ_SET_INFO \ - _IOW(KGSL_IOC_TYPE, 0x4C, struct kgsl_gpuobj_set_info) - -#endif /* _UAPI_MSM_KGSL_H */ diff --git a/third_party/linux/include/msm_media_info.h b/third_party/linux/include/msm_media_info.h deleted file mode 100644 index 39dceb2c49..0000000000 --- a/third_party/linux/include/msm_media_info.h +++ /dev/null @@ -1,819 +0,0 @@ -#ifndef __MEDIA_INFO_H__ -#define __MEDIA_INFO_H__ - -#ifndef MSM_MEDIA_ALIGN -#define MSM_MEDIA_ALIGN(__sz, __align) (((__sz) + (__align-1)) & (~(__align-1))) -#endif - -#ifndef MSM_MEDIA_ROUNDUP -#define MSM_MEDIA_ROUNDUP(__sz, __r) (((__sz) + ((__r) - 1)) / (__r)) -#endif - -#ifndef MSM_MEDIA_MAX -#define MSM_MEDIA_MAX(__a, __b) ((__a) > (__b)?(__a):(__b)) -#endif - -enum color_fmts { - /* Venus NV12: - * YUV 4:2:0 image with a plane of 8 bit Y samples followed - * by an interleaved U/V plane containing 8 bit 2x2 subsampled - * colour difference samples. - * - * <-------- Y/UV_Stride --------> - * <------- Width -------> - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . ^ ^ - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . Height | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | Y_Scanlines - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . V | - * . . . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . . . V - * U V U V U V U V U V U V . . . . ^ - * U V U V U V U V U V U V . . . . | - * U V U V U V U V U V U V . . . . | - * U V U V U V U V U V U V . . . . UV_Scanlines - * . . . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . . . V - * . . . . . . . . . . . . . . . . --> Buffer size alignment - * - * Y_Stride : Width aligned to 128 - * UV_Stride : Width aligned to 128 - * Y_Scanlines: Height aligned to 32 - * UV_Scanlines: Height/2 aligned to 16 - * Extradata: Arbitrary (software-imposed) padding - * Total size = align((Y_Stride * Y_Scanlines - * + UV_Stride * UV_Scanlines - * + max(Extradata, Y_Stride * 8), 4096) - */ - COLOR_FMT_NV12, - - /* Venus NV21: - * YUV 4:2:0 image with a plane of 8 bit Y samples followed - * by an interleaved V/U plane containing 8 bit 2x2 subsampled - * colour difference samples. - * - * <-------- Y/UV_Stride --------> - * <------- Width -------> - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . ^ ^ - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . Height | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | Y_Scanlines - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . V | - * . . . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . . . V - * V U V U V U V U V U V U . . . . ^ - * V U V U V U V U V U V U . . . . | - * V U V U V U V U V U V U . . . . | - * V U V U V U V U V U V U . . . . UV_Scanlines - * . . . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . . . V - * . . . . . . . . . . . . . . . . --> Padding & Buffer size alignment - * - * Y_Stride : Width aligned to 128 - * UV_Stride : Width aligned to 128 - * Y_Scanlines: Height aligned to 32 - * UV_Scanlines: Height/2 aligned to 16 - * Extradata: Arbitrary (software-imposed) padding - * Total size = align((Y_Stride * Y_Scanlines - * + UV_Stride * UV_Scanlines - * + max(Extradata, Y_Stride * 8), 4096) - */ - COLOR_FMT_NV21, - /* Venus NV12_MVTB: - * Two YUV 4:2:0 images/views one after the other - * in a top-bottom layout, same as NV12 - * with a plane of 8 bit Y samples followed - * by an interleaved U/V plane containing 8 bit 2x2 subsampled - * colour difference samples. - * - * - * <-------- Y/UV_Stride --------> - * <------- Width -------> - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . ^ ^ ^ - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . Height | | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | Y_Scanlines | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . V | | - * . . . . . . . . . . . . . . . . | View_1 - * . . . . . . . . . . . . . . . . | | - * . . . . . . . . . . . . . . . . | | - * . . . . . . . . . . . . . . . . V | - * U V U V U V U V U V U V . . . . ^ | - * U V U V U V U V U V U V . . . . | | - * U V U V U V U V U V U V . . . . | | - * U V U V U V U V U V U V . . . . UV_Scanlines | - * . . . . . . . . . . . . . . . . | | - * . . . . . . . . . . . . . . . . V V - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . ^ ^ ^ - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . Height | | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | Y_Scanlines | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . | | | - * Y Y Y Y Y Y Y Y Y Y Y Y . . . . V | | - * . . . . . . . . . . . . . . . . | View_2 - * . . . . . . . . . . . . . . . . | | - * . . . . . . . . . . . . . . . . | | - * . . . . . . . . . . . . . . . . V | - * U V U V U V U V U V U V . . . . ^ | - * U V U V U V U V U V U V . . . . | | - * U V U V U V U V U V U V . . . . | | - * U V U V U V U V U V U V . . . . UV_Scanlines | - * . . . . . . . . . . . . . . . . | | - * . . . . . . . . . . . . . . . . V V - * . . . . . . . . . . . . . . . . --> Buffer size alignment - * - * Y_Stride : Width aligned to 128 - * UV_Stride : Width aligned to 128 - * Y_Scanlines: Height aligned to 32 - * UV_Scanlines: Height/2 aligned to 16 - * View_1 begin at: 0 (zero) - * View_2 begin at: Y_Stride * Y_Scanlines + UV_Stride * UV_Scanlines - * Extradata: Arbitrary (software-imposed) padding - * Total size = align((2*(Y_Stride * Y_Scanlines) - * + 2*(UV_Stride * UV_Scanlines) + Extradata), 4096) - */ - COLOR_FMT_NV12_MVTB, - /* Venus NV12 UBWC: - * Compressed Macro-tile format for NV12. - * Contains 4 planes in the following order - - * (A) Y_Meta_Plane - * (B) Y_UBWC_Plane - * (C) UV_Meta_Plane - * (D) UV_UBWC_Plane - * - * Y_Meta_Plane consists of meta information to decode compressed - * tile data in Y_UBWC_Plane. - * Y_UBWC_Plane consists of Y data in compressed macro-tile format. - * UBWC decoder block will use the Y_Meta_Plane data together with - * Y_UBWC_Plane data to produce loss-less uncompressed 8 bit Y samples. - * - * UV_Meta_Plane consists of meta information to decode compressed - * tile data in UV_UBWC_Plane. - * UV_UBWC_Plane consists of UV data in compressed macro-tile format. - * UBWC decoder block will use UV_Meta_Plane data together with - * UV_UBWC_Plane data to produce loss-less uncompressed 8 bit 2x2 - * subsampled color difference samples. - * - * Each tile in Y_UBWC_Plane/UV_UBWC_Plane is independently decodable - * and randomly accessible. There is no dependency between tiles. - * - * <----- Y_Meta_Stride ----> - * <-------- Width ------> - * M M M M M M M M M M M M . . ^ ^ - * M M M M M M M M M M M M . . | | - * M M M M M M M M M M M M . . Height | - * M M M M M M M M M M M M . . | Meta_Y_Scanlines - * M M M M M M M M M M M M . . | | - * M M M M M M M M M M M M . . | | - * M M M M M M M M M M M M . . | | - * M M M M M M M M M M M M . . V | - * . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . -------> Buffer size aligned to 4k - * . . . . . . . . . . . . . . V - * <--Compressed tile Y Stride---> - * <------- Width -------> - * Y* Y* Y* Y* Y* Y* Y* Y* . . . . ^ ^ - * Y* Y* Y* Y* Y* Y* Y* Y* . . . . | | - * Y* Y* Y* Y* Y* Y* Y* Y* . . . . Height | - * Y* Y* Y* Y* Y* Y* Y* Y* . . . . | Macro_tile_Y_Scanlines - * Y* Y* Y* Y* Y* Y* Y* Y* . . . . | | - * Y* Y* Y* Y* Y* Y* Y* Y* . . . . | | - * Y* Y* Y* Y* Y* Y* Y* Y* . . . . | | - * Y* Y* Y* Y* Y* Y* Y* Y* . . . . V | - * . . . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . . . -------> Buffer size aligned to 4k - * . . . . . . . . . . . . . . . . V - * <----- UV_Meta_Stride ----> - * M M M M M M M M M M M M . . ^ - * M M M M M M M M M M M M . . | - * M M M M M M M M M M M M . . | - * M M M M M M M M M M M M . . M_UV_Scanlines - * . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . V - * . . . . . . . . . . . . . . -------> Buffer size aligned to 4k - * <--Compressed tile UV Stride---> - * U* V* U* V* U* V* U* V* . . . . ^ - * U* V* U* V* U* V* U* V* . . . . | - * U* V* U* V* U* V* U* V* . . . . | - * U* V* U* V* U* V* U* V* . . . . UV_Scanlines - * . . . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . . . V - * . . . . . . . . . . . . . . . . -------> Buffer size aligned to 4k - * - * Y_Stride = align(Width, 128) - * UV_Stride = align(Width, 128) - * Y_Scanlines = align(Height, 32) - * UV_Scanlines = align(Height/2, 16) - * Y_UBWC_Plane_size = align(Y_Stride * Y_Scanlines, 4096) - * UV_UBWC_Plane_size = align(UV_Stride * UV_Scanlines, 4096) - * Y_Meta_Stride = align(roundup(Width, Y_TileWidth), 64) - * Y_Meta_Scanlines = align(roundup(Height, Y_TileHeight), 16) - * Y_Meta_Plane_size = align(Y_Meta_Stride * Y_Meta_Scanlines, 4096) - * UV_Meta_Stride = align(roundup(Width, UV_TileWidth), 64) - * UV_Meta_Scanlines = align(roundup(Height, UV_TileHeight), 16) - * UV_Meta_Plane_size = align(UV_Meta_Stride * UV_Meta_Scanlines, 4096) - * Extradata = 8k - * - * Total size = align( Y_UBWC_Plane_size + UV_UBWC_Plane_size + - * Y_Meta_Plane_size + UV_Meta_Plane_size - * + max(Extradata, Y_Stride * 48), 4096) - */ - COLOR_FMT_NV12_UBWC, - /* Venus NV12 10-bit UBWC: - * Compressed Macro-tile format for NV12. - * Contains 4 planes in the following order - - * (A) Y_Meta_Plane - * (B) Y_UBWC_Plane - * (C) UV_Meta_Plane - * (D) UV_UBWC_Plane - * - * Y_Meta_Plane consists of meta information to decode compressed - * tile data in Y_UBWC_Plane. - * Y_UBWC_Plane consists of Y data in compressed macro-tile format. - * UBWC decoder block will use the Y_Meta_Plane data together with - * Y_UBWC_Plane data to produce loss-less uncompressed 10 bit Y samples. - * - * UV_Meta_Plane consists of meta information to decode compressed - * tile data in UV_UBWC_Plane. - * UV_UBWC_Plane consists of UV data in compressed macro-tile format. - * UBWC decoder block will use UV_Meta_Plane data together with - * UV_UBWC_Plane data to produce loss-less uncompressed 10 bit 2x2 - * subsampled color difference samples. - * - * Each tile in Y_UBWC_Plane/UV_UBWC_Plane is independently decodable - * and randomly accessible. There is no dependency between tiles. - * - * <----- Y_Meta_Stride -----> - * <-------- Width ------> - * M M M M M M M M M M M M . . ^ ^ - * M M M M M M M M M M M M . . | | - * M M M M M M M M M M M M . . Height | - * M M M M M M M M M M M M . . | Meta_Y_Scanlines - * M M M M M M M M M M M M . . | | - * M M M M M M M M M M M M . . | | - * M M M M M M M M M M M M . . | | - * M M M M M M M M M M M M . . V | - * . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . -------> Buffer size aligned to 4k - * . . . . . . . . . . . . . . V - * <--Compressed tile Y Stride---> - * <------- Width -------> - * Y* Y* Y* Y* Y* Y* Y* Y* . . . . ^ ^ - * Y* Y* Y* Y* Y* Y* Y* Y* . . . . | | - * Y* Y* Y* Y* Y* Y* Y* Y* . . . . Height | - * Y* Y* Y* Y* Y* Y* Y* Y* . . . . | Macro_tile_Y_Scanlines - * Y* Y* Y* Y* Y* Y* Y* Y* . . . . | | - * Y* Y* Y* Y* Y* Y* Y* Y* . . . . | | - * Y* Y* Y* Y* Y* Y* Y* Y* . . . . | | - * Y* Y* Y* Y* Y* Y* Y* Y* . . . . V | - * . . . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . . . -------> Buffer size aligned to 4k - * . . . . . . . . . . . . . . . . V - * <----- UV_Meta_Stride ----> - * M M M M M M M M M M M M . . ^ - * M M M M M M M M M M M M . . | - * M M M M M M M M M M M M . . | - * M M M M M M M M M M M M . . M_UV_Scanlines - * . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . V - * . . . . . . . . . . . . . . -------> Buffer size aligned to 4k - * <--Compressed tile UV Stride---> - * U* V* U* V* U* V* U* V* . . . . ^ - * U* V* U* V* U* V* U* V* . . . . | - * U* V* U* V* U* V* U* V* . . . . | - * U* V* U* V* U* V* U* V* . . . . UV_Scanlines - * . . . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . . . V - * . . . . . . . . . . . . . . . . -------> Buffer size aligned to 4k - * - * - * Y_Stride = align(Width * 4/3, 128) - * UV_Stride = align(Width * 4/3, 128) - * Y_Scanlines = align(Height, 32) - * UV_Scanlines = align(Height/2, 16) - * Y_UBWC_Plane_Size = align(Y_Stride * Y_Scanlines, 4096) - * UV_UBWC_Plane_Size = align(UV_Stride * UV_Scanlines, 4096) - * Y_Meta_Stride = align(roundup(Width, Y_TileWidth), 64) - * Y_Meta_Scanlines = align(roundup(Height, Y_TileHeight), 16) - * Y_Meta_Plane_size = align(Y_Meta_Stride * Y_Meta_Scanlines, 4096) - * UV_Meta_Stride = align(roundup(Width, UV_TileWidth), 64) - * UV_Meta_Scanlines = align(roundup(Height, UV_TileHeight), 16) - * UV_Meta_Plane_size = align(UV_Meta_Stride * UV_Meta_Scanlines, 4096) - * Extradata = 8k - * - * Total size = align(Y_UBWC_Plane_size + UV_UBWC_Plane_size + - * Y_Meta_Plane_size + UV_Meta_Plane_size - * + max(Extradata, Y_Stride * 48), 4096) - */ - COLOR_FMT_NV12_BPP10_UBWC, - /* Venus RGBA8888 format: - * Contains 1 plane in the following order - - * (A) RGBA plane - * - * <-------- RGB_Stride --------> - * <------- Width -------> - * R R R R R R R R R R R R . . . . ^ ^ - * R R R R R R R R R R R R . . . . | | - * R R R R R R R R R R R R . . . . Height | - * R R R R R R R R R R R R . . . . | RGB_Scanlines - * R R R R R R R R R R R R . . . . | | - * R R R R R R R R R R R R . . . . | | - * R R R R R R R R R R R R . . . . | | - * R R R R R R R R R R R R . . . . V | - * . . . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . . . V - * - * RGB_Stride = align(Width * 4, 128) - * RGB_Scanlines = align(Height, 32) - * RGB_Plane_size = align(RGB_Stride * RGB_Scanlines, 4096) - * Extradata = 8k - * - * Total size = align(RGB_Plane_size + Extradata, 4096) - */ - COLOR_FMT_RGBA8888, - /* Venus RGBA8888 UBWC format: - * Contains 2 planes in the following order - - * (A) Meta plane - * (B) RGBA plane - * - * <--- RGB_Meta_Stride ----> - * <-------- Width ------> - * M M M M M M M M M M M M . . ^ ^ - * M M M M M M M M M M M M . . | | - * M M M M M M M M M M M M . . Height | - * M M M M M M M M M M M M . . | Meta_RGB_Scanlines - * M M M M M M M M M M M M . . | | - * M M M M M M M M M M M M . . | | - * M M M M M M M M M M M M . . | | - * M M M M M M M M M M M M . . V | - * . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . -------> Buffer size aligned to 4k - * . . . . . . . . . . . . . . V - * <-------- RGB_Stride --------> - * <------- Width -------> - * R R R R R R R R R R R R . . . . ^ ^ - * R R R R R R R R R R R R . . . . | | - * R R R R R R R R R R R R . . . . Height | - * R R R R R R R R R R R R . . . . | RGB_Scanlines - * R R R R R R R R R R R R . . . . | | - * R R R R R R R R R R R R . . . . | | - * R R R R R R R R R R R R . . . . | | - * R R R R R R R R R R R R . . . . V | - * . . . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . . . | - * . . . . . . . . . . . . . . . . -------> Buffer size aligned to 4k - * . . . . . . . . . . . . . . . . V - * - * RGB_Stride = align(Width * 4, 128) - * RGB_Scanlines = align(Height, 32) - * RGB_Plane_size = align(RGB_Stride * RGB_Scanlines, 4096) - * RGB_Meta_Stride = align(roundup(Width, RGB_TileWidth), 64) - * RGB_Meta_Scanline = align(roundup(Height, RGB_TileHeight), 16) - * RGB_Meta_Plane_size = align(RGB_Meta_Stride * - * RGB_Meta_Scanlines, 4096) - * Extradata = 8k - * - * Total size = align(RGB_Meta_Plane_size + RGB_Plane_size + - * Extradata, 4096) - */ - COLOR_FMT_RGBA8888_UBWC, -}; - -static inline unsigned int VENUS_EXTRADATA_SIZE(int width, int height) -{ - (void)height; - (void)width; - - /* - * In the future, calculate the size based on the w/h but just - * hardcode it for now since 16K satisfies all current usecases. - */ - return 16 * 1024; -} - -static inline unsigned int VENUS_Y_STRIDE(int color_fmt, int width) -{ - unsigned int alignment, stride = 0; - if (!width) - goto invalid_input; - - switch (color_fmt) { - case COLOR_FMT_NV21: - case COLOR_FMT_NV12: - case COLOR_FMT_NV12_MVTB: - case COLOR_FMT_NV12_UBWC: - alignment = 128; - stride = MSM_MEDIA_ALIGN(width, alignment); - break; - case COLOR_FMT_NV12_BPP10_UBWC: - alignment = 256; - stride = MSM_MEDIA_ALIGN(width, 192); - stride = MSM_MEDIA_ALIGN(stride * 4/3, alignment); - break; - default: - break; - } -invalid_input: - return stride; -} - -static inline unsigned int VENUS_UV_STRIDE(int color_fmt, int width) -{ - unsigned int alignment, stride = 0; - if (!width) - goto invalid_input; - - switch (color_fmt) { - case COLOR_FMT_NV21: - case COLOR_FMT_NV12: - case COLOR_FMT_NV12_MVTB: - case COLOR_FMT_NV12_UBWC: - alignment = 128; - stride = MSM_MEDIA_ALIGN(width, alignment); - break; - case COLOR_FMT_NV12_BPP10_UBWC: - alignment = 256; - stride = MSM_MEDIA_ALIGN(width, 192); - stride = MSM_MEDIA_ALIGN(stride * 4/3, alignment); - break; - default: - break; - } -invalid_input: - return stride; -} - -static inline unsigned int VENUS_Y_SCANLINES(int color_fmt, int height) -{ - unsigned int alignment, sclines = 0; - if (!height) - goto invalid_input; - - switch (color_fmt) { - case COLOR_FMT_NV21: - case COLOR_FMT_NV12: - case COLOR_FMT_NV12_MVTB: - case COLOR_FMT_NV12_UBWC: - alignment = 32; - break; - case COLOR_FMT_NV12_BPP10_UBWC: - alignment = 16; - break; - default: - return 0; - } - sclines = MSM_MEDIA_ALIGN(height, alignment); -invalid_input: - return sclines; -} - -static inline unsigned int VENUS_UV_SCANLINES(int color_fmt, int height) -{ - unsigned int alignment, sclines = 0; - if (!height) - goto invalid_input; - - switch (color_fmt) { - case COLOR_FMT_NV21: - case COLOR_FMT_NV12: - case COLOR_FMT_NV12_MVTB: - case COLOR_FMT_NV12_BPP10_UBWC: - alignment = 16; - break; - case COLOR_FMT_NV12_UBWC: - alignment = 32; - break; - default: - goto invalid_input; - } - - sclines = MSM_MEDIA_ALIGN(height / 2, alignment); - -invalid_input: - return sclines; -} - -static inline unsigned int VENUS_Y_META_STRIDE(int color_fmt, int width) -{ - int y_tile_width = 0, y_meta_stride = 0; - - if (!width) - goto invalid_input; - - switch (color_fmt) { - case COLOR_FMT_NV12_UBWC: - y_tile_width = 32; - break; - case COLOR_FMT_NV12_BPP10_UBWC: - y_tile_width = 48; - break; - default: - goto invalid_input; - } - - y_meta_stride = MSM_MEDIA_ROUNDUP(width, y_tile_width); - y_meta_stride = MSM_MEDIA_ALIGN(y_meta_stride, 64); - -invalid_input: - return y_meta_stride; -} - -static inline unsigned int VENUS_Y_META_SCANLINES(int color_fmt, int height) -{ - int y_tile_height = 0, y_meta_scanlines = 0; - - if (!height) - goto invalid_input; - - switch (color_fmt) { - case COLOR_FMT_NV12_UBWC: - y_tile_height = 8; - break; - case COLOR_FMT_NV12_BPP10_UBWC: - y_tile_height = 4; - break; - default: - goto invalid_input; - } - - y_meta_scanlines = MSM_MEDIA_ROUNDUP(height, y_tile_height); - y_meta_scanlines = MSM_MEDIA_ALIGN(y_meta_scanlines, 16); - -invalid_input: - return y_meta_scanlines; -} - -static inline unsigned int VENUS_UV_META_STRIDE(int color_fmt, int width) -{ - int uv_tile_width = 0, uv_meta_stride = 0; - - if (!width) - goto invalid_input; - - switch (color_fmt) { - case COLOR_FMT_NV12_UBWC: - uv_tile_width = 16; - break; - case COLOR_FMT_NV12_BPP10_UBWC: - uv_tile_width = 24; - break; - default: - goto invalid_input; - } - - uv_meta_stride = MSM_MEDIA_ROUNDUP(width / 2, uv_tile_width); - uv_meta_stride = MSM_MEDIA_ALIGN(uv_meta_stride, 64); - -invalid_input: - return uv_meta_stride; -} - -static inline unsigned int VENUS_UV_META_SCANLINES(int color_fmt, int height) -{ - int uv_tile_height = 0, uv_meta_scanlines = 0; - - if (!height) - goto invalid_input; - - switch (color_fmt) { - case COLOR_FMT_NV12_UBWC: - uv_tile_height = 8; - break; - case COLOR_FMT_NV12_BPP10_UBWC: - uv_tile_height = 4; - break; - default: - goto invalid_input; - } - - uv_meta_scanlines = MSM_MEDIA_ROUNDUP(height / 2, uv_tile_height); - uv_meta_scanlines = MSM_MEDIA_ALIGN(uv_meta_scanlines, 16); - -invalid_input: - return uv_meta_scanlines; -} - -static inline unsigned int VENUS_RGB_STRIDE(int color_fmt, int width) -{ - unsigned int alignment = 0, stride = 0; - if (!width) - goto invalid_input; - - switch (color_fmt) { - case COLOR_FMT_RGBA8888: - alignment = 128; - break; - case COLOR_FMT_RGBA8888_UBWC: - alignment = 256; - break; - default: - goto invalid_input; - } - - stride = MSM_MEDIA_ALIGN(width * 4, alignment); - -invalid_input: - return stride; -} - -static inline unsigned int VENUS_RGB_SCANLINES(int color_fmt, int height) -{ - unsigned int alignment = 0, scanlines = 0; - - if (!height) - goto invalid_input; - - switch (color_fmt) { - case COLOR_FMT_RGBA8888: - alignment = 32; - break; - case COLOR_FMT_RGBA8888_UBWC: - alignment = 16; - break; - default: - goto invalid_input; - } - - scanlines = MSM_MEDIA_ALIGN(height, alignment); - -invalid_input: - return scanlines; -} - -static inline unsigned int VENUS_RGB_META_STRIDE(int color_fmt, int width) -{ - int rgb_tile_width = 0, rgb_meta_stride = 0; - - if (!width) - goto invalid_input; - - switch (color_fmt) { - case COLOR_FMT_RGBA8888_UBWC: - rgb_tile_width = 16; - break; - default: - goto invalid_input; - } - - rgb_meta_stride = MSM_MEDIA_ROUNDUP(width, rgb_tile_width); - rgb_meta_stride = MSM_MEDIA_ALIGN(rgb_meta_stride, 64); - -invalid_input: - return rgb_meta_stride; -} - -static inline unsigned int VENUS_RGB_META_SCANLINES(int color_fmt, int height) -{ - int rgb_tile_height = 0, rgb_meta_scanlines = 0; - - if (!height) - goto invalid_input; - - switch (color_fmt) { - case COLOR_FMT_RGBA8888_UBWC: - rgb_tile_height = 4; - break; - default: - goto invalid_input; - } - - rgb_meta_scanlines = MSM_MEDIA_ROUNDUP(height, rgb_tile_height); - rgb_meta_scanlines = MSM_MEDIA_ALIGN(rgb_meta_scanlines, 16); - -invalid_input: - return rgb_meta_scanlines; -} - -static inline unsigned int VENUS_BUFFER_SIZE( - int color_fmt, int width, int height) -{ - const unsigned int extra_size = VENUS_EXTRADATA_SIZE(width, height); - unsigned int uv_alignment = 0, size = 0; - unsigned int y_plane, uv_plane, y_stride, - uv_stride, y_sclines, uv_sclines; - unsigned int y_ubwc_plane = 0, uv_ubwc_plane = 0; - unsigned int y_meta_stride = 0, y_meta_scanlines = 0; - unsigned int uv_meta_stride = 0, uv_meta_scanlines = 0; - unsigned int y_meta_plane = 0, uv_meta_plane = 0; - unsigned int rgb_stride = 0, rgb_scanlines = 0; - unsigned int rgb_plane = 0, rgb_ubwc_plane = 0, rgb_meta_plane = 0; - unsigned int rgb_meta_stride = 0, rgb_meta_scanlines = 0; - - if (!width || !height) - goto invalid_input; - - y_stride = VENUS_Y_STRIDE(color_fmt, width); - uv_stride = VENUS_UV_STRIDE(color_fmt, width); - y_sclines = VENUS_Y_SCANLINES(color_fmt, height); - uv_sclines = VENUS_UV_SCANLINES(color_fmt, height); - rgb_stride = VENUS_RGB_STRIDE(color_fmt, width); - rgb_scanlines = VENUS_RGB_SCANLINES(color_fmt, height); - - switch (color_fmt) { - case COLOR_FMT_NV21: - case COLOR_FMT_NV12: - uv_alignment = 4096; - y_plane = y_stride * y_sclines; - uv_plane = uv_stride * uv_sclines + uv_alignment; - size = y_plane + uv_plane + - MSM_MEDIA_MAX(extra_size, 8 * y_stride); - size = MSM_MEDIA_ALIGN(size, 4096); - break; - case COLOR_FMT_NV12_MVTB: - uv_alignment = 4096; - y_plane = y_stride * y_sclines; - uv_plane = uv_stride * uv_sclines + uv_alignment; - size = y_plane + uv_plane; - size = 2 * size + extra_size; - size = MSM_MEDIA_ALIGN(size, 4096); - break; - case COLOR_FMT_NV12_UBWC: - case COLOR_FMT_NV12_BPP10_UBWC: - y_ubwc_plane = MSM_MEDIA_ALIGN(y_stride * y_sclines, 4096); - uv_ubwc_plane = MSM_MEDIA_ALIGN(uv_stride * uv_sclines, 4096); - y_meta_stride = VENUS_Y_META_STRIDE(color_fmt, width); - y_meta_scanlines = VENUS_Y_META_SCANLINES(color_fmt, height); - y_meta_plane = MSM_MEDIA_ALIGN( - y_meta_stride * y_meta_scanlines, 4096); - uv_meta_stride = VENUS_UV_META_STRIDE(color_fmt, width); - uv_meta_scanlines = VENUS_UV_META_SCANLINES(color_fmt, height); - uv_meta_plane = MSM_MEDIA_ALIGN(uv_meta_stride * - uv_meta_scanlines, 4096); - - size = y_ubwc_plane + uv_ubwc_plane + y_meta_plane + - uv_meta_plane + - MSM_MEDIA_MAX(extra_size + 8192, 48 * y_stride); - size = MSM_MEDIA_ALIGN(size, 4096); - break; - case COLOR_FMT_RGBA8888: - rgb_plane = MSM_MEDIA_ALIGN(rgb_stride * rgb_scanlines, 4096); - size = rgb_plane; - size = MSM_MEDIA_ALIGN(size, 4096); - break; - case COLOR_FMT_RGBA8888_UBWC: - rgb_ubwc_plane = MSM_MEDIA_ALIGN(rgb_stride * rgb_scanlines, - 4096); - rgb_meta_stride = VENUS_RGB_META_STRIDE(color_fmt, width); - rgb_meta_scanlines = VENUS_RGB_META_SCANLINES(color_fmt, - height); - rgb_meta_plane = MSM_MEDIA_ALIGN(rgb_meta_stride * - rgb_meta_scanlines, 4096); - size = rgb_ubwc_plane + rgb_meta_plane; - size = MSM_MEDIA_ALIGN(size, 4096); - break; - default: - break; - } -invalid_input: - return size; -} - -static inline unsigned int VENUS_VIEW2_OFFSET( - int color_fmt, int width, int height) -{ - unsigned int offset = 0; - unsigned int y_plane, uv_plane, y_stride, - uv_stride, y_sclines, uv_sclines; - if (!width || !height) - goto invalid_input; - - y_stride = VENUS_Y_STRIDE(color_fmt, width); - uv_stride = VENUS_UV_STRIDE(color_fmt, width); - y_sclines = VENUS_Y_SCANLINES(color_fmt, height); - uv_sclines = VENUS_UV_SCANLINES(color_fmt, height); - switch (color_fmt) { - case COLOR_FMT_NV12_MVTB: - y_plane = y_stride * y_sclines; - uv_plane = uv_stride * uv_sclines; - offset = y_plane + uv_plane; - break; - default: - break; - } -invalid_input: - return offset; -} - -#endif diff --git a/third_party/linux/include/msmb_camera.h b/third_party/linux/include/msmb_camera.h deleted file mode 100644 index f4c4b3e183..0000000000 --- a/third_party/linux/include/msmb_camera.h +++ /dev/null @@ -1,220 +0,0 @@ -#ifndef __LINUX_MSMB_CAMERA_H -#define __LINUX_MSMB_CAMERA_H - -#include -#include -#include - -#define MSM_CAM_LOGSYNC_FILE_NAME "logsync" -#define MSM_CAM_LOGSYNC_FILE_BASEDIR "camera" - -#define MSM_CAM_V4L2_IOCTL_NOTIFY \ - _IOW('V', BASE_VIDIOC_PRIVATE + 30, struct msm_v4l2_event_data) - -#define MSM_CAM_V4L2_IOCTL_NOTIFY_META \ - _IOW('V', BASE_VIDIOC_PRIVATE + 31, struct msm_v4l2_event_data) - -#define MSM_CAM_V4L2_IOCTL_CMD_ACK \ - _IOW('V', BASE_VIDIOC_PRIVATE + 32, struct msm_v4l2_event_data) - -#define MSM_CAM_V4L2_IOCTL_NOTIFY_ERROR \ - _IOW('V', BASE_VIDIOC_PRIVATE + 33, struct msm_v4l2_event_data) - -#define MSM_CAM_V4L2_IOCTL_NOTIFY_DEBUG \ - _IOW('V', BASE_VIDIOC_PRIVATE + 34, struct msm_v4l2_event_data) - -#ifdef CONFIG_COMPAT -#define MSM_CAM_V4L2_IOCTL_NOTIFY32 \ - _IOW('V', BASE_VIDIOC_PRIVATE + 30, struct v4l2_event32) - -#define MSM_CAM_V4L2_IOCTL_NOTIFY_META32 \ - _IOW('V', BASE_VIDIOC_PRIVATE + 31, struct v4l2_event32) - -#define MSM_CAM_V4L2_IOCTL_CMD_ACK32 \ - _IOW('V', BASE_VIDIOC_PRIVATE + 32, struct v4l2_event32) - -#define MSM_CAM_V4L2_IOCTL_NOTIFY_ERROR32 \ - _IOW('V', BASE_VIDIOC_PRIVATE + 33, struct v4l2_event32) - -#define MSM_CAM_V4L2_IOCTL_NOTIFY_DEBUG32 \ - _IOW('V', BASE_VIDIOC_PRIVATE + 34, struct v4l2_event32) - -#endif - -#define QCAMERA_DEVICE_GROUP_ID 1 -#define QCAMERA_VNODE_GROUP_ID 2 -#define MSM_CAMERA_NAME "msm_camera" -#define MSM_CONFIGURATION_NAME "msm_config" - -#define MSM_CAMERA_SUBDEV_CSIPHY 0 -#define MSM_CAMERA_SUBDEV_CSID 1 -#define MSM_CAMERA_SUBDEV_ISPIF 2 -#define MSM_CAMERA_SUBDEV_VFE 3 -#define MSM_CAMERA_SUBDEV_AXI 4 -#define MSM_CAMERA_SUBDEV_VPE 5 -#define MSM_CAMERA_SUBDEV_SENSOR 6 -#define MSM_CAMERA_SUBDEV_ACTUATOR 7 -#define MSM_CAMERA_SUBDEV_EEPROM 8 -#define MSM_CAMERA_SUBDEV_CPP 9 -#define MSM_CAMERA_SUBDEV_CCI 10 -#define MSM_CAMERA_SUBDEV_LED_FLASH 11 -#define MSM_CAMERA_SUBDEV_STROBE_FLASH 12 -#define MSM_CAMERA_SUBDEV_BUF_MNGR 13 -#define MSM_CAMERA_SUBDEV_SENSOR_INIT 14 -#define MSM_CAMERA_SUBDEV_OIS 15 -#define MSM_CAMERA_SUBDEV_FLASH 16 -#define MSM_CAMERA_SUBDEV_EXT 17 - -#define MSM_MAX_CAMERA_SENSORS 5 - -/* The below macro is defined to put an upper limit on maximum - * number of buffer requested per stream. In case of extremely - * large value for number of buffer due to data structure corruption - * we return error to avoid integer overflow. Group processing - * can have max of 9 groups of 8 bufs each. This value may be - * configured in future*/ -#define MSM_CAMERA_MAX_STREAM_BUF 72 - -/* Max batch size of processing */ -#define MSM_CAMERA_MAX_USER_BUFF_CNT 16 - -/* featur base */ -#define MSM_CAMERA_FEATURE_BASE 0x00010000 -#define MSM_CAMERA_FEATURE_SHUTDOWN (MSM_CAMERA_FEATURE_BASE + 1) - -#define MSM_CAMERA_STATUS_BASE 0x00020000 -#define MSM_CAMERA_STATUS_FAIL (MSM_CAMERA_STATUS_BASE + 1) -#define MSM_CAMERA_STATUS_SUCCESS (MSM_CAMERA_STATUS_BASE + 2) - -/* event type */ -#define MSM_CAMERA_V4L2_EVENT_TYPE (V4L2_EVENT_PRIVATE_START + 0x00002000) - -/* event id */ -#define MSM_CAMERA_EVENT_MIN 0 -#define MSM_CAMERA_NEW_SESSION (MSM_CAMERA_EVENT_MIN + 1) -#define MSM_CAMERA_DEL_SESSION (MSM_CAMERA_EVENT_MIN + 2) -#define MSM_CAMERA_SET_PARM (MSM_CAMERA_EVENT_MIN + 3) -#define MSM_CAMERA_GET_PARM (MSM_CAMERA_EVENT_MIN + 4) -#define MSM_CAMERA_MAPPING_CFG (MSM_CAMERA_EVENT_MIN + 5) -#define MSM_CAMERA_MAPPING_SES (MSM_CAMERA_EVENT_MIN + 6) -#define MSM_CAMERA_MSM_NOTIFY (MSM_CAMERA_EVENT_MIN + 7) -#define MSM_CAMERA_EVENT_MAX (MSM_CAMERA_EVENT_MIN + 8) - -/* data.command */ -#define MSM_CAMERA_PRIV_S_CROP (V4L2_CID_PRIVATE_BASE + 1) -#define MSM_CAMERA_PRIV_G_CROP (V4L2_CID_PRIVATE_BASE + 2) -#define MSM_CAMERA_PRIV_G_FMT (V4L2_CID_PRIVATE_BASE + 3) -#define MSM_CAMERA_PRIV_S_FMT (V4L2_CID_PRIVATE_BASE + 4) -#define MSM_CAMERA_PRIV_TRY_FMT (V4L2_CID_PRIVATE_BASE + 5) -#define MSM_CAMERA_PRIV_METADATA (V4L2_CID_PRIVATE_BASE + 6) -#define MSM_CAMERA_PRIV_QUERY_CAP (V4L2_CID_PRIVATE_BASE + 7) -#define MSM_CAMERA_PRIV_STREAM_ON (V4L2_CID_PRIVATE_BASE + 8) -#define MSM_CAMERA_PRIV_STREAM_OFF (V4L2_CID_PRIVATE_BASE + 9) -#define MSM_CAMERA_PRIV_NEW_STREAM (V4L2_CID_PRIVATE_BASE + 10) -#define MSM_CAMERA_PRIV_DEL_STREAM (V4L2_CID_PRIVATE_BASE + 11) -#define MSM_CAMERA_PRIV_SHUTDOWN (V4L2_CID_PRIVATE_BASE + 12) -#define MSM_CAMERA_PRIV_STREAM_INFO_SYNC \ - (V4L2_CID_PRIVATE_BASE + 13) -#define MSM_CAMERA_PRIV_G_SESSION_ID (V4L2_CID_PRIVATE_BASE + 14) -#define MSM_CAMERA_PRIV_CMD_MAX 20 - -/* data.status - success */ -#define MSM_CAMERA_CMD_SUCESS 0x00000001 -#define MSM_CAMERA_BUF_MAP_SUCESS 0x00000002 - -/* data.status - error */ -#define MSM_CAMERA_ERR_EVT_BASE 0x00010000 -#define MSM_CAMERA_ERR_CMD_FAIL (MSM_CAMERA_ERR_EVT_BASE + 1) -#define MSM_CAMERA_ERR_MAPPING (MSM_CAMERA_ERR_EVT_BASE + 2) -#define MSM_CAMERA_ERR_DEVICE_BUSY (MSM_CAMERA_ERR_EVT_BASE + 3) - -/* The msm_v4l2_event_data structure should match the - * v4l2_event.u.data field. - * should not exceed 16 elements */ -struct msm_v4l2_event_data { - /*word 0*/ - unsigned int command; - /*word 1*/ - unsigned int status; - /*word 2*/ - unsigned int session_id; - /*word 3*/ - unsigned int stream_id; - /*word 4*/ - unsigned int map_op; - /*word 5*/ - unsigned int map_buf_idx; - /*word 6*/ - unsigned int notify; - /*word 7*/ - unsigned int arg_value; - /*word 8*/ - unsigned int ret_value; - /*word 9*/ - unsigned int v4l2_event_type; - /*word 10*/ - unsigned int v4l2_event_id; - /*word 11*/ - unsigned int handle; - /*word 12*/ - unsigned int nop6; - /*word 13*/ - unsigned int nop7; - /*word 14*/ - unsigned int nop8; - /*word 15*/ - unsigned int nop9; -}; - -/* map to v4l2_format.fmt.raw_data */ -struct msm_v4l2_format_data { - enum v4l2_buf_type type; - unsigned int width; - unsigned int height; - unsigned int pixelformat; /* FOURCC */ - unsigned char num_planes; - unsigned int plane_sizes[VIDEO_MAX_PLANES]; -}; - -/* MSM Four-character-code (FOURCC) */ -#define msm_v4l2_fourcc(a, b, c, d)\ - ((__u32)(a) | ((__u32)(b) << 8) | ((__u32)(c) << 16) |\ - ((__u32)(d) << 24)) - -/* Composite stats */ -#define MSM_V4L2_PIX_FMT_STATS_COMB v4l2_fourcc('S', 'T', 'C', 'M') -/* AEC stats */ -#define MSM_V4L2_PIX_FMT_STATS_AE v4l2_fourcc('S', 'T', 'A', 'E') -/* AF stats */ -#define MSM_V4L2_PIX_FMT_STATS_AF v4l2_fourcc('S', 'T', 'A', 'F') -/* AWB stats */ -#define MSM_V4L2_PIX_FMT_STATS_AWB v4l2_fourcc('S', 'T', 'W', 'B') -/* IHIST stats */ -#define MSM_V4L2_PIX_FMT_STATS_IHST v4l2_fourcc('I', 'H', 'S', 'T') -/* Column count stats */ -#define MSM_V4L2_PIX_FMT_STATS_CS v4l2_fourcc('S', 'T', 'C', 'S') -/* Row count stats */ -#define MSM_V4L2_PIX_FMT_STATS_RS v4l2_fourcc('S', 'T', 'R', 'S') -/* Bayer Grid stats */ -#define MSM_V4L2_PIX_FMT_STATS_BG v4l2_fourcc('S', 'T', 'B', 'G') -/* Bayer focus stats */ -#define MSM_V4L2_PIX_FMT_STATS_BF v4l2_fourcc('S', 'T', 'B', 'F') -/* Bayer hist stats */ -#define MSM_V4L2_PIX_FMT_STATS_BHST v4l2_fourcc('B', 'H', 'S', 'T') - -enum smmu_attach_mode { - NON_SECURE_MODE = 0x01, - SECURE_MODE = 0x02, - MAX_PROTECTION_MODE = 0x03, -}; - -struct msm_camera_smmu_attach_type { - enum smmu_attach_mode attach; -}; - -struct msm_camera_user_buf_cont_t { - unsigned int buf_cnt; - unsigned int buf_idx[MSM_CAMERA_MAX_USER_BUFF_CNT]; -}; - -#endif /* __LINUX_MSMB_CAMERA_H */ diff --git a/third_party/linux/include/msmb_isp.h b/third_party/linux/include/msmb_isp.h deleted file mode 100644 index 35589e050a..0000000000 --- a/third_party/linux/include/msmb_isp.h +++ /dev/null @@ -1,880 +0,0 @@ -#ifndef __MSMB_ISP__ -#define __MSMB_ISP__ - -#include - -#define MAX_PLANES_PER_STREAM 3 -#define MAX_NUM_STREAM 7 - -#define ISP_VERSION_47 47 -#define ISP_VERSION_46 46 -#define ISP_VERSION_44 44 -#define ISP_VERSION_40 40 -#define ISP_VERSION_32 32 -#define ISP_NATIVE_BUF_BIT (0x10000 << 0) -#define ISP0_BIT (0x10000 << 1) -#define ISP1_BIT (0x10000 << 2) -#define ISP_META_CHANNEL_BIT (0x10000 << 3) -#define ISP_SCRATCH_BUF_BIT (0x10000 << 4) -#define ISP_OFFLINE_STATS_BIT (0x10000 << 5) -#define ISP_STATS_STREAM_BIT 0x80000000 - -struct msm_vfe_cfg_cmd_list; - -enum ISP_START_PIXEL_PATTERN { - ISP_BAYER_RGRGRG, - ISP_BAYER_GRGRGR, - ISP_BAYER_BGBGBG, - ISP_BAYER_GBGBGB, - ISP_YUV_YCbYCr, - ISP_YUV_YCrYCb, - ISP_YUV_CbYCrY, - ISP_YUV_CrYCbY, - ISP_PIX_PATTERN_MAX -}; - -enum msm_vfe_plane_fmt { - Y_PLANE, - CB_PLANE, - CR_PLANE, - CRCB_PLANE, - CBCR_PLANE, - VFE_PLANE_FMT_MAX -}; - -enum msm_vfe_input_src { - VFE_PIX_0, - VFE_RAW_0, - VFE_RAW_1, - VFE_RAW_2, - VFE_SRC_MAX, -}; - -enum msm_vfe_axi_stream_src { - PIX_ENCODER, - PIX_VIEWFINDER, - PIX_VIDEO, - CAMIF_RAW, - IDEAL_RAW, - RDI_INTF_0, - RDI_INTF_1, - RDI_INTF_2, - VFE_AXI_SRC_MAX -}; - -enum msm_vfe_frame_skip_pattern { - NO_SKIP, - EVERY_2FRAME, - EVERY_3FRAME, - EVERY_4FRAME, - EVERY_5FRAME, - EVERY_6FRAME, - EVERY_7FRAME, - EVERY_8FRAME, - EVERY_16FRAME, - EVERY_32FRAME, - SKIP_ALL, - SKIP_RANGE, - MAX_SKIP, -}; - -/* - * Define an unused period. When this period is set it means that the stream is - * stopped(i.e the pattern is 0). We don't track the current pattern, just the - * period defines what the pattern is, if period is this then pattern is 0 else - * pattern is 1 - */ -#define MSM_VFE_STREAM_STOP_PERIOD 15 - -enum msm_isp_stats_type { - MSM_ISP_STATS_AEC, /* legacy based AEC */ - MSM_ISP_STATS_AF, /* legacy based AF */ - MSM_ISP_STATS_AWB, /* legacy based AWB */ - MSM_ISP_STATS_RS, /* legacy based RS */ - MSM_ISP_STATS_CS, /* legacy based CS */ - MSM_ISP_STATS_IHIST, /* legacy based HIST */ - MSM_ISP_STATS_SKIN, /* legacy based SKIN */ - MSM_ISP_STATS_BG, /* Bayer Grids */ - MSM_ISP_STATS_BF, /* Bayer Focus */ - MSM_ISP_STATS_BE, /* Bayer Exposure*/ - MSM_ISP_STATS_BHIST, /* Bayer Hist */ - MSM_ISP_STATS_BF_SCALE, /* Bayer Focus scale */ - MSM_ISP_STATS_HDR_BE, /* HDR Bayer Exposure */ - MSM_ISP_STATS_HDR_BHIST, /* HDR Bayer Hist */ - MSM_ISP_STATS_AEC_BG, /* AEC BG */ - MSM_ISP_STATS_MAX /* MAX */ -}; - -/* - * @stats_type_mask: Stats type mask (enum msm_isp_stats_type). - * @stream_src_mask: Stream src mask (enum msm_vfe_axi_stream_src) - * @skip_mode: skip pattern, if skip mode is range only then min/max is used - * @min_frame_id: minimum frame id (valid only if skip_mode = RANGE) - * @max_frame_id: maximum frame id (valid only if skip_mode = RANGE) -*/ -struct msm_isp_sw_framskip { - uint32_t stats_type_mask; - uint32_t stream_src_mask; - enum msm_vfe_frame_skip_pattern skip_mode; - uint32_t min_frame_id; - uint32_t max_frame_id; -}; - -enum msm_vfe_testgen_color_pattern { - COLOR_BAR_8_COLOR, - UNICOLOR_WHITE, - UNICOLOR_YELLOW, - UNICOLOR_CYAN, - UNICOLOR_GREEN, - UNICOLOR_MAGENTA, - UNICOLOR_RED, - UNICOLOR_BLUE, - UNICOLOR_BLACK, - MAX_COLOR, -}; - -enum msm_vfe_camif_input { - CAMIF_DISABLED, - CAMIF_PAD_REG_INPUT, - CAMIF_MIDDI_INPUT, - CAMIF_MIPI_INPUT, -}; - -struct msm_vfe_fetch_engine_cfg { - uint32_t input_format; - uint32_t buf_width; - uint32_t buf_height; - uint32_t fetch_width; - uint32_t fetch_height; - uint32_t x_offset; - uint32_t y_offset; - uint32_t buf_stride; -}; - -enum msm_vfe_camif_output_format { - CAMIF_QCOM_RAW, - CAMIF_MIPI_RAW, - CAMIF_PLAIN_8, - CAMIF_PLAIN_16, - CAMIF_MAX_FORMAT, -}; - -/* - * Camif output general configuration - */ -struct msm_vfe_camif_subsample_cfg { - uint32_t irq_subsample_period; - uint32_t irq_subsample_pattern; - uint32_t sof_counter_step; - uint32_t pixel_skip; - uint32_t line_skip; - uint32_t first_line; - uint32_t last_line; - uint32_t first_pixel; - uint32_t last_pixel; - enum msm_vfe_camif_output_format output_format; -}; - -/* - * Camif frame and window configuration - */ -struct msm_vfe_camif_cfg { - uint32_t lines_per_frame; - uint32_t pixels_per_line; - uint32_t first_pixel; - uint32_t last_pixel; - uint32_t first_line; - uint32_t last_line; - uint32_t epoch_line0; - uint32_t epoch_line1; - uint32_t is_split; - enum msm_vfe_camif_input camif_input; - struct msm_vfe_camif_subsample_cfg subsample_cfg; -}; - -struct msm_vfe_testgen_cfg { - uint32_t lines_per_frame; - uint32_t pixels_per_line; - uint32_t v_blank; - uint32_t h_blank; - enum ISP_START_PIXEL_PATTERN pixel_bayer_pattern; - uint32_t rotate_period; - enum msm_vfe_testgen_color_pattern color_bar_pattern; - uint32_t burst_num_frame; -}; - -enum msm_vfe_inputmux { - CAMIF, - TESTGEN, - EXTERNAL_READ, -}; - -enum msm_vfe_stats_composite_group { - STATS_COMPOSITE_GRP_NONE, - STATS_COMPOSITE_GRP_1, - STATS_COMPOSITE_GRP_2, - STATS_COMPOSITE_GRP_MAX, -}; - -enum msm_vfe_hvx_streaming_cmd { - HVX_DISABLE, - HVX_ONE_WAY, - HVX_ROUND_TRIP -}; - -struct msm_vfe_pix_cfg { - struct msm_vfe_camif_cfg camif_cfg; - struct msm_vfe_testgen_cfg testgen_cfg; - struct msm_vfe_fetch_engine_cfg fetch_engine_cfg; - enum msm_vfe_inputmux input_mux; - enum ISP_START_PIXEL_PATTERN pixel_pattern; - uint32_t input_format; - enum msm_vfe_hvx_streaming_cmd hvx_cmd; - uint32_t is_split; -}; - -struct msm_vfe_rdi_cfg { - uint8_t cid; - uint8_t frame_based; -}; - -struct msm_vfe_input_cfg { - union { - struct msm_vfe_pix_cfg pix_cfg; - struct msm_vfe_rdi_cfg rdi_cfg; - } d; - enum msm_vfe_input_src input_src; - uint32_t input_pix_clk; -}; - -struct msm_vfe_fetch_eng_start { - uint32_t session_id; - uint32_t stream_id; - uint32_t buf_idx; - uint8_t offline_mode; - uint32_t fd; - uint32_t buf_addr; - uint32_t frame_id; -}; - -struct msm_vfe_axi_plane_cfg { - uint32_t output_width; /*Include padding*/ - uint32_t output_height; - uint32_t output_stride; - uint32_t output_scan_lines; - uint32_t output_plane_format; /*Y/Cb/Cr/CbCr*/ - uint32_t plane_addr_offset; - uint8_t csid_src; /*RDI 0-2*/ - uint8_t rdi_cid;/*CID 1-16*/ -}; - -enum msm_stream_memory_input_t { - MEMORY_INPUT_DISABLED, - MEMORY_INPUT_ENABLED -}; - -struct msm_vfe_axi_stream_request_cmd { - uint32_t session_id; - uint32_t stream_id; - uint32_t vt_enable; - uint32_t output_format;/*Planar/RAW/Misc*/ - enum msm_vfe_axi_stream_src stream_src; /*CAMIF/IDEAL/RDIs*/ - struct msm_vfe_axi_plane_cfg plane_cfg[MAX_PLANES_PER_STREAM]; - - uint32_t burst_count; - uint32_t hfr_mode; - uint8_t frame_base; - - uint32_t init_frame_drop; /*MAX 31 Frames*/ - enum msm_vfe_frame_skip_pattern frame_skip_pattern; - uint8_t buf_divert; /* if TRUE no vb2 buf done. */ - /*Return values*/ - uint32_t axi_stream_handle; - uint32_t controllable_output; - uint32_t burst_len; - /* Flag indicating memory input stream */ - enum msm_stream_memory_input_t memory_input; -}; - -struct msm_vfe_axi_stream_release_cmd { - uint32_t stream_handle; -}; - -enum msm_vfe_axi_stream_cmd { - STOP_STREAM, - START_STREAM, - STOP_IMMEDIATELY, -}; - -struct msm_vfe_axi_stream_cfg_cmd { - uint8_t num_streams; - uint32_t stream_handle[VFE_AXI_SRC_MAX]; - enum msm_vfe_axi_stream_cmd cmd; - uint8_t sync_frame_id_src; -}; - -enum msm_vfe_axi_stream_update_type { - ENABLE_STREAM_BUF_DIVERT, - DISABLE_STREAM_BUF_DIVERT, - UPDATE_STREAM_FRAMEDROP_PATTERN, - UPDATE_STREAM_STATS_FRAMEDROP_PATTERN, - UPDATE_STREAM_AXI_CONFIG, - UPDATE_STREAM_REQUEST_FRAMES, - UPDATE_STREAM_ADD_BUFQ, - UPDATE_STREAM_REMOVE_BUFQ, - UPDATE_STREAM_SW_FRAME_DROP, -}; - -enum msm_vfe_iommu_type { - IOMMU_ATTACH, - IOMMU_DETACH, -}; - -enum msm_vfe_buff_queue_id { - VFE_BUF_QUEUE_DEFAULT, - VFE_BUF_QUEUE_SHARED, - VFE_BUF_QUEUE_MAX, -}; - -struct msm_vfe_axi_stream_cfg_update_info { - uint32_t stream_handle; - uint32_t output_format; - uint32_t user_stream_id; - uint32_t frame_id; - enum msm_vfe_frame_skip_pattern skip_pattern; - struct msm_vfe_axi_plane_cfg plane_cfg[MAX_PLANES_PER_STREAM]; - struct msm_isp_sw_framskip sw_skip_info; -}; - -struct msm_vfe_axi_halt_cmd { - uint32_t stop_camif; - uint32_t overflow_detected; - uint32_t blocking_halt; -}; - -struct msm_vfe_axi_reset_cmd { - uint32_t blocking; - uint32_t frame_id; -}; - -struct msm_vfe_axi_restart_cmd { - uint32_t enable_camif; -}; - -struct msm_vfe_axi_stream_update_cmd { - uint32_t num_streams; - enum msm_vfe_axi_stream_update_type update_type; - struct msm_vfe_axi_stream_cfg_update_info - update_info[MSM_ISP_STATS_MAX]; -}; - -struct msm_vfe_smmu_attach_cmd { - uint32_t security_mode; - uint32_t iommu_attach_mode; -}; - -struct msm_vfe_stats_stream_request_cmd { - uint32_t session_id; - uint32_t stream_id; - enum msm_isp_stats_type stats_type; - uint32_t composite_flag; - uint32_t framedrop_pattern; - uint32_t init_frame_drop; /*MAX 31 Frames*/ - uint32_t irq_subsample_pattern; - uint32_t buffer_offset; - uint32_t stream_handle; -}; - -struct msm_vfe_stats_stream_release_cmd { - uint32_t stream_handle; -}; -struct msm_vfe_stats_stream_cfg_cmd { - uint8_t num_streams; - uint32_t stream_handle[MSM_ISP_STATS_MAX]; - uint8_t enable; - uint32_t stats_burst_len; -}; - -enum msm_vfe_reg_cfg_type { - VFE_WRITE, - VFE_WRITE_MB, - VFE_READ, - VFE_CFG_MASK, - VFE_WRITE_DMI_16BIT, - VFE_WRITE_DMI_32BIT, - VFE_WRITE_DMI_64BIT, - VFE_READ_DMI_16BIT, - VFE_READ_DMI_32BIT, - VFE_READ_DMI_64BIT, - GET_MAX_CLK_RATE, - GET_CLK_RATES, - GET_ISP_ID, - VFE_HW_UPDATE_LOCK, - VFE_HW_UPDATE_UNLOCK, - SET_WM_UB_SIZE, - SET_UB_POLICY, -}; - -struct msm_vfe_cfg_cmd2 { - uint16_t num_cfg; - uint16_t cmd_len; - void __user *cfg_data; - void __user *cfg_cmd; -}; - -struct msm_vfe_cfg_cmd_list { - struct msm_vfe_cfg_cmd2 cfg_cmd; - struct msm_vfe_cfg_cmd_list *next; - uint32_t next_size; -}; - -struct msm_vfe_reg_rw_info { - uint32_t reg_offset; - uint32_t cmd_data_offset; - uint32_t len; -}; - -struct msm_vfe_reg_mask_info { - uint32_t reg_offset; - uint32_t mask; - uint32_t val; -}; - -struct msm_vfe_reg_dmi_info { - uint32_t hi_tbl_offset; /*Optional*/ - uint32_t lo_tbl_offset; /*Required*/ - uint32_t len; -}; - -struct msm_vfe_reg_cfg_cmd { - union { - struct msm_vfe_reg_rw_info rw_info; - struct msm_vfe_reg_mask_info mask_info; - struct msm_vfe_reg_dmi_info dmi_info; - } u; - - enum msm_vfe_reg_cfg_type cmd_type; -}; - -enum vfe_sd_type { - VFE_SD_0 = 0, - VFE_SD_1, - VFE_SD_COMMON, - VFE_SD_MAX, -}; - -/* When you change the value below, check for the sof event_data size. - * V4l2 limits payload to 64 bytes */ -#define MS_NUM_SLAVE_MAX 1 - -/* Usecases when 2 HW need to be related or synced */ -enum msm_vfe_dual_hw_type { - DUAL_NONE = 0, - DUAL_HW_VFE_SPLIT = 1, - DUAL_HW_MASTER_SLAVE = 2, -}; - -/* Type for 2 INTF when used in Master-Slave mode */ -enum msm_vfe_dual_hw_ms_type { - MS_TYPE_NONE, - MS_TYPE_MASTER, - MS_TYPE_SLAVE, -}; - -struct msm_isp_set_dual_hw_ms_cmd { - uint8_t num_src; - /* Each session can be only one type but multiple intf if YUV cam */ - enum msm_vfe_dual_hw_ms_type dual_hw_ms_type; - /* Primary intf is mostly associated with preview. - * This primary intf SOF frame_id and timestamp is tracked - * and used to calculate delta */ - enum msm_vfe_input_src primary_intf; - /* input_src array indicates other input INTF that may be Master/Slave. - * For these additional intf, frame_id and timestamp are not saved. - * However, if these are slaves then they will still get their - * frame_id from Master */ - enum msm_vfe_input_src input_src[VFE_SRC_MAX]; - uint32_t sof_delta_threshold; /* In milliseconds. Sent for Master */ -}; - -enum msm_isp_buf_type { - ISP_PRIVATE_BUF, - ISP_SHARE_BUF, - MAX_ISP_BUF_TYPE, -}; - -struct msm_isp_unmap_buf_req { - uint32_t fd; -}; - -struct msm_isp_buf_request { - uint32_t session_id; - uint32_t stream_id; - uint8_t num_buf; - uint32_t handle; - enum msm_isp_buf_type buf_type; -}; - -struct msm_isp_qbuf_plane { - uint32_t addr; - uint32_t offset; - uint32_t length; -}; - -struct msm_isp_qbuf_buffer { - struct msm_isp_qbuf_plane planes[MAX_PLANES_PER_STREAM]; - uint32_t num_planes; -}; - -struct msm_isp_qbuf_info { - uint32_t handle; - int32_t buf_idx; - /*Only used for prepare buffer*/ - struct msm_isp_qbuf_buffer buffer; - /*Only used for diverted buffer*/ - uint32_t dirty_buf; -}; - -struct msm_isp_clk_rates { - uint32_t svs_rate; - uint32_t nominal_rate; - uint32_t high_rate; -}; - -struct msm_vfe_axi_src_state { - enum msm_vfe_input_src input_src; - uint32_t src_active; - uint32_t src_frame_id; -}; - -enum msm_isp_event_mask_index { - ISP_EVENT_MASK_INDEX_STATS_NOTIFY = 0, - ISP_EVENT_MASK_INDEX_ERROR = 1, - ISP_EVENT_MASK_INDEX_IOMMU_P_FAULT = 2, - ISP_EVENT_MASK_INDEX_STREAM_UPDATE_DONE = 3, - ISP_EVENT_MASK_INDEX_REG_UPDATE = 4, - ISP_EVENT_MASK_INDEX_SOF = 5, - ISP_EVENT_MASK_INDEX_BUF_DIVERT = 6, - ISP_EVENT_MASK_INDEX_COMP_STATS_NOTIFY = 7, - ISP_EVENT_MASK_INDEX_MASK_FE_READ_DONE = 8, - ISP_EVENT_MASK_INDEX_BUF_DONE = 9, - ISP_EVENT_MASK_INDEX_REG_UPDATE_MISSING = 10, - ISP_EVENT_MASK_INDEX_PING_PONG_MISMATCH = 11, - ISP_EVENT_MASK_INDEX_BUF_FATAL_ERROR = 12, -}; - - -#define ISP_EVENT_SUBS_MASK_NONE 0 - -#define ISP_EVENT_SUBS_MASK_STATS_NOTIFY \ - (1 << ISP_EVENT_MASK_INDEX_STATS_NOTIFY) - -#define ISP_EVENT_SUBS_MASK_ERROR \ - (1 << ISP_EVENT_MASK_INDEX_ERROR) - -#define ISP_EVENT_SUBS_MASK_IOMMU_P_FAULT \ - (1 << ISP_EVENT_MASK_INDEX_IOMMU_P_FAULT) - -#define ISP_EVENT_SUBS_MASK_STREAM_UPDATE_DONE \ - (1 << ISP_EVENT_MASK_INDEX_STREAM_UPDATE_DONE) - -#define ISP_EVENT_SUBS_MASK_REG_UPDATE \ - (1 << ISP_EVENT_MASK_INDEX_REG_UPDATE) - -#define ISP_EVENT_SUBS_MASK_SOF \ - (1 << ISP_EVENT_MASK_INDEX_SOF) - -#define ISP_EVENT_SUBS_MASK_BUF_DIVERT \ - (1 << ISP_EVENT_MASK_INDEX_BUF_DIVERT) - -#define ISP_EVENT_SUBS_MASK_COMP_STATS_NOTIFY \ - (1 << ISP_EVENT_MASK_INDEX_COMP_STATS_NOTIFY) - -#define ISP_EVENT_SUBS_MASK_FE_READ_DONE \ - (1 << ISP_EVENT_MASK_INDEX_MASK_FE_READ_DONE) - -#define ISP_EVENT_SUBS_MASK_BUF_DONE \ - (1 << ISP_EVENT_MASK_INDEX_BUF_DONE) - -#define ISP_EVENT_SUBS_MASK_REG_UPDATE_MISSING \ - (1 << ISP_EVENT_MASK_INDEX_REG_UPDATE_MISSING) - -#define ISP_EVENT_SUBS_MASK_PING_PONG_MISMATCH \ - (1 << ISP_EVENT_MASK_INDEX_PING_PONG_MISMATCH) - -#define ISP_EVENT_SUBS_MASK_BUF_FATAL_ERROR \ - (1 << ISP_EVENT_MASK_INDEX_BUF_FATAL_ERROR) - -enum msm_isp_event_idx { - ISP_REG_UPDATE = 0, - ISP_EPOCH_0 = 1, - ISP_EPOCH_1 = 2, - ISP_START_ACK = 3, - ISP_STOP_ACK = 4, - ISP_IRQ_VIOLATION = 5, - ISP_STATS_OVERFLOW = 6, - ISP_BUF_DONE = 7, - ISP_FE_RD_DONE = 8, - ISP_IOMMU_P_FAULT = 9, - ISP_ERROR = 10, - ISP_HW_FATAL_ERROR = 11, - ISP_PING_PONG_MISMATCH = 12, - ISP_REG_UPDATE_MISSING = 13, - ISP_BUF_FATAL_ERROR = 14, - ISP_EVENT_MAX = 15 -}; - -#define ISP_EVENT_OFFSET 8 -#define ISP_EVENT_BASE (V4L2_EVENT_PRIVATE_START) -#define ISP_BUF_EVENT_BASE (ISP_EVENT_BASE + (1 << ISP_EVENT_OFFSET)) -#define ISP_STATS_EVENT_BASE (ISP_EVENT_BASE + (2 << ISP_EVENT_OFFSET)) -#define ISP_CAMIF_EVENT_BASE (ISP_EVENT_BASE + (3 << ISP_EVENT_OFFSET)) -#define ISP_STREAM_EVENT_BASE (ISP_EVENT_BASE + (4 << ISP_EVENT_OFFSET)) -#define ISP_EVENT_REG_UPDATE (ISP_EVENT_BASE + ISP_REG_UPDATE) -#define ISP_EVENT_EPOCH_0 (ISP_EVENT_BASE + ISP_EPOCH_0) -#define ISP_EVENT_EPOCH_1 (ISP_EVENT_BASE + ISP_EPOCH_1) -#define ISP_EVENT_START_ACK (ISP_EVENT_BASE + ISP_START_ACK) -#define ISP_EVENT_STOP_ACK (ISP_EVENT_BASE + ISP_STOP_ACK) -#define ISP_EVENT_IRQ_VIOLATION (ISP_EVENT_BASE + ISP_IRQ_VIOLATION) -#define ISP_EVENT_STATS_OVERFLOW (ISP_EVENT_BASE + ISP_STATS_OVERFLOW) -#define ISP_EVENT_ERROR (ISP_EVENT_BASE + ISP_ERROR) -#define ISP_EVENT_SOF (ISP_CAMIF_EVENT_BASE) -#define ISP_EVENT_EOF (ISP_CAMIF_EVENT_BASE + 1) -#define ISP_EVENT_BUF_DONE (ISP_EVENT_BASE + ISP_BUF_DONE) -#define ISP_EVENT_BUF_DIVERT (ISP_BUF_EVENT_BASE) -#define ISP_EVENT_STATS_NOTIFY (ISP_STATS_EVENT_BASE) -#define ISP_EVENT_COMP_STATS_NOTIFY (ISP_EVENT_STATS_NOTIFY + MSM_ISP_STATS_MAX) -#define ISP_EVENT_FE_READ_DONE (ISP_EVENT_BASE + ISP_FE_RD_DONE) -#define ISP_EVENT_IOMMU_P_FAULT (ISP_EVENT_BASE + ISP_IOMMU_P_FAULT) -#define ISP_EVENT_HW_FATAL_ERROR (ISP_EVENT_BASE + ISP_HW_FATAL_ERROR) -#define ISP_EVENT_PING_PONG_MISMATCH (ISP_EVENT_BASE + ISP_PING_PONG_MISMATCH) -#define ISP_EVENT_REG_UPDATE_MISSING (ISP_EVENT_BASE + ISP_REG_UPDATE_MISSING) -#define ISP_EVENT_BUF_FATAL_ERROR (ISP_EVENT_BASE + ISP_BUF_FATAL_ERROR) -#define ISP_EVENT_STREAM_UPDATE_DONE (ISP_STREAM_EVENT_BASE) - -/* The msm_v4l2_event_data structure should match the - * v4l2_event.u.data field. - * should not exceed 64 bytes */ - -struct msm_isp_buf_event { - uint32_t session_id; - uint32_t stream_id; - uint32_t handle; - uint32_t output_format; - int8_t buf_idx; -}; -struct msm_isp_fetch_eng_event { - uint32_t session_id; - uint32_t stream_id; - uint32_t handle; - uint32_t fd; - int8_t buf_idx; - int8_t offline_mode; -}; -struct msm_isp_stats_event { - uint32_t stats_mask; /* 4 bytes */ - uint8_t stats_buf_idxs[MSM_ISP_STATS_MAX]; /* 11 bytes */ -}; - -struct msm_isp_stream_ack { - uint32_t session_id; - uint32_t stream_id; - uint32_t handle; -}; - -enum msm_vfe_error_type { - ISP_ERROR_NONE, - ISP_ERROR_CAMIF, - ISP_ERROR_BUS_OVERFLOW, - ISP_ERROR_RETURN_EMPTY_BUFFER, - ISP_ERROR_FRAME_ID_MISMATCH, - ISP_ERROR_MAX, -}; - -struct msm_isp_error_info { - enum msm_vfe_error_type err_type; - uint32_t session_id; - uint32_t stream_id; - uint32_t stream_id_mask; -}; - -/* This structure reports delta between master and slave */ -struct msm_isp_ms_delta_info { - uint8_t num_delta_info; - uint32_t delta[MS_NUM_SLAVE_MAX]; -}; - -/* This is sent in EPOCH irq */ -struct msm_isp_output_info { - uint8_t regs_not_updated; - /* mask with bufq_handle for regs not updated or return empty */ - uint16_t output_err_mask; - /* mask with stream_idx for get_buf failed */ - uint8_t stream_framedrop_mask; - /* mask with stats stream_idx for get_buf failed */ - uint16_t stats_framedrop_mask; - /* delta between master and slave */ -}; - -/* This structure is piggybacked with SOF event */ -struct msm_isp_sof_info { - uint8_t regs_not_updated; - /* mask with AXI_SRC for regs not updated */ - uint16_t reg_update_fail_mask; - /* mask with bufq_handle for get_buf failed */ - uint32_t stream_get_buf_fail_mask; - /* mask with stats stream_idx for get_buf failed */ - uint16_t stats_get_buf_fail_mask; - /* delta between master and slave */ - struct msm_isp_ms_delta_info ms_delta_info; -}; - -struct msm_isp_event_data { - /*Wall clock except for buffer divert events - *which use monotonic clock - */ - struct timeval timestamp; - /* Monotonic timestamp since bootup */ - struct timeval mono_timestamp; - uint32_t frame_id; - union { - /* Sent for Stats_Done event */ - struct msm_isp_stats_event stats; - /* Sent for Buf_Divert event */ - struct msm_isp_buf_event buf_done; - /* Sent for offline fetch done event */ - struct msm_isp_fetch_eng_event fetch_done; - /* Sent for Error_Event */ - struct msm_isp_error_info error_info; - /* - * This struct needs to be removed once - * userspace switches to sof_info - */ - struct msm_isp_output_info output_info; - /* Sent for SOF event */ - struct msm_isp_sof_info sof_info; - } u; /* union can have max 52 bytes */ -}; - -#ifdef CONFIG_COMPAT -struct msm_isp_event_data32 { - struct compat_timeval timestamp; - struct compat_timeval mono_timestamp; - uint32_t frame_id; - union { - struct msm_isp_stats_event stats; - struct msm_isp_buf_event buf_done; - struct msm_isp_fetch_eng_event fetch_done; - struct msm_isp_error_info error_info; - struct msm_isp_output_info output_info; - struct msm_isp_sof_info sof_info; - } u; -}; -#endif - -#define V4L2_PIX_FMT_QBGGR8 v4l2_fourcc('Q', 'B', 'G', '8') -#define V4L2_PIX_FMT_QGBRG8 v4l2_fourcc('Q', 'G', 'B', '8') -#define V4L2_PIX_FMT_QGRBG8 v4l2_fourcc('Q', 'G', 'R', '8') -#define V4L2_PIX_FMT_QRGGB8 v4l2_fourcc('Q', 'R', 'G', '8') -#define V4L2_PIX_FMT_QBGGR10 v4l2_fourcc('Q', 'B', 'G', '0') -#define V4L2_PIX_FMT_QGBRG10 v4l2_fourcc('Q', 'G', 'B', '0') -#define V4L2_PIX_FMT_QGRBG10 v4l2_fourcc('Q', 'G', 'R', '0') -#define V4L2_PIX_FMT_QRGGB10 v4l2_fourcc('Q', 'R', 'G', '0') -#define V4L2_PIX_FMT_QBGGR12 v4l2_fourcc('Q', 'B', 'G', '2') -#define V4L2_PIX_FMT_QGBRG12 v4l2_fourcc('Q', 'G', 'B', '2') -#define V4L2_PIX_FMT_QGRBG12 v4l2_fourcc('Q', 'G', 'R', '2') -#define V4L2_PIX_FMT_QRGGB12 v4l2_fourcc('Q', 'R', 'G', '2') -#define V4L2_PIX_FMT_QBGGR14 v4l2_fourcc('Q', 'B', 'G', '4') -#define V4L2_PIX_FMT_QGBRG14 v4l2_fourcc('Q', 'G', 'B', '4') -#define V4L2_PIX_FMT_QGRBG14 v4l2_fourcc('Q', 'G', 'R', '4') -#define V4L2_PIX_FMT_QRGGB14 v4l2_fourcc('Q', 'R', 'G', '4') -#define V4L2_PIX_FMT_P16BGGR10 v4l2_fourcc('P', 'B', 'G', '0') -#define V4L2_PIX_FMT_P16GBRG10 v4l2_fourcc('P', 'G', 'B', '0') -#define V4L2_PIX_FMT_P16GRBG10 v4l2_fourcc('P', 'G', 'R', '0') -#define V4L2_PIX_FMT_P16RGGB10 v4l2_fourcc('P', 'R', 'G', '0') -#define V4L2_PIX_FMT_NV14 v4l2_fourcc('N', 'V', '1', '4') -#define V4L2_PIX_FMT_NV41 v4l2_fourcc('N', 'V', '4', '1') -#define V4L2_PIX_FMT_META v4l2_fourcc('Q', 'M', 'E', 'T') -#define V4L2_PIX_FMT_SBGGR14 v4l2_fourcc('B', 'G', '1', '4') /* 14 BGBG.GRGR.*/ -#define V4L2_PIX_FMT_SGBRG14 v4l2_fourcc('G', 'B', '1', '4') /* 14 GBGB.RGRG.*/ -#define V4L2_PIX_FMT_SGRBG14 v4l2_fourcc('B', 'A', '1', '4') /* 14 GRGR.BGBG.*/ -#define V4L2_PIX_FMT_SRGGB14 v4l2_fourcc('R', 'G', '1', '4') /* 14 RGRG.GBGB.*/ - -#define VIDIOC_MSM_VFE_REG_CFG \ - _IOWR('V', BASE_VIDIOC_PRIVATE, struct msm_vfe_cfg_cmd2) - -#define VIDIOC_MSM_ISP_REQUEST_BUF \ - _IOWR('V', BASE_VIDIOC_PRIVATE+1, struct msm_isp_buf_request) - -#define VIDIOC_MSM_ISP_ENQUEUE_BUF \ - _IOWR('V', BASE_VIDIOC_PRIVATE+2, struct msm_isp_qbuf_info) - -#define VIDIOC_MSM_ISP_RELEASE_BUF \ - _IOWR('V', BASE_VIDIOC_PRIVATE+3, struct msm_isp_buf_request) - -#define VIDIOC_MSM_ISP_REQUEST_STREAM \ - _IOWR('V', BASE_VIDIOC_PRIVATE+4, struct msm_vfe_axi_stream_request_cmd) - -#define VIDIOC_MSM_ISP_CFG_STREAM \ - _IOWR('V', BASE_VIDIOC_PRIVATE+5, struct msm_vfe_axi_stream_cfg_cmd) - -#define VIDIOC_MSM_ISP_RELEASE_STREAM \ - _IOWR('V', BASE_VIDIOC_PRIVATE+6, struct msm_vfe_axi_stream_release_cmd) - -#define VIDIOC_MSM_ISP_INPUT_CFG \ - _IOWR('V', BASE_VIDIOC_PRIVATE+7, struct msm_vfe_input_cfg) - -#define VIDIOC_MSM_ISP_SET_SRC_STATE \ - _IOWR('V', BASE_VIDIOC_PRIVATE+8, struct msm_vfe_axi_src_state) - -#define VIDIOC_MSM_ISP_REQUEST_STATS_STREAM \ - _IOWR('V', BASE_VIDIOC_PRIVATE+9, \ - struct msm_vfe_stats_stream_request_cmd) - -#define VIDIOC_MSM_ISP_CFG_STATS_STREAM \ - _IOWR('V', BASE_VIDIOC_PRIVATE+10, struct msm_vfe_stats_stream_cfg_cmd) - -#define VIDIOC_MSM_ISP_RELEASE_STATS_STREAM \ - _IOWR('V', BASE_VIDIOC_PRIVATE+11, \ - struct msm_vfe_stats_stream_release_cmd) - -#define VIDIOC_MSM_ISP_REG_UPDATE_CMD \ - _IOWR('V', BASE_VIDIOC_PRIVATE+12, enum msm_vfe_input_src) - -#define VIDIOC_MSM_ISP_UPDATE_STREAM \ - _IOWR('V', BASE_VIDIOC_PRIVATE+13, struct msm_vfe_axi_stream_update_cmd) - -#define VIDIOC_MSM_VFE_REG_LIST_CFG \ - _IOWR('V', BASE_VIDIOC_PRIVATE+14, struct msm_vfe_cfg_cmd_list) - -#define VIDIOC_MSM_ISP_SMMU_ATTACH \ - _IOWR('V', BASE_VIDIOC_PRIVATE+15, struct msm_vfe_smmu_attach_cmd) - -#define VIDIOC_MSM_ISP_UPDATE_STATS_STREAM \ - _IOWR('V', BASE_VIDIOC_PRIVATE+16, struct msm_vfe_axi_stream_update_cmd) - -#define VIDIOC_MSM_ISP_AXI_HALT \ - _IOWR('V', BASE_VIDIOC_PRIVATE+17, struct msm_vfe_axi_halt_cmd) - -#define VIDIOC_MSM_ISP_AXI_RESET \ - _IOWR('V', BASE_VIDIOC_PRIVATE+18, struct msm_vfe_axi_reset_cmd) - -#define VIDIOC_MSM_ISP_AXI_RESTART \ - _IOWR('V', BASE_VIDIOC_PRIVATE+19, struct msm_vfe_axi_restart_cmd) - -#define VIDIOC_MSM_ISP_FETCH_ENG_START \ - _IOWR('V', BASE_VIDIOC_PRIVATE+20, struct msm_vfe_fetch_eng_start) - -#define VIDIOC_MSM_ISP_DEQUEUE_BUF \ - _IOWR('V', BASE_VIDIOC_PRIVATE+21, struct msm_isp_qbuf_info) - -#define VIDIOC_MSM_ISP_SET_DUAL_HW_MASTER_SLAVE \ - _IOWR('V', BASE_VIDIOC_PRIVATE+22, struct msm_isp_set_dual_hw_ms_cmd) - -#define VIDIOC_MSM_ISP_MAP_BUF_START_FE \ - _IOWR('V', BASE_VIDIOC_PRIVATE+23, struct msm_vfe_fetch_eng_start) - -#define VIDIOC_MSM_ISP_UNMAP_BUF \ - _IOWR('V', BASE_VIDIOC_PRIVATE+24, struct msm_isp_unmap_buf_req) - -#endif /* __MSMB_ISP__ */ diff --git a/third_party/linux/include/msmb_ispif.h b/third_party/linux/include/msmb_ispif.h deleted file mode 100644 index 2564c33b7b..0000000000 --- a/third_party/linux/include/msmb_ispif.h +++ /dev/null @@ -1,125 +0,0 @@ -#ifndef MSM_CAM_ISPIF_H -#define MSM_CAM_ISPIF_H - -#define CSID_VERSION_V20 0x02000011 -#define CSID_VERSION_V22 0x02001000 -#define CSID_VERSION_V30 0x30000000 -#define CSID_VERSION_V3 0x30000000 - -enum msm_ispif_vfe_intf { - VFE0, - VFE1, - VFE_MAX -}; -#define VFE0_MASK (1 << VFE0) -#define VFE1_MASK (1 << VFE1) - -enum msm_ispif_intftype { - PIX0, - RDI0, - PIX1, - RDI1, - RDI2, - INTF_MAX -}; -#define MAX_PARAM_ENTRIES (INTF_MAX * 2) -#define MAX_CID_CH 8 - -#define PIX0_MASK (1 << PIX0) -#define PIX1_MASK (1 << PIX1) -#define RDI0_MASK (1 << RDI0) -#define RDI1_MASK (1 << RDI1) -#define RDI2_MASK (1 << RDI2) - - -enum msm_ispif_vc { - VC0, - VC1, - VC2, - VC3, - VC_MAX -}; - -enum msm_ispif_cid { - CID0, - CID1, - CID2, - CID3, - CID4, - CID5, - CID6, - CID7, - CID8, - CID9, - CID10, - CID11, - CID12, - CID13, - CID14, - CID15, - CID_MAX -}; - -enum msm_ispif_csid { - CSID0, - CSID1, - CSID2, - CSID3, - CSID_MAX -}; - -struct msm_ispif_params_entry { - enum msm_ispif_vfe_intf vfe_intf; - enum msm_ispif_intftype intftype; - int num_cids; - enum msm_ispif_cid cids[3]; - enum msm_ispif_csid csid; - int crop_enable; - uint16_t crop_start_pixel; - uint16_t crop_end_pixel; -}; - -struct msm_ispif_param_data { - uint32_t num; - struct msm_ispif_params_entry entries[MAX_PARAM_ENTRIES]; -}; - -struct msm_isp_info { - uint32_t max_resolution; - uint32_t id; - uint32_t ver; -}; - -struct msm_ispif_vfe_info { - int num_vfe; - struct msm_isp_info info[VFE_MAX]; -}; - -enum ispif_cfg_type_t { - ISPIF_CLK_ENABLE, - ISPIF_CLK_DISABLE, - ISPIF_INIT, - ISPIF_CFG, - ISPIF_START_FRAME_BOUNDARY, - ISPIF_RESTART_FRAME_BOUNDARY, - ISPIF_STOP_FRAME_BOUNDARY, - ISPIF_STOP_IMMEDIATELY, - ISPIF_RELEASE, - ISPIF_ENABLE_REG_DUMP, - ISPIF_SET_VFE_INFO, -}; - -struct ispif_cfg_data { - enum ispif_cfg_type_t cfg_type; - union { - int reg_dump; /* ISPIF_ENABLE_REG_DUMP */ - uint32_t csid_version; /* ISPIF_INIT */ - struct msm_ispif_vfe_info vfe_info; /* ISPIF_SET_VFE_INFO */ - struct msm_ispif_param_data params; /* CFG, START, STOP */ - }; -}; - -#define VIDIOC_MSM_ISPIF_CFG \ - _IOWR('V', BASE_VIDIOC_PRIVATE, struct ispif_cfg_data) - -#endif /* MSM_CAM_ISPIF_H */ diff --git a/third_party/linux/include/v4l2-controls.h b/third_party/linux/include/v4l2-controls.h deleted file mode 100644 index d14cd8fabe..0000000000 --- a/third_party/linux/include/v4l2-controls.h +++ /dev/null @@ -1,1696 +0,0 @@ -/* - * Video for Linux Two controls header file - * - * Copyright (C) 1999-2012 the contributors - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * Alternatively you can redistribute this file under the terms of the - * BSD license as stated below: - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * 3. The names of its contributors may not 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 - * OWNER 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. - * - * The contents of this header was split off from videodev2.h. All control - * definitions should be added to this header, which is included by - * videodev2.h. - */ - -#ifndef __LINUX_V4L2_CONTROLS_H -#define __LINUX_V4L2_CONTROLS_H - -/* Control classes */ -#define V4L2_CTRL_CLASS_USER 0x00980000 /* Old-style 'user' controls */ -#define V4L2_CTRL_CLASS_MPEG 0x00990000 /* MPEG-compression controls */ -#define V4L2_CTRL_CLASS_CAMERA 0x009a0000 /* Camera class controls */ -#define V4L2_CTRL_CLASS_FM_TX 0x009b0000 /* FM Modulator controls */ -#define V4L2_CTRL_CLASS_FLASH 0x009c0000 /* Camera flash controls */ -#define V4L2_CTRL_CLASS_JPEG 0x009d0000 /* JPEG-compression controls */ -#define V4L2_CTRL_CLASS_IMAGE_SOURCE 0x009e0000 /* Image source controls */ -#define V4L2_CTRL_CLASS_IMAGE_PROC 0x009f0000 /* Image processing controls */ -#define V4L2_CTRL_CLASS_DV 0x00a00000 /* Digital Video controls */ -#define V4L2_CTRL_CLASS_FM_RX 0x00a10000 /* FM Receiver controls */ -#define V4L2_CTRL_CLASS_RF_TUNER 0x00a20000 /* RF tuner controls */ -#define V4L2_CTRL_CLASS_DETECT 0x00a30000 /* Detection controls */ - -/* User-class control IDs */ - -#define V4L2_CID_BASE (V4L2_CTRL_CLASS_USER | 0x900) -#define V4L2_CID_USER_BASE V4L2_CID_BASE -#define V4L2_CID_USER_CLASS (V4L2_CTRL_CLASS_USER | 1) -#define V4L2_CID_BRIGHTNESS (V4L2_CID_BASE+0) -#define V4L2_CID_CONTRAST (V4L2_CID_BASE+1) -#define V4L2_CID_SATURATION (V4L2_CID_BASE+2) -#define V4L2_CID_HUE (V4L2_CID_BASE+3) -#define V4L2_CID_AUDIO_VOLUME (V4L2_CID_BASE+5) -#define V4L2_CID_AUDIO_BALANCE (V4L2_CID_BASE+6) -#define V4L2_CID_AUDIO_BASS (V4L2_CID_BASE+7) -#define V4L2_CID_AUDIO_TREBLE (V4L2_CID_BASE+8) -#define V4L2_CID_AUDIO_MUTE (V4L2_CID_BASE+9) -#define V4L2_CID_AUDIO_LOUDNESS (V4L2_CID_BASE+10) -#define V4L2_CID_BLACK_LEVEL (V4L2_CID_BASE+11) /* Deprecated */ -#define V4L2_CID_AUTO_WHITE_BALANCE (V4L2_CID_BASE+12) -#define V4L2_CID_DO_WHITE_BALANCE (V4L2_CID_BASE+13) -#define V4L2_CID_RED_BALANCE (V4L2_CID_BASE+14) -#define V4L2_CID_BLUE_BALANCE (V4L2_CID_BASE+15) -#define V4L2_CID_GAMMA (V4L2_CID_BASE+16) -#define V4L2_CID_WHITENESS (V4L2_CID_GAMMA) /* Deprecated */ -#define V4L2_CID_EXPOSURE (V4L2_CID_BASE+17) -#define V4L2_CID_AUTOGAIN (V4L2_CID_BASE+18) -#define V4L2_CID_GAIN (V4L2_CID_BASE+19) -#define V4L2_CID_HFLIP (V4L2_CID_BASE+20) -#define V4L2_CID_VFLIP (V4L2_CID_BASE+21) - -#define V4L2_CID_POWER_LINE_FREQUENCY (V4L2_CID_BASE+24) -enum v4l2_power_line_frequency { - V4L2_CID_POWER_LINE_FREQUENCY_DISABLED = 0, - V4L2_CID_POWER_LINE_FREQUENCY_50HZ = 1, - V4L2_CID_POWER_LINE_FREQUENCY_60HZ = 2, - V4L2_CID_POWER_LINE_FREQUENCY_AUTO = 3, -}; -#define V4L2_CID_HUE_AUTO (V4L2_CID_BASE+25) -#define V4L2_CID_WHITE_BALANCE_TEMPERATURE (V4L2_CID_BASE+26) -#define V4L2_CID_SHARPNESS (V4L2_CID_BASE+27) -#define V4L2_CID_BACKLIGHT_COMPENSATION (V4L2_CID_BASE+28) -#define V4L2_CID_CHROMA_AGC (V4L2_CID_BASE+29) -#define V4L2_CID_COLOR_KILLER (V4L2_CID_BASE+30) -#define V4L2_CID_COLORFX (V4L2_CID_BASE+31) -enum v4l2_colorfx { - V4L2_COLORFX_NONE = 0, - V4L2_COLORFX_BW = 1, - V4L2_COLORFX_SEPIA = 2, - V4L2_COLORFX_NEGATIVE = 3, - V4L2_COLORFX_EMBOSS = 4, - V4L2_COLORFX_SKETCH = 5, - V4L2_COLORFX_SKY_BLUE = 6, - V4L2_COLORFX_GRASS_GREEN = 7, - V4L2_COLORFX_SKIN_WHITEN = 8, - V4L2_COLORFX_VIVID = 9, - V4L2_COLORFX_AQUA = 10, - V4L2_COLORFX_ART_FREEZE = 11, - V4L2_COLORFX_SILHOUETTE = 12, - V4L2_COLORFX_SOLARIZATION = 13, - V4L2_COLORFX_ANTIQUE = 14, - V4L2_COLORFX_SET_CBCR = 15, -}; -#define V4L2_CID_AUTOBRIGHTNESS (V4L2_CID_BASE+32) -#define V4L2_CID_BAND_STOP_FILTER (V4L2_CID_BASE+33) - -#define V4L2_CID_ROTATE (V4L2_CID_BASE+34) -#define V4L2_CID_BG_COLOR (V4L2_CID_BASE+35) - -#define V4L2_CID_CHROMA_GAIN (V4L2_CID_BASE+36) - -#define V4L2_CID_ILLUMINATORS_1 (V4L2_CID_BASE+37) -#define V4L2_CID_ILLUMINATORS_2 (V4L2_CID_BASE+38) - -#define V4L2_CID_MIN_BUFFERS_FOR_CAPTURE (V4L2_CID_BASE+39) -#define V4L2_CID_MIN_BUFFERS_FOR_OUTPUT (V4L2_CID_BASE+40) - -#define V4L2_CID_ALPHA_COMPONENT (V4L2_CID_BASE+41) -#define V4L2_CID_COLORFX_CBCR (V4L2_CID_BASE+42) - -/* last CID + 1 */ -#define V4L2_CID_LASTP1 (V4L2_CID_BASE+43) - -/* USER-class private control IDs */ - -/* The base for the meye driver controls. See linux/meye.h for the list - * of controls. We reserve 16 controls for this driver. */ -#define V4L2_CID_USER_MEYE_BASE (V4L2_CID_USER_BASE + 0x1000) - -/* The base for the bttv driver controls. - * We reserve 32 controls for this driver. */ -#define V4L2_CID_USER_BTTV_BASE (V4L2_CID_USER_BASE + 0x1010) - - -/* The base for the s2255 driver controls. - * We reserve 16 controls for this driver. */ -#define V4L2_CID_USER_S2255_BASE (V4L2_CID_USER_BASE + 0x1030) - -/* - * The base for the si476x driver controls. See include/media/drv-intf/si476x.h - * for the list of controls. Total of 16 controls is reserved for this driver - */ -#define V4L2_CID_USER_SI476X_BASE (V4L2_CID_USER_BASE + 0x1040) - -/* The base for the TI VPE driver controls. Total of 16 controls is reserved for - * this driver */ -#define V4L2_CID_USER_TI_VPE_BASE (V4L2_CID_USER_BASE + 0x1050) - -/* The base for the saa7134 driver controls. - * We reserve 16 controls for this driver. */ -#define V4L2_CID_USER_SAA7134_BASE (V4L2_CID_USER_BASE + 0x1060) - -/* The base for the adv7180 driver controls. - * We reserve 16 controls for this driver. */ -#define V4L2_CID_USER_ADV7180_BASE (V4L2_CID_USER_BASE + 0x1070) - -/* The base for the tc358743 driver controls. - * We reserve 16 controls for this driver. */ -#define V4L2_CID_USER_TC358743_BASE (V4L2_CID_USER_BASE + 0x1080) - -/* MPEG-class control IDs */ -/* The MPEG controls are applicable to all codec controls - * and the 'MPEG' part of the define is historical */ - -#define V4L2_CID_MPEG_BASE (V4L2_CTRL_CLASS_MPEG | 0x900) -#define V4L2_CID_MPEG_CLASS (V4L2_CTRL_CLASS_MPEG | 1) - -/* MPEG streams, specific to multiplexed streams */ -#define V4L2_CID_MPEG_STREAM_TYPE (V4L2_CID_MPEG_BASE+0) -enum v4l2_mpeg_stream_type { - V4L2_MPEG_STREAM_TYPE_MPEG2_PS = 0, /* MPEG-2 program stream */ - V4L2_MPEG_STREAM_TYPE_MPEG2_TS = 1, /* MPEG-2 transport stream */ - V4L2_MPEG_STREAM_TYPE_MPEG1_SS = 2, /* MPEG-1 system stream */ - V4L2_MPEG_STREAM_TYPE_MPEG2_DVD = 3, /* MPEG-2 DVD-compatible stream */ - V4L2_MPEG_STREAM_TYPE_MPEG1_VCD = 4, /* MPEG-1 VCD-compatible stream */ - V4L2_MPEG_STREAM_TYPE_MPEG2_SVCD = 5, /* MPEG-2 SVCD-compatible stream */ -}; -#define V4L2_CID_MPEG_STREAM_PID_PMT (V4L2_CID_MPEG_BASE+1) -#define V4L2_CID_MPEG_STREAM_PID_AUDIO (V4L2_CID_MPEG_BASE+2) -#define V4L2_CID_MPEG_STREAM_PID_VIDEO (V4L2_CID_MPEG_BASE+3) -#define V4L2_CID_MPEG_STREAM_PID_PCR (V4L2_CID_MPEG_BASE+4) -#define V4L2_CID_MPEG_STREAM_PES_ID_AUDIO (V4L2_CID_MPEG_BASE+5) -#define V4L2_CID_MPEG_STREAM_PES_ID_VIDEO (V4L2_CID_MPEG_BASE+6) -#define V4L2_CID_MPEG_STREAM_VBI_FMT (V4L2_CID_MPEG_BASE+7) -enum v4l2_mpeg_stream_vbi_fmt { - V4L2_MPEG_STREAM_VBI_FMT_NONE = 0, /* No VBI in the MPEG stream */ - V4L2_MPEG_STREAM_VBI_FMT_IVTV = 1, /* VBI in private packets, IVTV format */ -}; - -/* MPEG audio controls specific to multiplexed streams */ -#define V4L2_CID_MPEG_AUDIO_SAMPLING_FREQ (V4L2_CID_MPEG_BASE+100) -enum v4l2_mpeg_audio_sampling_freq { - V4L2_MPEG_AUDIO_SAMPLING_FREQ_44100 = 0, - V4L2_MPEG_AUDIO_SAMPLING_FREQ_48000 = 1, - V4L2_MPEG_AUDIO_SAMPLING_FREQ_32000 = 2, -}; -#define V4L2_CID_MPEG_AUDIO_ENCODING (V4L2_CID_MPEG_BASE+101) -enum v4l2_mpeg_audio_encoding { - V4L2_MPEG_AUDIO_ENCODING_LAYER_1 = 0, - V4L2_MPEG_AUDIO_ENCODING_LAYER_2 = 1, - V4L2_MPEG_AUDIO_ENCODING_LAYER_3 = 2, - V4L2_MPEG_AUDIO_ENCODING_AAC = 3, - V4L2_MPEG_AUDIO_ENCODING_AC3 = 4, -}; -#define V4L2_CID_MPEG_AUDIO_L1_BITRATE (V4L2_CID_MPEG_BASE+102) -enum v4l2_mpeg_audio_l1_bitrate { - V4L2_MPEG_AUDIO_L1_BITRATE_32K = 0, - V4L2_MPEG_AUDIO_L1_BITRATE_64K = 1, - V4L2_MPEG_AUDIO_L1_BITRATE_96K = 2, - V4L2_MPEG_AUDIO_L1_BITRATE_128K = 3, - V4L2_MPEG_AUDIO_L1_BITRATE_160K = 4, - V4L2_MPEG_AUDIO_L1_BITRATE_192K = 5, - V4L2_MPEG_AUDIO_L1_BITRATE_224K = 6, - V4L2_MPEG_AUDIO_L1_BITRATE_256K = 7, - V4L2_MPEG_AUDIO_L1_BITRATE_288K = 8, - V4L2_MPEG_AUDIO_L1_BITRATE_320K = 9, - V4L2_MPEG_AUDIO_L1_BITRATE_352K = 10, - V4L2_MPEG_AUDIO_L1_BITRATE_384K = 11, - V4L2_MPEG_AUDIO_L1_BITRATE_416K = 12, - V4L2_MPEG_AUDIO_L1_BITRATE_448K = 13, -}; -#define V4L2_CID_MPEG_AUDIO_L2_BITRATE (V4L2_CID_MPEG_BASE+103) -enum v4l2_mpeg_audio_l2_bitrate { - V4L2_MPEG_AUDIO_L2_BITRATE_32K = 0, - V4L2_MPEG_AUDIO_L2_BITRATE_48K = 1, - V4L2_MPEG_AUDIO_L2_BITRATE_56K = 2, - V4L2_MPEG_AUDIO_L2_BITRATE_64K = 3, - V4L2_MPEG_AUDIO_L2_BITRATE_80K = 4, - V4L2_MPEG_AUDIO_L2_BITRATE_96K = 5, - V4L2_MPEG_AUDIO_L2_BITRATE_112K = 6, - V4L2_MPEG_AUDIO_L2_BITRATE_128K = 7, - V4L2_MPEG_AUDIO_L2_BITRATE_160K = 8, - V4L2_MPEG_AUDIO_L2_BITRATE_192K = 9, - V4L2_MPEG_AUDIO_L2_BITRATE_224K = 10, - V4L2_MPEG_AUDIO_L2_BITRATE_256K = 11, - V4L2_MPEG_AUDIO_L2_BITRATE_320K = 12, - V4L2_MPEG_AUDIO_L2_BITRATE_384K = 13, -}; -#define V4L2_CID_MPEG_AUDIO_L3_BITRATE (V4L2_CID_MPEG_BASE+104) -enum v4l2_mpeg_audio_l3_bitrate { - V4L2_MPEG_AUDIO_L3_BITRATE_32K = 0, - V4L2_MPEG_AUDIO_L3_BITRATE_40K = 1, - V4L2_MPEG_AUDIO_L3_BITRATE_48K = 2, - V4L2_MPEG_AUDIO_L3_BITRATE_56K = 3, - V4L2_MPEG_AUDIO_L3_BITRATE_64K = 4, - V4L2_MPEG_AUDIO_L3_BITRATE_80K = 5, - V4L2_MPEG_AUDIO_L3_BITRATE_96K = 6, - V4L2_MPEG_AUDIO_L3_BITRATE_112K = 7, - V4L2_MPEG_AUDIO_L3_BITRATE_128K = 8, - V4L2_MPEG_AUDIO_L3_BITRATE_160K = 9, - V4L2_MPEG_AUDIO_L3_BITRATE_192K = 10, - V4L2_MPEG_AUDIO_L3_BITRATE_224K = 11, - V4L2_MPEG_AUDIO_L3_BITRATE_256K = 12, - V4L2_MPEG_AUDIO_L3_BITRATE_320K = 13, -}; -#define V4L2_CID_MPEG_AUDIO_MODE (V4L2_CID_MPEG_BASE+105) -enum v4l2_mpeg_audio_mode { - V4L2_MPEG_AUDIO_MODE_STEREO = 0, - V4L2_MPEG_AUDIO_MODE_JOINT_STEREO = 1, - V4L2_MPEG_AUDIO_MODE_DUAL = 2, - V4L2_MPEG_AUDIO_MODE_MONO = 3, -}; -#define V4L2_CID_MPEG_AUDIO_MODE_EXTENSION (V4L2_CID_MPEG_BASE+106) -enum v4l2_mpeg_audio_mode_extension { - V4L2_MPEG_AUDIO_MODE_EXTENSION_BOUND_4 = 0, - V4L2_MPEG_AUDIO_MODE_EXTENSION_BOUND_8 = 1, - V4L2_MPEG_AUDIO_MODE_EXTENSION_BOUND_12 = 2, - V4L2_MPEG_AUDIO_MODE_EXTENSION_BOUND_16 = 3, -}; -#define V4L2_CID_MPEG_AUDIO_EMPHASIS (V4L2_CID_MPEG_BASE+107) -enum v4l2_mpeg_audio_emphasis { - V4L2_MPEG_AUDIO_EMPHASIS_NONE = 0, - V4L2_MPEG_AUDIO_EMPHASIS_50_DIV_15_uS = 1, - V4L2_MPEG_AUDIO_EMPHASIS_CCITT_J17 = 2, -}; -#define V4L2_CID_MPEG_AUDIO_CRC (V4L2_CID_MPEG_BASE+108) -enum v4l2_mpeg_audio_crc { - V4L2_MPEG_AUDIO_CRC_NONE = 0, - V4L2_MPEG_AUDIO_CRC_CRC16 = 1, -}; -#define V4L2_CID_MPEG_AUDIO_MUTE (V4L2_CID_MPEG_BASE+109) -#define V4L2_CID_MPEG_AUDIO_AAC_BITRATE (V4L2_CID_MPEG_BASE+110) -#define V4L2_CID_MPEG_AUDIO_AC3_BITRATE (V4L2_CID_MPEG_BASE+111) -enum v4l2_mpeg_audio_ac3_bitrate { - V4L2_MPEG_AUDIO_AC3_BITRATE_32K = 0, - V4L2_MPEG_AUDIO_AC3_BITRATE_40K = 1, - V4L2_MPEG_AUDIO_AC3_BITRATE_48K = 2, - V4L2_MPEG_AUDIO_AC3_BITRATE_56K = 3, - V4L2_MPEG_AUDIO_AC3_BITRATE_64K = 4, - V4L2_MPEG_AUDIO_AC3_BITRATE_80K = 5, - V4L2_MPEG_AUDIO_AC3_BITRATE_96K = 6, - V4L2_MPEG_AUDIO_AC3_BITRATE_112K = 7, - V4L2_MPEG_AUDIO_AC3_BITRATE_128K = 8, - V4L2_MPEG_AUDIO_AC3_BITRATE_160K = 9, - V4L2_MPEG_AUDIO_AC3_BITRATE_192K = 10, - V4L2_MPEG_AUDIO_AC3_BITRATE_224K = 11, - V4L2_MPEG_AUDIO_AC3_BITRATE_256K = 12, - V4L2_MPEG_AUDIO_AC3_BITRATE_320K = 13, - V4L2_MPEG_AUDIO_AC3_BITRATE_384K = 14, - V4L2_MPEG_AUDIO_AC3_BITRATE_448K = 15, - V4L2_MPEG_AUDIO_AC3_BITRATE_512K = 16, - V4L2_MPEG_AUDIO_AC3_BITRATE_576K = 17, - V4L2_MPEG_AUDIO_AC3_BITRATE_640K = 18, -}; -#define V4L2_CID_MPEG_AUDIO_DEC_PLAYBACK (V4L2_CID_MPEG_BASE+112) -enum v4l2_mpeg_audio_dec_playback { - V4L2_MPEG_AUDIO_DEC_PLAYBACK_AUTO = 0, - V4L2_MPEG_AUDIO_DEC_PLAYBACK_STEREO = 1, - V4L2_MPEG_AUDIO_DEC_PLAYBACK_LEFT = 2, - V4L2_MPEG_AUDIO_DEC_PLAYBACK_RIGHT = 3, - V4L2_MPEG_AUDIO_DEC_PLAYBACK_MONO = 4, - V4L2_MPEG_AUDIO_DEC_PLAYBACK_SWAPPED_STEREO = 5, -}; -#define V4L2_CID_MPEG_AUDIO_DEC_MULTILINGUAL_PLAYBACK (V4L2_CID_MPEG_BASE+113) - -/* MPEG video controls specific to multiplexed streams */ -#define V4L2_CID_MPEG_VIDEO_ENCODING (V4L2_CID_MPEG_BASE+200) -enum v4l2_mpeg_video_encoding { - V4L2_MPEG_VIDEO_ENCODING_MPEG_1 = 0, - V4L2_MPEG_VIDEO_ENCODING_MPEG_2 = 1, - V4L2_MPEG_VIDEO_ENCODING_MPEG_4_AVC = 2, -}; -#define V4L2_CID_MPEG_VIDEO_ASPECT (V4L2_CID_MPEG_BASE+201) -enum v4l2_mpeg_video_aspect { - V4L2_MPEG_VIDEO_ASPECT_1x1 = 0, - V4L2_MPEG_VIDEO_ASPECT_4x3 = 1, - V4L2_MPEG_VIDEO_ASPECT_16x9 = 2, - V4L2_MPEG_VIDEO_ASPECT_221x100 = 3, -}; -#define V4L2_CID_MPEG_VIDEO_B_FRAMES (V4L2_CID_MPEG_BASE+202) -#define V4L2_CID_MPEG_VIDEO_GOP_SIZE (V4L2_CID_MPEG_BASE+203) -#define V4L2_CID_MPEG_VIDEO_GOP_CLOSURE (V4L2_CID_MPEG_BASE+204) -#define V4L2_CID_MPEG_VIDEO_PULLDOWN (V4L2_CID_MPEG_BASE+205) -#define V4L2_CID_MPEG_VIDEO_BITRATE_MODE (V4L2_CID_MPEG_BASE+206) -enum v4l2_mpeg_video_bitrate_mode { - V4L2_MPEG_VIDEO_BITRATE_MODE_VBR = 0, - V4L2_MPEG_VIDEO_BITRATE_MODE_CBR = 1, -}; -#define V4L2_CID_MPEG_VIDEO_BITRATE (V4L2_CID_MPEG_BASE+207) -#define V4L2_CID_MPEG_VIDEO_BITRATE_PEAK (V4L2_CID_MPEG_BASE+208) -#define V4L2_CID_MPEG_VIDEO_TEMPORAL_DECIMATION (V4L2_CID_MPEG_BASE+209) -#define V4L2_CID_MPEG_VIDEO_MUTE (V4L2_CID_MPEG_BASE+210) -#define V4L2_CID_MPEG_VIDEO_MUTE_YUV (V4L2_CID_MPEG_BASE+211) -#define V4L2_CID_MPEG_VIDEO_DECODER_SLICE_INTERFACE (V4L2_CID_MPEG_BASE+212) -#define V4L2_CID_MPEG_VIDEO_DECODER_MPEG4_DEBLOCK_FILTER (V4L2_CID_MPEG_BASE+213) -#define V4L2_CID_MPEG_VIDEO_CYCLIC_INTRA_REFRESH_MB (V4L2_CID_MPEG_BASE+214) -#define V4L2_CID_MPEG_VIDEO_FRAME_RC_ENABLE (V4L2_CID_MPEG_BASE+215) -#define V4L2_CID_MPEG_VIDEO_HEADER_MODE (V4L2_CID_MPEG_BASE+216) -enum v4l2_mpeg_video_header_mode { - V4L2_MPEG_VIDEO_HEADER_MODE_SEPARATE = 0, - V4L2_MPEG_VIDEO_HEADER_MODE_JOINED_WITH_1ST_FRAME = 1, - V4L2_MPEG_VIDEO_HEADER_MODE_JOINED_WITH_I_FRAME = 2, -}; -#define V4L2_CID_MPEG_VIDEO_MAX_REF_PIC (V4L2_CID_MPEG_BASE+217) -#define V4L2_CID_MPEG_VIDEO_MB_RC_ENABLE (V4L2_CID_MPEG_BASE+218) -#define V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_BYTES (V4L2_CID_MPEG_BASE+219) -#define V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_MB (V4L2_CID_MPEG_BASE+220) -#define V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MODE (V4L2_CID_MPEG_BASE+221) -enum v4l2_mpeg_video_multi_slice_mode { - V4L2_MPEG_VIDEO_MULTI_SLICE_MODE_SINGLE = 0, - V4L2_MPEG_VIDEO_MULTI_SICE_MODE_MAX_MB = 1, - V4L2_MPEG_VIDEO_MULTI_SICE_MODE_MAX_BYTES = 2, - V4L2_MPEG_VIDEO_MULTI_SLICE_GOB = 3, -}; -#define V4L2_CID_MPEG_VIDEO_VBV_SIZE (V4L2_CID_MPEG_BASE+222) -#define V4L2_CID_MPEG_VIDEO_DEC_PTS (V4L2_CID_MPEG_BASE+223) -#define V4L2_CID_MPEG_VIDEO_DEC_FRAME (V4L2_CID_MPEG_BASE+224) -#define V4L2_CID_MPEG_VIDEO_VBV_DELAY (V4L2_CID_MPEG_BASE+225) -#define V4L2_CID_MPEG_VIDEO_REPEAT_SEQ_HEADER (V4L2_CID_MPEG_BASE+226) -#define V4L2_CID_MPEG_VIDEO_MV_H_SEARCH_RANGE (V4L2_CID_MPEG_BASE+227) -#define V4L2_CID_MPEG_VIDEO_MV_V_SEARCH_RANGE (V4L2_CID_MPEG_BASE+228) -#define V4L2_CID_MPEG_VIDEO_FORCE_KEY_FRAME (V4L2_CID_MPEG_BASE+229) - -#define V4L2_CID_MPEG_VIDEO_H263_I_FRAME_QP (V4L2_CID_MPEG_BASE+300) -#define V4L2_CID_MPEG_VIDEO_H263_P_FRAME_QP (V4L2_CID_MPEG_BASE+301) -#define V4L2_CID_MPEG_VIDEO_H263_B_FRAME_QP (V4L2_CID_MPEG_BASE+302) -#define V4L2_CID_MPEG_VIDEO_H263_MIN_QP (V4L2_CID_MPEG_BASE+303) -#define V4L2_CID_MPEG_VIDEO_H263_MAX_QP (V4L2_CID_MPEG_BASE+304) -#define V4L2_CID_MPEG_VIDEO_H264_I_FRAME_QP (V4L2_CID_MPEG_BASE+350) -#define V4L2_CID_MPEG_VIDEO_H264_P_FRAME_QP (V4L2_CID_MPEG_BASE+351) -#define V4L2_CID_MPEG_VIDEO_H264_B_FRAME_QP (V4L2_CID_MPEG_BASE+352) -#define V4L2_CID_MPEG_VIDEO_H264_MIN_QP (V4L2_CID_MPEG_BASE+353) -#define V4L2_CID_MPEG_VIDEO_H264_MAX_QP (V4L2_CID_MPEG_BASE+354) -#define V4L2_CID_MPEG_VIDEO_H264_8X8_TRANSFORM (V4L2_CID_MPEG_BASE+355) -#define V4L2_CID_MPEG_VIDEO_H264_CPB_SIZE (V4L2_CID_MPEG_BASE+356) -#define V4L2_CID_MPEG_VIDEO_H264_ENTROPY_MODE (V4L2_CID_MPEG_BASE+357) -enum v4l2_mpeg_video_h264_entropy_mode { - V4L2_MPEG_VIDEO_H264_ENTROPY_MODE_CAVLC = 0, - V4L2_MPEG_VIDEO_H264_ENTROPY_MODE_CABAC = 1, -}; -#define V4L2_CID_MPEG_VIDEO_H264_I_PERIOD (V4L2_CID_MPEG_BASE+358) -#define V4L2_CID_MPEG_VIDEO_H264_LEVEL (V4L2_CID_MPEG_BASE+359) -enum v4l2_mpeg_video_h264_level { - V4L2_MPEG_VIDEO_H264_LEVEL_1_0 = 0, - V4L2_MPEG_VIDEO_H264_LEVEL_1B = 1, - V4L2_MPEG_VIDEO_H264_LEVEL_1_1 = 2, - V4L2_MPEG_VIDEO_H264_LEVEL_1_2 = 3, - V4L2_MPEG_VIDEO_H264_LEVEL_1_3 = 4, - V4L2_MPEG_VIDEO_H264_LEVEL_2_0 = 5, - V4L2_MPEG_VIDEO_H264_LEVEL_2_1 = 6, - V4L2_MPEG_VIDEO_H264_LEVEL_2_2 = 7, - V4L2_MPEG_VIDEO_H264_LEVEL_3_0 = 8, - V4L2_MPEG_VIDEO_H264_LEVEL_3_1 = 9, - V4L2_MPEG_VIDEO_H264_LEVEL_3_2 = 10, - V4L2_MPEG_VIDEO_H264_LEVEL_4_0 = 11, - V4L2_MPEG_VIDEO_H264_LEVEL_4_1 = 12, - V4L2_MPEG_VIDEO_H264_LEVEL_4_2 = 13, - V4L2_MPEG_VIDEO_H264_LEVEL_5_0 = 14, - V4L2_MPEG_VIDEO_H264_LEVEL_5_1 = 15, - V4L2_MPEG_VIDEO_H264_LEVEL_5_2 = 16, -#define V4L2_MPEG_VIDEO_H264_LEVEL_UNKNOWN \ - V4L2_MPEG_VIDEO_H264_LEVEL_UNKNOWN - V4L2_MPEG_VIDEO_H264_LEVEL_UNKNOWN = 17, -}; -#define V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_ALPHA (V4L2_CID_MPEG_BASE+360) -#define V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_BETA (V4L2_CID_MPEG_BASE+361) -#define V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_MODE (V4L2_CID_MPEG_BASE+362) -enum v4l2_mpeg_video_h264_loop_filter_mode { - V4L2_MPEG_VIDEO_H264_LOOP_FILTER_MODE_ENABLED = 0, - V4L2_MPEG_VIDEO_H264_LOOP_FILTER_MODE_DISABLED = 1, - V4L2_MPEG_VIDEO_H264_LOOP_FILTER_MODE_DISABLED_AT_SLICE_BOUNDARY = 2, -}; -#define V4L2_CID_MPEG_VIDEO_H264_PROFILE (V4L2_CID_MPEG_BASE+363) -enum v4l2_mpeg_video_h264_profile { - V4L2_MPEG_VIDEO_H264_PROFILE_BASELINE = 0, - V4L2_MPEG_VIDEO_H264_PROFILE_CONSTRAINED_BASELINE = 1, - V4L2_MPEG_VIDEO_H264_PROFILE_MAIN = 2, - V4L2_MPEG_VIDEO_H264_PROFILE_EXTENDED = 3, - V4L2_MPEG_VIDEO_H264_PROFILE_HIGH = 4, - V4L2_MPEG_VIDEO_H264_PROFILE_HIGH_10 = 5, - V4L2_MPEG_VIDEO_H264_PROFILE_HIGH_422 = 6, - V4L2_MPEG_VIDEO_H264_PROFILE_HIGH_444_PREDICTIVE = 7, - V4L2_MPEG_VIDEO_H264_PROFILE_HIGH_10_INTRA = 8, - V4L2_MPEG_VIDEO_H264_PROFILE_HIGH_422_INTRA = 9, - V4L2_MPEG_VIDEO_H264_PROFILE_HIGH_444_INTRA = 10, - V4L2_MPEG_VIDEO_H264_PROFILE_CAVLC_444_INTRA = 11, - V4L2_MPEG_VIDEO_H264_PROFILE_SCALABLE_BASELINE = 12, - V4L2_MPEG_VIDEO_H264_PROFILE_SCALABLE_HIGH = 13, - V4L2_MPEG_VIDEO_H264_PROFILE_SCALABLE_HIGH_INTRA = 14, - V4L2_MPEG_VIDEO_H264_PROFILE_STEREO_HIGH = 15, - V4L2_MPEG_VIDEO_H264_PROFILE_MULTIVIEW_HIGH = 16, - V4L2_MPEG_VIDEO_H264_PROFILE_CONSTRAINED_HIGH = 17, -}; -#define V4L2_CID_MPEG_VIDEO_H264_VUI_EXT_SAR_HEIGHT (V4L2_CID_MPEG_BASE+364) -#define V4L2_CID_MPEG_VIDEO_H264_VUI_EXT_SAR_WIDTH (V4L2_CID_MPEG_BASE+365) -#define V4L2_CID_MPEG_VIDEO_H264_VUI_SAR_ENABLE (V4L2_CID_MPEG_BASE+366) -#define V4L2_CID_MPEG_VIDEO_H264_VUI_SAR_IDC (V4L2_CID_MPEG_BASE+367) -enum v4l2_mpeg_video_h264_vui_sar_idc { - V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_UNSPECIFIED = 0, - V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_1x1 = 1, - V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_12x11 = 2, - V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_10x11 = 3, - V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_16x11 = 4, - V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_40x33 = 5, - V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_24x11 = 6, - V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_20x11 = 7, - V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_32x11 = 8, - V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_80x33 = 9, - V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_18x11 = 10, - V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_15x11 = 11, - V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_64x33 = 12, - V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_160x99 = 13, - V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_4x3 = 14, - V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_3x2 = 15, - V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_2x1 = 16, - V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_EXTENDED = 17, -}; -#define V4L2_CID_MPEG_VIDEO_H264_SEI_FRAME_PACKING (V4L2_CID_MPEG_BASE+368) -#define V4L2_CID_MPEG_VIDEO_H264_SEI_FP_CURRENT_FRAME_0 (V4L2_CID_MPEG_BASE+369) -#define V4L2_CID_MPEG_VIDEO_H264_SEI_FP_ARRANGEMENT_TYPE (V4L2_CID_MPEG_BASE+370) -enum v4l2_mpeg_video_h264_sei_fp_arrangement_type { - V4L2_MPEG_VIDEO_H264_SEI_FP_ARRANGEMENT_TYPE_CHECKERBOARD = 0, - V4L2_MPEG_VIDEO_H264_SEI_FP_ARRANGEMENT_TYPE_COLUMN = 1, - V4L2_MPEG_VIDEO_H264_SEI_FP_ARRANGEMENT_TYPE_ROW = 2, - V4L2_MPEG_VIDEO_H264_SEI_FP_ARRANGEMENT_TYPE_SIDE_BY_SIDE = 3, - V4L2_MPEG_VIDEO_H264_SEI_FP_ARRANGEMENT_TYPE_TOP_BOTTOM = 4, - V4L2_MPEG_VIDEO_H264_SEI_FP_ARRANGEMENT_TYPE_TEMPORAL = 5, -}; -#define V4L2_CID_MPEG_VIDEO_H264_FMO (V4L2_CID_MPEG_BASE+371) -#define V4L2_CID_MPEG_VIDEO_H264_FMO_MAP_TYPE (V4L2_CID_MPEG_BASE+372) -enum v4l2_mpeg_video_h264_fmo_map_type { - V4L2_MPEG_VIDEO_H264_FMO_MAP_TYPE_INTERLEAVED_SLICES = 0, - V4L2_MPEG_VIDEO_H264_FMO_MAP_TYPE_SCATTERED_SLICES = 1, - V4L2_MPEG_VIDEO_H264_FMO_MAP_TYPE_FOREGROUND_WITH_LEFT_OVER = 2, - V4L2_MPEG_VIDEO_H264_FMO_MAP_TYPE_BOX_OUT = 3, - V4L2_MPEG_VIDEO_H264_FMO_MAP_TYPE_RASTER_SCAN = 4, - V4L2_MPEG_VIDEO_H264_FMO_MAP_TYPE_WIPE_SCAN = 5, - V4L2_MPEG_VIDEO_H264_FMO_MAP_TYPE_EXPLICIT = 6, -}; -#define V4L2_CID_MPEG_VIDEO_H264_FMO_SLICE_GROUP (V4L2_CID_MPEG_BASE+373) -#define V4L2_CID_MPEG_VIDEO_H264_FMO_CHANGE_DIRECTION (V4L2_CID_MPEG_BASE+374) -enum v4l2_mpeg_video_h264_fmo_change_dir { - V4L2_MPEG_VIDEO_H264_FMO_CHANGE_DIR_RIGHT = 0, - V4L2_MPEG_VIDEO_H264_FMO_CHANGE_DIR_LEFT = 1, -}; -#define V4L2_CID_MPEG_VIDEO_H264_FMO_CHANGE_RATE (V4L2_CID_MPEG_BASE+375) -#define V4L2_CID_MPEG_VIDEO_H264_FMO_RUN_LENGTH (V4L2_CID_MPEG_BASE+376) -#define V4L2_CID_MPEG_VIDEO_H264_ASO (V4L2_CID_MPEG_BASE+377) -#define V4L2_CID_MPEG_VIDEO_H264_ASO_SLICE_ORDER (V4L2_CID_MPEG_BASE+378) -#define V4L2_CID_MPEG_VIDEO_H264_HIERARCHICAL_CODING (V4L2_CID_MPEG_BASE+379) -#define V4L2_CID_MPEG_VIDEO_H264_HIERARCHICAL_CODING_TYPE (V4L2_CID_MPEG_BASE+380) -enum v4l2_mpeg_video_h264_hierarchical_coding_type { - V4L2_MPEG_VIDEO_H264_HIERARCHICAL_CODING_B = 0, - V4L2_MPEG_VIDEO_H264_HIERARCHICAL_CODING_P = 1, -}; -#define V4L2_CID_MPEG_VIDEO_H264_HIERARCHICAL_CODING_LAYER (V4L2_CID_MPEG_BASE+381) -#define V4L2_CID_MPEG_VIDEO_H264_HIERARCHICAL_CODING_LAYER_QP (V4L2_CID_MPEG_BASE+382) -#define V4L2_CID_MPEG_VIDEO_MPEG4_I_FRAME_QP (V4L2_CID_MPEG_BASE+400) -#define V4L2_CID_MPEG_VIDEO_MPEG4_P_FRAME_QP (V4L2_CID_MPEG_BASE+401) -#define V4L2_CID_MPEG_VIDEO_MPEG4_B_FRAME_QP (V4L2_CID_MPEG_BASE+402) -#define V4L2_CID_MPEG_VIDEO_MPEG4_MIN_QP (V4L2_CID_MPEG_BASE+403) -#define V4L2_CID_MPEG_VIDEO_MPEG4_MAX_QP (V4L2_CID_MPEG_BASE+404) -#define V4L2_CID_MPEG_VIDEO_MPEG4_LEVEL (V4L2_CID_MPEG_BASE+405) -enum v4l2_mpeg_video_mpeg4_level { - V4L2_MPEG_VIDEO_MPEG4_LEVEL_0 = 0, - V4L2_MPEG_VIDEO_MPEG4_LEVEL_0B = 1, - V4L2_MPEG_VIDEO_MPEG4_LEVEL_1 = 2, - V4L2_MPEG_VIDEO_MPEG4_LEVEL_2 = 3, - V4L2_MPEG_VIDEO_MPEG4_LEVEL_3 = 4, - V4L2_MPEG_VIDEO_MPEG4_LEVEL_3B = 5, - V4L2_MPEG_VIDEO_MPEG4_LEVEL_4 = 6, - V4L2_MPEG_VIDEO_MPEG4_LEVEL_5 = 7, -}; -#define V4L2_CID_MPEG_VIDEO_MPEG4_PROFILE (V4L2_CID_MPEG_BASE+406) -enum v4l2_mpeg_video_mpeg4_profile { - V4L2_MPEG_VIDEO_MPEG4_PROFILE_SIMPLE = 0, - V4L2_MPEG_VIDEO_MPEG4_PROFILE_ADVANCED_SIMPLE = 1, - V4L2_MPEG_VIDEO_MPEG4_PROFILE_CORE = 2, - V4L2_MPEG_VIDEO_MPEG4_PROFILE_SIMPLE_SCALABLE = 3, - V4L2_MPEG_VIDEO_MPEG4_PROFILE_ADVANCED_CODING_EFFICIENCY = 4, -}; -#define V4L2_CID_MPEG_VIDEO_MPEG4_QPEL (V4L2_CID_MPEG_BASE+407) - -/* Control IDs for VP8 streams - * Although VP8 is not part of MPEG we add these controls to the MPEG class - * as that class is already handling other video compression standards - */ -#define V4L2_CID_MPEG_VIDEO_VPX_NUM_PARTITIONS (V4L2_CID_MPEG_BASE+500) -enum v4l2_vp8_num_partitions { - V4L2_CID_MPEG_VIDEO_VPX_1_PARTITION = 0, - V4L2_CID_MPEG_VIDEO_VPX_2_PARTITIONS = 1, - V4L2_CID_MPEG_VIDEO_VPX_4_PARTITIONS = 2, - V4L2_CID_MPEG_VIDEO_VPX_8_PARTITIONS = 3, -}; -#define V4L2_CID_MPEG_VIDEO_VPX_IMD_DISABLE_4X4 (V4L2_CID_MPEG_BASE+501) -#define V4L2_CID_MPEG_VIDEO_VPX_NUM_REF_FRAMES (V4L2_CID_MPEG_BASE+502) -enum v4l2_vp8_num_ref_frames { - V4L2_CID_MPEG_VIDEO_VPX_1_REF_FRAME = 0, - V4L2_CID_MPEG_VIDEO_VPX_2_REF_FRAME = 1, - V4L2_CID_MPEG_VIDEO_VPX_3_REF_FRAME = 2, -}; -#define V4L2_CID_MPEG_VIDEO_VPX_FILTER_LEVEL (V4L2_CID_MPEG_BASE+503) -#define V4L2_CID_MPEG_VIDEO_VPX_FILTER_SHARPNESS (V4L2_CID_MPEG_BASE+504) -#define V4L2_CID_MPEG_VIDEO_VPX_GOLDEN_FRAME_REF_PERIOD (V4L2_CID_MPEG_BASE+505) -#define V4L2_CID_MPEG_VIDEO_VPX_GOLDEN_FRAME_SEL (V4L2_CID_MPEG_BASE+506) -enum v4l2_vp8_golden_frame_sel { - V4L2_CID_MPEG_VIDEO_VPX_GOLDEN_FRAME_USE_PREV = 0, - V4L2_CID_MPEG_VIDEO_VPX_GOLDEN_FRAME_USE_REF_PERIOD = 1, -}; -#define V4L2_CID_MPEG_VIDEO_VPX_MIN_QP (V4L2_CID_MPEG_BASE+507) -#define V4L2_CID_MPEG_VIDEO_VPX_MAX_QP (V4L2_CID_MPEG_BASE+508) -#define V4L2_CID_MPEG_VIDEO_VPX_I_FRAME_QP (V4L2_CID_MPEG_BASE+509) -#define V4L2_CID_MPEG_VIDEO_VPX_P_FRAME_QP (V4L2_CID_MPEG_BASE+510) -#define V4L2_CID_MPEG_VIDEO_VPX_PROFILE (V4L2_CID_MPEG_BASE+511) - -/* MPEG-class control IDs specific to the CX2341x driver as defined by V4L2 */ -#define V4L2_CID_MPEG_CX2341X_BASE (V4L2_CTRL_CLASS_MPEG | 0x1000) -#define V4L2_CID_MPEG_CX2341X_VIDEO_SPATIAL_FILTER_MODE (V4L2_CID_MPEG_CX2341X_BASE+0) -enum v4l2_mpeg_cx2341x_video_spatial_filter_mode { - V4L2_MPEG_CX2341X_VIDEO_SPATIAL_FILTER_MODE_MANUAL = 0, - V4L2_MPEG_CX2341X_VIDEO_SPATIAL_FILTER_MODE_AUTO = 1, -}; -#define V4L2_CID_MPEG_CX2341X_VIDEO_SPATIAL_FILTER (V4L2_CID_MPEG_CX2341X_BASE+1) -#define V4L2_CID_MPEG_CX2341X_VIDEO_LUMA_SPATIAL_FILTER_TYPE (V4L2_CID_MPEG_CX2341X_BASE+2) -enum v4l2_mpeg_cx2341x_video_luma_spatial_filter_type { - V4L2_MPEG_CX2341X_VIDEO_LUMA_SPATIAL_FILTER_TYPE_OFF = 0, - V4L2_MPEG_CX2341X_VIDEO_LUMA_SPATIAL_FILTER_TYPE_1D_HOR = 1, - V4L2_MPEG_CX2341X_VIDEO_LUMA_SPATIAL_FILTER_TYPE_1D_VERT = 2, - V4L2_MPEG_CX2341X_VIDEO_LUMA_SPATIAL_FILTER_TYPE_2D_HV_SEPARABLE = 3, - V4L2_MPEG_CX2341X_VIDEO_LUMA_SPATIAL_FILTER_TYPE_2D_SYM_NON_SEPARABLE = 4, -}; -#define V4L2_CID_MPEG_CX2341X_VIDEO_CHROMA_SPATIAL_FILTER_TYPE (V4L2_CID_MPEG_CX2341X_BASE+3) -enum v4l2_mpeg_cx2341x_video_chroma_spatial_filter_type { - V4L2_MPEG_CX2341X_VIDEO_CHROMA_SPATIAL_FILTER_TYPE_OFF = 0, - V4L2_MPEG_CX2341X_VIDEO_CHROMA_SPATIAL_FILTER_TYPE_1D_HOR = 1, -}; -#define V4L2_CID_MPEG_CX2341X_VIDEO_TEMPORAL_FILTER_MODE (V4L2_CID_MPEG_CX2341X_BASE+4) -enum v4l2_mpeg_cx2341x_video_temporal_filter_mode { - V4L2_MPEG_CX2341X_VIDEO_TEMPORAL_FILTER_MODE_MANUAL = 0, - V4L2_MPEG_CX2341X_VIDEO_TEMPORAL_FILTER_MODE_AUTO = 1, -}; -#define V4L2_CID_MPEG_CX2341X_VIDEO_TEMPORAL_FILTER (V4L2_CID_MPEG_CX2341X_BASE+5) -#define V4L2_CID_MPEG_CX2341X_VIDEO_MEDIAN_FILTER_TYPE (V4L2_CID_MPEG_CX2341X_BASE+6) -enum v4l2_mpeg_cx2341x_video_median_filter_type { - V4L2_MPEG_CX2341X_VIDEO_MEDIAN_FILTER_TYPE_OFF = 0, - V4L2_MPEG_CX2341X_VIDEO_MEDIAN_FILTER_TYPE_HOR = 1, - V4L2_MPEG_CX2341X_VIDEO_MEDIAN_FILTER_TYPE_VERT = 2, - V4L2_MPEG_CX2341X_VIDEO_MEDIAN_FILTER_TYPE_HOR_VERT = 3, - V4L2_MPEG_CX2341X_VIDEO_MEDIAN_FILTER_TYPE_DIAG = 4, -}; -#define V4L2_CID_MPEG_CX2341X_VIDEO_LUMA_MEDIAN_FILTER_BOTTOM (V4L2_CID_MPEG_CX2341X_BASE+7) -#define V4L2_CID_MPEG_CX2341X_VIDEO_LUMA_MEDIAN_FILTER_TOP (V4L2_CID_MPEG_CX2341X_BASE+8) -#define V4L2_CID_MPEG_CX2341X_VIDEO_CHROMA_MEDIAN_FILTER_BOTTOM (V4L2_CID_MPEG_CX2341X_BASE+9) -#define V4L2_CID_MPEG_CX2341X_VIDEO_CHROMA_MEDIAN_FILTER_TOP (V4L2_CID_MPEG_CX2341X_BASE+10) -#define V4L2_CID_MPEG_CX2341X_STREAM_INSERT_NAV_PACKETS (V4L2_CID_MPEG_CX2341X_BASE+11) - -/* MPEG-class control IDs specific to the Samsung MFC 5.1 driver as defined by V4L2 */ -#define V4L2_CID_MPEG_MFC51_BASE (V4L2_CTRL_CLASS_MPEG | 0x1100) - -#define V4L2_CID_MPEG_MFC51_VIDEO_DECODER_H264_DISPLAY_DELAY (V4L2_CID_MPEG_MFC51_BASE+0) -#define V4L2_CID_MPEG_MFC51_VIDEO_DECODER_H264_DISPLAY_DELAY_ENABLE (V4L2_CID_MPEG_MFC51_BASE+1) -#define V4L2_CID_MPEG_MFC51_VIDEO_FRAME_SKIP_MODE (V4L2_CID_MPEG_MFC51_BASE+2) -enum v4l2_mpeg_mfc51_video_frame_skip_mode { - V4L2_MPEG_MFC51_VIDEO_FRAME_SKIP_MODE_DISABLED = 0, - V4L2_MPEG_MFC51_VIDEO_FRAME_SKIP_MODE_LEVEL_LIMIT = 1, - V4L2_MPEG_MFC51_VIDEO_FRAME_SKIP_MODE_BUF_LIMIT = 2, -}; -#define V4L2_CID_MPEG_MFC51_VIDEO_FORCE_FRAME_TYPE (V4L2_CID_MPEG_MFC51_BASE+3) -enum v4l2_mpeg_mfc51_video_force_frame_type { - V4L2_MPEG_MFC51_VIDEO_FORCE_FRAME_TYPE_DISABLED = 0, - V4L2_MPEG_MFC51_VIDEO_FORCE_FRAME_TYPE_I_FRAME = 1, - V4L2_MPEG_MFC51_VIDEO_FORCE_FRAME_TYPE_NOT_CODED = 2, -}; -#define V4L2_CID_MPEG_MFC51_VIDEO_PADDING (V4L2_CID_MPEG_MFC51_BASE+4) -#define V4L2_CID_MPEG_MFC51_VIDEO_PADDING_YUV (V4L2_CID_MPEG_MFC51_BASE+5) -#define V4L2_CID_MPEG_MFC51_VIDEO_RC_FIXED_TARGET_BIT (V4L2_CID_MPEG_MFC51_BASE+6) -#define V4L2_CID_MPEG_MFC51_VIDEO_RC_REACTION_COEFF (V4L2_CID_MPEG_MFC51_BASE+7) -#define V4L2_CID_MPEG_MFC51_VIDEO_H264_ADAPTIVE_RC_ACTIVITY (V4L2_CID_MPEG_MFC51_BASE+50) -#define V4L2_CID_MPEG_MFC51_VIDEO_H264_ADAPTIVE_RC_DARK (V4L2_CID_MPEG_MFC51_BASE+51) -#define V4L2_CID_MPEG_MFC51_VIDEO_H264_ADAPTIVE_RC_SMOOTH (V4L2_CID_MPEG_MFC51_BASE+52) -#define V4L2_CID_MPEG_MFC51_VIDEO_H264_ADAPTIVE_RC_STATIC (V4L2_CID_MPEG_MFC51_BASE+53) -#define V4L2_CID_MPEG_MFC51_VIDEO_H264_NUM_REF_PIC_FOR_P (V4L2_CID_MPEG_MFC51_BASE+54) - -/* MPEG-class control IDs specific to the msm_vidc driver */ -#define V4L2_CID_MPEG_MSM_VIDC_BASE (V4L2_CTRL_CLASS_MPEG | 0x2000) - -#define V4L2_CID_MPEG_VIDC_VIDEO_PICTYPE_DEC_MODE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE+0) -enum v4l2_mpeg_vidc_video_pictype_dec_mode { - V4L2_MPEG_VIDC_VIDEO_PICTYPE_DECODE_OFF = 0, - V4L2_MPEG_VIDC_VIDEO_PICTYPE_DECODE_ON = 1, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_KEEP_ASPECT_RATIO \ - (V4L2_CID_MPEG_MSM_VIDC_BASE+1) - -#define V4L2_CID_MPEG_VIDC_VIDEO_STREAM_FORMAT (V4L2_CID_MPEG_MSM_VIDC_BASE+2) -enum v4l2_mpeg_vidc_video_stream_format { - V4L2_MPEG_VIDC_VIDEO_NAL_FORMAT_STARTCODES = 0, - V4L2_MPEG_VIDC_VIDEO_NAL_FORMAT_ONE_NAL_PER_BUFFER = 1, - V4L2_MPEG_VIDC_VIDEO_NAL_FORMAT_ONE_BYTE_LENGTH = 2, - V4L2_MPEG_VIDC_VIDEO_NAL_FORMAT_TWO_BYTE_LENGTH = 3, - V4L2_MPEG_VIDC_VIDEO_NAL_FORMAT_FOUR_BYTE_LENGTH = 4, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_OUTPUT_ORDER (V4L2_CID_MPEG_MSM_VIDC_BASE+3) -enum v4l2_mpeg_vidc_video_output_order { - V4L2_MPEG_VIDC_VIDEO_OUTPUT_ORDER_DISPLAY = 0, - V4L2_MPEG_VIDC_VIDEO_OUTPUT_ORDER_DECODE = 1, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_FRAME_RATE (V4L2_CID_MPEG_MSM_VIDC_BASE+4) -#define V4L2_CID_MPEG_VIDC_VIDEO_IDR_PERIOD (V4L2_CID_MPEG_MSM_VIDC_BASE+5) -#define V4L2_CID_MPEG_VIDC_VIDEO_NUM_P_FRAMES (V4L2_CID_MPEG_MSM_VIDC_BASE+6) -#define V4L2_CID_MPEG_VIDC_VIDEO_NUM_B_FRAMES (V4L2_CID_MPEG_MSM_VIDC_BASE+7) -#define V4L2_CID_MPEG_VIDC_VIDEO_REQUEST_IFRAME (V4L2_CID_MPEG_MSM_VIDC_BASE+8) - -#define V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL (V4L2_CID_MPEG_MSM_VIDC_BASE+9) -enum v4l2_mpeg_vidc_video_rate_control { - V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_OFF = 0, - V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_VBR_VFR = 1, - V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_VBR_CFR = 2, - V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_CBR_VFR = 3, - V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_CBR_CFR = 4, - V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_MBR_CFR = 5, - V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_MBR_VFR = 6, - V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_CQ = 7, -}; -#define V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_MBR_CFR \ - V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_MBR_CFR -#define V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_MBR_VFR \ - V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_MBR_VFR - -#define V4L2_CID_MPEG_VIDC_VIDEO_ROTATION (V4L2_CID_MPEG_MSM_VIDC_BASE+10) -enum v4l2_mpeg_vidc_video_rotation { - V4L2_CID_MPEG_VIDC_VIDEO_ROTATION_NONE = 0, - V4L2_CID_MPEG_VIDC_VIDEO_ROTATION_90 = 1, - V4L2_CID_MPEG_VIDC_VIDEO_ROTATION_180 = 2, - V4L2_CID_MPEG_VIDC_VIDEO_ROTATION_270 = 3, -}; -#define V4L2_CID_MPEG_VIDC_VIDEO_H264_CABAC_MODEL \ - (V4L2_CID_MPEG_MSM_VIDC_BASE+11) -enum v4l2_mpeg_vidc_h264_cabac_model { - V4L2_CID_MPEG_VIDC_VIDEO_H264_CABAC_MODEL_0 = 0, - V4L2_CID_MPEG_VIDC_VIDEO_H264_CABAC_MODEL_1 = 1, - V4L2_CID_MPEG_VIDC_VIDEO_H264_CABAC_MODEL_2 = 2, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_INTRA_REFRESH_MODE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE+12) -enum v4l2_mpeg_vidc_video_intra_refresh_mode { - V4L2_CID_MPEG_VIDC_VIDEO_INTRA_REFRESH_NONE = 0, - V4L2_CID_MPEG_VIDC_VIDEO_INTRA_REFRESH_CYCLIC = 1, - V4L2_CID_MPEG_VIDC_VIDEO_INTRA_REFRESH_RANDOM = 2, - V4L2_CID_MPEG_VIDC_VIDEO_INTRA_REFRESH_ADAPTIVE = 3, - V4L2_CID_MPEG_VIDC_VIDEO_INTRA_REFRESH_CYCLIC_ADAPTIVE = 4, -}; -#define V4L2_CID_MPEG_VIDC_VIDEO_IR_MBS (V4L2_CID_MPEG_MSM_VIDC_BASE+13) - -#define V4L2_CID_MPEG_VIDC_VIDEO_AU_DELIMITER \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 14) -enum v4l2_mpeg_vidc_video_au_delimiter { - V4L2_MPEG_VIDC_VIDEO_AU_DELIMITER_DISABLED = 0, - V4L2_MPEG_VIDC_VIDEO_AU_DELIMITER_ENABLED = 1 -}; -#define V4L2_CID_MPEG_VIDC_VIDEO_SYNC_FRAME_DECODE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 15) -enum v4l2_mpeg_vidc_video_sync_frame_decode { - V4L2_MPEG_VIDC_VIDEO_SYNC_FRAME_DECODE_DISABLE = 0, - V4L2_MPEG_VIDC_VIDEO_SYNC_FRAME_DECODE_ENABLE = 1 -}; -#define V4L2_CID_MPEG_VIDC_VIDEO_SECURE (V4L2_CID_MPEG_MSM_VIDC_BASE+16) -#define V4L2_CID_MPEG_VIDC_VIDEO_EXTRADATA \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 17) -enum v4l2_mpeg_vidc_extradata { - V4L2_MPEG_VIDC_EXTRADATA_NONE = 0, - V4L2_MPEG_VIDC_EXTRADATA_MB_QUANTIZATION = 1, - V4L2_MPEG_VIDC_EXTRADATA_INTERLACE_VIDEO = 2, - V4L2_MPEG_VIDC_EXTRADATA_VC1_FRAMEDISP = 3, - V4L2_MPEG_VIDC_EXTRADATA_VC1_SEQDISP = 4, - V4L2_MPEG_VIDC_EXTRADATA_TIMESTAMP = 5, - V4L2_MPEG_VIDC_EXTRADATA_S3D_FRAME_PACKING = 6, - V4L2_MPEG_VIDC_EXTRADATA_FRAME_RATE = 7, - V4L2_MPEG_VIDC_EXTRADATA_PANSCAN_WINDOW = 8, - V4L2_MPEG_VIDC_EXTRADATA_RECOVERY_POINT_SEI = 9, - V4L2_MPEG_VIDC_EXTRADATA_MULTISLICE_INFO = 10, - V4L2_MPEG_VIDC_EXTRADATA_NUM_CONCEALED_MB = 11, - V4L2_MPEG_VIDC_EXTRADATA_METADATA_FILLER = 12, - V4L2_MPEG_VIDC_EXTRADATA_INPUT_CROP = 13, - V4L2_MPEG_VIDC_EXTRADATA_DIGITAL_ZOOM = 14, - V4L2_MPEG_VIDC_EXTRADATA_ASPECT_RATIO = 15, - V4L2_MPEG_VIDC_EXTRADATA_MPEG2_SEQDISP = 16, - V4L2_MPEG_VIDC_EXTRADATA_STREAM_USERDATA = 17, - V4L2_MPEG_VIDC_EXTRADATA_FRAME_QP = 18, - V4L2_MPEG_VIDC_EXTRADATA_FRAME_BITS_INFO = 19, - V4L2_MPEG_VIDC_EXTRADATA_LTR = 20, - V4L2_MPEG_VIDC_EXTRADATA_METADATA_MBI = 21, - V4L2_MPEG_VIDC_EXTRADATA_VQZIP_SEI = 22, - V4L2_MPEG_VIDC_EXTRADATA_YUV_STATS = 23, - V4L2_MPEG_VIDC_EXTRADATA_ROI_QP = 24, -#define V4L2_MPEG_VIDC_EXTRADATA_OUTPUT_CROP \ - V4L2_MPEG_VIDC_EXTRADATA_OUTPUT_CROP - V4L2_MPEG_VIDC_EXTRADATA_OUTPUT_CROP = 25, -#define V4L2_MPEG_VIDC_EXTRADATA_DISPLAY_COLOUR_SEI \ - V4L2_MPEG_VIDC_EXTRADATA_DISPLAY_COLOUR_SEI - V4L2_MPEG_VIDC_EXTRADATA_DISPLAY_COLOUR_SEI = 26, -#define V4L2_MPEG_VIDC_EXTRADATA_CONTENT_LIGHT_LEVEL_SEI \ - V4L2_MPEG_VIDC_EXTRADATA_CONTENT_LIGHT_LEVEL_SEI - V4L2_MPEG_VIDC_EXTRADATA_CONTENT_LIGHT_LEVEL_SEI = 27, -#define V4L2_MPEG_VIDC_EXTRADATA_PQ_INFO \ - V4L2_MPEG_VIDC_EXTRADATA_PQ_INFO - V4L2_MPEG_VIDC_EXTRADATA_PQ_INFO = 28, -#define V4L2_MPEG_VIDC_EXTRADATA_VUI_DISPLAY \ - V4L2_MPEG_VIDC_EXTRADATA_VUI_DISPLAY - V4L2_MPEG_VIDC_EXTRADATA_VUI_DISPLAY = 29, -#define V4L2_MPEG_VIDC_EXTRADATA_VPX_COLORSPACE \ - V4L2_MPEG_VIDC_EXTRADATA_VPX_COLORSPACE - V4L2_MPEG_VIDC_EXTRADATA_VPX_COLORSPACE = 30, -#define V4L2_MPEG_VIDC_EXTRADATA_UBWC_CR_STATS_INFO \ - V4L2_MPEG_VIDC_EXTRADATA_UBWC_CR_STATS_INFO - V4L2_MPEG_VIDC_EXTRADATA_UBWC_CR_STATS_INFO = 31, -#define V4L2_MPEG_VIDC_EXTRADATA_ENC_FRAME_QP \ - V4L2_MPEG_VIDC_EXTRADATA_ENC_FRAME_QP - V4L2_MPEG_VIDC_EXTRADATA_ENC_FRAME_QP = 32, -}; - -#define V4L2_CID_MPEG_VIDEO_MULTI_SLICE_DELIVERY_MODE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 18) - -#define V4L2_CID_MPEG_VIDC_VIDEO_VUI_TIMING_INFO \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 19) -enum v4l2_mpeg_vidc_video_vui_timing_info { - V4L2_MPEG_VIDC_VIDEO_VUI_TIMING_INFO_DISABLED = 0, - V4L2_MPEG_VIDC_VIDEO_VUI_TIMING_INFO_ENABLED = 1 -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_VP8_PROFILE_LEVEL \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 20) -enum v4l2_mpeg_vidc_video_vp8_profile_level { - V4L2_MPEG_VIDC_VIDEO_VP8_UNUSED, - V4L2_MPEG_VIDC_VIDEO_VP8_VERSION_0, - V4L2_MPEG_VIDC_VIDEO_VP8_VERSION_1, - V4L2_MPEG_VIDC_VIDEO_VP8_VERSION_2, - V4L2_MPEG_VIDC_VIDEO_VP8_VERSION_3, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_PRESERVE_TEXT_QUALITY \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 21) -enum v4l2_mpeg_vidc_video_preserve_text_quality { - V4L2_MPEG_VIDC_VIDEO_PRESERVE_TEXT_QUALITY_DISABLED = 0, - V4L2_MPEG_VIDC_VIDEO_PRESERVE_TEXT_QUALITY_ENABLED = 1 -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_STREAM_OUTPUT_MODE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 22) -enum v4l2_mpeg_vidc_video_decoder_multi_stream { - V4L2_CID_MPEG_VIDC_VIDEO_STREAM_OUTPUT_PRIMARY = 0, - V4L2_CID_MPEG_VIDC_VIDEO_STREAM_OUTPUT_SECONDARY = 1, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_MPEG2_LEVEL (V4L2_CID_MPEG_MSM_VIDC_BASE+23) -enum v4l2_mpeg_vidc_video_mpeg2_level { - V4L2_MPEG_VIDC_VIDEO_MPEG2_LEVEL_0 = 0, - V4L2_MPEG_VIDC_VIDEO_MPEG2_LEVEL_1 = 1, - V4L2_MPEG_VIDC_VIDEO_MPEG2_LEVEL_2 = 2, - V4L2_MPEG_VIDC_VIDEO_MPEG2_LEVEL_3 = 3, -}; -#define V4L2_CID_MPEG_VIDC_VIDEO_MPEG2_PROFILE (V4L2_CID_MPEG_MSM_VIDC_BASE+24) -enum v4l2_mpeg_vidc_video_mpeg2_profile { - V4L2_MPEG_VIDC_VIDEO_MPEG2_PROFILE_SIMPLE = 0, - V4L2_MPEG_VIDC_VIDEO_MPEG2_PROFILE_MAIN = 1, - V4L2_MPEG_VIDC_VIDEO_MPEG2_PROFILE_422 = 2, - V4L2_MPEG_VIDC_VIDEO_MPEG2_PROFILE_SNR_SCALABLE = 3, - V4L2_MPEG_VIDC_VIDEO_MPEG2_PROFILE_SPATIAL_SCALABLE = 4, - V4L2_MPEG_VIDC_VIDEO_MPEG2_PROFILE_HIGH = 5, -}; - -enum v4l2_mpeg_vidc_video_mvc_layout { - V4L2_MPEG_VIDC_VIDEO_MVC_SEQUENTIAL = 0, - V4L2_MPEG_VIDC_VIDEO_MVC_TOP_BOTTOM = 1 -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_CONCEAL_COLOR \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 25) - -#define V4L2_CID_MPEG_VIDC_VIDEO_LTRMODE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 26) - -enum v4l2_mpeg_vidc_video_ltrmode { - V4L2_MPEG_VIDC_VIDEO_LTR_MODE_DISABLE = 0, - V4L2_MPEG_VIDC_VIDEO_LTR_MODE_MANUAL = 1, - V4L2_MPEG_VIDC_VIDEO_LTR_MODE_PERIODIC = 2 -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_LTRCOUNT \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 27) - -#define V4L2_CID_MPEG_VIDC_VIDEO_USELTRFRAME \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 28) - -#define V4L2_CID_MPEG_VIDC_VIDEO_MARKLTRFRAME \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 29) - -#define V4L2_CID_MPEG_VIDC_VIDEO_HIER_P_NUM_LAYERS \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 30) - -#define V4L2_CID_MPEG_VIDC_VIDEO_ALLOC_MODE_OUTPUT \ - (V4L2_CID_MPEG_MSM_VIDC_BASE+31) -enum v4l2_mpeg_vidc_video_alloc_mode_type { - V4L2_MPEG_VIDC_VIDEO_STATIC = 0, - V4L2_MPEG_VIDC_VIDEO_RING = 1, - V4L2_MPEG_VIDC_VIDEO_DYNAMIC = 2, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_IFRAME_X_RANGE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 32) - -#define V4L2_CID_MPEG_VIDC_VIDEO_PFRAME_X_RANGE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 33) - -#define V4L2_CID_MPEG_VIDC_VIDEO_BFRAME_X_RANGE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 34) - -#define V4L2_CID_MPEG_VIDC_VIDEO_IFRAME_Y_RANGE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 35) - -#define V4L2_CID_MPEG_VIDC_VIDEO_PFRAME_Y_RANGE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 36) - -#define V4L2_CID_MPEG_VIDC_VIDEO_BFRAME_Y_RANGE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 37) - -#define V4L2_CID_MPEG_VIDC_VIDEO_VPX_ERROR_RESILIENCE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 38) - -#define V4L2_CID_MPEG_VIDC_VIDEO_BUFFER_SIZE_LIMIT \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 39) - -enum vl42_mpeg_vidc_video_vpx_error_resilience { - V4L2_MPEG_VIDC_VIDEO_VPX_ERROR_RESILIENCE_DISABLED = 0, - V4L2_MPEG_VIDC_VIDEO_VPX_ERROR_RESILIENCE_ENABLED = 1, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_HEVC_PROFILE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 40) -enum v4l2_mpeg_video_hevc_profile { - V4L2_MPEG_VIDC_VIDEO_HEVC_PROFILE_MAIN = 0, - V4L2_MPEG_VIDC_VIDEO_HEVC_PROFILE_MAIN10 = 1, - V4L2_MPEG_VIDC_VIDEO_HEVC_PROFILE_MAIN_STILL_PIC = 2, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_HEVC_TIER_LEVEL \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 41) -enum v4l2_mpeg_video_hevc_level { - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_MAIN_TIER_LEVEL_1 = 0, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_1 = 1, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_MAIN_TIER_LEVEL_2 = 2, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_2 = 3, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_MAIN_TIER_LEVEL_2_1 = 4, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_2_1 = 5, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_MAIN_TIER_LEVEL_3 = 6, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_3 = 7, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_MAIN_TIER_LEVEL_3_1 = 8, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_3_1 = 9, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_MAIN_TIER_LEVEL_4 = 10, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_4 = 11, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_MAIN_TIER_LEVEL_4_1 = 12, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_4_1 = 13, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_MAIN_TIER_LEVEL_5 = 14, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_5 = 15, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_MAIN_TIER_LEVEL_5_1 = 16, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_5_1 = 17, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_MAIN_TIER_LEVEL_5_2 = 18, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_5_2 = 19, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_MAIN_TIER_LEVEL_6 = 20, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_6 = 21, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_MAIN_TIER_LEVEL_6_1 = 22, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_6_1 = 23, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_MAIN_TIER_LEVEL_6_2 = 24, - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_HIGH_TIER_LEVEL_6_2 = 25, -#define V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_UNKNOWN \ - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_UNKNOWN - V4L2_MPEG_VIDC_VIDEO_HEVC_LEVEL_UNKNOWN = 26, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_HIER_B_NUM_LAYERS \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 42) - -#define V4L2_CID_MPEG_VIDC_VIDEO_HYBRID_HIERP_MODE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 43) - -#define V4L2_CID_MPEG_VIDC_VIDEO_DPB_COLOR_FORMAT \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 44) - -enum v4l2_mpeg_vidc_video_dpb_color_format { - V4L2_MPEG_VIDC_VIDEO_DPB_COLOR_FMT_NONE = 0, - V4L2_MPEG_VIDC_VIDEO_DPB_COLOR_FMT_UBWC = 1, - V4L2_MPEG_VIDC_VIDEO_DPB_COLOR_FMT_TP10_UBWC = 2 -}; - -#define V4L2_CID_VIDC_QBUF_MODE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 45) -enum v4l2_vidc_qbuf_mode { - V4L2_VIDC_QBUF_STANDARD = 0, - V4L2_VIDC_QBUF_BATCHED = 1, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_MAX_HIERP_LAYERS \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 46) - -#define V4L2_CID_MPEG_VIDC_VIDEO_BASELAYER_ID \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 47) - -#define V4L2_CID_MPEG_VIDC_VENC_PARAM_SAR_WIDTH \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 48) - -#define V4L2_CID_MPEG_VIDC_VENC_PARAM_SAR_HEIGHT \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 49) - -#define V4L2_CID_MPEG_VIDC_VIDEO_VQZIP_SEI \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 50) - -enum v4l2_mpeg_vidc_video_vqzip_sei_enable { - V4L2_CID_MPEG_VIDC_VIDEO_VQZIP_SEI_DISABLE = 0, - V4L2_CID_MPEG_VIDC_VIDEO_VQZIP_SEI_ENABLE = 1 -}; - -#define V4L2_CID_MPEG_VIDC_VENC_PARAM_LAYER_BITRATE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 51) - -#define V4L2_CID_MPEG_VIDC_VIDEO_PRIORITY \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 52) - -enum v4l2_mpeg_vidc_video_priority { - V4L2_MPEG_VIDC_VIDEO_PRIORITY_REALTIME_ENABLE = 0, - V4L2_MPEG_VIDC_VIDEO_PRIORITY_REALTIME_DISABLE = 1, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_OPERATING_RATE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 53) - -#define V4L2_CID_MPEG_VIDC_VIDEO_VENC_BITRATE_TYPE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 54) - -enum v4l2_mpeg_vidc_video_venc_bitrate_type_enable { - V4L2_CID_MPEG_VIDC_VIDEO_VENC_BITRATE_DISABLE = 0, - V4L2_CID_MPEG_VIDC_VIDEO_VENC_BITRATE_ENABLE = 1 -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_VPE_CSC \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 55) - -enum v4l2_cid_mpeg_vidc_video_vpe_csc_type_enable { - V4L2_CID_MPEG_VIDC_VIDEO_VPE_CSC_DISABLE = 0, - V4L2_CID_MPEG_VIDC_VIDEO_VPE_CSC_ENABLE = 1 -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_LOWLATENCY_MODE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 56) - -enum v4l2_mpeg_vidc_video_lowlatency_mode { - V4L2_CID_MPEG_VIDC_VIDEO_LOWLATENCY_DISABLE = 0, - V4L2_CID_MPEG_VIDC_VIDEO_LOWLATENCY_ENABLE = 1, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_BLUR_WIDTH \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 57) - -#define V4L2_CID_MPEG_VIDC_VIDEO_BLUR_HEIGHT \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 58) - -#define V4L2_CID_MPEG_VIDC_VIDEO_H264_TRANSFORM_8x8 \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 59) -enum v4l2_mpeg_vidc_video_h264_transform_8x8 { - V4L2_MPEG_VIDC_VIDEO_H264_TRANSFORM_8x8_DISABLE = 0, - V4L2_MPEG_VIDC_VIDEO_H264_TRANSFORM_8x8_ENABLE = 1, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_COLOR_SPACE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 60) - -#define V4L2_CID_MPEG_VIDC_VIDEO_FULL_RANGE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 61) - -enum v4l2_cid_mpeg_vidc_video_full_range { - V4L2_CID_MPEG_VIDC_VIDEO_FULL_RANGE_DISABLE = 0, - V4L2_CID_MPEG_VIDC_VIDEO_FULL_RANGE_ENABLE = 1, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_TRANSFER_CHARS \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 62) - -#define V4L2_CID_MPEG_VIDC_VIDEO_MATRIX_COEFFS \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 63) - -#define V4L2_CID_MPEG_VIDC_VIDEO_IFRAME_SIZE_TYPE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 64) - -#define V4L2_CID_MPEG_VIDC_VIDEO_LAYER_ID \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 65) - -#define V4L2_CID_MPEG_VIDC_VIDEO_VP9_PROFILE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 66) -enum v4l2_mpeg_vidc_video_vp9_profile { - V4L2_MPEG_VIDC_VIDEO_VP9_PROFILE_UNUSED = 0, - V4L2_MPEG_VIDC_VIDEO_VP9_PROFILE_P0 = 1, - V4L2_MPEG_VIDC_VIDEO_VP9_PROFILE_P2_10 = 2, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_VP9_LEVEL \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 67) -enum v4l2_mpeg_vidc_video_vp9_level { - V4L2_MPEG_VIDC_VIDEO_VP9_LEVEL_UNUSED = 0, - V4L2_MPEG_VIDC_VIDEO_VP9_LEVEL_1 = 1, - V4L2_MPEG_VIDC_VIDEO_VP9_LEVEL_11 = 2, - V4L2_MPEG_VIDC_VIDEO_VP9_LEVEL_2 = 3, - V4L2_MPEG_VIDC_VIDEO_VP9_LEVEL_21 = 4, - V4L2_MPEG_VIDC_VIDEO_VP9_LEVEL_3 = 5, - V4L2_MPEG_VIDC_VIDEO_VP9_LEVEL_31 = 6, - V4L2_MPEG_VIDC_VIDEO_VP9_LEVEL_4 = 7, - V4L2_MPEG_VIDC_VIDEO_VP9_LEVEL_41 = 8, - V4L2_MPEG_VIDC_VIDEO_VP9_LEVEL_5 = 9, - V4L2_MPEG_VIDC_VIDEO_VP9_LEVEL_51 = 10, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_MB_ERROR_MAP_REPORTING \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 68) -#define V4L2_CID_MPEG_VIDC_VIDEO_CONTINUE_DATA_TRANSFER \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 69) - -#define V4L2_CID_MPEG_VIDC_VIDEO_ALLOC_MODE_INPUT \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 70) - -#define V4L2_CID_MPEG_VIDC_VIDEO_FRAME_ASSEMBLY \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 71) -enum v4l2_mpeg_vidc_video_assembly { - V4L2_MPEG_VIDC_FRAME_ASSEMBLY_DISABLE = 0, - V4L2_MPEG_VIDC_FRAME_ASSEMBLY_ENABLE = 1, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_H263_PROFILE\ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 72) -enum v4l2_mpeg_vidc_video_h263_profile { - V4L2_MPEG_VIDC_VIDEO_H263_PROFILE_BASELINE = 0, - V4L2_MPEG_VIDC_VIDEO_H263_PROFILE_H320CODING = 1, - V4L2_MPEG_VIDC_VIDEO_H263_PROFILE_BACKWARDCOMPATIBLE = 2, - V4L2_MPEG_VIDC_VIDEO_H263_PROFILE_ISWV2 = 3, - V4L2_MPEG_VIDC_VIDEO_H263_PROFILE_ISWV3 = 4, - V4L2_MPEG_VIDC_VIDEO_H263_PROFILE_HIGHCOMPRESSION = 5, - V4L2_MPEG_VIDC_VIDEO_H263_PROFILE_INTERNET = 6, - V4L2_MPEG_VIDC_VIDEO_H263_PROFILE_INTERLACE = 7, - V4L2_MPEG_VIDC_VIDEO_H263_PROFILE_HIGHLATENCY = 8, -}; - -#define V4L2_CID_MPEG_VIDEO_MIN_QP_PACKED \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 97) -#define V4L2_CID_MPEG_VIDEO_MAX_QP_PACKED \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 98) -#define V4L2_CID_MPEG_VIDC_VIDEO_I_FRAME_QP \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 99) -#define V4L2_CID_MPEG_VIDC_VIDEO_P_FRAME_QP \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 100) -#define V4L2_CID_MPEG_VIDC_VIDEO_B_FRAME_QP \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 101) -#define V4L2_CID_MPEG_VIDC_VIDEO_I_FRAME_QP_MIN \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 102) -#define V4L2_CID_MPEG_VIDC_VIDEO_P_FRAME_QP_MIN \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 103) -#define V4L2_CID_MPEG_VIDC_VIDEO_B_FRAME_QP_MIN \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 104) -#define V4L2_CID_MPEG_VIDC_VIDEO_I_FRAME_QP_MAX \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 105) -#define V4L2_CID_MPEG_VIDC_VIDEO_P_FRAME_QP_MAX \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 106) -#define V4L2_CID_MPEG_VIDC_VIDEO_B_FRAME_QP_MAX \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 107) -#define V4L2_CID_MPEG_VIDC_VIDEO_QP_MASK \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 108) - -enum v4l2_mpeg_vidc_video_venc_iframesize_type { - V4L2_CID_MPEG_VIDC_VIDEO_IFRAME_SIZE_DEFAULT, - V4L2_CID_MPEG_VIDC_VIDEO_IFRAME_SIZE_MEDIUM, - V4L2_CID_MPEG_VIDC_VIDEO_IFRAME_SIZE_HUGE, - V4L2_CID_MPEG_VIDC_VIDEO_IFRAME_SIZE_UNLIMITED, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_CONCEAL_COLOR_8BIT \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 109) -#define V4L2_CID_MPEG_VIDC_VIDEO_CONCEAL_COLOR_10BIT \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 110) - -#define V4L2_CID_MPEG_VIDC_VIDEO_TME_PROFILE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 111) - -enum v4l2_mpeg_vidc_video_tme_profile { - V4L2_MPEG_VIDC_VIDEO_TME_PROFILE_0 = 0, - V4L2_MPEG_VIDC_VIDEO_TME_PROFILE_1 = 1, - V4L2_MPEG_VIDC_VIDEO_TME_PROFILE_2 = 2, - V4L2_MPEG_VIDC_VIDEO_TME_PROFILE_3 = 3, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_TME_LEVEL \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 112) - -enum v4l2_mpeg_vidc_video_tme_level { - V4L2_MPEG_VIDC_VIDEO_TME_LEVEL_INTEGER = 0, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_TME_PAYLOAD_VERSION \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 113) - -#define V4L2_CID_MPEG_VIDC_VIDEO_VPE_CSC_CUSTOM_MATRIX \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 114) - -#define V4L2_CID_MPEG_VIDC_VIDEO_FLIP (V4L2_CID_MPEG_MSM_VIDC_BASE + 115) -enum v4l2_mpeg_vidc_video_flip { - V4L2_CID_MPEG_VIDC_VIDEO_FLIP_NONE = 0, - V4L2_CID_MPEG_VIDC_VIDEO_FLIP_HORI = 1, - V4L2_CID_MPEG_VIDC_VIDEO_FLIP_VERT = 2, - V4L2_CID_MPEG_VIDC_VIDEO_FLIP_BOTH = 3, -}; - -/* HDR SEI INFO related control IDs and definitions*/ -#define V4L2_MPEG_VIDC_VENC_HDR_INFO_ENABLED 1 -#define V4L2_MPEG_VIDC_VENC_HDR_INFO_DISABLED 0 - -#define V4L2_CID_MPEG_VIDC_VENC_HDR_INFO \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 116) -#define V4L2_CID_MPEG_VIDC_VENC_RGB_PRIMARY_00 \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 117) -#define V4L2_CID_MPEG_VIDC_VENC_RGB_PRIMARY_01 \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 118) -#define V4L2_CID_MPEG_VIDC_VENC_RGB_PRIMARY_10 \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 119) -#define V4L2_CID_MPEG_VIDC_VENC_RGB_PRIMARY_11 \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 120) -#define V4L2_CID_MPEG_VIDC_VENC_RGB_PRIMARY_20 \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 121) -#define V4L2_CID_MPEG_VIDC_VENC_RGB_PRIMARY_21 \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 122) -#define V4L2_CID_MPEG_VIDC_VENC_WHITEPOINT_X \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 123) -#define V4L2_CID_MPEG_VIDC_VENC_WHITEPOINT_Y \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 124) -#define V4L2_CID_MPEG_VIDC_VENC_MAX_DISP_LUM \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 125) -#define V4L2_CID_MPEG_VIDC_VENC_MIN_DISP_LUM \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 126) -#define V4L2_CID_MPEG_VIDC_VENC_MAX_CLL \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 127) -#define V4L2_CID_MPEG_VIDC_VENC_MAX_FLL \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 128) - -#define V4L2_CID_MPEG_VIDC_SET_PERF_LEVEL \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 129) -enum v4l2_mpeg_vidc_perf_level { - V4L2_CID_MPEG_VIDC_PERF_LEVEL_NOMINAL = 0, - V4L2_CID_MPEG_VIDC_PERF_LEVEL_PERFORMANCE = 1, - V4L2_CID_MPEG_VIDC_PERF_LEVEL_TURBO = 2, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_AIR_MBS (V4L2_CID_MPEG_MSM_VIDC_BASE + 130) -#define V4L2_CID_MPEG_VIDC_VIDEO_AIR_REF (V4L2_CID_MPEG_MSM_VIDC_BASE + 131) -#define V4L2_CID_MPEG_VIDC_VIDEO_CIR_MBS (V4L2_CID_MPEG_MSM_VIDC_BASE + 132) - -#define V4L2_CID_MPEG_VIDC_VIDEO_H264_VUI_TIMING_INFO \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 135) - -#define V4L2_CID_MPEG_VIDEO_MULTI_SLICE_GOB \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 136) - -#define V4L2_CID_MPEG_VIDC_VIDEO_H264_VUI_BITSTREAM_RESTRICT \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 137) -enum v4l2_mpeg_vidc_video_h264_vui_bitstream_restrict { - V4L2_MPEG_VIDC_VIDEO_H264_VUI_BITSTREAM_RESTRICT_DISABLED = 0, - V4L2_MPEG_VIDC_VIDEO_H264_VUI_BITSTREAM_RESTRICT_ENABLED = 1 -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_DEINTERLACE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 138) -enum v4l2_mpeg_vidc_video_deinterlace { - V4L2_CID_MPEG_VIDC_VIDEO_DEINTERLACE_DISABLED = 0, - V4L2_CID_MPEG_VIDC_VIDEO_DEINTERLACE_ENABLED = 1 -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_MPEG4_TIME_RESOLUTION \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 139) - -#define V4L2_CID_MPEG_VIDC_VIDEO_REQUEST_SEQ_HEADER \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 140) - -#define V4L2_CID_MPEG_VIDC_VIDEO_RATE_CONTROL_TIMESTAMP_MODE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 141) -enum v4l2_mpeg_vidc_video_rate_control_timestamp_mode { - V4L2_MPEG_VIDC_VIDEO_RATE_CONTROL_TIMESTAMP_MODE_HONOR = 0, - V4L2_MPEG_VIDC_VIDEO_RATE_CONTROL_TIMESTAMP_MODE_IGNORE = 1, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_ENABLE_INITIAL_QP \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 142) -enum vl42_mpeg_vidc_video_enable_initial_qp { - V4L2_CID_MPEG_VIDC_VIDEO_ENABLE_INITIAL_QP_IFRAME = 0x1, - V4L2_CID_MPEG_VIDC_VIDEO_ENABLE_INITIAL_QP_PFRAME = 0x2, - V4L2_CID_MPEG_VIDC_VIDEO_ENABLE_INITIAL_QP_BFRAME = 0x4, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_INITIAL_I_FRAME_QP \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 143) - -#define V4L2_CID_MPEG_VIDC_VIDEO_INITIAL_P_FRAME_QP \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 144) - -#define V4L2_CID_MPEG_VIDC_VIDEO_INITIAL_B_FRAME_QP \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 145) - -#define V4L2_CID_MPEG_VIDC_VIDEO_H264_NAL_SVC \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 146) - -#define V4L2_CID_MPEG_VIDC_VIDEO_PERF_MODE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 147) -enum v4l2_mpeg_vidc_video_perf_mode { - V4L2_MPEG_VIDC_VIDEO_PERF_MAX_QUALITY = 1, - V4L2_MPEG_VIDC_VIDEO_PERF_POWER_SAVE = 2 -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_MBI_STATISTICS_MODE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 148) - -#define V4L2_CID_MPEG_VIDC_VIDEO_CONFIG_QP \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 149) - -#define V4L2_CID_MPEG_VIDC_VIDEO_H264_PIC_ORDER_CNT \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 150) - -#define V4L2_CID_MPEG_VIDC_VIDEO_SCS_THRESHOLD \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 151) - -#define V4L2_CID_MPEG_VIDC_VIDEO_MVC_BUFFER_LAYOUT \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 152) - - -#define V4L2_CID_MPEG_VIDC_VIDEO_SECURE_SCALING_THRESHOLD \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 153) - -#define V4L2_CID_MPEG_VIDC_VIDEO_NON_SECURE_OUTPUT2 \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 154) - -#define V4L2_CID_MPEG_VIDC_VIDEO_VP8_MIN_QP (V4L2_CID_MPEG_MSM_VIDC_BASE + 155) -#define V4L2_CID_MPEG_VIDC_VIDEO_VP8_MAX_QP (V4L2_CID_MPEG_MSM_VIDC_BASE + 156) - -#define V4L2_CID_MPEG_VIDC_VIDEO_H263_LEVEL (V4L2_CID_MPEG_MSM_VIDC_BASE + 157) -enum v4l2_mpeg_vidc_video_h263_level { - V4L2_MPEG_VIDC_VIDEO_H263_LEVEL_1_0 = 0, - V4L2_MPEG_VIDC_VIDEO_H263_LEVEL_2_0 = 1, - V4L2_MPEG_VIDC_VIDEO_H263_LEVEL_3_0 = 2, - V4L2_MPEG_VIDC_VIDEO_H263_LEVEL_4_0 = 3, - V4L2_MPEG_VIDC_VIDEO_H263_LEVEL_4_5 = 4, - V4L2_MPEG_VIDC_VIDEO_H263_LEVEL_5_0 = 5, - V4L2_MPEG_VIDC_VIDEO_H263_LEVEL_6_0 = 6, - V4L2_MPEG_VIDC_VIDEO_H263_LEVEL_7_0 = 7, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_POST_LOOP_DEBLOCKER_MODE \ - (V4L2_CID_MPEG_MSM_VIDC_BASE + 158) - - -#define V4L2_CID_MPEG_VIDC_VIDEO_DIVX_FORMAT (V4L2_CID_MPEG_MSM_VIDC_BASE+159) - -enum v4l2_mpeg_vidc_video_divx_format_type { - V4L2_MPEG_VIDC_VIDEO_DIVX_FORMAT_4 = 0, - V4L2_MPEG_VIDC_VIDEO_DIVX_FORMAT_5 = 1, - V4L2_MPEG_VIDC_VIDEO_DIVX_FORMAT_6 = 2, -}; - -#define V4L2_CID_MPEG_VIDC_VIDEO_FRAME_QUALITY \ - (V4L2_CID_MPEG_MSM_VIDC_BASE+160) - -#define V4L2_CID_MPEG_VIDC_IMG_GRID_DIMENSION \ - (V4L2_CID_MPEG_MSM_VIDC_BASE+161) - -enum v4l2_mpeg_vidc_video_mbi_statistics_mode { - V4L2_CID_MPEG_VIDC_VIDEO_MBI_MODE_DEFAULT = 0, - V4L2_CID_MPEG_VIDC_VIDEO_MBI_MODE_1 = 1, - V4L2_CID_MPEG_VIDC_VIDEO_MBI_MODE_2 = 2, - V4L2_CID_MPEG_VIDC_VIDEO_MBI_MODE_3 = 3, -}; - -enum vl42_mpeg_vidc_video_h264_svc_nal { - V4L2_CID_MPEG_VIDC_VIDEO_H264_NAL_SVC_DISABLED = 0, - V4L2_CID_MPEG_VIDC_VIDEO_H264_NAL_SVC_ENABLED = 1, -}; - -enum v4l2_mpeg_vidc_video_h264_vui_timing_info { - V4L2_MPEG_VIDC_VIDEO_H264_VUI_TIMING_INFO_DISABLED = 0, - V4L2_MPEG_VIDC_VIDEO_H264_VUI_TIMING_INFO_ENABLED = 1 -}; - -/* Camera class control IDs */ - -#define V4L2_CID_CAMERA_CLASS_BASE (V4L2_CTRL_CLASS_CAMERA | 0x900) -#define V4L2_CID_CAMERA_CLASS (V4L2_CTRL_CLASS_CAMERA | 1) - -#define V4L2_CID_EXPOSURE_AUTO (V4L2_CID_CAMERA_CLASS_BASE+1) -enum v4l2_exposure_auto_type { - V4L2_EXPOSURE_AUTO = 0, - V4L2_EXPOSURE_MANUAL = 1, - V4L2_EXPOSURE_SHUTTER_PRIORITY = 2, - V4L2_EXPOSURE_APERTURE_PRIORITY = 3 -}; -#define V4L2_CID_EXPOSURE_ABSOLUTE (V4L2_CID_CAMERA_CLASS_BASE+2) -#define V4L2_CID_EXPOSURE_AUTO_PRIORITY (V4L2_CID_CAMERA_CLASS_BASE+3) - -#define V4L2_CID_PAN_RELATIVE (V4L2_CID_CAMERA_CLASS_BASE+4) -#define V4L2_CID_TILT_RELATIVE (V4L2_CID_CAMERA_CLASS_BASE+5) -#define V4L2_CID_PAN_RESET (V4L2_CID_CAMERA_CLASS_BASE+6) -#define V4L2_CID_TILT_RESET (V4L2_CID_CAMERA_CLASS_BASE+7) - -#define V4L2_CID_PAN_ABSOLUTE (V4L2_CID_CAMERA_CLASS_BASE+8) -#define V4L2_CID_TILT_ABSOLUTE (V4L2_CID_CAMERA_CLASS_BASE+9) - -#define V4L2_CID_FOCUS_ABSOLUTE (V4L2_CID_CAMERA_CLASS_BASE+10) -#define V4L2_CID_FOCUS_RELATIVE (V4L2_CID_CAMERA_CLASS_BASE+11) -#define V4L2_CID_FOCUS_AUTO (V4L2_CID_CAMERA_CLASS_BASE+12) - -#define V4L2_CID_ZOOM_ABSOLUTE (V4L2_CID_CAMERA_CLASS_BASE+13) -#define V4L2_CID_ZOOM_RELATIVE (V4L2_CID_CAMERA_CLASS_BASE+14) -#define V4L2_CID_ZOOM_CONTINUOUS (V4L2_CID_CAMERA_CLASS_BASE+15) - -#define V4L2_CID_PRIVACY (V4L2_CID_CAMERA_CLASS_BASE+16) - -#define V4L2_CID_IRIS_ABSOLUTE (V4L2_CID_CAMERA_CLASS_BASE+17) -#define V4L2_CID_IRIS_RELATIVE (V4L2_CID_CAMERA_CLASS_BASE+18) - -#define V4L2_CID_AUTO_EXPOSURE_BIAS (V4L2_CID_CAMERA_CLASS_BASE+19) - -#define V4L2_CID_AUTO_N_PRESET_WHITE_BALANCE (V4L2_CID_CAMERA_CLASS_BASE+20) -enum v4l2_auto_n_preset_white_balance { - V4L2_WHITE_BALANCE_MANUAL = 0, - V4L2_WHITE_BALANCE_AUTO = 1, - V4L2_WHITE_BALANCE_INCANDESCENT = 2, - V4L2_WHITE_BALANCE_FLUORESCENT = 3, - V4L2_WHITE_BALANCE_FLUORESCENT_H = 4, - V4L2_WHITE_BALANCE_HORIZON = 5, - V4L2_WHITE_BALANCE_DAYLIGHT = 6, - V4L2_WHITE_BALANCE_FLASH = 7, - V4L2_WHITE_BALANCE_CLOUDY = 8, - V4L2_WHITE_BALANCE_SHADE = 9, -}; - -#define V4L2_CID_WIDE_DYNAMIC_RANGE (V4L2_CID_CAMERA_CLASS_BASE+21) -#define V4L2_CID_IMAGE_STABILIZATION (V4L2_CID_CAMERA_CLASS_BASE+22) - -#define V4L2_CID_ISO_SENSITIVITY (V4L2_CID_CAMERA_CLASS_BASE+23) -#define V4L2_CID_ISO_SENSITIVITY_AUTO (V4L2_CID_CAMERA_CLASS_BASE+24) -enum v4l2_iso_sensitivity_auto_type { - V4L2_ISO_SENSITIVITY_MANUAL = 0, - V4L2_ISO_SENSITIVITY_AUTO = 1, -}; - -#define V4L2_CID_EXPOSURE_METERING (V4L2_CID_CAMERA_CLASS_BASE+25) -enum v4l2_exposure_metering { - V4L2_EXPOSURE_METERING_AVERAGE = 0, - V4L2_EXPOSURE_METERING_CENTER_WEIGHTED = 1, - V4L2_EXPOSURE_METERING_SPOT = 2, - V4L2_EXPOSURE_METERING_MATRIX = 3, -}; - -#define V4L2_CID_SCENE_MODE (V4L2_CID_CAMERA_CLASS_BASE+26) -enum v4l2_scene_mode { - V4L2_SCENE_MODE_NONE = 0, - V4L2_SCENE_MODE_BACKLIGHT = 1, - V4L2_SCENE_MODE_BEACH_SNOW = 2, - V4L2_SCENE_MODE_CANDLE_LIGHT = 3, - V4L2_SCENE_MODE_DAWN_DUSK = 4, - V4L2_SCENE_MODE_FALL_COLORS = 5, - V4L2_SCENE_MODE_FIREWORKS = 6, - V4L2_SCENE_MODE_LANDSCAPE = 7, - V4L2_SCENE_MODE_NIGHT = 8, - V4L2_SCENE_MODE_PARTY_INDOOR = 9, - V4L2_SCENE_MODE_PORTRAIT = 10, - V4L2_SCENE_MODE_SPORTS = 11, - V4L2_SCENE_MODE_SUNSET = 12, - V4L2_SCENE_MODE_TEXT = 13, -}; - -#define V4L2_CID_3A_LOCK (V4L2_CID_CAMERA_CLASS_BASE+27) -#define V4L2_LOCK_EXPOSURE (1 << 0) -#define V4L2_LOCK_WHITE_BALANCE (1 << 1) -#define V4L2_LOCK_FOCUS (1 << 2) - -#define V4L2_CID_AUTO_FOCUS_START (V4L2_CID_CAMERA_CLASS_BASE+28) -#define V4L2_CID_AUTO_FOCUS_STOP (V4L2_CID_CAMERA_CLASS_BASE+29) -#define V4L2_CID_AUTO_FOCUS_STATUS (V4L2_CID_CAMERA_CLASS_BASE+30) -#define V4L2_AUTO_FOCUS_STATUS_IDLE (0 << 0) -#define V4L2_AUTO_FOCUS_STATUS_BUSY (1 << 0) -#define V4L2_AUTO_FOCUS_STATUS_REACHED (1 << 1) -#define V4L2_AUTO_FOCUS_STATUS_FAILED (1 << 2) - -#define V4L2_CID_AUTO_FOCUS_RANGE (V4L2_CID_CAMERA_CLASS_BASE+31) -enum v4l2_auto_focus_range { - V4L2_AUTO_FOCUS_RANGE_AUTO = 0, - V4L2_AUTO_FOCUS_RANGE_NORMAL = 1, - V4L2_AUTO_FOCUS_RANGE_MACRO = 2, - V4L2_AUTO_FOCUS_RANGE_INFINITY = 3, -}; - -#define V4L2_CID_PAN_SPEED (V4L2_CID_CAMERA_CLASS_BASE+32) -#define V4L2_CID_TILT_SPEED (V4L2_CID_CAMERA_CLASS_BASE+33) - -/* FM Modulator class control IDs */ - -#define V4L2_CID_FM_TX_CLASS_BASE (V4L2_CTRL_CLASS_FM_TX | 0x900) -#define V4L2_CID_FM_TX_CLASS (V4L2_CTRL_CLASS_FM_TX | 1) - -#define V4L2_CID_RDS_TX_DEVIATION (V4L2_CID_FM_TX_CLASS_BASE + 1) -#define V4L2_CID_RDS_TX_PI (V4L2_CID_FM_TX_CLASS_BASE + 2) -#define V4L2_CID_RDS_TX_PTY (V4L2_CID_FM_TX_CLASS_BASE + 3) -#define V4L2_CID_RDS_TX_PS_NAME (V4L2_CID_FM_TX_CLASS_BASE + 5) -#define V4L2_CID_RDS_TX_RADIO_TEXT (V4L2_CID_FM_TX_CLASS_BASE + 6) -#define V4L2_CID_RDS_TX_MONO_STEREO (V4L2_CID_FM_TX_CLASS_BASE + 7) -#define V4L2_CID_RDS_TX_ARTIFICIAL_HEAD (V4L2_CID_FM_TX_CLASS_BASE + 8) -#define V4L2_CID_RDS_TX_COMPRESSED (V4L2_CID_FM_TX_CLASS_BASE + 9) -#define V4L2_CID_RDS_TX_DYNAMIC_PTY (V4L2_CID_FM_TX_CLASS_BASE + 10) -#define V4L2_CID_RDS_TX_TRAFFIC_ANNOUNCEMENT (V4L2_CID_FM_TX_CLASS_BASE + 11) -#define V4L2_CID_RDS_TX_TRAFFIC_PROGRAM (V4L2_CID_FM_TX_CLASS_BASE + 12) -#define V4L2_CID_RDS_TX_MUSIC_SPEECH (V4L2_CID_FM_TX_CLASS_BASE + 13) -#define V4L2_CID_RDS_TX_ALT_FREQS_ENABLE (V4L2_CID_FM_TX_CLASS_BASE + 14) -#define V4L2_CID_RDS_TX_ALT_FREQS (V4L2_CID_FM_TX_CLASS_BASE + 15) - -#define V4L2_CID_AUDIO_LIMITER_ENABLED (V4L2_CID_FM_TX_CLASS_BASE + 64) -#define V4L2_CID_AUDIO_LIMITER_RELEASE_TIME (V4L2_CID_FM_TX_CLASS_BASE + 65) -#define V4L2_CID_AUDIO_LIMITER_DEVIATION (V4L2_CID_FM_TX_CLASS_BASE + 66) - -#define V4L2_CID_AUDIO_COMPRESSION_ENABLED (V4L2_CID_FM_TX_CLASS_BASE + 80) -#define V4L2_CID_AUDIO_COMPRESSION_GAIN (V4L2_CID_FM_TX_CLASS_BASE + 81) -#define V4L2_CID_AUDIO_COMPRESSION_THRESHOLD (V4L2_CID_FM_TX_CLASS_BASE + 82) -#define V4L2_CID_AUDIO_COMPRESSION_ATTACK_TIME (V4L2_CID_FM_TX_CLASS_BASE + 83) -#define V4L2_CID_AUDIO_COMPRESSION_RELEASE_TIME (V4L2_CID_FM_TX_CLASS_BASE + 84) - -#define V4L2_CID_PILOT_TONE_ENABLED (V4L2_CID_FM_TX_CLASS_BASE + 96) -#define V4L2_CID_PILOT_TONE_DEVIATION (V4L2_CID_FM_TX_CLASS_BASE + 97) -#define V4L2_CID_PILOT_TONE_FREQUENCY (V4L2_CID_FM_TX_CLASS_BASE + 98) - -#define V4L2_CID_TUNE_PREEMPHASIS (V4L2_CID_FM_TX_CLASS_BASE + 112) -enum v4l2_preemphasis { - V4L2_PREEMPHASIS_DISABLED = 0, - V4L2_PREEMPHASIS_50_uS = 1, - V4L2_PREEMPHASIS_75_uS = 2, -}; -#define V4L2_CID_TUNE_POWER_LEVEL (V4L2_CID_FM_TX_CLASS_BASE + 113) -#define V4L2_CID_TUNE_ANTENNA_CAPACITOR (V4L2_CID_FM_TX_CLASS_BASE + 114) - - -/* Flash and privacy (indicator) light controls */ - -#define V4L2_CID_FLASH_CLASS_BASE (V4L2_CTRL_CLASS_FLASH | 0x900) -#define V4L2_CID_FLASH_CLASS (V4L2_CTRL_CLASS_FLASH | 1) - -#define V4L2_CID_FLASH_LED_MODE (V4L2_CID_FLASH_CLASS_BASE + 1) -enum v4l2_flash_led_mode { - V4L2_FLASH_LED_MODE_NONE, - V4L2_FLASH_LED_MODE_FLASH, - V4L2_FLASH_LED_MODE_TORCH, -}; - -#define V4L2_CID_FLASH_STROBE_SOURCE (V4L2_CID_FLASH_CLASS_BASE + 2) -enum v4l2_flash_strobe_source { - V4L2_FLASH_STROBE_SOURCE_SOFTWARE, - V4L2_FLASH_STROBE_SOURCE_EXTERNAL, -}; - -#define V4L2_CID_FLASH_STROBE (V4L2_CID_FLASH_CLASS_BASE + 3) -#define V4L2_CID_FLASH_STROBE_STOP (V4L2_CID_FLASH_CLASS_BASE + 4) -#define V4L2_CID_FLASH_STROBE_STATUS (V4L2_CID_FLASH_CLASS_BASE + 5) - -#define V4L2_CID_FLASH_TIMEOUT (V4L2_CID_FLASH_CLASS_BASE + 6) -#define V4L2_CID_FLASH_INTENSITY (V4L2_CID_FLASH_CLASS_BASE + 7) -#define V4L2_CID_FLASH_TORCH_INTENSITY (V4L2_CID_FLASH_CLASS_BASE + 8) -#define V4L2_CID_FLASH_INDICATOR_INTENSITY (V4L2_CID_FLASH_CLASS_BASE + 9) - -#define V4L2_CID_FLASH_FAULT (V4L2_CID_FLASH_CLASS_BASE + 10) -#define V4L2_FLASH_FAULT_OVER_VOLTAGE (1 << 0) -#define V4L2_FLASH_FAULT_TIMEOUT (1 << 1) -#define V4L2_FLASH_FAULT_OVER_TEMPERATURE (1 << 2) -#define V4L2_FLASH_FAULT_SHORT_CIRCUIT (1 << 3) -#define V4L2_FLASH_FAULT_OVER_CURRENT (1 << 4) -#define V4L2_FLASH_FAULT_INDICATOR (1 << 5) -#define V4L2_FLASH_FAULT_UNDER_VOLTAGE (1 << 6) -#define V4L2_FLASH_FAULT_INPUT_VOLTAGE (1 << 7) -#define V4L2_FLASH_FAULT_LED_OVER_TEMPERATURE (1 << 8) - -#define V4L2_CID_FLASH_CHARGE (V4L2_CID_FLASH_CLASS_BASE + 11) -#define V4L2_CID_FLASH_READY (V4L2_CID_FLASH_CLASS_BASE + 12) - - -/* JPEG-class control IDs */ - -#define V4L2_CID_JPEG_CLASS_BASE (V4L2_CTRL_CLASS_JPEG | 0x900) -#define V4L2_CID_JPEG_CLASS (V4L2_CTRL_CLASS_JPEG | 1) - -#define V4L2_CID_JPEG_CHROMA_SUBSAMPLING (V4L2_CID_JPEG_CLASS_BASE + 1) -enum v4l2_jpeg_chroma_subsampling { - V4L2_JPEG_CHROMA_SUBSAMPLING_444 = 0, - V4L2_JPEG_CHROMA_SUBSAMPLING_422 = 1, - V4L2_JPEG_CHROMA_SUBSAMPLING_420 = 2, - V4L2_JPEG_CHROMA_SUBSAMPLING_411 = 3, - V4L2_JPEG_CHROMA_SUBSAMPLING_410 = 4, - V4L2_JPEG_CHROMA_SUBSAMPLING_GRAY = 5, -}; -#define V4L2_CID_JPEG_RESTART_INTERVAL (V4L2_CID_JPEG_CLASS_BASE + 2) -#define V4L2_CID_JPEG_COMPRESSION_QUALITY (V4L2_CID_JPEG_CLASS_BASE + 3) - -#define V4L2_CID_JPEG_ACTIVE_MARKER (V4L2_CID_JPEG_CLASS_BASE + 4) -#define V4L2_JPEG_ACTIVE_MARKER_APP0 (1 << 0) -#define V4L2_JPEG_ACTIVE_MARKER_APP1 (1 << 1) -#define V4L2_JPEG_ACTIVE_MARKER_COM (1 << 16) -#define V4L2_JPEG_ACTIVE_MARKER_DQT (1 << 17) -#define V4L2_JPEG_ACTIVE_MARKER_DHT (1 << 18) - - -/* Image source controls */ -#define V4L2_CID_IMAGE_SOURCE_CLASS_BASE (V4L2_CTRL_CLASS_IMAGE_SOURCE | 0x900) -#define V4L2_CID_IMAGE_SOURCE_CLASS (V4L2_CTRL_CLASS_IMAGE_SOURCE | 1) - -#define V4L2_CID_VBLANK (V4L2_CID_IMAGE_SOURCE_CLASS_BASE + 1) -#define V4L2_CID_HBLANK (V4L2_CID_IMAGE_SOURCE_CLASS_BASE + 2) -#define V4L2_CID_ANALOGUE_GAIN (V4L2_CID_IMAGE_SOURCE_CLASS_BASE + 3) -#define V4L2_CID_TEST_PATTERN_RED (V4L2_CID_IMAGE_SOURCE_CLASS_BASE + 4) -#define V4L2_CID_TEST_PATTERN_GREENR (V4L2_CID_IMAGE_SOURCE_CLASS_BASE + 5) -#define V4L2_CID_TEST_PATTERN_BLUE (V4L2_CID_IMAGE_SOURCE_CLASS_BASE + 6) -#define V4L2_CID_TEST_PATTERN_GREENB (V4L2_CID_IMAGE_SOURCE_CLASS_BASE + 7) - - -/* Image processing controls */ - -#define V4L2_CID_IMAGE_PROC_CLASS_BASE (V4L2_CTRL_CLASS_IMAGE_PROC | 0x900) -#define V4L2_CID_IMAGE_PROC_CLASS (V4L2_CTRL_CLASS_IMAGE_PROC | 1) - -#define V4L2_CID_LINK_FREQ (V4L2_CID_IMAGE_PROC_CLASS_BASE + 1) -#define V4L2_CID_PIXEL_RATE (V4L2_CID_IMAGE_PROC_CLASS_BASE + 2) -#define V4L2_CID_TEST_PATTERN (V4L2_CID_IMAGE_PROC_CLASS_BASE + 3) - - -/* DV-class control IDs defined by V4L2 */ -#define V4L2_CID_DV_CLASS_BASE (V4L2_CTRL_CLASS_DV | 0x900) -#define V4L2_CID_DV_CLASS (V4L2_CTRL_CLASS_DV | 1) - -#define V4L2_CID_DV_TX_HOTPLUG (V4L2_CID_DV_CLASS_BASE + 1) -#define V4L2_CID_DV_TX_RXSENSE (V4L2_CID_DV_CLASS_BASE + 2) -#define V4L2_CID_DV_TX_EDID_PRESENT (V4L2_CID_DV_CLASS_BASE + 3) -#define V4L2_CID_DV_TX_MODE (V4L2_CID_DV_CLASS_BASE + 4) -enum v4l2_dv_tx_mode { - V4L2_DV_TX_MODE_DVI_D = 0, - V4L2_DV_TX_MODE_HDMI = 1, -}; -#define V4L2_CID_DV_TX_RGB_RANGE (V4L2_CID_DV_CLASS_BASE + 5) -enum v4l2_dv_rgb_range { - V4L2_DV_RGB_RANGE_AUTO = 0, - V4L2_DV_RGB_RANGE_LIMITED = 1, - V4L2_DV_RGB_RANGE_FULL = 2, -}; - -#define V4L2_CID_DV_TX_IT_CONTENT_TYPE (V4L2_CID_DV_CLASS_BASE + 6) -enum v4l2_dv_it_content_type { - V4L2_DV_IT_CONTENT_TYPE_GRAPHICS = 0, - V4L2_DV_IT_CONTENT_TYPE_PHOTO = 1, - V4L2_DV_IT_CONTENT_TYPE_CINEMA = 2, - V4L2_DV_IT_CONTENT_TYPE_GAME = 3, - V4L2_DV_IT_CONTENT_TYPE_NO_ITC = 4, -}; - -#define V4L2_CID_DV_RX_POWER_PRESENT (V4L2_CID_DV_CLASS_BASE + 100) -#define V4L2_CID_DV_RX_RGB_RANGE (V4L2_CID_DV_CLASS_BASE + 101) -#define V4L2_CID_DV_RX_IT_CONTENT_TYPE (V4L2_CID_DV_CLASS_BASE + 102) - -#define V4L2_CID_FM_RX_CLASS_BASE (V4L2_CTRL_CLASS_FM_RX | 0x900) -#define V4L2_CID_FM_RX_CLASS (V4L2_CTRL_CLASS_FM_RX | 1) - -#define V4L2_CID_TUNE_DEEMPHASIS (V4L2_CID_FM_RX_CLASS_BASE + 1) -enum v4l2_deemphasis { - V4L2_DEEMPHASIS_DISABLED = V4L2_PREEMPHASIS_DISABLED, - V4L2_DEEMPHASIS_50_uS = V4L2_PREEMPHASIS_50_uS, - V4L2_DEEMPHASIS_75_uS = V4L2_PREEMPHASIS_75_uS, -}; - -#define V4L2_CID_RDS_RECEPTION (V4L2_CID_FM_RX_CLASS_BASE + 2) -#define V4L2_CID_RDS_RX_PTY (V4L2_CID_FM_RX_CLASS_BASE + 3) -#define V4L2_CID_RDS_RX_PS_NAME (V4L2_CID_FM_RX_CLASS_BASE + 4) -#define V4L2_CID_RDS_RX_RADIO_TEXT (V4L2_CID_FM_RX_CLASS_BASE + 5) -#define V4L2_CID_RDS_RX_TRAFFIC_ANNOUNCEMENT (V4L2_CID_FM_RX_CLASS_BASE + 6) -#define V4L2_CID_RDS_RX_TRAFFIC_PROGRAM (V4L2_CID_FM_RX_CLASS_BASE + 7) -#define V4L2_CID_RDS_RX_MUSIC_SPEECH (V4L2_CID_FM_RX_CLASS_BASE + 8) - -#define V4L2_CID_RF_TUNER_CLASS_BASE (V4L2_CTRL_CLASS_RF_TUNER | 0x900) -#define V4L2_CID_RF_TUNER_CLASS (V4L2_CTRL_CLASS_RF_TUNER | 1) - -#define V4L2_CID_RF_TUNER_BANDWIDTH_AUTO (V4L2_CID_RF_TUNER_CLASS_BASE + 11) -#define V4L2_CID_RF_TUNER_BANDWIDTH (V4L2_CID_RF_TUNER_CLASS_BASE + 12) -#define V4L2_CID_RF_TUNER_RF_GAIN (V4L2_CID_RF_TUNER_CLASS_BASE + 32) -#define V4L2_CID_RF_TUNER_LNA_GAIN_AUTO (V4L2_CID_RF_TUNER_CLASS_BASE + 41) -#define V4L2_CID_RF_TUNER_LNA_GAIN (V4L2_CID_RF_TUNER_CLASS_BASE + 42) -#define V4L2_CID_RF_TUNER_MIXER_GAIN_AUTO (V4L2_CID_RF_TUNER_CLASS_BASE + 51) -#define V4L2_CID_RF_TUNER_MIXER_GAIN (V4L2_CID_RF_TUNER_CLASS_BASE + 52) -#define V4L2_CID_RF_TUNER_IF_GAIN_AUTO (V4L2_CID_RF_TUNER_CLASS_BASE + 61) -#define V4L2_CID_RF_TUNER_IF_GAIN (V4L2_CID_RF_TUNER_CLASS_BASE + 62) -#define V4L2_CID_RF_TUNER_PLL_LOCK (V4L2_CID_RF_TUNER_CLASS_BASE + 91) - - -/* Detection-class control IDs defined by V4L2 */ -#define V4L2_CID_DETECT_CLASS_BASE (V4L2_CTRL_CLASS_DETECT | 0x900) -#define V4L2_CID_DETECT_CLASS (V4L2_CTRL_CLASS_DETECT | 1) - -#define V4L2_CID_DETECT_MD_MODE (V4L2_CID_DETECT_CLASS_BASE + 1) -enum v4l2_detect_md_mode { - V4L2_DETECT_MD_MODE_DISABLED = 0, - V4L2_DETECT_MD_MODE_GLOBAL = 1, - V4L2_DETECT_MD_MODE_THRESHOLD_GRID = 2, - V4L2_DETECT_MD_MODE_REGION_GRID = 3, -}; -#define V4L2_CID_DETECT_MD_GLOBAL_THRESHOLD (V4L2_CID_DETECT_CLASS_BASE + 2) -#define V4L2_CID_DETECT_MD_THRESHOLD_GRID (V4L2_CID_DETECT_CLASS_BASE + 3) -#define V4L2_CID_DETECT_MD_REGION_GRID (V4L2_CID_DETECT_CLASS_BASE + 4) - -#endif diff --git a/third_party/mapd_pfeiferj/mapd b/third_party/mapd_pfeiferj/mapd deleted file mode 100755 index d24d9b757f..0000000000 Binary files a/third_party/mapd_pfeiferj/mapd and /dev/null differ diff --git a/third_party/opencl/include/CL/cl.h b/third_party/opencl/include/CL/cl.h deleted file mode 100644 index 0086319f5f..0000000000 --- a/third_party/opencl/include/CL/cl.h +++ /dev/null @@ -1,1452 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008-2015 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are 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 Materials. - * - * MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS - * KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS - * SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT - * https://www.khronos.org/registry/ - * - * THE MATERIALS ARE 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 - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - ******************************************************************************/ - -#ifndef __OPENCL_CL_H -#define __OPENCL_CL_H - -#ifdef __APPLE__ -#include -#else -#include -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -/******************************************************************************/ - -typedef struct _cl_platform_id * cl_platform_id; -typedef struct _cl_device_id * cl_device_id; -typedef struct _cl_context * cl_context; -typedef struct _cl_command_queue * cl_command_queue; -typedef struct _cl_mem * cl_mem; -typedef struct _cl_program * cl_program; -typedef struct _cl_kernel * cl_kernel; -typedef struct _cl_event * cl_event; -typedef struct _cl_sampler * cl_sampler; - -typedef cl_uint cl_bool; /* WARNING! Unlike cl_ types in cl_platform.h, cl_bool is not guaranteed to be the same size as the bool in kernels. */ -typedef cl_ulong cl_bitfield; -typedef cl_bitfield cl_device_type; -typedef cl_uint cl_platform_info; -typedef cl_uint cl_device_info; -typedef cl_bitfield cl_device_fp_config; -typedef cl_uint cl_device_mem_cache_type; -typedef cl_uint cl_device_local_mem_type; -typedef cl_bitfield cl_device_exec_capabilities; -typedef cl_bitfield cl_device_svm_capabilities; -typedef cl_bitfield cl_command_queue_properties; -typedef intptr_t cl_device_partition_property; -typedef cl_bitfield cl_device_affinity_domain; - -typedef intptr_t cl_context_properties; -typedef cl_uint cl_context_info; -typedef cl_bitfield cl_queue_properties; -typedef cl_uint cl_command_queue_info; -typedef cl_uint cl_channel_order; -typedef cl_uint cl_channel_type; -typedef cl_bitfield cl_mem_flags; -typedef cl_bitfield cl_svm_mem_flags; -typedef cl_uint cl_mem_object_type; -typedef cl_uint cl_mem_info; -typedef cl_bitfield cl_mem_migration_flags; -typedef cl_uint cl_image_info; -typedef cl_uint cl_buffer_create_type; -typedef cl_uint cl_addressing_mode; -typedef cl_uint cl_filter_mode; -typedef cl_uint cl_sampler_info; -typedef cl_bitfield cl_map_flags; -typedef intptr_t cl_pipe_properties; -typedef cl_uint cl_pipe_info; -typedef cl_uint cl_program_info; -typedef cl_uint cl_program_build_info; -typedef cl_uint cl_program_binary_type; -typedef cl_int cl_build_status; -typedef cl_uint cl_kernel_info; -typedef cl_uint cl_kernel_arg_info; -typedef cl_uint cl_kernel_arg_address_qualifier; -typedef cl_uint cl_kernel_arg_access_qualifier; -typedef cl_bitfield cl_kernel_arg_type_qualifier; -typedef cl_uint cl_kernel_work_group_info; -typedef cl_uint cl_kernel_sub_group_info; -typedef cl_uint cl_event_info; -typedef cl_uint cl_command_type; -typedef cl_uint cl_profiling_info; -typedef cl_bitfield cl_sampler_properties; -typedef cl_uint cl_kernel_exec_info; - -typedef struct _cl_image_format { - cl_channel_order image_channel_order; - cl_channel_type image_channel_data_type; -} cl_image_format; - -typedef struct _cl_image_desc { - cl_mem_object_type image_type; - size_t image_width; - size_t image_height; - size_t image_depth; - size_t image_array_size; - size_t image_row_pitch; - size_t image_slice_pitch; - cl_uint num_mip_levels; - cl_uint num_samples; -#ifdef __GNUC__ - __extension__ /* Prevents warnings about anonymous union in -pedantic builds */ -#endif - union { - cl_mem buffer; - cl_mem mem_object; - }; -} cl_image_desc; - -typedef struct _cl_buffer_region { - size_t origin; - size_t size; -} cl_buffer_region; - - -/******************************************************************************/ - -/* Error Codes */ -#define CL_SUCCESS 0 -#define CL_DEVICE_NOT_FOUND -1 -#define CL_DEVICE_NOT_AVAILABLE -2 -#define CL_COMPILER_NOT_AVAILABLE -3 -#define CL_MEM_OBJECT_ALLOCATION_FAILURE -4 -#define CL_OUT_OF_RESOURCES -5 -#define CL_OUT_OF_HOST_MEMORY -6 -#define CL_PROFILING_INFO_NOT_AVAILABLE -7 -#define CL_MEM_COPY_OVERLAP -8 -#define CL_IMAGE_FORMAT_MISMATCH -9 -#define CL_IMAGE_FORMAT_NOT_SUPPORTED -10 -#define CL_BUILD_PROGRAM_FAILURE -11 -#define CL_MAP_FAILURE -12 -#define CL_MISALIGNED_SUB_BUFFER_OFFSET -13 -#define CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST -14 -#define CL_COMPILE_PROGRAM_FAILURE -15 -#define CL_LINKER_NOT_AVAILABLE -16 -#define CL_LINK_PROGRAM_FAILURE -17 -#define CL_DEVICE_PARTITION_FAILED -18 -#define CL_KERNEL_ARG_INFO_NOT_AVAILABLE -19 - -#define CL_INVALID_VALUE -30 -#define CL_INVALID_DEVICE_TYPE -31 -#define CL_INVALID_PLATFORM -32 -#define CL_INVALID_DEVICE -33 -#define CL_INVALID_CONTEXT -34 -#define CL_INVALID_QUEUE_PROPERTIES -35 -#define CL_INVALID_COMMAND_QUEUE -36 -#define CL_INVALID_HOST_PTR -37 -#define CL_INVALID_MEM_OBJECT -38 -#define CL_INVALID_IMAGE_FORMAT_DESCRIPTOR -39 -#define CL_INVALID_IMAGE_SIZE -40 -#define CL_INVALID_SAMPLER -41 -#define CL_INVALID_BINARY -42 -#define CL_INVALID_BUILD_OPTIONS -43 -#define CL_INVALID_PROGRAM -44 -#define CL_INVALID_PROGRAM_EXECUTABLE -45 -#define CL_INVALID_KERNEL_NAME -46 -#define CL_INVALID_KERNEL_DEFINITION -47 -#define CL_INVALID_KERNEL -48 -#define CL_INVALID_ARG_INDEX -49 -#define CL_INVALID_ARG_VALUE -50 -#define CL_INVALID_ARG_SIZE -51 -#define CL_INVALID_KERNEL_ARGS -52 -#define CL_INVALID_WORK_DIMENSION -53 -#define CL_INVALID_WORK_GROUP_SIZE -54 -#define CL_INVALID_WORK_ITEM_SIZE -55 -#define CL_INVALID_GLOBAL_OFFSET -56 -#define CL_INVALID_EVENT_WAIT_LIST -57 -#define CL_INVALID_EVENT -58 -#define CL_INVALID_OPERATION -59 -#define CL_INVALID_GL_OBJECT -60 -#define CL_INVALID_BUFFER_SIZE -61 -#define CL_INVALID_MIP_LEVEL -62 -#define CL_INVALID_GLOBAL_WORK_SIZE -63 -#define CL_INVALID_PROPERTY -64 -#define CL_INVALID_IMAGE_DESCRIPTOR -65 -#define CL_INVALID_COMPILER_OPTIONS -66 -#define CL_INVALID_LINKER_OPTIONS -67 -#define CL_INVALID_DEVICE_PARTITION_COUNT -68 -#define CL_INVALID_PIPE_SIZE -69 -#define CL_INVALID_DEVICE_QUEUE -70 - -/* OpenCL Version */ -#define CL_VERSION_1_0 1 -#define CL_VERSION_1_1 1 -#define CL_VERSION_1_2 1 -#define CL_VERSION_2_0 1 -#define CL_VERSION_2_1 1 - -/* cl_bool */ -#define CL_FALSE 0 -#define CL_TRUE 1 -#define CL_BLOCKING CL_TRUE -#define CL_NON_BLOCKING CL_FALSE - -/* cl_platform_info */ -#define CL_PLATFORM_PROFILE 0x0900 -#define CL_PLATFORM_VERSION 0x0901 -#define CL_PLATFORM_NAME 0x0902 -#define CL_PLATFORM_VENDOR 0x0903 -#define CL_PLATFORM_EXTENSIONS 0x0904 -#define CL_PLATFORM_HOST_TIMER_RESOLUTION 0x0905 - -/* cl_device_type - bitfield */ -#define CL_DEVICE_TYPE_DEFAULT (1 << 0) -#define CL_DEVICE_TYPE_CPU (1 << 1) -#define CL_DEVICE_TYPE_GPU (1 << 2) -#define CL_DEVICE_TYPE_ACCELERATOR (1 << 3) -#define CL_DEVICE_TYPE_CUSTOM (1 << 4) -#define CL_DEVICE_TYPE_ALL 0xFFFFFFFF - -/* cl_device_info */ -#define CL_DEVICE_TYPE 0x1000 -#define CL_DEVICE_VENDOR_ID 0x1001 -#define CL_DEVICE_MAX_COMPUTE_UNITS 0x1002 -#define CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS 0x1003 -#define CL_DEVICE_MAX_WORK_GROUP_SIZE 0x1004 -#define CL_DEVICE_MAX_WORK_ITEM_SIZES 0x1005 -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR 0x1006 -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT 0x1007 -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT 0x1008 -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG 0x1009 -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT 0x100A -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE 0x100B -#define CL_DEVICE_MAX_CLOCK_FREQUENCY 0x100C -#define CL_DEVICE_ADDRESS_BITS 0x100D -#define CL_DEVICE_MAX_READ_IMAGE_ARGS 0x100E -#define CL_DEVICE_MAX_WRITE_IMAGE_ARGS 0x100F -#define CL_DEVICE_MAX_MEM_ALLOC_SIZE 0x1010 -#define CL_DEVICE_IMAGE2D_MAX_WIDTH 0x1011 -#define CL_DEVICE_IMAGE2D_MAX_HEIGHT 0x1012 -#define CL_DEVICE_IMAGE3D_MAX_WIDTH 0x1013 -#define CL_DEVICE_IMAGE3D_MAX_HEIGHT 0x1014 -#define CL_DEVICE_IMAGE3D_MAX_DEPTH 0x1015 -#define CL_DEVICE_IMAGE_SUPPORT 0x1016 -#define CL_DEVICE_MAX_PARAMETER_SIZE 0x1017 -#define CL_DEVICE_MAX_SAMPLERS 0x1018 -#define CL_DEVICE_MEM_BASE_ADDR_ALIGN 0x1019 -#define CL_DEVICE_MIN_DATA_TYPE_ALIGN_SIZE 0x101A -#define CL_DEVICE_SINGLE_FP_CONFIG 0x101B -#define CL_DEVICE_GLOBAL_MEM_CACHE_TYPE 0x101C -#define CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE 0x101D -#define CL_DEVICE_GLOBAL_MEM_CACHE_SIZE 0x101E -#define CL_DEVICE_GLOBAL_MEM_SIZE 0x101F -#define CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE 0x1020 -#define CL_DEVICE_MAX_CONSTANT_ARGS 0x1021 -#define CL_DEVICE_LOCAL_MEM_TYPE 0x1022 -#define CL_DEVICE_LOCAL_MEM_SIZE 0x1023 -#define CL_DEVICE_ERROR_CORRECTION_SUPPORT 0x1024 -#define CL_DEVICE_PROFILING_TIMER_RESOLUTION 0x1025 -#define CL_DEVICE_ENDIAN_LITTLE 0x1026 -#define CL_DEVICE_AVAILABLE 0x1027 -#define CL_DEVICE_COMPILER_AVAILABLE 0x1028 -#define CL_DEVICE_EXECUTION_CAPABILITIES 0x1029 -#define CL_DEVICE_QUEUE_PROPERTIES 0x102A /* deprecated */ -#define CL_DEVICE_QUEUE_ON_HOST_PROPERTIES 0x102A -#define CL_DEVICE_NAME 0x102B -#define CL_DEVICE_VENDOR 0x102C -#define CL_DRIVER_VERSION 0x102D -#define CL_DEVICE_PROFILE 0x102E -#define CL_DEVICE_VERSION 0x102F -#define CL_DEVICE_EXTENSIONS 0x1030 -#define CL_DEVICE_PLATFORM 0x1031 -#define CL_DEVICE_DOUBLE_FP_CONFIG 0x1032 -/* 0x1033 reserved for CL_DEVICE_HALF_FP_CONFIG */ -#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_HALF 0x1034 -#define CL_DEVICE_HOST_UNIFIED_MEMORY 0x1035 /* deprecated */ -#define CL_DEVICE_NATIVE_VECTOR_WIDTH_CHAR 0x1036 -#define CL_DEVICE_NATIVE_VECTOR_WIDTH_SHORT 0x1037 -#define CL_DEVICE_NATIVE_VECTOR_WIDTH_INT 0x1038 -#define CL_DEVICE_NATIVE_VECTOR_WIDTH_LONG 0x1039 -#define CL_DEVICE_NATIVE_VECTOR_WIDTH_FLOAT 0x103A -#define CL_DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE 0x103B -#define CL_DEVICE_NATIVE_VECTOR_WIDTH_HALF 0x103C -#define CL_DEVICE_OPENCL_C_VERSION 0x103D -#define CL_DEVICE_LINKER_AVAILABLE 0x103E -#define CL_DEVICE_BUILT_IN_KERNELS 0x103F -#define CL_DEVICE_IMAGE_MAX_BUFFER_SIZE 0x1040 -#define CL_DEVICE_IMAGE_MAX_ARRAY_SIZE 0x1041 -#define CL_DEVICE_PARENT_DEVICE 0x1042 -#define CL_DEVICE_PARTITION_MAX_SUB_DEVICES 0x1043 -#define CL_DEVICE_PARTITION_PROPERTIES 0x1044 -#define CL_DEVICE_PARTITION_AFFINITY_DOMAIN 0x1045 -#define CL_DEVICE_PARTITION_TYPE 0x1046 -#define CL_DEVICE_REFERENCE_COUNT 0x1047 -#define CL_DEVICE_PREFERRED_INTEROP_USER_SYNC 0x1048 -#define CL_DEVICE_PRINTF_BUFFER_SIZE 0x1049 -#define CL_DEVICE_IMAGE_PITCH_ALIGNMENT 0x104A -#define CL_DEVICE_IMAGE_BASE_ADDRESS_ALIGNMENT 0x104B -#define CL_DEVICE_MAX_READ_WRITE_IMAGE_ARGS 0x104C -#define CL_DEVICE_MAX_GLOBAL_VARIABLE_SIZE 0x104D -#define CL_DEVICE_QUEUE_ON_DEVICE_PROPERTIES 0x104E -#define CL_DEVICE_QUEUE_ON_DEVICE_PREFERRED_SIZE 0x104F -#define CL_DEVICE_QUEUE_ON_DEVICE_MAX_SIZE 0x1050 -#define CL_DEVICE_MAX_ON_DEVICE_QUEUES 0x1051 -#define CL_DEVICE_MAX_ON_DEVICE_EVENTS 0x1052 -#define CL_DEVICE_SVM_CAPABILITIES 0x1053 -#define CL_DEVICE_GLOBAL_VARIABLE_PREFERRED_TOTAL_SIZE 0x1054 -#define CL_DEVICE_MAX_PIPE_ARGS 0x1055 -#define CL_DEVICE_PIPE_MAX_ACTIVE_RESERVATIONS 0x1056 -#define CL_DEVICE_PIPE_MAX_PACKET_SIZE 0x1057 -#define CL_DEVICE_PREFERRED_PLATFORM_ATOMIC_ALIGNMENT 0x1058 -#define CL_DEVICE_PREFERRED_GLOBAL_ATOMIC_ALIGNMENT 0x1059 -#define CL_DEVICE_PREFERRED_LOCAL_ATOMIC_ALIGNMENT 0x105A -#define CL_DEVICE_IL_VERSION 0x105B -#define CL_DEVICE_MAX_NUM_SUB_GROUPS 0x105C -#define CL_DEVICE_SUB_GROUP_INDEPENDENT_FORWARD_PROGRESS 0x105D - -/* cl_device_fp_config - bitfield */ -#define CL_FP_DENORM (1 << 0) -#define CL_FP_INF_NAN (1 << 1) -#define CL_FP_ROUND_TO_NEAREST (1 << 2) -#define CL_FP_ROUND_TO_ZERO (1 << 3) -#define CL_FP_ROUND_TO_INF (1 << 4) -#define CL_FP_FMA (1 << 5) -#define CL_FP_SOFT_FLOAT (1 << 6) -#define CL_FP_CORRECTLY_ROUNDED_DIVIDE_SQRT (1 << 7) - -/* cl_device_mem_cache_type */ -#define CL_NONE 0x0 -#define CL_READ_ONLY_CACHE 0x1 -#define CL_READ_WRITE_CACHE 0x2 - -/* cl_device_local_mem_type */ -#define CL_LOCAL 0x1 -#define CL_GLOBAL 0x2 - -/* cl_device_exec_capabilities - bitfield */ -#define CL_EXEC_KERNEL (1 << 0) -#define CL_EXEC_NATIVE_KERNEL (1 << 1) - -/* cl_command_queue_properties - bitfield */ -#define CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE (1 << 0) -#define CL_QUEUE_PROFILING_ENABLE (1 << 1) -#define CL_QUEUE_ON_DEVICE (1 << 2) -#define CL_QUEUE_ON_DEVICE_DEFAULT (1 << 3) - -/* cl_context_info */ -#define CL_CONTEXT_REFERENCE_COUNT 0x1080 -#define CL_CONTEXT_DEVICES 0x1081 -#define CL_CONTEXT_PROPERTIES 0x1082 -#define CL_CONTEXT_NUM_DEVICES 0x1083 - -/* cl_context_properties */ -#define CL_CONTEXT_PLATFORM 0x1084 -#define CL_CONTEXT_INTEROP_USER_SYNC 0x1085 - -/* cl_device_partition_property */ -#define CL_DEVICE_PARTITION_EQUALLY 0x1086 -#define CL_DEVICE_PARTITION_BY_COUNTS 0x1087 -#define CL_DEVICE_PARTITION_BY_COUNTS_LIST_END 0x0 -#define CL_DEVICE_PARTITION_BY_AFFINITY_DOMAIN 0x1088 - -/* cl_device_affinity_domain */ -#define CL_DEVICE_AFFINITY_DOMAIN_NUMA (1 << 0) -#define CL_DEVICE_AFFINITY_DOMAIN_L4_CACHE (1 << 1) -#define CL_DEVICE_AFFINITY_DOMAIN_L3_CACHE (1 << 2) -#define CL_DEVICE_AFFINITY_DOMAIN_L2_CACHE (1 << 3) -#define CL_DEVICE_AFFINITY_DOMAIN_L1_CACHE (1 << 4) -#define CL_DEVICE_AFFINITY_DOMAIN_NEXT_PARTITIONABLE (1 << 5) - -/* cl_device_svm_capabilities */ -#define CL_DEVICE_SVM_COARSE_GRAIN_BUFFER (1 << 0) -#define CL_DEVICE_SVM_FINE_GRAIN_BUFFER (1 << 1) -#define CL_DEVICE_SVM_FINE_GRAIN_SYSTEM (1 << 2) -#define CL_DEVICE_SVM_ATOMICS (1 << 3) - -/* cl_command_queue_info */ -#define CL_QUEUE_CONTEXT 0x1090 -#define CL_QUEUE_DEVICE 0x1091 -#define CL_QUEUE_REFERENCE_COUNT 0x1092 -#define CL_QUEUE_PROPERTIES 0x1093 -#define CL_QUEUE_SIZE 0x1094 -#define CL_QUEUE_DEVICE_DEFAULT 0x1095 - -/* cl_mem_flags and cl_svm_mem_flags - bitfield */ -#define CL_MEM_READ_WRITE (1 << 0) -#define CL_MEM_WRITE_ONLY (1 << 1) -#define CL_MEM_READ_ONLY (1 << 2) -#define CL_MEM_USE_HOST_PTR (1 << 3) -#define CL_MEM_ALLOC_HOST_PTR (1 << 4) -#define CL_MEM_COPY_HOST_PTR (1 << 5) -/* reserved (1 << 6) */ -#define CL_MEM_HOST_WRITE_ONLY (1 << 7) -#define CL_MEM_HOST_READ_ONLY (1 << 8) -#define CL_MEM_HOST_NO_ACCESS (1 << 9) -#define CL_MEM_SVM_FINE_GRAIN_BUFFER (1 << 10) /* used by cl_svm_mem_flags only */ -#define CL_MEM_SVM_ATOMICS (1 << 11) /* used by cl_svm_mem_flags only */ -#define CL_MEM_KERNEL_READ_AND_WRITE (1 << 12) - -/* cl_mem_migration_flags - bitfield */ -#define CL_MIGRATE_MEM_OBJECT_HOST (1 << 0) -#define CL_MIGRATE_MEM_OBJECT_CONTENT_UNDEFINED (1 << 1) - -/* cl_channel_order */ -#define CL_R 0x10B0 -#define CL_A 0x10B1 -#define CL_RG 0x10B2 -#define CL_RA 0x10B3 -#define CL_RGB 0x10B4 -#define CL_RGBA 0x10B5 -#define CL_BGRA 0x10B6 -#define CL_ARGB 0x10B7 -#define CL_INTENSITY 0x10B8 -#define CL_LUMINANCE 0x10B9 -#define CL_Rx 0x10BA -#define CL_RGx 0x10BB -#define CL_RGBx 0x10BC -#define CL_DEPTH 0x10BD -#define CL_DEPTH_STENCIL 0x10BE -#define CL_sRGB 0x10BF -#define CL_sRGBx 0x10C0 -#define CL_sRGBA 0x10C1 -#define CL_sBGRA 0x10C2 -#define CL_ABGR 0x10C3 - -/* cl_channel_type */ -#define CL_SNORM_INT8 0x10D0 -#define CL_SNORM_INT16 0x10D1 -#define CL_UNORM_INT8 0x10D2 -#define CL_UNORM_INT16 0x10D3 -#define CL_UNORM_SHORT_565 0x10D4 -#define CL_UNORM_SHORT_555 0x10D5 -#define CL_UNORM_INT_101010 0x10D6 -#define CL_SIGNED_INT8 0x10D7 -#define CL_SIGNED_INT16 0x10D8 -#define CL_SIGNED_INT32 0x10D9 -#define CL_UNSIGNED_INT8 0x10DA -#define CL_UNSIGNED_INT16 0x10DB -#define CL_UNSIGNED_INT32 0x10DC -#define CL_HALF_FLOAT 0x10DD -#define CL_FLOAT 0x10DE -#define CL_UNORM_INT24 0x10DF -#define CL_UNORM_INT_101010_2 0x10E0 - -/* cl_mem_object_type */ -#define CL_MEM_OBJECT_BUFFER 0x10F0 -#define CL_MEM_OBJECT_IMAGE2D 0x10F1 -#define CL_MEM_OBJECT_IMAGE3D 0x10F2 -#define CL_MEM_OBJECT_IMAGE2D_ARRAY 0x10F3 -#define CL_MEM_OBJECT_IMAGE1D 0x10F4 -#define CL_MEM_OBJECT_IMAGE1D_ARRAY 0x10F5 -#define CL_MEM_OBJECT_IMAGE1D_BUFFER 0x10F6 -#define CL_MEM_OBJECT_PIPE 0x10F7 - -/* cl_mem_info */ -#define CL_MEM_TYPE 0x1100 -#define CL_MEM_FLAGS 0x1101 -#define CL_MEM_SIZE 0x1102 -#define CL_MEM_HOST_PTR 0x1103 -#define CL_MEM_MAP_COUNT 0x1104 -#define CL_MEM_REFERENCE_COUNT 0x1105 -#define CL_MEM_CONTEXT 0x1106 -#define CL_MEM_ASSOCIATED_MEMOBJECT 0x1107 -#define CL_MEM_OFFSET 0x1108 -#define CL_MEM_USES_SVM_POINTER 0x1109 - -/* cl_image_info */ -#define CL_IMAGE_FORMAT 0x1110 -#define CL_IMAGE_ELEMENT_SIZE 0x1111 -#define CL_IMAGE_ROW_PITCH 0x1112 -#define CL_IMAGE_SLICE_PITCH 0x1113 -#define CL_IMAGE_WIDTH 0x1114 -#define CL_IMAGE_HEIGHT 0x1115 -#define CL_IMAGE_DEPTH 0x1116 -#define CL_IMAGE_ARRAY_SIZE 0x1117 -#define CL_IMAGE_BUFFER 0x1118 -#define CL_IMAGE_NUM_MIP_LEVELS 0x1119 -#define CL_IMAGE_NUM_SAMPLES 0x111A - -/* cl_pipe_info */ -#define CL_PIPE_PACKET_SIZE 0x1120 -#define CL_PIPE_MAX_PACKETS 0x1121 - -/* cl_addressing_mode */ -#define CL_ADDRESS_NONE 0x1130 -#define CL_ADDRESS_CLAMP_TO_EDGE 0x1131 -#define CL_ADDRESS_CLAMP 0x1132 -#define CL_ADDRESS_REPEAT 0x1133 -#define CL_ADDRESS_MIRRORED_REPEAT 0x1134 - -/* cl_filter_mode */ -#define CL_FILTER_NEAREST 0x1140 -#define CL_FILTER_LINEAR 0x1141 - -/* cl_sampler_info */ -#define CL_SAMPLER_REFERENCE_COUNT 0x1150 -#define CL_SAMPLER_CONTEXT 0x1151 -#define CL_SAMPLER_NORMALIZED_COORDS 0x1152 -#define CL_SAMPLER_ADDRESSING_MODE 0x1153 -#define CL_SAMPLER_FILTER_MODE 0x1154 -#define CL_SAMPLER_MIP_FILTER_MODE 0x1155 -#define CL_SAMPLER_LOD_MIN 0x1156 -#define CL_SAMPLER_LOD_MAX 0x1157 - -/* cl_map_flags - bitfield */ -#define CL_MAP_READ (1 << 0) -#define CL_MAP_WRITE (1 << 1) -#define CL_MAP_WRITE_INVALIDATE_REGION (1 << 2) - -/* cl_program_info */ -#define CL_PROGRAM_REFERENCE_COUNT 0x1160 -#define CL_PROGRAM_CONTEXT 0x1161 -#define CL_PROGRAM_NUM_DEVICES 0x1162 -#define CL_PROGRAM_DEVICES 0x1163 -#define CL_PROGRAM_SOURCE 0x1164 -#define CL_PROGRAM_BINARY_SIZES 0x1165 -#define CL_PROGRAM_BINARIES 0x1166 -#define CL_PROGRAM_NUM_KERNELS 0x1167 -#define CL_PROGRAM_KERNEL_NAMES 0x1168 -#define CL_PROGRAM_IL 0x1169 - -/* cl_program_build_info */ -#define CL_PROGRAM_BUILD_STATUS 0x1181 -#define CL_PROGRAM_BUILD_OPTIONS 0x1182 -#define CL_PROGRAM_BUILD_LOG 0x1183 -#define CL_PROGRAM_BINARY_TYPE 0x1184 -#define CL_PROGRAM_BUILD_GLOBAL_VARIABLE_TOTAL_SIZE 0x1185 - -/* cl_program_binary_type */ -#define CL_PROGRAM_BINARY_TYPE_NONE 0x0 -#define CL_PROGRAM_BINARY_TYPE_COMPILED_OBJECT 0x1 -#define CL_PROGRAM_BINARY_TYPE_LIBRARY 0x2 -#define CL_PROGRAM_BINARY_TYPE_EXECUTABLE 0x4 - -/* cl_build_status */ -#define CL_BUILD_SUCCESS 0 -#define CL_BUILD_NONE -1 -#define CL_BUILD_ERROR -2 -#define CL_BUILD_IN_PROGRESS -3 - -/* cl_kernel_info */ -#define CL_KERNEL_FUNCTION_NAME 0x1190 -#define CL_KERNEL_NUM_ARGS 0x1191 -#define CL_KERNEL_REFERENCE_COUNT 0x1192 -#define CL_KERNEL_CONTEXT 0x1193 -#define CL_KERNEL_PROGRAM 0x1194 -#define CL_KERNEL_ATTRIBUTES 0x1195 -#define CL_KERNEL_MAX_NUM_SUB_GROUPS 0x11B9 -#define CL_KERNEL_COMPILE_NUM_SUB_GROUPS 0x11BA - -/* cl_kernel_arg_info */ -#define CL_KERNEL_ARG_ADDRESS_QUALIFIER 0x1196 -#define CL_KERNEL_ARG_ACCESS_QUALIFIER 0x1197 -#define CL_KERNEL_ARG_TYPE_NAME 0x1198 -#define CL_KERNEL_ARG_TYPE_QUALIFIER 0x1199 -#define CL_KERNEL_ARG_NAME 0x119A - -/* cl_kernel_arg_address_qualifier */ -#define CL_KERNEL_ARG_ADDRESS_GLOBAL 0x119B -#define CL_KERNEL_ARG_ADDRESS_LOCAL 0x119C -#define CL_KERNEL_ARG_ADDRESS_CONSTANT 0x119D -#define CL_KERNEL_ARG_ADDRESS_PRIVATE 0x119E - -/* cl_kernel_arg_access_qualifier */ -#define CL_KERNEL_ARG_ACCESS_READ_ONLY 0x11A0 -#define CL_KERNEL_ARG_ACCESS_WRITE_ONLY 0x11A1 -#define CL_KERNEL_ARG_ACCESS_READ_WRITE 0x11A2 -#define CL_KERNEL_ARG_ACCESS_NONE 0x11A3 - -/* cl_kernel_arg_type_qualifer */ -#define CL_KERNEL_ARG_TYPE_NONE 0 -#define CL_KERNEL_ARG_TYPE_CONST (1 << 0) -#define CL_KERNEL_ARG_TYPE_RESTRICT (1 << 1) -#define CL_KERNEL_ARG_TYPE_VOLATILE (1 << 2) -#define CL_KERNEL_ARG_TYPE_PIPE (1 << 3) - -/* cl_kernel_work_group_info */ -#define CL_KERNEL_WORK_GROUP_SIZE 0x11B0 -#define CL_KERNEL_COMPILE_WORK_GROUP_SIZE 0x11B1 -#define CL_KERNEL_LOCAL_MEM_SIZE 0x11B2 -#define CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE 0x11B3 -#define CL_KERNEL_PRIVATE_MEM_SIZE 0x11B4 -#define CL_KERNEL_GLOBAL_WORK_SIZE 0x11B5 - -/* cl_kernel_sub_group_info */ -#define CL_KERNEL_MAX_SUB_GROUP_SIZE_FOR_NDRANGE 0x2033 -#define CL_KERNEL_SUB_GROUP_COUNT_FOR_NDRANGE 0x2034 -#define CL_KERNEL_LOCAL_SIZE_FOR_SUB_GROUP_COUNT 0x11B8 - -/* cl_kernel_exec_info */ -#define CL_KERNEL_EXEC_INFO_SVM_PTRS 0x11B6 -#define CL_KERNEL_EXEC_INFO_SVM_FINE_GRAIN_SYSTEM 0x11B7 - -/* cl_event_info */ -#define CL_EVENT_COMMAND_QUEUE 0x11D0 -#define CL_EVENT_COMMAND_TYPE 0x11D1 -#define CL_EVENT_REFERENCE_COUNT 0x11D2 -#define CL_EVENT_COMMAND_EXECUTION_STATUS 0x11D3 -#define CL_EVENT_CONTEXT 0x11D4 - -/* cl_command_type */ -#define CL_COMMAND_NDRANGE_KERNEL 0x11F0 -#define CL_COMMAND_TASK 0x11F1 -#define CL_COMMAND_NATIVE_KERNEL 0x11F2 -#define CL_COMMAND_READ_BUFFER 0x11F3 -#define CL_COMMAND_WRITE_BUFFER 0x11F4 -#define CL_COMMAND_COPY_BUFFER 0x11F5 -#define CL_COMMAND_READ_IMAGE 0x11F6 -#define CL_COMMAND_WRITE_IMAGE 0x11F7 -#define CL_COMMAND_COPY_IMAGE 0x11F8 -#define CL_COMMAND_COPY_IMAGE_TO_BUFFER 0x11F9 -#define CL_COMMAND_COPY_BUFFER_TO_IMAGE 0x11FA -#define CL_COMMAND_MAP_BUFFER 0x11FB -#define CL_COMMAND_MAP_IMAGE 0x11FC -#define CL_COMMAND_UNMAP_MEM_OBJECT 0x11FD -#define CL_COMMAND_MARKER 0x11FE -#define CL_COMMAND_ACQUIRE_GL_OBJECTS 0x11FF -#define CL_COMMAND_RELEASE_GL_OBJECTS 0x1200 -#define CL_COMMAND_READ_BUFFER_RECT 0x1201 -#define CL_COMMAND_WRITE_BUFFER_RECT 0x1202 -#define CL_COMMAND_COPY_BUFFER_RECT 0x1203 -#define CL_COMMAND_USER 0x1204 -#define CL_COMMAND_BARRIER 0x1205 -#define CL_COMMAND_MIGRATE_MEM_OBJECTS 0x1206 -#define CL_COMMAND_FILL_BUFFER 0x1207 -#define CL_COMMAND_FILL_IMAGE 0x1208 -#define CL_COMMAND_SVM_FREE 0x1209 -#define CL_COMMAND_SVM_MEMCPY 0x120A -#define CL_COMMAND_SVM_MEMFILL 0x120B -#define CL_COMMAND_SVM_MAP 0x120C -#define CL_COMMAND_SVM_UNMAP 0x120D - -/* command execution status */ -#define CL_COMPLETE 0x0 -#define CL_RUNNING 0x1 -#define CL_SUBMITTED 0x2 -#define CL_QUEUED 0x3 - -/* cl_buffer_create_type */ -#define CL_BUFFER_CREATE_TYPE_REGION 0x1220 - -/* cl_profiling_info */ -#define CL_PROFILING_COMMAND_QUEUED 0x1280 -#define CL_PROFILING_COMMAND_SUBMIT 0x1281 -#define CL_PROFILING_COMMAND_START 0x1282 -#define CL_PROFILING_COMMAND_END 0x1283 -#define CL_PROFILING_COMMAND_COMPLETE 0x1284 - -/********************************************************************************************************/ - -/* Platform API */ -extern CL_API_ENTRY cl_int CL_API_CALL -clGetPlatformIDs(cl_uint /* num_entries */, - cl_platform_id * /* platforms */, - cl_uint * /* num_platforms */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetPlatformInfo(cl_platform_id /* platform */, - cl_platform_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -/* Device APIs */ -extern CL_API_ENTRY cl_int CL_API_CALL -clGetDeviceIDs(cl_platform_id /* platform */, - cl_device_type /* device_type */, - cl_uint /* num_entries */, - cl_device_id * /* devices */, - cl_uint * /* num_devices */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetDeviceInfo(cl_device_id /* device */, - cl_device_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clCreateSubDevices(cl_device_id /* in_device */, - const cl_device_partition_property * /* properties */, - cl_uint /* num_devices */, - cl_device_id * /* out_devices */, - cl_uint * /* num_devices_ret */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainDevice(cl_device_id /* device */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseDevice(cl_device_id /* device */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_int CL_API_CALL -clSetDefaultDeviceCommandQueue(cl_context /* context */, - cl_device_id /* device */, - cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_2_1; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetDeviceAndHostTimer(cl_device_id /* device */, - cl_ulong* /* device_timestamp */, - cl_ulong* /* host_timestamp */) CL_API_SUFFIX__VERSION_2_1; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetHostTimer(cl_device_id /* device */, - cl_ulong * /* host_timestamp */) CL_API_SUFFIX__VERSION_2_1; - - -/* Context APIs */ -extern CL_API_ENTRY cl_context CL_API_CALL -clCreateContext(const cl_context_properties * /* properties */, - cl_uint /* num_devices */, - const cl_device_id * /* devices */, - void (CL_CALLBACK * /* pfn_notify */)(const char *, const void *, size_t, void *), - void * /* user_data */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_context CL_API_CALL -clCreateContextFromType(const cl_context_properties * /* properties */, - cl_device_type /* device_type */, - void (CL_CALLBACK * /* pfn_notify*/ )(const char *, const void *, size_t, void *), - void * /* user_data */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainContext(cl_context /* context */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseContext(cl_context /* context */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetContextInfo(cl_context /* context */, - cl_context_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -/* Command Queue APIs */ -extern CL_API_ENTRY cl_command_queue CL_API_CALL -clCreateCommandQueueWithProperties(cl_context /* context */, - cl_device_id /* device */, - const cl_queue_properties * /* properties */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_2_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainCommandQueue(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseCommandQueue(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetCommandQueueInfo(cl_command_queue /* command_queue */, - cl_command_queue_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -/* Memory Object APIs */ -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateBuffer(cl_context /* context */, - cl_mem_flags /* flags */, - size_t /* size */, - void * /* host_ptr */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateSubBuffer(cl_mem /* buffer */, - cl_mem_flags /* flags */, - cl_buffer_create_type /* buffer_create_type */, - const void * /* buffer_create_info */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_1; - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateImage(cl_context /* context */, - cl_mem_flags /* flags */, - const cl_image_format * /* image_format */, - const cl_image_desc * /* image_desc */, - void * /* host_ptr */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreatePipe(cl_context /* context */, - cl_mem_flags /* flags */, - cl_uint /* pipe_packet_size */, - cl_uint /* pipe_max_packets */, - const cl_pipe_properties * /* properties */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_2_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainMemObject(cl_mem /* memobj */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseMemObject(cl_mem /* memobj */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetSupportedImageFormats(cl_context /* context */, - cl_mem_flags /* flags */, - cl_mem_object_type /* image_type */, - cl_uint /* num_entries */, - cl_image_format * /* image_formats */, - cl_uint * /* num_image_formats */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetMemObjectInfo(cl_mem /* memobj */, - cl_mem_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetImageInfo(cl_mem /* image */, - cl_image_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetPipeInfo(cl_mem /* pipe */, - cl_pipe_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_2_0; - - -extern CL_API_ENTRY cl_int CL_API_CALL -clSetMemObjectDestructorCallback(cl_mem /* memobj */, - void (CL_CALLBACK * /*pfn_notify*/)( cl_mem /* memobj */, void* /*user_data*/), - void * /*user_data */ ) CL_API_SUFFIX__VERSION_1_1; - -/* SVM Allocation APIs */ -extern CL_API_ENTRY void * CL_API_CALL -clSVMAlloc(cl_context /* context */, - cl_svm_mem_flags /* flags */, - size_t /* size */, - cl_uint /* alignment */) CL_API_SUFFIX__VERSION_2_0; - -extern CL_API_ENTRY void CL_API_CALL -clSVMFree(cl_context /* context */, - void * /* svm_pointer */) CL_API_SUFFIX__VERSION_2_0; - -/* Sampler APIs */ -extern CL_API_ENTRY cl_sampler CL_API_CALL -clCreateSamplerWithProperties(cl_context /* context */, - const cl_sampler_properties * /* normalized_coords */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_2_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainSampler(cl_sampler /* sampler */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseSampler(cl_sampler /* sampler */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetSamplerInfo(cl_sampler /* sampler */, - cl_sampler_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -/* Program Object APIs */ -extern CL_API_ENTRY cl_program CL_API_CALL -clCreateProgramWithSource(cl_context /* context */, - cl_uint /* count */, - const char ** /* strings */, - const size_t * /* lengths */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_program CL_API_CALL -clCreateProgramWithBinary(cl_context /* context */, - cl_uint /* num_devices */, - const cl_device_id * /* device_list */, - const size_t * /* lengths */, - const unsigned char ** /* binaries */, - cl_int * /* binary_status */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_program CL_API_CALL -clCreateProgramWithBuiltInKernels(cl_context /* context */, - cl_uint /* num_devices */, - const cl_device_id * /* device_list */, - const char * /* kernel_names */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_program CL_API_CALL -clCreateProgramWithIL(cl_context /* context */, - const void* /* il */, - size_t /* length */, - cl_int* /* errcode_ret */) CL_API_SUFFIX__VERSION_2_1; - - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainProgram(cl_program /* program */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseProgram(cl_program /* program */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clBuildProgram(cl_program /* program */, - cl_uint /* num_devices */, - const cl_device_id * /* device_list */, - const char * /* options */, - void (CL_CALLBACK * /* pfn_notify */)(cl_program /* program */, void * /* user_data */), - void * /* user_data */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clCompileProgram(cl_program /* program */, - cl_uint /* num_devices */, - const cl_device_id * /* device_list */, - const char * /* options */, - cl_uint /* num_input_headers */, - const cl_program * /* input_headers */, - const char ** /* header_include_names */, - void (CL_CALLBACK * /* pfn_notify */)(cl_program /* program */, void * /* user_data */), - void * /* user_data */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_program CL_API_CALL -clLinkProgram(cl_context /* context */, - cl_uint /* num_devices */, - const cl_device_id * /* device_list */, - const char * /* options */, - cl_uint /* num_input_programs */, - const cl_program * /* input_programs */, - void (CL_CALLBACK * /* pfn_notify */)(cl_program /* program */, void * /* user_data */), - void * /* user_data */, - cl_int * /* errcode_ret */ ) CL_API_SUFFIX__VERSION_1_2; - - -extern CL_API_ENTRY cl_int CL_API_CALL -clUnloadPlatformCompiler(cl_platform_id /* platform */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetProgramInfo(cl_program /* program */, - cl_program_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetProgramBuildInfo(cl_program /* program */, - cl_device_id /* device */, - cl_program_build_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -/* Kernel Object APIs */ -extern CL_API_ENTRY cl_kernel CL_API_CALL -clCreateKernel(cl_program /* program */, - const char * /* kernel_name */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clCreateKernelsInProgram(cl_program /* program */, - cl_uint /* num_kernels */, - cl_kernel * /* kernels */, - cl_uint * /* num_kernels_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_kernel CL_API_CALL -clCloneKernel(cl_kernel /* source_kernel */, - cl_int* /* errcode_ret */) CL_API_SUFFIX__VERSION_2_1; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainKernel(cl_kernel /* kernel */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseKernel(cl_kernel /* kernel */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clSetKernelArg(cl_kernel /* kernel */, - cl_uint /* arg_index */, - size_t /* arg_size */, - const void * /* arg_value */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clSetKernelArgSVMPointer(cl_kernel /* kernel */, - cl_uint /* arg_index */, - const void * /* arg_value */) CL_API_SUFFIX__VERSION_2_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clSetKernelExecInfo(cl_kernel /* kernel */, - cl_kernel_exec_info /* param_name */, - size_t /* param_value_size */, - const void * /* param_value */) CL_API_SUFFIX__VERSION_2_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetKernelInfo(cl_kernel /* kernel */, - cl_kernel_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetKernelArgInfo(cl_kernel /* kernel */, - cl_uint /* arg_indx */, - cl_kernel_arg_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetKernelWorkGroupInfo(cl_kernel /* kernel */, - cl_device_id /* device */, - cl_kernel_work_group_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetKernelSubGroupInfo(cl_kernel /* kernel */, - cl_device_id /* device */, - cl_kernel_sub_group_info /* param_name */, - size_t /* input_value_size */, - const void* /*input_value */, - size_t /* param_value_size */, - void* /* param_value */, - size_t* /* param_value_size_ret */ ) CL_API_SUFFIX__VERSION_2_1; - - -/* Event Object APIs */ -extern CL_API_ENTRY cl_int CL_API_CALL -clWaitForEvents(cl_uint /* num_events */, - const cl_event * /* event_list */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetEventInfo(cl_event /* event */, - cl_event_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_event CL_API_CALL -clCreateUserEvent(cl_context /* context */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_1; - -extern CL_API_ENTRY cl_int CL_API_CALL -clRetainEvent(cl_event /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clReleaseEvent(cl_event /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clSetUserEventStatus(cl_event /* event */, - cl_int /* execution_status */) CL_API_SUFFIX__VERSION_1_1; - -extern CL_API_ENTRY cl_int CL_API_CALL -clSetEventCallback( cl_event /* event */, - cl_int /* command_exec_callback_type */, - void (CL_CALLBACK * /* pfn_notify */)(cl_event, cl_int, void *), - void * /* user_data */) CL_API_SUFFIX__VERSION_1_1; - -/* Profiling APIs */ -extern CL_API_ENTRY cl_int CL_API_CALL -clGetEventProfilingInfo(cl_event /* event */, - cl_profiling_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -/* Flush and Finish APIs */ -extern CL_API_ENTRY cl_int CL_API_CALL -clFlush(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clFinish(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; - -/* Enqueued Commands APIs */ -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueReadBuffer(cl_command_queue /* command_queue */, - cl_mem /* buffer */, - cl_bool /* blocking_read */, - size_t /* offset */, - size_t /* size */, - void * /* ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueReadBufferRect(cl_command_queue /* command_queue */, - cl_mem /* buffer */, - cl_bool /* blocking_read */, - const size_t * /* buffer_offset */, - const size_t * /* host_offset */, - const size_t * /* region */, - size_t /* buffer_row_pitch */, - size_t /* buffer_slice_pitch */, - size_t /* host_row_pitch */, - size_t /* host_slice_pitch */, - void * /* ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_1; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueWriteBuffer(cl_command_queue /* command_queue */, - cl_mem /* buffer */, - cl_bool /* blocking_write */, - size_t /* offset */, - size_t /* size */, - const void * /* ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueWriteBufferRect(cl_command_queue /* command_queue */, - cl_mem /* buffer */, - cl_bool /* blocking_write */, - const size_t * /* buffer_offset */, - const size_t * /* host_offset */, - const size_t * /* region */, - size_t /* buffer_row_pitch */, - size_t /* buffer_slice_pitch */, - size_t /* host_row_pitch */, - size_t /* host_slice_pitch */, - const void * /* ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_1; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueFillBuffer(cl_command_queue /* command_queue */, - cl_mem /* buffer */, - const void * /* pattern */, - size_t /* pattern_size */, - size_t /* offset */, - size_t /* size */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueCopyBuffer(cl_command_queue /* command_queue */, - cl_mem /* src_buffer */, - cl_mem /* dst_buffer */, - size_t /* src_offset */, - size_t /* dst_offset */, - size_t /* size */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueCopyBufferRect(cl_command_queue /* command_queue */, - cl_mem /* src_buffer */, - cl_mem /* dst_buffer */, - const size_t * /* src_origin */, - const size_t * /* dst_origin */, - const size_t * /* region */, - size_t /* src_row_pitch */, - size_t /* src_slice_pitch */, - size_t /* dst_row_pitch */, - size_t /* dst_slice_pitch */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_1; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueReadImage(cl_command_queue /* command_queue */, - cl_mem /* image */, - cl_bool /* blocking_read */, - const size_t * /* origin[3] */, - const size_t * /* region[3] */, - size_t /* row_pitch */, - size_t /* slice_pitch */, - void * /* ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueWriteImage(cl_command_queue /* command_queue */, - cl_mem /* image */, - cl_bool /* blocking_write */, - const size_t * /* origin[3] */, - const size_t * /* region[3] */, - size_t /* input_row_pitch */, - size_t /* input_slice_pitch */, - const void * /* ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueFillImage(cl_command_queue /* command_queue */, - cl_mem /* image */, - const void * /* fill_color */, - const size_t * /* origin[3] */, - const size_t * /* region[3] */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueCopyImage(cl_command_queue /* command_queue */, - cl_mem /* src_image */, - cl_mem /* dst_image */, - const size_t * /* src_origin[3] */, - const size_t * /* dst_origin[3] */, - const size_t * /* region[3] */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueCopyImageToBuffer(cl_command_queue /* command_queue */, - cl_mem /* src_image */, - cl_mem /* dst_buffer */, - const size_t * /* src_origin[3] */, - const size_t * /* region[3] */, - size_t /* dst_offset */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueCopyBufferToImage(cl_command_queue /* command_queue */, - cl_mem /* src_buffer */, - cl_mem /* dst_image */, - size_t /* src_offset */, - const size_t * /* dst_origin[3] */, - const size_t * /* region[3] */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY void * CL_API_CALL -clEnqueueMapBuffer(cl_command_queue /* command_queue */, - cl_mem /* buffer */, - cl_bool /* blocking_map */, - cl_map_flags /* map_flags */, - size_t /* offset */, - size_t /* size */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY void * CL_API_CALL -clEnqueueMapImage(cl_command_queue /* command_queue */, - cl_mem /* image */, - cl_bool /* blocking_map */, - cl_map_flags /* map_flags */, - const size_t * /* origin[3] */, - const size_t * /* region[3] */, - size_t * /* image_row_pitch */, - size_t * /* image_slice_pitch */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueUnmapMemObject(cl_command_queue /* command_queue */, - cl_mem /* memobj */, - void * /* mapped_ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueMigrateMemObjects(cl_command_queue /* command_queue */, - cl_uint /* num_mem_objects */, - const cl_mem * /* mem_objects */, - cl_mem_migration_flags /* flags */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueNDRangeKernel(cl_command_queue /* command_queue */, - cl_kernel /* kernel */, - cl_uint /* work_dim */, - const size_t * /* global_work_offset */, - const size_t * /* global_work_size */, - const size_t * /* local_work_size */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueNativeKernel(cl_command_queue /* command_queue */, - void (CL_CALLBACK * /*user_func*/)(void *), - void * /* args */, - size_t /* cb_args */, - cl_uint /* num_mem_objects */, - const cl_mem * /* mem_list */, - const void ** /* args_mem_loc */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueMarkerWithWaitList(cl_command_queue /* command_queue */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueBarrierWithWaitList(cl_command_queue /* command_queue */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueSVMFree(cl_command_queue /* command_queue */, - cl_uint /* num_svm_pointers */, - void *[] /* svm_pointers[] */, - void (CL_CALLBACK * /*pfn_free_func*/)(cl_command_queue /* queue */, - cl_uint /* num_svm_pointers */, - void *[] /* svm_pointers[] */, - void * /* user_data */), - void * /* user_data */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_2_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueSVMMemcpy(cl_command_queue /* command_queue */, - cl_bool /* blocking_copy */, - void * /* dst_ptr */, - const void * /* src_ptr */, - size_t /* size */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_2_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueSVMMemFill(cl_command_queue /* command_queue */, - void * /* svm_ptr */, - const void * /* pattern */, - size_t /* pattern_size */, - size_t /* size */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_2_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueSVMMap(cl_command_queue /* command_queue */, - cl_bool /* blocking_map */, - cl_map_flags /* flags */, - void * /* svm_ptr */, - size_t /* size */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_2_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueSVMUnmap(cl_command_queue /* command_queue */, - void * /* svm_ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_2_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueSVMMigrateMem(cl_command_queue /* command_queue */, - cl_uint /* num_svm_pointers */, - const void ** /* svm_pointers */, - const size_t * /* sizes */, - cl_mem_migration_flags /* flags */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_2_1; - - -/* Extension function access - * - * Returns the extension function address for the given function name, - * or NULL if a valid function can not be found. The client must - * check to make sure the address is not NULL, before using or - * calling the returned function address. - */ -extern CL_API_ENTRY void * CL_API_CALL -clGetExtensionFunctionAddressForPlatform(cl_platform_id /* platform */, - const char * /* func_name */) CL_API_SUFFIX__VERSION_1_2; - - -/* Deprecated OpenCL 1.1 APIs */ -extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_1_1_DEPRECATED cl_mem CL_API_CALL -clCreateImage2D(cl_context /* context */, - cl_mem_flags /* flags */, - const cl_image_format * /* image_format */, - size_t /* image_width */, - size_t /* image_height */, - size_t /* image_row_pitch */, - void * /* host_ptr */, - cl_int * /* errcode_ret */) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; - -extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_1_1_DEPRECATED cl_mem CL_API_CALL -clCreateImage3D(cl_context /* context */, - cl_mem_flags /* flags */, - const cl_image_format * /* image_format */, - size_t /* image_width */, - size_t /* image_height */, - size_t /* image_depth */, - size_t /* image_row_pitch */, - size_t /* image_slice_pitch */, - void * /* host_ptr */, - cl_int * /* errcode_ret */) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; - -extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_1_1_DEPRECATED cl_int CL_API_CALL -clEnqueueMarker(cl_command_queue /* command_queue */, - cl_event * /* event */) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; - -extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_1_1_DEPRECATED cl_int CL_API_CALL -clEnqueueWaitForEvents(cl_command_queue /* command_queue */, - cl_uint /* num_events */, - const cl_event * /* event_list */) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; - -extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_1_1_DEPRECATED cl_int CL_API_CALL -clEnqueueBarrier(cl_command_queue /* command_queue */) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; - -extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_1_1_DEPRECATED cl_int CL_API_CALL -clUnloadCompiler(void) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; - -extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_1_1_DEPRECATED void * CL_API_CALL -clGetExtensionFunctionAddress(const char * /* func_name */) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; - -/* Deprecated OpenCL 2.0 APIs */ -extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_1_2_DEPRECATED cl_command_queue CL_API_CALL -clCreateCommandQueue(cl_context /* context */, - cl_device_id /* device */, - cl_command_queue_properties /* properties */, - cl_int * /* errcode_ret */) CL_EXT_SUFFIX__VERSION_1_2_DEPRECATED; - - -extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_1_2_DEPRECATED cl_sampler CL_API_CALL -clCreateSampler(cl_context /* context */, - cl_bool /* normalized_coords */, - cl_addressing_mode /* addressing_mode */, - cl_filter_mode /* filter_mode */, - cl_int * /* errcode_ret */) CL_EXT_SUFFIX__VERSION_1_2_DEPRECATED; - -extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_1_2_DEPRECATED cl_int CL_API_CALL -clEnqueueTask(cl_command_queue /* command_queue */, - cl_kernel /* kernel */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_EXT_SUFFIX__VERSION_1_2_DEPRECATED; - -#ifdef __cplusplus -} -#endif - -#endif /* __OPENCL_CL_H */ - diff --git a/third_party/opencl/include/CL/cl_d3d10.h b/third_party/opencl/include/CL/cl_d3d10.h deleted file mode 100644 index d5960a43f7..0000000000 --- a/third_party/opencl/include/CL/cl_d3d10.h +++ /dev/null @@ -1,131 +0,0 @@ -/********************************************************************************** - * Copyright (c) 2008-2015 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are 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 Materials. - * - * MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS - * KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS - * SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT - * https://www.khronos.org/registry/ - * - * THE MATERIALS ARE 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 - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - **********************************************************************************/ - -/* $Revision: 11708 $ on $Date: 2010-06-13 23:36:24 -0700 (Sun, 13 Jun 2010) $ */ - -#ifndef __OPENCL_CL_D3D10_H -#define __OPENCL_CL_D3D10_H - -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/****************************************************************************** - * cl_khr_d3d10_sharing */ -#define cl_khr_d3d10_sharing 1 - -typedef cl_uint cl_d3d10_device_source_khr; -typedef cl_uint cl_d3d10_device_set_khr; - -/******************************************************************************/ - -/* Error Codes */ -#define CL_INVALID_D3D10_DEVICE_KHR -1002 -#define CL_INVALID_D3D10_RESOURCE_KHR -1003 -#define CL_D3D10_RESOURCE_ALREADY_ACQUIRED_KHR -1004 -#define CL_D3D10_RESOURCE_NOT_ACQUIRED_KHR -1005 - -/* cl_d3d10_device_source_nv */ -#define CL_D3D10_DEVICE_KHR 0x4010 -#define CL_D3D10_DXGI_ADAPTER_KHR 0x4011 - -/* cl_d3d10_device_set_nv */ -#define CL_PREFERRED_DEVICES_FOR_D3D10_KHR 0x4012 -#define CL_ALL_DEVICES_FOR_D3D10_KHR 0x4013 - -/* cl_context_info */ -#define CL_CONTEXT_D3D10_DEVICE_KHR 0x4014 -#define CL_CONTEXT_D3D10_PREFER_SHARED_RESOURCES_KHR 0x402C - -/* cl_mem_info */ -#define CL_MEM_D3D10_RESOURCE_KHR 0x4015 - -/* cl_image_info */ -#define CL_IMAGE_D3D10_SUBRESOURCE_KHR 0x4016 - -/* cl_command_type */ -#define CL_COMMAND_ACQUIRE_D3D10_OBJECTS_KHR 0x4017 -#define CL_COMMAND_RELEASE_D3D10_OBJECTS_KHR 0x4018 - -/******************************************************************************/ - -typedef CL_API_ENTRY cl_int (CL_API_CALL *clGetDeviceIDsFromD3D10KHR_fn)( - cl_platform_id platform, - cl_d3d10_device_source_khr d3d_device_source, - void * d3d_object, - cl_d3d10_device_set_khr d3d_device_set, - cl_uint num_entries, - cl_device_id * devices, - cl_uint * num_devices) CL_API_SUFFIX__VERSION_1_0; - -typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromD3D10BufferKHR_fn)( - cl_context context, - cl_mem_flags flags, - ID3D10Buffer * resource, - cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0; - -typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromD3D10Texture2DKHR_fn)( - cl_context context, - cl_mem_flags flags, - ID3D10Texture2D * resource, - UINT subresource, - cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0; - -typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromD3D10Texture3DKHR_fn)( - cl_context context, - cl_mem_flags flags, - ID3D10Texture3D * resource, - UINT subresource, - cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0; - -typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueAcquireD3D10ObjectsKHR_fn)( - cl_command_queue command_queue, - cl_uint num_objects, - const cl_mem * mem_objects, - cl_uint num_events_in_wait_list, - const cl_event * event_wait_list, - cl_event * event) CL_API_SUFFIX__VERSION_1_0; - -typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueReleaseD3D10ObjectsKHR_fn)( - cl_command_queue command_queue, - cl_uint num_objects, - const cl_mem * mem_objects, - cl_uint num_events_in_wait_list, - const cl_event * event_wait_list, - cl_event * event) CL_API_SUFFIX__VERSION_1_0; - -#ifdef __cplusplus -} -#endif - -#endif /* __OPENCL_CL_D3D10_H */ - diff --git a/third_party/opencl/include/CL/cl_d3d11.h b/third_party/opencl/include/CL/cl_d3d11.h deleted file mode 100644 index 39f9072398..0000000000 --- a/third_party/opencl/include/CL/cl_d3d11.h +++ /dev/null @@ -1,131 +0,0 @@ -/********************************************************************************** - * Copyright (c) 2008-2015 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are 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 Materials. - * - * MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS - * KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS - * SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT - * https://www.khronos.org/registry/ - * - * THE MATERIALS ARE 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 - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - **********************************************************************************/ - -/* $Revision: 11708 $ on $Date: 2010-06-13 23:36:24 -0700 (Sun, 13 Jun 2010) $ */ - -#ifndef __OPENCL_CL_D3D11_H -#define __OPENCL_CL_D3D11_H - -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/****************************************************************************** - * cl_khr_d3d11_sharing */ -#define cl_khr_d3d11_sharing 1 - -typedef cl_uint cl_d3d11_device_source_khr; -typedef cl_uint cl_d3d11_device_set_khr; - -/******************************************************************************/ - -/* Error Codes */ -#define CL_INVALID_D3D11_DEVICE_KHR -1006 -#define CL_INVALID_D3D11_RESOURCE_KHR -1007 -#define CL_D3D11_RESOURCE_ALREADY_ACQUIRED_KHR -1008 -#define CL_D3D11_RESOURCE_NOT_ACQUIRED_KHR -1009 - -/* cl_d3d11_device_source */ -#define CL_D3D11_DEVICE_KHR 0x4019 -#define CL_D3D11_DXGI_ADAPTER_KHR 0x401A - -/* cl_d3d11_device_set */ -#define CL_PREFERRED_DEVICES_FOR_D3D11_KHR 0x401B -#define CL_ALL_DEVICES_FOR_D3D11_KHR 0x401C - -/* cl_context_info */ -#define CL_CONTEXT_D3D11_DEVICE_KHR 0x401D -#define CL_CONTEXT_D3D11_PREFER_SHARED_RESOURCES_KHR 0x402D - -/* cl_mem_info */ -#define CL_MEM_D3D11_RESOURCE_KHR 0x401E - -/* cl_image_info */ -#define CL_IMAGE_D3D11_SUBRESOURCE_KHR 0x401F - -/* cl_command_type */ -#define CL_COMMAND_ACQUIRE_D3D11_OBJECTS_KHR 0x4020 -#define CL_COMMAND_RELEASE_D3D11_OBJECTS_KHR 0x4021 - -/******************************************************************************/ - -typedef CL_API_ENTRY cl_int (CL_API_CALL *clGetDeviceIDsFromD3D11KHR_fn)( - cl_platform_id platform, - cl_d3d11_device_source_khr d3d_device_source, - void * d3d_object, - cl_d3d11_device_set_khr d3d_device_set, - cl_uint num_entries, - cl_device_id * devices, - cl_uint * num_devices) CL_API_SUFFIX__VERSION_1_2; - -typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromD3D11BufferKHR_fn)( - cl_context context, - cl_mem_flags flags, - ID3D11Buffer * resource, - cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_2; - -typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromD3D11Texture2DKHR_fn)( - cl_context context, - cl_mem_flags flags, - ID3D11Texture2D * resource, - UINT subresource, - cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_2; - -typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromD3D11Texture3DKHR_fn)( - cl_context context, - cl_mem_flags flags, - ID3D11Texture3D * resource, - UINT subresource, - cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_2; - -typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueAcquireD3D11ObjectsKHR_fn)( - cl_command_queue command_queue, - cl_uint num_objects, - const cl_mem * mem_objects, - cl_uint num_events_in_wait_list, - const cl_event * event_wait_list, - cl_event * event) CL_API_SUFFIX__VERSION_1_2; - -typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueReleaseD3D11ObjectsKHR_fn)( - cl_command_queue command_queue, - cl_uint num_objects, - const cl_mem * mem_objects, - cl_uint num_events_in_wait_list, - const cl_event * event_wait_list, - cl_event * event) CL_API_SUFFIX__VERSION_1_2; - -#ifdef __cplusplus -} -#endif - -#endif /* __OPENCL_CL_D3D11_H */ - diff --git a/third_party/opencl/include/CL/cl_dx9_media_sharing.h b/third_party/opencl/include/CL/cl_dx9_media_sharing.h deleted file mode 100644 index 2729e8b9e8..0000000000 --- a/third_party/opencl/include/CL/cl_dx9_media_sharing.h +++ /dev/null @@ -1,132 +0,0 @@ -/********************************************************************************** - * Copyright (c) 2008-2015 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are 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 Materials. - * - * MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS - * KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS - * SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT - * https://www.khronos.org/registry/ - * - * THE MATERIALS ARE 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 - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - **********************************************************************************/ - -/* $Revision: 11708 $ on $Date: 2010-06-13 23:36:24 -0700 (Sun, 13 Jun 2010) $ */ - -#ifndef __OPENCL_CL_DX9_MEDIA_SHARING_H -#define __OPENCL_CL_DX9_MEDIA_SHARING_H - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/******************************************************************************/ -/* cl_khr_dx9_media_sharing */ -#define cl_khr_dx9_media_sharing 1 - -typedef cl_uint cl_dx9_media_adapter_type_khr; -typedef cl_uint cl_dx9_media_adapter_set_khr; - -#if defined(_WIN32) -#include -typedef struct _cl_dx9_surface_info_khr -{ - IDirect3DSurface9 *resource; - HANDLE shared_handle; -} cl_dx9_surface_info_khr; -#endif - - -/******************************************************************************/ - -/* Error Codes */ -#define CL_INVALID_DX9_MEDIA_ADAPTER_KHR -1010 -#define CL_INVALID_DX9_MEDIA_SURFACE_KHR -1011 -#define CL_DX9_MEDIA_SURFACE_ALREADY_ACQUIRED_KHR -1012 -#define CL_DX9_MEDIA_SURFACE_NOT_ACQUIRED_KHR -1013 - -/* cl_media_adapter_type_khr */ -#define CL_ADAPTER_D3D9_KHR 0x2020 -#define CL_ADAPTER_D3D9EX_KHR 0x2021 -#define CL_ADAPTER_DXVA_KHR 0x2022 - -/* cl_media_adapter_set_khr */ -#define CL_PREFERRED_DEVICES_FOR_DX9_MEDIA_ADAPTER_KHR 0x2023 -#define CL_ALL_DEVICES_FOR_DX9_MEDIA_ADAPTER_KHR 0x2024 - -/* cl_context_info */ -#define CL_CONTEXT_ADAPTER_D3D9_KHR 0x2025 -#define CL_CONTEXT_ADAPTER_D3D9EX_KHR 0x2026 -#define CL_CONTEXT_ADAPTER_DXVA_KHR 0x2027 - -/* cl_mem_info */ -#define CL_MEM_DX9_MEDIA_ADAPTER_TYPE_KHR 0x2028 -#define CL_MEM_DX9_MEDIA_SURFACE_INFO_KHR 0x2029 - -/* cl_image_info */ -#define CL_IMAGE_DX9_MEDIA_PLANE_KHR 0x202A - -/* cl_command_type */ -#define CL_COMMAND_ACQUIRE_DX9_MEDIA_SURFACES_KHR 0x202B -#define CL_COMMAND_RELEASE_DX9_MEDIA_SURFACES_KHR 0x202C - -/******************************************************************************/ - -typedef CL_API_ENTRY cl_int (CL_API_CALL *clGetDeviceIDsFromDX9MediaAdapterKHR_fn)( - cl_platform_id platform, - cl_uint num_media_adapters, - cl_dx9_media_adapter_type_khr * media_adapter_type, - void * media_adapters, - cl_dx9_media_adapter_set_khr media_adapter_set, - cl_uint num_entries, - cl_device_id * devices, - cl_uint * num_devices) CL_API_SUFFIX__VERSION_1_2; - -typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromDX9MediaSurfaceKHR_fn)( - cl_context context, - cl_mem_flags flags, - cl_dx9_media_adapter_type_khr adapter_type, - void * surface_info, - cl_uint plane, - cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_2; - -typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueAcquireDX9MediaSurfacesKHR_fn)( - cl_command_queue command_queue, - cl_uint num_objects, - const cl_mem * mem_objects, - cl_uint num_events_in_wait_list, - const cl_event * event_wait_list, - cl_event * event) CL_API_SUFFIX__VERSION_1_2; - -typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueReleaseDX9MediaSurfacesKHR_fn)( - cl_command_queue command_queue, - cl_uint num_objects, - const cl_mem * mem_objects, - cl_uint num_events_in_wait_list, - const cl_event * event_wait_list, - cl_event * event) CL_API_SUFFIX__VERSION_1_2; - -#ifdef __cplusplus -} -#endif - -#endif /* __OPENCL_CL_DX9_MEDIA_SHARING_H */ - diff --git a/third_party/opencl/include/CL/cl_egl.h b/third_party/opencl/include/CL/cl_egl.h deleted file mode 100644 index a765bd5266..0000000000 --- a/third_party/opencl/include/CL/cl_egl.h +++ /dev/null @@ -1,136 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008-2015 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are 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 Materials. - * - * MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS - * KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS - * SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT - * https://www.khronos.org/registry/ - * - * THE MATERIALS ARE 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 - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - ******************************************************************************/ - -#ifndef __OPENCL_CL_EGL_H -#define __OPENCL_CL_EGL_H - -#ifdef __APPLE__ - -#else -#include -#endif - -#ifdef __cplusplus -extern "C" { -#endif - - -/* Command type for events created with clEnqueueAcquireEGLObjectsKHR */ -#define CL_COMMAND_EGL_FENCE_SYNC_OBJECT_KHR 0x202F -#define CL_COMMAND_ACQUIRE_EGL_OBJECTS_KHR 0x202D -#define CL_COMMAND_RELEASE_EGL_OBJECTS_KHR 0x202E - -/* Error type for clCreateFromEGLImageKHR */ -#define CL_INVALID_EGL_OBJECT_KHR -1093 -#define CL_EGL_RESOURCE_NOT_ACQUIRED_KHR -1092 - -/* CLeglImageKHR is an opaque handle to an EGLImage */ -typedef void* CLeglImageKHR; - -/* CLeglDisplayKHR is an opaque handle to an EGLDisplay */ -typedef void* CLeglDisplayKHR; - -/* CLeglSyncKHR is an opaque handle to an EGLSync object */ -typedef void* CLeglSyncKHR; - -/* properties passed to clCreateFromEGLImageKHR */ -typedef intptr_t cl_egl_image_properties_khr; - - -#define cl_khr_egl_image 1 - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateFromEGLImageKHR(cl_context /* context */, - CLeglDisplayKHR /* egldisplay */, - CLeglImageKHR /* eglimage */, - cl_mem_flags /* flags */, - const cl_egl_image_properties_khr * /* properties */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromEGLImageKHR_fn)( - cl_context context, - CLeglDisplayKHR egldisplay, - CLeglImageKHR eglimage, - cl_mem_flags flags, - const cl_egl_image_properties_khr * properties, - cl_int * errcode_ret); - - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueAcquireEGLObjectsKHR(cl_command_queue /* command_queue */, - cl_uint /* num_objects */, - const cl_mem * /* mem_objects */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueAcquireEGLObjectsKHR_fn)( - cl_command_queue command_queue, - cl_uint num_objects, - const cl_mem * mem_objects, - cl_uint num_events_in_wait_list, - const cl_event * event_wait_list, - cl_event * event); - - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueReleaseEGLObjectsKHR(cl_command_queue /* command_queue */, - cl_uint /* num_objects */, - const cl_mem * /* mem_objects */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueReleaseEGLObjectsKHR_fn)( - cl_command_queue command_queue, - cl_uint num_objects, - const cl_mem * mem_objects, - cl_uint num_events_in_wait_list, - const cl_event * event_wait_list, - cl_event * event); - - -#define cl_khr_egl_event 1 - -extern CL_API_ENTRY cl_event CL_API_CALL -clCreateEventFromEGLSyncKHR(cl_context /* context */, - CLeglSyncKHR /* sync */, - CLeglDisplayKHR /* display */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -typedef CL_API_ENTRY cl_event (CL_API_CALL *clCreateEventFromEGLSyncKHR_fn)( - cl_context context, - CLeglSyncKHR sync, - CLeglDisplayKHR display, - cl_int * errcode_ret); - -#ifdef __cplusplus -} -#endif - -#endif /* __OPENCL_CL_EGL_H */ diff --git a/third_party/opencl/include/CL/cl_ext.h b/third_party/opencl/include/CL/cl_ext.h deleted file mode 100644 index 7941583895..0000000000 --- a/third_party/opencl/include/CL/cl_ext.h +++ /dev/null @@ -1,391 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008-2015 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are 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 Materials. - * - * MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS - * KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS - * SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT - * https://www.khronos.org/registry/ - * - * THE MATERIALS ARE 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 - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - ******************************************************************************/ - -/* $Revision: 11928 $ on $Date: 2010-07-13 09:04:56 -0700 (Tue, 13 Jul 2010) $ */ - -/* cl_ext.h contains OpenCL extensions which don't have external */ -/* (OpenGL, D3D) dependencies. */ - -#ifndef __CL_EXT_H -#define __CL_EXT_H - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef __APPLE__ - #include - #include -#else - #include -#endif - -/* cl_khr_fp16 extension - no extension #define since it has no functions */ -#define CL_DEVICE_HALF_FP_CONFIG 0x1033 - -/* Memory object destruction - * - * Apple extension for use to manage externally allocated buffers used with cl_mem objects with CL_MEM_USE_HOST_PTR - * - * Registers a user callback function that will be called when the memory object is deleted and its resources - * freed. Each call to clSetMemObjectCallbackFn registers the specified user callback function on a callback - * stack associated with memobj. The registered user callback functions are called in the reverse order in - * which they were registered. The user callback functions are called and then the memory object is deleted - * and its resources freed. This provides a mechanism for the application (and libraries) using memobj to be - * notified when the memory referenced by host_ptr, specified when the memory object is created and used as - * the storage bits for the memory object, can be reused or freed. - * - * The application may not call CL api's with the cl_mem object passed to the pfn_notify. - * - * Please check for the "cl_APPLE_SetMemObjectDestructor" extension using clGetDeviceInfo(CL_DEVICE_EXTENSIONS) - * before using. - */ -#define cl_APPLE_SetMemObjectDestructor 1 -cl_int CL_API_ENTRY clSetMemObjectDestructorAPPLE( cl_mem /* memobj */, - void (* /*pfn_notify*/)( cl_mem /* memobj */, void* /*user_data*/), - void * /*user_data */ ) CL_EXT_SUFFIX__VERSION_1_0; - - -/* Context Logging Functions - * - * The next three convenience functions are intended to be used as the pfn_notify parameter to clCreateContext(). - * Please check for the "cl_APPLE_ContextLoggingFunctions" extension using clGetDeviceInfo(CL_DEVICE_EXTENSIONS) - * before using. - * - * clLogMessagesToSystemLog fowards on all log messages to the Apple System Logger - */ -#define cl_APPLE_ContextLoggingFunctions 1 -extern void CL_API_ENTRY clLogMessagesToSystemLogAPPLE( const char * /* errstr */, - const void * /* private_info */, - size_t /* cb */, - void * /* user_data */ ) CL_EXT_SUFFIX__VERSION_1_0; - -/* clLogMessagesToStdout sends all log messages to the file descriptor stdout */ -extern void CL_API_ENTRY clLogMessagesToStdoutAPPLE( const char * /* errstr */, - const void * /* private_info */, - size_t /* cb */, - void * /* user_data */ ) CL_EXT_SUFFIX__VERSION_1_0; - -/* clLogMessagesToStderr sends all log messages to the file descriptor stderr */ -extern void CL_API_ENTRY clLogMessagesToStderrAPPLE( const char * /* errstr */, - const void * /* private_info */, - size_t /* cb */, - void * /* user_data */ ) CL_EXT_SUFFIX__VERSION_1_0; - - -/************************ -* cl_khr_icd extension * -************************/ -#define cl_khr_icd 1 - -/* cl_platform_info */ -#define CL_PLATFORM_ICD_SUFFIX_KHR 0x0920 - -/* Additional Error Codes */ -#define CL_PLATFORM_NOT_FOUND_KHR -1001 - -extern CL_API_ENTRY cl_int CL_API_CALL -clIcdGetPlatformIDsKHR(cl_uint /* num_entries */, - cl_platform_id * /* platforms */, - cl_uint * /* num_platforms */); - -typedef CL_API_ENTRY cl_int (CL_API_CALL *clIcdGetPlatformIDsKHR_fn)( - cl_uint /* num_entries */, - cl_platform_id * /* platforms */, - cl_uint * /* num_platforms */); - - -/* Extension: cl_khr_image2D_buffer - * - * This extension allows a 2D image to be created from a cl_mem buffer without a copy. - * The type associated with a 2D image created from a buffer in an OpenCL program is image2d_t. - * Both the sampler and sampler-less read_image built-in functions are supported for 2D images - * and 2D images created from a buffer. Similarly, the write_image built-ins are also supported - * for 2D images created from a buffer. - * - * When the 2D image from buffer is created, the client must specify the width, - * height, image format (i.e. channel order and channel data type) and optionally the row pitch - * - * The pitch specified must be a multiple of CL_DEVICE_IMAGE_PITCH_ALIGNMENT pixels. - * The base address of the buffer must be aligned to CL_DEVICE_IMAGE_BASE_ADDRESS_ALIGNMENT pixels. - */ - -/************************************* - * cl_khr_initalize_memory extension * - *************************************/ - -#define CL_CONTEXT_MEMORY_INITIALIZE_KHR 0x2030 - - -/************************************** - * cl_khr_terminate_context extension * - **************************************/ - -#define CL_DEVICE_TERMINATE_CAPABILITY_KHR 0x2031 -#define CL_CONTEXT_TERMINATE_KHR 0x2032 - -#define cl_khr_terminate_context 1 -extern CL_API_ENTRY cl_int CL_API_CALL clTerminateContextKHR(cl_context /* context */) CL_EXT_SUFFIX__VERSION_1_2; - -typedef CL_API_ENTRY cl_int (CL_API_CALL *clTerminateContextKHR_fn)(cl_context /* context */) CL_EXT_SUFFIX__VERSION_1_2; - - -/* - * Extension: cl_khr_spir - * - * This extension adds support to create an OpenCL program object from a - * Standard Portable Intermediate Representation (SPIR) instance - */ - -#define CL_DEVICE_SPIR_VERSIONS 0x40E0 -#define CL_PROGRAM_BINARY_TYPE_INTERMEDIATE 0x40E1 - - -/****************************************** -* cl_nv_device_attribute_query extension * -******************************************/ -/* cl_nv_device_attribute_query extension - no extension #define since it has no functions */ -#define CL_DEVICE_COMPUTE_CAPABILITY_MAJOR_NV 0x4000 -#define CL_DEVICE_COMPUTE_CAPABILITY_MINOR_NV 0x4001 -#define CL_DEVICE_REGISTERS_PER_BLOCK_NV 0x4002 -#define CL_DEVICE_WARP_SIZE_NV 0x4003 -#define CL_DEVICE_GPU_OVERLAP_NV 0x4004 -#define CL_DEVICE_KERNEL_EXEC_TIMEOUT_NV 0x4005 -#define CL_DEVICE_INTEGRATED_MEMORY_NV 0x4006 - -/********************************* -* cl_amd_device_attribute_query * -*********************************/ -#define CL_DEVICE_PROFILING_TIMER_OFFSET_AMD 0x4036 - -/********************************* -* cl_arm_printf extension -*********************************/ -#define CL_PRINTF_CALLBACK_ARM 0x40B0 -#define CL_PRINTF_BUFFERSIZE_ARM 0x40B1 - -#ifdef CL_VERSION_1_1 - /*********************************** - * cl_ext_device_fission extension * - ***********************************/ - #define cl_ext_device_fission 1 - - extern CL_API_ENTRY cl_int CL_API_CALL - clReleaseDeviceEXT( cl_device_id /*device*/ ) CL_EXT_SUFFIX__VERSION_1_1; - - typedef CL_API_ENTRY cl_int - (CL_API_CALL *clReleaseDeviceEXT_fn)( cl_device_id /*device*/ ) CL_EXT_SUFFIX__VERSION_1_1; - - extern CL_API_ENTRY cl_int CL_API_CALL - clRetainDeviceEXT( cl_device_id /*device*/ ) CL_EXT_SUFFIX__VERSION_1_1; - - typedef CL_API_ENTRY cl_int - (CL_API_CALL *clRetainDeviceEXT_fn)( cl_device_id /*device*/ ) CL_EXT_SUFFIX__VERSION_1_1; - - typedef cl_ulong cl_device_partition_property_ext; - extern CL_API_ENTRY cl_int CL_API_CALL - clCreateSubDevicesEXT( cl_device_id /*in_device*/, - const cl_device_partition_property_ext * /* properties */, - cl_uint /*num_entries*/, - cl_device_id * /*out_devices*/, - cl_uint * /*num_devices*/ ) CL_EXT_SUFFIX__VERSION_1_1; - - typedef CL_API_ENTRY cl_int - ( CL_API_CALL * clCreateSubDevicesEXT_fn)( cl_device_id /*in_device*/, - const cl_device_partition_property_ext * /* properties */, - cl_uint /*num_entries*/, - cl_device_id * /*out_devices*/, - cl_uint * /*num_devices*/ ) CL_EXT_SUFFIX__VERSION_1_1; - - /* cl_device_partition_property_ext */ - #define CL_DEVICE_PARTITION_EQUALLY_EXT 0x4050 - #define CL_DEVICE_PARTITION_BY_COUNTS_EXT 0x4051 - #define CL_DEVICE_PARTITION_BY_NAMES_EXT 0x4052 - #define CL_DEVICE_PARTITION_BY_AFFINITY_DOMAIN_EXT 0x4053 - - /* clDeviceGetInfo selectors */ - #define CL_DEVICE_PARENT_DEVICE_EXT 0x4054 - #define CL_DEVICE_PARTITION_TYPES_EXT 0x4055 - #define CL_DEVICE_AFFINITY_DOMAINS_EXT 0x4056 - #define CL_DEVICE_REFERENCE_COUNT_EXT 0x4057 - #define CL_DEVICE_PARTITION_STYLE_EXT 0x4058 - - /* error codes */ - #define CL_DEVICE_PARTITION_FAILED_EXT -1057 - #define CL_INVALID_PARTITION_COUNT_EXT -1058 - #define CL_INVALID_PARTITION_NAME_EXT -1059 - - /* CL_AFFINITY_DOMAINs */ - #define CL_AFFINITY_DOMAIN_L1_CACHE_EXT 0x1 - #define CL_AFFINITY_DOMAIN_L2_CACHE_EXT 0x2 - #define CL_AFFINITY_DOMAIN_L3_CACHE_EXT 0x3 - #define CL_AFFINITY_DOMAIN_L4_CACHE_EXT 0x4 - #define CL_AFFINITY_DOMAIN_NUMA_EXT 0x10 - #define CL_AFFINITY_DOMAIN_NEXT_FISSIONABLE_EXT 0x100 - - /* cl_device_partition_property_ext list terminators */ - #define CL_PROPERTIES_LIST_END_EXT ((cl_device_partition_property_ext) 0) - #define CL_PARTITION_BY_COUNTS_LIST_END_EXT ((cl_device_partition_property_ext) 0) - #define CL_PARTITION_BY_NAMES_LIST_END_EXT ((cl_device_partition_property_ext) 0 - 1) - -/********************************* -* cl_qcom_ext_host_ptr extension -*********************************/ - -#define CL_MEM_EXT_HOST_PTR_QCOM (1 << 29) - -#define CL_DEVICE_EXT_MEM_PADDING_IN_BYTES_QCOM 0x40A0 -#define CL_DEVICE_PAGE_SIZE_QCOM 0x40A1 -#define CL_IMAGE_ROW_ALIGNMENT_QCOM 0x40A2 -#define CL_IMAGE_SLICE_ALIGNMENT_QCOM 0x40A3 -#define CL_MEM_HOST_UNCACHED_QCOM 0x40A4 -#define CL_MEM_HOST_WRITEBACK_QCOM 0x40A5 -#define CL_MEM_HOST_WRITETHROUGH_QCOM 0x40A6 -#define CL_MEM_HOST_WRITE_COMBINING_QCOM 0x40A7 - -typedef cl_uint cl_image_pitch_info_qcom; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetDeviceImageInfoQCOM(cl_device_id device, - size_t image_width, - size_t image_height, - const cl_image_format *image_format, - cl_image_pitch_info_qcom param_name, - size_t param_value_size, - void *param_value, - size_t *param_value_size_ret); - -typedef struct _cl_mem_ext_host_ptr -{ - /* Type of external memory allocation. */ - /* Legal values will be defined in layered extensions. */ - cl_uint allocation_type; - - /* Host cache policy for this external memory allocation. */ - cl_uint host_cache_policy; - -} cl_mem_ext_host_ptr; - -/********************************* -* cl_qcom_ion_host_ptr extension -*********************************/ - -#define CL_MEM_ION_HOST_PTR_QCOM 0x40A8 - -typedef struct _cl_mem_ion_host_ptr -{ - /* Type of external memory allocation. */ - /* Must be CL_MEM_ION_HOST_PTR_QCOM for ION allocations. */ - cl_mem_ext_host_ptr ext_host_ptr; - - /* ION file descriptor */ - int ion_filedesc; - - /* Host pointer to the ION allocated memory */ - void* ion_hostptr; - -} cl_mem_ion_host_ptr; - -#endif /* CL_VERSION_1_1 */ - - -#ifdef CL_VERSION_2_0 -/********************************* -* cl_khr_sub_groups extension -*********************************/ -#define cl_khr_sub_groups 1 - -typedef cl_uint cl_kernel_sub_group_info_khr; - -/* cl_khr_sub_group_info */ -#define CL_KERNEL_MAX_SUB_GROUP_SIZE_FOR_NDRANGE_KHR 0x2033 -#define CL_KERNEL_SUB_GROUP_COUNT_FOR_NDRANGE_KHR 0x2034 - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetKernelSubGroupInfoKHR(cl_kernel /* in_kernel */, - cl_device_id /*in_device*/, - cl_kernel_sub_group_info_khr /* param_name */, - size_t /*input_value_size*/, - const void * /*input_value*/, - size_t /*param_value_size*/, - void* /*param_value*/, - size_t* /*param_value_size_ret*/ ) CL_EXT_SUFFIX__VERSION_2_0_DEPRECATED; - -typedef CL_API_ENTRY cl_int - ( CL_API_CALL * clGetKernelSubGroupInfoKHR_fn)(cl_kernel /* in_kernel */, - cl_device_id /*in_device*/, - cl_kernel_sub_group_info_khr /* param_name */, - size_t /*input_value_size*/, - const void * /*input_value*/, - size_t /*param_value_size*/, - void* /*param_value*/, - size_t* /*param_value_size_ret*/ ) CL_EXT_SUFFIX__VERSION_2_0_DEPRECATED; -#endif /* CL_VERSION_2_0 */ - -#ifdef CL_VERSION_2_1 -/********************************* -* cl_khr_priority_hints extension -*********************************/ -#define cl_khr_priority_hints 1 - -typedef cl_uint cl_queue_priority_khr; - -/* cl_command_queue_properties */ -#define CL_QUEUE_PRIORITY_KHR 0x1096 - -/* cl_queue_priority_khr */ -#define CL_QUEUE_PRIORITY_HIGH_KHR (1<<0) -#define CL_QUEUE_PRIORITY_MED_KHR (1<<1) -#define CL_QUEUE_PRIORITY_LOW_KHR (1<<2) - -#endif /* CL_VERSION_2_1 */ - -#ifdef CL_VERSION_2_1 -/********************************* -* cl_khr_throttle_hints extension -*********************************/ -#define cl_khr_throttle_hints 1 - -typedef cl_uint cl_queue_throttle_khr; - -/* cl_command_queue_properties */ -#define CL_QUEUE_THROTTLE_KHR 0x1097 - -/* cl_queue_throttle_khr */ -#define CL_QUEUE_THROTTLE_HIGH_KHR (1<<0) -#define CL_QUEUE_THROTTLE_MED_KHR (1<<1) -#define CL_QUEUE_THROTTLE_LOW_KHR (1<<2) - -#endif /* CL_VERSION_2_1 */ - -#ifdef __cplusplus -} -#endif - - -#endif /* __CL_EXT_H */ diff --git a/third_party/opencl/include/CL/cl_ext_qcom.h b/third_party/opencl/include/CL/cl_ext_qcom.h deleted file mode 100644 index 6328a1cd93..0000000000 --- a/third_party/opencl/include/CL/cl_ext_qcom.h +++ /dev/null @@ -1,255 +0,0 @@ -/* Copyright (c) 2009-2017 Qualcomm Technologies, Inc. All Rights Reserved. - * Qualcomm Technologies Proprietary and Confidential. - */ - -#ifndef __OPENCL_CL_EXT_QCOM_H -#define __OPENCL_CL_EXT_QCOM_H - -// Needed by cl_khr_egl_event extension -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - - -/************************************ - * cl_qcom_create_buffer_from_image * - ************************************/ - -#define CL_BUFFER_FROM_IMAGE_ROW_PITCH_QCOM 0x40C0 -#define CL_BUFFER_FROM_IMAGE_SLICE_PITCH_QCOM 0x40C1 - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateBufferFromImageQCOM(cl_mem image, - cl_mem_flags flags, - cl_int *errcode_ret); - - -/************************************ - * cl_qcom_limited_printf extension * - ************************************/ - -/* Builtin printf function buffer size in bytes. */ -#define CL_DEVICE_PRINTF_BUFFER_SIZE_QCOM 0x1049 - - -/************************************* - * cl_qcom_extended_images extension * - *************************************/ - -#define CL_CONTEXT_ENABLE_EXTENDED_IMAGES_QCOM 0x40AA -#define CL_DEVICE_EXTENDED_IMAGE2D_MAX_WIDTH_QCOM 0x40AB -#define CL_DEVICE_EXTENDED_IMAGE2D_MAX_HEIGHT_QCOM 0x40AC -#define CL_DEVICE_EXTENDED_IMAGE3D_MAX_WIDTH_QCOM 0x40AD -#define CL_DEVICE_EXTENDED_IMAGE3D_MAX_HEIGHT_QCOM 0x40AE -#define CL_DEVICE_EXTENDED_IMAGE3D_MAX_DEPTH_QCOM 0x40AF - -/************************************* - * cl_qcom_perf_hint extension * - *************************************/ - -typedef cl_uint cl_perf_hint; - -#define CL_CONTEXT_PERF_HINT_QCOM 0x40C2 - -/*cl_perf_hint*/ -#define CL_PERF_HINT_HIGH_QCOM 0x40C3 -#define CL_PERF_HINT_NORMAL_QCOM 0x40C4 -#define CL_PERF_HINT_LOW_QCOM 0x40C5 - -extern CL_API_ENTRY cl_int CL_API_CALL -clSetPerfHintQCOM(cl_context context, - cl_perf_hint perf_hint); - -// This extension is published at Khronos, so its definitions are made in cl_ext.h. -// This duplication is for backward compatibility. - -#ifndef CL_MEM_ANDROID_NATIVE_BUFFER_HOST_PTR_QCOM - -/********************************* -* cl_qcom_android_native_buffer_host_ptr extension -*********************************/ - -#define CL_MEM_ANDROID_NATIVE_BUFFER_HOST_PTR_QCOM 0x40C6 - - -typedef struct _cl_mem_android_native_buffer_host_ptr -{ - // Type of external memory allocation. - // Must be CL_MEM_ANDROID_NATIVE_BUFFER_HOST_PTR_QCOM for Android native buffers. - cl_mem_ext_host_ptr ext_host_ptr; - - // Virtual pointer to the android native buffer - void* anb_ptr; - -} cl_mem_android_native_buffer_host_ptr; - -#endif //#ifndef CL_MEM_ANDROID_NATIVE_BUFFER_HOST_PTR_QCOM - -/*********************************** -* cl_img_egl_image extension * -************************************/ -typedef void* CLeglImageIMG; -typedef void* CLeglDisplayIMG; - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateFromEGLImageIMG(cl_context context, - cl_mem_flags flags, - CLeglImageIMG image, - CLeglDisplayIMG display, - cl_int *errcode_ret); - - -/********************************* -* cl_qcom_other_image extension -*********************************/ - -// Extended flag for creating/querying QCOM non-standard images -#define CL_MEM_OTHER_IMAGE_QCOM (1<<25) - -// cl_channel_type -#define CL_QCOM_UNORM_MIPI10 0x4159 -#define CL_QCOM_UNORM_MIPI12 0x415A -#define CL_QCOM_UNSIGNED_MIPI10 0x415B -#define CL_QCOM_UNSIGNED_MIPI12 0x415C -#define CL_QCOM_UNORM_INT10 0x415D -#define CL_QCOM_UNORM_INT12 0x415E -#define CL_QCOM_UNSIGNED_INT16 0x415F - -// cl_channel_order -// Dedicate 0x4130-0x415F range for QCOM extended image formats -// 0x4130 - 0x4132 range is assigned to pixel-oriented compressed format -#define CL_QCOM_BAYER 0x414E - -#define CL_QCOM_NV12 0x4133 -#define CL_QCOM_NV12_Y 0x4134 -#define CL_QCOM_NV12_UV 0x4135 - -#define CL_QCOM_TILED_NV12 0x4136 -#define CL_QCOM_TILED_NV12_Y 0x4137 -#define CL_QCOM_TILED_NV12_UV 0x4138 - -#define CL_QCOM_P010 0x413C -#define CL_QCOM_P010_Y 0x413D -#define CL_QCOM_P010_UV 0x413E - -#define CL_QCOM_TILED_P010 0x413F -#define CL_QCOM_TILED_P010_Y 0x4140 -#define CL_QCOM_TILED_P010_UV 0x4141 - - -#define CL_QCOM_TP10 0x4145 -#define CL_QCOM_TP10_Y 0x4146 -#define CL_QCOM_TP10_UV 0x4147 - -#define CL_QCOM_TILED_TP10 0x4148 -#define CL_QCOM_TILED_TP10_Y 0x4149 -#define CL_QCOM_TILED_TP10_UV 0x414A - -/********************************* -* cl_qcom_compressed_image extension -*********************************/ - -// Extended flag for creating/querying QCOM non-planar compressed images -#define CL_MEM_COMPRESSED_IMAGE_QCOM (1<<27) - -// Extended image format -// cl_channel_order -#define CL_QCOM_COMPRESSED_RGBA 0x4130 -#define CL_QCOM_COMPRESSED_RGBx 0x4131 - -#define CL_QCOM_COMPRESSED_NV12_Y 0x413A -#define CL_QCOM_COMPRESSED_NV12_UV 0x413B - -#define CL_QCOM_COMPRESSED_P010 0x4142 -#define CL_QCOM_COMPRESSED_P010_Y 0x4143 -#define CL_QCOM_COMPRESSED_P010_UV 0x4144 - -#define CL_QCOM_COMPRESSED_TP10 0x414B -#define CL_QCOM_COMPRESSED_TP10_Y 0x414C -#define CL_QCOM_COMPRESSED_TP10_UV 0x414D - -#define CL_QCOM_COMPRESSED_NV12_4R 0x414F -#define CL_QCOM_COMPRESSED_NV12_4R_Y 0x4150 -#define CL_QCOM_COMPRESSED_NV12_4R_UV 0x4151 -/********************************* -* cl_qcom_compressed_yuv_image_read extension -*********************************/ - -// Extended flag for creating/querying QCOM compressed images -#define CL_MEM_COMPRESSED_YUV_IMAGE_QCOM (1<<28) - -// Extended image format -#define CL_QCOM_COMPRESSED_NV12 0x10C4 - -// Extended flag for setting ION buffer allocation type -#define CL_MEM_ION_HOST_PTR_COMPRESSED_YUV_QCOM 0x40CD -#define CL_MEM_ION_HOST_PTR_PROTECTED_COMPRESSED_YUV_QCOM 0x40CE - -/********************************* -* cl_qcom_accelerated_image_ops -*********************************/ -#define CL_MEM_OBJECT_WEIGHT_IMAGE_QCOM 0x4110 -#define CL_DEVICE_HOF_MAX_NUM_PHASES_QCOM 0x4111 -#define CL_DEVICE_HOF_MAX_FILTER_SIZE_X_QCOM 0x4112 -#define CL_DEVICE_HOF_MAX_FILTER_SIZE_Y_QCOM 0x4113 -#define CL_DEVICE_BLOCK_MATCHING_MAX_REGION_SIZE_X_QCOM 0x4114 -#define CL_DEVICE_BLOCK_MATCHING_MAX_REGION_SIZE_Y_QCOM 0x4115 - -//Extended flag for specifying weight image type -#define CL_WEIGHT_IMAGE_SEPARABLE_QCOM (1<<0) - -// Box Filter -typedef struct _cl_box_filter_size_qcom -{ - // Width of box filter on X direction. - float box_filter_width; - - // Height of box filter on Y direction. - float box_filter_height; -} cl_box_filter_size_qcom; - -// HOF Weight Image Desc -typedef struct _cl_weight_desc_qcom -{ - /** Coordinate of the "center" point of the weight image, - based on the weight image's top-left corner as the origin. */ - size_t center_coord_x; - size_t center_coord_y; - cl_bitfield flags; -} cl_weight_desc_qcom; - -typedef struct _cl_weight_image_desc_qcom -{ - cl_image_desc image_desc; - cl_weight_desc_qcom weight_desc; -} cl_weight_image_desc_qcom; - -/************************************* - * cl_qcom_protected_context extension * - *************************************/ - -#define CL_CONTEXT_PROTECTED_QCOM 0x40C7 -#define CL_MEM_ION_HOST_PTR_PROTECTED_QCOM 0x40C8 - -/************************************* - * cl_qcom_priority_hint extension * - *************************************/ -#define CL_PRIORITY_HINT_NONE_QCOM 0 -typedef cl_uint cl_priority_hint; - -#define CL_CONTEXT_PRIORITY_HINT_QCOM 0x40C9 - -/*cl_priority_hint*/ -#define CL_PRIORITY_HINT_HIGH_QCOM 0x40CA -#define CL_PRIORITY_HINT_NORMAL_QCOM 0x40CB -#define CL_PRIORITY_HINT_LOW_QCOM 0x40CC - -#ifdef __cplusplus -} -#endif - -#endif /* __OPENCL_CL_EXT_QCOM_H */ diff --git a/third_party/opencl/include/CL/cl_gl.h b/third_party/opencl/include/CL/cl_gl.h deleted file mode 100644 index 945daa83d7..0000000000 --- a/third_party/opencl/include/CL/cl_gl.h +++ /dev/null @@ -1,167 +0,0 @@ -/********************************************************************************** - * Copyright (c) 2008-2015 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are 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 Materials. - * - * MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS - * KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS - * SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT - * https://www.khronos.org/registry/ - * - * THE MATERIALS ARE 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 - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - **********************************************************************************/ - -#ifndef __OPENCL_CL_GL_H -#define __OPENCL_CL_GL_H - -#ifdef __APPLE__ -#include -#else -#include -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -typedef cl_uint cl_gl_object_type; -typedef cl_uint cl_gl_texture_info; -typedef cl_uint cl_gl_platform_info; -typedef struct __GLsync *cl_GLsync; - -/* cl_gl_object_type = 0x2000 - 0x200F enum values are currently taken */ -#define CL_GL_OBJECT_BUFFER 0x2000 -#define CL_GL_OBJECT_TEXTURE2D 0x2001 -#define CL_GL_OBJECT_TEXTURE3D 0x2002 -#define CL_GL_OBJECT_RENDERBUFFER 0x2003 -#define CL_GL_OBJECT_TEXTURE2D_ARRAY 0x200E -#define CL_GL_OBJECT_TEXTURE1D 0x200F -#define CL_GL_OBJECT_TEXTURE1D_ARRAY 0x2010 -#define CL_GL_OBJECT_TEXTURE_BUFFER 0x2011 - -/* cl_gl_texture_info */ -#define CL_GL_TEXTURE_TARGET 0x2004 -#define CL_GL_MIPMAP_LEVEL 0x2005 -#define CL_GL_NUM_SAMPLES 0x2012 - - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateFromGLBuffer(cl_context /* context */, - cl_mem_flags /* flags */, - cl_GLuint /* bufobj */, - int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateFromGLTexture(cl_context /* context */, - cl_mem_flags /* flags */, - cl_GLenum /* target */, - cl_GLint /* miplevel */, - cl_GLuint /* texture */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_2; - -extern CL_API_ENTRY cl_mem CL_API_CALL -clCreateFromGLRenderbuffer(cl_context /* context */, - cl_mem_flags /* flags */, - cl_GLuint /* renderbuffer */, - cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetGLObjectInfo(cl_mem /* memobj */, - cl_gl_object_type * /* gl_object_type */, - cl_GLuint * /* gl_object_name */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetGLTextureInfo(cl_mem /* memobj */, - cl_gl_texture_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueAcquireGLObjects(cl_command_queue /* command_queue */, - cl_uint /* num_objects */, - const cl_mem * /* mem_objects */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - -extern CL_API_ENTRY cl_int CL_API_CALL -clEnqueueReleaseGLObjects(cl_command_queue /* command_queue */, - cl_uint /* num_objects */, - const cl_mem * /* mem_objects */, - cl_uint /* num_events_in_wait_list */, - const cl_event * /* event_wait_list */, - cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; - - -/* Deprecated OpenCL 1.1 APIs */ -extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_1_1_DEPRECATED cl_mem CL_API_CALL -clCreateFromGLTexture2D(cl_context /* context */, - cl_mem_flags /* flags */, - cl_GLenum /* target */, - cl_GLint /* miplevel */, - cl_GLuint /* texture */, - cl_int * /* errcode_ret */) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; - -extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_1_1_DEPRECATED cl_mem CL_API_CALL -clCreateFromGLTexture3D(cl_context /* context */, - cl_mem_flags /* flags */, - cl_GLenum /* target */, - cl_GLint /* miplevel */, - cl_GLuint /* texture */, - cl_int * /* errcode_ret */) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; - -/* cl_khr_gl_sharing extension */ - -#define cl_khr_gl_sharing 1 - -typedef cl_uint cl_gl_context_info; - -/* Additional Error Codes */ -#define CL_INVALID_GL_SHAREGROUP_REFERENCE_KHR -1000 - -/* cl_gl_context_info */ -#define CL_CURRENT_DEVICE_FOR_GL_CONTEXT_KHR 0x2006 -#define CL_DEVICES_FOR_GL_CONTEXT_KHR 0x2007 - -/* Additional cl_context_properties */ -#define CL_GL_CONTEXT_KHR 0x2008 -#define CL_EGL_DISPLAY_KHR 0x2009 -#define CL_GLX_DISPLAY_KHR 0x200A -#define CL_WGL_HDC_KHR 0x200B -#define CL_CGL_SHAREGROUP_KHR 0x200C - -extern CL_API_ENTRY cl_int CL_API_CALL -clGetGLContextInfoKHR(const cl_context_properties * /* properties */, - cl_gl_context_info /* param_name */, - size_t /* param_value_size */, - void * /* param_value */, - size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; - -typedef CL_API_ENTRY cl_int (CL_API_CALL *clGetGLContextInfoKHR_fn)( - const cl_context_properties * properties, - cl_gl_context_info param_name, - size_t param_value_size, - void * param_value, - size_t * param_value_size_ret); - -#ifdef __cplusplus -} -#endif - -#endif /* __OPENCL_CL_GL_H */ diff --git a/third_party/opencl/include/CL/cl_gl_ext.h b/third_party/opencl/include/CL/cl_gl_ext.h deleted file mode 100644 index e3c14c6408..0000000000 --- a/third_party/opencl/include/CL/cl_gl_ext.h +++ /dev/null @@ -1,74 +0,0 @@ -/********************************************************************************** - * Copyright (c) 2008-2015 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are 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 Materials. - * - * MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS - * KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS - * SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT - * https://www.khronos.org/registry/ - * - * THE MATERIALS ARE 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 - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - **********************************************************************************/ - -/* $Revision: 11708 $ on $Date: 2010-06-13 23:36:24 -0700 (Sun, 13 Jun 2010) $ */ - -/* cl_gl_ext.h contains vendor (non-KHR) OpenCL extensions which have */ -/* OpenGL dependencies. */ - -#ifndef __OPENCL_CL_GL_EXT_H -#define __OPENCL_CL_GL_EXT_H - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef __APPLE__ - #include -#else - #include -#endif - -/* - * For each extension, follow this template - * cl_VEN_extname extension */ -/* #define cl_VEN_extname 1 - * ... define new types, if any - * ... define new tokens, if any - * ... define new APIs, if any - * - * If you need GLtypes here, mirror them with a cl_GLtype, rather than including a GL header - * This allows us to avoid having to decide whether to include GL headers or GLES here. - */ - -/* - * cl_khr_gl_event extension - * See section 9.9 in the OpenCL 1.1 spec for more information - */ -#define CL_COMMAND_GL_FENCE_SYNC_OBJECT_KHR 0x200D - -extern CL_API_ENTRY cl_event CL_API_CALL -clCreateEventFromGLsyncKHR(cl_context /* context */, - cl_GLsync /* cl_GLsync */, - cl_int * /* errcode_ret */) CL_EXT_SUFFIX__VERSION_1_1; - -#ifdef __cplusplus -} -#endif - -#endif /* __OPENCL_CL_GL_EXT_H */ diff --git a/third_party/opencl/include/CL/cl_platform.h b/third_party/opencl/include/CL/cl_platform.h deleted file mode 100644 index 4e334a2918..0000000000 --- a/third_party/opencl/include/CL/cl_platform.h +++ /dev/null @@ -1,1333 +0,0 @@ -/********************************************************************************** - * Copyright (c) 2008-2015 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are 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 Materials. - * - * MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS - * KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS - * SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT - * https://www.khronos.org/registry/ - * - * THE MATERIALS ARE 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 - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - **********************************************************************************/ - -/* $Revision: 11803 $ on $Date: 2010-06-25 10:02:12 -0700 (Fri, 25 Jun 2010) $ */ - -#ifndef __CL_PLATFORM_H -#define __CL_PLATFORM_H - -#ifdef __APPLE__ - /* Contains #defines for AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER below */ - #include -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -#if defined(_WIN32) - #define CL_API_ENTRY - #define CL_API_CALL __stdcall - #define CL_CALLBACK __stdcall -#else - #define CL_API_ENTRY - #define CL_API_CALL - #define CL_CALLBACK -#endif - -/* - * Deprecation flags refer to the last version of the header in which the - * feature was not deprecated. - * - * E.g. VERSION_1_1_DEPRECATED means the feature is present in 1.1 without - * deprecation but is deprecated in versions later than 1.1. - */ - -#ifdef __APPLE__ - #define CL_EXTENSION_WEAK_LINK __attribute__((weak_import)) - #define CL_API_SUFFIX__VERSION_1_0 AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER - #define CL_EXT_SUFFIX__VERSION_1_0 CL_EXTENSION_WEAK_LINK AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER - #define CL_API_SUFFIX__VERSION_1_1 AVAILABLE_MAC_OS_X_VERSION_10_7_AND_LATER - #define GCL_API_SUFFIX__VERSION_1_1 AVAILABLE_MAC_OS_X_VERSION_10_7_AND_LATER - #define CL_EXT_SUFFIX__VERSION_1_1 CL_EXTENSION_WEAK_LINK AVAILABLE_MAC_OS_X_VERSION_10_7_AND_LATER - #define CL_EXT_SUFFIX__VERSION_1_0_DEPRECATED CL_EXTENSION_WEAK_LINK AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER_BUT_DEPRECATED_IN_MAC_OS_X_VERSION_10_7 - - #ifdef AVAILABLE_MAC_OS_X_VERSION_10_8_AND_LATER - #define CL_API_SUFFIX__VERSION_1_2 AVAILABLE_MAC_OS_X_VERSION_10_8_AND_LATER - #define GCL_API_SUFFIX__VERSION_1_2 AVAILABLE_MAC_OS_X_VERSION_10_8_AND_LATER - #define CL_EXT_SUFFIX__VERSION_1_2 CL_EXTENSION_WEAK_LINK AVAILABLE_MAC_OS_X_VERSION_10_8_AND_LATER - #define CL_EXT_PREFIX__VERSION_1_1_DEPRECATED - #define CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED CL_EXTENSION_WEAK_LINK AVAILABLE_MAC_OS_X_VERSION_10_7_AND_LATER_BUT_DEPRECATED_IN_MAC_OS_X_VERSION_10_8 - #else - #warning This path should never happen outside of internal operating system development. AvailabilityMacros do not function correctly here! - #define CL_API_SUFFIX__VERSION_1_2 AVAILABLE_MAC_OS_X_VERSION_10_7_AND_LATER - #define GCL_API_SUFFIX__VERSION_1_2 AVAILABLE_MAC_OS_X_VERSION_10_7_AND_LATER - #define CL_EXT_SUFFIX__VERSION_1_2 CL_EXTENSION_WEAK_LINK AVAILABLE_MAC_OS_X_VERSION_10_7_AND_LATER - #define CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED CL_EXTENSION_WEAK_LINK AVAILABLE_MAC_OS_X_VERSION_10_7_AND_LATER - #endif -#else - #define CL_EXTENSION_WEAK_LINK - #define CL_API_SUFFIX__VERSION_1_0 - #define CL_EXT_SUFFIX__VERSION_1_0 - #define CL_API_SUFFIX__VERSION_1_1 - #define CL_EXT_SUFFIX__VERSION_1_1 - #define CL_API_SUFFIX__VERSION_1_2 - #define CL_EXT_SUFFIX__VERSION_1_2 - #define CL_API_SUFFIX__VERSION_2_0 - #define CL_EXT_SUFFIX__VERSION_2_0 - #define CL_API_SUFFIX__VERSION_2_1 - #define CL_EXT_SUFFIX__VERSION_2_1 - - #ifdef __GNUC__ - #ifdef CL_USE_DEPRECATED_OPENCL_1_0_APIS - #define CL_EXT_SUFFIX__VERSION_1_0_DEPRECATED - #define CL_EXT_PREFIX__VERSION_1_0_DEPRECATED - #else - #define CL_EXT_SUFFIX__VERSION_1_0_DEPRECATED __attribute__((deprecated)) - #define CL_EXT_PREFIX__VERSION_1_0_DEPRECATED - #endif - - #ifdef CL_USE_DEPRECATED_OPENCL_1_1_APIS - #define CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED - #define CL_EXT_PREFIX__VERSION_1_1_DEPRECATED - #else - #define CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED __attribute__((deprecated)) - #define CL_EXT_PREFIX__VERSION_1_1_DEPRECATED - #endif - - #ifdef CL_USE_DEPRECATED_OPENCL_1_2_APIS - #define CL_EXT_SUFFIX__VERSION_1_2_DEPRECATED - #define CL_EXT_PREFIX__VERSION_1_2_DEPRECATED - #else - #define CL_EXT_SUFFIX__VERSION_1_2_DEPRECATED __attribute__((deprecated)) - #define CL_EXT_PREFIX__VERSION_1_2_DEPRECATED - #endif - - #ifdef CL_USE_DEPRECATED_OPENCL_2_0_APIS - #define CL_EXT_SUFFIX__VERSION_2_0_DEPRECATED - #define CL_EXT_PREFIX__VERSION_2_0_DEPRECATED - #else - #define CL_EXT_SUFFIX__VERSION_2_0_DEPRECATED __attribute__((deprecated)) - #define CL_EXT_PREFIX__VERSION_2_0_DEPRECATED - #endif - #elif _WIN32 - #ifdef CL_USE_DEPRECATED_OPENCL_1_0_APIS - #define CL_EXT_SUFFIX__VERSION_1_0_DEPRECATED - #define CL_EXT_PREFIX__VERSION_1_0_DEPRECATED - #else - #define CL_EXT_SUFFIX__VERSION_1_0_DEPRECATED - #define CL_EXT_PREFIX__VERSION_1_0_DEPRECATED __declspec(deprecated) - #endif - - #ifdef CL_USE_DEPRECATED_OPENCL_1_1_APIS - #define CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED - #define CL_EXT_PREFIX__VERSION_1_1_DEPRECATED - #else - #define CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED - #define CL_EXT_PREFIX__VERSION_1_1_DEPRECATED __declspec(deprecated) - #endif - - #ifdef CL_USE_DEPRECATED_OPENCL_1_2_APIS - #define CL_EXT_SUFFIX__VERSION_1_2_DEPRECATED - #define CL_EXT_PREFIX__VERSION_1_2_DEPRECATED - #else - #define CL_EXT_SUFFIX__VERSION_1_2_DEPRECATED - #define CL_EXT_PREFIX__VERSION_1_2_DEPRECATED __declspec(deprecated) - #endif - - #ifdef CL_USE_DEPRECATED_OPENCL_2_0_APIS - #define CL_EXT_SUFFIX__VERSION_2_0_DEPRECATED - #define CL_EXT_PREFIX__VERSION_2_0_DEPRECATED - #else - #define CL_EXT_SUFFIX__VERSION_2_0_DEPRECATED - #define CL_EXT_PREFIX__VERSION_2_0_DEPRECATED __declspec(deprecated) - #endif - #else - #define CL_EXT_SUFFIX__VERSION_1_0_DEPRECATED - #define CL_EXT_PREFIX__VERSION_1_0_DEPRECATED - - #define CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED - #define CL_EXT_PREFIX__VERSION_1_1_DEPRECATED - - #define CL_EXT_SUFFIX__VERSION_1_2_DEPRECATED - #define CL_EXT_PREFIX__VERSION_1_2_DEPRECATED - - #define CL_EXT_SUFFIX__VERSION_2_0_DEPRECATED - #define CL_EXT_PREFIX__VERSION_2_0_DEPRECATED - #endif -#endif - -#if (defined (_WIN32) && defined(_MSC_VER)) - -/* scalar types */ -typedef signed __int8 cl_char; -typedef unsigned __int8 cl_uchar; -typedef signed __int16 cl_short; -typedef unsigned __int16 cl_ushort; -typedef signed __int32 cl_int; -typedef unsigned __int32 cl_uint; -typedef signed __int64 cl_long; -typedef unsigned __int64 cl_ulong; - -typedef unsigned __int16 cl_half; -typedef float cl_float; -typedef double cl_double; - -/* Macro names and corresponding values defined by OpenCL */ -#define CL_CHAR_BIT 8 -#define CL_SCHAR_MAX 127 -#define CL_SCHAR_MIN (-127-1) -#define CL_CHAR_MAX CL_SCHAR_MAX -#define CL_CHAR_MIN CL_SCHAR_MIN -#define CL_UCHAR_MAX 255 -#define CL_SHRT_MAX 32767 -#define CL_SHRT_MIN (-32767-1) -#define CL_USHRT_MAX 65535 -#define CL_INT_MAX 2147483647 -#define CL_INT_MIN (-2147483647-1) -#define CL_UINT_MAX 0xffffffffU -#define CL_LONG_MAX ((cl_long) 0x7FFFFFFFFFFFFFFFLL) -#define CL_LONG_MIN ((cl_long) -0x7FFFFFFFFFFFFFFFLL - 1LL) -#define CL_ULONG_MAX ((cl_ulong) 0xFFFFFFFFFFFFFFFFULL) - -#define CL_FLT_DIG 6 -#define CL_FLT_MANT_DIG 24 -#define CL_FLT_MAX_10_EXP +38 -#define CL_FLT_MAX_EXP +128 -#define CL_FLT_MIN_10_EXP -37 -#define CL_FLT_MIN_EXP -125 -#define CL_FLT_RADIX 2 -#define CL_FLT_MAX 340282346638528859811704183484516925440.0f -#define CL_FLT_MIN 1.175494350822287507969e-38f -#define CL_FLT_EPSILON 0x1.0p-23f - -#define CL_DBL_DIG 15 -#define CL_DBL_MANT_DIG 53 -#define CL_DBL_MAX_10_EXP +308 -#define CL_DBL_MAX_EXP +1024 -#define CL_DBL_MIN_10_EXP -307 -#define CL_DBL_MIN_EXP -1021 -#define CL_DBL_RADIX 2 -#define CL_DBL_MAX 179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.0 -#define CL_DBL_MIN 2.225073858507201383090e-308 -#define CL_DBL_EPSILON 2.220446049250313080847e-16 - -#define CL_M_E 2.718281828459045090796 -#define CL_M_LOG2E 1.442695040888963387005 -#define CL_M_LOG10E 0.434294481903251816668 -#define CL_M_LN2 0.693147180559945286227 -#define CL_M_LN10 2.302585092994045901094 -#define CL_M_PI 3.141592653589793115998 -#define CL_M_PI_2 1.570796326794896557999 -#define CL_M_PI_4 0.785398163397448278999 -#define CL_M_1_PI 0.318309886183790691216 -#define CL_M_2_PI 0.636619772367581382433 -#define CL_M_2_SQRTPI 1.128379167095512558561 -#define CL_M_SQRT2 1.414213562373095145475 -#define CL_M_SQRT1_2 0.707106781186547572737 - -#define CL_M_E_F 2.71828174591064f -#define CL_M_LOG2E_F 1.44269502162933f -#define CL_M_LOG10E_F 0.43429449200630f -#define CL_M_LN2_F 0.69314718246460f -#define CL_M_LN10_F 2.30258512496948f -#define CL_M_PI_F 3.14159274101257f -#define CL_M_PI_2_F 1.57079637050629f -#define CL_M_PI_4_F 0.78539818525314f -#define CL_M_1_PI_F 0.31830987334251f -#define CL_M_2_PI_F 0.63661974668503f -#define CL_M_2_SQRTPI_F 1.12837922573090f -#define CL_M_SQRT2_F 1.41421353816986f -#define CL_M_SQRT1_2_F 0.70710676908493f - -#define CL_NAN (CL_INFINITY - CL_INFINITY) -#define CL_HUGE_VALF ((cl_float) 1e50) -#define CL_HUGE_VAL ((cl_double) 1e500) -#define CL_MAXFLOAT CL_FLT_MAX -#define CL_INFINITY CL_HUGE_VALF - -#else - -#include - -/* scalar types */ -typedef int8_t cl_char; -typedef uint8_t cl_uchar; -typedef int16_t cl_short __attribute__((aligned(2))); -typedef uint16_t cl_ushort __attribute__((aligned(2))); -typedef int32_t cl_int __attribute__((aligned(4))); -typedef uint32_t cl_uint __attribute__((aligned(4))); -typedef int64_t cl_long __attribute__((aligned(8))); -typedef uint64_t cl_ulong __attribute__((aligned(8))); - -typedef uint16_t cl_half __attribute__((aligned(2))); -typedef float cl_float __attribute__((aligned(4))); -typedef double cl_double __attribute__((aligned(8))); - -/* Macro names and corresponding values defined by OpenCL */ -#define CL_CHAR_BIT 8 -#define CL_SCHAR_MAX 127 -#define CL_SCHAR_MIN (-127-1) -#define CL_CHAR_MAX CL_SCHAR_MAX -#define CL_CHAR_MIN CL_SCHAR_MIN -#define CL_UCHAR_MAX 255 -#define CL_SHRT_MAX 32767 -#define CL_SHRT_MIN (-32767-1) -#define CL_USHRT_MAX 65535 -#define CL_INT_MAX 2147483647 -#define CL_INT_MIN (-2147483647-1) -#define CL_UINT_MAX 0xffffffffU -#define CL_LONG_MAX ((cl_long) 0x7FFFFFFFFFFFFFFFLL) -#define CL_LONG_MIN ((cl_long) -0x7FFFFFFFFFFFFFFFLL - 1LL) -#define CL_ULONG_MAX ((cl_ulong) 0xFFFFFFFFFFFFFFFFULL) - -#define CL_FLT_DIG 6 -#define CL_FLT_MANT_DIG 24 -#define CL_FLT_MAX_10_EXP +38 -#define CL_FLT_MAX_EXP +128 -#define CL_FLT_MIN_10_EXP -37 -#define CL_FLT_MIN_EXP -125 -#define CL_FLT_RADIX 2 -#define CL_FLT_MAX 0x1.fffffep127f -#define CL_FLT_MIN 0x1.0p-126f -#define CL_FLT_EPSILON 0x1.0p-23f - -#define CL_DBL_DIG 15 -#define CL_DBL_MANT_DIG 53 -#define CL_DBL_MAX_10_EXP +308 -#define CL_DBL_MAX_EXP +1024 -#define CL_DBL_MIN_10_EXP -307 -#define CL_DBL_MIN_EXP -1021 -#define CL_DBL_RADIX 2 -#define CL_DBL_MAX 0x1.fffffffffffffp1023 -#define CL_DBL_MIN 0x1.0p-1022 -#define CL_DBL_EPSILON 0x1.0p-52 - -#define CL_M_E 2.718281828459045090796 -#define CL_M_LOG2E 1.442695040888963387005 -#define CL_M_LOG10E 0.434294481903251816668 -#define CL_M_LN2 0.693147180559945286227 -#define CL_M_LN10 2.302585092994045901094 -#define CL_M_PI 3.141592653589793115998 -#define CL_M_PI_2 1.570796326794896557999 -#define CL_M_PI_4 0.785398163397448278999 -#define CL_M_1_PI 0.318309886183790691216 -#define CL_M_2_PI 0.636619772367581382433 -#define CL_M_2_SQRTPI 1.128379167095512558561 -#define CL_M_SQRT2 1.414213562373095145475 -#define CL_M_SQRT1_2 0.707106781186547572737 - -#define CL_M_E_F 2.71828174591064f -#define CL_M_LOG2E_F 1.44269502162933f -#define CL_M_LOG10E_F 0.43429449200630f -#define CL_M_LN2_F 0.69314718246460f -#define CL_M_LN10_F 2.30258512496948f -#define CL_M_PI_F 3.14159274101257f -#define CL_M_PI_2_F 1.57079637050629f -#define CL_M_PI_4_F 0.78539818525314f -#define CL_M_1_PI_F 0.31830987334251f -#define CL_M_2_PI_F 0.63661974668503f -#define CL_M_2_SQRTPI_F 1.12837922573090f -#define CL_M_SQRT2_F 1.41421353816986f -#define CL_M_SQRT1_2_F 0.70710676908493f - -#if defined( __GNUC__ ) - #define CL_HUGE_VALF __builtin_huge_valf() - #define CL_HUGE_VAL __builtin_huge_val() - #define CL_NAN __builtin_nanf( "" ) -#else - #define CL_HUGE_VALF ((cl_float) 1e50) - #define CL_HUGE_VAL ((cl_double) 1e500) - float nanf( const char * ); - #define CL_NAN nanf( "" ) -#endif -#define CL_MAXFLOAT CL_FLT_MAX -#define CL_INFINITY CL_HUGE_VALF - -#endif - -#include - -/* Mirror types to GL types. Mirror types allow us to avoid deciding which 87s to load based on whether we are using GL or GLES here. */ -typedef unsigned int cl_GLuint; -typedef int cl_GLint; -typedef unsigned int cl_GLenum; - -/* - * Vector types - * - * Note: OpenCL requires that all types be naturally aligned. - * This means that vector types must be naturally aligned. - * For example, a vector of four floats must be aligned to - * a 16 byte boundary (calculated as 4 * the natural 4-byte - * alignment of the float). The alignment qualifiers here - * will only function properly if your compiler supports them - * and if you don't actively work to defeat them. For example, - * in order for a cl_float4 to be 16 byte aligned in a struct, - * the start of the struct must itself be 16-byte aligned. - * - * Maintaining proper alignment is the user's responsibility. - */ - -/* Define basic vector types */ -#if defined( __VEC__ ) - #include /* may be omitted depending on compiler. AltiVec spec provides no way to detect whether the header is required. */ - typedef vector unsigned char __cl_uchar16; - typedef vector signed char __cl_char16; - typedef vector unsigned short __cl_ushort8; - typedef vector signed short __cl_short8; - typedef vector unsigned int __cl_uint4; - typedef vector signed int __cl_int4; - typedef vector float __cl_float4; - #define __CL_UCHAR16__ 1 - #define __CL_CHAR16__ 1 - #define __CL_USHORT8__ 1 - #define __CL_SHORT8__ 1 - #define __CL_UINT4__ 1 - #define __CL_INT4__ 1 - #define __CL_FLOAT4__ 1 -#endif - -#if defined( __SSE__ ) - #if defined( __MINGW64__ ) - #include - #else - #include - #endif - #if defined( __GNUC__ ) - typedef float __cl_float4 __attribute__((vector_size(16))); - #else - typedef __m128 __cl_float4; - #endif - #define __CL_FLOAT4__ 1 -#endif - -#if defined( __SSE2__ ) - #if defined( __MINGW64__ ) - #include - #else - #include - #endif - #if defined( __GNUC__ ) - typedef cl_uchar __cl_uchar16 __attribute__((vector_size(16))); - typedef cl_char __cl_char16 __attribute__((vector_size(16))); - typedef cl_ushort __cl_ushort8 __attribute__((vector_size(16))); - typedef cl_short __cl_short8 __attribute__((vector_size(16))); - typedef cl_uint __cl_uint4 __attribute__((vector_size(16))); - typedef cl_int __cl_int4 __attribute__((vector_size(16))); - typedef cl_ulong __cl_ulong2 __attribute__((vector_size(16))); - typedef cl_long __cl_long2 __attribute__((vector_size(16))); - typedef cl_double __cl_double2 __attribute__((vector_size(16))); - #else - typedef __m128i __cl_uchar16; - typedef __m128i __cl_char16; - typedef __m128i __cl_ushort8; - typedef __m128i __cl_short8; - typedef __m128i __cl_uint4; - typedef __m128i __cl_int4; - typedef __m128i __cl_ulong2; - typedef __m128i __cl_long2; - typedef __m128d __cl_double2; - #endif - #define __CL_UCHAR16__ 1 - #define __CL_CHAR16__ 1 - #define __CL_USHORT8__ 1 - #define __CL_SHORT8__ 1 - #define __CL_INT4__ 1 - #define __CL_UINT4__ 1 - #define __CL_ULONG2__ 1 - #define __CL_LONG2__ 1 - #define __CL_DOUBLE2__ 1 -#endif - -#if defined( __MMX__ ) - #include - #if defined( __GNUC__ ) - typedef cl_uchar __cl_uchar8 __attribute__((vector_size(8))); - typedef cl_char __cl_char8 __attribute__((vector_size(8))); - typedef cl_ushort __cl_ushort4 __attribute__((vector_size(8))); - typedef cl_short __cl_short4 __attribute__((vector_size(8))); - typedef cl_uint __cl_uint2 __attribute__((vector_size(8))); - typedef cl_int __cl_int2 __attribute__((vector_size(8))); - typedef cl_ulong __cl_ulong1 __attribute__((vector_size(8))); - typedef cl_long __cl_long1 __attribute__((vector_size(8))); - typedef cl_float __cl_float2 __attribute__((vector_size(8))); - #else - typedef __m64 __cl_uchar8; - typedef __m64 __cl_char8; - typedef __m64 __cl_ushort4; - typedef __m64 __cl_short4; - typedef __m64 __cl_uint2; - typedef __m64 __cl_int2; - typedef __m64 __cl_ulong1; - typedef __m64 __cl_long1; - typedef __m64 __cl_float2; - #endif - #define __CL_UCHAR8__ 1 - #define __CL_CHAR8__ 1 - #define __CL_USHORT4__ 1 - #define __CL_SHORT4__ 1 - #define __CL_INT2__ 1 - #define __CL_UINT2__ 1 - #define __CL_ULONG1__ 1 - #define __CL_LONG1__ 1 - #define __CL_FLOAT2__ 1 -#endif - -#if defined( __AVX__ ) - #if defined( __MINGW64__ ) - #include - #else - #include - #endif - #if defined( __GNUC__ ) - typedef cl_float __cl_float8 __attribute__((vector_size(32))); - typedef cl_double __cl_double4 __attribute__((vector_size(32))); - #else - typedef __m256 __cl_float8; - typedef __m256d __cl_double4; - #endif - #define __CL_FLOAT8__ 1 - #define __CL_DOUBLE4__ 1 -#endif - -/* Define capabilities for anonymous struct members. */ -#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) -#define __CL_HAS_ANON_STRUCT__ 1 -#define __CL_ANON_STRUCT__ __extension__ -#elif defined( _WIN32) && (_MSC_VER >= 1500) - /* Microsoft Developer Studio 2008 supports anonymous structs, but - * complains by default. */ -#define __CL_HAS_ANON_STRUCT__ 1 -#define __CL_ANON_STRUCT__ - /* Disable warning C4201: nonstandard extension used : nameless - * struct/union */ -#pragma warning( push ) -#pragma warning( disable : 4201 ) -#else -#define __CL_HAS_ANON_STRUCT__ 0 -#define __CL_ANON_STRUCT__ -#endif - -/* Define alignment keys */ -#if defined( __GNUC__ ) - #define CL_ALIGNED(_x) __attribute__ ((aligned(_x))) -#elif defined( _WIN32) && (_MSC_VER) - /* Alignment keys neutered on windows because MSVC can't swallow function arguments with alignment requirements */ - /* http://msdn.microsoft.com/en-us/library/373ak2y1%28VS.71%29.aspx */ - /* #include */ - /* #define CL_ALIGNED(_x) _CRT_ALIGN(_x) */ - #define CL_ALIGNED(_x) -#else - #warning Need to implement some method to align data here - #define CL_ALIGNED(_x) -#endif - -/* Indicate whether .xyzw, .s0123 and .hi.lo are supported */ -#if __CL_HAS_ANON_STRUCT__ - /* .xyzw and .s0123...{f|F} are supported */ - #define CL_HAS_NAMED_VECTOR_FIELDS 1 - /* .hi and .lo are supported */ - #define CL_HAS_HI_LO_VECTOR_FIELDS 1 -#endif - -/* Define cl_vector types */ - -/* ---- cl_charn ---- */ -typedef union -{ - cl_char CL_ALIGNED(2) s[2]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_char x, y; }; - __CL_ANON_STRUCT__ struct{ cl_char s0, s1; }; - __CL_ANON_STRUCT__ struct{ cl_char lo, hi; }; -#endif -#if defined( __CL_CHAR2__) - __cl_char2 v2; -#endif -}cl_char2; - -typedef union -{ - cl_char CL_ALIGNED(4) s[4]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_char x, y, z, w; }; - __CL_ANON_STRUCT__ struct{ cl_char s0, s1, s2, s3; }; - __CL_ANON_STRUCT__ struct{ cl_char2 lo, hi; }; -#endif -#if defined( __CL_CHAR2__) - __cl_char2 v2[2]; -#endif -#if defined( __CL_CHAR4__) - __cl_char4 v4; -#endif -}cl_char4; - -/* cl_char3 is identical in size, alignment and behavior to cl_char4. See section 6.1.5. */ -typedef cl_char4 cl_char3; - -typedef union -{ - cl_char CL_ALIGNED(8) s[8]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_char x, y, z, w; }; - __CL_ANON_STRUCT__ struct{ cl_char s0, s1, s2, s3, s4, s5, s6, s7; }; - __CL_ANON_STRUCT__ struct{ cl_char4 lo, hi; }; -#endif -#if defined( __CL_CHAR2__) - __cl_char2 v2[4]; -#endif -#if defined( __CL_CHAR4__) - __cl_char4 v4[2]; -#endif -#if defined( __CL_CHAR8__ ) - __cl_char8 v8; -#endif -}cl_char8; - -typedef union -{ - cl_char CL_ALIGNED(16) s[16]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_char x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __CL_ANON_STRUCT__ struct{ cl_char s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __CL_ANON_STRUCT__ struct{ cl_char8 lo, hi; }; -#endif -#if defined( __CL_CHAR2__) - __cl_char2 v2[8]; -#endif -#if defined( __CL_CHAR4__) - __cl_char4 v4[4]; -#endif -#if defined( __CL_CHAR8__ ) - __cl_char8 v8[2]; -#endif -#if defined( __CL_CHAR16__ ) - __cl_char16 v16; -#endif -}cl_char16; - - -/* ---- cl_ucharn ---- */ -typedef union -{ - cl_uchar CL_ALIGNED(2) s[2]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_uchar x, y; }; - __CL_ANON_STRUCT__ struct{ cl_uchar s0, s1; }; - __CL_ANON_STRUCT__ struct{ cl_uchar lo, hi; }; -#endif -#if defined( __cl_uchar2__) - __cl_uchar2 v2; -#endif -}cl_uchar2; - -typedef union -{ - cl_uchar CL_ALIGNED(4) s[4]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_uchar x, y, z, w; }; - __CL_ANON_STRUCT__ struct{ cl_uchar s0, s1, s2, s3; }; - __CL_ANON_STRUCT__ struct{ cl_uchar2 lo, hi; }; -#endif -#if defined( __CL_UCHAR2__) - __cl_uchar2 v2[2]; -#endif -#if defined( __CL_UCHAR4__) - __cl_uchar4 v4; -#endif -}cl_uchar4; - -/* cl_uchar3 is identical in size, alignment and behavior to cl_uchar4. See section 6.1.5. */ -typedef cl_uchar4 cl_uchar3; - -typedef union -{ - cl_uchar CL_ALIGNED(8) s[8]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_uchar x, y, z, w; }; - __CL_ANON_STRUCT__ struct{ cl_uchar s0, s1, s2, s3, s4, s5, s6, s7; }; - __CL_ANON_STRUCT__ struct{ cl_uchar4 lo, hi; }; -#endif -#if defined( __CL_UCHAR2__) - __cl_uchar2 v2[4]; -#endif -#if defined( __CL_UCHAR4__) - __cl_uchar4 v4[2]; -#endif -#if defined( __CL_UCHAR8__ ) - __cl_uchar8 v8; -#endif -}cl_uchar8; - -typedef union -{ - cl_uchar CL_ALIGNED(16) s[16]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_uchar x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __CL_ANON_STRUCT__ struct{ cl_uchar s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __CL_ANON_STRUCT__ struct{ cl_uchar8 lo, hi; }; -#endif -#if defined( __CL_UCHAR2__) - __cl_uchar2 v2[8]; -#endif -#if defined( __CL_UCHAR4__) - __cl_uchar4 v4[4]; -#endif -#if defined( __CL_UCHAR8__ ) - __cl_uchar8 v8[2]; -#endif -#if defined( __CL_UCHAR16__ ) - __cl_uchar16 v16; -#endif -}cl_uchar16; - - -/* ---- cl_shortn ---- */ -typedef union -{ - cl_short CL_ALIGNED(4) s[2]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_short x, y; }; - __CL_ANON_STRUCT__ struct{ cl_short s0, s1; }; - __CL_ANON_STRUCT__ struct{ cl_short lo, hi; }; -#endif -#if defined( __CL_SHORT2__) - __cl_short2 v2; -#endif -}cl_short2; - -typedef union -{ - cl_short CL_ALIGNED(8) s[4]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_short x, y, z, w; }; - __CL_ANON_STRUCT__ struct{ cl_short s0, s1, s2, s3; }; - __CL_ANON_STRUCT__ struct{ cl_short2 lo, hi; }; -#endif -#if defined( __CL_SHORT2__) - __cl_short2 v2[2]; -#endif -#if defined( __CL_SHORT4__) - __cl_short4 v4; -#endif -}cl_short4; - -/* cl_short3 is identical in size, alignment and behavior to cl_short4. See section 6.1.5. */ -typedef cl_short4 cl_short3; - -typedef union -{ - cl_short CL_ALIGNED(16) s[8]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_short x, y, z, w; }; - __CL_ANON_STRUCT__ struct{ cl_short s0, s1, s2, s3, s4, s5, s6, s7; }; - __CL_ANON_STRUCT__ struct{ cl_short4 lo, hi; }; -#endif -#if defined( __CL_SHORT2__) - __cl_short2 v2[4]; -#endif -#if defined( __CL_SHORT4__) - __cl_short4 v4[2]; -#endif -#if defined( __CL_SHORT8__ ) - __cl_short8 v8; -#endif -}cl_short8; - -typedef union -{ - cl_short CL_ALIGNED(32) s[16]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_short x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __CL_ANON_STRUCT__ struct{ cl_short s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __CL_ANON_STRUCT__ struct{ cl_short8 lo, hi; }; -#endif -#if defined( __CL_SHORT2__) - __cl_short2 v2[8]; -#endif -#if defined( __CL_SHORT4__) - __cl_short4 v4[4]; -#endif -#if defined( __CL_SHORT8__ ) - __cl_short8 v8[2]; -#endif -#if defined( __CL_SHORT16__ ) - __cl_short16 v16; -#endif -}cl_short16; - - -/* ---- cl_ushortn ---- */ -typedef union -{ - cl_ushort CL_ALIGNED(4) s[2]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_ushort x, y; }; - __CL_ANON_STRUCT__ struct{ cl_ushort s0, s1; }; - __CL_ANON_STRUCT__ struct{ cl_ushort lo, hi; }; -#endif -#if defined( __CL_USHORT2__) - __cl_ushort2 v2; -#endif -}cl_ushort2; - -typedef union -{ - cl_ushort CL_ALIGNED(8) s[4]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_ushort x, y, z, w; }; - __CL_ANON_STRUCT__ struct{ cl_ushort s0, s1, s2, s3; }; - __CL_ANON_STRUCT__ struct{ cl_ushort2 lo, hi; }; -#endif -#if defined( __CL_USHORT2__) - __cl_ushort2 v2[2]; -#endif -#if defined( __CL_USHORT4__) - __cl_ushort4 v4; -#endif -}cl_ushort4; - -/* cl_ushort3 is identical in size, alignment and behavior to cl_ushort4. See section 6.1.5. */ -typedef cl_ushort4 cl_ushort3; - -typedef union -{ - cl_ushort CL_ALIGNED(16) s[8]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_ushort x, y, z, w; }; - __CL_ANON_STRUCT__ struct{ cl_ushort s0, s1, s2, s3, s4, s5, s6, s7; }; - __CL_ANON_STRUCT__ struct{ cl_ushort4 lo, hi; }; -#endif -#if defined( __CL_USHORT2__) - __cl_ushort2 v2[4]; -#endif -#if defined( __CL_USHORT4__) - __cl_ushort4 v4[2]; -#endif -#if defined( __CL_USHORT8__ ) - __cl_ushort8 v8; -#endif -}cl_ushort8; - -typedef union -{ - cl_ushort CL_ALIGNED(32) s[16]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_ushort x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __CL_ANON_STRUCT__ struct{ cl_ushort s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __CL_ANON_STRUCT__ struct{ cl_ushort8 lo, hi; }; -#endif -#if defined( __CL_USHORT2__) - __cl_ushort2 v2[8]; -#endif -#if defined( __CL_USHORT4__) - __cl_ushort4 v4[4]; -#endif -#if defined( __CL_USHORT8__ ) - __cl_ushort8 v8[2]; -#endif -#if defined( __CL_USHORT16__ ) - __cl_ushort16 v16; -#endif -}cl_ushort16; - -/* ---- cl_intn ---- */ -typedef union -{ - cl_int CL_ALIGNED(8) s[2]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_int x, y; }; - __CL_ANON_STRUCT__ struct{ cl_int s0, s1; }; - __CL_ANON_STRUCT__ struct{ cl_int lo, hi; }; -#endif -#if defined( __CL_INT2__) - __cl_int2 v2; -#endif -}cl_int2; - -typedef union -{ - cl_int CL_ALIGNED(16) s[4]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_int x, y, z, w; }; - __CL_ANON_STRUCT__ struct{ cl_int s0, s1, s2, s3; }; - __CL_ANON_STRUCT__ struct{ cl_int2 lo, hi; }; -#endif -#if defined( __CL_INT2__) - __cl_int2 v2[2]; -#endif -#if defined( __CL_INT4__) - __cl_int4 v4; -#endif -}cl_int4; - -/* cl_int3 is identical in size, alignment and behavior to cl_int4. See section 6.1.5. */ -typedef cl_int4 cl_int3; - -typedef union -{ - cl_int CL_ALIGNED(32) s[8]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_int x, y, z, w; }; - __CL_ANON_STRUCT__ struct{ cl_int s0, s1, s2, s3, s4, s5, s6, s7; }; - __CL_ANON_STRUCT__ struct{ cl_int4 lo, hi; }; -#endif -#if defined( __CL_INT2__) - __cl_int2 v2[4]; -#endif -#if defined( __CL_INT4__) - __cl_int4 v4[2]; -#endif -#if defined( __CL_INT8__ ) - __cl_int8 v8; -#endif -}cl_int8; - -typedef union -{ - cl_int CL_ALIGNED(64) s[16]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_int x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __CL_ANON_STRUCT__ struct{ cl_int s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __CL_ANON_STRUCT__ struct{ cl_int8 lo, hi; }; -#endif -#if defined( __CL_INT2__) - __cl_int2 v2[8]; -#endif -#if defined( __CL_INT4__) - __cl_int4 v4[4]; -#endif -#if defined( __CL_INT8__ ) - __cl_int8 v8[2]; -#endif -#if defined( __CL_INT16__ ) - __cl_int16 v16; -#endif -}cl_int16; - - -/* ---- cl_uintn ---- */ -typedef union -{ - cl_uint CL_ALIGNED(8) s[2]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_uint x, y; }; - __CL_ANON_STRUCT__ struct{ cl_uint s0, s1; }; - __CL_ANON_STRUCT__ struct{ cl_uint lo, hi; }; -#endif -#if defined( __CL_UINT2__) - __cl_uint2 v2; -#endif -}cl_uint2; - -typedef union -{ - cl_uint CL_ALIGNED(16) s[4]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_uint x, y, z, w; }; - __CL_ANON_STRUCT__ struct{ cl_uint s0, s1, s2, s3; }; - __CL_ANON_STRUCT__ struct{ cl_uint2 lo, hi; }; -#endif -#if defined( __CL_UINT2__) - __cl_uint2 v2[2]; -#endif -#if defined( __CL_UINT4__) - __cl_uint4 v4; -#endif -}cl_uint4; - -/* cl_uint3 is identical in size, alignment and behavior to cl_uint4. See section 6.1.5. */ -typedef cl_uint4 cl_uint3; - -typedef union -{ - cl_uint CL_ALIGNED(32) s[8]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_uint x, y, z, w; }; - __CL_ANON_STRUCT__ struct{ cl_uint s0, s1, s2, s3, s4, s5, s6, s7; }; - __CL_ANON_STRUCT__ struct{ cl_uint4 lo, hi; }; -#endif -#if defined( __CL_UINT2__) - __cl_uint2 v2[4]; -#endif -#if defined( __CL_UINT4__) - __cl_uint4 v4[2]; -#endif -#if defined( __CL_UINT8__ ) - __cl_uint8 v8; -#endif -}cl_uint8; - -typedef union -{ - cl_uint CL_ALIGNED(64) s[16]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_uint x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __CL_ANON_STRUCT__ struct{ cl_uint s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __CL_ANON_STRUCT__ struct{ cl_uint8 lo, hi; }; -#endif -#if defined( __CL_UINT2__) - __cl_uint2 v2[8]; -#endif -#if defined( __CL_UINT4__) - __cl_uint4 v4[4]; -#endif -#if defined( __CL_UINT8__ ) - __cl_uint8 v8[2]; -#endif -#if defined( __CL_UINT16__ ) - __cl_uint16 v16; -#endif -}cl_uint16; - -/* ---- cl_longn ---- */ -typedef union -{ - cl_long CL_ALIGNED(16) s[2]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_long x, y; }; - __CL_ANON_STRUCT__ struct{ cl_long s0, s1; }; - __CL_ANON_STRUCT__ struct{ cl_long lo, hi; }; -#endif -#if defined( __CL_LONG2__) - __cl_long2 v2; -#endif -}cl_long2; - -typedef union -{ - cl_long CL_ALIGNED(32) s[4]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_long x, y, z, w; }; - __CL_ANON_STRUCT__ struct{ cl_long s0, s1, s2, s3; }; - __CL_ANON_STRUCT__ struct{ cl_long2 lo, hi; }; -#endif -#if defined( __CL_LONG2__) - __cl_long2 v2[2]; -#endif -#if defined( __CL_LONG4__) - __cl_long4 v4; -#endif -}cl_long4; - -/* cl_long3 is identical in size, alignment and behavior to cl_long4. See section 6.1.5. */ -typedef cl_long4 cl_long3; - -typedef union -{ - cl_long CL_ALIGNED(64) s[8]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_long x, y, z, w; }; - __CL_ANON_STRUCT__ struct{ cl_long s0, s1, s2, s3, s4, s5, s6, s7; }; - __CL_ANON_STRUCT__ struct{ cl_long4 lo, hi; }; -#endif -#if defined( __CL_LONG2__) - __cl_long2 v2[4]; -#endif -#if defined( __CL_LONG4__) - __cl_long4 v4[2]; -#endif -#if defined( __CL_LONG8__ ) - __cl_long8 v8; -#endif -}cl_long8; - -typedef union -{ - cl_long CL_ALIGNED(128) s[16]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_long x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __CL_ANON_STRUCT__ struct{ cl_long s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __CL_ANON_STRUCT__ struct{ cl_long8 lo, hi; }; -#endif -#if defined( __CL_LONG2__) - __cl_long2 v2[8]; -#endif -#if defined( __CL_LONG4__) - __cl_long4 v4[4]; -#endif -#if defined( __CL_LONG8__ ) - __cl_long8 v8[2]; -#endif -#if defined( __CL_LONG16__ ) - __cl_long16 v16; -#endif -}cl_long16; - - -/* ---- cl_ulongn ---- */ -typedef union -{ - cl_ulong CL_ALIGNED(16) s[2]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_ulong x, y; }; - __CL_ANON_STRUCT__ struct{ cl_ulong s0, s1; }; - __CL_ANON_STRUCT__ struct{ cl_ulong lo, hi; }; -#endif -#if defined( __CL_ULONG2__) - __cl_ulong2 v2; -#endif -}cl_ulong2; - -typedef union -{ - cl_ulong CL_ALIGNED(32) s[4]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_ulong x, y, z, w; }; - __CL_ANON_STRUCT__ struct{ cl_ulong s0, s1, s2, s3; }; - __CL_ANON_STRUCT__ struct{ cl_ulong2 lo, hi; }; -#endif -#if defined( __CL_ULONG2__) - __cl_ulong2 v2[2]; -#endif -#if defined( __CL_ULONG4__) - __cl_ulong4 v4; -#endif -}cl_ulong4; - -/* cl_ulong3 is identical in size, alignment and behavior to cl_ulong4. See section 6.1.5. */ -typedef cl_ulong4 cl_ulong3; - -typedef union -{ - cl_ulong CL_ALIGNED(64) s[8]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_ulong x, y, z, w; }; - __CL_ANON_STRUCT__ struct{ cl_ulong s0, s1, s2, s3, s4, s5, s6, s7; }; - __CL_ANON_STRUCT__ struct{ cl_ulong4 lo, hi; }; -#endif -#if defined( __CL_ULONG2__) - __cl_ulong2 v2[4]; -#endif -#if defined( __CL_ULONG4__) - __cl_ulong4 v4[2]; -#endif -#if defined( __CL_ULONG8__ ) - __cl_ulong8 v8; -#endif -}cl_ulong8; - -typedef union -{ - cl_ulong CL_ALIGNED(128) s[16]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_ulong x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __CL_ANON_STRUCT__ struct{ cl_ulong s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __CL_ANON_STRUCT__ struct{ cl_ulong8 lo, hi; }; -#endif -#if defined( __CL_ULONG2__) - __cl_ulong2 v2[8]; -#endif -#if defined( __CL_ULONG4__) - __cl_ulong4 v4[4]; -#endif -#if defined( __CL_ULONG8__ ) - __cl_ulong8 v8[2]; -#endif -#if defined( __CL_ULONG16__ ) - __cl_ulong16 v16; -#endif -}cl_ulong16; - - -/* --- cl_floatn ---- */ - -typedef union -{ - cl_float CL_ALIGNED(8) s[2]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_float x, y; }; - __CL_ANON_STRUCT__ struct{ cl_float s0, s1; }; - __CL_ANON_STRUCT__ struct{ cl_float lo, hi; }; -#endif -#if defined( __CL_FLOAT2__) - __cl_float2 v2; -#endif -}cl_float2; - -typedef union -{ - cl_float CL_ALIGNED(16) s[4]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_float x, y, z, w; }; - __CL_ANON_STRUCT__ struct{ cl_float s0, s1, s2, s3; }; - __CL_ANON_STRUCT__ struct{ cl_float2 lo, hi; }; -#endif -#if defined( __CL_FLOAT2__) - __cl_float2 v2[2]; -#endif -#if defined( __CL_FLOAT4__) - __cl_float4 v4; -#endif -}cl_float4; - -/* cl_float3 is identical in size, alignment and behavior to cl_float4. See section 6.1.5. */ -typedef cl_float4 cl_float3; - -typedef union -{ - cl_float CL_ALIGNED(32) s[8]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_float x, y, z, w; }; - __CL_ANON_STRUCT__ struct{ cl_float s0, s1, s2, s3, s4, s5, s6, s7; }; - __CL_ANON_STRUCT__ struct{ cl_float4 lo, hi; }; -#endif -#if defined( __CL_FLOAT2__) - __cl_float2 v2[4]; -#endif -#if defined( __CL_FLOAT4__) - __cl_float4 v4[2]; -#endif -#if defined( __CL_FLOAT8__ ) - __cl_float8 v8; -#endif -}cl_float8; - -typedef union -{ - cl_float CL_ALIGNED(64) s[16]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_float x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __CL_ANON_STRUCT__ struct{ cl_float s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __CL_ANON_STRUCT__ struct{ cl_float8 lo, hi; }; -#endif -#if defined( __CL_FLOAT2__) - __cl_float2 v2[8]; -#endif -#if defined( __CL_FLOAT4__) - __cl_float4 v4[4]; -#endif -#if defined( __CL_FLOAT8__ ) - __cl_float8 v8[2]; -#endif -#if defined( __CL_FLOAT16__ ) - __cl_float16 v16; -#endif -}cl_float16; - -/* --- cl_doublen ---- */ - -typedef union -{ - cl_double CL_ALIGNED(16) s[2]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_double x, y; }; - __CL_ANON_STRUCT__ struct{ cl_double s0, s1; }; - __CL_ANON_STRUCT__ struct{ cl_double lo, hi; }; -#endif -#if defined( __CL_DOUBLE2__) - __cl_double2 v2; -#endif -}cl_double2; - -typedef union -{ - cl_double CL_ALIGNED(32) s[4]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_double x, y, z, w; }; - __CL_ANON_STRUCT__ struct{ cl_double s0, s1, s2, s3; }; - __CL_ANON_STRUCT__ struct{ cl_double2 lo, hi; }; -#endif -#if defined( __CL_DOUBLE2__) - __cl_double2 v2[2]; -#endif -#if defined( __CL_DOUBLE4__) - __cl_double4 v4; -#endif -}cl_double4; - -/* cl_double3 is identical in size, alignment and behavior to cl_double4. See section 6.1.5. */ -typedef cl_double4 cl_double3; - -typedef union -{ - cl_double CL_ALIGNED(64) s[8]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_double x, y, z, w; }; - __CL_ANON_STRUCT__ struct{ cl_double s0, s1, s2, s3, s4, s5, s6, s7; }; - __CL_ANON_STRUCT__ struct{ cl_double4 lo, hi; }; -#endif -#if defined( __CL_DOUBLE2__) - __cl_double2 v2[4]; -#endif -#if defined( __CL_DOUBLE4__) - __cl_double4 v4[2]; -#endif -#if defined( __CL_DOUBLE8__ ) - __cl_double8 v8; -#endif -}cl_double8; - -typedef union -{ - cl_double CL_ALIGNED(128) s[16]; -#if __CL_HAS_ANON_STRUCT__ - __CL_ANON_STRUCT__ struct{ cl_double x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; - __CL_ANON_STRUCT__ struct{ cl_double s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; - __CL_ANON_STRUCT__ struct{ cl_double8 lo, hi; }; -#endif -#if defined( __CL_DOUBLE2__) - __cl_double2 v2[8]; -#endif -#if defined( __CL_DOUBLE4__) - __cl_double4 v4[4]; -#endif -#if defined( __CL_DOUBLE8__ ) - __cl_double8 v8[2]; -#endif -#if defined( __CL_DOUBLE16__ ) - __cl_double16 v16; -#endif -}cl_double16; - -/* Macro to facilitate debugging - * Usage: - * Place CL_PROGRAM_STRING_DEBUG_INFO on the line before the first line of your source. - * The first line ends with: CL_PROGRAM_STRING_DEBUG_INFO \" - * Each line thereafter of OpenCL C source must end with: \n\ - * The last line ends in "; - * - * Example: - * - * const char *my_program = CL_PROGRAM_STRING_DEBUG_INFO "\ - * kernel void foo( int a, float * b ) \n\ - * { \n\ - * // my comment \n\ - * *b[ get_global_id(0)] = a; \n\ - * } \n\ - * "; - * - * This should correctly set up the line, (column) and file information for your source - * string so you can do source level debugging. - */ -#define __CL_STRINGIFY( _x ) # _x -#define _CL_STRINGIFY( _x ) __CL_STRINGIFY( _x ) -#define CL_PROGRAM_STRING_DEBUG_INFO "#line " _CL_STRINGIFY(__LINE__) " \"" __FILE__ "\" \n\n" - -#ifdef __cplusplus -} -#endif - -#undef __CL_HAS_ANON_STRUCT__ -#undef __CL_ANON_STRUCT__ -#if defined( _WIN32) && (_MSC_VER >= 1500) -#pragma warning( pop ) -#endif - -#endif /* __CL_PLATFORM_H */ diff --git a/third_party/opencl/include/CL/opencl.h b/third_party/opencl/include/CL/opencl.h deleted file mode 100644 index 9855cd75e7..0000000000 --- a/third_party/opencl/include/CL/opencl.h +++ /dev/null @@ -1,59 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008-2015 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and/or associated documentation files (the - * "Materials"), to deal in the Materials without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Materials, and to - * permit persons to whom the Materials are 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 Materials. - * - * MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS - * KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS - * SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT - * https://www.khronos.org/registry/ - * - * THE MATERIALS ARE 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 - * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. - ******************************************************************************/ - -/* $Revision: 11708 $ on $Date: 2010-06-13 23:36:24 -0700 (Sun, 13 Jun 2010) $ */ - -#ifndef __OPENCL_H -#define __OPENCL_H - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef __APPLE__ - -#include -#include -#include -#include - -#else - -#include -#include -#include -#include - -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* __OPENCL_H */ - diff --git a/third_party/qrcode/QrCode.cc b/third_party/qrcode/QrCode.cc deleted file mode 100644 index b9de86215e..0000000000 --- a/third_party/qrcode/QrCode.cc +++ /dev/null @@ -1,862 +0,0 @@ -/* - * QR Code generator library (C++) - * - * Copyright (c) Project Nayuki. (MIT License) - * https://www.nayuki.io/page/qr-code-generator-library - * - * 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. - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include "QrCode.hpp" - -using std::int8_t; -using std::uint8_t; -using std::size_t; -using std::vector; - - -namespace qrcodegen { - -QrSegment::Mode::Mode(int mode, int cc0, int cc1, int cc2) : - modeBits(mode) { - numBitsCharCount[0] = cc0; - numBitsCharCount[1] = cc1; - numBitsCharCount[2] = cc2; -} - - -int QrSegment::Mode::getModeBits() const { - return modeBits; -} - - -int QrSegment::Mode::numCharCountBits(int ver) const { - return numBitsCharCount[(ver + 7) / 17]; -} - - -const QrSegment::Mode QrSegment::Mode::NUMERIC (0x1, 10, 12, 14); -const QrSegment::Mode QrSegment::Mode::ALPHANUMERIC(0x2, 9, 11, 13); -const QrSegment::Mode QrSegment::Mode::BYTE (0x4, 8, 16, 16); -const QrSegment::Mode QrSegment::Mode::KANJI (0x8, 8, 10, 12); -const QrSegment::Mode QrSegment::Mode::ECI (0x7, 0, 0, 0); - - -QrSegment QrSegment::makeBytes(const vector &data) { - if (data.size() > static_cast(INT_MAX)) - throw std::length_error("Data too long"); - BitBuffer bb; - for (uint8_t b : data) - bb.appendBits(b, 8); - return QrSegment(Mode::BYTE, static_cast(data.size()), std::move(bb)); -} - - -QrSegment QrSegment::makeNumeric(const char *digits) { - BitBuffer bb; - int accumData = 0; - int accumCount = 0; - int charCount = 0; - for (; *digits != '\0'; digits++, charCount++) { - char c = *digits; - if (c < '0' || c > '9') - throw std::domain_error("String contains non-numeric characters"); - accumData = accumData * 10 + (c - '0'); - accumCount++; - if (accumCount == 3) { - bb.appendBits(static_cast(accumData), 10); - accumData = 0; - accumCount = 0; - } - } - if (accumCount > 0) // 1 or 2 digits remaining - bb.appendBits(static_cast(accumData), accumCount * 3 + 1); - return QrSegment(Mode::NUMERIC, charCount, std::move(bb)); -} - - -QrSegment QrSegment::makeAlphanumeric(const char *text) { - BitBuffer bb; - int accumData = 0; - int accumCount = 0; - int charCount = 0; - for (; *text != '\0'; text++, charCount++) { - const char *temp = std::strchr(ALPHANUMERIC_CHARSET, *text); - if (temp == nullptr) - throw std::domain_error("String contains unencodable characters in alphanumeric mode"); - accumData = accumData * 45 + static_cast(temp - ALPHANUMERIC_CHARSET); - accumCount++; - if (accumCount == 2) { - bb.appendBits(static_cast(accumData), 11); - accumData = 0; - accumCount = 0; - } - } - if (accumCount > 0) // 1 character remaining - bb.appendBits(static_cast(accumData), 6); - return QrSegment(Mode::ALPHANUMERIC, charCount, std::move(bb)); -} - - -vector QrSegment::makeSegments(const char *text) { - // Select the most efficient segment encoding automatically - vector result; - if (*text == '\0'); // Leave result empty - else if (isNumeric(text)) - result.push_back(makeNumeric(text)); - else if (isAlphanumeric(text)) - result.push_back(makeAlphanumeric(text)); - else { - vector bytes; - for (; *text != '\0'; text++) - bytes.push_back(static_cast(*text)); - result.push_back(makeBytes(bytes)); - } - return result; -} - - -QrSegment QrSegment::makeEci(long assignVal) { - BitBuffer bb; - if (assignVal < 0) - throw std::domain_error("ECI assignment value out of range"); - else if (assignVal < (1 << 7)) - bb.appendBits(static_cast(assignVal), 8); - else if (assignVal < (1 << 14)) { - bb.appendBits(2, 2); - bb.appendBits(static_cast(assignVal), 14); - } else if (assignVal < 1000000L) { - bb.appendBits(6, 3); - bb.appendBits(static_cast(assignVal), 21); - } else - throw std::domain_error("ECI assignment value out of range"); - return QrSegment(Mode::ECI, 0, std::move(bb)); -} - - -QrSegment::QrSegment(Mode md, int numCh, const std::vector &dt) : - mode(md), - numChars(numCh), - data(dt) { - if (numCh < 0) - throw std::domain_error("Invalid value"); -} - - -QrSegment::QrSegment(Mode md, int numCh, std::vector &&dt) : - mode(md), - numChars(numCh), - data(std::move(dt)) { - if (numCh < 0) - throw std::domain_error("Invalid value"); -} - - -int QrSegment::getTotalBits(const vector &segs, int version) { - int result = 0; - for (const QrSegment &seg : segs) { - int ccbits = seg.mode.numCharCountBits(version); - if (seg.numChars >= (1L << ccbits)) - return -1; // The segment's length doesn't fit the field's bit width - if (4 + ccbits > INT_MAX - result) - return -1; // The sum will overflow an int type - result += 4 + ccbits; - if (seg.data.size() > static_cast(INT_MAX - result)) - return -1; // The sum will overflow an int type - result += static_cast(seg.data.size()); - } - return result; -} - - -bool QrSegment::isAlphanumeric(const char *text) { - for (; *text != '\0'; text++) { - if (std::strchr(ALPHANUMERIC_CHARSET, *text) == nullptr) - return false; - } - return true; -} - - -bool QrSegment::isNumeric(const char *text) { - for (; *text != '\0'; text++) { - char c = *text; - if (c < '0' || c > '9') - return false; - } - return true; -} - - -QrSegment::Mode QrSegment::getMode() const { - return mode; -} - - -int QrSegment::getNumChars() const { - return numChars; -} - - -const std::vector &QrSegment::getData() const { - return data; -} - - -const char *QrSegment::ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"; - - - -int QrCode::getFormatBits(Ecc ecl) { - switch (ecl) { - case Ecc::LOW : return 1; - case Ecc::MEDIUM : return 0; - case Ecc::QUARTILE: return 3; - case Ecc::HIGH : return 2; - default: throw std::logic_error("Assertion error"); - } -} - - -QrCode QrCode::encodeText(const char *text, Ecc ecl) { - vector segs = QrSegment::makeSegments(text); - return encodeSegments(segs, ecl); -} - - -QrCode QrCode::encodeBinary(const vector &data, Ecc ecl) { - vector segs{QrSegment::makeBytes(data)}; - return encodeSegments(segs, ecl); -} - - -QrCode QrCode::encodeSegments(const vector &segs, Ecc ecl, - int minVersion, int maxVersion, int mask, bool boostEcl) { - if (!(MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= MAX_VERSION) || mask < -1 || mask > 7) - throw std::invalid_argument("Invalid value"); - - // Find the minimal version number to use - int version, dataUsedBits; - for (version = minVersion; ; version++) { - int dataCapacityBits = getNumDataCodewords(version, ecl) * 8; // Number of data bits available - dataUsedBits = QrSegment::getTotalBits(segs, version); - if (dataUsedBits != -1 && dataUsedBits <= dataCapacityBits) - break; // This version number is found to be suitable - if (version >= maxVersion) { // All versions in the range could not fit the given data - std::ostringstream sb; - if (dataUsedBits == -1) - sb << "Segment too long"; - else { - sb << "Data length = " << dataUsedBits << " bits, "; - sb << "Max capacity = " << dataCapacityBits << " bits"; - } - throw data_too_long(sb.str()); - } - } - if (dataUsedBits == -1) - throw std::logic_error("Assertion error"); - - // Increase the error correction level while the data still fits in the current version number - for (Ecc newEcl : vector{Ecc::MEDIUM, Ecc::QUARTILE, Ecc::HIGH}) { // From low to high - if (boostEcl && dataUsedBits <= getNumDataCodewords(version, newEcl) * 8) - ecl = newEcl; - } - - // Concatenate all segments to create the data bit string - BitBuffer bb; - for (const QrSegment &seg : segs) { - bb.appendBits(static_cast(seg.getMode().getModeBits()), 4); - bb.appendBits(static_cast(seg.getNumChars()), seg.getMode().numCharCountBits(version)); - bb.insert(bb.end(), seg.getData().begin(), seg.getData().end()); - } - if (bb.size() != static_cast(dataUsedBits)) - throw std::logic_error("Assertion error"); - - // Add terminator and pad up to a byte if applicable - size_t dataCapacityBits = static_cast(getNumDataCodewords(version, ecl)) * 8; - if (bb.size() > dataCapacityBits) - throw std::logic_error("Assertion error"); - bb.appendBits(0, std::min(4, static_cast(dataCapacityBits - bb.size()))); - bb.appendBits(0, (8 - static_cast(bb.size() % 8)) % 8); - if (bb.size() % 8 != 0) - throw std::logic_error("Assertion error"); - - // Pad with alternating bytes until data capacity is reached - for (uint8_t padByte = 0xEC; bb.size() < dataCapacityBits; padByte ^= 0xEC ^ 0x11) - bb.appendBits(padByte, 8); - - // Pack bits into bytes in big endian - vector dataCodewords(bb.size() / 8); - for (size_t i = 0; i < bb.size(); i++) - dataCodewords[i >> 3] |= (bb.at(i) ? 1 : 0) << (7 - (i & 7)); - - // Create the QR Code object - return QrCode(version, ecl, dataCodewords, mask); -} - - -QrCode::QrCode(int ver, Ecc ecl, const vector &dataCodewords, int msk) : - // Initialize fields and check arguments - version(ver), - errorCorrectionLevel(ecl) { - if (ver < MIN_VERSION || ver > MAX_VERSION) - throw std::domain_error("Version value out of range"); - if (msk < -1 || msk > 7) - throw std::domain_error("Mask value out of range"); - size = ver * 4 + 17; - size_t sz = static_cast(size); - modules = vector >(sz, vector(sz)); // Initially all white - isFunction = vector >(sz, vector(sz)); - - // Compute ECC, draw modules - drawFunctionPatterns(); - const vector allCodewords = addEccAndInterleave(dataCodewords); - drawCodewords(allCodewords); - - // Do masking - if (msk == -1) { // Automatically choose best mask - long minPenalty = LONG_MAX; - for (int i = 0; i < 8; i++) { - applyMask(i); - drawFormatBits(i); - long penalty = getPenaltyScore(); - if (penalty < minPenalty) { - msk = i; - minPenalty = penalty; - } - applyMask(i); // Undoes the mask due to XOR - } - } - if (msk < 0 || msk > 7) - throw std::logic_error("Assertion error"); - this->mask = msk; - applyMask(msk); // Apply the final choice of mask - drawFormatBits(msk); // Overwrite old format bits - - isFunction.clear(); - isFunction.shrink_to_fit(); -} - - -int QrCode::getVersion() const { - return version; -} - - -int QrCode::getSize() const { - return size; -} - - -QrCode::Ecc QrCode::getErrorCorrectionLevel() const { - return errorCorrectionLevel; -} - - -int QrCode::getMask() const { - return mask; -} - - -bool QrCode::getModule(int x, int y) const { - return 0 <= x && x < size && 0 <= y && y < size && module(x, y); -} - - -std::string QrCode::toSvgString(int border) const { - if (border < 0) - throw std::domain_error("Border must be non-negative"); - if (border > INT_MAX / 2 || border * 2 > INT_MAX - size) - throw std::overflow_error("Border too large"); - - std::ostringstream sb; - sb << "\n"; - sb << "\n"; - sb << "\n"; - sb << "\t\n"; - sb << "\t\n"; - sb << "\n"; - return sb.str(); -} - - -void QrCode::drawFunctionPatterns() { - // Draw horizontal and vertical timing patterns - for (int i = 0; i < size; i++) { - setFunctionModule(6, i, i % 2 == 0); - setFunctionModule(i, 6, i % 2 == 0); - } - - // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules) - drawFinderPattern(3, 3); - drawFinderPattern(size - 4, 3); - drawFinderPattern(3, size - 4); - - // Draw numerous alignment patterns - const vector alignPatPos = getAlignmentPatternPositions(); - size_t numAlign = alignPatPos.size(); - for (size_t i = 0; i < numAlign; i++) { - for (size_t j = 0; j < numAlign; j++) { - // Don't draw on the three finder corners - if (!((i == 0 && j == 0) || (i == 0 && j == numAlign - 1) || (i == numAlign - 1 && j == 0))) - drawAlignmentPattern(alignPatPos.at(i), alignPatPos.at(j)); - } - } - - // Draw configuration data - drawFormatBits(0); // Dummy mask value; overwritten later in the constructor - drawVersion(); -} - - -void QrCode::drawFormatBits(int msk) { - // Calculate error correction code and pack bits - int data = getFormatBits(errorCorrectionLevel) << 3 | msk; // errCorrLvl is uint2, msk is uint3 - int rem = data; - for (int i = 0; i < 10; i++) - rem = (rem << 1) ^ ((rem >> 9) * 0x537); - int bits = (data << 10 | rem) ^ 0x5412; // uint15 - if (bits >> 15 != 0) - throw std::logic_error("Assertion error"); - - // Draw first copy - for (int i = 0; i <= 5; i++) - setFunctionModule(8, i, getBit(bits, i)); - setFunctionModule(8, 7, getBit(bits, 6)); - setFunctionModule(8, 8, getBit(bits, 7)); - setFunctionModule(7, 8, getBit(bits, 8)); - for (int i = 9; i < 15; i++) - setFunctionModule(14 - i, 8, getBit(bits, i)); - - // Draw second copy - for (int i = 0; i < 8; i++) - setFunctionModule(size - 1 - i, 8, getBit(bits, i)); - for (int i = 8; i < 15; i++) - setFunctionModule(8, size - 15 + i, getBit(bits, i)); - setFunctionModule(8, size - 8, true); // Always black -} - - -void QrCode::drawVersion() { - if (version < 7) - return; - - // Calculate error correction code and pack bits - int rem = version; // version is uint6, in the range [7, 40] - for (int i = 0; i < 12; i++) - rem = (rem << 1) ^ ((rem >> 11) * 0x1F25); - long bits = static_cast(version) << 12 | rem; // uint18 - if (bits >> 18 != 0) - throw std::logic_error("Assertion error"); - - // Draw two copies - for (int i = 0; i < 18; i++) { - bool bit = getBit(bits, i); - int a = size - 11 + i % 3; - int b = i / 3; - setFunctionModule(a, b, bit); - setFunctionModule(b, a, bit); - } -} - - -void QrCode::drawFinderPattern(int x, int y) { - for (int dy = -4; dy <= 4; dy++) { - for (int dx = -4; dx <= 4; dx++) { - int dist = std::max(std::abs(dx), std::abs(dy)); // Chebyshev/infinity norm - int xx = x + dx, yy = y + dy; - if (0 <= xx && xx < size && 0 <= yy && yy < size) - setFunctionModule(xx, yy, dist != 2 && dist != 4); - } - } -} - - -void QrCode::drawAlignmentPattern(int x, int y) { - for (int dy = -2; dy <= 2; dy++) { - for (int dx = -2; dx <= 2; dx++) - setFunctionModule(x + dx, y + dy, std::max(std::abs(dx), std::abs(dy)) != 1); - } -} - - -void QrCode::setFunctionModule(int x, int y, bool isBlack) { - size_t ux = static_cast(x); - size_t uy = static_cast(y); - modules .at(uy).at(ux) = isBlack; - isFunction.at(uy).at(ux) = true; -} - - -bool QrCode::module(int x, int y) const { - return modules.at(static_cast(y)).at(static_cast(x)); -} - - -vector QrCode::addEccAndInterleave(const vector &data) const { - if (data.size() != static_cast(getNumDataCodewords(version, errorCorrectionLevel))) - throw std::invalid_argument("Invalid argument"); - - // Calculate parameter numbers - int numBlocks = NUM_ERROR_CORRECTION_BLOCKS[static_cast(errorCorrectionLevel)][version]; - int blockEccLen = ECC_CODEWORDS_PER_BLOCK [static_cast(errorCorrectionLevel)][version]; - int rawCodewords = getNumRawDataModules(version) / 8; - int numShortBlocks = numBlocks - rawCodewords % numBlocks; - int shortBlockLen = rawCodewords / numBlocks; - - // Split data into blocks and append ECC to each block - vector > blocks; - const vector rsDiv = reedSolomonComputeDivisor(blockEccLen); - for (int i = 0, k = 0; i < numBlocks; i++) { - vector dat(data.cbegin() + k, data.cbegin() + (k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1))); - k += static_cast(dat.size()); - const vector ecc = reedSolomonComputeRemainder(dat, rsDiv); - if (i < numShortBlocks) - dat.push_back(0); - dat.insert(dat.end(), ecc.cbegin(), ecc.cend()); - blocks.push_back(std::move(dat)); - } - - // Interleave (not concatenate) the bytes from every block into a single sequence - vector result; - for (size_t i = 0; i < blocks.at(0).size(); i++) { - for (size_t j = 0; j < blocks.size(); j++) { - // Skip the padding byte in short blocks - if (i != static_cast(shortBlockLen - blockEccLen) || j >= static_cast(numShortBlocks)) - result.push_back(blocks.at(j).at(i)); - } - } - if (result.size() != static_cast(rawCodewords)) - throw std::logic_error("Assertion error"); - return result; -} - - -void QrCode::drawCodewords(const vector &data) { - if (data.size() != static_cast(getNumRawDataModules(version) / 8)) - throw std::invalid_argument("Invalid argument"); - - size_t i = 0; // Bit index into the data - // Do the funny zigzag scan - for (int right = size - 1; right >= 1; right -= 2) { // Index of right column in each column pair - if (right == 6) - right = 5; - for (int vert = 0; vert < size; vert++) { // Vertical counter - for (int j = 0; j < 2; j++) { - size_t x = static_cast(right - j); // Actual x coordinate - bool upward = ((right + 1) & 2) == 0; - size_t y = static_cast(upward ? size - 1 - vert : vert); // Actual y coordinate - if (!isFunction.at(y).at(x) && i < data.size() * 8) { - modules.at(y).at(x) = getBit(data.at(i >> 3), 7 - static_cast(i & 7)); - i++; - } - // If this QR Code has any remainder bits (0 to 7), they were assigned as - // 0/false/white by the constructor and are left unchanged by this method - } - } - } - if (i != data.size() * 8) - throw std::logic_error("Assertion error"); -} - - -void QrCode::applyMask(int msk) { - if (msk < 0 || msk > 7) - throw std::domain_error("Mask value out of range"); - size_t sz = static_cast(size); - for (size_t y = 0; y < sz; y++) { - for (size_t x = 0; x < sz; x++) { - bool invert; - switch (msk) { - case 0: invert = (x + y) % 2 == 0; break; - case 1: invert = y % 2 == 0; break; - case 2: invert = x % 3 == 0; break; - case 3: invert = (x + y) % 3 == 0; break; - case 4: invert = (x / 3 + y / 2) % 2 == 0; break; - case 5: invert = x * y % 2 + x * y % 3 == 0; break; - case 6: invert = (x * y % 2 + x * y % 3) % 2 == 0; break; - case 7: invert = ((x + y) % 2 + x * y % 3) % 2 == 0; break; - default: throw std::logic_error("Assertion error"); - } - modules.at(y).at(x) = modules.at(y).at(x) ^ (invert & !isFunction.at(y).at(x)); - } - } -} - - -long QrCode::getPenaltyScore() const { - long result = 0; - - // Adjacent modules in row having same color, and finder-like patterns - for (int y = 0; y < size; y++) { - bool runColor = false; - int runX = 0; - std::array runHistory = {}; - for (int x = 0; x < size; x++) { - if (module(x, y) == runColor) { - runX++; - if (runX == 5) - result += PENALTY_N1; - else if (runX > 5) - result++; - } else { - finderPenaltyAddHistory(runX, runHistory); - if (!runColor) - result += finderPenaltyCountPatterns(runHistory) * PENALTY_N3; - runColor = module(x, y); - runX = 1; - } - } - result += finderPenaltyTerminateAndCount(runColor, runX, runHistory) * PENALTY_N3; - } - // Adjacent modules in column having same color, and finder-like patterns - for (int x = 0; x < size; x++) { - bool runColor = false; - int runY = 0; - std::array runHistory = {}; - for (int y = 0; y < size; y++) { - if (module(x, y) == runColor) { - runY++; - if (runY == 5) - result += PENALTY_N1; - else if (runY > 5) - result++; - } else { - finderPenaltyAddHistory(runY, runHistory); - if (!runColor) - result += finderPenaltyCountPatterns(runHistory) * PENALTY_N3; - runColor = module(x, y); - runY = 1; - } - } - result += finderPenaltyTerminateAndCount(runColor, runY, runHistory) * PENALTY_N3; - } - - // 2*2 blocks of modules having same color - for (int y = 0; y < size - 1; y++) { - for (int x = 0; x < size - 1; x++) { - bool color = module(x, y); - if ( color == module(x + 1, y) && - color == module(x, y + 1) && - color == module(x + 1, y + 1)) - result += PENALTY_N2; - } - } - - // Balance of black and white modules - int black = 0; - for (const vector &row : modules) { - for (bool color : row) { - if (color) - black++; - } - } - int total = size * size; // Note that size is odd, so black/total != 1/2 - // Compute the smallest integer k >= 0 such that (45-5k)% <= black/total <= (55+5k)% - int k = static_cast((std::abs(black * 20L - total * 10L) + total - 1) / total) - 1; - result += k * PENALTY_N4; - return result; -} - - -vector QrCode::getAlignmentPatternPositions() const { - if (version == 1) - return vector(); - else { - int numAlign = version / 7 + 2; - int step = (version == 32) ? 26 : - (version*4 + numAlign*2 + 1) / (numAlign*2 - 2) * 2; - vector result; - for (int i = 0, pos = size - 7; i < numAlign - 1; i++, pos -= step) - result.insert(result.begin(), pos); - result.insert(result.begin(), 6); - return result; - } -} - - -int QrCode::getNumRawDataModules(int ver) { - if (ver < MIN_VERSION || ver > MAX_VERSION) - throw std::domain_error("Version number out of range"); - int result = (16 * ver + 128) * ver + 64; - if (ver >= 2) { - int numAlign = ver / 7 + 2; - result -= (25 * numAlign - 10) * numAlign - 55; - if (ver >= 7) - result -= 36; - } - if (!(208 <= result && result <= 29648)) - throw std::logic_error("Assertion error"); - return result; -} - - -int QrCode::getNumDataCodewords(int ver, Ecc ecl) { - return getNumRawDataModules(ver) / 8 - - ECC_CODEWORDS_PER_BLOCK [static_cast(ecl)][ver] - * NUM_ERROR_CORRECTION_BLOCKS[static_cast(ecl)][ver]; -} - - -vector QrCode::reedSolomonComputeDivisor(int degree) { - if (degree < 1 || degree > 255) - throw std::domain_error("Degree out of range"); - // Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1. - // For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array {255, 8, 93}. - vector result(static_cast(degree)); - result.at(result.size() - 1) = 1; // Start off with the monomial x^0 - - // Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}), - // and drop the highest monomial term which is always 1x^degree. - // Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D). - uint8_t root = 1; - for (int i = 0; i < degree; i++) { - // Multiply the current product by (x - r^i) - for (size_t j = 0; j < result.size(); j++) { - result.at(j) = reedSolomonMultiply(result.at(j), root); - if (j + 1 < result.size()) - result.at(j) ^= result.at(j + 1); - } - root = reedSolomonMultiply(root, 0x02); - } - return result; -} - - -vector QrCode::reedSolomonComputeRemainder(const vector &data, const vector &divisor) { - vector result(divisor.size()); - for (uint8_t b : data) { // Polynomial division - uint8_t factor = b ^ result.at(0); - result.erase(result.begin()); - result.push_back(0); - for (size_t i = 0; i < result.size(); i++) - result.at(i) ^= reedSolomonMultiply(divisor.at(i), factor); - } - return result; -} - - -uint8_t QrCode::reedSolomonMultiply(uint8_t x, uint8_t y) { - // Russian peasant multiplication - int z = 0; - for (int i = 7; i >= 0; i--) { - z = (z << 1) ^ ((z >> 7) * 0x11D); - z ^= ((y >> i) & 1) * x; - } - if (z >> 8 != 0) - throw std::logic_error("Assertion error"); - return static_cast(z); -} - - -int QrCode::finderPenaltyCountPatterns(const std::array &runHistory) const { - int n = runHistory.at(1); - if (n > size * 3) - throw std::logic_error("Assertion error"); - bool core = n > 0 && runHistory.at(2) == n && runHistory.at(3) == n * 3 && runHistory.at(4) == n && runHistory.at(5) == n; - return (core && runHistory.at(0) >= n * 4 && runHistory.at(6) >= n ? 1 : 0) - + (core && runHistory.at(6) >= n * 4 && runHistory.at(0) >= n ? 1 : 0); -} - - -int QrCode::finderPenaltyTerminateAndCount(bool currentRunColor, int currentRunLength, std::array &runHistory) const { - if (currentRunColor) { // Terminate black run - finderPenaltyAddHistory(currentRunLength, runHistory); - currentRunLength = 0; - } - currentRunLength += size; // Add white border to final run - finderPenaltyAddHistory(currentRunLength, runHistory); - return finderPenaltyCountPatterns(runHistory); -} - - -void QrCode::finderPenaltyAddHistory(int currentRunLength, std::array &runHistory) const { - if (runHistory.at(0) == 0) - currentRunLength += size; // Add white border to initial run - std::copy_backward(runHistory.cbegin(), runHistory.cend() - 1, runHistory.end()); - runHistory.at(0) = currentRunLength; -} - - -bool QrCode::getBit(long x, int i) { - return ((x >> i) & 1) != 0; -} - - -/*---- Tables of constants ----*/ - -const int QrCode::PENALTY_N1 = 3; -const int QrCode::PENALTY_N2 = 3; -const int QrCode::PENALTY_N3 = 40; -const int QrCode::PENALTY_N4 = 10; - - -const int8_t QrCode::ECC_CODEWORDS_PER_BLOCK[4][41] = { - // Version: (note that index 0 is for padding, and is set to an illegal value) - //0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level - {-1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // Low - {-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28}, // Medium - {-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // Quartile - {-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // High -}; - -const int8_t QrCode::NUM_ERROR_CORRECTION_BLOCKS[4][41] = { - // Version: (note that index 0 is for padding, and is set to an illegal value) - //0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level - {-1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25}, // Low - {-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49}, // Medium - {-1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68}, // Quartile - {-1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81}, // High -}; - - -data_too_long::data_too_long(const std::string &msg) : - std::length_error(msg) {} - - - -BitBuffer::BitBuffer() - : std::vector() {} - - -void BitBuffer::appendBits(std::uint32_t val, int len) { - if (len < 0 || len > 31 || val >> len != 0) - throw std::domain_error("Value out of range"); - for (int i = len - 1; i >= 0; i--) // Append bit by bit - this->push_back(((val >> i) & 1) != 0); -} - -} diff --git a/third_party/qrcode/QrCode.hpp b/third_party/qrcode/QrCode.hpp deleted file mode 100644 index 7341e41029..0000000000 --- a/third_party/qrcode/QrCode.hpp +++ /dev/null @@ -1,556 +0,0 @@ -/* - * QR Code generator library (C++) - * - * Copyright (c) Project Nayuki. (MIT License) - * https://www.nayuki.io/page/qr-code-generator-library - * - * 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. - */ - -#pragma once - -#include -#include -#include -#include -#include - - -namespace qrcodegen { - -/* - * A segment of character/binary/control data in a QR Code symbol. - * Instances of this class are immutable. - * The mid-level way to create a segment is to take the payload data - * and call a static factory function such as QrSegment::makeNumeric(). - * The low-level way to create a segment is to custom-make the bit buffer - * and call the QrSegment() constructor with appropriate values. - * This segment class imposes no length restrictions, but QR Codes have restrictions. - * Even in the most favorable conditions, a QR Code can only hold 7089 characters of data. - * Any segment longer than this is meaningless for the purpose of generating QR Codes. - */ -class QrSegment final { - - /*---- Public helper enumeration ----*/ - - /* - * Describes how a segment's data bits are interpreted. Immutable. - */ - public: class Mode final { - - /*-- Constants --*/ - - public: static const Mode NUMERIC; - public: static const Mode ALPHANUMERIC; - public: static const Mode BYTE; - public: static const Mode KANJI; - public: static const Mode ECI; - - - /*-- Fields --*/ - - // The mode indicator bits, which is a uint4 value (range 0 to 15). - private: int modeBits; - - // Number of character count bits for three different version ranges. - private: int numBitsCharCount[3]; - - - /*-- Constructor --*/ - - private: Mode(int mode, int cc0, int cc1, int cc2); - - - /*-- Methods --*/ - - /* - * (Package-private) Returns the mode indicator bits, which is an unsigned 4-bit value (range 0 to 15). - */ - public: int getModeBits() const; - - /* - * (Package-private) Returns the bit width of the character count field for a segment in - * this mode in a QR Code at the given version number. The result is in the range [0, 16]. - */ - public: int numCharCountBits(int ver) const; - - }; - - - - /*---- Static factory functions (mid level) ----*/ - - /* - * Returns a segment representing the given binary data encoded in - * byte mode. All input byte vectors are acceptable. Any text string - * can be converted to UTF-8 bytes and encoded as a byte mode segment. - */ - public: static QrSegment makeBytes(const std::vector &data); - - - /* - * Returns a segment representing the given string of decimal digits encoded in numeric mode. - */ - public: static QrSegment makeNumeric(const char *digits); - - - /* - * Returns a segment representing the given text string encoded in alphanumeric mode. - * The characters allowed are: 0 to 9, A to Z (uppercase only), space, - * dollar, percent, asterisk, plus, hyphen, period, slash, colon. - */ - public: static QrSegment makeAlphanumeric(const char *text); - - - /* - * Returns a list of zero or more segments to represent the given text string. The result - * may use various segment modes and switch modes to optimize the length of the bit stream. - */ - public: static std::vector makeSegments(const char *text); - - - /* - * Returns a segment representing an Extended Channel Interpretation - * (ECI) designator with the given assignment value. - */ - public: static QrSegment makeEci(long assignVal); - - - /*---- Public static helper functions ----*/ - - /* - * Tests whether the given string can be encoded as a segment in alphanumeric mode. - * A string is encodable iff each character is in the following set: 0 to 9, A to Z - * (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon. - */ - public: static bool isAlphanumeric(const char *text); - - - /* - * Tests whether the given string can be encoded as a segment in numeric mode. - * A string is encodable iff each character is in the range 0 to 9. - */ - public: static bool isNumeric(const char *text); - - - - /*---- Instance fields ----*/ - - /* The mode indicator of this segment. Accessed through getMode(). */ - private: Mode mode; - - /* The length of this segment's unencoded data. Measured in characters for - * numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode. - * Always zero or positive. Not the same as the data's bit length. - * Accessed through getNumChars(). */ - private: int numChars; - - /* The data bits of this segment. Accessed through getData(). */ - private: std::vector data; - - - /*---- Constructors (low level) ----*/ - - /* - * Creates a new QR Code segment with the given attributes and data. - * The character count (numCh) must agree with the mode and the bit buffer length, - * but the constraint isn't checked. The given bit buffer is copied and stored. - */ - public: QrSegment(Mode md, int numCh, const std::vector &dt); - - - /* - * Creates a new QR Code segment with the given parameters and data. - * The character count (numCh) must agree with the mode and the bit buffer length, - * but the constraint isn't checked. The given bit buffer is moved and stored. - */ - public: QrSegment(Mode md, int numCh, std::vector &&dt); - - - /*---- Methods ----*/ - - /* - * Returns the mode field of this segment. - */ - public: Mode getMode() const; - - - /* - * Returns the character count field of this segment. - */ - public: int getNumChars() const; - - - /* - * Returns the data bits of this segment. - */ - public: const std::vector &getData() const; - - - // (Package-private) Calculates the number of bits needed to encode the given segments at - // the given version. Returns a non-negative number if successful. Otherwise returns -1 if a - // segment has too many characters to fit its length field, or the total bits exceeds INT_MAX. - public: static int getTotalBits(const std::vector &segs, int version); - - - /*---- Private constant ----*/ - - /* The set of all legal characters in alphanumeric mode, where - * each character value maps to the index in the string. */ - private: static const char *ALPHANUMERIC_CHARSET; - -}; - - - -/* - * A QR Code symbol, which is a type of two-dimension barcode. - * Invented by Denso Wave and described in the ISO/IEC 18004 standard. - * Instances of this class represent an immutable square grid of black and white cells. - * The class provides static factory functions to create a QR Code from text or binary data. - * The class covers the QR Code Model 2 specification, supporting all versions (sizes) - * from 1 to 40, all 4 error correction levels, and 4 character encoding modes. - * - * Ways to create a QR Code object: - * - High level: Take the payload data and call QrCode::encodeText() or QrCode::encodeBinary(). - * - Mid level: Custom-make the list of segments and call QrCode::encodeSegments(). - * - Low level: Custom-make the array of data codeword bytes (including - * segment headers and final padding, excluding error correction codewords), - * supply the appropriate version number, and call the QrCode() constructor. - * (Note that all ways require supplying the desired error correction level.) - */ -class QrCode final { - - /*---- Public helper enumeration ----*/ - - /* - * The error correction level in a QR Code symbol. - */ - public: enum class Ecc { - LOW = 0 , // The QR Code can tolerate about 7% erroneous codewords - MEDIUM , // The QR Code can tolerate about 15% erroneous codewords - QUARTILE, // The QR Code can tolerate about 25% erroneous codewords - HIGH , // The QR Code can tolerate about 30% erroneous codewords - }; - - - // Returns a value in the range 0 to 3 (unsigned 2-bit integer). - private: static int getFormatBits(Ecc ecl); - - - - /*---- Static factory functions (high level) ----*/ - - /* - * Returns a QR Code representing the given Unicode text string at the given error correction level. - * As a conservative upper bound, this function is guaranteed to succeed for strings that have 2953 or fewer - * UTF-8 code units (not Unicode code points) if the low error correction level is used. The smallest possible - * QR Code version is automatically chosen for the output. The ECC level of the result may be higher than - * the ecl argument if it can be done without increasing the version. - */ - public: static QrCode encodeText(const char *text, Ecc ecl); - - - /* - * Returns a QR Code representing the given binary data at the given error correction level. - * This function always encodes using the binary segment mode, not any text mode. The maximum number of - * bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output. - * The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version. - */ - public: static QrCode encodeBinary(const std::vector &data, Ecc ecl); - - - /*---- Static factory functions (mid level) ----*/ - - /* - * Returns a QR Code representing the given segments with the given encoding parameters. - * The smallest possible QR Code version within the given range is automatically - * chosen for the output. Iff boostEcl is true, then the ECC level of the result - * may be higher than the ecl argument if it can be done without increasing the - * version. The mask number is either between 0 to 7 (inclusive) to force that - * mask, or -1 to automatically choose an appropriate mask (which may be slow). - * This function allows the user to create a custom sequence of segments that switches - * between modes (such as alphanumeric and byte) to encode text in less space. - * This is a mid-level API; the high-level API is encodeText() and encodeBinary(). - */ - public: static QrCode encodeSegments(const std::vector &segs, Ecc ecl, - int minVersion=1, int maxVersion=40, int mask=-1, bool boostEcl=true); // All optional parameters - - - - /*---- Instance fields ----*/ - - // Immutable scalar parameters: - - /* The version number of this QR Code, which is between 1 and 40 (inclusive). - * This determines the size of this barcode. */ - private: int version; - - /* The width and height of this QR Code, measured in modules, between - * 21 and 177 (inclusive). This is equal to version * 4 + 17. */ - private: int size; - - /* The error correction level used in this QR Code. */ - private: Ecc errorCorrectionLevel; - - /* The index of the mask pattern used in this QR Code, which is between 0 and 7 (inclusive). - * Even if a QR Code is created with automatic masking requested (mask = -1), - * the resulting object still has a mask value between 0 and 7. */ - private: int mask; - - // Private grids of modules/pixels, with dimensions of size*size: - - // The modules of this QR Code (false = white, true = black). - // Immutable after constructor finishes. Accessed through getModule(). - private: std::vector > modules; - - // Indicates function modules that are not subjected to masking. Discarded when constructor finishes. - private: std::vector > isFunction; - - - - /*---- Constructor (low level) ----*/ - - /* - * Creates a new QR Code with the given version number, - * error correction level, data codeword bytes, and mask number. - * This is a low-level API that most users should not use directly. - * A mid-level API is the encodeSegments() function. - */ - public: QrCode(int ver, Ecc ecl, const std::vector &dataCodewords, int msk); - - - - /*---- Public instance methods ----*/ - - /* - * Returns this QR Code's version, in the range [1, 40]. - */ - public: int getVersion() const; - - - /* - * Returns this QR Code's size, in the range [21, 177]. - */ - public: int getSize() const; - - - /* - * Returns this QR Code's error correction level. - */ - public: Ecc getErrorCorrectionLevel() const; - - - /* - * Returns this QR Code's mask, in the range [0, 7]. - */ - public: int getMask() const; - - - /* - * Returns the color of the module (pixel) at the given coordinates, which is false - * for white or true for black. The top left corner has the coordinates (x=0, y=0). - * If the given coordinates are out of bounds, then false (white) is returned. - */ - public: bool getModule(int x, int y) const; - - - /* - * Returns a string of SVG code for an image depicting this QR Code, with the given number - * of border modules. The string always uses Unix newlines (\n), regardless of the platform. - */ - public: std::string toSvgString(int border) const; - - - - /*---- Private helper methods for constructor: Drawing function modules ----*/ - - // Reads this object's version field, and draws and marks all function modules. - private: void drawFunctionPatterns(); - - - // Draws two copies of the format bits (with its own error correction code) - // based on the given mask and this object's error correction level field. - private: void drawFormatBits(int msk); - - - // Draws two copies of the version bits (with its own error correction code), - // based on this object's version field, iff 7 <= version <= 40. - private: void drawVersion(); - - - // Draws a 9*9 finder pattern including the border separator, - // with the center module at (x, y). Modules can be out of bounds. - private: void drawFinderPattern(int x, int y); - - - // Draws a 5*5 alignment pattern, with the center module - // at (x, y). All modules must be in bounds. - private: void drawAlignmentPattern(int x, int y); - - - // Sets the color of a module and marks it as a function module. - // Only used by the constructor. Coordinates must be in bounds. - private: void setFunctionModule(int x, int y, bool isBlack); - - - // Returns the color of the module at the given coordinates, which must be in range. - private: bool module(int x, int y) const; - - - /*---- Private helper methods for constructor: Codewords and masking ----*/ - - // Returns a new byte string representing the given data with the appropriate error correction - // codewords appended to it, based on this object's version and error correction level. - private: std::vector addEccAndInterleave(const std::vector &data) const; - - - // Draws the given sequence of 8-bit codewords (data and error correction) onto the entire - // data area of this QR Code. Function modules need to be marked off before this is called. - private: void drawCodewords(const std::vector &data); - - - // XORs the codeword modules in this QR Code with the given mask pattern. - // The function modules must be marked and the codeword bits must be drawn - // before masking. Due to the arithmetic of XOR, calling applyMask() with - // the same mask value a second time will undo the mask. A final well-formed - // QR Code needs exactly one (not zero, two, etc.) mask applied. - private: void applyMask(int msk); - - - // Calculates and returns the penalty score based on state of this QR Code's current modules. - // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score. - private: long getPenaltyScore() const; - - - - /*---- Private helper functions ----*/ - - // Returns an ascending list of positions of alignment patterns for this version number. - // Each position is in the range [0,177), and are used on both the x and y axes. - // This could be implemented as lookup table of 40 variable-length lists of unsigned bytes. - private: std::vector getAlignmentPatternPositions() const; - - - // Returns the number of data bits that can be stored in a QR Code of the given version number, after - // all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8. - // The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table. - private: static int getNumRawDataModules(int ver); - - - // Returns the number of 8-bit data (i.e. not error correction) codewords contained in any - // QR Code of the given version number and error correction level, with remainder bits discarded. - // This stateless pure function could be implemented as a (40*4)-cell lookup table. - private: static int getNumDataCodewords(int ver, Ecc ecl); - - - // Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be - // implemented as a lookup table over all possible parameter values, instead of as an algorithm. - private: static std::vector reedSolomonComputeDivisor(int degree); - - - // Returns the Reed-Solomon error correction codeword for the given data and divisor polynomials. - private: static std::vector reedSolomonComputeRemainder(const std::vector &data, const std::vector &divisor); - - - // Returns the product of the two given field elements modulo GF(2^8/0x11D). - // All inputs are valid. This could be implemented as a 256*256 lookup table. - private: static std::uint8_t reedSolomonMultiply(std::uint8_t x, std::uint8_t y); - - - // Can only be called immediately after a white run is added, and - // returns either 0, 1, or 2. A helper function for getPenaltyScore(). - private: int finderPenaltyCountPatterns(const std::array &runHistory) const; - - - // Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore(). - private: int finderPenaltyTerminateAndCount(bool currentRunColor, int currentRunLength, std::array &runHistory) const; - - - // Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore(). - private: void finderPenaltyAddHistory(int currentRunLength, std::array &runHistory) const; - - - // Returns true iff the i'th bit of x is set to 1. - private: static bool getBit(long x, int i); - - - /*---- Constants and tables ----*/ - - // The minimum version number supported in the QR Code Model 2 standard. - public: static constexpr int MIN_VERSION = 1; - - // The maximum version number supported in the QR Code Model 2 standard. - public: static constexpr int MAX_VERSION = 40; - - - // For use in getPenaltyScore(), when evaluating which mask is best. - private: static const int PENALTY_N1; - private: static const int PENALTY_N2; - private: static const int PENALTY_N3; - private: static const int PENALTY_N4; - - - private: static const std::int8_t ECC_CODEWORDS_PER_BLOCK[4][41]; - private: static const std::int8_t NUM_ERROR_CORRECTION_BLOCKS[4][41]; - -}; - - - -/*---- Public exception class ----*/ - -/* - * Thrown when the supplied data does not fit any QR Code version. Ways to handle this exception include: - * - Decrease the error correction level if it was greater than Ecc::LOW. - * - If the encodeSegments() function was called with a maxVersion argument, then increase - * it if it was less than QrCode::MAX_VERSION. (This advice does not apply to the other - * factory functions because they search all versions up to QrCode::MAX_VERSION.) - * - Split the text data into better or optimal segments in order to reduce the number of bits required. - * - Change the text or binary data to be shorter. - * - Change the text to fit the character set of a particular segment mode (e.g. alphanumeric). - * - Propagate the error upward to the caller/user. - */ -class data_too_long : public std::length_error { - - public: explicit data_too_long(const std::string &msg); - -}; - - - -/* - * An appendable sequence of bits (0s and 1s). Mainly used by QrSegment. - */ -class BitBuffer final : public std::vector { - - /*---- Constructor ----*/ - - // Creates an empty bit buffer (length 0). - public: BitBuffer(); - - - - /*---- Method ----*/ - - // Appends the given number of low-order bits of the given value - // to this buffer. Requires 0 <= len <= 31 and val < 2^len. - public: void appendBits(std::uint32_t val, int len); - -}; - -} diff --git a/third_party/qt5/larch64/bin/lrelease b/third_party/qt5/larch64/bin/lrelease deleted file mode 100755 index 5891f85851..0000000000 --- a/third_party/qt5/larch64/bin/lrelease +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:56ddfc4ead01eaf43cba41e2095ec4f52309c53a60ba9e351d8dbd900151228f -size 546824 diff --git a/third_party/qt5/larch64/bin/lupdate b/third_party/qt5/larch64/bin/lupdate deleted file mode 100755 index 0055aae229..0000000000 --- a/third_party/qt5/larch64/bin/lupdate +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:7af679aa708031f6d19baabbd48e92d23462c6ff287caccdcb5c6324168d985d -size 1095744 diff --git a/third_party/raylib/.gitignore b/third_party/raylib/.gitignore deleted file mode 100644 index c4afad9c38..0000000000 --- a/third_party/raylib/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -/raylib_repo/ -/raylib_python_repo/ -/wheel/ diff --git a/third_party/raylib/Darwin/libraylib.a b/third_party/raylib/Darwin/libraylib.a deleted file mode 100644 index 837ad8818e..0000000000 --- a/third_party/raylib/Darwin/libraylib.a +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:7ffe1fc6497f0c111fc507988e94fd29ce4db53a4876dc82ab9267895ad82584 -size 6515352 diff --git a/third_party/raylib/build.sh b/third_party/raylib/build.sh deleted file mode 100755 index 9e85f90df9..0000000000 --- a/third_party/raylib/build.sh +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/env bash -set -e - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )" -cd $DIR - -RAYLIB_PLATFORM="PLATFORM_DESKTOP" - -ARCHNAME=$(uname -m) -if [ -f /TICI ]; then - ARCHNAME="larch64" - RAYLIB_PLATFORM="PLATFORM_COMMA" -fi - -if [[ "$OSTYPE" == "darwin"* ]]; then - ARCHNAME="Darwin" -fi - -INSTALL_DIR="$DIR/$ARCHNAME" -rm -rf $INSTALL_DIR -mkdir -p $INSTALL_DIR - -INSTALL_H_DIR="$DIR/include" -rm -rf $INSTALL_H_DIR -mkdir -p $INSTALL_H_DIR - -if [ ! -d raylib_repo ]; then - git clone -b master --no-tags https://github.com/commaai/raylib.git raylib_repo -fi - -cd raylib_repo - -COMMIT=${1:-66030a7de62c9e1ee8ab30a1d657a740333bb4f2} -git fetch origin $COMMIT -git reset --hard $COMMIT -git clean -xdff . - -cd src - -make -j$(nproc) PLATFORM=$RAYLIB_PLATFORM RAYLIB_RELEASE_PATH=$INSTALL_DIR -cp raylib.h raymath.h rlgl.h $INSTALL_H_DIR/ -echo "raylib development files installed/updated in $INSTALL_H_DIR" - -# this commit needs to be in line with raylib -set -x -RAYGUI_COMMIT="76b36b597edb70ffaf96f046076adc20d67e7827" -curl -fsSLo $INSTALL_H_DIR/raygui.h https://raw.githubusercontent.com/raysan5/raygui/$RAYGUI_COMMIT/src/raygui.h - -if [ -f /TICI ]; then - - # Building the python bindings - cd $DIR - - if [ ! -d raylib_python_repo ]; then - git clone -b master --no-tags https://github.com/commaai/raylib-python-cffi.git raylib_python_repo - fi - - cd raylib_python_repo - - BINDINGS_COMMIT="ef8141c7979d5fa630ef4108605fc221f07d8cb7" - git fetch origin $BINDINGS_COMMIT - git reset --hard $BINDINGS_COMMIT - git clean -xdff . - - RAYLIB_PLATFORM=$RAYLIB_PLATFORM RAYLIB_INCLUDE_PATH=$INSTALL_H_DIR RAYLIB_LIB_PATH=$INSTALL_DIR python setup.py bdist_wheel - cd $DIR - - rm -rf wheel - mkdir wheel - cp raylib_python_repo/dist/*.whl wheel/ - -fi diff --git a/third_party/raylib/include/raygui.h b/third_party/raylib/include/raygui.h deleted file mode 100644 index fe233a16cf..0000000000 --- a/third_party/raylib/include/raygui.h +++ /dev/null @@ -1,5759 +0,0 @@ -/******************************************************************************************* -* -* raygui v4.5-dev - A simple and easy-to-use immediate-mode gui library -* -* DESCRIPTION: -* raygui is a tools-dev-focused immediate-mode-gui library based on raylib but also -* available as a standalone library, as long as input and drawing functions are provided. -* -* FEATURES: -* - Immediate-mode gui, minimal retained data -* - +25 controls provided (basic and advanced) -* - Styling system for colors, font and metrics -* - Icons supported, embedded as a 1-bit icons pack -* - Standalone mode option (custom input/graphics backend) -* - Multiple support tools provided for raygui development -* -* POSSIBLE IMPROVEMENTS: -* - Better standalone mode API for easy plug of custom backends -* - Externalize required inputs, allow user easier customization -* -* LIMITATIONS: -* - No editable multi-line word-wraped text box supported -* - No auto-layout mechanism, up to the user to define controls position and size -* - Standalone mode requires library modification and some user work to plug another backend -* -* NOTES: -* - WARNING: GuiLoadStyle() and GuiLoadStyle{Custom}() functions, allocate memory for -* font atlas recs and glyphs, freeing that memory is (usually) up to the user, -* no unload function is explicitly provided... but note that GuiLoadStyleDefault() unloads -* by default any previously loaded font (texture, recs, glyphs). -* - Global UI alpha (guiAlpha) is applied inside GuiDrawRectangle() and GuiDrawText() functions -* -* CONTROLS PROVIDED: -* # Container/separators Controls -* - WindowBox --> StatusBar, Panel -* - GroupBox --> Line -* - Line -* - Panel --> StatusBar -* - ScrollPanel --> StatusBar -* - TabBar --> Button -* -* # Basic Controls -* - Label -* - LabelButton --> Label -* - Button -* - Toggle -* - ToggleGroup --> Toggle -* - ToggleSlider -* - CheckBox -* - ComboBox -* - DropdownBox -* - TextBox -* - ValueBox --> TextBox -* - Spinner --> Button, ValueBox -* - Slider -* - SliderBar --> Slider -* - ProgressBar -* - StatusBar -* - DummyRec -* - Grid -* -* # Advance Controls -* - ListView -* - ColorPicker --> ColorPanel, ColorBarHue -* - MessageBox --> Window, Label, Button -* - TextInputBox --> Window, Label, TextBox, Button -* -* It also provides a set of functions for styling the controls based on its properties (size, color). -* -* -* RAYGUI STYLE (guiStyle): -* raygui uses a global data array for all gui style properties (allocated on data segment by default), -* when a new style is loaded, it is loaded over the global style... but a default gui style could always be -* recovered with GuiLoadStyleDefault() function, that overwrites the current style to the default one -* -* The global style array size is fixed and depends on the number of controls and properties: -* -* static unsigned int guiStyle[RAYGUI_MAX_CONTROLS*(RAYGUI_MAX_PROPS_BASE + RAYGUI_MAX_PROPS_EXTENDED)]; -* -* guiStyle size is by default: 16*(16 + 8) = 384*4 = 1536 bytes = 1.5 KB -* -* Note that the first set of BASE properties (by default guiStyle[0..15]) belong to the generic style -* used for all controls, when any of those base values is set, it is automatically populated to all -* controls, so, specific control values overwriting generic style should be set after base values. -* -* After the first BASE set we have the EXTENDED properties (by default guiStyle[16..23]), those -* properties are actually common to all controls and can not be overwritten individually (like BASE ones) -* Some of those properties are: TEXT_SIZE, TEXT_SPACING, LINE_COLOR, BACKGROUND_COLOR -* -* Custom control properties can be defined using the EXTENDED properties for each independent control. -* -* TOOL: rGuiStyler is a visual tool to customize raygui style: github.com/raysan5/rguistyler -* -* -* RAYGUI ICONS (guiIcons): -* raygui could use a global array containing icons data (allocated on data segment by default), -* a custom icons set could be loaded over this array using GuiLoadIcons(), but loaded icons set -* must be same RAYGUI_ICON_SIZE and no more than RAYGUI_ICON_MAX_ICONS will be loaded -* -* Every icon is codified in binary form, using 1 bit per pixel, so, every 16x16 icon -* requires 8 integers (16*16/32) to be stored in memory. -* -* When the icon is draw, actually one quad per pixel is drawn if the bit for that pixel is set. -* -* The global icons array size is fixed and depends on the number of icons and size: -* -* static unsigned int guiIcons[RAYGUI_ICON_MAX_ICONS*RAYGUI_ICON_DATA_ELEMENTS]; -* -* guiIcons size is by default: 256*(16*16/32) = 2048*4 = 8192 bytes = 8 KB -* -* TOOL: rGuiIcons is a visual tool to customize/create raygui icons: github.com/raysan5/rguiicons -* -* RAYGUI LAYOUT: -* raygui currently does not provide an auto-layout mechanism like other libraries, -* layouts must be defined manually on controls drawing, providing the right bounds Rectangle for it. -* -* TOOL: rGuiLayout is a visual tool to create raygui layouts: github.com/raysan5/rguilayout -* -* CONFIGURATION: -* #define RAYGUI_IMPLEMENTATION -* Generates the implementation of the library into the included file. -* If not defined, the library is in header only mode and can be included in other headers -* or source files without problems. But only ONE file should hold the implementation. -* -* #define RAYGUI_STANDALONE -* Avoid raylib.h header inclusion in this file. Data types defined on raylib are defined -* internally in the library and input management and drawing functions must be provided by -* the user (check library implementation for further details). -* -* #define RAYGUI_NO_ICONS -* Avoid including embedded ricons data (256 icons, 16x16 pixels, 1-bit per pixel, 2KB) -* -* #define RAYGUI_CUSTOM_ICONS -* Includes custom ricons.h header defining a set of custom icons, -* this file can be generated using rGuiIcons tool -* -* #define RAYGUI_DEBUG_RECS_BOUNDS -* Draw control bounds rectangles for debug -* -* #define RAYGUI_DEBUG_TEXT_BOUNDS -* Draw text bounds rectangles for debug -* -* VERSIONS HISTORY: -* 4.5-dev (Sep-2024) Current dev version... -* ADDED: guiControlExclusiveMode and guiControlExclusiveRec for exclusive modes -* ADDED: GuiValueBoxFloat() -* ADDED: GuiDropdonwBox() properties: DROPDOWN_ARROW_HIDDEN, DROPDOWN_ROLL_UP -* ADDED: GuiListView() property: LIST_ITEMS_BORDER_WIDTH -* ADDED: Multiple new icons -* REVIEWED: GuiTabBar(), close tab with mouse middle button -* REVIEWED: GuiScrollPanel(), scroll speed proportional to content -* REVIEWED: GuiDropdownBox(), support roll up and hidden arrow -* REVIEWED: GuiTextBox(), cursor position initialization -* REVIEWED: GuiSliderPro(), control value change check -* REVIEWED: GuiGrid(), simplified implementation -* REVIEWED: GuiIconText(), increase buffer size and reviewed padding -* REVIEWED: GuiDrawText(), improved wrap mode drawing -* REVIEWED: GuiScrollBar(), minor tweaks -* REVIEWED: Functions descriptions, removed wrong return value reference -* REDESIGNED: GuiColorPanel(), improved HSV <-> RGBA convertion -* -* 4.0 (12-Sep-2023) ADDED: GuiToggleSlider() -* ADDED: GuiColorPickerHSV() and GuiColorPanelHSV() -* ADDED: Multiple new icons, mostly compiler related -* ADDED: New DEFAULT properties: TEXT_LINE_SPACING, TEXT_ALIGNMENT_VERTICAL, TEXT_WRAP_MODE -* ADDED: New enum values: GuiTextAlignment, GuiTextAlignmentVertical, GuiTextWrapMode -* ADDED: Support loading styles with custom font charset from external file -* REDESIGNED: GuiTextBox(), support mouse cursor positioning -* REDESIGNED: GuiDrawText(), support multiline and word-wrap modes (read only) -* REDESIGNED: GuiProgressBar() to be more visual, progress affects border color -* REDESIGNED: Global alpha consideration moved to GuiDrawRectangle() and GuiDrawText() -* REDESIGNED: GuiScrollPanel(), get parameters by reference and return result value -* REDESIGNED: GuiToggleGroup(), get parameters by reference and return result value -* REDESIGNED: GuiComboBox(), get parameters by reference and return result value -* REDESIGNED: GuiCheckBox(), get parameters by reference and return result value -* REDESIGNED: GuiSlider(), get parameters by reference and return result value -* REDESIGNED: GuiSliderBar(), get parameters by reference and return result value -* REDESIGNED: GuiProgressBar(), get parameters by reference and return result value -* REDESIGNED: GuiListView(), get parameters by reference and return result value -* REDESIGNED: GuiColorPicker(), get parameters by reference and return result value -* REDESIGNED: GuiColorPanel(), get parameters by reference and return result value -* REDESIGNED: GuiColorBarAlpha(), get parameters by reference and return result value -* REDESIGNED: GuiColorBarHue(), get parameters by reference and return result value -* REDESIGNED: GuiGrid(), get parameters by reference and return result value -* REDESIGNED: GuiGrid(), added extra parameter -* REDESIGNED: GuiListViewEx(), change parameters order -* REDESIGNED: All controls return result as int value -* REVIEWED: GuiScrollPanel() to avoid smallish scroll-bars -* REVIEWED: All examples and specially controls_test_suite -* RENAMED: gui_file_dialog module to gui_window_file_dialog -* UPDATED: All styles to include ISO-8859-15 charset (as much as possible) -* -* 3.6 (10-May-2023) ADDED: New icon: SAND_TIMER -* ADDED: GuiLoadStyleFromMemory() (binary only) -* REVIEWED: GuiScrollBar() horizontal movement key -* REVIEWED: GuiTextBox() crash on cursor movement -* REVIEWED: GuiTextBox(), additional inputs support -* REVIEWED: GuiLabelButton(), avoid text cut -* REVIEWED: GuiTextInputBox(), password input -* REVIEWED: Local GetCodepointNext(), aligned with raylib -* REDESIGNED: GuiSlider*()/GuiScrollBar() to support out-of-bounds -* -* 3.5 (20-Apr-2023) ADDED: GuiTabBar(), based on GuiToggle() -* ADDED: Helper functions to split text in separate lines -* ADDED: Multiple new icons, useful for code editing tools -* REMOVED: Unneeded icon editing functions -* REMOVED: GuiTextBoxMulti(), very limited and broken -* REMOVED: MeasureTextEx() dependency, logic directly implemented -* REMOVED: DrawTextEx() dependency, logic directly implemented -* REVIEWED: GuiScrollBar(), improve mouse-click behaviour -* REVIEWED: Library header info, more info, better organized -* REDESIGNED: GuiTextBox() to support cursor movement -* REDESIGNED: GuiDrawText() to divide drawing by lines -* -* 3.2 (22-May-2022) RENAMED: Some enum values, for unification, avoiding prefixes -* REMOVED: GuiScrollBar(), only internal -* REDESIGNED: GuiPanel() to support text parameter -* REDESIGNED: GuiScrollPanel() to support text parameter -* REDESIGNED: GuiColorPicker() to support text parameter -* REDESIGNED: GuiColorPanel() to support text parameter -* REDESIGNED: GuiColorBarAlpha() to support text parameter -* REDESIGNED: GuiColorBarHue() to support text parameter -* REDESIGNED: GuiTextInputBox() to support password -* -* 3.1 (12-Jan-2022) REVIEWED: Default style for consistency (aligned with rGuiLayout v2.5 tool) -* REVIEWED: GuiLoadStyle() to support compressed font atlas image data and unload previous textures -* REVIEWED: External icons usage logic -* REVIEWED: GuiLine() for centered alignment when including text -* RENAMED: Multiple controls properties definitions to prepend RAYGUI_ -* RENAMED: RICON_ references to RAYGUI_ICON_ for library consistency -* Projects updated and multiple tweaks -* -* 3.0 (04-Nov-2021) Integrated ricons data to avoid external file -* REDESIGNED: GuiTextBoxMulti() -* REMOVED: GuiImageButton*() -* Multiple minor tweaks and bugs corrected -* -* 2.9 (17-Mar-2021) REMOVED: Tooltip API -* 2.8 (03-May-2020) Centralized rectangles drawing to GuiDrawRectangle() -* 2.7 (20-Feb-2020) ADDED: Possible tooltips API -* 2.6 (09-Sep-2019) ADDED: GuiTextInputBox() -* REDESIGNED: GuiListView*(), GuiDropdownBox(), GuiSlider*(), GuiProgressBar(), GuiMessageBox() -* REVIEWED: GuiTextBox(), GuiSpinner(), GuiValueBox(), GuiLoadStyle() -* Replaced property INNER_PADDING by TEXT_PADDING, renamed some properties -* ADDED: 8 new custom styles ready to use -* Multiple minor tweaks and bugs corrected -* -* 2.5 (28-May-2019) Implemented extended GuiTextBox(), GuiValueBox(), GuiSpinner() -* 2.3 (29-Apr-2019) ADDED: rIcons auxiliar library and support for it, multiple controls reviewed -* Refactor all controls drawing mechanism to use control state -* 2.2 (05-Feb-2019) ADDED: GuiScrollBar(), GuiScrollPanel(), reviewed GuiListView(), removed Gui*Ex() controls -* 2.1 (26-Dec-2018) REDESIGNED: GuiCheckBox(), GuiComboBox(), GuiDropdownBox(), GuiToggleGroup() > Use combined text string -* REDESIGNED: Style system (breaking change) -* 2.0 (08-Nov-2018) ADDED: Support controls guiLock and custom fonts -* REVIEWED: GuiComboBox(), GuiListView()... -* 1.9 (09-Oct-2018) REVIEWED: GuiGrid(), GuiTextBox(), GuiTextBoxMulti(), GuiValueBox()... -* 1.8 (01-May-2018) Lot of rework and redesign to align with rGuiStyler and rGuiLayout -* 1.5 (21-Jun-2017) Working in an improved styles system -* 1.4 (15-Jun-2017) Rewritten all GUI functions (removed useless ones) -* 1.3 (12-Jun-2017) Complete redesign of style system -* 1.1 (01-Jun-2017) Complete review of the library -* 1.0 (07-Jun-2016) Converted to header-only by Ramon Santamaria. -* 0.9 (07-Mar-2016) Reviewed and tested by Albert Martos, Ian Eito, Sergio Martinez and Ramon Santamaria. -* 0.8 (27-Aug-2015) Initial release. Implemented by Kevin Gato, Daniel Nicolás and Ramon Santamaria. -* -* DEPENDENCIES: -* raylib 5.0 - Inputs reading (keyboard/mouse), shapes drawing, font loading and text drawing -* -* STANDALONE MODE: -* By default raygui depends on raylib mostly for the inputs and the drawing functionality but that dependency can be disabled -* with the config flag RAYGUI_STANDALONE. In that case is up to the user to provide another backend to cover library needs. -* -* The following functions should be redefined for a custom backend: -* -* - Vector2 GetMousePosition(void); -* - float GetMouseWheelMove(void); -* - bool IsMouseButtonDown(int button); -* - bool IsMouseButtonPressed(int button); -* - bool IsMouseButtonReleased(int button); -* - bool IsKeyDown(int key); -* - bool IsKeyPressed(int key); -* - int GetCharPressed(void); // -- GuiTextBox(), GuiValueBox() -* -* - void DrawRectangle(int x, int y, int width, int height, Color color); // -- GuiDrawRectangle() -* - void DrawRectangleGradientEx(Rectangle rec, Color col1, Color col2, Color col3, Color col4); // -- GuiColorPicker() -* -* - Font GetFontDefault(void); // -- GuiLoadStyleDefault() -* - Font LoadFontEx(const char *fileName, int fontSize, int *codepoints, int codepointCount); // -- GuiLoadStyle() -* - Texture2D LoadTextureFromImage(Image image); // -- GuiLoadStyle(), required to load texture from embedded font atlas image -* - void SetShapesTexture(Texture2D tex, Rectangle rec); // -- GuiLoadStyle(), required to set shapes rec to font white rec (optimization) -* - char *LoadFileText(const char *fileName); // -- GuiLoadStyle(), required to load charset data -* - void UnloadFileText(char *text); // -- GuiLoadStyle(), required to unload charset data -* - const char *GetDirectoryPath(const char *filePath); // -- GuiLoadStyle(), required to find charset/font file from text .rgs -* - int *LoadCodepoints(const char *text, int *count); // -- GuiLoadStyle(), required to load required font codepoints list -* - void UnloadCodepoints(int *codepoints); // -- GuiLoadStyle(), required to unload codepoints list -* - unsigned char *DecompressData(const unsigned char *compData, int compDataSize, int *dataSize); // -- GuiLoadStyle() -* -* CONTRIBUTORS: -* Ramon Santamaria: Supervision, review, redesign, update and maintenance -* Vlad Adrian: Complete rewrite of GuiTextBox() to support extended features (2019) -* Sergio Martinez: Review, testing (2015) and redesign of multiple controls (2018) -* Adria Arranz: Testing and implementation of additional controls (2018) -* Jordi Jorba: Testing and implementation of additional controls (2018) -* Albert Martos: Review and testing of the library (2015) -* Ian Eito: Review and testing of the library (2015) -* Kevin Gato: Initial implementation of basic components (2014) -* Daniel Nicolas: Initial implementation of basic components (2014) -* -* -* LICENSE: zlib/libpng -* -* Copyright (c) 2014-2025 Ramon Santamaria (@raysan5) -* -* This software is provided "as-is", without any express or implied warranty. In no event -* will the authors be held liable for any damages arising from the use of this software. -* -* Permission is granted to anyone to use this software for any purpose, including commercial -* applications, and to alter it and redistribute it freely, subject to the following restrictions: -* -* 1. The origin of this software must not be misrepresented; you must not claim that you -* wrote the original software. If you use this software in a product, an acknowledgment -* in the product documentation would be appreciated but is not required. -* -* 2. Altered source versions must be plainly marked as such, and must not be misrepresented -* as being the original software. -* -* 3. This notice may not be removed or altered from any source distribution. -* -**********************************************************************************************/ - -#ifndef RAYGUI_H -#define RAYGUI_H - -#define RAYGUI_VERSION_MAJOR 4 -#define RAYGUI_VERSION_MINOR 5 -#define RAYGUI_VERSION_PATCH 0 -#define RAYGUI_VERSION "4.5-dev" - -#if !defined(RAYGUI_STANDALONE) - #include "raylib.h" -#endif - -// Function specifiers in case library is build/used as a shared library (Windows) -// NOTE: Microsoft specifiers to tell compiler that symbols are imported/exported from a .dll -#if defined(_WIN32) - #if defined(BUILD_LIBTYPE_SHARED) - #define RAYGUIAPI __declspec(dllexport) // We are building the library as a Win32 shared library (.dll) - #elif defined(USE_LIBTYPE_SHARED) - #define RAYGUIAPI __declspec(dllimport) // We are using the library as a Win32 shared library (.dll) - #endif -#endif - -// Function specifiers definition -#ifndef RAYGUIAPI - #define RAYGUIAPI // Functions defined as 'extern' by default (implicit specifiers) -#endif - -//---------------------------------------------------------------------------------- -// Defines and Macros -//---------------------------------------------------------------------------------- -// Allow custom memory allocators -#ifndef RAYGUI_MALLOC - #define RAYGUI_MALLOC(sz) malloc(sz) -#endif -#ifndef RAYGUI_CALLOC - #define RAYGUI_CALLOC(n,sz) calloc(n,sz) -#endif -#ifndef RAYGUI_FREE - #define RAYGUI_FREE(p) free(p) -#endif - -// Simple log system to avoid printf() calls if required -// NOTE: Avoiding those calls, also avoids const strings memory usage -#define RAYGUI_SUPPORT_LOG_INFO -#if defined(RAYGUI_SUPPORT_LOG_INFO) - #define RAYGUI_LOG(...) printf(__VA_ARGS__) -#else - #define RAYGUI_LOG(...) -#endif - -//---------------------------------------------------------------------------------- -// Types and Structures Definition -// NOTE: Some types are required for RAYGUI_STANDALONE usage -//---------------------------------------------------------------------------------- -#if defined(RAYGUI_STANDALONE) - #ifndef __cplusplus - // Boolean type - #ifndef true - typedef enum { false, true } bool; - #endif - #endif - - // Vector2 type - typedef struct Vector2 { - float x; - float y; - } Vector2; - - // Vector3 type // -- ConvertHSVtoRGB(), ConvertRGBtoHSV() - typedef struct Vector3 { - float x; - float y; - float z; - } Vector3; - - // Color type, RGBA (32bit) - typedef struct Color { - unsigned char r; - unsigned char g; - unsigned char b; - unsigned char a; - } Color; - - // Rectangle type - typedef struct Rectangle { - float x; - float y; - float width; - float height; - } Rectangle; - - // TODO: Texture2D type is very coupled to raylib, required by Font type - // It should be redesigned to be provided by user - typedef struct Texture2D { - unsigned int id; // OpenGL texture id - int width; // Texture base width - int height; // Texture base height - int mipmaps; // Mipmap levels, 1 by default - int format; // Data format (PixelFormat type) - } Texture2D; - - // Image, pixel data stored in CPU memory (RAM) - typedef struct Image { - void *data; // Image raw data - int width; // Image base width - int height; // Image base height - int mipmaps; // Mipmap levels, 1 by default - int format; // Data format (PixelFormat type) - } Image; - - // GlyphInfo, font characters glyphs info - typedef struct GlyphInfo { - int value; // Character value (Unicode) - int offsetX; // Character offset X when drawing - int offsetY; // Character offset Y when drawing - int advanceX; // Character advance position X - Image image; // Character image data - } GlyphInfo; - - // TODO: Font type is very coupled to raylib, mostly required by GuiLoadStyle() - // It should be redesigned to be provided by user - typedef struct Font { - int baseSize; // Base size (default chars height) - int glyphCount; // Number of glyph characters - int glyphPadding; // Padding around the glyph characters - Texture2D texture; // Texture atlas containing the glyphs - Rectangle *recs; // Rectangles in texture for the glyphs - GlyphInfo *glyphs; // Glyphs info data - } Font; -#endif - -// Style property -// NOTE: Used when exporting style as code for convenience -typedef struct GuiStyleProp { - unsigned short controlId; // Control identifier - unsigned short propertyId; // Property identifier - int propertyValue; // Property value -} GuiStyleProp; - -/* -// Controls text style -NOT USED- -// NOTE: Text style is defined by control -typedef struct GuiTextStyle { - unsigned int size; - int charSpacing; - int lineSpacing; - int alignmentH; - int alignmentV; - int padding; -} GuiTextStyle; -*/ - -// Gui control state -typedef enum { - STATE_NORMAL = 0, - STATE_FOCUSED, - STATE_PRESSED, - STATE_DISABLED -} GuiState; - -// Gui control text alignment -typedef enum { - TEXT_ALIGN_LEFT = 0, - TEXT_ALIGN_CENTER, - TEXT_ALIGN_RIGHT -} GuiTextAlignment; - -// Gui control text alignment vertical -// NOTE: Text vertical position inside the text bounds -typedef enum { - TEXT_ALIGN_TOP = 0, - TEXT_ALIGN_MIDDLE, - TEXT_ALIGN_BOTTOM -} GuiTextAlignmentVertical; - -// Gui control text wrap mode -// NOTE: Useful for multiline text -typedef enum { - TEXT_WRAP_NONE = 0, - TEXT_WRAP_CHAR, - TEXT_WRAP_WORD -} GuiTextWrapMode; - -// Gui controls -typedef enum { - // Default -> populates to all controls when set - DEFAULT = 0, - - // Basic controls - LABEL, // Used also for: LABELBUTTON - BUTTON, - TOGGLE, // Used also for: TOGGLEGROUP - SLIDER, // Used also for: SLIDERBAR, TOGGLESLIDER - PROGRESSBAR, - CHECKBOX, - COMBOBOX, - DROPDOWNBOX, - TEXTBOX, // Used also for: TEXTBOXMULTI - VALUEBOX, - SPINNER, // Uses: BUTTON, VALUEBOX - LISTVIEW, - COLORPICKER, - SCROLLBAR, - STATUSBAR -} GuiControl; - -// Gui base properties for every control -// NOTE: RAYGUI_MAX_PROPS_BASE properties (by default 16 properties) -typedef enum { - BORDER_COLOR_NORMAL = 0, // Control border color in STATE_NORMAL - BASE_COLOR_NORMAL, // Control base color in STATE_NORMAL - TEXT_COLOR_NORMAL, // Control text color in STATE_NORMAL - BORDER_COLOR_FOCUSED, // Control border color in STATE_FOCUSED - BASE_COLOR_FOCUSED, // Control base color in STATE_FOCUSED - TEXT_COLOR_FOCUSED, // Control text color in STATE_FOCUSED - BORDER_COLOR_PRESSED, // Control border color in STATE_PRESSED - BASE_COLOR_PRESSED, // Control base color in STATE_PRESSED - TEXT_COLOR_PRESSED, // Control text color in STATE_PRESSED - BORDER_COLOR_DISABLED, // Control border color in STATE_DISABLED - BASE_COLOR_DISABLED, // Control base color in STATE_DISABLED - TEXT_COLOR_DISABLED, // Control text color in STATE_DISABLED - BORDER_WIDTH, // Control border size, 0 for no border - //TEXT_SIZE, // Control text size (glyphs max height) -> GLOBAL for all controls - //TEXT_SPACING, // Control text spacing between glyphs -> GLOBAL for all controls - //TEXT_LINE_SPACING // Control text spacing between lines -> GLOBAL for all controls - TEXT_PADDING, // Control text padding, not considering border - TEXT_ALIGNMENT, // Control text horizontal alignment inside control text bound (after border and padding) - //TEXT_WRAP_MODE // Control text wrap-mode inside text bounds -> GLOBAL for all controls -} GuiControlProperty; - -// TODO: Which text styling properties should be global or per-control? -// At this moment TEXT_PADDING and TEXT_ALIGNMENT is configured and saved per control while -// TEXT_SIZE, TEXT_SPACING, TEXT_LINE_SPACING, TEXT_ALIGNMENT_VERTICAL, TEXT_WRAP_MODE are global and -// should be configured by user as needed while defining the UI layout - -// Gui extended properties depend on control -// NOTE: RAYGUI_MAX_PROPS_EXTENDED properties (by default, max 8 properties) -//---------------------------------------------------------------------------------- -// DEFAULT extended properties -// NOTE: Those properties are common to all controls or global -// WARNING: We only have 8 slots for those properties by default!!! -> New global control: TEXT? -typedef enum { - TEXT_SIZE = 16, // Text size (glyphs max height) - TEXT_SPACING, // Text spacing between glyphs - LINE_COLOR, // Line control color - BACKGROUND_COLOR, // Background color - TEXT_LINE_SPACING, // Text spacing between lines - TEXT_ALIGNMENT_VERTICAL, // Text vertical alignment inside text bounds (after border and padding) - TEXT_WRAP_MODE // Text wrap-mode inside text bounds - //TEXT_DECORATION // Text decoration: 0-None, 1-Underline, 2-Line-through, 3-Overline - //TEXT_DECORATION_THICK // Text decoration line thickness -} GuiDefaultProperty; - -// Other possible text properties: -// TEXT_WEIGHT // Normal, Italic, Bold -> Requires specific font change -// TEXT_INDENT // Text indentation -> Now using TEXT_PADDING... - -// Label -//typedef enum { } GuiLabelProperty; - -// Button/Spinner -//typedef enum { } GuiButtonProperty; - -// Toggle/ToggleGroup -typedef enum { - GROUP_PADDING = 16, // ToggleGroup separation between toggles -} GuiToggleProperty; - -// Slider/SliderBar -typedef enum { - SLIDER_WIDTH = 16, // Slider size of internal bar - SLIDER_PADDING // Slider/SliderBar internal bar padding -} GuiSliderProperty; - -// ProgressBar -typedef enum { - PROGRESS_PADDING = 16, // ProgressBar internal padding -} GuiProgressBarProperty; - -// ScrollBar -typedef enum { - ARROWS_SIZE = 16, // ScrollBar arrows size - ARROWS_VISIBLE, // ScrollBar arrows visible - SCROLL_SLIDER_PADDING, // ScrollBar slider internal padding - SCROLL_SLIDER_SIZE, // ScrollBar slider size - SCROLL_PADDING, // ScrollBar scroll padding from arrows - SCROLL_SPEED, // ScrollBar scrolling speed -} GuiScrollBarProperty; - -// CheckBox -typedef enum { - CHECK_PADDING = 16 // CheckBox internal check padding -} GuiCheckBoxProperty; - -// ComboBox -typedef enum { - COMBO_BUTTON_WIDTH = 16, // ComboBox right button width - COMBO_BUTTON_SPACING // ComboBox button separation -} GuiComboBoxProperty; - -// DropdownBox -typedef enum { - ARROW_PADDING = 16, // DropdownBox arrow separation from border and items - DROPDOWN_ITEMS_SPACING, // DropdownBox items separation - DROPDOWN_ARROW_HIDDEN, // DropdownBox arrow hidden - DROPDOWN_ROLL_UP // DropdownBox roll up flag (default rolls down) -} GuiDropdownBoxProperty; - -// TextBox/TextBoxMulti/ValueBox/Spinner -typedef enum { - TEXT_READONLY = 16, // TextBox in read-only mode: 0-text editable, 1-text no-editable -} GuiTextBoxProperty; - -// Spinner -typedef enum { - SPIN_BUTTON_WIDTH = 16, // Spinner left/right buttons width - SPIN_BUTTON_SPACING, // Spinner buttons separation -} GuiSpinnerProperty; - -// ListView -typedef enum { - LIST_ITEMS_HEIGHT = 16, // ListView items height - LIST_ITEMS_SPACING, // ListView items separation - SCROLLBAR_WIDTH, // ListView scrollbar size (usually width) - SCROLLBAR_SIDE, // ListView scrollbar side (0-SCROLLBAR_LEFT_SIDE, 1-SCROLLBAR_RIGHT_SIDE) - LIST_ITEMS_BORDER_WIDTH // ListView items border width -} GuiListViewProperty; - -// ColorPicker -typedef enum { - COLOR_SELECTOR_SIZE = 16, - HUEBAR_WIDTH, // ColorPicker right hue bar width - HUEBAR_PADDING, // ColorPicker right hue bar separation from panel - HUEBAR_SELECTOR_HEIGHT, // ColorPicker right hue bar selector height - HUEBAR_SELECTOR_OVERFLOW // ColorPicker right hue bar selector overflow -} GuiColorPickerProperty; - -#define SCROLLBAR_LEFT_SIDE 0 -#define SCROLLBAR_RIGHT_SIDE 1 - -//---------------------------------------------------------------------------------- -// Global Variables Definition -//---------------------------------------------------------------------------------- -// ... - -//---------------------------------------------------------------------------------- -// Module Functions Declaration -//---------------------------------------------------------------------------------- - -#if defined(__cplusplus) -extern "C" { // Prevents name mangling of functions -#endif - -// Global gui state control functions -RAYGUIAPI void GuiEnable(void); // Enable gui controls (global state) -RAYGUIAPI void GuiDisable(void); // Disable gui controls (global state) -RAYGUIAPI void GuiLock(void); // Lock gui controls (global state) -RAYGUIAPI void GuiUnlock(void); // Unlock gui controls (global state) -RAYGUIAPI bool GuiIsLocked(void); // Check if gui is locked (global state) -RAYGUIAPI void GuiSetAlpha(float alpha); // Set gui controls alpha (global state), alpha goes from 0.0f to 1.0f -RAYGUIAPI void GuiSetState(int state); // Set gui state (global state) -RAYGUIAPI int GuiGetState(void); // Get gui state (global state) - -// Font set/get functions -RAYGUIAPI void GuiSetFont(Font font); // Set gui custom font (global state) -RAYGUIAPI Font GuiGetFont(void); // Get gui custom font (global state) - -// Style set/get functions -RAYGUIAPI void GuiSetStyle(int control, int property, int value); // Set one style property -RAYGUIAPI int GuiGetStyle(int control, int property); // Get one style property - -// Styles loading functions -RAYGUIAPI void GuiLoadStyle(const char *fileName); // Load style file over global style variable (.rgs) -RAYGUIAPI void GuiLoadStyleDefault(void); // Load style default over global style - -// Tooltips management functions -RAYGUIAPI void GuiEnableTooltip(void); // Enable gui tooltips (global state) -RAYGUIAPI void GuiDisableTooltip(void); // Disable gui tooltips (global state) -RAYGUIAPI void GuiSetTooltip(const char *tooltip); // Set tooltip string - -// Icons functionality -RAYGUIAPI const char *GuiIconText(int iconId, const char *text); // Get text with icon id prepended (if supported) -#if !defined(RAYGUI_NO_ICONS) -RAYGUIAPI void GuiSetIconScale(int scale); // Set default icon drawing size -RAYGUIAPI unsigned int *GuiGetIcons(void); // Get raygui icons data pointer -RAYGUIAPI char **GuiLoadIcons(const char *fileName, bool loadIconsName); // Load raygui icons file (.rgi) into internal icons data -RAYGUIAPI void GuiDrawIcon(int iconId, int posX, int posY, int pixelSize, Color color); // Draw icon using pixel size at specified position -#endif - -// Controls -//---------------------------------------------------------------------------------------------------------- -// Container/separator controls, useful for controls organization -RAYGUIAPI int GuiWindowBox(Rectangle bounds, const char *title); // Window Box control, shows a window that can be closed -RAYGUIAPI int GuiGroupBox(Rectangle bounds, const char *text); // Group Box control with text name -RAYGUIAPI int GuiLine(Rectangle bounds, const char *text); // Line separator control, could contain text -RAYGUIAPI int GuiPanel(Rectangle bounds, const char *text); // Panel control, useful to group controls -RAYGUIAPI int GuiTabBar(Rectangle bounds, const char **text, int count, int *active); // Tab Bar control, returns TAB to be closed or -1 -RAYGUIAPI int GuiScrollPanel(Rectangle bounds, const char *text, Rectangle content, Vector2 *scroll, Rectangle *view); // Scroll Panel control - -// Basic controls set -RAYGUIAPI int GuiLabel(Rectangle bounds, const char *text); // Label control -RAYGUIAPI int GuiButton(Rectangle bounds, const char *text); // Button control, returns true when clicked -RAYGUIAPI int GuiLabelButton(Rectangle bounds, const char *text); // Label button control, returns true when clicked -RAYGUIAPI int GuiToggle(Rectangle bounds, const char *text, bool *active); // Toggle Button control -RAYGUIAPI int GuiToggleGroup(Rectangle bounds, const char *text, int *active); // Toggle Group control -RAYGUIAPI int GuiToggleSlider(Rectangle bounds, const char *text, int *active); // Toggle Slider control -RAYGUIAPI int GuiCheckBox(Rectangle bounds, const char *text, bool *checked); // Check Box control, returns true when active -RAYGUIAPI int GuiComboBox(Rectangle bounds, const char *text, int *active); // Combo Box control - -RAYGUIAPI int GuiDropdownBox(Rectangle bounds, const char *text, int *active, bool editMode); // Dropdown Box control -RAYGUIAPI int GuiSpinner(Rectangle bounds, const char *text, int *value, int minValue, int maxValue, bool editMode); // Spinner control -RAYGUIAPI int GuiValueBox(Rectangle bounds, const char *text, int *value, int minValue, int maxValue, bool editMode); // Value Box control, updates input text with numbers -RAYGUIAPI int GuiValueBoxFloat(Rectangle bounds, const char *text, char *textValue, float *value, bool editMode); // Value box control for float values -RAYGUIAPI int GuiTextBox(Rectangle bounds, char *text, int textSize, bool editMode); // Text Box control, updates input text - -RAYGUIAPI int GuiSlider(Rectangle bounds, const char *textLeft, const char *textRight, float *value, float minValue, float maxValue); // Slider control -RAYGUIAPI int GuiSliderBar(Rectangle bounds, const char *textLeft, const char *textRight, float *value, float minValue, float maxValue); // Slider Bar control -RAYGUIAPI int GuiProgressBar(Rectangle bounds, const char *textLeft, const char *textRight, float *value, float minValue, float maxValue); // Progress Bar control -RAYGUIAPI int GuiStatusBar(Rectangle bounds, const char *text); // Status Bar control, shows info text -RAYGUIAPI int GuiDummyRec(Rectangle bounds, const char *text); // Dummy control for placeholders -RAYGUIAPI int GuiGrid(Rectangle bounds, const char *text, float spacing, int subdivs, Vector2 *mouseCell); // Grid control - -// Advance controls set -RAYGUIAPI int GuiListView(Rectangle bounds, const char *text, int *scrollIndex, int *active); // List View control -RAYGUIAPI int GuiListViewEx(Rectangle bounds, const char **text, int count, int *scrollIndex, int *active, int *focus); // List View with extended parameters -RAYGUIAPI int GuiMessageBox(Rectangle bounds, const char *title, const char *message, const char *buttons); // Message Box control, displays a message -RAYGUIAPI int GuiTextInputBox(Rectangle bounds, const char *title, const char *message, const char *buttons, char *text, int textMaxSize, bool *secretViewActive); // Text Input Box control, ask for text, supports secret -RAYGUIAPI int GuiColorPicker(Rectangle bounds, const char *text, Color *color); // Color Picker control (multiple color controls) -RAYGUIAPI int GuiColorPanel(Rectangle bounds, const char *text, Color *color); // Color Panel control -RAYGUIAPI int GuiColorBarAlpha(Rectangle bounds, const char *text, float *alpha); // Color Bar Alpha control -RAYGUIAPI int GuiColorBarHue(Rectangle bounds, const char *text, float *value); // Color Bar Hue control -RAYGUIAPI int GuiColorPickerHSV(Rectangle bounds, const char *text, Vector3 *colorHsv); // Color Picker control that avoids conversion to RGB on each call (multiple color controls) -RAYGUIAPI int GuiColorPanelHSV(Rectangle bounds, const char *text, Vector3 *colorHsv); // Color Panel control that updates Hue-Saturation-Value color value, used by GuiColorPickerHSV() -//---------------------------------------------------------------------------------------------------------- - -#if !defined(RAYGUI_NO_ICONS) - -#if !defined(RAYGUI_CUSTOM_ICONS) -//---------------------------------------------------------------------------------- -// Icons enumeration -//---------------------------------------------------------------------------------- -typedef enum { - ICON_NONE = 0, - ICON_FOLDER_FILE_OPEN = 1, - ICON_FILE_SAVE_CLASSIC = 2, - ICON_FOLDER_OPEN = 3, - ICON_FOLDER_SAVE = 4, - ICON_FILE_OPEN = 5, - ICON_FILE_SAVE = 6, - ICON_FILE_EXPORT = 7, - ICON_FILE_ADD = 8, - ICON_FILE_DELETE = 9, - ICON_FILETYPE_TEXT = 10, - ICON_FILETYPE_AUDIO = 11, - ICON_FILETYPE_IMAGE = 12, - ICON_FILETYPE_PLAY = 13, - ICON_FILETYPE_VIDEO = 14, - ICON_FILETYPE_INFO = 15, - ICON_FILE_COPY = 16, - ICON_FILE_CUT = 17, - ICON_FILE_PASTE = 18, - ICON_CURSOR_HAND = 19, - ICON_CURSOR_POINTER = 20, - ICON_CURSOR_CLASSIC = 21, - ICON_PENCIL = 22, - ICON_PENCIL_BIG = 23, - ICON_BRUSH_CLASSIC = 24, - ICON_BRUSH_PAINTER = 25, - ICON_WATER_DROP = 26, - ICON_COLOR_PICKER = 27, - ICON_RUBBER = 28, - ICON_COLOR_BUCKET = 29, - ICON_TEXT_T = 30, - ICON_TEXT_A = 31, - ICON_SCALE = 32, - ICON_RESIZE = 33, - ICON_FILTER_POINT = 34, - ICON_FILTER_BILINEAR = 35, - ICON_CROP = 36, - ICON_CROP_ALPHA = 37, - ICON_SQUARE_TOGGLE = 38, - ICON_SYMMETRY = 39, - ICON_SYMMETRY_HORIZONTAL = 40, - ICON_SYMMETRY_VERTICAL = 41, - ICON_LENS = 42, - ICON_LENS_BIG = 43, - ICON_EYE_ON = 44, - ICON_EYE_OFF = 45, - ICON_FILTER_TOP = 46, - ICON_FILTER = 47, - ICON_TARGET_POINT = 48, - ICON_TARGET_SMALL = 49, - ICON_TARGET_BIG = 50, - ICON_TARGET_MOVE = 51, - ICON_CURSOR_MOVE = 52, - ICON_CURSOR_SCALE = 53, - ICON_CURSOR_SCALE_RIGHT = 54, - ICON_CURSOR_SCALE_LEFT = 55, - ICON_UNDO = 56, - ICON_REDO = 57, - ICON_REREDO = 58, - ICON_MUTATE = 59, - ICON_ROTATE = 60, - ICON_REPEAT = 61, - ICON_SHUFFLE = 62, - ICON_EMPTYBOX = 63, - ICON_TARGET = 64, - ICON_TARGET_SMALL_FILL = 65, - ICON_TARGET_BIG_FILL = 66, - ICON_TARGET_MOVE_FILL = 67, - ICON_CURSOR_MOVE_FILL = 68, - ICON_CURSOR_SCALE_FILL = 69, - ICON_CURSOR_SCALE_RIGHT_FILL = 70, - ICON_CURSOR_SCALE_LEFT_FILL = 71, - ICON_UNDO_FILL = 72, - ICON_REDO_FILL = 73, - ICON_REREDO_FILL = 74, - ICON_MUTATE_FILL = 75, - ICON_ROTATE_FILL = 76, - ICON_REPEAT_FILL = 77, - ICON_SHUFFLE_FILL = 78, - ICON_EMPTYBOX_SMALL = 79, - ICON_BOX = 80, - ICON_BOX_TOP = 81, - ICON_BOX_TOP_RIGHT = 82, - ICON_BOX_RIGHT = 83, - ICON_BOX_BOTTOM_RIGHT = 84, - ICON_BOX_BOTTOM = 85, - ICON_BOX_BOTTOM_LEFT = 86, - ICON_BOX_LEFT = 87, - ICON_BOX_TOP_LEFT = 88, - ICON_BOX_CENTER = 89, - ICON_BOX_CIRCLE_MASK = 90, - ICON_POT = 91, - ICON_ALPHA_MULTIPLY = 92, - ICON_ALPHA_CLEAR = 93, - ICON_DITHERING = 94, - ICON_MIPMAPS = 95, - ICON_BOX_GRID = 96, - ICON_GRID = 97, - ICON_BOX_CORNERS_SMALL = 98, - ICON_BOX_CORNERS_BIG = 99, - ICON_FOUR_BOXES = 100, - ICON_GRID_FILL = 101, - ICON_BOX_MULTISIZE = 102, - ICON_ZOOM_SMALL = 103, - ICON_ZOOM_MEDIUM = 104, - ICON_ZOOM_BIG = 105, - ICON_ZOOM_ALL = 106, - ICON_ZOOM_CENTER = 107, - ICON_BOX_DOTS_SMALL = 108, - ICON_BOX_DOTS_BIG = 109, - ICON_BOX_CONCENTRIC = 110, - ICON_BOX_GRID_BIG = 111, - ICON_OK_TICK = 112, - ICON_CROSS = 113, - ICON_ARROW_LEFT = 114, - ICON_ARROW_RIGHT = 115, - ICON_ARROW_DOWN = 116, - ICON_ARROW_UP = 117, - ICON_ARROW_LEFT_FILL = 118, - ICON_ARROW_RIGHT_FILL = 119, - ICON_ARROW_DOWN_FILL = 120, - ICON_ARROW_UP_FILL = 121, - ICON_AUDIO = 122, - ICON_FX = 123, - ICON_WAVE = 124, - ICON_WAVE_SINUS = 125, - ICON_WAVE_SQUARE = 126, - ICON_WAVE_TRIANGULAR = 127, - ICON_CROSS_SMALL = 128, - ICON_PLAYER_PREVIOUS = 129, - ICON_PLAYER_PLAY_BACK = 130, - ICON_PLAYER_PLAY = 131, - ICON_PLAYER_PAUSE = 132, - ICON_PLAYER_STOP = 133, - ICON_PLAYER_NEXT = 134, - ICON_PLAYER_RECORD = 135, - ICON_MAGNET = 136, - ICON_LOCK_CLOSE = 137, - ICON_LOCK_OPEN = 138, - ICON_CLOCK = 139, - ICON_TOOLS = 140, - ICON_GEAR = 141, - ICON_GEAR_BIG = 142, - ICON_BIN = 143, - ICON_HAND_POINTER = 144, - ICON_LASER = 145, - ICON_COIN = 146, - ICON_EXPLOSION = 147, - ICON_1UP = 148, - ICON_PLAYER = 149, - ICON_PLAYER_JUMP = 150, - ICON_KEY = 151, - ICON_DEMON = 152, - ICON_TEXT_POPUP = 153, - ICON_GEAR_EX = 154, - ICON_CRACK = 155, - ICON_CRACK_POINTS = 156, - ICON_STAR = 157, - ICON_DOOR = 158, - ICON_EXIT = 159, - ICON_MODE_2D = 160, - ICON_MODE_3D = 161, - ICON_CUBE = 162, - ICON_CUBE_FACE_TOP = 163, - ICON_CUBE_FACE_LEFT = 164, - ICON_CUBE_FACE_FRONT = 165, - ICON_CUBE_FACE_BOTTOM = 166, - ICON_CUBE_FACE_RIGHT = 167, - ICON_CUBE_FACE_BACK = 168, - ICON_CAMERA = 169, - ICON_SPECIAL = 170, - ICON_LINK_NET = 171, - ICON_LINK_BOXES = 172, - ICON_LINK_MULTI = 173, - ICON_LINK = 174, - ICON_LINK_BROKE = 175, - ICON_TEXT_NOTES = 176, - ICON_NOTEBOOK = 177, - ICON_SUITCASE = 178, - ICON_SUITCASE_ZIP = 179, - ICON_MAILBOX = 180, - ICON_MONITOR = 181, - ICON_PRINTER = 182, - ICON_PHOTO_CAMERA = 183, - ICON_PHOTO_CAMERA_FLASH = 184, - ICON_HOUSE = 185, - ICON_HEART = 186, - ICON_CORNER = 187, - ICON_VERTICAL_BARS = 188, - ICON_VERTICAL_BARS_FILL = 189, - ICON_LIFE_BARS = 190, - ICON_INFO = 191, - ICON_CROSSLINE = 192, - ICON_HELP = 193, - ICON_FILETYPE_ALPHA = 194, - ICON_FILETYPE_HOME = 195, - ICON_LAYERS_VISIBLE = 196, - ICON_LAYERS = 197, - ICON_WINDOW = 198, - ICON_HIDPI = 199, - ICON_FILETYPE_BINARY = 200, - ICON_HEX = 201, - ICON_SHIELD = 202, - ICON_FILE_NEW = 203, - ICON_FOLDER_ADD = 204, - ICON_ALARM = 205, - ICON_CPU = 206, - ICON_ROM = 207, - ICON_STEP_OVER = 208, - ICON_STEP_INTO = 209, - ICON_STEP_OUT = 210, - ICON_RESTART = 211, - ICON_BREAKPOINT_ON = 212, - ICON_BREAKPOINT_OFF = 213, - ICON_BURGER_MENU = 214, - ICON_CASE_SENSITIVE = 215, - ICON_REG_EXP = 216, - ICON_FOLDER = 217, - ICON_FILE = 218, - ICON_SAND_TIMER = 219, - ICON_WARNING = 220, - ICON_HELP_BOX = 221, - ICON_INFO_BOX = 222, - ICON_PRIORITY = 223, - ICON_LAYERS_ISO = 224, - ICON_LAYERS2 = 225, - ICON_MLAYERS = 226, - ICON_MAPS = 227, - ICON_HOT = 228, - ICON_229 = 229, - ICON_230 = 230, - ICON_231 = 231, - ICON_232 = 232, - ICON_233 = 233, - ICON_234 = 234, - ICON_235 = 235, - ICON_236 = 236, - ICON_237 = 237, - ICON_238 = 238, - ICON_239 = 239, - ICON_240 = 240, - ICON_241 = 241, - ICON_242 = 242, - ICON_243 = 243, - ICON_244 = 244, - ICON_245 = 245, - ICON_246 = 246, - ICON_247 = 247, - ICON_248 = 248, - ICON_249 = 249, - ICON_250 = 250, - ICON_251 = 251, - ICON_252 = 252, - ICON_253 = 253, - ICON_254 = 254, - ICON_255 = 255, -} GuiIconName; -#endif - -#endif - -#if defined(__cplusplus) -} // Prevents name mangling of functions -#endif - -#endif // RAYGUI_H - -/*********************************************************************************** -* -* RAYGUI IMPLEMENTATION -* -************************************************************************************/ - -#if defined(RAYGUI_IMPLEMENTATION) - -#include // required for: isspace() [GuiTextBox()] -#include // Required for: FILE, fopen(), fclose(), fprintf(), feof(), fscanf(), vsprintf() [GuiLoadStyle(), GuiLoadIcons()] -#include // Required for: malloc(), calloc(), free() [GuiLoadStyle(), GuiLoadIcons()] -#include // Required for: strlen() [GuiTextBox(), GuiValueBox()], memset(), memcpy() -#include // Required for: va_list, va_start(), vfprintf(), va_end() [TextFormat()] -#include // Required for: roundf() [GuiColorPicker()] - -#ifdef __cplusplus - #define RAYGUI_CLITERAL(name) name -#else - #define RAYGUI_CLITERAL(name) (name) -#endif - -// Check if two rectangles are equal, used to validate a slider bounds as an id -#ifndef CHECK_BOUNDS_ID - #define CHECK_BOUNDS_ID(src, dst) ((src.x == dst.x) && (src.y == dst.y) && (src.width == dst.width) && (src.height == dst.height)) -#endif - -#if !defined(RAYGUI_NO_ICONS) && !defined(RAYGUI_CUSTOM_ICONS) - -// Embedded icons, no external file provided -#define RAYGUI_ICON_SIZE 16 // Size of icons in pixels (squared) -#define RAYGUI_ICON_MAX_ICONS 256 // Maximum number of icons -#define RAYGUI_ICON_MAX_NAME_LENGTH 32 // Maximum length of icon name id - -// Icons data is defined by bit array (every bit represents one pixel) -// Those arrays are stored as unsigned int data arrays, so, -// every array element defines 32 pixels (bits) of information -// One icon is defined by 8 int, (8 int * 32 bit = 256 bit = 16*16 pixels) -// NOTE: Number of elemens depend on RAYGUI_ICON_SIZE (by default 16x16 pixels) -#define RAYGUI_ICON_DATA_ELEMENTS (RAYGUI_ICON_SIZE*RAYGUI_ICON_SIZE/32) - -//---------------------------------------------------------------------------------- -// Icons data for all gui possible icons (allocated on data segment by default) -// -// NOTE 1: Every icon is codified in binary form, using 1 bit per pixel, so, -// every 16x16 icon requires 8 integers (16*16/32) to be stored -// -// NOTE 2: A different icon set could be loaded over this array using GuiLoadIcons(), -// but loaded icons set must be same RAYGUI_ICON_SIZE and no more than RAYGUI_ICON_MAX_ICONS -// -// guiIcons size is by default: 256*(16*16/32) = 2048*4 = 8192 bytes = 8 KB -//---------------------------------------------------------------------------------- -static unsigned int guiIcons[RAYGUI_ICON_MAX_ICONS*RAYGUI_ICON_DATA_ELEMENTS] = { - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, // ICON_NONE - 0x3ff80000, 0x2f082008, 0x2042207e, 0x40027fc2, 0x40024002, 0x40024002, 0x40024002, 0x00007ffe, // ICON_FOLDER_FILE_OPEN - 0x3ffe0000, 0x44226422, 0x400247e2, 0x5ffa4002, 0x57ea500a, 0x500a500a, 0x40025ffa, 0x00007ffe, // ICON_FILE_SAVE_CLASSIC - 0x00000000, 0x0042007e, 0x40027fc2, 0x40024002, 0x41024002, 0x44424282, 0x793e4102, 0x00000100, // ICON_FOLDER_OPEN - 0x00000000, 0x0042007e, 0x40027fc2, 0x40024002, 0x41024102, 0x44424102, 0x793e4282, 0x00000000, // ICON_FOLDER_SAVE - 0x3ff00000, 0x201c2010, 0x20042004, 0x21042004, 0x24442284, 0x21042104, 0x20042104, 0x00003ffc, // ICON_FILE_OPEN - 0x3ff00000, 0x201c2010, 0x20042004, 0x21042004, 0x21042104, 0x22842444, 0x20042104, 0x00003ffc, // ICON_FILE_SAVE - 0x3ff00000, 0x201c2010, 0x00042004, 0x20041004, 0x20844784, 0x00841384, 0x20042784, 0x00003ffc, // ICON_FILE_EXPORT - 0x3ff00000, 0x201c2010, 0x20042004, 0x20042004, 0x22042204, 0x22042f84, 0x20042204, 0x00003ffc, // ICON_FILE_ADD - 0x3ff00000, 0x201c2010, 0x20042004, 0x20042004, 0x25042884, 0x25042204, 0x20042884, 0x00003ffc, // ICON_FILE_DELETE - 0x3ff00000, 0x201c2010, 0x20042004, 0x20042ff4, 0x20042ff4, 0x20042ff4, 0x20042004, 0x00003ffc, // ICON_FILETYPE_TEXT - 0x3ff00000, 0x201c2010, 0x27042004, 0x244424c4, 0x26442444, 0x20642664, 0x20042004, 0x00003ffc, // ICON_FILETYPE_AUDIO - 0x3ff00000, 0x201c2010, 0x26042604, 0x20042004, 0x35442884, 0x2414222c, 0x20042004, 0x00003ffc, // ICON_FILETYPE_IMAGE - 0x3ff00000, 0x201c2010, 0x20c42004, 0x22442144, 0x22442444, 0x20c42144, 0x20042004, 0x00003ffc, // ICON_FILETYPE_PLAY - 0x3ff00000, 0x3ffc2ff0, 0x3f3c2ff4, 0x3dbc2eb4, 0x3dbc2bb4, 0x3f3c2eb4, 0x3ffc2ff4, 0x00002ff4, // ICON_FILETYPE_VIDEO - 0x3ff00000, 0x201c2010, 0x21842184, 0x21842004, 0x21842184, 0x21842184, 0x20042184, 0x00003ffc, // ICON_FILETYPE_INFO - 0x0ff00000, 0x381c0810, 0x28042804, 0x28042804, 0x28042804, 0x28042804, 0x20102ffc, 0x00003ff0, // ICON_FILE_COPY - 0x00000000, 0x701c0000, 0x079c1e14, 0x55a000f0, 0x079c00f0, 0x701c1e14, 0x00000000, 0x00000000, // ICON_FILE_CUT - 0x01c00000, 0x13e41bec, 0x3f841004, 0x204420c4, 0x20442044, 0x20442044, 0x207c2044, 0x00003fc0, // ICON_FILE_PASTE - 0x00000000, 0x3aa00fe0, 0x2abc2aa0, 0x2aa42aa4, 0x20042aa4, 0x20042004, 0x3ffc2004, 0x00000000, // ICON_CURSOR_HAND - 0x00000000, 0x003c000c, 0x030800c8, 0x30100c10, 0x10202020, 0x04400840, 0x01800280, 0x00000000, // ICON_CURSOR_POINTER - 0x00000000, 0x00180000, 0x01f00078, 0x03e007f0, 0x07c003e0, 0x04000e40, 0x00000000, 0x00000000, // ICON_CURSOR_CLASSIC - 0x00000000, 0x04000000, 0x11000a00, 0x04400a80, 0x01100220, 0x00580088, 0x00000038, 0x00000000, // ICON_PENCIL - 0x04000000, 0x15000a00, 0x50402880, 0x14102820, 0x05040a08, 0x015c028c, 0x007c00bc, 0x00000000, // ICON_PENCIL_BIG - 0x01c00000, 0x01400140, 0x01400140, 0x0ff80140, 0x0ff80808, 0x0aa80808, 0x0aa80aa8, 0x00000ff8, // ICON_BRUSH_CLASSIC - 0x1ffc0000, 0x5ffc7ffe, 0x40004000, 0x00807f80, 0x01c001c0, 0x01c001c0, 0x01c001c0, 0x00000080, // ICON_BRUSH_PAINTER - 0x00000000, 0x00800000, 0x01c00080, 0x03e001c0, 0x07f003e0, 0x036006f0, 0x000001c0, 0x00000000, // ICON_WATER_DROP - 0x00000000, 0x3e003800, 0x1f803f80, 0x0c201e40, 0x02080c10, 0x00840104, 0x00380044, 0x00000000, // ICON_COLOR_PICKER - 0x00000000, 0x07800300, 0x1fe00fc0, 0x3f883fd0, 0x0e021f04, 0x02040402, 0x00f00108, 0x00000000, // ICON_RUBBER - 0x00c00000, 0x02800140, 0x08200440, 0x20081010, 0x2ffe3004, 0x03f807fc, 0x00e001f0, 0x00000040, // ICON_COLOR_BUCKET - 0x00000000, 0x21843ffc, 0x01800180, 0x01800180, 0x01800180, 0x01800180, 0x03c00180, 0x00000000, // ICON_TEXT_T - 0x00800000, 0x01400180, 0x06200340, 0x0c100620, 0x1ff80c10, 0x380c1808, 0x70067004, 0x0000f80f, // ICON_TEXT_A - 0x78000000, 0x50004000, 0x00004800, 0x03c003c0, 0x03c003c0, 0x00100000, 0x0002000a, 0x0000000e, // ICON_SCALE - 0x75560000, 0x5e004002, 0x54001002, 0x41001202, 0x408200fe, 0x40820082, 0x40820082, 0x00006afe, // ICON_RESIZE - 0x00000000, 0x3f003f00, 0x3f003f00, 0x3f003f00, 0x00400080, 0x001c0020, 0x001c001c, 0x00000000, // ICON_FILTER_POINT - 0x6d800000, 0x00004080, 0x40804080, 0x40800000, 0x00406d80, 0x001c0020, 0x001c001c, 0x00000000, // ICON_FILTER_BILINEAR - 0x40080000, 0x1ffe2008, 0x14081008, 0x11081208, 0x10481088, 0x10081028, 0x10047ff8, 0x00001002, // ICON_CROP - 0x00100000, 0x3ffc0010, 0x2ab03550, 0x22b02550, 0x20b02150, 0x20302050, 0x2000fff0, 0x00002000, // ICON_CROP_ALPHA - 0x40000000, 0x1ff82000, 0x04082808, 0x01082208, 0x00482088, 0x00182028, 0x35542008, 0x00000002, // ICON_SQUARE_TOGGLE - 0x00000000, 0x02800280, 0x06c006c0, 0x0ea00ee0, 0x1e901eb0, 0x3e883e98, 0x7efc7e8c, 0x00000000, // ICON_SYMMETRY - 0x01000000, 0x05600100, 0x1d480d50, 0x7d423d44, 0x3d447d42, 0x0d501d48, 0x01000560, 0x00000100, // ICON_SYMMETRY_HORIZONTAL - 0x01800000, 0x04200240, 0x10080810, 0x00001ff8, 0x00007ffe, 0x0ff01ff8, 0x03c007e0, 0x00000180, // ICON_SYMMETRY_VERTICAL - 0x00000000, 0x010800f0, 0x02040204, 0x02040204, 0x07f00308, 0x1c000e00, 0x30003800, 0x00000000, // ICON_LENS - 0x00000000, 0x061803f0, 0x08240c0c, 0x08040814, 0x0c0c0804, 0x23f01618, 0x18002400, 0x00000000, // ICON_LENS_BIG - 0x00000000, 0x00000000, 0x1c7007c0, 0x638e3398, 0x1c703398, 0x000007c0, 0x00000000, 0x00000000, // ICON_EYE_ON - 0x00000000, 0x10002000, 0x04700fc0, 0x610e3218, 0x1c703098, 0x001007a0, 0x00000008, 0x00000000, // ICON_EYE_OFF - 0x00000000, 0x00007ffc, 0x40047ffc, 0x10102008, 0x04400820, 0x02800280, 0x02800280, 0x00000100, // ICON_FILTER_TOP - 0x00000000, 0x40027ffe, 0x10082004, 0x04200810, 0x02400240, 0x02400240, 0x01400240, 0x000000c0, // ICON_FILTER - 0x00800000, 0x00800080, 0x00000080, 0x3c9e0000, 0x00000000, 0x00800080, 0x00800080, 0x00000000, // ICON_TARGET_POINT - 0x00800000, 0x00800080, 0x00800080, 0x3f7e01c0, 0x008001c0, 0x00800080, 0x00800080, 0x00000000, // ICON_TARGET_SMALL - 0x00800000, 0x00800080, 0x03e00080, 0x3e3e0220, 0x03e00220, 0x00800080, 0x00800080, 0x00000000, // ICON_TARGET_BIG - 0x01000000, 0x04400280, 0x01000100, 0x43842008, 0x43849ab2, 0x01002008, 0x04400100, 0x01000280, // ICON_TARGET_MOVE - 0x01000000, 0x04400280, 0x01000100, 0x41042108, 0x41049ff2, 0x01002108, 0x04400100, 0x01000280, // ICON_CURSOR_MOVE - 0x781e0000, 0x500a4002, 0x04204812, 0x00000240, 0x02400000, 0x48120420, 0x4002500a, 0x0000781e, // ICON_CURSOR_SCALE - 0x00000000, 0x20003c00, 0x24002800, 0x01000200, 0x00400080, 0x00140024, 0x003c0004, 0x00000000, // ICON_CURSOR_SCALE_RIGHT - 0x00000000, 0x0004003c, 0x00240014, 0x00800040, 0x02000100, 0x28002400, 0x3c002000, 0x00000000, // ICON_CURSOR_SCALE_LEFT - 0x00000000, 0x00100020, 0x10101fc8, 0x10001020, 0x10001000, 0x10001000, 0x00001fc0, 0x00000000, // ICON_UNDO - 0x00000000, 0x08000400, 0x080813f8, 0x00080408, 0x00080008, 0x00080008, 0x000003f8, 0x00000000, // ICON_REDO - 0x00000000, 0x3ffc0000, 0x20042004, 0x20002000, 0x20402000, 0x3f902020, 0x00400020, 0x00000000, // ICON_REREDO - 0x00000000, 0x3ffc0000, 0x20042004, 0x27fc2004, 0x20202000, 0x3fc82010, 0x00200010, 0x00000000, // ICON_MUTATE - 0x00000000, 0x0ff00000, 0x10081818, 0x11801008, 0x10001180, 0x18101020, 0x00100fc8, 0x00000020, // ICON_ROTATE - 0x00000000, 0x04000200, 0x240429fc, 0x20042204, 0x20442004, 0x3f942024, 0x00400020, 0x00000000, // ICON_REPEAT - 0x00000000, 0x20001000, 0x22104c0e, 0x00801120, 0x11200040, 0x4c0e2210, 0x10002000, 0x00000000, // ICON_SHUFFLE - 0x7ffe0000, 0x50024002, 0x44024802, 0x41024202, 0x40424082, 0x40124022, 0x4002400a, 0x00007ffe, // ICON_EMPTYBOX - 0x00800000, 0x03e00080, 0x08080490, 0x3c9e0808, 0x08080808, 0x03e00490, 0x00800080, 0x00000000, // ICON_TARGET - 0x00800000, 0x00800080, 0x00800080, 0x3ffe01c0, 0x008001c0, 0x00800080, 0x00800080, 0x00000000, // ICON_TARGET_SMALL_FILL - 0x00800000, 0x00800080, 0x03e00080, 0x3ffe03e0, 0x03e003e0, 0x00800080, 0x00800080, 0x00000000, // ICON_TARGET_BIG_FILL - 0x01000000, 0x07c00380, 0x01000100, 0x638c2008, 0x638cfbbe, 0x01002008, 0x07c00100, 0x01000380, // ICON_TARGET_MOVE_FILL - 0x01000000, 0x07c00380, 0x01000100, 0x610c2108, 0x610cfffe, 0x01002108, 0x07c00100, 0x01000380, // ICON_CURSOR_MOVE_FILL - 0x781e0000, 0x6006700e, 0x04204812, 0x00000240, 0x02400000, 0x48120420, 0x700e6006, 0x0000781e, // ICON_CURSOR_SCALE_FILL - 0x00000000, 0x38003c00, 0x24003000, 0x01000200, 0x00400080, 0x000c0024, 0x003c001c, 0x00000000, // ICON_CURSOR_SCALE_RIGHT_FILL - 0x00000000, 0x001c003c, 0x0024000c, 0x00800040, 0x02000100, 0x30002400, 0x3c003800, 0x00000000, // ICON_CURSOR_SCALE_LEFT_FILL - 0x00000000, 0x00300020, 0x10301ff8, 0x10001020, 0x10001000, 0x10001000, 0x00001fc0, 0x00000000, // ICON_UNDO_FILL - 0x00000000, 0x0c000400, 0x0c081ff8, 0x00080408, 0x00080008, 0x00080008, 0x000003f8, 0x00000000, // ICON_REDO_FILL - 0x00000000, 0x3ffc0000, 0x20042004, 0x20002000, 0x20402000, 0x3ff02060, 0x00400060, 0x00000000, // ICON_REREDO_FILL - 0x00000000, 0x3ffc0000, 0x20042004, 0x27fc2004, 0x20202000, 0x3ff82030, 0x00200030, 0x00000000, // ICON_MUTATE_FILL - 0x00000000, 0x0ff00000, 0x10081818, 0x11801008, 0x10001180, 0x18301020, 0x00300ff8, 0x00000020, // ICON_ROTATE_FILL - 0x00000000, 0x06000200, 0x26042ffc, 0x20042204, 0x20442004, 0x3ff42064, 0x00400060, 0x00000000, // ICON_REPEAT_FILL - 0x00000000, 0x30001000, 0x32107c0e, 0x00801120, 0x11200040, 0x7c0e3210, 0x10003000, 0x00000000, // ICON_SHUFFLE_FILL - 0x00000000, 0x30043ffc, 0x24042804, 0x21042204, 0x20442084, 0x20142024, 0x3ffc200c, 0x00000000, // ICON_EMPTYBOX_SMALL - 0x00000000, 0x20043ffc, 0x20042004, 0x20042004, 0x20042004, 0x20042004, 0x3ffc2004, 0x00000000, // ICON_BOX - 0x00000000, 0x23c43ffc, 0x23c423c4, 0x200423c4, 0x20042004, 0x20042004, 0x3ffc2004, 0x00000000, // ICON_BOX_TOP - 0x00000000, 0x3e043ffc, 0x3e043e04, 0x20043e04, 0x20042004, 0x20042004, 0x3ffc2004, 0x00000000, // ICON_BOX_TOP_RIGHT - 0x00000000, 0x20043ffc, 0x20042004, 0x3e043e04, 0x3e043e04, 0x20042004, 0x3ffc2004, 0x00000000, // ICON_BOX_RIGHT - 0x00000000, 0x20043ffc, 0x20042004, 0x20042004, 0x3e042004, 0x3e043e04, 0x3ffc3e04, 0x00000000, // ICON_BOX_BOTTOM_RIGHT - 0x00000000, 0x20043ffc, 0x20042004, 0x20042004, 0x23c42004, 0x23c423c4, 0x3ffc23c4, 0x00000000, // ICON_BOX_BOTTOM - 0x00000000, 0x20043ffc, 0x20042004, 0x20042004, 0x207c2004, 0x207c207c, 0x3ffc207c, 0x00000000, // ICON_BOX_BOTTOM_LEFT - 0x00000000, 0x20043ffc, 0x20042004, 0x207c207c, 0x207c207c, 0x20042004, 0x3ffc2004, 0x00000000, // ICON_BOX_LEFT - 0x00000000, 0x207c3ffc, 0x207c207c, 0x2004207c, 0x20042004, 0x20042004, 0x3ffc2004, 0x00000000, // ICON_BOX_TOP_LEFT - 0x00000000, 0x20043ffc, 0x20042004, 0x23c423c4, 0x23c423c4, 0x20042004, 0x3ffc2004, 0x00000000, // ICON_BOX_CENTER - 0x7ffe0000, 0x40024002, 0x47e24182, 0x4ff247e2, 0x47e24ff2, 0x418247e2, 0x40024002, 0x00007ffe, // ICON_BOX_CIRCLE_MASK - 0x7fff0000, 0x40014001, 0x40014001, 0x49555ddd, 0x4945495d, 0x400149c5, 0x40014001, 0x00007fff, // ICON_POT - 0x7ffe0000, 0x53327332, 0x44ce4cce, 0x41324332, 0x404e40ce, 0x48125432, 0x4006540e, 0x00007ffe, // ICON_ALPHA_MULTIPLY - 0x7ffe0000, 0x53327332, 0x44ce4cce, 0x41324332, 0x5c4e40ce, 0x44124432, 0x40065c0e, 0x00007ffe, // ICON_ALPHA_CLEAR - 0x7ffe0000, 0x42fe417e, 0x42fe417e, 0x42fe417e, 0x42fe417e, 0x42fe417e, 0x42fe417e, 0x00007ffe, // ICON_DITHERING - 0x07fe0000, 0x1ffa0002, 0x7fea000a, 0x402a402a, 0x5b2a512a, 0x5128552a, 0x40205128, 0x00007fe0, // ICON_MIPMAPS - 0x00000000, 0x1ff80000, 0x12481248, 0x12481ff8, 0x1ff81248, 0x12481248, 0x00001ff8, 0x00000000, // ICON_BOX_GRID - 0x12480000, 0x7ffe1248, 0x12481248, 0x12487ffe, 0x7ffe1248, 0x12481248, 0x12487ffe, 0x00001248, // ICON_GRID - 0x00000000, 0x1c380000, 0x1c3817e8, 0x08100810, 0x08100810, 0x17e81c38, 0x00001c38, 0x00000000, // ICON_BOX_CORNERS_SMALL - 0x700e0000, 0x700e5ffa, 0x20042004, 0x20042004, 0x20042004, 0x20042004, 0x5ffa700e, 0x0000700e, // ICON_BOX_CORNERS_BIG - 0x3f7e0000, 0x21422142, 0x21422142, 0x00003f7e, 0x21423f7e, 0x21422142, 0x3f7e2142, 0x00000000, // ICON_FOUR_BOXES - 0x00000000, 0x3bb80000, 0x3bb83bb8, 0x3bb80000, 0x3bb83bb8, 0x3bb80000, 0x3bb83bb8, 0x00000000, // ICON_GRID_FILL - 0x7ffe0000, 0x7ffe7ffe, 0x77fe7000, 0x77fe77fe, 0x777e7700, 0x777e777e, 0x777e777e, 0x0000777e, // ICON_BOX_MULTISIZE - 0x781e0000, 0x40024002, 0x00004002, 0x01800000, 0x00000180, 0x40020000, 0x40024002, 0x0000781e, // ICON_ZOOM_SMALL - 0x781e0000, 0x40024002, 0x00004002, 0x03c003c0, 0x03c003c0, 0x40020000, 0x40024002, 0x0000781e, // ICON_ZOOM_MEDIUM - 0x781e0000, 0x40024002, 0x07e04002, 0x07e007e0, 0x07e007e0, 0x400207e0, 0x40024002, 0x0000781e, // ICON_ZOOM_BIG - 0x781e0000, 0x5ffa4002, 0x1ff85ffa, 0x1ff81ff8, 0x1ff81ff8, 0x5ffa1ff8, 0x40025ffa, 0x0000781e, // ICON_ZOOM_ALL - 0x00000000, 0x2004381c, 0x00002004, 0x00000000, 0x00000000, 0x20040000, 0x381c2004, 0x00000000, // ICON_ZOOM_CENTER - 0x00000000, 0x1db80000, 0x10081008, 0x10080000, 0x00001008, 0x10081008, 0x00001db8, 0x00000000, // ICON_BOX_DOTS_SMALL - 0x35560000, 0x00002002, 0x00002002, 0x00002002, 0x00002002, 0x00002002, 0x35562002, 0x00000000, // ICON_BOX_DOTS_BIG - 0x7ffe0000, 0x40024002, 0x48124ff2, 0x49924812, 0x48124992, 0x4ff24812, 0x40024002, 0x00007ffe, // ICON_BOX_CONCENTRIC - 0x00000000, 0x10841ffc, 0x10841084, 0x1ffc1084, 0x10841084, 0x10841084, 0x00001ffc, 0x00000000, // ICON_BOX_GRID_BIG - 0x00000000, 0x00000000, 0x10000000, 0x04000800, 0x01040200, 0x00500088, 0x00000020, 0x00000000, // ICON_OK_TICK - 0x00000000, 0x10080000, 0x04200810, 0x01800240, 0x02400180, 0x08100420, 0x00001008, 0x00000000, // ICON_CROSS - 0x00000000, 0x02000000, 0x00800100, 0x00200040, 0x00200010, 0x00800040, 0x02000100, 0x00000000, // ICON_ARROW_LEFT - 0x00000000, 0x00400000, 0x01000080, 0x04000200, 0x04000800, 0x01000200, 0x00400080, 0x00000000, // ICON_ARROW_RIGHT - 0x00000000, 0x00000000, 0x00000000, 0x08081004, 0x02200410, 0x00800140, 0x00000000, 0x00000000, // ICON_ARROW_DOWN - 0x00000000, 0x00000000, 0x01400080, 0x04100220, 0x10040808, 0x00000000, 0x00000000, 0x00000000, // ICON_ARROW_UP - 0x00000000, 0x02000000, 0x03800300, 0x03e003c0, 0x03e003f0, 0x038003c0, 0x02000300, 0x00000000, // ICON_ARROW_LEFT_FILL - 0x00000000, 0x00400000, 0x01c000c0, 0x07c003c0, 0x07c00fc0, 0x01c003c0, 0x004000c0, 0x00000000, // ICON_ARROW_RIGHT_FILL - 0x00000000, 0x00000000, 0x00000000, 0x0ff81ffc, 0x03e007f0, 0x008001c0, 0x00000000, 0x00000000, // ICON_ARROW_DOWN_FILL - 0x00000000, 0x00000000, 0x01c00080, 0x07f003e0, 0x1ffc0ff8, 0x00000000, 0x00000000, 0x00000000, // ICON_ARROW_UP_FILL - 0x00000000, 0x18a008c0, 0x32881290, 0x24822686, 0x26862482, 0x12903288, 0x08c018a0, 0x00000000, // ICON_AUDIO - 0x00000000, 0x04800780, 0x004000c0, 0x662000f0, 0x08103c30, 0x130a0e18, 0x0000318e, 0x00000000, // ICON_FX - 0x00000000, 0x00800000, 0x08880888, 0x2aaa0a8a, 0x0a8a2aaa, 0x08880888, 0x00000080, 0x00000000, // ICON_WAVE - 0x00000000, 0x00600000, 0x01080090, 0x02040108, 0x42044204, 0x24022402, 0x00001800, 0x00000000, // ICON_WAVE_SINUS - 0x00000000, 0x07f80000, 0x04080408, 0x04080408, 0x04080408, 0x7c0e0408, 0x00000000, 0x00000000, // ICON_WAVE_SQUARE - 0x00000000, 0x00000000, 0x00a00040, 0x22084110, 0x08021404, 0x00000000, 0x00000000, 0x00000000, // ICON_WAVE_TRIANGULAR - 0x00000000, 0x00000000, 0x04200000, 0x01800240, 0x02400180, 0x00000420, 0x00000000, 0x00000000, // ICON_CROSS_SMALL - 0x00000000, 0x18380000, 0x12281428, 0x10a81128, 0x112810a8, 0x14281228, 0x00001838, 0x00000000, // ICON_PLAYER_PREVIOUS - 0x00000000, 0x18000000, 0x11801600, 0x10181060, 0x10601018, 0x16001180, 0x00001800, 0x00000000, // ICON_PLAYER_PLAY_BACK - 0x00000000, 0x00180000, 0x01880068, 0x18080608, 0x06081808, 0x00680188, 0x00000018, 0x00000000, // ICON_PLAYER_PLAY - 0x00000000, 0x1e780000, 0x12481248, 0x12481248, 0x12481248, 0x12481248, 0x00001e78, 0x00000000, // ICON_PLAYER_PAUSE - 0x00000000, 0x1ff80000, 0x10081008, 0x10081008, 0x10081008, 0x10081008, 0x00001ff8, 0x00000000, // ICON_PLAYER_STOP - 0x00000000, 0x1c180000, 0x14481428, 0x15081488, 0x14881508, 0x14281448, 0x00001c18, 0x00000000, // ICON_PLAYER_NEXT - 0x00000000, 0x03c00000, 0x08100420, 0x10081008, 0x10081008, 0x04200810, 0x000003c0, 0x00000000, // ICON_PLAYER_RECORD - 0x00000000, 0x0c3007e0, 0x13c81818, 0x14281668, 0x14281428, 0x1c381c38, 0x08102244, 0x00000000, // ICON_MAGNET - 0x07c00000, 0x08200820, 0x3ff80820, 0x23882008, 0x21082388, 0x20082108, 0x1ff02008, 0x00000000, // ICON_LOCK_CLOSE - 0x07c00000, 0x08000800, 0x3ff80800, 0x23882008, 0x21082388, 0x20082108, 0x1ff02008, 0x00000000, // ICON_LOCK_OPEN - 0x01c00000, 0x0c180770, 0x3086188c, 0x60832082, 0x60034781, 0x30062002, 0x0c18180c, 0x01c00770, // ICON_CLOCK - 0x0a200000, 0x1b201b20, 0x04200e20, 0x04200420, 0x04700420, 0x0e700e70, 0x0e700e70, 0x04200e70, // ICON_TOOLS - 0x01800000, 0x3bdc318c, 0x0ff01ff8, 0x7c3e1e78, 0x1e787c3e, 0x1ff80ff0, 0x318c3bdc, 0x00000180, // ICON_GEAR - 0x01800000, 0x3ffc318c, 0x1c381ff8, 0x781e1818, 0x1818781e, 0x1ff81c38, 0x318c3ffc, 0x00000180, // ICON_GEAR_BIG - 0x00000000, 0x08080ff8, 0x08081ffc, 0x0aa80aa8, 0x0aa80aa8, 0x0aa80aa8, 0x08080aa8, 0x00000ff8, // ICON_BIN - 0x00000000, 0x00000000, 0x20043ffc, 0x08043f84, 0x04040f84, 0x04040784, 0x000007fc, 0x00000000, // ICON_HAND_POINTER - 0x00000000, 0x24400400, 0x00001480, 0x6efe0e00, 0x00000e00, 0x24401480, 0x00000400, 0x00000000, // ICON_LASER - 0x00000000, 0x03c00000, 0x08300460, 0x11181118, 0x11181118, 0x04600830, 0x000003c0, 0x00000000, // ICON_COIN - 0x00000000, 0x10880080, 0x06c00810, 0x366c07e0, 0x07e00240, 0x00001768, 0x04200240, 0x00000000, // ICON_EXPLOSION - 0x00000000, 0x3d280000, 0x2528252c, 0x3d282528, 0x05280528, 0x05e80528, 0x00000000, 0x00000000, // ICON_1UP - 0x01800000, 0x03c003c0, 0x018003c0, 0x0ff007e0, 0x0bd00bd0, 0x0a500bd0, 0x02400240, 0x02400240, // ICON_PLAYER - 0x01800000, 0x03c003c0, 0x118013c0, 0x03c81ff8, 0x07c003c8, 0x04400440, 0x0c080478, 0x00000000, // ICON_PLAYER_JUMP - 0x3ff80000, 0x30183ff8, 0x30183018, 0x3ff83ff8, 0x03000300, 0x03c003c0, 0x03e00300, 0x000003e0, // ICON_KEY - 0x3ff80000, 0x3ff83ff8, 0x33983ff8, 0x3ff83398, 0x3ff83ff8, 0x00000540, 0x0fe00aa0, 0x00000fe0, // ICON_DEMON - 0x00000000, 0x0ff00000, 0x20041008, 0x25442004, 0x10082004, 0x06000bf0, 0x00000300, 0x00000000, // ICON_TEXT_POPUP - 0x00000000, 0x11440000, 0x07f00be8, 0x1c1c0e38, 0x1c1c0c18, 0x07f00e38, 0x11440be8, 0x00000000, // ICON_GEAR_EX - 0x00000000, 0x20080000, 0x0c601010, 0x07c00fe0, 0x07c007c0, 0x0c600fe0, 0x20081010, 0x00000000, // ICON_CRACK - 0x00000000, 0x20080000, 0x0c601010, 0x04400fe0, 0x04405554, 0x0c600fe0, 0x20081010, 0x00000000, // ICON_CRACK_POINTS - 0x00000000, 0x00800080, 0x01c001c0, 0x1ffc3ffe, 0x03e007f0, 0x07f003e0, 0x0c180770, 0x00000808, // ICON_STAR - 0x0ff00000, 0x08180810, 0x08100818, 0x0a100810, 0x08180810, 0x08100818, 0x08100810, 0x00001ff8, // ICON_DOOR - 0x0ff00000, 0x08100810, 0x08100810, 0x10100010, 0x4f902010, 0x10102010, 0x08100010, 0x00000ff0, // ICON_EXIT - 0x00040000, 0x001f000e, 0x0ef40004, 0x12f41284, 0x0ef41214, 0x10040004, 0x7ffc3004, 0x10003000, // ICON_MODE_2D - 0x78040000, 0x501f600e, 0x0ef44004, 0x12f41284, 0x0ef41284, 0x10140004, 0x7ffc300c, 0x10003000, // ICON_MODE_3D - 0x7fe00000, 0x50286030, 0x47fe4804, 0x44224402, 0x44224422, 0x241275e2, 0x0c06140a, 0x000007fe, // ICON_CUBE - 0x7fe00000, 0x5ff87ff0, 0x47fe4ffc, 0x44224402, 0x44224422, 0x241275e2, 0x0c06140a, 0x000007fe, // ICON_CUBE_FACE_TOP - 0x7fe00000, 0x50386030, 0x47c2483c, 0x443e443e, 0x443e443e, 0x241e75fe, 0x0c06140e, 0x000007fe, // ICON_CUBE_FACE_LEFT - 0x7fe00000, 0x50286030, 0x47fe4804, 0x47fe47fe, 0x47fe47fe, 0x27fe77fe, 0x0ffe17fe, 0x000007fe, // ICON_CUBE_FACE_FRONT - 0x7fe00000, 0x50286030, 0x47fe4804, 0x44224402, 0x44224422, 0x3bf27be2, 0x0bfe1bfa, 0x000007fe, // ICON_CUBE_FACE_BOTTOM - 0x7fe00000, 0x70286030, 0x7ffe7804, 0x7c227c02, 0x7c227c22, 0x3c127de2, 0x0c061c0a, 0x000007fe, // ICON_CUBE_FACE_RIGHT - 0x7fe00000, 0x6fe85ff0, 0x781e77e4, 0x7be27be2, 0x7be27be2, 0x24127be2, 0x0c06140a, 0x000007fe, // ICON_CUBE_FACE_BACK - 0x00000000, 0x2a0233fe, 0x22022602, 0x22022202, 0x2a022602, 0x00a033fe, 0x02080110, 0x00000000, // ICON_CAMERA - 0x00000000, 0x200c3ffc, 0x000c000c, 0x3ffc000c, 0x30003000, 0x30003000, 0x3ffc3004, 0x00000000, // ICON_SPECIAL - 0x00000000, 0x0022003e, 0x012201e2, 0x0100013e, 0x01000100, 0x79000100, 0x4f004900, 0x00007800, // ICON_LINK_NET - 0x00000000, 0x44007c00, 0x45004600, 0x00627cbe, 0x00620022, 0x45007cbe, 0x44004600, 0x00007c00, // ICON_LINK_BOXES - 0x00000000, 0x0044007c, 0x0010007c, 0x3f100010, 0x3f1021f0, 0x3f100010, 0x3f0021f0, 0x00000000, // ICON_LINK_MULTI - 0x00000000, 0x0044007c, 0x00440044, 0x0010007c, 0x00100010, 0x44107c10, 0x440047f0, 0x00007c00, // ICON_LINK - 0x00000000, 0x0044007c, 0x00440044, 0x0000007c, 0x00000010, 0x44007c10, 0x44004550, 0x00007c00, // ICON_LINK_BROKE - 0x02a00000, 0x22a43ffc, 0x20042004, 0x20042ff4, 0x20042ff4, 0x20042ff4, 0x20042004, 0x00003ffc, // ICON_TEXT_NOTES - 0x3ffc0000, 0x20042004, 0x245e27c4, 0x27c42444, 0x2004201e, 0x201e2004, 0x20042004, 0x00003ffc, // ICON_NOTEBOOK - 0x00000000, 0x07e00000, 0x04200420, 0x24243ffc, 0x24242424, 0x24242424, 0x3ffc2424, 0x00000000, // ICON_SUITCASE - 0x00000000, 0x0fe00000, 0x08200820, 0x40047ffc, 0x7ffc5554, 0x40045554, 0x7ffc4004, 0x00000000, // ICON_SUITCASE_ZIP - 0x00000000, 0x20043ffc, 0x3ffc2004, 0x13c81008, 0x100813c8, 0x10081008, 0x1ff81008, 0x00000000, // ICON_MAILBOX - 0x00000000, 0x40027ffe, 0x5ffa5ffa, 0x5ffa5ffa, 0x40025ffa, 0x03c07ffe, 0x1ff81ff8, 0x00000000, // ICON_MONITOR - 0x0ff00000, 0x6bfe7ffe, 0x7ffe7ffe, 0x68167ffe, 0x08106816, 0x08100810, 0x0ff00810, 0x00000000, // ICON_PRINTER - 0x3ff80000, 0xfffe2008, 0x870a8002, 0x904a888a, 0x904a904a, 0x870a888a, 0xfffe8002, 0x00000000, // ICON_PHOTO_CAMERA - 0x0fc00000, 0xfcfe0cd8, 0x8002fffe, 0x84428382, 0x84428442, 0x80028382, 0xfffe8002, 0x00000000, // ICON_PHOTO_CAMERA_FLASH - 0x00000000, 0x02400180, 0x08100420, 0x20041008, 0x23c42004, 0x22442244, 0x3ffc2244, 0x00000000, // ICON_HOUSE - 0x00000000, 0x1c700000, 0x3ff83ef8, 0x3ff83ff8, 0x0fe01ff0, 0x038007c0, 0x00000100, 0x00000000, // ICON_HEART - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x80000000, 0xe000c000, // ICON_CORNER - 0x00000000, 0x14001c00, 0x15c01400, 0x15401540, 0x155c1540, 0x15541554, 0x1ddc1554, 0x00000000, // ICON_VERTICAL_BARS - 0x00000000, 0x03000300, 0x1b001b00, 0x1b601b60, 0x1b6c1b60, 0x1b6c1b6c, 0x1b6c1b6c, 0x00000000, // ICON_VERTICAL_BARS_FILL - 0x00000000, 0x00000000, 0x403e7ffe, 0x7ffe403e, 0x7ffe0000, 0x43fe43fe, 0x00007ffe, 0x00000000, // ICON_LIFE_BARS - 0x7ffc0000, 0x43844004, 0x43844284, 0x43844004, 0x42844284, 0x42844284, 0x40044384, 0x00007ffc, // ICON_INFO - 0x40008000, 0x10002000, 0x04000800, 0x01000200, 0x00400080, 0x00100020, 0x00040008, 0x00010002, // ICON_CROSSLINE - 0x00000000, 0x1ff01ff0, 0x18301830, 0x1f001830, 0x03001f00, 0x00000300, 0x03000300, 0x00000000, // ICON_HELP - 0x3ff00000, 0x2abc3550, 0x2aac3554, 0x2aac3554, 0x2aac3554, 0x2aac3554, 0x2aac3554, 0x00003ffc, // ICON_FILETYPE_ALPHA - 0x3ff00000, 0x201c2010, 0x22442184, 0x28142424, 0x29942814, 0x2ff42994, 0x20042004, 0x00003ffc, // ICON_FILETYPE_HOME - 0x07fe0000, 0x04020402, 0x7fe20402, 0x44224422, 0x44224422, 0x402047fe, 0x40204020, 0x00007fe0, // ICON_LAYERS_VISIBLE - 0x07fe0000, 0x04020402, 0x7c020402, 0x44024402, 0x44024402, 0x402047fe, 0x40204020, 0x00007fe0, // ICON_LAYERS - 0x00000000, 0x40027ffe, 0x7ffe4002, 0x40024002, 0x40024002, 0x40024002, 0x7ffe4002, 0x00000000, // ICON_WINDOW - 0x09100000, 0x09f00910, 0x09100910, 0x00000910, 0x24a2779e, 0x27a224a2, 0x709e20a2, 0x00000000, // ICON_HIDPI - 0x3ff00000, 0x201c2010, 0x2a842e84, 0x2e842a84, 0x2ba42004, 0x2aa42aa4, 0x20042ba4, 0x00003ffc, // ICON_FILETYPE_BINARY - 0x00000000, 0x00000000, 0x00120012, 0x4a5e4bd2, 0x485233d2, 0x00004bd2, 0x00000000, 0x00000000, // ICON_HEX - 0x01800000, 0x381c0660, 0x23c42004, 0x23c42044, 0x13c82204, 0x08101008, 0x02400420, 0x00000180, // ICON_SHIELD - 0x007e0000, 0x20023fc2, 0x40227fe2, 0x400a403a, 0x400a400a, 0x400a400a, 0x4008400e, 0x00007ff8, // ICON_FILE_NEW - 0x00000000, 0x0042007e, 0x40027fc2, 0x44024002, 0x5f024402, 0x44024402, 0x7ffe4002, 0x00000000, // ICON_FOLDER_ADD - 0x44220000, 0x12482244, 0xf3cf0000, 0x14280420, 0x48122424, 0x08100810, 0x1ff81008, 0x03c00420, // ICON_ALARM - 0x0aa00000, 0x1ff80aa0, 0x1068700e, 0x1008706e, 0x1008700e, 0x1008700e, 0x0aa01ff8, 0x00000aa0, // ICON_CPU - 0x07e00000, 0x04201db8, 0x04a01c38, 0x04a01d38, 0x04a01d38, 0x04a01d38, 0x04201d38, 0x000007e0, // ICON_ROM - 0x00000000, 0x03c00000, 0x3c382ff0, 0x3c04380c, 0x01800000, 0x03c003c0, 0x00000180, 0x00000000, // ICON_STEP_OVER - 0x01800000, 0x01800180, 0x01800180, 0x03c007e0, 0x00000180, 0x01800000, 0x03c003c0, 0x00000180, // ICON_STEP_INTO - 0x01800000, 0x07e003c0, 0x01800180, 0x01800180, 0x00000180, 0x01800000, 0x03c003c0, 0x00000180, // ICON_STEP_OUT - 0x00000000, 0x0ff003c0, 0x181c1c34, 0x303c301c, 0x30003000, 0x1c301800, 0x03c00ff0, 0x00000000, // ICON_RESTART - 0x00000000, 0x00000000, 0x07e003c0, 0x0ff00ff0, 0x0ff00ff0, 0x03c007e0, 0x00000000, 0x00000000, // ICON_BREAKPOINT_ON - 0x00000000, 0x00000000, 0x042003c0, 0x08100810, 0x08100810, 0x03c00420, 0x00000000, 0x00000000, // ICON_BREAKPOINT_OFF - 0x00000000, 0x00000000, 0x1ff81ff8, 0x1ff80000, 0x00001ff8, 0x1ff81ff8, 0x00000000, 0x00000000, // ICON_BURGER_MENU - 0x00000000, 0x00000000, 0x00880070, 0x0c880088, 0x1e8810f8, 0x3e881288, 0x00000000, 0x00000000, // ICON_CASE_SENSITIVE - 0x00000000, 0x02000000, 0x07000a80, 0x07001fc0, 0x02000a80, 0x00300030, 0x00000000, 0x00000000, // ICON_REG_EXP - 0x00000000, 0x0042007e, 0x40027fc2, 0x40024002, 0x40024002, 0x40024002, 0x7ffe4002, 0x00000000, // ICON_FOLDER - 0x3ff00000, 0x201c2010, 0x20042004, 0x20042004, 0x20042004, 0x20042004, 0x20042004, 0x00003ffc, // ICON_FILE - 0x1ff00000, 0x20082008, 0x17d02fe8, 0x05400ba0, 0x09200540, 0x23881010, 0x2fe827c8, 0x00001ff0, // ICON_SAND_TIMER - 0x01800000, 0x02400240, 0x05a00420, 0x09900990, 0x11881188, 0x21842004, 0x40024182, 0x00003ffc, // ICON_WARNING - 0x7ffe0000, 0x4ff24002, 0x4c324ff2, 0x4f824c02, 0x41824f82, 0x41824002, 0x40024182, 0x00007ffe, // ICON_HELP_BOX - 0x7ffe0000, 0x41824002, 0x40024182, 0x41824182, 0x41824182, 0x41824182, 0x40024182, 0x00007ffe, // ICON_INFO_BOX - 0x01800000, 0x04200240, 0x10080810, 0x7bde2004, 0x0a500a50, 0x08500bd0, 0x08100850, 0x00000ff0, // ICON_PRIORITY - 0x01800000, 0x18180660, 0x80016006, 0x98196006, 0x99996666, 0x19986666, 0x01800660, 0x00000000, // ICON_LAYERS_ISO - 0x07fe0000, 0x1c020402, 0x74021402, 0x54025402, 0x54025402, 0x500857fe, 0x40205ff8, 0x00007fe0, // ICON_LAYERS2 - 0x0ffe0000, 0x3ffa0802, 0x7fea200a, 0x402a402a, 0x422a422a, 0x422e422a, 0x40384e28, 0x00007fe0, // ICON_MLAYERS - 0x0ffe0000, 0x3ffa0802, 0x7fea200a, 0x402a402a, 0x5b2a512a, 0x512e552a, 0x40385128, 0x00007fe0, // ICON_MAPS - 0x04200000, 0x1cf00c60, 0x11f019f0, 0x0f3807b8, 0x1e3c0f3c, 0x1c1c1e1c, 0x1e3c1c1c, 0x00000f70, // ICON_HOT - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, // ICON_229 - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, // ICON_230 - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, // ICON_231 - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, // ICON_232 - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, // ICON_233 - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, // ICON_234 - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, // ICON_235 - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, // ICON_236 - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, // ICON_237 - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, // ICON_238 - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, // ICON_239 - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, // ICON_240 - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, // ICON_241 - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, // ICON_242 - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, // ICON_243 - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, // ICON_244 - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, // ICON_245 - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, // ICON_246 - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, // ICON_247 - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, // ICON_248 - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, // ICON_249 - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, // ICON_250 - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, // ICON_251 - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, // ICON_252 - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, // ICON_253 - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, // ICON_254 - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, // ICON_255 -}; - -// NOTE: A pointer to current icons array should be defined -static unsigned int *guiIconsPtr = guiIcons; - -#endif // !RAYGUI_NO_ICONS && !RAYGUI_CUSTOM_ICONS - -#ifndef RAYGUI_ICON_SIZE - #define RAYGUI_ICON_SIZE 0 -#endif - -// WARNING: Those values define the total size of the style data array, -// if changed, previous saved styles could become incompatible -#define RAYGUI_MAX_CONTROLS 16 // Maximum number of controls -#define RAYGUI_MAX_PROPS_BASE 16 // Maximum number of base properties -#define RAYGUI_MAX_PROPS_EXTENDED 8 // Maximum number of extended properties - -//---------------------------------------------------------------------------------- -// Types and Structures Definition -//---------------------------------------------------------------------------------- -// Gui control property style color element -typedef enum { BORDER = 0, BASE, TEXT, OTHER } GuiPropertyElement; - -//---------------------------------------------------------------------------------- -// Global Variables Definition -//---------------------------------------------------------------------------------- -static GuiState guiState = STATE_NORMAL; // Gui global state, if !STATE_NORMAL, forces defined state - -static Font guiFont = { 0 }; // Gui current font (WARNING: highly coupled to raylib) -static bool guiLocked = false; // Gui lock state (no inputs processed) -static float guiAlpha = 1.0f; // Gui controls transparency - -static unsigned int guiIconScale = 1; // Gui icon default scale (if icons enabled) - -static bool guiTooltip = false; // Tooltip enabled/disabled -static const char *guiTooltipPtr = NULL; // Tooltip string pointer (string provided by user) - -static bool guiControlExclusiveMode = false; // Gui control exclusive mode (no inputs processed except current control) -static Rectangle guiControlExclusiveRec = { 0 }; // Gui control exclusive bounds rectangle, used as an unique identifier - -static int textBoxCursorIndex = 0; // Cursor index, shared by all GuiTextBox*() -//static int blinkCursorFrameCounter = 0; // Frame counter for cursor blinking -static int autoCursorCooldownCounter = 0; // Cooldown frame counter for automatic cursor movement on key-down -static int autoCursorDelayCounter = 0; // Delay frame counter for automatic cursor movement - -//---------------------------------------------------------------------------------- -// Style data array for all gui style properties (allocated on data segment by default) -// -// NOTE 1: First set of BASE properties are generic to all controls but could be individually -// overwritten per control, first set of EXTENDED properties are generic to all controls and -// can not be overwritten individually but custom EXTENDED properties can be used by control -// -// NOTE 2: A new style set could be loaded over this array using GuiLoadStyle(), -// but default gui style could always be recovered with GuiLoadStyleDefault() -// -// guiStyle size is by default: 16*(16 + 8) = 384*4 = 1536 bytes = 1.5 KB -//---------------------------------------------------------------------------------- -static unsigned int guiStyle[RAYGUI_MAX_CONTROLS*(RAYGUI_MAX_PROPS_BASE + RAYGUI_MAX_PROPS_EXTENDED)] = { 0 }; - -static bool guiStyleLoaded = false; // Style loaded flag for lazy style initialization - -//---------------------------------------------------------------------------------- -// Standalone Mode Functions Declaration -// -// NOTE: raygui depend on some raylib input and drawing functions -// To use raygui as standalone library, below functions must be defined by the user -//---------------------------------------------------------------------------------- -#if defined(RAYGUI_STANDALONE) - -#define KEY_RIGHT 262 -#define KEY_LEFT 263 -#define KEY_DOWN 264 -#define KEY_UP 265 -#define KEY_BACKSPACE 259 -#define KEY_ENTER 257 - -#define MOUSE_LEFT_BUTTON 0 - -// Input required functions -//------------------------------------------------------------------------------- -static Vector2 GetMousePosition(void); -static float GetMouseWheelMove(void); -static bool IsMouseButtonDown(int button); -static bool IsMouseButtonPressed(int button); -static bool IsMouseButtonReleased(int button); - -static bool IsKeyDown(int key); -static bool IsKeyPressed(int key); -static int GetCharPressed(void); // -- GuiTextBox(), GuiValueBox() -//------------------------------------------------------------------------------- - -// Drawing required functions -//------------------------------------------------------------------------------- -static void DrawRectangle(int x, int y, int width, int height, Color color); // -- GuiDrawRectangle() -static void DrawRectangleGradientEx(Rectangle rec, Color col1, Color col2, Color col3, Color col4); // -- GuiColorPicker() -//------------------------------------------------------------------------------- - -// Text required functions -//------------------------------------------------------------------------------- -static Font GetFontDefault(void); // -- GuiLoadStyleDefault() -static Font LoadFontEx(const char *fileName, int fontSize, int *codepoints, int codepointCount); // -- GuiLoadStyle(), load font - -static Texture2D LoadTextureFromImage(Image image); // -- GuiLoadStyle(), required to load texture from embedded font atlas image -static void SetShapesTexture(Texture2D tex, Rectangle rec); // -- GuiLoadStyle(), required to set shapes rec to font white rec (optimization) - -static char *LoadFileText(const char *fileName); // -- GuiLoadStyle(), required to load charset data -static void UnloadFileText(char *text); // -- GuiLoadStyle(), required to unload charset data - -static const char *GetDirectoryPath(const char *filePath); // -- GuiLoadStyle(), required to find charset/font file from text .rgs - -static int *LoadCodepoints(const char *text, int *count); // -- GuiLoadStyle(), required to load required font codepoints list -static void UnloadCodepoints(int *codepoints); // -- GuiLoadStyle(), required to unload codepoints list - -static unsigned char *DecompressData(const unsigned char *compData, int compDataSize, int *dataSize); // -- GuiLoadStyle() -//------------------------------------------------------------------------------- - -// raylib functions already implemented in raygui -//------------------------------------------------------------------------------- -static Color GetColor(int hexValue); // Returns a Color struct from hexadecimal value -static int ColorToInt(Color color); // Returns hexadecimal value for a Color -static bool CheckCollisionPointRec(Vector2 point, Rectangle rec); // Check if point is inside rectangle -static const char *TextFormat(const char *text, ...); // Formatting of text with variables to 'embed' -static const char **TextSplit(const char *text, char delimiter, int *count); // Split text into multiple strings -static int TextToInteger(const char *text); // Get integer value from text -static float TextToFloat(const char *text); // Get float value from text - -static int GetCodepointNext(const char *text, int *codepointSize); // Get next codepoint in a UTF-8 encoded text -static const char *CodepointToUTF8(int codepoint, int *byteSize); // Encode codepoint into UTF-8 text (char array size returned as parameter) - -static void DrawRectangleGradientV(int posX, int posY, int width, int height, Color color1, Color color2); // Draw rectangle vertical gradient -//------------------------------------------------------------------------------- - -#endif // RAYGUI_STANDALONE - -//---------------------------------------------------------------------------------- -// Module specific Functions Declaration -//---------------------------------------------------------------------------------- -static void GuiLoadStyleFromMemory(const unsigned char *fileData, int dataSize); // Load style from memory (binary only) - -static int GetTextWidth(const char *text); // Gui get text width using gui font and style -static Rectangle GetTextBounds(int control, Rectangle bounds); // Get text bounds considering control bounds -static const char *GetTextIcon(const char *text, int *iconId); // Get text icon if provided and move text cursor - -static void GuiDrawText(const char *text, Rectangle textBounds, int alignment, Color tint); // Gui draw text using default font -static void GuiDrawRectangle(Rectangle rec, int borderWidth, Color borderColor, Color color); // Gui draw rectangle using default raygui style - -static const char **GuiTextSplit(const char *text, char delimiter, int *count, int *textRow); // Split controls text into multiple strings -static Vector3 ConvertHSVtoRGB(Vector3 hsv); // Convert color data from HSV to RGB -static Vector3 ConvertRGBtoHSV(Vector3 rgb); // Convert color data from RGB to HSV - -static int GuiScrollBar(Rectangle bounds, int value, int minValue, int maxValue); // Scroll bar control, used by GuiScrollPanel() -static void GuiTooltip(Rectangle controlRec); // Draw tooltip using control rec position - -static Color GuiFade(Color color, float alpha); // Fade color by an alpha factor - -//---------------------------------------------------------------------------------- -// Gui Setup Functions Definition -//---------------------------------------------------------------------------------- -// Enable gui global state -// NOTE: We check for STATE_DISABLED to avoid messing custom global state setups -void GuiEnable(void) { if (guiState == STATE_DISABLED) guiState = STATE_NORMAL; } - -// Disable gui global state -// NOTE: We check for STATE_NORMAL to avoid messing custom global state setups -void GuiDisable(void) { if (guiState == STATE_NORMAL) guiState = STATE_DISABLED; } - -// Lock gui global state -void GuiLock(void) { guiLocked = true; } - -// Unlock gui global state -void GuiUnlock(void) { guiLocked = false; } - -// Check if gui is locked (global state) -bool GuiIsLocked(void) { return guiLocked; } - -// Set gui controls alpha global state -void GuiSetAlpha(float alpha) -{ - if (alpha < 0.0f) alpha = 0.0f; - else if (alpha > 1.0f) alpha = 1.0f; - - guiAlpha = alpha; -} - -// Set gui state (global state) -void GuiSetState(int state) { guiState = (GuiState)state; } - -// Get gui state (global state) -int GuiGetState(void) { return guiState; } - -// Set custom gui font -// NOTE: Font loading/unloading is external to raygui -void GuiSetFont(Font font) -{ - if (font.texture.id > 0) - { - // NOTE: If we try to setup a font but default style has not been - // lazily loaded before, it will be overwritten, so we need to force - // default style loading first - if (!guiStyleLoaded) GuiLoadStyleDefault(); - - guiFont = font; - } -} - -// Get custom gui font -Font GuiGetFont(void) -{ - return guiFont; -} - -// Set control style property value -void GuiSetStyle(int control, int property, int value) -{ - if (!guiStyleLoaded) GuiLoadStyleDefault(); - guiStyle[control*(RAYGUI_MAX_PROPS_BASE + RAYGUI_MAX_PROPS_EXTENDED) + property] = value; - - // Default properties are propagated to all controls - if ((control == 0) && (property < RAYGUI_MAX_PROPS_BASE)) - { - for (int i = 1; i < RAYGUI_MAX_CONTROLS; i++) guiStyle[i*(RAYGUI_MAX_PROPS_BASE + RAYGUI_MAX_PROPS_EXTENDED) + property] = value; - } -} - -// Get control style property value -int GuiGetStyle(int control, int property) -{ - if (!guiStyleLoaded) GuiLoadStyleDefault(); - return guiStyle[control*(RAYGUI_MAX_PROPS_BASE + RAYGUI_MAX_PROPS_EXTENDED) + property]; -} - -//---------------------------------------------------------------------------------- -// Gui Controls Functions Definition -//---------------------------------------------------------------------------------- - -// Window Box control -int GuiWindowBox(Rectangle bounds, const char *title) -{ - // Window title bar height (including borders) - // NOTE: This define is also used by GuiMessageBox() and GuiTextInputBox() - #if !defined(RAYGUI_WINDOWBOX_STATUSBAR_HEIGHT) - #define RAYGUI_WINDOWBOX_STATUSBAR_HEIGHT 24 - #endif - - int result = 0; - //GuiState state = guiState; - - int statusBarHeight = RAYGUI_WINDOWBOX_STATUSBAR_HEIGHT; - - Rectangle statusBar = { bounds.x, bounds.y, bounds.width, (float)statusBarHeight }; - if (bounds.height < statusBarHeight*2.0f) bounds.height = statusBarHeight*2.0f; - - Rectangle windowPanel = { bounds.x, bounds.y + (float)statusBarHeight - 1, bounds.width, bounds.height - (float)statusBarHeight + 1 }; - Rectangle closeButtonRec = { statusBar.x + statusBar.width - GuiGetStyle(STATUSBAR, BORDER_WIDTH) - 20, - statusBar.y + statusBarHeight/2.0f - 18.0f/2.0f, 18, 18 }; - - // Update control - //-------------------------------------------------------------------- - // NOTE: Logic is directly managed by button - //-------------------------------------------------------------------- - - // Draw control - //-------------------------------------------------------------------- - GuiStatusBar(statusBar, title); // Draw window header as status bar - GuiPanel(windowPanel, NULL); // Draw window base - - // Draw window close button - int tempBorderWidth = GuiGetStyle(BUTTON, BORDER_WIDTH); - int tempTextAlignment = GuiGetStyle(BUTTON, TEXT_ALIGNMENT); - GuiSetStyle(BUTTON, BORDER_WIDTH, 1); - GuiSetStyle(BUTTON, TEXT_ALIGNMENT, TEXT_ALIGN_CENTER); -#if defined(RAYGUI_NO_ICONS) - result = GuiButton(closeButtonRec, "x"); -#else - result = GuiButton(closeButtonRec, GuiIconText(ICON_CROSS_SMALL, NULL)); -#endif - GuiSetStyle(BUTTON, BORDER_WIDTH, tempBorderWidth); - GuiSetStyle(BUTTON, TEXT_ALIGNMENT, tempTextAlignment); - //-------------------------------------------------------------------- - - return result; // Window close button clicked: result = 1 -} - -// Group Box control with text name -int GuiGroupBox(Rectangle bounds, const char *text) -{ - #if !defined(RAYGUI_GROUPBOX_LINE_THICK) - #define RAYGUI_GROUPBOX_LINE_THICK 1 - #endif - - int result = 0; - GuiState state = guiState; - - // Draw control - //-------------------------------------------------------------------- - GuiDrawRectangle(RAYGUI_CLITERAL(Rectangle){ bounds.x, bounds.y, RAYGUI_GROUPBOX_LINE_THICK, bounds.height }, 0, BLANK, GetColor(GuiGetStyle(DEFAULT, (state == STATE_DISABLED)? (int)BORDER_COLOR_DISABLED : (int)LINE_COLOR))); - GuiDrawRectangle(RAYGUI_CLITERAL(Rectangle){ bounds.x, bounds.y + bounds.height - 1, bounds.width, RAYGUI_GROUPBOX_LINE_THICK }, 0, BLANK, GetColor(GuiGetStyle(DEFAULT, (state == STATE_DISABLED)? (int)BORDER_COLOR_DISABLED : (int)LINE_COLOR))); - GuiDrawRectangle(RAYGUI_CLITERAL(Rectangle){ bounds.x + bounds.width - 1, bounds.y, RAYGUI_GROUPBOX_LINE_THICK, bounds.height }, 0, BLANK, GetColor(GuiGetStyle(DEFAULT, (state == STATE_DISABLED)? (int)BORDER_COLOR_DISABLED : (int)LINE_COLOR))); - - GuiLine(RAYGUI_CLITERAL(Rectangle){ bounds.x, bounds.y - GuiGetStyle(DEFAULT, TEXT_SIZE)/2, bounds.width, (float)GuiGetStyle(DEFAULT, TEXT_SIZE) }, text); - //-------------------------------------------------------------------- - - return result; -} - -// Line control -int GuiLine(Rectangle bounds, const char *text) -{ - #if !defined(RAYGUI_LINE_ORIGIN_SIZE) - #define RAYGUI_LINE_MARGIN_TEXT 12 - #endif - #if !defined(RAYGUI_LINE_TEXT_PADDING) - #define RAYGUI_LINE_TEXT_PADDING 4 - #endif - - int result = 0; - GuiState state = guiState; - - Color color = GetColor(GuiGetStyle(DEFAULT, (state == STATE_DISABLED)? (int)BORDER_COLOR_DISABLED : (int)LINE_COLOR)); - - // Draw control - //-------------------------------------------------------------------- - if (text == NULL) GuiDrawRectangle(RAYGUI_CLITERAL(Rectangle){ bounds.x, bounds.y + bounds.height/2, bounds.width, 1 }, 0, BLANK, color); - else - { - Rectangle textBounds = { 0 }; - textBounds.width = (float)GetTextWidth(text) + 2; - textBounds.height = bounds.height; - textBounds.x = bounds.x + RAYGUI_LINE_MARGIN_TEXT; - textBounds.y = bounds.y; - - // Draw line with embedded text label: "--- text --------------" - GuiDrawRectangle(RAYGUI_CLITERAL(Rectangle){ bounds.x, bounds.y + bounds.height/2, RAYGUI_LINE_MARGIN_TEXT - RAYGUI_LINE_TEXT_PADDING, 1 }, 0, BLANK, color); - GuiDrawText(text, textBounds, TEXT_ALIGN_LEFT, color); - GuiDrawRectangle(RAYGUI_CLITERAL(Rectangle){ bounds.x + 12 + textBounds.width + 4, bounds.y + bounds.height/2, bounds.width - textBounds.width - RAYGUI_LINE_MARGIN_TEXT - RAYGUI_LINE_TEXT_PADDING, 1 }, 0, BLANK, color); - } - //-------------------------------------------------------------------- - - return result; -} - -// Panel control -int GuiPanel(Rectangle bounds, const char *text) -{ - #if !defined(RAYGUI_PANEL_BORDER_WIDTH) - #define RAYGUI_PANEL_BORDER_WIDTH 1 - #endif - - int result = 0; - GuiState state = guiState; - - // Text will be drawn as a header bar (if provided) - Rectangle statusBar = { bounds.x, bounds.y, bounds.width, (float)RAYGUI_WINDOWBOX_STATUSBAR_HEIGHT }; - if ((text != NULL) && (bounds.height < RAYGUI_WINDOWBOX_STATUSBAR_HEIGHT*2.0f)) bounds.height = RAYGUI_WINDOWBOX_STATUSBAR_HEIGHT*2.0f; - - if (text != NULL) - { - // Move panel bounds after the header bar - bounds.y += (float)RAYGUI_WINDOWBOX_STATUSBAR_HEIGHT - 1; - bounds.height -= (float)RAYGUI_WINDOWBOX_STATUSBAR_HEIGHT - 1; - } - - // Draw control - //-------------------------------------------------------------------- - if (text != NULL) GuiStatusBar(statusBar, text); // Draw panel header as status bar - - GuiDrawRectangle(bounds, RAYGUI_PANEL_BORDER_WIDTH, GetColor(GuiGetStyle(DEFAULT, (state == STATE_DISABLED)? (int)BORDER_COLOR_DISABLED: (int)LINE_COLOR)), - GetColor(GuiGetStyle(DEFAULT, (state == STATE_DISABLED)? BASE_COLOR_DISABLED : BACKGROUND_COLOR))); - //-------------------------------------------------------------------- - - return result; -} - -// Tab Bar control -// NOTE: Using GuiToggle() for the TABS -int GuiTabBar(Rectangle bounds, const char **text, int count, int *active) -{ - #define RAYGUI_TABBAR_ITEM_WIDTH 160 - - int result = -1; - //GuiState state = guiState; - - Rectangle tabBounds = { bounds.x, bounds.y, RAYGUI_TABBAR_ITEM_WIDTH, bounds.height }; - - if (*active < 0) *active = 0; - else if (*active > count - 1) *active = count - 1; - - int offsetX = 0; // Required in case tabs go out of screen - offsetX = (*active + 2)*RAYGUI_TABBAR_ITEM_WIDTH - GetScreenWidth(); - if (offsetX < 0) offsetX = 0; - - bool toggle = false; // Required for individual toggles - - // Draw control - //-------------------------------------------------------------------- - for (int i = 0; i < count; i++) - { - tabBounds.x = bounds.x + (RAYGUI_TABBAR_ITEM_WIDTH + 4)*i - offsetX; - - if (tabBounds.x < GetScreenWidth()) - { - // Draw tabs as toggle controls - int textAlignment = GuiGetStyle(TOGGLE, TEXT_ALIGNMENT); - int textPadding = GuiGetStyle(TOGGLE, TEXT_PADDING); - GuiSetStyle(TOGGLE, TEXT_ALIGNMENT, TEXT_ALIGN_LEFT); - GuiSetStyle(TOGGLE, TEXT_PADDING, 8); - - if (i == (*active)) - { - toggle = true; - GuiToggle(tabBounds, GuiIconText(12, text[i]), &toggle); - } - else - { - toggle = false; - GuiToggle(tabBounds, GuiIconText(12, text[i]), &toggle); - if (toggle) *active = i; - } - - // Close tab with middle mouse button pressed - if (CheckCollisionPointRec(GetMousePosition(), tabBounds) && IsMouseButtonPressed(MOUSE_MIDDLE_BUTTON)) result = i; - - GuiSetStyle(TOGGLE, TEXT_PADDING, textPadding); - GuiSetStyle(TOGGLE, TEXT_ALIGNMENT, textAlignment); - - // Draw tab close button - // NOTE: Only draw close button for current tab: if (CheckCollisionPointRec(mousePosition, tabBounds)) - int tempBorderWidth = GuiGetStyle(BUTTON, BORDER_WIDTH); - int tempTextAlignment = GuiGetStyle(BUTTON, TEXT_ALIGNMENT); - GuiSetStyle(BUTTON, BORDER_WIDTH, 1); - GuiSetStyle(BUTTON, TEXT_ALIGNMENT, TEXT_ALIGN_CENTER); -#if defined(RAYGUI_NO_ICONS) - if (GuiButton(RAYGUI_CLITERAL(Rectangle){ tabBounds.x + tabBounds.width - 14 - 5, tabBounds.y + 5, 14, 14 }, "x")) result = i; -#else - if (GuiButton(RAYGUI_CLITERAL(Rectangle){ tabBounds.x + tabBounds.width - 14 - 5, tabBounds.y + 5, 14, 14 }, GuiIconText(ICON_CROSS_SMALL, NULL))) result = i; -#endif - GuiSetStyle(BUTTON, BORDER_WIDTH, tempBorderWidth); - GuiSetStyle(BUTTON, TEXT_ALIGNMENT, tempTextAlignment); - } - } - - // Draw tab-bar bottom line - GuiDrawRectangle(RAYGUI_CLITERAL(Rectangle){ bounds.x, bounds.y + bounds.height - 1, bounds.width, 1 }, 0, BLANK, GetColor(GuiGetStyle(TOGGLE, BORDER_COLOR_NORMAL))); - //-------------------------------------------------------------------- - - return result; // Return as result the current TAB closing requested -} - -// Scroll Panel control -int GuiScrollPanel(Rectangle bounds, const char *text, Rectangle content, Vector2 *scroll, Rectangle *view) -{ - #define RAYGUI_MIN_SCROLLBAR_WIDTH 40 - #define RAYGUI_MIN_SCROLLBAR_HEIGHT 40 - #define RAYGUI_MIN_MOUSE_WHEEL_SPEED 20 - - int result = 0; - GuiState state = guiState; - - Rectangle temp = { 0 }; - if (view == NULL) view = &temp; - - Vector2 scrollPos = { 0.0f, 0.0f }; - if (scroll != NULL) scrollPos = *scroll; - - // Text will be drawn as a header bar (if provided) - Rectangle statusBar = { bounds.x, bounds.y, bounds.width, (float)RAYGUI_WINDOWBOX_STATUSBAR_HEIGHT }; - if (bounds.height < RAYGUI_WINDOWBOX_STATUSBAR_HEIGHT*2.0f) bounds.height = RAYGUI_WINDOWBOX_STATUSBAR_HEIGHT*2.0f; - - if (text != NULL) - { - // Move panel bounds after the header bar - bounds.y += (float)RAYGUI_WINDOWBOX_STATUSBAR_HEIGHT - 1; - bounds.height -= (float)RAYGUI_WINDOWBOX_STATUSBAR_HEIGHT + 1; - } - - bool hasHorizontalScrollBar = (content.width > bounds.width - 2*GuiGetStyle(DEFAULT, BORDER_WIDTH))? true : false; - bool hasVerticalScrollBar = (content.height > bounds.height - 2*GuiGetStyle(DEFAULT, BORDER_WIDTH))? true : false; - - // Recheck to account for the other scrollbar being visible - if (!hasHorizontalScrollBar) hasHorizontalScrollBar = (hasVerticalScrollBar && (content.width > (bounds.width - 2*GuiGetStyle(DEFAULT, BORDER_WIDTH) - GuiGetStyle(LISTVIEW, SCROLLBAR_WIDTH))))? true : false; - if (!hasVerticalScrollBar) hasVerticalScrollBar = (hasHorizontalScrollBar && (content.height > (bounds.height - 2*GuiGetStyle(DEFAULT, BORDER_WIDTH) - GuiGetStyle(LISTVIEW, SCROLLBAR_WIDTH))))? true : false; - - int horizontalScrollBarWidth = hasHorizontalScrollBar? GuiGetStyle(LISTVIEW, SCROLLBAR_WIDTH) : 0; - int verticalScrollBarWidth = hasVerticalScrollBar? GuiGetStyle(LISTVIEW, SCROLLBAR_WIDTH) : 0; - Rectangle horizontalScrollBar = { - (float)((GuiGetStyle(LISTVIEW, SCROLLBAR_SIDE) == SCROLLBAR_LEFT_SIDE)? (float)bounds.x + verticalScrollBarWidth : (float)bounds.x) + GuiGetStyle(DEFAULT, BORDER_WIDTH), - (float)bounds.y + bounds.height - horizontalScrollBarWidth - GuiGetStyle(DEFAULT, BORDER_WIDTH), - (float)bounds.width - verticalScrollBarWidth - 2*GuiGetStyle(DEFAULT, BORDER_WIDTH), - (float)horizontalScrollBarWidth - }; - Rectangle verticalScrollBar = { - (float)((GuiGetStyle(LISTVIEW, SCROLLBAR_SIDE) == SCROLLBAR_LEFT_SIDE)? (float)bounds.x + GuiGetStyle(DEFAULT, BORDER_WIDTH) : (float)bounds.x + bounds.width - verticalScrollBarWidth - GuiGetStyle(DEFAULT, BORDER_WIDTH)), - (float)bounds.y + GuiGetStyle(DEFAULT, BORDER_WIDTH), - (float)verticalScrollBarWidth, - (float)bounds.height - horizontalScrollBarWidth - 2*GuiGetStyle(DEFAULT, BORDER_WIDTH) - }; - - // Make sure scroll bars have a minimum width/height - if (horizontalScrollBar.width < RAYGUI_MIN_SCROLLBAR_WIDTH) horizontalScrollBar.width = RAYGUI_MIN_SCROLLBAR_WIDTH; - if (verticalScrollBar.height < RAYGUI_MIN_SCROLLBAR_HEIGHT) verticalScrollBar.height = RAYGUI_MIN_SCROLLBAR_HEIGHT; - - // Calculate view area (area without the scrollbars) - *view = (GuiGetStyle(LISTVIEW, SCROLLBAR_SIDE) == SCROLLBAR_LEFT_SIDE)? - RAYGUI_CLITERAL(Rectangle){ bounds.x + verticalScrollBarWidth + GuiGetStyle(DEFAULT, BORDER_WIDTH), bounds.y + GuiGetStyle(DEFAULT, BORDER_WIDTH), bounds.width - 2*GuiGetStyle(DEFAULT, BORDER_WIDTH) - verticalScrollBarWidth, bounds.height - 2*GuiGetStyle(DEFAULT, BORDER_WIDTH) - horizontalScrollBarWidth } : - RAYGUI_CLITERAL(Rectangle){ bounds.x + GuiGetStyle(DEFAULT, BORDER_WIDTH), bounds.y + GuiGetStyle(DEFAULT, BORDER_WIDTH), bounds.width - 2*GuiGetStyle(DEFAULT, BORDER_WIDTH) - verticalScrollBarWidth, bounds.height - 2*GuiGetStyle(DEFAULT, BORDER_WIDTH) - horizontalScrollBarWidth }; - - // Clip view area to the actual content size - if (view->width > content.width) view->width = content.width; - if (view->height > content.height) view->height = content.height; - - float horizontalMin = hasHorizontalScrollBar? ((GuiGetStyle(LISTVIEW, SCROLLBAR_SIDE) == SCROLLBAR_LEFT_SIDE)? (float)-verticalScrollBarWidth : 0) - (float)GuiGetStyle(DEFAULT, BORDER_WIDTH) : (((float)GuiGetStyle(LISTVIEW, SCROLLBAR_SIDE) == SCROLLBAR_LEFT_SIDE)? (float)-verticalScrollBarWidth : 0) - (float)GuiGetStyle(DEFAULT, BORDER_WIDTH); - float horizontalMax = hasHorizontalScrollBar? content.width - bounds.width + (float)verticalScrollBarWidth + GuiGetStyle(DEFAULT, BORDER_WIDTH) - (((float)GuiGetStyle(LISTVIEW, SCROLLBAR_SIDE) == SCROLLBAR_LEFT_SIDE)? (float)verticalScrollBarWidth : 0) : (float)-GuiGetStyle(DEFAULT, BORDER_WIDTH); - float verticalMin = hasVerticalScrollBar? 0.0f : -1.0f; - float verticalMax = hasVerticalScrollBar? content.height - bounds.height + (float)horizontalScrollBarWidth + (float)GuiGetStyle(DEFAULT, BORDER_WIDTH) : (float)-GuiGetStyle(DEFAULT, BORDER_WIDTH); - - // Update control - //-------------------------------------------------------------------- - if ((state != STATE_DISABLED) && !guiLocked) - { - Vector2 mousePoint = GetMousePosition(); - - // Check button state - if (CheckCollisionPointRec(mousePoint, bounds)) - { - if (IsMouseButtonDown(MOUSE_LEFT_BUTTON)) state = STATE_PRESSED; - else state = STATE_FOCUSED; - -#if defined(SUPPORT_SCROLLBAR_KEY_INPUT) - if (hasHorizontalScrollBar) - { - if (IsKeyDown(KEY_RIGHT)) scrollPos.x -= GuiGetStyle(SCROLLBAR, SCROLL_SPEED); - if (IsKeyDown(KEY_LEFT)) scrollPos.x += GuiGetStyle(SCROLLBAR, SCROLL_SPEED); - } - - if (hasVerticalScrollBar) - { - if (IsKeyDown(KEY_DOWN)) scrollPos.y -= GuiGetStyle(SCROLLBAR, SCROLL_SPEED); - if (IsKeyDown(KEY_UP)) scrollPos.y += GuiGetStyle(SCROLLBAR, SCROLL_SPEED); - } -#endif - float wheelMove = GetMouseWheelMove(); - - // Set scrolling speed with mouse wheel based on ratio between bounds and content - Vector2 mouseWheelSpeed = { content.width/bounds.width, content.height/bounds.height }; - if (mouseWheelSpeed.x < RAYGUI_MIN_MOUSE_WHEEL_SPEED) mouseWheelSpeed.x = RAYGUI_MIN_MOUSE_WHEEL_SPEED; - if (mouseWheelSpeed.y < RAYGUI_MIN_MOUSE_WHEEL_SPEED) mouseWheelSpeed.y = RAYGUI_MIN_MOUSE_WHEEL_SPEED; - - // Horizontal and vertical scrolling with mouse wheel - if (hasHorizontalScrollBar && (IsKeyDown(KEY_LEFT_CONTROL) || IsKeyDown(KEY_LEFT_SHIFT))) scrollPos.x += wheelMove*mouseWheelSpeed.x; - else scrollPos.y += wheelMove*mouseWheelSpeed.y; // Vertical scroll - } - } - - // Normalize scroll values - if (scrollPos.x > -horizontalMin) scrollPos.x = -horizontalMin; - if (scrollPos.x < -horizontalMax) scrollPos.x = -horizontalMax; - if (scrollPos.y > -verticalMin) scrollPos.y = -verticalMin; - if (scrollPos.y < -verticalMax) scrollPos.y = -verticalMax; - //-------------------------------------------------------------------- - - // Draw control - //-------------------------------------------------------------------- - if (text != NULL) GuiStatusBar(statusBar, text); // Draw panel header as status bar - - GuiDrawRectangle(bounds, 0, BLANK, GetColor(GuiGetStyle(DEFAULT, BACKGROUND_COLOR))); // Draw background - - // Save size of the scrollbar slider - const int slider = GuiGetStyle(SCROLLBAR, SCROLL_SLIDER_SIZE); - - // Draw horizontal scrollbar if visible - if (hasHorizontalScrollBar) - { - // Change scrollbar slider size to show the diff in size between the content width and the widget width - GuiSetStyle(SCROLLBAR, SCROLL_SLIDER_SIZE, (int)(((bounds.width - 2*GuiGetStyle(DEFAULT, BORDER_WIDTH) - verticalScrollBarWidth)/(int)content.width)*((int)bounds.width - 2*GuiGetStyle(DEFAULT, BORDER_WIDTH) - verticalScrollBarWidth))); - scrollPos.x = (float)-GuiScrollBar(horizontalScrollBar, (int)-scrollPos.x, (int)horizontalMin, (int)horizontalMax); - } - else scrollPos.x = 0.0f; - - // Draw vertical scrollbar if visible - if (hasVerticalScrollBar) - { - // Change scrollbar slider size to show the diff in size between the content height and the widget height - GuiSetStyle(SCROLLBAR, SCROLL_SLIDER_SIZE, (int)(((bounds.height - 2*GuiGetStyle(DEFAULT, BORDER_WIDTH) - horizontalScrollBarWidth)/(int)content.height)*((int)bounds.height - 2*GuiGetStyle(DEFAULT, BORDER_WIDTH) - horizontalScrollBarWidth))); - scrollPos.y = (float)-GuiScrollBar(verticalScrollBar, (int)-scrollPos.y, (int)verticalMin, (int)verticalMax); - } - else scrollPos.y = 0.0f; - - // Draw detail corner rectangle if both scroll bars are visible - if (hasHorizontalScrollBar && hasVerticalScrollBar) - { - Rectangle corner = { (GuiGetStyle(LISTVIEW, SCROLLBAR_SIDE) == SCROLLBAR_LEFT_SIDE)? (bounds.x + GuiGetStyle(DEFAULT, BORDER_WIDTH) + 2) : (horizontalScrollBar.x + horizontalScrollBar.width + 2), verticalScrollBar.y + verticalScrollBar.height + 2, (float)horizontalScrollBarWidth - 4, (float)verticalScrollBarWidth - 4 }; - GuiDrawRectangle(corner, 0, BLANK, GetColor(GuiGetStyle(LISTVIEW, TEXT + (state*3)))); - } - - // Draw scrollbar lines depending on current state - GuiDrawRectangle(bounds, GuiGetStyle(LISTVIEW, BORDER_WIDTH), GetColor(GuiGetStyle(LISTVIEW, BORDER + (state*3))), BLANK); - - // Set scrollbar slider size back to the way it was before - GuiSetStyle(SCROLLBAR, SCROLL_SLIDER_SIZE, slider); - //-------------------------------------------------------------------- - - if (scroll != NULL) *scroll = scrollPos; - - return result; -} - -// Label control -int GuiLabel(Rectangle bounds, const char *text) -{ - int result = 0; - GuiState state = guiState; - - // Update control - //-------------------------------------------------------------------- - //... - //-------------------------------------------------------------------- - - // Draw control - //-------------------------------------------------------------------- - GuiDrawText(text, GetTextBounds(LABEL, bounds), GuiGetStyle(LABEL, TEXT_ALIGNMENT), GetColor(GuiGetStyle(LABEL, TEXT + (state*3)))); - //-------------------------------------------------------------------- - - return result; -} - -// Button control, returns true when clicked -int GuiButton(Rectangle bounds, const char *text) -{ - int result = 0; - GuiState state = guiState; - - // Update control - //-------------------------------------------------------------------- - if ((state != STATE_DISABLED) && !guiLocked && !guiControlExclusiveMode) - { - Vector2 mousePoint = GetMousePosition(); - - // Check button state - if (CheckCollisionPointRec(mousePoint, bounds)) - { - if (IsMouseButtonDown(MOUSE_LEFT_BUTTON)) state = STATE_PRESSED; - else state = STATE_FOCUSED; - - if (IsMouseButtonReleased(MOUSE_LEFT_BUTTON)) result = 1; - } - } - //-------------------------------------------------------------------- - - // Draw control - //-------------------------------------------------------------------- - GuiDrawRectangle(bounds, GuiGetStyle(BUTTON, BORDER_WIDTH), GetColor(GuiGetStyle(BUTTON, BORDER + (state*3))), GetColor(GuiGetStyle(BUTTON, BASE + (state*3)))); - GuiDrawText(text, GetTextBounds(BUTTON, bounds), GuiGetStyle(BUTTON, TEXT_ALIGNMENT), GetColor(GuiGetStyle(BUTTON, TEXT + (state*3)))); - - if (state == STATE_FOCUSED) GuiTooltip(bounds); - //------------------------------------------------------------------ - - return result; // Button pressed: result = 1 -} - -// Label button control -int GuiLabelButton(Rectangle bounds, const char *text) -{ - GuiState state = guiState; - bool pressed = false; - - // NOTE: We force bounds.width to be all text - float textWidth = (float)GetTextWidth(text); - if ((bounds.width - 2*GuiGetStyle(LABEL, BORDER_WIDTH) - 2*GuiGetStyle(LABEL, TEXT_PADDING)) < textWidth) bounds.width = textWidth + 2*GuiGetStyle(LABEL, BORDER_WIDTH) + 2*GuiGetStyle(LABEL, TEXT_PADDING) + 2; - - // Update control - //-------------------------------------------------------------------- - if ((state != STATE_DISABLED) && !guiLocked && !guiControlExclusiveMode) - { - Vector2 mousePoint = GetMousePosition(); - - // Check checkbox state - if (CheckCollisionPointRec(mousePoint, bounds)) - { - if (IsMouseButtonDown(MOUSE_LEFT_BUTTON)) state = STATE_PRESSED; - else state = STATE_FOCUSED; - - if (IsMouseButtonReleased(MOUSE_LEFT_BUTTON)) pressed = true; - } - } - //-------------------------------------------------------------------- - - // Draw control - //-------------------------------------------------------------------- - GuiDrawText(text, GetTextBounds(LABEL, bounds), GuiGetStyle(LABEL, TEXT_ALIGNMENT), GetColor(GuiGetStyle(LABEL, TEXT + (state*3)))); - //-------------------------------------------------------------------- - - return pressed; -} - -// Toggle Button control -int GuiToggle(Rectangle bounds, const char *text, bool *active) -{ - int result = 0; - GuiState state = guiState; - - bool temp = false; - if (active == NULL) active = &temp; - - // Update control - //-------------------------------------------------------------------- - if ((state != STATE_DISABLED) && !guiLocked && !guiControlExclusiveMode) - { - Vector2 mousePoint = GetMousePosition(); - - // Check toggle button state - if (CheckCollisionPointRec(mousePoint, bounds)) - { - if (IsMouseButtonDown(MOUSE_LEFT_BUTTON)) state = STATE_PRESSED; - else if (IsMouseButtonReleased(MOUSE_LEFT_BUTTON)) - { - state = STATE_NORMAL; - *active = !(*active); - } - else state = STATE_FOCUSED; - } - } - //-------------------------------------------------------------------- - - // Draw control - //-------------------------------------------------------------------- - if (state == STATE_NORMAL) - { - GuiDrawRectangle(bounds, GuiGetStyle(TOGGLE, BORDER_WIDTH), GetColor(GuiGetStyle(TOGGLE, ((*active)? BORDER_COLOR_PRESSED : (BORDER + state*3)))), GetColor(GuiGetStyle(TOGGLE, ((*active)? BASE_COLOR_PRESSED : (BASE + state*3))))); - GuiDrawText(text, GetTextBounds(TOGGLE, bounds), GuiGetStyle(TOGGLE, TEXT_ALIGNMENT), GetColor(GuiGetStyle(TOGGLE, ((*active)? TEXT_COLOR_PRESSED : (TEXT + state*3))))); - } - else - { - GuiDrawRectangle(bounds, GuiGetStyle(TOGGLE, BORDER_WIDTH), GetColor(GuiGetStyle(TOGGLE, BORDER + state*3)), GetColor(GuiGetStyle(TOGGLE, BASE + state*3))); - GuiDrawText(text, GetTextBounds(TOGGLE, bounds), GuiGetStyle(TOGGLE, TEXT_ALIGNMENT), GetColor(GuiGetStyle(TOGGLE, TEXT + state*3))); - } - - if (state == STATE_FOCUSED) GuiTooltip(bounds); - //-------------------------------------------------------------------- - - return result; -} - -// Toggle Group control -int GuiToggleGroup(Rectangle bounds, const char *text, int *active) -{ - #if !defined(RAYGUI_TOGGLEGROUP_MAX_ITEMS) - #define RAYGUI_TOGGLEGROUP_MAX_ITEMS 32 - #endif - - int result = 0; - float initBoundsX = bounds.x; - - int temp = 0; - if (active == NULL) active = &temp; - - bool toggle = false; // Required for individual toggles - - // Get substrings items from text (items pointers) - int rows[RAYGUI_TOGGLEGROUP_MAX_ITEMS] = { 0 }; - int itemCount = 0; - const char **items = GuiTextSplit(text, ';', &itemCount, rows); - - int prevRow = rows[0]; - - for (int i = 0; i < itemCount; i++) - { - if (prevRow != rows[i]) - { - bounds.x = initBoundsX; - bounds.y += (bounds.height + GuiGetStyle(TOGGLE, GROUP_PADDING)); - prevRow = rows[i]; - } - - if (i == (*active)) - { - toggle = true; - GuiToggle(bounds, items[i], &toggle); - } - else - { - toggle = false; - GuiToggle(bounds, items[i], &toggle); - if (toggle) *active = i; - } - - bounds.x += (bounds.width + GuiGetStyle(TOGGLE, GROUP_PADDING)); - } - - return result; -} - -// Toggle Slider control extended -int GuiToggleSlider(Rectangle bounds, const char *text, int *active) -{ - int result = 0; - GuiState state = guiState; - - int temp = 0; - if (active == NULL) active = &temp; - - //bool toggle = false; // Required for individual toggles - - // Get substrings items from text (items pointers) - int itemCount = 0; - const char **items = NULL; - - if (text != NULL) items = GuiTextSplit(text, ';', &itemCount, NULL); - - Rectangle slider = { - 0, // Calculated later depending on the active toggle - bounds.y + GuiGetStyle(SLIDER, BORDER_WIDTH) + GuiGetStyle(SLIDER, SLIDER_PADDING), - (bounds.width - 2*GuiGetStyle(SLIDER, BORDER_WIDTH) - (itemCount + 1)*GuiGetStyle(SLIDER, SLIDER_PADDING))/itemCount, - bounds.height - 2*GuiGetStyle(SLIDER, BORDER_WIDTH) - 2*GuiGetStyle(SLIDER, SLIDER_PADDING) }; - - // Update control - //-------------------------------------------------------------------- - if ((state != STATE_DISABLED) && !guiLocked) - { - Vector2 mousePoint = GetMousePosition(); - - if (CheckCollisionPointRec(mousePoint, bounds)) - { - if (IsMouseButtonDown(MOUSE_LEFT_BUTTON)) state = STATE_PRESSED; - else if (IsMouseButtonReleased(MOUSE_LEFT_BUTTON)) - { - state = STATE_PRESSED; - (*active)++; - result = 1; - } - else state = STATE_FOCUSED; - } - - if ((*active) && (state != STATE_FOCUSED)) state = STATE_PRESSED; - } - - if (*active >= itemCount) *active = 0; - slider.x = bounds.x + GuiGetStyle(SLIDER, BORDER_WIDTH) + (*active + 1)*GuiGetStyle(SLIDER, SLIDER_PADDING) + (*active)*slider.width; - //-------------------------------------------------------------------- - - // Draw control - //-------------------------------------------------------------------- - GuiDrawRectangle(bounds, GuiGetStyle(SLIDER, BORDER_WIDTH), GetColor(GuiGetStyle(TOGGLE, BORDER + (state*3))), - GetColor(GuiGetStyle(TOGGLE, BASE_COLOR_NORMAL))); - - // Draw internal slider - if (state == STATE_NORMAL) GuiDrawRectangle(slider, 0, BLANK, GetColor(GuiGetStyle(SLIDER, BASE_COLOR_PRESSED))); - else if (state == STATE_FOCUSED) GuiDrawRectangle(slider, 0, BLANK, GetColor(GuiGetStyle(SLIDER, BASE_COLOR_FOCUSED))); - else if (state == STATE_PRESSED) GuiDrawRectangle(slider, 0, BLANK, GetColor(GuiGetStyle(SLIDER, BASE_COLOR_PRESSED))); - - // Draw text in slider - if (text != NULL) - { - Rectangle textBounds = { 0 }; - textBounds.width = (float)GetTextWidth(text); - textBounds.height = (float)GuiGetStyle(DEFAULT, TEXT_SIZE); - textBounds.x = slider.x + slider.width/2 - textBounds.width/2; - textBounds.y = bounds.y + bounds.height/2 - GuiGetStyle(DEFAULT, TEXT_SIZE)/2; - - GuiDrawText(items[*active], textBounds, GuiGetStyle(TOGGLE, TEXT_ALIGNMENT), Fade(GetColor(GuiGetStyle(TOGGLE, TEXT + (state*3))), guiAlpha)); - } - //-------------------------------------------------------------------- - - return result; -} - -// Check Box control, returns 1 when state changed -int GuiCheckBox(Rectangle bounds, const char *text, bool *checked) -{ - int result = 0; - GuiState state = guiState; - - bool temp = false; - if (checked == NULL) checked = &temp; - - Rectangle textBounds = { 0 }; - - if (text != NULL) - { - textBounds.width = (float)GetTextWidth(text) + 2; - textBounds.height = (float)GuiGetStyle(DEFAULT, TEXT_SIZE); - textBounds.x = bounds.x + bounds.width + GuiGetStyle(CHECKBOX, TEXT_PADDING); - textBounds.y = bounds.y + bounds.height/2 - GuiGetStyle(DEFAULT, TEXT_SIZE)/2; - if (GuiGetStyle(CHECKBOX, TEXT_ALIGNMENT) == TEXT_ALIGN_LEFT) textBounds.x = bounds.x - textBounds.width - GuiGetStyle(CHECKBOX, TEXT_PADDING); - } - - // Update control - //-------------------------------------------------------------------- - if ((state != STATE_DISABLED) && !guiLocked && !guiControlExclusiveMode) - { - Vector2 mousePoint = GetMousePosition(); - - Rectangle totalBounds = { - (GuiGetStyle(CHECKBOX, TEXT_ALIGNMENT) == TEXT_ALIGN_LEFT)? textBounds.x : bounds.x, - bounds.y, - bounds.width + textBounds.width + GuiGetStyle(CHECKBOX, TEXT_PADDING), - bounds.height, - }; - - // Check checkbox state - if (CheckCollisionPointRec(mousePoint, totalBounds)) - { - if (IsMouseButtonDown(MOUSE_LEFT_BUTTON)) state = STATE_PRESSED; - else state = STATE_FOCUSED; - - if (IsMouseButtonReleased(MOUSE_LEFT_BUTTON)) - { - *checked = !(*checked); - result = 1; - } - } - } - //-------------------------------------------------------------------- - - // Draw control - //-------------------------------------------------------------------- - GuiDrawRectangle(bounds, GuiGetStyle(CHECKBOX, BORDER_WIDTH), GetColor(GuiGetStyle(CHECKBOX, BORDER + (state*3))), BLANK); - - if (*checked) - { - Rectangle check = { bounds.x + GuiGetStyle(CHECKBOX, BORDER_WIDTH) + GuiGetStyle(CHECKBOX, CHECK_PADDING), - bounds.y + GuiGetStyle(CHECKBOX, BORDER_WIDTH) + GuiGetStyle(CHECKBOX, CHECK_PADDING), - bounds.width - 2*(GuiGetStyle(CHECKBOX, BORDER_WIDTH) + GuiGetStyle(CHECKBOX, CHECK_PADDING)), - bounds.height - 2*(GuiGetStyle(CHECKBOX, BORDER_WIDTH) + GuiGetStyle(CHECKBOX, CHECK_PADDING)) }; - GuiDrawRectangle(check, 0, BLANK, GetColor(GuiGetStyle(CHECKBOX, TEXT + state*3))); - } - - GuiDrawText(text, textBounds, (GuiGetStyle(CHECKBOX, TEXT_ALIGNMENT) == TEXT_ALIGN_RIGHT)? TEXT_ALIGN_LEFT : TEXT_ALIGN_RIGHT, GetColor(GuiGetStyle(LABEL, TEXT + (state*3)))); - //-------------------------------------------------------------------- - - return result; -} - -// Combo Box control -int GuiComboBox(Rectangle bounds, const char *text, int *active) -{ - int result = 0; - GuiState state = guiState; - - int temp = 0; - if (active == NULL) active = &temp; - - bounds.width -= (GuiGetStyle(COMBOBOX, COMBO_BUTTON_WIDTH) + GuiGetStyle(COMBOBOX, COMBO_BUTTON_SPACING)); - - Rectangle selector = { (float)bounds.x + bounds.width + GuiGetStyle(COMBOBOX, COMBO_BUTTON_SPACING), - (float)bounds.y, (float)GuiGetStyle(COMBOBOX, COMBO_BUTTON_WIDTH), (float)bounds.height }; - - // Get substrings items from text (items pointers, lengths and count) - int itemCount = 0; - const char **items = GuiTextSplit(text, ';', &itemCount, NULL); - - if (*active < 0) *active = 0; - else if (*active > (itemCount - 1)) *active = itemCount - 1; - - // Update control - //-------------------------------------------------------------------- - if ((state != STATE_DISABLED) && !guiLocked && (itemCount > 1) && !guiControlExclusiveMode) - { - Vector2 mousePoint = GetMousePosition(); - - if (CheckCollisionPointRec(mousePoint, bounds) || - CheckCollisionPointRec(mousePoint, selector)) - { - if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) - { - *active += 1; - if (*active >= itemCount) *active = 0; // Cyclic combobox - } - - if (IsMouseButtonDown(MOUSE_LEFT_BUTTON)) state = STATE_PRESSED; - else state = STATE_FOCUSED; - } - } - //-------------------------------------------------------------------- - - // Draw control - //-------------------------------------------------------------------- - // Draw combo box main - GuiDrawRectangle(bounds, GuiGetStyle(COMBOBOX, BORDER_WIDTH), GetColor(GuiGetStyle(COMBOBOX, BORDER + (state*3))), GetColor(GuiGetStyle(COMBOBOX, BASE + (state*3)))); - GuiDrawText(items[*active], GetTextBounds(COMBOBOX, bounds), GuiGetStyle(COMBOBOX, TEXT_ALIGNMENT), GetColor(GuiGetStyle(COMBOBOX, TEXT + (state*3)))); - - // Draw selector using a custom button - // NOTE: BORDER_WIDTH and TEXT_ALIGNMENT forced values - int tempBorderWidth = GuiGetStyle(BUTTON, BORDER_WIDTH); - int tempTextAlign = GuiGetStyle(BUTTON, TEXT_ALIGNMENT); - GuiSetStyle(BUTTON, BORDER_WIDTH, 1); - GuiSetStyle(BUTTON, TEXT_ALIGNMENT, TEXT_ALIGN_CENTER); - - GuiButton(selector, TextFormat("%i/%i", *active + 1, itemCount)); - - GuiSetStyle(BUTTON, TEXT_ALIGNMENT, tempTextAlign); - GuiSetStyle(BUTTON, BORDER_WIDTH, tempBorderWidth); - //-------------------------------------------------------------------- - - return result; -} - -// Dropdown Box control -// NOTE: Returns mouse click -int GuiDropdownBox(Rectangle bounds, const char *text, int *active, bool editMode) -{ - int result = 0; - GuiState state = guiState; - - int temp = 0; - if (active == NULL) active = &temp; - - int itemSelected = *active; - int itemFocused = -1; - - int direction = 0; // Dropdown box open direction: down (default) - if (GuiGetStyle(DROPDOWNBOX, DROPDOWN_ROLL_UP) == 1) direction = 1; // Up - - // Get substrings items from text (items pointers, lengths and count) - int itemCount = 0; - const char **items = GuiTextSplit(text, ';', &itemCount, NULL); - - Rectangle boundsOpen = bounds; - boundsOpen.height = (itemCount + 1)*(bounds.height + GuiGetStyle(DROPDOWNBOX, DROPDOWN_ITEMS_SPACING)); - if (direction == 1) boundsOpen.y -= itemCount*(bounds.height + GuiGetStyle(DROPDOWNBOX, DROPDOWN_ITEMS_SPACING)) + GuiGetStyle(DROPDOWNBOX, DROPDOWN_ITEMS_SPACING); - - Rectangle itemBounds = bounds; - - // Update control - //-------------------------------------------------------------------- - if ((state != STATE_DISABLED) && (editMode || !guiLocked) && (itemCount > 1) && !guiControlExclusiveMode) - { - Vector2 mousePoint = GetMousePosition(); - - if (editMode) - { - state = STATE_PRESSED; - - // Check if mouse has been pressed or released outside limits - if (!CheckCollisionPointRec(mousePoint, boundsOpen)) - { - if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON) || IsMouseButtonReleased(MOUSE_LEFT_BUTTON)) result = 1; - } - - // Check if already selected item has been pressed again - if (CheckCollisionPointRec(mousePoint, bounds) && IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) result = 1; - - // Check focused and selected item - for (int i = 0; i < itemCount; i++) - { - // Update item rectangle y position for next item - if (direction == 0) itemBounds.y += (bounds.height + GuiGetStyle(DROPDOWNBOX, DROPDOWN_ITEMS_SPACING)); - else itemBounds.y -= (bounds.height + GuiGetStyle(DROPDOWNBOX, DROPDOWN_ITEMS_SPACING)); - - if (CheckCollisionPointRec(mousePoint, itemBounds)) - { - itemFocused = i; - if (IsMouseButtonReleased(MOUSE_LEFT_BUTTON)) - { - itemSelected = i; - result = 1; // Item selected - } - break; - } - } - - itemBounds = bounds; - } - else - { - if (CheckCollisionPointRec(mousePoint, bounds)) - { - if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) - { - result = 1; - state = STATE_PRESSED; - } - else state = STATE_FOCUSED; - } - } - } - //-------------------------------------------------------------------- - - // Draw control - //-------------------------------------------------------------------- - if (editMode) GuiPanel(boundsOpen, NULL); - - GuiDrawRectangle(bounds, GuiGetStyle(DROPDOWNBOX, BORDER_WIDTH), GetColor(GuiGetStyle(DROPDOWNBOX, BORDER + state*3)), GetColor(GuiGetStyle(DROPDOWNBOX, BASE + state*3))); - GuiDrawText(items[itemSelected], GetTextBounds(DROPDOWNBOX, bounds), GuiGetStyle(DROPDOWNBOX, TEXT_ALIGNMENT), GetColor(GuiGetStyle(DROPDOWNBOX, TEXT + state*3))); - - if (editMode) - { - // Draw visible items - for (int i = 0; i < itemCount; i++) - { - // Update item rectangle y position for next item - if (direction == 0) itemBounds.y += (bounds.height + GuiGetStyle(DROPDOWNBOX, DROPDOWN_ITEMS_SPACING)); - else itemBounds.y -= (bounds.height + GuiGetStyle(DROPDOWNBOX, DROPDOWN_ITEMS_SPACING)); - - if (i == itemSelected) - { - GuiDrawRectangle(itemBounds, GuiGetStyle(DROPDOWNBOX, BORDER_WIDTH), GetColor(GuiGetStyle(DROPDOWNBOX, BORDER_COLOR_PRESSED)), GetColor(GuiGetStyle(DROPDOWNBOX, BASE_COLOR_PRESSED))); - GuiDrawText(items[i], GetTextBounds(DROPDOWNBOX, itemBounds), GuiGetStyle(DROPDOWNBOX, TEXT_ALIGNMENT), GetColor(GuiGetStyle(DROPDOWNBOX, TEXT_COLOR_PRESSED))); - } - else if (i == itemFocused) - { - GuiDrawRectangle(itemBounds, GuiGetStyle(DROPDOWNBOX, BORDER_WIDTH), GetColor(GuiGetStyle(DROPDOWNBOX, BORDER_COLOR_FOCUSED)), GetColor(GuiGetStyle(DROPDOWNBOX, BASE_COLOR_FOCUSED))); - GuiDrawText(items[i], GetTextBounds(DROPDOWNBOX, itemBounds), GuiGetStyle(DROPDOWNBOX, TEXT_ALIGNMENT), GetColor(GuiGetStyle(DROPDOWNBOX, TEXT_COLOR_FOCUSED))); - } - else GuiDrawText(items[i], GetTextBounds(DROPDOWNBOX, itemBounds), GuiGetStyle(DROPDOWNBOX, TEXT_ALIGNMENT), GetColor(GuiGetStyle(DROPDOWNBOX, TEXT_COLOR_NORMAL))); - } - } - - if (!GuiGetStyle(DROPDOWNBOX, DROPDOWN_ARROW_HIDDEN)) - { - // Draw arrows (using icon if available) -#if defined(RAYGUI_NO_ICONS) - GuiDrawText("v", RAYGUI_CLITERAL(Rectangle){ bounds.x + bounds.width - GuiGetStyle(DROPDOWNBOX, ARROW_PADDING), bounds.y + bounds.height/2 - 2, 10, 10 }, - TEXT_ALIGN_CENTER, GetColor(GuiGetStyle(DROPDOWNBOX, TEXT + (state*3)))); -#else - GuiDrawText(direction? "#121#" : "#120#", RAYGUI_CLITERAL(Rectangle){ bounds.x + bounds.width - GuiGetStyle(DROPDOWNBOX, ARROW_PADDING), bounds.y + bounds.height/2 - 6, 10, 10 }, - TEXT_ALIGN_CENTER, GetColor(GuiGetStyle(DROPDOWNBOX, TEXT + (state*3)))); // ICON_ARROW_DOWN_FILL -#endif - } - //-------------------------------------------------------------------- - - *active = itemSelected; - - // TODO: Use result to return more internal states: mouse-press out-of-bounds, mouse-press over selected-item... - return result; // Mouse click: result = 1 -} - -// Text Box control -// NOTE: Returns true on ENTER pressed (useful for data validation) -int GuiTextBox(Rectangle bounds, char *text, int textSize, bool editMode) -{ - #if !defined(RAYGUI_TEXTBOX_AUTO_CURSOR_COOLDOWN) - #define RAYGUI_TEXTBOX_AUTO_CURSOR_COOLDOWN 40 // Frames to wait for autocursor movement - #endif - #if !defined(RAYGUI_TEXTBOX_AUTO_CURSOR_DELAY) - #define RAYGUI_TEXTBOX_AUTO_CURSOR_DELAY 1 // Frames delay for autocursor movement - #endif - - int result = 0; - GuiState state = guiState; - - bool multiline = false; // TODO: Consider multiline text input - int wrapMode = GuiGetStyle(DEFAULT, TEXT_WRAP_MODE); - - Rectangle textBounds = GetTextBounds(TEXTBOX, bounds); - int textLength = (int)strlen(text); // Get current text length - int thisCursorIndex = textBoxCursorIndex; - if (thisCursorIndex > textLength) thisCursorIndex = textLength; - int textWidth = GetTextWidth(text) - GetTextWidth(text + thisCursorIndex); - int textIndexOffset = 0; // Text index offset to start drawing in the box - - // Cursor rectangle - // NOTE: Position X value should be updated - Rectangle cursor = { - textBounds.x + textWidth + GuiGetStyle(DEFAULT, TEXT_SPACING), - textBounds.y + textBounds.height/2 - GuiGetStyle(DEFAULT, TEXT_SIZE), - 2, - (float)GuiGetStyle(DEFAULT, TEXT_SIZE)*2 - }; - - if (cursor.height >= bounds.height) cursor.height = bounds.height - GuiGetStyle(TEXTBOX, BORDER_WIDTH)*2; - if (cursor.y < (bounds.y + GuiGetStyle(TEXTBOX, BORDER_WIDTH))) cursor.y = bounds.y + GuiGetStyle(TEXTBOX, BORDER_WIDTH); - - // Mouse cursor rectangle - // NOTE: Initialized outside of screen - Rectangle mouseCursor = cursor; - mouseCursor.x = -1; - mouseCursor.width = 1; - - // Auto-cursor movement logic - // NOTE: Cursor moves automatically when key down after some time - if (IsKeyDown(KEY_LEFT) || IsKeyDown(KEY_RIGHT) || IsKeyDown(KEY_UP) || IsKeyDown(KEY_DOWN) || IsKeyDown(KEY_BACKSPACE) || IsKeyDown(KEY_DELETE)) autoCursorCooldownCounter++; - else - { - autoCursorCooldownCounter = 0; // GLOBAL: Cursor cooldown counter - autoCursorDelayCounter = 0; // GLOBAL: Cursor delay counter - } - - // Blink-cursor frame counter - //if (!autoCursorMode) blinkCursorFrameCounter++; - //else blinkCursorFrameCounter = 0; - - // Update control - //-------------------------------------------------------------------- - // WARNING: Text editing is only supported under certain conditions: - if ((state != STATE_DISABLED) && // Control not disabled - !GuiGetStyle(TEXTBOX, TEXT_READONLY) && // TextBox not on read-only mode - !guiLocked && // Gui not locked - !guiControlExclusiveMode && // No gui slider on dragging - (wrapMode == TEXT_WRAP_NONE)) // No wrap mode - { - Vector2 mousePosition = GetMousePosition(); - - if (editMode) - { - state = STATE_PRESSED; - - if (textBoxCursorIndex > textLength) textBoxCursorIndex = textLength; - - // If text does not fit in the textbox and current cursor position is out of bounds, - // we add an index offset to text for drawing only what requires depending on cursor - while (textWidth >= textBounds.width) - { - int nextCodepointSize = 0; - GetCodepointNext(text + textIndexOffset, &nextCodepointSize); - - textIndexOffset += nextCodepointSize; - - textWidth = GetTextWidth(text + textIndexOffset) - GetTextWidth(text + textBoxCursorIndex); - } - - int codepoint = GetCharPressed(); // Get Unicode codepoint - if (multiline && IsKeyPressed(KEY_ENTER)) codepoint = (int)'\n'; - - // Encode codepoint as UTF-8 - int codepointSize = 0; - const char *charEncoded = CodepointToUTF8(codepoint, &codepointSize); - - // Add codepoint to text, at current cursor position - // NOTE: Make sure we do not overflow buffer size - if (((multiline && (codepoint == (int)'\n')) || (codepoint >= 32)) && ((textLength + codepointSize) < textSize)) - { - // Move forward data from cursor position - for (int i = (textLength + codepointSize); i > textBoxCursorIndex; i--) text[i] = text[i - codepointSize]; - - // Add new codepoint in current cursor position - for (int i = 0; i < codepointSize; i++) text[textBoxCursorIndex + i] = charEncoded[i]; - - textBoxCursorIndex += codepointSize; - textLength += codepointSize; - - // Make sure text last character is EOL - text[textLength] = '\0'; - } - - // Move cursor to start - if ((textLength > 0) && IsKeyPressed(KEY_HOME)) textBoxCursorIndex = 0; - - // Move cursor to end - if ((textLength > textBoxCursorIndex) && IsKeyPressed(KEY_END)) textBoxCursorIndex = textLength; - - // Delete codepoint from text, after current cursor position - if ((textLength > textBoxCursorIndex) && (IsKeyPressed(KEY_DELETE) || (IsKeyDown(KEY_DELETE) && (autoCursorCooldownCounter >= RAYGUI_TEXTBOX_AUTO_CURSOR_COOLDOWN)))) - { - autoCursorDelayCounter++; - - if (IsKeyPressed(KEY_DELETE) || (autoCursorDelayCounter%RAYGUI_TEXTBOX_AUTO_CURSOR_DELAY) == 0) // Delay every movement some frames - { - int nextCodepointSize = 0; - GetCodepointNext(text + textBoxCursorIndex, &nextCodepointSize); - - // Move backward text from cursor position - for (int i = textBoxCursorIndex; i < textLength; i++) text[i] = text[i + nextCodepointSize]; - - textLength -= codepointSize; - if (textBoxCursorIndex > textLength) textBoxCursorIndex = textLength; - - // Make sure text last character is EOL - text[textLength] = '\0'; - } - } - - // Delete related codepoints from text, before current cursor position - if ((textLength > 0) && IsKeyPressed(KEY_BACKSPACE) && (IsKeyDown(KEY_LEFT_CONTROL) || IsKeyDown(KEY_RIGHT_CONTROL))) - { - int i = textBoxCursorIndex - 1; - int accCodepointSize = 0; - - // Move cursor to the end of word if on space already - while ((i > 0) && isspace(text[i])) - { - int prevCodepointSize = 0; - GetCodepointPrevious(text + i, &prevCodepointSize); - i -= prevCodepointSize; - accCodepointSize += prevCodepointSize; - } - - // Move cursor to the start of the word - while ((i > 0) && !isspace(text[i])) - { - int prevCodepointSize = 0; - GetCodepointPrevious(text + i, &prevCodepointSize); - i -= prevCodepointSize; - accCodepointSize += prevCodepointSize; - } - - // Move forward text from cursor position - for (int j = (textBoxCursorIndex - accCodepointSize); j < textLength; j++) text[j] = text[j + accCodepointSize]; - - // Prevent cursor index from decrementing past 0 - if (textBoxCursorIndex > 0) - { - textBoxCursorIndex -= accCodepointSize; - textLength -= accCodepointSize; - } - - // Make sure text last character is EOL - text[textLength] = '\0'; - } - else if ((textLength > 0) && (IsKeyPressed(KEY_BACKSPACE) || (IsKeyDown(KEY_BACKSPACE) && (autoCursorCooldownCounter >= RAYGUI_TEXTBOX_AUTO_CURSOR_COOLDOWN)))) - { - autoCursorDelayCounter++; - - if (IsKeyPressed(KEY_BACKSPACE) || (autoCursorDelayCounter%RAYGUI_TEXTBOX_AUTO_CURSOR_DELAY) == 0) // Delay every movement some frames - { - int prevCodepointSize = 0; - - // Prevent cursor index from decrementing past 0 - if (textBoxCursorIndex > 0) - { - GetCodepointPrevious(text + textBoxCursorIndex, &prevCodepointSize); - - // Move backward text from cursor position - for (int i = (textBoxCursorIndex - prevCodepointSize); i < textLength; i++) text[i] = text[i + prevCodepointSize]; - - textBoxCursorIndex -= codepointSize; - textLength -= codepointSize; - } - - // Make sure text last character is EOL - text[textLength] = '\0'; - } - } - - // Move cursor position with keys - if (IsKeyPressed(KEY_LEFT) || (IsKeyDown(KEY_LEFT) && (autoCursorCooldownCounter > RAYGUI_TEXTBOX_AUTO_CURSOR_COOLDOWN))) - { - autoCursorDelayCounter++; - - if (IsKeyPressed(KEY_LEFT) || (autoCursorDelayCounter%RAYGUI_TEXTBOX_AUTO_CURSOR_DELAY) == 0) // Delay every movement some frames - { - int prevCodepointSize = 0; - if (textBoxCursorIndex > 0) GetCodepointPrevious(text + textBoxCursorIndex, &prevCodepointSize); - - if (textBoxCursorIndex >= prevCodepointSize) textBoxCursorIndex -= prevCodepointSize; - } - } - else if (IsKeyPressed(KEY_RIGHT) || (IsKeyDown(KEY_RIGHT) && (autoCursorCooldownCounter > RAYGUI_TEXTBOX_AUTO_CURSOR_COOLDOWN))) - { - autoCursorDelayCounter++; - - if (IsKeyPressed(KEY_RIGHT) || (autoCursorDelayCounter%RAYGUI_TEXTBOX_AUTO_CURSOR_DELAY) == 0) // Delay every movement some frames - { - int nextCodepointSize = 0; - GetCodepointNext(text + textBoxCursorIndex, &nextCodepointSize); - - if ((textBoxCursorIndex + nextCodepointSize) <= textLength) textBoxCursorIndex += nextCodepointSize; - } - } - - // Move cursor position with mouse - if (CheckCollisionPointRec(mousePosition, textBounds)) // Mouse hover text - { - float scaleFactor = (float)GuiGetStyle(DEFAULT, TEXT_SIZE)/(float)guiFont.baseSize; - int codepointIndex = 0; - float glyphWidth = 0.0f; - float widthToMouseX = 0; - int mouseCursorIndex = 0; - - for (int i = textIndexOffset; i < textLength; i++) - { - codepoint = GetCodepointNext(&text[i], &codepointSize); - codepointIndex = GetGlyphIndex(guiFont, codepoint); - - if (guiFont.glyphs[codepointIndex].advanceX == 0) glyphWidth = ((float)guiFont.recs[codepointIndex].width*scaleFactor); - else glyphWidth = ((float)guiFont.glyphs[codepointIndex].advanceX*scaleFactor); - - if (mousePosition.x <= (textBounds.x + (widthToMouseX + glyphWidth/2))) - { - mouseCursor.x = textBounds.x + widthToMouseX; - mouseCursorIndex = i; - break; - } - - widthToMouseX += (glyphWidth + (float)GuiGetStyle(DEFAULT, TEXT_SPACING)); - } - - // Check if mouse cursor is at the last position - int textEndWidth = GetTextWidth(text + textIndexOffset); - if (GetMousePosition().x >= (textBounds.x + textEndWidth - glyphWidth/2)) - { - mouseCursor.x = textBounds.x + textEndWidth; - mouseCursorIndex = textLength; - } - - // Place cursor at required index on mouse click - if ((mouseCursor.x >= 0) && IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) - { - cursor.x = mouseCursor.x; - textBoxCursorIndex = mouseCursorIndex; - } - } - else mouseCursor.x = -1; - - // Recalculate cursor position.y depending on textBoxCursorIndex - cursor.x = bounds.x + GuiGetStyle(TEXTBOX, TEXT_PADDING) + GetTextWidth(text + textIndexOffset) - GetTextWidth(text + textBoxCursorIndex) + GuiGetStyle(DEFAULT, TEXT_SPACING); - //if (multiline) cursor.y = GetTextLines() - - // Finish text editing on ENTER or mouse click outside bounds - if ((!multiline && IsKeyPressed(KEY_ENTER)) || - (!CheckCollisionPointRec(mousePosition, bounds) && IsMouseButtonPressed(MOUSE_LEFT_BUTTON))) - { - textBoxCursorIndex = 0; // GLOBAL: Reset the shared cursor index - result = 1; - } - } - else - { - if (CheckCollisionPointRec(mousePosition, bounds)) - { - state = STATE_FOCUSED; - - if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) - { - textBoxCursorIndex = textLength; // GLOBAL: Place cursor index to the end of current text - result = 1; - } - } - } - } - //-------------------------------------------------------------------- - - // Draw control - //-------------------------------------------------------------------- - if (state == STATE_PRESSED) - { - GuiDrawRectangle(bounds, GuiGetStyle(TEXTBOX, BORDER_WIDTH), GetColor(GuiGetStyle(TEXTBOX, BORDER + (state*3))), GetColor(GuiGetStyle(TEXTBOX, BASE_COLOR_PRESSED))); - } - else if (state == STATE_DISABLED) - { - GuiDrawRectangle(bounds, GuiGetStyle(TEXTBOX, BORDER_WIDTH), GetColor(GuiGetStyle(TEXTBOX, BORDER + (state*3))), GetColor(GuiGetStyle(TEXTBOX, BASE_COLOR_DISABLED))); - } - else GuiDrawRectangle(bounds, GuiGetStyle(TEXTBOX, BORDER_WIDTH), GetColor(GuiGetStyle(TEXTBOX, BORDER + (state*3))), BLANK); - - // Draw text considering index offset if required - // NOTE: Text index offset depends on cursor position - GuiDrawText(text + textIndexOffset, textBounds, GuiGetStyle(TEXTBOX, TEXT_ALIGNMENT), GetColor(GuiGetStyle(TEXTBOX, TEXT + (state*3)))); - - // Draw cursor - if (editMode && !GuiGetStyle(TEXTBOX, TEXT_READONLY)) - { - //if (autoCursorMode || ((blinkCursorFrameCounter/40)%2 == 0)) - GuiDrawRectangle(cursor, 0, BLANK, GetColor(GuiGetStyle(TEXTBOX, BORDER_COLOR_PRESSED))); - - // Draw mouse position cursor (if required) - if (mouseCursor.x >= 0) GuiDrawRectangle(mouseCursor, 0, BLANK, GetColor(GuiGetStyle(TEXTBOX, BORDER_COLOR_PRESSED))); - } - else if (state == STATE_FOCUSED) GuiTooltip(bounds); - //-------------------------------------------------------------------- - - return result; // Mouse button pressed: result = 1 -} - -/* -// Text Box control with multiple lines and word-wrap -// NOTE: This text-box is readonly, no editing supported by default -bool GuiTextBoxMulti(Rectangle bounds, char *text, int textSize, bool editMode) -{ - bool pressed = false; - - GuiSetStyle(TEXTBOX, TEXT_READONLY, 1); - GuiSetStyle(DEFAULT, TEXT_WRAP_MODE, TEXT_WRAP_WORD); // WARNING: If wrap mode enabled, text editing is not supported - GuiSetStyle(DEFAULT, TEXT_ALIGNMENT_VERTICAL, TEXT_ALIGN_TOP); - - // TODO: Implement methods to calculate cursor position properly - pressed = GuiTextBox(bounds, text, textSize, editMode); - - GuiSetStyle(DEFAULT, TEXT_ALIGNMENT_VERTICAL, TEXT_ALIGN_MIDDLE); - GuiSetStyle(DEFAULT, TEXT_WRAP_MODE, TEXT_WRAP_NONE); - GuiSetStyle(TEXTBOX, TEXT_READONLY, 0); - - return pressed; -} -*/ - -// Spinner control, returns selected value -int GuiSpinner(Rectangle bounds, const char *text, int *value, int minValue, int maxValue, bool editMode) -{ - int result = 1; - GuiState state = guiState; - - int tempValue = *value; - - Rectangle spinner = { bounds.x + GuiGetStyle(SPINNER, SPIN_BUTTON_WIDTH) + GuiGetStyle(SPINNER, SPIN_BUTTON_SPACING), bounds.y, - bounds.width - 2*(GuiGetStyle(SPINNER, SPIN_BUTTON_WIDTH) + GuiGetStyle(SPINNER, SPIN_BUTTON_SPACING)), bounds.height }; - Rectangle leftButtonBound = { (float)bounds.x, (float)bounds.y, (float)GuiGetStyle(SPINNER, SPIN_BUTTON_WIDTH), (float)bounds.height }; - Rectangle rightButtonBound = { (float)bounds.x + bounds.width - GuiGetStyle(SPINNER, SPIN_BUTTON_WIDTH), (float)bounds.y, (float)GuiGetStyle(SPINNER, SPIN_BUTTON_WIDTH), (float)bounds.height }; - - Rectangle textBounds = { 0 }; - if (text != NULL) - { - textBounds.width = (float)GetTextWidth(text) + 2; - textBounds.height = (float)GuiGetStyle(DEFAULT, TEXT_SIZE); - textBounds.x = bounds.x + bounds.width + GuiGetStyle(SPINNER, TEXT_PADDING); - textBounds.y = bounds.y + bounds.height/2 - GuiGetStyle(DEFAULT, TEXT_SIZE)/2; - if (GuiGetStyle(SPINNER, TEXT_ALIGNMENT) == TEXT_ALIGN_LEFT) textBounds.x = bounds.x - textBounds.width - GuiGetStyle(SPINNER, TEXT_PADDING); - } - - // Update control - //-------------------------------------------------------------------- - if ((state != STATE_DISABLED) && !guiLocked && !guiControlExclusiveMode) - { - Vector2 mousePoint = GetMousePosition(); - - // Check spinner state - if (CheckCollisionPointRec(mousePoint, bounds)) - { - if (IsMouseButtonDown(MOUSE_LEFT_BUTTON)) state = STATE_PRESSED; - else state = STATE_FOCUSED; - } - } - -#if defined(RAYGUI_NO_ICONS) - if (GuiButton(leftButtonBound, "<")) tempValue--; - if (GuiButton(rightButtonBound, ">")) tempValue++; -#else - if (GuiButton(leftButtonBound, GuiIconText(ICON_ARROW_LEFT_FILL, NULL))) tempValue--; - if (GuiButton(rightButtonBound, GuiIconText(ICON_ARROW_RIGHT_FILL, NULL))) tempValue++; -#endif - - if (!editMode) - { - if (tempValue < minValue) tempValue = minValue; - if (tempValue > maxValue) tempValue = maxValue; - } - //-------------------------------------------------------------------- - - // Draw control - //-------------------------------------------------------------------- - result = GuiValueBox(spinner, NULL, &tempValue, minValue, maxValue, editMode); - - // Draw value selector custom buttons - // NOTE: BORDER_WIDTH and TEXT_ALIGNMENT forced values - int tempBorderWidth = GuiGetStyle(BUTTON, BORDER_WIDTH); - int tempTextAlign = GuiGetStyle(BUTTON, TEXT_ALIGNMENT); - GuiSetStyle(BUTTON, BORDER_WIDTH, GuiGetStyle(SPINNER, BORDER_WIDTH)); - GuiSetStyle(BUTTON, TEXT_ALIGNMENT, TEXT_ALIGN_CENTER); - - GuiSetStyle(BUTTON, TEXT_ALIGNMENT, tempTextAlign); - GuiSetStyle(BUTTON, BORDER_WIDTH, tempBorderWidth); - - // Draw text label if provided - GuiDrawText(text, textBounds, (GuiGetStyle(SPINNER, TEXT_ALIGNMENT) == TEXT_ALIGN_RIGHT)? TEXT_ALIGN_LEFT : TEXT_ALIGN_RIGHT, GetColor(GuiGetStyle(LABEL, TEXT + (state*3)))); - //-------------------------------------------------------------------- - - *value = tempValue; - return result; -} - -// Value Box control, updates input text with numbers -// NOTE: Requires static variables: frameCounter -int GuiValueBox(Rectangle bounds, const char *text, int *value, int minValue, int maxValue, bool editMode) -{ - #if !defined(RAYGUI_VALUEBOX_MAX_CHARS) - #define RAYGUI_VALUEBOX_MAX_CHARS 32 - #endif - - int result = 0; - GuiState state = guiState; - - char textValue[RAYGUI_VALUEBOX_MAX_CHARS + 1] = "\0"; - sprintf(textValue, "%i", *value); - - Rectangle textBounds = { 0 }; - if (text != NULL) - { - textBounds.width = (float)GetTextWidth(text) + 2; - textBounds.height = (float)GuiGetStyle(DEFAULT, TEXT_SIZE); - textBounds.x = bounds.x + bounds.width + GuiGetStyle(VALUEBOX, TEXT_PADDING); - textBounds.y = bounds.y + bounds.height/2 - GuiGetStyle(DEFAULT, TEXT_SIZE)/2; - if (GuiGetStyle(VALUEBOX, TEXT_ALIGNMENT) == TEXT_ALIGN_LEFT) textBounds.x = bounds.x - textBounds.width - GuiGetStyle(VALUEBOX, TEXT_PADDING); - } - - // Update control - //-------------------------------------------------------------------- - if ((state != STATE_DISABLED) && !guiLocked && !guiControlExclusiveMode) - { - Vector2 mousePoint = GetMousePosition(); - - bool valueHasChanged = false; - - if (editMode) - { - state = STATE_PRESSED; - - int keyCount = (int)strlen(textValue); - - // Only allow keys in range [48..57] - if (keyCount < RAYGUI_VALUEBOX_MAX_CHARS) - { - if (GetTextWidth(textValue) < bounds.width) - { - int key = GetCharPressed(); - if ((key >= 48) && (key <= 57)) - { - textValue[keyCount] = (char)key; - keyCount++; - valueHasChanged = true; - } - } - } - - // Delete text - if (keyCount > 0) - { - if (IsKeyPressed(KEY_BACKSPACE)) - { - keyCount--; - textValue[keyCount] = '\0'; - valueHasChanged = true; - } - } - - if (valueHasChanged) *value = TextToInteger(textValue); - - // NOTE: We are not clamp values until user input finishes - //if (*value > maxValue) *value = maxValue; - //else if (*value < minValue) *value = minValue; - - if ((IsKeyPressed(KEY_ENTER) || IsKeyPressed(KEY_KP_ENTER)) || (!CheckCollisionPointRec(mousePoint, bounds) && IsMouseButtonPressed(MOUSE_LEFT_BUTTON))) - { - if (*value > maxValue) *value = maxValue; - else if (*value < minValue) *value = minValue; - - result = 1; - } - } - else - { - if (*value > maxValue) *value = maxValue; - else if (*value < minValue) *value = minValue; - - if (CheckCollisionPointRec(mousePoint, bounds)) - { - state = STATE_FOCUSED; - if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) result = 1; - } - } - } - //-------------------------------------------------------------------- - - // Draw control - //-------------------------------------------------------------------- - Color baseColor = BLANK; - if (state == STATE_PRESSED) baseColor = GetColor(GuiGetStyle(VALUEBOX, BASE_COLOR_PRESSED)); - else if (state == STATE_DISABLED) baseColor = GetColor(GuiGetStyle(VALUEBOX, BASE_COLOR_DISABLED)); - - GuiDrawRectangle(bounds, GuiGetStyle(VALUEBOX, BORDER_WIDTH), GetColor(GuiGetStyle(VALUEBOX, BORDER + (state*3))), baseColor); - GuiDrawText(textValue, GetTextBounds(VALUEBOX, bounds), TEXT_ALIGN_CENTER, GetColor(GuiGetStyle(VALUEBOX, TEXT + (state*3)))); - - // Draw cursor - if (editMode) - { - // NOTE: ValueBox internal text is always centered - Rectangle cursor = { bounds.x + GetTextWidth(textValue)/2 + bounds.width/2 + 1, bounds.y + 2*GuiGetStyle(VALUEBOX, BORDER_WIDTH), 4, bounds.height - 4*GuiGetStyle(VALUEBOX, BORDER_WIDTH) }; - GuiDrawRectangle(cursor, 0, BLANK, GetColor(GuiGetStyle(VALUEBOX, BORDER_COLOR_PRESSED))); - } - - // Draw text label if provided - GuiDrawText(text, textBounds, (GuiGetStyle(VALUEBOX, TEXT_ALIGNMENT) == TEXT_ALIGN_RIGHT)? TEXT_ALIGN_LEFT : TEXT_ALIGN_RIGHT, GetColor(GuiGetStyle(LABEL, TEXT + (state*3)))); - //-------------------------------------------------------------------- - - return result; -} - -// Floating point Value Box control, updates input val_str with numbers -// NOTE: Requires static variables: frameCounter -int GuiValueBoxFloat(Rectangle bounds, const char *text, char *textValue, float *value, bool editMode) -{ - #if !defined(RAYGUI_VALUEBOX_MAX_CHARS) - #define RAYGUI_VALUEBOX_MAX_CHARS 32 - #endif - - int result = 0; - GuiState state = guiState; - - //char textValue[RAYGUI_VALUEBOX_MAX_CHARS + 1] = "\0"; - //sprintf(textValue, "%2.2f", *value); - - Rectangle textBounds = {0}; - if (text != NULL) - { - textBounds.width = (float)GetTextWidth(text) + 2; - textBounds.height = (float)GuiGetStyle(DEFAULT, TEXT_SIZE); - textBounds.x = bounds.x + bounds.width + GuiGetStyle(VALUEBOX, TEXT_PADDING); - textBounds.y = bounds.y + bounds.height/2 - GuiGetStyle(DEFAULT, TEXT_SIZE)/2; - if (GuiGetStyle(VALUEBOX, TEXT_ALIGNMENT) == TEXT_ALIGN_LEFT) textBounds.x = bounds.x - textBounds.width - GuiGetStyle(VALUEBOX, TEXT_PADDING); - } - - // Update control - //-------------------------------------------------------------------- - if ((state != STATE_DISABLED) && !guiLocked && !guiControlExclusiveMode) - { - Vector2 mousePoint = GetMousePosition(); - - bool valueHasChanged = false; - - if (editMode) - { - state = STATE_PRESSED; - - int keyCount = (int)strlen(textValue); - - // Only allow keys in range [48..57] - if (keyCount < RAYGUI_VALUEBOX_MAX_CHARS) - { - if (GetTextWidth(textValue) < bounds.width) - { - int key = GetCharPressed(); - if (((key >= 48) && (key <= 57)) || - (key == '.') || - ((keyCount == 0) && (key == '+')) || // NOTE: Sign can only be in first position - ((keyCount == 0) && (key == '-'))) - { - textValue[keyCount] = (char)key; - keyCount++; - - valueHasChanged = true; - } - } - } - - // Pressed backspace - if (IsKeyPressed(KEY_BACKSPACE)) - { - if (keyCount > 0) - { - keyCount--; - textValue[keyCount] = '\0'; - valueHasChanged = true; - } - } - - if (valueHasChanged) *value = TextToFloat(textValue); - - if ((IsKeyPressed(KEY_ENTER) || IsKeyPressed(KEY_KP_ENTER)) || (!CheckCollisionPointRec(mousePoint, bounds) && IsMouseButtonPressed(MOUSE_LEFT_BUTTON))) result = 1; - } - else - { - if (CheckCollisionPointRec(mousePoint, bounds)) - { - state = STATE_FOCUSED; - if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) result = 1; - } - } - } - //-------------------------------------------------------------------- - - // Draw control - //-------------------------------------------------------------------- - Color baseColor = BLANK; - if (state == STATE_PRESSED) baseColor = GetColor(GuiGetStyle(VALUEBOX, BASE_COLOR_PRESSED)); - else if (state == STATE_DISABLED) baseColor = GetColor(GuiGetStyle(VALUEBOX, BASE_COLOR_DISABLED)); - - GuiDrawRectangle(bounds, GuiGetStyle(VALUEBOX, BORDER_WIDTH), GetColor(GuiGetStyle(VALUEBOX, BORDER + (state*3))), baseColor); - GuiDrawText(textValue, GetTextBounds(VALUEBOX, bounds), TEXT_ALIGN_CENTER, GetColor(GuiGetStyle(VALUEBOX, TEXT + (state*3)))); - - // Draw cursor - if (editMode) - { - // NOTE: ValueBox internal text is always centered - Rectangle cursor = {bounds.x + GetTextWidth(textValue)/2 + bounds.width/2 + 1, - bounds.y + 2*GuiGetStyle(VALUEBOX, BORDER_WIDTH), 4, - bounds.height - 4*GuiGetStyle(VALUEBOX, BORDER_WIDTH)}; - GuiDrawRectangle(cursor, 0, BLANK, GetColor(GuiGetStyle(VALUEBOX, BORDER_COLOR_PRESSED))); - } - - // Draw text label if provided - GuiDrawText(text, textBounds, - (GuiGetStyle(VALUEBOX, TEXT_ALIGNMENT) == TEXT_ALIGN_RIGHT)? TEXT_ALIGN_LEFT : TEXT_ALIGN_RIGHT, - GetColor(GuiGetStyle(LABEL, TEXT + (state*3)))); - //-------------------------------------------------------------------- - - return result; -} - -// Slider control with pro parameters -// NOTE: Other GuiSlider*() controls use this one -int GuiSliderPro(Rectangle bounds, const char *textLeft, const char *textRight, float *value, float minValue, float maxValue, int sliderWidth) -{ - int result = 0; - GuiState state = guiState; - - float temp = (maxValue - minValue)/2.0f; - if (value == NULL) value = &temp; - float oldValue = *value; - - Rectangle slider = { bounds.x, bounds.y + GuiGetStyle(SLIDER, BORDER_WIDTH) + GuiGetStyle(SLIDER, SLIDER_PADDING), - 0, bounds.height - 2*GuiGetStyle(SLIDER, BORDER_WIDTH) - 2*GuiGetStyle(SLIDER, SLIDER_PADDING) }; - - // Update control - //-------------------------------------------------------------------- - if ((state != STATE_DISABLED) && !guiLocked) - { - Vector2 mousePoint = GetMousePosition(); - - if (guiControlExclusiveMode) // Allows to keep dragging outside of bounds - { - if (IsMouseButtonDown(MOUSE_LEFT_BUTTON)) - { - if (CHECK_BOUNDS_ID(bounds, guiControlExclusiveRec)) - { - state = STATE_PRESSED; - // Get equivalent value and slider position from mousePosition.x - *value = (maxValue - minValue)*((mousePoint.x - bounds.x - sliderWidth/2)/(bounds.width-sliderWidth)) + minValue; - } - } - else - { - guiControlExclusiveMode = false; - guiControlExclusiveRec = RAYGUI_CLITERAL(Rectangle){ 0, 0, 0, 0 }; - } - } - else if (CheckCollisionPointRec(mousePoint, bounds)) - { - if (IsMouseButtonDown(MOUSE_LEFT_BUTTON)) - { - state = STATE_PRESSED; - guiControlExclusiveMode = true; - guiControlExclusiveRec = bounds; // Store bounds as an identifier when dragging starts - - if (!CheckCollisionPointRec(mousePoint, slider)) - { - // Get equivalent value and slider position from mousePosition.x - *value = (maxValue - minValue)*((mousePoint.x - bounds.x - sliderWidth/2)/(bounds.width-sliderWidth)) + minValue; - } - } - else state = STATE_FOCUSED; - } - - if (*value > maxValue) *value = maxValue; - else if (*value < minValue) *value = minValue; - } - - // Control value change check - if (oldValue == *value) result = 0; - else result = 1; - - // Slider bar limits check - float sliderValue = (((*value - minValue)/(maxValue - minValue))*(bounds.width - sliderWidth - 2*GuiGetStyle(SLIDER, BORDER_WIDTH))); - if (sliderWidth > 0) // Slider - { - slider.x += sliderValue; - slider.width = (float)sliderWidth; - if (slider.x <= (bounds.x + GuiGetStyle(SLIDER, BORDER_WIDTH))) slider.x = bounds.x + GuiGetStyle(SLIDER, BORDER_WIDTH); - else if ((slider.x + slider.width) >= (bounds.x + bounds.width)) slider.x = bounds.x + bounds.width - slider.width - GuiGetStyle(SLIDER, BORDER_WIDTH); - } - else if (sliderWidth == 0) // SliderBar - { - slider.x += GuiGetStyle(SLIDER, BORDER_WIDTH); - slider.width = sliderValue; - if (slider.width > bounds.width) slider.width = bounds.width - 2*GuiGetStyle(SLIDER, BORDER_WIDTH); - } - //-------------------------------------------------------------------- - - // Draw control - //-------------------------------------------------------------------- - GuiDrawRectangle(bounds, GuiGetStyle(SLIDER, BORDER_WIDTH), GetColor(GuiGetStyle(SLIDER, BORDER + (state*3))), GetColor(GuiGetStyle(SLIDER, (state != STATE_DISABLED)? BASE_COLOR_NORMAL : BASE_COLOR_DISABLED))); - - // Draw slider internal bar (depends on state) - if (state == STATE_NORMAL) GuiDrawRectangle(slider, 0, BLANK, GetColor(GuiGetStyle(SLIDER, BASE_COLOR_PRESSED))); - else if (state == STATE_FOCUSED) GuiDrawRectangle(slider, 0, BLANK, GetColor(GuiGetStyle(SLIDER, TEXT_COLOR_FOCUSED))); - else if (state == STATE_PRESSED) GuiDrawRectangle(slider, 0, BLANK, GetColor(GuiGetStyle(SLIDER, TEXT_COLOR_PRESSED))); - - // Draw left/right text if provided - if (textLeft != NULL) - { - Rectangle textBounds = { 0 }; - textBounds.width = (float)GetTextWidth(textLeft); - textBounds.height = (float)GuiGetStyle(DEFAULT, TEXT_SIZE); - textBounds.x = bounds.x - textBounds.width - GuiGetStyle(SLIDER, TEXT_PADDING); - textBounds.y = bounds.y + bounds.height/2 - GuiGetStyle(DEFAULT, TEXT_SIZE)/2; - - GuiDrawText(textLeft, textBounds, TEXT_ALIGN_RIGHT, GetColor(GuiGetStyle(SLIDER, TEXT + (state*3)))); - } - - if (textRight != NULL) - { - Rectangle textBounds = { 0 }; - textBounds.width = (float)GetTextWidth(textRight); - textBounds.height = (float)GuiGetStyle(DEFAULT, TEXT_SIZE); - textBounds.x = bounds.x + bounds.width + GuiGetStyle(SLIDER, TEXT_PADDING); - textBounds.y = bounds.y + bounds.height/2 - GuiGetStyle(DEFAULT, TEXT_SIZE)/2; - - GuiDrawText(textRight, textBounds, TEXT_ALIGN_LEFT, GetColor(GuiGetStyle(SLIDER, TEXT + (state*3)))); - } - //-------------------------------------------------------------------- - - return result; -} - -// Slider control extended, returns selected value and has text -int GuiSlider(Rectangle bounds, const char *textLeft, const char *textRight, float *value, float minValue, float maxValue) -{ - return GuiSliderPro(bounds, textLeft, textRight, value, minValue, maxValue, GuiGetStyle(SLIDER, SLIDER_WIDTH)); -} - -// Slider Bar control extended, returns selected value -int GuiSliderBar(Rectangle bounds, const char *textLeft, const char *textRight, float *value, float minValue, float maxValue) -{ - return GuiSliderPro(bounds, textLeft, textRight, value, minValue, maxValue, 0); -} - -// Progress Bar control extended, shows current progress value -int GuiProgressBar(Rectangle bounds, const char *textLeft, const char *textRight, float *value, float minValue, float maxValue) -{ - int result = 0; - GuiState state = guiState; - - float temp = (maxValue - minValue)/2.0f; - if (value == NULL) value = &temp; - - // Progress bar - Rectangle progress = { bounds.x + GuiGetStyle(PROGRESSBAR, BORDER_WIDTH), - bounds.y + GuiGetStyle(PROGRESSBAR, BORDER_WIDTH) + GuiGetStyle(PROGRESSBAR, PROGRESS_PADDING), 0, - bounds.height - 2*GuiGetStyle(PROGRESSBAR, BORDER_WIDTH) - 2*GuiGetStyle(PROGRESSBAR, PROGRESS_PADDING) }; - - // Update control - //-------------------------------------------------------------------- - if (*value > maxValue) *value = maxValue; - - // WARNING: Working with floats could lead to rounding issues - if ((state != STATE_DISABLED)) progress.width = (float)(*value/(maxValue - minValue))*bounds.width - ((*value >= maxValue)? (float)(2*GuiGetStyle(PROGRESSBAR, BORDER_WIDTH)) : 0.0f); - //-------------------------------------------------------------------- - - // Draw control - //-------------------------------------------------------------------- - if (state == STATE_DISABLED) - { - GuiDrawRectangle(bounds, GuiGetStyle(PROGRESSBAR, BORDER_WIDTH), GetColor(GuiGetStyle(PROGRESSBAR, BORDER + (state*3))), BLANK); - } - else - { - if (*value > minValue) - { - // Draw progress bar with colored border, more visual - GuiDrawRectangle(RAYGUI_CLITERAL(Rectangle){ bounds.x, bounds.y, (int)progress.width + (float)GuiGetStyle(PROGRESSBAR, BORDER_WIDTH), (float)GuiGetStyle(PROGRESSBAR, BORDER_WIDTH) }, 0, BLANK, GetColor(GuiGetStyle(PROGRESSBAR, BORDER_COLOR_FOCUSED))); - GuiDrawRectangle(RAYGUI_CLITERAL(Rectangle){ bounds.x, bounds.y + 1, (float)GuiGetStyle(PROGRESSBAR, BORDER_WIDTH), bounds.height - 2 }, 0, BLANK, GetColor(GuiGetStyle(PROGRESSBAR, BORDER_COLOR_FOCUSED))); - GuiDrawRectangle(RAYGUI_CLITERAL(Rectangle){ bounds.x, bounds.y + bounds.height - 1, (int)progress.width + (float)GuiGetStyle(PROGRESSBAR, BORDER_WIDTH), (float)GuiGetStyle(PROGRESSBAR, BORDER_WIDTH) }, 0, BLANK, GetColor(GuiGetStyle(PROGRESSBAR, BORDER_COLOR_FOCUSED))); - } - else GuiDrawRectangle(RAYGUI_CLITERAL(Rectangle){ bounds.x, bounds.y, (float)GuiGetStyle(PROGRESSBAR, BORDER_WIDTH), bounds.height }, 0, BLANK, GetColor(GuiGetStyle(PROGRESSBAR, BORDER_COLOR_NORMAL))); - - if (*value >= maxValue) GuiDrawRectangle(RAYGUI_CLITERAL(Rectangle){ bounds.x + progress.width + 1, bounds.y, (float)GuiGetStyle(PROGRESSBAR, BORDER_WIDTH), bounds.height }, 0, BLANK, GetColor(GuiGetStyle(PROGRESSBAR, BORDER_COLOR_FOCUSED))); - else - { - // Draw borders not yet reached by value - GuiDrawRectangle(RAYGUI_CLITERAL(Rectangle){ bounds.x + (int)progress.width + 1, bounds.y, bounds.width - (int)progress.width - 1, (float)GuiGetStyle(PROGRESSBAR, BORDER_WIDTH) }, 0, BLANK, GetColor(GuiGetStyle(PROGRESSBAR, BORDER_COLOR_NORMAL))); - GuiDrawRectangle(RAYGUI_CLITERAL(Rectangle){ bounds.x + (int)progress.width + 1, bounds.y + bounds.height - 1, bounds.width - (int)progress.width - 1, (float)GuiGetStyle(PROGRESSBAR, BORDER_WIDTH) }, 0, BLANK, GetColor(GuiGetStyle(PROGRESSBAR, BORDER_COLOR_NORMAL))); - GuiDrawRectangle(RAYGUI_CLITERAL(Rectangle){ bounds.x + bounds.width - 1, bounds.y + 1, (float)GuiGetStyle(PROGRESSBAR, BORDER_WIDTH), bounds.height - 2 }, 0, BLANK, GetColor(GuiGetStyle(PROGRESSBAR, BORDER_COLOR_NORMAL))); - } - - // Draw slider internal progress bar (depends on state) - GuiDrawRectangle(progress, 0, BLANK, GetColor(GuiGetStyle(PROGRESSBAR, BASE_COLOR_PRESSED))); - } - - // Draw left/right text if provided - if (textLeft != NULL) - { - Rectangle textBounds = { 0 }; - textBounds.width = (float)GetTextWidth(textLeft); - textBounds.height = (float)GuiGetStyle(DEFAULT, TEXT_SIZE); - textBounds.x = bounds.x - textBounds.width - GuiGetStyle(PROGRESSBAR, TEXT_PADDING); - textBounds.y = bounds.y + bounds.height/2 - GuiGetStyle(DEFAULT, TEXT_SIZE)/2; - - GuiDrawText(textLeft, textBounds, TEXT_ALIGN_RIGHT, GetColor(GuiGetStyle(PROGRESSBAR, TEXT + (state*3)))); - } - - if (textRight != NULL) - { - Rectangle textBounds = { 0 }; - textBounds.width = (float)GetTextWidth(textRight); - textBounds.height = (float)GuiGetStyle(DEFAULT, TEXT_SIZE); - textBounds.x = bounds.x + bounds.width + GuiGetStyle(PROGRESSBAR, TEXT_PADDING); - textBounds.y = bounds.y + bounds.height/2 - GuiGetStyle(DEFAULT, TEXT_SIZE)/2; - - GuiDrawText(textRight, textBounds, TEXT_ALIGN_LEFT, GetColor(GuiGetStyle(PROGRESSBAR, TEXT + (state*3)))); - } - //-------------------------------------------------------------------- - - return result; -} - -// Status Bar control -int GuiStatusBar(Rectangle bounds, const char *text) -{ - int result = 0; - GuiState state = guiState; - - // Draw control - //-------------------------------------------------------------------- - GuiDrawRectangle(bounds, GuiGetStyle(STATUSBAR, BORDER_WIDTH), GetColor(GuiGetStyle(STATUSBAR, BORDER + (state*3))), GetColor(GuiGetStyle(STATUSBAR, BASE + (state*3)))); - GuiDrawText(text, GetTextBounds(STATUSBAR, bounds), GuiGetStyle(STATUSBAR, TEXT_ALIGNMENT), GetColor(GuiGetStyle(STATUSBAR, TEXT + (state*3)))); - //-------------------------------------------------------------------- - - return result; -} - -// Dummy rectangle control, intended for placeholding -int GuiDummyRec(Rectangle bounds, const char *text) -{ - int result = 0; - GuiState state = guiState; - - // Update control - //-------------------------------------------------------------------- - if ((state != STATE_DISABLED) && !guiLocked && !guiControlExclusiveMode) - { - Vector2 mousePoint = GetMousePosition(); - - // Check button state - if (CheckCollisionPointRec(mousePoint, bounds)) - { - if (IsMouseButtonDown(MOUSE_LEFT_BUTTON)) state = STATE_PRESSED; - else state = STATE_FOCUSED; - } - } - //-------------------------------------------------------------------- - - // Draw control - //-------------------------------------------------------------------- - GuiDrawRectangle(bounds, 0, BLANK, GetColor(GuiGetStyle(DEFAULT, (state != STATE_DISABLED)? BASE_COLOR_NORMAL : BASE_COLOR_DISABLED))); - GuiDrawText(text, GetTextBounds(DEFAULT, bounds), TEXT_ALIGN_CENTER, GetColor(GuiGetStyle(BUTTON, (state != STATE_DISABLED)? TEXT_COLOR_NORMAL : TEXT_COLOR_DISABLED))); - //------------------------------------------------------------------ - - return result; -} - -// List View control -int GuiListView(Rectangle bounds, const char *text, int *scrollIndex, int *active) -{ - int result = 0; - int itemCount = 0; - const char **items = NULL; - - if (text != NULL) items = GuiTextSplit(text, ';', &itemCount, NULL); - - result = GuiListViewEx(bounds, items, itemCount, scrollIndex, active, NULL); - - return result; -} - -// List View control with extended parameters -int GuiListViewEx(Rectangle bounds, const char **text, int count, int *scrollIndex, int *active, int *focus) -{ - int result = 0; - GuiState state = guiState; - - int itemFocused = (focus == NULL)? -1 : *focus; - int itemSelected = (active == NULL)? -1 : *active; - - // Check if we need a scroll bar - bool useScrollBar = false; - if ((GuiGetStyle(LISTVIEW, LIST_ITEMS_HEIGHT) + GuiGetStyle(LISTVIEW, LIST_ITEMS_SPACING))*count > bounds.height) useScrollBar = true; - - // Define base item rectangle [0] - Rectangle itemBounds = { 0 }; - itemBounds.x = bounds.x + GuiGetStyle(LISTVIEW, LIST_ITEMS_SPACING); - itemBounds.y = bounds.y + GuiGetStyle(LISTVIEW, LIST_ITEMS_SPACING) + GuiGetStyle(DEFAULT, BORDER_WIDTH); - itemBounds.width = bounds.width - 2*GuiGetStyle(LISTVIEW, LIST_ITEMS_SPACING) - GuiGetStyle(DEFAULT, BORDER_WIDTH); - itemBounds.height = (float)GuiGetStyle(LISTVIEW, LIST_ITEMS_HEIGHT); - if (useScrollBar) itemBounds.width -= GuiGetStyle(LISTVIEW, SCROLLBAR_WIDTH); - - // Get items on the list - int visibleItems = (int)bounds.height/(GuiGetStyle(LISTVIEW, LIST_ITEMS_HEIGHT) + GuiGetStyle(LISTVIEW, LIST_ITEMS_SPACING)); - if (visibleItems > count) visibleItems = count; - - int startIndex = (scrollIndex == NULL)? 0 : *scrollIndex; - if ((startIndex < 0) || (startIndex > (count - visibleItems))) startIndex = 0; - int endIndex = startIndex + visibleItems; - - // Update control - //-------------------------------------------------------------------- - if ((state != STATE_DISABLED) && !guiLocked && !guiControlExclusiveMode) - { - Vector2 mousePoint = GetMousePosition(); - - // Check mouse inside list view - if (CheckCollisionPointRec(mousePoint, bounds)) - { - state = STATE_FOCUSED; - - // Check focused and selected item - for (int i = 0; i < visibleItems; i++) - { - if (CheckCollisionPointRec(mousePoint, itemBounds)) - { - itemFocused = startIndex + i; - if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) - { - if (itemSelected == (startIndex + i)) itemSelected = -1; - else itemSelected = startIndex + i; - } - break; - } - - // Update item rectangle y position for next item - itemBounds.y += (GuiGetStyle(LISTVIEW, LIST_ITEMS_HEIGHT) + GuiGetStyle(LISTVIEW, LIST_ITEMS_SPACING)); - } - - if (useScrollBar) - { - int wheelMove = (int)GetMouseWheelMove(); - startIndex -= wheelMove; - - if (startIndex < 0) startIndex = 0; - else if (startIndex > (count - visibleItems)) startIndex = count - visibleItems; - - endIndex = startIndex + visibleItems; - if (endIndex > count) endIndex = count; - } - } - else itemFocused = -1; - - // Reset item rectangle y to [0] - itemBounds.y = bounds.y + GuiGetStyle(LISTVIEW, LIST_ITEMS_SPACING) + GuiGetStyle(DEFAULT, BORDER_WIDTH); - } - //-------------------------------------------------------------------- - - // Draw control - //-------------------------------------------------------------------- - GuiDrawRectangle(bounds, GuiGetStyle(LISTVIEW, BORDER_WIDTH), GetColor(GuiGetStyle(LISTVIEW, BORDER + state*3)), GetColor(GuiGetStyle(DEFAULT, BACKGROUND_COLOR))); // Draw background - - // Draw visible items - for (int i = 0; ((i < visibleItems) && (text != NULL)); i++) - { - GuiDrawRectangle(itemBounds, GuiGetStyle(LISTVIEW, LIST_ITEMS_BORDER_WIDTH), GetColor(GuiGetStyle(LISTVIEW, BORDER_COLOR_NORMAL)), BLANK); - - if (state == STATE_DISABLED) - { - if ((startIndex + i) == itemSelected) GuiDrawRectangle(itemBounds, GuiGetStyle(LISTVIEW, BORDER_WIDTH), GetColor(GuiGetStyle(LISTVIEW, BORDER_COLOR_DISABLED)), GetColor(GuiGetStyle(LISTVIEW, BASE_COLOR_DISABLED))); - - GuiDrawText(text[startIndex + i], GetTextBounds(DEFAULT, itemBounds), GuiGetStyle(LISTVIEW, TEXT_ALIGNMENT), GetColor(GuiGetStyle(LISTVIEW, TEXT_COLOR_DISABLED))); - } - else - { - if (((startIndex + i) == itemSelected) && (active != NULL)) - { - // Draw item selected - GuiDrawRectangle(itemBounds, GuiGetStyle(LISTVIEW, BORDER_WIDTH), GetColor(GuiGetStyle(LISTVIEW, BORDER_COLOR_PRESSED)), GetColor(GuiGetStyle(LISTVIEW, BASE_COLOR_PRESSED))); - GuiDrawText(text[startIndex + i], GetTextBounds(DEFAULT, itemBounds), GuiGetStyle(LISTVIEW, TEXT_ALIGNMENT), GetColor(GuiGetStyle(LISTVIEW, TEXT_COLOR_PRESSED))); - } - else if (((startIndex + i) == itemFocused)) // && (focus != NULL)) // NOTE: We want items focused, despite not returned! - { - // Draw item focused - GuiDrawRectangle(itemBounds, GuiGetStyle(LISTVIEW, BORDER_WIDTH), GetColor(GuiGetStyle(LISTVIEW, BORDER_COLOR_FOCUSED)), GetColor(GuiGetStyle(LISTVIEW, BASE_COLOR_FOCUSED))); - GuiDrawText(text[startIndex + i], GetTextBounds(DEFAULT, itemBounds), GuiGetStyle(LISTVIEW, TEXT_ALIGNMENT), GetColor(GuiGetStyle(LISTVIEW, TEXT_COLOR_FOCUSED))); - } - else - { - // Draw item normal - GuiDrawText(text[startIndex + i], GetTextBounds(DEFAULT, itemBounds), GuiGetStyle(LISTVIEW, TEXT_ALIGNMENT), GetColor(GuiGetStyle(LISTVIEW, TEXT_COLOR_NORMAL))); - } - } - - // Update item rectangle y position for next item - itemBounds.y += (GuiGetStyle(LISTVIEW, LIST_ITEMS_HEIGHT) + GuiGetStyle(LISTVIEW, LIST_ITEMS_SPACING)); - } - - if (useScrollBar) - { - Rectangle scrollBarBounds = { - bounds.x + bounds.width - GuiGetStyle(LISTVIEW, BORDER_WIDTH) - GuiGetStyle(LISTVIEW, SCROLLBAR_WIDTH), - bounds.y + GuiGetStyle(LISTVIEW, BORDER_WIDTH), (float)GuiGetStyle(LISTVIEW, SCROLLBAR_WIDTH), - bounds.height - 2*GuiGetStyle(DEFAULT, BORDER_WIDTH) - }; - - // Calculate percentage of visible items and apply same percentage to scrollbar - float percentVisible = (float)(endIndex - startIndex)/count; - float sliderSize = bounds.height*percentVisible; - - int prevSliderSize = GuiGetStyle(SCROLLBAR, SCROLL_SLIDER_SIZE); // Save default slider size - int prevScrollSpeed = GuiGetStyle(SCROLLBAR, SCROLL_SPEED); // Save default scroll speed - GuiSetStyle(SCROLLBAR, SCROLL_SLIDER_SIZE, (int)sliderSize); // Change slider size - GuiSetStyle(SCROLLBAR, SCROLL_SPEED, count - visibleItems); // Change scroll speed - - startIndex = GuiScrollBar(scrollBarBounds, startIndex, 0, count - visibleItems); - - GuiSetStyle(SCROLLBAR, SCROLL_SPEED, prevScrollSpeed); // Reset scroll speed to default - GuiSetStyle(SCROLLBAR, SCROLL_SLIDER_SIZE, prevSliderSize); // Reset slider size to default - } - //-------------------------------------------------------------------- - - if (active != NULL) *active = itemSelected; - if (focus != NULL) *focus = itemFocused; - if (scrollIndex != NULL) *scrollIndex = startIndex; - - return result; -} - -// Color Panel control - Color (RGBA) variant. -int GuiColorPanel(Rectangle bounds, const char *text, Color *color) -{ - int result = 0; - - Vector3 vcolor = { (float)color->r/255.0f, (float)color->g/255.0f, (float)color->b/255.0f }; - Vector3 hsv = ConvertRGBtoHSV(vcolor); - Vector3 prevHsv = hsv; // workaround to see if GuiColorPanelHSV modifies the hsv. - - GuiColorPanelHSV(bounds, text, &hsv); - - // Check if the hsv was changed, only then change the color. - // This is required, because the Color->HSV->Color conversion has precision errors. - // Thus the assignment from HSV to Color should only be made, if the HSV has a new user-entered value. - // Otherwise GuiColorPanel would often modify it's color without user input. - // TODO: GuiColorPanelHSV could return 1 if the slider was dragged, to simplify this check. - if (hsv.x != prevHsv.x || hsv.y != prevHsv.y || hsv.z != prevHsv.z) - { - Vector3 rgb = ConvertHSVtoRGB(hsv); - - // NOTE: Vector3ToColor() only available on raylib 1.8.1 - *color = RAYGUI_CLITERAL(Color){ (unsigned char)(255.0f*rgb.x), - (unsigned char)(255.0f*rgb.y), - (unsigned char)(255.0f*rgb.z), - color->a }; - } - return result; -} - -// Color Bar Alpha control -// NOTE: Returns alpha value normalized [0..1] -int GuiColorBarAlpha(Rectangle bounds, const char *text, float *alpha) -{ - #if !defined(RAYGUI_COLORBARALPHA_CHECKED_SIZE) - #define RAYGUI_COLORBARALPHA_CHECKED_SIZE 10 - #endif - - int result = 0; - GuiState state = guiState; - Rectangle selector = { (float)bounds.x + (*alpha)*bounds.width - GuiGetStyle(COLORPICKER, HUEBAR_SELECTOR_HEIGHT)/2, (float)bounds.y - GuiGetStyle(COLORPICKER, HUEBAR_SELECTOR_OVERFLOW), (float)GuiGetStyle(COLORPICKER, HUEBAR_SELECTOR_HEIGHT), (float)bounds.height + GuiGetStyle(COLORPICKER, HUEBAR_SELECTOR_OVERFLOW)*2 }; - - // Update control - //-------------------------------------------------------------------- - if ((state != STATE_DISABLED) && !guiLocked) - { - Vector2 mousePoint = GetMousePosition(); - - if (guiControlExclusiveMode) // Allows to keep dragging outside of bounds - { - if (IsMouseButtonDown(MOUSE_LEFT_BUTTON)) - { - if (CHECK_BOUNDS_ID(bounds, guiControlExclusiveRec)) - { - state = STATE_PRESSED; - - *alpha = (mousePoint.x - bounds.x)/bounds.width; - if (*alpha <= 0.0f) *alpha = 0.0f; - if (*alpha >= 1.0f) *alpha = 1.0f; - } - } - else - { - guiControlExclusiveMode = false; - guiControlExclusiveRec = RAYGUI_CLITERAL(Rectangle){ 0, 0, 0, 0 }; - } - } - else if (CheckCollisionPointRec(mousePoint, bounds) || CheckCollisionPointRec(mousePoint, selector)) - { - if (IsMouseButtonDown(MOUSE_LEFT_BUTTON)) - { - state = STATE_PRESSED; - guiControlExclusiveMode = true; - guiControlExclusiveRec = bounds; // Store bounds as an identifier when dragging starts - - *alpha = (mousePoint.x - bounds.x)/bounds.width; - if (*alpha <= 0.0f) *alpha = 0.0f; - if (*alpha >= 1.0f) *alpha = 1.0f; - //selector.x = bounds.x + (int)(((alpha - 0)/(100 - 0))*(bounds.width - 2*GuiGetStyle(SLIDER, BORDER_WIDTH))) - selector.width/2; - } - else state = STATE_FOCUSED; - } - } - //-------------------------------------------------------------------- - - // Draw control - //-------------------------------------------------------------------- - - // Draw alpha bar: checked background - if (state != STATE_DISABLED) - { - int checksX = (int)bounds.width/RAYGUI_COLORBARALPHA_CHECKED_SIZE; - int checksY = (int)bounds.height/RAYGUI_COLORBARALPHA_CHECKED_SIZE; - - for (int x = 0; x < checksX; x++) - { - for (int y = 0; y < checksY; y++) - { - Rectangle check = { bounds.x + x*RAYGUI_COLORBARALPHA_CHECKED_SIZE, bounds.y + y*RAYGUI_COLORBARALPHA_CHECKED_SIZE, RAYGUI_COLORBARALPHA_CHECKED_SIZE, RAYGUI_COLORBARALPHA_CHECKED_SIZE }; - GuiDrawRectangle(check, 0, BLANK, ((x + y)%2)? Fade(GetColor(GuiGetStyle(COLORPICKER, BORDER_COLOR_DISABLED)), 0.4f) : Fade(GetColor(GuiGetStyle(COLORPICKER, BASE_COLOR_DISABLED)), 0.4f)); - } - } - - DrawRectangleGradientEx(bounds, RAYGUI_CLITERAL(Color){ 255, 255, 255, 0 }, RAYGUI_CLITERAL(Color){ 255, 255, 255, 0 }, Fade(RAYGUI_CLITERAL(Color){ 0, 0, 0, 255 }, guiAlpha), Fade(RAYGUI_CLITERAL(Color){ 0, 0, 0, 255 }, guiAlpha)); - } - else DrawRectangleGradientEx(bounds, Fade(GetColor(GuiGetStyle(COLORPICKER, BASE_COLOR_DISABLED)), 0.1f), Fade(GetColor(GuiGetStyle(COLORPICKER, BASE_COLOR_DISABLED)), 0.1f), Fade(GetColor(GuiGetStyle(COLORPICKER, BORDER_COLOR_DISABLED)), guiAlpha), Fade(GetColor(GuiGetStyle(COLORPICKER, BORDER_COLOR_DISABLED)), guiAlpha)); - - GuiDrawRectangle(bounds, GuiGetStyle(COLORPICKER, BORDER_WIDTH), GetColor(GuiGetStyle(COLORPICKER, BORDER + state*3)), BLANK); - - // Draw alpha bar: selector - GuiDrawRectangle(selector, 0, BLANK, GetColor(GuiGetStyle(COLORPICKER, BORDER + state*3))); - //-------------------------------------------------------------------- - - return result; -} - -// Color Bar Hue control -// Returns hue value normalized [0..1] -// NOTE: Other similar bars (for reference): -// Color GuiColorBarSat() [WHITE->color] -// Color GuiColorBarValue() [BLACK->color], HSV/HSL -// float GuiColorBarLuminance() [BLACK->WHITE] -int GuiColorBarHue(Rectangle bounds, const char *text, float *hue) -{ - int result = 0; - GuiState state = guiState; - Rectangle selector = { (float)bounds.x - GuiGetStyle(COLORPICKER, HUEBAR_SELECTOR_OVERFLOW), (float)bounds.y + (*hue)/360.0f*bounds.height - GuiGetStyle(COLORPICKER, HUEBAR_SELECTOR_HEIGHT)/2, (float)bounds.width + GuiGetStyle(COLORPICKER, HUEBAR_SELECTOR_OVERFLOW)*2, (float)GuiGetStyle(COLORPICKER, HUEBAR_SELECTOR_HEIGHT) }; - - // Update control - //-------------------------------------------------------------------- - if ((state != STATE_DISABLED) && !guiLocked) - { - Vector2 mousePoint = GetMousePosition(); - - if (guiControlExclusiveMode) // Allows to keep dragging outside of bounds - { - if (IsMouseButtonDown(MOUSE_LEFT_BUTTON)) - { - if (CHECK_BOUNDS_ID(bounds, guiControlExclusiveRec)) - { - state = STATE_PRESSED; - - *hue = (mousePoint.y - bounds.y)*360/bounds.height; - if (*hue <= 0.0f) *hue = 0.0f; - if (*hue >= 359.0f) *hue = 359.0f; - } - } - else - { - guiControlExclusiveMode = false; - guiControlExclusiveRec = RAYGUI_CLITERAL(Rectangle){ 0, 0, 0, 0 }; - } - } - else if (CheckCollisionPointRec(mousePoint, bounds) || CheckCollisionPointRec(mousePoint, selector)) - { - if (IsMouseButtonDown(MOUSE_LEFT_BUTTON)) - { - state = STATE_PRESSED; - guiControlExclusiveMode = true; - guiControlExclusiveRec = bounds; // Store bounds as an identifier when dragging starts - - *hue = (mousePoint.y - bounds.y)*360/bounds.height; - if (*hue <= 0.0f) *hue = 0.0f; - if (*hue >= 359.0f) *hue = 359.0f; - - } - else state = STATE_FOCUSED; - - /*if (IsKeyDown(KEY_UP)) - { - hue -= 2.0f; - if (hue <= 0.0f) hue = 0.0f; - } - else if (IsKeyDown(KEY_DOWN)) - { - hue += 2.0f; - if (hue >= 360.0f) hue = 360.0f; - }*/ - } - } - //-------------------------------------------------------------------- - - // Draw control - //-------------------------------------------------------------------- - if (state != STATE_DISABLED) - { - // Draw hue bar:color bars - // TODO: Use directly DrawRectangleGradientEx(bounds, color1, color2, color2, color1); - DrawRectangleGradientV((int)bounds.x, (int)(bounds.y), (int)bounds.width, (int)ceilf(bounds.height/6), Fade(RAYGUI_CLITERAL(Color){ 255, 0, 0, 255 }, guiAlpha), Fade(RAYGUI_CLITERAL(Color){ 255, 255, 0, 255 }, guiAlpha)); - DrawRectangleGradientV((int)bounds.x, (int)(bounds.y + bounds.height/6), (int)bounds.width, (int)ceilf(bounds.height/6), Fade(RAYGUI_CLITERAL(Color){ 255, 255, 0, 255 }, guiAlpha), Fade(RAYGUI_CLITERAL(Color){ 0, 255, 0, 255 }, guiAlpha)); - DrawRectangleGradientV((int)bounds.x, (int)(bounds.y + 2*(bounds.height/6)), (int)bounds.width, (int)ceilf(bounds.height/6), Fade(RAYGUI_CLITERAL(Color){ 0, 255, 0, 255 }, guiAlpha), Fade(RAYGUI_CLITERAL(Color){ 0, 255, 255, 255 }, guiAlpha)); - DrawRectangleGradientV((int)bounds.x, (int)(bounds.y + 3*(bounds.height/6)), (int)bounds.width, (int)ceilf(bounds.height/6), Fade(RAYGUI_CLITERAL(Color){ 0, 255, 255, 255 }, guiAlpha), Fade(RAYGUI_CLITERAL(Color){ 0, 0, 255, 255 }, guiAlpha)); - DrawRectangleGradientV((int)bounds.x, (int)(bounds.y + 4*(bounds.height/6)), (int)bounds.width, (int)ceilf(bounds.height/6), Fade(RAYGUI_CLITERAL(Color){ 0, 0, 255, 255 }, guiAlpha), Fade(RAYGUI_CLITERAL(Color){ 255, 0, 255, 255 }, guiAlpha)); - DrawRectangleGradientV((int)bounds.x, (int)(bounds.y + 5*(bounds.height/6)), (int)bounds.width, (int)(bounds.height/6), Fade(RAYGUI_CLITERAL(Color){ 255, 0, 255, 255 }, guiAlpha), Fade(RAYGUI_CLITERAL(Color){ 255, 0, 0, 255 }, guiAlpha)); - } - else DrawRectangleGradientV((int)bounds.x, (int)bounds.y, (int)bounds.width, (int)bounds.height, Fade(Fade(GetColor(GuiGetStyle(COLORPICKER, BASE_COLOR_DISABLED)), 0.1f), guiAlpha), Fade(GetColor(GuiGetStyle(COLORPICKER, BORDER_COLOR_DISABLED)), guiAlpha)); - - GuiDrawRectangle(bounds, GuiGetStyle(COLORPICKER, BORDER_WIDTH), GetColor(GuiGetStyle(COLORPICKER, BORDER + state*3)), BLANK); - - // Draw hue bar: selector - GuiDrawRectangle(selector, 0, BLANK, GetColor(GuiGetStyle(COLORPICKER, BORDER + state*3))); - //-------------------------------------------------------------------- - - return result; -} - -// Color Picker control -// NOTE: It's divided in multiple controls: -// Color GuiColorPanel(Rectangle bounds, Color color) -// float GuiColorBarAlpha(Rectangle bounds, float alpha) -// float GuiColorBarHue(Rectangle bounds, float value) -// NOTE: bounds define GuiColorPanel() size -// NOTE: this picker converts RGB to HSV, which can cause the Hue control to jump. If you have this problem, consider using the HSV variant instead -int GuiColorPicker(Rectangle bounds, const char *text, Color *color) -{ - int result = 0; - - Color temp = { 200, 0, 0, 255 }; - if (color == NULL) color = &temp; - - GuiColorPanel(bounds, NULL, color); - - Rectangle boundsHue = { (float)bounds.x + bounds.width + GuiGetStyle(COLORPICKER, HUEBAR_PADDING), (float)bounds.y, (float)GuiGetStyle(COLORPICKER, HUEBAR_WIDTH), (float)bounds.height }; - //Rectangle boundsAlpha = { bounds.x, bounds.y + bounds.height + GuiGetStyle(COLORPICKER, BARS_PADDING), bounds.width, GuiGetStyle(COLORPICKER, BARS_THICK) }; - - // NOTE: this conversion can cause low hue-resolution, if the r, g and b value are very similar, which causes the hue bar to shift around when only the GuiColorPanel is used. - Vector3 hsv = ConvertRGBtoHSV(RAYGUI_CLITERAL(Vector3){ (*color).r/255.0f, (*color).g/255.0f, (*color).b/255.0f }); - - GuiColorBarHue(boundsHue, NULL, &hsv.x); - - //color.a = (unsigned char)(GuiColorBarAlpha(boundsAlpha, (float)color.a/255.0f)*255.0f); - Vector3 rgb = ConvertHSVtoRGB(hsv); - - *color = RAYGUI_CLITERAL(Color){ (unsigned char)roundf(rgb.x*255.0f), (unsigned char)roundf(rgb.y*255.0f), (unsigned char)roundf(rgb.z*255.0f), (*color).a }; - - return result; -} - -// Color Picker control that avoids conversion to RGB and back to HSV on each call, thus avoiding jittering. -// The user can call ConvertHSVtoRGB() to convert *colorHsv value to RGB. -// NOTE: It's divided in multiple controls: -// int GuiColorPanelHSV(Rectangle bounds, const char *text, Vector3 *colorHsv) -// int GuiColorBarAlpha(Rectangle bounds, const char *text, float *alpha) -// float GuiColorBarHue(Rectangle bounds, float value) -// NOTE: bounds define GuiColorPanelHSV() size -int GuiColorPickerHSV(Rectangle bounds, const char *text, Vector3 *colorHsv) -{ - int result = 0; - - Vector3 tempHsv = { 0 }; - - if (colorHsv == NULL) - { - const Vector3 tempColor = { 200.0f/255.0f, 0.0f, 0.0f }; - tempHsv = ConvertRGBtoHSV(tempColor); - colorHsv = &tempHsv; - } - - GuiColorPanelHSV(bounds, NULL, colorHsv); - - const Rectangle boundsHue = { (float)bounds.x + bounds.width + GuiGetStyle(COLORPICKER, HUEBAR_PADDING), (float)bounds.y, (float)GuiGetStyle(COLORPICKER, HUEBAR_WIDTH), (float)bounds.height }; - - GuiColorBarHue(boundsHue, NULL, &colorHsv->x); - - return result; -} - -// Color Panel control - HSV variant -int GuiColorPanelHSV(Rectangle bounds, const char *text, Vector3 *colorHsv) -{ - int result = 0; - GuiState state = guiState; - Vector2 pickerSelector = { 0 }; - - const Color colWhite = { 255, 255, 255, 255 }; - const Color colBlack = { 0, 0, 0, 255 }; - - pickerSelector.x = bounds.x + (float)colorHsv->y*bounds.width; // HSV: Saturation - pickerSelector.y = bounds.y + (1.0f - (float)colorHsv->z)*bounds.height; // HSV: Value - - Vector3 maxHue = { colorHsv->x, 1.0f, 1.0f }; - Vector3 rgbHue = ConvertHSVtoRGB(maxHue); - Color maxHueCol = { (unsigned char)(255.0f*rgbHue.x), - (unsigned char)(255.0f*rgbHue.y), - (unsigned char)(255.0f*rgbHue.z), 255 }; - - // Update control - //-------------------------------------------------------------------- - if ((state != STATE_DISABLED) && !guiLocked) - { - Vector2 mousePoint = GetMousePosition(); - - if (guiControlExclusiveMode) // Allows to keep dragging outside of bounds - { - if (IsMouseButtonDown(MOUSE_LEFT_BUTTON)) - { - if (CHECK_BOUNDS_ID(bounds, guiControlExclusiveRec)) - { - pickerSelector = mousePoint; - - if (pickerSelector.x < bounds.x) pickerSelector.x = bounds.x; - if (pickerSelector.x > bounds.x + bounds.width) pickerSelector.x = bounds.x + bounds.width; - if (pickerSelector.y < bounds.y) pickerSelector.y = bounds.y; - if (pickerSelector.y > bounds.y + bounds.height) pickerSelector.y = bounds.y + bounds.height; - - // Calculate color from picker - Vector2 colorPick = { pickerSelector.x - bounds.x, pickerSelector.y - bounds.y }; - - colorPick.x /= (float)bounds.width; // Get normalized value on x - colorPick.y /= (float)bounds.height; // Get normalized value on y - - colorHsv->y = colorPick.x; - colorHsv->z = 1.0f - colorPick.y; - - } - } - else - { - guiControlExclusiveMode = false; - guiControlExclusiveRec = RAYGUI_CLITERAL(Rectangle){ 0, 0, 0, 0 }; - } - } - else if (CheckCollisionPointRec(mousePoint, bounds)) - { - if (IsMouseButtonDown(MOUSE_LEFT_BUTTON)) - { - state = STATE_PRESSED; - guiControlExclusiveMode = true; - guiControlExclusiveRec = bounds; - pickerSelector = mousePoint; - - // Calculate color from picker - Vector2 colorPick = { pickerSelector.x - bounds.x, pickerSelector.y - bounds.y }; - - colorPick.x /= (float)bounds.width; // Get normalized value on x - colorPick.y /= (float)bounds.height; // Get normalized value on y - - colorHsv->y = colorPick.x; - colorHsv->z = 1.0f - colorPick.y; - } - else state = STATE_FOCUSED; - } - } - //-------------------------------------------------------------------- - - // Draw control - //-------------------------------------------------------------------- - if (state != STATE_DISABLED) - { - DrawRectangleGradientEx(bounds, Fade(colWhite, guiAlpha), Fade(colWhite, guiAlpha), Fade(maxHueCol, guiAlpha), Fade(maxHueCol, guiAlpha)); - DrawRectangleGradientEx(bounds, Fade(colBlack, 0), Fade(colBlack, guiAlpha), Fade(colBlack, guiAlpha), Fade(colBlack, 0)); - - // Draw color picker: selector - Rectangle selector = { pickerSelector.x - GuiGetStyle(COLORPICKER, COLOR_SELECTOR_SIZE)/2, pickerSelector.y - GuiGetStyle(COLORPICKER, COLOR_SELECTOR_SIZE)/2, (float)GuiGetStyle(COLORPICKER, COLOR_SELECTOR_SIZE), (float)GuiGetStyle(COLORPICKER, COLOR_SELECTOR_SIZE) }; - GuiDrawRectangle(selector, 0, BLANK, colWhite); - } - else - { - DrawRectangleGradientEx(bounds, Fade(Fade(GetColor(GuiGetStyle(COLORPICKER, BASE_COLOR_DISABLED)), 0.1f), guiAlpha), Fade(Fade(colBlack, 0.6f), guiAlpha), Fade(Fade(colBlack, 0.6f), guiAlpha), Fade(Fade(GetColor(GuiGetStyle(COLORPICKER, BORDER_COLOR_DISABLED)), 0.6f), guiAlpha)); - } - - GuiDrawRectangle(bounds, GuiGetStyle(COLORPICKER, BORDER_WIDTH), GetColor(GuiGetStyle(COLORPICKER, BORDER + state*3)), BLANK); - //-------------------------------------------------------------------- - - return result; -} - -// Message Box control -int GuiMessageBox(Rectangle bounds, const char *title, const char *message, const char *buttons) -{ - #if !defined(RAYGUI_MESSAGEBOX_BUTTON_HEIGHT) - #define RAYGUI_MESSAGEBOX_BUTTON_HEIGHT 24 - #endif - #if !defined(RAYGUI_MESSAGEBOX_BUTTON_PADDING) - #define RAYGUI_MESSAGEBOX_BUTTON_PADDING 12 - #endif - - int result = -1; // Returns clicked button from buttons list, 0 refers to closed window button - - int buttonCount = 0; - const char **buttonsText = GuiTextSplit(buttons, ';', &buttonCount, NULL); - Rectangle buttonBounds = { 0 }; - buttonBounds.x = bounds.x + RAYGUI_MESSAGEBOX_BUTTON_PADDING; - buttonBounds.y = bounds.y + bounds.height - RAYGUI_MESSAGEBOX_BUTTON_HEIGHT - RAYGUI_MESSAGEBOX_BUTTON_PADDING; - buttonBounds.width = (bounds.width - RAYGUI_MESSAGEBOX_BUTTON_PADDING*(buttonCount + 1))/buttonCount; - buttonBounds.height = RAYGUI_MESSAGEBOX_BUTTON_HEIGHT; - - //int textWidth = GetTextWidth(message) + 2; - - Rectangle textBounds = { 0 }; - textBounds.x = bounds.x + RAYGUI_MESSAGEBOX_BUTTON_PADDING; - textBounds.y = bounds.y + RAYGUI_WINDOWBOX_STATUSBAR_HEIGHT + RAYGUI_MESSAGEBOX_BUTTON_PADDING; - textBounds.width = bounds.width - RAYGUI_MESSAGEBOX_BUTTON_PADDING*2; - textBounds.height = bounds.height - RAYGUI_WINDOWBOX_STATUSBAR_HEIGHT - 3*RAYGUI_MESSAGEBOX_BUTTON_PADDING - RAYGUI_MESSAGEBOX_BUTTON_HEIGHT; - - // Draw control - //-------------------------------------------------------------------- - if (GuiWindowBox(bounds, title)) result = 0; - - int prevTextAlignment = GuiGetStyle(LABEL, TEXT_ALIGNMENT); - GuiSetStyle(LABEL, TEXT_ALIGNMENT, TEXT_ALIGN_CENTER); - GuiLabel(textBounds, message); - GuiSetStyle(LABEL, TEXT_ALIGNMENT, prevTextAlignment); - - prevTextAlignment = GuiGetStyle(BUTTON, TEXT_ALIGNMENT); - GuiSetStyle(BUTTON, TEXT_ALIGNMENT, TEXT_ALIGN_CENTER); - - for (int i = 0; i < buttonCount; i++) - { - if (GuiButton(buttonBounds, buttonsText[i])) result = i + 1; - buttonBounds.x += (buttonBounds.width + RAYGUI_MESSAGEBOX_BUTTON_PADDING); - } - - GuiSetStyle(BUTTON, TEXT_ALIGNMENT, prevTextAlignment); - //-------------------------------------------------------------------- - - return result; -} - -// Text Input Box control, ask for text -int GuiTextInputBox(Rectangle bounds, const char *title, const char *message, const char *buttons, char *text, int textMaxSize, bool *secretViewActive) -{ - #if !defined(RAYGUI_TEXTINPUTBOX_BUTTON_HEIGHT) - #define RAYGUI_TEXTINPUTBOX_BUTTON_HEIGHT 24 - #endif - #if !defined(RAYGUI_TEXTINPUTBOX_BUTTON_PADDING) - #define RAYGUI_TEXTINPUTBOX_BUTTON_PADDING 12 - #endif - #if !defined(RAYGUI_TEXTINPUTBOX_HEIGHT) - #define RAYGUI_TEXTINPUTBOX_HEIGHT 26 - #endif - - // Used to enable text edit mode - // WARNING: No more than one GuiTextInputBox() should be open at the same time - static bool textEditMode = false; - - int result = -1; - - int buttonCount = 0; - const char **buttonsText = GuiTextSplit(buttons, ';', &buttonCount, NULL); - Rectangle buttonBounds = { 0 }; - buttonBounds.x = bounds.x + RAYGUI_TEXTINPUTBOX_BUTTON_PADDING; - buttonBounds.y = bounds.y + bounds.height - RAYGUI_TEXTINPUTBOX_BUTTON_HEIGHT - RAYGUI_TEXTINPUTBOX_BUTTON_PADDING; - buttonBounds.width = (bounds.width - RAYGUI_TEXTINPUTBOX_BUTTON_PADDING*(buttonCount + 1))/buttonCount; - buttonBounds.height = RAYGUI_TEXTINPUTBOX_BUTTON_HEIGHT; - - int messageInputHeight = (int)bounds.height - RAYGUI_WINDOWBOX_STATUSBAR_HEIGHT - GuiGetStyle(STATUSBAR, BORDER_WIDTH) - RAYGUI_TEXTINPUTBOX_BUTTON_HEIGHT - 2*RAYGUI_TEXTINPUTBOX_BUTTON_PADDING; - - Rectangle textBounds = { 0 }; - if (message != NULL) - { - int textSize = GetTextWidth(message) + 2; - - textBounds.x = bounds.x + bounds.width/2 - textSize/2; - textBounds.y = bounds.y + RAYGUI_WINDOWBOX_STATUSBAR_HEIGHT + messageInputHeight/4 - (float)GuiGetStyle(DEFAULT, TEXT_SIZE)/2; - textBounds.width = (float)textSize; - textBounds.height = (float)GuiGetStyle(DEFAULT, TEXT_SIZE); - } - - Rectangle textBoxBounds = { 0 }; - textBoxBounds.x = bounds.x + RAYGUI_TEXTINPUTBOX_BUTTON_PADDING; - textBoxBounds.y = bounds.y + RAYGUI_WINDOWBOX_STATUSBAR_HEIGHT - RAYGUI_TEXTINPUTBOX_HEIGHT/2; - if (message == NULL) textBoxBounds.y = bounds.y + 24 + RAYGUI_TEXTINPUTBOX_BUTTON_PADDING; - else textBoxBounds.y += (messageInputHeight/2 + messageInputHeight/4); - textBoxBounds.width = bounds.width - RAYGUI_TEXTINPUTBOX_BUTTON_PADDING*2; - textBoxBounds.height = RAYGUI_TEXTINPUTBOX_HEIGHT; - - // Draw control - //-------------------------------------------------------------------- - if (GuiWindowBox(bounds, title)) result = 0; - - // Draw message if available - if (message != NULL) - { - int prevTextAlignment = GuiGetStyle(LABEL, TEXT_ALIGNMENT); - GuiSetStyle(LABEL, TEXT_ALIGNMENT, TEXT_ALIGN_CENTER); - GuiLabel(textBounds, message); - GuiSetStyle(LABEL, TEXT_ALIGNMENT, prevTextAlignment); - } - - if (secretViewActive != NULL) - { - static char stars[] = "****************"; - if (GuiTextBox(RAYGUI_CLITERAL(Rectangle){ textBoxBounds.x, textBoxBounds.y, textBoxBounds.width - 4 - RAYGUI_TEXTINPUTBOX_HEIGHT, textBoxBounds.height }, - ((*secretViewActive == 1) || textEditMode)? text : stars, textMaxSize, textEditMode)) textEditMode = !textEditMode; - - GuiToggle(RAYGUI_CLITERAL(Rectangle){ textBoxBounds.x + textBoxBounds.width - RAYGUI_TEXTINPUTBOX_HEIGHT, textBoxBounds.y, RAYGUI_TEXTINPUTBOX_HEIGHT, RAYGUI_TEXTINPUTBOX_HEIGHT }, (*secretViewActive == 1)? "#44#" : "#45#", secretViewActive); - } - else - { - if (GuiTextBox(textBoxBounds, text, textMaxSize, textEditMode)) textEditMode = !textEditMode; - } - - int prevBtnTextAlignment = GuiGetStyle(BUTTON, TEXT_ALIGNMENT); - GuiSetStyle(BUTTON, TEXT_ALIGNMENT, TEXT_ALIGN_CENTER); - - for (int i = 0; i < buttonCount; i++) - { - if (GuiButton(buttonBounds, buttonsText[i])) result = i + 1; - buttonBounds.x += (buttonBounds.width + RAYGUI_MESSAGEBOX_BUTTON_PADDING); - } - - if (result >= 0) textEditMode = false; - - GuiSetStyle(BUTTON, TEXT_ALIGNMENT, prevBtnTextAlignment); - //-------------------------------------------------------------------- - - return result; // Result is the pressed button index -} - -// Grid control -// NOTE: Returns grid mouse-hover selected cell -// About drawing lines at subpixel spacing, simple put, not easy solution: -// https://stackoverflow.com/questions/4435450/2d-opengl-drawing-lines-that-dont-exactly-fit-pixel-raster -int GuiGrid(Rectangle bounds, const char *text, float spacing, int subdivs, Vector2 *mouseCell) -{ - // Grid lines alpha amount - #if !defined(RAYGUI_GRID_ALPHA) - #define RAYGUI_GRID_ALPHA 0.15f - #endif - - int result = 0; - GuiState state = guiState; - - Vector2 mousePoint = GetMousePosition(); - Vector2 currentMouseCell = { -1, -1 }; - - float spaceWidth = spacing/(float)subdivs; - int linesV = (int)(bounds.width/spaceWidth) + 1; - int linesH = (int)(bounds.height/spaceWidth) + 1; - - int color = GuiGetStyle(DEFAULT, LINE_COLOR); - - // Update control - //-------------------------------------------------------------------- - if ((state != STATE_DISABLED) && !guiLocked && !guiControlExclusiveMode) - { - if (CheckCollisionPointRec(mousePoint, bounds)) - { - // NOTE: Cell values must be the upper left of the cell the mouse is in - currentMouseCell.x = floorf((mousePoint.x - bounds.x)/spacing); - currentMouseCell.y = floorf((mousePoint.y - bounds.y)/spacing); - } - } - //-------------------------------------------------------------------- - - // Draw control - //-------------------------------------------------------------------- - if (state == STATE_DISABLED) color = GuiGetStyle(DEFAULT, BORDER_COLOR_DISABLED); - - if (subdivs > 0) - { - // Draw vertical grid lines - for (int i = 0; i < linesV; i++) - { - Rectangle lineV = { bounds.x + spacing*i/subdivs, bounds.y, 1, bounds.height + 1 }; - GuiDrawRectangle(lineV, 0, BLANK, ((i%subdivs) == 0)? GuiFade(GetColor(color), RAYGUI_GRID_ALPHA*4) : GuiFade(GetColor(color), RAYGUI_GRID_ALPHA)); - } - - // Draw horizontal grid lines - for (int i = 0; i < linesH; i++) - { - Rectangle lineH = { bounds.x, bounds.y + spacing*i/subdivs, bounds.width + 1, 1 }; - GuiDrawRectangle(lineH, 0, BLANK, ((i%subdivs) == 0)? GuiFade(GetColor(color), RAYGUI_GRID_ALPHA*4) : GuiFade(GetColor(color), RAYGUI_GRID_ALPHA)); - } - } - - if (mouseCell != NULL) *mouseCell = currentMouseCell; - return result; -} - -//---------------------------------------------------------------------------------- -// Tooltip management functions -// NOTE: Tooltips requires some global variables: tooltipPtr -//---------------------------------------------------------------------------------- -// Enable gui tooltips (global state) -void GuiEnableTooltip(void) { guiTooltip = true; } - -// Disable gui tooltips (global state) -void GuiDisableTooltip(void) { guiTooltip = false; } - -// Set tooltip string -void GuiSetTooltip(const char *tooltip) { guiTooltipPtr = tooltip; } - -//---------------------------------------------------------------------------------- -// Styles loading functions -//---------------------------------------------------------------------------------- - -// Load raygui style file (.rgs) -// NOTE: By default a binary file is expected, that file could contain a custom font, -// in that case, custom font image atlas is GRAY+ALPHA and pixel data can be compressed (DEFLATE) -void GuiLoadStyle(const char *fileName) -{ - #define MAX_LINE_BUFFER_SIZE 256 - - bool tryBinary = false; - if (!guiStyleLoaded) GuiLoadStyleDefault(); - - // Try reading the files as text file first - FILE *rgsFile = fopen(fileName, "rt"); - - if (rgsFile != NULL) - { - char buffer[MAX_LINE_BUFFER_SIZE] = { 0 }; - fgets(buffer, MAX_LINE_BUFFER_SIZE, rgsFile); - - if (buffer[0] == '#') - { - int controlId = 0; - int propertyId = 0; - unsigned int propertyValue = 0; - - while (!feof(rgsFile)) - { - switch (buffer[0]) - { - case 'p': - { - // Style property: p - - sscanf(buffer, "p %d %d 0x%x", &controlId, &propertyId, &propertyValue); - GuiSetStyle(controlId, propertyId, (int)propertyValue); - - } break; - case 'f': - { - // Style font: f - - int fontSize = 0; - char charmapFileName[256] = { 0 }; - char fontFileName[256] = { 0 }; - sscanf(buffer, "f %d %s %[^\r\n]s", &fontSize, charmapFileName, fontFileName); - - Font font = { 0 }; - int *codepoints = NULL; - int codepointCount = 0; - - if (charmapFileName[0] != '0') - { - // Load text data from file - // NOTE: Expected an UTF-8 array of codepoints, no separation - char *textData = LoadFileText(TextFormat("%s/%s", GetDirectoryPath(fileName), charmapFileName)); - codepoints = LoadCodepoints(textData, &codepointCount); - UnloadFileText(textData); - } - - if (fontFileName[0] != '\0') - { - // In case a font is already loaded and it is not default internal font, unload it - if (font.texture.id != GetFontDefault().texture.id) UnloadTexture(font.texture); - - if (codepointCount > 0) font = LoadFontEx(TextFormat("%s/%s", GetDirectoryPath(fileName), fontFileName), fontSize, codepoints, codepointCount); - else font = LoadFontEx(TextFormat("%s/%s", GetDirectoryPath(fileName), fontFileName), fontSize, NULL, 0); // Default to 95 standard codepoints - } - - // If font texture not properly loaded, revert to default font and size/spacing - if (font.texture.id == 0) - { - font = GetFontDefault(); - GuiSetStyle(DEFAULT, TEXT_SIZE, 10); - GuiSetStyle(DEFAULT, TEXT_SPACING, 1); - } - - UnloadCodepoints(codepoints); - - if ((font.texture.id > 0) && (font.glyphCount > 0)) GuiSetFont(font); - - } break; - default: break; - } - - fgets(buffer, MAX_LINE_BUFFER_SIZE, rgsFile); - } - } - else tryBinary = true; - - fclose(rgsFile); - } - - if (tryBinary) - { - rgsFile = fopen(fileName, "rb"); - - if (rgsFile != NULL) - { - fseek(rgsFile, 0, SEEK_END); - int fileDataSize = ftell(rgsFile); - fseek(rgsFile, 0, SEEK_SET); - - if (fileDataSize > 0) - { - unsigned char *fileData = (unsigned char *)RAYGUI_MALLOC(fileDataSize*sizeof(unsigned char)); - fread(fileData, sizeof(unsigned char), fileDataSize, rgsFile); - - GuiLoadStyleFromMemory(fileData, fileDataSize); - - RAYGUI_FREE(fileData); - } - - fclose(rgsFile); - } - } -} - -// Load style default over global style -void GuiLoadStyleDefault(void) -{ - // We set this variable first to avoid cyclic function calls - // when calling GuiSetStyle() and GuiGetStyle() - guiStyleLoaded = true; - - // Initialize default LIGHT style property values - // WARNING: Default value are applied to all controls on set but - // they can be overwritten later on for every custom control - GuiSetStyle(DEFAULT, BORDER_COLOR_NORMAL, 0x838383ff); - GuiSetStyle(DEFAULT, BASE_COLOR_NORMAL, 0xc9c9c9ff); - GuiSetStyle(DEFAULT, TEXT_COLOR_NORMAL, 0x686868ff); - GuiSetStyle(DEFAULT, BORDER_COLOR_FOCUSED, 0x5bb2d9ff); - GuiSetStyle(DEFAULT, BASE_COLOR_FOCUSED, 0xc9effeff); - GuiSetStyle(DEFAULT, TEXT_COLOR_FOCUSED, 0x6c9bbcff); - GuiSetStyle(DEFAULT, BORDER_COLOR_PRESSED, 0x0492c7ff); - GuiSetStyle(DEFAULT, BASE_COLOR_PRESSED, 0x97e8ffff); - GuiSetStyle(DEFAULT, TEXT_COLOR_PRESSED, 0x368bafff); - GuiSetStyle(DEFAULT, BORDER_COLOR_DISABLED, 0xb5c1c2ff); - GuiSetStyle(DEFAULT, BASE_COLOR_DISABLED, 0xe6e9e9ff); - GuiSetStyle(DEFAULT, TEXT_COLOR_DISABLED, 0xaeb7b8ff); - GuiSetStyle(DEFAULT, BORDER_WIDTH, 1); - GuiSetStyle(DEFAULT, TEXT_PADDING, 0); - GuiSetStyle(DEFAULT, TEXT_ALIGNMENT, TEXT_ALIGN_CENTER); - - // Initialize default extended property values - // NOTE: By default, extended property values are initialized to 0 - GuiSetStyle(DEFAULT, TEXT_SIZE, 10); // DEFAULT, shared by all controls - GuiSetStyle(DEFAULT, TEXT_SPACING, 1); // DEFAULT, shared by all controls - GuiSetStyle(DEFAULT, LINE_COLOR, 0x90abb5ff); // DEFAULT specific property - GuiSetStyle(DEFAULT, BACKGROUND_COLOR, 0xf5f5f5ff); // DEFAULT specific property - GuiSetStyle(DEFAULT, TEXT_LINE_SPACING, 15); // DEFAULT, 15 pixels between lines - GuiSetStyle(DEFAULT, TEXT_ALIGNMENT_VERTICAL, TEXT_ALIGN_MIDDLE); // DEFAULT, text aligned vertically to middle of text-bounds - - // Initialize control-specific property values - // NOTE: Those properties are in default list but require specific values by control type - GuiSetStyle(LABEL, TEXT_ALIGNMENT, TEXT_ALIGN_LEFT); - GuiSetStyle(BUTTON, BORDER_WIDTH, 2); - GuiSetStyle(SLIDER, TEXT_PADDING, 4); - GuiSetStyle(PROGRESSBAR, TEXT_PADDING, 4); - GuiSetStyle(CHECKBOX, TEXT_PADDING, 4); - GuiSetStyle(CHECKBOX, TEXT_ALIGNMENT, TEXT_ALIGN_RIGHT); - GuiSetStyle(DROPDOWNBOX, TEXT_PADDING, 0); - GuiSetStyle(DROPDOWNBOX, TEXT_ALIGNMENT, TEXT_ALIGN_CENTER); - GuiSetStyle(TEXTBOX, TEXT_PADDING, 4); - GuiSetStyle(TEXTBOX, TEXT_ALIGNMENT, TEXT_ALIGN_LEFT); - GuiSetStyle(VALUEBOX, TEXT_PADDING, 0); - GuiSetStyle(VALUEBOX, TEXT_ALIGNMENT, TEXT_ALIGN_LEFT); - GuiSetStyle(SPINNER, TEXT_PADDING, 0); - GuiSetStyle(SPINNER, TEXT_ALIGNMENT, TEXT_ALIGN_LEFT); - GuiSetStyle(STATUSBAR, TEXT_PADDING, 8); - GuiSetStyle(STATUSBAR, TEXT_ALIGNMENT, TEXT_ALIGN_LEFT); - - // Initialize extended property values - // NOTE: By default, extended property values are initialized to 0 - GuiSetStyle(TOGGLE, GROUP_PADDING, 2); - GuiSetStyle(SLIDER, SLIDER_WIDTH, 16); - GuiSetStyle(SLIDER, SLIDER_PADDING, 1); - GuiSetStyle(PROGRESSBAR, PROGRESS_PADDING, 1); - GuiSetStyle(CHECKBOX, CHECK_PADDING, 1); - GuiSetStyle(COMBOBOX, COMBO_BUTTON_WIDTH, 32); - GuiSetStyle(COMBOBOX, COMBO_BUTTON_SPACING, 2); - GuiSetStyle(DROPDOWNBOX, ARROW_PADDING, 16); - GuiSetStyle(DROPDOWNBOX, DROPDOWN_ITEMS_SPACING, 2); - GuiSetStyle(SPINNER, SPIN_BUTTON_WIDTH, 24); - GuiSetStyle(SPINNER, SPIN_BUTTON_SPACING, 2); - GuiSetStyle(SCROLLBAR, BORDER_WIDTH, 0); - GuiSetStyle(SCROLLBAR, ARROWS_VISIBLE, 0); - GuiSetStyle(SCROLLBAR, ARROWS_SIZE, 6); - GuiSetStyle(SCROLLBAR, SCROLL_SLIDER_PADDING, 0); - GuiSetStyle(SCROLLBAR, SCROLL_SLIDER_SIZE, 16); - GuiSetStyle(SCROLLBAR, SCROLL_PADDING, 0); - GuiSetStyle(SCROLLBAR, SCROLL_SPEED, 12); - GuiSetStyle(LISTVIEW, LIST_ITEMS_HEIGHT, 28); - GuiSetStyle(LISTVIEW, LIST_ITEMS_SPACING, 2); - GuiSetStyle(LISTVIEW, SCROLLBAR_WIDTH, 12); - GuiSetStyle(LISTVIEW, SCROLLBAR_SIDE, SCROLLBAR_RIGHT_SIDE); - GuiSetStyle(COLORPICKER, COLOR_SELECTOR_SIZE, 8); - GuiSetStyle(COLORPICKER, HUEBAR_WIDTH, 16); - GuiSetStyle(COLORPICKER, HUEBAR_PADDING, 8); - GuiSetStyle(COLORPICKER, HUEBAR_SELECTOR_HEIGHT, 8); - GuiSetStyle(COLORPICKER, HUEBAR_SELECTOR_OVERFLOW, 2); - - if (guiFont.texture.id != GetFontDefault().texture.id) - { - // Unload previous font texture - UnloadTexture(guiFont.texture); - RL_FREE(guiFont.recs); - RL_FREE(guiFont.glyphs); - guiFont.recs = NULL; - guiFont.glyphs = NULL; - - // Setup default raylib font - guiFont = GetFontDefault(); - - // NOTE: Default raylib font character 95 is a white square - Rectangle whiteChar = guiFont.recs[95]; - - // NOTE: We set up a 1px padding on char rectangle to avoid pixel bleeding on MSAA filtering - SetShapesTexture(guiFont.texture, RAYGUI_CLITERAL(Rectangle){ whiteChar.x + 1, whiteChar.y + 1, whiteChar.width - 2, whiteChar.height - 2 }); - } -} - -// Get text with icon id prepended -// NOTE: Useful to add icons by name id (enum) instead of -// a number that can change between ricon versions -const char *GuiIconText(int iconId, const char *text) -{ -#if defined(RAYGUI_NO_ICONS) - return NULL; -#else - static char buffer[1024] = { 0 }; - static char iconBuffer[16] = { 0 }; - - if (text != NULL) - { - memset(buffer, 0, 1024); - sprintf(buffer, "#%03i#", iconId); - - for (int i = 5; i < 1024; i++) - { - buffer[i] = text[i - 5]; - if (text[i - 5] == '\0') break; - } - - return buffer; - } - else - { - sprintf(iconBuffer, "#%03i#", iconId); - - return iconBuffer; - } -#endif -} - -#if !defined(RAYGUI_NO_ICONS) -// Get full icons data pointer -unsigned int *GuiGetIcons(void) { return guiIconsPtr; } - -// Load raygui icons file (.rgi) -// NOTE: In case nameIds are required, they can be requested with loadIconsName, -// they are returned as a guiIconsName[iconCount][RAYGUI_ICON_MAX_NAME_LENGTH], -// WARNING: guiIconsName[]][] memory should be manually freed! -char **GuiLoadIcons(const char *fileName, bool loadIconsName) -{ - // Style File Structure (.rgi) - // ------------------------------------------------------ - // Offset | Size | Type | Description - // ------------------------------------------------------ - // 0 | 4 | char | Signature: "rGI " - // 4 | 2 | short | Version: 100 - // 6 | 2 | short | reserved - - // 8 | 2 | short | Num icons (N) - // 10 | 2 | short | Icons size (Options: 16, 32, 64) (S) - - // Icons name id (32 bytes per name id) - // foreach (icon) - // { - // 12+32*i | 32 | char | Icon NameId - // } - - // Icons data: One bit per pixel, stored as unsigned int array (depends on icon size) - // S*S pixels/32bit per unsigned int = K unsigned int per icon - // foreach (icon) - // { - // ... | K | unsigned int | Icon Data - // } - - FILE *rgiFile = fopen(fileName, "rb"); - - char **guiIconsName = NULL; - - if (rgiFile != NULL) - { - char signature[5] = { 0 }; - short version = 0; - short reserved = 0; - short iconCount = 0; - short iconSize = 0; - - fread(signature, 1, 4, rgiFile); - fread(&version, sizeof(short), 1, rgiFile); - fread(&reserved, sizeof(short), 1, rgiFile); - fread(&iconCount, sizeof(short), 1, rgiFile); - fread(&iconSize, sizeof(short), 1, rgiFile); - - if ((signature[0] == 'r') && - (signature[1] == 'G') && - (signature[2] == 'I') && - (signature[3] == ' ')) - { - if (loadIconsName) - { - guiIconsName = (char **)RAYGUI_MALLOC(iconCount*sizeof(char **)); - for (int i = 0; i < iconCount; i++) - { - guiIconsName[i] = (char *)RAYGUI_MALLOC(RAYGUI_ICON_MAX_NAME_LENGTH); - fread(guiIconsName[i], 1, RAYGUI_ICON_MAX_NAME_LENGTH, rgiFile); - } - } - else fseek(rgiFile, iconCount*RAYGUI_ICON_MAX_NAME_LENGTH, SEEK_CUR); - - // Read icons data directly over internal icons array - fread(guiIconsPtr, sizeof(unsigned int), iconCount*(iconSize*iconSize/32), rgiFile); - } - - fclose(rgiFile); - } - - return guiIconsName; -} - -// Draw selected icon using rectangles pixel-by-pixel -void GuiDrawIcon(int iconId, int posX, int posY, int pixelSize, Color color) -{ - #define BIT_CHECK(a,b) ((a) & (1u<<(b))) - - for (int i = 0, y = 0; i < RAYGUI_ICON_SIZE*RAYGUI_ICON_SIZE/32; i++) - { - for (int k = 0; k < 32; k++) - { - if (BIT_CHECK(guiIconsPtr[iconId*RAYGUI_ICON_DATA_ELEMENTS + i], k)) - { - #if !defined(RAYGUI_STANDALONE) - GuiDrawRectangle(RAYGUI_CLITERAL(Rectangle){ (float)posX + (k%RAYGUI_ICON_SIZE)*pixelSize, (float)posY + y*pixelSize, (float)pixelSize, (float)pixelSize }, 0, BLANK, color); - #endif - } - - if ((k == 15) || (k == 31)) y++; - } - } -} - -// Set icon drawing size -void GuiSetIconScale(int scale) -{ - if (scale >= 1) guiIconScale = scale; -} - -#endif // !RAYGUI_NO_ICONS - -//---------------------------------------------------------------------------------- -// Module specific Functions Definition -//---------------------------------------------------------------------------------- - -// Load style from memory -// WARNING: Binary files only -static void GuiLoadStyleFromMemory(const unsigned char *fileData, int dataSize) -{ - unsigned char *fileDataPtr = (unsigned char *)fileData; - - char signature[5] = { 0 }; - short version = 0; - short reserved = 0; - int propertyCount = 0; - - memcpy(signature, fileDataPtr, 4); - memcpy(&version, fileDataPtr + 4, sizeof(short)); - memcpy(&reserved, fileDataPtr + 4 + 2, sizeof(short)); - memcpy(&propertyCount, fileDataPtr + 4 + 2 + 2, sizeof(int)); - fileDataPtr += 12; - - if ((signature[0] == 'r') && - (signature[1] == 'G') && - (signature[2] == 'S') && - (signature[3] == ' ')) - { - short controlId = 0; - short propertyId = 0; - unsigned int propertyValue = 0; - - for (int i = 0; i < propertyCount; i++) - { - memcpy(&controlId, fileDataPtr, sizeof(short)); - memcpy(&propertyId, fileDataPtr + 2, sizeof(short)); - memcpy(&propertyValue, fileDataPtr + 2 + 2, sizeof(unsigned int)); - fileDataPtr += 8; - - if (controlId == 0) // DEFAULT control - { - // If a DEFAULT property is loaded, it is propagated to all controls - // NOTE: All DEFAULT properties should be defined first in the file - GuiSetStyle(0, (int)propertyId, propertyValue); - - if (propertyId < RAYGUI_MAX_PROPS_BASE) for (int j = 1; j < RAYGUI_MAX_CONTROLS; j++) GuiSetStyle(j, (int)propertyId, propertyValue); - } - else GuiSetStyle((int)controlId, (int)propertyId, propertyValue); - } - - // Font loading is highly dependant on raylib API to load font data and image - -#if !defined(RAYGUI_STANDALONE) - // Load custom font if available - int fontDataSize = 0; - memcpy(&fontDataSize, fileDataPtr, sizeof(int)); - fileDataPtr += 4; - - if (fontDataSize > 0) - { - Font font = { 0 }; - int fontType = 0; // 0-Normal, 1-SDF - - memcpy(&font.baseSize, fileDataPtr, sizeof(int)); - memcpy(&font.glyphCount, fileDataPtr + 4, sizeof(int)); - memcpy(&fontType, fileDataPtr + 4 + 4, sizeof(int)); - fileDataPtr += 12; - - // Load font white rectangle - Rectangle fontWhiteRec = { 0 }; - memcpy(&fontWhiteRec, fileDataPtr, sizeof(Rectangle)); - fileDataPtr += 16; - - // Load font image parameters - int fontImageUncompSize = 0; - int fontImageCompSize = 0; - memcpy(&fontImageUncompSize, fileDataPtr, sizeof(int)); - memcpy(&fontImageCompSize, fileDataPtr + 4, sizeof(int)); - fileDataPtr += 8; - - Image imFont = { 0 }; - imFont.mipmaps = 1; - memcpy(&imFont.width, fileDataPtr, sizeof(int)); - memcpy(&imFont.height, fileDataPtr + 4, sizeof(int)); - memcpy(&imFont.format, fileDataPtr + 4 + 4, sizeof(int)); - fileDataPtr += 12; - - if ((fontImageCompSize > 0) && (fontImageCompSize != fontImageUncompSize)) - { - // Compressed font atlas image data (DEFLATE), it requires DecompressData() - int dataUncompSize = 0; - unsigned char *compData = (unsigned char *)RAYGUI_MALLOC(fontImageCompSize); - memcpy(compData, fileDataPtr, fontImageCompSize); - fileDataPtr += fontImageCompSize; - - imFont.data = DecompressData(compData, fontImageCompSize, &dataUncompSize); - - // Security check, dataUncompSize must match the provided fontImageUncompSize - if (dataUncompSize != fontImageUncompSize) RAYGUI_LOG("WARNING: Uncompressed font atlas image data could be corrupted"); - - RAYGUI_FREE(compData); - } - else - { - // Font atlas image data is not compressed - imFont.data = (unsigned char *)RAYGUI_MALLOC(fontImageUncompSize); - memcpy(imFont.data, fileDataPtr, fontImageUncompSize); - fileDataPtr += fontImageUncompSize; - } - - if (font.texture.id != GetFontDefault().texture.id) UnloadTexture(font.texture); - font.texture = LoadTextureFromImage(imFont); - - RAYGUI_FREE(imFont.data); - - // Validate font atlas texture was loaded correctly - if (font.texture.id != 0) - { - // Load font recs data - int recsDataSize = font.glyphCount*sizeof(Rectangle); - int recsDataCompressedSize = 0; - - // WARNING: Version 400 adds the compression size parameter - if (version >= 400) - { - // RGS files version 400 support compressed recs data - memcpy(&recsDataCompressedSize, fileDataPtr, sizeof(int)); - fileDataPtr += sizeof(int); - } - - if ((recsDataCompressedSize > 0) && (recsDataCompressedSize != recsDataSize)) - { - // Recs data is compressed, uncompress it - unsigned char *recsDataCompressed = (unsigned char *)RAYGUI_MALLOC(recsDataCompressedSize); - - memcpy(recsDataCompressed, fileDataPtr, recsDataCompressedSize); - fileDataPtr += recsDataCompressedSize; - - int recsDataUncompSize = 0; - font.recs = (Rectangle *)DecompressData(recsDataCompressed, recsDataCompressedSize, &recsDataUncompSize); - - // Security check, data uncompressed size must match the expected original data size - if (recsDataUncompSize != recsDataSize) RAYGUI_LOG("WARNING: Uncompressed font recs data could be corrupted"); - - RAYGUI_FREE(recsDataCompressed); - } - else - { - // Recs data is uncompressed - font.recs = (Rectangle *)RAYGUI_CALLOC(font.glyphCount, sizeof(Rectangle)); - for (int i = 0; i < font.glyphCount; i++) - { - memcpy(&font.recs[i], fileDataPtr, sizeof(Rectangle)); - fileDataPtr += sizeof(Rectangle); - } - } - - // Load font glyphs info data - int glyphsDataSize = font.glyphCount*16; // 16 bytes data per glyph - int glyphsDataCompressedSize = 0; - - // WARNING: Version 400 adds the compression size parameter - if (version >= 400) - { - // RGS files version 400 support compressed glyphs data - memcpy(&glyphsDataCompressedSize, fileDataPtr, sizeof(int)); - fileDataPtr += sizeof(int); - } - - // Allocate required glyphs space to fill with data - font.glyphs = (GlyphInfo *)RAYGUI_CALLOC(font.glyphCount, sizeof(GlyphInfo)); - - if ((glyphsDataCompressedSize > 0) && (glyphsDataCompressedSize != glyphsDataSize)) - { - // Glyphs data is compressed, uncompress it - unsigned char *glypsDataCompressed = (unsigned char *)RAYGUI_MALLOC(glyphsDataCompressedSize); - - memcpy(glypsDataCompressed, fileDataPtr, glyphsDataCompressedSize); - fileDataPtr += glyphsDataCompressedSize; - - int glyphsDataUncompSize = 0; - unsigned char *glyphsDataUncomp = DecompressData(glypsDataCompressed, glyphsDataCompressedSize, &glyphsDataUncompSize); - - // Security check, data uncompressed size must match the expected original data size - if (glyphsDataUncompSize != glyphsDataSize) RAYGUI_LOG("WARNING: Uncompressed font glyphs data could be corrupted"); - - unsigned char *glyphsDataUncompPtr = glyphsDataUncomp; - - for (int i = 0; i < font.glyphCount; i++) - { - memcpy(&font.glyphs[i].value, glyphsDataUncompPtr, sizeof(int)); - memcpy(&font.glyphs[i].offsetX, glyphsDataUncompPtr + 4, sizeof(int)); - memcpy(&font.glyphs[i].offsetY, glyphsDataUncompPtr + 8, sizeof(int)); - memcpy(&font.glyphs[i].advanceX, glyphsDataUncompPtr + 12, sizeof(int)); - glyphsDataUncompPtr += 16; - } - - RAYGUI_FREE(glypsDataCompressed); - RAYGUI_FREE(glyphsDataUncomp); - } - else - { - // Glyphs data is uncompressed - for (int i = 0; i < font.glyphCount; i++) - { - memcpy(&font.glyphs[i].value, fileDataPtr, sizeof(int)); - memcpy(&font.glyphs[i].offsetX, fileDataPtr + 4, sizeof(int)); - memcpy(&font.glyphs[i].offsetY, fileDataPtr + 8, sizeof(int)); - memcpy(&font.glyphs[i].advanceX, fileDataPtr + 12, sizeof(int)); - fileDataPtr += 16; - } - } - } - else font = GetFontDefault(); // Fallback in case of errors loading font atlas texture - - GuiSetFont(font); - - // Set font texture source rectangle to be used as white texture to draw shapes - // NOTE: It makes possible to draw shapes and text (full UI) in a single draw call - if ((fontWhiteRec.x > 0) && - (fontWhiteRec.y > 0) && - (fontWhiteRec.width > 0) && - (fontWhiteRec.height > 0)) SetShapesTexture(font.texture, fontWhiteRec); - } -#endif - } -} - -// Gui get text width considering icon -static int GetTextWidth(const char *text) -{ - #if !defined(ICON_TEXT_PADDING) - #define ICON_TEXT_PADDING 4 - #endif - - Vector2 textSize = { 0 }; - int textIconOffset = 0; - - if ((text != NULL) && (text[0] != '\0')) - { - if (text[0] == '#') - { - for (int i = 1; (i < 5) && (text[i] != '\0'); i++) - { - if (text[i] == '#') - { - textIconOffset = i; - break; - } - } - } - - text += textIconOffset; - - // Make sure guiFont is set, GuiGetStyle() initializes it lazynessly - float fontSize = (float)GuiGetStyle(DEFAULT, TEXT_SIZE); - - // Custom MeasureText() implementation - if ((guiFont.texture.id > 0) && (text != NULL)) - { - // Get size in bytes of text, considering end of line and line break - int size = 0; - for (int i = 0; i < MAX_LINE_BUFFER_SIZE; i++) - { - if ((text[i] != '\0') && (text[i] != '\n')) size++; - else break; - } - - float scaleFactor = fontSize/(float)guiFont.baseSize; - textSize.y = (float)guiFont.baseSize*scaleFactor; - float glyphWidth = 0.0f; - - for (int i = 0, codepointSize = 0; i < size; i += codepointSize) - { - int codepoint = GetCodepointNext(&text[i], &codepointSize); - int codepointIndex = GetGlyphIndex(guiFont, codepoint); - - if (guiFont.glyphs[codepointIndex].advanceX == 0) glyphWidth = ((float)guiFont.recs[codepointIndex].width*scaleFactor); - else glyphWidth = ((float)guiFont.glyphs[codepointIndex].advanceX*scaleFactor); - - textSize.x += (glyphWidth + (float)GuiGetStyle(DEFAULT, TEXT_SPACING)); - } - } - - if (textIconOffset > 0) textSize.x += (RAYGUI_ICON_SIZE + ICON_TEXT_PADDING); - } - - return (int)textSize.x; -} - -// Get text bounds considering control bounds -static Rectangle GetTextBounds(int control, Rectangle bounds) -{ - Rectangle textBounds = bounds; - - textBounds.x = bounds.x + GuiGetStyle(control, BORDER_WIDTH); - textBounds.y = bounds.y + GuiGetStyle(control, BORDER_WIDTH) + GuiGetStyle(control, TEXT_PADDING); - textBounds.width = bounds.width - 2*GuiGetStyle(control, BORDER_WIDTH) - 2*GuiGetStyle(control, TEXT_PADDING); - textBounds.height = bounds.height - 2*GuiGetStyle(control, BORDER_WIDTH) - 2*GuiGetStyle(control, TEXT_PADDING); // NOTE: Text is processed line per line! - - // Depending on control, TEXT_PADDING and TEXT_ALIGNMENT properties could affect the text-bounds - switch (control) - { - case COMBOBOX: - case DROPDOWNBOX: - case LISTVIEW: - // TODO: Special cases (no label): COMBOBOX, DROPDOWNBOX, LISTVIEW - case SLIDER: - case CHECKBOX: - case VALUEBOX: - case SPINNER: - // TODO: More special cases (label on side): SLIDER, CHECKBOX, VALUEBOX, SPINNER - default: - { - // TODO: WARNING: TEXT_ALIGNMENT is already considered in GuiDrawText() - if (GuiGetStyle(control, TEXT_ALIGNMENT) == TEXT_ALIGN_RIGHT) textBounds.x -= GuiGetStyle(control, TEXT_PADDING); - else textBounds.x += GuiGetStyle(control, TEXT_PADDING); - } - break; - } - - return textBounds; -} - -// Get text icon if provided and move text cursor -// NOTE: We support up to 999 values for iconId -static const char *GetTextIcon(const char *text, int *iconId) -{ -#if !defined(RAYGUI_NO_ICONS) - *iconId = -1; - if (text[0] == '#') // Maybe we have an icon! - { - char iconValue[4] = { 0 }; // Maximum length for icon value: 3 digits + '\0' - - int pos = 1; - while ((pos < 4) && (text[pos] >= '0') && (text[pos] <= '9')) - { - iconValue[pos - 1] = text[pos]; - pos++; - } - - if (text[pos] == '#') - { - *iconId = TextToInteger(iconValue); - - // Move text pointer after icon - // WARNING: If only icon provided, it could point to EOL character: '\0' - if (*iconId >= 0) text += (pos + 1); - } - } -#endif - - return text; -} - -// Get text divided into lines (by line-breaks '\n') -const char **GetTextLines(const char *text, int *count) -{ - #define RAYGUI_MAX_TEXT_LINES 128 - - static const char *lines[RAYGUI_MAX_TEXT_LINES] = { 0 }; - for (int i = 0; i < RAYGUI_MAX_TEXT_LINES; i++) lines[i] = NULL; // Init NULL pointers to substrings - - int textSize = (int)strlen(text); - - lines[0] = text; - int len = 0; - *count = 1; - //int lineSize = 0; // Stores current line size, not returned - - for (int i = 0, k = 0; (i < textSize) && (*count < RAYGUI_MAX_TEXT_LINES); i++) - { - if (text[i] == '\n') - { - //lineSize = len; - k++; - lines[k] = &text[i + 1]; // WARNING: next value is valid? - len = 0; - *count += 1; - } - else len++; - } - - //lines[*count - 1].size = len; - - return lines; -} - -// Get text width to next space for provided string -static float GetNextSpaceWidth(const char *text, int *nextSpaceIndex) -{ - float width = 0; - int codepointByteCount = 0; - int codepoint = 0; - int index = 0; - float glyphWidth = 0; - float scaleFactor = (float)GuiGetStyle(DEFAULT, TEXT_SIZE)/guiFont.baseSize; - - for (int i = 0; text[i] != '\0'; i++) - { - if (text[i] != ' ') - { - codepoint = GetCodepoint(&text[i], &codepointByteCount); - index = GetGlyphIndex(guiFont, codepoint); - glyphWidth = (guiFont.glyphs[index].advanceX == 0)? guiFont.recs[index].width*scaleFactor : guiFont.glyphs[index].advanceX*scaleFactor; - width += (glyphWidth + (float)GuiGetStyle(DEFAULT, TEXT_SPACING)); - } - else - { - *nextSpaceIndex = i; - break; - } - } - - return width; -} - -// Gui draw text using default font -static void GuiDrawText(const char *text, Rectangle textBounds, int alignment, Color tint) -{ - #define TEXT_VALIGN_PIXEL_OFFSET(h) ((int)h%2) // Vertical alignment for pixel perfect - - #if !defined(ICON_TEXT_PADDING) - #define ICON_TEXT_PADDING 4 - #endif - - if ((text == NULL) || (text[0] == '\0')) return; // Security check - - // PROCEDURE: - // - Text is processed line per line - // - For every line, horizontal alignment is defined - // - For all text, vertical alignment is defined (multiline text only) - // - For every line, wordwrap mode is checked (useful for GuitextBox(), read-only) - - // Get text lines (using '\n' as delimiter) to be processed individually - // WARNING: We can't use GuiTextSplit() function because it can be already used - // before the GuiDrawText() call and its buffer is static, it would be overriden :( - int lineCount = 0; - const char **lines = GetTextLines(text, &lineCount); - - // Text style variables - //int alignment = GuiGetStyle(DEFAULT, TEXT_ALIGNMENT); - int alignmentVertical = GuiGetStyle(DEFAULT, TEXT_ALIGNMENT_VERTICAL); - int wrapMode = GuiGetStyle(DEFAULT, TEXT_WRAP_MODE); // Wrap-mode only available in read-only mode, no for text editing - - // TODO: WARNING: This totalHeight is not valid for vertical alignment in case of word-wrap - float totalHeight = (float)(lineCount*GuiGetStyle(DEFAULT, TEXT_SIZE) + (lineCount - 1)*GuiGetStyle(DEFAULT, TEXT_SIZE)/2); - float posOffsetY = 0.0f; - - for (int i = 0; i < lineCount; i++) - { - int iconId = 0; - lines[i] = GetTextIcon(lines[i], &iconId); // Check text for icon and move cursor - - // Get text position depending on alignment and iconId - //--------------------------------------------------------------------------------- - Vector2 textBoundsPosition = { textBounds.x, textBounds.y }; - float textBoundsWidthOffset = 0.0f; - - // NOTE: We get text size after icon has been processed - // WARNING: GetTextWidth() also processes text icon to get width! -> Really needed? - int textSizeX = GetTextWidth(lines[i]); - - // If text requires an icon, add size to measure - if (iconId >= 0) - { - textSizeX += RAYGUI_ICON_SIZE*guiIconScale; - - // WARNING: If only icon provided, text could be pointing to EOF character: '\0' -#if !defined(RAYGUI_NO_ICONS) - if ((lines[i] != NULL) && (lines[i][0] != '\0')) textSizeX += ICON_TEXT_PADDING; -#endif - } - - // Check guiTextAlign global variables - switch (alignment) - { - case TEXT_ALIGN_LEFT: textBoundsPosition.x = textBounds.x; break; - case TEXT_ALIGN_CENTER: textBoundsPosition.x = textBounds.x + textBounds.width/2 - textSizeX/2; break; - case TEXT_ALIGN_RIGHT: textBoundsPosition.x = textBounds.x + textBounds.width - textSizeX; break; - default: break; - } - - if (textSizeX > textBounds.width && (lines[i] != NULL) && (lines[i][0] != '\0')) textBoundsPosition.x = textBounds.x; - - switch (alignmentVertical) - { - // Only valid in case of wordWrap = 0; - case TEXT_ALIGN_TOP: textBoundsPosition.y = textBounds.y + posOffsetY; break; - case TEXT_ALIGN_MIDDLE: textBoundsPosition.y = textBounds.y + posOffsetY + textBounds.height/2 - totalHeight/2 + TEXT_VALIGN_PIXEL_OFFSET(textBounds.height); break; - case TEXT_ALIGN_BOTTOM: textBoundsPosition.y = textBounds.y + posOffsetY + textBounds.height - totalHeight + TEXT_VALIGN_PIXEL_OFFSET(textBounds.height); break; - default: break; - } - - // NOTE: Make sure we get pixel-perfect coordinates, - // In case of decimals we got weird text positioning - textBoundsPosition.x = (float)((int)textBoundsPosition.x); - textBoundsPosition.y = (float)((int)textBoundsPosition.y); - //--------------------------------------------------------------------------------- - - // Draw text (with icon if available) - //--------------------------------------------------------------------------------- -#if !defined(RAYGUI_NO_ICONS) - if (iconId >= 0) - { - // NOTE: We consider icon height, probably different than text size - GuiDrawIcon(iconId, (int)textBoundsPosition.x, (int)(textBounds.y + textBounds.height/2 - RAYGUI_ICON_SIZE*guiIconScale/2 + TEXT_VALIGN_PIXEL_OFFSET(textBounds.height)), guiIconScale, tint); - textBoundsPosition.x += (float)(RAYGUI_ICON_SIZE*guiIconScale + ICON_TEXT_PADDING); - textBoundsWidthOffset = (float)(RAYGUI_ICON_SIZE*guiIconScale + ICON_TEXT_PADDING); - } -#endif - // Get size in bytes of text, - // considering end of line and line break - int lineSize = 0; - for (int c = 0; (lines[i][c] != '\0') && (lines[i][c] != '\n') && (lines[i][c] != '\r'); c++, lineSize++){ } - float scaleFactor = (float)GuiGetStyle(DEFAULT, TEXT_SIZE)/guiFont.baseSize; - - int lastSpaceIndex = 0; - bool tempWrapCharMode = false; - - int textOffsetY = 0; - float textOffsetX = 0.0f; - float glyphWidth = 0; - - int ellipsisWidth = GetTextWidth("..."); - bool textOverflow = false; - for (int c = 0, codepointSize = 0; c < lineSize; c += codepointSize) - { - int codepoint = GetCodepointNext(&lines[i][c], &codepointSize); - int index = GetGlyphIndex(guiFont, codepoint); - - // NOTE: Normally we exit the decoding sequence as soon as a bad byte is found (and return 0x3f) - // but we need to draw all of the bad bytes using the '?' symbol moving one byte - if (codepoint == 0x3f) codepointSize = 1; // TODO: Review not recognized codepoints size - - // Get glyph width to check if it goes out of bounds - if (guiFont.glyphs[index].advanceX == 0) glyphWidth = ((float)guiFont.recs[index].width*scaleFactor); - else glyphWidth = (float)guiFont.glyphs[index].advanceX*scaleFactor; - - // Wrap mode text measuring, to validate if - // it can be drawn or a new line is required - if (wrapMode == TEXT_WRAP_CHAR) - { - // Jump to next line if current character reach end of the box limits - if ((textOffsetX + glyphWidth) > textBounds.width - textBoundsWidthOffset) - { - textOffsetX = 0.0f; - textOffsetY += GuiGetStyle(DEFAULT, TEXT_LINE_SPACING); - - if (tempWrapCharMode) // Wrap at char level when too long words - { - wrapMode = TEXT_WRAP_WORD; - tempWrapCharMode = false; - } - } - } - else if (wrapMode == TEXT_WRAP_WORD) - { - if (codepoint == 32) lastSpaceIndex = c; - - // Get width to next space in line - int nextSpaceIndex = 0; - float nextSpaceWidth = GetNextSpaceWidth(lines[i] + c, &nextSpaceIndex); - - int nextSpaceIndex2 = 0; - float nextWordSize = GetNextSpaceWidth(lines[i] + lastSpaceIndex + 1, &nextSpaceIndex2); - - if (nextWordSize > textBounds.width - textBoundsWidthOffset) - { - // Considering the case the next word is longer than bounds - tempWrapCharMode = true; - wrapMode = TEXT_WRAP_CHAR; - } - else if ((textOffsetX + nextSpaceWidth) > textBounds.width - textBoundsWidthOffset) - { - textOffsetX = 0.0f; - textOffsetY += GuiGetStyle(DEFAULT, TEXT_LINE_SPACING); - } - } - - if (codepoint == '\n') break; // WARNING: Lines are already processed manually, no need to keep drawing after this codepoint - else - { - // TODO: There are multiple types of spaces in Unicode, - // maybe it's a good idea to add support for more: http://jkorpela.fi/chars/spaces.html - if ((codepoint != ' ') && (codepoint != '\t')) // Do not draw codepoints with no glyph - { - if (wrapMode == TEXT_WRAP_NONE) - { - // Draw only required text glyphs fitting the textBounds.width - if (textSizeX > textBounds.width) - { - if (textOffsetX <= (textBounds.width - glyphWidth - textBoundsWidthOffset - ellipsisWidth)) - { - DrawTextCodepoint(guiFont, codepoint, RAYGUI_CLITERAL(Vector2){ textBoundsPosition.x + textOffsetX, textBoundsPosition.y + textOffsetY }, (float)GuiGetStyle(DEFAULT, TEXT_SIZE), GuiFade(tint, guiAlpha)); - } - else if (!textOverflow) - { - textOverflow = true; - - for (int j = 0; j < ellipsisWidth; j += ellipsisWidth/3) - { - DrawTextCodepoint(guiFont, '.', RAYGUI_CLITERAL(Vector2){ textBoundsPosition.x + textOffsetX + j, textBoundsPosition.y + textOffsetY }, (float)GuiGetStyle(DEFAULT, TEXT_SIZE), GuiFade(tint, guiAlpha)); - } - } - } - else - { - DrawTextCodepoint(guiFont, codepoint, RAYGUI_CLITERAL(Vector2){ textBoundsPosition.x + textOffsetX, textBoundsPosition.y + textOffsetY }, (float)GuiGetStyle(DEFAULT, TEXT_SIZE), GuiFade(tint, guiAlpha)); - } - } - else if ((wrapMode == TEXT_WRAP_CHAR) || (wrapMode == TEXT_WRAP_WORD)) - { - // Draw only glyphs inside the bounds - if ((textBoundsPosition.y + textOffsetY) <= (textBounds.y + textBounds.height - GuiGetStyle(DEFAULT, TEXT_SIZE))) - { - DrawTextCodepoint(guiFont, codepoint, RAYGUI_CLITERAL(Vector2){ textBoundsPosition.x + textOffsetX, textBoundsPosition.y + textOffsetY }, (float)GuiGetStyle(DEFAULT, TEXT_SIZE), GuiFade(tint, guiAlpha)); - } - } - } - - if (guiFont.glyphs[index].advanceX == 0) textOffsetX += ((float)guiFont.recs[index].width*scaleFactor + (float)GuiGetStyle(DEFAULT, TEXT_SPACING)); - else textOffsetX += ((float)guiFont.glyphs[index].advanceX*scaleFactor + (float)GuiGetStyle(DEFAULT, TEXT_SPACING)); - } - } - - if (wrapMode == TEXT_WRAP_NONE) posOffsetY += (float)GuiGetStyle(DEFAULT, TEXT_LINE_SPACING); - else if ((wrapMode == TEXT_WRAP_CHAR) || (wrapMode == TEXT_WRAP_WORD)) posOffsetY += (textOffsetY + (float)GuiGetStyle(DEFAULT, TEXT_LINE_SPACING)); - //--------------------------------------------------------------------------------- - } - -#if defined(RAYGUI_DEBUG_TEXT_BOUNDS) - GuiDrawRectangle(textBounds, 0, WHITE, Fade(BLUE, 0.4f)); -#endif -} - -// Gui draw rectangle using default raygui plain style with borders -static void GuiDrawRectangle(Rectangle rec, int borderWidth, Color borderColor, Color color) -{ - if (color.a > 0) - { - // Draw rectangle filled with color - DrawRectangle((int)rec.x, (int)rec.y, (int)rec.width, (int)rec.height, GuiFade(color, guiAlpha)); - } - - if (borderWidth > 0) - { - // Draw rectangle border lines with color - DrawRectangle((int)rec.x, (int)rec.y, (int)rec.width, borderWidth, GuiFade(borderColor, guiAlpha)); - DrawRectangle((int)rec.x, (int)rec.y + borderWidth, borderWidth, (int)rec.height - 2*borderWidth, GuiFade(borderColor, guiAlpha)); - DrawRectangle((int)rec.x + (int)rec.width - borderWidth, (int)rec.y + borderWidth, borderWidth, (int)rec.height - 2*borderWidth, GuiFade(borderColor, guiAlpha)); - DrawRectangle((int)rec.x, (int)rec.y + (int)rec.height - borderWidth, (int)rec.width, borderWidth, GuiFade(borderColor, guiAlpha)); - } - -#if defined(RAYGUI_DEBUG_RECS_BOUNDS) - DrawRectangle((int)rec.x, (int)rec.y, (int)rec.width, (int)rec.height, Fade(RED, 0.4f)); -#endif -} - -// Draw tooltip using control bounds -static void GuiTooltip(Rectangle controlRec) -{ - if (!guiLocked && guiTooltip && (guiTooltipPtr != NULL) && !guiControlExclusiveMode) - { - Vector2 textSize = MeasureTextEx(GuiGetFont(), guiTooltipPtr, (float)GuiGetStyle(DEFAULT, TEXT_SIZE), (float)GuiGetStyle(DEFAULT, TEXT_SPACING)); - - if ((controlRec.x + textSize.x + 16) > GetScreenWidth()) controlRec.x -= (textSize.x + 16 - controlRec.width); - - GuiPanel(RAYGUI_CLITERAL(Rectangle){ controlRec.x, controlRec.y + controlRec.height + 4, textSize.x + 16, GuiGetStyle(DEFAULT, TEXT_SIZE) + 8.f }, NULL); - - int textPadding = GuiGetStyle(LABEL, TEXT_PADDING); - int textAlignment = GuiGetStyle(LABEL, TEXT_ALIGNMENT); - GuiSetStyle(LABEL, TEXT_PADDING, 0); - GuiSetStyle(LABEL, TEXT_ALIGNMENT, TEXT_ALIGN_CENTER); - GuiLabel(RAYGUI_CLITERAL(Rectangle){ controlRec.x, controlRec.y + controlRec.height + 4, textSize.x + 16, GuiGetStyle(DEFAULT, TEXT_SIZE) + 8.f }, guiTooltipPtr); - GuiSetStyle(LABEL, TEXT_ALIGNMENT, textAlignment); - GuiSetStyle(LABEL, TEXT_PADDING, textPadding); - } -} - -// Split controls text into multiple strings -// Also check for multiple columns (required by GuiToggleGroup()) -static const char **GuiTextSplit(const char *text, char delimiter, int *count, int *textRow) -{ - // NOTE: Current implementation returns a copy of the provided string with '\0' (string end delimiter) - // inserted between strings defined by "delimiter" parameter. No memory is dynamically allocated, - // all used memory is static... it has some limitations: - // 1. Maximum number of possible split strings is set by RAYGUI_TEXTSPLIT_MAX_ITEMS - // 2. Maximum size of text to split is RAYGUI_TEXTSPLIT_MAX_TEXT_SIZE - // NOTE: Those definitions could be externally provided if required - - // TODO: HACK: GuiTextSplit() - Review how textRows are returned to user - // textRow is an externally provided array of integers that stores row number for every splitted string - - #if !defined(RAYGUI_TEXTSPLIT_MAX_ITEMS) - #define RAYGUI_TEXTSPLIT_MAX_ITEMS 128 - #endif - #if !defined(RAYGUI_TEXTSPLIT_MAX_TEXT_SIZE) - #define RAYGUI_TEXTSPLIT_MAX_TEXT_SIZE 1024 - #endif - - static const char *result[RAYGUI_TEXTSPLIT_MAX_ITEMS] = { NULL }; // String pointers array (points to buffer data) - static char buffer[RAYGUI_TEXTSPLIT_MAX_TEXT_SIZE] = { 0 }; // Buffer data (text input copy with '\0' added) - memset(buffer, 0, RAYGUI_TEXTSPLIT_MAX_TEXT_SIZE); - - result[0] = buffer; - int counter = 1; - - if (textRow != NULL) textRow[0] = 0; - - // Count how many substrings we have on text and point to every one - for (int i = 0; i < RAYGUI_TEXTSPLIT_MAX_TEXT_SIZE; i++) - { - buffer[i] = text[i]; - if (buffer[i] == '\0') break; - else if ((buffer[i] == delimiter) || (buffer[i] == '\n')) - { - result[counter] = buffer + i + 1; - - if (textRow != NULL) - { - if (buffer[i] == '\n') textRow[counter] = textRow[counter - 1] + 1; - else textRow[counter] = textRow[counter - 1]; - } - - buffer[i] = '\0'; // Set an end of string at this point - - counter++; - if (counter > RAYGUI_TEXTSPLIT_MAX_ITEMS) break; - } - } - - *count = counter; - - return result; -} - -// Convert color data from RGB to HSV -// NOTE: Color data should be passed normalized -static Vector3 ConvertRGBtoHSV(Vector3 rgb) -{ - Vector3 hsv = { 0 }; - float min = 0.0f; - float max = 0.0f; - float delta = 0.0f; - - min = (rgb.x < rgb.y)? rgb.x : rgb.y; - min = (min < rgb.z)? min : rgb.z; - - max = (rgb.x > rgb.y)? rgb.x : rgb.y; - max = (max > rgb.z)? max : rgb.z; - - hsv.z = max; // Value - delta = max - min; - - if (delta < 0.00001f) - { - hsv.y = 0.0f; - hsv.x = 0.0f; // Undefined, maybe NAN? - return hsv; - } - - if (max > 0.0f) - { - // NOTE: If max is 0, this divide would cause a crash - hsv.y = (delta/max); // Saturation - } - else - { - // NOTE: If max is 0, then r = g = b = 0, s = 0, h is undefined - hsv.y = 0.0f; - hsv.x = 0.0f; // Undefined, maybe NAN? - return hsv; - } - - // NOTE: Comparing float values could not work properly - if (rgb.x >= max) hsv.x = (rgb.y - rgb.z)/delta; // Between yellow & magenta - else - { - if (rgb.y >= max) hsv.x = 2.0f + (rgb.z - rgb.x)/delta; // Between cyan & yellow - else hsv.x = 4.0f + (rgb.x - rgb.y)/delta; // Between magenta & cyan - } - - hsv.x *= 60.0f; // Convert to degrees - - if (hsv.x < 0.0f) hsv.x += 360.0f; - - return hsv; -} - -// Convert color data from HSV to RGB -// NOTE: Color data should be passed normalized -static Vector3 ConvertHSVtoRGB(Vector3 hsv) -{ - Vector3 rgb = { 0 }; - float hh = 0.0f, p = 0.0f, q = 0.0f, t = 0.0f, ff = 0.0f; - long i = 0; - - // NOTE: Comparing float values could not work properly - if (hsv.y <= 0.0f) - { - rgb.x = hsv.z; - rgb.y = hsv.z; - rgb.z = hsv.z; - return rgb; - } - - hh = hsv.x; - if (hh >= 360.0f) hh = 0.0f; - hh /= 60.0f; - - i = (long)hh; - ff = hh - i; - p = hsv.z*(1.0f - hsv.y); - q = hsv.z*(1.0f - (hsv.y*ff)); - t = hsv.z*(1.0f - (hsv.y*(1.0f - ff))); - - switch (i) - { - case 0: - { - rgb.x = hsv.z; - rgb.y = t; - rgb.z = p; - } break; - case 1: - { - rgb.x = q; - rgb.y = hsv.z; - rgb.z = p; - } break; - case 2: - { - rgb.x = p; - rgb.y = hsv.z; - rgb.z = t; - } break; - case 3: - { - rgb.x = p; - rgb.y = q; - rgb.z = hsv.z; - } break; - case 4: - { - rgb.x = t; - rgb.y = p; - rgb.z = hsv.z; - } break; - case 5: - default: - { - rgb.x = hsv.z; - rgb.y = p; - rgb.z = q; - } break; - } - - return rgb; -} - -// Scroll bar control (used by GuiScrollPanel()) -static int GuiScrollBar(Rectangle bounds, int value, int minValue, int maxValue) -{ - GuiState state = guiState; - - // Is the scrollbar horizontal or vertical? - bool isVertical = (bounds.width > bounds.height)? false : true; - - // The size (width or height depending on scrollbar type) of the spinner buttons - const int spinnerSize = GuiGetStyle(SCROLLBAR, ARROWS_VISIBLE)? - (isVertical? (int)bounds.width - 2*GuiGetStyle(SCROLLBAR, BORDER_WIDTH) : - (int)bounds.height - 2*GuiGetStyle(SCROLLBAR, BORDER_WIDTH)) : 0; - - // Arrow buttons [<] [>] [∧] [∨] - Rectangle arrowUpLeft = { 0 }; - Rectangle arrowDownRight = { 0 }; - - // Actual area of the scrollbar excluding the arrow buttons - Rectangle scrollbar = { 0 }; - - // Slider bar that moves --[///]----- - Rectangle slider = { 0 }; - - // Normalize value - if (value > maxValue) value = maxValue; - if (value < minValue) value = minValue; - - int valueRange = maxValue - minValue; - if (valueRange <= 0) valueRange = 1; - - int sliderSize = GuiGetStyle(SCROLLBAR, SCROLL_SLIDER_SIZE); - if (sliderSize < 1) sliderSize = 1; // TODO: Consider a minimum slider size - - // Calculate rectangles for all of the components - arrowUpLeft = RAYGUI_CLITERAL(Rectangle){ - (float)bounds.x + GuiGetStyle(SCROLLBAR, BORDER_WIDTH), - (float)bounds.y + GuiGetStyle(SCROLLBAR, BORDER_WIDTH), - (float)spinnerSize, (float)spinnerSize }; - - if (isVertical) - { - arrowDownRight = RAYGUI_CLITERAL(Rectangle){ (float)bounds.x + GuiGetStyle(SCROLLBAR, BORDER_WIDTH), (float)bounds.y + bounds.height - spinnerSize - GuiGetStyle(SCROLLBAR, BORDER_WIDTH), (float)spinnerSize, (float)spinnerSize }; - scrollbar = RAYGUI_CLITERAL(Rectangle){ bounds.x + GuiGetStyle(SCROLLBAR, BORDER_WIDTH) + GuiGetStyle(SCROLLBAR, SCROLL_PADDING), arrowUpLeft.y + arrowUpLeft.height, bounds.width - 2*(GuiGetStyle(SCROLLBAR, BORDER_WIDTH) + GuiGetStyle(SCROLLBAR, SCROLL_PADDING)), bounds.height - arrowUpLeft.height - arrowDownRight.height - 2*GuiGetStyle(SCROLLBAR, BORDER_WIDTH) }; - - // Make sure the slider won't get outside of the scrollbar - sliderSize = (sliderSize >= scrollbar.height)? ((int)scrollbar.height - 2) : sliderSize; - slider = RAYGUI_CLITERAL(Rectangle){ - bounds.x + GuiGetStyle(SCROLLBAR, BORDER_WIDTH) + GuiGetStyle(SCROLLBAR, SCROLL_SLIDER_PADDING), - scrollbar.y + (int)(((float)(value - minValue)/valueRange)*(scrollbar.height - sliderSize)), - bounds.width - 2*(GuiGetStyle(SCROLLBAR, BORDER_WIDTH) + GuiGetStyle(SCROLLBAR, SCROLL_SLIDER_PADDING)), - (float)sliderSize }; - } - else // horizontal - { - arrowDownRight = RAYGUI_CLITERAL(Rectangle){ (float)bounds.x + bounds.width - spinnerSize - GuiGetStyle(SCROLLBAR, BORDER_WIDTH), (float)bounds.y + GuiGetStyle(SCROLLBAR, BORDER_WIDTH), (float)spinnerSize, (float)spinnerSize }; - scrollbar = RAYGUI_CLITERAL(Rectangle){ arrowUpLeft.x + arrowUpLeft.width, bounds.y + GuiGetStyle(SCROLLBAR, BORDER_WIDTH) + GuiGetStyle(SCROLLBAR, SCROLL_PADDING), bounds.width - arrowUpLeft.width - arrowDownRight.width - 2*GuiGetStyle(SCROLLBAR, BORDER_WIDTH), bounds.height - 2*(GuiGetStyle(SCROLLBAR, BORDER_WIDTH) + GuiGetStyle(SCROLLBAR, SCROLL_PADDING)) }; - - // Make sure the slider won't get outside of the scrollbar - sliderSize = (sliderSize >= scrollbar.width)? ((int)scrollbar.width - 2) : sliderSize; - slider = RAYGUI_CLITERAL(Rectangle){ - scrollbar.x + (int)(((float)(value - minValue)/valueRange)*(scrollbar.width - sliderSize)), - bounds.y + GuiGetStyle(SCROLLBAR, BORDER_WIDTH) + GuiGetStyle(SCROLLBAR, SCROLL_SLIDER_PADDING), - (float)sliderSize, - bounds.height - 2*(GuiGetStyle(SCROLLBAR, BORDER_WIDTH) + GuiGetStyle(SCROLLBAR, SCROLL_SLIDER_PADDING)) }; - } - - // Update control - //-------------------------------------------------------------------- - if ((state != STATE_DISABLED) && !guiLocked) - { - Vector2 mousePoint = GetMousePosition(); - - if (guiControlExclusiveMode) // Allows to keep dragging outside of bounds - { - if (IsMouseButtonDown(MOUSE_LEFT_BUTTON) && - !CheckCollisionPointRec(mousePoint, arrowUpLeft) && - !CheckCollisionPointRec(mousePoint, arrowDownRight)) - { - if (CHECK_BOUNDS_ID(bounds, guiControlExclusiveRec)) - { - state = STATE_PRESSED; - - if (isVertical) value = (int)(((float)(mousePoint.y - scrollbar.y - slider.height/2)*valueRange)/(scrollbar.height - slider.height) + minValue); - else value = (int)(((float)(mousePoint.x - scrollbar.x - slider.width/2)*valueRange)/(scrollbar.width - slider.width) + minValue); - } - } - else - { - guiControlExclusiveMode = false; - guiControlExclusiveRec = RAYGUI_CLITERAL(Rectangle){ 0, 0, 0, 0 }; - } - } - else if (CheckCollisionPointRec(mousePoint, bounds)) - { - state = STATE_FOCUSED; - - // Handle mouse wheel - int wheel = (int)GetMouseWheelMove(); - if (wheel != 0) value += wheel; - - // Handle mouse button down - if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) - { - guiControlExclusiveMode = true; - guiControlExclusiveRec = bounds; // Store bounds as an identifier when dragging starts - - // Check arrows click - if (CheckCollisionPointRec(mousePoint, arrowUpLeft)) value -= valueRange/GuiGetStyle(SCROLLBAR, SCROLL_SPEED); - else if (CheckCollisionPointRec(mousePoint, arrowDownRight)) value += valueRange/GuiGetStyle(SCROLLBAR, SCROLL_SPEED); - else if (!CheckCollisionPointRec(mousePoint, slider)) - { - // If click on scrollbar position but not on slider, place slider directly on that position - if (isVertical) value = (int)(((float)(mousePoint.y - scrollbar.y - slider.height/2)*valueRange)/(scrollbar.height - slider.height) + minValue); - else value = (int)(((float)(mousePoint.x - scrollbar.x - slider.width/2)*valueRange)/(scrollbar.width - slider.width) + minValue); - } - - state = STATE_PRESSED; - } - - // Keyboard control on mouse hover scrollbar - /* - if (isVertical) - { - if (IsKeyDown(KEY_DOWN)) value += 5; - else if (IsKeyDown(KEY_UP)) value -= 5; - } - else - { - if (IsKeyDown(KEY_RIGHT)) value += 5; - else if (IsKeyDown(KEY_LEFT)) value -= 5; - } - */ - } - - // Normalize value - if (value > maxValue) value = maxValue; - if (value < minValue) value = minValue; - } - //-------------------------------------------------------------------- - - // Draw control - //-------------------------------------------------------------------- - GuiDrawRectangle(bounds, GuiGetStyle(SCROLLBAR, BORDER_WIDTH), GetColor(GuiGetStyle(LISTVIEW, BORDER + state*3)), GetColor(GuiGetStyle(DEFAULT, BORDER_COLOR_DISABLED))); // Draw the background - - GuiDrawRectangle(scrollbar, 0, BLANK, GetColor(GuiGetStyle(BUTTON, BASE_COLOR_NORMAL))); // Draw the scrollbar active area background - GuiDrawRectangle(slider, 0, BLANK, GetColor(GuiGetStyle(SLIDER, BORDER + state*3))); // Draw the slider bar - - // Draw arrows (using icon if available) - if (GuiGetStyle(SCROLLBAR, ARROWS_VISIBLE)) - { -#if defined(RAYGUI_NO_ICONS) - GuiDrawText(isVertical? "^" : "<", - RAYGUI_CLITERAL(Rectangle){ arrowUpLeft.x, arrowUpLeft.y, isVertical? bounds.width : bounds.height, isVertical? bounds.width : bounds.height }, - TEXT_ALIGN_CENTER, GetColor(GuiGetStyle(DROPDOWNBOX, TEXT + (state*3)))); - GuiDrawText(isVertical? "v" : ">", - RAYGUI_CLITERAL(Rectangle){ arrowDownRight.x, arrowDownRight.y, isVertical? bounds.width : bounds.height, isVertical? bounds.width : bounds.height }, - TEXT_ALIGN_CENTER, GetColor(GuiGetStyle(DROPDOWNBOX, TEXT + (state*3)))); -#else - GuiDrawText(isVertical? "#121#" : "#118#", - RAYGUI_CLITERAL(Rectangle){ arrowUpLeft.x, arrowUpLeft.y, isVertical? bounds.width : bounds.height, isVertical? bounds.width : bounds.height }, - TEXT_ALIGN_CENTER, GetColor(GuiGetStyle(SCROLLBAR, TEXT + state*3))); // ICON_ARROW_UP_FILL / ICON_ARROW_LEFT_FILL - GuiDrawText(isVertical? "#120#" : "#119#", - RAYGUI_CLITERAL(Rectangle){ arrowDownRight.x, arrowDownRight.y, isVertical? bounds.width : bounds.height, isVertical? bounds.width : bounds.height }, - TEXT_ALIGN_CENTER, GetColor(GuiGetStyle(SCROLLBAR, TEXT + state*3))); // ICON_ARROW_DOWN_FILL / ICON_ARROW_RIGHT_FILL -#endif - } - //-------------------------------------------------------------------- - - return value; -} - -// Color fade-in or fade-out, alpha goes from 0.0f to 1.0f -// WARNING: It multiplies current alpha by alpha scale factor -static Color GuiFade(Color color, float alpha) -{ - if (alpha < 0.0f) alpha = 0.0f; - else if (alpha > 1.0f) alpha = 1.0f; - - Color result = { color.r, color.g, color.b, (unsigned char)(color.a*alpha) }; - - return result; -} - -#if defined(RAYGUI_STANDALONE) -// Returns a Color struct from hexadecimal value -static Color GetColor(int hexValue) -{ - Color color; - - color.r = (unsigned char)(hexValue >> 24) & 0xFF; - color.g = (unsigned char)(hexValue >> 16) & 0xFF; - color.b = (unsigned char)(hexValue >> 8) & 0xFF; - color.a = (unsigned char)hexValue & 0xFF; - - return color; -} - -// Returns hexadecimal value for a Color -static int ColorToInt(Color color) -{ - return (((int)color.r << 24) | ((int)color.g << 16) | ((int)color.b << 8) | (int)color.a); -} - -// Check if point is inside rectangle -static bool CheckCollisionPointRec(Vector2 point, Rectangle rec) -{ - bool collision = false; - - if ((point.x >= rec.x) && (point.x <= (rec.x + rec.width)) && - (point.y >= rec.y) && (point.y <= (rec.y + rec.height))) collision = true; - - return collision; -} - -// Formatting of text with variables to 'embed' -static const char *TextFormat(const char *text, ...) -{ - #if !defined(RAYGUI_TEXTFORMAT_MAX_SIZE) - #define RAYGUI_TEXTFORMAT_MAX_SIZE 256 - #endif - - static char buffer[RAYGUI_TEXTFORMAT_MAX_SIZE]; - - va_list args; - va_start(args, text); - vsprintf(buffer, text, args); - va_end(args); - - return buffer; -} - -// Draw rectangle with vertical gradient fill color -// NOTE: This function is only used by GuiColorPicker() -static void DrawRectangleGradientV(int posX, int posY, int width, int height, Color color1, Color color2) -{ - Rectangle bounds = { (float)posX, (float)posY, (float)width, (float)height }; - DrawRectangleGradientEx(bounds, color1, color2, color2, color1); -} - -// Split string into multiple strings -const char **TextSplit(const char *text, char delimiter, int *count) -{ - // NOTE: Current implementation returns a copy of the provided string with '\0' (string end delimiter) - // inserted between strings defined by "delimiter" parameter. No memory is dynamically allocated, - // all used memory is static... it has some limitations: - // 1. Maximum number of possible split strings is set by RAYGUI_TEXTSPLIT_MAX_ITEMS - // 2. Maximum size of text to split is RAYGUI_TEXTSPLIT_MAX_TEXT_SIZE - - #if !defined(RAYGUI_TEXTSPLIT_MAX_ITEMS) - #define RAYGUI_TEXTSPLIT_MAX_ITEMS 128 - #endif - #if !defined(RAYGUI_TEXTSPLIT_MAX_TEXT_SIZE) - #define RAYGUI_TEXTSPLIT_MAX_TEXT_SIZE 1024 - #endif - - static const char *result[RAYGUI_TEXTSPLIT_MAX_ITEMS] = { NULL }; - static char buffer[RAYGUI_TEXTSPLIT_MAX_TEXT_SIZE] = { 0 }; - memset(buffer, 0, RAYGUI_TEXTSPLIT_MAX_TEXT_SIZE); - - result[0] = buffer; - int counter = 0; - - if (text != NULL) - { - counter = 1; - - // Count how many substrings we have on text and point to every one - for (int i = 0; i < RAYGUI_TEXTSPLIT_MAX_TEXT_SIZE; i++) - { - buffer[i] = text[i]; - if (buffer[i] == '\0') break; - else if (buffer[i] == delimiter) - { - buffer[i] = '\0'; // Set an end of string at this point - result[counter] = buffer + i + 1; - counter++; - - if (counter == RAYGUI_TEXTSPLIT_MAX_ITEMS) break; - } - } - } - - *count = counter; - return result; -} - -// Get integer value from text -// NOTE: This function replaces atoi() [stdlib.h] -static int TextToInteger(const char *text) -{ - int value = 0; - int sign = 1; - - if ((text[0] == '+') || (text[0] == '-')) - { - if (text[0] == '-') sign = -1; - text++; - } - - for (int i = 0; ((text[i] >= '0') && (text[i] <= '9')); ++i) value = value*10 + (int)(text[i] - '0'); - - return value*sign; -} - -// Get float value from text -// NOTE: This function replaces atof() [stdlib.h] -// WARNING: Only '.' character is understood as decimal point -static float TextToFloat(const char *text) -{ - float value = 0.0f; - float sign = 1.0f; - - if ((text[0] == '+') || (text[0] == '-')) - { - if (text[0] == '-') sign = -1.0f; - text++; - } - - int i = 0; - for (; ((text[i] >= '0') && (text[i] <= '9')); i++) value = value*10.0f + (float)(text[i] - '0'); - - if (text[i++] != '.') value *= sign; - else - { - float divisor = 10.0f; - for (; ((text[i] >= '0') && (text[i] <= '9')); i++) - { - value += ((float)(text[i] - '0'))/divisor; - divisor = divisor*10.0f; - } - } - - return value; -} - -// Encode codepoint into UTF-8 text (char array size returned as parameter) -static const char *CodepointToUTF8(int codepoint, int *byteSize) -{ - static char utf8[6] = { 0 }; - int size = 0; - - if (codepoint <= 0x7f) - { - utf8[0] = (char)codepoint; - size = 1; - } - else if (codepoint <= 0x7ff) - { - utf8[0] = (char)(((codepoint >> 6) & 0x1f) | 0xc0); - utf8[1] = (char)((codepoint & 0x3f) | 0x80); - size = 2; - } - else if (codepoint <= 0xffff) - { - utf8[0] = (char)(((codepoint >> 12) & 0x0f) | 0xe0); - utf8[1] = (char)(((codepoint >> 6) & 0x3f) | 0x80); - utf8[2] = (char)((codepoint & 0x3f) | 0x80); - size = 3; - } - else if (codepoint <= 0x10ffff) - { - utf8[0] = (char)(((codepoint >> 18) & 0x07) | 0xf0); - utf8[1] = (char)(((codepoint >> 12) & 0x3f) | 0x80); - utf8[2] = (char)(((codepoint >> 6) & 0x3f) | 0x80); - utf8[3] = (char)((codepoint & 0x3f) | 0x80); - size = 4; - } - - *byteSize = size; - - return utf8; -} - -// Get next codepoint in a UTF-8 encoded text, scanning until '\0' is found -// When a invalid UTF-8 byte is encountered we exit as soon as possible and a '?'(0x3f) codepoint is returned -// Total number of bytes processed are returned as a parameter -// NOTE: the standard says U+FFFD should be returned in case of errors -// but that character is not supported by the default font in raylib -static int GetCodepointNext(const char *text, int *codepointSize) -{ - const char *ptr = text; - int codepoint = 0x3f; // Codepoint (defaults to '?') - *codepointSize = 1; - - // Get current codepoint and bytes processed - if (0xf0 == (0xf8 & ptr[0])) - { - // 4 byte UTF-8 codepoint - if (((ptr[1] & 0xC0) ^ 0x80) || ((ptr[2] & 0xC0) ^ 0x80) || ((ptr[3] & 0xC0) ^ 0x80)) { return codepoint; } //10xxxxxx checks - codepoint = ((0x07 & ptr[0]) << 18) | ((0x3f & ptr[1]) << 12) | ((0x3f & ptr[2]) << 6) | (0x3f & ptr[3]); - *codepointSize = 4; - } - else if (0xe0 == (0xf0 & ptr[0])) - { - // 3 byte UTF-8 codepoint */ - if (((ptr[1] & 0xC0) ^ 0x80) || ((ptr[2] & 0xC0) ^ 0x80)) { return codepoint; } //10xxxxxx checks - codepoint = ((0x0f & ptr[0]) << 12) | ((0x3f & ptr[1]) << 6) | (0x3f & ptr[2]); - *codepointSize = 3; - } - else if (0xc0 == (0xe0 & ptr[0])) - { - // 2 byte UTF-8 codepoint - if ((ptr[1] & 0xC0) ^ 0x80) { return codepoint; } //10xxxxxx checks - codepoint = ((0x1f & ptr[0]) << 6) | (0x3f & ptr[1]); - *codepointSize = 2; - } - else if (0x00 == (0x80 & ptr[0])) - { - // 1 byte UTF-8 codepoint - codepoint = ptr[0]; - *codepointSize = 1; - } - - return codepoint; -} -#endif // RAYGUI_STANDALONE - -#endif // RAYGUI_IMPLEMENTATION diff --git a/third_party/raylib/include/raylib.h b/third_party/raylib/include/raylib.h deleted file mode 100644 index ea973ff1ba..0000000000 --- a/third_party/raylib/include/raylib.h +++ /dev/null @@ -1,1766 +0,0 @@ -/********************************************************************************************** -* -* raylib v5.6-dev - A simple and easy-to-use library to enjoy videogames programming (www.raylib.com) -* -* FEATURES: -* - NO external dependencies, all required libraries included with raylib -* - Multiplatform: Windows, Linux, FreeBSD, OpenBSD, NetBSD, DragonFly, -* MacOS, Haiku, Android, Raspberry Pi, DRM native, HTML5. -* - Written in plain C code (C99) in PascalCase/camelCase notation -* - Hardware accelerated with OpenGL (1.1, 2.1, 3.3, 4.3, ES2, ES3 - choose at compile) -* - Unique OpenGL abstraction layer (usable as standalone module): [rlgl] -* - Multiple Fonts formats supported (TTF, OTF, FNT, BDF, Sprite fonts) -* - Outstanding texture formats support, including compressed formats (DXT, ETC, ASTC) -* - Full 3d support for 3d Shapes, Models, Billboards, Heightmaps and more! -* - Flexible Materials system, supporting classic maps and PBR maps -* - Animated 3D models supported (skeletal bones animation) (IQM, M3D, GLTF) -* - Shaders support, including Model shaders and Postprocessing shaders -* - Powerful math module for Vector, Matrix and Quaternion operations: [raymath] -* - Audio loading and playing with streaming support (WAV, OGG, MP3, FLAC, QOA, XM, MOD) -* - VR stereo rendering with configurable HMD device parameters -* - Bindings to multiple programming languages available! -* -* NOTES: -* - One default Font is loaded on InitWindow()->LoadFontDefault() [core, text] -* - One default Texture2D is loaded on rlglInit(), 1x1 white pixel R8G8B8A8 [rlgl] (OpenGL 3.3 or ES2) -* - One default Shader is loaded on rlglInit()->rlLoadShaderDefault() [rlgl] (OpenGL 3.3 or ES2) -* - One default RenderBatch is loaded on rlglInit()->rlLoadRenderBatch() [rlgl] (OpenGL 3.3 or ES2) -* -* DEPENDENCIES (included): -* [rcore][GLFW] rglfw (Camilla Löwy - github.com/glfw/glfw) for window/context management and input -* [rcore][RGFW] rgfw (ColleagueRiley - github.com/ColleagueRiley/RGFW) for window/context management and input -* [rlgl] glad/glad_gles2 (David Herberth - github.com/Dav1dde/glad) for OpenGL 3.3 extensions loading -* [raudio] miniaudio (David Reid - github.com/mackron/miniaudio) for audio device/context management -* -* OPTIONAL DEPENDENCIES (included): -* [rcore] msf_gif (Miles Fogle) for GIF recording -* [rcore] sinfl (Micha Mettke) for DEFLATE decompression algorithm -* [rcore] sdefl (Micha Mettke) for DEFLATE compression algorithm -* [rcore] rprand (Ramon Snatamaria) for pseudo-random numbers generation -* [rtextures] qoi (Dominic Szablewski - https://phoboslab.org) for QOI image manage -* [rtextures] stb_image (Sean Barret) for images loading (BMP, TGA, PNG, JPEG, HDR...) -* [rtextures] stb_image_write (Sean Barret) for image writing (BMP, TGA, PNG, JPG) -* [rtextures] stb_image_resize2 (Sean Barret) for image resizing algorithms -* [rtextures] stb_perlin (Sean Barret) for Perlin Noise image generation -* [rtext] stb_truetype (Sean Barret) for ttf fonts loading -* [rtext] stb_rect_pack (Sean Barret) for rectangles packing -* [rmodels] par_shapes (Philip Rideout) for parametric 3d shapes generation -* [rmodels] tinyobj_loader_c (Syoyo Fujita) for models loading (OBJ, MTL) -* [rmodels] cgltf (Johannes Kuhlmann) for models loading (glTF) -* [rmodels] m3d (bzt) for models loading (M3D, https://bztsrc.gitlab.io/model3d) -* [rmodels] vox_loader (Johann Nadalutti) for models loading (VOX) -* [raudio] dr_wav (David Reid) for WAV audio file loading -* [raudio] dr_flac (David Reid) for FLAC audio file loading -* [raudio] dr_mp3 (David Reid) for MP3 audio file loading -* [raudio] stb_vorbis (Sean Barret) for OGG audio loading -* [raudio] jar_xm (Joshua Reisenauer) for XM audio module loading -* [raudio] jar_mod (Joshua Reisenauer) for MOD audio module loading -* [raudio] qoa (Dominic Szablewski - https://phoboslab.org) for QOA audio manage -* -* -* LICENSE: zlib/libpng -* -* raylib is licensed under an unmodified zlib/libpng license, which is an OSI-certified, -* BSD-like license that allows static linking with closed source software: -* -* Copyright (c) 2013-2024 Ramon Santamaria (@raysan5) -* -* This software is provided "as-is", without any express or implied warranty. In no event -* will the authors be held liable for any damages arising from the use of this software. -* -* Permission is granted to anyone to use this software for any purpose, including commercial -* applications, and to alter it and redistribute it freely, subject to the following restrictions: -* -* 1. The origin of this software must not be misrepresented; you must not claim that you -* wrote the original software. If you use this software in a product, an acknowledgment -* in the product documentation would be appreciated but is not required. -* -* 2. Altered source versions must be plainly marked as such, and must not be misrepresented -* as being the original software. -* -* 3. This notice may not be removed or altered from any source distribution. -* -**********************************************************************************************/ - -#ifndef RAYLIB_H -#define RAYLIB_H - -#include // Required for: va_list - Only used by TraceLogCallback - -#define RAYLIB_VERSION_MAJOR 5 -#define RAYLIB_VERSION_MINOR 6 -#define RAYLIB_VERSION_PATCH 0 -#define RAYLIB_VERSION "5.6-dev" - -// Function specifiers in case library is build/used as a shared library -// NOTE: Microsoft specifiers to tell compiler that symbols are imported/exported from a .dll -// NOTE: visibility("default") attribute makes symbols "visible" when compiled with -fvisibility=hidden -#if defined(_WIN32) - #if defined(__TINYC__) - #define __declspec(x) __attribute__((x)) - #endif - #if defined(BUILD_LIBTYPE_SHARED) - #define RLAPI __declspec(dllexport) // We are building the library as a Win32 shared library (.dll) - #elif defined(USE_LIBTYPE_SHARED) - #define RLAPI __declspec(dllimport) // We are using the library as a Win32 shared library (.dll) - #endif -#else - #if defined(BUILD_LIBTYPE_SHARED) - #define RLAPI __attribute__((visibility("default"))) // We are building as a Unix shared library (.so/.dylib) - #endif -#endif - -#ifndef RLAPI - #define RLAPI // Functions defined as 'extern' by default (implicit specifiers) -#endif - -//---------------------------------------------------------------------------------- -// Some basic Defines -//---------------------------------------------------------------------------------- -#ifndef PI - #define PI 3.14159265358979323846f -#endif -#ifndef DEG2RAD - #define DEG2RAD (PI/180.0f) -#endif -#ifndef RAD2DEG - #define RAD2DEG (180.0f/PI) -#endif - -// Allow custom memory allocators -// NOTE: Require recompiling raylib sources -#ifndef RL_MALLOC - #define RL_MALLOC(sz) malloc(sz) -#endif -#ifndef RL_CALLOC - #define RL_CALLOC(n,sz) calloc(n,sz) -#endif -#ifndef RL_REALLOC - #define RL_REALLOC(ptr,sz) realloc(ptr,sz) -#endif -#ifndef RL_FREE - #define RL_FREE(ptr) free(ptr) -#endif - -// NOTE: MSVC C++ compiler does not support compound literals (C99 feature) -// Plain structures in C++ (without constructors) can be initialized with { } -// This is called aggregate initialization (C++11 feature) -#if defined(__cplusplus) - #define CLITERAL(type) type -#else - #define CLITERAL(type) (type) -#endif - -// Some compilers (mostly macos clang) default to C++98, -// where aggregate initialization can't be used -// So, give a more clear error stating how to fix this -#if !defined(_MSC_VER) && (defined(__cplusplus) && __cplusplus < 201103L) - #error "C++11 or later is required. Add -std=c++11" -#endif - -// NOTE: We set some defines with some data types declared by raylib -// Other modules (raymath, rlgl) also require some of those types, so, -// to be able to use those other modules as standalone (not depending on raylib) -// this defines are very useful for internal check and avoid type (re)definitions -#define RL_COLOR_TYPE -#define RL_RECTANGLE_TYPE -#define RL_VECTOR2_TYPE -#define RL_VECTOR3_TYPE -#define RL_VECTOR4_TYPE -#define RL_QUATERNION_TYPE -#define RL_MATRIX_TYPE - -// Some Basic Colors -// NOTE: Custom raylib color palette for amazing visuals on WHITE background -#define _rl_LIGHTGRAY CLITERAL(Color){ 200, 200, 200, 255 } // Light Gray -#define _rl_GRAY CLITERAL(Color){ 130, 130, 130, 255 } // Gray -#define _rl_DARKGRAY CLITERAL(Color){ 80, 80, 80, 255 } // Dark Gray -#define _rl_YELLOW CLITERAL(Color){ 253, 249, 0, 255 } // Yellow -#define _rl_GOLD CLITERAL(Color){ 255, 203, 0, 255 } // Gold -#define _rl_ORANGE CLITERAL(Color){ 255, 161, 0, 255 } // Orange -#define _rl_PINK CLITERAL(Color){ 255, 109, 194, 255 } // Pink -#define _rl_RED CLITERAL(Color){ 230, 41, 55, 255 } // Red -#define _rl_MAROON CLITERAL(Color){ 190, 33, 55, 255 } // Maroon -#define _rl_GREEN CLITERAL(Color){ 0, 228, 48, 255 } // Green -#define _rl_LIME CLITERAL(Color){ 0, 158, 47, 255 } // Lime -#define _rl_DARKGREEN CLITERAL(Color){ 0, 117, 44, 255 } // Dark Green -#define _rl_SKYBLUE CLITERAL(Color){ 102, 191, 255, 255 } // Sky Blue -#define _rl_BLUE CLITERAL(Color){ 0, 121, 241, 255 } // Blue -#define _rl_DARKBLUE CLITERAL(Color){ 0, 82, 172, 255 } // Dark Blue -#define _rl_PURPLE CLITERAL(Color){ 200, 122, 255, 255 } // Purple -#define _rl_VIOLET CLITERAL(Color){ 135, 60, 190, 255 } // Violet -#define _rl_DARKPURPLE CLITERAL(Color){ 112, 31, 126, 255 } // Dark Purple -#define _rl_BEIGE CLITERAL(Color){ 211, 176, 131, 255 } // Beige -#define _rl_BROWN CLITERAL(Color){ 127, 106, 79, 255 } // Brown -#define _rl_DARKBROWN CLITERAL(Color){ 76, 63, 47, 255 } // Dark Brown - -#define _rl_WHITE CLITERAL(Color){ 255, 255, 255, 255 } // White -#define _rl_BLACK CLITERAL(Color){ 0, 0, 0, 255 } // Black -#define _rl_BLANK CLITERAL(Color){ 0, 0, 0, 0 } // Blank (Transparent) -#define _rl_MAGENTA CLITERAL(Color){ 255, 0, 255, 255 } // Magenta -#define _rl_RAYWHITE CLITERAL(Color){ 245, 245, 245, 255 } // My own White (raylib logo) - -#ifndef OPENPILOT_RAYLIB - #define LIGHTGRAY _rl_LIGHTGRAY - #define GRAY _rl_GRAY - #define DARKGRAY _rl_DARKGRAY - #define YELLOW _rl_YELLOW - #define GOLD _rl_GOLD - #define ORANGE _rl_ORANGE - #define PINK _rl_PINK - #define RED _rl_RED - #define MAROON _rl_MAROON - #define GREEN _rl_GREEN - #define LIME _rl_LIME - #define DARKGREEN _rl_DARKGREEN - #define SKYBLUE _rl_SKYBLUE - #define BLUE _rl_BLUE - #define DARKBLUE _rl_DARKBLUE - #define PURPLE _rl_PURPLE - #define VIOLET _rl_VIOLET - #define DARKPURPLE _rl_DARKBLUE - #define BEIGE _rl_BEIGE - #define BROWN _rl_BROWN - #define DARKBROWN _rl_DARKBROWN - - #define WHITE _rl_WHITE - #define BLACK _rl_BLACK - #define BLANK _rl_BLANK - #define MAGENTA _rl_MAGENTA - #define RAYWHITE _rl_RAYWHITE -#else - #define RAYLIB_LIGHTGRAY _rl_LIGHTGRAY - #define RAYLIB_GRAY _rl_GRAY - #define RAYLIB_DARKGRAY _rl_DARKGRAY - #define RAYLIB_YELLOW _rl_YELLOW - #define RAYLIB_GOLD _rl_GOLD - #define RAYLIB_ORANGE _rl_ORANGE - #define RAYLIB_PINK _rl_PINK - #define RAYLIB_RED _rl_RED - #define RAYLIB_MAROON _rl_MAROON - #define RAYLIB_GREEN _rl_GREEN - #define RAYLIB_LIME _rl_LIME - #define RAYLIB_DARKGREEN _rl_DARKGREEN - #define RAYLIB_SKYBLUE _rl_SKYBLUE - #define RAYLIB_BLUE _rl_BLUE - #define RAYLIB_DARKBLUE _rl_DARKBLUE - #define RAYLIB_PURPLE _rl_PURPLE - #define RAYLIB_VIOLET _rl_VIOLET - #define RAYLIB_DARKPURPLE _rl_DARKBLUE - #define RAYLIB_BEIGE _rl_BEIGE - #define RAYLIB_BROWN _rl_BROWN - #define RAYLIB_DARKBROWN _rl_DARKBROWN - - #define RAYLIB_WHITE _rl_WHITE - #define RAYLIB_BLACK _rl_BLACK - #define RAYLIB_BLANK _rl_BLANK - #define RAYLIB_MAGENTA _rl_MAGENTA - #define RAYLIB_RAYWHITE _rl_RAYWHITE -#endif - -//---------------------------------------------------------------------------------- -// Structures Definition -//---------------------------------------------------------------------------------- -// Boolean type -#if (defined(__STDC__) && __STDC_VERSION__ >= 199901L) || (defined(_MSC_VER) && _MSC_VER >= 1800) - #include -#elif !defined(__cplusplus) && !defined(bool) - typedef enum bool { false = 0, true = !false } bool; - #define RL_BOOL_TYPE -#endif - -// Vector2, 2 components -typedef struct Vector2 { - float x; // Vector x component - float y; // Vector y component -} Vector2; - -// Vector3, 3 components -typedef struct Vector3 { - float x; // Vector x component - float y; // Vector y component - float z; // Vector z component -} Vector3; - -// Vector4, 4 components -typedef struct Vector4 { - float x; // Vector x component - float y; // Vector y component - float z; // Vector z component - float w; // Vector w component -} Vector4; - -// Quaternion, 4 components (Vector4 alias) -typedef Vector4 Quaternion; - -// Matrix, 4x4 components, column major, OpenGL style, right-handed -typedef struct Matrix { - float m0, m4, m8, m12; // Matrix first row (4 components) - float m1, m5, m9, m13; // Matrix second row (4 components) - float m2, m6, m10, m14; // Matrix third row (4 components) - float m3, m7, m11, m15; // Matrix fourth row (4 components) -} Matrix; - -// Color, 4 components, R8G8B8A8 (32bit) -typedef struct Color { - unsigned char r; // Color red value - unsigned char g; // Color green value - unsigned char b; // Color blue value - unsigned char a; // Color alpha value -} Color; - -// Rectangle, 4 components -typedef struct Rectangle { - float x; // Rectangle top-left corner position x - float y; // Rectangle top-left corner position y - float width; // Rectangle width - float height; // Rectangle height -} Rectangle; - -// Image, pixel data stored in CPU memory (RAM) -typedef struct Image { - void *data; // Image raw data - int width; // Image base width - int height; // Image base height - int mipmaps; // Mipmap levels, 1 by default - int format; // Data format (PixelFormat type) -} Image; - -// Texture, tex data stored in GPU memory (VRAM) -typedef struct Texture { - unsigned int id; // OpenGL texture id - int width; // Texture base width - int height; // Texture base height - int mipmaps; // Mipmap levels, 1 by default - int format; // Data format (PixelFormat type) -} Texture; - -// Texture2D, same as Texture -typedef Texture Texture2D; - -// TextureCubemap, same as Texture -typedef Texture TextureCubemap; - -// RenderTexture, fbo for texture rendering -typedef struct RenderTexture { - unsigned int id; // OpenGL framebuffer object id - Texture texture; // Color buffer attachment texture - Texture depth; // Depth buffer attachment texture -} RenderTexture; - -// RenderTexture2D, same as RenderTexture -typedef RenderTexture RenderTexture2D; - -// NPatchInfo, n-patch layout info -typedef struct NPatchInfo { - Rectangle source; // Texture source rectangle - int left; // Left border offset - int top; // Top border offset - int right; // Right border offset - int bottom; // Bottom border offset - int layout; // Layout of the n-patch: 3x3, 1x3 or 3x1 -} NPatchInfo; - -// GlyphInfo, font characters glyphs info -typedef struct GlyphInfo { - int value; // Character value (Unicode) - int offsetX; // Character offset X when drawing - int offsetY; // Character offset Y when drawing - int advanceX; // Character advance position X - Image image; // Character image data -} GlyphInfo; - -// Font, font texture and GlyphInfo array data -typedef struct Font { - int baseSize; // Base size (default chars height) - int glyphCount; // Number of glyph characters - int glyphPadding; // Padding around the glyph characters - Texture2D texture; // Texture atlas containing the glyphs - Rectangle *recs; // Rectangles in texture for the glyphs - GlyphInfo *glyphs; // Glyphs info data -} Font; - -// Camera, defines position/orientation in 3d space -typedef struct Camera3D { - Vector3 position; // Camera position - Vector3 target; // Camera target it looks-at - Vector3 up; // Camera up vector (rotation over its axis) - float fovy; // Camera field-of-view aperture in Y (degrees) in perspective, used as near plane width in orthographic - int projection; // Camera projection: CAMERA_PERSPECTIVE or CAMERA_ORTHOGRAPHIC -} Camera3D; - -typedef Camera3D Camera; // Camera type fallback, defaults to Camera3D - -// Camera2D, defines position/orientation in 2d space -typedef struct Camera2D { - Vector2 offset; // Camera offset (displacement from target) - Vector2 target; // Camera target (rotation and zoom origin) - float rotation; // Camera rotation in degrees - float zoom; // Camera zoom (scaling), should be 1.0f by default -} Camera2D; - -// Mesh, vertex data and vao/vbo -typedef struct Mesh { - int vertexCount; // Number of vertices stored in arrays - int triangleCount; // Number of triangles stored (indexed or not) - - // Vertex attributes data - float *vertices; // Vertex position (XYZ - 3 components per vertex) (shader-location = 0) - float *texcoords; // Vertex texture coordinates (UV - 2 components per vertex) (shader-location = 1) - float *texcoords2; // Vertex texture second coordinates (UV - 2 components per vertex) (shader-location = 5) - float *normals; // Vertex normals (XYZ - 3 components per vertex) (shader-location = 2) - float *tangents; // Vertex tangents (XYZW - 4 components per vertex) (shader-location = 4) - unsigned char *colors; // Vertex colors (RGBA - 4 components per vertex) (shader-location = 3) - unsigned short *indices; // Vertex indices (in case vertex data comes indexed) - - // Animation vertex data - float *animVertices; // Animated vertex positions (after bones transformations) - float *animNormals; // Animated normals (after bones transformations) - unsigned char *boneIds; // Vertex bone ids, max 255 bone ids, up to 4 bones influence by vertex (skinning) (shader-location = 6) - float *boneWeights; // Vertex bone weight, up to 4 bones influence by vertex (skinning) (shader-location = 7) - Matrix *boneMatrices; // Bones animated transformation matrices - int boneCount; // Number of bones - - // OpenGL identifiers - unsigned int vaoId; // OpenGL Vertex Array Object id - unsigned int *vboId; // OpenGL Vertex Buffer Objects id (default vertex data) -} Mesh; - -// Shader -typedef struct Shader { - unsigned int id; // Shader program id - int *locs; // Shader locations array (RL_MAX_SHADER_LOCATIONS) -} Shader; - -// MaterialMap -typedef struct MaterialMap { - Texture2D texture; // Material map texture - Color color; // Material map color - float value; // Material map value -} MaterialMap; - -// Material, includes shader and maps -typedef struct Material { - Shader shader; // Material shader - MaterialMap *maps; // Material maps array (MAX_MATERIAL_MAPS) - float params[4]; // Material generic parameters (if required) -} Material; - -// Transform, vertex transformation data -typedef struct Transform { - Vector3 translation; // Translation - Quaternion rotation; // Rotation - Vector3 scale; // Scale -} Transform; - -// Bone, skeletal animation bone -typedef struct BoneInfo { - char name[32]; // Bone name - int parent; // Bone parent -} BoneInfo; - -// Model, meshes, materials and animation data -typedef struct Model { - Matrix transform; // Local transform matrix - - int meshCount; // Number of meshes - int materialCount; // Number of materials - Mesh *meshes; // Meshes array - Material *materials; // Materials array - int *meshMaterial; // Mesh material number - - // Animation data - int boneCount; // Number of bones - BoneInfo *bones; // Bones information (skeleton) - Transform *bindPose; // Bones base transformation (pose) -} Model; - -// ModelAnimation -typedef struct ModelAnimation { - int boneCount; // Number of bones - int frameCount; // Number of animation frames - BoneInfo *bones; // Bones information (skeleton) - Transform **framePoses; // Poses array by frame - char name[32]; // Animation name -} ModelAnimation; - -// Ray, ray for raycasting -typedef struct Ray { - Vector3 position; // Ray position (origin) - Vector3 direction; // Ray direction (normalized) -} Ray; - -// RayCollision, ray hit information -typedef struct RayCollision { - bool hit; // Did the ray hit something? - float distance; // Distance to the nearest hit - Vector3 point; // Point of the nearest hit - Vector3 normal; // Surface normal of hit -} RayCollision; - -// BoundingBox -typedef struct BoundingBox { - Vector3 min; // Minimum vertex box-corner - Vector3 max; // Maximum vertex box-corner -} BoundingBox; - -// Wave, audio wave data -typedef struct Wave { - unsigned int frameCount; // Total number of frames (considering channels) - unsigned int sampleRate; // Frequency (samples per second) - unsigned int sampleSize; // Bit depth (bits per sample): 8, 16, 32 (24 not supported) - unsigned int channels; // Number of channels (1-mono, 2-stereo, ...) - void *data; // Buffer data pointer -} Wave; - -// Opaque structs declaration -// NOTE: Actual structs are defined internally in raudio module -typedef struct rAudioBuffer rAudioBuffer; -typedef struct rAudioProcessor rAudioProcessor; - -// AudioStream, custom audio stream -typedef struct AudioStream { - rAudioBuffer *buffer; // Pointer to internal data used by the audio system - rAudioProcessor *processor; // Pointer to internal data processor, useful for audio effects - - unsigned int sampleRate; // Frequency (samples per second) - unsigned int sampleSize; // Bit depth (bits per sample): 8, 16, 32 (24 not supported) - unsigned int channels; // Number of channels (1-mono, 2-stereo, ...) -} AudioStream; - -// Sound -typedef struct Sound { - AudioStream stream; // Audio stream - unsigned int frameCount; // Total number of frames (considering channels) -} Sound; - -// Music, audio stream, anything longer than ~10 seconds should be streamed -typedef struct Music { - AudioStream stream; // Audio stream - unsigned int frameCount; // Total number of frames (considering channels) - bool looping; // Music looping enable - - int ctxType; // Type of music context (audio filetype) - void *ctxData; // Audio context data, depends on type -} Music; - -// VrDeviceInfo, Head-Mounted-Display device parameters -typedef struct VrDeviceInfo { - int hResolution; // Horizontal resolution in pixels - int vResolution; // Vertical resolution in pixels - float hScreenSize; // Horizontal size in meters - float vScreenSize; // Vertical size in meters - float eyeToScreenDistance; // Distance between eye and display in meters - float lensSeparationDistance; // Lens separation distance in meters - float interpupillaryDistance; // IPD (distance between pupils) in meters - float lensDistortionValues[4]; // Lens distortion constant parameters - float chromaAbCorrection[4]; // Chromatic aberration correction parameters -} VrDeviceInfo; - -// VrStereoConfig, VR stereo rendering configuration for simulator -typedef struct VrStereoConfig { - Matrix projection[2]; // VR projection matrices (per eye) - Matrix viewOffset[2]; // VR view offset matrices (per eye) - float leftLensCenter[2]; // VR left lens center - float rightLensCenter[2]; // VR right lens center - float leftScreenCenter[2]; // VR left screen center - float rightScreenCenter[2]; // VR right screen center - float scale[2]; // VR distortion scale - float scaleIn[2]; // VR distortion scale in -} VrStereoConfig; - -// File path list -typedef struct FilePathList { - unsigned int capacity; // Filepaths max entries - unsigned int count; // Filepaths entries count - char **paths; // Filepaths entries -} FilePathList; - -// Automation event -typedef struct AutomationEvent { - unsigned int frame; // Event frame - unsigned int type; // Event type (AutomationEventType) - int params[4]; // Event parameters (if required) -} AutomationEvent; - -// Automation event list -typedef struct AutomationEventList { - unsigned int capacity; // Events max entries (MAX_AUTOMATION_EVENTS) - unsigned int count; // Events entries count - AutomationEvent *events; // Events entries -} AutomationEventList; - -//---------------------------------------------------------------------------------- -// Enumerators Definition -//---------------------------------------------------------------------------------- -// System/Window config flags -// NOTE: Every bit registers one state (use it with bit masks) -// By default all flags are set to 0 -typedef enum { - FLAG_VSYNC_HINT = 0x00000040, // Set to try enabling V-Sync on GPU - FLAG_FULLSCREEN_MODE = 0x00000002, // Set to run program in fullscreen - FLAG_WINDOW_RESIZABLE = 0x00000004, // Set to allow resizable window - FLAG_WINDOW_UNDECORATED = 0x00000008, // Set to disable window decoration (frame and buttons) - FLAG_WINDOW_HIDDEN = 0x00000080, // Set to hide window - FLAG_WINDOW_MINIMIZED = 0x00000200, // Set to minimize window (iconify) - FLAG_WINDOW_MAXIMIZED = 0x00000400, // Set to maximize window (expanded to monitor) - FLAG_WINDOW_UNFOCUSED = 0x00000800, // Set to window non focused - FLAG_WINDOW_TOPMOST = 0x00001000, // Set to window always on top - FLAG_WINDOW_ALWAYS_RUN = 0x00000100, // Set to allow windows running while minimized - FLAG_WINDOW_TRANSPARENT = 0x00000010, // Set to allow transparent framebuffer - FLAG_WINDOW_HIGHDPI = 0x00002000, // Set to support HighDPI - FLAG_WINDOW_MOUSE_PASSTHROUGH = 0x00004000, // Set to support mouse passthrough, only supported when FLAG_WINDOW_UNDECORATED - FLAG_BORDERLESS_WINDOWED_MODE = 0x00008000, // Set to run program in borderless windowed mode - FLAG_MSAA_4X_HINT = 0x00000020, // Set to try enabling MSAA 4X - FLAG_INTERLACED_HINT = 0x00010000 // Set to try enabling interlaced video format (for V3D) -} ConfigFlags; - -// Trace log level -// NOTE: Organized by priority level -typedef enum { - LOG_ALL = 0, // Display all logs - LOG_TRACE, // Trace logging, intended for internal use only - LOG_DEBUG, // Debug logging, used for internal debugging, it should be disabled on release builds - LOG_INFO, // Info logging, used for program execution info - LOG_WARNING, // Warning logging, used on recoverable failures - LOG_ERROR, // Error logging, used on unrecoverable failures - LOG_FATAL, // Fatal logging, used to abort program: exit(EXIT_FAILURE) - LOG_NONE // Disable logging -} TraceLogLevel; - -// Keyboard keys (US keyboard layout) -// NOTE: Use GetKeyPressed() to allow redefining -// required keys for alternative layouts -typedef enum { - KEY_NULL = 0, // Key: NULL, used for no key pressed - // Alphanumeric keys - KEY_APOSTROPHE = 39, // Key: ' - KEY_COMMA = 44, // Key: , - KEY_MINUS = 45, // Key: - - KEY_PERIOD = 46, // Key: . - KEY_SLASH = 47, // Key: / - KEY_ZERO = 48, // Key: 0 - KEY_ONE = 49, // Key: 1 - KEY_TWO = 50, // Key: 2 - KEY_THREE = 51, // Key: 3 - KEY_FOUR = 52, // Key: 4 - KEY_FIVE = 53, // Key: 5 - KEY_SIX = 54, // Key: 6 - KEY_SEVEN = 55, // Key: 7 - KEY_EIGHT = 56, // Key: 8 - KEY_NINE = 57, // Key: 9 - KEY_SEMICOLON = 59, // Key: ; - KEY_EQUAL = 61, // Key: = - KEY_A = 65, // Key: A | a - KEY_B = 66, // Key: B | b - KEY_C = 67, // Key: C | c - KEY_D = 68, // Key: D | d - KEY_E = 69, // Key: E | e - KEY_F = 70, // Key: F | f - KEY_G = 71, // Key: G | g - KEY_H = 72, // Key: H | h - KEY_I = 73, // Key: I | i - KEY_J = 74, // Key: J | j - KEY_K = 75, // Key: K | k - KEY_L = 76, // Key: L | l - KEY_M = 77, // Key: M | m - KEY_N = 78, // Key: N | n - KEY_O = 79, // Key: O | o - KEY_P = 80, // Key: P | p - KEY_Q = 81, // Key: Q | q - KEY_R = 82, // Key: R | r - KEY_S = 83, // Key: S | s - KEY_T = 84, // Key: T | t - KEY_U = 85, // Key: U | u - KEY_V = 86, // Key: V | v - KEY_W = 87, // Key: W | w - KEY_X = 88, // Key: X | x - KEY_Y = 89, // Key: Y | y - KEY_Z = 90, // Key: Z | z - KEY_LEFT_BRACKET = 91, // Key: [ - KEY_BACKSLASH = 92, // Key: '\' - KEY_RIGHT_BRACKET = 93, // Key: ] - KEY_GRAVE = 96, // Key: ` - // Function keys - KEY_SPACE = 32, // Key: Space - KEY_ESCAPE = 256, // Key: Esc - KEY_ENTER = 257, // Key: Enter - KEY_TAB = 258, // Key: Tab - KEY_BACKSPACE = 259, // Key: Backspace - KEY_INSERT = 260, // Key: Ins - KEY_DELETE = 261, // Key: Del - KEY_RIGHT = 262, // Key: Cursor right - KEY_LEFT = 263, // Key: Cursor left - KEY_DOWN = 264, // Key: Cursor down - KEY_UP = 265, // Key: Cursor up - KEY_PAGE_UP = 266, // Key: Page up - KEY_PAGE_DOWN = 267, // Key: Page down - KEY_HOME = 268, // Key: Home - KEY_END = 269, // Key: End - KEY_CAPS_LOCK = 280, // Key: Caps lock - KEY_SCROLL_LOCK = 281, // Key: Scroll down - KEY_NUM_LOCK = 282, // Key: Num lock - KEY_PRINT_SCREEN = 283, // Key: Print screen - KEY_PAUSE = 284, // Key: Pause - KEY_F1 = 290, // Key: F1 - KEY_F2 = 291, // Key: F2 - KEY_F3 = 292, // Key: F3 - KEY_F4 = 293, // Key: F4 - KEY_F5 = 294, // Key: F5 - KEY_F6 = 295, // Key: F6 - KEY_F7 = 296, // Key: F7 - KEY_F8 = 297, // Key: F8 - KEY_F9 = 298, // Key: F9 - KEY_F10 = 299, // Key: F10 - KEY_F11 = 300, // Key: F11 - KEY_F12 = 301, // Key: F12 - KEY_LEFT_SHIFT = 340, // Key: Shift left - KEY_LEFT_CONTROL = 341, // Key: Control left - KEY_LEFT_ALT = 342, // Key: Alt left - KEY_LEFT_SUPER = 343, // Key: Super left - KEY_RIGHT_SHIFT = 344, // Key: Shift right - KEY_RIGHT_CONTROL = 345, // Key: Control right - KEY_RIGHT_ALT = 346, // Key: Alt right - KEY_RIGHT_SUPER = 347, // Key: Super right - KEY_KB_MENU = 348, // Key: KB menu - // Keypad keys - KEY_KP_0 = 320, // Key: Keypad 0 - KEY_KP_1 = 321, // Key: Keypad 1 - KEY_KP_2 = 322, // Key: Keypad 2 - KEY_KP_3 = 323, // Key: Keypad 3 - KEY_KP_4 = 324, // Key: Keypad 4 - KEY_KP_5 = 325, // Key: Keypad 5 - KEY_KP_6 = 326, // Key: Keypad 6 - KEY_KP_7 = 327, // Key: Keypad 7 - KEY_KP_8 = 328, // Key: Keypad 8 - KEY_KP_9 = 329, // Key: Keypad 9 - KEY_KP_DECIMAL = 330, // Key: Keypad . - KEY_KP_DIVIDE = 331, // Key: Keypad / - KEY_KP_MULTIPLY = 332, // Key: Keypad * - KEY_KP_SUBTRACT = 333, // Key: Keypad - - KEY_KP_ADD = 334, // Key: Keypad + - KEY_KP_ENTER = 335, // Key: Keypad Enter - KEY_KP_EQUAL = 336, // Key: Keypad = - // Android key buttons - KEY_BACK = 4, // Key: Android back button - KEY_MENU = 5, // Key: Android menu button - KEY_VOLUME_UP = 24, // Key: Android volume up button - KEY_VOLUME_DOWN = 25 // Key: Android volume down button -} KeyboardKey; - -// Add backwards compatibility support for deprecated names -#define MOUSE_LEFT_BUTTON MOUSE_BUTTON_LEFT -#define MOUSE_RIGHT_BUTTON MOUSE_BUTTON_RIGHT -#define MOUSE_MIDDLE_BUTTON MOUSE_BUTTON_MIDDLE - -// Mouse buttons -typedef enum { - MOUSE_BUTTON_LEFT = 0, // Mouse button left - MOUSE_BUTTON_RIGHT = 1, // Mouse button right - MOUSE_BUTTON_MIDDLE = 2, // Mouse button middle (pressed wheel) - MOUSE_BUTTON_SIDE = 3, // Mouse button side (advanced mouse device) - MOUSE_BUTTON_EXTRA = 4, // Mouse button extra (advanced mouse device) - MOUSE_BUTTON_FORWARD = 5, // Mouse button forward (advanced mouse device) - MOUSE_BUTTON_BACK = 6, // Mouse button back (advanced mouse device) -} MouseButton; - -// Mouse cursor -typedef enum { - MOUSE_CURSOR_DEFAULT = 0, // Default pointer shape - MOUSE_CURSOR_ARROW = 1, // Arrow shape - MOUSE_CURSOR_IBEAM = 2, // Text writing cursor shape - MOUSE_CURSOR_CROSSHAIR = 3, // Cross shape - MOUSE_CURSOR_POINTING_HAND = 4, // Pointing hand cursor - MOUSE_CURSOR_RESIZE_EW = 5, // Horizontal resize/move arrow shape - MOUSE_CURSOR_RESIZE_NS = 6, // Vertical resize/move arrow shape - MOUSE_CURSOR_RESIZE_NWSE = 7, // Top-left to bottom-right diagonal resize/move arrow shape - MOUSE_CURSOR_RESIZE_NESW = 8, // The top-right to bottom-left diagonal resize/move arrow shape - MOUSE_CURSOR_RESIZE_ALL = 9, // The omnidirectional resize/move cursor shape - MOUSE_CURSOR_NOT_ALLOWED = 10 // The operation-not-allowed shape -} MouseCursor; - -// Gamepad buttons -typedef enum { - GAMEPAD_BUTTON_UNKNOWN = 0, // Unknown button, just for error checking - GAMEPAD_BUTTON_LEFT_FACE_UP, // Gamepad left DPAD up button - GAMEPAD_BUTTON_LEFT_FACE_RIGHT, // Gamepad left DPAD right button - GAMEPAD_BUTTON_LEFT_FACE_DOWN, // Gamepad left DPAD down button - GAMEPAD_BUTTON_LEFT_FACE_LEFT, // Gamepad left DPAD left button - GAMEPAD_BUTTON_RIGHT_FACE_UP, // Gamepad right button up (i.e. PS3: Triangle, Xbox: Y) - GAMEPAD_BUTTON_RIGHT_FACE_RIGHT, // Gamepad right button right (i.e. PS3: Circle, Xbox: B) - GAMEPAD_BUTTON_RIGHT_FACE_DOWN, // Gamepad right button down (i.e. PS3: Cross, Xbox: A) - GAMEPAD_BUTTON_RIGHT_FACE_LEFT, // Gamepad right button left (i.e. PS3: Square, Xbox: X) - GAMEPAD_BUTTON_LEFT_TRIGGER_1, // Gamepad top/back trigger left (first), it could be a trailing button - GAMEPAD_BUTTON_LEFT_TRIGGER_2, // Gamepad top/back trigger left (second), it could be a trailing button - GAMEPAD_BUTTON_RIGHT_TRIGGER_1, // Gamepad top/back trigger right (first), it could be a trailing button - GAMEPAD_BUTTON_RIGHT_TRIGGER_2, // Gamepad top/back trigger right (second), it could be a trailing button - GAMEPAD_BUTTON_MIDDLE_LEFT, // Gamepad center buttons, left one (i.e. PS3: Select) - GAMEPAD_BUTTON_MIDDLE, // Gamepad center buttons, middle one (i.e. PS3: PS, Xbox: XBOX) - GAMEPAD_BUTTON_MIDDLE_RIGHT, // Gamepad center buttons, right one (i.e. PS3: Start) - GAMEPAD_BUTTON_LEFT_THUMB, // Gamepad joystick pressed button left - GAMEPAD_BUTTON_RIGHT_THUMB // Gamepad joystick pressed button right -} GamepadButton; - -// Gamepad axis -typedef enum { - GAMEPAD_AXIS_LEFT_X = 0, // Gamepad left stick X axis - GAMEPAD_AXIS_LEFT_Y = 1, // Gamepad left stick Y axis - GAMEPAD_AXIS_RIGHT_X = 2, // Gamepad right stick X axis - GAMEPAD_AXIS_RIGHT_Y = 3, // Gamepad right stick Y axis - GAMEPAD_AXIS_LEFT_TRIGGER = 4, // Gamepad back trigger left, pressure level: [1..-1] - GAMEPAD_AXIS_RIGHT_TRIGGER = 5 // Gamepad back trigger right, pressure level: [1..-1] -} GamepadAxis; - -// Material map index -typedef enum { - MATERIAL_MAP_ALBEDO = 0, // Albedo material (same as: MATERIAL_MAP_DIFFUSE) - MATERIAL_MAP_METALNESS, // Metalness material (same as: MATERIAL_MAP_SPECULAR) - MATERIAL_MAP_NORMAL, // Normal material - MATERIAL_MAP_ROUGHNESS, // Roughness material - MATERIAL_MAP_OCCLUSION, // Ambient occlusion material - MATERIAL_MAP_EMISSION, // Emission material - MATERIAL_MAP_HEIGHT, // Heightmap material - MATERIAL_MAP_CUBEMAP, // Cubemap material (NOTE: Uses GL_TEXTURE_CUBE_MAP) - MATERIAL_MAP_IRRADIANCE, // Irradiance material (NOTE: Uses GL_TEXTURE_CUBE_MAP) - MATERIAL_MAP_PREFILTER, // Prefilter material (NOTE: Uses GL_TEXTURE_CUBE_MAP) - MATERIAL_MAP_BRDF // Brdf material -} MaterialMapIndex; - -#define MATERIAL_MAP_DIFFUSE MATERIAL_MAP_ALBEDO -#define MATERIAL_MAP_SPECULAR MATERIAL_MAP_METALNESS - -// Shader location index -typedef enum { - SHADER_LOC_VERTEX_POSITION = 0, // Shader location: vertex attribute: position - SHADER_LOC_VERTEX_TEXCOORD01, // Shader location: vertex attribute: texcoord01 - SHADER_LOC_VERTEX_TEXCOORD02, // Shader location: vertex attribute: texcoord02 - SHADER_LOC_VERTEX_NORMAL, // Shader location: vertex attribute: normal - SHADER_LOC_VERTEX_TANGENT, // Shader location: vertex attribute: tangent - SHADER_LOC_VERTEX_COLOR, // Shader location: vertex attribute: color - SHADER_LOC_MATRIX_MVP, // Shader location: matrix uniform: model-view-projection - SHADER_LOC_MATRIX_VIEW, // Shader location: matrix uniform: view (camera transform) - SHADER_LOC_MATRIX_PROJECTION, // Shader location: matrix uniform: projection - SHADER_LOC_MATRIX_MODEL, // Shader location: matrix uniform: model (transform) - SHADER_LOC_MATRIX_NORMAL, // Shader location: matrix uniform: normal - SHADER_LOC_VECTOR_VIEW, // Shader location: vector uniform: view - SHADER_LOC_COLOR_DIFFUSE, // Shader location: vector uniform: diffuse color - SHADER_LOC_COLOR_SPECULAR, // Shader location: vector uniform: specular color - SHADER_LOC_COLOR_AMBIENT, // Shader location: vector uniform: ambient color - SHADER_LOC_MAP_ALBEDO, // Shader location: sampler2d texture: albedo (same as: SHADER_LOC_MAP_DIFFUSE) - SHADER_LOC_MAP_METALNESS, // Shader location: sampler2d texture: metalness (same as: SHADER_LOC_MAP_SPECULAR) - SHADER_LOC_MAP_NORMAL, // Shader location: sampler2d texture: normal - SHADER_LOC_MAP_ROUGHNESS, // Shader location: sampler2d texture: roughness - SHADER_LOC_MAP_OCCLUSION, // Shader location: sampler2d texture: occlusion - SHADER_LOC_MAP_EMISSION, // Shader location: sampler2d texture: emission - SHADER_LOC_MAP_HEIGHT, // Shader location: sampler2d texture: height - SHADER_LOC_MAP_CUBEMAP, // Shader location: samplerCube texture: cubemap - SHADER_LOC_MAP_IRRADIANCE, // Shader location: samplerCube texture: irradiance - SHADER_LOC_MAP_PREFILTER, // Shader location: samplerCube texture: prefilter - SHADER_LOC_MAP_BRDF, // Shader location: sampler2d texture: brdf - SHADER_LOC_VERTEX_BONEIDS, // Shader location: vertex attribute: boneIds - SHADER_LOC_VERTEX_BONEWEIGHTS, // Shader location: vertex attribute: boneWeights - SHADER_LOC_BONE_MATRICES // Shader location: array of matrices uniform: boneMatrices -} ShaderLocationIndex; - -#define SHADER_LOC_MAP_DIFFUSE SHADER_LOC_MAP_ALBEDO -#define SHADER_LOC_MAP_SPECULAR SHADER_LOC_MAP_METALNESS - -// Shader uniform data type -typedef enum { - SHADER_UNIFORM_FLOAT = 0, // Shader uniform type: float - SHADER_UNIFORM_VEC2, // Shader uniform type: vec2 (2 float) - SHADER_UNIFORM_VEC3, // Shader uniform type: vec3 (3 float) - SHADER_UNIFORM_VEC4, // Shader uniform type: vec4 (4 float) - SHADER_UNIFORM_INT, // Shader uniform type: int - SHADER_UNIFORM_IVEC2, // Shader uniform type: ivec2 (2 int) - SHADER_UNIFORM_IVEC3, // Shader uniform type: ivec3 (3 int) - SHADER_UNIFORM_IVEC4, // Shader uniform type: ivec4 (4 int) - SHADER_UNIFORM_SAMPLER2D // Shader uniform type: sampler2d -} ShaderUniformDataType; - -// Shader attribute data types -typedef enum { - SHADER_ATTRIB_FLOAT = 0, // Shader attribute type: float - SHADER_ATTRIB_VEC2, // Shader attribute type: vec2 (2 float) - SHADER_ATTRIB_VEC3, // Shader attribute type: vec3 (3 float) - SHADER_ATTRIB_VEC4 // Shader attribute type: vec4 (4 float) -} ShaderAttributeDataType; - -// Pixel formats -// NOTE: Support depends on OpenGL version and platform -typedef enum { - PIXELFORMAT_UNCOMPRESSED_GRAYSCALE = 1, // 8 bit per pixel (no alpha) - PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA, // 8*2 bpp (2 channels) - PIXELFORMAT_UNCOMPRESSED_R5G6B5, // 16 bpp - PIXELFORMAT_UNCOMPRESSED_R8G8B8, // 24 bpp - PIXELFORMAT_UNCOMPRESSED_R5G5B5A1, // 16 bpp (1 bit alpha) - PIXELFORMAT_UNCOMPRESSED_R4G4B4A4, // 16 bpp (4 bit alpha) - PIXELFORMAT_UNCOMPRESSED_R8G8B8A8, // 32 bpp - PIXELFORMAT_UNCOMPRESSED_R32, // 32 bpp (1 channel - float) - PIXELFORMAT_UNCOMPRESSED_R32G32B32, // 32*3 bpp (3 channels - float) - PIXELFORMAT_UNCOMPRESSED_R32G32B32A32, // 32*4 bpp (4 channels - float) - PIXELFORMAT_UNCOMPRESSED_R16, // 16 bpp (1 channel - half float) - PIXELFORMAT_UNCOMPRESSED_R16G16B16, // 16*3 bpp (3 channels - half float) - PIXELFORMAT_UNCOMPRESSED_R16G16B16A16, // 16*4 bpp (4 channels - half float) - PIXELFORMAT_COMPRESSED_DXT1_RGB, // 4 bpp (no alpha) - PIXELFORMAT_COMPRESSED_DXT1_RGBA, // 4 bpp (1 bit alpha) - PIXELFORMAT_COMPRESSED_DXT3_RGBA, // 8 bpp - PIXELFORMAT_COMPRESSED_DXT5_RGBA, // 8 bpp - PIXELFORMAT_COMPRESSED_ETC1_RGB, // 4 bpp - PIXELFORMAT_COMPRESSED_ETC2_RGB, // 4 bpp - PIXELFORMAT_COMPRESSED_ETC2_EAC_RGBA, // 8 bpp - PIXELFORMAT_COMPRESSED_PVRT_RGB, // 4 bpp - PIXELFORMAT_COMPRESSED_PVRT_RGBA, // 4 bpp - PIXELFORMAT_COMPRESSED_ASTC_4x4_RGBA, // 8 bpp - PIXELFORMAT_COMPRESSED_ASTC_8x8_RGBA // 2 bpp -} PixelFormat; - -// Texture parameters: filter mode -// NOTE 1: Filtering considers mipmaps if available in the texture -// NOTE 2: Filter is accordingly set for minification and magnification -typedef enum { - TEXTURE_FILTER_POINT = 0, // No filter, just pixel approximation - TEXTURE_FILTER_BILINEAR, // Linear filtering - TEXTURE_FILTER_TRILINEAR, // Trilinear filtering (linear with mipmaps) - TEXTURE_FILTER_ANISOTROPIC_4X, // Anisotropic filtering 4x - TEXTURE_FILTER_ANISOTROPIC_8X, // Anisotropic filtering 8x - TEXTURE_FILTER_ANISOTROPIC_16X, // Anisotropic filtering 16x -} TextureFilter; - -// Texture parameters: wrap mode -typedef enum { - TEXTURE_WRAP_REPEAT = 0, // Repeats texture in tiled mode - TEXTURE_WRAP_CLAMP, // Clamps texture to edge pixel in tiled mode - TEXTURE_WRAP_MIRROR_REPEAT, // Mirrors and repeats the texture in tiled mode - TEXTURE_WRAP_MIRROR_CLAMP // Mirrors and clamps to border the texture in tiled mode -} TextureWrap; - -// Cubemap layouts -typedef enum { - CUBEMAP_LAYOUT_AUTO_DETECT = 0, // Automatically detect layout type - CUBEMAP_LAYOUT_LINE_VERTICAL, // Layout is defined by a vertical line with faces - CUBEMAP_LAYOUT_LINE_HORIZONTAL, // Layout is defined by a horizontal line with faces - CUBEMAP_LAYOUT_CROSS_THREE_BY_FOUR, // Layout is defined by a 3x4 cross with cubemap faces - CUBEMAP_LAYOUT_CROSS_FOUR_BY_THREE // Layout is defined by a 4x3 cross with cubemap faces -} CubemapLayout; - -// Font type, defines generation method -typedef enum { - FONT_DEFAULT = 0, // Default font generation, anti-aliased - FONT_BITMAP, // Bitmap font generation, no anti-aliasing - FONT_SDF // SDF font generation, requires external shader -} FontType; - -// Color blending modes (pre-defined) -typedef enum { - BLEND_ALPHA = 0, // Blend textures considering alpha (default) - BLEND_ADDITIVE, // Blend textures adding colors - BLEND_MULTIPLIED, // Blend textures multiplying colors - BLEND_ADD_COLORS, // Blend textures adding colors (alternative) - BLEND_SUBTRACT_COLORS, // Blend textures subtracting colors (alternative) - BLEND_ALPHA_PREMULTIPLY, // Blend premultiplied textures considering alpha - BLEND_CUSTOM, // Blend textures using custom src/dst factors (use rlSetBlendFactors()) - BLEND_CUSTOM_SEPARATE // Blend textures using custom rgb/alpha separate src/dst factors (use rlSetBlendFactorsSeparate()) -} BlendMode; - -// Gesture -// NOTE: Provided as bit-wise flags to enable only desired gestures -typedef enum { - GESTURE_NONE = 0, // No gesture - GESTURE_TAP = 1, // Tap gesture - GESTURE_DOUBLETAP = 2, // Double tap gesture - GESTURE_HOLD = 4, // Hold gesture - GESTURE_DRAG = 8, // Drag gesture - GESTURE_SWIPE_RIGHT = 16, // Swipe right gesture - GESTURE_SWIPE_LEFT = 32, // Swipe left gesture - GESTURE_SWIPE_UP = 64, // Swipe up gesture - GESTURE_SWIPE_DOWN = 128, // Swipe down gesture - GESTURE_PINCH_IN = 256, // Pinch in gesture - GESTURE_PINCH_OUT = 512 // Pinch out gesture -} Gesture; - -// Camera system modes -typedef enum { - CAMERA_CUSTOM = 0, // Camera custom, controlled by user (UpdateCamera() does nothing) - CAMERA_FREE, // Camera free mode - CAMERA_ORBITAL, // Camera orbital, around target, zoom supported - CAMERA_FIRST_PERSON, // Camera first person - CAMERA_THIRD_PERSON // Camera third person -} CameraMode; - -// Camera projection -typedef enum { - CAMERA_PERSPECTIVE = 0, // Perspective projection - CAMERA_ORTHOGRAPHIC // Orthographic projection -} CameraProjection; - -// N-patch layout -typedef enum { - NPATCH_NINE_PATCH = 0, // Npatch layout: 3x3 tiles - NPATCH_THREE_PATCH_VERTICAL, // Npatch layout: 1x3 tiles - NPATCH_THREE_PATCH_HORIZONTAL // Npatch layout: 3x1 tiles -} NPatchLayout; - -// Callbacks to hook some internal functions -// WARNING: These callbacks are intended for advanced users -typedef void (*TraceLogCallback)(int logLevel, const char *text, va_list args); // Logging: Redirect trace log messages -typedef unsigned char *(*LoadFileDataCallback)(const char *fileName, int *dataSize); // FileIO: Load binary data -typedef bool (*SaveFileDataCallback)(const char *fileName, void *data, int dataSize); // FileIO: Save binary data -typedef char *(*LoadFileTextCallback)(const char *fileName); // FileIO: Load text data -typedef bool (*SaveFileTextCallback)(const char *fileName, char *text); // FileIO: Save text data - -//------------------------------------------------------------------------------------ -// Global Variables Definition -//------------------------------------------------------------------------------------ -// It's lonely here... - -//------------------------------------------------------------------------------------ -// Window and Graphics Device Functions (Module: core) -//------------------------------------------------------------------------------------ - -#if defined(__cplusplus) -extern "C" { // Prevents name mangling of functions -#endif - -// Window-related functions -RLAPI void InitWindow(int width, int height, const char *title); // Initialize window and OpenGL context -RLAPI void CloseWindow(void); // Close window and unload OpenGL context -RLAPI bool WindowShouldClose(void); // Check if application should close (KEY_ESCAPE pressed or windows close icon clicked) -RLAPI bool IsWindowReady(void); // Check if window has been initialized successfully -RLAPI bool IsWindowFullscreen(void); // Check if window is currently fullscreen -RLAPI bool IsWindowHidden(void); // Check if window is currently hidden -RLAPI bool IsWindowMinimized(void); // Check if window is currently minimized -RLAPI bool IsWindowMaximized(void); // Check if window is currently maximized -RLAPI bool IsWindowFocused(void); // Check if window is currently focused -RLAPI bool IsWindowResized(void); // Check if window has been resized last frame -RLAPI bool IsWindowState(unsigned int flag); // Check if one specific window flag is enabled -RLAPI void SetWindowState(unsigned int flags); // Set window configuration state using flags -RLAPI void ClearWindowState(unsigned int flags); // Clear window configuration state flags -RLAPI void ToggleFullscreen(void); // Toggle window state: fullscreen/windowed, resizes monitor to match window resolution -RLAPI void ToggleBorderlessWindowed(void); // Toggle window state: borderless windowed, resizes window to match monitor resolution -RLAPI void MaximizeWindow(void); // Set window state: maximized, if resizable -RLAPI void MinimizeWindow(void); // Set window state: minimized, if resizable -RLAPI void RestoreWindow(void); // Set window state: not minimized/maximized -RLAPI void SetWindowIcon(Image image); // Set icon for window (single image, RGBA 32bit) -RLAPI void SetWindowIcons(Image *images, int count); // Set icon for window (multiple images, RGBA 32bit) -RLAPI void SetWindowTitle(const char *title); // Set title for window -RLAPI void SetWindowPosition(int x, int y); // Set window position on screen -RLAPI void SetWindowMonitor(int monitor); // Set monitor for the current window -RLAPI void SetWindowMinSize(int width, int height); // Set window minimum dimensions (for FLAG_WINDOW_RESIZABLE) -RLAPI void SetWindowMaxSize(int width, int height); // Set window maximum dimensions (for FLAG_WINDOW_RESIZABLE) -RLAPI void SetWindowSize(int width, int height); // Set window dimensions -RLAPI void SetWindowOpacity(float opacity); // Set window opacity [0.0f..1.0f] -RLAPI void SetWindowFocused(void); // Set window focused -RLAPI void *GetWindowHandle(void); // Get native window handle -RLAPI int GetScreenWidth(void); // Get current screen width -RLAPI int GetScreenHeight(void); // Get current screen height -RLAPI int GetRenderWidth(void); // Get current render width (it considers HiDPI) -RLAPI int GetRenderHeight(void); // Get current render height (it considers HiDPI) -RLAPI int GetMonitorCount(void); // Get number of connected monitors -RLAPI int GetCurrentMonitor(void); // Get current monitor where window is placed -RLAPI Vector2 GetMonitorPosition(int monitor); // Get specified monitor position -RLAPI int GetMonitorWidth(int monitor); // Get specified monitor width (current video mode used by monitor) -RLAPI int GetMonitorHeight(int monitor); // Get specified monitor height (current video mode used by monitor) -RLAPI int GetMonitorPhysicalWidth(int monitor); // Get specified monitor physical width in millimetres -RLAPI int GetMonitorPhysicalHeight(int monitor); // Get specified monitor physical height in millimetres -RLAPI int GetMonitorRefreshRate(int monitor); // Get specified monitor refresh rate -RLAPI Vector2 GetWindowPosition(void); // Get window position XY on monitor -RLAPI Vector2 GetWindowScaleDPI(void); // Get window scale DPI factor -RLAPI const char *GetMonitorName(int monitor); // Get the human-readable, UTF-8 encoded name of the specified monitor -RLAPI void SetClipboardText(const char *text); // Set clipboard text content -RLAPI const char *GetClipboardText(void); // Get clipboard text content -RLAPI Image GetClipboardImage(void); // Get clipboard image content -RLAPI void EnableEventWaiting(void); // Enable waiting for events on EndDrawing(), no automatic event polling -RLAPI void DisableEventWaiting(void); // Disable waiting for events on EndDrawing(), automatic events polling - -// Cursor-related functions -RLAPI void ShowCursor(void); // Shows cursor -RLAPI void HideCursor(void); // Hides cursor -RLAPI bool IsCursorHidden(void); // Check if cursor is not visible -RLAPI void EnableCursor(void); // Enables cursor (unlock cursor) -RLAPI void DisableCursor(void); // Disables cursor (lock cursor) -RLAPI bool IsCursorOnScreen(void); // Check if cursor is on the screen - -// Drawing-related functions -RLAPI void ClearBackground(Color color); // Set background color (framebuffer clear color) -RLAPI void BeginDrawing(void); // Setup canvas (framebuffer) to start drawing -RLAPI void EndDrawing(void); // End canvas drawing and swap buffers (double buffering) -RLAPI void BeginMode2D(Camera2D camera); // Begin 2D mode with custom camera (2D) -RLAPI void EndMode2D(void); // Ends 2D mode with custom camera -RLAPI void BeginMode3D(Camera3D camera); // Begin 3D mode with custom camera (3D) -RLAPI void EndMode3D(void); // Ends 3D mode and returns to default 2D orthographic mode -RLAPI void BeginTextureMode(RenderTexture2D target); // Begin drawing to render texture -RLAPI void EndTextureMode(void); // Ends drawing to render texture -RLAPI void BeginShaderMode(Shader shader); // Begin custom shader drawing -RLAPI void EndShaderMode(void); // End custom shader drawing (use default shader) -RLAPI void BeginBlendMode(int mode); // Begin blending mode (alpha, additive, multiplied, subtract, custom) -RLAPI void EndBlendMode(void); // End blending mode (reset to default: alpha blending) -RLAPI void BeginScissorMode(int x, int y, int width, int height); // Begin scissor mode (define screen area for following drawing) -RLAPI void EndScissorMode(void); // End scissor mode -RLAPI void BeginVrStereoMode(VrStereoConfig config); // Begin stereo rendering (requires VR simulator) -RLAPI void EndVrStereoMode(void); // End stereo rendering (requires VR simulator) - -// VR stereo config functions for VR simulator -RLAPI VrStereoConfig LoadVrStereoConfig(VrDeviceInfo device); // Load VR stereo config for VR simulator device parameters -RLAPI void UnloadVrStereoConfig(VrStereoConfig config); // Unload VR stereo config - -// Shader management functions -// NOTE: Shader functionality is not available on OpenGL 1.1 -RLAPI Shader LoadShader(const char *vsFileName, const char *fsFileName); // Load shader from files and bind default locations -RLAPI Shader LoadShaderFromMemory(const char *vsCode, const char *fsCode); // Load shader from code strings and bind default locations -RLAPI bool IsShaderValid(Shader shader); // Check if a shader is valid (loaded on GPU) -RLAPI int GetShaderLocation(Shader shader, const char *uniformName); // Get shader uniform location -RLAPI int GetShaderLocationAttrib(Shader shader, const char *attribName); // Get shader attribute location -RLAPI void SetShaderValue(Shader shader, int locIndex, const void *value, int uniformType); // Set shader uniform value -RLAPI void SetShaderValueV(Shader shader, int locIndex, const void *value, int uniformType, int count); // Set shader uniform value vector -RLAPI void SetShaderValueMatrix(Shader shader, int locIndex, Matrix mat); // Set shader uniform value (matrix 4x4) -RLAPI void SetShaderValueTexture(Shader shader, int locIndex, Texture2D texture); // Set shader uniform value for texture (sampler2d) -RLAPI void UnloadShader(Shader shader); // Unload shader from GPU memory (VRAM) - -// Screen-space-related functions -#define GetMouseRay GetScreenToWorldRay // Compatibility hack for previous raylib versions -RLAPI Ray GetScreenToWorldRay(Vector2 position, Camera camera); // Get a ray trace from screen position (i.e mouse) -RLAPI Ray GetScreenToWorldRayEx(Vector2 position, Camera camera, int width, int height); // Get a ray trace from screen position (i.e mouse) in a viewport -RLAPI Vector2 GetWorldToScreen(Vector3 position, Camera camera); // Get the screen space position for a 3d world space position -RLAPI Vector2 GetWorldToScreenEx(Vector3 position, Camera camera, int width, int height); // Get size position for a 3d world space position -RLAPI Vector2 GetWorldToScreen2D(Vector2 position, Camera2D camera); // Get the screen space position for a 2d camera world space position -RLAPI Vector2 GetScreenToWorld2D(Vector2 position, Camera2D camera); // Get the world space position for a 2d camera screen space position -RLAPI Matrix GetCameraMatrix(Camera camera); // Get camera transform matrix (view matrix) -RLAPI Matrix GetCameraMatrix2D(Camera2D camera); // Get camera 2d transform matrix - -// Timing-related functions -RLAPI void SetTargetFPS(int fps); // Set target FPS (maximum) -RLAPI float GetFrameTime(void); // Get time in seconds for last frame drawn (delta time) -RLAPI double GetTime(void); // Get elapsed time in seconds since InitWindow() -RLAPI int GetFPS(void); // Get current FPS - -// Custom frame control functions -// NOTE: Those functions are intended for advanced users that want full control over the frame processing -// By default EndDrawing() does this job: draws everything + SwapScreenBuffer() + manage frame timing + PollInputEvents() -// To avoid that behaviour and control frame processes manually, enable in config.h: SUPPORT_CUSTOM_FRAME_CONTROL -RLAPI void SwapScreenBuffer(void); // Swap back buffer with front buffer (screen drawing) -RLAPI void PollInputEvents(void); // Register all input events -RLAPI void WaitTime(double seconds); // Wait for some time (halt program execution) - -// Random values generation functions -RLAPI void SetRandomSeed(unsigned int seed); // Set the seed for the random number generator -RLAPI int GetRandomValue(int min, int max); // Get a random value between min and max (both included) -RLAPI int *LoadRandomSequence(unsigned int count, int min, int max); // Load random values sequence, no values repeated -RLAPI void UnloadRandomSequence(int *sequence); // Unload random values sequence - -// Misc. functions -RLAPI void TakeScreenshot(const char *fileName); // Takes a screenshot of current screen (filename extension defines format) -RLAPI void SetConfigFlags(unsigned int flags); // Setup init configuration flags (view FLAGS) -RLAPI void OpenURL(const char *url); // Open URL with default system browser (if available) - -// NOTE: Following functions implemented in module [utils] -//------------------------------------------------------------------ -RLAPI void TraceLog(int logLevel, const char *text, ...); // Show trace log messages (LOG_DEBUG, LOG_INFO, LOG_WARNING, LOG_ERROR...) -RLAPI void SetTraceLogLevel(int logLevel); // Set the current threshold (minimum) log level -RLAPI void *MemAlloc(unsigned int size); // Internal memory allocator -RLAPI void *MemRealloc(void *ptr, unsigned int size); // Internal memory reallocator -RLAPI void MemFree(void *ptr); // Internal memory free - -// Set custom callbacks -// WARNING: Callbacks setup is intended for advanced users -RLAPI void SetTraceLogCallback(TraceLogCallback callback); // Set custom trace log -RLAPI void SetLoadFileDataCallback(LoadFileDataCallback callback); // Set custom file binary data loader -RLAPI void SetSaveFileDataCallback(SaveFileDataCallback callback); // Set custom file binary data saver -RLAPI void SetLoadFileTextCallback(LoadFileTextCallback callback); // Set custom file text data loader -RLAPI void SetSaveFileTextCallback(SaveFileTextCallback callback); // Set custom file text data saver - -// Files management functions -RLAPI unsigned char *LoadFileData(const char *fileName, int *dataSize); // Load file data as byte array (read) -RLAPI void UnloadFileData(unsigned char *data); // Unload file data allocated by LoadFileData() -RLAPI bool SaveFileData(const char *fileName, void *data, int dataSize); // Save data to file from byte array (write), returns true on success -RLAPI bool ExportDataAsCode(const unsigned char *data, int dataSize, const char *fileName); // Export data to code (.h), returns true on success -RLAPI char *LoadFileText(const char *fileName); // Load text data from file (read), returns a '\0' terminated string -RLAPI void UnloadFileText(char *text); // Unload file text data allocated by LoadFileText() -RLAPI bool SaveFileText(const char *fileName, char *text); // Save text data to file (write), string must be '\0' terminated, returns true on success -//------------------------------------------------------------------ - -// File system functions -RLAPI bool FileExists(const char *fileName); // Check if file exists -RLAPI bool DirectoryExists(const char *dirPath); // Check if a directory path exists -RLAPI bool IsFileExtension(const char *fileName, const char *ext); // Check file extension (including point: .png, .wav) -RLAPI int GetFileLength(const char *fileName); // Get file length in bytes (NOTE: GetFileSize() conflicts with windows.h) -RLAPI const char *GetFileExtension(const char *fileName); // Get pointer to extension for a filename string (includes dot: '.png') -RLAPI const char *GetFileName(const char *filePath); // Get pointer to filename for a path string -RLAPI const char *GetFileNameWithoutExt(const char *filePath); // Get filename string without extension (uses static string) -RLAPI const char *GetDirectoryPath(const char *filePath); // Get full path for a given fileName with path (uses static string) -RLAPI const char *GetPrevDirectoryPath(const char *dirPath); // Get previous directory path for a given path (uses static string) -RLAPI const char *GetWorkingDirectory(void); // Get current working directory (uses static string) -RLAPI const char *GetApplicationDirectory(void); // Get the directory of the running application (uses static string) -RLAPI int MakeDirectory(const char *dirPath); // Create directories (including full path requested), returns 0 on success -RLAPI bool ChangeDirectory(const char *dir); // Change working directory, return true on success -RLAPI bool IsPathFile(const char *path); // Check if a given path is a file or a directory -RLAPI bool IsFileNameValid(const char *fileName); // Check if fileName is valid for the platform/OS -RLAPI FilePathList LoadDirectoryFiles(const char *dirPath); // Load directory filepaths -RLAPI FilePathList LoadDirectoryFilesEx(const char *basePath, const char *filter, bool scanSubdirs); // Load directory filepaths with extension filtering and recursive directory scan. Use 'DIR' in the filter string to include directories in the result -RLAPI void UnloadDirectoryFiles(FilePathList files); // Unload filepaths -RLAPI bool IsFileDropped(void); // Check if a file has been dropped into window -RLAPI FilePathList LoadDroppedFiles(void); // Load dropped filepaths -RLAPI void UnloadDroppedFiles(FilePathList files); // Unload dropped filepaths -RLAPI long GetFileModTime(const char *fileName); // Get file modification time (last write time) - -// Compression/Encoding functionality -RLAPI unsigned char *CompressData(const unsigned char *data, int dataSize, int *compDataSize); // Compress data (DEFLATE algorithm), memory must be MemFree() -RLAPI unsigned char *DecompressData(const unsigned char *compData, int compDataSize, int *dataSize); // Decompress data (DEFLATE algorithm), memory must be MemFree() -RLAPI char *EncodeDataBase64(const unsigned char *data, int dataSize, int *outputSize); // Encode data to Base64 string, memory must be MemFree() -RLAPI unsigned char *DecodeDataBase64(const unsigned char *data, int *outputSize); // Decode Base64 string data, memory must be MemFree() -RLAPI unsigned int ComputeCRC32(unsigned char *data, int dataSize); // Compute CRC32 hash code -RLAPI unsigned int *ComputeMD5(unsigned char *data, int dataSize); // Compute MD5 hash code, returns static int[4] (16 bytes) -RLAPI unsigned int *ComputeSHA1(unsigned char *data, int dataSize); // Compute SHA1 hash code, returns static int[5] (20 bytes) - - -// Automation events functionality -RLAPI AutomationEventList LoadAutomationEventList(const char *fileName); // Load automation events list from file, NULL for empty list, capacity = MAX_AUTOMATION_EVENTS -RLAPI void UnloadAutomationEventList(AutomationEventList list); // Unload automation events list from file -RLAPI bool ExportAutomationEventList(AutomationEventList list, const char *fileName); // Export automation events list as text file -RLAPI void SetAutomationEventList(AutomationEventList *list); // Set automation event list to record to -RLAPI void SetAutomationEventBaseFrame(int frame); // Set automation event internal base frame to start recording -RLAPI void StartAutomationEventRecording(void); // Start recording automation events (AutomationEventList must be set) -RLAPI void StopAutomationEventRecording(void); // Stop recording automation events -RLAPI void PlayAutomationEvent(AutomationEvent event); // Play a recorded automation event - -//------------------------------------------------------------------------------------ -// Input Handling Functions (Module: core) -//------------------------------------------------------------------------------------ - -// Input-related functions: keyboard -RLAPI bool IsKeyPressed(int key); // Check if a key has been pressed once -RLAPI bool IsKeyPressedRepeat(int key); // Check if a key has been pressed again -RLAPI bool IsKeyDown(int key); // Check if a key is being pressed -RLAPI bool IsKeyReleased(int key); // Check if a key has been released once -RLAPI bool IsKeyUp(int key); // Check if a key is NOT being pressed -RLAPI int GetKeyPressed(void); // Get key pressed (keycode), call it multiple times for keys queued, returns 0 when the queue is empty -RLAPI int GetCharPressed(void); // Get char pressed (unicode), call it multiple times for chars queued, returns 0 when the queue is empty -RLAPI void SetExitKey(int key); // Set a custom key to exit program (default is ESC) - -// Input-related functions: gamepads -RLAPI bool IsGamepadAvailable(int gamepad); // Check if a gamepad is available -RLAPI const char *GetGamepadName(int gamepad); // Get gamepad internal name id -RLAPI bool IsGamepadButtonPressed(int gamepad, int button); // Check if a gamepad button has been pressed once -RLAPI bool IsGamepadButtonDown(int gamepad, int button); // Check if a gamepad button is being pressed -RLAPI bool IsGamepadButtonReleased(int gamepad, int button); // Check if a gamepad button has been released once -RLAPI bool IsGamepadButtonUp(int gamepad, int button); // Check if a gamepad button is NOT being pressed -RLAPI int GetGamepadButtonPressed(void); // Get the last gamepad button pressed -RLAPI int GetGamepadAxisCount(int gamepad); // Get gamepad axis count for a gamepad -RLAPI float GetGamepadAxisMovement(int gamepad, int axis); // Get axis movement value for a gamepad axis -RLAPI int SetGamepadMappings(const char *mappings); // Set internal gamepad mappings (SDL_GameControllerDB) -RLAPI void SetGamepadVibration(int gamepad, float leftMotor, float rightMotor, float duration); // Set gamepad vibration for both motors (duration in seconds) - -// Input-related functions: mouse -RLAPI bool IsMouseButtonPressed(int button); // Check if a mouse button has been pressed once -RLAPI bool IsMouseButtonDown(int button); // Check if a mouse button is being pressed -RLAPI bool IsMouseButtonReleased(int button); // Check if a mouse button has been released once -RLAPI bool IsMouseButtonUp(int button); // Check if a mouse button is NOT being pressed -RLAPI int GetMouseX(void); // Get mouse position X -RLAPI int GetMouseY(void); // Get mouse position Y -RLAPI Vector2 GetMousePosition(void); // Get mouse position XY -RLAPI Vector2 GetMouseDelta(void); // Get mouse delta between frames -RLAPI void SetMousePosition(int x, int y); // Set mouse position XY -RLAPI void SetMouseOffset(int offsetX, int offsetY); // Set mouse offset -RLAPI void SetMouseScale(float scaleX, float scaleY); // Set mouse scaling -RLAPI float GetMouseWheelMove(void); // Get mouse wheel movement for X or Y, whichever is larger -RLAPI Vector2 GetMouseWheelMoveV(void); // Get mouse wheel movement for both X and Y -RLAPI void SetMouseCursor(int cursor); // Set mouse cursor - -// Input-related functions: touch -RLAPI int GetTouchX(void); // Get touch position X for touch point 0 (relative to screen size) -RLAPI int GetTouchY(void); // Get touch position Y for touch point 0 (relative to screen size) -RLAPI Vector2 GetTouchPosition(int index); // Get touch position XY for a touch point index (relative to screen size) -RLAPI int GetTouchPointId(int index); // Get touch point identifier for given index -RLAPI int GetTouchPointCount(void); // Get number of touch points - -//------------------------------------------------------------------------------------ -// Gestures and Touch Handling Functions (Module: rgestures) -//------------------------------------------------------------------------------------ -RLAPI void SetGesturesEnabled(unsigned int flags); // Enable a set of gestures using flags -RLAPI bool IsGestureDetected(unsigned int gesture); // Check if a gesture have been detected -RLAPI int GetGestureDetected(void); // Get latest detected gesture -RLAPI float GetGestureHoldDuration(void); // Get gesture hold time in seconds -RLAPI Vector2 GetGestureDragVector(void); // Get gesture drag vector -RLAPI float GetGestureDragAngle(void); // Get gesture drag angle -RLAPI Vector2 GetGesturePinchVector(void); // Get gesture pinch delta -RLAPI float GetGesturePinchAngle(void); // Get gesture pinch angle - -//------------------------------------------------------------------------------------ -// Camera System Functions (Module: rcamera) -//------------------------------------------------------------------------------------ -RLAPI void UpdateCamera(Camera *camera, int mode); // Update camera position for selected mode -RLAPI void UpdateCameraPro(Camera *camera, Vector3 movement, Vector3 rotation, float zoom); // Update camera movement/rotation - -//------------------------------------------------------------------------------------ -// Basic Shapes Drawing Functions (Module: shapes) -//------------------------------------------------------------------------------------ -// Set texture and rectangle to be used on shapes drawing -// NOTE: It can be useful when using basic shapes and one single font, -// defining a font char white rectangle would allow drawing everything in a single draw call -RLAPI void SetShapesTexture(Texture2D texture, Rectangle source); // Set texture and rectangle to be used on shapes drawing -RLAPI Texture2D GetShapesTexture(void); // Get texture that is used for shapes drawing -RLAPI Rectangle GetShapesTextureRectangle(void); // Get texture source rectangle that is used for shapes drawing - -// Basic shapes drawing functions -RLAPI void DrawPixel(int posX, int posY, Color color); // Draw a pixel using geometry [Can be slow, use with care] -RLAPI void DrawPixelV(Vector2 position, Color color); // Draw a pixel using geometry (Vector version) [Can be slow, use with care] -RLAPI void DrawLine(int startPosX, int startPosY, int endPosX, int endPosY, Color color); // Draw a line -RLAPI void DrawLineV(Vector2 startPos, Vector2 endPos, Color color); // Draw a line (using gl lines) -RLAPI void DrawLineEx(Vector2 startPos, Vector2 endPos, float thick, Color color); // Draw a line (using triangles/quads) -RLAPI void DrawLineStrip(const Vector2 *points, int pointCount, Color color); // Draw lines sequence (using gl lines) -RLAPI void DrawLineBezier(Vector2 startPos, Vector2 endPos, float thick, Color color); // Draw line segment cubic-bezier in-out interpolation -RLAPI void DrawCircle(int centerX, int centerY, float radius, Color color); // Draw a color-filled circle -RLAPI void DrawCircleSector(Vector2 center, float radius, float startAngle, float endAngle, int segments, Color color); // Draw a piece of a circle -RLAPI void DrawCircleSectorLines(Vector2 center, float radius, float startAngle, float endAngle, int segments, Color color); // Draw circle sector outline -RLAPI void DrawCircleGradient(int centerX, int centerY, float radius, Color inner, Color outer); // Draw a gradient-filled circle -RLAPI void DrawCircleV(Vector2 center, float radius, Color color); // Draw a color-filled circle (Vector version) -RLAPI void DrawCircleLines(int centerX, int centerY, float radius, Color color); // Draw circle outline -RLAPI void DrawCircleLinesV(Vector2 center, float radius, Color color); // Draw circle outline (Vector version) -RLAPI void DrawEllipse(int centerX, int centerY, float radiusH, float radiusV, Color color); // Draw ellipse -RLAPI void DrawEllipseLines(int centerX, int centerY, float radiusH, float radiusV, Color color); // Draw ellipse outline -RLAPI void DrawRing(Vector2 center, float innerRadius, float outerRadius, float startAngle, float endAngle, int segments, Color color); // Draw ring -RLAPI void DrawRingLines(Vector2 center, float innerRadius, float outerRadius, float startAngle, float endAngle, int segments, Color color); // Draw ring outline -RLAPI void DrawRectangle(int posX, int posY, int width, int height, Color color); // Draw a color-filled rectangle -RLAPI void DrawRectangleV(Vector2 position, Vector2 size, Color color); // Draw a color-filled rectangle (Vector version) -RLAPI void DrawRectangleRec(Rectangle rec, Color color); // Draw a color-filled rectangle -RLAPI void DrawRectanglePro(Rectangle rec, Vector2 origin, float rotation, Color color); // Draw a color-filled rectangle with pro parameters -RLAPI void DrawRectangleGradientV(int posX, int posY, int width, int height, Color top, Color bottom); // Draw a vertical-gradient-filled rectangle -RLAPI void DrawRectangleGradientH(int posX, int posY, int width, int height, Color left, Color right); // Draw a horizontal-gradient-filled rectangle -RLAPI void DrawRectangleGradientEx(Rectangle rec, Color topLeft, Color bottomLeft, Color topRight, Color bottomRight); // Draw a gradient-filled rectangle with custom vertex colors -RLAPI void DrawRectangleLines(int posX, int posY, int width, int height, Color color); // Draw rectangle outline -RLAPI void DrawRectangleLinesEx(Rectangle rec, float lineThick, Color color); // Draw rectangle outline with extended parameters -RLAPI void DrawRectangleRounded(Rectangle rec, float roundness, int segments, Color color); // Draw rectangle with rounded edges -RLAPI void DrawRectangleRoundedLines(Rectangle rec, float roundness, int segments, Color color); // Draw rectangle lines with rounded edges -RLAPI void DrawRectangleRoundedLinesEx(Rectangle rec, float roundness, int segments, float lineThick, Color color); // Draw rectangle with rounded edges outline -RLAPI void DrawTriangle(Vector2 v1, Vector2 v2, Vector2 v3, Color color); // Draw a color-filled triangle (vertex in counter-clockwise order!) -RLAPI void DrawTriangleLines(Vector2 v1, Vector2 v2, Vector2 v3, Color color); // Draw triangle outline (vertex in counter-clockwise order!) -RLAPI void DrawTriangleFan(const Vector2 *points, int pointCount, Color color); // Draw a triangle fan defined by points (first vertex is the center) -RLAPI void DrawTriangleStrip(const Vector2 *points, int pointCount, Color color); // Draw a triangle strip defined by points -RLAPI void DrawPoly(Vector2 center, int sides, float radius, float rotation, Color color); // Draw a regular polygon (Vector version) -RLAPI void DrawPolyLines(Vector2 center, int sides, float radius, float rotation, Color color); // Draw a polygon outline of n sides -RLAPI void DrawPolyLinesEx(Vector2 center, int sides, float radius, float rotation, float lineThick, Color color); // Draw a polygon outline of n sides with extended parameters - -// Splines drawing functions -RLAPI void DrawSplineLinear(const Vector2 *points, int pointCount, float thick, Color color); // Draw spline: Linear, minimum 2 points -RLAPI void DrawSplineBasis(const Vector2 *points, int pointCount, float thick, Color color); // Draw spline: B-Spline, minimum 4 points -RLAPI void DrawSplineCatmullRom(const Vector2 *points, int pointCount, float thick, Color color); // Draw spline: Catmull-Rom, minimum 4 points -RLAPI void DrawSplineBezierQuadratic(const Vector2 *points, int pointCount, float thick, Color color); // Draw spline: Quadratic Bezier, minimum 3 points (1 control point): [p1, c2, p3, c4...] -RLAPI void DrawSplineBezierCubic(const Vector2 *points, int pointCount, float thick, Color color); // Draw spline: Cubic Bezier, minimum 4 points (2 control points): [p1, c2, c3, p4, c5, c6...] -RLAPI void DrawSplineSegmentLinear(Vector2 p1, Vector2 p2, float thick, Color color); // Draw spline segment: Linear, 2 points -RLAPI void DrawSplineSegmentBasis(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4, float thick, Color color); // Draw spline segment: B-Spline, 4 points -RLAPI void DrawSplineSegmentCatmullRom(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4, float thick, Color color); // Draw spline segment: Catmull-Rom, 4 points -RLAPI void DrawSplineSegmentBezierQuadratic(Vector2 p1, Vector2 c2, Vector2 p3, float thick, Color color); // Draw spline segment: Quadratic Bezier, 2 points, 1 control point -RLAPI void DrawSplineSegmentBezierCubic(Vector2 p1, Vector2 c2, Vector2 c3, Vector2 p4, float thick, Color color); // Draw spline segment: Cubic Bezier, 2 points, 2 control points - -// Spline segment point evaluation functions, for a given t [0.0f .. 1.0f] -RLAPI Vector2 GetSplinePointLinear(Vector2 startPos, Vector2 endPos, float t); // Get (evaluate) spline point: Linear -RLAPI Vector2 GetSplinePointBasis(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4, float t); // Get (evaluate) spline point: B-Spline -RLAPI Vector2 GetSplinePointCatmullRom(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4, float t); // Get (evaluate) spline point: Catmull-Rom -RLAPI Vector2 GetSplinePointBezierQuad(Vector2 p1, Vector2 c2, Vector2 p3, float t); // Get (evaluate) spline point: Quadratic Bezier -RLAPI Vector2 GetSplinePointBezierCubic(Vector2 p1, Vector2 c2, Vector2 c3, Vector2 p4, float t); // Get (evaluate) spline point: Cubic Bezier - -// Basic shapes collision detection functions -RLAPI bool CheckCollisionRecs(Rectangle rec1, Rectangle rec2); // Check collision between two rectangles -RLAPI bool CheckCollisionCircles(Vector2 center1, float radius1, Vector2 center2, float radius2); // Check collision between two circles -RLAPI bool CheckCollisionCircleRec(Vector2 center, float radius, Rectangle rec); // Check collision between circle and rectangle -RLAPI bool CheckCollisionCircleLine(Vector2 center, float radius, Vector2 p1, Vector2 p2); // Check if circle collides with a line created betweeen two points [p1] and [p2] -RLAPI bool CheckCollisionPointRec(Vector2 point, Rectangle rec); // Check if point is inside rectangle -RLAPI bool CheckCollisionPointCircle(Vector2 point, Vector2 center, float radius); // Check if point is inside circle -RLAPI bool CheckCollisionPointTriangle(Vector2 point, Vector2 p1, Vector2 p2, Vector2 p3); // Check if point is inside a triangle -RLAPI bool CheckCollisionPointLine(Vector2 point, Vector2 p1, Vector2 p2, int threshold); // Check if point belongs to line created between two points [p1] and [p2] with defined margin in pixels [threshold] -RLAPI bool CheckCollisionPointPoly(Vector2 point, const Vector2 *points, int pointCount); // Check if point is within a polygon described by array of vertices -RLAPI bool CheckCollisionLines(Vector2 startPos1, Vector2 endPos1, Vector2 startPos2, Vector2 endPos2, Vector2 *collisionPoint); // Check the collision between two lines defined by two points each, returns collision point by reference -RLAPI Rectangle GetCollisionRec(Rectangle rec1, Rectangle rec2); // Get collision rectangle for two rectangles collision - -//------------------------------------------------------------------------------------ -// Texture Loading and Drawing Functions (Module: textures) -//------------------------------------------------------------------------------------ - -// Image loading functions -// NOTE: These functions do not require GPU access -RLAPI Image LoadImage(const char *fileName); // Load image from file into CPU memory (RAM) -RLAPI Image LoadImageRaw(const char *fileName, int width, int height, int format, int headerSize); // Load image from RAW file data -RLAPI Image LoadImageAnim(const char *fileName, int *frames); // Load image sequence from file (frames appended to image.data) -RLAPI Image LoadImageAnimFromMemory(const char *fileType, const unsigned char *fileData, int dataSize, int *frames); // Load image sequence from memory buffer -RLAPI Image LoadImageFromMemory(const char *fileType, const unsigned char *fileData, int dataSize); // Load image from memory buffer, fileType refers to extension: i.e. '.png' -RLAPI Image LoadImageFromTexture(Texture2D texture); // Load image from GPU texture data -RLAPI Image LoadImageFromScreen(void); // Load image from screen buffer and (screenshot) -RLAPI bool IsImageValid(Image image); // Check if an image is valid (data and parameters) -RLAPI void UnloadImage(Image image); // Unload image from CPU memory (RAM) -RLAPI bool ExportImage(Image image, const char *fileName); // Export image data to file, returns true on success -RLAPI unsigned char *ExportImageToMemory(Image image, const char *fileType, int *fileSize); // Export image to memory buffer -RLAPI bool ExportImageAsCode(Image image, const char *fileName); // Export image as code file defining an array of bytes, returns true on success - -// Image generation functions -RLAPI Image GenImageColor(int width, int height, Color color); // Generate image: plain color -RLAPI Image GenImageGradientLinear(int width, int height, int direction, Color start, Color end); // Generate image: linear gradient, direction in degrees [0..360], 0=Vertical gradient -RLAPI Image GenImageGradientRadial(int width, int height, float density, Color inner, Color outer); // Generate image: radial gradient -RLAPI Image GenImageGradientSquare(int width, int height, float density, Color inner, Color outer); // Generate image: square gradient -RLAPI Image GenImageChecked(int width, int height, int checksX, int checksY, Color col1, Color col2); // Generate image: checked -RLAPI Image GenImageWhiteNoise(int width, int height, float factor); // Generate image: white noise -RLAPI Image GenImagePerlinNoise(int width, int height, int offsetX, int offsetY, float scale); // Generate image: perlin noise -RLAPI Image GenImageCellular(int width, int height, int tileSize); // Generate image: cellular algorithm, bigger tileSize means bigger cells -RLAPI Image GenImageText(int width, int height, const char *text); // Generate image: grayscale image from text data - -// Image manipulation functions -RLAPI Image ImageCopy(Image image); // Create an image duplicate (useful for transformations) -RLAPI Image ImageFromImage(Image image, Rectangle rec); // Create an image from another image piece -RLAPI Image ImageFromChannel(Image image, int selectedChannel); // Create an image from a selected channel of another image (GRAYSCALE) -RLAPI Image ImageText(const char *text, int fontSize, Color color); // Create an image from text (default font) -RLAPI Image ImageTextEx(Font font, const char *text, float fontSize, float spacing, Color tint); // Create an image from text (custom sprite font) -RLAPI void ImageFormat(Image *image, int newFormat); // Convert image data to desired format -RLAPI void ImageToPOT(Image *image, Color fill); // Convert image to POT (power-of-two) -RLAPI void ImageCrop(Image *image, Rectangle crop); // Crop an image to a defined rectangle -RLAPI void ImageAlphaCrop(Image *image, float threshold); // Crop image depending on alpha value -RLAPI void ImageAlphaClear(Image *image, Color color, float threshold); // Clear alpha channel to desired color -RLAPI void ImageAlphaMask(Image *image, Image alphaMask); // Apply alpha mask to image -RLAPI void ImageAlphaPremultiply(Image *image); // Premultiply alpha channel -RLAPI void ImageBlurGaussian(Image *image, int blurSize); // Apply Gaussian blur using a box blur approximation -RLAPI void ImageKernelConvolution(Image *image, const float *kernel, int kernelSize); // Apply custom square convolution kernel to image -RLAPI void ImageResize(Image *image, int newWidth, int newHeight); // Resize image (Bicubic scaling algorithm) -RLAPI void ImageResizeNN(Image *image, int newWidth,int newHeight); // Resize image (Nearest-Neighbor scaling algorithm) -RLAPI void ImageResizeCanvas(Image *image, int newWidth, int newHeight, int offsetX, int offsetY, Color fill); // Resize canvas and fill with color -RLAPI void ImageMipmaps(Image *image); // Compute all mipmap levels for a provided image -RLAPI void ImageDither(Image *image, int rBpp, int gBpp, int bBpp, int aBpp); // Dither image data to 16bpp or lower (Floyd-Steinberg dithering) -RLAPI void ImageFlipVertical(Image *image); // Flip image vertically -RLAPI void ImageFlipHorizontal(Image *image); // Flip image horizontally -RLAPI void ImageRotate(Image *image, int degrees); // Rotate image by input angle in degrees (-359 to 359) -RLAPI void ImageRotateCW(Image *image); // Rotate image clockwise 90deg -RLAPI void ImageRotateCCW(Image *image); // Rotate image counter-clockwise 90deg -RLAPI void ImageColorTint(Image *image, Color color); // Modify image color: tint -RLAPI void ImageColorInvert(Image *image); // Modify image color: invert -RLAPI void ImageColorGrayscale(Image *image); // Modify image color: grayscale -RLAPI void ImageColorContrast(Image *image, float contrast); // Modify image color: contrast (-100 to 100) -RLAPI void ImageColorBrightness(Image *image, int brightness); // Modify image color: brightness (-255 to 255) -RLAPI void ImageColorReplace(Image *image, Color color, Color replace); // Modify image color: replace color -RLAPI Color *LoadImageColors(Image image); // Load color data from image as a Color array (RGBA - 32bit) -RLAPI Color *LoadImagePalette(Image image, int maxPaletteSize, int *colorCount); // Load colors palette from image as a Color array (RGBA - 32bit) -RLAPI void UnloadImageColors(Color *colors); // Unload color data loaded with LoadImageColors() -RLAPI void UnloadImagePalette(Color *colors); // Unload colors palette loaded with LoadImagePalette() -RLAPI Rectangle GetImageAlphaBorder(Image image, float threshold); // Get image alpha border rectangle -RLAPI Color GetImageColor(Image image, int x, int y); // Get image pixel color at (x, y) position - -// Image drawing functions -// NOTE: Image software-rendering functions (CPU) -RLAPI void ImageClearBackground(Image *dst, Color color); // Clear image background with given color -RLAPI void ImageDrawPixel(Image *dst, int posX, int posY, Color color); // Draw pixel within an image -RLAPI void ImageDrawPixelV(Image *dst, Vector2 position, Color color); // Draw pixel within an image (Vector version) -RLAPI void ImageDrawLine(Image *dst, int startPosX, int startPosY, int endPosX, int endPosY, Color color); // Draw line within an image -RLAPI void ImageDrawLineV(Image *dst, Vector2 start, Vector2 end, Color color); // Draw line within an image (Vector version) -RLAPI void ImageDrawLineEx(Image *dst, Vector2 start, Vector2 end, int thick, Color color); // Draw a line defining thickness within an image -RLAPI void ImageDrawCircle(Image *dst, int centerX, int centerY, int radius, Color color); // Draw a filled circle within an image -RLAPI void ImageDrawCircleV(Image *dst, Vector2 center, int radius, Color color); // Draw a filled circle within an image (Vector version) -RLAPI void ImageDrawCircleLines(Image *dst, int centerX, int centerY, int radius, Color color); // Draw circle outline within an image -RLAPI void ImageDrawCircleLinesV(Image *dst, Vector2 center, int radius, Color color); // Draw circle outline within an image (Vector version) -RLAPI void ImageDrawRectangle(Image *dst, int posX, int posY, int width, int height, Color color); // Draw rectangle within an image -RLAPI void ImageDrawRectangleV(Image *dst, Vector2 position, Vector2 size, Color color); // Draw rectangle within an image (Vector version) -RLAPI void ImageDrawRectangleRec(Image *dst, Rectangle rec, Color color); // Draw rectangle within an image -RLAPI void ImageDrawRectangleLines(Image *dst, Rectangle rec, int thick, Color color); // Draw rectangle lines within an image -RLAPI void ImageDrawTriangle(Image *dst, Vector2 v1, Vector2 v2, Vector2 v3, Color color); // Draw triangle within an image -RLAPI void ImageDrawTriangleEx(Image *dst, Vector2 v1, Vector2 v2, Vector2 v3, Color c1, Color c2, Color c3); // Draw triangle with interpolated colors within an image -RLAPI void ImageDrawTriangleLines(Image *dst, Vector2 v1, Vector2 v2, Vector2 v3, Color color); // Draw triangle outline within an image -RLAPI void ImageDrawTriangleFan(Image *dst, Vector2 *points, int pointCount, Color color); // Draw a triangle fan defined by points within an image (first vertex is the center) -RLAPI void ImageDrawTriangleStrip(Image *dst, Vector2 *points, int pointCount, Color color); // Draw a triangle strip defined by points within an image -RLAPI void ImageDraw(Image *dst, Image src, Rectangle srcRec, Rectangle dstRec, Color tint); // Draw a source image within a destination image (tint applied to source) -RLAPI void ImageDrawText(Image *dst, const char *text, int posX, int posY, int fontSize, Color color); // Draw text (using default font) within an image (destination) -RLAPI void ImageDrawTextEx(Image *dst, Font font, const char *text, Vector2 position, float fontSize, float spacing, Color tint); // Draw text (custom sprite font) within an image (destination) - -// Texture loading functions -// NOTE: These functions require GPU access -RLAPI Texture2D LoadTexture(const char *fileName); // Load texture from file into GPU memory (VRAM) -RLAPI Texture2D LoadTextureFromImage(Image image); // Load texture from image data -RLAPI TextureCubemap LoadTextureCubemap(Image image, int layout); // Load cubemap from image, multiple image cubemap layouts supported -RLAPI RenderTexture2D LoadRenderTexture(int width, int height); // Load texture for rendering (framebuffer) -RLAPI bool IsTextureValid(Texture2D texture); // Check if a texture is valid (loaded in GPU) -RLAPI void UnloadTexture(Texture2D texture); // Unload texture from GPU memory (VRAM) -RLAPI bool IsRenderTextureValid(RenderTexture2D target); // Check if a render texture is valid (loaded in GPU) -RLAPI void UnloadRenderTexture(RenderTexture2D target); // Unload render texture from GPU memory (VRAM) -RLAPI void UpdateTexture(Texture2D texture, const void *pixels); // Update GPU texture with new data -RLAPI void UpdateTextureRec(Texture2D texture, Rectangle rec, const void *pixels); // Update GPU texture rectangle with new data - -// Texture configuration functions -RLAPI void GenTextureMipmaps(Texture2D *texture); // Generate GPU mipmaps for a texture -RLAPI void SetTextureFilter(Texture2D texture, int filter); // Set texture scaling filter mode -RLAPI void SetTextureWrap(Texture2D texture, int wrap); // Set texture wrapping mode - -// Texture drawing functions -RLAPI void DrawTexture(Texture2D texture, int posX, int posY, Color tint); // Draw a Texture2D -RLAPI void DrawTextureV(Texture2D texture, Vector2 position, Color tint); // Draw a Texture2D with position defined as Vector2 -RLAPI void DrawTextureEx(Texture2D texture, Vector2 position, float rotation, float scale, Color tint); // Draw a Texture2D with extended parameters -RLAPI void DrawTextureRec(Texture2D texture, Rectangle source, Vector2 position, Color tint); // Draw a part of a texture defined by a rectangle -RLAPI void DrawTexturePro(Texture2D texture, Rectangle source, Rectangle dest, Vector2 origin, float rotation, Color tint); // Draw a part of a texture defined by a rectangle with 'pro' parameters -RLAPI void DrawTextureNPatch(Texture2D texture, NPatchInfo nPatchInfo, Rectangle dest, Vector2 origin, float rotation, Color tint); // Draws a texture (or part of it) that stretches or shrinks nicely - -// Color/pixel related functions -RLAPI bool ColorIsEqual(Color col1, Color col2); // Check if two colors are equal -RLAPI Color Fade(Color color, float alpha); // Get color with alpha applied, alpha goes from 0.0f to 1.0f -RLAPI int ColorToInt(Color color); // Get hexadecimal value for a Color (0xRRGGBBAA) -RLAPI Vector4 ColorNormalize(Color color); // Get Color normalized as float [0..1] -RLAPI Color ColorFromNormalized(Vector4 normalized); // Get Color from normalized values [0..1] -RLAPI Vector3 ColorToHSV(Color color); // Get HSV values for a Color, hue [0..360], saturation/value [0..1] -RLAPI Color ColorFromHSV(float hue, float saturation, float value); // Get a Color from HSV values, hue [0..360], saturation/value [0..1] -RLAPI Color ColorTint(Color color, Color tint); // Get color multiplied with another color -RLAPI Color ColorBrightness(Color color, float factor); // Get color with brightness correction, brightness factor goes from -1.0f to 1.0f -RLAPI Color ColorContrast(Color color, float contrast); // Get color with contrast correction, contrast values between -1.0f and 1.0f -RLAPI Color ColorAlpha(Color color, float alpha); // Get color with alpha applied, alpha goes from 0.0f to 1.0f -RLAPI Color ColorAlphaBlend(Color dst, Color src, Color tint); // Get src alpha-blended into dst color with tint -RLAPI Color ColorLerp(Color color1, Color color2, float factor); // Get color lerp interpolation between two colors, factor [0.0f..1.0f] -RLAPI Color GetColor(unsigned int hexValue); // Get Color structure from hexadecimal value -RLAPI Color GetPixelColor(void *srcPtr, int format); // Get Color from a source pixel pointer of certain format -RLAPI void SetPixelColor(void *dstPtr, Color color, int format); // Set color formatted into destination pixel pointer -RLAPI int GetPixelDataSize(int width, int height, int format); // Get pixel data size in bytes for certain format - -//------------------------------------------------------------------------------------ -// Font Loading and Text Drawing Functions (Module: text) -//------------------------------------------------------------------------------------ - -// Font loading/unloading functions -RLAPI Font GetFontDefault(void); // Get the default Font -RLAPI Font LoadFont(const char *fileName); // Load font from file into GPU memory (VRAM) -RLAPI Font LoadFontEx(const char *fileName, int fontSize, int *codepoints, int codepointCount); // Load font from file with extended parameters, use NULL for codepoints and 0 for codepointCount to load the default character set, font size is provided in pixels height -RLAPI Font LoadFontFromImage(Image image, Color key, int firstChar); // Load font from Image (XNA style) -RLAPI Font LoadFontFromMemory(const char *fileType, const unsigned char *fileData, int dataSize, int fontSize, int *codepoints, int codepointCount); // Load font from memory buffer, fileType refers to extension: i.e. '.ttf' -RLAPI bool IsFontValid(Font font); // Check if a font is valid (font data loaded, WARNING: GPU texture not checked) -RLAPI GlyphInfo *LoadFontData(const unsigned char *fileData, int dataSize, int fontSize, int *codepoints, int codepointCount, int type); // Load font data for further use -RLAPI Image GenImageFontAtlas(const GlyphInfo *glyphs, Rectangle **glyphRecs, int glyphCount, int fontSize, int padding, int packMethod); // Generate image font atlas using chars info -RLAPI void UnloadFontData(GlyphInfo *glyphs, int glyphCount); // Unload font chars info data (RAM) -RLAPI void UnloadFont(Font font); // Unload font from GPU memory (VRAM) -RLAPI bool ExportFontAsCode(Font font, const char *fileName); // Export font as code file, returns true on success - -// Text drawing functions -RLAPI void DrawFPS(int posX, int posY); // Draw current FPS -RLAPI void DrawText(const char *text, int posX, int posY, int fontSize, Color color); // Draw text (using default font) -RLAPI void DrawTextEx(Font font, const char *text, Vector2 position, float fontSize, float spacing, Color tint); // Draw text using font and additional parameters -RLAPI void DrawTextPro(Font font, const char *text, Vector2 position, Vector2 origin, float rotation, float fontSize, float spacing, Color tint); // Draw text using Font and pro parameters (rotation) -RLAPI void DrawTextCodepoint(Font font, int codepoint, Vector2 position, float fontSize, Color tint); // Draw one character (codepoint) -RLAPI void DrawTextCodepoints(Font font, const int *codepoints, int codepointCount, Vector2 position, float fontSize, float spacing, Color tint); // Draw multiple character (codepoint) - -// Text font info functions -RLAPI void SetTextLineSpacing(int spacing); // Set vertical line spacing when drawing with line-breaks -RLAPI int MeasureText(const char *text, int fontSize); // Measure string width for default font -RLAPI Vector2 MeasureTextEx(Font font, const char *text, float fontSize, float spacing); // Measure string size for Font -RLAPI int GetGlyphIndex(Font font, int codepoint); // Get glyph index position in font for a codepoint (unicode character), fallback to '?' if not found -RLAPI GlyphInfo GetGlyphInfo(Font font, int codepoint); // Get glyph font info data for a codepoint (unicode character), fallback to '?' if not found -RLAPI Rectangle GetGlyphAtlasRec(Font font, int codepoint); // Get glyph rectangle in font atlas for a codepoint (unicode character), fallback to '?' if not found - -// Text codepoints management functions (unicode characters) -RLAPI char *LoadUTF8(const int *codepoints, int length); // Load UTF-8 text encoded from codepoints array -RLAPI void UnloadUTF8(char *text); // Unload UTF-8 text encoded from codepoints array -RLAPI int *LoadCodepoints(const char *text, int *count); // Load all codepoints from a UTF-8 text string, codepoints count returned by parameter -RLAPI void UnloadCodepoints(int *codepoints); // Unload codepoints data from memory -RLAPI int GetCodepointCount(const char *text); // Get total number of codepoints in a UTF-8 encoded string -RLAPI int GetCodepoint(const char *text, int *codepointSize); // Get next codepoint in a UTF-8 encoded string, 0x3f('?') is returned on failure -RLAPI int GetCodepointNext(const char *text, int *codepointSize); // Get next codepoint in a UTF-8 encoded string, 0x3f('?') is returned on failure -RLAPI int GetCodepointPrevious(const char *text, int *codepointSize); // Get previous codepoint in a UTF-8 encoded string, 0x3f('?') is returned on failure -RLAPI const char *CodepointToUTF8(int codepoint, int *utf8Size); // Encode one codepoint into UTF-8 byte array (array length returned as parameter) - -// Text strings management functions (no UTF-8 strings, only byte chars) -// NOTE: Some strings allocate memory internally for returned strings, just be careful! -RLAPI int TextCopy(char *dst, const char *src); // Copy one string to another, returns bytes copied -RLAPI bool TextIsEqual(const char *text1, const char *text2); // Check if two text string are equal -RLAPI unsigned int TextLength(const char *text); // Get text length, checks for '\0' ending -RLAPI const char *TextFormat(const char *text, ...); // Text formatting with variables (sprintf() style) -RLAPI const char *TextSubtext(const char *text, int position, int length); // Get a piece of a text string -RLAPI char *TextReplace(const char *text, const char *replace, const char *by); // Replace text string (WARNING: memory must be freed!) -RLAPI char *TextInsert(const char *text, const char *insert, int position); // Insert text in a position (WARNING: memory must be freed!) -RLAPI const char *TextJoin(const char **textList, int count, const char *delimiter); // Join text strings with delimiter -RLAPI const char **TextSplit(const char *text, char delimiter, int *count); // Split text into multiple strings -RLAPI void TextAppend(char *text, const char *append, int *position); // Append text at specific position and move cursor! -RLAPI int TextFindIndex(const char *text, const char *find); // Find first text occurrence within a string -RLAPI const char *TextToUpper(const char *text); // Get upper case version of provided string -RLAPI const char *TextToLower(const char *text); // Get lower case version of provided string -RLAPI const char *TextToPascal(const char *text); // Get Pascal case notation version of provided string -RLAPI const char *TextToSnake(const char *text); // Get Snake case notation version of provided string -RLAPI const char *TextToCamel(const char *text); // Get Camel case notation version of provided string - -RLAPI int TextToInteger(const char *text); // Get integer value from text (negative values not supported) -RLAPI float TextToFloat(const char *text); // Get float value from text (negative values not supported) - -//------------------------------------------------------------------------------------ -// Basic 3d Shapes Drawing Functions (Module: models) -//------------------------------------------------------------------------------------ - -// Basic geometric 3D shapes drawing functions -RLAPI void DrawLine3D(Vector3 startPos, Vector3 endPos, Color color); // Draw a line in 3D world space -RLAPI void DrawPoint3D(Vector3 position, Color color); // Draw a point in 3D space, actually a small line -RLAPI void DrawCircle3D(Vector3 center, float radius, Vector3 rotationAxis, float rotationAngle, Color color); // Draw a circle in 3D world space -RLAPI void DrawTriangle3D(Vector3 v1, Vector3 v2, Vector3 v3, Color color); // Draw a color-filled triangle (vertex in counter-clockwise order!) -RLAPI void DrawTriangleStrip3D(const Vector3 *points, int pointCount, Color color); // Draw a triangle strip defined by points -RLAPI void DrawCube(Vector3 position, float width, float height, float length, Color color); // Draw cube -RLAPI void DrawCubeV(Vector3 position, Vector3 size, Color color); // Draw cube (Vector version) -RLAPI void DrawCubeWires(Vector3 position, float width, float height, float length, Color color); // Draw cube wires -RLAPI void DrawCubeWiresV(Vector3 position, Vector3 size, Color color); // Draw cube wires (Vector version) -RLAPI void DrawSphere(Vector3 centerPos, float radius, Color color); // Draw sphere -RLAPI void DrawSphereEx(Vector3 centerPos, float radius, int rings, int slices, Color color); // Draw sphere with extended parameters -RLAPI void DrawSphereWires(Vector3 centerPos, float radius, int rings, int slices, Color color); // Draw sphere wires -RLAPI void DrawCylinder(Vector3 position, float radiusTop, float radiusBottom, float height, int slices, Color color); // Draw a cylinder/cone -RLAPI void DrawCylinderEx(Vector3 startPos, Vector3 endPos, float startRadius, float endRadius, int sides, Color color); // Draw a cylinder with base at startPos and top at endPos -RLAPI void DrawCylinderWires(Vector3 position, float radiusTop, float radiusBottom, float height, int slices, Color color); // Draw a cylinder/cone wires -RLAPI void DrawCylinderWiresEx(Vector3 startPos, Vector3 endPos, float startRadius, float endRadius, int sides, Color color); // Draw a cylinder wires with base at startPos and top at endPos -RLAPI void DrawCapsule(Vector3 startPos, Vector3 endPos, float radius, int slices, int rings, Color color); // Draw a capsule with the center of its sphere caps at startPos and endPos -RLAPI void DrawCapsuleWires(Vector3 startPos, Vector3 endPos, float radius, int slices, int rings, Color color); // Draw capsule wireframe with the center of its sphere caps at startPos and endPos -RLAPI void DrawPlane(Vector3 centerPos, Vector2 size, Color color); // Draw a plane XZ -RLAPI void DrawRay(Ray ray, Color color); // Draw a ray line -RLAPI void DrawGrid(int slices, float spacing); // Draw a grid (centered at (0, 0, 0)) - -//------------------------------------------------------------------------------------ -// Model 3d Loading and Drawing Functions (Module: models) -//------------------------------------------------------------------------------------ - -// Model management functions -RLAPI Model LoadModel(const char *fileName); // Load model from files (meshes and materials) -RLAPI Model LoadModelFromMesh(Mesh mesh); // Load model from generated mesh (default material) -RLAPI bool IsModelValid(Model model); // Check if a model is valid (loaded in GPU, VAO/VBOs) -RLAPI void UnloadModel(Model model); // Unload model (including meshes) from memory (RAM and/or VRAM) -RLAPI BoundingBox GetModelBoundingBox(Model model); // Compute model bounding box limits (considers all meshes) - -// Model drawing functions -RLAPI void DrawModel(Model model, Vector3 position, float scale, Color tint); // Draw a model (with texture if set) -RLAPI void DrawModelEx(Model model, Vector3 position, Vector3 rotationAxis, float rotationAngle, Vector3 scale, Color tint); // Draw a model with extended parameters -RLAPI void DrawModelWires(Model model, Vector3 position, float scale, Color tint); // Draw a model wires (with texture if set) -RLAPI void DrawModelWiresEx(Model model, Vector3 position, Vector3 rotationAxis, float rotationAngle, Vector3 scale, Color tint); // Draw a model wires (with texture if set) with extended parameters -RLAPI void DrawModelPoints(Model model, Vector3 position, float scale, Color tint); // Draw a model as points -RLAPI void DrawModelPointsEx(Model model, Vector3 position, Vector3 rotationAxis, float rotationAngle, Vector3 scale, Color tint); // Draw a model as points with extended parameters -RLAPI void DrawBoundingBox(BoundingBox box, Color color); // Draw bounding box (wires) -RLAPI void DrawBillboard(Camera camera, Texture2D texture, Vector3 position, float scale, Color tint); // Draw a billboard texture -RLAPI void DrawBillboardRec(Camera camera, Texture2D texture, Rectangle source, Vector3 position, Vector2 size, Color tint); // Draw a billboard texture defined by source -RLAPI void DrawBillboardPro(Camera camera, Texture2D texture, Rectangle source, Vector3 position, Vector3 up, Vector2 size, Vector2 origin, float rotation, Color tint); // Draw a billboard texture defined by source and rotation - -// Mesh management functions -RLAPI void UploadMesh(Mesh *mesh, bool dynamic); // Upload mesh vertex data in GPU and provide VAO/VBO ids -RLAPI void UpdateMeshBuffer(Mesh mesh, int index, const void *data, int dataSize, int offset); // Update mesh vertex data in GPU for a specific buffer index -RLAPI void UnloadMesh(Mesh mesh); // Unload mesh data from CPU and GPU -RLAPI void DrawMesh(Mesh mesh, Material material, Matrix transform); // Draw a 3d mesh with material and transform -RLAPI void DrawMeshInstanced(Mesh mesh, Material material, const Matrix *transforms, int instances); // Draw multiple mesh instances with material and different transforms -RLAPI BoundingBox GetMeshBoundingBox(Mesh mesh); // Compute mesh bounding box limits -RLAPI void GenMeshTangents(Mesh *mesh); // Compute mesh tangents -RLAPI bool ExportMesh(Mesh mesh, const char *fileName); // Export mesh data to file, returns true on success -RLAPI bool ExportMeshAsCode(Mesh mesh, const char *fileName); // Export mesh as code file (.h) defining multiple arrays of vertex attributes - -// Mesh generation functions -RLAPI Mesh GenMeshPoly(int sides, float radius); // Generate polygonal mesh -RLAPI Mesh GenMeshPlane(float width, float length, int resX, int resZ); // Generate plane mesh (with subdivisions) -RLAPI Mesh GenMeshCube(float width, float height, float length); // Generate cuboid mesh -RLAPI Mesh GenMeshSphere(float radius, int rings, int slices); // Generate sphere mesh (standard sphere) -RLAPI Mesh GenMeshHemiSphere(float radius, int rings, int slices); // Generate half-sphere mesh (no bottom cap) -RLAPI Mesh GenMeshCylinder(float radius, float height, int slices); // Generate cylinder mesh -RLAPI Mesh GenMeshCone(float radius, float height, int slices); // Generate cone/pyramid mesh -RLAPI Mesh GenMeshTorus(float radius, float size, int radSeg, int sides); // Generate torus mesh -RLAPI Mesh GenMeshKnot(float radius, float size, int radSeg, int sides); // Generate trefoil knot mesh -RLAPI Mesh GenMeshHeightmap(Image heightmap, Vector3 size); // Generate heightmap mesh from image data -RLAPI Mesh GenMeshCubicmap(Image cubicmap, Vector3 cubeSize); // Generate cubes-based map mesh from image data - -// Material loading/unloading functions -RLAPI Material *LoadMaterials(const char *fileName, int *materialCount); // Load materials from model file -RLAPI Material LoadMaterialDefault(void); // Load default material (Supports: DIFFUSE, SPECULAR, NORMAL maps) -RLAPI bool IsMaterialValid(Material material); // Check if a material is valid (shader assigned, map textures loaded in GPU) -RLAPI void UnloadMaterial(Material material); // Unload material from GPU memory (VRAM) -RLAPI void SetMaterialTexture(Material *material, int mapType, Texture2D texture); // Set texture for a material map type (MATERIAL_MAP_DIFFUSE, MATERIAL_MAP_SPECULAR...) -RLAPI void SetModelMeshMaterial(Model *model, int meshId, int materialId); // Set material for a mesh - -// Model animations loading/unloading functions -RLAPI ModelAnimation *LoadModelAnimations(const char *fileName, int *animCount); // Load model animations from file -RLAPI void UpdateModelAnimation(Model model, ModelAnimation anim, int frame); // Update model animation pose (CPU) -RLAPI void UpdateModelAnimationBones(Model model, ModelAnimation anim, int frame); // Update model animation mesh bone matrices (GPU skinning) -RLAPI void UnloadModelAnimation(ModelAnimation anim); // Unload animation data -RLAPI void UnloadModelAnimations(ModelAnimation *animations, int animCount); // Unload animation array data -RLAPI bool IsModelAnimationValid(Model model, ModelAnimation anim); // Check model animation skeleton match - -// Collision detection functions -RLAPI bool CheckCollisionSpheres(Vector3 center1, float radius1, Vector3 center2, float radius2); // Check collision between two spheres -RLAPI bool CheckCollisionBoxes(BoundingBox box1, BoundingBox box2); // Check collision between two bounding boxes -RLAPI bool CheckCollisionBoxSphere(BoundingBox box, Vector3 center, float radius); // Check collision between box and sphere -RLAPI RayCollision GetRayCollisionSphere(Ray ray, Vector3 center, float radius); // Get collision info between ray and sphere -RLAPI RayCollision GetRayCollisionBox(Ray ray, BoundingBox box); // Get collision info between ray and box -RLAPI RayCollision GetRayCollisionMesh(Ray ray, Mesh mesh, Matrix transform); // Get collision info between ray and mesh -RLAPI RayCollision GetRayCollisionTriangle(Ray ray, Vector3 p1, Vector3 p2, Vector3 p3); // Get collision info between ray and triangle -RLAPI RayCollision GetRayCollisionQuad(Ray ray, Vector3 p1, Vector3 p2, Vector3 p3, Vector3 p4); // Get collision info between ray and quad - -//------------------------------------------------------------------------------------ -// Audio Loading and Playing Functions (Module: audio) -//------------------------------------------------------------------------------------ -typedef void (*AudioCallback)(void *bufferData, unsigned int frames); - -// Audio device management functions -RLAPI void InitAudioDevice(void); // Initialize audio device and context -RLAPI void CloseAudioDevice(void); // Close the audio device and context -RLAPI bool IsAudioDeviceReady(void); // Check if audio device has been initialized successfully -RLAPI void SetMasterVolume(float volume); // Set master volume (listener) -RLAPI float GetMasterVolume(void); // Get master volume (listener) - -// Wave/Sound loading/unloading functions -RLAPI Wave LoadWave(const char *fileName); // Load wave data from file -RLAPI Wave LoadWaveFromMemory(const char *fileType, const unsigned char *fileData, int dataSize); // Load wave from memory buffer, fileType refers to extension: i.e. '.wav' -RLAPI bool IsWaveValid(Wave wave); // Checks if wave data is valid (data loaded and parameters) -RLAPI Sound LoadSound(const char *fileName); // Load sound from file -RLAPI Sound LoadSoundFromWave(Wave wave); // Load sound from wave data -RLAPI Sound LoadSoundAlias(Sound source); // Create a new sound that shares the same sample data as the source sound, does not own the sound data -RLAPI bool IsSoundValid(Sound sound); // Checks if a sound is valid (data loaded and buffers initialized) -RLAPI void UpdateSound(Sound sound, const void *data, int sampleCount); // Update sound buffer with new data -RLAPI void UnloadWave(Wave wave); // Unload wave data -RLAPI void UnloadSound(Sound sound); // Unload sound -RLAPI void UnloadSoundAlias(Sound alias); // Unload a sound alias (does not deallocate sample data) -RLAPI bool ExportWave(Wave wave, const char *fileName); // Export wave data to file, returns true on success -RLAPI bool ExportWaveAsCode(Wave wave, const char *fileName); // Export wave sample data to code (.h), returns true on success - -// Wave/Sound management functions -RLAPI void PlaySound(Sound sound); // Play a sound -RLAPI void StopSound(Sound sound); // Stop playing a sound -RLAPI void PauseSound(Sound sound); // Pause a sound -RLAPI void ResumeSound(Sound sound); // Resume a paused sound -RLAPI bool IsSoundPlaying(Sound sound); // Check if a sound is currently playing -RLAPI void SetSoundVolume(Sound sound, float volume); // Set volume for a sound (1.0 is max level) -RLAPI void SetSoundPitch(Sound sound, float pitch); // Set pitch for a sound (1.0 is base level) -RLAPI void SetSoundPan(Sound sound, float pan); // Set pan for a sound (0.5 is center) -RLAPI Wave WaveCopy(Wave wave); // Copy a wave to a new wave -RLAPI void WaveCrop(Wave *wave, int initFrame, int finalFrame); // Crop a wave to defined frames range -RLAPI void WaveFormat(Wave *wave, int sampleRate, int sampleSize, int channels); // Convert wave data to desired format -RLAPI float *LoadWaveSamples(Wave wave); // Load samples data from wave as a 32bit float data array -RLAPI void UnloadWaveSamples(float *samples); // Unload samples data loaded with LoadWaveSamples() - -// Music management functions -RLAPI Music LoadMusicStream(const char *fileName); // Load music stream from file -RLAPI Music LoadMusicStreamFromMemory(const char *fileType, const unsigned char *data, int dataSize); // Load music stream from data -RLAPI bool IsMusicValid(Music music); // Checks if a music stream is valid (context and buffers initialized) -RLAPI void UnloadMusicStream(Music music); // Unload music stream -RLAPI void PlayMusicStream(Music music); // Start music playing -RLAPI bool IsMusicStreamPlaying(Music music); // Check if music is playing -RLAPI void UpdateMusicStream(Music music); // Updates buffers for music streaming -RLAPI void StopMusicStream(Music music); // Stop music playing -RLAPI void PauseMusicStream(Music music); // Pause music playing -RLAPI void ResumeMusicStream(Music music); // Resume playing paused music -RLAPI void SeekMusicStream(Music music, float position); // Seek music to a position (in seconds) -RLAPI void SetMusicVolume(Music music, float volume); // Set volume for music (1.0 is max level) -RLAPI void SetMusicPitch(Music music, float pitch); // Set pitch for a music (1.0 is base level) -RLAPI void SetMusicPan(Music music, float pan); // Set pan for a music (0.5 is center) -RLAPI float GetMusicTimeLength(Music music); // Get music time length (in seconds) -RLAPI float GetMusicTimePlayed(Music music); // Get current music time played (in seconds) - -// AudioStream management functions -RLAPI AudioStream LoadAudioStream(unsigned int sampleRate, unsigned int sampleSize, unsigned int channels); // Load audio stream (to stream raw audio pcm data) -RLAPI bool IsAudioStreamValid(AudioStream stream); // Checks if an audio stream is valid (buffers initialized) -RLAPI void UnloadAudioStream(AudioStream stream); // Unload audio stream and free memory -RLAPI void UpdateAudioStream(AudioStream stream, const void *data, int frameCount); // Update audio stream buffers with data -RLAPI bool IsAudioStreamProcessed(AudioStream stream); // Check if any audio stream buffers requires refill -RLAPI void PlayAudioStream(AudioStream stream); // Play audio stream -RLAPI void PauseAudioStream(AudioStream stream); // Pause audio stream -RLAPI void ResumeAudioStream(AudioStream stream); // Resume audio stream -RLAPI bool IsAudioStreamPlaying(AudioStream stream); // Check if audio stream is playing -RLAPI void StopAudioStream(AudioStream stream); // Stop audio stream -RLAPI void SetAudioStreamVolume(AudioStream stream, float volume); // Set volume for audio stream (1.0 is max level) -RLAPI void SetAudioStreamPitch(AudioStream stream, float pitch); // Set pitch for audio stream (1.0 is base level) -RLAPI void SetAudioStreamPan(AudioStream stream, float pan); // Set pan for audio stream (0.5 is centered) -RLAPI void SetAudioStreamBufferSizeDefault(int size); // Default size for new audio streams -RLAPI void SetAudioStreamCallback(AudioStream stream, AudioCallback callback); // Audio thread callback to request new data - -RLAPI void AttachAudioStreamProcessor(AudioStream stream, AudioCallback processor); // Attach audio stream processor to stream, receives the samples as 'float' -RLAPI void DetachAudioStreamProcessor(AudioStream stream, AudioCallback processor); // Detach audio stream processor from stream - -RLAPI void AttachAudioMixedProcessor(AudioCallback processor); // Attach audio stream processor to the entire audio pipeline, receives the samples as 'float' -RLAPI void DetachAudioMixedProcessor(AudioCallback processor); // Detach audio stream processor from the entire audio pipeline - -#if defined(__cplusplus) -} -#endif - -#endif // RAYLIB_H diff --git a/third_party/raylib/include/raymath.h b/third_party/raylib/include/raymath.h deleted file mode 100644 index 5b5e4c74ff..0000000000 --- a/third_party/raylib/include/raymath.h +++ /dev/null @@ -1,2949 +0,0 @@ -/********************************************************************************************** -* -* raymath v2.0 - Math functions to work with Vector2, Vector3, Matrix and Quaternions -* -* CONVENTIONS: -* - Matrix structure is defined as row-major (memory layout) but parameters naming AND all -* math operations performed by the library consider the structure as it was column-major -* It is like transposed versions of the matrices are used for all the maths -* It benefits some functions making them cache-friendly and also avoids matrix -* transpositions sometimes required by OpenGL -* Example: In memory order, row0 is [m0 m4 m8 m12] but in semantic math row0 is [m0 m1 m2 m3] -* - Functions are always self-contained, no function use another raymath function inside, -* required code is directly re-implemented inside -* - Functions input parameters are always received by value (2 unavoidable exceptions) -* - Functions use always a "result" variable for return (except C++ operators) -* - Functions are always defined inline -* - Angles are always in radians (DEG2RAD/RAD2DEG macros provided for convenience) -* - No compound literals used to make sure libray is compatible with C++ -* -* CONFIGURATION: -* #define RAYMATH_IMPLEMENTATION -* Generates the implementation of the library into the included file. -* If not defined, the library is in header only mode and can be included in other headers -* or source files without problems. But only ONE file should hold the implementation. -* -* #define RAYMATH_STATIC_INLINE -* Define static inline functions code, so #include header suffices for use. -* This may use up lots of memory. -* -* #define RAYMATH_DISABLE_CPP_OPERATORS -* Disables C++ operator overloads for raymath types. -* -* LICENSE: zlib/libpng -* -* Copyright (c) 2015-2024 Ramon Santamaria (@raysan5) -* -* This software is provided "as-is", without any express or implied warranty. In no event -* will the authors be held liable for any damages arising from the use of this software. -* -* Permission is granted to anyone to use this software for any purpose, including commercial -* applications, and to alter it and redistribute it freely, subject to the following restrictions: -* -* 1. The origin of this software must not be misrepresented; you must not claim that you -* wrote the original software. If you use this software in a product, an acknowledgment -* in the product documentation would be appreciated but is not required. -* -* 2. Altered source versions must be plainly marked as such, and must not be misrepresented -* as being the original software. -* -* 3. This notice may not be removed or altered from any source distribution. -* -**********************************************************************************************/ - -#ifndef RAYMATH_H -#define RAYMATH_H - -#if defined(RAYMATH_IMPLEMENTATION) && defined(RAYMATH_STATIC_INLINE) - #error "Specifying both RAYMATH_IMPLEMENTATION and RAYMATH_STATIC_INLINE is contradictory" -#endif - -// Function specifiers definition -#if defined(RAYMATH_IMPLEMENTATION) - #if defined(_WIN32) && defined(BUILD_LIBTYPE_SHARED) - #define RMAPI __declspec(dllexport) extern inline // We are building raylib as a Win32 shared library (.dll) - #elif defined(BUILD_LIBTYPE_SHARED) - #define RMAPI __attribute__((visibility("default"))) // We are building raylib as a Unix shared library (.so/.dylib) - #elif defined(_WIN32) && defined(USE_LIBTYPE_SHARED) - #define RMAPI __declspec(dllimport) // We are using raylib as a Win32 shared library (.dll) - #else - #define RMAPI extern inline // Provide external definition - #endif -#elif defined(RAYMATH_STATIC_INLINE) - #define RMAPI static inline // Functions may be inlined, no external out-of-line definition -#else - #if defined(__TINYC__) - #define RMAPI static inline // plain inline not supported by tinycc (See issue #435) - #else - #define RMAPI inline // Functions may be inlined or external definition used - #endif -#endif - - -//---------------------------------------------------------------------------------- -// Defines and Macros -//---------------------------------------------------------------------------------- -#ifndef PI - #define PI 3.14159265358979323846f -#endif - -#ifndef EPSILON - #define EPSILON 0.000001f -#endif - -#ifndef DEG2RAD - #define DEG2RAD (PI/180.0f) -#endif - -#ifndef RAD2DEG - #define RAD2DEG (180.0f/PI) -#endif - -// Get float vector for Matrix -#ifndef MatrixToFloat - #define MatrixToFloat(mat) (MatrixToFloatV(mat).v) -#endif - -// Get float vector for Vector3 -#ifndef Vector3ToFloat - #define Vector3ToFloat(vec) (Vector3ToFloatV(vec).v) -#endif - -//---------------------------------------------------------------------------------- -// Types and Structures Definition -//---------------------------------------------------------------------------------- -#if !defined(RL_VECTOR2_TYPE) -// Vector2 type -typedef struct Vector2 { - float x; - float y; -} Vector2; -#define RL_VECTOR2_TYPE -#endif - -#if !defined(RL_VECTOR3_TYPE) -// Vector3 type -typedef struct Vector3 { - float x; - float y; - float z; -} Vector3; -#define RL_VECTOR3_TYPE -#endif - -#if !defined(RL_VECTOR4_TYPE) -// Vector4 type -typedef struct Vector4 { - float x; - float y; - float z; - float w; -} Vector4; -#define RL_VECTOR4_TYPE -#endif - -#if !defined(RL_QUATERNION_TYPE) -// Quaternion type -typedef Vector4 Quaternion; -#define RL_QUATERNION_TYPE -#endif - -#if !defined(RL_MATRIX_TYPE) -// Matrix type (OpenGL style 4x4 - right handed, column major) -typedef struct Matrix { - float m0, m4, m8, m12; // Matrix first row (4 components) - float m1, m5, m9, m13; // Matrix second row (4 components) - float m2, m6, m10, m14; // Matrix third row (4 components) - float m3, m7, m11, m15; // Matrix fourth row (4 components) -} Matrix; -#define RL_MATRIX_TYPE -#endif - -// NOTE: Helper types to be used instead of array return types for *ToFloat functions -typedef struct float3 { - float v[3]; -} float3; - -typedef struct float16 { - float v[16]; -} float16; - -#include // Required for: sinf(), cosf(), tan(), atan2f(), sqrtf(), floor(), fminf(), fmaxf(), fabsf() - -//---------------------------------------------------------------------------------- -// Module Functions Definition - Utils math -//---------------------------------------------------------------------------------- - -// Clamp float value -RMAPI float Clamp(float value, float min, float max) -{ - float result = (value < min)? min : value; - - if (result > max) result = max; - - return result; -} - -// Calculate linear interpolation between two floats -RMAPI float Lerp(float start, float end, float amount) -{ - float result = start + amount*(end - start); - - return result; -} - -// Normalize input value within input range -RMAPI float Normalize(float value, float start, float end) -{ - float result = (value - start)/(end - start); - - return result; -} - -// Remap input value within input range to output range -RMAPI float Remap(float value, float inputStart, float inputEnd, float outputStart, float outputEnd) -{ - float result = (value - inputStart)/(inputEnd - inputStart)*(outputEnd - outputStart) + outputStart; - - return result; -} - -// Wrap input value from min to max -RMAPI float Wrap(float value, float min, float max) -{ - float result = value - (max - min)*floorf((value - min)/(max - min)); - - return result; -} - -// Check whether two given floats are almost equal -RMAPI int FloatEquals(float x, float y) -{ -#if !defined(EPSILON) - #define EPSILON 0.000001f -#endif - - int result = (fabsf(x - y)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(x), fabsf(y)))); - - return result; -} - -//---------------------------------------------------------------------------------- -// Module Functions Definition - Vector2 math -//---------------------------------------------------------------------------------- - -// Vector with components value 0.0f -RMAPI Vector2 Vector2Zero(void) -{ - Vector2 result = { 0.0f, 0.0f }; - - return result; -} - -// Vector with components value 1.0f -RMAPI Vector2 Vector2One(void) -{ - Vector2 result = { 1.0f, 1.0f }; - - return result; -} - -// Add two vectors (v1 + v2) -RMAPI Vector2 Vector2Add(Vector2 v1, Vector2 v2) -{ - Vector2 result = { v1.x + v2.x, v1.y + v2.y }; - - return result; -} - -// Add vector and float value -RMAPI Vector2 Vector2AddValue(Vector2 v, float add) -{ - Vector2 result = { v.x + add, v.y + add }; - - return result; -} - -// Subtract two vectors (v1 - v2) -RMAPI Vector2 Vector2Subtract(Vector2 v1, Vector2 v2) -{ - Vector2 result = { v1.x - v2.x, v1.y - v2.y }; - - return result; -} - -// Subtract vector by float value -RMAPI Vector2 Vector2SubtractValue(Vector2 v, float sub) -{ - Vector2 result = { v.x - sub, v.y - sub }; - - return result; -} - -// Calculate vector length -RMAPI float Vector2Length(Vector2 v) -{ - float result = sqrtf((v.x*v.x) + (v.y*v.y)); - - return result; -} - -// Calculate vector square length -RMAPI float Vector2LengthSqr(Vector2 v) -{ - float result = (v.x*v.x) + (v.y*v.y); - - return result; -} - -// Calculate two vectors dot product -RMAPI float Vector2DotProduct(Vector2 v1, Vector2 v2) -{ - float result = (v1.x*v2.x + v1.y*v2.y); - - return result; -} - -// Calculate two vectors cross product -RMAPI float Vector2CrossProduct(Vector2 v1, Vector2 v2) -{ - float result = (v1.x*v2.y - v1.y*v2.x); - - return result; -} - -// Calculate distance between two vectors -RMAPI float Vector2Distance(Vector2 v1, Vector2 v2) -{ - float result = sqrtf((v1.x - v2.x)*(v1.x - v2.x) + (v1.y - v2.y)*(v1.y - v2.y)); - - return result; -} - -// Calculate square distance between two vectors -RMAPI float Vector2DistanceSqr(Vector2 v1, Vector2 v2) -{ - float result = ((v1.x - v2.x)*(v1.x - v2.x) + (v1.y - v2.y)*(v1.y - v2.y)); - - return result; -} - -// Calculate angle between two vectors -// NOTE: Angle is calculated from origin point (0, 0) -RMAPI float Vector2Angle(Vector2 v1, Vector2 v2) -{ - float result = 0.0f; - - float dot = v1.x*v2.x + v1.y*v2.y; - float det = v1.x*v2.y - v1.y*v2.x; - - result = atan2f(det, dot); - - return result; -} - -// Calculate angle defined by a two vectors line -// NOTE: Parameters need to be normalized -// Current implementation should be aligned with glm::angle -RMAPI float Vector2LineAngle(Vector2 start, Vector2 end) -{ - float result = 0.0f; - - // TODO(10/9/2023): Currently angles move clockwise, determine if this is wanted behavior - result = -atan2f(end.y - start.y, end.x - start.x); - - return result; -} - -// Scale vector (multiply by value) -RMAPI Vector2 Vector2Scale(Vector2 v, float scale) -{ - Vector2 result = { v.x*scale, v.y*scale }; - - return result; -} - -// Multiply vector by vector -RMAPI Vector2 Vector2Multiply(Vector2 v1, Vector2 v2) -{ - Vector2 result = { v1.x*v2.x, v1.y*v2.y }; - - return result; -} - -// Negate vector -RMAPI Vector2 Vector2Negate(Vector2 v) -{ - Vector2 result = { -v.x, -v.y }; - - return result; -} - -// Divide vector by vector -RMAPI Vector2 Vector2Divide(Vector2 v1, Vector2 v2) -{ - Vector2 result = { v1.x/v2.x, v1.y/v2.y }; - - return result; -} - -// Normalize provided vector -RMAPI Vector2 Vector2Normalize(Vector2 v) -{ - Vector2 result = { 0 }; - float length = sqrtf((v.x*v.x) + (v.y*v.y)); - - if (length > 0) - { - float ilength = 1.0f/length; - result.x = v.x*ilength; - result.y = v.y*ilength; - } - - return result; -} - -// Transforms a Vector2 by a given Matrix -RMAPI Vector2 Vector2Transform(Vector2 v, Matrix mat) -{ - Vector2 result = { 0 }; - - float x = v.x; - float y = v.y; - float z = 0; - - result.x = mat.m0*x + mat.m4*y + mat.m8*z + mat.m12; - result.y = mat.m1*x + mat.m5*y + mat.m9*z + mat.m13; - - return result; -} - -// Calculate linear interpolation between two vectors -RMAPI Vector2 Vector2Lerp(Vector2 v1, Vector2 v2, float amount) -{ - Vector2 result = { 0 }; - - result.x = v1.x + amount*(v2.x - v1.x); - result.y = v1.y + amount*(v2.y - v1.y); - - return result; -} - -// Calculate reflected vector to normal -RMAPI Vector2 Vector2Reflect(Vector2 v, Vector2 normal) -{ - Vector2 result = { 0 }; - - float dotProduct = (v.x*normal.x + v.y*normal.y); // Dot product - - result.x = v.x - (2.0f*normal.x)*dotProduct; - result.y = v.y - (2.0f*normal.y)*dotProduct; - - return result; -} - -// Get min value for each pair of components -RMAPI Vector2 Vector2Min(Vector2 v1, Vector2 v2) -{ - Vector2 result = { 0 }; - - result.x = fminf(v1.x, v2.x); - result.y = fminf(v1.y, v2.y); - - return result; -} - -// Get max value for each pair of components -RMAPI Vector2 Vector2Max(Vector2 v1, Vector2 v2) -{ - Vector2 result = { 0 }; - - result.x = fmaxf(v1.x, v2.x); - result.y = fmaxf(v1.y, v2.y); - - return result; -} - -// Rotate vector by angle -RMAPI Vector2 Vector2Rotate(Vector2 v, float angle) -{ - Vector2 result = { 0 }; - - float cosres = cosf(angle); - float sinres = sinf(angle); - - result.x = v.x*cosres - v.y*sinres; - result.y = v.x*sinres + v.y*cosres; - - return result; -} - -// Move Vector towards target -RMAPI Vector2 Vector2MoveTowards(Vector2 v, Vector2 target, float maxDistance) -{ - Vector2 result = { 0 }; - - float dx = target.x - v.x; - float dy = target.y - v.y; - float value = (dx*dx) + (dy*dy); - - if ((value == 0) || ((maxDistance >= 0) && (value <= maxDistance*maxDistance))) return target; - - float dist = sqrtf(value); - - result.x = v.x + dx/dist*maxDistance; - result.y = v.y + dy/dist*maxDistance; - - return result; -} - -// Invert the given vector -RMAPI Vector2 Vector2Invert(Vector2 v) -{ - Vector2 result = { 1.0f/v.x, 1.0f/v.y }; - - return result; -} - -// Clamp the components of the vector between -// min and max values specified by the given vectors -RMAPI Vector2 Vector2Clamp(Vector2 v, Vector2 min, Vector2 max) -{ - Vector2 result = { 0 }; - - result.x = fminf(max.x, fmaxf(min.x, v.x)); - result.y = fminf(max.y, fmaxf(min.y, v.y)); - - return result; -} - -// Clamp the magnitude of the vector between two min and max values -RMAPI Vector2 Vector2ClampValue(Vector2 v, float min, float max) -{ - Vector2 result = v; - - float length = (v.x*v.x) + (v.y*v.y); - if (length > 0.0f) - { - length = sqrtf(length); - - float scale = 1; // By default, 1 as the neutral element. - if (length < min) - { - scale = min/length; - } - else if (length > max) - { - scale = max/length; - } - - result.x = v.x*scale; - result.y = v.y*scale; - } - - return result; -} - -// Check whether two given vectors are almost equal -RMAPI int Vector2Equals(Vector2 p, Vector2 q) -{ -#if !defined(EPSILON) - #define EPSILON 0.000001f -#endif - - int result = ((fabsf(p.x - q.x)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.x), fabsf(q.x))))) && - ((fabsf(p.y - q.y)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.y), fabsf(q.y))))); - - return result; -} - -// Compute the direction of a refracted ray -// v: normalized direction of the incoming ray -// n: normalized normal vector of the interface of two optical media -// r: ratio of the refractive index of the medium from where the ray comes -// to the refractive index of the medium on the other side of the surface -RMAPI Vector2 Vector2Refract(Vector2 v, Vector2 n, float r) -{ - Vector2 result = { 0 }; - - float dot = v.x*n.x + v.y*n.y; - float d = 1.0f - r*r*(1.0f - dot*dot); - - if (d >= 0.0f) - { - d = sqrtf(d); - v.x = r*v.x - (r*dot + d)*n.x; - v.y = r*v.y - (r*dot + d)*n.y; - - result = v; - } - - return result; -} - - -//---------------------------------------------------------------------------------- -// Module Functions Definition - Vector3 math -//---------------------------------------------------------------------------------- - -// Vector with components value 0.0f -RMAPI Vector3 Vector3Zero(void) -{ - Vector3 result = { 0.0f, 0.0f, 0.0f }; - - return result; -} - -// Vector with components value 1.0f -RMAPI Vector3 Vector3One(void) -{ - Vector3 result = { 1.0f, 1.0f, 1.0f }; - - return result; -} - -// Add two vectors -RMAPI Vector3 Vector3Add(Vector3 v1, Vector3 v2) -{ - Vector3 result = { v1.x + v2.x, v1.y + v2.y, v1.z + v2.z }; - - return result; -} - -// Add vector and float value -RMAPI Vector3 Vector3AddValue(Vector3 v, float add) -{ - Vector3 result = { v.x + add, v.y + add, v.z + add }; - - return result; -} - -// Subtract two vectors -RMAPI Vector3 Vector3Subtract(Vector3 v1, Vector3 v2) -{ - Vector3 result = { v1.x - v2.x, v1.y - v2.y, v1.z - v2.z }; - - return result; -} - -// Subtract vector by float value -RMAPI Vector3 Vector3SubtractValue(Vector3 v, float sub) -{ - Vector3 result = { v.x - sub, v.y - sub, v.z - sub }; - - return result; -} - -// Multiply vector by scalar -RMAPI Vector3 Vector3Scale(Vector3 v, float scalar) -{ - Vector3 result = { v.x*scalar, v.y*scalar, v.z*scalar }; - - return result; -} - -// Multiply vector by vector -RMAPI Vector3 Vector3Multiply(Vector3 v1, Vector3 v2) -{ - Vector3 result = { v1.x*v2.x, v1.y*v2.y, v1.z*v2.z }; - - return result; -} - -// Calculate two vectors cross product -RMAPI Vector3 Vector3CrossProduct(Vector3 v1, Vector3 v2) -{ - Vector3 result = { v1.y*v2.z - v1.z*v2.y, v1.z*v2.x - v1.x*v2.z, v1.x*v2.y - v1.y*v2.x }; - - return result; -} - -// Calculate one vector perpendicular vector -RMAPI Vector3 Vector3Perpendicular(Vector3 v) -{ - Vector3 result = { 0 }; - - float min = fabsf(v.x); - Vector3 cardinalAxis = {1.0f, 0.0f, 0.0f}; - - if (fabsf(v.y) < min) - { - min = fabsf(v.y); - Vector3 tmp = {0.0f, 1.0f, 0.0f}; - cardinalAxis = tmp; - } - - if (fabsf(v.z) < min) - { - Vector3 tmp = {0.0f, 0.0f, 1.0f}; - cardinalAxis = tmp; - } - - // Cross product between vectors - result.x = v.y*cardinalAxis.z - v.z*cardinalAxis.y; - result.y = v.z*cardinalAxis.x - v.x*cardinalAxis.z; - result.z = v.x*cardinalAxis.y - v.y*cardinalAxis.x; - - return result; -} - -// Calculate vector length -RMAPI float Vector3Length(const Vector3 v) -{ - float result = sqrtf(v.x*v.x + v.y*v.y + v.z*v.z); - - return result; -} - -// Calculate vector square length -RMAPI float Vector3LengthSqr(const Vector3 v) -{ - float result = v.x*v.x + v.y*v.y + v.z*v.z; - - return result; -} - -// Calculate two vectors dot product -RMAPI float Vector3DotProduct(Vector3 v1, Vector3 v2) -{ - float result = (v1.x*v2.x + v1.y*v2.y + v1.z*v2.z); - - return result; -} - -// Calculate distance between two vectors -RMAPI float Vector3Distance(Vector3 v1, Vector3 v2) -{ - float result = 0.0f; - - float dx = v2.x - v1.x; - float dy = v2.y - v1.y; - float dz = v2.z - v1.z; - result = sqrtf(dx*dx + dy*dy + dz*dz); - - return result; -} - -// Calculate square distance between two vectors -RMAPI float Vector3DistanceSqr(Vector3 v1, Vector3 v2) -{ - float result = 0.0f; - - float dx = v2.x - v1.x; - float dy = v2.y - v1.y; - float dz = v2.z - v1.z; - result = dx*dx + dy*dy + dz*dz; - - return result; -} - -// Calculate angle between two vectors -RMAPI float Vector3Angle(Vector3 v1, Vector3 v2) -{ - float result = 0.0f; - - Vector3 cross = { v1.y*v2.z - v1.z*v2.y, v1.z*v2.x - v1.x*v2.z, v1.x*v2.y - v1.y*v2.x }; - float len = sqrtf(cross.x*cross.x + cross.y*cross.y + cross.z*cross.z); - float dot = (v1.x*v2.x + v1.y*v2.y + v1.z*v2.z); - result = atan2f(len, dot); - - return result; -} - -// Negate provided vector (invert direction) -RMAPI Vector3 Vector3Negate(Vector3 v) -{ - Vector3 result = { -v.x, -v.y, -v.z }; - - return result; -} - -// Divide vector by vector -RMAPI Vector3 Vector3Divide(Vector3 v1, Vector3 v2) -{ - Vector3 result = { v1.x/v2.x, v1.y/v2.y, v1.z/v2.z }; - - return result; -} - -// Normalize provided vector -RMAPI Vector3 Vector3Normalize(Vector3 v) -{ - Vector3 result = v; - - float length = sqrtf(v.x*v.x + v.y*v.y + v.z*v.z); - if (length != 0.0f) - { - float ilength = 1.0f/length; - - result.x *= ilength; - result.y *= ilength; - result.z *= ilength; - } - - return result; -} - -//Calculate the projection of the vector v1 on to v2 -RMAPI Vector3 Vector3Project(Vector3 v1, Vector3 v2) -{ - Vector3 result = { 0 }; - - float v1dv2 = (v1.x*v2.x + v1.y*v2.y + v1.z*v2.z); - float v2dv2 = (v2.x*v2.x + v2.y*v2.y + v2.z*v2.z); - - float mag = v1dv2/v2dv2; - - result.x = v2.x*mag; - result.y = v2.y*mag; - result.z = v2.z*mag; - - return result; -} - -//Calculate the rejection of the vector v1 on to v2 -RMAPI Vector3 Vector3Reject(Vector3 v1, Vector3 v2) -{ - Vector3 result = { 0 }; - - float v1dv2 = (v1.x*v2.x + v1.y*v2.y + v1.z*v2.z); - float v2dv2 = (v2.x*v2.x + v2.y*v2.y + v2.z*v2.z); - - float mag = v1dv2/v2dv2; - - result.x = v1.x - (v2.x*mag); - result.y = v1.y - (v2.y*mag); - result.z = v1.z - (v2.z*mag); - - return result; -} - -// Orthonormalize provided vectors -// Makes vectors normalized and orthogonal to each other -// Gram-Schmidt function implementation -RMAPI void Vector3OrthoNormalize(Vector3 *v1, Vector3 *v2) -{ - float length = 0.0f; - float ilength = 0.0f; - - // Vector3Normalize(*v1); - Vector3 v = *v1; - length = sqrtf(v.x*v.x + v.y*v.y + v.z*v.z); - if (length == 0.0f) length = 1.0f; - ilength = 1.0f/length; - v1->x *= ilength; - v1->y *= ilength; - v1->z *= ilength; - - // Vector3CrossProduct(*v1, *v2) - Vector3 vn1 = { v1->y*v2->z - v1->z*v2->y, v1->z*v2->x - v1->x*v2->z, v1->x*v2->y - v1->y*v2->x }; - - // Vector3Normalize(vn1); - v = vn1; - length = sqrtf(v.x*v.x + v.y*v.y + v.z*v.z); - if (length == 0.0f) length = 1.0f; - ilength = 1.0f/length; - vn1.x *= ilength; - vn1.y *= ilength; - vn1.z *= ilength; - - // Vector3CrossProduct(vn1, *v1) - Vector3 vn2 = { vn1.y*v1->z - vn1.z*v1->y, vn1.z*v1->x - vn1.x*v1->z, vn1.x*v1->y - vn1.y*v1->x }; - - *v2 = vn2; -} - -// Transforms a Vector3 by a given Matrix -RMAPI Vector3 Vector3Transform(Vector3 v, Matrix mat) -{ - Vector3 result = { 0 }; - - float x = v.x; - float y = v.y; - float z = v.z; - - result.x = mat.m0*x + mat.m4*y + mat.m8*z + mat.m12; - result.y = mat.m1*x + mat.m5*y + mat.m9*z + mat.m13; - result.z = mat.m2*x + mat.m6*y + mat.m10*z + mat.m14; - - return result; -} - -// Transform a vector by quaternion rotation -RMAPI Vector3 Vector3RotateByQuaternion(Vector3 v, Quaternion q) -{ - Vector3 result = { 0 }; - - result.x = v.x*(q.x*q.x + q.w*q.w - q.y*q.y - q.z*q.z) + v.y*(2*q.x*q.y - 2*q.w*q.z) + v.z*(2*q.x*q.z + 2*q.w*q.y); - result.y = v.x*(2*q.w*q.z + 2*q.x*q.y) + v.y*(q.w*q.w - q.x*q.x + q.y*q.y - q.z*q.z) + v.z*(-2*q.w*q.x + 2*q.y*q.z); - result.z = v.x*(-2*q.w*q.y + 2*q.x*q.z) + v.y*(2*q.w*q.x + 2*q.y*q.z)+ v.z*(q.w*q.w - q.x*q.x - q.y*q.y + q.z*q.z); - - return result; -} - -// Rotates a vector around an axis -RMAPI Vector3 Vector3RotateByAxisAngle(Vector3 v, Vector3 axis, float angle) -{ - // Using Euler-Rodrigues Formula - // Ref.: https://en.wikipedia.org/w/index.php?title=Euler%E2%80%93Rodrigues_formula - - Vector3 result = v; - - // Vector3Normalize(axis); - float length = sqrtf(axis.x*axis.x + axis.y*axis.y + axis.z*axis.z); - if (length == 0.0f) length = 1.0f; - float ilength = 1.0f/length; - axis.x *= ilength; - axis.y *= ilength; - axis.z *= ilength; - - angle /= 2.0f; - float a = sinf(angle); - float b = axis.x*a; - float c = axis.y*a; - float d = axis.z*a; - a = cosf(angle); - Vector3 w = { b, c, d }; - - // Vector3CrossProduct(w, v) - Vector3 wv = { w.y*v.z - w.z*v.y, w.z*v.x - w.x*v.z, w.x*v.y - w.y*v.x }; - - // Vector3CrossProduct(w, wv) - Vector3 wwv = { w.y*wv.z - w.z*wv.y, w.z*wv.x - w.x*wv.z, w.x*wv.y - w.y*wv.x }; - - // Vector3Scale(wv, 2*a) - a *= 2; - wv.x *= a; - wv.y *= a; - wv.z *= a; - - // Vector3Scale(wwv, 2) - wwv.x *= 2; - wwv.y *= 2; - wwv.z *= 2; - - result.x += wv.x; - result.y += wv.y; - result.z += wv.z; - - result.x += wwv.x; - result.y += wwv.y; - result.z += wwv.z; - - return result; -} - -// Move Vector towards target -RMAPI Vector3 Vector3MoveTowards(Vector3 v, Vector3 target, float maxDistance) -{ - Vector3 result = { 0 }; - - float dx = target.x - v.x; - float dy = target.y - v.y; - float dz = target.z - v.z; - float value = (dx*dx) + (dy*dy) + (dz*dz); - - if ((value == 0) || ((maxDistance >= 0) && (value <= maxDistance*maxDistance))) return target; - - float dist = sqrtf(value); - - result.x = v.x + dx/dist*maxDistance; - result.y = v.y + dy/dist*maxDistance; - result.z = v.z + dz/dist*maxDistance; - - return result; -} - -// Calculate linear interpolation between two vectors -RMAPI Vector3 Vector3Lerp(Vector3 v1, Vector3 v2, float amount) -{ - Vector3 result = { 0 }; - - result.x = v1.x + amount*(v2.x - v1.x); - result.y = v1.y + amount*(v2.y - v1.y); - result.z = v1.z + amount*(v2.z - v1.z); - - return result; -} - -// Calculate cubic hermite interpolation between two vectors and their tangents -// as described in the GLTF 2.0 specification: https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#interpolation-cubic -RMAPI Vector3 Vector3CubicHermite(Vector3 v1, Vector3 tangent1, Vector3 v2, Vector3 tangent2, float amount) -{ - Vector3 result = { 0 }; - - float amountPow2 = amount*amount; - float amountPow3 = amount*amount*amount; - - result.x = (2*amountPow3 - 3*amountPow2 + 1)*v1.x + (amountPow3 - 2*amountPow2 + amount)*tangent1.x + (-2*amountPow3 + 3*amountPow2)*v2.x + (amountPow3 - amountPow2)*tangent2.x; - result.y = (2*amountPow3 - 3*amountPow2 + 1)*v1.y + (amountPow3 - 2*amountPow2 + amount)*tangent1.y + (-2*amountPow3 + 3*amountPow2)*v2.y + (amountPow3 - amountPow2)*tangent2.y; - result.z = (2*amountPow3 - 3*amountPow2 + 1)*v1.z + (amountPow3 - 2*amountPow2 + amount)*tangent1.z + (-2*amountPow3 + 3*amountPow2)*v2.z + (amountPow3 - amountPow2)*tangent2.z; - - return result; -} - -// Calculate reflected vector to normal -RMAPI Vector3 Vector3Reflect(Vector3 v, Vector3 normal) -{ - Vector3 result = { 0 }; - - // I is the original vector - // N is the normal of the incident plane - // R = I - (2*N*(DotProduct[I, N])) - - float dotProduct = (v.x*normal.x + v.y*normal.y + v.z*normal.z); - - result.x = v.x - (2.0f*normal.x)*dotProduct; - result.y = v.y - (2.0f*normal.y)*dotProduct; - result.z = v.z - (2.0f*normal.z)*dotProduct; - - return result; -} - -// Get min value for each pair of components -RMAPI Vector3 Vector3Min(Vector3 v1, Vector3 v2) -{ - Vector3 result = { 0 }; - - result.x = fminf(v1.x, v2.x); - result.y = fminf(v1.y, v2.y); - result.z = fminf(v1.z, v2.z); - - return result; -} - -// Get max value for each pair of components -RMAPI Vector3 Vector3Max(Vector3 v1, Vector3 v2) -{ - Vector3 result = { 0 }; - - result.x = fmaxf(v1.x, v2.x); - result.y = fmaxf(v1.y, v2.y); - result.z = fmaxf(v1.z, v2.z); - - return result; -} - -// Compute barycenter coordinates (u, v, w) for point p with respect to triangle (a, b, c) -// NOTE: Assumes P is on the plane of the triangle -RMAPI Vector3 Vector3Barycenter(Vector3 p, Vector3 a, Vector3 b, Vector3 c) -{ - Vector3 result = { 0 }; - - Vector3 v0 = { b.x - a.x, b.y - a.y, b.z - a.z }; // Vector3Subtract(b, a) - Vector3 v1 = { c.x - a.x, c.y - a.y, c.z - a.z }; // Vector3Subtract(c, a) - Vector3 v2 = { p.x - a.x, p.y - a.y, p.z - a.z }; // Vector3Subtract(p, a) - float d00 = (v0.x*v0.x + v0.y*v0.y + v0.z*v0.z); // Vector3DotProduct(v0, v0) - float d01 = (v0.x*v1.x + v0.y*v1.y + v0.z*v1.z); // Vector3DotProduct(v0, v1) - float d11 = (v1.x*v1.x + v1.y*v1.y + v1.z*v1.z); // Vector3DotProduct(v1, v1) - float d20 = (v2.x*v0.x + v2.y*v0.y + v2.z*v0.z); // Vector3DotProduct(v2, v0) - float d21 = (v2.x*v1.x + v2.y*v1.y + v2.z*v1.z); // Vector3DotProduct(v2, v1) - - float denom = d00*d11 - d01*d01; - - result.y = (d11*d20 - d01*d21)/denom; - result.z = (d00*d21 - d01*d20)/denom; - result.x = 1.0f - (result.z + result.y); - - return result; -} - -// Projects a Vector3 from screen space into object space -// NOTE: We are avoiding calling other raymath functions despite available -RMAPI Vector3 Vector3Unproject(Vector3 source, Matrix projection, Matrix view) -{ - Vector3 result = { 0 }; - - // Calculate unprojected matrix (multiply view matrix by projection matrix) and invert it - Matrix matViewProj = { // MatrixMultiply(view, projection); - view.m0*projection.m0 + view.m1*projection.m4 + view.m2*projection.m8 + view.m3*projection.m12, - view.m0*projection.m1 + view.m1*projection.m5 + view.m2*projection.m9 + view.m3*projection.m13, - view.m0*projection.m2 + view.m1*projection.m6 + view.m2*projection.m10 + view.m3*projection.m14, - view.m0*projection.m3 + view.m1*projection.m7 + view.m2*projection.m11 + view.m3*projection.m15, - view.m4*projection.m0 + view.m5*projection.m4 + view.m6*projection.m8 + view.m7*projection.m12, - view.m4*projection.m1 + view.m5*projection.m5 + view.m6*projection.m9 + view.m7*projection.m13, - view.m4*projection.m2 + view.m5*projection.m6 + view.m6*projection.m10 + view.m7*projection.m14, - view.m4*projection.m3 + view.m5*projection.m7 + view.m6*projection.m11 + view.m7*projection.m15, - view.m8*projection.m0 + view.m9*projection.m4 + view.m10*projection.m8 + view.m11*projection.m12, - view.m8*projection.m1 + view.m9*projection.m5 + view.m10*projection.m9 + view.m11*projection.m13, - view.m8*projection.m2 + view.m9*projection.m6 + view.m10*projection.m10 + view.m11*projection.m14, - view.m8*projection.m3 + view.m9*projection.m7 + view.m10*projection.m11 + view.m11*projection.m15, - view.m12*projection.m0 + view.m13*projection.m4 + view.m14*projection.m8 + view.m15*projection.m12, - view.m12*projection.m1 + view.m13*projection.m5 + view.m14*projection.m9 + view.m15*projection.m13, - view.m12*projection.m2 + view.m13*projection.m6 + view.m14*projection.m10 + view.m15*projection.m14, - view.m12*projection.m3 + view.m13*projection.m7 + view.m14*projection.m11 + view.m15*projection.m15 }; - - // Calculate inverted matrix -> MatrixInvert(matViewProj); - // Cache the matrix values (speed optimization) - float a00 = matViewProj.m0, a01 = matViewProj.m1, a02 = matViewProj.m2, a03 = matViewProj.m3; - float a10 = matViewProj.m4, a11 = matViewProj.m5, a12 = matViewProj.m6, a13 = matViewProj.m7; - float a20 = matViewProj.m8, a21 = matViewProj.m9, a22 = matViewProj.m10, a23 = matViewProj.m11; - float a30 = matViewProj.m12, a31 = matViewProj.m13, a32 = matViewProj.m14, a33 = matViewProj.m15; - - float b00 = a00*a11 - a01*a10; - float b01 = a00*a12 - a02*a10; - float b02 = a00*a13 - a03*a10; - float b03 = a01*a12 - a02*a11; - float b04 = a01*a13 - a03*a11; - float b05 = a02*a13 - a03*a12; - float b06 = a20*a31 - a21*a30; - float b07 = a20*a32 - a22*a30; - float b08 = a20*a33 - a23*a30; - float b09 = a21*a32 - a22*a31; - float b10 = a21*a33 - a23*a31; - float b11 = a22*a33 - a23*a32; - - // Calculate the invert determinant (inlined to avoid double-caching) - float invDet = 1.0f/(b00*b11 - b01*b10 + b02*b09 + b03*b08 - b04*b07 + b05*b06); - - Matrix matViewProjInv = { - (a11*b11 - a12*b10 + a13*b09)*invDet, - (-a01*b11 + a02*b10 - a03*b09)*invDet, - (a31*b05 - a32*b04 + a33*b03)*invDet, - (-a21*b05 + a22*b04 - a23*b03)*invDet, - (-a10*b11 + a12*b08 - a13*b07)*invDet, - (a00*b11 - a02*b08 + a03*b07)*invDet, - (-a30*b05 + a32*b02 - a33*b01)*invDet, - (a20*b05 - a22*b02 + a23*b01)*invDet, - (a10*b10 - a11*b08 + a13*b06)*invDet, - (-a00*b10 + a01*b08 - a03*b06)*invDet, - (a30*b04 - a31*b02 + a33*b00)*invDet, - (-a20*b04 + a21*b02 - a23*b00)*invDet, - (-a10*b09 + a11*b07 - a12*b06)*invDet, - (a00*b09 - a01*b07 + a02*b06)*invDet, - (-a30*b03 + a31*b01 - a32*b00)*invDet, - (a20*b03 - a21*b01 + a22*b00)*invDet }; - - // Create quaternion from source point - Quaternion quat = { source.x, source.y, source.z, 1.0f }; - - // Multiply quat point by unprojecte matrix - Quaternion qtransformed = { // QuaternionTransform(quat, matViewProjInv) - matViewProjInv.m0*quat.x + matViewProjInv.m4*quat.y + matViewProjInv.m8*quat.z + matViewProjInv.m12*quat.w, - matViewProjInv.m1*quat.x + matViewProjInv.m5*quat.y + matViewProjInv.m9*quat.z + matViewProjInv.m13*quat.w, - matViewProjInv.m2*quat.x + matViewProjInv.m6*quat.y + matViewProjInv.m10*quat.z + matViewProjInv.m14*quat.w, - matViewProjInv.m3*quat.x + matViewProjInv.m7*quat.y + matViewProjInv.m11*quat.z + matViewProjInv.m15*quat.w }; - - // Normalized world points in vectors - result.x = qtransformed.x/qtransformed.w; - result.y = qtransformed.y/qtransformed.w; - result.z = qtransformed.z/qtransformed.w; - - return result; -} - -// Get Vector3 as float array -RMAPI float3 Vector3ToFloatV(Vector3 v) -{ - float3 buffer = { 0 }; - - buffer.v[0] = v.x; - buffer.v[1] = v.y; - buffer.v[2] = v.z; - - return buffer; -} - -// Invert the given vector -RMAPI Vector3 Vector3Invert(Vector3 v) -{ - Vector3 result = { 1.0f/v.x, 1.0f/v.y, 1.0f/v.z }; - - return result; -} - -// Clamp the components of the vector between -// min and max values specified by the given vectors -RMAPI Vector3 Vector3Clamp(Vector3 v, Vector3 min, Vector3 max) -{ - Vector3 result = { 0 }; - - result.x = fminf(max.x, fmaxf(min.x, v.x)); - result.y = fminf(max.y, fmaxf(min.y, v.y)); - result.z = fminf(max.z, fmaxf(min.z, v.z)); - - return result; -} - -// Clamp the magnitude of the vector between two values -RMAPI Vector3 Vector3ClampValue(Vector3 v, float min, float max) -{ - Vector3 result = v; - - float length = (v.x*v.x) + (v.y*v.y) + (v.z*v.z); - if (length > 0.0f) - { - length = sqrtf(length); - - float scale = 1; // By default, 1 as the neutral element. - if (length < min) - { - scale = min/length; - } - else if (length > max) - { - scale = max/length; - } - - result.x = v.x*scale; - result.y = v.y*scale; - result.z = v.z*scale; - } - - return result; -} - -// Check whether two given vectors are almost equal -RMAPI int Vector3Equals(Vector3 p, Vector3 q) -{ -#if !defined(EPSILON) - #define EPSILON 0.000001f -#endif - - int result = ((fabsf(p.x - q.x)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.x), fabsf(q.x))))) && - ((fabsf(p.y - q.y)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.y), fabsf(q.y))))) && - ((fabsf(p.z - q.z)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.z), fabsf(q.z))))); - - return result; -} - -// Compute the direction of a refracted ray -// v: normalized direction of the incoming ray -// n: normalized normal vector of the interface of two optical media -// r: ratio of the refractive index of the medium from where the ray comes -// to the refractive index of the medium on the other side of the surface -RMAPI Vector3 Vector3Refract(Vector3 v, Vector3 n, float r) -{ - Vector3 result = { 0 }; - - float dot = v.x*n.x + v.y*n.y + v.z*n.z; - float d = 1.0f - r*r*(1.0f - dot*dot); - - if (d >= 0.0f) - { - d = sqrtf(d); - v.x = r*v.x - (r*dot + d)*n.x; - v.y = r*v.y - (r*dot + d)*n.y; - v.z = r*v.z - (r*dot + d)*n.z; - - result = v; - } - - return result; -} - - -//---------------------------------------------------------------------------------- -// Module Functions Definition - Vector4 math -//---------------------------------------------------------------------------------- - -RMAPI Vector4 Vector4Zero(void) -{ - Vector4 result = { 0.0f, 0.0f, 0.0f, 0.0f }; - return result; -} - -RMAPI Vector4 Vector4One(void) -{ - Vector4 result = { 1.0f, 1.0f, 1.0f, 1.0f }; - return result; -} - -RMAPI Vector4 Vector4Add(Vector4 v1, Vector4 v2) -{ - Vector4 result = { - v1.x + v2.x, - v1.y + v2.y, - v1.z + v2.z, - v1.w + v2.w - }; - return result; -} - -RMAPI Vector4 Vector4AddValue(Vector4 v, float add) -{ - Vector4 result = { - v.x + add, - v.y + add, - v.z + add, - v.w + add - }; - return result; -} - -RMAPI Vector4 Vector4Subtract(Vector4 v1, Vector4 v2) -{ - Vector4 result = { - v1.x - v2.x, - v1.y - v2.y, - v1.z - v2.z, - v1.w - v2.w - }; - return result; -} - -RMAPI Vector4 Vector4SubtractValue(Vector4 v, float add) -{ - Vector4 result = { - v.x - add, - v.y - add, - v.z - add, - v.w - add - }; - return result; -} - -RMAPI float Vector4Length(Vector4 v) -{ - float result = sqrtf((v.x*v.x) + (v.y*v.y) + (v.z*v.z) + (v.w*v.w)); - return result; -} - -RMAPI float Vector4LengthSqr(Vector4 v) -{ - float result = (v.x*v.x) + (v.y*v.y) + (v.z*v.z) + (v.w*v.w); - return result; -} - -RMAPI float Vector4DotProduct(Vector4 v1, Vector4 v2) -{ - float result = (v1.x*v2.x + v1.y*v2.y + v1.z*v2.z + v1.w*v2.w); - return result; -} - -// Calculate distance between two vectors -RMAPI float Vector4Distance(Vector4 v1, Vector4 v2) -{ - float result = sqrtf( - (v1.x - v2.x)*(v1.x - v2.x) + (v1.y - v2.y)*(v1.y - v2.y) + - (v1.z - v2.z)*(v1.z - v2.z) + (v1.w - v2.w)*(v1.w - v2.w)); - return result; -} - -// Calculate square distance between two vectors -RMAPI float Vector4DistanceSqr(Vector4 v1, Vector4 v2) -{ - float result = - (v1.x - v2.x)*(v1.x - v2.x) + (v1.y - v2.y)*(v1.y - v2.y) + - (v1.z - v2.z)*(v1.z - v2.z) + (v1.w - v2.w)*(v1.w - v2.w); - - return result; -} - -RMAPI Vector4 Vector4Scale(Vector4 v, float scale) -{ - Vector4 result = { v.x*scale, v.y*scale, v.z*scale, v.w*scale }; - return result; -} - -// Multiply vector by vector -RMAPI Vector4 Vector4Multiply(Vector4 v1, Vector4 v2) -{ - Vector4 result = { v1.x*v2.x, v1.y*v2.y, v1.z*v2.z, v1.w*v2.w }; - return result; -} - -// Negate vector -RMAPI Vector4 Vector4Negate(Vector4 v) -{ - Vector4 result = { -v.x, -v.y, -v.z, -v.w }; - return result; -} - -// Divide vector by vector -RMAPI Vector4 Vector4Divide(Vector4 v1, Vector4 v2) -{ - Vector4 result = { v1.x/v2.x, v1.y/v2.y, v1.z/v2.z, v1.w/v2.w }; - return result; -} - -// Normalize provided vector -RMAPI Vector4 Vector4Normalize(Vector4 v) -{ - Vector4 result = { 0 }; - float length = sqrtf((v.x*v.x) + (v.y*v.y) + (v.z*v.z) + (v.w*v.w)); - - if (length > 0) - { - float ilength = 1.0f/length; - result.x = v.x*ilength; - result.y = v.y*ilength; - result.z = v.z*ilength; - result.w = v.w*ilength; - } - - return result; -} - -// Get min value for each pair of components -RMAPI Vector4 Vector4Min(Vector4 v1, Vector4 v2) -{ - Vector4 result = { 0 }; - - result.x = fminf(v1.x, v2.x); - result.y = fminf(v1.y, v2.y); - result.z = fminf(v1.z, v2.z); - result.w = fminf(v1.w, v2.w); - - return result; -} - -// Get max value for each pair of components -RMAPI Vector4 Vector4Max(Vector4 v1, Vector4 v2) -{ - Vector4 result = { 0 }; - - result.x = fmaxf(v1.x, v2.x); - result.y = fmaxf(v1.y, v2.y); - result.z = fmaxf(v1.z, v2.z); - result.w = fmaxf(v1.w, v2.w); - - return result; -} - -// Calculate linear interpolation between two vectors -RMAPI Vector4 Vector4Lerp(Vector4 v1, Vector4 v2, float amount) -{ - Vector4 result = { 0 }; - - result.x = v1.x + amount*(v2.x - v1.x); - result.y = v1.y + amount*(v2.y - v1.y); - result.z = v1.z + amount*(v2.z - v1.z); - result.w = v1.w + amount*(v2.w - v1.w); - - return result; -} - -// Move Vector towards target -RMAPI Vector4 Vector4MoveTowards(Vector4 v, Vector4 target, float maxDistance) -{ - Vector4 result = { 0 }; - - float dx = target.x - v.x; - float dy = target.y - v.y; - float dz = target.z - v.z; - float dw = target.w - v.w; - float value = (dx*dx) + (dy*dy) + (dz*dz) + (dw*dw); - - if ((value == 0) || ((maxDistance >= 0) && (value <= maxDistance*maxDistance))) return target; - - float dist = sqrtf(value); - - result.x = v.x + dx/dist*maxDistance; - result.y = v.y + dy/dist*maxDistance; - result.z = v.z + dz/dist*maxDistance; - result.w = v.w + dw/dist*maxDistance; - - return result; -} - -// Invert the given vector -RMAPI Vector4 Vector4Invert(Vector4 v) -{ - Vector4 result = { 1.0f/v.x, 1.0f/v.y, 1.0f/v.z, 1.0f/v.w }; - return result; -} - -// Check whether two given vectors are almost equal -RMAPI int Vector4Equals(Vector4 p, Vector4 q) -{ -#if !defined(EPSILON) - #define EPSILON 0.000001f -#endif - - int result = ((fabsf(p.x - q.x)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.x), fabsf(q.x))))) && - ((fabsf(p.y - q.y)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.y), fabsf(q.y))))) && - ((fabsf(p.z - q.z)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.z), fabsf(q.z))))) && - ((fabsf(p.w - q.w)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.w), fabsf(q.w))))); - return result; -} - - -//---------------------------------------------------------------------------------- -// Module Functions Definition - Matrix math -//---------------------------------------------------------------------------------- - -// Compute matrix determinant -RMAPI float MatrixDeterminant(Matrix mat) -{ - float result = 0.0f; - - // Cache the matrix values (speed optimization) - float a00 = mat.m0, a01 = mat.m1, a02 = mat.m2, a03 = mat.m3; - float a10 = mat.m4, a11 = mat.m5, a12 = mat.m6, a13 = mat.m7; - float a20 = mat.m8, a21 = mat.m9, a22 = mat.m10, a23 = mat.m11; - float a30 = mat.m12, a31 = mat.m13, a32 = mat.m14, a33 = mat.m15; - - result = a30*a21*a12*a03 - a20*a31*a12*a03 - a30*a11*a22*a03 + a10*a31*a22*a03 + - a20*a11*a32*a03 - a10*a21*a32*a03 - a30*a21*a02*a13 + a20*a31*a02*a13 + - a30*a01*a22*a13 - a00*a31*a22*a13 - a20*a01*a32*a13 + a00*a21*a32*a13 + - a30*a11*a02*a23 - a10*a31*a02*a23 - a30*a01*a12*a23 + a00*a31*a12*a23 + - a10*a01*a32*a23 - a00*a11*a32*a23 - a20*a11*a02*a33 + a10*a21*a02*a33 + - a20*a01*a12*a33 - a00*a21*a12*a33 - a10*a01*a22*a33 + a00*a11*a22*a33; - - return result; -} - -// Get the trace of the matrix (sum of the values along the diagonal) -RMAPI float MatrixTrace(Matrix mat) -{ - float result = (mat.m0 + mat.m5 + mat.m10 + mat.m15); - - return result; -} - -// Transposes provided matrix -RMAPI Matrix MatrixTranspose(Matrix mat) -{ - Matrix result = { 0 }; - - result.m0 = mat.m0; - result.m1 = mat.m4; - result.m2 = mat.m8; - result.m3 = mat.m12; - result.m4 = mat.m1; - result.m5 = mat.m5; - result.m6 = mat.m9; - result.m7 = mat.m13; - result.m8 = mat.m2; - result.m9 = mat.m6; - result.m10 = mat.m10; - result.m11 = mat.m14; - result.m12 = mat.m3; - result.m13 = mat.m7; - result.m14 = mat.m11; - result.m15 = mat.m15; - - return result; -} - -// Invert provided matrix -RMAPI Matrix MatrixInvert(Matrix mat) -{ - Matrix result = { 0 }; - - // Cache the matrix values (speed optimization) - float a00 = mat.m0, a01 = mat.m1, a02 = mat.m2, a03 = mat.m3; - float a10 = mat.m4, a11 = mat.m5, a12 = mat.m6, a13 = mat.m7; - float a20 = mat.m8, a21 = mat.m9, a22 = mat.m10, a23 = mat.m11; - float a30 = mat.m12, a31 = mat.m13, a32 = mat.m14, a33 = mat.m15; - - float b00 = a00*a11 - a01*a10; - float b01 = a00*a12 - a02*a10; - float b02 = a00*a13 - a03*a10; - float b03 = a01*a12 - a02*a11; - float b04 = a01*a13 - a03*a11; - float b05 = a02*a13 - a03*a12; - float b06 = a20*a31 - a21*a30; - float b07 = a20*a32 - a22*a30; - float b08 = a20*a33 - a23*a30; - float b09 = a21*a32 - a22*a31; - float b10 = a21*a33 - a23*a31; - float b11 = a22*a33 - a23*a32; - - // Calculate the invert determinant (inlined to avoid double-caching) - float invDet = 1.0f/(b00*b11 - b01*b10 + b02*b09 + b03*b08 - b04*b07 + b05*b06); - - result.m0 = (a11*b11 - a12*b10 + a13*b09)*invDet; - result.m1 = (-a01*b11 + a02*b10 - a03*b09)*invDet; - result.m2 = (a31*b05 - a32*b04 + a33*b03)*invDet; - result.m3 = (-a21*b05 + a22*b04 - a23*b03)*invDet; - result.m4 = (-a10*b11 + a12*b08 - a13*b07)*invDet; - result.m5 = (a00*b11 - a02*b08 + a03*b07)*invDet; - result.m6 = (-a30*b05 + a32*b02 - a33*b01)*invDet; - result.m7 = (a20*b05 - a22*b02 + a23*b01)*invDet; - result.m8 = (a10*b10 - a11*b08 + a13*b06)*invDet; - result.m9 = (-a00*b10 + a01*b08 - a03*b06)*invDet; - result.m10 = (a30*b04 - a31*b02 + a33*b00)*invDet; - result.m11 = (-a20*b04 + a21*b02 - a23*b00)*invDet; - result.m12 = (-a10*b09 + a11*b07 - a12*b06)*invDet; - result.m13 = (a00*b09 - a01*b07 + a02*b06)*invDet; - result.m14 = (-a30*b03 + a31*b01 - a32*b00)*invDet; - result.m15 = (a20*b03 - a21*b01 + a22*b00)*invDet; - - return result; -} - -// Get identity matrix -RMAPI Matrix MatrixIdentity(void) -{ - Matrix result = { 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f }; - - return result; -} - -// Add two matrices -RMAPI Matrix MatrixAdd(Matrix left, Matrix right) -{ - Matrix result = { 0 }; - - result.m0 = left.m0 + right.m0; - result.m1 = left.m1 + right.m1; - result.m2 = left.m2 + right.m2; - result.m3 = left.m3 + right.m3; - result.m4 = left.m4 + right.m4; - result.m5 = left.m5 + right.m5; - result.m6 = left.m6 + right.m6; - result.m7 = left.m7 + right.m7; - result.m8 = left.m8 + right.m8; - result.m9 = left.m9 + right.m9; - result.m10 = left.m10 + right.m10; - result.m11 = left.m11 + right.m11; - result.m12 = left.m12 + right.m12; - result.m13 = left.m13 + right.m13; - result.m14 = left.m14 + right.m14; - result.m15 = left.m15 + right.m15; - - return result; -} - -// Subtract two matrices (left - right) -RMAPI Matrix MatrixSubtract(Matrix left, Matrix right) -{ - Matrix result = { 0 }; - - result.m0 = left.m0 - right.m0; - result.m1 = left.m1 - right.m1; - result.m2 = left.m2 - right.m2; - result.m3 = left.m3 - right.m3; - result.m4 = left.m4 - right.m4; - result.m5 = left.m5 - right.m5; - result.m6 = left.m6 - right.m6; - result.m7 = left.m7 - right.m7; - result.m8 = left.m8 - right.m8; - result.m9 = left.m9 - right.m9; - result.m10 = left.m10 - right.m10; - result.m11 = left.m11 - right.m11; - result.m12 = left.m12 - right.m12; - result.m13 = left.m13 - right.m13; - result.m14 = left.m14 - right.m14; - result.m15 = left.m15 - right.m15; - - return result; -} - -// Get two matrix multiplication -// NOTE: When multiplying matrices... the order matters! -RMAPI Matrix MatrixMultiply(Matrix left, Matrix right) -{ - Matrix result = { 0 }; - - result.m0 = left.m0*right.m0 + left.m1*right.m4 + left.m2*right.m8 + left.m3*right.m12; - result.m1 = left.m0*right.m1 + left.m1*right.m5 + left.m2*right.m9 + left.m3*right.m13; - result.m2 = left.m0*right.m2 + left.m1*right.m6 + left.m2*right.m10 + left.m3*right.m14; - result.m3 = left.m0*right.m3 + left.m1*right.m7 + left.m2*right.m11 + left.m3*right.m15; - result.m4 = left.m4*right.m0 + left.m5*right.m4 + left.m6*right.m8 + left.m7*right.m12; - result.m5 = left.m4*right.m1 + left.m5*right.m5 + left.m6*right.m9 + left.m7*right.m13; - result.m6 = left.m4*right.m2 + left.m5*right.m6 + left.m6*right.m10 + left.m7*right.m14; - result.m7 = left.m4*right.m3 + left.m5*right.m7 + left.m6*right.m11 + left.m7*right.m15; - result.m8 = left.m8*right.m0 + left.m9*right.m4 + left.m10*right.m8 + left.m11*right.m12; - result.m9 = left.m8*right.m1 + left.m9*right.m5 + left.m10*right.m9 + left.m11*right.m13; - result.m10 = left.m8*right.m2 + left.m9*right.m6 + left.m10*right.m10 + left.m11*right.m14; - result.m11 = left.m8*right.m3 + left.m9*right.m7 + left.m10*right.m11 + left.m11*right.m15; - result.m12 = left.m12*right.m0 + left.m13*right.m4 + left.m14*right.m8 + left.m15*right.m12; - result.m13 = left.m12*right.m1 + left.m13*right.m5 + left.m14*right.m9 + left.m15*right.m13; - result.m14 = left.m12*right.m2 + left.m13*right.m6 + left.m14*right.m10 + left.m15*right.m14; - result.m15 = left.m12*right.m3 + left.m13*right.m7 + left.m14*right.m11 + left.m15*right.m15; - - return result; -} - -// Get translation matrix -RMAPI Matrix MatrixTranslate(float x, float y, float z) -{ - Matrix result = { 1.0f, 0.0f, 0.0f, x, - 0.0f, 1.0f, 0.0f, y, - 0.0f, 0.0f, 1.0f, z, - 0.0f, 0.0f, 0.0f, 1.0f }; - - return result; -} - -// Create rotation matrix from axis and angle -// NOTE: Angle should be provided in radians -RMAPI Matrix MatrixRotate(Vector3 axis, float angle) -{ - Matrix result = { 0 }; - - float x = axis.x, y = axis.y, z = axis.z; - - float lengthSquared = x*x + y*y + z*z; - - if ((lengthSquared != 1.0f) && (lengthSquared != 0.0f)) - { - float ilength = 1.0f/sqrtf(lengthSquared); - x *= ilength; - y *= ilength; - z *= ilength; - } - - float sinres = sinf(angle); - float cosres = cosf(angle); - float t = 1.0f - cosres; - - result.m0 = x*x*t + cosres; - result.m1 = y*x*t + z*sinres; - result.m2 = z*x*t - y*sinres; - result.m3 = 0.0f; - - result.m4 = x*y*t - z*sinres; - result.m5 = y*y*t + cosres; - result.m6 = z*y*t + x*sinres; - result.m7 = 0.0f; - - result.m8 = x*z*t + y*sinres; - result.m9 = y*z*t - x*sinres; - result.m10 = z*z*t + cosres; - result.m11 = 0.0f; - - result.m12 = 0.0f; - result.m13 = 0.0f; - result.m14 = 0.0f; - result.m15 = 1.0f; - - return result; -} - -// Get x-rotation matrix -// NOTE: Angle must be provided in radians -RMAPI Matrix MatrixRotateX(float angle) -{ - Matrix result = { 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f }; // MatrixIdentity() - - float cosres = cosf(angle); - float sinres = sinf(angle); - - result.m5 = cosres; - result.m6 = sinres; - result.m9 = -sinres; - result.m10 = cosres; - - return result; -} - -// Get y-rotation matrix -// NOTE: Angle must be provided in radians -RMAPI Matrix MatrixRotateY(float angle) -{ - Matrix result = { 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f }; // MatrixIdentity() - - float cosres = cosf(angle); - float sinres = sinf(angle); - - result.m0 = cosres; - result.m2 = -sinres; - result.m8 = sinres; - result.m10 = cosres; - - return result; -} - -// Get z-rotation matrix -// NOTE: Angle must be provided in radians -RMAPI Matrix MatrixRotateZ(float angle) -{ - Matrix result = { 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f }; // MatrixIdentity() - - float cosres = cosf(angle); - float sinres = sinf(angle); - - result.m0 = cosres; - result.m1 = sinres; - result.m4 = -sinres; - result.m5 = cosres; - - return result; -} - - -// Get xyz-rotation matrix -// NOTE: Angle must be provided in radians -RMAPI Matrix MatrixRotateXYZ(Vector3 angle) -{ - Matrix result = { 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f }; // MatrixIdentity() - - float cosz = cosf(-angle.z); - float sinz = sinf(-angle.z); - float cosy = cosf(-angle.y); - float siny = sinf(-angle.y); - float cosx = cosf(-angle.x); - float sinx = sinf(-angle.x); - - result.m0 = cosz*cosy; - result.m1 = (cosz*siny*sinx) - (sinz*cosx); - result.m2 = (cosz*siny*cosx) + (sinz*sinx); - - result.m4 = sinz*cosy; - result.m5 = (sinz*siny*sinx) + (cosz*cosx); - result.m6 = (sinz*siny*cosx) - (cosz*sinx); - - result.m8 = -siny; - result.m9 = cosy*sinx; - result.m10= cosy*cosx; - - return result; -} - -// Get zyx-rotation matrix -// NOTE: Angle must be provided in radians -RMAPI Matrix MatrixRotateZYX(Vector3 angle) -{ - Matrix result = { 0 }; - - float cz = cosf(angle.z); - float sz = sinf(angle.z); - float cy = cosf(angle.y); - float sy = sinf(angle.y); - float cx = cosf(angle.x); - float sx = sinf(angle.x); - - result.m0 = cz*cy; - result.m4 = cz*sy*sx - cx*sz; - result.m8 = sz*sx + cz*cx*sy; - result.m12 = 0; - - result.m1 = cy*sz; - result.m5 = cz*cx + sz*sy*sx; - result.m9 = cx*sz*sy - cz*sx; - result.m13 = 0; - - result.m2 = -sy; - result.m6 = cy*sx; - result.m10 = cy*cx; - result.m14 = 0; - - result.m3 = 0; - result.m7 = 0; - result.m11 = 0; - result.m15 = 1; - - return result; -} - -// Get scaling matrix -RMAPI Matrix MatrixScale(float x, float y, float z) -{ - Matrix result = { x, 0.0f, 0.0f, 0.0f, - 0.0f, y, 0.0f, 0.0f, - 0.0f, 0.0f, z, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f }; - - return result; -} - -// Get perspective projection matrix -RMAPI Matrix MatrixFrustum(double left, double right, double bottom, double top, double nearPlane, double farPlane) -{ - Matrix result = { 0 }; - - float rl = (float)(right - left); - float tb = (float)(top - bottom); - float fn = (float)(farPlane - nearPlane); - - result.m0 = ((float)nearPlane*2.0f)/rl; - result.m1 = 0.0f; - result.m2 = 0.0f; - result.m3 = 0.0f; - - result.m4 = 0.0f; - result.m5 = ((float)nearPlane*2.0f)/tb; - result.m6 = 0.0f; - result.m7 = 0.0f; - - result.m8 = ((float)right + (float)left)/rl; - result.m9 = ((float)top + (float)bottom)/tb; - result.m10 = -((float)farPlane + (float)nearPlane)/fn; - result.m11 = -1.0f; - - result.m12 = 0.0f; - result.m13 = 0.0f; - result.m14 = -((float)farPlane*(float)nearPlane*2.0f)/fn; - result.m15 = 0.0f; - - return result; -} - -// Get perspective projection matrix -// NOTE: Fovy angle must be provided in radians -RMAPI Matrix MatrixPerspective(double fovY, double aspect, double nearPlane, double farPlane) -{ - Matrix result = { 0 }; - - double top = nearPlane*tan(fovY*0.5); - double bottom = -top; - double right = top*aspect; - double left = -right; - - // MatrixFrustum(-right, right, -top, top, near, far); - float rl = (float)(right - left); - float tb = (float)(top - bottom); - float fn = (float)(farPlane - nearPlane); - - result.m0 = ((float)nearPlane*2.0f)/rl; - result.m5 = ((float)nearPlane*2.0f)/tb; - result.m8 = ((float)right + (float)left)/rl; - result.m9 = ((float)top + (float)bottom)/tb; - result.m10 = -((float)farPlane + (float)nearPlane)/fn; - result.m11 = -1.0f; - result.m14 = -((float)farPlane*(float)nearPlane*2.0f)/fn; - - return result; -} - -// Get orthographic projection matrix -RMAPI Matrix MatrixOrtho(double left, double right, double bottom, double top, double nearPlane, double farPlane) -{ - Matrix result = { 0 }; - - float rl = (float)(right - left); - float tb = (float)(top - bottom); - float fn = (float)(farPlane - nearPlane); - - result.m0 = 2.0f/rl; - result.m1 = 0.0f; - result.m2 = 0.0f; - result.m3 = 0.0f; - result.m4 = 0.0f; - result.m5 = 2.0f/tb; - result.m6 = 0.0f; - result.m7 = 0.0f; - result.m8 = 0.0f; - result.m9 = 0.0f; - result.m10 = -2.0f/fn; - result.m11 = 0.0f; - result.m12 = -((float)left + (float)right)/rl; - result.m13 = -((float)top + (float)bottom)/tb; - result.m14 = -((float)farPlane + (float)nearPlane)/fn; - result.m15 = 1.0f; - - return result; -} - -// Get camera look-at matrix (view matrix) -RMAPI Matrix MatrixLookAt(Vector3 eye, Vector3 target, Vector3 up) -{ - Matrix result = { 0 }; - - float length = 0.0f; - float ilength = 0.0f; - - // Vector3Subtract(eye, target) - Vector3 vz = { eye.x - target.x, eye.y - target.y, eye.z - target.z }; - - // Vector3Normalize(vz) - Vector3 v = vz; - length = sqrtf(v.x*v.x + v.y*v.y + v.z*v.z); - if (length == 0.0f) length = 1.0f; - ilength = 1.0f/length; - vz.x *= ilength; - vz.y *= ilength; - vz.z *= ilength; - - // Vector3CrossProduct(up, vz) - Vector3 vx = { up.y*vz.z - up.z*vz.y, up.z*vz.x - up.x*vz.z, up.x*vz.y - up.y*vz.x }; - - // Vector3Normalize(x) - v = vx; - length = sqrtf(v.x*v.x + v.y*v.y + v.z*v.z); - if (length == 0.0f) length = 1.0f; - ilength = 1.0f/length; - vx.x *= ilength; - vx.y *= ilength; - vx.z *= ilength; - - // Vector3CrossProduct(vz, vx) - Vector3 vy = { vz.y*vx.z - vz.z*vx.y, vz.z*vx.x - vz.x*vx.z, vz.x*vx.y - vz.y*vx.x }; - - result.m0 = vx.x; - result.m1 = vy.x; - result.m2 = vz.x; - result.m3 = 0.0f; - result.m4 = vx.y; - result.m5 = vy.y; - result.m6 = vz.y; - result.m7 = 0.0f; - result.m8 = vx.z; - result.m9 = vy.z; - result.m10 = vz.z; - result.m11 = 0.0f; - result.m12 = -(vx.x*eye.x + vx.y*eye.y + vx.z*eye.z); // Vector3DotProduct(vx, eye) - result.m13 = -(vy.x*eye.x + vy.y*eye.y + vy.z*eye.z); // Vector3DotProduct(vy, eye) - result.m14 = -(vz.x*eye.x + vz.y*eye.y + vz.z*eye.z); // Vector3DotProduct(vz, eye) - result.m15 = 1.0f; - - return result; -} - -// Get float array of matrix data -RMAPI float16 MatrixToFloatV(Matrix mat) -{ - float16 result = { 0 }; - - result.v[0] = mat.m0; - result.v[1] = mat.m1; - result.v[2] = mat.m2; - result.v[3] = mat.m3; - result.v[4] = mat.m4; - result.v[5] = mat.m5; - result.v[6] = mat.m6; - result.v[7] = mat.m7; - result.v[8] = mat.m8; - result.v[9] = mat.m9; - result.v[10] = mat.m10; - result.v[11] = mat.m11; - result.v[12] = mat.m12; - result.v[13] = mat.m13; - result.v[14] = mat.m14; - result.v[15] = mat.m15; - - return result; -} - -//---------------------------------------------------------------------------------- -// Module Functions Definition - Quaternion math -//---------------------------------------------------------------------------------- - -// Add two quaternions -RMAPI Quaternion QuaternionAdd(Quaternion q1, Quaternion q2) -{ - Quaternion result = {q1.x + q2.x, q1.y + q2.y, q1.z + q2.z, q1.w + q2.w}; - - return result; -} - -// Add quaternion and float value -RMAPI Quaternion QuaternionAddValue(Quaternion q, float add) -{ - Quaternion result = {q.x + add, q.y + add, q.z + add, q.w + add}; - - return result; -} - -// Subtract two quaternions -RMAPI Quaternion QuaternionSubtract(Quaternion q1, Quaternion q2) -{ - Quaternion result = {q1.x - q2.x, q1.y - q2.y, q1.z - q2.z, q1.w - q2.w}; - - return result; -} - -// Subtract quaternion and float value -RMAPI Quaternion QuaternionSubtractValue(Quaternion q, float sub) -{ - Quaternion result = {q.x - sub, q.y - sub, q.z - sub, q.w - sub}; - - return result; -} - -// Get identity quaternion -RMAPI Quaternion QuaternionIdentity(void) -{ - Quaternion result = { 0.0f, 0.0f, 0.0f, 1.0f }; - - return result; -} - -// Computes the length of a quaternion -RMAPI float QuaternionLength(Quaternion q) -{ - float result = sqrtf(q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w); - - return result; -} - -// Normalize provided quaternion -RMAPI Quaternion QuaternionNormalize(Quaternion q) -{ - Quaternion result = { 0 }; - - float length = sqrtf(q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w); - if (length == 0.0f) length = 1.0f; - float ilength = 1.0f/length; - - result.x = q.x*ilength; - result.y = q.y*ilength; - result.z = q.z*ilength; - result.w = q.w*ilength; - - return result; -} - -// Invert provided quaternion -RMAPI Quaternion QuaternionInvert(Quaternion q) -{ - Quaternion result = q; - - float lengthSq = q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w; - - if (lengthSq != 0.0f) - { - float invLength = 1.0f/lengthSq; - - result.x *= -invLength; - result.y *= -invLength; - result.z *= -invLength; - result.w *= invLength; - } - - return result; -} - -// Calculate two quaternion multiplication -RMAPI Quaternion QuaternionMultiply(Quaternion q1, Quaternion q2) -{ - Quaternion result = { 0 }; - - float qax = q1.x, qay = q1.y, qaz = q1.z, qaw = q1.w; - float qbx = q2.x, qby = q2.y, qbz = q2.z, qbw = q2.w; - - result.x = qax*qbw + qaw*qbx + qay*qbz - qaz*qby; - result.y = qay*qbw + qaw*qby + qaz*qbx - qax*qbz; - result.z = qaz*qbw + qaw*qbz + qax*qby - qay*qbx; - result.w = qaw*qbw - qax*qbx - qay*qby - qaz*qbz; - - return result; -} - -// Scale quaternion by float value -RMAPI Quaternion QuaternionScale(Quaternion q, float mul) -{ - Quaternion result = { 0 }; - - result.x = q.x*mul; - result.y = q.y*mul; - result.z = q.z*mul; - result.w = q.w*mul; - - return result; -} - -// Divide two quaternions -RMAPI Quaternion QuaternionDivide(Quaternion q1, Quaternion q2) -{ - Quaternion result = { q1.x/q2.x, q1.y/q2.y, q1.z/q2.z, q1.w/q2.w }; - - return result; -} - -// Calculate linear interpolation between two quaternions -RMAPI Quaternion QuaternionLerp(Quaternion q1, Quaternion q2, float amount) -{ - Quaternion result = { 0 }; - - result.x = q1.x + amount*(q2.x - q1.x); - result.y = q1.y + amount*(q2.y - q1.y); - result.z = q1.z + amount*(q2.z - q1.z); - result.w = q1.w + amount*(q2.w - q1.w); - - return result; -} - -// Calculate slerp-optimized interpolation between two quaternions -RMAPI Quaternion QuaternionNlerp(Quaternion q1, Quaternion q2, float amount) -{ - Quaternion result = { 0 }; - - // QuaternionLerp(q1, q2, amount) - result.x = q1.x + amount*(q2.x - q1.x); - result.y = q1.y + amount*(q2.y - q1.y); - result.z = q1.z + amount*(q2.z - q1.z); - result.w = q1.w + amount*(q2.w - q1.w); - - // QuaternionNormalize(q); - Quaternion q = result; - float length = sqrtf(q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w); - if (length == 0.0f) length = 1.0f; - float ilength = 1.0f/length; - - result.x = q.x*ilength; - result.y = q.y*ilength; - result.z = q.z*ilength; - result.w = q.w*ilength; - - return result; -} - -// Calculates spherical linear interpolation between two quaternions -RMAPI Quaternion QuaternionSlerp(Quaternion q1, Quaternion q2, float amount) -{ - Quaternion result = { 0 }; - -#if !defined(EPSILON) - #define EPSILON 0.000001f -#endif - - float cosHalfTheta = q1.x*q2.x + q1.y*q2.y + q1.z*q2.z + q1.w*q2.w; - - if (cosHalfTheta < 0) - { - q2.x = -q2.x; q2.y = -q2.y; q2.z = -q2.z; q2.w = -q2.w; - cosHalfTheta = -cosHalfTheta; - } - - if (fabsf(cosHalfTheta) >= 1.0f) result = q1; - else if (cosHalfTheta > 0.95f) result = QuaternionNlerp(q1, q2, amount); - else - { - float halfTheta = acosf(cosHalfTheta); - float sinHalfTheta = sqrtf(1.0f - cosHalfTheta*cosHalfTheta); - - if (fabsf(sinHalfTheta) < EPSILON) - { - result.x = (q1.x*0.5f + q2.x*0.5f); - result.y = (q1.y*0.5f + q2.y*0.5f); - result.z = (q1.z*0.5f + q2.z*0.5f); - result.w = (q1.w*0.5f + q2.w*0.5f); - } - else - { - float ratioA = sinf((1 - amount)*halfTheta)/sinHalfTheta; - float ratioB = sinf(amount*halfTheta)/sinHalfTheta; - - result.x = (q1.x*ratioA + q2.x*ratioB); - result.y = (q1.y*ratioA + q2.y*ratioB); - result.z = (q1.z*ratioA + q2.z*ratioB); - result.w = (q1.w*ratioA + q2.w*ratioB); - } - } - - return result; -} - -// Calculate quaternion cubic spline interpolation using Cubic Hermite Spline algorithm -// as described in the GLTF 2.0 specification: https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#interpolation-cubic -RMAPI Quaternion QuaternionCubicHermiteSpline(Quaternion q1, Quaternion outTangent1, Quaternion q2, Quaternion inTangent2, float t) -{ - float t2 = t*t; - float t3 = t2*t; - float h00 = 2*t3 - 3*t2 + 1; - float h10 = t3 - 2*t2 + t; - float h01 = -2*t3 + 3*t2; - float h11 = t3 - t2; - - Quaternion p0 = QuaternionScale(q1, h00); - Quaternion m0 = QuaternionScale(outTangent1, h10); - Quaternion p1 = QuaternionScale(q2, h01); - Quaternion m1 = QuaternionScale(inTangent2, h11); - - Quaternion result = { 0 }; - - result = QuaternionAdd(p0, m0); - result = QuaternionAdd(result, p1); - result = QuaternionAdd(result, m1); - result = QuaternionNormalize(result); - - return result; -} - -// Calculate quaternion based on the rotation from one vector to another -RMAPI Quaternion QuaternionFromVector3ToVector3(Vector3 from, Vector3 to) -{ - Quaternion result = { 0 }; - - float cos2Theta = (from.x*to.x + from.y*to.y + from.z*to.z); // Vector3DotProduct(from, to) - Vector3 cross = { from.y*to.z - from.z*to.y, from.z*to.x - from.x*to.z, from.x*to.y - from.y*to.x }; // Vector3CrossProduct(from, to) - - result.x = cross.x; - result.y = cross.y; - result.z = cross.z; - result.w = 1.0f + cos2Theta; - - // QuaternionNormalize(q); - // NOTE: Normalize to essentially nlerp the original and identity to 0.5 - Quaternion q = result; - float length = sqrtf(q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w); - if (length == 0.0f) length = 1.0f; - float ilength = 1.0f/length; - - result.x = q.x*ilength; - result.y = q.y*ilength; - result.z = q.z*ilength; - result.w = q.w*ilength; - - return result; -} - -// Get a quaternion for a given rotation matrix -RMAPI Quaternion QuaternionFromMatrix(Matrix mat) -{ - Quaternion result = { 0 }; - - float fourWSquaredMinus1 = mat.m0 + mat.m5 + mat.m10; - float fourXSquaredMinus1 = mat.m0 - mat.m5 - mat.m10; - float fourYSquaredMinus1 = mat.m5 - mat.m0 - mat.m10; - float fourZSquaredMinus1 = mat.m10 - mat.m0 - mat.m5; - - int biggestIndex = 0; - float fourBiggestSquaredMinus1 = fourWSquaredMinus1; - if (fourXSquaredMinus1 > fourBiggestSquaredMinus1) - { - fourBiggestSquaredMinus1 = fourXSquaredMinus1; - biggestIndex = 1; - } - - if (fourYSquaredMinus1 > fourBiggestSquaredMinus1) - { - fourBiggestSquaredMinus1 = fourYSquaredMinus1; - biggestIndex = 2; - } - - if (fourZSquaredMinus1 > fourBiggestSquaredMinus1) - { - fourBiggestSquaredMinus1 = fourZSquaredMinus1; - biggestIndex = 3; - } - - float biggestVal = sqrtf(fourBiggestSquaredMinus1 + 1.0f)*0.5f; - float mult = 0.25f/biggestVal; - - switch (biggestIndex) - { - case 0: - result.w = biggestVal; - result.x = (mat.m6 - mat.m9)*mult; - result.y = (mat.m8 - mat.m2)*mult; - result.z = (mat.m1 - mat.m4)*mult; - break; - case 1: - result.x = biggestVal; - result.w = (mat.m6 - mat.m9)*mult; - result.y = (mat.m1 + mat.m4)*mult; - result.z = (mat.m8 + mat.m2)*mult; - break; - case 2: - result.y = biggestVal; - result.w = (mat.m8 - mat.m2)*mult; - result.x = (mat.m1 + mat.m4)*mult; - result.z = (mat.m6 + mat.m9)*mult; - break; - case 3: - result.z = biggestVal; - result.w = (mat.m1 - mat.m4)*mult; - result.x = (mat.m8 + mat.m2)*mult; - result.y = (mat.m6 + mat.m9)*mult; - break; - } - - return result; -} - -// Get a matrix for a given quaternion -RMAPI Matrix QuaternionToMatrix(Quaternion q) -{ - Matrix result = { 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f }; // MatrixIdentity() - - float a2 = q.x*q.x; - float b2 = q.y*q.y; - float c2 = q.z*q.z; - float ac = q.x*q.z; - float ab = q.x*q.y; - float bc = q.y*q.z; - float ad = q.w*q.x; - float bd = q.w*q.y; - float cd = q.w*q.z; - - result.m0 = 1 - 2*(b2 + c2); - result.m1 = 2*(ab + cd); - result.m2 = 2*(ac - bd); - - result.m4 = 2*(ab - cd); - result.m5 = 1 - 2*(a2 + c2); - result.m6 = 2*(bc + ad); - - result.m8 = 2*(ac + bd); - result.m9 = 2*(bc - ad); - result.m10 = 1 - 2*(a2 + b2); - - return result; -} - -// Get rotation quaternion for an angle and axis -// NOTE: Angle must be provided in radians -RMAPI Quaternion QuaternionFromAxisAngle(Vector3 axis, float angle) -{ - Quaternion result = { 0.0f, 0.0f, 0.0f, 1.0f }; - - float axisLength = sqrtf(axis.x*axis.x + axis.y*axis.y + axis.z*axis.z); - - if (axisLength != 0.0f) - { - angle *= 0.5f; - - float length = 0.0f; - float ilength = 0.0f; - - // Vector3Normalize(axis) - length = axisLength; - if (length == 0.0f) length = 1.0f; - ilength = 1.0f/length; - axis.x *= ilength; - axis.y *= ilength; - axis.z *= ilength; - - float sinres = sinf(angle); - float cosres = cosf(angle); - - result.x = axis.x*sinres; - result.y = axis.y*sinres; - result.z = axis.z*sinres; - result.w = cosres; - - // QuaternionNormalize(q); - Quaternion q = result; - length = sqrtf(q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w); - if (length == 0.0f) length = 1.0f; - ilength = 1.0f/length; - result.x = q.x*ilength; - result.y = q.y*ilength; - result.z = q.z*ilength; - result.w = q.w*ilength; - } - - return result; -} - -// Get the rotation angle and axis for a given quaternion -RMAPI void QuaternionToAxisAngle(Quaternion q, Vector3 *outAxis, float *outAngle) -{ - if (fabsf(q.w) > 1.0f) - { - // QuaternionNormalize(q); - float length = sqrtf(q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w); - if (length == 0.0f) length = 1.0f; - float ilength = 1.0f/length; - - q.x = q.x*ilength; - q.y = q.y*ilength; - q.z = q.z*ilength; - q.w = q.w*ilength; - } - - Vector3 resAxis = { 0.0f, 0.0f, 0.0f }; - float resAngle = 2.0f*acosf(q.w); - float den = sqrtf(1.0f - q.w*q.w); - - if (den > EPSILON) - { - resAxis.x = q.x/den; - resAxis.y = q.y/den; - resAxis.z = q.z/den; - } - else - { - // This occurs when the angle is zero. - // Not a problem: just set an arbitrary normalized axis. - resAxis.x = 1.0f; - } - - *outAxis = resAxis; - *outAngle = resAngle; -} - -// Get the quaternion equivalent to Euler angles -// NOTE: Rotation order is ZYX -RMAPI Quaternion QuaternionFromEuler(float pitch, float yaw, float roll) -{ - Quaternion result = { 0 }; - - float x0 = cosf(pitch*0.5f); - float x1 = sinf(pitch*0.5f); - float y0 = cosf(yaw*0.5f); - float y1 = sinf(yaw*0.5f); - float z0 = cosf(roll*0.5f); - float z1 = sinf(roll*0.5f); - - result.x = x1*y0*z0 - x0*y1*z1; - result.y = x0*y1*z0 + x1*y0*z1; - result.z = x0*y0*z1 - x1*y1*z0; - result.w = x0*y0*z0 + x1*y1*z1; - - return result; -} - -// Get the Euler angles equivalent to quaternion (roll, pitch, yaw) -// NOTE: Angles are returned in a Vector3 struct in radians -RMAPI Vector3 QuaternionToEuler(Quaternion q) -{ - Vector3 result = { 0 }; - - // Roll (x-axis rotation) - float x0 = 2.0f*(q.w*q.x + q.y*q.z); - float x1 = 1.0f - 2.0f*(q.x*q.x + q.y*q.y); - result.x = atan2f(x0, x1); - - // Pitch (y-axis rotation) - float y0 = 2.0f*(q.w*q.y - q.z*q.x); - y0 = y0 > 1.0f ? 1.0f : y0; - y0 = y0 < -1.0f ? -1.0f : y0; - result.y = asinf(y0); - - // Yaw (z-axis rotation) - float z0 = 2.0f*(q.w*q.z + q.x*q.y); - float z1 = 1.0f - 2.0f*(q.y*q.y + q.z*q.z); - result.z = atan2f(z0, z1); - - return result; -} - -// Transform a quaternion given a transformation matrix -RMAPI Quaternion QuaternionTransform(Quaternion q, Matrix mat) -{ - Quaternion result = { 0 }; - - result.x = mat.m0*q.x + mat.m4*q.y + mat.m8*q.z + mat.m12*q.w; - result.y = mat.m1*q.x + mat.m5*q.y + mat.m9*q.z + mat.m13*q.w; - result.z = mat.m2*q.x + mat.m6*q.y + mat.m10*q.z + mat.m14*q.w; - result.w = mat.m3*q.x + mat.m7*q.y + mat.m11*q.z + mat.m15*q.w; - - return result; -} - -// Check whether two given quaternions are almost equal -RMAPI int QuaternionEquals(Quaternion p, Quaternion q) -{ -#if !defined(EPSILON) - #define EPSILON 0.000001f -#endif - - int result = (((fabsf(p.x - q.x)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.x), fabsf(q.x))))) && - ((fabsf(p.y - q.y)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.y), fabsf(q.y))))) && - ((fabsf(p.z - q.z)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.z), fabsf(q.z))))) && - ((fabsf(p.w - q.w)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.w), fabsf(q.w)))))) || - (((fabsf(p.x + q.x)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.x), fabsf(q.x))))) && - ((fabsf(p.y + q.y)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.y), fabsf(q.y))))) && - ((fabsf(p.z + q.z)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.z), fabsf(q.z))))) && - ((fabsf(p.w + q.w)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.w), fabsf(q.w)))))); - - return result; -} - -// Decompose a transformation matrix into its rotational, translational and scaling components -RMAPI void MatrixDecompose(Matrix mat, Vector3 *translation, Quaternion *rotation, Vector3 *scale) -{ - // Extract translation. - translation->x = mat.m12; - translation->y = mat.m13; - translation->z = mat.m14; - - // Extract upper-left for determinant computation - const float a = mat.m0; - const float b = mat.m4; - const float c = mat.m8; - const float d = mat.m1; - const float e = mat.m5; - const float f = mat.m9; - const float g = mat.m2; - const float h = mat.m6; - const float i = mat.m10; - const float A = e*i - f*h; - const float B = f*g - d*i; - const float C = d*h - e*g; - - // Extract scale - const float det = a*A + b*B + c*C; - Vector3 abc = { a, b, c }; - Vector3 def = { d, e, f }; - Vector3 ghi = { g, h, i }; - - float scalex = Vector3Length(abc); - float scaley = Vector3Length(def); - float scalez = Vector3Length(ghi); - Vector3 s = { scalex, scaley, scalez }; - - if (det < 0) s = Vector3Negate(s); - - *scale = s; - - // Remove scale from the matrix if it is not close to zero - Matrix clone = mat; - if (!FloatEquals(det, 0)) - { - clone.m0 /= s.x; - clone.m4 /= s.x; - clone.m8 /= s.x; - clone.m1 /= s.y; - clone.m5 /= s.y; - clone.m9 /= s.y; - clone.m2 /= s.z; - clone.m6 /= s.z; - clone.m10 /= s.z; - - // Extract rotation - *rotation = QuaternionFromMatrix(clone); - } - else - { - // Set to identity if close to zero - *rotation = QuaternionIdentity(); - } -} - -#if defined(__cplusplus) && !defined(RAYMATH_DISABLE_CPP_OPERATORS) - -// Optional C++ math operators -//------------------------------------------------------------------------------- - -// Vector2 operators -static constexpr Vector2 Vector2Zeros = { 0, 0 }; -static constexpr Vector2 Vector2Ones = { 1, 1 }; -static constexpr Vector2 Vector2UnitX = { 1, 0 }; -static constexpr Vector2 Vector2UnitY = { 0, 1 }; - -inline Vector2 operator + (const Vector2& lhs, const Vector2& rhs) -{ - return Vector2Add(lhs, rhs); -} - -inline const Vector2& operator += (Vector2& lhs, const Vector2& rhs) -{ - lhs = Vector2Add(lhs, rhs); - return lhs; -} - -inline Vector2 operator - (const Vector2& lhs, const Vector2& rhs) -{ - return Vector2Subtract(lhs, rhs); -} - -inline const Vector2& operator -= (Vector2& lhs, const Vector2& rhs) -{ - lhs = Vector2Subtract(lhs, rhs); - return lhs; -} - -inline Vector2 operator * (const Vector2& lhs, const float& rhs) -{ - return Vector2Scale(lhs, rhs); -} - -inline const Vector2& operator *= (Vector2& lhs, const float& rhs) -{ - lhs = Vector2Scale(lhs, rhs); - return lhs; -} - -inline Vector2 operator * (const Vector2& lhs, const Vector2& rhs) -{ - return Vector2Multiply(lhs, rhs); -} - -inline const Vector2& operator *= (Vector2& lhs, const Vector2& rhs) -{ - lhs = Vector2Multiply(lhs, rhs); - return lhs; -} - -inline Vector2 operator * (const Vector2& lhs, const Matrix& rhs) -{ - return Vector2Transform(lhs, rhs); -} - -inline const Vector2& operator *= (Vector2& lhs, const Matrix& rhs) -{ - lhs = Vector2Transform(lhs, rhs); - return lhs; -} - -inline Vector2 operator / (const Vector2& lhs, const float& rhs) -{ - return Vector2Scale(lhs, 1.0f / rhs); -} - -inline const Vector2& operator /= (Vector2& lhs, const float& rhs) -{ - lhs = Vector2Scale(lhs, 1.0f / rhs); - return lhs; -} - -inline Vector2 operator / (const Vector2& lhs, const Vector2& rhs) -{ - return Vector2Divide(lhs, rhs); -} - -inline const Vector2& operator /= (Vector2& lhs, const Vector2& rhs) -{ - lhs = Vector2Divide(lhs, rhs); - return lhs; -} - -inline bool operator == (const Vector2& lhs, const Vector2& rhs) -{ - return FloatEquals(lhs.x, rhs.x) && FloatEquals(lhs.y, rhs.y); -} - -inline bool operator != (const Vector2& lhs, const Vector2& rhs) -{ - return !FloatEquals(lhs.x, rhs.x) || !FloatEquals(lhs.y, rhs.y); -} - -// Vector3 operators -static constexpr Vector3 Vector3Zeros = { 0, 0, 0 }; -static constexpr Vector3 Vector3Ones = { 1, 1, 1 }; -static constexpr Vector3 Vector3UnitX = { 1, 0, 0 }; -static constexpr Vector3 Vector3UnitY = { 0, 1, 0 }; -static constexpr Vector3 Vector3UnitZ = { 0, 0, 1 }; - -inline Vector3 operator + (const Vector3& lhs, const Vector3& rhs) -{ - return Vector3Add(lhs, rhs); -} - -inline const Vector3& operator += (Vector3& lhs, const Vector3& rhs) -{ - lhs = Vector3Add(lhs, rhs); - return lhs; -} - -inline Vector3 operator - (const Vector3& lhs, const Vector3& rhs) -{ - return Vector3Subtract(lhs, rhs); -} - -inline const Vector3& operator -= (Vector3& lhs, const Vector3& rhs) -{ - lhs = Vector3Subtract(lhs, rhs); - return lhs; -} - -inline Vector3 operator * (const Vector3& lhs, const float& rhs) -{ - return Vector3Scale(lhs, rhs); -} - -inline const Vector3& operator *= (Vector3& lhs, const float& rhs) -{ - lhs = Vector3Scale(lhs, rhs); - return lhs; -} - -inline Vector3 operator * (const Vector3& lhs, const Vector3& rhs) -{ - return Vector3Multiply(lhs, rhs); -} - -inline const Vector3& operator *= (Vector3& lhs, const Vector3& rhs) -{ - lhs = Vector3Multiply(lhs, rhs); - return lhs; -} - -inline Vector3 operator * (const Vector3& lhs, const Matrix& rhs) -{ - return Vector3Transform(lhs, rhs); -} - -inline const Vector3& operator *= (Vector3& lhs, const Matrix& rhs) -{ - lhs = Vector3Transform(lhs, rhs); - return lhs; -} - -inline Vector3 operator / (const Vector3& lhs, const float& rhs) -{ - return Vector3Scale(lhs, 1.0f / rhs); -} - -inline const Vector3& operator /= (Vector3& lhs, const float& rhs) -{ - lhs = Vector3Scale(lhs, 1.0f / rhs); - return lhs; -} - -inline Vector3 operator / (const Vector3& lhs, const Vector3& rhs) -{ - return Vector3Divide(lhs, rhs); -} - -inline const Vector3& operator /= (Vector3& lhs, const Vector3& rhs) -{ - lhs = Vector3Divide(lhs, rhs); - return lhs; -} - -inline bool operator == (const Vector3& lhs, const Vector3& rhs) -{ - return FloatEquals(lhs.x, rhs.x) && FloatEquals(lhs.y, rhs.y) && FloatEquals(lhs.z, rhs.z); -} - -inline bool operator != (const Vector3& lhs, const Vector3& rhs) -{ - return !FloatEquals(lhs.x, rhs.x) || !FloatEquals(lhs.y, rhs.y) || !FloatEquals(lhs.z, rhs.z); -} - -// Vector4 operators -static constexpr Vector4 Vector4Zeros = { 0, 0, 0, 0 }; -static constexpr Vector4 Vector4Ones = { 1, 1, 1, 1 }; -static constexpr Vector4 Vector4UnitX = { 1, 0, 0, 0 }; -static constexpr Vector4 Vector4UnitY = { 0, 1, 0, 0 }; -static constexpr Vector4 Vector4UnitZ = { 0, 0, 1, 0 }; -static constexpr Vector4 Vector4UnitW = { 0, 0, 0, 1 }; - -inline Vector4 operator + (const Vector4& lhs, const Vector4& rhs) -{ - return Vector4Add(lhs, rhs); -} - -inline const Vector4& operator += (Vector4& lhs, const Vector4& rhs) -{ - lhs = Vector4Add(lhs, rhs); - return lhs; -} - -inline Vector4 operator - (const Vector4& lhs, const Vector4& rhs) -{ - return Vector4Subtract(lhs, rhs); -} - -inline const Vector4& operator -= (Vector4& lhs, const Vector4& rhs) -{ - lhs = Vector4Subtract(lhs, rhs); - return lhs; -} - -inline Vector4 operator * (const Vector4& lhs, const float& rhs) -{ - return Vector4Scale(lhs, rhs); -} - -inline const Vector4& operator *= (Vector4& lhs, const float& rhs) -{ - lhs = Vector4Scale(lhs, rhs); - return lhs; -} - -inline Vector4 operator * (const Vector4& lhs, const Vector4& rhs) -{ - return Vector4Multiply(lhs, rhs); -} - -inline const Vector4& operator *= (Vector4& lhs, const Vector4& rhs) -{ - lhs = Vector4Multiply(lhs, rhs); - return lhs; -} - -inline Vector4 operator / (const Vector4& lhs, const float& rhs) -{ - return Vector4Scale(lhs, 1.0f / rhs); -} - -inline const Vector4& operator /= (Vector4& lhs, const float& rhs) -{ - lhs = Vector4Scale(lhs, 1.0f / rhs); - return lhs; -} - -inline Vector4 operator / (const Vector4& lhs, const Vector4& rhs) -{ - return Vector4Divide(lhs, rhs); -} - -inline const Vector4& operator /= (Vector4& lhs, const Vector4& rhs) -{ - lhs = Vector4Divide(lhs, rhs); - return lhs; -} - -inline bool operator == (const Vector4& lhs, const Vector4& rhs) -{ - return FloatEquals(lhs.x, rhs.x) && FloatEquals(lhs.y, rhs.y) && FloatEquals(lhs.z, rhs.z) && FloatEquals(lhs.w, rhs.w); -} - -inline bool operator != (const Vector4& lhs, const Vector4& rhs) -{ - return !FloatEquals(lhs.x, rhs.x) || !FloatEquals(lhs.y, rhs.y) || !FloatEquals(lhs.z, rhs.z) || !FloatEquals(lhs.w, rhs.w); -} - -// Quaternion operators -static constexpr Quaternion QuaternionZeros = { 0, 0, 0, 0 }; -static constexpr Quaternion QuaternionOnes = { 1, 1, 1, 1 }; -static constexpr Quaternion QuaternionUnitX = { 0, 0, 0, 1 }; - -inline Quaternion operator + (const Quaternion& lhs, const float& rhs) -{ - return QuaternionAddValue(lhs, rhs); -} - -inline const Quaternion& operator += (Quaternion& lhs, const float& rhs) -{ - lhs = QuaternionAddValue(lhs, rhs); - return lhs; -} - -inline Quaternion operator - (const Quaternion& lhs, const float& rhs) -{ - return QuaternionSubtractValue(lhs, rhs); -} - -inline const Quaternion& operator -= (Quaternion& lhs, const float& rhs) -{ - lhs = QuaternionSubtractValue(lhs, rhs); - return lhs; -} - -inline Quaternion operator * (const Quaternion& lhs, const Matrix& rhs) -{ - return QuaternionTransform(lhs, rhs); -} - -inline const Quaternion& operator *= (Quaternion& lhs, const Matrix& rhs) -{ - lhs = QuaternionTransform(lhs, rhs); - return lhs; -} - -// Matrix operators -inline Matrix operator + (const Matrix& lhs, const Matrix& rhs) -{ - return MatrixAdd(lhs, rhs); -} - -inline const Matrix& operator += (Matrix& lhs, const Matrix& rhs) -{ - lhs = MatrixAdd(lhs, rhs); - return lhs; -} - -inline Matrix operator - (const Matrix& lhs, const Matrix& rhs) -{ - return MatrixSubtract(lhs, rhs); -} - -inline const Matrix& operator -= (Matrix& lhs, const Matrix& rhs) -{ - lhs = MatrixSubtract(lhs, rhs); - return lhs; -} - -inline Matrix operator * (const Matrix& lhs, const Matrix& rhs) -{ - return MatrixMultiply(lhs, rhs); -} - -inline const Matrix& operator *= (Matrix& lhs, const Matrix& rhs) -{ - lhs = MatrixMultiply(lhs, rhs); - return lhs; -} -//------------------------------------------------------------------------------- -#endif // C++ operators - -#endif // RAYMATH_H diff --git a/third_party/raylib/include/rlgl.h b/third_party/raylib/include/rlgl.h deleted file mode 100644 index 92971df627..0000000000 --- a/third_party/raylib/include/rlgl.h +++ /dev/null @@ -1,5262 +0,0 @@ -/********************************************************************************************** -* -* rlgl v5.0 - A multi-OpenGL abstraction layer with an immediate-mode style API -* -* DESCRIPTION: -* An abstraction layer for multiple OpenGL versions (1.1, 2.1, 3.3 Core, 4.3 Core, ES 2.0, ES 3.0) -* that provides a pseudo-OpenGL 1.1 immediate-mode style API (rlVertex, rlTranslate, rlRotate...) -* -* ADDITIONAL NOTES: -* When choosing an OpenGL backend different than OpenGL 1.1, some internal buffer are -* initialized on rlglInit() to accumulate vertex data -* -* When an internal state change is required all the stored vertex data is renderer in batch, -* additionally, rlDrawRenderBatchActive() could be called to force flushing of the batch -* -* Some resources are also loaded for convenience, here the complete list: -* - Default batch (RLGL.defaultBatch): RenderBatch system to accumulate vertex data -* - Default texture (RLGL.defaultTextureId): 1x1 white pixel R8G8B8A8 -* - Default shader (RLGL.State.defaultShaderId, RLGL.State.defaultShaderLocs) -* -* Internal buffer (and resources) must be manually unloaded calling rlglClose() -* -* CONFIGURATION: -* #define GRAPHICS_API_OPENGL_11 -* #define GRAPHICS_API_OPENGL_21 -* #define GRAPHICS_API_OPENGL_33 -* #define GRAPHICS_API_OPENGL_43 -* #define GRAPHICS_API_OPENGL_ES2 -* #define GRAPHICS_API_OPENGL_ES3 -* Use selected OpenGL graphics backend, should be supported by platform -* Those preprocessor defines are only used on rlgl module, if OpenGL version is -* required by any other module, use rlGetVersion() to check it -* -* #define RLGL_IMPLEMENTATION -* Generates the implementation of the library into the included file -* If not defined, the library is in header only mode and can be included in other headers -* or source files without problems. But only ONE file should hold the implementation -* -* #define RLGL_RENDER_TEXTURES_HINT -* Enable framebuffer objects (fbo) support (enabled by default) -* Some GPUs could not support them despite the OpenGL version -* -* #define RLGL_SHOW_GL_DETAILS_INFO -* Show OpenGL extensions and capabilities detailed logs on init -* -* #define RLGL_ENABLE_OPENGL_DEBUG_CONTEXT -* Enable debug context (only available on OpenGL 4.3) -* -* rlgl capabilities could be customized just defining some internal -* values before library inclusion (default values listed): -* -* #define RL_DEFAULT_BATCH_BUFFER_ELEMENTS 8192 // Default internal render batch elements limits -* #define RL_DEFAULT_BATCH_BUFFERS 1 // Default number of batch buffers (multi-buffering) -* #define RL_DEFAULT_BATCH_DRAWCALLS 256 // Default number of batch draw calls (by state changes: mode, texture) -* #define RL_DEFAULT_BATCH_MAX_TEXTURE_UNITS 4 // Maximum number of textures units that can be activated on batch drawing (SetShaderValueTexture()) -* -* #define RL_MAX_MATRIX_STACK_SIZE 32 // Maximum size of internal Matrix stack -* #define RL_MAX_SHADER_LOCATIONS 32 // Maximum number of shader locations supported -* #define RL_CULL_DISTANCE_NEAR 0.01 // Default projection matrix near cull distance -* #define RL_CULL_DISTANCE_FAR 1000.0 // Default projection matrix far cull distance -* -* When loading a shader, the following vertex attributes and uniform -* location names are tried to be set automatically: -* -* #define RL_DEFAULT_SHADER_ATTRIB_NAME_POSITION "vertexPosition" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_LOCATION_POSITION -* #define RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD "vertexTexCoord" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD -* #define RL_DEFAULT_SHADER_ATTRIB_NAME_NORMAL "vertexNormal" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_LOCATION_NORMAL -* #define RL_DEFAULT_SHADER_ATTRIB_NAME_COLOR "vertexColor" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_LOCATION_COLOR -* #define RL_DEFAULT_SHADER_ATTRIB_NAME_TANGENT "vertexTangent" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_LOCATION_TANGENT -* #define RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD2 "vertexTexCoord2" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD2 -* #define RL_DEFAULT_SHADER_ATTRIB_NAME_BONEIDS "vertexBoneIds" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_LOCATION_BONEIDS -* #define RL_DEFAULT_SHADER_ATTRIB_NAME_BONEWEIGHTS "vertexBoneWeights" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_LOCATION_BONEWEIGHTS -* #define RL_DEFAULT_SHADER_UNIFORM_NAME_MVP "mvp" // model-view-projection matrix -* #define RL_DEFAULT_SHADER_UNIFORM_NAME_VIEW "matView" // view matrix -* #define RL_DEFAULT_SHADER_UNIFORM_NAME_PROJECTION "matProjection" // projection matrix -* #define RL_DEFAULT_SHADER_UNIFORM_NAME_MODEL "matModel" // model matrix -* #define RL_DEFAULT_SHADER_UNIFORM_NAME_NORMAL "matNormal" // normal matrix (transpose(inverse(matModelView))) -* #define RL_DEFAULT_SHADER_UNIFORM_NAME_COLOR "colDiffuse" // color diffuse (base tint color, multiplied by texture color) -* #define RL_DEFAULT_SHADER_UNIFORM_NAME_BONE_MATRICES "boneMatrices" // bone matrices -* #define RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE0 "texture0" // texture0 (texture slot active 0) -* #define RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE1 "texture1" // texture1 (texture slot active 1) -* #define RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE2 "texture2" // texture2 (texture slot active 2) -* -* DEPENDENCIES: -* - OpenGL libraries (depending on platform and OpenGL version selected) -* - GLAD OpenGL extensions loading library (only for OpenGL 3.3 Core, 4.3 Core) -* -* -* LICENSE: zlib/libpng -* -* Copyright (c) 2014-2024 Ramon Santamaria (@raysan5) -* -* This software is provided "as-is", without any express or implied warranty. In no event -* will the authors be held liable for any damages arising from the use of this software. -* -* Permission is granted to anyone to use this software for any purpose, including commercial -* applications, and to alter it and redistribute it freely, subject to the following restrictions: -* -* 1. The origin of this software must not be misrepresented; you must not claim that you -* wrote the original software. If you use this software in a product, an acknowledgment -* in the product documentation would be appreciated but is not required. -* -* 2. Altered source versions must be plainly marked as such, and must not be misrepresented -* as being the original software. -* -* 3. This notice may not be removed or altered from any source distribution. -* -**********************************************************************************************/ - -#ifndef RLGL_H -#define RLGL_H - -#define RLGL_VERSION "5.0" - -// Function specifiers in case library is build/used as a shared library -// NOTE: Microsoft specifiers to tell compiler that symbols are imported/exported from a .dll -// NOTE: visibility(default) attribute makes symbols "visible" when compiled with -fvisibility=hidden -#if defined(_WIN32) && defined(BUILD_LIBTYPE_SHARED) - #define RLAPI __declspec(dllexport) // We are building the library as a Win32 shared library (.dll) -#elif defined(BUILD_LIBTYPE_SHARED) - #define RLAPI __attribute__((visibility("default"))) // We are building the library as a Unix shared library (.so/.dylib) -#elif defined(_WIN32) && defined(USE_LIBTYPE_SHARED) - #define RLAPI __declspec(dllimport) // We are using the library as a Win32 shared library (.dll) -#endif - -// Function specifiers definition -#ifndef RLAPI - #define RLAPI // Functions defined as 'extern' by default (implicit specifiers) -#endif - -// Support TRACELOG macros -#ifndef TRACELOG - #define TRACELOG(level, ...) (void)0 - #define TRACELOGD(...) (void)0 -#endif - -// Allow custom memory allocators -#ifndef RL_MALLOC - #define RL_MALLOC(sz) malloc(sz) -#endif -#ifndef RL_CALLOC - #define RL_CALLOC(n,sz) calloc(n,sz) -#endif -#ifndef RL_REALLOC - #define RL_REALLOC(n,sz) realloc(n,sz) -#endif -#ifndef RL_FREE - #define RL_FREE(p) free(p) -#endif - -// Security check in case no GRAPHICS_API_OPENGL_* defined -#if !defined(GRAPHICS_API_OPENGL_11) && \ - !defined(GRAPHICS_API_OPENGL_21) && \ - !defined(GRAPHICS_API_OPENGL_33) && \ - !defined(GRAPHICS_API_OPENGL_43) && \ - !defined(GRAPHICS_API_OPENGL_ES2) && \ - !defined(GRAPHICS_API_OPENGL_ES3) - #define GRAPHICS_API_OPENGL_33 -#endif - -// Security check in case multiple GRAPHICS_API_OPENGL_* defined -#if defined(GRAPHICS_API_OPENGL_11) - #if defined(GRAPHICS_API_OPENGL_21) - #undef GRAPHICS_API_OPENGL_21 - #endif - #if defined(GRAPHICS_API_OPENGL_33) - #undef GRAPHICS_API_OPENGL_33 - #endif - #if defined(GRAPHICS_API_OPENGL_43) - #undef GRAPHICS_API_OPENGL_43 - #endif - #if defined(GRAPHICS_API_OPENGL_ES2) - #undef GRAPHICS_API_OPENGL_ES2 - #endif -#endif - -// OpenGL 2.1 uses most of OpenGL 3.3 Core functionality -// WARNING: Specific parts are checked with #if defines -#if defined(GRAPHICS_API_OPENGL_21) - #define GRAPHICS_API_OPENGL_33 -#endif - -// OpenGL 4.3 uses OpenGL 3.3 Core functionality -#if defined(GRAPHICS_API_OPENGL_43) - #define GRAPHICS_API_OPENGL_33 -#endif - -// OpenGL ES 3.0 uses OpenGL ES 2.0 functionality (and more) -#if defined(GRAPHICS_API_OPENGL_ES3) - #define GRAPHICS_API_OPENGL_ES2 -#endif - -// Support framebuffer objects by default -// NOTE: Some driver implementation do not support it, despite they should -#define RLGL_RENDER_TEXTURES_HINT - -//---------------------------------------------------------------------------------- -// Defines and Macros -//---------------------------------------------------------------------------------- - -// Default internal render batch elements limits -#ifndef RL_DEFAULT_BATCH_BUFFER_ELEMENTS - #if defined(GRAPHICS_API_OPENGL_11) || defined(GRAPHICS_API_OPENGL_33) - // This is the maximum amount of elements (quads) per batch - // NOTE: Be careful with text, every letter maps to a quad - #define RL_DEFAULT_BATCH_BUFFER_ELEMENTS 8192 - #endif - #if defined(GRAPHICS_API_OPENGL_ES2) - // We reduce memory sizes for embedded systems (RPI and HTML5) - // NOTE: On HTML5 (emscripten) this is allocated on heap, - // by default it's only 16MB!...just take care... - #define RL_DEFAULT_BATCH_BUFFER_ELEMENTS 2048 - #endif -#endif -#ifndef RL_DEFAULT_BATCH_BUFFERS - #define RL_DEFAULT_BATCH_BUFFERS 1 // Default number of batch buffers (multi-buffering) -#endif -#ifndef RL_DEFAULT_BATCH_DRAWCALLS - #define RL_DEFAULT_BATCH_DRAWCALLS 256 // Default number of batch draw calls (by state changes: mode, texture) -#endif -#ifndef RL_DEFAULT_BATCH_MAX_TEXTURE_UNITS - #define RL_DEFAULT_BATCH_MAX_TEXTURE_UNITS 4 // Maximum number of textures units that can be activated on batch drawing (SetShaderValueTexture()) -#endif - -// Internal Matrix stack -#ifndef RL_MAX_MATRIX_STACK_SIZE - #define RL_MAX_MATRIX_STACK_SIZE 32 // Maximum size of Matrix stack -#endif - -// Shader limits -#ifndef RL_MAX_SHADER_LOCATIONS - #define RL_MAX_SHADER_LOCATIONS 32 // Maximum number of shader locations supported -#endif - -// Projection matrix culling -#ifndef RL_CULL_DISTANCE_NEAR - #define RL_CULL_DISTANCE_NEAR 0.01 // Default near cull distance -#endif -#ifndef RL_CULL_DISTANCE_FAR - #define RL_CULL_DISTANCE_FAR 1000.0 // Default far cull distance -#endif - -// Texture parameters (equivalent to OpenGL defines) -#define RL_TEXTURE_WRAP_S 0x2802 // GL_TEXTURE_WRAP_S -#define RL_TEXTURE_WRAP_T 0x2803 // GL_TEXTURE_WRAP_T -#define RL_TEXTURE_MAG_FILTER 0x2800 // GL_TEXTURE_MAG_FILTER -#define RL_TEXTURE_MIN_FILTER 0x2801 // GL_TEXTURE_MIN_FILTER - -#define RL_TEXTURE_FILTER_NEAREST 0x2600 // GL_NEAREST -#define RL_TEXTURE_FILTER_LINEAR 0x2601 // GL_LINEAR -#define RL_TEXTURE_FILTER_MIP_NEAREST 0x2700 // GL_NEAREST_MIPMAP_NEAREST -#define RL_TEXTURE_FILTER_NEAREST_MIP_LINEAR 0x2702 // GL_NEAREST_MIPMAP_LINEAR -#define RL_TEXTURE_FILTER_LINEAR_MIP_NEAREST 0x2701 // GL_LINEAR_MIPMAP_NEAREST -#define RL_TEXTURE_FILTER_MIP_LINEAR 0x2703 // GL_LINEAR_MIPMAP_LINEAR -#define RL_TEXTURE_FILTER_ANISOTROPIC 0x3000 // Anisotropic filter (custom identifier) -#define RL_TEXTURE_MIPMAP_BIAS_RATIO 0x4000 // Texture mipmap bias, percentage ratio (custom identifier) - -#define RL_TEXTURE_WRAP_REPEAT 0x2901 // GL_REPEAT -#define RL_TEXTURE_WRAP_CLAMP 0x812F // GL_CLAMP_TO_EDGE -#define RL_TEXTURE_WRAP_MIRROR_REPEAT 0x8370 // GL_MIRRORED_REPEAT -#define RL_TEXTURE_WRAP_MIRROR_CLAMP 0x8742 // GL_MIRROR_CLAMP_EXT - -// Matrix modes (equivalent to OpenGL) -#define RL_MODELVIEW 0x1700 // GL_MODELVIEW -#define RL_PROJECTION 0x1701 // GL_PROJECTION -#define RL_TEXTURE 0x1702 // GL_TEXTURE - -// Primitive assembly draw modes -#define RL_LINES 0x0001 // GL_LINES -#define RL_TRIANGLES 0x0004 // GL_TRIANGLES -#define RL_QUADS 0x0007 // GL_QUADS - -// GL equivalent data types -#define RL_UNSIGNED_BYTE 0x1401 // GL_UNSIGNED_BYTE -#define RL_FLOAT 0x1406 // GL_FLOAT - -// GL buffer usage hint -#define RL_STREAM_DRAW 0x88E0 // GL_STREAM_DRAW -#define RL_STREAM_READ 0x88E1 // GL_STREAM_READ -#define RL_STREAM_COPY 0x88E2 // GL_STREAM_COPY -#define RL_STATIC_DRAW 0x88E4 // GL_STATIC_DRAW -#define RL_STATIC_READ 0x88E5 // GL_STATIC_READ -#define RL_STATIC_COPY 0x88E6 // GL_STATIC_COPY -#define RL_DYNAMIC_DRAW 0x88E8 // GL_DYNAMIC_DRAW -#define RL_DYNAMIC_READ 0x88E9 // GL_DYNAMIC_READ -#define RL_DYNAMIC_COPY 0x88EA // GL_DYNAMIC_COPY - -// GL Shader type -#define RL_FRAGMENT_SHADER 0x8B30 // GL_FRAGMENT_SHADER -#define RL_VERTEX_SHADER 0x8B31 // GL_VERTEX_SHADER -#define RL_COMPUTE_SHADER 0x91B9 // GL_COMPUTE_SHADER - -// GL blending factors -#define RL_ZERO 0 // GL_ZERO -#define RL_ONE 1 // GL_ONE -#define RL_SRC_COLOR 0x0300 // GL_SRC_COLOR -#define RL_ONE_MINUS_SRC_COLOR 0x0301 // GL_ONE_MINUS_SRC_COLOR -#define RL_SRC_ALPHA 0x0302 // GL_SRC_ALPHA -#define RL_ONE_MINUS_SRC_ALPHA 0x0303 // GL_ONE_MINUS_SRC_ALPHA -#define RL_DST_ALPHA 0x0304 // GL_DST_ALPHA -#define RL_ONE_MINUS_DST_ALPHA 0x0305 // GL_ONE_MINUS_DST_ALPHA -#define RL_DST_COLOR 0x0306 // GL_DST_COLOR -#define RL_ONE_MINUS_DST_COLOR 0x0307 // GL_ONE_MINUS_DST_COLOR -#define RL_SRC_ALPHA_SATURATE 0x0308 // GL_SRC_ALPHA_SATURATE -#define RL_CONSTANT_COLOR 0x8001 // GL_CONSTANT_COLOR -#define RL_ONE_MINUS_CONSTANT_COLOR 0x8002 // GL_ONE_MINUS_CONSTANT_COLOR -#define RL_CONSTANT_ALPHA 0x8003 // GL_CONSTANT_ALPHA -#define RL_ONE_MINUS_CONSTANT_ALPHA 0x8004 // GL_ONE_MINUS_CONSTANT_ALPHA - -// GL blending functions/equations -#define RL_FUNC_ADD 0x8006 // GL_FUNC_ADD -#define RL_MIN 0x8007 // GL_MIN -#define RL_MAX 0x8008 // GL_MAX -#define RL_FUNC_SUBTRACT 0x800A // GL_FUNC_SUBTRACT -#define RL_FUNC_REVERSE_SUBTRACT 0x800B // GL_FUNC_REVERSE_SUBTRACT -#define RL_BLEND_EQUATION 0x8009 // GL_BLEND_EQUATION -#define RL_BLEND_EQUATION_RGB 0x8009 // GL_BLEND_EQUATION_RGB // (Same as BLEND_EQUATION) -#define RL_BLEND_EQUATION_ALPHA 0x883D // GL_BLEND_EQUATION_ALPHA -#define RL_BLEND_DST_RGB 0x80C8 // GL_BLEND_DST_RGB -#define RL_BLEND_SRC_RGB 0x80C9 // GL_BLEND_SRC_RGB -#define RL_BLEND_DST_ALPHA 0x80CA // GL_BLEND_DST_ALPHA -#define RL_BLEND_SRC_ALPHA 0x80CB // GL_BLEND_SRC_ALPHA -#define RL_BLEND_COLOR 0x8005 // GL_BLEND_COLOR - -#define RL_READ_FRAMEBUFFER 0x8CA8 // GL_READ_FRAMEBUFFER -#define RL_DRAW_FRAMEBUFFER 0x8CA9 // GL_DRAW_FRAMEBUFFER - -// Default shader vertex attribute locations -#ifndef RL_DEFAULT_SHADER_ATTRIB_LOCATION_POSITION - #define RL_DEFAULT_SHADER_ATTRIB_LOCATION_POSITION 0 -#endif -#ifndef RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD - #define RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD 1 -#endif -#ifndef RL_DEFAULT_SHADER_ATTRIB_LOCATION_NORMAL - #define RL_DEFAULT_SHADER_ATTRIB_LOCATION_NORMAL 2 -#endif -#ifndef RL_DEFAULT_SHADER_ATTRIB_LOCATION_COLOR - #define RL_DEFAULT_SHADER_ATTRIB_LOCATION_COLOR 3 -#endif - #ifndef RL_DEFAULT_SHADER_ATTRIB_LOCATION_TANGENT -#define RL_DEFAULT_SHADER_ATTRIB_LOCATION_TANGENT 4 -#endif -#ifndef RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD2 - #define RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD2 5 -#endif -#ifndef RL_DEFAULT_SHADER_ATTRIB_LOCATION_INDICES - #define RL_DEFAULT_SHADER_ATTRIB_LOCATION_INDICES 6 -#endif -#ifdef RL_SUPPORT_MESH_GPU_SKINNING -#ifndef RL_DEFAULT_SHADER_ATTRIB_LOCATION_BONEIDS - #define RL_DEFAULT_SHADER_ATTRIB_LOCATION_BONEIDS 7 -#endif -#ifndef RL_DEFAULT_SHADER_ATTRIB_LOCATION_BONEWEIGHTS - #define RL_DEFAULT_SHADER_ATTRIB_LOCATION_BONEWEIGHTS 8 -#endif -#endif - -//---------------------------------------------------------------------------------- -// Types and Structures Definition -//---------------------------------------------------------------------------------- -#if (defined(__STDC__) && __STDC_VERSION__ >= 199901L) || (defined(_MSC_VER) && _MSC_VER >= 1800) - #include -#elif !defined(__cplusplus) && !defined(bool) && !defined(RL_BOOL_TYPE) - // Boolean type -typedef enum bool { false = 0, true = !false } bool; -#endif - -#if !defined(RL_MATRIX_TYPE) -// Matrix, 4x4 components, column major, OpenGL style, right handed -typedef struct Matrix { - float m0, m4, m8, m12; // Matrix first row (4 components) - float m1, m5, m9, m13; // Matrix second row (4 components) - float m2, m6, m10, m14; // Matrix third row (4 components) - float m3, m7, m11, m15; // Matrix fourth row (4 components) -} Matrix; -#define RL_MATRIX_TYPE -#endif - -// Dynamic vertex buffers (position + texcoords + colors + indices arrays) -typedef struct rlVertexBuffer { - int elementCount; // Number of elements in the buffer (QUADS) - - float *vertices; // Vertex position (XYZ - 3 components per vertex) (shader-location = 0) - float *texcoords; // Vertex texture coordinates (UV - 2 components per vertex) (shader-location = 1) - float *normals; // Vertex normal (XYZ - 3 components per vertex) (shader-location = 2) - unsigned char *colors; // Vertex colors (RGBA - 4 components per vertex) (shader-location = 3) -#if defined(GRAPHICS_API_OPENGL_11) || defined(GRAPHICS_API_OPENGL_33) - unsigned int *indices; // Vertex indices (in case vertex data comes indexed) (6 indices per quad) -#endif -#if defined(GRAPHICS_API_OPENGL_ES2) - unsigned short *indices; // Vertex indices (in case vertex data comes indexed) (6 indices per quad) -#endif - unsigned int vaoId; // OpenGL Vertex Array Object id - unsigned int vboId[5]; // OpenGL Vertex Buffer Objects id (5 types of vertex data) -} rlVertexBuffer; - -// Draw call type -// NOTE: Only texture changes register a new draw, other state-change-related elements are not -// used at this moment (vaoId, shaderId, matrices), raylib just forces a batch draw call if any -// of those state-change happens (this is done in core module) -typedef struct rlDrawCall { - int mode; // Drawing mode: LINES, TRIANGLES, QUADS - int vertexCount; // Number of vertex of the draw - int vertexAlignment; // Number of vertex required for index alignment (LINES, TRIANGLES) - //unsigned int vaoId; // Vertex array id to be used on the draw -> Using RLGL.currentBatch->vertexBuffer.vaoId - //unsigned int shaderId; // Shader id to be used on the draw -> Using RLGL.currentShaderId - unsigned int textureId; // Texture id to be used on the draw -> Use to create new draw call if changes - - //Matrix projection; // Projection matrix for this draw -> Using RLGL.projection by default - //Matrix modelview; // Modelview matrix for this draw -> Using RLGL.modelview by default -} rlDrawCall; - -// rlRenderBatch type -typedef struct rlRenderBatch { - int bufferCount; // Number of vertex buffers (multi-buffering support) - int currentBuffer; // Current buffer tracking in case of multi-buffering - rlVertexBuffer *vertexBuffer; // Dynamic buffer(s) for vertex data - - rlDrawCall *draws; // Draw calls array, depends on textureId - int drawCounter; // Draw calls counter - float currentDepth; // Current depth value for next draw -} rlRenderBatch; - -// OpenGL version -typedef enum { - RL_OPENGL_11 = 1, // OpenGL 1.1 - RL_OPENGL_21, // OpenGL 2.1 (GLSL 120) - RL_OPENGL_33, // OpenGL 3.3 (GLSL 330) - RL_OPENGL_43, // OpenGL 4.3 (using GLSL 330) - RL_OPENGL_ES_20, // OpenGL ES 2.0 (GLSL 100) - RL_OPENGL_ES_30 // OpenGL ES 3.0 (GLSL 300 es) -} rlGlVersion; - -// Trace log level -// NOTE: Organized by priority level -typedef enum { - RL_LOG_ALL = 0, // Display all logs - RL_LOG_TRACE, // Trace logging, intended for internal use only - RL_LOG_DEBUG, // Debug logging, used for internal debugging, it should be disabled on release builds - RL_LOG_INFO, // Info logging, used for program execution info - RL_LOG_WARNING, // Warning logging, used on recoverable failures - RL_LOG_ERROR, // Error logging, used on unrecoverable failures - RL_LOG_FATAL, // Fatal logging, used to abort program: exit(EXIT_FAILURE) - RL_LOG_NONE // Disable logging -} rlTraceLogLevel; - -// Texture pixel formats -// NOTE: Support depends on OpenGL version -typedef enum { - RL_PIXELFORMAT_UNCOMPRESSED_GRAYSCALE = 1, // 8 bit per pixel (no alpha) - RL_PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA, // 8*2 bpp (2 channels) - RL_PIXELFORMAT_UNCOMPRESSED_R5G6B5, // 16 bpp - RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8, // 24 bpp - RL_PIXELFORMAT_UNCOMPRESSED_R5G5B5A1, // 16 bpp (1 bit alpha) - RL_PIXELFORMAT_UNCOMPRESSED_R4G4B4A4, // 16 bpp (4 bit alpha) - RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8A8, // 32 bpp - RL_PIXELFORMAT_UNCOMPRESSED_R32, // 32 bpp (1 channel - float) - RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32, // 32*3 bpp (3 channels - float) - RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32A32, // 32*4 bpp (4 channels - float) - RL_PIXELFORMAT_UNCOMPRESSED_R16, // 16 bpp (1 channel - half float) - RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16, // 16*3 bpp (3 channels - half float) - RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16A16, // 16*4 bpp (4 channels - half float) - RL_PIXELFORMAT_COMPRESSED_DXT1_RGB, // 4 bpp (no alpha) - RL_PIXELFORMAT_COMPRESSED_DXT1_RGBA, // 4 bpp (1 bit alpha) - RL_PIXELFORMAT_COMPRESSED_DXT3_RGBA, // 8 bpp - RL_PIXELFORMAT_COMPRESSED_DXT5_RGBA, // 8 bpp - RL_PIXELFORMAT_COMPRESSED_ETC1_RGB, // 4 bpp - RL_PIXELFORMAT_COMPRESSED_ETC2_RGB, // 4 bpp - RL_PIXELFORMAT_COMPRESSED_ETC2_EAC_RGBA, // 8 bpp - RL_PIXELFORMAT_COMPRESSED_PVRT_RGB, // 4 bpp - RL_PIXELFORMAT_COMPRESSED_PVRT_RGBA, // 4 bpp - RL_PIXELFORMAT_COMPRESSED_ASTC_4x4_RGBA, // 8 bpp - RL_PIXELFORMAT_COMPRESSED_ASTC_8x8_RGBA // 2 bpp -} rlPixelFormat; - -// Texture parameters: filter mode -// NOTE 1: Filtering considers mipmaps if available in the texture -// NOTE 2: Filter is accordingly set for minification and magnification -typedef enum { - RL_TEXTURE_FILTER_POINT = 0, // No filter, just pixel approximation - RL_TEXTURE_FILTER_BILINEAR, // Linear filtering - RL_TEXTURE_FILTER_TRILINEAR, // Trilinear filtering (linear with mipmaps) - RL_TEXTURE_FILTER_ANISOTROPIC_4X, // Anisotropic filtering 4x - RL_TEXTURE_FILTER_ANISOTROPIC_8X, // Anisotropic filtering 8x - RL_TEXTURE_FILTER_ANISOTROPIC_16X, // Anisotropic filtering 16x -} rlTextureFilter; - -// Color blending modes (pre-defined) -typedef enum { - RL_BLEND_ALPHA = 0, // Blend textures considering alpha (default) - RL_BLEND_ADDITIVE, // Blend textures adding colors - RL_BLEND_MULTIPLIED, // Blend textures multiplying colors - RL_BLEND_ADD_COLORS, // Blend textures adding colors (alternative) - RL_BLEND_SUBTRACT_COLORS, // Blend textures subtracting colors (alternative) - RL_BLEND_ALPHA_PREMULTIPLY, // Blend premultiplied textures considering alpha - RL_BLEND_CUSTOM, // Blend textures using custom src/dst factors (use rlSetBlendFactors()) - RL_BLEND_CUSTOM_SEPARATE // Blend textures using custom src/dst factors (use rlSetBlendFactorsSeparate()) -} rlBlendMode; - -// Shader location point type -typedef enum { - RL_SHADER_LOC_VERTEX_POSITION = 0, // Shader location: vertex attribute: position - RL_SHADER_LOC_VERTEX_TEXCOORD01, // Shader location: vertex attribute: texcoord01 - RL_SHADER_LOC_VERTEX_TEXCOORD02, // Shader location: vertex attribute: texcoord02 - RL_SHADER_LOC_VERTEX_NORMAL, // Shader location: vertex attribute: normal - RL_SHADER_LOC_VERTEX_TANGENT, // Shader location: vertex attribute: tangent - RL_SHADER_LOC_VERTEX_COLOR, // Shader location: vertex attribute: color - RL_SHADER_LOC_MATRIX_MVP, // Shader location: matrix uniform: model-view-projection - RL_SHADER_LOC_MATRIX_VIEW, // Shader location: matrix uniform: view (camera transform) - RL_SHADER_LOC_MATRIX_PROJECTION, // Shader location: matrix uniform: projection - RL_SHADER_LOC_MATRIX_MODEL, // Shader location: matrix uniform: model (transform) - RL_SHADER_LOC_MATRIX_NORMAL, // Shader location: matrix uniform: normal - RL_SHADER_LOC_VECTOR_VIEW, // Shader location: vector uniform: view - RL_SHADER_LOC_COLOR_DIFFUSE, // Shader location: vector uniform: diffuse color - RL_SHADER_LOC_COLOR_SPECULAR, // Shader location: vector uniform: specular color - RL_SHADER_LOC_COLOR_AMBIENT, // Shader location: vector uniform: ambient color - RL_SHADER_LOC_MAP_ALBEDO, // Shader location: sampler2d texture: albedo (same as: RL_SHADER_LOC_MAP_DIFFUSE) - RL_SHADER_LOC_MAP_METALNESS, // Shader location: sampler2d texture: metalness (same as: RL_SHADER_LOC_MAP_SPECULAR) - RL_SHADER_LOC_MAP_NORMAL, // Shader location: sampler2d texture: normal - RL_SHADER_LOC_MAP_ROUGHNESS, // Shader location: sampler2d texture: roughness - RL_SHADER_LOC_MAP_OCCLUSION, // Shader location: sampler2d texture: occlusion - RL_SHADER_LOC_MAP_EMISSION, // Shader location: sampler2d texture: emission - RL_SHADER_LOC_MAP_HEIGHT, // Shader location: sampler2d texture: height - RL_SHADER_LOC_MAP_CUBEMAP, // Shader location: samplerCube texture: cubemap - RL_SHADER_LOC_MAP_IRRADIANCE, // Shader location: samplerCube texture: irradiance - RL_SHADER_LOC_MAP_PREFILTER, // Shader location: samplerCube texture: prefilter - RL_SHADER_LOC_MAP_BRDF // Shader location: sampler2d texture: brdf -} rlShaderLocationIndex; - -#define RL_SHADER_LOC_MAP_DIFFUSE RL_SHADER_LOC_MAP_ALBEDO -#define RL_SHADER_LOC_MAP_SPECULAR RL_SHADER_LOC_MAP_METALNESS - -// Shader uniform data type -typedef enum { - RL_SHADER_UNIFORM_FLOAT = 0, // Shader uniform type: float - RL_SHADER_UNIFORM_VEC2, // Shader uniform type: vec2 (2 float) - RL_SHADER_UNIFORM_VEC3, // Shader uniform type: vec3 (3 float) - RL_SHADER_UNIFORM_VEC4, // Shader uniform type: vec4 (4 float) - RL_SHADER_UNIFORM_INT, // Shader uniform type: int - RL_SHADER_UNIFORM_IVEC2, // Shader uniform type: ivec2 (2 int) - RL_SHADER_UNIFORM_IVEC3, // Shader uniform type: ivec3 (3 int) - RL_SHADER_UNIFORM_IVEC4, // Shader uniform type: ivec4 (4 int) - RL_SHADER_UNIFORM_UINT, // Shader uniform type: unsigned int - RL_SHADER_UNIFORM_UIVEC2, // Shader uniform type: uivec2 (2 unsigned int) - RL_SHADER_UNIFORM_UIVEC3, // Shader uniform type: uivec3 (3 unsigned int) - RL_SHADER_UNIFORM_UIVEC4, // Shader uniform type: uivec4 (4 unsigned int) - RL_SHADER_UNIFORM_SAMPLER2D // Shader uniform type: sampler2d -} rlShaderUniformDataType; - -// Shader attribute data types -typedef enum { - RL_SHADER_ATTRIB_FLOAT = 0, // Shader attribute type: float - RL_SHADER_ATTRIB_VEC2, // Shader attribute type: vec2 (2 float) - RL_SHADER_ATTRIB_VEC3, // Shader attribute type: vec3 (3 float) - RL_SHADER_ATTRIB_VEC4 // Shader attribute type: vec4 (4 float) -} rlShaderAttributeDataType; - -// Framebuffer attachment type -// NOTE: By default up to 8 color channels defined, but it can be more -typedef enum { - RL_ATTACHMENT_COLOR_CHANNEL0 = 0, // Framebuffer attachment type: color 0 - RL_ATTACHMENT_COLOR_CHANNEL1 = 1, // Framebuffer attachment type: color 1 - RL_ATTACHMENT_COLOR_CHANNEL2 = 2, // Framebuffer attachment type: color 2 - RL_ATTACHMENT_COLOR_CHANNEL3 = 3, // Framebuffer attachment type: color 3 - RL_ATTACHMENT_COLOR_CHANNEL4 = 4, // Framebuffer attachment type: color 4 - RL_ATTACHMENT_COLOR_CHANNEL5 = 5, // Framebuffer attachment type: color 5 - RL_ATTACHMENT_COLOR_CHANNEL6 = 6, // Framebuffer attachment type: color 6 - RL_ATTACHMENT_COLOR_CHANNEL7 = 7, // Framebuffer attachment type: color 7 - RL_ATTACHMENT_DEPTH = 100, // Framebuffer attachment type: depth - RL_ATTACHMENT_STENCIL = 200, // Framebuffer attachment type: stencil -} rlFramebufferAttachType; - -// Framebuffer texture attachment type -typedef enum { - RL_ATTACHMENT_CUBEMAP_POSITIVE_X = 0, // Framebuffer texture attachment type: cubemap, +X side - RL_ATTACHMENT_CUBEMAP_NEGATIVE_X = 1, // Framebuffer texture attachment type: cubemap, -X side - RL_ATTACHMENT_CUBEMAP_POSITIVE_Y = 2, // Framebuffer texture attachment type: cubemap, +Y side - RL_ATTACHMENT_CUBEMAP_NEGATIVE_Y = 3, // Framebuffer texture attachment type: cubemap, -Y side - RL_ATTACHMENT_CUBEMAP_POSITIVE_Z = 4, // Framebuffer texture attachment type: cubemap, +Z side - RL_ATTACHMENT_CUBEMAP_NEGATIVE_Z = 5, // Framebuffer texture attachment type: cubemap, -Z side - RL_ATTACHMENT_TEXTURE2D = 100, // Framebuffer texture attachment type: texture2d - RL_ATTACHMENT_RENDERBUFFER = 200, // Framebuffer texture attachment type: renderbuffer -} rlFramebufferAttachTextureType; - -// Face culling mode -typedef enum { - RL_CULL_FACE_FRONT = 0, - RL_CULL_FACE_BACK -} rlCullMode; - -//------------------------------------------------------------------------------------ -// Functions Declaration - Matrix operations -//------------------------------------------------------------------------------------ - -#if defined(__cplusplus) -extern "C" { // Prevents name mangling of functions -#endif - -RLAPI void rlMatrixMode(int mode); // Choose the current matrix to be transformed -RLAPI void rlPushMatrix(void); // Push the current matrix to stack -RLAPI void rlPopMatrix(void); // Pop latest inserted matrix from stack -RLAPI void rlLoadIdentity(void); // Reset current matrix to identity matrix -RLAPI void rlTranslatef(float x, float y, float z); // Multiply the current matrix by a translation matrix -RLAPI void rlRotatef(float angle, float x, float y, float z); // Multiply the current matrix by a rotation matrix -RLAPI void rlScalef(float x, float y, float z); // Multiply the current matrix by a scaling matrix -RLAPI void rlMultMatrixf(const float *matf); // Multiply the current matrix by another matrix -RLAPI void rlFrustum(double left, double right, double bottom, double top, double znear, double zfar); -RLAPI void rlOrtho(double left, double right, double bottom, double top, double znear, double zfar); -RLAPI void rlViewport(int x, int y, int width, int height); // Set the viewport area -RLAPI void rlSetClipPlanes(double nearPlane, double farPlane); // Set clip planes distances -RLAPI double rlGetCullDistanceNear(void); // Get cull plane distance near -RLAPI double rlGetCullDistanceFar(void); // Get cull plane distance far - -//------------------------------------------------------------------------------------ -// Functions Declaration - Vertex level operations -//------------------------------------------------------------------------------------ -RLAPI void rlBegin(int mode); // Initialize drawing mode (how to organize vertex) -RLAPI void rlEnd(void); // Finish vertex providing -RLAPI void rlVertex2i(int x, int y); // Define one vertex (position) - 2 int -RLAPI void rlVertex2f(float x, float y); // Define one vertex (position) - 2 float -RLAPI void rlVertex3f(float x, float y, float z); // Define one vertex (position) - 3 float -RLAPI void rlTexCoord2f(float x, float y); // Define one vertex (texture coordinate) - 2 float -RLAPI void rlNormal3f(float x, float y, float z); // Define one vertex (normal) - 3 float -RLAPI void rlColor4ub(unsigned char r, unsigned char g, unsigned char b, unsigned char a); // Define one vertex (color) - 4 byte -RLAPI void rlColor3f(float x, float y, float z); // Define one vertex (color) - 3 float -RLAPI void rlColor4f(float x, float y, float z, float w); // Define one vertex (color) - 4 float - -//------------------------------------------------------------------------------------ -// Functions Declaration - OpenGL style functions (common to 1.1, 3.3+, ES2) -// NOTE: This functions are used to completely abstract raylib code from OpenGL layer, -// some of them are direct wrappers over OpenGL calls, some others are custom -//------------------------------------------------------------------------------------ - -// Vertex buffers state -RLAPI bool rlEnableVertexArray(unsigned int vaoId); // Enable vertex array (VAO, if supported) -RLAPI void rlDisableVertexArray(void); // Disable vertex array (VAO, if supported) -RLAPI void rlEnableVertexBuffer(unsigned int id); // Enable vertex buffer (VBO) -RLAPI void rlDisableVertexBuffer(void); // Disable vertex buffer (VBO) -RLAPI void rlEnableVertexBufferElement(unsigned int id); // Enable vertex buffer element (VBO element) -RLAPI void rlDisableVertexBufferElement(void); // Disable vertex buffer element (VBO element) -RLAPI void rlEnableVertexAttribute(unsigned int index); // Enable vertex attribute index -RLAPI void rlDisableVertexAttribute(unsigned int index); // Disable vertex attribute index -#if defined(GRAPHICS_API_OPENGL_11) -RLAPI void rlEnableStatePointer(int vertexAttribType, void *buffer); // Enable attribute state pointer -RLAPI void rlDisableStatePointer(int vertexAttribType); // Disable attribute state pointer -#endif - -// Textures state -RLAPI void rlActiveTextureSlot(int slot); // Select and active a texture slot -RLAPI void rlEnableTexture(unsigned int id); // Enable texture -RLAPI void rlDisableTexture(void); // Disable texture -RLAPI void rlEnableTextureCubemap(unsigned int id); // Enable texture cubemap -RLAPI void rlDisableTextureCubemap(void); // Disable texture cubemap -RLAPI void rlTextureParameters(unsigned int id, int param, int value); // Set texture parameters (filter, wrap) -RLAPI void rlCubemapParameters(unsigned int id, int param, int value); // Set cubemap parameters (filter, wrap) - -// Shader state -RLAPI void rlEnableShader(unsigned int id); // Enable shader program -RLAPI void rlDisableShader(void); // Disable shader program - -// Framebuffer state -RLAPI void rlEnableFramebuffer(unsigned int id); // Enable render texture (fbo) -RLAPI void rlDisableFramebuffer(void); // Disable render texture (fbo), return to default framebuffer -RLAPI unsigned int rlGetActiveFramebuffer(void); // Get the currently active render texture (fbo), 0 for default framebuffer -RLAPI void rlActiveDrawBuffers(int count); // Activate multiple draw color buffers -RLAPI void rlBlitFramebuffer(int srcX, int srcY, int srcWidth, int srcHeight, int dstX, int dstY, int dstWidth, int dstHeight, int bufferMask); // Blit active framebuffer to main framebuffer -RLAPI void rlBindFramebuffer(unsigned int target, unsigned int framebuffer); // Bind framebuffer (FBO) - -// General render state -RLAPI void rlEnableColorBlend(void); // Enable color blending -RLAPI void rlDisableColorBlend(void); // Disable color blending -RLAPI void rlEnableDepthTest(void); // Enable depth test -RLAPI void rlDisableDepthTest(void); // Disable depth test -RLAPI void rlEnableDepthMask(void); // Enable depth write -RLAPI void rlDisableDepthMask(void); // Disable depth write -RLAPI void rlEnableBackfaceCulling(void); // Enable backface culling -RLAPI void rlDisableBackfaceCulling(void); // Disable backface culling -RLAPI void rlColorMask(bool r, bool g, bool b, bool a); // Color mask control -RLAPI void rlSetCullFace(int mode); // Set face culling mode -RLAPI void rlEnableScissorTest(void); // Enable scissor test -RLAPI void rlDisableScissorTest(void); // Disable scissor test -RLAPI void rlScissor(int x, int y, int width, int height); // Scissor test -RLAPI void rlEnableWireMode(void); // Enable wire mode -RLAPI void rlEnablePointMode(void); // Enable point mode -RLAPI void rlDisableWireMode(void); // Disable wire (and point) mode -RLAPI void rlSetLineWidth(float width); // Set the line drawing width -RLAPI float rlGetLineWidth(void); // Get the line drawing width -RLAPI void rlEnableSmoothLines(void); // Enable line aliasing -RLAPI void rlDisableSmoothLines(void); // Disable line aliasing -RLAPI void rlEnableStereoRender(void); // Enable stereo rendering -RLAPI void rlDisableStereoRender(void); // Disable stereo rendering -RLAPI bool rlIsStereoRenderEnabled(void); // Check if stereo render is enabled - -RLAPI void rlClearColor(unsigned char r, unsigned char g, unsigned char b, unsigned char a); // Clear color buffer with color -RLAPI void rlClearScreenBuffers(void); // Clear used screen buffers (color and depth) -RLAPI void rlCheckErrors(void); // Check and log OpenGL error codes -RLAPI void rlSetBlendMode(int mode); // Set blending mode -RLAPI void rlSetBlendFactors(int glSrcFactor, int glDstFactor, int glEquation); // Set blending mode factor and equation (using OpenGL factors) -RLAPI void rlSetBlendFactorsSeparate(int glSrcRGB, int glDstRGB, int glSrcAlpha, int glDstAlpha, int glEqRGB, int glEqAlpha); // Set blending mode factors and equations separately (using OpenGL factors) - -//------------------------------------------------------------------------------------ -// Functions Declaration - rlgl functionality -//------------------------------------------------------------------------------------ -// rlgl initialization functions -RLAPI void rlglInit(int width, int height); // Initialize rlgl (buffers, shaders, textures, states) -RLAPI void rlglClose(void); // De-initialize rlgl (buffers, shaders, textures) -RLAPI void rlLoadExtensions(void *loader); // Load OpenGL extensions (loader function required) -RLAPI int rlGetVersion(void); // Get current OpenGL version -RLAPI void rlSetFramebufferWidth(int width); // Set current framebuffer width -RLAPI int rlGetFramebufferWidth(void); // Get default framebuffer width -RLAPI void rlSetFramebufferHeight(int height); // Set current framebuffer height -RLAPI int rlGetFramebufferHeight(void); // Get default framebuffer height - -RLAPI unsigned int rlGetTextureIdDefault(void); // Get default texture id -RLAPI unsigned int rlGetShaderIdDefault(void); // Get default shader id -RLAPI int *rlGetShaderLocsDefault(void); // Get default shader locations - -// Render batch management -// NOTE: rlgl provides a default render batch to behave like OpenGL 1.1 immediate mode -// but this render batch API is exposed in case of custom batches are required -RLAPI rlRenderBatch rlLoadRenderBatch(int numBuffers, int bufferElements); // Load a render batch system -RLAPI void rlUnloadRenderBatch(rlRenderBatch batch); // Unload render batch system -RLAPI void rlDrawRenderBatch(rlRenderBatch *batch); // Draw render batch data (Update->Draw->Reset) -RLAPI void rlSetRenderBatchActive(rlRenderBatch *batch); // Set the active render batch for rlgl (NULL for default internal) -RLAPI void rlDrawRenderBatchActive(void); // Update and draw internal render batch -RLAPI bool rlCheckRenderBatchLimit(int vCount); // Check internal buffer overflow for a given number of vertex - -RLAPI void rlSetTexture(unsigned int id); // Set current texture for render batch and check buffers limits - -//------------------------------------------------------------------------------------------------------------------------ - -// Vertex buffers management -RLAPI unsigned int rlLoadVertexArray(void); // Load vertex array (vao) if supported -RLAPI unsigned int rlLoadVertexBuffer(const void *buffer, int size, bool dynamic); // Load a vertex buffer object -RLAPI unsigned int rlLoadVertexBufferElement(const void *buffer, int size, bool dynamic); // Load vertex buffer elements object -RLAPI void rlUpdateVertexBuffer(unsigned int bufferId, const void *data, int dataSize, int offset); // Update vertex buffer object data on GPU buffer -RLAPI void rlUpdateVertexBufferElements(unsigned int id, const void *data, int dataSize, int offset); // Update vertex buffer elements data on GPU buffer -RLAPI void rlUnloadVertexArray(unsigned int vaoId); // Unload vertex array (vao) -RLAPI void rlUnloadVertexBuffer(unsigned int vboId); // Unload vertex buffer object -RLAPI void rlSetVertexAttribute(unsigned int index, int compSize, int type, bool normalized, int stride, int offset); // Set vertex attribute data configuration -RLAPI void rlSetVertexAttributeDivisor(unsigned int index, int divisor); // Set vertex attribute data divisor -RLAPI void rlSetVertexAttributeDefault(int locIndex, const void *value, int attribType, int count); // Set vertex attribute default value, when attribute to provided -RLAPI void rlDrawVertexArray(int offset, int count); // Draw vertex array (currently active vao) -RLAPI void rlDrawVertexArrayElements(int offset, int count, const void *buffer); // Draw vertex array elements -RLAPI void rlDrawVertexArrayInstanced(int offset, int count, int instances); // Draw vertex array (currently active vao) with instancing -RLAPI void rlDrawVertexArrayElementsInstanced(int offset, int count, const void *buffer, int instances); // Draw vertex array elements with instancing - -// Textures management -RLAPI unsigned int rlLoadTexture(const void *data, int width, int height, int format, int mipmapCount); // Load texture data -RLAPI unsigned int rlLoadTextureDepth(int width, int height, bool useRenderBuffer); // Load depth texture/renderbuffer (to be attached to fbo) -RLAPI unsigned int rlLoadTextureCubemap(const void *data, int size, int format, int mipmapCount); // Load texture cubemap data -RLAPI void rlUpdateTexture(unsigned int id, int offsetX, int offsetY, int width, int height, int format, const void *data); // Update texture with new data on GPU -RLAPI void rlGetGlTextureFormats(int format, unsigned int *glInternalFormat, unsigned int *glFormat, unsigned int *glType); // Get OpenGL internal formats -RLAPI const char *rlGetPixelFormatName(unsigned int format); // Get name string for pixel format -RLAPI void rlUnloadTexture(unsigned int id); // Unload texture from GPU memory -RLAPI void rlGenTextureMipmaps(unsigned int id, int width, int height, int format, int *mipmaps); // Generate mipmap data for selected texture -RLAPI void *rlReadTexturePixels(unsigned int id, int width, int height, int format); // Read texture pixel data -RLAPI unsigned char *rlReadScreenPixels(int width, int height); // Read screen pixel data (color buffer) - -// Framebuffer management (fbo) -RLAPI unsigned int rlLoadFramebuffer(void); // Load an empty framebuffer -RLAPI void rlFramebufferAttach(unsigned int fboId, unsigned int texId, int attachType, int texType, int mipLevel); // Attach texture/renderbuffer to a framebuffer -RLAPI bool rlFramebufferComplete(unsigned int id); // Verify framebuffer is complete -RLAPI void rlUnloadFramebuffer(unsigned int id); // Delete framebuffer from GPU - -// Shaders management -RLAPI unsigned int rlLoadShaderCode(const char *vsCode, const char *fsCode); // Load shader from code strings -RLAPI unsigned int rlCompileShader(const char *shaderCode, int type); // Compile custom shader and return shader id (type: RL_VERTEX_SHADER, RL_FRAGMENT_SHADER, RL_COMPUTE_SHADER) -RLAPI unsigned int rlLoadShaderProgram(unsigned int vShaderId, unsigned int fShaderId); // Load custom shader program -RLAPI void rlUnloadShaderProgram(unsigned int id); // Unload shader program -RLAPI int rlGetLocationUniform(unsigned int shaderId, const char *uniformName); // Get shader location uniform -RLAPI int rlGetLocationAttrib(unsigned int shaderId, const char *attribName); // Get shader location attribute -RLAPI void rlSetUniform(int locIndex, const void *value, int uniformType, int count); // Set shader value uniform -RLAPI void rlSetUniformMatrix(int locIndex, Matrix mat); // Set shader value matrix -RLAPI void rlSetUniformMatrices(int locIndex, const Matrix *mat, int count); // Set shader value matrices -RLAPI void rlSetUniformSampler(int locIndex, unsigned int textureId); // Set shader value sampler -RLAPI void rlSetShader(unsigned int id, int *locs); // Set shader currently active (id and locations) - -// Compute shader management -RLAPI unsigned int rlLoadComputeShaderProgram(unsigned int shaderId); // Load compute shader program -RLAPI void rlComputeShaderDispatch(unsigned int groupX, unsigned int groupY, unsigned int groupZ); // Dispatch compute shader (equivalent to *draw* for graphics pipeline) - -// Shader buffer storage object management (ssbo) -RLAPI unsigned int rlLoadShaderBuffer(unsigned int size, const void *data, int usageHint); // Load shader storage buffer object (SSBO) -RLAPI void rlUnloadShaderBuffer(unsigned int ssboId); // Unload shader storage buffer object (SSBO) -RLAPI void rlUpdateShaderBuffer(unsigned int id, const void *data, unsigned int dataSize, unsigned int offset); // Update SSBO buffer data -RLAPI void rlBindShaderBuffer(unsigned int id, unsigned int index); // Bind SSBO buffer -RLAPI void rlReadShaderBuffer(unsigned int id, void *dest, unsigned int count, unsigned int offset); // Read SSBO buffer data (GPU->CPU) -RLAPI void rlCopyShaderBuffer(unsigned int destId, unsigned int srcId, unsigned int destOffset, unsigned int srcOffset, unsigned int count); // Copy SSBO data between buffers -RLAPI unsigned int rlGetShaderBufferSize(unsigned int id); // Get SSBO buffer size - -// Buffer management -RLAPI void rlBindImageTexture(unsigned int id, unsigned int index, int format, bool readonly); // Bind image texture - -// Matrix state management -RLAPI Matrix rlGetMatrixModelview(void); // Get internal modelview matrix -RLAPI Matrix rlGetMatrixProjection(void); // Get internal projection matrix -RLAPI Matrix rlGetMatrixTransform(void); // Get internal accumulated transform matrix -RLAPI Matrix rlGetMatrixProjectionStereo(int eye); // Get internal projection matrix for stereo render (selected eye) -RLAPI Matrix rlGetMatrixViewOffsetStereo(int eye); // Get internal view offset matrix for stereo render (selected eye) -RLAPI void rlSetMatrixProjection(Matrix proj); // Set a custom projection matrix (replaces internal projection matrix) -RLAPI void rlSetMatrixModelview(Matrix view); // Set a custom modelview matrix (replaces internal modelview matrix) -RLAPI void rlSetMatrixProjectionStereo(Matrix right, Matrix left); // Set eyes projection matrices for stereo rendering -RLAPI void rlSetMatrixViewOffsetStereo(Matrix right, Matrix left); // Set eyes view offsets matrices for stereo rendering - -// Quick and dirty cube/quad buffers load->draw->unload -RLAPI void rlLoadDrawCube(void); // Load and draw a cube -RLAPI void rlLoadDrawQuad(void); // Load and draw a quad - -#if defined(__cplusplus) -} -#endif - -#endif // RLGL_H - -/*********************************************************************************** -* -* RLGL IMPLEMENTATION -* -************************************************************************************/ - -#if defined(RLGL_IMPLEMENTATION) - -// Expose OpenGL functions from glad in raylib -#if defined(BUILD_LIBTYPE_SHARED) - #define GLAD_API_CALL_EXPORT - #define GLAD_API_CALL_EXPORT_BUILD -#endif - -#if defined(GRAPHICS_API_OPENGL_11) - #if defined(__APPLE__) - #include // OpenGL 1.1 library for OSX - #include // OpenGL extensions library - #else - // APIENTRY for OpenGL function pointer declarations is required - #if !defined(APIENTRY) - #if defined(_WIN32) - #define APIENTRY __stdcall - #else - #define APIENTRY - #endif - #endif - // WINGDIAPI definition. Some Windows OpenGL headers need it - #if !defined(WINGDIAPI) && defined(_WIN32) - #define WINGDIAPI __declspec(dllimport) - #endif - - #include // OpenGL 1.1 library - #endif -#endif - -#if defined(GRAPHICS_API_OPENGL_33) - #define GLAD_MALLOC RL_MALLOC - #define GLAD_FREE RL_FREE - - #define GLAD_GL_IMPLEMENTATION - #include "external/glad.h" // GLAD extensions loading library, includes OpenGL headers -#endif - -#if defined(GRAPHICS_API_OPENGL_ES3) - #include // OpenGL ES 3.0 library - #define GL_GLEXT_PROTOTYPES - #include // OpenGL ES 2.0 extensions library -#elif defined(GRAPHICS_API_OPENGL_ES2) - // NOTE: OpenGL ES 2.0 can be enabled on Desktop platforms, - // in that case, functions are loaded from a custom glad for OpenGL ES 2.0 - #if defined(PLATFORM_DESKTOP_GLFW) || defined(PLATFORM_DESKTOP_SDL) - #define GLAD_GLES2_IMPLEMENTATION - #include "external/glad_gles2.h" - #else - #define GL_GLEXT_PROTOTYPES - //#include // EGL library -> not required, platform layer - #include // OpenGL ES 2.0 library - #include // OpenGL ES 2.0 extensions library - #endif - - // It seems OpenGL ES 2.0 instancing entry points are not defined on Raspberry Pi - // provided headers (despite being defined in official Khronos GLES2 headers) - #if defined(PLATFORM_DRM) - typedef void (GL_APIENTRYP PFNGLDRAWARRAYSINSTANCEDEXTPROC) (GLenum mode, GLint start, GLsizei count, GLsizei primcount); - typedef void (GL_APIENTRYP PFNGLDRAWELEMENTSINSTANCEDEXTPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount); - typedef void (GL_APIENTRYP PFNGLVERTEXATTRIBDIVISOREXTPROC) (GLuint index, GLuint divisor); - #endif -#endif - -#include // Required for: malloc(), free() -#include // Required for: strcmp(), strlen() [Used in rlglInit(), on extensions loading] -#include // Required for: sqrtf(), sinf(), cosf(), floor(), log() - -//---------------------------------------------------------------------------------- -// Defines and Macros -//---------------------------------------------------------------------------------- -#ifndef PI - #define PI 3.14159265358979323846f -#endif -#ifndef DEG2RAD - #define DEG2RAD (PI/180.0f) -#endif -#ifndef RAD2DEG - #define RAD2DEG (180.0f/PI) -#endif - -#ifndef GL_SHADING_LANGUAGE_VERSION - #define GL_SHADING_LANGUAGE_VERSION 0x8B8C -#endif - -#ifndef GL_COMPRESSED_RGB_S3TC_DXT1_EXT - #define GL_COMPRESSED_RGB_S3TC_DXT1_EXT 0x83F0 -#endif -#ifndef GL_COMPRESSED_RGBA_S3TC_DXT1_EXT - #define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1 -#endif -#ifndef GL_COMPRESSED_RGBA_S3TC_DXT3_EXT - #define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2 -#endif -#ifndef GL_COMPRESSED_RGBA_S3TC_DXT5_EXT - #define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3 -#endif -#ifndef GL_ETC1_RGB8_OES - #define GL_ETC1_RGB8_OES 0x8D64 -#endif -#ifndef GL_COMPRESSED_RGB8_ETC2 - #define GL_COMPRESSED_RGB8_ETC2 0x9274 -#endif -#ifndef GL_COMPRESSED_RGBA8_ETC2_EAC - #define GL_COMPRESSED_RGBA8_ETC2_EAC 0x9278 -#endif -#ifndef GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG - #define GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG 0x8C00 -#endif -#ifndef GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG - #define GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG 0x8C02 -#endif -#ifndef GL_COMPRESSED_RGBA_ASTC_4x4_KHR - #define GL_COMPRESSED_RGBA_ASTC_4x4_KHR 0x93b0 -#endif -#ifndef GL_COMPRESSED_RGBA_ASTC_8x8_KHR - #define GL_COMPRESSED_RGBA_ASTC_8x8_KHR 0x93b7 -#endif - -#ifndef GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT - #define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF -#endif -#ifndef GL_TEXTURE_MAX_ANISOTROPY_EXT - #define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE -#endif - -#ifndef GL_PROGRAM_POINT_SIZE - #define GL_PROGRAM_POINT_SIZE 0x8642 -#endif - -#ifndef GL_LINE_WIDTH - #define GL_LINE_WIDTH 0x0B21 -#endif - -#if defined(GRAPHICS_API_OPENGL_11) - #define GL_UNSIGNED_SHORT_5_6_5 0x8363 - #define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 - #define GL_UNSIGNED_SHORT_4_4_4_4 0x8033 -#endif - -#if defined(GRAPHICS_API_OPENGL_21) - #define GL_LUMINANCE 0x1909 - #define GL_LUMINANCE_ALPHA 0x190A -#endif - -#if defined(GRAPHICS_API_OPENGL_ES2) - #define glClearDepth glClearDepthf - #if !defined(GRAPHICS_API_OPENGL_ES3) - #define GL_READ_FRAMEBUFFER GL_FRAMEBUFFER - #define GL_DRAW_FRAMEBUFFER GL_FRAMEBUFFER - #endif -#endif - -// Default shader vertex attribute names to set location points -#ifndef RL_DEFAULT_SHADER_ATTRIB_NAME_POSITION - #define RL_DEFAULT_SHADER_ATTRIB_NAME_POSITION "vertexPosition" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_NAME_POSITION -#endif -#ifndef RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD - #define RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD "vertexTexCoord" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD -#endif -#ifndef RL_DEFAULT_SHADER_ATTRIB_NAME_NORMAL - #define RL_DEFAULT_SHADER_ATTRIB_NAME_NORMAL "vertexNormal" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_NAME_NORMAL -#endif -#ifndef RL_DEFAULT_SHADER_ATTRIB_NAME_COLOR - #define RL_DEFAULT_SHADER_ATTRIB_NAME_COLOR "vertexColor" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_NAME_COLOR -#endif -#ifndef RL_DEFAULT_SHADER_ATTRIB_NAME_TANGENT - #define RL_DEFAULT_SHADER_ATTRIB_NAME_TANGENT "vertexTangent" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_NAME_TANGENT -#endif -#ifndef RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD2 - #define RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD2 "vertexTexCoord2" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD2 -#endif -#ifndef RL_DEFAULT_SHADER_ATTRIB_NAME_BONEIDS - #define RL_DEFAULT_SHADER_ATTRIB_NAME_BONEIDS "vertexBoneIds" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_NAME_BONEIDS -#endif -#ifndef RL_DEFAULT_SHADER_ATTRIB_NAME_BONEWEIGHTS - #define RL_DEFAULT_SHADER_ATTRIB_NAME_BONEWEIGHTS "vertexBoneWeights" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_NAME_BONEWEIGHTS -#endif - -#ifndef RL_DEFAULT_SHADER_UNIFORM_NAME_MVP - #define RL_DEFAULT_SHADER_UNIFORM_NAME_MVP "mvp" // model-view-projection matrix -#endif -#ifndef RL_DEFAULT_SHADER_UNIFORM_NAME_VIEW - #define RL_DEFAULT_SHADER_UNIFORM_NAME_VIEW "matView" // view matrix -#endif -#ifndef RL_DEFAULT_SHADER_UNIFORM_NAME_PROJECTION - #define RL_DEFAULT_SHADER_UNIFORM_NAME_PROJECTION "matProjection" // projection matrix -#endif -#ifndef RL_DEFAULT_SHADER_UNIFORM_NAME_MODEL - #define RL_DEFAULT_SHADER_UNIFORM_NAME_MODEL "matModel" // model matrix -#endif -#ifndef RL_DEFAULT_SHADER_UNIFORM_NAME_NORMAL - #define RL_DEFAULT_SHADER_UNIFORM_NAME_NORMAL "matNormal" // normal matrix (transpose(inverse(matModelView)) -#endif -#ifndef RL_DEFAULT_SHADER_UNIFORM_NAME_COLOR - #define RL_DEFAULT_SHADER_UNIFORM_NAME_COLOR "colDiffuse" // color diffuse (base tint color, multiplied by texture color) -#endif -#ifndef RL_DEFAULT_SHADER_UNIFORM_NAME_BONE_MATRICES - #define RL_DEFAULT_SHADER_UNIFORM_NAME_BONE_MATRICES "boneMatrices" // bone matrices -#endif -#ifndef RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE0 - #define RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE0 "texture0" // texture0 (texture slot active 0) -#endif -#ifndef RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE1 - #define RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE1 "texture1" // texture1 (texture slot active 1) -#endif -#ifndef RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE2 - #define RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE2 "texture2" // texture2 (texture slot active 2) -#endif - -//---------------------------------------------------------------------------------- -// Types and Structures Definition -//---------------------------------------------------------------------------------- -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) -typedef struct rlglData { - rlRenderBatch *currentBatch; // Current render batch - rlRenderBatch defaultBatch; // Default internal render batch - - struct { - int vertexCounter; // Current active render batch vertex counter (generic, used for all batches) - float texcoordx, texcoordy; // Current active texture coordinate (added on glVertex*()) - float normalx, normaly, normalz; // Current active normal (added on glVertex*()) - unsigned char colorr, colorg, colorb, colora; // Current active color (added on glVertex*()) - - int currentMatrixMode; // Current matrix mode - Matrix *currentMatrix; // Current matrix pointer - Matrix modelview; // Default modelview matrix - Matrix projection; // Default projection matrix - Matrix transform; // Transform matrix to be used with rlTranslate, rlRotate, rlScale - bool transformRequired; // Require transform matrix application to current draw-call vertex (if required) - Matrix stack[RL_MAX_MATRIX_STACK_SIZE];// Matrix stack for push/pop - int stackCounter; // Matrix stack counter - - unsigned int defaultTextureId; // Default texture used on shapes/poly drawing (required by shader) - unsigned int activeTextureId[RL_DEFAULT_BATCH_MAX_TEXTURE_UNITS]; // Active texture ids to be enabled on batch drawing (0 active by default) - unsigned int defaultVShaderId; // Default vertex shader id (used by default shader program) - unsigned int defaultFShaderId; // Default fragment shader id (used by default shader program) - unsigned int defaultShaderId; // Default shader program id, supports vertex color and diffuse texture - int *defaultShaderLocs; // Default shader locations pointer to be used on rendering - unsigned int currentShaderId; // Current shader id to be used on rendering (by default, defaultShaderId) - int *currentShaderLocs; // Current shader locations pointer to be used on rendering (by default, defaultShaderLocs) - - bool stereoRender; // Stereo rendering flag - Matrix projectionStereo[2]; // VR stereo rendering eyes projection matrices - Matrix viewOffsetStereo[2]; // VR stereo rendering eyes view offset matrices - - // Blending variables - int currentBlendMode; // Blending mode active - int glBlendSrcFactor; // Blending source factor - int glBlendDstFactor; // Blending destination factor - int glBlendEquation; // Blending equation - int glBlendSrcFactorRGB; // Blending source RGB factor - int glBlendDestFactorRGB; // Blending destination RGB factor - int glBlendSrcFactorAlpha; // Blending source alpha factor - int glBlendDestFactorAlpha; // Blending destination alpha factor - int glBlendEquationRGB; // Blending equation for RGB - int glBlendEquationAlpha; // Blending equation for alpha - bool glCustomBlendModeModified; // Custom blending factor and equation modification status - - int framebufferWidth; // Current framebuffer width - int framebufferHeight; // Current framebuffer height - - } State; // Renderer state - struct { - bool vao; // VAO support (OpenGL ES2 could not support VAO extension) (GL_ARB_vertex_array_object) - bool instancing; // Instancing supported (GL_ANGLE_instanced_arrays, GL_EXT_draw_instanced + GL_EXT_instanced_arrays) - bool texNPOT; // NPOT textures full support (GL_ARB_texture_non_power_of_two, GL_OES_texture_npot) - bool texDepth; // Depth textures supported (GL_ARB_depth_texture, GL_OES_depth_texture) - bool texDepthWebGL; // Depth textures supported WebGL specific (GL_WEBGL_depth_texture) - bool texFloat32; // float textures support (32 bit per channel) (GL_OES_texture_float) - bool texFloat16; // half float textures support (16 bit per channel) (GL_OES_texture_half_float) - bool texCompDXT; // DDS texture compression support (GL_EXT_texture_compression_s3tc, GL_WEBGL_compressed_texture_s3tc, GL_WEBKIT_WEBGL_compressed_texture_s3tc) - bool texCompETC1; // ETC1 texture compression support (GL_OES_compressed_ETC1_RGB8_texture, GL_WEBGL_compressed_texture_etc1) - bool texCompETC2; // ETC2/EAC texture compression support (GL_ARB_ES3_compatibility) - bool texCompPVRT; // PVR texture compression support (GL_IMG_texture_compression_pvrtc) - bool texCompASTC; // ASTC texture compression support (GL_KHR_texture_compression_astc_hdr, GL_KHR_texture_compression_astc_ldr) - bool texMirrorClamp; // Clamp mirror wrap mode supported (GL_EXT_texture_mirror_clamp) - bool texAnisoFilter; // Anisotropic texture filtering support (GL_EXT_texture_filter_anisotropic) - bool computeShader; // Compute shaders support (GL_ARB_compute_shader) - bool ssbo; // Shader storage buffer object support (GL_ARB_shader_storage_buffer_object) - - float maxAnisotropyLevel; // Maximum anisotropy level supported (minimum is 2.0f) - int maxDepthBits; // Maximum bits for depth component - - } ExtSupported; // Extensions supported flags -} rlglData; - -typedef void *(*rlglLoadProc)(const char *name); // OpenGL extension functions loader signature (same as GLADloadproc) - -#endif // GRAPHICS_API_OPENGL_33 || GRAPHICS_API_OPENGL_ES2 - -//---------------------------------------------------------------------------------- -// Global Variables Definition -//---------------------------------------------------------------------------------- -static double rlCullDistanceNear = RL_CULL_DISTANCE_NEAR; -static double rlCullDistanceFar = RL_CULL_DISTANCE_FAR; - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) -static rlglData RLGL = { 0 }; -#endif // GRAPHICS_API_OPENGL_33 || GRAPHICS_API_OPENGL_ES2 - -#if defined(GRAPHICS_API_OPENGL_ES2) && !defined(GRAPHICS_API_OPENGL_ES3) -// NOTE: VAO functionality is exposed through extensions (OES) -static PFNGLGENVERTEXARRAYSOESPROC glGenVertexArrays = NULL; -static PFNGLBINDVERTEXARRAYOESPROC glBindVertexArray = NULL; -static PFNGLDELETEVERTEXARRAYSOESPROC glDeleteVertexArrays = NULL; - -// NOTE: Instancing functionality could also be available through extension -static PFNGLDRAWARRAYSINSTANCEDEXTPROC glDrawArraysInstanced = NULL; -static PFNGLDRAWELEMENTSINSTANCEDEXTPROC glDrawElementsInstanced = NULL; -static PFNGLVERTEXATTRIBDIVISOREXTPROC glVertexAttribDivisor = NULL; -#endif - -//---------------------------------------------------------------------------------- -// Module specific Functions Declaration -//---------------------------------------------------------------------------------- -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) -static void rlLoadShaderDefault(void); // Load default shader -static void rlUnloadShaderDefault(void); // Unload default shader -#if defined(RLGL_SHOW_GL_DETAILS_INFO) -static const char *rlGetCompressedFormatName(int format); // Get compressed format official GL identifier name -#endif // RLGL_SHOW_GL_DETAILS_INFO -#endif // GRAPHICS_API_OPENGL_33 || GRAPHICS_API_OPENGL_ES2 - -static int rlGetPixelDataSize(int width, int height, int format); // Get pixel data size in bytes (image or texture) - -// Auxiliar matrix math functions -typedef struct rl_float16 { - float v[16]; -} rl_float16; -static rl_float16 rlMatrixToFloatV(Matrix mat); // Get float array of matrix data -#define rlMatrixToFloat(mat) (rlMatrixToFloatV(mat).v) // Get float vector for Matrix -static Matrix rlMatrixIdentity(void); // Get identity matrix -static Matrix rlMatrixMultiply(Matrix left, Matrix right); // Multiply two matrices -static Matrix rlMatrixTranspose(Matrix mat); // Transposes provided matrix -static Matrix rlMatrixInvert(Matrix mat); // Invert provided matrix - -//---------------------------------------------------------------------------------- -// Module Functions Definition - Matrix operations -//---------------------------------------------------------------------------------- - -#if defined(GRAPHICS_API_OPENGL_11) -// Fallback to OpenGL 1.1 function calls -//--------------------------------------- -void rlMatrixMode(int mode) -{ - switch (mode) - { - case RL_PROJECTION: glMatrixMode(GL_PROJECTION); break; - case RL_MODELVIEW: glMatrixMode(GL_MODELVIEW); break; - case RL_TEXTURE: glMatrixMode(GL_TEXTURE); break; - default: break; - } -} - -void rlFrustum(double left, double right, double bottom, double top, double znear, double zfar) -{ - glFrustum(left, right, bottom, top, znear, zfar); -} - -void rlOrtho(double left, double right, double bottom, double top, double znear, double zfar) -{ - glOrtho(left, right, bottom, top, znear, zfar); -} - -void rlPushMatrix(void) { glPushMatrix(); } -void rlPopMatrix(void) { glPopMatrix(); } -void rlLoadIdentity(void) { glLoadIdentity(); } -void rlTranslatef(float x, float y, float z) { glTranslatef(x, y, z); } -void rlRotatef(float angle, float x, float y, float z) { glRotatef(angle, x, y, z); } -void rlScalef(float x, float y, float z) { glScalef(x, y, z); } -void rlMultMatrixf(const float *matf) { glMultMatrixf(matf); } -#endif -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) -// Choose the current matrix to be transformed -void rlMatrixMode(int mode) -{ - if (mode == RL_PROJECTION) RLGL.State.currentMatrix = &RLGL.State.projection; - else if (mode == RL_MODELVIEW) RLGL.State.currentMatrix = &RLGL.State.modelview; - //else if (mode == RL_TEXTURE) // Not supported - - RLGL.State.currentMatrixMode = mode; -} - -// Push the current matrix into RLGL.State.stack -void rlPushMatrix(void) -{ - if (RLGL.State.stackCounter >= RL_MAX_MATRIX_STACK_SIZE) TRACELOG(RL_LOG_ERROR, "RLGL: Matrix stack overflow (RL_MAX_MATRIX_STACK_SIZE)"); - - if (RLGL.State.currentMatrixMode == RL_MODELVIEW) - { - RLGL.State.transformRequired = true; - RLGL.State.currentMatrix = &RLGL.State.transform; - } - - RLGL.State.stack[RLGL.State.stackCounter] = *RLGL.State.currentMatrix; - RLGL.State.stackCounter++; -} - -// Pop lattest inserted matrix from RLGL.State.stack -void rlPopMatrix(void) -{ - if (RLGL.State.stackCounter > 0) - { - Matrix mat = RLGL.State.stack[RLGL.State.stackCounter - 1]; - *RLGL.State.currentMatrix = mat; - RLGL.State.stackCounter--; - } - - if ((RLGL.State.stackCounter == 0) && (RLGL.State.currentMatrixMode == RL_MODELVIEW)) - { - RLGL.State.currentMatrix = &RLGL.State.modelview; - RLGL.State.transformRequired = false; - } -} - -// Reset current matrix to identity matrix -void rlLoadIdentity(void) -{ - *RLGL.State.currentMatrix = rlMatrixIdentity(); -} - -// Multiply the current matrix by a translation matrix -void rlTranslatef(float x, float y, float z) -{ - Matrix matTranslation = { - 1.0f, 0.0f, 0.0f, x, - 0.0f, 1.0f, 0.0f, y, - 0.0f, 0.0f, 1.0f, z, - 0.0f, 0.0f, 0.0f, 1.0f - }; - - // NOTE: We transpose matrix with multiplication order - *RLGL.State.currentMatrix = rlMatrixMultiply(matTranslation, *RLGL.State.currentMatrix); -} - -// Multiply the current matrix by a rotation matrix -// NOTE: The provided angle must be in degrees -void rlRotatef(float angle, float x, float y, float z) -{ - Matrix matRotation = rlMatrixIdentity(); - - // Axis vector (x, y, z) normalization - float lengthSquared = x*x + y*y + z*z; - if ((lengthSquared != 1.0f) && (lengthSquared != 0.0f)) - { - float inverseLength = 1.0f/sqrtf(lengthSquared); - x *= inverseLength; - y *= inverseLength; - z *= inverseLength; - } - - // Rotation matrix generation - float sinres = sinf(DEG2RAD*angle); - float cosres = cosf(DEG2RAD*angle); - float t = 1.0f - cosres; - - matRotation.m0 = x*x*t + cosres; - matRotation.m1 = y*x*t + z*sinres; - matRotation.m2 = z*x*t - y*sinres; - matRotation.m3 = 0.0f; - - matRotation.m4 = x*y*t - z*sinres; - matRotation.m5 = y*y*t + cosres; - matRotation.m6 = z*y*t + x*sinres; - matRotation.m7 = 0.0f; - - matRotation.m8 = x*z*t + y*sinres; - matRotation.m9 = y*z*t - x*sinres; - matRotation.m10 = z*z*t + cosres; - matRotation.m11 = 0.0f; - - matRotation.m12 = 0.0f; - matRotation.m13 = 0.0f; - matRotation.m14 = 0.0f; - matRotation.m15 = 1.0f; - - // NOTE: We transpose matrix with multiplication order - *RLGL.State.currentMatrix = rlMatrixMultiply(matRotation, *RLGL.State.currentMatrix); -} - -// Multiply the current matrix by a scaling matrix -void rlScalef(float x, float y, float z) -{ - Matrix matScale = { - x, 0.0f, 0.0f, 0.0f, - 0.0f, y, 0.0f, 0.0f, - 0.0f, 0.0f, z, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f - }; - - // NOTE: We transpose matrix with multiplication order - *RLGL.State.currentMatrix = rlMatrixMultiply(matScale, *RLGL.State.currentMatrix); -} - -// Multiply the current matrix by another matrix -void rlMultMatrixf(const float *matf) -{ - // Matrix creation from array - Matrix mat = { matf[0], matf[4], matf[8], matf[12], - matf[1], matf[5], matf[9], matf[13], - matf[2], matf[6], matf[10], matf[14], - matf[3], matf[7], matf[11], matf[15] }; - - *RLGL.State.currentMatrix = rlMatrixMultiply(mat, *RLGL.State.currentMatrix); -} - -// Multiply the current matrix by a perspective matrix generated by parameters -void rlFrustum(double left, double right, double bottom, double top, double znear, double zfar) -{ - Matrix matFrustum = { 0 }; - - float rl = (float)(right - left); - float tb = (float)(top - bottom); - float fn = (float)(zfar - znear); - - matFrustum.m0 = ((float) znear*2.0f)/rl; - matFrustum.m1 = 0.0f; - matFrustum.m2 = 0.0f; - matFrustum.m3 = 0.0f; - - matFrustum.m4 = 0.0f; - matFrustum.m5 = ((float) znear*2.0f)/tb; - matFrustum.m6 = 0.0f; - matFrustum.m7 = 0.0f; - - matFrustum.m8 = ((float)right + (float)left)/rl; - matFrustum.m9 = ((float)top + (float)bottom)/tb; - matFrustum.m10 = -((float)zfar + (float)znear)/fn; - matFrustum.m11 = -1.0f; - - matFrustum.m12 = 0.0f; - matFrustum.m13 = 0.0f; - matFrustum.m14 = -((float)zfar*(float)znear*2.0f)/fn; - matFrustum.m15 = 0.0f; - - *RLGL.State.currentMatrix = rlMatrixMultiply(*RLGL.State.currentMatrix, matFrustum); -} - -// Multiply the current matrix by an orthographic matrix generated by parameters -void rlOrtho(double left, double right, double bottom, double top, double znear, double zfar) -{ - // NOTE: If left-right and top-botton values are equal it could create a division by zero, - // response to it is platform/compiler dependant - Matrix matOrtho = { 0 }; - - float rl = (float)(right - left); - float tb = (float)(top - bottom); - float fn = (float)(zfar - znear); - - matOrtho.m0 = 2.0f/rl; - matOrtho.m1 = 0.0f; - matOrtho.m2 = 0.0f; - matOrtho.m3 = 0.0f; - matOrtho.m4 = 0.0f; - matOrtho.m5 = 2.0f/tb; - matOrtho.m6 = 0.0f; - matOrtho.m7 = 0.0f; - matOrtho.m8 = 0.0f; - matOrtho.m9 = 0.0f; - matOrtho.m10 = -2.0f/fn; - matOrtho.m11 = 0.0f; - matOrtho.m12 = -((float)left + (float)right)/rl; - matOrtho.m13 = -((float)top + (float)bottom)/tb; - matOrtho.m14 = -((float)zfar + (float)znear)/fn; - matOrtho.m15 = 1.0f; - - *RLGL.State.currentMatrix = rlMatrixMultiply(*RLGL.State.currentMatrix, matOrtho); -} -#endif - -// Set the viewport area (transformation from normalized device coordinates to window coordinates) -// NOTE: We store current viewport dimensions -void rlViewport(int x, int y, int width, int height) -{ - glViewport(x, y, width, height); -} - -// Set clip planes distances -void rlSetClipPlanes(double nearPlane, double farPlane) -{ - rlCullDistanceNear = nearPlane; - rlCullDistanceFar = farPlane; -} - -// Get cull plane distance near -double rlGetCullDistanceNear(void) -{ - return rlCullDistanceNear; -} - -// Get cull plane distance far -double rlGetCullDistanceFar(void) -{ - return rlCullDistanceFar; -} - -//---------------------------------------------------------------------------------- -// Module Functions Definition - Vertex level operations -//---------------------------------------------------------------------------------- -#if defined(GRAPHICS_API_OPENGL_11) -// Fallback to OpenGL 1.1 function calls -//--------------------------------------- -void rlBegin(int mode) -{ - switch (mode) - { - case RL_LINES: glBegin(GL_LINES); break; - case RL_TRIANGLES: glBegin(GL_TRIANGLES); break; - case RL_QUADS: glBegin(GL_QUADS); break; - default: break; - } -} - -void rlEnd(void) { glEnd(); } -void rlVertex2i(int x, int y) { glVertex2i(x, y); } -void rlVertex2f(float x, float y) { glVertex2f(x, y); } -void rlVertex3f(float x, float y, float z) { glVertex3f(x, y, z); } -void rlTexCoord2f(float x, float y) { glTexCoord2f(x, y); } -void rlNormal3f(float x, float y, float z) { glNormal3f(x, y, z); } -void rlColor4ub(unsigned char r, unsigned char g, unsigned char b, unsigned char a) { glColor4ub(r, g, b, a); } -void rlColor3f(float x, float y, float z) { glColor3f(x, y, z); } -void rlColor4f(float x, float y, float z, float w) { glColor4f(x, y, z, w); } -#endif -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) -// Initialize drawing mode (how to organize vertex) -void rlBegin(int mode) -{ - // Draw mode can be RL_LINES, RL_TRIANGLES and RL_QUADS - // NOTE: In all three cases, vertex are accumulated over default internal vertex buffer - if (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode != mode) - { - if (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount > 0) - { - // Make sure current RLGL.currentBatch->draws[i].vertexCount is aligned a multiple of 4, - // that way, following QUADS drawing will keep aligned with index processing - // It implies adding some extra alignment vertex at the end of the draw, - // those vertex are not processed but they are considered as an additional offset - // for the next set of vertex to be drawn - if (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode == RL_LINES) RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexAlignment = ((RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount < 4)? RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount : RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount%4); - else if (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode == RL_TRIANGLES) RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexAlignment = ((RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount < 4)? 1 : (4 - (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount%4))); - else RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexAlignment = 0; - - if (!rlCheckRenderBatchLimit(RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexAlignment)) - { - RLGL.State.vertexCounter += RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexAlignment; - RLGL.currentBatch->drawCounter++; - } - } - - if (RLGL.currentBatch->drawCounter >= RL_DEFAULT_BATCH_DRAWCALLS) rlDrawRenderBatch(RLGL.currentBatch); - - RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode = mode; - RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount = 0; - RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].textureId = RLGL.State.defaultTextureId; - } -} - -// Finish vertex providing -void rlEnd(void) -{ - // NOTE: Depth increment is dependant on rlOrtho(): z-near and z-far values, - // as well as depth buffer bit-depth (16bit or 24bit or 32bit) - // Correct increment formula would be: depthInc = (zfar - znear)/pow(2, bits) - RLGL.currentBatch->currentDepth += (1.0f/20000.0f); -} - -// Define one vertex (position) -// NOTE: Vertex position data is the basic information required for drawing -void rlVertex3f(float x, float y, float z) -{ - float tx = x; - float ty = y; - float tz = z; - - // Transform provided vector if required - if (RLGL.State.transformRequired) - { - tx = RLGL.State.transform.m0*x + RLGL.State.transform.m4*y + RLGL.State.transform.m8*z + RLGL.State.transform.m12; - ty = RLGL.State.transform.m1*x + RLGL.State.transform.m5*y + RLGL.State.transform.m9*z + RLGL.State.transform.m13; - tz = RLGL.State.transform.m2*x + RLGL.State.transform.m6*y + RLGL.State.transform.m10*z + RLGL.State.transform.m14; - } - - // WARNING: We can't break primitives when launching a new batch - // RL_LINES comes in pairs, RL_TRIANGLES come in groups of 3 vertices and RL_QUADS come in groups of 4 vertices - // We must check current draw.mode when a new vertex is required and finish the batch only if the draw.mode draw.vertexCount is %2, %3 or %4 - if (RLGL.State.vertexCounter > (RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].elementCount*4 - 4)) - { - if ((RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode == RL_LINES) && - (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount%2 == 0)) - { - // Reached the maximum number of vertices for RL_LINES drawing - // Launch a draw call but keep current state for next vertices comming - // NOTE: We add +1 vertex to the check for security - rlCheckRenderBatchLimit(2 + 1); - } - else if ((RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode == RL_TRIANGLES) && - (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount%3 == 0)) - { - rlCheckRenderBatchLimit(3 + 1); - } - else if ((RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode == RL_QUADS) && - (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount%4 == 0)) - { - rlCheckRenderBatchLimit(4 + 1); - } - } - - // Add vertices - RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].vertices[3*RLGL.State.vertexCounter] = tx; - RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].vertices[3*RLGL.State.vertexCounter + 1] = ty; - RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].vertices[3*RLGL.State.vertexCounter + 2] = tz; - - // Add current texcoord - RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].texcoords[2*RLGL.State.vertexCounter] = RLGL.State.texcoordx; - RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].texcoords[2*RLGL.State.vertexCounter + 1] = RLGL.State.texcoordy; - - // Add current normal - RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].normals[3*RLGL.State.vertexCounter] = RLGL.State.normalx; - RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].normals[3*RLGL.State.vertexCounter + 1] = RLGL.State.normaly; - RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].normals[3*RLGL.State.vertexCounter + 2] = RLGL.State.normalz; - - // Add current color - RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].colors[4*RLGL.State.vertexCounter] = RLGL.State.colorr; - RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].colors[4*RLGL.State.vertexCounter + 1] = RLGL.State.colorg; - RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].colors[4*RLGL.State.vertexCounter + 2] = RLGL.State.colorb; - RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].colors[4*RLGL.State.vertexCounter + 3] = RLGL.State.colora; - - RLGL.State.vertexCounter++; - RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount++; -} - -// Define one vertex (position) -void rlVertex2f(float x, float y) -{ - rlVertex3f(x, y, RLGL.currentBatch->currentDepth); -} - -// Define one vertex (position) -void rlVertex2i(int x, int y) -{ - rlVertex3f((float)x, (float)y, RLGL.currentBatch->currentDepth); -} - -// Define one vertex (texture coordinate) -// NOTE: Texture coordinates are limited to QUADS only -void rlTexCoord2f(float x, float y) -{ - RLGL.State.texcoordx = x; - RLGL.State.texcoordy = y; -} - -// Define one vertex (normal) -// NOTE: Normals limited to TRIANGLES only? -void rlNormal3f(float x, float y, float z) -{ - float normalx = x; - float normaly = y; - float normalz = z; - if (RLGL.State.transformRequired) - { - normalx = RLGL.State.transform.m0*x + RLGL.State.transform.m4*y + RLGL.State.transform.m8*z; - normaly = RLGL.State.transform.m1*x + RLGL.State.transform.m5*y + RLGL.State.transform.m9*z; - normalz = RLGL.State.transform.m2*x + RLGL.State.transform.m6*y + RLGL.State.transform.m10*z; - } - float length = sqrtf(normalx*normalx + normaly*normaly + normalz*normalz); - if (length != 0.0f) - { - float ilength = 1.0f/length; - normalx *= ilength; - normaly *= ilength; - normalz *= ilength; - } - RLGL.State.normalx = normalx; - RLGL.State.normaly = normaly; - RLGL.State.normalz = normalz; -} - -// Define one vertex (color) -void rlColor4ub(unsigned char x, unsigned char y, unsigned char z, unsigned char w) -{ - RLGL.State.colorr = x; - RLGL.State.colorg = y; - RLGL.State.colorb = z; - RLGL.State.colora = w; -} - -// Define one vertex (color) -void rlColor4f(float r, float g, float b, float a) -{ - rlColor4ub((unsigned char)(r*255), (unsigned char)(g*255), (unsigned char)(b*255), (unsigned char)(a*255)); -} - -// Define one vertex (color) -void rlColor3f(float x, float y, float z) -{ - rlColor4ub((unsigned char)(x*255), (unsigned char)(y*255), (unsigned char)(z*255), 255); -} - -#endif - -//-------------------------------------------------------------------------------------- -// Module Functions Definition - OpenGL style functions (common to 1.1, 3.3+, ES2) -//-------------------------------------------------------------------------------------- - -// Set current texture to use -void rlSetTexture(unsigned int id) -{ - if (id == 0) - { -#if defined(GRAPHICS_API_OPENGL_11) - rlDisableTexture(); -#else - // NOTE: If quads batch limit is reached, we force a draw call and next batch starts - if (RLGL.State.vertexCounter >= - RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].elementCount*4) - { - rlDrawRenderBatch(RLGL.currentBatch); - } -#endif - } - else - { -#if defined(GRAPHICS_API_OPENGL_11) - rlEnableTexture(id); -#else - if (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].textureId != id) - { - if (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount > 0) - { - // Make sure current RLGL.currentBatch->draws[i].vertexCount is aligned a multiple of 4, - // that way, following QUADS drawing will keep aligned with index processing - // It implies adding some extra alignment vertex at the end of the draw, - // those vertex are not processed but they are considered as an additional offset - // for the next set of vertex to be drawn - if (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode == RL_LINES) RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexAlignment = ((RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount < 4)? RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount : RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount%4); - else if (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode == RL_TRIANGLES) RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexAlignment = ((RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount < 4)? 1 : (4 - (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount%4))); - else RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexAlignment = 0; - - if (!rlCheckRenderBatchLimit(RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexAlignment)) - { - RLGL.State.vertexCounter += RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexAlignment; - - RLGL.currentBatch->drawCounter++; - } - } - - if (RLGL.currentBatch->drawCounter >= RL_DEFAULT_BATCH_DRAWCALLS) rlDrawRenderBatch(RLGL.currentBatch); - - RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].textureId = id; - RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount = 0; - } -#endif - } -} - -// Select and active a texture slot -void rlActiveTextureSlot(int slot) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glActiveTexture(GL_TEXTURE0 + slot); -#endif -} - -// Enable texture -void rlEnableTexture(unsigned int id) -{ -#if defined(GRAPHICS_API_OPENGL_11) - glEnable(GL_TEXTURE_2D); -#endif - glBindTexture(GL_TEXTURE_2D, id); -} - -// Disable texture -void rlDisableTexture(void) -{ -#if defined(GRAPHICS_API_OPENGL_11) - glDisable(GL_TEXTURE_2D); -#endif - glBindTexture(GL_TEXTURE_2D, 0); -} - -// Enable texture cubemap -void rlEnableTextureCubemap(unsigned int id) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glBindTexture(GL_TEXTURE_CUBE_MAP, id); -#endif -} - -// Disable texture cubemap -void rlDisableTextureCubemap(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glBindTexture(GL_TEXTURE_CUBE_MAP, 0); -#endif -} - -// Set texture parameters (wrap mode/filter mode) -void rlTextureParameters(unsigned int id, int param, int value) -{ - glBindTexture(GL_TEXTURE_2D, id); - -#if !defined(GRAPHICS_API_OPENGL_11) - // Reset anisotropy filter, in case it was set - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1.0f); -#endif - - switch (param) - { - case RL_TEXTURE_WRAP_S: - case RL_TEXTURE_WRAP_T: - { - if (value == RL_TEXTURE_WRAP_MIRROR_CLAMP) - { -#if !defined(GRAPHICS_API_OPENGL_11) - if (RLGL.ExtSupported.texMirrorClamp) glTexParameteri(GL_TEXTURE_2D, param, value); - else TRACELOG(RL_LOG_WARNING, "GL: Clamp mirror wrap mode not supported (GL_MIRROR_CLAMP_EXT)"); -#endif - } - else glTexParameteri(GL_TEXTURE_2D, param, value); - - } break; - case RL_TEXTURE_MAG_FILTER: - case RL_TEXTURE_MIN_FILTER: glTexParameteri(GL_TEXTURE_2D, param, value); break; - case RL_TEXTURE_FILTER_ANISOTROPIC: - { -#if !defined(GRAPHICS_API_OPENGL_11) - if (value <= RLGL.ExtSupported.maxAnisotropyLevel) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, (float)value); - else if (RLGL.ExtSupported.maxAnisotropyLevel > 0.0f) - { - TRACELOG(RL_LOG_WARNING, "GL: Maximum anisotropic filter level supported is %iX", id, (int)RLGL.ExtSupported.maxAnisotropyLevel); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, (float)value); - } - else TRACELOG(RL_LOG_WARNING, "GL: Anisotropic filtering not supported"); -#endif - } break; -#if defined(GRAPHICS_API_OPENGL_33) - case RL_TEXTURE_MIPMAP_BIAS_RATIO: glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_LOD_BIAS, value/100.0f); -#endif - default: break; - } - - glBindTexture(GL_TEXTURE_2D, 0); -} - -// Set cubemap parameters (wrap mode/filter mode) -void rlCubemapParameters(unsigned int id, int param, int value) -{ -#if !defined(GRAPHICS_API_OPENGL_11) - glBindTexture(GL_TEXTURE_CUBE_MAP, id); - - // Reset anisotropy filter, in case it was set - glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1.0f); - - switch (param) - { - case RL_TEXTURE_WRAP_S: - case RL_TEXTURE_WRAP_T: - { - if (value == RL_TEXTURE_WRAP_MIRROR_CLAMP) - { - if (RLGL.ExtSupported.texMirrorClamp) glTexParameteri(GL_TEXTURE_CUBE_MAP, param, value); - else TRACELOG(RL_LOG_WARNING, "GL: Clamp mirror wrap mode not supported (GL_MIRROR_CLAMP_EXT)"); - } - else glTexParameteri(GL_TEXTURE_CUBE_MAP, param, value); - - } break; - case RL_TEXTURE_MAG_FILTER: - case RL_TEXTURE_MIN_FILTER: glTexParameteri(GL_TEXTURE_CUBE_MAP, param, value); break; - case RL_TEXTURE_FILTER_ANISOTROPIC: - { - if (value <= RLGL.ExtSupported.maxAnisotropyLevel) glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_ANISOTROPY_EXT, (float)value); - else if (RLGL.ExtSupported.maxAnisotropyLevel > 0.0f) - { - TRACELOG(RL_LOG_WARNING, "GL: Maximum anisotropic filter level supported is %iX", id, (int)RLGL.ExtSupported.maxAnisotropyLevel); - glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_ANISOTROPY_EXT, (float)value); - } - else TRACELOG(RL_LOG_WARNING, "GL: Anisotropic filtering not supported"); - } break; -#if defined(GRAPHICS_API_OPENGL_33) - case RL_TEXTURE_MIPMAP_BIAS_RATIO: glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_LOD_BIAS, value/100.0f); -#endif - default: break; - } - - glBindTexture(GL_TEXTURE_CUBE_MAP, 0); -#endif -} - -// Enable shader program -void rlEnableShader(unsigned int id) -{ -#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) - glUseProgram(id); -#endif -} - -// Disable shader program -void rlDisableShader(void) -{ -#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) - glUseProgram(0); -#endif -} - -// Enable rendering to texture (fbo) -void rlEnableFramebuffer(unsigned int id) -{ -#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) && defined(RLGL_RENDER_TEXTURES_HINT) - glBindFramebuffer(GL_FRAMEBUFFER, id); -#endif -} - -// return the active render texture (fbo) -unsigned int rlGetActiveFramebuffer(void) -{ - GLint fboId = 0; -#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES3)) && defined(RLGL_RENDER_TEXTURES_HINT) - glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &fboId); -#endif - return fboId; -} - -// Disable rendering to texture -void rlDisableFramebuffer(void) -{ -#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) && defined(RLGL_RENDER_TEXTURES_HINT) - glBindFramebuffer(GL_FRAMEBUFFER, 0); -#endif -} - -// Blit active framebuffer to main framebuffer -void rlBlitFramebuffer(int srcX, int srcY, int srcWidth, int srcHeight, int dstX, int dstY, int dstWidth, int dstHeight, int bufferMask) -{ -#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES3)) && defined(RLGL_RENDER_TEXTURES_HINT) - glBlitFramebuffer(srcX, srcY, srcWidth, srcHeight, dstX, dstY, dstWidth, dstHeight, bufferMask, GL_NEAREST); -#endif -} - -// Bind framebuffer object (fbo) -void rlBindFramebuffer(unsigned int target, unsigned int framebuffer) -{ -#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) && defined(RLGL_RENDER_TEXTURES_HINT) - glBindFramebuffer(target, framebuffer); -#endif -} - -// Activate multiple draw color buffers -// NOTE: One color buffer is always active by default -void rlActiveDrawBuffers(int count) -{ -#if ((defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES3)) && defined(RLGL_RENDER_TEXTURES_HINT)) - // NOTE: Maximum number of draw buffers supported is implementation dependant, - // it can be queried with glGet*() but it must be at least 8 - //GLint maxDrawBuffers = 0; - //glGetIntegerv(GL_MAX_DRAW_BUFFERS, &maxDrawBuffers); - - if (count > 0) - { - if (count > 8) TRACELOG(LOG_WARNING, "GL: Max color buffers limited to 8"); - else - { - unsigned int buffers[8] = { -#if defined(GRAPHICS_API_OPENGL_ES3) - GL_COLOR_ATTACHMENT0_EXT, - GL_COLOR_ATTACHMENT1_EXT, - GL_COLOR_ATTACHMENT2_EXT, - GL_COLOR_ATTACHMENT3_EXT, - GL_COLOR_ATTACHMENT4_EXT, - GL_COLOR_ATTACHMENT5_EXT, - GL_COLOR_ATTACHMENT6_EXT, - GL_COLOR_ATTACHMENT7_EXT, -#else - GL_COLOR_ATTACHMENT0, - GL_COLOR_ATTACHMENT1, - GL_COLOR_ATTACHMENT2, - GL_COLOR_ATTACHMENT3, - GL_COLOR_ATTACHMENT4, - GL_COLOR_ATTACHMENT5, - GL_COLOR_ATTACHMENT6, - GL_COLOR_ATTACHMENT7, -#endif - }; - -#if defined(GRAPHICS_API_OPENGL_ES3) - glDrawBuffersEXT(count, buffers); -#else - glDrawBuffers(count, buffers); -#endif - } - } - else TRACELOG(LOG_WARNING, "GL: One color buffer active by default"); -#endif -} - -//---------------------------------------------------------------------------------- -// General render state configuration -//---------------------------------------------------------------------------------- - -// Enable color blending -void rlEnableColorBlend(void) { glEnable(GL_BLEND); } - -// Disable color blending -void rlDisableColorBlend(void) { glDisable(GL_BLEND); } - -// Enable depth test -void rlEnableDepthTest(void) { glEnable(GL_DEPTH_TEST); } - -// Disable depth test -void rlDisableDepthTest(void) { glDisable(GL_DEPTH_TEST); } - -// Enable depth write -void rlEnableDepthMask(void) { glDepthMask(GL_TRUE); } - -// Disable depth write -void rlDisableDepthMask(void) { glDepthMask(GL_FALSE); } - -// Enable backface culling -void rlEnableBackfaceCulling(void) { glEnable(GL_CULL_FACE); } - -// Disable backface culling -void rlDisableBackfaceCulling(void) { glDisable(GL_CULL_FACE); } - -// Set color mask active for screen read/draw -void rlColorMask(bool r, bool g, bool b, bool a) { glColorMask(r, g, b, a); } - -// Set face culling mode -void rlSetCullFace(int mode) -{ - switch (mode) - { - case RL_CULL_FACE_BACK: glCullFace(GL_BACK); break; - case RL_CULL_FACE_FRONT: glCullFace(GL_FRONT); break; - default: break; - } -} - -// Enable scissor test -void rlEnableScissorTest(void) { glEnable(GL_SCISSOR_TEST); } - -// Disable scissor test -void rlDisableScissorTest(void) { glDisable(GL_SCISSOR_TEST); } - -// Scissor test -void rlScissor(int x, int y, int width, int height) { glScissor(x, y, width, height); } - -// Enable wire mode -void rlEnableWireMode(void) -{ -#if defined(GRAPHICS_API_OPENGL_11) || defined(GRAPHICS_API_OPENGL_33) - // NOTE: glPolygonMode() not available on OpenGL ES - glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); -#endif -} - -// Enable point mode -void rlEnablePointMode(void) -{ -#if defined(GRAPHICS_API_OPENGL_11) || defined(GRAPHICS_API_OPENGL_33) - // NOTE: glPolygonMode() not available on OpenGL ES - glPolygonMode(GL_FRONT_AND_BACK, GL_POINT); - glEnable(GL_PROGRAM_POINT_SIZE); -#endif -} - -// Disable wire mode -void rlDisableWireMode(void) -{ -#if defined(GRAPHICS_API_OPENGL_11) || defined(GRAPHICS_API_OPENGL_33) - // NOTE: glPolygonMode() not available on OpenGL ES - glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); -#endif -} - -// Set the line drawing width -void rlSetLineWidth(float width) { glLineWidth(width); } - -// Get the line drawing width -float rlGetLineWidth(void) -{ - float width = 0; - glGetFloatv(GL_LINE_WIDTH, &width); - return width; -} - -// Enable line aliasing -void rlEnableSmoothLines(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_11) - glEnable(GL_LINE_SMOOTH); -#endif -} - -// Disable line aliasing -void rlDisableSmoothLines(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_11) - glDisable(GL_LINE_SMOOTH); -#endif -} - -// Enable stereo rendering -void rlEnableStereoRender(void) -{ -#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) - RLGL.State.stereoRender = true; -#endif -} - -// Disable stereo rendering -void rlDisableStereoRender(void) -{ -#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) - RLGL.State.stereoRender = false; -#endif -} - -// Check if stereo render is enabled -bool rlIsStereoRenderEnabled(void) -{ -#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) - return RLGL.State.stereoRender; -#else - return false; -#endif -} - -// Clear color buffer with color -void rlClearColor(unsigned char r, unsigned char g, unsigned char b, unsigned char a) -{ - // Color values clamp to 0.0f(0) and 1.0f(255) - float cr = (float)r/255; - float cg = (float)g/255; - float cb = (float)b/255; - float ca = (float)a/255; - - glClearColor(cr, cg, cb, ca); -} - -// Clear used screen buffers (color and depth) -void rlClearScreenBuffers(void) -{ - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear used buffers: Color and Depth (Depth is used for 3D) - //glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); // Stencil buffer not used... -} - -// Check and log OpenGL error codes -void rlCheckErrors(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - int check = 1; - while (check) - { - const GLenum err = glGetError(); - switch (err) - { - case GL_NO_ERROR: check = 0; break; - case 0x0500: TRACELOG(RL_LOG_WARNING, "GL: Error detected: GL_INVALID_ENUM"); break; - case 0x0501: TRACELOG(RL_LOG_WARNING, "GL: Error detected: GL_INVALID_VALUE"); break; - case 0x0502: TRACELOG(RL_LOG_WARNING, "GL: Error detected: GL_INVALID_OPERATION"); break; - case 0x0503: TRACELOG(RL_LOG_WARNING, "GL: Error detected: GL_STACK_OVERFLOW"); break; - case 0x0504: TRACELOG(RL_LOG_WARNING, "GL: Error detected: GL_STACK_UNDERFLOW"); break; - case 0x0505: TRACELOG(RL_LOG_WARNING, "GL: Error detected: GL_OUT_OF_MEMORY"); break; - case 0x0506: TRACELOG(RL_LOG_WARNING, "GL: Error detected: GL_INVALID_FRAMEBUFFER_OPERATION"); break; - default: TRACELOG(RL_LOG_WARNING, "GL: Error detected: Unknown error code: %x", err); break; - } - } -#endif -} - -// Set blend mode -void rlSetBlendMode(int mode) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if ((RLGL.State.currentBlendMode != mode) || ((mode == RL_BLEND_CUSTOM || mode == RL_BLEND_CUSTOM_SEPARATE) && RLGL.State.glCustomBlendModeModified)) - { - rlDrawRenderBatch(RLGL.currentBatch); - - switch (mode) - { - case RL_BLEND_ALPHA: glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBlendEquation(GL_FUNC_ADD); break; - case RL_BLEND_ADDITIVE: glBlendFunc(GL_SRC_ALPHA, GL_ONE); glBlendEquation(GL_FUNC_ADD); break; - case RL_BLEND_MULTIPLIED: glBlendFunc(GL_DST_COLOR, GL_ONE_MINUS_SRC_ALPHA); glBlendEquation(GL_FUNC_ADD); break; - case RL_BLEND_ADD_COLORS: glBlendFunc(GL_ONE, GL_ONE); glBlendEquation(GL_FUNC_ADD); break; - case RL_BLEND_SUBTRACT_COLORS: glBlendFunc(GL_ONE, GL_ONE); glBlendEquation(GL_FUNC_SUBTRACT); break; - case RL_BLEND_ALPHA_PREMULTIPLY: glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); glBlendEquation(GL_FUNC_ADD); break; - case RL_BLEND_CUSTOM: - { - // NOTE: Using GL blend src/dst factors and GL equation configured with rlSetBlendFactors() - glBlendFunc(RLGL.State.glBlendSrcFactor, RLGL.State.glBlendDstFactor); glBlendEquation(RLGL.State.glBlendEquation); - - } break; - case RL_BLEND_CUSTOM_SEPARATE: - { - // NOTE: Using GL blend src/dst factors and GL equation configured with rlSetBlendFactorsSeparate() - glBlendFuncSeparate(RLGL.State.glBlendSrcFactorRGB, RLGL.State.glBlendDestFactorRGB, RLGL.State.glBlendSrcFactorAlpha, RLGL.State.glBlendDestFactorAlpha); - glBlendEquationSeparate(RLGL.State.glBlendEquationRGB, RLGL.State.glBlendEquationAlpha); - - } break; - default: break; - } - - RLGL.State.currentBlendMode = mode; - RLGL.State.glCustomBlendModeModified = false; - } -#endif -} - -// Set blending mode factor and equation -void rlSetBlendFactors(int glSrcFactor, int glDstFactor, int glEquation) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if ((RLGL.State.glBlendSrcFactor != glSrcFactor) || - (RLGL.State.glBlendDstFactor != glDstFactor) || - (RLGL.State.glBlendEquation != glEquation)) - { - RLGL.State.glBlendSrcFactor = glSrcFactor; - RLGL.State.glBlendDstFactor = glDstFactor; - RLGL.State.glBlendEquation = glEquation; - - RLGL.State.glCustomBlendModeModified = true; - } -#endif -} - -// Set blending mode factor and equation separately for RGB and alpha -void rlSetBlendFactorsSeparate(int glSrcRGB, int glDstRGB, int glSrcAlpha, int glDstAlpha, int glEqRGB, int glEqAlpha) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if ((RLGL.State.glBlendSrcFactorRGB != glSrcRGB) || - (RLGL.State.glBlendDestFactorRGB != glDstRGB) || - (RLGL.State.glBlendSrcFactorAlpha != glSrcAlpha) || - (RLGL.State.glBlendDestFactorAlpha != glDstAlpha) || - (RLGL.State.glBlendEquationRGB != glEqRGB) || - (RLGL.State.glBlendEquationAlpha != glEqAlpha)) - { - RLGL.State.glBlendSrcFactorRGB = glSrcRGB; - RLGL.State.glBlendDestFactorRGB = glDstRGB; - RLGL.State.glBlendSrcFactorAlpha = glSrcAlpha; - RLGL.State.glBlendDestFactorAlpha = glDstAlpha; - RLGL.State.glBlendEquationRGB = glEqRGB; - RLGL.State.glBlendEquationAlpha = glEqAlpha; - - RLGL.State.glCustomBlendModeModified = true; - } -#endif -} - -//---------------------------------------------------------------------------------- -// Module Functions Definition - OpenGL Debug -//---------------------------------------------------------------------------------- -#if defined(RLGL_ENABLE_OPENGL_DEBUG_CONTEXT) && defined(GRAPHICS_API_OPENGL_43) -static void GLAPIENTRY rlDebugMessageCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam) -{ - // Ignore non-significant error/warning codes (NVidia drivers) - // NOTE: Here there are the details with a sample output: - // - #131169 - Framebuffer detailed info: The driver allocated storage for renderbuffer 2. (severity: low) - // - #131185 - Buffer detailed info: Buffer object 1 (bound to GL_ELEMENT_ARRAY_BUFFER_ARB, usage hint is GL_ENUM_88e4) - // will use VIDEO memory as the source for buffer object operations. (severity: low) - // - #131218 - Program/shader state performance warning: Vertex shader in program 7 is being recompiled based on GL state. (severity: medium) - // - #131204 - Texture state usage warning: The texture object (0) bound to texture image unit 0 does not have - // a defined base level and cannot be used for texture mapping. (severity: low) - if ((id == 131169) || (id == 131185) || (id == 131218) || (id == 131204)) return; - - const char *msgSource = NULL; - switch (source) - { - case GL_DEBUG_SOURCE_API: msgSource = "API"; break; - case GL_DEBUG_SOURCE_WINDOW_SYSTEM: msgSource = "WINDOW_SYSTEM"; break; - case GL_DEBUG_SOURCE_SHADER_COMPILER: msgSource = "SHADER_COMPILER"; break; - case GL_DEBUG_SOURCE_THIRD_PARTY: msgSource = "THIRD_PARTY"; break; - case GL_DEBUG_SOURCE_APPLICATION: msgSource = "APPLICATION"; break; - case GL_DEBUG_SOURCE_OTHER: msgSource = "OTHER"; break; - default: break; - } - - const char *msgType = NULL; - switch (type) - { - case GL_DEBUG_TYPE_ERROR: msgType = "ERROR"; break; - case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: msgType = "DEPRECATED_BEHAVIOR"; break; - case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: msgType = "UNDEFINED_BEHAVIOR"; break; - case GL_DEBUG_TYPE_PORTABILITY: msgType = "PORTABILITY"; break; - case GL_DEBUG_TYPE_PERFORMANCE: msgType = "PERFORMANCE"; break; - case GL_DEBUG_TYPE_MARKER: msgType = "MARKER"; break; - case GL_DEBUG_TYPE_PUSH_GROUP: msgType = "PUSH_GROUP"; break; - case GL_DEBUG_TYPE_POP_GROUP: msgType = "POP_GROUP"; break; - case GL_DEBUG_TYPE_OTHER: msgType = "OTHER"; break; - default: break; - } - - const char *msgSeverity = "DEFAULT"; - switch (severity) - { - case GL_DEBUG_SEVERITY_LOW: msgSeverity = "LOW"; break; - case GL_DEBUG_SEVERITY_MEDIUM: msgSeverity = "MEDIUM"; break; - case GL_DEBUG_SEVERITY_HIGH: msgSeverity = "HIGH"; break; - case GL_DEBUG_SEVERITY_NOTIFICATION: msgSeverity = "NOTIFICATION"; break; - default: break; - } - - TRACELOG(LOG_WARNING, "GL: OpenGL debug message: %s", message); - TRACELOG(LOG_WARNING, " > Type: %s", msgType); - TRACELOG(LOG_WARNING, " > Source = %s", msgSource); - TRACELOG(LOG_WARNING, " > Severity = %s", msgSeverity); -} -#endif - -//---------------------------------------------------------------------------------- -// Module Functions Definition - rlgl functionality -//---------------------------------------------------------------------------------- - -// Initialize rlgl: OpenGL extensions, default buffers/shaders/textures, OpenGL states -void rlglInit(int width, int height) -{ - // Enable OpenGL debug context if required -#if defined(RLGL_ENABLE_OPENGL_DEBUG_CONTEXT) && defined(GRAPHICS_API_OPENGL_43) - if ((glDebugMessageCallback != NULL) && (glDebugMessageControl != NULL)) - { - glDebugMessageCallback(rlDebugMessageCallback, 0); - // glDebugMessageControl(GL_DEBUG_SOURCE_API, GL_DEBUG_TYPE_ERROR, GL_DEBUG_SEVERITY_HIGH, 0, 0, GL_TRUE); - - // Debug context options: - // - GL_DEBUG_OUTPUT - Faster version but not useful for breakpoints - // - GL_DEBUG_OUTPUT_SYNCHRONUS - Callback is in sync with errors, so a breakpoint can be placed on the callback in order to get a stacktrace for the GL error - glEnable(GL_DEBUG_OUTPUT); - glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); - } -#endif - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - // Init default white texture - unsigned char pixels[4] = { 255, 255, 255, 255 }; // 1 pixel RGBA (4 bytes) - RLGL.State.defaultTextureId = rlLoadTexture(pixels, 1, 1, RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8A8, 1); - - if (RLGL.State.defaultTextureId != 0) TRACELOG(RL_LOG_INFO, "TEXTURE: [ID %i] Default texture loaded successfully", RLGL.State.defaultTextureId); - else TRACELOG(RL_LOG_WARNING, "TEXTURE: Failed to load default texture"); - - // Init default Shader (customized for GL 3.3 and ES2) - // Loaded: RLGL.State.defaultShaderId + RLGL.State.defaultShaderLocs - rlLoadShaderDefault(); - RLGL.State.currentShaderId = RLGL.State.defaultShaderId; - RLGL.State.currentShaderLocs = RLGL.State.defaultShaderLocs; - - // Init default vertex arrays buffers - // Simulate that the default shader has the location RL_SHADER_LOC_VERTEX_NORMAL to bind the normal buffer for the default render batch - RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_NORMAL] = RL_DEFAULT_SHADER_ATTRIB_LOCATION_NORMAL; - RLGL.defaultBatch = rlLoadRenderBatch(RL_DEFAULT_BATCH_BUFFERS, RL_DEFAULT_BATCH_BUFFER_ELEMENTS); - RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_NORMAL] = -1; - RLGL.currentBatch = &RLGL.defaultBatch; - - // Init stack matrices (emulating OpenGL 1.1) - for (int i = 0; i < RL_MAX_MATRIX_STACK_SIZE; i++) RLGL.State.stack[i] = rlMatrixIdentity(); - - // Init internal matrices - RLGL.State.transform = rlMatrixIdentity(); - RLGL.State.projection = rlMatrixIdentity(); - RLGL.State.modelview = rlMatrixIdentity(); - RLGL.State.currentMatrix = &RLGL.State.modelview; -#endif // GRAPHICS_API_OPENGL_33 || GRAPHICS_API_OPENGL_ES2 - - // Initialize OpenGL default states - //---------------------------------------------------------- - // Init state: Depth test - glDepthFunc(GL_LEQUAL); // Type of depth testing to apply - glDisable(GL_DEPTH_TEST); // Disable depth testing for 2D (only used for 3D) - - // Init state: Blending mode - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Color blending function (how colors are mixed) - glEnable(GL_BLEND); // Enable color blending (required to work with transparencies) - - // Init state: Culling - // NOTE: All shapes/models triangles are drawn CCW - glCullFace(GL_BACK); // Cull the back face (default) - glFrontFace(GL_CCW); // Front face are defined counter clockwise (default) - glEnable(GL_CULL_FACE); // Enable backface culling - - // Init state: Cubemap seamless -#if defined(GRAPHICS_API_OPENGL_33) - glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); // Seamless cubemaps (not supported on OpenGL ES 2.0) -#endif - -#if defined(GRAPHICS_API_OPENGL_11) - // Init state: Color hints (deprecated in OpenGL 3.0+) - glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Improve quality of color and texture coordinate interpolation - glShadeModel(GL_SMOOTH); // Smooth shading between vertex (vertex colors interpolation) -#endif - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - // Store screen size into global variables - RLGL.State.framebufferWidth = width; - RLGL.State.framebufferHeight = height; - - TRACELOG(RL_LOG_INFO, "RLGL: Default OpenGL state initialized successfully"); - //---------------------------------------------------------- -#endif - - // Init state: Color/Depth buffers clear - glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Set clear color (black) - glClearDepth(1.0f); // Set clear depth value (default) - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear color and depth buffers (depth buffer required for 3D) -} - -// Vertex Buffer Object deinitialization (memory free) -void rlglClose(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - rlUnloadRenderBatch(RLGL.defaultBatch); - - rlUnloadShaderDefault(); // Unload default shader - - glDeleteTextures(1, &RLGL.State.defaultTextureId); // Unload default texture - TRACELOG(RL_LOG_INFO, "TEXTURE: [ID %i] Default texture unloaded successfully", RLGL.State.defaultTextureId); -#endif -} - -// Load OpenGL extensions -// NOTE: External loader function must be provided -void rlLoadExtensions(void *loader) -{ -#if defined(GRAPHICS_API_OPENGL_33) // Also defined for GRAPHICS_API_OPENGL_21 - // NOTE: glad is generated and contains only required OpenGL 3.3 Core extensions (and lower versions) - if (gladLoadGL((GLADloadfunc)loader) == 0) TRACELOG(RL_LOG_WARNING, "GLAD: Cannot load OpenGL extensions"); - else TRACELOG(RL_LOG_INFO, "GLAD: OpenGL extensions loaded successfully"); - - // Get number of supported extensions - GLint numExt = 0; - glGetIntegerv(GL_NUM_EXTENSIONS, &numExt); - TRACELOG(RL_LOG_INFO, "GL: Supported extensions count: %i", numExt); - -#if defined(RLGL_SHOW_GL_DETAILS_INFO) - // Get supported extensions list - // WARNING: glGetStringi() not available on OpenGL 2.1 - TRACELOG(RL_LOG_INFO, "GL: OpenGL extensions:"); - for (int i = 0; i < numExt; i++) TRACELOG(RL_LOG_INFO, " %s", glGetStringi(GL_EXTENSIONS, i)); -#endif - -#if defined(GRAPHICS_API_OPENGL_21) - // Register supported extensions flags - // Optional OpenGL 2.1 extensions - RLGL.ExtSupported.vao = GLAD_GL_ARB_vertex_array_object; - RLGL.ExtSupported.instancing = (GLAD_GL_EXT_draw_instanced && GLAD_GL_ARB_instanced_arrays); - RLGL.ExtSupported.texNPOT = GLAD_GL_ARB_texture_non_power_of_two; - RLGL.ExtSupported.texFloat32 = GLAD_GL_ARB_texture_float; - RLGL.ExtSupported.texFloat16 = GLAD_GL_ARB_texture_float; - RLGL.ExtSupported.texDepth = GLAD_GL_ARB_depth_texture; - RLGL.ExtSupported.maxDepthBits = 32; - RLGL.ExtSupported.texAnisoFilter = GLAD_GL_EXT_texture_filter_anisotropic; - RLGL.ExtSupported.texMirrorClamp = GLAD_GL_EXT_texture_mirror_clamp; -#else - // Register supported extensions flags - // OpenGL 3.3 extensions supported by default (core) - RLGL.ExtSupported.vao = true; - RLGL.ExtSupported.instancing = true; - RLGL.ExtSupported.texNPOT = true; - RLGL.ExtSupported.texFloat32 = true; - RLGL.ExtSupported.texFloat16 = true; - RLGL.ExtSupported.texDepth = true; - RLGL.ExtSupported.maxDepthBits = 32; - RLGL.ExtSupported.texAnisoFilter = true; - RLGL.ExtSupported.texMirrorClamp = true; -#endif - - // Optional OpenGL 3.3 extensions - RLGL.ExtSupported.texCompASTC = GLAD_GL_KHR_texture_compression_astc_hdr && GLAD_GL_KHR_texture_compression_astc_ldr; - RLGL.ExtSupported.texCompDXT = GLAD_GL_EXT_texture_compression_s3tc; // Texture compression: DXT - RLGL.ExtSupported.texCompETC2 = GLAD_GL_ARB_ES3_compatibility; // Texture compression: ETC2/EAC - #if defined(GRAPHICS_API_OPENGL_43) - RLGL.ExtSupported.computeShader = GLAD_GL_ARB_compute_shader; - RLGL.ExtSupported.ssbo = GLAD_GL_ARB_shader_storage_buffer_object; - #endif - -#endif // GRAPHICS_API_OPENGL_33 - -#if defined(GRAPHICS_API_OPENGL_ES3) - // Register supported extensions flags - // OpenGL ES 3.0 extensions supported by default (or it should be) - RLGL.ExtSupported.vao = true; - RLGL.ExtSupported.instancing = true; - RLGL.ExtSupported.texNPOT = true; - RLGL.ExtSupported.texFloat32 = true; - RLGL.ExtSupported.texFloat16 = true; - RLGL.ExtSupported.texDepth = true; - RLGL.ExtSupported.texDepthWebGL = true; - RLGL.ExtSupported.maxDepthBits = 24; - RLGL.ExtSupported.texAnisoFilter = true; - RLGL.ExtSupported.texMirrorClamp = true; - // TODO: Check for additional OpenGL ES 3.0 supported extensions: - //RLGL.ExtSupported.texCompDXT = true; - //RLGL.ExtSupported.texCompETC1 = true; - //RLGL.ExtSupported.texCompETC2 = true; - //RLGL.ExtSupported.texCompPVRT = true; - //RLGL.ExtSupported.texCompASTC = true; - //RLGL.ExtSupported.maxAnisotropyLevel = true; - //RLGL.ExtSupported.computeShader = true; - //RLGL.ExtSupported.ssbo = true; - -#elif defined(GRAPHICS_API_OPENGL_ES2) - - #if defined(PLATFORM_DESKTOP_GLFW) || defined(PLATFORM_DESKTOP_SDL) - // TODO: Support GLAD loader for OpenGL ES 3.0 - if (gladLoadGLES2((GLADloadfunc)loader) == 0) TRACELOG(RL_LOG_WARNING, "GLAD: Cannot load OpenGL ES2.0 functions"); - else TRACELOG(RL_LOG_INFO, "GLAD: OpenGL ES 2.0 loaded successfully"); - #endif - - // Get supported extensions list - GLint numExt = 0; - const char **extList = RL_MALLOC(512*sizeof(const char *)); // Allocate 512 strings pointers (2 KB) - const char *extensions = (const char *)glGetString(GL_EXTENSIONS); // One big const string - - // NOTE: We have to duplicate string because glGetString() returns a const string - int size = strlen(extensions) + 1; // Get extensions string size in bytes - char *extensionsDup = (char *)RL_CALLOC(size, sizeof(char)); - strcpy(extensionsDup, extensions); - extList[numExt] = extensionsDup; - - for (int i = 0; i < size; i++) - { - if (extensionsDup[i] == ' ') - { - extensionsDup[i] = '\0'; - numExt++; - extList[numExt] = &extensionsDup[i + 1]; - } - } - - TRACELOG(RL_LOG_INFO, "GL: Supported extensions count: %i", numExt); - -#if defined(RLGL_SHOW_GL_DETAILS_INFO) - TRACELOG(RL_LOG_INFO, "GL: OpenGL extensions:"); - for (int i = 0; i < numExt; i++) TRACELOG(RL_LOG_INFO, " %s", extList[i]); -#endif - - // Check required extensions - for (int i = 0; i < numExt; i++) - { - // Check VAO support - // NOTE: Only check on OpenGL ES, OpenGL 3.3 has VAO support as core feature - if (strcmp(extList[i], (const char *)"GL_OES_vertex_array_object") == 0) - { - // The extension is supported by our hardware and driver, try to get related functions pointers - // NOTE: emscripten does not support VAOs natively, it uses emulation and it reduces overall performance... - glGenVertexArrays = (PFNGLGENVERTEXARRAYSOESPROC)((rlglLoadProc)loader)("glGenVertexArraysOES"); - glBindVertexArray = (PFNGLBINDVERTEXARRAYOESPROC)((rlglLoadProc)loader)("glBindVertexArrayOES"); - glDeleteVertexArrays = (PFNGLDELETEVERTEXARRAYSOESPROC)((rlglLoadProc)loader)("glDeleteVertexArraysOES"); - //glIsVertexArray = (PFNGLISVERTEXARRAYOESPROC)loader("glIsVertexArrayOES"); // NOTE: Fails in WebGL, omitted - - if ((glGenVertexArrays != NULL) && (glBindVertexArray != NULL) && (glDeleteVertexArrays != NULL)) RLGL.ExtSupported.vao = true; - } - - // Check instanced rendering support - if (strstr(extList[i], (const char*)"instanced_arrays") != NULL) // Broad check for instanced_arrays - { - // Specific check - if (strcmp(extList[i], (const char *)"GL_ANGLE_instanced_arrays") == 0) // ANGLE - { - glDrawArraysInstanced = (PFNGLDRAWARRAYSINSTANCEDEXTPROC)((rlglLoadProc)loader)("glDrawArraysInstancedANGLE"); - glDrawElementsInstanced = (PFNGLDRAWELEMENTSINSTANCEDEXTPROC)((rlglLoadProc)loader)("glDrawElementsInstancedANGLE"); - glVertexAttribDivisor = (PFNGLVERTEXATTRIBDIVISOREXTPROC)((rlglLoadProc)loader)("glVertexAttribDivisorANGLE"); - } - else if (strcmp(extList[i], (const char *)"GL_EXT_instanced_arrays") == 0) // EXT - { - glDrawArraysInstanced = (PFNGLDRAWARRAYSINSTANCEDEXTPROC)((rlglLoadProc)loader)("glDrawArraysInstancedEXT"); - glDrawElementsInstanced = (PFNGLDRAWELEMENTSINSTANCEDEXTPROC)((rlglLoadProc)loader)("glDrawElementsInstancedEXT"); - glVertexAttribDivisor = (PFNGLVERTEXATTRIBDIVISOREXTPROC)((rlglLoadProc)loader)("glVertexAttribDivisorEXT"); - } - else if (strcmp(extList[i], (const char *)"GL_NV_instanced_arrays") == 0) // NVIDIA GLES - { - glDrawArraysInstanced = (PFNGLDRAWARRAYSINSTANCEDEXTPROC)((rlglLoadProc)loader)("glDrawArraysInstancedNV"); - glDrawElementsInstanced = (PFNGLDRAWELEMENTSINSTANCEDEXTPROC)((rlglLoadProc)loader)("glDrawElementsInstancedNV"); - glVertexAttribDivisor = (PFNGLVERTEXATTRIBDIVISOREXTPROC)((rlglLoadProc)loader)("glVertexAttribDivisorNV"); - } - - // The feature will only be marked as supported if the elements from GL_XXX_instanced_arrays are present - if ((glDrawArraysInstanced != NULL) && (glDrawElementsInstanced != NULL) && (glVertexAttribDivisor != NULL)) RLGL.ExtSupported.instancing = true; - } - else if (strstr(extList[i], (const char *)"draw_instanced") != NULL) - { - // GL_ANGLE_draw_instanced doesn't exist - if (strcmp(extList[i], (const char *)"GL_EXT_draw_instanced") == 0) - { - glDrawArraysInstanced = (PFNGLDRAWARRAYSINSTANCEDEXTPROC)((rlglLoadProc)loader)("glDrawArraysInstancedEXT"); - glDrawElementsInstanced = (PFNGLDRAWELEMENTSINSTANCEDEXTPROC)((rlglLoadProc)loader)("glDrawElementsInstancedEXT"); - } - else if (strcmp(extList[i], (const char*)"GL_NV_draw_instanced") == 0) - { - glDrawArraysInstanced = (PFNGLDRAWARRAYSINSTANCEDEXTPROC)((rlglLoadProc)loader)("glDrawArraysInstancedNV"); - glDrawElementsInstanced = (PFNGLDRAWELEMENTSINSTANCEDEXTPROC)((rlglLoadProc)loader)("glDrawElementsInstancedNV"); - } - - // But the functions will at least be loaded if only GL_XX_EXT_draw_instanced exist - if ((glDrawArraysInstanced != NULL) && (glDrawElementsInstanced != NULL) && (glVertexAttribDivisor != NULL)) RLGL.ExtSupported.instancing = true; - } - - // Check NPOT textures support - // NOTE: Only check on OpenGL ES, OpenGL 3.3 has NPOT textures full support as core feature - if (strcmp(extList[i], (const char *)"GL_OES_texture_npot") == 0) RLGL.ExtSupported.texNPOT = true; - - // Check texture float support - if (strcmp(extList[i], (const char *)"GL_OES_texture_float") == 0) RLGL.ExtSupported.texFloat32 = true; - if (strcmp(extList[i], (const char *)"GL_OES_texture_half_float") == 0) RLGL.ExtSupported.texFloat16 = true; - - // Check depth texture support - if (strcmp(extList[i], (const char *)"GL_OES_depth_texture") == 0) RLGL.ExtSupported.texDepth = true; - if (strcmp(extList[i], (const char *)"GL_WEBGL_depth_texture") == 0) RLGL.ExtSupported.texDepthWebGL = true; // WebGL requires unsized internal format - if (RLGL.ExtSupported.texDepthWebGL) RLGL.ExtSupported.texDepth = true; - - if (strcmp(extList[i], (const char *)"GL_OES_depth24") == 0) RLGL.ExtSupported.maxDepthBits = 24; // Not available on WebGL - if (strcmp(extList[i], (const char *)"GL_OES_depth32") == 0) RLGL.ExtSupported.maxDepthBits = 32; // Not available on WebGL - - // Check texture compression support: DXT - if ((strcmp(extList[i], (const char *)"GL_EXT_texture_compression_s3tc") == 0) || - (strcmp(extList[i], (const char *)"GL_WEBGL_compressed_texture_s3tc") == 0) || - (strcmp(extList[i], (const char *)"GL_WEBKIT_WEBGL_compressed_texture_s3tc") == 0)) RLGL.ExtSupported.texCompDXT = true; - - // Check texture compression support: ETC1 - if ((strcmp(extList[i], (const char *)"GL_OES_compressed_ETC1_RGB8_texture") == 0) || - (strcmp(extList[i], (const char *)"GL_WEBGL_compressed_texture_etc1") == 0)) RLGL.ExtSupported.texCompETC1 = true; - - // Check texture compression support: ETC2/EAC - if (strcmp(extList[i], (const char *)"GL_ARB_ES3_compatibility") == 0) RLGL.ExtSupported.texCompETC2 = true; - - // Check texture compression support: PVR - if (strcmp(extList[i], (const char *)"GL_IMG_texture_compression_pvrtc") == 0) RLGL.ExtSupported.texCompPVRT = true; - - // Check texture compression support: ASTC - if (strcmp(extList[i], (const char *)"GL_KHR_texture_compression_astc_hdr") == 0) RLGL.ExtSupported.texCompASTC = true; - - // Check anisotropic texture filter support - if (strcmp(extList[i], (const char *)"GL_EXT_texture_filter_anisotropic") == 0) RLGL.ExtSupported.texAnisoFilter = true; - - // Check clamp mirror wrap mode support - if (strcmp(extList[i], (const char *)"GL_EXT_texture_mirror_clamp") == 0) RLGL.ExtSupported.texMirrorClamp = true; - } - - // Free extensions pointers - RL_FREE(extList); - RL_FREE(extensionsDup); // Duplicated string must be deallocated -#endif // GRAPHICS_API_OPENGL_ES2 - - // Check OpenGL information and capabilities - //------------------------------------------------------------------------------ - // Show current OpenGL and GLSL version - TRACELOG(RL_LOG_INFO, "GL: OpenGL device information:"); - TRACELOG(RL_LOG_INFO, " > Vendor: %s", glGetString(GL_VENDOR)); - TRACELOG(RL_LOG_INFO, " > Renderer: %s", glGetString(GL_RENDERER)); - TRACELOG(RL_LOG_INFO, " > Version: %s", glGetString(GL_VERSION)); - TRACELOG(RL_LOG_INFO, " > GLSL: %s", glGetString(GL_SHADING_LANGUAGE_VERSION)); - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - // NOTE: Anisotropy levels capability is an extension - #ifndef GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT - #define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF - #endif - glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &RLGL.ExtSupported.maxAnisotropyLevel); - -#if defined(RLGL_SHOW_GL_DETAILS_INFO) - // Show some OpenGL GPU capabilities - TRACELOG(RL_LOG_INFO, "GL: OpenGL capabilities:"); - GLint capability = 0; - glGetIntegerv(GL_MAX_TEXTURE_SIZE, &capability); - TRACELOG(RL_LOG_INFO, " GL_MAX_TEXTURE_SIZE: %i", capability); - glGetIntegerv(GL_MAX_CUBE_MAP_TEXTURE_SIZE, &capability); - TRACELOG(RL_LOG_INFO, " GL_MAX_CUBE_MAP_TEXTURE_SIZE: %i", capability); - glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &capability); - TRACELOG(RL_LOG_INFO, " GL_MAX_TEXTURE_IMAGE_UNITS: %i", capability); - glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &capability); - TRACELOG(RL_LOG_INFO, " GL_MAX_VERTEX_ATTRIBS: %i", capability); - #if !defined(GRAPHICS_API_OPENGL_ES2) - glGetIntegerv(GL_MAX_UNIFORM_BLOCK_SIZE, &capability); - TRACELOG(RL_LOG_INFO, " GL_MAX_UNIFORM_BLOCK_SIZE: %i", capability); - glGetIntegerv(GL_MAX_DRAW_BUFFERS, &capability); - TRACELOG(RL_LOG_INFO, " GL_MAX_DRAW_BUFFERS: %i", capability); - if (RLGL.ExtSupported.texAnisoFilter) TRACELOG(RL_LOG_INFO, " GL_MAX_TEXTURE_MAX_ANISOTROPY: %.0f", RLGL.ExtSupported.maxAnisotropyLevel); - #endif - glGetIntegerv(GL_NUM_COMPRESSED_TEXTURE_FORMATS, &capability); - TRACELOG(RL_LOG_INFO, " GL_NUM_COMPRESSED_TEXTURE_FORMATS: %i", capability); - GLint *compFormats = (GLint *)RL_CALLOC(capability, sizeof(GLint)); - glGetIntegerv(GL_COMPRESSED_TEXTURE_FORMATS, compFormats); - for (int i = 0; i < capability; i++) TRACELOG(RL_LOG_INFO, " %s", rlGetCompressedFormatName(compFormats[i])); - RL_FREE(compFormats); - -#if defined(GRAPHICS_API_OPENGL_43) - glGetIntegerv(GL_MAX_VERTEX_ATTRIB_BINDINGS, &capability); - TRACELOG(RL_LOG_INFO, " GL_MAX_VERTEX_ATTRIB_BINDINGS: %i", capability); - glGetIntegerv(GL_MAX_UNIFORM_LOCATIONS, &capability); - TRACELOG(RL_LOG_INFO, " GL_MAX_UNIFORM_LOCATIONS: %i", capability); -#endif // GRAPHICS_API_OPENGL_43 -#else // RLGL_SHOW_GL_DETAILS_INFO - - // Show some basic info about GL supported features - if (RLGL.ExtSupported.vao) TRACELOG(RL_LOG_INFO, "GL: VAO extension detected, VAO functions loaded successfully"); - else TRACELOG(RL_LOG_WARNING, "GL: VAO extension not found, VAO not supported"); - if (RLGL.ExtSupported.texNPOT) TRACELOG(RL_LOG_INFO, "GL: NPOT textures extension detected, full NPOT textures supported"); - else TRACELOG(RL_LOG_WARNING, "GL: NPOT textures extension not found, limited NPOT support (no-mipmaps, no-repeat)"); - if (RLGL.ExtSupported.texCompDXT) TRACELOG(RL_LOG_INFO, "GL: DXT compressed textures supported"); - if (RLGL.ExtSupported.texCompETC1) TRACELOG(RL_LOG_INFO, "GL: ETC1 compressed textures supported"); - if (RLGL.ExtSupported.texCompETC2) TRACELOG(RL_LOG_INFO, "GL: ETC2/EAC compressed textures supported"); - if (RLGL.ExtSupported.texCompPVRT) TRACELOG(RL_LOG_INFO, "GL: PVRT compressed textures supported"); - if (RLGL.ExtSupported.texCompASTC) TRACELOG(RL_LOG_INFO, "GL: ASTC compressed textures supported"); - if (RLGL.ExtSupported.computeShader) TRACELOG(RL_LOG_INFO, "GL: Compute shaders supported"); - if (RLGL.ExtSupported.ssbo) TRACELOG(RL_LOG_INFO, "GL: Shader storage buffer objects supported"); -#endif // RLGL_SHOW_GL_DETAILS_INFO - -#endif // GRAPHICS_API_OPENGL_33 || GRAPHICS_API_OPENGL_ES2 -} - -// Get current OpenGL version -int rlGetVersion(void) -{ - int glVersion = 0; -#if defined(GRAPHICS_API_OPENGL_11) - glVersion = RL_OPENGL_11; -#endif -#if defined(GRAPHICS_API_OPENGL_21) - glVersion = RL_OPENGL_21; -#elif defined(GRAPHICS_API_OPENGL_43) - glVersion = RL_OPENGL_43; -#elif defined(GRAPHICS_API_OPENGL_33) - glVersion = RL_OPENGL_33; -#endif -#if defined(GRAPHICS_API_OPENGL_ES3) - glVersion = RL_OPENGL_ES_30; -#elif defined(GRAPHICS_API_OPENGL_ES2) - glVersion = RL_OPENGL_ES_20; -#endif - - return glVersion; -} - -// Set current framebuffer width -void rlSetFramebufferWidth(int width) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - RLGL.State.framebufferWidth = width; -#endif -} - -// Set current framebuffer height -void rlSetFramebufferHeight(int height) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - RLGL.State.framebufferHeight = height; -#endif -} - -// Get default framebuffer width -int rlGetFramebufferWidth(void) -{ - int width = 0; -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - width = RLGL.State.framebufferWidth; -#endif - return width; -} - -// Get default framebuffer height -int rlGetFramebufferHeight(void) -{ - int height = 0; -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - height = RLGL.State.framebufferHeight; -#endif - return height; -} - -// Get default internal texture (white texture) -// NOTE: Default texture is a 1x1 pixel UNCOMPRESSED_R8G8B8A8 -unsigned int rlGetTextureIdDefault(void) -{ - unsigned int id = 0; -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - id = RLGL.State.defaultTextureId; -#endif - return id; -} - -// Get default shader id -unsigned int rlGetShaderIdDefault(void) -{ - unsigned int id = 0; -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - id = RLGL.State.defaultShaderId; -#endif - return id; -} - -// Get default shader locs -int *rlGetShaderLocsDefault(void) -{ - int *locs = NULL; -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - locs = RLGL.State.defaultShaderLocs; -#endif - return locs; -} - -// Render batch management -//------------------------------------------------------------------------------------------------ -// Load render batch -rlRenderBatch rlLoadRenderBatch(int numBuffers, int bufferElements) -{ - rlRenderBatch batch = { 0 }; - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - // Initialize CPU (RAM) vertex buffers (position, texcoord, color data and indexes) - //-------------------------------------------------------------------------------------------- - batch.vertexBuffer = (rlVertexBuffer *)RL_MALLOC(numBuffers*sizeof(rlVertexBuffer)); - - for (int i = 0; i < numBuffers; i++) - { - batch.vertexBuffer[i].elementCount = bufferElements; - - batch.vertexBuffer[i].vertices = (float *)RL_MALLOC(bufferElements*3*4*sizeof(float)); // 3 float by vertex, 4 vertex by quad - batch.vertexBuffer[i].texcoords = (float *)RL_MALLOC(bufferElements*2*4*sizeof(float)); // 2 float by texcoord, 4 texcoord by quad - batch.vertexBuffer[i].normals = (float *)RL_MALLOC(bufferElements*3*4*sizeof(float)); // 3 float by vertex, 4 vertex by quad - batch.vertexBuffer[i].colors = (unsigned char *)RL_MALLOC(bufferElements*4*4*sizeof(unsigned char)); // 4 float by color, 4 colors by quad -#if defined(GRAPHICS_API_OPENGL_33) - batch.vertexBuffer[i].indices = (unsigned int *)RL_MALLOC(bufferElements*6*sizeof(unsigned int)); // 6 int by quad (indices) -#endif -#if defined(GRAPHICS_API_OPENGL_ES2) - batch.vertexBuffer[i].indices = (unsigned short *)RL_MALLOC(bufferElements*6*sizeof(unsigned short)); // 6 int by quad (indices) -#endif - - for (int j = 0; j < (3*4*bufferElements); j++) batch.vertexBuffer[i].vertices[j] = 0.0f; - for (int j = 0; j < (2*4*bufferElements); j++) batch.vertexBuffer[i].texcoords[j] = 0.0f; - for (int j = 0; j < (3*4*bufferElements); j++) batch.vertexBuffer[i].normals[j] = 0.0f; - for (int j = 0; j < (4*4*bufferElements); j++) batch.vertexBuffer[i].colors[j] = 0; - - int k = 0; - - // Indices can be initialized right now - for (int j = 0; j < (6*bufferElements); j += 6) - { - batch.vertexBuffer[i].indices[j] = 4*k; - batch.vertexBuffer[i].indices[j + 1] = 4*k + 1; - batch.vertexBuffer[i].indices[j + 2] = 4*k + 2; - batch.vertexBuffer[i].indices[j + 3] = 4*k; - batch.vertexBuffer[i].indices[j + 4] = 4*k + 2; - batch.vertexBuffer[i].indices[j + 5] = 4*k + 3; - - k++; - } - - RLGL.State.vertexCounter = 0; - } - - TRACELOG(RL_LOG_INFO, "RLGL: Render batch vertex buffers loaded successfully in RAM (CPU)"); - //-------------------------------------------------------------------------------------------- - - // Upload to GPU (VRAM) vertex data and initialize VAOs/VBOs - //-------------------------------------------------------------------------------------------- - for (int i = 0; i < numBuffers; i++) - { - if (RLGL.ExtSupported.vao) - { - // Initialize Quads VAO - glGenVertexArrays(1, &batch.vertexBuffer[i].vaoId); - glBindVertexArray(batch.vertexBuffer[i].vaoId); - } - - // Quads - Vertex buffers binding and attributes enable - // Vertex position buffer (shader-location = 0) - glGenBuffers(1, &batch.vertexBuffer[i].vboId[0]); - glBindBuffer(GL_ARRAY_BUFFER, batch.vertexBuffer[i].vboId[0]); - glBufferData(GL_ARRAY_BUFFER, bufferElements*3*4*sizeof(float), batch.vertexBuffer[i].vertices, GL_DYNAMIC_DRAW); - glEnableVertexAttribArray(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_POSITION]); - glVertexAttribPointer(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_POSITION], 3, GL_FLOAT, 0, 0, 0); - - // Vertex texcoord buffer (shader-location = 1) - glGenBuffers(1, &batch.vertexBuffer[i].vboId[1]); - glBindBuffer(GL_ARRAY_BUFFER, batch.vertexBuffer[i].vboId[1]); - glBufferData(GL_ARRAY_BUFFER, bufferElements*2*4*sizeof(float), batch.vertexBuffer[i].texcoords, GL_DYNAMIC_DRAW); - glEnableVertexAttribArray(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_TEXCOORD01]); - glVertexAttribPointer(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_TEXCOORD01], 2, GL_FLOAT, 0, 0, 0); - - // Vertex normal buffer (shader-location = 2) - glGenBuffers(1, &batch.vertexBuffer[i].vboId[2]); - glBindBuffer(GL_ARRAY_BUFFER, batch.vertexBuffer[i].vboId[2]); - glBufferData(GL_ARRAY_BUFFER, bufferElements*3*4*sizeof(float), batch.vertexBuffer[i].normals, GL_DYNAMIC_DRAW); - glEnableVertexAttribArray(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_NORMAL]); - glVertexAttribPointer(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_NORMAL], 3, GL_FLOAT, 0, 0, 0); - - // Vertex color buffer (shader-location = 3) - glGenBuffers(1, &batch.vertexBuffer[i].vboId[3]); - glBindBuffer(GL_ARRAY_BUFFER, batch.vertexBuffer[i].vboId[3]); - glBufferData(GL_ARRAY_BUFFER, bufferElements*4*4*sizeof(unsigned char), batch.vertexBuffer[i].colors, GL_DYNAMIC_DRAW); - glEnableVertexAttribArray(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_COLOR]); - glVertexAttribPointer(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_COLOR], 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, 0); - - // Fill index buffer - glGenBuffers(1, &batch.vertexBuffer[i].vboId[4]); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, batch.vertexBuffer[i].vboId[4]); -#if defined(GRAPHICS_API_OPENGL_33) - glBufferData(GL_ELEMENT_ARRAY_BUFFER, bufferElements*6*sizeof(int), batch.vertexBuffer[i].indices, GL_STATIC_DRAW); -#endif -#if defined(GRAPHICS_API_OPENGL_ES2) - glBufferData(GL_ELEMENT_ARRAY_BUFFER, bufferElements*6*sizeof(short), batch.vertexBuffer[i].indices, GL_STATIC_DRAW); -#endif - } - - TRACELOG(RL_LOG_INFO, "RLGL: Render batch vertex buffers loaded successfully in VRAM (GPU)"); - - // Unbind the current VAO - if (RLGL.ExtSupported.vao) glBindVertexArray(0); - //-------------------------------------------------------------------------------------------- - - // Init draw calls tracking system - //-------------------------------------------------------------------------------------------- - batch.draws = (rlDrawCall *)RL_MALLOC(RL_DEFAULT_BATCH_DRAWCALLS*sizeof(rlDrawCall)); - - for (int i = 0; i < RL_DEFAULT_BATCH_DRAWCALLS; i++) - { - batch.draws[i].mode = RL_QUADS; - batch.draws[i].vertexCount = 0; - batch.draws[i].vertexAlignment = 0; - //batch.draws[i].vaoId = 0; - //batch.draws[i].shaderId = 0; - batch.draws[i].textureId = RLGL.State.defaultTextureId; - //batch.draws[i].RLGL.State.projection = rlMatrixIdentity(); - //batch.draws[i].RLGL.State.modelview = rlMatrixIdentity(); - } - - batch.bufferCount = numBuffers; // Record buffer count - batch.drawCounter = 1; // Reset draws counter - batch.currentDepth = -1.0f; // Reset depth value - //-------------------------------------------------------------------------------------------- -#endif - - return batch; -} - -// Unload default internal buffers vertex data from CPU and GPU -void rlUnloadRenderBatch(rlRenderBatch batch) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - // Unbind everything - glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); - - // Unload all vertex buffers data - for (int i = 0; i < batch.bufferCount; i++) - { - // Unbind VAO attribs data - if (RLGL.ExtSupported.vao) - { - glBindVertexArray(batch.vertexBuffer[i].vaoId); - glDisableVertexAttribArray(RL_DEFAULT_SHADER_ATTRIB_LOCATION_POSITION); - glDisableVertexAttribArray(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD); - glDisableVertexAttribArray(RL_DEFAULT_SHADER_ATTRIB_LOCATION_NORMAL); - glDisableVertexAttribArray(RL_DEFAULT_SHADER_ATTRIB_LOCATION_COLOR); - glBindVertexArray(0); - } - - // Delete VBOs from GPU (VRAM) - glDeleteBuffers(1, &batch.vertexBuffer[i].vboId[0]); - glDeleteBuffers(1, &batch.vertexBuffer[i].vboId[1]); - glDeleteBuffers(1, &batch.vertexBuffer[i].vboId[2]); - glDeleteBuffers(1, &batch.vertexBuffer[i].vboId[3]); - glDeleteBuffers(1, &batch.vertexBuffer[i].vboId[4]); - - // Delete VAOs from GPU (VRAM) - if (RLGL.ExtSupported.vao) glDeleteVertexArrays(1, &batch.vertexBuffer[i].vaoId); - - // Free vertex arrays memory from CPU (RAM) - RL_FREE(batch.vertexBuffer[i].vertices); - RL_FREE(batch.vertexBuffer[i].texcoords); - RL_FREE(batch.vertexBuffer[i].normals); - RL_FREE(batch.vertexBuffer[i].colors); - RL_FREE(batch.vertexBuffer[i].indices); - } - - // Unload arrays - RL_FREE(batch.vertexBuffer); - RL_FREE(batch.draws); -#endif -} - -// Draw render batch -// NOTE: We require a pointer to reset batch and increase current buffer (multi-buffer) -void rlDrawRenderBatch(rlRenderBatch *batch) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - // Update batch vertex buffers - //------------------------------------------------------------------------------------------------------------ - // NOTE: If there is not vertex data, buffers doesn't need to be updated (vertexCount > 0) - // TODO: If no data changed on the CPU arrays --> No need to re-update GPU arrays (use a change detector flag?) - if (RLGL.State.vertexCounter > 0) - { - // Activate elements VAO - if (RLGL.ExtSupported.vao) glBindVertexArray(batch->vertexBuffer[batch->currentBuffer].vaoId); - - // Vertex positions buffer - glBindBuffer(GL_ARRAY_BUFFER, batch->vertexBuffer[batch->currentBuffer].vboId[0]); - glBufferSubData(GL_ARRAY_BUFFER, 0, RLGL.State.vertexCounter*3*sizeof(float), batch->vertexBuffer[batch->currentBuffer].vertices); - //glBufferData(GL_ARRAY_BUFFER, sizeof(float)*3*4*batch->vertexBuffer[batch->currentBuffer].elementCount, batch->vertexBuffer[batch->currentBuffer].vertices, GL_DYNAMIC_DRAW); // Update all buffer - - // Texture coordinates buffer - glBindBuffer(GL_ARRAY_BUFFER, batch->vertexBuffer[batch->currentBuffer].vboId[1]); - glBufferSubData(GL_ARRAY_BUFFER, 0, RLGL.State.vertexCounter*2*sizeof(float), batch->vertexBuffer[batch->currentBuffer].texcoords); - //glBufferData(GL_ARRAY_BUFFER, sizeof(float)*2*4*batch->vertexBuffer[batch->currentBuffer].elementCount, batch->vertexBuffer[batch->currentBuffer].texcoords, GL_DYNAMIC_DRAW); // Update all buffer - - // Normals buffer - glBindBuffer(GL_ARRAY_BUFFER, batch->vertexBuffer[batch->currentBuffer].vboId[2]); - glBufferSubData(GL_ARRAY_BUFFER, 0, RLGL.State.vertexCounter*3*sizeof(float), batch->vertexBuffer[batch->currentBuffer].normals); - //glBufferData(GL_ARRAY_BUFFER, sizeof(float)*3*4*batch->vertexBuffer[batch->currentBuffer].elementCount, batch->vertexBuffer[batch->currentBuffer].normals, GL_DYNAMIC_DRAW); // Update all buffer - - // Colors buffer - glBindBuffer(GL_ARRAY_BUFFER, batch->vertexBuffer[batch->currentBuffer].vboId[3]); - glBufferSubData(GL_ARRAY_BUFFER, 0, RLGL.State.vertexCounter*4*sizeof(unsigned char), batch->vertexBuffer[batch->currentBuffer].colors); - //glBufferData(GL_ARRAY_BUFFER, sizeof(float)*4*4*batch->vertexBuffer[batch->currentBuffer].elementCount, batch->vertexBuffer[batch->currentBuffer].colors, GL_DYNAMIC_DRAW); // Update all buffer - - // NOTE: glMapBuffer() causes sync issue - // If GPU is working with this buffer, glMapBuffer() will wait(stall) until GPU to finish its job - // To avoid waiting (idle), you can call first glBufferData() with NULL pointer before glMapBuffer() - // If you do that, the previous data in PBO will be discarded and glMapBuffer() returns a new - // allocated pointer immediately even if GPU is still working with the previous data - - // Another option: map the buffer object into client's memory - // Probably this code could be moved somewhere else... - // batch->vertexBuffer[batch->currentBuffer].vertices = (float *)glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE); - // if (batch->vertexBuffer[batch->currentBuffer].vertices) - // { - // Update vertex data - // } - // glUnmapBuffer(GL_ARRAY_BUFFER); - - // Unbind the current VAO - if (RLGL.ExtSupported.vao) glBindVertexArray(0); - } - //------------------------------------------------------------------------------------------------------------ - - // Draw batch vertex buffers (considering VR stereo if required) - //------------------------------------------------------------------------------------------------------------ - Matrix matProjection = RLGL.State.projection; - Matrix matModelView = RLGL.State.modelview; - - int eyeCount = 1; - if (RLGL.State.stereoRender) eyeCount = 2; - - for (int eye = 0; eye < eyeCount; eye++) - { - if (eyeCount == 2) - { - // Setup current eye viewport (half screen width) - rlViewport(eye*RLGL.State.framebufferWidth/2, 0, RLGL.State.framebufferWidth/2, RLGL.State.framebufferHeight); - - // Set current eye view offset to modelview matrix - rlSetMatrixModelview(rlMatrixMultiply(matModelView, RLGL.State.viewOffsetStereo[eye])); - // Set current eye projection matrix - rlSetMatrixProjection(RLGL.State.projectionStereo[eye]); - } - - // Draw buffers - if (RLGL.State.vertexCounter > 0) - { - // Set current shader and upload current MVP matrix - glUseProgram(RLGL.State.currentShaderId); - - // Create modelview-projection matrix and upload to shader - Matrix matMVP = rlMatrixMultiply(RLGL.State.modelview, RLGL.State.projection); - glUniformMatrix4fv(RLGL.State.currentShaderLocs[RL_SHADER_LOC_MATRIX_MVP], 1, false, rlMatrixToFloat(matMVP)); - - if (RLGL.State.currentShaderLocs[RL_SHADER_LOC_MATRIX_PROJECTION] != -1) - { - glUniformMatrix4fv(RLGL.State.currentShaderLocs[RL_SHADER_LOC_MATRIX_PROJECTION], 1, false, rlMatrixToFloat(RLGL.State.projection)); - } - - // WARNING: For the following setup of the view, model, and normal matrices, it is expected that - // transformations and rendering occur between rlPushMatrix() and rlPopMatrix() - - if (RLGL.State.currentShaderLocs[RL_SHADER_LOC_MATRIX_VIEW] != -1) - { - glUniformMatrix4fv(RLGL.State.currentShaderLocs[RL_SHADER_LOC_MATRIX_VIEW], 1, false, rlMatrixToFloat(RLGL.State.modelview)); - } - - if (RLGL.State.currentShaderLocs[RL_SHADER_LOC_MATRIX_MODEL] != -1) - { - glUniformMatrix4fv(RLGL.State.currentShaderLocs[RL_SHADER_LOC_MATRIX_MODEL], 1, false, rlMatrixToFloat(RLGL.State.transform)); - } - - if (RLGL.State.currentShaderLocs[RL_SHADER_LOC_MATRIX_NORMAL] != -1) - { - glUniformMatrix4fv(RLGL.State.currentShaderLocs[RL_SHADER_LOC_MATRIX_NORMAL], 1, false, rlMatrixToFloat(rlMatrixTranspose(rlMatrixInvert(RLGL.State.transform)))); - } - - if (RLGL.ExtSupported.vao) glBindVertexArray(batch->vertexBuffer[batch->currentBuffer].vaoId); - else - { - // Bind vertex attrib: position (shader-location = 0) - glBindBuffer(GL_ARRAY_BUFFER, batch->vertexBuffer[batch->currentBuffer].vboId[0]); - glVertexAttribPointer(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_POSITION], 3, GL_FLOAT, 0, 0, 0); - glEnableVertexAttribArray(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_POSITION]); - - // Bind vertex attrib: texcoord (shader-location = 1) - glBindBuffer(GL_ARRAY_BUFFER, batch->vertexBuffer[batch->currentBuffer].vboId[1]); - glVertexAttribPointer(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_TEXCOORD01], 2, GL_FLOAT, 0, 0, 0); - glEnableVertexAttribArray(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_TEXCOORD01]); - - // Bind vertex attrib: normal (shader-location = 2) - glBindBuffer(GL_ARRAY_BUFFER, batch->vertexBuffer[batch->currentBuffer].vboId[2]); - glVertexAttribPointer(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_NORMAL], 3, GL_FLOAT, 0, 0, 0); - glEnableVertexAttribArray(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_NORMAL]); - - // Bind vertex attrib: color (shader-location = 3) - glBindBuffer(GL_ARRAY_BUFFER, batch->vertexBuffer[batch->currentBuffer].vboId[3]); - glVertexAttribPointer(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_COLOR], 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, 0); - glEnableVertexAttribArray(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_COLOR]); - - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, batch->vertexBuffer[batch->currentBuffer].vboId[4]); - } - - // Setup some default shader values - glUniform4f(RLGL.State.currentShaderLocs[RL_SHADER_LOC_COLOR_DIFFUSE], 1.0f, 1.0f, 1.0f, 1.0f); - glUniform1i(RLGL.State.currentShaderLocs[RL_SHADER_LOC_MAP_DIFFUSE], 0); // Active default sampler2D: texture0 - - // Activate additional sampler textures - // Those additional textures will be common for all draw calls of the batch - for (int i = 0; i < RL_DEFAULT_BATCH_MAX_TEXTURE_UNITS; i++) - { - if (RLGL.State.activeTextureId[i] > 0) - { - glActiveTexture(GL_TEXTURE0 + 1 + i); - glBindTexture(GL_TEXTURE_2D, RLGL.State.activeTextureId[i]); - } - } - - // Activate default sampler2D texture0 (one texture is always active for default batch shader) - // NOTE: Batch system accumulates calls by texture0 changes, additional textures are enabled for all the draw calls - glActiveTexture(GL_TEXTURE0); - - for (int i = 0, vertexOffset = 0; i < batch->drawCounter; i++) - { - // Bind current draw call texture, activated as GL_TEXTURE0 and Bound to sampler2D texture0 by default - glBindTexture(GL_TEXTURE_2D, batch->draws[i].textureId); - - if ((batch->draws[i].mode == RL_LINES) || (batch->draws[i].mode == RL_TRIANGLES)) glDrawArrays(batch->draws[i].mode, vertexOffset, batch->draws[i].vertexCount); - else - { - #if defined(GRAPHICS_API_OPENGL_33) - // We need to define the number of indices to be processed: elementCount*6 - // NOTE: The final parameter tells the GPU the offset in bytes from the - // start of the index buffer to the location of the first index to process - glDrawElements(GL_TRIANGLES, batch->draws[i].vertexCount/4*6, GL_UNSIGNED_INT, (GLvoid *)(vertexOffset/4*6*sizeof(GLuint))); - #endif - #if defined(GRAPHICS_API_OPENGL_ES2) - glDrawElements(GL_TRIANGLES, batch->draws[i].vertexCount/4*6, GL_UNSIGNED_SHORT, (GLvoid *)(vertexOffset/4*6*sizeof(GLushort))); - #endif - } - - vertexOffset += (batch->draws[i].vertexCount + batch->draws[i].vertexAlignment); - } - - if (!RLGL.ExtSupported.vao) - { - glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); - } - - glBindTexture(GL_TEXTURE_2D, 0); // Unbind textures - } - - if (RLGL.ExtSupported.vao) glBindVertexArray(0); // Unbind VAO - - glUseProgram(0); // Unbind shader program - } - - // Restore viewport to default measures - if (eyeCount == 2) rlViewport(0, 0, RLGL.State.framebufferWidth, RLGL.State.framebufferHeight); - //------------------------------------------------------------------------------------------------------------ - - // Reset batch buffers - //------------------------------------------------------------------------------------------------------------ - // Reset vertex counter for next frame - RLGL.State.vertexCounter = 0; - - // Reset depth for next draw - batch->currentDepth = -1.0f; - - // Restore projection/modelview matrices - RLGL.State.projection = matProjection; - RLGL.State.modelview = matModelView; - - // Reset RLGL.currentBatch->draws array - for (int i = 0; i < RL_DEFAULT_BATCH_DRAWCALLS; i++) - { - batch->draws[i].mode = RL_QUADS; - batch->draws[i].vertexCount = 0; - batch->draws[i].textureId = RLGL.State.defaultTextureId; - } - - // Reset active texture units for next batch - for (int i = 0; i < RL_DEFAULT_BATCH_MAX_TEXTURE_UNITS; i++) RLGL.State.activeTextureId[i] = 0; - - // Reset draws counter to one draw for the batch - batch->drawCounter = 1; - //------------------------------------------------------------------------------------------------------------ - - // Change to next buffer in the list (in case of multi-buffering) - batch->currentBuffer++; - if (batch->currentBuffer >= batch->bufferCount) batch->currentBuffer = 0; -#endif -} - -// Set the active render batch for rlgl -void rlSetRenderBatchActive(rlRenderBatch *batch) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - rlDrawRenderBatch(RLGL.currentBatch); - - if (batch != NULL) RLGL.currentBatch = batch; - else RLGL.currentBatch = &RLGL.defaultBatch; -#endif -} - -// Update and draw internal render batch -void rlDrawRenderBatchActive(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - rlDrawRenderBatch(RLGL.currentBatch); // NOTE: Stereo rendering is checked inside -#endif -} - -// Check internal buffer overflow for a given number of vertex -// and force a rlRenderBatch draw call if required -bool rlCheckRenderBatchLimit(int vCount) -{ - bool overflow = false; - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if ((RLGL.State.vertexCounter + vCount) >= - (RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].elementCount*4)) - { - overflow = true; - - // Store current primitive drawing mode and texture id - int currentMode = RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode; - int currentTexture = RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].textureId; - - rlDrawRenderBatch(RLGL.currentBatch); // NOTE: Stereo rendering is checked inside - - // Restore state of last batch so we can continue adding vertices - RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode = currentMode; - RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].textureId = currentTexture; - } -#endif - - return overflow; -} - -// Textures data management -//----------------------------------------------------------------------------------------- -// Convert image data to OpenGL texture (returns OpenGL valid Id) -unsigned int rlLoadTexture(const void *data, int width, int height, int format, int mipmapCount) -{ - unsigned int id = 0; - - glBindTexture(GL_TEXTURE_2D, 0); // Free any old binding - - // Check texture format support by OpenGL 1.1 (compressed textures not supported) -#if defined(GRAPHICS_API_OPENGL_11) - if (format >= RL_PIXELFORMAT_COMPRESSED_DXT1_RGB) - { - TRACELOG(RL_LOG_WARNING, "GL: OpenGL 1.1 does not support GPU compressed texture formats"); - return id; - } -#else - if ((!RLGL.ExtSupported.texCompDXT) && ((format == RL_PIXELFORMAT_COMPRESSED_DXT1_RGB) || (format == RL_PIXELFORMAT_COMPRESSED_DXT1_RGBA) || - (format == RL_PIXELFORMAT_COMPRESSED_DXT3_RGBA) || (format == RL_PIXELFORMAT_COMPRESSED_DXT5_RGBA))) - { - TRACELOG(RL_LOG_WARNING, "GL: DXT compressed texture format not supported"); - return id; - } -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if ((!RLGL.ExtSupported.texCompETC1) && (format == RL_PIXELFORMAT_COMPRESSED_ETC1_RGB)) - { - TRACELOG(RL_LOG_WARNING, "GL: ETC1 compressed texture format not supported"); - return id; - } - - if ((!RLGL.ExtSupported.texCompETC2) && ((format == RL_PIXELFORMAT_COMPRESSED_ETC2_RGB) || (format == RL_PIXELFORMAT_COMPRESSED_ETC2_EAC_RGBA))) - { - TRACELOG(RL_LOG_WARNING, "GL: ETC2 compressed texture format not supported"); - return id; - } - - if ((!RLGL.ExtSupported.texCompPVRT) && ((format == RL_PIXELFORMAT_COMPRESSED_PVRT_RGB) || (format == RL_PIXELFORMAT_COMPRESSED_PVRT_RGBA))) - { - TRACELOG(RL_LOG_WARNING, "GL: PVRT compressed texture format not supported"); - return id; - } - - if ((!RLGL.ExtSupported.texCompASTC) && ((format == RL_PIXELFORMAT_COMPRESSED_ASTC_4x4_RGBA) || (format == RL_PIXELFORMAT_COMPRESSED_ASTC_8x8_RGBA))) - { - TRACELOG(RL_LOG_WARNING, "GL: ASTC compressed texture format not supported"); - return id; - } -#endif -#endif // GRAPHICS_API_OPENGL_11 - - glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - - glGenTextures(1, &id); // Generate texture id - - glBindTexture(GL_TEXTURE_2D, id); - - int mipWidth = width; - int mipHeight = height; - int mipOffset = 0; // Mipmap data offset, only used for tracelog - - // NOTE: Added pointer math separately from function to avoid UBSAN complaining - unsigned char *dataPtr = NULL; - if (data != NULL) dataPtr = (unsigned char *)data; - - // Load the different mipmap levels - for (int i = 0; i < mipmapCount; i++) - { - unsigned int mipSize = rlGetPixelDataSize(mipWidth, mipHeight, format); - - unsigned int glInternalFormat, glFormat, glType; - rlGetGlTextureFormats(format, &glInternalFormat, &glFormat, &glType); - - TRACELOGD("TEXTURE: Load mipmap level %i (%i x %i), size: %i, offset: %i", i, mipWidth, mipHeight, mipSize, mipOffset); - - if (glInternalFormat != 0) - { - if (format < RL_PIXELFORMAT_COMPRESSED_DXT1_RGB) glTexImage2D(GL_TEXTURE_2D, i, glInternalFormat, mipWidth, mipHeight, 0, glFormat, glType, dataPtr); -#if !defined(GRAPHICS_API_OPENGL_11) - else glCompressedTexImage2D(GL_TEXTURE_2D, i, glInternalFormat, mipWidth, mipHeight, 0, mipSize, dataPtr); -#endif - -#if defined(GRAPHICS_API_OPENGL_33) - if (format == RL_PIXELFORMAT_UNCOMPRESSED_GRAYSCALE) - { - GLint swizzleMask[] = { GL_RED, GL_RED, GL_RED, GL_ONE }; - glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask); - } - else if (format == RL_PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA) - { -#if defined(GRAPHICS_API_OPENGL_21) - GLint swizzleMask[] = { GL_RED, GL_RED, GL_RED, GL_ALPHA }; -#elif defined(GRAPHICS_API_OPENGL_33) - GLint swizzleMask[] = { GL_RED, GL_RED, GL_RED, GL_GREEN }; -#endif - glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask); - } -#endif - } - - mipWidth /= 2; - mipHeight /= 2; - mipOffset += mipSize; // Increment offset position to next mipmap - if (data != NULL) dataPtr += mipSize; // Increment data pointer to next mipmap - - // Security check for NPOT textures - if (mipWidth < 1) mipWidth = 1; - if (mipHeight < 1) mipHeight = 1; - } - - // Texture parameters configuration - // NOTE: glTexParameteri does NOT affect texture uploading, just the way it's used -#if defined(GRAPHICS_API_OPENGL_ES2) - // NOTE: OpenGL ES 2.0 with no GL_OES_texture_npot support (i.e. WebGL) has limited NPOT support, so CLAMP_TO_EDGE must be used - if (RLGL.ExtSupported.texNPOT) - { - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // Set texture to repeat on x-axis - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // Set texture to repeat on y-axis - } - else - { - // NOTE: If using negative texture coordinates (LoadOBJ()), it does not work! - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); // Set texture to clamp on x-axis - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // Set texture to clamp on y-axis - } -#else - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // Set texture to repeat on x-axis - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // Set texture to repeat on y-axis -#endif - - // Magnification and minification filters - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // Alternative: GL_LINEAR - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); // Alternative: GL_LINEAR - -#if defined(GRAPHICS_API_OPENGL_33) - if (mipmapCount > 1) - { - // Activate Trilinear filtering if mipmaps are available - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); - } -#endif - - // At this point we have the texture loaded in GPU and texture parameters configured - - // NOTE: If mipmaps were not in data, they are not generated automatically - - // Unbind current texture - glBindTexture(GL_TEXTURE_2D, 0); - - if (id > 0) TRACELOG(RL_LOG_INFO, "TEXTURE: [ID %i] Texture loaded successfully (%ix%i | %s | %i mipmaps)", id, width, height, rlGetPixelFormatName(format), mipmapCount); - else TRACELOG(RL_LOG_WARNING, "TEXTURE: Failed to load texture"); - - return id; -} - -// Load depth texture/renderbuffer (to be attached to fbo) -// WARNING: OpenGL ES 2.0 requires GL_OES_depth_texture and WebGL requires WEBGL_depth_texture extensions -unsigned int rlLoadTextureDepth(int width, int height, bool useRenderBuffer) -{ - unsigned int id = 0; - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - // In case depth textures not supported, we force renderbuffer usage - if (!RLGL.ExtSupported.texDepth) useRenderBuffer = true; - - // NOTE: We let the implementation to choose the best bit-depth - // Possible formats: GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT32 and GL_DEPTH_COMPONENT32F - unsigned int glInternalFormat = GL_DEPTH_COMPONENT; - -#if (defined(GRAPHICS_API_OPENGL_ES2) || defined(GRAPHICS_API_OPENGL_ES3)) - // WARNING: WebGL platform requires unsized internal format definition (GL_DEPTH_COMPONENT) - // while other platforms using OpenGL ES 2.0 require/support sized internal formats depending on the GPU capabilities - if (!RLGL.ExtSupported.texDepthWebGL || useRenderBuffer) - { - if (RLGL.ExtSupported.maxDepthBits == 32) glInternalFormat = GL_DEPTH_COMPONENT32_OES; - else if (RLGL.ExtSupported.maxDepthBits == 24) glInternalFormat = GL_DEPTH_COMPONENT24_OES; - else glInternalFormat = GL_DEPTH_COMPONENT16; - } -#endif - - if (!useRenderBuffer && RLGL.ExtSupported.texDepth) - { - glGenTextures(1, &id); - glBindTexture(GL_TEXTURE_2D, id); - glTexImage2D(GL_TEXTURE_2D, 0, glInternalFormat, width, height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL); - - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - - glBindTexture(GL_TEXTURE_2D, 0); - - TRACELOG(RL_LOG_INFO, "TEXTURE: Depth texture loaded successfully"); - } - else - { - // Create the renderbuffer that will serve as the depth attachment for the framebuffer - // NOTE: A renderbuffer is simpler than a texture and could offer better performance on embedded devices - glGenRenderbuffers(1, &id); - glBindRenderbuffer(GL_RENDERBUFFER, id); - glRenderbufferStorage(GL_RENDERBUFFER, glInternalFormat, width, height); - - glBindRenderbuffer(GL_RENDERBUFFER, 0); - - TRACELOG(RL_LOG_INFO, "TEXTURE: [ID %i] Depth renderbuffer loaded successfully (%i bits)", id, (RLGL.ExtSupported.maxDepthBits >= 24)? RLGL.ExtSupported.maxDepthBits : 16); - } -#endif - - return id; -} - -// Load texture cubemap -// NOTE: Cubemap data is expected to be 6 images in a single data array (one after the other), -// expected the following convention: +X, -X, +Y, -Y, +Z, -Z -unsigned int rlLoadTextureCubemap(const void *data, int size, int format, int mipmapCount) -{ - unsigned int id = 0; - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - int mipSize = size; - - // NOTE: Added pointer math separately from function to avoid UBSAN complaining - unsigned char *dataPtr = NULL; - if (data != NULL) dataPtr = (unsigned char *)data; - - unsigned int dataSize = rlGetPixelDataSize(size, size, format); - - glGenTextures(1, &id); - glBindTexture(GL_TEXTURE_CUBE_MAP, id); - - unsigned int glInternalFormat, glFormat, glType; - rlGetGlTextureFormats(format, &glInternalFormat, &glFormat, &glType); - - if (glInternalFormat != 0) - { - // Load cubemap faces/mipmaps - for (int i = 0; i < 6*mipmapCount; i++) - { - int mipmapLevel = i/6; - int face = i%6; - - if (data == NULL) - { - if (format < RL_PIXELFORMAT_COMPRESSED_DXT1_RGB) - { - if ((format == RL_PIXELFORMAT_UNCOMPRESSED_R32) || - (format == RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32A32) || - (format == RL_PIXELFORMAT_UNCOMPRESSED_R16) || - (format == RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16A16)) TRACELOG(RL_LOG_WARNING, "TEXTURES: Cubemap requested format not supported"); - else glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, mipmapLevel, glInternalFormat, mipSize, mipSize, 0, glFormat, glType, NULL); - } - else TRACELOG(RL_LOG_WARNING, "TEXTURES: Empty cubemap creation does not support compressed format"); - } - else - { - if (format < RL_PIXELFORMAT_COMPRESSED_DXT1_RGB) glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, mipmapLevel, glInternalFormat, mipSize, mipSize, 0, glFormat, glType, (unsigned char *)dataPtr + face*dataSize); - else glCompressedTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, mipmapLevel, glInternalFormat, mipSize, mipSize, 0, dataSize, (unsigned char *)dataPtr + face*dataSize); - } - -#if defined(GRAPHICS_API_OPENGL_33) - if (format == RL_PIXELFORMAT_UNCOMPRESSED_GRAYSCALE) - { - GLint swizzleMask[] = { GL_RED, GL_RED, GL_RED, GL_ONE }; - glTexParameteriv(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask); - } - else if (format == RL_PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA) - { -#if defined(GRAPHICS_API_OPENGL_21) - GLint swizzleMask[] = { GL_RED, GL_RED, GL_RED, GL_ALPHA }; -#elif defined(GRAPHICS_API_OPENGL_33) - GLint swizzleMask[] = { GL_RED, GL_RED, GL_RED, GL_GREEN }; -#endif - glTexParameteriv(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask); - } -#endif - if (face == 5) - { - mipSize /= 2; - if (data != NULL) dataPtr += dataSize*6; // Increment data pointer to next mipmap - - // Security check for NPOT textures - if (mipSize < 1) mipSize = 1; - - dataSize = rlGetPixelDataSize(mipSize, mipSize, format); - } - } - } - - // Set cubemap texture sampling parameters - if (mipmapCount > 1) glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); - else glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); -#if defined(GRAPHICS_API_OPENGL_33) - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); // Flag not supported on OpenGL ES 2.0 -#endif - - glBindTexture(GL_TEXTURE_CUBE_MAP, 0); -#endif - - if (id > 0) TRACELOG(RL_LOG_INFO, "TEXTURE: [ID %i] Cubemap texture loaded successfully (%ix%i)", id, size, size); - else TRACELOG(RL_LOG_WARNING, "TEXTURE: Failed to load cubemap texture"); - - return id; -} - -// Update already loaded texture in GPU with new data -// NOTE: We don't know safely if internal texture format is the expected one... -void rlUpdateTexture(unsigned int id, int offsetX, int offsetY, int width, int height, int format, const void *data) -{ - glBindTexture(GL_TEXTURE_2D, id); - - unsigned int glInternalFormat, glFormat, glType; - rlGetGlTextureFormats(format, &glInternalFormat, &glFormat, &glType); - - if ((glInternalFormat != 0) && (format < RL_PIXELFORMAT_COMPRESSED_DXT1_RGB)) - { - glTexSubImage2D(GL_TEXTURE_2D, 0, offsetX, offsetY, width, height, glFormat, glType, data); - } - else TRACELOG(RL_LOG_WARNING, "TEXTURE: [ID %i] Failed to update for current texture format (%i)", id, format); -} - -// Get OpenGL internal formats and data type from raylib PixelFormat -void rlGetGlTextureFormats(int format, unsigned int *glInternalFormat, unsigned int *glFormat, unsigned int *glType) -{ - *glInternalFormat = 0; - *glFormat = 0; - *glType = 0; - - switch (format) - { - #if defined(GRAPHICS_API_OPENGL_11) || defined(GRAPHICS_API_OPENGL_21) || defined(GRAPHICS_API_OPENGL_ES2) - // NOTE: on OpenGL ES 2.0 (WebGL), internalFormat must match format and options allowed are: GL_LUMINANCE, GL_RGB, GL_RGBA - case RL_PIXELFORMAT_UNCOMPRESSED_GRAYSCALE: *glInternalFormat = GL_LUMINANCE; *glFormat = GL_LUMINANCE; *glType = GL_UNSIGNED_BYTE; break; - case RL_PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA: *glInternalFormat = GL_LUMINANCE_ALPHA; *glFormat = GL_LUMINANCE_ALPHA; *glType = GL_UNSIGNED_BYTE; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R5G6B5: *glInternalFormat = GL_RGB; *glFormat = GL_RGB; *glType = GL_UNSIGNED_SHORT_5_6_5; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8: *glInternalFormat = GL_RGB; *glFormat = GL_RGB; *glType = GL_UNSIGNED_BYTE; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R5G5B5A1: *glInternalFormat = GL_RGBA; *glFormat = GL_RGBA; *glType = GL_UNSIGNED_SHORT_5_5_5_1; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R4G4B4A4: *glInternalFormat = GL_RGBA; *glFormat = GL_RGBA; *glType = GL_UNSIGNED_SHORT_4_4_4_4; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8A8: *glInternalFormat = GL_RGBA; *glFormat = GL_RGBA; *glType = GL_UNSIGNED_BYTE; break; - #if !defined(GRAPHICS_API_OPENGL_11) - #if defined(GRAPHICS_API_OPENGL_ES3) - case RL_PIXELFORMAT_UNCOMPRESSED_R32: if (RLGL.ExtSupported.texFloat32) *glInternalFormat = GL_R32F_EXT; *glFormat = GL_RED_EXT; *glType = GL_FLOAT; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32: if (RLGL.ExtSupported.texFloat32) *glInternalFormat = GL_RGB32F_EXT; *glFormat = GL_RGB; *glType = GL_FLOAT; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32A32: if (RLGL.ExtSupported.texFloat32) *glInternalFormat = GL_RGBA32F_EXT; *glFormat = GL_RGBA; *glType = GL_FLOAT; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_R16F_EXT; *glFormat = GL_RED_EXT; *glType = GL_HALF_FLOAT; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_RGB16F_EXT; *glFormat = GL_RGB; *glType = GL_HALF_FLOAT; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16A16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_RGBA16F_EXT; *glFormat = GL_RGBA; *glType = GL_HALF_FLOAT; break; - #else - case RL_PIXELFORMAT_UNCOMPRESSED_R32: if (RLGL.ExtSupported.texFloat32) *glInternalFormat = GL_LUMINANCE; *glFormat = GL_LUMINANCE; *glType = GL_FLOAT; break; // NOTE: Requires extension OES_texture_float - case RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32: if (RLGL.ExtSupported.texFloat32) *glInternalFormat = GL_RGB; *glFormat = GL_RGB; *glType = GL_FLOAT; break; // NOTE: Requires extension OES_texture_float - case RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32A32: if (RLGL.ExtSupported.texFloat32) *glInternalFormat = GL_RGBA; *glFormat = GL_RGBA; *glType = GL_FLOAT; break; // NOTE: Requires extension OES_texture_float - #if defined(GRAPHICS_API_OPENGL_21) - case RL_PIXELFORMAT_UNCOMPRESSED_R16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_LUMINANCE; *glFormat = GL_LUMINANCE; *glType = GL_HALF_FLOAT_ARB; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_RGB; *glFormat = GL_RGB; *glType = GL_HALF_FLOAT_ARB; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16A16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_RGBA; *glFormat = GL_RGBA; *glType = GL_HALF_FLOAT_ARB; break; - #else // defined(GRAPHICS_API_OPENGL_ES2) - case RL_PIXELFORMAT_UNCOMPRESSED_R16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_LUMINANCE; *glFormat = GL_LUMINANCE; *glType = GL_HALF_FLOAT_OES; break; // NOTE: Requires extension OES_texture_half_float - case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_RGB; *glFormat = GL_RGB; *glType = GL_HALF_FLOAT_OES; break; // NOTE: Requires extension OES_texture_half_float - case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16A16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_RGBA; *glFormat = GL_RGBA; *glType = GL_HALF_FLOAT_OES; break; // NOTE: Requires extension OES_texture_half_float - #endif - #endif - #endif - #elif defined(GRAPHICS_API_OPENGL_33) - case RL_PIXELFORMAT_UNCOMPRESSED_GRAYSCALE: *glInternalFormat = GL_R8; *glFormat = GL_RED; *glType = GL_UNSIGNED_BYTE; break; - case RL_PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA: *glInternalFormat = GL_RG8; *glFormat = GL_RG; *glType = GL_UNSIGNED_BYTE; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R5G6B5: *glInternalFormat = GL_RGB565; *glFormat = GL_RGB; *glType = GL_UNSIGNED_SHORT_5_6_5; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8: *glInternalFormat = GL_RGB8; *glFormat = GL_RGB; *glType = GL_UNSIGNED_BYTE; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R5G5B5A1: *glInternalFormat = GL_RGB5_A1; *glFormat = GL_RGBA; *glType = GL_UNSIGNED_SHORT_5_5_5_1; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R4G4B4A4: *glInternalFormat = GL_RGBA4; *glFormat = GL_RGBA; *glType = GL_UNSIGNED_SHORT_4_4_4_4; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8A8: *glInternalFormat = GL_RGBA8; *glFormat = GL_RGBA; *glType = GL_UNSIGNED_BYTE; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R32: if (RLGL.ExtSupported.texFloat32) *glInternalFormat = GL_R32F; *glFormat = GL_RED; *glType = GL_FLOAT; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32: if (RLGL.ExtSupported.texFloat32) *glInternalFormat = GL_RGB32F; *glFormat = GL_RGB; *glType = GL_FLOAT; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32A32: if (RLGL.ExtSupported.texFloat32) *glInternalFormat = GL_RGBA32F; *glFormat = GL_RGBA; *glType = GL_FLOAT; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_R16F; *glFormat = GL_RED; *glType = GL_HALF_FLOAT; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_RGB16F; *glFormat = GL_RGB; *glType = GL_HALF_FLOAT; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16A16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_RGBA16F; *glFormat = GL_RGBA; *glType = GL_HALF_FLOAT; break; - #endif - #if !defined(GRAPHICS_API_OPENGL_11) - case RL_PIXELFORMAT_COMPRESSED_DXT1_RGB: if (RLGL.ExtSupported.texCompDXT) *glInternalFormat = GL_COMPRESSED_RGB_S3TC_DXT1_EXT; break; - case RL_PIXELFORMAT_COMPRESSED_DXT1_RGBA: if (RLGL.ExtSupported.texCompDXT) *glInternalFormat = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; break; - case RL_PIXELFORMAT_COMPRESSED_DXT3_RGBA: if (RLGL.ExtSupported.texCompDXT) *glInternalFormat = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; break; - case RL_PIXELFORMAT_COMPRESSED_DXT5_RGBA: if (RLGL.ExtSupported.texCompDXT) *glInternalFormat = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; break; - case RL_PIXELFORMAT_COMPRESSED_ETC1_RGB: if (RLGL.ExtSupported.texCompETC1) *glInternalFormat = GL_ETC1_RGB8_OES; break; // NOTE: Requires OpenGL ES 2.0 or OpenGL 4.3 - case RL_PIXELFORMAT_COMPRESSED_ETC2_RGB: if (RLGL.ExtSupported.texCompETC2) *glInternalFormat = GL_COMPRESSED_RGB8_ETC2; break; // NOTE: Requires OpenGL ES 3.0 or OpenGL 4.3 - case RL_PIXELFORMAT_COMPRESSED_ETC2_EAC_RGBA: if (RLGL.ExtSupported.texCompETC2) *glInternalFormat = GL_COMPRESSED_RGBA8_ETC2_EAC; break; // NOTE: Requires OpenGL ES 3.0 or OpenGL 4.3 - case RL_PIXELFORMAT_COMPRESSED_PVRT_RGB: if (RLGL.ExtSupported.texCompPVRT) *glInternalFormat = GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG; break; // NOTE: Requires PowerVR GPU - case RL_PIXELFORMAT_COMPRESSED_PVRT_RGBA: if (RLGL.ExtSupported.texCompPVRT) *glInternalFormat = GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; break; // NOTE: Requires PowerVR GPU - case RL_PIXELFORMAT_COMPRESSED_ASTC_4x4_RGBA: if (RLGL.ExtSupported.texCompASTC) *glInternalFormat = GL_COMPRESSED_RGBA_ASTC_4x4_KHR; break; // NOTE: Requires OpenGL ES 3.1 or OpenGL 4.3 - case RL_PIXELFORMAT_COMPRESSED_ASTC_8x8_RGBA: if (RLGL.ExtSupported.texCompASTC) *glInternalFormat = GL_COMPRESSED_RGBA_ASTC_8x8_KHR; break; // NOTE: Requires OpenGL ES 3.1 or OpenGL 4.3 - #endif - default: TRACELOG(RL_LOG_WARNING, "TEXTURE: Current format not supported (%i)", format); break; - } -} - -// Unload texture from GPU memory -void rlUnloadTexture(unsigned int id) -{ - glDeleteTextures(1, &id); -} - -// Generate mipmap data for selected texture -// NOTE: Only supports GPU mipmap generation -void rlGenTextureMipmaps(unsigned int id, int width, int height, int format, int *mipmaps) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glBindTexture(GL_TEXTURE_2D, id); - - // Check if texture is power-of-two (POT) - bool texIsPOT = false; - - if (((width > 0) && ((width & (width - 1)) == 0)) && - ((height > 0) && ((height & (height - 1)) == 0))) texIsPOT = true; - - if ((texIsPOT) || (RLGL.ExtSupported.texNPOT)) - { - //glHint(GL_GENERATE_MIPMAP_HINT, GL_DONT_CARE); // Hint for mipmaps generation algorithm: GL_FASTEST, GL_NICEST, GL_DONT_CARE - glGenerateMipmap(GL_TEXTURE_2D); // Generate mipmaps automatically - - #define MIN(a,b) (((a)<(b))? (a):(b)) - #define MAX(a,b) (((a)>(b))? (a):(b)) - - *mipmaps = 1 + (int)floor(log(MAX(width, height))/log(2)); - TRACELOG(RL_LOG_INFO, "TEXTURE: [ID %i] Mipmaps generated automatically, total: %i", id, *mipmaps); - } - else TRACELOG(RL_LOG_WARNING, "TEXTURE: [ID %i] Failed to generate mipmaps", id); - - glBindTexture(GL_TEXTURE_2D, 0); -#else - TRACELOG(RL_LOG_WARNING, "TEXTURE: [ID %i] GPU mipmap generation not supported", id); -#endif -} - -// Read texture pixel data -void *rlReadTexturePixels(unsigned int id, int width, int height, int format) -{ - void *pixels = NULL; - -#if defined(GRAPHICS_API_OPENGL_11) || defined(GRAPHICS_API_OPENGL_33) - glBindTexture(GL_TEXTURE_2D, id); - - // NOTE: Using texture id, we can retrieve some texture info (but not on OpenGL ES 2.0) - // Possible texture info: GL_TEXTURE_RED_SIZE, GL_TEXTURE_GREEN_SIZE, GL_TEXTURE_BLUE_SIZE, GL_TEXTURE_ALPHA_SIZE - //int width, height, format; - //glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &width); - //glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &height); - //glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_INTERNAL_FORMAT, &format); - - // NOTE: Each row written to or read from by OpenGL pixel operations like glGetTexImage are aligned to a 4 byte boundary by default, which may add some padding - // Use glPixelStorei to modify padding with the GL_[UN]PACK_ALIGNMENT setting - // GL_PACK_ALIGNMENT affects operations that read from OpenGL memory (glReadPixels, glGetTexImage, etc.) - // GL_UNPACK_ALIGNMENT affects operations that write to OpenGL memory (glTexImage, etc.) - glPixelStorei(GL_PACK_ALIGNMENT, 1); - - unsigned int glInternalFormat, glFormat, glType; - rlGetGlTextureFormats(format, &glInternalFormat, &glFormat, &glType); - unsigned int size = rlGetPixelDataSize(width, height, format); - - if ((glInternalFormat != 0) && (format < RL_PIXELFORMAT_COMPRESSED_DXT1_RGB)) - { - pixels = RL_MALLOC(size); - glGetTexImage(GL_TEXTURE_2D, 0, glFormat, glType, pixels); - } - else TRACELOG(RL_LOG_WARNING, "TEXTURE: [ID %i] Data retrieval not suported for pixel format (%i)", id, format); - - glBindTexture(GL_TEXTURE_2D, 0); -#endif - -#if defined(GRAPHICS_API_OPENGL_ES2) - // glGetTexImage() is not available on OpenGL ES 2.0 - // Texture width and height are required on OpenGL ES 2.0, there is no way to get it from texture id - // Two possible Options: - // 1 - Bind texture to color fbo attachment and glReadPixels() - // 2 - Create an fbo, activate it, render quad with texture, glReadPixels() - // We are using Option 1, just need to care for texture format on retrieval - // NOTE: This behaviour could be conditioned by graphic driver... - unsigned int fboId = rlLoadFramebuffer(); - - glBindFramebuffer(GL_FRAMEBUFFER, fboId); - glBindTexture(GL_TEXTURE_2D, 0); - - // Attach our texture to FBO - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, id, 0); - - // We read data as RGBA because FBO texture is configured as RGBA, despite binding another texture format - pixels = (unsigned char *)RL_MALLOC(rlGetPixelDataSize(width, height, RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8A8)); - glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels); - - glBindFramebuffer(GL_FRAMEBUFFER, 0); - - // Clean up temporal fbo - rlUnloadFramebuffer(fboId); -#endif - - return pixels; -} - -// Read screen pixel data (color buffer) -unsigned char *rlReadScreenPixels(int width, int height) -{ - unsigned char *screenData = (unsigned char *)RL_CALLOC(width*height*4, sizeof(unsigned char)); - - // NOTE 1: glReadPixels returns image flipped vertically -> (0,0) is the bottom left corner of the framebuffer - // NOTE 2: We are getting alpha channel! Be careful, it can be transparent if not cleared properly! - glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, screenData); - - // Flip image vertically! - unsigned char *imgData = (unsigned char *)RL_MALLOC(width*height*4*sizeof(unsigned char)); - - for (int y = height - 1; y >= 0; y--) - { - for (int x = 0; x < (width*4); x++) - { - imgData[((height - 1) - y)*width*4 + x] = screenData[(y*width*4) + x]; // Flip line - - // Set alpha component value to 255 (no trasparent image retrieval) - // NOTE: Alpha value has already been applied to RGB in framebuffer, we don't need it! - if (((x + 1)%4) == 0) imgData[((height - 1) - y)*width*4 + x] = 255; - } - } - - RL_FREE(screenData); - - return imgData; // NOTE: image data should be freed -} - -// Framebuffer management (fbo) -//----------------------------------------------------------------------------------------- -// Load a framebuffer to be used for rendering -// NOTE: No textures attached -unsigned int rlLoadFramebuffer(void) -{ - unsigned int fboId = 0; - -#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) && defined(RLGL_RENDER_TEXTURES_HINT) - glGenFramebuffers(1, &fboId); // Create the framebuffer object - glBindFramebuffer(GL_FRAMEBUFFER, 0); // Unbind any framebuffer -#endif - - return fboId; -} - -// Attach color buffer texture to an fbo (unloads previous attachment) -// NOTE: Attach type: 0-Color, 1-Depth renderbuffer, 2-Depth texture -void rlFramebufferAttach(unsigned int fboId, unsigned int texId, int attachType, int texType, int mipLevel) -{ -#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) && defined(RLGL_RENDER_TEXTURES_HINT) - glBindFramebuffer(GL_FRAMEBUFFER, fboId); - - switch (attachType) - { - case RL_ATTACHMENT_COLOR_CHANNEL0: - case RL_ATTACHMENT_COLOR_CHANNEL1: - case RL_ATTACHMENT_COLOR_CHANNEL2: - case RL_ATTACHMENT_COLOR_CHANNEL3: - case RL_ATTACHMENT_COLOR_CHANNEL4: - case RL_ATTACHMENT_COLOR_CHANNEL5: - case RL_ATTACHMENT_COLOR_CHANNEL6: - case RL_ATTACHMENT_COLOR_CHANNEL7: - { - if (texType == RL_ATTACHMENT_TEXTURE2D) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + attachType, GL_TEXTURE_2D, texId, mipLevel); - else if (texType == RL_ATTACHMENT_RENDERBUFFER) glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + attachType, GL_RENDERBUFFER, texId); - else if (texType >= RL_ATTACHMENT_CUBEMAP_POSITIVE_X) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + attachType, GL_TEXTURE_CUBE_MAP_POSITIVE_X + texType, texId, mipLevel); - - } break; - case RL_ATTACHMENT_DEPTH: - { - if (texType == RL_ATTACHMENT_TEXTURE2D) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, texId, mipLevel); - else if (texType == RL_ATTACHMENT_RENDERBUFFER) glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, texId); - - } break; - case RL_ATTACHMENT_STENCIL: - { - if (texType == RL_ATTACHMENT_TEXTURE2D) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, texId, mipLevel); - else if (texType == RL_ATTACHMENT_RENDERBUFFER) glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, texId); - - } break; - default: break; - } - - glBindFramebuffer(GL_FRAMEBUFFER, 0); -#endif -} - -// Verify render texture is complete -bool rlFramebufferComplete(unsigned int id) -{ - bool result = false; - -#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) && defined(RLGL_RENDER_TEXTURES_HINT) - glBindFramebuffer(GL_FRAMEBUFFER, id); - - GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); - - if (status != GL_FRAMEBUFFER_COMPLETE) - { - switch (status) - { - case GL_FRAMEBUFFER_UNSUPPORTED: TRACELOG(RL_LOG_WARNING, "FBO: [ID %i] Framebuffer is unsupported", id); break; - case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: TRACELOG(RL_LOG_WARNING, "FBO: [ID %i] Framebuffer has incomplete attachment", id); break; -#if defined(GRAPHICS_API_OPENGL_ES2) - case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS: TRACELOG(RL_LOG_WARNING, "FBO: [ID %i] Framebuffer has incomplete dimensions", id); break; -#endif - case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: TRACELOG(RL_LOG_WARNING, "FBO: [ID %i] Framebuffer has a missing attachment", id); break; - default: break; - } - } - - glBindFramebuffer(GL_FRAMEBUFFER, 0); - - result = (status == GL_FRAMEBUFFER_COMPLETE); -#endif - - return result; -} - -// Unload framebuffer from GPU memory -// NOTE: All attached textures/cubemaps/renderbuffers are also deleted -void rlUnloadFramebuffer(unsigned int id) -{ -#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) && defined(RLGL_RENDER_TEXTURES_HINT) - // Query depth attachment to automatically delete texture/renderbuffer - int depthType = 0, depthId = 0; - glBindFramebuffer(GL_FRAMEBUFFER, id); // Bind framebuffer to query depth texture type - glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &depthType); - - // TODO: Review warning retrieving object name in WebGL - // WARNING: WebGL: INVALID_ENUM: getFramebufferAttachmentParameter: invalid parameter name - // https://registry.khronos.org/webgl/specs/latest/1.0/ - glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &depthId); - - unsigned int depthIdU = (unsigned int)depthId; - if (depthType == GL_RENDERBUFFER) glDeleteRenderbuffers(1, &depthIdU); - else if (depthType == GL_TEXTURE) glDeleteTextures(1, &depthIdU); - - // NOTE: If a texture object is deleted while its image is attached to the *currently bound* framebuffer, - // the texture image is automatically detached from the currently bound framebuffer - - glBindFramebuffer(GL_FRAMEBUFFER, 0); - glDeleteFramebuffers(1, &id); - - TRACELOG(RL_LOG_INFO, "FBO: [ID %i] Unloaded framebuffer from VRAM (GPU)", id); -#endif -} - -// Vertex data management -//----------------------------------------------------------------------------------------- -// Load a new attributes buffer -unsigned int rlLoadVertexBuffer(const void *buffer, int size, bool dynamic) -{ - unsigned int id = 0; - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glGenBuffers(1, &id); - glBindBuffer(GL_ARRAY_BUFFER, id); - glBufferData(GL_ARRAY_BUFFER, size, buffer, dynamic? GL_DYNAMIC_DRAW : GL_STATIC_DRAW); -#endif - - return id; -} - -// Load a new attributes element buffer -unsigned int rlLoadVertexBufferElement(const void *buffer, int size, bool dynamic) -{ - unsigned int id = 0; - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glGenBuffers(1, &id); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, id); - glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, buffer, dynamic? GL_DYNAMIC_DRAW : GL_STATIC_DRAW); -#endif - - return id; -} - -// Enable vertex buffer (VBO) -void rlEnableVertexBuffer(unsigned int id) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glBindBuffer(GL_ARRAY_BUFFER, id); -#endif -} - -// Disable vertex buffer (VBO) -void rlDisableVertexBuffer(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glBindBuffer(GL_ARRAY_BUFFER, 0); -#endif -} - -// Enable vertex buffer element (VBO element) -void rlEnableVertexBufferElement(unsigned int id) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, id); -#endif -} - -// Disable vertex buffer element (VBO element) -void rlDisableVertexBufferElement(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); -#endif -} - -// Update vertex buffer with new data -// NOTE: dataSize and offset must be provided in bytes -void rlUpdateVertexBuffer(unsigned int id, const void *data, int dataSize, int offset) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glBindBuffer(GL_ARRAY_BUFFER, id); - glBufferSubData(GL_ARRAY_BUFFER, offset, dataSize, data); -#endif -} - -// Update vertex buffer elements with new data -// NOTE: dataSize and offset must be provided in bytes -void rlUpdateVertexBufferElements(unsigned int id, const void *data, int dataSize, int offset) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, id); - glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, offset, dataSize, data); -#endif -} - -// Enable vertex array object (VAO) -bool rlEnableVertexArray(unsigned int vaoId) -{ - bool result = false; -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if (RLGL.ExtSupported.vao) - { - glBindVertexArray(vaoId); - result = true; - } -#endif - return result; -} - -// Disable vertex array object (VAO) -void rlDisableVertexArray(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if (RLGL.ExtSupported.vao) glBindVertexArray(0); -#endif -} - -// Enable vertex attribute index -void rlEnableVertexAttribute(unsigned int index) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glEnableVertexAttribArray(index); -#endif -} - -// Disable vertex attribute index -void rlDisableVertexAttribute(unsigned int index) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glDisableVertexAttribArray(index); -#endif -} - -// Draw vertex array -void rlDrawVertexArray(int offset, int count) -{ - glDrawArrays(GL_TRIANGLES, offset, count); -} - -// Draw vertex array elements -void rlDrawVertexArrayElements(int offset, int count, const void *buffer) -{ - // NOTE: Added pointer math separately from function to avoid UBSAN complaining - unsigned short *bufferPtr = (unsigned short *)buffer; - if (offset > 0) bufferPtr += offset; - - glDrawElements(GL_TRIANGLES, count, GL_UNSIGNED_SHORT, (const unsigned short *)bufferPtr); -} - -// Draw vertex array instanced -void rlDrawVertexArrayInstanced(int offset, int count, int instances) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glDrawArraysInstanced(GL_TRIANGLES, 0, count, instances); -#endif -} - -// Draw vertex array elements instanced -void rlDrawVertexArrayElementsInstanced(int offset, int count, const void *buffer, int instances) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - // NOTE: Added pointer math separately from function to avoid UBSAN complaining - unsigned short *bufferPtr = (unsigned short *)buffer; - if (offset > 0) bufferPtr += offset; - - glDrawElementsInstanced(GL_TRIANGLES, count, GL_UNSIGNED_SHORT, (const unsigned short *)bufferPtr, instances); -#endif -} - -#if defined(GRAPHICS_API_OPENGL_11) -// Enable vertex state pointer -void rlEnableStatePointer(int vertexAttribType, void *buffer) -{ - if (buffer != NULL) glEnableClientState(vertexAttribType); - switch (vertexAttribType) - { - case GL_VERTEX_ARRAY: glVertexPointer(3, GL_FLOAT, 0, buffer); break; - case GL_TEXTURE_COORD_ARRAY: glTexCoordPointer(2, GL_FLOAT, 0, buffer); break; - case GL_NORMAL_ARRAY: if (buffer != NULL) glNormalPointer(GL_FLOAT, 0, buffer); break; - case GL_COLOR_ARRAY: if (buffer != NULL) glColorPointer(4, GL_UNSIGNED_BYTE, 0, buffer); break; - //case GL_INDEX_ARRAY: if (buffer != NULL) glIndexPointer(GL_SHORT, 0, buffer); break; // Indexed colors - default: break; - } -} - -// Disable vertex state pointer -void rlDisableStatePointer(int vertexAttribType) -{ - glDisableClientState(vertexAttribType); -} -#endif - -// Load vertex array object (VAO) -unsigned int rlLoadVertexArray(void) -{ - unsigned int vaoId = 0; -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if (RLGL.ExtSupported.vao) - { - glGenVertexArrays(1, &vaoId); - } -#endif - return vaoId; -} - -// Set vertex attribute -void rlSetVertexAttribute(unsigned int index, int compSize, int type, bool normalized, int stride, int offset) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - // NOTE: Data type could be: GL_BYTE, GL_UNSIGNED_BYTE, GL_SHORT, GL_UNSIGNED_SHORT, GL_INT, GL_UNSIGNED_INT - // Additional types (depends on OpenGL version or extensions): - // - GL_HALF_FLOAT, GL_FLOAT, GL_DOUBLE, GL_FIXED, - // - GL_INT_2_10_10_10_REV, GL_UNSIGNED_INT_2_10_10_10_REV, GL_UNSIGNED_INT_10F_11F_11F_REV - - size_t offsetNative = offset; - glVertexAttribPointer(index, compSize, type, normalized, stride, (void *)offsetNative); -#endif -} - -// Set vertex attribute divisor -void rlSetVertexAttributeDivisor(unsigned int index, int divisor) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glVertexAttribDivisor(index, divisor); -#endif -} - -// Unload vertex array object (VAO) -void rlUnloadVertexArray(unsigned int vaoId) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if (RLGL.ExtSupported.vao) - { - glBindVertexArray(0); - glDeleteVertexArrays(1, &vaoId); - TRACELOG(RL_LOG_INFO, "VAO: [ID %i] Unloaded vertex array data from VRAM (GPU)", vaoId); - } -#endif -} - -// Unload vertex buffer (VBO) -void rlUnloadVertexBuffer(unsigned int vboId) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glDeleteBuffers(1, &vboId); - //TRACELOG(RL_LOG_INFO, "VBO: Unloaded vertex data from VRAM (GPU)"); -#endif -} - -// Shaders management -//----------------------------------------------------------------------------------------------- -// Load shader from code strings -// NOTE: If shader string is NULL, using default vertex/fragment shaders -unsigned int rlLoadShaderCode(const char *vsCode, const char *fsCode) -{ - unsigned int id = 0; - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - unsigned int vertexShaderId = 0; - unsigned int fragmentShaderId = 0; - - // Compile vertex shader (if provided) - // NOTE: If not vertex shader is provided, use default one - if (vsCode != NULL) vertexShaderId = rlCompileShader(vsCode, GL_VERTEX_SHADER); - else vertexShaderId = RLGL.State.defaultVShaderId; - - // Compile fragment shader (if provided) - // NOTE: If not vertex shader is provided, use default one - if (fsCode != NULL) fragmentShaderId = rlCompileShader(fsCode, GL_FRAGMENT_SHADER); - else fragmentShaderId = RLGL.State.defaultFShaderId; - - // In case vertex and fragment shader are the default ones, no need to recompile, we can just assign the default shader program id - if ((vertexShaderId == RLGL.State.defaultVShaderId) && (fragmentShaderId == RLGL.State.defaultFShaderId)) id = RLGL.State.defaultShaderId; - else if ((vertexShaderId > 0) && (fragmentShaderId > 0)) - { - // One of or both shader are new, we need to compile a new shader program - id = rlLoadShaderProgram(vertexShaderId, fragmentShaderId); - - // We can detach and delete vertex/fragment shaders (if not default ones) - // NOTE: We detach shader before deletion to make sure memory is freed - if (vertexShaderId != RLGL.State.defaultVShaderId) - { - // WARNING: Shader program linkage could fail and returned id is 0 - if (id > 0) glDetachShader(id, vertexShaderId); - glDeleteShader(vertexShaderId); - } - if (fragmentShaderId != RLGL.State.defaultFShaderId) - { - // WARNING: Shader program linkage could fail and returned id is 0 - if (id > 0) glDetachShader(id, fragmentShaderId); - glDeleteShader(fragmentShaderId); - } - - // In case shader program loading failed, we assign default shader - if (id == 0) - { - // In case shader loading fails, we return the default shader - TRACELOG(RL_LOG_WARNING, "SHADER: Failed to load custom shader code, using default shader"); - id = RLGL.State.defaultShaderId; - } - /* - else - { - // Get available shader uniforms - // NOTE: This information is useful for debug... - int uniformCount = -1; - glGetProgramiv(id, GL_ACTIVE_UNIFORMS, &uniformCount); - - for (int i = 0; i < uniformCount; i++) - { - int namelen = -1; - int num = -1; - char name[256] = { 0 }; // Assume no variable names longer than 256 - GLenum type = GL_ZERO; - - // Get the name of the uniforms - glGetActiveUniform(id, i, sizeof(name) - 1, &namelen, &num, &type, name); - - name[namelen] = 0; - TRACELOGD("SHADER: [ID %i] Active uniform (%s) set at location: %i", id, name, glGetUniformLocation(id, name)); - } - } - */ - } -#endif - - return id; -} - -// Compile custom shader and return shader id -unsigned int rlCompileShader(const char *shaderCode, int type) -{ - unsigned int shader = 0; - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - shader = glCreateShader(type); - glShaderSource(shader, 1, &shaderCode, NULL); - - GLint success = 0; - glCompileShader(shader); - glGetShaderiv(shader, GL_COMPILE_STATUS, &success); - - if (success == GL_FALSE) - { - switch (type) - { - case GL_VERTEX_SHADER: TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Failed to compile vertex shader code", shader); break; - case GL_FRAGMENT_SHADER: TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Failed to compile fragment shader code", shader); break; - //case GL_GEOMETRY_SHADER: - #if defined(GRAPHICS_API_OPENGL_43) - case GL_COMPUTE_SHADER: TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Failed to compile compute shader code", shader); break; - #elif defined(GRAPHICS_API_OPENGL_33) - case GL_COMPUTE_SHADER: TRACELOG(RL_LOG_WARNING, "SHADER: Compute shaders not enabled. Define GRAPHICS_API_OPENGL_43", shader); break; - #endif - default: break; - } - - int maxLength = 0; - glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength); - - if (maxLength > 0) - { - int length = 0; - char *log = (char *)RL_CALLOC(maxLength, sizeof(char)); - glGetShaderInfoLog(shader, maxLength, &length, log); - TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Compile error: %s", shader, log); - RL_FREE(log); - } - - shader = 0; - } - else - { - switch (type) - { - case GL_VERTEX_SHADER: TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Vertex shader compiled successfully", shader); break; - case GL_FRAGMENT_SHADER: TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Fragment shader compiled successfully", shader); break; - //case GL_GEOMETRY_SHADER: - #if defined(GRAPHICS_API_OPENGL_43) - case GL_COMPUTE_SHADER: TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Compute shader compiled successfully", shader); break; - #elif defined(GRAPHICS_API_OPENGL_33) - case GL_COMPUTE_SHADER: TRACELOG(RL_LOG_WARNING, "SHADER: Compute shaders not enabled. Define GRAPHICS_API_OPENGL_43", shader); break; - #endif - default: break; - } - } -#endif - - return shader; -} - -// Load custom shader strings and return program id -unsigned int rlLoadShaderProgram(unsigned int vShaderId, unsigned int fShaderId) -{ - unsigned int program = 0; - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - GLint success = 0; - program = glCreateProgram(); - - glAttachShader(program, vShaderId); - glAttachShader(program, fShaderId); - - // NOTE: Default attribute shader locations must be Bound before linking - glBindAttribLocation(program, RL_DEFAULT_SHADER_ATTRIB_LOCATION_POSITION, RL_DEFAULT_SHADER_ATTRIB_NAME_POSITION); - glBindAttribLocation(program, RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD, RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD); - glBindAttribLocation(program, RL_DEFAULT_SHADER_ATTRIB_LOCATION_NORMAL, RL_DEFAULT_SHADER_ATTRIB_NAME_NORMAL); - glBindAttribLocation(program, RL_DEFAULT_SHADER_ATTRIB_LOCATION_COLOR, RL_DEFAULT_SHADER_ATTRIB_NAME_COLOR); - glBindAttribLocation(program, RL_DEFAULT_SHADER_ATTRIB_LOCATION_TANGENT, RL_DEFAULT_SHADER_ATTRIB_NAME_TANGENT); - glBindAttribLocation(program, RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD2, RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD2); - -#ifdef RL_SUPPORT_MESH_GPU_SKINNING - glBindAttribLocation(program, RL_DEFAULT_SHADER_ATTRIB_LOCATION_BONEIDS, RL_DEFAULT_SHADER_ATTRIB_NAME_BONEIDS); - glBindAttribLocation(program, RL_DEFAULT_SHADER_ATTRIB_LOCATION_BONEWEIGHTS, RL_DEFAULT_SHADER_ATTRIB_NAME_BONEWEIGHTS); -#endif - - // NOTE: If some attrib name is no found on the shader, it locations becomes -1 - - glLinkProgram(program); - - // NOTE: All uniform variables are intitialised to 0 when a program links - - glGetProgramiv(program, GL_LINK_STATUS, &success); - - if (success == GL_FALSE) - { - TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Failed to link shader program", program); - - int maxLength = 0; - glGetProgramiv(program, GL_INFO_LOG_LENGTH, &maxLength); - - if (maxLength > 0) - { - int length = 0; - char *log = (char *)RL_CALLOC(maxLength, sizeof(char)); - glGetProgramInfoLog(program, maxLength, &length, log); - TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Link error: %s", program, log); - RL_FREE(log); - } - - glDeleteProgram(program); - - program = 0; - } - else - { - // Get the size of compiled shader program (not available on OpenGL ES 2.0) - // NOTE: If GL_LINK_STATUS is GL_FALSE, program binary length is zero - //GLint binarySize = 0; - //glGetProgramiv(id, GL_PROGRAM_BINARY_LENGTH, &binarySize); - - TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Program shader loaded successfully", program); - } -#endif - return program; -} - -// Unload shader program -void rlUnloadShaderProgram(unsigned int id) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glDeleteProgram(id); - - TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Unloaded shader program data from VRAM (GPU)", id); -#endif -} - -// Get shader location uniform -int rlGetLocationUniform(unsigned int shaderId, const char *uniformName) -{ - int location = -1; -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - location = glGetUniformLocation(shaderId, uniformName); - - //if (location == -1) TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Failed to find shader uniform: %s", shaderId, uniformName); - //else TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Shader uniform (%s) set at location: %i", shaderId, uniformName, location); -#endif - return location; -} - -// Get shader location attribute -int rlGetLocationAttrib(unsigned int shaderId, const char *attribName) -{ - int location = -1; -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - location = glGetAttribLocation(shaderId, attribName); - - //if (location == -1) TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Failed to find shader attribute: %s", shaderId, attribName); - //else TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Shader attribute (%s) set at location: %i", shaderId, attribName, location); -#endif - return location; -} - -// Set shader value uniform -void rlSetUniform(int locIndex, const void *value, int uniformType, int count) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - switch (uniformType) - { - case RL_SHADER_UNIFORM_FLOAT: glUniform1fv(locIndex, count, (float *)value); break; - case RL_SHADER_UNIFORM_VEC2: glUniform2fv(locIndex, count, (float *)value); break; - case RL_SHADER_UNIFORM_VEC3: glUniform3fv(locIndex, count, (float *)value); break; - case RL_SHADER_UNIFORM_VEC4: glUniform4fv(locIndex, count, (float *)value); break; - case RL_SHADER_UNIFORM_INT: glUniform1iv(locIndex, count, (int *)value); break; - case RL_SHADER_UNIFORM_IVEC2: glUniform2iv(locIndex, count, (int *)value); break; - case RL_SHADER_UNIFORM_IVEC3: glUniform3iv(locIndex, count, (int *)value); break; - case RL_SHADER_UNIFORM_IVEC4: glUniform4iv(locIndex, count, (int *)value); break; - #if !defined(GRAPHICS_API_OPENGL_ES2) - case RL_SHADER_UNIFORM_UINT: glUniform1uiv(locIndex, count, (unsigned int *)value); break; - case RL_SHADER_UNIFORM_UIVEC2: glUniform2uiv(locIndex, count, (unsigned int *)value); break; - case RL_SHADER_UNIFORM_UIVEC3: glUniform3uiv(locIndex, count, (unsigned int *)value); break; - case RL_SHADER_UNIFORM_UIVEC4: glUniform4uiv(locIndex, count, (unsigned int *)value); break; - #endif - case RL_SHADER_UNIFORM_SAMPLER2D: glUniform1iv(locIndex, count, (int *)value); break; - default: TRACELOG(RL_LOG_WARNING, "SHADER: Failed to set uniform value, data type not recognized"); - - // TODO: Support glUniform1uiv(), glUniform2uiv(), glUniform3uiv(), glUniform4uiv() - } -#endif -} - -// Set shader value attribute -void rlSetVertexAttributeDefault(int locIndex, const void *value, int attribType, int count) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - switch (attribType) - { - case RL_SHADER_ATTRIB_FLOAT: if (count == 1) glVertexAttrib1fv(locIndex, (float *)value); break; - case RL_SHADER_ATTRIB_VEC2: if (count == 2) glVertexAttrib2fv(locIndex, (float *)value); break; - case RL_SHADER_ATTRIB_VEC3: if (count == 3) glVertexAttrib3fv(locIndex, (float *)value); break; - case RL_SHADER_ATTRIB_VEC4: if (count == 4) glVertexAttrib4fv(locIndex, (float *)value); break; - default: TRACELOG(RL_LOG_WARNING, "SHADER: Failed to set attrib default value, data type not recognized"); - } -#endif -} - -// Set shader value uniform matrix -void rlSetUniformMatrix(int locIndex, Matrix mat) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - float matfloat[16] = { - mat.m0, mat.m1, mat.m2, mat.m3, - mat.m4, mat.m5, mat.m6, mat.m7, - mat.m8, mat.m9, mat.m10, mat.m11, - mat.m12, mat.m13, mat.m14, mat.m15 - }; - glUniformMatrix4fv(locIndex, 1, false, matfloat); -#endif -} - -// Set shader value uniform matrix -void rlSetUniformMatrices(int locIndex, const Matrix *matrices, int count) -{ -#if defined(GRAPHICS_API_OPENGL_33) - glUniformMatrix4fv(locIndex, count, true, (const float *)matrices); -#elif defined(GRAPHICS_API_OPENGL_ES2) - // WARNING: WebGL does not support Matrix transpose ("true" parameter) - // REF: https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/uniformMatrix - glUniformMatrix4fv(locIndex, count, false, (const float *)matrices); -#endif -} - -// Set shader value uniform sampler -void rlSetUniformSampler(int locIndex, unsigned int textureId) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - // Check if texture is already active - for (int i = 0; i < RL_DEFAULT_BATCH_MAX_TEXTURE_UNITS; i++) - { - if (RLGL.State.activeTextureId[i] == textureId) - { - glUniform1i(locIndex, 1 + i); - return; - } - } - - // Register a new active texture for the internal batch system - // NOTE: Default texture is always activated as GL_TEXTURE0 - for (int i = 0; i < RL_DEFAULT_BATCH_MAX_TEXTURE_UNITS; i++) - { - if (RLGL.State.activeTextureId[i] == 0) - { - glUniform1i(locIndex, 1 + i); // Activate new texture unit - RLGL.State.activeTextureId[i] = textureId; // Save texture id for binding on drawing - break; - } - } -#endif -} - -// Set shader currently active (id and locations) -void rlSetShader(unsigned int id, int *locs) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if (RLGL.State.currentShaderId != id) - { - rlDrawRenderBatch(RLGL.currentBatch); - RLGL.State.currentShaderId = id; - RLGL.State.currentShaderLocs = locs; - } -#endif -} - -// Load compute shader program -unsigned int rlLoadComputeShaderProgram(unsigned int shaderId) -{ - unsigned int program = 0; - -#if defined(GRAPHICS_API_OPENGL_43) - GLint success = 0; - program = glCreateProgram(); - glAttachShader(program, shaderId); - glLinkProgram(program); - - // NOTE: All uniform variables are intitialised to 0 when a program links - - glGetProgramiv(program, GL_LINK_STATUS, &success); - - if (success == GL_FALSE) - { - TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Failed to link compute shader program", program); - - int maxLength = 0; - glGetProgramiv(program, GL_INFO_LOG_LENGTH, &maxLength); - - if (maxLength > 0) - { - int length = 0; - char *log = (char *)RL_CALLOC(maxLength, sizeof(char)); - glGetProgramInfoLog(program, maxLength, &length, log); - TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Link error: %s", program, log); - RL_FREE(log); - } - - glDeleteProgram(program); - - program = 0; - } - else - { - // Get the size of compiled shader program (not available on OpenGL ES 2.0) - // NOTE: If GL_LINK_STATUS is GL_FALSE, program binary length is zero - //GLint binarySize = 0; - //glGetProgramiv(id, GL_PROGRAM_BINARY_LENGTH, &binarySize); - - TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Compute shader program loaded successfully", program); - } -#else - TRACELOG(RL_LOG_WARNING, "SHADER: Compute shaders not enabled. Define GRAPHICS_API_OPENGL_43"); -#endif - - return program; -} - -// Dispatch compute shader (equivalent to *draw* for graphics pilepine) -void rlComputeShaderDispatch(unsigned int groupX, unsigned int groupY, unsigned int groupZ) -{ -#if defined(GRAPHICS_API_OPENGL_43) - glDispatchCompute(groupX, groupY, groupZ); -#endif -} - -// Load shader storage buffer object (SSBO) -unsigned int rlLoadShaderBuffer(unsigned int size, const void *data, int usageHint) -{ - unsigned int ssbo = 0; - -#if defined(GRAPHICS_API_OPENGL_43) - glGenBuffers(1, &ssbo); - glBindBuffer(GL_SHADER_STORAGE_BUFFER, ssbo); - glBufferData(GL_SHADER_STORAGE_BUFFER, size, data, usageHint? usageHint : RL_STREAM_COPY); - if (data == NULL) glClearBufferData(GL_SHADER_STORAGE_BUFFER, GL_R8UI, GL_RED_INTEGER, GL_UNSIGNED_BYTE, NULL); // Clear buffer data to 0 - glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0); -#else - TRACELOG(RL_LOG_WARNING, "SSBO: SSBO not enabled. Define GRAPHICS_API_OPENGL_43"); -#endif - - return ssbo; -} - -// Unload shader storage buffer object (SSBO) -void rlUnloadShaderBuffer(unsigned int ssboId) -{ -#if defined(GRAPHICS_API_OPENGL_43) - glDeleteBuffers(1, &ssboId); -#else - TRACELOG(RL_LOG_WARNING, "SSBO: SSBO not enabled. Define GRAPHICS_API_OPENGL_43"); -#endif - -} - -// Update SSBO buffer data -void rlUpdateShaderBuffer(unsigned int id, const void *data, unsigned int dataSize, unsigned int offset) -{ -#if defined(GRAPHICS_API_OPENGL_43) - glBindBuffer(GL_SHADER_STORAGE_BUFFER, id); - glBufferSubData(GL_SHADER_STORAGE_BUFFER, offset, dataSize, data); -#endif -} - -// Get SSBO buffer size -unsigned int rlGetShaderBufferSize(unsigned int id) -{ -#if defined(GRAPHICS_API_OPENGL_43) - GLint64 size = 0; - glBindBuffer(GL_SHADER_STORAGE_BUFFER, id); - glGetBufferParameteri64v(GL_SHADER_STORAGE_BUFFER, GL_BUFFER_SIZE, &size); - return (size > 0)? (unsigned int)size : 0; -#else - return 0; -#endif -} - -// Read SSBO buffer data (GPU->CPU) -void rlReadShaderBuffer(unsigned int id, void *dest, unsigned int count, unsigned int offset) -{ -#if defined(GRAPHICS_API_OPENGL_43) - glBindBuffer(GL_SHADER_STORAGE_BUFFER, id); - glGetBufferSubData(GL_SHADER_STORAGE_BUFFER, offset, count, dest); -#endif -} - -// Bind SSBO buffer -void rlBindShaderBuffer(unsigned int id, unsigned int index) -{ -#if defined(GRAPHICS_API_OPENGL_43) - glBindBufferBase(GL_SHADER_STORAGE_BUFFER, index, id); -#endif -} - -// Copy SSBO buffer data -void rlCopyShaderBuffer(unsigned int destId, unsigned int srcId, unsigned int destOffset, unsigned int srcOffset, unsigned int count) -{ -#if defined(GRAPHICS_API_OPENGL_43) - glBindBuffer(GL_COPY_READ_BUFFER, srcId); - glBindBuffer(GL_COPY_WRITE_BUFFER, destId); - glCopyBufferSubData(GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, srcOffset, destOffset, count); -#endif -} - -// Bind image texture -void rlBindImageTexture(unsigned int id, unsigned int index, int format, bool readonly) -{ -#if defined(GRAPHICS_API_OPENGL_43) - unsigned int glInternalFormat = 0, glFormat = 0, glType = 0; - - rlGetGlTextureFormats(format, &glInternalFormat, &glFormat, &glType); - glBindImageTexture(index, id, 0, 0, 0, readonly? GL_READ_ONLY : GL_READ_WRITE, glInternalFormat); -#else - TRACELOG(RL_LOG_WARNING, "TEXTURE: Image texture binding not enabled. Define GRAPHICS_API_OPENGL_43"); -#endif -} - -// Matrix state management -//----------------------------------------------------------------------------------------- -// Get internal modelview matrix -Matrix rlGetMatrixModelview(void) -{ - Matrix matrix = rlMatrixIdentity(); -#if defined(GRAPHICS_API_OPENGL_11) - float mat[16]; - glGetFloatv(GL_MODELVIEW_MATRIX, mat); - matrix.m0 = mat[0]; - matrix.m1 = mat[1]; - matrix.m2 = mat[2]; - matrix.m3 = mat[3]; - matrix.m4 = mat[4]; - matrix.m5 = mat[5]; - matrix.m6 = mat[6]; - matrix.m7 = mat[7]; - matrix.m8 = mat[8]; - matrix.m9 = mat[9]; - matrix.m10 = mat[10]; - matrix.m11 = mat[11]; - matrix.m12 = mat[12]; - matrix.m13 = mat[13]; - matrix.m14 = mat[14]; - matrix.m15 = mat[15]; -#else - matrix = RLGL.State.modelview; -#endif - return matrix; -} - -// Get internal projection matrix -Matrix rlGetMatrixProjection(void) -{ -#if defined(GRAPHICS_API_OPENGL_11) - float mat[16]; - glGetFloatv(GL_PROJECTION_MATRIX,mat); - Matrix m; - m.m0 = mat[0]; - m.m1 = mat[1]; - m.m2 = mat[2]; - m.m3 = mat[3]; - m.m4 = mat[4]; - m.m5 = mat[5]; - m.m6 = mat[6]; - m.m7 = mat[7]; - m.m8 = mat[8]; - m.m9 = mat[9]; - m.m10 = mat[10]; - m.m11 = mat[11]; - m.m12 = mat[12]; - m.m13 = mat[13]; - m.m14 = mat[14]; - m.m15 = mat[15]; - return m; -#else - return RLGL.State.projection; -#endif -} - -// Get internal accumulated transform matrix -Matrix rlGetMatrixTransform(void) -{ - Matrix mat = rlMatrixIdentity(); -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - // TODO: Consider possible transform matrices in the RLGL.State.stack - // Is this the right order? or should we start with the first stored matrix instead of the last one? - //Matrix matStackTransform = rlMatrixIdentity(); - //for (int i = RLGL.State.stackCounter; i > 0; i--) matStackTransform = rlMatrixMultiply(RLGL.State.stack[i], matStackTransform); - mat = RLGL.State.transform; -#endif - return mat; -} - -// Get internal projection matrix for stereo render (selected eye) -Matrix rlGetMatrixProjectionStereo(int eye) -{ - Matrix mat = rlMatrixIdentity(); -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - mat = RLGL.State.projectionStereo[eye]; -#endif - return mat; -} - -// Get internal view offset matrix for stereo render (selected eye) -Matrix rlGetMatrixViewOffsetStereo(int eye) -{ - Matrix mat = rlMatrixIdentity(); -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - mat = RLGL.State.viewOffsetStereo[eye]; -#endif - return mat; -} - -// Set a custom modelview matrix (replaces internal modelview matrix) -void rlSetMatrixModelview(Matrix view) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - RLGL.State.modelview = view; -#endif -} - -// Set a custom projection matrix (replaces internal projection matrix) -void rlSetMatrixProjection(Matrix projection) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - RLGL.State.projection = projection; -#endif -} - -// Set eyes projection matrices for stereo rendering -void rlSetMatrixProjectionStereo(Matrix right, Matrix left) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - RLGL.State.projectionStereo[0] = right; - RLGL.State.projectionStereo[1] = left; -#endif -} - -// Set eyes view offsets matrices for stereo rendering -void rlSetMatrixViewOffsetStereo(Matrix right, Matrix left) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - RLGL.State.viewOffsetStereo[0] = right; - RLGL.State.viewOffsetStereo[1] = left; -#endif -} - -// Load and draw a quad in NDC -void rlLoadDrawQuad(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - unsigned int quadVAO = 0; - unsigned int quadVBO = 0; - - float vertices[] = { - // Positions Texcoords - -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, - -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, - 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, - 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, - }; - - // Gen VAO to contain VBO - glGenVertexArrays(1, &quadVAO); - glBindVertexArray(quadVAO); - - // Gen and fill vertex buffer (VBO) - glGenBuffers(1, &quadVBO); - glBindBuffer(GL_ARRAY_BUFFER, quadVBO); - glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), &vertices, GL_STATIC_DRAW); - - // Bind vertex attributes (position, texcoords) - glEnableVertexAttribArray(RL_DEFAULT_SHADER_ATTRIB_LOCATION_POSITION); - glVertexAttribPointer(RL_DEFAULT_SHADER_ATTRIB_LOCATION_POSITION, 3, GL_FLOAT, GL_FALSE, 5*sizeof(float), (void *)0); // Positions - glEnableVertexAttribArray(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD); - glVertexAttribPointer(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD, 2, GL_FLOAT, GL_FALSE, 5*sizeof(float), (void *)(3*sizeof(float))); // Texcoords - - // Draw quad - glBindVertexArray(quadVAO); - glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); - glBindVertexArray(0); - - // Delete buffers (VBO and VAO) - glDeleteBuffers(1, &quadVBO); - glDeleteVertexArrays(1, &quadVAO); -#endif -} - -// Load and draw a cube in NDC -void rlLoadDrawCube(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - unsigned int cubeVAO = 0; - unsigned int cubeVBO = 0; - - float vertices[] = { - // Positions Normals Texcoords - -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, - 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, - 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, - 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, - -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, - -1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, - -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, - 1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, - 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, - -1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, - -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, - -1.0f, 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, - -1.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f, - -1.0f, -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, - -1.0f, -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, - -1.0f, -1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, - -1.0f, 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, - 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, - 1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, - 1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, - 1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, - 1.0f, -1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, - -1.0f, -1.0f, -1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, - 1.0f, -1.0f, -1.0f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f, - 1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, - 1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, - -1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, - -1.0f, -1.0f, -1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, - -1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, - 1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, - -1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, - -1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f - }; - - // Gen VAO to contain VBO - glGenVertexArrays(1, &cubeVAO); - glBindVertexArray(cubeVAO); - - // Gen and fill vertex buffer (VBO) - glGenBuffers(1, &cubeVBO); - glBindBuffer(GL_ARRAY_BUFFER, cubeVBO); - glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); - - // Bind vertex attributes (position, normals, texcoords) - glBindVertexArray(cubeVAO); - glEnableVertexAttribArray(RL_DEFAULT_SHADER_ATTRIB_LOCATION_POSITION); - glVertexAttribPointer(RL_DEFAULT_SHADER_ATTRIB_LOCATION_POSITION, 3, GL_FLOAT, GL_FALSE, 8*sizeof(float), (void *)0); // Positions - glEnableVertexAttribArray(RL_DEFAULT_SHADER_ATTRIB_LOCATION_NORMAL); - glVertexAttribPointer(RL_DEFAULT_SHADER_ATTRIB_LOCATION_NORMAL, 3, GL_FLOAT, GL_FALSE, 8*sizeof(float), (void *)(3*sizeof(float))); // Normals - glEnableVertexAttribArray(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD); - glVertexAttribPointer(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD, 2, GL_FLOAT, GL_FALSE, 8*sizeof(float), (void *)(6*sizeof(float))); // Texcoords - glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindVertexArray(0); - - // Draw cube - glBindVertexArray(cubeVAO); - glDrawArrays(GL_TRIANGLES, 0, 36); - glBindVertexArray(0); - - // Delete VBO and VAO - glDeleteBuffers(1, &cubeVBO); - glDeleteVertexArrays(1, &cubeVAO); -#endif -} - -// Get name string for pixel format -const char *rlGetPixelFormatName(unsigned int format) -{ - switch (format) - { - case RL_PIXELFORMAT_UNCOMPRESSED_GRAYSCALE: return "GRAYSCALE"; break; // 8 bit per pixel (no alpha) - case RL_PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA: return "GRAY_ALPHA"; break; // 8*2 bpp (2 channels) - case RL_PIXELFORMAT_UNCOMPRESSED_R5G6B5: return "R5G6B5"; break; // 16 bpp - case RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8: return "R8G8B8"; break; // 24 bpp - case RL_PIXELFORMAT_UNCOMPRESSED_R5G5B5A1: return "R5G5B5A1"; break; // 16 bpp (1 bit alpha) - case RL_PIXELFORMAT_UNCOMPRESSED_R4G4B4A4: return "R4G4B4A4"; break; // 16 bpp (4 bit alpha) - case RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8A8: return "R8G8B8A8"; break; // 32 bpp - case RL_PIXELFORMAT_UNCOMPRESSED_R32: return "R32"; break; // 32 bpp (1 channel - float) - case RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32: return "R32G32B32"; break; // 32*3 bpp (3 channels - float) - case RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32A32: return "R32G32B32A32"; break; // 32*4 bpp (4 channels - float) - case RL_PIXELFORMAT_UNCOMPRESSED_R16: return "R16"; break; // 16 bpp (1 channel - half float) - case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16: return "R16G16B16"; break; // 16*3 bpp (3 channels - half float) - case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16A16: return "R16G16B16A16"; break; // 16*4 bpp (4 channels - half float) - case RL_PIXELFORMAT_COMPRESSED_DXT1_RGB: return "DXT1_RGB"; break; // 4 bpp (no alpha) - case RL_PIXELFORMAT_COMPRESSED_DXT1_RGBA: return "DXT1_RGBA"; break; // 4 bpp (1 bit alpha) - case RL_PIXELFORMAT_COMPRESSED_DXT3_RGBA: return "DXT3_RGBA"; break; // 8 bpp - case RL_PIXELFORMAT_COMPRESSED_DXT5_RGBA: return "DXT5_RGBA"; break; // 8 bpp - case RL_PIXELFORMAT_COMPRESSED_ETC1_RGB: return "ETC1_RGB"; break; // 4 bpp - case RL_PIXELFORMAT_COMPRESSED_ETC2_RGB: return "ETC2_RGB"; break; // 4 bpp - case RL_PIXELFORMAT_COMPRESSED_ETC2_EAC_RGBA: return "ETC2_RGBA"; break; // 8 bpp - case RL_PIXELFORMAT_COMPRESSED_PVRT_RGB: return "PVRT_RGB"; break; // 4 bpp - case RL_PIXELFORMAT_COMPRESSED_PVRT_RGBA: return "PVRT_RGBA"; break; // 4 bpp - case RL_PIXELFORMAT_COMPRESSED_ASTC_4x4_RGBA: return "ASTC_4x4_RGBA"; break; // 8 bpp - case RL_PIXELFORMAT_COMPRESSED_ASTC_8x8_RGBA: return "ASTC_8x8_RGBA"; break; // 2 bpp - default: return "UNKNOWN"; break; - } -} - -//---------------------------------------------------------------------------------- -// Module specific Functions Definition -//---------------------------------------------------------------------------------- -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) -// Load default shader (just vertex positioning and texture coloring) -// NOTE: This shader program is used for internal buffers -// NOTE: Loaded: RLGL.State.defaultShaderId, RLGL.State.defaultShaderLocs -static void rlLoadShaderDefault(void) -{ - RLGL.State.defaultShaderLocs = (int *)RL_CALLOC(RL_MAX_SHADER_LOCATIONS, sizeof(int)); - - // NOTE: All locations must be reseted to -1 (no location) - for (int i = 0; i < RL_MAX_SHADER_LOCATIONS; i++) RLGL.State.defaultShaderLocs[i] = -1; - - // Vertex shader directly defined, no external file required - const char *defaultVShaderCode = -#if defined(GRAPHICS_API_OPENGL_21) - "#version 120 \n" - "attribute vec3 vertexPosition; \n" - "attribute vec2 vertexTexCoord; \n" - "attribute vec4 vertexColor; \n" - "varying vec2 fragTexCoord; \n" - "varying vec4 fragColor; \n" -#elif defined(GRAPHICS_API_OPENGL_33) - "#version 330 \n" - "in vec3 vertexPosition; \n" - "in vec2 vertexTexCoord; \n" - "in vec4 vertexColor; \n" - "out vec2 fragTexCoord; \n" - "out vec4 fragColor; \n" -#endif - -#if defined(GRAPHICS_API_OPENGL_ES3) - "#version 300 es \n" - "precision mediump float; \n" // Precision required for OpenGL ES3 (WebGL 2) (on some browsers) - "in vec3 vertexPosition; \n" - "in vec2 vertexTexCoord; \n" - "in vec4 vertexColor; \n" - "out vec2 fragTexCoord; \n" - "out vec4 fragColor; \n" -#elif defined(GRAPHICS_API_OPENGL_ES2) - "#version 100 \n" - "precision mediump float; \n" // Precision required for OpenGL ES2 (WebGL) (on some browsers) - "attribute vec3 vertexPosition; \n" - "attribute vec2 vertexTexCoord; \n" - "attribute vec4 vertexColor; \n" - "varying vec2 fragTexCoord; \n" - "varying vec4 fragColor; \n" -#endif - - "uniform mat4 mvp; \n" - "void main() \n" - "{ \n" - " fragTexCoord = vertexTexCoord; \n" - " fragColor = vertexColor; \n" - " gl_Position = mvp*vec4(vertexPosition, 1.0); \n" - "} \n"; - - // Fragment shader directly defined, no external file required - const char *defaultFShaderCode = -#if defined(GRAPHICS_API_OPENGL_21) - "#version 120 \n" - "varying vec2 fragTexCoord; \n" - "varying vec4 fragColor; \n" - "uniform sampler2D texture0; \n" - "uniform vec4 colDiffuse; \n" - "void main() \n" - "{ \n" - " vec4 texelColor = texture2D(texture0, fragTexCoord); \n" - " gl_FragColor = texelColor*colDiffuse*fragColor; \n" - "} \n"; -#elif defined(GRAPHICS_API_OPENGL_33) - "#version 330 \n" - "in vec2 fragTexCoord; \n" - "in vec4 fragColor; \n" - "out vec4 finalColor; \n" - "uniform sampler2D texture0; \n" - "uniform vec4 colDiffuse; \n" - "void main() \n" - "{ \n" - " vec4 texelColor = texture(texture0, fragTexCoord); \n" - " finalColor = texelColor*colDiffuse*fragColor; \n" - "} \n"; -#endif - -#if defined(GRAPHICS_API_OPENGL_ES3) - "#version 300 es \n" - "precision mediump float; \n" // Precision required for OpenGL ES3 (WebGL 2) - "in vec2 fragTexCoord; \n" - "in vec4 fragColor; \n" - "out vec4 finalColor; \n" - "uniform sampler2D texture0; \n" - "uniform vec4 colDiffuse; \n" - "void main() \n" - "{ \n" - " vec4 texelColor = texture(texture0, fragTexCoord); \n" - " finalColor = texelColor*colDiffuse*fragColor; \n" - "} \n"; -#elif defined(GRAPHICS_API_OPENGL_ES2) - "#version 100 \n" - "precision mediump float; \n" // Precision required for OpenGL ES2 (WebGL) - "varying vec2 fragTexCoord; \n" - "varying vec4 fragColor; \n" - "uniform sampler2D texture0; \n" - "uniform vec4 colDiffuse; \n" - "void main() \n" - "{ \n" - " vec4 texelColor = texture2D(texture0, fragTexCoord); \n" - " gl_FragColor = texelColor*colDiffuse*fragColor; \n" - "} \n"; -#endif - - // NOTE: Compiled vertex/fragment shaders are not deleted, - // they are kept for re-use as default shaders in case some shader loading fails - RLGL.State.defaultVShaderId = rlCompileShader(defaultVShaderCode, GL_VERTEX_SHADER); // Compile default vertex shader - RLGL.State.defaultFShaderId = rlCompileShader(defaultFShaderCode, GL_FRAGMENT_SHADER); // Compile default fragment shader - - RLGL.State.defaultShaderId = rlLoadShaderProgram(RLGL.State.defaultVShaderId, RLGL.State.defaultFShaderId); - - if (RLGL.State.defaultShaderId > 0) - { - TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Default shader loaded successfully", RLGL.State.defaultShaderId); - - // Set default shader locations: attributes locations - RLGL.State.defaultShaderLocs[RL_SHADER_LOC_VERTEX_POSITION] = glGetAttribLocation(RLGL.State.defaultShaderId, RL_DEFAULT_SHADER_ATTRIB_NAME_POSITION); - RLGL.State.defaultShaderLocs[RL_SHADER_LOC_VERTEX_TEXCOORD01] = glGetAttribLocation(RLGL.State.defaultShaderId, RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD); - RLGL.State.defaultShaderLocs[RL_SHADER_LOC_VERTEX_COLOR] = glGetAttribLocation(RLGL.State.defaultShaderId, RL_DEFAULT_SHADER_ATTRIB_NAME_COLOR); - - // Set default shader locations: uniform locations - RLGL.State.defaultShaderLocs[RL_SHADER_LOC_MATRIX_MVP] = glGetUniformLocation(RLGL.State.defaultShaderId, RL_DEFAULT_SHADER_UNIFORM_NAME_MVP); - RLGL.State.defaultShaderLocs[RL_SHADER_LOC_COLOR_DIFFUSE] = glGetUniformLocation(RLGL.State.defaultShaderId, RL_DEFAULT_SHADER_UNIFORM_NAME_COLOR); - RLGL.State.defaultShaderLocs[RL_SHADER_LOC_MAP_DIFFUSE] = glGetUniformLocation(RLGL.State.defaultShaderId, RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE0); - } - else TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Failed to load default shader", RLGL.State.defaultShaderId); -} - -// Unload default shader -// NOTE: Unloads: RLGL.State.defaultShaderId, RLGL.State.defaultShaderLocs -static void rlUnloadShaderDefault(void) -{ - glUseProgram(0); - - glDetachShader(RLGL.State.defaultShaderId, RLGL.State.defaultVShaderId); - glDetachShader(RLGL.State.defaultShaderId, RLGL.State.defaultFShaderId); - glDeleteShader(RLGL.State.defaultVShaderId); - glDeleteShader(RLGL.State.defaultFShaderId); - - glDeleteProgram(RLGL.State.defaultShaderId); - - RL_FREE(RLGL.State.defaultShaderLocs); - - TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Default shader unloaded successfully", RLGL.State.defaultShaderId); -} - -#if defined(RLGL_SHOW_GL_DETAILS_INFO) -// Get compressed format official GL identifier name -static const char *rlGetCompressedFormatName(int format) -{ - switch (format) - { - // GL_EXT_texture_compression_s3tc - case 0x83F0: return "GL_COMPRESSED_RGB_S3TC_DXT1_EXT"; break; - case 0x83F1: return "GL_COMPRESSED_RGBA_S3TC_DXT1_EXT"; break; - case 0x83F2: return "GL_COMPRESSED_RGBA_S3TC_DXT3_EXT"; break; - case 0x83F3: return "GL_COMPRESSED_RGBA_S3TC_DXT5_EXT"; break; - // GL_3DFX_texture_compression_FXT1 - case 0x86B0: return "GL_COMPRESSED_RGB_FXT1_3DFX"; break; - case 0x86B1: return "GL_COMPRESSED_RGBA_FXT1_3DFX"; break; - // GL_IMG_texture_compression_pvrtc - case 0x8C00: return "GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG"; break; - case 0x8C01: return "GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG"; break; - case 0x8C02: return "GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG"; break; - case 0x8C03: return "GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG"; break; - // GL_OES_compressed_ETC1_RGB8_texture - case 0x8D64: return "GL_ETC1_RGB8_OES"; break; - // GL_ARB_texture_compression_rgtc - case 0x8DBB: return "GL_COMPRESSED_RED_RGTC1"; break; - case 0x8DBC: return "GL_COMPRESSED_SIGNED_RED_RGTC1"; break; - case 0x8DBD: return "GL_COMPRESSED_RG_RGTC2"; break; - case 0x8DBE: return "GL_COMPRESSED_SIGNED_RG_RGTC2"; break; - // GL_ARB_texture_compression_bptc - case 0x8E8C: return "GL_COMPRESSED_RGBA_BPTC_UNORM_ARB"; break; - case 0x8E8D: return "GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB"; break; - case 0x8E8E: return "GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB"; break; - case 0x8E8F: return "GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB"; break; - // GL_ARB_ES3_compatibility - case 0x9274: return "GL_COMPRESSED_RGB8_ETC2"; break; - case 0x9275: return "GL_COMPRESSED_SRGB8_ETC2"; break; - case 0x9276: return "GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2"; break; - case 0x9277: return "GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2"; break; - case 0x9278: return "GL_COMPRESSED_RGBA8_ETC2_EAC"; break; - case 0x9279: return "GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC"; break; - case 0x9270: return "GL_COMPRESSED_R11_EAC"; break; - case 0x9271: return "GL_COMPRESSED_SIGNED_R11_EAC"; break; - case 0x9272: return "GL_COMPRESSED_RG11_EAC"; break; - case 0x9273: return "GL_COMPRESSED_SIGNED_RG11_EAC"; break; - // GL_KHR_texture_compression_astc_hdr - case 0x93B0: return "GL_COMPRESSED_RGBA_ASTC_4x4_KHR"; break; - case 0x93B1: return "GL_COMPRESSED_RGBA_ASTC_5x4_KHR"; break; - case 0x93B2: return "GL_COMPRESSED_RGBA_ASTC_5x5_KHR"; break; - case 0x93B3: return "GL_COMPRESSED_RGBA_ASTC_6x5_KHR"; break; - case 0x93B4: return "GL_COMPRESSED_RGBA_ASTC_6x6_KHR"; break; - case 0x93B5: return "GL_COMPRESSED_RGBA_ASTC_8x5_KHR"; break; - case 0x93B6: return "GL_COMPRESSED_RGBA_ASTC_8x6_KHR"; break; - case 0x93B7: return "GL_COMPRESSED_RGBA_ASTC_8x8_KHR"; break; - case 0x93B8: return "GL_COMPRESSED_RGBA_ASTC_10x5_KHR"; break; - case 0x93B9: return "GL_COMPRESSED_RGBA_ASTC_10x6_KHR"; break; - case 0x93BA: return "GL_COMPRESSED_RGBA_ASTC_10x8_KHR"; break; - case 0x93BB: return "GL_COMPRESSED_RGBA_ASTC_10x10_KHR"; break; - case 0x93BC: return "GL_COMPRESSED_RGBA_ASTC_12x10_KHR"; break; - case 0x93BD: return "GL_COMPRESSED_RGBA_ASTC_12x12_KHR"; break; - case 0x93D0: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR"; break; - case 0x93D1: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR"; break; - case 0x93D2: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR"; break; - case 0x93D3: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR"; break; - case 0x93D4: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR"; break; - case 0x93D5: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR"; break; - case 0x93D6: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR"; break; - case 0x93D7: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR"; break; - case 0x93D8: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR"; break; - case 0x93D9: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR"; break; - case 0x93DA: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR"; break; - case 0x93DB: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR"; break; - case 0x93DC: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR"; break; - case 0x93DD: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR"; break; - default: return "GL_COMPRESSED_UNKNOWN"; break; - } -} -#endif // RLGL_SHOW_GL_DETAILS_INFO - -#endif // GRAPHICS_API_OPENGL_33 || GRAPHICS_API_OPENGL_ES2 - -// Get pixel data size in bytes (image or texture) -// NOTE: Size depends on pixel format -static int rlGetPixelDataSize(int width, int height, int format) -{ - int dataSize = 0; // Size in bytes - int bpp = 0; // Bits per pixel - - switch (format) - { - case RL_PIXELFORMAT_UNCOMPRESSED_GRAYSCALE: bpp = 8; break; - case RL_PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA: - case RL_PIXELFORMAT_UNCOMPRESSED_R5G6B5: - case RL_PIXELFORMAT_UNCOMPRESSED_R5G5B5A1: - case RL_PIXELFORMAT_UNCOMPRESSED_R4G4B4A4: bpp = 16; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8A8: bpp = 32; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8: bpp = 24; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R32: bpp = 32; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32: bpp = 32*3; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32A32: bpp = 32*4; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R16: bpp = 16; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16: bpp = 16*3; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16A16: bpp = 16*4; break; - case RL_PIXELFORMAT_COMPRESSED_DXT1_RGB: - case RL_PIXELFORMAT_COMPRESSED_DXT1_RGBA: - case RL_PIXELFORMAT_COMPRESSED_ETC1_RGB: - case RL_PIXELFORMAT_COMPRESSED_ETC2_RGB: - case RL_PIXELFORMAT_COMPRESSED_PVRT_RGB: - case RL_PIXELFORMAT_COMPRESSED_PVRT_RGBA: bpp = 4; break; - case RL_PIXELFORMAT_COMPRESSED_DXT3_RGBA: - case RL_PIXELFORMAT_COMPRESSED_DXT5_RGBA: - case RL_PIXELFORMAT_COMPRESSED_ETC2_EAC_RGBA: - case RL_PIXELFORMAT_COMPRESSED_ASTC_4x4_RGBA: bpp = 8; break; - case RL_PIXELFORMAT_COMPRESSED_ASTC_8x8_RGBA: bpp = 2; break; - default: break; - } - - double bytesPerPixel = (double)bpp/8.0; - dataSize = (int)(bytesPerPixel*width*height); // Total data size in bytes - - // Most compressed formats works on 4x4 blocks, - // if texture is smaller, minimum dataSize is 8 or 16 - if ((width < 4) && (height < 4)) - { - if ((format >= RL_PIXELFORMAT_COMPRESSED_DXT1_RGB) && (format < RL_PIXELFORMAT_COMPRESSED_DXT3_RGBA)) dataSize = 8; - else if ((format >= RL_PIXELFORMAT_COMPRESSED_DXT3_RGBA) && (format < RL_PIXELFORMAT_COMPRESSED_ASTC_8x8_RGBA)) dataSize = 16; - } - - return dataSize; -} - -// Auxiliar math functions - -// Get float array of matrix data -static rl_float16 rlMatrixToFloatV(Matrix mat) -{ - rl_float16 result = { 0 }; - - result.v[0] = mat.m0; - result.v[1] = mat.m1; - result.v[2] = mat.m2; - result.v[3] = mat.m3; - result.v[4] = mat.m4; - result.v[5] = mat.m5; - result.v[6] = mat.m6; - result.v[7] = mat.m7; - result.v[8] = mat.m8; - result.v[9] = mat.m9; - result.v[10] = mat.m10; - result.v[11] = mat.m11; - result.v[12] = mat.m12; - result.v[13] = mat.m13; - result.v[14] = mat.m14; - result.v[15] = mat.m15; - - return result; -} - -// Get identity matrix -static Matrix rlMatrixIdentity(void) -{ - Matrix result = { - 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f - }; - - return result; -} - -// Get two matrix multiplication -// NOTE: When multiplying matrices... the order matters! -static Matrix rlMatrixMultiply(Matrix left, Matrix right) -{ - Matrix result = { 0 }; - - result.m0 = left.m0*right.m0 + left.m1*right.m4 + left.m2*right.m8 + left.m3*right.m12; - result.m1 = left.m0*right.m1 + left.m1*right.m5 + left.m2*right.m9 + left.m3*right.m13; - result.m2 = left.m0*right.m2 + left.m1*right.m6 + left.m2*right.m10 + left.m3*right.m14; - result.m3 = left.m0*right.m3 + left.m1*right.m7 + left.m2*right.m11 + left.m3*right.m15; - result.m4 = left.m4*right.m0 + left.m5*right.m4 + left.m6*right.m8 + left.m7*right.m12; - result.m5 = left.m4*right.m1 + left.m5*right.m5 + left.m6*right.m9 + left.m7*right.m13; - result.m6 = left.m4*right.m2 + left.m5*right.m6 + left.m6*right.m10 + left.m7*right.m14; - result.m7 = left.m4*right.m3 + left.m5*right.m7 + left.m6*right.m11 + left.m7*right.m15; - result.m8 = left.m8*right.m0 + left.m9*right.m4 + left.m10*right.m8 + left.m11*right.m12; - result.m9 = left.m8*right.m1 + left.m9*right.m5 + left.m10*right.m9 + left.m11*right.m13; - result.m10 = left.m8*right.m2 + left.m9*right.m6 + left.m10*right.m10 + left.m11*right.m14; - result.m11 = left.m8*right.m3 + left.m9*right.m7 + left.m10*right.m11 + left.m11*right.m15; - result.m12 = left.m12*right.m0 + left.m13*right.m4 + left.m14*right.m8 + left.m15*right.m12; - result.m13 = left.m12*right.m1 + left.m13*right.m5 + left.m14*right.m9 + left.m15*right.m13; - result.m14 = left.m12*right.m2 + left.m13*right.m6 + left.m14*right.m10 + left.m15*right.m14; - result.m15 = left.m12*right.m3 + left.m13*right.m7 + left.m14*right.m11 + left.m15*right.m15; - - return result; -} - -// Transposes provided matrix -static Matrix rlMatrixTranspose(Matrix mat) -{ - Matrix result = { 0 }; - - result.m0 = mat.m0; - result.m1 = mat.m4; - result.m2 = mat.m8; - result.m3 = mat.m12; - result.m4 = mat.m1; - result.m5 = mat.m5; - result.m6 = mat.m9; - result.m7 = mat.m13; - result.m8 = mat.m2; - result.m9 = mat.m6; - result.m10 = mat.m10; - result.m11 = mat.m14; - result.m12 = mat.m3; - result.m13 = mat.m7; - result.m14 = mat.m11; - result.m15 = mat.m15; - - return result; -} - -// Invert provided matrix -static Matrix rlMatrixInvert(Matrix mat) -{ - Matrix result = { 0 }; - - // Cache the matrix values (speed optimization) - float a00 = mat.m0, a01 = mat.m1, a02 = mat.m2, a03 = mat.m3; - float a10 = mat.m4, a11 = mat.m5, a12 = mat.m6, a13 = mat.m7; - float a20 = mat.m8, a21 = mat.m9, a22 = mat.m10, a23 = mat.m11; - float a30 = mat.m12, a31 = mat.m13, a32 = mat.m14, a33 = mat.m15; - - float b00 = a00*a11 - a01*a10; - float b01 = a00*a12 - a02*a10; - float b02 = a00*a13 - a03*a10; - float b03 = a01*a12 - a02*a11; - float b04 = a01*a13 - a03*a11; - float b05 = a02*a13 - a03*a12; - float b06 = a20*a31 - a21*a30; - float b07 = a20*a32 - a22*a30; - float b08 = a20*a33 - a23*a30; - float b09 = a21*a32 - a22*a31; - float b10 = a21*a33 - a23*a31; - float b11 = a22*a33 - a23*a32; - - // Calculate the invert determinant (inlined to avoid double-caching) - float invDet = 1.0f/(b00*b11 - b01*b10 + b02*b09 + b03*b08 - b04*b07 + b05*b06); - - result.m0 = (a11*b11 - a12*b10 + a13*b09)*invDet; - result.m1 = (-a01*b11 + a02*b10 - a03*b09)*invDet; - result.m2 = (a31*b05 - a32*b04 + a33*b03)*invDet; - result.m3 = (-a21*b05 + a22*b04 - a23*b03)*invDet; - result.m4 = (-a10*b11 + a12*b08 - a13*b07)*invDet; - result.m5 = (a00*b11 - a02*b08 + a03*b07)*invDet; - result.m6 = (-a30*b05 + a32*b02 - a33*b01)*invDet; - result.m7 = (a20*b05 - a22*b02 + a23*b01)*invDet; - result.m8 = (a10*b10 - a11*b08 + a13*b06)*invDet; - result.m9 = (-a00*b10 + a01*b08 - a03*b06)*invDet; - result.m10 = (a30*b04 - a31*b02 + a33*b00)*invDet; - result.m11 = (-a20*b04 + a21*b02 - a23*b00)*invDet; - result.m12 = (-a10*b09 + a11*b07 - a12*b06)*invDet; - result.m13 = (a00*b09 - a01*b07 + a02*b06)*invDet; - result.m14 = (-a30*b03 + a31*b01 - a32*b00)*invDet; - result.m15 = (a20*b03 - a21*b01 + a22*b00)*invDet; - - return result; -} - -#endif // RLGL_IMPLEMENTATION diff --git a/third_party/raylib/larch64/libraylib.a b/third_party/raylib/larch64/libraylib.a deleted file mode 100644 index e1c5c19307..0000000000 --- a/third_party/raylib/larch64/libraylib.a +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:9c3125236db11e7bebcc6ad5868444ed0605c6343f98b212d39267c092b3b481 -size 3140628 diff --git a/third_party/raylib/x86_64/libraylib.a b/third_party/raylib/x86_64/libraylib.a deleted file mode 100644 index cf69482563..0000000000 --- a/third_party/raylib/x86_64/libraylib.a +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:f0b8f59758fe1291be82a8bda7a7ca05629c7addb0683936dd404ed08e19e143 -size 2769684 diff --git a/third_party/snpe/aarch64-ubuntu-gcc7.5/libPlatformValidatorShared.so b/third_party/snpe/aarch64-ubuntu-gcc7.5/libPlatformValidatorShared.so deleted file mode 100644 index a1c6fed910..0000000000 --- a/third_party/snpe/aarch64-ubuntu-gcc7.5/libPlatformValidatorShared.so +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:fb3b1fd29d958e9a3a6625eac9fac9e7cd6eb40309b285ad973324761db0b4c9 -size 1202792 diff --git a/third_party/snpe/aarch64-ubuntu-gcc7.5/libSNPE.so b/third_party/snpe/aarch64-ubuntu-gcc7.5/libSNPE.so deleted file mode 100644 index 54c0c32e41..0000000000 --- a/third_party/snpe/aarch64-ubuntu-gcc7.5/libSNPE.so +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:161a5d0bf7347465b53ae49690a38fbacf03d606ef204147b3b148a5f59188da -size 9008016 diff --git a/third_party/snpe/aarch64-ubuntu-gcc7.5/libcalculator.so b/third_party/snpe/aarch64-ubuntu-gcc7.5/libcalculator.so deleted file mode 100644 index 2154203026..0000000000 --- a/third_party/snpe/aarch64-ubuntu-gcc7.5/libcalculator.so +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:7e0e66c12a1eb3b5b4b2b2694831ca51e5132818f400dad789adbcc30e0e0793 -size 14032 diff --git a/third_party/snpe/aarch64-ubuntu-gcc7.5/libhta.so b/third_party/snpe/aarch64-ubuntu-gcc7.5/libhta.so deleted file mode 100644 index 1d81abd3a5..0000000000 --- a/third_party/snpe/aarch64-ubuntu-gcc7.5/libhta.so +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:784f2e80fa3534cf7934c5ecbbda37db633104380f2b41d896b4721ad6006eb2 -size 2420312 diff --git a/third_party/snpe/aarch64-ubuntu-gcc7.5/libsnpe_dsp_domains_v2.so b/third_party/snpe/aarch64-ubuntu-gcc7.5/libsnpe_dsp_domains_v2.so deleted file mode 100644 index 40e3d5af74..0000000000 --- a/third_party/snpe/aarch64-ubuntu-gcc7.5/libsnpe_dsp_domains_v2.so +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:33afe465e74bbe2c409350d2ca8e86cfadf050ceb8feac75a86adc19ff1f9c48 -size 26016 diff --git a/third_party/snpe/dsp/libcalculator_skel.so b/third_party/snpe/dsp/libcalculator_skel.so deleted file mode 100644 index 9e9e9221be..0000000000 --- a/third_party/snpe/dsp/libcalculator_skel.so +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:7bee94d38195478ffdd0ce15292a2dfa7813377f4c3b7d99c270e05079d1746b -size 20828 diff --git a/third_party/snpe/dsp/libsnpe_dsp_v65_domains_v2_skel.so b/third_party/snpe/dsp/libsnpe_dsp_v65_domains_v2_skel.so deleted file mode 100644 index 3f1b7a8b8c..0000000000 --- a/third_party/snpe/dsp/libsnpe_dsp_v65_domains_v2_skel.so +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4e040c87072aa915c47859c8c7f74076b98c6919b83ddd5dc4bb555870d586a7 -size 1813866 diff --git a/third_party/snpe/dsp/libsnpe_dsp_v66_domains_v2_skel.so b/third_party/snpe/dsp/libsnpe_dsp_v66_domains_v2_skel.so deleted file mode 100644 index aa42b5e830..0000000000 --- a/third_party/snpe/dsp/libsnpe_dsp_v66_domains_v2_skel.so +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:838bc58ac0094ba9593cf7c44ab6e8a94ae3dbbe176e320d9fbe86ceead53c5e -size 1817962 diff --git a/third_party/snpe/dsp/libsnpe_dsp_v68_domains_v3_skel.so b/third_party/snpe/dsp/libsnpe_dsp_v68_domains_v3_skel.so deleted file mode 100644 index 9423da1b94..0000000000 --- a/third_party/snpe/dsp/libsnpe_dsp_v68_domains_v3_skel.so +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:77d025d59521e13e4ed012f0d9d2b684cdb858208d70426078df51219eaeb9bd -size 10098673 diff --git a/third_party/snpe/include/DiagLog/IDiagLog.hpp b/third_party/snpe/include/DiagLog/IDiagLog.hpp deleted file mode 100644 index 018b567256..0000000000 --- a/third_party/snpe/include/DiagLog/IDiagLog.hpp +++ /dev/null @@ -1,84 +0,0 @@ -//============================================================================= -// -// Copyright (c) 2015, 2020 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================= -#ifndef __IDIAGLOG_HPP_ -#define __IDIAGLOG_HPP_ - -#include - -#include "DiagLog/Options.hpp" -#include "DlSystem/String.hpp" -#include "DlSystem/ZdlExportDefine.hpp" - -namespace zdl -{ -namespace DiagLog -{ - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/// @brief . -/// -/// Interface for controlling logging for zdl components. - -class ZDL_EXPORT IDiagLog -{ -public: - - /// @brief . - /// - /// Sets the options after initialization occurs. - /// - /// @param[in] loggingOptions The options to set up diagnostic logging. - /// - /// @return False if the options could not be set. Ensure logging is not started. - virtual bool setOptions(const Options& loggingOptions) = 0; - - /// @brief . - /// - /// Gets the curent options for the diag logger. - /// - /// @return Diag log options object. - virtual Options getOptions() = 0; - - /// @brief . - /// - /// Allows for setting the log mask once diag logging has started - /// - /// @return True if the level was set successfully, false if a failure occurred. - virtual bool setDiagLogMask(const std::string& mask) = 0; - - /// @brief . - /// - /// Allows for setting the log mask once diag logging has started - /// - /// @return True if the level was set successfully, false if a failure occurred. - virtual bool setDiagLogMask(const zdl::DlSystem::String& mask) = 0; - - /// @brief . - /// - /// Enables logging for zdl components. - /// - /// Logging should be started prior to the instantiation of zdl components - /// to ensure all events are captured. - /// - /// @return False if diagnostic logging could not be started. - virtual bool start(void) = 0; - - /// @brief Disables logging for zdl components. - virtual bool stop(void) = 0; - - virtual ~IDiagLog() {}; -}; - -} // DiagLog namespace -} // zdl namespace - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -#endif diff --git a/third_party/snpe/include/DiagLog/Options.hpp b/third_party/snpe/include/DiagLog/Options.hpp deleted file mode 100644 index 798fa3f124..0000000000 --- a/third_party/snpe/include/DiagLog/Options.hpp +++ /dev/null @@ -1,79 +0,0 @@ -//============================================================================= -// -// Copyright (c) 2015, 2020 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================= -#ifndef __DIAGLOG_OPTIONS_HPP_ -#define __DIAGLOG_OPTIONS_HPP_ - -#include -#include "DlSystem/ZdlExportDefine.hpp" - -namespace zdl -{ -namespace DiagLog -{ -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/// @brief . -/// -/// Options for setting up diagnostic logging for zdl components. -class ZDL_EXPORT Options -{ -public: - Options() : - DiagLogMask(""), - LogFileDirectory("diaglogs"), - LogFileName("DiagLog"), - LogFileRotateCount(20), - LogFileReplace(true) - { - // Solves the empty string problem with multiple std libs - DiagLogMask.reserve(1); - } - - /// @brief . - /// - /// Enables diag logging only on the specified area mask (DNN_RUNTIME=ON | OFF) - std::string DiagLogMask; - - /// @brief . - /// - /// The path to the directory where log files will be written. - /// The path may be relative or absolute. Relative paths are interpreted - /// from the current working directory. - /// Default value is "diaglogs" - std::string LogFileDirectory; - - /// @brief . - /// - //// The name used for log files. If this value is empty then BaseName will be - /// used as the default file name. - /// Default value is "DiagLog" - std::string LogFileName; - - /// @brief . - /// - /// The maximum number of log files to create. If set to 0 no log rotation - /// will be used and the log file name specified will be used each time, overwriting - /// any existing log file that may exist. - /// Default value is 20 - uint32_t LogFileRotateCount; - - /// @brief - /// - /// If the log file already exists, control whether it will be replaced - /// (existing contents truncated), or appended. - /// Default value is true - bool LogFileReplace; -}; -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -} // DiagLog namespace -} // zdl namespace - - -#endif diff --git a/third_party/snpe/include/DlContainer/IDlContainer.hpp b/third_party/snpe/include/DlContainer/IDlContainer.hpp deleted file mode 100644 index 4e29b39bb4..0000000000 --- a/third_party/snpe/include/DlContainer/IDlContainer.hpp +++ /dev/null @@ -1,191 +0,0 @@ -//============================================================================= -// -// Copyright (c) 2015-2020 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================= - -#ifndef ZEROTH_IDNC_CONTAINER_HPP -#define ZEROTH_IDNC_CONTAINER_HPP - -#include -#include -#include -#include -#include - -#include "DlSystem/ZdlExportDefine.hpp" -#include "DlSystem/String.hpp" - -namespace zdl { -namespace DlContainer { - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -class IDlContainer; -class dlc_error; - -/** - * The structure of a record in a DL container. - */ -struct ZDL_EXPORT DlcRecord -{ - /// Name of the record. - std::string name; - /// Byte blob holding the data for the record. - std::vector data; - - DlcRecord(); - DlcRecord( DlcRecord&& other ) - : name(std::move(other.name)) - , data(std::move(other.data)) - {} - DlcRecord(const std::string& new_name) - : name(new_name) - , data() - { - if(name.empty()) - { - name.reserve(1); - } - } - DlcRecord(const DlcRecord&) = delete; -}; - -// The maximum length of any record name. -extern const uint32_t RECORD_NAME_MAX_SIZE; -// The maximum size of the record payload (bytes). -extern const uint32_t RECORD_DATA_MAX_SIZE; -// The maximum number of records in an archive at one time. -extern const uint32_t ARCHIVE_MAX_RECORDS; - -/** - * Represents a container for a neural network model which can - * be used to load the model into the SNPE runtime. - */ -class ZDL_EXPORT IDlContainer -{ -public: - /** - * Initializes a container from a container archive file. - * - * @param[in] filename Container archive file path. - * - * @return A pointer to the initialized container - */ - static std::unique_ptr - open(const std::string &filename) noexcept; - - /** - * Initializes a container from a container archive file. - * - * @param[in] filename Container archive file path. - * - * @return A pointer to the initialized container - */ - static std::unique_ptr - open(const zdl::DlSystem::String &filename) noexcept; - - /** - * Initializes a container from a byte buffer. - * - * @param[in] buffer Byte buffer holding the contents of an archive - * file. - * - * @return A pointer to the initialized container - */ - static std::unique_ptr - open(const std::vector &buffer) noexcept; - - /** - * Initializes a container from a byte buffer. - * - * @param[in] buffer Byte buffer holding the contents of an archive - * file. - * - * @param[in] size Size of the byte buffer. - * - * @return A pointer to the initialized container - */ - static std::unique_ptr - open(const uint8_t* buffer, const size_t size) noexcept; - - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - - /** - * Get the record catalog for a container. - * - * @param[out] catalog Buffer that will hold the record names on - * return. - */ - virtual void getCatalog(std::set &catalog) const = 0; - - /** - * Get the record catalog for a container. - * - * @param[out] catalog Buffer that will hold the record names on - * return. - */ - virtual void getCatalog(std::set &catalog) const = 0; - - /** - * Get a record from a container by name. - * - * @param[in] name Name of the record to fetch. - * @param[out] record The passed in record will be populated with the - * record data on return. Note that the caller - * will own the data in the record and is - * responsible for freeing it if needed. - */ - virtual void getRecord(const std::string &name, DlcRecord &record) const = 0; - - /** - * Get a record from a container by name. - * - * @param[in] name Name of the record to fetch. - * @param[out] record The passed in record will be populated with the - * record data on return. Note that the caller - * will own the data in the record and is - * responsible for freeing it if needed. - */ - virtual void getRecord(const zdl::DlSystem::String &name, DlcRecord &record) const = 0; - - /** - * Save the container to an archive on disk. This function will save the - * container if the filename is different from the file that it was opened - * from, or if at least one record was modified since the container was - * opened. - * - * It will truncate any existing file at the target path. - * - * @param filename Container archive file path. - * - * @return indication of success/failure - */ - virtual bool save(const std::string &filename) = 0; - - /** - * Save the container to an archive on disk. This function will save the - * container if the filename is different from the file that it was opened - * from, or if at least one record was modified since the container was - * opened. - * - * It will truncate any existing file at the target path. - * - * @param filename Container archive file path. - * - * @return indication of success/failure - */ - virtual bool save (const zdl::DlSystem::String &filename) = 0; - - virtual ~IDlContainer() {} -}; - -} // ns DlContainer -} // ns zdl - - -#endif diff --git a/third_party/snpe/include/DlSystem/DlEnums.hpp b/third_party/snpe/include/DlSystem/DlEnums.hpp deleted file mode 100644 index c9b3ef970a..0000000000 --- a/third_party/snpe/include/DlSystem/DlEnums.hpp +++ /dev/null @@ -1,234 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2014-2021 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== - -#ifndef _DL_ENUMS_HPP_ -#define _DL_ENUMS_HPP_ - -#include "DlSystem/ZdlExportDefine.hpp" - - -namespace zdl { -namespace DlSystem -{ -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * Enumeration of supported target runtimes. - */ -enum class Runtime_t -{ - /// Run the processing on Snapdragon CPU. - /// Data: float 32bit - /// Math: float 32bit - CPU_FLOAT32 = 0, - - /// Run the processing on the Adreno GPU. - /// Data: float 16bit - /// Math: float 32bit - GPU_FLOAT32_16_HYBRID = 1, - - /// Run the processing on the Hexagon DSP. - /// Data: 8bit fixed point Tensorflow style format - /// Math: 8bit fixed point Tensorflow style format - DSP_FIXED8_TF = 2, - - /// Run the processing on the Adreno GPU. - /// Data: float 16bit - /// Math: float 16bit - GPU_FLOAT16 = 3, - - /// Run the processing on Snapdragon AIX+HVX. - /// Data: 8bit fixed point Tensorflow style format - /// Math: 8bit fixed point Tensorflow style format - AIP_FIXED8_TF = 5, - AIP_FIXED_TF = AIP_FIXED8_TF, - - /// Default legacy enum to retain backward compatibility. - /// CPU = CPU_FLOAT32 - CPU = CPU_FLOAT32, - - /// Default legacy enum to retain backward compatibility. - /// GPU = GPU_FLOAT32_16_HYBRID - GPU = GPU_FLOAT32_16_HYBRID, - - /// Default legacy enum to retain backward compatibility. - /// DSP = DSP_FIXED8_TF - DSP = DSP_FIXED8_TF, - - /// Special value indicating the property is unset. - UNSET = -1 -}; - -/** - * Enumeration of runtime available check options. - */ -enum class RuntimeCheckOption_t -{ - /// Perform standard runtime available check - DEFAULT = 0, - /// Perform standard runtime available check - NORMAL_CHECK = 0, - /// Perform basic runtime available check, may be runtime specific - BASIC_CHECK = 1, - /// Perform unsignedPD runtime available check - UNSIGNEDPD_CHECK = 2, -}; - -/** - * Enumeration of various performance profiles that can be requested. - */ -enum class PerformanceProfile_t -{ - /// Run in a standard mode. - /// This mode will be deprecated in the future and replaced with BALANCED. - DEFAULT = 0, - /// Run in a balanced mode. - BALANCED = 0, - - /// Run in high performance mode - HIGH_PERFORMANCE = 1, - - /// Run in a power sensitive mode, at the expense of performance. - POWER_SAVER = 2, - - /// Use system settings. SNPE makes no calls to any performance related APIs. - SYSTEM_SETTINGS = 3, - - /// Run in sustained high performance mode - SUSTAINED_HIGH_PERFORMANCE = 4, - - /// Run in burst mode - BURST = 5, - - /// Run in lower clock than POWER_SAVER, at the expense of performance. - LOW_POWER_SAVER = 6, - - /// Run in higher clock and provides better performance than POWER_SAVER. - HIGH_POWER_SAVER = 7, - - /// Run in lower balanced mode - LOW_BALANCED = 8, -}; - -/** - * Enumeration of various profilngLevels that can be requested. - */ -enum class ProfilingLevel_t -{ - /// No profiling. - /// Collects no runtime stats in the DiagLog - OFF = 0, - - /// Basic profiling - /// Collects some runtime stats in the DiagLog - BASIC = 1, - - /// Detailed profiling - /// Collects more runtime stats in the DiagLog, including per-layer statistics - /// Performance may be impacted - DETAILED = 2, - - /// Moderate profiling - /// Collects more runtime stats in the DiagLog, no per-layer statistics - MODERATE = 3 -}; - -/** - * Enumeration of various execution priority hints. - */ -enum class ExecutionPriorityHint_t -{ - /// Normal priority - NORMAL = 0, - - /// Higher than normal priority - HIGH = 1, - - /// Lower priority - LOW = 2 - -}; - -/** @} */ /* end_addtogroup c_plus_plus_apis C++*/ - -/** - * Enumeration that lists the supported image encoding formats. - */ -enum class ImageEncoding_t -{ - /// For unknown image type. Also used as a default value for ImageEncoding_t. - UNKNOWN = 0, - - /// The RGB format consists of 3 bytes per pixel: one byte for - /// Red, one for Green, and one for Blue. The byte ordering is - /// endian independent and is always in RGB byte order. - RGB = 1, - - /// The ARGB32 format consists of 4 bytes per pixel: one byte for - /// Red, one for Green, one for Blue, and one for the alpha channel. - /// The alpha channel is ignored. The byte ordering depends on the - /// underlying CPU. For little endian CPUs, the byte order is BGRA. - /// For big endian CPUs, the byte order is ARGB. - ARGB32 = 2, - - /// The RGBA format consists of 4 bytes per pixel: one byte for - /// Red, one for Green, one for Blue, and one for the alpha channel. - /// The alpha channel is ignored. The byte ordering is endian independent - /// and is always in RGBA byte order. - RGBA = 3, - - /// The GRAYSCALE format is for 8-bit grayscale. - GRAYSCALE = 4, - - /// NV21 is the Android version of YUV. The Chrominance is down - /// sampled and has a subsampling ratio of 4:2:0. Note that this - /// image format has 3 channels, but the U and V channels - /// are subsampled. For every four Y pixels there is one U and one V pixel. @newpage - NV21 = 5, - - /// The BGR format consists of 3 bytes per pixel: one byte for - /// Red, one for Green and one for Blue. The byte ordering is - /// endian independent and is always BGR byte order. - BGR = 6 -}; - -/** - * Enumeration that lists the supported LogLevels that can be set by users. - */ -enum class LogLevel_t -{ - /// Enumeration variable to be used by user to set logging level to FATAL. - LOG_FATAL = 0, - - /// Enumeration variable to be used by user to set logging level to ERROR. - LOG_ERROR = 1, - - /// Enumeration variable to be used by user to set logging level to WARN. - LOG_WARN = 2, - - /// Enumeration variable to be used by user to set logging level to INFO. - LOG_INFO = 3, - - /// Enumeration variable to be used by user to set logging level to VERBOSE. - LOG_VERBOSE = 4 -}; - -typedef enum : int -{ - UNSPECIFIED = 0, - FLOATING_POINT_32 = 1, - FLOATING_POINT_16 = 2, - FIXED_POINT_8 = 3, - FIXED_POINT_16 = 4 -} IOBufferDataType_t; - -}} // namespaces end - - -#endif diff --git a/third_party/snpe/include/DlSystem/DlError.hpp b/third_party/snpe/include/DlSystem/DlError.hpp deleted file mode 100644 index 57592f01ba..0000000000 --- a/third_party/snpe/include/DlSystem/DlError.hpp +++ /dev/null @@ -1,259 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2016-2021 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== - -#ifndef _DL_ERROR_HPP_ -#define _DL_ERROR_HPP_ - -#include -#include // numeric_limits - -#include "DlSystem/ZdlExportDefine.hpp" - -namespace zdl { -namespace DlSystem { - -// clang and arm gcc different in how ZDL_EXPORT is used with enum class -#if !defined (__clang__) -enum class ErrorCode : uint32_t ZDL_EXPORT { -#else -enum class ZDL_EXPORT ErrorCode : uint32_t { -#endif // ARM64V8A - NONE = 0, - - // System config errors - SNPE_CONFIG_MISSING_PARAM = 100, - SNPE_CONFIG_INVALID_PARAM = 101, - SNPE_CONFIG_MISSING_FILE = 102, - SNPE_CONFIG_NNCONFIG_NOT_SET = 103, - SNPE_CONFIG_NNCONFIG_INVALID = 104, - SNPE_CONFIG_WRONG_INPUT_NAME = 105, - SNPE_CONFIG_INCORRECT_INPUT_DIMENSIONS = 106, - SNPE_CONFIG_DIMENSIONS_MODIFICATION_NOT_SUPPORTED = 107, - SNPE_CONFIG_BOTH_OUTPUT_LAYER_TENSOR_NAMES_SET = 108, - - SNPE_CONFIG_NNCONFIG_ONLY_TENSOR_SUPPORTED = 120, - SNPE_CONFIG_NNCONFIG_ONLY_USER_BUFFER_SUPPORTED = 121, - - // DlSystem errors - SNPE_DLSYSTEM_MISSING_BUFFER = 200, - SNPE_DLSYSTEM_TENSOR_CAST_FAILED = 201, - SNPE_DLSYSTEM_FIXED_POINT_PARAM_INVALID = 202, - SNPE_DLSYSTEM_SIZE_MISMATCH = 203, - SNPE_DLSYSTEM_NAME_NOT_FOUND = 204, - SNPE_DLSYSTEM_VALUE_MISMATCH = 205, - SNPE_DLSYSTEM_INSERT_FAILED = 206, - SNPE_DLSYSTEM_TENSOR_FILE_READ_FAILED = 207, - SNPE_DLSYSTEM_DIAGLOG_FAILURE = 208, - SNPE_DLSYSTEM_LAYER_NOT_SET = 209, - SNPE_DLSYSTEM_WRONG_NUMBER_INPUT_BUFFERS = 210, - SNPE_DLSYSTEM_RUNTIME_TENSOR_SHAPE_MISMATCH = 211, - SNPE_DLSYSTEM_TENSOR_MISSING = 212, - SNPE_DLSYSTEM_TENSOR_ITERATION_UNSUPPORTED = 213, - SNPE_DLSYSTEM_BUFFER_MANAGER_MISSING = 214, - SNPE_DLSYSTEM_RUNTIME_BUFFER_SOURCE_UNSUPPORTED = 215, - SNPE_DLSYSTEM_BUFFER_CAST_FAILED = 216, - SNPE_DLSYSTEM_WRONG_TRANSITION_TYPE = 217, - SNPE_DLSYSTEM_LAYER_ALREADY_REGISTERED = 218, - SNPE_DLSYSTEM_TENSOR_DIM_INVALID = 219, - - SNPE_DLSYSTEM_BUFFERENCODING_UNKNOWN = 240, - SNPE_DLSYSTEM_BUFFER_INVALID_PARAM = 241, - - // DlContainer errors - SNPE_DLCONTAINER_MODEL_PARSING_FAILED = 300, - SNPE_DLCONTAINER_UNKNOWN_LAYER_CODE = 301, - SNPE_DLCONTAINER_MISSING_LAYER_PARAM = 302, - SNPE_DLCONTAINER_LAYER_PARAM_NOT_SUPPORTED = 303, - SNPE_DLCONTAINER_LAYER_PARAM_INVALID = 304, - SNPE_DLCONTAINER_TENSOR_DATA_MISSING = 305, - SNPE_DLCONTAINER_MODEL_LOAD_FAILED = 306, - SNPE_DLCONTAINER_MISSING_RECORDS = 307, - SNPE_DLCONTAINER_INVALID_RECORD = 308, - SNPE_DLCONTAINER_WRITE_FAILURE = 309, - SNPE_DLCONTAINER_READ_FAILURE = 310, - SNPE_DLCONTAINER_BAD_CONTAINER = 311, - SNPE_DLCONTAINER_BAD_DNN_FORMAT_VERSION = 312, - SNPE_DLCONTAINER_UNKNOWN_AXIS_ANNOTATION = 313, - SNPE_DLCONTAINER_UNKNOWN_SHUFFLE_TYPE = 314, - SNPE_DLCONTAINER_TEMP_FILE_FAILURE = 315, - - // Network errors - SNPE_NETWORK_EMPTY_NETWORK = 400, - SNPE_NETWORK_CREATION_FAILED = 401, - SNPE_NETWORK_PARTITION_FAILED = 402, - SNPE_NETWORK_NO_OUTPUT_DEFINED = 403, - SNPE_NETWORK_MISMATCH_BETWEEN_NAMES_AND_DIMS = 404, - SNPE_NETWORK_MISSING_INPUT_NAMES = 405, - SNPE_NETWORK_MISSING_OUTPUT_NAMES = 406, - SNPE_NETWORK_EXECUTION_FAILED = 407, - - // Host runtime errors - SNPE_HOST_RUNTIME_TARGET_UNAVAILABLE = 500, - - // CPU runtime errors - SNPE_CPU_LAYER_NOT_SUPPORTED = 600, - SNPE_CPU_LAYER_PARAM_NOT_SUPPORTED = 601, - SNPE_CPU_LAYER_PARAM_INVALID = 602, - SNPE_CPU_LAYER_PARAM_COMBINATION_INVALID = 603, - SNPE_CPU_BUFFER_NOT_FOUND = 604, - SNPE_CPU_NETWORK_NOT_SUPPORTED = 605, - SNPE_CPU_UDO_OPERATION_FAILED = 606, - - // CPU fixed-point runtime errors - SNPE_CPU_FXP_LAYER_NOT_SUPPORTED = 700, - SNPE_CPU_FXP_LAYER_PARAM_NOT_SUPPORTED = 701, - SNPE_CPU_FXP_LAYER_PARAM_INVALID = 702, - - // GPU runtime errors - SNPE_GPU_LAYER_NOT_SUPPORTED = 800, - SNPE_GPU_LAYER_PARAM_NOT_SUPPORTED = 801, - SNPE_GPU_LAYER_PARAM_INVALID = 802, - SNPE_GPU_LAYER_PARAM_COMBINATION_INVALID = 803, - SNPE_GPU_KERNEL_COMPILATION_FAILED = 804, - SNPE_GPU_CONTEXT_NOT_SET = 805, - SNPE_GPU_KERNEL_NOT_SET = 806, - SNPE_GPU_KERNEL_PARAM_INVALID = 807, - SNPE_GPU_OPENCL_CHECK_FAILED = 808, - SNPE_GPU_OPENCL_FUNCTION_ERROR = 809, - SNPE_GPU_BUFFER_NOT_FOUND = 810, - SNPE_GPU_TENSOR_DIM_INVALID = 811, - SNPE_GPU_MEMORY_FLAGS_INVALID = 812, - SNPE_GPU_UNEXPECTED_NUMBER_OF_IO = 813, - SNPE_GPU_LAYER_PROXY_ERROR = 814, - SNPE_GPU_BUFFER_IN_USE = 815, - SNPE_GPU_BUFFER_MODIFICATION_ERROR = 816, - SNPE_GPU_DATA_ARRANGEMENT_INVALID = 817, - SNPE_GPU_UDO_OPERATION_FAILED = 818, - // DSP runtime errors - SNPE_DSP_LAYER_NOT_SUPPORTED = 900, - SNPE_DSP_LAYER_PARAM_NOT_SUPPORTED = 901, - SNPE_DSP_LAYER_PARAM_INVALID = 902, - SNPE_DSP_LAYER_PARAM_COMBINATION_INVALID = 903, - SNPE_DSP_STUB_NOT_PRESENT = 904, - SNPE_DSP_LAYER_NAME_TRUNCATED = 905, - SNPE_DSP_LAYER_INPUT_BUFFER_NAME_TRUNCATED = 906, - SNPE_DSP_LAYER_OUTPUT_BUFFER_NAME_TRUNCATED = 907, - SNPE_DSP_RUNTIME_COMMUNICATION_ERROR = 908, - SNPE_DSP_RUNTIME_INVALID_PARAM_ERROR = 909, - SNPE_DSP_RUNTIME_SYSTEM_ERROR = 910, - SNPE_DSP_RUNTIME_CRASHED_ERROR = 911, - SNPE_DSP_BUFFER_SIZE_ERROR = 912, - SNPE_DSP_UDO_EXECUTE_ERROR = 913, - SNPE_DSP_UDO_LIB_NOT_REGISTERED_ERROR = 914, - SNPE_DSP_UDO_INVALID_QUANTIZATION_TYPE_ERROR = 915, - SNPE_DSP_RUNTIME_INVALID_RPC_DRIVER = 916, - SNPE_DSP_RUNTIME_RPC_PERMISSION_ERROR = 917, - SNPE_DSP_RUNTIME_DSP_FILE_OPEN_ERROR = 918, - - // Model validataion errors - SNPE_MODEL_VALIDATION_LAYER_NOT_SUPPORTED = 1000, - SNPE_MODEL_VALIDATION_LAYER_PARAM_NOT_SUPPORTED = 1001, - SNPE_MODEL_VALIDATION_LAYER_PARAM_INVALID = 1002, - SNPE_MODEL_VALIDATION_LAYER_PARAM_MISSING = 1003, - SNPE_MODEL_VALIDATION_LAYER_PARAM_COMBINATION_INVALID = 1004, - SNPE_MODEL_VALIDATION_LAYER_ORDERING_INVALID = 1005, - SNPE_MODEL_VALIDATION_INVALID_CONSTRAINT = 1006, - SNPE_MODEL_VALIDATION_MISSING_BUFFER = 1007, - SNPE_MODEL_VALIDATION_BUFFER_REUSE_NOT_SUPPORTED = 1008, - SNPE_MODEL_VALIDATION_LAYER_COULD_NOT_BE_ASSIGNED = 1009, - SNPE_MODEL_VALIDATION_UDO_LAYER_FAILED = 1010, - - // UDL errors - SNPE_UDL_LAYER_EMPTY_UDL_NETWORK = 1100, - SNPE_UDL_LAYER_PARAM_INVALID = 1101, - SNPE_UDL_LAYER_INSTANCE_MISSING = 1102, - SNPE_UDL_LAYER_SETUP_FAILED = 1103, - SNPE_UDL_EXECUTE_FAILED = 1104, - SNPE_UDL_BUNDLE_INVALID = 1105, - SNPE_UDO_REGISTRATION_FAILED = 1106, - SNPE_UDO_GET_PACKAGE_FAILED = 1107, - SNPE_UDO_GET_IMPLEMENTATION_FAILED = 1108, - - // Dependent library errors - SNPE_STD_LIBRARY_ERROR = 1200, - - // Unknown exception (catch (...)), Has no component attached to this - SNPE_UNKNOWN_EXCEPTION = 1210, - - // Storage Errors - SNPE_STORAGE_INVALID_KERNEL_REPO = 1300, - - // AIP runtime errors - SNPE_AIP_LAYER_NOT_SUPPORTED = 1400, - SNPE_AIP_LAYER_PARAM_NOT_SUPPORTED = 1401, - SNPE_AIP_LAYER_PARAM_INVALID = 1402, - SNPE_AIP_LAYER_PARAM_COMBINATION_INVALID = 1403, - SNPE_AIP_STUB_NOT_PRESENT = 1404, - SNPE_AIP_LAYER_NAME_TRUNCATED = 1405, - SNPE_AIP_LAYER_INPUT_BUFFER_NAME_TRUNCATED = 1406, - SNPE_AIP_LAYER_OUTPUT_BUFFER_NAME_TRUNCATED = 1407, - SNPE_AIP_RUNTIME_COMMUNICATION_ERROR = 1408, - SNPE_AIP_RUNTIME_INVALID_PARAM_ERROR = 1409, - SNPE_AIP_RUNTIME_SYSTEM_ERROR = 1410, - SNPE_AIP_RUNTIME_TENSOR_MISSING = 1411, - SNPE_AIP_RUNTIME_TENSOR_SHAPE_MISMATCH = 1412, - SNPE_AIP_RUNTIME_BAD_AIX_RECORD = 1413, - - // DlCaching errors - SNPE_DLCACHING_INVALID_METADATA = 1500, - SNPE_DLCACHING_INVALID_INITBLOB = 1501, - - // Infrastructure Errors - SNPE_INFRA_CLUSTERMGR_INSTANCE_INVALID = 1600, - SNPE_INFRA_CLUSTERMGR_EXECUTE_SYNC_FAILED = 1601, - - // Memory Errors - SNPE_MEMORY_CORRUPTION_ERROR = 1700 - -}; - - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * Returns the error code of the last error encountered. - * - * @return The error code. - * - * @note The returned error code is significant only when the return - * value of the call indicated an error. - */ -ZDL_EXPORT ErrorCode getLastErrorCode(); - -/** - * Returns the error string of the last error encountered. - * - * @return The error string. - * - * @note The returned error string is significant only when the return - * value of the call indicated an error. - */ -ZDL_EXPORT const char* getLastErrorString(); - -/** - * Returns the info string of the last error encountered. - */ -ZDL_EXPORT const char* getLastInfoString(); - -/** - * Returns the uint32_t representation of the error code enum. - * - * @param[in] code The error code to be converted. - * - * @return uint32_t representation of the error code. - */ -ZDL_EXPORT uint32_t enumToUInt32(zdl::DlSystem::ErrorCode code); - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -} // DlSystem -} // zdl - -#endif // _DL_ERROR_HPP_ - diff --git a/third_party/snpe/include/DlSystem/DlOptional.hpp b/third_party/snpe/include/DlSystem/DlOptional.hpp deleted file mode 100644 index 4f83e6b4e4..0000000000 --- a/third_party/snpe/include/DlSystem/DlOptional.hpp +++ /dev/null @@ -1,225 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2016, 2020 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== - -#ifndef _DL_SYSTEM_OPTIONAL_HPP_ -#define _DL_SYSTEM_OPTIONAL_HPP_ - -#include -#include -#include - -#include "DlSystem/ZdlExportDefine.hpp" - -namespace zdl { -namespace DlSystem { - -template - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * @brief . - * - * Class to manage a value that may or may not exist. The boolean value - * of the Optional class is true if the object contains a value and false - * if it does not contain a value. - * - * The class must be evaluated and confirmed as true (containing a value) - * before being dereferenced. - */ -class ZDL_EXPORT Optional final { -public: - enum class LIFECYCLE { - NONE = 0, - REFERENCE_OWNED = 1, - POINTER_OWNED = 2, - POINTER_NOT_OWNED = 3 - }; - - struct ReferenceCount { - size_t count = 0; - - void increment() { count++; } - - size_t decrement() { - if (count > 0) { - count--; - } - return count; - } - }; - - using U = typename std::remove_pointer::type; - - /** - * The default constructor is set to not have any value, and is - * therefore evaluated as false. - */ - // Do not explicit it so we can return {} - Optional() { - m_Type = LIFECYCLE::NONE; - } - - /** - * Construct an Optional class using an object. - * @param[in] Reference to an object v - * @param[out] Optional instance of object v - */ - template - Optional (const T& v, typename std::enable_if::value>::type* = 0) - : m_Type(LIFECYCLE::REFERENCE_OWNED) { - try { - m_StoragePtr = new T(v); - } catch (...) { - m_StoragePtr = nullptr; - m_Type = LIFECYCLE::NONE; - } - } - - template - Optional(U* v, LIFECYCLE type, typename std::enable_if::value>::type* = 0) - : m_Type(type) { - switch (m_Type) { - case LIFECYCLE::POINTER_OWNED: - m_StoragePtr = v; - m_Count = new ReferenceCount(); - m_Count->increment(); - break; - case LIFECYCLE::POINTER_NOT_OWNED: - m_StoragePtr = v; - break; - case LIFECYCLE::REFERENCE_OWNED: - throw std::bad_exception(); - case LIFECYCLE::NONE: - break; - } - } - - Optional(const Optional &other) : m_Type(other.m_Type), m_Count(other.m_Count) { - if (isReference()) { - m_StoragePtr = new U(*other.m_StoragePtr); - } else if (isPointer()) { - m_StoragePtr = other.m_StoragePtr; - if (isOwned()) { - m_Count->increment(); - } - } - } - - Optional& operator=(const Optional& other) noexcept { - Optional tmp(other); - swap(std::move(tmp)); - return *this; - } - - Optional(Optional&& other) noexcept { - swap(std::move(other)); - } - - Optional& operator=(Optional&& other) noexcept { - swap(std::move(other)); - return *this; - } - - ~Optional() { - if (isOwned()) { - if (isReference() || (isPointer() && m_Count->decrement() == 0)) { - delete m_StoragePtr; - delete m_Count; - } - } - } - - /** - * Boolean value of Optional class is only true when there exists a value. - */ - operator bool() const noexcept { return isValid(); } - - bool operator!() const noexcept { return !isValid(); } - - /** - * Get reference of Optional object - * @warning User must validate Optional has value before. - */ - const T& operator*() { return this->GetReference(); } - - /** - * Get reference of Optional object - * @warning User must validate Optional has value before. - */ - const T& operator*() const { return this->GetReference(); } - - operator T&() { return this->GetReference(); } - - T operator->() { - T self = this->GetReference(); - return self; - } -private: - void swap(Optional&& other) { - m_Type = other.m_Type; - m_StoragePtr = other.m_StoragePtr; - m_Count = other.m_Count; - - other.m_Type = LIFECYCLE::NONE; - other.m_StoragePtr = nullptr; - other.m_Count = nullptr; - } - - template - typename std::enable_if::value, const Q&>::type GetReference() const noexcept { - if (!isReference()) std::terminate(); - return *static_cast(m_StoragePtr); - } - - template - typename std::enable_if::value, const Q&>::type GetReference() const noexcept { - if (!isPointer()) std::terminate(); - return static_cast(m_StoragePtr); - } - - template - typename std::enable_if::value, Q&>::type GetReference() noexcept { - if (!isReference()) std::terminate(); - return *m_StoragePtr; - } - - template - typename std::enable_if::value, Q&>::type GetReference() noexcept { - if (!isPointer()) std::terminate(); - return m_StoragePtr; - } - - bool isPointer() const { - return m_Type == LIFECYCLE::POINTER_OWNED || m_Type == LIFECYCLE::POINTER_NOT_OWNED; - } - - bool isOwned() const { - return m_Type == LIFECYCLE::REFERENCE_OWNED || m_Type == LIFECYCLE::POINTER_OWNED; - } - - bool isReference() const { - return m_Type == LIFECYCLE::REFERENCE_OWNED; - } - - bool isValid() const { - return m_Type != LIFECYCLE::NONE; - } - - U* m_StoragePtr = nullptr; - LIFECYCLE m_Type; - ReferenceCount *m_Count = nullptr; -}; - -} // ns DlSystem -} // ns zdl - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -#endif // _DL_SYSTEM_OPTIONAL_HPP_ diff --git a/third_party/snpe/include/DlSystem/DlVersion.hpp b/third_party/snpe/include/DlSystem/DlVersion.hpp deleted file mode 100644 index beb8d75f21..0000000000 --- a/third_party/snpe/include/DlSystem/DlVersion.hpp +++ /dev/null @@ -1,78 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2014-2015 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== - - -#ifndef _DL_VERSION_HPP_ -#define _DL_VERSION_HPP_ - -#include "ZdlExportDefine.hpp" -#include -#include -#include "DlSystem/String.hpp" - - -namespace zdl { -namespace DlSystem -{ - class Version_t; -}} - - -namespace zdl { namespace DlSystem -{ -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * A class that contains the different portions of a version number. - */ -class ZDL_EXPORT Version_t -{ -public: - /// Holds the major version number. Changes in this value indicate - /// major changes that break backward compatibility. - int32_t Major; - - /// Holds the minor version number. Changes in this value indicate - /// minor changes made to library that are backwards compatible - /// (such as additions to the interface). - int32_t Minor; - - /// Holds the teeny version number. Changes in this value indicate - /// changes such as bug fixes and patches made to the library that - /// do not affect the interface. - int32_t Teeny; - - /// This string holds information about the build version. - /// - std::string Build; - - static zdl::DlSystem::Version_t fromString(const std::string &stringValue); - - static zdl::DlSystem::Version_t fromString(const zdl::DlSystem::String &stringValue); - - /** - * @brief Returns a string in the form Major.Minor.Teeny.Build - * - * @return A formatted string holding the version information. - */ - const std::string toString() const; - - /** - * @brief Returns a string in the form Major.Minor.Teeny.Build - * - * @return A formatted string holding the version information. - */ - const zdl::DlSystem::String asString() const; -}; - -}} - -/** @} */ /* end_addtogroup c_plus_plus_apis */ - -#endif diff --git a/third_party/snpe/include/DlSystem/IBufferAttributes.hpp b/third_party/snpe/include/DlSystem/IBufferAttributes.hpp deleted file mode 100644 index f893e0a237..0000000000 --- a/third_party/snpe/include/DlSystem/IBufferAttributes.hpp +++ /dev/null @@ -1,86 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2017-2019 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== - -#ifndef _IBUFFER_ATTRIBUTES_HPP -#define _IBUFFER_ATTRIBUTES_HPP -#include "IUserBuffer.hpp" -#include "TensorShape.hpp" -#include "ZdlExportDefine.hpp" - -namespace zdl { - namespace DlSystem { - class UserBufferEncoding; - } -} - -namespace zdl { -namespace DlSystem { - -/** - * @brief IBufferAttributes returns a buffer's dimension and alignment - * requirements, along with info on its encoding type - */ -class ZDL_EXPORT IBufferAttributes { -public: - - /** - * @brief Gets the buffer's element size, in bytes - * - * This can be used to compute the memory size required - * to back this buffer. - * - * @return Element size, in bytes - */ - virtual size_t getElementSize() const noexcept = 0; - - /** - * @brief Gets the element's encoding type - * - * @return encoding type - */ - virtual zdl::DlSystem::UserBufferEncoding::ElementType_t getEncodingType() const noexcept = 0; - - /** - * @brief Gets the number of elements in each dimension - * - * @return Dimension size, in terms of number of elements - */ - virtual const TensorShape getDims() const noexcept = 0; - - /** - * @brief Gets the alignment requirement of each dimension - * - * Alignment per each dimension is expressed as an multiple, for - * example, if one particular dimension can accept multiples of 8, - * the alignment will be 8. - * - * @return Alignment in each dimension, in terms of multiple of - * number of elements - */ - virtual const TensorShape getAlignments() const noexcept = 0; - - /** - * @brief Gets the buffer encoding returned from the network responsible - * for generating this buffer. Depending on the encoding type, this will - * be an instance of an encoding type specific derived class. - * - * @return Derived user buffer encoding object. - */ - virtual zdl::DlSystem::UserBufferEncoding* getEncoding() const noexcept = 0; - - virtual ~IBufferAttributes() {} -}; - - - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -} -} - -#endif diff --git a/third_party/snpe/include/DlSystem/IOBufferDataTypeMap.hpp b/third_party/snpe/include/DlSystem/IOBufferDataTypeMap.hpp deleted file mode 100644 index ac33c84af8..0000000000 --- a/third_party/snpe/include/DlSystem/IOBufferDataTypeMap.hpp +++ /dev/null @@ -1,127 +0,0 @@ -//============================================================================= -// -// Copyright (c) 2021-2022 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================= - - -#ifndef DL_SYSTEM_IOBUFFER_DATATYPE_MAP_HPP -#define DL_SYSTEM_IOBUFFER_DATATYPE_MAP_HPP - -#include -#include -#include "DlSystem/DlEnums.hpp" - -namespace DlSystem -{ - // Forward declaration of IOBufferDataTypeMapImpl implementation. - class IOBufferDataTypeMapImpl; -} - -namespace zdl -{ -namespace DlSystem -{ -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * @brief . - * - * The IoBufferDataTypeMap class definition - */ -class ZDL_EXPORT IOBufferDataTypeMap final -{ -public: - - /** - * @brief . - * - * Creates a new Buffer Data type map - * - */ - IOBufferDataTypeMap(); - - /** - * @brief Adds a name and the corresponding buffer data type - * to the map - * - * @param[name] name The name of the buffer - * @param[bufferDataType] buffer Data Type of the buffer - * - * @note If a buffer with the same name already exists, no new - * buffer is added. - */ - void add(const char* name, zdl::DlSystem::IOBufferDataType_t bufferDataType); - - /** - * @brief Removes a buffer name from the map - * - * @param[name] name The name of the buffer - * - */ - void remove(const char* name); - - /** - * @brief Returns the type of the named buffer - * - * @param[name] name The name of the buffer - * - * @return The type of the buffer, or UNSPECIFIED if the buffer does not exist - * - */ - zdl::DlSystem::IOBufferDataType_t getBufferDataType(const char* name); - - /** - * @brief Returns the type of the first buffer - * - * @return The type of the first buffer, or UNSPECIFIED if the map is empty. - * - */ - zdl::DlSystem::IOBufferDataType_t getBufferDataType(); - - /** - * @brief Returns the size of the buffer type map. - * - * @return The size of the map - * - */ - size_t size(); - - /** - * @brief Checks the existence of the named buffer in the map - * - * @return True if the named buffer exists, false otherwise. - * - */ - bool find(const char* name); - - /** - * @brief Resets the map - * - */ - void clear(); - - /** - * @brief Checks whether the map is empty - * - * @return True if the map is empty, false otherwise. - * - */ - bool empty(); - - /** - * @brief Destroys the map - * - */ - ~IOBufferDataTypeMap(); - -private: - std::shared_ptr<::DlSystem::IOBufferDataTypeMapImpl> m_IOBufferDataTypeMapImpl; -}; -} - -} -#endif diff --git a/third_party/snpe/include/DlSystem/ITensor.hpp b/third_party/snpe/include/DlSystem/ITensor.hpp deleted file mode 100644 index 2f006c857f..0000000000 --- a/third_party/snpe/include/DlSystem/ITensor.hpp +++ /dev/null @@ -1,146 +0,0 @@ -//============================================================================= -// -// Copyright (c) 2015-2020 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================= - -#ifndef _ITENSOR_HPP_ -#define _ITENSOR_HPP_ - -#include "ITensorItr.hpp" -#include "ITensorItrImpl.hpp" -#include "TensorShape.hpp" -#include "ZdlExportDefine.hpp" -#include -#include -#include - -namespace zdl { -namespace DlSystem -{ - class ITensor; -}} - -namespace zdl { namespace DlSystem -{ -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * Represents a tensor which holds n-dimensional data. It is important to - * understand how the tensor data is represented in memory - * relative to the tensor dimensions. Tensors store data in - * memory in row-major order (i.e. the last tensor dimension is - * the fastest varying one). For example, if you have a two - * dimensional tensor with 3 rows and 2 columns (i.e. the tensor - * dimensions are 3,2 as returned in tensor dimension vectors) - * with the following data in terms rows and columns: - * - * | 1 2 |
- * | 3 4 |
- * | 5 6 |
- * - * This data would be stored in memory as 1,2,3,4,5,6. - */ -class ZDL_EXPORT ITensor -{ -public: - - typedef zdl::DlSystem::ITensorItr iterator; - typedef zdl::DlSystem::ITensorItr const_iterator; - - virtual ~ITensor() {} - - /** - * Returns a tensor iterator pointing to the beginning - * of the data in the tensor. - * - * @return A tensor iterator that points to the first data - * element in the tensor. - */ - virtual iterator begin() = 0; - - /** - * Returns the const version of a tensor iterator - * pointing to the beginning of the data in the tensor. - * - * @return A tensor const iterator that points to the first data - * element in the tensor. - */ - virtual const_iterator cbegin() const = 0; - - /** - * Returns a tensor iterator pointing to the end of the - * data in the tensor. This tensor should not be - * dereferenced. - * - * @return A tensor iterator that points to the end of the data - * (one past the last element) in the tensor. - */ - virtual iterator end() = 0; - - /** - * Returns the const version of a tensor iterator - * pointing to the end of the data in the tensor. This - * tensor should not be dereferenced. - * - * @return A tensor const iterator that points to the end of the - * data (one past the last element) in the tensor. - */ - virtual const_iterator cend() const = 0; - - /** - * @brief Gets the shape of this tensor. - * - * The last element of the vector represents the fastest varying - * dimension and the zeroth element represents the slowest - * varying dimension, etc. - * - * @return A shape class holding the tensor dimensions. - */ - virtual TensorShape getShape() const = 0; - - /** - * Returns the element size of the data in the tensor - * (discounting strides). This is how big a buffer would - * need to be to hold the tensor data contiguously in - * memory. - * - * @return The size of the tensor (in elements). - */ - virtual size_t getSize() const = 0; - - /** - * @brief Serializes the tensor to an output stream. - * - * @param[in] output The output stream to which to write the tensor - * - * @throw std::runtime_error If the stream is ever in a bad - * state before the tensor is fully serialized. - */ - virtual void serialize(std::ostream &output) const = 0; - - friend iterator; - friend const_iterator; - - virtual bool isQuantized() {return false;} - virtual float GetDelta() {return NAN;}; - virtual float GetOffset() {return NAN;}; - -protected: - - /** - * Returns the tensor iterator implementation. - * - * @return A pointer to the tensor iterator implementation. - */ - virtual std::unique_ptr<::DlSystem::ITensorItrImpl> getItrImpl() const = 0; -}; - -}} - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -#endif diff --git a/third_party/snpe/include/DlSystem/ITensorFactory.hpp b/third_party/snpe/include/DlSystem/ITensorFactory.hpp deleted file mode 100644 index 57d2c8ea99..0000000000 --- a/third_party/snpe/include/DlSystem/ITensorFactory.hpp +++ /dev/null @@ -1,92 +0,0 @@ -//============================================================================= -// -// Copyright (c) 2015-2016 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================= - -#ifndef _ITENSOR_FACTORY_HPP -#define _ITENSOR_FACTORY_HPP - -#include "ITensor.hpp" -#include "TensorShape.hpp" -#include "ZdlExportDefine.hpp" -#include - -namespace zdl { - namespace DlSystem - { - class ITensor; - class TensorShape; - } -} - -namespace zdl { namespace DlSystem -{ - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * Factory interface class to create ITensor objects. - */ -class ZDL_EXPORT ITensorFactory -{ -public: - virtual ~ITensorFactory() = default; - - /** - * Creates a new ITensor with uninitialized data. - * - * The strides for the tensor will match the tensor dimensions - * (i.e., the tensor data is contiguous in memory). - * - * @param[in] shape The dimensions for the tensor in which the last - * element of the vector represents the fastest varying - * dimension and the zeroth element represents the slowest - * varying, etc. - * - * @return A pointer to the created tensor or nullptr if creating failed. - */ - virtual std::unique_ptr - createTensor(const TensorShape &shape) noexcept = 0; - - /** - * Creates a new ITensor by loading it from a file. - * - * @param[in] input The input stream from which to read the tensor - * data. - * - * @return A pointer to the created tensor or nullptr if creating failed. - * - */ - virtual std::unique_ptr createTensor(std::istream &input) noexcept = 0; - - /** - * Create a new ITensor with specific data. - * (i.e. the tensor data is contiguous in memory). This tensor is - * primarily used to create a tensor where tensor size can't be - * computed directly from dimension. One such example is - * NV21-formatted image, or any YUV formatted image - * - * @param[in] shape The dimensions for the tensor in which the last - * element of the vector represents the fastest varying - * dimension and the zeroth element represents the slowest - * varying, etc. - * - * @param[in] data The actual data with which the Tensor object is filled. - * - * @param[in] dataSize The size of data - * - * @return A pointer to the created tensor - */ - virtual std::unique_ptr - createTensor(const TensorShape &shape, const unsigned char *data, size_t dataSize) noexcept = 0; -}; - -}} - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -#endif diff --git a/third_party/snpe/include/DlSystem/ITensorItr.hpp b/third_party/snpe/include/DlSystem/ITensorItr.hpp deleted file mode 100644 index 4ce12a9f11..0000000000 --- a/third_party/snpe/include/DlSystem/ITensorItr.hpp +++ /dev/null @@ -1,182 +0,0 @@ -//============================================================================= -// -// Copyright (c) 2015 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================= - -#ifndef _ITENSOR_ITR_HPP_ -#define _ITENSOR_ITR_HPP_ - -#include "ZdlExportDefine.hpp" -#include "ITensorItrImpl.hpp" - -#include -#include -#include - -namespace zdl { -namespace DlSystem -{ - template class ITensorItr; - class ITensor; - void ZDL_EXPORT fill(ITensorItr first, ITensorItr end, float val); - template OutItr ZDL_EXPORT copy(InItr first, InItr last, OutItr result) - { - return std::copy(first, last, result); - } -}} -namespace DlSystem -{ - class ITensorItrImpl; -} - -namespace zdl { namespace DlSystem -{ - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * A bidirectional iterator (with limited random access - * capabilities) for the zdl::DlSystem::ITensor class. - * - * This is a standard bidrectional iterator and is compatible - * with standard algorithm functions that operate on bidirectional - * access iterators (e.g., std::copy, std::fill, etc.). It uses a - * template parameter to create const and non-const iterators - * from the same code. Iterators are easiest to declare via the - * typedefs iterator and const_iterator in the ITensor class - * (e.g., zdl::DlSystem::ITensor::iterator). - * - * Note that if the tensor the iterator is traversing was - * created with nondefault (i.e., nontrivial) strides, the - * iterator will obey the strides when traversing the tensor - * data. - * - * Also note that nontrivial strides dramatically affect the - * performance of the iterator (on the order of 20x slower). - */ -template -class ZDL_EXPORT ITensorItr : public std::iterator -{ -public: - - typedef typename std::conditional::type VALUE_REF; - - ITensorItr() = delete; - virtual ~ITensorItr() {} - - ITensorItr(std::unique_ptr<::DlSystem::ITensorItrImpl> impl, - bool isTrivial = false, - float* data = nullptr) - : m_Impl(impl->clone()) - , m_IsTrivial(isTrivial) - , m_Data(data) - , m_DataStart(data) {} - - ITensorItr(const ITensorItr& itr) - : m_Impl(itr.m_Impl->clone()), - m_IsTrivial(itr.m_IsTrivial), - m_Data(itr.m_Data), - m_DataStart(itr.m_DataStart) {} - - zdl::DlSystem::ITensorItr& operator=(const ITensorItr& other) - { - if (this == &other) return *this; - m_Impl = std::move(other.m_Impl->clone()); - m_IsTrivial = other.m_IsTrivial; - m_Data = other.m_Data; - m_DataStart = other.m_DataStart; - return *this; - } - - inline zdl::DlSystem::ITensorItr& operator++() - { - if (m_IsTrivial) m_Data++; else m_Impl->increment(); - return *this; - } - inline zdl::DlSystem::ITensorItr operator++(int) - { - ITensorItr tmp(*this); - operator++(); - return tmp; - } - inline zdl::DlSystem::ITensorItr& operator--() - { - if (m_IsTrivial) m_Data--; else m_Impl->decrement(); - return *this; - } - inline zdl::DlSystem::ITensorItr operator--(int) - { - ITensorItr tmp(*this); - operator--(); - return tmp; - } - inline zdl::DlSystem::ITensorItr& operator+=(int rhs) - { - if (m_IsTrivial) m_Data += rhs; else m_Impl->increment(rhs); - return *this; - } - inline friend zdl::DlSystem::ITensorItr operator+(zdl::DlSystem::ITensorItr lhs, int rhs) - { lhs += rhs; return lhs; } - inline zdl::DlSystem::ITensorItr& operator-=(int rhs) - { - if (m_IsTrivial) m_Data -= rhs; else m_Impl->decrement(rhs); - return *this; - } - inline friend zdl::DlSystem::ITensorItr operator-(zdl::DlSystem::ITensorItr lhs, int rhs) - { lhs -= rhs; return lhs; } - - inline size_t operator-(const zdl::DlSystem::ITensorItr& rhs) - { - if (m_IsTrivial) return (m_Data - m_DataStart) - (rhs.m_Data - rhs.m_DataStart); - return m_Impl->getPosition() - rhs.m_Impl->getPosition(); - } - - inline friend bool operator<(const ITensorItr& lhs, const ITensorItr& rhs) - { - if (lhs.m_IsTrivial) return lhs.m_Data < rhs.m_Data; - return lhs.m_Impl->dataPointer() < rhs.m_Impl->dataPointer(); - } - inline friend bool operator>(const ITensorItr& lhs, const ITensorItr& rhs) - { return rhs < lhs; } - inline friend bool operator<=(const ITensorItr& lhs, const ITensorItr& rhs) - { return !(lhs > rhs); } - inline friend bool operator>=(const ITensorItr& lhs, const ITensorItr& rhs) - { return !(lhs < rhs); } - - inline bool operator==(const ITensorItr& rhs) const - { - if (m_IsTrivial) return m_Data == rhs.m_Data; - return m_Impl->dataPointer() == rhs.m_Impl->dataPointer(); - } - inline bool operator!=(const ITensorItr& rhs) const - { return !operator==(rhs); } - - inline VALUE_REF operator[](size_t idx) - { - if (m_IsTrivial) return *(m_DataStart + idx); - return m_Impl->getReferenceAt(idx); - } - inline VALUE_REF operator*() - { if (m_IsTrivial) return *m_Data; else return m_Impl->getReference(); } - inline VALUE_REF operator->() - { return *(*this); } - inline float* dataPointer() const - { if (m_IsTrivial) return m_Data; else return m_Impl->dataPointer(); } - - -protected: - std::unique_ptr<::DlSystem::ITensorItrImpl> m_Impl; - bool m_IsTrivial = false; - float* m_Data = nullptr; - float* m_DataStart = nullptr; -}; - -}} - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -#endif diff --git a/third_party/snpe/include/DlSystem/ITensorItrImpl.hpp b/third_party/snpe/include/DlSystem/ITensorItrImpl.hpp deleted file mode 100644 index 069e7a1d69..0000000000 --- a/third_party/snpe/include/DlSystem/ITensorItrImpl.hpp +++ /dev/null @@ -1,42 +0,0 @@ -//============================================================================= -// -// Copyright (c) 2015-2020 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================= - -#ifndef _ITENSOR_ITR_IMPL_HPP_ -#define _ITENSOR_ITR_IMPL_HPP_ - -#include "ZdlExportDefine.hpp" - -#include -#include - -namespace DlSystem -{ - class ITensorItrImpl; -} - -class ZDL_EXPORT DlSystem::ITensorItrImpl -{ -public: - ITensorItrImpl() {} - virtual ~ITensorItrImpl() {} - - virtual float getValue() const = 0; - virtual float& getReference() = 0; - virtual float& getReferenceAt(size_t idx) = 0; - virtual float* dataPointer() const = 0; - virtual void increment(int incVal = 1) = 0; - virtual void decrement(int decVal = 1) = 0; - virtual size_t getPosition() = 0; - virtual std::unique_ptr clone() = 0; - -private: - ITensorItrImpl& operator=(const ITensorItrImpl& other) = delete; - ITensorItrImpl(const ITensorItrImpl& other) = delete; -}; - -#endif diff --git a/third_party/snpe/include/DlSystem/IUDL.hpp b/third_party/snpe/include/DlSystem/IUDL.hpp deleted file mode 100644 index a171ac7e81..0000000000 --- a/third_party/snpe/include/DlSystem/IUDL.hpp +++ /dev/null @@ -1,105 +0,0 @@ -//============================================================================= -// -// Copyright (c) 2016-2021 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================= - -#ifndef _DL_SYSTEM_IUDL_HPP_ -#define _DL_SYSTEM_IUDL_HPP_ - -#include "ZdlExportDefine.hpp" - -namespace zdl { -namespace DlSystem { - -/** - * NOTE: DEPRECATED, MAY BE REMOVED IN THE FUTURE. - * - * @brief . - * - * Base class user concrete UDL implementation. - * - * All functions are marked as: - * - * - virtual - * - noexcept - * - * User should make sure no exceptions are propagated outside of - * their module. Errors can be communicated via return values. - */ -class ZDL_EXPORT IUDL { -public: - /** - * NOTE: DEPRECATED, MAY BE REMOVED IN THE FUTURE. - * - * @brief . - * - * Destructor - */ - virtual ~IUDL() = default; - - /** - * NOTE: DEPRECATED, MAY BE REMOVED IN THE FUTURE. - * - * @brief Sets up the user's environment. - * This is called by the SNPE framework to allow the user the - * opportunity to setup anything which is needed for running - * user defined layers. - * - * @param cookie User provided opaque data returned by the SNPE - * runtime - * - * @param insz How many elements in input size array - * @param indim Pointer to a buffer that holds input dimension - * array - * @param indimsz Input dimension size array of the buffer - * 'indim'. Corresponds to indim - * - * @param outsz How many elements in output size array - * @param outdim Pointer to a buffer that holds output - * dimension array - * @param outdimsz Output dimension size of the buffer 'oudim'. - * Corresponds to indim - * - * @return true on success, false otherwise - */ - virtual bool setup(void *cookie, - size_t insz, const size_t **indim, const size_t *indimsz, - size_t outsz, const size_t **outdim, const size_t *outdimsz) = 0; - - /** - * NOTE: DEPRECATED, MAY BE REMOVED IN THE FUTURE. - * - * @brief Close the instance. Invoked by the SNPE - * framework to allow the user the opportunity to release any resources - * allocated during setup. - * - * @param cookie - User provided opaque data returned by the SNPE runtime - */ - virtual void close(void *cookie) noexcept = 0; - - /** - * NOTE: DEPRECATED, MAY BE REMOVED IN THE FUTURE. - * - * @brief Execute the user defined layer - * - * @param cookie User provided opaque data returned by the SNPE - * runtime - * - * @param input Const pointer to a float buffer that contains - * the input - * - * @param output Float pointer to a buffer that would hold - * the user defined layer's output. This buffer - * is allocated and owned by SNPE runtime. - */ - virtual bool execute(void *cookie, const float **input, float **output) = 0; -}; - -} // ns DlSystem - -} // ns zdl - -#endif // _DL_SYSTEM_IUDL_HPP_ diff --git a/third_party/snpe/include/DlSystem/IUserBuffer.hpp b/third_party/snpe/include/DlSystem/IUserBuffer.hpp deleted file mode 100644 index ea491a545b..0000000000 --- a/third_party/snpe/include/DlSystem/IUserBuffer.hpp +++ /dev/null @@ -1,358 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2017-2020 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== - -#ifndef _IUSER_BUFFER_HPP -#define _IUSER_BUFFER_HPP - -#include "TensorShape.hpp" -#include "ZdlExportDefine.hpp" -#include - -namespace zdl { -namespace DlSystem { - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - - -/** - * @brief . - * - * A base class buffer encoding type - */ -class ZDL_EXPORT UserBufferEncoding { -public: - - /** - * @brief . - * - * An enum class of all supported element types in a IUserBuffer - */ - enum class ElementType_t - { - /// Unknown element type. - UNKNOWN = 0, - - /// Each element is presented by float. - FLOAT = 1, - - /// Each element is presented by an unsigned int. - UNSIGNED8BIT = 2, - - /// Each element is presented by an 8-bit quantized value. - TF8 = 10, - - /// Each element is presented by an 16-bit quantized value. - TF16 = 11 - }; - - /** - * @brief Retrieves the size of the element, in bytes. - * - * @return Size of the element, in bytes. - */ - virtual size_t getElementSize() const noexcept = 0; - - /** - * @brief Retrieves the element type - * - * @return Element type - */ - ElementType_t getElementType() const noexcept {return m_ElementType;}; - - virtual ~UserBufferEncoding() {} - -protected: - UserBufferEncoding(ElementType_t elementType) : m_ElementType(elementType) {}; -private: - const ElementType_t m_ElementType; -}; - -/** - * @brief . - * - * A base class buffer source type - * - * @note User buffer from CPU support all kinds of runtimes; - * User buffer from GLBUFFER support only GPU runtime. - */ -class ZDL_EXPORT UserBufferSource { -public: - enum class SourceType_t - { - /// Unknown buffer source type. - UNKNOWN = 0, - - /// The network inputs are from CPU buffer. - CPU = 1, - - /// The network inputs are from OpenGL buffer. - GLBUFFER = 2 - }; - - /** - * @brief Retrieves the source type - * - * @return Source type - */ - SourceType_t getSourceType() const noexcept {return m_SourceType;}; - -protected: - UserBufferSource(SourceType_t sourceType): m_SourceType(sourceType) {}; -private: - const SourceType_t m_SourceType; -}; - -/** - * @brief . - * - * An source type where input data is delivered from OpenGL buffer - */ -class ZDL_EXPORT UserBufferSourceGLBuffer : public UserBufferSource{ -public: - UserBufferSourceGLBuffer() : UserBufferSource(SourceType_t::GLBUFFER) {}; -}; - -/** - * @brief . - * - * An encoding type where each element is represented by an unsigned int - */ -class ZDL_EXPORT UserBufferEncodingUnsigned8Bit : public UserBufferEncoding { -public: - UserBufferEncodingUnsigned8Bit() : UserBufferEncoding(ElementType_t::UNSIGNED8BIT) {}; - size_t getElementSize() const noexcept override; - -protected: - UserBufferEncodingUnsigned8Bit(ElementType_t elementType) : UserBufferEncoding(elementType) {}; - -}; - -/** - * @brief . - * - * An encoding type where each element is represented by a float - */ -class ZDL_EXPORT UserBufferEncodingFloat : public UserBufferEncoding { -public: - UserBufferEncodingFloat() : UserBufferEncoding(ElementType_t::FLOAT) {}; - size_t getElementSize() const noexcept override; - -}; - -/** - * @brief . - * - * An encoding type where each element is represented by tf8, which is an - * 8-bit quantizd value, which has an exact representation of 0.0 - */ -class ZDL_EXPORT UserBufferEncodingTfN : public UserBufferEncoding { -public: - UserBufferEncodingTfN() = delete; - UserBufferEncodingTfN(uint64_t stepFor0, float stepSize, uint8_t bWidth=8): - UserBufferEncoding(getTypeFromWidth(bWidth)), - bitWidth(bWidth), - m_StepExactly0(stepFor0), - m_QuantizedStepSize(stepSize){}; - - UserBufferEncodingTfN(const zdl::DlSystem::UserBufferEncoding &ubEncoding) : UserBufferEncoding(ubEncoding.getElementType()){ - const zdl::DlSystem::UserBufferEncodingTfN* ubEncodingTfN - = dynamic_cast (&ubEncoding); - if (ubEncodingTfN) { - m_StepExactly0 = ubEncodingTfN->getStepExactly0(); - m_QuantizedStepSize = ubEncodingTfN->getQuantizedStepSize(); - bitWidth = ubEncodingTfN->bitWidth; - } - } - - size_t getElementSize() const noexcept override; - /** - * @brief Sets the step value that represents 0 - * - * @param[in] stepExactly0 The step value that represents 0 - * - */ - void setStepExactly0(uint64_t stepExactly0) { - m_StepExactly0 = stepExactly0; - } - - /** - * @brief Sets the float value that each step represents - * - * @param[in] quantizedStepSize The float value of each step size - * - */ - void setQuantizedStepSize(const float quantizedStepSize) { - m_QuantizedStepSize = quantizedStepSize; - } - - /** - * @brief Retrieves the step that represents 0.0 - * - * @return Step value - */ - uint64_t getStepExactly0() const { - return m_StepExactly0; - } - - /** - * Calculates the minimum floating point value that - * can be represented with this encoding. - * - * @return Minimum representable floating point value - */ - float getMin() const { - return static_cast(m_QuantizedStepSize * (0 - (double)m_StepExactly0)); - } - - /** - * Calculates the maximum floating point value that - * can be represented with this encoding. - * - * @return Maximum representable floating point value - */ - float getMax() const{ - return static_cast(m_QuantizedStepSize * (pow(2,bitWidth)-1 - (double)m_StepExactly0)); - }; - - /** - * @brief Retrieves the step size - * - * @return Step size - */ - float getQuantizedStepSize() const { - return m_QuantizedStepSize; - } - - ElementType_t getTypeFromWidth(uint8_t width); - - uint8_t bitWidth; -protected: - uint64_t m_StepExactly0; - float m_QuantizedStepSize; -}; - - -class ZDL_EXPORT UserBufferEncodingTf8 : public UserBufferEncodingTfN { -public: - UserBufferEncodingTf8() = delete; - UserBufferEncodingTf8(unsigned char stepFor0, float stepSize) : - UserBufferEncodingTfN(stepFor0, stepSize) {}; - - UserBufferEncodingTf8(const zdl::DlSystem::UserBufferEncoding &ubEncoding) : UserBufferEncodingTfN(ubEncoding){} - -/** - * @brief Sets the step value that represents 0 - * - * @param[in] stepExactly0 The step value that represents 0 - * - */ - - void setStepExactly0(const unsigned char stepExactly0) { - UserBufferEncodingTfN::m_StepExactly0 = stepExactly0; - } - -/** - * @brief Retrieves the step that represents 0.0 - * - * @return Step value - */ - - unsigned char getStepExactly0() const { - return UserBufferEncodingTfN::m_StepExactly0; - } - -}; - - -/** - * @brief UserBuffer contains a pointer and info on how to walk it and interpret its content. - */ -class ZDL_EXPORT IUserBuffer { -public: - virtual ~IUserBuffer() = default; - - /** - * @brief Retrieves the total number of bytes between elements in each dimension if - * the buffer were to be interpreted as a multi-dimensional array. - * - * @return Number of bytes between elements in each dimension. - * e.g. A tightly packed tensor of floats with dimensions [4, 3, 2] would - * return strides of [24, 8, 4]. - */ - virtual const TensorShape& getStrides() const = 0; - - /** - * @brief Retrieves the size of the buffer, in bytes. - * - * @return Size of the underlying buffer, in bytes. - */ - virtual size_t getSize() const = 0; - - /** - * @brief Retrieves the size of the inference data in the buffer, in bytes. - * - * The inference results from a dynamic-sized model may not be exactly the same size - * as the UserBuffer provided to SNPE. This function can be used to get the amount - * of output inference data, which may be less or greater than the size of the UserBuffer. - * - * If the inference results fit in the UserBuffer, getOutputSize() would be less than - * or equal to getSize(). But if the inference results were more than the capacity of - * the provided UserBuffer, the results would be truncated to fit the UserBuffer. But, - * getOutputSize() would be greater than getSize(), which indicates a bigger buffer - * needs to be provided to SNPE to hold all of the inference results. - * - * @return Size required for the buffer to hold all inference results, which can be less - * or more than the size of the buffer, in bytes. - */ - virtual size_t getOutputSize() const = 0; - - /** - * @brief Changes the underlying memory that backs the UserBuffer. - * - * This can be used to avoid creating multiple UserBuffer objects - * when the only thing that differs is the memory location. - * - * @param[in] buffer Pointer to the memory location - * - * @return Whether the set succeeds. - */ - virtual bool setBufferAddress(void *buffer) noexcept = 0; - - /** - * @brief Gets a const reference to the data encoding object of - * the underlying buffer - * - * This is necessary when the UserBuffer is filled by SNPE with - * data types such as TF8, where the caller needs to know the quantization - * parameters in order to interpret the data properly - * - * @return A read-only encoding object - */ - virtual const UserBufferEncoding& getEncoding() const noexcept = 0; - - /** - * @brief Gets a reference to the data encoding object of - * the underlying buffer - * - * This is necessary when the UserBuffer is re-used, and the encoding - * parameters can change. For example, each input can be quantized with - * different step sizes. - * - * @return Data encoding meta-data - */ - virtual UserBufferEncoding& getEncoding() noexcept = 0; - -}; - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -} -} - -#endif diff --git a/third_party/snpe/include/DlSystem/IUserBufferFactory.hpp b/third_party/snpe/include/DlSystem/IUserBufferFactory.hpp deleted file mode 100644 index 59803fbd8f..0000000000 --- a/third_party/snpe/include/DlSystem/IUserBufferFactory.hpp +++ /dev/null @@ -1,81 +0,0 @@ -//============================================================================= -// -// Copyright (c) 2017 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================= - -#ifndef _IUSERBUFFER_FACTORY_HPP -#define _IUSERBUFFER_FACTORY_HPP - -#include "IUserBuffer.hpp" -#include "TensorShape.hpp" -#include "ZdlExportDefine.hpp" -#include "DlEnums.hpp" -namespace zdl { - namespace DlSystem { - class IUserBuffer; - - class TensorShape; - } -} - -namespace zdl { -namespace DlSystem { - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** -* Factory interface class to create IUserBuffer objects. -*/ -class ZDL_EXPORT IUserBufferFactory { -public: - virtual ~IUserBufferFactory() = default; - - /** - * @brief Creates a UserBuffer - * - * @param[in] buffer Pointer to the buffer that the caller supplies - * - * @param[in] bufSize Buffer size, in bytes - * - * @param[in] strides Total number of bytes between elements in each dimension. - * E.g. A tightly packed tensor of floats with dimensions [4, 3, 2] would have strides of [24, 8, 4]. - * - * @param[in] userBufferEncoding Reference to an UserBufferEncoding object - * - * @note Caller has to ensure that memory pointed to by buffer stays accessible - * for the lifetime of the object created - */ - virtual std::unique_ptr - createUserBuffer(void *buffer, size_t bufSize, const zdl::DlSystem::TensorShape &strides, zdl::DlSystem::UserBufferEncoding* userBufferEncoding) noexcept = 0; - - /** - * @brief Creates a UserBuffer - * - * @param[in] buffer Pointer to the buffer that the caller supplies - * - * @param[in] bufSize Buffer size, in bytes - * - * @param[in] strides Total number of bytes between elements in each dimension. - * E.g. A tightly packed tensor of floats with dimensions [4, 3, 2] would have strides of [24, 8, 4]. - * - * @param[in] userBufferEncoding Reference to an UserBufferEncoding object - * - * @param[in] userBufferSource Reference to an UserBufferSource object - * - * @note Caller has to ensure that memory pointed to by buffer stays accessible - * for the lifetime of the object created - */ - virtual std::unique_ptr - createUserBuffer(void *buffer, size_t bufSize, const zdl::DlSystem::TensorShape &strides, zdl::DlSystem::UserBufferEncoding* userBufferEncoding, zdl::DlSystem::UserBufferSource* userBufferSource) noexcept = 0; -}; -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -} -} - - -#endif diff --git a/third_party/snpe/include/DlSystem/PlatformConfig.hpp b/third_party/snpe/include/DlSystem/PlatformConfig.hpp deleted file mode 100644 index c7b85f43c1..0000000000 --- a/third_party/snpe/include/DlSystem/PlatformConfig.hpp +++ /dev/null @@ -1,230 +0,0 @@ -//============================================================================= -// -// Copyright (c) 2017-2018,2021 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================= - -#ifndef _DL_SYSTEM_PLATFORM_CONFIG_HPP_ -#define _DL_SYSTEM_PLATFORM_CONFIG_HPP_ - -#include "DlSystem/ZdlExportDefine.hpp" -#include - -namespace zdl{ -namespace DlSystem -{ - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - - -/** - * @brief . - * - * A structure OpenGL configuration - * - * @note When certain OpenGL context and display are provided to UserGLConfig for using - * GPU buffer as input directly, the user MUST ensure the particular OpenGL - * context and display remain vaild throughout the execution of neural network models. - */ -struct ZDL_EXPORT UserGLConfig -{ - /// Holds user EGL context. - /// - void* userGLContext = nullptr; - - /// Holds user EGL display. - void* userGLDisplay = nullptr; -}; - -/** - * @brief . - * - * A structure Gpu configuration - */ -struct ZDL_EXPORT UserGpuConfig{ - /// Holds user OpenGL configuration. - /// - UserGLConfig userGLConfig; -}; - -/** - * @brief . - * - * A class user platform configuration - */ -class ZDL_EXPORT PlatformConfig -{ -public: - - /** - * @brief . - * - * An enum class of all supported platform types - */ - enum class PlatformType_t - { - /// Unknown platform type. - UNKNOWN = 0, - - /// Snapdragon CPU. - CPU = 1, - - /// Adreno GPU. - GPU = 2, - - /// Hexagon DSP. - DSP = 3 - }; - - /** - * @brief . - * - * A union class user platform configuration information - */ - union PlatformConfigInfo - { - /// Holds user GPU Configuration. - /// - UserGpuConfig userGpuConfig; - - PlatformConfigInfo(){}; - }; - - PlatformConfig() : m_PlatformType(PlatformType_t::UNKNOWN), - m_PlatformOptions("") {}; - - /** - * @brief Retrieves the platform type - * - * @return Platform type - */ - PlatformType_t getPlatformType() const {return m_PlatformType;}; - - /** - * @brief Indicates whther the plaform configuration is valid. - * - * @return True if the platform configuration is valid; false otherwise. - */ - bool isValid() const {return (PlatformType_t::UNKNOWN != m_PlatformType);}; - - /** - * @brief Retrieves the Gpu configuration - * - * @param[out] userGpuConfig The passed in userGpuConfig populated with the Gpu configuration on return. - * - * @return True if Gpu configuration was retrieved; false otherwise. - */ - bool getUserGpuConfig(UserGpuConfig& userGpuConfig) const - { - if(m_PlatformType == PlatformType_t::GPU) - { - userGpuConfig = m_PlatformConfigInfo.userGpuConfig; - return true; - } - else - { - return false; - } - } - - /** - * @brief Sets the Gpu configuration - * - * @param[in] userGpuConfig Gpu Configuration - * - * @return True if Gpu configuration was successfully set; false otherwise. - */ - bool setUserGpuConfig(UserGpuConfig& userGpuConfig) - { - if((userGpuConfig.userGLConfig.userGLContext != nullptr) && (userGpuConfig.userGLConfig.userGLDisplay != nullptr)) - { - switch (m_PlatformType) - { - case PlatformType_t::GPU: - m_PlatformConfigInfo.userGpuConfig = userGpuConfig; - return true; - case PlatformType_t::UNKNOWN: - m_PlatformType = PlatformType_t::GPU; - m_PlatformConfigInfo.userGpuConfig = userGpuConfig; - return true; - default: - return false; - } - } - else - return false; - } - - /** - * @brief Sets the platform options - * - * @param[in] options Options as a string in the form of "keyword:options" - * - * @return True if options are pass validation; otherwise false. If false, the options are not updated. - */ - bool setPlatformOptions(std::string options) { - std::string oldOptions = m_PlatformOptions; - m_PlatformOptions = options; - if (isOptionsValid()) { - return true; - } else { - m_PlatformOptions = oldOptions; - return false; - } - } - - /** - * @brief Indicates whther the plaform configuration is valid. - * - * @return True if the platform configuration is valid; false otherwise. - */ - bool isOptionsValid() const; - - /** - * @brief Gets the platform options - * - * @return Options as a string - */ - std::string getPlatformOptions() const { return m_PlatformOptions; } - - /** - * @brief Sets the platform options - * - * @param[in] optionName Name of platform options" - * @param[in] value Value of specified optionName - * - * @return If true, add "optionName:value" to platform options if optionName don't exist, otherwise update the - * value of specified optionName. - * If false, the platform options will not be changed. - */ - bool setPlatformOptionValue(const std::string& optionName, const std::string& value); - - /** - * @brief Removes the platform options - * - * @param[in] optionName Name of platform options" - * @param[in] value Value of specified optionName - * - * @return If true, removed "optionName:value" to platform options if optionName don't exist, do nothing. - * If false, the platform options will not be changed. - */ - bool removePlatformOptionValue(const std::string& optionName, const std::string& value); - - static void SetIsUserGLBuffer(bool isUserGLBuffer); - static bool GetIsUserGLBuffer(); - -private: - PlatformType_t m_PlatformType; - PlatformConfigInfo m_PlatformConfigInfo; - std::string m_PlatformOptions; - static bool m_IsUserGLBuffer; -}; - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -}} //namespace end - -#endif diff --git a/third_party/snpe/include/DlSystem/RuntimeList.hpp b/third_party/snpe/include/DlSystem/RuntimeList.hpp deleted file mode 100644 index 1088a5b31f..0000000000 --- a/third_party/snpe/include/DlSystem/RuntimeList.hpp +++ /dev/null @@ -1,154 +0,0 @@ -//============================================================================= -// -// Copyright (c) 2019 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================= - -#include "ZdlExportDefine.hpp" -#include "DlSystem/DlEnums.hpp" -#include "DlSystem/StringList.hpp" -#include -#include - -#ifndef DL_SYSTEM_RUNTIME_LIST_HPP -#define DL_SYSTEM_RUNTIME_LIST_HPP - -namespace DlSystem -{ - // Forward declaration of Runtime List implementation. - class RuntimeListImpl; -} - -namespace zdl -{ -namespace DlSystem -{ - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * @brief . - * - * A class representing list of runtimes - */ -class ZDL_EXPORT RuntimeList final -{ -public: - - /** - * @brief . - * - * Creates a new runtime list - * - */ - RuntimeList(); - - /** - * @brief . - * - * copy constructor. - * @param[in] other object to copy. - */ - RuntimeList(const RuntimeList& other); - - /** - * @brief . - * - * constructor with single Runtime_t object - * @param[in] Runtime_t object - */ - RuntimeList(const zdl::DlSystem::Runtime_t& runtime); - - /** - * @brief . - * - * assignment operator. - */ - RuntimeList& operator=(const RuntimeList& other); - - /** - * @brief . - * - * subscript operator. - */ - Runtime_t& operator[](size_t index); - - /** - * @brief Adds runtime to the end of the runtime list - * order of precedence is former followed by latter entry - * - * @param[in] runtime to add - * - * Ruturns false If the runtime already exists - */ - bool add(const zdl::DlSystem::Runtime_t& runtime); - - /** - * @brief Removes the runtime from the list - * - * @param[in] runtime to be removed - * - * @note If the runtime is not found, nothing is done. - */ - void remove(const zdl::DlSystem::Runtime_t runtime) noexcept; - - /** - * @brief Returns the number of runtimes in the list - */ - size_t size() const noexcept; - - /** - * @brief Returns true if the list is empty - */ - bool empty() const noexcept; - - /** - * @brief . - * - * Removes all runtime from the list - */ - void clear() noexcept; - - /** - * @brief . - * - * Returns a StringList of names from the runtime list in - * order of precedence - */ - zdl::DlSystem::StringList getRuntimeListNames() const; - - /** - * @brief . - * - * @param[in] runtime string - * Returns a Runtime enum corresponding to the in param string - * - */ - static zdl::DlSystem::Runtime_t stringToRuntime(const char* runtimeStr); - - /** - * @brief . - * - * @param[in] runtime - * Returns a string corresponding to the in param runtime enum - * - */ - static const char* runtimeToString(const zdl::DlSystem::Runtime_t runtime); - - ~RuntimeList(); - -private: - void deepCopy(const RuntimeList &other); - std::unique_ptr<::DlSystem::RuntimeListImpl> m_RuntimeListImpl; -}; - -} // DlSystem namespace -} // zdl namespace - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -#endif // DL_SYSTEM_RUNTIME_LIST_HPP - diff --git a/third_party/snpe/include/DlSystem/String.hpp b/third_party/snpe/include/DlSystem/String.hpp deleted file mode 100644 index c1eba3bad9..0000000000 --- a/third_party/snpe/include/DlSystem/String.hpp +++ /dev/null @@ -1,104 +0,0 @@ -//============================================================================= -// -// Copyright (c) 2017, 2020 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================= - -#ifndef PLATFORM_STANDARD_STRING_HPP -#define PLATFORM_STANDARD_STRING_HPP - -#include -#include -#include -#include "DlSystem/ZdlExportDefine.hpp" - -namespace zdl -{ -namespace DlSystem -{ -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * @brief . - * - * Class for wrapping char * as a really stripped down std::string replacement. - */ -class ZDL_EXPORT String final -{ -public: - String() = delete; - - /** - * Construct a string from std::string reference. - * @param str Reference to a std::string - */ - explicit String(const std::string& str); - - /** - * Construct a string from char* reference. - * @param a char* - */ - explicit String(const char* str); - - /** - * move constructor. - */ - String(String&& other) noexcept; - - /** - * copy constructor. - */ - String(const String& other) = delete; - - /** - * assignment operator. - */ - String& operator=(const String&) = delete; - - /** - * move assignment operator. - */ - String& operator=(String&&) = delete; - - /** - * class comparators - */ - bool operator<(const String& rhs) const noexcept; - bool operator>(const String& rhs) const noexcept; - bool operator<=(const String& rhs) const noexcept; - bool operator>=(const String& rhs) const noexcept; - bool operator==(const String& rhs) const noexcept; - bool operator!=(const String& rhs) const noexcept; - - /** - * class comparators against std::string - */ - bool operator<(const std::string& rhs) const noexcept; - bool operator>(const std::string& rhs) const noexcept; - bool operator<=(const std::string& rhs) const noexcept; - bool operator>=(const std::string& rhs) const noexcept; - bool operator==(const std::string& rhs) const noexcept; - bool operator!=(const std::string& rhs) const noexcept; - - const char* c_str() const noexcept; - - ~String(); -private: - - char* m_string; -}; - -/** - * overloaded << operator - */ -ZDL_EXPORT std::ostream& operator<<(std::ostream& os, const String& str) noexcept; - -} // DlSystem namespace -} // zdl namespace - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -#endif // PLATFORM_STANDARD_STRING_HPP diff --git a/third_party/snpe/include/DlSystem/StringList.hpp b/third_party/snpe/include/DlSystem/StringList.hpp deleted file mode 100644 index a9a7d5ed89..0000000000 --- a/third_party/snpe/include/DlSystem/StringList.hpp +++ /dev/null @@ -1,107 +0,0 @@ -//============================================================================= -// -// Copyright (c) 2016 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================= -#include -#include "ZdlExportDefine.hpp" - -#ifndef DL_SYSTEM_STRINGLIST_HPP -#define DL_SYSTEM_STRINGLIST_HPP - -namespace zdl -{ -namespace DlSystem -{ -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * @brief . - * - * Class for holding an order list of null-terminated ASCII strings. - */ -class ZDL_EXPORT StringList final -{ -public: - StringList() {} - - /** - * Construct a string list with some pre-allocated memory. - * @warning Contents of the list will be uninitialized - * @param[in] length Number of elements for which to pre-allocate space. - */ - explicit StringList(size_t length); - - /** - * Append a string to the list. - * @param[in] str Null-terminated ASCII string to append to the list. - */ - void append(const char* str); - - /** - * Returns the string at the indicated position, - * or an empty string if the positions is greater than the size - * of the list. - * @param[in] idx Position in the list of the desired string - */ - const char* at(size_t idx) const noexcept; - - /** - * Pointer to the first string in the list. - * Can be used to iterate through the list. - */ - const char** begin() const noexcept; - - /** - * Pointer to one after the last string in the list. - * Can be used to iterate through the list. - */ - const char** end() const noexcept; - - /** - * Return the number of valid string pointers held by this list. - */ - size_t size() const noexcept; - - - /** - * assignment operator. - */ - StringList& operator=(const StringList&) noexcept; - - /** - * copy constructor. - * @param[in] other object to copy. - */ - StringList(const StringList& other); - - /** - * move constructor. - * @param[in] other object to move. - */ - StringList(StringList&& other) noexcept; - - ~StringList(); -private: - void copy(const StringList& other); - - void resize(size_t length); - - void clear(); - - static const char* s_Empty; - const char** m_Strings = nullptr; - const char** m_End = nullptr; - size_t m_Size = 0; -}; - -} // DlSystem namespace -} // zdl namespace - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -#endif // DL_SYSTEM_STRINGLIST_HPP - diff --git a/third_party/snpe/include/DlSystem/TensorMap.hpp b/third_party/snpe/include/DlSystem/TensorMap.hpp deleted file mode 100644 index feecec6667..0000000000 --- a/third_party/snpe/include/DlSystem/TensorMap.hpp +++ /dev/null @@ -1,120 +0,0 @@ -//============================================================================= -// -// Copyright (c) 2016 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================= -#include -#include "ZdlExportDefine.hpp" -#include "ITensor.hpp" -#include "StringList.hpp" - -#ifndef DL_SYSTEM_TENSOR_MAP_HPP -#define DL_SYSTEM_TENSOR_MAP_HPP - -namespace DlSystem -{ - // Forward declaration of tensor map implementation. - class TensorMapImpl; -} - -namespace zdl -{ -namespace DlSystem -{ - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * @brief . - * - * A class representing the map of tensor. - */ -class ZDL_EXPORT TensorMap final -{ -public: - - /** - * @brief . - * - * Creates a new empty tensor map - */ - TensorMap(); - - /** - * copy constructor. - * @param[in] other object to copy. - */ - TensorMap(const TensorMap& other); - - /** - * assignment operator. - */ - TensorMap& operator=(const TensorMap& other); - - /** - * @brief Adds a name and the corresponding tensor pointer - * to the map - * - * @param[in] name The name of the tensor - * @param[out] tensor The pointer to the tensor - * - * @note If a tensor with the same name already exists, the - * tensor is replaced with the existing tensor. - */ - void add(const char *name, zdl::DlSystem::ITensor *tensor); - - /** - * @brief Removes a mapping of tensor and its name by its name - * - * @param[in] name The name of tensor to be removed - * - * @note If no tensor with the specified name is found, nothing - * is done. - */ - void remove(const char *name) noexcept; - - /** - * @brief Returns the number of tensors in the map - */ - size_t size() const noexcept; - - /** - * @brief . - * - * Removes all tensors from the map - */ - void clear() noexcept; - - /** - * @brief Returns the tensor given its name. - * - * @param[in] name The name of the tensor to get. - * - * @return nullptr if no tensor with the specified name is - * found; otherwise, a valid pointer to the tensor. - */ - zdl::DlSystem::ITensor* getTensor(const char *name) const noexcept; - - /** - * @brief . - * - * Returns the names of all tensors - */ - zdl::DlSystem::StringList getTensorNames() const; - - ~TensorMap(); -private: - void swap(const TensorMap &other); - std::unique_ptr<::DlSystem::TensorMapImpl> m_TensorMapImpl; -}; - -} // DlSystem namespace -} // zdl namespace - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -#endif // DL_SYSTEM_TENSOR_MAP_HPP - diff --git a/third_party/snpe/include/DlSystem/TensorShape.hpp b/third_party/snpe/include/DlSystem/TensorShape.hpp deleted file mode 100644 index 99583dccb4..0000000000 --- a/third_party/snpe/include/DlSystem/TensorShape.hpp +++ /dev/null @@ -1,203 +0,0 @@ -//============================================================================= -// -// Copyright (c) 2016 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================= -#include -#include -#include -#include -#include "ZdlExportDefine.hpp" - -#ifndef DL_SYSTEM_TENSOR_SHAPE_HPP -#define DL_SYSTEM_TENSOR_SHAPE_HPP - -namespace DlSystem -{ - // Forward declaration of tensor shape implementation. - class TensorShapeImpl; -} - -namespace zdl -{ -namespace DlSystem -{ - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * @brief . - * - * Convenient typedef to represent dimension - */ -using Dimension = size_t; - -/** - * @brief . - * - * A class representing the shape of tensor. It is used at the - * time of creation of tensor. - */ -class ZDL_EXPORT TensorShape final -{ -public: - - /** - * @brief . - * - * Creates a new shape with a list of dims specified in - * initializer list fashion. - * - * @param[in] dims The dimensions are specified in which the last - * element of the vector represents the fastest varying - * dimension and the zeroth element represents the slowest - * varying, etc. - * - */ - TensorShape(std::initializer_list dims); - - /** - * @brief . - * - * Creates a new shape with a list of dims specified in array - * - * @param[in] dims The dimensions are specified in which the last - * element of the vector represents the fastest varying - * dimension and the zeroth element represents the slowest - * varying, etc. - * - * @param[in] size Size of the array. - * - */ - TensorShape(const Dimension *dims, size_t size); - - /** - * @brief . - * - * Creates a new shape with a vector of dims specified in - * vector fashion. - * - * @param[in] dims The dimensions are specified in which the last - * element of the vector represents the fastest varying - * dimension and the zeroth element represents the slowest - * varying, etc. - * - */ - TensorShape(std::vector dims); - - /** - * @brief . - * - * copy constructor. - * @param[in] other object to copy. - */ - TensorShape(const TensorShape& other); - - /** - * @brief . - * - * assignment operator. - */ - TensorShape& operator=(const TensorShape& other); - - /** - * @brief . - * - * Creates a new shape with no dims. It can be extended later - * by invoking concatenate. - */ - TensorShape(); - - /** - * @brief . - * - * Concatenates additional dimensions specified in - * initializer list fashion to the existing dimensions. - * - * @param[in] dims The dimensions are specified in which the last - * element of the vector represents the fastest varying - * dimension and the zeroth element represents the slowest - * varying, etc. - * - */ - void concatenate(std::initializer_list dims); - - /** - * @brief . - * - * Concatenates additional dimensions specified in - * the array to the existing dimensions. - * - * @param[in] dims The dimensions are specified in which the last - * element of the vector represents the fastest varying - * dimension and the zeroth element represents the slowest - * varying, etc. - * - * @param[in] size Size of the array. - * - */ - void concatenate(const Dimension *dims, size_t size); - - /** - * @brief . - * - * Concatenates an additional dimension to the existing - * dimensions. - * - * @param[in] dim The dimensions are specified in which the last element - * of the vector represents the fastest varying dimension and the - * zeroth element represents the slowest varying, etc. - * - */ - void concatenate(const Dimension &dim); - - /** - * @brief . - * - * Retrieves a single dimension, based on its index. - * - * @return The value of dimension - * - * @throws std::out_of_range if the index is >= the number of - * dimensions (or rank). - */ - Dimension& operator[](size_t index); - Dimension& operator[](size_t index) const; - - /** - * @brief . - * - * Retrieves the rank i.e. number of dimensions. - * - * @return The rank - */ - size_t rank() const; - - /** - * @brief . - * - * Retrieves a pointer to the first dimension of shape - * - * @return nullptr if no dimension exists; otherwise, points to - * the first dimension. - * - */ - const Dimension* getDimensions() const; - - ~TensorShape(); - -private: - void swap(const TensorShape &other); - std::unique_ptr<::DlSystem::TensorShapeImpl> m_TensorShapeImpl; -}; - -} // DlSystem namespace -} // zdl namespace - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -#endif // DL_SYSTEM_TENSOR_SHAPE_HPP - diff --git a/third_party/snpe/include/DlSystem/TensorShapeMap.hpp b/third_party/snpe/include/DlSystem/TensorShapeMap.hpp deleted file mode 100644 index cef946e2e6..0000000000 --- a/third_party/snpe/include/DlSystem/TensorShapeMap.hpp +++ /dev/null @@ -1,127 +0,0 @@ -//============================================================================= -// -// Copyright (c) 2017-2020 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================= -#include -#include -#include -#include "ZdlExportDefine.hpp" -#include "DlSystem/TensorShape.hpp" -#include "DlSystem/StringList.hpp" - -#ifndef DL_SYSTEM_TENSOR_SHAPE_MAP_HPP -#define DL_SYSTEM_TENSOR_SHAPE_MAP_HPP - -namespace DlSystem -{ - // Forward declaration of tensor shape map implementation. - class TensorShapeMapImpl; -} - -namespace zdl -{ -namespace DlSystem -{ - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * @brief . - * - * A class representing the map of names and tensorshapes. - */ -class ZDL_EXPORT TensorShapeMap final -{ -public: - - /** - * @brief . - * - * Creates a new tensor shape map - * - */ - TensorShapeMap(); - - /** - * @brief . - * - * copy constructor. - * @param[in] other object to copy. - */ - TensorShapeMap(const TensorShapeMap& other); - - /** - * @brief . - * - * assignment operator. - */ - TensorShapeMap& operator=(const TensorShapeMap& other); - - /** - * @brief Adds a name and the corresponding tensor pointer - * to the map - * - * @param[in] name The name of the tensor - * @param[out] tensor The pointer to the tensor - * - * @note If a tensor with the same name already exists, no new - * tensor is added. - */ - void add(const char *name, const zdl::DlSystem::TensorShape& tensorShape); - - /** - * @brief Removes a mapping of tensor and its name by its name - * - * @param[in] name The name of tensor to be removed - * - * @note If no tensor with the specified name is found, nothing - * is done. - */ - void remove(const char *name) noexcept; - - /** - * @brief Returns the number of tensors in the map - */ - size_t size() const noexcept; - - /** - * @brief . - * - * Removes all tensors from the map - */ - void clear() noexcept; - - /** - * @brief Returns the tensor given its name. - * - * @param[in] name The name of the tensor to get. - * - * @return nullptr if no tensor with the specified name is - * found; otherwise, a valid pointer to the tensor. - */ - zdl::DlSystem::TensorShape getTensorShape(const char *name) const noexcept; - - /** - * @brief . - * - * Returns the names of all tensor shapes - */ - zdl::DlSystem::StringList getTensorShapeNames() const; - - ~TensorShapeMap(); -private: - void swap(const TensorShapeMap &other); - std::unique_ptr<::DlSystem::TensorShapeMapImpl> m_TensorShapeMapImpl; -}; - -} // DlSystem namespace -} // zdl namespace - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -#endif // DL_SYSTEM_TENSOR_SHAPE_MAP_HPP - diff --git a/third_party/snpe/include/DlSystem/UDLContext.hpp b/third_party/snpe/include/DlSystem/UDLContext.hpp deleted file mode 100644 index 21fce1b04a..0000000000 --- a/third_party/snpe/include/DlSystem/UDLContext.hpp +++ /dev/null @@ -1,243 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2016-2021 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== - -#ifndef UDL_CONTEXT_HPP -#define UDL_CONTEXT_HPP - -#include // memset -#include - -#include "ZdlExportDefine.hpp" - -namespace zdl { namespace DlSystem { - -/** - * NOTE: DEPRECATED, MAY BE REMOVED IN THE FUTURE. - * - * @brief . - * - * UDLContext holds the user defined layer context which - * consists of a layer name, layer ID, blob and blob size. - * - * An instance of UDLContext is passed as an argument to the - * UDLFactoryFunc provided by the user every time the SNPE - * runtime encounters an unknown layer descriptor. The instance - * of a UDLContext is created by the SNPE runtime and is - * consumed by the user's factory function. The user should - * obtain a copy of this class and should not assume any - * prolonged object lifetime beyond the UDLFactoryFunction. - */ -class ZDL_EXPORT UDLContext final { -public: - /** - * @brief Constructor - * - * @param[in] name name of the layer - * - * @param[in] type layer type - * - * @param[in] id identifier for the layer - * - * @param[in] id Blob/bytes as packed by the user code as part of - * the Python converter script - */ - UDLContext(const std::string& name, - const std::string& type, - int32_t id, - const std::string& blob) : - m_Name(name), m_Type(type), m_Size(blob.size()), m_Id(id) { - // FIXME not dealing with alloc error - m_Buffer = new uint8_t[m_Size]; - std::memcpy(m_Buffer, blob.data(), m_Size); - } - - /** - * @brief . - * - * Empty constructor is useful for - * creating an empty UDLContext and then run copy constructor - * from a fully initialized one. - */ - explicit UDLContext() {} - - /** - * @brief . - * - * destructor Deallocates any internal allocated memory - */ - ~UDLContext() { release(); } - - /** - * @brief . - * - * Deallocate any internally allocated memory - */ - void release() { - if (m_Buffer && m_Size) - std::memset(m_Buffer, 0, m_Size); - delete []m_Buffer; - m_Buffer = nullptr; - m_Size = 0; - } - - /** - * @brief . - * - * Copy Constructor - makes a copy from ctx - * - * @param[in] ctx Source UDLContext to copy from - */ - UDLContext(const UDLContext& ctx) : m_Name(ctx.m_Name), - m_Type(ctx.m_Type), - m_Id(ctx.m_Id) { - std::tuple cpy = ctx.getCopy(); - // current compiler does not support get - m_Buffer = std::get<0>(cpy); - m_Size = std::get<1>(cpy); - } - - /** - * @brief - * - * Assignment operator - makes a copy from ctx - * - * @param[in] ctx Source UDLContext to copy from - * - * @return this - */ - UDLContext& operator=(const UDLContext& ctx) { - UDLContext c (ctx); - this->swap(c); // non throwing swap - return *this; - } - - /** - * @brief . - * - * Move Constructor - Move internals from ctx into this - * - * @param[in] ctx Source UDLContext to move from - */ - UDLContext(UDLContext&& ctx) : - m_Name(std::move(ctx.m_Name)), - m_Type(std::move(ctx.m_Type)), - m_Buffer(ctx.m_Buffer), - m_Size(ctx.m_Size), - m_Id(ctx.m_Id) { - ctx.clear(); - } - - /** - * @brief . - * - * Assignment move - Move assignment operator from ctx - * - * @param[in] ctx Source UDLContext to move from - * - * @return this - */ - UDLContext& operator=(UDLContext&& ctx) { - m_Name = std::move(ctx.m_Name); - m_Type = std::move(ctx.m_Type); - m_Buffer = ctx.m_Buffer; - m_Size = ctx.m_Size; - m_Id = ctx.m_Id; - ctx.clear(); - return *this; - } - - /** - * @brief . - * - * Obtain the name of the layer - * - * @return const reference to the name of the layer - */ - const std::string& getName() const noexcept { return m_Name; } - - /** - * @brief . - * - * Obtain the type of the layer - * - * @return const reference to the type of the layer - */ - const std::string& getType() const noexcept { return m_Type; } - - /** - * @brief . - * - * Obtain the Id of the layer - * - * @return The id of the layer - */ - int32_t getId() const noexcept { return m_Id; } - - /** - * @brief . - * - * Obtain the size of the blob - * - * @return Size of the internal blob - */ - size_t getSize() const noexcept { return m_Size; } - - /** - * @brief . - * - * Get a const pointer to the internal blob - * - * @return Const pointer to the internal blob - */ - const uint8_t* getBlob() const noexcept { return m_Buffer; } - - /** - * @brief . - * - * Get a copy of the blob/size into a tuple - * - * @return A tuple with a pointer to a copy of the blob and a - * size - */ - std::tuple getCopy() const { - uint8_t* buf = new uint8_t[m_Size]; - // FIXME missing memcpy - std::memcpy(buf, m_Buffer, m_Size); - return std::make_tuple(buf, m_Size); - } - - /** - * @brief . - * - * Set zeros in the internals members - */ - void clear() { - m_Name.clear(); - m_Type.clear(); - m_Buffer = 0; - m_Size = 0; - m_Id = -1; - } -private: - void swap(UDLContext& c) noexcept { - std::swap(m_Name, c.m_Name); - std::swap(m_Type, c.m_Type); - std::swap(m_Id, c.m_Id); - std::swap(m_Buffer, c.m_Buffer); - std::swap(m_Size, c.m_Size); - } - std::string m_Name; // name of the layer instance - std::string m_Type; // The actual layer type - uint8_t* m_Buffer = nullptr; - size_t m_Size = 0; - int32_t m_Id = -1; -}; - -}} - -#endif /* UDL_CONTEXT_HPP */ diff --git a/third_party/snpe/include/DlSystem/UDLFunc.hpp b/third_party/snpe/include/DlSystem/UDLFunc.hpp deleted file mode 100644 index 6a95eef170..0000000000 --- a/third_party/snpe/include/DlSystem/UDLFunc.hpp +++ /dev/null @@ -1,87 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2015-2021 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== - -#ifndef _UDL_FUNC_HPP_ -#define _UDL_FUNC_HPP_ - -#include - -#include "ZdlExportDefine.hpp" -#include - -namespace zdl { - namespace DlSystem { - class UDLContext; - } -} - -namespace zdl { namespace DlSystem { -/** - * NOTE: DEPRECATED, MAY BE REMOVED IN THE FUTURE. - * - * @brief . - * - * Definition of UDLFactoyFunc, using/typedef and default FactoryFunction - * UDLBundle - a simple way to bundle func and cookie into one type - */ - - -/** - * @brief . - * - * Convenient typedef for user defined layer creation factory - * - * @param[out] void* Cookie - a user opaque data that was passed during SNPE's runtime's - * CreateInstance. SNPE's runtime is passing this back to the user. - * - * @param[out] DlSystem::UDLContext* - The specific Layer Description context what is passe - * SNPE runtime. - * - * @return IUDL* - a Concrete instance of IUDL derivative - */ -using UDLFactoryFunc = std::function; - -/** - * NOTE: DEPRECATED, MAY BE REMOVED IN THE FUTURE. - * - * @brief . - * - * default UDL factory implementation - * - * @param[out] DlSystem::UDLContext* - The specific Layer Description context what is passe - * SNPE runtime. - * - * @param[out] void* Cookie - a user opaque data that was passed during SNPE's runtime's - * CreateInstance. SNPE's runtime is passing this back to the user. - * - * @return IUDL* - nullptr to indicate SNPE's runtime that there is no specific - * implementation for UDL. When SNPE's runtime sees nullptr as a return - * value from the factory, it will halt execution if model has an unknown layer - * - */ -inline ZDL_EXPORT zdl::DlSystem::IUDL* DefaultUDLFunc(void*, const zdl::DlSystem::UDLContext*) { return nullptr; } - -/** - * NOTE: DEPRECATED, MAY BE REMOVED IN THE FUTURE. - * - * @brief . - * - * Simple struct to bundle 2 elements. - * A user defined cookie that would be returned for each - * IUDL call. The user can place anything there and the - * SNPE runtime will provide it back - */ -struct ZDL_EXPORT UDLBundle { - void *cookie = nullptr; - UDLFactoryFunc func = DefaultUDLFunc; -}; - -}} - - -#endif // _UDL_FUNC_HPP_ diff --git a/third_party/snpe/include/DlSystem/UserBufferMap.hpp b/third_party/snpe/include/DlSystem/UserBufferMap.hpp deleted file mode 100644 index a03ddfe1d1..0000000000 --- a/third_party/snpe/include/DlSystem/UserBufferMap.hpp +++ /dev/null @@ -1,122 +0,0 @@ -//============================================================================= -// -// Copyright (c) 2017 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================= -#include -#include "ZdlExportDefine.hpp" -#include "StringList.hpp" - -#ifndef DL_SYSTEM_USER_BUFFER_MAP_HPP -#define DL_SYSTEM_USER_BUFFER_MAP_HPP - -namespace DlSystem -{ - // Forward declaration of UserBuffer map implementation. - class UserBufferMapImpl; -} - -namespace zdl -{ -namespace DlSystem -{ -class IUserBuffer; - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * @brief . - * - * A class representing the map of UserBuffer. - */ -class ZDL_EXPORT UserBufferMap final -{ -public: - - /** - * @brief . - * - * Creates a new empty UserBuffer map - */ - UserBufferMap(); - - /** - * copy constructor. - * @param[in] other object to copy. - */ - UserBufferMap(const UserBufferMap& other); - - /** - * assignment operator. - */ - UserBufferMap& operator=(const UserBufferMap& other); - - /** - * @brief Adds a name and the corresponding UserBuffer pointer - * to the map - * - * @param[in] name The name of the UserBuffer - * @param[in] userBuffer The pointer to the UserBuffer - * - * @note If a UserBuffer with the same name already exists, the new - * UserBuffer pointer would be updated. - */ - void add(const char *name, zdl::DlSystem::IUserBuffer *buffer); - - /** - * @brief Removes a mapping of one UserBuffer and its name by its name - * - * @param[in] name The name of UserBuffer to be removed - * - * @note If no UserBuffer with the specified name is found, nothing - * is done. - */ - void remove(const char *name) noexcept; - - /** - * @brief Returns the number of UserBuffers in the map - */ - size_t size() const noexcept; - - /** - * @brief . - * - * Removes all UserBuffers from the map - */ - void clear() noexcept; - - /** - * @brief Returns the UserBuffer given its name. - * - * @param[in] name The name of the UserBuffer to get. - * - * @return nullptr if no UserBuffer with the specified name is - * found; otherwise, a valid pointer to the UserBuffer. - */ - zdl::DlSystem::IUserBuffer* getUserBuffer(const char *name) const noexcept; - - /** - * @brief . - * - * Returns the names of all UserBuffers - * - * @return A list of UserBuffer names. - */ - zdl::DlSystem::StringList getUserBufferNames() const; - - ~UserBufferMap(); -private: - void swap(const UserBufferMap &other); - std::unique_ptr<::DlSystem::UserBufferMapImpl> m_UserBufferMapImpl; -}; -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -} // DlSystem namespace -} // zdl namespace - - -#endif // DL_SYSTEM_TENSOR_MAP_HPP - diff --git a/third_party/snpe/include/DlSystem/UserMemoryMap.hpp b/third_party/snpe/include/DlSystem/UserMemoryMap.hpp deleted file mode 100644 index 3685a8ddab..0000000000 --- a/third_party/snpe/include/DlSystem/UserMemoryMap.hpp +++ /dev/null @@ -1,129 +0,0 @@ -//============================================================================= -// -// Copyright (c) 2021 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================= -#include -#include "ZdlExportDefine.hpp" -#include "StringList.hpp" - -#ifndef DL_SYSTEM_USER_MEMORY_MAP_HPP -#define DL_SYSTEM_USER_MEMORY_MAP_HPP - -namespace DlSystem -{ - // Forward declaration of UserMemory map implementation. - class UserMemoryMapImpl; -} - -namespace zdl -{ -namespace DlSystem -{ -class IUserBuffer; - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * @brief . - * - * A class representing the map of UserMemory. - */ -class ZDL_EXPORT UserMemoryMap final -{ -public: - - /** - * @brief . - * - * Creates a new empty UserMemory map - */ - UserMemoryMap(); - - /** - * copy constructor. - * @param[in] other object to copy. - */ - UserMemoryMap(const UserMemoryMap& other); - - /** - * assignment operator. - */ - UserMemoryMap& operator=(const UserMemoryMap& other); - - /** - * @brief Adds a name and the corresponding buffer address - * to the map - * - * @param[in] name The name of the UserMemory - * @param[in] address The pointer to the Buffer Memory - * - * @note If a UserBuffer with the same name already exists, the new - * address would be updated. - */ - void add(const char *name, void *address); - - /** - * @brief Removes a mapping of one Buffer address and its name by its name - * - * @param[in] name The name of Memory address to be removed - * - * @note If no UserBuffer with the specified name is found, nothing - * is done. - */ - void remove(const char *name) noexcept; - - /** - * @brief Returns the number of User Memory addresses in the map - */ - size_t size() const noexcept; - - /** - * @brief . - * - * Removes all User Memory from the map - */ - void clear() noexcept; - - /** - * @brief . - * - * Returns the names of all User Memory - * - * @return A list of Buffer names. - */ - zdl::DlSystem::StringList getUserBufferNames() const; - - /** - * @brief Returns the no of UserMemory addresses mapped to the buffer - * - * @param[in] name The name of the UserMemory - * - */ - size_t getUserMemoryAddressCount(const char *name) const noexcept; - - /** - * @brief Returns address at a specified index corresponding to a UserMemory buffer name - * - * @param[in] name The name of the buffer - * @param[in] index The index in the list of addresses - * - */ - void* getUserMemoryAddressAtIndex(const char *name, uint32_t index) const noexcept; - - ~UserMemoryMap(); -private: - void swap(const UserMemoryMap &other); - std::unique_ptr<::DlSystem::UserMemoryMapImpl> m_UserMemoryMapImpl; -}; -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -} // DlSystem namespace -} // zdl namespace - - -#endif // DL_SYSTEM_TENSOR_MAP_HPP - diff --git a/third_party/snpe/include/DlSystem/ZdlExportDefine.hpp b/third_party/snpe/include/DlSystem/ZdlExportDefine.hpp deleted file mode 100644 index 92eb786d31..0000000000 --- a/third_party/snpe/include/DlSystem/ZdlExportDefine.hpp +++ /dev/null @@ -1,13 +0,0 @@ -//============================================================================= -// -// Copyright (c) 2015, 2020 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================= - -#pragma once - -#ifndef ZDL_EXPORT -#define ZDL_EXPORT -#endif diff --git a/third_party/snpe/include/PlatformValidator/PlatformValidator.hpp b/third_party/snpe/include/PlatformValidator/PlatformValidator.hpp deleted file mode 100644 index 66097ba569..0000000000 --- a/third_party/snpe/include/PlatformValidator/PlatformValidator.hpp +++ /dev/null @@ -1,118 +0,0 @@ -// ============================================================================= -// -// Copyright (c) 2018-2020 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -// ============================================================================= - -#ifndef SNPE_PLATFORMVALIDATOR_HPP -#define SNPE_PLATFORMVALIDATOR_HPP - -#include "DlSystem/DlEnums.hpp" -#include "DlSystem/ZdlExportDefine.hpp" - -#define DO_PRAGMA(s) _Pragma(#s) -#define NO_WARNING "-Wunused-variable" - -#ifdef __clang__ -#define SNPE_DISABLE_WARNINGS(clang_warning,gcc_warning) \ -_Pragma("clang diagnostic push") \ -DO_PRAGMA(clang diagnostic ignored clang_warning) - -#define SNPE_ENABLE_WARNINGS \ -_Pragma("clang diagnostic pop") - -#elif defined __GNUC__ -#define SNPE_DISABLE_WARNINGS(clang_warning,gcc_warning) \ -_Pragma("GCC diagnostic push") \ -DO_PRAGMA(GCC diagnostic ignored gcc_warning) - -#define SNPE_ENABLE_WARNINGS \ -_Pragma("GCC diagnostic pop") - -#else -#define SNPE_DISABLE_WARNINGS(...) -#define SNPE_ENABLE_WARNINGS -#endif - -SNPE_DISABLE_WARNINGS("-Wdelete-non-virtual-dtor","-Wdelete-non-virtual-dtor") -#include -#include -SNPE_ENABLE_WARNINGS - -namespace zdl -{ - namespace SNPE - { - class PlatformValidator; - - class IPlatformValidatorRuntime; - } -} - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** -* The class for checking SNPE compatibility/capability of a device. -* -*/ - -class ZDL_EXPORT zdl::SNPE::PlatformValidator -{ -public: - /** - * @brief Default Constructor of the PlatformValidator Class - * - * @return A new instance of a PlatformValidator object - * that can be used to check the SNPE compatibility - * of a device - */ - PlatformValidator(); - - ~PlatformValidator(); - - /** - * @brief Sets the runtime processor for compatibility check - * - * @return Void - */ - void setRuntime(zdl::DlSystem::Runtime_t runtime); - - /** - * @brief Checks if the Runtime prerequisites for SNPE are available. - * - * @return True if the Runtime prerequisites are available, else false. - */ - bool isRuntimeAvailable(); - - /** - * @brief Returns the core version for the Runtime selected. - * - * @return String which contains the actual core version value - */ - std::string getCoreVersion(); - - /** - * @brief Returns the library version for the Runtime selected. - * - * @return String which contains the actual lib version value - */ - std::string getLibVersion(); - - /** - * @brief Runs a small program on the runtime and Checks if SNPE is supported for Runtime. - * - * @return If True, the device is ready for SNPE execution, else not. - */ - - bool runtimeCheck(); - -private: - zdl::DlSystem::Runtime_t m_runtimeType; - std::unique_ptr m_platformValidatorRuntime; -}; -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -#endif //SNPE_PLATFORMVALIDATOR_HPP diff --git a/third_party/snpe/include/SNPE/ApplicationBufferMap.hpp b/third_party/snpe/include/SNPE/ApplicationBufferMap.hpp deleted file mode 100644 index 380a3e0e6e..0000000000 --- a/third_party/snpe/include/SNPE/ApplicationBufferMap.hpp +++ /dev/null @@ -1,101 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2019 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== - -#ifndef PSNPE_APPLICATIONBUFFERMAP_HPP -#define PSNPE_APPLICATIONBUFFERMAP_HPP -#include -#include -#include - -#include "DlSystem/UserBufferMap.hpp" -#include "DlSystem/ZdlExportDefine.hpp" - -namespace zdl -{ -namespace PSNPE -{ -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * @brief . - * - * A class representing the UserBufferMap of Input and Output asynchronous mode. - */ - -class ZDL_EXPORT ApplicationBufferMap final -{ - - public: - /** - * @brief Adds a name and the corresponding buffer - * to the map - * - * @param[in] name The name of the UserBuffer - * @param[in] buffer The vector of the uint8_t data - * - * @note If a UserBuffer with the same name already exists, the new - * UserBuffer pointer would be updated. - */ - void add(const char* name, std::vector& buff) noexcept; - void add(const char* name, std::vector& buff) noexcept; - /** - * @brief Removes a mapping of one UserBuffer and its name by its name - * - * @param[in] name The name of UserBuffer to be removed - * - * @note If no UserBuffer with the specified name is found, nothing - * is done. - */ - void remove(const char* name) noexcept; - - /** - * @brief Returns the number of UserBuffers in the map - */ - size_t size() const noexcept; - - /** - * @brief . - * - * Removes all UserBuffers from the map - */ - void clear() noexcept; - - /** - * @brief Returns the UserBuffer given its name. - * - * @param[in] name The name of the UserBuffer to get. - * - * @return nullptr if no UserBuffer with the specified name is - * found; otherwise, a valid pointer to the UserBuffer. - */ - const std::vector& getUserBuffer(const char* name) const; - const std::vector& operator[](const char* name) const; - /** - * @brief . - * - * Returns the names of all UserAsyncBufferMap - * - * @return A list of UserBuffer names. - */ - zdl::DlSystem::StringList getUserBufferNames() const; - const std::unordered_map>& getUserBuffer() const; - explicit ApplicationBufferMap(); - ~ApplicationBufferMap(); - explicit ApplicationBufferMap( - const std::unordered_map> buffer); - - private: - std::unordered_map> m_UserMap; -}; - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ -} // namespace PSNPE -} // namespace zdl - -#endif // PSNPE_APPLICATIONBUFFERMAP_HPP diff --git a/third_party/snpe/include/SNPE/PSNPE.hpp b/third_party/snpe/include/SNPE/PSNPE.hpp deleted file mode 100644 index a823c0c7fa..0000000000 --- a/third_party/snpe/include/SNPE/PSNPE.hpp +++ /dev/null @@ -1,205 +0,0 @@ -// ============================================================================= -// -// Copyright (c) 2019-2021 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -// ============================================================================= - -#ifndef PSNPE_HPP -#define PSNPE_HPP - -#include -#include -#include "SNPE/SNPE.hpp" -#include "DlSystem/UserBufferMap.hpp" -#include "DlContainer/IDlContainer.hpp" -#include "DlSystem/DlEnums.hpp" -#include "DlSystem/ZdlExportDefine.hpp" - -#include "UserBufferList.hpp" -#include "RuntimeConfigList.hpp" -#include "ApplicationBufferMap.hpp" - -namespace zdl -{ -namespace PSNPE -{ - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - *@ brief build snpe instance in serial or parallel - * - */ -enum ZDL_EXPORT BuildMode { - SERIAL = 0, - PARALLEL = 1 -}; -/** - * @brief Input and output transmission mode - */ -enum ZDL_EXPORT InputOutputTransmissionMode -{ - sync = 0, - outputAsync = 1, - inputOutputAsync = 2 -}; - -/** - * @brief A structure representing parameters of callback function of Async Output mode - */ -struct ZDL_EXPORT OutputAsyncCallbackParam -{ - size_t dataIndex; - bool executeStatus; - std::string errorMsg; - OutputAsyncCallbackParam(size_t _index,bool _status, const std::string& _errorMsg = std::string()) - : dataIndex(_index),executeStatus(_status), errorMsg(_errorMsg){}; -}; -/** - * @brief A structure representing parameters of callback function of Async Input/Output mode - */ -struct ZDL_EXPORT InputOutputAsyncCallbackParam -{ - size_t dataIndex; - const ApplicationBufferMap& outputMap; - bool executeStatus; - std::string errorMsg; - InputOutputAsyncCallbackParam(size_t _index, const ApplicationBufferMap& output_map,bool _status, - const std::string _ErrorMsg = std::string()) - : dataIndex(_index) - , outputMap(output_map) - , executeStatus(_status) - , errorMsg(_ErrorMsg){}; -}; -/** - * @brief This callback is called when the output data is ready, only use for Output Async mode - */ -using OutputAsyncCallbackFunc = std::function; -/** - * @brief This callback is called when the output data is ready, only use for Output-Input Async mode - */ -using InputOutputAsyncCallbackFunc = std::function; -/** - * @brief This callback is called when the input data is ready,only use for Output-Input Async mode - */ -using InputOutputAsyncInputCallback = std::function(const std::vector &, - const zdl::DlSystem::StringList &)>; -/** - * @brief . - * - * A structure PSNPE configuration - * - */ -struct ZDL_EXPORT BuildConfig final -{ - BuildMode buildMode = BuildMode::SERIAL; ///< Specify build in serial mode or parallel mode - zdl::DlContainer::IDlContainer* container;///< The opened container ptr - zdl::DlSystem::StringList outputBufferNames;///< Specify the output layer name - zdl::DlSystem::StringList outputTensors;///< Specify the output layer name - RuntimeConfigList runtimeConfigList;///< The runtime config list for PSNPE, @see RuntimeConfig - size_t inputThreadNumbers = 1;///< Specify the number of threads used in the execution phase to process input data, only used in inputOutputAsync mode - size_t outputThreadNumbers = 1;///< Specify the number of threads used in the execution phase to process output data, only used in inputOutputAsync and outputAsync mode - OutputAsyncCallbackFunc outputCallback;///< The callback to deal with output data ,only used in outputAsync mode - InputOutputAsyncCallbackFunc inputOutputCallback;///< The callback to deal with output data ,only used in inputOutputAsync mode - InputOutputAsyncInputCallback inputOutputInputCallback;///< The callback to deal with input data ,only used in inputOutputAsync mode - InputOutputTransmissionMode inputOutputTransmissionMode = InputOutputTransmissionMode::sync;///< Specify execution mode - zdl::DlSystem::ProfilingLevel_t profilingLevel = zdl::DlSystem::ProfilingLevel_t::OFF;///< Specify profiling level for Diaglog - uint64_t encode[2] = {0, 0}; - bool enableInitCache = false; - std::string platformOptions; - std::string diaglogOutputDir = "./diaglogs/"; ///< Specify a diaglog output directory to save the generated Diaglog files. -}; -/** - * @brief . - * - * The class for executing SNPE instances in parallel. - */ -class ZDL_EXPORT PSNPE final -{ - public: - ~PSNPE(); - - explicit PSNPE() noexcept :m_TransmissionMode(InputOutputTransmissionMode::sync){}; - - /** - * @brief Build snpe instances. - * - */ - bool build(BuildConfig& buildConfig) noexcept; - - /** - * @brief Execute snpe instances in Async Output mode and Sync mode - * - * @param[in] inputBufferList A list of user buffers that contains the input data - * - * @param[in,out] outputBufferList A list of user buffers that will hold the output data - * - */ - bool execute(UserBufferList& inputBufferList, UserBufferList& outputBufferList) noexcept; - - /** - * @brief Execute snpe instances in Async Input/Output mode - * - * @param[in]inputMap A map of input buffers that contains input data. The names of buffers - * need to be matched with names retrived through getInputTensorNames() - * - * @param dataIndex Index of the input data - * - * @param isTF8buff Whether prefer to using 8 bit quantized element for inference - * - * @return True if executed successfully; flase, otherwise. - */ - bool executeInputOutputAsync(const std::vector& inputMap, size_t dataIndex, bool isTF8buff) noexcept; - bool executeInputOutputAsync(const std::vector& inputMap, size_t dataIndex, bool isTF8buff,bool isTF8Outputbuff) noexcept; - /** - * @brief Returns the input layer names of the network. - * - * @return StringList which contains the input layer names - */ - const zdl::DlSystem::StringList getInputTensorNames() const noexcept; - - /** - * @brief Returns the output layer names of the network. - * - * @return StringList which contains the output layer names - */ - const zdl::DlSystem::StringList getOutputTensorNames() const noexcept; - - /** - * @brief Returns the input tensor dimensions of the network. - * - * @return TensorShape which contains the dimensions. - */ - const zdl::DlSystem::TensorShape getInputDimensions() const noexcept; - - const zdl::DlSystem::TensorShape getInputDimensions(const char *name) const noexcept; - - /** - * @brief Returns attributes of buffers. - * - * @see zdl::SNPE - * - * @return BufferAttributes of input/output tensor named. - */ - const zdl::DlSystem::TensorShape getBufferAttributesDims(const char *name) const noexcept; - - zdl::DlSystem::Optional getInputOutputBufferAttributes(const char *name) const noexcept; - bool registerIonBuffers(const zdl::DlSystem::UserMemoryMap& ionBufferMap) const noexcept; - bool deregisterIonBuffers(const zdl::DlSystem::StringList& ionBufferNames) const noexcept; - - const char* getLastErrorString(); - - private: - PSNPE(const PSNPE&) = delete; - PSNPE& operator=(const PSNPE&) = delete; - zdl::PSNPE::InputOutputTransmissionMode m_TransmissionMode; - -}; - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ -} // namespace PSNPE -} // namespace zdl -#endif // PSNPE_HPP diff --git a/third_party/snpe/include/SNPE/RuntimeConfigList.hpp b/third_party/snpe/include/SNPE/RuntimeConfigList.hpp deleted file mode 100644 index 837dba092a..0000000000 --- a/third_party/snpe/include/SNPE/RuntimeConfigList.hpp +++ /dev/null @@ -1,85 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2019-2020 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== -#ifndef PSNPE_RUNTIMECONFIGLIST_HPP -#define PSNPE_RUNTIMECONFIGLIST_HPP - -#include -#include "DlContainer/IDlContainer.hpp" -#include "DlSystem/DlEnums.hpp" -#include "DlSystem/RuntimeList.hpp" -#include "DlSystem/TensorShapeMap.hpp" -#include "DlSystem/ZdlExportDefine.hpp" -namespace zdl { -namespace PSNPE { - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * @brief . - * - * The structure for configuring a BulkSNPE runtime - * - */ -struct ZDL_EXPORT RuntimeConfig final { - zdl::DlSystem::Runtime_t runtime; - zdl::DlSystem::RuntimeList runtimeList; - zdl::DlSystem::PerformanceProfile_t perfProfile; - zdl::DlSystem::TensorShapeMap inputDimensionsMap; - bool enableCPUFallback; - RuntimeConfig() - : runtime{zdl::DlSystem::Runtime_t::CPU_FLOAT32}, - perfProfile{zdl::DlSystem::PerformanceProfile_t::HIGH_PERFORMANCE}, - enableCPUFallback{false} {} - RuntimeConfig(const RuntimeConfig& other) { - runtime = other.runtime; - runtimeList = other.runtimeList; - perfProfile = other.perfProfile; - enableCPUFallback = other.enableCPUFallback; - inputDimensionsMap = other.inputDimensionsMap; - } - - RuntimeConfig& operator=(const RuntimeConfig& other) { - this->runtimeList = other.runtimeList; - this->runtime = other.runtime; - this->perfProfile = other.perfProfile; - this->enableCPUFallback = other.enableCPUFallback; - this->inputDimensionsMap = other.inputDimensionsMap; - return *this; - } - - ~RuntimeConfig() {} -}; - -/** - * @brief . - * - * The class for creating a RuntimeConfig container. - * - */ -class ZDL_EXPORT RuntimeConfigList final { - public: - RuntimeConfigList(); - RuntimeConfigList(const size_t size); - void push_back(const RuntimeConfig& runtimeConfig); - RuntimeConfig& operator[](const size_t index); - RuntimeConfigList& operator=(const RuntimeConfigList& other); - size_t size() const noexcept; - size_t capacity() const noexcept; - void clear() noexcept; - ~RuntimeConfigList() = default; - - private: - void swap(const RuntimeConfigList& other); - std::vector m_runtimeConfigs; -}; -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -} // namespace PSNPE -} // namespace zdl -#endif // PSNPE_RUNTIMECONFIGLIST_HPP diff --git a/third_party/snpe/include/SNPE/SNPE.hpp b/third_party/snpe/include/SNPE/SNPE.hpp deleted file mode 100644 index 5ab45b82ee..0000000000 --- a/third_party/snpe/include/SNPE/SNPE.hpp +++ /dev/null @@ -1,258 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2015-2021 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== - -#ifndef _SNPE_SNPE_HPP_ -#define _SNPE_SNPE_HPP_ - -#include "DlSystem/DlOptional.hpp" -#include "DlSystem/DlVersion.hpp" -#include "DlSystem/IBufferAttributes.hpp" -#include "DlSystem/ITensor.hpp" -#include "DlSystem/TensorShape.hpp" -#include "DlSystem/TensorMap.hpp" -#include "DlSystem/String.hpp" -#include "DlSystem/StringList.hpp" -#include "DlSystem/IUserBuffer.hpp" -#include "DlSystem/UserBufferMap.hpp" -#include "DlSystem/UserMemoryMap.hpp" -#include "DlSystem/ZdlExportDefine.hpp" - -namespace zdl { - namespace SNPE - { - class SnpeRuntime; - } -} -namespace zdl { - namespace DiagLog - { - class IDiagLog; - } -} - -namespace zdl { namespace SNPE { -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * @brief . - * - * The SNPE interface class definition - */ -class ZDL_EXPORT SNPE final -{ -public: - - // keep this undocumented to be hidden in doxygen using HIDE_UNDOC_MEMBERS - explicit SNPE(std::unique_ptr&& runtime) noexcept; - ~SNPE(); - - /** - * @brief Gets the names of input tensors to the network - * - * To support multiple input scenarios, where multiple tensors are - * passed through execute() in a TensorMap, each tensor needs to - * be uniquely named. The names of tensors can be retrieved - * through this function. - * - * In the case of a single input, one name will be returned. - * - * @note Note that because the returned value is an Optional list, - * the list must be verified as boolean true value before being - * dereferenced. - * - * @return An Optional List of input tensor names. - * - * @see zdl::DlSystem::Optional - */ - zdl::DlSystem::Optional - getInputTensorNames() const noexcept; - - /** - * @brief Gets the names of output tensors to the network - * - * @return List of output tensor names. - */ - zdl::DlSystem::Optional - getOutputTensorNames() const noexcept; - - /** - * @brief Gets the name of output tensor from the input layer name - * - * @return Output tensor name. - */ - zdl::DlSystem::StringList - getOutputTensorNamesByLayerName(const char *name) const noexcept; - - /** - * @brief Processes the input data and returns the output - * - * @param[in] A map of tensors that contains the input data for - * each input. The names of tensors needs to be - * matched with names retrieved through - * getInputTensorNames() - * - * @param[in,out] An empty map of tensors that will contain the output - * data of potentially multiple layers (the key - * in the map is the layer name) upon return - * - * @note output tensormap has to be empty. To forward propagate - * and get results in user-supplied tensors, use - * executeWithSuppliedOutputTensors. - */ - bool execute(const zdl::DlSystem::TensorMap &input, - zdl::DlSystem::TensorMap &output) noexcept; - - /** - * @brief Processes the input data and returns the output - * - * @param[in] A single tensor contains the input data. - * - * @param[in,out] An empty map of tensors that will contain the output - * data of potentially multiple layers (the key - * in the map is the layer name) upon return - * - * @note output tensormap has to be empty. - */ - bool execute(const zdl::DlSystem::ITensor *input, - zdl::DlSystem::TensorMap &output) noexcept; - - /** - * @brief Processes the input data and returns the output, using - * user-supplied buffers - * - * @param[in] A map of UserBuffers that contains the input data for - * each input. The names of UserBuffers needs to be - * matched with names retrieved through - * getInputTensorNames() - * - * @param[in,out] A map of UserBuffers that will hold the output - * data of potentially multiple layers (the key - * in the map is the UserBuffer name) - * - * @note input and output UserBuffer maps must be fully pre-populated. with - * dimensions matching what the network expects. - * For example, if there are 5 output UserBuffers they all have to be - * present in map. - * - * Caller must guarantee that for the duration of execute(), the buffer - * stored in UserBuffer would remain valid. For more detail on buffer - * ownership and lifetime requirements, please refer to zdl::DlSystem::UserBuffer - * documentation. - */ - bool execute(const zdl::DlSystem::UserBufferMap &input, - const zdl::DlSystem::UserBufferMap &output) noexcept; - - - /** - * @brief Regiter Client ION Buffers - * @param[in] A UserMemoryMap of virtual addresses - * - */ - bool registerIonBuffers(const zdl::DlSystem::UserMemoryMap& ionBufferMap) noexcept; - - /** - * @brief Regiter Client ION Buffers - * @param[in] A StringList of ION Buffer names - * - */ - bool deregisterIonBuffers(const zdl::DlSystem::StringList& ionBufferNames) noexcept; - - /** - * @brief Returns the version string embedded at model conversion - * time. - * - * @return Model version string, which is a free-form string - * supplied at the time of the conversion - * - */ - zdl::DlSystem::String getModelVersion() const noexcept; - - /** - * @brief Returns the dimensions of the input data to the model in the - * form of TensorShape. The dimensions in TensorShape corresponds to - * what the tensor dimensions would need to be for an input tensor to - * the model. - * - * @param[in] layer input name. - * - * @note Note that this function only makes sense for networks - * that have a fixed input size. For networks in which the - * input size varies with each call of Execute(), this - * function should not be used. - * - * @note Because the returned type is an Optional instance, it must - * be verified as a boolean true value before being dereferenced. - * - * @return An Optional instance of TensorShape that maintains dimensions, - * matching the tensor dimensions for input to the model, - * where the last entry is the fastest varying dimension, etc. - * - * @see zdl::DlSystem::ITensor - * @see zdl::DlSystem::TensorShape - * @see zdl::DlSystem::Optional - */ - zdl::DlSystem::Optional - getInputDimensions() const noexcept; - zdl::DlSystem::Optional - getInputDimensions(const char *name) const noexcept; - - /** - * @brief Gets the output layer(s) for the network. - * - * Note that the output layers returned by this function may be - * different than those specified when the network was created - * via the zdl::SNPE::SNPEBuilder. For example, if the - * network was created in debug mode with no explicit output - * layers specified, this will contain all layers. - * - * @note Note that because the returned value is an Optional StringList, - * the list must be verified as a boolean true value before being - * dereferenced. - * - * @return A List of output layer names. - * - * @see zdl::DlSystem::Optional - */ - zdl::DlSystem::Optional - getOutputLayerNames() const noexcept; - - /** - * @brief Returns attributes of buffers used to feed input tensors and receive result from output tensors. - * - * @param[in] Tensor name. - * - * @return BufferAttributes of input/output tensor named - */ - zdl::DlSystem::Optional getInputOutputBufferAttributes(const char *name) const noexcept; - - /** - * @brief . - * - * Get the diagnostic logging interface - * - * @note Note that because the returned type is an Optional instance, - * it must be verified as a boolean true value before being - * dereferenced. - * - * @see zdl::DlSystem::Optional - */ - zdl::DlSystem::Optional - getDiagLogInterface() noexcept; - -private: - SNPE(const SNPE&) = delete; - SNPE& operator=(const SNPE&) = delete; - - std::unique_ptr m_Runtime; -}; - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ -}} - -#endif diff --git a/third_party/snpe/include/SNPE/SNPEBuilder.hpp b/third_party/snpe/include/SNPE/SNPEBuilder.hpp deleted file mode 100644 index 5fc7846ced..0000000000 --- a/third_party/snpe/include/SNPE/SNPEBuilder.hpp +++ /dev/null @@ -1,306 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2017-2021 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== - -#ifndef _SNPE_BUILDER_HPP_ -#define _SNPE_BUILDER_HPP_ - -#include "SNPE/SNPE.hpp" -#include "DlSystem/DlEnums.hpp" -#include "DlSystem/UDLFunc.hpp" -#include "DlSystem/DlOptional.hpp" -#include "DlSystem/TensorShapeMap.hpp" -#include "DlSystem/PlatformConfig.hpp" -#include "DlSystem/IOBufferDataTypeMap.hpp" -#include "DlSystem/RuntimeList.hpp" - -namespace zdl { - namespace DlContainer - { - class IDlContainer; - } -} - -struct SNPEBuilderImpl; - - -namespace zdl { namespace SNPE { -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * The builder class for creating SNPE objects. - * Not meant to be extended. - */ -class ZDL_EXPORT SNPEBuilder final -{ -private: - std::unique_ptr<::SNPEBuilderImpl> m_Impl; -public: - - /** - * @brief Constructor of NeuralNetwork Builder with a supplied model. - * - * @param[in] container A container holding the model. - * - * @return A new instance of a SNPEBuilder object - * that can be used to configure and build - * an instance of SNPE. - * - */ - explicit SNPEBuilder( - zdl::DlContainer::IDlContainer* container); - ~SNPEBuilder(); - - /** - * NOTE: DEPRECATED, MAY BE REMOVED IN THE FUTURE. Please use - * setRuntimeProcessorOrder() - * - * @brief Sets the runtime processor. - * - * @param[in] targetRuntimeProcessor The target runtime. - * - * @return The current instance of SNPEBuilder. - */ - SNPEBuilder& setRuntimeProcessor( - zdl::DlSystem::Runtime_t targetRuntimeProcessor); - - /** - * @brief Requests a performance profile. - * - * @param[in] targetRuntimeProfile The target performance profile. - * - * @return The current instance of SNPEBuilder. - */ - SNPEBuilder& setPerformanceProfile( - zdl::DlSystem::PerformanceProfile_t performanceProfile); - - /** - * @brief Sets the profiling level. Default profiling level for - * SNPEBuilder is off. Off and basic only applies to DSP runtime. - * - * @param[in] profilingLevel The target profiling level. - * - * @return The current instance of SNPEBuilder. - */ - SNPEBuilder& setProfilingLevel( - zdl::DlSystem::ProfilingLevel_t profilingLevel); - - /** - * @brief Sets a preference for execution priority. - * - * This allows the caller to give coarse hint to SNPE runtime - * about the priority of the network. SNPE runtime is free to use - * this information to co-ordinate between different workloads - * that may or may not extend beyond SNPE. - * - * @param[in] ExecutionPriorityHint_t The target performance profile. - * - * @return The current instance of SNPEBuilder. - */ - SNPEBuilder& setExecutionPriorityHint( - zdl::DlSystem::ExecutionPriorityHint_t priority); - - /** - * @brief Sets the layers that will generate output. - * - * @param[in] outputLayerNames List of layer names to - * output. An empty list will - * result in only the final - * layer of the model being - * the output layer. The list - * will be copied. - * - * @return The current instance of SNPEBuilder. - */ - SNPEBuilder& setOutputLayers( - const zdl::DlSystem::StringList& outputLayerNames); - - /** - * @brief Sets the output tensor names. - * - * @param[in] outputTensorNames List of tensor names to - * output. An empty list will - * result in producing output for the final - * output tensor of the model. - * The list will be copied. - * - * @return The current instance of SNPEBuilder. - */ - SNPEBuilder& setOutputTensors( - const zdl::DlSystem::StringList& outputTensorNames); - - /** - * @brief Passes in a User-defined layer. - * - * @param udlBundle Bundle of udl factory function and a cookie - * - * @return The current instance of SNPEBuilder. - */ - SNPEBuilder& setUdlBundle( - zdl::DlSystem::UDLBundle udlBundle); - - /** - * @brief Sets whether this neural network will perform inference with - * input from user-supplied buffers, and write output to user-supplied - * buffers. Default behaviour is to use tensors created by - * ITensorFactory. - * - * @param[in] bufferMode Whether to use user-supplied buffer or not. - * - * @return The current instance of SNPEBuilder. - */ - SNPEBuilder& setUseUserSuppliedBuffers( - bool bufferMode); - - /** - * @brief Sets the debug mode of the runtime. - * - * @param[in] debugMode This enables debug mode for the runtime. It - * does two things. For an empty - * outputLayerNames list, all layers will be - * output. It might also disable some internal - * runtime optimizations (e.g., some networks - * might be optimized by combining layers, - * etc.). - * - * @return The current instance of SNPEBuilder. - */ - SNPEBuilder& setDebugMode( - bool debugMode); - - /** - * NOTE: DEPRECATED, MAY BE REMOVED IN THE FUTURE. Please use - * setRuntimeProcessorOrder() - * - * @brief Sets the mode of CPU fallback functionality. - * - * @param[in] mode This flag enables/disables the functionality - * of CPU fallback. When the CPU fallback - * functionality is enabled, layers in model that - * violates runtime constraints will run on CPU - * while the rest of non-violating layers will - * run on the chosen runtime processor. In - * disabled mode, models with layers violating - * runtime constraints will NOT run on the chosen - * runtime processor and will result in runtime - * exception. By default, the functionality is - * enabled. - * - * @return The current instance of SNPEBuilder. - */ - SNPEBuilder& setCPUFallbackMode( - bool mode); - - - /** - * @brief Sets network's input dimensions to enable resizing of - * the spatial dimensions of each layer for fully convolutional networks, - * and the batch dimension for all networks. - * - * @param[in] tensorShapeMap The map of input names and their new dimensions. - * The new dimensions overwrite the input dimensions - * embedded in the model and then resize each layer - * of the model. If the model contains - * layers whose dimensions cannot be resized e.g FullyConnected, - * exception will be thrown when SNPE instance is actually built. - * In general the batch dimension is always resizable. - * After resizing of layers' dimensions in model based - * on new input dimensions, the new model is revalidated - * against all runtime constraints, whose failures may - * result in cpu fallback situation. - * - * @return The current instance of SNPEBuilder. - */ - SNPEBuilder& setInputDimensions(const zdl::DlSystem::TensorShapeMap& inputDimensionsMap); - - /** - * @brief Sets the mode of init caching functionality. - * - * @param[in] mode This flag enables/disables the functionality of init caching. - * When init caching functionality is enabled, a set of init caches - * will be created during network building/initialization process - * and will be added to DLC container. If such DLC container is saved - * by the user, in subsequent network building/initialization processes - * these init caches will be loaded from the DLC so as to reduce initialization time. - * In disable mode, no init caches will be added to DLC container. - * - * @return The current instance of SNPEBuilder. - */ - SNPEBuilder& setInitCacheMode( - bool cacheMode); - - /** - * @brief Returns an instance of SNPE based on the current parameters. - * - * @return A new instance of a SNPE object that can be used - * to execute models or null if any errors occur. - */ - std::unique_ptr build() noexcept; - - /** - * @brief Sets the platform configuration. - * - * @param[in] platformConfig The platform configuration. - * - * @return The current instance of SNPEBuilder. - */ - SNPEBuilder& setPlatformConfig(const zdl::DlSystem::PlatformConfig& platformConfig); - - /** - * @brief Sets network's runtime order of precedence. Example: - * CPU_FLOAT32, GPU_FLOAT16, AIP_FIXED8_TF - * Note:- setRuntimeProcessor() or setCPUFallbackMode() will be silently ignored when - * setRuntimeProcessorOrder() is invoked - * - * @param[in] runtimeList The list of runtime in order of precedence - * - * @return The current instance of SNPEBuilder. - */ - SNPEBuilder& setRuntimeProcessorOrder(const zdl::DlSystem::RuntimeList& runtimeList); - - /** - * @brief Sets the unconsumed tensors as output - * - * @param[in] setOutput This enables unconsumed tensors (i.e) - * outputs which are not inputs to any - * layer (basically dead ends) to be marked - * for output - * - * @return The current instance of SNPEBuilder. - */ - SNPEBuilder& setUnconsumedTensorsAsOutputs( - bool setOutput); - - /** - * @brief Execution terminated when exceeding time limit. - * Only valid for dsp runtime currently. - * - * @param[in] timeout Time limit value - * - * @return The current instance of SNPEBuilder. - */ - SNPEBuilder& setTimeOut( - uint64_t timeout); - - - /** - * @brief Sets the datatype of the buffer. - * Only valid for dsp runtime currently. - * - * @param[in] Map of the buffer names and the datatype that needs to be set. - * - * @return The current instance of SNPEBuilder. - */ - SNPEBuilder& setBufferDataType(const zdl::DlSystem::IOBufferDataTypeMap& dataTypeMap); - -}; -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -}} - -#endif diff --git a/third_party/snpe/include/SNPE/SNPEFactory.hpp b/third_party/snpe/include/SNPE/SNPEFactory.hpp deleted file mode 100644 index 2d78e81b17..0000000000 --- a/third_party/snpe/include/SNPE/SNPEFactory.hpp +++ /dev/null @@ -1,220 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2015-2021 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== - -#ifndef _SNPE_FACTORY_HPP_ -#define _SNPE_FACTORY_HPP_ - -#include "SNPE/SNPE.hpp" -#include "DlSystem/DlEnums.hpp" -#include "DlSystem/UDLFunc.hpp" -#include "DlSystem/ZdlExportDefine.hpp" -#include "DlSystem/DlOptional.hpp" - -namespace zdl { - namespace DlSystem - { - class ITensorFactory; - class IUserBufferFactory; - } - namespace DlContainer - { - class IDlContainer; - } -} - - - -namespace zdl { namespace SNPE { -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * The factory class for creating SNPE objects. - * - */ -class ZDL_EXPORT SNPEFactory -{ -public: - - /** - * Indicates whether the supplied runtime is available on the - * current platform. - * - * @param[in] runtime The target runtime to check. - * - * @return True if the supplied runtime is available; false, - * otherwise. - */ - static bool isRuntimeAvailable(zdl::DlSystem::Runtime_t runtime); - - /** - * Indicates whether the supplied runtime is available on the - * current platform. - * - * @param[in] runtime The target runtime to check. - * - * @param[in] option Extent to perform runtime available check. - * - * @return True if the supplied runtime is available; false, - * otherwise. - */ - static bool isRuntimeAvailable(zdl::DlSystem::Runtime_t runtime, - zdl::DlSystem::RuntimeCheckOption_t option); - - /** - * Gets a reference to the tensor factory. - * - * @return A reference to the tensor factory. - */ - static zdl::DlSystem::ITensorFactory& getTensorFactory(); - - /** - * Gets a reference to the UserBuffer factory. - * - * @return A reference to the UserBuffer factory. - */ - static zdl::DlSystem::IUserBufferFactory& getUserBufferFactory(); - - /** - * Gets the version of the SNPE library. - * - * @return Version of the SNPE library. - * - */ - static zdl::DlSystem::Version_t getLibraryVersion(); - - /** - * Set the SNPE storage location for all SNPE instances in this - * process. Note that this may only be called once, and if so - * must be called before creating any SNPE instances. - * - * @param[in] storagePath Absolute path to a directory which SNPE may - * use for caching and other storage purposes. - * - * @return True if the supplied path was succesfully set as - * the SNPE storage location, false otherwise. - */ - static bool setSNPEStorageLocation(const char* storagePath); - - /** - * @brief Register a user-defined op package with SNPE. - * - * @param[in] regLibraryPath Path to the registration library - * that allows clients to register a set of operations that are - * part of the package, and share op info with SNPE - * - * @return True if successful, False otherwise. - */ - static bool addOpPackage( const std::string& regLibraryPath ); - - /** - * Indicates whether the OpenGL and OpenCL interoperability is supported - * on GPU platform. - * - * @return True if the OpenGL and OpenCl interop is supported; false, - * otherwise. - */ - static bool isGLCLInteropSupported(); - - static const char* getLastError(); - - /** - * Initializes logging with the specified log level. - * initializeLogging with level, is used on Android platforms - * and after successful initialization, SNPE - * logs are printed in android logcat logs. - * - * It is recommended to initializeLogging before creating any - * SNPE instances, in order to capture information related to - * core initialization. If this is called again after first - * time initialization, subsequent calls are ignored. - * Also, Logging can be re-initialized after a call to - * terminateLogging API by calling initializeLogging again. - * - * A typical usage of Logging life cycle can be - * initializeLogging() - * any other SNPE API like isRuntimeAvailable() - * * setLogLevel() - optional - can be called anytime - * between initializeLogging & terminateLogging - * SNPE instance creation, inference, destroy - * terminateLogging(). - * - * Please note, enabling logging can have performance impact. - * - * @param[in] LogLevel_t Log level (LOG_INFO, LOG_WARN, etc.). - * - * @return True if successful, False otherwise. - */ - static bool initializeLogging(const zdl::DlSystem::LogLevel_t& level); - - /** - * Initializes logging with the specified log level and log path. - * initializeLogging with level & log path, is used on non Android - * platforms and after successful initialization, SNPE - * logs are printed in std output & into log files created in the - * log path. - * - * It is recommended to initializeLogging before creating any - * SNPE instances, in order to capture information related to - * core initialization. If this is called again after first - * time initialization, subsequent calls are ignored. - * Also, Logging can be re-initialized after a call to - * terminateLogging API by calling initializeLogging again. - * - * A typical usage of Logging life cycle can be - * initializeLogging() - * any other SNPE API like isRuntimeAvailable() - * * setLogLevel() - optional - can be called anytime - * between initializeLogging & terminateLogging - * SNPE instance creation, inference, destroy - * terminateLogging() - * - * Please note, enabling logging can have performance impact - * - * @param[in] LogLevel_t Log level (LOG_INFO, LOG_WARN, etc.). - * - * @param[in] Path of directory to store logs. - * If path is empty, the default path is "./Log". - * For android, the log path is ignored. - * - * @return True if successful, False otherwise. - */ - static bool initializeLogging(const zdl::DlSystem::LogLevel_t& level, const std::string& logPath); - - /** - * Updates the current logging level with the specified level. - * setLogLevel is optional, called anytime after initializeLogging - * and before terminateLogging, to update the log level set. - * Log levels can be updated multiple times by calling setLogLevel - * A call to setLogLevel() is ignored if it is made before - * initializeLogging() or after terminateLogging() - * - * @param[in] LogLevel_t Log level (LOG_INFO, LOG_WARN, etc.). - * - * @return True if successful, False otherwise. - */ - static bool setLogLevel(const zdl::DlSystem::LogLevel_t& level); - - /** - * Terminates logging. - * - * It is recommended to terminateLogging after initializeLogging - * in order to disable logging information. - * If this is called before initialization or after first time termination, - * calls are ignored. - * - * @return True if successful, False otherwise. - */ - static bool terminateLogging(void); -}; - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ -}} - - -#endif diff --git a/third_party/snpe/include/SNPE/UserBufferList.hpp b/third_party/snpe/include/SNPE/UserBufferList.hpp deleted file mode 100644 index a660bca0f6..0000000000 --- a/third_party/snpe/include/SNPE/UserBufferList.hpp +++ /dev/null @@ -1,49 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2019 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== -#ifndef PSNPE_USERBUFFERLIST_HPP -#define PSNPE_USERBUFFERLIST_HPP - -#include -#include "DlSystem/UserBufferMap.hpp" -#include "DlSystem/ZdlExportDefine.hpp" - -namespace zdl { -namespace PSNPE -{ - -/** @addtogroup c_plus_plus_apis C++ -@{ */ -/** -* @brief . -* -* The class for creating a UserBufferMap container. -* -*/ -class ZDL_EXPORT UserBufferList final -{ -public: - UserBufferList(); - UserBufferList(const size_t size); - void push_back(const zdl::DlSystem::UserBufferMap &userBufferMap); - zdl::DlSystem::UserBufferMap& operator[](const size_t index); - UserBufferList& operator =(const UserBufferList &other); - size_t size() const noexcept; - size_t capacity() const noexcept; - void clear() noexcept; - ~UserBufferList() = default; - -private: - void swap(const UserBufferList &other); - std::vector m_userBufferMaps; - -}; -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -} // namespace PSNPE -} // namespace zdl -#endif //PSNPE_USERBUFFERLIST_HPP diff --git a/third_party/snpe/include/SnpeUdo/UdoBase.h b/third_party/snpe/include/SnpeUdo/UdoBase.h deleted file mode 100644 index 7b2567920e..0000000000 --- a/third_party/snpe/include/SnpeUdo/UdoBase.h +++ /dev/null @@ -1,537 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2019-2021 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== - -#ifndef SNPE_UDO_BASE_H -#define SNPE_UDO_BASE_H - -#include - -// Provide values to use for API version. -#define API_VERSION_MAJOR 1 -#define API_VERSION_MINOR 6 -#define API_VERSION_TEENY 0 - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -// Defines a bitmask of enum values. -typedef uint32_t SnpeUdo_Bitmask_t; -typedef SnpeUdo_Bitmask_t Udo_Bitmask_t; - -// A string of characters, rather than an array of bytes. -// Assumed to be UTF-8. -typedef char* SnpeUdo_String_t; -typedef SnpeUdo_String_t Udo_String_t; - -// The maximum allowable length of a SnpeUdo_String_t in bytes, -// including null terminator. SNPE will truncate strings longer -// than this. -#define SNPE_UDO_MAX_STRING_SIZE 1024 - -/** - * An enum which holds the various error types. - * The error types are divided to classes : - * 0 - 99 : generic errors - * 100 - 200 : errors related to configuration - * - */ -typedef enum -{ - /// No Error - SNPE_UDO_NO_ERROR = 0, UDO_NO_ERROR = 0, - /// Unsupported value for core type - SNPE_UDO_WRONG_CORE = 1, UDO_WRONG_CORE = 1, - /// Invalid attribute/argument passed into UDO API - SNPE_UDO_INVALID_ARGUMENT = 2, UDO_INVALID_ARGUMENT = 2, - /// Unsupported feature error - SNPE_UDO_UNSUPPORTED_FEATURE = 3, UDO_UNSUPPORTED_FEATURE = 3, - /// Error relating to memory allocation - SNPE_UDO_MEM_ALLOC_ERROR = 4, UDO_MEM_ALLOC_ERROR = 4, - /* Configuration Specific errors */ - /// No op with given attributes available in library - SNPE_UDO_WRONG_OPERATION = 100, UDO_WRONG_OPERATION = 100, - /// Unsupported value for core type in UDO configuration - SNPE_UDO_WRONG_CORE_TYPE = 101, UDO_WRONG_CORE_TYPE = 101, - /// Wrong number of params in UDO definition - SNPE_UDO_WRONG_NUM_OF_PARAMS = 102, UDO_WRONG_NUM_OF_PARAMS = 102, - /// Wrong number of dimensions for tensor(s) in UDO definition - SNPE_UDO_WRONG_NUM_OF_DIMENSIONS = 103, UDO_WRONG_NUM_OF_DIMENSIONS = 103, - /// Wrong number of input tensors in UDO definition - SNPE_UDO_WRONG_NUM_OF_INPUTS = 104, UDO_WRONG_NUM_OF_INPUTS = 104, - /// Wrong number of output tensors in UDO definition - SNPE_UDO_WRONG_NUM_OF_OUTPUTS = 105, UDO_WRONG_NUM_OF_OUTPUTS = 105, - SNPE_UDO_PROGRAM_CACHE_NOT_FOUND = 106, UDO_PROGRAM_CACHE_NOT_FOUND = 106, - SNPE_UDO_UNKNOWN_ERROR = 0xFFFFFFFF, UDO_UNKNOWN_ERROR = 0xFFFFFFFF -} SnpeUdo_ErrorType_t; - -typedef SnpeUdo_ErrorType_t Udo_ErrorType_t; - -/** - * An enum which holds the various data types. - * Designed to be used as single values or combined into a bitfield parameter - * (0x1, 0x2, 0x4, etc) - * \n FIXED_XX types are targeted for data in tensors. - * \n UINT / INT types are targeted for scalar params - */ -typedef enum -{ - /// data type: 16-bit floating point - SNPE_UDO_DATATYPE_FLOAT_16 = 0x01, UDO_DATATYPE_FLOAT_16 = 0x01, - /// data type: 32-bit floating point - SNPE_UDO_DATATYPE_FLOAT_32 = 0x02, UDO_DATATYPE_FLOAT_32 = 0x02, - /// data type: 4-bit fixed point - SNPE_UDO_DATATYPE_FIXED_4 = 0x04, UDO_DATATYPE_FIXED_4 = 0x04, - /// data type: 8-bit fixed point - SNPE_UDO_DATATYPE_FIXED_8 = 0x08, UDO_DATATYPE_FIXED_8 = 0x08, - /// data type: 16-bit fixed point - SNPE_UDO_DATATYPE_FIXED_16 = 0x10, UDO_DATATYPE_FIXED_16 = 0x10, - /// data type: 32-bit fixed point - SNPE_UDO_DATATYPE_FIXED_32 = 0x20, UDO_DATATYPE_FIXED_32 = 0x20, - /// data type: 8-bit unsigned integer - SNPE_UDO_DATATYPE_UINT_8 = 0x100, UDO_DATATYPE_UINT_8 = 0x100, - /// data type: 16-bit unsigned integer - SNPE_UDO_DATATYPE_UINT_16 = 0x200, UDO_DATATYPE_UINT_16 = 0x200, - /// data type: 32-bit unsigned integer - SNPE_UDO_DATATYPE_UINT_32 = 0x400, UDO_DATATYPE_UINT_32 = 0x400, - /// data type: 8-bit signed integer - SNPE_UDO_DATATYPE_INT_8 = 0x1000, UDO_DATATYPE_INT_8 = 0x1000, - /// data type: 16-bit signed integer - SNPE_UDO_DATATYPE_INT_16 = 0x2000, UDO_DATATYPE_INT_16 = 0x2000, - /// data type: 32-bit signed integer - SNPE_UDO_DATATYPE_INT_32 = 0x4000, UDO_DATATYPE_INT_32 = 0x4000, - SNPE_UDO_DATATYPE_LAST = 0xFFFFFFFF, UDO_DATATYPE_LAST = 0xFFFFFFFF -} SnpeUdo_DataType_t; - -typedef SnpeUdo_DataType_t Udo_DataType_t; - -/** - * An enum which holds the various layouts. - * Designed to be used as single values or combined into a bitfield parameter - * (0x1, 0x2, 0x4, etc) - */ -typedef enum -{ - /// data layout (4D): NHWC (batch-height-width-channel) - SNPE_UDO_LAYOUT_NHWC = 0x01, UDO_LAYOUT_NHWC = 0x01, - /// data layout (4D): NCHW (batch-channel-height-width) - SNPE_UDO_LAYOUT_NCHW = 0x02, UDO_LAYOUT_NCHW = 0x02, - /// data layout (5D): NDHWC (batch-dimension-height-width-channel) - SNPE_UDO_LAYOUT_NDHWC = 0x04, UDO_LAYOUT_NDHWC = 0x04, - SNPE_UDO_LAYOUT_GPU_OPTIMAL1 = 0x08, UDO_LAYOUT_GPU_OPTIMAL1 = 0x08, - SNPE_UDO_LAYOUT_GPU_OPTIMAL2 = 0x10, UDO_LAYOUT_GPU_OPTIMAL2 = 0x10, - SNPE_UDO_LAYOUT_DSP_OPTIMAL1 = 0x11, UDO_LAYOUT_DSP_OPTIMAL1 = 0x11, - SNPE_UDO_LAYOUT_DSP_OPTIMAL2 = 0x12, UDO_LAYOUT_DSP_OPTIMAL2 = 0x12, - // Indicates no data will be allocated for this tensor. - // Used to specify optional inputs/outputs positionally. - SNPE_UDO_LAYOUT_NULL = 0x13, UDO_LAYOUT_NULL = 0x13, - SNPE_UDO_LAYOUT_LAST = 0xFFFFFFFF, UDO_LAYOUT_LAST = 0xFFFFFFFF -} SnpeUdo_TensorLayout_t; - -typedef SnpeUdo_TensorLayout_t Udo_TensorLayout_t; - -/** - * An enum which holds the UDO library Core type . - * Designed to be used as single values or combined into a bitfield parameter - * (0x1, 0x2, 0x4, etc) - */ -typedef enum -{ - /// Library target IP Core is undefined - SNPE_UDO_CORETYPE_UNDEFINED = 0x00, UDO_CORETYPE_UNDEFINED = 0x00, - /// Library target IP Core is CPU - SNPE_UDO_CORETYPE_CPU = 0x01, UDO_CORETYPE_CPU = 0x01, - /// Library target IP Core is GPU - SNPE_UDO_CORETYPE_GPU = 0x02, UDO_CORETYPE_GPU = 0x02, - /// Library target IP Core is DSP - SNPE_UDO_CORETYPE_DSP = 0x04, UDO_CORETYPE_DSP = 0x04, - SNPE_UDO_CORETYPE_LAST = 0xFFFFFFFF, UDO_CORETYPE_LAST = 0xFFFFFFFF -} SnpeUdo_CoreType_t; - -typedef SnpeUdo_CoreType_t Udo_CoreType_t; - -/** - * An enum to specify the parameter type : Scalar or Tensor - */ -typedef enum -{ - /// UDO static param type: scalar - SNPE_UDO_PARAMTYPE_SCALAR = 0x00, UDO_PARAMTYPE_SCALAR = 0x00, - /// UDO static param type: string - SNPE_UDO_PARAMTYPE_STRING = 0x01, UDO_PARAMTYPE_STRING = 0x01, - /// UDO static param type: tensor - SNPE_UDO_PARAMTYPE_TENSOR = 0x02, UDO_PARAMTYPE_TENSOR = 0x02, - SNPE_UDO_PARAMTYPE_LAST = 0xFFFFFFFF, UDO_PARAMTYPE_LAST = 0xFFFFFFFF -} SnpeUdo_ParamType_t; - -typedef SnpeUdo_ParamType_t Udo_ParamType_t; - -/** - * An enum to specify quantization type - */ -typedef enum -{ - /// Tensor Quantization type: NONE. Signifies unquantized tensor data - SNPE_UDO_QUANTIZATION_NONE = 0x00, UDO_QUANTIZATION_NONE = 0x00, - /// Tensor Quantization type: Tensorflow-style - SNPE_UDO_QUANTIZATION_TF = 0x01, UDO_QUANTIZATION_TF = 0x01, - SNPE_UDO_QUANTIZATION_QMN = 0x02, UDO_QUANTIZATION_QMN = 0x02, - SNPE_UDO_QUANTIZATION_LAST = 0xFFFFFFFF, UDO_QUANTIZATION_LAST = 0xFFFFFFFF -} SnpeUdo_QuantizationType_t; - -typedef SnpeUdo_QuantizationType_t Udo_QuantizationType_t; - -/** - * @brief A struct which is used to provide a version number using 3 values : major, minor, teeny - * - */ -typedef struct -{ - /// version field: major - for backward-incompatible changes - uint32_t major; - /// version field: minor - for backward-compatible feature updates - uint32_t minor; - /// version field: teeny - for minor bug-fixes and clean-up - uint32_t teeny; -} SnpeUdo_Version_t; - -typedef SnpeUdo_Version_t Udo_Version_t; - -/** - * @brief A struct returned from version query, contains the Library version and API version - * - */ -typedef struct -{ - /// Version of UDO library. Controlled by users - SnpeUdo_Version_t libVersion; - /// Version of SNPE UDO API used in compiling library. Determined by SNPE - SnpeUdo_Version_t apiVersion; -} SnpeUdo_LibVersion_t; - -/** - * @brief A struct returned from version query, contains the package version - * - */ -typedef struct -{ - /// Version of UDO API used in package. - Udo_Version_t apiVersion; -} Udo_PkgVersion_t; - -/** - * @brief A union to hold the value of a generic type. Allows defining a parameter struct - * in a generic way, with a "value" location that holds the data regardless of the type. - * - */ -typedef union -{ - /// value type: float - float floatValue; - /// value type: unsigned 32-bit integer - uint32_t uint32Value; - /// value type: signed 32-bit integer - int32_t int32Value; - /// value type: unsigned 16-bit integer - uint16_t uint16Value; - /// value type: signed 16-bit integer - int16_t int16Value; - /// value type: unsigned 8-bit integer - uint8_t uint8Value; - /// value type: signed 8-bit integer - int8_t int8Value; -} SnpeUdo_Value_t; - -typedef SnpeUdo_Value_t Udo_Value_t; - -/** - * @brief A struct which defines a scalar parameter : name, data type, and union of values - * - */ -typedef struct -{ - /// The parameter data type : float, int, etc. - SnpeUdo_DataType_t dataType; - /// a union of specified type which holds the data - SnpeUdo_Value_t dataValue; -} SnpeUdo_ScalarParam_t; - -typedef SnpeUdo_ScalarParam_t Udo_ScalarParam_t; - -/** - * @brief A struct which defines the quantization parameters in case of Tensorflow style quantization - * - */ -typedef struct -{ - /// minimum value of the quantization range of data - float minValue; - /// maximum value of the quantization range of data - float maxValue; -} SnpeUdo_TFQuantize_t; - -typedef SnpeUdo_TFQuantize_t Udo_TFQuantize_t; - -/** - * @brief A struct which defines the quantization type, and union of supported quantization structs - * - */ -typedef struct -{ - /// quantization type (only TF-style currently supported) - SnpeUdo_QuantizationType_t quantizeType; - union - { - /// TF-style min-max quantization ranges - SnpeUdo_TFQuantize_t TFParams; - }; -} SnpeUdo_QuantizeParams_t; - -typedef SnpeUdo_QuantizeParams_t Udo_QuantizeParams_t; - -/** - * @brief A struct which defines the datatype associated with a specified core-type - * This should be used to denote the datatypes for a single tensor info, depending - * on the intended execution core. - * - */ -typedef struct -{ - /// The IP Core - SnpeUdo_CoreType_t coreType; - /// The associated datatype for this coreType - SnpeUdo_DataType_t dataType; -} SnpeUdo_PerCoreDatatype_t; - -typedef SnpeUdo_PerCoreDatatype_t Udo_PerCoreDatatype_t; - -/** - * @brief A struct which defines a tensor parameter : name, data type, layout, quantization, more. - * Also holds a pointer to the tensor data. - * - */ -typedef struct -{ - /// The maximum allowable dimensions of the tensor. The memory held in - /// _tensorData_ is guaranteed to be large enough for this. - uint32_t* maxDimensions; - /// The current dimensions of the tensor. An operation may modify the current - /// dimensions of its output, to indicate cases where the output has been - /// "resized". - /// Note that for static parameters, the current and max dimensions must - /// match. - uint32_t* currDimensions; - /// Quantization params applicable to the tensor. Currently only supports - /// Tensorflow quantization style. - SnpeUdo_QuantizeParams_t quantizeParams; - /// Number of dimensions to the tensor: 3D, 4D, etc. - uint32_t tensorRank; - /// The parameter data type: float, int, etc. - SnpeUdo_DataType_t dataType; - /// The tensor layout type: NCHW, NHWC, etc. - SnpeUdo_TensorLayout_t layout; - /// Opaque pointer to tensor data. User may be required to re-interpret the pointer - /// based on core-specific definitions. - void* tensorData; -} SnpeUdo_TensorParam_t; - -typedef SnpeUdo_TensorParam_t Udo_TensorParam_t; - -/** - * @brief A struct which defines tensor information for activation tensors only - * - * It describes an activation tensor object using its name, the intended layout and the datatype - * it will take depending on the intended runtime core. The repeated field indicates that - * that the tensor info describes several input/output activation tensors, which all share the - * aforementioned properties. - */ -typedef struct -{ - /// The tensor name - SnpeUdo_String_t tensorName; - /// The tensor layout type: NCHW, NHWC, etc. - SnpeUdo_TensorLayout_t layout; - /// The per core datatype: {SNPE_UDO_DATATYPE, SNPE_UDO_CORE_TYPE} - SnpeUdo_PerCoreDatatype_t* perCoreDatatype; - /// A boolean field indicating that this tensorinfo will be repeated e.x for ops such as Concat or Split - bool repeated; - /// A boolean field indicating whether input is static or not. - bool isStatic; -} SnpeUdo_TensorInfo_t; - -typedef SnpeUdo_TensorInfo_t Udo_TensorInfo_t; - -/** - * @brief struct which defines a UDO parameter - a union of scalar, tensor and string parameters - * - */ -typedef struct -{ - /// Type is scalar or tensor - SnpeUdo_ParamType_t paramType; - /// The param name, for example : "offset", "activation_type" - SnpeUdo_String_t paramName; - union - { - /// scalar param value - SnpeUdo_ScalarParam_t scalarParam; - /// tensor param value - SnpeUdo_TensorParam_t tensorParam; - /// string param value - SnpeUdo_String_t stringParam; - }; -} SnpeUdo_Param_t; - -typedef SnpeUdo_Param_t Udo_Param_t; - -/** - * @brief A struct which defines Operation information which is specific for IP core (CPU, GPU, DSP ...) - * - */ -typedef struct -{ - /// The IP Core - SnpeUdo_CoreType_t udoCoreType; - /// Bitmask, defines supported internal calculation types (like FLOAT_32, etc) - /// Based on SnpeUdo_DataType - SnpeUdo_Bitmask_t operationCalculationTypes; -} SnpeUdo_OpCoreInfo_t; - -typedef SnpeUdo_OpCoreInfo_t Udo_OpCoreInfo_t; - -/** - * @brief A struct which defines the common and core-specific Operation information - * - */ -typedef struct -{ - /// Operation type - SnpeUdo_String_t operationType; - /// A bitmask describing which IP Cores (CPU, GPU, DSP ...) support this operation - /// Translated based on SnpeUdo_CoreType - SnpeUdo_Bitmask_t supportedByCores; - /// Number of static parameters defined by the op - uint32_t numOfStaticParams; - /// Array of static parameters. Can be scalar or tensor params - SnpeUdo_Param_t* staticParams; - /// Number of input tensors this op receives - uint32_t numOfInputs; - /// Array of input tensor names to this operation - SnpeUdo_String_t* inputNames; - /// Number of output tensors this op receives - uint32_t numOfOutputs; - /// Array of output tensor names to this operation - SnpeUdo_String_t* outputNames; - /// Number of cores that the op can execute on - uint32_t numOfCoreInfo; - /// Array of per-core information entries - SnpeUdo_OpCoreInfo_t* opPerCoreInfo; - /// Array of input tensor infos for this operation - SnpeUdo_TensorInfo_t* inputInfos; - /// Array of output tensor infos for this operation - SnpeUdo_TensorInfo_t* outputInfos; -} SnpeUdo_OperationInfo_t; - -typedef SnpeUdo_OperationInfo_t Udo_OperationInfo_t; - -/** - * @brief A struct which provides the implementation library info : type, name - * - */ -typedef struct -{ - /// Defines the IP Core that this implementation library is targeting - SnpeUdo_CoreType_t udoCoreType; - /// library name. will be looked at in the standard library path - SnpeUdo_String_t libraryName; -} SnpeUdo_LibraryInfo_t; - -typedef SnpeUdo_LibraryInfo_t Udo_LibraryInfo_t; - -/** - * @brief A struct returned by the registration library and contains information on the UDO package : - * name, operations, libraries, etc. - * - */ -typedef struct -{ - /// A string containing the package name - SnpeUdo_String_t packageName; - /// A bitmask describing supported IP cores (CPU, GPU, DSP ...) - /// Translated based on SnpeUdo_CoreType - SnpeUdo_Bitmask_t supportedCoreTypes; - /// The number of implementation libraries in the package - uint32_t numOfImplementationLib; - /// Array of implementation libraries names/types - SnpeUdo_LibraryInfo_t* implementationLib; - /// A string containing all operation types separated by space - SnpeUdo_String_t operationsString; - /// Number of supported operations - uint32_t numOfOperations; - /// Array of Operation info structs. Each entry describes one - /// Operation (name, params, inputs, outputs) - SnpeUdo_OperationInfo_t* operationsInfo; -} SnpeUdo_RegInfo_t; - -typedef SnpeUdo_RegInfo_t Udo_RegInfo_t; - -/** -* @brief A struct returned by the implementation library and contains information on the -* specific library: name, IP Core, operations, etc. -* -*/ -typedef struct -{ - /// Defines the IP Core that this implementation library is targeting - SnpeUdo_CoreType_t udoCoreType; - /// A string containing the package name - SnpeUdo_String_t packageName; - /// A string containing all operation types separated by space - SnpeUdo_String_t operationsString; - /// Number of supported operations - uint32_t numOfOperations; -} SnpeUdo_ImpInfo_t; - -typedef SnpeUdo_ImpInfo_t Udo_ImpInfo_t; - -/** - * @brief This struct defines an operation. It is used for validation - * or creation of an operation. - * In case of using it for creation, the static params which are tensors - * contain pointers to the real data (weights, for example), and input/output - * tensors also include pointers to the buffers used. - */ -typedef struct -{ - /// The IP Core that the operation is defined for - CPU, GPU, DSP... - SnpeUdo_CoreType_t udoCoreType; - /// Operation type - SnpeUdo_String_t operationType; - /// The number of static parameters provided in the staticParams array. - /// this number has to match the number provided by the UDO Registration library information - uint32_t numOfStaticParams; - /// Array of static parameters - SnpeUdo_Param_t* staticParams; - /// The number of input parameters provided in inputs array. - /// this number has to match the number provided by the UDO Registration library information - uint32_t numOfInputs; - /// Array of input tensors, providing layout, data type, sizes, etc - /// When used to create an operation, also contains the initial location of the data - SnpeUdo_TensorParam_t* inputs; - /// The number of output parameters provided in inputs array. - /// this number has to match the number provided by the UDO Registration library information - uint32_t numOfOutputs; - /// Array of output tensors, providing layout, data type, sizes, etc - /// When used to create an operation, also contains the initial location of the data - SnpeUdo_TensorParam_t* outputs; -} SnpeUdo_OpDefinition_t; - -typedef SnpeUdo_OpDefinition_t Udo_OpDefinition_t; - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -#endif //SNPE_UDO_BASE_H diff --git a/third_party/snpe/include/SnpeUdo/UdoImpl.h b/third_party/snpe/include/SnpeUdo/UdoImpl.h deleted file mode 100644 index a0cb648cf7..0000000000 --- a/third_party/snpe/include/SnpeUdo/UdoImpl.h +++ /dev/null @@ -1,343 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2019-2021 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== - -#ifndef SNPE_UDO_IMPL_H -#define SNPE_UDO_IMPL_H - -#include - -#include "SnpeUdo/UdoShared.h" - -#ifdef __cplusplus -extern "C" -{ -#endif - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -typedef struct _SnpeUdo_OpFactory_t* SnpeUdo_OpFactory_t; -typedef struct _SnpeUdo_Operation_t* SnpeUdo_Operation_t; - -typedef SnpeUdo_OpFactory_t Udo_OpFactory_t; -typedef SnpeUdo_Operation_t Udo_Operation_t; - -/** - * @brief Initialize the shared library's data structures. Calling any other - * library function before this one will result in error. - * - * @param[in] globalInfrastructure Global core-specific infrastructure to be - * used by operations created in this library. The definition and - * semantics of this object will be defined in the corresponding - * implementation header for the core type. - * @return Error code - */ -SnpeUdo_ErrorType_t -SnpeUdo_initImplLibrary(void* globalInfrastructure); - -typedef SnpeUdo_ErrorType_t -(*SnpeUdo_InitImplLibraryFunction_t)(void*); - -/** - * @brief A function to query the API version of the UDO implementation library. - * The function populates a SnpeUdo_LibVersion_t struct, which contains a SnpeUdo_Version_t - * struct for API version and library version. - * - * @param[in, out] version A pointer to struct which contains major, minor, teeny information for - * library and api versions. - * - * @return Error code - */ -SnpeUdo_ErrorType_t -SnpeUdo_getImplVersion(SnpeUdo_LibVersion_t** version); - -typedef SnpeUdo_ErrorType_t -(*SnpeUdo_getImplVersion_t)(SnpeUdo_LibVersion_t** version); - -/** - * @brief Release the shared library's data structures, and invalidate any - * handles returned by the library. The behavior of any outstanding - * asynchronous calls made to this library when this function is called - * are undefined. All library functions (except SnpeUdo_initImplLibrary) will - * return an error after this function has been successfully called. - * - * It should be possible to call SnpeUdo_initImplLibrary after calling this - * function, and re-initialize the library. - * - * @return Error code - */ -SnpeUdo_ErrorType_t -SnpeUdo_terminateImplLibrary(void); - -typedef SnpeUdo_ErrorType_t -(*SnpeUdo_TerminateImplLibraryFunction_t)(void); - - -/** - * @brief A function to query info on the UDO implementation library. - * The function populates a structure which contains information about - * operations that are part of this library - * - * @param[in, out] implementationInfo A pointer to struct which contains information - * on the operations - * - * @return error code - * - */ -SnpeUdo_ErrorType_t -SnpeUdo_getImpInfo(SnpeUdo_ImpInfo_t** implementationInfo); - -typedef SnpeUdo_ErrorType_t -(*SnpeUdo_GetImpInfoFunction_t)(SnpeUdo_ImpInfo_t** implementationInfo); - -typedef SnpeUdo_GetImpInfoFunction_t Udo_GetImpInfoFunction_t; - -/** - * @brief A function to create an operation factory. - * The function receives the operation type, and an array of static parameters, - * and returns operation factory handler - * - * @param[in] udoCoreType The Core type to create the operation on. An error will - * be returned if this does not match the core type of the library. - * - * @param[in] perFactoryInfrastructure CreateOpFactory infrastructure appropriate to this - * core type. The definition and semantics of this object will be defined - * in the corresponding implementation header for the core type. - * - * @param[in] operationType A string containing Operation type. for example "MY_CONV" - * - * @param[in] numOfStaticParams The number of static parameters. - * - * @param[in] staticParams Array of static parameters - * - * @param[in,out] opFactory Handler to Operation Factory, to be used when creating operations - * - * @return Error Code - */ -SnpeUdo_ErrorType_t -SnpeUdo_createOpFactory(SnpeUdo_CoreType_t udoCoreType, - void* perFactoryInfrastructure, - SnpeUdo_String_t operationType, - uint32_t numOfStaticParams, - SnpeUdo_Param_t* staticParams, - SnpeUdo_OpFactory_t* opFactory); - -typedef SnpeUdo_ErrorType_t -(*SnpeUdo_CreateOpFactoryFunction_t)(SnpeUdo_CoreType_t, - void*, - SnpeUdo_String_t, - uint32_t, - SnpeUdo_Param_t*, - SnpeUdo_OpFactory_t*); - -typedef SnpeUdo_CreateOpFactoryFunction_t Udo_CreateOpFactoryFunction_t; - -/** - * @brief A function to release the resources allocated for an operation factory - * created by this library. - * - * @param[in] factory The operation factory to release. Upon success this handle will be invalidated. - * - * @return Error Code - */ -SnpeUdo_ErrorType_t -SnpeUdo_releaseOpFactory(SnpeUdo_OpFactory_t opFactory); - -typedef SnpeUdo_ErrorType_t -(*SnpeUdo_ReleaseOpFactoryFunction_t)(SnpeUdo_OpFactory_t); - -typedef SnpeUdo_ReleaseOpFactoryFunction_t Udo_ReleaseOpFactoryFunction_t; - -/** - * @brief A function to create an operation from the factory. - * The function receives array of inputs and array of outputs, and creates an operation - * instance, returning the operation instance handler. - * - * @param[in] opFactory OpFactory instance containing the parameters for this operation. - * - * @param[in] perOpInfrastructure Per-Op infrastructure for this operation. The definition - * and semantics of this object will be defined in the implementation header - * appropriate to this core type. - * - * @param[in] numOfInputs The number of input tensors this operation will receive. - * - * @param[in] inputs Array of input tensors, providing both the sizes and initial - * location of the data. - * - * @param[in] numOfOutputs Number of output tensors this operation will produce. - * - * @param[in] outputs Array of output tensors, providing both the sizes and - * initial location of the data. - * - * @param[in,out] operation Handle for newly created operation instance. - * - * @return Error Code - */ -SnpeUdo_ErrorType_t -SnpeUdo_createOperation(SnpeUdo_OpFactory_t opFactory, - void* perOpInfrastructure, - uint32_t numOfInputs, - SnpeUdo_TensorParam_t* inputs, - uint32_t numOfOutputs, - SnpeUdo_TensorParam_t* outputs, - SnpeUdo_Operation_t* operation); - -typedef SnpeUdo_ErrorType_t -(*SnpeUdo_CreateOperationFunction_t)(SnpeUdo_OpFactory_t, - void*, - uint32_t, - SnpeUdo_TensorParam_t*, - uint32_t, - SnpeUdo_TensorParam_t*, - SnpeUdo_Operation_t*); - -typedef SnpeUdo_CreateOperationFunction_t Udo_CreateOperationFunction_t; - -/** - * @brief A pointer to notification function. - * - * The notification function supports the non-blocking (e.g. asynchronous) execution use-case. - * In case an "executeUdoOp" function is called with "blocking" set to zero, and a - * notify function, this function will be called by the implementation library at the - * end of execution. The implementation library will pass the notify function the ID - * that was provided to it when "executeUdoOp" was called. - * - * @param[in] ID 32-bit value, that was provided to executeUdoOp by the calling entity. - * Can be used to track the notifications, in case of multiple execute calls issued. - * - * @return Error code - * - */ -typedef SnpeUdo_ErrorType_t -(*SnpeUdo_ExternalNotify_t)(const uint32_t ID); - -typedef SnpeUdo_ExternalNotify_t Udo_ExternalNotify_t; - -/** - * @brief Operation execution function. - * - * Calling this function will run the operation on set of inputs, generating a set of outputs. - * The call can be blocking (synchronous) or non-blocking (asynchronous). To support the - * non-blocking mode, the calling entity can pass an ID and a notification function. - * At the end of the execution this notification function would be called, passing it the ID. - * NOTE: Asynchronous execution mode not supported in this release. - * - * @param[in] operation handle to the operation on which execute is invoked - * @param[in] blocking flag to indicate execution mode. - * If set, execution is blocking, - * e.g SnpeUdo_executeOp call does not return until execution is done. - * If not set, SnpeUdo_executeOp returns immediately, and the - * library will call the notification function (if set) when execution is done. - * - * @param[in] ID 32-bit number that can be used by the calling entity to track execution - * in case of non-blocking execution. - * For example, it can be a sequence number, increased by one on each call. - * - * @param[in] notifyFunc Pointer to notification function. if the pointer is set, and execution is - * non-blocking, the library will call this function at end of execution, - * passing the number provided as ID - * - * @return Error code - * - */ -SnpeUdo_ErrorType_t -SnpeUdo_executeOp(SnpeUdo_Operation_t operation, - bool blocking, - const uint32_t ID, - SnpeUdo_ExternalNotify_t notifyFunc); - -typedef SnpeUdo_ErrorType_t -(*SnpeUdo_ExecuteOpFunction_t)(SnpeUdo_Operation_t, - bool, - const uint32_t, - SnpeUdo_ExternalNotify_t); - -typedef SnpeUdo_ExecuteOpFunction_t Udo_ExecuteOpFunction_t; - -/** - * @brief A function to setting the inputs & outputs. part of SnpeUdo_Operation struct, - * returned from creation of a new operation instance. - * Not supported in this release. - * - * This function allows the calling entity to change some of the inputs and outputs - * between calls to execute. - * Note that the change is limited to changing the pointer to the tensor data only. - * Any other change may be rejected by the implementation library, causing - * immediate invalidation of the operation instance - * - * @param[in] operation Operation on which IO tensors are set - * - * @param[in] inputs array of tensor parameters. The calling entity may provide a subset of the - * operation inputs, providing only those that it wants to change. - * - * @param[in] outputs array of tensor parameters. The calling entity may provide a subset of the - * operation outputs, providing only those that it wants to change. - * - * @return Error code - * - */ -SnpeUdo_ErrorType_t -SnpeUdo_setOpIO(SnpeUdo_Operation_t operation, - SnpeUdo_TensorParam_t* inputs, - SnpeUdo_TensorParam_t* outputs); - -typedef SnpeUdo_ErrorType_t -(*SnpeUdo_SetOpIOFunction_t)(SnpeUdo_Operation_t, - SnpeUdo_TensorParam_t*, - SnpeUdo_TensorParam_t*); - -typedef SnpeUdo_SetOpIOFunction_t Udo_SetOpIOFunction_t; - -/** - * @brief A function to return execution times. - * - * This function can be called to query the operation execution times on the IP core - * on which the operation is run. The time is provided in micro-seconds - * - * @param[in] operation Handle to operation whose execution time is being profiled - * - * @param[in,out] executionTime pointer to a uint32 value.This function writes the operation - * execution time in usec into this value. - * - * @return Error code - * - */ -SnpeUdo_ErrorType_t -SnpeUdo_profileOp(SnpeUdo_Operation_t operation, uint32_t *executionTime); - -typedef SnpeUdo_ErrorType_t -(*SnpeUdo_ProfileOpFunction_t)(SnpeUdo_Operation_t, uint32_t*); - -typedef SnpeUdo_ProfileOpFunction_t Udo_ProfileOpFunction_t; - -/** - * @brief A function to release the operation instance - * \n When it is called, the implementation library needs to release all resources - * allocated for this operation instance. - * \n Note that all function pointers which are part of SnpeUdo_Operation become - * invalid once releaseUdoOp call returns. - * - * @param[in] operation Handle to operation to be released - * @return Error code - * - */ -SnpeUdo_ErrorType_t -SnpeUdo_releaseOp(SnpeUdo_Operation_t operation); - -typedef SnpeUdo_ErrorType_t -(*SnpeUdo_ReleaseOpFunction_t)(SnpeUdo_Operation_t); - -typedef SnpeUdo_ReleaseOpFunction_t Udo_ReleaseOpFunction_t; - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -#ifdef __cplusplus -} // extern "C" -#endif - -#endif //SNPE_UDO_IMPL_H diff --git a/third_party/snpe/include/SnpeUdo/UdoImplCpu.h b/third_party/snpe/include/SnpeUdo/UdoImplCpu.h deleted file mode 100644 index 3bbe0638e6..0000000000 --- a/third_party/snpe/include/SnpeUdo/UdoImplCpu.h +++ /dev/null @@ -1,44 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2019-2020 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== - -// Header to be used by a CPU UDO Implementation library - -#ifndef SNPE_UDO_IMPL_CPU_H -#define SNPE_UDO_IMPL_CPU_H - -#include - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * @brief This struct provides the infrastructure needed by a developer of - * CPU UDO Implementation library. - * - * The framework/runtime which loads the CPU UDO implementation library provides - * this infrastructure data to the loaded library at the time of op factory creation. - * as an opaque pointer. It contains hooks for the UDO library to invoke supported - * functionality at the time of execution - * - * @param getData function pointer to retrieve raw tensor data from opaque pointer - * passed into the UDO when creating an instance. - * @param getDataSize function pointer to retrieve tensor data size from opaque pointer - */ - -typedef struct -{ - /// function pointer to retrieve raw tensor data from opaque pointer - /// passed into the UDO when creating an instance. - float* (*getData)(void*); - /// function pointer to retrieve tensor data size from opaque pointer - size_t (*getDataSize) (void*); -} SnpeUdo_CpuInfrastructure_t; - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -#endif // SNPE_UDO_IMPL_CPU_H \ No newline at end of file diff --git a/third_party/snpe/include/SnpeUdo/UdoImplDsp.h b/third_party/snpe/include/SnpeUdo/UdoImplDsp.h deleted file mode 100644 index b97a649320..0000000000 --- a/third_party/snpe/include/SnpeUdo/UdoImplDsp.h +++ /dev/null @@ -1,207 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2019-2021 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== - -//============================================================================== -/* - * THIS HEADER FILE IS COPIED FROM HEXAGON-NN PROJECT - * - */ -//============================================================================== - - -// Header to be used by a DSP Hexnn UDO Implementation library - -#ifndef SNPE_UDO_IMPL_DSP_H -#define SNPE_UDO_IMPL_DSP_H -#include -#include "SnpeUdo/UdoImpl.h" - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * @brief A function to validate that a set of params is supported by an operation - * This function is HexNN specific, use case is when registration library is not in use. - * Optional function. - * - * @param[in] operationType Operation type - * @param[in] numOfStaticParams Number of static params defined by the op - * @param[in] staticParams Array of static params to the op - * @return Error code, indicating if the operation can be created on this set of configuration or not. - * - */ - -SnpeUdo_ErrorType_t -SnpeUdo_validateOperation (SnpeUdo_String_t operationType, - uint32_t numOfStaticParams, - const SnpeUdo_Param_t* staticParams); - -typedef SnpeUdo_ErrorType_t (*SnpeUdo_ValidateOperationFunction_t) (SnpeUdo_String_t, - uint32_t, - const SnpeUdo_Param_t*); - -typedef SnpeUdo_ValidateOperationFunction_t Udo_ValidateOperationFunction_t; - -// enum used for indicating input/outout tensor data layouts on DSP, plain vs d32 -typedef enum { - SNPE_UDO_DSP_TENSOR_LAYOUT_PLAIN = 0x00, UDO_DSP_TENSOR_LAYOUT_PLAIN = 0x00, - SNPE_UDO_DSP_TENSOR_LAYOUT_D32 = 0x01, UDO_DSP_TENSOR_LAYOUT_D32 = 0x01 -} SnpeUdo_HexNNTensorLayout_t; - -typedef SnpeUdo_HexNNTensorLayout_t Udo_HexNNTensorLayout_t; - -/** - * @brief A function to query numbers of inputs and outputs, - * quantization type of each input and each output as arrays, - * and data layout (plain vs d32) of each input and each output as arrays - * of an operation. - * inputsQuantTypes and inputsLayouts should point to arrays of size numOfInputs - * outputsQuantTypes and outputsLayouts should point to arrays of size numOfOutputs - * - * Note: inputsLayouts and inputsLayouts can point to NULL, in this case, it is - * assumed all inputs and/or outputs have plain data layouts, i.e. no D32 - * - * @param[in] operationType Operation type - * @param[in] numOfStaticParams Number of static params defined by the op - * @param[in] staticParams Array of static params to the op - * @param[in,out] numOfInputs Number of input tensors to the op - * @param[in,out] inputsQuantTypes Array of Quantization info for each input tensor - * @param[in,out] inputsLayouts Array of layout type for each input tensor - * @param[in,out] numOfOutputs Number of output tensors to the op - * @param[in,out] outputsQuantTypes Array of Quantization info for each output tensor - * @param[in,out] outputsLayouts Array of layout type for each output tensor - * @return error code, indicating status of query - */ - -SnpeUdo_ErrorType_t -SnpeUdo_queryOperation (SnpeUdo_String_t operationType, - uint32_t numOfStaticParams, - const SnpeUdo_Param_t* staticParams, - uint32_t* numOfInputs, - SnpeUdo_QuantizationType_t** inputsQuantTypes, - SnpeUdo_HexNNTensorLayout_t** inputsLayouts, - uint32_t* numOfOutputs, - SnpeUdo_QuantizationType_t** outputsQuantTypes, - SnpeUdo_HexNNTensorLayout_t** outputsLayouts); - -typedef SnpeUdo_ErrorType_t (*SnpeUdo_QueryOperationFunction_t) (SnpeUdo_String_t, - uint32_t, - const SnpeUdo_Param_t*, - uint32_t*, - SnpeUdo_QuantizationType_t**, - SnpeUdo_HexNNTensorLayout_t**, - uint32_t*, - SnpeUdo_QuantizationType_t**, - SnpeUdo_HexNNTensorLayout_t**); - -typedef SnpeUdo_QueryOperationFunction_t Udo_QueryOperationFunction_t; - -// Global infrastructure functions supported by Hexagon-NN v2 -typedef void (*workerThread_t) (void* perOpInfrastructure, void* userData); -typedef int (*udoSetOutputTensorSize_t) (void* perOpInfrastructure, uint32_t outIdx, uint32_t size); -typedef int (*udoGetInputD32Paddings_t) (void* perOpInfrastructure, uint32_t inIdx, - uint32_t* heightPadBefore, uint32_t* heightPadAfter, - uint32_t* widthPadBefore, uint32_t* widthPadAfter, - uint32_t* depthPadBefore, uint32_t* depthPadAfter); -typedef int (*udoSetOutputD32ShapeSizePaddings_t) (void* perOpInfrastructure, uint32_t outIdx, - uint32_t batch, - uint32_t height, uint32_t heightPadBefore, uint32_t heightPadAfter, - uint32_t width, uint32_t widthPadBefore, uint32_t widthPadAfter, - uint32_t depth, uint32_t depthPadBefore, uint32_t depthPadAfter, - SnpeUdo_DataType_t dataType); -typedef void* (*udoMemalign_t) (size_t n, size_t size); -typedef void* (*udoMalloc_t) (size_t size); -typedef void* (*udoCalloc_t) (size_t n, size_t size); -typedef void (*udoFree_t) (void* ptr); -typedef uint32_t (*udoGetVtcmSize_t) (void* perOpInfrastructure); -typedef void* (*udoGetVtcmPtr_t) (void* perOpInfrastructure); -typedef uint32_t (*udoVtcmIsReal_t) (void* perOpInfrastructure); -typedef void (*udoRunWorkerThreads_t) (void* perOpInfrastructure, uint32_t nThreads, workerThread_t w, void* userData); - -typedef struct hexNNv2GlobalInfra { - udoSetOutputTensorSize_t udoSetOutputTensorSize; - udoGetInputD32Paddings_t udoGetInputD32Paddings; - udoSetOutputD32ShapeSizePaddings_t udoSetOutputD32ShapeSizePaddings; - udoMemalign_t udoMemalign; - udoMalloc_t udoMalloc; - udoCalloc_t udoCalloc; - udoFree_t udoFree; - udoGetVtcmSize_t udoGetVtcmSize; - udoGetVtcmPtr_t udoGetVtcmPtr; - udoVtcmIsReal_t udoVtcmIsReal; - udoRunWorkerThreads_t udoRunWorkerThreads; -} SnpeUdo_HexNNv2GlobalInfra_t; - -typedef SnpeUdo_HexNNv2GlobalInfra_t Udo_HexNNv2GlobalInfra_t; - -// hexnn types -typedef enum hexnnInfraType { - UDO_INFRA_HEXNN_V2, - UDO_INFRA_HEXNN_V3 // reserved, do not use -} SnpeUdo_HexNNInfraType_t; - -typedef SnpeUdo_HexNNInfraType_t Udo_HexNNInfraType_t; - -typedef struct { - Udo_CreateOpFactoryFunction_t create_op_factory; - Udo_CreateOperationFunction_t create_operation; - Udo_ExecuteOpFunction_t execute_op; - Udo_ReleaseOpFunction_t release_op; - Udo_ReleaseOpFactoryFunction_t release_op_factory; - Udo_ValidateOperationFunction_t validate_op; - Udo_QueryOperationFunction_t query_op; -} udo_func_package_t; - -/** - * @brief Infrastructures needed by a developer of DSP Hexnn UDO Implementation library. - * - * The framework/runtime which loads the Hexnn UDO implementation library provides - * this infrastructure to the loaded library by calling "SnpeUdo_initImplLibrary" - * function, and passing it (cast to void*). The Hexnn UDO library is expected - * to cast it back to this structure. - * - */ -typedef struct dspGlobalInfrastructure { - SnpeUdo_Version_t dspInfraVersion; // api version - SnpeUdo_HexNNInfraType_t infraType; - SnpeUdo_HexNNv2GlobalInfra_t hexNNv2Infra; -} SnpeUdo_DspGlobalInfrastructure_t; - -typedef SnpeUdo_DspGlobalInfrastructure_t Udo_DspGlobalInfrastructure_t; - -/** - * hexnn v2 per op factory infrastructure - * - * The framework/runtime passes per op factory infrastructure as a void pointer - * to HexNN UDO implementation library by calling function "SnpeUdo_createOpFactory". - * UDO implementation library is expected to cast it back to this following struct. - * - */ -typedef struct hexnnv2OpFactoryInfra { - unsigned long graphId; -} SnpeUdo_HexNNv2OpFactoryInfra_t; - -typedef SnpeUdo_HexNNv2OpFactoryInfra_t Udo_HexNNv2OpFactoryInfra_t; - -/** - * hexnn v2 per operation infrastructure - * - * The framework/runtime passes per operation infrastructure as a void pointer - * to HexNN UDO implementation library by calling function "SnpeUdo_createOperation". - * UDO implementation library is expected to cast it to the following type and save it. - * - * This is needed to be passed back into some functions from global infrastructure. - * - */ -typedef void* SnpeUdo_HexNNv2OpInfra_t; - -typedef SnpeUdo_HexNNv2OpInfra_t Udo_HexNNv2OpInfra_t; - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -#endif // SNPE_UDO_IMPL_DSP_H diff --git a/third_party/snpe/include/SnpeUdo/UdoImplGpu.h b/third_party/snpe/include/SnpeUdo/UdoImplGpu.h deleted file mode 100644 index 1af654d110..0000000000 --- a/third_party/snpe/include/SnpeUdo/UdoImplGpu.h +++ /dev/null @@ -1,112 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2019-2020 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== - -// Header to be used by a GPU UDO Implementation library - -#ifndef SNPE_UDO_IMPL_GPU_H -#define SNPE_UDO_IMPL_GPU_H - -#include "CL/cl.h" -#include "SnpeUdo/UdoBase.h" - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * This header defines version 0.0.0 of the GPU UDO Infrastructure. - * It defines the interpretation of the global and per-OpFactory infrastructure pointers - * as well as the interpretation of tensorData pointers. - * - * The per-Operation infrastructure pointer is defined to be null, and should not be used. - * - * The SnpeUdoTensorParam_t struct below provides the interpretation for - * the tensorData opaque pointer for SnpeUdoTensorParams representing inputs or outputs. - * - * The tensorData opaque pointer populated in SnpeUdoScalarParam_t structs should be interpreted - * as a host-readable data pointer. - * - */ - -/** - * @brief Function to retrieve opencl program from Program Cache repository. - * @param programCache is opaque pointer to Program Cache repository provided by - * SNPE GPU UDO runtime. - * @param programName is name associated with opencl program for UDO. - * @param program is pointer to opencl program which will be populated with - * valid opencl program if found in Program Cache repository. - * @return SnpeUdo_ErrorType_t is error type returned. SNPE_UDO_NO_ERROR is returned - * on success. - */ -typedef SnpeUdo_ErrorType_t (*SnpeUdo_getProgram_t) - (void* programCache, const char* programName, cl_program* program); - -/** - * @brief Function to store valid opencl program in Program Cache repository. - * @param programCache is opaque pointer to Program Cache repository provided by - * SNPE GPU UDO runtime. - * @param programName is name associated with opencl program for UDO. - * @param program is valid opencl program after program is built. - * @return SnpeUdo_ErrorType_t is error type returned. SNPE_UDO_NO_ERROR is returned - * on success. - * */ -typedef SnpeUdo_ErrorType_t (*SnpeUdo_storeProgram_t) - (void* programCache, const char * programName, cl_program program); - -/** - * @brief Global Infrastructure Definition for GPU UDO Implementations. - */ -typedef struct { - // Infrastructure definition version. This header is 0.0.0 - SnpeUdo_Version_t gpuInfraVersion; - SnpeUdo_getProgram_t SnpeUdo_getProgram; - SnpeUdo_storeProgram_t SnpeUdo_storeProgram; -} SnpeUdo_GpuInfrastructure_t; - -/** - * @brief Per OpFactory Infrastructure Definition for GPU UDO Implementations. - * @note This version of the infrastructure definition guarantees that the same - * Per OpFactory infrastructure pointer will be provided to all OpFactories - * in the same network. - */ -typedef struct -{ - cl_context context; - cl_command_queue commandQueue; - void* programCache; -} SnpeUdo_GpuOpFactoryInfrastructure_t; - -/** - * @brief Opaque tensorData definition for operation inputs and outputs. - * - * The following is a list of all SnpeUdoTensorLayout_t values supported by the - * GPU UDO implementation, and how the parameters of the struct should be - * interpreted in each case: - * - * SNPE_UDO_LAYOUT_NHWC: - * mem shall be single-element array, pointing to a cl buffer memory object. - * the dimensions of this object match the dimensions specified in the encompassing - * SnpeUdoTensorParam_t's currDimensions. - * - * memCount shall be 1. - * - * paddedRank and paddedDimensions are undefined and shall be ignored by the UDO - * implementation. - * - */ -typedef struct -{ - cl_mem* mem; - uint32_t memCount; - uint32_t paddedRank; - uint32_t* paddedDimensions; - -} SnpeUdo_GpuTensorData_t; - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -#endif // SNPE_UDO_IMPL_GPU_H diff --git a/third_party/snpe/include/SnpeUdo/UdoReg.h b/third_party/snpe/include/SnpeUdo/UdoReg.h deleted file mode 100644 index a5d2398833..0000000000 --- a/third_party/snpe/include/SnpeUdo/UdoReg.h +++ /dev/null @@ -1,108 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2019-2020 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== - -#ifndef SNPE_UDO_REG_H -#define SNPE_UDO_REG_H - -#include "SnpeUdo/UdoShared.h" - -#ifdef __cplusplus -extern "C" -{ -#endif - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * @brief Initialize the shared library's data structures. Calling any other - * library function before this one will result in an error being returned. - * - * @return Error code - */ -SnpeUdo_ErrorType_t -SnpeUdo_initRegLibrary(void); - -typedef SnpeUdo_ErrorType_t -(*SnpeUdo_InitRegLibraryFunction_t)(void); - -/** - * @brief A function to query the API version of the UDO registration library. - * The function populates a SnpeUdo_LibVersion_t struct, which contains a SnpeUdo_Version_t - * struct for API version and library version. - * - * @param[in, out] version A pointer to struct which contains major, minor, teeny information for - * library and api versions. - * - * @return Error code - */ -SnpeUdo_ErrorType_t -SnpeUdo_getRegLibraryVersion(SnpeUdo_LibVersion_t** version); - -typedef SnpeUdo_ErrorType_t -(*SnpeUdo_getRegLibraryVersion_t)(SnpeUdo_LibVersion_t** version); - -/** - * @brief Release the shared library's data structures, and invalidate any - * handles returned by the library. The behavior of any outstanding - * asynchronous calls made to this library when this function is called - * are undefined. All library functions (except SnpeUdo_InitRegLibrary) will - * return an error after this function has been successfully called. - * - * It should be possible to call SnpeUdo_InitRegLibrary after calling this - * function, and re-initialize the library. - * - * @return Error code - */ -SnpeUdo_ErrorType_t -SnpeUdo_terminateRegLibrary(void); - -typedef SnpeUdo_ErrorType_t -(*SnpeUdo_TerminateRegLibraryFunction_t)(void); - - -/** - * @brief A function to query the info on the UDO set. - * The function populates a structure which contains information about - * the package and operations contained in it. - * - * @param[in, out] registrationInfo A struct which contains information on the set of UDOs - * - * @return Error code - * - */ -SnpeUdo_ErrorType_t -SnpeUdo_getRegInfo(SnpeUdo_RegInfo_t** registrationInfo); - -typedef SnpeUdo_ErrorType_t -(*SnpeUdo_GetRegInfoFunction_t)(SnpeUdo_RegInfo_t** registrationInfo); - -/** - * @brief A function to validate that a set of params is supported by an operation - * The function receives an operation definition struct, and returns if this configuration is - * supported (e.g. if an operation can be created using this configuration) - * - * @param[in] opDefinition A struct of SnpeUdo_OpDefinition type, containing the information needed to - * validate that an operation can be created with this configuration. - * - * @return Error code, indicating is the operation can be created on this set or not. - * - */ -SnpeUdo_ErrorType_t -SnpeUdo_validateOperation(SnpeUdo_OpDefinition_t* opDefinition); - -typedef SnpeUdo_ErrorType_t -(*SnpeUdo_ValidateOperationFunction_t)(SnpeUdo_OpDefinition_t* opDefinition); - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -#ifdef __cplusplus -} // extern "C" -#endif - -#endif //SNPE_UDO_REG_H diff --git a/third_party/snpe/include/SnpeUdo/UdoShared.h b/third_party/snpe/include/SnpeUdo/UdoShared.h deleted file mode 100644 index 418d9db9e2..0000000000 --- a/third_party/snpe/include/SnpeUdo/UdoShared.h +++ /dev/null @@ -1,48 +0,0 @@ -//============================================================================== -// -// Copyright (c) 2019-2021 Qualcomm Technologies, Inc. -// All Rights Reserved. -// Confidential and Proprietary - Qualcomm Technologies, Inc. -// -//============================================================================== - -#ifndef SNPE_UDO_SHARED_H -#define SNPE_UDO_SHARED_H - -#include "SnpeUdo/UdoBase.h" - -#ifdef __cplusplus -extern "C" -{ -#endif - -/** @addtogroup c_plus_plus_apis C++ -@{ */ - -/** - * @brief A function to return the various versions as they relate to the UDO - * The function returns a struct containing the the following: - * libVersion: the version of the implementation library compiled for the UDO. Set by user - * apiVersion: the version of the UDO API used in compiling the implementation library. - * Set by SNPE - * - * @param[in, out] version A pointer to Version struct of type SnpeUdo_LibVersion_t - * - * @return Error code - * - */ -SnpeUdo_ErrorType_t -SnpeUdo_getVersion (SnpeUdo_LibVersion_t** version); - -typedef SnpeUdo_ErrorType_t -(*SnpeUdo_GetVersionFunction_t) (SnpeUdo_LibVersion_t** version); - -typedef SnpeUdo_GetVersionFunction_t Udo_GetVersionFunction_t; - -#ifdef __cplusplus -} // extern "C" -#endif - -/** @} */ /* end_addtogroup c_plus_plus_apis C++ */ - -#endif // SNPE_UDO_SHARED_H diff --git a/third_party/snpe/larch64 b/third_party/snpe/larch64 deleted file mode 120000 index 2e2a1c315b..0000000000 --- a/third_party/snpe/larch64 +++ /dev/null @@ -1 +0,0 @@ -aarch64-ubuntu-gcc7.5 \ No newline at end of file diff --git a/third_party/snpe/x86_64 b/third_party/snpe/x86_64 deleted file mode 120000 index 700025efab..0000000000 --- a/third_party/snpe/x86_64 +++ /dev/null @@ -1 +0,0 @@ -x86_64-linux-clang \ No newline at end of file diff --git a/third_party/snpe/x86_64-linux-clang/libHtpPrepare.so b/third_party/snpe/x86_64-linux-clang/libHtpPrepare.so deleted file mode 100644 index 20d1377a01..0000000000 --- a/third_party/snpe/x86_64-linux-clang/libHtpPrepare.so +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:c4c33680010a8c7b2eef33e809844c0ad1d5ab0f0ec37abd49d924204670b357 -size 13556072 diff --git a/third_party/snpe/x86_64-linux-clang/libSNPE.so b/third_party/snpe/x86_64-linux-clang/libSNPE.so deleted file mode 100644 index 0367b1106b..0000000000 --- a/third_party/snpe/x86_64-linux-clang/libSNPE.so +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:024891d2e4e4e265a1e7e72b27bad41ee6ae077d2197f45959bb32f8071dc8cf -size 5350008 diff --git a/third_party/snpe/x86_64-linux-clang/libomp.so b/third_party/snpe/x86_64-linux-clang/libomp.so deleted file mode 100755 index db98cba162..0000000000 --- a/third_party/snpe/x86_64-linux-clang/libomp.so +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:f4784aa68e7ebdbe97db732eab87618b0a5fb73abeab4daed5476e01829b0e6e -size 759208 diff --git a/tinygrad b/tinygrad deleted file mode 120000 index cb003823c6..0000000000 --- a/tinygrad +++ /dev/null @@ -1 +0,0 @@ -tinygrad_repo/tinygrad \ No newline at end of file diff --git a/tinygrad_repo b/tinygrad_repo index 519dec6677..ac1632ab96 160000 --- a/tinygrad_repo +++ b/tinygrad_repo @@ -1 +1 @@ -Subproject commit 519dec6677f98718ee4f2d07be1936eb91dde73b +Subproject commit ac1632ab966c77ba96a7048b893a30f1a714dc87 diff --git a/tools/Brewfile b/tools/Brewfile new file mode 100644 index 0000000000..af610be75d --- /dev/null +++ b/tools/Brewfile @@ -0,0 +1,15 @@ +brew "git-lfs" +brew "capnp" +brew "coreutils" +brew "eigen" +brew "ffmpeg" +brew "glfw" +brew "libusb" +brew "libtool" +brew "llvm" +brew "openssl@3.0" +brew "qt@5" +brew "zeromq" +cask "gcc-arm-embedded" +brew "portaudio" +brew "gcc@13" diff --git a/tools/CTF.md b/tools/CTF.md index 32891cd389..2b877a0e25 100644 --- a/tools/CTF.md +++ b/tools/CTF.md @@ -5,16 +5,16 @@ Welcome to the first part of the comma CTF! * there's 2 flags in each segment, with roughly increasing difficulty * everything you'll need to find the flags is in the openpilot repo * grep is also your friend - * first, [setup](https://github.com/commaai/openpilot/tree/master/tools#setup-your-pc) your PC - * read the docs & checkout out the tools in tools/ and selfdrive/debug/ + * first, [setup](https://github.com/commaai/openpilot/tree/master/openpilot/tools#setup-your-pc) your PC + * read the docs & checkout out the tools in openpilot/tools/ * tip: once you get the replay and UI up, start by familiarizing yourself with seeking in replay getting started ```bash # start the route replay -cd tools/replay +cd openpilot/tools/replay ./replay '0c7f0c7f0c7f0c7f|2021-10-13--13-00-00' --dcam --ecam # start the UI in another terminal -selfdrive/ui/ui +openpilot/selfdrive/ui/ui ``` diff --git a/tools/README.md b/tools/README.md index d52c8f4522..1ea42bbe1d 100644 --- a/tools/README.md +++ b/tools/README.md @@ -29,7 +29,7 @@ source .venv/bin/activate **4. Build openpilot** ``` bash -scons -u -j$(nproc) +scons -u ``` ## WSL on Windows @@ -38,7 +38,7 @@ scons -u -j$(nproc) Follow [these instructions](https://docs.microsoft.com/en-us/windows/wsl/install) to setup the WSL and install the `Ubuntu-24.04` distribution. Once your Ubuntu WSL environment is setup, follow the Linux setup instructions to finish setting up your environment. See [these instructions](https://learn.microsoft.com/en-us/windows/wsl/tutorials/gui-apps) for running GUI apps. -**NOTE**: If you are running WSL and any GUIs are failing (segfaulting or other strange issues) even after following the steps above, you may need to enable software rendering with `LIBGL_ALWAYS_SOFTWARE=1`, e.g. `LIBGL_ALWAYS_SOFTWARE=1 selfdrive/ui/ui`. +**NOTE**: If you are running WSL 2 and experiencing performance issues with the UI or simulator, you may need to explicitly enable hardware acceleration by setting `GALLIUM_DRIVER=d3d12` before commands. Add `export GALLIUM_DRIVER=d3d12` to your `~/.bashrc` file to make it automatic for future sessions. ## CTF Learn about the openpilot ecosystem and tools by playing our [CTF](/tools/CTF.md). diff --git a/tools/auto_source.py b/tools/auto_source.py deleted file mode 100755 index 401929a9ad..0000000000 --- a/tools/auto_source.py +++ /dev/null @@ -1,17 +0,0 @@ -#!/usr/bin/env python3 -import sys -from openpilot.tools.lib.logreader import LogReader - - -def main(): - if len(sys.argv) != 2: - print("Usage: python auto_source.py ") - sys.exit(1) - - log_path = sys.argv[1] - lr = LogReader(log_path, sort_by_time=True) - print("\n".join(lr.logreader_identifiers)) - - -if __name__ == "__main__": - main() diff --git a/tools/bodyteleop/.gitignore b/tools/bodyteleop/.gitignore deleted file mode 100644 index adeab99a95..0000000000 --- a/tools/bodyteleop/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -av -av-10.0.0/* -key.pem -cert.pem \ No newline at end of file diff --git a/tools/bodyteleop/static/index.html b/tools/bodyteleop/static/index.html deleted file mode 100644 index 3654769756..0000000000 --- a/tools/bodyteleop/static/index.html +++ /dev/null @@ -1,103 +0,0 @@ - - - - - commabody - - - - - - - - - - -
-

comma body

- - -
-
-
-
-
- - - -
-

body

-
-
-
- - -
-

you

-
-
-
-
-
-
-
- - -
-

ping time

-
-
-
- - -
-

battery

-
-
-
- -
-
-
-
-
-
W
-
0,0x,y
-
-
-
A
-
S
-
D
-
-
-
- - - - -
-
-
-
-
-
-

Play Sounds

-
-
- - - -
-
-
-
-
-
-
-
-
-
- - - diff --git a/tools/bodyteleop/static/js/controls.js b/tools/bodyteleop/static/js/controls.js deleted file mode 100644 index b1e0e7ee70..0000000000 --- a/tools/bodyteleop/static/js/controls.js +++ /dev/null @@ -1,54 +0,0 @@ -const keyVals = {w: 0, a: 0, s: 0, d: 0} - -export function getXY() { - let x = -keyVals.w + keyVals.s - let y = -keyVals.d + keyVals.a - return {x, y} -} - -export const handleKeyX = (key, setValue) => { - if (['w', 'a', 's', 'd'].includes(key)){ - keyVals[key] = setValue; - let color = "#333"; - if (setValue === 1){ - color = "#e74c3c"; - } - $("#key-"+key).css('background', color); - const {x, y} = getXY(); - $("#pos-vals").text(x+","+y); - } -}; - -export async function executePlan() { - let plan = $("#plan-text").val(); - const planList = []; - plan.split("\n").forEach(function(e){ - let line = e.split(",").map(k=>parseInt(k)); - if (line.length != 5 || line.slice(0, 4).map(e=>[1, 0].includes(e)).includes(false) || line[4] < 0 || line[4] > 10){ - console.log("invalid plan"); - } - else{ - planList.push(line) - } - }); - - async function execute() { - for (var i = 0; i < planList.length; i++) { - let [w, a, s, d, t] = planList[i]; - while(t > 0){ - console.log(w, a, s, d, t); - if(w==1){$("#key-w").mousedown();} - if(a==1){$("#key-a").mousedown();} - if(s==1){$("#key-s").mousedown();} - if(d==1){$("#key-d").mousedown();} - await sleep(50); - $("#key-w").mouseup(); - $("#key-a").mouseup(); - $("#key-s").mouseup(); - $("#key-d").mouseup(); - t = t - 0.05; - } - } - } - execute(); -} \ No newline at end of file diff --git a/tools/bodyteleop/static/js/jsmain.js b/tools/bodyteleop/static/js/jsmain.js deleted file mode 100644 index 83205a876b..0000000000 --- a/tools/bodyteleop/static/js/jsmain.js +++ /dev/null @@ -1,27 +0,0 @@ -import { handleKeyX, executePlan } from "./controls.js"; -import { start, stop, lastChannelMessageTime, playSoundRequest } from "./webrtc.js"; - -export var pc = null; -export var dc = null; - -document.addEventListener('keydown', (e)=>(handleKeyX(e.key.toLowerCase(), 1))); -document.addEventListener('keyup', (e)=>(handleKeyX(e.key.toLowerCase(), 0))); -$(".keys").bind("mousedown touchstart", (e)=>handleKeyX($(e.target).attr('id').replace('key-', ''), 1)); -$(".keys").bind("mouseup touchend", (e)=>handleKeyX($(e.target).attr('id').replace('key-', ''), 0)); -$("#plan-button").click(executePlan); -$(".sound").click((e)=>{ - const sound = $(e.target).attr('id').replace('sound-', '') - return playSoundRequest(sound); -}); - -setInterval( () => { - const dt = new Date().getTime(); - if ((dt - lastChannelMessageTime) > 1000) { - $(".pre-blob").removeClass('blob'); - $("#battery").text("-"); - $("#ping-time").text('-'); - $("video")[0].load(); - } -}, 5000); - -start(pc, dc); diff --git a/tools/bodyteleop/static/js/plots.js b/tools/bodyteleop/static/js/plots.js deleted file mode 100644 index 5327bf71be..0000000000 --- a/tools/bodyteleop/static/js/plots.js +++ /dev/null @@ -1,53 +0,0 @@ -export const pingPoints = []; -export const batteryPoints = []; - -function getChartConfig(pts, color, title, ymax=100) { - return { - type: 'line', - data: { - datasets: [{ - label: title, - data: pts, - borderWidth: 1, - borderColor: color, - backgroundColor: color, - fill: 'origin' - }] - }, - options: { - scales: { - x: { - type: 'time', - time: { - unit: 'minute', - displayFormats: { - second: 'h:mm a' - } - }, - grid: { - color: '#222', // Grid lines color - }, - ticks: { - source: 'data', - fontColor: 'rgba(255, 255, 255, 1.0)', // Y-axis label color - } - }, - y: { - beginAtZero: true, - max: ymax, - grid: { - color: 'rgba(255, 255, 255, 0.1)', // Grid lines color - }, - ticks: { - fontColor: 'rgba(255, 255, 255, 0.7)', // Y-axis label color - } - } - } - } - } -} - -const ctxPing = document.getElementById('chart-ping'); -const ctxBattery = document.getElementById('chart-battery'); -export const chartPing = new Chart(ctxPing, getChartConfig(pingPoints, 'rgba(192, 57, 43, 0.7)', 'Controls Ping Time (ms)', 250)); -export const chartBattery = new Chart(ctxBattery, getChartConfig(batteryPoints, 'rgba(41, 128, 185, 0.7)', 'Battery %', 100)); diff --git a/tools/bodyteleop/static/js/webrtc.js b/tools/bodyteleop/static/js/webrtc.js deleted file mode 100644 index 165a2ce6c4..0000000000 --- a/tools/bodyteleop/static/js/webrtc.js +++ /dev/null @@ -1,209 +0,0 @@ -import { getXY } from "./controls.js"; -import { pingPoints, batteryPoints, chartPing, chartBattery } from "./plots.js"; - -export let controlCommandInterval = null; -export let latencyInterval = null; -export let lastChannelMessageTime = null; - - -export function offerRtcRequest(sdp, type) { - return fetch('/offer', { - body: JSON.stringify({sdp: sdp, type: type}), - headers: {'Content-Type': 'application/json'}, - method: 'POST' - }); -} - - -export function playSoundRequest(sound) { - return fetch('/sound', { - body: JSON.stringify({sound}), - headers: {'Content-Type': 'application/json'}, - method: 'POST' - }); -} - - -export function pingHeadRequest() { - return fetch('/', { - method: 'HEAD' - }); -} - - -export function createPeerConnection(pc) { - var config = { - sdpSemantics: 'unified-plan' - }; - - pc = new RTCPeerConnection(config); - - // connect audio / video - pc.addEventListener('track', function(evt) { - console.log("Adding Tracks!") - if (evt.track.kind == 'video') - document.getElementById('video').srcObject = evt.streams[0]; - else - document.getElementById('audio').srcObject = evt.streams[0]; - }); - return pc; -} - - -export function negotiate(pc) { - return pc.createOffer({offerToReceiveAudio:true, offerToReceiveVideo:true}).then(function(offer) { - return pc.setLocalDescription(offer); - }).then(function() { - return new Promise(function(resolve) { - if (pc.iceGatheringState === 'complete') { - resolve(); - } - else { - function checkState() { - if (pc.iceGatheringState === 'complete') { - pc.removeEventListener('icegatheringstatechange', checkState); - resolve(); - } - } - pc.addEventListener('icegatheringstatechange', checkState); - } - }); - }).then(function() { - var offer = pc.localDescription; - return offerRtcRequest(offer.sdp, offer.type); - }).then(function(response) { - console.log(response); - return response.json(); - }).then(function(answer) { - return pc.setRemoteDescription(answer); - }).catch(function(e) { - alert(e); - }); -} - - -function isMobile() { - let check = false; - (function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))) check = true;})(navigator.userAgent||navigator.vendor||window.opera); - return check; -}; - - -export const constraints = { - audio: { - autoGainControl: false, - sampleRate: 48000, - sampleSize: 16, - echoCancellation: true, - noiseSuppression: true, - channelCount: 1 - }, - video: isMobile() -}; - - -export function start(pc, dc) { - pc = createPeerConnection(pc); - - // add audio track - navigator.mediaDevices.enumerateDevices() - .then(function(devices) { - const hasAudioInput = devices.find((device) => device.kind === "audioinput"); - var modifiedConstraints = {}; - modifiedConstraints.video = constraints.video; - modifiedConstraints.audio = hasAudioInput ? constraints.audio : false; - - return Promise.resolve(modifiedConstraints); - }) - .then(function(constraints) { - if (constraints.audio || constraints.video) { - return navigator.mediaDevices.getUserMedia(constraints); - } else{ - return Promise.resolve(null); - } - }) - .then(function(stream) { - if (stream) { - stream.getTracks().forEach(function(track) { - pc.addTrack(track, stream); - }); - } - - return negotiate(pc); - }) - .catch(function(err) { - alert('Could not acquire media: ' + err); - }); - - var parameters = {"ordered": true}; - dc = pc.createDataChannel('data', parameters); - dc.onclose = function() { - clearInterval(controlCommandInterval); - clearInterval(latencyInterval); - }; - - function sendJoystickOverDataChannel() { - const {x, y} = getXY(); - var message = JSON.stringify({type: "testJoystick", data: {axes: [x, y], buttons: [false]}}) - dc.send(message); - } - function checkLatency() { - const initialTime = new Date().getTime(); - pingHeadRequest().then(function() { - const currentTime = new Date().getTime(); - if (Math.abs(currentTime - lastChannelMessageTime) < 1000) { - const pingtime = currentTime - initialTime; - pingPoints.push({'x': currentTime, 'y': pingtime}); - if (pingPoints.length > 1000) { - pingPoints.shift(); - } - chartPing.update(); - $("#ping-time").text((pingtime) + "ms"); - } - }) - } - dc.onopen = function() { - controlCommandInterval = setInterval(sendJoystickOverDataChannel, 50); - latencyInterval = setInterval(checkLatency, 1000); - sendJoystickOverDataChannel(); - }; - - const textDecoder = new TextDecoder(); - var carStaterIndex = 0; - dc.onmessage = function(evt) { - const text = textDecoder.decode(evt.data); - const msg = JSON.parse(text); - if (carStaterIndex % 100 == 0 && msg.type === 'carState') { - const batteryLevel = Math.round(msg.data.fuelGauge * 100); - $("#battery").text(batteryLevel + "%"); - batteryPoints.push({'x': new Date().getTime(), 'y': batteryLevel}); - if (batteryPoints.length > 1000) { - batteryPoints.shift(); - } - chartBattery.update(); - } - carStaterIndex += 1; - lastChannelMessageTime = new Date().getTime(); - $(".pre-blob").addClass('blob'); - }; -} - - -export function stop(pc, dc) { - if (dc) { - dc.close(); - } - if (pc.getTransceivers) { - pc.getTransceivers().forEach(function(transceiver) { - if (transceiver.stop) { - transceiver.stop(); - } - }); - } - pc.getSenders().forEach(function(sender) { - sender.track.stop(); - }); - setTimeout(function() { - pc.close(); - }, 500); -} diff --git a/tools/bodyteleop/static/main.css b/tools/bodyteleop/static/main.css deleted file mode 100644 index 1bfb5982b4..0000000000 --- a/tools/bodyteleop/static/main.css +++ /dev/null @@ -1,185 +0,0 @@ -body { - background: #333 !important; - color: #fff !important; - display: flex; - justify-content: center; - align-items: start; -} - -p { - margin: 0px !important; -} - -i { - font-style: normal; -} - -.small { - font-size: 1em !important -} - -.jumbo { - font-size: 8rem; -} - - -@media (max-width: 600px) { - .small { - font-size: 0.5em !important - } - .jumbo { - display: none; - } - -} - -#main { - display: flex; - flex-direction: column; - align-content: center; - justify-content: center; - align-items: center; - font-size: 30px; - width: 100%; - max-width: 1200px; -} - -video { - width: 95%; -} - -.pre-blob { - display: flex; - background: #333; - border-radius: 50%; - margin: 10px; - height: 45px; - width: 45px; - justify-content: center; - align-items: center; - font-size: 1rem; -} - -.blob { - background: rgba(231, 76, 60,1.0); - box-shadow: 0 0 0 0 rgba(231, 76, 60,1.0); - animation: pulse 2s infinite; -} - -@keyframes pulse { - 0% { - box-shadow: 0 0 0 0px rgba(192, 57, 43, 1); - } - 100% { - box-shadow: 0 0 0 20px rgba(192, 57, 43, 0); - } -} - - -.icon-sup-panel { - display: flex; - flex-direction: row; - justify-content: space-around; - align-items: center; - background: #222; - border-radius: 10px; - padding: 5px; - margin: 5px 0px 5px 0px; -} - -.icon-sub-panel { - display: flex; - flex-direction: column; - justify-content: space-between; - align-items: center; -} - -#icon-panel { - display: flex; - width: 100%; - justify-content: space-between; - margin-top: 5px; -} - -.icon-sub-sub-panel { - display: flex; - flex-direction: row; -} - -.keys, #key-val { - background: #333; - padding: 2rem; - margin: 5px; - color: #fff; - display: flex; - justify-content: center; - align-items: center; - border-radius: 10px; - cursor: pointer; -} - -#key-val { - pointer-events: none; - background: #fff; - color: #333; - line-height: 1; - font-size: 20px; - flex-direction: column; -} - -.wasd-row { - display: flex; - flex-direction: row; - justify-content: center; - align-items: stretch; -} - -#wasd { - margin: 5px 0px 5px 0px; - background: #222; - border-radius: 10px; - width: 100%; - padding: 20px; - display: flex; - flex-direction: row; - justify-content: space-around; - align-items: stretch; - - user-select: none; - -webkit-touch-callout: none; - -webkit-user-select: none; - -khtml-user-select: none; - -moz-user-select: none; - -ms-user-select: none; - touch-action: manipulation; -} - -.panel { - display: flex; - justify-content: center; - margin: 5px 0px 5px 0px !important; - background: #222; - border-radius: 10px; - width: 100%; - padding: 10px; -} - -#ping-time, #battery { - font-size: 25px; -} - -#stop { - display: none; -} - -.plan-form { - display: flex; - flex-direction: column; - justify-content: space-between; - align-items: center; -} - -.details { - display: flex; - padding: 0px 10px 0px 10px; -} diff --git a/tools/bodyteleop/static/poster.png b/tools/bodyteleop/static/poster.png deleted file mode 100644 index 2f2b02dd8a..0000000000 --- a/tools/bodyteleop/static/poster.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:8740da2be7faac198b5e10780c646166056a76ebbe3d64499e0cdc49280c8a4f -size 8297 diff --git a/tools/bodyteleop/web.py b/tools/bodyteleop/web.py deleted file mode 100644 index fd8f691d19..0000000000 --- a/tools/bodyteleop/web.py +++ /dev/null @@ -1,127 +0,0 @@ -import asyncio -import dataclasses -import json -import logging -import os -import ssl -import subprocess - -import pyaudio -import wave -from aiohttp import web -from aiohttp import ClientSession - -from openpilot.common.basedir import BASEDIR -from openpilot.system.webrtc.webrtcd import StreamRequestBody -from openpilot.common.params import Params - -logger = logging.getLogger("bodyteleop") -logging.basicConfig(level=logging.INFO) - -TELEOPDIR = f"{BASEDIR}/tools/bodyteleop" -WEBRTCD_HOST, WEBRTCD_PORT = "localhost", 5001 - - -## UTILS -async def play_sound(sound: str): - SOUNDS = { - "engage": "selfdrive/assets/sounds/engage.wav", - "disengage": "selfdrive/assets/sounds/disengage.wav", - "error": "selfdrive/assets/sounds/warning_immediate.wav", - } - assert sound in SOUNDS - - chunk = 5120 - with wave.open(os.path.join(BASEDIR, SOUNDS[sound]), "rb") as wf: - def callback(in_data, frame_count, time_info, status): - data = wf.readframes(frame_count) - return data, pyaudio.paContinue - - p = pyaudio.PyAudio() - stream = p.open(format=p.get_format_from_width(wf.getsampwidth()), - channels=wf.getnchannels(), - rate=wf.getframerate(), - output=True, - frames_per_buffer=chunk, - stream_callback=callback) - stream.start_stream() - while stream.is_active(): - await asyncio.sleep(0) - stream.stop_stream() - stream.close() - p.terminate() - -## SSL -def create_ssl_cert(cert_path: str, key_path: str): - try: - proc = subprocess.run(f'openssl req -x509 -newkey rsa:4096 -nodes -out {cert_path} -keyout {key_path} \ - -days 365 -subj "/C=US/ST=California/O=commaai/OU=comma body"', - capture_output=True, shell=True) - proc.check_returncode() - except subprocess.CalledProcessError as ex: - raise ValueError(f"Error creating SSL certificate:\n[stdout]\n{proc.stdout.decode()}\n[stderr]\n{proc.stderr.decode()}") from ex - - -def create_ssl_context(): - cert_path = os.path.join(TELEOPDIR, "cert.pem") - key_path = os.path.join(TELEOPDIR, "key.pem") - if not os.path.exists(cert_path) or not os.path.exists(key_path): - logger.info("Creating certificate...") - create_ssl_cert(cert_path, key_path) - else: - logger.info("Certificate exists!") - ssl_context = ssl.SSLContext(protocol=ssl.PROTOCOL_TLS_SERVER) - ssl_context.load_cert_chain(cert_path, key_path) - - return ssl_context - -## ENDPOINTS -async def index(request: 'web.Request'): - with open(os.path.join(TELEOPDIR, "static", "index.html")) as f: - content = f.read() - return web.Response(content_type="text/html", text=content) - - -async def ping(request: 'web.Request'): - return web.Response(text="pong") - - -async def sound(request: 'web.Request'): - params = await request.json() - sound_to_play = params["sound"] - - await play_sound(sound_to_play) - return web.json_response({"status": "ok"}) - - -async def offer(request: 'web.Request'): - params = await request.json() - body = StreamRequestBody(params["sdp"], ["driver"], ["testJoystick"], ["carState"]) - body_json = json.dumps(dataclasses.asdict(body)) - - logger.info("Sending offer to webrtcd...") - webrtcd_url = f"http://{WEBRTCD_HOST}:{WEBRTCD_PORT}/stream" - async with ClientSession() as session, session.post(webrtcd_url, data=body_json) as resp: - assert resp.status == 200 - answer = await resp.json() - return web.json_response(answer) - - -def main(): - # Enable joystick debug mode - Params().put_bool("JoystickDebugMode", True) - - # App needs to be HTTPS for microphone and audio autoplay to work on the browser - ssl_context = create_ssl_context() - - app = web.Application() - app.router.add_get("/", index) - app.router.add_get("/ping", ping, allow_head=True) - app.router.add_post("/offer", offer) - app.router.add_post("/sound", sound) - app.router.add_static('/static', os.path.join(TELEOPDIR, 'static')) - web.run_app(app, access_log=None, host="0.0.0.0", port=5000, ssl_context=ssl_context) - - -if __name__ == "__main__": - main() diff --git a/tools/cabana/.gitignore b/tools/cabana/.gitignore deleted file mode 100644 index 362a51f5c9..0000000000 --- a/tools/cabana/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -moc_* -*.moc - -cabana -dbc/car_fingerprint_to_dbc.json -tests/test_cabana diff --git a/tools/cabana/README.md b/tools/cabana/README.md deleted file mode 100644 index 7933098e34..0000000000 --- a/tools/cabana/README.md +++ /dev/null @@ -1,100 +0,0 @@ -# Cabana - -Cabana is a tool developed to view raw CAN data. One use for this is creating and editing [CAN Dictionaries](http://socialledge.com/sjsu/index.php/DBC_Format) (DBC files), and the tool provides direct integration with [commaai/opendbc](https://github.com/commaai/opendbc) (a collection of DBC files), allowing you to load the DBC files direct from source, and save to your fork. In addition, you can load routes from [comma connect](https://connect.comma.ai). - -## Usage Instructions - -```bash -$ ./cabana -h -Usage: ./cabana [options] route - -Options: - -h, --help Displays help on commandline options. - --help-all Displays help including Qt specific options. - --demo use a demo route instead of providing your own - --auto Auto load the route from the best available source (no video): - internal, openpilotci, comma_api, car_segments, testing_closet - --qcam load qcamera - --ecam load wide road camera - --msgq read can messages from msgq - --panda read can messages from panda - --panda-serial read can messages from panda with given serial - --socketcan read can messages from given SocketCAN device - --zmq read can messages from zmq at the specified ip-address - messages - --data_dir local directory with routes - --no-vipc do not output video - --dbc dbc file to open - -Arguments: - route the drive to replay. find your drives at - connect.comma.ai -``` - -## Examples - -### Running Cabana in Demo Mode -To run Cabana using a built-in demo route, use the following command: - -```shell -cabana --demo -``` - -### Loading a Specific Route - -To load a specific route for replay, provide the route as an argument: - -```shell -cabana "a2a0ccea32023010|2023-07-27--13-01-19" -``` - -Replace "0ccea32023010|2023-07-27--13-01-19" with your desired route identifier. - - -### Running Cabana with multiple cameras -To run Cabana with multiple cameras, use the following command: - -```shell -cabana "a2a0ccea32023010|2023-07-27--13-01-19" --dcam --ecam -``` - -### Streaming CAN Messages from a comma Device - -[SSH into your device](https://github.com/commaai/openpilot/wiki/SSH) and start the bridge with the following command: - -```shell -cd /data/openpilot/cereal/messaging/ -./bridge & -``` - -Then Run Cabana with the device's IP address: - -```shell -cabana --zmq -``` - -Replace <ipaddress> with your comma device's IP address. - -While streaming from the device, Cabana will log the CAN messages to a local directory. By default, this directory is ~/cabana_live_stream/. You can change the log directory in Cabana by navigating to menu -> tools -> settings. - -After disconnecting from the device, you can replay the logged CAN messages from the stream selector dialog -> browse local route. - -### Streaming CAN Messages from Panda - -To read CAN messages from a connected Panda, use the following command: - -```shell -cabana --panda -``` - -### Using the Stream Selector Dialog - -If you run Cabana without any arguments, a stream selector dialog will pop up, allowing you to choose the stream. - -```shell -cabana -``` - -## Additional Information - -For more information, see the [openpilot wiki](https://github.com/commaai/openpilot/wiki/Cabana) diff --git a/tools/cabana/SConscript b/tools/cabana/SConscript deleted file mode 100644 index c8e6093b86..0000000000 --- a/tools/cabana/SConscript +++ /dev/null @@ -1,42 +0,0 @@ -Import('qt_env', 'arch', 'common', 'messaging', 'visionipc', 'replay_lib', 'cereal', 'widgets') - -base_frameworks = qt_env['FRAMEWORKS'] -base_libs = [common, messaging, cereal, visionipc, 'qt_util', 'm', 'ssl', 'crypto', 'pthread'] + qt_env["LIBS"] - -if arch == "Darwin": - base_frameworks.append('OpenCL') - base_frameworks.append('QtCharts') - base_frameworks.append('QtSerialBus') -else: - base_libs.append('OpenCL') - base_libs.append('Qt5Charts') - base_libs.append('Qt5SerialBus') - -qt_libs = ['qt_util'] + base_libs - -cabana_env = qt_env.Clone() -cabana_libs = [widgets, cereal, messaging, visionipc, replay_lib, 'panda', 'avutil', 'avcodec', 'avformat', 'bz2', 'zstd', 'curl', 'yuv', 'usb-1.0'] + qt_libs -opendbc_path = '-DOPENDBC_FILE_PATH=\'"%s"\'' % (cabana_env.Dir("../../opendbc/dbc").abspath) -cabana_env['CXXFLAGS'] += [opendbc_path] - -# build assets -assets = "assets/assets.cc" -assets_src = "assets/assets.qrc" -cabana_env.Command(assets, assets_src, f"rcc $SOURCES -o $TARGET") -cabana_env.Depends(assets, Glob('/assets/*', exclude=[assets, assets_src, "assets/assets.o"])) - -cabana_lib = cabana_env.Library("cabana_lib", ['mainwin.cc', 'streams/socketcanstream.cc', 'streams/pandastream.cc', 'streams/devicestream.cc', 'streams/livestream.cc', 'streams/abstractstream.cc', 'streams/replaystream.cc', 'binaryview.cc', 'historylog.cc', 'videowidget.cc', 'signalview.cc', - 'streams/routes.cc', 'dbc/dbc.cc', 'dbc/dbcfile.cc', 'dbc/dbcmanager.cc', - 'utils/export.cc', 'utils/util.cc', - 'chart/chartswidget.cc', 'chart/chart.cc', 'chart/signalselector.cc', 'chart/tiplabel.cc', 'chart/sparkline.cc', - 'commands.cc', 'messageswidget.cc', 'streamselector.cc', 'settings.cc', 'detailwidget.cc', 'tools/findsimilarbits.cc', 'tools/findsignal.cc', 'tools/routeinfo.cc'], LIBS=cabana_libs, FRAMEWORKS=base_frameworks) -cabana_env.Program('cabana', ['cabana.cc', cabana_lib, assets], LIBS=cabana_libs, FRAMEWORKS=base_frameworks) - -if GetOption('extras'): - cabana_env.Program('tests/test_cabana', ['tests/test_runner.cc', 'tests/test_cabana.cc', cabana_lib], LIBS=[cabana_libs]) - -output_json_file = 'tools/cabana/dbc/car_fingerprint_to_dbc.json' -generate_dbc = cabana_env.Command('#' + output_json_file, - ['dbc/generate_dbc_json.py'], - "python3 tools/cabana/dbc/generate_dbc_json.py --out " + output_json_file) -cabana_env.Depends(generate_dbc, ["#common", "#selfdrive/pandad", '#opendbc_repo', "#cereal", "#msgq_repo"]) diff --git a/tools/cabana/assets/.gitignore b/tools/cabana/assets/.gitignore deleted file mode 100644 index 283034ca8b..0000000000 --- a/tools/cabana/assets/.gitignore +++ /dev/null @@ -1 +0,0 @@ -*.cc diff --git a/tools/cabana/assets/assets.qrc b/tools/cabana/assets/assets.qrc deleted file mode 100644 index 6a8e5a3414..0000000000 --- a/tools/cabana/assets/assets.qrc +++ /dev/null @@ -1,6 +0,0 @@ - - - ../../../third_party/bootstrap/bootstrap-icons.svg - cabana-icon.png - - diff --git a/tools/cabana/cabana.cc b/tools/cabana/cabana.cc deleted file mode 100644 index 97f178b1f3..0000000000 --- a/tools/cabana/cabana.cc +++ /dev/null @@ -1,83 +0,0 @@ -#include -#include - -#include "selfdrive/ui/qt/util.h" -#include "tools/cabana/mainwin.h" -#include "tools/cabana/streams/devicestream.h" -#include "tools/cabana/streams/pandastream.h" -#include "tools/cabana/streams/replaystream.h" -#include "tools/cabana/streams/socketcanstream.h" - -int main(int argc, char *argv[]) { - QCoreApplication::setApplicationName("Cabana"); - QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts); - initApp(argc, argv, false); - QApplication app(argc, argv); - app.setApplicationDisplayName("Cabana"); - app.setWindowIcon(QIcon(":cabana-icon.png")); - - UnixSignalHandler signalHandler; - utils::setTheme(settings.theme); - - QCommandLineParser cmd_parser; - cmd_parser.addHelpOption(); - cmd_parser.addPositionalArgument("route", "the drive to replay. find your drives at connect.comma.ai"); - cmd_parser.addOption({"demo", "use a demo route instead of providing your own"}); - cmd_parser.addOption({"auto", "Auto load the route from the best available source (no video): internal, openpilotci, comma_api, car_segments, testing_closet"}); - cmd_parser.addOption({"qcam", "load qcamera"}); - cmd_parser.addOption({"ecam", "load wide road camera"}); - cmd_parser.addOption({"dcam", "load driver camera"}); - cmd_parser.addOption({"msgq", "read can messages from the msgq"}); - cmd_parser.addOption({"panda", "read can messages from panda"}); - cmd_parser.addOption({"panda-serial", "read can messages from panda with given serial", "panda-serial"}); - if (SocketCanStream::available()) { - cmd_parser.addOption({"socketcan", "read can messages from given SocketCAN device", "socketcan"}); - } - cmd_parser.addOption({"zmq", "read can messages from zmq at the specified ip-address", "ip-address"}); - cmd_parser.addOption({"data_dir", "local directory with routes", "data_dir"}); - cmd_parser.addOption({"no-vipc", "do not output video"}); - cmd_parser.addOption({"dbc", "dbc file to open", "dbc"}); - cmd_parser.process(app); - - AbstractStream *stream = nullptr; - - if (cmd_parser.isSet("msgq")) { - stream = new DeviceStream(&app); - } else if (cmd_parser.isSet("zmq")) { - stream = new DeviceStream(&app, cmd_parser.value("zmq")); - } else if (cmd_parser.isSet("panda") || cmd_parser.isSet("panda-serial")) { - try { - stream = new PandaStream(&app, {.serial = cmd_parser.value("panda-serial")}); - } catch (std::exception &e) { - qWarning() << e.what(); - return 0; - } - } else if (SocketCanStream::available() && cmd_parser.isSet("socketcan")) { - stream = new SocketCanStream(&app, {.device = cmd_parser.value("socketcan")}); - } else { - uint32_t replay_flags = REPLAY_FLAG_NONE; - if (cmd_parser.isSet("ecam")) replay_flags |= REPLAY_FLAG_ECAM; - if (cmd_parser.isSet("qcam")) replay_flags |= REPLAY_FLAG_QCAMERA; - if (cmd_parser.isSet("dcam")) replay_flags |= REPLAY_FLAG_DCAM; - if (cmd_parser.isSet("no-vipc")) replay_flags |= REPLAY_FLAG_NO_VIPC; - - const QStringList args = cmd_parser.positionalArguments(); - QString route; - if (args.size() > 0) { - route = args.first(); - } else if (cmd_parser.isSet("demo")) { - route = DEMO_ROUTE; - } - if (!route.isEmpty()) { - auto replay_stream = std::make_unique(&app); - bool auto_source = cmd_parser.isSet("auto"); - if (!replay_stream->loadRoute(route, cmd_parser.value("data_dir"), replay_flags, auto_source)) { - return 0; - } - stream = replay_stream.release(); - } - } - - MainWindow w(stream, cmd_parser.value("dbc")); - return app.exec(); -} diff --git a/tools/cabana/chart/chart.cc b/tools/cabana/chart/chart.cc deleted file mode 100644 index 3588c5edc6..0000000000 --- a/tools/cabana/chart/chart.cc +++ /dev/null @@ -1,860 +0,0 @@ -#include "tools/cabana/chart/chart.h" - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "tools/cabana/chart/chartswidget.h" - -// ChartAxisElement's padding is 4 (https://codebrowser.dev/qt5/qtcharts/src/charts/axis/chartaxiselement_p.h.html) -const int AXIS_X_TOP_MARGIN = 4; -const double MIN_ZOOM_SECONDS = 0.01; // 10ms -// Define a small value of epsilon to compare double values -const float EPSILON = 0.000001; -static inline bool xLessThan(const QPointF &p, float x) { return p.x() < (x - EPSILON); } - -ChartView::ChartView(const std::pair &x_range, ChartsWidget *parent) - : charts_widget(parent), QChartView(parent) { - series_type = (SeriesType)settings.chart_series_type; - chart()->setBackgroundVisible(false); - axis_x = new QValueAxis(this); - axis_y = new QValueAxis(this); - chart()->addAxis(axis_x, Qt::AlignBottom); - chart()->addAxis(axis_y, Qt::AlignLeft); - chart()->legend()->layout()->setContentsMargins(0, 0, 0, 0); - chart()->legend()->setShowToolTips(true); - chart()->setMargins({0, 0, 0, 0}); - - axis_x->setRange(x_range.first, x_range.second); - - tip_label = new TipLabel(this); - createToolButtons(); - setRubberBand(QChartView::HorizontalRubberBand); - setMouseTracking(true); - setTheme(settings.theme == DARK_THEME ? QChart::QChart::ChartThemeDark : QChart::ChartThemeLight); - signal_value_font.setPointSize(9); - - QObject::connect(axis_y, &QValueAxis::rangeChanged, this, &ChartView::resetChartCache); - QObject::connect(axis_y, &QAbstractAxis::titleTextChanged, this, &ChartView::resetChartCache); - QObject::connect(window()->windowHandle(), &QWindow::screenChanged, this, &ChartView::resetChartCache); - - QObject::connect(dbc(), &DBCManager::signalRemoved, this, &ChartView::signalRemoved); - QObject::connect(dbc(), &DBCManager::signalUpdated, this, &ChartView::signalUpdated); - QObject::connect(dbc(), &DBCManager::msgRemoved, this, &ChartView::msgRemoved); - QObject::connect(dbc(), &DBCManager::msgUpdated, this, &ChartView::msgUpdated); -} - -void ChartView::createToolButtons() { - move_icon = new QGraphicsPixmapItem(utils::icon("grip-horizontal"), chart()); - move_icon->setToolTip(tr("Drag and drop to move chart")); - - QToolButton *remove_btn = new ToolButton("x", tr("Remove Chart")); - close_btn_proxy = new QGraphicsProxyWidget(chart()); - close_btn_proxy->setWidget(remove_btn); - close_btn_proxy->setZValue(chart()->zValue() + 11); - - menu = new QMenu(this); - // series types - auto change_series_group = new QActionGroup(menu); - change_series_group->setExclusive(true); - QStringList types{tr("Line"), tr("Step Line"), tr("Scatter")}; - for (int i = 0; i < types.size(); ++i) { - QAction *act = new QAction(types[i], change_series_group); - act->setData(i); - act->setCheckable(true); - act->setChecked(i == (int)series_type); - menu->addAction(act); - } - menu->addSeparator(); - menu->addAction(tr("Manage Signals"), this, &ChartView::manageSignals); - split_chart_act = menu->addAction(tr("Split Chart"), [this]() { charts_widget->splitChart(this); }); - - QToolButton *manage_btn = new ToolButton("list", ""); - manage_btn->setMenu(menu); - manage_btn->setPopupMode(QToolButton::InstantPopup); - manage_btn->setStyleSheet("QToolButton::menu-indicator { image: none; }"); - manage_btn_proxy = new QGraphicsProxyWidget(chart()); - manage_btn_proxy->setWidget(manage_btn); - manage_btn_proxy->setZValue(chart()->zValue() + 11); - - close_act = new QAction(tr("Close"), this); - QObject::connect(close_act, &QAction::triggered, [this] () { charts_widget->removeChart(this); }); - QObject::connect(remove_btn, &QToolButton::clicked, close_act, &QAction::triggered); - QObject::connect(change_series_group, &QActionGroup::triggered, [this](QAction *action) { - setSeriesType((SeriesType)action->data().toInt()); - }); -} - -QSize ChartView::sizeHint() const { - return {CHART_MIN_WIDTH, settings.chart_height}; -} - -void ChartView::setTheme(QChart::ChartTheme theme) { - chart()->setTheme(theme); - if (theme == QChart::ChartThemeDark) { - axis_x->setTitleBrush(palette().text()); - axis_x->setLabelsBrush(palette().text()); - axis_y->setTitleBrush(palette().text()); - axis_y->setLabelsBrush(palette().text()); - chart()->legend()->setLabelColor(palette().color(QPalette::Text)); - } - axis_x->setLineVisible(false); - axis_y->setLineVisible(false); - for (auto &s : sigs) { - s.series->setColor(s.sig->color); - } -} - -void ChartView::addSignal(const MessageId &msg_id, const cabana::Signal *sig) { - if (hasSignal(msg_id, sig)) return; - - QXYSeries *series = createSeries(series_type, sig->color); - sigs.push_back({.msg_id = msg_id, .sig = sig, .series = series}); - updateSeries(sig); - updateSeriesPoints(); - updateTitle(); - emit charts_widget->seriesChanged(); -} - -bool ChartView::hasSignal(const MessageId &msg_id, const cabana::Signal *sig) const { - return std::any_of(sigs.cbegin(), sigs.cend(), [&](auto &s) { return s.msg_id == msg_id && s.sig == sig; }); -} - -void ChartView::removeIf(std::function predicate) { - int prev_size = sigs.size(); - for (auto it = sigs.begin(); it != sigs.end(); /**/) { - if (predicate(*it)) { - chart()->removeSeries(it->series); - it->series->deleteLater(); - it = sigs.erase(it); - } else { - ++it; - } - } - if (sigs.empty()) { - charts_widget->removeChart(this); - } else if (sigs.size() != prev_size) { - emit charts_widget->seriesChanged(); - updateAxisY(); - resetChartCache(); - } -} - -void ChartView::signalUpdated(const cabana::Signal *sig) { - auto it = std::find_if(sigs.begin(), sigs.end(), [sig](auto &s) { return s.sig == sig; }); - if (it != sigs.end()) { - if (it->series->color() != sig->color) { - setSeriesColor(it->series, sig->color); - } - updateTitle(); - updateSeries(sig); - } -} - -void ChartView::msgUpdated(MessageId id) { - if (std::any_of(sigs.cbegin(), sigs.cend(), [=](auto &s) { return s.msg_id.address == id.address; })) { - updateTitle(); - } -} - -void ChartView::manageSignals() { - SignalSelector dlg(tr("Manage Chart"), this); - for (auto &s : sigs) { - dlg.addSelected(s.msg_id, s.sig); - } - if (dlg.exec() == QDialog::Accepted) { - auto items = dlg.seletedItems(); - for (auto s : items) { - addSignal(s->msg_id, s->sig); - } - removeIf([&](auto &s) { - return std::none_of(items.cbegin(), items.cend(), [&](auto &it) { return s.msg_id == it->msg_id && s.sig == it->sig; }); - }); - } -} - -void ChartView::resizeEvent(QResizeEvent *event) { - qreal left, top, right, bottom; - chart()->layout()->getContentsMargins(&left, &top, &right, &bottom); - move_icon->setPos(left, top); - close_btn_proxy->setPos(rect().right() - right - close_btn_proxy->size().width(), top); - int x = close_btn_proxy->pos().x() - manage_btn_proxy->size().width() - style()->pixelMetric(QStyle::PM_LayoutHorizontalSpacing); - manage_btn_proxy->setPos(x, top); - if (align_to > 0) { - updatePlotArea(align_to, true); - } - QChartView::resizeEvent(event); -} - -void ChartView::updatePlotArea(int left_pos, bool force) { - if (align_to != left_pos || force) { - align_to = left_pos; - - qreal left, top, right, bottom; - chart()->layout()->getContentsMargins(&left, &top, &right, &bottom); - QSizeF legend_size = chart()->legend()->layout()->minimumSize(); - legend_size.setWidth(manage_btn_proxy->sceneBoundingRect().left() - move_icon->sceneBoundingRect().right()); - chart()->legend()->setGeometry({move_icon->sceneBoundingRect().topRight(), legend_size}); - - // add top space for signal value - int adjust_top = chart()->legend()->geometry().height() + QFontMetrics(signal_value_font).height() + 3; - adjust_top = std::max(adjust_top, manage_btn_proxy->sceneBoundingRect().height() + style()->pixelMetric(QStyle::PM_LayoutTopMargin)); - // add right space for x-axis label - QSizeF x_label_size = QFontMetrics(axis_x->labelsFont()).size(Qt::TextSingleLine, QString::number(axis_x->max(), 'f', 2)); - x_label_size += QSizeF{5, 5}; - chart()->setPlotArea(rect().adjusted(align_to + left, adjust_top + top, -x_label_size.width() / 2 - right, -x_label_size.height() - bottom)); - chart()->layout()->invalidate(); - resetChartCache(); - } -} - -void ChartView::updateTitle() { - for (QLegendMarker *marker : chart()->legend()->markers()) { - QObject::connect(marker, &QLegendMarker::clicked, this, &ChartView::handleMarkerClicked, Qt::UniqueConnection); - } - - // Use CSS to draw titles in the WindowText color - auto tmp = palette().color(QPalette::WindowText); - auto titleColorCss = tmp.name(QColor::HexArgb); - // Draw message details in similar color, but slightly fade it to the background - tmp.setAlpha(180); - auto msgColorCss = tmp.name(QColor::HexArgb); - - for (auto &s : sigs) { - auto decoration = s.series->isVisible() ? "none" : "line-through"; - s.series->setName(QString("%3 %5 %6") - .arg(decoration, titleColorCss, s.sig->name, - msgColorCss, msgName(s.msg_id), s.msg_id.toString())); - } - split_chart_act->setEnabled(sigs.size() > 1); - resetChartCache(); -} - -void ChartView::updatePlot(double cur, double min, double max) { - cur_sec = cur; - if (min != axis_x->min() || max != axis_x->max()) { - axis_x->setRange(min, max); - updateAxisY(); - updateSeriesPoints(); - // update tooltip - if (tooltip_x >= 0) { - showTip(chart()->mapToValue({tooltip_x, 0}).x()); - } - resetChartCache(); - } - viewport()->update(); -} - -void ChartView::updateSeriesPoints() { - // Show points when zoomed in enough - for (auto &s : sigs) { - auto begin = std::lower_bound(s.vals.cbegin(), s.vals.cend(), axis_x->min(), xLessThan); - auto end = std::lower_bound(begin, s.vals.cend(), axis_x->max(), xLessThan); - if (begin != end) { - int num_points = std::max((end - begin), 1); - QPointF right_pt = end == s.vals.cend() ? s.vals.back() : *end; - double pixels_per_point = (chart()->mapToPosition(right_pt).x() - chart()->mapToPosition(*begin).x()) / num_points; - - if (series_type == SeriesType::Scatter) { - qreal size = std::clamp(pixels_per_point / 2.0, 2.0, 8.0); - if (s.series->useOpenGL()) { - size *= devicePixelRatioF(); - } - ((QScatterSeries *)s.series)->setMarkerSize(size); - } else { - s.series->setPointsVisible(num_points == 1 || pixels_per_point > 20); - } - } - } -} - -void ChartView::appendCanEvents(const cabana::Signal *sig, const std::vector &events, - std::vector &vals, std::vector &step_vals) { - vals.reserve(vals.size() + events.capacity()); - step_vals.reserve(step_vals.size() + events.capacity() * 2); - - double value = 0; - for (const CanEvent *e : events) { - if (sig->getValue(e->dat, e->size, &value)) { - const double ts = can->toSeconds(e->mono_time); - vals.emplace_back(ts, value); - if (!step_vals.empty()) - step_vals.emplace_back(ts, step_vals.back().y()); - step_vals.emplace_back(ts, value); - } - } -} - -void ChartView::updateSeries(const cabana::Signal *sig, const MessageEventsMap *msg_new_events) { - for (auto &s : sigs) { - if (!sig || s.sig == sig) { - if (!msg_new_events) { - s.vals.clear(); - s.step_vals.clear(); - } - auto events = msg_new_events ? msg_new_events : &can->eventsMap(); - auto it = events->find(s.msg_id); - if (it == events->end() || it->second.empty()) continue; - - if (s.vals.empty() || can->toSeconds(it->second.back()->mono_time) > s.vals.back().x()) { - appendCanEvents(s.sig, it->second, s.vals, s.step_vals); - } else { - std::vector vals, step_vals; - appendCanEvents(s.sig, it->second, vals, step_vals); - s.vals.insert(std::lower_bound(s.vals.begin(), s.vals.end(), vals.front().x(), xLessThan), - vals.begin(), vals.end()); - s.step_vals.insert(std::lower_bound(s.step_vals.begin(), s.step_vals.end(), step_vals.front().x(), xLessThan), - step_vals.begin(), step_vals.end()); - } - - if (!can->liveStreaming()) { - s.segment_tree.build(s.vals); - } - s.series->replace(QVector::fromStdVector(series_type == SeriesType::StepLine ? s.step_vals : s.vals)); - } - } - updateAxisY(); - // invoke resetChartCache in ui thread - QMetaObject::invokeMethod(this, &ChartView::resetChartCache, Qt::QueuedConnection); -} - -// auto zoom on yaxis -void ChartView::updateAxisY() { - if (sigs.empty()) return; - - double min = std::numeric_limits::max(); - double max = std::numeric_limits::lowest(); - QString unit = sigs[0].sig->unit; - - for (auto &s : sigs) { - if (!s.series->isVisible()) continue; - - // Only show unit when all signals have the same unit - if (unit != s.sig->unit) { - unit.clear(); - } - - auto first = std::lower_bound(s.vals.cbegin(), s.vals.cend(), axis_x->min(), xLessThan); - auto last = std::lower_bound(first, s.vals.cend(), axis_x->max(), xLessThan); - s.min = std::numeric_limits::max(); - s.max = std::numeric_limits::lowest(); - if (can->liveStreaming()) { - for (auto it = first; it != last; ++it) { - if (it->y() < s.min) s.min = it->y(); - if (it->y() > s.max) s.max = it->y(); - } - } else { - std::tie(s.min, s.max) = s.segment_tree.minmax(std::distance(s.vals.cbegin(), first), std::distance(s.vals.cbegin(), last)); - } - min = std::min(min, s.min); - max = std::max(max, s.max); - } - if (min == std::numeric_limits::max()) min = 0; - if (max == std::numeric_limits::lowest()) max = 0; - - if (axis_y->titleText() != unit) { - axis_y->setTitleText(unit); - y_label_width = 0; // recalc width - } - - double delta = std::abs(max - min) < 1e-3 ? 1 : (max - min) * 0.05; - auto [min_y, max_y, tick_count] = getNiceAxisNumbers(min - delta, max + delta, 3); - if (min_y != axis_y->min() || max_y != axis_y->max() || y_label_width == 0) { - axis_y->setRange(min_y, max_y); - axis_y->setTickCount(tick_count); - - int n = std::max(int(-std::floor(std::log10((max_y - min_y) / (tick_count - 1)))), 0); - int max_label_width = 0; - QFontMetrics fm(axis_y->labelsFont()); - for (int i = 0; i < tick_count; i++) { - qreal value = min_y + (i * (max_y - min_y) / (tick_count - 1)); - max_label_width = std::max(max_label_width, fm.width(QString::number(value, 'f', n))); - } - - int title_spacing = unit.isEmpty() ? 0 : QFontMetrics(axis_y->titleFont()).size(Qt::TextSingleLine, unit).height(); - y_label_width = title_spacing + max_label_width + 15; - axis_y->setLabelFormat(QString("%.%1f").arg(n)); - emit axisYLabelWidthChanged(y_label_width); - } -} - -std::tuple ChartView::getNiceAxisNumbers(qreal min, qreal max, int tick_count) { - qreal range = niceNumber((max - min), true); // range with ceiling - qreal step = niceNumber(range / (tick_count - 1), false); - min = std::floor(min / step); - max = std::ceil(max / step); - tick_count = int(max - min) + 1; - return {min * step, max * step, tick_count}; -} - -// nice numbers can be expressed as form of 1*10^n, 2* 10^n or 5*10^n -qreal ChartView::niceNumber(qreal x, bool ceiling) { - qreal z = std::pow(10, std::floor(std::log10(x))); //find corresponding number of the form of 10^n than is smaller than x - qreal q = x / z; //q<10 && q>=1; - if (ceiling) { - if (q <= 1.0) q = 1; - else if (q <= 2.0) q = 2; - else if (q <= 5.0) q = 5; - else q = 10; - } else { - if (q < 1.5) q = 1; - else if (q < 3.0) q = 2; - else if (q < 7.0) q = 5; - else q = 10; - } - return q * z; -} - -QPixmap getBlankShadowPixmap(const QPixmap &px, int radius) { - QGraphicsDropShadowEffect *e = new QGraphicsDropShadowEffect; - e->setColor(QColor(40, 40, 40, 245)); - e->setOffset(0, 0); - e->setBlurRadius(radius); - - qreal dpr = px.devicePixelRatio(); - QPixmap blank(px.size()); - blank.setDevicePixelRatio(dpr); - blank.fill(Qt::white); - - QGraphicsScene scene; - QGraphicsPixmapItem item(blank); - item.setGraphicsEffect(e); - scene.addItem(&item); - - QPixmap shadow(px.size() + QSize(radius * dpr * 2, radius * dpr * 2)); - shadow.setDevicePixelRatio(dpr); - shadow.fill(Qt::transparent); - QPainter p(&shadow); - scene.render(&p, {QPoint(), shadow.size() / dpr}, item.boundingRect().adjusted(-radius, -radius, radius, radius)); - return shadow; -} - -static QPixmap getDropPixmap(const QPixmap &src) { - static QPixmap shadow_px; - const int radius = 10; - if (shadow_px.size() != src.size() + QSize(radius * 2, radius * 2)) { - shadow_px = getBlankShadowPixmap(src, radius); - } - QPixmap px = shadow_px; - QPainter p(&px); - QRectF target_rect(QPointF(radius, radius), src.size() / src.devicePixelRatio()); - p.drawPixmap(target_rect.topLeft(), src); - p.setCompositionMode(QPainter::CompositionMode_DestinationIn); - p.fillRect(target_rect, QColor(0, 0, 0, 200)); - return px; -} - -void ChartView::contextMenuEvent(QContextMenuEvent *event) { - QMenu context_menu(this); - context_menu.addActions(menu->actions()); - context_menu.addSeparator(); - context_menu.addAction(charts_widget->undo_zoom_action); - context_menu.addAction(charts_widget->redo_zoom_action); - context_menu.addSeparator(); - context_menu.addAction(close_act); - context_menu.exec(event->globalPos()); -} - -void ChartView::mousePressEvent(QMouseEvent *event) { - if (event->button() == Qt::LeftButton && move_icon->sceneBoundingRect().contains(event->pos())) { - QMimeData *mimeData = new QMimeData; - mimeData->setData(CHART_MIME_TYPE, QByteArray::number((qulonglong)this)); - QPixmap px = grab().scaledToWidth(CHART_MIN_WIDTH * viewport()->devicePixelRatio(), Qt::SmoothTransformation); - charts_widget->stopAutoScroll(); - QDrag *drag = new QDrag(this); - drag->setMimeData(mimeData); - drag->setPixmap(getDropPixmap(px)); - drag->setHotSpot(-QPoint(5, 5)); - drag->exec(Qt::CopyAction | Qt::MoveAction, Qt::MoveAction); - } else if (event->button() == Qt::LeftButton && QApplication::keyboardModifiers().testFlag(Qt::ShiftModifier)) { - // Save current playback state when scrubbing - resume_after_scrub = !can->isPaused(); - if (resume_after_scrub) { - can->pause(true); - } - is_scrubbing = true; - } else { - QChartView::mousePressEvent(event); - } -} - -void ChartView::mouseReleaseEvent(QMouseEvent *event) { - auto rubber = findChild(); - if (event->button() == Qt::LeftButton && rubber && rubber->isVisible()) { - rubber->hide(); - auto rect = rubber->geometry().normalized(); - // Prevent zooming/seeking past the end of the route - double min = std::clamp(chart()->mapToValue(rect.topLeft()).x(), can->minSeconds(), can->maxSeconds()); - double max = std::clamp(chart()->mapToValue(rect.bottomRight()).x(), can->minSeconds(), can->maxSeconds()); - if (rubber->width() <= 0) { - // no rubber dragged, seek to mouse position - can->seekTo(min); - } else if (rubber->width() > 10 && (max - min) > MIN_ZOOM_SECONDS) { - charts_widget->zoom_undo_stack->push(new ZoomCommand({min, max})); - } else { - viewport()->update(); - } - event->accept(); - } else if (event->button() == Qt::RightButton) { - charts_widget->zoom_undo_stack->undo(); - event->accept(); - } else { - QGraphicsView::mouseReleaseEvent(event); - } - - // Resume playback if we were scrubbing - is_scrubbing = false; - if (resume_after_scrub) { - can->pause(false); - resume_after_scrub = false; - } -} - -void ChartView::mouseMoveEvent(QMouseEvent *ev) { - const auto plot_area = chart()->plotArea(); - // Scrubbing - if (is_scrubbing && QApplication::keyboardModifiers().testFlag(Qt::ShiftModifier)) { - if (plot_area.contains(ev->pos())) { - can->seekTo(std::clamp(chart()->mapToValue(ev->pos()).x(), can->minSeconds(), can->maxSeconds())); - } - } - - auto rubber = findChild(); - bool is_zooming = rubber && rubber->isVisible(); - clearTrackPoints(); - - if (!is_zooming && plot_area.contains(ev->pos()) && isActiveWindow()) { - charts_widget->showValueTip(secondsAtPoint(ev->pos())); - } else if (tip_label->isVisible()) { - charts_widget->showValueTip(-1); - } - - QChartView::mouseMoveEvent(ev); - if (is_zooming) { - QRect rubber_rect = rubber->geometry(); - rubber_rect.setLeft(std::max(rubber_rect.left(), (int)plot_area.left())); - rubber_rect.setRight(std::min(rubber_rect.right(), (int)plot_area.right())); - if (rubber_rect != rubber->geometry()) { - rubber->setGeometry(rubber_rect); - } - viewport()->update(); - } -} - -void ChartView::showTip(double sec) { - QRect tip_area(0, chart()->plotArea().top(), rect().width(), chart()->plotArea().height()); - QRect visible_rect = charts_widget->chartVisibleRect(this).intersected(tip_area); - if (visible_rect.isEmpty()) { - tip_label->hide(); - return; - } - - tooltip_x = chart()->mapToPosition({sec, 0}).x(); - qreal x = -1; - QStringList text_list; - for (auto &s : sigs) { - if (s.series->isVisible()) { - QString value = "--"; - // use reverse iterator to find last item <= sec. - auto it = std::lower_bound(s.vals.crbegin(), s.vals.crend(), sec, [](auto &p, double x) { return p.x() > x; }); - if (it != s.vals.crend() && it->x() >= axis_x->min()) { - value = s.sig->formatValue(it->y(), false); - s.track_pt = *it; - x = std::max(x, chart()->mapToPosition(*it).x()); - } - QString name = sigs.size() > 1 ? s.sig->name + ": " : ""; - QString min = s.min == std::numeric_limits::max() ? "--" : QString::number(s.min); - QString max = s.max == std::numeric_limits::lowest() ? "--" : QString::number(s.max); - text_list << QString("%2%3 (%4, %5)") - .arg(s.series->color().name(), name, value, min, max); - } - } - if (x < 0) { - x = tooltip_x; - } - QPoint pt(x, chart()->plotArea().top()); - text_list.push_front(QString::number(chart()->mapToValue({x, 0}).x(), 'f', 3)); - QString text = "

" % text_list.join("
") % "

"; - tip_label->showText(pt, text, this, visible_rect); - viewport()->update(); -} - -void ChartView::hideTip() { - clearTrackPoints(); - tooltip_x = -1; - tip_label->hide(); - viewport()->update(); -} - -void ChartView::dragEnterEvent(QDragEnterEvent *event) { - if (event->mimeData()->hasFormat(CHART_MIME_TYPE)) { - drawDropIndicator(event->source() != this); - event->acceptProposedAction(); - } -} - -void ChartView::dragMoveEvent(QDragMoveEvent *event) { - if (event->mimeData()->hasFormat(CHART_MIME_TYPE)) { - event->setDropAction(event->source() == this ? Qt::MoveAction : Qt::CopyAction); - event->accept(); - } - charts_widget->startAutoScroll(); -} - -void ChartView::dropEvent(QDropEvent *event) { - if (event->mimeData()->hasFormat(CHART_MIME_TYPE)) { - if (event->source() != this) { - ChartView *source_chart = (ChartView *)event->source(); - for (auto &s : source_chart->sigs) { - source_chart->chart()->removeSeries(s.series); - addSeries(s.series); - } - sigs.insert(sigs.end(), std::move_iterator(source_chart->sigs.begin()), std::move_iterator(source_chart->sigs.end())); - updateAxisY(); - updateTitle(); - startAnimation(); - - source_chart->sigs.clear(); - charts_widget->removeChart(source_chart); - event->acceptProposedAction(); - } - can_drop = false; - } -} - -void ChartView::resetChartCache() { - chart_pixmap = QPixmap(); - viewport()->update(); -} - -void ChartView::startAnimation() { - QGraphicsOpacityEffect *eff = new QGraphicsOpacityEffect(this); - viewport()->setGraphicsEffect(eff); - QPropertyAnimation *a = new QPropertyAnimation(eff, "opacity"); - a->setDuration(250); - a->setStartValue(0.3); - a->setEndValue(1); - a->setEasingCurve(QEasingCurve::InBack); - a->start(QPropertyAnimation::DeleteWhenStopped); -} - -void ChartView::paintEvent(QPaintEvent *event) { - if (!can->liveStreaming()) { - if (chart_pixmap.isNull()) { - const qreal dpr = viewport()->devicePixelRatioF(); - chart_pixmap = QPixmap(viewport()->size() * dpr); - chart_pixmap.setDevicePixelRatio(dpr); - QPainter p(&chart_pixmap); - p.setRenderHints(QPainter::Antialiasing); - drawBackground(&p, viewport()->rect()); - scene()->setSceneRect(viewport()->rect()); - scene()->render(&p, viewport()->rect()); - } - - QPainter painter(viewport()); - painter.setRenderHints(QPainter::Antialiasing); - painter.drawPixmap(QPoint(), chart_pixmap); - if (can_drop) { - painter.setPen(QPen(palette().color(QPalette::Highlight), 4)); - painter.drawRect(viewport()->rect()); - } - QRectF exposed_rect = mapToScene(event->region().boundingRect()).boundingRect(); - drawForeground(&painter, exposed_rect); - } else { - QChartView::paintEvent(event); - } -} - -void ChartView::drawBackground(QPainter *painter, const QRectF &rect) { - painter->fillRect(rect, palette().color(QPalette::Base)); -} - -void ChartView::drawForeground(QPainter *painter, const QRectF &rect) { - drawTimeline(painter); - drawSignalValue(painter); - // draw track points - painter->setPen(Qt::NoPen); - qreal track_line_x = -1; - for (auto &s : sigs) { - if (!s.track_pt.isNull() && s.series->isVisible()) { - painter->setBrush(s.series->color().darker(125)); - QPointF pos = chart()->mapToPosition(s.track_pt); - painter->drawEllipse(pos, 5.5, 5.5); - track_line_x = std::max(track_line_x, pos.x()); - } - } - if (track_line_x > 0) { - auto plot_area = chart()->plotArea(); - painter->setPen(QPen(Qt::darkGray, 1, Qt::DashLine)); - painter->drawLine(QPointF{track_line_x, plot_area.top()}, QPointF{track_line_x, plot_area.bottom()}); - } - - // paint points. OpenGL mode lacks certain features (such as showing points) - painter->setPen(Qt::NoPen); - for (auto &s : sigs) { - if (s.series->useOpenGL() && s.series->isVisible() && s.series->pointsVisible()) { - auto first = std::lower_bound(s.vals.cbegin(), s.vals.cend(), axis_x->min(), xLessThan); - auto last = std::lower_bound(first, s.vals.cend(), axis_x->max(), xLessThan); - painter->setBrush(s.series->color()); - for (auto it = first; it != last; ++it) { - painter->drawEllipse(chart()->mapToPosition(*it), 4, 4); - } - } - } - - drawRubberBandTimeRange(painter); -} - -void ChartView::drawRubberBandTimeRange(QPainter *painter) { - auto rubber = findChild(); - if (rubber && rubber->isVisible() && rubber->width() > 1) { - painter->setPen(Qt::white); - auto rubber_rect = rubber->geometry().normalized(); - for (const auto &pt : {rubber_rect.bottomLeft(), rubber_rect.bottomRight()}) { - QString sec = QString::number(chart()->mapToValue(pt).x(), 'f', 2); - auto r = painter->fontMetrics().boundingRect(sec).adjusted(-6, -AXIS_X_TOP_MARGIN, 6, AXIS_X_TOP_MARGIN); - pt == rubber_rect.bottomLeft() ? r.moveTopRight(pt + QPoint{0, 2}) : r.moveTopLeft(pt + QPoint{0, 2}); - painter->fillRect(r, Qt::gray); - painter->drawText(r, Qt::AlignCenter, sec); - } - } -} - -void ChartView::drawTimeline(QPainter *painter) { - const auto plot_area = chart()->plotArea(); - // draw vertical time line - qreal x = std::clamp(chart()->mapToPosition(QPointF{cur_sec, 0}).x(), plot_area.left(), plot_area.right()); - painter->setPen(QPen(chart()->titleBrush().color(), 1)); - painter->drawLine(QPointF{x, plot_area.top() - 1}, QPointF{x, plot_area.bottom() + 1}); - - // draw current time under the axis-x - QString time_str = QString::number(cur_sec, 'f', 2); - QSize time_str_size = QFontMetrics(axis_x->labelsFont()).size(Qt::TextSingleLine, time_str) + QSize(8, 2); - QRectF time_str_rect(QPointF(x - time_str_size.width() / 2.0, plot_area.bottom() + AXIS_X_TOP_MARGIN), time_str_size); - QPainterPath path; - path.addRoundedRect(time_str_rect, 3, 3); - painter->fillPath(path, settings.theme == DARK_THEME ? Qt::darkGray : Qt::gray); - painter->setPen(palette().color(QPalette::BrightText)); - painter->setFont(axis_x->labelsFont()); - painter->drawText(time_str_rect, Qt::AlignCenter, time_str); -} - -void ChartView::drawSignalValue(QPainter *painter) { - auto item_group = qgraphicsitem_cast(chart()->legend()->childItems()[0]); - assert(item_group != nullptr); - auto legend_markers = item_group->childItems(); - assert(legend_markers.size() == sigs.size()); - - painter->setFont(signal_value_font); - painter->setPen(chart()->legend()->labelColor()); - int i = 0; - for (auto &s : sigs) { - auto it = std::lower_bound(s.vals.crbegin(), s.vals.crend(), cur_sec, - [](auto &p, double x) { return p.x() > x + EPSILON; }); - QString value = (it != s.vals.crend() && it->x() >= axis_x->min()) ? s.sig->formatValue(it->y()) : "--"; - QRectF marker_rect = legend_markers[i++]->sceneBoundingRect(); - QRectF value_rect(marker_rect.bottomLeft() - QPoint(0, 1), marker_rect.size()); - QString elided_val = painter->fontMetrics().elidedText(value, Qt::ElideRight, value_rect.width()); - painter->drawText(value_rect, Qt::AlignHCenter | Qt::AlignTop, elided_val); - } -} - -QXYSeries *ChartView::createSeries(SeriesType type, QColor color) { - QXYSeries *series = nullptr; - if (type == SeriesType::Line) { - series = new QLineSeries(this); - chart()->legend()->setMarkerShape(QLegend::MarkerShapeRectangle); - } else if (type == SeriesType::StepLine) { - series = new QLineSeries(this); - chart()->legend()->setMarkerShape(QLegend::MarkerShapeFromSeries); - } else { - series = new QScatterSeries(this); - static_cast(series)->setBorderColor(color); - chart()->legend()->setMarkerShape(QLegend::MarkerShapeCircle); - } - series->setColor(color); - // TODO: Due to a bug in CameraWidget the camera frames - // are drawn instead of the graphs on MacOS. Re-enable OpenGL when fixed -#ifndef __APPLE__ - series->setUseOpenGL(true); - // Qt doesn't properly apply device pixel ratio in OpenGL mode - QPen pen = series->pen(); - pen.setWidthF(2.0 * devicePixelRatioF()); - series->setPen(pen); -#endif - addSeries(series); - return series; -} - -void ChartView::addSeries(QXYSeries *series) { - setSeriesColor(series, series->color()); - chart()->addSeries(series); - series->attachAxis(axis_x); - series->attachAxis(axis_y); - - // disables the delivery of mouse events to the opengl widget. - // this enables the user to select the zoom area when the mouse press on the data point. - auto glwidget = findChild(); - if (glwidget && !glwidget->testAttribute(Qt::WA_TransparentForMouseEvents)) { - glwidget->setAttribute(Qt::WA_TransparentForMouseEvents); - } -} - -void ChartView::setSeriesColor(QXYSeries *series, QColor color) { - auto existing_series = chart()->series(); - for (auto s : existing_series) { - if (s != series && std::abs(color.hueF() - qobject_cast(s)->color().hueF()) < 0.1) { - // use different color to distinguish it from others. - auto last_color = qobject_cast(existing_series.back())->color(); - color.setHsvF(std::fmod(last_color.hueF() + 60 / 360.0, 1.0), - QRandomGenerator::global()->bounded(35, 100) / 100.0, - QRandomGenerator::global()->bounded(85, 100) / 100.0); - break; - } - } - series->setColor(color); -} - -void ChartView::setSeriesType(SeriesType type) { - if (type != series_type) { - series_type = type; - for (auto &s : sigs) { - chart()->removeSeries(s.series); - s.series->deleteLater(); - } - for (auto &s : sigs) { - s.series = createSeries(series_type, s.sig->color); - s.series->replace(QVector::fromStdVector(series_type == SeriesType::StepLine ? s.step_vals : s.vals)); - } - updateSeriesPoints(); - updateTitle(); - - menu->actions()[(int)type]->setChecked(true); - } -} - -void ChartView::handleMarkerClicked() { - auto marker = qobject_cast(sender()); - Q_ASSERT(marker); - if (sigs.size() > 1) { - auto series = marker->series(); - series->setVisible(!series->isVisible()); - marker->setVisible(true); - updateAxisY(); - updateTitle(); - } -} diff --git a/tools/cabana/chart/chart.h b/tools/cabana/chart/chart.h deleted file mode 100644 index f9472bd4f6..0000000000 --- a/tools/cabana/chart/chart.h +++ /dev/null @@ -1,123 +0,0 @@ -#pragma once - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -using namespace QtCharts; - -#include "tools/cabana/chart/tiplabel.h" -#include "tools/cabana/dbc/dbcmanager.h" -#include "tools/cabana/streams/abstractstream.h" - -enum class SeriesType { - Line = 0, - StepLine, - Scatter -}; - -class ChartsWidget; -class ChartView : public QChartView { - Q_OBJECT - -public: - ChartView(const std::pair &x_range, ChartsWidget *parent = nullptr); - void addSignal(const MessageId &msg_id, const cabana::Signal *sig); - bool hasSignal(const MessageId &msg_id, const cabana::Signal *sig) const; - void updateSeries(const cabana::Signal *sig = nullptr, const MessageEventsMap *msg_new_events = nullptr); - void updatePlot(double cur, double min, double max); - void setSeriesType(SeriesType type); - void updatePlotArea(int left, bool force = false); - void showTip(double sec); - void hideTip(); - void startAnimation(); - double secondsAtPoint(const QPointF &pt) const { return chart()->mapToValue(pt).x(); } - - struct SigItem { - MessageId msg_id; - const cabana::Signal *sig = nullptr; - QXYSeries *series = nullptr; - std::vector vals; - std::vector step_vals; - QPointF track_pt{}; - SegmentTree segment_tree; - double min = 0; - double max = 0; - }; - -signals: - void axisYLabelWidthChanged(int w); - -private slots: - void signalUpdated(const cabana::Signal *sig); - void manageSignals(); - void handleMarkerClicked(); - void msgUpdated(MessageId id); - void msgRemoved(MessageId id) { removeIf([=](auto &s) { return s.msg_id.address == id.address && !dbc()->msg(id); }); } - void signalRemoved(const cabana::Signal *sig) { removeIf([=](auto &s) { return s.sig == sig; }); } - -private: - void appendCanEvents(const cabana::Signal *sig, const std::vector &events, - std::vector &vals, std::vector &step_vals); - void createToolButtons(); - void addSeries(QXYSeries *series); - void contextMenuEvent(QContextMenuEvent *event) override; - void mousePressEvent(QMouseEvent *event) override; - void mouseReleaseEvent(QMouseEvent *event) override; - void mouseMoveEvent(QMouseEvent *ev) override; - void dragEnterEvent(QDragEnterEvent *event) override; - void dragLeaveEvent(QDragLeaveEvent *event) override { drawDropIndicator(false); } - void dragMoveEvent(QDragMoveEvent *event) override; - void dropEvent(QDropEvent *event) override; - void resizeEvent(QResizeEvent *event) override; - QSize sizeHint() const override; - void updateAxisY(); - void updateTitle(); - void resetChartCache(); - void setTheme(QChart::ChartTheme theme); - void paintEvent(QPaintEvent *event) override; - void drawForeground(QPainter *painter, const QRectF &rect) override; - void drawBackground(QPainter *painter, const QRectF &rect) override; - void drawDropIndicator(bool draw) { if (std::exchange(can_drop, draw) != can_drop) viewport()->update(); } - void drawSignalValue(QPainter *painter); - void drawTimeline(QPainter *painter); - void drawRubberBandTimeRange(QPainter *painter); - std::tuple getNiceAxisNumbers(qreal min, qreal max, int tick_count); - qreal niceNumber(qreal x, bool ceiling); - QXYSeries *createSeries(SeriesType type, QColor color); - void setSeriesColor(QXYSeries *, QColor color); - void updateSeriesPoints(); - void removeIf(std::function predicate); - inline void clearTrackPoints() { for (auto &s : sigs) s.track_pt = {}; } - - int y_label_width = 0; - int align_to = 0; - QValueAxis *axis_x; - QValueAxis *axis_y; - QMenu *menu; - QAction *split_chart_act; - QAction *close_act; - QGraphicsPixmapItem *move_icon; - QGraphicsProxyWidget *close_btn_proxy; - QGraphicsProxyWidget *manage_btn_proxy; - TipLabel *tip_label; - std::vector sigs; - double cur_sec = 0; - SeriesType series_type = SeriesType::Line; - bool is_scrubbing = false; - bool resume_after_scrub = false; - QPixmap chart_pixmap; - bool can_drop = false; - double tooltip_x = -1; - QFont signal_value_font; - ChartsWidget *charts_widget; - friend class ChartsWidget; -}; diff --git a/tools/cabana/chart/chartswidget.cc b/tools/cabana/chart/chartswidget.cc deleted file mode 100644 index 08840f4663..0000000000 --- a/tools/cabana/chart/chartswidget.cc +++ /dev/null @@ -1,569 +0,0 @@ -#include "tools/cabana/chart/chartswidget.h" - -#include - -#include -#include -#include -#include -#include -#include - -#include "tools/cabana/chart/chart.h" - -const int MAX_COLUMN_COUNT = 4; -const int CHART_SPACING = 4; - -ChartsWidget::ChartsWidget(QWidget *parent) : QFrame(parent) { - align_timer = new QTimer(this); - auto_scroll_timer = new QTimer(this); - setFrameStyle(QFrame::StyledPanel | QFrame::Plain); - QVBoxLayout *main_layout = new QVBoxLayout(this); - main_layout->setContentsMargins(0, 0, 0, 0); - main_layout->setSpacing(0); - - // toolbar - toolbar = new QToolBar(tr("Charts"), this); - int icon_size = style()->pixelMetric(QStyle::PM_SmallIconSize); - toolbar->setIconSize({icon_size, icon_size}); - - auto new_plot_btn = new ToolButton("file-plus", tr("New Chart")); - auto new_tab_btn = new ToolButton("window-stack", tr("New Tab")); - toolbar->addWidget(new_plot_btn); - toolbar->addWidget(new_tab_btn); - toolbar->addWidget(title_label = new QLabel()); - title_label->setContentsMargins(0, 0, style()->pixelMetric(QStyle::PM_LayoutHorizontalSpacing), 0); - - auto chart_type_action = toolbar->addAction(""); - QMenu *chart_type_menu = new QMenu(this); - auto types = std::array{tr("Line"), tr("Step"), tr("Scatter")}; - for (int i = 0; i < types.size(); ++i) { - QString type_text = types[i]; - chart_type_menu->addAction(type_text, this, [=]() { - settings.chart_series_type = i; - chart_type_action->setText("Type: " + type_text); - settingChanged(); - }); - } - chart_type_action->setText("Type: " + types[settings.chart_series_type]); - chart_type_action->setMenu(chart_type_menu); - qobject_cast(toolbar->widgetForAction(chart_type_action))->setPopupMode(QToolButton::InstantPopup); - - QMenu *menu = new QMenu(this); - for (int i = 0; i < MAX_COLUMN_COUNT; ++i) { - menu->addAction(tr("%1").arg(i + 1), [=]() { setColumnCount(i + 1); }); - } - columns_action = toolbar->addAction(""); - columns_action->setMenu(menu); - qobject_cast(toolbar->widgetForAction(columns_action))->setPopupMode(QToolButton::InstantPopup); - - QWidget *spacer = new QWidget(this); - spacer->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred); - toolbar->addWidget(spacer); - - range_lb_action = toolbar->addWidget(range_lb = new QLabel(this)); - range_slider = new LogSlider(1000, Qt::Horizontal, this); - range_slider->setFixedWidth(150 * qApp->devicePixelRatio()); - range_slider->setToolTip(tr("Set the chart range")); - range_slider->setRange(1, settings.max_cached_minutes * 60); - range_slider->setSingleStep(1); - range_slider->setPageStep(60); // 1 min - range_slider_action = toolbar->addWidget(range_slider); - - // zoom controls - zoom_undo_stack = new QUndoStack(this); - toolbar->addAction(undo_zoom_action = zoom_undo_stack->createUndoAction(this)); - undo_zoom_action->setIcon(utils::icon("arrow-counterclockwise")); - toolbar->addAction(redo_zoom_action = zoom_undo_stack->createRedoAction(this)); - redo_zoom_action->setIcon(utils::icon("arrow-clockwise")); - reset_zoom_action = toolbar->addWidget(reset_zoom_btn = new ToolButton("zoom-out", tr("Reset Zoom"))); - reset_zoom_btn->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); - - toolbar->addWidget(remove_all_btn = new ToolButton("x-square", tr("Remove all charts"))); - toolbar->addWidget(dock_btn = new ToolButton("")); - main_layout->addWidget(toolbar); - - // tabbar - tabbar = new TabBar(this); - tabbar->setAutoHide(true); - tabbar->setExpanding(false); - tabbar->setDrawBase(true); - tabbar->setAcceptDrops(true); - tabbar->setChangeCurrentOnDrag(true); - tabbar->setUsesScrollButtons(true); - main_layout->addWidget(tabbar); - - // charts - charts_container = new ChartsContainer(this); - charts_container->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); - charts_scroll = new QScrollArea(this); - charts_scroll->viewport()->setBackgroundRole(QPalette::Base); - charts_scroll->setFrameStyle(QFrame::NoFrame); - charts_scroll->setWidgetResizable(true); - charts_scroll->setWidget(charts_container); - charts_scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - main_layout->addWidget(charts_scroll); - - // init settings - current_theme = settings.theme; - column_count = std::clamp(settings.chart_column_count, 1, MAX_COLUMN_COUNT); - max_chart_range = std::clamp(settings.chart_range, 1, settings.max_cached_minutes * 60); - display_range = std::make_pair(can->minSeconds(), can->minSeconds() + max_chart_range); - range_slider->setValue(max_chart_range); - updateToolBar(); - - align_timer->setSingleShot(true); - QObject::connect(align_timer, &QTimer::timeout, this, &ChartsWidget::alignCharts); - QObject::connect(auto_scroll_timer, &QTimer::timeout, this, &ChartsWidget::doAutoScroll); - QObject::connect(dbc(), &DBCManager::DBCFileChanged, this, &ChartsWidget::removeAll); - QObject::connect(can, &AbstractStream::eventsMerged, this, &ChartsWidget::eventsMerged); - QObject::connect(can, &AbstractStream::msgsReceived, this, &ChartsWidget::updateState); - QObject::connect(can, &AbstractStream::seeking, this, &ChartsWidget::updateState); - QObject::connect(can, &AbstractStream::timeRangeChanged, this, &ChartsWidget::timeRangeChanged); - QObject::connect(range_slider, &QSlider::valueChanged, this, &ChartsWidget::setMaxChartRange); - QObject::connect(new_plot_btn, &QToolButton::clicked, this, &ChartsWidget::newChart); - QObject::connect(remove_all_btn, &QToolButton::clicked, this, &ChartsWidget::removeAll); - QObject::connect(reset_zoom_btn, &QToolButton::clicked, this, &ChartsWidget::zoomReset); - QObject::connect(&settings, &Settings::changed, this, &ChartsWidget::settingChanged); - QObject::connect(new_tab_btn, &QToolButton::clicked, this, &ChartsWidget::newTab); - QObject::connect(this, &ChartsWidget::seriesChanged, this, &ChartsWidget::updateTabBar); - QObject::connect(tabbar, &QTabBar::tabCloseRequested, this, &ChartsWidget::removeTab); - QObject::connect(tabbar, &QTabBar::currentChanged, [this](int index) { - if (index != -1) updateLayout(true); - }); - QObject::connect(dock_btn, &QToolButton::clicked, this, &ChartsWidget::toggleChartsDocking); - - setIsDocked(true); - newTab(); - qApp->installEventFilter(this); - setWhatsThis(tr(R"( - Chart View
- Click: Click to seek to a corresponding time.
- Drag: Zoom into the chart.
- Shift + Drag: Scrub through the chart to view values.
- Right Mouse: Open the context menu.
- )")); -} - -void ChartsWidget::newTab() { - static int tab_unique_id = 0; - int idx = tabbar->addTab(""); - tabbar->setTabData(idx, tab_unique_id++); - tabbar->setCurrentIndex(idx); - updateTabBar(); -} - -void ChartsWidget::removeTab(int index) { - int id = tabbar->tabData(index).toInt(); - for (auto &c : tab_charts[id]) { - removeChart(c); - } - tab_charts.erase(id); - tabbar->removeTab(index); - updateTabBar(); -} - -void ChartsWidget::updateTabBar() { - for (int i = 0; i < tabbar->count(); ++i) { - const auto &charts_in_tab = tab_charts[tabbar->tabData(i).toInt()]; - tabbar->setTabText(i, QString("Tab %1 (%2)").arg(i + 1).arg(charts_in_tab.count())); - } -} - -void ChartsWidget::eventsMerged(const MessageEventsMap &new_events) { - QFutureSynchronizer future_synchronizer; - for (auto c : charts) { - future_synchronizer.addFuture(QtConcurrent::run(c, &ChartView::updateSeries, nullptr, &new_events)); - } -} - -void ChartsWidget::timeRangeChanged(const std::optional> &time_range) { - updateToolBar(); - updateState(); -} - -void ChartsWidget::zoomReset() { - can->setTimeRange(std::nullopt); - zoom_undo_stack->clear(); -} - -QRect ChartsWidget::chartVisibleRect(ChartView *chart) { - const QRect visible_rect(-charts_container->pos(), charts_scroll->viewport()->size()); - return chart->rect().intersected(QRect(chart->mapFrom(charts_container, visible_rect.topLeft()), visible_rect.size())); -} - -void ChartsWidget::showValueTip(double sec) { - emit showTip(sec); - if (sec < 0 && !value_tip_visible_) return; - - value_tip_visible_ = sec >= 0; - for (auto c : currentCharts()) { - value_tip_visible_ ? c->showTip(sec) : c->hideTip(); - } -} - -void ChartsWidget::updateState() { - if (charts.isEmpty()) return; - - const auto &time_range = can->timeRange(); - const double cur_sec = can->currentSec(); - if (!time_range.has_value()) { - double pos = (cur_sec - display_range.first) / std::max(1.0, max_chart_range); - if (pos < 0 || pos > 0.8) { - display_range.first = std::max(can->minSeconds(), cur_sec - max_chart_range * 0.1); - } - double max_sec = std::min(display_range.first + max_chart_range, can->maxSeconds()); - display_range.first = std::max(can->minSeconds(), max_sec - max_chart_range); - display_range.second = display_range.first + max_chart_range; - } - - const auto &range = time_range ? *time_range : display_range; - for (auto c : charts) { - c->updatePlot(cur_sec, range.first, range.second); - } -} - -void ChartsWidget::setMaxChartRange(int value) { - max_chart_range = settings.chart_range = range_slider->value(); - updateToolBar(); - updateState(); -} - -void ChartsWidget::setIsDocked(bool docked) { - is_docked = docked; - dock_btn->setIcon(is_docked ? "arrow-up-right-square" : "arrow-down-left-square"); - dock_btn->setToolTip(is_docked ? tr("Float the charts window") : tr("Dock the charts window")); -} - -void ChartsWidget::updateToolBar() { - title_label->setText(tr("Charts: %1").arg(charts.size())); - columns_action->setText(tr("Columns: %1").arg(column_count)); - range_lb->setText(utils::formatSeconds(max_chart_range)); - - bool is_zoomed = can->timeRange().has_value(); - range_lb_action->setVisible(!is_zoomed); - range_slider_action->setVisible(!is_zoomed); - undo_zoom_action->setVisible(is_zoomed); - redo_zoom_action->setVisible(is_zoomed); - reset_zoom_action->setVisible(is_zoomed); - reset_zoom_btn->setText(is_zoomed ? tr("%1-%2").arg(can->timeRange()->first, 0, 'f', 2).arg(can->timeRange()->second, 0, 'f', 2) : ""); - remove_all_btn->setEnabled(!charts.isEmpty()); -} - -void ChartsWidget::settingChanged() { - if (std::exchange(current_theme, settings.theme) != current_theme) { - undo_zoom_action->setIcon(utils::icon("arrow-counterclockwise")); - redo_zoom_action->setIcon(utils::icon("arrow-clockwise")); - auto theme = settings.theme == DARK_THEME ? QChart::QChart::ChartThemeDark : QChart::ChartThemeLight; - for (auto c : charts) { - c->setTheme(theme); - } - } - if (range_slider->maximum() != settings.max_cached_minutes * 60) { - range_slider->setRange(1, settings.max_cached_minutes * 60); - } - for (auto c : charts) { - c->setFixedHeight(settings.chart_height); - c->setSeriesType((SeriesType)settings.chart_series_type); - c->resetChartCache(); - } -} - -ChartView *ChartsWidget::findChart(const MessageId &id, const cabana::Signal *sig) { - for (auto c : charts) - if (c->hasSignal(id, sig)) return c; - return nullptr; -} - -ChartView *ChartsWidget::createChart(int pos) { - auto chart = new ChartView(can->timeRange().value_or(display_range), this); - chart->setFixedHeight(settings.chart_height); - chart->setMinimumWidth(CHART_MIN_WIDTH); - chart->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed); - QObject::connect(chart, &ChartView::axisYLabelWidthChanged, align_timer, qOverload<>(&QTimer::start)); - pos = std::clamp(pos, 0, charts.size()); - charts.insert(pos, chart); - currentCharts().insert(pos, chart); - updateLayout(true); - updateToolBar(); - return chart; -} - -void ChartsWidget::showChart(const MessageId &id, const cabana::Signal *sig, bool show, bool merge) { - ChartView *chart = findChart(id, sig); - if (show && !chart) { - chart = merge && currentCharts().size() > 0 ? currentCharts().front() : createChart(); - chart->addSignal(id, sig); - updateState(); - } else if (!show && chart) { - chart->removeIf([&](auto &s) { return s.msg_id == id && s.sig == sig; }); - } -} - -void ChartsWidget::splitChart(ChartView *src_chart) { - if (src_chart->sigs.size() > 1) { - int pos = charts.indexOf(src_chart) + 1; - for (auto it = src_chart->sigs.begin() + 1; it != src_chart->sigs.end(); /**/) { - auto c = createChart(pos); - src_chart->chart()->removeSeries(it->series); - - // Restore to the original color - it->series->setColor(it->sig->color); - - c->addSeries(it->series); - c->sigs.emplace_back(std::move(*it)); - c->updateAxisY(); - c->updateTitle(); - it = src_chart->sigs.erase(it); - } - src_chart->updateAxisY(); - src_chart->updateTitle(); - QTimer::singleShot(0, src_chart, &ChartView::resetChartCache); - } -} - -void ChartsWidget::setColumnCount(int n) { - n = std::clamp(n, 1, MAX_COLUMN_COUNT); - if (column_count != n) { - column_count = settings.chart_column_count = n; - updateToolBar(); - updateLayout(); - } -} - -void ChartsWidget::updateLayout(bool force) { - auto charts_layout = charts_container->charts_layout; - int n = MAX_COLUMN_COUNT; - for (; n > 1; --n) { - if ((n * CHART_MIN_WIDTH + (n - 1) * charts_layout->horizontalSpacing()) < charts_layout->geometry().width()) break; - } - - bool show_column_cb = n > 1; - columns_action->setVisible(show_column_cb); - - n = std::min(column_count, n); - auto ¤t_charts = currentCharts(); - if ((current_charts.size() != charts_layout->count() || n != current_column_count) || force) { - current_column_count = n; - charts_container->setUpdatesEnabled(false); - for (auto c : charts) { - c->setVisible(false); - } - for (int i = 0; i < current_charts.size(); ++i) { - charts_layout->addWidget(current_charts[i], i / n, i % n); - if (current_charts[i]->sigs.empty()) { - // the chart will be resized after add signal. delay setVisible to reduce flicker. - QTimer::singleShot(0, current_charts[i], [c = current_charts[i]]() { c->setVisible(true); }); - } else { - current_charts[i]->setVisible(true); - } - } - charts_container->setUpdatesEnabled(true); - } -} - -void ChartsWidget::startAutoScroll() { - auto_scroll_timer->start(50); -} - -void ChartsWidget::stopAutoScroll() { - auto_scroll_timer->stop(); - auto_scroll_count = 0; -} - -void ChartsWidget::doAutoScroll() { - QScrollBar *scroll = charts_scroll->verticalScrollBar(); - if (auto_scroll_count < scroll->pageStep()) { - ++auto_scroll_count; - } - - int value = scroll->value(); - QPoint pos = charts_scroll->viewport()->mapFromGlobal(QCursor::pos()); - QRect area = charts_scroll->viewport()->rect(); - - if (pos.y() - area.top() < settings.chart_height / 2) { - scroll->setValue(value - auto_scroll_count); - } else if (area.bottom() - pos.y() < settings.chart_height / 2) { - scroll->setValue(value + auto_scroll_count); - } - bool vertical_unchanged = value == scroll->value(); - if (vertical_unchanged) { - stopAutoScroll(); - } else { - // mouseMoveEvent to updates the drag-selection rectangle - const QPoint globalPos = charts_scroll->viewport()->mapToGlobal(pos); - const QPoint windowPos = charts_scroll->window()->mapFromGlobal(globalPos); - QMouseEvent mm(QEvent::MouseMove, pos, windowPos, globalPos, - Qt::NoButton, Qt::LeftButton, Qt::NoModifier, Qt::MouseEventSynthesizedByQt); - QApplication::sendEvent(charts_scroll->viewport(), &mm); - } -} - -QSize ChartsWidget::minimumSizeHint() const { - return QSize(CHART_MIN_WIDTH * 1.5 * qApp->devicePixelRatio(), QWidget::minimumSizeHint().height()); -} - -void ChartsWidget::newChart() { - SignalSelector dlg(tr("New Chart"), this); - if (dlg.exec() == QDialog::Accepted) { - auto items = dlg.seletedItems(); - if (!items.isEmpty()) { - auto c = createChart(); - for (auto it : items) { - c->addSignal(it->msg_id, it->sig); - } - } - } -} - -void ChartsWidget::removeChart(ChartView *chart) { - charts.removeOne(chart); - chart->deleteLater(); - for (auto &[_, list] : tab_charts) { - list.removeOne(chart); - } - updateToolBar(); - updateLayout(true); - alignCharts(); - emit seriesChanged(); -} - -void ChartsWidget::removeAll() { - while (tabbar->count() > 1) { - tabbar->removeTab(1); - } - tab_charts.clear(); - - if (!charts.isEmpty()) { - for (auto c : charts) { - delete c; - } - charts.clear(); - emit seriesChanged(); - } - zoomReset(); -} - -void ChartsWidget::alignCharts() { - int plot_left = 0; - for (auto c : charts) { - plot_left = std::max(plot_left, c->y_label_width); - } - plot_left = std::max((plot_left / 10) * 10 + 10, 50); - for (auto c : charts) { - c->updatePlotArea(plot_left); - } -} - -bool ChartsWidget::eventFilter(QObject *o, QEvent *e) { - if (!value_tip_visible_) return false; - - if (e->type() == QEvent::MouseMove) { - bool on_tip = qobject_cast(o) != nullptr; - auto global_pos = static_cast(e)->globalPos(); - - for (const auto &c : charts) { - auto local_pos = c->mapFromGlobal(global_pos); - if (c->chart()->plotArea().contains(local_pos)) { - if (on_tip) { - showValueTip(c->secondsAtPoint(local_pos)); - } - return false; - } - } - - showValueTip(-1); - } else if (e->type() == QEvent::Wheel) { - if (auto tip = qobject_cast(o)) { - // Forward the event to the parent widget - QCoreApplication::sendEvent(tip->parentWidget(), e); - } - } - return false; -} - -bool ChartsWidget::event(QEvent *event) { - bool back_button = false; - switch (event->type()) { - case QEvent::Resize: - updateLayout(); - break; - case QEvent::MouseButtonPress: - back_button = static_cast(event)->button() == Qt::BackButton; - break; - case QEvent::NativeGesture: - back_button = (static_cast(event)->value() == 180); - break; - case QEvent::WindowDeactivate: - case QEvent::FocusOut: - showValueTip(-1); - default: - break; - } - - if (back_button) { - zoom_undo_stack->undo(); - return true; // Return true since the event has been handled - } - return QFrame::event(event); -} - -// ChartsContainer - -ChartsContainer::ChartsContainer(ChartsWidget *parent) : charts_widget(parent), QWidget(parent) { - setAcceptDrops(true); - setBackgroundRole(QPalette::Window); - QVBoxLayout *charts_main_layout = new QVBoxLayout(this); - charts_main_layout->setContentsMargins(0, CHART_SPACING, 0, CHART_SPACING); - charts_layout = new QGridLayout(); - charts_layout->setSpacing(CHART_SPACING); - charts_main_layout->addLayout(charts_layout); - charts_main_layout->addStretch(0); -} - -void ChartsContainer::dragEnterEvent(QDragEnterEvent *event) { - if (event->mimeData()->hasFormat(CHART_MIME_TYPE)) { - event->acceptProposedAction(); - drawDropIndicator(event->pos()); - } -} - -void ChartsContainer::dropEvent(QDropEvent *event) { - if (event->mimeData()->hasFormat(CHART_MIME_TYPE)) { - auto w = getDropAfter(event->pos()); - auto chart = qobject_cast(event->source()); - if (w != chart) { - for (auto &[_, list] : charts_widget->tab_charts) { - list.removeOne(chart); - } - int to = w ? charts_widget->currentCharts().indexOf(w) + 1 : 0; - charts_widget->currentCharts().insert(to, chart); - charts_widget->updateLayout(true); - charts_widget->updateTabBar(); - event->acceptProposedAction(); - chart->startAnimation(); - } - drawDropIndicator({}); - } -} - -void ChartsContainer::paintEvent(QPaintEvent *ev) { - if (!drop_indictor_pos.isNull() && !childAt(drop_indictor_pos)) { - QRect r = geometry(); - r.setHeight(CHART_SPACING); - if (auto insert_after = getDropAfter(drop_indictor_pos)) { - r.moveTop(insert_after->geometry().bottom()); - } - - QPainter p(this); - p.fillRect(r, palette().highlight()); - } -} - -ChartView *ChartsContainer::getDropAfter(const QPoint &pos) const { - auto it = std::find_if(charts_widget->currentCharts().crbegin(), charts_widget->currentCharts().crend(), [&pos](auto c) { - auto area = c->geometry(); - return pos.x() >= area.left() && pos.x() <= area.right() && pos.y() >= area.bottom(); - }); - return it == charts_widget->currentCharts().crend() ? nullptr : *it; -} diff --git a/tools/cabana/chart/sparkline.cc b/tools/cabana/chart/sparkline.cc deleted file mode 100644 index 09f86a095a..0000000000 --- a/tools/cabana/chart/sparkline.cc +++ /dev/null @@ -1,54 +0,0 @@ -#include "tools/cabana/chart/sparkline.h" - -#include -#include -#include - -void Sparkline::update(const MessageId &msg_id, const cabana::Signal *sig, double last_msg_ts, int range, QSize size) { - points.clear(); - double value = 0; - auto [first, last] = can->eventsInRange(msg_id, std::make_pair(last_msg_ts -range, last_msg_ts)); - for (auto it = first; it != last; ++it) { - if (sig->getValue((*it)->dat, (*it)->size, &value)) { - points.emplace_back(((*it)->mono_time - (*first)->mono_time) / 1e9, value); - } - } - - if (points.empty() || size.isEmpty()) { - pixmap = QPixmap(); - return; - } - - const auto [min, max] = std::minmax_element(points.begin(), points.end(), - [](auto &l, auto &r) { return l.y() < r.y(); }); - min_val = min->y() == max->y() ? min->y() - 1 : min->y(); - max_val = min->y() == max->y() ? max->y() + 1 : max->y(); - freq_ = points.size() / std::max(points.back().x() - points.front().x(), 1.0); - render(sig->color, range, size); -} - -void Sparkline::render(const QColor &color, int range, QSize size) { - const double xscale = (size.width() - 1) / (double)range; - const double yscale = (size.height() - 3) / (max_val - min_val); - for (auto &v : points) { - v = QPoint(v.x() * xscale, 1 + std::abs(v.y() - max_val) * yscale); - } - - qreal dpr = qApp->devicePixelRatio(); - size *= dpr; - if (size != pixmap.size()) { - pixmap = QPixmap(size); - } - pixmap.setDevicePixelRatio(dpr); - pixmap.fill(Qt::transparent); - QPainter painter(&pixmap); - painter.setRenderHint(QPainter::Antialiasing, points.size() < 500); - painter.setPen(color); - painter.drawPolyline(points.data(), points.size()); - painter.setPen(QPen(color, 3)); - if ((points.back().x() - points.front().x()) / points.size() > 8) { - painter.drawPoints(points.data(), points.size()); - } else { - painter.drawPoint(points.back()); - } -} diff --git a/tools/cabana/chart/sparkline.h b/tools/cabana/chart/sparkline.h deleted file mode 100644 index 806f0a61eb..0000000000 --- a/tools/cabana/chart/sparkline.h +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once - -#include -#include -#include - -#include "tools/cabana/dbc/dbc.h" -#include "tools/cabana/streams/abstractstream.h" - -class Sparkline { -public: - void update(const MessageId &msg_id, const cabana::Signal *sig, double last_msg_ts, int range, QSize size); - inline double freq() const { return freq_; } - bool isEmpty() const { return pixmap.isNull(); } - - QPixmap pixmap; - double min_val = 0; - double max_val = 0; - -private: - void render(const QColor &color, int range, QSize size); - - std::vector points; - double freq_ = 0; -}; diff --git a/tools/cabana/commands.cc b/tools/cabana/commands.cc deleted file mode 100644 index 52861723f4..0000000000 --- a/tools/cabana/commands.cc +++ /dev/null @@ -1,124 +0,0 @@ -#include - -#include "tools/cabana/commands.h" - -// EditMsgCommand - -EditMsgCommand::EditMsgCommand(const MessageId &id, const QString &name, int size, - const QString &node, const QString &comment, QUndoCommand *parent) - : id(id), new_name(name), new_size(size), new_node(node), new_comment(comment), QUndoCommand(parent) { - if (auto msg = dbc()->msg(id)) { - old_name = msg->name; - old_size = msg->size; - old_node = msg->transmitter; - old_comment = msg->comment; - setText(QObject::tr("edit message %1:%2").arg(name).arg(id.address)); - } else { - setText(QObject::tr("new message %1:%2").arg(name).arg(id.address)); - } -} - -void EditMsgCommand::undo() { - if (old_name.isEmpty()) - dbc()->removeMsg(id); - else - dbc()->updateMsg(id, old_name, old_size, old_node, old_comment); -} - -void EditMsgCommand::redo() { - dbc()->updateMsg(id, new_name, new_size, new_node, new_comment); -} - -// RemoveMsgCommand - -RemoveMsgCommand::RemoveMsgCommand(const MessageId &id, QUndoCommand *parent) : id(id), QUndoCommand(parent) { - if (auto msg = dbc()->msg(id)) { - message = *msg; - setText(QObject::tr("remove message %1:%2").arg(message.name).arg(id.address)); - } -} - -void RemoveMsgCommand::undo() { - if (!message.name.isEmpty()) { - dbc()->updateMsg(id, message.name, message.size, message.transmitter, message.comment); - for (auto s : message.getSignals()) - dbc()->addSignal(id, *s); - } -} - -void RemoveMsgCommand::redo() { - if (!message.name.isEmpty()) - dbc()->removeMsg(id); -} - -// AddSigCommand - -AddSigCommand::AddSigCommand(const MessageId &id, const cabana::Signal &sig, QUndoCommand *parent) - : id(id), signal(sig), QUndoCommand(parent) { - setText(QObject::tr("add signal %1 to %2:%3").arg(sig.name).arg(msgName(id)).arg(id.address)); -} - -void AddSigCommand::undo() { - dbc()->removeSignal(id, signal.name); - if (msg_created) dbc()->removeMsg(id); -} - -void AddSigCommand::redo() { - if (auto msg = dbc()->msg(id); !msg) { - msg_created = true; - dbc()->updateMsg(id, dbc()->newMsgName(id), can->lastMessage(id).dat.size(), "", ""); - } - signal.name = dbc()->newSignalName(id); - signal.max = std::pow(2, signal.size) - 1; - dbc()->addSignal(id, signal); -} - -// RemoveSigCommand - -RemoveSigCommand::RemoveSigCommand(const MessageId &id, const cabana::Signal *sig, QUndoCommand *parent) - : id(id), QUndoCommand(parent) { - sigs.push_back(*sig); - if (sig->type == cabana::Signal::Type::Multiplexor) { - for (const auto &s : dbc()->msg(id)->sigs) { - if (s->type == cabana::Signal::Type::Multiplexed) { - sigs.push_back(*s); - } - } - } - setText(QObject::tr("remove signal %1 from %2:%3").arg(sig->name).arg(msgName(id)).arg(id.address)); -} - -void RemoveSigCommand::undo() { for (const auto &s : sigs) dbc()->addSignal(id, s); } -void RemoveSigCommand::redo() { for (const auto &s : sigs) dbc()->removeSignal(id, s.name); } - -// EditSignalCommand - -EditSignalCommand::EditSignalCommand(const MessageId &id, const cabana::Signal *sig, const cabana::Signal &new_sig, QUndoCommand *parent) - : id(id), QUndoCommand(parent) { - sigs.push_back({*sig, new_sig}); - if (sig->type == cabana::Signal::Type::Multiplexor && new_sig.type == cabana::Signal::Type::Normal) { - // convert all multiplexed signals to normal signals - auto msg = dbc()->msg(id); - assert(msg); - for (const auto &s : msg->sigs) { - if (s->type == cabana::Signal::Type::Multiplexed) { - auto new_s = *s; - new_s.type = cabana::Signal::Type::Normal; - sigs.push_back({*s, new_s}); - } - } - } - setText(QObject::tr("edit signal %1 in %2:%3").arg(sig->name).arg(msgName(id)).arg(id.address)); -} - -void EditSignalCommand::undo() { for (const auto &s : sigs) dbc()->updateSignal(id, s.second.name, s.first); } -void EditSignalCommand::redo() { for (const auto &s : sigs) dbc()->updateSignal(id, s.first.name, s.second); } - -namespace UndoStack { - -QUndoStack *instance() { - static QUndoStack *undo_stack = new QUndoStack(qApp); - return undo_stack; -} - -} // namespace UndoStack diff --git a/tools/cabana/commands.h b/tools/cabana/commands.h deleted file mode 100644 index 0736d9b83f..0000000000 --- a/tools/cabana/commands.h +++ /dev/null @@ -1,72 +0,0 @@ -#pragma once - -#include - -#include -#include - -#include "tools/cabana/dbc/dbcmanager.h" -#include "tools/cabana/streams/abstractstream.h" - -class EditMsgCommand : public QUndoCommand { -public: - EditMsgCommand(const MessageId &id, const QString &name, int size, const QString &node, - const QString &comment, QUndoCommand *parent = nullptr); - void undo() override; - void redo() override; - -private: - const MessageId id; - QString old_name, new_name, old_comment, new_comment, old_node, new_node; - int old_size = 0, new_size = 0; -}; - -class RemoveMsgCommand : public QUndoCommand { -public: - RemoveMsgCommand(const MessageId &id, QUndoCommand *parent = nullptr); - void undo() override; - void redo() override; - -private: - const MessageId id; - cabana::Msg message; -}; - -class AddSigCommand : public QUndoCommand { -public: - AddSigCommand(const MessageId &id, const cabana::Signal &sig, QUndoCommand *parent = nullptr); - void undo() override; - void redo() override; - -private: - const MessageId id; - bool msg_created = false; - cabana::Signal signal = {}; -}; - -class RemoveSigCommand : public QUndoCommand { -public: - RemoveSigCommand(const MessageId &id, const cabana::Signal *sig, QUndoCommand *parent = nullptr); - void undo() override; - void redo() override; - -private: - const MessageId id; - QList sigs; -}; - -class EditSignalCommand : public QUndoCommand { -public: - EditSignalCommand(const MessageId &id, const cabana::Signal *sig, const cabana::Signal &new_sig, QUndoCommand *parent = nullptr); - void undo() override; - void redo() override; - -private: - const MessageId id; - QList> sigs; // QList<{old_sig, new_sig}> -}; - -namespace UndoStack { - QUndoStack *instance(); - inline void push(QUndoCommand *cmd) { instance()->push(cmd); } -}; diff --git a/tools/cabana/dbc/dbc.h b/tools/cabana/dbc/dbc.h deleted file mode 100644 index d2b25bc5f2..0000000000 --- a/tools/cabana/dbc/dbc.h +++ /dev/null @@ -1,120 +0,0 @@ -#pragma once - -#include -#include -#include - -#include -#include -#include - -const QString UNTITLED = "untitled"; -const QString DEFAULT_NODE_NAME = "XXX"; -constexpr int CAN_MAX_DATA_BYTES = 64; - -struct MessageId { - uint8_t source = 0; - uint32_t address = 0; - - QString toString() const { - return QString("%1:%2").arg(source).arg(QString::number(address, 16).toUpper()); - } - - bool operator==(const MessageId &other) const { - return source == other.source && address == other.address; - } - - bool operator!=(const MessageId &other) const { - return !(*this == other); - } - - bool operator<(const MessageId &other) const { - return std::tie(source, address) < std::tie(other.source, other.address); - } - - bool operator>(const MessageId &other) const { - return std::tie(source, address) > std::tie(other.source, other.address); - } -}; - -uint qHash(const MessageId &item); -Q_DECLARE_METATYPE(MessageId); - -template <> -struct std::hash { - std::size_t operator()(const MessageId &k) const noexcept { return qHash(k); } -}; - -typedef std::vector> ValueDescription; - -namespace cabana { - -class Signal { -public: - Signal() = default; - Signal(const Signal &other) = default; - void update(); - bool getValue(const uint8_t *data, size_t data_size, double *val) const; - QString formatValue(double value, bool with_unit = true) const; - bool operator==(const cabana::Signal &other) const; - inline bool operator!=(const cabana::Signal &other) const { return !(*this == other); } - - enum class Type { - Normal = 0, - Multiplexed, - Multiplexor - }; - - Type type = Type::Normal; - QString name; - int start_bit, msb, lsb, size; - double factor = 1.0; - double offset = 0; - bool is_signed; - bool is_little_endian; - double min, max; - QString unit; - QString comment; - QString receiver_name; - ValueDescription val_desc; - int precision = 0; - QColor color; - - // Multiplexed - int multiplex_value = 0; - Signal *multiplexor = nullptr; -}; - -class Msg { -public: - Msg() = default; - Msg(const Msg &other) { *this = other; } - ~Msg(); - cabana::Signal *addSignal(const cabana::Signal &sig); - cabana::Signal *updateSignal(const QString &sig_name, const cabana::Signal &sig); - void removeSignal(const QString &sig_name); - Msg &operator=(const Msg &other); - int indexOf(const cabana::Signal *sig) const; - cabana::Signal *sig(const QString &sig_name) const; - QString newSignalName(); - void update(); - inline const std::vector &getSignals() const { return sigs; } - - uint32_t address; - QString name; - uint32_t size; - QString comment; - QString transmitter; - std::vector sigs; - - std::vector mask; - cabana::Signal *multiplexor = nullptr; -}; - -} // namespace cabana - -// Helper functions -double get_raw_value(const uint8_t *data, size_t data_size, const cabana::Signal &sig); -void updateMsbLsb(cabana::Signal &s); -inline int flipBitPos(int start_bit) { return 8 * (start_bit / 8) + 7 - start_bit % 8; } -inline QString doubleToString(double value) { return QString::number(value, 'g', std::numeric_limits::digits10); } diff --git a/tools/cabana/dbc/dbcfile.cc b/tools/cabana/dbc/dbcfile.cc deleted file mode 100644 index 1c03c8a0aa..0000000000 --- a/tools/cabana/dbc/dbcfile.cc +++ /dev/null @@ -1,274 +0,0 @@ -#include "tools/cabana/dbc/dbcfile.h" - -#include -#include -#include - -DBCFile::DBCFile(const QString &dbc_file_name) { - QFile file(dbc_file_name); - if (file.open(QIODevice::ReadOnly)) { - name_ = QFileInfo(dbc_file_name).baseName(); - filename = dbc_file_name; - parse(file.readAll()); - } else { - throw std::runtime_error("Failed to open file."); - } -} - -DBCFile::DBCFile(const QString &name, const QString &content) : name_(name), filename("") { - parse(content); -} - -bool DBCFile::save() { - assert(!filename.isEmpty()); - return writeContents(filename); -} - -bool DBCFile::saveAs(const QString &new_filename) { - filename = new_filename; - return save(); -} - -bool DBCFile::writeContents(const QString &fn) { - QFile file(fn); - if (file.open(QIODevice::WriteOnly)) { - return file.write(generateDBC().toUtf8()) >= 0; - } - return false; -} - -void DBCFile::updateMsg(const MessageId &id, const QString &name, uint32_t size, const QString &node, const QString &comment) { - auto &m = msgs[id.address]; - m.address = id.address; - m.name = name; - m.size = size; - m.transmitter = node.isEmpty() ? DEFAULT_NODE_NAME : node; - m.comment = comment; -} - -cabana::Msg *DBCFile::msg(uint32_t address) { - auto it = msgs.find(address); - return it != msgs.end() ? &it->second : nullptr; -} - -cabana::Msg *DBCFile::msg(const QString &name) { - auto it = std::find_if(msgs.begin(), msgs.end(), [&name](auto &m) { return m.second.name == name; }); - return it != msgs.end() ? &(it->second) : nullptr; -} - -cabana::Signal *DBCFile::signal(uint32_t address, const QString &name) { - auto m = msg(address); - return m ? (cabana::Signal *)m->sig(name) : nullptr; -} - -void DBCFile::parse(const QString &content) { - msgs.clear(); - - int line_num = 0; - QString line; - cabana::Msg *current_msg = nullptr; - int multiplexor_cnt = 0; - bool seen_first = false; - QTextStream stream((QString *)&content); - - while (!stream.atEnd()) { - ++line_num; - QString raw_line = stream.readLine(); - line = raw_line.trimmed(); - - bool seen = true; - try { - if (line.startsWith("BO_ ")) { - multiplexor_cnt = 0; - current_msg = parseBO(line); - } else if (line.startsWith("SG_ ")) { - parseSG(line, current_msg, multiplexor_cnt); - } else if (line.startsWith("VAL_ ")) { - parseVAL(line); - } else if (line.startsWith("CM_ BO_")) { - parseCM_BO(line, content, raw_line, stream); - } else if (line.startsWith("CM_ SG_ ")) { - parseCM_SG(line, content, raw_line, stream); - } else { - seen = false; - } - } catch (std::exception &e) { - throw std::runtime_error(QString("[%1:%2]%3: %4").arg(filename).arg(line_num).arg(e.what()).arg(line).toStdString()); - } - - if (seen) { - seen_first = true; - } else if (!seen_first) { - header += raw_line + "\n"; - } - } - - for (auto &[_, m] : msgs) { - m.update(); - } -} - -cabana::Msg *DBCFile::parseBO(const QString &line) { - static QRegularExpression bo_regexp(R"(^BO_ (?
\w+) (?\w+) *: (?\w+) (?\w+))"); - - QRegularExpressionMatch match = bo_regexp.match(line); - if (!match.hasMatch()) - throw std::runtime_error("Invalid BO_ line format"); - - uint32_t address = match.captured("address").toUInt(); - if (msgs.count(address) > 0) - throw std::runtime_error(QString("Duplicate message address: %1").arg(address).toStdString()); - - // Create a new message object - cabana::Msg *msg = &msgs[address]; - msg->address = address; - msg->name = match.captured("name"); - msg->size = match.captured("size").toULong(); - msg->transmitter = match.captured("transmitter").trimmed(); - return msg; -} - -void DBCFile::parseCM_BO(const QString &line, const QString &content, const QString &raw_line, const QTextStream &stream) { - static QRegularExpression msg_comment_regexp(R"(^CM_ BO_ *(?
\w+) *\"(?(?:[^"\\]|\\.)*)\"\s*;)"); - - QString parse_line = line; - if (!parse_line.endsWith("\";")) { - int pos = stream.pos() - raw_line.length() - 1; - parse_line = content.mid(pos, content.indexOf("\";", pos)); - } - auto match = msg_comment_regexp.match(parse_line); - if (!match.hasMatch()) - throw std::runtime_error("Invalid message comment format"); - - if (auto m = (cabana::Msg *)msg(match.captured("address").toUInt())) - m->comment = match.captured("comment").trimmed().replace("\\\"", "\""); -} - -void DBCFile::parseSG(const QString &line, cabana::Msg *current_msg, int &multiplexor_cnt) { - static QRegularExpression sg_regexp(R"(^SG_ (\w+) *: (\d+)\|(\d+)@(\d+)([\+|\-]) \(([0-9.+\-eE]+),([0-9.+\-eE]+)\) \[([0-9.+\-eE]+)\|([0-9.+\-eE]+)\] \"(.*)\" (.*))"); - static QRegularExpression sgm_regexp(R"(^SG_ (\w+) (\w+) *: (\d+)\|(\d+)@(\d+)([\+|\-]) \(([0-9.+\-eE]+),([0-9.+\-eE]+)\) \[([0-9.+\-eE]+)\|([0-9.+\-eE]+)\] \"(.*)\" (.*))"); - - if (!current_msg) - throw std::runtime_error("No Message"); - - int offset = 0; - auto match = sg_regexp.match(line); - if (!match.hasMatch()) { - match = sgm_regexp.match(line); - offset = 1; - } - if (!match.hasMatch()) - throw std::runtime_error("Invalid SG_ line format"); - - QString name = match.captured(1); - if (current_msg->sig(name) != nullptr) - throw std::runtime_error("Duplicate signal name"); - - cabana::Signal s{}; - if (offset == 1) { - auto indicator = match.captured(2); - if (indicator == "M") { - ++multiplexor_cnt; - // Only one signal within a single message can be the multiplexer switch. - if (multiplexor_cnt >= 2) - throw std::runtime_error("Multiple multiplexor"); - - s.type = cabana::Signal::Type::Multiplexor; - } else { - s.type = cabana::Signal::Type::Multiplexed; - s.multiplex_value = indicator.mid(1).toInt(); - } - } - s.name = name; - s.start_bit = match.captured(offset + 2).toInt(); - s.size = match.captured(offset + 3).toInt(); - s.is_little_endian = match.captured(offset + 4).toInt() == 1; - s.is_signed = match.captured(offset + 5) == "-"; - s.factor = match.captured(offset + 6).toDouble(); - s.offset = match.captured(offset + 7).toDouble(); - s.min = match.captured(8 + offset).toDouble(); - s.max = match.captured(9 + offset).toDouble(); - s.unit = match.captured(10 + offset); - s.receiver_name = match.captured(11 + offset).trimmed(); - current_msg->sigs.push_back(new cabana::Signal(s)); -} - -void DBCFile::parseCM_SG(const QString &line, const QString &content, const QString &raw_line, const QTextStream &stream) { - static QRegularExpression sg_comment_regexp(R"(^CM_ SG_ *(\w+) *(\w+) *\"((?:[^"\\]|\\.)*)\"\s*;)"); - - QString parse_line = line; - if (!parse_line.endsWith("\";")) { - int pos = stream.pos() - raw_line.length() - 1; - parse_line = content.mid(pos, content.indexOf("\";", pos)); - } - auto match = sg_comment_regexp.match(parse_line); - if (!match.hasMatch()) - throw std::runtime_error("Invalid CM_ SG_ line format"); - - if (auto s = signal(match.captured(1).toUInt(), match.captured(2))) { - s->comment = match.captured(3).trimmed().replace("\\\"", "\""); - } -} - -void DBCFile::parseVAL(const QString &line) { - static QRegularExpression val_regexp(R"(VAL_ (\w+) (\w+) (\s*[-+]?[0-9]+\s+\".+?\"[^;]*))"); - - auto match = val_regexp.match(line); - if (!match.hasMatch()) - throw std::runtime_error("invalid VAL_ line format"); - - if (auto s = signal(match.captured(1).toUInt(), match.captured(2))) { - QStringList desc_list = match.captured(3).trimmed().split('"'); - for (int i = 0; i < desc_list.size(); i += 2) { - auto val = desc_list[i].trimmed(); - if (!val.isEmpty() && (i + 1) < desc_list.size()) { - auto desc = desc_list[i + 1].trimmed(); - s->val_desc.push_back({val.toDouble(), desc}); - } - } - } -} - -QString DBCFile::generateDBC() { - QString dbc_string, comment, val_desc; - for (const auto &[address, m] : msgs) { - const QString transmitter = m.transmitter.isEmpty() ? DEFAULT_NODE_NAME : m.transmitter; - dbc_string += QString("BO_ %1 %2: %3 %4\n").arg(address).arg(m.name).arg(m.size).arg(transmitter); - if (!m.comment.isEmpty()) { - comment += QString("CM_ BO_ %1 \"%2\";\n").arg(address).arg(QString(m.comment).replace("\"", "\\\"")); - } - for (auto sig : m.getSignals()) { - QString multiplexer_indicator; - if (sig->type == cabana::Signal::Type::Multiplexor) { - multiplexer_indicator = "M "; - } else if (sig->type == cabana::Signal::Type::Multiplexed) { - multiplexer_indicator = QString("m%1 ").arg(sig->multiplex_value); - } - dbc_string += QString(" SG_ %1 %2: %3|%4@%5%6 (%7,%8) [%9|%10] \"%11\" %12\n") - .arg(sig->name) - .arg(multiplexer_indicator) - .arg(sig->start_bit) - .arg(sig->size) - .arg(sig->is_little_endian ? '1' : '0') - .arg(sig->is_signed ? '-' : '+') - .arg(doubleToString(sig->factor)) - .arg(doubleToString(sig->offset)) - .arg(doubleToString(sig->min)) - .arg(doubleToString(sig->max)) - .arg(sig->unit) - .arg(sig->receiver_name.isEmpty() ? DEFAULT_NODE_NAME : sig->receiver_name); - if (!sig->comment.isEmpty()) { - comment += QString("CM_ SG_ %1 %2 \"%3\";\n").arg(address).arg(sig->name).arg(QString(sig->comment).replace("\"", "\\\"")); - } - if (!sig->val_desc.empty()) { - QStringList text; - for (auto &[val, desc] : sig->val_desc) { - text << QString("%1 \"%2\"").arg(val).arg(desc); - } - val_desc += QString("VAL_ %1 %2 %3;\n").arg(address).arg(sig->name).arg(text.join(" ")); - } - } - dbc_string += "\n"; - } - return header + dbc_string + comment + val_desc; -} diff --git a/tools/cabana/dbc/dbcfile.h b/tools/cabana/dbc/dbcfile.h deleted file mode 100644 index bd267898f9..0000000000 --- a/tools/cabana/dbc/dbcfile.h +++ /dev/null @@ -1,44 +0,0 @@ -#pragma once - -#include -#include - -#include "tools/cabana/dbc/dbc.h" - -class DBCFile { -public: - DBCFile(const QString &dbc_file_name); - DBCFile(const QString &name, const QString &content); - ~DBCFile() {} - - bool save(); - bool saveAs(const QString &new_filename); - bool writeContents(const QString &fn); - QString generateDBC(); - - void updateMsg(const MessageId &id, const QString &name, uint32_t size, const QString &node, const QString &comment); - inline void removeMsg(const MessageId &id) { msgs.erase(id.address); } - - inline const std::map &getMessages() const { return msgs; } - cabana::Msg *msg(uint32_t address); - cabana::Msg *msg(const QString &name); - inline cabana::Msg *msg(const MessageId &id) { return msg(id.address); } - cabana::Signal *signal(uint32_t address, const QString &name); - - inline QString name() const { return name_.isEmpty() ? "untitled" : name_; } - inline bool isEmpty() const { return msgs.empty() && name_.isEmpty(); } - - QString filename; - -private: - void parse(const QString &content); - cabana::Msg *parseBO(const QString &line); - void parseSG(const QString &line, cabana::Msg *current_msg, int &multiplexor_cnt); - void parseCM_BO(const QString &line, const QString &content, const QString &raw_line, const QTextStream &stream); - void parseCM_SG(const QString &line, const QString &content, const QString &raw_line, const QTextStream &stream); - void parseVAL(const QString &line); - - QString header; - std::map msgs; - QString name_; -}; diff --git a/tools/cabana/dbc/dbcmanager.cc b/tools/cabana/dbc/dbcmanager.cc deleted file mode 100644 index 8e98d95322..0000000000 --- a/tools/cabana/dbc/dbcmanager.cc +++ /dev/null @@ -1,178 +0,0 @@ -#include "tools/cabana/dbc/dbcmanager.h" - -#include -#include -#include - -bool DBCManager::open(const SourceSet &sources, const QString &dbc_file_name, QString *error) { - try { - auto it = std::find_if(dbc_files.begin(), dbc_files.end(), - [&](auto &f) { return f.second && f.second->filename == dbc_file_name; }); - auto file = (it != dbc_files.end()) ? it->second : std::make_shared(dbc_file_name); - for (auto s : sources) { - dbc_files[s] = file; - } - } catch (std::exception &e) { - if (error) *error = e.what(); - return false; - } - - emit DBCFileChanged(); - return true; -} - -bool DBCManager::open(const SourceSet &sources, const QString &name, const QString &content, QString *error) { - try { - auto file = std::make_shared(name, content); - for (auto s : sources) { - dbc_files[s] = file; - } - } catch (std::exception &e) { - if (error) *error = e.what(); - return false; - } - - emit DBCFileChanged(); - return true; -} - -void DBCManager::close(const SourceSet &sources) { - for (auto s : sources) { - dbc_files[s] = nullptr; - } - emit DBCFileChanged(); -} - -void DBCManager::close(DBCFile *dbc_file) { - for (auto &[_, f] : dbc_files) { - if (f.get() == dbc_file) f = nullptr; - } - emit DBCFileChanged(); -} - -void DBCManager::closeAll() { - dbc_files.clear(); - emit DBCFileChanged(); -} - -void DBCManager::addSignal(const MessageId &id, const cabana::Signal &sig) { - if (auto m = msg(id)) { - if (auto s = m->addSignal(sig)) { - emit signalAdded(id, s); - emit maskUpdated(); - } - } -} - -void DBCManager::updateSignal(const MessageId &id, const QString &sig_name, const cabana::Signal &sig) { - if (auto m = msg(id)) { - if (auto s = m->updateSignal(sig_name, sig)) { - emit signalUpdated(s); - emit maskUpdated(); - } - } -} - -void DBCManager::removeSignal(const MessageId &id, const QString &sig_name) { - if (auto m = msg(id)) { - if (auto s = m->sig(sig_name)) { - emit signalRemoved(s); - m->removeSignal(sig_name); - emit maskUpdated(); - } - } -} - -void DBCManager::updateMsg(const MessageId &id, const QString &name, uint32_t size, const QString &node, const QString &comment) { - auto dbc_file = findDBCFile(id); - assert(dbc_file); // This should be impossible - dbc_file->updateMsg(id, name, size, node, comment); - emit msgUpdated(id); -} - -void DBCManager::removeMsg(const MessageId &id) { - auto dbc_file = findDBCFile(id); - assert(dbc_file); // This should be impossible - dbc_file->removeMsg(id); - emit msgRemoved(id); - emit maskUpdated(); -} - -QString DBCManager::newMsgName(const MessageId &id) { - return QString("NEW_MSG_") + QString::number(id.address, 16).toUpper(); -} - -QString DBCManager::newSignalName(const MessageId &id) { - auto m = msg(id); - return m ? m->newSignalName() : ""; -} - -const std::map &DBCManager::getMessages(uint8_t source) { - static std::map empty_msgs; - auto dbc_file = findDBCFile(source); - return dbc_file ? dbc_file->getMessages() : empty_msgs; -} - -cabana::Msg *DBCManager::msg(const MessageId &id) { - auto dbc_file = findDBCFile(id); - return dbc_file ? dbc_file->msg(id) : nullptr; -} - -cabana::Msg *DBCManager::msg(uint8_t source, const QString &name) { - auto dbc_file = findDBCFile(source); - return dbc_file ? dbc_file->msg(name) : nullptr; -} - -QStringList DBCManager::signalNames() { - // Used for autocompletion - QSet names; - for (auto &f : allDBCFiles()) { - for (auto &[_, m] : f->getMessages()) { - for (auto sig : m.getSignals()) { - names.insert(sig->name); - } - } - } - QStringList ret = names.values(); - ret.sort(); - return ret; -} - -int DBCManager::nonEmptyDBCCount() { - auto files = allDBCFiles(); - return std::count_if(files.cbegin(), files.cend(), [](auto &f) { return !f->isEmpty(); }); -} - -DBCFile *DBCManager::findDBCFile(const uint8_t source) { - // Find DBC file that matches id.source, fall back to SOURCE_ALL if no specific DBC is found - auto it = dbc_files.count(source) ? dbc_files.find(source) : dbc_files.find(-1); - return it != dbc_files.end() ? it->second.get() : nullptr; -} - -std::set DBCManager::allDBCFiles() { - std::set files; - for (const auto &[_, f] : dbc_files) { - if (f) files.insert(f.get()); - } - return files; -} - -const SourceSet DBCManager::sources(const DBCFile *dbc_file) const { - SourceSet sources; - for (auto &[s, f] : dbc_files) { - if (f.get() == dbc_file) sources.insert(s); - } - return sources; -} - -QString toString(const SourceSet &ss) { - return std::accumulate(ss.cbegin(), ss.cend(), QString(), [](QString str, int source) { - if (!str.isEmpty()) str += ", "; - return str + (source == -1 ? QStringLiteral("all") : QString::number(source)); - }); -} - -DBCManager *dbc() { - static DBCManager dbc_manager(nullptr); - return &dbc_manager; -} diff --git a/tools/cabana/dbc/dbcmanager.h b/tools/cabana/dbc/dbcmanager.h deleted file mode 100644 index 5f183752d2..0000000000 --- a/tools/cabana/dbc/dbcmanager.h +++ /dev/null @@ -1,69 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -#include "tools/cabana/dbc/dbcfile.h" - -typedef std::set SourceSet; -const SourceSet SOURCE_ALL = {-1}; -const int INVALID_SOURCE = 0xff; -inline bool operator<(const std::shared_ptr &l, const std::shared_ptr &r) { return l.get() < r.get(); } - -class DBCManager : public QObject { - Q_OBJECT - -public: - DBCManager(QObject *parent) : QObject(parent) {} - ~DBCManager() {} - bool open(const SourceSet &sources, const QString &dbc_file_name, QString *error = nullptr); - bool open(const SourceSet &sources, const QString &name, const QString &content, QString *error = nullptr); - void close(const SourceSet &sources); - void close(DBCFile *dbc_file); - void closeAll(); - - void addSignal(const MessageId &id, const cabana::Signal &sig); - void updateSignal(const MessageId &id, const QString &sig_name, const cabana::Signal &sig); - void removeSignal(const MessageId &id, const QString &sig_name); - - void updateMsg(const MessageId &id, const QString &name, uint32_t size, const QString &node, const QString &comment); - void removeMsg(const MessageId &id); - - QString newMsgName(const MessageId &id); - QString newSignalName(const MessageId &id); - - const std::map &getMessages(uint8_t source); - cabana::Msg *msg(const MessageId &id); - cabana::Msg* msg(uint8_t source, const QString &name); - - QStringList signalNames(); - inline int dbcCount() { return allDBCFiles().size(); } - int nonEmptyDBCCount(); - - const SourceSet sources(const DBCFile *dbc_file) const; - DBCFile *findDBCFile(const uint8_t source); - inline DBCFile *findDBCFile(const MessageId &id) { return findDBCFile(id.source); } - std::set allDBCFiles(); - -signals: - void signalAdded(MessageId id, const cabana::Signal *sig); - void signalRemoved(const cabana::Signal *sig); - void signalUpdated(const cabana::Signal *sig); - void msgUpdated(MessageId id); - void msgRemoved(MessageId id); - void DBCFileChanged(); - void maskUpdated(); - -private: - std::map> dbc_files; -}; - -DBCManager *dbc(); - -QString toString(const SourceSet &ss); -inline QString msgName(const MessageId &id) { - auto msg = dbc()->msg(id); - return msg ? msg->name : UNTITLED; -} diff --git a/tools/cabana/mainwin.cc b/tools/cabana/mainwin.cc deleted file mode 100644 index 8361befb53..0000000000 --- a/tools/cabana/mainwin.cc +++ /dev/null @@ -1,655 +0,0 @@ -#include "tools/cabana/mainwin.h" - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "tools/cabana/commands.h" -#include "tools/cabana/streamselector.h" -#include "tools/cabana/tools/findsignal.h" -#include "tools/cabana/utils/export.h" - -MainWindow::MainWindow(AbstractStream *stream, const QString &dbc_file) : QMainWindow() { - loadFingerprints(); - createDockWindows(); - setCentralWidget(center_widget = new CenterWidget(this)); - createActions(); - createStatusBar(); - createShortcuts(); - - // save default window state to allow resetting it - default_state = saveState(); - - // restore states - restoreGeometry(settings.geometry); - if (isMaximized()) { - setGeometry(QApplication::desktop()->availableGeometry(this)); - } - restoreState(settings.window_state); - - // install handlers - static auto static_main_win = this; - qRegisterMetaType("uint64_t"); - qRegisterMetaType("SourceSet"); - installDownloadProgressHandler([](uint64_t cur, uint64_t total, bool success) { - emit static_main_win->updateProgressBar(cur, total, success); - }); - qInstallMessageHandler([](QtMsgType type, const QMessageLogContext &context, const QString &msg) { - if (type == QtDebugMsg) return; - emit static_main_win->showMessage(msg, 2000); - }); - installMessageHandler([](ReplyMsgType type, const std::string msg) { qInfo() << msg.c_str(); }); - - setStyleSheet(QString(R"(QMainWindow::separator { - width: %1px; /* when vertical */ - height: %1px; /* when horizontal */ - })").arg(style()->pixelMetric(QStyle::PM_SplitterWidth))); - - QObject::connect(this, &MainWindow::showMessage, statusBar(), &QStatusBar::showMessage); - QObject::connect(this, &MainWindow::updateProgressBar, this, &MainWindow::updateDownloadProgress); - QObject::connect(dbc(), &DBCManager::DBCFileChanged, this, &MainWindow::DBCFileChanged); - QObject::connect(UndoStack::instance(), &QUndoStack::cleanChanged, this, &MainWindow::undoStackCleanChanged); - QObject::connect(&settings, &Settings::changed, this, &MainWindow::updateStatus); - - QTimer::singleShot(0, this, [=]() { stream ? openStream(stream, dbc_file) : selectAndOpenStream(); }); - show(); -} - -void MainWindow::loadFingerprints() { - QFile json_file(QApplication::applicationDirPath() + "/dbc/car_fingerprint_to_dbc.json"); - if (json_file.open(QIODevice::ReadOnly)) { - fingerprint_to_dbc = QJsonDocument::fromJson(json_file.readAll()); - } -} - -void MainWindow::createActions() { - // File menu - QMenu *file_menu = menuBar()->addMenu(tr("&File")); - file_menu->addAction(tr("Open Stream..."), this, &MainWindow::selectAndOpenStream); - close_stream_act = file_menu->addAction(tr("Close stream"), this, &MainWindow::closeStream); - export_to_csv_act = file_menu->addAction(tr("Export to CSV..."), this, &MainWindow::exportToCSV); - close_stream_act->setEnabled(false); - export_to_csv_act->setEnabled(false); - file_menu->addSeparator(); - - file_menu->addAction(tr("New DBC File"), [this]() { newFile(); }, QKeySequence::New); - file_menu->addAction(tr("Open DBC File..."), [this]() { openFile(); }, QKeySequence::Open); - - manage_dbcs_menu = file_menu->addMenu(tr("Manage &DBC Files")); - QObject::connect(manage_dbcs_menu, &QMenu::aboutToShow, this, &MainWindow::updateLoadSaveMenus); - - open_recent_menu = file_menu->addMenu(tr("Open &Recent")); - QObject::connect(open_recent_menu, &QMenu::aboutToShow, this, &MainWindow::updateRecentFileMenu); - - file_menu->addSeparator(); - QMenu *load_opendbc_menu = file_menu->addMenu(tr("Load DBC from commaai/opendbc")); - // load_opendbc_menu->setStyleSheet("QMenu { menu-scrollable: true; }"); - for (const auto &dbc_name : QDir(OPENDBC_FILE_PATH).entryList({"*.dbc"}, QDir::Files, QDir::Name)) { - load_opendbc_menu->addAction(dbc_name, [this, name = dbc_name]() { loadDBCFromOpendbc(name); }); - } - - file_menu->addAction(tr("Load DBC From Clipboard"), [=]() { loadFromClipboard(); }); - - file_menu->addSeparator(); - save_dbc = file_menu->addAction(tr("Save DBC..."), this, &MainWindow::save, QKeySequence::Save); - save_dbc_as = file_menu->addAction(tr("Save DBC As..."), this, &MainWindow::saveAs, QKeySequence::SaveAs); - copy_dbc_to_clipboard = file_menu->addAction(tr("Copy DBC To Clipboard"), this, &MainWindow::saveToClipboard); - - file_menu->addSeparator(); - file_menu->addAction(tr("Settings..."), this, &MainWindow::setOption, QKeySequence::Preferences); - - file_menu->addSeparator(); - file_menu->addAction(tr("E&xit"), qApp, &QApplication::closeAllWindows, QKeySequence::Quit); - - // Edit Menu - QMenu *edit_menu = menuBar()->addMenu(tr("&Edit")); - auto undo_act = UndoStack::instance()->createUndoAction(this, tr("&Undo")); - undo_act->setShortcuts(QKeySequence::Undo); - edit_menu->addAction(undo_act); - auto redo_act = UndoStack::instance()->createRedoAction(this, tr("&Rndo")); - redo_act->setShortcuts(QKeySequence::Redo); - edit_menu->addAction(redo_act); - edit_menu->addSeparator(); - - QMenu *commands_menu = edit_menu->addMenu(tr("Command &List")); - QWidgetAction *commands_act = new QWidgetAction(this); - commands_act->setDefaultWidget(new QUndoView(UndoStack::instance())); - commands_menu->addAction(commands_act); - - // View Menu - QMenu *view_menu = menuBar()->addMenu(tr("&View")); - auto act = view_menu->addAction(tr("Full Screen"), this, &MainWindow::toggleFullScreen, QKeySequence::FullScreen); - addAction(act); - view_menu->addSeparator(); - view_menu->addAction(messages_dock->toggleViewAction()); - view_menu->addAction(video_dock->toggleViewAction()); - view_menu->addSeparator(); - view_menu->addAction(tr("Reset Window Layout"), [this]() { restoreState(default_state); }); - - // Tools Menu - tools_menu = menuBar()->addMenu(tr("&Tools")); - tools_menu->addAction(tr("Find &Similar Bits"), this, &MainWindow::findSimilarBits); - tools_menu->addAction(tr("&Find Signal"), this, &MainWindow::findSignal); - - // Help Menu - QMenu *help_menu = menuBar()->addMenu(tr("&Help")); - help_menu->addAction(tr("Help"), this, &MainWindow::onlineHelp, QKeySequence::HelpContents); - help_menu->addAction(tr("About &Qt"), qApp, &QApplication::aboutQt); -} - -void MainWindow::createDockWindows() { - messages_dock = new QDockWidget(tr("MESSAGES"), this); - messages_dock->setObjectName("MessagesPanel"); - messages_dock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::TopDockWidgetArea | Qt::BottomDockWidgetArea); - messages_dock->setFeatures(QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetClosable); - addDockWidget(Qt::LeftDockWidgetArea, messages_dock); - - video_dock = new QDockWidget("", this); - video_dock->setObjectName(tr("VideoPanel")); - video_dock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea); - video_dock->setFeatures(QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetClosable); - addDockWidget(Qt::RightDockWidgetArea, video_dock); -} - -void MainWindow::createDockWidgets() { - messages_widget = new MessagesWidget(this); - messages_dock->setWidget(messages_widget); - QObject::connect(messages_widget, &MessagesWidget::titleChanged, messages_dock, &QDockWidget::setWindowTitle); - QObject::connect(messages_widget, &MessagesWidget::msgSelectionChanged, center_widget, &CenterWidget::setMessage); - - // right panel - charts_widget = new ChartsWidget(this); - QWidget *charts_container = new QWidget(this); - charts_layout = new QVBoxLayout(charts_container); - charts_layout->setContentsMargins(0, 0, 0, 0); - charts_layout->addWidget(charts_widget); - - // splitter between video and charts - video_splitter = new QSplitter(Qt::Vertical, this); - video_widget = new VideoWidget(this); - video_splitter->addWidget(video_widget); - - video_splitter->addWidget(charts_container); - video_splitter->setStretchFactor(1, 1); - video_splitter->restoreState(settings.video_splitter_state); - video_splitter->handle(1)->setEnabled(!can->liveStreaming()); - video_dock->setWidget(video_splitter); - QObject::connect(charts_widget, &ChartsWidget::toggleChartsDocking, this, &MainWindow::toggleChartsDocking); - QObject::connect(charts_widget, &ChartsWidget::showTip, video_widget, &VideoWidget::showThumbnail); -} - -void MainWindow::createStatusBar() { - progress_bar = new QProgressBar(); - progress_bar->setRange(0, 100); - progress_bar->setTextVisible(true); - progress_bar->setFixedSize({300, 16}); - progress_bar->setVisible(false); - statusBar()->addWidget(new QLabel(tr("For Help, Press F1"))); - statusBar()->addPermanentWidget(progress_bar); - statusBar()->addPermanentWidget(status_label = new QLabel(this)); - updateStatus(); -} - -void MainWindow::createShortcuts() { - auto shortcut = new QShortcut(QKeySequence(Qt::Key_Space), this, nullptr, nullptr, Qt::ApplicationShortcut); - QObject::connect(shortcut, &QShortcut::activated, this, []() { - if (can) can->pause(!can->isPaused()); - }); - // TODO: add more shortcuts here. -} - -void MainWindow::undoStackCleanChanged(bool clean) { - setWindowModified(!clean); -} - -void MainWindow::DBCFileChanged() { - UndoStack::instance()->clear(); - - // Update file menu - int cnt = dbc()->nonEmptyDBCCount(); - save_dbc->setText(cnt > 1 ? tr("Save %1 DBCs...").arg(cnt) : tr("Save DBC...")); - save_dbc->setEnabled(cnt > 0); - save_dbc_as->setEnabled(cnt == 1); - // TODO: Support clipboard for multiple files - copy_dbc_to_clipboard->setEnabled(cnt == 1); - manage_dbcs_menu->setEnabled(dynamic_cast(can) == nullptr); - - QStringList title; - for (auto f : dbc()->allDBCFiles()) { - title.push_back(tr("(%1) %2").arg(toString(dbc()->sources(f)), f->name())); - } - setWindowFilePath(title.join(" | ")); -} - -void MainWindow::selectAndOpenStream() { - StreamSelector dlg(this); - if (dlg.exec()) { - openStream(dlg.stream(), dlg.dbcFile()); - } else if (!can) { - openStream(new DummyStream(this)); - } -} - -void MainWindow::closeStream() { - openStream(new DummyStream(this)); - if (dbc()->nonEmptyDBCCount() > 0) { - emit dbc()->DBCFileChanged(); - } - statusBar()->showMessage(tr("stream closed")); -} - -void MainWindow::exportToCSV() { - QString dir = QString("%1/%2.csv").arg(settings.last_dir).arg(can->routeName()); - QString fn = QFileDialog::getSaveFileName(this, "Export stream to CSV file", dir, tr("csv (*.csv)")); - if (!fn.isEmpty()) { - utils::exportToCSV(fn); - } -} - -void MainWindow::newFile(SourceSet s) { - closeFile(s); - dbc()->open(s, "", ""); -} - -void MainWindow::openFile(SourceSet s) { - remindSaveChanges(); - QString fn = QFileDialog::getOpenFileName(this, tr("Open File"), settings.last_dir, "DBC (*.dbc)"); - if (!fn.isEmpty()) { - loadFile(fn, s); - } -} - -void MainWindow::loadFile(const QString &fn, SourceSet s) { - if (!fn.isEmpty()) { - closeFile(s); - - QString error; - if (dbc()->open(s, fn, &error)) { - updateRecentFiles(fn); - statusBar()->showMessage(tr("DBC File %1 loaded").arg(fn), 2000); - } else { - QMessageBox msg_box(QMessageBox::Warning, tr("Failed to load DBC file"), tr("Failed to parse DBC file %1").arg(fn)); - msg_box.setDetailedText(error); - msg_box.exec(); - } - } -} - -void MainWindow::loadDBCFromOpendbc(const QString &name) { - loadFile(QString("%1/%2").arg(OPENDBC_FILE_PATH, name)); -} - -void MainWindow::loadFromClipboard(SourceSet s, bool close_all) { - closeFile(s); - - QString dbc_str = QGuiApplication::clipboard()->text(); - QString error; - bool ret = dbc()->open(s, "", dbc_str, &error); - if (ret && dbc()->nonEmptyDBCCount() > 0) { - QMessageBox::information(this, tr("Load From Clipboard"), tr("DBC Successfully Loaded!")); - } else { - QMessageBox msg_box(QMessageBox::Warning, tr("Failed to load DBC from clipboard"), tr("Make sure that you paste the text with correct format.")); - msg_box.setDetailedText(error); - msg_box.exec(); - } -} - -void MainWindow::openStream(AbstractStream *stream, const QString &dbc_file) { - center_widget->clear(); - delete messages_widget; - delete video_splitter; - - delete can; - can = stream; - can->setParent(this); // take ownership - can->start(); - - loadFile(dbc_file); - statusBar()->showMessage(tr("Stream [%1] started").arg(can->routeName()), 2000); - - bool has_stream = dynamic_cast(can) == nullptr; - close_stream_act->setEnabled(has_stream); - export_to_csv_act->setEnabled(has_stream); - tools_menu->setEnabled(has_stream); - createDockWidgets(); - - video_dock->setWindowTitle(can->routeName()); - if (can->liveStreaming() || video_splitter->sizes()[0] == 0) { - // display video at minimum size. - video_splitter->setSizes({1, 1}); - } - // Don't overwrite already loaded DBC - if (!dbc()->nonEmptyDBCCount()) { - newFile(); - } - - QObject::connect(can, &AbstractStream::eventsMerged, this, &MainWindow::eventsMerged); - - if (has_stream) { - auto wait_dlg = new QProgressDialog( - can->liveStreaming() ? tr("Waiting for the live stream to start...") : tr("Loading segment data..."), - tr("&Abort"), 0, 100, this); - wait_dlg->setWindowModality(Qt::WindowModal); - wait_dlg->setFixedSize(400, wait_dlg->sizeHint().height()); - QObject::connect(wait_dlg, &QProgressDialog::canceled, this, &MainWindow::close); - QObject::connect(can, &AbstractStream::eventsMerged, wait_dlg, &QProgressDialog::deleteLater); - QObject::connect(this, &MainWindow::updateProgressBar, wait_dlg, [=](uint64_t cur, uint64_t total, bool success) { - wait_dlg->setValue((int)((cur / (double)total) * 100)); - }); - } -} - -void MainWindow::eventsMerged() { - if (!can->liveStreaming() && std::exchange(car_fingerprint, can->carFingerprint()) != car_fingerprint) { - video_dock->setWindowTitle(tr("ROUTE: %1 FINGERPRINT: %2") - .arg(can->routeName()) - .arg(car_fingerprint.isEmpty() ? tr("Unknown Car") : car_fingerprint)); - // Don't overwrite already loaded DBC - if (!dbc()->nonEmptyDBCCount() && fingerprint_to_dbc.object().contains(car_fingerprint)) { - QTimer::singleShot(0, this, [this]() { loadDBCFromOpendbc(fingerprint_to_dbc[car_fingerprint].toString() + ".dbc"); }); - } - } -} - -void MainWindow::save() { - // Save all open DBC files - for (auto dbc_file : dbc()->allDBCFiles()) { - if (dbc_file->isEmpty()) continue; - saveFile(dbc_file); - } -} - -void MainWindow::saveAs() { - // Save as all open DBC files. Should not be called with more than 1 file open - for (auto dbc_file : dbc()->allDBCFiles()) { - if (dbc_file->isEmpty()) continue; - saveFileAs(dbc_file); - } -} - -void MainWindow::closeFile(SourceSet s) { - remindSaveChanges(); - if (s == SOURCE_ALL) { - dbc()->closeAll(); - } else { - dbc()->close(s); - } -} - -void MainWindow::closeFile(DBCFile *dbc_file) { - assert(dbc_file != nullptr); - remindSaveChanges(); - dbc()->close(dbc_file); - // Ensure we always have at least one file open - if (dbc()->dbcCount() == 0) { - newFile(); - } -} - -void MainWindow::saveFile(DBCFile *dbc_file) { - assert(dbc_file != nullptr); - if (!dbc_file->filename.isEmpty()) { - dbc_file->save(); - UndoStack::instance()->setClean(); - statusBar()->showMessage(tr("File saved"), 2000); - } else if (!dbc_file->isEmpty()) { - saveFileAs(dbc_file); - } -} - -void MainWindow::saveFileAs(DBCFile *dbc_file) { - QString title = tr("Save File (bus: %1)").arg(toString(dbc()->sources(dbc_file))); - QString fn = QFileDialog::getSaveFileName(this, title, QDir::cleanPath(settings.last_dir + "/untitled.dbc"), tr("DBC (*.dbc)")); - if (!fn.isEmpty()) { - dbc_file->saveAs(fn); - UndoStack::instance()->setClean(); - statusBar()->showMessage(tr("File saved as %1").arg(fn), 2000); - updateRecentFiles(fn); - } -} - -void MainWindow::saveToClipboard() { - // Copy all open DBC files to clipboard. Should not be called with more than 1 file open - for (auto dbc_file : dbc()->allDBCFiles()) { - if (dbc_file->isEmpty()) continue; - saveFileToClipboard(dbc_file); - } -} - -void MainWindow::saveFileToClipboard(DBCFile *dbc_file) { - assert(dbc_file != nullptr); - QGuiApplication::clipboard()->setText(dbc_file->generateDBC()); - QMessageBox::information(this, tr("Copy To Clipboard"), tr("DBC Successfully copied!")); -} - -void MainWindow::updateLoadSaveMenus() { - manage_dbcs_menu->clear(); - - for (int source : can->sources) { - if (source >= 64) continue; // Sent and blocked buses are handled implicitly - - SourceSet ss = {source, uint8_t(source + 128), uint8_t(source + 192)}; - - QMenu *bus_menu = new QMenu(this); - bus_menu->addAction(tr("New DBC File..."), [=]() { newFile(ss); }); - bus_menu->addAction(tr("Open DBC File..."), [=]() { openFile(ss); }); - bus_menu->addAction(tr("Load DBC From Clipboard..."), [=]() { loadFromClipboard(ss, false); }); - - // Show sub-menu for each dbc for this source. - auto dbc_file = dbc()->findDBCFile(source); - if (dbc_file) { - bus_menu->addSeparator(); - bus_menu->addAction(dbc_file->name() + " (" + toString(dbc()->sources(dbc_file)) + ")")->setEnabled(false); - bus_menu->addAction(tr("Save..."), [=]() { saveFile(dbc_file); }); - bus_menu->addAction(tr("Save As..."), [=]() { saveFileAs(dbc_file); }); - bus_menu->addAction(tr("Copy to Clipboard..."), [=]() { saveFileToClipboard(dbc_file); }); - bus_menu->addAction(tr("Remove from this bus..."), [=]() { closeFile(ss); }); - bus_menu->addAction(tr("Remove from all buses..."), [=]() { closeFile(dbc_file); }); - } - bus_menu->setTitle(tr("Bus %1 (%2)").arg(source).arg(dbc_file ? dbc_file->name() : "No DBCs loaded")); - - manage_dbcs_menu->addMenu(bus_menu); - } -} - -void MainWindow::updateRecentFiles(const QString &fn) { - settings.recent_files.removeAll(fn); - settings.recent_files.prepend(fn); - while (settings.recent_files.size() > MAX_RECENT_FILES) { - settings.recent_files.removeLast(); - } - settings.last_dir = QFileInfo(fn).absolutePath(); -} - -void MainWindow::updateRecentFileMenu() { - open_recent_menu->clear(); - - int num_recent_files = std::min(settings.recent_files.size(), MAX_RECENT_FILES); - if (!num_recent_files) { - open_recent_menu->addAction(tr("No Recent Files"))->setEnabled(false); - return; - } - - for (int i = 0; i < num_recent_files; ++i) { - QString text = tr("&%1 %2").arg(i + 1).arg(QFileInfo(settings.recent_files[i]).fileName()); - open_recent_menu->addAction(text, this, [this, file = settings.recent_files[i]]() { loadFile(file); }); - } -} - -void MainWindow::remindSaveChanges() { - while (!UndoStack::instance()->isClean()) { - QString text = tr("You have unsaved changes. Press ok to save them, cancel to discard."); - int ret = QMessageBox::question(this, tr("Unsaved Changes"), text, QMessageBox::Ok | QMessageBox::Cancel); - if (ret != QMessageBox::Ok) break; - save(); - } - UndoStack::instance()->clear(); -} - -void MainWindow::updateDownloadProgress(uint64_t cur, uint64_t total, bool success) { - if (success && cur < total) { - progress_bar->setValue((cur / (double)total) * 100); - progress_bar->setFormat(tr("Downloading %p% (%1)").arg(formattedDataSize(total).c_str())); - progress_bar->show(); - } else { - progress_bar->hide(); - } -} - -void MainWindow::updateStatus() { - status_label->setText(tr("Cached Minutes:%1 FPS:%2").arg(settings.max_cached_minutes).arg(settings.fps)); -} - -bool MainWindow::eventFilter(QObject *obj, QEvent *event) { - if (obj == floating_window && event->type() == QEvent::Close) { - toggleChartsDocking(); - return true; - } - return QMainWindow::eventFilter(obj, event); -} - -void MainWindow::toggleChartsDocking() { - if (floating_window) { - // Dock the charts widget back to the main window - floating_window->removeEventFilter(this); - charts_layout->insertWidget(0, charts_widget, 1); - floating_window->deleteLater(); - floating_window = nullptr; - charts_widget->setIsDocked(true); - } else { - // Float the charts widget in a separate window - floating_window = new QWidget(this, Qt::Window); - floating_window->setWindowTitle("Charts"); - floating_window->setLayout(new QVBoxLayout()); - floating_window->layout()->addWidget(charts_widget); - floating_window->installEventFilter(this); - floating_window->showMaximized(); - charts_widget->setIsDocked(false); - } -} - -void MainWindow::closeEvent(QCloseEvent *event) { - remindSaveChanges(); - - installDownloadProgressHandler(nullptr); - qInstallMessageHandler(nullptr); - - if (floating_window) - floating_window->deleteLater(); - - // save states - settings.geometry = saveGeometry(); - settings.window_state = saveState(); - if (can && !can->liveStreaming()) { - settings.video_splitter_state = video_splitter->saveState(); - } - if (messages_widget) { - settings.message_header_state = messages_widget->saveHeaderState(); - } - - QWidget::closeEvent(event); -} - -void MainWindow::setOption() { - SettingsDlg dlg(this); - dlg.exec(); -} - -void MainWindow::findSimilarBits() { - FindSimilarBitsDlg *dlg = new FindSimilarBitsDlg(this); - QObject::connect(dlg, &FindSimilarBitsDlg::openMessage, messages_widget, &MessagesWidget::selectMessage); - dlg->show(); -} - -void MainWindow::findSignal() { - FindSignalDlg *dlg = new FindSignalDlg(this); - QObject::connect(dlg, &FindSignalDlg::openMessage, messages_widget, &MessagesWidget::selectMessage); - dlg->show(); -} - -void MainWindow::onlineHelp() { - if (auto help = findChild()) { - help->close(); - } else { - help = new HelpOverlay(this); - help->setGeometry(rect()); - help->show(); - help->raise(); - } -} - -void MainWindow::toggleFullScreen() { - if (isFullScreen()) { - menuBar()->show(); - statusBar()->show(); - showNormal(); - showMaximized(); - } else { - menuBar()->hide(); - statusBar()->hide(); - showFullScreen(); - } -} - -// HelpOverlay -HelpOverlay::HelpOverlay(MainWindow *parent) : QWidget(parent) { - setAttribute(Qt::WA_NoSystemBackground, true); - setAttribute(Qt::WA_TranslucentBackground, true); - setAttribute(Qt::WA_DeleteOnClose); - parent->installEventFilter(this); -} - -void HelpOverlay::paintEvent(QPaintEvent *event) { - QPainter painter(this); - painter.fillRect(rect(), QColor(0, 0, 0, 50)); - auto parent = parentWidget(); - drawHelpForWidget(painter, parent->findChild()); - drawHelpForWidget(painter, parent->findChild()); - drawHelpForWidget(painter, parent->findChild()); - drawHelpForWidget(painter, parent->findChild()); - drawHelpForWidget(painter, parent->findChild()); -} - -void HelpOverlay::drawHelpForWidget(QPainter &painter, QWidget *w) { - if (w && w->isVisible() && !w->whatsThis().isEmpty()) { - QPoint pt = mapFromGlobal(w->mapToGlobal(w->rect().center())); - if (rect().contains(pt)) { - QTextDocument document; - document.setHtml(w->whatsThis()); - QSize doc_size = document.size().toSize(); - QPoint topleft = {pt.x() - doc_size.width() / 2, pt.y() - doc_size.height() / 2}; - painter.translate(topleft); - painter.fillRect(QRect{{0, 0}, doc_size}, palette().toolTipBase()); - document.drawContents(&painter); - painter.translate(-topleft); - } - } -} - -bool HelpOverlay::eventFilter(QObject *obj, QEvent *event) { - if (obj == parentWidget() && event->type() == QEvent::Resize) { - QResizeEvent *resize_event = (QResizeEvent *)(event); - setGeometry(QRect{QPoint(0, 0), resize_event->size()}); - } - return false; -} - -void HelpOverlay::mouseReleaseEvent(QMouseEvent *event) { - close(); -} diff --git a/tools/cabana/settings.cc b/tools/cabana/settings.cc deleted file mode 100644 index cccc9b6d9a..0000000000 --- a/tools/cabana/settings.cc +++ /dev/null @@ -1,137 +0,0 @@ -#include "tools/cabana/settings.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "tools/cabana/utils/util.h" - -const int MIN_CACHE_MINIUTES = 30; -const int MAX_CACHE_MINIUTES = 120; - -Settings settings; - -template -void settings_op(SettingOperation op) { - QSettings s("cabana"); - op(s, "absolute_time", settings.absolute_time); - op(s, "fps", settings.fps); - op(s, "max_cached_minutes", settings.max_cached_minutes); - op(s, "chart_height", settings.chart_height); - op(s, "chart_range", settings.chart_range); - op(s, "chart_column_count", settings.chart_column_count); - op(s, "last_dir", settings.last_dir); - op(s, "last_route_dir", settings.last_route_dir); - op(s, "window_state", settings.window_state); - op(s, "geometry", settings.geometry); - op(s, "video_splitter_state", settings.video_splitter_state); - op(s, "recent_files", settings.recent_files); - op(s, "message_header_state", settings.message_header_state); - op(s, "chart_series_type", settings.chart_series_type); - op(s, "theme", settings.theme); - op(s, "sparkline_range", settings.sparkline_range); - op(s, "multiple_lines_hex", settings.multiple_lines_hex); - op(s, "log_livestream", settings.log_livestream); - op(s, "log_path", settings.log_path); - op(s, "drag_direction", (int &)settings.drag_direction); - op(s, "suppress_defined_signals", settings.suppress_defined_signals); -} - -Settings::Settings() { - last_dir = last_route_dir = QDir::homePath(); - log_path = QStandardPaths::writableLocation(QStandardPaths::HomeLocation) + "/cabana_live_stream/"; - settings_op([](QSettings &s, const QString &key, auto &value) { - if (auto v = s.value(key); v.canConvert>()) - value = v.value>(); - }); -} - -Settings::~Settings() { - settings_op([](QSettings &s, const QString &key, auto &v) { s.setValue(key, v); }); -} - -// SettingsDlg - -SettingsDlg::SettingsDlg(QWidget *parent) : QDialog(parent) { - setWindowTitle(tr("Settings")); - QVBoxLayout *main_layout = new QVBoxLayout(this); - QGroupBox *groupbox = new QGroupBox("General"); - QFormLayout *form_layout = new QFormLayout(groupbox); - - form_layout->addRow(tr("Color Theme"), theme = new QComboBox(this)); - theme->setToolTip(tr("You may need to restart cabana after changes theme")); - theme->addItems({tr("Automatic"), tr("Light"), tr("Dark")}); - theme->setCurrentIndex(settings.theme); - - form_layout->addRow("FPS", fps = new QSpinBox(this)); - fps->setRange(10, 100); - fps->setSingleStep(10); - fps->setValue(settings.fps); - - form_layout->addRow(tr("Max Cached Minutes"), cached_minutes = new QSpinBox(this)); - cached_minutes->setRange(MIN_CACHE_MINIUTES, MAX_CACHE_MINIUTES); - cached_minutes->setSingleStep(1); - cached_minutes->setValue(settings.max_cached_minutes); - main_layout->addWidget(groupbox); - - groupbox = new QGroupBox("New Signal Settings"); - form_layout = new QFormLayout(groupbox); - form_layout->addRow(tr("Drag Direction"), drag_direction = new QComboBox(this)); - drag_direction->addItems({tr("MSB First"), tr("LSB First"), tr("Always Little Endian"), tr("Always Big Endian")}); - drag_direction->setCurrentIndex(settings.drag_direction); - main_layout->addWidget(groupbox); - - groupbox = new QGroupBox("Chart"); - form_layout = new QFormLayout(groupbox); - form_layout->addRow(tr("Chart Height"), chart_height = new QSpinBox(this)); - chart_height->setRange(100, 500); - chart_height->setSingleStep(10); - chart_height->setValue(settings.chart_height); - main_layout->addWidget(groupbox); - - log_livestream = new QGroupBox(tr("Enable live stream logging"), this); - log_livestream->setCheckable(true); - QHBoxLayout *path_layout = new QHBoxLayout(log_livestream); - path_layout->addWidget(log_path = new QLineEdit(settings.log_path, this)); - log_path->setReadOnly(true); - auto browse_btn = new QPushButton(tr("B&rowse...")); - path_layout->addWidget(browse_btn); - main_layout->addWidget(log_livestream); - - auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); - main_layout->addWidget(buttonBox); - setFixedSize(400, sizeHint().height()); - - QObject::connect(browse_btn, &QPushButton::clicked, [this]() { - QString fn = QFileDialog::getExistingDirectory( - this, tr("Log File Location"), - QStandardPaths::writableLocation(QStandardPaths::HomeLocation), - QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); - if (!fn.isEmpty()) { - log_path->setText(fn); - } - }); - QObject::connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); - QObject::connect(buttonBox, &QDialogButtonBox::accepted, this, &SettingsDlg::save); -} - -void SettingsDlg::save() { - if (std::exchange(settings.theme, theme->currentIndex()) != settings.theme) { - // set theme before emit changed - utils::setTheme(settings.theme); - } - settings.fps = fps->value(); - settings.max_cached_minutes = cached_minutes->value(); - settings.chart_height = chart_height->value(); - settings.log_livestream = log_livestream->isChecked(); - settings.log_path = log_path->text(); - settings.drag_direction = (Settings::DragDirection)drag_direction->currentIndex(); - emit settings.changed(); - QDialog::accept(); -} diff --git a/tools/cabana/settings.h b/tools/cabana/settings.h deleted file mode 100644 index e75c519ac7..0000000000 --- a/tools/cabana/settings.h +++ /dev/null @@ -1,67 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include - -#define LIGHT_THEME 1 -#define DARK_THEME 2 - -class Settings : public QObject { - Q_OBJECT - -public: - enum DragDirection { - MsbFirst, - LsbFirst, - AlwaysLE, - AlwaysBE, - }; - - Settings(); - ~Settings(); - - bool absolute_time = false; - int fps = 10; - int max_cached_minutes = 30; - int chart_height = 200; - int chart_column_count = 1; - int chart_range = 3 * 60; // 3 minutes - int chart_series_type = 0; - int theme = 0; - int sparkline_range = 15; // 15 seconds - bool multiple_lines_hex = false; - bool log_livestream = true; - bool suppress_defined_signals = false; - QString log_path; - QString last_dir; - QString last_route_dir; - QByteArray geometry; - QByteArray video_splitter_state; - QByteArray window_state; - QStringList recent_files; - QByteArray message_header_state; - DragDirection drag_direction = MsbFirst; - -signals: - void changed(); -}; - -class SettingsDlg : public QDialog { -public: - SettingsDlg(QWidget *parent); - void save(); - QSpinBox *fps; - QSpinBox *cached_minutes; - QSpinBox *chart_height; - QComboBox *chart_series_type; - QComboBox *theme; - QGroupBox *log_livestream; - QLineEdit *log_path; - QComboBox *drag_direction; -}; - -extern Settings settings; diff --git a/tools/cabana/streams/abstractstream.h b/tools/cabana/streams/abstractstream.h deleted file mode 100644 index f35b19d34f..0000000000 --- a/tools/cabana/streams/abstractstream.h +++ /dev/null @@ -1,157 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#include "cereal/messaging/messaging.h" -#include "tools/cabana/dbc/dbcmanager.h" -#include "tools/cabana/utils/util.h" -#include "tools/replay/util.h" - -struct CanData { - void compute(const MessageId &msg_id, const uint8_t *dat, const int size, double current_sec, - double playback_speed, const std::vector &mask, double in_freq = 0); - - double ts = 0.; - uint32_t count = 0; - double freq = 0; - std::vector dat; - std::vector colors; - - struct ByteLastChange { - double ts = 0; - int delta = 0; - int same_delta_counter = 0; - bool suppressed = false; - }; - std::vector last_changes; - std::vector> bit_flip_counts; - double last_freq_update_ts = 0; -}; - -struct CanEvent { - uint8_t src; - uint32_t address; - uint64_t mono_time; - uint8_t size; - uint8_t dat[]; -}; - -struct CompareCanEvent { - constexpr bool operator()(const CanEvent *const e, uint64_t ts) const { return e->mono_time < ts; } - constexpr bool operator()(uint64_t ts, const CanEvent *const e) const { return ts < e->mono_time; } -}; - -typedef std::unordered_map> MessageEventsMap; -using CanEventIter = std::vector::const_iterator; - -class AbstractStream : public QObject { - Q_OBJECT - -public: - AbstractStream(QObject *parent); - virtual ~AbstractStream() {} - virtual void start() = 0; - virtual bool liveStreaming() const { return true; } - virtual void seekTo(double ts) {} - virtual QString routeName() const = 0; - virtual QString carFingerprint() const { return ""; } - virtual QDateTime beginDateTime() const { return {}; } - virtual uint64_t beginMonoTime() const { return 0; } - virtual double minSeconds() const { return 0; } - virtual double maxSeconds() const { return 0; } - virtual void setSpeed(float speed) {} - virtual double getSpeed() { return 1; } - virtual bool isPaused() const { return false; } - virtual void pause(bool pause) {} - void setTimeRange(const std::optional> &range); - const std::optional> &timeRange() const { return time_range_; } - - inline double currentSec() const { return current_sec_; } - inline uint64_t toMonoTime(double sec) const { return beginMonoTime() + std::max(sec, 0.0) * 1e9; } - inline double toSeconds(uint64_t mono_time) const { return std::max(0.0, (mono_time - beginMonoTime()) / 1e9); } - - inline const std::unordered_map &lastMessages() const { return last_msgs; } - bool isMessageActive(const MessageId &id) const; - inline const MessageEventsMap &eventsMap() const { return events_; } - inline const std::vector &allEvents() const { return all_events_; } - const CanData &lastMessage(const MessageId &id) const; - const std::vector &events(const MessageId &id) const; - std::pair eventsInRange(const MessageId &id, std::optional> time_range) const; - - size_t suppressHighlighted(); - void clearSuppressed(); - void suppressDefinedSignals(bool suppress); - -signals: - void paused(); - void resume(); - void seeking(double sec); - void seekedTo(double sec); - void timeRangeChanged(const std::optional> &range); - void eventsMerged(const MessageEventsMap &events_map); - void msgsReceived(const std::set *new_msgs, bool has_new_ids); - void sourcesUpdated(const SourceSet &s); - void privateUpdateLastMsgsSignal(); - -public: - SourceSet sources; - -protected: - void mergeEvents(const std::vector &events); - const CanEvent *newEvent(uint64_t mono_time, const cereal::CanData::Reader &c); - void updateEvent(const MessageId &id, double sec, const uint8_t *data, uint8_t size); - void waitForSeekFinshed(); - std::vector all_events_; - double current_sec_ = 0; - std::optional> time_range_; - -private: - void updateLastMessages(); - void updateLastMsgsTo(double sec); - void updateMasks(); - - MessageEventsMap events_; - std::unordered_map last_msgs; - std::unique_ptr event_buffer_; - - // Members accessed in multiple threads. (mutex protected) - std::mutex mutex_; - std::condition_variable seek_finished_cv_; - bool seek_finished_ = false; - std::set new_msgs_; - std::unordered_map messages_; - std::unordered_map> masks_; -}; - -class AbstractOpenStreamWidget : public QWidget { - Q_OBJECT -public: - AbstractOpenStreamWidget(QWidget *parent = nullptr) : QWidget(parent) {} - virtual AbstractStream *open() = 0; - -signals: - void enableOpenButton(bool); -}; - -class DummyStream : public AbstractStream { - Q_OBJECT -public: - DummyStream(QObject *parent) : AbstractStream(parent) {} - QString routeName() const override { return tr("No Stream"); } - void start() override {} -}; - -// A global pointer referring to the unique AbstractStream object -extern AbstractStream *can; diff --git a/tools/cabana/streams/devicestream.cc b/tools/cabana/streams/devicestream.cc deleted file mode 100644 index 6de63dfbbc..0000000000 --- a/tools/cabana/streams/devicestream.cc +++ /dev/null @@ -1,65 +0,0 @@ -#include "tools/cabana/streams/devicestream.h" - -#include -#include - -#include -#include -#include -#include -#include -#include - -// DeviceStream - -DeviceStream::DeviceStream(QObject *parent, QString address) : zmq_address(address), LiveStream(parent) { -} - -void DeviceStream::streamThread() { - zmq_address.isEmpty() ? unsetenv("ZMQ") : setenv("ZMQ", "1", 1); - - std::unique_ptr context(Context::create()); - std::string address = zmq_address.isEmpty() ? "127.0.0.1" : zmq_address.toStdString(); - std::unique_ptr sock(SubSocket::create(context.get(), "can", address)); - assert(sock != NULL); - // run as fast as messages come in - while (!QThread::currentThread()->isInterruptionRequested()) { - std::unique_ptr msg(sock->receive(true)); - if (!msg) { - QThread::msleep(50); - continue; - } - handleEvent(kj::ArrayPtr((capnp::word*)msg->getData(), msg->getSize() / sizeof(capnp::word))); - } -} - -// OpenDeviceWidget - -OpenDeviceWidget::OpenDeviceWidget(QWidget *parent) : AbstractOpenStreamWidget(parent) { - QRadioButton *msgq = new QRadioButton(tr("MSGQ")); - QRadioButton *zmq = new QRadioButton(tr("ZMQ")); - ip_address = new QLineEdit(this); - ip_address->setPlaceholderText(tr("Enter device Ip Address")); - QString ip_range = "(?:[0-1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])"; - QString pattern("^" + ip_range + "\\." + ip_range + "\\." + ip_range + "\\." + ip_range + "$"); - QRegularExpression re(pattern); - ip_address->setValidator(new QRegularExpressionValidator(re, this)); - - group = new QButtonGroup(this); - group->addButton(msgq, 0); - group->addButton(zmq, 1); - - QFormLayout *form_layout = new QFormLayout(this); - form_layout->addRow(msgq); - form_layout->addRow(zmq, ip_address); - QObject::connect(group, qOverload(&QButtonGroup::buttonToggled), [=](QAbstractButton *button, bool checked) { - ip_address->setEnabled(button == zmq && checked); - }); - zmq->setChecked(true); -} - -AbstractStream *OpenDeviceWidget::open() { - QString ip = ip_address->text().isEmpty() ? "127.0.0.1" : ip_address->text(); - bool msgq = group->checkedId() == 0; - return new DeviceStream(qApp, msgq ? "" : ip); -} diff --git a/tools/cabana/streams/devicestream.h b/tools/cabana/streams/devicestream.h deleted file mode 100644 index 3bdf224998..0000000000 --- a/tools/cabana/streams/devicestream.h +++ /dev/null @@ -1,28 +0,0 @@ -#pragma once - -#include "tools/cabana/streams/livestream.h" - -class DeviceStream : public LiveStream { - Q_OBJECT -public: - DeviceStream(QObject *parent, QString address = {}); - inline QString routeName() const override { - return QString("Live Streaming From %1").arg(zmq_address.isEmpty() ? "127.0.0.1" : zmq_address); - } - -protected: - void streamThread() override; - const QString zmq_address; -}; - -class OpenDeviceWidget : public AbstractOpenStreamWidget { - Q_OBJECT - -public: - OpenDeviceWidget(QWidget *parent = nullptr); - AbstractStream *open() override; - -private: - QLineEdit *ip_address; - QButtonGroup *group; -}; diff --git a/tools/cabana/streams/livestream.cc b/tools/cabana/streams/livestream.cc deleted file mode 100644 index ac9a6fa105..0000000000 --- a/tools/cabana/streams/livestream.cc +++ /dev/null @@ -1,148 +0,0 @@ -#include "tools/cabana/streams/livestream.h" - -#include -#include -#include -#include - -#include "common/timing.h" -#include "common/util.h" - -struct LiveStream::Logger { - Logger() : start_ts(seconds_since_epoch()), segment_num(-1) {} - - void write(kj::ArrayPtr data) { - int n = (seconds_since_epoch() - start_ts) / 60.0; - if (std::exchange(segment_num, n) != segment_num) { - QString dir = QString("%1/%2--%3") - .arg(settings.log_path) - .arg(QDateTime::fromSecsSinceEpoch(start_ts).toString("yyyy-MM-dd--hh-mm-ss")) - .arg(n); - util::create_directories(dir.toStdString(), 0755); - fs.reset(new std::ofstream((dir + "/rlog").toStdString(), std::ios::binary | std::ios::out)); - } - - auto bytes = data.asBytes(); - fs->write((const char*)bytes.begin(), bytes.size()); - } - - std::unique_ptr fs; - int segment_num; - uint64_t start_ts; -}; - -LiveStream::LiveStream(QObject *parent) : AbstractStream(parent) { - if (settings.log_livestream) { - logger = std::make_unique(); - } - stream_thread = new QThread(this); - - QObject::connect(&settings, &Settings::changed, this, &LiveStream::startUpdateTimer); - QObject::connect(stream_thread, &QThread::started, [=]() { streamThread(); }); - QObject::connect(stream_thread, &QThread::finished, stream_thread, &QThread::deleteLater); -} - -LiveStream::~LiveStream() { - stop(); -} - -void LiveStream::startUpdateTimer() { - update_timer.stop(); - update_timer.start(1000.0 / settings.fps, this); - timer_id = update_timer.timerId(); -} - -void LiveStream::start() { - stream_thread->start(); - startUpdateTimer(); - begin_date_time = QDateTime::currentDateTime(); -} - -void LiveStream::stop() { - if (!stream_thread) return; - - update_timer.stop(); - stream_thread->requestInterruption(); - stream_thread->quit(); - stream_thread->wait(); - stream_thread = nullptr; -} - -// called in streamThread -void LiveStream::handleEvent(kj::ArrayPtr data) { - if (logger) { - logger->write(data); - } - - capnp::FlatArrayMessageReader reader(data); - auto event = reader.getRoot(); - if (event.which() == cereal::Event::Which::CAN) { - const uint64_t mono_time = event.getLogMonoTime(); - std::lock_guard lk(lock); - for (const auto &c : event.getCan()) { - received_events_.push_back(newEvent(mono_time, c)); - } - } -} - -void LiveStream::timerEvent(QTimerEvent *event) { - if (event->timerId() == timer_id) { - { - // merge events received from live stream thread. - std::lock_guard lk(lock); - mergeEvents(received_events_); - uint64_t last_received_ts = !received_events_.empty() ? received_events_.back()->mono_time : 0; - lastest_event_ts = std::max(lastest_event_ts, last_received_ts); - received_events_.clear(); - } - if (!all_events_.empty()) { - begin_event_ts = all_events_.front()->mono_time; - updateEvents(); - return; - } - } - QObject::timerEvent(event); -} - -void LiveStream::updateEvents() { - static double prev_speed = 1.0; - - if (first_update_ts == 0) { - first_update_ts = nanos_since_boot(); - first_event_ts = current_event_ts = all_events_.back()->mono_time; - } - - if (paused_ || prev_speed != speed_) { - prev_speed = speed_; - first_update_ts = nanos_since_boot(); - first_event_ts = current_event_ts; - return; - } - - uint64_t last_ts = post_last_event && speed_ == 1.0 - ? all_events_.back()->mono_time - : first_event_ts + (nanos_since_boot() - first_update_ts) * speed_; - auto first = std::upper_bound(all_events_.cbegin(), all_events_.cend(), current_event_ts, CompareCanEvent()); - auto last = std::upper_bound(first, all_events_.cend(), last_ts, CompareCanEvent()); - - for (auto it = first; it != last; ++it) { - const CanEvent *e = *it; - MessageId id = {.source = e->src, .address = e->address}; - updateEvent(id, (e->mono_time - begin_event_ts) / 1e9, e->dat, e->size); - current_event_ts = e->mono_time; - } - emit privateUpdateLastMsgsSignal(); -} - -void LiveStream::seekTo(double sec) { - sec = std::max(0.0, sec); - first_update_ts = nanos_since_boot(); - current_event_ts = first_event_ts = std::min(sec * 1e9 + begin_event_ts, lastest_event_ts); - post_last_event = (first_event_ts == lastest_event_ts); - emit seekedTo((current_event_ts - begin_event_ts) / 1e9); -} - -void LiveStream::pause(bool pause) { - paused_ = pause; - emit(pause ? paused() : resume()); -} diff --git a/tools/cabana/streams/livestream.h b/tools/cabana/streams/livestream.h deleted file mode 100644 index 24b9285092..0000000000 --- a/tools/cabana/streams/livestream.h +++ /dev/null @@ -1,56 +0,0 @@ -#pragma once - -#include -#include -#include - -#include - -#include "tools/cabana/streams/abstractstream.h" - -class LiveStream : public AbstractStream { - Q_OBJECT - -public: - LiveStream(QObject *parent); - virtual ~LiveStream(); - void start() override; - void stop(); - inline QDateTime beginDateTime() const { return begin_date_time; } - inline uint64_t beginMonoTime() const override { return begin_event_ts; } - double maxSeconds() const override { return std::max(1.0, (lastest_event_ts - begin_event_ts) / 1e9); } - void setSpeed(float speed) override { speed_ = speed; } - double getSpeed() override { return speed_; } - bool isPaused() const override { return paused_; } - void pause(bool pause) override; - void seekTo(double sec) override; - -protected: - virtual void streamThread() = 0; - void handleEvent(kj::ArrayPtr event); - -private: - void startUpdateTimer(); - void timerEvent(QTimerEvent *event) override; - void updateEvents(); - - std::mutex lock; - QThread *stream_thread; - std::vector received_events_; - - int timer_id; - QBasicTimer update_timer; - - QDateTime begin_date_time; - uint64_t begin_event_ts = 0; - uint64_t lastest_event_ts = 0; - uint64_t current_event_ts = 0; - uint64_t first_event_ts = 0; - uint64_t first_update_ts = 0; - bool post_last_event = true; - double speed_ = 1; - bool paused_ = false; - - struct Logger; - std::unique_ptr logger; -}; diff --git a/tools/cabana/streams/routes.cc b/tools/cabana/streams/routes.cc deleted file mode 100644 index 5915c98065..0000000000 --- a/tools/cabana/streams/routes.cc +++ /dev/null @@ -1,138 +0,0 @@ -#include "tools/cabana/streams/routes.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -class OneShotHttpRequest : public HttpRequest { -public: - OneShotHttpRequest(QObject *parent) : HttpRequest(parent, false) {} - void send(const QString &url) { - if (reply) { - reply->disconnect(); - reply->abort(); - reply->deleteLater(); - reply = nullptr; - } - sendRequest(url); - } -}; - -// The RouteListWidget class extends QListWidget to display a custom message when empty -class RouteListWidget : public QListWidget { -public: - RouteListWidget(QWidget *parent = nullptr) : QListWidget(parent) {} - void setEmptyText(const QString &text) { - empty_text_ = text; - viewport()->update(); - } - void paintEvent(QPaintEvent *event) override { - QListWidget::paintEvent(event); - if (count() == 0) { - QPainter painter(viewport()); - painter.drawText(viewport()->rect(), Qt::AlignCenter, empty_text_); - } - } - QString empty_text_ = tr("No items"); -}; - -RoutesDialog::RoutesDialog(QWidget *parent) : QDialog(parent), route_requester_(new OneShotHttpRequest(this)) { - setWindowTitle(tr("Remote routes")); - - QFormLayout *layout = new QFormLayout(this); - layout->addRow(tr("Device"), device_list_ = new QComboBox(this)); - layout->addRow(period_selector_ = new QComboBox(this)); - layout->addRow(route_list_ = new RouteListWidget(this)); - auto button_box = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); - layout->addRow(button_box); - - device_list_->addItem(tr("Loading...")); - // Populate period selector with predefined durations - period_selector_->addItem(tr("Last week"), 7); - period_selector_->addItem(tr("Last 2 weeks"), 14); - period_selector_->addItem(tr("Last month"), 30); - period_selector_->addItem(tr("Last 6 months"), 180); - period_selector_->addItem(tr("Preserved"), -1); - - // Connect signals and slots - QObject::connect(route_requester_, &HttpRequest::requestDone, this, &RoutesDialog::parseRouteList); - connect(device_list_, QOverload::of(&QComboBox::currentIndexChanged), this, &RoutesDialog::fetchRoutes); - connect(period_selector_, QOverload::of(&QComboBox::currentIndexChanged), this, &RoutesDialog::fetchRoutes); - connect(route_list_, &QListWidget::itemDoubleClicked, this, &QDialog::accept); - QObject::connect(button_box, &QDialogButtonBox::accepted, this, &QDialog::accept); - QObject::connect(button_box, &QDialogButtonBox::rejected, this, &QDialog::reject); - - // Send request to fetch devices - HttpRequest *http = new HttpRequest(this, false); - QObject::connect(http, &HttpRequest::requestDone, this, &RoutesDialog::parseDeviceList); - http->sendRequest(CommaApi::BASE_URL + "/v1/me/devices/"); -} - -void RoutesDialog::parseDeviceList(const QString &json, bool success, QNetworkReply::NetworkError err) { - if (success) { - device_list_->clear(); - auto devices = QJsonDocument::fromJson(json.toUtf8()).array(); - for (const QJsonValue &device : devices) { - QString dongle_id = device["dongle_id"].toString(); - device_list_->addItem(dongle_id, dongle_id); - } - } else { - bool unauthorized = (err == QNetworkReply::ContentAccessDenied || err == QNetworkReply::AuthenticationRequiredError); - QMessageBox::warning(this, tr("Error"), unauthorized ? tr("Unauthorized, Authenticate with tools/lib/auth.py") : tr("Network error")); - reject(); - } - sender()->deleteLater(); -} - -void RoutesDialog::fetchRoutes() { - if (device_list_->currentIndex() == -1 || device_list_->currentData().isNull()) - return; - - route_list_->clear(); - route_list_->setEmptyText(tr("Loading...")); - // Construct URL with selected device and date range - QString url = QString("%1/v1/devices/%2").arg(CommaApi::BASE_URL, device_list_->currentText()); - int period = period_selector_->currentData().toInt(); - if (period == -1) { - url += "/routes/preserved"; - } else { - QDateTime now = QDateTime::currentDateTime(); - url += QString("/routes_segments?start=%1&end=%2") - .arg(now.addDays(-period).toMSecsSinceEpoch()) - .arg(now.toMSecsSinceEpoch()); - } - route_requester_->send(url); -} - -void RoutesDialog::parseRouteList(const QString &json, bool success, QNetworkReply::NetworkError err) { - if (success) { - for (const QJsonValue &route : QJsonDocument::fromJson(json.toUtf8()).array()) { - QDateTime from, to; - if (period_selector_->currentData().toInt() == -1) { - from = QDateTime::fromString(route["start_time"].toString(), Qt::ISODateWithMs); - to = QDateTime::fromString(route["end_time"].toString(), Qt::ISODateWithMs); - } else { - from = QDateTime::fromMSecsSinceEpoch(route["start_time_utc_millis"].toDouble()); - to = QDateTime::fromMSecsSinceEpoch(route["end_time_utc_millis"].toDouble()); - } - auto item = new QListWidgetItem(QString("%1 %2min").arg(from.toString()).arg(from.secsTo(to) / 60)); - item->setData(Qt::UserRole, route["fullname"].toString()); - route_list_->addItem(item); - } - if (route_list_->count() > 0) route_list_->setCurrentRow(0); - } else { - QMessageBox::warning(this, tr("Error"), tr("Failed to fetch routes. Check your network connection.")); - reject(); - } - route_list_->setEmptyText(tr("No items")); -} - -QString RoutesDialog::route() { - auto current_item = route_list_->currentItem(); - return current_item ? current_item->data(Qt::UserRole).toString() : ""; -} diff --git a/tools/cabana/streams/routes.h b/tools/cabana/streams/routes.h deleted file mode 100644 index ee50712212..0000000000 --- a/tools/cabana/streams/routes.h +++ /dev/null @@ -1,26 +0,0 @@ -#pragma once - -#include -#include - -#include "selfdrive/ui/qt/api.h" - -class RouteListWidget; -class OneShotHttpRequest; - -class RoutesDialog : public QDialog { - Q_OBJECT -public: - RoutesDialog(QWidget *parent); - QString route(); - -protected: - void parseDeviceList(const QString &json, bool success, QNetworkReply::NetworkError err); - void parseRouteList(const QString &json, bool success, QNetworkReply::NetworkError err); - void fetchRoutes(); - - QComboBox *device_list_; - QComboBox *period_selector_; - RouteListWidget *route_list_; - OneShotHttpRequest *route_requester_; -}; diff --git a/tools/cabana/streams/socketcanstream.cc b/tools/cabana/streams/socketcanstream.cc deleted file mode 100644 index e4801df9c0..0000000000 --- a/tools/cabana/streams/socketcanstream.cc +++ /dev/null @@ -1,111 +0,0 @@ -#include "tools/cabana/streams/socketcanstream.h" - -#include -#include -#include -#include -#include -#include - -SocketCanStream::SocketCanStream(QObject *parent, SocketCanStreamConfig config_) : config(config_), LiveStream(parent) { - if (!available()) { - throw std::runtime_error("SocketCAN plugin not available"); - } - - qDebug() << "Connecting to SocketCAN device" << config.device; - if (!connect()) { - throw std::runtime_error("Failed to connect to SocketCAN device"); - } -} - -bool SocketCanStream::available() { - return QCanBus::instance()->plugins().contains("socketcan"); -} - -bool SocketCanStream::connect() { - // Connecting might generate some warnings about missing socketcan/libsocketcan libraries - // These are expected and can be ignored, we don't need the advanced features of libsocketcan - QString errorString; - device.reset(QCanBus::instance()->createDevice("socketcan", config.device, &errorString)); - device->setConfigurationParameter(QCanBusDevice::CanFdKey, true); - - if (!device) { - qDebug() << "Failed to create SocketCAN device" << errorString; - return false; - } - - if (!device->connectDevice()) { - qDebug() << "Failed to connect to device"; - return false; - } - - return true; -} - -void SocketCanStream::streamThread() { - while (!QThread::currentThread()->isInterruptionRequested()) { - QThread::msleep(1); - - auto frames = device->readAllFrames(); - if (frames.size() == 0) continue; - - MessageBuilder msg; - auto evt = msg.initEvent(); - auto canData = evt.initCan(frames.size()); - - for (uint i = 0; i < frames.size(); i++) { - if (!frames[i].isValid()) continue; - - canData[i].setAddress(frames[i].frameId()); - canData[i].setSrc(0); - - auto payload = frames[i].payload(); - canData[i].setDat(kj::arrayPtr((uint8_t*)payload.data(), payload.size())); - } - - handleEvent(capnp::messageToFlatArray(msg)); - } -} - -OpenSocketCanWidget::OpenSocketCanWidget(QWidget *parent) : AbstractOpenStreamWidget(parent) { - QVBoxLayout *main_layout = new QVBoxLayout(this); - main_layout->addStretch(1); - - QFormLayout *form_layout = new QFormLayout(); - - QHBoxLayout *device_layout = new QHBoxLayout(); - device_edit = new QComboBox(); - device_edit->setFixedWidth(300); - device_layout->addWidget(device_edit); - - QPushButton *refresh = new QPushButton(tr("Refresh")); - refresh->setFixedWidth(100); - device_layout->addWidget(refresh); - form_layout->addRow(tr("Device"), device_layout); - main_layout->addLayout(form_layout); - - main_layout->addStretch(1); - - QObject::connect(refresh, &QPushButton::clicked, this, &OpenSocketCanWidget::refreshDevices); - QObject::connect(device_edit, &QComboBox::currentTextChanged, this, [=]{ config.device = device_edit->currentText(); }); - - // Populate devices - refreshDevices(); -} - -void OpenSocketCanWidget::refreshDevices() { - device_edit->clear(); - for (auto device : QCanBus::instance()->availableDevices(QStringLiteral("socketcan"))) { - device_edit->addItem(device.name()); - } -} - - -AbstractStream *OpenSocketCanWidget::open() { - try { - return new SocketCanStream(qApp, config); - } catch (std::exception &e) { - QMessageBox::warning(nullptr, tr("Warning"), tr("Failed to connect to SocketCAN device: '%1'").arg(e.what())); - return nullptr; - } -} diff --git a/tools/cabana/streams/socketcanstream.h b/tools/cabana/streams/socketcanstream.h deleted file mode 100644 index 8083b687e9..0000000000 --- a/tools/cabana/streams/socketcanstream.h +++ /dev/null @@ -1,47 +0,0 @@ -#pragma once - -#include - -#include -#include -#include -#include - -#include "tools/cabana/streams/livestream.h" - -struct SocketCanStreamConfig { - QString device = ""; // TODO: support multiple devices/buses at once -}; - -class SocketCanStream : public LiveStream { - Q_OBJECT -public: - SocketCanStream(QObject *parent, SocketCanStreamConfig config_ = {}); - ~SocketCanStream() { stop(); } - static bool available(); - - inline QString routeName() const override { - return QString("Live Streaming From Socket CAN %1").arg(config.device); - } - -protected: - void streamThread() override; - bool connect(); - - SocketCanStreamConfig config = {}; - std::unique_ptr device; -}; - -class OpenSocketCanWidget : public AbstractOpenStreamWidget { - Q_OBJECT - -public: - OpenSocketCanWidget(QWidget *parent = nullptr); - AbstractStream *open() override; - -private: - void refreshDevices(); - - QComboBox *device_edit; - SocketCanStreamConfig config = {}; -}; diff --git a/tools/cabana/tests/test_cabana.cc b/tools/cabana/tests/test_cabana.cc deleted file mode 100644 index d9fcae6f21..0000000000 --- a/tools/cabana/tests/test_cabana.cc +++ /dev/null @@ -1,157 +0,0 @@ - -#undef INFO -#include - -#include "catch2/catch.hpp" -#include "tools/cabana/dbc/dbcmanager.h" - -const std::string TEST_RLOG_URL = "https://commadataci.blob.core.windows.net/openpilotci/0c94aa1e1296d7c6/2021-05-05--19-48-37/0/rlog.bz2"; - -TEST_CASE("DBCFile::generateDBC") { - QString fn = QString("%1/%2.dbc").arg(OPENDBC_FILE_PATH, "tesla_can"); - DBCFile dbc_origin(fn); - DBCFile dbc_from_generated("", dbc_origin.generateDBC()); - - REQUIRE(dbc_origin.getMessages().size() == dbc_from_generated.getMessages().size()); - auto &msgs = dbc_origin.getMessages(); - auto &new_msgs = dbc_from_generated.getMessages(); - for (auto &[id, m] : msgs) { - auto &new_m = new_msgs.at(id); - REQUIRE(m.name == new_m.name); - REQUIRE(m.size == new_m.size); - REQUIRE(m.getSignals().size() == new_m.getSignals().size()); - auto sigs = m.getSignals(); - auto new_sigs = new_m.getSignals(); - for (int i = 0; i < sigs.size(); ++i) { - REQUIRE(*sigs[i] == *new_sigs[i]); - } - } -} - -TEST_CASE("DBCFile::generateDBC - comment order") { - // Ensure that message comments are followed by signal comments and in the correct order - auto content = R"(BO_ 160 message_1: 8 EON - SG_ signal_1 : 0|12@1+ (1,0) [0|4095] "unit" XXX - -BO_ 162 message_2: 8 EON - SG_ signal_2 : 0|12@1+ (1,0) [0|4095] "unit" XXX - -CM_ BO_ 160 "message comment"; -CM_ SG_ 160 signal_1 "signal comment"; -CM_ BO_ 162 "message comment"; -CM_ SG_ 162 signal_2 "signal comment"; -)"; - DBCFile dbc("", content); - REQUIRE(dbc.generateDBC() == content); -} - -TEST_CASE("DBCFile::generateDBC -- preserve original header") { - QString content = R"(VERSION "1.0" - -NS_ : - CM_ - -BS_: - -BU_: EON - -BO_ 160 message_1: 8 EON - SG_ signal_1 : 0|12@1+ (1,0) [0|4095] "unit" XXX - -CM_ BO_ 160 "message comment"; -CM_ SG_ 160 signal_1 "signal comment"; -)"; - DBCFile dbc("", content); - REQUIRE(dbc.generateDBC() == content); -} - -TEST_CASE("DBCFile::generateDBC - escaped quotes") { - QString content = R"(BO_ 160 message_1: 8 EON - SG_ signal_1 : 0|12@1+ (1,0) [0|4095] "unit" XXX - -CM_ BO_ 160 "message comment with \"escaped quotes\""; -CM_ SG_ 160 signal_1 "signal comment with \"escaped quotes\""; -)"; - DBCFile dbc("", content); - REQUIRE(dbc.generateDBC() == content); -} - -TEST_CASE("parse_dbc") { - QString content = R"( -BO_ 160 message_1: 8 EON - SG_ signal_1 : 0|12@1+ (1,0) [0|4095] "unit" XXX - SG_ signal_2 : 12|1@1+ (1.0,0.0) [0.0|1] "" XXX - -BO_ 162 message_1: 8 XXX - SG_ signal_1 M : 0|12@1+ (1,0) [0|4095] "unit" XXX - SG_ signal_2 M4 : 12|1@1+ (1.0,0.0) [0.0|1] "" XXX - -VAL_ 160 signal_1 0 "disabled" 1.2 "initializing" 2 "fault"; - -CM_ BO_ 160 "message comment" ; -CM_ SG_ 160 signal_1 "signal comment"; -CM_ SG_ 160 signal_2 "multiple line comment -1 -2 -"; - -CM_ BO_ 162 "message comment with \"escaped quotes\""; -CM_ SG_ 162 signal_1 "signal comment with \"escaped quotes\""; -)"; - - DBCFile file("", content); - auto msg = file.msg(160); - REQUIRE(msg != nullptr); - REQUIRE(msg->name == "message_1"); - REQUIRE(msg->size == 8); - REQUIRE(msg->comment == "message comment"); - REQUIRE(msg->sigs.size() == 2); - REQUIRE(msg->transmitter == "EON"); - REQUIRE(file.msg("message_1") != nullptr); - - auto sig_1 = msg->sigs[0]; - REQUIRE(sig_1->name == "signal_1"); - REQUIRE(sig_1->start_bit == 0); - REQUIRE(sig_1->size == 12); - REQUIRE(sig_1->min == 0); - REQUIRE(sig_1->max == 4095); - REQUIRE(sig_1->unit == "unit"); - REQUIRE(sig_1->comment == "signal comment"); - REQUIRE(sig_1->receiver_name == "XXX"); - REQUIRE(sig_1->val_desc.size() == 3); - REQUIRE(sig_1->val_desc[0] == std::pair{0, "disabled"}); - REQUIRE(sig_1->val_desc[1] == std::pair{1.2, "initializing"}); - REQUIRE(sig_1->val_desc[2] == std::pair{2, "fault"}); - - auto &sig_2 = msg->sigs[1]; - REQUIRE(sig_2->comment == "multiple line comment \n1\n2"); - - // multiplexed signals - msg = file.msg(162); - REQUIRE(msg != nullptr); - REQUIRE(msg->sigs.size() == 2); - REQUIRE(msg->sigs[0]->type == cabana::Signal::Type::Multiplexor); - REQUIRE(msg->sigs[1]->type == cabana::Signal::Type::Multiplexed); - REQUIRE(msg->sigs[1]->multiplex_value == 4); - REQUIRE(msg->sigs[1]->start_bit == 12); - REQUIRE(msg->sigs[1]->size == 1); - REQUIRE(msg->sigs[1]->receiver_name == "XXX"); - - // escaped quotes - REQUIRE(msg->comment == "message comment with \"escaped quotes\""); - REQUIRE(msg->sigs[0]->comment == "signal comment with \"escaped quotes\""); -} - -TEST_CASE("parse_opendbc") { - QDir dir(OPENDBC_FILE_PATH); - QStringList errors; - for (auto fn : dir.entryList({"*.dbc"}, QDir::Files, QDir::Name)) { - try { - auto dbc = DBCFile(dir.filePath(fn)); - } catch (std::exception &e) { - errors.push_back(e.what()); - } - } - INFO(errors.join("\n").toStdString()); - REQUIRE(errors.empty()); -} diff --git a/tools/cabana/tests/test_runner.cc b/tools/cabana/tests/test_runner.cc deleted file mode 100644 index b20ac86c64..0000000000 --- a/tools/cabana/tests/test_runner.cc +++ /dev/null @@ -1,10 +0,0 @@ -#define CATCH_CONFIG_RUNNER -#include "catch2/catch.hpp" -#include - -int main(int argc, char **argv) { - // unit tests for Qt - QCoreApplication app(argc, argv); - const int res = Catch::Session().run(argc, argv); - return (res < 0xff ? res : 0xff); -} diff --git a/tools/cabana/utils/export.cc b/tools/cabana/utils/export.cc deleted file mode 100644 index 79ca97ba8f..0000000000 --- a/tools/cabana/utils/export.cc +++ /dev/null @@ -1,45 +0,0 @@ -#include "tools/cabana/utils/export.h" - -#include -#include - -#include "tools/cabana/streams/abstractstream.h" - -namespace utils { - -void exportToCSV(const QString &file_name, std::optional msg_id) { - QFile file(file_name); - if (file.open(QIODevice::ReadWrite | QIODevice::Truncate)) { - QTextStream stream(&file); - stream << "time,addr,bus,data\n"; - for (auto e : msg_id ? can->events(*msg_id) : can->allEvents()) { - stream << QString::number(can->toSeconds(e->mono_time), 'f', 3) << "," - << "0x" << QString::number(e->address, 16) << "," << e->src << "," - << "0x" << QByteArray::fromRawData((const char *)e->dat, e->size).toHex().toUpper() << "\n"; - } - } -} - -void exportSignalsToCSV(const QString &file_name, const MessageId &msg_id) { - QFile file(file_name); - if (auto msg = dbc()->msg(msg_id); msg && msg->sigs.size() && file.open(QIODevice::ReadWrite | QIODevice::Truncate)) { - QTextStream stream(&file); - stream << "time,addr,bus"; - for (auto s : msg->sigs) - stream << "," << s->name; - stream << "\n"; - - for (auto e : can->events(msg_id)) { - stream << QString::number(can->toSeconds(e->mono_time), 'f', 3) << "," - << "0x" << QString::number(e->address, 16) << "," << e->src; - for (auto s : msg->sigs) { - double value = 0; - s->getValue(e->dat, e->size, &value); - stream << "," << QString::number(value, 'f', s->precision); - } - stream << "\n"; - } - } -} - -} // namespace utils diff --git a/tools/cabana/utils/export.h b/tools/cabana/utils/export.h deleted file mode 100644 index 270906b163..0000000000 --- a/tools/cabana/utils/export.h +++ /dev/null @@ -1,10 +0,0 @@ -#pragma once - -#include - -#include "tools/cabana/dbc/dbcmanager.h" - -namespace utils { -void exportToCSV(const QString &file_name, std::optional msg_id = std::nullopt); -void exportSignalsToCSV(const QString &file_name, const MessageId &msg_id); -} // namespace utils diff --git a/tools/cabana/utils/util.cc b/tools/cabana/utils/util.cc deleted file mode 100644 index 4556f90850..0000000000 --- a/tools/cabana/utils/util.cc +++ /dev/null @@ -1,271 +0,0 @@ -#include "tools/cabana/utils/util.h" - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -#include "selfdrive/ui/qt/util.h" - -// SegmentTree - -void SegmentTree::build(const std::vector &arr) { - size = arr.size(); - tree.resize(4 * size); // size of the tree is 4 times the size of the array - if (size > 0) { - build_tree(arr, 1, 0, size - 1); - } -} - -void SegmentTree::build_tree(const std::vector &arr, int n, int left, int right) { - if (left == right) { - const double y = arr[left].y(); - tree[n] = {y, y}; - } else { - const int mid = (left + right) >> 1; - build_tree(arr, 2 * n, left, mid); - build_tree(arr, 2 * n + 1, mid + 1, right); - tree[n] = {std::min(tree[2 * n].first, tree[2 * n + 1].first), std::max(tree[2 * n].second, tree[2 * n + 1].second)}; - } -} - -std::pair SegmentTree::get_minmax(int n, int left, int right, int range_left, int range_right) const { - if (range_left > right || range_right < left) - return {std::numeric_limits::max(), std::numeric_limits::lowest()}; - if (range_left <= left && range_right >= right) - return tree[n]; - int mid = (left + right) >> 1; - auto l = get_minmax(2 * n, left, mid, range_left, range_right); - auto r = get_minmax(2 * n + 1, mid + 1, right, range_left, range_right); - return {std::min(l.first, r.first), std::max(l.second, r.second)}; -} - -// MessageBytesDelegate - -MessageBytesDelegate::MessageBytesDelegate(QObject *parent, bool multiple_lines) - : font_metrics(QApplication::font()), multiple_lines(multiple_lines), QStyledItemDelegate(parent) { - fixed_font = QFontDatabase::systemFont(QFontDatabase::FixedFont); - byte_size = QFontMetrics(fixed_font).size(Qt::TextSingleLine, "00 ") + QSize(0, 2); - for (int i = 0; i < 256; ++i) { - hex_text_table[i].setText(QStringLiteral("%1").arg(i, 2, 16, QLatin1Char('0')).toUpper()); - hex_text_table[i].prepare({}, fixed_font); - } - h_margin = QApplication::style()->pixelMetric(QStyle::PM_FocusFrameHMargin) + 1; - v_margin = QApplication::style()->pixelMetric(QStyle::PM_FocusFrameVMargin) + 1; -} - -QSize MessageBytesDelegate::sizeForBytes(int n) const { - int rows = multiple_lines ? std::max(1, n / 8) : 1; - return {(n / rows) * byte_size.width() + h_margin * 2, rows * byte_size.height() + v_margin * 2}; -} - -QSize MessageBytesDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { - auto data = index.data(BytesRole); - return sizeForBytes(data.isValid() ? static_cast *>(data.value())->size() : 0); -} - -void MessageBytesDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { - if (option.state & QStyle::State_Selected) { - painter->fillRect(option.rect, option.palette.brush(QPalette::Normal, QPalette::Highlight)); - } - - QRect item_rect = option.rect.adjusted(h_margin, v_margin, -h_margin, -v_margin); - QColor highlighted_color = option.palette.color(QPalette::HighlightedText); - auto text_color = index.data(Qt::ForegroundRole).value(); - bool inactive = text_color.isValid(); - if (!inactive) { - text_color = option.palette.color(QPalette::Text); - } - auto data = index.data(BytesRole); - if (!data.isValid()) { - painter->setFont(option.font); - painter->setPen(option.state & QStyle::State_Selected ? highlighted_color : text_color); - QString text = font_metrics.elidedText(index.data(Qt::DisplayRole).toString(), Qt::ElideRight, item_rect.width()); - painter->drawText(item_rect, Qt::AlignLeft | Qt::AlignVCenter, text); - return; - } - - // Paint hex column - const auto &bytes = *static_cast *>(data.value()); - const auto &colors = *static_cast *>(index.data(ColorsRole).value()); - - painter->setFont(fixed_font); - const QPen text_pen(option.state & QStyle::State_Selected ? highlighted_color : text_color); - const QPoint pt = item_rect.topLeft(); - for (int i = 0; i < bytes.size(); ++i) { - int row = !multiple_lines ? 0 : i / 8; - int column = !multiple_lines ? i : i % 8; - QRect r({pt.x() + column * byte_size.width(), pt.y() + row * byte_size.height()}, byte_size); - - if (!inactive && i < colors.size() && colors[i].alpha() > 0) { - if (option.state & QStyle::State_Selected) { - painter->setPen(option.palette.color(QPalette::Text)); - painter->fillRect(r, option.palette.color(QPalette::Window)); - } - painter->fillRect(r, colors[i]); - } else { - painter->setPen(text_pen); - } - utils::drawStaticText(painter, r, hex_text_table[bytes[i]]); - } -} - -// TabBar - -int TabBar::addTab(const QString &text) { - int index = QTabBar::addTab(text); - QToolButton *btn = new ToolButton("x", tr("Close Tab")); - int width = style()->pixelMetric(QStyle::PM_TabCloseIndicatorWidth, nullptr, btn); - int height = style()->pixelMetric(QStyle::PM_TabCloseIndicatorHeight, nullptr, btn); - btn->setFixedSize({width, height}); - setTabButton(index, QTabBar::RightSide, btn); - QObject::connect(btn, &QToolButton::clicked, this, &TabBar::closeTabClicked); - return index; -} - -void TabBar::closeTabClicked() { - QObject *object = sender(); - for (int i = 0; i < count(); ++i) { - if (tabButton(i, QTabBar::RightSide) == object) { - emit tabCloseRequested(i); - break; - } - } -} - -// UnixSignalHandler - -UnixSignalHandler::UnixSignalHandler(QObject *parent) : QObject(nullptr) { - if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sig_fd)) { - qFatal("Couldn't create TERM socketpair"); - } - - sn = new QSocketNotifier(sig_fd[1], QSocketNotifier::Read, this); - connect(sn, &QSocketNotifier::activated, this, &UnixSignalHandler::handleSigTerm); - std::signal(SIGINT, signalHandler); - std::signal(SIGTERM, UnixSignalHandler::signalHandler); -} - -UnixSignalHandler::~UnixSignalHandler() { - ::close(sig_fd[0]); - ::close(sig_fd[1]); -} - -void UnixSignalHandler::signalHandler(int s) { - ::write(sig_fd[0], &s, sizeof(s)); -} - -void UnixSignalHandler::handleSigTerm() { - sn->setEnabled(false); - int tmp; - ::read(sig_fd[1], &tmp, sizeof(tmp)); - - printf("\nexiting...\n"); - qApp->closeAllWindows(); - qApp->exit(); -} - -// NameValidator - -NameValidator::NameValidator(QObject *parent) : QRegExpValidator(QRegExp("^(\\w+)"), parent) {} - -QValidator::State NameValidator::validate(QString &input, int &pos) const { - input.replace(' ', '_'); - return QRegExpValidator::validate(input, pos); -} - -DoubleValidator::DoubleValidator(QObject *parent) : QDoubleValidator(parent) { - // Match locale of QString::toDouble() instead of system - QLocale locale(QLocale::C); - locale.setNumberOptions(QLocale::RejectGroupSeparator); - setLocale(locale); -} - -namespace utils { -QPixmap icon(const QString &id) { - bool dark_theme = settings.theme == DARK_THEME; - QPixmap pm; - QString key = "bootstrap_" % id % (dark_theme ? "1" : "0"); - if (!QPixmapCache::find(key, &pm)) { - pm = bootstrapPixmap(id); - if (dark_theme) { - QPainter p(&pm); - p.setCompositionMode(QPainter::CompositionMode_SourceIn); - p.fillRect(pm.rect(), QColor("#bbbbbb")); - } - QPixmapCache::insert(key, pm); - } - return pm; -} - -void setTheme(int theme) { - auto style = QApplication::style(); - if (!style) return; - - static int prev_theme = 0; - if (theme != prev_theme) { - prev_theme = theme; - QPalette new_palette; - if (theme == DARK_THEME) { - // "Darcula" like dark theme - new_palette.setColor(QPalette::Window, QColor("#353535")); - new_palette.setColor(QPalette::WindowText, QColor("#bbbbbb")); - new_palette.setColor(QPalette::Base, QColor("#3c3f41")); - new_palette.setColor(QPalette::AlternateBase, QColor("#3c3f41")); - new_palette.setColor(QPalette::ToolTipBase, QColor("#3c3f41")); - new_palette.setColor(QPalette::ToolTipText, QColor("#bbb")); - new_palette.setColor(QPalette::Text, QColor("#bbbbbb")); - new_palette.setColor(QPalette::Button, QColor("#3c3f41")); - new_palette.setColor(QPalette::ButtonText, QColor("#bbbbbb")); - new_palette.setColor(QPalette::Highlight, QColor("#2f65ca")); - new_palette.setColor(QPalette::HighlightedText, QColor("#bbbbbb")); - new_palette.setColor(QPalette::BrightText, QColor("#f0f0f0")); - new_palette.setColor(QPalette::Disabled, QPalette::ButtonText, QColor("#777777")); - new_palette.setColor(QPalette::Disabled, QPalette::WindowText, QColor("#777777")); - new_palette.setColor(QPalette::Disabled, QPalette::Text, QColor("#777777")); - new_palette.setColor(QPalette::Light, QColor("#777777")); - new_palette.setColor(QPalette::Dark, QColor("#353535")); - } else { - new_palette = style->standardPalette(); - } - qApp->setPalette(new_palette); - style->polish(qApp); - for (auto w : QApplication::allWidgets()) { - w->setPalette(new_palette); - } - } -} - -QString formatSeconds(double sec, bool include_milliseconds, bool absolute_time) { - QString format = absolute_time ? "yyyy-MM-dd hh:mm:ss" - : (sec > 60 * 60 ? "hh:mm:ss" : "mm:ss"); - if (include_milliseconds) format += ".zzz"; - return QDateTime::fromMSecsSinceEpoch(sec * 1000).toString(format); -} - -} // namespace utils - -int num_decimals(double num) { - const QString string = QString::number(num); - auto dot_pos = string.indexOf('.'); - return dot_pos == -1 ? 0 : string.size() - dot_pos - 1; -} - -QString signalToolTip(const cabana::Signal *sig) { - return QObject::tr(R"( - %1
- Start Bit: %2 Size: %3
- MSB: %4 LSB: %5
- Little Endian: %6 Signed: %7
- )").arg(sig->name).arg(sig->start_bit).arg(sig->size).arg(sig->msb).arg(sig->lsb) - .arg(sig->is_little_endian ? "Y" : "N").arg(sig->is_signed ? "Y" : "N"); -} diff --git a/tools/cabana/utils/util.h b/tools/cabana/utils/util.h deleted file mode 100644 index 1aad3103db..0000000000 --- a/tools/cabana/utils/util.h +++ /dev/null @@ -1,166 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "tools/cabana/dbc/dbc.h" -#include "tools/cabana/settings.h" - -class LogSlider : public QSlider { - Q_OBJECT - -public: - LogSlider(double factor, Qt::Orientation orientation, QWidget *parent = nullptr) : factor(factor), QSlider(orientation, parent) {} - - void setRange(double min, double max) { - log_min = factor * std::log10(min); - log_max = factor * std::log10(max); - QSlider::setRange(min, max); - setValue(QSlider::value()); - } - int value() const { - double v = log_min + (log_max - log_min) * ((QSlider::value() - minimum()) / double(maximum() - minimum())); - return std::lround(std::pow(10, v / factor)); - } - void setValue(int v) { - double log_v = std::clamp(factor * std::log10(v), log_min, log_max); - v = minimum() + (maximum() - minimum()) * ((log_v - log_min) / (log_max - log_min)); - QSlider::setValue(v); - } - -private: - double factor, log_min = 0, log_max = 1; -}; - -enum { - ColorsRole = Qt::UserRole + 1, - BytesRole = Qt::UserRole + 2 -}; - -class SegmentTree { -public: - SegmentTree() = default; - void build(const std::vector &arr); - inline std::pair minmax(int left, int right) const { return get_minmax(1, 0, size - 1, left, right); } - -private: - std::pair get_minmax(int n, int left, int right, int range_left, int range_right) const; - void build_tree(const std::vector &arr, int n, int left, int right); - std::vector> tree; - int size = 0; -}; - -class MessageBytesDelegate : public QStyledItemDelegate { - Q_OBJECT -public: - MessageBytesDelegate(QObject *parent, bool multiple_lines = false); - void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override; - QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override; - bool multipleLines() const { return multiple_lines; } - void setMultipleLines(bool v) { multiple_lines = v; } - QSize sizeForBytes(int n) const; - -private: - std::array hex_text_table; - QFontMetrics font_metrics; - QFont fixed_font; - QSize byte_size = {}; - bool multiple_lines = false; - int h_margin, v_margin; -}; - -class NameValidator : public QRegExpValidator { - Q_OBJECT -public: - NameValidator(QObject *parent=nullptr); - QValidator::State validate(QString &input, int &pos) const override; -}; - -class DoubleValidator : public QDoubleValidator { - Q_OBJECT -public: - DoubleValidator(QObject *parent = nullptr); -}; - -namespace utils { -QPixmap icon(const QString &id); -void setTheme(int theme); -QString formatSeconds(double sec, bool include_milliseconds = false, bool absolute_time = false); -inline void drawStaticText(QPainter *p, const QRect &r, const QStaticText &text) { - auto size = (r.size() - text.size()) / 2; - p->drawStaticText(r.left() + size.width(), r.top() + size.height(), text); -} -inline QString toHex(const std::vector &dat, char separator = '\0') { - return QByteArray::fromRawData((const char *)dat.data(), dat.size()).toHex(separator).toUpper(); -} - -} - -class ToolButton : public QToolButton { - Q_OBJECT -public: - ToolButton(const QString &icon, const QString &tooltip = {}, QWidget *parent = nullptr) : QToolButton(parent) { - setIcon(icon); - setToolTip(tooltip); - setAutoRaise(true); - const int metric = QApplication::style()->pixelMetric(QStyle::PM_SmallIconSize); - setIconSize({metric, metric}); - theme = settings.theme; - connect(&settings, &Settings::changed, this, &ToolButton::updateIcon); - } - void setIcon(const QString &icon) { - icon_str = icon; - QToolButton::setIcon(utils::icon(icon_str)); - } - -private: - void updateIcon() { if (std::exchange(theme, settings.theme) != theme) setIcon(icon_str); } - QString icon_str; - int theme; -}; - -class TabBar : public QTabBar { - Q_OBJECT - -public: - TabBar(QWidget *parent) : QTabBar(parent) {} - int addTab(const QString &text); - -private: - void closeTabClicked(); -}; - -class UnixSignalHandler : public QObject { - Q_OBJECT - -public: - UnixSignalHandler(QObject *parent = nullptr); - ~UnixSignalHandler(); - static void signalHandler(int s); - -public slots: - void handleSigTerm(); - -private: - inline static int sig_fd[2] = {}; - QSocketNotifier *sn; -}; - -int num_decimals(double num); -QString signalToolTip(const cabana::Signal *sig); -inline QString toHexString(int value) { return QString("0x%1").arg(QString::number(value, 16).toUpper(), 2, '0'); } diff --git a/tools/camerastream/README.md b/tools/camerastream/README.md deleted file mode 100644 index 7dbafb4be5..0000000000 --- a/tools/camerastream/README.md +++ /dev/null @@ -1,66 +0,0 @@ -# Camera stream - -`compressed_vipc.py` connects to a remote device running openpilot, decodes the video streams, and republishes them over VisionIPC. - -## Usage - -### On the device -SSH into the device and run following in separate terminals: - -`cd /data/openpilot/cereal/messaging && ./bridge` - -`cd /data/openpilot/system/loggerd && ./encoderd` - -`cd /data/openpilot/system/camerad && ./camerad` - -Note that both the device and your PC must be on the same openpilot commit. - -Alternatively paste this as a single command: -``` -( - cd /data/openpilot/cereal/messaging/ - ./bridge & - - cd /data/openpilot/system/camerad/ - ./camerad & - - cd /data/openpilot/system/loggerd/ - ./encoderd & - - wait -) ; trap 'kill $(jobs -p)' SIGINT -``` -Ctrl+C will stop all three processes. - -### On the PC -Decode the stream with `compressed_vipc.py`: - -```cd ~/openpilot/tools/camerastream && ./compressed_vipc.py ``` - -To actually display the stream, run `watch3` in separate terminal: - -```cd ~/openpilot/selfdrive/ui/ && ./watch3``` - -## compressed_vipc.py usage -``` -$ python3 compressed_vipc.py -h -usage: compressed_vipc.py [-h] [--nvidia] [--cams CAMS] [--silent] addr - -Decode video streams and broadcast on VisionIPC - -positional arguments: - addr Address of comma three - -options: - -h, --help show this help message and exit - --nvidia Use nvidia instead of ffmpeg - --cams CAMS Cameras to decode - --silent Suppress debug output -``` - - -## Example: -``` -cd ~/openpilot/tools/camerastream && ./compressed_vipc.py comma-ffffffff --cams 0 -cd ~/openpilot/selfdrive/ui/ && ./watch3 -``` diff --git a/tools/camerastream/compressed_vipc.py b/tools/camerastream/compressed_vipc.py deleted file mode 100755 index 8c773f9dfe..0000000000 --- a/tools/camerastream/compressed_vipc.py +++ /dev/null @@ -1,162 +0,0 @@ -#!/usr/bin/env python3 -import av -import os -import sys -import argparse -import numpy as np -import multiprocessing -import time -import signal - - -import cereal.messaging as messaging -from msgq.visionipc import VisionIpcServer, VisionStreamType - -V4L2_BUF_FLAG_KEYFRAME = 8 - -# start encoderd -# also start cereal messaging bridge -# then run this "./compressed_vipc.py " - -ENCODE_SOCKETS = { - VisionStreamType.VISION_STREAM_ROAD: "roadEncodeData", - VisionStreamType.VISION_STREAM_DRIVER: "driverEncodeData", - VisionStreamType.VISION_STREAM_WIDE_ROAD: "wideRoadEncodeData", -} - -def decoder(addr, vipc_server, vst, nvidia, W, H, debug=False): - sock_name = ENCODE_SOCKETS[vst] - if debug: - print(f"start decoder for {sock_name}, {W}x{H}") - - if nvidia: - os.environ["NV_LOW_LATENCY"] = "3" # both bLowLatency and CUVID_PKT_ENDOFPICTURE - sys.path += os.environ["LD_LIBRARY_PATH"].split(":") - import PyNvCodec as nvc - - nvDec = nvc.PyNvDecoder(W, H, nvc.PixelFormat.NV12, nvc.CudaVideoCodec.HEVC, 0) - cc1 = nvc.ColorspaceConversionContext(nvc.ColorSpace.BT_709, nvc.ColorRange.JPEG) - conv_yuv = nvc.PySurfaceConverter(W, H, nvc.PixelFormat.NV12, nvc.PixelFormat.YUV420, 0) - nvDwn_yuv = nvc.PySurfaceDownloader(W, H, nvc.PixelFormat.YUV420, 0) - img_yuv = np.ndarray((H*W//2*3), dtype=np.uint8) - else: - codec = av.CodecContext.create("hevc", "r") - - os.environ["ZMQ"] = "1" - messaging.reset_context() - sock = messaging.sub_sock(sock_name, None, addr=addr, conflate=False) - cnt = 0 - last_idx = -1 - seen_iframe = False - - time_q = [] - while 1: - msgs = messaging.drain_sock(sock, wait_for_one=True) - for evt in msgs: - evta = getattr(evt, evt.which()) - if debug and evta.idx.encodeId != 0 and evta.idx.encodeId != (last_idx+1): - print("DROP PACKET!") - last_idx = evta.idx.encodeId - if not seen_iframe and not (evta.idx.flags & V4L2_BUF_FLAG_KEYFRAME): - if debug: - print("waiting for iframe") - continue - time_q.append(time.monotonic()) - network_latency = (int(time.time()*1e9) - evta.unixTimestampNanos)/1e6 - frame_latency = ((evta.idx.timestampEof/1e9) - (evta.idx.timestampSof/1e9))*1000 - process_latency = ((evt.logMonoTime/1e9) - (evta.idx.timestampEof/1e9))*1000 - - # put in header (first) - if not seen_iframe: - if nvidia: - nvDec.DecodeSurfaceFromPacket(np.frombuffer(evta.header, dtype=np.uint8)) - else: - codec.decode(av.packet.Packet(evta.header)) - seen_iframe = True - - if nvidia: - rawSurface = nvDec.DecodeSurfaceFromPacket(np.frombuffer(evta.data, dtype=np.uint8)) - if rawSurface.Empty(): - if debug: - print("DROP SURFACE") - continue - convSurface = conv_yuv.Execute(rawSurface, cc1) - nvDwn_yuv.DownloadSingleSurface(convSurface, img_yuv) - else: - frames = codec.decode(av.packet.Packet(evta.data)) - if len(frames) == 0: - if debug: - print("DROP SURFACE") - continue - assert len(frames) == 1 - img_yuv = frames[0].to_ndarray(format=av.video.format.VideoFormat('yuv420p')).flatten() - uv_offset = H*W - y = img_yuv[:uv_offset] - uv = img_yuv[uv_offset:].reshape(2, -1).ravel('F') - img_yuv = np.hstack((y, uv)) - - vipc_server.send(vst, img_yuv.data, cnt, int(time_q[0]*1e9), int(time.monotonic()*1e9)) - cnt += 1 - - pc_latency = (time.monotonic()-time_q[0])*1000 - time_q = time_q[1:] - if debug: - print(f"{len(msgs):2d} {evta.idx.encodeId:4d} {evt.logMonoTime/1e9:.3f} {evta.idx.timestampEof/1e6:.3f} \ - roll {frame_latency:6.2f} ms latency {process_latency:6.2f} ms + {network_latency:6.2f} ms + {pc_latency:6.2f} ms \ - = {process_latency+network_latency+pc_latency:6.2f} ms", len(evta.data), sock_name) - - -class CompressedVipc: - def __init__(self, addr, vision_streams, nvidia=False, debug=False): - print("getting frame sizes") - os.environ["ZMQ"] = "1" - messaging.reset_context() - sm = messaging.SubMaster([ENCODE_SOCKETS[s] for s in vision_streams], addr=addr) - while min(sm.recv_frame.values()) == 0: - sm.update(100) - os.environ.pop("ZMQ") - messaging.reset_context() - - self.vipc_server = VisionIpcServer("camerad") - for vst in vision_streams: - ed = sm[ENCODE_SOCKETS[vst]] - self.vipc_server.create_buffers(vst, 4, ed.width, ed.height) - self.vipc_server.start_listener() - - self.procs = [] - for vst in vision_streams: - ed = sm[ENCODE_SOCKETS[vst]] - p = multiprocessing.Process(target=decoder, args=(addr, self.vipc_server, vst, nvidia, ed.width, ed.height, debug)) - p.start() - self.procs.append(p) - - def join(self): - for p in self.procs: - p.join() - - def kill(self): - for p in self.procs: - p.terminate() - self.join() - -if __name__ == "__main__": - parser = argparse.ArgumentParser(description="Decode video streams and broadcast on VisionIPC") - parser.add_argument("addr", help="Address of comma three") - parser.add_argument("--nvidia", action="store_true", help="Use nvidia instead of ffmpeg") - parser.add_argument("--cams", default="0,1,2", help="Cameras to decode") - parser.add_argument("--silent", action="store_true", help="Suppress debug output") - args = parser.parse_args() - - vision_streams = [ - VisionStreamType.VISION_STREAM_ROAD, - VisionStreamType.VISION_STREAM_DRIVER, - VisionStreamType.VISION_STREAM_WIDE_ROAD, - ] - - vsts = [vision_streams[int(x)] for x in args.cams.split(",")] - cvipc = CompressedVipc(args.addr, vsts, args.nvidia, debug=(not args.silent)) - - # register exit handler - signal.signal(signal.SIGINT, lambda sig, frame: cvipc.kill()) - - cvipc.join() diff --git a/tools/car_porting/README.md b/tools/car_porting/README.md index 77492035ca..07ca2d0eba 100644 --- a/tools/car_porting/README.md +++ b/tools/car_porting/README.md @@ -6,13 +6,13 @@ Check out [this blog post](https://blog.comma.ai/how-to-write-a-car-port-for-ope Testing car ports in your car is very time-consuming. Check out these utilities to do basic checks on your work before running it in your car. -### [Cabana](/tools/cabana/README.md) +### [Cabana](/openpilot/tools/cabana/README.md) View your car's CAN signals through DBC files, which openpilot uses to parse and create messages that talk to the car. Example: ```bash -> tools/cabana/cabana '1bbe6bf2d62f58a8|2022-07-14--17-11-43' +> openpilot/tools/cabana/cabana '1bbe6bf2d62f58a8|2022-07-14--17-11-43' ``` ### [tools/car_porting/auto_fingerprint.py](/tools/car_porting/auto_fingerprint.py) @@ -25,17 +25,17 @@ Example: Attempting to add fw version for: OUTBACK ``` -### [selfdrive/car/tests/test_car_interfaces.py](/selfdrive/car/tests/test_car_interfaces.py) +### [openpilot/selfdrive/car/tests/test_car_interfaces.py](/openpilot/selfdrive/car/tests/test_car_interfaces.py) Finds common bugs for car interfaces, without even requiring a route. #### Example: Typo in signal name ```bash -> pytest selfdrive/car/tests/test_car_interfaces.py -k subaru # replace with the brand you are working on +> pytest openpilot/selfdrive/car/tests/test_car_interfaces.py -k subaru # replace with the brand you are working on ===================================================================== -FAILED selfdrive/car/tests/test_car_interfaces.py::TestCarInterfaces::test_car_interfaces_165_SUBARU_LEGACY_7TH_GEN - KeyError: 'CruiseControlOOPS' +FAILED openpilot/selfdrive/car/tests/test_car_interfaces.py::TestCarInterfaces::test_car_interfaces_165_SUBARU_LEGACY_7TH_GEN - KeyError: 'CruiseControlOOPS' ``` diff --git a/tools/car_porting/examples/find_segments_with_message.ipynb b/tools/car_porting/examples/find_segments_with_message.ipynb index 4e688cc65b..f91827f7e5 100644 --- a/tools/car_porting/examples/find_segments_with_message.ipynb +++ b/tools/car_porting/examples/find_segments_with_message.ipynb @@ -9,7 +9,6 @@ "source": [ "# Import all cars from opendbc\n", "\n", - "from opendbc.car import structs\n", "from opendbc.car.values import PLATFORMS as TEST_PLATFORMS\n", "\n", "# Example: add additional platforms/segments to test outside of commaCarSegments\n", @@ -76,7 +75,7 @@ " if platform not in database:\n", " print(f\"No segments available for {platform}\")\n", " continue\n", - " \n", + "\n", " all_segments = database[platform]\n", " NUM_SEGMENTS = min(len(all_segments), MAX_SEGS_PER_PLATFORM)\n", " TEST_SEGMENTS.extend(random.sample(all_segments, NUM_SEGMENTS))\n", @@ -147,8 +146,8 @@ } ], "source": [ - "from openpilot.tools.lib.logreader import LogReader\n", - "from tqdm.notebook import tqdm, tnrange\n", + "from openpilot.tools.lib.logreader import comma_car_segments_source\n", + "from tqdm.notebook import tnrange\n", "\n", "# Example search for CAN ignition messages\n", "# Be careful when filtering by bus, account for odd harness arrangements on Honda/HKG\n", @@ -169,7 +168,7 @@ "progress_bar = tnrange(len(TEST_SEGMENTS), desc=\"segments searched\")\n", "\n", "for segment in TEST_SEGMENTS:\n", - " lr = LogReader(segment)\n", + " lr = LogReader(segment, sources=[comma_car_segments_source])\n", " CP = lr.first(\"carParams\")\n", " if CP is None:\n", " progress_bar.update()\n", diff --git a/tools/car_porting/examples/ford_vin_fingerprint.ipynb b/tools/car_porting/examples/ford_vin_fingerprint.ipynb index 7b0dd656da..cb5fd8f820 100644 --- a/tools/car_porting/examples/ford_vin_fingerprint.ipynb +++ b/tools/car_porting/examples/ford_vin_fingerprint.ipynb @@ -20,7 +20,7 @@ "source": [ "\"\"\"In this example, we use the public comma car segments database to check if vin fingerprinting is feasible for ford.\"\"\"\n", "\n", - "from openpilot.tools.lib.logreader import LogReader\n", + "from openpilot.tools.lib.logreader import LogReader, comma_car_segments_source\n", "from openpilot.tools.lib.comma_car_segments import get_comma_car_segments_database\n", "from opendbc.car.ford.values import CAR\n", "\n", @@ -53,12 +53,12 @@ " if vin.startswith('1FT'):\n", " if vin_positions_567 in F150_CODES:\n", " if vin[7] in LIGHTNING_CODES:\n", - " return f\"FORD F-150 LIGHTNING 1ST GEN\"\n", + " return \"FORD F-150 LIGHTNING 1ST GEN\"\n", " else:\n", - " return f\"FORD F-150 14TH GEN\"\n", + " return \"FORD F-150 14TH GEN\"\n", " elif vin.startswith('3FM'):\n", " if vin_positions_567 in MACHE_CODES:\n", - " return f\"FORD MUSTANG MACH-E 1ST GEN\"\n", + " return \"FORD MUSTANG MACH-E 1ST GEN\"\n", " elif vin.startswith('5LM'):\n", " pass\n", "\n", @@ -100,7 +100,7 @@ " if platform not in database:\n", " print(f\"Skipping platform: {platform}, no data available\")\n", " continue\n", - " \n", + "\n", " all_segments = database[platform]\n", "\n", " NUM_SEGMENTS = min(len(all_segments), MAX_SEGS_PER_PLATFORM)\n", @@ -110,7 +110,7 @@ " segments = random.sample(all_segments, NUM_SEGMENTS)\n", "\n", " for segment in segments:\n", - " lr = LogReader(segment)\n", + " lr = LogReader(segment, sources=[comma_car_segments_source])\n", " CP = lr.first(\"carParams\")\n", " if \"FORD\" not in CP.carFingerprint:\n", " print(segment, CP.carFingerprint)\n", @@ -147,7 +147,8 @@ "source": [ "for vin, real_fingerprint in VINS_TO_CHECK:\n", " determined_fingerprint = ford_vin_fingerprint(vin)\n", - " print(f\"vin: {vin} real platform: {real_fingerprint: <30} determined platform: {determined_fingerprint: <30} correct: {real_fingerprint == determined_fingerprint}\")" + " print(f\"vin: {vin} real platform: {real_fingerprint: <30} \" +\n", + " f\"determined platform: {determined_fingerprint: <30} correct: {real_fingerprint == determined_fingerprint}\")" ] } ], diff --git a/tools/car_porting/examples/hkg_canfd_gear_message.ipynb b/tools/car_porting/examples/hkg_canfd_gear_message.ipynb index 5fdbdda684..ec902b7d10 100644 --- a/tools/car_porting/examples/hkg_canfd_gear_message.ipynb +++ b/tools/car_porting/examples/hkg_canfd_gear_message.ipynb @@ -21,9 +21,7 @@ } ], "source": [ - "from opendbc.car import structs\n", "from opendbc.car.hyundai.values import CAR, HyundaiFlags\n", - "from opendbc.car.hyundai.fingerprints import FW_VERSIONS\n", "\n", "TEST_PLATFORMS = set(CAR.with_flags(HyundaiFlags.CANFD)) & set(CAR.with_flags(HyundaiFlags.EV)) # CAN-FD electric vehicles only\n", "#TEST_PLATFORMS = set(CAR.with_flags(HyundaiFlags.CANFD)) - set(CAR.with_flags(HyundaiFlags.EV)) # CAN-FD hybrid and ICE vehicles only\n", @@ -72,7 +70,7 @@ " #if platform not in database:\n", " # print(f\"Skipping platform: {platform}, no data available\")\n", " # continue\n", - " \n", + "\n", " all_segments = database[platform]\n", "\n", " NUM_SEGMENTS = min(len(all_segments), MAX_SEGS_PER_PLATFORM)\n", @@ -190,20 +188,18 @@ ], "source": [ "import copy\n", - "import matplotlib.pyplot as plt\n", - "import numpy as np\n", "\n", "from opendbc.can.parser import CANParser\n", "from opendbc.car.hyundai.values import DBC\n", "from opendbc.car.hyundai.hyundaicanfd import CanBus\n", "\n", "from openpilot.selfdrive.pandad import can_capnp_to_list\n", - "from openpilot.tools.lib.logreader import LogReader\n", + "from openpilot.tools.lib.logreader import comma_car_segments_source\n", "\n", "message_names = [\"GEAR_SHIFTER\", \"ACCELERATOR\", \"GEAR\", \"GEAR_ALT\", \"GEAR_ALT_2\"]\n", "\n", "for segment in TEST_SEGMENTS:\n", - " lr = LogReader(segment)\n", + " lr = LogReader(segment, sources=[comma_car_segments_source])\n", " CP = lr.first(\"carParams\")\n", " if CP is None:\n", " continue\n", @@ -229,11 +225,11 @@ " for i, parsed_messages in enumerate(parsed_message_history):\n", " gear = parsed_messages[name][\"GEAR\"]\n", " if gear != gear_prev:\n", - " print(f\" *** Signal transition found! ***\")\n", + " print(\" *** Signal transition found! ***\")\n", " examples.append(i)\n", " gear_prev = gear\n", "\n", - "print(f\"Analysis finished\")\n" + "print(\"Analysis finished\")\n" ] }, { diff --git a/tools/car_porting/examples/hyundai_angle_steering.ipynb b/tools/car_porting/examples/hyundai_angle_steering.ipynb new file mode 100644 index 0000000000..ab59270b45 --- /dev/null +++ b/tools/car_porting/examples/hyundai_angle_steering.ipynb @@ -0,0 +1,228 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 28, + "id": "41c8c6a2-8780-44f8-b9ef-5c74784762ad", + "metadata": {}, + "outputs": [], + "source": [ + "segments = [\n", + " \"2bfcfe373379cd18/00000040--c8733fdf3b\"\n", + "]\n", + "platform = \"GENESIS_GV80_2025\"" + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "id": "cb455835-596f-4c0b-921e-a9173d282202", + "metadata": {}, + "outputs": [], + "source": [ + "import copy\n", + "import numpy as np\n", + "\n", + "from opendbc.car.common.conversions import Conversions as CV\n", + "from opendbc.can.parser import CANParser\n", + "from opendbc.car.hyundai.values import DBC\n", + "\n", + "from openpilot.selfdrive.pandad import can_capnp_to_list\n", + "from openpilot.tools.lib.logreader import LogReader\n", + "\n", + "for segment in segments:\n", + " lr = LogReader(segment)\n", + "\n", + " messages = [\n", + " (\"MDPS\", 100),\n", + " (\"ADAS_CMD_35_10ms\", 100),\n", + " (\"WHEEL_SPEEDS\", 100),\n", + " ]\n", + "\n", + " cp = CANParser(DBC[platform][\"pt\"], messages, 1)\n", + "\n", + " mdps_history = []\n", + " adas_cmd_35_10ms_history = []\n", + " velocity_history = []\n", + " timestamp_history = []\n", + "\n", + " last_vego_mph = 0\n", + " timestamp = 0\n", + "\n", + " for msg in lr:\n", + " if msg.which() == \"can\":\n", + " cp.update(can_capnp_to_list([msg.as_builder().to_bytes()]))\n", + " mdps_history.append(copy.copy(cp.vl[\"MDPS\"]))\n", + " adas_cmd_35_10ms_history.append(copy.copy(cp.vl[\"ADAS_CMD_35_10ms\"]))\n", + " timestamp_history.append(timestamp)\n", + " timestamp += 0.01\n", + "\n", + " velocity_history.append(last_vego_mph)\n", + "\n", + " if msg.which() == \"carState\":\n", + " last_vego_mph = msg.carState.vEgo * CV.MS_TO_MPH" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "id": "e539c020-ac92-4a6b-b7c8-6a2076a82096", + "metadata": {}, + "outputs": [], + "source": [ + "def process(history, func):\n", + " return np.array([func(h) for h in history])\n", + "\n", + "ADAS_ActvACILvl2Sta = process(adas_cmd_35_10ms_history, lambda x: x[\"ADAS_ActvACILvl2Sta\"])\n", + "ADAS_StrAnglReqVal = process(adas_cmd_35_10ms_history, lambda x: x[\"ADAS_StrAnglReqVal\"])\n", + "ADAS_ACIAnglTqRedcGainVal = process(adas_cmd_35_10ms_history, lambda x: x[\"ADAS_ACIAnglTqRedcGainVal\"])\n", + "STEERING_ANGLE_2 = process(mdps_history, lambda x: x[\"STEERING_ANGLE_2\"])\n", + "STEERING_COL_TORQUE = process(mdps_history, lambda x: x[\"STEERING_COL_TORQUE\"])\n", + "velocity_mph = np.array(velocity_history)\n", + "timestamps = np.array(timestamp_history)" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "id": "b2219289-0eb3-431d-b847-4a395446f8b7", + "metadata": {}, + "outputs": [ + { + "ename": "ModuleNotFoundError", + "evalue": "No module named 'pandas'", + "output_type": "error", + "traceback": [ + "\u001b[31m---------------------------------------------------------------------------\u001b[39m", + "\u001b[31mModuleNotFoundError\u001b[39m Traceback (most recent call last)", + "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[32]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m \u001b[38;5;28;01mimport\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34;01mpandas\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[38;5;28;01mas\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34;01mpd\u001b[39;00m\n\u001b[32m 3\u001b[39m df = pd.DataFrame({\n\u001b[32m 4\u001b[39m \u001b[33m'\u001b[39m\u001b[33mtimestamp\u001b[39m\u001b[33m'\u001b[39m: timestamps,\n\u001b[32m 5\u001b[39m \u001b[33m'\u001b[39m\u001b[33mvelocity_mph\u001b[39m\u001b[33m'\u001b[39m: velocity_mph,\n\u001b[32m (...)\u001b[39m\u001b[32m 10\u001b[39m \u001b[33m'\u001b[39m\u001b[33mSTEERING_COL_TORQUE\u001b[39m\u001b[33m'\u001b[39m: STEERING_COL_TORQUE,\n\u001b[32m 11\u001b[39m })\n\u001b[32m 13\u001b[39m \u001b[38;5;66;03m# Add derived columns\u001b[39;00m\n", + "\u001b[31mModuleNotFoundError\u001b[39m: No module named 'pandas'" + ] + } + ], + "source": [ + "import pandas as pd\n", + "\n", + "df = pd.DataFrame({\n", + " 'timestamp': timestamps,\n", + " 'velocity_mph': velocity_mph,\n", + " 'ADAS_ActvACILvl2Sta': ADAS_ActvACILvl2Sta,\n", + " 'ADAS_StrAnglReqVal': ADAS_StrAnglReqVal,\n", + " 'ADAS_ACIAnglTqRedcGainVal': ADAS_ACIAnglTqRedcGainVal,\n", + " 'STEERING_ANGLE_2': STEERING_ANGLE_2,\n", + " 'STEERING_COL_TORQUE': STEERING_COL_TORQUE,\n", + "})\n", + "\n", + "# Add derived columns\n", + "df['angle_error'] = df['ADAS_StrAnglReqVal'] - df['STEERING_ANGLE_2']\n", + "df['torque_reduction_pct'] = df['ADAS_ACIAnglTqRedcGainVal'] * 100\n", + "df['abs_col_torque'] = df['STEERING_COL_TORQUE'].abs()\n", + "\n", + "# Filter for conditions:\n", + "# 1. ADAS_ActvACILvl2Sta == 2 (ADAS active)\n", + "# 2. velocity_mph > 10 (vehicle moving)\n", + "filtered_df = df[(df['ADAS_ActvACILvl2Sta'] == 2) & (df['velocity_mph'] > 10)].copy()\n", + "\n", + "# Add additional analysis columns for the filtered data\n", + "if len(filtered_df) > 0:\n", + " # Calculate rate of change for torque reduction gain\n", + " filtered_df['tq_gain_delta'] = filtered_df['ADAS_ACIAnglTqRedcGainVal'].diff()\n", + "\n", + " # Identify potential override events (you may need to adjust threshold)\n", + " # Assuming override when absolute column torque exceeds certain value\n", + " torque_threshold = 50 # Adjust based on your data\n", + " filtered_df['driver_override'] = filtered_df['abs_col_torque'] > torque_threshold\n", + "\n", + " # Mark transitions in override state\n", + " filtered_df['override_transition'] = filtered_df['driver_override'].diff().fillna(0)\n", + "\n", + "# Save to CSV\n", + "output_filename = f\"adas_steering_analysis_{segment.replace('/', '_').replace('|', '_')}.csv\"\n", + "filtered_df.to_csv(output_filename, index=False)\n", + "\n", + "print(f\"Data exported to: {output_filename}\")\n", + "print(f\"Total frames: {len(df)}\")\n", + "print(f\"Filtered frames (ADAS active & velocity > 10 mph): {len(filtered_df)}\")\n", + "if len(filtered_df) > 0:\n", + " print(f\"Velocity range: {filtered_df['velocity_mph'].min():.1f} - {filtered_df['velocity_mph'].max():.1f} mph\")\n", + " print(f\"Torque reduction gain range: {filtered_df['ADAS_ACIAnglTqRedcGainVal'].min():.3f} - {filtered_df['ADAS_ACIAnglTqRedcGainVal'].max():.3f}\")\n", + " print(f\"Column torque range: {filtered_df['STEERING_COL_TORQUE'].min():.0f} - {filtered_df['STEERING_COL_TORQUE'].max():.0f}\")" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "id": "0bad114a-4b6c-4dc7-8064-5edcd304e3ce", + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAk0AAAHHCAYAAACiOWx7AAAAOnRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjEwLjUsIGh0dHBzOi8vbWF0cGxvdGxpYi5vcmcvWftoOwAAAAlwSFlzAAAPYQAAD2EBqD+naQABAABJREFUeJzsnXecFdX5/99Tbt/O7gJLWbpURRFrEEENGkvsDQ12Y8euPxNLorEkMZqixmggKn7tmkRFbBgVO3YEacvS2WX77VPO74+597J3G3eXbcB5v16r3Kln5s6d+cxznvN5FCGEQCKRSCQSiUTSJmpPN0AikUgkEolkZ0CKJolEIpFIJJIMkKJJIpFIJBKJJAOkaJJIJBKJRCLJACmaJBKJRCKRSDJAiiaJRCKRSCSSDJCiSSKRSCQSiSQDpGiSSCQSiUQiyQApmiQSiUQikUgyQIqmXo6iKNx+++093YxO4/bbb0dRlJ5uhkQi2YlYs2YNiqIwd+7cbt/33LlzURSFNWvWdPu+u5IhQ4Zwzjnn9HQzWuW9995DURTee++9nm5KGrudaPruu+84+eSTKS0txev1MmDAAI444gj+8pe/pC33u9/9jldeeaVnGtmLqK+v54477mCvvfYiKysLn8/H+PHjufHGG9m4cWNPN6/bUBQlo7/e9gPfWbAsi5KSEhRFYf78+S0ukxTcyT+/38/gwYM59thjmTNnDrFYbIe2D/Dhhx9y1FFHMWDAALxeb2r7Tz/9dKvrJB+q2/sbMmRIxudjZyApZJJ/qqpSUFDAUUcdxccff9zTzWs3vfWeb9s2TzzxBEcccQSFhYW4XC6Ki4v56U9/yqOPPtrmdd9d7LnnngwePJi2qrIdfPDB9O3bF9M0u7FlnY/e0w3oTj766COmTZvG4MGDufDCC+nXrx/r1q3jk08+4cEHH+SKK65ILfu73/2Ok08+meOPP77nGgxEIhF0vWe+ptWrV3P44Yezdu1aTjnlFC666CLcbjfffvstjz/+OC+//DLLly/vkbZ1N08++WTa5yeeeIK33nqr2fQxY8Z0Z7N2Gd599102bdrEkCFDmDdvHkcddVSryz788MNkZWURi8XYsGEDCxYs4LzzzuOBBx7g1VdfZdCgQR3a/vPPP89pp53GxIkTueqqq8jPz6esrIz333+ff/zjH5x55pkttueQQw5pdh1ccMEF7Lffflx00UWpaVlZWZmejp2KM844g5/97GdYlsXy5ct56KGHmDZtGp9//jkTJkzo6eZlTGv3/LPPPpvTTz8dj8fT7W2KRCKccMIJLFiwgIMOOojrrruOvn37Ul1dzf/+9z8uvfRSPv30Ux5//PF2b/vHH39EVTsnbjJz5kxuuukmPvjgAw455JBm89esWcPHH3/M5Zdf3mPPs05D7Eb87Gc/E0VFRaKmpqbZvC1btqR9DgQCYtasWd3TsCZYliUikUiP7DuJYRhir732En6/X3zwwQfN5tfV1Yn/9//+X7u3e9ttt4ld4bK77LLLOu04esP33dP84he/EPvss4948MEHRSAQEMFgsNkyyWunsrKy2bynnnpKqKoq9t9//w5vf+zYsWLcuHEiFos1m9f0/rA9OvP+0VJbewNlZWUCEL///e/Tps+fP18A4pJLLun0fc2ZM6fTttmUnrznt8bFF18sAPHAAw+0OH/58uXib3/7Wze3qjlr164ViqKIiy++uMX5v/vd7wQgPvnkk4y3uXDhQgGIhQsXdlIrO4ed/+nVDvbYYw9x6KGHbnc5oNlf4x/T+vXrxbnnniuKi4uF2+0WY8eOFY8//niz7USjUXHrrbeK4cOHC7fbLQYOHCiuv/56EY1Gm+3vsssuE0899ZQYO3as0HVdvPzyy6l5t912W2rZ5INjxYoVYtasWSI3N1fk5OSIc845R4RCobTthsNhccUVV4g+ffqIrKwsceyxx4r169c322ZLPPPMMwIQd91113bPV5LnnntO7LPPPsLr9Yo+ffqImTNnivXr16ct01Q0tXUzbO3Yf/zxRzFz5kyRk5MjCgsLxa9+9Sth27ZYu3atOO6440R2drbo27ev+MMf/pC2veSP8NlnnxV33nmnGDBggPB4PGL69OlixYoVGR+nEC2LpmAwKK655hoxcOBA4Xa7xahRo8Tvf/97Ydt2s+Nq7fv+/vvvxbRp04TX6xUDBgwQv/3tb8Xjjz8uAFFWVtbquUlSWlra7MZfU1MjrrrqqlS7hg8fLu655x5hWVabx3j00UeLoUOHtjjvgAMOEJMmTUp9fvPNN8XBBx8scnNzRSAQEKNGjRI333xzm9tPEg6HRXZ2trjvvvvEpk2bhKqqYt68ec2Wa0s0CSHERRddJADx5ptvdmj7Ho9HnHPOORm1eXu09AD+8ssvxZFHHimys7NFIBAQ06dPFx9//HHaMnPmzBGAeO+998Qll1wiioqKRF5eXmr+3//+dzFs2DDh9XrF5MmTxfvvvy+mTp0qpk6d2mwbja8XIVp/CH3yySdixowZIicnR/h8PnHIIYeIDz/8cLvH2JpoCgaDAhA//elP06Zneh3W1NSIWbNmiZycHJGbmyt+8YtfiK+++qrZfaLpcSeZNWuWKC0tTZtmWZZ44IEHxPjx44XH4xGFhYVixowZ4vPPPxdCtH3Pb+18/u1vfxNjx44Vbrdb9O/fX1x66aXNXsinTp0qxo0bJ5YsWSIOPfRQ4fP5RElJibj33nvbPrnCESKapokjjzxyu8s25ve//7048MADRUFBgfB6vWKfffYRzz//fLPlmt4rksf54YcfiquvvloUFhYKv98vjj/+eFFRUbHd/U6dOlX06dNHxOPxZvPGjx8vhg8fLoQQYs2aNeKSSy4Ro0aNEl6vVxQUFIiTTz45o+u1pftbct9Nr4VMn7/tZSePk7WP0tJSPv74Y77//nvGjx/f6nJPPvlks/D68OHDAdiyZQsHHHAAiqJw+eWXU1RUxPz58zn//POpr69n9uzZgNMPfdxxx/Hhhx9y0UUXMWbMGL777jv+9Kc/sXz58mZ95++++y7PPfccl19+OYWFhdvNfzj11FMZOnQod999N19++SWPPfYYxcXF3HvvvallzjnnHJ577jnOPvtsDjjgAP73v/9x9NFHZ3Su/vOf/wBOaDoT5s6dy7nnnsvkyZO5++672bJlCw8++CCLFi3iq6++Ii8vL6PtZMJpp53GmDFjuOeee3jttde48847KSgo4O9//zvTp0/n3nvvZd68eVx33XVMnjy5Wbj4nnvuQVVVrrvuOurq6rjvvvuYOXMmn376aYfbJITguOOOY+HChZx//vlMnDiRBQsWcP3117Nhwwb+9Kc/pS3f0ve9efNmpk2bhmma3HTTTQQCAR599FF8Pl+H2xUOh5k6dSobNmzg4osvZvDgwXz00UfcfPPNbNq0iQceeKDVdU877TR+8Ytf8PnnnzN58uTU9PLycj755BN+//vfA7BkyRKOOeYY9txzT37zm9/g8XhYuXIlixYtyqiN//nPfwgGg5x++un069ePQw89lHnz5rXaHdYaZ599No8++ihvvvkmRxxxRLu3X1payjvvvMP69esZOHBgu/a9PZYsWcKUKVPIycnhhhtuwOVy8fe//51DDz2U//3vf+y///5py1966aUUFRVx6623EgqFAHj88ce5+OKLOeigg5g9ezarV6/muOOOo6CgoMUuyUx49913Oeqoo5g0aRK33XYbqqoyZ84cpk+fzgcffMB+++3X7m0mE6bz8/NT0zK9DoUQ/PznP+fDDz/kl7/8JWPGjOHll19m1qxZHTq+JOeffz5z587lqKOO4oILLsA0TT744AM++eQT9t133zbv+S1x++23c8cdd3D44YdzySWX8OOPP/Lwww/z+eefs2jRIlwuV2rZmpoajjzySE488UROPfVUXnjhBW688UYmTJjQZjf0/PnzsSyLs846q13H+uCDD3Lccccxc+ZM4vE4zzzzDKeccgqvvvpqRvf/K664gvz8fG677TbWrFnDAw88wOWXX86zzz7b5nozZ87koosuYsGCBRxzzDGp6d999x3ff/89t956KwCff/45H330EaeffjoDBw5kzZo1PPzwwxx66KH88MMP+P3+dh1vS7T3+dsudkhy7WS8+eabQtM0oWmaOPDAA8UNN9wgFixY0KIybi1Ue/7554v+/fuLrVu3pk0//fTTRW5urgiHw0IIIZ588kmhqmqzrq1HHnlEAGLRokWpaYBQVVUsWbKk2f5oJdpy3nnnpS13wgkniD59+qQ+L168WABi9uzZacudc845GUWa9t57b5Gbm9vmMkni8bgoLi4W48ePT+tmevXVVwUgbr311mbtT9KRSNNFF12Ummaaphg4cKBQFEXcc889qek1NTXC5/OlfYfJN5cxY8akdcE8+OCDAhDfffddRscrRPNI0yuvvCIAceedd6Ytd/LJJwtFUcTKlSvTjqul73v27NkCEJ9++mlqWkVFhcjNze1wpOm3v/2tCAQCYvny5WnL3XTTTULTNLF27dpWj7Gurk54PB5x7bXXpk2/7777hKIoory8XAghxJ/+9Kc2I0Db45hjjhEHH3xw6vOjjz4qdF1v9na7vUhTTU2NAMQJJ5zQoe0nI3put1tMmzZN/PrXvxYffPDBdiNyLdH0/nH88ccLt9stVq1alZq2ceNGkZ2dLQ455JDUtOTb/k9+8hNhmmZqevI3NnHixLRr99FHHxVAhyJNtm2LkSNHihkzZqRFQ8PhsBg6dKg44ogj2jzG5G/3jjvuEJWVlWLz5s3igw8+EJMnTxZAWnQj0+sw+Tu67777UsuYpimmTJnS4UjTu+++KwBx5ZVXNlu28XG3ds9vej4rKiqE2+0WP/3pT9Oujb/+9a8CEP/85z/T2giIJ554IjUtFouJfv36iZNOOqnZvhpz9dVXC0B8/fXXadNjsZiorKxM/TV9FiWfQUni8bgYP368mD59etr01iJNhx9+eNp5ufrqq4WmaaK2trbN9lZXVwuPxyPOOOOMtOk33XRTqoegpfYJIcTHH3/c7DztSKSpPc/f9rJbjZ474ogj+PjjjznuuOP45ptvuO+++5gxYwYDBgxIRVbaQgjBiy++yLHHHosQgq1bt6b+ZsyYQV1dHV9++SXgJJWOGTOG0aNHpy03ffp0ABYuXJi27alTpzJ27NiMj+WXv/xl2ucpU6ZQVVVFfX09AG+88QbgvLE2pnGye1vU19eTnZ2d0bJffPEFFRUVXHrppXi93tT0o48+mtGjR/Paa69ltJ1MueCCC1L/1jSNfffdFyEE559/fmp6Xl4ee+yxB6tXr262/rnnnovb7U59njJlCkCLy2bK66+/jqZpXHnllWnTr732WoQQzUZstfR9v/766xxwwAFpb/dFRUXMnDmzw+16/vnnmTJlCvn5+WnX4eGHH45lWbz//vutrpuTk8NRRx3Fc889lzYq5tlnn+WAAw5g8ODBAKko4r///W9s225X+6qqqliwYAFnnHFGatpJJ52Eoig899xz7dpWMtG6oaGhQ9s/77zzeOONNzj00EP58MMP+e1vf8uUKVMYOXIkH330Ubva0hjLsnjzzTc5/vjjGTZsWGp6//79OfPMM/nwww9Tv9skF154IZqmpT4nf2O//OUv067dc845h9zc3A616+uvv2bFihWceeaZVFVVpa6NUCjEYYcdxvvvv5/R93nbbbdRVFREv379mDJlCkuXLuWPf/wjJ598cmqZTK/D119/HV3XueSSS1LrapqW8X2rJV588UUUReG2225rNq8j9idvv/028Xic2bNnpyVSX3jhheTk5DS732VlZaVFi9xuN/vtt9927zfJa6LpAILXX3+doqKi1F9paWna/MaR6ZqaGurq6pgyZUrq2bQ9LrroorTzMmXKFCzLory8vM318vPz+dnPfsZ//vOfVHRUCMEzzzzDvvvuy6hRo5q1zzAMqqqqGDFiBHl5eRm3cXu09/nbHnYr0QQwefJkXnrpJWpqavjss8+4+eabaWho4OSTT+aHH35oc93Kykpqa2t59NFH0y7aoqIizj33XAAqKioAWLFiBUuWLGm2XPLCSS6XZOjQoe06juQDK0kyFF5TUwM4XSiqqjbb7ogRIzLafk5OTtrDpy2SP6Y99tij2bzRo0dv98fWXpoee25uLl6vl8LCwmbTk+ejrfWbnruOUF5eTklJSTOhmRxN1/QctPR9l5eXM3LkyGbTWzqvmbJixQreeOONZtfh4YcfDjS/Dpty2mmnsW7dutQQ8lWrVrF48WJOO+20tGUOPvhgLrjgAvr27cvpp5/Oc889l9ED99lnn8UwDPbee29WrlzJypUrqa6uZv/992fevHntOtZgMAiQ9h20d/szZsxgwYIF1NbW8v7773PZZZdRXl7OMcccs91z1RqVlZWEw+EWv8cxY8Zg2zbr1q1Lm970+kheP02vD5fLlSbE2sOKFSsAmDVrVrPr47HHHiMWi1FXV7fd7Vx00UW89dZb/Pe//+Xqq68mEolgWVazfWVyHZaXl9O/f/9mQmFHfgOrVq2ipKSEgoKCDm+jMa3d79xuN8OGDWv2Wx84cGAzcZafn7/d+03yOk5e10kOPvhg3nrrLd566y1++tOfNlvv1Vdf5YADDsDr9VJQUEBRUREPP/xwRt8l7Nj9cebMmYRCIf79738Dzoj1NWvWpL34RSIRbr31VgYNGoTH46GwsJCioiJqa2szbuP2aO/ztz3sVjlNjXG73UyePJnJkyczatQozj33XJ5//vkW30aSJB8CZ511Vqt97HvuuWdq2QkTJnD//fe3uFzTHIT25q00fgttTOOIwI4wevRovvrqK9atW9fhfIlMaO1Nr+lNtzEtHXt7zkdXn7tM2JE8pbZoet5s2+aII47ghhtuaHH55E2kNY499lj8fj/PPfccBx10EM899xyqqnLKKaeklvH5fLz//vssXLiQ1157jTfeeINnn32W6dOn8+abb7Z6voGUcDn44INbnL969eqMRcH3338PpL8YdHT7fr+fKVOmMGXKFAoLC7njjjuYP3/+DufWZMqOXB+Z/qaS97Pf//73TJw4scV1MrFJGDlyZEr8HHPMMWiaxk033cS0adPYd999U/vakeuwJRRFafE329a9oyfo6P1m9OjRgHNd77XXXqnpjcXmU089lbbOBx98wHHHHcchhxzCQw89RP/+/XG5XMyZM6dNr7HOaC84339ubi5PP/00Z555Jk8//TSapnH66aenlrniiiuYM2cOs2fP5sADDyQ3NxdFUTj99NO3+6LV1rXduN3tff62h91WNDUm+cPetGlTalpLX05RURHZ2dlYlpW6aFtj+PDhfPPNNxx22GE94oBdWlqKbduUlZWlvZ2uXLkyo/WPPfZY/u///o+nnnqKm2++ebv7Asf3Ixn+TPLjjz82Cx83JvkWU1tbmza9s6NTXU1paSlvv/02DQ0NaZGOZcuWpeZnso3k239jfvzxx2bT8vPzm52zeDyedg2Dcx0Gg8HtXq+tEQgEOOaYY3j++ee5//77efbZZ5kyZQolJSVpy6mqymGHHcZhhx3G/fffz+9+9ztuueUWFi5c2Oq+y8rK+Oijj7j88suZOnVq2jzbtjn77LN5+umn+dWvfpVRW5NeSTNmzOjU7bd0f2gPRUVF+P3+Fr/HZcuWoarqdm/iyetnxYoVab8xwzAoKytLe6hm+ptKJjrn5OR0+PpoiVtuuYV//OMf/OpXv0qlCWR6HSaT8YPBYJpga+030FIXV0vHuWDBAqqrq9uMNmV6n258v2ssuOPxOGVlZZ12Lo866ig0TWPevHkZd9G/+OKLeL1eFixYkOYrNWfOnE5p0/bweDycfPLJPPHEE2zZsoXnn3+e6dOn069fv9QyL7zwArNmzeKPf/xjalo0Gm12vbZES/c9cL7zxt9FVz5/d6vuuYULF7aoll9//XUgPdwaCASafTmapnHSSSfx4osvpt5qG1NZWZn696mnnsqGDRv4xz/+0Wy5SCSS6vPtKpIPjoceeihtelPn89Y4+eSTmTBhAnfddVeL7r4NDQ3ccsstgPNQKS4u5pFHHklzp50/fz5Lly5tc8RGTk4OhYWFzXJrmra7t5M09/vrX/+aNv1Pf/oTiqK0OUqm8TY++eQTPvvss9S0ysrKFruRhg8f3uycPfroo83esk899VQ+/vhjFixY0GwbtbW1GbnznnbaaWzcuJHHHnuMb775Jq1rDqC6urrZOsnIRVtuxcnjuuGGGzj55JPT/k499VSmTp2acRfd008/zWOPPcaBBx7IYYcd1qHtv/POOy1uu6X7Q3vQNI2f/vSn/Pvf/04rxbFlyxaefvppfvKTn5CTk9PmNvbdd1+Kiop45JFHiMfjqelz585tdp9KiqHG14dlWTz66KNpy02aNInhw4fzhz/8oVkXEKTfz9pDXl4eF198MQsWLODrr78GMr8Of/azn2GaJg8//HBa21u6bw0fPpxly5altfObb75pNmrzpJNOQgjBHXfc0WwbjZ8HLd3zW+Lwww/H7Xbz5z//OW39xx9/nLq6uoxHKG+PwYMHc9555zF//vxm95UkTZ9nmqahKErafWDNmjXd6nQ+c+ZMDMPg4osvprKyspng0zStWbv/8pe/ZBQhHD58OJ988knab+DVV19t1r3dlc/f3SrSdMUVVxAOhznhhBMYPXo08Xicjz76iGeffZYhQ4ak8pLAuaG8/fbb3H///ZSUlDB06FD2339/7rnnHhYuXMj+++/PhRdeyNixY6murubLL7/k7bffTj1Azj77bJ577jl++ctfsnDhQg4++GAsy2LZsmU899xzLFiwIPUG2xVMmjSJk046iQceeICqqqqU5UDSwXt76tvlcvHSSy9x+OGHc8ghh3Dqqady8MEH43K5WLJkCU8//TT5+fncdddduFwu7r33Xs4991ymTp3KGWeckbIcGDJkCFdffXWb+7rgggu45557uOCCC9h33315//33dzqn8WOPPZZp06Zxyy23sGbNGvbaay/efPNN/v3vfzN79uw2hy8nueGGG3jyySc58sgjueqqq1KWA6WlpXz77bdpy15wwQX88pe/5KSTTuKII47gm2++YcGCBc3yuq6//nr+85//cMwxx3DOOecwadIkQqEQ3333HS+88AJr1qxptk5Tfvazn5Gdnc11112XenFozG9+8xvef/99jj76aEpLS6moqOChhx5i4MCB/OQnP2l1u/PmzWPixImtRlmOO+44rrjiCr788kv22Wef1PQXXniBrKws4vF4yhF80aJF7LXXXjz//PMd3v7Pf/5zhg4dyrHHHsvw4cMJhUK8/fbb/Pe//2Xy5Mkce+yxbZ6ntrjzzjt56623+MlPfsKll16Kruv8/e9/JxaLcd999213fZfLxZ133snFF1/M9OnTOe200ygrK2POnDnNuhfHjRvHAQccwM0335yKrjzzzDPNBLKqqjz22GMcddRRjBs3jnPPPZcBAwawYcMGFi5cSE5ODv/97387dLxXXXUVDzzwAPfccw/PPPNMxtfhsccey8EHH8xNN93EmjVrGDt2LC+99FKLuS7nnXce999/PzNmzOD888+noqKCRx55hHHjxqUl1k+bNo2zzz6bP//5z6xYsYIjjzwS27b54IMPmDZtGpdffjnQ+j2/KUVFRdx8883ccccdHHnkkRx33HH8+OOPPPTQQ0yePLndFgFt8cADD1BWVsYVV1zBM888w7HHHktxcTFbt25l0aJF/Pe//00T80cffTT3338/Rx55JGeeeSYVFRX87W9/Y8SIEc3uIV3F1KlTGThwIP/+97/x+XyceOKJafOPOeYYnnzySXJzcxk7diwff/wxb7/9Nn369Nnuti+44AJeeOEFjjzySE499VRWrVrFU0891ez+2qXP3w6Pu9sJmT9/vjjvvPPE6NGjRVZWlnC73WLEiBHiiiuuaOb4u2zZMnHIIYcIn8/XzNxyy5Yt4rLLLhODBg0SLpdL9OvXTxx22GHi0UcfTdtGPB4X9957rxg3bpzweDwiPz9fTJo0Sdxxxx2irq4utRwJs8OWoJVh902HXbc0zDgUConLLrtMFBQUiKysLHH88ceLH3/8UQBpw/PboqamRtx6661iwoQJwu/3C6/XK8aPHy9uvvlmsWnTprRln332WbH33nsLj8cjCgoKMjK3FMIZgnr++eeL3NxckZ2dLU499VRRUVGR8bHPmjVLBAKBZm1PGsslSQ5hbWr01hG34ZbMLRsaGsTVV18tSkpKhMvlEiNHjmzT3LIlvv32WzF16tTtmltaliVuvPHGlAHdjBkzxMqVK1scktvQ0CBuvvlmMWLECOF2u0VhYaE46KCDxB/+8IcW7TZaYubMmanhyE155513xM9//nNRUlIi3G63KCkpEWeccUaz4eWNSVpi/PrXv251mTVr1ghAXH311UKIbd9/8s/r9YqBAweKY445Rvzzn/9MM63ryPb/7//+T5x++uli+PDhwufzCa/XK8aOHStuueUWUV9fv91z1JjWzC1nzJghsrKyhN/vF9OmTRMfffRR2jLJ33HSdLEpDz30kBg6dKjweDxi3333bdHcUgghVq1aJQ4//HDh8XhE3759xf/7f/9PvPXWWy2aW3711VfixBNPFH369BEej0eUlpaKU089VbzzzjttHmNr5pZJzjnnHKFpWspuI9PrsKqqSpx99tkpc8uzzz67RXNLIRwn+GHDhgm32y0mTpwoFixY0KK5pWma4ve//70YPXq0cLvdoqioSBx11FFi8eLFqWVau+e3ZuHw17/+VYwePVq4XC7Rt29fcckll7RqbtmUltrYGqZpijlz5ojp06eLgoICoeu6KCwsFIcddph45JFHmlUTePzxx8XIkSOFx+MRo0ePFnPmzGnxvtua5UDTa68jztzXX3+9AMSpp57abF5NTY0499xzRWFhocjKyhIzZswQy5Yta9ae1vb7xz/+MWVMfPDBB4svvviixd9Aps/f9qII0Y3Zr5Ie5+uvv2bvvffmqaee2qGh7JLuI2kcWlZWtssVfZXsOIceeiiALBYtkXQDu1VO0+5GJBJpNu2BBx5AVdUWiypKJBKJRCJpnd0qp2l347777mPx4sVMmzYNXdeZP38+8+fP56KLLupSGwGJRCKRSHZFpGjahTnooIN46623+O1vf0swGGTw4MHcfvvtqVFvEolEIpFIMkfmNEkkEolEIpFkgMxpkkgkEolEIskAKZokEolEIpFIMkDmNDXBtm02btxIdnZ2j5Q/kUgkEolE0n6EEDQ0NFBSUoKqdk1MSIqmJmzcuFGOLJNIJBKJZCdl3bp1DBw4sEu2LUVTE5LFVtetW7fdelASiUQikUh6B/X19QwaNCitaHpnI0VTE5Jdcjk5OVI0SSQSiUSyk9GVqTUyEVwikUgkEokkA6RokkgkEolEIskAKZokEolEIpFIMkDmNHUA27aJx+M93QyJpMtxuVxomtbTzZBIJJJegRRN7SQej1NWVoZt2z3dFImkW8jLy6Nfv37St0wikez2SNHUDoQQbNq0CU3TGDRoUJeZZ0kkvQEhBOFwmIqKCgD69+/fwy2SSCSSnkWKpnZgmibhcJiSkhL8fn9PN0ci6XJ8Ph8AFRUVFBcXy646iUSyWyNDJe3AsiwA3G53D7dEIuk+ki8IhmH0cEskEomkZ5GiqQPI3A7J7oS83iUSicRBds9JJBJJJ2PbgmWb6/luQx1b6qP0zfUyoSSX0f1yUFXFmb+lnu/WJ+bneJkwIJdRxdms3BqkJhSnOhynIWJQ0RBLzU+uL5FIegYpmiSSXZzbb7+dV155ha+//rqnm7LLY9uCV77ewJxFa/hxcz2GJRCAqoBHVxlRnM2hexTxZXkNX62rJRK3UvPdukqWR0dXFeoiBlHDRjTatkdTGNM/mxMnDWK/oQWMKs6WAkoi6WZk99wujqIobf7dfvvtPd3EHuO9995LOxdFRUX87Gc/47vvvuu2Nqxfvx6328348eO7bZ+SrmFxeTW/+Odn3Pjit3y3oY54QjAB2AIihs13G+r4y7srWbSqikjcQlFAU5z5UcNmazDOlvoYkSaCCSBmCb5eX89v/vsDv3xyMbOf/ZrF5dXdfZgSyW6NFE09QDJ0/+nqKpZtrse2m94eO49Nmzal/h544AFycnLSpl133XXt2t6umAz8448/smnTJhYsWEAsFuPoo4/uNvPSuXPncuqpp1JfX8+nn37aLfuUdD6Ly6u589Uf+KK8GsPK7Pfc2lLbW9u0BVXBGEs21HHXa0ulcJJIuhEpmrqZxeXVzH72a6559htuefk7rnn2my59Y+zXr1/qLzc3F0VRUp+Li4u5//77GThwIB6Ph4kTJ/LGG2+k1l2zZg2KovDss88ydepUvF4v8+bNw7IsrrnmGvLy8ujTpw833HADs2bN4vjjj0+tO2TIEB544IG0tkycODEtslVbW8sFF1xAUVEROTk5TJ8+nW+++abVYznooIO48cYb06ZVVlbicrl4//33AXjooYcYOXIkXq+Xvn37cvLJJ2/3HBUXF9OvXz/22WcfZs+ezbp161i2bFlq/ocffsiUKVPw+XwMGjSIK6+8klAolJpfUVHBsccei8/nY+jQocybN6/F42+KEII5c+Zw9tlnc+aZZ/L444+nzU+e/5deeolp06bh9/vZa6+9+Pjjj9OW+8c//sGgQYPw+/2ccMIJ3H///eTl5bW578cee4wxY8bg9XoZPXo0Dz300HbPk6RlbFswd9EaNtZFiZvtM721BWSosdJoiFm4dKcb74mPyrv0xUsikWxDiqZuZHF5NXe9tpTvN9SR49UZmO8nx6uzZGPPvDE++OCD/PGPf+QPf/gD3377LTNmzOC4445jxYoVacvddNNNXHXVVSxdupQZM2bwxz/+kblz5/LPf/6TDz/8kOrqal5++eV27/+UU06hoqKC+fPns3jxYvbZZx8OO+wwqqtbPg8zZ87kmWeeQYhtD4hnn32WkpISpkyZwhdffMGVV17Jb37zG3788UfeeOMNDjnkkIzbU1dXxzPPPANss5VYtWoVRx55JCeddBLffvstzz77LB9++CGXX355ar1zzjmHdevWsXDhQl544QUeeuihlCFkWyxcuJBwOMzhhx/OWWedxTPPPJMmxpLccsstXHfddXz99deMGjWKM844A9M0AVi0aBG//OUvueqqq/j666854ogjuOuuu9rc77x587j11lu56667WLp0Kb/73e/49a9/zb/+9a+Mz5VkG698vZ7/La9kazBGd2qX1ZUhvLrKioogyysaum/HEslujEwE7yZsW/Cvj8qpDRsM6eNPDeMOeHT8bo3y6jBPfFTO3oPyuy258w9/+AM33ngjp59+OgD33nsvCxcu5IEHHuBvf/tbarnZs2dz4oknpj4/8MAD3HzzzalpjzzyCAsWLGjXvj/88EM+++wzKioq8Hg8qfa88sorvPDCC1x00UXN1jn11FOZPXt2KvID8PTTT3PGGWegKApr164lEAhwzDHHkJ2dTWlpKXvvvfd22zJw4ECAlGA57rjjGD16NAB33303M2fOZPbs2QCMHDmSP//5z0ydOpWHH36YtWvXMn/+fD777DMmT54MwOOPP86YMWO2u9/HH3+c008/HU3TGD9+PMOGDeP555/nnHPOSVvuuuuu4+ijjwbgjjvuYNy4caxcuZLRo0fzl7/8haOOOirVzTpq1Cg++ugjXn311Vb3e9ttt/HHP/4x9f0NHTqUH374gb///e/MmjVru+2WbGNxeTUPv7eacNzC6ubKSnFLUNEQI8erUxfe9brNJZLeiIw0dRPLKxpYWRGkONvTzPdGURSKsjzd+sZYX1/Pxo0bOfjgg9OmH3zwwSxdujRt2r777pv6d11dHZs2bWL//fdPTdN1PW2ZTPjmm28IBoP06dOHrKys1F9ZWRmrVq1qcZ2ioiJ++tOfMm/ePADKysr4+OOPmTlzJgBHHHEEpaWlDBs2jLPPPpt58+YRDoe325YPPviAxYsXM3fuXEaNGsUjjzyS1s65c+emtXHGjBnYtk1ZWRlLly5F13UmTZqUWmf06NHb7R6rra3lpZde4qyzzkpNO+uss5p10QHsueeeqX8nS5kkI1k//vgj++23X9ryTT83JhQKsWrVKs4///y0Y7rzzjtbPe+Slkm+CIVjZo+1oSFqIlDI9bt6rA0Sye6EjDR1E3Vhg7hp4XV5WpzvdWlsDcZ65RtjIBBo9zqqqqZ1o0F6EnkwGKR///689957zdZtS3DMnDmTK6+8kr/85S88/fTTTJgwgQkTJgCQnZ3Nl19+yXvvvcebb77Jrbfeyu23387nn3/e5jaHDh1KXl4ee+yxBxUVFZx22mmpHKlgMMjFF1/MlVde2Wy9wYMHs3z58jbOQus8/fTTRKPRNPEphMC2bZYvX86oUaNS012ubQ/EpODuaMHoYDAIOHlQjfcNyBIp7ST5IlQQcLG5IYqaGAXXnRi2Tf9cL6OKs7t3xxLJboqMNHUTuX4Xbl0jalgtzo8aFm5d67Y3xpycHEpKSli0aFHa9EWLFjF27NhW18vNzaV///5pI71M02Tx4sVpyxUVFbFp06bU5/r6esrKylKf99lnHzZv3oyu64wYMSLtr7CwsNX9//znPycajfLGG2/w9NNPp6JMSXRd5/DDD+e+++7j22+/Zc2aNbz77rttn4xGXHbZZXz//fepHK199tmHH374oVkbR4wYgdvtZvTo0c2O/8cff6S2trbN/Tz++ONce+21fP3116m/b775hilTpvDPf/4z4/busccefP7552nTmn5uTN++fSkpKWH16tXNjmfo0KEZ71ey7UVIU1V0VUVVHL+l7kRXFU6aNED6NUkk3YSMNHUTo4qzGVGcxZKNdfjdWloXnRCCymCM8SW53frGeP3113PbbbcxfPhwJk6cyJw5c/j6669T3V+tcdVVV3HPPfcwcuRIRo8ezf33399MJEyfPp25c+dy7LHHkpeXx6233poWyTj88MM58MADOf7447nvvvsYNWoUGzdu5LXXXuOEE05otbsvEAhw/PHH8+tf/5qlS5dyxhlnpOa9+uqrrF69mkMOOYT8/Hxef/11bNtmjz32yPic+P1+LrzwQm677TaOP/54brzxRg444AAuv/xyLrjgAgKBAD/88ANvvfUWf/3rX9ljjz048sgjufjii3n44YfRdZ3Zs2enCt22xNdff82XX37JvHnzUrlTSc444wx+85vfcOedd2bU3iuuuIJDDjmE+++/n2OPPZZ3332X+fPnt1n65I477uDKK68kNzeXI488klgsxhdffEFNTQ3XXHNNZidKknoRsoXApSm4VI24ZWPaotsiTmP753D8RCcnz7YFyysaqAsb5Ppd0vxSIukCZKSpm1BVhVkHlZLrc1FeHSYUM7FsQShmUl4dJtfn4hcHlXbrTe7KK6/kmmuu4dprr2XChAm88cYb/Oc//2HkyJFtrnfttddy9tlnM2vWLA488ECys7M54YQT0pa5+eabmTp1KscccwxHH300xx9/PMOHD0/NVxSF119/nUMOOYRzzz2XUaNGcfrpp1NeXk7fvn3b3P/MmTNTUZnBgwenpufl5fHSSy8xffp0xowZwyOPPML//d//MW7cuHadl8svv5ylS5fy/PPPs+eee/K///2P5cuXM2XKFPbee29uvfVWSkpKUsvPmTOHkpISpk6dyoknnshFF11EcXFxq9t//PHHGTt2bDPBBHDCCSdQUVHB66+/nlFbDz74YB555BHuv/9+9tprL9544w2uvvpqvF5vq+tccMEFPPbYY8yZM4cJEyYwdepU5s6dKyNN7ST5IhSMmQTcOjaQ5dbI8epke7q+q1NT4IS9B6KqSrdbmUgkuyuKaJp4sptTX19Pbm4udXV15OTkpM2LRqOUlZUxdOjQNh9KbbG4vJp/fVTOyoogcdPpkhtZnMUvDiplUmlBZxxCj3DOOedQW1vLK6+80tNN6RUMGTKE2bNnp0bddScXXnghy5Yt44MPPuiU7XXGdb+rkrQR2VIfpS5iYNlOl5lp2cQsG1uAgtNt1xE/ptbQFBiY7+fvv5hEKGZy12tLqQ0bFGd78LqcNIDKYIxcn4tbjh7T5r1FRqgkuwptPb87C9k9181MKi1g70H58iYl6TT+8Ic/cMQRRxAIBJg/fz7/+te/pFllNzGptIBbjh7Dvz4q59v1tWwNxohbNpqqoAmFbJeGqipE4iaWKVABVXUSxpOCStD8/5oCQkBL6f4eTaFPlpuJg/IYUZjFNc9/08zKxO/R6SME62si/PXdlfzj7H3R9eYdC41f4mKmUwevf46XkyYN5PiJMldKImmKFE09gKoqjO7XNSpYsvvx2Wefcd9999HQ0MCwYcP485//zAUXXNDTzdptaPwiVBOKUxsx2FQbYc6iNQwrDKCpChUNMVZsCaIqoGkKkbiFqjijZs1EHhTCKdpr2jYKCv1yPGyuj6YiVAqQ7dHI9rnom+PlFweVsnJrsJmVSW3EYH1NmFDMwrRtPlpVxQVPfMEVh41Iizglo2S1YQOfW6MhahCMWqyrDvPl2lpe+nIDVx8xcqeOgEsknY0UTZJOYe7cuT3dhF7FmjVrum1fzz33XLftS9IyTV+Elm2u54XFG4iZNoYtqGiIYgqBbQkwnWiSqoBbU/FqCmHDxud2uurjps3KyiAuXaVvjoe6iIkAsjwafQIeRvXNTnXnf7q6Ks3KpDZisGJLA6YlcOsqbk0jbFgs39LAXa8tTXXVNTbbzfO7WFkRTK3jVVTChsXX62q489Uf+NUxY6VwkkgS7FSi6f333+f3v/89ixcvZtOmTbz88stp9c6EENx222384x//oLa2loMPPpiHH354u4nNEolk96SlfB5gh7vPk0nii8urqU/kOvl0lahpYwknqmQLMCwbgRNhGlaYRbbXRShmMijfz5WHj6TA7ybbp4NwjCybtqexlYnfo7O+JoxpCXxuDQWnuK+uKgzM91EViqeqDiQ9poqyPaypCqWtA+DVNUzbpjIY7/ZKBRJJb2anEk2hUIi99tqL8847L62sR5L77ruPP//5z/zrX/9i6NCh/PrXv2bGjBn88MMPnZrAKnPnJbsTu+r13tKgjIKAGxBUh4zUtBHFWcxqY6BGa8LrkFGFvLusgohh49VVVFVBVaBxTd9w3MKjq2T7XdhCUB+JU14dIdens3RjHQGPjlvT6Jfn5YjRfZvlJTW2MukjBKGYhVtXndwoIYhbNtlenSyPjqooqaoDSY8p29bS1kmiKRAXkOPRU+vIlAKJZCcTTUcddRRHHXVUi/OEEDzwwAP86le/4uc//zkATzzxBH379uWVV15J1VfbEZI+Q/F4vE0fHolkVyJZiqaxM/nOTuN8HmfEmYfKhiifr3GG6I8ozmJgvp+oYaUKarc0Cq1l4eUCFFZXBgnFnK61ULxlU1sBRE2bDbVRNtRGU9MrGmKseHdbWRtNgXy/mzP2H8zVh4/CtgVvLdvCptoI+X4XigIrEm1QXRqmDXHLdqJMeU6CeOOqA8kIVShuYguBpqaLMUs43Yd+j05tON4rKxVIJD3BTiWa2qKsrIzNmzdz+OGHp6bl5uay//778/HHH3eKaNJ1Hb/fT2VlJS6XC1WVNleSXRchBOFwmIqKCvLy8naZMistFc8WQrA1GEdTk/+O0TfH22ZB7RaFVzDG52tqsIWgMzuzLAFbQ3H++u5KXvpyPTHTpi5iYFqCpnHAuGWiqwrZXp1hhVnkJaoMNK46kIxQfbW2BgWwEt14kB6h0hS6tVKBRNLb2WVE0+bNmwGaGSP27ds3Na8lYrEYsVgs9bm+vr7VZRVFoX///pSVlVFeXr6DLZZIdg7y8vLo169fTzej02ipeHYoZhGKm7g1ddvnmEmWR29WUHt0v5xmwgtFIRgz2FgbwbZtrEaWAp2JgLSIVGsoCEzLTjWgadWBpNnuuuowNWGDqGnhd2nYonGEysfWULzbKxVIJL2ZXUY0dZS7776bO+64I+Pl3W43I0eOJB6Pd2GrJJLegcvl2mUiTElaKp5t2I4RpaYAikLcsjGsbclHTQtqNxZedRGTNVUh6qMGRhMHy+7OBlMSfzZgWIJ11SH0wiy2JowuG1cdmFRawK+OGcOf3lrO4vIaGmImLlUly6tTlOWmNmL0SKUCiaQ3s8uIpuSb8JYtW+jfv39q+pYtW5g4cWKr6918881p9bbq6+sZNGhQm/tSVVU6I0skOymNR5wFPM4t0JUouGsJQAhURcGlbet+b1pQOym8qsI2aypDmHbzbrLuJGmKKQCPrmIkwly1YZPKYIwJJbktVh2YVFrAE+ftzytfr+fFxRvYVBdFQSBQGN/KOhLJ7swuI5qGDh1Kv379eOedd1Iiqb6+nk8//ZRLLrmk1fU8Hg8ej6fV+RKJZNeipeLZAY9GwK3TEDMRQpDjc6UEVUsFtXP9LkxbsH5rqFPLo+wISeGkqgpuBQYX+AlGTS6ZOpyT9hnYarRIVRVO3GcQx08cKCsVSCTbYacSTcFgkJUrV6Y+l5WV8fXXX1NQUMDgwYOZPXs2d955JyNHjkxZDpSUlKR5OUkkkt2bZD7PXa8tpbw6TFGWU6+tMNElBVCY5cG2RaqGW47PxdQ9ivh8TTW5fhfDCgKEYiZmo1IoPU2yDQpONNyja2h+lQkDczMSP7JSgUSyfXaqgr3vvfce06ZNazZ91qxZzJ07N2Vu+eijj1JbW8tPfvITHnroIUaNGpXxPrqj4J9EIul5WrIL6BNwI5r4NPXJciGEQnUonprmcal8v6GuWQ5TT6Mq4NWdvKRsj4vxA3L502kTZcRIslvQHc/vnUo0dQdSNEkkuw/bcwTfUBvmyY/LqYuYCVsBjcpgjOVbGnqdYALQVfDoGnl+pz5dS95SEsmuSnc8v3eq7jmJRCLpTFrrkkraCsx7di11EXObnxOwNRijNwZudFVJdTPuNTBPJnFLJF2AFE0SiUTSAi37OZmEYhY+l45lG2klUboLBfC5VOKWoE/AzZHj+3HE2L40xEzyfW7yAjKJWyLpKqRokkgkkhZo0c/JslNlR9y6hpkoj9LdyeA24HWpXDZtBL84aEg37lki2b2RokkikUhaoEU/J01FVRQsW6ApCgqgqQmPJJH4a7KdzhZUKjAoz4uuaew3THa/SSTdiSyeJpFIJC2Q9HOqDMZIjpcJeHQCHo2YaWHaNm7diThluXWyPDpuXcXv3uag3hUdZBawrjZKYZZHljeRSLoZKZokEomkBZJ+Trk+F+XVYUIxE9sWjodTorZcSa4XXVWImDbBmEnMtAknuuxgm0t3ZxM1bNZUhfhqXU0XbF0ikbSGFE0SiUTSCpNKC7jl6DGMK8mlPmqyviaMELDf0HwmDynA53aiS5ZlI7qgQG9bVDbE+NdH5dh277M+kEh2VWROk0QikbTBpNIC9h6U36Kf07LN9dz12lLKKoNEDYuQYaMrEDK6flhd1LT5fE0VyysapJO3RNJNSNEkkUgk26E1PydVVagJGxRme1i9NYTPpSGEQDHsbhlNt6U+xmerq6Vokki6Cdk9J5FIJB0kaUugKgq2AE0BlO6zH7AFvPzVBtlFJ5F0E1I0SSQSSQdJ2hLYQqAqYHVV5ncbLNlYxytfb+jenUokuylSNEkkEkkHSdoSBGMmAbdOPGF+2Z0YluDFxetltEki6QakaJJIJJIOkrQlyPO70TUFVYF4N9dWUYFN9VGWVzR0634lkt0RKZokEolkB0jaEkwqLSDLo2N2c6QJIGZY1IWNbt+vRLK7IUfPSSQSyQ4yqbQA24YVWxpQFSfiVBmMYVrCyXPCSRK3ukBPKQpUh+JsqA0DfTp/BxKJJIWMNEkkEskOYtuCJz8pJ2ba9MvxEjEcs8vGIkkAPpfa6QaYpoC4ZfPSYjmKTiLpamSkSSKRSHaQ5RUNrKwIIoDvNtRhtiBebOGUP+lsWaMqzt/n5TX88a0fOXpCf1AcO4TaiEG+z01eYJshZ9KkM9urgwJVdTFe+WYDG2ojGJZgn0G5TBiUhyls3vhuCzHDpCDgYWy/XBRNYUz/bPIDboQFP2yuB2CP/lmsq4pQ0RCjX66XI0b3RdflO7lk10OKJolEItlB6sIGdZE4W+qiWAI0VUEI0aw7riviQErivzHT5rEPynjy43IsW2ALgS3ApakUZrkZmO8DFKpDceoicRqiJuG41UzgLV5bC5Q328/LbAKcbkbn+JzpNgI7kfuuqQqaqlCY5ebSaSOYuX9pFxyxRNJzSNEkkUgkHcC2RSpqszUYozZsYArQVUfGdEX+UktYAuzEzuKmjW3bmLYj0DQFLMtmQ43FuuowKFAQcBOJmYQNm4705lkCrFYOzrQFbk2loiHGXa8tBZDCSbJLIUWTRCKRZEhSKH22upp3l1VQ0RAjblpYQhA1LGchIbC6uV2i0f8bl71LaZtkWEhAZUO8S9sSNiyyPRpR0+ahhSs5bdIg2VUn2WWQokkikUgyYHF5Nf/6qJxv19eyqS6KEJDt1RjcJ0DM2CaTLNHtpuC9jlDcwqtrbA3GeWvZFo4a37+nmySRdApS/kskEsl2WFxezV2vLeW79bU0RE1URcHnUokYNqsqgoCCR3dGxu3uggmcpHfDsrCFYHNdtKebI5F0GlI0SSQSSRvYtuBfH5VTGzYoyvYQMy08uopLU/G5NExbUBWK4XFpPd3UXoVpO0nq/XK9Pd0UiaTTkN1zEolE0gZJO4HibE+itpyTYA2OKHBrKvUR6cbdFAHk+FwcMbpvTzclY0zT5q1lW9hcF6U428OgAh9LNzWwpT5K3xwvEwbmMrpvDqra2W5bkp0FKZokEomkDerCBnHTwuvyIITjiWQJ0BPPTVVViFsCXVXwuzVipo2qCOLdnQ3ey1CAM/YbvNMkgc/7tJyHFq6koj6KZUPTCoIK4NFVxvTP4eajRpPjd1EbMqgKxQjGnC7bcQNypKjaxZGiSSKRSNog1+/CrWtEDYuARyPg1qmLGrhUBU1VsWyBEAKXpmIL6JPlxqurrKuJdGhI/67ChAE5XH34qJ5uRkbM+7Scu15bStSwWv3OBBA1bb5aV8sZj31CrtdFxLCImY77u6aC360zvCiLE/YewH7DChhVnC0F1C6GFE0SiUTSBqOKsxlRnMWSjXXk+lzELZu4aRMToGClEr8tG1yaQp7PxerKUK8VTApOtMylq1zwkyHsX9qHxxat4pPV1cS2Ex1zqY4PVbxJTT23CigqRsLlckgfP7cdN26nEAxmwhqhLcHUFMuG6kSBZAWn/p8toCFq8vW6Wr7fWMeAPB97Dsxj1kGlTCot6LoDkHQrUjRJJBJJIxqbViZLjexbms8362tZsrEeBfC5NOKWjWmJlGhyawojirMpqwpi9FbFBOiaQnG2J82xe8roYhaXV/Ont1bw1doaIgkBoSrg1lW8evJ4bSyhEPBoDC0MIIRgTVWYqGGDEPjdOnsNzGP2ESN3GqHw1rItVNRHU1ZW7UVTSaszqOBcQ/URg+831HLXa2FuOXrMTnM+JG0jRZNEIpEkSHoxrawIpkqNAGiKQjBuYtkCj64icERStlenj9/N+toIpi0IxQ1qwz2bFO53KQS8LnK9LoYXZzGmXxbF2T5CcRNNVeif52uxNtyk0gKeOG8/lm2p57v1dWypj9Ivx8f4gTmMKspmeWUDSzY4tebGleQwul8OAMs217NkY2L6TpjTs7kuir0D3lp2k/wnVXG2FTEsRmRlURWK88RH5ew9KH+nOi+SlpGiSSKRSNjmxVQbNvC5NeojBhHDwmySERwxbIqzPQztEyDg0VAUBbeusqIyxMqKnu2W239oPrMPH0V+wN2hfBpVVRjbP5ex/XObzWt1ekkuY0uaT99Z6JfrZUcMtpomjKemC6esTFGWhxUVQZZXNKSEpmTnZecY1iCRSCRdSGMvptI+frYGY0QMu5lgSlLREKM2EkdRHFFSmOVxCtkqCj0VS/DoKrcdO44Dhxcyut/OFe3pSY4Y3Zdcb+fHD1QFXKqK16URNy3qejgCKekcpGiSSCS7PY29mMJxi/qIgbmdkFHZ1hB2IhGmJhzHFjCyb4BsX/cH8FUFJg/Jl5GMDqDrKlcd0Xmj/CzhBK6yvToBjzPq0q1r5PpdnbYPSc8hRZNEItntqQ0ZNEQNoqbF5vooEaO1TpdtGJZgazCGEIKtwTguTaVPlpcRRVkp88vuYkC+j6uPGCWjSx1k1oFDOW6vkk7bnselMSg/AEBlMMbI4ixGFWd32vYlPYfMaZJIJLs8jUfE5fpdqQfY8ooGPltdzX++2UhFQ4wt9VHiVmbJLQJniHk4bpHrc+HWVWKGRb7fTZ8sNxUN8S48om34XRq/nDpcjs7aQf58xt5MLs3nvjeX0RDdMWfSgEuluiHMD5viIBRUFX736vcU5/kZ3z+XguyO5ZxJeh4pmiQSyS5N4xFxcdPpKikIuAHB+poIm+qi2LZAUdhul1xTTFuw18A8zjpwME9+vJYlG+vwuzX65ni7RTS5VIWCLDefra7mjMmD5UN4Bzn7oCGcsd9gHvlgFS9+sY611REy1NBpVIYMKkPJT4IVW0Ks2OJMUBXom+Nl8pAC6eG0EyJFk0Qi2SWxbcErX2/g4fdWETEsBuT58Lk8VDZE+XxNNUIIfC4NVVHwutWUN1Gm5Plc/H3mJMaUOEnXqqJw12tLKa8O0yfg7roDa0S2T2dAnk+OzupEdF3l8mkjuXTqCF76aj1/fmcloZhBOGYSMXd8aKQtYFNdlHeXbmZtVZBfHztOCqedCJnTJJFIdilsW/DSl+s567FP+PW/v2dNVYiaUJw1VSHqowZbg3E0VUFRIBS38OgqLs0Z5ZQpqgLX/XQPxg3MTUV3JpUWcMvRYxhXksvWYPd0zRVmeRyjTTk6q9NRVYWTJw3i4qnDEiPgOtdLIhi3+Xp9PXf8ewl2LzZDlaQjI00SiWSno6UcJVVVUq7Wi8trMCwLywZdBUVRaIia/Li5AVsIPLqGCcRNCyEEoKAq2+x6tmfbc+I+AzjrwNJm0yeVFrD3oHz+unAFf3prRYcNEzNlbXUYl6bK0Vk7iGnavLVsC5tro5i2TZZXR1dVFAWe/3wtoZhJV9Vf/nZjPTe8+A1/OGVixuvYtuCHTXW8u6yCUNTAFKCiEDFMCrM89M31kuN10SfgIS/gkvlTnYgUTRKJZKeipRylEcVZ7D+sgBe+WMfyLUEETtdbKO6YUwrDwu/WiJk2pm3jc2loiSFupi1waY7Hkq6CYTu1xBTRcqX7A4cVcN9Je7XaPlVV6J/rQ1XoUD5Me4gaNsu3NHBAojispP3M+7SchxaupKIhhtHoC9NUQHT9dwjw8pcbOHXSIPYb1me7yy4ur+aO/yzhh00NbebgKYDXpdI3xytr4HUiUjRJJJJeSUvRpK/W1aRcu4uzPXhdHqKGxfcbavlgRSUuzel282oaIJzitCrYQhA1bTyaimHZGJZAVRyBYwmBEAJFUZwIVNxK1SHTFZyuGctG4BSivXbGHm2+tdu2wOdW0TQFq5O7dFrCtARi+w4Jux2tjZhctrme7zY4ZWJWbw0x/7vNGJbdLJ/N6sZzagm4b8Eynrv4oDavrcXl1Vz1f1+xvja63W06pVxsttRHWVxezfqa1mvgmabNgh828/2GOnxujeljihnbL1dGp1pAiiaJRNLr+Lysmr8tXMmaqhCWLcj2uhheFKAmHKc2bDCkjz/lxh3w6BQKD+trInhdKrYg4ZOkoKkKlu2IJ8sWKE79XeKWjapAjlfHsgUR08atqVhCkO118lcMy0ZRFOKWwOvS2GtQLrMPH9Xm23qye/CbdTWdngPTGgJYtrlhl08ET4qgmlCc2ohBvs9Njl8HAXURY9s0n84Pm+p5+csNbKqPogCexIjJ+qjByoogkbjV5V2n7WX11lCr32GyO+7657/JSDA1JmLYbK6L0hA1ufmlb5m+RzETBuUxY0w/VFXh/reWM2dRGaH4tg7IP721gnH9s7nj+PEyOtUEKZokEkmvwbYFf3p7OXMXrSFqWmiqgqYohOMmW4POjX9YUVZKMCUxbYGqKhimEzGyBOiqkuqis4VA2ALLttFVFSEENgoleT7cmsra6jANUQNVUSgIeNhzQC6H7FGIEM5+kgVqtxcFuPml7yivCiOEQFO7L1qxNRTnhcXr+dXRY7tnh11MMsdoU20EyxZUB+N8tLqKjXURglGncLKWGLEowPk+RaJYriAleN2aSpZXw/YIPi1rSHW/9cr4iVBSyfxJgVgbMviivIr5321m6eaGDtc1tATUR03qoybLt5QB4NUVdFUhGG9+kQrg+00NXPCvz3ls1mQpnBohRZNEIukVLC6v5v43l/PJ6qpUKQohQNUVInEbgcCwBJUNUfrmeNMefC5VRVMVTMvG73JylzTFGRUXcEPYsDAtQcwU+N0aew7MAwTVCSfw4mxHKE0bU8x+QwvanThr24K5i9awoSbifBYCu5u7zF78Yj03zRiNrqupNrVm6Lm9aY2Pvel2RhRmsXJrsMXP2T4n8tMQNVvdftP1k/tL7ueFL9bzn282UhOOp+UYNaPRPAVw6woRo1FOEgJVddpSHTKwevkINY+usjUY44XFa3n5y42UbQ1RHYoR7aKIpbPdtrddEza5/d/f8+/Lp8iuugRSNEkkkh5ncXk1d776A8s2NaSehQIngmTGLXRVSUQRBMGoRShmkuXZdvsKeDS8ukaDKeiX42VDbSTV5aYl1vW6NAbm+7jk0GEcP3Eg0LZYaA/LKxpYsrEe2xaOYBLbexx1PjURg4ffX8kV00e1aehZHTLanDaiOCuVNNx0O6btdFu6NBVdVdI+G5ZNQ9QEnLpruT53s+03Xb9xEv+nq6v5rKyKLfWxdp87AcSaiAsBxC2Bz6USNcy0bfZG+VQTjnH9898QS1SJ7olrqCV+2NTAD5vrGF+S19NN6RVI0SSRSHoU2xb866NyKhviWCI9egDbxJOCM6otbtnETQs86bcvJ59JI27aDMr3URmME4yaGLaNrirsOySvWU5SZ+UA1YUNYoaTJ2NZoscedk9+vJaCgIcXF69PS5ZPGnoCjCjOYmC+v8VpUcNiycY67nptKSdNGpi2nZipsqKigVhCjJbk+9haH01E9RQnWpT4/uojBm5d5fM1wdT2s72utPVH9cvGo6ksLq/m7aVbyPVqVIeMTjt3iqJg2TaW1fsjJG5NRVUgajZPSO9pLAHvLq2QoimBFE0SiaRHWV7RwMqKINlenY11254YTZ8dTu4KKIpTINeja3hdThX5ymCMvjleTpo0kE9XVzvb82hkeXT653o5adIAjp84sMu6GHL9LjwuDcsWzWwKupOtDTF+99pSAl6dsX2ziZg2dZE4m+tjaKqSKC4cozjbkzL5TE7rm+Ml4NHxuzXWVIV4aOFKPLrGkD5+AMq2hrAFZHt0IobF2qowmqqQ5daoj5pgK+R6dZREDtrG2mhq+5UNURSU1PpR02ZjbYSx/XMwLSf6FIonctNobvXQMQQiEa1RErlOO0LArbXbNT4TfC4VXVEId8G2O4tIvKtcqnY+pGiSSCQ9Sm0ir6ilYd8tYdmQ53dTHzXZGozh1jXGl+Tyi0SX0hmTB3dat1umjCrOpn+ul9VbQ9tfuAuxcVzOQ3GLrQ0xXJqaGi2oKQouXaU+YrC+JkwobuLWnPynUGxbl6eiKGR5dDbUBtmjbzaKohCMmqnlVUVBV9XEZ51UZkyiW1JXSJuvaSoNUSuRd+Ss79ZUQjGLrcEYobiJV9eIGrYjijvpXDgC2xkQoKkKdpMcqPboE79LJd/vIke4CLhUGuImWxvineLhFDF6t1+EAowfkNvTzeg1ZCSavv3224w3uOeee3a4MRKJZPdicXk1j/xvFZvro20n/TZCAaqCUf5x9mSCcbOZMFJVpYeG3veuMIEtIGbaeHXVGVEmBEbcES/lVWEsIQi4FVyaStyyMRoN9VMVp6tNTRTaMmy7kZVD48iNSI0wFIJE95ySNl9TVWzhdK8m19dUhbhlEzWc7Xp1hYhhbxNgnYAQzn401blmGru9twefS2VAgQ/DFMTjFhvqosR7YTdaV1GY5WbG2H493YxeQ0aiaeLEiSiKkig30JzkPEVRsCwZxpNIJOm0ZVRZHYylPdTaQgF8Lo2qkMHa2jBHje/f9Y3PgOUVDWyqi+HWHF+n3kTUTI9kCBz3c8MSBGMmfreOqjjiKYkthCOcEqu6VDXlcK4r26I4SYEEzmdV2SagkvMt29mWwrb1k9O8rkQuj2Fj7mDApfH14wglx66iIeYMJBjTPxuBwsqKIOEm3U2a4rS3cRu0Rsama6siDMjzEjctDNPuFpfw3oBbU5h9xKjUiExJhqKprKysq9shkUh2AVoTR01HcjU2qizO8bKlIYZli+0+jNyagkd3vGU217XP5K8rSSaCKygo9FwieKZETTuVIxaMmeT7XQQSifVCOGKqMMtNKPH/gEcj4NZpiJmoioppOyPgLCHQcQQRSmKEI6TNN02bbK+zVHL9uOVMK8zysKU+RmUwhorTfddU5G2PZORISagmRXESq726itet0zfbw5kHDGJ8SR71EZPPy6t4a8kWNtVFiZo2cdNGUZxr16WC161SEPBQnO1hbVWY2nAc07JZUxXebaJLCk6EafYRo5i5f/Mai7szGYmm0lJ50iQSSds0Hp7eEDXQVIV8v/PgNW2RVvbkq3W1VAVjDCvKckbGKUoi0dbGaOXJlHzzN20notEv19vNR9g6yURwpb19Pz2EgLSE63DcpCYUx6OrVAZj5PndqdFz5VVhAh6dHK9OQ9SkIebkNg3M97GpLkIwYQmBohBKdP+5NIXCbA8bE+7VRdle3Joz+i65fr7fzZb6KKZlg0jaBrRPMGmNE7xFUlRrxCyLhphJzHSSwR98e2XKFqE6FAecHpKkM3gySuXRVCwbakJxAm6N+qiBYYtdXixluTVK8n0M7eNnSGEWew7MZcbYfjLC1AIdTgT/4YcfWLt2LfF4PG36cccdt8ONkkgkOxeLy6u567WlbKmPEjWsRHeLTXlVGEVxhpwnIxkBj05RlvPArGyIMqRPVqIOnEqOVyUStwi38PD0uTQ0VSEcMynO9nDE6L7dfZitMqo4m3ElOWyuj3TKSK3uwCYhOnCS61dUBBlc4E9Lqgd4aOFK1tdGUnYCuqqQ43MhhCDLo2PZBqYtsG0nkVtTFLK9Oj6Xzn5DChCNTEQLszyEYibhuMXqyhAkonKZnC5VAZeqoGsKUcPpImsamYxZgphlOvlTqoJhWWypd5zlvS4Vl+Z0F5oJIaTgbNOpPwgxyyZb1zBt4USiEnlWuzJel8q9J+/JUeP7SwPLDGi3aFq9ejUnnHAC3333XVqeU7Ksgcxpkkh2L5I+S1vqo9RHDCzb6WbRNQXDMrEFlFWGyPbq5PncALg1DZeqEoxagEh1/fh0Fb9HxxYG0UZPRF1x7jHJKMWl00b0+Ftw067IXxw4hB+3NDhD83tZ0kvTYfya4iSKKwp4dZU+WR7ips2J+wzgnAOHoOsqn5dV89TH5di2oF+OxxmJpyiYpoXXrXPwyEIWrdiKV1fJ8blQE75INWEDn1vngilDmpmIbqgN88RHa9gaNJy6f0KwYkswrZ1J0dlYTClAlkfHtgXBDIe/26KR5QAC0xJEDNvpPm309QhEKvEdIGLaZLn1XlmfrrNRgH1L86VgagftFk1XXXUVQ4cO5Z133mHo0KF89tlnVFVVce211/KHP/yhK9ookUh6MUmfpahhYdngc2sAxBoNITdtwZqtYfYa5EbBcfDO8uqJUhk2A/P9rKhoSLl4K6qCX1OIJUZXoTijrYqzPVw6bUSbeRYt5VW1tyTK9tZvyXHbcdIewvzvNvPJ6q07nNjcmaQJJjWRsG0LLBsMS7C1IYZhC578uJxv19cxeWg+j7y3ii31sZSYcGq5OVGkmGUz/7tNeHStWS3Aomwv5dVh/vfj1pQ31uh+Odi2YN6za6mLmJTkeTEsm9VbQ2ltE5Dydmp6/sJxM+PSNE27Hy0BrkTekgKoibqALYki2xIIIXp92ZXOYEC+l6uPGCUFUztot2j6+OOPeffddyksLERVVVRV5Sc/+Ql33303V155JV999VVXtFMikfRS6sJO10vUsHHrKjHTJmJYzR461aE4m+si9M/1oSgKRVlu6iMGG+ui9PG7Kcn1UdEQJRgzURWF4mwPQ/r46ZfrIz/gZsLAXGaMaTvPonUxU5pR0dFM1k92RTZ23E46aa+vCXPCPgNYXx1iTXVkx07sDtLaaETLBpRt3WKOUFFRVEGuT2dxeTVvLtmMkehug20jpOOmoD7idH+ZQjCmX06z4snOd+thRUWQ5RUNKfuH5RUNfLu+loaoSWUwhmkLYgmPIi0xMk/gRMCaNtylgWG1z44grWxKwg4hOU1tdHYccbZtaRunuO2uLplG9g1wz4l7ymK87aTd8W3LssjOdoowFhYWsnHjRsBJFv/xxx87t3Xt5Pbbb0dRlLS/0aNH92ibJJJdnVy/K5E/YhOMmQRjZotv6QJYWRGkNmIghKA2YpDtdbpBVlaGWL01iGkLxpfkctaBpQwtzKIyaLC4vIb3l29lwfdb+GZDbavtSIqZ7zfUkePVGZjvJ8erp8qCLC6vbvM4Mlk/2RVZGzYY0sdPwKOjqQoBj05pgZ/acJxH3luFqqp4tJ57e3drCoPytyXKe/T0tlhiW96V36VhJfKT+gTcKYduyyaVo6QqiQgQjviwhNPdpbbyBPG6NOKmRV3YSE37bHU1m+qihOMWuqriahTdsBp5QNktjKKMW0mrhMzPQeNL0EkyF6l/t2af03j5XRVdgb0H5jL/ikOkYOoA7Y40jR8/nm+++YahQ4ey//77c9999+F2u3n00UcZNmxYV7SxXYwbN46333479VnXpem5RNIV2LZg2ZZ6vllXS9S0MvIniluCFZvryfa6qIkY5PtdDCvKwrYFobiZGp31/vJKTEs0i+Tc9dpSbjl6TLObfVMxk4x+JMuClFeHeeKjcvYelN9iV0Sm6/umaqysCFKc7WkxwpJ00i4MuHvMrymZBL25LproilIIuHU8mk0obqUKwQpAV8GwBbqqMDDPTzhuE4qbjl1AYih+YzdIVVGcri7VidSEYyYFfjehmIVh27hUlYDHKW3j1jVy/S4ATNPmP99sxLIFLl1xxI+qoihWSrwlT1fytO5oMn3TSJvjI+VE2npZylm3keXWGNk3i18dM7bHcwJ3VtqtKH71q18RCjmlAn7zm99wzDHHMGXKFPr06cOzzz7b6Q1sL7qu06+fdC+VSNrL9nJ5Gs9fVx3mqU/KWbbZKcDanmdQfczC69bI97tSZToAcnwu+mbbfFZeg4LC5CH5KbPE7YmfZF5Va2Kmpe6ixmS6/pKN9cRNC6/L0+KxqYqCadlUBGM9Gq1QACOZkK8qRBO5YgG3k+icdF/XVJVsr87APD95fhc14bhTCqXR8zRpXAyO8LAsgZ0wg6xoiFHZECdqWontOQJN1xT2LS1gVHE2i8ur+cs7K/luQx22EITiFnHLRtfUFoVRW2KpPWKn6aIKTlQtbtmpqNPuRIHfxZSRRWkjIyXtJ2PRtO+++3LBBRdw5plnkpPj3HRGjBjBsmXLqK6uJj8/v9nNpidYsWIFJSUleL1eDjzwQO6++24GDx7c6vKxWIxYLJb6XF9f3x3NlEh6jGSEaMkG51ofV5JDKGbx5Cet5/I0zvWpbIiyNRhvtyhQGzlJ66rKoHx/s3tGOG4jbGdEUzhukeXZdotqS/zUhY02xYzXpbE1GEvrLmpMpusDuHUnkhLwNL992kKgKGRcEqYrEGwTF4MLfOR43alac3bCy8jn0gjFTAbkeRnSJ5D6HvRE7lKyHJqTC+QUSU5+dvLyFXQV6iJO7o+aqPGmoFAdjuPSVPYbVpByfd9cF0Ug8CRy3gxLEG9lpHVnnzlNISHQBGHD2insIDoLFThkVCEXTBlGYbanW+ow7upkLJr22msvbrjhBq699lpOOukkzjvvPA499FAACgp6h2rdf//9mTt3LnvssQebNm3ijjvuYMqUKXz//fepPKym3H333dxxxx3d3FKJpGdYXF7Nn95awbfra4kaFuD43miKQo5PZ1C+v1l3WNLksDZs4HOrHRJMjUmOpvO6tGbzjMTwKIFIq4WWpDXxk+t3tSlmmnYXNSXT9ccNyGFEcRZLNtbhd2tpoi/ppB3w6NRFzDbPQVeiq1CU5aaiIYbPpZPnd5Hry0nrQhPCZtmWYJq4qw07hXwNy/ExSh5ZkzxppxyKbZO8dhBODpKznkWuT8fv1vl0VRWfrKpKeXeZliCZXt2dusUWYFo2mqago+J2qQRju36iN5AS8AcNL5RiqZPIuFPz8ccfZ/Pmzfztb39j7dq1HHbYYYwYMYLf/e53bNiwoSvbmDFHHXUUp5xyCnvuuSczZszg9ddfp7a2lueee67VdW6++Wbq6upSf+vWrevGFksk3cfi8mpufuk7Pl9TTdyycesauiqIGBbBmOMIbdiiWWLzQwtXUhs2KO3jZ111pMMPm2SUyevSyPLoCdGWjiuRWayQXgstSWviZ1RxNiOKs6gMxpol+QohqAzGGFmcxajill+eMl1/dN8cZh1USq7PRXl1mFAi6T0UMymvDpPnd3PQ8D7tOi+dTfLRWJTtGEkmu9eyvDr5fqckytZQnBFFWXh0lSWb6lm5pYFlm+upixioirONZEmUlrBsZ77XpeFz6wQ8OlkeDbeu4tY1Bub5+H5jPYvX1lAbNogYjsFk4/Yl6Yx8eZcGbt1JWG+67WTNvLgpnBeEREL77oAQsLEuwvKKhp5uyi5DuzLB/H4/55xzDu+99x7Lly/n9NNP5+9//ztDhgzh6KOP5qWXXuqqdnaIvLw8Ro0axcqVK1tdxuPxkJOTk/Ynkexq2LZg7qI1bKiJON0vpu04MxvbDACjps36mvA2Q8FEYvPWYJwsj04oMTKuoyQ9ePYenMu4kpwWBYrfraKoTvKy350eiWpL/Kiq0qaYyfW5+MVBpa2+bbdn/UmlBdxy9BjGleRSHzVZXxOmPmoyviSXW44ew1kHlLZ/WHInYtrg0VVO3GcgOT692fH8uKWBmrDBpvooG2ojVDbEKK+JEIpbGJbtCOY+/mbnSlWcUXiq6vw7bonUNRGOW8Qsga6qzr6EI3BrQnFsW+B36/hdesJEMr29yc+a0lxQbQ9NdbobbQGG2bzcSVPXcMcKw273fnZWbCBu2q12S0vajyK2N/ZyOwghePHFF7n44oupra3tVY7gwWCQwYMHc/vtt3PllVdmtE59fT25ubnU1dVJASXZ6Ukmb3+3vo77Fixja0PbXWseXWXioLxULlFVMMaSTfWMK8mhNmywpirc4bZ4dJXSPn7uPnECAHe9tpS6iEFRlgevy+kaqwzGUhEJyxbN5uX6XC2OnkvSks/SyOKsjJNf27N+a4nzyzbXc+ajn1Ddgw+qbI9GYZaHkjwviqJSHYoTNx1RVBM2UBSIGzZCCDRNJZyoGecE+pxoTLKQrYojKocXZQFQtjWUSv5PWREkfJCcunMqwwoD1MdMKuqjeHQNTyKz3LCcUZJmI3WTLOWiJVy520oHUxr9X1FgcIGXLfVxTFtkVPAZnNwryxa4NKXHRjh2J338buZdtH+LAyB2Nbrj+b1D4/Hfe+895syZw4svvoiu61x44YWd1a4Ocd1113HsscdSWlrKxo0bue2229A0jTPOOKNH2yWRdDe2LXjpq/U89Uk5FfUx6qMGwdj2X2ji5raCpgGPU+ZCAeojJpvrox1uT8CtMX10MeccPCQlPm45ekxKoGwNxnDrWqruGdDqvLbEz6TSAvYelN9hR/D2rJ90um7KqOJsBvfxUx2uy2ifXUEwZhGKhdlQF6E4y8vp+w0i4NF4+L3VjnO7ENi2U1g3FRVTthk9JhPandIowvFOsgV5fnea4MFZHEVxRI9pCQzbpj5qMrjAR03IETTuRBehS3MKM9dFt0UsXZqCYYtU4dzWSPpJBdwqXt3JJ6toMIhbjgBq1q5WSHqI7Q6CCRwxO6Iwq6ebscvQbtG0fv165s6dy9y5c1m9ejVTpkzhoYce4pRTTsHn83VFG9vVtjPOOIOqqiqKior4yU9+wieffEJRUVGPtksi6U4Wl1dzx39+YMnGunb70QigvCrEproouup0sdgC1laHM34oQdIryOni65vj5ZojRqZKaiTZnkDpqPhpTcxkyo6u31twumYE62sj/HXhSlyaUwzZo6uYhpXwLBJYtkWiqsq2dRP/FkKgJuZtDcXI9emJ0XM4YgmwhHActhNCy7Yhy6tx8r6D2FgXZWswliqPoyk0u462Df931k9GkTRVcewNSESjhOMnlcyh8rs0KoIxQBA1RMZ5SruHVNqG162ycmtwl7imewMZi6bnnnuOf/7zn7zzzjsUFxcza9YszjvvPEaMGNGV7WsXzzzzTE83QSLpURaXV3PTi9+yqjKEEM0LtWaCqoBhWQRjTpSpX66HmpCRsWhSIPFw09hrYB6zjxjZanSoLYGyM4kX07R5a9kWNtdFsWzB5rqOR+U6g6bfVNSwMUw7ZWwJ20qjOA7ZzbeRNIdMunXHDItgzEJTHA8oVVXw6ipx08YS24rgujWVM/Yr5bg9S/jP1xsJRk1sIYgaFkYiYtXUeDIlm4ST1N0/x0dd1CAYNVGEsy9NU8nx6RQEPNRHDBqiJkoiEtZVQqgjv5/uoLUSOS0tp6mqzGnqRDIWTWeddRZHH300L7/8Mj/72c9QW/PPl0gkPUIy2Xt9dSRR/gJIvPm3h2gj4z+B88DN87vYXB9rfaUEBw7N5/h9BqIqCuMG5DC6b84uP9R53qflPLRwJVuDcae+WQvFZnuKlsRJOO5009rbSWdtPNcSEDFs6iJxQMHrUvC6tJQtRHJTmurYRbzy1Qbe+mEz62si1EUNTMsRSi2dlqatMCxYW+PU7fPoCnk+F/l+D7oGoZjF6soGDAuy3CqmZaeu9a7obesKMdYZQsyrq0QyuMi0hJ1Ia1YbkvaTsWhav349xcXFXdkWiUSyAyyvaGDJxvqEGSEkekx2mJqwQYE/s1vF8fsM5LTJrZvJ7mrM+7Scu15bimHZeHUNl6YQjluY7VWqXURT4bMj2AKqQnFyfS7cuorfpbF6ayhtu5YNuq6wZGMdiqJQkufDlUi87si1qCoKfrdOWZVThWJgvg8UBY+uEEp0HSuddJ23RFds1q2rqKqCbdvETZESUGqTLtK2yEQwASAEwwoDrVptSNpPxqKpsWBasWIFCxcupKKiArvJzeHWW2/tvNZJJJKMqQsbxAwrVburM6Md1WGz2RuyCqlcGAH43RoTBuZ23k57OaZp89DClRiWTbZHT5V82VUCa2rC44jEsP2ARyPX52JonwDLK4KsqA01WydpXeHWFFQEm2ojqIoTLYoaFmEjs4vSpTqJ3XHLZmNdNHVOq0NxhHA8mRRFI2aapDLIe3GykqqAz6USMwWj+2dz5/HjaYiafL6mmic+Lqchajh2DfHOHX3ud+tcOn34Lh/t7U7anQj+j3/8g0suuYTCwkL69euX5oirKIoUTRJJD5Hrd+FxaQjR3K+mM1BVEiVOEiSGiquKk3MyaXA+o/vuHDlIncFby7awNRjHq2spwSSAWAtO5jsjSf+uZDRncH6AHJ/O2uoQVcG2u2oNS+DxaITijsO6qihoauYdU0lPL8sWxG2bLI+OpipEDTuRfO5EoZKlebREmKYrrvsdRU2UcXFpGkI4Iwt1TeXA4YXkB9y88vVGQlGTSAtmrzuCrsL1R+7B5CE9a7a6q9Fu0XTnnXdy1113ceONN3ZFeyQSSQcZVZzN2P7ZlFc3jwB0BkqiWyRq2qg47t3OKCcYkO9n9hEjd6s32s11UWzhDHcH50HvmCf2bLvaS/IbEzi5MlHTTn22E0nYOV6dfrkeLFuwqT663a4+gTNKTohG3krtvDQaL68gEqJL4HFpxEwbr66iq2qia1RFVRTChuXYIzRpX0cCUU49veTeSXUxqqoTRTNtyPHqGLbAtJx6ek334TirJxLmLZssr4YCqcTsEYVZDMrzsbYqlLHgy+RYdFXh1mPGcvYBQzI/YElGtFs01dTUcMopp3RFWyQSyQ6gqgpDiwJd99AWgiyvC6/Lxu/WUQCPS2N8SQ6zGvkv7co0NrQ0LCfqETUsVFV16qv1xlBHBiTzgqIt9OnqqkK+30VNOE5lQ4xMAyLJUW0x08Zu53kRYptTPWyrHweOgNsajBMxLFQck82wYYFwRE5BlpuIYREzLCzAtDogmHB8oQqz3PTJchMzBTHTBgQBt0ZDzKS8KkKfgJvSwgDhuEVNOM6GhLN6Ek11cphipo1LUyjK8iKA6nCcJz5ew7tLK/hxS0O7utJbOpbGQirg1rj5qDGcdWBpO49akgntdgQ///zzmTx5Mr/85S+7qk09inQEl+ysLC6v5qr/+4r1tV0z3N2lKfxkRCGXThtOttfVIfPInZnGbuF1kTh14TihuN2bU2kyIpME5KRbeHdF0RqLAKXRZ01VcOsqQjj5Tq21R1Ug2+vCmxAsDVFjhxLhVcWxUmjsZ2VYNpqiUBBwMzDfT57fhS0EX6ypThnJJqNliuLkaTmliVz43Spb6mOpEYwtRalaoul5Sf5bU516jQUBN385Y2/2H7Z7dsn1SkfwESNG8Otf/5pPPvmECRMm4HKlD2XMtFyJRCLpPGxb8Ke3lu+Qa3dbuDWVg4b34R9n74uu7xp2I7YtWLalniUb6gEY2y8HoQq+W1/Hkg31RA0Lr1tjQv9cNF1h3ifl1EVMfC6VhqiJ2cUjt7qLTIJATvdUlzclbX+Q8PzSSEW3NNXpQgzFtnWDtpQppSpQFzGoA/rneAnHTawdUE12IgqnNvq+A24Vy4bKYIyacJyiLDd+j4vsVJedY9bp0VU0VSFi2BiGjWnHiZmqE6nVnahVpqiqYyEi2HaOVAXyfS6Kcrz85rjxTB6660d8e5J2R5qGDh3a+sYUhdWrV+9wo3oSGWmS7Cw07iqqDEa58cXvCMesTo98uDSFoYUB7j5xwk7fBZc8Z5+trualr9azYkuQeKKOmt2kS6gpCjCyyEdN2KQ2Ydho2+3v+tlZac+Q+KbrNT2vTnZS2wPf1ER0xhTbuutU1Vk3w0F4XUKyvbqqIBDNxKRHV8j2uAjFTGfwBAoKgrglEg7rzsjAbI+OLQQNGZQ3SqInIrqNu4EDbo3DRhfvNl3kbdErI01lZWVd0Q6JRJIByYf+p6ur+O+3m6hsiBGJm9RHzBbzUXYUv0tl0pB8Zh8+qtfekFsqnAukTRtRmMV/vt3Ii4vXU1YVYkt9tN2REwEsr4x0/gH0QpoKmWTEJNIOtZLssfW7NfSEGbJp28QtR2mW9vGja870LI9OOG6xsiKIoghUVIYVB7AsQXlVGFVRiJlOzlhP59knz0tr+WtO/lMcl6aQ43Lhd2vURw3CcRNF2ZbrFYmb7ToWhW3CPklBwMX/+9kYTtx74G7RRd4b2KGCvRKJpPtI5tR8VlZFRUMs7ebZmdEOr+6ULzl4ZB+OnlDC6H6919W7cZ5R3LRw6xoFATcgqA4ZxBMP2mDMpD5qYttOHszuEh3qKM1EEzhipx0kI1OqoqQiJJqqEU+Ucwl4dPoEPKnlLVugqQpeXUt4PamgOUIhZlppJWC6m46MvjMsQTBqUhuOp34/aiPn8ng71Z+eGKVpJfKfdFUhx+vi/eVbGVoY6LUvNbsaGYmma665ht/+9rcEAgGuueaaNpe9//77O6VhEolkG4vLq7nz1aWsqwlRHTIc7xw67yGS3JbfrfGb48Zx4j7d/+baVsSoJhSnNmKQ73OT49dBwBdravi/z9YSM22Ksz14XR4qG6J8vqYagBHFWWR7XSzfUk848YTy6spOO8KtO2n6PLcbJ9Fkuo3E8kI4gkvgdLPZiU65mpDhCCrNMfyKxC0Qzig1IYRjJeDSnOhSDwom6Pi+TdsRiNgiEWXq+LaMRCkaIDESz40tBJ+XVbFiSwO/OX5cmidTS7+n5G+66bwRhVms3Bps9rk2ZFATiTulbALu3WbQR1tkJJq++uorDMNI/bs1lPYacUgkku2STPJeuqk+rQuuswWTS1P4f0eN4eR9B3XKdhsnWttC4HWprNkaJhI3KcjyMLpvNj9uaaAqGKc2EmdTbZTKYLxZxGh9TYStwRiGJVKGhqridI9YNuT5dfIDbvwKbA3G0VSnEG1lQxQFBcveFvWIS8HUbSRPdcuJzoLy6jBrq8MoihONUhCpXCUFWF0ZcmrKdWFB3q4mGVXqrLp4yc0YlmBj3TaD0YqGGLOf+ZoHTtubyUMLWozAFmd7mD66mCyvzsJlFayqDKUisYZl49JU9IQTu2HZWLagPmJi2Haqft2YfjlcNm1EKtk8Kb7aEleNi1kX53goLfATilk77cjbdieC7+rIRHBJb+OlL9dx80vfJ3xiOh9NcbpKrj9yjw6Z4TV+a832bYsCvfjVepZtakglWmdCwK0xql82ccNiZWUIW4hUPowCKddkTXUeyl5dA8XpqhiY72dtdSi1fMy0E+aCjo+PkxMiu+Z2Fnp5ZZReh6bAyL7ZnH1gKS8uXk9t2KA420PMsllbFaIhaiESaeluXaW0jx+3rrJ8cwNxy8ajq/TP87GxJkLUsFoUepoCOT4X183Yg9H9svnXR+V8u76WrcF4QngpFGZ52HNgHrMOKmXZ5oZUMWvLFtiJRPg8v4vibC8jirOYdVBpp3UtdsfzW4qmJkjRJOlN2LbgrMc+4aPV1V2yfa9L5YChfbhs+vAOlVto6l3UEDUxbUEk3vFRfB7dKdIaNSzipg2KQk6iJEfSZVpLeAbpmpPXETEsPAlPHp+ugqIQjJmJYd2q82+lc+vxSTofBcegsidHx+3MeHWFbK+bLI/G0MIAdVGTFVsaMC3HuT4YtxBC4NYU3LqGpirEDBuvy3GCd1zPnZF+raEpTjd+v1wv4bhFbdjAtgW6pmLaAk2FXJ8LVVGobIhhCYFLVRyT08RmFcUZCKAqCrk+F7ccPaZThFOvHD0H8MUXX/Dcc8+xdu1a4vF42ryXXnqpUxomkezu2LZgwQ+b+WZDXZds3+fS+O3PO56/tLi8mrteW0pt2MDrUqkOxdNujB0lZgos28Tn0ohhg3BKVli2cEZkKQq2EKmRSJYtcGtqWl0yEm+0yaPSEt0OnWnSqHZgRJmkbQRSMO0IhiXYGoyR7fETjFmsrnQsNfxuzYmyJmIkyVI0ZlyQ5XHc/REQT0Rn20RAMG6xviZClkdDCPAntuEWgohpY5g2W0NxBJDv0wnG7GY2DRtroxw4rIB1NRGe+KicvQfl7xRdde12qXvmmWc46KCDWLp0KS+//DKGYbBkyRLeffddcnNzu6KNEslug20LfthUx71vLOWoB9/nlhe/JdQOH5dMUBXI9mj86hgnf6kjNyrbFvzro3JqwwaaCks3NRAxdlwwJUmG8sFJJLbEtryWpKGkqijOPNt2CrYi8LicGl8x0yLbq6WMBj0JQ05VVfDpGjt6b9YVp+6YgoLW++/zPcLOcFp2te9OTRTRXlcb4bv1tdSGDeKWTTBmOsn4yR+RcASMlchfaoiZRE0nOrw9zWqR+E3agmDMxq2rjeoLKrg11Rmpmhg8YNhgCdspaq04y6iK46heFYpTlOVhRUWQ5RUNXXRWOpd2R5p+97vf8ac//YnLLruM7OxsHnzwQYYOHcrFF19M//79u6KNEkmvpGkSZI5Xpz5qOiO8fDoo0BAx0xIeG69T2RDlk7IqNtZEGJDvY2xJDk98VM6KymCnuy+7NQW/W0NTVYYW+rl+xmgmDylg2eb6Nv2NWhtxUx2Os2JLAwJYWRHq9NwTAUQbdfEJe5uAAkf8uHWn3pthCzCdm3K+z8W6WsdLKdvrItujE6oMEjVtXKqC26URbxTKcKugaaoTxUKQ5dUThWGhPmq2GEUKeDSKsjwJl2eL+ohTxT4cM9vs1pD0Pna1r2tbiReBrjeyObAFlr3t5UtRQFNUBBaRRL5fe7GEQBEi8cKyDU1x5qXalCx03LgAs+I4m0cNmz4Bja3BWKqIcW+n3aJp1apVHH300QC43W5CoRCKonD11Vczffp07rjjjk5vpETS20jm8iSTIB0fGZHypEmO8vK5NXwunaGFAQ4bW8xnq6tZXF7Dlob2myvuCP1zPIhEtfZQzOIv764AFKpDjUeruZpNSyZqAmmjcUxbUBmMETc634E8SeP4WqRxMpJwuulsW5Dj1XHrGrXhOJqqsjUUx62p2MIZdefSFLI8Ol6Xk2cVMyyEcIqoel0afpeWMG7UGFTg47DRfdl3aD4IqI+YVDZE+XjVVlZUBMkPuDl6Qn+G9AnwvxWVhGMWn6+pxqVAQ9QZIeaS+TgpdjE9slPQVAQmX3gUZZttgyKcLiZLON3VSUHTljt7i/uyQVec7nG9kSKyBGiKgpHYkqoqTnSYbdFHIRzh5HU5Lz5uXSPX72q+k15Iu0VTfn4+DQ1OGG3AgAF8//33TJgwgdraWsLhcKc3UCLpbSRzebbUR6lNVLu3Em9TNgIjcedSgFDcQldNNtZGeH95JZqmpOZ3J+U1UWdkWt9s4pbN52tqABhRFGBgvp/KYKzZtKhhsWRjHTe/9B0ApiVSfkjVoTjrayI9llidrAWmqQp+N/TP9aXebgfk+fC6NGpCcbYGY7h0lWxNxeuyyPHq2ALWVYcJxUxMy2ZkcTYeXWV9TYSnPi3nzR+2pIRj4+HYG+uiLFpZlRrFqODYHjQu4irpOXQFTPk9pIiatlOrLtWV7Ygkt64StQSmbTsFhYUjdFTVyXMMxTNPB7BsQcSwUnlRyULKOV6deCKnyaU6US3TttFwcprsxItLn4CbdTURxpfkpiLdvZ125zQdcsghvPXWWwCccsopXHXVVVx44YWcccYZHHbYYZ3eQImkN9E4l8ewbGx7m0BKePSlSOQjJ24STvmHnhBMSUJxix+3NLCxNoKKkxy9NRRHUWBrMJY2TU3YEAwu8LOxNsqG2gilBT4CHh1NVSjM9uB19Xzh3nDcoiFq4nap2LagJNebaqPPrdE3x0NFfYyNdRFyvRqGJdhUF8GyBV5dJW4JVlUGqY04ZS/Kq8J8ta7GyXVRoKI+SkVDjC31MbY2xFIj+JKJ6Anfwt0KXYECv6tX5SwF3BoBryvjB5pL69Lm9DjJXC3Ldq5PM+F1JQC3JojFLeKmSJnkulSnKLdIRHEzxRSOtUddJE44bhGKW07NQF1lQJ4Pj6bSELPQ1W0vGZYzIJaSPC/raiLk+lz84qDSnSIJHDoQafrrX/9KNOpUUr/llltwuVx89NFHnHTSSfzqV7/q9AZKJL2J5RUNrKwIkuXRqWiIoWsq8URNKVCalbxXVQXT6j3mfJG4RdSwyPboKIpCKGayNRgjFLPwJJ4koZhJKGaR5XXqgSWFYThuk+Xd5plUnOMlWBnqqUMBnIdAQ8wiuCWIrkFNOI5Lc6rKG4m36Wiiv2zJpmDauokeNeKmTf3mYEoEGBasrAwSt2xs2xkCnyzjkcQW7NT5S1qi6zjX66IuahCOWygK5HidWmm1YYOIYbUoCE0B1WEDBejjd66juojRI92SqkKqO9ayMvcDMzowtmJn8o1qy4+sPpY+xwIQ0D/Hi9+tUV4VBiEIt+MLNW0wbQtNhTy/h31LC/hFE58mJWFgmvRp8rl0RhZn8YtO9GnqDtotmgoKth2cqqrcdNNNndogiaQ3Uxd26pm5vXrCeFFJ66tvTu+6zSajXyjOgzMunGRMWwgnAVoI4gIM27lhGpadMsRLTktSWuCnfGuoVyTTCpwHoWHZHbYASCWdC1JCUU1YFTQ+xJ3p4dkaloBgzCLYaGSmBtRHDWoyTMgVQFW4JbfvrkfBSeJHdQY41EWMLrsOk79tt64Q20n6/9rbSktAeVWY4mw3AJ6Eb1OmUVSXqlCS58WwBLk+F2cd4AihSaUFnDZp0C7lCN7hgr1LlizBshr94DSNcePGdUqjJJLeSq7fhVvXsO1tQ97b/sn3zkesZQkUzUlW97pUVMUZfgzO27srMYLMpakk3Y6S05KoikJRjofNjco57CokhZKmbH8I9q6Cley/2QkQQMwGbEHM7NpRV8lTEt9JBNOOUNEQx6WCLVQnip5h0qJhCwoCbvL9bsqrwzz1STmTSh3fJV1XOWr8rjOyPuOkhA8++IDJkyenPh9wwAHsvffeTJw4kYkTJ7Lnnnvy9ttvd0kjJZLewqjibEYUZxGKmfjdieRG1RFPTbvmkomRWi8zg1FxIklxyybg0SnM8hDwaMRMKzUt4HG66vxuDVVVUFXwu9NvF0IIXKqK16V2yO9GAXy9IC+qJSyRyAURvadrVdKz7Oh1sLMEVJwuaYVhhf52/a4d131lp/Ndai8Z37Eeeughzj777LRpCxcupKysjNWrV3PVVVfx8MMPd3oDJZLehKoqzDqolFy/C5fmRGjAuaE27R4QONEYdy/TBV6XmjKnKwy4EQIKszzYjabZwsltWlsdpiTPS0mej7U1EUIxE8sWhGIm5dVhCrOd/IXSPgHG9c9mcIGfoix3Rjdbt+ZYM/QyTZlGS0WmpIiSdISdZcBAwKszMM+HYQq87ciYT/5WvC6NuGntNL5L7SXj7rkvvviCW265JW3awIEDKS11PFzOPvvslH+TRLIrM6m0gFuOHpPm0yQa+TQlR4mA83bZ2xKGc30u+ud5MSxHGK2rDuFx6UwekkcoZlMdilMfdZLdx5fk8ouET9PcRWtYsrGemOEkjY8vyWHWwUMAuPPVH6gMxsnx6BRneyjK8qQK7ub5XfjdTpmTcMwibjtDkgNunZqwgaYqWL3sHEkkuys+t8aZ+5fyRXkNocSIuEzXA3Y636X2krFoWr9+fVqZlH/961/069cv9bmgoICqqqrObZ1E0kuZVFrA3oPyW3UEX18b5r/fbKSsMsi6mmhPNzdF/xw3o/pmU5kw5ESBfjk+9inNZ83WENWhUCIpXKFvjjeV0Lm4PFEwWNn211jmBDw6qypDVNTHAOcNdUz/LLK9btbXhNkajGFYApem0ifgIRy3WFcd2W3yhSSSnQGXCvk+F/sNK+CsA0pZ8MNmbnvleyqC8TbXc2sKhVkehHBMb3cm36X2krFoys7OZtWqVQwaNAiAE088MW1+WVlZl1UVlkh6I6qqMLpfa9d8H07ceyD/XFTG3a8v7RUjzAC2hgyUiiCDC/x4XR6ihsWaqhBfraslz+dicIGf4mxn+rqaMHfPX8pJkwby4uL11IaNhLmlRtSw+GFTfZrx5Zj+Odi2IBQ3aYiaqIrKkeP6Me/TcnK8LgqzPOQH3GxtiLGlvr5NwaTgeOnYQklF7SQSSdehALl+N3v0y0mNapsxth/zv9vMopWV1IQMbBq5ejdat7QgQCRuURmM7XS+S+0lY9G0//7788QTT3DooYe2OH/u3Lnsv//+ndUuiWSnR1WVbUnivQTDEpiWU/VcURT8Hh3DslOu5snpAY+e8mx5aOFK3JrK0MIASiKHK+DR8bk1Pl9Tg0CwX2k+amJ0XY7PRb8cQXlVmIf/56w7ul82iuLYM2yujzbL72g6xlAA2V43+X6dlZWy0oBE0pVoCuQH3Awu8KcJnmQO5/qaMIoSpj5iOLUeEz9WBSgIuBEI6qNmqjt/Z/Jdai8Zi6ZrrrmGww8/nD59+nD99ddTXFwMQEVFBffeey9PPfUUb775Zpc1VCLZGemX63VKGXRBP1RSaCiw3VIejZdtaGReGYqZhOM2Xl0jFN82HUiJp/W1Efbom5USTElaM75sa11nf44ZaFMx2VQ4heMmem/OEpdIdnJcKuT7XRQEPOzRL6dFwdM4h3P55npqIgYIGFzg55oZI8n3e1os8L2rkrFomjZtGn/5y1+4+uqruf/++8nJyXGcYOvq0HWdBx54gOnTp3dlWyWSnY4jRvcl3++mcjs5Ae1FV0FX1VQdNFVRsNsIaTUWJHYT80pbOCVFoqZoZmCpKqQS3JvSlvFla+saCdfm7blXJedHO2LdLJFIWkQBdE0h3+/i8mkj2W9YQUaCp3EO5+4kkFqiXeaWl156KcceeywvvPACK1asAGDkyJGcfPLJqVwniUSyDV1XueqwUdz6n+87bcixrkK2WyNiiYQwad8w+KbmlarilBxpPD1JsthnS4KsLePL1tZ1aSq6qmIqIm16U1d1TXUqpYdinSOaFByrhSGFfnwunYhhUbY1lCqxImmOimPmGjVs+uV4Eq7rTlma6kQx1t5p3SppjJ6IdKsq5Pvd/OLAUqaNKSYYcX4DeT4XthAs21xPfcSkKhwjGDVRFYVxJTmM7peT8GprK4dz96HdjuCDBg3i6quv7oq2SCS7JGcdWMramjCPvb+6w6PFnMRoJSFEHDdkt6bic2nUR81UN1lriEb/z25kXunkLqnUhA0K/O7UdHDMK0Mxk8IsN8GYSWGWSOuiSxpfgmjR+LKldQMenYBbI9ZCBKnxEZg2WHFrhx/ImgrDi7KYddAQXly8nrqIQa5XJcfrQlUUVlcGU67H7RWfuzqq4thTBKMR6iJx4pYTOTQb1XiT56v3Y9qkXq7qoybPfLaOFxavpyrkFB1XFRJ14RyrFMOyEcIp3u13a+w5MJerjxi1S+cptQdFiPalqd5999307duX8847L236P//5TyorK7nxxhs7tYHdTX19Pbm5udTV1cnRgJJO5dOyrVz33Desr4lu92HjUsGja3hcKqri1IdTFAW3rhKKmWiqQmmBH7eusWxzfSpi0tJ2kzJHS3Tp9clyMyjfnxoFt64mTG3YIM/vSpueHAmTHD1XFzEoyvKkzdcS4XnLFs3mJdd94Yv1bKqL4NFV6qMGtWGzWx62Lk3hgGEFzD7cueF/XlbN3xauZE1VCMsWZHtdjCjO4pBRhayqCPLs52upi5pYMviUok9Apypkoqvgc+mYdsdr+/VWktEyFScaI1BQhKClqima4vyOMrQu6pWoCng0laT0jZvNXe9VxTkvmqqgKAqlffzcfeKEXi+cuuP53W7RNGTIEJ5++mkOOuigtOmffvopp59+OmVlZZ3awO5GiiZJV2Lbgh821/Hu0gpCMYuCgIssn05lfRwhnGhM/1wvEwbmMqoom5Vbg9SFDbK9OijQEDHZUBtm4bJKVlWGiJsWZsKhOxS3MEy7xQKzPrfGpMH5HDmhH5+urmZlRdApPKxrjCzOYr9hBS1OTyaGLi6v5l8flbc4H2h13rLNDfzpreVs7eScru2hKdAny8OH10/D7dZS7V+xpYFgzOl6GFoY4LLpwwG45Kkvu72NOxvJaEVvRcFpY1v2HiqgJSK2QjijRU1rW3TFrasEEiNIBRC3bAzTImYK3LrKmH5ZRE2bFRXBRP3JtvfXm9le16qqOOVUVAV0TWP66GIeOG1ir85j6pWiyev1snTpUoYOHZo2ffXq1YwdO5ZotPcY+XUEKZokOwO2LdKSMkcUZrG8ooElG+sRAnxulWDMpLIhRt8cR4SN7uvkJjRdN5nQ2dr01vbZeH7jedleHVsIHnt/Nf/9dlO3P1RUBTy6imkLbjxyNHsNzOPu+UupDRtkefTUaMZQzETTFCfaVh2RXU07EclISCbXVlOxp+EUYXbpKtkeHcsW1EWMRNe15rj6K05OHYpCxLBwaQoxwyLX7ybg1thQG2lWwHdXvH5UBQJu5xz1y/Py0Mx9enVeU3c8vzuU07Ro0aJmomnRokWUlJR0WsMkEknrtJSUObYkl7Elua2s0fa6bU3PZH5y3uLyan73+lI+X1OTGtnX3diCVBfSQwtX4nNpxBK5GxUNsdSIPp9LIRizsOxtDzyZ2Nz70VVH1Gwvjw+c77PpYsmeNV1VsGxBzLRSEaNgzEJJCDJVdWojenSV4mwv62vCBKMmNSEjrUwS7LzRpu1hJ7L9BYKYsevWk2sP7RZNF154IbNnz8YwjJTFwDvvvMMNN9zAtdde2+kNlEgkOweLy6u5+aXvWFUZ7DV5QdVhAwXnRu/WncR5TVWxbEFD1CJm2rTgpiDpxQghnILTbfh8aSpkuV0Ytk24hQQkBcfOQggn9820FRQBILCFIxZsW6ApzqjLDTURLBtG9Avg1TUqgzHW10R2C7d6y3ZsRTyuXbeeXHtot2i6/vrrqaqq4tJLLyUed3IAvF4vN954IzfffHOnN1AikfR+bFswd9Ea1leHe41gSpLyp7KdmnoKTpTBrTs+V42fe7v+I3Dnp7FY0hrVQPTqKhHDTnWtaYogbDmfVRwhpCiQ7XWBEERNG59LIWYKPLqG36USjFm4dRXDsokl8gUrGpznnEdzrpkcn4ssj8bmugg9FEztVgzTwuPSd+l6cu2h3aJJURTuvfdefv3rX7N06VJ8Ph8jR47E4/F0RfskEslOwPKKBpZsqu/Vb96GLbBsgZ4sEeGkrPSqMje7AirQJ8tFVchwhAqdL0ZdmoJX13AnRmSalsCla5gCDNMpCRS3BKYl0DUFn0sjGDNTXW+apuJODMHXVJURxQG8Lo0VWxqIGlYzE1bHdV9hxZYg/XN9bKqLEG1peN0uiKKolOR5mbUL15NrD+0WTUmysrKYPHlyZ7ZFIpHsJCQTv6sb4vywuZ511SFqQzHivTy5I2qYeHTHiyrZzSPpXFRNIRS30RSF5DgjrZNHmSkouBMldrREKMkwLdyaimk50cOo6eQnuTWFuGXj1lVnvi2IW3bC+0wj4NEoyvKgqQoji7NZsrEuFZVKNtmtKXhcKpG4xarKYJvu+70RlW0vCILMRaxLVdhvaL70aWpERqLpxBNPzHiDL730UocbI5FIeh9JgVQbMqgKx/h+Qx0fr6xibXWImm7yXOosoqYgaprNoh+6Qou+PNtD1xQsq7nPzc6E2uhhmilp+UMKeF0aQjhD9F2KQty0sAWOVQYkbB6S+1PQVDAt0WEhpSgQtwSGbaGpCv1yvUTiFqG4ha4qmLbAparEbTvlcaarjju9R9fok+XGqzvRJxQnvyng0dE1JfHnWBHETRsbZ19m1NypDFA9uoLaqMRRjtdFnywPG2vDRAy7TfsIBSjOdnP9kaM5ce+BMsLUiIxEU27uthE5QghefvllcnNz2XfffQFYvHgxtbW17RJXEomk99CShcHKrUE+W13Nu8sqWFMVYkt9zEme7enGdgKNu15UBbxujVCs/cdm9vLIWlM0xREtRqMnZvKf7elG87tVwnEbTVXI9Tk5QhHTpk+Wm8H5PraGYmyqi+Fza/TP8bJsS0OiXI/TdWaZHRcfCoAQhOKO+LVVhS31UXxujYH5XuojJqP6ZnPkhGLufHUZUcMm4NbQNWcAQMSw2FQbIcfnYtLgfATww6Z6/G4Nw7IxLKcbt3FXs6Btx/ieHHWp4ETCAh6NgFunX66PY/bqz+QhBaDAF2tqeHdpBVvqoxiWTVG2N/U91EUMooadNnrU59aYVJqXMoWVpJORaJozZ07q3zfeeCOnnnoqjzzyCJrmhLkty+LSSy+VvkYSyU5IU+PKZCkFyxbUhA0sWyBsgc3O85adCcljURNCoiN1/HY2BM4oQqOFEWWZHreTQO8s7XOpifwhG11VyPO5WVsTIRg1MSybmpBBfcRMLSOgw6MVVcVxqB7aJ0A4brG5PuqUdbEFhiWIGDa1YYMB+T4umzaCJz8pT5TLMTFsgaI4o+HcmkoobqLHLc4+cAiqCne9tpTy6jAkcqJayu/uyHWhQtq2Cvw6wbjVzONpe2gKDMj3ke9zEzZMasMGuqZywt4D+Nme/VBRaIiaLfqrje2fy1n7l7b4UlQTilMdjtMQMahIeroNyE3Vm5M0p93mlkVFRXz44YfsscceadN//PFHDjroIKqqqjq1gd2NNLeUZEJrkZlMjCGzfTqRqMmD766kOhijX66XM/cfTMS0CYZNNtZHqArGCMdNpxyJR6dvnp9hfQJUheMUBTzUxwyqQ3ECHp1po4rRdIW6sEFtxCDX46ImEk85X48pyUZFoT5iUhOJk+PVqY+a5PvcrK8N8Y/3V1MdMsjyaNgCNtdFU2/ZmqpgWqLDNfN2FpxE323/3skCSBmTdHm27ZbLhLQVMdFUhQK/i4BHJxy3qA7FURPdXtk+nTyfm011EUzLGaVoI+iX7WFzfYxQQqRpiuN/ZNmOV1bjaE6b+1YcsTYw30ffHC+rKoLUhA3iTYZqCgFZHo3bjhvHPz9cQ45Xx7AE62vChOJmqnajR9fI9uo8cvaklL/Y3EVr+N/ySuqjZkbnMnnNZDL2QQEKAm7y/S5MW1AbilEbzawWiwIUZbvpE/BgWHYzt37JNnqluaVpmixbtqyZaFq2bBm2vavfWiWS9MhMQ9RIlFqwE6UXBF5dY0TfLI7bq4T+uV7eXLKFz8uq2FAXJRo3iTW5V36/qYG3l1V2uD33v7UCXXWiJbYQ2Lbzdquw7cauqiBsRwy0ZuRYGWy+bWtXVQ9NEIDPpTk5LDtZkm+mOBE1pyirpoCSuBa0JgnCLlVhWFEWWW6VsqowU0YWctiYYgCWbmqgJhxnfVWIr2ImUdNCEyrCFlT8f/bOPE6ussz33/c959ReXd2ddGdPJyEJSdgJEGG8I4qIiDK4L6Cgc50ZXBGXkcFZriPqzOjIHR2HmTEiooPOjMKVAUYRcVzYg2whIQtJJ51O792116mzvPePt6p6SXenOuktcL6fT8SuOnXqrapTdZ7zPL/n92RLuJ4iYklKrk8yYtK2IE5zPMSTB4YAsAw9S9H1FAg1yq1bVA7IWgYQiIclEcskGbE4dWkDF25o4f/+fA/9+TJO5djURpQQMQ09p9FVfP+RdmzHJZIMEw8LUtEG8raH4/tYUmrvpaFizaxxc1szUcvguc40ZdenVPESmCiQs6TAMiW+P1zKq5Z8TalH+ID+PVjZHOOTr11PYyJUu6h6cv8gf3bXc/V9bhL+77vOoikemvCiLGD2mHLQ9P73v58//MM/ZO/evZx33nmAnjv35S9/mfe///3TvsCAgPnEtvYBbrpnB92ZEiXHqwRNY7dy6EyX+PWuvlkr9ejf+CPHOlT8+vDGuah9aYYGU2PUSVHpctN4ZognOiMHKwNEwwYh06BY1gaPPgoBxEImqxbEaYxZ5G2Xxakorzq5hX9/ooNnOtIUy14tOxQNGYRNA18phkoOjquIVgImUwqWN8YQQuApPbIE9EiOYuX99ZUOPgxDUnI8LEPiK1UT1i9MhklETJY0RHjr5uVcceYyvvdIO4fTRRxf1SwjQAd9JdcnFjKQUtGdsWvDo+NhEyEEicjw6S5vu4TM0WaN2ZKL66maLQFM/B3xfMXKVIRsySFX8lD4SCk4dWkDn339Bhpi1qQBzs+2d9X92TXFQjTFQ/N6fMnLiSkHTV/5yldYvHgxX/3qVzl8+DAAS5Ys4dOf/nTgCB7wksb3Fbc91E53pkSm6FB2/UmnnQdByfymmomrfk6u72MfR0fXfCVkCBJhE19RGUyraIiEOLutCd/3ebojzcJEiJBp6AAD3fDTm7NZ2hjhn365lwMDxcp7VcnuVDrOLEMSC+ngpIzC9hQL4xbLm2I0VgISy5AYQuApxcrmKJZhsLsnS7HsEQsZtZJZa6WUp5RPKmqycUkDtqO1S997pJ0VTTF+sbNHZ6aULvPVohsUSmmRtyUFhtSDr7syJWKVAby1LSuvbaxZYypmISuDek1DTCryV0Cu5JKMWCQi1qjArp4M0L6+fF2fXdSSpKJWML5kHjHloElKyWc+8xk+85nPkMlkAALtT8DLgl09Wfb05Cg5el6Z9xIt47xckGI4EyfRZSoQmKaYs7l500m1NOt4WihtGTpwMaWgJRni6gvaAC2CThcdWhIGvq8oOR69OZuGqIXvw+G0jQTClkHWVkg9b0QHYa6PEZac1JJgd3cOIaCtOUYyOpzBiYUMTENg2x6Op2iKGaxpSbC7O0ux0o2ZDJukiw6O5xO1JKsWJjClwAybxEIG7QMFvvnLPXRnSiQq21bLYUAlKNJmlrGQQTJi8dbNy/jeIwdoHyjQkgjXMk+9OZtU1OJ9Y8wa17cmWb0wzuF0EUtOHjQJoW0U3nD6Ys5bvYCLNyzCrGTTjsbj+wa4//nuurZd2hghbAbjS+YT9X3KY3Bdl5///OfccccdtQi+s7OTXG4cUURAwEuEdMEhW9ItuoYh5t24kID6ESP+K9HBk+3q4OKlEDBViVoSKaHs+mRtF4HgrBVNfO6Nm9jc1szmtmZuvGwjpyxNkSm5dAwWyJRcTl2a4r2vaONwpoTvq9poEc/XmbiqNs4HBvIuedslGpK4vk95RC14qODwfGeGgq19m3Z1Z3m6I43vK1Y0xzCkRCAqQYhHQ8Rk/eIGGkcEXUIIWhJh9vXlydkuq1titWG71esWpcDzqRhWSta1JrjizOUTvrYbL9t4hIhaSsGHX3MS8bBZ6/QbD1kZy5Ive9zx6EH+4ee7uf4/nmZb+8BRPw/fV3zx3h3kxwobxyFmSZSCda2JYHzJPGLKmab29nZe//rXc+DAAWzb5uKLLyaZTPI3f/M32LbNLbfcMhPrDAiYc1IxC0Pqq3WDo6fgA+Y3vtKi3UTUnDaTzqNpYWYTUXHhNoSgpSFMW3Ns3BLS5rZmzlrRNKobdH1rksf3D2A7Hq6vvYsmiiV9YH9/oRLIwAvdedZ4ipCpy3C2q924lzZFGcjZZEsuzx/OsCQV4TUbWrnw5BbSRYdv/2Yfa1oStTE3I4lYRq3jLmwYrGlN8GJPDtcf1iAZUjuFtyTCtSzSRK9tohLauasW8KlLTuZL9+4gNyKwGRlk+2rYRqDk+hwaKpIpOXQMFsYNxkZy11OHeK4zrf3BYNKu1FjYpDEWOiIjFjC3TDlo+vjHP84555zD008/zYIFC2q3v/nNb+aDH/zgtC4uIGA+sb41yaoFcTqHSvhyPpwWA46FkaefiGUQtUwGOXqbuSEhapksSISQQnB4qIgUAiH0nDOBLmGFDEl/vjxj668XWRlOu741wY1v3MiGRRN770gpjhAap2IWCl3eq+do95QiGTHxlOLFimbH86EpZrGiOU5j1GJFU4xcyaFjsMjqhXH+/u1nYJqSnV0Z/uOJDmzHwwwfeVoqOR7JiEVrMszBwQJtzTESIZP9/XkKZRdfKZTSZcfPX3HKqMBlvNc2GVduaSNsSD73/57TbuKVfYAaN7ucs92aOP67D7Vz1oqmcd9n31fc+tt9tbLfZAGTIeG0pSk+ctHawFZgnjHloOnXv/41Dz30EKFQaNTtq1at4tChQ9O2sICA+YaUgg+/ei1PdwyRs11MCc5Lp5LzsmBtSxzL0KqERNjgcNrmcLo4apuJskWrF8RZuSBeE48Xyi7ZkotlGAihsyklx0dJVZl3NreBtevrwbYfv2gdm5akJt226iM2mC8zVHRoioZIhk3s8tRc0qs+SjsOZ8iWXNYuitPSEBmVqUlGLFY2C7ozNnv6cmxY3MD61iRrWxNs70xPKty+6vyVfOnenTWd0qnLUgzmy/TlbFIxi89ffqp2wj5O3nL2cu5+upOH9vYTMiWmFGTtiQNr3Ukr2NWdZVdP9oggzfcV3/zlHnZ2ZScu+zHsUH/2yib+9X3n1K2TCpg9phw0+b6PN07/ckdHB8lkUHcNeOni+4pk1OStm5fz748fpGAfOcMsYPoxpsmpO2xKVjRFkXL4RNRfKI/qlhuZHxj52cpKtxhKgRAIYHlTjF1dGfJll4aIxYqmKLu6s2RKTk33MtcxdedQifd/53FuuHQj56xuGrdEVfUde6ZjiL6cXRGNSxqiJkPF+rq2hNBaoohlIIWgOR5iIF8mbI1fyI5YBn05u9YVJqXg6gvaas7cEwm3qxqsmoN9ziZkGpy7qnnazR7fdOZStrUPUnQ8/VlOcABWvabyZZdsyTmi021b+wBbf7WX+3f0THqRVb0rGjL4zOtPDgKmecqUg6bXve513HzzzfzLv/wLoEV6uVyOv/zLv+QNb3jDtC/wWPjHf/xH/u7v/o6uri7OOOMMvv71r9c8pQICymWP7z7aTsdAgZAp+V/rF7IgHsZHsaMzi68UibDJgniYxrh2+77r6Q6+9/ABurM2htAlh4hlUCy75MteXa7AAaOpN+D0FCTDEoUYpTOZCoaAVQviowImoJZ1qjKyI2sksZBBNGSOOqFbUtAQtTDLHsmISW/ORgiBr5hQ/zMX5Msen/t/z7G4IUwibBIyDda2JkZ1z3WlS2RKDp6vx4y4vk9fzsZTR/+cqpUoQ4ja+xkPmYCgYLt6Nt0YSo53hE/S2ICorxIQnbo0NSogmqpOaapU3cG3tQ9ie74Wvk+yfVWf5Pn6X/U1+b7irqc6+PzdzzNUrN9l/P2/t5pzVy046rYBc8OUg6avfvWrXHLJJWzatIlSqcR73vMedu/ezcKFC7njjjtmYo1T4oc//CHXX389t9xyC1u2bOHmm2/mkksu4YUXXqC1tXWulxcwx3zx3h3c/vB+iiMu+f7l1/tqIlKlFL5OJhA2JY2xkC7DFN2ay7aUgkTIwDIlrq9ojoWIWAa9uRKepxBSEDJ0Sj9d50iGExlDckydhEcLmCRA7SpeD4etttGrOjNPhtAXdiuaoixvih5xf0jK2v4Moa/2xzpJaA+hCNdeuIZfvtA36oR+TlszV72ijYODBf7pl3uxXV9npOYhPRmb9WsTlD3F9s40X/ivHcTDJoP5Mp6vj/uYJRFCEEKSLbnU8y5XxdFhSxKv6JGkFEQsScZ2WaxUXT5JUH9ANFWdUr1sax/ghh8/y8GBAqU6a+++PxxYLm4Is741WQu8frq966hl2pGv7NRlDXziteuPef0BM8+UZ8+Bthz44Q9/yNNPP00ul+Pss8/myiuvJBo98kdpttmyZQvnnnsu3/jGNwBdTlyxYgUf/ehH+exnP3vUxwez515auK7Pfc8f5lcv9PFMxxAvdB+7LYYBtZO4GOFGvCAeBhS5kkc0ZNQmvpccr2bcVz2xwIldzput7rBqwBQxJcXKFPZFyTA520EpakFvxJK10SBupYa3ZU0zS1NRNixK4AvBgzt7ODhYZF1LHCFEbZyGKQW9mRKDRaeWCZBUgjKofXYhQ/CK1Qv4kwvX0hA1axlJgFOWNrB2YYIPfu8Jnu/MkLddCvNY6Hbq0gYWNURQSrG7J0e66NDWHGNffx5TylGda3bFpqCKnCRYlQI2LE6yJBVFKUX7QIGljRFyJZdMyR233Ha0TrPZxnV93v7PD/NcZ7oWRBqi/jmEUsDfvu10Vi+MV7J3RTrT9lEfF5L6wYYQ3PTmU3nL2SuO74W8jJmXs+cATNPkyiuv5Morr6zddvjwYT796U/XgpW5oFwus23bNm644YbabVJKXvva1/Lwww+P+xjbtrHt4QO7atgZcOLz/Ufb+dv/3km6ztT4SMYrSfjoH1GzMmi0+qOaLTogBGFT6qCiEk1VT7rVk008bGK7Xm1m1omAIfWVdHXFE5Wvppuq6eTI+WJlzyceMukv6M407Urt14LXalD6uwNDHEoWefjFfixD+wsN5Mv052wsQ+IpPS/Mq9SeGiJWLVs2dhpN1fdn/0CBz931LK6vcDwfq5JJdH3FUKFMujg9lgUzTbbksKghghCCZMSkO1Oi7Pm1Y3kklimR5RHBvtJz0EYeD1AVd5u0JCPkbbcWFF1XyZgcrdw2V4wcon1oqMBdvzvE0x1Dw7PwprAvAZy2LMUVZyzj+v94mq50qe4OSk9B1DA4a2WKK85cPuXXETC7TClo2r59Ow8++CChUIh3vOMdNDY20tfXx0033cQtt9zCmjVrZmqdddHX14fneSxatGjU7YsWLWLnzp3jPuZLX/oS/+f//J/ZWF7ALPL9R9v5q59sP+YAZbxH1W6rBEJVgz9PqYpPzIifWTV8sq8+1hB6KKznu7VN1rbEiYQMujM2vVn7iJPRXJ+ILSkpK1/rnxkuW9quXxuNMRN6rmpw5imFlLpsajs+TakwfZWTkT8ikhu5hJLjczhdQqHXuq41Scg0aO/PU3J8LENUAln9LIWyhykEPmrc9z9sGSxuiGB7Pru6spQ9n7ApWdIYpXuoOKrUO9+RI8pkVd2R4/q149kccQj7viJs6nlwZVe/N1UDSSnANCTxkNaaNUYtDg0Wxg2KZlJ/NBXGBkkP7uxlb2+edLHMQL6sB12rYQG//m7rx473XRz5ClY2R/mLN21iT1+OZzqGGCyUsd36vhghU7JuUYLrXrs+8GM6Aag7aPrJT37C2972NlxX/+D/7d/+Lf/6r//KO97xDjZv3sydd97J61//+hlb6Exxww03cP3119f+zmQyrFgRpEdPZFzX5xsP7JqRjE71ZC4qQhgdTAik0A7FtfJG5eRU275yk3Y/1kGAELqLqDUZoTUZoTNd5IXD2VoXjRRauzGXmSlDCqoWRtWxI4aovIYZeL6xHWsKHdwYlRqnISUhQ1J2/VHZL0C/90rhKnA9RSpqYnuKznQRpRRhQ6LQ3UkCHVxFLKl1Z0rRFLPwfEWxcrsUSmuphCAaMth3OI9SeuRHyfU50F/AOcFs4RfGh61iqroju5LBy9ouhpC1z7bs+SQjphZ3Kz3Ud6jg4FUcwhcmwpyxvJGrzl9JMjLxgNqZ0h+Nx8jAaORaqh2Ce3pytSBJCkHbglhlHt/wXL3xIqSRfxrooMqs1HJbk2G+8o4z2NzWzMN7+yrDvOs/LlYviPO5eVaqDJiYuoOmL3zhC3z4wx/mr//6r/nWt77F9ddfz8c+9jHuvfdezj333JlcY90sXLgQwzDo7h4916e7u5vFixeP+5hwOEw4HJ6N5QXMEvfv7KY3NzPmgmOvAxUQD+vZWjnbw5BGLctUbUWGyjT3ihBKonCUzoIsTAyfxBY3RDgwUMD1FBKFEoKIKcnZw5Plq/utVwh9PEihxb1Fx2Pk+cQwBIYvcGcgYBj5mixDYLt6mn3YNAClg5lKAFXte1NKB3dCjNaNKXQnWLZSOgtbBgB2RSOlsyjVjBP4SrfaCyFqQVnENMiXXfpyNnnbI2RKpNCfZdGdn4LviTAlJCL6J18pRV/O5owVKXIll56sjRRQcPxK2dFHVrrhFjVEuOHSjSSjJkN5h8FimcaoRVM8NGdZo/EYGRiVXa/WJbhlTTM/2tbBUMGhJRmmL1fS3x8BBwYKeL6+eFFKUfbco2ZODUOQCJnELEljPDTKG2qgUK6N4aknU2wZgh//yQVEIseklAmYA+r+pF544QX+7d/+jUQiwUc/+lE+9alP8bWvfW3eBEwAoVCIzZs388ADD3DFFVcAWgj+wAMP8JGPfGRuFxcwa3SlS8ddMproB69apvJ8VStTRCxJUzxMsZwnX9ZpmZAhaW0I0522tV5E6iyH4/ooBFJo92Sd1RA1geyyRt1MkbddSo5HyfEZe07y1ezoisIVs8aoZVB0PDw1HPyFDIlb0cJMRxlxrBeTFDoQCpvVjkb9fi1MhOkYLFIoexW9mC4Rikq5beQ6lNKBgl+53ahEmyP/rmYZqh10w2vR21iGpOQqSo6PrxRGzbKgPpfs+YQpJVnbw5T+uLqjqk9TuaLZWpgIccbyxnmhPzoa29oH+MJ/PU9vtkxDRI8fMQRsP5Tm17t7iVoGGxYnyZc9CmWfiGVgCMiVPdzKkGAhJaYAd5Jjuvq9a4pZR7w3vq/Y052r+7enai8QBEwnFnV/WtlstqZGNwyDaDQ65xqm8bj++uu5+uqrOeecczjvvPO4+eabyefzvP/975/rpQXMEotTkVFZnmNhPP1CdZ9VDVMibPLuLSvpSpfY05OjIWpV2rS1MDYVDbEoGeHQUJFsySVru0ghWNQQ5rLTl9YeN1YgC8Pi2WzJwZDaLDBqGezrz9daxHV2RdQ681zfr3X9TES1k09BZQSILmWNfYhRKSUmwgYtyQjdmRKDhbJ2wnY8jIqQuOyqirC6UuKoIwNmVlrj9CwxrfNa3hSj5Hp0DpUAxdLGKC2JMIWyx57eHJ6vWBgPoRQ0x0MMFXQXXciUlJSH7w9ryGql0IpOR1bKTZ5fzQAO/119D2C4G3LkY5yKcM2tqJ/Lno/vq3lrKzAe+lg1sF3F4aEiqVhoQt3RSEfwxvjc6Y+mgu8rvnb/bnZ15xBCZ3uk0Jqt5niIvO3VtFyONxz8CvTFjePp2XphUxALm2RLbm2e3cjvUsiUnLq0gSvOXMZ5a5pZuzDBnr4cj77YX9NIbWsfrGvNpoQPvHINf/aGjdP/hgTMKFMKcX/605+SSqWA4QzOc889N2qbyy+/fPpWdwy8853vpLe3l7/4i7+gq6uLM888k//+7/8+Qhwe8NLl4g2LaEmEOJw5vhKdQJenEiGTgqOvSCX6h/bkxUluuHQj565uHqWjSEZMEJAtujVNhe8r7t/ZTVe6xOJUhIs3LMI05YT6CxhfPAuwqyc7qkSSilogIFNwGSyWSUUsBgtlcraLUtTcqX0FyaiJKSQblyTZ2ZXlzicPcThTQiiwPZ/GmMUlmxaxuDHCXU926vvQgdDvnbSQc1c18/Md3ezvz+P5imTEYm1rggtPbiFXcnlgZzcHB/Tw0rztIoQOumIhk0LZw/V0sOEphWUIEmETQ+oSkOv7xEImW9Y0oZRgIF9msFAmZBqct3r4to7BAiFDkoyYtZljQuiOLsvQHYwFx0cphev5uEp3x4EiW3Tx0BYCslKCM43hz9v3FWnbwVOKiGkQMiBju0jg0GBRz2CrzyB7XpGMmGxYnKQvX+baV53EactTc6o7mm7ueuoQT+wfwEcRkhKr8rqytluxTFCUXI+87WEZcpT+0DJ00Fz2/FrpNWLJWna16o5+5ooUbz9nBVecuazynB389d3PczhdouS4DBYcpBA0xY808hyLAL76tjP4g7ODTrkTkbp9msY66Y67MyHGHbFyIhH4NL00qKd7riFi4lX8fRqiFouSYRzfx3F98mWPhojFtReexOWnL2VXb5bth7QdxSlLG9iweOLhpycKkwVtE91X72PGBo/Vq/Kxmpjq7eMFh+Pd9p/bOvjJU4cYyJdrrtuG0K3wOjsk8CouzqB1T6mYiRSC/vyxRTymoV/3ier63tYcxTQkpy5N8bV3nnnCH7cj8X3FH/zjb3juUKbWOFDtZI2YkrKvcFwf0xCcsjRFYyzE9s402ZJb6WRV2K7ORFVLsg0Ri1ULYhxOl4hYBtdeeBJXnLmsJij/2v272NY+iFsJqLxKd6lZcUMvjpnXV818gr4AiViSW685j1ecFLh+TzfzyqfJ90+sLpGAlzdXbtFlrvF8mqSABfEQLckI61oTnLemmUdfHGBPTw7PU0Qsk9OWjdYrbFqSOurQ0xONybILE913LI+pMtF9491evc11fX76fBdd6RK7urPc+WSH9rWxTEB3urm+wvMgZIBX+Z2ypLYQkEC6OCzuNcSwcWW9VKfSj50lNx9myx0NKXQZckFCz257KQRMI4Pzx/cP8EJXtnZf9eV5vqLg+ERMiVP525TDMwN3d2cplN1akLQwEeLAQBHP11nQnO1x9sqmUb8BWje1g13dWTxfNyV4PtiuwhAQMaFcKTmP1Oepyv/IikZvUUOExjoyUgHzk0CBFvCS5cotbbxz84qaI7gQ8L9OWsialgS5sjsqU/Luc1fOCy+ZlwuTZaxAB0t//pPnuPfZw+QqQW81hx0xtEi92iHnen5lVIUiFtLiddev+AqNeE5L6qv8nH1soU7NCqLy35ApKc2nIXPjELEMzl7ZxNW/t2rei7nrYWSHnO16dKVLOJ6qZZmGfahUpRuu6hyvBwRLIUiGTVY0x2jvL9SCJBC8ZkMrF57cwrLG6LhZ1O/8dj/7+3O1TJLjeaOMVW1XC8xdT2FVDpJqpjtkSlJRbd9wxvLGI8bHBJw4TDlo+slPflL3tnOtbwoIME3Jm05fxptOXzbpdieypmM+MllQNFFr+NWVq/qjObmXPHAqovSRGaOyp7UpAv15Shhlvun6kLP9owrVj4ZCl1tMWTXJrIiGj3O/041lCD706pP40KvWntAXANVj6bF9A9zx6AFKjseihgieb3BoqAiMMEOtift116XjKUKm4P2/t5r2/sKoxovJgqTq8+7sytQyWg/s6K6N9KHyfNU/qk0DEatyXFSiONPQnZgrmmL4viIVe+lk/F6uTDlouuKKK2oH5EjG3vZS0DcFBARMncmCIoCb7tnBUMGhNRkmYoUpOR7bO9PcdM8OzlnVzHcf2kfpKG7KI6VqY9vDhRj2shoZVE2XJKlabjEMgeFp89H5dgoMG5KFCYtz25pP6BP0yGPpwECBsuvRFAtpUT46QDKlDohlJYj1lQ54qh/4yYuTtSG49WaTx5ph9mbLtaxVlWqms4qPznqahmBlc5y+XImhgkvIFJhSsH5Jwwlh3xAwOVMOmn72s5/xp3/6p3zxi1/k/PPPB+Dhhx/mc5/7HF/84he5+OKLp32RAQEB85taNuDFAe547AC26x8RFH3hv54nHjYZKjisWhDTruromXyxkMG+vhy3P7z/uB3QfQXCV3UPWq2XscGZqmQ1JGpeZZlMWTUmNUnFTlztzOP7+/mLu7YzVHRIhE183ydsGmRtl909WZY3RZFCELZM/LKL5ysSYRMpBZ7vU/a0m/s1F6yqBUf1ZJNHPu/CRIiy603qyjXyuLB9n+ZImGTYwHYsFiTCvPvclZy3pjko+b9EmHLQdN1113HLLbfwyle+snbbJZdcQiwW44/+6I/YsWPHtC4wICBg7jia9giGr8p3d2c5OFig7CoaYyZN8RBxKWpB0a6eHHt782xc0lALmKoIITANrUcaOzj2aIx3OpuJyTMjdxkyBSVX2x00xiwyJUfPLpv+p50yUcug5PosSUVOWO3M4/sGuO6HT9GbtTGkYCBv47iKaEgQMQQlT9GfLxMLacf8WMjQtiC+QlR81ELHMAT38X0DfPwHv6Mna2NIyWC+XJs1OHJ49KjgecT/l2gbg6ztceqy+TGYOGB6mXLQtHfvXhobG4+4PZVKsX///mlYUkBAwGxwtIDoaNqj6jbVclsibNTGk+Rsj93dWdYtStIYtRBC0BA26cnYNSPKsdSMMafDYnyaGZYXa1oSEdYtSvDqk1tpaQjzDz/fTdnz6RwsUpxDcbhAe26ZUvDWzctOyMzGtvYB/uL/PUdvtowptYeX6+tsXr7sUZbajytvu6xsjlNyCjqwMQxWL4yjUGRLLguT4UmH4I49/tPFMtfd8TSHM3ZFH6U/R4UevVM9LLXg/Egj13hI2xOcu6o5aCZ5CTPloOncc8/l+uuv5/bbb68ZRnZ3d/PpT3+a8847b9oXGBAQMP0cLSAaGQyNpz268bKNnLWiidseaq+V24aKVZduAULPrOsYLJCKphBALKxtAvJll4bokWWjmgvzfEjXjMAyBFFLz74rlLUJ6C3vO5tNi1M176r7nu1ie2ea5c0xXuzLUTEQn3WkAEtKzm5rnFKGZb7g+4rbHmonXXQARdnTXXAjHf4dX+E7HqYhiViSta0JdnXnkAJKjkvYMo+wCxjL2OPf9RWdQ8VKF+boQduK8TOIonKnENAYtXjluhY+dOGJLboPODpTDpq+/e1v8+Y3v5mVK1eyYsUKAA4ePMi6deu46667pnt9AQEB08zo7JBJKGLi+3pO10337OCGN2zg9ocPTKg9ah8o8N2H2om+ymBPT47WZBghBJaU2hdIgSm0c3re9sjbrnb/Frr1O1tyWdygRpXoqg7eEUtOaUL8VLAEOGMimbFeS4bQxojlEd5MEVOiFJRcXab5xMXrOXVp4/A+pODqC9q46Z4d9GRtwoaBtLSupjhDr2UiFiRCLGuKTZphmc/s6smypyfHgniI7qxdC5hETfCtP5fq2KCy4zJU8liSivAHZy5lc1vTEYOEx2aUsiWHL927s3ZBYHuSnYcztc+8ylihNwxnHKuz68qetixoWxDj6qAr7mXBlIOmtWvX8swzz3D//fezc+dOADZu3MhrX/vaI3QKAQEB84vqlXx3poTj+fRkbfxK12vIEGRtl3/8xV56snYtGBqJEIKWRJjdPTm2d2Youx4RKwxAPGwQD5lkbRdDyErw4VeG4ir68mXOWN5IznZpHyjQkggTsYzasOKmeJiLT1nCt3/zIjNR4VraFKU3a1N0/FGzxaoO0k0xi3jYxJSCnO2SLjq4vqLk+kghaE2G+dCr19aMU0eyua2ZGy/byHd+u5//2dVLsTKfbzYrjTFT8orVC05oT6Z0waHseqRioeHPpxKIVG0eqh5cvg/7+otIAeWQwX880cET+wf58GtOmtTeIl0soxRsWJwEIdjXmcab5Hgb+RlKqdegfEVJKUwpOWtFE9ddvO6Efc8DpkbdQdNrXvMafvzjH9PY2IgQgte97nW87nWvm8m1BQQETDO7erI80zFUG3grpdAz2nxFsQzg8kixn4aoRWsyPO4+qkaBACFTBz3xsIkQQrst92Qpun4taHA9RftAgVTU4rqL1wHDA4nHDive3NZMtuRwx2MHp/V11wKjeIiQ7RIL6Z8+KQUrm6K87ZwVXH760lEjXdY0x3lgV88RMwMnYnNbM2etaOKupw7xT7/cS6bkkC46M5Y5G0vJ8zkwWJh35c2pkIpZhEyDou3q4ESpUYOVq2UzywBficosOciWXIYKDocGCzy+v58PvHI1v7+ulS/dN7rEPJDX9gEhU5AuupiGIG97mIagPIFDziihtxAsTIQJWwZLGiK8dfPy2oiVgJcHdQdNv/zlLymXj28AakBAwNwylHfoy5XxfYVlSgplD18Nn5SqmRW/UKY3Z7O4IXLEPkqOvmI/ZVkDa1sTbO9MEwsZCCFojFmsa03SMVioDdx1fTUqKILxBxJXTzxvPnMZ/7mt47isB6qnMKPi4SMqwt1z2pq56hVtJKPmuM89tiX90lOXTOl5pRS85ezltC2I1bJOtnP8hpr14Ct4+mCaP7r9CT51ycnjZsTmO+tbk6xtTfDkgUFMQ2AaJmXPx/MVvq+0Zs4QRCyDfNmj5HiVTOZwmdUt+3zjF3u549GDhC3JyYuStYypaQgMCZ4PHUMFlqYi+EphydFZQUPo/Y20I7Sk4GMXreW8VQsCoffLmGCMSkDAy4jBYhnH8wkZegSIrxSGFLVOoGFxq6C9v0BrMjxiNIXWHvXmbE5dmmLDooaalmdkuc0yBPGwQXM8wbu3rOS81Ud61Ix0YB85Xy5vO/z8+W7iIZOhYn0DdscrgdUGtwqBNAQnL07yN287jQ2LZmfQ8ua2Zs5Y1sgtv97Lbb/dT3++PCsDfxU66/KVn77A+kUJzl11Yg2FrerDDg7kGSyU8XyfeEgH3rbjYUhBayLMoaEiCmo6pLHJNQX05cvELEm65NJYaTywDIkhJQLI2y7uCAdxUwqcER+SKYUO1pT+/1vWNPPhC9cFgdLLnCkFTc8//zxdXV2TbnP66acf14ICAgKmj7Ei2FTEwjIEjufjej5CVDQiY07ojVGTTMljT0+OZY3RUdqjVHR4FERVy1P1aTo0VEQKwZqFcT70mpOOetL+/qPtfPPBPTr7VSnFCKBpCgNNFeMPzxXoyfPLmqL81eWbZnXgclVL80zHEDnbPeL9nUksQ5C3Xb75i71svebEcAQfe5z+2WUb+b8/38O29kFytotE1LKFh9IlqobxIwPm8YLnguOzrzfHmSubEOhmhnjYIFN0at5g8bBuTohYEtf2auN5/EpAZkjB6oUxPnHxiSmuD5hephQ0XXTRRUeMT4HhESrB6JSAgPnDtvYBvvPb/Ww/nMF2PMKWwYrGKImwSbpiD+BPcDbPllziYZOVzTEGCw59ORvLkKxsivHqja3Ewya+r2qBk+/DN36xW2t4PK/WYSeFmFAg+/1H27npnh04nk/ENBAVbYoP9OXqyzKNRFbE3dWq3oJkiPPXLBzlKzUbVLsTu9IlMiWnJlwey0yJxJXSn8uLfXl29WTnfKbisfqBffyidRwcLHDrb/exqzuHr3SJrCFiVN7XiU0mRzJUdOhKl1iSiiCA5U0xdpYyOJ6P5/ksTUXZVcpSqgzcjZiCouvjejoLe+6qZj4RCL0DKkwpaHr00UdpaWmZqbUEBARME9vaB7jhx8/SOVTSWhB0/e3wYBGEzsCoMQLlqi+NaQg8pSi7Pje8YQOmIXnsxQF+sbOH7qzNdx/azw8eOzhqntyNdz3LocFiLaOStz26syVe6M7ypbecdsQJx3V9vvngHhzPJ1kRkWdLzjEHET4glDbWFFJwUktiVstxtXVUuhMH82U8X1Fy/Fqb/FhmKvlUchVhU1B0XJ7tSI+rvanH6b1ejmc482R+YF+6bwc3XLqRVQviDBYcWhIhQqZBLGSwrX2QTGn8gc5HrE/BwcECiytBUypi0lgZL+N4ikLZoSUZxvH8SvlOoCAQegeMy5SCppUrV9La2jpTawkICJgGfF/xtft30d5fQAJhy8BXiqLj4Xo66yFGBEwGQKX0IaUgYkrKlRO9lLrUc9dTh8Y9sX3hv3bg+Yr2/gKGFIRMiVHxaip7Pu39BW6+fze3feC8USee+3d205crEzH1+Ivp6DCLhgyaYxYtDRE+d9nGWS3HVan6DCUjJl2Z0oQB00xjuz6D+TL/9Mu9/Hp33xEu7kdzeq+X4xnOfMOlG7n9kfZJ/cC++cs9dKVLLG+MEg8Pn66a46G6gyaAXMmlc6hIY9SiN2ezqCHCDZduHNUQsHZhYlT3ZCD0DhiPQAgeEHACMJXMwM6uDM90pGsu3K7n6y45X9XMJ0eeyj20Jsg0BCFD4iptTJmM6BPKHY8dnPDEtqsnR1e6hCEhahrDXUoCDCHJOx5PdwyxszszKojpSpfwlaLsetjTNChO+T5nr2yaU5+iqs+QFTZnzWpgIpIRi5ZEaJSLO0weyNx42cZR7914xx1Qx3DmHZMOZx4ZECXCWvRvGtpTwPUVliFZmAizry+P5ysWjejiHCo6DOTLdZc3q9u19+eRCxNHdHKOZK5LmQHzn7qDple96lWEQqGZXEtAQMA4jKdNOmVJA9dMEBxs78xQcnyiloRKhsmvGgKOOMsItFmfFAKj4rqMgGTYZGE8hEIwVHRGuX6PRAhByNRC8qhljnt/xDQolF22HxodNC1ORVAK7GnMxDTEQvzJhSexaensZ5iqVH2GCmV3zsfnLUiESES0YWf7QIHbfrsfBUcEMrGQwYJ4iI7BIt94YA//+r5zME05bhapOW4Bgv6cPelw5t09Ofb25thYMZDM2W6t/BUPm7Qkwuw4nCVddHQg76taVs6UWqAdC0lAj7CpeoEpoGOwgOspGiJmTQM3ESOPSNv1OTxUwHHK/NmPhwibBg1Ri2WNETwlWZaKEAlJBvMORcelORFmaTJKPGKQtV26M9qbbFEyTKbk0J8tcyhTJCIlBdfF9RSpqMXaRQlS4RDduWFH80UNEcKW5P7nuznQl2cgbyOFREj9fYuGTBanIpy7pokDfUX29hYImZIzViRxXCi7PqcuS3HJpsVIKcYNZHd0Zrh/ZzeHBguETcmmZQ2kQiFyjotAEA1LciX9OnzPZ09vlq50kbIHi5MRWhpCSClJhC1OW97AyuYYz3dmK5YiJqevSHHxyYt4cSA/bnYuGTVBaV3iyHXt7M6w/VAGgE2LGxAGZIvuCZvNqztoevDBB2dyHQEBAeMwVpvkeLq750B/gSf2D3Dzu89ky+qF4zxSD8WyPXXEeIiReD4YBqRiIXxfETYNfN/jhe4cIVNy8093cDirNR9RyzjiB84ytNnjRIJy3Thy5I9iT3b6S1cDGZt/eOAF+rMOSggu3tjK+y9YTShkTOvzTMb61iTNcYtHXszM2nNORMQyUEqRtz3ChuTJA0NYpmBRMlILmIYKDh2DBfJl3X7/0Iv9/O/vPsHFpyziR9s6RmWkenM2j+8fBGB5Y2TS4czJiEl3pkS65LK/v6CDm4ofWDJi0hCzGMiX8ZW2v3B9VTuGHF9hGpJMyUUAyxoj9OZsYiHtzZS3vVoZ+GjpppF3+QoGiy6DxfrLerODXflvmnue7R51z/3PD/8thc4etjXHcH01KpA9nC6xvz8/qbP5ZDxH9qjbaFNRQXM8RCJs4vqqFgg7nk+2Ui5NRkxS0RDNcYtM0WV/f56S49X0jiFT0hizSEVDx1wWnkvqCpqamprqHpEyMDBwXAsKCAjQjNQmoZQeVFo7CygOZ2yu+tZj/OUbT+Gq84eNDE9Z1oBlSDLF+oTVZU/VrqJH4pY9XugtApApuezry7O8Kca61kRtm1Bl3pzj+0QwRoVHCrAr8+ROWTpc9nBdn3/5nxfrfyPqxAH+e3tv7e8n2gf525+9wB++cg1/9oaN0/584/G7g4O09xdmZAzMVCk6Hts7M+TLLr4PjudjGoLGaIh4WAdMu3uyuL4iZEhCBhQcj13dWZ7uGCJqGWxYrI0hFdCXs5HosSYDBQffV0QsOe5w5njIRCl4sTeHN6Z70M5p6wopBA0Rk3RJZ0LNSvuj5yts16u5fcdDJiBoH9AZFM/3MaXBUMmdFe+r+YKvIF10eOZQmtULYrQtiNObs3nkxYFZ0c5VfbG6MzZmk2QwX6bs+ZhS+1xVg95M0SFkGjy6L4tbmc1nGfoY8ZX+XVHoIccTlYXnM3UFTTfffPMMLyMgIGCsfsT1fJ7pSKOUwvHGb1t3PMVf3b2d/97eSWMsxLJUjHhEX/lN98+or+DAQIGebInFDRHiIYPBgkMqapG3XXK2M8o80Hb11eUZK1KjtCJVEbglYaZlP54P//KrF3mxN8c1F6zi+c40OzrTPHc4A0qwMG4ipSRX9ljWGOXijYuwPUV3pohCsKghTCxksK83T+dQiSWNEdYuTFB0fRSKRNikKRYiXXJIRSxu+R/tOVUVw88lHf0FpCEJGRIlFL7SpdTdPVlOXpSkY7CoS6umrPl1mVLSHLfY1V0eZWqat12dsbJ01s6ufHATDWcWAnwUnjc8wqaaFKqe4AWKlkSYoWK+MiJFi+1EZZuwCW3NMQYKDv/7f63mly/08lxlTlzZ9fBeThHTGDrTJdoWxOjL2rPebKCAQ4NFwoYgGTZIlzxQPqmIiZCSYlmL7r0RX4By5SrCqswOtF2fvnyZTYuTHBgs8t2H2jlrRdMJUaqrK2i6+uqrZ3odAQEvax7f388//mIv+/ry+EqfjMOWrAm4J/tZdH3Fb/ZMPcN7rD+1Jcdnf38B0Ce4RNjAV+B5OkMAHobQafi25hhb1izgtof31+a3daVLeL6PMZ4j5Qzx8x09/HxHzxG37x5OTPF0R4Z7n+s+YpuJqP68S6G7DKUQ2PMhxVSh7Ctiph4lU3S03kYpxWDRqZVMQoZRyySVPZ9kxCRkGkgJJVeXwhIRE8fT7vEKge/7+CiipoHt+eMOZ+5Ml2oHmDal1MfwyEDSU3BwsIgQIBGV/Q9bXzTFQsRCJgOFMssao9z8zjPZ2ZXhpnt28HRHmlk7eOYhZdenY7BIujR1P7PpQAFSSnwlat6NPjqgMAxJseRWPtfhIFlWNJOG1J91tuhSKPu1AeDzwVOsHqbcPZfJjF+rF0IQDocDsXhAwBT5/qPt/N1/79TOx0JgVNr8fZizlvV6UUDWPtLQ1lc6c9adLfH1B/bU9CwLEyE2LmnQQdZ8k5ZMkeon41UCxplzXjo2fAU526tkiCTLm2MA5A9nSBddpISwqY+xaplleVMMUwoMIXA9xUChjBKKoYJDyfEoVqbaikp2ScC4w5ldz8evZI0mO4QL1YwVCkPoTISnFL4PvTmb/lwZ0xAcGiqwRS5g09IU179uPX/4ncdn9s2b5yjgwGAR51hFTNOB0FpGpYZnO1ZuHhX8KqhtA5Vtff1Yx/dpiFj05WzShbkJAKfKxCO7J6CxsZGmpqYj/jU2NhKNRmlra+Mv//Iv8U/kUdsBAbPE4/sG+PK9O0gXtT6jmrpOFx1KE41dn8eYEuIhAynA9hTpooslBcmwSciQdGdsfrGzB9R8CzFeuih0ZiJn6xls6xcldclOaQ2T6yuSEbMm5HZ9nTGyXZ/9fTme2D/Ii315/MpnVj0J2o5XE4Pbrlcr8S1tjNQyS9VsQz14Sh8zrq/tL6KWxEcLxG9/uJ1t7TqburmtmVOXzv+MxExTdv1ZHc9zBIraoG8YDopGtn5Ul6fLr5XbKgGUFAJLytoA8FSs/tFJc8mUM03f+c53uPHGG7nmmms477zzAHjssce47bbb+NznPkdvby9f+cpXCIfD/Nmf/dm0Lzgg4KWC7yu+eO8OcrZHJXM9fJ/SLdKzWME6bozK1aZpCFR5xO2V0lXIFJQctzIAFYLrqtnDV7CvN0fMMvB8RduCGEIKutMlFqfCxEImOdulP2fTky3hK/15TqQ5q4qCLXwEsKYlwXu2rOSctib+6Zd7MaU8Ll2XgcB2tUB9XWuCoaJT070ANEQCi8G5RGcQ/dqwY5RCoo8Lz/MJmRLH9fHRHXdKgacUBnoIspSCZNQkFpIcGCxy6tJUzaJgvjPlI++2227jq1/9Ku94xztqt73pTW/itNNO45//+Z954IEHWLlyJTfddFMQNAUETMLO7gy7urP6ykxpk8mxzIYscjpnoFVPpiPPtZ6vsAz9Xx+BFLoLsCURoi9XDjJOs0TZUzx7aAgQWIbuXMuUtFHk2M/AEDqDVJhEqa+g0h0FH3jlKk5f3sizHWm2d2ZoiJj05MQoMfBUcHyfBbEQK5riNMYsLEPWdC8A+wdKLIhZ9J8gJZ2XEgJY1hRlMF8ma3uEDIEQkoLrAz6WFLQmwxwaLOJWPv+QqbvnnMpA7rApWRgPcWCwOGoA+InAlIOmhx56iFtuueWI28866ywefvhhAF75yldy4MCB419dQMBLmGc70jWNyESnJh8IGWJSr6VjJWIKSu7kIvOpImBCEYvWP+grUk9B2DSIVkt5jo8zz/VbLwVcX3etKXTpFMYPmD0FxQkCppHZTx8olD2+cPfzWKbE87XAl6pZah3IaulGadG65+vZiKsWxElGdMkmYhmjdC9l1+O05Y3sOJyhO3ukXUbAzNEUs4iYctS8vrE+TTHL5BVrmkkXhn2ajIqJbtWnSSEmdWefr0w5aFqxYgVbt27ly1/+8qjbt27dyooVKwDo7++nqalpelYYEPASZFv7AN/69Yt1ld4sQ+JWTC2nM6xwPO1WPF2xilI6FW8YAkaIvCv+l7VUvq8UQkA0JJFFgSkFvgGOP5xrmyj7VW1f95WatnW/3BACGsKm1tFRcYYfUUozKsfE2Le3+pmMPWYVkLE9GNkQoEAodYS2ZTyqJd1qd54Q+vgY2QQxVvcSMrVL+KnLUmxwXV7sK5AuOXieQqBwlWJta5w9XXlMCR5ab+X742d0A47OooYQjRGL6153Ms2xUOAIXi9f+cpXePvb3859993HueeeC8ATTzzBzp07+c///E8AHn/8cd75zndO70oDAk4gjjb5/Qv/tYOOwVJd+0pFLeJhg4F8mYgp8Xxdvjje7nZPQWsyRCJsMFRwMaTgdZsWYQrFT3f00JMpT0lPJSolHSklAh3kmRJMqaMmQwokCkfp7ZY1RsmUXLIlF9NAu1NWmOgkKxgWF6vKid2UlW69IIg6KtXTk+sPv8dVywR8VQucRgZRVab69la3rzp3T9ToJQXELJOi4+J42uTSlFokDNquoDdnj9K9rG1NVMZ7GJimyfpKq7pSunvv1KUpvvr2M7j+P55me2eatmY9Nsb3fR56cUCLqKf4euYT01lSnwyzkvkLmYK4ZbJhyfAolypHswnYtCQ1J8OzZ4opB02XX345O3fu5J//+Z/ZtWsXAJdeeil33XUXq1atAuDaa6+d1kUGBJxIjOe5tG5RkqsvaOOsFU3c9lB7xRGZo4plY5YkGjJ49YYl/NujB7TDdqWslS05x20O2ZMt05OFkKFbyJ9oH+D9v7ead25ZRb7s8n9/vpsn2gcnHD5rGfrH01cKU0gdyPl+raRYEwwbVAw6taYpGdEDbZemouwqZSk6fl1ZLyn1ibG6nSQQlNdLyBQ4rqp0aY5+09SINqyqVcB0oQ0wh7VsIxHo2XfVbipdOtSl24glydsuvTn7CN3L1Re0cdM9O2gfKNCSCBOpzKcbua1pynG3W5qKjPIZOxGDJ0OCqoiqZwqBDphEZXxLYzx0QmmPZgqh1Jw2Lc47MpkMqVSKdDpNQ0PQ1hpQP76v+NrPd3Hrb/fpGn5l8GikcgJY1BDhqle08a1f7wMU+/sLCAH5cXyOQP9otS2IEQuZ/P07z2Bb+yDffFA7Tld9jywpyM2ANUHUlJzd1sh1rz2ZsCX498c62NmVwXY9YiGD5U0x1i9JcurSFN2ZEr/Y0cPzh7MUbQcfQUsixJKmGM91DDJQ0HPHBJCKmmxc0sCB/gLpgm6xc3w9IgalmOCtqL0fhtDlIV9BxJS87pTF/Pdzh49Z87WyKcyKpthRHcF/u7uPnz7fTbbkDvvRiOH2acHcO4BPhoSKr47+26w4M1fvm6j0O11BhUCX4EKGxFPaebxYdhFCYBraFypiaWdyz9dGnKYUhEyDda2JcXUv4w0UHm/b8bazpOBQuki66OBO4LY/F4RNSdQycDyfkuuNm50zBMTDJmesSNEUC3P/810T6s+OlZpxq9Tf5S2rF5wQ2qPZOH8fU9A0NDTEY489Rk9PzxF+TO973/umbXFzQRA0BRwL29oH+Puf7eLhF/vxlS45mFKfJHz0/09GTFYtiNOVLtIcD7OjK4tZMbIcK4I2pM78LEiE2byyia+980ykFLiuz/07u+lKl1icitAUtfjj7z1Jujj9XUQCaIyZGFKSLbm4vvaFMYSgMWbRkozUBm6etaKJr/18F3c8eoBMSc+8k0KwMB7i909uIWoZPLS3vyIKnfwH3hCQCJtYhkQIrWcplL1RpaPmeIhPXLyeDYuTXPPtx8Y12KyHv7hsIx/4X2vq2vbx/f1c94On9JT4ys9m1eTRMgTZkjdvTr7jYTCs55ksqzcy+xkydBBzPAHhomQI19efY9nziVoGF65v4bzVC/j5ju7KoFlFMmKxrjXBVa9oIxk1xy1tj2WyMvjRtvN9pb9LQyU8pVjfmmBXT66S7RKsXRDjrqcP8dyhNP35ciW4UixKhlmzMErWVrgK1rUksAzFr3f3U3B8IqagMWqSs7U3lkIPcj53TSPPHcrSnysTCxu0JiPELJPmpIUhBItTUU5bpkuQu3qybO/M4Po+uZJLteCdjJiYUs9y3LC4ASkF5bLHdx9t50B/nlzJ0c7bUrJuUZxNSxrIlFwyeYfnu9IUyz7hkGRhLARSoHzFQN6h5Posb4py4YaFHBoo0Z3RthObljTQnAidMNqjeRk03X333Vx55ZXkcjkaGhpGdUgIIU74gb1B0BQwVaoapZ1dWYqOp4eajshCxEMGroKoZdAQNREIWpJh9vfntZ5HCj0uZcRXsXpVvq41wefeuGncK7xt7QPcdM8OutIlMiWHckUEa7vTe+oW6LXbnp4lVy3frFoYRwqtuTpnVTO3P7y/0k1jYBkCz/OxK5fKMcvQYuE6MSVcc8Fq3nbOctYuTPBCV5YHXuimUPY4bXmKSzZqXcV7tz7CQ3sHjjlY+dxlG/nfdQZNoM1I/+L/PUe66BAPG8RDJlnbGTWkt1KxnJeZp6omrPoZjmc1oKDipSVYvTCO6/kkIiY526O9P1/TktWDFHDWikZMQ9I5VCRiGVx74UlcceYypBR1Bz0BAfUwG+fvKWuaPvnJT/KBD3yAL37xi8RisZlYU0DACYPvq5pGyfNH2AfU7G8hX/aIWgZFxyUaMljZFOHAYJGGiEWu5OJ4PhHLwHbc2olXIli/KMkVZy4jHjbxK4ZwY593qOCwYXGSdNGlY7BAvuwCalpnoCm08JxKBs2oOD8fHiqyZXUTu7uzbP31UC1IcH2PkjPsDFzrrpoCrg/3PHOIz75+A6YpOWV5ilOWjxaTPt+Z5sn2oWMOmAwJG5dMzVDv3NXNfOHNp9bKPVnbpTdbRiEwpX7F862zb2RwZBl6TE/VbNCpfGjVI8tXWrDfGDNZkoqSt108X7EgHqYlKRgqlBmagjdSxDIYKpQJWyZnr2w6osQjpTgh5o0FBFSZctB06NAhPvaxjwUBU0AAsKsny56eHKYUOBPEBV4lcNL6JZei69GXLeH6WpekUNoEsOKavawxSipqUSx7fPfh/fzg8YO1Mlj1hFN93tZkGFEpl6WiDeRtD8f3OTBQoC9XHn9Bx4Dna3uCamZZSj2c9on2IQrlI8tSasx/j4XeXJn7d3Zz6alLxr3/nmc7KR5jcCgFtCTCLEiEp/zYzW3NnLWiiV09WZ7tSPN/H9iN4/qELROllNaYzROpqGUIopaBAGzPZ0VTjOZ4iFjIoDNdZG9PnpNa4jRELXJ2xWcnbJKIWPi+IlPU5Z6S4xEPm6xpSfB8Z7ouDc2ihjB/+voN+ngOskgBLxGmPHvukksu4YknnpiJtQQEnHCkCw6245IpOpO2HFVLHumCw77evJ79he4oczxwlWJFU5Q/+v3VpKIm6aKDZUgSERNTCrYfSnPTPTtq87fSBYey6xGxjNpzCCFIREyaYiFOXZpiYdyqeSQdL0fEAJXZYuMFTNOFr6ArPb4tg+8rfru7/5j2GzYlzXEtbj3W0Q3VDMnK5pjuPBPUhP9qHqWZpBj2xzKloDkWIhE2kUIQNgwMKQibkoaIxdJUlKWpKMmIhUBrkJIRi9UL4/TmbJRSNEYtNi1tIGJOfGAJod3ev/Ges3jL2cvZsmZBTX8TEHCiM+VM02WXXcanP/1pnn/+eU477TQsa/SQvcsvv3zaFhcQMN9JVZxtS46eEn+0ThwfGCq6GELrhIxKF5Pt+gwWHJ5sH6Ina+N4Pj1Zu9YlFwtJSq5Xm7+Vilk1g794+MivccnxaG2I8qev38g3/2cPg3lnXMF5vYw0d1ZqWBg8k+GBFLA4FRn3vl09Wboz9flcjdonsKQhTHMiPC3t06mYRdgyEJX2b9f3582sQAnEQyZFRw/TTUZM4mEdZCulyNsuCxMhcrbLwoQapU8d6Y101fkr+dK9O2tt+8mwxUktCXb35FDoYL8pFmKwWCZb8lgQD/HXf3Aq566a351WAQHHwpSDpg9+8IMAfP7znz/iPiEEnhf4rQa8fFjfmmRJKsLBwQIRU1LwvboEwAoouT7xkEHUMjClIGe7bDswWEn/CkKmxJB6NEXO9hB4PN0xxK6eLOtbk6MM/iY64b1183LWtMa57aF2nukYomOwOMppuR4MdBZFe8KMVgFPp6P4WFoSIS7esGjc+x7bN0B/furlRwW0NET47KUbpqV9en1rklOWNNCdKZEtOfNK/N0QNViSirKnNwdKsTAewldQKle8j2IWH9i8mh9t65jU72hzWzM3XraxpuPqy9mETIMta5pQSjCQL5MuOkRMk9PWNJ4QrekBAcfKlIOmsRYDAQEvZ6QUvHXzMp48MIjjK0KmQXEicdMIBDq4KTmedkA2JMLxsB1tDJmoTHH3fIWv9LR32/Hoy5UZyjtIKeoy+JNSjNLgPLZvgAee72ZPb4500cF2vFHu0LXXhTaS9HwQUmBKiae8I5y3ZypgChmCj1y0HnOcMpDvK36xo2fKz20InTG79NTF03ZSl1KXviby2porJBAPWyjgvNXDwU3HYIGQaYya+bVhcfKIgGjsTLCRx9DITjcg6H4LeFkx5aBpIoaGhvje977HRz7ykenaZUDACcEVZy7nx08e4qmDaUqOe/QHMGxH4HiKsudXdCc6eJFS4vqKouPh+XrIrai4JbtKMVjUGZaJMgDjDcGsanA2LG7gqi1ttRNdMqo78+559jC/2NHDQL6stVFhk1OXpVicinDPM53aUNMf3RE3U6SiJp95/Qau3NI27v07uzK0D+SZqsWcr8CSgiWN0elYJgBfvHcHdz/dOW37my6uf906zl21oK7gZqKAaGzwM1GnW9D9FvBy4rgdwR944AG2bt3KnXfeSSwWo7//2MSZ84XApyngWNjWPsBn//MZ9vTmpxxQyIqjdNgyKJY9PbzUVzWDSCF0dsWvBFp/8aZNXHPB6trjp8vrZqL9uK7Pn//kOe599jA5251whtixELUkbzxtCemSS0PE5FUbWrh005JxM0wwbCL6yL7+Y1rHwkSIRz570YT7nwrlssfpn/8ZpWm0d5gOWuIhHr3xtUHGJ+Blx7z0aQI4ePAgt956K7feeisHDhzgXe96F3feeScXXXTRdK8vIOCE4KwVTSSiphZMT8H8DyqdaQJsx8MytJjcp2qSqGqda7JSXvqfnb287xWraifFer1ujhZcSSlqbsTpgsPOrgwI+PGTh7jzyUM4nj+tnfQC+PwfnMLbz1lZ1/Y1M8+h4jEHbhdvWjTlgKn6vg3lHQaLZRqjFk3xEL96oWfeBUwAn7hkbRAwBQTMEHUHTY7jcNddd/Gtb32LX//617z+9a/n7/7u73j3u9/NjTfeyKZNm2ZynQEB85pdPVkG8w4hUxI2DcqOV7eHkCl1pOWp6lBbjVfRXRuVdvZq2awrU2JXT3ZKZZHx5m9VvZ9OW5Liu4+2s619gBe6cpQdl7KvKJa9il7HxRszxHU6SnSnLUvx1rNXTHj/yJExrQ1h/vvZLoYKDpHQsWWJQobg8jOWTukxj+/v5xsP7OG5zkwly+YTNiXJiEW2VF8pdjZJRUzedc6quV5GQMBLlrqDpmXLlrFhwwauuuoqfvCDH9DU1ATAu9/97hlbXEDAiUK64OD5CkMIBBAyZW2EyHiT3as3VUXgZc+rjbcYiyklUoJlSFY2x8iWHNJTcGWuZmiGCg6JsEkoYuL7sP1Qmmu/t43+fHnczE01s1UNmMYu7XgCp0UNYf7y8k0TZkS+/2j7qOHEAL5SREwD2z020XVzPERTPDTpNtVA7fBgkV+80M2jLw4w1sfRK/sUyvYxrWEmiYUMvv3+c4MsU0DADFJ30OS6eiK1EALDMI7+gICAlxGpmEUyYlEouxQdH8sQtTlfsjK5vRpgiMowXykEqxfG6BwqYbsTd6LZnk9T2GTNwiSWIbBNg1TMGn/jMVTHrXRnSkd4P5VGjG0Z97EK5AR+TFVB+FQxJCxORrj53WdO2MH2/UfbuemeHXq8jKnn2Gmnc0W+fGwBUzVbt3ZhYsJtqoFaV6Y0afmv+l4Yle7CucaSgnNXNfPJS9YHrf4BATNM3UFTZ2cnP/rRj9i6dSsf//jHufTSS7nqqqtG+cMEBLxcqfompYtlyq5P2fWRFW8jUTnNGgJMQxIytPdSsjK8N2e7R22f93xFMizZ01egrTmmheFj5tGNx66eLM90DDFUcFCKmvdToTx5wFRlumKCqCVpjFo0xkN8/vJh48ORJbjFqQivWrOQ//vz3ZQrHlamIUEpPHV8K7EMiWVI9vTlRpU1q3ql/9zWwe0P76fsTm5OOpKZDpgWxk1OXdrI8qYwBUexIBkiGba4cEMLEsGOw1mAURPvAwICZpa6g6ZIJMKVV17JlVdeyd69e7n11lv52Mc+huu63HTTTVxzzTW85jWvCbJQAS9Lqr5JHYMFQDty520PV2lRtylgVUucwbxDpuQQMSXLGqPs68tPWr6rki15PLp/ENBeaR/5t9+xJBXhrZuXccWZyyc8YQ7lnYpdgCJWcQ4vu35ds8OOxmTBRfU1CPT8s0UNEc5YPtr4cLwSHOixMgLIlT0M6WNAXQHeZCxIhjClqJU1fV9x11Md/GjbITqHiuzvL8yojcJUEMAbT1vMNa9cPWnm6NRljbO2poCAAM1xWQ74vs9Pf/pTtm7dyt13300ymaSvr2861zfrBJYDAcfDSMF1tuTgeD6+0noTszIyJV10iIUMFsRD7O7JjQpgRoY+Y7+YliFY1hihUPbJlVwcX49u2dzWxCcuHr80c99zh7nuB08RMiQ+Wtw93YaUEl1ytAypNVC+wpCCpliI9YuSvGZDK+etaR7VrTe2BAe69FZdm2DYhfxYl1stjyoFa1vjWIbBRy9aS2/W5s4nO9hxOFPLFh3reJmZwBDwB2cu5dRlKZY0Rrl4w9Q7/gICXo7Mxvn7uH2aqvT29nL77bdz/fXXT8fu5owgaAo4Xsa29q9dmGBPX672d7bocvsj7Tx9cIjOIT3WpKZ3GrGfI4ImqQt9htST66WAguNhSsm61gSfe+PGIwKnh/f28cHvPoHt+jjHMeNjonEpphRsXJLk6gtWsWlpA5mCO6otfzzPKNf1edVXHqQna5MMm7i+Iltypz3TY0jwfd01tyAZRlTW25XRs/0A4iFjVLA2nxCAaQhak2E+9Oq1E5p9BgQEaOatT9N4tLS0nPABU0DAdDCeb9LYvze3NfHT57v4m/t24vqKjsFi7b6Jzt8KVcmMKJSSSCmJmAaO59Obs/nGL/bwR7+/ZlSw0hQPsSAe5sBA4bhekxauAwgaIhaRkKQpZjGQd1i9MMFbzpq4RDiW+3d205crEzENPJ8ZCZhAa44kEAmZDOTLREyJ4/l4vl9zZC+UvWn1nppOFOB6iq5MiZvu2QEQBE4BAXNM3UFTU1NTXaLvgYGB41pQQMDLASkFl2xazL3PHOZ3BwaJWpKi408YPBjVESuVclN1Zp0hBSVHkSk6/HZPH9sPpUlELE5Z2sA1v7eKs1Y00dIQpv04gqaq9QBod/Jc2aXgCGzXZ2EizJ6e3JR8o7rSpYqGSZGZoYAJdKCXilrkSg62pyiN0XFJ9Hs6T2MmQK/N83Vw9+V7d3DqkgZOW94YiL4DAuaIuoOmm2++eQaXERDw0mY8N+7fHRxksFCmP18+aunMr5zdTSlQKBxf6SwJYLs+dkUpnS665GyP7myJF7qzfOktp3H6shRPVETkUyVkCOJhk7LroZSodN9prVG25FKwXRqi1pR8o1qTYZSC7AwMuTUlNEYtLjt9CasWxvmXX+3DnuC9HWvYOd/J2h5/8M2HOG1Zir+6fFNgLxAQMAfUHTRdffXVM7mOgICXLOO5cTfHLXqyNq6nWNOSoDdT0l1kIx6nO88kvu/jVUazjNQ/jXUclwIilkQIQdnzae8vcPP9u3nXlhV89+H9x9SBdtrSJLt7C3g+xMNGLcjQWS6DfNklW3JJRur7KdnWPsC9z3TizoCIKGpJzlnVxHWvXc9ZK5r4+A9+R39uchPK+ZxlmohnD6X537c9wbeuPicInAICZpm6WzIGBwf5+te/TiaTOeK+dDo94X2zyapVq2oGnNV/X/7yl+d0TQEvL3xfsbMrw6Mv9rOzK8Pj+/u56Z4dPHcoTUPEZHlTjGTE5KmDadr7CzTFLBY3RFi1ME4kZBAPSSxDYAgdpCQjJvGIRbUac7Q2/+q8OlNoDdRTBwdZ2Rij+ShO2OMRMgTvrGpoBBwh/hn59yQpm+p78t2H9nPjnc/x+DFmvcbDrDxvY9Tk3//ofG57/xY2tzWzqyfLc53pUcHZiZRVOhqDBYe/+sl2/PmoYA8IeAlTd6bpG9/4Bs888wwf/ehHj7gvlUrx61//mkwmw4033jitC5wqn//85/ngBz9Y+zuZTM7hagJe6lTLboP5MtvaB3hoTz9dGRuBImyZpItllIINi5OjNIFKKYSAjqEiqahVO7lHLBPLUORsF9dThE3dNRcLGUctZ3mKmkaoeip1XI//3t7F5WcuY+uv900ps/Le89toa46TjJhkSy5F1ydkSIzKaJWyp/9ORkyyxdFz2Krvy2MvDvCLnT10Z0rs789ju8c29He87j1LChAQNySffv0GTlvRWLsvXXDI2+6o56r3aet1+pbAG89YylltKf7PT3bUuffp4/nODDs6M5yyPDXrzx0Q8HKl7qDpRz/6EV/96lcnvP+P//iP+dSnPjXnQVMymWTx4sVzuoaAlwfVstszHUN0Z0o1obEe6GoSdhXdGRvLEAwVnNrcM8fTgu+IaZC3XfK2h2XI2rgVWRm94iutGzINsOs0o3QrA36rgnEfuPuZw1z32nUsTkXoz9mUj6KfEsCihghvP0cP001FQzRGLfpyZfJll7LS+09GTBbGQyjEqLEu29oH+M5v97PtwCC9WV0eCxmi9v5MJWZqjJqYhiRTdHA9VStfCrSYfmEiNG47fipmYUidSK++F0cT2YdMgfK1ZswbZ2sJLG0Ks6IxyinLGvnUa08mUilL/q49zU+e7pzCKzt+PAVf/fkL/MtV54xyVQ98nQICZo66g6a9e/eybt26Ce9ft24de/funZZFHQ9f/vKX+eu//mtWrlzJe97zHj7xiU9gmtPmrBAQAAwPwe1Kl0gXyzqDUrnPdn3K+XLtRO35iu2HM5y6tIHGWKgWICml8BU4vk9jLEQ8bJAuaEPM4bhGMdVxa74CUwh8FIbQg25/+UIv57Q1sb0zQzQkebE3T2mcbr1ESJKKhTinTZtRAqxtTbC9M82mJUkKZR/H97GkJBaSHBgscurSVG3bbe0D3PDjZzk0WKTkaP8jBTWhu0QHMfVYRjXFLP7lvedw1orGWlDQGg/jS0VftjxpgLC+Ncn61gTdmRJKaW+r8XRUUsDKBTG6MzZhQ5AuuhOOjvGBgazNdRedzIrmGPuHCjVrh5vfeSamgB8/NbuB0y929nLG53+G66vaTMGJAsmAgIDjp+5owjAMOjs7Wbly5bj3d3Z2IuXcXt187GMf4+yzz6a5uZmHHnqIG264gcOHD/P3f//3Ez7Gtm1se1gsOte6rID5T3UI7mC+TNHxKDr+qNKRQmc2qsU4gS5lvdCV5eTFDaRilg6Qig6mFFhSIoDGWIjuzOTC5XqoCsaF0BmXZY1R9vTk+N//axWHhoqkiw5rWhIc6M9je34tqFiaiiAqWaP3XdBWa2u/+oI2brpnBwcGi7QkwjRELEqOx4FBXVqsbuv7iq/dv4v2/gIoVbNIGBkg+dUFHoWoKbnlqs2cu1oLnS89dcmU3gMpBR+5aC1PHhgkZ3vapXzMWvR7btGSiNCbtSk5/lFn7RVc+LM7n2VFc4ywabC2NcGWNc3c9+xhnulIT2gCOpPkyx4xyyAeMnA8RU/WDnydAgJmiLqjnLPOOou77rprwvvvvPNOzjrrrOlY0yg++9nPHiHuHvtv586dAFx//fVceOGFnH766fzJn/wJX/3qV/n6178+Kigay5e+9CVSqVTt34oVK6b9NQTMf8YKuEcKbMfet7M7w56eHFJAuuhMqNERohI4VQaxOb6iY0gHFMsao7XHFcou/TmbjuM0oBxL1DJYvTBB1DIoux7LGmPceNlGTlmaQiloiFpETIOopUe6RCyTU5eluPGy0c7im9uaa4/LlFw6BgtkSi6nLh297c6uDM90pBFA2NIzKKdqQi4EJMMGn3vTJrasWXBcr//cVQv47Bs2kgiberzLmIApFtLvTyJsELOMI7oRJ6LsKRzPpyFisq19gL+++3ke3TdAvnz0wcszRdnz9ftuSpJhE8fz+eaDe3CPd2hfQEDAKOrONH3kIx/hXe96F8uXL+faa6+tDeb1PI9vfvObfO1rX+Pf/u3fpn2Bn/zkJ7nmmmsm3WbNmjXj3r5lyxZc12X//v2cfPLJ425zww03jHIyz2QyQeD0EmesZ1K25HD7wwdGWQKsbU1w9QX6Kn2sXUBTzCJdsMmXdZZmonKTP8YHyJCCnO3Sl7PJlz1ak2FytsvO7iy+UnWJj+tFCljeFKMxapG3XUKmQSpmsWFxA2etaKq9/mTEBAHZolvzjxrPOHFzW/Oox4237fbODCXHJ2pJOIaMiwQWxC0+9tr105YhuXJLG+tbk3z9F7vYcThLoexScnwMKWiImBRKDp2Defpy5Snt99BgkTUL4ziej+35MIlmajZwfYWnFKYQSCGImAZ9uTL37+yecpYuICBgYuoOmt761rfymc98ho997GPceOONtUDlxRdfJJfL8elPf5q3ve1t077AlpYWWlpajumxTz31FFJKWltbJ9wmHA4TDoePdXkBJxhV8fbu7iw528XxfAplj3jIoG1BnIgVplh2efLAIE8eGKyIqgWLGiJErLAuSw0U6Ms7tQ44IQQCNW7GSYiKDYAA1/PwfOjOlGiIWvRlbUquP5yNmkY8BR2DBRJhg6GiM0p3NN6Yl3qo73EKUdFrTQUBJCIGliG588lDbFrScNweRNXg+JlDg3QMlsiXPexKKdXzFIczNoePsRzqKdh+OEO+5M0Ls6exjhCWISi5iq50ac7WFBDwUmRKCumbbrqJP/iDP+D73/8+e/bsQSnFq171Kt7znvdw3nnnzdQa6+Lhhx/m0Ucf5dWvfjXJZJKHH36YT3ziE1x11VU0NTXN6doC5gcjxdu261NyPYqVYa2FskdDNEQirOgYLJAv6642BLQkQjieIh7W7thrWxP05WxK7rDQ2hACd5xAodrBBnp4rAJ6c2W6s8OZDVX7n+mlUPbY2Z1lfWtilEZppjhlWQMRy6DketoOYIrkyz6u5yCE4LsPtXPWiqZjXnM1OH5wZ/eMOI8DDOTKmIZWOMx13CSojrrROJ4WhS9OReZsTQEBL0Wm3FZ23nnnjRsgDQ0N8b3vfY+PfOQj07KwqRIOh/nBD37AX/3VX2HbNqtXr+YTn/hEMEQ4ABgWb3elS9oDydeBDuhMkOcr9vRmiZgGCmr3oSBTdNntZFnXmiQVNSnYHk0xi860jUKfrHTn0pElKcXwuI7qXbOle1Ho533v+W2TZm3GG/FyLMHKhkUNnL68kcf3D0w4umQ8DAkCbbFQcrVH1e4pzrOr6s62d2bY35/ngee7OTRYIFueOU2Pp8CoBMojP9+5wJDDx6x+H3X59+INi+ZwVQEBLz2Ouxf/gQceYOvWrdx5553EYrE5C5rOPvtsHnnkkTl57oD5z66eLLu7s9iuj+sroqbEqUQvUgqUpzVFRcejsWI2WY2bLEO3q7/YlyNkSHK2U9MfqYovki90Jmki5uqEakrJ7u4c//HEQU5Z1sCGRQ2jAqLxRrxU9VxHK4+NF2x94uJ13PDjZzkwBVG7qAwCNio+VbmSS7bk1D3Pblv7AH//sxd46mAa2/XxRoyamWlCpsTx575EZ0qJAsqVDGrIkHzo1WsDv6aAgGnmmIKmgwcPcuutt3Lrrbdy4MAB3vWud3HnnXdy0UUXTff6AgKmhXTBIWe7tROKEAJZ0SNVxdy+0v8cT9U8lABcT4tsC2UPSwKVkzvo0pvytaeQ7frkp2qqNMMMFR3++VcvYghByJKcubyR61+3ns1tzbVy5VDBoTUZ1noux+N3BwbZcTjDtReexBVnLhs36zRZsPWlt5zGP/x8N7/Z01dX95znKwypAycpdIDq+WqUYeZEbGsf4LofPMWhoeKsd64JIGRIXEMfH0qpY5rvN9XnlEIH+gKBaQitX3J8sraLFILWZDjwaQoImCGEqlOx6TgOd911F9/61rf49a9/zetf/3re85738O53v5unn36aTZs2zfRaZ4VMJkMqlSKdTtPQMHWxbMD8ZGdXhj/+7ja6syXilqGDJSBru7iVdu3qCb4aI0x0Eq4NrTUEIUPOu0BpIqq6l2WNUf7+HWdy+yPtPHcozaoFMYQQDBUdOgYL5EouZc8nahm8an0L1/zeqlFZpyODLYOS49Gbs0lFLW68bCOnLUlx3pd+ztCY8SoTrk3oIcC+r/AUnLUixY+u/b1Jy4S+r3jv1kd5+MX+WqfibMZNlhS8/tTFvOKkBTWfprztTtlmAXQ2M2pKVjTHKDo+juuBECTCJotTEU5qSbCnJ0d3RpeXDSlYvTDOhy5cO8r8M3AED3g5Mxvn77ozTcuWLWPDhg1cddVV/OAHP6iJq9/97nfPyMICAqaT9a1JVi+MczhdxFN60KtAexnlfH9Uu/9kIzeAiuYJYiETU0DJ8Y7pRDmbVEeFKAUdg0U+d9eztaxENWDa3Z3F9RQhU2IZkrLr87uDQxy6Zwc3XraRs1Y0sbMrw9//bBfd6RJLGyOUK+aY8bBBW3OM9oEC332onQ/+/ura2JR6UEoHQX6l3HnlK44uXN/ZneGpjqFacDtbH0HVD+mDv7+GT7x2PVIK3n3uypqmyvV9MkWHwbxDJGQAiv94/CBZ2yNmSWIhk5ApyJRcQobkNRsXce7q5lqwM5HGbDLtWWArEBAwO9QdNLmuWzOTrHo0BQScKEgp+PBrTuLpjiFytkvMMjAN7cRtCjFq1lg9J18hBKao+uPM2LKnjbFrfKE7R9QUbFiaIoa2J3A9RTRkVNrXVa1zMF10uPn+3TTGLLYfznCgv4BSiu6sjSl1iSgeMlneFKMlEWZ3T46f7+ihPEXjqapg/qTWBFecseyo2z/bkaY0Q51xkxGxJDe+YRNXnT9c/pJSsGlpik1Lxx+e+7/WtYwqZ0ppcO6qFO8bRzs2kbXDsVpFBAQETB91B02dnZ386Ec/YuvWrXz84x/n0ksv5aqrrho1uT0gYD5z7qoFfOqSk/nKT18gb3tIz8cQgkjIwLc9pASFoDxCmDJRycdXWsfizbaQZhopuorth4ZYszBOpuhWugj1e+JVdF4hwyBi+jzRPsiCRAhTaj2XEDozpJTClCZZ22V3T5aTWhKUXY/OY9QYGVKLma//j6cnFKP7vuLHT3bwjV/sYbZDpkXJME0xi3NWH2ljMlkmqB5z0GNhujof52r/M8GJuOaAE4e6NU0j2bt3L7feeiu33XYbhw4d4t3vfjfXXHMNr3nNa074LFSgaXrp8/i+Af7xwT3s78/j+drPpj9fZt2iBHnbZU9PbtQJf7zASQpIhk1KroftnriB00hkpWSpRdmCxpjFpsVJth/OMlgoc8qSJAcHSwwUypXBu0K7UBuSRMig5GodVGsyzGnLUvz7to6jPqcpoPr2NcdM2hYkCJtylD5qrJ7q/9z9PM8dSs+a8FtbIoDnQypqsSBu8cW3nD5qzMvxdCEeKzP9nHPxmo6XE3HNAdPHbJy/jyloquL7Pj/96U/ZunUrd999N8lkkr6+vulc36wTBE1HciJczU51HyO3HyiU+foDe2iImCjgmY40tutVhNPD3jcjtU5SQMwyyJ0gIvB6qBiX46NHmqxtTdAUC/HsoTQAJ7XGebE3V2nr18GEqphBJcO6061Q1jPpBopl9vcd3XbAMvT7u64lweJUpPZ+K6VoHyhwypIG/uTCk0gXHba1D3DHowc4lD7+ocZTodqxptAWA0tTUb551dm1Ulk9wvhjOWFPdkzPxHOOfL5DQwVuf7iddNGd1tc0k8zU5xBw4jCvhODjIaXk0ksv5dJLL6W3t5fbb7+9dt8dd9zB5ZdfTjweP+5FBswdJ8LV7LHsY6Q+xPcV9z3bxfbONCubYyQjBuWcVjkJpfAB05BYUozqlHMnM2Y6AVEMB4UKaB8ooJSP4/s0xSxKrk/J8Wvb1aqYCmzX02Nl0IOJy45/1G42AVhSsnphjMWp6Oj7hCBiSn65q5cn2gcZKjgUnLkJUBW6k9KUevzKklSkNpKmapo6VHBqXYgA8bBJLGTUhPFTdTef7Jg+a0XTtD/nyOezXY/erI3nKzYsThIPm9PymmaSmfocAgLGMm19qS0tLaPct//4j/+Y7u7u6dp9wBxQvXJ77lCahogW+jZETLZ3prnpnh1sax+Yk/1X3Z8ffbGfHz95kC/81/NH7OO5Q0N87s7n+O7D+9nZlcGfpJYjpeDqC9pIRS0ODBRoSUYImxKlhsXJlgRPKSxDEAvpElQyYk3fF2geoeftaW3RvoEiAoVlSDoGCrXW/rGvu1iZ6ZaMWOTLLgsTYSKWZKLzkymhOW7RHLdoSR456mOo4LC/X9sfdGVKcxYwValmHU1D8NbNw95Vu3qy7OnJ1boQRz1GiJowfldPtu7nOtr34q6nDk3rc459vuZYqOZNtrsnx9AIk9FjfU0zzUx8DgEB43HcjuATcRxVv4B5wExfuR3r/uu5InY8Rd726Bgs8rf//QIrm2NHzTxtbmvmxss21vbdFA9BwaFcGajreLpr6oxVKT72mvUkoybPdqT5m/t20Jevz7n6RMCSQht2KlUbJ6MUHBoq1TJHE3ULlj1tABq2JCuaYjRELdIFB18p3ErQWjUSbYyFOG1Ziq50iZLj1T47gMFCme2dGexqKmsaf0oEICVMsbEP04CQaXDWyhRXnLm8dnu64FB2PSLW+EO/I5ZBX86u2928nu/Fj7Z1YDsukeTxP+d4zzdYKIOAmKl1ah1DBVLRhtpapvqaZoPp/hwCAiZixoKmgBObqVy5HUsb9LHsf6xmwfMNDg+V8NFXxOsqJZPdPVlcXxE2DXylMKWoXaVPpmsY2eE0mC8zkC+TtR16MjaLGiKctizFhsXDY0jWtyb5r6c7+Z/dJ7aOr4oUEAubOsjxfFxPVf6/GrXNZALssuczVHAolV2WN8Uo2BkcTxG2DCSVrkNf0ZII86EL13L7I+1s70wTsST9+TJDBYeebInyDIrrxRRsME2p/biSYYNkNMTFmxazqydb0xelYhYhU2tnYiGDvO3h+D6WlMTD+vaQadTlbg71fS8OZ0qAOCLYrDKV5xzv+SxDIoXAV9rxPG/r4dWJiDnl/c8WIz+H431PAgImIwiaAsZlpq/cprr/uq6IBwuVURZ6thxCUHQ8TEOMMl6cLDsmpSBvu9zx2MEj9CRrWxOjHiel4COvWceTBwbJzoFf0HSjFORKDv4E5p5Vc8yJiIUMfF9Rdn0ODRVZ1BDBNCRFx8dzh9+fBYkQn7/iFM5d1YyUcN0PnuI3e/pr2aiZROux6n8eKXQ5FqGDlO8+tJ8fPHZwlL5obWuCbe0DuJ4iX3bxK9m0eMjENATntDXXNFBHo57vhQAWpyJ0ZUrEQsao4EopRW/O5tSlqbqec7zni4dN4mGDbMklYko9Wqii35vq/meL9a1J1rYm2N6ZPu73JCBgMl6KkoyAaWDkldt4HO+V21T3X88VcbbkkrXd2my5qp2AVfm7Hl3DVHVW565u5rNv2EgyfGJbbcBw6e1YQhft6SQIV8Z3OJ7Pc50ZipUr/3jYqMxJkzTHQsjKZ7izK0tPpcQ6W/LcevX7qxfEuOoVbTTFQoRNg8UNkSOOh98dHGTLmmYGK12YAi1gFwgGCmUGCw7nrWmuu4Rdz/cibBq8dfMyUlGL9oGCHt3iK/K2S/tAgVTU4n0XHN1RfaLnE8DyphimFFpLpnTweCz7ny1G6hKP9z0JCJiMIGgKGJfqlVtvzj5Cn1a9clvXmjjmK7ep7n/4ing4OKmejMueXykbDY/hUOhSUTxs1NL1Ecug7HoTZsfGZrPiYRNDCuJhk7bmGOmiw3cfaj9CVH7llja+/f5zedW6hSyIW1gnfvw0ZVRl2LGeGgANUQvLkBhC4Hg+IGiOhzh1WQOeUnz3oXbKZY9vPrgHXykaoybxihv5TP8ojQ0KDYbtFqr/IqYkbEp+ur2LTMmhbUEMBWRKDgpYWTkebnuonUf29tMUs2iKWSig5OoOw+ptj704MGkjwkjq/V5cceZybrxsI6csTZEpuXQMFsiUtN3DVFrrJ3q+xqjF2tYEppSYhmAwbx/T/meTqi7xeN+TgIDJmLHyXFtbG5YV1I9PVKpXbjfds4P2gQItiSN9T47nym2q+x9Ps1C9It7dndVXxEKfcMuewlM+phQsb4rVMhhHy44dj47r3FULuPX9zdz1VAdf/dku+nJllO/jqYmF0y81io6HIQWWKXE9xSlL9XvkeD6WIYmHTQQ6K7i7J8d3H22nL1cmYhoYUqLQwa8QIGbxffOp+EUJPd8tbErWL07ieT69fTaGFDx1cAinovGSQhAPGyxMhHmuMw0KVjTFiIVN8rY76vUWbHdK2r+pfC+mw2V8sudLFx3WLUrw3le0sawxekK4a8+U83pAQJXjCppKpRI//OEPyefzXHzxxaxbt65233PPPXfciwuYW8Z2lPXlbEKmwalLx5+ZNZP7n0izUL0i3tWdQ1bGgNiuT2PMZEVznMaoDpDq0TUM5R2yJYeQKVBQO8lXqUfH9eMnD9GX047Z4bCFIQUF26XovrQ8ncYiANfTJbZ1rQkKtkvUMjDGOVlV38eOwQJ+xcYBdKeeURnTUt3nTMdN1dV5vsKQgua4VTtuBgtlpBCUHJ+yp0iEDfAFnu8zWPAp2C5hyyBsyJrWKDFGhHws2r+pfC+mYx7dTH/PZ5tgRl/ATFJ30HT99dfjOA5f//rXASiXy5x//vls376dWCzGZz7zGe6//37OP//8GVtswOwz01du9e6/3iviXMnljscOUHZ9rMoJuJ7s2Lb2AW75n730ZG16czZmpftpeVOMxqguuwzky7i+YqBQxvfVEfvZ2ZXhmY40At2FVr03HjYxDe8lIRafiGpIGA+bXH3BKr754F56MiWSEYt4eDjIVUoxkLdxPKW1Z2iLiLCpR7dELINcyWU2QkxDwlnLU6RLLvv7C6xaEGV5c7z2uZlS1MTpvq/IFN1RQVzZBdv1Wd4Um/aurdnOmAQZmoCA+qg7aPrZz37GF7/4xdrf3//+92lvb2f37t2sXLmSD3zgA3zhC1/gnnvumZGFBswdM33lVu/+670iPmVZw5Sumqvi78F8mUTYpFD2MARkSy67u7MsaYwymLcZKriETME//Hw39z3bdYTv0/bODCXHJ2rJI0TNQkyl0f3EJVtyuO2h/fTlbIqOR9iUxENaUA/QMVjQGRwp+H9PdQKQt11MaeL4UHRmJ2ACLQi3XUU8pH8GY2Myi6jhTruJPreyp8jZDiXHY3lTVJfkyh6Op8vD/bkypy47tq6t2c6YBBmagICjU3fQdODAATZt2lT7+2c/+xlve9vbaGtrA+DjH/84b3jDG6Z/hQEBI6jningqV80jxd+rF8ZJF11292RxfJ0JKZZd9nZnEUIQtiTrWpOETTmJ75M6Qg9VdDwKZe8lGzBVhdtC6NEqzx/OcvKiOAcHiji+Il1yyHZlUErbEXiVNr2SMzxDbrDozvq6FTBYcGiOW7oLc0y05iqFIeBo+cGebBnLEPRkbWTFTZ3K/uJhY0rdcwEBAfObuoMmKeWo7opHHnmEP//zP6/93djYyODg4PSuLiBgHOq5Ip5sm7HDend2DuH6il3dOaKWZHVzlINDJYqOh11RIxsolFL0Z4tYpgFKsbsny6f//SkuWNfCpiVJMkUHKQS5skPMkCCg7Oluqpc0YnigLYpK6VKyfnEDHYMFskWH4pig0ZACCbj+VFyTpp/+nI2vfBYmQuRtl4WJ0LClhZSV/3/0FUohcJVP2auM3TEE0ZAkakl+tK2DDYuTJ5w2KCAg4EjqDpo2btzI3XffzfXXX8/27ds5cOAAr371q2v3t7e3s2jRohlZZEDAdDF2EGp3tkS2dGQuwZCj/Xw8BfmyT75sj9ouWyryYv+BIx6fmeqcjhMYAbU5faBDjP19eVY2x0lFLfK2hxpRdKu29c81Am1LUXR8rn/deu588tAovRyoSc08R2K7PqbQdhee0h2DpqvwTIPuTCkYFhsQ8BKh7qDpM5/5DO9617u455572L59O294wxtYvXp17f57772X8847b0YWGRAwHTy+b4A//3/P0Z8rk4yaDObL4wZMMPXZZC9ntD/T6NvytseOw5lxt1dQMR6dW42XZUiSEYNkxOLcVc1sWqK1cLu7sxwaKiKFYFkqyr6BQu0xk+WdRk5+0T5hMFR0sAzB0x1DxzxyKCAgYP5Qd9D05je/mXvvvZf/+q//4nWvex0f/ehHR90fi8X40Ic+NO0LDAiYDh7f38+133+SgXwZX0Fvzj76gwLqYrzxKqNKcWK059LRBv/ONNrfK8rSxigRy+DQYIF0wWHLmgX4Pvzjg3so9ufxfEUsbGIZAsebXBA+Hn7F8VMpSV/OZjBfnpHXExAQMHtMyafpoosu4qKLLhr3vr/8y78MvJkC5gUjNUupmEW25PDJf3+avpw+aY30AgqYeSYLqGYTCYRMwaoFcWLhI4fPbmsf4Ev36YHQixsiNUuLVNSqHTtToVq29FGUXcVQ8djmNAYEBMwfjtsRPJvNcscdd7B161aeeOIJPO+l60UTMP8Zq1kKmQbd6SL9I8wFg4BpdpkvlU7D0D5QHUMlfKWNOIUQnLUyxdqFCa7/j6dHDYQG7Tt1+rIU2w4MkSk6dQd8QuhmBKUUnq+wLIOmaGjGXltAQMDscMxjnn71q19x9dVXs2TJEr7yla/w6le/mkceeWQ61xYQMCXGG7abLpZHBUwBM0fEFPNG5F3FkLqTzTK0Y3nVgytkSDylcDyf7ozNT57pnHSEzsbFSRY1hAmZQu9Pipq9wHiv1xBCi+MrEWMqatIYD8ZKBQSc6Ewp09TV1cV3vvMdtm7dSiaT4R3veAe2bXPXXXeN8nAKCJhtxg7bFUIwVHDoypTmemkvG6QQSDlxJm8uzD09X5fHqk1rhhQ4vkIKRSpqsbwxylDR4UfbOrAdl0gyPO5+IpaBZUiWNERJRS1MQ49X6coUGSo4o0qQAq1nEkJgSn3LxsUNxzzcOiAgYP5Qd6bpTW96EyeffDLPPPMMN998M52dnbWRKgEBc83YYbtKKfb3548wLAyYOaSUiEnCorkqio4UnS9piLJhcZJTlqQ4ZUkDjbEQC+Mh2gcKFByfgbw9yo8Ohke/SCFoSYbJ2Q6NUYslqQhnLG+kKRbC1LZcGEIbWibCJlFLghAkIiYfes1Jgd1AQMBLgLozTffddx8f+9jHuPbaa0cN5g0ImA+kCw5l1yNi6UxB3vYolLXL9MthfMlco4fuqlFmkAJdvpqrLrnxGCzatC2IIqW+XhwqOBwYyNeG8/ZmSzTHQnpob8xiMF9mf3+eTMnBMrR3U6bkYrtZVjTFiFgGi1MRcraLFIqIJfF8KPs+vq8H+H7qkpM5d9WCuX3hAQEB00LdQdNvfvMbtm7dyubNm9m4cSPvfe97ede73jWTawsIqJtUzCJkGrXBqY7vo9CCXCGCbrmRSKG9leohZEgUCtc70rnbkgKzcn9zzGJhIkzZ9dnbl8P1ht/7uh0iZxgFDBVcnjmUYdWCOAA7ujKUHA+lQBq6nNebK5O1XRYkwhxOF/H8qsu3Imd7GFJQKHt0ZUqYUhAyDc5b3YRSgoF8mWzJwZCC1QvjfOjCtZy7OnACDwh4qVB30PSKV7yCV7ziFdx888388Ic/5Nvf/jbXX389vu9z//33s2LFCpLJoGYfMDesb02ytjXB9s40sZCBJSWmFHgVewFZOXePPX0LIBE2KHtaFKwqRo2GFHiemjedX9OBQAujq0EAjJ+Bq9bsUzGL1QtivNCTI2JCNGSQsz2UUsRCBqlYiFOXptiypplHXxxgT08Ox1dELRPPVCyMh+nKFJlPU2QUkCk57O7JopSqBUymIUiETcqeoui4FB2fjsEiAJaEaMhECkHR8TClIBk2Wb0wzh/9/hqa4qGaXqmeeYcBAQEnLkKNLeBPgRdeeIGtW7dy++23MzQ0xMUXX8xPfvKT6VzfrJPJZEilUqTTaRoaAvfeE4lq91y66LAwHmJff4GhooPj+ggBsZCBIQVl16PsQcSUtCTDLGqIAHr0heP5WIbEMvSsxb5cmTedtoSnOgb53cE0jTGLsuvTlZmf5piNUYN1rUnylUzIUN5BCFjUECFTLFeCQ/2VDxmSciWCkujskyF1q3zYkKxsjlFyfRoiJu89v41ljTGSERMEZIvuqMBgpDfWoaEC332onRe6sxSdeRQxVZCVoLj6PhgCEhELqxLg+EoxWNTi7qgpiIWt4SBTKYquT9QyaE2G+dq7zgxcvgMC5gmzcf4+rqCpiud53H333Xz7298OgqaAOWWkT1O6WGYg7wAKy5B4vsJTqjZ9/vrXrefxfYNs70zT1hwb1WqulKJ9oMCpS1N87Z1n8vj+AW6881mWN8V46uDQvDQqXBAPcdqyFD1Zu+ZRtSBh1cpG6WKZbMnF8xW+0sGBbpsXGFIQNiV2JS2UjJikoiHWtSZ43wVtUx42+5/bDvLZHz2LO0/LolXllSkgPiJgAj1EOF3xZIqHDKKWMeqxrq9wfJ/mWIivvP0MtqwJ9EoBAfOB2Th/T9ncUinFtm3b2L9/P0IIVq9ezVlnncUVV1zBFVdcMQNLDAion81tzZy1omlE1qPIgzt72NubH1drsmlJAzfds2PUoNaS49Gbs0lFLd53QRtSilGaqahlzLugaXFDCMsw+KPfX0NzIjSqRATDZaNqpihTcBkslmmMWqRiFijIltwJM0lTRY03W2UeIAVETENnFX1F2DJGBUxQGX9S/f/j7MMQUPIVUujjIiAg4OXDlIKmBx98kD/8wz+kvb291pZbDZy+/e1v8/u///szssiAgKkgpRhVMrnizGUTak02tzVz42Uba9mpvpxNyDQ4dWlqVIZlpGZqfWucw/PM/2kg7yKEy7/86kU+/Oq1pGIW6YLDrp4s61uTs1JCcl2f+3d205Uusbc3N6+65mBYq2VK8JRAVDJGEYxRBpVSDBsnKF8L4Efe7yntC7ZmYTzwXgoIeJlRd3luz549nHHGGWzZsoWPf/zjbNiwAaUUzz//PP/wD//AE088wTPPPMOaNWtmes0zSlCee3kydl7deBmWkZqp3qxNpuTO0WqPJGxoP6CIZVAo63lp1c6uta0Jrj6GEttU+P6j7XzzwT305cr4Ss1LEb1R+ThjIRPb9YiHDPJlr1KaNGozCW3HxfYUltTu3z6CkCExpMD1fAqORyJs8i/v2xxYCQQEzCPmlabpIx/5CDt27OCBBx444j6lFK997WvZtGnTCW94GQRNAZMxUjO1ry83b4TO8ZDBsqYoHQMFbM8nHjJY15Kg6PhkbJeWRIjPvXETm9uaJwwQ6wkcx+P7j7Zz0z07cDyfiGngK5+i49dtazBbCMCUAoUiGbG4/nXruf3hdjqHSvi+QqEQCKQUNMUtopZB3nYpOR4lxx+lh/vUJSdz5Za2uX5JAQEBI5hXmqZf/vKXfOlLXxr3PiEE1113HTfccMO0LSwgYD4yVjMVFoJvP7SXX+7up1j2mKsYKhExae8vUHb9Slu9x5MH0xhSBwr9OZuv/WwXH3/tem5/ZPRA47WtiVG2ASNvP1qGynV9vvngHt11KAX5sjvvgqWRKCAZsWpBz6YlDXznt/vZfjiD7XiELV2avfoCHRBVA+TAeykgIACmkGlqaGjgmWeeYdWqVePev2/fPk4//XSy2ex0rm/WCTJNAceC7yvueuoQ//lEB3v6cuRKLoWyN+X9jHQvn8xLqUrVqDJsVuwDxvGiqu1bQGsiTCxkkIxo3yHPV3RlimRKHg0Rg8UNEQwp8ZUiZ7s0xkLceNnGCQOn+547zHU/eAqg1nk33zAlhAyDhqjJxiUNRwQ9k2XYjjX7FhAQMPvMq0xTLgS11h0AAEFNSURBVJcjFotNeH8sFqNQKEzLogICTiS2tQ/wtft3s619EMfz8f1j1/OEDIGrFCGp55Z5vk95jKJ6ZGClVOVvdfRmNaWgJ2vTGDXpzdm4nsL1FV5F7NyX8xkoOJhSYhmCeMjEdkt896F2zlrRNG6w0JUu4SvtGD7fMCS8/pTFvPGMpTRGrZoJ5djXMbZxoN77AgICXn5MqXvu+eefp6ura9z7+vr6pmVBAQEnEtvaB/jCfz3Pru6c1ryoI8eN1IsATFPS1hjl6gtWcd+zXWxrHwRvOGMlGW6DrwZPhtDBVj2JLQUMFV3CFWNLf8x9SoHr+UgkQ0UHKeCpg4Ps6smOGzwsTkUmzW7NFVXR94Mv9HLB2oVceuqSuV1QQEDAS4IpBU0XXXTRERPARzLSHDAg4KWO7ytue6id3mwZPWKtasNxbBZFixsinLuqiat/bxWb25p597krueupQ9z62/3s7MrU5r8ZEoQCt5JlQoDr1V8KVEDJGz8XppQOykoVF3WloGOoyKMv9rO+NXlEqeriDYuIhQ3SxfnTSQhaGG8akqzt8s0H9/DOzSswTXn0BwYEBARMQt1B0759+466zYmuZwoImIyx+hbPVTzXqcXWjjdcoppKvGQA0ZDkXee18bZzlo8qH0kpeMvZy7nizGXc9VQH//lEBwcGimSKNhnbrz2X58PU1VPjo0b+Vw3v/+u/2M3PtncxWHCPEIq/4bQl3PHYwWlawfTg+oqQKYiYBn25Mvfv7A6yTQEBAcdN3UFTW9v47bXZbJY77riDrVu38sQTT+BN4Yo3IOBEYaTVQNn1cH0tlE4XHKSEsju1spwhoCUZZuPiBj70mpMm9fvRwdMKrjhzOZ/50dP857ZDx/+CGK2NGo+R9/XlHAYLg5y8KMHyphglx2N7Z5qb7tnBZ1+/gXufPTyvsk2262MZPpYhKLmKrvT8MiMNCAg4MZnyGJUqv/rVr9i6dSs/+tGPWLp0KW95y1v4xje+MZ1rCwiYc6pdcf/0y70UHY9ljVHKrmR3T5aS4+H5EDUk9eaXpIAlqQh/9Ptr2LJmAWsXJtjVk+WHjx7gucNpYiGD01c0csnGxUgpRmW2BnI2P56mgOlY8H3FgYECUcukMWYRCxm0DxT4/qMH+NQlJ3PTfz1PyZ0f6iZfQb7sETIkUgitvQoICAg4TqYUNHV1dfGd73yHrVu3kslkeMc73oFt29x1111s2rRpptYYEDAnbGsf4Du/3c//7Oql6HiYQpAulHEqHWeWFPhKUaqz1V4KCJmSK85cxntfsYrfHRzkmu88xuP7B7DHBBvxkMHSxiimFGSKZXJlj2zRnVaX7amEN9WslOMpOoYKpKINCCFoSYTZ3ZPj2lefxJ+/6RS+dv8u+nLlaVzlsSHRM+SKjseSVJiLNyya6yUFBAS8BKg7aHrTm97Er371Ky677DJuvvlmXv/612MYBrfccstMri8gYFap6pYe2dvPv/56HznboVj29AlYKRhRgZrqyF4pwPN87nuui6c70rT35zk0VBzXDDJf9tjdkzuu1zIZRyvNjUVRCfoMSd52ydtebWxLX84mXXC4cksb79y8glt+tYdv/3Y/A/m5G2qsKv5VAnhrIAIPCAiYJuoOmu677z4+9rGPce2117Ju3bqZXFNAwJxQ1S09+mIf3dnpyZaMDE4MKUlFLRbGLX53YJD8MZhfHi+y0hFXb8BUNc8Era2qaoQcX+e8So4WhadiFqAtE84/aSEP7+3n0RcHmO5qnSmhnsSer/Q8voaoxSvXLpzeRQQEBLxsqfvy6ze/+Q3ZbJbNmzezZcsWvvGNbwTeTAEvGarDeB/a20fPNAVMUdOo+QXpobCSFU0xhJB4/sy5Z0uG3cSrGEIHQKBLfzHL0L5QBkQtScgQRMbJxozMggmlKJY9PM+jYLtkSw492RLrWhOsb00CVd+qHTzdkcGQgoaISdQyavsIGwLTGF7TVDCnYOUQD0nOWNFISzJSC+gCAgICjpe6g6ZXvOIV/Ou//iuHDx/mj//4j/nBD37A0qVL8X2f+++/P7AbCDhhqfotDebLZEvOcRk1CnQwYAiwPQ9X6WClIWKyrjVJY8zC8f26siXHikJrp6rrEejgJ2ZJEmETT4HjeSggETJZ2RxDCHFUbZbjQ9H1sT14oTvHkwcGGSw4nLemuTbw97aH2itu49o4M2+72O5wRs1XirCho6apmohHLIlZ5wiTkuPTPlBg7YiALiAgIOB4mXKhPx6P84EPfIDf/OY3PPvss3zyk5/ky1/+Mq2trVx++eUzscaAgBllV0+WPT05TEPieGrqX4oRVMXepiGQAsKGZH1rkrNWNNJYyXhYUjKTPrDxkMHSVLhWGqz+Kzo+JcdDjXAtzxZddnXnpjw3ruoeLgV87+F2vvvwfn76fBe7u7OYUlD2fDxfIcTorJfjQ9E5trKklJK2hfFaxmyyt9BT0J2x2XZggB//rgN/Pk8RDggIOGGoe2DvZHiex9133823v/1tfvKTn0zHuuaMYGDvy49HX+znxjufBWBvb76m45nqF8MQsL41QUM0hO16HM6UCBuSpY1R4uFh+aBSiicODJKZIV+jZMggOwt6KYEOEJVShEyDBYkQfVkbKSBX9pBQM+p0fXVMLukjiRiQjFr0553azD0pwfeZtKtQAKcta+AvLz9lwsHDAQEBJz6zcf6elpYSwzC44oorTviAKeDlSSpmETINhBC1DJA8hm/GgniIJY3RWlfZgniYNS0JenM2nufRkylxYKBAT6bEosTM6WxmI2ACHVSWXR/L0IFT2NAZprztacE5OkBU6viyd8PPJxAIQoasZc9g8oCpus5nD2X4xA+f4vF9A9OwkoCAgJcrQR9uwMue9a1J1rYm8DztIF1tVTem8O2IhwxWNMcRQqCUojdns641wYdfcxJl1+fXe/t5rjPD7p4czx3Osru3OGOvZzbRs/CE1kdFLOIhA59K6UzpTjfXn7p+aSwCsAxJwfFY1hjBNKoZrPrXeWCgyLXf38Z/bjsYlOsCAgKOiSBoCnjZI6Xg6gvaaIyHSEYshNDz1uotJ4UNwaoFMZIRk7zt0j5QIBW1eN8FbezqztGbtY+p3Hei4FYCkKLj0RzXWir3KCWzqSKEDs58BcmIxaJkmMUN4Snvpy9X5sY7n+N9336Mbe1B1ikgIGBqnDBB00033cQFF1xALBajsbFx3G0OHDjAZZddRiwWo7W1lU9/+tO47vyZhxUwf9nc1syNl23kgpMW0poMI6Wo6WYsQ7AwbrG2Jc7ihjCNUZOFcYszlzXw4VefxOtOWYxC0DFYIFNyOXVpihsv28gZyxr55oN78JSiMWJOKXN1IlEoexTLHi/25ulKl2YkOFQKyq4Wsedtl0zR4XDGnvJ+BOD5iifbB/nru58PAqeAgIApccyz52abcrnM29/+ds4//3y2bt16xP2e53HZZZexePFiHnroIQ4fPsz73vc+LMvii1/84hysOOBEY3NbM2etaGJXT5aBXJnnD2f0rLjGKBdvWHTELLj1rclaq/14t9/33GH6cmUipoHjKbwZtBmYaxR6SO5MNQUqoOgqJIrdvfnj2o/rKzzf44XuHDf/fBe3vX9LTbAeEBAQMBnT0j03m3znO9/huuuuY2hoaNTt9913H2984xvp7Oxk0SI9Z+qWW27hT//0T+nt7SUUCtW1/6B7LmC6uPW3+/jivTtIhAwyRZfZ9/8OGA+jIlI3pcCQgpvefCpvOXvFXC8rICDgODlhuufmAw8//DCnnXZaLWACuOSSS8hkMmzfvn3Cx9m2TSaTGfUvIGA6WJyKIIXAdtXLNmAy5LAT+XyhKkqPWAaur/jRtkOBMDwgIKAuXjJBU1dX16iACaj93dXVNeHjvvSlL5FKpWr/VqwIrjgDpoeLNyxiYSKE7b1cQyZQ/vwLmkBrpDxfYUnJ4XSJXT3BRIOAgICjM6dB02c/+9mKN87E/3bu3Dmja7jhhhtIp9O1fwcPHpzR5wt4+WCakg+9ei3GTNp/z3Oq+Zv5dnWmgJLrk4iYCBTpgjPXSwoICDgBmFMh+Cc/+UmuueaaSbdZs2ZNXftavHgxjz322Kjburu7a/dNRDgcJhyeeutyQADouXU7uzNsP6TLuqcsbWDtwgQP7OqhK12iNRlmSUOY9sHSHK90bjANLZSvzXSZJ0ihjTeTYZOwZQRDfQMCAupiToOmlpYWWlpapmVf559/PjfddBM9PT20trYCcP/999PQ0MCmTZum5TkCAkayrX2Ar92/m2c6hvRMN4ZjA19p/2rFS7trbjIMAXFLUnJVbRhwwhLknLmPnnyls18Z2+X8ZalgqG9AQEBdnDCWAwcOHGBgYIADBw7geR5PPfUUAGvXriWRSPC6172OTZs28d73vpe//du/pauri8997nN8+MMfDjJJAdPO4/sG+OR/PE3nUMXZWyncI2KBuQ8OZhtDgillbVhvrqwH9xoSVjbFaFsQ57lDQ/Tl574c5gODeZuBfJnfHRwM5tIFBAQclRPGcuCaa67htttuO+L2Bx98kAsvvBCA9vZ2rr32Wn75y18Sj8e5+uqr+fKXv4xp1h8bBpYDAUfj8f39/Mnt2+ifByf++YQBrFwY47RljVy1ZSW9OZt/+uVeerM2GxcnMAwDgM6hIju65ofwWgCrF8RojIe48bKNQeAUEHACMxvn7xMmaJotgqApYDIe3dfHh7/35LzIlMwnWhMhPvKadZy3prlm7rmzK8P1P3yahohJPDx84ZItOmw7OHjUsqUlBc4sWAGsao5iGJJTl6b42jvPDIwuAwJOUGbj/H3ClOcCAuaKquP3vz9+kNsfacc53umzR+F4NdPVU74QurV+psOOxqjFxy9ez5Vb2kbdni44lF2PiDW6PJ6ImDRELIYKjh74Kxh3Np+apfLmwcEi61sT7O7Jsasny4bFwcVSQEDA+ARBU0DAGEaORTk4WODupzt58sAg2dLM+S39//buPDyq8uwf+Pcss2a27CEQAhhCICyylAhtLVYwUmqtUoXWvsJba7XYn4pUq9VCpY2iVulVfy7vdfkqtLXa8rPiAtiignUBKpSwhlUJWxayzkySWc459++PkzlkyCSZrCTk/lxX3rdzznOWmTOcuX2e+9yPCGBMugMQBNw4ZSiqG0KobQzho0OVKPeFIKA5GOogEDJLgMduRorDCotJhKJqqG0IocIbQLgHE9JFAUh3WZHsMKMpqOKNXaeRl+GMGt5y200wyxICYTWqp0kQBIxKceBgWT2awhpixaCRSX/7gkrAkXN+JNrNXHqAMdYuDpoYa2FXaQ3WflaKY5V+VPoCqG0IxfxR72kpTjNCGmF8pgu3fW2UMUT0+Ylq/PTP/0G1P6QHSgRIogCnVcaIZDvO1geQ4rBg5qgk/ONgBTw2M1Kclqg54NKcVmR6bDhbH8DU4R68u7es2+9JEPSK50l2M8hBKK1pxB8/K8XkrETj3HPTnMhJc+DA2XrYzRKEFvWq3DYZZllEUxuRXF/nDKgaUO0P4VRtIwqQ3MdHZ4wNFP2t5hxjF82u0hoUbSjB/jP1AKjPAiZA731x20y4dWZ2VE7NV0Yk44VbpmJMugMpDjNGpiRgUpYHuWkOeAMKhnpsWHl9Ph761jhcnpWIhpCid0W1QESobghhZIodB87W98h70jRAaU5KEgQBqQ6LMbwVIYoCFs3MhttmQmlNIxqCClSN0BBUcKK6EU0hFaIAJJgliNCH6S4mAvCHD45i2/EqHCr3QlE0HCr3YscX1ThU7uWpVhhj3NPEGKAPya39rBR1jWFkJ9ux44vqPguYJBGYPiIJi786IubTW18ZmYSiGycYPWD1jSGYZQnjM924dWa2sc2imdko2lCC0ppGpDossJr0obFz/iBcNhM0DThTF+yROpOCoE94G2E1SajyB1sNb03NTsLD88Ya517lD8IsS0h2mHGqthEJZlmfZqWf5F6frGnC3a/9BwkWE8KqBpMkQhYFmGUJl6Um4Kq8VAz12OG2m4yEd8bY4MFBE2MAjlT6cKzSjzSnBV9WNaCxmwlAIvTAQhD0Xpm29maWBNzxjcuwdHZuuz/AU7OTMDkr0ci1ivWj3VaAMj7TjW+MScX/3XIMWnP9JAF68nVXmSQRZlkyXgfCKsxy7Mrasc79s2NVKD5VB5MkNBcC7T9qGsLwB1UoGsEsicjNcCIUVvHh4Uq8X1KBpAQzXFYT0l1WfHNsGqaPTOIAirFBgoMmxnD+SS+zZMKZSMHKLhIAJFgkKJr+/JckCyAiNIU1EPQkakkUkOow465vjm711FlbRFHo8MmutoKrz0/UIBhWAUEPUCLpRV0NnDx2k5HcTUQ45w9ifGbblbUvPPcvqxogCgLCKsEsCZBEAUoPDH+Jzd1o3Ql5VQKCiga3VUZQJZyoaoCqkZGA3xhSEAhrOH7Oj+1fVCPDbcXEYR4satHrxxi7NHHQxBjOP+lV5g1A6ea4HAHwBVVYTSJMogCVgLBGsMoCvjtlGHLTnchwWzEnLx2y3PNphbGCK7fdBItJgggBoqgPR3a1X0QWBaQ4LNA0Mob/YuVjtWdOXjpSHGZU+oIwSTJsJgkNIRVaN8vGCQB64hlHjQBVI5hEAd6AApMkIMEkIahoqG9SYJZF2M0ygooKXyCM/afr8MibPny/YDimjUgECPAFFB7GY+wSw0ETYzj/pNenx6p6bJ+BsIYA9B9ysyQgwWpCQ1BFwagk+JoUHKvy99kPam6aE/lDXKj0BqEqKgRB6FKA4rHJyM90o7YxjNO1jTFzq+IhyyKWXJWDog0l8AUVWGUJNpOIhqDa7V6inuIPqrCY9ClhrM3BbUjVQKQX3pRFAZAlNIY0EMLw1zXh8Y2HIIt60GUzS3BZTcjPdLWZr8YYG1g4aGIM55/02ne6DtUNoR5Jlo4gACGV4A2E8UFJBfaeqkVTWEVYJbisMuZOyMB1lw9FXrqr1wIoURSw+KsjcLjCh9LqRohonlCY4ishKQnAsEQbfnfzJEwdntRublW8IsOSz285hip/CBoRZEmARRLRqKjdnuhYhP7Zd/U6aoBREkHTCEFFMwqbSqIeRGlECCoqVE2DKAhoCp/v52oMqfA1hVHhC+BwhQ+P3ziBAyfGBjieRuUCPI3K4LbjyyosfvlzNIW1Hg2cOmKWBEwfmYylc0b36g/rrtIarN58BHtP16MppIJAkEURsiQgpKhQtOg8J1kUYDdLmJTlxr2zc3vl3BRFw+ZDFSivDxjDlrtP1eHBN/bgeFVjt/Y9KsWOkEoIKRokQe+J8gWUqOCmswQATqusD90FFYRVgizGLsYpADBJAgjA2AwXVs2fgNw0J45V+bsddDLGovHccxcBB03sz9tKUbTxYHOSsgiChqZw7/8zkUTgslRHr/dIaBrhULkXB856AQD5Q13ITXXiSKUPB856oRHBbpHQFNQgCEB+pgt5Gb3XC9beeT69+RD+56Mvulwd3GEW8defzIQ/pOcX+ZoU/Oqt/TjUjQmDBeiJ/BZZRENINZZ19A0RBSDDZYUgIKqUQU6ag5PIGesBHDRdBBw0MQB4dUdp1LCRRgRN6/2eJ7tJwOyxGfj9wsnc+9DsT9tP4DfvHESoiwlL103MwJTsJKS5LBiRmICdJ2uw+v2jqOvGlCmRK0Po3FyBFlmERudLGZhFAafrmiCJAq6bNARzxw8BAJSU6UHdxQpYGRuIOGi6CDhoYhEXDhslWk144V/HsfNErdHD0NPMkoBhiXY8/8MpPHFsC/9v5yk89OY+aM1lHLpSnUCA3tvjspngsso45wvGXY8rEhi1DJBiLeuIWRLhsEgIKBoszcnl3kDYyN+KhEYi9Dw0m1nCxGFuLJ3TO0OjjF1K+uL3mxPBGWuDLIvGf/lHTB+VjCOVPmw7XoUXtxxDhb9nJ3glAoJhdUBPHNtywuOeytm5ccowrC8+g+JT9SDSSx10tuOJoOc01TaGEVI0WEzn575ruatI7lNEJNgCALtZhqJpCCr60KXayd5HiyxCFASIQMyersi+VOglD7Sggn9/WYOH/r6PE8kZ6wc4aGKsEyI1kPIyXFg0YyR+948SPP/Rlz22f0EALKbYlbUHgpYTHocUtcdydkRRwNI5ufjtuyU4U9eIkKpB7UZ9Ab0mlKjPfWeRoGh6VXONWgdBkXBPFgWYJQFmWQZBgdMiQyOgIRhGUOn4KURRaE4Kb37iLp5eKpUAVSWcqmnC2gsmRGaM9T2esJexLhJFAQ/MHYefXDkKUg/9S5JFYHymq83K2v2RomjYtL8MK985gJ//bQ/2nKyBLAIOiwxZBPafqUPRhhLsKq3p1nGmZifhl/PyYJLEHkkuCzdnlysqMCLZDrfNBFFoNd8xIOiTEltNEgRBgKJq0DQgP9ONmZclIynBDLMstFssVBQi+UyASmQktsf7NprCKnaW1kRNiMwY63vc08RYN/3yW2MxOy8Nv3prP45X+qF08QddEoFhSQlY9NURA6Y3IZIwf84XjErUlusCMMkiJFFAgllGUAngjz3QU+K0muC2mZGUYMaJ6kb4AkqX96WQ3tMTUvX8oslZHpTXB1FW36TnGTW/HQGAVdafdlM0QmNYhcMi466rciCKwJm6JggQUNsYRljToGkUNbwnC8CoNAfqG8PwBRVIQtdivsr6ADbtK8O249W9WlGeMdY2DpoY6wHTRyVj0z1XYn3xabzy6QmUnPV2KniyyCKmj0jCvb1cp6knvbqjFEUbShBUVGgX5FMrBGhhDXazBF9QgSgAe07X4Uilr1sJ7pE5Aocl2mGWJRwq86IxpHa544kAKBrhWGUD8jMlpLkscFolfFndgPomBTaTnoMUVDU0hFVoGsFhkfHzwjH4ykj9OkUmSd57ug5V/iDCKsEiCrDKEhRNg9MqI8luRoJZxpEKLxqCXaufoBDwhw+OQRL1ufpSHGYsuSon7rkLGWPdx0ETYz1EFAXcOCUL3718GNYXn8bLn3yJQ+W+VjWGJAFw2mSkJFhwWZoDs8akYlKWp1crgvc0RdHw/JZjRsAUK2jRAL1XxiwhrAFV/iBqG0LdOm5kjsBAWIXHZkLeEBdO1zSirimMYFeLOQHwBRUcrfQjsXn/M0alYPqoJOz4ogZHK3zwBxWIgoBRKQlY8s3L8JURyca2LSdJrm0Ioa4pjESbGZ4EvS7Un7brOV71TSGoWvcmE9afHCSYBRGVviCKNpQAAAdOjPURDpoY62Etg6dD5V7sOV2Hg2e9sJklpDgsyM90IdlhGXCVoFs+FbfvTD0qvYEOa1dpBAQUDWZJRFgl1DV176nAyByBB87Ww26W4LGZ4B7qRkNQQSAUxr6zPlCMZO54+INh/GHB5Uh2nb823//K8LieBIw1SXLE1OxErC8+g2c2H4HSPFFyd1KyNNKDUbOoT9WyamMJxme4MCHLM6C+T4wNRBw0MdZLRFHAuEw3xmW6L/apdNqFZQN8gTD+tO2k8VScL6ggzhJHCKsEQdBgkiQk2szdOq/IHIFFG0pQWtOIVIdFT9AG4A9pGOqx4ZwviKCidTowCSqEA+Ve/CT3sqjj9US9rC2HKlHbEEJ8M/3FJ9T8+fuCKm588TPkD3VjxXXjBszwLmMDEQdNjDGDphHWF5/GG7vOoKw+AJCGgKJPNmwzSRiVkgCb04Jj5/xx71N/tF7PwfEkdL+UwtTsJCOP6FilH1X+IMyyhPGZbtw6MxuHyn1YvfkIqvydHwp8bcdJTM1O7NHAIzI9jUoEIr2sRE+XFFYJ2He6Hve+XozfL7ycAyfGegkHTYwxAOcn891VWgtFJYiCAAhAWNX0IaGQCkUjjEpxGI/rx0ME4LLJmDTM02OlFFrmEV04dDY1OwkLpmbhhY+O4ffvH+1UEczqBj1P6OF5Y3ss8KhvDCMYVkGkD6311gAaASirD2DNpye4nhNjvYSDJsYYdpXW4LfvluBopR9EgNUkojF0vtijCL13xBtQcKjcC430x/ADcQRPFlnEUI8Nt87M7tEf8vaGzmRZxP+5OheeBDMefftA3BP+ygJQ6Q3gmX8ewQ+uGI4kuxmJCWYj2OtKpXM9eV00huZ6a94qAXoV8d2nuv+UImMsNg6aGBvkNI2w9rNSnPMHQUSwyCKawvrcepGhJAIgiQI0IoRVgqppcNlMceUOTc1OxD1zRsNmkrBu5ykAQP5QV588LfhfV4zAiaoG/O8nJ+JqXx9Q4QupOFsfwL9P1MAii0hxWDAs0QZAQE1DqFWl88lZiThU7sW+s/UoqwmgqiGIBIuEiVkeFI7NgK9JQUjREO5qAa84CUJz4v0An4aHsf6MgybGBrkjlT4cq/TDZZVR0xACBL3HQh+d0wOllj/3sggoGqCohASLDH+w7QKTSXYTLh+eiN9vPoJ9Z7wIhDUABKtJwsRhHiztg7pUN14+DOs+PwlvHPWR9GlL9P8tghAIazhV04iTNY0QBMBjM8NhlUGqio+PnsPWw5WwmUTUNSmtSh4IAJxWCVaThJCiQZaAcO/M8wzg/NCfdQBPw8NYf8dBE2ODXKRgZKLdDFEQoKpkzIvWnNYEAkCkB1ImSURQ1RBUVEiiAJMkQNMIWnNkFdnWahLhDSh4fusxAPrcbbbmqUgCiorPT/T+RLSv7ijFcx8eha8LBSUVFYgaTCOguiGE6gtqTXkDsbcnAN6ACm+gFyOlC4gCMDmr53LHGGPRuAY/Y4NcpGCkKArNk9dSVLJyZAhNIxjJ4SZRNKppS4IAh9UEh1WGJOoBkywJkEURRHowFUmCBvTgKcEkQRIFnK1rwtpPT0DTen7oKlKx/Jw/BJM0OJKinVYJw5NteOM/p3GwrL5XPlfGBjPuaWJskGtZMHKox4bGoIKw2hwkNQ/NiYIeMEmC/hSdzSRh4jAX6ptUHC73IaToU4yozcUuFZXgVxWjn0bPjSIEwipkUYAgCDBLIkKKhv1nvT2euBypWB5WNTgtMnztDCFeSuqaVLz40ZeQBPTpEChjgwX3NDE2yEUKRrptJtQ3hTE8OQEumwyQPt8ZEeC2yhiT7kSq04oRyQn49Xfy8ccfXYEn5k/AsCQb3DYTFO187hMh+imxyFCfohHU5iJFkc6fYC8kLm8+VIEqfwhWWYJGeo7WYKFqBEkUEFI1Ywh0V2nNxT4txi4JHDQxxoyCkfmZbhABSQkWZHisSEkwY4jHiiSHBQRgyvBErJo/ATdOGWY88p/htKDCG2y3HpJK55/CixR2jLS39ELicnl9ABqRnm/VXFRyMAkqGux9MATK2GDDw3OMMQCxC0bmpDhwrMrfZm2iXaW1OFjui6v2kJ4TdX6oLqRqEEVgfKarxxOXM9xWiIKAsKr3uvRGFe7+TCMgrFGvDoEyNhhx0MQYM8QqGNnWD+2u0hosf2s/fHFOwkvN/4cIaFD0CtnDku1Y9NURPV6vaU5eOlIcZlT6gnBaZL3GVGdKg18CNI1glvXPtTeGQBkbjDhoYoy1mqC3rQrYkWV1DWG8+NFxVHoDnapwTQCawiqsJgmThnlwby8lKcuyiCVX5aBoQwl8QQUmUYSiqr1Wjbs/EkWhV4dAGRuMOGhibJDbVVpjTH4bqXadlGDChRWwWy7zBcIo9wai6jN1RBKBb08Ygq+NTu2TiuC3FGQDAJ7fcgxV/hAkUTASwoUWhzWJAiRJhKYRwqrWqbnqWhIBOKwyEu0mXJ7lQU66A9uOVePfJ2qh9HE+kSjo7yug9N4QKGODEQdNjA1iu0prULShBHWNYaQ5LbCaLDjnD+LzE7UAgJzUBAxLtLdaluww40xdU1x5QgIAm0mESsC1E4Zg7vghvfiOot1SkI0FU7Ow+VAFyusDSHNakJVsw+EyPzQiOKwykuxmuG0mQADqGsI4WOZtnsdNQ0NQRZk3gAyXBTazhLomBTaThOwUG0rPNeFsfRMyXTZclpGAlASLMU9dJBi8axbh77tP46l/HEa1PwQQQRSAUOdrbXaKRRbRGO7dIVDGBiMOmhgbpDSNsObTE6j0BpHqNINI74Gp8gchAhBEAVUNIaS5rK2WpTrMAFpUDKe2J6K1mUSENUKa04I5eel99O7Ok2WxVaA2cWhim+1n5qT02LFFUcD3pmZhZEoCVm8+gr2n6xEIazCJenkGucV8fm19fpFQJ56+KqH5mKpGvT4EythgxEETY4NAy5wlp1UGBGDD3jJ8eKgSmkaoaQxBFACLLKExpMJikgAADUEFVf4gGoLRy5LsZgiCAGruOdGg/2BfOApllgTjKa4lV+VAlgdnlZOp2Un4448KcKjciwNnvQCAsUP0Hilvo4LqxiB8TQoqfQGkOi1wWmX4AwoqfUGku6wYP8QNFRo+KKlESZkPLquM0RkOjE134UilH6IApLutGO6x41CFD0DfTYrM2GDCQRNjA1CsxO22fhxb5izVN4XgCyhQNUJAUaFqgEkSYBMEiKIIf1BBWNVgkgSYRAEhAgJhDRoRJFEEiBBqDozMkoCQolcBFwQgwSIjpGhRE9cSgDSnBUuuyjFyjAYrURQwLtONcZnuLu9j4rDWPWRXjkmLej0hy9Pl/TPG2sdBE2MDTKzE7Zw0BxbNzG41DNMyZ8lmluBtCiOs6jWSiNCcu0NoDGtIMAuwyiJCqoamsArBJEEU9Il3ReF8ErUoAE6rCS6bCfWNYaianjwdVjSYJBFuqwyFCJkeG3466zIUjs0YtD1MjLFLC9/JGOsjmkY4VO7Fji+qcajc26UKzZEgaP+ZerisMoYl2uGyyjhwth5FG0qipsvQNMLaz0pR1xhGdrIdVf4gVE2fkwxofoJM0IfUtOZ54SRRgCwKUFRCUNGQYJGR4rAgwSIhqKgIqfoyh0XCsES7PhGuIMBpNWFMugOjUhLgtJowIjkBj34nH/MmZHLAxBi7ZHBPExuwFEUznorKcFsxJy+93/5Ad6Z3qC0tg6ARyXYIzc/NJ1hk2M0SSmsa8cfPSjE5KxGiKOBIpQ/HKv1Ic1rQGFLREFRhlkVodL7HKFKlO1JBWiU9/yisqlCJkJKgJ4inOCyoawwDzcs00h9pd9lMkEMq3DYTGkL6+xo/1I1bO/G+GGNsoOCgifWpzuTitOfVHaVG/R2NCKIgIMVh7pe5M7Ee6w+EVaN36OF5Y+MKMFoGQYIQ/ZkJgoBUhwVHK/3GdBn1jWGEFBVWkwXeQPh8XpIGI4kb0HueQqoGRSUEwhokQUCCWUJuuhNBRcPp2kaYZQnTRyaCSK/TFFk2LTsJP7wiG06b3O1ryhhj/R0HTazP9ERvC6AHTEUbShBWNVhlCSZJn2Os0hdE0YYSAOg3gVNne4fa0zIIisVqklDlDxrTZbjtJphlCYGwCpN0Pi9JEgVIooCwoj/5ZpIEmCQ9iXt4kg0NIRWThyfimZsmtZp3DmhdJZwDJMbYYNE/xzJYn+pMrk1X83I6k4vTHkXR8PyWYwirGpwWGRZZDwYssginRUZY1dcrSi9XD4xTZ3qHOtIyCIolENYD0ch0GblpTuSkOXDOH4TdLCHBovcoAYBVFo2q2Jqm5y/ZzPr6VKcFi2ZmQ5ZF5GW4UDAqGXkZ+qPrkbnpWi5jjLHBgnua+kC883q19QPU1SGteLbr7JNYXekp6snels2HKlDlD8EqSxAvCEJEQYBVllDlD2HzoYo+rTzdls72DrUnEgQdOFsPu1mKCsKICOf8QYzPdBvfL1EUsGhmNoo2lOBkTSNSHBY0BhU0hBTj2LIIBMIEQQCcVhkThno4H4kxxtrAQVMvi3der54OVOLZrjO5Nt3Jy+lsLk57yusD0Ij0p7ZiMEkCAgqhvD7Q7n76SsveoQRL639uF/YOtadlEFRa04hUhwVWk77vc/4g3DYTbp2ZHRV4Ts1OwsPzxhrfBZfNBF9AD5qcVhlumxnpLguuGpOG6aOSeLiNMcbawUFTL4p3Xq+eDlTi2W5yVmLcvT8AutVT1JO9LRluK0RBz2GyyK2PFVb1pPAMt7XDffWFzvYOdeTCIKjKH9SfWMts+4m1qdlJmJyV2KoiuK9J4bwkxhjrBA6aekmsISlC63m90l3WHg1U4h0Ks82SOpVr052eop7sbZmTl44UhxmVviBMkhA1RKeRXuX6Ys1xFktXeoc6cmEQFE/gE8lFYowx1nWcCN5LYg1JNQQVYw4vsyQar4HWwUdXE4jj3e7AGW9z748U8/ytJgkhRUV9Y7hFT1HHbWNpmZAcecw9ItLbMjrNEVdviyzrc5iZJBG+oIKgok/xEVQ0+IJKv5zjLNI7lJ/phjeg4HRtI7wBBeMz3XGXG7gQJ2Qzxljf456mXhJrSCqstp7DK6ydf8rrwmGqrgxpxTsUBqBTvT/d6Snq6d6WSDmBSJ2mgKIPyfXnOc660jvEGGOsf+GgqZfEGpJqWSsH0Csxm8TzPSI9EajEOxSWn+nqVK5Nd/NyupKL055bCrKxYGrWgKkIDvAQGWOMDXQcNPWSWAnACRYZCRZ90lRBEOC06q+BngtU4k08zstwdar3pyd6inq6t0WWxX5RVoAxxtjg0H//s3yAiwxJuW0mlNY0oiGoQNMIKQ4LNNJnlo/M4dUQVFBa0xgVfMTaXtUoZtuOjtvWdp3JtempvBzOxWGMMTZQCXRhZm4/VVRUhA0bNqC4uBhmsxl1dXWt2lyY+AwAr732GhYuXBj3cbxeL9xuN+rr6+FydX8oJVa9pGSHyZjDK7JsdJoj5jBVrO3batvV7TpTPLOn5o5jjDHGelJP/37HMmCCphUrVsDj8eD06dP43//93zaDpldeeQXXXnutsczj8cBqjb9mT2986P25IjhjjDF2KeiLoGnA5DQ9+uijAIA1a9a0287j8SAjI6MPzih+bSUAx5sU3NUEYk48ZowxxnrOJZfTdNdddyElJQXTp0/Hyy+/3Kou0IWCwSC8Xm/UH2OMMcbYhQZMT1M8Vq5ciW9+85uw2+345z//iSVLlsDv9+Puu+9uc5vHH3/c6MVijDHGGGvLRc1pevDBB/HEE0+026akpAR5eXnG6zVr1uDee++NmdN0oeXLl+OVV17BqVOn2mwTDAYRDAaN116vF1lZWb06JsoYY4yxnnXJ5zQtW7YMixcvbrfNqFGjurz/goIC/OY3v0EwGITFErtCtsViaXMdY4wxxljERQ2aUlNTkZqa2mv7Ly4uRmJiIgdFjDHGGOu2AZPTdPLkSdTU1ODkyZNQVRXFxcUAgJycHDgcDrzzzjuoqKjAFVdcAavVis2bN+Oxxx7Dz3/+84t74owxxhi7JAyYoGn58uVYu3at8Xry5MkAgC1btmDWrFkwmUx47rnnsHTpUhARcnJy8Mwzz+D222+/WKfMGGOMsUvIgClu2Vf6IpGMMcYYYz2rL36/L7k6TYwxxhhjvWHADM/1lUjHGxe5ZIwxxgaOyO92bw6gcdB0AZ/PBwDIysq6yGfCGGOMsc7y+Xxwu929sm/OabqApmk4e/YsnE4nBIEnt+0JkYKhp06d4jyxfoSvS//E16V/4uvSP7W8Lk6nEz6fD5mZmRDF3sk+4p6mC4iiiGHDhl3s07gkuVwuvtn0Q3xd+ie+Lv0TX5f+KXJdequHKYITwRljjDHG4sBBE2OMMcZYHDhoYr3OYrFgxYoVPJ1NP8PXpX/i69I/8XXpn/r6unAiOGOMMcZYHLiniTHGGGMsDhw0McYYY4zFgYMmxhhjjLE4cNDEGGOMMRYHDppYlxUVFWHmzJmw2+3weDwx25w8eRLz5s2D3W5HWloa7r//fiiKEtVm69atmDJlCiwWC3JycrBmzZpW+3nuuecwYsQIWK1WFBQU4N///ncvvKNL14gRIyAIQtTfqlWrotrs3bsXX//612G1WpGVlYUnn3yy1X7WrVuHvLw8WK1WTJgwARs3buyrtzBo8He97/z6179u9e8iLy/PWB8IBHDXXXchOTkZDocD8+fPR0VFRdQ+4rnHsfb961//wnXXXYfMzEwIgoD169dHrSciLF++HEOGDIHNZsPs2bNx9OjRqDY1NTW45ZZb4HK54PF4cNttt8Hv90e1iece1yFirIuWL19OzzzzDN13333kdrtbrVcUhcaPH0+zZ8+m3bt308aNGyklJYUeeugho80XX3xBdrud7rvvPjp48CA9++yzJEkSvffee0ab119/ncxmM7388st04MABuv3228nj8VBFRUVfvM1LQnZ2Nq1cuZLKysqMP7/fb6yvr6+n9PR0uuWWW2j//v302muvkc1mo//5n/8x2nz66ackSRI9+eSTdPDgQXrkkUfIZDLRvn37LsZbuiTxd71vrVixgvLz86P+XZw7d85Yf+edd1JWVhZ98MEHtHPnTrriiito5syZxvp47nGsYxs3bqSHH36Y/v73vxMAevPNN6PWr1q1itxuN61fv5727NlD3/nOd2jkyJHU1NRktLn22mtp0qRJtH37dvr4448pJyeHvv/97xvr47nHxYODJtZtr7zySsygaePGjSSKIpWXlxvLXnjhBXK5XBQMBomI6IEHHqD8/Pyo7RYsWECFhYXG6+nTp9Ndd91lvFZVlTIzM+nxxx/v4Xdy6crOzqbVq1e3uf7555+nxMRE47oQEf3iF7+gMWPGGK9vvvlmmjdvXtR2BQUFdMcdd/T4+Q5W/F3vWytWrKBJkybFXFdXV0cmk4nWrVtnLCspKSEAtG3bNiKK7x7HOufCoEnTNMrIyKCnnnrKWFZXV0cWi4Vee+01IiI6ePAgAaDPP//caLNp0yYSBIHOnDlDRPHd4+LBw3Os12zbtg0TJkxAenq6saywsBBerxcHDhww2syePTtqu8LCQmzbtg0AEAqFsGvXrqg2oihi9uzZRhsWn1WrViE5ORmTJ0/GU089FTWEsG3bNlx55ZUwm83GssLCQhw+fBi1tbVGm/auFese/q5fHEePHkVmZiZGjRqFW265BSdPngQA7Nq1C+FwOOp65OXlYfjw4cb1iOcex7rnyy+/RHl5edR1cLvdKCgoiLoOHo8H06ZNM9rMnj0boihix44dRpuO7nHx4Al7Wa8pLy+PupkAMF6Xl5e328br9aKpqQm1tbVQVTVmm0OHDvXi2V9a7r77bkyZMgVJSUn47LPP8NBDD6GsrAzPPPMMAP06jBw5MmqbltcqMTGxzWsVuZase6qqqvi73scKCgqwZs0ajBkzBmVlZXj00Ufx9a9/Hfv370d5eTnMZnOrfM2W3/l47nGseyKfY3v3nvLycqSlpUWtl2UZSUlJUW06usfFg4MmFuXBBx/EE0880W6bkpKSqGRJdnF05lrdd999xrKJEyfCbDbjjjvuwOOPP87TQrBBa+7cucb/njhxIgoKCpCdnY2//e1vsNlsF/HMWH/FQROLsmzZMixevLjdNqNGjYprXxkZGa2e/Ik8eZKRkWH8/wufRqmoqIDL5YLNZoMkSZAkKWabyD4Gq+5cq4KCAiiKghMnTmDMmDFtXgeg42s12K9DT0lJSeHv+kXm8XiQm5uLY8eOYc6cOQiFQqirq4vqbWp5PeK5x7HuiXyOFRUVGDJkiLG8oqICl19+udGmsrIyajtFUVBTU9Ph/avlMeLBOU0sSmpqKvLy8tr9azkm3J4ZM2Zg3759UV/mzZs3w+VyYdy4cUabDz74IGq7zZs3Y8aMGQAAs9mMqVOnRrXRNA0ffPCB0Waw6s61Ki4uhiiKRpf2jBkz8K9//QvhcNhos3nzZowZM8botu7oWrHu4e/6xef3+3H8+HEMGTIEU6dOhclkiroehw8fxsmTJ43rEc89jnXPyJEjkZGREXUdvF4vduzYEXUd6urqsGvXLqPNhx9+CE3TUFBQYLTp6B4Xl65ktzNGRFRaWkq7d++mRx99lBwOB+3evZt2795NPp+PiM4/jnvNNddQcXExvffee5Samhqz5MD9999PJSUl9Nxzz8UsOWCxWGjNmjV08OBB+slPfkIejyfqiRXWts8++4xWr15NxcXFdPz4cfrzn/9MqampdOuttxpt6urqKD09nf7rv/6L9u/fT6+//jrZ7fZWJQdkWabf/e53VFJSQitWrOCSAz2Mv+t9a9myZbR161b68ssv6dNPP6XZs2dTSkoKVVZWEpFecmD48OH04Ycf0s6dO2nGjBk0Y8YMY/t47nGsYz6fz/j9AEDPPPMM7d69m0pLS4lILzng8Xjorbfeor1799L1118fs+TA5MmTaceOHfTJJ5/Q6NGjo0oOxHOPiwcHTazLFi1aRABa/W3ZssVoc+LECZo7dy7ZbDZKSUmhZcuWUTgcjtrPli1b6PLLLyez2UyjRo2iV155pdWxnn32WRo+fDiZzWaaPn06bd++vZff3aVj165dVFBQQG63m6xWK40dO5Yee+wxCgQCUe327NlDX/va18hisdDQoUNp1apVrfb1t7/9jXJzc8lsNlN+fj5t2LChr97GoMHf9b6zYMECGjJkCJnNZho6dCgtWLCAjh07ZqxvamqiJUuWUGJiItntdrrhhhuorKwsah/x3ONY+7Zs2RLzt2TRokVEpJcd+NWvfkXp6elksVjo6quvpsOHD0fto7q6mr7//e+Tw+Egl8tF//3f/238B3xEPPe4jghERF3pMmOMMcYYG0w4p4kxxhhjLA4cNDHGGGOMxYGDJsYYY4yxOHDQxBhjjDEWBw6aGGOMMcbiwEETY4wxxlgcOGhijDHGGIsDB02MMcYYY3HgoImxfu7cuXP46U9/iuHDh8NisSAjIwOFhYUoKiqCIAjt/m3duhVr1qyJuc5qtRrHWLx4ccw21157rdFmxIgRxnK73Y4JEybgpZdeijrXrVu3QhAE1NXVRb3Oz8+HqqpRbT0eD9asWRO1bPfu3ViwYAGGDBkCi8WC7OxsfPvb38Y777yDztThfeONNzBr1iy43W44HA5MnDgRK1euRE1NjdGmqakJK1asQG5uLiwWC1JSUnDTTTfhwIEDUfv69a9/bUwMGq8TJ050eG0i711VVaxevRoTJkyA1WpFYmIi5s6di08//TRqny2voyiKGDJkCBYsWICTJ0+2Ov6BAwdw8803IzU1FRaLBbm5uVi+fDkaGxuj2gmCgPXr17fafvHixfjud79rvJ41a1bM93DnnXd26nNhbKDjoImxfm7+/PnYvXs31q5diyNHjuDtt9/GrFmzMGHCBJSVlRl/N998M6699tqoZTNnzgQAuFyuqOVlZWUoLS2NOs6F25aVleG1116LarNy5UqUlZVh//79+OEPf4jbb78dmzZt6vA9fPHFF/jjH//Ybpu33noLV1xxBfx+P9auXYuSkhK89957uOGGG/DII4+gvr4+rs/r4YcfxoIFC/CVr3wFmzZtwv79+/H0009jz549+NOf/gQACAaDmD17Nl5++WX89re/xZEjR7Bx40YoioKCggJs3749rmO1JSsrK+pzXLZsGfLz86OWLViwAESEhQsXYuXKlbjnnntQUlKCrVu3IisrC7NmzWoV0ESu45kzZ/DGG2/g8OHDuOmmm6LabN++HQUFBQiFQtiwYQOOHDmCoqIirFmzBnPmzEEoFOrSe7r99ttbfT+efPLJrn5EjA1MXZoohjHWJ2prawkAbd26tcO2ixYtouuvv77V8ldeeYXcbneXtm0pOzubVq9eHbUsKSmJli5daryOzCFVW1sb9fr++++nrKysqPnu3G63Mc+g3++n5ORkuuGGG9o8vqZp7Z4fEdGOHTsIAP3+97+PuT5yXqtWrSJBEKi4uDhqvaqqNG3aNBo3bpxxvBUrVtCkSZM6PHZ72trH66+/TgDo7bffbrXuxhtvpOTkZPL7/UQU+zr+4Q9/IABUX19PRPpnNG7cOJo2bRqpqhrVtri4mARBiJpvCwC9+eabrY594ffhG9/4Bt1zzz3xvVnGLmHc08RYP+ZwOOBwOLB+/XoEg8GLfToGTdPwxhtvoLa2FmazucP29957LxRFwbPPPhtz/T//+U9UV1fjgQceaHMfgiB0eJxXX30VDocDS5Ysibne4/EAAP7yl79gzpw5mDRpUtR6URSxdOlSHDx4EHv27OnweN31l7/8Bbm5ubjuuutarVu2bBmqq6uxefPmmNtWVlbizTffhCRJkCQJAFBcXIyDBw/ivvvugyhG394nTZqE2bNnt+o9ZIzFj4MmxvoxWZaxZs0arF27Fh6PB1/96lfxy1/+Env37u3Ufurr640ALPI3d+7cqDbvvvtuqzaPPfZYVJtf/OIXcDgcsFgs+N73vofExET8+Mc/7vD4drsdK1aswOOPPx5zmO3IkSMAgDFjxhjLPv/886hzeffddzs8ztGjRzFq1CiYTKZ22x05cgRjx46NuS6yPHJOvamz5xG5jgkJCUhPT8eWLVtw1113ISEhIapte/vs6vt6/vnnW30/Xn311S7ti7GBSr7YJ8AYa9/8+fMxb948fPzxx9i+fTs2bdqEJ598Ei+99BIWL14c1z6cTif+85//RC2z2WxRr6+66iq88MILUcuSkpKiXt9///1YvHgxysrKcP/992PJkiXIycmJ6xxuu+02PP3003jiiSdaBWOxTJw4EcXFxQCA0aNHQ1GUDrehTiSLd6Ztb+rMeUSuYzgcxqZNm/Dqq6+iqKioU/uMp2cwlltuuQUPP/xw1LL09PQu7YuxgYqDJsYGAKvVijlz5mDOnDn41a9+hR//+MdYsWJF3EGTKIodBjcJCQkdtklJSUFOTg5ycnKwbt06TJgwAdOmTcO4ceM6PAdZllFUVITFixfjZz/7WdS60aNHAwAOHz6MK664AgBgsVjiDsgicnNz8cknnyAcDrfb25Sbm4uSkpKY6yLLc3NzO3XsrujsebS8jmPHjsXx48fx05/+1Ehwj3yOJSUlmDx5csx9ttyf0+mM2fNXV1cHt9sdtcztdnf6ejB2qeHhOcYGoHHjxqGhoeGinkNWVhYWLFiAhx56KO5tbrrpJuTn5+PRRx+NWn7NNdcgKSkJTzzxRLfO6Qc/+AH8fj+ef/75mOsjpRAWLlyI999/v1XekqZpWL16NcaNG9cq36k3LFy4EEePHsU777zTat3TTz+N5ORkzJkzp83tH3zwQfz1r381ehEnT56MvLw8rF69GpqmRbXds2cP3n///ahAe8yYMdi1a1dUO1VVsWfPnj4JGhkbaLinibF+rLq6GjfddBN+9KMfYeLEiXA6ndi5cyeefPJJXH/99XHvh4hQXl7eanlaWpqRMBwMBlu1kWUZKSkpbe73nnvuwfjx47Fz505MmzYtrnNZtWoVCgsLo5Y5HA689NJLWLBgAebNm4e7774bo0ePht/vx3vvvQcARrJzewoKCvDAAw9g2bJlOHPmDG644QZkZmbi2LFjePHFF/G1r30N99xzD5YuXYq33noL1113HZ5++mkUFBSgoqICjz32GEpKSvD+++9HJZ43NTUZQ4URTqcTl112WVzvuS0LFy7EunXrsGjRIjz11FO4+uqr4fV68dxzz+Htt9/GunXrjHylWLKysnDDDTdg+fLlePfddyEIAl566SVcc801mD9/Ph566CFkZGRgx44dWLZsGQoLC3HHHXcY299333247bbbkJeXhzlz5qChoQHPPvssamtrW+WqNTY2tvp+WCwWJCYmduszYGxAuajP7jHG2hUIBOjBBx+kKVOmkNvtJrvdTmPGjKFHHnmEGhsbo9q2V3IAQMy/srIyY9tY68eMGWPsJ1bJASKiwsJCmjt3LhG1XXIg8jrimmuuIQBGyYGIzz//nL73ve9RWloaybJMycnJVFhYSK+//npcJQci/vrXv9KVV15JTqeTEhISaOLEibRy5cqo82hoaKCHH36YcnJyyGQyUVJSEs2fP5/27dsXta8VK1bE/GyuvvrquM+nvbIF4XCYnnrqKcrPzyez2Uwul4sKCwvpk08+iWrXVumIbdu2EQDasWOHsWzv3r00f/58SkpKMs73Zz/7GYXD4Vbbv/rqqzR16lRyOp2Unp5O3/rWt2jPnj1Rbb7xjW/E/AwKCwvj/gwYuxQIRP0kG5IxxliP0zQNt912G/7xj3/go48+MvKeGGOdx0ETY4xd4jRNw7PPPgun04kf/ehHF/t0GBuwOGhijA0Yd955J/785z/HXPfDH/4QL774Yp+dy8cff9yq1lVLfr+/z86FMdY3OGhijA0YlZWV8Hq9Mde5XC6kpaX12bk0NTXhzJkzba7nx/MZu/Rw0MQYY4wxFgeu08QYY4wxFgcOmhhjjDHG4sBBE2OMMcZYHDhoYowxxhiLAwdNjDHGGGNx4KCJMcYYYywOHDQxxhhjjMWBgybGGGOMsTj8f2zGFgpkJV9HAAAAAElFTkSuQmCC", + "text/plain": [ + "
" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "import matplotlib.pyplot as plt\n", + "\n", + "valid_steering = (ADAS_ActvACILvl2Sta == 2) # only when cruise is activated and eyesight is braking\n", + "\n", + "fig, ax = plt.subplots()\n", + "\n", + "ax.set_title(\"Steering Column Torque vs ADAS Torque Reduction Gain Value\")\n", + "ax.set_xlabel(\"STEERING_COL_TORQUE\")\n", + "ax.set_ylabel(\"ADAS_ACIAnglTqRedcGainVal\")\n", + "\n", + "ax.scatter(\n", + " STEERING_COL_TORQUE[valid_steering],\n", + " ADAS_StrAnglReqVal[valid_steering],\n", + " label=\"Torque vs Req Angle\",\n", + " alpha=0.7\n", + ")\n", + "\n", + "ax.scatter(\n", + " ADAS_ACIAnglTqRedcGainVal[valid_steering],\n", + " STEERING_ANGLE_2[valid_steering],\n", + " label=\"ADAS Gain vs Measured Angle\",\n", + " alpha=0.7\n", + ")\n", + "\n", + "ax.legend()\n", + "plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "dcb36483-a30d-4f04-ba04-6884291c3020", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.0" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/tools/tuning/measure_steering_accuracy.py b/tools/car_porting/measure_steering_accuracy.py similarity index 94% rename from tools/tuning/measure_steering_accuracy.py rename to tools/car_porting/measure_steering_accuracy.py index a2f437819f..fa1da959a7 100755 --- a/tools/tuning/measure_steering_accuracy.py +++ b/tools/car_porting/measure_steering_accuracy.py @@ -1,5 +1,4 @@ #!/usr/bin/env python3 -# type: ignore import os import time @@ -7,7 +6,7 @@ import argparse import signal from collections import defaultdict -import cereal.messaging as messaging +import openpilot.cereal.messaging as messaging from openpilot.tools.lib.logreader import LogReader def sigint_handler(signal, frame): @@ -49,7 +48,7 @@ class SteeringAccuracyTool: active = sm['controlsState'].active steer = sm['carOutput'].actuatorsOutput.torque standstill = sm['carState'].standstill - steer_limited_by_controls = abs(sm['carControl'].actuators.torque - sm['carControl'].actuatorsOutput.torque) > 1e-2 + steer_limited_by_safety = abs(sm['carControl'].actuators.torque - sm['carControl'].actuatorsOutput.torque) > 1e-2 overriding = sm['carState'].steeringPressed changing_lanes = sm['modelV2'].meta.laneChangeState != 0 model_points = sm['modelV2'].position.y @@ -77,7 +76,7 @@ class SteeringAccuracyTool: self.speed_group_stats[group][angle_abs]["steer"] += abs(steer) if len(model_points): self.speed_group_stats[group][angle_abs]["dpp"] += abs(model_points[0]) - if steer_limited_by_controls: + if steer_limited_by_safety: self.speed_group_stats[group][angle_abs]["limited"] += 1 if control_state.saturated: self.speed_group_stats[group][angle_abs]["saturated"] += 1 @@ -118,12 +117,8 @@ if __name__ == "__main__": parser.add_argument('--route', help="route name") parser.add_argument('--addr', default='127.0.0.1', help="IP address for optional ZMQ listener, default to msgq") parser.add_argument('--group', default='all', help="speed group to display, [crawl|slow|medium|fast|veryfast|germany|all], default to all") - parser.add_argument('--cache', default=False, action='store_true', help="use cached data, default to False") args = parser.parse_args() - if args.cache: - os.environ['FILEREADER_CACHE'] = '1' - tool = SteeringAccuracyTool(args) if args.route is not None: diff --git a/tools/car_porting/test_car_model.py b/tools/car_porting/test_car_model.py index dd248f562e..61ec2e15ed 100755 --- a/tools/car_porting/test_car_model.py +++ b/tools/car_porting/test_car_model.py @@ -1,8 +1,7 @@ #!/usr/bin/env python3 import argparse import sys -import unittest # noqa: TID251 - +import unittest from opendbc.car.tests.routes import CarTestRoute from openpilot.selfdrive.car.tests.test_models import TestCarModel from openpilot.tools.lib.route import SegmentRange @@ -20,7 +19,7 @@ def create_test_models_suite(routes: list[CarTestRoute]) -> unittest.TestSuite: if __name__ == "__main__": parser = argparse.ArgumentParser(description="Test any route against common issues with a new car port. " + - "Uses selfdrive/car/tests/test_models.py") + "Uses openpilot/selfdrive/car/tests/test_models.py") parser.add_argument("route_or_segment_name", help="Specify route to run tests on") parser.add_argument("--car", help="Specify car model for test route") args = parser.parse_args() diff --git a/tools/clip/run.py b/tools/clip/run.py deleted file mode 100755 index a84290f9c4..0000000000 --- a/tools/clip/run.py +++ /dev/null @@ -1,320 +0,0 @@ -#!/usr/bin/env python3 - -import atexit -import logging -import os -import platform -import shutil -import sys -import time -from argparse import ArgumentParser, ArgumentTypeError -from collections.abc import Sequence -from pathlib import Path -from random import randint -from subprocess import Popen, PIPE -from typing import Literal - -from cereal.messaging import SubMaster -from openpilot.common.basedir import BASEDIR -from openpilot.common.params import Params, UnknownKeyName -from openpilot.common.prefix import OpenpilotPrefix -from openpilot.tools.lib.route import Route -from openpilot.tools.lib.logreader import LogReader - -DEFAULT_OUTPUT = 'output.mp4' -DEMO_START = 90 -DEMO_END = 105 -DEMO_ROUTE = 'a2a0ccea32023010/2023-07-27--13-01-19' -FRAMERATE = 20 -PIXEL_DEPTH = '24' -RESOLUTION = '2160x1080' -SECONDS_TO_WARM = 2 -PROC_WAIT_SECONDS = 30 - -OPENPILOT_FONT = str(Path(BASEDIR, 'selfdrive/assets/fonts/Inter-Regular.ttf').resolve()) -REPLAY = str(Path(BASEDIR, 'tools/replay/replay').resolve()) -UI = str(Path(BASEDIR, 'selfdrive/ui/ui').resolve()) - -logger = logging.getLogger('clip.py') - - -def check_for_failure(proc: Popen): - exit_code = proc.poll() - if exit_code is not None and exit_code != 0: - cmd = str(proc.args) - if isinstance(proc.args, str): - cmd = proc.args - elif isinstance(proc.args, Sequence): - cmd = str(proc.args[0]) - msg = f'{cmd} failed, exit code {exit_code}' - logger.error(msg) - stdout, stderr = proc.communicate() - if stdout: - logger.error(stdout.decode()) - if stderr: - logger.error(stderr.decode()) - raise ChildProcessError(msg) - - -def escape_ffmpeg_text(value: str): - special_chars = {',': '\\,', ':': '\\:', '=': '\\=', '[': '\\[', ']': '\\]'} - value = value.replace('\\', '\\\\\\\\\\\\\\\\') - for char, escaped in special_chars.items(): - value = value.replace(char, escaped) - return value - - -def get_logreader(route: Route): - return LogReader(route.qlog_paths()[0] if len(route.qlog_paths()) else route.name.canonical_name) - - -def get_meta_text(lr: LogReader, route: Route): - init_data = lr.first('initData') - car_params = lr.first('carParams') - origin_parts = init_data.gitRemote.split('/') - origin = origin_parts[3] if len(origin_parts) > 3 else 'unknown' - return ', '.join([ - f"openpilot v{init_data.version}", - f"route: {route.name.canonical_name}", - f"car: {car_params.carFingerprint}", - f"origin: {origin}", - f"branch: {init_data.gitBranch}", - f"commit: {init_data.gitCommit[:7]}", - f"modified: {str(init_data.dirty).lower()}", - ]) - - -def parse_args(parser: ArgumentParser): - args = parser.parse_args() - if args.demo: - args.route = DEMO_ROUTE - if args.start is None or args.end is None: - args.start = DEMO_START - args.end = DEMO_END - elif args.route.count('/') == 1: - if args.start is None or args.end is None: - parser.error('must provide both start and end if timing is not in the route ID') - elif args.route.count('/') == 3: - if args.start is not None or args.end is not None: - parser.error('don\'t provide timing when including it in the route ID') - parts = args.route.split('/') - args.route = '/'.join(parts[:2]) - args.start = int(parts[2]) - args.end = int(parts[3]) - if args.end <= args.start: - parser.error(f'end ({args.end}) must be greater than start ({args.start})') - if args.start < SECONDS_TO_WARM: - parser.error(f'start must be greater than {SECONDS_TO_WARM}s to allow the UI time to warm up') - - try: - args.route = Route(args.route, data_dir=args.data_dir) - except Exception as e: - parser.error(f'failed to get route: {e}') - - # FIXME: length isn't exactly max segment seconds, simplify to replay exiting at end of data - length = round(args.route.max_seg_number * 60) - if args.start >= length: - parser.error(f'start ({args.start}s) cannot be after end of route ({length}s)') - if args.end > length: - parser.error(f'end ({args.end}s) cannot be after end of route ({length}s)') - - return args - - -def populate_car_params(lr: LogReader): - init_data = lr.first('initData') - assert init_data is not None - - params = Params() - entries = init_data.params.entries - for cp in entries: - key, value = cp.key, cp.value - try: - params.put(key, value) - except UnknownKeyName: - # forks of openpilot may have other Params keys configured. ignore these - logger.warning(f"unknown Params key '{key}', skipping") - logger.debug('persisted CarParams') - - -def start_proc(args: list[str], env: dict[str, str]): - return Popen(args, env=env, stdout=PIPE, stderr=PIPE) - - -def validate_env(parser: ArgumentParser): - if platform.system() not in ['Linux']: - parser.exit(1, f'clip.py: error: {platform.system()} is not a supported operating system\n') - for proc in ['Xvfb', 'ffmpeg']: - if shutil.which(proc) is None: - parser.exit(1, f'clip.py: error: missing {proc} command, is it installed?\n') - for proc in [REPLAY, UI]: - if shutil.which(proc) is None: - parser.exit(1, f'clip.py: error: missing {proc} command, did you build openpilot yet?\n') - - -def validate_output_file(output_file: str): - if not output_file.endswith('.mp4'): - raise ArgumentTypeError('output must be an mp4') - return output_file - - -def validate_route(route: str): - if route.count('/') not in (1, 3): - raise ArgumentTypeError(f'route must include or exclude timing, example: {DEMO_ROUTE}') - return route - - -def validate_title(title: str): - if len(title) > 80: - raise ArgumentTypeError('title must be no longer than 80 chars') - return title - - -def wait_for_frames(procs: list[Popen]): - sm = SubMaster(['uiDebug']) - no_frames_drawn = True - while no_frames_drawn: - sm.update() - no_frames_drawn = sm['uiDebug'].drawTimeMillis == 0. - for proc in procs: - check_for_failure(proc) - - -def clip( - data_dir: str | None, - quality: Literal['low', 'high'], - prefix: str, - route: Route, - out: str, - start: int, - end: int, - target_mb: int, - title: str | None, -): - logger.info(f'clipping route {route.name.canonical_name}, start={start} end={end} quality={quality} target_filesize={target_mb}MB') - lr = get_logreader(route) - - begin_at = max(start - SECONDS_TO_WARM, 0) - duration = end - start - bit_rate_kbps = int(round(target_mb * 8 * 1024 * 1024 / duration / 1000)) - - # TODO: evaluate creating fn that inspects /tmp/.X11-unix and creates unused display to avoid possibility of collision - display = f':{randint(99, 999)}' - - box_style = 'box=1:boxcolor=black@0.33:boxborderw=7' - meta_text = get_meta_text(lr, route) - overlays = [ - # metadata overlay - f"drawtext=text='{escape_ffmpeg_text(meta_text)}':fontfile={OPENPILOT_FONT}:fontcolor=white:fontsize=15:{box_style}:x=(w-text_w)/2:y=5.5:enable='between(t,1,5)'", - # route time overlay - f"drawtext=text='%{{eif\\:floor(({start}+t)/60)\\:d\\:2}}\\:%{{eif\\:mod({start}+t\\,60)\\:d\\:2}}':fontfile={OPENPILOT_FONT}:fontcolor=white:fontsize=24:{box_style}:x=w-text_w-38:y=38" - ] - if title: - overlays.append(f"drawtext=text='{escape_ffmpeg_text(title)}':fontfile={OPENPILOT_FONT}:fontcolor=white:fontsize=32:{box_style}:x=(w-text_w)/2:y=53") - - ffmpeg_cmd = [ - 'ffmpeg', '-y', - '-video_size', RESOLUTION, - '-framerate', str(FRAMERATE), - '-f', 'x11grab', - '-rtbufsize', '100M', - '-draw_mouse', '0', - '-i', display, - '-c:v', 'libx264', - '-maxrate', f'{bit_rate_kbps}k', - '-bufsize', f'{bit_rate_kbps*2}k', - '-crf', '23', - '-filter:v', ','.join(overlays), - '-preset', 'ultrafast', - '-tune', 'zerolatency', - '-pix_fmt', 'yuv420p', - '-movflags', '+faststart', - '-f', 'mp4', - '-t', str(duration), - out, - ] - - replay_cmd = [REPLAY, '--ecam', '-c', '1', '-s', str(begin_at), '--prefix', prefix] - if data_dir: - replay_cmd.extend(['--data_dir', data_dir]) - if quality == 'low': - replay_cmd.append('--qcam') - replay_cmd.append(route.name.canonical_name) - - ui_cmd = [UI, '-platform', 'xcb'] - xvfb_cmd = ['Xvfb', display, '-terminate', '-screen', '0', f'{RESOLUTION}x{PIXEL_DEPTH}'] - - with OpenpilotPrefix(prefix, shared_download_cache=True): - populate_car_params(lr) - - env = os.environ.copy() - env['DISPLAY'] = display - - xvfb_proc = start_proc(xvfb_cmd, env) - atexit.register(lambda: xvfb_proc.terminate()) - ui_proc = start_proc(ui_cmd, env) - atexit.register(lambda: ui_proc.terminate()) - replay_proc = start_proc(replay_cmd, env) - atexit.register(lambda: replay_proc.terminate()) - procs = [replay_proc, ui_proc, xvfb_proc] - - logger.info('waiting for replay to begin (loading segments, may take a while)...') - wait_for_frames(procs) - - logger.debug(f'letting UI warm up ({SECONDS_TO_WARM}s)...') - time.sleep(SECONDS_TO_WARM) - for proc in procs: - check_for_failure(proc) - - ffmpeg_proc = start_proc(ffmpeg_cmd, env) - procs.append(ffmpeg_proc) - atexit.register(lambda: ffmpeg_proc.terminate()) - - logger.info(f'recording in progress ({duration}s)...') - ffmpeg_proc.wait(duration + PROC_WAIT_SECONDS) - for proc in procs: - check_for_failure(proc) - logger.info(f'recording complete: {Path(out).resolve()}') - - -def main(): - p = ArgumentParser(prog='clip.py', description='clip your openpilot route.', epilog='comma.ai') - validate_env(p) - route_group = p.add_mutually_exclusive_group(required=True) - route_group.add_argument('route', nargs='?', type=validate_route, help=f'The route (e.g. {DEMO_ROUTE} or {DEMO_ROUTE}/{DEMO_START}/{DEMO_END})') - route_group.add_argument('--demo', help='use the demo route', action='store_true') - p.add_argument('-d', '--data-dir', help='local directory where route data is stored') - p.add_argument('-e', '--end', help='stop clipping at seconds', type=int) - p.add_argument('-f', '--file-size', help='target file size (Discord/GitHub support max 10MB, default is 9MB)', type=float, default=9.) - p.add_argument('-o', '--output', help='output clip to (.mp4)', type=validate_output_file, default=DEFAULT_OUTPUT) - p.add_argument('-p', '--prefix', help='openpilot prefix', default=f'clip_{randint(100, 99999)}') - p.add_argument('-q', '--quality', help='quality of camera (low = qcam, high = hevc)', choices=['low', 'high'], default='high') - p.add_argument('-s', '--start', help='start clipping at seconds', type=int) - p.add_argument('-t', '--title', help='overlay this title on the video (e.g. "Chill driving across the Golden Gate Bridge")', type=validate_title) - args = parse_args(p) - exit_code = 1 - try: - clip( - data_dir=args.data_dir, - quality=args.quality, - prefix=args.prefix, - route=args.route, - out=args.output, - start=args.start, - end=args.end, - target_mb=args.file_size, - title=args.title, - ) - exit_code = 0 - except KeyboardInterrupt as e: - logger.exception('interrupted by user', exc_info=e) - except Exception as e: - logger.exception('encountered error', exc_info=e) - finally: - atexit._run_exitfuncs() - sys.exit(exit_code) - - -if __name__ == '__main__': - logging.basicConfig(level=logging.INFO, format='%(asctime)s %(name)s %(levelname)s\t%(message)s') - main() diff --git a/tools/install_python_dependencies.sh b/tools/install_python_dependencies.sh deleted file mode 100755 index cdbaca32cf..0000000000 --- a/tools/install_python_dependencies.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/usr/bin/env bash -set -e - -# Increase the pip timeout to handle TimeoutError -export PIP_DEFAULT_TIMEOUT=200 - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )" -ROOT="$DIR"/../ -cd "$ROOT" - -if ! command -v "uv" > /dev/null 2>&1; then - echo "installing uv..." - curl -LsSf https://astral.sh/uv/install.sh | sh - UV_BIN="$HOME/.local/bin" - PATH="$UV_BIN:$PATH" -fi - -echo "updating uv..." -# ok to fail, can also fail due to installing with brew -uv self update || true - -echo "installing python packages..." -uv sync --frozen --all-extras -source .venv/bin/activate - -if [[ "$(uname)" == 'Darwin' ]]; then - touch "$ROOT"/.env - echo "# msgq doesn't work on mac" >> "$ROOT"/.env - echo "export ZMQ=1" >> "$ROOT"/.env - echo "export OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES" >> "$ROOT"/.env -fi diff --git a/tools/install_ubuntu_dependencies.sh b/tools/install_ubuntu_dependencies.sh deleted file mode 100755 index f33569704a..0000000000 --- a/tools/install_ubuntu_dependencies.sh +++ /dev/null @@ -1,126 +0,0 @@ -#!/usr/bin/env bash -set -e - -SUDO="" - -# Use sudo if not root -if [[ ! $(id -u) -eq 0 ]]; then - if [[ -z $(which sudo) ]]; then - echo "Please install sudo or run as root" - exit 1 - fi - SUDO="sudo" -fi - -# Check if stdin is open -if [ -t 0 ]; then - INTERACTIVE=1 -fi - -# Install common packages -function install_ubuntu_common_requirements() { - $SUDO apt-get update - $SUDO apt-get install -y --no-install-recommends \ - ca-certificates \ - clang \ - build-essential \ - gcc-arm-none-eabi \ - liblzma-dev \ - capnproto \ - libcapnp-dev \ - curl \ - libcurl4-openssl-dev \ - git \ - git-lfs \ - ffmpeg \ - libavformat-dev \ - libavcodec-dev \ - libavdevice-dev \ - libavutil-dev \ - libavfilter-dev \ - libbz2-dev \ - libeigen3-dev \ - libffi-dev \ - libglew-dev \ - libgles2-mesa-dev \ - libglfw3-dev \ - libglib2.0-0 \ - libjpeg-dev \ - libqt5charts5-dev \ - libncurses5-dev \ - libssl-dev \ - libusb-1.0-0-dev \ - libzmq3-dev \ - libzstd-dev \ - libsqlite3-dev \ - libsystemd-dev \ - locales \ - opencl-headers \ - ocl-icd-libopencl1 \ - ocl-icd-opencl-dev \ - portaudio19-dev \ - qttools5-dev-tools \ - libqt5svg5-dev \ - libqt5serialbus5-dev \ - libqt5x11extras5-dev \ - libqt5opengl5-dev \ - xvfb -} - -# Install Ubuntu 24.04 LTS packages -function install_ubuntu_lts_latest_requirements() { - install_ubuntu_common_requirements - - $SUDO apt-get install -y --no-install-recommends \ - g++-12 \ - qtbase5-dev \ - qtchooser \ - qt5-qmake \ - qtbase5-dev-tools \ - python3-dev \ - python3-venv -} - -# Detect OS using /etc/os-release file -if [ -f "/etc/os-release" ]; then - source /etc/os-release - case "$VERSION_CODENAME" in - "jammy" | "kinetic" | "noble") - install_ubuntu_lts_latest_requirements - ;; - *) - echo "$ID $VERSION_ID is unsupported. This setup script is written for Ubuntu 24.04." - read -p "Would you like to attempt installation anyway? " -n 1 -r - echo "" - if [[ ! $REPLY =~ ^[Yy]$ ]]; then - exit 1 - fi - install_ubuntu_lts_latest_requirements - esac - - if [[ -d "/etc/udev/rules.d/" ]]; then - # Setup jungle udev rules - $SUDO tee /etc/udev/rules.d/12-panda_jungle.rules > /dev/null < /dev/null < /data/params/d/JoystickDebugMode - ``` -3. Run bridge with your laptop's IP address. This republishes the `testJoystick` packets sent from your laptop so that openpilot can receive them: - ```shell - # on your comma device - cereal/messaging/bridge {LAPTOP_IP} testJoystick - ``` -4. Start joystick_control on your laptop in ZMQ mode. - ```shell - # on your laptop - export ZMQ=1 - tools/joystick/joystick_control.py - ``` - ---- -Now start your car and openpilot should go into joystick mode with an alert on startup! The status of the axes will display on the alert, while button statuses print in the shell. - -Make sure the conditions are met in the panda to allow controls (e.g. cruise control engaged). You can also make a modification to the panda code to always allow controls. - -![](https://github.com/commaai/openpilot/assets/8762862/e640cbca-cb7a-4dcb-abce-b23b036ad8e7) diff --git a/tools/joystick/joystick_control.py b/tools/joystick/joystick_control.py deleted file mode 100755 index f6735eeb74..0000000000 --- a/tools/joystick/joystick_control.py +++ /dev/null @@ -1,216 +0,0 @@ -#!/usr/bin/env python3 -import os -import argparse -import threading -import numpy as np -try: - import pygame as pg -except ImportError: - print("pygame is not installed. Please install it with 'uv pip install pygame'") - -from cereal import messaging -from openpilot.common.params import Params -from openpilot.common.realtime import Ratekeeper -from openpilot.system.hardware import HARDWARE -from openpilot.tools.lib.kbhit import KBHit - -# Set SDL environment variable to avoid using a video driver for headless operation -os.environ["SDL_VIDEODRIVER"] = "dummy" - -EXPO = 0.4 # Exponential factor for joystick response curve - - -class Keyboard: - def __init__(self): - self.kb = KBHit() - self.axis_increment = 0.05 # 5% of full actuation each key press - self.axes_map = {'w': 'gb', 's': 'gb', - 'a': 'steer', 'd': 'steer'} - self.axes_values = {'gb': 0., 'steer': 0.} - self.axes_order = ['gb', 'steer'] - self.cancel = False - - def update(self): - key = self.kb.getch().lower() - self.cancel = False - if key == 'r': - self.axes_values = dict.fromkeys(self.axes_values, 0.) - elif key == 'c': - self.cancel = True - elif key in self.axes_map: - axis = self.axes_map[key] - incr = self.axis_increment if key in ['w', 'a'] else -self.axis_increment - self.axes_values[axis] = float(np.clip(self.axes_values[axis] + incr, -1, 1)) - else: - return False - return True - - -class PyGameJoystick: - def __init__(self): - # Initialize pygame and joystick subsystem - pg.init() - if not pg.joystick.get_init(): - pg.joystick.init() - - # Find connected joysticks - joystick_count = pg.joystick.get_count() - if joystick_count == 0: - print("No joysticks found. Please connect a controller.") - exit(1) - - # Initialize the first joystick - self.joystick = pg.joystick.Joystick(0) - self.joystick.init() - - print(f"Using joystick: {self.joystick.get_name()}") - print(f"Number of axes: {self.joystick.get_numaxes()}") - print(f"Number of buttons: {self.joystick.get_numbuttons()}") - print(f"Number of hats: {self.joystick.get_numhats()}") - - # This supports PlayStation and Xbox controllers on different platforms - if HARDWARE.get_device_type() == 'pc': - # Xbox mapping on PC - self.accel_axis = 5 # Right trigger - self.brake_axis = 4 # Left trigger - self.steer_axis = 0 # Left stick horizontal - self.cancel_button = 3 # Y/Triangle button - else: - # PlayStation mapping on comma device - self.accel_axis = 5 # R2 - self.brake_axis = 4 # L2 - self.steer_axis = 0 # Left stick horizontal - self.cancel_button = 3 # Triangle button - - # Configure for adaptive mappings based on detected controller - controller_name = self.joystick.get_name().lower() - if "xbox" in controller_name: - print("Xbox controller detected, using Xbox mappings") - self.accel_axis = 5 # Right trigger (RT) - self.brake_axis = 4 # Left trigger (LT) - self.cancel_button = 3 # Y button - elif "playstation" in controller_name or "dual" in controller_name: - print("PlayStation controller detected, using PlayStation mappings") - self.accel_axis = 5 # R2 - self.brake_axis = 4 # L2 - self.cancel_button = 3 # Triangle - - # Initialize values - self.axes_values = {'gb': 0., 'steer': 0.} # Maintain same keys as Keyboard class - self.axes_order = ['gb', 'steer'] # Match expected format - self.cancel = False - self.deadzone = 0.03 # 3% deadzone for noisy joysticks - - # Process events once to clear the event queue - pg.event.pump() - - def update(self): - # Process pygame events - try: - for event in pg.event.get(): - if event.type == pg.JOYDEVICEREMOVED: - if event.instance_id == self.joystick.get_instance_id(): - print("Joystick disconnected!") - self.axes_values = {'gb': 0., 'steer': 0.} - return False - - elif event.type == pg.JOYBUTTONDOWN: - if event.button == self.cancel_button: - self.cancel = True - - elif event.type == pg.JOYBUTTONUP: - if event.button == self.cancel_button: - self.cancel = False - except Exception as e: - print(f"Error processing events: {e}") - return False - - # Read current joystick state directly - try: - if not self.joystick.get_init(): - print("Joystick not initialized") - return False - - # Read steering (left stick horizontal) - steer_raw = self.joystick.get_axis(self.steer_axis) * -1 - steer = steer_raw if abs(steer_raw) > self.deadzone else 0.0 - - # Read gas (right trigger) - accel_raw = self.joystick.get_axis(self.accel_axis) - # Convert from [-1, 1] to [0, 1] range (triggers often start at -1 when not pressed) - accel = (accel_raw + 1) / 2 if self.accel_axis in [4, 5] else accel_raw - accel = accel if accel > self.deadzone else 0.0 - - # Read brake (left trigger) - brake_raw = self.joystick.get_axis(self.brake_axis) - # Convert from [-1, 1] to [0, 1] range (triggers often start at -1 when not pressed) - brake = (brake_raw + 1) / 2 if self.brake_axis in [4, 5] else brake_raw - brake = brake if brake > self.deadzone else 0.0 - - # Apply expo for steering - self.axes_values['steer'] = EXPO * steer**3 + (1 - EXPO) * steer # Apply expo for fine control - - # Calculate combined gas/brake value for output [-1, 1] where negative is brake - self.axes_values['gb'] = accel - brake - - except Exception as e: - print(f"Error reading joystick: {e}") - self.axes_values = {'gb': 0., 'steer': 0.} - return False - return True - - -def send_thread(joystick): - pm = messaging.PubMaster(['testJoystick']) - rk = Ratekeeper(100, print_delay_threshold=None) - - while True: - if rk.frame % 20 == 0: - print('\n' + ', '.join(f'{name}: {round(v, 3)}' for name, v in joystick.axes_values.items())) - - joystick_msg = messaging.new_message('testJoystick') - joystick_msg.valid = True - joystick_msg.testJoystick.axes = [joystick.axes_values[ax] for ax in joystick.axes_order] - - pm.send('testJoystick', joystick_msg) - rk.keep_time() - - -def joystick_control_thread(joystick): - Params().put_bool('JoystickDebugMode', True) - threading.Thread(target=send_thread, args=(joystick,), daemon=True).start() - while True: - joystick.update() - - -def main(): - joystick_control_thread(PyGameJoystick()) - -if __name__ == '__main__': - parser = argparse.ArgumentParser(description='Publishes events from your joystick to control your car.\n' + - 'openpilot must be offroad before starting joystick_control. This tool supports ' + - 'PlayStation and Xbox controllers on various platforms.', - formatter_class=argparse.ArgumentDefaultsHelpFormatter) - parser.add_argument('--keyboard', action='store_true', help='Use your keyboard instead of a joystick') - args = parser.parse_args() - - if not Params().get_bool("IsOffroad") and "ZMQ" not in os.environ: - print("The car must be off before running joystick_control.") - exit() - - print() - if args.keyboard: - print('Gas/brake control: `W` and `S` keys') - print('Steering control: `A` and `D` keys') - print('Buttons') - print('- `R`: Resets axes') - print('- `C`: Cancel cruise control') - joystick_control_thread(Keyboard()) - else: - print('Using pygame joystick') - print('Standard controller mapping:') - print('- Left stick: Steering') - print('- Right trigger (R2): Gas') - print('- Left trigger (L2): Brake') - print('- Triangle/Y button: Cancel') - joystick_control_thread(PyGameJoystick()) diff --git a/tools/lib/README.md b/tools/lib/README.md deleted file mode 100644 index af1ad0de22..0000000000 --- a/tools/lib/README.md +++ /dev/null @@ -1,59 +0,0 @@ -## LogReader - -Route is a class for conveniently accessing all the [logs](/system/loggerd/) from your routes. The LogReader class reads the non-video logs, i.e. rlog.bz2 and qlog.bz2. There's also a matching FrameReader class for reading the videos. - -```python -from openpilot.tools.lib.route import Route -from openpilot.tools.lib.logreader import LogReader - -r = Route("a2a0ccea32023010|2023-07-27--13-01-19") - -# get a list of paths for the route's rlog files -print(r.log_paths()) - -# and road camera (fcamera.hevc) files -print(r.camera_paths()) - -# setup a LogReader to read the route's first rlog -lr = LogReader(r.log_paths()[0]) - -# print out all the messages in the log -import codecs -codecs.register_error("strict", codecs.backslashreplace_errors) -for msg in lr: - print(msg) - -# setup a LogReader for the route's second qlog -lr = LogReader(r.log_paths()[1]) - -# print all the steering angles values from the log -for msg in lr: - if msg.which() == "carState": - print(msg.carState.steeringAngleDeg) -``` - -### Segment Ranges - -We also support a new format called a "segment range": - -``` -344c5c15b34f2d8a / 2024-01-03--09-37-12 / 2:6 / q -[ dongle id ] [ timestamp ] [ selector ] [ query type] -``` - -you can specify which segments from a route to load - -```python -lr = LogReader("a2a0ccea32023010|2023-07-27--13-01-19/4") # 4th segment -lr = LogReader("a2a0ccea32023010|2023-07-27--13-01-19/4:6") # 4th and 5th segment -lr = LogReader("a2a0ccea32023010|2023-07-27--13-01-19/-1") # last segment -lr = LogReader("a2a0ccea32023010|2023-07-27--13-01-19/:5") # first 5 segments -lr = LogReader("a2a0ccea32023010|2023-07-27--13-01-19/1:") # all except first segment -``` - -and can select which type of logs to grab - -```python -lr = LogReader("a2a0ccea32023010|2023-07-27--13-01-19/4/q") # get qlogs -lr = LogReader("a2a0ccea32023010|2023-07-27--13-01-19/4/r") # get rlogs (default) -``` diff --git a/tools/lib/api.py b/tools/lib/api.py deleted file mode 100644 index c2e1b1a8cd..0000000000 --- a/tools/lib/api.py +++ /dev/null @@ -1,34 +0,0 @@ -import os -import requests -API_HOST = os.getenv('API_HOST', 'https://api.commadotai.com') - -class CommaApi: - def __init__(self, token=None): - self.session = requests.Session() - self.session.headers['User-agent'] = 'OpenpilotTools' - if token: - self.session.headers['Authorization'] = 'JWT ' + token - - def request(self, method, endpoint, **kwargs): - with self.session.request(method, API_HOST + '/' + endpoint, **kwargs) as resp: - resp_json = resp.json() - if isinstance(resp_json, dict) and resp_json.get('error'): - if resp.status_code in [401, 403]: - raise UnauthorizedError('Unauthorized. Authenticate with tools/lib/auth.py') - - e = APIError(str(resp.status_code) + ":" + resp_json.get('description', str(resp_json['error']))) - e.status_code = resp.status_code - raise e - return resp_json - - def get(self, endpoint, **kwargs): - return self.request('GET', endpoint, **kwargs) - - def post(self, endpoint, **kwargs): - return self.request('POST', endpoint, **kwargs) - -class APIError(Exception): - pass - -class UnauthorizedError(Exception): - pass diff --git a/tools/lib/filereader.py b/tools/lib/filereader.py deleted file mode 100644 index 0bb4abd2fa..0000000000 --- a/tools/lib/filereader.py +++ /dev/null @@ -1,44 +0,0 @@ -import os -import posixpath -import socket -from urllib.parse import urlparse - -from openpilot.tools.lib.url_file import URLFile - -DATA_ENDPOINT = os.getenv("DATA_ENDPOINT", "http://data-raw.comma.internal/") - - -def internal_source_available(url=DATA_ENDPOINT): - if os.path.isdir(url): - return True - - try: - hostname = urlparse(url).hostname - port = urlparse(url).port or 80 - with socket.socket(socket.AF_INET,socket.SOCK_STREAM) as s: - s.settimeout(0.5) - s.connect((hostname, port)) - return True - except (socket.gaierror, ConnectionRefusedError): - pass - return False - - -def resolve_name(fn): - if fn.startswith("cd:/"): - return posixpath.join(DATA_ENDPOINT, fn[4:]) - return fn - - -def file_exists(fn): - fn = resolve_name(fn) - if fn.startswith(("http://", "https://")): - return URLFile(fn).get_length_online() != -1 - return os.path.exists(fn) - - -def FileReader(fn, debug=False): - fn = resolve_name(fn) - if fn.startswith(("http://", "https://")): - return URLFile(fn, debug=debug) - return open(fn, "rb") diff --git a/tools/lib/helpers.py b/tools/lib/helpers.py deleted file mode 100644 index 7c34e17cb1..0000000000 --- a/tools/lib/helpers.py +++ /dev/null @@ -1,17 +0,0 @@ -# regex patterns -class RE: - DONGLE_ID = r'(?P[a-f0-9]{16})' - TIMESTAMP = r'(?P[0-9]{4}-[0-9]{2}-[0-9]{2}--[0-9]{2}-[0-9]{2}-[0-9]{2})' - LOG_ID_V2 = r'(?P[a-f0-9]{8})--(?P[a-z0-9]{10})' - LOG_ID = fr'(?P(?:{TIMESTAMP}|{LOG_ID_V2}))' - ROUTE_NAME = fr'(?P{DONGLE_ID}[|_/]{LOG_ID})' - SEGMENT_NAME = fr'{ROUTE_NAME}(?:--|/)(?P[0-9]+)' - - INDEX = r'-?[0-9]+' - SLICE = fr'(?P{INDEX})?:?(?P{INDEX})?:?(?P{INDEX})?' - SEGMENT_RANGE = fr'{ROUTE_NAME}(?:(--|/)(?P({SLICE})))?(?:/(?P([qras])))?' - - BOOTLOG_NAME = ROUTE_NAME - - EXPLORER_FILE = fr'^(?P{SEGMENT_NAME})--(?P[a-z]+\.[a-z0-9]+)$' - OP_SEGMENT_DIR = fr'^(?P{SEGMENT_NAME})$' diff --git a/tools/lib/logreader.py b/tools/lib/logreader.py deleted file mode 100755 index 34d3e5ea9f..0000000000 --- a/tools/lib/logreader.py +++ /dev/null @@ -1,339 +0,0 @@ -#!/usr/bin/env python3 -import bz2 -from functools import cache, partial -import multiprocessing -import capnp -import enum -import os -import pathlib -import sys -import tqdm -import urllib.parse -import warnings -import zstandard as zstd - -from collections.abc import Callable, Iterable, Iterator -from urllib.parse import parse_qs, urlparse - -from cereal import log as capnp_log -from openpilot.common.swaglog import cloudlog -from openpilot.tools.lib.comma_car_segments import get_url as get_comma_segments_url -from openpilot.tools.lib.openpilotci import get_url -from openpilot.tools.lib.filereader import FileReader, file_exists, internal_source_available -from openpilot.tools.lib.route import Route, SegmentRange -from openpilot.tools.lib.log_time_series import msgs_to_time_series - -LogMessage = type[capnp._DynamicStructReader] -LogIterable = Iterable[LogMessage] -RawLogIterable = Iterable[bytes] - - -def save_log(dest, log_msgs, compress=True): - dat = b"".join(msg.as_builder().to_bytes() for msg in log_msgs) - - if compress and dest.endswith(".bz2"): - dat = bz2.compress(dat) - elif compress and dest.endswith(".zst"): - dat = zstd.compress(dat, 10) - - with open(dest, "wb") as f: - f.write(dat) - -def decompress_stream(data: bytes): - dctx = zstd.ZstdDecompressor() - decompressed_data = b"" - - with dctx.stream_reader(data) as reader: - decompressed_data = reader.read() - - return decompressed_data - -class _LogFileReader: - def __init__(self, fn, canonicalize=True, only_union_types=False, sort_by_time=False, dat=None): - self.data_version = None - self._only_union_types = only_union_types - - ext = None - if not dat: - _, ext = os.path.splitext(urllib.parse.urlparse(fn).path) - if ext not in ('', '.bz2', '.zst'): - # old rlogs weren't compressed - raise ValueError(f"unknown extension {ext}") - - with FileReader(fn) as f: - dat = f.read() - - if ext == ".bz2" or dat.startswith(b'BZh9'): - dat = bz2.decompress(dat) - elif ext == ".zst" or dat.startswith(b'\x28\xB5\x2F\xFD'): - # https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#zstandard-frames - dat = decompress_stream(dat) - - ents = capnp_log.Event.read_multiple_bytes(dat) - - self._ents = [] - try: - for e in ents: - self._ents.append(e) - except capnp.KjException: - warnings.warn("Corrupted events detected", RuntimeWarning, stacklevel=1) - - if sort_by_time: - self._ents.sort(key=lambda x: x.logMonoTime) - - def __iter__(self) -> Iterator[capnp._DynamicStructReader]: - for ent in self._ents: - if self._only_union_types: - try: - ent.which() - yield ent - except capnp.lib.capnp.KjException: - pass - else: - yield ent - - -class ReadMode(enum.StrEnum): - RLOG = "r" # only read rlogs - QLOG = "q" # only read qlogs - SANITIZED = "s" # read from the commaCarSegments database - AUTO = "a" # default to rlogs, fallback to qlogs - AUTO_INTERACTIVE = "i" # default to rlogs, fallback to qlogs with a prompt from the user - - -LogPath = str | None -ValidFileCallable = Callable[[LogPath], bool] -Source = Callable[[SegmentRange, ReadMode], list[LogPath]] - -InternalUnavailableException = Exception("Internal source not available") - - -class LogsUnavailable(Exception): - pass - - -@cache -def default_valid_file(fn: LogPath) -> bool: - return fn is not None and file_exists(fn) - - -def auto_strategy(rlog_paths: list[LogPath], qlog_paths: list[LogPath], interactive: bool, valid_file: ValidFileCallable) -> list[LogPath]: - # auto select logs based on availability - missing_rlogs = [rlog is None or not valid_file(rlog) for rlog in rlog_paths].count(True) - if missing_rlogs != 0: - if interactive: - if input(f"{missing_rlogs}/{len(rlog_paths)} rlogs were not found, would you like to fallback to qlogs for those segments? (y/n) ").lower() != "y": - return rlog_paths - else: - cloudlog.warning(f"{missing_rlogs}/{len(rlog_paths)} rlogs were not found, falling back to qlogs for those segments...") - - return [rlog if valid_file(rlog) else (qlog if valid_file(qlog) else None) - for (rlog, qlog) in zip(rlog_paths, qlog_paths, strict=True)] - return rlog_paths - - -def apply_strategy(mode: ReadMode, rlog_paths: list[LogPath], qlog_paths: list[LogPath], valid_file: ValidFileCallable = default_valid_file) -> list[LogPath]: - if mode == ReadMode.RLOG: - return rlog_paths - elif mode == ReadMode.QLOG: - return qlog_paths - elif mode == ReadMode.AUTO: - return auto_strategy(rlog_paths, qlog_paths, False, valid_file) - elif mode == ReadMode.AUTO_INTERACTIVE: - return auto_strategy(rlog_paths, qlog_paths, True, valid_file) - raise ValueError(f"invalid mode: {mode}") - - -def comma_api_source(sr: SegmentRange, mode: ReadMode) -> list[LogPath]: - route = Route(sr.route_name) - - rlog_paths = [route.log_paths()[seg] for seg in sr.seg_idxs] - qlog_paths = [route.qlog_paths()[seg] for seg in sr.seg_idxs] - - # comma api will have already checked if the file exists - def valid_file(fn): - return fn is not None - - return apply_strategy(mode, rlog_paths, qlog_paths, valid_file=valid_file) - - -def internal_source(sr: SegmentRange, mode: ReadMode, file_ext: str = "bz2") -> list[LogPath]: - if not internal_source_available(): - raise InternalUnavailableException - - def get_internal_url(sr: SegmentRange, seg, file): - return f"cd:/{sr.dongle_id}/{sr.log_id}/{seg}/{file}.{file_ext}" - - # TODO: list instead of using static URLs to support routes with multiple file extensions - rlog_paths = [get_internal_url(sr, seg, "rlog") for seg in sr.seg_idxs] - qlog_paths = [get_internal_url(sr, seg, "qlog") for seg in sr.seg_idxs] - - return apply_strategy(mode, rlog_paths, qlog_paths) - - -def internal_source_zst(sr: SegmentRange, mode: ReadMode, file_ext: str = "zst") -> list[LogPath]: - return internal_source(sr, mode, file_ext) - - -def openpilotci_source(sr: SegmentRange, mode: ReadMode, file_ext: str = "bz2") -> list[LogPath]: - rlog_paths = [get_url(sr.route_name, seg, f"rlog.{file_ext}") for seg in sr.seg_idxs] - qlog_paths = [get_url(sr.route_name, seg, f"qlog.{file_ext}") for seg in sr.seg_idxs] - - return apply_strategy(mode, rlog_paths, qlog_paths) - - -def openpilotci_source_zst(sr: SegmentRange, mode: ReadMode) -> list[LogPath]: - return openpilotci_source(sr, mode, "zst") - - -def comma_car_segments_source(sr: SegmentRange, mode=ReadMode.RLOG) -> list[LogPath]: - return [get_comma_segments_url(sr.route_name, seg) for seg in sr.seg_idxs] - - -def testing_closet_source(sr: SegmentRange, mode=ReadMode.RLOG) -> list[LogPath]: - if not internal_source_available('http://testing.comma.life'): - raise InternalUnavailableException - return [f"http://testing.comma.life/download/{sr.route_name.replace('|', '/')}/{seg}/rlog" for seg in sr.seg_idxs] - - -def direct_source(file_or_url: str) -> list[LogPath]: - return [file_or_url] - - -def get_invalid_files(files): - for f in files: - if f is None or not file_exists(f): - yield f - - -def check_source(source: Source, *args) -> list[LogPath]: - files = source(*args) - assert len(files) > 0, "No files on source" - assert next(get_invalid_files(files), False) is False, "Some files are invalid" - return files - - -def auto_source(sr: SegmentRange, mode=ReadMode.RLOG, sources: list[Source] = None) -> list[LogPath]: - if mode == ReadMode.SANITIZED: - return comma_car_segments_source(sr, mode) - - if sources is None: - sources = [internal_source, internal_source_zst, openpilotci_source, openpilotci_source_zst, - comma_api_source, comma_car_segments_source, testing_closet_source] - exceptions = {} - - # for automatic fallback modes, auto_source needs to first check if rlogs exist for any source - if mode in [ReadMode.AUTO, ReadMode.AUTO_INTERACTIVE]: - for source in sources: - try: - return check_source(source, sr, ReadMode.RLOG) - except Exception: - pass - - # Automatically determine viable source - for source in sources: - try: - return check_source(source, sr, mode) - except Exception as e: - exceptions[source.__name__] = e - - raise LogsUnavailable("auto_source could not find any valid source, exceptions for sources:\n - " + - "\n - ".join([f"{k}: {repr(v)}" for k, v in exceptions.items()])) - - -def parse_indirect(identifier: str) -> str: - if "useradmin.comma.ai" in identifier: - query = parse_qs(urlparse(identifier).query) - return query["onebox"][0] - return identifier - - -def parse_direct(identifier: str): - if identifier.startswith(("http://", "https://", "cd:/")) or pathlib.Path(identifier).exists(): - return identifier - return None - - -class LogReader: - def _parse_identifier(self, identifier: str) -> list[LogPath]: - # useradmin, etc. - identifier = parse_indirect(identifier) - - # direct url or file - direct_parsed = parse_direct(identifier) - if direct_parsed is not None: - return direct_source(identifier) - - sr = SegmentRange(identifier) - mode = self.default_mode if sr.selector is None else ReadMode(sr.selector) - - identifiers = self.source(sr, mode) - - invalid_count = len(list(get_invalid_files(identifiers))) - assert invalid_count == 0, (f"{invalid_count}/{len(identifiers)} invalid log(s) found, please ensure all logs " + - "are uploaded or auto fallback to qlogs with '/a' selector at the end of the route name.") - return identifiers - - def __init__(self, identifier: str | list[str], default_mode: ReadMode = ReadMode.RLOG, - source: Source = auto_source, sort_by_time=False, only_union_types=False): - self.default_mode = default_mode - self.source = source - self.identifier = identifier - if isinstance(identifier, str): - self.identifier = [identifier] - - self.sort_by_time = sort_by_time - self.only_union_types = only_union_types - - self.__lrs: dict[int, _LogFileReader] = {} - self.reset() - - def _get_lr(self, i): - if i not in self.__lrs: - self.__lrs[i] = _LogFileReader(self.logreader_identifiers[i], sort_by_time=self.sort_by_time, only_union_types=self.only_union_types) - return self.__lrs[i] - - def __iter__(self): - for i in range(len(self.logreader_identifiers)): - yield from self._get_lr(i) - - def _run_on_segment(self, func, i): - return func(self._get_lr(i)) - - def run_across_segments(self, num_processes, func, disable_tqdm=False, desc=None): - with multiprocessing.Pool(num_processes) as pool: - ret = [] - num_segs = len(self.logreader_identifiers) - for p in tqdm.tqdm(pool.imap(partial(self._run_on_segment, func), range(num_segs)), total=num_segs, disable=disable_tqdm, desc=desc): - ret.extend(p) - return ret - - def reset(self): - self.logreader_identifiers = [] - for identifier in self.identifier: - self.logreader_identifiers.extend(self._parse_identifier(identifier)) - - @staticmethod - def from_bytes(dat): - return _LogFileReader("", dat=dat) - - def filter(self, msg_type: str): - return (getattr(m, m.which()) for m in filter(lambda m: m.which() == msg_type, self)) - - def first(self, msg_type: str): - return next(self.filter(msg_type), None) - - @property - def time_series(self): - return msgs_to_time_series(self) - -if __name__ == "__main__": - import codecs - - # capnproto <= 0.8.0 throws errors converting byte data to string - # below line catches those errors and replaces the bytes with \x__ - codecs.register_error("strict", codecs.backslashreplace_errors) - log_path = sys.argv[1] - lr = LogReader(log_path, sort_by_time=True) - for msg in lr: - print(msg) diff --git a/tools/lib/openpilotci.py b/tools/lib/openpilotci.py deleted file mode 100644 index 1c1e1f171b..0000000000 --- a/tools/lib/openpilotci.py +++ /dev/null @@ -1,12 +0,0 @@ -from openpilot.tools.lib.openpilotcontainers import OpenpilotCIContainer - -def get_url(*args, **kwargs): - return OpenpilotCIContainer.get_url(*args, **kwargs) - -def upload_file(*args, **kwargs): - return OpenpilotCIContainer.upload_file(*args, **kwargs) - -def upload_bytes(*args, **kwargs): - return OpenpilotCIContainer.upload_bytes(*args, **kwargs) - -BASE_URL = OpenpilotCIContainer.BASE_URL diff --git a/tools/lib/tests/test_caching.py b/tools/lib/tests/test_caching.py deleted file mode 100644 index 2bb63b4dce..0000000000 --- a/tools/lib/tests/test_caching.py +++ /dev/null @@ -1,130 +0,0 @@ -import http.server -import os -import shutil -import socket -import pytest - -from openpilot.selfdrive.test.helpers import http_server_context -from openpilot.system.hardware.hw import Paths -from openpilot.tools.lib.url_file import URLFile - - -class CachingTestRequestHandler(http.server.BaseHTTPRequestHandler): - FILE_EXISTS = True - - def do_GET(self): - if self.FILE_EXISTS: - self.send_response(206 if "Range" in self.headers else 200, b'1234') - else: - self.send_response(404) - self.end_headers() - - def do_HEAD(self): - if self.FILE_EXISTS: - self.send_response(200) - self.send_header("Content-Length", "4") - else: - self.send_response(404) - self.end_headers() - - -@pytest.fixture -def host(): - with http_server_context(handler=CachingTestRequestHandler) as (host, port): - yield f"http://{host}:{port}" - -class TestFileDownload: - - def test_pipeline_defaults(self, host): - # TODO: parameterize the defaults so we don't rely on hard-coded values in xx - - assert URLFile.pool_manager().pools._maxsize == 10# PoolManager num_pools param - pool_manager_defaults = { - "maxsize": 100, - "socket_options": [(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),], - } - for k, v in pool_manager_defaults.items(): - assert URLFile.pool_manager().connection_pool_kw.get(k) == v - - retry_defaults = { - "total": 5, - "backoff_factor": 0.5, - "status_forcelist": [409, 429, 503, 504], - } - for k, v in retry_defaults.items(): - assert getattr(URLFile.pool_manager().connection_pool_kw["retries"], k) == v - - # ensure caching off by default and cache dir doesn't get created - os.environ.pop("FILEREADER_CACHE", None) - if os.path.exists(Paths.download_cache_root()): - shutil.rmtree(Paths.download_cache_root()) - URLFile(f"{host}/test.txt").get_length() - URLFile(f"{host}/test.txt").read() - assert not os.path.exists(Paths.download_cache_root()) - - def compare_loads(self, url, start=0, length=None): - """Compares range between cached and non cached version""" - file_cached = URLFile(url, cache=True) - file_downloaded = URLFile(url, cache=False) - - file_cached.seek(start) - file_downloaded.seek(start) - - assert file_cached.get_length() == file_downloaded.get_length() - assert length + start if length is not None else 0 <= file_downloaded.get_length() - - response_cached = file_cached.read(ll=length) - response_downloaded = file_downloaded.read(ll=length) - - assert response_cached == response_downloaded - - # Now test with cache in place - file_cached = URLFile(url, cache=True) - file_cached.seek(start) - response_cached = file_cached.read(ll=length) - - assert file_cached.get_length() == file_downloaded.get_length() - assert response_cached == response_downloaded - - def test_small_file(self): - # Make sure we don't force cache - os.environ["FILEREADER_CACHE"] = "0" - small_file_url = "https://raw.githubusercontent.com/commaai/openpilot/master/docs/SAFETY.md" - # If you want large file to be larger than a chunk - # large_file_url = "https://commadataci.blob.core.windows.net/openpilotci/0375fdf7b1ce594d/2019-06-13--08-32-25/3/fcamera.hevc" - - # Load full small file - self.compare_loads(small_file_url) - - file_small = URLFile(small_file_url) - length = file_small.get_length() - - self.compare_loads(small_file_url, length - 100, 100) - self.compare_loads(small_file_url, 50, 100) - - # Load small file 100 bytes at a time - for i in range(length // 100): - self.compare_loads(small_file_url, 100 * i, 100) - - def test_large_file(self): - large_file_url = "https://commadataci.blob.core.windows.net/openpilotci/0375fdf7b1ce594d/2019-06-13--08-32-25/3/qlog.bz2" - # Load the end 100 bytes of both files - file_large = URLFile(large_file_url) - length = file_large.get_length() - - self.compare_loads(large_file_url, length - 100, 100) - self.compare_loads(large_file_url) - - @pytest.mark.parametrize("cache_enabled", [True, False]) - def test_recover_from_missing_file(self, host, cache_enabled): - os.environ["FILEREADER_CACHE"] = "1" if cache_enabled else "0" - - file_url = f"{host}/test.png" - - CachingTestRequestHandler.FILE_EXISTS = False - length = URLFile(file_url).get_length() - assert length == -1 - - CachingTestRequestHandler.FILE_EXISTS = True - length = URLFile(file_url).get_length() - assert length == 4 diff --git a/tools/lib/url_file.py b/tools/lib/url_file.py deleted file mode 100644 index b2a11dc77b..0000000000 --- a/tools/lib/url_file.py +++ /dev/null @@ -1,163 +0,0 @@ -import logging -import os -import socket -import time -from hashlib import sha256 -from urllib3 import PoolManager, Retry -from urllib3.response import BaseHTTPResponse -from urllib3.util import Timeout - -from openpilot.common.file_helpers import atomic_write_in_dir -from openpilot.system.hardware.hw import Paths -# Cache chunk size -K = 1000 -CHUNK_SIZE = 1000 * K - -logging.getLogger("urllib3").setLevel(logging.WARNING) - -def hash_256(link: str) -> str: - return sha256((link.split("?")[0]).encode('utf-8')).hexdigest() - - -class URLFileException(Exception): - pass - - -class URLFile: - _pool_manager: PoolManager|None = None - - @staticmethod - def reset() -> None: - URLFile._pool_manager = None - - @staticmethod - def pool_manager() -> PoolManager: - if URLFile._pool_manager is None: - socket_options = [(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),] - retries = Retry(total=5, backoff_factor=0.5, status_forcelist=[409, 429, 503, 504]) - URLFile._pool_manager = PoolManager(num_pools=10, maxsize=100, socket_options=socket_options, retries=retries) - return URLFile._pool_manager - - def __init__(self, url: str, timeout: int=10, debug: bool=False, cache: bool|None=None): - self._url = url - self._timeout = Timeout(connect=timeout, read=timeout) - self._pos = 0 - self._length: int|None = None - self._debug = debug - # True by default, false if FILEREADER_CACHE is defined, but can be overwritten by the cache input - self._force_download = not int(os.environ.get("FILEREADER_CACHE", "0")) - if cache is not None: - self._force_download = not cache - - if not self._force_download: - os.makedirs(Paths.download_cache_root(), exist_ok=True) - - def __enter__(self): - return self - - def __exit__(self, exc_type, exc_value, traceback) -> None: - pass - - def _request(self, method: str, url: str, headers: dict[str, str]|None=None) -> BaseHTTPResponse: - return URLFile.pool_manager().request(method, url, timeout=self._timeout, headers=headers) - - def get_length_online(self) -> int: - response = self._request('HEAD', self._url) - if not (200 <= response.status <= 299): - return -1 - length = response.headers.get('content-length', 0) - return int(length) - - def get_length(self) -> int: - if self._length is not None: - return self._length - - file_length_path = os.path.join(Paths.download_cache_root(), hash_256(self._url) + "_length") - if not self._force_download and os.path.exists(file_length_path): - with open(file_length_path) as file_length: - content = file_length.read() - self._length = int(content) - return self._length - - self._length = self.get_length_online() - if not self._force_download and self._length != -1: - with atomic_write_in_dir(file_length_path, mode="w", overwrite=True) as file_length: - file_length.write(str(self._length)) - return self._length - - def read(self, ll: int|None=None) -> bytes: - if self._force_download: - return self.read_aux(ll=ll) - - file_begin = self._pos - file_end = self._pos + ll if ll is not None else self.get_length() - assert file_end != -1, f"Remote file is empty or doesn't exist: {self._url}" - # We have to align with chunks we store. Position is the begginiing of the latest chunk that starts before or at our file - position = (file_begin // CHUNK_SIZE) * CHUNK_SIZE - response = b"" - while True: - self._pos = position - chunk_number = self._pos / CHUNK_SIZE - file_name = hash_256(self._url) + "_" + str(chunk_number) - full_path = os.path.join(Paths.download_cache_root(), str(file_name)) - data = None - # If we don't have a file, download it - if not os.path.exists(full_path): - data = self.read_aux(ll=CHUNK_SIZE) - with atomic_write_in_dir(full_path, mode="wb", overwrite=True) as new_cached_file: - new_cached_file.write(data) - else: - with open(full_path, "rb") as cached_file: - data = cached_file.read() - - response += data[max(0, file_begin - position): min(CHUNK_SIZE, file_end - position)] - - position += CHUNK_SIZE - if position >= file_end: - self._pos = file_end - return response - - def read_aux(self, ll: int|None=None) -> bytes: - download_range = False - headers = {} - if self._pos != 0 or ll is not None: - if ll is None: - end = self.get_length() - 1 - else: - end = min(self._pos + ll, self.get_length()) - 1 - if self._pos >= end: - return b"" - headers['Range'] = f"bytes={self._pos}-{end}" - download_range = True - - if self._debug: - t1 = time.time() - - response = self._request('GET', self._url, headers=headers) - ret = response.data - - if self._debug: - t2 = time.time() - if t2 - t1 > 0.1: - print(f"get {self._url} {headers!r} {t2 - t1:.3f} slow") - - response_code = response.status - if response_code == 416: # Requested Range Not Satisfiable - raise URLFileException(f"Error, range out of bounds {response_code} {headers} ({self._url}): {repr(ret)[:500]}") - if download_range and response_code != 206: # Partial Content - raise URLFileException(f"Error, requested range but got unexpected response {response_code} {headers} ({self._url}): {repr(ret)[:500]}") - if (not download_range) and response_code != 200: # OK - raise URLFileException(f"Error {response_code} {headers} ({self._url}): {repr(ret)[:500]}") - - self._pos += len(ret) - return ret - - def seek(self, pos:int) -> None: - self._pos = pos - - @property - def name(self) -> str: - return self._url - - -os.register_at_fork(after_in_child=URLFile.reset) diff --git a/tools/longitudinal_maneuvers/README.md b/tools/longitudinal_maneuvers/README.md deleted file mode 100644 index 643af7fd82..0000000000 --- a/tools/longitudinal_maneuvers/README.md +++ /dev/null @@ -1,48 +0,0 @@ -# Longitudinal Maneuvers Testing Tool - -Test your vehicle's longitudinal control tuning with this tool. The tool will test the vehicle's ability to follow a few longitudinal maneuvers and includes a tool to generate a report from the route. - -
Sample snapshot of a report.
- -## Instructions - -1. Check out a development branch such as `master` on your comma device. -2. Locate either a large empty parking lot or road devoid of any car or foot traffic. Flat, straight road is preferred. The full maneuver suite can take 1 mile or more if left running, however it is recommended to disengage openpilot between maneuvers and turn around if there is not enough space. -3. Turn off the vehicle and set this parameter which will signal to openpilot to start the longitudinal maneuver daemon: - - ```sh - echo -n 1 > /data/params/d/LongitudinalManeuverMode - ``` - -4. Turn your vehicle back on. You will see the "Longitudinal Maneuver Mode" alert: - - ![videoframe_6652](https://github.com/user-attachments/assets/e9d4c95a-cd76-4ab7-933e-19937792fa0f) - -5. Ensure the road ahead is clear, as openpilot will not brake for any obstructions in this mode. Once you are ready, press "Set" on your steering wheel to start the tests. The tests will run for about 4 minutes. If you need to pause the tests, press "Cancel" on your steering wheel. You can resume the tests by pressing "Resume" on your steering wheel. - - **Note:** For GM cars, it is recommended to hold down the resume button for all low-speed tests (starting, stopping and creep) to avoid the car entering standstill. - - ![cog-clip-00 01 11 250-00 01 22 250](https://github.com/user-attachments/assets/c312c1cc-76e8-46e1-a05e-bb9dfb58994f) - -6. When the testing is complete, you'll see an alert that says "Maneuvers Finished." Complete the route by pulling over and turning off the vehicle. - - ![fin2](https://github.com/user-attachments/assets/c06960ae-7cfb-44af-beaa-4dc28848e49d) - -7. Visit https://connect.comma.ai and locate the route(s). They will stand out with lots of orange intervals in their timeline. Ensure "All logs" show as "uploaded." - - ![image](https://github.com/user-attachments/assets/cfe4c6d9-752f-4b24-b421-4b90a01933dc) - -8. Gather the route ID and then run the report generator. The file will be exported to the same directory: - - ```sh - $ python tools/longitudinal_maneuvers/generate_report.py 57048cfce01d9625/0000010e--5b26bc3be7 'pcm accel compensation' - - processing report for LEXUS_ES_TSS2 - plotting maneuver: start from stop, runs: 4 - plotting maneuver: creep: alternate between +1m/s^2 and -1m/s^2, runs: 2 - plotting maneuver: gas step response: +1m/s^2 from 20mph, runs: 2 - - Report written to /home/batman/openpilot/tools/longitudinal_maneuvers/longitudinal_reports/LEXUS_ES_TSS2_57048cfce01d9625_0000010e--5b26bc3be7.html - ``` - -You can reach out on [Discord](https://discord.comma.ai) if you have any questions about these instructions or the tool itself. diff --git a/tools/longitudinal_maneuvers/generate_report.py b/tools/longitudinal_maneuvers/generate_report.py deleted file mode 100755 index 8c16e30d56..0000000000 --- a/tools/longitudinal_maneuvers/generate_report.py +++ /dev/null @@ -1,187 +0,0 @@ -#!/usr/bin/env python3 -import argparse -import base64 -import io -import os -import math -import pprint -import webbrowser -from collections import defaultdict -from pathlib import Path -import matplotlib.pyplot as plt -from tabulate import tabulate - -from openpilot.tools.lib.logreader import LogReader -from openpilot.system.hardware.hw import Paths - - -def format_car_params(CP): - return pprint.pformat({k: v for k, v in CP.to_dict().items() if not k.endswith('DEPRECATED')}, indent=2) - - -def report(platform, route, _description, CP, ID, maneuvers): - output_path = Path(__file__).resolve().parent / "longitudinal_reports" - output_fn = output_path / f"{platform}_{route.replace('/', '_')}.html" - output_path.mkdir(exist_ok=True) - target_cross_times = defaultdict(list) - - builder = [ - "\n", - "

Longitudinal maneuver report

\n", - f"

{platform}

\n", - f"

{route}

\n", - f"

{ID.gitCommit}, {ID.gitBranch}, {ID.gitRemote}

\n", - ] - if _description is not None: - builder.append(f"

Description: {_description}

\n") - builder.append(f"

CarParams

{format_car_params(CP)}
\n") - builder.append('{ summary }') # to be replaced below - for description, runs in maneuvers: - print(f'plotting maneuver: {description}, runs: {len(runs)}') - builder.append("
\n") - builder.append(f"

{description}

\n") - for run, msgs in enumerate(runs): - t_carControl, carControl = zip(*[(m.logMonoTime, m.carControl) for m in msgs if m.which() == 'carControl'], strict=True) - t_carOutput, carOutput = zip(*[(m.logMonoTime, m.carOutput) for m in msgs if m.which() == 'carOutput'], strict=True) - t_carState, carState = zip(*[(m.logMonoTime, m.carState) for m in msgs if m.which() == 'carState'], strict=True) - t_livePose, livePose = zip(*[(m.logMonoTime, m.livePose) for m in msgs if m.which() == 'livePose'], strict=True) - t_longitudinalPlan, longitudinalPlan = zip(*[(m.logMonoTime, m.longitudinalPlan) for m in msgs if m.which() == 'longitudinalPlan'], strict=True) - - # make time relative seconds - t_carControl = [(t - t_carControl[0]) / 1e9 for t in t_carControl] - t_carOutput = [(t - t_carOutput[0]) / 1e9 for t in t_carOutput] - t_carState = [(t - t_carState[0]) / 1e9 for t in t_carState] - t_livePose = [(t - t_livePose[0]) / 1e9 for t in t_livePose] - t_longitudinalPlan = [(t - t_longitudinalPlan[0]) / 1e9 for t in t_longitudinalPlan] - - # maneuver validity - longActive = [m.longActive for m in carControl] - maneuver_valid = all(longActive) and (not any(cs.cruiseState.standstill for cs in carState) or CP.autoResumeSng) - - _open = 'open' if maneuver_valid else '' - title = f'Run #{int(run)+1}' + (' (invalid maneuver!)' if not maneuver_valid else '') - - builder.append(f"

{title}

\n") - - # get first acceleration target and first intersection - aTarget = longitudinalPlan[0].aTarget - target_cross_time = None - builder.append(f'

Initial aTarget: {round(aTarget, 2)} m/s^2') - - # Localizer is noisy, require two consecutive 20Hz frames above threshold - prev_crossed = False - for t, lp in zip(t_livePose, livePose, strict=True): - crossed = (0 < aTarget < lp.accelerationDevice.x) or (0 > aTarget > lp.accelerationDevice.x) - if crossed and prev_crossed: - builder.append(f', crossed in {t:.3f}s') - target_cross_time = t - if maneuver_valid: - target_cross_times[description].append(t) - break - prev_crossed = crossed - else: - builder.append(', not crossed') - builder.append('

') - - pitches = [math.degrees(m.orientationNED[1]) for m in carControl] - builder.append(f'

Average pitch: {sum(pitches) / len(pitches):0.2f} degrees

') - - plt.rcParams['font.size'] = 40 - fig = plt.figure(figsize=(30, 26)) - ax = fig.subplots(4, 1, sharex=True, gridspec_kw={'height_ratios': [5, 3, 1, 1]}) - - ax[0].grid(linewidth=4) - ax[0].plot(t_carControl, [m.actuators.accel for m in carControl], label='carControl.actuators.accel', linewidth=6) - ax[0].plot(t_carOutput, [m.actuatorsOutput.accel for m in carOutput], label='carOutput.actuatorsOutput.accel', linewidth=6) - ax[0].plot(t_longitudinalPlan, [m.aTarget for m in longitudinalPlan], label='longitudinalPlan.aTarget', linewidth=6) - ax[0].plot(t_carState, [m.aEgo for m in carState], label='carState.aEgo', linewidth=6) - ax[0].plot(t_livePose, [m.accelerationDevice.x for m in livePose], label='livePose.accelerationDevice.x', linewidth=6) - # TODO localizer accel - ax[0].set_ylabel('Acceleration (m/s^2)') - #ax[0].set_ylim(-6.5, 6.5) - ax[0].legend(prop={'size': 30}) - - if target_cross_time is not None: - ax[0].plot(target_cross_time, aTarget, marker='o', markersize=50, markeredgewidth=7, markeredgecolor='black', markerfacecolor='None') - - ax[1].grid(linewidth=4) - ax[1].plot(t_carState, [m.vEgo for m in carState], 'g', label='vEgo', linewidth=6) - ax[1].set_ylabel('Velocity (m/s)') - ax[1].legend() - - ax[2].plot(t_carControl, longActive, label='longActive', linewidth=6) - ax[3].plot(t_carState, [m.gasPressed for m in carState], label='gasPressed', linewidth=6) - ax[3].plot(t_carState, [m.brakePressed for m in carState], label='brakePressed', linewidth=6) - for i in (2, 3): - ax[i].set_yticks([0, 1], minor=False) - ax[i].set_ylim(-1, 2) - ax[i].legend() - - ax[-1].set_xlabel("Time (s)") - fig.tight_layout() - - buffer = io.BytesIO() - fig.savefig(buffer, format='webp') - plt.close(fig) - buffer.seek(0) - builder.append(f"\n") - builder.append("
\n") - - summary = ["

Summary

\n"] - cols = ['maneuver', 'crossed', 'runs', 'mean', 'min', 'max'] - table = [] - for description, runs in maneuvers: - times = target_cross_times[description] - l = [description, len(times), len(runs)] - if len(times): - l.extend([round(sum(times) / len(times), 2), round(min(times), 2), round(max(times), 2)]) - table.append(l) - summary.append(tabulate(table, headers=cols, tablefmt='html', numalign='left') + '\n') - - sum_idx = builder.index('{ summary }') - builder[sum_idx:sum_idx + 1] = summary - - with open(output_fn, "w") as f: - f.write(''.join(builder)) - - print(f"\nOpening report: {output_fn}\n") - webbrowser.open_new_tab(str(output_fn)) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser(description='Generate longitudinal maneuver report from route') - parser.add_argument('route', type=str, help='Route name (e.g. 00000000--5f742174be)') - parser.add_argument('description', type=str, nargs='?') - - args = parser.parse_args() - - if '/' in args.route or '|' in args.route: - lr = LogReader(args.route) - else: - segs = [seg for seg in os.listdir(Paths.log_root()) if args.route in seg] - lr = LogReader([os.path.join(Paths.log_root(), seg, 'rlog.zst') for seg in segs]) - - CP = lr.first('carParams') - ID = lr.first('initData') - platform = CP.carFingerprint - print('processing report for', platform) - - maneuvers: list[tuple[str, list[list]]] = [] - active_prev = False - description_prev = None - - for msg in lr: - if msg.which() == 'alertDebug': - active = 'Maneuver Active' in msg.alertDebug.alertText1 - if active and not active_prev: - if msg.alertDebug.alertText2 == description_prev: - maneuvers[-1][1].append([]) - else: - maneuvers.append((msg.alertDebug.alertText2, [[]])) - description_prev = maneuvers[-1][0] - active_prev = active - - if active_prev: - maneuvers[-1][1][-1].append(msg) - - report(platform, args.route, args.description, CP, ID, maneuvers) diff --git a/tools/mac_setup.sh b/tools/mac_setup.sh deleted file mode 100755 index d23052d0f0..0000000000 --- a/tools/mac_setup.sh +++ /dev/null @@ -1,99 +0,0 @@ -#!/usr/bin/env bash -set -e - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )" -ROOT="$(cd $DIR/../ && pwd)" -ARCH=$(uname -m) - -# homebrew update is slow -export HOMEBREW_NO_AUTO_UPDATE=1 - -if [[ $SHELL == "/bin/zsh" ]]; then - RC_FILE="$HOME/.zshrc" -elif [[ $SHELL == "/bin/bash" ]]; then - RC_FILE="$HOME/.bash_profile" -fi - -# Install brew if required -if [[ $(command -v brew) == "" ]]; then - echo "Installing Homebrew" - /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" - echo "[ ] installed brew t=$SECONDS" - - # make brew available now - if [[ $ARCH == "x86_64" ]]; then - echo 'eval "$(/usr/local/bin/brew shellenv)"' >> $RC_FILE - eval "$(/usr/local/bin/brew shellenv)" - else - echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> $RC_FILE - eval "$(/opt/homebrew/bin/brew shellenv)" - fi -else - brew up -fi - -brew bundle --file=- <<-EOS -brew "git-lfs" -brew "zlib" -brew "capnp" -brew "coreutils" -brew "eigen" -brew "ffmpeg" -brew "glfw" -brew "libarchive" -brew "libusb" -brew "libtool" -brew "llvm" -brew "openssl@3.0" -brew "qt@5" -brew "zeromq" -cask "gcc-arm-embedded" -brew "portaudio" -brew "gcc@13" -EOS - -echo "[ ] finished brew install t=$SECONDS" - -BREW_PREFIX=$(brew --prefix) - -# archive backend tools for pip dependencies -export LDFLAGS="$LDFLAGS -L${BREW_PREFIX}/opt/zlib/lib" -export LDFLAGS="$LDFLAGS -L${BREW_PREFIX}/opt/bzip2/lib" -export CPPFLAGS="$CPPFLAGS -I${BREW_PREFIX}/opt/zlib/include" -export CPPFLAGS="$CPPFLAGS -I${BREW_PREFIX}/opt/bzip2/include" - -# pycurl curl/openssl backend dependencies -export LDFLAGS="$LDFLAGS -L${BREW_PREFIX}/opt/openssl@3/lib" -export CPPFLAGS="$CPPFLAGS -I${BREW_PREFIX}/opt/openssl@3/include" -export PYCURL_CURL_CONFIG=/usr/bin/curl-config -export PYCURL_SSL_LIBRARY=openssl - -# install python dependencies -$DIR/install_python_dependencies.sh -echo "[ ] installed python dependencies t=$SECONDS" - -# brew does not link qt5 by default -# check if qt5 can be linked, if not, prompt the user to link it -QT_BIN_LOCATION="$(command -v lupdate || :)" -if [ -n "$QT_BIN_LOCATION" ]; then - # if qt6 is linked, prompt the user to unlink it and link the right version - QT_BIN_VERSION="$(lupdate -version | awk '{print $NF}')" - if [[ ! "$QT_BIN_VERSION" =~ 5\.[0-9]+\.[0-9]+ ]]; then - echo - echo "lupdate/lrelease available at PATH is $QT_BIN_VERSION" - if [[ "$QT_BIN_LOCATION" == "$(brew --prefix)/"* ]]; then - echo "Run the following command to link qt5:" - echo "brew unlink qt@6 && brew link qt@5" - else - echo "Remove conflicting qt entries from PATH and run the following command to link qt5:" - echo "brew link qt@5" - fi - fi -else - brew link qt@5 -fi - -echo -echo "---- OPENPILOT SETUP DONE ----" -echo "Open a new shell or configure your active shell env by running:" -echo "source $RC_FILE" diff --git a/tools/op.sh b/tools/op.sh index 9142d50a18..1ee7b232b0 100755 --- a/tools/op.sh +++ b/tools/op.sh @@ -21,22 +21,34 @@ if [ "$(uname)" == "Darwin" ] && [ $SHELL == "/bin/bash" ]; then fi function op_install() { echo "Installing op system-wide..." - CMD="\nalias op='"$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )/op.sh" \"\$@\"'\n" - grep "alias op=" "$RC_FILE" &> /dev/null || printf "$CMD" >> $RC_FILE + OP_SH="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )/op.sh" + CMD=$(cat </dev/null || printf '\n%s\n' "$CMD" >> "$RC_FILE" echo -e " ↳ [${GREEN}✔${NC}] op installed successfully. Open a new shell to use it." } -function loge() { - if [[ -f "$LOG_FILE" ]]; then - # error type - echo "$1" >> $LOG_FILE - # error log - echo "$2" >> $LOG_FILE - fi +function retry() { + local attempts=$1 + shift + for i in $(seq 1 "$attempts"); do + if "$@"; then + return 0 + fi + if [ "$i" -lt "$attempts" ]; then + echo " Attempt $i/$attempts failed, retrying in 5s..." + sleep 5 + fi + done + return 1 } function op_run_command() { - CMD="$@" + CMD="$*" echo -e "${BOLD}Running command →${NC} $CMD │" for ((i=0; i<$((19 + ${#CMD})); i++)); do @@ -45,7 +57,7 @@ function op_run_command() { echo -e "┘\n" if [[ -z "$DRY" ]]; then - eval "$CMD" + "$@" fi } @@ -62,7 +74,8 @@ function op_get_openpilot_dir() { done # Fallback to hardcoded directories if not found - for dir in "$HOME/openpilot" "/data/openpilot"; do + SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null && pwd)" + for dir in "$(readlink -f "$SCRIPT_DIR/../..")" "$HOME/openpilot" "/data/openpilot"; do if [[ -f "$dir/launch_openpilot.sh" ]]; then OPENPILOT_ROOT="$dir" return 0 @@ -103,7 +116,7 @@ function op_check_git() { fi echo "Checking for git lfs files..." - if [[ $(file -b $OPENPILOT_ROOT/selfdrive/modeld/models/dmonitoring_model.onnx) == "data" ]]; then + if [[ $(file -b $OPENPILOT_ROOT/openpilot/selfdrive/modeld/models/dmonitoring_model.onnx) == "data" ]]; then echo -e " ↳ [${GREEN}✔${NC}] git lfs files found." else echo -e " ↳ [${RED}✗${NC}] git lfs files not found! Run 'git lfs pull'" @@ -132,13 +145,11 @@ function op_check_os() { ;; * ) echo -e " ↳ [${RED}✗${NC}] Incompatible Ubuntu version $VERSION_CODENAME detected!" - loge "ERROR_INCOMPATIBLE_UBUNTU" "$VERSION_CODENAME" return 1 ;; esac else echo -e " ↳ [${RED}✗${NC}] No /etc/os-release on your system. Make sure you're running on Ubuntu, or similar!" - loge "ERROR_UNKNOWN_UBUNTU" return 1 fi @@ -146,34 +157,10 @@ function op_check_os() { echo -e " ↳ [${GREEN}✔${NC}] macOS detected." else echo -e " ↳ [${RED}✗${NC}] OS type $OSTYPE not supported!" - loge "ERROR_UNKNOWN_OS" "$OSTYPE" return 1 fi } -function op_check_python() { - echo "Checking for compatible python version..." - REQUIRED_PYTHON_VERSION=$(grep "requires-python" $OPENPILOT_ROOT/pyproject.toml) - INSTALLED_PYTHON_VERSION=$(python3 --version 2> /dev/null || true) - - if [[ -z $INSTALLED_PYTHON_VERSION ]]; then - echo -e " ↳ [${RED}✗${NC}] python3 not found on your system. You need python version satisfying $(echo $REQUIRED_PYTHON_VERSION | cut -d '=' -f2-) to continue!" - loge "ERROR_PYTHON_NOT_FOUND" - return 1 - else - LB=$(echo $REQUIRED_PYTHON_VERSION | tr -d -c '[0-9,]' | cut -d ',' -f1) - UB=$(echo $REQUIRED_PYTHON_VERSION | tr -d -c '[0-9,]' | cut -d ',' -f2) - VERSION=$(echo $INSTALLED_PYTHON_VERSION | grep -o '[0-9]\+\.[0-9]\+' | tr -d -c '[0-9]') - if [[ $VERSION -ge LB && $VERSION -lt UB ]]; then - echo -e " ↳ [${GREEN}✔${NC}] $INSTALLED_PYTHON_VERSION detected." - else - echo -e " ↳ [${RED}✗${NC}] You need a python version satisfying $(echo $REQUIRED_PYTHON_VERSION | cut -d '=' -f2-) to continue!" - loge "ERROR_PYTHON_VERSION" "$INSTALLED_PYTHON_VERSION" - return 1 - fi - fi -} - function op_check_venv() { echo "Checking for venv..." if [[ -f $OPENPILOT_ROOT/.venv/bin/activate ]]; then @@ -198,8 +185,6 @@ function op_before_cmd() { op_activate_venv - result="${result}\n$(( op_check_python ) 2>&1)" || (echo -e "$result" && return 1) - if [[ -z $VERBOSE ]]; then echo -e "${BOLD}Checking system →${NC} [${GREEN}✔${NC}]" else @@ -214,36 +199,33 @@ function op_setup() { op_check_openpilot_dir op_check_os - echo "Installing dependencies..." - st="$(date +%s)" - if [[ "$OSTYPE" == "linux-gnu"* ]]; then - SETUP_SCRIPT="tools/ubuntu_setup.sh" - elif [[ "$OSTYPE" == "darwin"* ]]; then - SETUP_SCRIPT="tools/mac_setup.sh" - fi - if ! $OPENPILOT_ROOT/$SETUP_SCRIPT; then - echo -e " ↳ [${RED}✗${NC}] Dependencies installation failed!" - loge "ERROR_DEPENDENCIES_INSTALLATION" - return 1 - fi - et="$(date +%s)" - echo -e " ↳ [${GREEN}✔${NC}] Dependencies installed successfully in $((et - st)) seconds." - + # Submodules must be present before uv sync: pyproject path sources + # (pandacan, opendbc, msgq, ...) live in the submodule checkouts. echo "Getting git submodules..." st="$(date +%s)" - if ! git submodule update --filter=blob:none --jobs 4 --init --recursive; then + if ! retry 3 git submodule update --jobs 4 --init --recursive; then echo -e " ↳ [${RED}✗${NC}] Getting git submodules failed!" - loge "ERROR_GIT_SUBMODULES" return 1 fi et="$(date +%s)" echo -e " ↳ [${GREEN}✔${NC}] Submodules installed successfully in $((et - st)) seconds." + echo "Installing dependencies..." + st="$(date +%s)" + SETUP_SCRIPT="tools/setup_dependencies.sh" + if ! $OPENPILOT_ROOT/$SETUP_SCRIPT; then + echo -e " ↳ [${RED}✗${NC}] Dependencies installation failed!" + return 1 + fi + et="$(date +%s)" + echo -e " ↳ [${GREEN}✔${NC}] Dependencies installed successfully in $((et - st)) seconds." + + op_activate_venv + echo "Pulling git lfs files..." st="$(date +%s)" - if ! git lfs pull; then + if ! retry 3 git lfs pull; then echo -e " ↳ [${RED}✗${NC}] Pulling git lfs files failed!" - loge "ERROR_GIT_LFS" return 1 fi et="$(date +%s)" @@ -254,7 +236,7 @@ function op_setup() { function op_auth() { op_before_cmd - op_run_command tools/lib/auth.py "$@" + op_run_command openpilot/tools/lib/auth.py "$@" } function op_activate_venv() { @@ -262,6 +244,11 @@ function op_activate_venv() { set +e source $OPENPILOT_ROOT/.venv/bin/activate &> /dev/null || true set -e + + # persist venv on PATH across GitHub Actions steps + if [ -n "$GITHUB_PATH" ]; then + echo "$OPENPILOT_ROOT/.venv/bin" >> "$GITHUB_PATH" + fi } function op_venv() { @@ -284,7 +271,25 @@ function op_venv() { function op_adb() { op_before_cmd - op_run_command tools/scripts/adb_ssh.sh + op_run_command tools/scripts/adb_ssh.sh "$@" +} + +function op_ssh() { + op_before_cmd + op_run_command tools/scripts/ssh.py "$@" +} + +function op_script() { + op_before_cmd + + case $1 in + som-debug ) op_run_command panda/scripts/som_debug.sh "${@:2}" ;; + * ) + echo -e "Unknown script '$1'. Available scripts:" + echo -e " ${BOLD}som-debug${NC} SOM serial debug console via panda" + return 1 + ;; + esac } function op_check() { @@ -295,7 +300,7 @@ function op_check() { function op_esim() { op_before_cmd - op_run_command system/hardware/esim.py "$@" + op_run_command openpilot/common/esim/esim.py "$@" } function op_build() { @@ -304,47 +309,46 @@ function op_build() { cd "$CDIR" if [[ -f "/AGNOS" ]]; then # needed on AGNOS to not run out of memory - op_run_command system/manager/build.py + op_run_command openpilot/system/manager/build.py else - # scons is fine on PC - op_run_command scons $@ + op_run_command scons -u "$@" fi } function op_juggle() { op_before_cmd - op_run_command tools/plotjuggler/juggle.py $@ + op_run_command openpilot/tools/plotjuggler/juggle.py "$@" } function op_lint() { op_before_cmd - op_run_command scripts/lint/lint.sh $@ + op_run_command scripts/lint/lint.sh "$@" } function op_test() { op_before_cmd - op_run_command pytest $@ + op_run_command pytest "$@" } function op_replay() { op_before_cmd - op_run_command tools/replay/replay $@ + op_run_command openpilot/tools/replay/replay "$@" } function op_cabana() { op_before_cmd - op_run_command tools/cabana/cabana $@ + op_run_command openpilot/tools/cabana/cabana "$@" } function op_sim() { op_before_cmd - op_run_command exec tools/sim/run_bridge.py & - op_run_command exec tools/sim/launch_openpilot.sh + op_run_command exec openpilot/tools/sim/run_bridge.py & + op_run_command exec openpilot/tools/sim/launch_openpilot.sh } function op_clip() { op_before_cmd - op_run_command tools/clip/run.py $@ + op_run_command openpilot/tools/clip/run.py "$@" } function op_switch() { @@ -360,14 +364,20 @@ function op_switch() { fi BRANCH="$1" + git config --replace-all remote.origin.fetch "+refs/heads/*:refs/remotes/origin/*" + git submodule deinit --all --force git fetch "$REMOTE" "$BRANCH" git checkout -f FETCH_HEAD git checkout -B "$BRANCH" --track "$REMOTE"/"$BRANCH" + git submodule deinit --all --force git reset --hard "${REMOTE}/${BRANCH}" git clean -df git submodule update --init --recursive git submodule foreach git reset --hard git submodule foreach git clean -df + + # remove openpilot update flag if present + rm -f .overlay_init } function op_start() { @@ -396,7 +406,7 @@ function op_default() { echo "" echo -e "${BOLD}${UNDERLINE}Commands [System]:${NC}" echo -e " ${BOLD}auth${NC} Authenticate yourself for API use" - echo -e " ${BOLD}check${NC} Check the development environment (git, os, python) to start using openpilot" + echo -e " ${BOLD}check${NC} Check the development environment (git, os) to start using openpilot" echo -e " ${BOLD}esim${NC} Manage eSIM profiles on your comma device" echo -e " ${BOLD}venv${NC} Activate the python virtual environment" echo -e " ${BOLD}setup${NC} Install openpilot dependencies" @@ -412,6 +422,10 @@ function op_default() { echo -e " ${BOLD}cabana${NC} Run Cabana" echo -e " ${BOLD}clip${NC} Run clip (linux only)" echo -e " ${BOLD}adb${NC} Run adb shell" + echo -e " ${BOLD}ssh${NC} comma prime SSH helper" + echo "" + echo -e "${BOLD}${UNDERLINE}Commands [Scripts]:${NC}" + echo -e " ${BOLD}script${NC} Run a script (e.g. op script som-debug)" echo "" echo -e "${BOLD}${UNDERLINE}Commands [Testing]:${NC}" echo -e " ${BOLD}sim${NC} Run openpilot in a simulator" @@ -446,7 +460,6 @@ function _op() { -d | --dir ) shift 1; OPENPILOT_ROOT="$1"; shift 1 ;; --dry ) shift 1; DRY="1" ;; -n | --no-verify ) shift 1; NO_VERIFY="1" ;; - -l | --log ) shift 1; LOG_FILE="$1" ; shift 1 ;; esac # parse Commands @@ -471,8 +484,10 @@ function _op() { restart ) shift 1; op_restart "$@" ;; post-commit ) shift 1; op_install_post_commit "$@" ;; adb ) shift 1; op_adb "$@" ;; + ssh ) shift 1; op_ssh "$@" ;; + script ) shift 1; op_script "$@" ;; * ) op_default "$@" ;; esac } -_op $@ +_op "$@" diff --git a/tools/plotjuggler/.gitignore b/tools/plotjuggler/.gitignore deleted file mode 100644 index 45559d0b09..0000000000 --- a/tools/plotjuggler/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -bin/ -bin -*.rlog diff --git a/tools/plotjuggler/README.md b/tools/plotjuggler/README.md deleted file mode 100644 index 794c292e68..0000000000 --- a/tools/plotjuggler/README.md +++ /dev/null @@ -1,74 +0,0 @@ -# PlotJuggler - -[PlotJuggler](https://github.com/facontidavide/PlotJuggler) is a tool to quickly visualize time series data, and we've written plugins to parse openpilot logs. Check out our plugins: https://github.com/commaai/PlotJuggler. - -## Installation - -Once you've [set up the openpilot environment](../README.md), this command will download PlotJuggler and install our plugins: - -`cd tools/plotjuggler && ./juggle.py --install` - -## Usage - -``` -$ ./juggle.py -h -usage: juggle.py [-h] [--demo] [--can] [--stream] [--layout [LAYOUT]] [--install] [--dbc DBC] - [route_or_segment_name] [segment_count] - -A helper to run PlotJuggler on openpilot routes - -positional arguments: - route_or_segment_name - The route or segment name to plot (cabana share URL accepted) (default: None) - segment_count The number of segments to plot (default: None) - -optional arguments: - -h, --help show this help message and exit - --demo Use the demo route instead of providing one (default: False) - --can Parse CAN data (default: False) - --stream Start PlotJuggler in streaming mode (default: False) - --layout [LAYOUT] Run PlotJuggler with a pre-defined layout (default: None) - --install Install or update PlotJuggler + plugins (default: False) - --dbc DBC Set the DBC name to load for parsing CAN data. If not set, the DBC will be automatically - inferred from the logs. (default: None) - -``` - -Examples using route name: - -`./juggle.py "a2a0ccea32023010/2023-07-27--13-01-19"` - -Examples using segment range: - -`./juggle.py "a2a0ccea32023010/2023-07-27--13-01-19/1"` - -`./juggle.py "a2a0ccea32023010/2023-07-27--13-01-19/1/q" # use qlogs` - -## Streaming - -Explore live data from your car! Follow these steps to stream from your comma device to your laptop: -- Enable wifi tethering on your comma device -- [SSH into your device](https://github.com/commaai/openpilot/wiki/SSH) and run `cd /data/openpilot && ./cereal/messaging/bridge` -- On your laptop, connect to the device's wifi hotspot -- Start PlotJuggler with `ZMQ=1 ./juggle.py --stream`, find the `Cereal Subscriber` plugin in the dropdown under Streaming, and click `Start`. - -If streaming to PlotJuggler from a replay on your PC, simply run: `./juggle.py --stream` and start the cereal subscriber. - -## Demo - -For a quick demo, go through the installation step and run this command: - -`./juggle.py --demo --layout=layouts/tuning.xml` - -## Layouts - -If you create a layout that's useful for others, consider upstreaming it. - -### Tuning - -Use this layout to improve your car's tuning and generate plots for tuning PRs. Also see the [tuning wiki](https://github.com/commaai/openpilot/wiki/Tuning) and tuning PR template. - -`--layout layouts/tuning.xml` - - -![screenshot](https://i.imgur.com/cizHCH3.png) diff --git a/tools/plotjuggler/juggle.py b/tools/plotjuggler/juggle.py deleted file mode 100755 index 34f33d1959..0000000000 --- a/tools/plotjuggler/juggle.py +++ /dev/null @@ -1,141 +0,0 @@ -#!/usr/bin/env python3 -import os -import sys -import platform -import shutil -import subprocess -import tarfile -import tempfile -import requests -import argparse -from functools import partial - -from opendbc.car.fingerprints import MIGRATION -from openpilot.common.basedir import BASEDIR -from openpilot.common.swaglog import cloudlog -from openpilot.tools.cabana.dbc.generate_dbc_json import generate_dbc_dict -from openpilot.tools.lib.logreader import LogReader, ReadMode, save_log -from openpilot.selfdrive.test.process_replay.migration import migrate_all - -juggle_dir = os.path.dirname(os.path.realpath(__file__)) - -os.environ['LD_LIBRARY_PATH'] = os.environ.get('LD_LIBRARY_PATH', '') + f":{juggle_dir}/bin/" - -DEMO_ROUTE = "a2a0ccea32023010|2023-07-27--13-01-19" -RELEASES_URL = "https://github.com/commaai/PlotJuggler/releases/download/latest" -INSTALL_DIR = os.path.join(juggle_dir, "bin") -PLOTJUGGLER_BIN = os.path.join(juggle_dir, "bin/plotjuggler") -MINIMUM_PLOTJUGGLER_VERSION = (3, 5, 2) -MAX_STREAMING_BUFFER_SIZE = 1000 - - -def install(): - m = f"{platform.system()}-{platform.machine()}" - supported = ("Linux-x86_64", "Linux-aarch64", "Darwin-arm64", "Darwin-x86_64") - if m not in supported: - raise Exception(f"Unsupported platform: '{m}'. Supported platforms: {supported}") - - if os.path.exists(INSTALL_DIR): - shutil.rmtree(INSTALL_DIR) - os.mkdir(INSTALL_DIR) - - url = os.path.join(RELEASES_URL, m + ".tar.gz") - with requests.get(url, stream=True, timeout=10) as r, tempfile.NamedTemporaryFile() as tmp: - r.raise_for_status() - with open(tmp.name, 'wb') as tmpf: - for chunk in r.iter_content(chunk_size=1024 * 1024): - tmpf.write(chunk) - - with tarfile.open(tmp.name) as tar: - tar.extractall(path=INSTALL_DIR) - - -def get_plotjuggler_version(): - out = subprocess.check_output([PLOTJUGGLER_BIN, "-v"], encoding="utf-8").strip() - version = out.split(" ")[1] - return tuple(map(int, version.split("."))) - - -def start_juggler(fn=None, dbc=None, layout=None, route_or_segment_name=None, platform=None): - env = os.environ.copy() - env["BASEDIR"] = BASEDIR - env["PATH"] = f"{INSTALL_DIR}:{os.getenv('PATH', '')}" - if dbc: - if os.path.exists(dbc): - dbc = os.path.abspath(dbc) - env["DBC_NAME"] = dbc - - extra_args = "" - if fn is not None: - extra_args += f" -d {os.path.abspath(fn)}" - if layout is not None: - extra_args += f" -l {os.path.abspath(layout)}" - if route_or_segment_name is not None: - extra_args += f" --window_title \"{route_or_segment_name}{f' ({platform})' if platform is not None else ''}\"" - - cmd = f'{PLOTJUGGLER_BIN} --buffer_size {MAX_STREAMING_BUFFER_SIZE} --plugin_folders {INSTALL_DIR}{extra_args}' - subprocess.call(cmd, shell=True, env=env, cwd=juggle_dir) - - -def process(can, lr): - return [d for d in lr if can or d.which() not in ['can', 'sendcan'] and not d.which().startswith('customReserved')] - - -def juggle_route(route_or_segment_name, can, layout, dbc, should_migrate): - lr = LogReader(route_or_segment_name, default_mode=ReadMode.AUTO_INTERACTIVE) - - all_data = lr.run_across_segments(24, partial(process, can)) - if should_migrate: - all_data = migrate_all(all_data) - - # Infer DBC name from logs - platform = None - if dbc is None: - try: - CP = lr.first('carParams') - platform = MIGRATION.get(CP.carFingerprint, CP.carFingerprint) - dbc = generate_dbc_dict()[platform] - except Exception: - cloudlog.exception("Failed to get DBC name from logs!") - - with tempfile.NamedTemporaryFile(suffix='.rlog', dir=juggle_dir) as tmp: - save_log(tmp.name, all_data, compress=False) - del all_data - start_juggler(tmp.name, dbc, layout, route_or_segment_name, platform) - - -if __name__ == "__main__": - parser = argparse.ArgumentParser(description="A helper to run PlotJuggler on openpilot routes", - formatter_class=argparse.ArgumentDefaultsHelpFormatter) - - parser.add_argument("--demo", action="store_true", help="Use the demo route instead of providing one") - parser.add_argument("--can", action="store_true", help="Parse CAN data") - parser.add_argument("--stream", action="store_true", help="Start PlotJuggler in streaming mode") - parser.add_argument("--no-migration", action="store_true", help="Do not perform log migration") - parser.add_argument("--layout", nargs='?', help="Run PlotJuggler with a pre-defined layout") - parser.add_argument("--install", action="store_true", help="Install or update PlotJuggler + plugins") - parser.add_argument("--dbc", help="Set the DBC name to load for parsing CAN data. If not set, the DBC will be automatically inferred from the logs.") - parser.add_argument("route_or_segment_name", nargs='?', help="The route or segment name to plot (cabana share URL accepted)") - - if len(sys.argv) == 1: - parser.print_help() - sys.exit() - args = parser.parse_args() - - if args.install: - install() - sys.exit() - - if not os.path.exists(PLOTJUGGLER_BIN): - print("PlotJuggler is missing. Downloading...") - install() - - if get_plotjuggler_version() < MINIMUM_PLOTJUGGLER_VERSION: - print("PlotJuggler is out of date. Installing update...") - install() - - if args.stream: - start_juggler(layout=args.layout) - else: - route_or_segment_name = DEMO_ROUTE if args.demo else args.route_or_segment_name.strip() - juggle_route(route_or_segment_name, args.can, args.layout, args.dbc, not args.no_migration) diff --git a/tools/plotjuggler/layouts/analyzing-panda-block-angle-hkg.xml b/tools/plotjuggler/layouts/analyzing-panda-block-angle-hkg.xml deleted file mode 100644 index 6f60d52f36..0000000000 --- a/tools/plotjuggler/layouts/analyzing-panda-block-angle-hkg.xml +++ /dev/null @@ -1,131 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tools/plotjuggler/layouts/analyzing-torque-angle-hkg.xml b/tools/plotjuggler/layouts/analyzing-torque-angle-hkg.xml deleted file mode 100644 index 7245ae248d..0000000000 --- a/tools/plotjuggler/layouts/analyzing-torque-angle-hkg.xml +++ /dev/null @@ -1,209 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - return (value * v1 ^ 2) - (v2 * 9.81) - /controlsState/desiredCurvature - - /carState/vEgo - /liveParameters/roll - - - - - return (value * v1 ^ 2) - (v2 * 9.81) - /controlsState/curvature - - /carState/vEgo - /liveParameters/roll - - - - - if (v1 == 0 and v2 == 1) then - return (value * -9.8) - (v3 * 9.81) -end ---return 0 - return (value * -9.8) - (v3 * 9.81) - /can/1/IMU_01_10ms/IMU_LatAccelVal - - /carState/steeringPressed - /carControl/latActive - /liveParameters/roll - - - - - return value * -9.8 - /can/1/IMU_01_10ms/IMU_LatAccelVal - - /carState/steeringPressed - /carControl/latActive - - - - - if (v1 == 0 and v2 == 1) then - return value * -9.8 -end -return 0 - /can/1/IMU_01_10ms/IMU_LatAccelVal - - /carState/steeringPressed - /carControl/latActive - - - - - if (v3 == 0 and v4 == 1) then - return (value * v1 ^ 2) - (v2 * 9.81) -end -return 0 - /controlsState/curvature - - /carState/vEgo - /liveParameters/roll - /carState/steeringPressed - /carControl/latActive - - - - - return value * -9.8 - /can/1/IMU_01_10ms/IMU_LatAccelVal - - /carState/steeringPressed - /carControl/latActive - - - - - - - diff --git a/tools/plotjuggler/layouts/hkg_angle_control.xml b/tools/plotjuggler/layouts/hkg_angle_control.xml deleted file mode 100644 index ac77a0fb16..0000000000 --- a/tools/plotjuggler/layouts/hkg_angle_control.xml +++ /dev/null @@ -1,281 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - min=0 -max=250 -max_from_speed=96 - -rate_lim = 500 - -la_deadzone = 0.38 - -k1=200 -k2=20 -k3=1.0 -k4=1 -k5=10 - -old = 0 - -function sign(number) - return number > 0 and 1 or (number == 0 and 0 or -1) -end - -function apply_rate_limit(old, new, limit) - return math.min(math.max(new, old - limit), old + limit) -end - -function apply_deadzone(val, deadzone) - if math.abs(val) <= deadzone then - return 0.0 - elseif val < 0.0 then - return val + deadzone - else - return val - deadzone - end -end - return 0 - /carState/aEgo - - - min=0 -max=250 -max_from_speed=96 - -k1=200 -k2=30 -k3=1 -k4=1 -k5=10 - -function sign(number) - return number > 0 and 1 or (number == 0 and 0 or -1) -end - return 250 - value * 20 - desired lateral jark - - - firstX = 0 -firstY = 0 -is_first = true -secondX = 0 -secondY = 0 -is_second = false - -- Wait for initial values -if (is_first) then - is_first = false - is_second = true - firstX = time - firstY = value -end - -if (is_second) then - is_second = false - secondX = time - secondY = value -end - --- Central derivative: dy/dx ~= f(x+delta_x)-f(x-delta_x)/(2*delta_x) -dx = time - firstX -dy = value - firstY --- Increment -firstX = secondX -firstY = secondY -secondX = time -secondY = value - -return dy/dx - /can/1/LFA_ALT/LKAS_ANGLE_CMD - - - min=0 -max=250 -max_from_speed=96 - -rate_lim = 500 - -la_deadzone = 0.38 - -k1=200 -k2=20 -k3=1.0 -k4=1 -k5=10 - -old = 0 - -function sign(number) - return number > 0 and 1 or (number == 0 and 0 or -1) -end - -function apply_rate_limit(old, new, limit) - return math.min(math.max(new, old - limit), old + limit) -end - -function apply_deadzone(val, deadzone) - if math.abs(val) <= deadzone then - return 0.0 - elseif val < 0.0 then - return val + deadzone - else - return val - deadzone - end -end - la = apply_deadzone(v2, la_deadzone) -lj = v3 - -if la == 0.0 then - lj = 0.0 -end - -fla = math.min(math.abs(k1 * la)^k3, max) -flj = math.min(math.abs(k2 * lj)^k4, max) - -out = fla - -flv = math.min(max_from_speed, k5 * v4) - -out = out + flv - -out = math.max(math.min(out, max), min) - -if sign(la) == sign(lj) then - out = out - flj -else - out = out + flj -end - - -if v5 == 1.0 then - out = 0.0 -end - -out = math.max(math.min(out, max), min) -out = apply_rate_limit(old, out, rate_lim) -old = out - -return out - /can/1/LFA_ALT/LKAS_ANGLE_CMD - - ang_cmd rate - desired lat accel - desired lateral jark - /carState/vEgo - /can/1/LFA_ALT/LKAS_ANGLE_ACTIVE - - - - firstX = 0 -firstY = 0 -is_first = true -secondX = 0 -secondY = 0 -is_second = false - -- Wait for initial values -if (is_first) then - is_first = false - is_second = true - firstX = time - firstY = value -end - -if (is_second) then - is_second = false - secondX = time - secondY = value -end - --- Central derivative: dy/dx ~= f(x+delta_x)-f(x-delta_x)/(2*delta_x) -dx = time - firstX -dy = value - firstY --- Increment -firstX = secondX -firstY = secondY -secondX = time -secondY = value - -return dy/dx - desired lat accel - - - - return math.abs(value) - desired lat accel - - - - return value * v1^2 - /controlsState/desiredCurvature - - /carState/vEgo - - - - - return math.abs(value) - /can/1/LFA_ALT/LKAS_ANGLE_CMD - - - - - - diff --git a/tools/plotjuggler/layouts/safety-limits-angle-kkg.xml b/tools/plotjuggler/layouts/safety-limits-angle-kkg.xml deleted file mode 100644 index b4033150ef..0000000000 --- a/tools/plotjuggler/layouts/safety-limits-angle-kkg.xml +++ /dev/null @@ -1,175 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - return value * -9.8 - /can/1/IMU_01_10ms/IMU_LatAccelVal - - /carState/steeringPressed - /carControl/latActive - - - - - if (v3 == 0 and v4 == 1) then - return (value * v1 ^ 2) - (v2 * 9.81) -end -return 0 - /controlsState/curvature - - /carState/vEgo - /liveParameters/roll - /carState/steeringPressed - /carControl/latActive - - - - - if (v1 == 0 and v2 == 1) then - return value * -9.8 -end -return 0 - /can/1/IMU_01_10ms/IMU_LatAccelVal - - /carState/steeringPressed - /carControl/latActive - - - - - return value * -9.8 - /can/1/IMU_01_10ms/IMU_LatAccelVal - - /carState/steeringPressed - /carControl/latActive - - - - - - -if (v1 == 0 and v2 == 1) then - return (value * -9.8) - (v3 * 9.81) -end -return 0 - /can/1/IMU_01_10ms/IMU_LatAccelVal - - /carState/steeringPressed - /carControl/latActive - /liveParameters/roll - - - - - return (value * v1 ^ 2) - (v2 * 9.81) - /controlsState/curvature - - /carState/vEgo - /liveParameters/roll - - - - - return (value * v1 ^ 2) - (v2 * 9.81) - /controlsState/desiredCurvature - - /carState/vEgo - /liveParameters/roll - - - - - - - diff --git a/tools/plotjuggler/layouts/torque-controller.xml b/tools/plotjuggler/layouts/torque-controller.xml deleted file mode 100644 index 606df03611..0000000000 --- a/tools/plotjuggler/layouts/torque-controller.xml +++ /dev/null @@ -1,245 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - return (0) - /carState/canValid - - - - return (value * v1 ^ 2) - (v2 * 9.81) - /controlsState/curvature - - /carState/vEgo - /liveParameters/roll - - - - - return (value * v1 ^ 2) - (v2 * 9.81) - /controlsState/desiredCurvature - - /carState/vEgo - /liveParameters/roll - - - - - return value * 2.23694 - /carState/vEgo - - - - return value * 3.6 - /carState/vEgo - - - - - - diff --git a/tools/profiling/snapdragon/README.md b/tools/profiling/snapdragon/README.md deleted file mode 100644 index f56ca182a7..0000000000 --- a/tools/profiling/snapdragon/README.md +++ /dev/null @@ -1,13 +0,0 @@ -snapdragon profiler --------- - - -* download from https://developer.qualcomm.com/software/snapdragon-profiler/tools-archive (need a qc developer account) - * choose v2021.5 (verified working with 24.04 dev environment) -* unzip to selfdrive/debug/profiling/snapdragon/SnapdragonProfiler -* run ```./setup-profiler.sh``` -* run ```./setup-agnos.sh``` -* run ```selfdrive/debug/adb.sh``` on device -* run the ```adb connect xxx``` command that was given to you on local pc -* cd to SnapdragonProfiler and run ```./run_sdp.sh``` -* connect to device -> choose device you just setup diff --git a/tools/release/README.md b/tools/release/README.md new file mode 100644 index 0000000000..862836bf90 --- /dev/null +++ b/tools/release/README.md @@ -0,0 +1,35 @@ +# openpilot releases + +``` +## release checklist + +### Go to staging +- [ ] make a GitHub issue to track release with this checklist +- [ ] create release master branch + - [ ] create a branch from upstream master named `zerotentwo` for release `v0.10.2` + - [ ] revert risky commits (double check with autonomy team) + - [ ] push the new branch +- [ ] push to staging: + - [ ] make sure you are on the newly created release master branch (`zerotentwo`) + - [ ] run `BRANCH=devel-staging tools/release/build_stripped.sh`. Jenkins will then automatically build staging on device, run `test_onroad` and update the staging branch +- [ ] bump version on master: `openpilot/common/version.h` and `RELEASES.md` +- [ ] post on Discord, tag `@release crew` + +### Go to release +- [ ] before going to release, test the following: + - [ ] update from previous release -> new release + - [ ] update from new release -> previous release + - [ ] fresh install with `openpilot-test.comma.ai` + - [ ] drive on fresh install + - [ ] no submodules or LFS + - [ ] check sentry, MTBF, etc. + - [ ] stress test passes in production +- [ ] publish the blog post +- [ ] `git reset --hard origin/release-mici-staging` +- [ ] tag the release: `git tag v0.X.X && git push origin v0.X.X` +- [ ] create GitHub release +- [ ] final test install on `openpilot.comma.ai` +- [ ] update factory provisioning +- [ ] close out milestone and issue +- [ ] post on Discord, X, etc. +``` diff --git a/tools/release/build_release.sh b/tools/release/build_release.sh new file mode 100755 index 0000000000..6a019a80d0 --- /dev/null +++ b/tools/release/build_release.sh @@ -0,0 +1,106 @@ +#!/usr/bin/env bash +set -e +set -x + +# git diff --name-status origin/release3-staging | grep "^A" | less + +DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null && pwd)" + +cd $DIR + +BUILD_DIR=/data/openpilot +SOURCE_DIR="$(git rev-parse --show-toplevel)" + +if [ -z "$RELEASE_BRANCH" ]; then + echo "RELEASE_BRANCH is not set" + exit 1 +fi + +BUILD_BRANCH=release-mici-staging + + +# set git identity +source $DIR/identity.sh + +echo "[-] Setting up repo T=$SECONDS" +rm -rf $BUILD_DIR +mkdir -p $BUILD_DIR +cd $BUILD_DIR +git init +git remote add origin git@github.com:commaai/openpilot.git +git checkout --orphan $BUILD_BRANCH + +# do the files copy +echo "[-] copying files T=$SECONDS" +cd $SOURCE_DIR +cp -pR --parents $(./tools/release/release_files.py) $BUILD_DIR/ + +# in the directory +cd $BUILD_DIR + +rm -f panda/board/obj/panda.bin.signed +rm -f panda/board/obj/panda_h7.bin.signed + +VERSION=$(cat openpilot/sunnypilot/common/version.h | awk -F[\"-] '{print $2}') +echo "[-] committing version $VERSION T=$SECONDS" +git add -f . +git commit -a -m "openpilot v$VERSION release" + +# Build +export PYTHONPATH="$BUILD_DIR" +scons + +if [ -z "$PANDA_DEBUG_BUILD" ]; then + # release panda fw + CERT=/data/pandaextra/certs/release RELEASE=1 scons panda/ +else + # build with ALLOW_DEBUG=1 to enable features like experimental longitudinal + scons panda/ +fi + +# Ensure no submodules in release +if test "$(git submodule--helper list | wc -l)" -gt "0"; then + echo "submodules found:" + git submodule--helper list + exit 1 +fi +git submodule status + +# Cleanup +find . -name '*.a' -delete +find . -name '*.o' -delete +find . -name '*.os' -delete +find . -name '*.pyc' -delete +find . -name 'moc_*' -delete +find . -name '__pycache__' -delete +rm -rf .sconsign.dblite Jenkinsfile tools/release/ +rm -f openpilot/selfdrive/modeld/models/*.onnx* +rm -f openpilot/sunnypilot/modeld*/models/*.onnx* + +find openpilot/third_party/ -name '*x86*' -exec rm -r {} + +find openpilot/third_party/ -name '*Darwin*' -exec rm -r {} + + + +# Restore third_party +git checkout openpilot/third_party/ + +# Mark as prebuilt release +touch prebuilt + +# Add built files to git +git add -f . +git commit --amend -m "openpilot v$VERSION" + +# Run tests +cd $BUILD_DIR +RELEASE=1 pytest -n0 -s openpilot/selfdrive/test/test_onroad.py +#pytest openpilot/selfdrive/car/tests/test_car_interfaces.py + +echo "[-] pushing release T=$SECONDS" +REFS=() +for branch in ${RELEASE_BRANCH//,/ }; do + REFS+=("$BUILD_BRANCH:$branch") +done +git push -f origin "${REFS[@]}" + +echo "[-] done T=$SECONDS" diff --git a/tools/release/build_stripped.sh b/tools/release/build_stripped.sh new file mode 100755 index 0000000000..b5092b15a7 --- /dev/null +++ b/tools/release/build_stripped.sh @@ -0,0 +1,89 @@ +#!/usr/bin/env bash +set -ex + +DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null && pwd)" + +SOURCE_DIR="$(git -C $DIR rev-parse --show-toplevel)" +if [ -z "$TARGET_DIR" ]; then + TARGET_DIR="$(mktemp -d)" +fi + +# set git identity +source $DIR/identity.sh + +echo "[-] Setting up target repo T=$SECONDS" + +rm -rf $TARGET_DIR +mkdir -p $TARGET_DIR +cd $TARGET_DIR +cp -r $SOURCE_DIR/.git $TARGET_DIR + +echo "[-] setting up stripped branch sync T=$SECONDS" +cd $TARGET_DIR + +# tmp branch +git checkout --orphan tmp + +# remove everything except .git +echo "[-] erasing old sunnypilot T=$SECONDS" +git submodule deinit -f --all +git rm -rf --cached . +find . -maxdepth 1 -not -path './.git' -not -name '.' -not -name '..' -exec rm -rf '{}' \; + +# cleanup before the copy +cd $SOURCE_DIR +git clean -xdff +git submodule foreach --recursive git clean -xdff + +# do the files copy +echo "[-] copying files T=$SECONDS" +cd $SOURCE_DIR +./tools/release/release_files.py | xargs -d '\n' cp -pR --parents -t "$TARGET_DIR" + +# in the directory +cd $TARGET_DIR +rm -rf .git/modules/ +rm -f panda/board/obj/panda.bin.signed + +find openpilot/selfdrive/modeld/models -name '*.onnx' -size +95M -exec ./openpilot/common/file_chunker.py {} \; + +# include source commit hash and build date in commit +GIT_HASH=$(git --git-dir=$SOURCE_DIR/.git rev-parse HEAD) +GIT_COMMIT_DATE=$(git --git-dir=$SOURCE_DIR/.git show --no-patch --format='%ct %ci' HEAD) +DATETIME=$(date '+%Y-%m-%dT%H:%M:%S') +VERSION=$(cat $SOURCE_DIR/openpilot/sunnypilot/common/version.h | awk -F\" '{print $2}') + +echo -n "$GIT_HASH" > git_src_commit +echo -n "$GIT_COMMIT_DATE" > git_src_commit_date + +echo "[-] committing version $VERSION T=$SECONDS" +git add -f . +git status +git commit -a -m "sunnypilot v$VERSION release + +date: $DATETIME +master commit: $GIT_HASH +" + +# should be no submodules or LFS files +git submodule status +if [ ! -z "$(git lfs ls-files)" ]; then + echo "LFS files detected!" + exit 1 +fi + +# ensure files are within GitHub's limit +BIG_FILES="$(find . -type f -not -path './.git/*' -size +95M)" +if [ ! -z "$BIG_FILES" ]; then + printf '\n\n\n' + echo "Found files exceeding GitHub's 100MB limit:" + echo "$BIG_FILES" + exit 1 +fi + +if [ ! -z "$BRANCH" ]; then + echo "[-] Pushing to $BRANCH T=$SECONDS" + git push -f origin tmp:$BRANCH +fi + +echo "[-] done T=$SECONDS, ready at $TARGET_DIR" diff --git a/release/check-dirty.sh b/tools/release/check-dirty.sh similarity index 100% rename from release/check-dirty.sh rename to tools/release/check-dirty.sh diff --git a/tools/release/check-submodules.sh b/tools/release/check-submodules.sh new file mode 100755 index 0000000000..7120fa15d8 --- /dev/null +++ b/tools/release/check-submodules.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash + +has_submodule_changes() { + local submodule_path="$1" + if [ -n "$SUBMODULE_PATHS" ]; then + echo "$SUBMODULE_PATHS" | grep -q "$submodule_path" + return $? + fi + return 1 +} + +while read hash submodule ref; do + if [ -z "$hash" ] || [ -z "$submodule" ]; then + continue + fi + + hash=$(echo "$hash" | sed 's/^[+-]//') + + if [ "$submodule" = "tinygrad_repo" ]; then + echo "Skipping $submodule" + continue + fi + + if [ "$CHECK_PR_REFS" = "true" ] && has_submodule_changes "$submodule"; then + echo "Checking $submodule (non-master): verifying hash $hash exists" + git -C $submodule fetch --depth 100 origin + if git -C $submodule cat-file -e $hash 2>/dev/null; then + echo "$submodule ok (hash exists)" + else + echo "$submodule: $hash does not exist in the repository" + exit 1 + fi + else + git -C $submodule fetch --depth 100 origin master + git -C $submodule branch -r --contains $hash | grep "origin/master" + if [ "$?" -eq 0 ]; then + echo "$submodule ok" + else + echo "$submodule: $hash is not on master" + exit 1 + fi + fi +done <<< $(git submodule status --recursive) diff --git a/tools/release/identity.sh b/tools/release/identity.sh new file mode 100644 index 0000000000..1913df3c5b --- /dev/null +++ b/tools/release/identity.sh @@ -0,0 +1,4 @@ +export GIT_COMMITTER_NAME="github-actions[bot]" +export GIT_COMMITTER_EMAIL="github-actions[bot]@users.noreply.github.com" +export GIT_AUTHOR_NAME="github-actions[bot]" +export GIT_AUTHOR_EMAIL="github-actions[bot]@users.noreply.github.com" diff --git a/release/pack.py b/tools/release/pack.py similarity index 82% rename from release/pack.py rename to tools/release/pack.py index 1cb1a47a48..f29ea034db 100755 --- a/release/pack.py +++ b/tools/release/pack.py @@ -11,13 +11,14 @@ from pathlib import Path from openpilot.common.basedir import BASEDIR -DIRS = ['cereal', 'openpilot'] -EXTS = ['.png', '.py', '.ttf', '.capnp'] +DIRS = ['openpilot'] +EXTS = ['.png', '.py', '.ttf', '.capnp', '.json', '.fnt', '.mo', '.po'] +EXCLUDE = ['openpilot/selfdrive/assets/training'] INTERPRETER = '/usr/bin/env python3' def copy(src, dest): - if any(src.endswith(ext) for ext in EXTS): + if any(src.endswith(ext) for ext in EXTS) and not any(exc in src for exc in EXCLUDE): shutil.copy2(src, dest, follow_symlinks=True) @@ -28,6 +29,8 @@ if __name__ == '__main__': parser.add_argument('module', help="the module to target, e.g. 'openpilot.system.ui.spinner'") args = parser.parse_args() + print('WARNING: copying all files! make sure to run scons and git tree is clean') + if not args.output: args.output = args.module diff --git a/release/release_files.py b/tools/release/release_files.py similarity index 90% rename from release/release_files.py rename to tools/release/release_files.py index 98b88293b9..7f08719ea8 100755 --- a/release/release_files.py +++ b/tools/release/release_files.py @@ -4,7 +4,7 @@ import re from pathlib import Path HERE = os.path.abspath(os.path.dirname(__file__)) -ROOT = HERE + "/.." +ROOT = os.path.abspath(os.path.join(HERE, "../..")) blacklist = [ ".git/", @@ -17,6 +17,8 @@ blacklist = [ ".gitattributes", ".git$", ".gitmodules", + ".run/", + ".idea/", ] # gets you through the blacklist diff --git a/tools/replay/.gitignore b/tools/replay/.gitignore deleted file mode 100644 index 83f0e99a8b..0000000000 --- a/tools/replay/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -moc_* -*.moc - -replay -tests/test_replay diff --git a/tools/replay/README.md b/tools/replay/README.md deleted file mode 100644 index 8b4afb0acc..0000000000 --- a/tools/replay/README.md +++ /dev/null @@ -1,150 +0,0 @@ -# Replay - -`replay` allows you to simulate a driving session by replaying all messages logged during the use of openpilot. This provides a way to analyze and visualize system behavior as if it were live. - -## Setup - -Before starting a replay, you need to authenticate with your comma account using `auth.py`. This will allow you to access your routes from the server. - -```bash -# Authenticate to access routes from your comma account: -python3 tools/lib/auth.py -``` - -## Replay a Remote Route -You can replay a route from your comma account by specifying the route name. - -```bash -# Start a replay with a specific route: -tools/replay/replay - -# Example: -tools/replay/replay 'a2a0ccea32023010|2023-07-27--13-01-19' - -# Replay the default demo route: -tools/replay/replay --demo -``` - -## Replay a Local Route -To replay a route stored locally on your machine, specify the route name and provide the path to the directory where the route files are stored. - -```bash -# Replay a local route -tools/replay/replay --data_dir="/path_to/route" - -# Example: -# If you have a local route stored at /path_to_routes with segments like: -# a2a0ccea32023010|2023-07-27--13-01-19--0 -# a2a0ccea32023010|2023-07-27--13-01-19--1 -# You can replay it like this: -tools/replay/replay "a2a0ccea32023010|2023-07-27--13-01-19" --data_dir="/path_to_routes" -``` - -## Send Messages via ZMQ -By default, replay sends messages via MSGQ. To switch to ZMQ, set the ZMQ environment variable. - -```bash -# Start replay and send messages via ZMQ: -ZMQ=1 tools/replay/replay -``` - -## Usage -For more information on available options and arguments, use the help command: - -``` bash -$ tools/replay/replay -h -Usage: tools/replay/replay [options] route -Mock openpilot components by publishing logged messages. - -Options: - -h, --help Displays this help. - -a, --allow whitelist of services to send (comma-separated) - -b, --block blacklist of services to send (comma-separated) - -c, --cache cache segments in memory. default is 5 - -s, --start start from - -x playback . between 0.2 - 3 - --demo use a demo route instead of providing your own - --auto Auto load the route from the best available source (no video): - internal, openpilotci, comma_api, car_segments, testing_closet - --data_dir local directory with routes - --prefix set OPENPILOT_PREFIX - --dcam load driver camera - --ecam load wide road camera - --no-loop stop at the end of the route - --no-cache turn off local cache - --qcam load qcamera - --no-hw-decoder disable HW video decoding - --no-vipc do not output video - --all do output all messages including uiDebug, userFlag. - this may causes issues when used along with UI - -Arguments: - route the drive to replay. find your drives at - connect.comma.ai -``` - -## Visualize the Replay in the openpilot UI -To visualize the replay within the openpilot UI, run the following commands: - -```bash -tools/replay/replay -cd selfdrive/ui && ./ui -``` - -## Try Radar Point Visualization with Rerun -To visualize radar points, run rp_visualization.py while tools/replay/replay is active. - -```bash -tools/replay/replay -python3 replay/rp_visualization.py -``` - -## Work with plotjuggler -If you want to use replay with plotjuggler, you can stream messages by running: - -```bash -tools/replay/replay -tools/plotjuggler/juggle.py --stream -``` - -## watch3 - -watch all three cameras simultaneously from your comma three routes with watch3 - -simply replay a route using the `--dcam` and `--ecam` flags: - -```bash -# start a replay -cd tools/replay && ./replay --demo --dcam --ecam - -# then start watch3 -cd selfdrive/ui && ./watch3 -``` - -![](https://i.imgur.com/IeaOdAb.png) - -## Stream CAN messages to your device - -Replay CAN messages as they were recorded using a [panda jungle](https://comma.ai/shop/products/panda-jungle). The jungle has 6x OBD-C ports for connecting all your comma devices. Check out the [jungle repo](https://github.com/commaai/panda_jungle) for more info. - -In order to run your device as if it was in a car: -* connect a panda jungle to your PC -* connect a comma device or panda to the jungle via OBD-C -* run `can_replay.py` - -``` bash -batman:replay$ ./can_replay.py -h -usage: can_replay.py [-h] [route_or_segment_name] - -Replay CAN messages from a route to all connected pandas and jungles -in a loop. - -positional arguments: - route_or_segment_name - The route or segment name to replay. If not - specified, a default public route will be - used. (default: None) - -optional arguments: - -h, --help show this help message and exit -``` diff --git a/tools/replay/SConscript b/tools/replay/SConscript deleted file mode 100644 index 18849407cf..0000000000 --- a/tools/replay/SConscript +++ /dev/null @@ -1,22 +0,0 @@ -Import('env', 'arch', 'common', 'messaging', 'visionipc', 'cereal') - -replay_env = env.Clone() -replay_env['CCFLAGS'] += ['-Wno-deprecated-declarations'] - -base_frameworks = [] -base_libs = [common, messaging, cereal, visionipc, 'm', 'ssl', 'crypto', 'pthread'] - -if arch == "Darwin": - base_frameworks.append('OpenCL') -else: - base_libs.append('OpenCL') - -replay_lib_src = ["replay.cc", "consoleui.cc", "camera.cc", "filereader.cc", "logreader.cc", "framereader.cc", - "route.cc", "util.cc", "seg_mgr.cc", "timeline.cc", "api.cc"] -replay_lib = replay_env.Library("replay", replay_lib_src, LIBS=base_libs, FRAMEWORKS=base_frameworks) -Export('replay_lib') -replay_libs = [replay_lib, 'avutil', 'avcodec', 'avformat', 'bz2', 'zstd', 'curl', 'yuv', 'ncurses'] + base_libs -replay_env.Program("replay", ["main.cc"], LIBS=replay_libs, FRAMEWORKS=base_frameworks) - -if GetOption('extras'): - replay_env.Program('tests/test_replay', ['tests/test_replay.cc'], LIBS=replay_libs) diff --git a/tools/replay/api.cc b/tools/replay/api.cc deleted file mode 100644 index 85e4e52b28..0000000000 --- a/tools/replay/api.cc +++ /dev/null @@ -1,162 +0,0 @@ - -#include "tools/replay/api.h" - -#include -#include -#include -#include - -#include -#include -#include - -#include "common/params.h" -#include "common/version.h" -#include "system/hardware/hw.h" - -namespace CommaApi2 { - -// Base64 URL-safe character set (uses '-' and '_' instead of '+' and '/') -static const std::string base64url_chars = - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz" - "0123456789-_"; - -std::string base64url_encode(const std::string &in) { - std::string out; - int val = 0, valb = -6; - for (unsigned char c : in) { - val = (val << 8) + c; - valb += 8; - while (valb >= 0) { - out.push_back(base64url_chars[(val >> valb) & 0x3F]); - valb -= 6; - } - } - if (valb > -6) { - out.push_back(base64url_chars[((val << 8) >> (valb + 8)) & 0x3F]); - } - - return out; -} - -EVP_PKEY *get_rsa_private_key() { - static std::unique_ptr rsa_private(nullptr, EVP_PKEY_free); - if (!rsa_private) { - FILE *fp = fopen(Path::rsa_file().c_str(), "rb"); - if (!fp) { - std::cerr << "No RSA private key found, please run manager.py or registration.py" << std::endl; - return nullptr; - } - rsa_private.reset(PEM_read_PrivateKey(fp, NULL, NULL, NULL)); - fclose(fp); - } - return rsa_private.get(); -} - -std::string rsa_sign(const std::string &data) { - EVP_PKEY *private_key = get_rsa_private_key(); - if (!private_key) return {}; - - EVP_MD_CTX *mdctx = EVP_MD_CTX_new(); - assert(mdctx != nullptr); - - std::vector sig(EVP_PKEY_size(private_key)); - uint32_t sig_len; - - EVP_SignInit(mdctx, EVP_sha256()); - EVP_SignUpdate(mdctx, data.data(), data.size()); - int ret = EVP_SignFinal(mdctx, sig.data(), &sig_len, private_key); - - EVP_MD_CTX_free(mdctx); - - assert(ret == 1); - assert(sig.size() == sig_len); - return std::string(sig.begin(), sig.begin() + sig_len); -} - -std::string create_jwt(const json11::Json &extra, int exp_time) { - int now = std::chrono::seconds(std::time(nullptr)).count(); - std::string dongle_id = Params().get("DongleId"); - - // Create header and payload - json11::Json header = json11::Json::object{{"alg", "RS256"}}; - auto payload = json11::Json::object{ - {"identity", dongle_id}, - {"iat", now}, - {"nbf", now}, - {"exp", now + exp_time}, - }; - // Merge extra payload - for (const auto &item : extra.object_items()) { - payload[item.first] = item.second; - } - - // JWT construction - std::string jwt = base64url_encode(header.dump()) + '.' + - base64url_encode(json11::Json(payload).dump()); - - // Hash and sign - std::string hash(SHA256_DIGEST_LENGTH, '\0'); - SHA256((uint8_t *)jwt.data(), jwt.size(), (uint8_t *)hash.data()); - std::string signature = rsa_sign(hash); - - return jwt + "." + base64url_encode(signature); -} - -std::string create_token(bool use_jwt, const json11::Json &payloads, int expiry) { - if (use_jwt) { - return create_jwt(payloads, expiry); - } - - std::string token_json = util::read_file(util::getenv("HOME") + "/.comma/auth.json"); - std::string err; - auto json = json11::Json::parse(token_json, err); - if (!err.empty()) { - std::cerr << "Error parsing auth.json " << err << std::endl; - return ""; - } - return json["access_token"].string_value(); -} - -std::string httpGet(const std::string &url, long *response_code) { - CURL *curl = curl_easy_init(); - assert(curl); - - std::string readBuffer; - const std::string token = CommaApi2::create_token(!Hardware::PC()); - - // Set up the lambda for the write callback - // The '+' makes the lambda non-capturing, allowing it to be used as a C function pointer - auto writeCallback = +[](char *contents, size_t size, size_t nmemb, std::string *userp) ->size_t{ - size_t totalSize = size * nmemb; - userp->append((char *)contents, totalSize); - return totalSize; - }; - - curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); - curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeCallback); - curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer); - curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); - - // Handle headers - struct curl_slist *headers = nullptr; - headers = curl_slist_append(headers, "User-Agent: openpilot-" COMMA_VERSION); - if (!token.empty()) { - headers = curl_slist_append(headers, ("Authorization: JWT " + token).c_str()); - } - curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); - - CURLcode res = curl_easy_perform(curl); - - if (response_code) { - curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, response_code); - } - - curl_slist_free_all(headers); - curl_easy_cleanup(curl); - - return res == CURLE_OK ? readBuffer : std::string{}; -} - -} // namespace CommaApi diff --git a/tools/replay/api.h b/tools/replay/api.h deleted file mode 100644 index dff59c0659..0000000000 --- a/tools/replay/api.h +++ /dev/null @@ -1,15 +0,0 @@ -#pragma once - -#include -#include - -#include "common/util.h" -#include "third_party/json11/json11.hpp" - -namespace CommaApi2 { - -const std::string BASE_URL = util::getenv("API_HOST", "https://api.commadotai.com").c_str(); -std::string create_token(bool use_jwt, const json11::Json& payloads = {}, int expiry = 3600); -std::string httpGet(const std::string &url, long *response_code = nullptr); - -} // namespace CommaApi2 diff --git a/tools/replay/camera.cc b/tools/replay/camera.cc deleted file mode 100644 index 73243ed20d..0000000000 --- a/tools/replay/camera.cc +++ /dev/null @@ -1,125 +0,0 @@ -#include "tools/replay/camera.h" - -#include -#include - -#include - -#include "third_party/linux/include/msm_media_info.h" -#include "tools/replay/util.h" - -const int BUFFER_COUNT = 40; - -std::tuple get_nv12_info(int width, int height) { - int nv12_width = VENUS_Y_STRIDE(COLOR_FMT_NV12, width); - int nv12_height = VENUS_Y_SCANLINES(COLOR_FMT_NV12, height); - assert(nv12_width == VENUS_UV_STRIDE(COLOR_FMT_NV12, width)); - assert(nv12_height / 2 == VENUS_UV_SCANLINES(COLOR_FMT_NV12, height)); - size_t nv12_buffer_size = 2346 * nv12_width; // comes from v4l2_format.fmt.pix_mp.plane_fmt[0].sizeimage - return {nv12_width, nv12_height, nv12_buffer_size}; -} - -CameraServer::CameraServer(std::pair camera_size[MAX_CAMERAS]) { - for (int i = 0; i < MAX_CAMERAS; ++i) { - std::tie(cameras_[i].width, cameras_[i].height) = camera_size[i]; - } - startVipcServer(); -} - -CameraServer::~CameraServer() { - for (auto &cam : cameras_) { - if (cam.thread.joinable()) { - // Clear the queue - std::pair item; - while (cam.queue.try_pop(item)) { - --publishing_; - } - - // Signal termination and join the thread - cam.queue.push({}); - cam.thread.join(); - } - } - vipc_server_.reset(nullptr); -} - -void CameraServer::startVipcServer() { - vipc_server_.reset(new VisionIpcServer("camerad")); - for (auto &cam : cameras_) { - cam.cached_buf.clear(); - - if (cam.width > 0 && cam.height > 0) { - rInfo("camera[%d] frame size %dx%d", cam.type, cam.width, cam.height); - auto [nv12_width, nv12_height, nv12_buffer_size] = get_nv12_info(cam.width, cam.height); - vipc_server_->create_buffers_with_sizes(cam.stream_type, BUFFER_COUNT, cam.width, cam.height, - nv12_buffer_size, nv12_width, nv12_width * nv12_height); - if (!cam.thread.joinable()) { - cam.thread = std::thread(&CameraServer::cameraThread, this, std::ref(cam)); - } - } - } - vipc_server_->start_listener(); -} - -void CameraServer::cameraThread(Camera &cam) { - while (true) { - const auto [fr, event] = cam.queue.pop(); - if (!fr) break; - - capnp::FlatArrayMessageReader reader(event->data); - auto evt = reader.getRoot(); - auto eidx = capnp::AnyStruct::Reader(evt).getPointerSection()[0].getAs(); - - int segment_id = eidx.getSegmentId(); - uint32_t frame_id = eidx.getFrameId(); - if (auto yuv = getFrame(cam, fr, segment_id, frame_id)) { - VisionIpcBufExtra extra = { - .frame_id = frame_id, - .timestamp_sof = eidx.getTimestampSof(), - .timestamp_eof = eidx.getTimestampEof(), - }; - vipc_server_->send(yuv, &extra); - } else { - rError("camera[%d] failed to get frame: %lu", cam.type, segment_id); - } - - // Prefetch the next frame - getFrame(cam, fr, segment_id + 1, frame_id + 1); - - --publishing_; - } -} - -VisionBuf *CameraServer::getFrame(Camera &cam, FrameReader *fr, int32_t segment_id, uint32_t frame_id) { - // Check if the frame is cached - auto buf_it = std::find_if(cam.cached_buf.begin(), cam.cached_buf.end(), - [frame_id](VisionBuf *buf) { return buf->get_frame_id() == frame_id; }); - if (buf_it != cam.cached_buf.end()) return *buf_it; - - VisionBuf *yuv_buf = vipc_server_->get_buffer(cam.stream_type); - if (fr->get(segment_id, yuv_buf)) { - yuv_buf->set_frame_id(frame_id); - cam.cached_buf.insert(yuv_buf); - return yuv_buf; - } - return nullptr; -} - -void CameraServer::pushFrame(CameraType type, FrameReader *fr, const Event *event) { - auto &cam = cameras_[type]; - if (cam.width != fr->width || cam.height != fr->height) { - cam.width = fr->width; - cam.height = fr->height; - waitForSent(); - startVipcServer(); - } - - ++publishing_; - cam.queue.push({fr, event}); -} - -void CameraServer::waitForSent() { - while (publishing_ > 0) { - std::this_thread::yield(); - } -} diff --git a/tools/replay/camera.h b/tools/replay/camera.h deleted file mode 100644 index 21c3d98dcf..0000000000 --- a/tools/replay/camera.h +++ /dev/null @@ -1,43 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -#include "msgq/visionipc/visionipc_server.h" -#include "common/queue.h" -#include "tools/replay/framereader.h" -#include "tools/replay/logreader.h" - -std::tuple get_nv12_info(int width, int height); - -class CameraServer { -public: - CameraServer(std::pair camera_size[MAX_CAMERAS] = nullptr); - ~CameraServer(); - void pushFrame(CameraType type, FrameReader* fr, const Event *event); - void waitForSent(); - -protected: - struct Camera { - CameraType type; - VisionStreamType stream_type; - int width; - int height; - std::thread thread; - SafeQueue> queue; - std::set cached_buf; - }; - void startVipcServer(); - void cameraThread(Camera &cam); - VisionBuf *getFrame(Camera &cam, FrameReader *fr, int32_t segment_id, uint32_t frame_id); - - Camera cameras_[MAX_CAMERAS] = { - {.type = RoadCam, .stream_type = VISION_STREAM_ROAD}, - {.type = DriverCam, .stream_type = VISION_STREAM_DRIVER}, - {.type = WideRoadCam, .stream_type = VISION_STREAM_WIDE_ROAD}, - }; - std::atomic publishing_ = 0; - std::unique_ptr vipc_server_; -}; diff --git a/tools/replay/filereader.cc b/tools/replay/filereader.cc deleted file mode 100644 index d74aaebaba..0000000000 --- a/tools/replay/filereader.cc +++ /dev/null @@ -1,49 +0,0 @@ -#include "tools/replay/filereader.h" - -#include - -#include "common/util.h" -#include "system/hardware/hw.h" -#include "tools/replay/util.h" - -std::string cacheFilePath(const std::string &url) { - static std::string cache_path = [] { - const std::string comma_cache = Path::download_cache_root(); - util::create_directories(comma_cache, 0755); - return comma_cache.back() == '/' ? comma_cache : comma_cache + "/"; - }(); - - return cache_path + sha256(getUrlWithoutQuery(url)); -} - -std::string FileReader::read(const std::string &file, std::atomic *abort) { - const bool is_remote = file.find("https://") == 0; - const std::string local_file = is_remote ? cacheFilePath(file) : file; - std::string result; - - if ((!is_remote || cache_to_local_) && util::file_exists(local_file)) { - result = util::read_file(local_file); - } else if (is_remote) { - result = download(file, abort); - if (cache_to_local_ && !result.empty()) { - std::ofstream fs(local_file, std::ios::binary | std::ios::out); - fs.write(result.data(), result.size()); - } - } - return result; -} - -std::string FileReader::download(const std::string &url, std::atomic *abort) { - for (int i = 0; i <= max_retries_ && !(abort && *abort); ++i) { - if (i > 0) { - rWarning("download failed, retrying %d", i); - util::sleep_for(3000); - } - - std::string result = httpGet(url, chunk_size_, abort); - if (!result.empty()) { - return result; - } - } - return {}; -} diff --git a/tools/replay/filereader.h b/tools/replay/filereader.h deleted file mode 100644 index 34aa91e858..0000000000 --- a/tools/replay/filereader.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once - -#include -#include - -class FileReader { -public: - FileReader(bool cache_to_local, size_t chunk_size = 0, int retries = 3) - : cache_to_local_(cache_to_local), chunk_size_(chunk_size), max_retries_(retries) {} - virtual ~FileReader() {} - std::string read(const std::string &file, std::atomic *abort = nullptr); - -private: - std::string download(const std::string &url, std::atomic *abort); - size_t chunk_size_; - int max_retries_; - bool cache_to_local_; -}; - -std::string cacheFilePath(const std::string &url); diff --git a/tools/replay/framereader.cc b/tools/replay/framereader.cc deleted file mode 100644 index 690645aca9..0000000000 --- a/tools/replay/framereader.cc +++ /dev/null @@ -1,241 +0,0 @@ -#include "tools/replay/framereader.h" - -#include -#include -#include -#include - -#include "common/util.h" -#include "third_party/libyuv/include/libyuv.h" -#include "tools/replay/util.h" - -#ifdef __APPLE__ -#define HW_DEVICE_TYPE AV_HWDEVICE_TYPE_VIDEOTOOLBOX -#define HW_PIX_FMT AV_PIX_FMT_VIDEOTOOLBOX -#else -#define HW_DEVICE_TYPE AV_HWDEVICE_TYPE_CUDA -#define HW_PIX_FMT AV_PIX_FMT_CUDA -#endif - -namespace { - -enum AVPixelFormat get_hw_format(AVCodecContext *ctx, const enum AVPixelFormat *pix_fmts) { - enum AVPixelFormat *hw_pix_fmt = reinterpret_cast(ctx->opaque); - for (const enum AVPixelFormat *p = pix_fmts; *p != -1; p++) { - if (*p == *hw_pix_fmt) return *p; - } - rWarning("Please run replay with the --no-hw-decoder flag!"); - *hw_pix_fmt = AV_PIX_FMT_NONE; - return AV_PIX_FMT_YUV420P; -} - -struct DecoderManager { - VideoDecoder *acquire(CameraType type, AVCodecParameters *codecpar, bool hw_decoder) { - auto key = std::tuple(type, codecpar->width, codecpar->height); - std::unique_lock lock(mutex_); - if (auto it = decoders_.find(key); it != decoders_.end()) { - return it->second.get(); - } - - auto decoder = std::make_unique(); - if (!decoder->open(codecpar, hw_decoder)) { - decoder.reset(nullptr); - } - decoders_[key] = std::move(decoder); - return decoders_[key].get(); - } - - std::mutex mutex_; - std::map, std::unique_ptr> decoders_; -}; - -DecoderManager decoder_manager; - -} // namespace - -FrameReader::FrameReader() { - av_log_set_level(AV_LOG_QUIET); -} - -FrameReader::~FrameReader() { - if (input_ctx) avformat_close_input(&input_ctx); -} - -bool FrameReader::load(CameraType type, const std::string &url, bool no_hw_decoder, std::atomic *abort, bool local_cache, int chunk_size, int retries) { - auto local_file_path = url.find("https://") == 0 ? cacheFilePath(url) : url; - if (!util::file_exists(local_file_path)) { - FileReader f(local_cache, chunk_size, retries); - if (f.read(url, abort).empty()) { - return false; - } - } - return loadFromFile(type, local_file_path, no_hw_decoder, abort); -} - -bool FrameReader::loadFromFile(CameraType type, const std::string &file, bool no_hw_decoder, std::atomic *abort) { - if (avformat_open_input(&input_ctx, file.c_str(), nullptr, nullptr) != 0 || - avformat_find_stream_info(input_ctx, nullptr) < 0) { - rError("Failed to open input file or find video stream"); - return false; - } - input_ctx->probesize = 10 * 1024 * 1024; // 10MB - - decoder_ = decoder_manager.acquire(type, input_ctx->streams[0]->codecpar, !no_hw_decoder); - if (!decoder_) { - return false; - } - width = decoder_->width; - height = decoder_->height; - - AVPacket pkt; - packets_info.reserve(60 * 20); // 20fps, one minute - while (!(abort && *abort) && av_read_frame(input_ctx, &pkt) == 0) { - packets_info.emplace_back(PacketInfo{.flags = pkt.flags, .pos = pkt.pos}); - av_packet_unref(&pkt); - } - avio_seek(input_ctx->pb, 0, SEEK_SET); - return !packets_info.empty(); -} - -bool FrameReader::get(int idx, VisionBuf *buf) { - if (!buf || idx < 0 || idx >= packets_info.size()) { - return false; - } - return decoder_->decode(this, idx, buf); -} - -// class VideoDecoder - -VideoDecoder::VideoDecoder() { - av_frame_ = av_frame_alloc(); - hw_frame_ = av_frame_alloc(); -} - -VideoDecoder::~VideoDecoder() { - if (hw_device_ctx) av_buffer_unref(&hw_device_ctx); - if (decoder_ctx) avcodec_free_context(&decoder_ctx); - av_frame_free(&av_frame_); - av_frame_free(&hw_frame_); -} - -bool VideoDecoder::open(AVCodecParameters *codecpar, bool hw_decoder) { - const AVCodec *decoder = avcodec_find_decoder(codecpar->codec_id); - if (!decoder) return false; - - decoder_ctx = avcodec_alloc_context3(decoder); - if (!decoder_ctx || avcodec_parameters_to_context(decoder_ctx, codecpar) != 0) { - rError("Failed to allocate or initialize codec context"); - return false; - } - width = (decoder_ctx->width + 3) & ~3; - height = decoder_ctx->height; - - if (hw_decoder && !initHardwareDecoder(HW_DEVICE_TYPE)) { - rWarning("No device with hardware decoder found. fallback to CPU decoding."); - } - - if (avcodec_open2(decoder_ctx, decoder, nullptr) < 0) { - rError("Failed to open codec"); - return false; - } - return true; -} - -bool VideoDecoder::initHardwareDecoder(AVHWDeviceType hw_device_type) { - const AVCodecHWConfig *config = nullptr; - for (int i = 0; (config = avcodec_get_hw_config(decoder_ctx->codec, i)) != nullptr; i++) { - if (config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX && config->device_type == hw_device_type) { - hw_pix_fmt = config->pix_fmt; - break; - } - } - if (!config) { - rWarning("Hardware configuration not found"); - return false; - } - - int ret = av_hwdevice_ctx_create(&hw_device_ctx, hw_device_type, nullptr, nullptr, 0); - if (ret < 0) { - hw_pix_fmt = AV_PIX_FMT_NONE; - rWarning("Failed to create specified HW device %d.", ret); - return false; - } - - decoder_ctx->hw_device_ctx = av_buffer_ref(hw_device_ctx); - decoder_ctx->opaque = &hw_pix_fmt; - decoder_ctx->get_format = get_hw_format; - return true; -} - -bool VideoDecoder::decode(FrameReader *reader, int idx, VisionBuf *buf) { - int from_idx = idx; - if (idx != reader->prev_idx + 1) { - // seeking to the nearest key frame - for (int i = idx; i >= 0; --i) { - if (reader->packets_info[i].flags & AV_PKT_FLAG_KEY) { - from_idx = i; - break; - } - } - - auto pos = reader->packets_info[from_idx].pos; - int ret = avformat_seek_file(reader->input_ctx, 0, pos, pos, pos, AVSEEK_FLAG_BYTE); - if (ret < 0) { - rError("Failed to seek to byte position %lld: %d", pos, AVERROR(ret)); - return false; - } - avcodec_flush_buffers(decoder_ctx); - } - reader->prev_idx = idx; - - bool result = false; - AVPacket pkt; - for (int i = from_idx; i <= idx; ++i) { - if (av_read_frame(reader->input_ctx, &pkt) == 0) { - AVFrame *f = decodeFrame(&pkt); - if (f && i == idx) { - result = copyBuffer(f, buf); - } - av_packet_unref(&pkt); - } - } - return result; -} - -AVFrame *VideoDecoder::decodeFrame(AVPacket *pkt) { - int ret = avcodec_send_packet(decoder_ctx, pkt); - if (ret < 0) { - rError("Error sending a packet for decoding: %d", ret); - return nullptr; - } - - ret = avcodec_receive_frame(decoder_ctx, av_frame_); - if (ret != 0) { - rError("avcodec_receive_frame error: %d", ret); - return nullptr; - } - - if (av_frame_->format == hw_pix_fmt && av_hwframe_transfer_data(hw_frame_, av_frame_, 0) < 0) { - rError("error transferring frame data from GPU to CPU"); - return nullptr; - } - return (av_frame_->format == hw_pix_fmt) ? hw_frame_ : av_frame_; -} - -bool VideoDecoder::copyBuffer(AVFrame *f, VisionBuf *buf) { - if (hw_pix_fmt == HW_PIX_FMT) { - for (int i = 0; i < height/2; i++) { - memcpy(buf->y + (i*2 + 0)*buf->stride, f->data[0] + (i*2 + 0)*f->linesize[0], width); - memcpy(buf->y + (i*2 + 1)*buf->stride, f->data[0] + (i*2 + 1)*f->linesize[0], width); - memcpy(buf->uv + i*buf->stride, f->data[1] + i*f->linesize[1], width); - } - } else { - libyuv::I420ToNV12(f->data[0], f->linesize[0], - f->data[1], f->linesize[1], - f->data[2], f->linesize[2], - buf->y, buf->stride, - buf->uv, buf->stride, - width, height); - } - return true; -} diff --git a/tools/replay/framereader.h b/tools/replay/framereader.h deleted file mode 100644 index 03ea5be8b2..0000000000 --- a/tools/replay/framereader.h +++ /dev/null @@ -1,57 +0,0 @@ -#pragma once - -#include -#include - -#include "msgq/visionipc/visionbuf.h" -#include "tools/replay/filereader.h" -#include "tools/replay/util.h" - -extern "C" { -#include -#include -} - -class VideoDecoder; - -class FrameReader { -public: - FrameReader(); - ~FrameReader(); - bool load(CameraType type, const std::string &url, bool no_hw_decoder = false, std::atomic *abort = nullptr, bool local_cache = false, - int chunk_size = -1, int retries = 0); - bool loadFromFile(CameraType type, const std::string &file, bool no_hw_decoder = false, std::atomic *abort = nullptr); - bool get(int idx, VisionBuf *buf); - size_t getFrameCount() const { return packets_info.size(); } - - int width = 0, height = 0; - - VideoDecoder *decoder_ = nullptr; - AVFormatContext *input_ctx = nullptr; - int prev_idx = -1; - struct PacketInfo { - int flags; - int64_t pos; - }; - std::vector packets_info; -}; - - -class VideoDecoder { -public: - VideoDecoder(); - ~VideoDecoder(); - bool open(AVCodecParameters *codecpar, bool hw_decoder); - bool decode(FrameReader *reader, int idx, VisionBuf *buf); - int width = 0, height = 0; - -private: - bool initHardwareDecoder(AVHWDeviceType hw_device_type); - AVFrame *decodeFrame(AVPacket *pkt); - bool copyBuffer(AVFrame *f, VisionBuf *buf); - - AVFrame *av_frame_, *hw_frame_; - AVCodecContext *decoder_ctx = nullptr; - AVPixelFormat hw_pix_fmt = AV_PIX_FMT_NONE; - AVBufferRef *hw_device_ctx = nullptr; -}; diff --git a/tools/replay/lib/rp_helpers.py b/tools/replay/lib/rp_helpers.py deleted file mode 100644 index aa20ab8e32..0000000000 --- a/tools/replay/lib/rp_helpers.py +++ /dev/null @@ -1,109 +0,0 @@ -import numpy as np -from openpilot.selfdrive.controls.radard import RADAR_TO_CAMERA - -# Color palette used for rerun AnnotationContext -rerunColorPalette = [(96, "red", (255, 0, 0)), - (100, "pink", (255, 36, 0)), - (124, "yellow", (255, 255, 0)), - (230, "vibrantpink", (255, 36, 170)), - (240, "orange", (255, 146, 0)), - (255, "white", (255, 255, 255)), - (110, "carColor", (255,0,127)), - (0, "background", (0, 0, 0))] - - -class UIParams: - lidar_x, lidar_y, lidar_zoom = 384, 960, 6 - lidar_car_x, lidar_car_y = lidar_x / 2., lidar_y / 1.1 - car_hwidth = 1.7272 / 2 * lidar_zoom - car_front = 2.6924 * lidar_zoom - car_back = 1.8796 * lidar_zoom - car_color = rerunColorPalette[6][0] -UP = UIParams - - -def to_topdown_pt(y, x): - px, py = x * UP.lidar_zoom + UP.lidar_car_x, -y * UP.lidar_zoom + UP.lidar_car_y - if px > 0 and py > 0 and px < UP.lidar_x and py < UP.lidar_y: - return int(px), int(py) - return -1, -1 - - -def draw_path(path, lid_overlay, lid_color=None): - x, y = np.asarray(path.x), np.asarray(path.y) - # draw lidar path point on lidar - if lid_color is not None and lid_overlay is not None: - for i in range(len(x)): - px, py = to_topdown_pt(x[i], y[i]) - if px != -1: - lid_overlay[px, py] = lid_color - - -def plot_model(m, lid_overlay): - if lid_overlay is None: - return - for lead in m.leadsV3: - if lead.prob < 0.5: - continue - x, y = lead.x[0], lead.y[0] - x_std = lead.xStd[0] - x -= RADAR_TO_CAMERA - _, py_top = to_topdown_pt(x + x_std, y) - px, py_bottom = to_topdown_pt(x - x_std, y) - lid_overlay[int(round(px - 4)):int(round(px + 4)), py_top:py_bottom] = rerunColorPalette[2][0] - - for path in m.laneLines: - draw_path(path, lid_overlay, rerunColorPalette[2][0]) - for edge in m.roadEdges: - draw_path(edge, lid_overlay, rerunColorPalette[0][0]) - draw_path(m.position, lid_overlay, rerunColorPalette[0][0]) - - -def plot_lead(rs, lid_overlay): - for lead in [rs.leadOne, rs.leadTwo]: - if not lead.status: - continue - x = lead.dRel - px_left, py = to_topdown_pt(x, -10) - px_right, _ = to_topdown_pt(x, 10) - lid_overlay[px_left:px_right, py] = rerunColorPalette[0][0] - - -def update_radar_points(lt, lid_overlay): - ar_pts = [] - if lt is not None: - ar_pts = {} - for track in lt: - ar_pts[track.trackId] = [track.dRel, track.yRel, track.vRel, track.aRel, track.oncoming, track.stationary] - for ids, pt in ar_pts.items(): - # negative here since radar is left positive - px, py = to_topdown_pt(pt[0], -pt[1]) - if px != -1: - if pt[-1]: - color = rerunColorPalette[4][0] - elif pt[-2]: - color = rerunColorPalette[3][0] - else: - color = rerunColorPalette[5][0] - if int(ids) == 1: - lid_overlay[px - 2:px + 2, py - 10:py + 10] = rerunColorPalette[1][0] - else: - lid_overlay[px - 2:px + 2, py - 2:py + 2] = color - - -def get_blank_lid_overlay(UP): - lid_overlay = np.zeros((UP.lidar_x, UP.lidar_y), 'uint8') - # Draw the car. - lid_overlay[int(round(UP.lidar_car_x - UP.car_hwidth)):int( - round(UP.lidar_car_x + UP.car_hwidth)), int(round(UP.lidar_car_y - - UP.car_front))] = UP.car_color - lid_overlay[int(round(UP.lidar_car_x - UP.car_hwidth)):int( - round(UP.lidar_car_x + UP.car_hwidth)), int(round(UP.lidar_car_y + - UP.car_back))] = UP.car_color - lid_overlay[int(round(UP.lidar_car_x - UP.car_hwidth)), int( - round(UP.lidar_car_y - UP.car_front)):int(round( - UP.lidar_car_y + UP.car_back))] = UP.car_color - lid_overlay[int(round(UP.lidar_car_x + UP.car_hwidth)), int( - round(UP.lidar_car_y - UP.car_front)):int(round( - UP.lidar_car_y + UP.car_back))] = UP.car_color - return lid_overlay diff --git a/tools/replay/lib/ui_helpers.py b/tools/replay/lib/ui_helpers.py deleted file mode 100644 index 39431eca10..0000000000 --- a/tools/replay/lib/ui_helpers.py +++ /dev/null @@ -1,226 +0,0 @@ -import itertools -from typing import Any - -import matplotlib.pyplot as plt -import numpy as np -import pygame - -from matplotlib.backends.backend_agg import FigureCanvasAgg - -from openpilot.common.transformations.camera import get_view_frame_from_calib_frame -from openpilot.selfdrive.controls.radard import RADAR_TO_CAMERA - - -RED = (255, 0, 0) -GREEN = (0, 255, 0) -BLUE = (0, 0, 255) -YELLOW = (255, 255, 0) -BLACK = (0, 0, 0) -WHITE = (255, 255, 255) - -class UIParams: - lidar_x, lidar_y, lidar_zoom = 384, 960, 6 - lidar_car_x, lidar_car_y = lidar_x / 2., lidar_y / 1.1 - car_hwidth = 1.7272 / 2 * lidar_zoom - car_front = 2.6924 * lidar_zoom - car_back = 1.8796 * lidar_zoom - car_color = 110 -UP = UIParams - -METER_WIDTH = 20 - -class Calibration: - def __init__(self, num_px, rpy, intrinsic, calib_scale): - self.intrinsic = intrinsic - self.extrinsics_matrix = get_view_frame_from_calib_frame(rpy[0], rpy[1], rpy[2], 0.0)[:,:3] - self.zoom = calib_scale - - def car_space_to_ff(self, x, y, z): - car_space_projective = np.column_stack((x, y, z)).T - - ep = self.extrinsics_matrix.dot(car_space_projective) - kep = self.intrinsic.dot(ep) - return (kep[:-1, :] / kep[-1, :]).T - - def car_space_to_bb(self, x, y, z): - pts = self.car_space_to_ff(x, y, z) - return pts / self.zoom - - -_COLOR_CACHE : dict[tuple[int, int, int], Any] = {} -def find_color(lidar_surface, color): - if color in _COLOR_CACHE: - return _COLOR_CACHE[color] - tcolor = 0 - ret = 255 - for x in lidar_surface.get_palette(): - if x[0:3] == color: - ret = tcolor - break - tcolor += 1 - _COLOR_CACHE[color] = ret - return ret - - -def to_topdown_pt(y, x): - px, py = x * UP.lidar_zoom + UP.lidar_car_x, -y * UP.lidar_zoom + UP.lidar_car_y - if px > 0 and py > 0 and px < UP.lidar_x and py < UP.lidar_y: - return int(px), int(py) - return -1, -1 - - -def draw_path(path, color, img, calibration, top_down, lid_color=None, z_off=0): - x, y, z = np.asarray(path.x), np.asarray(path.y), np.asarray(path.z) + z_off - pts = calibration.car_space_to_bb(x, y, z) - pts = np.round(pts).astype(int) - - # draw lidar path point on lidar - # find color in 8 bit - if lid_color is not None and top_down is not None: - tcolor = find_color(top_down[0], lid_color) - for i in range(len(x)): - px, py = to_topdown_pt(x[i], y[i]) - if px != -1: - top_down[1][px, py] = tcolor - - height, width = img.shape[:2] - for x, y in pts: - if 1 < x < width - 1 and 1 < y < height - 1: - for a, b in itertools.permutations([-1, 0, -1], 2): - img[y + a, x + b] = color - - -def init_plots(arr, name_to_arr_idx, plot_xlims, plot_ylims, plot_names, plot_colors, plot_styles): - color_palette = { "r": (1, 0, 0), - "g": (0, 1, 0), - "b": (0, 0, 1), - "k": (0, 0, 0), - "y": (1, 1, 0), - "p": (0, 1, 1), - "m": (1, 0, 1)} - - dpi = 90 - fig = plt.figure(figsize=(575 / dpi, 600 / dpi), dpi=dpi) - canvas = FigureCanvasAgg(fig) - - fig.set_facecolor((0.2, 0.2, 0.2)) - - axs = [] - for pn in range(len(plot_ylims)): - ax = fig.add_subplot(len(plot_ylims), 1, len(axs)+1) - ax.set_xlim(plot_xlims[pn][0], plot_xlims[pn][1]) - ax.set_ylim(plot_ylims[pn][0], plot_ylims[pn][1]) - ax.patch.set_facecolor((0.4, 0.4, 0.4)) - axs.append(ax) - - plots, idxs, plot_select = [], [], [] - for i, pl_list in enumerate(plot_names): - for j, item in enumerate(pl_list): - plot, = axs[i].plot(arr[:, name_to_arr_idx[item]], - label=item, - color=color_palette[plot_colors[i][j]], - linestyle=plot_styles[i][j]) - plots.append(plot) - idxs.append(name_to_arr_idx[item]) - plot_select.append(i) - axs[i].set_title(", ".join(f"{nm} ({cl})" - for (nm, cl) in zip(pl_list, plot_colors[i], strict=False)), fontsize=10) - axs[i].tick_params(axis="x", colors="white") - axs[i].tick_params(axis="y", colors="white") - axs[i].title.set_color("white") - - if i < len(plot_ylims) - 1: - axs[i].set_xticks([]) - - canvas.draw() - - def draw_plots(arr): - for ax in axs: - ax.draw_artist(ax.patch) - for i in range(len(plots)): - plots[i].set_ydata(arr[:, idxs[i]]) - axs[plot_select[i]].draw_artist(plots[i]) - - raw_data = canvas.buffer_rgba() - plot_surface = pygame.image.frombuffer(raw_data, canvas.get_width_height(), "RGBA").convert() - return plot_surface - - return draw_plots - - -def pygame_modules_have_loaded(): - return pygame.display.get_init() and pygame.font.get_init() - - -def plot_model(m, img, calibration, top_down): - if calibration is None or top_down is None: - return - - for lead in m.leadsV3: - if lead.prob < 0.5: - continue - - x, y = lead.x[0], lead.y[0] - x_std = lead.xStd[0] - x -= RADAR_TO_CAMERA - - _, py_top = to_topdown_pt(x + x_std, y) - px, py_bottom = to_topdown_pt(x - x_std, y) - top_down[1][int(round(px - 4)):int(round(px + 4)), py_top:py_bottom] = find_color(top_down[0], YELLOW) - - for path, prob, _ in zip(m.laneLines, m.laneLineProbs, m.laneLineStds, strict=True): - color = (0, int(255 * prob), 0) - draw_path(path, color, img, calibration, top_down, YELLOW) - - for edge, std in zip(m.roadEdges, m.roadEdgeStds, strict=True): - prob = max(1 - std, 0) - color = (int(255 * prob), 0, 0) - draw_path(edge, color, img, calibration, top_down, RED) - - color = (255, 0, 0) - draw_path(m.position, color, img, calibration, top_down, RED, 1.22) - - -def plot_lead(rs, top_down): - for lead in [rs.leadOne, rs.leadTwo]: - if not lead.status: - continue - - x = lead.dRel - px_left, py = to_topdown_pt(x, -10) - px_right, _ = to_topdown_pt(x, 10) - top_down[1][px_left:px_right, py] = find_color(top_down[0], RED) - - -def maybe_update_radar_points(lt, lid_overlay): - ar_pts = [] - if lt is not None: - ar_pts = {} - for track in lt: - ar_pts[track.trackId] = [track.dRel, track.yRel, track.vRel, track.aRel] - for ids, pt in ar_pts.items(): - # negative here since radar is left positive - px, py = to_topdown_pt(pt[0], -pt[1]) - if px != -1: - color = 255 - if int(ids) == 1: - lid_overlay[px - 2:px + 2, py - 10:py + 10] = 100 - else: - lid_overlay[px - 2:px + 2, py - 2:py + 2] = color - -def get_blank_lid_overlay(UP): - lid_overlay = np.zeros((UP.lidar_x, UP.lidar_y), 'uint8') - # Draw the car. - lid_overlay[int(round(UP.lidar_car_x - UP.car_hwidth)):int( - round(UP.lidar_car_x + UP.car_hwidth)), int(round(UP.lidar_car_y - - UP.car_front))] = UP.car_color - lid_overlay[int(round(UP.lidar_car_x - UP.car_hwidth)):int( - round(UP.lidar_car_x + UP.car_hwidth)), int(round(UP.lidar_car_y + - UP.car_back))] = UP.car_color - lid_overlay[int(round(UP.lidar_car_x - UP.car_hwidth)), int( - round(UP.lidar_car_y - UP.car_front)):int(round( - UP.lidar_car_y + UP.car_back))] = UP.car_color - lid_overlay[int(round(UP.lidar_car_x + UP.car_hwidth)), int( - round(UP.lidar_car_y - UP.car_front)):int(round( - UP.lidar_car_y + UP.car_back))] = UP.car_color - return lid_overlay diff --git a/tools/replay/logreader.cc b/tools/replay/logreader.cc deleted file mode 100644 index 75abb8417b..0000000000 --- a/tools/replay/logreader.cc +++ /dev/null @@ -1,116 +0,0 @@ -#include "tools/replay/logreader.h" - -#include -#include -#include "tools/replay/filereader.h" -#include "tools/replay/util.h" -#include "common/util.h" - -bool LogReader::load(const std::string &url, std::atomic *abort, bool local_cache, int chunk_size, int retries) { - std::string data = FileReader(local_cache, chunk_size, retries).read(url, abort); - if (!data.empty()) { - if (url.find(".bz2") != std::string::npos || util::starts_with(data, "BZh9")) { - data = decompressBZ2(data, abort); - } else if (url.find(".zst") != std::string::npos || util::starts_with(data, "\x28\xB5\x2F\xFD")) { - data = decompressZST(data, abort); - } - } - - bool success = !data.empty() && load(data.data(), data.size(), abort); - if (filters_.empty()) - raw_ = std::move(data); - return success; -} - -bool LogReader::load(const char *data, size_t size, std::atomic *abort) { - try { - events.reserve(65000); - kj::ArrayPtr words((const capnp::word *)data, size / sizeof(capnp::word)); - while (words.size() > 0 && !(abort && *abort)) { - capnp::FlatArrayMessageReader reader(words); - auto event = reader.getRoot(); - auto which = event.which(); - auto event_data = kj::arrayPtr(words.begin(), reader.getEnd()); - words = kj::arrayPtr(reader.getEnd(), words.end()); - if (which == cereal::Event::Which::SELFDRIVE_STATE) { - requires_migration = false; - } - - if (!filters_.empty()) { - if (which >= filters_.size() || !filters_[which]) - continue; - auto buf = buffer_.allocate(event_data.size() * sizeof(capnp::word)); - memcpy(buf, event_data.begin(), event_data.size() * sizeof(capnp::word)); - event_data = kj::arrayPtr((const capnp::word *)buf, event_data.size()); - } - - uint64_t mono_time = event.getLogMonoTime(); - const Event &evt = events.emplace_back(which, mono_time, event_data); - // Add encodeIdx packet again as a frame packet for the video stream - if (evt.which == cereal::Event::ROAD_ENCODE_IDX || - evt.which == cereal::Event::DRIVER_ENCODE_IDX || - evt.which == cereal::Event::WIDE_ROAD_ENCODE_IDX) { - auto idx = capnp::AnyStruct::Reader(event).getPointerSection()[0].getAs(); - if (idx.getType() == cereal::EncodeIndex::Type::FULL_H_E_V_C) { - uint64_t sof = idx.getTimestampSof(); - events.emplace_back(which, sof ? sof : mono_time, event_data, idx.getSegmentNum()); - } - } - } - } catch (const kj::Exception &e) { - rWarning("Failed to parse log : %s.\nRetrieved %zu events from corrupt log", e.getDescription().cStr(), events.size()); - } - - if (requires_migration) { - migrateOldEvents(); - } - - if (!events.empty() && !(abort && *abort)) { - events.shrink_to_fit(); - std::sort(events.begin(), events.end()); - return true; - } - return false; -} - -void LogReader::migrateOldEvents() { - size_t events_size = events.size(); - for (int i = 0; i < events_size; ++i) { - // Check if the event is of the old CONTROLS_STATE type - auto &event = events[i]; - if (event.which == cereal::Event::CONTROLS_STATE) { - // Read the old event data - capnp::FlatArrayMessageReader reader(event.data); - auto old_evt = reader.getRoot(); - auto old_state = old_evt.getControlsState(); - - // Migrate relevant fields from old CONTROLS_STATE to new SelfdriveState - MessageBuilder msg; - auto new_evt = msg.initEvent(old_evt.getValid()); - new_evt.setLogMonoTime(old_evt.getLogMonoTime()); - auto new_state = new_evt.initSelfdriveState(); - - new_state.setActive(old_state.getActiveDEPRECATED()); - new_state.setAlertSize(old_state.getAlertSizeDEPRECATED()); - new_state.setAlertSound(old_state.getAlertSound2DEPRECATED()); - new_state.setAlertStatus(old_state.getAlertStatusDEPRECATED()); - new_state.setAlertText1(old_state.getAlertText1DEPRECATED()); - new_state.setAlertText2(old_state.getAlertText2DEPRECATED()); - new_state.setAlertType(old_state.getAlertTypeDEPRECATED()); - new_state.setEnabled(old_state.getEnabledDEPRECATED()); - new_state.setEngageable(old_state.getEngageableDEPRECATED()); - new_state.setExperimentalMode(old_state.getExperimentalModeDEPRECATED()); - new_state.setPersonality(old_state.getPersonalityDEPRECATED()); - new_state.setState(old_state.getStateDEPRECATED()); - - // Serialize the new event to the buffer - auto buf_size = msg.getSerializedSize(); - auto buf = buffer_.allocate(buf_size); - msg.serializeToBuffer(reinterpret_cast(buf), buf_size); - - // Store the migrated event in the events list - auto event_data = kj::arrayPtr(reinterpret_cast(buf), buf_size); - events.emplace_back(new_evt.which(), new_evt.getLogMonoTime(), event_data); - } - } -} diff --git a/tools/replay/logreader.h b/tools/replay/logreader.h deleted file mode 100644 index f8d60ffadd..0000000000 --- a/tools/replay/logreader.h +++ /dev/null @@ -1,42 +0,0 @@ -#pragma once - -#include -#include - -#include "cereal/gen/cpp/log.capnp.h" -#include "tools/replay/util.h" - -const CameraType ALL_CAMERAS[] = {RoadCam, DriverCam, WideRoadCam}; -const int MAX_CAMERAS = std::size(ALL_CAMERAS); - -class Event { -public: - Event(cereal::Event::Which which, uint64_t mono_time, const kj::ArrayPtr &data, int eidx_segnum = -1) - : which(which), mono_time(mono_time), data(data), eidx_segnum(eidx_segnum) {} - - bool operator<(const Event &other) const { - return mono_time < other.mono_time || (mono_time == other.mono_time && which < other.which); - } - - uint64_t mono_time; - cereal::Event::Which which; - kj::ArrayPtr data; - int32_t eidx_segnum; -}; - -class LogReader { -public: - LogReader(const std::vector &filters = {}) { filters_ = filters; } - bool load(const std::string &url, std::atomic *abort = nullptr, - bool local_cache = false, int chunk_size = -1, int retries = 0); - bool load(const char *data, size_t size, std::atomic *abort = nullptr); - std::vector events; - -private: - void migrateOldEvents(); - - std::string raw_; - bool requires_migration = true; - std::vector filters_; - MonotonicBuffer buffer_{1024 * 1024}; -}; diff --git a/tools/replay/main.cc b/tools/replay/main.cc deleted file mode 100644 index 38a1da292a..0000000000 --- a/tools/replay/main.cc +++ /dev/null @@ -1,155 +0,0 @@ -#include - -#include -#include -#include -#include - -#include "common/prefix.h" -#include "tools/replay/consoleui.h" -#include "tools/replay/replay.h" -#include "tools/replay/util.h" - -const std::string helpText = -R"(Usage: replay [options] [route] -Options: - -a, --allow Whitelist of services to send (comma-separated) - -b, --block Blacklist of services to send (comma-separated) - -c, --cache Cache segments in memory. Default is 5 - -s, --start Start from - -x, --playback Playback - --demo Use a demo route instead of providing your own - --auto Auto load the route from the best available source (no video): - internal, openpilotci, comma_api, car_segments, testing_closet - -d, --data_dir Local directory with routes - -p, --prefix Set OPENPILOT_PREFIX - --dcam Load driver camera - --ecam Load wide road camera - --no-loop Stop at the end of the route - --no-cache Turn off local cache - --qcam Load qcamera - --no-hw-decoder Disable HW video decoding - --no-vipc Do not output video - --all Output all messages including uiDebug, userFlag - -h, --help Show this help message -)"; - -struct ReplayConfig { - std::string route; - std::vector allow; - std::vector block; - std::string data_dir; - std::string prefix; - uint32_t flags = REPLAY_FLAG_NONE; - bool auto_source = false; - int start_seconds = 0; - int cache_segments = -1; - float playback_speed = -1; -}; - -bool parseArgs(int argc, char *argv[], ReplayConfig &config) { - const struct option cli_options[] = { - {"allow", required_argument, nullptr, 'a'}, - {"block", required_argument, nullptr, 'b'}, - {"cache", required_argument, nullptr, 'c'}, - {"start", required_argument, nullptr, 's'}, - {"playback", required_argument, nullptr, 'x'}, - {"demo", no_argument, nullptr, 0}, - {"auto", no_argument, nullptr, 0}, - {"data_dir", required_argument, nullptr, 'd'}, - {"prefix", required_argument, nullptr, 'p'}, - {"dcam", no_argument, nullptr, 0}, - {"ecam", no_argument, nullptr, 0}, - {"no-loop", no_argument, nullptr, 0}, - {"no-cache", no_argument, nullptr, 0}, - {"qcam", no_argument, nullptr, 0}, - {"no-hw-decoder", no_argument, nullptr, 0}, - {"no-vipc", no_argument, nullptr, 0}, - {"all", no_argument, nullptr, 0}, - {"help", no_argument, nullptr, 'h'}, - {nullptr, 0, nullptr, 0}, // Terminating entry - }; - - const std::map flag_map = { - {"dcam", REPLAY_FLAG_DCAM}, - {"ecam", REPLAY_FLAG_ECAM}, - {"no-loop", REPLAY_FLAG_NO_LOOP}, - {"no-cache", REPLAY_FLAG_NO_FILE_CACHE}, - {"qcam", REPLAY_FLAG_QCAMERA}, - {"no-hw-decoder", REPLAY_FLAG_NO_HW_DECODER}, - {"no-vipc", REPLAY_FLAG_NO_VIPC}, - {"all", REPLAY_FLAG_ALL_SERVICES}, - }; - - if (argc == 1) { - std::cout << helpText; - return false; - } - - int opt, option_index = 0; - while ((opt = getopt_long(argc, argv, "a:b:c:s:x:d:p:h", cli_options, &option_index)) != -1) { - switch (opt) { - case 'a': config.allow = split(optarg, ','); break; - case 'b': config.block = split(optarg, ','); break; - case 'c': config.cache_segments = std::atoi(optarg); break; - case 's': config.start_seconds = std::atoi(optarg); break; - case 'x': config.playback_speed = std::atof(optarg); break; - case 'd': config.data_dir = optarg; break; - case 'p': config.prefix = optarg; break; - case 0: { - std::string name = cli_options[option_index].name; - if (name == "demo") config.route = DEMO_ROUTE; - else if (name == "auto") config.auto_source = true; - else config.flags |= flag_map.at(name); - break; - } - case 'h': std::cout << helpText; return false; - default: return false; - } - } - - // Check for a route name (first positional argument) - if (config.route.empty() && optind < argc) { - config.route = argv[optind]; - } - - if (config.route.empty()) { - std::cerr << "No route provided. Use --help for usage information.\n"; - return false; - } - - return true; -} - -int main(int argc, char *argv[]) { -#ifdef __APPLE__ - // With all sockets opened, we might hit the default limit of 256 on macOS - util::set_file_descriptor_limit(1024); -#endif - - ReplayConfig config; - - if (!parseArgs(argc, argv, config)) { - return 1; - } - - std::unique_ptr op_prefix; - if (!config.prefix.empty()) { - op_prefix = std::make_unique(config.prefix); - } - - Replay replay(config.route, config.allow, config.block, nullptr, config.flags, config.data_dir, config.auto_source); - if (config.cache_segments > 0) { - replay.setSegmentCacheLimit(config.cache_segments); - } - if (config.playback_speed > 0) { - replay.setSpeed(std::clamp(config.playback_speed, ConsoleUI::speed_array.front(), ConsoleUI::speed_array.back())); - } - if (!replay.load()) { - return 1; - } - - ConsoleUI console_ui(&replay); - replay.start(config.start_seconds); - return console_ui.exec(); -} diff --git a/tools/replay/rp_visualization.py b/tools/replay/rp_visualization.py deleted file mode 100755 index 25169b72ae..0000000000 --- a/tools/replay/rp_visualization.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env python3 -import argparse -import os -import sys -import numpy as np -import rerun as rr -import cereal.messaging as messaging -from openpilot.common.basedir import BASEDIR -from openpilot.tools.replay.lib.rp_helpers import (UP, rerunColorPalette, - get_blank_lid_overlay, - update_radar_points, plot_lead, - plot_model) -from msgq.visionipc import VisionIpcClient, VisionStreamType - -os.environ['BASEDIR'] = BASEDIR - -UP.lidar_zoom = 6 - -def visualize(addr): - sm = messaging.SubMaster(['radarState', 'liveTracks', 'modelV2'], addr=addr) - vipc_client = VisionIpcClient("camerad", VisionStreamType.VISION_STREAM_ROAD, True) - while True: - if not vipc_client.is_connected(): - vipc_client.connect(True) - new_data = vipc_client.recv() - if new_data is None or not new_data.data.any(): - continue - - sm.update(0) - lid_overlay = get_blank_lid_overlay(UP) - if sm.recv_frame['modelV2']: - plot_model(sm['modelV2'], lid_overlay) - if sm.recv_frame['radarState']: - plot_lead(sm['radarState'], lid_overlay) - liveTracksTime = sm.logMonoTime['liveTracks'] - if sm.updated['liveTracks']: - update_radar_points(sm['liveTracks'], lid_overlay) - rr.set_time_nanos("TIMELINE", liveTracksTime) - rr.log("tracks", rr.SegmentationImage(np.flip(np.rot90(lid_overlay, k=-1), axis=1))) - - -def get_arg_parser(): - parser = argparse.ArgumentParser( - description="Show replay data in a UI.", - formatter_class=argparse.ArgumentDefaultsHelpFormatter) - parser.add_argument("ip_address", nargs="?", default="127.0.0.1", - help="The ip address on which to receive zmq messages.") - parser.add_argument("--frame-address", default=None, - help="The frame address (fully qualified ZMQ endpoint for frames) on which to receive zmq messages.") - return parser - - -if __name__ == "__main__": - args = get_arg_parser().parse_args(sys.argv[1:]) - if args.ip_address != "127.0.0.1": - os.environ["ZMQ"] = "1" - messaging.reset_context() - rr.init("RadarPoints", spawn= True) - rr.log("tracks", rr.AnnotationContext(rerunColorPalette), static=True) - visualize(args.ip_address) diff --git a/tools/replay/ui.py b/tools/replay/ui.py deleted file mode 100755 index 6e40579902..0000000000 --- a/tools/replay/ui.py +++ /dev/null @@ -1,237 +0,0 @@ -#!/usr/bin/env python3 -import argparse -import os -import sys - -import cv2 -import numpy as np -import pygame - -import cereal.messaging as messaging -from openpilot.common.basedir import BASEDIR -from openpilot.common.transformations.camera import DEVICE_CAMERAS -from openpilot.tools.replay.lib.ui_helpers import (UP, - BLACK, GREEN, - YELLOW, Calibration, - get_blank_lid_overlay, init_plots, - maybe_update_radar_points, plot_lead, - plot_model, - pygame_modules_have_loaded) -from msgq.visionipc import VisionIpcClient, VisionStreamType - -os.environ['BASEDIR'] = BASEDIR - -ANGLE_SCALE = 5.0 - -def ui_thread(addr): - cv2.setNumThreads(1) - pygame.init() - pygame.font.init() - assert pygame_modules_have_loaded() - - disp_info = pygame.display.Info() - max_height = disp_info.current_h - - hor_mode = os.getenv("HORIZONTAL") is not None - hor_mode = True if max_height < 960+300 else hor_mode - - if hor_mode: - size = (640+384+640, 960) - write_x = 5 - write_y = 680 - else: - size = (640+384, 960+300) - write_x = 645 - write_y = 970 - - pygame.display.set_caption("openpilot debug UI") - screen = pygame.display.set_mode(size, pygame.DOUBLEBUF) - - alert1_font = pygame.font.SysFont("arial", 30) - alert2_font = pygame.font.SysFont("arial", 20) - info_font = pygame.font.SysFont("arial", 15) - - camera_surface = pygame.surface.Surface((640, 480), 0, 24).convert() - top_down_surface = pygame.surface.Surface((UP.lidar_x, UP.lidar_y), 0, 8) - - sm = messaging.SubMaster(['carState', 'longitudinalPlan', 'carControl', 'radarState', 'liveCalibration', 'controlsState', - 'selfdriveState', 'liveTracks', 'modelV2', 'liveParameters', 'roadCameraState'], addr=addr) - - img = np.zeros((480, 640, 3), dtype='uint8') - imgff = None - num_px = 0 - calibration = None - - lid_overlay_blank = get_blank_lid_overlay(UP) - - # plots - name_to_arr_idx = { "gas": 0, - "computer_gas": 1, - "user_brake": 2, - "computer_brake": 3, - "v_ego": 4, - "v_pid": 5, - "angle_steers_des": 6, - "angle_steers": 7, - "angle_steers_k": 8, - "steer_torque": 9, - "v_override": 10, - "v_cruise": 11, - "a_ego": 12, - "a_target": 13} - - plot_arr = np.zeros((100, len(name_to_arr_idx.values()))) - - plot_xlims = [(0, plot_arr.shape[0]), (0, plot_arr.shape[0]), (0, plot_arr.shape[0]), (0, plot_arr.shape[0])] - plot_ylims = [(-0.1, 1.1), (-ANGLE_SCALE, ANGLE_SCALE), (0., 75.), (-3.0, 2.0)] - plot_names = [["gas", "computer_gas", "user_brake", "computer_brake"], - ["angle_steers", "angle_steers_des", "angle_steers_k", "steer_torque"], - ["v_ego", "v_override", "v_pid", "v_cruise"], - ["a_ego", "a_target"]] - plot_colors = [["b", "b", "g", "r", "y"], - ["b", "g", "y", "r"], - ["b", "g", "r", "y"], - ["b", "r"]] - plot_styles = [["-", "-", "-", "-", "-"], - ["-", "-", "-", "-"], - ["-", "-", "-", "-"], - ["-", "-"]] - - draw_plots = init_plots(plot_arr, name_to_arr_idx, plot_xlims, plot_ylims, plot_names, plot_colors, plot_styles) - - vipc_client = VisionIpcClient("camerad", VisionStreamType.VISION_STREAM_ROAD, True) - while True: - for event in pygame.event.get(): - if event.type == pygame.QUIT: - pygame.quit() - sys.exit() - - screen.fill((64, 64, 64)) - lid_overlay = lid_overlay_blank.copy() - top_down = top_down_surface, lid_overlay - - # ***** frame ***** - if not vipc_client.is_connected(): - vipc_client.connect(True) - - yuv_img_raw = vipc_client.recv() - if yuv_img_raw is None or not yuv_img_raw.data.any(): - continue - - sm.update(0) - - camera = DEVICE_CAMERAS[("tici", str(sm['roadCameraState'].sensor))] - - imgff = np.frombuffer(yuv_img_raw.data, dtype=np.uint8).reshape((len(yuv_img_raw.data) // vipc_client.stride, vipc_client.stride)) - num_px = vipc_client.width * vipc_client.height - rgb = cv2.cvtColor(imgff[:vipc_client.height * 3 // 2, :vipc_client.width], cv2.COLOR_YUV2RGB_NV12) - - qcam = "QCAM" in os.environ - bb_scale = (528 if qcam else camera.fcam.width) / 640. - calib_scale = camera.fcam.width / 640. - zoom_matrix = np.asarray([ - [bb_scale, 0., 0.], - [0., bb_scale, 0.], - [0., 0., 1.]]) - cv2.warpAffine(rgb, zoom_matrix[:2], (img.shape[1], img.shape[0]), dst=img, flags=cv2.WARP_INVERSE_MAP) - - intrinsic_matrix = camera.fcam.intrinsics - - w = sm['controlsState'].lateralControlState.which() - if w == 'lqrStateDEPRECATED': - angle_steers_k = sm['controlsState'].lateralControlState.lqrStateDEPRECATED.steeringAngleDeg - elif w == 'indiState': - angle_steers_k = sm['controlsState'].lateralControlState.indiState.steeringAngleDeg - else: - angle_steers_k = np.inf - - plot_arr[:-1] = plot_arr[1:] - plot_arr[-1, name_to_arr_idx['angle_steers']] = sm['carState'].steeringAngleDeg - plot_arr[-1, name_to_arr_idx['angle_steers_des']] = sm['carControl'].actuators.steeringAngleDeg - plot_arr[-1, name_to_arr_idx['angle_steers_k']] = angle_steers_k - plot_arr[-1, name_to_arr_idx['gas']] = sm['carState'].gas - # TODO gas is deprecated - plot_arr[-1, name_to_arr_idx['computer_gas']] = np.clip(sm['carControl'].actuators.accel/4.0, 0.0, 1.0) - plot_arr[-1, name_to_arr_idx['user_brake']] = sm['carState'].brake - plot_arr[-1, name_to_arr_idx['steer_torque']] = sm['carControl'].actuators.torque * ANGLE_SCALE - # TODO brake is deprecated - plot_arr[-1, name_to_arr_idx['computer_brake']] = np.clip(-sm['carControl'].actuators.accel/4.0, 0.0, 1.0) - plot_arr[-1, name_to_arr_idx['v_ego']] = sm['carState'].vEgo - plot_arr[-1, name_to_arr_idx['v_cruise']] = sm['carState'].cruiseState.speed - plot_arr[-1, name_to_arr_idx['a_ego']] = sm['carState'].aEgo - - if len(sm['longitudinalPlan'].accels): - plot_arr[-1, name_to_arr_idx['a_target']] = sm['longitudinalPlan'].accels[0] - - if sm.recv_frame['modelV2']: - plot_model(sm['modelV2'], img, calibration, top_down) - - if sm.recv_frame['radarState']: - plot_lead(sm['radarState'], top_down) - - # draw all radar points - maybe_update_radar_points(sm['liveTracks'].points, top_down[1]) - - if sm.updated['liveCalibration'] and num_px: - rpyCalib = np.asarray(sm['liveCalibration'].rpyCalib) - calibration = Calibration(num_px, rpyCalib, intrinsic_matrix, calib_scale) - - # *** blits *** - pygame.surfarray.blit_array(camera_surface, img.swapaxes(0, 1)) - screen.blit(camera_surface, (0, 0)) - - # display alerts - alert_line1 = alert1_font.render(sm['selfdriveState'].alertText1, True, (255, 0, 0)) - alert_line2 = alert2_font.render(sm['selfdriveState'].alertText2, True, (255, 0, 0)) - screen.blit(alert_line1, (180, 150)) - screen.blit(alert_line2, (180, 190)) - - if hor_mode: - screen.blit(draw_plots(plot_arr), (640+384, 0)) - else: - screen.blit(draw_plots(plot_arr), (0, 600)) - - pygame.surfarray.blit_array(*top_down) - screen.blit(top_down[0], (640, 0)) - - SPACING = 25 - - lines = [ - info_font.render("ENABLED", True, GREEN if sm['selfdriveState'].enabled else BLACK), - info_font.render("SPEED: " + str(round(sm['carState'].vEgo, 1)) + " m/s", True, YELLOW), - info_font.render("LONG CONTROL STATE: " + str(sm['controlsState'].longControlState), True, YELLOW), - info_font.render("LONG MPC SOURCE: " + str(sm['longitudinalPlan'].longitudinalPlanSource), True, YELLOW), - None, - info_font.render("ANGLE OFFSET (AVG): " + str(round(sm['liveParameters'].angleOffsetAverageDeg, 2)) + " deg", True, YELLOW), - info_font.render("ANGLE OFFSET (INSTANT): " + str(round(sm['liveParameters'].angleOffsetDeg, 2)) + " deg", True, YELLOW), - info_font.render("STIFFNESS: " + str(round(sm['liveParameters'].stiffnessFactor * 100., 2)) + " %", True, YELLOW), - info_font.render("STEER RATIO: " + str(round(sm['liveParameters'].steerRatio, 2)), True, YELLOW) - ] - - for i, line in enumerate(lines): - if line is not None: - screen.blit(line, (write_x, write_y + i * SPACING)) - - # this takes time...vsync or something - pygame.display.flip() - -def get_arg_parser(): - parser = argparse.ArgumentParser( - description="Show replay data in a UI.", - formatter_class=argparse.ArgumentDefaultsHelpFormatter) - - parser.add_argument("ip_address", nargs="?", default="127.0.0.1", - help="The ip address on which to receive zmq messages.") - - parser.add_argument("--frame-address", default=None, - help="The frame address (fully qualified ZMQ endpoint for frames) on which to receive zmq messages.") - return parser - -if __name__ == "__main__": - args = get_arg_parser().parse_args(sys.argv[1:]) - - if args.ip_address != "127.0.0.1": - os.environ["ZMQ"] = "1" - messaging.reset_context() - - ui_thread(args.ip_address) diff --git a/tools/replay/unlog_ci_segment.py b/tools/replay/unlog_ci_segment.py deleted file mode 100755 index 6ddc1b298a..0000000000 --- a/tools/replay/unlog_ci_segment.py +++ /dev/null @@ -1,108 +0,0 @@ -#!/usr/bin/env python3 - -import argparse -import bisect -import select -import sys -import termios -import time -import tty -from collections import defaultdict - -import cereal.messaging as messaging -from openpilot.tools.lib.framereader import FrameReader -from openpilot.tools.lib.logreader import LogReader -from openpilot.tools.lib.openpilotci import get_url - -IGNORE = ['initData', 'sentinel'] - - -def input_ready(): - return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], []) - - -def replay(route, segment, loop): - route = route.replace('|', '/') - - lr = LogReader(get_url(route, segment, "rlog.bz2")) - fr = FrameReader(get_url(route, segment, "fcamera.hevc"), readahead=True) - - # Build mapping from frameId to segmentId from roadEncodeIdx, type == fullHEVC - msgs = [m for m in lr if m.which() not in IGNORE] - msgs = sorted(msgs, key=lambda m: m.logMonoTime) - times = [m.logMonoTime for m in msgs] - frame_idx = {m.roadEncodeIdx.frameId: m.roadEncodeIdx.segmentId for m in msgs if m.which() == 'roadEncodeIdx' and m.roadEncodeIdx.type == 'fullHEVC'} - - socks = {} - lag = 0.0 - i = 0 - max_i = len(msgs) - 2 - - while True: - msg = msgs[i].as_builder() - next_msg = msgs[i + 1] - - start_time = time.time() - w = msg.which() - - if w == 'roadCameraState': - try: - img = fr.get(frame_idx[msg.roadCameraState.frameId]) - img = img[:, ::-1] # Convert RGB to BGR, which is what the camera outputs - msg.roadCameraState.image = img.flatten().tobytes() - except (KeyError, ValueError): - pass - - if w not in socks: - socks[w] = messaging.pub_sock(w) - - try: - if socks[w]: - socks[w].send(msg.to_bytes()) - except messaging.messaging_pyx.MultiplePublishersError: - socks[w] = None - - lag += (next_msg.logMonoTime - msg.logMonoTime) / 1e9 - lag -= time.time() - start_time - - dt = max(lag, 0.0) - lag -= dt - time.sleep(dt) - - if lag < -1.0 and i % 1000 == 0: - print(f"{-lag:.2f} s behind") - - if input_ready(): - key = sys.stdin.read(1) - - # Handle pause - if key == " ": - while True: - if input_ready() and sys.stdin.read(1) == " ": - break - time.sleep(0.01) - - # Handle seek - dt = defaultdict(int, s=10, S=-10)[key] - new_time = msgs[i].logMonoTime + dt * 1e9 - i = bisect.bisect_left(times, new_time) - - i = (i + 1) % max_i if loop else min(i + 1, max_i) - - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument("--loop", action='store_true') - parser.add_argument("route") - parser.add_argument("segment") - args = parser.parse_args() - - orig_settings = termios.tcgetattr(sys.stdin) - tty.setcbreak(sys.stdin) - - try: - replay(args.route, args.segment, args.loop) - termios.tcsetattr(sys.stdin, termios.TCSADRAIN, orig_settings) - except Exception: - termios.tcsetattr(sys.stdin, termios.TCSADRAIN, orig_settings) - raise diff --git a/tools/replay/util.cc b/tools/replay/util.cc deleted file mode 100644 index 94cea961ff..0000000000 --- a/tools/replay/util.cc +++ /dev/null @@ -1,434 +0,0 @@ -#include "tools/replay/util.h" - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "common/timing.h" -#include "common/util.h" - -ReplayMessageHandler message_handler = nullptr; -void installMessageHandler(ReplayMessageHandler handler) { message_handler = handler; } - -void logMessage(ReplyMsgType type, const char *fmt, ...) { - static std::mutex lock; - std::lock_guard lk(lock); - - char *msg_buf = nullptr; - va_list args; - va_start(args, fmt); - int ret = vasprintf(&msg_buf, fmt, args); - va_end(args); - if (ret <= 0 || !msg_buf) return; - - if (message_handler) { - message_handler(type, msg_buf); - } else { - if (type == ReplyMsgType::Debug) { - std::cout << "\033[38;5;248m" << msg_buf << "\033[00m" << std::endl; - } else if (type == ReplyMsgType::Warning) { - std::cout << "\033[38;5;227m" << msg_buf << "\033[00m" << std::endl; - } else if (type == ReplyMsgType::Critical) { - std::cout << "\033[38;5;196m" << msg_buf << "\033[00m" << std::endl; - } else { - std::cout << msg_buf << std::endl; - } - } - - free(msg_buf); -} - -namespace { - -struct CURLGlobalInitializer { - CURLGlobalInitializer() { curl_global_init(CURL_GLOBAL_DEFAULT); } - ~CURLGlobalInitializer() { curl_global_cleanup(); } -}; - -static CURLGlobalInitializer curl_initializer; - -template -struct MultiPartWriter { - T *buf; - size_t *total_written; - size_t offset; - size_t end; - - size_t write(char *data, size_t size, size_t count) { - size_t bytes = size * count; - if ((offset + bytes) > end) return 0; - - if constexpr (std::is_same::value) { - memcpy(buf->data() + offset, data, bytes); - } else if constexpr (std::is_same::value) { - buf->seekp(offset); - buf->write(data, bytes); - } - - offset += bytes; - *total_written += bytes; - return bytes; - } -}; - -template -size_t write_cb(char *data, size_t size, size_t count, void *userp) { - auto w = (MultiPartWriter *)userp; - return w->write(data, size, count); -} - -size_t dumy_write_cb(char *data, size_t size, size_t count, void *userp) { return size * count; } - -struct DownloadStats { - void installDownloadProgressHandler(DownloadProgressHandler handler) { - std::lock_guard lk(lock); - download_progress_handler = handler; - } - - void add(const std::string &url, uint64_t total_bytes) { - std::lock_guard lk(lock); - items[url] = {0, total_bytes}; - } - - void remove(const std::string &url) { - std::lock_guard lk(lock); - items.erase(url); - } - - void update(const std::string &url, uint64_t downloaded, bool success = true) { - std::lock_guard lk(lock); - items[url].first = downloaded; - - auto stat = std::accumulate(items.begin(), items.end(), std::pair{}, [=](auto &a, auto &b){ - return std::pair{a.first + b.second.first, a.second + b.second.second}; - }); - double tm = millis_since_boot(); - if (download_progress_handler && ((tm - prev_tm) > 500 || !success || stat.first >= stat.second)) { - download_progress_handler(stat.first, stat.second, success); - prev_tm = tm; - } - } - - std::mutex lock; - std::map> items; - double prev_tm = 0; - DownloadProgressHandler download_progress_handler = nullptr; -}; - -static DownloadStats download_stats; - -} // namespace - -void installDownloadProgressHandler(DownloadProgressHandler handler) { - download_stats.installDownloadProgressHandler(handler); -} - -std::string formattedDataSize(size_t size) { - if (size < 1024) { - return std::to_string(size) + " B"; - } else if (size < 1024 * 1024) { - return util::string_format("%.2f KB", (float)size / 1024); - } else { - return util::string_format("%.2f MB", (float)size / (1024 * 1024)); - } -} - -size_t getRemoteFileSize(const std::string &url, std::atomic *abort) { - CURL *curl = curl_easy_init(); - if (!curl) return -1; - - curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); - curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, dumy_write_cb); - curl_easy_setopt(curl, CURLOPT_HEADER, 1); - curl_easy_setopt(curl, CURLOPT_NOBODY, 1); - - CURLM *cm = curl_multi_init(); - curl_multi_add_handle(cm, curl); - int still_running = 1; - while (still_running > 0 && !(abort && *abort)) { - CURLMcode mc = curl_multi_perform(cm, &still_running); - if (mc != CURLM_OK) break; - if (still_running > 0) { - curl_multi_wait(cm, nullptr, 0, 1000, nullptr); - } - } - - double content_length = -1; - curl_easy_getinfo(curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &content_length); - curl_multi_remove_handle(cm, curl); - curl_easy_cleanup(curl); - curl_multi_cleanup(cm); - return content_length > 0 ? (size_t)content_length : 0; -} - -std::string getUrlWithoutQuery(const std::string &url) { - size_t idx = url.find("?"); - return (idx == std::string::npos ? url : url.substr(0, idx)); -} - -template -bool httpDownload(const std::string &url, T &buf, size_t chunk_size, size_t content_length, std::atomic *abort) { - download_stats.add(url, content_length); - - int parts = 1; - if (chunk_size > 0 && content_length > 10 * 1024 * 1024) { - parts = std::nearbyint(content_length / (float)chunk_size); - parts = std::clamp(parts, 1, 5); - } - - CURLM *cm = curl_multi_init(); - size_t written = 0; - std::map> writers; - const int part_size = content_length / parts; - for (int i = 0; i < parts; ++i) { - CURL *eh = curl_easy_init(); - writers[eh] = { - .buf = &buf, - .total_written = &written, - .offset = (size_t)(i * part_size), - .end = i == parts - 1 ? content_length : (i + 1) * part_size, - }; - curl_easy_setopt(eh, CURLOPT_WRITEFUNCTION, write_cb); - curl_easy_setopt(eh, CURLOPT_WRITEDATA, (void *)(&writers[eh])); - curl_easy_setopt(eh, CURLOPT_URL, url.c_str()); - curl_easy_setopt(eh, CURLOPT_RANGE, util::string_format("%d-%d", writers[eh].offset, writers[eh].end - 1).c_str()); - curl_easy_setopt(eh, CURLOPT_HTTPGET, 1); - curl_easy_setopt(eh, CURLOPT_NOSIGNAL, 1); - curl_easy_setopt(eh, CURLOPT_FOLLOWLOCATION, 1); - - curl_multi_add_handle(cm, eh); - } - - int still_running = 1; - size_t prev_written = 0; - while (still_running > 0 && !(abort && *abort)) { - CURLMcode mc = curl_multi_perform(cm, &still_running); - if (mc != CURLM_OK) { - break; - } - if (still_running > 0) { - curl_multi_wait(cm, nullptr, 0, 1000, nullptr); - } - - if (((written - prev_written) / (double)content_length) >= 0.01) { - download_stats.update(url, written); - prev_written = written; - } - } - - CURLMsg *msg; - int msgs_left = -1; - int complete = 0; - while ((msg = curl_multi_info_read(cm, &msgs_left)) && !(abort && *abort)) { - if (msg->msg == CURLMSG_DONE) { - if (msg->data.result == CURLE_OK) { - long res_status = 0; - curl_easy_getinfo(msg->easy_handle, CURLINFO_RESPONSE_CODE, &res_status); - if (res_status == 206) { - complete++; - } else { - rWarning("Download failed: http error code: %d", res_status); - } - } else { - rWarning("Download failed: connection failure: %d", msg->data.result); - } - } - } - - bool success = complete == parts; - download_stats.update(url, written, success); - download_stats.remove(url); - - for (const auto &[e, w] : writers) { - curl_multi_remove_handle(cm, e); - curl_easy_cleanup(e); - } - curl_multi_cleanup(cm); - - return success; -} - -std::string httpGet(const std::string &url, size_t chunk_size, std::atomic *abort) { - size_t size = getRemoteFileSize(url, abort); - if (size == 0) return {}; - - std::string result(size, '\0'); - return httpDownload(url, result, chunk_size, size, abort) ? result : ""; -} - -bool httpDownload(const std::string &url, const std::string &file, size_t chunk_size, std::atomic *abort) { - size_t size = getRemoteFileSize(url, abort); - if (size == 0) return false; - - std::ofstream of(file, std::ios::binary | std::ios::out); - of.seekp(size - 1).write("\0", 1); - return httpDownload(url, of, chunk_size, size, abort); -} - -std::string decompressBZ2(const std::string &in, std::atomic *abort) { - return decompressBZ2((std::byte *)in.data(), in.size(), abort); -} - -std::string decompressBZ2(const std::byte *in, size_t in_size, std::atomic *abort) { - if (in_size == 0) return {}; - - bz_stream strm = {}; - int bzerror = BZ2_bzDecompressInit(&strm, 0, 0); - assert(bzerror == BZ_OK); - - strm.next_in = (char *)in; - strm.avail_in = in_size; - std::string out(in_size * 5, '\0'); - do { - strm.next_out = (char *)(&out[strm.total_out_lo32]); - strm.avail_out = out.size() - strm.total_out_lo32; - - const char *prev_write_pos = strm.next_out; - bzerror = BZ2_bzDecompress(&strm); - if (bzerror == BZ_OK && prev_write_pos == strm.next_out) { - // content is corrupt - bzerror = BZ_STREAM_END; - rWarning("decompressBZ2 error: content is corrupt"); - break; - } - - if (bzerror == BZ_OK && strm.avail_in > 0 && strm.avail_out == 0) { - out.resize(out.size() * 2); - } - } while (bzerror == BZ_OK && !(abort && *abort)); - - BZ2_bzDecompressEnd(&strm); - if (bzerror == BZ_STREAM_END && !(abort && *abort)) { - out.resize(strm.total_out_lo32); - out.shrink_to_fit(); - return out; - } - return {}; -} - -std::string decompressZST(const std::string &in, std::atomic *abort) { - return decompressZST((std::byte *)in.data(), in.size(), abort); -} - -std::string decompressZST(const std::byte *in, size_t in_size, std::atomic *abort) { - ZSTD_DCtx *dctx = ZSTD_createDCtx(); - assert(dctx != nullptr); - - // Initialize input and output buffers - ZSTD_inBuffer input = {in, in_size, 0}; - - // Estimate and reserve memory for decompressed data - size_t estimatedDecompressedSize = ZSTD_getFrameContentSize(in, in_size); - if (estimatedDecompressedSize == ZSTD_CONTENTSIZE_ERROR || estimatedDecompressedSize == ZSTD_CONTENTSIZE_UNKNOWN) { - estimatedDecompressedSize = in_size * 2; // Use a fallback size - } - - std::string decompressedData; - decompressedData.reserve(estimatedDecompressedSize); - - const size_t bufferSize = ZSTD_DStreamOutSize(); // Recommended output buffer size - std::string outputBuffer(bufferSize, '\0'); - - while (input.pos < input.size && !(abort && *abort)) { - ZSTD_outBuffer output = {outputBuffer.data(), bufferSize, 0}; - - size_t result = ZSTD_decompressStream(dctx, &output, &input); - if (ZSTD_isError(result)) { - rWarning("decompressZST error: content is corrupt"); - break; - } - - decompressedData.append(outputBuffer.data(), output.pos); - } - - ZSTD_freeDCtx(dctx); - if (!(abort && *abort)) { - decompressedData.shrink_to_fit(); - return decompressedData; - } - return {}; -} - -void precise_nano_sleep(int64_t nanoseconds, std::atomic &interrupt_requested) { - struct timespec req, rem; - req.tv_sec = nanoseconds / 1000000000; - req.tv_nsec = nanoseconds % 1000000000; - while (!interrupt_requested) { -#ifdef __APPLE__ - int ret = nanosleep(&req, &rem); - if (ret == 0 || errno != EINTR) - break; -#else - int ret = clock_nanosleep(CLOCK_MONOTONIC, 0, &req, &rem); - if (ret == 0 || ret != EINTR) - break; -#endif - // Retry sleep if interrupted by a signal - req = rem; - } -} - -std::string sha256(const std::string &str) { - unsigned char hash[SHA256_DIGEST_LENGTH]; - SHA256_CTX sha256; - SHA256_Init(&sha256); - SHA256_Update(&sha256, str.c_str(), str.size()); - SHA256_Final(hash, &sha256); - return util::hexdump(hash, SHA256_DIGEST_LENGTH); -} - -std::vector split(std::string_view source, char delimiter) { - std::vector fields; - size_t last = 0; - for (size_t i = 0; i < source.length(); ++i) { - if (source[i] == delimiter) { - fields.emplace_back(source.substr(last, i - last)); - last = i + 1; - } - } - fields.emplace_back(source.substr(last)); - return fields; -} - -std::string extractFileName(const std::string &file) { - size_t queryPos = file.find_first_of("?"); - std::string path = (queryPos != std::string::npos) ? file.substr(0, queryPos) : file; - size_t lastSlash = path.find_last_of("/\\"); - return (lastSlash != std::string::npos) ? path.substr(lastSlash + 1) : path; -} - -// MonotonicBuffer - -void *MonotonicBuffer::allocate(size_t bytes, size_t alignment) { - assert(bytes > 0); - void *p = std::align(alignment, bytes, current_buf, available); - if (p == nullptr) { - available = next_buffer_size = std::max(next_buffer_size, bytes); - current_buf = buffers.emplace_back(std::aligned_alloc(alignment, next_buffer_size)); - next_buffer_size *= growth_factor; - p = current_buf; - } - - current_buf = (char *)current_buf + bytes; - available -= bytes; - return p; -} - -MonotonicBuffer::~MonotonicBuffer() { - for (auto buf : buffers) { - free(buf); - } -} diff --git a/tools/replay/util.h b/tools/replay/util.h deleted file mode 100644 index 1f61951d21..0000000000 --- a/tools/replay/util.h +++ /dev/null @@ -1,74 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include "cereal/messaging/messaging.h" - -enum CameraType { - RoadCam = 0, - DriverCam, - WideRoadCam -}; - -enum class ReplyMsgType { - Info, - Debug, - Warning, - Critical -}; - -typedef std::function ReplayMessageHandler; -void installMessageHandler(ReplayMessageHandler); -void logMessage(ReplyMsgType type, const char* fmt, ...); - -#define rInfo(fmt, ...) ::logMessage(ReplyMsgType::Info, fmt, ## __VA_ARGS__) -#define rDebug(fmt, ...) ::logMessage(ReplyMsgType::Debug, fmt, ## __VA_ARGS__) -#define rWarning(fmt, ...) ::logMessage(ReplyMsgType::Warning, fmt, ## __VA_ARGS__) -#define rError(fmt, ...) ::logMessage(ReplyMsgType::Critical , fmt, ## __VA_ARGS__) - -class MonotonicBuffer { -public: - MonotonicBuffer(size_t initial_size) : next_buffer_size(initial_size) {} - ~MonotonicBuffer(); - void *allocate(size_t bytes, size_t alignment = 16ul); - void deallocate(void *p) {} - -private: - void *current_buf = nullptr; - size_t next_buffer_size = 0; - size_t available = 0; - std::deque buffers; - static constexpr float growth_factor = 1.5; -}; - -std::string sha256(const std::string &str); -void precise_nano_sleep(int64_t nanoseconds, std::atomic &interrupt_requested); -std::string decompressBZ2(const std::string &in, std::atomic *abort = nullptr); -std::string decompressBZ2(const std::byte *in, size_t in_size, std::atomic *abort = nullptr); -std::string decompressZST(const std::string &in, std::atomic *abort = nullptr); -std::string decompressZST(const std::byte *in, size_t in_size, std::atomic *abort = nullptr); -std::string getUrlWithoutQuery(const std::string &url); -size_t getRemoteFileSize(const std::string &url, std::atomic *abort = nullptr); -std::string httpGet(const std::string &url, size_t chunk_size = 0, std::atomic *abort = nullptr); - -typedef std::function DownloadProgressHandler; -void installDownloadProgressHandler(DownloadProgressHandler); -bool httpDownload(const std::string &url, const std::string &file, size_t chunk_size = 0, std::atomic *abort = nullptr); -std::string formattedDataSize(size_t size); -std::string extractFileName(const std::string& file); -std::vector split(std::string_view source, char delimiter); - -template -std::string join(const Iterable& elements, const std::string& separator) { - std::ostringstream oss; - for (auto it = elements.begin(); it != elements.end(); ++it) { - if (it != elements.begin()) oss << separator; - oss << *it; - } - return oss.str(); -} diff --git a/tools/rerun/README.md b/tools/rerun/README.md deleted file mode 100644 index 11a8d33ee1..0000000000 --- a/tools/rerun/README.md +++ /dev/null @@ -1,37 +0,0 @@ -# Rerun -Rerun is a tool to quickly visualize time series data. It supports all openpilot logs , both the `logMessages` and video logs. - -[Instructions](https://rerun.io/docs/reference/viewer/overview) for navigation within the Rerun Viewer. - -## Usage -``` -usage: run.py [-h] [--demo] [--qcam] [--fcam] [--ecam] [--dcam] [route_or_segment_name] - -A helper to run rerun on openpilot routes - -positional arguments: - route_or_segment_name - The route or segment name to plot (default: None) - -options: - -h, --help show this help message and exit - --demo Use the demo route instead of providing one (default: False) - --qcam Show low-res road camera (default: False) - --fcam Show driving camera (default: False) - --ecam Show wide camera (default: False) - --dcam Show driver monitoring camera (default: False) -``` - -Examples using route name to observe accelerometer and qcamera: - -`./run.py --qcam "a2a0ccea32023010/2023-07-27--13-01-19"` - -Examples using segment range (more on [SegmentRange](https://github.com/commaai/openpilot/tree/master/tools/lib)): - -`./run.py --qcam "a2a0ccea32023010/2023-07-27--13-01-19/2:4"` - -## Cautions: -- Showing hevc videos (`--fcam`, `--ecam`, and `--dcam`) are expensive, and it's recommended to use `--qcam` for optimized performance. If possible, limiting your route to a few segments using `SegmentRange` will speed up logging and reduce memory usage - -## Demo -`./run.py --qcam --demo` diff --git a/tools/rerun/camera_reader.py b/tools/rerun/camera_reader.py deleted file mode 100644 index 8366a3c1cf..0000000000 --- a/tools/rerun/camera_reader.py +++ /dev/null @@ -1,93 +0,0 @@ -import tqdm -import subprocess -import multiprocessing -from enum import StrEnum -from functools import partial -from collections import namedtuple - -from openpilot.tools.lib.framereader import ffprobe - -CameraConfig = namedtuple("CameraConfig", ["qcam", "fcam", "ecam", "dcam"]) - -class CameraType(StrEnum): - qcam = "qcamera" - fcam = "fcamera" - ecam = "ecamera" - dcam = "dcamera" - - -def probe_packet_info(camera_path): - args = ["ffprobe", "-v", "quiet", "-show_packets", "-probesize", "10M", camera_path] - dat = subprocess.check_output(args) - dat = dat.decode().split() - return dat - - -class _FrameReader: - def __init__(self, camera_path, segment, h, w, start_time): - self.camera_path = camera_path - self.segment = segment - self.h = h - self.w = w - self.start_time = start_time - - self.ts = self._get_ts() - - def _read_stream_nv12(self): - frame_sz = self.w * self.h * 3 // 2 - proc = subprocess.Popen( - ["ffmpeg", "-v", "quiet", "-i", self.camera_path, "-f", "rawvideo", "-pix_fmt", "nv12", "-"], - stdin=subprocess.PIPE, - stdout=subprocess.PIPE, - stderr=subprocess.DEVNULL - ) - try: - while True: - dat = proc.stdout.read(frame_sz) - if len(dat) == 0: - break - yield dat - finally: - proc.kill() - - def _get_ts(self): - dat = probe_packet_info(self.camera_path) - try: - ret = [float(d.split('=')[1]) for d in dat if d.startswith("pts_time=")] - except ValueError: - # pts_times aren't available. Infer timestamps from duration_times - ret = [d for d in dat if d.startswith("duration_time")] - ret = [float(d.split('=')[1])*(i+1)+(self.segment*60)+self.start_time for i, d in enumerate(ret)] - return ret - - def __iter__(self): - for i, frame in enumerate(self._read_stream_nv12()): - yield self.ts[i], frame - - -class CameraReader: - def __init__(self, camera_paths, start_time, seg_idxs): - self.seg_idxs = seg_idxs - self.camera_paths = camera_paths - self.start_time = start_time - - probe = ffprobe(camera_paths[0])["streams"][0] - self.h = probe["height"] - self.w = probe["width"] - - self.__frs = {} - - def _get_fr(self, i): - if i not in self.__frs: - self.__frs[i] = _FrameReader(self.camera_paths[i], segment=i, h=self.h, w=self.w, start_time=self.start_time) - return self.__frs[i] - - def _run_on_segment(self, func, i): - return func(self._get_fr(i)) - - def run_across_segments(self, num_processes, func, desc=None): - with multiprocessing.Pool(num_processes) as pool: - num_segs = len(self.seg_idxs) - for _ in tqdm.tqdm(pool.imap_unordered(partial(self._run_on_segment, func), self.seg_idxs), total=num_segs, desc=desc): - continue - diff --git a/tools/rerun/run.py b/tools/rerun/run.py deleted file mode 100755 index 6ce8a37937..0000000000 --- a/tools/rerun/run.py +++ /dev/null @@ -1,180 +0,0 @@ -#!/usr/bin/env python3 - -import sys -import argparse -import multiprocessing -import rerun as rr -import rerun.blueprint as rrb -from functools import partial -from collections import defaultdict - -from cereal.services import SERVICE_LIST -from openpilot.tools.rerun.camera_reader import probe_packet_info, CameraReader, CameraConfig, CameraType -from openpilot.tools.lib.logreader import LogReader -from openpilot.tools.lib.route import Route, SegmentRange - - -NUM_CPUS = multiprocessing.cpu_count() -DEMO_ROUTE = "a2a0ccea32023010|2023-07-27--13-01-19" -RR_TIMELINE_NAME = "Timeline" -RR_WIN = "openpilot logs" - - -""" -Relevant upstream Rerun issues: -- loading videos directly: https://github.com/rerun-io/rerun/issues/6532 -""" - -class Rerunner: - def __init__(self, route, segment_range, camera_config): - self.lr = LogReader(route_or_segment_name) - - # hevc files don't have start_time. We get it from qcamera.ts - start_time = 0 - dat = probe_packet_info(route.qcamera_paths()[0]) - for d in dat: - if d.startswith("pts_time="): - start_time = float(d.split('=')[1]) - break - - qcam, fcam, ecam, dcam = camera_config - self.camera_readers = {} - if qcam: - self.camera_readers[CameraType.qcam] = CameraReader(route.qcamera_paths(), start_time, segment_range.seg_idxs) - if fcam: - self.camera_readers[CameraType.fcam] = CameraReader(route.camera_paths(), start_time, segment_range.seg_idxs) - if ecam: - self.camera_readers[CameraType.ecam] = CameraReader(route.ecamera_paths(), start_time, segment_range.seg_idxs) - if dcam: - self.camera_readers[CameraType.dcam] = CameraReader(route.dcamera_paths(), start_time, segment_range.seg_idxs) - - def _create_blueprint(self): - blueprint = None - service_views = [] - - for topic in sorted(SERVICE_LIST.keys()): - View = rrb.TimeSeriesView if topic != "thumbnail" else rrb.Spatial2DView - service_views.append(View(name=topic, origin=f"/{topic}/", visible=False)) - rr.log(topic, rr.SeriesLine(name=topic), timeless=True) - - center_view = [rrb.Vertical(*service_views, name="streams")] - if len(self.camera_readers): - center_view.append(rrb.Vertical(*[rrb.Spatial2DView(name=cam_type, origin=cam_type) for cam_type in self.camera_readers.keys()], name="cameras")) - - blueprint = rrb.Blueprint( - rrb.Horizontal( - *center_view - ), - rrb.SelectionPanel(expanded=False), - rrb.TimePanel(expanded=False), - ) - return blueprint - - @staticmethod - def _parse_msg(msg, parent_key=''): - stack = [(msg, parent_key)] - while stack: - current_msg, current_parent_key = stack.pop() - if isinstance(current_msg, list): - for index, item in enumerate(current_msg): - new_key = f"{current_parent_key}/{index}" - if isinstance(item, (int, float)): - yield new_key, item - elif isinstance(item, dict): - stack.append((item, new_key)) - elif isinstance(current_msg, dict): - for key, value in current_msg.items(): - new_key = f"{current_parent_key}/{key}" - if isinstance(value, (int, float)): - yield new_key, value - elif isinstance(value, dict): - stack.append((value, new_key)) - elif isinstance(value, list): - for index, item in enumerate(value): - if isinstance(item, (int, float)): - yield f"{new_key}/{index}", item - else: - pass # Not a plottable value - - @staticmethod - @rr.shutdown_at_exit - def _process_log_msgs(blueprint, lr): - rr.init(RR_WIN) - rr.connect() - rr.send_blueprint(blueprint) - - log_msgs = defaultdict(lambda: defaultdict(list)) - for msg in lr: - msg_type = msg.which() - - if msg_type == "thumbnail": - continue - - for entity_path, dat in Rerunner._parse_msg(msg.to_dict()[msg_type], msg_type): - log_msgs[entity_path]["times"].append(msg.logMonoTime) - log_msgs[entity_path]["data"].append(dat) - - for entity_path, log_msg in log_msgs.items(): - rr.send_columns( - entity_path, - times=[rr.TimeNanosColumn(RR_TIMELINE_NAME, log_msg["times"])], - components=[rr.components.ScalarBatch(log_msg["data"])] - ) - - return [] - - @staticmethod - @rr.shutdown_at_exit - def _process_cam_readers(blueprint, cam_type, h, w, fr): - rr.init(RR_WIN) - rr.connect() - rr.send_blueprint(blueprint) - - for ts, frame in fr: - rr.set_time_nanos(RR_TIMELINE_NAME, int(ts * 1e9)) - rr.log(cam_type, rr.Image(bytes=frame, width=w, height=h, pixel_format=rr.PixelFormat.NV12)) - - def load_data(self): - rr.init(RR_WIN, spawn=True) - - startup_blueprint = self._create_blueprint() - self.lr.run_across_segments(NUM_CPUS, partial(self._process_log_msgs, startup_blueprint), desc="Log messages") - for cam_type, cr in self.camera_readers.items(): - cr.run_across_segments(NUM_CPUS, partial(self._process_cam_readers, startup_blueprint, cam_type, cr.h, cr.w), desc=cam_type) - - rr.send_blueprint(self._create_blueprint()) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser(description="A helper to run rerun on openpilot routes", - formatter_class=argparse.ArgumentDefaultsHelpFormatter) - parser.add_argument("--demo", action="store_true", help="Use the demo route instead of providing one") - parser.add_argument("--qcam", action="store_true", help="Show low-res road camera") - parser.add_argument("--fcam", action="store_true", help="Show driving camera") - parser.add_argument("--ecam", action="store_true", help="Show wide camera") - parser.add_argument("--dcam", action="store_true", help="Show driver monitoring camera") - parser.add_argument("route_or_segment_name", nargs='?', help="The route or segment name to plot") - args = parser.parse_args() - - if not args.demo and not args.route_or_segment_name: - parser.print_help() - sys.exit() - - camera_config = CameraConfig(args.qcam, args.fcam, args.ecam, args.dcam) - route_or_segment_name = DEMO_ROUTE if args.demo else args.route_or_segment_name.strip() - - sr = SegmentRange(route_or_segment_name) - r = Route(sr.route_name) - - hevc_requested = any(camera_config[1:]) - if len(sr.seg_idxs) > 1 and hevc_requested: - print("You're requesting more than 1 segment with hevc videos, " + \ - "please be aware that might take a lot of memory " + \ - "since rerun isn't yet well supported for high resolution video logging") - response = input("Do you wish to continue? (Y/n): ") - if response.strip().lower() != "y": - sys.exit() - - rerunner = Rerunner(r, sr, camera_config) - rerunner.load_data() - diff --git a/tools/scripts/__init__.py b/tools/scripts/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tools/scripts/adb_ssh.sh b/tools/scripts/adb_ssh.sh index 43c8e07de6..c584a72f2b 100755 --- a/tools/scripts/adb_ssh.sh +++ b/tools/scripts/adb_ssh.sh @@ -1,7 +1,42 @@ #!/usr/bin/env bash -set -e +set -euo pipefail -# this is a little nicer than "adb shell" since -# "adb shell" doesn't do full terminal emulation -adb forward tcp:2222 tcp:22 -ssh comma@localhost -p 2222 +# Forward all openpilot service ports +while IFS=' ' read -r name port; do + adb forward "tcp:${port}" "tcp:${port}" > /dev/null +done < <(python3 - <<'PY' +from openpilot.cereal.services import SERVICE_LIST + +FNV_PRIME = 0x100000001b3 +FNV_OFFSET_BASIS = 0xcbf29ce484222325 +START_PORT = 8023 +MAX_PORT = 65535 +PORT_RANGE = MAX_PORT - START_PORT +MASK = 0xffffffffffffffff + +def fnv1a(endpoint: str) -> int: + h = FNV_OFFSET_BASIS + for b in endpoint.encode(): + h ^= b + h = (h * FNV_PRIME) & MASK + return h + +ports = set() +for name in SERVICE_LIST.keys(): + port = START_PORT + fnv1a(name) % PORT_RANGE + ports.add((name, port)) + +for name, port in sorted(ports): + print(f"{name} {port}") +PY +) + +# Forward SSH port, finding a free local port if 2222 is taken. +SSH_PORT=2222 +while ss -tln | grep -q ":${SSH_PORT} "; do + SSH_PORT=$((SSH_PORT + 1)) +done +adb forward tcp:${SSH_PORT} tcp:22 + +# SSH! +ssh comma@localhost -p ${SSH_PORT} "$@" diff --git a/selfdrive/debug/can_print_changes.py b/tools/scripts/car/can_print_changes.py similarity index 97% rename from selfdrive/debug/can_print_changes.py rename to tools/scripts/car/can_print_changes.py index 97d60b2b05..e466cd2968 100755 --- a/selfdrive/debug/can_print_changes.py +++ b/tools/scripts/car/can_print_changes.py @@ -4,8 +4,8 @@ import binascii import time from collections import defaultdict -import cereal.messaging as messaging -from openpilot.selfdrive.debug.can_table import can_table +import openpilot.cereal.messaging as messaging +from tools.scripts.car.can_table import can_table from openpilot.tools.lib.logreader import LogIterable, LogReader RED = '\033[91m' diff --git a/selfdrive/debug/can_printer.py b/tools/scripts/car/can_printer.py similarity index 97% rename from selfdrive/debug/can_printer.py rename to tools/scripts/car/can_printer.py index f2ed6730d3..85f129f795 100755 --- a/selfdrive/debug/can_printer.py +++ b/tools/scripts/car/can_printer.py @@ -4,7 +4,7 @@ import binascii import time from collections import defaultdict -import cereal.messaging as messaging +import openpilot.cereal.messaging as messaging def can_printer(bus, max_msg, addr, ascii_decode): diff --git a/selfdrive/debug/can_table.py b/tools/scripts/car/can_table.py similarity index 96% rename from selfdrive/debug/can_table.py rename to tools/scripts/car/can_table.py index 11d070e708..e2d9874fec 100755 --- a/selfdrive/debug/can_table.py +++ b/tools/scripts/car/can_table.py @@ -2,7 +2,7 @@ import argparse import pandas as pd -import cereal.messaging as messaging +import openpilot.cereal.messaging as messaging def can_table(dat): diff --git a/selfdrive/debug/car/clear_dtc.py b/tools/scripts/car/clear_dtc.py similarity index 100% rename from selfdrive/debug/car/clear_dtc.py rename to tools/scripts/car/clear_dtc.py diff --git a/selfdrive/debug/car/disable_ecu.py b/tools/scripts/car/disable_ecu.py similarity index 91% rename from selfdrive/debug/car/disable_ecu.py rename to tools/scripts/car/disable_ecu.py index 14d0cbb9cf..884b86896b 100755 --- a/selfdrive/debug/car/disable_ecu.py +++ b/tools/scripts/car/disable_ecu.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 import time -import cereal.messaging as messaging +import openpilot.cereal.messaging as messaging from opendbc.car.disable_ecu import disable_ecu from openpilot.selfdrive.car.card import can_comm_callbacks diff --git a/selfdrive/debug/car/ecu_addrs.py b/tools/scripts/car/ecu_addrs.py similarity index 89% rename from selfdrive/debug/car/ecu_addrs.py rename to tools/scripts/car/ecu_addrs.py index 584c930ebf..0dfce880b0 100755 --- a/selfdrive/debug/car/ecu_addrs.py +++ b/tools/scripts/car/ecu_addrs.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 import argparse import time -import cereal.messaging as messaging +import openpilot.cereal.messaging as messaging from opendbc.car.carlog import carlog from opendbc.car.ecu_addrs import get_all_ecu_addrs from openpilot.common.params import Params @@ -26,9 +26,9 @@ if __name__ == "__main__": # Set up params for pandad params = Params() params.remove("FirmwareQueryDone") - params.put_bool("IsOnroad", False) + params.put_bool("IsOffroad", True, block=True) time.sleep(0.2) # thread is 10 Hz - params.put_bool("IsOnroad", True) + params.put_bool("IsOffroad", False, block=True) obd_callback(params)(not args.no_obd) diff --git a/selfdrive/debug/car/fw_versions.py b/tools/scripts/car/fw_versions.py similarity index 83% rename from selfdrive/debug/car/fw_versions.py rename to tools/scripts/car/fw_versions.py index 03d066cdcb..e68447d69e 100755 --- a/selfdrive/debug/car/fw_versions.py +++ b/tools/scripts/car/fw_versions.py @@ -1,8 +1,8 @@ #!/usr/bin/env python3 import time import argparse -import cereal.messaging as messaging -from cereal import car +import openpilot.cereal.messaging as messaging +from opendbc.car.structs import car from opendbc.car.carlog import carlog from opendbc.car.fw_versions import get_fw_versions, match_fw_to_car from opendbc.car.vin import get_vin @@ -30,9 +30,9 @@ if __name__ == "__main__": # Set up params for pandad params = Params() params.remove("FirmwareQueryDone") - params.put_bool("IsOnroad", False) + params.put_bool("IsOffroad", True, block=True) time.sleep(0.2) # thread is 10 Hz - params.put_bool("IsOnroad", True) + params.put_bool("IsOffroad", False, block=True) set_obd_multiplexing = obd_callback(params) extra: Any = None @@ -45,18 +45,16 @@ if __name__ == "__main__": extra[(Ecu.unknown, 0x750, i)] = [] extra = {"any": {"debug": extra}} - num_pandas = len(messaging.recv_one_retry(pandaStates_sock).pandaStates) - - t = time.time() + t = time.monotonic() print("Getting vin...") set_obd_multiplexing(True) vin_rx_addr, vin_rx_bus, vin = get_vin(*can_callbacks, (0, 1)) print(f'RX: {hex(vin_rx_addr)}, BUS: {vin_rx_bus}, VIN: {vin}') - print(f"Getting VIN took {time.time() - t:.3f} s") + print(f"Getting VIN took {time.monotonic() - t:.3f} s") print() - t = time.time() - fw_vers = get_fw_versions(*can_callbacks, set_obd_multiplexing, query_brand=args.brand, extra=extra, num_pandas=num_pandas, progress=True) + t = time.monotonic() + fw_vers = get_fw_versions(*can_callbacks, set_obd_multiplexing, query_brand=args.brand, extra=extra, progress=True) _, candidates = match_fw_to_car(fw_vers, vin) print() @@ -71,4 +69,4 @@ if __name__ == "__main__": print() print("Possible matches:", candidates) - print(f"Getting fw took {time.time() - t:.3f} s") + print(f"Getting fw took {time.monotonic() - t:.3f} s") diff --git a/selfdrive/debug/car/hyundai_enable_radar_points.py b/tools/scripts/car/hyundai_enable_radar_points.py similarity index 97% rename from selfdrive/debug/car/hyundai_enable_radar_points.py rename to tools/scripts/car/hyundai_enable_radar_points.py index 30e2949378..5fbd13f2b0 100755 --- a/selfdrive/debug/car/hyundai_enable_radar_points.py +++ b/tools/scripts/car/hyundai_enable_radar_points.py @@ -15,7 +15,6 @@ import sys import argparse from typing import NamedTuple from subprocess import check_output, CalledProcessError - from opendbc.car.carlog import carlog from opendbc.car.uds import UdsClient, SESSION_TYPE, DATA_IDENTIFIER_TYPE from opendbc.car.structs import CarParams @@ -108,11 +107,11 @@ if __name__ == "__main__": uds_client = UdsClient(panda, 0x7D0, bus=args.bus) print("\n[START DIAGNOSTIC SESSION]") - session_type : SESSION_TYPE = 0x07 # type: ignore + session_type : SESSION_TYPE = 0x07 uds_client.diagnostic_session_control(session_type) print("[HARDWARE/SOFTWARE VERSION]") - fw_version_data_id : DATA_IDENTIFIER_TYPE = 0xf100 # type: ignore + fw_version_data_id : DATA_IDENTIFIER_TYPE = 0xf100 fw_version = uds_client.read_data_by_identifier(fw_version_data_id) print(fw_version) if fw_version not in SUPPORTED_FW_VERSIONS.keys(): @@ -120,7 +119,7 @@ if __name__ == "__main__": sys.exit(1) print("[GET CONFIGURATION]") - config_data_id : DATA_IDENTIFIER_TYPE = 0x0142 # type: ignore + config_data_id : DATA_IDENTIFIER_TYPE = 0x0142 current_config = uds_client.read_data_by_identifier(config_data_id) config_values = SUPPORTED_FW_VERSIONS[fw_version] new_config = config_values.default_config if args.default else config_values.tracks_enabled diff --git a/selfdrive/debug/max_lat_accel.py b/tools/scripts/car/max_lat_accel.py similarity index 100% rename from selfdrive/debug/max_lat_accel.py rename to tools/scripts/car/max_lat_accel.py diff --git a/selfdrive/debug/measure_torque_time_to_max.py b/tools/scripts/car/measure_torque_time_to_max.py similarity index 95% rename from selfdrive/debug/measure_torque_time_to_max.py rename to tools/scripts/car/measure_torque_time_to_max.py index 7052dccf7d..df41e5738e 100755 --- a/selfdrive/debug/measure_torque_time_to_max.py +++ b/tools/scripts/car/measure_torque_time_to_max.py @@ -1,5 +1,4 @@ #!/usr/bin/env python3 -# type: ignore import os import argparse @@ -7,8 +6,8 @@ import struct from collections import deque from statistics import mean -from cereal import log -import cereal.messaging as messaging +from openpilot.cereal import log +import openpilot.cereal.messaging as messaging if __name__ == "__main__": diff --git a/selfdrive/debug/read_dtc_status.py b/tools/scripts/car/read_dtc_status.py similarity index 100% rename from selfdrive/debug/read_dtc_status.py rename to tools/scripts/car/read_dtc_status.py diff --git a/selfdrive/debug/car/toyota_eps_factor.py b/tools/scripts/car/toyota_eps_factor.py similarity index 100% rename from selfdrive/debug/car/toyota_eps_factor.py rename to tools/scripts/car/toyota_eps_factor.py diff --git a/selfdrive/debug/car/vin.py b/tools/scripts/car/vin.py similarity index 94% rename from selfdrive/debug/car/vin.py rename to tools/scripts/car/vin.py index 9b1d6528cc..732d3d3f4a 100755 --- a/selfdrive/debug/car/vin.py +++ b/tools/scripts/car/vin.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 import argparse import time -import cereal.messaging as messaging +import openpilot.cereal.messaging as messaging from opendbc.car.carlog import carlog from opendbc.car.vin import get_vin from openpilot.selfdrive.car.card import can_comm_callbacks diff --git a/selfdrive/debug/car/vw_mqb_config.py b/tools/scripts/car/vw_mqb_config.py similarity index 96% rename from selfdrive/debug/car/vw_mqb_config.py rename to tools/scripts/car/vw_mqb_config.py index 7ff5774a71..13ee7786d9 100755 --- a/selfdrive/debug/car/vw_mqb_config.py +++ b/tools/scripts/car/vw_mqb_config.py @@ -40,8 +40,7 @@ if __name__ == "__main__": panda = Panda() panda.set_safety_mode(CarParams.SafetyModel.elm327) - bus = 1 if panda.has_obd() else 0 - uds_client = UdsClient(panda, MQB_EPS_CAN_ADDR, MQB_EPS_CAN_ADDR + RX_OFFSET, bus, timeout=0.2) + uds_client = UdsClient(panda, MQB_EPS_CAN_ADDR, MQB_EPS_CAN_ADDR + RX_OFFSET, 1, timeout=0.2) try: uds_client.diagnostic_session_control(SESSION_TYPE.EXTENDED_DIAGNOSTIC) @@ -56,7 +55,7 @@ if __name__ == "__main__": sw_ver = uds_client.read_data_by_identifier(DATA_IDENTIFIER_TYPE.VEHICLE_MANUFACTURER_ECU_SOFTWARE_VERSION_NUMBER).decode("utf-8") component = uds_client.read_data_by_identifier(DATA_IDENTIFIER_TYPE.SYSTEM_NAME_OR_ENGINE_TYPE).decode("utf-8") odx_file = uds_client.read_data_by_identifier(DATA_IDENTIFIER_TYPE.ODX_FILE).decode("utf-8").rstrip('\x00') - current_coding = uds_client.read_data_by_identifier(VOLKSWAGEN_DATA_IDENTIFIER_TYPE.CODING) # type: ignore + current_coding = uds_client.read_data_by_identifier(VOLKSWAGEN_DATA_IDENTIFIER_TYPE.CODING) coding_text = current_coding.hex() print("\nEPS diagnostic data\n") @@ -127,9 +126,9 @@ if __name__ == "__main__": new_coding = current_coding[0:coding_byte] + new_byte.to_bytes(1, "little") + current_coding[coding_byte+1:] try: - seed = uds_client.security_access(ACCESS_TYPE_LEVEL_1.REQUEST_SEED) # type: ignore + seed = uds_client.security_access(ACCESS_TYPE_LEVEL_1.REQUEST_SEED) key = struct.unpack("!I", seed)[0] + 28183 # yeah, it's like that - uds_client.security_access(ACCESS_TYPE_LEVEL_1.SEND_KEY, struct.pack("!I", key)) # type: ignore + uds_client.security_access(ACCESS_TYPE_LEVEL_1.SEND_KEY, struct.pack("!I", key)) except (NegativeResponseError, MessageTimeoutError): print("Security access failed!") print("Open the hood and retry (disables the \"diagnostic firewall\" on newer vehicles)") @@ -149,7 +148,7 @@ if __name__ == "__main__": uds_client.write_data_by_identifier(DATA_IDENTIFIER_TYPE.PROGRAMMING_DATE, prog_date) tester_num = uds_client.read_data_by_identifier(DATA_IDENTIFIER_TYPE.CALIBRATION_REPAIR_SHOP_CODE_OR_CALIBRATION_EQUIPMENT_SERIAL_NUMBER) uds_client.write_data_by_identifier(DATA_IDENTIFIER_TYPE.REPAIR_SHOP_CODE_OR_TESTER_SERIAL_NUMBER, tester_num) - uds_client.write_data_by_identifier(VOLKSWAGEN_DATA_IDENTIFIER_TYPE.CODING, new_coding) # type: ignore + uds_client.write_data_by_identifier(VOLKSWAGEN_DATA_IDENTIFIER_TYPE.CODING, new_coding) except (NegativeResponseError, MessageTimeoutError): print("Writing new configuration failed!") print("Make sure the comma processes are stopped: tmux kill-session -t comma") @@ -157,7 +156,7 @@ if __name__ == "__main__": try: # Read back result just to make 100% sure everything worked - current_coding_text = uds_client.read_data_by_identifier(VOLKSWAGEN_DATA_IDENTIFIER_TYPE.CODING).hex() # type: ignore + current_coding_text = uds_client.read_data_by_identifier(VOLKSWAGEN_DATA_IDENTIFIER_TYPE.CODING).hex() print(f" New coding: {current_coding_text}") except (NegativeResponseError, MessageTimeoutError): print("Reading back updated coding failed!") diff --git a/selfdrive/debug/count_events.py b/tools/scripts/count_events.py similarity index 97% rename from selfdrive/debug/count_events.py rename to tools/scripts/count_events.py index 76e02d414e..a7e71210ac 100755 --- a/selfdrive/debug/count_events.py +++ b/tools/scripts/count_events.py @@ -6,7 +6,7 @@ from collections import Counter from pprint import pprint from typing import cast -from cereal.services import SERVICE_LIST +from openpilot.cereal.services import SERVICE_LIST from openpilot.tools.lib.logreader import LogReader, ReadMode from openpilot.selfdrive.test.process_replay.migration import migrate_all diff --git a/selfdrive/debug/cycle_alerts.py b/tools/scripts/cycle_alerts.py similarity index 91% rename from selfdrive/debug/cycle_alerts.py rename to tools/scripts/cycle_alerts.py index 11e75a7a8e..0bd42bcd3f 100755 --- a/selfdrive/debug/cycle_alerts.py +++ b/tools/scripts/cycle_alerts.py @@ -2,8 +2,9 @@ import time import random -from cereal import car, log -import cereal.messaging as messaging +from openpilot.cereal import log +from opendbc.car.structs import car +import openpilot.cereal.messaging as messaging from opendbc.car.honda.interface import CarInterface from openpilot.common.realtime import DT_CTRL from openpilot.selfdrive.selfdrived.events import ET, Events @@ -30,9 +31,9 @@ def cycle_alerts(duration=200, is_metric=False): (EventName.accFaulted, ET.IMMEDIATE_DISABLE), # DM sequence - (EventName.preDriverDistracted, ET.WARNING), - (EventName.promptDriverDistracted, ET.WARNING), - (EventName.driverDistracted, ET.WARNING), + (EventName.driverDistracted1, ET.WARNING), + (EventName.driverDistracted2, ET.WARNING), + (EventName.driverDistracted3, ET.WARNING), ] # debug alerts @@ -99,8 +100,7 @@ def cycle_alerts(duration=200, is_metric=False): alert = AM.process_alerts(frame, []) print(alert) for _ in range(duration): - dat = messaging.new_message() - dat.init('selfdriveState') + dat = messaging.new_message('selfdriveState') dat.selfdriveState.enabled = False if alert: @@ -112,8 +112,7 @@ def cycle_alerts(duration=200, is_metric=False): dat.selfdriveState.alertSound = alert.audible_alert pm.send('selfdriveState', dat) - dat = messaging.new_message() - dat.init('deviceState') + dat = messaging.new_message('deviceState') dat.deviceState.started = True pm.send('deviceState', dat) diff --git a/selfdrive/debug/debug_fw_fingerprinting_offline.py b/tools/scripts/debug_fw_fingerprinting_offline.py similarity index 97% rename from selfdrive/debug/debug_fw_fingerprinting_offline.py rename to tools/scripts/debug_fw_fingerprinting_offline.py index d841e91053..b33817e944 100755 --- a/selfdrive/debug/debug_fw_fingerprinting_offline.py +++ b/tools/scripts/debug_fw_fingerprinting_offline.py @@ -1,6 +1,5 @@ #!/usr/bin/env python3 import argparse - from opendbc.car import uds from openpilot.tools.lib.live_logreader import live_logreader from openpilot.tools.lib.logreader import LogReader, ReadMode @@ -44,7 +43,7 @@ if __name__ == "__main__": parser = argparse.ArgumentParser(description='View back and forth ISO-TP communication between various ECUs given an address') parser.add_argument('route', nargs='?', help='Route name, live if not specified') parser.add_argument('--addrs', nargs='*', default=[], help='List of tx address to view (0x7e0 for engine)') - parser.add_argument('--rxoffset', default='') + parser.add_argument('--rxoffset', default='0x8') args = parser.parse_args() addrs = [int(addr, base=16) if addr.startswith('0x') else int(addr) for addr in args.addrs] diff --git a/tools/scripts/devsync.py b/tools/scripts/devsync.py new file mode 100755 index 0000000000..98312dd545 --- /dev/null +++ b/tools/scripts/devsync.py @@ -0,0 +1,93 @@ +#!/usr/bin/env python3 +import argparse +import shlex +import subprocess +import threading +import time + +from watchdog.events import FileSystemEventHandler +from watchdog.observers import Observer + +from openpilot.common.basedir import BASEDIR + + +def build_rsync_cmd(args) -> list[str]: + ssh = [ + "ssh", + "-o", "ControlMaster=auto", + "-o", f"ControlPath=/tmp/devsync-{args.ip}.ctl", + "-o", "ControlPersist=10m", + "-o", "StrictHostKeyChecking=accept-new", + ] + if args.identity: + ssh += ["-i", args.identity] + + return [ + "rsync", "-az", + "--files-from=-", "--from0", + "-e", " ".join(shlex.quote(p) for p in ssh), + "--out-format=%n", + BASEDIR + "/", f"comma@{args.ip}:{args.remote}/", + ] + + +def git_tracked_files() -> bytes: + return subprocess.check_output( + ["git", "-C", BASEDIR, "ls-files", "--recurse-submodules", "-z"] + ) + + +class Handler(FileSystemEventHandler): + def __init__(self, sync_fn): + self.dirty = threading.Event() + self.sync_fn = sync_fn + + def on_any_event(self, event): + if not event.is_directory: + self.dirty.set() + + def run(self): + while True: + time.sleep(1) + if self.dirty.is_set(): + self.dirty.clear() + self.sync_fn() + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("ip", help="device IP / hostname") + p.add_argument("--remote", default="/data/openpilot", help="remote path on device") + p.add_argument("-i", "--identity", default=None, help="ssh identity file") + args = p.parse_args() + + print(f"[devsync] watching {BASEDIR}") + print(f"[devsync] target comma@{args.ip}:{args.remote}") + + def run_sync(): + file_list = git_tracked_files() + cmd = build_rsync_cmd(args) + t0 = time.monotonic() + r = subprocess.run(cmd, input=file_list, capture_output=True) + dt = time.monotonic() - t0 + if r.returncode: + print(f"[devsync] ERR rc={r.returncode} in {dt:.2f}s") + return + files = [ln for ln in r.stdout.decode().splitlines() if ln.strip()] + msg = f"{len(files)} files: {', '.join(files)}" if files else "no changes" + print(f"[devsync] {dt:.2f}s · {msg}") + + run_sync() + + handler = Handler(run_sync) + obs = Observer() + obs.schedule(handler, BASEDIR, recursive=True) + obs.start() + handler.run() + + +if __name__ == "__main__": + try: + main() + except KeyboardInterrupt: + print("\n[devsync] stopping") diff --git a/selfdrive/debug/dump.py b/tools/scripts/dump.py similarity index 93% rename from selfdrive/debug/dump.py rename to tools/scripts/dump.py index 78cf51e3db..e4f5495f9b 100755 --- a/selfdrive/debug/dump.py +++ b/tools/scripts/dump.py @@ -4,8 +4,8 @@ import argparse import json import codecs -from cereal import log -from cereal.services import SERVICE_LIST +from openpilot.cereal import log +from openpilot.cereal.services import SERVICE_LIST from openpilot.tools.lib.live_logreader import raw_live_logreader @@ -25,7 +25,7 @@ def hexdump(msg): if __name__ == "__main__": - parser = argparse.ArgumentParser(description='Dump communication sockets. See cereal/services.py for a complete list of available sockets.') + parser = argparse.ArgumentParser(description='Dump communication sockets. See openpilot/cereal/services.py for a complete list of available sockets.') parser.add_argument('--pipe', action='store_true') parser.add_argument('--raw', action='store_true') parser.add_argument('--json', action='store_true') diff --git a/tools/scripts/extract_audio.py b/tools/scripts/extract_audio.py new file mode 100755 index 0000000000..2a6ad9f9e3 --- /dev/null +++ b/tools/scripts/extract_audio.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python3 +import os +import sys +import wave +import argparse +import numpy as np + +from openpilot.tools.lib.logreader import LogReader, ReadMode + + +def extract_audio(route_or_segment_name, output_file=None, play=False): + lr = LogReader(route_or_segment_name, default_mode=ReadMode.AUTO_INTERACTIVE) + audio_messages = list(lr.filter("rawAudioData")) + if not audio_messages: + print("No rawAudioData messages found in logs") + return + sample_rate = audio_messages[0].sampleRate + + audio_chunks = [] + total_frames = 0 + for msg in audio_messages: + audio_array = np.frombuffer(msg.data, dtype=np.int16) + audio_chunks.append(audio_array) + total_frames += len(audio_array) + full_audio = np.concatenate(audio_chunks) + + print(f"Found {total_frames} frames from {len(audio_messages)} audio messages at {sample_rate} Hz") + + if output_file: + if write_wav_file(output_file, full_audio, sample_rate): + print(f"Audio written to {output_file}") + else: + print("Audio extraction canceled.") + if play: + play_audio(full_audio, sample_rate) + + +def write_wav_file(filename, audio_data, sample_rate): + if os.path.exists(filename): + if input(f"File '{filename}' exists. Overwrite? (y/N): ").lower() not in ['y', 'yes']: + return False + + with wave.open(filename, 'wb') as wav_file: + wav_file.setnchannels(1) # Mono + wav_file.setsampwidth(2) # 16-bit + wav_file.setframerate(sample_rate) + wav_file.writeframes(audio_data.tobytes()) + return True + + +def play_audio(audio_data, sample_rate): + try: + import sounddevice as sd + + print("Playing audio... Press Ctrl+C to stop") + sd.play(audio_data, sample_rate) + sd.wait() + except KeyboardInterrupt: + print("\nPlayback stopped") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Extract audio data from openpilot logs") + parser.add_argument("-o", "--output", help="Output WAV file path") + parser.add_argument("--play", action="store_true", help="Play audio with sounddevice") + parser.add_argument("route_or_segment_name", nargs='?', help="The route or segment name") + + if len(sys.argv) == 1: + parser.print_help() + sys.exit() + args = parser.parse_args() + + output_file = args.output + if not args.output and not args.play: + output_file = "extracted_audio.wav" + + extract_audio(args.route_or_segment_name.strip(), output_file, args.play) diff --git a/tools/scripts/fetch_image_from_route.py b/tools/scripts/fetch_image_from_route.py deleted file mode 100755 index 77bf48f946..0000000000 --- a/tools/scripts/fetch_image_from_route.py +++ /dev/null @@ -1,43 +0,0 @@ -#!/usr/bin/env python3 -import sys - -if len(sys.argv) < 4: - print(f"{sys.argv[0]} [front|wide|driver]") - print('example: ./fetch_image_from_route.py "02c45f73a2e5c6e9|2020-06-01--18-03-08" 3 500 driver') - exit(0) - -cameras = { - "front": "cameras", - "wide": "ecameras", - "driver": "dcameras" -} - -import requests -from PIL import Image -from openpilot.tools.lib.auth_config import get_token -from openpilot.tools.lib.framereader import FrameReader - -jwt = get_token() - -route = sys.argv[1] -segment = int(sys.argv[2]) -frame = int(sys.argv[3]) -camera = cameras[sys.argv[4]] if len(sys.argv) > 4 and sys.argv[4] in cameras else "cameras" - -url = f'https://api.commadotai.com/v1/route/{route}/files' -r = requests.get(url, headers={"Authorization": f"JWT {jwt}"}, timeout=10) -assert r.status_code == 200 -print("got api response") - -segments = r.json()[camera] -if segment >= len(segments): - raise Exception(f"segment {segment} not found, got {len(segments)} segments") - -fr = FrameReader(segments[segment]) -if frame >= fr.frame_count: - raise Exception("frame {frame} not found, got {fr.frame_count} frames") - -im = Image.fromarray(fr.get(frame)) -fn = f"uxxx_{route.replace('|', '_')}_{segment}_{frame}.png" -im.save(fn) -print(f"saved {fn}") diff --git a/selfdrive/debug/filter_log_message.py b/tools/scripts/filter_log_message.py similarity index 77% rename from selfdrive/debug/filter_log_message.py rename to tools/scripts/filter_log_message.py index 9cbab0b41f..1ec0333169 100755 --- a/selfdrive/debug/filter_log_message.py +++ b/tools/scripts/filter_log_message.py @@ -2,7 +2,7 @@ import argparse import json -import cereal.messaging as messaging +import openpilot.cereal.messaging as messaging from openpilot.tools.lib.logreader import LogReader LEVELS = { @@ -13,7 +13,7 @@ LEVELS = { "CRITICAL": 50, } -ANDROID_LOG_SOURCE = { +OPERATING_SYSTEM_LOG_SOURCE = { 0: "MAIN", 1: "RADIO", 2: "EVENTS", @@ -34,8 +34,8 @@ def print_logmessage(t, msg, min_level): print(f"[{t / 1e9:.6f}] decode error: {msg}") -def print_androidlog(t, msg): - source = ANDROID_LOG_SOURCE[msg.id] +def print_operating_system_log(t, msg): + source = msg.tag or OPERATING_SYSTEM_LOG_SOURCE.get(msg.id, "SYSTEM") try: m = json.loads(msg.message)['MESSAGE'] except Exception: @@ -65,15 +65,15 @@ if __name__ == "__main__": print_logmessage(m.logMonoTime-st, m.logMessage, min_level) elif m.which() == 'errorLogMessage': print_logmessage(m.logMonoTime-st, m.errorLogMessage, min_level) - elif m.which() == 'androidLog': - print_androidlog(m.logMonoTime-st, m.androidLog) + elif m.which() == 'operatingSystemLog': + print_operating_system_log(m.logMonoTime-st, m.operatingSystemLog) else: - sm = messaging.SubMaster(['logMessage', 'androidLog'], addr=args.addr) + sm = messaging.SubMaster(['logMessage', 'operatingSystemLog'], addr=args.addr) while True: sm.update() if sm.updated['logMessage']: print_logmessage(sm.logMonoTime['logMessage'], sm['logMessage'], min_level) - if sm.updated['androidLog']: - print_androidlog(sm.logMonoTime['androidLog'], sm['androidLog']) + if sm.updated['operatingSystemLog']: + print_operating_system_log(sm.logMonoTime['operatingSystemLog'], sm['operatingSystemLog']) diff --git a/selfdrive/debug/fingerprint_from_route.py b/tools/scripts/fingerprint_from_route.py similarity index 84% rename from selfdrive/debug/fingerprint_from_route.py rename to tools/scripts/fingerprint_from_route.py index 179ff4c838..5fd46f5b76 100755 --- a/selfdrive/debug/fingerprint_from_route.py +++ b/tools/scripts/fingerprint_from_route.py @@ -28,11 +28,12 @@ def get_fingerprint(lr): # TODO: also print the fw fingerprint merged with the existing ones # show FW fingerprint - print("\nFW fingerprint:\n") - for f in fw: - print(f" (Ecu.{f.ecu}, {hex(f.address)}, {None if f.subAddress == 0 else f.subAddress}): [") - print(f" {f.fwVersion},") - print(" ],") + if fw: + print("\nFW fingerprint:\n") + for f in fw: + print(f" (Ecu.{f.ecu}, {hex(f.address)}, {None if f.subAddress == 0 else f.subAddress}): [") + print(f" {f.fwVersion},") + print(" ],") print() print(f"VIN: {vin}") diff --git a/selfdrive/debug/fuzz_fw_fingerprint.py b/tools/scripts/fuzz_fw_fingerprint.py similarity index 98% rename from selfdrive/debug/fuzz_fw_fingerprint.py rename to tools/scripts/fuzz_fw_fingerprint.py index fa99e6bfbe..5b0ba9cfd0 100755 --- a/selfdrive/debug/fuzz_fw_fingerprint.py +++ b/tools/scripts/fuzz_fw_fingerprint.py @@ -1,10 +1,8 @@ #!/usr/bin/env python3 -# type: ignore import random from collections import defaultdict from tqdm import tqdm - from opendbc.car.fw_versions import match_fw_to_car_fuzzy from opendbc.car.toyota.values import FW_VERSIONS as TOYOTA_FW_VERSIONS from opendbc.car.honda.values import FW_VERSIONS as HONDA_FW_VERSIONS diff --git a/selfdrive/debug/get_fingerprint.py b/tools/scripts/get_fingerprint.py similarity index 91% rename from selfdrive/debug/get_fingerprint.py rename to tools/scripts/get_fingerprint.py index 75c3d5579f..1e5e8eca5a 100755 --- a/selfdrive/debug/get_fingerprint.py +++ b/tools/scripts/get_fingerprint.py @@ -4,13 +4,13 @@ # Instructions: # - connect to a Panda -# - run selfdrive/pandad/pandad +# - run openpilot/selfdrive/pandad/pandad # - launching this script # Note: it's very important that the car is in stock mode, in order to collect a complete fingerprint # - since some messages are published at low frequency, keep this script running for at least 30s, # until all messages are received at least once -import cereal.messaging as messaging +import openpilot.cereal.messaging as messaging logcan = messaging.sub_sock('can') msgs = {} diff --git a/selfdrive/debug/live_cpu_and_temp.py b/tools/scripts/live_cpu_and_temp.py similarity index 98% rename from selfdrive/debug/live_cpu_and_temp.py rename to tools/scripts/live_cpu_and_temp.py index ee0524ec9d..484207d0fe 100755 --- a/selfdrive/debug/live_cpu_and_temp.py +++ b/tools/scripts/live_cpu_and_temp.py @@ -4,7 +4,7 @@ import numpy as np import capnp from collections import defaultdict -from cereal.messaging import SubMaster +from openpilot.cereal.messaging import SubMaster def cputime_total(ct): return ct.user + ct.nice + ct.system + ct.idle + ct.iowait + ct.irq + ct.softirq diff --git a/tools/scripts/mem_usage.py b/tools/scripts/mem_usage.py new file mode 100755 index 0000000000..9b13a56ce2 --- /dev/null +++ b/tools/scripts/mem_usage.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python3 +import argparse +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) + +from openpilot.selfdrive.test.mem_usage import DEMO_ROUTE, print_report +from openpilot.tools.lib.logreader import LogReader + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Analyze memory usage from route logs") + parser.add_argument("route", nargs="?", default=None, help="route ID or local rlog path") + parser.add_argument("--demo", action="store_true", help=f"use demo route ({DEMO_ROUTE})") + args = parser.parse_args() + + if args.demo: + route = DEMO_ROUTE + elif args.route: + route = args.route + else: + parser.error("provide a route or use --demo") + + print(f"Reading logs from: {route}") + + proc_logs = [] + device_states = [] + for msg in LogReader(route): + if msg.which() == 'procLog': + proc_logs.append(msg) + elif msg.which() == 'deviceState': + device_states.append(msg) + + print_report(proc_logs, device_states) diff --git a/selfdrive/debug/print_flags.py b/tools/scripts/print_flags.py similarity index 100% rename from selfdrive/debug/print_flags.py rename to tools/scripts/print_flags.py diff --git a/tools/profiling/clpeak/.gitignore b/tools/scripts/profiling/clpeak/.gitignore similarity index 100% rename from tools/profiling/clpeak/.gitignore rename to tools/scripts/profiling/clpeak/.gitignore diff --git a/tools/profiling/clpeak/build.sh b/tools/scripts/profiling/clpeak/build.sh similarity index 100% rename from tools/profiling/clpeak/build.sh rename to tools/scripts/profiling/clpeak/build.sh diff --git a/tools/profiling/clpeak/no_print.patch b/tools/scripts/profiling/clpeak/no_print.patch similarity index 100% rename from tools/profiling/clpeak/no_print.patch rename to tools/scripts/profiling/clpeak/no_print.patch diff --git a/tools/profiling/clpeak/run_continuously.patch b/tools/scripts/profiling/clpeak/run_continuously.patch similarity index 100% rename from tools/profiling/clpeak/run_continuously.patch rename to tools/scripts/profiling/clpeak/run_continuously.patch diff --git a/tools/profiling/ftrace.sh b/tools/scripts/profiling/ftrace.sh similarity index 100% rename from tools/profiling/ftrace.sh rename to tools/scripts/profiling/ftrace.sh diff --git a/tools/profiling/palanteer/.gitignore b/tools/scripts/profiling/palanteer/.gitignore similarity index 100% rename from tools/profiling/palanteer/.gitignore rename to tools/scripts/profiling/palanteer/.gitignore diff --git a/tools/profiling/palanteer/setup.sh b/tools/scripts/profiling/palanteer/setup.sh similarity index 100% rename from tools/profiling/palanteer/setup.sh rename to tools/scripts/profiling/palanteer/setup.sh diff --git a/tools/profiling/perfetto/.gitignore b/tools/scripts/profiling/perfetto/.gitignore similarity index 100% rename from tools/profiling/perfetto/.gitignore rename to tools/scripts/profiling/perfetto/.gitignore diff --git a/tools/profiling/perfetto/build.sh b/tools/scripts/profiling/perfetto/build.sh similarity index 100% rename from tools/profiling/perfetto/build.sh rename to tools/scripts/profiling/perfetto/build.sh diff --git a/tools/profiling/perfetto/copy.sh b/tools/scripts/profiling/perfetto/copy.sh similarity index 100% rename from tools/profiling/perfetto/copy.sh rename to tools/scripts/profiling/perfetto/copy.sh diff --git a/tools/profiling/perfetto/record.sh b/tools/scripts/profiling/perfetto/record.sh similarity index 100% rename from tools/profiling/perfetto/record.sh rename to tools/scripts/profiling/perfetto/record.sh diff --git a/tools/profiling/perfetto/server.sh b/tools/scripts/profiling/perfetto/server.sh similarity index 100% rename from tools/profiling/perfetto/server.sh rename to tools/scripts/profiling/perfetto/server.sh diff --git a/tools/profiling/perfetto/traces.sh b/tools/scripts/profiling/perfetto/traces.sh similarity index 100% rename from tools/profiling/perfetto/traces.sh rename to tools/scripts/profiling/perfetto/traces.sh diff --git a/tools/profiling/py-spy/profile.sh b/tools/scripts/profiling/py-spy/profile.sh similarity index 100% rename from tools/profiling/py-spy/profile.sh rename to tools/scripts/profiling/py-spy/profile.sh diff --git a/tools/profiling/snapdragon/.gitignore b/tools/scripts/profiling/snapdragon/.gitignore similarity index 100% rename from tools/profiling/snapdragon/.gitignore rename to tools/scripts/profiling/snapdragon/.gitignore diff --git a/tools/scripts/profiling/snapdragon/README.md b/tools/scripts/profiling/snapdragon/README.md new file mode 100644 index 0000000000..383d83ba9b --- /dev/null +++ b/tools/scripts/profiling/snapdragon/README.md @@ -0,0 +1,13 @@ +snapdragon profiler +-------- + + +* download from https://developer.qualcomm.com/software/snapdragon-profiler/tools-archive (need a qc developer account) + * choose v2021.5 (verified working with 24.04 dev environment) +* unzip to openpilot/selfdrive/debug/profiling/snapdragon/SnapdragonProfiler +* run ```./setup-profiler.sh``` +* run ```./setup-agnos.sh``` +* run ```openpilot/selfdrive/debug/adb.sh``` on device +* run the ```adb connect xxx``` command that was given to you on local pc +* cd to SnapdragonProfiler and run ```./run_sdp.sh``` +* connect to device -> choose device you just setup diff --git a/tools/profiling/snapdragon/setup-agnos.sh b/tools/scripts/profiling/snapdragon/setup-agnos.sh similarity index 100% rename from tools/profiling/snapdragon/setup-agnos.sh rename to tools/scripts/profiling/snapdragon/setup-agnos.sh diff --git a/tools/profiling/snapdragon/setup-profiler.sh b/tools/scripts/profiling/snapdragon/setup-profiler.sh similarity index 100% rename from tools/profiling/snapdragon/setup-profiler.sh rename to tools/scripts/profiling/snapdragon/setup-profiler.sh diff --git a/tools/profiling/watch-irqs.sh b/tools/scripts/profiling/watch-irqs.sh similarity index 100% rename from tools/profiling/watch-irqs.sh rename to tools/scripts/profiling/watch-irqs.sh diff --git a/selfdrive/debug/qlog_size.py b/tools/scripts/qlog_size.py similarity index 96% rename from selfdrive/debug/qlog_size.py rename to tools/scripts/qlog_size.py index 6d494b6f75..46ef4b8be0 100755 --- a/selfdrive/debug/qlog_size.py +++ b/tools/scripts/qlog_size.py @@ -5,8 +5,8 @@ from collections import defaultdict import matplotlib.pyplot as plt -from cereal.services import SERVICE_LIST -from openpilot.common.file_helpers import LOG_COMPRESSION_LEVEL +from openpilot.cereal.services import SERVICE_LIST +from openpilot.common.utils import LOG_COMPRESSION_LEVEL from openpilot.tools.lib.logreader import LogReader from tqdm import tqdm diff --git a/tools/scripts/run_process_on_route.py b/tools/scripts/run_process_on_route.py new file mode 100755 index 0000000000..d6743fedcb --- /dev/null +++ b/tools/scripts/run_process_on_route.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 +import argparse + +from openpilot.selfdrive.test.process_replay.process_replay import CONFIGS, replay_process +from openpilot.selfdrive.test.process_replay.test_processes import EXCLUDED_PROCS +from openpilot.tools.lib.logreader import LogReader, save_log + +ALLOW_PROCS = {c.proc_name for c in CONFIGS} + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Run process on route and create new logs", + formatter_class=argparse.ArgumentDefaultsHelpFormatter) + parser.add_argument("route", help="The route name to use") + parser.add_argument("--fingerprint", help="The fingerprint to use") + parser.add_argument("--whitelist-procs", nargs='*', default=ALLOW_PROCS, help="Whitelist given processes (e.g. controlsd)") + parser.add_argument("--blacklist-procs", nargs='*', default=EXCLUDED_PROCS, help="Blacklist given processes (e.g. controlsd)") + args = parser.parse_args() + + allowed_procs = set(args.whitelist_procs) - set(args.blacklist_procs) + cfgs = [c for c in CONFIGS if c.proc_name in allowed_procs] + + inputs = list(LogReader(args.route)) + outputs = replay_process(cfgs, inputs, fingerprint=args.fingerprint) + + # Remove message generated by the process under test and merge in the new messages + produces = {o.which() for o in outputs} + inputs = [i for i in inputs if i.which() not in produces] + outputs = sorted(inputs + outputs, key=lambda x: x.logMonoTime) + + fn = f"{args.route.replace('/', '_')}_{'_'.join(allowed_procs)}.zst" + print(f"Saving log to {fn}") + save_log(fn, outputs) diff --git a/tools/scripts/save_ubloxraw_stream.py b/tools/scripts/save_ubloxraw_stream.py deleted file mode 100755 index b5354a7831..0000000000 --- a/tools/scripts/save_ubloxraw_stream.py +++ /dev/null @@ -1,47 +0,0 @@ -#!/usr/bin/env python3 -import argparse -import os -import sys -from openpilot.common.basedir import BASEDIR -from openpilot.tools.lib.logreader import LogReader - -os.environ['BASEDIR'] = BASEDIR - - -def get_arg_parser(): - parser = argparse.ArgumentParser( - description="Unlogging and save to file", - formatter_class=argparse.ArgumentDefaultsHelpFormatter) - - parser.add_argument("route", type=(lambda x: x.replace("#", "|")), nargs="?", - help="The route whose messages will be published.") - parser.add_argument("--out_path", nargs='?', default='/data/ubloxRaw.stream', - help="Output pickle file path") - return parser - - -def main(): - args = get_arg_parser().parse_args(sys.argv[1:]) - - lr = LogReader(args.route) - - with open(args.out_path, 'wb') as f: - try: - done = False - i = 0 - while not done: - msg = next(lr) - if not msg: - break - smsg = msg.as_builder() - typ = smsg.which() - if typ == 'ubloxRaw': - f.write(smsg.to_bytes()) - i += 1 - except StopIteration: - print('All done') - print(f'Writed {i} msgs') - - -if __name__ == "__main__": - main() diff --git a/selfdrive/debug/set_car_params.py b/tools/scripts/set_car_params.py similarity index 88% rename from selfdrive/debug/set_car_params.py rename to tools/scripts/set_car_params.py index aec30b4d74..3864de0838 100755 --- a/selfdrive/debug/set_car_params.py +++ b/tools/scripts/set_car_params.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 import sys -from cereal import car +from opendbc.car.structs import car from openpilot.common.params import Params from openpilot.tools.lib.route import Route from openpilot.tools.lib.logreader import LogReader @@ -19,4 +19,4 @@ if __name__ == "__main__": cp_bytes = CP.to_bytes() for p in ("CarParams", "CarParamsCache", "CarParamsPersistent"): - Params().put(p, cp_bytes) + Params().put(p, cp_bytes, block=True) diff --git a/tools/scripts/setup_ssh_keys.py b/tools/scripts/setup_ssh_keys.py index 45dc0aa977..e599dd3c5d 100755 --- a/tools/scripts/setup_ssh_keys.py +++ b/tools/scripts/setup_ssh_keys.py @@ -15,9 +15,9 @@ if __name__ == "__main__": if keys.status_code == 200: params = Params() - params.put_bool("SshEnabled", True) - params.put("GithubSshKeys", keys.text) - params.put("GithubUsername", username) + params.put_bool("SshEnabled", True, block=True) + params.put("GithubSshKeys", keys.text, block=True) + params.put("GithubUsername", username, block=True) print("Set up ssh keys successfully") else: print("Error getting public keys from github") diff --git a/tools/scripts/ssh.py b/tools/scripts/ssh.py new file mode 100755 index 0000000000..86e86c7eed --- /dev/null +++ b/tools/scripts/ssh.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +import os +import sys +import argparse +import re + +from openpilot.common.basedir import BASEDIR +from openpilot.tools.lib.auth_config import get_token +from openpilot.tools.lib.api import CommaApi + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="A helper for connecting to devices over the comma prime SSH proxy.\ + Adding your SSH key to your SSH config is recommended for more convenient use; see https://docs.comma.ai/how-to/connect-to-comma/.") + parser.add_argument("device", help="device name or dongle id") + parser.add_argument("--host", help="ssh jump server host", default="ssh.comma.ai") + parser.add_argument("--port", help="ssh jump server port", default=22, type=int) + parser.add_argument("--key", help="ssh key", default=os.path.join(BASEDIR, "openpilot/common/hardware/tici/id_rsa")) + parser.add_argument("--debug", help="enable debug output", action="store_true") + args = parser.parse_args() + + r = CommaApi(get_token()).get("v1/me/devices") + devices = {x['dongle_id']: x['alias'] for x in r} + + if not re.match("[0-9a-zA-Z]{16}", args.device): + user_input = args.device.replace(" ", "").lower() + matches = { k: v for k, v in devices.items() if isinstance(v, str) and user_input in v.replace(" ", "").lower() } + if len(matches) == 1: + dongle_id = list(matches.keys())[0] + else: + print(f"failed to look up dongle id for \"{args.device}\"", file=sys.stderr) + if len(matches) > 1: + print("found multiple matches:", file=sys.stderr) + for k, v in matches.items(): + print(f" \"{v}\" ({k})", file=sys.stderr) + exit(1) + else: + dongle_id = args.device + + name = dongle_id + if dongle_id in devices: + name = f"{devices[dongle_id]} ({dongle_id})" + print(f"connecting to {name} through {args.host}:{args.port} ...") + + command = [ + "ssh", + "-i", args.key, + "-o", f"ProxyCommand=ssh -i {args.key} -W %h:%p -p %p %h@{args.host}", + "-p", str(args.port), + ] + if args.debug: + command += ["-v"] + command += [ + f"comma@comma-{dongle_id}", + ] + if args.debug: + print(" ".join([f"'{c}'" if " " in c else c for c in command])) + os.execvp(command[0], command) diff --git a/selfdrive/debug/test_fw_query_on_routes.py b/tools/scripts/test_fw_query_on_routes.py similarity index 99% rename from selfdrive/debug/test_fw_query_on_routes.py rename to tools/scripts/test_fw_query_on_routes.py index 1216b7299f..ab539e4feb 100755 --- a/selfdrive/debug/test_fw_query_on_routes.py +++ b/tools/scripts/test_fw_query_on_routes.py @@ -1,5 +1,4 @@ #!/usr/bin/env python3 -# type: ignore from collections import defaultdict import argparse diff --git a/selfdrive/debug/uiview.py b/tools/scripts/uiview.py similarity index 79% rename from selfdrive/debug/uiview.py rename to tools/scripts/uiview.py index ad3ccea036..f28ba3b2ec 100755 --- a/selfdrive/debug/uiview.py +++ b/tools/scripts/uiview.py @@ -1,18 +1,17 @@ #!/usr/bin/env python3 import time -from cereal import car, log, messaging +from openpilot.cereal import log, messaging +from opendbc.car.structs import car from openpilot.common.params import Params -from openpilot.system.manager.process_config import managed_processes, is_snpe_model, is_tinygrad_model, is_stock_model -from openpilot.system.hardware import HARDWARE +from openpilot.system.manager.process_config import managed_processes, is_tinygrad_model, is_stock_model +from openpilot.common.hardware import HARDWARE if __name__ == "__main__": CP = car.CarParams(notCar=True, wheelbase=1, steerRatio=10) params = Params() - params.put("CarParams", CP.to_bytes()) + params.put("CarParams", CP.to_bytes(), block=True) - if use_snpe_modeld := is_snpe_model(False, params, CP): - print("Using SNPE modeld") if use_tinygrad_modeld := is_tinygrad_model(False, params, CP): print("Using TinyGrad modeld") if use_stock_modeld := is_stock_model(False, params, CP): @@ -21,7 +20,7 @@ if __name__ == "__main__": HARDWARE.set_power_save(False) procs = ['camerad', 'ui', 'calibrationd', 'plannerd', 'dmonitoringmodeld', 'dmonitoringd'] - procs += ["modeld_snpe" if use_snpe_modeld else "modeld_tinygrad" if use_tinygrad_modeld else "modeld"] + procs += ["modeld_tinygrad" if use_tinygrad_modeld else "modeld"] for p in procs: managed_processes[p].start() diff --git a/tools/scripts/watch_timings.py b/tools/scripts/watch_timings.py new file mode 100755 index 0000000000..0df9db2033 --- /dev/null +++ b/tools/scripts/watch_timings.py @@ -0,0 +1,102 @@ +#!/usr/bin/env python3 +import argparse +import datetime +import time +from collections import deque +from dataclasses import dataclass, field + +import numpy as np + +import openpilot.cereal.messaging as messaging +from openpilot.cereal.services import SERVICE_LIST + + +@dataclass +class ServiceTiming: + times: list[float] = field(default_factory=list) + window: deque[float] = field(default_factory=lambda: deque(maxlen=100)) + valids: deque[bool] = field(default_factory=lambda: deque(maxlen=100)) + lag_events: list[tuple[float, float]] = field(default_factory=list) + + def add(self, mono_time: float, valid: bool, expected_interval: float | None, lag_threshold: float) -> None: + if self.times: + dt = mono_time - self.times[-1] + self.window.append(dt) + if expected_interval is not None and dt > lag_threshold * expected_interval: + self.lag_events.append((mono_time, dt)) + + self.times.append(mono_time) + self.valids.append(valid) + + def intervals(self, latest_only: bool) -> np.ndarray: + if latest_only: + return np.array(self.window) + return np.diff(self.times) + + +def format_row(name: str, timing: ServiceTiming, latest_only: bool) -> str: + dts = timing.intervals(latest_only) + if len(dts) == 0: + return f"{name:25} waiting for messages" + + mean = np.mean(dts) + hz = 1.0 / mean if mean > 0 else 0.0 + valid = all(timing.valids) if timing.valids else False + return f"{name:25} {hz:8.2f}Hz {mean * 1e3:8.2f}ms {np.std(dts) * 1e3:8.2f}ms {np.max(dts) * 1e3:8.2f}ms {np.min(dts) * 1e3:8.2f}ms valid={valid}" + + +def print_lag_events(name: str, timing: ServiceTiming, printed_lags: dict[str, int]) -> None: + start = printed_lags.get(name, 0) + for mono_time, dt in timing.lag_events[start:]: + print(f"{mono_time:.3f} {name} lag {dt:.3f}s", flush=True) + printed_lags[name] = len(timing.lag_events) + + +def monitor_services(socket_names: list[str], print_interval: float, lag_threshold: float, lag_only: bool) -> None: + sockets = {name: messaging.sub_sock(name, conflate=False) for name in socket_names} + timings = {name: ServiceTiming() for name in socket_names} + printed_lags: dict[str, int] = {} + + start_time = time.monotonic() + last_print = start_time + + try: + while True: + for name, sock in sockets.items(): + for msg in messaging.drain_sock(sock): + expected_interval = 1.0 / SERVICE_LIST[name].frequency if name in SERVICE_LIST else None + timings[name].add(msg.logMonoTime / 1e9, msg.valid, expected_interval, lag_threshold) + + now = time.monotonic() + if now - last_print < print_interval: + time.sleep(0.01) + continue + + if not lag_only: + print(flush=True) + print(f"{'service':25} {'freq':>10} {'mean':>10} {'std':>10} {'max':>10} {'min':>10} valid", flush=True) + for name in socket_names: + print(format_row(name, timings[name], latest_only=True), flush=True) + + for name in socket_names: + print_lag_events(name, timings[name], printed_lags) + + last_print = now + except KeyboardInterrupt: + print("\n", flush=True) + print("=" * 5, "timing summary", "=" * 5, flush=True) + print(f"{'service':25} {'freq':>10} {'mean':>10} {'std':>10} {'max':>10} {'min':>10} valid", flush=True) + for name in socket_names: + print(format_row(name, timings[name], latest_only=False), flush=True) + print("=" * 5, datetime.timedelta(seconds=time.monotonic() - start_time), "=" * 5, flush=True) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Check live service timing, frequency, validity, and lag") + parser.add_argument("socket", nargs="*", default=["carState"], help="service/socket name") + parser.add_argument("--lag-threshold", type=float, default=10.0, help="report intervals above this multiple of the expected service interval") + parser.add_argument("--lag-only", action="store_true", help="only print lag events") + parser.add_argument("--print-interval", type=float, default=1.0, help="seconds between table updates") + args = parser.parse_args() + + monitor_services(args.socket, args.print_interval, args.lag_threshold, args.lag_only) diff --git a/tools/setup.sh b/tools/setup.sh index e0a9a4f6a6..dafd466ef9 100755 --- a/tools/setup.sh +++ b/tools/setup.sh @@ -1,6 +1,5 @@ #!/usr/bin/env bash - -set -e +set -euo pipefail RED='\033[0;31m' GREEN='\033[0;32m' @@ -34,39 +33,6 @@ cat << 'EOF' EOF } -function sentry_send_event() { - SENTRY_KEY=dd0cba62ba0ac07ff9f388f8f1e6a7f4 - SENTRY_URL=https://sentry.io/api/4507726145781760/store/ - - EVENT=$1 - EVENT_TYPE=${2:-$EVENT} - EVENT_LOG=${3:-"NA"} - - PLATFORM=$(uname -s) - ARCH=$(uname -m) - SYSTEM=$(uname -a) - if [[ $PLATFORM == "Darwin" ]]; then - OS="macos" - elif [[ $PLATFORM == "Linux" ]]; then - OS="linux" - fi - - if [[ $ARCH == armv8* ]] || [[ $ARCH == arm64* ]] || [[ $ARCH == aarch64* ]]; then - ARCH="aarch64" - elif [[ $ARCH == "x86_64" ]] || [[ $ARCH == i686* ]]; then - ARCH="x86" - fi - - PYTHON_VERSION=$(echo $(python3 --version 2> /dev/null || echo "NA")) - BRANCH=$(echo $(git -C $OPENPILOT_ROOT rev-parse --abbrev-ref HEAD 2> /dev/null || echo "NA")) - COMMIT=$(echo $(git -C $OPENPILOT_ROOT rev-parse HEAD 2> /dev/null || echo "NA")) - - curl -s -o /dev/null -X POST -g --data "{ \"exception\": { \"values\": [{ \"type\": \"$EVENT\" }] }, \"tags\" : { \"event_type\" : \"$EVENT_TYPE\", \"event_log\" : \"$EVENT_LOG\", \"os\" : \"$OS\", \"arch\" : \"$ARCH\", \"python_version\" : \"$PYTHON_VERSION\" , \"git_branch\" : \"$BRANCH\", \"git_commit\" : \"$COMMIT\", \"system\" : \"$SYSTEM\" } }" \ - -H 'Content-Type: application/json' \ - -H "X-Sentry-Auth: Sentry sentry_version=7, sentry_key=$SENTRY_KEY, sentry_client=op_setup/0.1" \ - $SENTRY_URL 2> /dev/null -} - function check_stdin() { if [ -t 0 ]; then INTERACTIVE=1 @@ -132,7 +98,6 @@ function check_git() { echo "Checking for git..." if ! command -v "git" > /dev/null 2>&1; then echo -e " ↳ [${RED}✗${NC}] git not found on your system, can't continue!" - sentry_send_event "SETUP_FAILURE" "ERROR_GIT_NOT_FOUND" return 1 else echo -e " ↳ [${GREEN}✔${NC}] git found.\n" @@ -151,7 +116,6 @@ function git_clone() { fi echo -e " ↳ [${RED}✗${NC}] failed to clone openpilot!" - sentry_send_event "SETUP_FAILURE" "ERROR_GIT_CLONE" return 1 } @@ -160,18 +124,9 @@ function install_with_op() { $OPENPILOT_ROOT/tools/op.sh install $OPENPILOT_ROOT/tools/op.sh post-commit - LOG_FILE=$(mktemp) - - if ! $OPENPILOT_ROOT/tools/op.sh --log $LOG_FILE setup; then + if ! $OPENPILOT_ROOT/tools/op.sh setup; then echo -e "\n[${RED}✗${NC}] failed to install openpilot!" - - ERROR_TYPE="$(cat "$LOG_FILE" | sed '1p;d')" - ERROR_LOG="$(cat "$LOG_FILE" | sed '2p;d')" - sentry_send_event "SETUP_FAILURE" "$ERROR_TYPE" "$ERROR_LOG" || true - return 1 - else - sentry_send_event "SETUP_SUCCESS" || true fi echo -e "\n----------------------------------------------------------------------" diff --git a/tools/setup_dependencies.sh b/tools/setup_dependencies.sh new file mode 100755 index 0000000000..b76fdc7dde --- /dev/null +++ b/tools/setup_dependencies.sh @@ -0,0 +1,138 @@ +#!/usr/bin/env bash +set -e + +DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )" +ROOT="$(git -C "$DIR" rev-parse --show-toplevel)" + +function retry() { + local attempts=$1 + shift + for i in $(seq 1 "$attempts"); do + if "$@"; then + return 0 + fi + if [ "$i" -lt "$attempts" ]; then + echo " Attempt $i/$attempts failed, retrying in 5s..." + sleep 5 + fi + done + return 1 +} + +function install_linux_deps() { + SUDO="" + + if [[ ! $(id -u) -eq 0 ]]; then + if [[ -z $(which sudo) ]]; then + echo "Please install sudo or run as root" + exit 1 + fi + SUDO="sudo" + fi + + local missing_linux_deps=0 + for cmd in gcc g++ make curl curl-config git; do + if ! command -v "$cmd" > /dev/null 2>&1; then + missing_linux_deps=1 + break + fi + done + + # normal stuff, this mostly for bare docker images + if [[ "$missing_linux_deps" -eq 0 ]]; then + # the native package managers are slow, so skip if we can + echo "[ ] system packages already installed t=$SECONDS" + elif command -v apt-get > /dev/null 2>&1; then + $SUDO apt-get update + $SUDO apt-get install -y --no-install-recommends ca-certificates build-essential curl libcurl4-openssl-dev locales git xclip wl-clipboard + elif command -v dnf > /dev/null 2>&1; then + $SUDO dnf install -y ca-certificates gcc gcc-c++ make curl libcurl-devel glibc-langpack-en git + elif command -v yum > /dev/null 2>&1; then + $SUDO yum install -y ca-certificates gcc gcc-c++ make curl libcurl-devel glibc-langpack-en git + elif command -v pacman > /dev/null 2>&1; then + $SUDO pacman -Syu --noconfirm --needed base-devel ca-certificates curl git + elif command -v zypper > /dev/null 2>&1; then + $SUDO zypper --non-interactive refresh + $SUDO zypper --non-interactive install ca-certificates gcc gcc-c++ make curl libcurl-devel glibc-locale git + elif command -v apk > /dev/null 2>&1; then + $SUDO apk add --no-cache ca-certificates build-base curl curl-dev musl-locales git + elif command -v xbps-install > /dev/null 2>&1; then + $SUDO xbps-install -Syu base-devel ca-certificates curl git libcurl-devel glibc-locales + else + echo "Unsupported Linux distribution. Supported package managers: apt-get, dnf, yum, pacman, zypper, apk, xbps-install." + exit 1 + fi + + if [[ -d "/etc/udev/rules.d/" ]]; then + $SUDO tee /etc/udev/rules.d/11-openpilot.rules > /dev/null <<-EOF + # Panda Jungle devices + SUBSYSTEM=="usb", ATTRS{idVendor}=="3801", ATTRS{idProduct}=="ddcf", MODE="0666" + SUBSYSTEM=="usb", ATTRS{idVendor}=="3801", ATTRS{idProduct}=="ddef", MODE="0666" + SUBSYSTEM=="usb", ATTRS{idVendor}=="bbaa", ATTRS{idProduct}=="ddcf", MODE="0666" + SUBSYSTEM=="usb", ATTRS{idVendor}=="bbaa", ATTRS{idProduct}=="ddef", MODE="0666" + + # Panda devices + SUBSYSTEM=="usb", ATTRS{idVendor}=="0483", ATTRS{idProduct}=="df11", MODE="0666" + SUBSYSTEM=="usb", ATTRS{idVendor}=="3801", ATTRS{idProduct}=="ddcc", MODE="0666" + SUBSYSTEM=="usb", ATTRS{idVendor}=="3801", ATTRS{idProduct}=="ddee", MODE="0666" + SUBSYSTEM=="usb", ATTRS{idVendor}=="bbaa", ATTRS{idProduct}=="ddcc", MODE="0666" + SUBSYSTEM=="usb", ATTRS{idVendor}=="bbaa", ATTRS{idProduct}=="ddee", MODE="0666" + + # comma devices over ADB + SUBSYSTEM=="usb", ATTR{idVendor}=="04d8", ATTR{idProduct}=="1234", ENV{adb_user}="yes" + EOF + + # delete the old ones + $SUDO rm -f /etc/udev/rules.d/11-panda.rules /etc/udev/rules.d/12-panda_jungle.rules /etc/udev/rules.d/50-comma-adb.rules + + $SUDO udevadm control --reload-rules && $SUDO udevadm trigger || true + fi +} + +function install_python_deps() { + # Increase the pip timeout to handle TimeoutError + export PIP_DEFAULT_TIMEOUT=200 + + cd "$ROOT" + + if ! command -v "uv" > /dev/null 2>&1; then + echo "installing uv..." + # TODO: outer retry can be removed once https://github.com/axodotdev/cargo-dist/pull/2311 is merged + retry 3 sh -c 'curl --retry 5 --retry-delay 5 --retry-all-errors -LsSf https://astral.sh/uv/install.sh | UV_GITHUB_TOKEN="${GITHUB_TOKEN:-}" sh' + UV_BIN="$HOME/.local/bin" + PATH="$UV_BIN:$PATH" + fi + + echo "updating uv..." + # ok to fail, can also fail due to installing with brew + uv self update || true + + echo "installing python packages..." + uv sync --frozen --all-extras + source .venv/bin/activate +} + +# --- Main --- + +if [[ "$OSTYPE" == "linux-gnu"* ]]; then + install_linux_deps + echo "[ ] installed system dependencies t=$SECONDS" +elif [[ "$OSTYPE" == "darwin"* ]]; then + if [[ $SHELL == "/bin/zsh" ]]; then + RC_FILE="$HOME/.zshrc" + elif [[ $SHELL == "/bin/bash" ]]; then + RC_FILE="$HOME/.bash_profile" + fi +fi + +if [ -f "$ROOT/pyproject.toml" ]; then + install_python_deps + echo "[ ] installed python dependencies t=$SECONDS" +fi + +if [[ "$OSTYPE" == "darwin"* ]] && [[ -n "${RC_FILE:-}" ]]; then + echo + echo "---- OPENPILOT SETUP DONE ----" + echo "Open a new shell or configure your active shell env by running:" + echo "source $RC_FILE" +fi diff --git a/tools/sim/README.md b/tools/sim/README.md deleted file mode 100644 index f6ddde2580..0000000000 --- a/tools/sim/README.md +++ /dev/null @@ -1,50 +0,0 @@ -openpilot in simulator -===================== - -openpilot implements a [bridge](run_bridge.py) that allows it to run in the [MetaDrive simulator](https://github.com/metadriverse/metadrive). - -## Launching openpilot -First, start openpilot. -``` bash -# Run locally -./tools/sim/launch_openpilot.sh -``` - -## Bridge usage -``` -$ ./run_bridge.py -h -usage: run_bridge.py [-h] [--joystick] [--high_quality] [--dual_camera] -Bridge between the simulator and openpilot. - -options: - -h, --help show this help message and exit - --joystick - --high_quality - --dual_camera -``` - -#### Bridge Controls: -- To engage openpilot press 2, then press 1 to increase the speed and 2 to decrease. -- To disengage, press "S" (simulates a user brake) - -#### All inputs: - -``` -| key | functionality | -|------|-----------------------| -| 1 | Cruise Resume / Accel | -| 2 | Cruise Set / Decel | -| 3 | Cruise Cancel | -| r | Reset Simulation | -| i | Toggle Ignition | -| q | Exit all | -| wasd | Control manually | -``` - -## MetaDrive - -### Launching Metadrive -Start bridge processes located in tools/sim: -``` bash -./run_bridge.py -``` \ No newline at end of file diff --git a/tools/sim/bridge/common.py b/tools/sim/bridge/common.py deleted file mode 100644 index 69dec173ca..0000000000 --- a/tools/sim/bridge/common.py +++ /dev/null @@ -1,206 +0,0 @@ -import signal -import threading -import functools -import numpy as np - -from collections import namedtuple -from enum import Enum -from multiprocessing import Process, Queue, Value -from abc import ABC, abstractmethod - -from opendbc.car.honda.values import CruiseButtons -from openpilot.common.params import Params -from openpilot.common.realtime import Ratekeeper -from openpilot.selfdrive.test.helpers import set_params_enabled -from openpilot.tools.sim.lib.common import SimulatorState, World -from openpilot.tools.sim.lib.simulated_car import SimulatedCar -from openpilot.tools.sim.lib.simulated_sensors import SimulatedSensors - -QueueMessage = namedtuple("QueueMessage", ["type", "info"], defaults=[None]) - -class QueueMessageType(Enum): - START_STATUS = 0 - CONTROL_COMMAND = 1 - TERMINATION_INFO = 2 - CLOSE_STATUS = 3 - -def control_cmd_gen(cmd: str): - return QueueMessage(QueueMessageType.CONTROL_COMMAND, cmd) - -def rk_loop(function, hz, exit_event: threading.Event): - rk = Ratekeeper(hz, None) - while not exit_event.is_set(): - function() - rk.keep_time() - - -class SimulatorBridge(ABC): - TICKS_PER_FRAME = 5 - - def __init__(self, dual_camera, high_quality): - set_params_enabled() - self.params = Params() - self.params.put_bool("AlphaLongitudinalEnabled", True) - - self.rk = Ratekeeper(100, None) - - self.dual_camera = dual_camera - self.high_quality = high_quality - - self._exit_event: threading.Event | None = None - self._threads = [] - self._keep_alive = True - self.started = Value('i', False) - signal.signal(signal.SIGTERM, self._on_shutdown) - self.simulator_state = SimulatorState() - - self.world: World | None = None - - self.past_startup_engaged = False - self.startup_button_prev = True - - self.test_run = False - - def _on_shutdown(self, signal, frame): - self.shutdown() - - def shutdown(self): - self._keep_alive = False - - def bridge_keep_alive(self, q: Queue, retries: int): - try: - self._run(q) - finally: - self.close("bridge terminated") - - def close(self, reason): - self.started.value = False - - if self._exit_event is not None: - self._exit_event.set() - - if self.world is not None: - self.world.close(reason) - - def run(self, queue, retries=-1): - bridge_p = Process(name="bridge", target=self.bridge_keep_alive, args=(queue, retries)) - bridge_p.start() - return bridge_p - - def print_status(self): - print( - f""" -State: -Ignition: {self.simulator_state.ignition} Engaged: {self.simulator_state.is_engaged} - """) - - @abstractmethod - def spawn_world(self, q: Queue) -> World: - pass - - def _run(self, q: Queue): - self.world = self.spawn_world(q) - - self.simulated_car = SimulatedCar() - self.simulated_sensors = SimulatedSensors(self.dual_camera) - - self._exit_event = threading.Event() - - self.simulated_car_thread = threading.Thread(target=rk_loop, args=(functools.partial(self.simulated_car.update, self.simulator_state), - 100, self._exit_event)) - self.simulated_car_thread.start() - - self.simulated_camera_thread = threading.Thread(target=rk_loop, args=(functools.partial(self.simulated_sensors.send_camera_images, self.world), - 20, self._exit_event)) - self.simulated_camera_thread.start() - - # Simulation tends to be slow in the initial steps. This prevents lagging later - for _ in range(20): - self.world.tick() - - while self._keep_alive: - throttle_out = steer_out = brake_out = 0.0 - throttle_op = steer_op = brake_op = 0.0 - - self.simulator_state.cruise_button = 0 - self.simulator_state.left_blinker = False - self.simulator_state.right_blinker = False - - throttle_manual = steer_manual = brake_manual = 0. - - # Read manual controls - if not q.empty(): - message = q.get() - if message.type == QueueMessageType.CONTROL_COMMAND: - m = message.info.split('_') - if m[0] == "steer": - steer_manual = float(m[1]) - elif m[0] == "throttle": - throttle_manual = float(m[1]) - elif m[0] == "brake": - brake_manual = float(m[1]) - elif m[0] == "cruise": - if m[1] == "down": - self.simulator_state.cruise_button = CruiseButtons.DECEL_SET - elif m[1] == "up": - self.simulator_state.cruise_button = CruiseButtons.RES_ACCEL - elif m[1] == "cancel": - self.simulator_state.cruise_button = CruiseButtons.CANCEL - elif m[1] == "main": - self.simulator_state.cruise_button = CruiseButtons.MAIN - elif m[0] == "blinker": - if m[1] == "left": - self.simulator_state.left_blinker = True - elif m[1] == "right": - self.simulator_state.right_blinker = True - elif m[0] == "ignition": - self.simulator_state.ignition = not self.simulator_state.ignition - elif m[0] == "reset": - self.world.reset() - elif m[0] == "quit": - break - - self.simulator_state.user_brake = brake_manual - self.simulator_state.user_gas = throttle_manual - self.simulator_state.user_torque = steer_manual * -10000 - - steer_manual = steer_manual * -40 - - # Update openpilot on current sensor state - self.simulated_sensors.update(self.simulator_state, self.world) - - self.simulated_car.sm.update(0) - self.simulator_state.is_engaged = self.simulated_car.sm['selfdriveState'].active - - if self.simulator_state.is_engaged: - throttle_op = np.clip(self.simulated_car.sm['carControl'].actuators.accel / 1.6, 0.0, 1.0) - brake_op = np.clip(-self.simulated_car.sm['carControl'].actuators.accel / 4.0, 0.0, 1.0) - steer_op = self.simulated_car.sm['carControl'].actuators.steeringAngleDeg - - self.past_startup_engaged = True - elif not self.past_startup_engaged and self.simulated_car.sm['selfdriveState'].engageable: - self.simulator_state.cruise_button = CruiseButtons.DECEL_SET if self.startup_button_prev else CruiseButtons.MAIN # force engagement on startup - self.startup_button_prev = not self.startup_button_prev - - throttle_out = throttle_op if self.simulator_state.is_engaged else throttle_manual - brake_out = brake_op if self.simulator_state.is_engaged else brake_manual - steer_out = steer_op if self.simulator_state.is_engaged else steer_manual - - self.world.apply_controls(steer_out, throttle_out, brake_out) - self.world.read_state() - self.world.read_sensors(self.simulator_state) - - if self.world.exit_event.is_set(): - self.shutdown() - - if self.rk.frame % self.TICKS_PER_FRAME == 0: - self.world.tick() - self.world.read_cameras() - - # don't print during test, so no print/IO Block between OP and metadrive processes - if not self.test_run and self.rk.frame % 25 == 0: - self.print_status() - - self.started.value = True - - self.rk.keep_time() diff --git a/tools/sim/bridge/metadrive/metadrive_bridge.py b/tools/sim/bridge/metadrive/metadrive_bridge.py deleted file mode 100644 index b8dc94cf86..0000000000 --- a/tools/sim/bridge/metadrive/metadrive_bridge.py +++ /dev/null @@ -1,93 +0,0 @@ -import math -from multiprocessing import Queue - -from metadrive.component.sensors.base_camera import _cuda_enable -from metadrive.component.map.pg_map import MapGenerateMethod - -from openpilot.tools.sim.bridge.common import SimulatorBridge -from openpilot.tools.sim.bridge.metadrive.metadrive_common import RGBCameraRoad, RGBCameraWide -from openpilot.tools.sim.bridge.metadrive.metadrive_world import MetaDriveWorld -from openpilot.tools.sim.lib.camerad import W, H - - -def straight_block(length): - return { - "id": "S", - "pre_block_socket_index": 0, - "length": length - } - -def curve_block(length, angle=45, direction=0): - return { - "id": "C", - "pre_block_socket_index": 0, - "length": length, - "radius": length, - "angle": angle, - "dir": direction - } - -def create_map(track_size=60): - curve_len = track_size * 2 - return dict( - type=MapGenerateMethod.PG_MAP_FILE, - lane_num=2, - lane_width=4.5, - config=[ - None, - straight_block(track_size), - curve_block(curve_len, 90), - straight_block(track_size), - curve_block(curve_len, 90), - straight_block(track_size), - curve_block(curve_len, 90), - straight_block(track_size), - curve_block(curve_len, 90), - ] - ) - - -class MetaDriveBridge(SimulatorBridge): - TICKS_PER_FRAME = 5 - - def __init__(self, dual_camera, high_quality, test_duration=math.inf, test_run=False): - super().__init__(dual_camera, high_quality) - - self.should_render = False - self.test_run = test_run - self.test_duration = test_duration if self.test_run else math.inf - - def spawn_world(self, queue: Queue): - sensors = { - "rgb_road": (RGBCameraRoad, W, H, ) - } - - if self.dual_camera: - sensors["rgb_wide"] = (RGBCameraWide, W, H) - - config = dict( - use_render=self.should_render, - vehicle_config=dict( - enable_reverse=False, - render_vehicle=False, - image_source="rgb_road", - ), - sensors=sensors, - image_on_cuda=_cuda_enable, - image_observation=True, - interface_panel=[], - out_of_route_done=False, - on_continuous_line_done=False, - crash_vehicle_done=False, - crash_object_done=False, - arrive_dest_done=False, - traffic_density=0.0, # traffic is incredibly expensive - map_config=create_map(), - decision_repeat=1, - physics_world_step_size=self.TICKS_PER_FRAME/100, - preload_models=False, - show_logo=False, - anisotropic_filtering=False - ) - - return MetaDriveWorld(queue, config, self.test_duration, self.test_run, self.dual_camera) diff --git a/tools/sim/lib/camerad.py b/tools/sim/lib/camerad.py deleted file mode 100644 index be4e1a610c..0000000000 --- a/tools/sim/lib/camerad.py +++ /dev/null @@ -1,70 +0,0 @@ -import numpy as np -import os -import pyopencl as cl -import pyopencl.array as cl_array - -from msgq.visionipc import VisionIpcServer, VisionStreamType -from cereal import messaging - -from openpilot.common.basedir import BASEDIR -from openpilot.tools.sim.lib.common import W, H - -class Camerad: - """Simulates the camerad daemon""" - def __init__(self, dual_camera): - self.pm = messaging.PubMaster(['roadCameraState', 'wideRoadCameraState']) - - self.frame_road_id = 0 - self.frame_wide_id = 0 - self.vipc_server = VisionIpcServer("camerad") - - self.vipc_server.create_buffers(VisionStreamType.VISION_STREAM_ROAD, 5, W, H) - if dual_camera: - self.vipc_server.create_buffers(VisionStreamType.VISION_STREAM_WIDE_ROAD, 5, W, H) - - self.vipc_server.start_listener() - - # set up for pyopencl rgb to yuv conversion - self.ctx = cl.create_some_context() - self.queue = cl.CommandQueue(self.ctx) - cl_arg = f" -DHEIGHT={H} -DWIDTH={W} -DRGB_STRIDE={W * 3} -DUV_WIDTH={W // 2} -DUV_HEIGHT={H // 2} -DRGB_SIZE={W * H} -DCL_DEBUG " - - kernel_fn = os.path.join(BASEDIR, "tools/sim/rgb_to_nv12.cl") - with open(kernel_fn) as f: - prg = cl.Program(self.ctx, f.read()).build(cl_arg) - self.krnl = prg.rgb_to_nv12 - self.Wdiv4 = W // 4 if (W % 4 == 0) else (W + (4 - W % 4)) // 4 - self.Hdiv4 = H // 4 if (H % 4 == 0) else (H + (4 - H % 4)) // 4 - - def cam_send_yuv_road(self, yuv): - self._send_yuv(yuv, self.frame_road_id, 'roadCameraState', VisionStreamType.VISION_STREAM_ROAD) - self.frame_road_id += 1 - - def cam_send_yuv_wide_road(self, yuv): - self._send_yuv(yuv, self.frame_wide_id, 'wideRoadCameraState', VisionStreamType.VISION_STREAM_WIDE_ROAD) - self.frame_wide_id += 1 - - # Returns: yuv bytes - def rgb_to_yuv(self, rgb): - assert rgb.shape == (H, W, 3), f"{rgb.shape}" - assert rgb.dtype == np.uint8 - - rgb_cl = cl_array.to_device(self.queue, rgb) - yuv_cl = cl_array.empty_like(rgb_cl) - self.krnl(self.queue, (self.Wdiv4, self.Hdiv4), None, rgb_cl.data, yuv_cl.data).wait() - yuv = np.resize(yuv_cl.get(), rgb.size // 2) - return yuv.data.tobytes() - - def _send_yuv(self, yuv, frame_id, pub_type, yuv_type): - eof = int(frame_id * 0.05 * 1e9) - self.vipc_server.send(yuv_type, yuv, frame_id, eof, eof) - - dat = messaging.new_message(pub_type, valid=True) - msg = { - "frameId": frame_id, - "transform": [1.0, 0.0, 0.0, - 0.0, 1.0, 0.0, - 0.0, 0.0, 1.0] - } - setattr(dat, pub_type, msg) - self.pm.send(pub_type, dat) diff --git a/tools/sim/lib/common.py b/tools/sim/lib/common.py deleted file mode 100644 index 1324932131..0000000000 --- a/tools/sim/lib/common.py +++ /dev/null @@ -1,100 +0,0 @@ -import math -import multiprocessing -import numpy as np - -from abc import ABC, abstractmethod -from collections import namedtuple - -W, H = 1928, 1208 - - -vec3 = namedtuple("vec3", ["x", "y", "z"]) - -class GPSState: - def __init__(self): - self.latitude = 0 - self.longitude = 0 - self.altitude = 0 - - def from_xy(self, xy): - """Simulates a lat/lon from an xy coordinate on a plane, for simple simulation. TODO: proper global projection?""" - BASE_LAT = 32.75308505188913 - BASE_LON = -117.2095393365393 - DEG_TO_METERS = 100000 - - self.latitude = float(BASE_LAT + xy[0] / DEG_TO_METERS) - self.longitude = float(BASE_LON + xy[1] / DEG_TO_METERS) - self.altitude = 0 - - -class IMUState: - def __init__(self): - self.accelerometer: vec3 = vec3(0,0,0) - self.gyroscope: vec3 = vec3(0,0,0) - self.bearing: float = 0 - - -class SimulatorState: - def __init__(self): - self.valid = False - self.is_engaged = False - self.ignition = True - - self.velocity: vec3 = None - self.bearing: float = 0 - self.gps = GPSState() - self.imu = IMUState() - - self.steering_angle: float = 0 - - self.user_gas: float = 0 - self.user_brake: float = 0 - self.user_torque: float = 0 - - self.cruise_button = 0 - - self.left_blinker = False - self.right_blinker = False - - @property - def speed(self): - return math.sqrt(self.velocity.x ** 2 + self.velocity.y ** 2 + self.velocity.z ** 2) - - -class World(ABC): - def __init__(self, dual_camera): - self.dual_camera = dual_camera - - self.image_lock = multiprocessing.Semaphore(value=0) - self.road_image = np.zeros((H, W, 3), dtype=np.uint8) - self.wide_road_image = np.zeros((H, W, 3), dtype=np.uint8) - - self.exit_event = multiprocessing.Event() - - @abstractmethod - def apply_controls(self, steer_sim, throttle_out, brake_out): - pass - - @abstractmethod - def tick(self): - pass - - @abstractmethod - def read_state(self): - pass - - @abstractmethod - def read_sensors(self, simulator_state: SimulatorState): - pass - - @abstractmethod - def read_cameras(self): - pass - - @abstractmethod - def close(self, reason: str): - pass - - @abstractmethod - def reset(self): - pass diff --git a/tools/sim/rgb_to_nv12.cl b/tools/sim/rgb_to_nv12.cl deleted file mode 100644 index 54816d5d7d..0000000000 --- a/tools/sim/rgb_to_nv12.cl +++ /dev/null @@ -1,119 +0,0 @@ -#define RGB_TO_Y(r, g, b) ((((mul24(b, 13) + mul24(g, 65) + mul24(r, 33)) + 64) >> 7) + 16) -#define RGB_TO_U(r, g, b) ((mul24(b, 56) - mul24(g, 37) - mul24(r, 19) + 0x8080) >> 8) -#define RGB_TO_V(r, g, b) ((mul24(r, 56) - mul24(g, 47) - mul24(b, 9) + 0x8080) >> 8) -#define AVERAGE(x, y, z, w) ((convert_ushort(x) + convert_ushort(y) + convert_ushort(z) + convert_ushort(w) + 1) >> 1) - -inline void convert_2_ys(__global uchar * out_yuv, int yi, const uchar8 rgbs1) { - uchar2 yy = (uchar2)( - RGB_TO_Y(rgbs1.s2, rgbs1.s1, rgbs1.s0), - RGB_TO_Y(rgbs1.s5, rgbs1.s4, rgbs1.s3) - ); -#ifdef CL_DEBUG - if(yi >= RGB_SIZE) - printf("Y vector2 overflow, %d > %d\n", yi, RGB_SIZE); -#endif - vstore2(yy, 0, out_yuv + yi); -} - -inline void convert_4_ys(__global uchar * out_yuv, int yi, const uchar8 rgbs1, const uchar8 rgbs3) { - const uchar4 yy = (uchar4)( - RGB_TO_Y(rgbs1.s2, rgbs1.s1, rgbs1.s0), - RGB_TO_Y(rgbs1.s5, rgbs1.s4, rgbs1.s3), - RGB_TO_Y(rgbs3.s0, rgbs1.s7, rgbs1.s6), - RGB_TO_Y(rgbs3.s3, rgbs3.s2, rgbs3.s1) - ); -#ifdef CL_DEBUG - if(yi > RGB_SIZE - 4) - printf("Y vector4 overflow, %d > %d\n", yi, RGB_SIZE - 4); -#endif - vstore4(yy, 0, out_yuv + yi); -} - -inline void convert_uv(__global uchar * out_yuv, int uvi, - const uchar8 rgbs1, const uchar8 rgbs2) { - // U & V: average of 2x2 pixels square - const short ab = AVERAGE(rgbs1.s0, rgbs1.s3, rgbs2.s0, rgbs2.s3); - const short ag = AVERAGE(rgbs1.s1, rgbs1.s4, rgbs2.s1, rgbs2.s4); - const short ar = AVERAGE(rgbs1.s2, rgbs1.s5, rgbs2.s2, rgbs2.s5); -#ifdef CL_DEBUG - if(uvi >= RGB_SIZE + RGB_SIZE / 2) - printf("UV overflow, %d >= %d\n", uvi, RGB_SIZE + RGB_SIZE / 2); -#endif - out_yuv[uvi] = RGB_TO_U(ar, ag, ab); - out_yuv[uvi+1] = RGB_TO_V(ar, ag, ab); -} - -inline void convert_2_uvs(__global uchar * out_yuv, int uvi, - const uchar8 rgbs1, const uchar8 rgbs2, const uchar8 rgbs3, const uchar8 rgbs4) { - // U & V: average of 2x2 pixels square - const short ab1 = AVERAGE(rgbs1.s0, rgbs1.s3, rgbs2.s0, rgbs2.s3); - const short ag1 = AVERAGE(rgbs1.s1, rgbs1.s4, rgbs2.s1, rgbs2.s4); - const short ar1 = AVERAGE(rgbs1.s2, rgbs1.s5, rgbs2.s2, rgbs2.s5); - const short ab2 = AVERAGE(rgbs1.s6, rgbs3.s1, rgbs2.s6, rgbs4.s1); - const short ag2 = AVERAGE(rgbs1.s7, rgbs3.s2, rgbs2.s7, rgbs4.s2); - const short ar2 = AVERAGE(rgbs3.s0, rgbs3.s3, rgbs4.s0, rgbs4.s3); - uchar4 uv = (uchar4)( - RGB_TO_U(ar1, ag1, ab1), - RGB_TO_V(ar1, ag1, ab1), - RGB_TO_U(ar2, ag2, ab2), - RGB_TO_V(ar2, ag2, ab2) - ); -#ifdef CL_DEBUG1 - if(uvi > RGB_SIZE + RGB_SIZE / 2 - 4) - printf("UV2 overflow, %d >= %d\n", uvi, RGB_SIZE + RGB_SIZE / 2 - 2); -#endif - vstore4(uv, 0, out_yuv + uvi); -} - -__kernel void rgb_to_nv12(__global uchar const * const rgb, - __global uchar * out_yuv) -{ - const int dx = get_global_id(0); - const int dy = get_global_id(1); - const int col = mul24(dx, 4); // Current column in rgb image - const int row = mul24(dy, 4); // Current row in rgb image - const int bgri_start = mad24(row, RGB_STRIDE, mul24(col, 3)); // Start offset of rgb data being converted - const int yi_start = mad24(row, WIDTH, col); // Start offset in the target yuv buffer - int uvi = mad24(row / 2, WIDTH, RGB_SIZE + col); - int num_col = min(WIDTH - col, 4); - int num_row = min(HEIGHT - row, 4); - if(num_row == 4) { - const uchar8 rgbs0_0 = vload8(0, rgb + bgri_start); - const uchar8 rgbs0_1 = vload8(0, rgb + bgri_start + 8); - const uchar8 rgbs1_0 = vload8(0, rgb + bgri_start + RGB_STRIDE); - const uchar8 rgbs1_1 = vload8(0, rgb + bgri_start + RGB_STRIDE + 8); - const uchar8 rgbs2_0 = vload8(0, rgb + bgri_start + RGB_STRIDE * 2); - const uchar8 rgbs2_1 = vload8(0, rgb + bgri_start + RGB_STRIDE * 2 + 8); - const uchar8 rgbs3_0 = vload8(0, rgb + bgri_start + RGB_STRIDE * 3); - const uchar8 rgbs3_1 = vload8(0, rgb + bgri_start + RGB_STRIDE * 3 + 8); - if(num_col == 4) { - convert_4_ys(out_yuv, yi_start, rgbs0_0, rgbs0_1); - convert_4_ys(out_yuv, yi_start + WIDTH, rgbs1_0, rgbs1_1); - convert_4_ys(out_yuv, yi_start + WIDTH * 2, rgbs2_0, rgbs2_1); - convert_4_ys(out_yuv, yi_start + WIDTH * 3, rgbs3_0, rgbs3_1); - convert_2_uvs(out_yuv, uvi, rgbs0_0, rgbs1_0, rgbs0_1, rgbs1_1); - convert_2_uvs(out_yuv, uvi + WIDTH, rgbs2_0, rgbs3_0, rgbs2_1, rgbs3_1); - } else if(num_col == 2) { - convert_2_ys(out_yuv, yi_start, rgbs0_0); - convert_2_ys(out_yuv, yi_start + WIDTH, rgbs1_0); - convert_2_ys(out_yuv, yi_start + WIDTH * 2, rgbs2_0); - convert_2_ys(out_yuv, yi_start + WIDTH * 3, rgbs3_0); - convert_uv(out_yuv, uvi, rgbs0_0, rgbs1_0); - convert_uv(out_yuv, uvi + WIDTH, rgbs2_0, rgbs3_0); - } - } else { - const uchar8 rgbs0_0 = vload8(0, rgb + bgri_start); - const uchar8 rgbs0_1 = vload8(0, rgb + bgri_start + 8); - const uchar8 rgbs1_0 = vload8(0, rgb + bgri_start + RGB_STRIDE); - const uchar8 rgbs1_1 = vload8(0, rgb + bgri_start + RGB_STRIDE + 8); - if(num_col == 4) { - convert_4_ys(out_yuv, yi_start, rgbs0_0, rgbs0_1); - convert_4_ys(out_yuv, yi_start + WIDTH, rgbs1_0, rgbs1_1); - convert_2_uvs(out_yuv, uvi, rgbs0_0, rgbs1_0, rgbs0_1, rgbs1_1); - } else if(num_col == 2) { - convert_2_ys(out_yuv, yi_start, rgbs0_0); - convert_2_ys(out_yuv, yi_start + WIDTH, rgbs1_0); - convert_uv(out_yuv, uvi, rgbs0_0, rgbs1_0); - } - } -} diff --git a/tools/ubuntu_setup.sh b/tools/ubuntu_setup.sh deleted file mode 100755 index be4cfb68fa..0000000000 --- a/tools/ubuntu_setup.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env bash - -set -e - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )" - -# NOTE: this is used in a docker build, so do not run any scripts here. - -"$DIR"/install_ubuntu_dependencies.sh -"$DIR"/install_python_dependencies.sh diff --git a/tools/webcam/README.md b/tools/webcam/README.md deleted file mode 100644 index 67ad2cc8cb..0000000000 --- a/tools/webcam/README.md +++ /dev/null @@ -1,35 +0,0 @@ -# Run openpilot with webcam on PC - -What's needed: -- Ubuntu 24.04 ([WSL2 is not supported](https://github.com/commaai/openpilot/issues/34216)) or macOS -- GPU (recommended) -- One USB webcam, at least 720p and 78 degrees FOV (e.g. Logitech C920/C615, NexiGo N60) -- [Car harness](https://comma.ai/shop/products/comma-car-harness) -- [panda](https://comma.ai/shop/panda) -- USB-A to USB-A cable to connect panda to your computer - -## Setup openpilot -- Follow [this readme](../README.md) to install and build the requirements -- Install OpenCL Driver (Ubuntu) -``` -sudo apt install pocl-opencl-icd -``` - -## Connect the hardware -- Connect the camera first -- Connect your computer to panda - -## GO -``` -USE_WEBCAM=1 system/manager/manager.py -``` -- Start the car, then the UI should show the road webcam's view -- Adjust and secure the webcam -- Finish calibration and engage! - -## Specify Cameras - -Use the `ROAD_CAM` (default 0) and optional `DRIVER_CAM`, `WIDE_CAM` environment variables to specify which camera is which (ie. `ROAD_CAM=1` uses `/dev/video1`, on Ubuntu, for the road camera): -``` -USE_WEBCAM=1 ROAD_CAM=1 system/manager/manager.py -``` diff --git a/tools/webcam/camera.py b/tools/webcam/camera.py deleted file mode 100644 index 45f9379038..0000000000 --- a/tools/webcam/camera.py +++ /dev/null @@ -1,30 +0,0 @@ -import av -import cv2 as cv - -class Camera: - def __init__(self, cam_type_state, stream_type, camera_id): - try: - camera_id = int(camera_id) - except ValueError: # allow strings, ex: /dev/video0 - pass - self.cam_type_state = cam_type_state - self.stream_type = stream_type - self.cur_frame_id = 0 - - self.cap = cv.VideoCapture(camera_id) - self.W = self.cap.get(cv.CAP_PROP_FRAME_WIDTH) - self.H = self.cap.get(cv.CAP_PROP_FRAME_HEIGHT) - - @classmethod - def bgr2nv12(self, bgr): - frame = av.VideoFrame.from_ndarray(bgr, format='bgr24') - return frame.reformat(format='nv12').to_ndarray() - - def read_frames(self): - while True: - ret, frame = self.cap.read() - if not ret: - break - yuv = Camera.bgr2nv12(frame) - yield yuv.data.tobytes() - self.cap.release() diff --git a/tools/webcam/camerad.py b/tools/webcam/camerad.py deleted file mode 100755 index cb096dc00b..0000000000 --- a/tools/webcam/camerad.py +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/bin/env python3 -import threading -import os -from collections import namedtuple - -from msgq.visionipc import VisionIpcServer, VisionStreamType -from cereal import messaging - -from openpilot.tools.webcam.camera import Camera -from openpilot.common.realtime import Ratekeeper - -ROAD_CAM = os.getenv("ROAD_CAM", "0") -WIDE_CAM = os.getenv("WIDE_CAM") -DRIVER_CAM = os.getenv("DRIVER_CAM") - -CameraType = namedtuple("CameraType", ["msg_name", "stream_type", "cam_id"]) - -CAMERAS = [ - CameraType("roadCameraState", VisionStreamType.VISION_STREAM_ROAD, ROAD_CAM) -] -if WIDE_CAM: - CAMERAS.append(CameraType("wideRoadCameraState", VisionStreamType.VISION_STREAM_WIDE_ROAD, WIDE_CAM)) -if DRIVER_CAM: - CAMERAS.append(CameraType("driverCameraState", VisionStreamType.VISION_STREAM_DRIVER, DRIVER_CAM)) - -class Camerad: - def __init__(self): - self.pm = messaging.PubMaster([c.msg_name for c in CAMERAS]) - self.vipc_server = VisionIpcServer("camerad") - - self.cameras = [] - for c in CAMERAS: - cam_device = f"/dev/video{c.cam_id}" - print(f"opening {c.msg_name} at {cam_device}") - cam = Camera(c.msg_name, c.stream_type, cam_device) - self.cameras.append(cam) - self.vipc_server.create_buffers(c.stream_type, 20, cam.W, cam.H) - - self.vipc_server.start_listener() - - def _send_yuv(self, yuv, frame_id, pub_type, yuv_type): - eof = int(frame_id * 0.05 * 1e9) - self.vipc_server.send(yuv_type, yuv, frame_id, eof, eof) - dat = messaging.new_message(pub_type, valid=True) - msg = { - "frameId": frame_id, - "transform": [1.0, 0.0, 0.0, - 0.0, 1.0, 0.0, - 0.0, 0.0, 1.0] - } - setattr(dat, pub_type, msg) - self.pm.send(pub_type, dat) - - def camera_runner(self, cam): - rk = Ratekeeper(20, None) - for yuv in cam.read_frames(): - self._send_yuv(yuv, cam.cur_frame_id, cam.cam_type_state, cam.stream_type) - cam.cur_frame_id += 1 - rk.keep_time() - - def run(self): - threads = [] - for cam in self.cameras: - cam_thread = threading.Thread(target=self.camera_runner, args=(cam,)) - cam_thread.start() - threads.append(cam_thread) - - for t in threads: - t.join() - - -def main(): - camerad = Camerad() - camerad.run() - - -if __name__ == "__main__": - main() diff --git a/uv.lock b/uv.lock index 530db4ec9d..a0a951d33d 100644 --- a/uv.lock +++ b/uv.lock @@ -1,328 +1,95 @@ version = 1 -revision = 2 -requires-python = ">=3.11, <3.13" -resolution-markers = [ - "python_full_version >= '3.12' and sys_platform == 'darwin'", - "python_full_version >= '3.12' and platform_machine == 'aarch64' and sys_platform == 'linux'", - "(python_full_version >= '3.12' and platform_machine != 'aarch64' and sys_platform == 'linux') or (python_full_version >= '3.12' and sys_platform != 'darwin' and sys_platform != 'linux')", - "python_full_version < '3.12' and sys_platform == 'darwin'", - "python_full_version < '3.12' and platform_machine == 'aarch64' and sys_platform == 'linux'", - "(python_full_version < '3.12' and platform_machine != 'aarch64' and sys_platform == 'linux') or (python_full_version < '3.12' and sys_platform != 'darwin' and sys_platform != 'linux')", -] +revision = 3 +requires-python = ">=3.12.3, <3.13" -[[package]] -name = "aiohappyeyeballs" -version = "2.6.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/26/30/f84a107a9c4331c14b2b586036f40965c128aa4fee4dda5d3d51cb14ad54/aiohappyeyeballs-2.6.1.tar.gz", hash = "sha256:c3f9d0113123803ccadfdf3f0faa505bc78e6a72d1cc4806cbd719826e943558", size = 22760, upload-time = "2025-03-12T01:42:48.764Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/0f/15/5bf3b99495fb160b63f95972b81750f18f7f4e02ad051373b669d17d44f2/aiohappyeyeballs-2.6.1-py3-none-any.whl", hash = "sha256:f349ba8f4b75cb25c99c5c2d84e997e485204d2902a9597802b0371f09331fb8", size = 15265, upload-time = "2025-03-12T01:42:47.083Z" }, -] - -[[package]] -name = "aiohttp" -version = "3.12.13" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "aiohappyeyeballs" }, - { name = "aiosignal" }, - { name = "attrs" }, - { name = "frozenlist" }, - { name = "multidict" }, - { name = "propcache" }, - { name = "yarl" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/42/6e/ab88e7cb2a4058bed2f7870276454f85a7c56cd6da79349eb314fc7bbcaa/aiohttp-3.12.13.tar.gz", hash = "sha256:47e2da578528264a12e4e3dd8dd72a7289e5f812758fe086473fab037a10fcce", size = 7819160, upload-time = "2025-06-14T15:15:41.354Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/6a/65/5566b49553bf20ffed6041c665a5504fb047cefdef1b701407b8ce1a47c4/aiohttp-3.12.13-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:7c229b1437aa2576b99384e4be668af1db84b31a45305d02f61f5497cfa6f60c", size = 709401, upload-time = "2025-06-14T15:13:30.774Z" }, - { url = "https://files.pythonhosted.org/packages/14/b5/48e4cc61b54850bdfafa8fe0b641ab35ad53d8e5a65ab22b310e0902fa42/aiohttp-3.12.13-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:04076d8c63471e51e3689c93940775dc3d12d855c0c80d18ac5a1c68f0904358", size = 481669, upload-time = "2025-06-14T15:13:32.316Z" }, - { url = "https://files.pythonhosted.org/packages/04/4f/e3f95c8b2a20a0437d51d41d5ccc4a02970d8ad59352efb43ea2841bd08e/aiohttp-3.12.13-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:55683615813ce3601640cfaa1041174dc956d28ba0511c8cbd75273eb0587014", size = 469933, upload-time = "2025-06-14T15:13:34.104Z" }, - { url = "https://files.pythonhosted.org/packages/41/c9/c5269f3b6453b1cfbd2cfbb6a777d718c5f086a3727f576c51a468b03ae2/aiohttp-3.12.13-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:921bc91e602d7506d37643e77819cb0b840d4ebb5f8d6408423af3d3bf79a7b7", size = 1740128, upload-time = "2025-06-14T15:13:35.604Z" }, - { url = "https://files.pythonhosted.org/packages/6f/49/a3f76caa62773d33d0cfaa842bdf5789a78749dbfe697df38ab1badff369/aiohttp-3.12.13-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:e72d17fe0974ddeae8ed86db297e23dba39c7ac36d84acdbb53df2e18505a013", size = 1688796, upload-time = "2025-06-14T15:13:37.125Z" }, - { url = "https://files.pythonhosted.org/packages/ad/e4/556fccc4576dc22bf18554b64cc873b1a3e5429a5bdb7bbef7f5d0bc7664/aiohttp-3.12.13-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:0653d15587909a52e024a261943cf1c5bdc69acb71f411b0dd5966d065a51a47", size = 1787589, upload-time = "2025-06-14T15:13:38.745Z" }, - { url = "https://files.pythonhosted.org/packages/b9/3d/d81b13ed48e1a46734f848e26d55a7391708421a80336e341d2aef3b6db2/aiohttp-3.12.13-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:a77b48997c66722c65e157c06c74332cdf9c7ad00494b85ec43f324e5c5a9b9a", size = 1826635, upload-time = "2025-06-14T15:13:40.733Z" }, - { url = "https://files.pythonhosted.org/packages/75/a5/472e25f347da88459188cdaadd1f108f6292f8a25e62d226e63f860486d1/aiohttp-3.12.13-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d6946bae55fd36cfb8e4092c921075cde029c71c7cb571d72f1079d1e4e013bc", size = 1729095, upload-time = "2025-06-14T15:13:42.312Z" }, - { url = "https://files.pythonhosted.org/packages/b9/fe/322a78b9ac1725bfc59dfc301a5342e73d817592828e4445bd8f4ff83489/aiohttp-3.12.13-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:4f95db8c8b219bcf294a53742c7bda49b80ceb9d577c8e7aa075612b7f39ffb7", size = 1666170, upload-time = "2025-06-14T15:13:44.884Z" }, - { url = "https://files.pythonhosted.org/packages/7a/77/ec80912270e231d5e3839dbd6c065472b9920a159ec8a1895cf868c2708e/aiohttp-3.12.13-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:03d5eb3cfb4949ab4c74822fb3326cd9655c2b9fe22e4257e2100d44215b2e2b", size = 1714444, upload-time = "2025-06-14T15:13:46.401Z" }, - { url = "https://files.pythonhosted.org/packages/21/b2/fb5aedbcb2b58d4180e58500e7c23ff8593258c27c089abfbcc7db65bd40/aiohttp-3.12.13-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:6383dd0ffa15515283c26cbf41ac8e6705aab54b4cbb77bdb8935a713a89bee9", size = 1709604, upload-time = "2025-06-14T15:13:48.377Z" }, - { url = "https://files.pythonhosted.org/packages/e3/15/a94c05f7c4dc8904f80b6001ad6e07e035c58a8ebfcc15e6b5d58500c858/aiohttp-3.12.13-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:6548a411bc8219b45ba2577716493aa63b12803d1e5dc70508c539d0db8dbf5a", size = 1689786, upload-time = "2025-06-14T15:13:50.401Z" }, - { url = "https://files.pythonhosted.org/packages/1d/fd/0d2e618388f7a7a4441eed578b626bda9ec6b5361cd2954cfc5ab39aa170/aiohttp-3.12.13-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:81b0fcbfe59a4ca41dc8f635c2a4a71e63f75168cc91026c61be665945739e2d", size = 1783389, upload-time = "2025-06-14T15:13:51.945Z" }, - { url = "https://files.pythonhosted.org/packages/a6/6b/6986d0c75996ef7e64ff7619b9b7449b1d1cbbe05c6755e65d92f1784fe9/aiohttp-3.12.13-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:6a83797a0174e7995e5edce9dcecc517c642eb43bc3cba296d4512edf346eee2", size = 1803853, upload-time = "2025-06-14T15:13:53.533Z" }, - { url = "https://files.pythonhosted.org/packages/21/65/cd37b38f6655d95dd07d496b6d2f3924f579c43fd64b0e32b547b9c24df5/aiohttp-3.12.13-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:a5734d8469a5633a4e9ffdf9983ff7cdb512524645c7a3d4bc8a3de45b935ac3", size = 1716909, upload-time = "2025-06-14T15:13:55.148Z" }, - { url = "https://files.pythonhosted.org/packages/fd/20/2de7012427dc116714c38ca564467f6143aec3d5eca3768848d62aa43e62/aiohttp-3.12.13-cp311-cp311-win32.whl", hash = "sha256:fef8d50dfa482925bb6b4c208b40d8e9fa54cecba923dc65b825a72eed9a5dbd", size = 427036, upload-time = "2025-06-14T15:13:57.076Z" }, - { url = "https://files.pythonhosted.org/packages/f8/b6/98518bcc615ef998a64bef371178b9afc98ee25895b4f476c428fade2220/aiohttp-3.12.13-cp311-cp311-win_amd64.whl", hash = "sha256:9a27da9c3b5ed9d04c36ad2df65b38a96a37e9cfba6f1381b842d05d98e6afe9", size = 451427, upload-time = "2025-06-14T15:13:58.505Z" }, - { url = "https://files.pythonhosted.org/packages/b4/6a/ce40e329788013cd190b1d62bbabb2b6a9673ecb6d836298635b939562ef/aiohttp-3.12.13-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:0aa580cf80558557285b49452151b9c69f2fa3ad94c5c9e76e684719a8791b73", size = 700491, upload-time = "2025-06-14T15:14:00.048Z" }, - { url = "https://files.pythonhosted.org/packages/28/d9/7150d5cf9163e05081f1c5c64a0cdf3c32d2f56e2ac95db2a28fe90eca69/aiohttp-3.12.13-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:b103a7e414b57e6939cc4dece8e282cfb22043efd0c7298044f6594cf83ab347", size = 475104, upload-time = "2025-06-14T15:14:01.691Z" }, - { url = "https://files.pythonhosted.org/packages/f8/91/d42ba4aed039ce6e449b3e2db694328756c152a79804e64e3da5bc19dffc/aiohttp-3.12.13-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:78f64e748e9e741d2eccff9597d09fb3cd962210e5b5716047cbb646dc8fe06f", size = 467948, upload-time = "2025-06-14T15:14:03.561Z" }, - { url = "https://files.pythonhosted.org/packages/99/3b/06f0a632775946981d7c4e5a865cddb6e8dfdbaed2f56f9ade7bb4a1039b/aiohttp-3.12.13-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:29c955989bf4c696d2ededc6b0ccb85a73623ae6e112439398935362bacfaaf6", size = 1714742, upload-time = "2025-06-14T15:14:05.558Z" }, - { url = "https://files.pythonhosted.org/packages/92/a6/2552eebad9ec5e3581a89256276009e6a974dc0793632796af144df8b740/aiohttp-3.12.13-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:d640191016763fab76072c87d8854a19e8e65d7a6fcfcbf017926bdbbb30a7e5", size = 1697393, upload-time = "2025-06-14T15:14:07.194Z" }, - { url = "https://files.pythonhosted.org/packages/d8/9f/bd08fdde114b3fec7a021381b537b21920cdd2aa29ad48c5dffd8ee314f1/aiohttp-3.12.13-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:4dc507481266b410dede95dd9f26c8d6f5a14315372cc48a6e43eac652237d9b", size = 1752486, upload-time = "2025-06-14T15:14:08.808Z" }, - { url = "https://files.pythonhosted.org/packages/f7/e1/affdea8723aec5bd0959171b5490dccd9a91fcc505c8c26c9f1dca73474d/aiohttp-3.12.13-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:8a94daa873465d518db073bd95d75f14302e0208a08e8c942b2f3f1c07288a75", size = 1798643, upload-time = "2025-06-14T15:14:10.767Z" }, - { url = "https://files.pythonhosted.org/packages/f3/9d/666d856cc3af3a62ae86393baa3074cc1d591a47d89dc3bf16f6eb2c8d32/aiohttp-3.12.13-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:177f52420cde4ce0bb9425a375d95577fe082cb5721ecb61da3049b55189e4e6", size = 1718082, upload-time = "2025-06-14T15:14:12.38Z" }, - { url = "https://files.pythonhosted.org/packages/f3/ce/3c185293843d17be063dada45efd2712bb6bf6370b37104b4eda908ffdbd/aiohttp-3.12.13-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:0f7df1f620ec40f1a7fbcb99ea17d7326ea6996715e78f71a1c9a021e31b96b8", size = 1633884, upload-time = "2025-06-14T15:14:14.415Z" }, - { url = "https://files.pythonhosted.org/packages/3a/5b/f3413f4b238113be35dfd6794e65029250d4b93caa0974ca572217745bdb/aiohttp-3.12.13-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3062d4ad53b36e17796dce1c0d6da0ad27a015c321e663657ba1cc7659cfc710", size = 1694943, upload-time = "2025-06-14T15:14:16.48Z" }, - { url = "https://files.pythonhosted.org/packages/82/c8/0e56e8bf12081faca85d14a6929ad5c1263c146149cd66caa7bc12255b6d/aiohttp-3.12.13-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:8605e22d2a86b8e51ffb5253d9045ea73683d92d47c0b1438e11a359bdb94462", size = 1716398, upload-time = "2025-06-14T15:14:18.589Z" }, - { url = "https://files.pythonhosted.org/packages/ea/f3/33192b4761f7f9b2f7f4281365d925d663629cfaea093a64b658b94fc8e1/aiohttp-3.12.13-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:54fbbe6beafc2820de71ece2198458a711e224e116efefa01b7969f3e2b3ddae", size = 1657051, upload-time = "2025-06-14T15:14:20.223Z" }, - { url = "https://files.pythonhosted.org/packages/5e/0b/26ddd91ca8f84c48452431cb4c5dd9523b13bc0c9766bda468e072ac9e29/aiohttp-3.12.13-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:050bd277dfc3768b606fd4eae79dd58ceda67d8b0b3c565656a89ae34525d15e", size = 1736611, upload-time = "2025-06-14T15:14:21.988Z" }, - { url = "https://files.pythonhosted.org/packages/c3/8d/e04569aae853302648e2c138a680a6a2f02e374c5b6711732b29f1e129cc/aiohttp-3.12.13-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:2637a60910b58f50f22379b6797466c3aa6ae28a6ab6404e09175ce4955b4e6a", size = 1764586, upload-time = "2025-06-14T15:14:23.979Z" }, - { url = "https://files.pythonhosted.org/packages/ac/98/c193c1d1198571d988454e4ed75adc21c55af247a9fda08236602921c8c8/aiohttp-3.12.13-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:e986067357550d1aaa21cfe9897fa19e680110551518a5a7cf44e6c5638cb8b5", size = 1724197, upload-time = "2025-06-14T15:14:25.692Z" }, - { url = "https://files.pythonhosted.org/packages/e7/9e/07bb8aa11eec762c6b1ff61575eeeb2657df11ab3d3abfa528d95f3e9337/aiohttp-3.12.13-cp312-cp312-win32.whl", hash = "sha256:ac941a80aeea2aaae2875c9500861a3ba356f9ff17b9cb2dbfb5cbf91baaf5bf", size = 421771, upload-time = "2025-06-14T15:14:27.364Z" }, - { url = "https://files.pythonhosted.org/packages/52/66/3ce877e56ec0813069cdc9607cd979575859c597b6fb9b4182c6d5f31886/aiohttp-3.12.13-cp312-cp312-win_amd64.whl", hash = "sha256:671f41e6146a749b6c81cb7fd07f5a8356d46febdaaaf07b0e774ff04830461e", size = 447869, upload-time = "2025-06-14T15:14:29.05Z" }, -] - -[[package]] -name = "aioice" -version = "0.10.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "dnspython" }, - { name = "ifaddr" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/95/a2/45dfab1d5a7f96c48595a5770379acf406cdf02a2cd1ac1729b599322b08/aioice-0.10.1.tar.gz", hash = "sha256:5c8e1422103448d171925c678fb39795e5fe13d79108bebb00aa75a899c2094a", size = 44304, upload-time = "2025-04-13T08:15:25.629Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/3b/58/af07dda649c22a1ae954ffb7aaaf4d4a57f1bf00ebdf62307affc0b8552f/aioice-0.10.1-py3-none-any.whl", hash = "sha256:f31ae2abc8608b1283ed5f21aebd7b6bd472b152ff9551e9b559b2d8efed79e9", size = 24872, upload-time = "2025-04-13T08:15:24.044Z" }, -] - -[[package]] -name = "aiortc" -version = "1.10.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "aioice" }, - { name = "av" }, - { name = "cffi" }, - { name = "cryptography" }, - { name = "google-crc32c" }, - { name = "pyee" }, - { name = "pylibsrtp" }, - { name = "pyopenssl" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/8a/f8/408e092748521889c9d33dddcef920afd9891cf6db4615ba6b6bfe114ff8/aiortc-1.10.1.tar.gz", hash = "sha256:64926ad86bde20c1a4dacb7c3a164e57b522606b70febe261fada4acf79641b5", size = 1179406, upload-time = "2025-02-02T17:36:38.684Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/0a/6b/74547a30d1ddcc81f905ef4ff7fcc2c89b7482cb2045688f2aaa4fa918aa/aiortc-1.10.1-cp39-abi3-macosx_10_9_x86_64.whl", hash = "sha256:3bef536f38394b518aefae9dbf9cdd08f39e4c425f316f9692f0d8dc724810bd", size = 1218457, upload-time = "2025-02-02T17:36:23.172Z" }, - { url = "https://files.pythonhosted.org/packages/46/92/b4ccf39cd18e366ace2a11dc7d98ed55967b4b325707386b5788149db15e/aiortc-1.10.1-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:8842c02e38513d9432ef22982572833487bb015f23348fa10a690616dbf55143", size = 898855, upload-time = "2025-02-02T17:36:25.9Z" }, - { url = "https://files.pythonhosted.org/packages/a4/e9/2676de48b493787d8b03129713e6bb2dfbacca2a565090f2a89cbad71f96/aiortc-1.10.1-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:954a420de01c0bf6b07a0c58b662029b1c4204ddbd8f5c4162bbdebd43f882b1", size = 1750403, upload-time = "2025-02-02T17:36:28.446Z" }, - { url = "https://files.pythonhosted.org/packages/c3/9d/ab6d09183cdaf5df060923d9bd5c9ed5fb1802661d9401dba35f3c85a57b/aiortc-1.10.1-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e7c0d46fb30307a9d7deb4b7d66f0b0e73b77a7221b063fb6dc78821a5d2aa1e", size = 1867886, upload-time = "2025-02-02T17:36:30.209Z" }, - { url = "https://files.pythonhosted.org/packages/c2/71/0b5666e6b965dbd9a7f331aa827a6c3ab3eb4d582fefb686a7f4227b7954/aiortc-1.10.1-cp39-abi3-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:89582f6923046f79f15d9045f432bc78191eacc95f6bed18714e86ec935188d9", size = 1893709, upload-time = "2025-02-02T17:36:32.342Z" }, - { url = "https://files.pythonhosted.org/packages/9d/0a/8c0c78fad79ef595a0ed6e2ab413900e6bd0eac65fc5c31c9d8736bff909/aiortc-1.10.1-cp39-abi3-win32.whl", hash = "sha256:d1cbe87f740b33ffaa8e905f21092773e74916be338b64b81c8b79af4c3847eb", size = 923265, upload-time = "2025-02-02T17:36:34.685Z" }, - { url = "https://files.pythonhosted.org/packages/73/12/a27dd588a4988021da88cb4d338d8ee65ac097afc14e9193ab0be4a48790/aiortc-1.10.1-cp39-abi3-win_amd64.whl", hash = "sha256:c9a5a0b23f8a77540068faec8837fa0a65b0396c20f09116bdb874b75e0b6abe", size = 1009488, upload-time = "2025-02-02T17:36:36.317Z" }, -] - -[[package]] -name = "aiosignal" -version = "1.3.2" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "frozenlist" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/ba/b5/6d55e80f6d8a08ce22b982eafa278d823b541c925f11ee774b0b9c43473d/aiosignal-1.3.2.tar.gz", hash = "sha256:a8c255c66fafb1e499c9351d0bf32ff2d8a0321595ebac3b93713656d2436f54", size = 19424, upload-time = "2024-12-13T17:10:40.86Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/ec/6a/bc7e17a3e87a2985d3e8f4da4cd0f481060eb78fb08596c42be62c90a4d9/aiosignal-1.3.2-py2.py3-none-any.whl", hash = "sha256:45cde58e409a301715980c2b01d0c28bdde3770d8290b5eb2173759d9acb31a5", size = 7597, upload-time = "2024-12-13T17:10:38.469Z" }, -] +[manifest] +overrides = [{ name = "opendbc", editable = "opendbc_repo" }] [[package]] name = "attrs" -version = "25.3.0" +version = "26.1.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/5a/b0/1367933a8532ee6ff8d63537de4f1177af4bff9f3e829baf7331f595bb24/attrs-25.3.0.tar.gz", hash = "sha256:75d7cefc7fb576747b2c81b4442d4d4a1ce0900973527c011d1030fd3bf4af1b", size = 812032, upload-time = "2025-03-13T11:10:22.779Z" } +sdist = { url = "https://files.pythonhosted.org/packages/9a/8e/82a0fe20a541c03148528be8cac2408564a6c9a0cc7e9171802bc1d26985/attrs-26.1.0.tar.gz", hash = "sha256:d03ceb89cb322a8fd706d4fb91940737b6642aa36998fe130a9bc96c985eff32", size = 952055, upload-time = "2026-03-19T14:22:25.026Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/77/06/bb80f5f86020c4551da315d78b3ab75e8228f89f0162f2c3a819e407941a/attrs-25.3.0-py3-none-any.whl", hash = "sha256:427318ce031701fea540783410126f03899a97ffc6f61596ad581ac2e40e3bc3", size = 63815, upload-time = "2025-03-13T11:10:21.14Z" }, -] - -[[package]] -name = "av" -version = "13.1.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/0c/9d/486d31e76784cc0ad943f420c5e05867263b32b37e2f4b0f7f22fdc1ca3a/av-13.1.0.tar.gz", hash = "sha256:d3da736c55847d8596eb8c26c60e036f193001db3bc5c10da8665622d906c17e", size = 3957908, upload-time = "2024-10-06T04:54:57.507Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/39/54/c4227080c9700384db90072ace70d89b6a288b3748bd2ec0e32580a49e7f/av-13.1.0-cp311-cp311-macosx_10_13_x86_64.whl", hash = "sha256:867385e6701464a5c95903e24d2e0df1c7e0dbf211ed91d0ce639cd687373e10", size = 24255112, upload-time = "2024-10-06T04:52:48.49Z" }, - { url = "https://files.pythonhosted.org/packages/32/4a/eb9348231655ca99b200b380f4edbceff7358c927a285badcc84b18fb1c9/av-13.1.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:cb7a3f319401a46b0017771268ff4928501e77cf00b1a2aa0721e20b2fd1146e", size = 19467930, upload-time = "2024-10-06T04:52:52.118Z" }, - { url = "https://files.pythonhosted.org/packages/14/c7/48c80252bdbc3a75a54dd205a7fab8f613914009b9e5416202757208e040/av-13.1.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ad904f860147bceaca65b0d3174a8153f35c570d465161d210f1879970b15559", size = 32207671, upload-time = "2024-10-06T04:52:55.82Z" }, - { url = "https://files.pythonhosted.org/packages/f9/66/3332c7fa8c43b65680a94f279ea3e832b5500de3a1392bac6112881e984b/av-13.1.0-cp311-cp311-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:a906e017b29d0eb80d9ccf7a98d19268122da792dbb68eb741cfebba156e6aed", size = 31520911, upload-time = "2024-10-06T04:52:59.231Z" }, - { url = "https://files.pythonhosted.org/packages/e5/bb/2e03acb9b27591d97f700a3a6c27cfd1bc53fa148177747eda8a70cca1e9/av-13.1.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:5ce894d7847897da7be63277a0875bd93c51327134ac226c67978de014c7979f", size = 34048399, upload-time = "2024-10-06T04:53:03.934Z" }, - { url = "https://files.pythonhosted.org/packages/85/44/527aa3b65947d42cfe829326026edf0cd1a8c459390076034be275616c36/av-13.1.0-cp311-cp311-win_amd64.whl", hash = "sha256:384bcdb5fc3238a263a5a25cc9efc690859fa4148cc4b07e00fae927178db22a", size = 25779569, upload-time = "2024-10-06T04:53:07.582Z" }, - { url = "https://files.pythonhosted.org/packages/9b/aa/4bdd8ce59173574fc6e0c282c71ee6f96fca82643d97bf172bc4cb5a5674/av-13.1.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:261dbc3f4b55f4f8f3375b10b2258fca7f2ab7a6365c01bc65e77a0d5327a195", size = 24268674, upload-time = "2024-10-06T04:53:11.251Z" }, - { url = "https://files.pythonhosted.org/packages/17/b4/b267dd5bad99eed49ec6731827c6bcb5ab03864bf732a7ebb81e3df79911/av-13.1.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:83d259ef86b9054eb914bc7c6a7f6092a6d75cb939295e70ee979cfd92a67b99", size = 19475617, upload-time = "2024-10-06T04:53:13.832Z" }, - { url = "https://files.pythonhosted.org/packages/68/32/4209e51f54d7b54a1feb576d309c671ed1ff437b54fcc4ec68c239199e0a/av-13.1.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f3b4d3ca159eceab97e3c0fb08fe756520fb95508417f76e48198fda2a5b0806", size = 32468873, upload-time = "2024-10-06T04:53:17.639Z" }, - { url = "https://files.pythonhosted.org/packages/b6/d8/c174da5f06b24f3c9e36f91fd02a7411c39da9ce792c17964260d4be675e/av-13.1.0-cp312-cp312-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:40e8f757e373b73a2dc4640852a00cce4a4a92ef19b2e642a96d6994cd1fffbf", size = 31818484, upload-time = "2024-10-06T04:53:21.509Z" }, - { url = "https://files.pythonhosted.org/packages/7f/22/0dd8d1d5cad415772bb707d16aea8b81cf75d340d11d3668eea43468c730/av-13.1.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d8aaec2c0bfd024359db3821d679009d4e637e1bee0321d20f61c54ed6b20f41", size = 34398652, upload-time = "2024-10-06T04:53:25.798Z" }, - { url = "https://files.pythonhosted.org/packages/7b/ff/48fa68888b8d5bae36d915556ff18f9e5fdc6b5ff5ae23dc4904c9713168/av-13.1.0-cp312-cp312-win_amd64.whl", hash = "sha256:5ea0deab0e6a739cb742fba2a3983d8102f7516a3cdf3c46669f3cac0ed1f351", size = 25781343, upload-time = "2024-10-06T04:53:29.577Z" }, -] - -[[package]] -name = "azure-core" -version = "1.34.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "requests" }, - { name = "six" }, - { name = "typing-extensions" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/c9/29/ff7a519a315e41c85bab92a7478c6acd1cf0b14353139a08caee4c691f77/azure_core-1.34.0.tar.gz", hash = "sha256:bdb544989f246a0ad1c85d72eeb45f2f835afdcbc5b45e43f0dbde7461c81ece", size = 297999, upload-time = "2025-05-01T23:17:27.59Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/84/9e/5c87b49f65bb16571599bc789857d0ded2f53014d3392bc88a5d1f3ad779/azure_core-1.34.0-py3-none-any.whl", hash = "sha256:0615d3b756beccdb6624d1c0ae97284f38b78fb59a2a9839bf927c66fbbdddd6", size = 207409, upload-time = "2025-05-01T23:17:29.818Z" }, -] - -[[package]] -name = "azure-identity" -version = "1.23.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "azure-core" }, - { name = "cryptography" }, - { name = "msal" }, - { name = "msal-extensions" }, - { name = "typing-extensions" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/41/52/458c1be17a5d3796570ae2ed3c6b7b55b134b22d5ef8132b4f97046a9051/azure_identity-1.23.0.tar.gz", hash = "sha256:d9cdcad39adb49d4bb2953a217f62aec1f65bbb3c63c9076da2be2a47e53dde4", size = 265280, upload-time = "2025-05-14T00:18:30.408Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/07/16/a51d47780f41e4b87bb2d454df6aea90a44a346e918ac189d3700f3d728d/azure_identity-1.23.0-py3-none-any.whl", hash = "sha256:dbbeb64b8e5eaa81c44c565f264b519ff2de7ff0e02271c49f3cb492762a50b0", size = 186097, upload-time = "2025-05-14T00:18:32.734Z" }, -] - -[[package]] -name = "azure-storage-blob" -version = "12.25.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "azure-core" }, - { name = "cryptography" }, - { name = "isodate" }, - { name = "typing-extensions" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/8b/f3/f764536c25cc3829d36857167f03933ce9aee2262293179075439f3cd3ad/azure_storage_blob-12.25.1.tar.gz", hash = "sha256:4f294ddc9bc47909ac66b8934bd26b50d2000278b10ad82cc109764fdc6e0e3b", size = 570541, upload-time = "2025-03-27T17:13:05.424Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/57/33/085d9352d416e617993821b9d9488222fbb559bc15c3641d6cbd6d16d236/azure_storage_blob-12.25.1-py3-none-any.whl", hash = "sha256:1f337aab12e918ec3f1b638baada97550673911c4ceed892acc8e4e891b74167", size = 406990, upload-time = "2025-03-27T17:13:06.879Z" }, -] - -[[package]] -name = "casadi" -version = "3.7.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "numpy" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/b3/49/f8b8eb7c8e98e28e0cca1b41988932025d59a602fb2075f737cbaecf764d/casadi-3.7.0.tar.gz", hash = "sha256:21254f17eb5551c4a938641cc1b815ff3da27271ab2c36e44a3e90ec50ba471f", size = 6027731, upload-time = "2025-03-29T22:31:31.309Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/83/cf/7d1dc6b16f690f1fac22a0a43684de3a03b3f631a1d8c25393f320b5f971/casadi-3.7.0-cp311-none-macosx_10_13_x86_64.macosx_10_13_intel.whl", hash = "sha256:50bba75bb9575baa09a2e25ce3c1968803320c49b9dcc218139321dab02f0400", size = 48302536, upload-time = "2025-03-30T07:31:37.067Z" }, - { url = "https://files.pythonhosted.org/packages/74/d2/f69156aaf4545543995c791a0f97551b66f9c9bc8d92361973ee6378ad25/casadi-3.7.0-cp311-none-macosx_11_0_arm64.whl", hash = "sha256:8f138bf370603f6f820385d78882f840168e8e0866bea5de08b6b54a6e22c093", size = 44713683, upload-time = "2025-03-30T07:33:37.446Z" }, - { url = "https://files.pythonhosted.org/packages/2e/3b/13a7d92c27543e0a2eb559f2a5acc7278f1a2ef0217772b09df50ac1c2dc/casadi-3.7.0-cp311-none-manylinux2014_aarch64.whl", hash = "sha256:4d844a1281c7ff527115d27ee8f2c58315d0008cac835656323a6d502de27010", size = 45518255, upload-time = "2025-03-30T07:36:03.844Z" }, - { url = "https://files.pythonhosted.org/packages/bb/88/00adcb26a0c313ebeaa2db8b2691e37418d6b7c3e06b4a90a3ac9380b91b/casadi-3.7.0-cp311-none-manylinux2014_i686.whl", hash = "sha256:b8640486db98b75a75eb05b6191d5a7f0d44774c36c07c7da327d4d740914284", size = 74329105, upload-time = "2025-03-30T07:39:19.069Z" }, - { url = "https://files.pythonhosted.org/packages/60/64/b31fd4ce5b93f97fd16a9ba7ce8d4a8d36334a518f1ad00525340db31ff4/casadi-3.7.0-cp311-none-manylinux2014_x86_64.whl", hash = "sha256:65d9a61660c75ff8f0c30abf52e2f9cefcdee1cbb9301e26678f64116f509ee7", size = 77330636, upload-time = "2025-03-30T07:46:55.954Z" }, - { url = "https://files.pythonhosted.org/packages/c4/25/79bb6b866a7005186ccdfcb89e01032885a9efa90acfe2d079253685622b/casadi-3.7.0-cp311-none-win_amd64.whl", hash = "sha256:391b5ee886cde28bf813e820958bfcdef98314bd367a93c95e7bef1bf713b886", size = 50949252, upload-time = "2025-03-30T07:49:05.348Z" }, - { url = "https://files.pythonhosted.org/packages/b8/27/6ca4c831d9131eb15ca34346398c1379a577363c264ad47983c1be65b3e1/casadi-3.7.0-cp312-none-macosx_10_13_x86_64.macosx_10_13_intel.whl", hash = "sha256:ceb4d67c1c5cdf80f233866fcdcaf7d77523115983081fe909b70fe89fd7b708", size = 48303214, upload-time = "2025-03-30T07:51:05.246Z" }, - { url = "https://files.pythonhosted.org/packages/b2/cb/cd8be8aeac6453e2aad96793101fa287f54f86b643d542375969738930c3/casadi-3.7.0-cp312-none-macosx_11_0_arm64.whl", hash = "sha256:83dbc27125044e7600b04af648f24e6924d46e81afe6ff088218e4b7e9a37f08", size = 44713758, upload-time = "2025-03-30T07:52:44.766Z" }, - { url = "https://files.pythonhosted.org/packages/a4/3d/c8a392eac772b1537f63ee16b57be87bcdef9d9bc9530b54c95b1a122960/casadi-3.7.0-cp312-none-manylinux2014_aarch64.whl", hash = "sha256:53731171b41ca0640b76657d2320b929634a137ff30f12f985196df35411885b", size = 45517623, upload-time = "2025-03-30T07:54:25.318Z" }, - { url = "https://files.pythonhosted.org/packages/68/d2/2acd3b8cf8fa25bca342cd539f69dc94b0fa1bf3acaa30f13848fa0f31ee/casadi-3.7.0-cp312-none-manylinux2014_i686.whl", hash = "sha256:6b30fb73d8c140fbbe51e60d00412aaefe5a7b775257a422ea244f423bd2351c", size = 74319729, upload-time = "2025-03-30T07:57:18.329Z" }, - { url = "https://files.pythonhosted.org/packages/0f/35/ec351423c854a74884218501a431e018c6eee79461dde8e91f9ce6b4e2b5/casadi-3.7.0-cp312-none-manylinux2014_x86_64.whl", hash = "sha256:b795371bf09ec0bfd22eaa0a1e81ce2cd3ecd811c9d370b98f6853b87e8397c9", size = 77323153, upload-time = "2025-03-30T08:00:32.507Z" }, - { url = "https://files.pythonhosted.org/packages/d5/4b/ab605b5948795fe15b5930ecc5ac7ba72ebad116a9003c0117421cbe34a8/casadi-3.7.0-cp312-none-win_amd64.whl", hash = "sha256:e77173aad67b817ebf4320c31cef37c7d666f9895bc5970f3370b2ae6fdad587", size = 50946897, upload-time = "2025-03-30T08:02:37.836Z" }, + { url = "https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl", hash = "sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309", size = 67548, upload-time = "2026-03-19T14:22:23.645Z" }, ] [[package]] name = "certifi" -version = "2025.6.15" +version = "2026.6.17" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/73/f7/f14b46d4bcd21092d7d3ccef689615220d8a08fb25e564b65d20738e672e/certifi-2025.6.15.tar.gz", hash = "sha256:d747aa5a8b9bbbb1bb8c22bb13e22bd1f18e9796defa16bab421f7f7a317323b", size = 158753, upload-time = "2025-06-15T02:45:51.329Z" } +sdist = { url = "https://files.pythonhosted.org/packages/c9/c7/424b75da314c1045981bd9777432fad05a9e0c69daa4ed7e308bbaffe405/certifi-2026.6.17.tar.gz", hash = "sha256:024c88eeec92ca068db80f02b8b07c9cef7b9fe261d1d535abfd5abd6f6af432", size = 134594, upload-time = "2026-06-17T10:31:07.894Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/84/ae/320161bd181fc06471eed047ecce67b693fd7515b16d495d8932db763426/certifi-2025.6.15-py3-none-any.whl", hash = "sha256:2e0c7ce7cb5d8f8634ca55d2ba7e6ec2689a2fd6537d8dec1296a477a4910057", size = 157650, upload-time = "2025-06-15T02:45:49.977Z" }, + { url = "https://files.pythonhosted.org/packages/ef/2f/c5464532e965badff2f4c4c1a3a83f5697f0d7c407ed0cda44aaa99bb451/certifi-2026.6.17-py3-none-any.whl", hash = "sha256:2227dcbaafe0d2f59279d1762ddddc37783ed4354594f194ffc31d20f41fc3db", size = 133289, upload-time = "2026-06-17T10:31:06.348Z" }, ] [[package]] name = "cffi" -version = "1.17.1" +version = "2.0.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "pycparser" }, + { name = "pycparser", marker = "implementation_name != 'PyPy'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/fc/97/c783634659c2920c3fc70419e3af40972dbaf758daa229a7d6ea6135c90d/cffi-1.17.1.tar.gz", hash = "sha256:1c39c6016c32bc48dd54561950ebd6836e1670f2ae46128f67cf49e789c52824", size = 516621, upload-time = "2024-09-04T20:45:21.852Z" } +sdist = { url = "https://files.pythonhosted.org/packages/eb/56/b1ba7935a17738ae8453301356628e8147c79dbb825bcbc73dc7401f9846/cffi-2.0.0.tar.gz", hash = "sha256:44d1b5909021139fe36001ae048dbdde8214afa20200eda0f64c068cac5d5529", size = 523588, upload-time = "2025-09-08T23:24:04.541Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/6b/f4/927e3a8899e52a27fa57a48607ff7dc91a9ebe97399b357b85a0c7892e00/cffi-1.17.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:a45e3c6913c5b87b3ff120dcdc03f6131fa0065027d0ed7ee6190736a74cd401", size = 182264, upload-time = "2024-09-04T20:43:51.124Z" }, - { url = "https://files.pythonhosted.org/packages/6c/f5/6c3a8efe5f503175aaddcbea6ad0d2c96dad6f5abb205750d1b3df44ef29/cffi-1.17.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:30c5e0cb5ae493c04c8b42916e52ca38079f1b235c2f8ae5f4527b963c401caf", size = 178651, upload-time = "2024-09-04T20:43:52.872Z" }, - { url = "https://files.pythonhosted.org/packages/94/dd/a3f0118e688d1b1a57553da23b16bdade96d2f9bcda4d32e7d2838047ff7/cffi-1.17.1-cp311-cp311-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f75c7ab1f9e4aca5414ed4d8e5c0e303a34f4421f8a0d47a4d019ceff0ab6af4", size = 445259, upload-time = "2024-09-04T20:43:56.123Z" }, - { url = "https://files.pythonhosted.org/packages/2e/ea/70ce63780f096e16ce8588efe039d3c4f91deb1dc01e9c73a287939c79a6/cffi-1.17.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a1ed2dd2972641495a3ec98445e09766f077aee98a1c896dcb4ad0d303628e41", size = 469200, upload-time = "2024-09-04T20:43:57.891Z" }, - { url = "https://files.pythonhosted.org/packages/1c/a0/a4fa9f4f781bda074c3ddd57a572b060fa0df7655d2a4247bbe277200146/cffi-1.17.1-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:46bf43160c1a35f7ec506d254e5c890f3c03648a4dbac12d624e4490a7046cd1", size = 477235, upload-time = "2024-09-04T20:44:00.18Z" }, - { url = "https://files.pythonhosted.org/packages/62/12/ce8710b5b8affbcdd5c6e367217c242524ad17a02fe5beec3ee339f69f85/cffi-1.17.1-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:a24ed04c8ffd54b0729c07cee15a81d964e6fee0e3d4d342a27b020d22959dc6", size = 459721, upload-time = "2024-09-04T20:44:01.585Z" }, - { url = "https://files.pythonhosted.org/packages/ff/6b/d45873c5e0242196f042d555526f92aa9e0c32355a1be1ff8c27f077fd37/cffi-1.17.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:610faea79c43e44c71e1ec53a554553fa22321b65fae24889706c0a84d4ad86d", size = 467242, upload-time = "2024-09-04T20:44:03.467Z" }, - { url = "https://files.pythonhosted.org/packages/1a/52/d9a0e523a572fbccf2955f5abe883cfa8bcc570d7faeee06336fbd50c9fc/cffi-1.17.1-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:a9b15d491f3ad5d692e11f6b71f7857e7835eb677955c00cc0aefcd0669adaf6", size = 477999, upload-time = "2024-09-04T20:44:05.023Z" }, - { url = "https://files.pythonhosted.org/packages/44/74/f2a2460684a1a2d00ca799ad880d54652841a780c4c97b87754f660c7603/cffi-1.17.1-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:de2ea4b5833625383e464549fec1bc395c1bdeeb5f25c4a3a82b5a8c756ec22f", size = 454242, upload-time = "2024-09-04T20:44:06.444Z" }, - { url = "https://files.pythonhosted.org/packages/f8/4a/34599cac7dfcd888ff54e801afe06a19c17787dfd94495ab0c8d35fe99fb/cffi-1.17.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:fc48c783f9c87e60831201f2cce7f3b2e4846bf4d8728eabe54d60700b318a0b", size = 478604, upload-time = "2024-09-04T20:44:08.206Z" }, - { url = "https://files.pythonhosted.org/packages/34/33/e1b8a1ba29025adbdcda5fb3a36f94c03d771c1b7b12f726ff7fef2ebe36/cffi-1.17.1-cp311-cp311-win32.whl", hash = "sha256:85a950a4ac9c359340d5963966e3e0a94a676bd6245a4b55bc43949eee26a655", size = 171727, upload-time = "2024-09-04T20:44:09.481Z" }, - { url = "https://files.pythonhosted.org/packages/3d/97/50228be003bb2802627d28ec0627837ac0bf35c90cf769812056f235b2d1/cffi-1.17.1-cp311-cp311-win_amd64.whl", hash = "sha256:caaf0640ef5f5517f49bc275eca1406b0ffa6aa184892812030f04c2abf589a0", size = 181400, upload-time = "2024-09-04T20:44:10.873Z" }, - { url = "https://files.pythonhosted.org/packages/5a/84/e94227139ee5fb4d600a7a4927f322e1d4aea6fdc50bd3fca8493caba23f/cffi-1.17.1-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:805b4371bf7197c329fcb3ead37e710d1bca9da5d583f5073b799d5c5bd1eee4", size = 183178, upload-time = "2024-09-04T20:44:12.232Z" }, - { url = "https://files.pythonhosted.org/packages/da/ee/fb72c2b48656111c4ef27f0f91da355e130a923473bf5ee75c5643d00cca/cffi-1.17.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:733e99bc2df47476e3848417c5a4540522f234dfd4ef3ab7fafdf555b082ec0c", size = 178840, upload-time = "2024-09-04T20:44:13.739Z" }, - { url = "https://files.pythonhosted.org/packages/cc/b6/db007700f67d151abadf508cbfd6a1884f57eab90b1bb985c4c8c02b0f28/cffi-1.17.1-cp312-cp312-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1257bdabf294dceb59f5e70c64a3e2f462c30c7ad68092d01bbbfb1c16b1ba36", size = 454803, upload-time = "2024-09-04T20:44:15.231Z" }, - { url = "https://files.pythonhosted.org/packages/1a/df/f8d151540d8c200eb1c6fba8cd0dfd40904f1b0682ea705c36e6c2e97ab3/cffi-1.17.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:da95af8214998d77a98cc14e3a3bd00aa191526343078b530ceb0bd710fb48a5", size = 478850, upload-time = "2024-09-04T20:44:17.188Z" }, - { url = "https://files.pythonhosted.org/packages/28/c0/b31116332a547fd2677ae5b78a2ef662dfc8023d67f41b2a83f7c2aa78b1/cffi-1.17.1-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d63afe322132c194cf832bfec0dc69a99fb9bb6bbd550f161a49e9e855cc78ff", size = 485729, upload-time = "2024-09-04T20:44:18.688Z" }, - { url = "https://files.pythonhosted.org/packages/91/2b/9a1ddfa5c7f13cab007a2c9cc295b70fbbda7cb10a286aa6810338e60ea1/cffi-1.17.1-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f79fc4fc25f1c8698ff97788206bb3c2598949bfe0fef03d299eb1b5356ada99", size = 471256, upload-time = "2024-09-04T20:44:20.248Z" }, - { url = "https://files.pythonhosted.org/packages/b2/d5/da47df7004cb17e4955df6a43d14b3b4ae77737dff8bf7f8f333196717bf/cffi-1.17.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b62ce867176a75d03a665bad002af8e6d54644fad99a3c70905c543130e39d93", size = 479424, upload-time = "2024-09-04T20:44:21.673Z" }, - { url = "https://files.pythonhosted.org/packages/0b/ac/2a28bcf513e93a219c8a4e8e125534f4f6db03e3179ba1c45e949b76212c/cffi-1.17.1-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:386c8bf53c502fff58903061338ce4f4950cbdcb23e2902d86c0f722b786bbe3", size = 484568, upload-time = "2024-09-04T20:44:23.245Z" }, - { url = "https://files.pythonhosted.org/packages/d4/38/ca8a4f639065f14ae0f1d9751e70447a261f1a30fa7547a828ae08142465/cffi-1.17.1-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:4ceb10419a9adf4460ea14cfd6bc43d08701f0835e979bf821052f1805850fe8", size = 488736, upload-time = "2024-09-04T20:44:24.757Z" }, - { url = "https://files.pythonhosted.org/packages/86/c5/28b2d6f799ec0bdecf44dced2ec5ed43e0eb63097b0f58c293583b406582/cffi-1.17.1-cp312-cp312-win32.whl", hash = "sha256:a08d7e755f8ed21095a310a693525137cfe756ce62d066e53f502a83dc550f65", size = 172448, upload-time = "2024-09-04T20:44:26.208Z" }, - { url = "https://files.pythonhosted.org/packages/50/b9/db34c4755a7bd1cb2d1603ac3863f22bcecbd1ba29e5ee841a4bc510b294/cffi-1.17.1-cp312-cp312-win_amd64.whl", hash = "sha256:51392eae71afec0d0c8fb1a53b204dbb3bcabcb3c9b807eedf3e1e6ccf2de903", size = 181976, upload-time = "2024-09-04T20:44:27.578Z" }, + { url = "https://files.pythonhosted.org/packages/ea/47/4f61023ea636104d4f16ab488e268b93008c3d0bb76893b1b31db1f96802/cffi-2.0.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:6d02d6655b0e54f54c4ef0b94eb6be0607b70853c45ce98bd278dc7de718be5d", size = 185271, upload-time = "2025-09-08T23:22:44.795Z" }, + { url = "https://files.pythonhosted.org/packages/df/a2/781b623f57358e360d62cdd7a8c681f074a71d445418a776eef0aadb4ab4/cffi-2.0.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:8eca2a813c1cb7ad4fb74d368c2ffbbb4789d377ee5bb8df98373c2cc0dee76c", size = 181048, upload-time = "2025-09-08T23:22:45.938Z" }, + { url = "https://files.pythonhosted.org/packages/ff/df/a4f0fbd47331ceeba3d37c2e51e9dfc9722498becbeec2bd8bc856c9538a/cffi-2.0.0-cp312-cp312-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:21d1152871b019407d8ac3985f6775c079416c282e431a4da6afe7aefd2bccbe", size = 212529, upload-time = "2025-09-08T23:22:47.349Z" }, + { url = "https://files.pythonhosted.org/packages/d5/72/12b5f8d3865bf0f87cf1404d8c374e7487dcf097a1c91c436e72e6badd83/cffi-2.0.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:b21e08af67b8a103c71a250401c78d5e0893beff75e28c53c98f4de42f774062", size = 220097, upload-time = "2025-09-08T23:22:48.677Z" }, + { url = "https://files.pythonhosted.org/packages/c2/95/7a135d52a50dfa7c882ab0ac17e8dc11cec9d55d2c18dda414c051c5e69e/cffi-2.0.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:1e3a615586f05fc4065a8b22b8152f0c1b00cdbc60596d187c2a74f9e3036e4e", size = 207983, upload-time = "2025-09-08T23:22:50.06Z" }, + { url = "https://files.pythonhosted.org/packages/3a/c8/15cb9ada8895957ea171c62dc78ff3e99159ee7adb13c0123c001a2546c1/cffi-2.0.0-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:81afed14892743bbe14dacb9e36d9e0e504cd204e0b165062c488942b9718037", size = 206519, upload-time = "2025-09-08T23:22:51.364Z" }, + { url = "https://files.pythonhosted.org/packages/78/2d/7fa73dfa841b5ac06c7b8855cfc18622132e365f5b81d02230333ff26e9e/cffi-2.0.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:3e17ed538242334bf70832644a32a7aae3d83b57567f9fd60a26257e992b79ba", size = 219572, upload-time = "2025-09-08T23:22:52.902Z" }, + { url = "https://files.pythonhosted.org/packages/07/e0/267e57e387b4ca276b90f0434ff88b2c2241ad72b16d31836adddfd6031b/cffi-2.0.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3925dd22fa2b7699ed2617149842d2e6adde22b262fcbfada50e3d195e4b3a94", size = 222963, upload-time = "2025-09-08T23:22:54.518Z" }, + { url = "https://files.pythonhosted.org/packages/b6/75/1f2747525e06f53efbd878f4d03bac5b859cbc11c633d0fb81432d98a795/cffi-2.0.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:2c8f814d84194c9ea681642fd164267891702542f028a15fc97d4674b6206187", size = 221361, upload-time = "2025-09-08T23:22:55.867Z" }, + { url = "https://files.pythonhosted.org/packages/7b/2b/2b6435f76bfeb6bbf055596976da087377ede68df465419d192acf00c437/cffi-2.0.0-cp312-cp312-win32.whl", hash = "sha256:da902562c3e9c550df360bfa53c035b2f241fed6d9aef119048073680ace4a18", size = 172932, upload-time = "2025-09-08T23:22:57.188Z" }, + { url = "https://files.pythonhosted.org/packages/f8/ed/13bd4418627013bec4ed6e54283b1959cf6db888048c7cf4b4c3b5b36002/cffi-2.0.0-cp312-cp312-win_amd64.whl", hash = "sha256:da68248800ad6320861f129cd9c1bf96ca849a2771a59e0344e88681905916f5", size = 183557, upload-time = "2025-09-08T23:22:58.351Z" }, + { url = "https://files.pythonhosted.org/packages/95/31/9f7f93ad2f8eff1dbc1c3656d7ca5bfd8fb52c9d786b4dcf19b2d02217fa/cffi-2.0.0-cp312-cp312-win_arm64.whl", hash = "sha256:4671d9dd5ec934cb9a73e7ee9676f9362aba54f7f34910956b84d727b0d73fb6", size = 177762, upload-time = "2025-09-08T23:22:59.668Z" }, ] [[package]] name = "charset-normalizer" -version = "3.4.2" +version = "3.4.7" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/e4/33/89c2ced2b67d1c2a61c19c6751aa8902d46ce3dacb23600a283619f5a12d/charset_normalizer-3.4.2.tar.gz", hash = "sha256:5baececa9ecba31eff645232d59845c07aa030f0c81ee70184a90d35099a0e63", size = 126367, upload-time = "2025-05-02T08:34:42.01Z" } +sdist = { url = "https://files.pythonhosted.org/packages/e7/a1/67fe25fac3c7642725500a3f6cfe5821ad557c3abb11c9d20d12c7008d3e/charset_normalizer-3.4.7.tar.gz", hash = "sha256:ae89db9e5f98a11a4bf50407d4363e7b09b31e55bc117b4f7d80aab97ba009e5", size = 144271, upload-time = "2026-04-02T09:28:39.342Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/05/85/4c40d00dcc6284a1c1ad5de5e0996b06f39d8232f1031cd23c2f5c07ee86/charset_normalizer-3.4.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:be1e352acbe3c78727a16a455126d9ff83ea2dfdcbc83148d2982305a04714c2", size = 198794, upload-time = "2025-05-02T08:32:11.945Z" }, - { url = "https://files.pythonhosted.org/packages/41/d9/7a6c0b9db952598e97e93cbdfcb91bacd89b9b88c7c983250a77c008703c/charset_normalizer-3.4.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:aa88ca0b1932e93f2d961bf3addbb2db902198dca337d88c89e1559e066e7645", size = 142846, upload-time = "2025-05-02T08:32:13.946Z" }, - { url = "https://files.pythonhosted.org/packages/66/82/a37989cda2ace7e37f36c1a8ed16c58cf48965a79c2142713244bf945c89/charset_normalizer-3.4.2-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d524ba3f1581b35c03cb42beebab4a13e6cdad7b36246bd22541fa585a56cccd", size = 153350, upload-time = "2025-05-02T08:32:15.873Z" }, - { url = "https://files.pythonhosted.org/packages/df/68/a576b31b694d07b53807269d05ec3f6f1093e9545e8607121995ba7a8313/charset_normalizer-3.4.2-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:28a1005facc94196e1fb3e82a3d442a9d9110b8434fc1ded7a24a2983c9888d8", size = 145657, upload-time = "2025-05-02T08:32:17.283Z" }, - { url = "https://files.pythonhosted.org/packages/92/9b/ad67f03d74554bed3aefd56fe836e1623a50780f7c998d00ca128924a499/charset_normalizer-3.4.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fdb20a30fe1175ecabed17cbf7812f7b804b8a315a25f24678bcdf120a90077f", size = 147260, upload-time = "2025-05-02T08:32:18.807Z" }, - { url = "https://files.pythonhosted.org/packages/a6/e6/8aebae25e328160b20e31a7e9929b1578bbdc7f42e66f46595a432f8539e/charset_normalizer-3.4.2-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:0f5d9ed7f254402c9e7d35d2f5972c9bbea9040e99cd2861bd77dc68263277c7", size = 149164, upload-time = "2025-05-02T08:32:20.333Z" }, - { url = "https://files.pythonhosted.org/packages/8b/f2/b3c2f07dbcc248805f10e67a0262c93308cfa149a4cd3d1fe01f593e5fd2/charset_normalizer-3.4.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:efd387a49825780ff861998cd959767800d54f8308936b21025326de4b5a42b9", size = 144571, upload-time = "2025-05-02T08:32:21.86Z" }, - { url = "https://files.pythonhosted.org/packages/60/5b/c3f3a94bc345bc211622ea59b4bed9ae63c00920e2e8f11824aa5708e8b7/charset_normalizer-3.4.2-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:f0aa37f3c979cf2546b73e8222bbfa3dc07a641585340179d768068e3455e544", size = 151952, upload-time = "2025-05-02T08:32:23.434Z" }, - { url = "https://files.pythonhosted.org/packages/e2/4d/ff460c8b474122334c2fa394a3f99a04cf11c646da895f81402ae54f5c42/charset_normalizer-3.4.2-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:e70e990b2137b29dc5564715de1e12701815dacc1d056308e2b17e9095372a82", size = 155959, upload-time = "2025-05-02T08:32:24.993Z" }, - { url = "https://files.pythonhosted.org/packages/a2/2b/b964c6a2fda88611a1fe3d4c400d39c66a42d6c169c924818c848f922415/charset_normalizer-3.4.2-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:0c8c57f84ccfc871a48a47321cfa49ae1df56cd1d965a09abe84066f6853b9c0", size = 153030, upload-time = "2025-05-02T08:32:26.435Z" }, - { url = "https://files.pythonhosted.org/packages/59/2e/d3b9811db26a5ebf444bc0fa4f4be5aa6d76fc6e1c0fd537b16c14e849b6/charset_normalizer-3.4.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:6b66f92b17849b85cad91259efc341dce9c1af48e2173bf38a85c6329f1033e5", size = 148015, upload-time = "2025-05-02T08:32:28.376Z" }, - { url = "https://files.pythonhosted.org/packages/90/07/c5fd7c11eafd561bb51220d600a788f1c8d77c5eef37ee49454cc5c35575/charset_normalizer-3.4.2-cp311-cp311-win32.whl", hash = "sha256:daac4765328a919a805fa5e2720f3e94767abd632ae410a9062dff5412bae65a", size = 98106, upload-time = "2025-05-02T08:32:30.281Z" }, - { url = "https://files.pythonhosted.org/packages/a8/05/5e33dbef7e2f773d672b6d79f10ec633d4a71cd96db6673625838a4fd532/charset_normalizer-3.4.2-cp311-cp311-win_amd64.whl", hash = "sha256:e53efc7c7cee4c1e70661e2e112ca46a575f90ed9ae3fef200f2a25e954f4b28", size = 105402, upload-time = "2025-05-02T08:32:32.191Z" }, - { url = "https://files.pythonhosted.org/packages/d7/a4/37f4d6035c89cac7930395a35cc0f1b872e652eaafb76a6075943754f095/charset_normalizer-3.4.2-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:0c29de6a1a95f24b9a1aa7aefd27d2487263f00dfd55a77719b530788f75cff7", size = 199936, upload-time = "2025-05-02T08:32:33.712Z" }, - { url = "https://files.pythonhosted.org/packages/ee/8a/1a5e33b73e0d9287274f899d967907cd0bf9c343e651755d9307e0dbf2b3/charset_normalizer-3.4.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:cddf7bd982eaa998934a91f69d182aec997c6c468898efe6679af88283b498d3", size = 143790, upload-time = "2025-05-02T08:32:35.768Z" }, - { url = "https://files.pythonhosted.org/packages/66/52/59521f1d8e6ab1482164fa21409c5ef44da3e9f653c13ba71becdd98dec3/charset_normalizer-3.4.2-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:fcbe676a55d7445b22c10967bceaaf0ee69407fbe0ece4d032b6eb8d4565982a", size = 153924, upload-time = "2025-05-02T08:32:37.284Z" }, - { url = "https://files.pythonhosted.org/packages/86/2d/fb55fdf41964ec782febbf33cb64be480a6b8f16ded2dbe8db27a405c09f/charset_normalizer-3.4.2-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:d41c4d287cfc69060fa91cae9683eacffad989f1a10811995fa309df656ec214", size = 146626, upload-time = "2025-05-02T08:32:38.803Z" }, - { url = "https://files.pythonhosted.org/packages/8c/73/6ede2ec59bce19b3edf4209d70004253ec5f4e319f9a2e3f2f15601ed5f7/charset_normalizer-3.4.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4e594135de17ab3866138f496755f302b72157d115086d100c3f19370839dd3a", size = 148567, upload-time = "2025-05-02T08:32:40.251Z" }, - { url = "https://files.pythonhosted.org/packages/09/14/957d03c6dc343c04904530b6bef4e5efae5ec7d7990a7cbb868e4595ee30/charset_normalizer-3.4.2-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:cf713fe9a71ef6fd5adf7a79670135081cd4431c2943864757f0fa3a65b1fafd", size = 150957, upload-time = "2025-05-02T08:32:41.705Z" }, - { url = "https://files.pythonhosted.org/packages/0d/c8/8174d0e5c10ccebdcb1b53cc959591c4c722a3ad92461a273e86b9f5a302/charset_normalizer-3.4.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:a370b3e078e418187da8c3674eddb9d983ec09445c99a3a263c2011993522981", size = 145408, upload-time = "2025-05-02T08:32:43.709Z" }, - { url = "https://files.pythonhosted.org/packages/58/aa/8904b84bc8084ac19dc52feb4f5952c6df03ffb460a887b42615ee1382e8/charset_normalizer-3.4.2-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:a955b438e62efdf7e0b7b52a64dc5c3396e2634baa62471768a64bc2adb73d5c", size = 153399, upload-time = "2025-05-02T08:32:46.197Z" }, - { url = "https://files.pythonhosted.org/packages/c2/26/89ee1f0e264d201cb65cf054aca6038c03b1a0c6b4ae998070392a3ce605/charset_normalizer-3.4.2-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:7222ffd5e4de8e57e03ce2cef95a4c43c98fcb72ad86909abdfc2c17d227fc1b", size = 156815, upload-time = "2025-05-02T08:32:48.105Z" }, - { url = "https://files.pythonhosted.org/packages/fd/07/68e95b4b345bad3dbbd3a8681737b4338ff2c9df29856a6d6d23ac4c73cb/charset_normalizer-3.4.2-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:bee093bf902e1d8fc0ac143c88902c3dfc8941f7ea1d6a8dd2bcb786d33db03d", size = 154537, upload-time = "2025-05-02T08:32:49.719Z" }, - { url = "https://files.pythonhosted.org/packages/77/1a/5eefc0ce04affb98af07bc05f3bac9094513c0e23b0562d64af46a06aae4/charset_normalizer-3.4.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:dedb8adb91d11846ee08bec4c8236c8549ac721c245678282dcb06b221aab59f", size = 149565, upload-time = "2025-05-02T08:32:51.404Z" }, - { url = "https://files.pythonhosted.org/packages/37/a0/2410e5e6032a174c95e0806b1a6585eb21e12f445ebe239fac441995226a/charset_normalizer-3.4.2-cp312-cp312-win32.whl", hash = "sha256:db4c7bf0e07fc3b7d89ac2a5880a6a8062056801b83ff56d8464b70f65482b6c", size = 98357, upload-time = "2025-05-02T08:32:53.079Z" }, - { url = "https://files.pythonhosted.org/packages/6c/4f/c02d5c493967af3eda9c771ad4d2bbc8df6f99ddbeb37ceea6e8716a32bc/charset_normalizer-3.4.2-cp312-cp312-win_amd64.whl", hash = "sha256:5a9979887252a82fefd3d3ed2a8e3b937a7a809f65dcb1e068b090e165bbe99e", size = 105776, upload-time = "2025-05-02T08:32:54.573Z" }, - { url = "https://files.pythonhosted.org/packages/20/94/c5790835a017658cbfabd07f3bfb549140c3ac458cfc196323996b10095a/charset_normalizer-3.4.2-py3-none-any.whl", hash = "sha256:7f56930ab0abd1c45cd15be65cc741c28b1c9a34876ce8c17a2fa107810c0af0", size = 52626, upload-time = "2025-05-02T08:34:40.053Z" }, + { url = "https://files.pythonhosted.org/packages/0c/eb/4fc8d0a7110eb5fc9cc161723a34a8a6c200ce3b4fbf681bc86feee22308/charset_normalizer-3.4.7-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:eca9705049ad3c7345d574e3510665cb2cf844c2f2dcfe675332677f081cbd46", size = 311328, upload-time = "2026-04-02T09:26:24.331Z" }, + { url = "https://files.pythonhosted.org/packages/f8/e3/0fadc706008ac9d7b9b5be6dc767c05f9d3e5df51744ce4cc9605de7b9f4/charset_normalizer-3.4.7-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6178f72c5508bfc5fd446a5905e698c6212932f25bcdd4b47a757a50605a90e2", size = 208061, upload-time = "2026-04-02T09:26:25.568Z" }, + { url = "https://files.pythonhosted.org/packages/42/f0/3dd1045c47f4a4604df85ec18ad093912ae1344ac706993aff91d38773a2/charset_normalizer-3.4.7-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e1421b502d83040e6d7fb2fb18dff63957f720da3d77b2fbd3187ceb63755d7b", size = 229031, upload-time = "2026-04-02T09:26:26.865Z" }, + { url = "https://files.pythonhosted.org/packages/dc/67/675a46eb016118a2fbde5a277a5d15f4f69d5f3f5f338e5ee2f8948fcf43/charset_normalizer-3.4.7-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:edac0f1ab77644605be2cbba52e6b7f630731fc42b34cb0f634be1a6eface56a", size = 225239, upload-time = "2026-04-02T09:26:28.044Z" }, + { url = "https://files.pythonhosted.org/packages/4b/f8/d0118a2f5f23b02cd166fa385c60f9b0d4f9194f574e2b31cef350ad7223/charset_normalizer-3.4.7-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5649fd1c7bade02f320a462fdefd0b4bd3ce036065836d4f42e0de958038e116", size = 216589, upload-time = "2026-04-02T09:26:29.239Z" }, + { url = "https://files.pythonhosted.org/packages/b1/f1/6d2b0b261b6c4ceef0fcb0d17a01cc5bc53586c2d4796fa04b5c540bc13d/charset_normalizer-3.4.7-cp312-cp312-manylinux_2_31_armv7l.whl", hash = "sha256:203104ed3e428044fd943bc4bf45fa73c0730391f9621e37fe39ecf477b128cb", size = 202733, upload-time = "2026-04-02T09:26:30.5Z" }, + { url = "https://files.pythonhosted.org/packages/6f/c0/7b1f943f7e87cc3db9626ba17807d042c38645f0a1d4415c7a14afb5591f/charset_normalizer-3.4.7-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:298930cec56029e05497a76988377cbd7457ba864beeea92ad7e844fe74cd1f1", size = 212652, upload-time = "2026-04-02T09:26:31.709Z" }, + { url = "https://files.pythonhosted.org/packages/38/dd/5a9ab159fe45c6e72079398f277b7d2b523e7f716acc489726115a910097/charset_normalizer-3.4.7-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:708838739abf24b2ceb208d0e22403dd018faeef86ddac04319a62ae884c4f15", size = 211229, upload-time = "2026-04-02T09:26:33.282Z" }, + { url = "https://files.pythonhosted.org/packages/d5/ff/531a1cad5ca855d1c1a8b69cb71abfd6d85c0291580146fda7c82857caa1/charset_normalizer-3.4.7-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:0f7eb884681e3938906ed0434f20c63046eacd0111c4ba96f27b76084cd679f5", size = 203552, upload-time = "2026-04-02T09:26:34.845Z" }, + { url = "https://files.pythonhosted.org/packages/c1/4c/a5fb52d528a8ca41f7598cb619409ece30a169fbdf9cdce592e53b46c3a6/charset_normalizer-3.4.7-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:4dc1e73c36828f982bfe79fadf5919923f8a6f4df2860804db9a98c48824ce8d", size = 230806, upload-time = "2026-04-02T09:26:36.152Z" }, + { url = "https://files.pythonhosted.org/packages/59/7a/071feed8124111a32b316b33ae4de83d36923039ef8cf48120266844285b/charset_normalizer-3.4.7-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:aed52fea0513bac0ccde438c188c8a471c4e0f457c2dd20cdbf6ea7a450046c7", size = 212316, upload-time = "2026-04-02T09:26:37.672Z" }, + { url = "https://files.pythonhosted.org/packages/fd/35/f7dba3994312d7ba508e041eaac39a36b120f32d4c8662b8814dab876431/charset_normalizer-3.4.7-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:fea24543955a6a729c45a73fe90e08c743f0b3334bbf3201e6c4bc1b0c7fa464", size = 227274, upload-time = "2026-04-02T09:26:38.93Z" }, + { url = "https://files.pythonhosted.org/packages/8a/2d/a572df5c9204ab7688ec1edc895a73ebded3b023bb07364710b05dd1c9be/charset_normalizer-3.4.7-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:bb6d88045545b26da47aa879dd4a89a71d1dce0f0e549b1abcb31dfe4a8eac49", size = 218468, upload-time = "2026-04-02T09:26:40.17Z" }, + { url = "https://files.pythonhosted.org/packages/86/eb/890922a8b03a568ca2f336c36585a4713c55d4d67bf0f0c78924be6315ca/charset_normalizer-3.4.7-cp312-cp312-win32.whl", hash = "sha256:2257141f39fe65a3fdf38aeccae4b953e5f3b3324f4ff0daf9f15b8518666a2c", size = 148460, upload-time = "2026-04-02T09:26:41.416Z" }, + { url = "https://files.pythonhosted.org/packages/35/d9/0e7dffa06c5ab081f75b1b786f0aefc88365825dfcd0ac544bdb7b2b6853/charset_normalizer-3.4.7-cp312-cp312-win_amd64.whl", hash = "sha256:5ed6ab538499c8644b8a3e18debabcd7ce684f3fa91cf867521a7a0279cab2d6", size = 159330, upload-time = "2026-04-02T09:26:42.554Z" }, + { url = "https://files.pythonhosted.org/packages/9e/5d/481bcc2a7c88ea6b0878c299547843b2521ccbc40980cb406267088bc701/charset_normalizer-3.4.7-cp312-cp312-win_arm64.whl", hash = "sha256:56be790f86bfb2c98fb742ce566dfb4816e5a83384616ab59c49e0604d49c51d", size = 147828, upload-time = "2026-04-02T09:26:44.075Z" }, + { url = "https://files.pythonhosted.org/packages/db/8f/61959034484a4a7c527811f4721e75d02d653a35afb0b6054474d8185d4c/charset_normalizer-3.4.7-py3-none-any.whl", hash = "sha256:3dce51d0f5e7951f8bb4900c257dad282f49190fdbebecd4ba99bcc41fef404d", size = 61958, upload-time = "2026-04-02T09:28:37.794Z" }, ] [[package]] name = "click" -version = "8.2.1" +version = "8.4.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "colorama", marker = "sys_platform == 'win32'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/60/6c/8ca2efa64cf75a977a0d7fac081354553ebe483345c734fb6b6515d96bbc/click-8.2.1.tar.gz", hash = "sha256:27c491cc05d968d271d5a1db13e3b5a184636d9d930f148c50b038f0d0646202", size = 286342, upload-time = "2025-05-20T23:19:49.832Z" } +sdist = { url = "https://files.pythonhosted.org/packages/76/d4/81420972a676e8ffea40450d8c8c92943e7218a78fe9b64359836cc9876b/click-8.4.2.tar.gz", hash = "sha256:9a6cea6e60b17ebe0a44c5cc636d94f09bd66142c1cd7d8b4cd731c4917a15f6", size = 338000, upload-time = "2026-06-24T17:45:15.148Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/85/32/10bb5764d90a8eee674e9dc6f4db6a0ab47c8c4d0d83c27f7c39ac415a4d/click-8.2.1-py3-none-any.whl", hash = "sha256:61a3265b914e850b85317d0b3109c7f8cd35a670f963866005d6ef1d5175a12b", size = 102215, upload-time = "2025-05-20T23:19:47.796Z" }, -] - -[[package]] -name = "cloudpickle" -version = "3.1.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/52/39/069100b84d7418bc358d81669d5748efb14b9cceacd2f9c75f550424132f/cloudpickle-3.1.1.tar.gz", hash = "sha256:b216fa8ae4019d5482a8ac3c95d8f6346115d8835911fd4aefd1a445e4242c64", size = 22113, upload-time = "2025-01-14T17:02:05.085Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/7e/e8/64c37fadfc2816a7701fa8a6ed8d87327c7d54eacfbfb6edab14a2f2be75/cloudpickle-3.1.1-py3-none-any.whl", hash = "sha256:c8c5a44295039331ee9dad40ba100a9c7297b6f988e50e87ccdf3765a668350e", size = 20992, upload-time = "2025-01-14T17:02:02.417Z" }, + { url = "https://files.pythonhosted.org/packages/fb/e2/79c688af8b210d232694e31e59da9f6ec747bae31c3f5946e4e9b98860d5/click-8.4.2-py3-none-any.whl", hash = "sha256:e6f9f66136c816745b9d65817da91d61d957fb16e02e4dcd0552553c5a197b76", size = 119243, upload-time = "2026-06-24T17:45:13.73Z" }, ] [[package]] name = "codespell" -version = "2.4.1" +version = "2.4.2" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/15/e0/709453393c0ea77d007d907dd436b3ee262e28b30995ea1aa36c6ffbccaf/codespell-2.4.1.tar.gz", hash = "sha256:299fcdcb09d23e81e35a671bbe746d5ad7e8385972e65dbb833a2eaac33c01e5", size = 344740, upload-time = "2025-01-28T18:52:39.411Z" } +sdist = { url = "https://files.pythonhosted.org/packages/2d/9d/1d0903dff693160f893ca6abcabad545088e7a2ee0a6deae7c24e958be69/codespell-2.4.2.tar.gz", hash = "sha256:3c33be9ae34543807f088aeb4832dfad8cb2dae38da61cac0a7045dd376cfdf3", size = 352058, upload-time = "2026-03-05T18:10:42.936Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/20/01/b394922252051e97aab231d416c86da3d8a6d781eeadcdca1082867de64e/codespell-2.4.1-py3-none-any.whl", hash = "sha256:3dadafa67df7e4a3dbf51e0d7315061b80d265f9552ebd699b3dd6834b47e425", size = 344501, upload-time = "2025-01-28T18:52:37.057Z" }, + { url = "https://files.pythonhosted.org/packages/42/a1/52fa05533e95fe45bcc09bcf8a503874b1c08f221a4e35608017e0938f55/codespell-2.4.2-py3-none-any.whl", hash = "sha256:97e0c1060cf46bd1d5db89a936c98db8c2b804e1fdd4b5c645e82a1ec6b1f886", size = 353715, upload-time = "2026-03-05T18:10:41.398Z" }, ] [[package]] @@ -335,109 +102,248 @@ wheels = [ ] [[package]] -name = "contourpy" -version = "1.3.2" +name = "comma-deps-acados" +version = "0.2.2.post95" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "numpy" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/66/54/eb9bfc647b19f2009dd5c7f5ec51c4e6ca831725f1aea7a993034f483147/contourpy-1.3.2.tar.gz", hash = "sha256:b6945942715a034c671b7fc54f9588126b0b8bf23db2696e3ca8328f3ff0ab54", size = 13466130, upload-time = "2025-04-15T17:47:53.79Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/b3/b9/ede788a0b56fc5b071639d06c33cb893f68b1178938f3425debebe2dab78/contourpy-1.3.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:6a37a2fb93d4df3fc4c0e363ea4d16f83195fc09c891bc8ce072b9d084853445", size = 269636, upload-time = "2025-04-15T17:35:54.473Z" }, - { url = "https://files.pythonhosted.org/packages/e6/75/3469f011d64b8bbfa04f709bfc23e1dd71be54d05b1b083be9f5b22750d1/contourpy-1.3.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:b7cd50c38f500bbcc9b6a46643a40e0913673f869315d8e70de0438817cb7773", size = 254636, upload-time = "2025-04-15T17:35:58.283Z" }, - { url = "https://files.pythonhosted.org/packages/8d/2f/95adb8dae08ce0ebca4fd8e7ad653159565d9739128b2d5977806656fcd2/contourpy-1.3.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d6658ccc7251a4433eebd89ed2672c2ed96fba367fd25ca9512aa92a4b46c4f1", size = 313053, upload-time = "2025-04-15T17:36:03.235Z" }, - { url = "https://files.pythonhosted.org/packages/c3/a6/8ccf97a50f31adfa36917707fe39c9a0cbc24b3bbb58185577f119736cc9/contourpy-1.3.2-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:70771a461aaeb335df14deb6c97439973d253ae70660ca085eec25241137ef43", size = 352985, upload-time = "2025-04-15T17:36:08.275Z" }, - { url = "https://files.pythonhosted.org/packages/1d/b6/7925ab9b77386143f39d9c3243fdd101621b4532eb126743201160ffa7e6/contourpy-1.3.2-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:65a887a6e8c4cd0897507d814b14c54a8c2e2aa4ac9f7686292f9769fcf9a6ab", size = 323750, upload-time = "2025-04-15T17:36:13.29Z" }, - { url = "https://files.pythonhosted.org/packages/c2/f3/20c5d1ef4f4748e52d60771b8560cf00b69d5c6368b5c2e9311bcfa2a08b/contourpy-1.3.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3859783aefa2b8355697f16642695a5b9792e7a46ab86da1118a4a23a51a33d7", size = 326246, upload-time = "2025-04-15T17:36:18.329Z" }, - { url = "https://files.pythonhosted.org/packages/8c/e5/9dae809e7e0b2d9d70c52b3d24cba134dd3dad979eb3e5e71f5df22ed1f5/contourpy-1.3.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:eab0f6db315fa4d70f1d8ab514e527f0366ec021ff853d7ed6a2d33605cf4b83", size = 1308728, upload-time = "2025-04-15T17:36:33.878Z" }, - { url = "https://files.pythonhosted.org/packages/e2/4a/0058ba34aeea35c0b442ae61a4f4d4ca84d6df8f91309bc2d43bb8dd248f/contourpy-1.3.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:d91a3ccc7fea94ca0acab82ceb77f396d50a1f67412efe4c526f5d20264e6ecd", size = 1375762, upload-time = "2025-04-15T17:36:51.295Z" }, - { url = "https://files.pythonhosted.org/packages/09/33/7174bdfc8b7767ef2c08ed81244762d93d5c579336fc0b51ca57b33d1b80/contourpy-1.3.2-cp311-cp311-win32.whl", hash = "sha256:1c48188778d4d2f3d48e4643fb15d8608b1d01e4b4d6b0548d9b336c28fc9b6f", size = 178196, upload-time = "2025-04-15T17:36:55.002Z" }, - { url = "https://files.pythonhosted.org/packages/5e/fe/4029038b4e1c4485cef18e480b0e2cd2d755448bb071eb9977caac80b77b/contourpy-1.3.2-cp311-cp311-win_amd64.whl", hash = "sha256:5ebac872ba09cb8f2131c46b8739a7ff71de28a24c869bcad554477eb089a878", size = 222017, upload-time = "2025-04-15T17:36:58.576Z" }, - { url = "https://files.pythonhosted.org/packages/34/f7/44785876384eff370c251d58fd65f6ad7f39adce4a093c934d4a67a7c6b6/contourpy-1.3.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:4caf2bcd2969402bf77edc4cb6034c7dd7c0803213b3523f111eb7460a51b8d2", size = 271580, upload-time = "2025-04-15T17:37:03.105Z" }, - { url = "https://files.pythonhosted.org/packages/93/3b/0004767622a9826ea3d95f0e9d98cd8729015768075d61f9fea8eeca42a8/contourpy-1.3.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:82199cb78276249796419fe36b7386bd8d2cc3f28b3bc19fe2454fe2e26c4c15", size = 255530, upload-time = "2025-04-15T17:37:07.026Z" }, - { url = "https://files.pythonhosted.org/packages/e7/bb/7bd49e1f4fa805772d9fd130e0d375554ebc771ed7172f48dfcd4ca61549/contourpy-1.3.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:106fab697af11456fcba3e352ad50effe493a90f893fca6c2ca5c033820cea92", size = 307688, upload-time = "2025-04-15T17:37:11.481Z" }, - { url = "https://files.pythonhosted.org/packages/fc/97/e1d5dbbfa170725ef78357a9a0edc996b09ae4af170927ba8ce977e60a5f/contourpy-1.3.2-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d14f12932a8d620e307f715857107b1d1845cc44fdb5da2bc8e850f5ceba9f87", size = 347331, upload-time = "2025-04-15T17:37:18.212Z" }, - { url = "https://files.pythonhosted.org/packages/6f/66/e69e6e904f5ecf6901be3dd16e7e54d41b6ec6ae3405a535286d4418ffb4/contourpy-1.3.2-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:532fd26e715560721bb0d5fc7610fce279b3699b018600ab999d1be895b09415", size = 318963, upload-time = "2025-04-15T17:37:22.76Z" }, - { url = "https://files.pythonhosted.org/packages/a8/32/b8a1c8965e4f72482ff2d1ac2cd670ce0b542f203c8e1d34e7c3e6925da7/contourpy-1.3.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f26b383144cf2d2c29f01a1e8170f50dacf0eac02d64139dcd709a8ac4eb3cfe", size = 323681, upload-time = "2025-04-15T17:37:33.001Z" }, - { url = "https://files.pythonhosted.org/packages/30/c6/12a7e6811d08757c7162a541ca4c5c6a34c0f4e98ef2b338791093518e40/contourpy-1.3.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:c49f73e61f1f774650a55d221803b101d966ca0c5a2d6d5e4320ec3997489441", size = 1308674, upload-time = "2025-04-15T17:37:48.64Z" }, - { url = "https://files.pythonhosted.org/packages/2a/8a/bebe5a3f68b484d3a2b8ffaf84704b3e343ef1addea528132ef148e22b3b/contourpy-1.3.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:3d80b2c0300583228ac98d0a927a1ba6a2ba6b8a742463c564f1d419ee5b211e", size = 1380480, upload-time = "2025-04-15T17:38:06.7Z" }, - { url = "https://files.pythonhosted.org/packages/34/db/fcd325f19b5978fb509a7d55e06d99f5f856294c1991097534360b307cf1/contourpy-1.3.2-cp312-cp312-win32.whl", hash = "sha256:90df94c89a91b7362e1142cbee7568f86514412ab8a2c0d0fca72d7e91b62912", size = 178489, upload-time = "2025-04-15T17:38:10.338Z" }, - { url = "https://files.pythonhosted.org/packages/01/c8/fadd0b92ffa7b5eb5949bf340a63a4a496a6930a6c37a7ba0f12acb076d6/contourpy-1.3.2-cp312-cp312-win_amd64.whl", hash = "sha256:8c942a01d9163e2e5cfb05cb66110121b8d07ad438a17f9e766317bcb62abf73", size = 223042, upload-time = "2025-04-15T17:38:14.239Z" }, - { url = "https://files.pythonhosted.org/packages/ff/c0/91f1215d0d9f9f343e4773ba6c9b89e8c0cc7a64a6263f21139da639d848/contourpy-1.3.2-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:5f5964cdad279256c084b69c3f412b7801e15356b16efa9d78aa974041903da0", size = 266807, upload-time = "2025-04-15T17:45:15.535Z" }, - { url = "https://files.pythonhosted.org/packages/d4/79/6be7e90c955c0487e7712660d6cead01fa17bff98e0ea275737cc2bc8e71/contourpy-1.3.2-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:49b65a95d642d4efa8f64ba12558fcb83407e58a2dfba9d796d77b63ccfcaff5", size = 318729, upload-time = "2025-04-15T17:45:20.166Z" }, - { url = "https://files.pythonhosted.org/packages/87/68/7f46fb537958e87427d98a4074bcde4b67a70b04900cfc5ce29bc2f556c1/contourpy-1.3.2-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:8c5acb8dddb0752bf252e01a3035b21443158910ac16a3b0d20e7fed7d534ce5", size = 221791, upload-time = "2025-04-15T17:45:24.794Z" }, + { url = "https://files.pythonhosted.org/packages/58/83/e76d3f89de07a672c5fc452d81b6f00f972721342eb75de2171d2c3a8b19/comma_deps_acados-0.2.2.post95-py3-none-macosx_11_0_arm64.whl", hash = "sha256:fd7c583ac2a33b414540c0601173e3a9c28c5d8f825cb24736c64e3c07271f56", size = 10631724, upload-time = "2026-06-24T23:58:31.726Z" }, + { url = "https://files.pythonhosted.org/packages/64/96/4b8e50a153dcb5f34628f854dc58774588b8dbfb26b6bedd0b99acb4aa71/comma_deps_acados-0.2.2.post95-py3-none-manylinux_2_28_aarch64.whl", hash = "sha256:1f47c3a665193937c993d3ee15989be5ba75eb427c9733fe1b9e800bf33c56aa", size = 11663713, upload-time = "2026-06-24T23:58:33.725Z" }, + { url = "https://files.pythonhosted.org/packages/1b/2f/bf57b9656e86950ba19c7a88992fccc0abb89878f9c30fb1b2252d57f0a7/comma_deps_acados-0.2.2.post95-py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:00b49d5b691fa97d07fa5e5b842e0d2e1a6faa6856d2a081eefcee649f93329b", size = 13167209, upload-time = "2026-06-24T23:58:35.941Z" }, +] + +[[package]] +name = "comma-deps-bootstrap-icons" +version = "1.10.5.0.post95" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/44/0b/bb713dd4bed94b0b2b21657b7337e264953bd785a2b2f5c1b0706cdcde29/comma_deps_bootstrap_icons-1.10.5.0.post95-py3-none-any.whl", hash = "sha256:d59fc8d3e642e00f83d7a4854164f1dee21c3d17c726d5537b1b72b149f5788b", size = 386001, upload-time = "2026-06-24T23:58:37.84Z" }, +] + +[[package]] +name = "comma-deps-bzip2" +version = "1.0.8.post95" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f8/ac/539d76e9bcebbc53d62274a19c47522b118dce3261fc6baea045f93c98b6/comma_deps_bzip2-1.0.8.post95-py3-none-macosx_11_0_arm64.whl", hash = "sha256:be466743b7fc56fa18c2c389a46bdeb0fc885cf3cf39b779d748ce540609ebd5", size = 42832, upload-time = "2026-06-24T23:58:39.592Z" }, + { url = "https://files.pythonhosted.org/packages/a1/fe/5206bd6d716022cea259c4878c6a1927ab3555f4caa48a74efaa83d8f418/comma_deps_bzip2-1.0.8.post95-py3-none-manylinux_2_28_aarch64.whl", hash = "sha256:7c015d720cc5462f87062b4482c54684de6a237b4edb60612c2f58721413682f", size = 38629, upload-time = "2026-06-24T23:58:40.496Z" }, + { url = "https://files.pythonhosted.org/packages/39/0e/78218f9a645ad9d27000153795d6819b3b52ca62d882aa46a413e40887be/comma_deps_bzip2-1.0.8.post95-py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:3188a197aaf3efbfac975193887c59600b91a3b4eb7f62cc975377133cd48834", size = 36271, upload-time = "2026-06-24T23:58:41.2Z" }, +] + +[[package]] +name = "comma-deps-capnproto" +version = "1.0.1.post93" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/19/a6/97c22a112e23f530db28f8ecf7b191ec16685d282fdbe892dff7437bdf6d/comma_deps_capnproto-1.0.1.post93-py3-none-macosx_11_0_arm64.whl", hash = "sha256:6717e8e34ef12116502f244b23f092984c1d15afa4e40b956450b74a0d4d2520", size = 2407330, upload-time = "2026-07-08T19:30:41.395Z" }, + { url = "https://files.pythonhosted.org/packages/6d/f2/79a15ff5f2c97a741923a97357f6a4235e4ced928ba1d4079d01c66df4b0/comma_deps_capnproto-1.0.1.post93-py3-none-manylinux_2_28_aarch64.whl", hash = "sha256:a70349446e2ec17b281ebaaae02ca4c35495f4210043c716c55139a05a826090", size = 2506341, upload-time = "2026-07-08T19:30:45.607Z" }, + { url = "https://files.pythonhosted.org/packages/80/a9/f61fe62045c4ea867f51f2d74b4edfabd6c272c62a3281a9f1f33825a725/comma_deps_capnproto-1.0.1.post93-py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:f98cdba8f8c7f08a7a0c0a4b7cc0bfcf515e29ad8f1b5cb8eda4e253bef5e6e3", size = 2590769, upload-time = "2026-07-08T19:30:49.728Z" }, +] + +[[package]] +name = "comma-deps-catch2" +version = "2.13.10.post93" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/88/ee/b4ef7758d04a024775d49558ca930fec19aa37cd691ad9182b7141f4d4d7/comma_deps_catch2-2.13.10.post93-py3-none-any.whl", hash = "sha256:8f23293251b5db48c08885d8816ca252b3fb11b0c1c26775bae36e8b217e865e", size = 137085, upload-time = "2026-07-08T19:30:53.44Z" }, +] + +[[package]] +name = "comma-deps-eigen" +version = "3.4.0.post93" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fa/3c/b262d6103a3b7a5cb0296b821eb4f1385b349e527bba75d7efe057cea802/comma_deps_eigen-3.4.0.post93-py3-none-macosx_11_0_arm64.whl", hash = "sha256:f90433cea3f59f1b9ed58bd92d0f1b55721eff8b473d579ed40fa2fcdc2c1787", size = 2275895, upload-time = "2026-07-08T19:31:08.983Z" }, + { url = "https://files.pythonhosted.org/packages/00/a1/b9bf332a096267ff26ebd546b104d9a92b905857c59bae899794897c790b/comma_deps_eigen-3.4.0.post93-py3-none-manylinux_2_28_aarch64.whl", hash = "sha256:3169d82b825ca8accdae5f3e1a9cddd9f28f8bd5f66e4353fedae68b23f13cdb", size = 2275897, upload-time = "2026-07-08T19:31:12.66Z" }, + { url = "https://files.pythonhosted.org/packages/bd/c6/1132467acd1257ea159cf4608c6f00ef0b3ca353fd86aaced0d76dcce62c/comma_deps_eigen-3.4.0.post93-py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:d0b042c817070a0124b8c0e78b87ff5e8b44db21a1abea740afe7115f5bd8447", size = 2275900, upload-time = "2026-07-08T19:31:16.352Z" }, +] + +[[package]] +name = "comma-deps-ffmpeg" +version = "7.1.0.post94" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7d/5c/47e10049fd96b581e8ddc9fba31c3397562732fcc99db6c062690e862300/comma_deps_ffmpeg-7.1.0.post94-py3-none-macosx_11_0_arm64.whl", hash = "sha256:2e87b4dd0fb0fc25d6992167ee266b5c9e92305aefa3d343ddd22a17219363b8", size = 7329953, upload-time = "2026-07-09T03:07:11.516Z" }, + { url = "https://files.pythonhosted.org/packages/a7/d5/c4edfbbe488983ff45fb6cacab78342fc56cc0f28010a946e8697613ffe2/comma_deps_ffmpeg-7.1.0.post94-py3-none-manylinux_2_28_aarch64.whl", hash = "sha256:7ea34368c5b564cecab0fd77d6423bc15d8f100051648f64ad79a3499f43dafb", size = 4441314, upload-time = "2026-07-09T03:07:15.679Z" }, + { url = "https://files.pythonhosted.org/packages/80/8f/76a876a26572c52d52dbcf8ed39227f5023d343201a32af4b992c4b9f13e/comma_deps_ffmpeg-7.1.0.post94-py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:5b2d6cfbba59ecd673dd0c8bd8eb5a5b3472bdfa025e1063c011e6234877fe84", size = 4685134, upload-time = "2026-07-09T03:07:19.596Z" }, +] + +[[package]] +name = "comma-deps-gcc-arm-none-eabi" +version = "13.2.1.post93" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c0/9f/9a6c7f04faf18fdc4ab3e5b55ecfdbcb3998333a450fd5a1c986af571d15/comma_deps_gcc_arm_none_eabi-13.2.1.post93-py3-none-macosx_11_0_arm64.whl", hash = "sha256:00de06a94ecf4379c79b150d36b3116d0f37bc341bbf1ef2ad850c8a5985eeb1", size = 15238809, upload-time = "2026-07-08T19:31:33.509Z" }, + { url = "https://files.pythonhosted.org/packages/83/94/1cdb11c170b96f2677dfd1be7cfb9a2994d3518555c154f2a131929057da/comma_deps_gcc_arm_none_eabi-13.2.1.post93-py3-none-manylinux_2_28_aarch64.whl", hash = "sha256:de1cf3ff89ea84fac5df62c65d843af877eaa2634439d793f527f0cfeea66e59", size = 17367238, upload-time = "2026-07-08T19:31:38.137Z" }, + { url = "https://files.pythonhosted.org/packages/23/3c/4b2f60274f080b9583da2fdaad54f692f4f8719bd360558d4460d79f8fb4/comma_deps_gcc_arm_none_eabi-13.2.1.post93-py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:3cf7f022ffa1b3d3e20eb32610c7e59f84932e516d9ed11236df787546d82d67", size = 16941134, upload-time = "2026-07-08T19:31:43.102Z" }, +] + +[[package]] +name = "comma-deps-git-lfs" +version = "3.6.1.post93" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/df/62/e06ea6fb98b8cee2686fb409fb28426d902f3318b077cbd78d9bbec0354b/comma_deps_git_lfs-3.6.1.post93-py3-none-macosx_11_0_arm64.whl", hash = "sha256:89cbffd3d6800fa8e366301b98c09c4ccbc973fb59721aa2546b36158b9b64c0", size = 4685107, upload-time = "2026-07-08T19:31:47.273Z" }, + { url = "https://files.pythonhosted.org/packages/ce/cf/f08dc359e8bc7e1b21b7f4a93167a14ac61dc78f1bfb27a0e7554c78cb09/comma_deps_git_lfs-3.6.1.post93-py3-none-manylinux_2_28_aarch64.whl", hash = "sha256:39844960733a3885d99bbfdf4f7b414e7d0bf4b4d56f9d77a88ea10d72f549c5", size = 4485276, upload-time = "2026-07-08T19:31:51.253Z" }, + { url = "https://files.pythonhosted.org/packages/2f/af/3dfae2a56320165b45ceab0d7a2c6dea69cc5766928f408d17997ff2a525/comma_deps_git_lfs-3.6.1.post93-py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:e445cbadec41856997de775d5d415d1e707db0ba563c705df1b55ce198179bbe", size = 4889583, upload-time = "2026-07-08T19:31:55.153Z" }, +] + +[[package]] +name = "comma-deps-imgui" +version = "1.92.7.post93" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/48/e8/a5f99714d4b2ef85744bd6af9ee46b016a70cea8383c9cca3097847c6940/comma_deps_imgui-1.92.7.post93-py3-none-macosx_11_0_arm64.whl", hash = "sha256:ae7cbb655cd61157b785e7f388cc1bfe17bf6a2bf8c40ff9484702bd9be71074", size = 1688022, upload-time = "2026-07-08T19:31:58.849Z" }, + { url = "https://files.pythonhosted.org/packages/86/f1/0ebcbb7d55ef1ad0f516831c52f37cafdf0ed94b73e0396c531ecd89dbc1/comma_deps_imgui-1.92.7.post93-py3-none-manylinux_2_28_aarch64.whl", hash = "sha256:efc689e8279900c10e3922e9bf188fe34e16ab28d8660878e82b7192d7d86c68", size = 2522798, upload-time = "2026-07-08T19:32:02.435Z" }, + { url = "https://files.pythonhosted.org/packages/c3/94/6f0bd31d599f5748736b57e0b71a42d15ec0782906155f268bc7056fd0ac/comma_deps_imgui-1.92.7.post93-py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:b08a763c00a1f037dc5e2e2e0322c46960fe8a2cc972ce17781d547ccce3eaa6", size = 2655457, upload-time = "2026-07-08T19:32:06.273Z" }, +] + +[[package]] +name = "comma-deps-json11" +version = "20170411.0.post93" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b7/3e/f2bb5d0e0d9e63535007c64859b2ab5e17164ca1f4cfa279fd228dbcef80/comma_deps_json11-20170411.0.post93-py3-none-macosx_11_0_arm64.whl", hash = "sha256:0088d66fd76ea27712d09f2ffa783596f7d70b5b152a039c36d65befcebe3863", size = 34033, upload-time = "2026-07-08T19:32:10.175Z" }, + { url = "https://files.pythonhosted.org/packages/b8/6e/9576bb1ba5d8371f32664268401fa61231ca1092aa5da45141c37984d868/comma_deps_json11-20170411.0.post93-py3-none-manylinux_2_28_aarch64.whl", hash = "sha256:659c18d4b2634bf7d2388c6e855c6f083f384d2a70052945c1c9ddabbb0dcb21", size = 41846, upload-time = "2026-07-08T19:32:13.457Z" }, + { url = "https://files.pythonhosted.org/packages/cc/34/6d673c311c9a23e65a0db56352878b53b575aca0539e57c71121d2fe544b/comma_deps_json11-20170411.0.post93-py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:4c24a9c9db71b38192ec9c515f13fd14b4495b8080bb1f687b84b193613d95be", size = 42603, upload-time = "2026-07-08T19:32:16.601Z" }, +] + +[[package]] +name = "comma-deps-libusb" +version = "1.0.29.post93" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/56/a3/4fb912d8af7af134a0a54eeb893beecc9e1cb3ed8371e055319faa74a580/comma_deps_libusb-1.0.29.post93-py3-none-macosx_11_0_arm64.whl", hash = "sha256:1dba5fe7832877994ea9ff3daf056851f1b5c9a47552525af08b35074c5ff65e", size = 102339, upload-time = "2026-07-08T19:32:19.785Z" }, + { url = "https://files.pythonhosted.org/packages/ce/ad/6d36327352fa1030997409ee650de3f307cc26e3fec4f2a8ea6254430e6a/comma_deps_libusb-1.0.29.post93-py3-none-manylinux_2_28_aarch64.whl", hash = "sha256:c2a29c888668cb4c0ab549ac71206d6b53da8d2db5e581a55a113574aaabe950", size = 94439, upload-time = "2026-07-08T19:32:23.104Z" }, + { url = "https://files.pythonhosted.org/packages/84/47/f4f2da67db202bacc3fa578fdebdb916f45c97bee0c3d2c5fbe845a6f129/comma_deps_libusb-1.0.29.post93-py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:f136dbbfc461d228378731361cc66a90a483e17d55f8ba43f23eeab6bcf41963", size = 93461, upload-time = "2026-07-08T19:32:26.434Z" }, +] + +[[package]] +name = "comma-deps-ncurses" +version = "6.5.post93" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1c/3d/f85c036037e9d72c8cc444a1613ae8ca6967c0997148fbc8c03b8cdeb21c/comma_deps_ncurses-6.5.post93-py3-none-macosx_11_0_arm64.whl", hash = "sha256:0fbc94bdb42577389ec9e475deb7425f027b4e6a097b7b326ee0ee3ecb4c26ff", size = 264892, upload-time = "2026-07-08T22:08:58.325Z" }, + { url = "https://files.pythonhosted.org/packages/f4/da/13881cefe9ca963665a57f066683fd9995c15349839f0268686741942cd7/comma_deps_ncurses-6.5.post93-py3-none-manylinux_2_28_aarch64.whl", hash = "sha256:a8786c9e7693fbe235044ed068292ddae1e8c25e9cc3ffba9364c233b6df9f9c", size = 260837, upload-time = "2026-07-08T22:09:02.514Z" }, + { url = "https://files.pythonhosted.org/packages/11/98/6a278e4436ca901c084ae111dc23f064e3eb5f64481dc970111aff8a91fd/comma_deps_ncurses-6.5.post93-py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:1de1011e71833d46d545a0d64150316f980385d13731eb138f9fc53642942c55", size = 248341, upload-time = "2026-07-08T22:09:06.591Z" }, +] + +[[package]] +name = "comma-deps-raylib" +version = "6.0.0.1.post93" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cffi" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/ee/5a/1abdc781fc242e0db517e22c53fa676fc81b76344c5d6c86677bdd5d6a9a/comma_deps_raylib-6.0.0.1.post93-py3-none-macosx_11_0_arm64.whl", hash = "sha256:ef4dbc7036e4449f9ee029cec077c23f64975b55b60cce0be818b70640c1732a", size = 2004199, upload-time = "2026-07-08T22:09:10.731Z" }, + { url = "https://files.pythonhosted.org/packages/79/90/919fd98aa72c8c1d31e657abc0bc28b3933d7408f4dc8ccbb7272ef638a9/comma_deps_raylib-6.0.0.1.post93-py3-none-manylinux_2_28_aarch64.whl", hash = "sha256:a64f2a77ad55b05350ed4301f3a1a814176810d1d408c77bdbaa1bd5a3ab5135", size = 7203010, upload-time = "2026-07-08T22:09:15.323Z" }, + { url = "https://files.pythonhosted.org/packages/ef/b6/419b387b132efe43ace20dced9852448f36195d71d1305fccfd5e0617083/comma_deps_raylib-6.0.0.1.post93-py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:11bf076441b636434bc76a00b2e349c22a825e0b83416a4fb3dd4b8217638f8a", size = 5055450, upload-time = "2026-07-08T22:09:19.844Z" }, +] + +[[package]] +name = "comma-deps-zeromq" +version = "4.3.5.post93" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fb/6f/d50752a3a6f6ecd4b4289bf76090fd35c11ac8d4b9353534e91e9a640512/comma_deps_zeromq-4.3.5.post93-py3-none-macosx_11_0_arm64.whl", hash = "sha256:b5951b302ec3db7ad3638161af00dff6ad1d8e0272aa242a0b57d692a093bacc", size = 815166, upload-time = "2026-07-08T22:09:24.48Z" }, + { url = "https://files.pythonhosted.org/packages/57/24/0fa08db746438533a67e44886bffb1cd7e2a587c68d57fba745e84036965/comma_deps_zeromq-4.3.5.post93-py3-none-manylinux_2_28_aarch64.whl", hash = "sha256:a7d4813155ea13548158204a60e6a37e2dedfcf7ae34cbb78491474ac784ac24", size = 833412, upload-time = "2026-07-08T22:09:28.872Z" }, + { url = "https://files.pythonhosted.org/packages/c5/83/9083466d8269bf273a7ff4ff154fbcd300a8d9c79ca7754fb98215caf602/comma_deps_zeromq-4.3.5.post93-py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:378f121eea1084c7cd45ee73c3dbc437e3d07547e8333d230174711e963f958d", size = 798729, upload-time = "2026-07-08T22:09:32.859Z" }, +] + +[[package]] +name = "comma-deps-zstd" +version = "1.5.6.post93" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b4/32/e62e39d77d356675b07fa0c03286d3f5620bb39fe8619285bfaf3c085f6b/comma_deps_zstd-1.5.6.post93-py3-none-macosx_11_0_arm64.whl", hash = "sha256:9c40c10fa541c5ed975a06327f4e5cc5fe380d49c50fd2899f367c52e0d535a1", size = 1065092, upload-time = "2026-07-08T22:09:37.023Z" }, + { url = "https://files.pythonhosted.org/packages/a8/f9/80e530ffed74b767591e50367dd51413c99e8aa10a975745086f2f10eac8/comma_deps_zstd-1.5.6.post93-py3-none-manylinux_2_28_aarch64.whl", hash = "sha256:3a1da859191a9b4c778498afdaa80a7000e5967d4851d827e422c467aa159f9a", size = 1006181, upload-time = "2026-07-08T22:09:41.332Z" }, + { url = "https://files.pythonhosted.org/packages/ad/b1/5b544af0a50235b1efe9a9de469180ded30814feb8e6a2cd89d4064f995e/comma_deps_zstd-1.5.6.post93-py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:fe85e5fd24ac81964cac30ad04327ae157b5976a69725604ec960e773f06a9a8", size = 1030331, upload-time = "2026-07-08T22:09:45.535Z" }, +] + +[[package]] +name = "contourpy" +version = "1.3.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/58/01/1253e6698a07380cd31a736d248a3f2a50a7c88779a1813da27503cadc2a/contourpy-1.3.3.tar.gz", hash = "sha256:083e12155b210502d0bca491432bb04d56dc3432f95a979b429f2848c3dbe880", size = 13466174, upload-time = "2025-07-26T12:03:12.549Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/be/45/adfee365d9ea3d853550b2e735f9d66366701c65db7855cd07621732ccfc/contourpy-1.3.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:b08a32ea2f8e42cf1d4be3169a98dd4be32bafe4f22b6c4cb4ba810fa9e5d2cb", size = 293419, upload-time = "2025-07-26T12:01:21.16Z" }, + { url = "https://files.pythonhosted.org/packages/53/3e/405b59cfa13021a56bba395a6b3aca8cec012b45bf177b0eaf7a202cde2c/contourpy-1.3.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:556dba8fb6f5d8742f2923fe9457dbdd51e1049c4a43fd3986a0b14a1d815fc6", size = 273979, upload-time = "2025-07-26T12:01:22.448Z" }, + { url = "https://files.pythonhosted.org/packages/d4/1c/a12359b9b2ca3a845e8f7f9ac08bdf776114eb931392fcad91743e2ea17b/contourpy-1.3.3-cp312-cp312-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:92d9abc807cf7d0e047b95ca5d957cf4792fcd04e920ca70d48add15c1a90ea7", size = 332653, upload-time = "2025-07-26T12:01:24.155Z" }, + { url = "https://files.pythonhosted.org/packages/63/12/897aeebfb475b7748ea67b61e045accdfcf0d971f8a588b67108ed7f5512/contourpy-1.3.3-cp312-cp312-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:b2e8faa0ed68cb29af51edd8e24798bb661eac3bd9f65420c1887b6ca89987c8", size = 379536, upload-time = "2025-07-26T12:01:25.91Z" }, + { url = "https://files.pythonhosted.org/packages/43/8a/a8c584b82deb248930ce069e71576fc09bd7174bbd35183b7943fb1064fd/contourpy-1.3.3-cp312-cp312-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:626d60935cf668e70a5ce6ff184fd713e9683fb458898e4249b63be9e28286ea", size = 384397, upload-time = "2025-07-26T12:01:27.152Z" }, + { url = "https://files.pythonhosted.org/packages/cc/8f/ec6289987824b29529d0dfda0d74a07cec60e54b9c92f3c9da4c0ac732de/contourpy-1.3.3-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4d00e655fcef08aba35ec9610536bfe90267d7ab5ba944f7032549c55a146da1", size = 362601, upload-time = "2025-07-26T12:01:28.808Z" }, + { url = "https://files.pythonhosted.org/packages/05/0a/a3fe3be3ee2dceb3e615ebb4df97ae6f3828aa915d3e10549ce016302bd1/contourpy-1.3.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:451e71b5a7d597379ef572de31eeb909a87246974d960049a9848c3bc6c41bf7", size = 1331288, upload-time = "2025-07-26T12:01:31.198Z" }, + { url = "https://files.pythonhosted.org/packages/33/1d/acad9bd4e97f13f3e2b18a3977fe1b4a37ecf3d38d815333980c6c72e963/contourpy-1.3.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:459c1f020cd59fcfe6650180678a9993932d80d44ccde1fa1868977438f0b411", size = 1403386, upload-time = "2025-07-26T12:01:33.947Z" }, + { url = "https://files.pythonhosted.org/packages/cf/8f/5847f44a7fddf859704217a99a23a4f6417b10e5ab1256a179264561540e/contourpy-1.3.3-cp312-cp312-win32.whl", hash = "sha256:023b44101dfe49d7d53932be418477dba359649246075c996866106da069af69", size = 185018, upload-time = "2025-07-26T12:01:35.64Z" }, + { url = "https://files.pythonhosted.org/packages/19/e8/6026ed58a64563186a9ee3f29f41261fd1828f527dd93d33b60feca63352/contourpy-1.3.3-cp312-cp312-win_amd64.whl", hash = "sha256:8153b8bfc11e1e4d75bcb0bff1db232f9e10b274e0929de9d608027e0d34ff8b", size = 226567, upload-time = "2025-07-26T12:01:36.804Z" }, + { url = "https://files.pythonhosted.org/packages/d1/e2/f05240d2c39a1ed228d8328a78b6f44cd695f7ef47beb3e684cf93604f86/contourpy-1.3.3-cp312-cp312-win_arm64.whl", hash = "sha256:07ce5ed73ecdc4a03ffe3e1b3e3c1166db35ae7584be76f65dbbe28a7791b0cc", size = 193655, upload-time = "2025-07-26T12:01:37.999Z" }, ] [[package]] name = "coverage" -version = "7.9.1" +version = "7.15.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/e7/e0/98670a80884f64578f0c22cd70c5e81a6e07b08167721c7487b4d70a7ca0/coverage-7.9.1.tar.gz", hash = "sha256:6cf43c78c4282708a28e466316935ec7489a9c487518a77fa68f716c67909cec", size = 813650, upload-time = "2025-06-13T13:02:28.627Z" } +sdist = { url = "https://files.pythonhosted.org/packages/cc/8b/adeb62ea8951f13c4c7fef2e7a85e1a06b499c8d8237ea589d496029e53f/coverage-7.15.0.tar.gz", hash = "sha256:9ac3fe7a1435986463eaa8ee253ae2f2a268709ba4ae5c7dd1f52a05391ad78f", size = 925362, upload-time = "2026-07-02T13:10:50.535Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/60/34/fa69372a07d0903a78ac103422ad34db72281c9fc625eba94ac1185da66f/coverage-7.9.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:95c765060e65c692da2d2f51a9499c5e9f5cf5453aeaf1420e3fc847cc060582", size = 212146, upload-time = "2025-06-13T13:00:48.496Z" }, - { url = "https://files.pythonhosted.org/packages/27/f0/da1894915d2767f093f081c42afeba18e760f12fdd7a2f4acbe00564d767/coverage-7.9.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:ba383dc6afd5ec5b7a0d0c23d38895db0e15bcba7fb0fa8901f245267ac30d86", size = 212536, upload-time = "2025-06-13T13:00:51.535Z" }, - { url = "https://files.pythonhosted.org/packages/10/d5/3fc33b06e41e390f88eef111226a24e4504d216ab8e5d1a7089aa5a3c87a/coverage-7.9.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:37ae0383f13cbdcf1e5e7014489b0d71cc0106458878ccde52e8a12ced4298ed", size = 245092, upload-time = "2025-06-13T13:00:52.883Z" }, - { url = "https://files.pythonhosted.org/packages/0a/39/7aa901c14977aba637b78e95800edf77f29f5a380d29768c5b66f258305b/coverage-7.9.1-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:69aa417a030bf11ec46149636314c24c8d60fadb12fc0ee8f10fda0d918c879d", size = 242806, upload-time = "2025-06-13T13:00:54.571Z" }, - { url = "https://files.pythonhosted.org/packages/43/fc/30e5cfeaf560b1fc1989227adedc11019ce4bb7cce59d65db34fe0c2d963/coverage-7.9.1-cp311-cp311-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0a4be2a28656afe279b34d4f91c3e26eccf2f85500d4a4ff0b1f8b54bf807338", size = 244610, upload-time = "2025-06-13T13:00:56.932Z" }, - { url = "https://files.pythonhosted.org/packages/bf/15/cca62b13f39650bc87b2b92bb03bce7f0e79dd0bf2c7529e9fc7393e4d60/coverage-7.9.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:382e7ddd5289f140259b610e5f5c58f713d025cb2f66d0eb17e68d0a94278875", size = 244257, upload-time = "2025-06-13T13:00:58.545Z" }, - { url = "https://files.pythonhosted.org/packages/cd/1a/c0f2abe92c29e1464dbd0ff9d56cb6c88ae2b9e21becdb38bea31fcb2f6c/coverage-7.9.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:e5532482344186c543c37bfad0ee6069e8ae4fc38d073b8bc836fc8f03c9e250", size = 242309, upload-time = "2025-06-13T13:00:59.836Z" }, - { url = "https://files.pythonhosted.org/packages/57/8d/c6fd70848bd9bf88fa90df2af5636589a8126d2170f3aade21ed53f2b67a/coverage-7.9.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:a39d18b3f50cc121d0ce3838d32d58bd1d15dab89c910358ebefc3665712256c", size = 242898, upload-time = "2025-06-13T13:01:02.506Z" }, - { url = "https://files.pythonhosted.org/packages/c2/9e/6ca46c7bff4675f09a66fe2797cd1ad6a24f14c9c7c3b3ebe0470a6e30b8/coverage-7.9.1-cp311-cp311-win32.whl", hash = "sha256:dd24bd8d77c98557880def750782df77ab2b6885a18483dc8588792247174b32", size = 214561, upload-time = "2025-06-13T13:01:04.012Z" }, - { url = "https://files.pythonhosted.org/packages/a1/30/166978c6302010742dabcdc425fa0f938fa5a800908e39aff37a7a876a13/coverage-7.9.1-cp311-cp311-win_amd64.whl", hash = "sha256:6b55ad10a35a21b8015eabddc9ba31eb590f54adc9cd39bcf09ff5349fd52125", size = 215493, upload-time = "2025-06-13T13:01:05.702Z" }, - { url = "https://files.pythonhosted.org/packages/60/07/a6d2342cd80a5be9f0eeab115bc5ebb3917b4a64c2953534273cf9bc7ae6/coverage-7.9.1-cp311-cp311-win_arm64.whl", hash = "sha256:6ad935f0016be24c0e97fc8c40c465f9c4b85cbbe6eac48934c0dc4d2568321e", size = 213869, upload-time = "2025-06-13T13:01:09.345Z" }, - { url = "https://files.pythonhosted.org/packages/68/d9/7f66eb0a8f2fce222de7bdc2046ec41cb31fe33fb55a330037833fb88afc/coverage-7.9.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:a8de12b4b87c20de895f10567639c0797b621b22897b0af3ce4b4e204a743626", size = 212336, upload-time = "2025-06-13T13:01:10.909Z" }, - { url = "https://files.pythonhosted.org/packages/20/20/e07cb920ef3addf20f052ee3d54906e57407b6aeee3227a9c91eea38a665/coverage-7.9.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:5add197315a054e92cee1b5f686a2bcba60c4c3e66ee3de77ace6c867bdee7cb", size = 212571, upload-time = "2025-06-13T13:01:12.518Z" }, - { url = "https://files.pythonhosted.org/packages/78/f8/96f155de7e9e248ca9c8ff1a40a521d944ba48bec65352da9be2463745bf/coverage-7.9.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:600a1d4106fe66f41e5d0136dfbc68fe7200a5cbe85610ddf094f8f22e1b0300", size = 246377, upload-time = "2025-06-13T13:01:14.87Z" }, - { url = "https://files.pythonhosted.org/packages/3e/cf/1d783bd05b7bca5c10ded5f946068909372e94615a4416afadfe3f63492d/coverage-7.9.1-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:2a876e4c3e5a2a1715a6608906aa5a2e0475b9c0f68343c2ada98110512ab1d8", size = 243394, upload-time = "2025-06-13T13:01:16.23Z" }, - { url = "https://files.pythonhosted.org/packages/02/dd/e7b20afd35b0a1abea09fb3998e1abc9f9bd953bee548f235aebd2b11401/coverage-7.9.1-cp312-cp312-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:81f34346dd63010453922c8e628a52ea2d2ccd73cb2487f7700ac531b247c8a5", size = 245586, upload-time = "2025-06-13T13:01:17.532Z" }, - { url = "https://files.pythonhosted.org/packages/4e/38/b30b0006fea9d617d1cb8e43b1bc9a96af11eff42b87eb8c716cf4d37469/coverage-7.9.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:888f8eee13f2377ce86d44f338968eedec3291876b0b8a7289247ba52cb984cd", size = 245396, upload-time = "2025-06-13T13:01:19.164Z" }, - { url = "https://files.pythonhosted.org/packages/31/e4/4d8ec1dc826e16791f3daf1b50943e8e7e1eb70e8efa7abb03936ff48418/coverage-7.9.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:9969ef1e69b8c8e1e70d591f91bbc37fc9a3621e447525d1602801a24ceda898", size = 243577, upload-time = "2025-06-13T13:01:22.433Z" }, - { url = "https://files.pythonhosted.org/packages/25/f4/b0e96c5c38e6e40ef465c4bc7f138863e2909c00e54a331da335faf0d81a/coverage-7.9.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:60c458224331ee3f1a5b472773e4a085cc27a86a0b48205409d364272d67140d", size = 244809, upload-time = "2025-06-13T13:01:24.143Z" }, - { url = "https://files.pythonhosted.org/packages/8a/65/27e0a1fa5e2e5079bdca4521be2f5dabf516f94e29a0defed35ac2382eb2/coverage-7.9.1-cp312-cp312-win32.whl", hash = "sha256:5f646a99a8c2b3ff4c6a6e081f78fad0dde275cd59f8f49dc4eab2e394332e74", size = 214724, upload-time = "2025-06-13T13:01:25.435Z" }, - { url = "https://files.pythonhosted.org/packages/9b/a8/d5b128633fd1a5e0401a4160d02fa15986209a9e47717174f99dc2f7166d/coverage-7.9.1-cp312-cp312-win_amd64.whl", hash = "sha256:30f445f85c353090b83e552dcbbdad3ec84c7967e108c3ae54556ca69955563e", size = 215535, upload-time = "2025-06-13T13:01:27.861Z" }, - { url = "https://files.pythonhosted.org/packages/a3/37/84bba9d2afabc3611f3e4325ee2c6a47cd449b580d4a606b240ce5a6f9bf/coverage-7.9.1-cp312-cp312-win_arm64.whl", hash = "sha256:af41da5dca398d3474129c58cb2b106a5d93bbb196be0d307ac82311ca234342", size = 213904, upload-time = "2025-06-13T13:01:29.202Z" }, - { url = "https://files.pythonhosted.org/packages/3e/e5/c723545c3fd3204ebde3b4cc4b927dce709d3b6dc577754bb57f63ca4a4a/coverage-7.9.1-pp39.pp310.pp311-none-any.whl", hash = "sha256:db0f04118d1db74db6c9e1cb1898532c7dcc220f1d2718f058601f7c3f499514", size = 204009, upload-time = "2025-06-13T13:02:25.787Z" }, - { url = "https://files.pythonhosted.org/packages/08/b8/7ddd1e8ba9701dea08ce22029917140e6f66a859427406579fd8d0ca7274/coverage-7.9.1-py3-none-any.whl", hash = "sha256:66b974b145aa189516b6bf2d8423e888b742517d37872f6ee4c5be0073bd9a3c", size = 204000, upload-time = "2025-06-13T13:02:27.173Z" }, + { url = "https://files.pythonhosted.org/packages/2a/74/fd4c0901137c4f8d81a76ada99e43c65163b4c94a02ece107a4ec0c6b615/coverage-7.15.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:b75ee5e8cb7575636ac598719b4307ac529ec8fcd79608a35c3cd4d4dada812d", size = 220838, upload-time = "2026-07-02T13:09:02.084Z" }, + { url = "https://files.pythonhosted.org/packages/0f/2e/2347583467bd7f0402635101a916961915cc68fce652cd0db5f173ea04fc/coverage-7.15.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ffb31267816b93b075302248cc1737506081b4f163df4401e9df1a6424aafabe", size = 221197, upload-time = "2026-07-02T13:09:03.617Z" }, + { url = "https://files.pythonhosted.org/packages/f0/17/99fa688541ae1d6e84543a0e544f83de0c944815b63e9e7b1ed411d15036/coverage-7.15.0-cp312-cp312-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:e4d0bb73455bf97ab243a8f12c37c686ccf1c13bb614b7b85f1d062f06f42b2c", size = 252705, upload-time = "2026-07-02T13:09:05.059Z" }, + { url = "https://files.pythonhosted.org/packages/fb/02/6a95a5cd83b74839017ef9cf48d2d8c9ae60af919e17a3f336e6f9f1b7bd/coverage-7.15.0-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:20d9ccc4ebd0edc434d86dfd2a1dd2a8efa6b6b3073d0485a394fee86459ebb4", size = 255441, upload-time = "2026-07-02T13:09:06.559Z" }, + { url = "https://files.pythonhosted.org/packages/67/f2/406f6c57d600f68185942422c4c00f1a3255d60aee6e5fd961425cd9987e/coverage-7.15.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:20c8a976c365c8cb12f0cbd099508772ea41fb5fa80657a8506df0e11bd278c5", size = 256556, upload-time = "2026-07-02T13:09:08.197Z" }, + { url = "https://files.pythonhosted.org/packages/74/8e/d3fa48489c15ecdec1ba48fd61f68798555dddd2f6716f9ad42adeb1a2a9/coverage-7.15.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f948fd5ba1b9cbca91f0ae08b4c1ce2b139509149a435e2585d056d57d70bf01", size = 258815, upload-time = "2026-07-02T13:09:09.691Z" }, + { url = "https://files.pythonhosted.org/packages/47/2e/2d40ddd110462c6a2769677cf7f1c119a52b45f568978fc6c98e4cc0dd0f/coverage-7.15.0-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f58185f06edf6ad68ec9fb155d63ef650c82f3fbd7e1770e2867751fb13158f4", size = 253117, upload-time = "2026-07-02T13:09:11.212Z" }, + { url = "https://files.pythonhosted.org/packages/51/c0/310782f0d7c3cb2b5ac05ba8d205fe91f24a36f6bf3256098f1782181c38/coverage-7.15.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:02adc79a920c73c647c5d117f55747df7f2de94571884758ce8bc58e04f0a796", size = 254475, upload-time = "2026-07-02T13:09:13.029Z" }, + { url = "https://files.pythonhosted.org/packages/86/f7/702da6c275f8ae6ade423d2877243122932c9b27f5403003b9ef8c927d12/coverage-7.15.0-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:6eb7c300fbed667fd6e3588eba71c1904cdb06110ca6fdf908c26bdd88b8e382", size = 252619, upload-time = "2026-07-02T13:09:14.699Z" }, + { url = "https://files.pythonhosted.org/packages/fb/84/c5b15a7e5ecba4e56218d772d99fe80a63e63f8d11f12783723a6005ab45/coverage-7.15.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:b5fb23fa2de9dce1f5c36c09066d8fcda16cd96e8e26686caa2d7cb9b567d65c", size = 256689, upload-time = "2026-07-02T13:09:16.103Z" }, + { url = "https://files.pythonhosted.org/packages/95/2f/c8b07559b57701230c61b23a953858c052890c12ef568d81780c6c46e92e/coverage-7.15.0-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:cec79341dbe6281484024979976d0c7f22beae08b4a254655decd25d42cbe766", size = 252189, upload-time = "2026-07-02T13:09:17.828Z" }, + { url = "https://files.pythonhosted.org/packages/6b/80/6d2f049dd3fd3dbfd60b62ba6b2162a04009e2c002ce70b24cf3878dec7a/coverage-7.15.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:6c664c5444b1d970b1b2a450e21fb19ee5c9cfdf151ded2dda37260031cca0da", size = 254059, upload-time = "2026-07-02T13:09:19.304Z" }, + { url = "https://files.pythonhosted.org/packages/ce/92/b0287a2c42031d25c628f815f89a3cd9f8268ee78bb1252c9356cda1c689/coverage-7.15.0-cp312-cp312-win32.whl", hash = "sha256:5f764a3fa339bde6b3aa97657f5a6a3a9451e4a5b4ea98a2892c773a43525f77", size = 222893, upload-time = "2026-07-02T13:09:20.812Z" }, + { url = "https://files.pythonhosted.org/packages/a9/69/e34c481915fecb499b3146975061dac528752e37706edc1804f32c822469/coverage-7.15.0-cp312-cp312-win_amd64.whl", hash = "sha256:52f9a4d2c4c56c8848bc2f524916698354b0211488b38c49ad9ae54f6cafbff6", size = 223429, upload-time = "2026-07-02T13:09:22.315Z" }, + { url = "https://files.pythonhosted.org/packages/fe/98/6e878f0b571d32684ef3f38d7c03db241ca5b82a5da8a5391596a8f209c4/coverage-7.15.0-cp312-cp312-win_arm64.whl", hash = "sha256:31e5c3e70c85307ea35a12964e2e40f56ca2ee4b1c8c721ccf4609d17071080b", size = 222810, upload-time = "2026-07-02T13:09:23.812Z" }, + { url = "https://files.pythonhosted.org/packages/52/30/21b2ad45959cd50e909e02ebac1e30b4ceb7162e91c11d4c570223a458b7/coverage-7.15.0-py3-none-any.whl", hash = "sha256:56da6a4cbe8f7e9e80bd072ca9cefe67d7106a440a7ec06519ec6507ac94ad19", size = 212632, upload-time = "2026-07-02T13:10:48.641Z" }, ] -[package.optional-dependencies] -toml = [ - { name = "tomli", marker = "python_full_version <= '3.11'" }, -] - -[[package]] -name = "crcmod" -version = "1.7" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/6b/b0/e595ce2a2527e169c3bcd6c33d2473c1918e0b7f6826a043ca1245dd4e5b/crcmod-1.7.tar.gz", hash = "sha256:dc7051a0db5f2bd48665a990d3ec1cc305a466a77358ca4492826f41f283601e", size = 89670, upload-time = "2010-06-27T14:35:29.538Z" } - [[package]] name = "cryptography" -version = "43.0.3" +version = "49.0.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "cffi", marker = "platform_python_implementation != 'PyPy'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/0d/05/07b55d1fa21ac18c3a8c79f764e2514e6f6a9698f1be44994f5adf0d29db/cryptography-43.0.3.tar.gz", hash = "sha256:315b9001266a492a6ff443b61238f956b214dbec9910a081ba5b6646a055a805", size = 686989, upload-time = "2024-10-18T15:58:32.918Z" } +sdist = { url = "https://files.pythonhosted.org/packages/1f/99/d1c90d6041656cc6ee229dc99cd67fd0cd5aec3c5f7d72fffc27cc750054/cryptography-49.0.0.tar.gz", hash = "sha256:f89660a348f4f78a92366240a61404e337586ef7f5909a2fef59ca88ef505493", size = 854345, upload-time = "2026-06-12T20:02:30.512Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1f/f3/01fdf26701a26f4b4dbc337a26883ad5bccaa6f1bbbdd29cd89e22f18a1c/cryptography-43.0.3-cp37-abi3-macosx_10_9_universal2.whl", hash = "sha256:bf7a1932ac4176486eab36a19ed4c0492da5d97123f1406cf15e41b05e787d2e", size = 6225303, upload-time = "2024-10-18T15:57:36.753Z" }, - { url = "https://files.pythonhosted.org/packages/a3/01/4896f3d1b392025d4fcbecf40fdea92d3df8662123f6835d0af828d148fd/cryptography-43.0.3-cp37-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:63efa177ff54aec6e1c0aefaa1a241232dcd37413835a9b674b6e3f0ae2bfd3e", size = 3760905, upload-time = "2024-10-18T15:57:39.166Z" }, - { url = "https://files.pythonhosted.org/packages/0a/be/f9a1f673f0ed4b7f6c643164e513dbad28dd4f2dcdf5715004f172ef24b6/cryptography-43.0.3-cp37-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7e1ce50266f4f70bf41a2c6dc4358afadae90e2a1e5342d3c08883df1675374f", size = 3977271, upload-time = "2024-10-18T15:57:41.227Z" }, - { url = "https://files.pythonhosted.org/packages/4e/49/80c3a7b5514d1b416d7350830e8c422a4d667b6d9b16a9392ebfd4a5388a/cryptography-43.0.3-cp37-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:443c4a81bb10daed9a8f334365fe52542771f25aedaf889fd323a853ce7377d6", size = 3746606, upload-time = "2024-10-18T15:57:42.903Z" }, - { url = "https://files.pythonhosted.org/packages/0e/16/a28ddf78ac6e7e3f25ebcef69ab15c2c6be5ff9743dd0709a69a4f968472/cryptography-43.0.3-cp37-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:74f57f24754fe349223792466a709f8e0c093205ff0dca557af51072ff47ab18", size = 3986484, upload-time = "2024-10-18T15:57:45.434Z" }, - { url = "https://files.pythonhosted.org/packages/01/f5/69ae8da70c19864a32b0315049866c4d411cce423ec169993d0434218762/cryptography-43.0.3-cp37-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:9762ea51a8fc2a88b70cf2995e5675b38d93bf36bd67d91721c309df184f49bd", size = 3852131, upload-time = "2024-10-18T15:57:47.267Z" }, - { url = "https://files.pythonhosted.org/packages/fd/db/e74911d95c040f9afd3612b1f732e52b3e517cb80de8bf183be0b7d413c6/cryptography-43.0.3-cp37-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:81ef806b1fef6b06dcebad789f988d3b37ccaee225695cf3e07648eee0fc6b73", size = 4075647, upload-time = "2024-10-18T15:57:49.684Z" }, - { url = "https://files.pythonhosted.org/packages/56/48/7b6b190f1462818b324e674fa20d1d5ef3e24f2328675b9b16189cbf0b3c/cryptography-43.0.3-cp37-abi3-win32.whl", hash = "sha256:cbeb489927bd7af4aa98d4b261af9a5bc025bd87f0e3547e11584be9e9427be2", size = 2623873, upload-time = "2024-10-18T15:57:51.822Z" }, - { url = "https://files.pythonhosted.org/packages/eb/b1/0ebff61a004f7f89e7b65ca95f2f2375679d43d0290672f7713ee3162aff/cryptography-43.0.3-cp37-abi3-win_amd64.whl", hash = "sha256:f46304d6f0c6ab8e52770addfa2fc41e6629495548862279641972b6215451cd", size = 3068039, upload-time = "2024-10-18T15:57:54.426Z" }, - { url = "https://files.pythonhosted.org/packages/30/d5/c8b32c047e2e81dd172138f772e81d852c51f0f2ad2ae8a24f1122e9e9a7/cryptography-43.0.3-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:8ac43ae87929a5982f5948ceda07001ee5e83227fd69cf55b109144938d96984", size = 6222984, upload-time = "2024-10-18T15:57:56.174Z" }, - { url = "https://files.pythonhosted.org/packages/2f/78/55356eb9075d0be6e81b59f45c7b48df87f76a20e73893872170471f3ee8/cryptography-43.0.3-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:846da004a5804145a5f441b8530b4bf35afbf7da70f82409f151695b127213d5", size = 3762968, upload-time = "2024-10-18T15:57:58.206Z" }, - { url = "https://files.pythonhosted.org/packages/2a/2c/488776a3dc843f95f86d2f957ca0fc3407d0242b50bede7fad1e339be03f/cryptography-43.0.3-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0f996e7268af62598f2fc1204afa98a3b5712313a55c4c9d434aef49cadc91d4", size = 3977754, upload-time = "2024-10-18T15:58:00.683Z" }, - { url = "https://files.pythonhosted.org/packages/7c/04/2345ca92f7a22f601a9c62961741ef7dd0127c39f7310dffa0041c80f16f/cryptography-43.0.3-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:f7b178f11ed3664fd0e995a47ed2b5ff0a12d893e41dd0494f406d1cf555cab7", size = 3749458, upload-time = "2024-10-18T15:58:02.225Z" }, - { url = "https://files.pythonhosted.org/packages/ac/25/e715fa0bc24ac2114ed69da33adf451a38abb6f3f24ec207908112e9ba53/cryptography-43.0.3-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:c2e6fc39c4ab499049df3bdf567f768a723a5e8464816e8f009f121a5a9f4405", size = 3988220, upload-time = "2024-10-18T15:58:04.331Z" }, - { url = "https://files.pythonhosted.org/packages/21/ce/b9c9ff56c7164d8e2edfb6c9305045fbc0df4508ccfdb13ee66eb8c95b0e/cryptography-43.0.3-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:e1be4655c7ef6e1bbe6b5d0403526601323420bcf414598955968c9ef3eb7d16", size = 3853898, upload-time = "2024-10-18T15:58:06.113Z" }, - { url = "https://files.pythonhosted.org/packages/2a/33/b3682992ab2e9476b9c81fff22f02c8b0a1e6e1d49ee1750a67d85fd7ed2/cryptography-43.0.3-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:df6b6c6d742395dd77a23ea3728ab62f98379eff8fb61be2744d4679ab678f73", size = 4076592, upload-time = "2024-10-18T15:58:08.673Z" }, - { url = "https://files.pythonhosted.org/packages/81/1e/ffcc41b3cebd64ca90b28fd58141c5f68c83d48563c88333ab660e002cd3/cryptography-43.0.3-cp39-abi3-win32.whl", hash = "sha256:d56e96520b1020449bbace2b78b603442e7e378a9b3bd68de65c782db1507995", size = 2623145, upload-time = "2024-10-18T15:58:10.264Z" }, - { url = "https://files.pythonhosted.org/packages/87/5c/3dab83cc4aba1f4b0e733e3f0c3e7d4386440d660ba5b1e3ff995feb734d/cryptography-43.0.3-cp39-abi3-win_amd64.whl", hash = "sha256:0c580952eef9bf68c4747774cde7ec1d85a6e61de97281f2dba83c7d2c806362", size = 3068026, upload-time = "2024-10-18T15:58:11.916Z" }, + { url = "https://files.pythonhosted.org/packages/9b/22/adf66990e63584a68dfb50c24f48a125c07b1699899381c8151e63ed458c/cryptography-49.0.0-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:966fe0e9c67490071f14c0d2b1cb2dfb3023c5ce39457343931415f08382f2db", size = 4032100, upload-time = "2026-06-12T20:02:32.143Z" }, + { url = "https://files.pythonhosted.org/packages/09/41/3797cfaf69cae04a13ee78ebd83f0678d9c02b4779d21ce24445326f1a69/cryptography-49.0.0-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:36d1709f992593689b45bda411498d62c6e365f2ca00b84657d4dadd24de16db", size = 4692978, upload-time = "2026-06-12T20:01:21.305Z" }, + { url = "https://files.pythonhosted.org/packages/e6/8b/43011f7ebe515a8aa20d61f290a326cd890c2e738e16e59eaff8d9c3a412/cryptography-49.0.0-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:0e959b578856a3924bc0cbb710fc12c387b9412a951389f3ca61704a9e25f325", size = 4716422, upload-time = "2026-06-12T20:01:48.566Z" }, + { url = "https://files.pythonhosted.org/packages/4a/91/01ce7303a4579e6d3a6abef01bd322848e9ea7a219adcabc5048b9033571/cryptography-49.0.0-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:53ecee2e23f7169b6117e99fc8a944e5e50f79e69758a83b52a00cb98ab2b2d2", size = 4700503, upload-time = "2026-06-12T20:02:47.091Z" }, + { url = "https://files.pythonhosted.org/packages/62/99/a2c95cf8293f07491e9e27c20cc4dcd18176d944e674679adeb1d0173fd6/cryptography-49.0.0-cp311-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:2eda353d8a27bcbcaa4cbed18994a74ab4d19a2ca897db188ea269ab9b71419b", size = 5309779, upload-time = "2026-06-12T20:02:08.987Z" }, + { url = "https://files.pythonhosted.org/packages/20/2c/0622f20ff02b2ef32558733443805dc82fd4c275be01b2d19d14676f3a1b/cryptography-49.0.0-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:2afe9051da7ae7bd5905da5a949280c7d2bb75682e188f650a9d0f2756b834c6", size = 4749683, upload-time = "2026-06-12T20:02:03.335Z" }, + { url = "https://files.pythonhosted.org/packages/a3/5b/c5246635d5fd3b64e0d45ae10e99fd32fe9676a79915ccfe5a61ba9af1a5/cryptography-49.0.0-cp311-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:0b82e28ee398a386f0807bba7884d30f25218855690f45115831bcce5d90822c", size = 4337874, upload-time = "2026-06-12T20:02:54.323Z" }, + { url = "https://files.pythonhosted.org/packages/6d/88/05563c7fe2e914e87d1a536d06fe83e66b4e1d95cb593e05aea375531da8/cryptography-49.0.0-cp311-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:ccac2bfebc306b862133e3bb71f3f6ee8bb525240089b2d952e4144b3a6d5da7", size = 4700283, upload-time = "2026-06-12T20:01:34.822Z" }, + { url = "https://files.pythonhosted.org/packages/c4/b6/d7696e4e890d6ae1469935164c9e5215c557671cb78d6e3f458ccceaa632/cryptography-49.0.0-cp311-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:d0527ce944105f257f605a827d6ebead966c752038b6e8656abb9c5edee6fc68", size = 5265844, upload-time = "2026-06-12T20:01:24.09Z" }, + { url = "https://files.pythonhosted.org/packages/a9/3c/f3ad17eecc1a57b0ba236dc01f90e783c51f4a2f35f64777cc4f47a184b2/cryptography-49.0.0-cp311-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:cbc77da8c523d5abd028635ba850a6966fcee2c82e2bf65a41d1d8afe0f98be9", size = 4749290, upload-time = "2026-06-12T20:01:30.848Z" }, + { url = "https://files.pythonhosted.org/packages/4f/01/339573cf1023163a400b0b5d16f6d507de413b9f60be6fd1b77feeaf6737/cryptography-49.0.0-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:b87e65d263b3e5d3bb92a57e2a6638e2f31110fa7aa890c7b2dbba42248d0a3f", size = 4834612, upload-time = "2026-06-12T20:01:29.246Z" }, + { url = "https://files.pythonhosted.org/packages/71/fd/577302e213a1be9468f92d1afef66fcf1ef83d516819d9992ca547f592bd/cryptography-49.0.0-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:66ec79c3904820572d7e987abdf304281f141d37ad9a489b8e97066e7b9b6459", size = 4980804, upload-time = "2026-06-12T20:01:42.853Z" }, + { url = "https://files.pythonhosted.org/packages/1f/09/f42b1d190c5ba75f72062a387f8030d1d75f6ab035788f1d9c4b01de6525/cryptography-49.0.0-cp311-abi3-win_amd64.whl", hash = "sha256:e5dfc1e64de5677cec922ffa8da89c546d0415bf6efdf081842e5d44c84e1f0e", size = 3810026, upload-time = "2026-06-12T20:02:39.262Z" }, + { url = "https://files.pythonhosted.org/packages/19/2a/5bb823f5bedcf80718cea7fbc95ec5515cca3769633c4b01a32be7f30e7c/cryptography-49.0.0-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:ec5e529fb80935c94fe7b729f9972b50e351a0e6b50aa294fd5cabb109fcc29a", size = 4025947, upload-time = "2026-06-12T20:01:25.745Z" }, + { url = "https://files.pythonhosted.org/packages/3d/df/40577043ca124e17012f408ddddaeb213b856336ac82ddb3bc915f39e29f/cryptography-49.0.0-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f78ff2c9ed8dc2d036b0f4d640e22522213d047c1b14e61205a7e55c80a494d4", size = 4692429, upload-time = "2026-06-12T20:01:53.628Z" }, + { url = "https://files.pythonhosted.org/packages/2c/99/2d13299eb3dd27b02dcfaafcc91d6b5cb3329f7cbd6d8f51921acd566c1a/cryptography-49.0.0-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:35b151772baff2c74cba7fa290ceaff4c3b11c0c881eb93eb5dbc05a7cfbba18", size = 4700968, upload-time = "2026-06-12T20:02:45.383Z" }, + { url = "https://files.pythonhosted.org/packages/a5/4d/9c0cd02f95e2602dd5e563da149ee0830abef3537be8b34dc56281ebe27a/cryptography-49.0.0-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:0f21641cf4b30fca7aee061ced0ec7ad7b073518088b7c9969a297c0ae796c69", size = 4697758, upload-time = "2026-06-12T20:01:41.13Z" }, + { url = "https://files.pythonhosted.org/packages/24/01/186c825898477d77e2324d5360fefe622ff1d8d1963ec0554e2cada8ec77/cryptography-49.0.0-cp39-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:9e82dcc8e56052715fb18b2429e3bca4823b1629136a2084fc45a9a5cecb9b64", size = 5298863, upload-time = "2026-06-12T20:02:24.579Z" }, + { url = "https://files.pythonhosted.org/packages/b8/7b/62cbbab75d0659865bf0273790031544a0b16c8072d258f9428dcd8190dc/cryptography-49.0.0-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:6f2debedf9ca60cf1d5bd466475638af5130f89965605cd818484d19987d3a21", size = 4735983, upload-time = "2026-06-12T20:01:50.14Z" }, + { url = "https://files.pythonhosted.org/packages/6c/72/3e798c064bc39e471008075d0f9bc9daf77a80879c092e4a8e170c585ed4/cryptography-49.0.0-cp39-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:8c25ceb16df5b9435f3f6a9829204985b0e0cbee3b48aacd432c7d2c850b44d9", size = 4334173, upload-time = "2026-06-12T20:01:44.743Z" }, + { url = "https://files.pythonhosted.org/packages/f0/ee/6fca21d1ac73e06f8bef71940abfd4d2f6472b4bca284d770f32bd4086f6/cryptography-49.0.0-cp39-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:28d8b15e6275f12c8a207dc309dfa957903c927d08d0cc937ee3f63f200693cc", size = 4697298, upload-time = "2026-06-12T20:02:20.918Z" }, + { url = "https://files.pythonhosted.org/packages/67/d0/a5fcd3515f0bae49a7b6d0413cc1bdccdcc1fc0047037a0d480642cdc5d6/cryptography-49.0.0-cp39-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:6fc361c34fb6aac015ce19435876635e5c6d21db31998b0920f675f131e043b8", size = 5254338, upload-time = "2026-06-12T20:02:22.737Z" }, + { url = "https://files.pythonhosted.org/packages/a0/84/84fe36f19caf857d61cb7fc9c63035a47ffabd84ea12d1d393148efa3615/cryptography-49.0.0-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:2400ef9c9e2299a25614eb1dea3db54a69b1349efd043bfac9c67630d136df36", size = 4735650, upload-time = "2026-06-12T20:02:41.389Z" }, + { url = "https://files.pythonhosted.org/packages/6c/a0/db537264e234f7273a73ec020873d6d6b39dfd8a53db78b550ca8320440e/cryptography-49.0.0-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:67e1d20ad9ef3a563c59ef22e7a8a0b8210bd26604369ea4a30a7c66aefe504e", size = 4834820, upload-time = "2026-06-12T20:01:51.847Z" }, + { url = "https://files.pythonhosted.org/packages/93/77/8df9eb486495979bccecd1062e2eaf435250e84437040295b57d09048b0b/cryptography-49.0.0-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:42b0684e0e40cf26122427802486f6d93aea593612603a94fbf260c7eb1e9c1b", size = 4967968, upload-time = "2026-06-12T20:02:12.524Z" }, + { url = "https://files.pythonhosted.org/packages/c2/e6/f60198ea8d9dfa15fff9ed4ca02ce362f6eadd9ba757dcc50634c4257b63/cryptography-49.0.0-cp39-abi3-win_amd64.whl", hash = "sha256:026ac7423e6fa66872d3bf889be5974507da3944f866f704fa200eadacd00001", size = 3785547, upload-time = "2026-06-12T20:02:26.847Z" }, ] [[package]] @@ -451,221 +357,59 @@ wheels = [ [[package]] name = "cython" -version = "3.1.2" +version = "3.2.8" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/18/40/7b17cd866158238db704965da1b5849af261dbad393ea3ac966f934b2d39/cython-3.1.2.tar.gz", hash = "sha256:6bbf7a953fa6762dfecdec015e3b054ba51c0121a45ad851fa130f63f5331381", size = 3184825, upload-time = "2025-06-09T07:08:48.465Z" } +sdist = { url = "https://files.pythonhosted.org/packages/b6/6b/80101e02ebacaf9232ecf32bf6a788d36b27d820ee02434746252569ef98/cython-3.2.8.tar.gz", hash = "sha256:f4f23a56b25221a06f91817fe8f3114ab8b48a4fac73187dbb64bc2c4a87961f", size = 3290300, upload-time = "2026-06-30T07:41:57.874Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1f/de/502ddebaf5fe78f13cd6361acdd74710d3a5b15c22a9edc0ea4c873a59a5/cython-3.1.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:5548573e0912d7dc80579827493315384c462e2f15797b91a8ed177686d31eb9", size = 3007792, upload-time = "2025-06-09T07:09:28.777Z" }, - { url = "https://files.pythonhosted.org/packages/bb/c8/91b00bc68effba9ba1ff5b33988052ac4d98fc1ac3021ade7261661299c6/cython-3.1.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:4bf3ea5bc50d80762c490f42846820a868a6406fdb5878ae9e4cc2f11b50228a", size = 2870798, upload-time = "2025-06-09T07:09:30.745Z" }, - { url = "https://files.pythonhosted.org/packages/f4/4b/29d290f14607785112c00a5e1685d766f433531bbd6a11ad229ab61b7a70/cython-3.1.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:20ce53951d06ab2bca39f153d9c5add1d631c2a44d58bf67288c9d631be9724e", size = 3131280, upload-time = "2025-06-09T07:09:32.785Z" }, - { url = "https://files.pythonhosted.org/packages/38/3c/7c61e9ce25377ec7c4aa0b7ceeed34559ebca7b5cfd384672ba64eeaa4ba/cython-3.1.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e05a36224e3002d48c7c1c695b3771343bd16bc57eab60d6c5d5e08f3cbbafd8", size = 3223898, upload-time = "2025-06-09T07:09:35.345Z" }, - { url = "https://files.pythonhosted.org/packages/10/96/2d3fbe7e50e98b53ac86fefb48b64262b2e1304b3495e8e25b3cd1c3473e/cython-3.1.2-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:dbc0fc0777c7ab82297c01c61a1161093a22a41714f62e8c35188a309bd5db8e", size = 3291527, upload-time = "2025-06-09T07:09:37.502Z" }, - { url = "https://files.pythonhosted.org/packages/bd/e4/4cd3624e250d86f05bdb121a567865b9cca75cdc6dce4eedd68e626ea4f8/cython-3.1.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:18161ef3dd0e90a944daa2be468dd27696712a5f792d6289e97d2a31298ad688", size = 3184034, upload-time = "2025-06-09T07:09:40.225Z" }, - { url = "https://files.pythonhosted.org/packages/24/de/f8c1243c3e50ec95cb81f3a7936c8cf162f28050db8683e291c3861b46a0/cython-3.1.2-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:ca45020950cd52d82189d6dfb6225737586be6fe7b0b9d3fadd7daca62eff531", size = 3386084, upload-time = "2025-06-09T07:09:42.206Z" }, - { url = "https://files.pythonhosted.org/packages/c8/95/2365937da44741ef0781bb9ecc1f8f52b38b65acb7293b5fc7c3eaee5346/cython-3.1.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:aaae97d6d07610224be2b73a93e9e3dd85c09aedfd8e47054e3ef5a863387dae", size = 3309974, upload-time = "2025-06-09T07:09:44.801Z" }, - { url = "https://files.pythonhosted.org/packages/9b/b8/280eed114110a1a3aa9e2e76bcd06cdd5ef0df7ab77c0be9d5378ca28c57/cython-3.1.2-cp311-cp311-win32.whl", hash = "sha256:3d439d9b19e7e70f6ff745602906d282a853dd5219d8e7abbf355de680c9d120", size = 2482942, upload-time = "2025-06-09T07:09:46.583Z" }, - { url = "https://files.pythonhosted.org/packages/a2/50/0aa65be5a4ab65bde3224b8fd23ed795f699d1e724ac109bb0a32036b82d/cython-3.1.2-cp311-cp311-win_amd64.whl", hash = "sha256:8efa44ee2f1876e40eb5e45f6513a19758077c56bf140623ccab43d31f873b61", size = 2686535, upload-time = "2025-06-09T07:09:48.345Z" }, - { url = "https://files.pythonhosted.org/packages/22/86/9393ab7204d5bb65f415dd271b658c18f57b9345d06002cae069376a5a7a/cython-3.1.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:9c2c4b6f9a941c857b40168b3f3c81d514e509d985c2dcd12e1a4fea9734192e", size = 3015898, upload-time = "2025-06-09T07:09:50.79Z" }, - { url = "https://files.pythonhosted.org/packages/f9/b8/3d10ac37ab7b7ee60bc6bfb48f6682ebee7fddaccf56e1e135f0d46ca79f/cython-3.1.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:bdbc115bbe1b8c1dcbcd1b03748ea87fa967eb8dfc3a1a9bb243d4a382efcff4", size = 2846204, upload-time = "2025-06-09T07:09:52.832Z" }, - { url = "https://files.pythonhosted.org/packages/f8/34/637771d8e10ebabc34a34cdd0d63fe797b66c334e150189955bf6442d710/cython-3.1.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c05111f89db1ca98edc0675cfaa62be47b3ff519a29876eb095532a9f9e052b8", size = 3080671, upload-time = "2025-06-09T07:09:54.924Z" }, - { url = "https://files.pythonhosted.org/packages/6b/c8/383ad1851fb272920a152c5a30bb6f08c3471b5438079d9488fc3074a170/cython-3.1.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f6e7188df8709be32cfdfadc7c3782e361c929df9132f95e1bbc90a340dca3c7", size = 3199022, upload-time = "2025-06-09T07:09:56.978Z" }, - { url = "https://files.pythonhosted.org/packages/e6/11/20adc8f2db37a29f245e8fd4b8b8a8245fce4bbbd128185cc9a7b1065e4c/cython-3.1.2-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1c0ecc71e60a051732c2607b8eb8f2a03a5dac09b28e52b8af323c329db9987b", size = 3241337, upload-time = "2025-06-09T07:09:59.156Z" }, - { url = "https://files.pythonhosted.org/packages/6f/0b/491f1fd3e177cccb6bb6d52f9609f78d395edde83ac47ebb06d21717ca29/cython-3.1.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:f27143cf88835c8bcc9bf3304953f23f377d1d991e8942982fe7be344c7cfce3", size = 3131808, upload-time = "2025-06-09T07:10:01.31Z" }, - { url = "https://files.pythonhosted.org/packages/db/d2/5e7053a3214c9baa7ad72940555eb87cf4750e597f10b2bb43db62c3f39f/cython-3.1.2-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:d8c43566701133f53bf13485839d8f3f309095fe0d3b9d0cd5873073394d2edc", size = 3340319, upload-time = "2025-06-09T07:10:03.485Z" }, - { url = "https://files.pythonhosted.org/packages/95/42/4842f8ddac9b36c94ae08b23c7fcde3f930c1dd49ac8992bb5320a4d96b5/cython-3.1.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:a3bb893e85f027a929c1764bb14db4c31cbdf8a96f59a78f608f2ba7cfbbce95", size = 3287370, upload-time = "2025-06-09T07:10:05.637Z" }, - { url = "https://files.pythonhosted.org/packages/03/0d/417745ed75d414176e50310087b43299a3e611e75c379ff998f60f2ca1a8/cython-3.1.2-cp312-cp312-win32.whl", hash = "sha256:12c5902f105e43ca9af7874cdf87a23627f98c15d5a4f6d38bc9d334845145c0", size = 2487734, upload-time = "2025-06-09T07:10:07.591Z" }, - { url = "https://files.pythonhosted.org/packages/8e/82/df61d09ab81979ba171a8252af8fb8a3b26a0f19d1330c2679c11fe41667/cython-3.1.2-cp312-cp312-win_amd64.whl", hash = "sha256:06789eb7bd2e55b38b9dd349e9309f794aee0fed99c26ea5c9562d463877763f", size = 2695542, upload-time = "2025-06-09T07:10:09.545Z" }, - { url = "https://files.pythonhosted.org/packages/25/d6/ef8557d5e75cc57d55df579af4976935ee111a85bbee4a5b72354e257066/cython-3.1.2-py3-none-any.whl", hash = "sha256:d23fd7ffd7457205f08571a42b108a3cf993e83a59fe4d72b42e6fc592cf2639", size = 1224753, upload-time = "2025-06-09T07:08:44.849Z" }, + { url = "https://files.pythonhosted.org/packages/ed/c4/47e0bcfc15b36b1c5cbde5235c60bf88df552ab216ddb836d7f816386ae6/cython-3.2.8-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f2547a31fbd3b1610a8859a16edee2a141f7781691cb98a2c6fd54870c5f7541", size = 2995546, upload-time = "2026-06-30T07:42:23.618Z" }, + { url = "https://files.pythonhosted.org/packages/4a/f4/bc5830abeb57a7c7498cd9a0f2df953fd9fc7f33e3f5352c9824802b83bb/cython-3.2.8-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ab1fe11ebd61e497a848622cdd157a4324ac06e7935b1219715408844e15dd13", size = 3179546, upload-time = "2026-06-30T07:42:25.566Z" }, + { url = "https://files.pythonhosted.org/packages/89/38/a70e879ea52debac11d2810e066a5a2cb16e71229edae303f024506bc142/cython-3.2.8-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f3bce1f079734753649f8a3d3a95832297207feb120d0ef4fd5db4c813cc6c04", size = 3351714, upload-time = "2026-06-30T07:42:27.513Z" }, + { url = "https://files.pythonhosted.org/packages/45/f1/f071c5e7050a7924ffad9822558c74d489afe4764f7486cb68555a509219/cython-3.2.8-cp312-cp312-win_amd64.whl", hash = "sha256:8297efe129e6421c34ddbeb09ed5627ef6c0fc4868bf7f9bdf6c147f595ccaed", size = 2774196, upload-time = "2026-06-30T07:42:29.47Z" }, + { url = "https://files.pythonhosted.org/packages/92/a2/0f2eaa5076bcaef52567471a54ce02ffd70007bf8688cd054f7aab9bc3b8/cython-3.2.8-cp39-abi3-macosx_10_9_x86_64.whl", hash = "sha256:127bc4039be48c6eebe7f1d68c33d23eb3a0c5ae95e1d730bdd048837751438b", size = 2892527, upload-time = "2026-06-30T07:42:55.45Z" }, + { url = "https://files.pythonhosted.org/packages/a4/08/b5488aef44662e48ac09b42d4cb398207f591c770797036fb1d6fbeb7a52/cython-3.2.8-cp39-abi3-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:e480ae9f195cd29e5ce334e3d434c83dbac0783c0cc88f2407e31ba997724192", size = 3220335, upload-time = "2026-06-30T07:42:57.403Z" }, + { url = "https://files.pythonhosted.org/packages/7c/96/d04a3621045e9fe9c7c5e406a688ee3d6e04a65f545ea7c622ead4b4afd8/cython-3.2.8-cp39-abi3-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:3142407b9d63f233c766e17000e2aac782411bf0409b9adc97cb7c320aecd199", size = 2876481, upload-time = "2026-06-30T07:42:59.406Z" }, + { url = "https://files.pythonhosted.org/packages/71/9a/daa259b638c5eabb8a8c36f203b85b01b5362101ff8fc4ec6ad592d34bb3/cython-3.2.8-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:41c118fd91d320cd72af26e29232ff3f1a0a170c47d477c9a176d766067a4718", size = 2999974, upload-time = "2026-06-30T07:43:01.29Z" }, + { url = "https://files.pythonhosted.org/packages/21/de/71cc5b4be5ee4d34c3302b6e7272189106a4072e9890d284d05239d2b645/cython-3.2.8-cp39-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:6335c6e8737a39734e20d25f89f425bf3274c104fc7efc05aacc7ed1a4858c9d", size = 2897932, upload-time = "2026-06-30T07:43:03.606Z" }, + { url = "https://files.pythonhosted.org/packages/5d/0c/da68b9d3056e90b2060970b50d575cd7fcd1c778e8f23cc467f346e1d471/cython-3.2.8-cp39-abi3-musllinux_1_2_i686.whl", hash = "sha256:1034facc082cb882e1e5beb61e136ae8e282df2eafa11e9771e9b0a15c860801", size = 3235980, upload-time = "2026-06-30T07:43:05.486Z" }, + { url = "https://files.pythonhosted.org/packages/36/0b/d88bc50e66fd1f1160dd2677d9af18273a2fb2f102c086d21f64a5a9c78b/cython-3.2.8-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:8896ff6b133f346ebcf22aa23706c4031e8d9d5ae184433dfc67dc1053318b69", size = 3118504, upload-time = "2026-06-30T07:43:07.485Z" }, + { url = "https://files.pythonhosted.org/packages/db/de/511c4364808b3b4036d051a0301b0b142a3ddf8a319bfdbbd474fcfdc879/cython-3.2.8-cp39-abi3-win32.whl", hash = "sha256:3fd6464433d925cba66ae31bf5780c8a469a06da1d109180cffb39ee3c88ae20", size = 2435866, upload-time = "2026-06-30T07:43:09.367Z" }, + { url = "https://files.pythonhosted.org/packages/18/4f/911b2b2a0a02be15829ccbf0c906029a318efbf53d9f8e021e438261c206/cython-3.2.8-cp39-abi3-win_arm64.whl", hash = "sha256:4e9447d9b652396a285cdfbd4f9f0721842c63c6df281720e87dcc4b9ea65af5", size = 2457829, upload-time = "2026-06-30T07:43:11.645Z" }, + { url = "https://files.pythonhosted.org/packages/c4/19/31aa63ab719b2e1eea5f200a8a54e2591dc1966a6b75e3de30ef8be9bc2c/cython-3.2.8-py3-none-any.whl", hash = "sha256:f635e113677666de13a2ec2979e9b1d5b90617cdfd1a691d3559be81e2dd6cb9", size = 1258688, upload-time = "2026-06-30T07:41:55.624Z" }, ] [[package]] -name = "dbus-next" -version = "0.2.3" +name = "deepmerge" +version = "2.1.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/ce/45/6a40fbe886d60a8c26f480e7d12535502b5ba123814b3b9a0b002ebca198/dbus_next-0.2.3.tar.gz", hash = "sha256:f4eae26909332ada528c0a3549dda8d4f088f9b365153952a408e28023a626a5", size = 71112, upload-time = "2021-07-25T22:11:28.398Z" } +sdist = { url = "https://files.pythonhosted.org/packages/2a/78/6e9e20106224083cfb817d2d3c26e80e72258d617b616721a169b87081e0/deepmerge-2.1.0.tar.gz", hash = "sha256:07ca7a7b8935df596c512fa8161877c0487ac61f691c07766e7d71d2b23bdd2f", size = 21449, upload-time = "2026-06-22T05:46:07.669Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/d2/fc/c0a3f4c4eaa5a22fbef91713474666e13d0ea2a69c84532579490a9f2cc8/dbus_next-0.2.3-py3-none-any.whl", hash = "sha256:58948f9aff9db08316734c0be2a120f6dc502124d9642f55e90ac82ffb16a18b", size = 57885, upload-time = "2021-07-25T22:11:25.466Z" }, -] - -[[package]] -name = "dictdiffer" -version = "0.9.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/61/7b/35cbccb7effc5d7e40f4c55e2b79399e1853041997fcda15c9ff160abba0/dictdiffer-0.9.0.tar.gz", hash = "sha256:17bacf5fbfe613ccf1b6d512bd766e6b21fb798822a133aa86098b8ac9997578", size = 31513, upload-time = "2021-07-22T13:24:29.276Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/47/ef/4cb333825d10317a36a1154341ba37e6e9c087bac99c1990ef07ffdb376f/dictdiffer-0.9.0-py2.py3-none-any.whl", hash = "sha256:442bfc693cfcadaf46674575d2eba1c53b42f5e404218ca2c2ff549f2df56595", size = 16754, upload-time = "2021-07-22T13:24:26.783Z" }, -] - -[[package]] -name = "dnspython" -version = "2.7.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/b5/4a/263763cb2ba3816dd94b08ad3a33d5fdae34ecb856678773cc40a3605829/dnspython-2.7.0.tar.gz", hash = "sha256:ce9c432eda0dc91cf618a5cedf1a4e142651196bbcd2c80e89ed5a907e5cfaf1", size = 345197, upload-time = "2024-10-05T20:14:59.362Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/68/1b/e0a87d256e40e8c888847551b20a017a6b98139178505dc7ffb96f04e954/dnspython-2.7.0-py3-none-any.whl", hash = "sha256:b4c34b7d10b51bcc3a5071e7b8dee77939f1e878477eeecc965e9835f63c6c86", size = 313632, upload-time = "2024-10-05T20:14:57.687Z" }, -] - -[[package]] -name = "ewmhlib" -version = "0.2" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "python-xlib", marker = "sys_platform == 'linux'" }, - { name = "typing-extensions" }, -] -wheels = [ - { url = "https://files.pythonhosted.org/packages/2f/3a/46ca34abf0725a754bc44ef474ad34aedcc3ea23b052d97b18b76715a6a9/EWMHlib-0.2-py3-none-any.whl", hash = "sha256:f5b07d8cfd4c7734462ee744c32d490f2f3233fa7ab354240069344208d2f6f5", size = 46657, upload-time = "2024-04-17T08:15:56.338Z" }, + { url = "https://files.pythonhosted.org/packages/51/25/2a75b47cb057b1e164c604fb81ab690a6cdb5e2260ce651194eae90f64a3/deepmerge-2.1.0-py3-none-any.whl", hash = "sha256:8f148339a91d680a75ecb74ade235d9e759a93df373a0b04e9d31c8666cfeb75", size = 14345, upload-time = "2026-06-22T05:46:06.742Z" }, ] [[package]] name = "execnet" -version = "2.1.1" +version = "2.1.2" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/bb/ff/b4c0dc78fbe20c3e59c0c7334de0c27eb4001a2b2017999af398bf730817/execnet-2.1.1.tar.gz", hash = "sha256:5189b52c6121c24feae288166ab41b32549c7e2348652736540b9e6e7d4e72e3", size = 166524, upload-time = "2024-04-08T09:04:19.245Z" } +sdist = { url = "https://files.pythonhosted.org/packages/bf/89/780e11f9588d9e7128a3f87788354c7946a9cbb1401ad38a48c4db9a4f07/execnet-2.1.2.tar.gz", hash = "sha256:63d83bfdd9a23e35b9c6a3261412324f964c2ec8dcd8d3c6916ee9373e0befcd", size = 166622, upload-time = "2025-11-12T09:56:37.75Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/43/09/2aea36ff60d16dd8879bdb2f5b3ee0ba8d08cbbdcdfe870e695ce3784385/execnet-2.1.1-py3-none-any.whl", hash = "sha256:26dee51f1b80cebd6d0ca8e74dd8745419761d3bef34163928cbebbdc4749fdc", size = 40612, upload-time = "2024-04-08T09:04:17.414Z" }, -] - -[[package]] -name = "farama-notifications" -version = "0.0.4" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/2e/2c/8384832b7a6b1fd6ba95bbdcae26e7137bb3eedc955c42fd5cdcc086cfbf/Farama-Notifications-0.0.4.tar.gz", hash = "sha256:13fceff2d14314cf80703c8266462ebf3733c7d165336eee998fc58e545efd18", size = 2131, upload-time = "2023-02-27T18:28:41.047Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/05/2c/ffc08c54c05cdce6fbed2aeebc46348dbe180c6d2c541c7af7ba0aa5f5f8/Farama_Notifications-0.0.4-py3-none-any.whl", hash = "sha256:14de931035a41961f7c056361dc7f980762a143d05791ef5794a751a2caf05ae", size = 2511, upload-time = "2023-02-27T18:28:39.447Z" }, -] - -[[package]] -name = "filelock" -version = "3.18.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/0a/10/c23352565a6544bdc5353e0b15fc1c563352101f30e24bf500207a54df9a/filelock-3.18.0.tar.gz", hash = "sha256:adbc88eabb99d2fec8c9c1b229b171f18afa655400173ddc653d5d01501fb9f2", size = 18075, upload-time = "2025-03-14T07:11:40.47Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/4d/36/2a115987e2d8c300a974597416d9de88f2444426de9571f4b59b2cca3acc/filelock-3.18.0-py3-none-any.whl", hash = "sha256:c401f4f8377c4464e6db25fff06205fd89bdd83b65eb0488ed1b160f780e21de", size = 16215, upload-time = "2025-03-14T07:11:39.145Z" }, + { url = "https://files.pythonhosted.org/packages/ab/84/02fc1827e8cdded4aa65baef11296a9bbe595c474f0d6d758af082d849fd/execnet-2.1.2-py3-none-any.whl", hash = "sha256:67fba928dd5a544b783f6056f449e5e3931a5c378b128bc18501f7ea79e296ec", size = 40708, upload-time = "2025-11-12T09:56:36.333Z" }, ] [[package]] name = "fonttools" -version = "4.58.4" +version = "4.63.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/2e/5a/1124b2c8cb3a8015faf552e92714040bcdbc145dfa29928891b02d147a18/fonttools-4.58.4.tar.gz", hash = "sha256:928a8009b9884ed3aae17724b960987575155ca23c6f0b8146e400cc9e0d44ba", size = 3525026, upload-time = "2025-06-13T17:25:15.426Z" } +sdist = { url = "https://files.pythonhosted.org/packages/84/69/c97f2c18e0db87d2c7b15da1974dace76ae938f1cfa22e2727a648b7ed43/fonttools-4.63.0.tar.gz", hash = "sha256:caeb583deeb5168e694b65cda8b4ee62abedfa66cf88488734466f2366b9c4e0", size = 3597189, upload-time = "2026-05-14T12:04:30.958Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/17/7b/cc6e9bb41bab223bd2dc70ba0b21386b85f604e27f4c3206b4205085a2ab/fonttools-4.58.4-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:a3841991c9ee2dc0562eb7f23d333d34ce81e8e27c903846f0487da21e0028eb", size = 2768901, upload-time = "2025-06-13T17:24:05.901Z" }, - { url = "https://files.pythonhosted.org/packages/3d/15/98d75df9f2b4e7605f3260359ad6e18e027c11fa549f74fce567270ac891/fonttools-4.58.4-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:3c98f91b6a9604e7ffb5ece6ea346fa617f967c2c0944228801246ed56084664", size = 2328696, upload-time = "2025-06-13T17:24:09.18Z" }, - { url = "https://files.pythonhosted.org/packages/a8/c8/dc92b80f5452c9c40164e01b3f78f04b835a00e673bd9355ca257008ff61/fonttools-4.58.4-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ab9f891eb687ddf6a4e5f82901e00f992e18012ca97ab7acd15f13632acd14c1", size = 5018830, upload-time = "2025-06-13T17:24:11.282Z" }, - { url = "https://files.pythonhosted.org/packages/19/48/8322cf177680505d6b0b6062e204f01860cb573466a88077a9b795cb70e8/fonttools-4.58.4-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:891c5771e8f0094b7c0dc90eda8fc75e72930b32581418f2c285a9feedfd9a68", size = 4960922, upload-time = "2025-06-13T17:24:14.9Z" }, - { url = "https://files.pythonhosted.org/packages/14/e0/2aff149ed7eb0916de36da513d473c6fff574a7146891ce42de914899395/fonttools-4.58.4-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:43ba4d9646045c375d22e3473b7d82b18b31ee2ac715cd94220ffab7bc2d5c1d", size = 4997135, upload-time = "2025-06-13T17:24:16.959Z" }, - { url = "https://files.pythonhosted.org/packages/e6/6f/4d9829b29a64a2e63a121cb11ecb1b6a9524086eef3e35470949837a1692/fonttools-4.58.4-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:33d19f16e6d2ffd6669bda574a6589941f6c99a8d5cfb9f464038244c71555de", size = 5108701, upload-time = "2025-06-13T17:24:18.849Z" }, - { url = "https://files.pythonhosted.org/packages/6f/1e/2d656ddd1b0cd0d222f44b2d008052c2689e66b702b9af1cd8903ddce319/fonttools-4.58.4-cp311-cp311-win32.whl", hash = "sha256:b59e5109b907da19dc9df1287454821a34a75f2632a491dd406e46ff432c2a24", size = 2200177, upload-time = "2025-06-13T17:24:20.823Z" }, - { url = "https://files.pythonhosted.org/packages/fb/83/ba71ad053fddf4157cb0697c8da8eff6718d059f2a22986fa5f312b49c92/fonttools-4.58.4-cp311-cp311-win_amd64.whl", hash = "sha256:3d471a5b567a0d1648f2e148c9a8bcf00d9ac76eb89e976d9976582044cc2509", size = 2247892, upload-time = "2025-06-13T17:24:22.927Z" }, - { url = "https://files.pythonhosted.org/packages/04/3c/1d1792bfe91ef46f22a3d23b4deb514c325e73c17d4f196b385b5e2faf1c/fonttools-4.58.4-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:462211c0f37a278494e74267a994f6be9a2023d0557aaa9ecbcbfce0f403b5a6", size = 2754082, upload-time = "2025-06-13T17:24:24.862Z" }, - { url = "https://files.pythonhosted.org/packages/2a/1f/2b261689c901a1c3bc57a6690b0b9fc21a9a93a8b0c83aae911d3149f34e/fonttools-4.58.4-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:0c7a12fb6f769165547f00fcaa8d0df9517603ae7e04b625e5acb8639809b82d", size = 2321677, upload-time = "2025-06-13T17:24:26.815Z" }, - { url = "https://files.pythonhosted.org/packages/fe/6b/4607add1755a1e6581ae1fc0c9a640648e0d9cdd6591cc2d581c2e07b8c3/fonttools-4.58.4-cp312-cp312-manylinux1_x86_64.manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:2d42c63020a922154add0a326388a60a55504629edc3274bc273cd3806b4659f", size = 4896354, upload-time = "2025-06-13T17:24:28.428Z" }, - { url = "https://files.pythonhosted.org/packages/cd/95/34b4f483643d0cb11a1f830b72c03fdd18dbd3792d77a2eb2e130a96fada/fonttools-4.58.4-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8f2b4e6fd45edc6805f5f2c355590b092ffc7e10a945bd6a569fc66c1d2ae7aa", size = 4941633, upload-time = "2025-06-13T17:24:30.568Z" }, - { url = "https://files.pythonhosted.org/packages/81/ac/9bafbdb7694059c960de523e643fa5a61dd2f698f3f72c0ca18ae99257c7/fonttools-4.58.4-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:f155b927f6efb1213a79334e4cb9904d1e18973376ffc17a0d7cd43d31981f1e", size = 4886170, upload-time = "2025-06-13T17:24:32.724Z" }, - { url = "https://files.pythonhosted.org/packages/ae/44/a3a3b70d5709405f7525bb7cb497b4e46151e0c02e3c8a0e40e5e9fe030b/fonttools-4.58.4-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:e38f687d5de97c7fb7da3e58169fb5ba349e464e141f83c3c2e2beb91d317816", size = 5037851, upload-time = "2025-06-13T17:24:35.034Z" }, - { url = "https://files.pythonhosted.org/packages/21/cb/e8923d197c78969454eb876a4a55a07b59c9c4c46598f02b02411dc3b45c/fonttools-4.58.4-cp312-cp312-win32.whl", hash = "sha256:636c073b4da9db053aa683db99580cac0f7c213a953b678f69acbca3443c12cc", size = 2187428, upload-time = "2025-06-13T17:24:36.996Z" }, - { url = "https://files.pythonhosted.org/packages/46/e6/fe50183b1a0e1018e7487ee740fa8bb127b9f5075a41e20d017201e8ab14/fonttools-4.58.4-cp312-cp312-win_amd64.whl", hash = "sha256:82e8470535743409b30913ba2822e20077acf9ea70acec40b10fcf5671dceb58", size = 2236649, upload-time = "2025-06-13T17:24:38.985Z" }, - { url = "https://files.pythonhosted.org/packages/0b/2f/c536b5b9bb3c071e91d536a4d11f969e911dbb6b227939f4c5b0bca090df/fonttools-4.58.4-py3-none-any.whl", hash = "sha256:a10ce13a13f26cbb9f37512a4346bb437ad7e002ff6fa966a7ce7ff5ac3528bd", size = 1114660, upload-time = "2025-06-13T17:25:13.321Z" }, -] - -[[package]] -name = "frozenlist" -version = "1.7.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/79/b1/b64018016eeb087db503b038296fd782586432b9c077fc5c7839e9cb6ef6/frozenlist-1.7.0.tar.gz", hash = "sha256:2e310d81923c2437ea8670467121cc3e9b0f76d3043cc1d2331d56c7fb7a3a8f", size = 45078, upload-time = "2025-06-09T23:02:35.538Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/34/7e/803dde33760128acd393a27eb002f2020ddb8d99d30a44bfbaab31c5f08a/frozenlist-1.7.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:aa51e147a66b2d74de1e6e2cf5921890de6b0f4820b257465101d7f37b49fb5a", size = 82251, upload-time = "2025-06-09T23:00:16.279Z" }, - { url = "https://files.pythonhosted.org/packages/75/a9/9c2c5760b6ba45eae11334db454c189d43d34a4c0b489feb2175e5e64277/frozenlist-1.7.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:9b35db7ce1cd71d36ba24f80f0c9e7cff73a28d7a74e91fe83e23d27c7828750", size = 48183, upload-time = "2025-06-09T23:00:17.698Z" }, - { url = "https://files.pythonhosted.org/packages/47/be/4038e2d869f8a2da165f35a6befb9158c259819be22eeaf9c9a8f6a87771/frozenlist-1.7.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:34a69a85e34ff37791e94542065c8416c1afbf820b68f720452f636d5fb990cd", size = 47107, upload-time = "2025-06-09T23:00:18.952Z" }, - { url = "https://files.pythonhosted.org/packages/79/26/85314b8a83187c76a37183ceed886381a5f992975786f883472fcb6dc5f2/frozenlist-1.7.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4a646531fa8d82c87fe4bb2e596f23173caec9185bfbca5d583b4ccfb95183e2", size = 237333, upload-time = "2025-06-09T23:00:20.275Z" }, - { url = "https://files.pythonhosted.org/packages/1f/fd/e5b64f7d2c92a41639ffb2ad44a6a82f347787abc0c7df5f49057cf11770/frozenlist-1.7.0-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:79b2ffbba483f4ed36a0f236ccb85fbb16e670c9238313709638167670ba235f", size = 231724, upload-time = "2025-06-09T23:00:21.705Z" }, - { url = "https://files.pythonhosted.org/packages/20/fb/03395c0a43a5976af4bf7534759d214405fbbb4c114683f434dfdd3128ef/frozenlist-1.7.0-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:a26f205c9ca5829cbf82bb2a84b5c36f7184c4316617d7ef1b271a56720d6b30", size = 245842, upload-time = "2025-06-09T23:00:23.148Z" }, - { url = "https://files.pythonhosted.org/packages/d0/15/c01c8e1dffdac5d9803507d824f27aed2ba76b6ed0026fab4d9866e82f1f/frozenlist-1.7.0-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:bcacfad3185a623fa11ea0e0634aac7b691aa925d50a440f39b458e41c561d98", size = 239767, upload-time = "2025-06-09T23:00:25.103Z" }, - { url = "https://files.pythonhosted.org/packages/14/99/3f4c6fe882c1f5514b6848aa0a69b20cb5e5d8e8f51a339d48c0e9305ed0/frozenlist-1.7.0-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:72c1b0fe8fe451b34f12dce46445ddf14bd2a5bcad7e324987194dc8e3a74c86", size = 224130, upload-time = "2025-06-09T23:00:27.061Z" }, - { url = "https://files.pythonhosted.org/packages/4d/83/220a374bd7b2aeba9d0725130665afe11de347d95c3620b9b82cc2fcab97/frozenlist-1.7.0-cp311-cp311-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:61d1a5baeaac6c0798ff6edfaeaa00e0e412d49946c53fae8d4b8e8b3566c4ae", size = 235301, upload-time = "2025-06-09T23:00:29.02Z" }, - { url = "https://files.pythonhosted.org/packages/03/3c/3e3390d75334a063181625343e8daab61b77e1b8214802cc4e8a1bb678fc/frozenlist-1.7.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:7edf5c043c062462f09b6820de9854bf28cc6cc5b6714b383149745e287181a8", size = 234606, upload-time = "2025-06-09T23:00:30.514Z" }, - { url = "https://files.pythonhosted.org/packages/23/1e/58232c19608b7a549d72d9903005e2d82488f12554a32de2d5fb59b9b1ba/frozenlist-1.7.0-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:d50ac7627b3a1bd2dcef6f9da89a772694ec04d9a61b66cf87f7d9446b4a0c31", size = 248372, upload-time = "2025-06-09T23:00:31.966Z" }, - { url = "https://files.pythonhosted.org/packages/c0/a4/e4a567e01702a88a74ce8a324691e62a629bf47d4f8607f24bf1c7216e7f/frozenlist-1.7.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:ce48b2fece5aeb45265bb7a58259f45027db0abff478e3077e12b05b17fb9da7", size = 229860, upload-time = "2025-06-09T23:00:33.375Z" }, - { url = "https://files.pythonhosted.org/packages/73/a6/63b3374f7d22268b41a9db73d68a8233afa30ed164c46107b33c4d18ecdd/frozenlist-1.7.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:fe2365ae915a1fafd982c146754e1de6ab3478def8a59c86e1f7242d794f97d5", size = 245893, upload-time = "2025-06-09T23:00:35.002Z" }, - { url = "https://files.pythonhosted.org/packages/6d/eb/d18b3f6e64799a79673c4ba0b45e4cfbe49c240edfd03a68be20002eaeaa/frozenlist-1.7.0-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:45a6f2fdbd10e074e8814eb98b05292f27bad7d1883afbe009d96abdcf3bc898", size = 246323, upload-time = "2025-06-09T23:00:36.468Z" }, - { url = "https://files.pythonhosted.org/packages/5a/f5/720f3812e3d06cd89a1d5db9ff6450088b8f5c449dae8ffb2971a44da506/frozenlist-1.7.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:21884e23cffabb157a9dd7e353779077bf5b8f9a58e9b262c6caad2ef5f80a56", size = 233149, upload-time = "2025-06-09T23:00:37.963Z" }, - { url = "https://files.pythonhosted.org/packages/69/68/03efbf545e217d5db8446acfd4c447c15b7c8cf4dbd4a58403111df9322d/frozenlist-1.7.0-cp311-cp311-win32.whl", hash = "sha256:284d233a8953d7b24f9159b8a3496fc1ddc00f4db99c324bd5fb5f22d8698ea7", size = 39565, upload-time = "2025-06-09T23:00:39.753Z" }, - { url = "https://files.pythonhosted.org/packages/58/17/fe61124c5c333ae87f09bb67186d65038834a47d974fc10a5fadb4cc5ae1/frozenlist-1.7.0-cp311-cp311-win_amd64.whl", hash = "sha256:387cbfdcde2f2353f19c2f66bbb52406d06ed77519ac7ee21be0232147c2592d", size = 44019, upload-time = "2025-06-09T23:00:40.988Z" }, - { url = "https://files.pythonhosted.org/packages/ef/a2/c8131383f1e66adad5f6ecfcce383d584ca94055a34d683bbb24ac5f2f1c/frozenlist-1.7.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:3dbf9952c4bb0e90e98aec1bd992b3318685005702656bc6f67c1a32b76787f2", size = 81424, upload-time = "2025-06-09T23:00:42.24Z" }, - { url = "https://files.pythonhosted.org/packages/4c/9d/02754159955088cb52567337d1113f945b9e444c4960771ea90eb73de8db/frozenlist-1.7.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:1f5906d3359300b8a9bb194239491122e6cf1444c2efb88865426f170c262cdb", size = 47952, upload-time = "2025-06-09T23:00:43.481Z" }, - { url = "https://files.pythonhosted.org/packages/01/7a/0046ef1bd6699b40acd2067ed6d6670b4db2f425c56980fa21c982c2a9db/frozenlist-1.7.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:3dabd5a8f84573c8d10d8859a50ea2dec01eea372031929871368c09fa103478", size = 46688, upload-time = "2025-06-09T23:00:44.793Z" }, - { url = "https://files.pythonhosted.org/packages/d6/a2/a910bafe29c86997363fb4c02069df4ff0b5bc39d33c5198b4e9dd42d8f8/frozenlist-1.7.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:aa57daa5917f1738064f302bf2626281a1cb01920c32f711fbc7bc36111058a8", size = 243084, upload-time = "2025-06-09T23:00:46.125Z" }, - { url = "https://files.pythonhosted.org/packages/64/3e/5036af9d5031374c64c387469bfcc3af537fc0f5b1187d83a1cf6fab1639/frozenlist-1.7.0-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c193dda2b6d49f4c4398962810fa7d7c78f032bf45572b3e04dd5249dff27e08", size = 233524, upload-time = "2025-06-09T23:00:47.73Z" }, - { url = "https://files.pythonhosted.org/packages/06/39/6a17b7c107a2887e781a48ecf20ad20f1c39d94b2a548c83615b5b879f28/frozenlist-1.7.0-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:bfe2b675cf0aaa6d61bf8fbffd3c274b3c9b7b1623beb3809df8a81399a4a9c4", size = 248493, upload-time = "2025-06-09T23:00:49.742Z" }, - { url = "https://files.pythonhosted.org/packages/be/00/711d1337c7327d88c44d91dd0f556a1c47fb99afc060ae0ef66b4d24793d/frozenlist-1.7.0-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:8fc5d5cda37f62b262405cf9652cf0856839c4be8ee41be0afe8858f17f4c94b", size = 244116, upload-time = "2025-06-09T23:00:51.352Z" }, - { url = "https://files.pythonhosted.org/packages/24/fe/74e6ec0639c115df13d5850e75722750adabdc7de24e37e05a40527ca539/frozenlist-1.7.0-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b0d5ce521d1dd7d620198829b87ea002956e4319002ef0bc8d3e6d045cb4646e", size = 224557, upload-time = "2025-06-09T23:00:52.855Z" }, - { url = "https://files.pythonhosted.org/packages/8d/db/48421f62a6f77c553575201e89048e97198046b793f4a089c79a6e3268bd/frozenlist-1.7.0-cp312-cp312-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:488d0a7d6a0008ca0db273c542098a0fa9e7dfaa7e57f70acef43f32b3f69dca", size = 241820, upload-time = "2025-06-09T23:00:54.43Z" }, - { url = "https://files.pythonhosted.org/packages/1d/fa/cb4a76bea23047c8462976ea7b7a2bf53997a0ca171302deae9d6dd12096/frozenlist-1.7.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:15a7eaba63983d22c54d255b854e8108e7e5f3e89f647fc854bd77a237e767df", size = 236542, upload-time = "2025-06-09T23:00:56.409Z" }, - { url = "https://files.pythonhosted.org/packages/5d/32/476a4b5cfaa0ec94d3f808f193301debff2ea42288a099afe60757ef6282/frozenlist-1.7.0-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:1eaa7e9c6d15df825bf255649e05bd8a74b04a4d2baa1ae46d9c2d00b2ca2cb5", size = 249350, upload-time = "2025-06-09T23:00:58.468Z" }, - { url = "https://files.pythonhosted.org/packages/8d/ba/9a28042f84a6bf8ea5dbc81cfff8eaef18d78b2a1ad9d51c7bc5b029ad16/frozenlist-1.7.0-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:e4389e06714cfa9d47ab87f784a7c5be91d3934cd6e9a7b85beef808297cc025", size = 225093, upload-time = "2025-06-09T23:01:00.015Z" }, - { url = "https://files.pythonhosted.org/packages/bc/29/3a32959e68f9cf000b04e79ba574527c17e8842e38c91d68214a37455786/frozenlist-1.7.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:73bd45e1488c40b63fe5a7df892baf9e2a4d4bb6409a2b3b78ac1c6236178e01", size = 245482, upload-time = "2025-06-09T23:01:01.474Z" }, - { url = "https://files.pythonhosted.org/packages/80/e8/edf2f9e00da553f07f5fa165325cfc302dead715cab6ac8336a5f3d0adc2/frozenlist-1.7.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:99886d98e1643269760e5fe0df31e5ae7050788dd288947f7f007209b8c33f08", size = 249590, upload-time = "2025-06-09T23:01:02.961Z" }, - { url = "https://files.pythonhosted.org/packages/1c/80/9a0eb48b944050f94cc51ee1c413eb14a39543cc4f760ed12657a5a3c45a/frozenlist-1.7.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:290a172aae5a4c278c6da8a96222e6337744cd9c77313efe33d5670b9f65fc43", size = 237785, upload-time = "2025-06-09T23:01:05.095Z" }, - { url = "https://files.pythonhosted.org/packages/f3/74/87601e0fb0369b7a2baf404ea921769c53b7ae00dee7dcfe5162c8c6dbf0/frozenlist-1.7.0-cp312-cp312-win32.whl", hash = "sha256:426c7bc70e07cfebc178bc4c2bf2d861d720c4fff172181eeb4a4c41d4ca2ad3", size = 39487, upload-time = "2025-06-09T23:01:06.54Z" }, - { url = "https://files.pythonhosted.org/packages/0b/15/c026e9a9fc17585a9d461f65d8593d281fedf55fbf7eb53f16c6df2392f9/frozenlist-1.7.0-cp312-cp312-win_amd64.whl", hash = "sha256:563b72efe5da92e02eb68c59cb37205457c977aa7a449ed1b37e6939e5c47c6a", size = 43874, upload-time = "2025-06-09T23:01:07.752Z" }, - { url = "https://files.pythonhosted.org/packages/ee/45/b82e3c16be2182bff01179db177fe144d58b5dc787a7d4492c6ed8b9317f/frozenlist-1.7.0-py3-none-any.whl", hash = "sha256:9a5af342e34f7e97caf8c995864c7a396418ae2859cc6fdf1b1073020d516a7e", size = 13106, upload-time = "2025-06-09T23:02:34.204Z" }, -] - -[[package]] -name = "future-fstrings" -version = "1.2.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/5d/e2/3874574cce18a2e3608abfe5b4b5b3c9765653c464f5da18df8971cf501d/future_fstrings-1.2.0.tar.gz", hash = "sha256:6cf41cbe97c398ab5a81168ce0dbb8ad95862d3caf23c21e4430627b90844089", size = 5786, upload-time = "2019-06-16T03:04:42.651Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/ab/6d/ea1d52e9038558dd37f5d30647eb9f07888c164960a5d4daa5f970c6da25/future_fstrings-1.2.0-py2.py3-none-any.whl", hash = "sha256:90e49598b553d8746c4dc7d9442e0359d038c3039d802c91c0a55505da318c63", size = 6138, upload-time = "2019-06-16T03:04:40.395Z" }, -] - -[[package]] -name = "ghp-import" -version = "2.1.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "python-dateutil" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/d9/29/d40217cbe2f6b1359e00c6c307bb3fc876ba74068cbab3dde77f03ca0dc4/ghp-import-2.1.0.tar.gz", hash = "sha256:9c535c4c61193c2df8871222567d7fd7e5014d835f97dc7b7439069e2413d343", size = 10943, upload-time = "2022-05-02T15:47:16.11Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/f7/ec/67fbef5d497f86283db54c22eec6f6140243aae73265799baaaa19cd17fb/ghp_import-2.1.0-py3-none-any.whl", hash = "sha256:8337dd7b50877f163d4c0289bc1f1c7f127550241988d568c1db512c4324a619", size = 11034, upload-time = "2022-05-02T15:47:14.552Z" }, -] - -[[package]] -name = "google-crc32c" -version = "1.7.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/19/ae/87802e6d9f9d69adfaedfcfd599266bf386a54d0be058b532d04c794f76d/google_crc32c-1.7.1.tar.gz", hash = "sha256:2bff2305f98846f3e825dbeec9ee406f89da7962accdb29356e4eadc251bd472", size = 14495, upload-time = "2025-03-26T14:29:13.32Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/f7/94/220139ea87822b6fdfdab4fb9ba81b3fff7ea2c82e2af34adc726085bffc/google_crc32c-1.7.1-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:6fbab4b935989e2c3610371963ba1b86afb09537fd0c633049be82afe153ac06", size = 30468, upload-time = "2025-03-26T14:32:52.215Z" }, - { url = "https://files.pythonhosted.org/packages/94/97/789b23bdeeb9d15dc2904660463ad539d0318286d7633fe2760c10ed0c1c/google_crc32c-1.7.1-cp311-cp311-macosx_12_0_x86_64.whl", hash = "sha256:ed66cbe1ed9cbaaad9392b5259b3eba4a9e565420d734e6238813c428c3336c9", size = 30313, upload-time = "2025-03-26T14:57:38.758Z" }, - { url = "https://files.pythonhosted.org/packages/81/b8/976a2b843610c211e7ccb3e248996a61e87dbb2c09b1499847e295080aec/google_crc32c-1.7.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ee6547b657621b6cbed3562ea7826c3e11cab01cd33b74e1f677690652883e77", size = 33048, upload-time = "2025-03-26T14:41:30.679Z" }, - { url = "https://files.pythonhosted.org/packages/c9/16/a3842c2cf591093b111d4a5e2bfb478ac6692d02f1b386d2a33283a19dc9/google_crc32c-1.7.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d68e17bad8f7dd9a49181a1f5a8f4b251c6dbc8cc96fb79f1d321dfd57d66f53", size = 32669, upload-time = "2025-03-26T14:41:31.432Z" }, - { url = "https://files.pythonhosted.org/packages/04/17/ed9aba495916fcf5fe4ecb2267ceb851fc5f273c4e4625ae453350cfd564/google_crc32c-1.7.1-cp311-cp311-win_amd64.whl", hash = "sha256:6335de12921f06e1f774d0dd1fbea6bf610abe0887a1638f64d694013138be5d", size = 33476, upload-time = "2025-03-26T14:29:10.211Z" }, - { url = "https://files.pythonhosted.org/packages/dd/b7/787e2453cf8639c94b3d06c9d61f512234a82e1d12d13d18584bd3049904/google_crc32c-1.7.1-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:2d73a68a653c57281401871dd4aeebbb6af3191dcac751a76ce430df4d403194", size = 30470, upload-time = "2025-03-26T14:34:31.655Z" }, - { url = "https://files.pythonhosted.org/packages/ed/b4/6042c2b0cbac3ec3a69bb4c49b28d2f517b7a0f4a0232603c42c58e22b44/google_crc32c-1.7.1-cp312-cp312-macosx_12_0_x86_64.whl", hash = "sha256:22beacf83baaf59f9d3ab2bbb4db0fb018da8e5aebdce07ef9f09fce8220285e", size = 30315, upload-time = "2025-03-26T15:01:54.634Z" }, - { url = "https://files.pythonhosted.org/packages/29/ad/01e7a61a5d059bc57b702d9ff6a18b2585ad97f720bd0a0dbe215df1ab0e/google_crc32c-1.7.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:19eafa0e4af11b0a4eb3974483d55d2d77ad1911e6cf6f832e1574f6781fd337", size = 33180, upload-time = "2025-03-26T14:41:32.168Z" }, - { url = "https://files.pythonhosted.org/packages/3b/a5/7279055cf004561894ed3a7bfdf5bf90a53f28fadd01af7cd166e88ddf16/google_crc32c-1.7.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b6d86616faaea68101195c6bdc40c494e4d76f41e07a37ffdef270879c15fb65", size = 32794, upload-time = "2025-03-26T14:41:33.264Z" }, - { url = "https://files.pythonhosted.org/packages/0f/d6/77060dbd140c624e42ae3ece3df53b9d811000729a5c821b9fd671ceaac6/google_crc32c-1.7.1-cp312-cp312-win_amd64.whl", hash = "sha256:b7491bdc0c7564fcf48c0179d2048ab2f7c7ba36b84ccd3a3e1c3f7a72d3bba6", size = 33477, upload-time = "2025-03-26T14:29:10.94Z" }, - { url = "https://files.pythonhosted.org/packages/16/1b/1693372bf423ada422f80fd88260dbfd140754adb15cbc4d7e9a68b1cb8e/google_crc32c-1.7.1-pp311-pypy311_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:85fef7fae11494e747c9fd1359a527e5970fc9603c90764843caabd3a16a0a48", size = 28241, upload-time = "2025-03-26T14:41:45.898Z" }, - { url = "https://files.pythonhosted.org/packages/fd/3c/2a19a60a473de48717b4efb19398c3f914795b64a96cf3fbe82588044f78/google_crc32c-1.7.1-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6efb97eb4369d52593ad6f75e7e10d053cf00c48983f7a973105bc70b0ac4d82", size = 28048, upload-time = "2025-03-26T14:41:46.696Z" }, -] - -[[package]] -name = "gymnasium" -version = "1.1.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "cloudpickle" }, - { name = "farama-notifications" }, - { name = "numpy" }, - { name = "typing-extensions" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/90/69/70cd29e9fc4953d013b15981ee71d4c9ef4d8b2183e6ef2fe89756746dce/gymnasium-1.1.1.tar.gz", hash = "sha256:8bd9ea9bdef32c950a444ff36afc785e1d81051ec32d30435058953c20d2456d", size = 829326, upload-time = "2025-03-06T16:30:36.428Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/f9/68/2bdc7b46b5f543dd865575f9d19716866bdb76e50dd33b71ed1a3dd8bb42/gymnasium-1.1.1-py3-none-any.whl", hash = "sha256:9c167ec0a2b388666e37f63b2849cd2552f7f5b71938574c637bb36487eb928a", size = 965410, upload-time = "2025-03-06T16:30:34.443Z" }, + { url = "https://files.pythonhosted.org/packages/08/ef/b3c6b9b5be2f82416d73fe2ed2e96e2793cd80e7510bd6a17ca79cdd88ec/fonttools-4.63.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:37dd23e621e3b0aef1baa70a303b80aaf38449632cfc8fd2a55fb285bbccfc02", size = 2881131, upload-time = "2026-05-14T12:03:13.386Z" }, + { url = "https://files.pythonhosted.org/packages/44/a0/c815bea63117fa63e4e1c01f8a1110d2112fa003f838e6467094ec2432ce/fonttools-4.63.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:a9faff9e0c1f76f9fd55899d2ce785832efebab37eb8ae13995853aef178bef0", size = 2426704, upload-time = "2026-05-14T12:03:15.801Z" }, + { url = "https://files.pythonhosted.org/packages/44/04/0b91d8e916e92ad1fac9e4624760baf0fd5ff2ead614c2f68fb21373f03f/fonttools-4.63.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ef3048ef05dbb552b89817713d9cac912e00d0fde4a3105c00d29e52e10c89af", size = 5044298, upload-time = "2026-05-14T12:03:18.085Z" }, + { url = "https://files.pythonhosted.org/packages/77/c7/2342da9830e3e9d4870305ca5d2091d2a83284f2953079b7bdd3b5e029d8/fonttools-4.63.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:58dc6bb86a78d782f00f9190ca02c119cf5bbe2807536e361e18d42019f877d8", size = 4999800, upload-time = "2026-05-14T12:03:20.161Z" }, + { url = "https://files.pythonhosted.org/packages/e6/6d/67fe16c48d7ce050979b33f47e0d28a318f02da030602e944c34f7a16ef3/fonttools-4.63.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:ee08ebfa58f6e1aeff5697ab9582105bb620008c1caafb681e4c557e7483027b", size = 4982666, upload-time = "2026-05-14T12:03:22.87Z" }, + { url = "https://files.pythonhosted.org/packages/f2/00/3bbab338c07c71fa56269953845e92c951a61457bbbb0f1022551ea266d9/fonttools-4.63.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:27fdc65af8da6f88b9c6121c47a464cbe359fcfff7ff6fc2d37a1f395d755b78", size = 5133598, upload-time = "2026-05-14T12:03:25.168Z" }, + { url = "https://files.pythonhosted.org/packages/62/f2/aa27c7f98db5b064883dadcc5283947e81e034de42e22a33675878d98b54/fonttools-4.63.0-cp312-cp312-win32.whl", hash = "sha256:af2fd1664d00a397d75f806985ddb36282091c2131a73a6485c23b4a34722263", size = 2292575, upload-time = "2026-05-14T12:03:27.496Z" }, + { url = "https://files.pythonhosted.org/packages/87/36/cccb9bc2a6ab63d1b2980374f0dca72ce95ae267c9b4cfe77455bb70d0d4/fonttools-4.63.0-cp312-cp312-win_amd64.whl", hash = "sha256:59ac449f8cca9b4ffa08d2e7bbadad87ce710d69d1eda5c3c1ce579baa987272", size = 2343211, upload-time = "2026-05-14T12:03:30.057Z" }, + { url = "https://files.pythonhosted.org/packages/2c/47/c99d5268f354002ce80f8d029cd9d7d872969da1de8b93d32de4dc56d6f4/fonttools-4.63.0-py3-none-any.whl", hash = "sha256:445af2eab030a16b9171ea8bdda7ebf7d96bda2df88ee182a464252f6e05e20d", size = 1164562, upload-time = "2026-05-14T12:04:29.092Z" }, ] [[package]] @@ -683,29 +427,29 @@ wheels = [ [[package]] name = "idna" -version = "3.10" +version = "3.18" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/f1/70/7703c29685631f5a7590aa73f1f1d3fa9a380e654b86af429e0934a32f7d/idna-3.10.tar.gz", hash = "sha256:12f65c9b470abda6dc35cf8e63cc574b1c52b11df2c86030af0ac09b01b13ea9", size = 190490, upload-time = "2024-09-15T18:07:39.745Z" } +sdist = { url = "https://files.pythonhosted.org/packages/cd/63/9496c57188a2ee585e0f1db071d75089a11e98aa86eb99d9d7618fc1edce/idna-3.18.tar.gz", hash = "sha256:ffb385a7e039654cef1ab9ef32c6fafe283c0c0467bba1d9029738ce4a14a848", size = 196711, upload-time = "2026-06-02T14:34:07.794Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/76/c6/c88e154df9c4e1a2a66ccf0005a88dfb2650c1dffb6f5ce603dfbd452ce3/idna-3.10-py3-none-any.whl", hash = "sha256:946d195a0d259cbba61165e88e65941f16e9b36ea6ddb97f00452bae8b1287d3", size = 70442, upload-time = "2024-09-15T18:07:37.964Z" }, + { url = "https://files.pythonhosted.org/packages/1e/5e/d4e9f1a599fb8e573b7b87160658329fbf28d19eac2718f51fc3def3aa5a/idna-3.18-py3-none-any.whl", hash = "sha256:7f952cbe720b688055e3f87de14f5c3e5fdaa8bc3928985c4077ca689de849a2", size = 65455, upload-time = "2026-06-02T14:34:06.319Z" }, ] [[package]] -name = "ifaddr" -version = "0.2.0" +name = "importlib-resources" +version = "7.1.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/e8/ac/fb4c578f4a3256561548cd825646680edcadb9440f3f68add95ade1eb791/ifaddr-0.2.0.tar.gz", hash = "sha256:cc0cbfcaabf765d44595825fb96a99bb12c79716b73b44330ea38ee2b0c4aed4", size = 10485, upload-time = "2022-06-15T21:40:27.561Z" } +sdist = { url = "https://files.pythonhosted.org/packages/e4/06/b56dfa750b44e86157093bc8fca0ab81dccbf5260510de4eaf1cb69b5b99/importlib_resources-7.1.0.tar.gz", hash = "sha256:0722d4c6212489c530f2a145a34c0a7a3b4721bc96a15fada5930e2a0b760708", size = 44985, upload-time = "2026-04-12T16:36:09.232Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/9c/1f/19ebc343cc71a7ffa78f17018535adc5cbdd87afb31d7c34874680148b32/ifaddr-0.2.0-py3-none-any.whl", hash = "sha256:085e0305cfe6f16ab12d72e2024030f5d52674afad6911bb1eee207177b8a748", size = 12314, upload-time = "2022-06-15T21:40:25.756Z" }, + { url = "https://files.pythonhosted.org/packages/8a/db/55a262f3606bebcae07cc14095338471ad7c0bbcaa37707e6f0ee49725b7/importlib_resources-7.1.0-py3-none-any.whl", hash = "sha256:1bd7b48b4088eddb2cd16382150bb515af0bd2c70128194392725f82ad2c96a1", size = 37232, upload-time = "2026-04-12T16:36:08.219Z" }, ] [[package]] name = "iniconfig" -version = "2.1.0" +version = "2.3.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/f2/97/ebf4da567aa6827c909642694d71c9fcf53e5b504f2d96afea02718862f3/iniconfig-2.1.0.tar.gz", hash = "sha256:3abbd2e30b36733fee78f9c7f7308f2d0050e88f0087fd25c2645f63c773e1c7", size = 4793, upload-time = "2025-03-19T20:09:59.721Z" } +sdist = { url = "https://files.pythonhosted.org/packages/72/34/14ca021ce8e5dfedc35312d08ba8bf51fdd999c576889fc2c24cb97f4f10/iniconfig-2.3.0.tar.gz", hash = "sha256:c76315c77db068650d49c5b56314774a7804df16fee4402c1f19d6d15d8c4730", size = 20503, upload-time = "2025-10-18T21:55:43.219Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/2c/e1/e6716421ea10d38022b952c159d5161ca1193197fb744506875fbb87ea7b/iniconfig-2.1.0-py3-none-any.whl", hash = "sha256:9deba5723312380e77435581c6bf4935c94cbfab9b1ed33ef8d238ea168eb760", size = 6050, upload-time = "2025-03-19T20:10:01.071Z" }, + { url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" }, ] [[package]] @@ -718,12 +462,12 @@ wheels = [ ] [[package]] -name = "isodate" -version = "0.7.2" +name = "jeepney" +version = "0.9.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/54/4d/e940025e2ce31a8ce1202635910747e5a87cc3a6a6bb2d00973375014749/isodate-0.7.2.tar.gz", hash = "sha256:4cd1aa0f43ca76f4a6c6c0292a85f40b35ec2e43e315b59f06e6d32171a953e6", size = 29705, upload-time = "2024-10-08T23:04:11.5Z" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/6f/357efd7602486741aa73ffc0617fb310a29b588ed0fd69c2399acbb85b0c/jeepney-0.9.0.tar.gz", hash = "sha256:cf0e9e845622b81e4a28df94c40345400256ec608d0e55bb8a3feaa9163f5732", size = 106758, upload-time = "2025-02-27T18:51:01.684Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/15/aa/0aca39a37d3c7eb941ba736ede56d689e7be91cab5d9ca846bde3999eba6/isodate-0.7.2-py3-none-any.whl", hash = "sha256:28009937d8031054830160fce6d409ed342816b543597cece116d966c6d99e15", size = 22320, upload-time = "2024-10-08T23:04:09.501Z" }, + { url = "https://files.pythonhosted.org/packages/b2/a3/e137168c9c44d18eff0376253da9f1e9234d0239e0ee230d2fee6cea8e55/jeepney-0.9.0-py3-none-any.whl", hash = "sha256:97e5714520c16fc0a45695e5365a2e11b81ea79bba796e26f9f1d178cb182683", size = 49010, upload-time = "2025-02-27T18:51:00.104Z" }, ] [[package]] @@ -739,163 +483,105 @@ wheels = [ ] [[package]] -name = "json-rpc" -version = "1.15.0" +name = "kiwisolver" +version = "1.5.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/6d/9e/59f4a5b7855ced7346ebf40a2e9a8942863f644378d956f68bcef2c88b90/json-rpc-1.15.0.tar.gz", hash = "sha256:e6441d56c1dcd54241c937d0a2dcd193bdf0bdc539b5316524713f554b7f85b9", size = 28854, upload-time = "2023-06-11T09:45:49.078Z" } +sdist = { url = "https://files.pythonhosted.org/packages/d0/67/9c61eccb13f0bdca9307614e782fec49ffdde0f7a2314935d489fa93cd9c/kiwisolver-1.5.0.tar.gz", hash = "sha256:d4193f3d9dc3f6f79aaed0e5637f45d98850ebf01f7ca20e69457f3e8946b66a", size = 103482, upload-time = "2026-03-09T13:15:53.382Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/94/9e/820c4b086ad01ba7d77369fb8b11470a01fac9b4977f02e18659cf378b6b/json_rpc-1.15.0-py2.py3-none-any.whl", hash = "sha256:4a4668bbbe7116feb4abbd0f54e64a4adcf4b8f648f19ffa0848ad0f6606a9bf", size = 39450, upload-time = "2023-06-11T09:45:47.136Z" }, + { url = "https://files.pythonhosted.org/packages/4d/b2/818b74ebea34dabe6d0c51cb1c572e046730e64844da6ed646d5298c40ce/kiwisolver-1.5.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:4e9750bc21b886308024f8a54ccb9a2cc38ac9fa813bf4348434e3d54f337ff9", size = 123158, upload-time = "2026-03-09T13:13:23.127Z" }, + { url = "https://files.pythonhosted.org/packages/bf/d9/405320f8077e8e1c5c4bd6adc45e1e6edf6d727b6da7f2e2533cf58bff71/kiwisolver-1.5.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:72ec46b7eba5b395e0a7b63025490d3214c11013f4aacb4f5e8d6c3041829588", size = 66388, upload-time = "2026-03-09T13:13:24.765Z" }, + { url = "https://files.pythonhosted.org/packages/99/9f/795fedf35634f746151ca8839d05681ceb6287fbed6cc1c9bf235f7887c2/kiwisolver-1.5.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ed3a984b31da7481b103f68776f7128a89ef26ed40f4dc41a2223cda7fb24819", size = 64068, upload-time = "2026-03-09T13:13:25.878Z" }, + { url = "https://files.pythonhosted.org/packages/c4/13/680c54afe3e65767bed7ec1a15571e1a2f1257128733851ade24abcefbcc/kiwisolver-1.5.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:bb5136fb5352d3f422df33f0c879a1b0c204004324150cc3b5e3c4f310c9049f", size = 1477934, upload-time = "2026-03-09T13:13:27.166Z" }, + { url = "https://files.pythonhosted.org/packages/c8/2f/cebfcdb60fd6a9b0f6b47a9337198bcbad6fbe15e68189b7011fd914911f/kiwisolver-1.5.0-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b2af221f268f5af85e776a73d62b0845fc8baf8ef0abfae79d29c77d0e776aaf", size = 1278537, upload-time = "2026-03-09T13:13:28.707Z" }, + { url = "https://files.pythonhosted.org/packages/f2/0d/9b782923aada3fafb1d6b84e13121954515c669b18af0c26e7d21f579855/kiwisolver-1.5.0-cp312-cp312-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:b0f172dc8ffaccb8522d7c5d899de00133f2f1ca7b0a49b7da98e901de87bf2d", size = 1296685, upload-time = "2026-03-09T13:13:30.528Z" }, + { url = "https://files.pythonhosted.org/packages/27/70/83241b6634b04fe44e892688d5208332bde130f38e610c0418f9ede47ded/kiwisolver-1.5.0-cp312-cp312-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:6ab8ba9152203feec73758dad83af9a0bbe05001eb4639e547207c40cfb52083", size = 1346024, upload-time = "2026-03-09T13:13:32.818Z" }, + { url = "https://files.pythonhosted.org/packages/e4/db/30ed226fb271ae1a6431fc0fe0edffb2efe23cadb01e798caeb9f2ceae8f/kiwisolver-1.5.0-cp312-cp312-manylinux_2_39_riscv64.whl", hash = "sha256:cdee07c4d7f6d72008d3f73b9bf027f4e11550224c7c50d8df1ae4a37c1402a6", size = 987241, upload-time = "2026-03-09T13:13:34.435Z" }, + { url = "https://files.pythonhosted.org/packages/ec/bd/c314595208e4c9587652d50959ead9e461995389664e490f4dce7ff0f782/kiwisolver-1.5.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:7c60d3c9b06fb23bd9c6139281ccbdc384297579ae037f08ae90c69f6845c0b1", size = 2227742, upload-time = "2026-03-09T13:13:36.4Z" }, + { url = "https://files.pythonhosted.org/packages/c1/43/0499cec932d935229b5543d073c2b87c9c22846aab48881e9d8d6e742a2d/kiwisolver-1.5.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:e315e5ec90d88e140f57696ff85b484ff68bb311e36f2c414aa4286293e6dee0", size = 2323966, upload-time = "2026-03-09T13:13:38.204Z" }, + { url = "https://files.pythonhosted.org/packages/3d/6f/79b0d760907965acfd9d61826a3d41f8f093c538f55cd2633d3f0db269f6/kiwisolver-1.5.0-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:1465387ac63576c3e125e5337a6892b9e99e0627d52317f3ca79e6930d889d15", size = 1977417, upload-time = "2026-03-09T13:13:39.966Z" }, + { url = "https://files.pythonhosted.org/packages/ab/31/01d0537c41cb75a551a438c3c7a80d0c60d60b81f694dac83dd436aec0d0/kiwisolver-1.5.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:530a3fd64c87cffa844d4b6b9768774763d9caa299e9b75d8eca6a4423b31314", size = 2491238, upload-time = "2026-03-09T13:13:41.698Z" }, + { url = "https://files.pythonhosted.org/packages/e4/34/8aefdd0be9cfd00a44509251ba864f5caf2991e36772e61c408007e7f417/kiwisolver-1.5.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:1d9daea4ea6b9be74fe2f01f7fbade8d6ffab263e781274cffca0dba9be9eec9", size = 2294947, upload-time = "2026-03-09T13:13:43.343Z" }, + { url = "https://files.pythonhosted.org/packages/ad/cf/0348374369ca588f8fe9c338fae49fa4e16eeb10ffb3d012f23a54578a9e/kiwisolver-1.5.0-cp312-cp312-win_amd64.whl", hash = "sha256:f18c2d9782259a6dc132fdc7a63c168cbc74b35284b6d75c673958982a378384", size = 73569, upload-time = "2026-03-09T13:13:45.792Z" }, + { url = "https://files.pythonhosted.org/packages/28/26/192b26196e2316e2bd29deef67e37cdf9870d9af8e085e521afff0fed526/kiwisolver-1.5.0-cp312-cp312-win_arm64.whl", hash = "sha256:f7c7553b13f69c1b29a5bde08ddc6d9d0c8bfb84f9ed01c30db25944aeb852a7", size = 64997, upload-time = "2026-03-09T13:13:46.878Z" }, + { url = "https://files.pythonhosted.org/packages/1c/fa/2910df836372d8761bb6eff7d8bdcb1613b5c2e03f260efe7abe34d388a7/kiwisolver-1.5.0-graalpy312-graalpy250_312_native-macosx_10_13_x86_64.whl", hash = "sha256:5ae8e62c147495b01a0f4765c878e9bfdf843412446a247e28df59936e99e797", size = 130262, upload-time = "2026-03-09T13:15:35.629Z" }, + { url = "https://files.pythonhosted.org/packages/0f/41/c5f71f9f00aabcc71fee8b7475e3f64747282580c2fe748961ba29b18385/kiwisolver-1.5.0-graalpy312-graalpy250_312_native-macosx_11_0_arm64.whl", hash = "sha256:f6764a4ccab3078db14a632420930f6186058750df066b8ea2a7106df91d3203", size = 138036, upload-time = "2026-03-09T13:15:36.894Z" }, + { url = "https://files.pythonhosted.org/packages/fa/06/7399a607f434119c6e1fdc8ec89a8d51ccccadf3341dee4ead6bd14caaf5/kiwisolver-1.5.0-graalpy312-graalpy250_312_native-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c31c13da98624f957b0fb1b5bae5383b2333c2c3f6793d9825dd5ce79b525cb7", size = 194295, upload-time = "2026-03-09T13:15:38.22Z" }, + { url = "https://files.pythonhosted.org/packages/b5/91/53255615acd2a1eaca307ede3c90eb550bae9c94581f8c00081b6b1c8f44/kiwisolver-1.5.0-graalpy312-graalpy250_312_native-win_amd64.whl", hash = "sha256:1f1489f769582498610e015a8ef2d36f28f505ab3096d0e16b4858a9ec214f57", size = 75987, upload-time = "2026-03-09T13:15:39.65Z" }, ] [[package]] -name = "kiwisolver" -version = "1.4.8" +name = "libdatachannel-py" +version = "2026.1.0.dev2" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/82/59/7c91426a8ac292e1cdd53a63b6d9439abd573c875c3f92c146767dd33faf/kiwisolver-1.4.8.tar.gz", hash = "sha256:23d5f023bdc8c7e54eb65f03ca5d5bb25b601eac4d7f1a042888a1f45237987e", size = 97538, upload-time = "2024-12-24T18:30:51.519Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/da/ed/c913ee28936c371418cb167b128066ffb20bbf37771eecc2c97edf8a6e4c/kiwisolver-1.4.8-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:a4d3601908c560bdf880f07d94f31d734afd1bb71e96585cace0e38ef44c6d84", size = 124635, upload-time = "2024-12-24T18:28:51.826Z" }, - { url = "https://files.pythonhosted.org/packages/4c/45/4a7f896f7467aaf5f56ef093d1f329346f3b594e77c6a3c327b2d415f521/kiwisolver-1.4.8-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:856b269c4d28a5c0d5e6c1955ec36ebfd1651ac00e1ce0afa3e28da95293b561", size = 66717, upload-time = "2024-12-24T18:28:54.256Z" }, - { url = "https://files.pythonhosted.org/packages/5f/b4/c12b3ac0852a3a68f94598d4c8d569f55361beef6159dce4e7b624160da2/kiwisolver-1.4.8-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:c2b9a96e0f326205af81a15718a9073328df1173a2619a68553decb7097fd5d7", size = 65413, upload-time = "2024-12-24T18:28:55.184Z" }, - { url = "https://files.pythonhosted.org/packages/a9/98/1df4089b1ed23d83d410adfdc5947245c753bddfbe06541c4aae330e9e70/kiwisolver-1.4.8-cp311-cp311-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c5020c83e8553f770cb3b5fc13faac40f17e0b205bd237aebd21d53d733adb03", size = 1343994, upload-time = "2024-12-24T18:28:57.493Z" }, - { url = "https://files.pythonhosted.org/packages/8d/bf/b4b169b050c8421a7c53ea1ea74e4ef9c335ee9013216c558a047f162d20/kiwisolver-1.4.8-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:dace81d28c787956bfbfbbfd72fdcef014f37d9b48830829e488fdb32b49d954", size = 1434804, upload-time = "2024-12-24T18:29:00.077Z" }, - { url = "https://files.pythonhosted.org/packages/66/5a/e13bd341fbcf73325ea60fdc8af752addf75c5079867af2e04cc41f34434/kiwisolver-1.4.8-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:11e1022b524bd48ae56c9b4f9296bce77e15a2e42a502cceba602f804b32bb79", size = 1450690, upload-time = "2024-12-24T18:29:01.401Z" }, - { url = "https://files.pythonhosted.org/packages/9b/4f/5955dcb376ba4a830384cc6fab7d7547bd6759fe75a09564910e9e3bb8ea/kiwisolver-1.4.8-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:3b9b4d2892fefc886f30301cdd80debd8bb01ecdf165a449eb6e78f79f0fabd6", size = 1376839, upload-time = "2024-12-24T18:29:02.685Z" }, - { url = "https://files.pythonhosted.org/packages/3a/97/5edbed69a9d0caa2e4aa616ae7df8127e10f6586940aa683a496c2c280b9/kiwisolver-1.4.8-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3a96c0e790ee875d65e340ab383700e2b4891677b7fcd30a699146f9384a2bb0", size = 1435109, upload-time = "2024-12-24T18:29:04.113Z" }, - { url = "https://files.pythonhosted.org/packages/13/fc/e756382cb64e556af6c1809a1bbb22c141bbc2445049f2da06b420fe52bf/kiwisolver-1.4.8-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:23454ff084b07ac54ca8be535f4174170c1094a4cff78fbae4f73a4bcc0d4dab", size = 2245269, upload-time = "2024-12-24T18:29:05.488Z" }, - { url = "https://files.pythonhosted.org/packages/76/15/e59e45829d7f41c776d138245cabae6515cb4eb44b418f6d4109c478b481/kiwisolver-1.4.8-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:87b287251ad6488e95b4f0b4a79a6d04d3ea35fde6340eb38fbd1ca9cd35bbbc", size = 2393468, upload-time = "2024-12-24T18:29:06.79Z" }, - { url = "https://files.pythonhosted.org/packages/e9/39/483558c2a913ab8384d6e4b66a932406f87c95a6080112433da5ed668559/kiwisolver-1.4.8-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:b21dbe165081142b1232a240fc6383fd32cdd877ca6cc89eab93e5f5883e1c25", size = 2355394, upload-time = "2024-12-24T18:29:08.24Z" }, - { url = "https://files.pythonhosted.org/packages/01/aa/efad1fbca6570a161d29224f14b082960c7e08268a133fe5dc0f6906820e/kiwisolver-1.4.8-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:768cade2c2df13db52475bd28d3a3fac8c9eff04b0e9e2fda0f3760f20b3f7fc", size = 2490901, upload-time = "2024-12-24T18:29:09.653Z" }, - { url = "https://files.pythonhosted.org/packages/c9/4f/15988966ba46bcd5ab9d0c8296914436720dd67fca689ae1a75b4ec1c72f/kiwisolver-1.4.8-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:d47cfb2650f0e103d4bf68b0b5804c68da97272c84bb12850d877a95c056bd67", size = 2312306, upload-time = "2024-12-24T18:29:12.644Z" }, - { url = "https://files.pythonhosted.org/packages/2d/27/bdf1c769c83f74d98cbc34483a972f221440703054894a37d174fba8aa68/kiwisolver-1.4.8-cp311-cp311-win_amd64.whl", hash = "sha256:ed33ca2002a779a2e20eeb06aea7721b6e47f2d4b8a8ece979d8ba9e2a167e34", size = 71966, upload-time = "2024-12-24T18:29:14.089Z" }, - { url = "https://files.pythonhosted.org/packages/4a/c9/9642ea855604aeb2968a8e145fc662edf61db7632ad2e4fb92424be6b6c0/kiwisolver-1.4.8-cp311-cp311-win_arm64.whl", hash = "sha256:16523b40aab60426ffdebe33ac374457cf62863e330a90a0383639ce14bf44b2", size = 65311, upload-time = "2024-12-24T18:29:15.892Z" }, - { url = "https://files.pythonhosted.org/packages/fc/aa/cea685c4ab647f349c3bc92d2daf7ae34c8e8cf405a6dcd3a497f58a2ac3/kiwisolver-1.4.8-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:d6af5e8815fd02997cb6ad9bbed0ee1e60014438ee1a5c2444c96f87b8843502", size = 124152, upload-time = "2024-12-24T18:29:16.85Z" }, - { url = "https://files.pythonhosted.org/packages/c5/0b/8db6d2e2452d60d5ebc4ce4b204feeb16176a851fd42462f66ade6808084/kiwisolver-1.4.8-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:bade438f86e21d91e0cf5dd7c0ed00cda0f77c8c1616bd83f9fc157fa6760d31", size = 66555, upload-time = "2024-12-24T18:29:19.146Z" }, - { url = "https://files.pythonhosted.org/packages/60/26/d6a0db6785dd35d3ba5bf2b2df0aedc5af089962c6eb2cbf67a15b81369e/kiwisolver-1.4.8-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:b83dc6769ddbc57613280118fb4ce3cd08899cc3369f7d0e0fab518a7cf37fdb", size = 65067, upload-time = "2024-12-24T18:29:20.096Z" }, - { url = "https://files.pythonhosted.org/packages/c9/ed/1d97f7e3561e09757a196231edccc1bcf59d55ddccefa2afc9c615abd8e0/kiwisolver-1.4.8-cp312-cp312-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:111793b232842991be367ed828076b03d96202c19221b5ebab421ce8bcad016f", size = 1378443, upload-time = "2024-12-24T18:29:22.843Z" }, - { url = "https://files.pythonhosted.org/packages/29/61/39d30b99954e6b46f760e6289c12fede2ab96a254c443639052d1b573fbc/kiwisolver-1.4.8-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:257af1622860e51b1a9d0ce387bf5c2c4f36a90594cb9514f55b074bcc787cfc", size = 1472728, upload-time = "2024-12-24T18:29:24.463Z" }, - { url = "https://files.pythonhosted.org/packages/0c/3e/804163b932f7603ef256e4a715e5843a9600802bb23a68b4e08c8c0ff61d/kiwisolver-1.4.8-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:69b5637c3f316cab1ec1c9a12b8c5f4750a4c4b71af9157645bf32830e39c03a", size = 1478388, upload-time = "2024-12-24T18:29:25.776Z" }, - { url = "https://files.pythonhosted.org/packages/8a/9e/60eaa75169a154700be74f875a4d9961b11ba048bef315fbe89cb6999056/kiwisolver-1.4.8-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:782bb86f245ec18009890e7cb8d13a5ef54dcf2ebe18ed65f795e635a96a1c6a", size = 1413849, upload-time = "2024-12-24T18:29:27.202Z" }, - { url = "https://files.pythonhosted.org/packages/bc/b3/9458adb9472e61a998c8c4d95cfdfec91c73c53a375b30b1428310f923e4/kiwisolver-1.4.8-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cc978a80a0db3a66d25767b03688f1147a69e6237175c0f4ffffaaedf744055a", size = 1475533, upload-time = "2024-12-24T18:29:28.638Z" }, - { url = "https://files.pythonhosted.org/packages/e4/7a/0a42d9571e35798de80aef4bb43a9b672aa7f8e58643d7bd1950398ffb0a/kiwisolver-1.4.8-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:36dbbfd34838500a31f52c9786990d00150860e46cd5041386f217101350f0d3", size = 2268898, upload-time = "2024-12-24T18:29:30.368Z" }, - { url = "https://files.pythonhosted.org/packages/d9/07/1255dc8d80271400126ed8db35a1795b1a2c098ac3a72645075d06fe5c5d/kiwisolver-1.4.8-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:eaa973f1e05131de5ff3569bbba7f5fd07ea0595d3870ed4a526d486fe57fa1b", size = 2425605, upload-time = "2024-12-24T18:29:33.151Z" }, - { url = "https://files.pythonhosted.org/packages/84/df/5a3b4cf13780ef6f6942df67b138b03b7e79e9f1f08f57c49957d5867f6e/kiwisolver-1.4.8-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:a66f60f8d0c87ab7f59b6fb80e642ebb29fec354a4dfad687ca4092ae69d04f4", size = 2375801, upload-time = "2024-12-24T18:29:34.584Z" }, - { url = "https://files.pythonhosted.org/packages/8f/10/2348d068e8b0f635c8c86892788dac7a6b5c0cb12356620ab575775aad89/kiwisolver-1.4.8-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:858416b7fb777a53f0c59ca08190ce24e9abbd3cffa18886a5781b8e3e26f65d", size = 2520077, upload-time = "2024-12-24T18:29:36.138Z" }, - { url = "https://files.pythonhosted.org/packages/32/d8/014b89fee5d4dce157d814303b0fce4d31385a2af4c41fed194b173b81ac/kiwisolver-1.4.8-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:085940635c62697391baafaaeabdf3dd7a6c3643577dde337f4d66eba021b2b8", size = 2338410, upload-time = "2024-12-24T18:29:39.991Z" }, - { url = "https://files.pythonhosted.org/packages/bd/72/dfff0cc97f2a0776e1c9eb5bef1ddfd45f46246c6533b0191887a427bca5/kiwisolver-1.4.8-cp312-cp312-win_amd64.whl", hash = "sha256:01c3d31902c7db5fb6182832713d3b4122ad9317c2c5877d0539227d96bb2e50", size = 71853, upload-time = "2024-12-24T18:29:42.006Z" }, - { url = "https://files.pythonhosted.org/packages/dc/85/220d13d914485c0948a00f0b9eb419efaf6da81b7d72e88ce2391f7aed8d/kiwisolver-1.4.8-cp312-cp312-win_arm64.whl", hash = "sha256:a3c44cb68861de93f0c4a8175fbaa691f0aa22550c331fefef02b618a9dcb476", size = 65424, upload-time = "2024-12-24T18:29:44.38Z" }, + { url = "https://files.pythonhosted.org/packages/46/2f/68e8306327ddef4b2133d2efb163cb05b319759ce8bd50b8b32dcd03dd95/libdatachannel_py-2026.1.0.dev2-cp312-cp312-macosx_15_0_arm64.whl", hash = "sha256:6607fa1439e1b5bfceecd387c433470c9d45e439c3c06fa064f5c4669ad7e582", size = 1213155, upload-time = "2026-05-19T03:37:12.796Z" }, + { url = "https://files.pythonhosted.org/packages/fc/e3/10aed36ffaf1744795322aae612db777991575b72a9f04e2c677c2c022bf/libdatachannel_py-2026.1.0.dev2-cp312-cp312-macosx_26_0_arm64.whl", hash = "sha256:a060b1250f57d1fccb36e3a6b36ac8f4fd34926a6b51c564e787e8b7206458aa", size = 1224706, upload-time = "2026-05-19T03:37:12.679Z" }, + { url = "https://files.pythonhosted.org/packages/09/a9/103fc647a8f9c721ab140fe8d2f8dbd90817e917ca763c4eb0f843fe247e/libdatachannel_py-2026.1.0.dev2-cp312-cp312-manylinux_2_35_aarch64.whl", hash = "sha256:0b8aa3be2fa3654ea24f882756d6599e847de866a44f7a291c60994548a2debb", size = 1638879, upload-time = "2026-05-19T03:37:18.138Z" }, + { url = "https://files.pythonhosted.org/packages/09/a8/0dc7d3fe80fc247ec165dbd455bc2a1a307ef65702a43e24473202c2bf42/libdatachannel_py-2026.1.0.dev2-cp312-cp312-manylinux_2_35_x86_64.whl", hash = "sha256:339a79fcbc8c6caf91c620f6e4a0f1b8ccb6a941a966d10a3135c980ae4651a6", size = 1718006, upload-time = "2026-05-19T03:37:11.891Z" }, + { url = "https://files.pythonhosted.org/packages/6d/86/30904a8753e9db60d8c3cf8efda09585fc68f2004d3d7aa2910c93a8eed5/libdatachannel_py-2026.1.0.dev2-cp312-cp312-manylinux_2_38_aarch64.whl", hash = "sha256:b9f476cb065b50856ab2e53bf774ccca9c6a66454b7ce903aaf6dfcdef2a4482", size = 1643757, upload-time = "2026-05-19T03:37:12.207Z" }, + { url = "https://files.pythonhosted.org/packages/d7/9d/1e10131396d28e84a8088a63c14978cc215f6677dc85acdd96b6068f0664/libdatachannel_py-2026.1.0.dev2-cp312-cp312-manylinux_2_38_x86_64.whl", hash = "sha256:1f31db7347549edcd69fcc1ecb8b31e7183894808ccf9387afc49a4d68debaae", size = 1751748, upload-time = "2026-05-19T03:37:06.98Z" }, +] + +[[package]] +name = "libusb-package" +version = "1.0.30.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "importlib-resources" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/42/a8/8b3d5dae7340880d556f9f866874b9674b2e3a22fee1e2b96f1ab0feae36/libusb_package-1.0.30.0-py3-none-macosx_10_9_x86_64.whl", hash = "sha256:2b98784bac3bedda7e95bb5039dd0eded84b02f36110e4d5d607375366c61090", size = 69516, upload-time = "2026-06-30T07:41:02.451Z" }, + { url = "https://files.pythonhosted.org/packages/52/6f/26de4e9f858ab50e87931f0be268f3c1bbfce33e8584add60da857632142/libusb_package-1.0.30.0-py3-none-macosx_11_0_arm64.whl", hash = "sha256:4ad25f8d254bbbdd234446d5580b24d62d59bb0e690d8090457dac347f044437", size = 65700, upload-time = "2026-06-30T07:41:03.557Z" }, + { url = "https://files.pythonhosted.org/packages/11/12/9ba8fa91dc95b1cbfa4a68207d4048b08b900fd3686fa72b99846608de01/libusb_package-1.0.30.0-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c71b5f8c65b286425c02c7d624eee1fd7f08bfb1dfa492ddc20e27f06fee3829", size = 76166, upload-time = "2026-06-30T07:41:04.462Z" }, + { url = "https://files.pythonhosted.org/packages/6f/e1/a7c83535749332825f02d6693868f8ee9ae99c4104e60a483773bb652c0e/libusb_package-1.0.30.0-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f502ad5a0527b8c0431de817662325c88a1bba2cc334173665b04ad168d7b6d3", size = 76159, upload-time = "2026-06-30T07:41:05.543Z" }, + { url = "https://files.pythonhosted.org/packages/de/56/a1fb1726fc96a8ee3bd0e04e5e505500f022dd310dd348ecebf5cdae7a60/libusb_package-1.0.30.0-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:7a2a1c82f6ef85d9920cbe2898aa6927d4c487744ef9f20b0d7d6d95705095bb", size = 77162, upload-time = "2026-06-30T07:41:06.581Z" }, + { url = "https://files.pythonhosted.org/packages/7b/03/264cefc51275ecb047194c4973bc40b3b278566a64bbe6e74f86bf1e0afc/libusb_package-1.0.30.0-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:2ee5ef8ac6f08402b4e8334f7404850316bdd26037c9a97f2a7456ee9a5d1550", size = 76676, upload-time = "2026-06-30T07:41:07.505Z" }, + { url = "https://files.pythonhosted.org/packages/e5/95/d166eeefe0d9dd5833d5724a97b023ec380c3a2d364040ec0485fd57703c/libusb_package-1.0.30.0-py3-none-win32.whl", hash = "sha256:79728146e1f01e525786900b2ccd8298a8eca53cd94b37fb0885e56aa6f9d60a", size = 78769, upload-time = "2026-06-30T07:41:08.432Z" }, + { url = "https://files.pythonhosted.org/packages/60/4a/ff49bd77f33af05ca26fee29d601beb1e19ca791bb86efece82a3833885c/libusb_package-1.0.30.0-py3-none-win_amd64.whl", hash = "sha256:90808da724c8939a333d931d0c7226372ca5fefd98e2f2f3ef79fd918aa37522", size = 90711, upload-time = "2026-06-30T07:41:09.318Z" }, ] [[package]] name = "libusb1" -version = "3.3.1" +version = "3.4.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a2/7f/c59ad56d1bca8fa4321d1bb77ba4687775751a4deceec14943a44da18ca0/libusb1-3.3.1.tar.gz", hash = "sha256:3951d360f2daf0e0eacf839e15d2d1d2f4f5e7830231eb3188eeffef2dd17bad", size = 107600, upload-time = "2025-03-24T05:36:47.834Z" } +sdist = { url = "https://files.pythonhosted.org/packages/89/35/f9d2a990d092d647b47540cd229e1d68432c0f51183484ca189612a4824c/libusb1-3.4.0.tar.gz", hash = "sha256:9cf5638506d54f21bf36550d97ea63189111a23c4d8078f630103a2052135f45", size = 91206, upload-time = "2026-05-16T20:59:19.315Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/10/f7/4577cfc55c9520ecab5563173e83235382ac7980c8c2c08d6c9f7ef9e615/libusb1-3.3.1-py3-none-any.whl", hash = "sha256:808c9362299dcee01651aa87e71e9d681ccedb27fc4dbd70aaf14e245fb855f1", size = 67243, upload-time = "2025-03-24T05:36:42.312Z" }, - { url = "https://files.pythonhosted.org/packages/6a/60/d3fd4831c601f063a16fc59f465ef4c1108247b07fbff371a982bd1bac45/libusb1-3.3.1-py3-none-win32.whl", hash = "sha256:0ef69825173ce74af34444754c081cc324233edc6acc405658b3ad784833e076", size = 129576, upload-time = "2025-03-24T05:36:45.202Z" }, - { url = "https://files.pythonhosted.org/packages/94/6d/344a164d32d65d503ffe9201cd74cf13a020099dc446554d1e50b07f167b/libusb1-3.3.1-py3-none-win_amd64.whl", hash = "sha256:6e21b772d80d6487fbb55d3d2141218536db302da82f1983754e96c72781c102", size = 141080, upload-time = "2025-03-24T05:36:46.594Z" }, -] - -[[package]] -name = "llvmlite" -version = "0.44.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/89/6a/95a3d3610d5c75293d5dbbb2a76480d5d4eeba641557b69fe90af6c5b84e/llvmlite-0.44.0.tar.gz", hash = "sha256:07667d66a5d150abed9157ab6c0b9393c9356f229784a4385c02f99e94fc94d4", size = 171880, upload-time = "2025-01-20T11:14:41.342Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b5/e2/86b245397052386595ad726f9742e5223d7aea999b18c518a50e96c3aca4/llvmlite-0.44.0-cp311-cp311-macosx_10_14_x86_64.whl", hash = "sha256:eed7d5f29136bda63b6d7804c279e2b72e08c952b7c5df61f45db408e0ee52f3", size = 28132305, upload-time = "2025-01-20T11:12:53.936Z" }, - { url = "https://files.pythonhosted.org/packages/ff/ec/506902dc6870249fbe2466d9cf66d531265d0f3a1157213c8f986250c033/llvmlite-0.44.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:ace564d9fa44bb91eb6e6d8e7754977783c68e90a471ea7ce913bff30bd62427", size = 26201090, upload-time = "2025-01-20T11:12:59.847Z" }, - { url = "https://files.pythonhosted.org/packages/99/fe/d030f1849ebb1f394bb3f7adad5e729b634fb100515594aca25c354ffc62/llvmlite-0.44.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c5d22c3bfc842668168a786af4205ec8e3ad29fb1bc03fd11fd48460d0df64c1", size = 42361858, upload-time = "2025-01-20T11:13:07.623Z" }, - { url = "https://files.pythonhosted.org/packages/d7/7a/ce6174664b9077fc673d172e4c888cb0b128e707e306bc33fff8c2035f0d/llvmlite-0.44.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f01a394e9c9b7b1d4e63c327b096d10f6f0ed149ef53d38a09b3749dcf8c9610", size = 41184200, upload-time = "2025-01-20T11:13:20.058Z" }, - { url = "https://files.pythonhosted.org/packages/5f/c6/258801143975a6d09a373f2641237992496e15567b907a4d401839d671b8/llvmlite-0.44.0-cp311-cp311-win_amd64.whl", hash = "sha256:d8489634d43c20cd0ad71330dde1d5bc7b9966937a263ff1ec1cebb90dc50955", size = 30331193, upload-time = "2025-01-20T11:13:26.976Z" }, - { url = "https://files.pythonhosted.org/packages/15/86/e3c3195b92e6e492458f16d233e58a1a812aa2bfbef9bdd0fbafcec85c60/llvmlite-0.44.0-cp312-cp312-macosx_10_14_x86_64.whl", hash = "sha256:1d671a56acf725bf1b531d5ef76b86660a5ab8ef19bb6a46064a705c6ca80aad", size = 28132297, upload-time = "2025-01-20T11:13:32.57Z" }, - { url = "https://files.pythonhosted.org/packages/d6/53/373b6b8be67b9221d12b24125fd0ec56b1078b660eeae266ec388a6ac9a0/llvmlite-0.44.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:5f79a728e0435493611c9f405168682bb75ffd1fbe6fc360733b850c80a026db", size = 26201105, upload-time = "2025-01-20T11:13:38.744Z" }, - { url = "https://files.pythonhosted.org/packages/cb/da/8341fd3056419441286c8e26bf436923021005ece0bff5f41906476ae514/llvmlite-0.44.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c0143a5ef336da14deaa8ec26c5449ad5b6a2b564df82fcef4be040b9cacfea9", size = 42361901, upload-time = "2025-01-20T11:13:46.711Z" }, - { url = "https://files.pythonhosted.org/packages/53/ad/d79349dc07b8a395a99153d7ce8b01d6fcdc9f8231355a5df55ded649b61/llvmlite-0.44.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d752f89e31b66db6f8da06df8b39f9b91e78c5feea1bf9e8c1fba1d1c24c065d", size = 41184247, upload-time = "2025-01-20T11:13:56.159Z" }, - { url = "https://files.pythonhosted.org/packages/e2/3b/a9a17366af80127bd09decbe2a54d8974b6d8b274b39bf47fbaedeec6307/llvmlite-0.44.0-cp312-cp312-win_amd64.whl", hash = "sha256:eae7e2d4ca8f88f89d315b48c6b741dcb925d6a1042da694aa16ab3dd4cbd3a1", size = 30332380, upload-time = "2025-01-20T11:14:02.442Z" }, -] - -[[package]] -name = "lxml" -version = "5.4.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/76/3d/14e82fc7c8fb1b7761f7e748fd47e2ec8276d137b6acfe5a4bb73853e08f/lxml-5.4.0.tar.gz", hash = "sha256:d12832e1dbea4be280b22fd0ea7c9b87f0d8fc51ba06e92dc62d52f804f78ebd", size = 3679479, upload-time = "2025-04-23T01:50:29.322Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/81/2d/67693cc8a605a12e5975380d7ff83020dcc759351b5a066e1cced04f797b/lxml-5.4.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:98a3912194c079ef37e716ed228ae0dcb960992100461b704aea4e93af6b0bb9", size = 8083240, upload-time = "2025-04-23T01:45:18.566Z" }, - { url = "https://files.pythonhosted.org/packages/73/53/b5a05ab300a808b72e848efd152fe9c022c0181b0a70b8bca1199f1bed26/lxml-5.4.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:0ea0252b51d296a75f6118ed0d8696888e7403408ad42345d7dfd0d1e93309a7", size = 4387685, upload-time = "2025-04-23T01:45:21.387Z" }, - { url = "https://files.pythonhosted.org/packages/d8/cb/1a3879c5f512bdcd32995c301886fe082b2edd83c87d41b6d42d89b4ea4d/lxml-5.4.0-cp311-cp311-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b92b69441d1bd39f4940f9eadfa417a25862242ca2c396b406f9272ef09cdcaa", size = 4991164, upload-time = "2025-04-23T01:45:23.849Z" }, - { url = "https://files.pythonhosted.org/packages/f9/94/bbc66e42559f9d04857071e3b3d0c9abd88579367fd2588a4042f641f57e/lxml-5.4.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:20e16c08254b9b6466526bc1828d9370ee6c0d60a4b64836bc3ac2917d1e16df", size = 4746206, upload-time = "2025-04-23T01:45:26.361Z" }, - { url = "https://files.pythonhosted.org/packages/66/95/34b0679bee435da2d7cae895731700e519a8dfcab499c21662ebe671603e/lxml-5.4.0-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:7605c1c32c3d6e8c990dd28a0970a3cbbf1429d5b92279e37fda05fb0c92190e", size = 5342144, upload-time = "2025-04-23T01:45:28.939Z" }, - { url = "https://files.pythonhosted.org/packages/e0/5d/abfcc6ab2fa0be72b2ba938abdae1f7cad4c632f8d552683ea295d55adfb/lxml-5.4.0-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:ecf4c4b83f1ab3d5a7ace10bafcb6f11df6156857a3c418244cef41ca9fa3e44", size = 4825124, upload-time = "2025-04-23T01:45:31.361Z" }, - { url = "https://files.pythonhosted.org/packages/5a/78/6bd33186c8863b36e084f294fc0a5e5eefe77af95f0663ef33809cc1c8aa/lxml-5.4.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0cef4feae82709eed352cd7e97ae062ef6ae9c7b5dbe3663f104cd2c0e8d94ba", size = 4876520, upload-time = "2025-04-23T01:45:34.191Z" }, - { url = "https://files.pythonhosted.org/packages/3b/74/4d7ad4839bd0fc64e3d12da74fc9a193febb0fae0ba6ebd5149d4c23176a/lxml-5.4.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:df53330a3bff250f10472ce96a9af28628ff1f4efc51ccba351a8820bca2a8ba", size = 4765016, upload-time = "2025-04-23T01:45:36.7Z" }, - { url = "https://files.pythonhosted.org/packages/24/0d/0a98ed1f2471911dadfc541003ac6dd6879fc87b15e1143743ca20f3e973/lxml-5.4.0-cp311-cp311-manylinux_2_28_ppc64le.whl", hash = "sha256:aefe1a7cb852fa61150fcb21a8c8fcea7b58c4cb11fbe59c97a0a4b31cae3c8c", size = 5362884, upload-time = "2025-04-23T01:45:39.291Z" }, - { url = "https://files.pythonhosted.org/packages/48/de/d4f7e4c39740a6610f0f6959052b547478107967362e8424e1163ec37ae8/lxml-5.4.0-cp311-cp311-manylinux_2_28_s390x.whl", hash = "sha256:ef5a7178fcc73b7d8c07229e89f8eb45b2908a9238eb90dcfc46571ccf0383b8", size = 4902690, upload-time = "2025-04-23T01:45:42.386Z" }, - { url = "https://files.pythonhosted.org/packages/07/8c/61763abd242af84f355ca4ef1ee096d3c1b7514819564cce70fd18c22e9a/lxml-5.4.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:d2ed1b3cb9ff1c10e6e8b00941bb2e5bb568b307bfc6b17dffbbe8be5eecba86", size = 4944418, upload-time = "2025-04-23T01:45:46.051Z" }, - { url = "https://files.pythonhosted.org/packages/f9/c5/6d7e3b63e7e282619193961a570c0a4c8a57fe820f07ca3fe2f6bd86608a/lxml-5.4.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:72ac9762a9f8ce74c9eed4a4e74306f2f18613a6b71fa065495a67ac227b3056", size = 4827092, upload-time = "2025-04-23T01:45:48.943Z" }, - { url = "https://files.pythonhosted.org/packages/71/4a/e60a306df54680b103348545706a98a7514a42c8b4fbfdcaa608567bb065/lxml-5.4.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:f5cb182f6396706dc6cc1896dd02b1c889d644c081b0cdec38747573db88a7d7", size = 5418231, upload-time = "2025-04-23T01:45:51.481Z" }, - { url = "https://files.pythonhosted.org/packages/27/f2/9754aacd6016c930875854f08ac4b192a47fe19565f776a64004aa167521/lxml-5.4.0-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:3a3178b4873df8ef9457a4875703488eb1622632a9cee6d76464b60e90adbfcd", size = 5261798, upload-time = "2025-04-23T01:45:54.146Z" }, - { url = "https://files.pythonhosted.org/packages/38/a2/0c49ec6941428b1bd4f280650d7b11a0f91ace9db7de32eb7aa23bcb39ff/lxml-5.4.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:e094ec83694b59d263802ed03a8384594fcce477ce484b0cbcd0008a211ca751", size = 4988195, upload-time = "2025-04-23T01:45:56.685Z" }, - { url = "https://files.pythonhosted.org/packages/7a/75/87a3963a08eafc46a86c1131c6e28a4de103ba30b5ae903114177352a3d7/lxml-5.4.0-cp311-cp311-win32.whl", hash = "sha256:4329422de653cdb2b72afa39b0aa04252fca9071550044904b2e7036d9d97fe4", size = 3474243, upload-time = "2025-04-23T01:45:58.863Z" }, - { url = "https://files.pythonhosted.org/packages/fa/f9/1f0964c4f6c2be861c50db380c554fb8befbea98c6404744ce243a3c87ef/lxml-5.4.0-cp311-cp311-win_amd64.whl", hash = "sha256:fd3be6481ef54b8cfd0e1e953323b7aa9d9789b94842d0e5b142ef4bb7999539", size = 3815197, upload-time = "2025-04-23T01:46:01.096Z" }, - { url = "https://files.pythonhosted.org/packages/f8/4c/d101ace719ca6a4ec043eb516fcfcb1b396a9fccc4fcd9ef593df34ba0d5/lxml-5.4.0-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:b5aff6f3e818e6bdbbb38e5967520f174b18f539c2b9de867b1e7fde6f8d95a4", size = 8127392, upload-time = "2025-04-23T01:46:04.09Z" }, - { url = "https://files.pythonhosted.org/packages/11/84/beddae0cec4dd9ddf46abf156f0af451c13019a0fa25d7445b655ba5ccb7/lxml-5.4.0-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:942a5d73f739ad7c452bf739a62a0f83e2578afd6b8e5406308731f4ce78b16d", size = 4415103, upload-time = "2025-04-23T01:46:07.227Z" }, - { url = "https://files.pythonhosted.org/packages/d0/25/d0d93a4e763f0462cccd2b8a665bf1e4343dd788c76dcfefa289d46a38a9/lxml-5.4.0-cp312-cp312-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:460508a4b07364d6abf53acaa0a90b6d370fafde5693ef37602566613a9b0779", size = 5024224, upload-time = "2025-04-23T01:46:10.237Z" }, - { url = "https://files.pythonhosted.org/packages/31/ce/1df18fb8f7946e7f3388af378b1f34fcf253b94b9feedb2cec5969da8012/lxml-5.4.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:529024ab3a505fed78fe3cc5ddc079464e709f6c892733e3f5842007cec8ac6e", size = 4769913, upload-time = "2025-04-23T01:46:12.757Z" }, - { url = "https://files.pythonhosted.org/packages/4e/62/f4a6c60ae7c40d43657f552f3045df05118636be1165b906d3423790447f/lxml-5.4.0-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:7ca56ebc2c474e8f3d5761debfd9283b8b18c76c4fc0967b74aeafba1f5647f9", size = 5290441, upload-time = "2025-04-23T01:46:16.037Z" }, - { url = "https://files.pythonhosted.org/packages/9e/aa/04f00009e1e3a77838c7fc948f161b5d2d5de1136b2b81c712a263829ea4/lxml-5.4.0-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:a81e1196f0a5b4167a8dafe3a66aa67c4addac1b22dc47947abd5d5c7a3f24b5", size = 4820165, upload-time = "2025-04-23T01:46:19.137Z" }, - { url = "https://files.pythonhosted.org/packages/c9/1f/e0b2f61fa2404bf0f1fdf1898377e5bd1b74cc9b2cf2c6ba8509b8f27990/lxml-5.4.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:00b8686694423ddae324cf614e1b9659c2edb754de617703c3d29ff568448df5", size = 4932580, upload-time = "2025-04-23T01:46:21.963Z" }, - { url = "https://files.pythonhosted.org/packages/24/a2/8263f351b4ffe0ed3e32ea7b7830f845c795349034f912f490180d88a877/lxml-5.4.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:c5681160758d3f6ac5b4fea370495c48aac0989d6a0f01bb9a72ad8ef5ab75c4", size = 4759493, upload-time = "2025-04-23T01:46:24.316Z" }, - { url = "https://files.pythonhosted.org/packages/05/00/41db052f279995c0e35c79d0f0fc9f8122d5b5e9630139c592a0b58c71b4/lxml-5.4.0-cp312-cp312-manylinux_2_28_ppc64le.whl", hash = "sha256:2dc191e60425ad70e75a68c9fd90ab284df64d9cd410ba8d2b641c0c45bc006e", size = 5324679, upload-time = "2025-04-23T01:46:27.097Z" }, - { url = "https://files.pythonhosted.org/packages/1d/be/ee99e6314cdef4587617d3b3b745f9356d9b7dd12a9663c5f3b5734b64ba/lxml-5.4.0-cp312-cp312-manylinux_2_28_s390x.whl", hash = "sha256:67f779374c6b9753ae0a0195a892a1c234ce8416e4448fe1e9f34746482070a7", size = 4890691, upload-time = "2025-04-23T01:46:30.009Z" }, - { url = "https://files.pythonhosted.org/packages/ad/36/239820114bf1d71f38f12208b9c58dec033cbcf80101cde006b9bde5cffd/lxml-5.4.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:79d5bfa9c1b455336f52343130b2067164040604e41f6dc4d8313867ed540079", size = 4955075, upload-time = "2025-04-23T01:46:32.33Z" }, - { url = "https://files.pythonhosted.org/packages/d4/e1/1b795cc0b174efc9e13dbd078a9ff79a58728a033142bc6d70a1ee8fc34d/lxml-5.4.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3d3c30ba1c9b48c68489dc1829a6eede9873f52edca1dda900066542528d6b20", size = 4838680, upload-time = "2025-04-23T01:46:34.852Z" }, - { url = "https://files.pythonhosted.org/packages/72/48/3c198455ca108cec5ae3662ae8acd7fd99476812fd712bb17f1b39a0b589/lxml-5.4.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:1af80c6316ae68aded77e91cd9d80648f7dd40406cef73df841aa3c36f6907c8", size = 5391253, upload-time = "2025-04-23T01:46:37.608Z" }, - { url = "https://files.pythonhosted.org/packages/d6/10/5bf51858971c51ec96cfc13e800a9951f3fd501686f4c18d7d84fe2d6352/lxml-5.4.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:4d885698f5019abe0de3d352caf9466d5de2baded00a06ef3f1216c1a58ae78f", size = 5261651, upload-time = "2025-04-23T01:46:40.183Z" }, - { url = "https://files.pythonhosted.org/packages/2b/11/06710dd809205377da380546f91d2ac94bad9ff735a72b64ec029f706c85/lxml-5.4.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:aea53d51859b6c64e7c51d522c03cc2c48b9b5d6172126854cc7f01aa11f52bc", size = 5024315, upload-time = "2025-04-23T01:46:43.333Z" }, - { url = "https://files.pythonhosted.org/packages/f5/b0/15b6217834b5e3a59ebf7f53125e08e318030e8cc0d7310355e6edac98ef/lxml-5.4.0-cp312-cp312-win32.whl", hash = "sha256:d90b729fd2732df28130c064aac9bb8aff14ba20baa4aee7bd0795ff1187545f", size = 3486149, upload-time = "2025-04-23T01:46:45.684Z" }, - { url = "https://files.pythonhosted.org/packages/91/1e/05ddcb57ad2f3069101611bd5f5084157d90861a2ef460bf42f45cced944/lxml-5.4.0-cp312-cp312-win_amd64.whl", hash = "sha256:1dc4ca99e89c335a7ed47d38964abcb36c5910790f9bd106f2a8fa2ee0b909d2", size = 3817095, upload-time = "2025-04-23T01:46:48.521Z" }, + { url = "https://files.pythonhosted.org/packages/d4/64/d4b59444e4d3b6979aa5eb58840634465a24b41a9ab03dcf8434c9b89551/libusb1-3.4.0-py3-none-any.whl", hash = "sha256:e83d034e44c3efe1c4599c6281d34bca50a38c12cab3b7b6217d583161a01ffd", size = 67373, upload-time = "2026-05-16T20:59:13.142Z" }, + { url = "https://files.pythonhosted.org/packages/7e/55/a838a4278fac4ee49bf670ddc59d621999a1cb2a3188fb13a23609ea4f06/libusb1-3.4.0-py3-none-win32.whl", hash = "sha256:0a1aa1416034690eb9dc9a895eda0fef44d853bca1053eb1de50a5906684846d", size = 129704, upload-time = "2026-05-16T20:59:15.243Z" }, + { url = "https://files.pythonhosted.org/packages/5f/08/02aecf6dad627534a5835244ece14d7f187ef430354d9b8551199934d059/libusb1-3.4.0-py3-none-win_amd64.whl", hash = "sha256:b7dcc1f324a895af6aac708bc5513a17373f97349cc2ab8a277519c788bd18ca", size = 141212, upload-time = "2026-05-16T20:59:17.286Z" }, ] [[package]] name = "markdown" -version = "3.8.2" +version = "3.10.2" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/d7/c2/4ab49206c17f75cb08d6311171f2d65798988db4360c4d1485bd0eedd67c/markdown-3.8.2.tar.gz", hash = "sha256:247b9a70dd12e27f67431ce62523e675b866d254f900c4fe75ce3dda62237c45", size = 362071, upload-time = "2025-06-19T17:12:44.483Z" } +sdist = { url = "https://files.pythonhosted.org/packages/2b/f4/69fa6ed85ae003c2378ffa8f6d2e3234662abd02c10d216c0ba96081a238/markdown-3.10.2.tar.gz", hash = "sha256:994d51325d25ad8aa7ce4ebaec003febcce822c3f8c911e3b17c52f7f589f950", size = 368805, upload-time = "2026-02-09T14:57:26.942Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/96/2b/34cc11786bc00d0f04d0f5fdc3a2b1ae0b6239eef72d3d345805f9ad92a1/markdown-3.8.2-py3-none-any.whl", hash = "sha256:5c83764dbd4e00bdd94d85a19b8d55ccca20fe35b2e678a1422b380324dd5f24", size = 106827, upload-time = "2025-06-19T17:12:42.994Z" }, + { url = "https://files.pythonhosted.org/packages/de/1f/77fa3081e4f66ca3576c896ae5d31c3002ac6607f9747d2e3aa49227e464/markdown-3.10.2-py3-none-any.whl", hash = "sha256:e91464b71ae3ee7afd3017d9f358ef0baf158fd9a298db92f1d4761133824c36", size = 108180, upload-time = "2026-02-09T14:57:25.787Z" }, ] [[package]] name = "markupsafe" -version = "3.0.2" +version = "3.0.3" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/b2/97/5d42485e71dfc078108a86d6de8fa46db44a1a9295e89c5d6d4a06e23a62/markupsafe-3.0.2.tar.gz", hash = "sha256:ee55d3edf80167e48ea11a923c7386f4669df67d7994554387f84e7d8b0a2bf0", size = 20537, upload-time = "2024-10-18T15:21:54.129Z" } +sdist = { url = "https://files.pythonhosted.org/packages/7e/99/7690b6d4034fffd95959cbe0c02de8deb3098cc577c67bb6a24fe5d7caa7/markupsafe-3.0.3.tar.gz", hash = "sha256:722695808f4b6457b320fdc131280796bdceb04ab50fe1795cd540799ebe1698", size = 80313, upload-time = "2025-09-27T18:37:40.426Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/6b/28/bbf83e3f76936960b850435576dd5e67034e200469571be53f69174a2dfd/MarkupSafe-3.0.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:9025b4018f3a1314059769c7bf15441064b2207cb3f065e6ea1e7359cb46db9d", size = 14353, upload-time = "2024-10-18T15:21:02.187Z" }, - { url = "https://files.pythonhosted.org/packages/6c/30/316d194b093cde57d448a4c3209f22e3046c5bb2fb0820b118292b334be7/MarkupSafe-3.0.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:93335ca3812df2f366e80509ae119189886b0f3c2b81325d39efdb84a1e2ae93", size = 12392, upload-time = "2024-10-18T15:21:02.941Z" }, - { url = "https://files.pythonhosted.org/packages/f2/96/9cdafba8445d3a53cae530aaf83c38ec64c4d5427d975c974084af5bc5d2/MarkupSafe-3.0.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2cb8438c3cbb25e220c2ab33bb226559e7afb3baec11c4f218ffa7308603c832", size = 23984, upload-time = "2024-10-18T15:21:03.953Z" }, - { url = "https://files.pythonhosted.org/packages/f1/a4/aefb044a2cd8d7334c8a47d3fb2c9f328ac48cb349468cc31c20b539305f/MarkupSafe-3.0.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a123e330ef0853c6e822384873bef7507557d8e4a082961e1defa947aa59ba84", size = 23120, upload-time = "2024-10-18T15:21:06.495Z" }, - { url = "https://files.pythonhosted.org/packages/8d/21/5e4851379f88f3fad1de30361db501300d4f07bcad047d3cb0449fc51f8c/MarkupSafe-3.0.2-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1e084f686b92e5b83186b07e8a17fc09e38fff551f3602b249881fec658d3eca", size = 23032, upload-time = "2024-10-18T15:21:07.295Z" }, - { url = "https://files.pythonhosted.org/packages/00/7b/e92c64e079b2d0d7ddf69899c98842f3f9a60a1ae72657c89ce2655c999d/MarkupSafe-3.0.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:d8213e09c917a951de9d09ecee036d5c7d36cb6cb7dbaece4c71a60d79fb9798", size = 24057, upload-time = "2024-10-18T15:21:08.073Z" }, - { url = "https://files.pythonhosted.org/packages/f9/ac/46f960ca323037caa0a10662ef97d0a4728e890334fc156b9f9e52bcc4ca/MarkupSafe-3.0.2-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:5b02fb34468b6aaa40dfc198d813a641e3a63b98c2b05a16b9f80b7ec314185e", size = 23359, upload-time = "2024-10-18T15:21:09.318Z" }, - { url = "https://files.pythonhosted.org/packages/69/84/83439e16197337b8b14b6a5b9c2105fff81d42c2a7c5b58ac7b62ee2c3b1/MarkupSafe-3.0.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:0bff5e0ae4ef2e1ae4fdf2dfd5b76c75e5c2fa4132d05fc1b0dabcd20c7e28c4", size = 23306, upload-time = "2024-10-18T15:21:10.185Z" }, - { url = "https://files.pythonhosted.org/packages/9a/34/a15aa69f01e2181ed8d2b685c0d2f6655d5cca2c4db0ddea775e631918cd/MarkupSafe-3.0.2-cp311-cp311-win32.whl", hash = "sha256:6c89876f41da747c8d3677a2b540fb32ef5715f97b66eeb0c6b66f5e3ef6f59d", size = 15094, upload-time = "2024-10-18T15:21:11.005Z" }, - { url = "https://files.pythonhosted.org/packages/da/b8/3a3bd761922d416f3dc5d00bfbed11f66b1ab89a0c2b6e887240a30b0f6b/MarkupSafe-3.0.2-cp311-cp311-win_amd64.whl", hash = "sha256:70a87b411535ccad5ef2f1df5136506a10775d267e197e4cf531ced10537bd6b", size = 15521, upload-time = "2024-10-18T15:21:12.911Z" }, - { url = "https://files.pythonhosted.org/packages/22/09/d1f21434c97fc42f09d290cbb6350d44eb12f09cc62c9476effdb33a18aa/MarkupSafe-3.0.2-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:9778bd8ab0a994ebf6f84c2b949e65736d5575320a17ae8984a77fab08db94cf", size = 14274, upload-time = "2024-10-18T15:21:13.777Z" }, - { url = "https://files.pythonhosted.org/packages/6b/b0/18f76bba336fa5aecf79d45dcd6c806c280ec44538b3c13671d49099fdd0/MarkupSafe-3.0.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:846ade7b71e3536c4e56b386c2a47adf5741d2d8b94ec9dc3e92e5e1ee1e2225", size = 12348, upload-time = "2024-10-18T15:21:14.822Z" }, - { url = "https://files.pythonhosted.org/packages/e0/25/dd5c0f6ac1311e9b40f4af06c78efde0f3b5cbf02502f8ef9501294c425b/MarkupSafe-3.0.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1c99d261bd2d5f6b59325c92c73df481e05e57f19837bdca8413b9eac4bd8028", size = 24149, upload-time = "2024-10-18T15:21:15.642Z" }, - { url = "https://files.pythonhosted.org/packages/f3/f0/89e7aadfb3749d0f52234a0c8c7867877876e0a20b60e2188e9850794c17/MarkupSafe-3.0.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e17c96c14e19278594aa4841ec148115f9c7615a47382ecb6b82bd8fea3ab0c8", size = 23118, upload-time = "2024-10-18T15:21:17.133Z" }, - { url = "https://files.pythonhosted.org/packages/d5/da/f2eeb64c723f5e3777bc081da884b414671982008c47dcc1873d81f625b6/MarkupSafe-3.0.2-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:88416bd1e65dcea10bc7569faacb2c20ce071dd1f87539ca2ab364bf6231393c", size = 22993, upload-time = "2024-10-18T15:21:18.064Z" }, - { url = "https://files.pythonhosted.org/packages/da/0e/1f32af846df486dce7c227fe0f2398dc7e2e51d4a370508281f3c1c5cddc/MarkupSafe-3.0.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:2181e67807fc2fa785d0592dc2d6206c019b9502410671cc905d132a92866557", size = 24178, upload-time = "2024-10-18T15:21:18.859Z" }, - { url = "https://files.pythonhosted.org/packages/c4/f6/bb3ca0532de8086cbff5f06d137064c8410d10779c4c127e0e47d17c0b71/MarkupSafe-3.0.2-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:52305740fe773d09cffb16f8ed0427942901f00adedac82ec8b67752f58a1b22", size = 23319, upload-time = "2024-10-18T15:21:19.671Z" }, - { url = "https://files.pythonhosted.org/packages/a2/82/8be4c96ffee03c5b4a034e60a31294daf481e12c7c43ab8e34a1453ee48b/MarkupSafe-3.0.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:ad10d3ded218f1039f11a75f8091880239651b52e9bb592ca27de44eed242a48", size = 23352, upload-time = "2024-10-18T15:21:20.971Z" }, - { url = "https://files.pythonhosted.org/packages/51/ae/97827349d3fcffee7e184bdf7f41cd6b88d9919c80f0263ba7acd1bbcb18/MarkupSafe-3.0.2-cp312-cp312-win32.whl", hash = "sha256:0f4ca02bea9a23221c0182836703cbf8930c5e9454bacce27e767509fa286a30", size = 15097, upload-time = "2024-10-18T15:21:22.646Z" }, - { url = "https://files.pythonhosted.org/packages/c1/80/a61f99dc3a936413c3ee4e1eecac96c0da5ed07ad56fd975f1a9da5bc630/MarkupSafe-3.0.2-cp312-cp312-win_amd64.whl", hash = "sha256:8e06879fc22a25ca47312fbe7c8264eb0b662f6db27cb2d3bbbc74b1df4b9b87", size = 15601, upload-time = "2024-10-18T15:21:23.499Z" }, + { url = "https://files.pythonhosted.org/packages/5a/72/147da192e38635ada20e0a2e1a51cf8823d2119ce8883f7053879c2199b5/markupsafe-3.0.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:d53197da72cc091b024dd97249dfc7794d6a56530370992a5e1a08983ad9230e", size = 11615, upload-time = "2025-09-27T18:36:30.854Z" }, + { url = "https://files.pythonhosted.org/packages/9a/81/7e4e08678a1f98521201c3079f77db69fb552acd56067661f8c2f534a718/markupsafe-3.0.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1872df69a4de6aead3491198eaf13810b565bdbeec3ae2dc8780f14458ec73ce", size = 12020, upload-time = "2025-09-27T18:36:31.971Z" }, + { url = "https://files.pythonhosted.org/packages/1e/2c/799f4742efc39633a1b54a92eec4082e4f815314869865d876824c257c1e/markupsafe-3.0.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3a7e8ae81ae39e62a41ec302f972ba6ae23a5c5396c8e60113e9066ef893da0d", size = 24332, upload-time = "2025-09-27T18:36:32.813Z" }, + { url = "https://files.pythonhosted.org/packages/3c/2e/8d0c2ab90a8c1d9a24f0399058ab8519a3279d1bd4289511d74e909f060e/markupsafe-3.0.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d6dd0be5b5b189d31db7cda48b91d7e0a9795f31430b7f271219ab30f1d3ac9d", size = 22947, upload-time = "2025-09-27T18:36:33.86Z" }, + { url = "https://files.pythonhosted.org/packages/2c/54/887f3092a85238093a0b2154bd629c89444f395618842e8b0c41783898ea/markupsafe-3.0.3-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:94c6f0bb423f739146aec64595853541634bde58b2135f27f61c1ffd1cd4d16a", size = 21962, upload-time = "2025-09-27T18:36:35.099Z" }, + { url = "https://files.pythonhosted.org/packages/c9/2f/336b8c7b6f4a4d95e91119dc8521402461b74a485558d8f238a68312f11c/markupsafe-3.0.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:be8813b57049a7dc738189df53d69395eba14fb99345e0a5994914a3864c8a4b", size = 23760, upload-time = "2025-09-27T18:36:36.001Z" }, + { url = "https://files.pythonhosted.org/packages/32/43/67935f2b7e4982ffb50a4d169b724d74b62a3964bc1a9a527f5ac4f1ee2b/markupsafe-3.0.3-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:83891d0e9fb81a825d9a6d61e3f07550ca70a076484292a70fde82c4b807286f", size = 21529, upload-time = "2025-09-27T18:36:36.906Z" }, + { url = "https://files.pythonhosted.org/packages/89/e0/4486f11e51bbba8b0c041098859e869e304d1c261e59244baa3d295d47b7/markupsafe-3.0.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:77f0643abe7495da77fb436f50f8dab76dbc6e5fd25d39589a0f1fe6548bfa2b", size = 23015, upload-time = "2025-09-27T18:36:37.868Z" }, + { url = "https://files.pythonhosted.org/packages/2f/e1/78ee7a023dac597a5825441ebd17170785a9dab23de95d2c7508ade94e0e/markupsafe-3.0.3-cp312-cp312-win32.whl", hash = "sha256:d88b440e37a16e651bda4c7c2b930eb586fd15ca7406cb39e211fcff3bf3017d", size = 14540, upload-time = "2025-09-27T18:36:38.761Z" }, + { url = "https://files.pythonhosted.org/packages/aa/5b/bec5aa9bbbb2c946ca2733ef9c4ca91c91b6a24580193e891b5f7dbe8e1e/markupsafe-3.0.3-cp312-cp312-win_amd64.whl", hash = "sha256:26a5784ded40c9e318cfc2bdb30fe164bdb8665ded9cd64d500a34fb42067b1c", size = 15105, upload-time = "2025-09-27T18:36:39.701Z" }, + { url = "https://files.pythonhosted.org/packages/e5/f1/216fc1bbfd74011693a4fd837e7026152e89c4bcf3e77b6692fba9923123/markupsafe-3.0.3-cp312-cp312-win_arm64.whl", hash = "sha256:35add3b638a5d900e807944a078b51922212fb3dedb01633a8defc4b01a3c85f", size = 13906, upload-time = "2025-09-27T18:36:40.689Z" }, ] [[package]] name = "matplotlib" -version = "3.10.3" +version = "3.11.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "contourpy" }, @@ -908,134 +594,17 @@ dependencies = [ { name = "pyparsing" }, { name = "python-dateutil" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/26/91/d49359a21893183ed2a5b6c76bec40e0b1dcbf8ca148f864d134897cfc75/matplotlib-3.10.3.tar.gz", hash = "sha256:2f82d2c5bb7ae93aaaa4cd42aca65d76ce6376f83304fa3a630b569aca274df0", size = 34799811, upload-time = "2025-05-08T19:10:54.39Z" } +sdist = { url = "https://files.pythonhosted.org/packages/1f/24/080c99d223d158d3a8902769269ab6da5b50f7a0e6e072513907e02b7a6c/matplotlib-3.11.0.tar.gz", hash = "sha256:68c0c7be01b30dcca3638934f7f591df73401235cbdbf0d1ab1c71e7db7f8b57", size = 33251176, upload-time = "2026-06-12T02:29:15.508Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/f5/bd/af9f655456f60fe1d575f54fb14704ee299b16e999704817a7645dfce6b0/matplotlib-3.10.3-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:0ef061f74cd488586f552d0c336b2f078d43bc00dc473d2c3e7bfee2272f3fa8", size = 8178873, upload-time = "2025-05-08T19:09:53.857Z" }, - { url = "https://files.pythonhosted.org/packages/c2/86/e1c86690610661cd716eda5f9d0b35eaf606ae6c9b6736687cfc8f2d0cd8/matplotlib-3.10.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:d96985d14dc5f4a736bbea4b9de9afaa735f8a0fc2ca75be2fa9e96b2097369d", size = 8052205, upload-time = "2025-05-08T19:09:55.684Z" }, - { url = "https://files.pythonhosted.org/packages/54/51/a9f8e49af3883dacddb2da1af5fca1f7468677f1188936452dd9aaaeb9ed/matplotlib-3.10.3-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7c5f0283da91e9522bdba4d6583ed9d5521566f63729ffb68334f86d0bb98049", size = 8465823, upload-time = "2025-05-08T19:09:57.442Z" }, - { url = "https://files.pythonhosted.org/packages/e7/e3/c82963a3b86d6e6d5874cbeaa390166458a7f1961bab9feb14d3d1a10f02/matplotlib-3.10.3-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fdfa07c0ec58035242bc8b2c8aae37037c9a886370eef6850703d7583e19964b", size = 8606464, upload-time = "2025-05-08T19:09:59.471Z" }, - { url = "https://files.pythonhosted.org/packages/0e/34/24da1027e7fcdd9e82da3194c470143c551852757a4b473a09a012f5b945/matplotlib-3.10.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:c0b9849a17bce080a16ebcb80a7b714b5677d0ec32161a2cc0a8e5a6030ae220", size = 9413103, upload-time = "2025-05-08T19:10:03.208Z" }, - { url = "https://files.pythonhosted.org/packages/a6/da/948a017c3ea13fd4a97afad5fdebe2f5bbc4d28c0654510ce6fd6b06b7bd/matplotlib-3.10.3-cp311-cp311-win_amd64.whl", hash = "sha256:eef6ed6c03717083bc6d69c2d7ee8624205c29a8e6ea5a31cd3492ecdbaee1e1", size = 8065492, upload-time = "2025-05-08T19:10:05.271Z" }, - { url = "https://files.pythonhosted.org/packages/eb/43/6b80eb47d1071f234ef0c96ca370c2ca621f91c12045f1401b5c9b28a639/matplotlib-3.10.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:0ab1affc11d1f495ab9e6362b8174a25afc19c081ba5b0775ef00533a4236eea", size = 8179689, upload-time = "2025-05-08T19:10:07.602Z" }, - { url = "https://files.pythonhosted.org/packages/0f/70/d61a591958325c357204870b5e7b164f93f2a8cca1dc6ce940f563909a13/matplotlib-3.10.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:2a818d8bdcafa7ed2eed74487fdb071c09c1ae24152d403952adad11fa3c65b4", size = 8050466, upload-time = "2025-05-08T19:10:09.383Z" }, - { url = "https://files.pythonhosted.org/packages/e7/75/70c9d2306203148cc7902a961240c5927dd8728afedf35e6a77e105a2985/matplotlib-3.10.3-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:748ebc3470c253e770b17d8b0557f0aa85cf8c63fd52f1a61af5b27ec0b7ffee", size = 8456252, upload-time = "2025-05-08T19:10:11.958Z" }, - { url = "https://files.pythonhosted.org/packages/c4/91/ba0ae1ff4b3f30972ad01cd4a8029e70a0ec3b8ea5be04764b128b66f763/matplotlib-3.10.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ed70453fd99733293ace1aec568255bc51c6361cb0da94fa5ebf0649fdb2150a", size = 8601321, upload-time = "2025-05-08T19:10:14.47Z" }, - { url = "https://files.pythonhosted.org/packages/d2/88/d636041eb54a84b889e11872d91f7cbf036b3b0e194a70fa064eb8b04f7a/matplotlib-3.10.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:dbed9917b44070e55640bd13419de83b4c918e52d97561544814ba463811cbc7", size = 9406972, upload-time = "2025-05-08T19:10:16.569Z" }, - { url = "https://files.pythonhosted.org/packages/b1/79/0d1c165eac44405a86478082e225fce87874f7198300bbebc55faaf6d28d/matplotlib-3.10.3-cp312-cp312-win_amd64.whl", hash = "sha256:cf37d8c6ef1a48829443e8ba5227b44236d7fcaf7647caa3178a4ff9f7a5be05", size = 8067954, upload-time = "2025-05-08T19:10:18.663Z" }, + { url = "https://files.pythonhosted.org/packages/da/17/f5276b496c61477a6c4fc5e7401f4bfe1c2e5ef7c6cd67896f2ade3809cb/matplotlib-3.11.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:06b5872e9cf11adc8f589ded3ce11bc3e1061ad498259664fabc1f6615beb918", size = 9449976, upload-time = "2026-06-12T02:27:50.989Z" }, + { url = "https://files.pythonhosted.org/packages/82/34/bdd77418adb2178a1d59f044bd67bfebb115896e91b840b8a197eb3f4f4e/matplotlib-3.11.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:0515d495124be3124340e59f164d901ed4484e2246a5b74cfa483cac3b80bd97", size = 9279307, upload-time = "2026-06-12T02:27:53.247Z" }, + { url = "https://files.pythonhosted.org/packages/94/95/7f522393c88313336b20d70fc849555757b2e5febc22b83b3a3f0fd4bce9/matplotlib-3.11.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:be5f93a1d21981bfb802ded0d77a0caa92d4342a47d45754fac77e314a506344", size = 10031353, upload-time = "2026-06-12T02:27:55.215Z" }, + { url = "https://files.pythonhosted.org/packages/87/ce/8f25a0e3186aefd61913e7467d1b999465bcd0d0c03ac695c1b26ca559b7/matplotlib-3.11.0-cp312-cp312-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:41635d7909d19e52e924a521dde6d8f670b0f53ab1d0e8c331fa831554f681d1", size = 10839232, upload-time = "2026-06-12T02:27:57.746Z" }, + { url = "https://files.pythonhosted.org/packages/85/c2/db15da2bbdf9e3ca66df7db8e2c33a1dfed67be24a24d2c878efaaff01d6/matplotlib-3.11.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:94f5000f67ca9faa300863ea17f8bce9175cb67b88bec4bc7780502d53dd7c9e", size = 10923899, upload-time = "2026-06-12T02:28:00.223Z" }, + { url = "https://files.pythonhosted.org/packages/e5/2f/a58a4443a4d052a4ea77557478336aefc26c7981f6408d37adba763aa758/matplotlib-3.11.0-cp312-cp312-win_amd64.whl", hash = "sha256:ac6f1ef39f3d0f9e2463303013094992cdbe0f85f43bc54155bc472b2042768e", size = 9329528, upload-time = "2026-06-12T02:28:02.27Z" }, + { url = "https://files.pythonhosted.org/packages/61/0f/4b669589d47733b97ab9df4b58d6fc1e68acb5ea42a928dc7cbdd6bf5871/matplotlib-3.11.0-cp312-cp312-win_arm64.whl", hash = "sha256:9dd11fb612ce7bc60b1de5b4fc87ff959d22317b5de42aabf392f66f97af22eb", size = 9003413, upload-time = "2026-06-12T02:28:04.49Z" }, ] -[[package]] -name = "mergedeep" -version = "1.3.4" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/3a/41/580bb4006e3ed0361b8151a01d324fb03f420815446c7def45d02f74c270/mergedeep-1.3.4.tar.gz", hash = "sha256:0096d52e9dad9939c3d975a774666af186eda617e6ca84df4c94dec30004f2a8", size = 4661, upload-time = "2021-02-05T18:55:30.623Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/2c/19/04f9b178c2d8a15b076c8b5140708fa6ffc5601fb6f1e975537072df5b2a/mergedeep-1.3.4-py3-none-any.whl", hash = "sha256:70775750742b25c0d8f36c55aed03d24c3384d17c951b3175d898bd778ef0307", size = 6354, upload-time = "2021-02-05T18:55:29.583Z" }, -] - -[[package]] -name = "metadrive-simulator" -version = "0.4.2.4" -source = { url = "https://github.com/commaai/metadrive/releases/download/MetaDrive-minimal-0.4.2.4/metadrive_simulator-0.4.2.4-py3-none-any.whl" } -dependencies = [ - { name = "filelock" }, - { name = "gymnasium" }, - { name = "lxml" }, - { name = "matplotlib" }, - { name = "numpy" }, - { name = "opencv-python-headless" }, - { name = "panda3d" }, - { name = "panda3d-gltf" }, - { name = "pillow" }, - { name = "progressbar" }, - { name = "psutil" }, - { name = "pygments" }, - { name = "requests" }, - { name = "shapely" }, - { name = "tqdm" }, - { name = "yapf" }, -] -wheels = [ - { url = "https://github.com/commaai/metadrive/releases/download/MetaDrive-minimal-0.4.2.4/metadrive_simulator-0.4.2.4-py3-none-any.whl", hash = "sha256:fbf0ea9be67e65cd45d38ff930e3d49f705dd76c9ddbd1e1482e3f87b61efcef" }, -] - -[package.metadata] -requires-dist = [ - { name = "cuda-python", marker = "extra == 'cuda'", specifier = "==12.0.0" }, - { name = "filelock" }, - { name = "glfw", marker = "extra == 'cuda'" }, - { name = "gym", marker = "extra == 'gym'", specifier = ">=0.19.0,<=0.26.0" }, - { name = "gymnasium", specifier = ">=0.28" }, - { name = "lxml" }, - { name = "matplotlib" }, - { name = "numpy", specifier = ">=1.21.6" }, - { name = "opencv-python-headless" }, - { name = "panda3d", specifier = "==1.10.14" }, - { name = "panda3d-gltf", specifier = "==0.13" }, - { name = "pillow" }, - { name = "progressbar" }, - { name = "psutil" }, - { name = "pygments" }, - { name = "pyopengl", marker = "extra == 'cuda'", specifier = "==3.1.6" }, - { name = "pyopengl-accelerate", marker = "extra == 'cuda'", specifier = "==3.1.6" }, - { name = "pyrr", marker = "extra == 'cuda'", specifier = "==0.10.3" }, - { name = "requests" }, - { name = "shapely" }, - { name = "tqdm" }, - { name = "yapf" }, - { name = "zmq", marker = "extra == 'ros'" }, -] -provides-extras = ["cuda", "gym", "ros"] - -[[package]] -name = "mkdocs" -version = "1.6.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "click" }, - { name = "colorama", marker = "sys_platform == 'win32'" }, - { name = "ghp-import" }, - { name = "jinja2" }, - { name = "markdown" }, - { name = "markupsafe" }, - { name = "mergedeep" }, - { name = "mkdocs-get-deps" }, - { name = "packaging" }, - { name = "pathspec" }, - { name = "pyyaml" }, - { name = "pyyaml-env-tag" }, - { name = "watchdog" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/bc/c6/bbd4f061bd16b378247f12953ffcb04786a618ce5e904b8c5a01a0309061/mkdocs-1.6.1.tar.gz", hash = "sha256:7b432f01d928c084353ab39c57282f29f92136665bdd6abf7c1ec8d822ef86f2", size = 3889159, upload-time = "2024-08-30T12:24:06.899Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/22/5b/dbc6a8cddc9cfa9c4971d59fb12bb8d42e161b7e7f8cc89e49137c5b279c/mkdocs-1.6.1-py3-none-any.whl", hash = "sha256:db91759624d1647f3f34aa0c3f327dd2601beae39a366d6e064c03468d35c20e", size = 3864451, upload-time = "2024-08-30T12:24:05.054Z" }, -] - -[[package]] -name = "mkdocs-get-deps" -version = "0.2.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "mergedeep" }, - { name = "platformdirs" }, - { name = "pyyaml" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/98/f5/ed29cd50067784976f25ed0ed6fcd3c2ce9eb90650aa3b2796ddf7b6870b/mkdocs_get_deps-0.2.0.tar.gz", hash = "sha256:162b3d129c7fad9b19abfdcb9c1458a651628e4b1dea628ac68790fb3061c60c", size = 10239, upload-time = "2023-11-20T17:51:09.981Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/9f/d4/029f984e8d3f3b6b726bd33cafc473b75e9e44c0f7e80a5b29abc466bdea/mkdocs_get_deps-0.2.0-py3-none-any.whl", hash = "sha256:2bf11d0b133e77a0dd036abeeb06dec8775e46efa526dc70667d8863eefc6134", size = 9521, upload-time = "2023-11-20T17:51:08.587Z" }, -] - -[[package]] -name = "mouseinfo" -version = "0.1.3" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyperclip" }, - { name = "python3-xlib", marker = "sys_platform == 'linux'" }, - { name = "rubicon-objc", marker = "sys_platform == 'darwin'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/28/fa/b2ba8229b9381e8f6381c1dcae6f4159a7f72349e414ed19cfbbd1817173/MouseInfo-0.1.3.tar.gz", hash = "sha256:2c62fb8885062b8e520a3cce0a297c657adcc08c60952eb05bc8256ef6f7f6e7", size = 10850, upload-time = "2020-03-27T21:20:10.136Z" } - [[package]] name = "mpmath" version = "1.3.0" @@ -1046,188 +615,83 @@ wheels = [ ] [[package]] -name = "msal" -version = "1.32.3" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "cryptography" }, - { name = "pyjwt", extra = ["crypto"] }, - { name = "requests" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/3f/90/81dcc50f0be11a8c4dcbae1a9f761a26e5f905231330a7cacc9f04ec4c61/msal-1.32.3.tar.gz", hash = "sha256:5eea038689c78a5a70ca8ecbe1245458b55a857bd096efb6989c69ba15985d35", size = 151449, upload-time = "2025-04-25T13:12:34.204Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/04/bf/81516b9aac7fd867709984d08eb4db1d2e3fe1df795c8e442cde9b568962/msal-1.32.3-py3-none-any.whl", hash = "sha256:b2798db57760b1961b142f027ffb7c8169536bf77316e99a0df5c4aaebb11569", size = 115358, upload-time = "2025-04-25T13:12:33.034Z" }, -] +name = "msgq" +version = "0.0.1" +source = { editable = "msgq_repo" } -[[package]] -name = "msal-extensions" -version = "1.3.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "msal" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/01/99/5d239b6156eddf761a636bded1118414d161bd6b7b37a9335549ed159396/msal_extensions-1.3.1.tar.gz", hash = "sha256:c5b0fd10f65ef62b5f1d62f4251d51cbcaf003fcedae8c91b040a488614be1a4", size = 23315, upload-time = "2025-03-14T23:51:03.902Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/5e/75/bd9b7bb966668920f06b200e84454c8f3566b102183bc55c5473d96cb2b9/msal_extensions-1.3.1-py3-none-any.whl", hash = "sha256:96d3de4d034504e969ac5e85bae8106c8373b5c6568e4c8fa7af2eca9dbe6bca", size = 20583, upload-time = "2025-03-14T23:51:03.016Z" }, -] - -[[package]] -name = "multidict" -version = "6.5.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/46/b5/59f27b4ce9951a4bce56b88ba5ff5159486797ab18863f2b4c1c5e8465bd/multidict-6.5.0.tar.gz", hash = "sha256:942bd8002492ba819426a8d7aefde3189c1b87099cdf18aaaefefcf7f3f7b6d2", size = 98512, upload-time = "2025-06-17T14:15:56.556Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/75/ba/484f8e96ee58ec4fef42650eb9dbbedb24f9bc155780888398a4725d2270/multidict-6.5.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:8b4bf6bb15a05796a07a248084e3e46e032860c899c7a9b981030e61368dba95", size = 73283, upload-time = "2025-06-17T14:13:50.406Z" }, - { url = "https://files.pythonhosted.org/packages/71/48/01d62ea6199d76934c87746695b3ed16aeedfdd564e8d89184577037baac/multidict-6.5.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:46bb05d50219655c42a4b8fcda9c7ee658a09adbb719c48e65a20284e36328ea", size = 42937, upload-time = "2025-06-17T14:13:51.45Z" }, - { url = "https://files.pythonhosted.org/packages/da/cf/bb462d920f26d9e2e0aff8a78aeb06af1225b826e9a5468870c57591910a/multidict-6.5.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:54f524d73f4d54e87e03c98f6af601af4777e4668a52b1bd2ae0a4d6fc7b392b", size = 42748, upload-time = "2025-06-17T14:13:52.505Z" }, - { url = "https://files.pythonhosted.org/packages/cd/b1/d5c11ea0fdad68d3ed45f0e2527de6496d2fac8afe6b8ca6d407c20ad00f/multidict-6.5.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:529b03600466480ecc502000d62e54f185a884ed4570dee90d9a273ee80e37b5", size = 236448, upload-time = "2025-06-17T14:13:53.562Z" }, - { url = "https://files.pythonhosted.org/packages/fc/69/c3ceb264994f5b338c812911a8d660084f37779daef298fc30bd817f75c7/multidict-6.5.0-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:69ad681ad7c93a41ee7005cc83a144b5b34a3838bcf7261e2b5356057b0f78de", size = 228695, upload-time = "2025-06-17T14:13:54.775Z" }, - { url = "https://files.pythonhosted.org/packages/81/3d/c23dcc0d34a35ad29974184db2878021d28fe170ecb9192be6bfee73f1f2/multidict-6.5.0-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3fe9fada8bc0839466b09fa3f6894f003137942984843ec0c3848846329a36ae", size = 247434, upload-time = "2025-06-17T14:13:56.039Z" }, - { url = "https://files.pythonhosted.org/packages/06/b3/06cf7a049129ff52525a859277abb5648e61d7afae7fb7ed02e3806be34e/multidict-6.5.0-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f94c6ea6405fcf81baef1e459b209a78cda5442e61b5b7a57ede39d99b5204a0", size = 239431, upload-time = "2025-06-17T14:13:57.33Z" }, - { url = "https://files.pythonhosted.org/packages/8a/72/b2fe2fafa23af0c6123aebe23b4cd23fdad01dfe7009bb85624e4636d0dd/multidict-6.5.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:84ca75ad8a39ed75f079a8931435a5b51ee4c45d9b32e1740f99969a5d1cc2ee", size = 231542, upload-time = "2025-06-17T14:13:58.597Z" }, - { url = "https://files.pythonhosted.org/packages/a1/c9/a52ca0a342a02411a31b6af197a6428a5137d805293f10946eeab614ec06/multidict-6.5.0-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:be4c08f3a2a6cc42b414496017928d95898964fed84b1b2dace0c9ee763061f9", size = 233069, upload-time = "2025-06-17T14:13:59.834Z" }, - { url = "https://files.pythonhosted.org/packages/9b/55/a3328a3929b8e131e2678d5e65f552b0a6874fab62123e31f5a5625650b0/multidict-6.5.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:046a7540cfbb4d5dc846a1fd9843f3ba980c6523f2e0c5b8622b4a5c94138ae6", size = 250596, upload-time = "2025-06-17T14:14:01.178Z" }, - { url = "https://files.pythonhosted.org/packages/6c/b8/aa3905a38a8287013aeb0a54c73f79ccd8b32d2f1d53e5934643a36502c2/multidict-6.5.0-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:64306121171d988af77d74be0d8c73ee1a69cf6f96aea7fa6030c88f32a152dd", size = 237858, upload-time = "2025-06-17T14:14:03.232Z" }, - { url = "https://files.pythonhosted.org/packages/d3/eb/f11d5af028014f402e5dd01ece74533964fa4e7bfae4af4824506fa8c398/multidict-6.5.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:b4ac1dd5eb0ecf6f7351d5a9137f30a83f7182209c5d37f61614dfdce5714853", size = 249175, upload-time = "2025-06-17T14:14:04.561Z" }, - { url = "https://files.pythonhosted.org/packages/ac/57/d451905a62e5ef489cb4f92e8190d34ac5329427512afd7f893121da4e96/multidict-6.5.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:bab4a8337235365f4111a7011a1f028826ca683834ebd12de4b85e2844359c36", size = 259532, upload-time = "2025-06-17T14:14:05.798Z" }, - { url = "https://files.pythonhosted.org/packages/d3/90/ff82b5ac5cabe3c79c50cf62a62f3837905aa717e67b6b4b7872804f23c8/multidict-6.5.0-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:a05b5604c5a75df14a63eeeca598d11b2c3745b9008539b70826ea044063a572", size = 250554, upload-time = "2025-06-17T14:14:07.382Z" }, - { url = "https://files.pythonhosted.org/packages/d5/5a/0cabc50d4bc16e61d8b0a8a74499a1409fa7b4ef32970b7662a423781fc7/multidict-6.5.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:67c4a640952371c9ca65b6a710598be246ef3be5ca83ed38c16a7660d3980877", size = 248159, upload-time = "2025-06-17T14:14:08.65Z" }, - { url = "https://files.pythonhosted.org/packages/c0/1d/adeabae0771544f140d9f42ab2c46eaf54e793325999c36106078b7f6600/multidict-6.5.0-cp311-cp311-win32.whl", hash = "sha256:fdeae096ca36c12d8aca2640b8407a9d94e961372c68435bef14e31cce726138", size = 40357, upload-time = "2025-06-17T14:14:09.91Z" }, - { url = "https://files.pythonhosted.org/packages/e1/fe/bbd85ae65c96de5c9910c332ee1f4b7be0bf0fb21563895167bcb6502a1f/multidict-6.5.0-cp311-cp311-win_amd64.whl", hash = "sha256:e2977ef8b7ce27723ee8c610d1bd1765da4f3fbe5a64f9bf1fd3b4770e31fbc0", size = 44432, upload-time = "2025-06-17T14:14:11.013Z" }, - { url = "https://files.pythonhosted.org/packages/96/af/f9052d9c4e65195b210da9f7afdea06d3b7592b3221cc0ef1b407f762faa/multidict-6.5.0-cp311-cp311-win_arm64.whl", hash = "sha256:82d0cf0ea49bae43d9e8c3851e21954eff716259ff42da401b668744d1760bcb", size = 41408, upload-time = "2025-06-17T14:14:12.112Z" }, - { url = "https://files.pythonhosted.org/packages/0a/fa/18f4950e00924f7e84c8195f4fc303295e14df23f713d64e778b8fa8b903/multidict-6.5.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:1bb986c8ea9d49947bc325c51eced1ada6d8d9b4c5b15fd3fcdc3c93edef5a74", size = 73474, upload-time = "2025-06-17T14:14:13.528Z" }, - { url = "https://files.pythonhosted.org/packages/6c/66/0392a2a8948bccff57e4793c9dde3e5c088f01e8b7f8867ee58a2f187fc5/multidict-6.5.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:03c0923da300120830fc467e23805d63bbb4e98b94032bd863bc7797ea5fa653", size = 43741, upload-time = "2025-06-17T14:14:15.188Z" }, - { url = "https://files.pythonhosted.org/packages/98/3e/f48487c91b2a070566cfbab876d7e1ebe7deb0a8002e4e896a97998ae066/multidict-6.5.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:4c78d5ec00fdd35c91680ab5cf58368faad4bd1a8721f87127326270248de9bc", size = 42143, upload-time = "2025-06-17T14:14:16.612Z" }, - { url = "https://files.pythonhosted.org/packages/3f/49/439c6cc1cd00365cf561bdd3579cc3fa1a0d38effb3a59b8d9562839197f/multidict-6.5.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:aadc3cb78be90a887f8f6b73945b840da44b4a483d1c9750459ae69687940c97", size = 239303, upload-time = "2025-06-17T14:14:17.707Z" }, - { url = "https://files.pythonhosted.org/packages/c4/24/491786269e90081cb536e4d7429508725bc92ece176d1204a4449de7c41c/multidict-6.5.0-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:5b02e1ca495d71e07e652e4cef91adae3bf7ae4493507a263f56e617de65dafc", size = 236913, upload-time = "2025-06-17T14:14:18.981Z" }, - { url = "https://files.pythonhosted.org/packages/e8/76/bbe2558b820ebeca8a317ab034541790e8160ca4b1e450415383ac69b339/multidict-6.5.0-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:7fe92a62326eef351668eec4e2dfc494927764a0840a1895cff16707fceffcd3", size = 250752, upload-time = "2025-06-17T14:14:20.297Z" }, - { url = "https://files.pythonhosted.org/packages/3e/e3/3977f2c1123f553ceff9f53cd4de04be2c1912333c6fabbcd51531655476/multidict-6.5.0-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:7673ee4f63879ecd526488deb1989041abcb101b2d30a9165e1e90c489f3f7fb", size = 243937, upload-time = "2025-06-17T14:14:21.935Z" }, - { url = "https://files.pythonhosted.org/packages/b6/b8/7a6e9c13c79709cdd2f22ee849f058e6da76892d141a67acc0e6c30d845c/multidict-6.5.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fa097ae2a29f573de7e2d86620cbdda5676d27772d4ed2669cfa9961a0d73955", size = 237419, upload-time = "2025-06-17T14:14:23.215Z" }, - { url = "https://files.pythonhosted.org/packages/84/9d/8557f5e88da71bc7e7a8ace1ada4c28197f3bfdc2dd6e51d3b88f2e16e8e/multidict-6.5.0-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:300da0fa4f8457d9c4bd579695496116563409e676ac79b5e4dca18e49d1c308", size = 237222, upload-time = "2025-06-17T14:14:24.516Z" }, - { url = "https://files.pythonhosted.org/packages/a3/3b/8f023ad60e7969cb6bc0683738d0e1618f5ff5723d6d2d7818dc6df6ad3d/multidict-6.5.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:9a19bd108c35877b57393243d392d024cfbfdefe759fd137abb98f6fc910b64c", size = 247861, upload-time = "2025-06-17T14:14:25.839Z" }, - { url = "https://files.pythonhosted.org/packages/af/1c/9cf5a099ce7e3189906cf5daa72c44ee962dcb4c1983659f3a6f8a7446ab/multidict-6.5.0-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:0f32a1777465a35c35ddbbd7fc1293077938a69402fcc59e40b2846d04a120dd", size = 243917, upload-time = "2025-06-17T14:14:27.164Z" }, - { url = "https://files.pythonhosted.org/packages/6c/bb/88ee66ebeef56868044bac58feb1cc25658bff27b20e3cfc464edc181287/multidict-6.5.0-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:9cc1e10c14ce8112d1e6d8971fe3cdbe13e314f68bea0e727429249d4a6ce164", size = 249214, upload-time = "2025-06-17T14:14:28.795Z" }, - { url = "https://files.pythonhosted.org/packages/3e/ec/a90e88cc4a1309f33088ab1cdd5c0487718f49dfb82c5ffc845bb17c1973/multidict-6.5.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:e95c5e07a06594bdc288117ca90e89156aee8cb2d7c330b920d9c3dd19c05414", size = 258682, upload-time = "2025-06-17T14:14:30.066Z" }, - { url = "https://files.pythonhosted.org/packages/d2/d8/16dd69a6811920a31f4e06114ebe67b1cd922c8b05c9c82b050706d0b6fe/multidict-6.5.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:40ff26f58323795f5cd2855e2718a1720a1123fb90df4553426f0efd76135462", size = 254254, upload-time = "2025-06-17T14:14:31.323Z" }, - { url = "https://files.pythonhosted.org/packages/ac/a8/90193a5f5ca1bdbf92633d69a25a2ef9bcac7b412b8d48c84d01a2732518/multidict-6.5.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:76803a29fd71869a8b59c2118c9dcfb3b8f9c8723e2cce6baeb20705459505cf", size = 247741, upload-time = "2025-06-17T14:14:32.717Z" }, - { url = "https://files.pythonhosted.org/packages/cd/43/29c7a747153c05b41d1f67455426af39ed88d6de3f21c232b8f2724bde13/multidict-6.5.0-cp312-cp312-win32.whl", hash = "sha256:df7ecbc65a53a2ce1b3a0c82e6ad1a43dcfe7c6137733f9176a92516b9f5b851", size = 41049, upload-time = "2025-06-17T14:14:33.941Z" }, - { url = "https://files.pythonhosted.org/packages/1e/e8/8f3fc32b7e901f3a2719764d64aeaf6ae77b4ba961f1c3a3cf3867766636/multidict-6.5.0-cp312-cp312-win_amd64.whl", hash = "sha256:0ec1c3fbbb0b655a6540bce408f48b9a7474fd94ed657dcd2e890671fefa7743", size = 44700, upload-time = "2025-06-17T14:14:35.016Z" }, - { url = "https://files.pythonhosted.org/packages/24/e4/e250806adc98d524d41e69c8d4a42bc3513464adb88cb96224df12928617/multidict-6.5.0-cp312-cp312-win_arm64.whl", hash = "sha256:2d24a00d34808b22c1f15902899b9d82d0faeca9f56281641c791d8605eacd35", size = 41703, upload-time = "2025-06-17T14:14:36.168Z" }, - { url = "https://files.pythonhosted.org/packages/44/d8/45e8fc9892a7386d074941429e033adb4640e59ff0780d96a8cf46fe788e/multidict-6.5.0-py3-none-any.whl", hash = "sha256:5634b35f225977605385f56153bd95a7133faffc0ffe12ad26e10517537e8dfc", size = 12181, upload-time = "2025-06-17T14:15:55.156Z" }, -] - -[[package]] -name = "mypy" -version = "1.16.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "mypy-extensions" }, - { name = "pathspec" }, - { name = "typing-extensions" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/81/69/92c7fa98112e4d9eb075a239caa4ef4649ad7d441545ccffbd5e34607cbb/mypy-1.16.1.tar.gz", hash = "sha256:6bd00a0a2094841c5e47e7374bb42b83d64c527a502e3334e1173a0c24437bab", size = 3324747, upload-time = "2025-06-16T16:51:35.145Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/9a/61/ec1245aa1c325cb7a6c0f8570a2eee3bfc40fa90d19b1267f8e50b5c8645/mypy-1.16.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:472e4e4c100062488ec643f6162dd0d5208e33e2f34544e1fc931372e806c0cc", size = 10890557, upload-time = "2025-06-16T16:37:21.421Z" }, - { url = "https://files.pythonhosted.org/packages/6b/bb/6eccc0ba0aa0c7a87df24e73f0ad34170514abd8162eb0c75fd7128171fb/mypy-1.16.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:ea16e2a7d2714277e349e24d19a782a663a34ed60864006e8585db08f8ad1782", size = 10012921, upload-time = "2025-06-16T16:51:28.659Z" }, - { url = "https://files.pythonhosted.org/packages/5f/80/b337a12e2006715f99f529e732c5f6a8c143bb58c92bb142d5ab380963a5/mypy-1.16.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:08e850ea22adc4d8a4014651575567b0318ede51e8e9fe7a68f25391af699507", size = 11802887, upload-time = "2025-06-16T16:50:53.627Z" }, - { url = "https://files.pythonhosted.org/packages/d9/59/f7af072d09793d581a745a25737c7c0a945760036b16aeb620f658a017af/mypy-1.16.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:22d76a63a42619bfb90122889b903519149879ddbf2ba4251834727944c8baca", size = 12531658, upload-time = "2025-06-16T16:33:55.002Z" }, - { url = "https://files.pythonhosted.org/packages/82/c4/607672f2d6c0254b94a646cfc45ad589dd71b04aa1f3d642b840f7cce06c/mypy-1.16.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:2c7ce0662b6b9dc8f4ed86eb7a5d505ee3298c04b40ec13b30e572c0e5ae17c4", size = 12732486, upload-time = "2025-06-16T16:37:03.301Z" }, - { url = "https://files.pythonhosted.org/packages/b6/5e/136555ec1d80df877a707cebf9081bd3a9f397dedc1ab9750518d87489ec/mypy-1.16.1-cp311-cp311-win_amd64.whl", hash = "sha256:211287e98e05352a2e1d4e8759c5490925a7c784ddc84207f4714822f8cf99b6", size = 9479482, upload-time = "2025-06-16T16:47:37.48Z" }, - { url = "https://files.pythonhosted.org/packages/b4/d6/39482e5fcc724c15bf6280ff5806548c7185e0c090712a3736ed4d07e8b7/mypy-1.16.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:af4792433f09575d9eeca5c63d7d90ca4aeceda9d8355e136f80f8967639183d", size = 11066493, upload-time = "2025-06-16T16:47:01.683Z" }, - { url = "https://files.pythonhosted.org/packages/e6/e5/26c347890efc6b757f4d5bb83f4a0cf5958b8cf49c938ac99b8b72b420a6/mypy-1.16.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:66df38405fd8466ce3517eda1f6640611a0b8e70895e2a9462d1d4323c5eb4b9", size = 10081687, upload-time = "2025-06-16T16:48:19.367Z" }, - { url = "https://files.pythonhosted.org/packages/44/c7/b5cb264c97b86914487d6a24bd8688c0172e37ec0f43e93b9691cae9468b/mypy-1.16.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:44e7acddb3c48bd2713994d098729494117803616e116032af192871aed80b79", size = 11839723, upload-time = "2025-06-16T16:49:20.912Z" }, - { url = "https://files.pythonhosted.org/packages/15/f8/491997a9b8a554204f834ed4816bda813aefda31cf873bb099deee3c9a99/mypy-1.16.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0ab5eca37b50188163fa7c1b73c685ac66c4e9bdee4a85c9adac0e91d8895e15", size = 12722980, upload-time = "2025-06-16T16:37:40.929Z" }, - { url = "https://files.pythonhosted.org/packages/df/f0/2bd41e174b5fd93bc9de9a28e4fb673113633b8a7f3a607fa4a73595e468/mypy-1.16.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:dedb6229b2c9086247e21a83c309754b9058b438704ad2f6807f0d8227f6ebdd", size = 12903328, upload-time = "2025-06-16T16:34:35.099Z" }, - { url = "https://files.pythonhosted.org/packages/61/81/5572108a7bec2c46b8aff7e9b524f371fe6ab5efb534d38d6b37b5490da8/mypy-1.16.1-cp312-cp312-win_amd64.whl", hash = "sha256:1f0435cf920e287ff68af3d10a118a73f212deb2ce087619eb4e648116d1fe9b", size = 9562321, upload-time = "2025-06-16T16:48:58.823Z" }, - { url = "https://files.pythonhosted.org/packages/cf/d3/53e684e78e07c1a2bf7105715e5edd09ce951fc3f47cf9ed095ec1b7a037/mypy-1.16.1-py3-none-any.whl", hash = "sha256:5fc2ac4027d0ef28d6ba69a0343737a23c4d1b83672bf38d1fe237bdc0643b37", size = 2265923, upload-time = "2025-06-16T16:48:02.366Z" }, -] - -[[package]] -name = "mypy-extensions" -version = "1.1.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a2/6e/371856a3fb9d31ca8dac321cda606860fa4548858c0cc45d9d1d4ca2628b/mypy_extensions-1.1.0.tar.gz", hash = "sha256:52e68efc3284861e772bbcd66823fde5ae21fd2fdb51c62a211403730b916558", size = 6343, upload-time = "2025-04-22T14:54:24.164Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/79/7b/2c79738432f5c924bef5071f933bcc9efd0473bac3b4aa584a6f7c1c8df8/mypy_extensions-1.1.0-py3-none-any.whl", hash = "sha256:1be4cccdb0f2482337c4743e60421de3a356cd97508abadd57d47403e94f5505", size = 4963, upload-time = "2025-04-22T14:54:22.983Z" }, -] - -[[package]] -name = "natsort" -version = "8.4.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/e2/a9/a0c57aee75f77794adaf35322f8b6404cbd0f89ad45c87197a937764b7d0/natsort-8.4.0.tar.gz", hash = "sha256:45312c4a0e5507593da193dedd04abb1469253b601ecaf63445ad80f0a1ea581", size = 76575, upload-time = "2023-06-20T04:17:19.925Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/ef/82/7a9d0550484a62c6da82858ee9419f3dd1ccc9aa1c26a1e43da3ecd20b0d/natsort-8.4.0-py3-none-any.whl", hash = "sha256:4732914fb471f56b5cce04d7bae6f164a592c7712e1c85f9ef585e197299521c", size = 38268, upload-time = "2023-06-20T04:17:17.522Z" }, +[package.metadata] +requires-dist = [ + { name = "catch2", marker = "extra == 'dev'", git = "https://github.com/commaai/dependencies.git?subdirectory=catch2&rev=release-catch2" }, + { name = "codespell", marker = "extra == 'dev'" }, + { name = "cppcheck", marker = "extra == 'dev'" }, + { name = "cpplint", marker = "extra == 'dev'" }, + { name = "cython", marker = "extra == 'dev'" }, + { name = "lefthook", marker = "extra == 'dev'" }, + { name = "parameterized", marker = "extra == 'dev'" }, + { name = "ruff", marker = "extra == 'dev'" }, + { name = "scons", marker = "extra == 'dev'" }, + { name = "setuptools", marker = "extra == 'dev'" }, + { name = "ty", marker = "extra == 'dev'" }, ] +provides-extras = ["dev"] [[package]] name = "numpy" -version = "2.1.3" +version = "2.5.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/25/ca/1166b75c21abd1da445b97bf1fa2f14f423c6cfb4fc7c4ef31dccf9f6a94/numpy-2.1.3.tar.gz", hash = "sha256:aa08e04e08aaf974d4458def539dece0d28146d866a39da5639596f4921fd761", size = 20166090, upload-time = "2024-11-02T17:48:55.832Z" } +sdist = { url = "https://files.pythonhosted.org/packages/e7/05/3d27272d30698dc0ecb7fdfaa41ad70303b444f81722bb99bce1d818638a/numpy-2.5.0.tar.gz", hash = "sha256:5a129578019311b6e56bdd714250f19b518f7dceeeb8d1af5490f4942d3f891c", size = 20652461, upload-time = "2026-06-21T20:57:51.95Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/ad/81/c8167192eba5247593cd9d305ac236847c2912ff39e11402e72ae28a4985/numpy-2.1.3-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:4d1167c53b93f1f5d8a139a742b3c6f4d429b54e74e6b57d0eff40045187b15d", size = 21156252, upload-time = "2024-11-02T17:34:01.372Z" }, - { url = "https://files.pythonhosted.org/packages/da/74/5a60003fc3d8a718d830b08b654d0eea2d2db0806bab8f3c2aca7e18e010/numpy-2.1.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:c80e4a09b3d95b4e1cac08643f1152fa71a0a821a2d4277334c88d54b2219a41", size = 13784119, upload-time = "2024-11-02T17:34:23.809Z" }, - { url = "https://files.pythonhosted.org/packages/47/7c/864cb966b96fce5e63fcf25e1e4d957fe5725a635e5f11fe03f39dd9d6b5/numpy-2.1.3-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:576a1c1d25e9e02ed7fa5477f30a127fe56debd53b8d2c89d5578f9857d03ca9", size = 5352978, upload-time = "2024-11-02T17:34:34.001Z" }, - { url = "https://files.pythonhosted.org/packages/09/ac/61d07930a4993dd9691a6432de16d93bbe6aa4b1c12a5e573d468eefc1ca/numpy-2.1.3-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:973faafebaae4c0aaa1a1ca1ce02434554d67e628b8d805e61f874b84e136b09", size = 6892570, upload-time = "2024-11-02T17:34:45.401Z" }, - { url = "https://files.pythonhosted.org/packages/27/2f/21b94664f23af2bb52030653697c685022119e0dc93d6097c3cb45bce5f9/numpy-2.1.3-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:762479be47a4863e261a840e8e01608d124ee1361e48b96916f38b119cfda04a", size = 13896715, upload-time = "2024-11-02T17:35:06.564Z" }, - { url = "https://files.pythonhosted.org/packages/7a/f0/80811e836484262b236c684a75dfc4ba0424bc670e765afaa911468d9f39/numpy-2.1.3-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bc6f24b3d1ecc1eebfbf5d6051faa49af40b03be1aaa781ebdadcbc090b4539b", size = 16339644, upload-time = "2024-11-02T17:35:30.888Z" }, - { url = "https://files.pythonhosted.org/packages/fa/81/ce213159a1ed8eb7d88a2a6ef4fbdb9e4ffd0c76b866c350eb4e3c37e640/numpy-2.1.3-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:17ee83a1f4fef3c94d16dc1802b998668b5419362c8a4f4e8a491de1b41cc3ee", size = 16712217, upload-time = "2024-11-02T17:35:56.703Z" }, - { url = "https://files.pythonhosted.org/packages/7d/84/4de0b87d5a72f45556b2a8ee9fc8801e8518ec867fc68260c1f5dcb3903f/numpy-2.1.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:15cb89f39fa6d0bdfb600ea24b250e5f1a3df23f901f51c8debaa6a5d122b2f0", size = 14399053, upload-time = "2024-11-02T17:36:22.3Z" }, - { url = "https://files.pythonhosted.org/packages/7e/1c/e5fabb9ad849f9d798b44458fd12a318d27592d4bc1448e269dec070ff04/numpy-2.1.3-cp311-cp311-win32.whl", hash = "sha256:d9beb777a78c331580705326d2367488d5bc473b49a9bc3036c154832520aca9", size = 6534741, upload-time = "2024-11-02T17:36:33.552Z" }, - { url = "https://files.pythonhosted.org/packages/1e/48/a9a4b538e28f854bfb62e1dea3c8fea12e90216a276c7777ae5345ff29a7/numpy-2.1.3-cp311-cp311-win_amd64.whl", hash = "sha256:d89dd2b6da69c4fff5e39c28a382199ddedc3a5be5390115608345dec660b9e2", size = 12869487, upload-time = "2024-11-02T17:36:52.909Z" }, - { url = "https://files.pythonhosted.org/packages/8a/f0/385eb9970309643cbca4fc6eebc8bb16e560de129c91258dfaa18498da8b/numpy-2.1.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:f55ba01150f52b1027829b50d70ef1dafd9821ea82905b63936668403c3b471e", size = 20849658, upload-time = "2024-11-02T17:37:23.919Z" }, - { url = "https://files.pythonhosted.org/packages/54/4a/765b4607f0fecbb239638d610d04ec0a0ded9b4951c56dc68cef79026abf/numpy-2.1.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:13138eadd4f4da03074851a698ffa7e405f41a0845a6b1ad135b81596e4e9958", size = 13492258, upload-time = "2024-11-02T17:37:45.252Z" }, - { url = "https://files.pythonhosted.org/packages/bd/a7/2332679479c70b68dccbf4a8eb9c9b5ee383164b161bee9284ac141fbd33/numpy-2.1.3-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:a6b46587b14b888e95e4a24d7b13ae91fa22386c199ee7b418f449032b2fa3b8", size = 5090249, upload-time = "2024-11-02T17:37:54.252Z" }, - { url = "https://files.pythonhosted.org/packages/c1/67/4aa00316b3b981a822c7a239d3a8135be2a6945d1fd11d0efb25d361711a/numpy-2.1.3-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:0fa14563cc46422e99daef53d725d0c326e99e468a9320a240affffe87852564", size = 6621704, upload-time = "2024-11-02T17:38:05.127Z" }, - { url = "https://files.pythonhosted.org/packages/5e/da/1a429ae58b3b6c364eeec93bf044c532f2ff7b48a52e41050896cf15d5b1/numpy-2.1.3-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8637dcd2caa676e475503d1f8fdb327bc495554e10838019651b76d17b98e512", size = 13606089, upload-time = "2024-11-02T17:38:25.997Z" }, - { url = "https://files.pythonhosted.org/packages/9e/3e/3757f304c704f2f0294a6b8340fcf2be244038be07da4cccf390fa678a9f/numpy-2.1.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2312b2aa89e1f43ecea6da6ea9a810d06aae08321609d8dc0d0eda6d946a541b", size = 16043185, upload-time = "2024-11-02T17:38:51.07Z" }, - { url = "https://files.pythonhosted.org/packages/43/97/75329c28fea3113d00c8d2daf9bc5828d58d78ed661d8e05e234f86f0f6d/numpy-2.1.3-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:a38c19106902bb19351b83802531fea19dee18e5b37b36454f27f11ff956f7fc", size = 16410751, upload-time = "2024-11-02T17:39:15.801Z" }, - { url = "https://files.pythonhosted.org/packages/ad/7a/442965e98b34e0ae9da319f075b387bcb9a1e0658276cc63adb8c9686f7b/numpy-2.1.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:02135ade8b8a84011cbb67dc44e07c58f28575cf9ecf8ab304e51c05528c19f0", size = 14082705, upload-time = "2024-11-02T17:39:38.274Z" }, - { url = "https://files.pythonhosted.org/packages/ac/b6/26108cf2cfa5c7e03fb969b595c93131eab4a399762b51ce9ebec2332e80/numpy-2.1.3-cp312-cp312-win32.whl", hash = "sha256:e6988e90fcf617da2b5c78902fe8e668361b43b4fe26dbf2d7b0f8034d4cafb9", size = 6239077, upload-time = "2024-11-02T17:39:49.299Z" }, - { url = "https://files.pythonhosted.org/packages/a6/84/fa11dad3404b7634aaab50733581ce11e5350383311ea7a7010f464c0170/numpy-2.1.3-cp312-cp312-win_amd64.whl", hash = "sha256:0d30c543f02e84e92c4b1f415b7c6b5326cbe45ee7882b6b77db7195fb971e3a", size = 12566858, upload-time = "2024-11-02T17:40:08.851Z" }, + { url = "https://files.pythonhosted.org/packages/fa/0a/11486d02add7b1384dff7374d124b1cfbb0ee864dcc9f6a2c0380638cf84/numpy-2.5.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:489780423903667933b4ed6197b6ec3b75ea5dd17d1d8f0f38d798feb6921561", size = 16789987, upload-time = "2026-06-21T20:56:16.657Z" }, + { url = "https://files.pythonhosted.org/packages/55/b2/285f48640a181947b4587a3766d21ec1eaa7fea833d4b49957e09da467a2/numpy-2.5.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ece55976ced6bca95a03ae2839e2e5ccffe8eb6a3e7022415645eb154a81e4e6", size = 11760322, upload-time = "2026-06-21T20:56:19.813Z" }, + { url = "https://files.pythonhosted.org/packages/dd/67/b032db1eb03ca30d16eda3b0c22aaa615338b9263c2fd559d0f29451aca4/numpy-2.5.0-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:c83b664b0e6eee9594fa920cf0639d8af796606d3fad6cc70180c87e4b97c7be", size = 5319605, upload-time = "2026-06-21T20:56:22.173Z" }, + { url = "https://files.pythonhosted.org/packages/b9/83/03fc7300c7c6b6c84c487b1dc80d322817b95fbd1f4dd57a85e23b7198de/numpy-2.5.0-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:bf80333980bf37f523341ddd72c783f39d6829ec7736b9eb99086388a2d52cc2", size = 6653628, upload-time = "2026-06-21T20:56:23.914Z" }, + { url = "https://files.pythonhosted.org/packages/82/49/2ec21730bc63ccfda829323f7040a8ed4715b3852ce658689cf74ee96a8c/numpy-2.5.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a1a4874217b36d5ac8fc876f52e39df56f8182c88463e9e2dceabf7ca8b7efb8", size = 15153691, upload-time = "2026-06-21T20:56:25.631Z" }, + { url = "https://files.pythonhosted.org/packages/bb/6b/f4a3d0637692c49da8ef99d72d52526f92e0a8d6ac4f0ca9f31441b9d9ea/numpy-2.5.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:aaa760137137e8d3c920d27927748215b56014f92667dc9b6c27dfc61249255a", size = 16660066, upload-time = "2026-06-21T20:56:28.009Z" }, + { url = "https://files.pythonhosted.org/packages/3a/2f/c354ec86d1f3f5c19649463b0d39652e160736e5b0a4cd18dff0576715c4/numpy-2.5.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:7174ce8265fc7f7417d171c9ea8fe905220748893ea67a2a7abe726ec331c4b0", size = 16514638, upload-time = "2026-06-21T20:56:30.26Z" }, + { url = "https://files.pythonhosted.org/packages/06/34/43efdcb319988648580f93c11f1ae82cf7e2faa74925e98e454ae3aa95f8/numpy-2.5.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:b8c3daaf99de52415d20b42f8e8155c78642cb04207d02f9d317a0dcf1b3fb54", size = 18419647, upload-time = "2026-06-21T20:56:32.41Z" }, + { url = "https://files.pythonhosted.org/packages/71/e2/f5d1676b1d7fb682eb5e9a1641e7ebd2414b3216c370661d1029778908b4/numpy-2.5.0-cp312-cp312-win32.whl", hash = "sha256:6206db0af545d73d068add6d992279145f158428d1da6cc49adc4b630c5d6ee5", size = 6056688, upload-time = "2026-06-21T20:56:34.657Z" }, + { url = "https://files.pythonhosted.org/packages/8f/7c/48f115d1c58a34032facebcd51fdf2d02df2c51d4a46a81dd1197bb2ea6b/numpy-2.5.0-cp312-cp312-win_amd64.whl", hash = "sha256:6f2d6873e2940c860a309d21e25b1e69af6aaffdd80aa056b04c16380db1c4f2", size = 12419237, upload-time = "2026-06-21T20:56:36.24Z" }, + { url = "https://files.pythonhosted.org/packages/86/26/2e0882f4044d1b1a1b63e875151fb2393389032022a8b7f5657a7996d3b2/numpy-2.5.0-cp312-cp312-win_arm64.whl", hash = "sha256:a55e1eb2bca2cfd17a16b213c99dfc8502d47b0d494224d2122277d0400935ca", size = 10339912, upload-time = "2026-06-21T20:56:38.733Z" }, ] [[package]] -name = "onnx" -version = "1.18.0" -source = { registry = "https://pypi.org/simple" } +name = "opendbc" +version = "0.3.1" +source = { editable = "opendbc_repo" } dependencies = [ { name = "numpy" }, - { name = "protobuf" }, - { name = "typing-extensions" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/3d/60/e56e8ec44ed34006e6d4a73c92a04d9eea6163cc12440e35045aec069175/onnx-1.18.0.tar.gz", hash = "sha256:3d8dbf9e996629131ba3aa1afd1d8239b660d1f830c6688dd7e03157cccd6b9c", size = 12563009, upload-time = "2025-05-12T22:03:09.626Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/ed/3a/a336dac4db1eddba2bf577191e5b7d3e4c26fcee5ec518a5a5b11d13540d/onnx-1.18.0-cp311-cp311-macosx_12_0_universal2.whl", hash = "sha256:735e06d8d0cf250dc498f54038831401063c655a8d6e5975b2527a4e7d24be3e", size = 18281831, upload-time = "2025-05-12T22:02:06.429Z" }, - { url = "https://files.pythonhosted.org/packages/02/3a/56475a111120d1e5d11939acbcbb17c92198c8e64a205cd68e00bdfd8a1f/onnx-1.18.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:73160799472e1a86083f786fecdf864cf43d55325492a9b5a1cfa64d8a523ecc", size = 17424359, upload-time = "2025-05-12T22:02:09.866Z" }, - { url = "https://files.pythonhosted.org/packages/cf/03/5eb5e9ef446ed9e78c4627faf3c1bc25e0f707116dd00e9811de232a8df5/onnx-1.18.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6acafb3823238bbe8f4340c7ac32fb218689442e074d797bee1c5c9a02fdae75", size = 17586006, upload-time = "2025-05-12T22:02:13.217Z" }, - { url = "https://files.pythonhosted.org/packages/b0/4e/70943125729ce453271a6e46bb847b4a612496f64db6cbc6cb1f49f41ce1/onnx-1.18.0-cp311-cp311-win32.whl", hash = "sha256:4c8c4bbda760c654e65eaffddb1a7de71ec02e60092d33f9000521f897c99be9", size = 15734988, upload-time = "2025-05-12T22:02:16.561Z" }, - { url = "https://files.pythonhosted.org/packages/44/b0/435fd764011911e8f599e3361f0f33425b1004662c1ea33a0ad22e43db2d/onnx-1.18.0-cp311-cp311-win_amd64.whl", hash = "sha256:a5810194f0f6be2e58c8d6dedc6119510df7a14280dd07ed5f0f0a85bd74816a", size = 15849576, upload-time = "2025-05-12T22:02:19.569Z" }, - { url = "https://files.pythonhosted.org/packages/6c/f0/9e31f4b4626d60f1c034f71b411810bc9fafe31f4e7dd3598effd1b50e05/onnx-1.18.0-cp311-cp311-win_arm64.whl", hash = "sha256:aa1b7483fac6cdec26922174fc4433f8f5c2f239b1133c5625063bb3b35957d0", size = 15822961, upload-time = "2025-05-12T22:02:22.735Z" }, - { url = "https://files.pythonhosted.org/packages/a7/fe/16228aca685392a7114625b89aae98b2dc4058a47f0f467a376745efe8d0/onnx-1.18.0-cp312-cp312-macosx_12_0_universal2.whl", hash = "sha256:521bac578448667cbb37c50bf05b53c301243ede8233029555239930996a625b", size = 18285770, upload-time = "2025-05-12T22:02:26.116Z" }, - { url = "https://files.pythonhosted.org/packages/1e/77/ba50a903a9b5e6f9be0fa50f59eb2fca4a26ee653375408fbc72c3acbf9f/onnx-1.18.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e4da451bf1c5ae381f32d430004a89f0405bc57a8471b0bddb6325a5b334aa40", size = 17421291, upload-time = "2025-05-12T22:02:29.645Z" }, - { url = "https://files.pythonhosted.org/packages/11/23/25ec2ba723ac62b99e8fed6d7b59094dadb15e38d4c007331cc9ae3dfa5f/onnx-1.18.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:99afac90b4cdb1471432203c3c1f74e16549c526df27056d39f41a9a47cfb4af", size = 17584084, upload-time = "2025-05-12T22:02:32.789Z" }, - { url = "https://files.pythonhosted.org/packages/6a/4d/2c253a36070fb43f340ff1d2c450df6a9ef50b938adcd105693fee43c4ee/onnx-1.18.0-cp312-cp312-win32.whl", hash = "sha256:ee159b41a3ae58d9c7341cf432fc74b96aaf50bd7bb1160029f657b40dc69715", size = 15734892, upload-time = "2025-05-12T22:02:35.527Z" }, - { url = "https://files.pythonhosted.org/packages/e8/92/048ba8fafe6b2b9a268ec2fb80def7e66c0b32ab2cae74de886981f05a27/onnx-1.18.0-cp312-cp312-win_amd64.whl", hash = "sha256:102c04edc76b16e9dfeda5a64c1fccd7d3d2913b1544750c01d38f1ac3c04e05", size = 15850336, upload-time = "2025-05-12T22:02:38.545Z" }, - { url = "https://files.pythonhosted.org/packages/a1/66/bbc4ffedd44165dcc407a51ea4c592802a5391ce3dc94aa5045350f64635/onnx-1.18.0-cp312-cp312-win_arm64.whl", hash = "sha256:911b37d724a5d97396f3c2ef9ea25361c55cbc9aa18d75b12a52b620b67145af", size = 15823802, upload-time = "2025-05-12T22:02:42.037Z" }, + { name = "pycapnp" }, + { name = "pycryptodome" }, + { name = "tqdm" }, ] -[[package]] -name = "opencv-python-headless" -version = "4.11.0.86" -source = { registry = "https://pypi.org/simple" } -dependencies = [ +[package.metadata] +requires-dist = [ + { name = "cffi", marker = "extra == 'testing'" }, + { name = "codespell", marker = "extra == 'testing'" }, + { name = "cpplint", marker = "extra == 'testing'" }, + { name = "gcovr", marker = "extra == 'testing'" }, + { name = "hypothesis", marker = "extra == 'testing'", specifier = "==6.47.*" }, + { name = "inputs", marker = "extra == 'examples'" }, + { name = "jinja2", marker = "extra == 'docs'" }, + { name = "lefthook", marker = "extra == 'testing'" }, { name = "numpy" }, + { name = "pycapnp" }, + { name = "pycryptodome" }, + { name = "ruff", marker = "extra == 'testing'" }, + { name = "tqdm" }, + { name = "tree-sitter", marker = "extra == 'testing'" }, + { name = "tree-sitter-c", marker = "extra == 'testing'" }, + { name = "ty", marker = "extra == 'testing'" }, + { name = "unittest-parallel", marker = "extra == 'testing'" }, + { name = "zstandard", marker = "extra == 'testing'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/36/2f/5b2b3ba52c864848885ba988f24b7f105052f68da9ab0e693cc7c25b0b30/opencv-python-headless-4.11.0.86.tar.gz", hash = "sha256:996eb282ca4b43ec6a3972414de0e2331f5d9cda2b41091a49739c19fb843798", size = 95177929, upload-time = "2025-01-16T13:53:40.22Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/dc/53/2c50afa0b1e05ecdb4603818e85f7d174e683d874ef63a6abe3ac92220c8/opencv_python_headless-4.11.0.86-cp37-abi3-macosx_13_0_arm64.whl", hash = "sha256:48128188ade4a7e517237c8e1e11a9cdf5c282761473383e77beb875bb1e61ca", size = 37326460, upload-time = "2025-01-16T13:52:57.015Z" }, - { url = "https://files.pythonhosted.org/packages/3b/43/68555327df94bb9b59a1fd645f63fafb0762515344d2046698762fc19d58/opencv_python_headless-4.11.0.86-cp37-abi3-macosx_13_0_x86_64.whl", hash = "sha256:a66c1b286a9de872c343ee7c3553b084244299714ebb50fbdcd76f07ebbe6c81", size = 56723330, upload-time = "2025-01-16T13:55:45.731Z" }, - { url = "https://files.pythonhosted.org/packages/45/be/1438ce43ebe65317344a87e4b150865c5585f4c0db880a34cdae5ac46881/opencv_python_headless-4.11.0.86-cp37-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6efabcaa9df731f29e5ea9051776715b1bdd1845d7c9530065c7951d2a2899eb", size = 29487060, upload-time = "2025-01-16T13:51:59.625Z" }, - { url = "https://files.pythonhosted.org/packages/dd/5c/c139a7876099916879609372bfa513b7f1257f7f1a908b0bdc1c2328241b/opencv_python_headless-4.11.0.86-cp37-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0e0a27c19dd1f40ddff94976cfe43066fbbe9dfbb2ec1907d66c19caef42a57b", size = 49969856, upload-time = "2025-01-16T13:53:29.654Z" }, - { url = "https://files.pythonhosted.org/packages/95/dd/ed1191c9dc91abcc9f752b499b7928aacabf10567bb2c2535944d848af18/opencv_python_headless-4.11.0.86-cp37-abi3-win32.whl", hash = "sha256:f447d8acbb0b6f2808da71fddd29c1cdd448d2bc98f72d9bb78a7a898fc9621b", size = 29324425, upload-time = "2025-01-16T13:52:49.048Z" }, - { url = "https://files.pythonhosted.org/packages/86/8a/69176a64335aed183529207ba8bc3d329c2999d852b4f3818027203f50e6/opencv_python_headless-4.11.0.86-cp37-abi3-win_amd64.whl", hash = "sha256:6c304df9caa7a6a5710b91709dd4786bf20a74d57672b3c31f7033cc638174ca", size = 39402386, upload-time = "2025-01-16T13:52:56.418Z" }, +provides-extras = ["testing", "docs", "examples"] + +[package.metadata.requires-dev] +testing = [ + { name = "comma-car-segments", url = "https://huggingface.co/datasets/commaai/commaCarSegments/resolve/main/dist/comma_car_segments-0.1.0-py3-none-any.whl" }, + { name = "cppcheck", git = "https://github.com/commaai/dependencies.git?subdirectory=cppcheck&rev=release-cppcheck" }, ] [[package]] @@ -1235,286 +699,189 @@ name = "openpilot" version = "0.1.0" source = { editable = "." } dependencies = [ - { name = "aiohttp" }, - { name = "aiortc" }, - { name = "casadi" }, - { name = "cffi" }, - { name = "crcmod" }, + { name = "comma-deps-acados" }, + { name = "comma-deps-capnproto" }, + { name = "comma-deps-catch2" }, + { name = "comma-deps-ffmpeg" }, + { name = "comma-deps-gcc-arm-none-eabi" }, + { name = "comma-deps-git-lfs" }, + { name = "comma-deps-json11" }, + { name = "comma-deps-raylib" }, + { name = "comma-deps-zeromq" }, + { name = "comma-deps-zstd" }, { name = "cython" }, - { name = "future-fstrings" }, { name = "inputs" }, - { name = "json-rpc" }, - { name = "libusb1" }, - { name = "llvmlite" }, + { name = "jeepney" }, { name = "numpy" }, - { name = "onnx" }, - { name = "psutil" }, - { name = "pyaudio" }, + { name = "pillow" }, { name = "pycapnp" }, - { name = "pycryptodome" }, - { name = "pyjwt" }, - { name = "pyopenssl" }, - { name = "pyserial" }, + { name = "pyjwt", extra = ["crypto"] }, { name = "pyzmq" }, { name = "qrcode" }, { name = "requests" }, { name = "scons" }, { name = "sentry-sdk" }, { name = "setproctitle" }, - { name = "setuptools" }, - { name = "smbus2" }, { name = "sounddevice" }, - { name = "spidev", marker = "sys_platform == 'linux'" }, - { name = "sympy" }, { name = "tqdm" }, { name = "websocket-client" }, - { name = "xattr" }, { name = "zstandard" }, ] [package.optional-dependencies] dev = [ - { name = "av" }, - { name = "azure-identity" }, - { name = "azure-storage-blob" }, - { name = "dbus-next" }, - { name = "dictdiffer" }, { name = "matplotlib" }, - { name = "opencv-python-headless" }, - { name = "parameterized" }, - { name = "pyautogui" }, - { name = "pygame" }, - { name = "pyopencl", marker = "platform_machine != 'aarch64'" }, - { name = "pyprof2calltree" }, - { name = "pytools", marker = "platform_machine != 'aarch64'" }, - { name = "pywinctl" }, - { name = "raylib" }, - { name = "tabulate" }, - { name = "types-requests" }, - { name = "types-tabulate" }, ] docs = [ - { name = "jinja2" }, - { name = "mkdocs" }, - { name = "natsort" }, + { name = "zensical" }, +] +submodules = [ + { name = "msgq" }, + { name = "opendbc" }, + { name = "pandacan" }, + { name = "rednose" }, + { name = "teleoprtc" }, + { name = "tinygrad" }, ] testing = [ { name = "codespell" }, { name = "coverage" }, { name = "hypothesis" }, - { name = "mypy" }, - { name = "pre-commit-hooks" }, { name = "pytest" }, - { name = "pytest-asyncio" }, - { name = "pytest-cov" }, { name = "pytest-cpp" }, { name = "pytest-mock" }, - { name = "pytest-randomly" }, - { name = "pytest-repeat" }, { name = "pytest-subtests" }, - { name = "pytest-timeout" }, { name = "pytest-xdist" }, { name = "ruff" }, + { name = "ty" }, ] tools = [ - { name = "metadrive-simulator", marker = "platform_machine != 'aarch64'" }, - { name = "rerun-sdk" }, + { name = "comma-deps-bootstrap-icons" }, + { name = "comma-deps-bzip2" }, + { name = "comma-deps-imgui" }, + { name = "comma-deps-libusb" }, + { name = "comma-deps-ncurses" }, +] + +[package.dev-dependencies] +standalone = [ + { name = "openpilot", extra = ["submodules"] }, ] [package.metadata] requires-dist = [ - { name = "aiohttp" }, - { name = "aiortc" }, - { name = "av", marker = "extra == 'dev'" }, - { name = "azure-identity", marker = "extra == 'dev'" }, - { name = "azure-storage-blob", marker = "extra == 'dev'" }, - { name = "casadi", specifier = ">=3.6.6" }, - { name = "cffi" }, { name = "codespell", marker = "extra == 'testing'" }, + { name = "comma-deps-acados" }, + { name = "comma-deps-bootstrap-icons", marker = "extra == 'tools'" }, + { name = "comma-deps-bzip2", marker = "extra == 'tools'" }, + { name = "comma-deps-capnproto" }, + { name = "comma-deps-catch2" }, + { name = "comma-deps-ffmpeg" }, + { name = "comma-deps-gcc-arm-none-eabi" }, + { name = "comma-deps-git-lfs" }, + { name = "comma-deps-imgui", marker = "extra == 'tools'" }, + { name = "comma-deps-json11" }, + { name = "comma-deps-libusb", marker = "extra == 'tools'" }, + { name = "comma-deps-ncurses", marker = "extra == 'tools'" }, + { name = "comma-deps-raylib" }, + { name = "comma-deps-zeromq" }, + { name = "comma-deps-zstd" }, { name = "coverage", marker = "extra == 'testing'" }, - { name = "crcmod" }, { name = "cython" }, - { name = "dbus-next", marker = "extra == 'dev'" }, - { name = "dictdiffer", marker = "extra == 'dev'" }, - { name = "future-fstrings" }, { name = "hypothesis", marker = "extra == 'testing'", specifier = "==6.47.*" }, { name = "inputs" }, - { name = "jinja2", marker = "extra == 'docs'" }, - { name = "json-rpc" }, - { name = "libusb1" }, - { name = "llvmlite" }, + { name = "jeepney" }, { name = "matplotlib", marker = "extra == 'dev'" }, - { name = "metadrive-simulator", marker = "platform_machine != 'aarch64' and extra == 'tools'", url = "https://github.com/commaai/metadrive/releases/download/MetaDrive-minimal-0.4.2.4/metadrive_simulator-0.4.2.4-py3-none-any.whl" }, - { name = "mkdocs", marker = "extra == 'docs'" }, - { name = "mypy", marker = "extra == 'testing'" }, - { name = "natsort", marker = "extra == 'docs'" }, - { name = "numpy", specifier = ">=2.0,<2.2" }, - { name = "onnx", specifier = ">=1.14.0" }, - { name = "opencv-python-headless", marker = "extra == 'dev'" }, - { name = "parameterized", marker = "extra == 'dev'", specifier = ">=0.8,<0.9" }, - { name = "pre-commit-hooks", marker = "extra == 'testing'" }, - { name = "psutil" }, - { name = "pyaudio" }, - { name = "pyautogui", marker = "extra == 'dev'" }, - { name = "pycapnp" }, - { name = "pycryptodome" }, - { name = "pygame", marker = "extra == 'dev'" }, - { name = "pyjwt" }, - { name = "pyopencl", marker = "platform_machine != 'aarch64' and extra == 'dev'" }, - { name = "pyopenssl", specifier = "<24.3.0" }, - { name = "pyprof2calltree", marker = "extra == 'dev'" }, - { name = "pyserial" }, + { name = "msgq", marker = "extra == 'submodules'", editable = "msgq_repo" }, + { name = "numpy", specifier = ">=2.0" }, + { name = "opendbc", marker = "extra == 'submodules'", editable = "opendbc_repo" }, + { name = "pandacan", marker = "extra == 'submodules'", editable = "panda" }, + { name = "pillow" }, + { name = "pycapnp", specifier = "==2.1.0" }, + { name = "pyjwt", extras = ["crypto"] }, { name = "pytest", marker = "extra == 'testing'" }, - { name = "pytest-asyncio", marker = "extra == 'testing'" }, - { name = "pytest-cov", marker = "extra == 'testing'" }, { name = "pytest-cpp", marker = "extra == 'testing'" }, { name = "pytest-mock", marker = "extra == 'testing'" }, - { name = "pytest-randomly", marker = "extra == 'testing'" }, - { name = "pytest-repeat", marker = "extra == 'testing'" }, { name = "pytest-subtests", marker = "extra == 'testing'" }, - { name = "pytest-timeout", marker = "extra == 'testing'" }, - { name = "pytest-xdist", marker = "extra == 'testing'", git = "https://github.com/sshane/pytest-xdist?rev=909e97b49d12401c10608f9d777bfc9dab8a4413" }, - { name = "pytools", marker = "platform_machine != 'aarch64' and extra == 'dev'", specifier = "<2024.1.11" }, - { name = "pywinctl", marker = "extra == 'dev'" }, + { name = "pytest-xdist", marker = "extra == 'testing'", git = "https://github.com/sshane/pytest-xdist?rev=2b4372bd62699fb412c4fe2f95bf9f01bd2018da" }, { name = "pyzmq" }, { name = "qrcode" }, - { name = "raylib", marker = "extra == 'dev'" }, + { name = "rednose", marker = "extra == 'submodules'", editable = "rednose_repo" }, { name = "requests" }, - { name = "rerun-sdk", marker = "extra == 'tools'", specifier = ">=0.18" }, { name = "ruff", marker = "extra == 'testing'" }, { name = "scons" }, { name = "sentry-sdk" }, { name = "setproctitle" }, - { name = "setuptools" }, - { name = "smbus2" }, { name = "sounddevice" }, - { name = "spidev", marker = "sys_platform == 'linux'" }, - { name = "sympy" }, - { name = "tabulate", marker = "extra == 'dev'" }, + { name = "teleoprtc", marker = "extra == 'submodules'", editable = "teleoprtc_repo" }, + { name = "tinygrad", marker = "extra == 'submodules'", editable = "tinygrad_repo" }, { name = "tqdm" }, - { name = "types-requests", marker = "extra == 'dev'" }, - { name = "types-tabulate", marker = "extra == 'dev'" }, + { name = "ty", marker = "extra == 'testing'" }, { name = "websocket-client" }, - { name = "xattr" }, + { name = "zensical", marker = "extra == 'docs'" }, { name = "zstandard" }, ] -provides-extras = ["docs", "testing", "dev", "tools"] +provides-extras = ["docs", "testing", "dev", "tools", "submodules"] + +[package.metadata.requires-dev] +standalone = [{ name = "openpilot", extras = ["submodules"] }] [[package]] name = "packaging" -version = "25.0" +version = "26.2" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a1/d4/1fc4078c65507b51b96ca8f8c3ba19e6a61c8253c72794544580a7b6c24d/packaging-25.0.tar.gz", hash = "sha256:d443872c98d677bf60f6a1f2f8c1cb748e8fe762d2bf9d3148b5599295b0fc4f", size = 165727, upload-time = "2025-04-19T11:48:59.673Z" } +sdist = { url = "https://files.pythonhosted.org/packages/d7/f1/e7a6dd94a8d4a5626c03e4e99c87f241ba9e350cd9e6d75123f992427270/packaging-26.2.tar.gz", hash = "sha256:ff452ff5a3e828ce110190feff1178bb1f2ea2281fa2075aadb987c2fb221661", size = 228134, upload-time = "2026-04-24T20:15:23.917Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/20/12/38679034af332785aac8774540895e234f4d07f7545804097de4b666afd8/packaging-25.0-py3-none-any.whl", hash = "sha256:29572ef2b1f17581046b3a2227d5c611fb25ec70ca1ba8554b24b0e69331a484", size = 66469, upload-time = "2025-04-19T11:48:57.875Z" }, + { url = "https://files.pythonhosted.org/packages/df/b2/87e62e8c3e2f4b32e5fe99e0b86d576da1312593b39f47d8ceef365e95ed/packaging-26.2-py3-none-any.whl", hash = "sha256:5fc45236b9446107ff2415ce77c807cee2862cb6fac22b8a73826d0693b0980e", size = 100195, upload-time = "2026-04-24T20:15:22.081Z" }, ] [[package]] -name = "panda3d" -version = "1.10.14" -source = { registry = "https://pypi.org/simple" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/f5/9a/31d07e3d7c1b40335e8418c540d63f4d33c571648ed8d69896ab778e65c3/panda3d-1.10.14-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:54b8ef9fe3684960a2c7d47b0d63c0354c17bc516795e59db6c1e5bda8c16c1c", size = 67700752, upload-time = "2024-01-08T19:05:55.559Z" }, - { url = "https://files.pythonhosted.org/packages/61/05/fce327535d8907ac01f43813c980f30ea86d37db62c340847519ea2ab222/panda3d-1.10.14-cp311-cp311-macosx_11_0_universal2.whl", hash = "sha256:93414675894b18eea8d27edc1bbd1dc719eae207d45ec263d47195504bc4705f", size = 118966179, upload-time = "2024-01-08T19:06:03.165Z" }, - { url = "https://files.pythonhosted.org/packages/8a/54/24e205231e7b1bced58ba9620fbec7114673d821fc7ad9ed1804cab556b4/panda3d-1.10.14-cp311-cp311-manylinux2014_x86_64.whl", hash = "sha256:d1bc0d926f90c8fa14a1587fa9dbe5f89a4eda8c9684fa183a8eaa35fc8e891a", size = 55145295, upload-time = "2024-01-08T19:06:10.319Z" }, - { url = "https://files.pythonhosted.org/packages/06/d3/38e989822292935d7473d35117099f71481cc6b104cb2dd048cb8058a5a8/panda3d-1.10.14-cp311-cp311-win32.whl", hash = "sha256:1039340a4a7965fe4c3e904edb4fff691584df435a154fecccf534587cd07a34", size = 53137177, upload-time = "2024-01-08T19:06:15.901Z" }, - { url = "https://files.pythonhosted.org/packages/5c/32/b16c81661ed0d8ad62976004d81845baa321e53314e253ef0841155be770/panda3d-1.10.14-cp311-cp311-win_amd64.whl", hash = "sha256:1ddf01040b9c5497fb8659e3c5ef793a26c869cfdfb1b75e6d04d6fba0c03b73", size = 64447666, upload-time = "2024-01-08T19:06:22.105Z" }, - { url = "https://files.pythonhosted.org/packages/5a/d4/90e98993b1a3f3c9fae83267f8c51186e676a8c1365c4180dfc65cd7ba62/panda3d-1.10.14-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:1bfbcee77779f12ecce6a3d5a856e573b25d6343f8c4b107e814d9702e70a65d", size = 67839196, upload-time = "2024-01-08T19:01:00.417Z" }, - { url = "https://files.pythonhosted.org/packages/dc/e5/862821575073863ce49cc57b8349b47cb25ce11feae0e419b3d023ac1a69/panda3d-1.10.14-cp312-cp312-macosx_11_0_universal2.whl", hash = "sha256:bc6540c5559d7e14a8992eff7de0157b7c42406b7ba221941ed224289496841c", size = 119271341, upload-time = "2024-01-08T19:01:09.455Z" }, - { url = "https://files.pythonhosted.org/packages/f4/20/f16d91805777825e530037177d9075c83da7384f12b778b133e3164a31f3/panda3d-1.10.14-cp312-cp312-manylinux2014_aarch64.whl", hash = "sha256:143daab1ce6bedcba711ea3f6cab0ebe5082f22c5f43e7178fadd2dd01209da7", size = 47604077, upload-time = "2024-05-28T20:25:37.118Z" }, - { url = "https://files.pythonhosted.org/packages/11/69/806dcdbaee3e8deee1956abeea0d3d3e504315d2e9814de82a44809a8617/panda3d-1.10.14-cp312-cp312-manylinux2014_x86_64.whl", hash = "sha256:3c4399a286a142de7ff86f9356d7e526bbbd38892d7f7d39fecb5c33064972bc", size = 55539594, upload-time = "2024-01-08T19:01:15.979Z" }, - { url = "https://files.pythonhosted.org/packages/ad/25/005de5e2b6d0acd546f8b3f2b547cd29e308cdd04a397f0ea68046e26571/panda3d-1.10.14-cp312-cp312-win32.whl", hash = "sha256:e92e0dd907e2af33085a2c31ca2263dc8023b1b7bc70ce1b9fbc84631e130e51", size = 53479813, upload-time = "2024-01-08T19:01:20.923Z" }, - { url = "https://files.pythonhosted.org/packages/74/bb/cb57563855da994614a33f57bd5691fbcd69f12e5ccddd30d387d0be287f/panda3d-1.10.14-cp312-cp312-win_amd64.whl", hash = "sha256:a5f2defd822d38848f8ae1956115adcb6cc7f464f03a67e73681cc72df125ef4", size = 64893222, upload-time = "2024-01-08T19:01:26.347Z" }, -] - -[[package]] -name = "panda3d-gltf" -version = "0.13" -source = { registry = "https://pypi.org/simple" } +name = "pandacan" +version = "0.0.10" +source = { editable = "panda" } dependencies = [ - { name = "panda3d" }, - { name = "panda3d-simplepbr" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/07/7f/9f18fc3fa843a080acb891af6bcc12262e7bdf1d194a530f7042bebfc81f/panda3d-gltf-0.13.tar.gz", hash = "sha256:d06d373bdd91cf530909b669f43080e599463bbf6d3ef00c3558bad6c6b19675", size = 25573, upload-time = "2021-05-21T05:46:32.738Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/70/94/98ed1f81ca0f5daf6de80533805cc1e98ac162abe4e3e1d382caa7ba5c3c/panda3d_gltf-0.13-py3-none-any.whl", hash = "sha256:02d1a980f447bb1895ff4b48c667f289ba78f07a28ef308d8839b665a621efe2", size = 25568, upload-time = "2021-05-21T05:46:31.28Z" }, + { name = "libusb-package" }, + { name = "libusb1" }, + { name = "opendbc" }, + { name = "spidev", marker = "sys_platform == 'linux'" }, ] -[[package]] -name = "panda3d-simplepbr" -version = "0.13.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "panda3d" }, - { name = "typing-extensions" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/0d/be/c4d1ded04c22b357277cf6e6a44c1ab4abb285a700bd1991460460e05b99/panda3d_simplepbr-0.13.1.tar.gz", hash = "sha256:c83766d7c8f47499f365a07fe1dff078fc8b3054c2689bdc8dceabddfe7f1a35", size = 6216055, upload-time = "2025-03-30T16:57:41.087Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/11/5d/3744c6550dddf933785a37cdd4a9921fe13284e6d115b5a2637fe390f158/panda3d_simplepbr-0.13.1-py3-none-any.whl", hash = "sha256:cda41cb57cff035b851646956cfbdcc408bee42511dabd4f2d7bd4fbf48c57a9", size = 2457097, upload-time = "2025-03-30T16:57:39.729Z" }, -] - -[[package]] -name = "parameterized" -version = "0.8.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/c6/23/2288f308d238b4f261c039cafcd650435d624de97c6ffc903f06ea8af50f/parameterized-0.8.1.tar.gz", hash = "sha256:41bbff37d6186430f77f900d777e5bb6a24928a1c46fb1de692f8b52b8833b5c", size = 23936, upload-time = "2021-01-09T20:35:18.235Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/31/13/fe468c8c7400a8eca204e6e160a29bf7dcd45a76e20f1c030f3eaa690d93/parameterized-0.8.1-py2.py3-none-any.whl", hash = "sha256:9cbb0b69a03e8695d68b3399a8a5825200976536fe1cb79db60ed6a4c8c9efe9", size = 26354, upload-time = "2021-01-09T20:35:16.307Z" }, -] - -[[package]] -name = "pathspec" -version = "0.12.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/ca/bc/f35b8446f4531a7cb215605d100cd88b7ac6f44ab3fc94870c120ab3adbf/pathspec-0.12.1.tar.gz", hash = "sha256:a482d51503a1ab33b1c67a6c3813a26953dbdc71c31dacaef9a838c4e29f5712", size = 51043, upload-time = "2023-12-10T22:30:45Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/cc/20/ff623b09d963f88bfde16306a54e12ee5ea43e9b597108672ff3a408aad6/pathspec-0.12.1-py3-none-any.whl", hash = "sha256:a0d503e138a4c123b27490a4f7beda6a01c6f288df0e4a8b79c7eb0dc7b4cc08", size = 31191, upload-time = "2023-12-10T22:30:43.14Z" }, +[package.metadata] +requires-dist = [ + { name = "cffi", marker = "extra == 'dev'" }, + { name = "cppcheck", marker = "extra == 'dev'", git = "https://github.com/commaai/dependencies.git?subdirectory=cppcheck&rev=release-cppcheck" }, + { name = "flaky", marker = "extra == 'dev'" }, + { name = "gcc-arm-none-eabi", marker = "extra == 'dev'", git = "https://github.com/commaai/dependencies.git?subdirectory=gcc-arm-none-eabi&rev=release-gcc-arm-none-eabi" }, + { name = "libusb-package" }, + { name = "libusb1" }, + { name = "opendbc", git = "https://github.com/sunnypilot/opendbc.git?rev=master" }, + { name = "pycryptodome", marker = "extra == 'dev'", specifier = ">=3.9.8" }, + { name = "pytest", marker = "extra == 'dev'" }, + { name = "pytest-mock", marker = "extra == 'dev'" }, + { name = "pytest-timeout", marker = "extra == 'dev'" }, + { name = "pytest-xdist", marker = "extra == 'dev'" }, + { name = "ruff", marker = "extra == 'dev'" }, + { name = "scons", marker = "extra == 'dev'" }, + { name = "setuptools", marker = "extra == 'dev'" }, + { name = "spidev", marker = "sys_platform == 'linux'" }, ] +provides-extras = ["dev"] [[package]] name = "pillow" -version = "11.2.1" +version = "12.3.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/af/cb/bb5c01fcd2a69335b86c22142b2bccfc3464087efb7fd382eee5ffc7fdf7/pillow-11.2.1.tar.gz", hash = "sha256:a64dd61998416367b7ef979b73d3a85853ba9bec4c2925f74e588879a58716b6", size = 47026707, upload-time = "2025-04-12T17:50:03.289Z" } +sdist = { url = "https://files.pythonhosted.org/packages/1c/3d/bb7fca845737cf9d7dbde16ed1843984665ff2e0a518f5db43e77ec540b9/pillow-12.3.0.tar.gz", hash = "sha256:3b8182a766685eaa002637e28b4ec8d6b18819a0c71f579bf0dbaa5830297cce", size = 47025035, upload-time = "2026-07-01T11:56:38.965Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/68/08/3fbf4b98924c73037a8e8b4c2c774784805e0fb4ebca6c5bb60795c40125/pillow-11.2.1-cp311-cp311-macosx_10_10_x86_64.whl", hash = "sha256:35ca289f712ccfc699508c4658a1d14652e8033e9b69839edf83cbdd0ba39e70", size = 3198450, upload-time = "2025-04-12T17:47:37.135Z" }, - { url = "https://files.pythonhosted.org/packages/84/92/6505b1af3d2849d5e714fc75ba9e69b7255c05ee42383a35a4d58f576b16/pillow-11.2.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:e0409af9f829f87a2dfb7e259f78f317a5351f2045158be321fd135973fff7bf", size = 3030550, upload-time = "2025-04-12T17:47:39.345Z" }, - { url = "https://files.pythonhosted.org/packages/3c/8c/ac2f99d2a70ff966bc7eb13dacacfaab57c0549b2ffb351b6537c7840b12/pillow-11.2.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d4e5c5edee874dce4f653dbe59db7c73a600119fbea8d31f53423586ee2aafd7", size = 4415018, upload-time = "2025-04-12T17:47:41.128Z" }, - { url = "https://files.pythonhosted.org/packages/1f/e3/0a58b5d838687f40891fff9cbaf8669f90c96b64dc8f91f87894413856c6/pillow-11.2.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b93a07e76d13bff9444f1a029e0af2964e654bfc2e2c2d46bfd080df5ad5f3d8", size = 4498006, upload-time = "2025-04-12T17:47:42.912Z" }, - { url = "https://files.pythonhosted.org/packages/21/f5/6ba14718135f08fbfa33308efe027dd02b781d3f1d5c471444a395933aac/pillow-11.2.1-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:e6def7eed9e7fa90fde255afaf08060dc4b343bbe524a8f69bdd2a2f0018f600", size = 4517773, upload-time = "2025-04-12T17:47:44.611Z" }, - { url = "https://files.pythonhosted.org/packages/20/f2/805ad600fc59ebe4f1ba6129cd3a75fb0da126975c8579b8f57abeb61e80/pillow-11.2.1-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:8f4f3724c068be008c08257207210c138d5f3731af6c155a81c2b09a9eb3a788", size = 4607069, upload-time = "2025-04-12T17:47:46.46Z" }, - { url = "https://files.pythonhosted.org/packages/71/6b/4ef8a288b4bb2e0180cba13ca0a519fa27aa982875882392b65131401099/pillow-11.2.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:a0a6709b47019dff32e678bc12c63008311b82b9327613f534e496dacaefb71e", size = 4583460, upload-time = "2025-04-12T17:47:49.255Z" }, - { url = "https://files.pythonhosted.org/packages/62/ae/f29c705a09cbc9e2a456590816e5c234382ae5d32584f451c3eb41a62062/pillow-11.2.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:f6b0c664ccb879109ee3ca702a9272d877f4fcd21e5eb63c26422fd6e415365e", size = 4661304, upload-time = "2025-04-12T17:47:51.067Z" }, - { url = "https://files.pythonhosted.org/packages/6e/1a/c8217b6f2f73794a5e219fbad087701f412337ae6dbb956db37d69a9bc43/pillow-11.2.1-cp311-cp311-win32.whl", hash = "sha256:cc5d875d56e49f112b6def6813c4e3d3036d269c008bf8aef72cd08d20ca6df6", size = 2331809, upload-time = "2025-04-12T17:47:54.425Z" }, - { url = "https://files.pythonhosted.org/packages/e2/72/25a8f40170dc262e86e90f37cb72cb3de5e307f75bf4b02535a61afcd519/pillow-11.2.1-cp311-cp311-win_amd64.whl", hash = "sha256:0f5c7eda47bf8e3c8a283762cab94e496ba977a420868cb819159980b6709193", size = 2676338, upload-time = "2025-04-12T17:47:56.535Z" }, - { url = "https://files.pythonhosted.org/packages/06/9e/76825e39efee61efea258b479391ca77d64dbd9e5804e4ad0fa453b4ba55/pillow-11.2.1-cp311-cp311-win_arm64.whl", hash = "sha256:4d375eb838755f2528ac8cbc926c3e31cc49ca4ad0cf79cff48b20e30634a4a7", size = 2414918, upload-time = "2025-04-12T17:47:58.217Z" }, - { url = "https://files.pythonhosted.org/packages/c7/40/052610b15a1b8961f52537cc8326ca6a881408bc2bdad0d852edeb6ed33b/pillow-11.2.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:78afba22027b4accef10dbd5eed84425930ba41b3ea0a86fa8d20baaf19d807f", size = 3190185, upload-time = "2025-04-12T17:48:00.417Z" }, - { url = "https://files.pythonhosted.org/packages/e5/7e/b86dbd35a5f938632093dc40d1682874c33dcfe832558fc80ca56bfcb774/pillow-11.2.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:78092232a4ab376a35d68c4e6d5e00dfd73454bd12b230420025fbe178ee3b0b", size = 3030306, upload-time = "2025-04-12T17:48:02.391Z" }, - { url = "https://files.pythonhosted.org/packages/a4/5c/467a161f9ed53e5eab51a42923c33051bf8d1a2af4626ac04f5166e58e0c/pillow-11.2.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:25a5f306095c6780c52e6bbb6109624b95c5b18e40aab1c3041da3e9e0cd3e2d", size = 4416121, upload-time = "2025-04-12T17:48:04.554Z" }, - { url = "https://files.pythonhosted.org/packages/62/73/972b7742e38ae0e2ac76ab137ca6005dcf877480da0d9d61d93b613065b4/pillow-11.2.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0c7b29dbd4281923a2bfe562acb734cee96bbb129e96e6972d315ed9f232bef4", size = 4501707, upload-time = "2025-04-12T17:48:06.831Z" }, - { url = "https://files.pythonhosted.org/packages/e4/3a/427e4cb0b9e177efbc1a84798ed20498c4f233abde003c06d2650a6d60cb/pillow-11.2.1-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:3e645b020f3209a0181a418bffe7b4a93171eef6c4ef6cc20980b30bebf17b7d", size = 4522921, upload-time = "2025-04-12T17:48:09.229Z" }, - { url = "https://files.pythonhosted.org/packages/fe/7c/d8b1330458e4d2f3f45d9508796d7caf0c0d3764c00c823d10f6f1a3b76d/pillow-11.2.1-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:b2dbea1012ccb784a65349f57bbc93730b96e85b42e9bf7b01ef40443db720b4", size = 4612523, upload-time = "2025-04-12T17:48:11.631Z" }, - { url = "https://files.pythonhosted.org/packages/b3/2f/65738384e0b1acf451de5a573d8153fe84103772d139e1e0bdf1596be2ea/pillow-11.2.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:da3104c57bbd72948d75f6a9389e6727d2ab6333c3617f0a89d72d4940aa0443", size = 4587836, upload-time = "2025-04-12T17:48:13.592Z" }, - { url = "https://files.pythonhosted.org/packages/6a/c5/e795c9f2ddf3debb2dedd0df889f2fe4b053308bb59a3cc02a0cd144d641/pillow-11.2.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:598174aef4589af795f66f9caab87ba4ff860ce08cd5bb447c6fc553ffee603c", size = 4669390, upload-time = "2025-04-12T17:48:15.938Z" }, - { url = "https://files.pythonhosted.org/packages/96/ae/ca0099a3995976a9fce2f423166f7bff9b12244afdc7520f6ed38911539a/pillow-11.2.1-cp312-cp312-win32.whl", hash = "sha256:1d535df14716e7f8776b9e7fee118576d65572b4aad3ed639be9e4fa88a1cad3", size = 2332309, upload-time = "2025-04-12T17:48:17.885Z" }, - { url = "https://files.pythonhosted.org/packages/7c/18/24bff2ad716257fc03da964c5e8f05d9790a779a8895d6566e493ccf0189/pillow-11.2.1-cp312-cp312-win_amd64.whl", hash = "sha256:14e33b28bf17c7a38eede290f77db7c664e4eb01f7869e37fa98a5aa95978941", size = 2676768, upload-time = "2025-04-12T17:48:19.655Z" }, - { url = "https://files.pythonhosted.org/packages/da/bb/e8d656c9543276517ee40184aaa39dcb41e683bca121022f9323ae11b39d/pillow-11.2.1-cp312-cp312-win_arm64.whl", hash = "sha256:21e1470ac9e5739ff880c211fc3af01e3ae505859392bf65458c224d0bf283eb", size = 2415087, upload-time = "2025-04-12T17:48:21.991Z" }, - { url = "https://files.pythonhosted.org/packages/a4/ad/2613c04633c7257d9481ab21d6b5364b59fc5d75faafd7cb8693523945a3/pillow-11.2.1-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:80f1df8dbe9572b4b7abdfa17eb5d78dd620b1d55d9e25f834efdbee872d3aed", size = 3181734, upload-time = "2025-04-12T17:49:46.789Z" }, - { url = "https://files.pythonhosted.org/packages/a4/fd/dcdda4471ed667de57bb5405bb42d751e6cfdd4011a12c248b455c778e03/pillow-11.2.1-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:ea926cfbc3957090becbcbbb65ad177161a2ff2ad578b5a6ec9bb1e1cd78753c", size = 2999841, upload-time = "2025-04-12T17:49:48.812Z" }, - { url = "https://files.pythonhosted.org/packages/ac/89/8a2536e95e77432833f0db6fd72a8d310c8e4272a04461fb833eb021bf94/pillow-11.2.1-pp311-pypy311_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:738db0e0941ca0376804d4de6a782c005245264edaa253ffce24e5a15cbdc7bd", size = 3437470, upload-time = "2025-04-12T17:49:50.831Z" }, - { url = "https://files.pythonhosted.org/packages/9d/8f/abd47b73c60712f88e9eda32baced7bfc3e9bd6a7619bb64b93acff28c3e/pillow-11.2.1-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9db98ab6565c69082ec9b0d4e40dd9f6181dab0dd236d26f7a50b8b9bfbd5076", size = 3460013, upload-time = "2025-04-12T17:49:53.278Z" }, - { url = "https://files.pythonhosted.org/packages/f6/20/5c0a0aa83b213b7a07ec01e71a3d6ea2cf4ad1d2c686cc0168173b6089e7/pillow-11.2.1-pp311-pypy311_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:036e53f4170e270ddb8797d4c590e6dd14d28e15c7da375c18978045f7e6c37b", size = 3527165, upload-time = "2025-04-12T17:49:55.164Z" }, - { url = "https://files.pythonhosted.org/packages/58/0e/2abab98a72202d91146abc839e10c14f7cf36166f12838ea0c4db3ca6ecb/pillow-11.2.1-pp311-pypy311_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:14f73f7c291279bd65fda51ee87affd7c1e097709f7fdd0188957a16c264601f", size = 3571586, upload-time = "2025-04-12T17:49:57.171Z" }, - { url = "https://files.pythonhosted.org/packages/21/2c/5e05f58658cf49b6667762cca03d6e7d85cededde2caf2ab37b81f80e574/pillow-11.2.1-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:208653868d5c9ecc2b327f9b9ef34e0e42a4cdd172c2988fd81d62d2bc9bc044", size = 2674751, upload-time = "2025-04-12T17:49:59.628Z" }, -] - -[[package]] -name = "platformdirs" -version = "4.3.8" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/fe/8b/3c73abc9c759ecd3f1f7ceff6685840859e8070c4d947c93fae71f6a0bf2/platformdirs-4.3.8.tar.gz", hash = "sha256:3d512d96e16bcb959a814c9f348431070822a6496326a4be0911c40b5a74c2bc", size = 21362, upload-time = "2025-05-07T22:47:42.121Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/fe/39/979e8e21520d4e47a0bbe349e2713c0aac6f3d853d0e5b34d76206c439aa/platformdirs-4.3.8-py3-none-any.whl", hash = "sha256:ff7059bb7eb1179e2685604f4aaf157cfd9535242bd23742eadc3c13542139b4", size = 18567, upload-time = "2025-05-07T22:47:40.376Z" }, + { url = "https://files.pythonhosted.org/packages/37/bf/fb3ebff8ddcb76aac5a01389251bbbb9519922a9b520d8247c1ca864a25d/pillow-12.3.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:ba09209fbe443b4acccebe845d8a138b89a8f4fbaeedd44953490b5315d5e965", size = 5345969, upload-time = "2026-07-01T11:54:06.397Z" }, + { url = "https://files.pythonhosted.org/packages/d8/66/9a386a92561f402389a4fc70c18838bf6d35eb5eb5c6850b4b2dc64f5048/pillow-12.3.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ffd0c5368496f41b0944be820fcb7a838aa6e623d250b01acf2643939c3f99d7", size = 4780323, upload-time = "2026-07-01T11:54:09.351Z" }, + { url = "https://files.pythonhosted.org/packages/25/27/ac8f99618ffd3dde21db0f4d4b1d2ab00c0880595bfd17df103f7f39fd0c/pillow-12.3.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d9c7f76c0673154f044e9d78c8655fb4213f6ca31a836df48b40fe5d187717b9", size = 6266838, upload-time = "2026-07-01T11:54:11.71Z" }, + { url = "https://files.pythonhosted.org/packages/84/21/a35af28dcc61f37ed850a2d64c65c701321dfbf25085e469d5559360cbbf/pillow-12.3.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:78cb2c6865a35ab8ff8b75fd122f6033b92a62c82801110e48ddd6c936a45d91", size = 6940830, upload-time = "2026-07-01T11:54:13.732Z" }, + { url = "https://files.pythonhosted.org/packages/eb/51/8b08617af3ad95e33ce6d7dd2c99ed6c8298f7fb131636303956be022e25/pillow-12.3.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:e491916b378fba47242221bb9ead245211b70d504f495d105d17b14a24b4907c", size = 6344383, upload-time = "2026-07-01T11:54:15.756Z" }, + { url = "https://files.pythonhosted.org/packages/1d/72/cf78ac9780bb93c28328f408973845a309d4d145041665f734572ced1b52/pillow-12.3.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:0dd2064cbc55aaec028ef5fbb60fa47bb6c3e7918e07ff17935284b227a9d2df", size = 7052934, upload-time = "2026-07-01T11:54:17.721Z" }, + { url = "https://files.pythonhosted.org/packages/20/20/25e0f4dc178a6bc0696793720055519a0de89e7661dae886992decbd2f81/pillow-12.3.0-cp312-cp312-win32.whl", hash = "sha256:dbce0b29841537a2fa4a214c2bbf14de3587c9680caa9b4e217568472490b28f", size = 6472684, upload-time = "2026-07-01T11:54:19.839Z" }, + { url = "https://files.pythonhosted.org/packages/45/89/da2f7971a317f83d807fdd4065c0af40208e59e692cc43d315a71a0e96d1/pillow-12.3.0-cp312-cp312-win_amd64.whl", hash = "sha256:a2b55dd6b2a4c4b7d87ffa56bdb33fdc5fdb9a462173861a7bc097f17d91cb09", size = 7227137, upload-time = "2026-07-01T11:54:22.025Z" }, + { url = "https://files.pythonhosted.org/packages/de/47/4845a0a6c0dbf1db8456bd9fc791f13c5ced7ced20606d08a0aacfd25b49/pillow-12.3.0-cp312-cp312-win_arm64.whl", hash = "sha256:331b624368d4f1d069149002f25f44bc61c8919ce8ddb3c45bdad8f6e2d89510", size = 2568267, upload-time = "2026-07-01T11:54:24.051Z" }, ] [[package]] @@ -1526,191 +893,33 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" }, ] -[[package]] -name = "pre-commit-hooks" -version = "5.0.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "ruamel-yaml" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/ac/7d/3299241a753c738d114600c360d754550b28c285281dc6a5132c4ccfae65/pre_commit_hooks-5.0.0.tar.gz", hash = "sha256:10626959a9eaf602fbfc22bc61b6e75801436f82326bfcee82bb1f2fc4bc646e", size = 29747, upload-time = "2024-10-05T18:43:11.225Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/1e/29/db1d855a661c02dbde5cab3057969133fcc62e7a0c6393e48fe9d0e81679/pre_commit_hooks-5.0.0-py2.py3-none-any.whl", hash = "sha256:8d71cfb582c5c314a5498d94e0104b6567a8b93fb35903ea845c491f4e290a7a", size = 41245, upload-time = "2024-10-05T18:43:09.901Z" }, -] - -[[package]] -name = "progressbar" -version = "2.5" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a3/a6/b8e451f6cff1c99b4747a2f7235aa904d2d49e8e1464e0b798272aa84358/progressbar-2.5.tar.gz", hash = "sha256:5d81cb529da2e223b53962afd6c8ca0f05c6670e40309a7219eacc36af9b6c63", size = 10046, upload-time = "2018-06-29T02:32:00.222Z" } - -[[package]] -name = "propcache" -version = "0.3.2" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a6/16/43264e4a779dd8588c21a70f0709665ee8f611211bdd2c87d952cfa7c776/propcache-0.3.2.tar.gz", hash = "sha256:20d7d62e4e7ef05f221e0db2856b979540686342e7dd9973b815599c7057e168", size = 44139, upload-time = "2025-06-09T22:56:06.081Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/80/8d/e8b436717ab9c2cfc23b116d2c297305aa4cd8339172a456d61ebf5669b8/propcache-0.3.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:0b8d2f607bd8f80ddc04088bc2a037fdd17884a6fcadc47a96e334d72f3717be", size = 74207, upload-time = "2025-06-09T22:54:05.399Z" }, - { url = "https://files.pythonhosted.org/packages/d6/29/1e34000e9766d112171764b9fa3226fa0153ab565d0c242c70e9945318a7/propcache-0.3.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:06766d8f34733416e2e34f46fea488ad5d60726bb9481d3cddf89a6fa2d9603f", size = 43648, upload-time = "2025-06-09T22:54:08.023Z" }, - { url = "https://files.pythonhosted.org/packages/46/92/1ad5af0df781e76988897da39b5f086c2bf0f028b7f9bd1f409bb05b6874/propcache-0.3.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:a2dc1f4a1df4fecf4e6f68013575ff4af84ef6f478fe5344317a65d38a8e6dc9", size = 43496, upload-time = "2025-06-09T22:54:09.228Z" }, - { url = "https://files.pythonhosted.org/packages/b3/ce/e96392460f9fb68461fabab3e095cb00c8ddf901205be4eae5ce246e5b7e/propcache-0.3.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:be29c4f4810c5789cf10ddf6af80b041c724e629fa51e308a7a0fb19ed1ef7bf", size = 217288, upload-time = "2025-06-09T22:54:10.466Z" }, - { url = "https://files.pythonhosted.org/packages/c5/2a/866726ea345299f7ceefc861a5e782b045545ae6940851930a6adaf1fca6/propcache-0.3.2-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:59d61f6970ecbd8ff2e9360304d5c8876a6abd4530cb752c06586849ac8a9dc9", size = 227456, upload-time = "2025-06-09T22:54:11.828Z" }, - { url = "https://files.pythonhosted.org/packages/de/03/07d992ccb6d930398689187e1b3c718339a1c06b8b145a8d9650e4726166/propcache-0.3.2-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:62180e0b8dbb6b004baec00a7983e4cc52f5ada9cd11f48c3528d8cfa7b96a66", size = 225429, upload-time = "2025-06-09T22:54:13.823Z" }, - { url = "https://files.pythonhosted.org/packages/5d/e6/116ba39448753b1330f48ab8ba927dcd6cf0baea8a0ccbc512dfb49ba670/propcache-0.3.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c144ca294a204c470f18cf4c9d78887810d04a3e2fbb30eea903575a779159df", size = 213472, upload-time = "2025-06-09T22:54:15.232Z" }, - { url = "https://files.pythonhosted.org/packages/a6/85/f01f5d97e54e428885a5497ccf7f54404cbb4f906688a1690cd51bf597dc/propcache-0.3.2-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c5c2a784234c28854878d68978265617aa6dc0780e53d44b4d67f3651a17a9a2", size = 204480, upload-time = "2025-06-09T22:54:17.104Z" }, - { url = "https://files.pythonhosted.org/packages/e3/79/7bf5ab9033b8b8194cc3f7cf1aaa0e9c3256320726f64a3e1f113a812dce/propcache-0.3.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:5745bc7acdafa978ca1642891b82c19238eadc78ba2aaa293c6863b304e552d7", size = 214530, upload-time = "2025-06-09T22:54:18.512Z" }, - { url = "https://files.pythonhosted.org/packages/31/0b/bd3e0c00509b609317df4a18e6b05a450ef2d9a963e1d8bc9c9415d86f30/propcache-0.3.2-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:c0075bf773d66fa8c9d41f66cc132ecc75e5bb9dd7cce3cfd14adc5ca184cb95", size = 205230, upload-time = "2025-06-09T22:54:19.947Z" }, - { url = "https://files.pythonhosted.org/packages/7a/23/fae0ff9b54b0de4e819bbe559508da132d5683c32d84d0dc2ccce3563ed4/propcache-0.3.2-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:5f57aa0847730daceff0497f417c9de353c575d8da3579162cc74ac294c5369e", size = 206754, upload-time = "2025-06-09T22:54:21.716Z" }, - { url = "https://files.pythonhosted.org/packages/b7/7f/ad6a3c22630aaa5f618b4dc3c3598974a72abb4c18e45a50b3cdd091eb2f/propcache-0.3.2-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:eef914c014bf72d18efb55619447e0aecd5fb7c2e3fa7441e2e5d6099bddff7e", size = 218430, upload-time = "2025-06-09T22:54:23.17Z" }, - { url = "https://files.pythonhosted.org/packages/5b/2c/ba4f1c0e8a4b4c75910742f0d333759d441f65a1c7f34683b4a74c0ee015/propcache-0.3.2-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:2a4092e8549031e82facf3decdbc0883755d5bbcc62d3aea9d9e185549936dcf", size = 223884, upload-time = "2025-06-09T22:54:25.539Z" }, - { url = "https://files.pythonhosted.org/packages/88/e4/ebe30fc399e98572019eee82ad0caf512401661985cbd3da5e3140ffa1b0/propcache-0.3.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:85871b050f174bc0bfb437efbdb68aaf860611953ed12418e4361bc9c392749e", size = 211480, upload-time = "2025-06-09T22:54:26.892Z" }, - { url = "https://files.pythonhosted.org/packages/96/0a/7d5260b914e01d1d0906f7f38af101f8d8ed0dc47426219eeaf05e8ea7c2/propcache-0.3.2-cp311-cp311-win32.whl", hash = "sha256:36c8d9b673ec57900c3554264e630d45980fd302458e4ac801802a7fd2ef7897", size = 37757, upload-time = "2025-06-09T22:54:28.241Z" }, - { url = "https://files.pythonhosted.org/packages/e1/2d/89fe4489a884bc0da0c3278c552bd4ffe06a1ace559db5ef02ef24ab446b/propcache-0.3.2-cp311-cp311-win_amd64.whl", hash = "sha256:e53af8cb6a781b02d2ea079b5b853ba9430fcbe18a8e3ce647d5982a3ff69f39", size = 41500, upload-time = "2025-06-09T22:54:29.4Z" }, - { url = "https://files.pythonhosted.org/packages/a8/42/9ca01b0a6f48e81615dca4765a8f1dd2c057e0540f6116a27dc5ee01dfb6/propcache-0.3.2-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:8de106b6c84506b31c27168582cd3cb3000a6412c16df14a8628e5871ff83c10", size = 73674, upload-time = "2025-06-09T22:54:30.551Z" }, - { url = "https://files.pythonhosted.org/packages/af/6e/21293133beb550f9c901bbece755d582bfaf2176bee4774000bd4dd41884/propcache-0.3.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:28710b0d3975117239c76600ea351934ac7b5ff56e60953474342608dbbb6154", size = 43570, upload-time = "2025-06-09T22:54:32.296Z" }, - { url = "https://files.pythonhosted.org/packages/0c/c8/0393a0a3a2b8760eb3bde3c147f62b20044f0ddac81e9d6ed7318ec0d852/propcache-0.3.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ce26862344bdf836650ed2487c3d724b00fbfec4233a1013f597b78c1cb73615", size = 43094, upload-time = "2025-06-09T22:54:33.929Z" }, - { url = "https://files.pythonhosted.org/packages/37/2c/489afe311a690399d04a3e03b069225670c1d489eb7b044a566511c1c498/propcache-0.3.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:bca54bd347a253af2cf4544bbec232ab982f4868de0dd684246b67a51bc6b1db", size = 226958, upload-time = "2025-06-09T22:54:35.186Z" }, - { url = "https://files.pythonhosted.org/packages/9d/ca/63b520d2f3d418c968bf596839ae26cf7f87bead026b6192d4da6a08c467/propcache-0.3.2-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:55780d5e9a2ddc59711d727226bb1ba83a22dd32f64ee15594b9392b1f544eb1", size = 234894, upload-time = "2025-06-09T22:54:36.708Z" }, - { url = "https://files.pythonhosted.org/packages/11/60/1d0ed6fff455a028d678df30cc28dcee7af77fa2b0e6962ce1df95c9a2a9/propcache-0.3.2-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:035e631be25d6975ed87ab23153db6a73426a48db688070d925aa27e996fe93c", size = 233672, upload-time = "2025-06-09T22:54:38.062Z" }, - { url = "https://files.pythonhosted.org/packages/37/7c/54fd5301ef38505ab235d98827207176a5c9b2aa61939b10a460ca53e123/propcache-0.3.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ee6f22b6eaa39297c751d0e80c0d3a454f112f5c6481214fcf4c092074cecd67", size = 224395, upload-time = "2025-06-09T22:54:39.634Z" }, - { url = "https://files.pythonhosted.org/packages/ee/1a/89a40e0846f5de05fdc6779883bf46ba980e6df4d2ff8fb02643de126592/propcache-0.3.2-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:7ca3aee1aa955438c4dba34fc20a9f390e4c79967257d830f137bd5a8a32ed3b", size = 212510, upload-time = "2025-06-09T22:54:41.565Z" }, - { url = "https://files.pythonhosted.org/packages/5e/33/ca98368586c9566a6b8d5ef66e30484f8da84c0aac3f2d9aec6d31a11bd5/propcache-0.3.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:7a4f30862869fa2b68380d677cc1c5fcf1e0f2b9ea0cf665812895c75d0ca3b8", size = 222949, upload-time = "2025-06-09T22:54:43.038Z" }, - { url = "https://files.pythonhosted.org/packages/ba/11/ace870d0aafe443b33b2f0b7efdb872b7c3abd505bfb4890716ad7865e9d/propcache-0.3.2-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:b77ec3c257d7816d9f3700013639db7491a434644c906a2578a11daf13176251", size = 217258, upload-time = "2025-06-09T22:54:44.376Z" }, - { url = "https://files.pythonhosted.org/packages/5b/d2/86fd6f7adffcfc74b42c10a6b7db721d1d9ca1055c45d39a1a8f2a740a21/propcache-0.3.2-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:cab90ac9d3f14b2d5050928483d3d3b8fb6b4018893fc75710e6aa361ecb2474", size = 213036, upload-time = "2025-06-09T22:54:46.243Z" }, - { url = "https://files.pythonhosted.org/packages/07/94/2d7d1e328f45ff34a0a284cf5a2847013701e24c2a53117e7c280a4316b3/propcache-0.3.2-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:0b504d29f3c47cf6b9e936c1852246c83d450e8e063d50562115a6be6d3a2535", size = 227684, upload-time = "2025-06-09T22:54:47.63Z" }, - { url = "https://files.pythonhosted.org/packages/b7/05/37ae63a0087677e90b1d14710e532ff104d44bc1efa3b3970fff99b891dc/propcache-0.3.2-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:ce2ac2675a6aa41ddb2a0c9cbff53780a617ac3d43e620f8fd77ba1c84dcfc06", size = 234562, upload-time = "2025-06-09T22:54:48.982Z" }, - { url = "https://files.pythonhosted.org/packages/a4/7c/3f539fcae630408d0bd8bf3208b9a647ccad10976eda62402a80adf8fc34/propcache-0.3.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:62b4239611205294cc433845b914131b2a1f03500ff3c1ed093ed216b82621e1", size = 222142, upload-time = "2025-06-09T22:54:50.424Z" }, - { url = "https://files.pythonhosted.org/packages/7c/d2/34b9eac8c35f79f8a962546b3e97e9d4b990c420ee66ac8255d5d9611648/propcache-0.3.2-cp312-cp312-win32.whl", hash = "sha256:df4a81b9b53449ebc90cc4deefb052c1dd934ba85012aa912c7ea7b7e38b60c1", size = 37711, upload-time = "2025-06-09T22:54:52.072Z" }, - { url = "https://files.pythonhosted.org/packages/19/61/d582be5d226cf79071681d1b46b848d6cb03d7b70af7063e33a2787eaa03/propcache-0.3.2-cp312-cp312-win_amd64.whl", hash = "sha256:7046e79b989d7fe457bb755844019e10f693752d169076138abf17f31380800c", size = 41479, upload-time = "2025-06-09T22:54:53.234Z" }, - { url = "https://files.pythonhosted.org/packages/cc/35/cc0aaecf278bb4575b8555f2b137de5ab821595ddae9da9d3cd1da4072c7/propcache-0.3.2-py3-none-any.whl", hash = "sha256:98f1ec44fb675f5052cccc8e609c46ed23a35a1cfd18545ad4e29002d858a43f", size = 12663, upload-time = "2025-06-09T22:56:04.484Z" }, -] - -[[package]] -name = "protobuf" -version = "6.31.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/52/f3/b9655a711b32c19720253f6f06326faf90580834e2e83f840472d752bc8b/protobuf-6.31.1.tar.gz", hash = "sha256:d8cac4c982f0b957a4dc73a80e2ea24fab08e679c0de9deb835f4a12d69aca9a", size = 441797, upload-time = "2025-05-28T19:25:54.947Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/f3/6f/6ab8e4bf962fd5570d3deaa2d5c38f0a363f57b4501047b5ebeb83ab1125/protobuf-6.31.1-cp310-abi3-win32.whl", hash = "sha256:7fa17d5a29c2e04b7d90e5e32388b8bfd0e7107cd8e616feef7ed3fa6bdab5c9", size = 423603, upload-time = "2025-05-28T19:25:41.198Z" }, - { url = "https://files.pythonhosted.org/packages/44/3a/b15c4347dd4bf3a1b0ee882f384623e2063bb5cf9fa9d57990a4f7df2fb6/protobuf-6.31.1-cp310-abi3-win_amd64.whl", hash = "sha256:426f59d2964864a1a366254fa703b8632dcec0790d8862d30034d8245e1cd447", size = 435283, upload-time = "2025-05-28T19:25:44.275Z" }, - { url = "https://files.pythonhosted.org/packages/6a/c9/b9689a2a250264a84e66c46d8862ba788ee7a641cdca39bccf64f59284b7/protobuf-6.31.1-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:6f1227473dc43d44ed644425268eb7c2e488ae245d51c6866d19fe158e207402", size = 425604, upload-time = "2025-05-28T19:25:45.702Z" }, - { url = "https://files.pythonhosted.org/packages/76/a1/7a5a94032c83375e4fe7e7f56e3976ea6ac90c5e85fac8576409e25c39c3/protobuf-6.31.1-cp39-abi3-manylinux2014_aarch64.whl", hash = "sha256:a40fc12b84c154884d7d4c4ebd675d5b3b5283e155f324049ae396b95ddebc39", size = 322115, upload-time = "2025-05-28T19:25:47.128Z" }, - { url = "https://files.pythonhosted.org/packages/fa/b1/b59d405d64d31999244643d88c45c8241c58f17cc887e73bcb90602327f8/protobuf-6.31.1-cp39-abi3-manylinux2014_x86_64.whl", hash = "sha256:4ee898bf66f7a8b0bd21bce523814e6fbd8c6add948045ce958b73af7e8878c6", size = 321070, upload-time = "2025-05-28T19:25:50.036Z" }, - { url = "https://files.pythonhosted.org/packages/f7/af/ab3c51ab7507a7325e98ffe691d9495ee3d3aa5f589afad65ec920d39821/protobuf-6.31.1-py3-none-any.whl", hash = "sha256:720a6c7e6b77288b85063569baae8536671b39f15cc22037ec7045658d80489e", size = 168724, upload-time = "2025-05-28T19:25:53.926Z" }, -] - -[[package]] -name = "psutil" -version = "7.0.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/2a/80/336820c1ad9286a4ded7e845b2eccfcb27851ab8ac6abece774a6ff4d3de/psutil-7.0.0.tar.gz", hash = "sha256:7be9c3eba38beccb6495ea33afd982a44074b78f28c434a1f51cc07fd315c456", size = 497003, upload-time = "2025-02-13T21:54:07.946Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/ed/e6/2d26234410f8b8abdbf891c9da62bee396583f713fb9f3325a4760875d22/psutil-7.0.0-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:101d71dc322e3cffd7cea0650b09b3d08b8e7c4109dd6809fe452dfd00e58b25", size = 238051, upload-time = "2025-02-13T21:54:12.36Z" }, - { url = "https://files.pythonhosted.org/packages/04/8b/30f930733afe425e3cbfc0e1468a30a18942350c1a8816acfade80c005c4/psutil-7.0.0-cp36-abi3-macosx_11_0_arm64.whl", hash = "sha256:39db632f6bb862eeccf56660871433e111b6ea58f2caea825571951d4b6aa3da", size = 239535, upload-time = "2025-02-13T21:54:16.07Z" }, - { url = "https://files.pythonhosted.org/packages/2a/ed/d362e84620dd22876b55389248e522338ed1bf134a5edd3b8231d7207f6d/psutil-7.0.0-cp36-abi3-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1fcee592b4c6f146991ca55919ea3d1f8926497a713ed7faaf8225e174581e91", size = 275004, upload-time = "2025-02-13T21:54:18.662Z" }, - { url = "https://files.pythonhosted.org/packages/bf/b9/b0eb3f3cbcb734d930fdf839431606844a825b23eaf9a6ab371edac8162c/psutil-7.0.0-cp36-abi3-manylinux_2_12_x86_64.manylinux2010_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4b1388a4f6875d7e2aff5c4ca1cc16c545ed41dd8bb596cefea80111db353a34", size = 277986, upload-time = "2025-02-13T21:54:21.811Z" }, - { url = "https://files.pythonhosted.org/packages/eb/a2/709e0fe2f093556c17fbafda93ac032257242cabcc7ff3369e2cb76a97aa/psutil-7.0.0-cp36-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a5f098451abc2828f7dc6b58d44b532b22f2088f4999a937557b603ce72b1993", size = 279544, upload-time = "2025-02-13T21:54:24.68Z" }, - { url = "https://files.pythonhosted.org/packages/50/e6/eecf58810b9d12e6427369784efe814a1eec0f492084ce8eb8f4d89d6d61/psutil-7.0.0-cp37-abi3-win32.whl", hash = "sha256:ba3fcef7523064a6c9da440fc4d6bd07da93ac726b5733c29027d7dc95b39d99", size = 241053, upload-time = "2025-02-13T21:54:34.31Z" }, - { url = "https://files.pythonhosted.org/packages/50/1b/6921afe68c74868b4c9fa424dad3be35b095e16687989ebbb50ce4fceb7c/psutil-7.0.0-cp37-abi3-win_amd64.whl", hash = "sha256:4cf3d4eb1aa9b348dec30105c55cd9b7d4629285735a102beb4441e38db90553", size = 244885, upload-time = "2025-02-13T21:54:37.486Z" }, -] - -[[package]] -name = "pyarrow" -version = "20.0.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a2/ee/a7810cb9f3d6e9238e61d312076a9859bf3668fd21c69744de9532383912/pyarrow-20.0.0.tar.gz", hash = "sha256:febc4a913592573c8d5805091a6c2b5064c8bd6e002131f01061797d91c783c1", size = 1125187, upload-time = "2025-04-27T12:34:23.264Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/47/a2/b7930824181ceadd0c63c1042d01fa4ef63eee233934826a7a2a9af6e463/pyarrow-20.0.0-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:24ca380585444cb2a31324c546a9a56abbe87e26069189e14bdba19c86c049f0", size = 30856035, upload-time = "2025-04-27T12:28:40.78Z" }, - { url = "https://files.pythonhosted.org/packages/9b/18/c765770227d7f5bdfa8a69f64b49194352325c66a5c3bb5e332dfd5867d9/pyarrow-20.0.0-cp311-cp311-macosx_12_0_x86_64.whl", hash = "sha256:95b330059ddfdc591a3225f2d272123be26c8fa76e8c9ee1a77aad507361cfdb", size = 32309552, upload-time = "2025-04-27T12:28:47.051Z" }, - { url = "https://files.pythonhosted.org/packages/44/fb/dfb2dfdd3e488bb14f822d7335653092dde150cffc2da97de6e7500681f9/pyarrow-20.0.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5f0fb1041267e9968c6d0d2ce3ff92e3928b243e2b6d11eeb84d9ac547308232", size = 41334704, upload-time = "2025-04-27T12:28:55.064Z" }, - { url = "https://files.pythonhosted.org/packages/58/0d/08a95878d38808051a953e887332d4a76bc06c6ee04351918ee1155407eb/pyarrow-20.0.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b8ff87cc837601532cc8242d2f7e09b4e02404de1b797aee747dd4ba4bd6313f", size = 42399836, upload-time = "2025-04-27T12:29:02.13Z" }, - { url = "https://files.pythonhosted.org/packages/f3/cd/efa271234dfe38f0271561086eedcad7bc0f2ddd1efba423916ff0883684/pyarrow-20.0.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:7a3a5dcf54286e6141d5114522cf31dd67a9e7c9133d150799f30ee302a7a1ab", size = 40711789, upload-time = "2025-04-27T12:29:09.951Z" }, - { url = "https://files.pythonhosted.org/packages/46/1f/7f02009bc7fc8955c391defee5348f510e589a020e4b40ca05edcb847854/pyarrow-20.0.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:a6ad3e7758ecf559900261a4df985662df54fb7fdb55e8e3b3aa99b23d526b62", size = 42301124, upload-time = "2025-04-27T12:29:17.187Z" }, - { url = "https://files.pythonhosted.org/packages/4f/92/692c562be4504c262089e86757a9048739fe1acb4024f92d39615e7bab3f/pyarrow-20.0.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:6bb830757103a6cb300a04610e08d9636f0cd223d32f388418ea893a3e655f1c", size = 42916060, upload-time = "2025-04-27T12:29:24.253Z" }, - { url = "https://files.pythonhosted.org/packages/a4/ec/9f5c7e7c828d8e0a3c7ef50ee62eca38a7de2fa6eb1b8fa43685c9414fef/pyarrow-20.0.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:96e37f0766ecb4514a899d9a3554fadda770fb57ddf42b63d80f14bc20aa7db3", size = 44547640, upload-time = "2025-04-27T12:29:32.782Z" }, - { url = "https://files.pythonhosted.org/packages/54/96/46613131b4727f10fd2ffa6d0d6f02efcc09a0e7374eff3b5771548aa95b/pyarrow-20.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:3346babb516f4b6fd790da99b98bed9708e3f02e734c84971faccb20736848dc", size = 25781491, upload-time = "2025-04-27T12:29:38.464Z" }, - { url = "https://files.pythonhosted.org/packages/a1/d6/0c10e0d54f6c13eb464ee9b67a68b8c71bcf2f67760ef5b6fbcddd2ab05f/pyarrow-20.0.0-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:75a51a5b0eef32727a247707d4755322cb970be7e935172b6a3a9f9ae98404ba", size = 30815067, upload-time = "2025-04-27T12:29:44.384Z" }, - { url = "https://files.pythonhosted.org/packages/7e/e2/04e9874abe4094a06fd8b0cbb0f1312d8dd7d707f144c2ec1e5e8f452ffa/pyarrow-20.0.0-cp312-cp312-macosx_12_0_x86_64.whl", hash = "sha256:211d5e84cecc640c7a3ab900f930aaff5cd2702177e0d562d426fb7c4f737781", size = 32297128, upload-time = "2025-04-27T12:29:52.038Z" }, - { url = "https://files.pythonhosted.org/packages/31/fd/c565e5dcc906a3b471a83273039cb75cb79aad4a2d4a12f76cc5ae90a4b8/pyarrow-20.0.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4ba3cf4182828be7a896cbd232aa8dd6a31bd1f9e32776cc3796c012855e1199", size = 41334890, upload-time = "2025-04-27T12:29:59.452Z" }, - { url = "https://files.pythonhosted.org/packages/af/a9/3bdd799e2c9b20c1ea6dc6fa8e83f29480a97711cf806e823f808c2316ac/pyarrow-20.0.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2c3a01f313ffe27ac4126f4c2e5ea0f36a5fc6ab51f8726cf41fee4b256680bd", size = 42421775, upload-time = "2025-04-27T12:30:06.875Z" }, - { url = "https://files.pythonhosted.org/packages/10/f7/da98ccd86354c332f593218101ae56568d5dcedb460e342000bd89c49cc1/pyarrow-20.0.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:a2791f69ad72addd33510fec7bb14ee06c2a448e06b649e264c094c5b5f7ce28", size = 40687231, upload-time = "2025-04-27T12:30:13.954Z" }, - { url = "https://files.pythonhosted.org/packages/bb/1b/2168d6050e52ff1e6cefc61d600723870bf569cbf41d13db939c8cf97a16/pyarrow-20.0.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:4250e28a22302ce8692d3a0e8ec9d9dde54ec00d237cff4dfa9c1fbf79e472a8", size = 42295639, upload-time = "2025-04-27T12:30:21.949Z" }, - { url = "https://files.pythonhosted.org/packages/b2/66/2d976c0c7158fd25591c8ca55aee026e6d5745a021915a1835578707feb3/pyarrow-20.0.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:89e030dc58fc760e4010148e6ff164d2f44441490280ef1e97a542375e41058e", size = 42908549, upload-time = "2025-04-27T12:30:29.551Z" }, - { url = "https://files.pythonhosted.org/packages/31/a9/dfb999c2fc6911201dcbf348247f9cc382a8990f9ab45c12eabfd7243a38/pyarrow-20.0.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:6102b4864d77102dbbb72965618e204e550135a940c2534711d5ffa787df2a5a", size = 44557216, upload-time = "2025-04-27T12:30:36.977Z" }, - { url = "https://files.pythonhosted.org/packages/a0/8e/9adee63dfa3911be2382fb4d92e4b2e7d82610f9d9f668493bebaa2af50f/pyarrow-20.0.0-cp312-cp312-win_amd64.whl", hash = "sha256:96d6a0a37d9c98be08f5ed6a10831d88d52cac7b13f5287f1e0f625a0de8062b", size = 25660496, upload-time = "2025-04-27T12:30:42.809Z" }, -] - -[[package]] -name = "pyaudio" -version = "0.2.14" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/26/1d/8878c7752febb0f6716a7e1a52cb92ac98871c5aa522cba181878091607c/PyAudio-0.2.14.tar.gz", hash = "sha256:78dfff3879b4994d1f4fc6485646a57755c6ee3c19647a491f790a0895bd2f87", size = 47066, upload-time = "2023-11-07T07:11:48.806Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/7b/f0/b0eab89eafa70a86b7b566a4df2f94c7880a2d483aa8de1c77d335335b5b/PyAudio-0.2.14-cp311-cp311-win32.whl", hash = "sha256:506b32a595f8693811682ab4b127602d404df7dfc453b499c91a80d0f7bad289", size = 144624, upload-time = "2023-11-07T07:11:36.94Z" }, - { url = "https://files.pythonhosted.org/packages/82/d8/f043c854aad450a76e476b0cf9cda1956419e1dacf1062eb9df3c0055abe/PyAudio-0.2.14-cp311-cp311-win_amd64.whl", hash = "sha256:bbeb01d36a2f472ae5ee5e1451cacc42112986abe622f735bb870a5db77cf903", size = 164070, upload-time = "2023-11-07T07:11:38.579Z" }, - { url = "https://files.pythonhosted.org/packages/8d/45/8d2b76e8f6db783f9326c1305f3f816d4a12c8eda5edc6a2e1d03c097c3b/PyAudio-0.2.14-cp312-cp312-win32.whl", hash = "sha256:5fce4bcdd2e0e8c063d835dbe2860dac46437506af509353c7f8114d4bacbd5b", size = 144750, upload-time = "2023-11-07T07:11:40.142Z" }, - { url = "https://files.pythonhosted.org/packages/b0/6a/d25812e5f79f06285767ec607b39149d02aa3b31d50c2269768f48768930/PyAudio-0.2.14-cp312-cp312-win_amd64.whl", hash = "sha256:12f2f1ba04e06ff95d80700a78967897a489c05e093e3bffa05a84ed9c0a7fa3", size = 164126, upload-time = "2023-11-07T07:11:41.539Z" }, -] - -[[package]] -name = "pyautogui" -version = "0.9.54" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "mouseinfo" }, - { name = "pygetwindow" }, - { name = "pymsgbox" }, - { name = "pyobjc-core", marker = "sys_platform == 'darwin'" }, - { name = "pyobjc-framework-quartz", marker = "sys_platform == 'darwin'" }, - { name = "pyscreeze" }, - { name = "python3-xlib", marker = "sys_platform == 'linux'" }, - { name = "pytweening" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/65/ff/cdae0a8c2118a0de74b6cf4cbcdcaf8fd25857e6c3f205ce4b1794b27814/PyAutoGUI-0.9.54.tar.gz", hash = "sha256:dd1d29e8fd118941cb193f74df57e5c6ff8e9253b99c7b04f39cfc69f3ae04b2", size = 61236, upload-time = "2023-05-24T20:11:32.972Z" } - [[package]] name = "pycapnp" -version = "2.0.0" +version = "2.1.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/9b/fb/54b46b52c1fa2acd9afd81bd05810c61bb1b05c6084c9625b64bc6d41843/pycapnp-2.0.0.tar.gz", hash = "sha256:503ab9b7b16773590ee226f2460408972c6b1c2cb2d819037115b919bef682be", size = 574848, upload-time = "2024-04-12T15:35:44.019Z" } +sdist = { url = "https://files.pythonhosted.org/packages/15/86/a57e3c92acd3e1d2fc3dcad683ada191f722e4ac927e1a384b228ec2780a/pycapnp-2.1.0.tar.gz", hash = "sha256:69cc3d861fee1c9b26c73ad2e8a5d51e76ad87e4ff9be33a4fd2fc72f5846aec", size = 689734, upload-time = "2025-09-05T03:50:40.851Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/cb/82/cf311b1a9800b605759a38a0c337a55a639b685427364294e98a0f9b7306/pycapnp-2.0.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:829c7eb4e5f23dbcac25466110faf72a691035cf87c5d46e5053da15790e428d", size = 1673673, upload-time = "2024-04-12T15:33:32.211Z" }, - { url = "https://files.pythonhosted.org/packages/ae/55/4c03ca95c568776a1f637db9ffdcf302fb63f46e4d2a4f13edd8cb1a5f90/pycapnp-2.0.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:dab60fbe3e4eaf99ec97918a0a776216c6c149b6d49261383d91c2201adb475d", size = 1513351, upload-time = "2024-04-12T15:33:35.156Z" }, - { url = "https://files.pythonhosted.org/packages/55/98/e4b2dea076f8a2575abc45cd879a91bc9aa975c69ae2ac1cab61d83c5087/pycapnp-2.0.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2c48a0582078bb74d7326d28571db0b8e6919563365537a5a13e8f5360c12bfc", size = 4910666, upload-time = "2024-04-12T15:33:37.798Z" }, - { url = "https://files.pythonhosted.org/packages/1d/ee/3b5a182588f89074f4002fa6247e3f963bb85bc808acd1ac8deed91f1fa7/pycapnp-2.0.0-cp311-cp311-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:bcb5ab54aff857e3711d2c0cc934194aaffacdeb3481daa56863daef07d27941", size = 5007434, upload-time = "2024-04-12T15:33:40.362Z" }, - { url = "https://files.pythonhosted.org/packages/c5/e9/515a2ca7fdc84d57c654280d0b71dfd782fd1773d384c0ec0d56dc6fc35b/pycapnp-2.0.0-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:9600778036e6fe9dbea68f0c37678c5f4d561d2f2306b3cb741de5e1670ef2ae", size = 5188923, upload-time = "2024-04-12T15:33:42.33Z" }, - { url = "https://files.pythonhosted.org/packages/70/60/5db346e238985a526ba7589ed24f92195dad39e7dec9d85b17a567600b6f/pycapnp-2.0.0-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:7278ba0262fab8c398e77d634ae7ba026866d44b52cbfc27262be8d396ecacd1", size = 5048105, upload-time = "2024-04-12T15:33:44.294Z" }, - { url = "https://files.pythonhosted.org/packages/e3/ff/02b4a87c9ff9793f26d8f3d95312d902d260c094f216d84e19528a506606/pycapnp-2.0.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:23b2458d43c82302980a96518c96df257429204d2cc02bfff0c8cb6ebb371e01", size = 5063172, upload-time = "2024-04-12T15:33:46.954Z" }, - { url = "https://files.pythonhosted.org/packages/10/a1/35a7e14d765f99cfdcdfdcebc69bdf382f27016944470daa7a03c557f681/pycapnp-2.0.0-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:dd7755cc3fedc2ad8cc7864a0729471ddeff10c184963fe0f3689e295130f1b2", size = 5408718, upload-time = "2024-04-12T15:33:49.587Z" }, - { url = "https://files.pythonhosted.org/packages/5c/59/8bc8a993c38808c6fd90b10becba8de4a54543e8441bd87ce44ef3b7eee4/pycapnp-2.0.0-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:d47baf6b3db9981625ffc5ff188e089f2ebca8e7e1afb97aa5eb7bebb7bf3650", size = 5596714, upload-time = "2024-04-12T15:33:51.518Z" }, - { url = "https://files.pythonhosted.org/packages/ea/7d/79c481ef77f29e81355e92bb250f0d2a37a76f5fe0ba9433bf6c6c88b6e4/pycapnp-2.0.0-cp311-cp311-musllinux_1_1_ppc64le.whl", hash = "sha256:b375be92d93fdb6f7ac127ea9390bcec0fed4e485db137b084f9e7114dde7c83", size = 5709896, upload-time = "2024-04-12T15:33:53.716Z" }, - { url = "https://files.pythonhosted.org/packages/59/8d/f2eceeea1e8cae8b8a70a4752af5b772916f455e2ed388d0887e2b57d080/pycapnp-2.0.0-cp311-cp311-musllinux_1_1_s390x.whl", hash = "sha256:959bfdf1cddb3e5528e2293c4a375382be9a1bf044b073bc2e7eca1eb6b3a9a2", size = 5594823, upload-time = "2024-04-12T15:33:55.573Z" }, - { url = "https://files.pythonhosted.org/packages/2c/86/f8284637b61f83232e5618dd561a66080dd98ce2272d7e3ae89335d4fd97/pycapnp-2.0.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:d873af167cf5cc7578ce5432eefcb442f866c8f7a6c57d188baf8c5e709fa39d", size = 5572564, upload-time = "2024-04-12T15:33:59.112Z" }, - { url = "https://files.pythonhosted.org/packages/b3/b2/7f99d28a9935d1e37ec6955922c57b2be24fe0b74fe25929643686cc11e5/pycapnp-2.0.0-cp311-cp311-win32.whl", hash = "sha256:40ca8018e0b7686d549b920f087049b92a3e6f06976d9f5a8112603fc560cac4", size = 1040268, upload-time = "2024-04-12T15:34:00.933Z" }, - { url = "https://files.pythonhosted.org/packages/1d/37/89ab98961f18cffeae20d98cfc24afcfa85024bc014ecc48b0c4ac264fe0/pycapnp-2.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:d15cd8e46d541a899c84809095d7d7b3951f43642d1859e7a39bd91910778479", size = 1141758, upload-time = "2024-04-12T15:34:02.607Z" }, - { url = "https://files.pythonhosted.org/packages/ce/d5/0ee84de3ce34a86c373b6cfbea17d5486c2ca942d51efa99a0069723c1e3/pycapnp-2.0.0-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:0c111ef96676df25b8afef98f369d45f838ad4434e2898e48199eb43ef704efe", size = 1645816, upload-time = "2024-04-12T15:34:04.428Z" }, - { url = "https://files.pythonhosted.org/packages/35/1e/580572083165ba791fac5ae2d8917facb94db6e3f0500421673f55165dac/pycapnp-2.0.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:0d18906eb1fd1b9f206d93a9591ceedce1d52e7766b66e68f271453f104e9dca", size = 1507892, upload-time = "2024-04-12T15:34:06.933Z" }, - { url = "https://files.pythonhosted.org/packages/d7/ed/46b3cc5d32c525b6a3acb67eb43de2cec692a62775ec1ab66dafe2b7d6ad/pycapnp-2.0.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f5d1ed365ab1beabb8838068907a7190cc0b6f16de3499d783627e670fcc0eb2", size = 4707960, upload-time = "2024-04-12T15:34:08.771Z" }, - { url = "https://files.pythonhosted.org/packages/8e/51/0a0a4d4e44138adb84959478ea4966196c5ad32022f768b9b64d1590cb3e/pycapnp-2.0.0-cp312-cp312-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:495b39a7aa2629931bbca27ad743ce591c6c41e8f81792276be424742d9cd1c1", size = 4791780, upload-time = "2024-04-12T15:34:10.863Z" }, - { url = "https://files.pythonhosted.org/packages/28/71/2b59c6ddb253b25b3d01ee6f7b32b0297ac205c7272beeb6d13399054430/pycapnp-2.0.0-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:50e814fbde072dcc3d868b5b5cbb9b7a66a70bff9ad03942f3be9baf3ca1cfc6", size = 4961068, upload-time = "2024-04-12T15:34:13.543Z" }, - { url = "https://files.pythonhosted.org/packages/c3/b8/b64fdefa59d6d2802b5ee0a9439396c23a3e5954da6909be81f2722a234c/pycapnp-2.0.0-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:920fdda62d5fdef7a48339104dff0ceb9dcc21b138491f854457ba3a3d4d63ec", size = 4872917, upload-time = "2024-04-12T15:34:15.636Z" }, - { url = "https://files.pythonhosted.org/packages/c8/55/867595f575eb6cb3662e9a0b50a24b4be42df86f2938003e586f6c81606f/pycapnp-2.0.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3f9142eb4714c152b09dda0b055ea9dd43fd8fd894132e7eb4fa235fb4915edd", size = 4912169, upload-time = "2024-04-12T15:34:17.758Z" }, - { url = "https://files.pythonhosted.org/packages/e4/11/0d36b45e5005ecdf8510081d16c6fb7b22b49651f64af36d138df97980cc/pycapnp-2.0.0-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:c98f1d0c4d32109d03e42828ce3c65236afc895033633cbed3ca092993702e7b", size = 5201744, upload-time = "2024-04-12T15:34:20.468Z" }, - { url = "https://files.pythonhosted.org/packages/05/29/ad1357998656b7141939e55bb3aea727c7a5478026feed7f8ee8cf52c935/pycapnp-2.0.0-cp312-cp312-musllinux_1_1_i686.whl", hash = "sha256:4d3250c1875a309d67551843cd8bf3c5e7fccf159b7f5c118a92aee36c0e871c", size = 5351113, upload-time = "2024-04-12T15:34:23.173Z" }, - { url = "https://files.pythonhosted.org/packages/5a/b1/f4c442907948a29b6427dd7436f31d3732bb0d77f5c1dbcad749ba56dac0/pycapnp-2.0.0-cp312-cp312-musllinux_1_1_ppc64le.whl", hash = "sha256:174e6babe01f5507111c0ed226cd0b5e9325a9d2850751cfe4a57c1670f13881", size = 5472055, upload-time = "2024-04-12T15:34:25.799Z" }, - { url = "https://files.pythonhosted.org/packages/c1/06/a6eceb8b8015f518c0ccae1de5d1a6e18ed73b62b4b111aff54ce5f4f566/pycapnp-2.0.0-cp312-cp312-musllinux_1_1_s390x.whl", hash = "sha256:ed38ece414341285695526792e020f391f29f5064b2126d0367c8bdeef28e3e9", size = 5395743, upload-time = "2024-04-12T15:34:28.134Z" }, - { url = "https://files.pythonhosted.org/packages/e7/b0/63f2b0327853ae08158de61b4dfc7fa43ae5a5c00f1d28f769e7c30cdf55/pycapnp-2.0.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:8a20b7dc55ef83a1fa446bf12680bce25caeb8f81788b623b072c3ec820db50d", size = 5405076, upload-time = "2024-04-12T15:34:30.305Z" }, - { url = "https://files.pythonhosted.org/packages/7d/24/e025dd95f1abf34e373fbab8841ac8e5fa62afe3af4a4b0c61bd01354400/pycapnp-2.0.0-cp312-cp312-win32.whl", hash = "sha256:145eea66233fb5ac9152cd1c06b999ddb691815126f87f5cc37b9cda5d569f8a", size = 1030361, upload-time = "2024-04-12T15:34:32.25Z" }, - { url = "https://files.pythonhosted.org/packages/3f/70/a71108ee9d4db9a027b665a2c383202407207174f1956195d5be45aca705/pycapnp-2.0.0-cp312-cp312-win_amd64.whl", hash = "sha256:b8b03000769b29b36a8810f458b931f0f706f42027ee6676821eff28092d7734", size = 1135121, upload-time = "2024-04-12T15:34:34.208Z" }, + { url = "https://files.pythonhosted.org/packages/74/0e/66b41ba600e5f2523e900b7cc0d2e8496b397a1f2d6a5b7b323ab83418b7/pycapnp-2.1.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:2d2ec561bc948d11f64f43bf9601bede5d6a603d105ae311bd5583c7130624a4", size = 1619223, upload-time = "2025-09-05T03:48:54.64Z" }, + { url = "https://files.pythonhosted.org/packages/40/6e/9bcb30180bd40cb0534124ff7f8ba8746a735018d593f608bf40c97821c0/pycapnp-2.1.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:132cd97f57f6b6636323ca9b68d389dd90b96e87af38cde31e2b5c5a064f277e", size = 1484321, upload-time = "2025-09-05T03:48:55.85Z" }, + { url = "https://files.pythonhosted.org/packages/14/0a/9ee1c9ecaff499e4fd1df2f0335bc20f666ec6ce5cd80f8ab055007f3c9b/pycapnp-2.1.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:568e79268ba7c02a71fe558a8aec1ae3c0f0e6aff809ff618a46afe4964957d2", size = 5143502, upload-time = "2025-09-05T03:48:57.733Z" }, + { url = "https://files.pythonhosted.org/packages/4d/50/65837e1416f7a8861ca1e8fe4582a5aef37192d7ef5e2ecfe46880bfdf9c/pycapnp-2.1.0-cp312-cp312-manylinux_2_28_ppc64le.whl", hash = "sha256:bcbf6f882d78d368c8e4bb792295392f5c4d71ddffa13a48da27e7bd47b99e37", size = 5508134, upload-time = "2025-09-05T03:48:59.383Z" }, + { url = "https://files.pythonhosted.org/packages/a1/59/46df6db800e77dbc3cc940723fb3fd7bc837327c858edf464a0f904bf547/pycapnp-2.1.0-cp312-cp312-manylinux_2_28_s390x.whl", hash = "sha256:dc25b96e393410dde25c61c1df3ce644700ef94826c829426d58c2c6b3e2d2f5", size = 5631794, upload-time = "2025-09-05T03:49:03.511Z" }, + { url = "https://files.pythonhosted.org/packages/63/9d/18e978500d5f6bd8d152f4d6919e3cfb83ead8a71c14613bbb54322df8b9/pycapnp-2.1.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:48938e0436ab1be615fc0a41434119a2065490a6212b9a5e56949e89b0588b76", size = 5369378, upload-time = "2025-09-05T03:49:05.539Z" }, + { url = "https://files.pythonhosted.org/packages/96/dc/726f1917e9996dc29f9fd1cf30674a14546cdbdfa0777e1982b6bd1ad628/pycapnp-2.1.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:0c20de0f6e0b3fa9fa1df3864cf46051db3511b63bc29514d1092af65f2b82a0", size = 5999140, upload-time = "2025-09-05T03:49:07.341Z" }, + { url = "https://files.pythonhosted.org/packages/fd/3a/3bbc4c5776fc32fbf8a59df5c7c5810efd292b933cd6545eb4b16d896268/pycapnp-2.1.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:18caca6527862475167c10ea0809531130585aa8a86cc76cd1629eb87ee30637", size = 6454308, upload-time = "2025-09-05T03:49:08.998Z" }, + { url = "https://files.pythonhosted.org/packages/bf/dd/17e2d7808424f10ffddc47329b980488ed83ec716c504791787e593a7a93/pycapnp-2.1.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:9dcc11237697007b66e3bfc500d2ad892bd79672c9b50d61fbf728c6aaf936de", size = 6544212, upload-time = "2025-09-05T03:49:10.675Z" }, + { url = "https://files.pythonhosted.org/packages/6a/5b/68090013128d7853f34c43828dd4dc80a7c8516fd1b56057b134e1e4c2c0/pycapnp-2.1.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:c151edf78155b6416e7cb31e2e333d302d742ba52bb37d4dbdf71e75cc999d46", size = 6295279, upload-time = "2025-09-05T03:49:12.712Z" }, + { url = "https://files.pythonhosted.org/packages/5b/52/7d85212b4fcf127588888f71d3dbf5558ee7dc302eba760b12b1b325f9a3/pycapnp-2.1.0-cp312-cp312-win32.whl", hash = "sha256:c09b28419321dafafc644d60c57ff8ccaf3c3e686801b6060c612a7a3c580944", size = 1038995, upload-time = "2025-09-05T03:49:14.165Z" }, + { url = "https://files.pythonhosted.org/packages/f2/12/25d283ebf5c28717364647672e7494dc46196ca7a662f5420e4866f45687/pycapnp-2.1.0-cp312-cp312-win_amd64.whl", hash = "sha256:560cb69cc02b0347e85b0629e4c2f0a316240900aa905392f9df6bab0a359989", size = 1176620, upload-time = "2025-09-05T03:49:15.545Z" }, ] [[package]] name = "pycparser" -version = "2.22" +version = "3.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/1d/b2/31537cf4b1ca988837256c910a668b553fceb8f069bedc4b1c826024b52c/pycparser-2.22.tar.gz", hash = "sha256:491c8be9c040f5390f5bf44a5b07752bd07f56edf992381b05c701439eec10f6", size = 172736, upload-time = "2024-03-30T13:22:22.564Z" } +sdist = { url = "https://files.pythonhosted.org/packages/1b/7d/92392ff7815c21062bea51aa7b87d45576f649f16458d78b7cf94b9ab2e6/pycparser-3.0.tar.gz", hash = "sha256:600f49d217304a5902ac3c37e1281c9fe94e4d0489de643a9504c5cdfdfc6b29", size = 103492, upload-time = "2026-01-21T14:26:51.89Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/13/a3/a812df4e2dd5696d1f351d58b8fe16a405b234ad2886a0dab9183fb78109/pycparser-2.22-py3-none-any.whl", hash = "sha256:c3702b6d3dd8c7abc1afa565d7e63d53a1d0bd86cdc24edd75470f4de499cfcc", size = 117552, upload-time = "2024-03-30T13:22:20.476Z" }, + { url = "https://files.pythonhosted.org/packages/0c/c3/44f3fbbfa403ea2a7c779186dc20772604442dde72947e7d01069cbe98e3/pycparser-3.0-py3-none-any.whl", hash = "sha256:b727414169a36b7d524c1c3e31839a521725078d7b2ff038656844266160a992", size = 48172, upload-time = "2026-01-21T14:26:50.693Z" }, ] [[package]] @@ -1732,65 +941,22 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/18/3d/f9441a0d798bf2b1e645adc3265e55706aead1255ccdad3856dbdcffec14/pycryptodome-3.23.0-cp37-abi3-win_arm64.whl", hash = "sha256:11eeeb6917903876f134b56ba11abe95c0b0fd5e3330def218083c7d98bbcb3c", size = 1703675, upload-time = "2025-05-17T17:21:13.146Z" }, ] -[[package]] -name = "pyee" -version = "13.0.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "typing-extensions" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/95/03/1fd98d5841cd7964a27d729ccf2199602fe05eb7a405c1462eb7277945ed/pyee-13.0.0.tar.gz", hash = "sha256:b391e3c5a434d1f5118a25615001dbc8f669cf410ab67d04c4d4e07c55481c37", size = 31250, upload-time = "2025-03-17T18:53:15.955Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/9b/4d/b9add7c84060d4c1906abe9a7e5359f2a60f7a9a4f67268b2766673427d8/pyee-13.0.0-py3-none-any.whl", hash = "sha256:48195a3cddb3b1515ce0695ed76036b5ccc2ef3a9f963ff9f77aec0139845498", size = 15730, upload-time = "2025-03-17T18:53:14.532Z" }, -] - -[[package]] -name = "pygame" -version = "2.6.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/49/cc/08bba60f00541f62aaa252ce0cfbd60aebd04616c0b9574f755b583e45ae/pygame-2.6.1.tar.gz", hash = "sha256:56fb02ead529cee00d415c3e007f75e0780c655909aaa8e8bf616ee09c9feb1f", size = 14808125, upload-time = "2024-09-29T13:41:34.698Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/c4/ca/8f367cb9fe734c4f6f6400e045593beea2635cd736158f9fabf58ee14e3c/pygame-2.6.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:20349195326a5e82a16e351ed93465a7845a7e2a9af55b7bc1b2110ea3e344e1", size = 13113753, upload-time = "2024-09-29T14:26:13.751Z" }, - { url = "https://files.pythonhosted.org/packages/83/47/6edf2f890139616b3219be9cfcc8f0cb8f42eb15efd59597927e390538cb/pygame-2.6.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:f3935459109da4bb0b3901da9904f0a3e52028a3332a355d298b1673a334cf21", size = 12378146, upload-time = "2024-09-29T14:26:22.456Z" }, - { url = "https://files.pythonhosted.org/packages/00/9e/0d8aa8cf93db2d2ee38ebaf1c7b61d0df36ded27eb726221719c150c673d/pygame-2.6.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c31dbdb5d0217f32764797d21c2752e258e5fb7e895326538d82b5f75a0cd856", size = 13611760, upload-time = "2024-09-29T11:10:47.317Z" }, - { url = "https://files.pythonhosted.org/packages/d7/9e/d06adaa5cc65876bcd7a24f59f67e07f7e4194e6298130024ed3fb22c456/pygame-2.6.1-cp311-cp311-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:173badf82fa198e6888017bea40f511cb28e69ecdd5a72b214e81e4dcd66c3b1", size = 14298054, upload-time = "2024-09-29T11:39:53.891Z" }, - { url = "https://files.pythonhosted.org/packages/7a/a1/9ae2852ebd3a7cc7d9ae7ff7919ab983e4a5c1b7a14e840732f23b2b48f6/pygame-2.6.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ce8cc108b92de9b149b344ad2e25eedbe773af0dc41dfb24d1f07f679b558c60", size = 13977107, upload-time = "2024-09-29T11:39:56.831Z" }, - { url = "https://files.pythonhosted.org/packages/31/df/6788fd2e9a864d0496a77670e44a7c012184b7a5382866ab0e60c55c0f28/pygame-2.6.1-cp311-cp311-win32.whl", hash = "sha256:811e7b925146d8149d79193652cbb83e0eca0aae66476b1cb310f0f4226b8b5c", size = 10250863, upload-time = "2024-09-29T11:44:48.199Z" }, - { url = "https://files.pythonhosted.org/packages/d2/55/ca3eb851aeef4f6f2e98a360c201f0d00bd1ba2eb98e2c7850d80aabc526/pygame-2.6.1-cp311-cp311-win_amd64.whl", hash = "sha256:91476902426facd4bb0dad4dc3b2573bc82c95c71b135e0daaea072ed528d299", size = 10622016, upload-time = "2024-09-29T12:17:01.545Z" }, - { url = "https://files.pythonhosted.org/packages/92/16/2c602c332f45ff9526d61f6bd764db5096ff9035433e2172e2d2cadae8db/pygame-2.6.1-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:4ee7f2771f588c966fa2fa8b829be26698c9b4836f82ede5e4edc1a68594942e", size = 13118279, upload-time = "2024-09-29T14:26:30.427Z" }, - { url = "https://files.pythonhosted.org/packages/cd/53/77ccbc384b251c6e34bfd2e734c638233922449a7844e3c7a11ef91cee39/pygame-2.6.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:c8040ea2ab18c6b255af706ec01355c8a6b08dc48d77fd4ee783f8fc46a843bf", size = 12384524, upload-time = "2024-09-29T14:26:49.996Z" }, - { url = "https://files.pythonhosted.org/packages/06/be/3ed337583f010696c3b3435e89a74fb29d0c74d0931e8f33c0a4246307a9/pygame-2.6.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c47a6938de93fa610accd4969e638c2aebcb29b2fca518a84c3a39d91ab47116", size = 13587123, upload-time = "2024-09-29T11:10:50.072Z" }, - { url = "https://files.pythonhosted.org/packages/fd/ca/b015586a450db59313535662991b34d24c1f0c0dc149cc5f496573900f4e/pygame-2.6.1-cp312-cp312-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:33006f784e1c7d7e466fcb61d5489da59cc5f7eb098712f792a225df1d4e229d", size = 14275532, upload-time = "2024-09-29T11:39:59.356Z" }, - { url = "https://files.pythonhosted.org/packages/b9/f2/d31e6ad42d657af07be2ffd779190353f759a07b51232b9e1d724f2cda46/pygame-2.6.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1206125f14cae22c44565c9d333607f1d9f59487b1f1432945dfc809aeaa3e88", size = 13952653, upload-time = "2024-09-29T11:40:01.781Z" }, - { url = "https://files.pythonhosted.org/packages/f3/42/8ea2a6979e6fa971702fece1747e862e2256d4a8558fe0da6364dd946c53/pygame-2.6.1-cp312-cp312-win32.whl", hash = "sha256:84fc4054e25262140d09d39e094f6880d730199710829902f0d8ceae0213379e", size = 10252421, upload-time = "2024-09-29T11:14:26.877Z" }, - { url = "https://files.pythonhosted.org/packages/5f/90/7d766d54bb95939725e9a9361f9c06b0cfbe3fe100aa35400f0a461a278a/pygame-2.6.1-cp312-cp312-win_amd64.whl", hash = "sha256:3a9e7396be0d9633831c3f8d5d82dd63ba373ad65599628294b7a4f8a5a01a65", size = 10624591, upload-time = "2024-09-29T11:52:54.489Z" }, -] - -[[package]] -name = "pygetwindow" -version = "0.0.9" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyrect" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/e1/70/c7a4f46dbf06048c6d57d9489b8e0f9c4c3d36b7479f03c5ca97eaa2541d/PyGetWindow-0.0.9.tar.gz", hash = "sha256:17894355e7d2b305cd832d717708384017c1698a90ce24f6f7fbf0242dd0a688", size = 9699, upload-time = "2020-10-04T02:12:50.806Z" } - [[package]] name = "pygments" -version = "2.19.2" +version = "2.20.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/b0/77/a5b8c569bf593b0140bde72ea885a803b82086995367bf2037de0159d924/pygments-2.19.2.tar.gz", hash = "sha256:636cb2477cec7f8952536970bc533bc43743542f70392ae026374600add5b887", size = 4968631, upload-time = "2025-06-21T13:39:12.283Z" } +sdist = { url = "https://files.pythonhosted.org/packages/c3/b2/bc9c9196916376152d655522fdcebac55e66de6603a76a02bca1b6414f6c/pygments-2.20.0.tar.gz", hash = "sha256:6757cd03768053ff99f3039c1a36d6c0aa0b263438fcab17520b30a303a82b5f", size = 4955991, upload-time = "2026-03-29T13:29:33.898Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c7/21/705964c7812476f378728bdf590ca4b771ec72385c533964653c68e86bdc/pygments-2.19.2-py3-none-any.whl", hash = "sha256:86540386c03d588bb81d44bc3928634ff26449851e99741617ecb9037ee5ec0b", size = 1225217, upload-time = "2025-06-21T13:39:07.939Z" }, + { url = "https://files.pythonhosted.org/packages/f4/7e/a72dd26f3b0f4f2bf1dd8923c85f7ceb43172af56d63c7383eb62b332364/pygments-2.20.0-py3-none-any.whl", hash = "sha256:81a9e26dd42fd28a23a2d169d86d7ac03b46e2f8b59ed4698fb4785f946d0176", size = 1231151, upload-time = "2026-03-29T13:29:30.038Z" }, ] [[package]] name = "pyjwt" -version = "2.10.1" +version = "2.13.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/e7/46/bd74733ff231675599650d3e47f361794b22ef3e3770998dda30d3b63726/pyjwt-2.10.1.tar.gz", hash = "sha256:3cc5772eb20009233caf06e9d8a0577824723b44e6648ee0a2aedb6cf9381953", size = 87785, upload-time = "2024-11-28T03:43:29.933Z" } +sdist = { url = "https://files.pythonhosted.org/packages/3b/81/58d0ac84e1ef3a3843791d6954d94c0b33d526c75eeb1efbce9d0a4c4077/pyjwt-2.13.0.tar.gz", hash = "sha256:41571c89ca91598c79e8ef18a2d07367d4810fbbd6f637794879baf1b7703423", size = 107515, upload-time = "2026-05-21T19:54:36.618Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/61/ad/689f02752eeec26aed679477e80e632ef1b682313be70793d798c1d5fc8f/PyJWT-2.10.1-py3-none-any.whl", hash = "sha256:dcdd193e30abefd5debf142f9adfcdd2b58004e644f25406ffaebd50bd98dacb", size = 22997, upload-time = "2024-11-28T03:43:27.893Z" }, + { url = "https://files.pythonhosted.org/packages/a3/5e/ecf12fdb62546d64385c158514e9b2b671f7832108ef2ecd2020ce0af2d1/pyjwt-2.13.0-py3-none-any.whl", hash = "sha256:66adcc2aff09b3f1bbd95fc1e1577df8ac8723c978552fd43304c8a290ac5728", size = 31274, upload-time = "2026-05-21T19:54:35.362Z" }, ] [package.optional-dependencies] @@ -1799,2494 +965,30 @@ crypto = [ ] [[package]] -name = "pylibsrtp" -version = "0.12.0" +name = "pymdown-extensions" +version = "11.0.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "cffi" }, + { name = "markdown" }, + { name = "pyyaml" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/54/c8/a59e61f5dd655f5f21033bd643dd31fe980a537ed6f373cdfb49d3a3bd32/pylibsrtp-0.12.0.tar.gz", hash = "sha256:f5c3c0fb6954e7bb74dc7e6398352740ca67327e6759a199fe852dbc7b84b8ac", size = 10878, upload-time = "2025-04-06T12:35:51.804Z" } +sdist = { url = "https://files.pythonhosted.org/packages/21/a9/5f0c535ba3b08fe09270c16808e053a968868242ecbd5676d4e3a488bf28/pymdown_extensions-11.0.1.tar.gz", hash = "sha256:dd2905ae6fc5b75582fafb139a1266ffc754705efa902aa50067fa7ff4f94ec0", size = 857113, upload-time = "2026-07-02T17:59:22.955Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/65/f0/b818395c4cae2d5cc5a0c78fc47d694eae78e6a0d678baeb52a381a26327/pylibsrtp-0.12.0-cp39-abi3-macosx_10_9_x86_64.whl", hash = "sha256:5adde3cf9a5feef561d0eb7ed99dedb30b9bf1ce9a0c1770b2bf19fd0b98bc9a", size = 1727918, upload-time = "2025-04-06T12:35:36.456Z" }, - { url = "https://files.pythonhosted.org/packages/05/1a/ee553abe4431b7bd9bab18f078c0ad2298b94ea55e664da6ecb8700b1052/pylibsrtp-0.12.0-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:d2c81d152606721331ece87c80ed17159ba6da55c7c61a6b750cff67ab7f63a5", size = 2057900, upload-time = "2025-04-06T12:35:38.253Z" }, - { url = "https://files.pythonhosted.org/packages/7f/a2/2dd0188be58d3cba48c5eb4b3c787e5743c111cd0c9289de4b6f2798382a/pylibsrtp-0.12.0-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:242fa3d44219846bf1734d5df595563a2c8fbb0fb00ccc79ab0f569fc0af2c1b", size = 2567047, upload-time = "2025-04-06T12:35:39.797Z" }, - { url = "https://files.pythonhosted.org/packages/6c/3a/4bdab9fc1d78f2efa02c8a8f3e9c187bfa278e89481b5123f07c8dd69310/pylibsrtp-0.12.0-cp39-abi3-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b74aaf8fac1b119a3c762f54751c3d20e77227b84c26d85aae57c2c43129b49c", size = 2168775, upload-time = "2025-04-06T12:35:41.422Z" }, - { url = "https://files.pythonhosted.org/packages/d0/fc/0b1e1bfed420d79427d50aff84c370dcd78d81af9500c1e86fbcc5bf95e1/pylibsrtp-0.12.0-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:33e3e223102989b71f07e1deeb804170ed53fb4e1b283762eb031bd45bb425d4", size = 2225033, upload-time = "2025-04-06T12:35:43.03Z" }, - { url = "https://files.pythonhosted.org/packages/39/7b/e1021d27900315c2c077ec7d45f50274cedbdde067ff679d44df06f01a8a/pylibsrtp-0.12.0-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:36d07de64dbc82dbbb99fd77f36c8e23d6730bdbcccf09701945690a9a9a422a", size = 2606093, upload-time = "2025-04-06T12:35:44.587Z" }, - { url = "https://files.pythonhosted.org/packages/eb/c2/0fae6687a06fcde210a778148ec808af49e431c36fe9908503a695c35479/pylibsrtp-0.12.0-cp39-abi3-musllinux_1_2_i686.whl", hash = "sha256:ef03b4578577690f716fd023daed8914eee6de9a764fa128eda19a0e645cc032", size = 2193213, upload-time = "2025-04-06T12:35:46.167Z" }, - { url = "https://files.pythonhosted.org/packages/67/c2/2ed7a4a5c38b999fd34298f76b93d29f5ba8c06f85cfad3efd9468343715/pylibsrtp-0.12.0-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:0a8421e9fe4d20ce48d439430e55149f12b1bca1b0436741972c362c49948c0a", size = 2256774, upload-time = "2025-04-06T12:35:47.704Z" }, - { url = "https://files.pythonhosted.org/packages/48/d7/f13fedce3b21d24f6f154d1dee7287464a34728dcb3b0c50f687dbad5765/pylibsrtp-0.12.0-cp39-abi3-win32.whl", hash = "sha256:cbc9bfbfb2597e993a1aa16b832ba16a9dd4647f70815421bb78484f8b50b924", size = 1156186, upload-time = "2025-04-06T12:35:48.78Z" }, - { url = "https://files.pythonhosted.org/packages/9b/26/3a20b638a3a3995368f856eeb10701dd6c0e9ace9fb6665eeb1b95ccce19/pylibsrtp-0.12.0-cp39-abi3-win_amd64.whl", hash = "sha256:061ef1dbb5f08079ac6d7515b7e67ca48a3163e16e5b820beea6b01cb31d7e54", size = 1485072, upload-time = "2025-04-06T12:35:50.312Z" }, -] - -[[package]] -name = "pymonctl" -version = "0.92" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "ewmhlib", marker = "sys_platform == 'linux'" }, - { name = "pyobjc", marker = "sys_platform == 'darwin'" }, - { name = "python-xlib", marker = "sys_platform == 'linux'" }, - { name = "pywin32", marker = "sys_platform == 'win32'" }, - { name = "typing-extensions" }, -] -wheels = [ - { url = "https://files.pythonhosted.org/packages/2d/13/076a20da28b82be281f7e43e16d9da0f545090f5d14b2125699232b9feba/PyMonCtl-0.92-py3-none-any.whl", hash = "sha256:2495d8dab78f9a7dbce37e74543e60b8bd404a35c3108935697dda7768611b5a", size = 45945, upload-time = "2024-04-22T10:07:09.566Z" }, -] - -[[package]] -name = "pymsgbox" -version = "1.0.9" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/7d/ff/4c6f31a4f08979f12a663f2aeb6c8b765d3bd592e66eaaac445f547bb875/PyMsgBox-1.0.9.tar.gz", hash = "sha256:2194227de8bff7a3d6da541848705a155dcbb2a06ee120d9f280a1d7f51263ff", size = 18829, upload-time = "2020-10-11T01:51:43.227Z" } - -[[package]] -name = "pyobjc" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-accessibility", marker = "platform_release >= '20.0'" }, - { name = "pyobjc-framework-accounts", marker = "platform_release >= '12.0'" }, - { name = "pyobjc-framework-addressbook" }, - { name = "pyobjc-framework-adservices", marker = "platform_release >= '20.0'" }, - { name = "pyobjc-framework-adsupport", marker = "platform_release >= '18.0'" }, - { name = "pyobjc-framework-applescriptkit" }, - { name = "pyobjc-framework-applescriptobjc", marker = "platform_release >= '10.0'" }, - { name = "pyobjc-framework-applicationservices" }, - { name = "pyobjc-framework-apptrackingtransparency", marker = "platform_release >= '20.0'" }, - { name = "pyobjc-framework-audiovideobridging", marker = "platform_release >= '12.0'" }, - { name = "pyobjc-framework-authenticationservices", marker = "platform_release >= '19.0'" }, - { name = "pyobjc-framework-automaticassessmentconfiguration", marker = "platform_release >= '19.0'" }, - { name = "pyobjc-framework-automator" }, - { name = "pyobjc-framework-avfoundation", marker = "platform_release >= '11.0'" }, - { name = "pyobjc-framework-avkit", marker = "platform_release >= '13.0'" }, - { name = "pyobjc-framework-avrouting", marker = "platform_release >= '22.0'" }, - { name = "pyobjc-framework-backgroundassets", marker = "platform_release >= '22.0'" }, - { name = "pyobjc-framework-browserenginekit", marker = "platform_release >= '23.4'" }, - { name = "pyobjc-framework-businesschat", marker = "platform_release >= '18.0'" }, - { name = "pyobjc-framework-calendarstore", marker = "platform_release >= '9.0'" }, - { name = "pyobjc-framework-callkit", marker = "platform_release >= '20.0'" }, - { name = "pyobjc-framework-carbon" }, - { name = "pyobjc-framework-cfnetwork" }, - { name = "pyobjc-framework-cinematic", marker = "platform_release >= '23.0'" }, - { name = "pyobjc-framework-classkit", marker = "platform_release >= '20.0'" }, - { name = "pyobjc-framework-cloudkit", marker = "platform_release >= '14.0'" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-collaboration", marker = "platform_release >= '9.0'" }, - { name = "pyobjc-framework-colorsync", marker = "platform_release >= '17.0'" }, - { name = "pyobjc-framework-contacts", marker = "platform_release >= '15.0'" }, - { name = "pyobjc-framework-contactsui", marker = "platform_release >= '15.0'" }, - { name = "pyobjc-framework-coreaudio" }, - { name = "pyobjc-framework-coreaudiokit" }, - { name = "pyobjc-framework-corebluetooth", marker = "platform_release >= '14.0'" }, - { name = "pyobjc-framework-coredata" }, - { name = "pyobjc-framework-corehaptics", marker = "platform_release >= '19.0'" }, - { name = "pyobjc-framework-corelocation", marker = "platform_release >= '10.0'" }, - { name = "pyobjc-framework-coremedia", marker = "platform_release >= '11.0'" }, - { name = "pyobjc-framework-coremediaio", marker = "platform_release >= '11.0'" }, - { name = "pyobjc-framework-coremidi" }, - { name = "pyobjc-framework-coreml", marker = "platform_release >= '17.0'" }, - { name = "pyobjc-framework-coremotion", marker = "platform_release >= '19.0'" }, - { name = "pyobjc-framework-coreservices" }, - { name = "pyobjc-framework-corespotlight", marker = "platform_release >= '17.0'" }, - { name = "pyobjc-framework-coretext" }, - { name = "pyobjc-framework-corewlan", marker = "platform_release >= '10.0'" }, - { name = "pyobjc-framework-cryptotokenkit", marker = "platform_release >= '14.0'" }, - { name = "pyobjc-framework-datadetection", marker = "platform_release >= '21.0'" }, - { name = "pyobjc-framework-devicecheck", marker = "platform_release >= '19.0'" }, - { name = "pyobjc-framework-devicediscoveryextension", marker = "platform_release >= '24.0'" }, - { name = "pyobjc-framework-dictionaryservices", marker = "platform_release >= '9.0'" }, - { name = "pyobjc-framework-discrecording" }, - { name = "pyobjc-framework-discrecordingui" }, - { name = "pyobjc-framework-diskarbitration" }, - { name = "pyobjc-framework-dvdplayback" }, - { name = "pyobjc-framework-eventkit", marker = "platform_release >= '12.0'" }, - { name = "pyobjc-framework-exceptionhandling" }, - { name = "pyobjc-framework-executionpolicy", marker = "platform_release >= '19.0'" }, - { name = "pyobjc-framework-extensionkit", marker = "platform_release >= '22.0'" }, - { name = "pyobjc-framework-externalaccessory", marker = "platform_release >= '17.0'" }, - { name = "pyobjc-framework-fileprovider", marker = "platform_release >= '19.0'" }, - { name = "pyobjc-framework-fileproviderui", marker = "platform_release >= '19.0'" }, - { name = "pyobjc-framework-findersync", marker = "platform_release >= '14.0'" }, - { name = "pyobjc-framework-fsevents", marker = "platform_release >= '9.0'" }, - { name = "pyobjc-framework-fskit", marker = "platform_release >= '24.4'" }, - { name = "pyobjc-framework-gamecenter", marker = "platform_release >= '12.0'" }, - { name = "pyobjc-framework-gamecontroller", marker = "platform_release >= '13.0'" }, - { name = "pyobjc-framework-gamekit", marker = "platform_release >= '12.0'" }, - { name = "pyobjc-framework-gameplaykit", marker = "platform_release >= '15.0'" }, - { name = "pyobjc-framework-healthkit", marker = "platform_release >= '22.0'" }, - { name = "pyobjc-framework-imagecapturecore", marker = "platform_release >= '10.0'" }, - { name = "pyobjc-framework-inputmethodkit", marker = "platform_release >= '9.0'" }, - { name = "pyobjc-framework-installerplugins" }, - { name = "pyobjc-framework-instantmessage", marker = "platform_release >= '9.0'" }, - { name = "pyobjc-framework-intents", marker = "platform_release >= '16.0'" }, - { name = "pyobjc-framework-intentsui", marker = "platform_release >= '21.0'" }, - { name = "pyobjc-framework-iobluetooth" }, - { name = "pyobjc-framework-iobluetoothui" }, - { name = "pyobjc-framework-iosurface", marker = "platform_release >= '10.0'" }, - { name = "pyobjc-framework-ituneslibrary", marker = "platform_release >= '10.0'" }, - { name = "pyobjc-framework-kernelmanagement", marker = "platform_release >= '20.0'" }, - { name = "pyobjc-framework-latentsemanticmapping" }, - { name = "pyobjc-framework-launchservices" }, - { name = "pyobjc-framework-libdispatch", marker = "platform_release >= '12.0'" }, - { name = "pyobjc-framework-libxpc", marker = "platform_release >= '12.0'" }, - { name = "pyobjc-framework-linkpresentation", marker = "platform_release >= '19.0'" }, - { name = "pyobjc-framework-localauthentication", marker = "platform_release >= '14.0'" }, - { name = "pyobjc-framework-localauthenticationembeddedui", marker = "platform_release >= '21.0'" }, - { name = "pyobjc-framework-mailkit", marker = "platform_release >= '21.0'" }, - { name = "pyobjc-framework-mapkit", marker = "platform_release >= '13.0'" }, - { name = "pyobjc-framework-mediaaccessibility", marker = "platform_release >= '13.0'" }, - { name = "pyobjc-framework-mediaextension", marker = "platform_release >= '24.0'" }, - { name = "pyobjc-framework-medialibrary", marker = "platform_release >= '13.0'" }, - { name = "pyobjc-framework-mediaplayer", marker = "platform_release >= '16.0'" }, - { name = "pyobjc-framework-mediatoolbox", marker = "platform_release >= '13.0'" }, - { name = "pyobjc-framework-metal", marker = "platform_release >= '15.0'" }, - { name = "pyobjc-framework-metalfx", marker = "platform_release >= '22.0'" }, - { name = "pyobjc-framework-metalkit", marker = "platform_release >= '15.0'" }, - { name = "pyobjc-framework-metalperformanceshaders", marker = "platform_release >= '17.0'" }, - { name = "pyobjc-framework-metalperformanceshadersgraph", marker = "platform_release >= '20.0'" }, - { name = "pyobjc-framework-metrickit", marker = "platform_release >= '21.0'" }, - { name = "pyobjc-framework-mlcompute", marker = "platform_release >= '20.0'" }, - { name = "pyobjc-framework-modelio", marker = "platform_release >= '15.0'" }, - { name = "pyobjc-framework-multipeerconnectivity", marker = "platform_release >= '14.0'" }, - { name = "pyobjc-framework-naturallanguage", marker = "platform_release >= '18.0'" }, - { name = "pyobjc-framework-netfs", marker = "platform_release >= '10.0'" }, - { name = "pyobjc-framework-network", marker = "platform_release >= '18.0'" }, - { name = "pyobjc-framework-networkextension", marker = "platform_release >= '15.0'" }, - { name = "pyobjc-framework-notificationcenter", marker = "platform_release >= '14.0'" }, - { name = "pyobjc-framework-opendirectory", marker = "platform_release >= '10.0'" }, - { name = "pyobjc-framework-osakit" }, - { name = "pyobjc-framework-oslog", marker = "platform_release >= '19.0'" }, - { name = "pyobjc-framework-passkit", marker = "platform_release >= '20.0'" }, - { name = "pyobjc-framework-pencilkit", marker = "platform_release >= '19.0'" }, - { name = "pyobjc-framework-phase", marker = "platform_release >= '21.0'" }, - { name = "pyobjc-framework-photos", marker = "platform_release >= '15.0'" }, - { name = "pyobjc-framework-photosui", marker = "platform_release >= '15.0'" }, - { name = "pyobjc-framework-preferencepanes" }, - { name = "pyobjc-framework-pushkit", marker = "platform_release >= '19.0'" }, - { name = "pyobjc-framework-quartz" }, - { name = "pyobjc-framework-quicklookthumbnailing", marker = "platform_release >= '19.0'" }, - { name = "pyobjc-framework-replaykit", marker = "platform_release >= '20.0'" }, - { name = "pyobjc-framework-safariservices", marker = "platform_release >= '16.0'" }, - { name = "pyobjc-framework-safetykit", marker = "platform_release >= '22.0'" }, - { name = "pyobjc-framework-scenekit", marker = "platform_release >= '11.0'" }, - { name = "pyobjc-framework-screencapturekit", marker = "platform_release >= '21.4'" }, - { name = "pyobjc-framework-screensaver" }, - { name = "pyobjc-framework-screentime", marker = "platform_release >= '20.0'" }, - { name = "pyobjc-framework-scriptingbridge", marker = "platform_release >= '9.0'" }, - { name = "pyobjc-framework-searchkit" }, - { name = "pyobjc-framework-security" }, - { name = "pyobjc-framework-securityfoundation" }, - { name = "pyobjc-framework-securityinterface" }, - { name = "pyobjc-framework-securityui", marker = "platform_release >= '24.4'" }, - { name = "pyobjc-framework-sensitivecontentanalysis", marker = "platform_release >= '23.0'" }, - { name = "pyobjc-framework-servicemanagement", marker = "platform_release >= '10.0'" }, - { name = "pyobjc-framework-sharedwithyou", marker = "platform_release >= '22.0'" }, - { name = "pyobjc-framework-sharedwithyoucore", marker = "platform_release >= '22.0'" }, - { name = "pyobjc-framework-shazamkit", marker = "platform_release >= '21.0'" }, - { name = "pyobjc-framework-social", marker = "platform_release >= '12.0'" }, - { name = "pyobjc-framework-soundanalysis", marker = "platform_release >= '19.0'" }, - { name = "pyobjc-framework-speech", marker = "platform_release >= '19.0'" }, - { name = "pyobjc-framework-spritekit", marker = "platform_release >= '13.0'" }, - { name = "pyobjc-framework-storekit", marker = "platform_release >= '11.0'" }, - { name = "pyobjc-framework-symbols", marker = "platform_release >= '23.0'" }, - { name = "pyobjc-framework-syncservices" }, - { name = "pyobjc-framework-systemconfiguration" }, - { name = "pyobjc-framework-systemextensions", marker = "platform_release >= '19.0'" }, - { name = "pyobjc-framework-threadnetwork", marker = "platform_release >= '22.0'" }, - { name = "pyobjc-framework-uniformtypeidentifiers", marker = "platform_release >= '20.0'" }, - { name = "pyobjc-framework-usernotifications", marker = "platform_release >= '18.0'" }, - { name = "pyobjc-framework-usernotificationsui", marker = "platform_release >= '20.0'" }, - { name = "pyobjc-framework-videosubscriberaccount", marker = "platform_release >= '18.0'" }, - { name = "pyobjc-framework-videotoolbox", marker = "platform_release >= '12.0'" }, - { name = "pyobjc-framework-virtualization", marker = "platform_release >= '20.0'" }, - { name = "pyobjc-framework-vision", marker = "platform_release >= '17.0'" }, - { name = "pyobjc-framework-webkit" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/db/5e/16bc372806790d295c76b5c7851767cc9ee3787b3e581f5d7cc44158e4e0/pyobjc-11.1.tar.gz", hash = "sha256:a71b14389657811d658526ba4d5faba4ef7eadbddcf9fe8bf4fb3a6261effba3", size = 11161, upload-time = "2025-06-14T20:56:32.819Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/a9/32/ad08b45fc0ad9850054ffe66fb0cb2ff7af3d2007c192dda14cf9a3ea893/pyobjc-11.1-py3-none-any.whl", hash = "sha256:903f822cba40be53d408b8eaf834514937ec0b4e6af1c5ecc24fcb652812dd85", size = 4164, upload-time = "2025-06-14T20:44:42.659Z" }, -] - -[[package]] -name = "pyobjc-core" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/e8/e9/0b85c81e2b441267bca707b5d89f56c2f02578ef8f3eafddf0e0c0b8848c/pyobjc_core-11.1.tar.gz", hash = "sha256:b63d4d90c5df7e762f34739b39cc55bc63dbcf9fb2fb3f2671e528488c7a87fe", size = 974602, upload-time = "2025-06-14T20:56:34.189Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/5a/a7/55afc166d89e3fcd87966f48f8bca3305a3a2d7c62100715b9ffa7153a90/pyobjc_core-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:ec36680b5c14e2f73d432b03ba7c1457dc6ca70fa59fd7daea1073f2b4157d33", size = 671075, upload-time = "2025-06-14T20:44:46.594Z" }, - { url = "https://files.pythonhosted.org/packages/c0/09/e83228e878e73bf756749939f906a872da54488f18d75658afa7f1abbab1/pyobjc_core-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:765b97dea6b87ec4612b3212258024d8496ea23517c95a1c5f0735f96b7fd529", size = 677985, upload-time = "2025-06-14T20:44:48.375Z" }, -] - -[[package]] -name = "pyobjc-framework-accessibility" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-quartz" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/78/b4/10c16e9d48568a68da2f61866b19468d4ac7129c377d4b1333ee936ae5d0/pyobjc_framework_accessibility-11.1.tar.gz", hash = "sha256:c0fa5f1e00906ec002f582c7d3d80463a46d19f672bf5ec51144f819eeb40656", size = 45098, upload-time = "2025-06-14T20:56:35.287Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/ff/c5/8803e4f9c3f2d3f5672097438e305be9ccfb87ad092c68cbf02b172bf1d2/pyobjc_framework_accessibility-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:332263153d829b946b311ddc8b9a4402b52d40a572b44c69c3242451ced1b008", size = 11135, upload-time = "2025-06-14T20:44:58.339Z" }, - { url = "https://files.pythonhosted.org/packages/5d/bd/087d511e0ea356434399609a38e8819978943cbeaca3ca7cc5f35c93d0b2/pyobjc_framework_accessibility-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:a049b63b32514da68aaaeef0d6c00a125e0618e4042aa6dbe3867b74fb2a8b2b", size = 11158, upload-time = "2025-06-14T20:44:59.032Z" }, -] - -[[package]] -name = "pyobjc-framework-accounts" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/12/45/ca21003f68ad0f13b5a9ac1761862ad2ddd83224b4314a2f7d03ca437c8d/pyobjc_framework_accounts-11.1.tar.gz", hash = "sha256:384fec156e13ff75253bb094339013f4013464f6dfd47e2f7de3e2ae7441c030", size = 17086, upload-time = "2025-06-14T20:56:36.035Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/6d/db/fa1c4a964fb9f390af8fce1d82c053f9d4467ffe6acdaab464bb3220e673/pyobjc_framework_accounts-11.1-py2.py3-none-any.whl", hash = "sha256:9c3fe342be7b8e73cba735e5a38affbe349cf8bc19091aa4fd788eabf2074b72", size = 5117, upload-time = "2025-06-14T20:45:04.696Z" }, -] - -[[package]] -name = "pyobjc-framework-addressbook" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/eb/d3/f5bb5c72be5c6e52224f43e23e5a44e86d2c35ee9af36939e5514c6c7a0f/pyobjc_framework_addressbook-11.1.tar.gz", hash = "sha256:ce2db3be4a3128bf79d5c41319a6d16b73754785ce75ac694d0d658c690922fc", size = 97609, upload-time = "2025-06-14T20:56:37.324Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/8f/46/27ade210b0bcf2903540c37e96f5e88ec5303e98dc12b255148f12ef9c04/pyobjc_framework_addressbook-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:d1d69330b5a87a29d26feea95dcf40681fd00ba3b40ac89579072ce536b6b647", size = 13156, upload-time = "2025-06-14T20:45:06.788Z" }, - { url = "https://files.pythonhosted.org/packages/c2/de/e1ba5f113c05b543a097040add795fa4b85fdd5ad850b56d83cd6ce8afff/pyobjc_framework_addressbook-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:fb3d0a710f8342a0c63a8e4caf64a044b4d7e42d6d242c8e1b54470238b938cb", size = 13173, upload-time = "2025-06-14T20:45:07.755Z" }, -] - -[[package]] -name = "pyobjc-framework-adservices" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/2a/3f/af76eab6eee0a405a4fdee172e7181773040158476966ecd757b0a98bfc5/pyobjc_framework_adservices-11.1.tar.gz", hash = "sha256:44c72f8163705c9aa41baca938fdb17dde257639e5797e6a5c3a2b2d8afdade9", size = 12473, upload-time = "2025-06-14T20:56:38.147Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/8e/11/a63a171ce86c25a6ae85ebff6a9ab92b0d0cb1fd66ddc7d7b0d803f36191/pyobjc_framework_adservices-11.1-py2.py3-none-any.whl", hash = "sha256:1744f59a75b2375e139c39f3e85658e62cd10cc0f12b158a80421f18734e9ffc", size = 3474, upload-time = "2025-06-14T20:45:13.263Z" }, -] - -[[package]] -name = "pyobjc-framework-adsupport" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/7f/03/9c51edd964796a97def4e1433d76a128dd7059b685fb4366081bf4e292ba/pyobjc_framework_adsupport-11.1.tar.gz", hash = "sha256:78b9667c275785df96219d205bd4309731869c3298d0931e32aed83bede29096", size = 12556, upload-time = "2025-06-14T20:56:38.741Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/7d/b8/ad895efb24311cab2b9d6f7f7f6a833b7f354f80fec606e6c7893da9349b/pyobjc_framework_adsupport-11.1-py2.py3-none-any.whl", hash = "sha256:c3e009612778948910d3a7135b9d77b9b7c06aab29d40957770834c083acf825", size = 3387, upload-time = "2025-06-14T20:45:14.394Z" }, -] - -[[package]] -name = "pyobjc-framework-applescriptkit" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/bc/63/1bcfcdca53bf5bba3a7b4d73d24232ae1721a378a32fd4ebc34a35549df2/pyobjc_framework_applescriptkit-11.1.tar.gz", hash = "sha256:477707352eaa6cc4a5f8c593759dc3227a19d5958481b1482f0d59394a4601c3", size = 12392, upload-time = "2025-06-14T20:56:39.331Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/c6/0e/68ac4ce71e613697a087c262aefacc9ed54eaf0cf1d9ffcd89134bfdab9b/pyobjc_framework_applescriptkit-11.1-py2.py3-none-any.whl", hash = "sha256:e22cbc9d1a25a4a713f21aa94dd017c311186b02062fc7ffbde3009495fb0067", size = 4334, upload-time = "2025-06-14T20:45:15.205Z" }, -] - -[[package]] -name = "pyobjc-framework-applescriptobjc" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/a3/27/687b55b575367df045879b786f358355e40e41f847968e557d0718a6c4a4/pyobjc_framework_applescriptobjc-11.1.tar.gz", hash = "sha256:c8a0ec975b64411a4f16a1280c5ea8dbe949fd361e723edd343102f0f95aba6e", size = 12445, upload-time = "2025-06-14T20:56:39.976Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/2d/33/ceb6a512b41fbf3458b9a281997ebb3056cc354981215261f0a2bf7d15d6/pyobjc_framework_applescriptobjc-11.1-py2.py3-none-any.whl", hash = "sha256:ac22526fd1f0a3b07ac1d77f90046b77f10ec9549182114f2428ee1e96d3de2b", size = 4433, upload-time = "2025-06-14T20:45:16.061Z" }, -] - -[[package]] -name = "pyobjc-framework-applicationservices" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-coretext" }, - { name = "pyobjc-framework-quartz" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/be/3f/b33ce0cecc3a42f6c289dcbf9ff698b0d9e85f5796db2e9cb5dadccffbb9/pyobjc_framework_applicationservices-11.1.tar.gz", hash = "sha256:03fcd8c0c600db98fa8b85eb7b3bc31491701720c795e3f762b54e865138bbaf", size = 224842, upload-time = "2025-06-14T20:56:40.648Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/39/2d/9fde6de0b2a95fbb3d77ba11b3cc4f289dd208f38cb3a28389add87c0f44/pyobjc_framework_applicationservices-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:cf45d15eddae36dec2330a9992fc852476b61c8f529874b9ec2805c768a75482", size = 30991, upload-time = "2025-06-14T20:45:18.169Z" }, - { url = "https://files.pythonhosted.org/packages/38/ec/46a5c710e2d7edf55105223c34fed5a7b7cc7aba7d00a3a7b0405d6a2d1a/pyobjc_framework_applicationservices-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:f4a85ccd78bab84f7f05ac65ff9be117839dfc09d48c39edd65c617ed73eb01c", size = 31056, upload-time = "2025-06-14T20:45:18.925Z" }, -] - -[[package]] -name = "pyobjc-framework-apptrackingtransparency" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/49/68/7aa3afffd038dd6e5af764336bca734eb910121013ca71030457b61e5b99/pyobjc_framework_apptrackingtransparency-11.1.tar.gz", hash = "sha256:796cc5f83346c10973806cfb535d4200b894a5d2626ff2eeb1972d594d14fed4", size = 13135, upload-time = "2025-06-14T20:56:41.494Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/21/37/22cc0293c911a98a49c5fc007b968d82797101dd06e89c4c3266564ff443/pyobjc_framework_apptrackingtransparency-11.1-py2.py3-none-any.whl", hash = "sha256:e25c3eae25d24ee8b523b7ecc4d2b07af37c7733444b80c4964071dea7b0cb19", size = 3862, upload-time = "2025-06-14T20:45:23.851Z" }, -] - -[[package]] -name = "pyobjc-framework-audiovideobridging" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/c3/25/6c5a7b1443d30139cc722029880284ea9dfa575f0436471b9364fcd499f5/pyobjc_framework_audiovideobridging-11.1.tar.gz", hash = "sha256:12756b3aa35083b8ad5c9139b6a0e2f4792e217096b5bf6b702d499038203991", size = 72913, upload-time = "2025-06-14T20:56:42.128Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/3f/d0/952ccd59944f98f10f39c061ef7c3dceecbcd2654910e763c0ad2fd1c910/pyobjc_framework_audiovideobridging-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:db570433910d1df49cc45d25f7a966227033c794fb41133d59212689b86b1ac6", size = 11021, upload-time = "2025-06-14T20:45:25.498Z" }, - { url = "https://files.pythonhosted.org/packages/1d/69/3e8e3da4db835168d18155a2c90fcca441047fc9c2e021d2ea01b4c6eb8c/pyobjc_framework_audiovideobridging-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:591e80ff6973ea51a12f7c1a2e3fd59496633a51d5a1bf73f4fb989a43e23681", size = 11032, upload-time = "2025-06-14T20:45:26.196Z" }, -] - -[[package]] -name = "pyobjc-framework-authenticationservices" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/8f/b7/3e9ad0ed3625dc02e495615ea5dbf55ca95cbd25b3e31f25092f5caad640/pyobjc_framework_authenticationservices-11.1.tar.gz", hash = "sha256:8fd801cdb53d426b4e678b0a8529c005d0c44f5a17ccd7052a7c3a1a87caed6a", size = 115266, upload-time = "2025-06-14T20:56:42.889Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/31/99/0a9d2b9c1aa3b9713d322ddb90a59537013afdae5661af233409e7a24dc9/pyobjc_framework_authenticationservices-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:3987b7fc9493c2ba77b773df99f6631bff1ee9b957d99e34afa6b4e1c9d48bfb", size = 20280, upload-time = "2025-06-14T20:45:32.617Z" }, - { url = "https://files.pythonhosted.org/packages/7e/2d/cbb5e88c3713fb68cda7d76d37737076c1653bf1ac95418c30d4b614f4be/pyobjc_framework_authenticationservices-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:6655dd53d9135ef85265a4297da5e7459ed7836973f2796027fdfbfd7f08e433", size = 20385, upload-time = "2025-06-14T20:45:33.359Z" }, -] - -[[package]] -name = "pyobjc-framework-automaticassessmentconfiguration" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/3d/39/d4c94e0245d290b83919854c4f205851cc0b2603f843448fdfb8e74aad71/pyobjc_framework_automaticassessmentconfiguration-11.1.tar.gz", hash = "sha256:70eadbf8600101901a56fcd7014d8941604e14f3b3728bc4fb0178a9a9420032", size = 24933, upload-time = "2025-06-14T20:56:43.984Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b0/ca/f4ee1c9c274e0a41f8885f842fc78e520a367437edf9ca86eca46709e62d/pyobjc_framework_automaticassessmentconfiguration-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:50cc5466bec1f58f79921d49544b525b56897cb985dfcfabf825ee231c27bcfc", size = 9167, upload-time = "2025-06-14T20:45:39.52Z" }, - { url = "https://files.pythonhosted.org/packages/5e/e0/5a67f8ee0393447ca8251cbd06788cb7f3a1f4b9b052afd2e1b2cdfcb504/pyobjc_framework_automaticassessmentconfiguration-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:55d1684dd676730fb1afbc7c67e0669e3a7159f18c126fea7453fe6182c098f9", size = 9193, upload-time = "2025-06-14T20:45:40.52Z" }, -] - -[[package]] -name = "pyobjc-framework-automator" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/63/9f/097ed9f4de9e9491a1b08bb7d85d35a95d726c9e9f5f5bf203b359a436b6/pyobjc_framework_automator-11.1.tar.gz", hash = "sha256:9b46c55a4f9ae2b3c39ff560f42ced66bdd18c093188f0b5fc4060ad911838e4", size = 201439, upload-time = "2025-06-14T20:56:44.767Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/f0/c0/ebcc5a041440625ca984cde4ff96bc3e2cac4e5a37ca5bf4506ef4a98c54/pyobjc_framework_automator-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:bf675a19edd97de9c19dcfd0fea9af9ebbd3409786c162670d1d71cb2738e341", size = 10004, upload-time = "2025-06-14T20:45:46.111Z" }, - { url = "https://files.pythonhosted.org/packages/0e/1e/3ed1df2168e596151da2329258951dae334e194d7de3b117c7e29a768ffc/pyobjc_framework_automator-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:af5941f8d90167244209b352512b7779e5590d17dc1e703e087a6cfe79ee3d64", size = 10029, upload-time = "2025-06-14T20:45:46.823Z" }, -] - -[[package]] -name = "pyobjc-framework-avfoundation" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-coreaudio" }, - { name = "pyobjc-framework-coremedia" }, - { name = "pyobjc-framework-quartz" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/3c/1f/90cdbce1d3b4861cbb17c12adf57daeec32477eb1df8d3f9ab8551bdadfb/pyobjc_framework_avfoundation-11.1.tar.gz", hash = "sha256:6663056cc6ca49af8de6d36a7fff498f51e1a9a7f1bde7afba718a8ceaaa7377", size = 832178, upload-time = "2025-06-14T20:56:46.329Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/0f/48/31286b2b09a619d8047256d7180e0d511be71ab598e5f54f034977b59bbf/pyobjc_framework_avfoundation-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:8a0ccbdba46b69dec1d12eea52eef56fcd63c492f73e41011bb72508b2aa2d0e", size = 70711, upload-time = "2025-06-14T20:45:52.461Z" }, - { url = "https://files.pythonhosted.org/packages/43/30/d5d03dd4a508bdaa2156ff379e9e109020de23cbb6316c5865d341aa6db1/pyobjc_framework_avfoundation-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:94f065db4e87b1baebb5cf9f464cf9d82c5f903fff192001ebc974d9e3132c7e", size = 70746, upload-time = "2025-06-14T20:45:53.253Z" }, -] - -[[package]] -name = "pyobjc-framework-avkit" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-quartz" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/61/ff/9f41f2b8de786871184b48c4e5052cb7c9fcc204e7fee06687fa32b08bed/pyobjc_framework_avkit-11.1.tar.gz", hash = "sha256:d948204a7b94e0e878b19a909f9b33342e19d9ea519571d66a21fce8f72e3263", size = 46825, upload-time = "2025-06-14T20:56:47.494Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/a4/6c/ee7504367f4a9337d3e78cd34beb9fcb58ad30e274c2a9f1d8058b9837f2/pyobjc_framework_avkit-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:88f70e2a399e43ce7bc3124b3b35d65537daddb358ea542fbb0146fa6406be8a", size = 11517, upload-time = "2025-06-14T20:45:59.676Z" }, - { url = "https://files.pythonhosted.org/packages/b2/2f/6ec6a4ec7eb9ca329f36bbd2a51750fe5064d44dd437d8615abb7121ec93/pyobjc_framework_avkit-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:ef9cd9fe37c6199bfde7ee5cd6e76ede23a6797932882785c53ef3070e209afb", size = 11539, upload-time = "2025-06-14T20:46:00.375Z" }, -] - -[[package]] -name = "pyobjc-framework-avrouting" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/cf/42/94bc18b968a4ee8b6427257f907ffbfc97f8ba6a6202953da149b649d638/pyobjc_framework_avrouting-11.1.tar.gz", hash = "sha256:7db1291d9f53cc58d34b2a826feb721a85f50ceb5e71952e8762baacd3db3fc0", size = 21069, upload-time = "2025-06-14T20:56:48.57Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/54/d4/0d17fd5a761d8a3d7dab0e096315de694b47dd48d2bb9655534e44399385/pyobjc_framework_avrouting-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:45cbabbf69764b2467d78adb8f3b7f209d1a8ee690e19f9a32d05c62a9c3a131", size = 8192, upload-time = "2025-06-14T20:46:05.479Z" }, - { url = "https://files.pythonhosted.org/packages/01/17/ce199bc7fb3ba1f7b0474554bd71d1bdd3d5a141e1d9722ff9f46c104e1d/pyobjc_framework_avrouting-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:dc309e175abf3961f933f8b341c0504b17f4717931242ebb121a83256b8b5c13", size = 8212, upload-time = "2025-06-14T20:46:06.17Z" }, -] - -[[package]] -name = "pyobjc-framework-backgroundassets" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/08/76/21e1632a212f997d7a5f26d53eb997951978916858039b79f43ebe3d10b2/pyobjc_framework_backgroundassets-11.1.tar.gz", hash = "sha256:2e14b50539d96d5fca70c49f21b69fdbad81a22549e3630f5e4f20d5c0204fc2", size = 24803, upload-time = "2025-06-14T20:56:49.566Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/74/ac/b1cb5c0ec2691ea225d53c2b9411d5ea1896f8f72eb5ca92978664443bb0/pyobjc_framework_backgroundassets-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:bd371ce08d1b79f540d5994139898097b83b1d4e4471c264892433d448b24de0", size = 9691, upload-time = "2025-06-14T20:46:12.197Z" }, - { url = "https://files.pythonhosted.org/packages/ad/77/a6ad2df35fd71b3c26f52698d25174899ba1be134766022f5bf804ebf12d/pyobjc_framework_backgroundassets-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:13bf451c59b409b6ce1ac0e717a970a1b03bca7a944a7f19219da0d46ab7c561", size = 9707, upload-time = "2025-06-14T20:46:12.88Z" }, -] - -[[package]] -name = "pyobjc-framework-browserenginekit" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-coreaudio" }, - { name = "pyobjc-framework-coremedia" }, - { name = "pyobjc-framework-quartz" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/30/75/087270d9f81e913b57c7db58eaff8691fa0574b11faf9302340b3b8320f1/pyobjc_framework_browserenginekit-11.1.tar.gz", hash = "sha256:918440cefb10480024f645169de3733e30ede65e41267fa12c7b90c264a0a479", size = 31944, upload-time = "2025-06-14T20:56:50.195Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/ea/29/ec0a0cc6fb15911769cb8e5ad8ada85e3f5cf4889fafbb90d936c6b7053b/pyobjc_framework_browserenginekit-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:29b5f5949170af0235485e79aa465a7af2b2e0913d0c2c9ab1ac033224a90edb", size = 11088, upload-time = "2025-06-14T20:46:18.696Z" }, - { url = "https://files.pythonhosted.org/packages/89/90/a50bb66a5e041ace99b6c8b1df43b38d5f2e1bf771f57409e4aebf1dfae5/pyobjc_framework_browserenginekit-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:9b815b167533015d62832b956e9cfb962bd2026f5a4ccd66718cf3bb2e15ab27", size = 11115, upload-time = "2025-06-14T20:46:19.401Z" }, -] - -[[package]] -name = "pyobjc-framework-businesschat" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/85/be/9d9d9d9383c411a58323ea510d768443287ca21610af652b815b3205ea80/pyobjc_framework_businesschat-11.1.tar.gz", hash = "sha256:69589d2f0cb4e7892e5ecc6aed79b1abd1ec55c099a7faacae6a326bc921259d", size = 12698, upload-time = "2025-06-14T20:56:51.173Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/87/a4/5b8bb268b263678c0908cdaa8bed2534a6caac5862d05236f6c361d130ba/pyobjc_framework_businesschat-11.1-py2.py3-none-any.whl", hash = "sha256:7fdc1219b988ce3ae896bffd01f547c06cec3b4e4b2d0aa04d251444d7f1c2db", size = 3458, upload-time = "2025-06-14T20:46:24.651Z" }, -] - -[[package]] -name = "pyobjc-framework-calendarstore" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/41/df/7ca8ee65b16d5fc862d7e8664289472eed918cf4d76921de6bdaa1461c65/pyobjc_framework_calendarstore-11.1.tar.gz", hash = "sha256:858ee00e6a380d9c086c2d7db82c116a6c406234038e0ec8fc2ad02e385dc437", size = 68215, upload-time = "2025-06-14T20:56:51.799Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/c7/94/69cb863bd88349df0f6cf491fd3ca4d674816c4d66270f9e2620cc6e16ed/pyobjc_framework_calendarstore-11.1-py2.py3-none-any.whl", hash = "sha256:bf066e17392c978becf17a61863eb81727bf593a2bfdab261177126072557e24", size = 5265, upload-time = "2025-06-14T20:46:25.457Z" }, -] - -[[package]] -name = "pyobjc-framework-callkit" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/51/d5/4f0b62ab35be619e8c8d96538a03cf56fde6fd53540e1837e0fa588b3f6c/pyobjc_framework_callkit-11.1.tar.gz", hash = "sha256:b84d5ea38dff0cbe0754f5f9f6f33c742e216f12e7166179a8ec2cf4b0bfca94", size = 46648, upload-time = "2025-06-14T20:56:52.579Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/5a/f8/6e368225634cad9e457c4f8f0580ed318cb2f2c8110f2e56935fc12502f3/pyobjc_framework_callkit-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:1db8b74abd6489d73c8619972730bea87a7d1f55d47649150fc1a30fdc6840fb", size = 11211, upload-time = "2025-06-14T20:46:27.146Z" }, - { url = "https://files.pythonhosted.org/packages/18/2a/209572a6dba6768a57667e1f87a83ce8cadf18de5d6b1a91b95ce548d0f8/pyobjc_framework_callkit-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:554e09ca3dab44d93a89927d9e300f004d2ef0db020b10425a4622b432e7b684", size = 11269, upload-time = "2025-06-14T20:46:28.164Z" }, -] - -[[package]] -name = "pyobjc-framework-carbon" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/39/a4/d751851865d9a78405cfec0c8b2931b1e96b9914e9788cd441fa4e8290d0/pyobjc_framework_carbon-11.1.tar.gz", hash = "sha256:047f098535479efa3ab89da1ebdf3cf9ec0b439a33a4f32806193886e9fcea71", size = 37291, upload-time = "2025-06-14T20:56:53.642Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/84/44/f1a20b5aa3833af4d461074c479263a410ef90d17dbec11f78ad9c34dbab/pyobjc_framework_carbon-11.1-py2.py3-none-any.whl", hash = "sha256:1bf66853e939315ad7ee968170b16dd12cb838c42b80dfcd5354687760998825", size = 4753, upload-time = "2025-06-14T20:46:33.141Z" }, -] - -[[package]] -name = "pyobjc-framework-cfnetwork" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/6f/49/7b24172e3d6eb0ddffc33a7498a2bea264aa2958c3fecaeb463bef88f0b8/pyobjc_framework_cfnetwork-11.1.tar.gz", hash = "sha256:ad600163eeadb7bf71abc51a9b6f2b5462a018d3f9bb1510c5ce3fdf2f22959d", size = 79069, upload-time = "2025-06-14T20:56:54.615Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/e7/61/74b0d0430807615b7f91a688a871ffd94a61d4764a101e2a53e0c95dd05e/pyobjc_framework_cfnetwork-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:d7a24746d0754b3a0042def2cd64aa205e5614f12ea0de9461c8e26d97633c72", size = 18953, upload-time = "2025-06-14T20:46:35.409Z" }, - { url = "https://files.pythonhosted.org/packages/c2/31/05b4fb79e7f738f7f7d7a58734de2fab47d9a1fb219c2180e8c07efe2550/pyobjc_framework_cfnetwork-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:70beb8095df76e0e8eb7ab218be1e69ae180e01a4d77f7cad73c97b4eb7a296a", size = 19141, upload-time = "2025-06-14T20:46:36.134Z" }, -] - -[[package]] -name = "pyobjc-framework-cinematic" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-avfoundation" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-coremedia" }, - { name = "pyobjc-framework-metal" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/57/6f/c2d0b49e01e654496a1781bafb9da72a6fbd00f5abb39dc4a3a0045167c7/pyobjc_framework_cinematic-11.1.tar.gz", hash = "sha256:efde39a6a2379e1738dbc5434b2470cd187cf3114ffb81390b3b1abda470b382", size = 25522, upload-time = "2025-06-14T20:56:55.379Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/05/bd/a9b51c770bd96546a101c9e9994f851b87336f168a77048241517ca4db8c/pyobjc_framework_cinematic-11.1-py2.py3-none-any.whl", hash = "sha256:b62c024c1a9c7890481bc2fdfaf0cd3c251a4a08357d57dc1795d98920fcdbd1", size = 4562, upload-time = "2025-06-14T20:46:40.989Z" }, -] - -[[package]] -name = "pyobjc-framework-classkit" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/7a/8b/5150b4faddd15d5dd795bc62b2256c4f7dafc983cfa694fcf88121ea0016/pyobjc_framework_classkit-11.1.tar.gz", hash = "sha256:ee1e26395eb00b3ed5442e3234cdbfe925d2413185af38eca0477d7166651df4", size = 39831, upload-time = "2025-06-14T20:56:56.036Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/89/86/5b9ef1d5aa3f4835d164c9be46afae634911db56c6ad7795e212ef9bb50b/pyobjc_framework_classkit-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:018da363d06f3615c07a8623cbdb024a31b1f8b96a933ff2656c0e903063842c", size = 8895, upload-time = "2025-06-14T20:46:42.689Z" }, - { url = "https://files.pythonhosted.org/packages/75/79/2552fd5e1da73dffb35589469b3cd8c0928e3100462761350d19ea922e59/pyobjc_framework_classkit-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:161dcb9b718649e6331a5eab5a76c2b43a9b322b15b37b3f8f9c5faad12ee6d1", size = 8911, upload-time = "2025-06-14T20:46:43.714Z" }, -] - -[[package]] -name = "pyobjc-framework-cloudkit" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-accounts" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-coredata" }, - { name = "pyobjc-framework-corelocation" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/58/a6/bfe5be55ed95704efca0e86b218155a9c801735107cedba3af8ea4580a05/pyobjc_framework_cloudkit-11.1.tar.gz", hash = "sha256:40d2dc4bf28c5be9b836b01e4d267a15d847d756c2a65530e1fcd79b2825e86d", size = 122778, upload-time = "2025-06-14T20:56:56.73Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/25/d9/5570a217cef8130708e860b86f4f22bb5827247c97121523a9dfd4784148/pyobjc_framework_cloudkit-11.1-py2.py3-none-any.whl", hash = "sha256:c583e40c710cf85ebe34173d1d2995e832a20127edc8899b2f35b13f98498af1", size = 10870, upload-time = "2025-06-14T20:46:48.781Z" }, -] - -[[package]] -name = "pyobjc-framework-cocoa" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/4b/c5/7a866d24bc026f79239b74d05e2cf3088b03263da66d53d1b4cf5207f5ae/pyobjc_framework_cocoa-11.1.tar.gz", hash = "sha256:87df76b9b73e7ca699a828ff112564b59251bb9bbe72e610e670a4dc9940d038", size = 5565335, upload-time = "2025-06-14T20:56:59.683Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/90/43/6841046aa4e257b6276cd23e53cacedfb842ecaf3386bb360fa9cc319aa1/pyobjc_framework_cocoa-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:7b9a9b8ba07f5bf84866399e3de2aa311ed1c34d5d2788a995bdbe82cc36cfa0", size = 388177, upload-time = "2025-06-14T20:46:51.454Z" }, - { url = "https://files.pythonhosted.org/packages/68/da/41c0f7edc92ead461cced7e67813e27fa17da3c5da428afdb4086c69d7ba/pyobjc_framework_cocoa-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:806de56f06dfba8f301a244cce289d54877c36b4b19818e3b53150eb7c2424d0", size = 388983, upload-time = "2025-06-14T20:46:52.591Z" }, -] - -[[package]] -name = "pyobjc-framework-collaboration" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/66/49/9dbe8407d5dd663747267c1234d1b914bab66e1878d22f57926261a3063b/pyobjc_framework_collaboration-11.1.tar.gz", hash = "sha256:4564e3931bfc51773623d4f57f2431b58a39b75cb964ae5c48d27ee4dde2f4ea", size = 16839, upload-time = "2025-06-14T20:57:01.101Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/62/24/4c9deedcc62d223a45d4b4fa16162729923d2b3e2231467de6ecd079f3f8/pyobjc_framework_collaboration-11.1-py2.py3-none-any.whl", hash = "sha256:3629ea5b56c513fb330d43952afabb2df2a2ac2f9048b8ec6e8ab4486191390a", size = 4891, upload-time = "2025-06-14T20:46:59.734Z" }, -] - -[[package]] -name = "pyobjc-framework-colorsync" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/b5/97/7613b6041f62c52f972e42dd5d79476b56b84d017a8b5e4add4d9cfaca36/pyobjc_framework_colorsync-11.1.tar.gz", hash = "sha256:7a346f71f34b2ccd1b020a34c219b85bf8b6f6e05283d503185aeb7767a269dd", size = 38999, upload-time = "2025-06-14T20:57:01.761Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/30/d5/c8fc7c47cbb9865058094dc9cf3f57879156ff55fb261cf199e7081d1db7/pyobjc_framework_colorsync-11.1-py2.py3-none-any.whl", hash = "sha256:d19d6da2c7175a3896a63c9b40a8ab98ade0779a5b40062789681501c33efd5c", size = 5971, upload-time = "2025-06-14T20:47:00.547Z" }, -] - -[[package]] -name = "pyobjc-framework-contacts" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/a6/85/34868b6447d552adf8674bac226b55c2baacacee0d67ee031e33805d6faa/pyobjc_framework_contacts-11.1.tar.gz", hash = "sha256:752036e7d8952a4122296d7772f274170a5f35a53ee6454a27f3e1d9603222cc", size = 84814, upload-time = "2025-06-14T20:57:02.582Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/68/e1/27715ef476441cb05d4442b93fe6380a57a946cda008f70399cadb4ff1fd/pyobjc_framework_contacts-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:68148653f27c1eaeff2ad4831b5e68393071a382aab773629cd047ce55556726", size = 12067, upload-time = "2025-06-14T20:47:02.178Z" }, - { url = "https://files.pythonhosted.org/packages/30/c8/0d47af11112bf382e059cfe2dd03be98914f0621ddff8858bb9af864f8c5/pyobjc_framework_contacts-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:576ee4aec05d755444bff10b45833f73083b5b3d1b2740e133b92111f7765e54", size = 12141, upload-time = "2025-06-14T20:47:02.884Z" }, -] - -[[package]] -name = "pyobjc-framework-contactsui" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-contacts" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/3f/57/8765b54a30edaa2a56df62e11e7c32e41b6ea300513256adffa191689368/pyobjc_framework_contactsui-11.1.tar.gz", hash = "sha256:5bc29ea2b10a342018e1b96be6b140c10ebe3cfb6417278770feef5e88026a1f", size = 20031, upload-time = "2025-06-14T20:57:03.603Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/38/02/f65f2eb6e2ad91c95e5a6b532fe8dd5cd0c190fbaff71e4a85346e16c0f6/pyobjc_framework_contactsui-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:1c0f03c71e63daf5dbf760bf0e45620618a6f1ea62f8c17e288463c1fd4d2685", size = 7858, upload-time = "2025-06-14T20:47:08.346Z" }, - { url = "https://files.pythonhosted.org/packages/46/b6/50ec09f1bb18c422b8c079e02328689f32e977b43ab7651c05e8274854dc/pyobjc_framework_contactsui-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:c34a6f27ef5aa4742cc44fd5b4d16fe1e1745ff839578b4c059faf2c58eee3ca", size = 7875, upload-time = "2025-06-14T20:47:09.041Z" }, -] - -[[package]] -name = "pyobjc-framework-coreaudio" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/39/c0/4ab6005cf97e534725b0c14b110d4864b367c282b1c5b0d8f42aad74a83f/pyobjc_framework_coreaudio-11.1.tar.gz", hash = "sha256:b7b89540ae7efc6c1e3208ac838ef2acfc4d2c506dd629d91f6b3b3120e55c1b", size = 141032, upload-time = "2025-06-14T20:57:04.348Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/54/1d/81339c1087519a9f125396c717b85a05b49c2c54137bdf4ca01c1ccb6239/pyobjc_framework_coreaudio-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:73a46f0db2fa8ca2e8c47c3ddcc2751e67a0f8600246a6718553b15ee0dbbdb6", size = 35383, upload-time = "2025-06-14T20:47:14.234Z" }, - { url = "https://files.pythonhosted.org/packages/3d/fe/c43521642db98a4ec29fa535781c1316342bb52d5fc709696cbb1e8ca6cd/pyobjc_framework_coreaudio-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:2538d1242dab4e27efb346eafbad50594e7e95597fa7220f0bab2099c825da55", size = 36765, upload-time = "2025-06-14T20:47:15.344Z" }, -] - -[[package]] -name = "pyobjc-framework-coreaudiokit" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-coreaudio" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/f1/4e/c49b26c60047c511727efe994b412276c487dfe90f1ee0fced0bddbdf8a3/pyobjc_framework_coreaudiokit-11.1.tar.gz", hash = "sha256:0b461c3d6123fda4da6b6aaa022efc918c1de2e126a5cf07d2189d63fa54ba40", size = 21955, upload-time = "2025-06-14T20:57:05.218Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/07/44/0de5d26e383d0b00f2f44394db74e0953bc1e35b74072a67fde916e8e31e/pyobjc_framework_coreaudiokit-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:4743fbd210159cffffb0a7b8e06bf8b8527ba4bf01e76806fae2696fd6990e77", size = 7234, upload-time = "2025-06-14T20:47:21.271Z" }, - { url = "https://files.pythonhosted.org/packages/18/27/d8ff6293851a7d9665724fa5c324d28200776ec10a04b850ba21ad1f9be1/pyobjc_framework_coreaudiokit-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:20440a2926b1d91da8efc8bc060e77c7a195cb0443dbf3770eaca9e597276748", size = 7266, upload-time = "2025-06-14T20:47:22.136Z" }, -] - -[[package]] -name = "pyobjc-framework-corebluetooth" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/3d/fe/2081dfd9413b7b4d719935c33762fbed9cce9dc06430f322d1e2c9dbcd91/pyobjc_framework_corebluetooth-11.1.tar.gz", hash = "sha256:1deba46e3fcaf5e1c314f4bbafb77d9fe49ec248c493ad00d8aff2df212d6190", size = 60337, upload-time = "2025-06-14T20:57:05.919Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/8c/75/3318e85b7328c99c752e40592a907fc5c755cddc6d73beacbb432f6aa2d0/pyobjc_framework_corebluetooth-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:433b8593eb1ea8b6262b243ec903e1de4434b768ce103ebe15aac249b890cc2a", size = 13143, upload-time = "2025-06-14T20:47:28.889Z" }, - { url = "https://files.pythonhosted.org/packages/8a/bc/083ea1ae57a31645df7fad59921528f6690995f7b7c84a203399ded7e7fe/pyobjc_framework_corebluetooth-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:36bef95a822c68b72f505cf909913affd61a15b56eeaeafea7302d35a82f4f05", size = 13163, upload-time = "2025-06-14T20:47:29.624Z" }, -] - -[[package]] -name = "pyobjc-framework-coredata" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/00/e3/af497da7a7c895b6ff529d709d855a783f34afcc4b87ab57a1a2afb3f876/pyobjc_framework_coredata-11.1.tar.gz", hash = "sha256:fe9fd985f8e06c70c0fb1e6bbea5b731461f9e76f8f8d8e89c7c72667cdc6adf", size = 260628, upload-time = "2025-06-14T20:57:06.729Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/29/d9/7f12bdba0503d0ef7b1ac26e05429aecc33b4aaf190155a6bec8b576850d/pyobjc_framework_coredata-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:c66ae04cc658eafdfb987f9705e21f9782edee6773a8adb6bfa190500e4e7e29", size = 16428, upload-time = "2025-06-14T20:47:34.981Z" }, - { url = "https://files.pythonhosted.org/packages/5b/ac/77935aa9891bd6be952b1e6780df2bae748971dd0fe0b5155894004840bd/pyobjc_framework_coredata-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:c9b2374784e67694a18fc8c120a12f11b355a20b643c01f23ae2ce87330a75e0", size = 16443, upload-time = "2025-06-14T20:47:35.711Z" }, -] - -[[package]] -name = "pyobjc-framework-corehaptics" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/5f/83/cc997ec4687a68214dd3ad1bdf64353305f5c7e827fad211adac4c28b39f/pyobjc_framework_corehaptics-11.1.tar.gz", hash = "sha256:e5da3a97ed6aca9b7268c8c5196c0a339773a50baa72d1502d3435dc1a2a80f1", size = 42722, upload-time = "2025-06-14T20:57:08.019Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/21/d0/0fb20c0f19beae53c905653ffdcbf32e3b4119420c737ff4733f7ebb3b29/pyobjc_framework_corehaptics-11.1-py2.py3-none-any.whl", hash = "sha256:8f8c47ccca5052d07f95d2f35e6e399c5ac1f2072ba9d9eaae902edf4e3a7af4", size = 5363, upload-time = "2025-06-14T20:47:40.582Z" }, -] - -[[package]] -name = "pyobjc-framework-corelocation" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/95/ef/fbd2e01ec137208af7bfefe222773748d27f16f845b0efa950d65e2bd719/pyobjc_framework_corelocation-11.1.tar.gz", hash = "sha256:46a67b99925ee3d53914331759c6ee110b31bb790b74b05915acfca41074c206", size = 104508, upload-time = "2025-06-14T20:57:08.731Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/f9/f9/8137e8bf86f8e6350298217dcc635fd6577d64b484f9d250ddb85a84efa0/pyobjc_framework_corelocation-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:ea261e7d87c6f62f1b03c252c273ea7fd6f314e3e73c69c6fb3fe807bf183462", size = 12741, upload-time = "2025-06-14T20:47:42.583Z" }, - { url = "https://files.pythonhosted.org/packages/95/cb/282d59421cdb89a5e5fcce72fc37d6eeace98a2a86d71f3be3cd47801298/pyobjc_framework_corelocation-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:562e31124f80207becfd8df01868f73fa5aa70169cc4460e1209fb16916e4fb4", size = 12752, upload-time = "2025-06-14T20:47:43.273Z" }, -] - -[[package]] -name = "pyobjc-framework-coremedia" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/95/5d/81513acd219df77a89176f1574d936b81ad6f6002225cabb64d55efb7e8d/pyobjc_framework_coremedia-11.1.tar.gz", hash = "sha256:82cdc087f61e21b761e677ea618a575d4c0dbe00e98230bf9cea540cff931db3", size = 216389, upload-time = "2025-06-14T20:57:09.546Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/32/48/811ccea77d2c0d8156a489e2900298502eb6648d9c041c7f0c514c8f8a29/pyobjc_framework_coremedia-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:aacf47006e1c6bf6124fb2b5016a8d5fd5cf504b6b488f9eba4e389ab0f0a051", size = 29118, upload-time = "2025-06-14T20:47:48.895Z" }, - { url = "https://files.pythonhosted.org/packages/2c/d1/b3d004d6a2d2188d196779d92fe8cfa2533f5722cd216fbc4f0cffc63b24/pyobjc_framework_coremedia-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:ea5055298af91e463ffa7977d573530f9bada57b8f2968dcc76a75e339b9a598", size = 29015, upload-time = "2025-06-14T20:47:49.655Z" }, -] - -[[package]] -name = "pyobjc-framework-coremediaio" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/64/68/9cef2aefba8e69916049ff43120e8794df8051bdf1f690a55994bbe4eb57/pyobjc_framework_coremediaio-11.1.tar.gz", hash = "sha256:bccd69712578b177144ded398f4695d71a765ef61204da51a21f0c90b4ad4c64", size = 108326, upload-time = "2025-06-14T20:57:10.435Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/aa/38/6bcddd7d57fa19173621aa29b46342756ed1a081103d24e4bdac1cf882fe/pyobjc_framework_coremediaio-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:4438713ee4611d5310f4f2e71e557b6138bc79c0363e3d45ecb8c09227dfa58e", size = 17203, upload-time = "2025-06-14T20:47:55.781Z" }, - { url = "https://files.pythonhosted.org/packages/4b/b5/5dd941c1d7020a78b563a213fb8be7c6c3c1073c488914e158cd5417f4f7/pyobjc_framework_coremediaio-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:39ad2518de9943c474e5ca0037e78f92423c3352deeee6c513a489016dac1266", size = 17250, upload-time = "2025-06-14T20:47:56.505Z" }, -] - -[[package]] -name = "pyobjc-framework-coremidi" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/06/ca/2ae5149966ccd78290444f88fa62022e2b96ed2fddd47e71d9fd249a9f82/pyobjc_framework_coremidi-11.1.tar.gz", hash = "sha256:095030c59d50c23aa53608777102bc88744ff8b10dfb57afe24b428dcd12e376", size = 107817, upload-time = "2025-06-14T20:57:11.245Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/37/fc/db75c55e492e5e34be637da2eeeaadbb579655b6d17159de419237bc9bdf/pyobjc_framework_coremidi-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:5f8c2fdc9d1b7967e2a5ec0d5281eaddc00477bed9753aa14d5b881dc3a9ad8f", size = 24256, upload-time = "2025-06-14T20:48:02.448Z" }, - { url = "https://files.pythonhosted.org/packages/c2/2d/57c279dd74a9073d1416b10b05ebb9598f4868cad010d87f46ef4b517324/pyobjc_framework_coremidi-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:deb9120478a831a898f22f68737fc683bb9b937e77556e78b75986aebd349c55", size = 24277, upload-time = "2025-06-14T20:48:03.184Z" }, -] - -[[package]] -name = "pyobjc-framework-coreml" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/0d/5d/4309f220981d769b1a2f0dcb2c5c104490d31389a8ebea67e5595ce1cb74/pyobjc_framework_coreml-11.1.tar.gz", hash = "sha256:775923eefb9eac2e389c0821b10564372de8057cea89f1ea1cdaf04996c970a7", size = 82005, upload-time = "2025-06-14T20:57:12.004Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/76/9c/2218a8f457f56075a8a3f2490bd9d01c8e69c807139eaa0a6ac570531ca5/pyobjc_framework_coreml-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:b5be7889ad99da1aca040238fd99af9ee87ea8a6628f24d33e2e4890b88dd139", size = 11414, upload-time = "2025-06-14T20:48:09.267Z" }, - { url = "https://files.pythonhosted.org/packages/3e/9e/a1b6d30b4f91c7cc4780e745e1e73a322bd3524a773f66f5eac0b1600d85/pyobjc_framework_coreml-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:c768b03d72488b964d753392e9c587684961d8237b69cca848b3a5a00aea79c9", size = 11436, upload-time = "2025-06-14T20:48:10.048Z" }, -] - -[[package]] -name = "pyobjc-framework-coremotion" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/a5/95/e469dc7100ea6b9c29a074a4f713d78b32a78d7ec5498c25c83a56744fc2/pyobjc_framework_coremotion-11.1.tar.gz", hash = "sha256:5884a568521c0836fac39d46683a4dea3d259a23837920897042ffb922d9ac3e", size = 67050, upload-time = "2025-06-14T20:57:12.705Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/1d/3f/137c983dbccbdbc4a07fb2453e494af938078969bcde9252fbbad0ba939d/pyobjc_framework_coremotion-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:501248a726816e05552d1c1f7e2be2c7305cda792c46905d9aee7079dfad2eea", size = 10353, upload-time = "2025-06-14T20:48:15.365Z" }, - { url = "https://files.pythonhosted.org/packages/e9/17/ffa3cf9fde9df31f3d6ecb38507c61c6d8d81276d0a9116979cafd5a0ab7/pyobjc_framework_coremotion-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:8c3b33228a170bf8495508a8923451ec600435c7bff93d7614f19c913baeafd1", size = 10368, upload-time = "2025-06-14T20:48:16.066Z" }, -] - -[[package]] -name = "pyobjc-framework-coreservices" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-fsevents" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/a8/a9/141d18019a25776f507992f9e7ffc051ca5a734848d8ea8d848f7c938efc/pyobjc_framework_coreservices-11.1.tar.gz", hash = "sha256:cf8eb5e272c60a96d025313eca26ff2487dcd02c47034cc9db39f6852d077873", size = 1245086, upload-time = "2025-06-14T20:57:13.914Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/fc/35/a984b9aace173e92b3509f82afe5e0f8ecddf5cf43bf0c01c803f60a19ce/pyobjc_framework_coreservices-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:f7260e09a0550d57756ad655f3d3815f21fc3f0386aed014be4b46194c346941", size = 30243, upload-time = "2025-06-14T20:48:21.563Z" }, - { url = "https://files.pythonhosted.org/packages/fa/0f/52827197a1fa1dabefd77803920eaf340f25e0c81944844ab329d511cade/pyobjc_framework_coreservices-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:6bd313ec326efd715b4b10c3ebcc9f054e3ee3178be407b97ea225cd871351d2", size = 30252, upload-time = "2025-06-14T20:48:22.657Z" }, -] - -[[package]] -name = "pyobjc-framework-corespotlight" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/31/c7/b67ebfb63b7ccbfda780d583056d1fd4b610ba3839c8ebe3435b86122c61/pyobjc_framework_corespotlight-11.1.tar.gz", hash = "sha256:4dd363c8d3ff7619659b63dd31400f135b03e32435b5d151459ecdacea14e0f2", size = 87161, upload-time = "2025-06-14T20:57:14.934Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/46/d4/87a87384bbb2e27864d527eb00973a056bae72603e6c581711231f2479fc/pyobjc_framework_corespotlight-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:d3c571289ce9107f1ade92ad036633f81355f22f70e8ba82d7335f1757381b89", size = 9954, upload-time = "2025-06-14T20:48:28.065Z" }, - { url = "https://files.pythonhosted.org/packages/b9/f8/06b7edfeabe5b3874485b6e5bbe4a39d9f2e1f44348faa7cb320fbc6f21a/pyobjc_framework_corespotlight-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:7cedd3792fe1fe2a8dc65a8ff1f70baf12415a5dc9dc4d88f987059567d7e694", size = 9977, upload-time = "2025-06-14T20:48:28.757Z" }, -] - -[[package]] -name = "pyobjc-framework-coretext" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-quartz" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/65/e9/d3231c4f87d07b8525401fd6ad3c56607c9e512c5490f0a7a6abb13acab6/pyobjc_framework_coretext-11.1.tar.gz", hash = "sha256:a29bbd5d85c77f46a8ee81d381b847244c88a3a5a96ac22f509027ceceaffaf6", size = 274702, upload-time = "2025-06-14T20:57:16.059Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/4c/59/d6cc5470157cfd328b2d1ee2c1b6f846a5205307fce17291b57236d9f46e/pyobjc_framework_coretext-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:b4f4d2d2a6331fa64465247358d7aafce98e4fb654b99301a490627a073d021e", size = 30072, upload-time = "2025-06-14T20:48:34.248Z" }, - { url = "https://files.pythonhosted.org/packages/32/67/9cc5189c366e67dc3e5b5976fac73cc6405841095f795d3fa0d5fc43d76a/pyobjc_framework_coretext-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:1597bf7234270ee1b9963bf112e9061050d5fb8e1384b3f50c11bde2fe2b1570", size = 30175, upload-time = "2025-06-14T20:48:35.023Z" }, -] - -[[package]] -name = "pyobjc-framework-corewlan" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/c6/d8/03aff3c75485fc999e260946ef1e9adf17640a6e08d7bf603d31cfcf73fc/pyobjc_framework_corewlan-11.1.tar.gz", hash = "sha256:4a8afea75393cc0a6fe696e136233aa0ed54266f35a47b55a3583f4cb078e6ce", size = 65792, upload-time = "2025-06-14T20:57:16.931Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/03/ba/e73152fc1beee1bf75489d4a6f89ebd9783340e50ca1948cde029d7b0411/pyobjc_framework_corewlan-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:e12f127b37a7ab8f349167332633392f2d6d29b87c9b98137a289d0fc1e07b5b", size = 9993, upload-time = "2025-06-14T20:48:41.081Z" }, - { url = "https://files.pythonhosted.org/packages/09/8a/74feabaad1225eb2c44d043924ed8caea31683e6760cd9b918b8d965efea/pyobjc_framework_corewlan-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:7bd0775d2466ad500aad4747d8a889993db3a14240239f30ef53c087745e9c8e", size = 10016, upload-time = "2025-06-14T20:48:41.792Z" }, -] - -[[package]] -name = "pyobjc-framework-cryptotokenkit" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/eb/92/7fab6fcc6bb659d6946cfb2f670058180bcc4ca1626878b0f7c95107abf0/pyobjc_framework_cryptotokenkit-11.1.tar.gz", hash = "sha256:5f82f44d9ab466c715a7c8ad4d5ec47c68aacd78bd67b5466a7b8215a2265328", size = 59223, upload-time = "2025-06-14T20:57:17.658Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/eb/b6/783495dc440277a330930bac7b560cf54d5e1838fc30fdc3162722db8a62/pyobjc_framework_cryptotokenkit-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:2b76fb928bc398091141dc52b26e02511065afd0b6de5533fa0e71ab13c51589", size = 12515, upload-time = "2025-06-14T20:48:47.346Z" }, - { url = "https://files.pythonhosted.org/packages/76/f1/4cb9c90a55ec13301d60ac1c4d774c37b4ebc6db6331d3853021c933fcc8/pyobjc_framework_cryptotokenkit-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:6384cb1d86fc586e2da934a5a37900825bd789e3a5df97517691de9af354af0c", size = 12543, upload-time = "2025-06-14T20:48:48.079Z" }, -] - -[[package]] -name = "pyobjc-framework-datadetection" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/7d/4d/65c61d8878b44689e28d5729be9edbb73e20b1b0500d1095172cfd24aea6/pyobjc_framework_datadetection-11.1.tar.gz", hash = "sha256:cbe0080b51e09b2f91eaf2a9babec3dcf2883d7966bc0abd8393ef7abfcfc5db", size = 13485, upload-time = "2025-06-14T20:57:18.829Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/08/c4/ef2136e4e0cc69b02479295822aa33c8e26995b265c8a1184867b65a0a06/pyobjc_framework_datadetection-11.1-py2.py3-none-any.whl", hash = "sha256:5afd3dde7bba3324befb7a3133c9aeaa5088efd72dccc0804267a74799f4a12f", size = 3482, upload-time = "2025-06-14T20:48:54.301Z" }, -] - -[[package]] -name = "pyobjc-framework-devicecheck" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/f3/f2/b1d263f8231f815a9eeff15809f4b7428dacdc0a6aa267db5ed907445066/pyobjc_framework_devicecheck-11.1.tar.gz", hash = "sha256:8b05973eb2673571144d81346336e749a21cec90bd7fcaade76ffd3b147a0741", size = 13954, upload-time = "2025-06-14T20:57:19.782Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/39/72/17698a0d68b1067b20b32b4afd74bcafb53a7c73ae8fc608addc7b9e7a37/pyobjc_framework_devicecheck-11.1-py2.py3-none-any.whl", hash = "sha256:8edb36329cdd5d55e2c2c57c379cb5ba1f500f74a08fe8d2612b1a69b7a26435", size = 3668, upload-time = "2025-06-14T20:48:55.098Z" }, -] - -[[package]] -name = "pyobjc-framework-devicediscoveryextension" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/9a/b8/102863bfa2f1e414c88bb9f51151a9a58b99c268a841b59d46e0dcc5fe6d/pyobjc_framework_devicediscoveryextension-11.1.tar.gz", hash = "sha256:ae160ea40f25d3ee5e7ce80ac9c1b315f94d0a4c7ccb86920396f71c6bf799a0", size = 14298, upload-time = "2025-06-14T20:57:20.738Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/67/89/fce0c0c89746f399d13e08b40fc12e29a2495f4dcebd30893336d047af18/pyobjc_framework_devicediscoveryextension-11.1-py2.py3-none-any.whl", hash = "sha256:96e5b13c718bd0e6c80fbd4e14b8073cffc88b3ab9bb1bbb4dab7893a62e4f11", size = 4249, upload-time = "2025-06-14T20:48:55.895Z" }, -] - -[[package]] -name = "pyobjc-framework-dictionaryservices" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-coreservices" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/d6/13/c46f6db61133fee15e3471f33a679da2af10d63fa2b4369e0cd476988721/pyobjc_framework_dictionaryservices-11.1.tar.gz", hash = "sha256:39c24452d0ddd037afeb73a1742614c94535f15b1c024a8a6cc7ff081e1d22e7", size = 10578, upload-time = "2025-06-14T20:57:21.392Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/6c/86/4e757b4064a0feb8d60456672560adad0bb5df530ba6621fe65d175dbd90/pyobjc_framework_dictionaryservices-11.1-py2.py3-none-any.whl", hash = "sha256:92f4871066653f18e2394ac93b0a2ab50588d60020f6b3bd93e97b67cd511326", size = 3913, upload-time = "2025-06-14T20:48:56.806Z" }, -] - -[[package]] -name = "pyobjc-framework-discrecording" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/a5/b2/d8d1a28643c2ab681b517647bacb68496c98886336ffbd274f0b2ad28cdc/pyobjc_framework_discrecording-11.1.tar.gz", hash = "sha256:37585458e363b20bb28acdb5cc265dfca934d8a07b7baed2584953c11c927a87", size = 123004, upload-time = "2025-06-14T20:57:22.01Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/a8/8c/0ff85cc34218e54236eb866e71c35e3308a661f50aea090d400e9121d9c4/pyobjc_framework_discrecording-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:dc8a7820fc193c2bfcd843c31de945dc45e77e5413089eabbc72be16a4f52e53", size = 14558, upload-time = "2025-06-14T20:48:58.495Z" }, - { url = "https://files.pythonhosted.org/packages/5e/17/032fa44bb66b6a20c432f3311072f88478b42dcf39b21ebb6c3bbdf2954f/pyobjc_framework_discrecording-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:e29bc8c3741ae52fae092f892de856dbab2363e71537a8ae6fd026ecb88e2252", size = 14581, upload-time = "2025-06-14T20:48:59.228Z" }, -] - -[[package]] -name = "pyobjc-framework-discrecordingui" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-discrecording" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/25/53/d71717f00332b8fc3d8a5c7234fdc270adadfeb5ca9318a55986f5c29c44/pyobjc_framework_discrecordingui-11.1.tar.gz", hash = "sha256:a9f10e2e7ee19582c77f0755ae11a64e3d61c652cbd8a5bf52756f599be24797", size = 19370, upload-time = "2025-06-14T20:57:22.791Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/4a/a6/505af43f7a17e0ca3d45e099900764e8758e0ca65341e894b74ade513556/pyobjc_framework_discrecordingui-11.1-py2.py3-none-any.whl", hash = "sha256:33233b87d7b85ce277a51d27acca0f5b38485cf1d1dc8e28a065910047766ee2", size = 4721, upload-time = "2025-06-14T20:49:03.737Z" }, -] - -[[package]] -name = "pyobjc-framework-diskarbitration" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/da/2a/68fa0c99e04ec1ec24b0b7d6f5b7ec735d5e8a73277c5c0671438a69a403/pyobjc_framework_diskarbitration-11.1.tar.gz", hash = "sha256:a933efc6624779a393fafe0313e43378bcae2b85d6d15cff95ac30048c1ef490", size = 19866, upload-time = "2025-06-14T20:57:23.435Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/1f/72/9534ca88effbf2897e07b722920b3f10890dbc780c6fff1ab4893ec1af10/pyobjc_framework_diskarbitration-11.1-py2.py3-none-any.whl", hash = "sha256:6a8e551e54df481a9081abba6fd680f6633babe5c7735f649731b22896bb6f08", size = 4849, upload-time = "2025-06-14T20:49:04.513Z" }, -] - -[[package]] -name = "pyobjc-framework-dvdplayback" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/b8/76/77046325b1957f0cbcdf4f96667496d042ed4758f3413f1d21df5b085939/pyobjc_framework_dvdplayback-11.1.tar.gz", hash = "sha256:b44c36a62c8479e649133216e22941859407cca5796b5f778815ef9340a838f4", size = 64558, upload-time = "2025-06-14T20:57:24.118Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/59/0c/f0fefa171b6938010d87194e26e63eea5c990c33d2d7828de66802f57c36/pyobjc_framework_dvdplayback-11.1-py2.py3-none-any.whl", hash = "sha256:6094e4651ea29540ac817294b27e1596b9d1883d30e78fb5f9619daf94ed30cb", size = 8221, upload-time = "2025-06-14T20:49:05.297Z" }, -] - -[[package]] -name = "pyobjc-framework-eventkit" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/b4/c4/cbba8f2dce13b9be37ecfd423ba2b92aa3f209dbb58ede6c4ce3b242feee/pyobjc_framework_eventkit-11.1.tar.gz", hash = "sha256:5643150f584243681099c5e9435efa833a913e93fe9ca81f62007e287349b561", size = 75177, upload-time = "2025-06-14T20:57:24.81Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/05/0a/384b9ff4c6380cac310cb7b92c145896c20a690192dbfc07b38909787ded/pyobjc_framework_eventkit-11.1-py2.py3-none-any.whl", hash = "sha256:c303207610d9c742f4090799f60103cede466002f3c89cf66011c8bf1987750b", size = 6805, upload-time = "2025-06-14T20:49:06.147Z" }, -] - -[[package]] -name = "pyobjc-framework-exceptionhandling" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/19/0d/c72a885b40d28a99b586447f9ea6f400589f13d554fcd6f13a2c841bb6d2/pyobjc_framework_exceptionhandling-11.1.tar.gz", hash = "sha256:e010f56bf60ab4e9e3225954ebb53e9d7135d37097043ac6dd2a3f35770d4efa", size = 17890, upload-time = "2025-06-14T20:57:25.521Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/7f/81/dde9c73bf307b62c2d605fc818d3e49f857f39e0841766093dbc9ea47b08/pyobjc_framework_exceptionhandling-11.1-py2.py3-none-any.whl", hash = "sha256:31e6538160dfd7526ac0549bc0fce5d039932aea84c36abbe7b49c79ffc62437", size = 7078, upload-time = "2025-06-14T20:49:07.713Z" }, -] - -[[package]] -name = "pyobjc-framework-executionpolicy" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/0b/cf/54431846508c5d5bb114a415ebb96187da5847105918169e42f4ca3b00e6/pyobjc_framework_executionpolicy-11.1.tar.gz", hash = "sha256:3280ad2f4c5eaf45901f310cee0c52db940c0c63e959ad082efb8df41055d986", size = 13496, upload-time = "2025-06-14T20:57:26.173Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/a6/d2/cb192d55786d0f881f2fb60d45b61862a1fcade945f6a7a549ed62f47e61/pyobjc_framework_executionpolicy-11.1-py2.py3-none-any.whl", hash = "sha256:7d4141e572cb916e73bb34bb74f6f976a8aa0a396a0bffd1cf66e5505f7c76c8", size = 3719, upload-time = "2025-06-14T20:49:08.521Z" }, -] - -[[package]] -name = "pyobjc-framework-extensionkit" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/ce/7d/89adf16c7de4246477714dce8fcffae4242778aecd0c5f0ad9904725f42c/pyobjc_framework_extensionkit-11.1.tar.gz", hash = "sha256:c114a96f13f586dbbab8b6219a92fa4829896a645c8cd15652a6215bc8ff5409", size = 19766, upload-time = "2025-06-14T20:57:27.106Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/0f/90/e6607b779756e039c0a4725a37cf70dc5b13c54a8cedbcf01ec1608866b1/pyobjc_framework_extensionkit-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:61fd9f9758f95bcff2bf26fe475f679dfff9457d7130f114089e88fd5009675a", size = 7894, upload-time = "2025-06-14T20:49:10.593Z" }, - { url = "https://files.pythonhosted.org/packages/90/2a/93105b5452d2ff680a47e38a3ec6f2a37164babd95e0ab976c07984366de/pyobjc_framework_extensionkit-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:d505a64617c9db4373eb386664d62a82ba9ffc909bffad42cb4da8ca8e244c66", size = 7914, upload-time = "2025-06-14T20:49:11.842Z" }, -] - -[[package]] -name = "pyobjc-framework-externalaccessory" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/d9/a3/519242e6822e1ddc9e64e21f717529079dbc28a353474420da8315d0a8b1/pyobjc_framework_externalaccessory-11.1.tar.gz", hash = "sha256:50887e948b78a1d94646422c243ac2a9e40761675e38b9184487870a31e83371", size = 23123, upload-time = "2025-06-14T20:57:27.845Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/63/54/d532badd43eba2db3fed2501b8e47a57cab233de2090ee97f4cff723e706/pyobjc_framework_externalaccessory-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:a2b22f72b83721d841e5a3128df29fc41d785597357c6bbce84555a2b51a1e9d", size = 8887, upload-time = "2025-06-14T20:49:17.703Z" }, - { url = "https://files.pythonhosted.org/packages/7d/1b/e2def12aca9162b0fe0bbf0790d35595d46b2ef12603749c42af9234ffca/pyobjc_framework_externalaccessory-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:00caf75b959db5d14118d78c04085e2148255498839cdee735a0b9f6ef86b6a2", size = 8903, upload-time = "2025-06-14T20:49:18.393Z" }, -] - -[[package]] -name = "pyobjc-framework-fileprovider" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/1b/80/3ebba2c1e5e3aeae989fe038c259a93e7e7e18fd56666ece514d000d38ea/pyobjc_framework_fileprovider-11.1.tar.gz", hash = "sha256:748ca1c75f84afdf5419346a24bf8eec44dca071986f31f00071dc191b3e9ca8", size = 91696, upload-time = "2025-06-14T20:57:28.546Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/d1/e4/c7b985d1199e3697ab5c3247027fe488b9d81b1fb597c34350942dc5838c/pyobjc_framework_fileprovider-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:888d6fb3fd625889ce0e409320c3379330473a386095cb4eda2b4caf0198ff66", size = 19546, upload-time = "2025-06-14T20:49:23.436Z" }, - { url = "https://files.pythonhosted.org/packages/49/b2/859d733b0110e56511478ba837fd8a7ba43aa8f8c7e5231b9e3f0258bfbf/pyobjc_framework_fileprovider-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:ce6092dfe74c78c0b2abc03bfc18a0f5d8ddc624fc6a1d8dfef26d7796653072", size = 19622, upload-time = "2025-06-14T20:49:24.162Z" }, -] - -[[package]] -name = "pyobjc-framework-fileproviderui" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-fileprovider" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/75/ed/0f5af06869661822c4a70aacd674da5d1e6b6661240e2883bbc7142aa525/pyobjc_framework_fileproviderui-11.1.tar.gz", hash = "sha256:162a23e67f59e1bb247e84dda88d513d7944d815144901a46be6fe051b6c7970", size = 13163, upload-time = "2025-06-14T20:57:29.568Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/62/01/667e139a0610494e181fccdce519f644166f3d8955b330674deba5876f0d/pyobjc_framework_fileproviderui-11.1-py2.py3-none-any.whl", hash = "sha256:f2765f114c2f4356aa41fb45c621fa8f0a4fae0b6d3c6b1a274366f5fe7fe829", size = 3696, upload-time = "2025-06-14T20:49:29.404Z" }, -] - -[[package]] -name = "pyobjc-framework-findersync" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/2a/82/c6b670494ac0c4cf14cf2db0dfbe0df71925d20595404939383ddbcc56d3/pyobjc_framework_findersync-11.1.tar.gz", hash = "sha256:692364937f418f0e4e4abd395a09a7d4a0cdd55fd4e0184de85ee59642defb6e", size = 15045, upload-time = "2025-06-14T20:57:30.173Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/61/10/748ff914c5b7fbae5fa2436cd44b11caeabb8d2f6f6f1b9ab581f70f32af/pyobjc_framework_findersync-11.1-py2.py3-none-any.whl", hash = "sha256:c72b0fd8b746b99cfa498da36c5bb333121b2080ad73fa8cbea05cd47db1fa82", size = 4873, upload-time = "2025-06-14T20:49:30.194Z" }, -] - -[[package]] -name = "pyobjc-framework-fsevents" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/8e/83/ec0b9ba355dbc34f27ed748df9df4eb6dbfdd9bbd614b0f193752f36f419/pyobjc_framework_fsevents-11.1.tar.gz", hash = "sha256:d29157d04124503c4dfa9dcbbdc8c34d3bab134d3db3a48d96d93f26bd94c14d", size = 29587, upload-time = "2025-06-14T20:57:30.796Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/14/6a/25118832a128db99a53be4c45f473192f72923d9b9690785539cee1a9858/pyobjc_framework_fsevents-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:95cc5d839d298b8e95175fb72df8a8e1b08773fd2e0d031efe91eee23e0c8830", size = 13076, upload-time = "2025-06-14T20:49:32.269Z" }, - { url = "https://files.pythonhosted.org/packages/13/c7/378d78e0fd956370f2b120b209117384b5b98925c6d8210a33fd73db4a15/pyobjc_framework_fsevents-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:8b51d120b8f12a1ca94e28cf74113bf2bfd4c5aee7035b452e895518f4df7630", size = 13147, upload-time = "2025-06-14T20:49:33.022Z" }, -] - -[[package]] -name = "pyobjc-framework-fskit" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/46/47/d1f04c6115fa78936399a389cc5e0e443f8341c9a6c1c0df7f6fdbe51286/pyobjc_framework_fskit-11.1.tar.gz", hash = "sha256:9ded1eab19b4183cb04381e554bbbe679c1213fd58599d6fc6e135e93b51136f", size = 42091, upload-time = "2025-06-14T20:57:31.504Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/16/76/1152bd8121ef2c9a0ccdf10624d647095ce944d34f654f001b458edef668/pyobjc_framework_fskit-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:59a939ac8442d648f73a3da75923aa3637ac4693850d995f1914260c8f4f7947", size = 19922, upload-time = "2025-06-14T20:49:38.424Z" }, - { url = "https://files.pythonhosted.org/packages/59/8f/db8f03688db77bfa4b78e89af1d89e910c5e877e94d58bdb3e93cc302e5d/pyobjc_framework_fskit-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:1e50b8f949f1386fada73b408463c87eb81ef7fd0b3482bacf0c206a73723013", size = 19948, upload-time = "2025-06-14T20:49:39.18Z" }, -] - -[[package]] -name = "pyobjc-framework-gamecenter" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/1b/8e/b594fd1dc32a59462fc68ad502be2bd87c70e6359b4e879a99bcc4beaf5b/pyobjc_framework_gamecenter-11.1.tar.gz", hash = "sha256:a1c4ed54e11a6e4efba6f2a21ace92bcf186e3fe5c74a385b31f6b1a515ec20c", size = 31981, upload-time = "2025-06-14T20:57:32.192Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/21/a8/8d9c2d0ff9f42a0951063a9eaff1e39c46c15e89ce4e5e274114340ca976/pyobjc_framework_gamecenter-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:81abe136292ea157acb6c54871915fe6d386146a9386179ded0b974ac435045c", size = 18601, upload-time = "2025-06-14T20:49:44.946Z" }, - { url = "https://files.pythonhosted.org/packages/99/52/0e56f21a6660a4f43882ec641b9e19b7ea92dc7474cec48cda1c9bed9c49/pyobjc_framework_gamecenter-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:779cdf8f52348be7f64d16e3ea37fd621d5ee933c032db3a22a8ccad46d69c59", size = 18634, upload-time = "2025-06-14T20:49:45.737Z" }, -] - -[[package]] -name = "pyobjc-framework-gamecontroller" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/70/4c/1dd62103092a182f2ab8904c8a8e3922d2b0a80a7adab0c20e5fd0207d75/pyobjc_framework_gamecontroller-11.1.tar.gz", hash = "sha256:4d5346faf90e1ebe5602c0c480afbf528a35a7a1ad05f9b49991fdd2a97f105b", size = 115783, upload-time = "2025-06-14T20:57:32.879Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/e5/8e/09e73e03e9f57e77df58cf77f6069d3455a3c388a890ff815e86d036ae39/pyobjc_framework_gamecontroller-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:782779f080508acf869187c0cbd3a48c55ee059d3a14fe89ccd6349537923214", size = 20825, upload-time = "2025-06-14T20:49:51.565Z" }, - { url = "https://files.pythonhosted.org/packages/40/e3/e35bccb0284046ef716db4897b70d061b8b16c91fb2c434b1e782322ef56/pyobjc_framework_gamecontroller-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:d2cbc0c6c7d9c63e6b5b0b124d0c2bad01bb4b136f3cbc305f27d31f8aab6083", size = 20850, upload-time = "2025-06-14T20:49:52.401Z" }, -] - -[[package]] -name = "pyobjc-framework-gamekit" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-quartz" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/5b/7b/ba141ec0f85ca816f493d1f6fe68c72d01092e5562e53c470a0111d9c34b/pyobjc_framework_gamekit-11.1.tar.gz", hash = "sha256:9b8db075da8866c4ef039a165af227bc29393dc11a617a40671bf6b3975ae269", size = 165397, upload-time = "2025-06-14T20:57:33.711Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b4/2a/f206682b9ff76983bae14a479a9c8a9098e58efc3db31f88211d6ad4fd42/pyobjc_framework_gamekit-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:5e07c25eab051905c6bd46f368d8b341ef8603dce588ff6dbd82d609dd4fbf71", size = 21932, upload-time = "2025-06-14T20:49:58.154Z" }, - { url = "https://files.pythonhosted.org/packages/1f/23/094e4fe38f2de029365604f0b7dffde7b0edfc57c3d388294c20ed663de2/pyobjc_framework_gamekit-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:f945c7cfe53c4a349a03a1272f2736cc5cf88fe9e7a7a407abb03899635d860c", size = 21952, upload-time = "2025-06-14T20:49:58.933Z" }, -] - -[[package]] -name = "pyobjc-framework-gameplaykit" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-spritekit" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/e0/07/f38b1d83eac10ea4f75c605ffc4850585740db89b90842d311e586ee36cd/pyobjc_framework_gameplaykit-11.1.tar.gz", hash = "sha256:9ae2bee69b0cc1afa0e210b4663c7cdbb3cc94be1374808df06f98f992e83639", size = 73399, upload-time = "2025-06-14T20:57:34.538Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/0f/29/df66f53f887990878b2b00b1336e451a15e360a384be74559acf47854bc3/pyobjc_framework_gameplaykit-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:ac9f50941988c30175149af481a49b2026c56a9a497c6dbf2974ffb50ffe0af8", size = 13065, upload-time = "2025-06-14T20:50:05.243Z" }, - { url = "https://files.pythonhosted.org/packages/e7/f5/65bdbefb9de7cbc2edf0b1f76286736536e31c216cfac1a5f84ea15f0fc1/pyobjc_framework_gameplaykit-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:0e4f34db8177b8b4d89fd22a2a882a6c9f6e50cb438ea2fbbf96845481bcd80d", size = 13091, upload-time = "2025-06-14T20:50:05.962Z" }, -] - -[[package]] -name = "pyobjc-framework-healthkit" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/af/66/fa76f7c8e36e4c10677d42d91a8e220c135c610a06b759571db1abe26a32/pyobjc_framework_healthkit-11.1.tar.gz", hash = "sha256:20f59bd9e1ffafe5893b4eff5867fdfd20bd46c3d03bc4009219d82fc6815f76", size = 202009, upload-time = "2025-06-14T20:57:35.285Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/70/aa/c337d27dd98ffcbba2b1200126fcf624d1ccbeb7a4ed9205d48bfe2c1ca8/pyobjc_framework_healthkit-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:34bce3d144c461af7e577fcf6bbb7739d0537bf42f081960122923a7ef2e06c0", size = 20301, upload-time = "2025-06-14T20:50:12.158Z" }, - { url = "https://files.pythonhosted.org/packages/c7/08/12fca070ad2dc0b9c311df209b9b6d275ee192cb5ccbc94616d9ddd80d88/pyobjc_framework_healthkit-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:ab4350f9fe65909107dd7992b367a6c8aac7dc31ed3d5b52eeb2310367d0eb0b", size = 20311, upload-time = "2025-06-14T20:50:13.271Z" }, -] - -[[package]] -name = "pyobjc-framework-imagecapturecore" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/7b/3b/f4edbc58a8c7394393f8d00d0e764f655545e743ee4e33917f27b8c68e7b/pyobjc_framework_imagecapturecore-11.1.tar.gz", hash = "sha256:a610ceb6726e385b132a1481a68ce85ccf56f94667b6d6e1c45a2cfab806a624", size = 100398, upload-time = "2025-06-14T20:57:36.503Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/50/72/465741d33757ef2162a1c9e12d6c8a41b5490949a92431c42a139c132303/pyobjc_framework_imagecapturecore-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:ede4c15da909a4d819c732a5554b8282a7b56a1b73d82aef908124147921945a", size = 15999, upload-time = "2025-06-14T20:50:18.742Z" }, - { url = "https://files.pythonhosted.org/packages/61/62/54ed61e7cd3213549c8e98ca87a6b21afbb428d2c41948ae48ea019bf973/pyobjc_framework_imagecapturecore-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:ed296c23d3d8d1d9af96a6486d09fb8d294cc318e4a2152e6f134151c76065f8", size = 16021, upload-time = "2025-06-14T20:50:19.836Z" }, -] - -[[package]] -name = "pyobjc-framework-inputmethodkit" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/02/32/6a90bba682a31960ba1fc2d3b263e9be26043c4fb7aed273c13647c8b7d9/pyobjc_framework_inputmethodkit-11.1.tar.gz", hash = "sha256:7037579524041dcee71a649293c2660f9359800455a15e6a2f74a17b46d78496", size = 27203, upload-time = "2025-06-14T20:57:37.246Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/7f/23/a4226040eec8ed930c81073776064f30d627db03e9db5b24720aad8fd14d/pyobjc_framework_inputmethodkit-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:9b0e47c3bc7f1e628c906436c1735041ed2e9aa7cba3f70084b6311c63c508be", size = 9480, upload-time = "2025-06-14T20:50:25.184Z" }, - { url = "https://files.pythonhosted.org/packages/a8/0d/8a570072096fe339702e4ae9d98e59ee7c6c14124d4437c9a8c4482dda6d/pyobjc_framework_inputmethodkit-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:dd0c591a9d26967018a781fa4638470147ef2a9af3ab4a28612f147573eeefba", size = 9489, upload-time = "2025-06-14T20:50:25.875Z" }, -] - -[[package]] -name = "pyobjc-framework-installerplugins" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/4d/89/9a881e466476ca21f3ff3e8e87ccfba1aaad9b88f7eea4be6d3f05b07107/pyobjc_framework_installerplugins-11.1.tar.gz", hash = "sha256:363e59c7e05553d881f0facd41884f17b489ff443d7856e33dd0312064c746d9", size = 27451, upload-time = "2025-06-14T20:57:37.915Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/3d/01/45c3d159d671c5f488a40f70aa6791b8483a3ed32b461800990bb5ab4bb3/pyobjc_framework_installerplugins-11.1-py2.py3-none-any.whl", hash = "sha256:f92b06c9595f3c800b7aabf1c1a235bfb4b2de3f5406d5f604d8e2ddd0aecb4e", size = 4798, upload-time = "2025-06-14T20:50:30.799Z" }, -] - -[[package]] -name = "pyobjc-framework-instantmessage" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-quartz" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/9f/b9/5cec4dd0053b5f63c01211a60a286c47464d9f3e0c81bd682e6542dbff00/pyobjc_framework_instantmessage-11.1.tar.gz", hash = "sha256:c222aa61eb009704b333f6e63df01a0e690136e7e495907e5396882779bf9525", size = 33774, upload-time = "2025-06-14T20:57:38.553Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/91/34/acd618e90036822aaf01080d64558ba93e33e15ed91beb7d1d2aab290138/pyobjc_framework_instantmessage-11.1-py2.py3-none-any.whl", hash = "sha256:a70b716e279135eec5666af031f536c0f32dec57cfeae55cc9ff8457f10d4f3d", size = 5419, upload-time = "2025-06-14T20:50:31.993Z" }, -] - -[[package]] -name = "pyobjc-framework-intents" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/4c/af/d7f260d06b79acca8028e373c2fe30bf0be014388ba612f538f40597d929/pyobjc_framework_intents-11.1.tar.gz", hash = "sha256:13185f206493f45d6bd2d4903c2136b1c4f8b9aa37628309ace6ff4a906b4695", size = 448459, upload-time = "2025-06-14T20:57:39.589Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/c5/1d/10fdbf3b8dd6451465ae147143ba3159397a50ff81aed1eb86c153e987b5/pyobjc_framework_intents-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:da2f11ee64c75cfbebb1c2be52a20b3618f32b6c47863809ff64c61e8a1dffb9", size = 32227, upload-time = "2025-06-14T20:50:34.303Z" }, - { url = "https://files.pythonhosted.org/packages/8a/37/e6fa5737da42fb1265041bd3bd4f2be96f09294018fabf07139dd9dbc7b9/pyobjc_framework_intents-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:a663e2de1b7ae7b547de013f89773963f8180023e36f2cebfe8060395dc34c33", size = 32253, upload-time = "2025-06-14T20:50:35.028Z" }, -] - -[[package]] -name = "pyobjc-framework-intentsui" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-intents" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/86/46/20aae4a71efb514b096f36273a6129b48b01535bf501e5719d4a97fcb3a5/pyobjc_framework_intentsui-11.1.tar.gz", hash = "sha256:c8182155af4dce369c18d6e6ed9c25bbd8110c161ed5f1b4fb77cf5cdb99d135", size = 21305, upload-time = "2025-06-14T20:57:40.477Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/31/e3/db74fc161bb85bc442dfddf50321924613b67cf49288e2a8b335bf6d546a/pyobjc_framework_intentsui-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:252f7833fabb036cd56d59b445922b25cda1561b54c0989702618a5561d8e748", size = 8936, upload-time = "2025-06-14T20:50:40.522Z" }, - { url = "https://files.pythonhosted.org/packages/43/7c/77fbd2a6f85eb905fbf27ba7540eaf2a026771ed5100fb1c01143cf47e9b/pyobjc_framework_intentsui-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:99a3ae40eb2a6ef1125955dd513c8acc88ce7d8d90130a8cdeaec8336e6fbec5", size = 8965, upload-time = "2025-06-14T20:50:41.281Z" }, -] - -[[package]] -name = "pyobjc-framework-iobluetooth" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/93/e0/74b7b10c567b66c5f38b45ab240336325a4c889f43072d90f2b90aaeb7c0/pyobjc_framework_iobluetooth-11.1.tar.gz", hash = "sha256:094fd4be60cd1371b17cb4b33a3894e0d88a11b36683912be0540a7d51de76f1", size = 300992, upload-time = "2025-06-14T20:57:41.256Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/0a/13/31a514e48bd54880aadb1aac3a042fca5f499780628c18f4f54f06d4ece2/pyobjc_framework_iobluetooth-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:7d8858cf2e4b2ef5e8bf29b76c06d4f2e6a2264c325146d07dfab94c46633329", size = 40378, upload-time = "2025-06-14T20:50:46.298Z" }, - { url = "https://files.pythonhosted.org/packages/da/94/eef57045762e955795a4e3312674045c52f8c506133acf9efe1b3370b93f/pyobjc_framework_iobluetooth-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:883781e7223cb0c63fab029d640721ded747f2e2b067645bc8b695ef02a4a4dd", size = 40406, upload-time = "2025-06-14T20:50:47.101Z" }, -] - -[[package]] -name = "pyobjc-framework-iobluetoothui" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-iobluetooth" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/dd/32/872272faeab6fe471eac6962c75db72ce65c3556e00b4edebdb41aaab7cb/pyobjc_framework_iobluetoothui-11.1.tar.gz", hash = "sha256:060c721f1cd8af4452493e8153b72b572edcd2a7e3b635d79d844f885afee860", size = 22835, upload-time = "2025-06-14T20:57:42.119Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/d6/ed/35efed52ed3fa698480624e49ee5f3d859827aad5ff1c7334150c695e188/pyobjc_framework_iobluetoothui-11.1-py2.py3-none-any.whl", hash = "sha256:3c5a382d81f319a1ab9ab11b7ead04e53b758fdfeb604755d39c3039485eaac6", size = 4026, upload-time = "2025-06-14T20:50:52.018Z" }, -] - -[[package]] -name = "pyobjc-framework-iosurface" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/c5/ce/38ec17d860d0ee040bb737aad8ca7c7ff46bef6c9cffa47382d67682bb2d/pyobjc_framework_iosurface-11.1.tar.gz", hash = "sha256:a468b3a31e8cd70a2675a3ddc7176ab13aa521c035f11188b7a3af8fff8b148b", size = 20275, upload-time = "2025-06-14T20:57:42.742Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/1d/26/fa912d397b577ee318b20110a3c959e898514a1dce19b4f13f238a31a677/pyobjc_framework_iosurface-11.1-py2.py3-none-any.whl", hash = "sha256:0c36ad56f8ec675dd07616418a2bc29126412b54627655abd21de31bcafe2a79", size = 4948, upload-time = "2025-06-14T20:50:52.801Z" }, -] - -[[package]] -name = "pyobjc-framework-ituneslibrary" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/ee/43/aebefed774b434965752f9001685af0b19c02353aa7a12d2918af0948181/pyobjc_framework_ituneslibrary-11.1.tar.gz", hash = "sha256:e2212a9340e4328056ade3c2f9d4305c71f3f6af050204a135f9fa9aa3ba9c5e", size = 47388, upload-time = "2025-06-14T20:57:43.383Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/2a/57/a29150f734b45b7408cc06efb9e2156328ae74624e5c4a7fe95118e13e94/pyobjc_framework_ituneslibrary-11.1-py2.py3-none-any.whl", hash = "sha256:4e87d41f82acb6d98cf70ac3c932a568ceb3c2035383cbf177f54e63de6b815f", size = 5191, upload-time = "2025-06-14T20:50:53.637Z" }, -] - -[[package]] -name = "pyobjc-framework-kernelmanagement" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/1a/b6/708f10ac16425834cb5f8b71efdbe39b42c3b1009ac0c1796a42fc98cd36/pyobjc_framework_kernelmanagement-11.1.tar.gz", hash = "sha256:e934d1638cd89e38d6c6c5d4d9901b4295acee2d39cbfe0bd91aae9832961b44", size = 12543, upload-time = "2025-06-14T20:57:44.046Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b9/cf/17ff988ad1a0e55a4be5336c64220aa620ad19bb2f487a1122e9a864b29e/pyobjc_framework_kernelmanagement-11.1-py2.py3-none-any.whl", hash = "sha256:ec74690bd3383a7945c4a038cc4e1553ec5c1d2408b60e2b0003a3564bff7c47", size = 3656, upload-time = "2025-06-14T20:50:54.484Z" }, -] - -[[package]] -name = "pyobjc-framework-latentsemanticmapping" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/db/8a/4e54ee2bc77d59d770b287daf73b629e2715a2b3b31264d164398131cbad/pyobjc_framework_latentsemanticmapping-11.1.tar.gz", hash = "sha256:c6c3142301e4d375c24a47dfaeebc2f3d0fc33128a1c0a755794865b9a371145", size = 17444, upload-time = "2025-06-14T20:57:44.643Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/2c/50/d62815b02968236eb46c33f0fb0f7293a32ef68d2ec50c397140846d4e42/pyobjc_framework_latentsemanticmapping-11.1-py2.py3-none-any.whl", hash = "sha256:57f3b183021759a100d2847a4d8aa314f4033be3d2845038b62e5e823d96e871", size = 5454, upload-time = "2025-06-14T20:50:55.658Z" }, -] - -[[package]] -name = "pyobjc-framework-launchservices" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-coreservices" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/2b/0a/a76b13109b8ab563fdb2d7182ca79515f132f82ac6e1c52351a6b02896a8/pyobjc_framework_launchservices-11.1.tar.gz", hash = "sha256:80b55368b1e208d6c2c58395cc7bc12a630a2a402e00e4930493e9bace22b7bb", size = 20446, upload-time = "2025-06-14T20:57:45.258Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/12/30/a4de9021fdef7db0b224cdc1eae75811d889dc1debdfafdabf8be7bd0fb9/pyobjc_framework_launchservices-11.1-py2.py3-none-any.whl", hash = "sha256:8b58f1156651058b2905c87ce48468f4799db86a7edf760e1897fedd057a3908", size = 3889, upload-time = "2025-06-14T20:50:56.484Z" }, -] - -[[package]] -name = "pyobjc-framework-libdispatch" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/be/89/7830c293ba71feb086cb1551455757f26a7e2abd12f360d375aae32a4d7d/pyobjc_framework_libdispatch-11.1.tar.gz", hash = "sha256:11a704e50a0b7dbfb01552b7d686473ffa63b5254100fdb271a1fe368dd08e87", size = 53942, upload-time = "2025-06-14T20:57:45.903Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b0/cd/1010dee9f932a9686c27ce2e45e91d5b6875f5f18d2daafadea70090e111/pyobjc_framework_libdispatch-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:2ddca472c2cbc6bb192e05b8b501d528ce49333abe7ef0eef28df3133a8e18b7", size = 20441, upload-time = "2025-06-14T20:50:58.3Z" }, - { url = "https://files.pythonhosted.org/packages/ac/92/ff9ceb14e1604193dcdb50643f2578e1010c68556711cd1a00eb25489c2b/pyobjc_framework_libdispatch-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:dc9a7b8c2e8a63789b7cf69563bb7247bde15353208ef1353fff0af61b281684", size = 15627, upload-time = "2025-06-14T20:50:59.055Z" }, -] - -[[package]] -name = "pyobjc-framework-libxpc" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/6a/c9/7e15e38ac23f5bfb4e82bdf3b7ef88e2f56a8b4ad884009bc2d5267d2e1f/pyobjc_framework_libxpc-11.1.tar.gz", hash = "sha256:8fd7468aa520ff19915f6d793070b84be1498cb87224bee2bad1f01d8375273a", size = 49135, upload-time = "2025-06-14T20:57:46.59Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/39/01/f5fbc7627f838aea5960f3287b75cbda9233f76fc3ba82f088630d5d16cc/pyobjc_framework_libxpc-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:4ec8a7df24d85a561fc21d0eb0db89e8cddefeedec71c69bccf17f99804068ed", size = 19466, upload-time = "2025-06-14T20:51:05.138Z" }, - { url = "https://files.pythonhosted.org/packages/be/8f/dfd8e1e1e461f857a1e50138e69b17c0e62a8dcaf7dea791cc158d2bf854/pyobjc_framework_libxpc-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:c29b2df8d74ff6f489afa7c39f7c848c5f3d0531a6bbe704571782ee6c820084", size = 19573, upload-time = "2025-06-14T20:51:05.902Z" }, -] - -[[package]] -name = "pyobjc-framework-linkpresentation" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-quartz" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/b9/76/22873be73f12a3a11ae57af13167a1d2379e4e7eef584de137156a00f5ef/pyobjc_framework_linkpresentation-11.1.tar.gz", hash = "sha256:a785f393b01fdaada6d7d6d8de46b7173babba205b13b44f1dc884b3695c2fc9", size = 14987, upload-time = "2025-06-14T20:57:47.277Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/3d/59/23249e76e06e3c1a4f88acac7144999fae5a5a8ce4b90272d08cc0ac38ae/pyobjc_framework_linkpresentation-11.1-py2.py3-none-any.whl", hash = "sha256:018093469d780a45d98f4e159f1ea90771caec456b1599abcc6f3bf3c6873094", size = 3847, upload-time = "2025-06-14T20:51:10.817Z" }, -] - -[[package]] -name = "pyobjc-framework-localauthentication" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-security" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/e5/27/9e3195f3561574140e9b9071a36f7e0ebd18f50ade9261d23b5b9df8fccd/pyobjc_framework_localauthentication-11.1.tar.gz", hash = "sha256:3cd48907c794bd414ac68b8ac595d83c7e1453b63fc2cfc2d2035b690d31eaa1", size = 40700, upload-time = "2025-06-14T20:57:47.931Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/4e/9a/acc10d45041445db99a121950b0d4f4ff977dbe5e95ec154fe2e1740ff08/pyobjc_framework_localauthentication-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:1b6d52d07abd2240f7bc02b01ea1c630c280ed3fbc3fabe1e43b7444cfd41788", size = 10707, upload-time = "2025-06-14T20:51:12.436Z" }, - { url = "https://files.pythonhosted.org/packages/91/db/59f118cc2658814c6b501b7360ca4fe6a82fd289ced5897b99787130ceef/pyobjc_framework_localauthentication-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:aa3815f936612d78e51b53beed9115c57ae2fd49500bb52c4030a35856e6569e", size = 10730, upload-time = "2025-06-14T20:51:13.487Z" }, -] - -[[package]] -name = "pyobjc-framework-localauthenticationembeddedui" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-localauthentication" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/29/7b/08c1e52487b07e9aee4c24a78f7c82a46695fa883113e3eece40f8e32d40/pyobjc_framework_localauthenticationembeddedui-11.1.tar.gz", hash = "sha256:22baf3aae606e5204e194f02bb205f244e27841ea7b4a4431303955475b4fa56", size = 14076, upload-time = "2025-06-14T20:57:48.557Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/51/3d/2aaa3a4f0e82f0ac95cc432a6079f6dc20aa18a66c9a87ac6128c70df9ef/pyobjc_framework_localauthenticationembeddedui-11.1-py2.py3-none-any.whl", hash = "sha256:3539a947b102b41ea6e40e7c145f27280d2f36a2a9a1211de32fa675d91585eb", size = 3973, upload-time = "2025-06-14T20:51:18.2Z" }, -] - -[[package]] -name = "pyobjc-framework-mailkit" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/7e/7e/f22d733897e7618bd70a658b0353f5f897c583df04e7c5a2d68b99d43fbb/pyobjc_framework_mailkit-11.1.tar.gz", hash = "sha256:bf97dc44cb09b9eb9d591660dc0a41f077699976144b954caa4b9f0479211fd7", size = 32012, upload-time = "2025-06-14T20:57:49.173Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/bf/23/1897fc071e8e71bc0bef53bcb0d600eb1ed3bd6c4609f7257ddfe151d37a/pyobjc_framework_mailkit-11.1-py2.py3-none-any.whl", hash = "sha256:8e6026462567baba194468e710e83787f29d9e8c98ea0583f7b401ea9515966e", size = 4854, upload-time = "2025-06-14T20:51:18.978Z" }, -] - -[[package]] -name = "pyobjc-framework-mapkit" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-corelocation" }, - { name = "pyobjc-framework-quartz" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/57/f0/505e074f49c783f2e65ca82174fd2d4348568f3f7281c1b81af816cf83bb/pyobjc_framework_mapkit-11.1.tar.gz", hash = "sha256:f3a5016f266091be313a118a42c0ea4f951c399b5259d93639eb643dacc626f1", size = 165614, upload-time = "2025-06-14T20:57:50.362Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/a0/dc/a7e03a9066e6eed9d1707ae45453a5332057950e16de6665402c804ae7af/pyobjc_framework_mapkit-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:daee6bedc3acc23e62d1e7c3ab97e10425ca57e0c3cc47d2b212254705cc5c44", size = 22481, upload-time = "2025-06-14T20:51:20.694Z" }, - { url = "https://files.pythonhosted.org/packages/30/0a/50aa2fba57499ff657cacb9ef1730006442e4f42d9a822dae46239603ecc/pyobjc_framework_mapkit-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:91976c6dbc8cbb020e059a0ccdeab8933184712f77164dbad5a5526c1a49599d", size = 22515, upload-time = "2025-06-14T20:51:21.439Z" }, -] - -[[package]] -name = "pyobjc-framework-mediaaccessibility" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/8d/81/60412b423c121de0fa0aa3ef679825e1e2fe8b00fceddec7d72333ef564b/pyobjc_framework_mediaaccessibility-11.1.tar.gz", hash = "sha256:52479a998fec3d079d2d4590a945fc78c41fe7ac8c76f1964c9d8156880565a4", size = 18440, upload-time = "2025-06-14T20:57:51.126Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/99/a1/f4cbdf8478ad01859e2c8eef08e28b8a53b9aa4fe5d238a86bad29b73555/pyobjc_framework_mediaaccessibility-11.1-py2.py3-none-any.whl", hash = "sha256:cd07e7fc375ff1e8d225e0aa2bd9c2c1497a4d3aa5a80bfb13b08800fcd7f034", size = 4691, upload-time = "2025-06-14T20:51:26.596Z" }, -] - -[[package]] -name = "pyobjc-framework-mediaextension" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-avfoundation" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-coremedia" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/e1/09/fd214dc0cf3f3bc3f528815af4799c0cb7b4bf4032703b19ea63486a132b/pyobjc_framework_mediaextension-11.1.tar.gz", hash = "sha256:85a1c8a94e9175fb364c453066ef99b95752343fd113f08a3805cad56e2fa709", size = 58489, upload-time = "2025-06-14T20:57:51.796Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/ec/25/95315f730e9b73ef9e8936ed3ded636d3ac71b4d5653d4caf1d20a2314a8/pyobjc_framework_mediaextension-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:915c0cbb04913beb1f1ac8939dc0e615da8ddfba3927863a476af49f193415c5", size = 38858, upload-time = "2025-06-14T20:51:28.296Z" }, - { url = "https://files.pythonhosted.org/packages/56/78/2c2d8265851f6060dbf4434c21bd67bf569b8c3071ba1f257e43aae563a8/pyobjc_framework_mediaextension-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:06cb19004413a4b08dd75cf1e5dadea7f2df8d15feeeb7adb529d0cf947fa789", size = 38859, upload-time = "2025-06-14T20:51:29.102Z" }, -] - -[[package]] -name = "pyobjc-framework-medialibrary" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-quartz" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/2b/06/11ff622fb5fbdd557998a45cedd2b0a1c7ea5cc6c5cb015dd6e42ebd1c41/pyobjc_framework_medialibrary-11.1.tar.gz", hash = "sha256:102f4326f789734b7b2dfe689abd3840ca75a76fb8058bd3e4f85398ae2ce29d", size = 18706, upload-time = "2025-06-14T20:57:52.474Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/62/2b/a4200080d97f88fdd406119bb8f00ccb7f32794f84735485510c14e87e76/pyobjc_framework_medialibrary-11.1-py2.py3-none-any.whl", hash = "sha256:779be84bd280f63837ce02028ca46b41b090902aa4205887ffd5777f49377669", size = 4340, upload-time = "2025-06-14T20:51:34.339Z" }, -] - -[[package]] -name = "pyobjc-framework-mediaplayer" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-avfoundation" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/80/d5/daba26eb8c70af1f3823acfd7925356acc4dd75eeac4fc86dc95d94d0e15/pyobjc_framework_mediaplayer-11.1.tar.gz", hash = "sha256:d07a634b98e1b9eedd82d76f35e616525da096bd341051ea74f0971e0f2f2ddd", size = 93749, upload-time = "2025-06-14T20:57:53.165Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/2b/aa/b37aac80d821bd2fa347ddad1f6c7c75b23155e500edf1cb3b3740c27036/pyobjc_framework_mediaplayer-11.1-py2.py3-none-any.whl", hash = "sha256:b655cf537ea52d73209eb12935a047301c30239b318a366600f0f44335d51c9a", size = 6960, upload-time = "2025-06-14T20:51:35.171Z" }, -] - -[[package]] -name = "pyobjc-framework-mediatoolbox" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/e1/68/cc230d2dfdeb974fdcfa828de655a43ce2bf4962023fd55bbb7ab0970100/pyobjc_framework_mediatoolbox-11.1.tar.gz", hash = "sha256:97834addc5179b3165c0d8cd74cc97ad43ed4c89547724216426348aca3b822a", size = 23568, upload-time = "2025-06-14T20:57:53.913Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/99/bc/6b69ca3c2bf1573b907be460c6a413ff2dfd1c037da53f46aec3bcdb3c73/pyobjc_framework_mediatoolbox-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:da60c0409b18dfb9fa60a60589881e1382c007700b99722926270feadcf3bfc1", size = 12630, upload-time = "2025-06-14T20:51:36.873Z" }, - { url = "https://files.pythonhosted.org/packages/b5/23/6b5d999e1e71c42d5d116d992515955ac1bbc5cf4890072bb26f38eb9802/pyobjc_framework_mediatoolbox-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:2867c91645a335ee29b47e9c0e9fd3ea8c9daad0c0719c50b8bf244d76998056", size = 12785, upload-time = "2025-06-14T20:51:37.593Z" }, -] - -[[package]] -name = "pyobjc-framework-metal" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/af/cf/29fea96fd49bf72946c5dac4c43ef50f26c15e9f76edd6f15580d556aa23/pyobjc_framework_metal-11.1.tar.gz", hash = "sha256:f9fd3b7574a824632ee9b7602973da30f172d2b575dd0c0f5ef76b44cfe9f6f9", size = 446549, upload-time = "2025-06-14T20:57:54.731Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/e9/e8/cd0621e246dc0dc06f55c50af3002573ad19208e30f6806ec997ac587886/pyobjc_framework_metal-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:157a0052be459ffb35a3687f77a96ea87b42caf4cdd0b9f7245242b100edb4f0", size = 58066, upload-time = "2025-06-14T20:51:44.243Z" }, - { url = "https://files.pythonhosted.org/packages/4c/94/3d5a8bed000dec4a13e72dde175898b488192716b7256a05cc253c77020d/pyobjc_framework_metal-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:1f3aae0f9a4192a7f4f158dbee126ab5ef63a81bf9165ec63bc50c353c8d0e6f", size = 57969, upload-time = "2025-06-14T20:51:45.051Z" }, -] - -[[package]] -name = "pyobjc-framework-metalfx" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-metal" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/10/20/4c839a356b534c161fb97e06589f418fc78cc5a0808362bdecf4f9a61a8d/pyobjc_framework_metalfx-11.1.tar.gz", hash = "sha256:555c1b895d4ba31be43930f45e219a5d7bb0e531d148a78b6b75b677cc588fd8", size = 27002, upload-time = "2025-06-14T20:57:55.949Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/a2/f5/df29eeaaf053cd931fb74204a5f8827f88875a81c456b1e0fa24ea0bbcee/pyobjc_framework_metalfx-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:cbfca74f437fcde89de85d14de33c2e617d3084f5fc2b4d614a700e516324f55", size = 10091, upload-time = "2025-06-14T20:51:51.084Z" }, - { url = "https://files.pythonhosted.org/packages/36/73/a8df8fa445a09fbc917a495a30b13fbcf224b5576c1e464d5ece9824a493/pyobjc_framework_metalfx-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:60e1dcdf133d2504d810c3a9ba5a02781c9d54c2112a9238de8e3ca4e8debf31", size = 10107, upload-time = "2025-06-14T20:51:51.783Z" }, -] - -[[package]] -name = "pyobjc-framework-metalkit" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-metal" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/45/cb/7e01bc61625c7a6fea9c9888c9ed35aa6bbc47cda2fcd02b6525757bc2b8/pyobjc_framework_metalkit-11.1.tar.gz", hash = "sha256:8811cd81ee9583b9330df4f2499a73dcc53f3359cb92767b409acaec9e4faa1e", size = 45135, upload-time = "2025-06-14T20:57:56.601Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/2a/eb/fd5640015fc91b16e23cafe3a84508775344cd13f621e62b9c32d1750a83/pyobjc_framework_metalkit-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:95abb993d17be7a9d1174701594cc040e557983d0a0e9f49b1dfa9868ef20ed6", size = 8711, upload-time = "2025-06-14T20:51:56.765Z" }, - { url = "https://files.pythonhosted.org/packages/87/0c/516b6d7a67a170b7d2316701d5288797a19dd283fcc2f73b7b78973e1392/pyobjc_framework_metalkit-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:4854cf74fccf6ce516b49bf7cf8fc7c22da9a3743914a2f4b00f336206ad47ec", size = 8730, upload-time = "2025-06-14T20:51:57.824Z" }, -] - -[[package]] -name = "pyobjc-framework-metalperformanceshaders" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-metal" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/d0/11/5df398a158a6efe2c87ac5cae121ef2788242afe5d4302d703147b9fcd91/pyobjc_framework_metalperformanceshaders-11.1.tar.gz", hash = "sha256:8a312d090a0f51651e63d9001e6cc7c1aa04ceccf23b494cbf84b7fd3d122071", size = 302113, upload-time = "2025-06-14T20:57:57.407Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/64/ce/bbcf26f8aa94fb6edcf1a71ef23cd8df2afd4b5c2be451432211827c2ab0/pyobjc_framework_metalperformanceshaders-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:81ec1f85c55d11529008e6a0fb1329d5184620f04d89751c11bf14d7dd9798ee", size = 32650, upload-time = "2025-06-14T20:52:04.451Z" }, - { url = "https://files.pythonhosted.org/packages/89/df/f844516a54ef0fa1d047fe5fd94b63bc8b1218c09f7d4309b2a67a79708d/pyobjc_framework_metalperformanceshaders-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:06b2a4e446fe859e30f7efc7ccfbaefd443225a6ec53d949a113a6a4acc16c4c", size = 32888, upload-time = "2025-06-14T20:52:05.225Z" }, -] - -[[package]] -name = "pyobjc-framework-metalperformanceshadersgraph" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-metalperformanceshaders" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/32/c3/8d98661f7eecd1f1b0d80a80961069081b88efd3a82fbbed2d7e6050c0ad/pyobjc_framework_metalperformanceshadersgraph-11.1.tar.gz", hash = "sha256:d25225aab4edc6f786b29fe3d9badc4f3e2d0caeab1054cd4f224258c1b6dbe2", size = 105098, upload-time = "2025-06-14T20:57:58.273Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/0d/a1/2033cf8b0d9f059e3495a1d9a691751b242379c36dd5bcb96c8edb121c9e/pyobjc_framework_metalperformanceshadersgraph-11.1-py2.py3-none-any.whl", hash = "sha256:9b8b014e8301c2ae608a25f73bbf23c8f3f73a6f5fdbafddad509a21b84df681", size = 6461, upload-time = "2025-06-14T20:52:10.522Z" }, -] - -[[package]] -name = "pyobjc-framework-metrickit" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/bd/48/8ae969a51a91864000e39c1de74627b12ff587b1dbad9406f7a30dfe71f8/pyobjc_framework_metrickit-11.1.tar.gz", hash = "sha256:a79d37575489916c35840e6a07edd958be578d3be7a3d621684d028d721f0b85", size = 40952, upload-time = "2025-06-14T20:57:58.996Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/3b/cd/e459511c194d25c4acd31cbdb5c118215795785840861d55dbc8bd55cf35/pyobjc_framework_metrickit-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:a5d2b394f7acadd17d8947d188106424f59393b45dd4a842ac3cc50935170e3e", size = 8063, upload-time = "2025-06-14T20:52:12.696Z" }, - { url = "https://files.pythonhosted.org/packages/55/d1/aea4655e7eaa9ab19da8fe78ab363270443059c8a542b8f8a071b4988b57/pyobjc_framework_metrickit-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:a034e6b982e915da881edef87d71b063e596511d52aef7a32c683571f364156e", size = 8081, upload-time = "2025-06-14T20:52:13.72Z" }, -] - -[[package]] -name = "pyobjc-framework-mlcompute" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/8b/e6/f064dec650fb1209f41aba0c3074416cb9b975a7cf4d05d93036e3d917f0/pyobjc_framework_mlcompute-11.1.tar.gz", hash = "sha256:f6c4c3ea6a62e4e3927abf9783c40495aa8bb9a8c89def744b0822da58c2354b", size = 89021, upload-time = "2025-06-14T20:57:59.997Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/23/cc/f47a4ac2d1a792b82206fdab58cc61b3aae15e694803ea2c81f3dfc16d9d/pyobjc_framework_mlcompute-11.1-py2.py3-none-any.whl", hash = "sha256:975150725e919f8d3d33f830898f3cd2fd19a440999faab320609487f4eae19d", size = 6778, upload-time = "2025-06-14T20:52:19.844Z" }, -] - -[[package]] -name = "pyobjc-framework-modelio" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-quartz" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/a0/27/140bf75706332729de252cc4141e8c8afe16a0e9e5818b5a23155aa3473c/pyobjc_framework_modelio-11.1.tar.gz", hash = "sha256:fad0fa2c09d468ac7e49848e144f7bbce6826f2178b3120add8960a83e5bfcb7", size = 123203, upload-time = "2025-06-14T20:58:01.035Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/6c/66/8109e52c7d97a108d4852a2032c9d7a7ecd27c6085bd7b2920b2ab575df4/pyobjc_framework_modelio-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:4365fb96eb42b71c12efdfa2ff9d44755d5c292b8d1c78b947833d84271e359f", size = 20142, upload-time = "2025-06-14T20:52:21.582Z" }, - { url = "https://files.pythonhosted.org/packages/18/84/5f223b82894777388ef1aa09579d9c044044877a72075213741c97adc901/pyobjc_framework_modelio-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:5d5e11389bde0852490b2a37896aaf9eb674b2a3586f2c572f9101cecb7bc576", size = 20172, upload-time = "2025-06-14T20:52:22.327Z" }, -] - -[[package]] -name = "pyobjc-framework-multipeerconnectivity" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/73/99/75bf6170e282d9e546b353b65af7859de8b1b27ddc431fc4afbf15423d01/pyobjc_framework_multipeerconnectivity-11.1.tar.gz", hash = "sha256:a3dacca5e6e2f1960dd2d1107d98399ff81ecf54a9852baa8ec8767dbfdbf54b", size = 26149, upload-time = "2025-06-14T20:58:01.793Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/8d/fc/a3fc2514879a39673202f7ea5e835135255c5e510d30c58a43239ec1d9e0/pyobjc_framework_multipeerconnectivity-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:b3c9d4d36e0c142b4ce91033740ed5bca19fe7ec96870d90610d2942ecd3cd39", size = 11955, upload-time = "2025-06-14T20:52:28.392Z" }, - { url = "https://files.pythonhosted.org/packages/b4/fe/5c29c227f6ed81147ec6ec3e681fc680a7ffe0360f96901371435ea68570/pyobjc_framework_multipeerconnectivity-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:970031deb3dbf8da1fcb04e785d4bd2eeedae8f6677db92881df6d92b05c31d6", size = 11981, upload-time = "2025-06-14T20:52:29.406Z" }, -] - -[[package]] -name = "pyobjc-framework-naturallanguage" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/a2/e9/5352fbf09c5d5360405dea49fb77e53ed55acd572a94ce9a0d05f64d2b70/pyobjc_framework_naturallanguage-11.1.tar.gz", hash = "sha256:ab1fc711713aa29c32719774fc623bf2d32168aed21883970d4896e901ff4b41", size = 46120, upload-time = "2025-06-14T20:58:02.808Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/4b/f2/de86665d48737c74756b016c0f3bf93c99ca4151b48b14e2fbe7233283f8/pyobjc_framework_naturallanguage-11.1-py2.py3-none-any.whl", hash = "sha256:65a780273d2cdd12a3fa304e9c9ad822cb71facd9281f1b35a71640c53826f7c", size = 5306, upload-time = "2025-06-14T20:52:34.024Z" }, -] - -[[package]] -name = "pyobjc-framework-netfs" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/68/5d/d68cc59a1c1ea61f227ed58e7b185a444d560655320b53ced155076f5b78/pyobjc_framework_netfs-11.1.tar.gz", hash = "sha256:9c49f050c8171dc37e54d05dd12a63979c8b6b565c10f05092923a2250446f50", size = 15910, upload-time = "2025-06-14T20:58:03.811Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/77/cc/199b06f214f8a2db26eb47e3ab7015a306597a1bca25dcb4d14ddc65bd4a/pyobjc_framework_netfs-11.1-py2.py3-none-any.whl", hash = "sha256:f202e8e0c2e73516d3eac7a43b1c66f9911cdbb37ea32750ed197d82162c994a", size = 4143, upload-time = "2025-06-14T20:52:35.428Z" }, -] - -[[package]] -name = "pyobjc-framework-network" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/0a/ee/5ea93e48eca341b274027e1532bd8629fd55d609cd9c39c2c3acf26158c3/pyobjc_framework_network-11.1.tar.gz", hash = "sha256:f6df7a58a1279bbc976fd7e2efe813afbbb18427df40463e6e2ee28fba07d2df", size = 124670, upload-time = "2025-06-14T20:58:05.491Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/17/e9/a54f32daa0365bf000b739fc386d4783432273a9075337aa57a3808af65d/pyobjc_framework_network-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:e56691507584c09cdb50f1cd69b5f57b42fd55c396e8c34fab8c5b81b44d36ed", size = 19499, upload-time = "2025-06-14T20:52:37.158Z" }, - { url = "https://files.pythonhosted.org/packages/15/c2/3c6626fdb3616fde2c173d313d15caea22d141abcc2fbf3b615f8555abe3/pyobjc_framework_network-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:8cdc9be8ec3b0ae95e5c649e4bbcdf502cffd357dacc566223be707bdd5ac271", size = 19513, upload-time = "2025-06-14T20:52:38.423Z" }, -] - -[[package]] -name = "pyobjc-framework-networkextension" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/71/30/d1eee738d702bbca78effdaa346a2b05359ab8a96d961b7cb44838e236ca/pyobjc_framework_networkextension-11.1.tar.gz", hash = "sha256:2b74b430ca651293e5aa90a1e7571b200d0acbf42803af87306ac8a1c70b0d4b", size = 217252, upload-time = "2025-06-14T20:58:06.311Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/76/d7/b10aa191d37900ade78f1b7806d17ff29fa95f40ce7aeecce6f15ec94ac9/pyobjc_framework_networkextension-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:55e5ca70c81a864896b603cfcabf4c065783f64395460d16fe16db2bf0866d60", size = 14101, upload-time = "2025-06-14T20:52:44.527Z" }, - { url = "https://files.pythonhosted.org/packages/b6/26/526cd9f63e390e9c2153c41dc0982231b0b1ca88865deb538b77e1c3513d/pyobjc_framework_networkextension-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:853458aae8b43634461f6c44759750e2dc784c9aba561f9468ab14529b5a7fbe", size = 14114, upload-time = "2025-06-14T20:52:45.274Z" }, -] - -[[package]] -name = "pyobjc-framework-notificationcenter" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/a8/4a/d3529b9bd7aae2c89d258ebc234673c5435e217a5136abd8c0aba37b916b/pyobjc_framework_notificationcenter-11.1.tar.gz", hash = "sha256:0b938053f2d6b1cea9db79313639d7eb9ddd5b2a5436a346be0887e75101e717", size = 23389, upload-time = "2025-06-14T20:58:07.136Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/ea/ed/3beb825e2b80de45b90e7cd510ad52890ac4a5a4de88cd9a5291235519fb/pyobjc_framework_notificationcenter-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:3d44413818e7fa3662f784cdcf0730c86676dd7333b7d24a7da13d4ffcde491b", size = 9859, upload-time = "2025-06-14T20:52:51.744Z" }, - { url = "https://files.pythonhosted.org/packages/6d/92/cd00fe5e54a191fb77611fe728a8c8a0a6edb229857d32f27806582406ca/pyobjc_framework_notificationcenter-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:65fc67374a471890245c7a1d60cf67dcf160075a9c048a5d89608a8290f33b03", size = 9880, upload-time = "2025-06-14T20:52:52.406Z" }, -] - -[[package]] -name = "pyobjc-framework-opendirectory" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/9d/02/ac56c56fdfbc24cdf87f4a624f81bbe2e371d0983529b211a18c6170e932/pyobjc_framework_opendirectory-11.1.tar.gz", hash = "sha256:319ac3424ed0350be458b78148914468a8fc13a069d62e7869e3079108e4f118", size = 188880, upload-time = "2025-06-14T20:58:08.003Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/06/56/f0f5b7222d5030192c44010ab7260681e349efea2f1b1b9f116ba1951d6d/pyobjc_framework_opendirectory-11.1-py2.py3-none-any.whl", hash = "sha256:bb4219b0d98dff4a952c50a79b1855ce74e1defd0d241f3013def5b09256fd7b", size = 11829, upload-time = "2025-06-14T20:52:56.715Z" }, -] - -[[package]] -name = "pyobjc-framework-osakit" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/56/22/f9cdfb5de255b335f99e61a3284be7cb1552a43ed1dfe7c22cc868c23819/pyobjc_framework_osakit-11.1.tar.gz", hash = "sha256:920987da78b67578367c315d208f87e8fab01dd35825d72242909f29fb43c820", size = 22290, upload-time = "2025-06-14T20:58:09.103Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/14/65/c6531ce0792d5035d87f054b0ccf22e453328fda2e68e11a7f70486da23a/pyobjc_framework_osakit-11.1-py2.py3-none-any.whl", hash = "sha256:1b0c0cc537ffb8a8365ef9a8b46f717a7cc2906414b6a3983777a6c0e4d53d5a", size = 4143, upload-time = "2025-06-14T20:52:57.555Z" }, -] - -[[package]] -name = "pyobjc-framework-oslog" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-coremedia" }, - { name = "pyobjc-framework-quartz" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/79/93/3feb7f6150b50165524750a424f5434448392123420cb4673db766c3f54a/pyobjc_framework_oslog-11.1.tar.gz", hash = "sha256:b2af409617e6b68fa1f1467c5a5679ebf59afd0cdc4b4528e1616059959a7979", size = 24689, upload-time = "2025-06-14T20:58:09.739Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/66/7a/2db26fc24e16c84312a0de432bab16ca586223fd6c5ba08e49c192ae95f6/pyobjc_framework_oslog-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:5dab25ef1cde4237cd2957c1f61c2888968e924304f7b9d9699eceeb330e9817", size = 7793, upload-time = "2025-06-14T20:52:59.132Z" }, - { url = "https://files.pythonhosted.org/packages/40/da/fd3bd62899cd679743056aa2c28bc821c2688682a17ddde1a08d6d9d67fc/pyobjc_framework_oslog-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:7ae29c31ce51c476d3a37ca303465dd8bdfa98df2f6f951cf14c497e984a1ba9", size = 7799, upload-time = "2025-06-14T20:52:59.935Z" }, -] - -[[package]] -name = "pyobjc-framework-passkit" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/5c/05/063db500e7df70e39cbb5518a5a03c2acc06a1ca90b057061daea00129f3/pyobjc_framework_passkit-11.1.tar.gz", hash = "sha256:d2408b58960fca66607b483353c1ffbd751ef0bef394a1853ec414a34029566f", size = 144859, upload-time = "2025-06-14T20:58:10.761Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/80/18/343eb846e62704fbd64e178e0cbf75b121955c1973bf51ddd0871a42910a/pyobjc_framework_passkit-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:67b7b1ee9454919c073c2cba7bdba444a766a4e1dd15a5e906f4fa0c61525347", size = 13949, upload-time = "2025-06-14T20:53:04.98Z" }, - { url = "https://files.pythonhosted.org/packages/9d/ba/9e52213e0c0100079e4ef397cf4fd5ba8939fa4de19339755d1a373407a8/pyobjc_framework_passkit-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:779eaea4e1931cfda4c8701e1111307b14bf9067b359a319fc992b6848a86932", size = 13959, upload-time = "2025-06-14T20:53:05.694Z" }, -] - -[[package]] -name = "pyobjc-framework-pencilkit" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/75/d0/bbbe9dadcfc37e33a63d43b381a8d9a64eca27559df38efb74d524fa6260/pyobjc_framework_pencilkit-11.1.tar.gz", hash = "sha256:9c173e0fe70179feadc3558de113a8baad61b584fe70789b263af202bfa4c6be", size = 22570, upload-time = "2025-06-14T20:58:11.538Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/a3/f6/59ffc3f26ea9cfda4d40409f9afc2a38e5c0c6a68a3a8c9202e8b98b03b1/pyobjc_framework_pencilkit-11.1-py2.py3-none-any.whl", hash = "sha256:b7824907bbcf28812f588dda730e78f662313baf40befd485c6f2fcb49018019", size = 4026, upload-time = "2025-06-14T20:53:10.449Z" }, -] - -[[package]] -name = "pyobjc-framework-phase" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-avfoundation" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/c6/d2/e9384b5b3fbcc79e8176cb39fcdd48b77f60cd1cb64f9ee4353762b037dc/pyobjc_framework_phase-11.1.tar.gz", hash = "sha256:a940d81ac5c393ae3da94144cf40af33932e0a9731244e2cfd5c9c8eb851e3fc", size = 58986, upload-time = "2025-06-14T20:58:12.196Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/f5/9e/55782f02b3bfb58f030b062176e8b0dba5f8fbd6e50d27a687f559c4179d/pyobjc_framework_phase-11.1-py2.py3-none-any.whl", hash = "sha256:cfa61f9c6c004161913946501538258aed48c448b886adbf9ed035957d93fa15", size = 6822, upload-time = "2025-06-14T20:53:11.618Z" }, -] - -[[package]] -name = "pyobjc-framework-photos" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/78/b0/576652ecd05c26026ab4e75e0d81466edd570d060ce7df3d6bd812eb90d0/pyobjc_framework_photos-11.1.tar.gz", hash = "sha256:c8c3b25b14a2305047f72c7c081ff3655b3d051f7ed531476c03246798f8156d", size = 92569, upload-time = "2025-06-14T20:58:12.939Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/df/25/ec3b0234d20948816791399e580f6dd83c0d50a24219c954708f755742c4/pyobjc_framework_photos-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:959dfc82f20513366b85cd37d8541bb0a6ab4f3bfa2f8094e9758a5245032d67", size = 12198, upload-time = "2025-06-14T20:53:13.563Z" }, - { url = "https://files.pythonhosted.org/packages/fa/24/2400e6b738d3ed622c61a7cc6604eec769f398071a1eb6a16dfdf3a9ceea/pyobjc_framework_photos-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:8dbfffd29cfa63a8396ede0030785c15a5bc36065d3dd98fc6176a59e7abb3d3", size = 12224, upload-time = "2025-06-14T20:53:14.793Z" }, -] - -[[package]] -name = "pyobjc-framework-photosui" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/20/bb/e6de720efde2e9718677c95c6ae3f97047be437cda7a0f050cd1d6d2a434/pyobjc_framework_photosui-11.1.tar.gz", hash = "sha256:1c7ffab4860ce3e2b50feeed4f1d84488a9e38546db0bec09484d8d141c650df", size = 48443, upload-time = "2025-06-14T20:58:13.626Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/af/c1/3d67c2af53fe91feb6f64dbc501bbcfd5d325b7f0f0ffffd5d033334cb03/pyobjc_framework_photosui-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:d93722aeb8c134569035fd7e6632d0247e1bcb18c3cc4e0a288664218f241b85", size = 11667, upload-time = "2025-06-14T20:53:20.464Z" }, - { url = "https://files.pythonhosted.org/packages/f8/c1/a5c84c1695e7a066743d63d10b219d94f3c07d706871682e42f7db389f5c/pyobjc_framework_photosui-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:b2f278f569dfd596a32468351411518a651d12cb91e60620094e852c525a5f10", size = 11682, upload-time = "2025-06-14T20:53:21.162Z" }, -] - -[[package]] -name = "pyobjc-framework-preferencepanes" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/34/ac/9324602daf9916308ebf1935b8a4b91c93b9ae993dcd0da731c0619c2836/pyobjc_framework_preferencepanes-11.1.tar.gz", hash = "sha256:6e4a55195ec9fc921e0eaad6b3038d0ab91f0bb2f39206aa6fccd24b14a0f1d8", size = 26212, upload-time = "2025-06-14T20:58:14.361Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/a1/51/75c7e32272241f706ce8168e04a32be02c4b0c244358330f730fc85695c3/pyobjc_framework_preferencepanes-11.1-py2.py3-none-any.whl", hash = "sha256:6ee5f5a7eb294e03ea3bac522ac4b69e6dc83ceceff627a0a2d289afe1e01ad9", size = 4786, upload-time = "2025-06-14T20:53:25.603Z" }, -] - -[[package]] -name = "pyobjc-framework-pushkit" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/9f/f0/92d0eb26bf8af8ebf6b5b88df77e70b807de11f01af0162e0a429fcfb892/pyobjc_framework_pushkit-11.1.tar.gz", hash = "sha256:540769a4aadc3c9f08beca8496fe305372501eb28fdbca078db904a07b8e10f4", size = 21362, upload-time = "2025-06-14T20:58:15.642Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/d9/dc/415d6d7e3ed04d8b2f8dc6d458e7c6db3f503737b092d71b4856bf1607f7/pyobjc_framework_pushkit-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:5e2f08b667035df6b11a0a26f038610df1eebbedf9f3f111c241b5afaaf7c5fd", size = 8149, upload-time = "2025-06-14T20:53:28.096Z" }, - { url = "https://files.pythonhosted.org/packages/31/65/260014c5d13c54bd359221b0a890cbffdb99eecff3703f253cf648e45036/pyobjc_framework_pushkit-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:21993b7e9127b05575a954faa68e85301c6a4c04e34e38aff9050f67a05c562a", size = 8174, upload-time = "2025-06-14T20:53:28.805Z" }, -] - -[[package]] -name = "pyobjc-framework-quartz" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/c7/ac/6308fec6c9ffeda9942fef72724f4094c6df4933560f512e63eac37ebd30/pyobjc_framework_quartz-11.1.tar.gz", hash = "sha256:a57f35ccfc22ad48c87c5932818e583777ff7276605fef6afad0ac0741169f75", size = 3953275, upload-time = "2025-06-14T20:58:17.924Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/77/cb/38172fdb350b3f47e18d87c5760e50f4efbb4da6308182b5e1310ff0cde4/pyobjc_framework_quartz-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:2d501fe95ef15d8acf587cb7dc4ab4be3c5a84e2252017da8dbb7df1bbe7a72a", size = 215565, upload-time = "2025-06-14T20:53:35.262Z" }, - { url = "https://files.pythonhosted.org/packages/9b/37/ee6e0bdd31b3b277fec00e5ee84d30eb1b5b8b0e025095e24ddc561697d0/pyobjc_framework_quartz-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:9ac806067541917d6119b98d90390a6944e7d9bd737f5c0a79884202327c9204", size = 216410, upload-time = "2025-06-14T20:53:36.346Z" }, -] - -[[package]] -name = "pyobjc-framework-quicklookthumbnailing" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-quartz" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/aa/98/6e87f360c2dfc870ae7870b8a25fdea8ddf1d62092c755686cebe7ec1a07/pyobjc_framework_quicklookthumbnailing-11.1.tar.gz", hash = "sha256:1614dc108c1d45bbf899ea84b8691288a5b1d25f2d6f0c57dfffa962b7a478c3", size = 16527, upload-time = "2025-06-14T20:58:20.811Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/65/4a/ddc35bdcd44278f22df2154a52025915dba6c80d94e458d92e9e7430d1e4/pyobjc_framework_quicklookthumbnailing-11.1-py2.py3-none-any.whl", hash = "sha256:4d1863c6c83c2a199c1dbe704b4f8b71287168f4090ed218d37dc59277f0d9c9", size = 4219, upload-time = "2025-06-14T20:53:43.198Z" }, -] - -[[package]] -name = "pyobjc-framework-replaykit" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/c8/4f/014e95f0fd6842d7fcc3d443feb6ee65ac69d06c66ffa9327fc33ceb7c27/pyobjc_framework_replaykit-11.1.tar.gz", hash = "sha256:6919baa123a6d8aad769769fcff87369e13ee7bae11b955a8185a406a651061b", size = 26132, upload-time = "2025-06-14T20:58:21.853Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/72/97/2b4fbd52c6727977c0fdbde2b4a15226a9beb836248c289781e4129394e4/pyobjc_framework_replaykit-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:4d88c3867349865d8a3a06ea064f15aed7e5be20d22882ac8a647d9b6959594e", size = 10066, upload-time = "2025-06-14T20:53:45.555Z" }, - { url = "https://files.pythonhosted.org/packages/b9/73/846cebb36fc279df18f10dc3a27cba8fe2e47e95350a3651147e4d454719/pyobjc_framework_replaykit-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:22c6d09be9a6e758426d723a6c3658ad6bbb66f97ba9a1909bfcf29a91d99921", size = 10087, upload-time = "2025-06-14T20:53:46.242Z" }, -] - -[[package]] -name = "pyobjc-framework-safariservices" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/1a/fc/c47d2abf3c1de6db21d685cace76a0931d594aa369e3d090260295273f6e/pyobjc_framework_safariservices-11.1.tar.gz", hash = "sha256:39a17df1a8e1c339457f3acbff0dc0eae4681d158f9d783a11995cf484aa9cd0", size = 34905, upload-time = "2025-06-14T20:58:22.492Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/c9/aa/0c9f3456a57dbee711210a0ac3fe58aff9bf881ab7c65727b885193eb8af/pyobjc_framework_safariservices-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:a441a2e99f7d6475bea00c3d53de924143b8f90052be226aee16f1f6d9cfdc8c", size = 7262, upload-time = "2025-06-14T20:53:52.057Z" }, - { url = "https://files.pythonhosted.org/packages/d7/13/9636e9d3dc362daaaa025b2aa4e28606a1e197dfc6506d3a246be8315f8a/pyobjc_framework_safariservices-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:c92eb9e35f98368ea1bfaa8cdd41138ca8b004ea5a85833390a44e5626ca5061", size = 7275, upload-time = "2025-06-14T20:53:53.075Z" }, -] - -[[package]] -name = "pyobjc-framework-safetykit" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-quartz" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/28/cc/f6aa5d6f45179bd084416511be4e5b0dd0752cb76daa93869e6edb806096/pyobjc_framework_safetykit-11.1.tar.gz", hash = "sha256:c6b44e0cf69e27584ac3ef3d8b771d19a7c2ccd9c6de4138d091358e036322d4", size = 21240, upload-time = "2025-06-14T20:58:23.132Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/a3/ad/1e9c661510cc4cd96f2beffc7ba39af36064c742e265303c689e85aaa0ad/pyobjc_framework_safetykit-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:3333e8e53a1e8c8133936684813a2254e5d1b4fe313333a3d0273e31b9158cf7", size = 8513, upload-time = "2025-06-14T20:53:58.413Z" }, - { url = "https://files.pythonhosted.org/packages/9c/8f/6f4c833e31526a81faef9bf19695b332ba8d2fa53d92640abd6fb3ac1d78/pyobjc_framework_safetykit-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:b76fccdb970d3d751a540c47712e9110afac9abea952cb9b7bc0d5867db896e3", size = 8523, upload-time = "2025-06-14T20:53:59.443Z" }, -] - -[[package]] -name = "pyobjc-framework-scenekit" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-quartz" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/64/cf/2d89777120d2812e7ee53c703bf6fc8968606c29ddc1351bc63f0a2a5692/pyobjc_framework_scenekit-11.1.tar.gz", hash = "sha256:82941f1e5040114d6e2c9fd35507244e102ef561c637686091b71a7ad0f31306", size = 214118, upload-time = "2025-06-14T20:58:24.003Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/51/46/d011b5a88e45d78265f5df144759ff57e50d361d44c9adb68c2fb58b276d/pyobjc_framework_scenekit-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:3e777dacb563946ad0c2351e6cfe3f16b8587a65772ec0654e2be9f75764d234", size = 33490, upload-time = "2025-06-14T20:54:04.845Z" }, - { url = "https://files.pythonhosted.org/packages/e0/f9/bdcd8a4bc6c387ef07f3e2190cea6a03d4f7ed761784f492b01323e8d900/pyobjc_framework_scenekit-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:c803d95b30c4ce49f46ff7174806f5eb84e4c3a152f8f580c5da0313c5c67041", size = 33558, upload-time = "2025-06-14T20:54:05.59Z" }, -] - -[[package]] -name = "pyobjc-framework-screencapturekit" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-coremedia" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/32/a5/9bd1f1ad1773a1304ccde934ff39e0f0a0b0034441bf89166aea649606de/pyobjc_framework_screencapturekit-11.1.tar.gz", hash = "sha256:11443781a30ed446f2d892c9e6642ca4897eb45f1a1411136ca584997fa739e0", size = 53548, upload-time = "2025-06-14T20:58:24.837Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/7e/e0/fd1957e962c4a1624171dbbda4e425615848a7bcc9b45a524018dc449874/pyobjc_framework_screencapturekit-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:7203108d28d7373501c455cd4a8bbcd2eb7849906dbc7859ac17a350b141553c", size = 11280, upload-time = "2025-06-14T20:54:11.699Z" }, - { url = "https://files.pythonhosted.org/packages/98/37/840f306dcf01dd2bd092ae8dcf371a3bad3a0f88f0780d0840f899a8c047/pyobjc_framework_screencapturekit-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:641fa7834f54558859209e174c83551d5fa239ca6943ace52665f7d45e562ff2", size = 11308, upload-time = "2025-06-14T20:54:12.382Z" }, -] - -[[package]] -name = "pyobjc-framework-screensaver" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/7c/f6/f2d48583b29fc67b64aa1f415fd51faf003d045cdb1f3acab039b9a3f59f/pyobjc_framework_screensaver-11.1.tar.gz", hash = "sha256:d5fbc9dc076cc574ead183d521840b56be0c160415e43cb8e01cfddd6d6372c2", size = 24302, upload-time = "2025-06-14T20:58:25.52Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/f0/8c/2236e5796f329a92ce7664036da91e91d63d86217972dc2939261ce88dde/pyobjc_framework_screensaver-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:8b959761fddf06d9fb3fed6cd0cea6009d60473317e11490f66dcf0444011d5f", size = 8466, upload-time = "2025-06-14T20:54:18.329Z" }, - { url = "https://files.pythonhosted.org/packages/76/f9/4ae982c7a1387b64954130b72187e140329b73c647acb4d6b6eb3c033d8d/pyobjc_framework_screensaver-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:f2d22293cf9d715e4692267a1678096afd6793c0519d9417cf77c8a6c706a543", size = 8402, upload-time = "2025-06-14T20:54:19.044Z" }, -] - -[[package]] -name = "pyobjc-framework-screentime" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/82/33/ebed70a1de134de936bb9a12d5c76f24e1e335ff4964f9bb0af9b09607f1/pyobjc_framework_screentime-11.1.tar.gz", hash = "sha256:9bb8269456bbb674e1421182efe49f9168ceefd4e7c497047c7bf63e2f510a34", size = 14875, upload-time = "2025-06-14T20:58:26.179Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/ea/20/783eccea7206ceeda42a09a4614e3da92889e4c54abe9dec2e5e53576e1a/pyobjc_framework_screentime-11.1-py2.py3-none-any.whl", hash = "sha256:50a4e4ab33d6643a52616e990aa1c697d5e3e8f9f9bdab8d631e6d42d8287b4f", size = 3949, upload-time = "2025-06-14T20:54:26.916Z" }, -] - -[[package]] -name = "pyobjc-framework-scriptingbridge" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/8e/c1/5b1dd01ff173df4c6676f97405113458918819cb2064c1735b61948e8800/pyobjc_framework_scriptingbridge-11.1.tar.gz", hash = "sha256:604445c759210a35d86d3e0dfcde0aac8e5e3e9d9e35759e0723952138843699", size = 23155, upload-time = "2025-06-14T20:58:26.812Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/e6/76/e173ca0b121693bdc6ac5797b30fd5771f31a682d15fd46402dc6f9ca3d1/pyobjc_framework_scriptingbridge-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:d6020c69c14872105852ff99aab7cd2b2671e61ded3faefb071dc40a8916c527", size = 8301, upload-time = "2025-06-14T20:54:29.082Z" }, - { url = "https://files.pythonhosted.org/packages/c1/64/31849063e3e81b4c312ce838dc98f0409c09eb33bc79dbb5261cb994a4c4/pyobjc_framework_scriptingbridge-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:226ba12d9cbd504411b702323b0507dd1690e81b4ce657c5f0d8b998c46cf374", size = 8323, upload-time = "2025-06-14T20:54:30.105Z" }, -] - -[[package]] -name = "pyobjc-framework-searchkit" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-coreservices" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/6e/20/61b73fddae0d1a94f5defb0cd4b4f391ec03bfcce7ebe830cb827d5e208a/pyobjc_framework_searchkit-11.1.tar.gz", hash = "sha256:13a194eefcf1359ce9972cd92f2aadddf103f3efb1b18fd578ba5367dff3c10c", size = 30918, upload-time = "2025-06-14T20:58:27.447Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/2b/ed/a118d275a9132c8f5adcd353e4d9e844777068e33d51b195f46671161a7f/pyobjc_framework_searchkit-11.1-py2.py3-none-any.whl", hash = "sha256:9c9d6ca71cef637ccc3627225fb924a460b3d0618ed79bb0b3c12fcbe9270323", size = 3714, upload-time = "2025-06-14T20:54:34.329Z" }, -] - -[[package]] -name = "pyobjc-framework-security" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/ee/6f/ba50ed2d9c1192c67590a7cfefa44fc5f85c776d1e25beb224dec32081f6/pyobjc_framework_security-11.1.tar.gz", hash = "sha256:dabcee6987c6bae575e2d1ef0fcbe437678c4f49f1c25a4b131a5e960f31a2da", size = 302291, upload-time = "2025-06-14T20:58:28.506Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/ac/ae/1679770d9a1cf5f2fe532a3567a51f0c5ee09054ae2c4003ae8f3e11eea4/pyobjc_framework_security-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:d361231697486e97cfdafadf56709190696ab26a6a086dbba5f170e042e13daa", size = 41202, upload-time = "2025-06-14T20:54:36.255Z" }, - { url = "https://files.pythonhosted.org/packages/35/16/7fc52ab1364ada5885bf9b4c9ea9da3ad892b847c9b86aa59e086b16fc11/pyobjc_framework_security-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:2eb4ba6d8b221b9ad5d010e026247e8aa26ee43dcaf327e848340ed227d22d7e", size = 41222, upload-time = "2025-06-14T20:54:37.032Z" }, -] - -[[package]] -name = "pyobjc-framework-securityfoundation" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-security" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/5c/d4/19591dd0938a45b6d8711ef9ae5375b87c37a55b45d79c52d6f83a8d991f/pyobjc_framework_securityfoundation-11.1.tar.gz", hash = "sha256:b3c4cf70735a93e9df40f3a14478143959c415778f27be8c0dc9ae0c5b696b92", size = 13270, upload-time = "2025-06-14T20:58:29.304Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/6c/ab/23db6b1c09810d6bcc4eab96e62487fb4284b57e447eabe6c001cb41e36d/pyobjc_framework_securityfoundation-11.1-py2.py3-none-any.whl", hash = "sha256:25f2cf10f80c122f462e9d4d43efe9fd697299c194e0c357e76650e234e6d286", size = 3772, upload-time = "2025-06-14T20:54:41.732Z" }, -] - -[[package]] -name = "pyobjc-framework-securityinterface" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-security" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/a1/be/c846651c3e7f38a637c40ae1bcda9f14237c2395637c3a188df4f733c727/pyobjc_framework_securityinterface-11.1.tar.gz", hash = "sha256:e7aa6373e525f3ae05d71276e821a6348c53fec9f812b90eec1dbadfcb507bc9", size = 37648, upload-time = "2025-06-14T20:58:29.932Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/1c/ec/8073f37f56870efb039970f1cc4536f279c5d476abab2e8654129789277f/pyobjc_framework_securityinterface-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:3e884620b22918d462764f0665f6ac0cbb8142bb160fcd27c4f4357f81da73b7", size = 10769, upload-time = "2025-06-14T20:54:43.344Z" }, - { url = "https://files.pythonhosted.org/packages/6f/ab/48b8027a24f3f8924f5be5f97217961b4ed23e6be49b3bd94ee8a0d56a1e/pyobjc_framework_securityinterface-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:26056441b325029da06a7c7b8dd1a0c9a4ad7d980596c1b04d132a502b4cacc0", size = 10837, upload-time = "2025-06-14T20:54:44.052Z" }, -] - -[[package]] -name = "pyobjc-framework-securityui" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-security" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/07/5b/3b5585d56e0bcaba82e0661224bbc7aaf29fba6b10498971dbe08b2b490a/pyobjc_framework_securityui-11.1.tar.gz", hash = "sha256:e80c93e8a56bf89e4c0333047b9f8219752dd6de290681e9e2e2b2e26d69e92d", size = 12179, upload-time = "2025-06-14T20:58:30.928Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/d0/a4/c9fcc42065b6aed73b14b9650c1dc0a4af26a30d418cbc1bab33621b461c/pyobjc_framework_securityui-11.1-py2.py3-none-any.whl", hash = "sha256:3cdb101b03459fcf8e4064b90021d06761003f669181e02f43ff585e6ba2403d", size = 3581, upload-time = "2025-06-14T20:54:49.474Z" }, -] - -[[package]] -name = "pyobjc-framework-sensitivecontentanalysis" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-quartz" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/56/7b/e28f6b30d99e9d464427a07ada82b33cd3292f310bf478a1824051d066b9/pyobjc_framework_sensitivecontentanalysis-11.1.tar.gz", hash = "sha256:5b310515c7386f7afaf13e4632d7d9590688182bb7b563f8026c304bdf317308", size = 12796, upload-time = "2025-06-14T20:58:31.488Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/3c/63/76a939ecac74ca079702165330c692ad2c05ff9b2b446a72ddc8cdc63bb9/pyobjc_framework_sensitivecontentanalysis-11.1-py2.py3-none-any.whl", hash = "sha256:dbb78f5917f986a63878bb91263bceba28bd86fc381bad9461cf391646db369f", size = 3852, upload-time = "2025-06-14T20:54:50.75Z" }, -] - -[[package]] -name = "pyobjc-framework-servicemanagement" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/20/c6/32e11599d9d232311607b79eb2d1d21c52eaaf001599ea85f8771a933fa2/pyobjc_framework_servicemanagement-11.1.tar.gz", hash = "sha256:90a07164da49338480e0e135b445acc6ae7c08549a2037d1e512d2605fedd80a", size = 16645, upload-time = "2025-06-14T20:58:32.062Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b9/f1/222462f5afcb6cb3c1fc9e6092dfcffcc7eb9db8bd2cef8c1743a22fbe95/pyobjc_framework_servicemanagement-11.1-py2.py3-none-any.whl", hash = "sha256:104f56557342a05ad68cd0c9daf63b7f4678957fe1f919f03a872f1607a50710", size = 5338, upload-time = "2025-06-14T20:54:51.614Z" }, -] - -[[package]] -name = "pyobjc-framework-sharedwithyou" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-sharedwithyoucore" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/fe/a5/e299fbd0c13d4fac9356459f21372f6eef4279d0fbc99ba316d88dfbbfb4/pyobjc_framework_sharedwithyou-11.1.tar.gz", hash = "sha256:ece3a28a3083d0bcad0ac95b01f0eb699b9d2d0c02c61305bfd402678753ff6e", size = 34216, upload-time = "2025-06-14T20:58:32.75Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/2e/23/7caefaddc58702da830d1cc4eb3c45ae82dcd605ea362126ab47ebd54f7d/pyobjc_framework_sharedwithyou-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:ce1c37d5f8cf5b0fe8a261e4e7256da677162fd5aa7b724e83532cdfe58d8f94", size = 8725, upload-time = "2025-06-14T20:54:53.179Z" }, - { url = "https://files.pythonhosted.org/packages/57/44/211e1f18676e85d3656671fc0c954ced2cd007e55f1b0b6b2e4d0a0852eb/pyobjc_framework_sharedwithyou-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:99e1749187ae370be7b9c55dd076d1b8143f0d8db3e83f52540586f32e7abb33", size = 8740, upload-time = "2025-06-14T20:54:53.879Z" }, -] - -[[package]] -name = "pyobjc-framework-sharedwithyoucore" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/79/a3/1ca6ff1b785772c7c5a38a7c017c6f971b1eda638d6a0aab3bbde18ac086/pyobjc_framework_sharedwithyoucore-11.1.tar.gz", hash = "sha256:790050d25f47bda662a9f008b17ca640ac2460f2559a56b17995e53f2f44ed73", size = 29459, upload-time = "2025-06-14T20:58:33.422Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/7a/df/08cfa01dcdb4655514b7a10eb7c40da2bdb7866078c761d6ed26c9f464f7/pyobjc_framework_sharedwithyoucore-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:9a7fe5ffcc65093ef7cd25903769ad557c3d3c5a59155a31f3f934cf555101e6", size = 8489, upload-time = "2025-06-14T20:54:59.631Z" }, - { url = "https://files.pythonhosted.org/packages/b9/70/3b2e13fcf393aa434b1cf5c29c6aaf65ee5b8361254df3a920ed436bb5e4/pyobjc_framework_sharedwithyoucore-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:dd18c588b29de322c25821934d6aa6d2bbbdbb89b6a4efacdb248b4115fc488d", size = 8512, upload-time = "2025-06-14T20:55:00.411Z" }, -] - -[[package]] -name = "pyobjc-framework-shazamkit" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/de/08/ba739b97f1e441653bae8da5dd1e441bbbfa43940018d21edb60da7dd163/pyobjc_framework_shazamkit-11.1.tar.gz", hash = "sha256:c6e3c9ab8744d9319a89b78ae6f185bb5704efb68509e66d77bcd1f84a9446d6", size = 25797, upload-time = "2025-06-14T20:58:34.086Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/f8/b6/c03bc9aad7f15979b5d7f144baf5161c3c40e0bca194cce82e1bce0804a9/pyobjc_framework_shazamkit-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:2fe6990d0ec1b40d4efd0d0e49c2deb65198f49b963e6215c608c140b3149151", size = 8540, upload-time = "2025-06-14T20:55:05.978Z" }, - { url = "https://files.pythonhosted.org/packages/89/b7/594b8bdc406603a7a07cdb33f2be483fed16aebc35aeb087385fc9eca844/pyobjc_framework_shazamkit-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:b323f5409b01711aa2b6e2113306084fab2cc83fa57a0c3d55bd5876358b68d8", size = 8560, upload-time = "2025-06-14T20:55:07.564Z" }, -] - -[[package]] -name = "pyobjc-framework-social" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/07/2e/cc7707b7a40df392c579087947049f3e1f0e00597e7151ec411f654d8bef/pyobjc_framework_social-11.1.tar.gz", hash = "sha256:fbc09d7b00dad45b547f9b2329f4dcee3f5a50e2348de1870de0bd7be853a5b7", size = 14540, upload-time = "2025-06-14T20:58:35.116Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/86/1d/e1026c082a66075dbb7e57983c0aaaed3ee09f06c346743e8af24d1dc21a/pyobjc_framework_social-11.1-py2.py3-none-any.whl", hash = "sha256:ab5878c47d7a0639704c191cee43eeb259e09688808f0905c42551b9f79e1d57", size = 4444, upload-time = "2025-06-14T20:55:12.536Z" }, -] - -[[package]] -name = "pyobjc-framework-soundanalysis" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/e0/d4/b9497dbb57afdf0d22f61bb6e776a6f46cf9294c890448acde5b46dd61f3/pyobjc_framework_soundanalysis-11.1.tar.gz", hash = "sha256:42cd25b7e0f343d8b59367f72b5dae96cf65696bdb8eeead8d7424ed37aa1434", size = 16539, upload-time = "2025-06-14T20:58:35.813Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/13/b4/7e8cf3a02e615239568fdf12497233bbd5b58082615cd28a0c7cd4636309/pyobjc_framework_soundanalysis-11.1-py2.py3-none-any.whl", hash = "sha256:6cf983c24fb2ad2aa5e7499ab2d30ff134d887fe91fd2641acf7472e546ab4e5", size = 4161, upload-time = "2025-06-14T20:55:13.342Z" }, -] - -[[package]] -name = "pyobjc-framework-speech" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/67/76/2a1fd7637b2c662349ede09806e159306afeebfba18fb062ad053b41d811/pyobjc_framework_speech-11.1.tar.gz", hash = "sha256:d382977208c3710eacea89e05eae4578f1638bb5a7b667c06971e3d34e96845c", size = 41179, upload-time = "2025-06-14T20:58:36.43Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b5/d3/c3b1d542c5ddc816924f02edf2ececcda226f35c91e95ed80f2632fbd91c/pyobjc_framework_speech-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:d3e0276a66d2fa4357959a6f6fb5def03f8e0fd3aa43711d6a81ab2573b9415f", size = 9171, upload-time = "2025-06-14T20:55:15.316Z" }, - { url = "https://files.pythonhosted.org/packages/78/59/267f4699055beb39723ccbff70909ec3851e4adf17386f6ad85e5d983780/pyobjc_framework_speech-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:7726eff52cfa9cc7178ddcd1285cbc23b5f89ee55b4b850b0d2e90bb4f8e044b", size = 9180, upload-time = "2025-06-14T20:55:16.556Z" }, -] - -[[package]] -name = "pyobjc-framework-spritekit" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-quartz" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/16/02/2e253ba4f7fad6efe05fd5fcf44aede093f6c438d608d67c6c6623a1846d/pyobjc_framework_spritekit-11.1.tar.gz", hash = "sha256:914da6e846573cac8db5e403dec9a3e6f6edf5211f9b7e429734924d00f65108", size = 130297, upload-time = "2025-06-14T20:58:37.113Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/8f/83/1c874cffba691cf8c103e0fdf55b53d9749577794efb9fc30e4394ffef41/pyobjc_framework_spritekit-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:1c8c94d37c054b6e3c22c237f6458c12649776e5ac921d066ab99dee2e580909", size = 17718, upload-time = "2025-06-14T20:55:22.543Z" }, - { url = "https://files.pythonhosted.org/packages/f1/fe/39d92bf40ec7a6116f89fd95053321f7c00c50c10d82b9adfa0f9ebdb10c/pyobjc_framework_spritekit-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:8b470a890db69e70ef428dfff88da499500fca9b2d44da7120dc588d13a2dbdb", size = 17776, upload-time = "2025-06-14T20:55:23.639Z" }, -] - -[[package]] -name = "pyobjc-framework-storekit" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/44/a0/58cab9ebc9ac9282e1d4734b1987d1c3cd652b415ec3e678fcc5e735d279/pyobjc_framework_storekit-11.1.tar.gz", hash = "sha256:85acc30c0bfa120b37c3c5ac693fe9ad2c2e351ee7a1f9ea6f976b0c311ff164", size = 76421, upload-time = "2025-06-14T20:58:37.86Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/d4/30/7549a7bd2b068cd460792e09a66d88465aab2ac6fb2ddcf77b7bf5712eee/pyobjc_framework_storekit-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:624105bd26a9ce5a097b3f96653e2700d33bb095828ed65ee0f4679b34d9f1e1", size = 11841, upload-time = "2025-06-14T20:55:29.735Z" }, - { url = "https://files.pythonhosted.org/packages/ac/61/6404aac6857ea43798882333bcc26bfd3c9c3a1efc7a575cbf3e53538e2a/pyobjc_framework_storekit-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:5ca3373272b6989917c88571ca170ce6d771180fe1a2b44c7643fe084569b93e", size = 11868, upload-time = "2025-06-14T20:55:30.454Z" }, -] - -[[package]] -name = "pyobjc-framework-symbols" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/cd/af/7191276204bd3e7db1d0a3e490a869956606f77f7a303a04d92a5d0c3f7b/pyobjc_framework_symbols-11.1.tar.gz", hash = "sha256:0e09b7813ef2ebdca7567d3179807444dd60f3f393202b35b755d4e1baf99982", size = 13377, upload-time = "2025-06-14T20:58:38.542Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/9a/6a/c91f64ef9b8cd20245b88e392c66cb2279c511724f4ea2983d92584d6f3e/pyobjc_framework_symbols-11.1-py2.py3-none-any.whl", hash = "sha256:1de6fc3af15fc8d5fd4869663a3250311844ec33e99ec8a1991a352ab61d641d", size = 3312, upload-time = "2025-06-14T20:55:35.456Z" }, -] - -[[package]] -name = "pyobjc-framework-syncservices" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-coredata" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/69/45/cd9fa83ed1d75be7130fb8e41c375f05b5d6621737ec37e9d8da78676613/pyobjc_framework_syncservices-11.1.tar.gz", hash = "sha256:0f141d717256b98c17ec2eddbc983c4bd39dfa00dc0c31b4174742e73a8447fe", size = 57996, upload-time = "2025-06-14T20:58:39.146Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/f5/7e/60e184beafca85571cfa68d46a8f453a54edbc7d2eceb18163cfec438438/pyobjc_framework_syncservices-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:bc6159bda4597149c6999b052a35ffd9fc4817988293da6e54a1e073fa571653", size = 13464, upload-time = "2025-06-14T20:55:37.117Z" }, - { url = "https://files.pythonhosted.org/packages/01/2b/6d7d65c08a9c51eed12eb7f83eaa48deaed621036f77221b3b0346c3f6c2/pyobjc_framework_syncservices-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:03124c8c7c7ce837f51e1c9bdcf84c6f1d5201f92c8a1c172ec34908d5e57415", size = 13496, upload-time = "2025-06-14T20:55:37.83Z" }, -] - -[[package]] -name = "pyobjc-framework-systemconfiguration" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/e2/3d/41590c0afc72e93d911348fbde0c9c1071ff53c6f86df42df64b21174bb9/pyobjc_framework_systemconfiguration-11.1.tar.gz", hash = "sha256:f30ed0e9a8233fecb06522e67795918ab230ddcc4a18e15494eff7532f4c3ae1", size = 143410, upload-time = "2025-06-14T20:58:39.917Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/64/9b/8fe26a9ac85898fa58f6206f357745ec44cd95b63786503ce05c382344ce/pyobjc_framework_systemconfiguration-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:d12d5078611c905162bc951dffbb2a989b0dfd156952ba1884736c8dcbe38f7f", size = 21732, upload-time = "2025-06-14T20:55:43.951Z" }, - { url = "https://files.pythonhosted.org/packages/b9/61/0e9841bf1c7597f380a6dcefcc9335b6a909f20d9bdf07910cddc8552b42/pyobjc_framework_systemconfiguration-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:6881929b828a566bf1349f09db4943e96a2b33f42556e1f7f6f28b192420f6fc", size = 21639, upload-time = "2025-06-14T20:55:44.678Z" }, -] - -[[package]] -name = "pyobjc-framework-systemextensions" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/b4/57/4609fd9183383616b1e643c2489ad774335f679523a974b9ce346a6d4d5b/pyobjc_framework_systemextensions-11.1.tar.gz", hash = "sha256:8ff9f0aad14dcdd07dd47545c1dd20df7a286306967b0a0232c81fcc382babe6", size = 23062, upload-time = "2025-06-14T20:58:40.686Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/10/53/0fb6a200383fa98001ffa66b4f6344c68ccd092506699a353b30f18d7094/pyobjc_framework_systemextensions-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:7e742ae51cdd86c0e609fe47189ea446de98d13b235b0a138a3f2e37e98cd359", size = 9125, upload-time = "2025-06-14T20:55:50.431Z" }, - { url = "https://files.pythonhosted.org/packages/76/40/d9be444b39ec12d68b5e4f712b71d6c00d654936ff5744ea380c1bfabf06/pyobjc_framework_systemextensions-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:3a2b1e84e4a118bfe13efb9f2888b065dc937e2a7e60afd4d0a82b51b8301a10", size = 9130, upload-time = "2025-06-14T20:55:51.127Z" }, -] - -[[package]] -name = "pyobjc-framework-threadnetwork" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/e7/a4/5400a222ced0e4f077a8f4dd0188e08e2af4762e72ed0ed39f9d27feefc9/pyobjc_framework_threadnetwork-11.1.tar.gz", hash = "sha256:73a32782f44b61ca0f8a4a9811c36b1ca1cdcf96c8a3ba4de35d8e8e58a86ad5", size = 13572, upload-time = "2025-06-14T20:58:41.311Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b0/f0/b7a577d00bdb561efef82b046a75f627a60de53566ab2d9e9ddd5bd11b66/pyobjc_framework_threadnetwork-11.1-py2.py3-none-any.whl", hash = "sha256:55021455215a0d3ad4e40152f94154e29062e73655558c5f6e71ab097d90083e", size = 3751, upload-time = "2025-06-14T20:55:55.643Z" }, -] - -[[package]] -name = "pyobjc-framework-uniformtypeidentifiers" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/c5/4f/066ed1c69352ccc29165f45afb302f8c9c2b5c6f33ee3abfa41b873c07e5/pyobjc_framework_uniformtypeidentifiers-11.1.tar.gz", hash = "sha256:86c499bec8953aeb0c95af39b63f2592832384f09f12523405650b5d5f1ed5e9", size = 20599, upload-time = "2025-06-14T20:58:41.945Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/de/3b/b63b8137dd9f455d5abece6702c06c6b613fac6fda1319aaa2f79d00c380/pyobjc_framework_uniformtypeidentifiers-11.1-py2.py3-none-any.whl", hash = "sha256:6e2e8ea89eb8ca03bc2bc8e506fff901e71d916276475c8d81fbf0280059cb4c", size = 4891, upload-time = "2025-06-14T20:55:56.432Z" }, -] - -[[package]] -name = "pyobjc-framework-usernotifications" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/b4/4c/e7e180fcd06c246c37f218bcb01c40ea0213fde5ace3c09d359e60dcaafd/pyobjc_framework_usernotifications-11.1.tar.gz", hash = "sha256:38fc763afa7854b41ddfca8803f679a7305d278af8a7ad02044adc1265699996", size = 55428, upload-time = "2025-06-14T20:58:42.572Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/c1/bb/ae9c9301a86b7c0c26583c59ac761374cb6928c3d34cae514939e93e44b1/pyobjc_framework_usernotifications-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:7140d337dd9dc3635add2177086429fdd6ef24970935b22fffdc5ec7f02ebf60", size = 9599, upload-time = "2025-06-14T20:55:58.051Z" }, - { url = "https://files.pythonhosted.org/packages/03/af/a54e343a7226dc65a65f7a561c060f8c96cb9f92f41ce2242d20d82ae594/pyobjc_framework_usernotifications-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:ce6006989fd4a59ec355f6797ccdc9946014ea5241ff7875854799934dbba901", size = 9606, upload-time = "2025-06-14T20:55:59.088Z" }, -] - -[[package]] -name = "pyobjc-framework-usernotificationsui" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-usernotifications" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/d2/c4/03d97bd3adcee9b857533cb42967df0d019f6a034adcdbcfca2569d415b2/pyobjc_framework_usernotificationsui-11.1.tar.gz", hash = "sha256:18e0182bddd10381884530d6a28634ebb3280912592f8f2ad5bac2a9308c6a65", size = 14123, upload-time = "2025-06-14T20:58:43.267Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/9d/2c/0bb489b5ac4daf83b113018701ce30a0cb4bf47c615c92c5844a16e0a012/pyobjc_framework_usernotificationsui-11.1-py2.py3-none-any.whl", hash = "sha256:b84d73d90ab319acf8fad5c59b7a5e2b6023fbb2efd68c58b532e3b3b52f647a", size = 3914, upload-time = "2025-06-14T20:56:03.978Z" }, -] - -[[package]] -name = "pyobjc-framework-videosubscriberaccount" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/aa/00/cd9d93d06204bbb7fe68fb97022b0dd4ecdf8af3adb6d70a41e22c860d55/pyobjc_framework_videosubscriberaccount-11.1.tar.gz", hash = "sha256:2dd78586260fcee51044e129197e8bf2e157176e02babeec2f873afa4235d8c6", size = 28856, upload-time = "2025-06-14T20:58:43.903Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/4b/dc/b409dee6dd58a5db2e9a681bde8894c9715468689f18e040f7d252794c3d/pyobjc_framework_videosubscriberaccount-11.1-py2.py3-none-any.whl", hash = "sha256:d5a95ae9f2a6f0180a5bbb10e76c064f0fd327aae00a2fe90aa7b65ed4dad7ef", size = 4695, upload-time = "2025-06-14T20:56:06.027Z" }, -] - -[[package]] -name = "pyobjc-framework-videotoolbox" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-coremedia" }, - { name = "pyobjc-framework-quartz" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/e5/e3/df9096f54ae1f27cab8f922ee70cbda5d80f8c1d12734c38580829858133/pyobjc_framework_videotoolbox-11.1.tar.gz", hash = "sha256:a27985656e1b639cdb102fcc727ebc39f71bb1a44cdb751c8c80cc9fe938f3a9", size = 88551, upload-time = "2025-06-14T20:58:44.566Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/0b/41/fda951f1c734a68d7bf46ecc03bfff376a690ad771029c4289ba0423a52e/pyobjc_framework_videotoolbox-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:94c17bffe0f4692db2e7641390dfdcd0f73ddbb0afa6c81ef504219be0777930", size = 17325, upload-time = "2025-06-14T20:56:07.719Z" }, - { url = "https://files.pythonhosted.org/packages/1f/cf/569babadbf1f9598f62c400ee02da19d4ab5f36276978c81080999399df9/pyobjc_framework_videotoolbox-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:c55285c3c78183fd2a092d582e30b562777a82985cccca9e7e99a0aff2601591", size = 17432, upload-time = "2025-06-14T20:56:08.457Z" }, -] - -[[package]] -name = "pyobjc-framework-virtualization" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/f1/ff/57214e8f42755eeaad516a7e673dae4341b8742005d368ecc22c7a790b0b/pyobjc_framework_virtualization-11.1.tar.gz", hash = "sha256:4221ee5eb669e43a2ff46e04178bec149af2d65205deb5d4db5fa62ea060e022", size = 78633, upload-time = "2025-06-14T20:58:45.358Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/64/8b/5eeabfd08d5e6801010496969c1b67517bbda348ff0578ca5f075aa58926/pyobjc_framework_virtualization-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:c2a812da4c995e1f8076678130d0b0a63042aa48219f8fb43b70e13eabcbdbc2", size = 13054, upload-time = "2025-06-14T20:56:13.866Z" }, - { url = "https://files.pythonhosted.org/packages/c8/4f/fe1930f4ce2c7d2f4c34bb53adf43f412bc91364e8e4cb450a7c8a6b8b59/pyobjc_framework_virtualization-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:59df6702b3e63200752be7d9c0dc590cb4c3b699c886f9a8634dd224c74b3c3c", size = 13084, upload-time = "2025-06-14T20:56:14.617Z" }, -] - -[[package]] -name = "pyobjc-framework-vision" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, - { name = "pyobjc-framework-coreml" }, - { name = "pyobjc-framework-quartz" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/40/a8/7128da4d0a0103cabe58910a7233e2f98d18c590b1d36d4b3efaaedba6b9/pyobjc_framework_vision-11.1.tar.gz", hash = "sha256:26590512ee7758da3056499062a344b8a351b178be66d4b719327884dde4216b", size = 133721, upload-time = "2025-06-14T20:58:46.095Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/10/69/a745a5491d7af6034ac9e0d627e7b41b42978df0a469b86cdf372ba8917f/pyobjc_framework_vision-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:bfbde43c9d4296e1d26548b6d30ae413e2029425968cd8bce96d3c5a735e8f2c", size = 21657, upload-time = "2025-06-14T20:56:20.265Z" }, - { url = "https://files.pythonhosted.org/packages/a2/b5/54c0227a695557ea3065bc035b20a5c256f6f3b861e095eee1ec4b4d8cee/pyobjc_framework_vision-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:df076c3e3e672887182953efc934c1f9683304737e792ec09a29bfee90d2e26a", size = 16829, upload-time = "2025-06-14T20:56:21.355Z" }, -] - -[[package]] -name = "pyobjc-framework-webkit" -version = "11.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyobjc-core" }, - { name = "pyobjc-framework-cocoa" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/92/04/fb3d0b68994f7e657ef00c1ac5fc1c04ae2fc7ea581d647f5ae1f6739b14/pyobjc_framework_webkit-11.1.tar.gz", hash = "sha256:27e701c7aaf4f24fc7e601a128e2ef14f2773f4ab071b9db7438dc5afb5053ae", size = 717102, upload-time = "2025-06-14T20:58:47.461Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/8d/b6/d62c01a83c22619edf2379a6941c9f6b7aee01c565b9c1170696f85cba95/pyobjc_framework_webkit-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:10ec89d727af8f216ba5911ff5553f84a5b660f5ddf75b07788e3a439c281165", size = 51406, upload-time = "2025-06-14T20:56:26.845Z" }, - { url = "https://files.pythonhosted.org/packages/8a/7e/fa2c18c0c0f9321e5036e54b9da7a196956b531e50fe1a76e7dfdbe8fac2/pyobjc_framework_webkit-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:1a6e6f64ca53c4953f17e808ecac11da288d9a6ade738156ba161732a5e0c96a", size = 51464, upload-time = "2025-06-14T20:56:27.653Z" }, -] - -[[package]] -name = "pyopencl" -version = "2025.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "numpy" }, - { name = "platformdirs" }, - { name = "pytools" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/28/88/0ac460d3e2def08b2ad6345db6a13613815f616bbbd60c6f4bdf774f4c41/pyopencl-2025.1.tar.gz", hash = "sha256:0116736d7f7920f87b8db4b66a03f27b1d930d2e37ddd14518407cc22dd24779", size = 422510, upload-time = "2025-01-22T00:16:58.421Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/99/ce/c40c6248b29195397a6e176615c24a8047cdd3afe847932a1f27603c1b14/pyopencl-2025.1-cp311-cp311-macosx_10_14_x86_64.whl", hash = "sha256:a302e4ee1bb19ff244f5ae2b5a83a98977daa13f31929a85f23723020a4bec01", size = 424117, upload-time = "2025-01-22T00:16:08.957Z" }, - { url = "https://files.pythonhosted.org/packages/71/dd/8dd4e18396c705567be7eda65234932f8eb7e975cc15ae167265ed9c7d20/pyopencl-2025.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:48527fc5a250b9e89f2eaaa1c9423e1bc15ff181bd41ffa1e29e31890dc1d3b7", size = 408327, upload-time = "2025-01-22T00:16:10.42Z" }, - { url = "https://files.pythonhosted.org/packages/47/7b/270c4e6765b675eaa97af8ff0c964e21dc74ac2a2f04e2c24431c91ce382/pyopencl-2025.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:95490199c490e47b245b88e64e06f95272502d13810da172ac3b0f0340cf8715", size = 724636, upload-time = "2025-01-22T00:16:12.881Z" }, - { url = "https://files.pythonhosted.org/packages/0d/55/996d7877793acfc340678a71dc98151a8c39dbb289cf24ecae08c0af68eb/pyopencl-2025.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:cd2cb3c031beeec93cf660c8809d6ad58a2cde7dcd95ae12b4b2da6ac8e2da41", size = 1173429, upload-time = "2025-01-22T00:16:14.466Z" }, - { url = "https://files.pythonhosted.org/packages/3d/7c/d2a89b1c24c318375856e8b7611bc03ddf687134f68ddbb387496453eda8/pyopencl-2025.1-cp311-cp311-win_amd64.whl", hash = "sha256:d8d3cdb02dc8750a9cc11c5b37f219da1f61b4216af4a830eb52b451a0e9f9a7", size = 457877, upload-time = "2025-01-22T00:16:17.21Z" }, - { url = "https://files.pythonhosted.org/packages/02/c0/d9536211ecfddd3bdf7eaa1658d085fcd92120061ac6f4e662a5062660ff/pyopencl-2025.1-cp312-cp312-macosx_10_14_x86_64.whl", hash = "sha256:88c564d94a5067ab6b9429a7d92b655254da8b2b5a33c7e30e10c5a0cf3154e1", size = 425706, upload-time = "2025-01-22T00:16:18.771Z" }, - { url = "https://files.pythonhosted.org/packages/63/b9/3e6dd574cc9ffb2271be135ecdb36cd6aea70a1f74e80539b048072a256a/pyopencl-2025.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f204cd6974ca19e7ffe14f21afac9967b06a6718f3aecbbc4a4df313e8e7ebc2", size = 408163, upload-time = "2025-01-22T00:16:20.282Z" }, - { url = "https://files.pythonhosted.org/packages/a4/4d/7f6f2e24b12585b81fd49f689d21ba62187656d061e3cb43840f12097dad/pyopencl-2025.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dce8d1b3fd2046e89377b754117fdb3505f45edacfda6ad2b3a29670c0526ad1", size = 719348, upload-time = "2025-01-22T00:16:22.15Z" }, - { url = "https://files.pythonhosted.org/packages/f0/45/3c93510819859e047d494dd8f4ed80c26378bb964a8e5e850cc079cc1f6e/pyopencl-2025.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:fbb0b7b775424f0c4c929a00f09eb351075ea9e4d2b1c80afe37d09bec218ee9", size = 1170733, upload-time = "2025-01-22T00:16:24.575Z" }, - { url = "https://files.pythonhosted.org/packages/91/ba/b745715085ef893fa7d1c7e04c95e3e554b6b27b2fb0800d6bbca563b43c/pyopencl-2025.1-cp312-cp312-win_amd64.whl", hash = "sha256:78f2a58d2e177793fb5a7b9c8a574e3a5f1d178c4df713969d1b08341c817d60", size = 457762, upload-time = "2025-01-22T00:16:27.334Z" }, -] - -[[package]] -name = "pyopenssl" -version = "24.2.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "cryptography" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/5d/70/ff56a63248562e77c0c8ee4aefc3224258f1856977e0c1472672b62dadb8/pyopenssl-24.2.1.tar.gz", hash = "sha256:4247f0dbe3748d560dcbb2ff3ea01af0f9a1a001ef5f7c4c647956ed8cbf0e95", size = 184323, upload-time = "2024-07-20T17:26:31.252Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/d9/dd/e0aa7ebef5168c75b772eda64978c597a9129b46be17779054652a7999e4/pyOpenSSL-24.2.1-py3-none-any.whl", hash = "sha256:967d5719b12b243588573f39b0c677637145c7a1ffedcd495a487e58177fbb8d", size = 58390, upload-time = "2024-07-20T17:26:29.057Z" }, + { url = "https://files.pythonhosted.org/packages/d6/54/da572c98c0b77626a91b5d3b89f0231d8bff5125c225420908632f8b342d/pymdown_extensions-11.0.1-py3-none-any.whl", hash = "sha256:db3943a62bab7e03af1364f0c4083e64b91fb097675a4b6cceccfbe9a77e5eb2", size = 269455, upload-time = "2026-07-02T17:59:21.271Z" }, ] [[package]] name = "pyparsing" -version = "3.2.3" +version = "3.3.2" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/bb/22/f1129e69d94ffff626bdb5c835506b3a5b4f3d070f17ea295e12c2c6f60f/pyparsing-3.2.3.tar.gz", hash = "sha256:b9c13f1ab8b3b542f72e28f634bad4de758ab3ce4546e4301970ad6fa77c38be", size = 1088608, upload-time = "2025-03-25T05:01:28.114Z" } +sdist = { url = "https://files.pythonhosted.org/packages/f3/91/9c6ee907786a473bf81c5f53cf703ba0957b23ab84c264080fb5a450416f/pyparsing-3.3.2.tar.gz", hash = "sha256:c777f4d763f140633dcb6d8a3eda953bf7a214dc4eff598413c070bcdc117cbc", size = 6851574, upload-time = "2026-01-21T03:57:59.36Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/05/e7/df2285f3d08fee213f2d041540fa4fc9ca6c2d44cf36d3a035bf2a8d2bcc/pyparsing-3.2.3-py3-none-any.whl", hash = "sha256:a749938e02d6fd0b59b356ca504a24982314bb090c383e3cf201c95ef7e2bfcf", size = 111120, upload-time = "2025-03-25T05:01:24.908Z" }, -] - -[[package]] -name = "pyperclip" -version = "1.9.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/30/23/2f0a3efc4d6a32f3b63cdff36cd398d9701d26cda58e3ab97ac79fb5e60d/pyperclip-1.9.0.tar.gz", hash = "sha256:b7de0142ddc81bfc5c7507eea19da920b92252b548b96186caf94a5e2527d310", size = 20961, upload-time = "2024-06-18T20:38:48.401Z" } - -[[package]] -name = "pyprof2calltree" -version = "1.4.5" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/ca/2a/e9a76261183b4b5e059a6625d7aae0bcb0a77622bc767d4497148ce2e218/pyprof2calltree-1.4.5.tar.gz", hash = "sha256:a635672ff31677486350b2be9a823ef92f740e6354a6aeda8fa4a8a3768e8f2f", size = 10080, upload-time = "2020-04-19T10:39:09.819Z" } - -[[package]] -name = "pyrect" -version = "0.2.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/cb/04/2ba023d5f771b645f7be0c281cdacdcd939fe13d1deb331fc5ed1a6b3a98/PyRect-0.2.0.tar.gz", hash = "sha256:f65155f6df9b929b67caffbd57c0947c5ae5449d3b580d178074bffb47a09b78", size = 17219, upload-time = "2022-03-16T04:45:52.36Z" } - -[[package]] -name = "pyscreeze" -version = "1.0.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pillow", marker = "python_full_version < '3.12'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/ee/f0/cb456ac4f1a73723d5b866933b7986f02bacea27516629c00f8e7da94c2d/pyscreeze-1.0.1.tar.gz", hash = "sha256:cf1662710f1b46aa5ff229ee23f367da9e20af4a78e6e365bee973cad0ead4be", size = 27826, upload-time = "2024-08-20T23:03:07.291Z" } - -[[package]] -name = "pyserial" -version = "3.5" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/1e/7d/ae3f0a63f41e4d2f6cb66a5b57197850f919f59e558159a4dd3a818f5082/pyserial-3.5.tar.gz", hash = "sha256:3c77e014170dfffbd816e6ffc205e9842efb10be9f58ec16d3e8675b4925cddb", size = 159125, upload-time = "2020-11-23T03:59:15.045Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/07/bc/587a445451b253b285629263eb51c2d8e9bcea4fc97826266d186f96f558/pyserial-3.5-py2.py3-none-any.whl", hash = "sha256:c4451db6ba391ca6ca299fb3ec7bae67a5c55dde170964c7a14ceefec02f2cf0", size = 90585, upload-time = "2020-11-23T03:59:13.41Z" }, + { url = "https://files.pythonhosted.org/packages/10/bd/c038d7cc38edc1aa5bf91ab8068b63d4308c66c4c8bb3cbba7dfbc049f9c/pyparsing-3.3.2-py3-none-any.whl", hash = "sha256:850ba148bd908d7e2411587e247a1e4f0327839c40e2e5e6d05a007ecc69911d", size = 122781, upload-time = "2026-01-21T03:57:55.912Z" }, ] [[package]] name = "pytest" -version = "8.4.1" +version = "9.1.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "colorama", marker = "sys_platform == 'win32'" }, @@ -4295,35 +997,9 @@ dependencies = [ { name = "pluggy" }, { name = "pygments" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/08/ba/45911d754e8eba3d5a841a5ce61a65a685ff1798421ac054f85aa8747dfb/pytest-8.4.1.tar.gz", hash = "sha256:7c67fd69174877359ed9371ec3af8a3d2b04741818c51e5e99cc1742251fa93c", size = 1517714, upload-time = "2025-06-18T05:48:06.109Z" } +sdist = { url = "https://files.pythonhosted.org/packages/e4/47/b9efed96c114afcfa3c9d3fe98a76a1d14c74a9e266d397cf6eb64be5e01/pytest-9.1.1.tar.gz", hash = "sha256:1088fbde8f2b49d95a549a195707afa7a76a3ce9bcadc26b6d71f0ffda5fe313", size = 1636369, upload-time = "2026-06-19T10:58:32.857Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/29/16/c8a903f4c4dffe7a12843191437d7cd8e32751d5de349d45d3fe69544e87/pytest-8.4.1-py3-none-any.whl", hash = "sha256:539c70ba6fcead8e78eebbf1115e8b589e7565830d7d006a8723f19ac8a0afb7", size = 365474, upload-time = "2025-06-18T05:48:03.955Z" }, -] - -[[package]] -name = "pytest-asyncio" -version = "1.0.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pytest" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/d0/d4/14f53324cb1a6381bef29d698987625d80052bb33932d8e7cbf9b337b17c/pytest_asyncio-1.0.0.tar.gz", hash = "sha256:d15463d13f4456e1ead2594520216b225a16f781e144f8fdf6c5bb4667c48b3f", size = 46960, upload-time = "2025-05-26T04:54:40.484Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/30/05/ce271016e351fddc8399e546f6e23761967ee09c8c568bbfbecb0c150171/pytest_asyncio-1.0.0-py3-none-any.whl", hash = "sha256:4f024da9f1ef945e680dc68610b52550e36590a67fd31bb3b4943979a1f90ef3", size = 15976, upload-time = "2025-05-26T04:54:39.035Z" }, -] - -[[package]] -name = "pytest-cov" -version = "6.2.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "coverage", extra = ["toml"] }, - { name = "pluggy" }, - { name = "pytest" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/18/99/668cade231f434aaa59bbfbf49469068d2ddd945000621d3d165d2e7dd7b/pytest_cov-6.2.1.tar.gz", hash = "sha256:25cc6cc0a5358204b8108ecedc51a9b57b34cc6b8c967cc2c01a4e00d8a67da2", size = 69432, upload-time = "2025-06-12T10:47:47.684Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/bc/16/4ea354101abb1287856baa4af2732be351c7bee728065aed451b678153fd/pytest_cov-6.2.1-py3-none-any.whl", hash = "sha256:f5bc4c23f42f1cdd23c70b1dab1bbaef4fc505ba950d53e0081d0730dd7e86d5", size = 24644, upload-time = "2025-06-12T10:47:45.932Z" }, + { url = "https://files.pythonhosted.org/packages/24/25/1de2678b631f5a49215c6c96fff41ba892b0a34df68d6d80292b1b48aa7f/pytest-9.1.1-py3-none-any.whl", hash = "sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c", size = 386536, upload-time = "2026-06-19T10:58:31.347Z" }, ] [[package]] @@ -4340,69 +1016,33 @@ wheels = [ [[package]] name = "pytest-mock" -version = "3.14.1" +version = "3.15.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "pytest" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/71/28/67172c96ba684058a4d24ffe144d64783d2a270d0af0d9e792737bddc75c/pytest_mock-3.14.1.tar.gz", hash = "sha256:159e9edac4c451ce77a5cdb9fc5d1100708d2dd4ba3c3df572f14097351af80e", size = 33241, upload-time = "2025-05-26T13:58:45.167Z" } +sdist = { url = "https://files.pythonhosted.org/packages/68/14/eb014d26be205d38ad5ad20d9a80f7d201472e08167f0bb4361e251084a9/pytest_mock-3.15.1.tar.gz", hash = "sha256:1849a238f6f396da19762269de72cb1814ab44416fa73a8686deac10b0d87a0f", size = 34036, upload-time = "2025-09-16T16:37:27.081Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/b2/05/77b60e520511c53d1c1ca75f1930c7dd8e971d0c4379b7f4b3f9644685ba/pytest_mock-3.14.1-py3-none-any.whl", hash = "sha256:178aefcd11307d874b4cd3100344e7e2d888d9791a6a1d9bfe90fbc1b74fd1d0", size = 9923, upload-time = "2025-05-26T13:58:43.487Z" }, -] - -[[package]] -name = "pytest-randomly" -version = "3.16.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pytest" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/c0/68/d221ed7f4a2a49a664da721b8e87b52af6dd317af2a6cb51549cf17ac4b8/pytest_randomly-3.16.0.tar.gz", hash = "sha256:11bf4d23a26484de7860d82f726c0629837cf4064b79157bd18ec9d41d7feb26", size = 13367, upload-time = "2024-10-25T15:45:34.274Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/22/70/b31577d7c46d8e2f9baccfed5067dd8475262a2331ffb0bfdf19361c9bde/pytest_randomly-3.16.0-py3-none-any.whl", hash = "sha256:8633d332635a1a0983d3bba19342196807f6afb17c3eef78e02c2f85dade45d6", size = 8396, upload-time = "2024-10-25T15:45:32.78Z" }, -] - -[[package]] -name = "pytest-repeat" -version = "0.9.4" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pytest" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/80/d4/69e9dbb9b8266df0b157c72be32083403c412990af15c7c15f7a3fd1b142/pytest_repeat-0.9.4.tar.gz", hash = "sha256:d92ac14dfaa6ffcfe6917e5d16f0c9bc82380c135b03c2a5f412d2637f224485", size = 6488, upload-time = "2025-04-07T14:59:53.077Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/73/d4/8b706b81b07b43081bd68a2c0359fe895b74bf664b20aca8005d2bb3be71/pytest_repeat-0.9.4-py3-none-any.whl", hash = "sha256:c1738b4e412a6f3b3b9e0b8b29fcd7a423e50f87381ad9307ef6f5a8601139f3", size = 4180, upload-time = "2025-04-07T14:59:51.492Z" }, + { url = "https://files.pythonhosted.org/packages/5a/cc/06253936f4a7fa2e0f48dfe6d851d9c56df896a9ab09ac019d70b760619c/pytest_mock-3.15.1-py3-none-any.whl", hash = "sha256:0a25e2eb88fe5168d535041d09a4529a188176ae608a6d249ee65abc0949630d", size = 10095, upload-time = "2025-09-16T16:37:25.734Z" }, ] [[package]] name = "pytest-subtests" -version = "0.14.2" +version = "0.15.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "attrs" }, { name = "pytest" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/59/30/6ec8dfc678ddfd1c294212bbd7088c52d3f7fbf3f05e6d8a440c13b9741a/pytest_subtests-0.14.2.tar.gz", hash = "sha256:7154a8665fd528ee70a76d00216a44d139dc3c9c83521a0f779f7b0ad4f800de", size = 18083, upload-time = "2025-06-13T10:50:01.636Z" } +sdist = { url = "https://files.pythonhosted.org/packages/bb/d9/20097971a8d315e011e055d512fa120fd6be3bdb8f4b3aa3e3c6bf77bebc/pytest_subtests-0.15.0.tar.gz", hash = "sha256:cb495bde05551b784b8f0b8adfaa27edb4131469a27c339b80fd8d6ba33f887c", size = 18525, upload-time = "2025-10-20T16:26:18.358Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/47/d4/9bf12e59fb882b0cf4f993871e1adbee094802224c429b00861acee1a169/pytest_subtests-0.14.2-py3-none-any.whl", hash = "sha256:8da0787c994ab372a13a0ad7d390533ad2e4385cac167b3ac501258c885d0b66", size = 9115, upload-time = "2025-06-13T10:50:00.543Z" }, -] - -[[package]] -name = "pytest-timeout" -version = "2.4.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pytest" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/ac/82/4c9ecabab13363e72d880f2fb504c5f750433b2b6f16e99f4ec21ada284c/pytest_timeout-2.4.0.tar.gz", hash = "sha256:7e68e90b01f9eff71332b25001f85c75495fc4e3a836701876183c4bcfd0540a", size = 17973, upload-time = "2025-05-05T19:44:34.99Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/fa/b6/3127540ecdf1464a00e5a01ee60a1b09175f6913f0644ac748494d9c4b21/pytest_timeout-2.4.0-py3-none-any.whl", hash = "sha256:c42667e5cdadb151aeb5b26d114aff6bdf5a907f176a007a30b940d3d865b5c2", size = 14382, upload-time = "2025-05-05T19:44:33.502Z" }, + { url = "https://files.pythonhosted.org/packages/23/64/bba465299b37448b4c1b84c7a04178399ac22d47b3dc5db1874fe55a2bd3/pytest_subtests-0.15.0-py3-none-any.whl", hash = "sha256:da2d0ce348e1f8d831d5a40d81e3aeac439fec50bd5251cbb7791402696a9493", size = 9185, upload-time = "2025-10-20T16:26:17.239Z" }, ] [[package]] name = "pytest-xdist" -version = "3.7.1.dev3+g909e97b" -source = { git = "https://github.com/sshane/pytest-xdist?rev=909e97b49d12401c10608f9d777bfc9dab8a4413#909e97b49d12401c10608f9d777bfc9dab8a4413" } +version = "3.7.1.dev24+g2b4372b" +source = { git = "https://github.com/sshane/pytest-xdist?rev=2b4372bd62699fb412c4fe2f95bf9f01bd2018da#2b4372bd62699fb412c4fe2f95bf9f01bd2018da" } dependencies = [ { name = "execnet" }, { name = "pytest" }, @@ -4420,161 +1060,43 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892, upload-time = "2024-03-01T18:36:18.57Z" }, ] -[[package]] -name = "python-xlib" -version = "0.33" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "six" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/86/f5/8c0653e5bb54e0cbdfe27bf32d41f27bc4e12faa8742778c17f2a71be2c0/python-xlib-0.33.tar.gz", hash = "sha256:55af7906a2c75ce6cb280a584776080602444f75815a7aff4d287bb2d7018b32", size = 269068, upload-time = "2022-12-25T18:53:00.824Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/fc/b8/ff33610932e0ee81ae7f1269c890f697d56ff74b9f5b2ee5d9b7fa2c5355/python_xlib-0.33-py2.py3-none-any.whl", hash = "sha256:c3534038d42e0df2f1392a1b30a15a4ff5fdc2b86cfa94f072bf11b10a164398", size = 182185, upload-time = "2022-12-25T18:52:58.662Z" }, -] - -[[package]] -name = "python3-xlib" -version = "0.15" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/ef/c6/2c5999de3bb1533521f1101e8fe56fd9c266732f4d48011c7c69b29d12ae/python3-xlib-0.15.tar.gz", hash = "sha256:dc4245f3ae4aa5949c1d112ee4723901ade37a96721ba9645f2bfa56e5b383f8", size = 132828, upload-time = "2014-05-31T12:28:59.603Z" } - -[[package]] -name = "pytools" -version = "2024.1.10" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "platformdirs" }, - { name = "siphash24" }, - { name = "typing-extensions" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/ee/0f/56e109c0307f831b5d598ad73976aaaa84b4d0e98da29a642e797eaa940c/pytools-2024.1.10.tar.gz", hash = "sha256:9af6f4b045212c49be32bb31fe19606c478ee4b09631886d05a32459f4ce0a12", size = 81741, upload-time = "2024-07-17T18:47:38.287Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/66/cf/0a6aaa44b1f9e02b8c0648b5665a82246a93bcc75224c167b4fafa25c093/pytools-2024.1.10-py3-none-any.whl", hash = "sha256:9cabb71038048291400e244e2da441a051d86053339bc484e64e58d8ea263f44", size = 88108, upload-time = "2024-07-17T18:47:36.173Z" }, -] - -[[package]] -name = "pytweening" -version = "1.2.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/79/0c/c16bc93ac2755bac0066a8ecbd2a2931a1735a6fffd99a2b9681c7e83e90/pytweening-1.2.0.tar.gz", hash = "sha256:243318b7736698066c5f362ec5c2b6434ecf4297c3c8e7caa8abfe6af4cac71b", size = 171241, upload-time = "2024-02-20T03:37:56.809Z" } - -[[package]] -name = "pywin32" -version = "310" -source = { registry = "https://pypi.org/simple" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/f7/b1/68aa2986129fb1011dabbe95f0136f44509afaf072b12b8f815905a39f33/pywin32-310-cp311-cp311-win32.whl", hash = "sha256:1e765f9564e83011a63321bb9d27ec456a0ed90d3732c4b2e312b855365ed8bd", size = 8784284, upload-time = "2025-03-17T00:55:53.124Z" }, - { url = "https://files.pythonhosted.org/packages/b3/bd/d1592635992dd8db5bb8ace0551bc3a769de1ac8850200cfa517e72739fb/pywin32-310-cp311-cp311-win_amd64.whl", hash = "sha256:126298077a9d7c95c53823934f000599f66ec9296b09167810eb24875f32689c", size = 9520748, upload-time = "2025-03-17T00:55:55.203Z" }, - { url = "https://files.pythonhosted.org/packages/90/b1/ac8b1ffce6603849eb45a91cf126c0fa5431f186c2e768bf56889c46f51c/pywin32-310-cp311-cp311-win_arm64.whl", hash = "sha256:19ec5fc9b1d51c4350be7bb00760ffce46e6c95eaf2f0b2f1150657b1a43c582", size = 8455941, upload-time = "2025-03-17T00:55:57.048Z" }, - { url = "https://files.pythonhosted.org/packages/6b/ec/4fdbe47932f671d6e348474ea35ed94227fb5df56a7c30cbbb42cd396ed0/pywin32-310-cp312-cp312-win32.whl", hash = "sha256:8a75a5cc3893e83a108c05d82198880704c44bbaee4d06e442e471d3c9ea4f3d", size = 8796239, upload-time = "2025-03-17T00:55:58.807Z" }, - { url = "https://files.pythonhosted.org/packages/e3/e5/b0627f8bb84e06991bea89ad8153a9e50ace40b2e1195d68e9dff6b03d0f/pywin32-310-cp312-cp312-win_amd64.whl", hash = "sha256:bf5c397c9a9a19a6f62f3fb821fbf36cac08f03770056711f765ec1503972060", size = 9503839, upload-time = "2025-03-17T00:56:00.8Z" }, - { url = "https://files.pythonhosted.org/packages/1f/32/9ccf53748df72301a89713936645a664ec001abd35ecc8578beda593d37d/pywin32-310-cp312-cp312-win_arm64.whl", hash = "sha256:2349cc906eae872d0663d4d6290d13b90621eaf78964bb1578632ff20e152966", size = 8459470, upload-time = "2025-03-17T00:56:02.601Z" }, -] - -[[package]] -name = "pywinbox" -version = "0.7" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "ewmhlib", marker = "sys_platform == 'linux'" }, - { name = "pyobjc", marker = "sys_platform == 'darwin'" }, - { name = "python-xlib", marker = "sys_platform == 'linux'" }, - { name = "pywin32", marker = "sys_platform == 'win32'" }, - { name = "typing-extensions" }, -] -wheels = [ - { url = "https://files.pythonhosted.org/packages/b1/37/d59397221e15d2a7f38afaa4e8e6b8c244d818044f7daa0bdc5988df0a69/PyWinBox-0.7-py3-none-any.whl", hash = "sha256:8b2506a8dd7afa0a910b368762adfac885274132ef9151b0c81b0d2c6ffd6f83", size = 12274, upload-time = "2024-04-17T10:10:31.899Z" }, -] - -[[package]] -name = "pywinctl" -version = "0.4.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "ewmhlib", marker = "sys_platform == 'linux'" }, - { name = "pymonctl" }, - { name = "pyobjc", marker = "sys_platform == 'darwin'" }, - { name = "python-xlib", marker = "sys_platform == 'linux'" }, - { name = "pywin32", marker = "sys_platform == 'win32'" }, - { name = "pywinbox" }, - { name = "typing-extensions" }, -] -wheels = [ - { url = "https://files.pythonhosted.org/packages/be/33/8e4f632210b28fc9e998a9ab990e7ed97ecd2800cc50038e3800e1d85dbe/PyWinCtl-0.4.1-py3-none-any.whl", hash = "sha256:4d875e22969e1c6239d8c73156193630aaab876366167b8d97716f956384b089", size = 63158, upload-time = "2024-09-23T08:33:39.881Z" }, -] - [[package]] name = "pyyaml" -version = "6.0.2" +version = "6.0.3" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/54/ed/79a089b6be93607fa5cdaedf301d7dfb23af5f25c398d5ead2525b063e17/pyyaml-6.0.2.tar.gz", hash = "sha256:d584d9ec91ad65861cc08d42e834324ef890a082e591037abe114850ff7bbc3e", size = 130631, upload-time = "2024-08-06T20:33:50.674Z" } +sdist = { url = "https://files.pythonhosted.org/packages/05/8e/961c0007c59b8dd7729d542c61a4d537767a59645b82a0b521206e1e25c2/pyyaml-6.0.3.tar.gz", hash = "sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f", size = 130960, upload-time = "2025-09-25T21:33:16.546Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/f8/aa/7af4e81f7acba21a4c6be026da38fd2b872ca46226673c89a758ebdc4fd2/PyYAML-6.0.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:cc1c1159b3d456576af7a3e4d1ba7e6924cb39de8f67111c735f6fc832082774", size = 184612, upload-time = "2024-08-06T20:32:03.408Z" }, - { url = "https://files.pythonhosted.org/packages/8b/62/b9faa998fd185f65c1371643678e4d58254add437edb764a08c5a98fb986/PyYAML-6.0.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:1e2120ef853f59c7419231f3bf4e7021f1b936f6ebd222406c3b60212205d2ee", size = 172040, upload-time = "2024-08-06T20:32:04.926Z" }, - { url = "https://files.pythonhosted.org/packages/ad/0c/c804f5f922a9a6563bab712d8dcc70251e8af811fce4524d57c2c0fd49a4/PyYAML-6.0.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5d225db5a45f21e78dd9358e58a98702a0302f2659a3c6cd320564b75b86f47c", size = 736829, upload-time = "2024-08-06T20:32:06.459Z" }, - { url = "https://files.pythonhosted.org/packages/51/16/6af8d6a6b210c8e54f1406a6b9481febf9c64a3109c541567e35a49aa2e7/PyYAML-6.0.2-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:5ac9328ec4831237bec75defaf839f7d4564be1e6b25ac710bd1a96321cc8317", size = 764167, upload-time = "2024-08-06T20:32:08.338Z" }, - { url = "https://files.pythonhosted.org/packages/75/e4/2c27590dfc9992f73aabbeb9241ae20220bd9452df27483b6e56d3975cc5/PyYAML-6.0.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3ad2a3decf9aaba3d29c8f537ac4b243e36bef957511b4766cb0057d32b0be85", size = 762952, upload-time = "2024-08-06T20:32:14.124Z" }, - { url = "https://files.pythonhosted.org/packages/9b/97/ecc1abf4a823f5ac61941a9c00fe501b02ac3ab0e373c3857f7d4b83e2b6/PyYAML-6.0.2-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:ff3824dc5261f50c9b0dfb3be22b4567a6f938ccce4587b38952d85fd9e9afe4", size = 735301, upload-time = "2024-08-06T20:32:16.17Z" }, - { url = "https://files.pythonhosted.org/packages/45/73/0f49dacd6e82c9430e46f4a027baa4ca205e8b0a9dce1397f44edc23559d/PyYAML-6.0.2-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:797b4f722ffa07cc8d62053e4cff1486fa6dc094105d13fea7b1de7d8bf71c9e", size = 756638, upload-time = "2024-08-06T20:32:18.555Z" }, - { url = "https://files.pythonhosted.org/packages/22/5f/956f0f9fc65223a58fbc14459bf34b4cc48dec52e00535c79b8db361aabd/PyYAML-6.0.2-cp311-cp311-win32.whl", hash = "sha256:11d8f3dd2b9c1207dcaf2ee0bbbfd5991f571186ec9cc78427ba5bd32afae4b5", size = 143850, upload-time = "2024-08-06T20:32:19.889Z" }, - { url = "https://files.pythonhosted.org/packages/ed/23/8da0bbe2ab9dcdd11f4f4557ccaf95c10b9811b13ecced089d43ce59c3c8/PyYAML-6.0.2-cp311-cp311-win_amd64.whl", hash = "sha256:e10ce637b18caea04431ce14fabcf5c64a1c61ec9c56b071a4b7ca131ca52d44", size = 161980, upload-time = "2024-08-06T20:32:21.273Z" }, - { url = "https://files.pythonhosted.org/packages/86/0c/c581167fc46d6d6d7ddcfb8c843a4de25bdd27e4466938109ca68492292c/PyYAML-6.0.2-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:c70c95198c015b85feafc136515252a261a84561b7b1d51e3384e0655ddf25ab", size = 183873, upload-time = "2024-08-06T20:32:25.131Z" }, - { url = "https://files.pythonhosted.org/packages/a8/0c/38374f5bb272c051e2a69281d71cba6fdb983413e6758b84482905e29a5d/PyYAML-6.0.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ce826d6ef20b1bc864f0a68340c8b3287705cae2f8b4b1d932177dcc76721725", size = 173302, upload-time = "2024-08-06T20:32:26.511Z" }, - { url = "https://files.pythonhosted.org/packages/c3/93/9916574aa8c00aa06bbac729972eb1071d002b8e158bd0e83a3b9a20a1f7/PyYAML-6.0.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1f71ea527786de97d1a0cc0eacd1defc0985dcf6b3f17bb77dcfc8c34bec4dc5", size = 739154, upload-time = "2024-08-06T20:32:28.363Z" }, - { url = "https://files.pythonhosted.org/packages/95/0f/b8938f1cbd09739c6da569d172531567dbcc9789e0029aa070856f123984/PyYAML-6.0.2-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9b22676e8097e9e22e36d6b7bda33190d0d400f345f23d4065d48f4ca7ae0425", size = 766223, upload-time = "2024-08-06T20:32:30.058Z" }, - { url = "https://files.pythonhosted.org/packages/b9/2b/614b4752f2e127db5cc206abc23a8c19678e92b23c3db30fc86ab731d3bd/PyYAML-6.0.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:80bab7bfc629882493af4aa31a4cfa43a4c57c83813253626916b8c7ada83476", size = 767542, upload-time = "2024-08-06T20:32:31.881Z" }, - { url = "https://files.pythonhosted.org/packages/d4/00/dd137d5bcc7efea1836d6264f049359861cf548469d18da90cd8216cf05f/PyYAML-6.0.2-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:0833f8694549e586547b576dcfaba4a6b55b9e96098b36cdc7ebefe667dfed48", size = 731164, upload-time = "2024-08-06T20:32:37.083Z" }, - { url = "https://files.pythonhosted.org/packages/c9/1f/4f998c900485e5c0ef43838363ba4a9723ac0ad73a9dc42068b12aaba4e4/PyYAML-6.0.2-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:8b9c7197f7cb2738065c481a0461e50ad02f18c78cd75775628afb4d7137fb3b", size = 756611, upload-time = "2024-08-06T20:32:38.898Z" }, - { url = "https://files.pythonhosted.org/packages/df/d1/f5a275fdb252768b7a11ec63585bc38d0e87c9e05668a139fea92b80634c/PyYAML-6.0.2-cp312-cp312-win32.whl", hash = "sha256:ef6107725bd54b262d6dedcc2af448a266975032bc85ef0172c5f059da6325b4", size = 140591, upload-time = "2024-08-06T20:32:40.241Z" }, - { url = "https://files.pythonhosted.org/packages/0c/e8/4f648c598b17c3d06e8753d7d13d57542b30d56e6c2dedf9c331ae56312e/PyYAML-6.0.2-cp312-cp312-win_amd64.whl", hash = "sha256:7e7401d0de89a9a855c839bc697c079a4af81cf878373abd7dc625847d25cbd8", size = 156338, upload-time = "2024-08-06T20:32:41.93Z" }, -] - -[[package]] -name = "pyyaml-env-tag" -version = "1.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pyyaml" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/eb/2e/79c822141bfd05a853236b504869ebc6b70159afc570e1d5a20641782eaa/pyyaml_env_tag-1.1.tar.gz", hash = "sha256:2eb38b75a2d21ee0475d6d97ec19c63287a7e140231e4214969d0eac923cd7ff", size = 5737, upload-time = "2025-05-13T15:24:01.64Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/04/11/432f32f8097b03e3cd5fe57e88efb685d964e2e5178a48ed61e841f7fdce/pyyaml_env_tag-1.1-py3-none-any.whl", hash = "sha256:17109e1a528561e32f026364712fee1264bc2ea6715120891174ed1b980d2e04", size = 4722, upload-time = "2025-05-13T15:23:59.629Z" }, + { url = "https://files.pythonhosted.org/packages/d1/33/422b98d2195232ca1826284a76852ad5a86fe23e31b009c9886b2d0fb8b2/pyyaml-6.0.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:7f047e29dcae44602496db43be01ad42fc6f1cc0d8cd6c83d342306c32270196", size = 182063, upload-time = "2025-09-25T21:32:11.445Z" }, + { url = "https://files.pythonhosted.org/packages/89/a0/6cf41a19a1f2f3feab0e9c0b74134aa2ce6849093d5517a0c550fe37a648/pyyaml-6.0.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:fc09d0aa354569bc501d4e787133afc08552722d3ab34836a80547331bb5d4a0", size = 173973, upload-time = "2025-09-25T21:32:12.492Z" }, + { url = "https://files.pythonhosted.org/packages/ed/23/7a778b6bd0b9a8039df8b1b1d80e2e2ad78aa04171592c8a5c43a56a6af4/pyyaml-6.0.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9149cad251584d5fb4981be1ecde53a1ca46c891a79788c0df828d2f166bda28", size = 775116, upload-time = "2025-09-25T21:32:13.652Z" }, + { url = "https://files.pythonhosted.org/packages/65/30/d7353c338e12baef4ecc1b09e877c1970bd3382789c159b4f89d6a70dc09/pyyaml-6.0.3-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5fdec68f91a0c6739b380c83b951e2c72ac0197ace422360e6d5a959d8d97b2c", size = 844011, upload-time = "2025-09-25T21:32:15.21Z" }, + { url = "https://files.pythonhosted.org/packages/8b/9d/b3589d3877982d4f2329302ef98a8026e7f4443c765c46cfecc8858c6b4b/pyyaml-6.0.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ba1cc08a7ccde2d2ec775841541641e4548226580ab850948cbfda66a1befcdc", size = 807870, upload-time = "2025-09-25T21:32:16.431Z" }, + { url = "https://files.pythonhosted.org/packages/05/c0/b3be26a015601b822b97d9149ff8cb5ead58c66f981e04fedf4e762f4bd4/pyyaml-6.0.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:8dc52c23056b9ddd46818a57b78404882310fb473d63f17b07d5c40421e47f8e", size = 761089, upload-time = "2025-09-25T21:32:17.56Z" }, + { url = "https://files.pythonhosted.org/packages/be/8e/98435a21d1d4b46590d5459a22d88128103f8da4c2d4cb8f14f2a96504e1/pyyaml-6.0.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:41715c910c881bc081f1e8872880d3c650acf13dfa8214bad49ed4cede7c34ea", size = 790181, upload-time = "2025-09-25T21:32:18.834Z" }, + { url = "https://files.pythonhosted.org/packages/74/93/7baea19427dcfbe1e5a372d81473250b379f04b1bd3c4c5ff825e2327202/pyyaml-6.0.3-cp312-cp312-win32.whl", hash = "sha256:96b533f0e99f6579b3d4d4995707cf36df9100d67e0c8303a0c55b27b5f99bc5", size = 137658, upload-time = "2025-09-25T21:32:20.209Z" }, + { url = "https://files.pythonhosted.org/packages/86/bf/899e81e4cce32febab4fb42bb97dcdf66bc135272882d1987881a4b519e9/pyyaml-6.0.3-cp312-cp312-win_amd64.whl", hash = "sha256:5fcd34e47f6e0b794d17de1b4ff496c00986e1c83f7ab2fb8fcfe9616ff7477b", size = 154003, upload-time = "2025-09-25T21:32:21.167Z" }, + { url = "https://files.pythonhosted.org/packages/1a/08/67bd04656199bbb51dbed1439b7f27601dfb576fb864099c7ef0c3e55531/pyyaml-6.0.3-cp312-cp312-win_arm64.whl", hash = "sha256:64386e5e707d03a7e172c0701abfb7e10f0fb753ee1d773128192742712a98fd", size = 140344, upload-time = "2025-09-25T21:32:22.617Z" }, ] [[package]] name = "pyzmq" -version = "27.0.0" +version = "27.1.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "cffi", marker = "implementation_name == 'pypy'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/f1/06/50a4e9648b3e8b992bef8eb632e457307553a89d294103213cfd47b3da69/pyzmq-27.0.0.tar.gz", hash = "sha256:b1f08eeb9ce1510e6939b6e5dcd46a17765e2333daae78ecf4606808442e52cf", size = 280478, upload-time = "2025-06-13T14:09:07.087Z" } +sdist = { url = "https://files.pythonhosted.org/packages/04/0b/3c9baedbdf613ecaa7aa07027780b8867f57b6293b6ee50de316c9f3222b/pyzmq-27.1.0.tar.gz", hash = "sha256:ac0765e3d44455adb6ddbf4417dcce460fc40a05978c08efdf2948072f6db540", size = 281750, upload-time = "2025-09-08T23:10:18.157Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/44/df/84c630654106d9bd9339cdb564aa941ed41b023a0264251d6743766bb50e/pyzmq-27.0.0-cp311-cp311-macosx_10_15_universal2.whl", hash = "sha256:21457825249b2a53834fa969c69713f8b5a79583689387a5e7aed880963ac564", size = 1332718, upload-time = "2025-06-13T14:07:16.555Z" }, - { url = "https://files.pythonhosted.org/packages/c1/8e/f6a5461a07654d9840d256476434ae0ff08340bba562a455f231969772cb/pyzmq-27.0.0-cp311-cp311-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:1958947983fef513e6e98eff9cb487b60bf14f588dc0e6bf35fa13751d2c8251", size = 908248, upload-time = "2025-06-13T14:07:18.033Z" }, - { url = "https://files.pythonhosted.org/packages/7c/93/82863e8d695a9a3ae424b63662733ae204a295a2627d52af2f62c2cd8af9/pyzmq-27.0.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c0dc628b5493f9a8cd9844b8bee9732ef587ab00002157c9329e4fc0ef4d3afa", size = 668647, upload-time = "2025-06-13T14:07:19.378Z" }, - { url = "https://files.pythonhosted.org/packages/f3/85/15278769b348121eacdbfcbd8c4d40f1102f32fa6af5be1ffc032ed684be/pyzmq-27.0.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f7bbe9e1ed2c8d3da736a15694d87c12493e54cc9dc9790796f0321794bbc91f", size = 856600, upload-time = "2025-06-13T14:07:20.906Z" }, - { url = "https://files.pythonhosted.org/packages/d4/af/1c469b3d479bd095edb28e27f12eee10b8f00b356acbefa6aeb14dd295d1/pyzmq-27.0.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:dc1091f59143b471d19eb64f54bae4f54bcf2a466ffb66fe45d94d8d734eb495", size = 1657748, upload-time = "2025-06-13T14:07:22.549Z" }, - { url = "https://files.pythonhosted.org/packages/8c/f4/17f965d0ee6380b1d6326da842a50e4b8b9699745161207945f3745e8cb5/pyzmq-27.0.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:7011ade88c8e535cf140f8d1a59428676fbbce7c6e54fefce58bf117aefb6667", size = 2034311, upload-time = "2025-06-13T14:07:23.966Z" }, - { url = "https://files.pythonhosted.org/packages/e0/6e/7c391d81fa3149fd759de45d298003de6cfab343fb03e92c099821c448db/pyzmq-27.0.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:2c386339d7e3f064213aede5d03d054b237937fbca6dd2197ac8cf3b25a6b14e", size = 1893630, upload-time = "2025-06-13T14:07:25.899Z" }, - { url = "https://files.pythonhosted.org/packages/0e/e0/eaffe7a86f60e556399e224229e7769b717f72fec0706b70ab2c03aa04cb/pyzmq-27.0.0-cp311-cp311-win32.whl", hash = "sha256:0546a720c1f407b2172cb04b6b094a78773491497e3644863cf5c96c42df8cff", size = 567706, upload-time = "2025-06-13T14:07:27.595Z" }, - { url = "https://files.pythonhosted.org/packages/c9/05/89354a8cffdcce6e547d48adaaf7be17007fc75572123ff4ca90a4ca04fc/pyzmq-27.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:15f39d50bd6c9091c67315ceb878a4f531957b121d2a05ebd077eb35ddc5efed", size = 630322, upload-time = "2025-06-13T14:07:28.938Z" }, - { url = "https://files.pythonhosted.org/packages/fa/07/4ab976d5e1e63976719389cc4f3bfd248a7f5f2bb2ebe727542363c61b5f/pyzmq-27.0.0-cp311-cp311-win_arm64.whl", hash = "sha256:c5817641eebb391a2268c27fecd4162448e03538387093cdbd8bf3510c316b38", size = 558435, upload-time = "2025-06-13T14:07:30.256Z" }, - { url = "https://files.pythonhosted.org/packages/93/a7/9ad68f55b8834ede477842214feba6a4c786d936c022a67625497aacf61d/pyzmq-27.0.0-cp312-abi3-macosx_10_15_universal2.whl", hash = "sha256:cbabc59dcfaac66655c040dfcb8118f133fb5dde185e5fc152628354c1598e52", size = 1305438, upload-time = "2025-06-13T14:07:31.676Z" }, - { url = "https://files.pythonhosted.org/packages/ba/ee/26aa0f98665a22bc90ebe12dced1de5f3eaca05363b717f6fb229b3421b3/pyzmq-27.0.0-cp312-abi3-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:cb0ac5179cba4b2f94f1aa208fbb77b62c4c9bf24dd446278b8b602cf85fcda3", size = 895095, upload-time = "2025-06-13T14:07:33.104Z" }, - { url = "https://files.pythonhosted.org/packages/cf/85/c57e7ab216ecd8aa4cc7e3b83b06cc4e9cf45c87b0afc095f10cd5ce87c1/pyzmq-27.0.0-cp312-abi3-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:53a48f0228eab6cbf69fde3aa3c03cbe04e50e623ef92ae395fce47ef8a76152", size = 651826, upload-time = "2025-06-13T14:07:34.831Z" }, - { url = "https://files.pythonhosted.org/packages/69/9a/9ea7e230feda9400fb0ae0d61d7d6ddda635e718d941c44eeab22a179d34/pyzmq-27.0.0-cp312-abi3-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:111db5f395e09f7e775f759d598f43cb815fc58e0147623c4816486e1a39dc22", size = 839750, upload-time = "2025-06-13T14:07:36.553Z" }, - { url = "https://files.pythonhosted.org/packages/08/66/4cebfbe71f3dfbd417011daca267539f62ed0fbc68105357b68bbb1a25b7/pyzmq-27.0.0-cp312-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:c8878011653dcdc27cc2c57e04ff96f0471e797f5c19ac3d7813a245bcb24371", size = 1641357, upload-time = "2025-06-13T14:07:38.21Z" }, - { url = "https://files.pythonhosted.org/packages/ac/f6/b0f62578c08d2471c791287149cb8c2aaea414ae98c6e995c7dbe008adfb/pyzmq-27.0.0-cp312-abi3-musllinux_1_2_i686.whl", hash = "sha256:c0ed2c1f335ba55b5fdc964622254917d6b782311c50e138863eda409fbb3b6d", size = 2020281, upload-time = "2025-06-13T14:07:39.599Z" }, - { url = "https://files.pythonhosted.org/packages/37/b9/4f670b15c7498495da9159edc374ec09c88a86d9cd5a47d892f69df23450/pyzmq-27.0.0-cp312-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:e918d70862d4cfd4b1c187310015646a14e1f5917922ab45b29f28f345eeb6be", size = 1877110, upload-time = "2025-06-13T14:07:41.027Z" }, - { url = "https://files.pythonhosted.org/packages/66/31/9dee25c226295b740609f0d46db2fe972b23b6f5cf786360980524a3ba92/pyzmq-27.0.0-cp312-abi3-win32.whl", hash = "sha256:88b4e43cab04c3c0f0d55df3b1eef62df2b629a1a369b5289a58f6fa8b07c4f4", size = 559297, upload-time = "2025-06-13T14:07:42.533Z" }, - { url = "https://files.pythonhosted.org/packages/9b/12/52da5509800f7ff2d287b2f2b4e636e7ea0f001181cba6964ff6c1537778/pyzmq-27.0.0-cp312-abi3-win_amd64.whl", hash = "sha256:dce4199bf5f648a902ce37e7b3afa286f305cd2ef7a8b6ec907470ccb6c8b371", size = 619203, upload-time = "2025-06-13T14:07:43.843Z" }, - { url = "https://files.pythonhosted.org/packages/93/6d/7f2e53b19d1edb1eb4f09ec7c3a1f945ca0aac272099eab757d15699202b/pyzmq-27.0.0-cp312-abi3-win_arm64.whl", hash = "sha256:56e46bbb85d52c1072b3f809cc1ce77251d560bc036d3a312b96db1afe76db2e", size = 551927, upload-time = "2025-06-13T14:07:45.51Z" }, - { url = "https://files.pythonhosted.org/packages/98/a6/92394373b8dbc1edc9d53c951e8d3989d518185174ee54492ec27711779d/pyzmq-27.0.0-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:cd1dc59763effd1576f8368047c9c31468fce0af89d76b5067641137506792ae", size = 835948, upload-time = "2025-06-13T14:08:43.516Z" }, - { url = "https://files.pythonhosted.org/packages/56/f3/4dc38d75d9995bfc18773df3e41f2a2ca9b740b06f1a15dbf404077e7588/pyzmq-27.0.0-pp311-pypy311_pp73-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:60e8cc82d968174650c1860d7b716366caab9973787a1c060cf8043130f7d0f7", size = 799874, upload-time = "2025-06-13T14:08:45.017Z" }, - { url = "https://files.pythonhosted.org/packages/ab/ba/64af397e0f421453dc68e31d5e0784d554bf39013a2de0872056e96e58af/pyzmq-27.0.0-pp311-pypy311_pp73-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:14fe7aaac86e4e93ea779a821967360c781d7ac5115b3f1a171ced77065a0174", size = 567400, upload-time = "2025-06-13T14:08:46.855Z" }, - { url = "https://files.pythonhosted.org/packages/63/87/ec956cbe98809270b59a22891d5758edae147a258e658bf3024a8254c855/pyzmq-27.0.0-pp311-pypy311_pp73-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6ad0562d4e6abb785be3e4dd68599c41be821b521da38c402bc9ab2a8e7ebc7e", size = 747031, upload-time = "2025-06-13T14:08:48.419Z" }, - { url = "https://files.pythonhosted.org/packages/be/8a/4a3764a68abc02e2fbb0668d225b6fda5cd39586dd099cee8b2ed6ab0452/pyzmq-27.0.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:9df43a2459cd3a3563404c1456b2c4c69564daa7dbaf15724c09821a3329ce46", size = 544726, upload-time = "2025-06-13T14:08:49.903Z" }, + { url = "https://files.pythonhosted.org/packages/92/e7/038aab64a946d535901103da16b953c8c9cc9c961dadcbf3609ed6428d23/pyzmq-27.1.0-cp312-abi3-macosx_10_15_universal2.whl", hash = "sha256:452631b640340c928fa343801b0d07eb0c3789a5ffa843f6e1a9cee0ba4eb4fc", size = 1306279, upload-time = "2025-09-08T23:08:03.807Z" }, + { url = "https://files.pythonhosted.org/packages/e8/5e/c3c49fdd0f535ef45eefcc16934648e9e59dace4a37ee88fc53f6cd8e641/pyzmq-27.1.0-cp312-abi3-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:1c179799b118e554b66da67d88ed66cd37a169f1f23b5d9f0a231b4e8d44a113", size = 895645, upload-time = "2025-09-08T23:08:05.301Z" }, + { url = "https://files.pythonhosted.org/packages/f8/e5/b0b2504cb4e903a74dcf1ebae157f9e20ebb6ea76095f6cfffea28c42ecd/pyzmq-27.1.0-cp312-abi3-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3837439b7f99e60312f0c926a6ad437b067356dc2bc2ec96eb395fd0fe804233", size = 652574, upload-time = "2025-09-08T23:08:06.828Z" }, + { url = "https://files.pythonhosted.org/packages/f8/9b/c108cdb55560eaf253f0cbdb61b29971e9fb34d9c3499b0e96e4e60ed8a5/pyzmq-27.1.0-cp312-abi3-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:43ad9a73e3da1fab5b0e7e13402f0b2fb934ae1c876c51d0afff0e7c052eca31", size = 840995, upload-time = "2025-09-08T23:08:08.396Z" }, + { url = "https://files.pythonhosted.org/packages/c2/bb/b79798ca177b9eb0825b4c9998c6af8cd2a7f15a6a1a4272c1d1a21d382f/pyzmq-27.1.0-cp312-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:0de3028d69d4cdc475bfe47a6128eb38d8bc0e8f4d69646adfbcd840facbac28", size = 1642070, upload-time = "2025-09-08T23:08:09.989Z" }, + { url = "https://files.pythonhosted.org/packages/9c/80/2df2e7977c4ede24c79ae39dcef3899bfc5f34d1ca7a5b24f182c9b7a9ca/pyzmq-27.1.0-cp312-abi3-musllinux_1_2_i686.whl", hash = "sha256:cf44a7763aea9298c0aa7dbf859f87ed7012de8bda0f3977b6fb1d96745df856", size = 2021121, upload-time = "2025-09-08T23:08:11.907Z" }, + { url = "https://files.pythonhosted.org/packages/46/bd/2d45ad24f5f5ae7e8d01525eb76786fa7557136555cac7d929880519e33a/pyzmq-27.1.0-cp312-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:f30f395a9e6fbca195400ce833c731e7b64c3919aa481af4d88c3759e0cb7496", size = 1878550, upload-time = "2025-09-08T23:08:13.513Z" }, + { url = "https://files.pythonhosted.org/packages/e6/2f/104c0a3c778d7c2ab8190e9db4f62f0b6957b53c9d87db77c284b69f33ea/pyzmq-27.1.0-cp312-abi3-win32.whl", hash = "sha256:250e5436a4ba13885494412b3da5d518cd0d3a278a1ae640e113c073a5f88edd", size = 559184, upload-time = "2025-09-08T23:08:15.163Z" }, + { url = "https://files.pythonhosted.org/packages/fc/7f/a21b20d577e4100c6a41795842028235998a643b1ad406a6d4163ea8f53e/pyzmq-27.1.0-cp312-abi3-win_amd64.whl", hash = "sha256:9ce490cf1d2ca2ad84733aa1d69ce6855372cb5ce9223802450c9b2a7cba0ccf", size = 619480, upload-time = "2025-09-08T23:08:17.192Z" }, + { url = "https://files.pythonhosted.org/packages/78/c2/c012beae5f76b72f007a9e91ee9401cb88c51d0f83c6257a03e785c81cc2/pyzmq-27.1.0-cp312-abi3-win_arm64.whl", hash = "sha256:75a2f36223f0d535a0c919e23615fc85a1e23b71f40c7eb43d7b1dedb4d8f15f", size = 552993, upload-time = "2025-09-08T23:08:18.926Z" }, ] [[package]] @@ -4590,32 +1112,37 @@ wheels = [ ] [[package]] -name = "raylib" -version = "5.5.0.2" -source = { registry = "https://pypi.org/simple" } +name = "rednose" +version = "0.0.1" +source = { editable = "rednose_repo" } dependencies = [ { name = "cffi" }, + { name = "comma-deps-eigen" }, + { name = "cython" }, + { name = "numpy" }, + { name = "scons" }, + { name = "setuptools" }, + { name = "sympy" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/8c/35/9bf3a2af73c55fd4310dcaec4f997c739888e0db9b4dfac71b7680810852/raylib-5.5.0.2.tar.gz", hash = "sha256:83c108ae3b4af40b53c93d1de2afbe309e986dd5efeb280ebe2e61c79956edb0", size = 181172, upload-time = "2024-11-26T11:12:02.791Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/9e/c4/ce21721b474eb8f65379f7315b382ccfe1d5df728eea4dcf287b874e7461/raylib-5.5.0.2-cp311-cp311-macosx_10_13_x86_64.whl", hash = "sha256:37eb0ec97fc6b08f989489a50e09b5dde519e1bb8eb17e4033ac82227b0e5eda", size = 1703742, upload-time = "2024-11-26T11:09:31.115Z" }, - { url = "https://files.pythonhosted.org/packages/23/61/138e305c82549869bb8cd41abe75571559eafbeab6aed1ce7d8fbe3ffd58/raylib-5.5.0.2-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:bb9e506ecd3dbec6dba868eb036269837a8bde68220690842c3238239ee887ef", size = 1247449, upload-time = "2024-11-26T11:09:34.182Z" }, - { url = "https://files.pythonhosted.org/packages/85/e0/dc638c42d1a505f0992263d48e1434d82c21afdf376b06f549d2e281dfd4/raylib-5.5.0.2-cp311-cp311-manylinux2014_aarch64.whl", hash = "sha256:70aa8bed67875a8cf25191f35263ef92d646bdfcb1f507915c81562a321f4931", size = 2184315, upload-time = "2024-11-26T11:09:36.715Z" }, - { url = "https://files.pythonhosted.org/packages/c9/1a/49db57283a28fdc1ff0e4604911b7fff085128c2ac8bdd9efa8c5c47439d/raylib-5.5.0.2-cp311-cp311-manylinux2014_x86_64.whl", hash = "sha256:0365e8c578f72f598795d9377fc70342f0d62aa193c2f304ca048b3e28866752", size = 2278139, upload-time = "2024-11-26T11:09:39.475Z" }, - { url = "https://files.pythonhosted.org/packages/f0/8a/e1a690ab6889d4cb67346a2d32bad8b8e8b0f85ec826b00f76b0ad7e6ad6/raylib-5.5.0.2-cp311-cp311-win_amd64.whl", hash = "sha256:5219be70e7fca03e9c4fddebf7e60e885d77137125c7a13f3800a947f8562a13", size = 1693944, upload-time = "2024-11-26T11:09:41.596Z" }, - { url = "https://files.pythonhosted.org/packages/69/2b/49bfa6833ad74ddf318d54ecafe73d535f583531469ecbd5b009d79667d1/raylib-5.5.0.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:5233c529d9a0cfd469d88239c2182e55c5215a7755d83cc3d611148d3b9c9e67", size = 1706157, upload-time = "2024-11-26T11:09:43.6Z" }, - { url = "https://files.pythonhosted.org/packages/58/9c/8a3f4de0c81ad1228bf26410cfe3ecdc73011c59f18e542685ffc92c0120/raylib-5.5.0.2-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:1f76204ffbc492722b571b12dbdc0dca89b10da76ddf48c12a3968d2db061dff", size = 1248027, upload-time = "2025-01-04T20:21:46.269Z" }, - { url = "https://files.pythonhosted.org/packages/7f/16/63baf1aae94832b9f5d15cafcee67bb6dd07a20cf64d40bac09903b79274/raylib-5.5.0.2-cp312-cp312-manylinux2014_aarch64.whl", hash = "sha256:f8cc2e39f1d6b29211a97ec0ac818a5b04c43a40e747e4b4622101d48c711f9e", size = 2195374, upload-time = "2024-11-26T11:09:46.114Z" }, - { url = "https://files.pythonhosted.org/packages/70/bd/61a006b4e3ce4a6ca974cb0ceeb19f3816815ebabac650e9bf82767e65f6/raylib-5.5.0.2-cp312-cp312-manylinux2014_x86_64.whl", hash = "sha256:f12da578a28da7f48481f46323e5aab8dd25461982b0e80d045782d6e69649f5", size = 2299593, upload-time = "2024-11-26T11:09:48.963Z" }, - { url = "https://files.pythonhosted.org/packages/f4/4f/59d554cc495bea8235b17cebfc76ed57aaa602c613b870159e31282fd4c1/raylib-5.5.0.2-cp312-cp312-win_amd64.whl", hash = "sha256:b40234bbad9523fd6a2049640c76a98b4d6f0b8f4bd19bd33eaee55faf5e050d", size = 1696780, upload-time = "2024-11-26T11:09:50.787Z" }, - { url = "https://files.pythonhosted.org/packages/4a/22/2e02e3738ad041f5ec2830aecdfab411fc2960bfc3400e03b477284bfaf7/raylib-5.5.0.2-pp311-pypy311_pp73-macosx_10_13_x86_64.whl", hash = "sha256:bc45fe1c0aac50aa319a9a66d44bb2bd0dcd038a44d95978191ae7bfeb4a06d8", size = 1216231, upload-time = "2025-02-12T04:21:59.38Z" }, - { url = "https://files.pythonhosted.org/packages/fe/7d/b29afedc4a706b12143f74f322cb32ad5a6f43e56aaca2a9fb89b0d94eee/raylib-5.5.0.2-pp311-pypy311_pp73-manylinux2014_x86_64.whl", hash = "sha256:2242fd6079da5137e9863a447224f800adef6386ca8f59013a5d62cc5cadab2b", size = 1394928, upload-time = "2025-02-12T04:22:03.021Z" }, - { url = "https://files.pythonhosted.org/packages/b6/fa/2daf36d78078c6871b241168a36156169cfc8ea089faba5abe8edad304be/raylib-5.5.0.2-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:e475a40764c9f83f9e66406bd86d85587eb923329a61ade463c3c59e1e880b16", size = 1564224, upload-time = "2025-02-12T04:22:05.911Z" }, + +[package.metadata] +requires-dist = [ + { name = "cffi" }, + { name = "comma-deps-eigen" }, + { name = "cython" }, + { name = "numpy" }, + { name = "ruff", marker = "extra == 'dev'" }, + { name = "scipy", marker = "extra == 'dev'" }, + { name = "scons" }, + { name = "setuptools" }, + { name = "sympy" }, + { name = "ty", marker = "extra == 'dev'" }, ] +provides-extras = ["dev"] [[package]] name = "requests" -version = "2.32.4" +version = "2.34.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "certifi" }, @@ -4623,210 +1150,83 @@ dependencies = [ { name = "idna" }, { name = "urllib3" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/e1/0a/929373653770d8a0d7ea76c37de6e41f11eb07559b103b1c02cafb3f7cf8/requests-2.32.4.tar.gz", hash = "sha256:27d0316682c8a29834d3264820024b62a36942083d52caf2f14c0591336d3422", size = 135258, upload-time = "2025-06-09T16:43:07.34Z" } +sdist = { url = "https://files.pythonhosted.org/packages/ac/c3/e2a2b89f2d3e2179abd6d00ebd70bff6273f37fb3e0cc209f48b39d00cbf/requests-2.34.2.tar.gz", hash = "sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed", size = 142856, upload-time = "2026-05-14T19:25:27.735Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/7c/e4/56027c4a6b4ae70ca9de302488c5ca95ad4a39e190093d6c1a8ace08341b/requests-2.32.4-py3-none-any.whl", hash = "sha256:27babd3cda2a6d50b30443204ee89830707d396671944c998b5975b031ac2b2c", size = 64847, upload-time = "2025-06-09T16:43:05.728Z" }, -] - -[[package]] -name = "rerun-sdk" -version = "0.23.3" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "attrs" }, - { name = "numpy" }, - { name = "pillow" }, - { name = "pyarrow" }, - { name = "typing-extensions" }, -] -wheels = [ - { url = "https://files.pythonhosted.org/packages/00/54/710685ea836d91f14422de515262a9db5c2a17777e59ae4c1c19b46c1fa0/rerun_sdk-0.23.3-cp39-abi3-macosx_10_12_x86_64.whl", hash = "sha256:8a048ace69443aeb4040046d4bc28ba17be2c6862df7c2161e21b0608d5d6e0f", size = 59486089, upload-time = "2025-05-26T16:08:08.395Z" }, - { url = "https://files.pythonhosted.org/packages/26/81/b94c23cde1b9ed54900f47e337f8e156d9fdec7494eaa11bbb592c26a5d9/rerun_sdk-0.23.3-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:a3ef05acfa9315d956c69eb680a50e46c802ba27eb8025bab71e14a989299383", size = 55128863, upload-time = "2025-05-26T16:08:13.328Z" }, - { url = "https://files.pythonhosted.org/packages/02/bc/c32f71969a5d981087fded194012ef162391e49dba71ba5115a17c642065/rerun_sdk-0.23.3-cp39-abi3-manylinux_2_31_aarch64.whl", hash = "sha256:0cc9c60f1180edca1a4d70dbe591eb108e4dbe599c31136949b8d4106410cd14", size = 61603766, upload-time = "2025-05-26T16:08:17.476Z" }, - { url = "https://files.pythonhosted.org/packages/fa/ef/93b6a8932747842e5f7c27f3ce7ef82bbc046aad3b7d5b2e905ffc5614a7/rerun_sdk-0.23.3-cp39-abi3-manylinux_2_31_x86_64.whl", hash = "sha256:49833bf3a4854eaf287a8bfe7dfa4cd8f67b0fd7917a469c8bb7061895fb1cf8", size = 64875203, upload-time = "2025-05-26T16:08:21.95Z" }, - { url = "https://files.pythonhosted.org/packages/c5/36/759287d69301a3ada86ee102369a9521dfef0bb91b215e98a6a7b262a311/rerun_sdk-0.23.3-cp39-abi3-win_amd64.whl", hash = "sha256:88639632116b3761e2a45f4e5ac39eaf3406b615f516baccb508d93c6b42cc4e", size = 50862558, upload-time = "2025-05-26T16:08:26.98Z" }, -] - -[[package]] -name = "ruamel-yaml" -version = "0.18.14" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "ruamel-yaml-clib", marker = "platform_python_implementation == 'CPython'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/39/87/6da0df742a4684263261c253f00edd5829e6aca970fff69e75028cccc547/ruamel.yaml-0.18.14.tar.gz", hash = "sha256:7227b76aaec364df15936730efbf7d72b30c0b79b1d578bbb8e3dcb2d81f52b7", size = 145511, upload-time = "2025-06-09T08:51:09.828Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/af/6d/6fe4805235e193aad4aaf979160dd1f3c487c57d48b810c816e6e842171b/ruamel.yaml-0.18.14-py3-none-any.whl", hash = "sha256:710ff198bb53da66718c7db27eec4fbcc9aa6ca7204e4c1df2f282b6fe5eb6b2", size = 118570, upload-time = "2025-06-09T08:51:06.348Z" }, -] - -[[package]] -name = "ruamel-yaml-clib" -version = "0.2.12" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/20/84/80203abff8ea4993a87d823a5f632e4d92831ef75d404c9fc78d0176d2b5/ruamel.yaml.clib-0.2.12.tar.gz", hash = "sha256:6c8fbb13ec503f99a91901ab46e0b07ae7941cd527393187039aec586fdfd36f", size = 225315, upload-time = "2024-10-20T10:10:56.22Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/fb/8f/683c6ad562f558cbc4f7c029abcd9599148c51c54b5ef0f24f2638da9fbb/ruamel.yaml.clib-0.2.12-cp311-cp311-macosx_13_0_arm64.whl", hash = "sha256:4a6679521a58256a90b0d89e03992c15144c5f3858f40d7c18886023d7943db6", size = 132224, upload-time = "2024-10-20T10:12:45.162Z" }, - { url = "https://files.pythonhosted.org/packages/3c/d2/b79b7d695e2f21da020bd44c782490578f300dd44f0a4c57a92575758a76/ruamel.yaml.clib-0.2.12-cp311-cp311-manylinux2014_aarch64.whl", hash = "sha256:d84318609196d6bd6da0edfa25cedfbabd8dbde5140a0a23af29ad4b8f91fb1e", size = 641480, upload-time = "2024-10-20T10:12:46.758Z" }, - { url = "https://files.pythonhosted.org/packages/68/6e/264c50ce2a31473a9fdbf4fa66ca9b2b17c7455b31ef585462343818bd6c/ruamel.yaml.clib-0.2.12-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bb43a269eb827806502c7c8efb7ae7e9e9d0573257a46e8e952f4d4caba4f31e", size = 739068, upload-time = "2024-10-20T10:12:48.605Z" }, - { url = "https://files.pythonhosted.org/packages/86/29/88c2567bc893c84d88b4c48027367c3562ae69121d568e8a3f3a8d363f4d/ruamel.yaml.clib-0.2.12-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:811ea1594b8a0fb466172c384267a4e5e367298af6b228931f273b111f17ef52", size = 703012, upload-time = "2024-10-20T10:12:51.124Z" }, - { url = "https://files.pythonhosted.org/packages/11/46/879763c619b5470820f0cd6ca97d134771e502776bc2b844d2adb6e37753/ruamel.yaml.clib-0.2.12-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:cf12567a7b565cbf65d438dec6cfbe2917d3c1bdddfce84a9930b7d35ea59642", size = 704352, upload-time = "2024-10-21T11:26:41.438Z" }, - { url = "https://files.pythonhosted.org/packages/02/80/ece7e6034256a4186bbe50dee28cd032d816974941a6abf6a9d65e4228a7/ruamel.yaml.clib-0.2.12-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:7dd5adc8b930b12c8fc5b99e2d535a09889941aa0d0bd06f4749e9a9397c71d2", size = 737344, upload-time = "2024-10-21T11:26:43.62Z" }, - { url = "https://files.pythonhosted.org/packages/f0/ca/e4106ac7e80efbabdf4bf91d3d32fc424e41418458251712f5672eada9ce/ruamel.yaml.clib-0.2.12-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:1492a6051dab8d912fc2adeef0e8c72216b24d57bd896ea607cb90bb0c4981d3", size = 714498, upload-time = "2024-12-11T19:58:15.592Z" }, - { url = "https://files.pythonhosted.org/packages/67/58/b1f60a1d591b771298ffa0428237afb092c7f29ae23bad93420b1eb10703/ruamel.yaml.clib-0.2.12-cp311-cp311-win32.whl", hash = "sha256:bd0a08f0bab19093c54e18a14a10b4322e1eacc5217056f3c063bd2f59853ce4", size = 100205, upload-time = "2024-10-20T10:12:52.865Z" }, - { url = "https://files.pythonhosted.org/packages/b4/4f/b52f634c9548a9291a70dfce26ca7ebce388235c93588a1068028ea23fcc/ruamel.yaml.clib-0.2.12-cp311-cp311-win_amd64.whl", hash = "sha256:a274fb2cb086c7a3dea4322ec27f4cb5cc4b6298adb583ab0e211a4682f241eb", size = 118185, upload-time = "2024-10-20T10:12:54.652Z" }, - { url = "https://files.pythonhosted.org/packages/48/41/e7a405afbdc26af961678474a55373e1b323605a4f5e2ddd4a80ea80f628/ruamel.yaml.clib-0.2.12-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:20b0f8dc160ba83b6dcc0e256846e1a02d044e13f7ea74a3d1d56ede4e48c632", size = 133433, upload-time = "2024-10-20T10:12:55.657Z" }, - { url = "https://files.pythonhosted.org/packages/ec/b0/b850385604334c2ce90e3ee1013bd911aedf058a934905863a6ea95e9eb4/ruamel.yaml.clib-0.2.12-cp312-cp312-manylinux2014_aarch64.whl", hash = "sha256:943f32bc9dedb3abff9879edc134901df92cfce2c3d5c9348f172f62eb2d771d", size = 647362, upload-time = "2024-10-20T10:12:57.155Z" }, - { url = "https://files.pythonhosted.org/packages/44/d0/3f68a86e006448fb6c005aee66565b9eb89014a70c491d70c08de597f8e4/ruamel.yaml.clib-0.2.12-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:95c3829bb364fdb8e0332c9931ecf57d9be3519241323c5274bd82f709cebc0c", size = 754118, upload-time = "2024-10-20T10:12:58.501Z" }, - { url = "https://files.pythonhosted.org/packages/52/a9/d39f3c5ada0a3bb2870d7db41901125dbe2434fa4f12ca8c5b83a42d7c53/ruamel.yaml.clib-0.2.12-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:749c16fcc4a2b09f28843cda5a193e0283e47454b63ec4b81eaa2242f50e4ccd", size = 706497, upload-time = "2024-10-20T10:13:00.211Z" }, - { url = "https://files.pythonhosted.org/packages/b0/fa/097e38135dadd9ac25aecf2a54be17ddf6e4c23e43d538492a90ab3d71c6/ruamel.yaml.clib-0.2.12-cp312-cp312-musllinux_1_1_i686.whl", hash = "sha256:bf165fef1f223beae7333275156ab2022cffe255dcc51c27f066b4370da81e31", size = 698042, upload-time = "2024-10-21T11:26:46.038Z" }, - { url = "https://files.pythonhosted.org/packages/ec/d5/a659ca6f503b9379b930f13bc6b130c9f176469b73b9834296822a83a132/ruamel.yaml.clib-0.2.12-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:32621c177bbf782ca5a18ba4d7af0f1082a3f6e517ac2a18b3974d4edf349680", size = 745831, upload-time = "2024-10-21T11:26:47.487Z" }, - { url = "https://files.pythonhosted.org/packages/db/5d/36619b61ffa2429eeaefaab4f3374666adf36ad8ac6330d855848d7d36fd/ruamel.yaml.clib-0.2.12-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:b82a7c94a498853aa0b272fd5bc67f29008da798d4f93a2f9f289feb8426a58d", size = 715692, upload-time = "2024-12-11T19:58:17.252Z" }, - { url = "https://files.pythonhosted.org/packages/b1/82/85cb92f15a4231c89b95dfe08b09eb6adca929ef7df7e17ab59902b6f589/ruamel.yaml.clib-0.2.12-cp312-cp312-win32.whl", hash = "sha256:e8c4ebfcfd57177b572e2040777b8abc537cdef58a2120e830124946aa9b42c5", size = 98777, upload-time = "2024-10-20T10:13:01.395Z" }, - { url = "https://files.pythonhosted.org/packages/d7/8f/c3654f6f1ddb75daf3922c3d8fc6005b1ab56671ad56ffb874d908bfa668/ruamel.yaml.clib-0.2.12-cp312-cp312-win_amd64.whl", hash = "sha256:0467c5965282c62203273b838ae77c0d29d7638c8a4e3a1c8bdd3602c10904e4", size = 115523, upload-time = "2024-10-20T10:13:02.768Z" }, -] - -[[package]] -name = "rubicon-objc" -version = "0.5.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/e0/83/e57741dcf862a2581d53eccf8b11749c97f73d9754bbc538fb6c7b527da3/rubicon_objc-0.5.1.tar.gz", hash = "sha256:90bee9fc1de4515e17615e15648989b88bb8d4d2ffc8c7c52748272cd7f30a66", size = 174639, upload-time = "2025-06-03T06:33:50.822Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/58/0a/e451c3dbda38dd6abab1fd16c3b35623fc0635dffcbbf97f1acc55a58508/rubicon_objc-0.5.1-py3-none-any.whl", hash = "sha256:17092756241b8370231cfaad45ad6e8ce99534987f2acbc944d65df5bdf8f6cd", size = 63323, upload-time = "2025-06-03T06:33:48.863Z" }, + { url = "https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl", hash = "sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0", size = 73075, upload-time = "2026-05-14T19:25:26.443Z" }, ] [[package]] name = "ruff" -version = "0.12.0" +version = "0.15.20" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/24/90/5255432602c0b196a0da6720f6f76b93eb50baef46d3c9b0025e2f9acbf3/ruff-0.12.0.tar.gz", hash = "sha256:4d047db3662418d4a848a3fdbfaf17488b34b62f527ed6f10cb8afd78135bc5c", size = 4376101, upload-time = "2025-06-17T15:19:26.217Z" } +sdist = { url = "https://files.pythonhosted.org/packages/43/dc/35b341fc554ba02f217fc10da57d1a75168cfbcf75b0ef2202176d4c4f2d/ruff-0.15.20.tar.gz", hash = "sha256:1416eb04349192646b54de98f146c4f59afe37d0decfc02c3cbbf396f3a28566", size = 4755489, upload-time = "2026-06-25T17:20:37.578Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/e6/fd/b46bb20e14b11ff49dbc74c61de352e0dc07fb650189513631f6fb5fc69f/ruff-0.12.0-py3-none-linux_armv6l.whl", hash = "sha256:5652a9ecdb308a1754d96a68827755f28d5dfb416b06f60fd9e13f26191a8848", size = 10311554, upload-time = "2025-06-17T15:18:45.792Z" }, - { url = "https://files.pythonhosted.org/packages/e7/d3/021dde5a988fa3e25d2468d1dadeea0ae89dc4bc67d0140c6e68818a12a1/ruff-0.12.0-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:05ed0c914fabc602fc1f3b42c53aa219e5736cb030cdd85640c32dbc73da74a6", size = 11118435, upload-time = "2025-06-17T15:18:49.064Z" }, - { url = "https://files.pythonhosted.org/packages/07/a2/01a5acf495265c667686ec418f19fd5c32bcc326d4c79ac28824aecd6a32/ruff-0.12.0-py3-none-macosx_11_0_arm64.whl", hash = "sha256:07a7aa9b69ac3fcfda3c507916d5d1bca10821fe3797d46bad10f2c6de1edda0", size = 10466010, upload-time = "2025-06-17T15:18:51.341Z" }, - { url = "https://files.pythonhosted.org/packages/4c/57/7caf31dd947d72e7aa06c60ecb19c135cad871a0a8a251723088132ce801/ruff-0.12.0-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e7731c3eec50af71597243bace7ec6104616ca56dda2b99c89935fe926bdcd48", size = 10661366, upload-time = "2025-06-17T15:18:53.29Z" }, - { url = "https://files.pythonhosted.org/packages/e9/ba/aa393b972a782b4bc9ea121e0e358a18981980856190d7d2b6187f63e03a/ruff-0.12.0-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:952d0630eae628250ab1c70a7fffb641b03e6b4a2d3f3ec6c1d19b4ab6c6c807", size = 10173492, upload-time = "2025-06-17T15:18:55.262Z" }, - { url = "https://files.pythonhosted.org/packages/d7/50/9349ee777614bc3062fc6b038503a59b2034d09dd259daf8192f56c06720/ruff-0.12.0-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c021f04ea06966b02614d442e94071781c424ab8e02ec7af2f037b4c1e01cc82", size = 11761739, upload-time = "2025-06-17T15:18:58.906Z" }, - { url = "https://files.pythonhosted.org/packages/04/8f/ad459de67c70ec112e2ba7206841c8f4eb340a03ee6a5cabc159fe558b8e/ruff-0.12.0-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:7d235618283718ee2fe14db07f954f9b2423700919dc688eacf3f8797a11315c", size = 12537098, upload-time = "2025-06-17T15:19:01.316Z" }, - { url = "https://files.pythonhosted.org/packages/ed/50/15ad9c80ebd3c4819f5bd8883e57329f538704ed57bac680d95cb6627527/ruff-0.12.0-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:0c0758038f81beec8cc52ca22de9685b8ae7f7cc18c013ec2050012862cc9165", size = 12154122, upload-time = "2025-06-17T15:19:03.727Z" }, - { url = "https://files.pythonhosted.org/packages/76/e6/79b91e41bc8cc3e78ee95c87093c6cacfa275c786e53c9b11b9358026b3d/ruff-0.12.0-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:139b3d28027987b78fc8d6cfb61165447bdf3740e650b7c480744873688808c2", size = 11363374, upload-time = "2025-06-17T15:19:05.875Z" }, - { url = "https://files.pythonhosted.org/packages/db/c3/82b292ff8a561850934549aa9dc39e2c4e783ab3c21debe55a495ddf7827/ruff-0.12.0-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:68853e8517b17bba004152aebd9dd77d5213e503a5f2789395b25f26acac0da4", size = 11587647, upload-time = "2025-06-17T15:19:08.246Z" }, - { url = "https://files.pythonhosted.org/packages/2b/42/d5760d742669f285909de1bbf50289baccb647b53e99b8a3b4f7ce1b2001/ruff-0.12.0-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:3a9512af224b9ac4757f7010843771da6b2b0935a9e5e76bb407caa901a1a514", size = 10527284, upload-time = "2025-06-17T15:19:10.37Z" }, - { url = "https://files.pythonhosted.org/packages/19/f6/fcee9935f25a8a8bba4adbae62495c39ef281256693962c2159e8b284c5f/ruff-0.12.0-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:b08df3d96db798e5beb488d4df03011874aff919a97dcc2dd8539bb2be5d6a88", size = 10158609, upload-time = "2025-06-17T15:19:12.286Z" }, - { url = "https://files.pythonhosted.org/packages/37/fb/057febf0eea07b9384787bfe197e8b3384aa05faa0d6bd844b94ceb29945/ruff-0.12.0-py3-none-musllinux_1_2_i686.whl", hash = "sha256:6a315992297a7435a66259073681bb0d8647a826b7a6de45c6934b2ca3a9ed51", size = 11141462, upload-time = "2025-06-17T15:19:15.195Z" }, - { url = "https://files.pythonhosted.org/packages/10/7c/1be8571011585914b9d23c95b15d07eec2d2303e94a03df58294bc9274d4/ruff-0.12.0-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:1e55e44e770e061f55a7dbc6e9aed47feea07731d809a3710feda2262d2d4d8a", size = 11641616, upload-time = "2025-06-17T15:19:17.6Z" }, - { url = "https://files.pythonhosted.org/packages/6a/ef/b960ab4818f90ff59e571d03c3f992828d4683561095e80f9ef31f3d58b7/ruff-0.12.0-py3-none-win32.whl", hash = "sha256:7162a4c816f8d1555eb195c46ae0bd819834d2a3f18f98cc63819a7b46f474fb", size = 10525289, upload-time = "2025-06-17T15:19:19.688Z" }, - { url = "https://files.pythonhosted.org/packages/34/93/8b16034d493ef958a500f17cda3496c63a537ce9d5a6479feec9558f1695/ruff-0.12.0-py3-none-win_amd64.whl", hash = "sha256:d00b7a157b8fb6d3827b49d3324da34a1e3f93492c1f97b08e222ad7e9b291e0", size = 11598311, upload-time = "2025-06-17T15:19:21.785Z" }, - { url = "https://files.pythonhosted.org/packages/d0/33/4d3e79e4a84533d6cd526bfb42c020a23256ae5e4265d858bd1287831f7d/ruff-0.12.0-py3-none-win_arm64.whl", hash = "sha256:8cd24580405ad8c1cc64d61725bca091d6b6da7eb3d36f72cc605467069d7e8b", size = 10724946, upload-time = "2025-06-17T15:19:23.952Z" }, + { url = "https://files.pythonhosted.org/packages/94/d9/2d5014f0253ba541d2061d9fa7193f48e941c8b21bb88a7ff9bbe0bd0596/ruff-0.15.20-py3-none-linux_armv6l.whl", hash = "sha256:00e188c53e499c3c1637f73c91dcf2fb56d576cab76ce1be50a27c4e80e37078", size = 10839665, upload-time = "2026-06-25T17:19:44.702Z" }, + { url = "https://files.pythonhosted.org/packages/c6/d3/ac1798ba64f670698867fcfc591d50e7e421bef137db564858f619a30fcf/ruff-0.15.20-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:9ebd1fd9b9c95fc0bd7b2761aebec1f030013d2e193a2901b224af68fe47251b", size = 11208649, upload-time = "2026-06-25T17:19:48.787Z" }, + { url = "https://files.pythonhosted.org/packages/47/47/d3ac899991202095dfcf3d5176be4272642be3cf981a2f1a30f72a2afb95/ruff-0.15.20-py3-none-macosx_11_0_arm64.whl", hash = "sha256:c5b16cdd67ca108185cd36dce98c576350c03b1660a751de725fb049193a0632", size = 10622638, upload-time = "2026-06-25T17:19:51.354Z" }, + { url = "https://files.pythonhosted.org/packages/33/13/4e043fe30aa94d4ff5213a9881fc296d12960f5971b234a5263fdc225312/ruff-0.15.20-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3413bb3c3d2ca6a8208f1f4809cd2dca3c6de6d0b491c0e70847672bde6e6efd", size = 10984227, upload-time = "2026-06-25T17:19:54.044Z" }, + { url = "https://files.pythonhosted.org/packages/76/e6/92e7bf40388bc5800073b96564f56264f7e48bfd1a498f5ced6ae6d5a769/ruff-0.15.20-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:bd7ec42b3bb3da066488db093308a69c4ac5ee6d2af333a86ba6e2eb2e7dd44b", size = 10622882, upload-time = "2026-06-25T17:19:57.037Z" }, + { url = "https://files.pythonhosted.org/packages/13/7a/43460be3f24495a3aa46d4b16873e2c4941b3b5f0b00cf88c03b7b94b339/ruff-0.15.20-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e1a36ad0eb77fba9aabfb69ede54de6f376d04ac18ebea022847046d340a8267", size = 11474808, upload-time = "2026-06-25T17:20:00.357Z" }, + { url = "https://files.pythonhosted.org/packages/27/a0/f37077884873221c6b33b4ab49eb18f9f88e54a16a25a5bca59bef46dd66/ruff-0.15.20-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:b6df3b1e4610432f0386dba04d853b5f08cbbc903410c6fcc02f620f05aff53c", size = 12293094, upload-time = "2026-06-25T17:20:03.446Z" }, + { url = "https://files.pythonhosted.org/packages/a6/74/165545b60256a9704c21ac0ec4a0d07933b320812f9584836c9f4aca4292/ruff-0.15.20-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e89f198a1ea6ef0d727c1cf16088bc91a6cb0ab947dedc966715691647186eae", size = 11526176, upload-time = "2026-06-25T17:20:06.301Z" }, + { url = "https://files.pythonhosted.org/packages/86/b1/a976a136d40ade83ce743578399865f57001003a409acadc0ecbb3051082/ruff-0.15.20-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:309809086c2acb67624950a3c8133e80f32d0d3e27106c0cd60ff26657c9f24b", size = 11520767, upload-time = "2026-06-25T17:20:09.191Z" }, + { url = "https://files.pythonhosted.org/packages/19/0f/f032696cb01c9b54c0263fa393474d7758f1cdc021a01b04e3cbc2500999/ruff-0.15.20-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:2d2374caa2f2c2f9e2b7da0a50802cfb8b79f55a9b5e49379f564544fbf56487", size = 11500132, upload-time = "2026-06-25T17:20:13.602Z" }, + { url = "https://files.pythonhosted.org/packages/4b/f4/51b1a14bc69e8c224b15dab9cce8e99b425e0455d462caa2b3c9be2b6a8e/ruff-0.15.20-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:a1ed17b65293e0c2f22fc387bc13198a5de94bf4429589b0ff6946b0feaf21a3", size = 10943828, upload-time = "2026-06-25T17:20:16.635Z" }, + { url = "https://files.pythonhosted.org/packages/71/4b/fe267640783cd02bf6c5cc290b1df1051be2ec294c678b5c15fe19e52343/ruff-0.15.20-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:f701305e66b38ea6c91882490eb73459796808e4c6362a1b765255e0cdcd4053", size = 10645418, upload-time = "2026-06-25T17:20:19.4Z" }, + { url = "https://files.pythonhosted.org/packages/b0/c0/a65aa4ec2f5e87a1df32dc3ec1fede434fe3dfd5cbcf3b503cafc676ab54/ruff-0.15.20-py3-none-musllinux_1_2_i686.whl", hash = "sha256:5b9c0c367ad8e5d0d5b5b8537864c469a0a0e55417aadfbeca41fa61333be9f4", size = 11211770, upload-time = "2026-06-25T17:20:22.033Z" }, + { url = "https://files.pythonhosted.org/packages/5a/a4/0caa331d954ae2723d729d351c989cb4ca8b6077d5c6c2cb6de75e98c041/ruff-0.15.20-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:01cc00dd58f0df339d0e902219dd53990ea99996a0344e5d9cc8d45d5307e460", size = 11618698, upload-time = "2026-06-25T17:20:25.259Z" }, + { url = "https://files.pythonhosted.org/packages/10/9b/5f14927848d2fd4aa891fd88d883788c5a7baba561c7874732364045708c/ruff-0.15.20-py3-none-win32.whl", hash = "sha256:ed65ef510e43a137207e0f01cfcf998aeddb1aeeda5c9d35023e910284d7cf21", size = 10857322, upload-time = "2026-06-25T17:20:28.612Z" }, + { url = "https://files.pythonhosted.org/packages/fa/f0/fe47c501f9dea92a26d788ff98bb5d92ed4cb4c88792c5c88af6b697dc8e/ruff-0.15.20-py3-none-win_amd64.whl", hash = "sha256:a525c81c70fb0380344dd1d8745d8cc1c890b7fc94a58d5a07bd8eb9557b8415", size = 11993274, upload-time = "2026-06-25T17:20:31.871Z" }, + { url = "https://files.pythonhosted.org/packages/d7/2b/9555445e1201d92b3195f45cdb153a0b68f24e0a4273f6e3d5ab46e212bb/ruff-0.15.20-py3-none-win_arm64.whl", hash = "sha256:2f5b2a6d614e8700388806a14996c40fab2c47b819ef57d790a34878858ed9ca", size = 11343498, upload-time = "2026-06-25T17:20:35.03Z" }, ] [[package]] name = "scons" -version = "4.9.1" +version = "4.10.1" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/c8/c1/30176c76c1ef723fab62e5cdb15d3c972427a146cb6f868748613d7b25af/scons-4.9.1.tar.gz", hash = "sha256:bacac880ba2e86d6a156c116e2f8f2bfa82b257046f3ac2666c85c53c615c338", size = 3252106, upload-time = "2025-03-27T20:42:19.765Z" } +sdist = { url = "https://files.pythonhosted.org/packages/7d/c9/2f430bb39e4eccba32ce8008df4a3206df651276422204e177a09e12b30b/scons-4.10.1.tar.gz", hash = "sha256:99c0e94a42a2c1182fa6859b0be697953db07ba936ecc9817ae0d218ced20b15", size = 3258403, upload-time = "2025-11-16T22:43:39.258Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/45/92/50b739021983b131dcacd57aa8b04d31c5acc2e7e0eb4ed4a362f438c6b7/scons-4.9.1-py3-none-any.whl", hash = "sha256:d2db1a22eb6039e97cbbb0106f18f435af033d0aad190299c9688378e2810a5e", size = 4131331, upload-time = "2025-03-27T20:42:16.665Z" }, + { url = "https://files.pythonhosted.org/packages/ce/bf/931fb9fbb87234c32b8b1b1c15fba23472a10777c12043336675633809a7/scons-4.10.1-py3-none-any.whl", hash = "sha256:bd9d1c52f908d874eba92a8c0c0a8dcf2ed9f3b88ab956d0fce1da479c4e7126", size = 4136069, upload-time = "2025-11-16T22:43:35.933Z" }, ] [[package]] name = "sentry-sdk" -version = "2.30.0" +version = "2.64.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "certifi" }, { name = "urllib3" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/04/4c/af31e0201b48469786ddeb1bf6fd3dfa3a291cc613a0fe6a60163a7535f9/sentry_sdk-2.30.0.tar.gz", hash = "sha256:436369b02afef7430efb10300a344fb61a11fe6db41c2b11f41ee037d2dd7f45", size = 326767, upload-time = "2025-06-12T10:34:34.733Z" } +sdist = { url = "https://files.pythonhosted.org/packages/60/31/b7341f156a5f6f36f0b4845d6f1c28a2ae4799171dba7007f3a1e9b234b4/sentry_sdk-2.64.0.tar.gz", hash = "sha256:68be2c29e14ae310f8a39e1a79916b6d85c6cb41dcce789d14ff05fe293e4c55", size = 921020, upload-time = "2026-06-30T08:13:47.682Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/5a/99/31ac6faaae33ea698086692638f58d14f121162a8db0039e68e94135e7f1/sentry_sdk-2.30.0-py2.py3-none-any.whl", hash = "sha256:59391db1550662f746ea09b483806a631c3ae38d6340804a1a4c0605044f6877", size = 343149, upload-time = "2025-06-12T10:34:32.896Z" }, + { url = "https://files.pythonhosted.org/packages/36/a8/3fb9a4319efa3b26f5be0e90e6d8918df43fa7c7e977d26390f589501d82/sentry_sdk-2.64.0-py3-none-any.whl", hash = "sha256:715ea91ca860a819e8d8a50a7bde3a80d0df3b4ed7b6660a20fb9a2d084188f1", size = 498901, upload-time = "2026-06-30T08:13:45.566Z" }, ] [[package]] name = "setproctitle" -version = "1.3.6" +version = "1.3.7" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/9e/af/56efe21c53ac81ac87e000b15e60b3d8104224b4313b6eacac3597bd183d/setproctitle-1.3.6.tar.gz", hash = "sha256:c9f32b96c700bb384f33f7cf07954bb609d35dd82752cef57fb2ee0968409169", size = 26889, upload-time = "2025-04-29T13:35:00.184Z" } +sdist = { url = "https://files.pythonhosted.org/packages/8d/48/49393a96a2eef1ab418b17475fb92b8fcfad83d099e678751b05472e69de/setproctitle-1.3.7.tar.gz", hash = "sha256:bc2bc917691c1537d5b9bca1468437176809c7e11e5694ca79a9ca12345dcb9e", size = 27002, upload-time = "2025-09-05T12:51:25.278Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/27/3b/8288d0cd969a63500dd62fc2c99ce6980f9909ccef0770ab1f86c361e0bf/setproctitle-1.3.6-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:a1d856b0f4e4a33e31cdab5f50d0a14998f3a2d726a3fd5cb7c4d45a57b28d1b", size = 17412, upload-time = "2025-04-29T13:32:58.135Z" }, - { url = "https://files.pythonhosted.org/packages/39/37/43a5a3e25ca1048dbbf4db0d88d346226f5f1acd131bb8e660f4bfe2799f/setproctitle-1.3.6-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:50706b9c0eda55f7de18695bfeead5f28b58aa42fd5219b3b1692d554ecbc9ec", size = 11963, upload-time = "2025-04-29T13:32:59.17Z" }, - { url = "https://files.pythonhosted.org/packages/5b/47/f103c40e133154783c91a10ab08ac9fc410ed835aa85bcf7107cb882f505/setproctitle-1.3.6-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:af188f3305f0a65c3217c30c6d4c06891e79144076a91e8b454f14256acc7279", size = 31718, upload-time = "2025-04-29T13:33:00.36Z" }, - { url = "https://files.pythonhosted.org/packages/1f/13/7325dd1c008dd6c0ebd370ddb7505977054a87e406f142318e395031a792/setproctitle-1.3.6-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:cce0ed8b3f64c71c140f0ec244e5fdf8ecf78ddf8d2e591d4a8b6aa1c1214235", size = 33027, upload-time = "2025-04-29T13:33:01.499Z" }, - { url = "https://files.pythonhosted.org/packages/0c/0a/6075bfea05a71379d77af98a9ac61163e8b6e5ef1ae58cd2b05871b2079c/setproctitle-1.3.6-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:70100e2087fe05359f249a0b5f393127b3a1819bf34dec3a3e0d4941138650c9", size = 30223, upload-time = "2025-04-29T13:33:03.259Z" }, - { url = "https://files.pythonhosted.org/packages/cc/41/fbf57ec52f4f0776193bd94334a841f0bc9d17e745f89c7790f336420c65/setproctitle-1.3.6-cp311-cp311-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1065ed36bd03a3fd4186d6c6de5f19846650b015789f72e2dea2d77be99bdca1", size = 31204, upload-time = "2025-04-29T13:33:04.455Z" }, - { url = "https://files.pythonhosted.org/packages/97/b5/f799fb7a00de29fb0ac1dfd015528dea425b9e31a8f1068a0b3df52d317f/setproctitle-1.3.6-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:4adf6a0013fe4e0844e3ba7583ec203ca518b9394c6cc0d3354df2bf31d1c034", size = 31181, upload-time = "2025-04-29T13:33:05.697Z" }, - { url = "https://files.pythonhosted.org/packages/b5/b7/81f101b612014ec61723436022c31146178813d6ca6b947f7b9c84e9daf4/setproctitle-1.3.6-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:eb7452849f6615871eabed6560ffedfe56bc8af31a823b6be4ce1e6ff0ab72c5", size = 30101, upload-time = "2025-04-29T13:33:07.223Z" }, - { url = "https://files.pythonhosted.org/packages/67/23/681232eed7640eab96719daa8647cc99b639e3daff5c287bd270ef179a73/setproctitle-1.3.6-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:a094b7ce455ca341b59a0f6ce6be2e11411ba6e2860b9aa3dbb37468f23338f4", size = 32438, upload-time = "2025-04-29T13:33:08.538Z" }, - { url = "https://files.pythonhosted.org/packages/19/f8/4d075a7bdc3609ac71535b849775812455e4c40aedfbf0778a6f123b1774/setproctitle-1.3.6-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:ad1c2c2baaba62823a7f348f469a967ece0062140ca39e7a48e4bbb1f20d54c4", size = 30625, upload-time = "2025-04-29T13:33:09.707Z" }, - { url = "https://files.pythonhosted.org/packages/5f/73/a2a8259ebee166aee1ca53eead75de0e190b3ddca4f716e5c7470ebb7ef6/setproctitle-1.3.6-cp311-cp311-win32.whl", hash = "sha256:8050c01331135f77ec99d99307bfbc6519ea24d2f92964b06f3222a804a3ff1f", size = 11488, upload-time = "2025-04-29T13:33:10.953Z" }, - { url = "https://files.pythonhosted.org/packages/c9/15/52cf5e1ff0727d53704cfdde2858eaf237ce523b0b04db65faa84ff83e13/setproctitle-1.3.6-cp311-cp311-win_amd64.whl", hash = "sha256:9b73cf0fe28009a04a35bb2522e4c5b5176cc148919431dcb73fdbdfaab15781", size = 12201, upload-time = "2025-04-29T13:33:12.389Z" }, - { url = "https://files.pythonhosted.org/packages/8f/fb/99456fd94d4207c5f6c40746a048a33a52b4239cd7d9c8d4889e2210ec82/setproctitle-1.3.6-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:af44bb7a1af163806bbb679eb8432fa7b4fb6d83a5d403b541b675dcd3798638", size = 17399, upload-time = "2025-04-29T13:33:13.406Z" }, - { url = "https://files.pythonhosted.org/packages/d5/48/9699191fe6062827683c43bfa9caac33a2c89f8781dd8c7253fa3dba85fd/setproctitle-1.3.6-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:3cca16fd055316a48f0debfcbfb6af7cea715429fc31515ab3fcac05abd527d8", size = 11966, upload-time = "2025-04-29T13:33:14.976Z" }, - { url = "https://files.pythonhosted.org/packages/33/03/b085d192b9ecb9c7ce6ad6ef30ecf4110b7f39430b58a56245569827fcf4/setproctitle-1.3.6-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ea002088d5554fd75e619742cefc78b84a212ba21632e59931b3501f0cfc8f67", size = 32017, upload-time = "2025-04-29T13:33:16.163Z" }, - { url = "https://files.pythonhosted.org/packages/ae/68/c53162e645816f97212002111420d1b2f75bf6d02632e37e961dc2cd6d8b/setproctitle-1.3.6-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:bb465dd5825356c1191a038a86ee1b8166e3562d6e8add95eec04ab484cfb8a2", size = 33419, upload-time = "2025-04-29T13:33:18.239Z" }, - { url = "https://files.pythonhosted.org/packages/ac/0d/119a45d15a816a6cf5ccc61b19729f82620095b27a47e0a6838216a95fae/setproctitle-1.3.6-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:d2c8e20487b3b73c1fa72c56f5c89430617296cd380373e7af3a538a82d4cd6d", size = 30711, upload-time = "2025-04-29T13:33:19.571Z" }, - { url = "https://files.pythonhosted.org/packages/e3/fb/5e9b5068df9e9f31a722a775a5e8322a29a638eaaa3eac5ea7f0b35e6314/setproctitle-1.3.6-cp312-cp312-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a0d6252098e98129a1decb59b46920d4eca17b0395f3d71b0d327d086fefe77d", size = 31742, upload-time = "2025-04-29T13:33:21.172Z" }, - { url = "https://files.pythonhosted.org/packages/35/88/54de1e73e8fce87d587889c7eedb48fc4ee2bbe4e4ca6331690d03024f86/setproctitle-1.3.6-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:cf355fbf0d4275d86f9f57be705d8e5eaa7f8ddb12b24ced2ea6cbd68fdb14dc", size = 31925, upload-time = "2025-04-29T13:33:22.427Z" }, - { url = "https://files.pythonhosted.org/packages/f3/01/65948d7badd66e63e3db247b923143da142790fa293830fdecf832712c2d/setproctitle-1.3.6-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:e288f8a162d663916060beb5e8165a8551312b08efee9cf68302687471a6545d", size = 30981, upload-time = "2025-04-29T13:33:23.739Z" }, - { url = "https://files.pythonhosted.org/packages/22/20/c495e61786f1d38d5dc340b9d9077fee9be3dfc7e89f515afe12e1526dbc/setproctitle-1.3.6-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:b2e54f4a2dc6edf0f5ea5b1d0a608d2af3dcb5aa8c8eeab9c8841b23e1b054fe", size = 33209, upload-time = "2025-04-29T13:33:24.915Z" }, - { url = "https://files.pythonhosted.org/packages/98/3f/a457b8550fbd34d5b482fe20b8376b529e76bf1fbf9a474a6d9a641ab4ad/setproctitle-1.3.6-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:b6f4abde9a2946f57e8daaf1160b2351bcf64274ef539e6675c1d945dbd75e2a", size = 31587, upload-time = "2025-04-29T13:33:26.123Z" }, - { url = "https://files.pythonhosted.org/packages/44/fe/743517340e5a635e3f1c4310baea20c16c66202f96a6f4cead222ffd6d84/setproctitle-1.3.6-cp312-cp312-win32.whl", hash = "sha256:db608db98ccc21248370d30044a60843b3f0f3d34781ceeea67067c508cd5a28", size = 11487, upload-time = "2025-04-29T13:33:27.403Z" }, - { url = "https://files.pythonhosted.org/packages/60/9a/d88f1c1f0f4efff1bd29d9233583ee341114dda7d9613941453984849674/setproctitle-1.3.6-cp312-cp312-win_amd64.whl", hash = "sha256:082413db8a96b1f021088e8ec23f0a61fec352e649aba20881895815388b66d3", size = 12208, upload-time = "2025-04-29T13:33:28.852Z" }, + { url = "https://files.pythonhosted.org/packages/fb/f0/2dc88e842077719d7384d86cc47403e5102810492b33680e7dadcee64cd8/setproctitle-1.3.7-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:2dc99aec591ab6126e636b11035a70991bc1ab7a261da428491a40b84376654e", size = 18049, upload-time = "2025-09-05T12:49:36.241Z" }, + { url = "https://files.pythonhosted.org/packages/f0/b4/50940504466689cda65680c9e9a1e518e5750c10490639fa687489ac7013/setproctitle-1.3.7-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:cdd8aa571b7aa39840fdbea620e308a19691ff595c3a10231e9ee830339dd798", size = 13079, upload-time = "2025-09-05T12:49:38.088Z" }, + { url = "https://files.pythonhosted.org/packages/d0/99/71630546b9395b095f4082be41165d1078204d1696c2d9baade3de3202d0/setproctitle-1.3.7-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:2906b6c7959cdb75f46159bf0acd8cc9906cf1361c9e1ded0d065fe8f9039629", size = 32932, upload-time = "2025-09-05T12:49:39.271Z" }, + { url = "https://files.pythonhosted.org/packages/50/22/cee06af4ffcfb0e8aba047bd44f5262e644199ae7527ae2c1f672b86495c/setproctitle-1.3.7-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6915964a6dda07920a1159321dcd6d94fc7fc526f815ca08a8063aeca3c204f1", size = 33736, upload-time = "2025-09-05T12:49:40.565Z" }, + { url = "https://files.pythonhosted.org/packages/5c/00/a5949a8bb06ef5e7df214fc393bb2fb6aedf0479b17214e57750dfdd0f24/setproctitle-1.3.7-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:cff72899861c765bd4021d1ff1c68d60edc129711a2fdba77f9cb69ef726a8b6", size = 35605, upload-time = "2025-09-05T12:49:42.362Z" }, + { url = "https://files.pythonhosted.org/packages/b0/3a/50caca532a9343828e3bf5778c7a84d6c737a249b1796d50dd680290594d/setproctitle-1.3.7-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:b7cb05bd446687ff816a3aaaf831047fc4c364feff7ada94a66024f1367b448c", size = 33143, upload-time = "2025-09-05T12:49:43.515Z" }, + { url = "https://files.pythonhosted.org/packages/ca/14/b843a251296ce55e2e17c017d6b9f11ce0d3d070e9265de4ecad948b913d/setproctitle-1.3.7-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:3a57b9a00de8cae7e2a1f7b9f0c2ac7b69372159e16a7708aa2f38f9e5cc987a", size = 34434, upload-time = "2025-09-05T12:49:45.31Z" }, + { url = "https://files.pythonhosted.org/packages/c8/b7/06145c238c0a6d2c4bc881f8be230bb9f36d2bf51aff7bddcb796d5eed67/setproctitle-1.3.7-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:d8828b356114f6b308b04afe398ed93803d7fca4a955dd3abe84430e28d33739", size = 32795, upload-time = "2025-09-05T12:49:46.419Z" }, + { url = "https://files.pythonhosted.org/packages/ef/dc/ef76a81fac9bf27b84ed23df19c1f67391a753eed6e3c2254ebcb5133f56/setproctitle-1.3.7-cp312-cp312-win32.whl", hash = "sha256:b0304f905efc845829ac2bc791ddebb976db2885f6171f4a3de678d7ee3f7c9f", size = 12552, upload-time = "2025-09-05T12:49:47.635Z" }, + { url = "https://files.pythonhosted.org/packages/e2/5b/a9fe517912cd6e28cf43a212b80cb679ff179a91b623138a99796d7d18a0/setproctitle-1.3.7-cp312-cp312-win_amd64.whl", hash = "sha256:9888ceb4faea3116cf02a920ff00bfbc8cc899743e4b4ac914b03625bdc3c300", size = 13247, upload-time = "2025-09-05T12:49:49.16Z" }, ] [[package]] name = "setuptools" -version = "80.9.0" +version = "82.0.1" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/18/5d/3bf57dcd21979b887f014ea83c24ae194cfcd12b9e0fda66b957c69d1fca/setuptools-80.9.0.tar.gz", hash = "sha256:f36b47402ecde768dbfafc46e8e4207b4360c654f1f3bb84475f0a28628fb19c", size = 1319958, upload-time = "2025-05-27T00:56:51.443Z" } +sdist = { url = "https://files.pythonhosted.org/packages/4f/db/cfac1baf10650ab4d1c111714410d2fbb77ac5a616db26775db562c8fab2/setuptools-82.0.1.tar.gz", hash = "sha256:7d872682c5d01cfde07da7bccc7b65469d3dca203318515ada1de5eda35efbf9", size = 1152316, upload-time = "2026-03-09T12:47:17.221Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/a3/dc/17031897dae0efacfea57dfd3a82fdd2a2aeb58e0ff71b77b87e44edc772/setuptools-80.9.0-py3-none-any.whl", hash = "sha256:062d34222ad13e0cc312a4c02d73f059e86a4acbfbdea8f8f76b28c99f306922", size = 1201486, upload-time = "2025-05-27T00:56:49.664Z" }, -] - -[[package]] -name = "shapely" -version = "2.1.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "numpy" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/ca/3c/2da625233f4e605155926566c0e7ea8dda361877f48e8b1655e53456f252/shapely-2.1.1.tar.gz", hash = "sha256:500621967f2ffe9642454808009044c21e5b35db89ce69f8a2042c2ffd0e2772", size = 315422, upload-time = "2025-05-19T11:04:41.265Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/19/97/2df985b1e03f90c503796ad5ecd3d9ed305123b64d4ccb54616b30295b29/shapely-2.1.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:587a1aa72bc858fab9b8c20427b5f6027b7cbc92743b8e2c73b9de55aa71c7a7", size = 1819368, upload-time = "2025-05-19T11:03:55.937Z" }, - { url = "https://files.pythonhosted.org/packages/56/17/504518860370f0a28908b18864f43d72f03581e2b6680540ca668f07aa42/shapely-2.1.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:9fa5c53b0791a4b998f9ad84aad456c988600757a96b0a05e14bba10cebaaaea", size = 1625362, upload-time = "2025-05-19T11:03:57.06Z" }, - { url = "https://files.pythonhosted.org/packages/36/a1/9677337d729b79fce1ef3296aac6b8ef4743419086f669e8a8070eff8f40/shapely-2.1.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:aabecd038841ab5310d23495253f01c2a82a3aedae5ab9ca489be214aa458aa7", size = 2999005, upload-time = "2025-05-19T11:03:58.692Z" }, - { url = "https://files.pythonhosted.org/packages/a2/17/e09357274699c6e012bbb5a8ea14765a4d5860bb658df1931c9f90d53bd3/shapely-2.1.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:586f6aee1edec04e16227517a866df3e9a2e43c1f635efc32978bb3dc9c63753", size = 3108489, upload-time = "2025-05-19T11:04:00.059Z" }, - { url = "https://files.pythonhosted.org/packages/17/5d/93a6c37c4b4e9955ad40834f42b17260ca74ecf36df2e81bb14d12221b90/shapely-2.1.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:b9878b9e37ad26c72aada8de0c9cfe418d9e2ff36992a1693b7f65a075b28647", size = 3945727, upload-time = "2025-05-19T11:04:01.786Z" }, - { url = "https://files.pythonhosted.org/packages/a3/1a/ad696648f16fd82dd6bfcca0b3b8fbafa7aacc13431c7fc4c9b49e481681/shapely-2.1.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:d9a531c48f289ba355e37b134e98e28c557ff13965d4653a5228d0f42a09aed0", size = 4109311, upload-time = "2025-05-19T11:04:03.134Z" }, - { url = "https://files.pythonhosted.org/packages/d4/38/150dd245beab179ec0d4472bf6799bf18f21b1efbef59ac87de3377dbf1c/shapely-2.1.1-cp311-cp311-win32.whl", hash = "sha256:4866de2673a971820c75c0167b1f1cd8fb76f2d641101c23d3ca021ad0449bab", size = 1522982, upload-time = "2025-05-19T11:04:05.217Z" }, - { url = "https://files.pythonhosted.org/packages/93/5b/842022c00fbb051083c1c85430f3bb55565b7fd2d775f4f398c0ba8052ce/shapely-2.1.1-cp311-cp311-win_amd64.whl", hash = "sha256:20a9d79958b3d6c70d8a886b250047ea32ff40489d7abb47d01498c704557a93", size = 1703872, upload-time = "2025-05-19T11:04:06.791Z" }, - { url = "https://files.pythonhosted.org/packages/fb/64/9544dc07dfe80a2d489060791300827c941c451e2910f7364b19607ea352/shapely-2.1.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:2827365b58bf98efb60affc94a8e01c56dd1995a80aabe4b701465d86dcbba43", size = 1833021, upload-time = "2025-05-19T11:04:08.022Z" }, - { url = "https://files.pythonhosted.org/packages/07/aa/fb5f545e72e89b6a0f04a0effda144f5be956c9c312c7d4e00dfddbddbcf/shapely-2.1.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:a9c551f7fa7f1e917af2347fe983f21f212863f1d04f08eece01e9c275903fad", size = 1643018, upload-time = "2025-05-19T11:04:09.343Z" }, - { url = "https://files.pythonhosted.org/packages/03/46/61e03edba81de729f09d880ce7ae5c1af873a0814206bbfb4402ab5c3388/shapely-2.1.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:78dec4d4fbe7b1db8dc36de3031767e7ece5911fb7782bc9e95c5cdec58fb1e9", size = 2986417, upload-time = "2025-05-19T11:04:10.56Z" }, - { url = "https://files.pythonhosted.org/packages/1f/1e/83ec268ab8254a446b4178b45616ab5822d7b9d2b7eb6e27cf0b82f45601/shapely-2.1.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:872d3c0a7b8b37da0e23d80496ec5973c4692920b90de9f502b5beb994bbaaef", size = 3098224, upload-time = "2025-05-19T11:04:11.903Z" }, - { url = "https://files.pythonhosted.org/packages/f1/44/0c21e7717c243e067c9ef8fa9126de24239f8345a5bba9280f7bb9935959/shapely-2.1.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:2e2b9125ebfbc28ecf5353511de62f75a8515ae9470521c9a693e4bb9fbe0cf1", size = 3925982, upload-time = "2025-05-19T11:04:13.224Z" }, - { url = "https://files.pythonhosted.org/packages/15/50/d3b4e15fefc103a0eb13d83bad5f65cd6e07a5d8b2ae920e767932a247d1/shapely-2.1.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:4b96cea171b3d7f6786976a0520f178c42792897653ecca0c5422fb1e6946e6d", size = 4089122, upload-time = "2025-05-19T11:04:14.477Z" }, - { url = "https://files.pythonhosted.org/packages/bd/05/9a68f27fc6110baeedeeebc14fd86e73fa38738c5b741302408fb6355577/shapely-2.1.1-cp312-cp312-win32.whl", hash = "sha256:39dca52201e02996df02e447f729da97cfb6ff41a03cb50f5547f19d02905af8", size = 1522437, upload-time = "2025-05-19T11:04:16.203Z" }, - { url = "https://files.pythonhosted.org/packages/bc/e9/a4560e12b9338842a1f82c9016d2543eaa084fce30a1ca11991143086b57/shapely-2.1.1-cp312-cp312-win_amd64.whl", hash = "sha256:13d643256f81d55a50013eff6321142781cf777eb6a9e207c2c9e6315ba6044a", size = 1703479, upload-time = "2025-05-19T11:04:18.497Z" }, -] - -[[package]] -name = "siphash24" -version = "1.7" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/0e/be/f0a0ffbb00c51c5633b41459b5ce9b017c025a9256b4403e648c18e70850/siphash24-1.7.tar.gz", hash = "sha256:6e90fee5f199ea25b4e7303646b31872a437174fe885a93dbd4cf7784eb48164", size = 19801, upload-time = "2024-10-15T13:41:51.924Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/4e/67/4ffd23a848739966e1b314ef99f6410035bccee00be14261313787b8f506/siphash24-1.7-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:de75488e93f1cd12c8d5004efd1ebd958c0265205a9d73e8dd8b071900838841", size = 80493, upload-time = "2024-10-15T13:41:14.727Z" }, - { url = "https://files.pythonhosted.org/packages/56/bd/ec198a8c7aef65e967ae84f633bd9950d784c9e527d738c9a3e4bccc34a5/siphash24-1.7-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:ffca9908450f9f346e97a223185fcd16217d67d84c6f246f3080c4224f41a514", size = 75350, upload-time = "2024-10-15T13:41:16.262Z" }, - { url = "https://files.pythonhosted.org/packages/50/5a/77838c916bd15addfc2e51286db4c442cb12e25eb4f8d296c394c2280240/siphash24-1.7-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b8ff44ce166452993fea267ea1b2fd089d8e7f103b13d360da441f12b0df121d", size = 100567, upload-time = "2024-10-15T13:41:17.435Z" }, - { url = "https://files.pythonhosted.org/packages/f0/aa/736a0a2efae9a6f69ac1ee4d28c2274fcad2150349fac752d6c525c4e06e/siphash24-1.7-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4062548dcb1eef13bbe0356d6f8675bfe4571ef38d7103445daa82ba167240d1", size = 105630, upload-time = "2024-10-15T13:41:18.578Z" }, - { url = "https://files.pythonhosted.org/packages/79/52/1afbd70142d3db093d49197e3abe15ca2f1a14678299327ba776944b4771/siphash24-1.7-cp311-cp311-win32.whl", hash = "sha256:7b4ea29376b688fbcc3d25707c15a9dfe7b4ebbc4322878d75bb77e199210a39", size = 67648, upload-time = "2024-10-15T13:41:19.606Z" }, - { url = "https://files.pythonhosted.org/packages/b5/1d/bedcd04c2d1d199c9f6b3e61a6caae0e17257696c9f49594e49856b17a99/siphash24-1.7-cp311-cp311-win_amd64.whl", hash = "sha256:ec06104e6ef1e512ee30f1b8aeae2b83c0f55f12a94042f0df5a87d43a1f4c52", size = 80046, upload-time = "2024-10-15T13:41:20.654Z" }, - { url = "https://files.pythonhosted.org/packages/3e/62/93e552af9535a416f684327f870143ee42fc9e816091672467cdfd62cce6/siphash24-1.7-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:76a64ff0cdd192e4d0a391956d9b121c56ed56e773c5ab7eb7c3e035fd16e8cb", size = 82084, upload-time = "2024-10-15T13:41:21.776Z" }, - { url = "https://files.pythonhosted.org/packages/59/3e/b0791ab53aa9ac191b71a021eab2e75baa7c27d7feb7ec148d7961d148ba/siphash24-1.7-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:49ca649bc7437d614f758891deade3b187832792a853269219e77f10509f82fe", size = 76233, upload-time = "2024-10-15T13:41:22.787Z" }, - { url = "https://files.pythonhosted.org/packages/29/4c/4c1b809bf302e9b60f3ec09ba115b2a4ac1ff6755735ee8884924fcdb45e/siphash24-1.7-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:bc37dd0aed23f76bd257fbd2953fd5d954b329d7463c6ff57263a2699c52dde6", size = 98188, upload-time = "2024-10-15T13:41:24.327Z" }, - { url = "https://files.pythonhosted.org/packages/96/bf/e6b49f8ff88130bd224f291ea77d30fdde4df5f6572c519aca5d8fc8a27c/siphash24-1.7-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:eea490a200891905856b6ad0f9c56d4ec787876220bcb34c49441b2566b97887", size = 102946, upload-time = "2024-10-15T13:41:25.633Z" }, - { url = "https://files.pythonhosted.org/packages/3d/75/45c831626013950fb2ea715c218c3397e5cf2328a67208bf5d8ff69aa9e6/siphash24-1.7-cp312-cp312-win32.whl", hash = "sha256:69eb8c2c112a738875bb283cd53ef5e86874bc5aed17f3020b38e9174208fb79", size = 68323, upload-time = "2024-10-15T13:41:27.349Z" }, - { url = "https://files.pythonhosted.org/packages/e0/d3/39190c40a68defd19b99c1082dd7455543a52283803bfa111b0e45fae968/siphash24-1.7-cp312-cp312-win_amd64.whl", hash = "sha256:7459569ea4669b6feeaf7d299fc5157cc5c69ca1231dc0decb7a7da2397c782e", size = 81000, upload-time = "2024-10-15T13:41:28.364Z" }, + { url = "https://files.pythonhosted.org/packages/9d/76/f789f7a86709c6b087c5a2f52f911838cad707cc613162401badc665acfe/setuptools-82.0.1-py3-none-any.whl", hash = "sha256:a59e362652f08dcd477c78bb6e7bd9d80a7995bc73ce773050228a348ce2e5bb", size = 1006223, upload-time = "2026-03-09T12:47:15.026Z" }, ] [[package]] @@ -4838,15 +1238,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" }, ] -[[package]] -name = "smbus2" -version = "0.5.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/10/c9/6d85aa809e107adf85303010a59b340be109c8f815cbedc5c08c73bcffef/smbus2-0.5.0.tar.gz", hash = "sha256:4a5946fd82277870c2878befdb1a29bb28d15cda14ea4d8d2d54cf3d4bdcb035", size = 16950, upload-time = "2024-10-19T09:20:56.746Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/85/9f/2235ba9001e3c29fc342eeb222104420bcb7bac51555f0c034376a744075/smbus2-0.5.0-py2.py3-none-any.whl", hash = "sha256:1a15c3b9fa69357beb038cc0b5d37939702f8bfde1ddc89ca9f17d8461dbe949", size = 11527, upload-time = "2024-10-19T09:20:55.202Z" }, -] - [[package]] name = "sortedcontainers" version = "2.4.0" @@ -4858,24 +1249,25 @@ wheels = [ [[package]] name = "sounddevice" -version = "0.5.2" +version = "0.5.5" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "cffi" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/91/a6/91e9f08ed37c7c9f56b5227c6aea7f2ae63ba2d59520eefb24e82cbdd589/sounddevice-0.5.2.tar.gz", hash = "sha256:c634d51bd4e922d6f0fa5e1a975cc897c947f61d31da9f79ba7ea34dff448b49", size = 53150, upload-time = "2025-05-16T18:12:27.339Z" } +sdist = { url = "https://files.pythonhosted.org/packages/2a/f9/2592608737553638fca98e21e54bfec40bf577bb98a61b2770c912aab25e/sounddevice-0.5.5.tar.gz", hash = "sha256:22487b65198cb5bf2208755105b524f78ad173e5ab6b445bdab1c989f6698df3", size = 143191, upload-time = "2026-01-23T18:36:43.529Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/75/2d/582738fc01352a5bc20acac9221e58538365cecb3bb264838f66419df219/sounddevice-0.5.2-py3-none-any.whl", hash = "sha256:82375859fac2e73295a4ab3fc60bd4782743157adc339561c1f1142af472f505", size = 32450, upload-time = "2025-05-16T18:12:21.919Z" }, - { url = "https://files.pythonhosted.org/packages/3f/6f/e3dd751face4fcb5be25e8abba22f25d8e6457ebd7e9ed79068b768dc0e5/sounddevice-0.5.2-py3-none-macosx_10_6_x86_64.macosx_10_6_universal2.whl", hash = "sha256:943f27e66037d41435bdd0293454072cdf657b594c9cde63cd01ee3daaac7ab3", size = 108088, upload-time = "2025-05-16T18:12:23.146Z" }, - { url = "https://files.pythonhosted.org/packages/45/0b/bfad79af0b380aa7c0bfe73e4b03e0af45354a48ad62549489bd7696c5b0/sounddevice-0.5.2-py3-none-win32.whl", hash = "sha256:3a113ce614a2c557f14737cb20123ae6298c91fc9301eb014ada0cba6d248c5f", size = 312665, upload-time = "2025-05-16T18:12:24.726Z" }, - { url = "https://files.pythonhosted.org/packages/e1/3e/61d88e6b0a7383127cdc779195cb9d83ebcf11d39bc961de5777e457075e/sounddevice-0.5.2-py3-none-win_amd64.whl", hash = "sha256:e18944b767d2dac3771a7771bdd7ff7d3acd7d334e72c4bedab17d1aed5dbc22", size = 363808, upload-time = "2025-05-16T18:12:26Z" }, + { url = "https://files.pythonhosted.org/packages/1e/0a/478e441fd049002cf308520c0d62dd8333e7c6cc8d997f0dda07b9fbcc46/sounddevice-0.5.5-py3-none-any.whl", hash = "sha256:30ff99f6c107f49d25ad16a45cacd8d91c25a1bcdd3e81a206b921a3a6405b1f", size = 32807, upload-time = "2026-01-23T18:36:35.649Z" }, + { url = "https://files.pythonhosted.org/packages/56/f9/c037c35f6d0b6bc3bc7bfb314f1d6f1f9a341328ef47cd63fc4f850a7b27/sounddevice-0.5.5-py3-none-macosx_10_6_x86_64.macosx_10_6_universal2.whl", hash = "sha256:05eb9fd6c54c38d67741441c19164c0dae8ce80453af2d8c4ad2e7823d15b722", size = 108557, upload-time = "2026-01-23T18:36:37.41Z" }, + { url = "https://files.pythonhosted.org/packages/88/a1/d19dd9889cd4bce2e233c4fac007cd8daaf5b9fe6e6a5d432cf17be0b807/sounddevice-0.5.5-py3-none-win32.whl", hash = "sha256:1234cc9b4c9df97b6cbe748146ae0ec64dd7d6e44739e8e42eaa5b595313a103", size = 317765, upload-time = "2026-01-23T18:36:39.047Z" }, + { url = "https://files.pythonhosted.org/packages/c3/0e/002ed7c4c1c2ab69031f78989d3b789fee3a7fba9e586eb2b81688bf4961/sounddevice-0.5.5-py3-none-win_amd64.whl", hash = "sha256:cfc6b2c49fb7f555591c78cb8ecf48d6a637fd5b6e1db5fec6ed9365d64b3519", size = 365324, upload-time = "2026-01-23T18:36:40.496Z" }, + { url = "https://files.pythonhosted.org/packages/4e/39/a61d4b83a7746b70d23d9173be688c0c6bfc7173772344b7442c2c155497/sounddevice-0.5.5-py3-none-win_arm64.whl", hash = "sha256:3861901ddd8230d2e0e8ae62ac320cdd4c688d81df89da036dcb812f757bb3e6", size = 317115, upload-time = "2026-01-23T18:36:42.235Z" }, ] [[package]] name = "spidev" -version = "3.7" +version = "3.8" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/b5/99/dd50af8200e224ce9412ad01cdbeeb5b39b2d61acd72138f2b92c4a6d619/spidev-3.7.tar.gz", hash = "sha256:ce628a5ff489f45132679879bff5f455a66abf9751af01843850155b06ae92f0", size = 11616, upload-time = "2025-05-06T14:23:30.783Z" } +sdist = { url = "https://files.pythonhosted.org/packages/67/87/039b6eeea781598015b538691bc174cc0bf77df9d4d2d3b8bf9245c0de8c/spidev-3.8.tar.gz", hash = "sha256:2bc02fb8c6312d519ebf1f4331067427c0921d3f77b8bcaf05189a2e8b8382c0", size = 13893, upload-time = "2025-09-15T18:56:20.672Z" } [[package]] name = "sympy" @@ -4890,255 +1282,206 @@ wheels = [ ] [[package]] -name = "tabulate" -version = "0.9.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/ec/fe/802052aecb21e3797b8f7902564ab6ea0d60ff8ca23952079064155d1ae1/tabulate-0.9.0.tar.gz", hash = "sha256:0095b12bf5966de529c0feb1fa08671671b3368eec77d7ef7ab114be2c068b3c", size = 81090, upload-time = "2022-10-06T17:21:48.54Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/40/44/4a5f08c96eb108af5cb50b41f76142f0afa346dfa99d5296fe7202a11854/tabulate-0.9.0-py3-none-any.whl", hash = "sha256:024ca478df22e9340661486f85298cff5f6dcdba14f3813e8830015b9ed1948f", size = 35252, upload-time = "2022-10-06T17:21:44.262Z" }, +name = "teleoprtc" +version = "1.0.1" +source = { editable = "teleoprtc_repo" } +dependencies = [ + { name = "libdatachannel-py" }, ] +[package.metadata] +requires-dist = [ + { name = "libdatachannel-py", specifier = ">=2026.1.0.dev2" }, + { name = "parameterized", marker = "extra == 'dev'", specifier = ">=0.8" }, + { name = "pre-commit", marker = "extra == 'dev'" }, + { name = "pytest", marker = "extra == 'dev'" }, + { name = "pytest-asyncio", marker = "extra == 'dev'" }, + { name = "pytest-xdist", marker = "extra == 'dev'" }, +] +provides-extras = ["dev"] + +[[package]] +name = "tinygrad" +version = "0.12.0" +source = { editable = "tinygrad_repo" } + +[package.metadata] +requires-dist = [ + { name = "black", marker = "extra == 'docs'" }, + { name = "blobfile", marker = "extra == 'testing'" }, + { name = "boto3", marker = "extra == 'testing'" }, + { name = "bottle", marker = "extra == 'testing'" }, + { name = "capstone", marker = "extra == 'testing-unit'" }, + { name = "gguf", marker = "extra == 'testing-unit'", specifier = ">=0.18" }, + { name = "hypothesis", marker = "extra == 'testing-minimal'", specifier = ">=6.148.9" }, + { name = "influxdb3-python", marker = "extra == 'testing'" }, + { name = "librosa", marker = "extra == 'testing'" }, + { name = "markdown-callouts", marker = "extra == 'docs'" }, + { name = "markdown-exec", extras = ["ansi"], marker = "extra == 'docs'" }, + { name = "mkdocs", marker = "extra == 'docs'" }, + { name = "mkdocs-material", marker = "extra == 'docs'" }, + { name = "mkdocstrings", extras = ["python"], marker = "extra == 'docs'" }, + { name = "mypy", marker = "extra == 'linting'", specifier = "==1.19.1" }, + { name = "networkx", marker = "extra == 'testing'" }, + { name = "nibabel", marker = "extra == 'testing'" }, + { name = "numba", marker = "extra == 'testing'", specifier = ">=0.55" }, + { name = "numpy", marker = "extra == 'docs'" }, + { name = "numpy", marker = "extra == 'linting'" }, + { name = "numpy", marker = "extra == 'testing-minimal'" }, + { name = "onnx", marker = "extra == 'testing'", specifier = "==1.19.0" }, + { name = "onnx2torch", marker = "extra == 'testing'" }, + { name = "onnxruntime", marker = "extra == 'testing'" }, + { name = "openai", marker = "extra == 'testing-unit'" }, + { name = "opencv-python", marker = "extra == 'testing'" }, + { name = "pandas", marker = "extra == 'testing'" }, + { name = "pillow", marker = "extra == 'testing'" }, + { name = "pre-commit", marker = "extra == 'linting'" }, + { name = "pycocotools", marker = "extra == 'testing'" }, + { name = "pylint", marker = "extra == 'linting'" }, + { name = "pytest", marker = "extra == 'testing-minimal'" }, + { name = "pytest-split", marker = "extra == 'testing-minimal'" }, + { name = "pytest-timeout", marker = "extra == 'testing-minimal'" }, + { name = "pytest-xdist", marker = "extra == 'testing-minimal'" }, + { name = "ruff", marker = "extra == 'linting'", specifier = "==0.14.10" }, + { name = "safetensors", marker = "extra == 'testing-unit'" }, + { name = "sentencepiece", marker = "extra == 'testing'" }, + { name = "tabulate", marker = "extra == 'testing-unit'" }, + { name = "tiktoken", marker = "extra == 'testing'" }, + { name = "tinygrad", extras = ["testing-minimal"], marker = "extra == 'testing-unit'" }, + { name = "tinygrad", extras = ["testing-unit"], marker = "extra == 'testing'" }, + { name = "torch", marker = "extra == 'testing-minimal'", specifier = "==2.9.1" }, + { name = "tqdm", marker = "extra == 'testing-unit'" }, + { name = "transformers", marker = "extra == 'testing'" }, + { name = "typeguard", marker = "extra == 'linting'" }, + { name = "typing-extensions", marker = "extra == 'linting'" }, + { name = "z3-solver", marker = "extra == 'testing-minimal'", specifier = "<4.15.4" }, +] +provides-extras = ["linting", "testing-minimal", "testing-unit", "testing", "docs"] + [[package]] name = "tomli" -version = "2.2.1" +version = "2.4.1" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/18/87/302344fed471e44a87289cf4967697d07e532f2421fdaf868a303cbae4ff/tomli-2.2.1.tar.gz", hash = "sha256:cd45e1dc79c835ce60f7404ec8119f2eb06d38b1deba146f07ced3bbc44505ff", size = 17175, upload-time = "2024-11-27T22:38:36.873Z" } +sdist = { url = "https://files.pythonhosted.org/packages/22/de/48c59722572767841493b26183a0d1cc411d54fd759c5607c4590b6563a6/tomli-2.4.1.tar.gz", hash = "sha256:7c7e1a961a0b2f2472c1ac5b69affa0ae1132c39adcb67aba98568702b9cc23f", size = 17543, upload-time = "2026-03-25T20:22:03.828Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/43/ca/75707e6efa2b37c77dadb324ae7d9571cb424e61ea73fad7c56c2d14527f/tomli-2.2.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:678e4fa69e4575eb77d103de3df8a895e1591b48e740211bd1067378c69e8249", size = 131077, upload-time = "2024-11-27T22:37:54.956Z" }, - { url = "https://files.pythonhosted.org/packages/c7/16/51ae563a8615d472fdbffc43a3f3d46588c264ac4f024f63f01283becfbb/tomli-2.2.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:023aa114dd824ade0100497eb2318602af309e5a55595f76b626d6d9f3b7b0a6", size = 123429, upload-time = "2024-11-27T22:37:56.698Z" }, - { url = "https://files.pythonhosted.org/packages/f1/dd/4f6cd1e7b160041db83c694abc78e100473c15d54620083dbd5aae7b990e/tomli-2.2.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ece47d672db52ac607a3d9599a9d48dcb2f2f735c6c2d1f34130085bb12b112a", size = 226067, upload-time = "2024-11-27T22:37:57.63Z" }, - { url = "https://files.pythonhosted.org/packages/a9/6b/c54ede5dc70d648cc6361eaf429304b02f2871a345bbdd51e993d6cdf550/tomli-2.2.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6972ca9c9cc9f0acaa56a8ca1ff51e7af152a9f87fb64623e31d5c83700080ee", size = 236030, upload-time = "2024-11-27T22:37:59.344Z" }, - { url = "https://files.pythonhosted.org/packages/1f/47/999514fa49cfaf7a92c805a86c3c43f4215621855d151b61c602abb38091/tomli-2.2.1-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c954d2250168d28797dd4e3ac5cf812a406cd5a92674ee4c8f123c889786aa8e", size = 240898, upload-time = "2024-11-27T22:38:00.429Z" }, - { url = "https://files.pythonhosted.org/packages/73/41/0a01279a7ae09ee1573b423318e7934674ce06eb33f50936655071d81a24/tomli-2.2.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:8dd28b3e155b80f4d54beb40a441d366adcfe740969820caf156c019fb5c7ec4", size = 229894, upload-time = "2024-11-27T22:38:02.094Z" }, - { url = "https://files.pythonhosted.org/packages/55/18/5d8bc5b0a0362311ce4d18830a5d28943667599a60d20118074ea1b01bb7/tomli-2.2.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:e59e304978767a54663af13c07b3d1af22ddee3bb2fb0618ca1593e4f593a106", size = 245319, upload-time = "2024-11-27T22:38:03.206Z" }, - { url = "https://files.pythonhosted.org/packages/92/a3/7ade0576d17f3cdf5ff44d61390d4b3febb8a9fc2b480c75c47ea048c646/tomli-2.2.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:33580bccab0338d00994d7f16f4c4ec25b776af3ffaac1ed74e0b3fc95e885a8", size = 238273, upload-time = "2024-11-27T22:38:04.217Z" }, - { url = "https://files.pythonhosted.org/packages/72/6f/fa64ef058ac1446a1e51110c375339b3ec6be245af9d14c87c4a6412dd32/tomli-2.2.1-cp311-cp311-win32.whl", hash = "sha256:465af0e0875402f1d226519c9904f37254b3045fc5084697cefb9bdde1ff99ff", size = 98310, upload-time = "2024-11-27T22:38:05.908Z" }, - { url = "https://files.pythonhosted.org/packages/6a/1c/4a2dcde4a51b81be3530565e92eda625d94dafb46dbeb15069df4caffc34/tomli-2.2.1-cp311-cp311-win_amd64.whl", hash = "sha256:2d0f2fdd22b02c6d81637a3c95f8cd77f995846af7414c5c4b8d0545afa1bc4b", size = 108309, upload-time = "2024-11-27T22:38:06.812Z" }, - { url = "https://files.pythonhosted.org/packages/52/e1/f8af4c2fcde17500422858155aeb0d7e93477a0d59a98e56cbfe75070fd0/tomli-2.2.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:4a8f6e44de52d5e6c657c9fe83b562f5f4256d8ebbfe4ff922c495620a7f6cea", size = 132762, upload-time = "2024-11-27T22:38:07.731Z" }, - { url = "https://files.pythonhosted.org/packages/03/b8/152c68bb84fc00396b83e7bbddd5ec0bd3dd409db4195e2a9b3e398ad2e3/tomli-2.2.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:8d57ca8095a641b8237d5b079147646153d22552f1c637fd3ba7f4b0b29167a8", size = 123453, upload-time = "2024-11-27T22:38:09.384Z" }, - { url = "https://files.pythonhosted.org/packages/c8/d6/fc9267af9166f79ac528ff7e8c55c8181ded34eb4b0e93daa767b8841573/tomli-2.2.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4e340144ad7ae1533cb897d406382b4b6fede8890a03738ff1683af800d54192", size = 233486, upload-time = "2024-11-27T22:38:10.329Z" }, - { url = "https://files.pythonhosted.org/packages/5c/51/51c3f2884d7bab89af25f678447ea7d297b53b5a3b5730a7cb2ef6069f07/tomli-2.2.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:db2b95f9de79181805df90bedc5a5ab4c165e6ec3fe99f970d0e302f384ad222", size = 242349, upload-time = "2024-11-27T22:38:11.443Z" }, - { url = "https://files.pythonhosted.org/packages/ab/df/bfa89627d13a5cc22402e441e8a931ef2108403db390ff3345c05253935e/tomli-2.2.1-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:40741994320b232529c802f8bc86da4e1aa9f413db394617b9a256ae0f9a7f77", size = 252159, upload-time = "2024-11-27T22:38:13.099Z" }, - { url = "https://files.pythonhosted.org/packages/9e/6e/fa2b916dced65763a5168c6ccb91066f7639bdc88b48adda990db10c8c0b/tomli-2.2.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:400e720fe168c0f8521520190686ef8ef033fb19fc493da09779e592861b78c6", size = 237243, upload-time = "2024-11-27T22:38:14.766Z" }, - { url = "https://files.pythonhosted.org/packages/b4/04/885d3b1f650e1153cbb93a6a9782c58a972b94ea4483ae4ac5cedd5e4a09/tomli-2.2.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:02abe224de6ae62c19f090f68da4e27b10af2b93213d36cf44e6e1c5abd19fdd", size = 259645, upload-time = "2024-11-27T22:38:15.843Z" }, - { url = "https://files.pythonhosted.org/packages/9c/de/6b432d66e986e501586da298e28ebeefd3edc2c780f3ad73d22566034239/tomli-2.2.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:b82ebccc8c8a36f2094e969560a1b836758481f3dc360ce9a3277c65f374285e", size = 244584, upload-time = "2024-11-27T22:38:17.645Z" }, - { url = "https://files.pythonhosted.org/packages/1c/9a/47c0449b98e6e7d1be6cbac02f93dd79003234ddc4aaab6ba07a9a7482e2/tomli-2.2.1-cp312-cp312-win32.whl", hash = "sha256:889f80ef92701b9dbb224e49ec87c645ce5df3fa2cc548664eb8a25e03127a98", size = 98875, upload-time = "2024-11-27T22:38:19.159Z" }, - { url = "https://files.pythonhosted.org/packages/ef/60/9b9638f081c6f1261e2688bd487625cd1e660d0a85bd469e91d8db969734/tomli-2.2.1-cp312-cp312-win_amd64.whl", hash = "sha256:7fc04e92e1d624a4a63c76474610238576942d6b8950a2d7f908a340494e67e4", size = 109418, upload-time = "2024-11-27T22:38:20.064Z" }, - { url = "https://files.pythonhosted.org/packages/6e/c2/61d3e0f47e2b74ef40a68b9e6ad5984f6241a942f7cd3bbfbdbd03861ea9/tomli-2.2.1-py3-none-any.whl", hash = "sha256:cb55c73c5f4408779d0cf3eef9f762b9c9f147a77de7b258bef0a5628adc85cc", size = 14257, upload-time = "2024-11-27T22:38:35.385Z" }, + { url = "https://files.pythonhosted.org/packages/c1/ba/42f134a3fe2b370f555f44b1d72feebb94debcab01676bf918d0cb70e9aa/tomli-2.4.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:c742f741d58a28940ce01d58f0ab2ea3ced8b12402f162f4d534dfe18ba1cd6a", size = 155924, upload-time = "2026-03-25T20:21:21.626Z" }, + { url = "https://files.pythonhosted.org/packages/dc/c7/62d7a17c26487ade21c5422b646110f2162f1fcc95980ef7f63e73c68f14/tomli-2.4.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:7f86fd587c4ed9dd76f318225e7d9b29cfc5a9d43de44e5754db8d1128487085", size = 150018, upload-time = "2026-03-25T20:21:23.002Z" }, + { url = "https://files.pythonhosted.org/packages/5c/05/79d13d7c15f13bdef410bdd49a6485b1c37d28968314eabee452c22a7fda/tomli-2.4.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ff18e6a727ee0ab0388507b89d1bc6a22b138d1e2fa56d1ad494586d61d2eae9", size = 244948, upload-time = "2026-03-25T20:21:24.04Z" }, + { url = "https://files.pythonhosted.org/packages/10/90/d62ce007a1c80d0b2c93e02cab211224756240884751b94ca72df8a875ca/tomli-2.4.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:136443dbd7e1dee43c68ac2694fde36b2849865fa258d39bf822c10e8068eac5", size = 253341, upload-time = "2026-03-25T20:21:25.177Z" }, + { url = "https://files.pythonhosted.org/packages/1a/7e/caf6496d60152ad4ed09282c1885cca4eea150bfd007da84aea07bcc0a3e/tomli-2.4.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:5e262d41726bc187e69af7825504c933b6794dc3fbd5945e41a79bb14c31f585", size = 248159, upload-time = "2026-03-25T20:21:26.364Z" }, + { url = "https://files.pythonhosted.org/packages/99/e7/c6f69c3120de34bbd882c6fba7975f3d7a746e9218e56ab46a1bc4b42552/tomli-2.4.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:5cb41aa38891e073ee49d55fbc7839cfdb2bc0e600add13874d048c94aadddd1", size = 253290, upload-time = "2026-03-25T20:21:27.46Z" }, + { url = "https://files.pythonhosted.org/packages/d6/2f/4a3c322f22c5c66c4b836ec58211641a4067364f5dcdd7b974b4c5da300c/tomli-2.4.1-cp312-cp312-win32.whl", hash = "sha256:da25dc3563bff5965356133435b757a795a17b17d01dbc0f42fb32447ddfd917", size = 98141, upload-time = "2026-03-25T20:21:28.492Z" }, + { url = "https://files.pythonhosted.org/packages/24/22/4daacd05391b92c55759d55eaee21e1dfaea86ce5c571f10083360adf534/tomli-2.4.1-cp312-cp312-win_amd64.whl", hash = "sha256:52c8ef851d9a240f11a88c003eacb03c31fc1c9c4ec64a99a0f922b93874fda9", size = 108847, upload-time = "2026-03-25T20:21:29.386Z" }, + { url = "https://files.pythonhosted.org/packages/68/fd/70e768887666ddd9e9f5d85129e84910f2db2796f9096aa02b721a53098d/tomli-2.4.1-cp312-cp312-win_arm64.whl", hash = "sha256:f758f1b9299d059cc3f6546ae2af89670cb1c4d48ea29c3cacc4fe7de3058257", size = 95088, upload-time = "2026-03-25T20:21:30.677Z" }, + { url = "https://files.pythonhosted.org/packages/7b/61/cceae43728b7de99d9b847560c262873a1f6c98202171fd5ed62640b494b/tomli-2.4.1-py3-none-any.whl", hash = "sha256:0d85819802132122da43cb86656f8d1f8c6587d54ae7dcaf30e90533028b49fe", size = 14583, upload-time = "2026-03-25T20:22:03.012Z" }, ] [[package]] name = "tqdm" -version = "4.67.1" +version = "4.68.3" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "colorama", marker = "sys_platform == 'win32'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a8/4b/29b4ef32e036bb34e4ab51796dd745cdba7ed47ad142a9f4a1eb8e0c744d/tqdm-4.67.1.tar.gz", hash = "sha256:f8aef9c52c08c13a65f30ea34f4e5aac3fd1a34959879d7e59e63027286627f2", size = 169737, upload-time = "2024-11-24T20:12:22.481Z" } +sdist = { url = "https://files.pythonhosted.org/packages/87/d7/0535a28b1f5f24f6612fb3ff1e89fb1a8d160fee0f976e0aa6803862134b/tqdm-4.68.3.tar.gz", hash = "sha256:00dfa48452b6b6cfae3dd9885636c23d3422d1ec97c66d96818cbd5e0821d482", size = 170596, upload-time = "2026-06-17T07:36:52.105Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/d0/30/dc54f88dd4a2b5dc8a0279bdd7270e735851848b762aeb1c1184ed1f6b14/tqdm-4.67.1-py3-none-any.whl", hash = "sha256:26445eca388f82e72884e0d580d5464cd801a3ea01e63e5601bdff9ba6a48de2", size = 78540, upload-time = "2024-11-24T20:12:19.698Z" }, + { url = "https://files.pythonhosted.org/packages/d8/8e/bb97bb0c71802080bfc8952937d174e49cfc50de5c951dd47b2496f0dcdb/tqdm-4.68.3-py3-none-any.whl", hash = "sha256:39832cc2def2789a6f29df83f172db7416cea70052c0907a57801c5f2fdccb03", size = 78337, upload-time = "2026-06-17T07:36:50.132Z" }, ] [[package]] -name = "types-requests" -version = "2.32.4.20250611" +name = "ty" +version = "0.0.56" source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "urllib3" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/6d/7f/73b3a04a53b0fd2a911d4ec517940ecd6600630b559e4505cc7b68beb5a0/types_requests-2.32.4.20250611.tar.gz", hash = "sha256:741c8777ed6425830bf51e54d6abe245f79b4dcb9019f1622b773463946bf826", size = 23118, upload-time = "2025-06-11T03:11:41.272Z" } +sdist = { url = "https://files.pythonhosted.org/packages/55/07/fb29aea5235b0aa8ecfc4d1cc6ddf9fba8b863d67d96c6d345694d644c43/ty-0.0.56.tar.gz", hash = "sha256:84d114dc3796361c0fc72945016eabd74d46b9ee64f198cb0e485719704681e5", size = 6050123, upload-time = "2026-07-01T16:44:56.036Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/3d/ea/0be9258c5a4fa1ba2300111aa5a0767ee6d18eb3fd20e91616c12082284d/types_requests-2.32.4.20250611-py3-none-any.whl", hash = "sha256:ad2fe5d3b0cb3c2c902c8815a70e7fb2302c4b8c1f77bdcd738192cdb3878072", size = 20643, upload-time = "2025-06-11T03:11:40.186Z" }, -] - -[[package]] -name = "types-tabulate" -version = "0.9.0.20241207" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/3f/43/16030404a327e4ff8c692f2273854019ed36718667b2993609dc37d14dd4/types_tabulate-0.9.0.20241207.tar.gz", hash = "sha256:ac1ac174750c0a385dfd248edc6279fa328aaf4ea317915ab879a2ec47833230", size = 8195, upload-time = "2024-12-07T02:54:42.554Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/5e/86/a9ebfd509cbe74471106dffed320e208c72537f9aeb0a55eaa6b1b5e4d17/types_tabulate-0.9.0.20241207-py3-none-any.whl", hash = "sha256:b8dad1343c2a8ba5861c5441370c3e35908edd234ff036d4298708a1d4cf8a85", size = 8307, upload-time = "2024-12-07T02:54:41.031Z" }, -] - -[[package]] -name = "typing-extensions" -version = "4.14.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/d1/bc/51647cd02527e87d05cb083ccc402f93e441606ff1f01739a62c8ad09ba5/typing_extensions-4.14.0.tar.gz", hash = "sha256:8676b788e32f02ab42d9e7c61324048ae4c6d844a399eebace3d4979d75ceef4", size = 107423, upload-time = "2025-06-02T14:52:11.399Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/69/e0/552843e0d356fbb5256d21449fa957fa4eff3bbc135a74a691ee70c7c5da/typing_extensions-4.14.0-py3-none-any.whl", hash = "sha256:a1514509136dd0b477638fc68d6a91497af5076466ad0fa6c338e44e359944af", size = 43839, upload-time = "2025-06-02T14:52:10.026Z" }, + { url = "https://files.pythonhosted.org/packages/dc/48/bce79e7ca5c1cc529d3e0d37ddd1121aea4b68a4f749974ad1cc77161871/ty-0.0.56-py3-none-linux_armv6l.whl", hash = "sha256:186d4a53e15747c947e1ec3d7eec8e345d8e40a1ca10e634c585db52497e87dd", size = 11643066, upload-time = "2026-07-01T16:44:18.374Z" }, + { url = "https://files.pythonhosted.org/packages/80/d1/22555d8a1d719661f10050f3865d877bbf497da908961c75fe22217dd18a/ty-0.0.56-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:aae1a980fd9535da0469b7ba2b2e1b54a907743a5e0f442dd57eee9f5bfd034c", size = 11407487, upload-time = "2026-07-01T16:44:20.956Z" }, + { url = "https://files.pythonhosted.org/packages/cf/2d/b3b7a74ce8bc59ef48843ad80179bb0d9598bbd6cfc0d11d519bdf6b1352/ty-0.0.56-py3-none-macosx_11_0_arm64.whl", hash = "sha256:afd3058c0a6c5f241e814734f133008c93ee805f61c9cf4ce7412b8822b5d9ad", size = 10962270, upload-time = "2026-07-01T16:44:22.959Z" }, + { url = "https://files.pythonhosted.org/packages/64/ac/6c2fd7de0304a8a7218a756af74f7e62a5e8540fdb175e0a869e51042345/ty-0.0.56-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:058b52f7a823ac13aae3cae30809dd6b5145794b64d8478f9ef38c75d79b4483", size = 11471406, upload-time = "2026-07-01T16:44:25.327Z" }, + { url = "https://files.pythonhosted.org/packages/50/b6/11d861156861c03c7726b74558f9a0e0092661aff83a4fda1279df28c425/ty-0.0.56-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:2c66e00c1522add1f2bbdd2e45828c953b35c306b7bef03ec9169c75a63699a0", size = 11445612, upload-time = "2026-07-01T16:44:27.531Z" }, + { url = "https://files.pythonhosted.org/packages/fb/ba/09df108582090f3c0770ec4bc8675affed60248f6793a78d909be16211d9/ty-0.0.56-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:40903d71c669a30691b5a5d5728056c7877a1bd6be4f233a38883a8b28cf34d7", size = 12093889, upload-time = "2026-07-01T16:44:29.548Z" }, + { url = "https://files.pythonhosted.org/packages/d7/f7/dbb4b4ccb69cd64c209ae55b1ab788ace8222c2bc1f6845be9e7cbedbf25/ty-0.0.56-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:63fe3947fe0c46c69a7d950e6832ee70a9ec17321fefbff3d2e3c20baf9e5bd0", size = 12666337, upload-time = "2026-07-01T16:44:31.586Z" }, + { url = "https://files.pythonhosted.org/packages/86/e9/73f903fe4a3d9ea02f26f57c1eb07e3b1029ec92b0e8c2364718893440e3/ty-0.0.56-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:71a0c1a72f9854532e710e119b6871ffe4542c8a65146f1f65dcd78fecd885b4", size = 12280247, upload-time = "2026-07-01T16:44:33.637Z" }, + { url = "https://files.pythonhosted.org/packages/d6/90/cebd222495832f1a00dcd321ba25f3cab804221a4991b992c2178bec68ee/ty-0.0.56-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:70d1665596494e24d8ebd198438872b5a56ec3cae5f2bcf6c673be797acc4e3c", size = 11991107, upload-time = "2026-07-01T16:44:36.122Z" }, + { url = "https://files.pythonhosted.org/packages/b7/07/8f7337a07250f42d975cdb6decf47fc5b421e6c7da5e3e7be1e85f63a7e5/ty-0.0.56-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:778f99e51558afc1dbbe48ee38ab6aae7b31390ed8c1a1ef1499b295e9f1e82f", size = 12298970, upload-time = "2026-07-01T16:44:38.243Z" }, + { url = "https://files.pythonhosted.org/packages/3c/b9/a52cd59034a48f5f18c6b155cc2cc36861d874b6d0af204b12c898024c3d/ty-0.0.56-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:867bc5708e0066bb4ff6c7db524bd5deea2676c62bfe71d3303138b3be850af0", size = 11425683, upload-time = "2026-07-01T16:44:40.473Z" }, + { url = "https://files.pythonhosted.org/packages/1d/2e/48e42d33357d52eefb695c0c3fcfc96879b73668a7447d1d1e0ad774fedc/ty-0.0.56-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:a6012f4189c928edb330a37deb9930f982380bd4aa7c4b8e0428eec9651c7551", size = 11469258, upload-time = "2026-07-01T16:44:42.513Z" }, + { url = "https://files.pythonhosted.org/packages/d5/01/ad1b4138be1e3fa97863af3925aa2134f17a593240c35dc38c3429fb5ad1/ty-0.0.56-py3-none-musllinux_1_2_i686.whl", hash = "sha256:8ee83de1a7ff4cc32837ec06134ce391d441bc5b35ecd8d3cfe053f120f3e4c1", size = 11758736, upload-time = "2026-07-01T16:44:44.567Z" }, + { url = "https://files.pythonhosted.org/packages/09/34/9d81967ff240eaa57e9249728ef7b7790747cf6d3c9a98ec86b2cfdcc8ee/ty-0.0.56-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:62619b3b0e2c6248ef30d3f0e2f2217ae9893040585be07f32324242f197cd6f", size = 12100242, upload-time = "2026-07-01T16:44:46.584Z" }, + { url = "https://files.pythonhosted.org/packages/c3/36/f51d4666d2de6cf33c1f3a1fcc4bb6b70b197dd6ceaa491eef71d78fe8e8/ty-0.0.56-py3-none-win32.whl", hash = "sha256:b30687bb5cd9729d34c889a289edf32770388d9bb05243e534e723fb45e0381b", size = 11093759, upload-time = "2026-07-01T16:44:49.171Z" }, + { url = "https://files.pythonhosted.org/packages/5e/b4/8fb5d4acfa4afb152245b20fa263069a7547bd1f8e4bfca4eda280c897d7/ty-0.0.56-py3-none-win_amd64.whl", hash = "sha256:ad4c8c47b6f4e3f9ed3fc0b1a5d650088d229e17dd8f63c1826d6bbe94cc3235", size = 12100327, upload-time = "2026-07-01T16:44:51.26Z" }, + { url = "https://files.pythonhosted.org/packages/b8/fc/6a183e71edde90d0c35c2303f23f7a45b6891d1a2c45daf7b8f869831e19/ty-0.0.56-py3-none-win_arm64.whl", hash = "sha256:57538f273d444a5f1293fa7860e967178afe3917611fc5eff16b64e1204fe0d6", size = 11538780, upload-time = "2026-07-01T16:44:53.8Z" }, ] [[package]] name = "urllib3" -version = "2.5.0" +version = "2.7.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/15/22/9ee70a2574a4f4599c47dd506532914ce044817c7752a79b6a51286319bc/urllib3-2.5.0.tar.gz", hash = "sha256:3fc47733c7e419d4bc3f6b3dc2b4f890bb743906a30d56ba4a5bfa4bbff92760", size = 393185, upload-time = "2025-06-18T14:07:41.644Z" } +sdist = { url = "https://files.pythonhosted.org/packages/53/0c/06f8b233b8fd13b9e5ee11424ef85419ba0d8ba0b3138bf360be2ff56953/urllib3-2.7.0.tar.gz", hash = "sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c", size = 433602, upload-time = "2026-05-07T16:13:18.596Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/a7/c2/fe1e52489ae3122415c51f387e221dd0773709bad6c6cdaa599e8a2c5185/urllib3-2.5.0-py3-none-any.whl", hash = "sha256:e6b01673c0fa6a13e374b50871808eb3bf7046c4b125b216f6bf1cc604cff0dc", size = 129795, upload-time = "2025-06-18T14:07:40.39Z" }, -] - -[[package]] -name = "watchdog" -version = "6.0.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/db/7d/7f3d619e951c88ed75c6037b246ddcf2d322812ee8ea189be89511721d54/watchdog-6.0.0.tar.gz", hash = "sha256:9ddf7c82fda3ae8e24decda1338ede66e1c99883db93711d8fb941eaa2d8c282", size = 131220, upload-time = "2024-11-01T14:07:13.037Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/e0/24/d9be5cd6642a6aa68352ded4b4b10fb0d7889cb7f45814fb92cecd35f101/watchdog-6.0.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:6eb11feb5a0d452ee41f824e271ca311a09e250441c262ca2fd7ebcf2461a06c", size = 96393, upload-time = "2024-11-01T14:06:31.756Z" }, - { url = "https://files.pythonhosted.org/packages/63/7a/6013b0d8dbc56adca7fdd4f0beed381c59f6752341b12fa0886fa7afc78b/watchdog-6.0.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:ef810fbf7b781a5a593894e4f439773830bdecb885e6880d957d5b9382a960d2", size = 88392, upload-time = "2024-11-01T14:06:32.99Z" }, - { url = "https://files.pythonhosted.org/packages/d1/40/b75381494851556de56281e053700e46bff5b37bf4c7267e858640af5a7f/watchdog-6.0.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:afd0fe1b2270917c5e23c2a65ce50c2a4abb63daafb0d419fde368e272a76b7c", size = 89019, upload-time = "2024-11-01T14:06:34.963Z" }, - { url = "https://files.pythonhosted.org/packages/39/ea/3930d07dafc9e286ed356a679aa02d777c06e9bfd1164fa7c19c288a5483/watchdog-6.0.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:bdd4e6f14b8b18c334febb9c4425a878a2ac20efd1e0b231978e7b150f92a948", size = 96471, upload-time = "2024-11-01T14:06:37.745Z" }, - { url = "https://files.pythonhosted.org/packages/12/87/48361531f70b1f87928b045df868a9fd4e253d9ae087fa4cf3f7113be363/watchdog-6.0.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:c7c15dda13c4eb00d6fb6fc508b3c0ed88b9d5d374056b239c4ad1611125c860", size = 88449, upload-time = "2024-11-01T14:06:39.748Z" }, - { url = "https://files.pythonhosted.org/packages/5b/7e/8f322f5e600812e6f9a31b75d242631068ca8f4ef0582dd3ae6e72daecc8/watchdog-6.0.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:6f10cb2d5902447c7d0da897e2c6768bca89174d0c6e1e30abec5421af97a5b0", size = 89054, upload-time = "2024-11-01T14:06:41.009Z" }, - { url = "https://files.pythonhosted.org/packages/a9/c7/ca4bf3e518cb57a686b2feb4f55a1892fd9a3dd13f470fca14e00f80ea36/watchdog-6.0.0-py3-none-manylinux2014_aarch64.whl", hash = "sha256:7607498efa04a3542ae3e05e64da8202e58159aa1fa4acddf7678d34a35d4f13", size = 79079, upload-time = "2024-11-01T14:06:59.472Z" }, - { url = "https://files.pythonhosted.org/packages/5c/51/d46dc9332f9a647593c947b4b88e2381c8dfc0942d15b8edc0310fa4abb1/watchdog-6.0.0-py3-none-manylinux2014_armv7l.whl", hash = "sha256:9041567ee8953024c83343288ccc458fd0a2d811d6a0fd68c4c22609e3490379", size = 79078, upload-time = "2024-11-01T14:07:01.431Z" }, - { url = "https://files.pythonhosted.org/packages/d4/57/04edbf5e169cd318d5f07b4766fee38e825d64b6913ca157ca32d1a42267/watchdog-6.0.0-py3-none-manylinux2014_i686.whl", hash = "sha256:82dc3e3143c7e38ec49d61af98d6558288c415eac98486a5c581726e0737c00e", size = 79076, upload-time = "2024-11-01T14:07:02.568Z" }, - { url = "https://files.pythonhosted.org/packages/ab/cc/da8422b300e13cb187d2203f20b9253e91058aaf7db65b74142013478e66/watchdog-6.0.0-py3-none-manylinux2014_ppc64.whl", hash = "sha256:212ac9b8bf1161dc91bd09c048048a95ca3a4c4f5e5d4a7d1b1a7d5752a7f96f", size = 79077, upload-time = "2024-11-01T14:07:03.893Z" }, - { url = "https://files.pythonhosted.org/packages/2c/3b/b8964e04ae1a025c44ba8e4291f86e97fac443bca31de8bd98d3263d2fcf/watchdog-6.0.0-py3-none-manylinux2014_ppc64le.whl", hash = "sha256:e3df4cbb9a450c6d49318f6d14f4bbc80d763fa587ba46ec86f99f9e6876bb26", size = 79078, upload-time = "2024-11-01T14:07:05.189Z" }, - { url = "https://files.pythonhosted.org/packages/62/ae/a696eb424bedff7407801c257d4b1afda455fe40821a2be430e173660e81/watchdog-6.0.0-py3-none-manylinux2014_s390x.whl", hash = "sha256:2cce7cfc2008eb51feb6aab51251fd79b85d9894e98ba847408f662b3395ca3c", size = 79077, upload-time = "2024-11-01T14:07:06.376Z" }, - { url = "https://files.pythonhosted.org/packages/b5/e8/dbf020b4d98251a9860752a094d09a65e1b436ad181faf929983f697048f/watchdog-6.0.0-py3-none-manylinux2014_x86_64.whl", hash = "sha256:20ffe5b202af80ab4266dcd3e91aae72bf2da48c0d33bdb15c66658e685e94e2", size = 79078, upload-time = "2024-11-01T14:07:07.547Z" }, - { url = "https://files.pythonhosted.org/packages/07/f6/d0e5b343768e8bcb4cda79f0f2f55051bf26177ecd5651f84c07567461cf/watchdog-6.0.0-py3-none-win32.whl", hash = "sha256:07df1fdd701c5d4c8e55ef6cf55b8f0120fe1aef7ef39a1c6fc6bc2e606d517a", size = 79065, upload-time = "2024-11-01T14:07:09.525Z" }, - { url = "https://files.pythonhosted.org/packages/db/d9/c495884c6e548fce18a8f40568ff120bc3a4b7b99813081c8ac0c936fa64/watchdog-6.0.0-py3-none-win_amd64.whl", hash = "sha256:cbafb470cf848d93b5d013e2ecb245d4aa1c8fd0504e863ccefa32445359d680", size = 79070, upload-time = "2024-11-01T14:07:10.686Z" }, - { url = "https://files.pythonhosted.org/packages/33/e8/e40370e6d74ddba47f002a32919d91310d6074130fe4e17dabcafc15cbf1/watchdog-6.0.0-py3-none-win_ia64.whl", hash = "sha256:a1914259fa9e1454315171103c6a30961236f508b9b623eae470268bbcc6a22f", size = 79067, upload-time = "2024-11-01T14:07:11.845Z" }, + { url = "https://files.pythonhosted.org/packages/7f/3e/5db95bcf282c52709639744ca2a8b149baccf648e39c8cc87553df9eae0c/urllib3-2.7.0-py3-none-any.whl", hash = "sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897", size = 131087, upload-time = "2026-05-07T16:13:17.151Z" }, ] [[package]] name = "websocket-client" -version = "1.8.0" +version = "1.9.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/e6/30/fba0d96b4b5fbf5948ed3f4681f7da2f9f64512e1d303f94b4cc174c24a5/websocket_client-1.8.0.tar.gz", hash = "sha256:3239df9f44da632f96012472805d40a23281a991027ce11d2f45a6f24ac4c3da", size = 54648, upload-time = "2024-04-23T22:16:16.976Z" } +sdist = { url = "https://files.pythonhosted.org/packages/2c/41/aa4bf9664e4cda14c3b39865b12251e8e7d239f4cd0e3cc1b6c2ccde25c1/websocket_client-1.9.0.tar.gz", hash = "sha256:9e813624b6eb619999a97dc7958469217c3176312b3a16a4bd1bc7e08a46ec98", size = 70576, upload-time = "2025-10-07T21:16:36.495Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/5a/84/44687a29792a70e111c5c477230a72c4b957d88d16141199bf9acb7537a3/websocket_client-1.8.0-py3-none-any.whl", hash = "sha256:17b44cc997f5c498e809b22cdf2d9c7a9e71c02c8cc2b6c56e7c2d1239bfa526", size = 58826, upload-time = "2024-04-23T22:16:14.422Z" }, + { url = "https://files.pythonhosted.org/packages/34/db/b10e48aa8fff7407e67470363eac595018441cf32d5e1001567a7aeba5d2/websocket_client-1.9.0-py3-none-any.whl", hash = "sha256:af248a825037ef591efbf6ed20cc5faa03d3b47b9e5a2230a529eeee1c1fc3ef", size = 82616, upload-time = "2025-10-07T21:16:34.951Z" }, ] [[package]] -name = "xattr" -version = "1.1.4" +name = "zensical" +version = "0.0.46" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "cffi" }, + { name = "click" }, + { name = "deepmerge" }, + { name = "jinja2" }, + { name = "markdown" }, + { name = "pygments" }, + { name = "pymdown-extensions" }, + { name = "pyyaml" }, + { name = "tomli" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/62/bf/8b98081f9f8fd56d67b9478ff1e0f8c337cde08bcb92f0d592f0a7958983/xattr-1.1.4.tar.gz", hash = "sha256:b7b02ecb2270da5b7e7deaeea8f8b528c17368401c2b9d5f63e91f545b45d372", size = 16729, upload-time = "2025-01-06T19:19:32.557Z" } +sdist = { url = "https://files.pythonhosted.org/packages/aa/57/c7bbb71f943e1e0ba5ce460f4930ec836ead7286969e7fd742f7a6c049ab/zensical-0.0.46.tar.gz", hash = "sha256:3ec21f4fb1e78cd7c0d6b07ae336b04770e27ba020dabc457b2790e5d34f1978", size = 3973968, upload-time = "2026-06-21T18:52:40.368Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/78/5b/f64ba0f93e6447e1997068959f22ff99e08d77dd88d9edcf97ddcb9e9016/xattr-1.1.4-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:bb4bbe37ba95542081890dd34fa5347bef4651e276647adaa802d5d0d7d86452", size = 23920, upload-time = "2025-01-06T19:17:48.234Z" }, - { url = "https://files.pythonhosted.org/packages/c8/54/ad66655f0b1317b0a297aa2d6ed7d6e5d5343495841fad535bee37a56471/xattr-1.1.4-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:3da489ecef798705f9a39ea8cea4ead0d1eeed55f92c345add89740bd930bab6", size = 18883, upload-time = "2025-01-06T19:17:49.46Z" }, - { url = "https://files.pythonhosted.org/packages/4d/5d/7d5154570bbcb898e6123c292f697c87c33e12258a1a8b9741539f952681/xattr-1.1.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:798dd0cbe696635a6f74b06fc430818bf9c3b24314e1502eadf67027ab60c9b0", size = 19221, upload-time = "2025-01-06T19:17:51.654Z" }, - { url = "https://files.pythonhosted.org/packages/b9/b7/135cf3018278051f57bb5dde944cb1ca4f7ad4ec383465a08c6a5c7f7152/xattr-1.1.4-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7b2b6361626efad5eb5a6bf8172c6c67339e09397ee8140ec41258737bea9681", size = 39098, upload-time = "2025-01-06T19:17:53.099Z" }, - { url = "https://files.pythonhosted.org/packages/a5/62/577e2eb0108158b78cd93ea3782c7a8d464693f1338a5350a1db16f69a89/xattr-1.1.4-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:6e7fa20a0c9ce022d19123b1c5b848d00a68b837251835a7929fe041ee81dcd0", size = 36982, upload-time = "2025-01-06T19:17:54.493Z" }, - { url = "https://files.pythonhosted.org/packages/59/cc/ab3bd7a4bedf445be4b35de4a4627ef2944786724d18eaf28d05c1238c7c/xattr-1.1.4-cp311-cp311-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6e20eeb08e2c57fc7e71f050b1cfae35cbb46105449853a582bf53fd23c5379e", size = 38891, upload-time = "2025-01-06T19:17:55.853Z" }, - { url = "https://files.pythonhosted.org/packages/45/e8/2285651d92f1460159753fe6628af259c943fcc5071e48a0540fa11dc34d/xattr-1.1.4-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:477370e75821bded901487e5e752cffe554d1bd3bd4839b627d4d1ee8c95a093", size = 38362, upload-time = "2025-01-06T19:17:57.078Z" }, - { url = "https://files.pythonhosted.org/packages/5f/af/7856c0b1970272a53a428bb20dc125f9fd350fb1b40ebca4e54610af1b79/xattr-1.1.4-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:a8682091cd34a9f4a93c8aaea4101aae99f1506e24da00a3cc3dd2eca9566f21", size = 36724, upload-time = "2025-01-06T19:17:58.534Z" }, - { url = "https://files.pythonhosted.org/packages/5d/34/087e02b32d6288a40b7f6573e97a119016e6c3713d4f4b866bbf56cfb803/xattr-1.1.4-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:2e079b3b1a274ba2121cf0da38bbe5c8d2fb1cc49ecbceb395ce20eb7d69556d", size = 37945, upload-time = "2025-01-06T19:17:59.764Z" }, - { url = "https://files.pythonhosted.org/packages/f0/2a/d0f9e46de4cec5e4aa45fd939549b977c49dd68202fa844d07cb24ce5f17/xattr-1.1.4-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:ae6579dea05bf9f335a082f711d5924a98da563cac72a2d550f5b940c401c0e9", size = 23917, upload-time = "2025-01-06T19:18:00.868Z" }, - { url = "https://files.pythonhosted.org/packages/83/e0/a5764257cd9c9eb598f4648a3658d915dd3520ec111ecbd251b685de6546/xattr-1.1.4-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:cd6038ec9df2e67af23c212693751481d5f7e858156924f14340376c48ed9ac7", size = 18891, upload-time = "2025-01-06T19:18:02.029Z" }, - { url = "https://files.pythonhosted.org/packages/8b/83/a81a147987387fd2841a28f767efedb099cf90e23553ead458f2330e47c5/xattr-1.1.4-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:608b2877526674eb15df4150ef4b70b7b292ae00e65aecaae2f192af224be200", size = 19213, upload-time = "2025-01-06T19:18:03.303Z" }, - { url = "https://files.pythonhosted.org/packages/4b/52/bf093b4eb9873ffc9e9373dcb38ec8a9b5cd4e6a9f681c4c5cf6bf067a42/xattr-1.1.4-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c54dad1a6a998c6a23edfd25e99f4d38e9b942d54e518570044edf8c767687ea", size = 39302, upload-time = "2025-01-06T19:18:05.846Z" }, - { url = "https://files.pythonhosted.org/packages/2d/d8/9d7315ebae76a7f48bc5e1aecc7e592eb43376a0f6cf470a854d895d2093/xattr-1.1.4-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c0dab6ff72bb2b508f3850c368f8e53bd706585012676e1f71debba3310acde8", size = 37224, upload-time = "2025-01-06T19:18:07.226Z" }, - { url = "https://files.pythonhosted.org/packages/c8/b2/10eb17bea7e378b2bcd76fc8c2e5158318e2c08e774b13f548f333d7318a/xattr-1.1.4-cp312-cp312-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7a3c54c6af7cf09432b2c461af257d5f4b1cb2d59eee045f91bacef44421a46d", size = 39145, upload-time = "2025-01-06T19:18:08.403Z" }, - { url = "https://files.pythonhosted.org/packages/74/fb/95bbc28116b3c19a21acc34ec0a5973e9cc97fe49d3f47a65775af3760a8/xattr-1.1.4-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:e346e05a158d554639fbf7a0db169dc693c2d2260c7acb3239448f1ff4a9d67f", size = 38469, upload-time = "2025-01-06T19:18:09.602Z" }, - { url = "https://files.pythonhosted.org/packages/af/03/23db582cb271ed47f2d62956e112501d998b5493f892a77104b5795ae2fc/xattr-1.1.4-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:3ff6d9e2103d0d6e5fcd65b85a2005b66ea81c0720a37036445faadc5bbfa424", size = 36797, upload-time = "2025-01-06T19:18:10.709Z" }, - { url = "https://files.pythonhosted.org/packages/90/c4/b631d0174e097cf8c44d4f70c66545d91dc8ba15bbfa5054dd7da8371461/xattr-1.1.4-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:7a2ee4563c6414dfec0d1ac610f59d39d5220531ae06373eeb1a06ee37cd193f", size = 38128, upload-time = "2025-01-06T19:18:11.884Z" }, -] - -[[package]] -name = "yapf" -version = "0.43.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "platformdirs" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/23/97/b6f296d1e9cc1ec25c7604178b48532fa5901f721bcf1b8d8148b13e5588/yapf-0.43.0.tar.gz", hash = "sha256:00d3aa24bfedff9420b2e0d5d9f5ab6d9d4268e72afbf59bb3fa542781d5218e", size = 254907, upload-time = "2024-11-14T00:11:41.584Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/37/81/6acd6601f61e31cfb8729d3da6d5df966f80f374b78eff83760714487338/yapf-0.43.0-py3-none-any.whl", hash = "sha256:224faffbc39c428cb095818cf6ef5511fdab6f7430a10783fdfb292ccf2852ca", size = 256158, upload-time = "2024-11-14T00:11:39.37Z" }, -] - -[[package]] -name = "yarl" -version = "1.20.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "idna" }, - { name = "multidict" }, - { name = "propcache" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/3c/fb/efaa23fa4e45537b827620f04cf8f3cd658b76642205162e072703a5b963/yarl-1.20.1.tar.gz", hash = "sha256:d017a4997ee50c91fd5466cef416231bb82177b93b029906cefc542ce14c35ac", size = 186428, upload-time = "2025-06-10T00:46:09.923Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b1/18/893b50efc2350e47a874c5c2d67e55a0ea5df91186b2a6f5ac52eff887cd/yarl-1.20.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:47ee6188fea634bdfaeb2cc420f5b3b17332e6225ce88149a17c413c77ff269e", size = 133833, upload-time = "2025-06-10T00:43:07.393Z" }, - { url = "https://files.pythonhosted.org/packages/89/ed/b8773448030e6fc47fa797f099ab9eab151a43a25717f9ac043844ad5ea3/yarl-1.20.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:d0f6500f69e8402d513e5eedb77a4e1818691e8f45e6b687147963514d84b44b", size = 91070, upload-time = "2025-06-10T00:43:09.538Z" }, - { url = "https://files.pythonhosted.org/packages/e3/e3/409bd17b1e42619bf69f60e4f031ce1ccb29bd7380117a55529e76933464/yarl-1.20.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:7a8900a42fcdaad568de58887c7b2f602962356908eedb7628eaf6021a6e435b", size = 89818, upload-time = "2025-06-10T00:43:11.575Z" }, - { url = "https://files.pythonhosted.org/packages/f8/77/64d8431a4d77c856eb2d82aa3de2ad6741365245a29b3a9543cd598ed8c5/yarl-1.20.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:bad6d131fda8ef508b36be3ece16d0902e80b88ea7200f030a0f6c11d9e508d4", size = 347003, upload-time = "2025-06-10T00:43:14.088Z" }, - { url = "https://files.pythonhosted.org/packages/8d/d2/0c7e4def093dcef0bd9fa22d4d24b023788b0a33b8d0088b51aa51e21e99/yarl-1.20.1-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:df018d92fe22aaebb679a7f89fe0c0f368ec497e3dda6cb81a567610f04501f1", size = 336537, upload-time = "2025-06-10T00:43:16.431Z" }, - { url = "https://files.pythonhosted.org/packages/f0/f3/fc514f4b2cf02cb59d10cbfe228691d25929ce8f72a38db07d3febc3f706/yarl-1.20.1-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:8f969afbb0a9b63c18d0feecf0db09d164b7a44a053e78a7d05f5df163e43833", size = 362358, upload-time = "2025-06-10T00:43:18.704Z" }, - { url = "https://files.pythonhosted.org/packages/ea/6d/a313ac8d8391381ff9006ac05f1d4331cee3b1efaa833a53d12253733255/yarl-1.20.1-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:812303eb4aa98e302886ccda58d6b099e3576b1b9276161469c25803a8db277d", size = 357362, upload-time = "2025-06-10T00:43:20.888Z" }, - { url = "https://files.pythonhosted.org/packages/00/70/8f78a95d6935a70263d46caa3dd18e1f223cf2f2ff2037baa01a22bc5b22/yarl-1.20.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:98c4a7d166635147924aa0bf9bfe8d8abad6fffa6102de9c99ea04a1376f91e8", size = 348979, upload-time = "2025-06-10T00:43:23.169Z" }, - { url = "https://files.pythonhosted.org/packages/cb/05/42773027968968f4f15143553970ee36ead27038d627f457cc44bbbeecf3/yarl-1.20.1-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:12e768f966538e81e6e7550f9086a6236b16e26cd964cf4df35349970f3551cf", size = 337274, upload-time = "2025-06-10T00:43:27.111Z" }, - { url = "https://files.pythonhosted.org/packages/05/be/665634aa196954156741ea591d2f946f1b78ceee8bb8f28488bf28c0dd62/yarl-1.20.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:fe41919b9d899661c5c28a8b4b0acf704510b88f27f0934ac7a7bebdd8938d5e", size = 363294, upload-time = "2025-06-10T00:43:28.96Z" }, - { url = "https://files.pythonhosted.org/packages/eb/90/73448401d36fa4e210ece5579895731f190d5119c4b66b43b52182e88cd5/yarl-1.20.1-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:8601bc010d1d7780592f3fc1bdc6c72e2b6466ea34569778422943e1a1f3c389", size = 358169, upload-time = "2025-06-10T00:43:30.701Z" }, - { url = "https://files.pythonhosted.org/packages/c3/b0/fce922d46dc1eb43c811f1889f7daa6001b27a4005587e94878570300881/yarl-1.20.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:daadbdc1f2a9033a2399c42646fbd46da7992e868a5fe9513860122d7fe7a73f", size = 362776, upload-time = "2025-06-10T00:43:32.51Z" }, - { url = "https://files.pythonhosted.org/packages/f1/0d/b172628fce039dae8977fd22caeff3eeebffd52e86060413f5673767c427/yarl-1.20.1-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:03aa1e041727cb438ca762628109ef1333498b122e4c76dd858d186a37cec845", size = 381341, upload-time = "2025-06-10T00:43:34.543Z" }, - { url = "https://files.pythonhosted.org/packages/6b/9b/5b886d7671f4580209e855974fe1cecec409aa4a89ea58b8f0560dc529b1/yarl-1.20.1-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:642980ef5e0fa1de5fa96d905c7e00cb2c47cb468bfcac5a18c58e27dbf8d8d1", size = 379988, upload-time = "2025-06-10T00:43:36.489Z" }, - { url = "https://files.pythonhosted.org/packages/73/be/75ef5fd0fcd8f083a5d13f78fd3f009528132a1f2a1d7c925c39fa20aa79/yarl-1.20.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:86971e2795584fe8c002356d3b97ef6c61862720eeff03db2a7c86b678d85b3e", size = 371113, upload-time = "2025-06-10T00:43:38.592Z" }, - { url = "https://files.pythonhosted.org/packages/50/4f/62faab3b479dfdcb741fe9e3f0323e2a7d5cd1ab2edc73221d57ad4834b2/yarl-1.20.1-cp311-cp311-win32.whl", hash = "sha256:597f40615b8d25812f14562699e287f0dcc035d25eb74da72cae043bb884d773", size = 81485, upload-time = "2025-06-10T00:43:41.038Z" }, - { url = "https://files.pythonhosted.org/packages/f0/09/d9c7942f8f05c32ec72cd5c8e041c8b29b5807328b68b4801ff2511d4d5e/yarl-1.20.1-cp311-cp311-win_amd64.whl", hash = "sha256:26ef53a9e726e61e9cd1cda6b478f17e350fb5800b4bd1cd9fe81c4d91cfeb2e", size = 86686, upload-time = "2025-06-10T00:43:42.692Z" }, - { url = "https://files.pythonhosted.org/packages/5f/9a/cb7fad7d73c69f296eda6815e4a2c7ed53fc70c2f136479a91c8e5fbdb6d/yarl-1.20.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:bdcc4cd244e58593a4379fe60fdee5ac0331f8eb70320a24d591a3be197b94a9", size = 133667, upload-time = "2025-06-10T00:43:44.369Z" }, - { url = "https://files.pythonhosted.org/packages/67/38/688577a1cb1e656e3971fb66a3492501c5a5df56d99722e57c98249e5b8a/yarl-1.20.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:b29a2c385a5f5b9c7d9347e5812b6f7ab267193c62d282a540b4fc528c8a9d2a", size = 91025, upload-time = "2025-06-10T00:43:46.295Z" }, - { url = "https://files.pythonhosted.org/packages/50/ec/72991ae51febeb11a42813fc259f0d4c8e0507f2b74b5514618d8b640365/yarl-1.20.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1112ae8154186dfe2de4732197f59c05a83dc814849a5ced892b708033f40dc2", size = 89709, upload-time = "2025-06-10T00:43:48.22Z" }, - { url = "https://files.pythonhosted.org/packages/99/da/4d798025490e89426e9f976702e5f9482005c548c579bdae792a4c37769e/yarl-1.20.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:90bbd29c4fe234233f7fa2b9b121fb63c321830e5d05b45153a2ca68f7d310ee", size = 352287, upload-time = "2025-06-10T00:43:49.924Z" }, - { url = "https://files.pythonhosted.org/packages/1a/26/54a15c6a567aac1c61b18aa0f4b8aa2e285a52d547d1be8bf48abe2b3991/yarl-1.20.1-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:680e19c7ce3710ac4cd964e90dad99bf9b5029372ba0c7cbfcd55e54d90ea819", size = 345429, upload-time = "2025-06-10T00:43:51.7Z" }, - { url = "https://files.pythonhosted.org/packages/d6/95/9dcf2386cb875b234353b93ec43e40219e14900e046bf6ac118f94b1e353/yarl-1.20.1-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:4a979218c1fdb4246a05efc2cc23859d47c89af463a90b99b7c56094daf25a16", size = 365429, upload-time = "2025-06-10T00:43:53.494Z" }, - { url = "https://files.pythonhosted.org/packages/91/b2/33a8750f6a4bc224242a635f5f2cff6d6ad5ba651f6edcccf721992c21a0/yarl-1.20.1-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:255b468adf57b4a7b65d8aad5b5138dce6a0752c139965711bdcb81bc370e1b6", size = 363862, upload-time = "2025-06-10T00:43:55.766Z" }, - { url = "https://files.pythonhosted.org/packages/98/28/3ab7acc5b51f4434b181b0cee8f1f4b77a65919700a355fb3617f9488874/yarl-1.20.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a97d67108e79cfe22e2b430d80d7571ae57d19f17cda8bb967057ca8a7bf5bfd", size = 355616, upload-time = "2025-06-10T00:43:58.056Z" }, - { url = "https://files.pythonhosted.org/packages/36/a3/f666894aa947a371724ec7cd2e5daa78ee8a777b21509b4252dd7bd15e29/yarl-1.20.1-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:8570d998db4ddbfb9a590b185a0a33dbf8aafb831d07a5257b4ec9948df9cb0a", size = 339954, upload-time = "2025-06-10T00:43:59.773Z" }, - { url = "https://files.pythonhosted.org/packages/f1/81/5f466427e09773c04219d3450d7a1256138a010b6c9f0af2d48565e9ad13/yarl-1.20.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:97c75596019baae7c71ccf1d8cc4738bc08134060d0adfcbe5642f778d1dca38", size = 365575, upload-time = "2025-06-10T00:44:02.051Z" }, - { url = "https://files.pythonhosted.org/packages/2e/e3/e4b0ad8403e97e6c9972dd587388940a032f030ebec196ab81a3b8e94d31/yarl-1.20.1-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:1c48912653e63aef91ff988c5432832692ac5a1d8f0fb8a33091520b5bbe19ef", size = 365061, upload-time = "2025-06-10T00:44:04.196Z" }, - { url = "https://files.pythonhosted.org/packages/ac/99/b8a142e79eb86c926f9f06452eb13ecb1bb5713bd01dc0038faf5452e544/yarl-1.20.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:4c3ae28f3ae1563c50f3d37f064ddb1511ecc1d5584e88c6b7c63cf7702a6d5f", size = 364142, upload-time = "2025-06-10T00:44:06.527Z" }, - { url = "https://files.pythonhosted.org/packages/34/f2/08ed34a4a506d82a1a3e5bab99ccd930a040f9b6449e9fd050320e45845c/yarl-1.20.1-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:c5e9642f27036283550f5f57dc6156c51084b458570b9d0d96100c8bebb186a8", size = 381894, upload-time = "2025-06-10T00:44:08.379Z" }, - { url = "https://files.pythonhosted.org/packages/92/f8/9a3fbf0968eac704f681726eff595dce9b49c8a25cd92bf83df209668285/yarl-1.20.1-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:2c26b0c49220d5799f7b22c6838409ee9bc58ee5c95361a4d7831f03cc225b5a", size = 383378, upload-time = "2025-06-10T00:44:10.51Z" }, - { url = "https://files.pythonhosted.org/packages/af/85/9363f77bdfa1e4d690957cd39d192c4cacd1c58965df0470a4905253b54f/yarl-1.20.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:564ab3d517e3d01c408c67f2e5247aad4019dcf1969982aba3974b4093279004", size = 374069, upload-time = "2025-06-10T00:44:12.834Z" }, - { url = "https://files.pythonhosted.org/packages/35/99/9918c8739ba271dcd935400cff8b32e3cd319eaf02fcd023d5dcd487a7c8/yarl-1.20.1-cp312-cp312-win32.whl", hash = "sha256:daea0d313868da1cf2fac6b2d3a25c6e3a9e879483244be38c8e6a41f1d876a5", size = 81249, upload-time = "2025-06-10T00:44:14.731Z" }, - { url = "https://files.pythonhosted.org/packages/eb/83/5d9092950565481b413b31a23e75dd3418ff0a277d6e0abf3729d4d1ce25/yarl-1.20.1-cp312-cp312-win_amd64.whl", hash = "sha256:48ea7d7f9be0487339828a4de0360d7ce0efc06524a48e1810f945c45b813698", size = 86710, upload-time = "2025-06-10T00:44:16.716Z" }, - { url = "https://files.pythonhosted.org/packages/b4/2d/2345fce04cfd4bee161bf1e7d9cdc702e3e16109021035dbb24db654a622/yarl-1.20.1-py3-none-any.whl", hash = "sha256:83b8eb083fe4683c6115795d9fc1cfaf2cbbefb19b3a1cb68f6527460f483a77", size = 46542, upload-time = "2025-06-10T00:46:07.521Z" }, + { url = "https://files.pythonhosted.org/packages/4c/bd/bbc499ee35ac9ec5459dbfec7bb7231556689e97eaa13a5eddbe1f0443b5/zensical-0.0.46-cp310-abi3-macosx_10_12_x86_64.whl", hash = "sha256:d91af81ab058c8693dfd75f2f77b4c73bcba4125681d1d276f38624291820bd2", size = 12796482, upload-time = "2026-06-21T18:52:07.369Z" }, + { url = "https://files.pythonhosted.org/packages/88/1b/7acc273184d59b8e894d15ebe3cf1c5e81b3a822fde1792ea3e33be37a2e/zensical-0.0.46-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:d9221264a9a87409900a47e29985607b0c9245dacb89077e87c8e16e31edc167", size = 12660030, upload-time = "2026-06-21T18:52:10.186Z" }, + { url = "https://files.pythonhosted.org/packages/80/df/bd0a68de98a19fc6050c58be11f36d05ea72a213b6a7ff7395d33c793747/zensical-0.0.46-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ec43018d5343ca2e1d71aa352eeddd560fef504effd03025840a5a783abefa4f", size = 13057130, upload-time = "2026-06-21T18:52:12.911Z" }, + { url = "https://files.pythonhosted.org/packages/f4/db/e27635f5787a42245f900e658340698a6654e165d466f9a3b640efced2cd/zensical-0.0.46-cp310-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:26e98fb8ab7ab50cdd20a73e2c7d4d9aae0b46cf2d8691e6bb22f9c261b8a60a", size = 13022345, upload-time = "2026-06-21T18:52:15.84Z" }, + { url = "https://files.pythonhosted.org/packages/e7/9d/6ce2ba11c97154870b458a8dae4637ade93b7097912f0102f5ea7fe8cf5b/zensical-0.0.46-cp310-abi3-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:46fe578f26963f8ee89567983e62737b6fadc9197d4742e1020b522e092d7baa", size = 13377445, upload-time = "2026-06-21T18:52:18.538Z" }, + { url = "https://files.pythonhosted.org/packages/68/06/9930d43cd9d2f899b648d63491007c1b4f9716cf118b0c98e867b933069c/zensical-0.0.46-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:aef03fa186a5589148e10b62610500989c6b075a2c08e1554233adbf91b2a3dc", size = 13086749, upload-time = "2026-06-21T18:52:21.452Z" }, + { url = "https://files.pythonhosted.org/packages/c4/ed/2342cf860fbb02314938b0d1f1b02344935801b04d185ff3151ef1812898/zensical-0.0.46-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:bc7446cdf97a8dea390f20ed2bd6b030cddc1bd36a8ce113ea3efef6fa61c573", size = 13231120, upload-time = "2026-06-21T18:52:24.171Z" }, + { url = "https://files.pythonhosted.org/packages/de/b0/d2ece02f63cd767fcf10fd7608dc8e0a995f87dc5261209b1dbc296fd57b/zensical-0.0.46-cp310-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:bbee37801f1ed500f158dc0992c569282950f780ae353c37fe6969f99983d701", size = 13295035, upload-time = "2026-06-21T18:52:26.942Z" }, + { url = "https://files.pythonhosted.org/packages/4b/b2/cb0048a612e63e615399fc507472a557d1c5b7c2f74065c5bf11998fd597/zensical-0.0.46-cp310-abi3-musllinux_1_2_i686.whl", hash = "sha256:9487c147c9cceb50c04d0ad70b024821a6eab1629dafd70ab6d1e86ec841e623", size = 13437191, upload-time = "2026-06-21T18:52:29.69Z" }, + { url = "https://files.pythonhosted.org/packages/91/16/515f81db8055b109a510063be481e60a657c4fad1a883680b2ee4aa9a424/zensical-0.0.46-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:f42a4683c762f026878d19ede4bcf7bfbb84dbecb5ad923949abb77806ed88a5", size = 13369382, upload-time = "2026-06-21T18:52:32.521Z" }, + { url = "https://files.pythonhosted.org/packages/b9/5c/da54ee65b642eb7d88dd4a3db35845d0765915638e05d5d434a10b42f1c3/zensical-0.0.46-cp310-abi3-win32.whl", hash = "sha256:85f018f2a7ee76a83915c87ddb12b58cf343fd6154081d33ac95b6751b011dd7", size = 12354298, upload-time = "2026-06-21T18:52:34.976Z" }, + { url = "https://files.pythonhosted.org/packages/73/26/fc7ef081acbdada8436825221cb728ee84a81d4d78a7bb79aa58bd150d31/zensical-0.0.46-cp310-abi3-win_amd64.whl", hash = "sha256:1543a693a160de60e86ca589592401b584670e7e12c5ae30e3c2ba76786f7ec3", size = 12599687, upload-time = "2026-06-21T18:52:37.913Z" }, ] [[package]] name = "zstandard" -version = "0.23.0" +version = "0.25.0" source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "cffi", marker = "platform_python_implementation == 'PyPy'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/ed/f6/2ac0287b442160a89d726b17a9184a4c615bb5237db763791a7fd16d9df1/zstandard-0.23.0.tar.gz", hash = "sha256:b2d8c62d08e7255f68f7a740bae85b3c9b8e5466baa9cbf7f57f1cde0ac6bc09", size = 681701, upload-time = "2024-07-15T00:18:06.141Z" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/aa/3e0508d5a5dd96529cdc5a97011299056e14c6505b678fd58938792794b1/zstandard-0.25.0.tar.gz", hash = "sha256:7713e1179d162cf5c7906da876ec2ccb9c3a9dcbdffef0cc7f70c3667a205f0b", size = 711513, upload-time = "2025-09-14T22:15:54.002Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/9e/40/f67e7d2c25a0e2dc1744dd781110b0b60306657f8696cafb7ad7579469bd/zstandard-0.23.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:34895a41273ad33347b2fc70e1bff4240556de3c46c6ea430a7ed91f9042aa4e", size = 788699, upload-time = "2024-07-15T00:14:04.909Z" }, - { url = "https://files.pythonhosted.org/packages/e8/46/66d5b55f4d737dd6ab75851b224abf0afe5774976fe511a54d2eb9063a41/zstandard-0.23.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:77ea385f7dd5b5676d7fd943292ffa18fbf5c72ba98f7d09fc1fb9e819b34c23", size = 633681, upload-time = "2024-07-15T00:14:13.99Z" }, - { url = "https://files.pythonhosted.org/packages/63/b6/677e65c095d8e12b66b8f862b069bcf1f1d781b9c9c6f12eb55000d57583/zstandard-0.23.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:983b6efd649723474f29ed42e1467f90a35a74793437d0bc64a5bf482bedfa0a", size = 4944328, upload-time = "2024-07-15T00:14:16.588Z" }, - { url = "https://files.pythonhosted.org/packages/59/cc/e76acb4c42afa05a9d20827116d1f9287e9c32b7ad58cc3af0721ce2b481/zstandard-0.23.0-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:80a539906390591dd39ebb8d773771dc4db82ace6372c4d41e2d293f8e32b8db", size = 5311955, upload-time = "2024-07-15T00:14:19.389Z" }, - { url = "https://files.pythonhosted.org/packages/78/e4/644b8075f18fc7f632130c32e8f36f6dc1b93065bf2dd87f03223b187f26/zstandard-0.23.0-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:445e4cb5048b04e90ce96a79b4b63140e3f4ab5f662321975679b5f6360b90e2", size = 5344944, upload-time = "2024-07-15T00:14:22.173Z" }, - { url = "https://files.pythonhosted.org/packages/76/3f/dbafccf19cfeca25bbabf6f2dd81796b7218f768ec400f043edc767015a6/zstandard-0.23.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fd30d9c67d13d891f2360b2a120186729c111238ac63b43dbd37a5a40670b8ca", size = 5442927, upload-time = "2024-07-15T00:14:24.825Z" }, - { url = "https://files.pythonhosted.org/packages/0c/c3/d24a01a19b6733b9f218e94d1a87c477d523237e07f94899e1c10f6fd06c/zstandard-0.23.0-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:d20fd853fbb5807c8e84c136c278827b6167ded66c72ec6f9a14b863d809211c", size = 4864910, upload-time = "2024-07-15T00:14:26.982Z" }, - { url = "https://files.pythonhosted.org/packages/1c/a9/cf8f78ead4597264f7618d0875be01f9bc23c9d1d11afb6d225b867cb423/zstandard-0.23.0-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:ed1708dbf4d2e3a1c5c69110ba2b4eb6678262028afd6c6fbcc5a8dac9cda68e", size = 4935544, upload-time = "2024-07-15T00:14:29.582Z" }, - { url = "https://files.pythonhosted.org/packages/2c/96/8af1e3731b67965fb995a940c04a2c20997a7b3b14826b9d1301cf160879/zstandard-0.23.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:be9b5b8659dff1f913039c2feee1aca499cfbc19e98fa12bc85e037c17ec6ca5", size = 5467094, upload-time = "2024-07-15T00:14:40.126Z" }, - { url = "https://files.pythonhosted.org/packages/ff/57/43ea9df642c636cb79f88a13ab07d92d88d3bfe3e550b55a25a07a26d878/zstandard-0.23.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:65308f4b4890aa12d9b6ad9f2844b7ee42c7f7a4fd3390425b242ffc57498f48", size = 4860440, upload-time = "2024-07-15T00:14:42.786Z" }, - { url = "https://files.pythonhosted.org/packages/46/37/edb78f33c7f44f806525f27baa300341918fd4c4af9472fbc2c3094be2e8/zstandard-0.23.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:98da17ce9cbf3bfe4617e836d561e433f871129e3a7ac16d6ef4c680f13a839c", size = 4700091, upload-time = "2024-07-15T00:14:45.184Z" }, - { url = "https://files.pythonhosted.org/packages/c1/f1/454ac3962671a754f3cb49242472df5c2cced4eb959ae203a377b45b1a3c/zstandard-0.23.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:8ed7d27cb56b3e058d3cf684d7200703bcae623e1dcc06ed1e18ecda39fee003", size = 5208682, upload-time = "2024-07-15T00:14:47.407Z" }, - { url = "https://files.pythonhosted.org/packages/85/b2/1734b0fff1634390b1b887202d557d2dd542de84a4c155c258cf75da4773/zstandard-0.23.0-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:b69bb4f51daf461b15e7b3db033160937d3ff88303a7bc808c67bbc1eaf98c78", size = 5669707, upload-time = "2024-07-15T00:15:03.529Z" }, - { url = "https://files.pythonhosted.org/packages/52/5a/87d6971f0997c4b9b09c495bf92189fb63de86a83cadc4977dc19735f652/zstandard-0.23.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:034b88913ecc1b097f528e42b539453fa82c3557e414b3de9d5632c80439a473", size = 5201792, upload-time = "2024-07-15T00:15:28.372Z" }, - { url = "https://files.pythonhosted.org/packages/79/02/6f6a42cc84459d399bd1a4e1adfc78d4dfe45e56d05b072008d10040e13b/zstandard-0.23.0-cp311-cp311-win32.whl", hash = "sha256:f2d4380bf5f62daabd7b751ea2339c1a21d1c9463f1feb7fc2bdcea2c29c3160", size = 430586, upload-time = "2024-07-15T00:15:32.26Z" }, - { url = "https://files.pythonhosted.org/packages/be/a2/4272175d47c623ff78196f3c10e9dc7045c1b9caf3735bf041e65271eca4/zstandard-0.23.0-cp311-cp311-win_amd64.whl", hash = "sha256:62136da96a973bd2557f06ddd4e8e807f9e13cbb0bfb9cc06cfe6d98ea90dfe0", size = 495420, upload-time = "2024-07-15T00:15:34.004Z" }, - { url = "https://files.pythonhosted.org/packages/7b/83/f23338c963bd9de687d47bf32efe9fd30164e722ba27fb59df33e6b1719b/zstandard-0.23.0-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:b4567955a6bc1b20e9c31612e615af6b53733491aeaa19a6b3b37f3b65477094", size = 788713, upload-time = "2024-07-15T00:15:35.815Z" }, - { url = "https://files.pythonhosted.org/packages/5b/b3/1a028f6750fd9227ee0b937a278a434ab7f7fdc3066c3173f64366fe2466/zstandard-0.23.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1e172f57cd78c20f13a3415cc8dfe24bf388614324d25539146594c16d78fcc8", size = 633459, upload-time = "2024-07-15T00:15:37.995Z" }, - { url = "https://files.pythonhosted.org/packages/26/af/36d89aae0c1f95a0a98e50711bc5d92c144939efc1f81a2fcd3e78d7f4c1/zstandard-0.23.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b0e166f698c5a3e914947388c162be2583e0c638a4703fc6a543e23a88dea3c1", size = 4945707, upload-time = "2024-07-15T00:15:39.872Z" }, - { url = "https://files.pythonhosted.org/packages/cd/2e/2051f5c772f4dfc0aae3741d5fc72c3dcfe3aaeb461cc231668a4db1ce14/zstandard-0.23.0-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:12a289832e520c6bd4dcaad68e944b86da3bad0d339ef7989fb7e88f92e96072", size = 5306545, upload-time = "2024-07-15T00:15:41.75Z" }, - { url = "https://files.pythonhosted.org/packages/0a/9e/a11c97b087f89cab030fa71206963090d2fecd8eb83e67bb8f3ffb84c024/zstandard-0.23.0-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:d50d31bfedd53a928fed6707b15a8dbeef011bb6366297cc435accc888b27c20", size = 5337533, upload-time = "2024-07-15T00:15:44.114Z" }, - { url = "https://files.pythonhosted.org/packages/fc/79/edeb217c57fe1bf16d890aa91a1c2c96b28c07b46afed54a5dcf310c3f6f/zstandard-0.23.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:72c68dda124a1a138340fb62fa21b9bf4848437d9ca60bd35db36f2d3345f373", size = 5436510, upload-time = "2024-07-15T00:15:46.509Z" }, - { url = "https://files.pythonhosted.org/packages/81/4f/c21383d97cb7a422ddf1ae824b53ce4b51063d0eeb2afa757eb40804a8ef/zstandard-0.23.0-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:53dd9d5e3d29f95acd5de6802e909ada8d8d8cfa37a3ac64836f3bc4bc5512db", size = 4859973, upload-time = "2024-07-15T00:15:49.939Z" }, - { url = "https://files.pythonhosted.org/packages/ab/15/08d22e87753304405ccac8be2493a495f529edd81d39a0870621462276ef/zstandard-0.23.0-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:6a41c120c3dbc0d81a8e8adc73312d668cd34acd7725f036992b1b72d22c1772", size = 4936968, upload-time = "2024-07-15T00:15:52.025Z" }, - { url = "https://files.pythonhosted.org/packages/eb/fa/f3670a597949fe7dcf38119a39f7da49a8a84a6f0b1a2e46b2f71a0ab83f/zstandard-0.23.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:40b33d93c6eddf02d2c19f5773196068d875c41ca25730e8288e9b672897c105", size = 5467179, upload-time = "2024-07-15T00:15:54.971Z" }, - { url = "https://files.pythonhosted.org/packages/4e/a9/dad2ab22020211e380adc477a1dbf9f109b1f8d94c614944843e20dc2a99/zstandard-0.23.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:9206649ec587e6b02bd124fb7799b86cddec350f6f6c14bc82a2b70183e708ba", size = 4848577, upload-time = "2024-07-15T00:15:57.634Z" }, - { url = "https://files.pythonhosted.org/packages/08/03/dd28b4484b0770f1e23478413e01bee476ae8227bbc81561f9c329e12564/zstandard-0.23.0-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:76e79bc28a65f467e0409098fa2c4376931fd3207fbeb6b956c7c476d53746dd", size = 4693899, upload-time = "2024-07-15T00:16:00.811Z" }, - { url = "https://files.pythonhosted.org/packages/2b/64/3da7497eb635d025841e958bcd66a86117ae320c3b14b0ae86e9e8627518/zstandard-0.23.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:66b689c107857eceabf2cf3d3fc699c3c0fe8ccd18df2219d978c0283e4c508a", size = 5199964, upload-time = "2024-07-15T00:16:03.669Z" }, - { url = "https://files.pythonhosted.org/packages/43/a4/d82decbab158a0e8a6ebb7fc98bc4d903266bce85b6e9aaedea1d288338c/zstandard-0.23.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:9c236e635582742fee16603042553d276cca506e824fa2e6489db04039521e90", size = 5655398, upload-time = "2024-07-15T00:16:06.694Z" }, - { url = "https://files.pythonhosted.org/packages/f2/61/ac78a1263bc83a5cf29e7458b77a568eda5a8f81980691bbc6eb6a0d45cc/zstandard-0.23.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:a8fffdbd9d1408006baaf02f1068d7dd1f016c6bcb7538682622c556e7b68e35", size = 5191313, upload-time = "2024-07-15T00:16:09.758Z" }, - { url = "https://files.pythonhosted.org/packages/e7/54/967c478314e16af5baf849b6ee9d6ea724ae5b100eb506011f045d3d4e16/zstandard-0.23.0-cp312-cp312-win32.whl", hash = "sha256:dc1d33abb8a0d754ea4763bad944fd965d3d95b5baef6b121c0c9013eaf1907d", size = 430877, upload-time = "2024-07-15T00:16:11.758Z" }, - { url = "https://files.pythonhosted.org/packages/75/37/872d74bd7739639c4553bf94c84af7d54d8211b626b352bc57f0fd8d1e3f/zstandard-0.23.0-cp312-cp312-win_amd64.whl", hash = "sha256:64585e1dba664dc67c7cdabd56c1e5685233fbb1fc1966cfba2a340ec0dfff7b", size = 495595, upload-time = "2024-07-15T00:16:13.731Z" }, + { url = "https://files.pythonhosted.org/packages/82/fc/f26eb6ef91ae723a03e16eddb198abcfce2bc5a42e224d44cc8b6765e57e/zstandard-0.25.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:7b3c3a3ab9daa3eed242d6ecceead93aebbb8f5f84318d82cee643e019c4b73b", size = 795738, upload-time = "2025-09-14T22:16:56.237Z" }, + { url = "https://files.pythonhosted.org/packages/aa/1c/d920d64b22f8dd028a8b90e2d756e431a5d86194caa78e3819c7bf53b4b3/zstandard-0.25.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:913cbd31a400febff93b564a23e17c3ed2d56c064006f54efec210d586171c00", size = 640436, upload-time = "2025-09-14T22:16:57.774Z" }, + { url = "https://files.pythonhosted.org/packages/53/6c/288c3f0bd9fcfe9ca41e2c2fbfd17b2097f6af57b62a81161941f09afa76/zstandard-0.25.0-cp312-cp312-manylinux2010_i686.manylinux2014_i686.manylinux_2_12_i686.manylinux_2_17_i686.whl", hash = "sha256:011d388c76b11a0c165374ce660ce2c8efa8e5d87f34996aa80f9c0816698b64", size = 5343019, upload-time = "2025-09-14T22:16:59.302Z" }, + { url = "https://files.pythonhosted.org/packages/1e/15/efef5a2f204a64bdb5571e6161d49f7ef0fffdbca953a615efbec045f60f/zstandard-0.25.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:6dffecc361d079bb48d7caef5d673c88c8988d3d33fb74ab95b7ee6da42652ea", size = 5063012, upload-time = "2025-09-14T22:17:01.156Z" }, + { url = "https://files.pythonhosted.org/packages/b7/37/a6ce629ffdb43959e92e87ebdaeebb5ac81c944b6a75c9c47e300f85abdf/zstandard-0.25.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:7149623bba7fdf7e7f24312953bcf73cae103db8cae49f8154dd1eadc8a29ecb", size = 5394148, upload-time = "2025-09-14T22:17:03.091Z" }, + { url = "https://files.pythonhosted.org/packages/e3/79/2bf870b3abeb5c070fe2d670a5a8d1057a8270f125ef7676d29ea900f496/zstandard-0.25.0-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:6a573a35693e03cf1d67799fd01b50ff578515a8aeadd4595d2a7fa9f3ec002a", size = 5451652, upload-time = "2025-09-14T22:17:04.979Z" }, + { url = "https://files.pythonhosted.org/packages/53/60/7be26e610767316c028a2cbedb9a3beabdbe33e2182c373f71a1c0b88f36/zstandard-0.25.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:5a56ba0db2d244117ed744dfa8f6f5b366e14148e00de44723413b2f3938a902", size = 5546993, upload-time = "2025-09-14T22:17:06.781Z" }, + { url = "https://files.pythonhosted.org/packages/85/c7/3483ad9ff0662623f3648479b0380d2de5510abf00990468c286c6b04017/zstandard-0.25.0-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:10ef2a79ab8e2974e2075fb984e5b9806c64134810fac21576f0668e7ea19f8f", size = 5046806, upload-time = "2025-09-14T22:17:08.415Z" }, + { url = "https://files.pythonhosted.org/packages/08/b3/206883dd25b8d1591a1caa44b54c2aad84badccf2f1de9e2d60a446f9a25/zstandard-0.25.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:aaf21ba8fb76d102b696781bddaa0954b782536446083ae3fdaa6f16b25a1c4b", size = 5576659, upload-time = "2025-09-14T22:17:10.164Z" }, + { url = "https://files.pythonhosted.org/packages/9d/31/76c0779101453e6c117b0ff22565865c54f48f8bd807df2b00c2c404b8e0/zstandard-0.25.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:1869da9571d5e94a85a5e8d57e4e8807b175c9e4a6294e3b66fa4efb074d90f6", size = 4953933, upload-time = "2025-09-14T22:17:11.857Z" }, + { url = "https://files.pythonhosted.org/packages/18/e1/97680c664a1bf9a247a280a053d98e251424af51f1b196c6d52f117c9720/zstandard-0.25.0-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:809c5bcb2c67cd0ed81e9229d227d4ca28f82d0f778fc5fea624a9def3963f91", size = 5268008, upload-time = "2025-09-14T22:17:13.627Z" }, + { url = "https://files.pythonhosted.org/packages/1e/73/316e4010de585ac798e154e88fd81bb16afc5c5cb1a72eeb16dd37e8024a/zstandard-0.25.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:f27662e4f7dbf9f9c12391cb37b4c4c3cb90ffbd3b1fb9284dadbbb8935fa708", size = 5433517, upload-time = "2025-09-14T22:17:16.103Z" }, + { url = "https://files.pythonhosted.org/packages/5b/60/dd0f8cfa8129c5a0ce3ea6b7f70be5b33d2618013a161e1ff26c2b39787c/zstandard-0.25.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:99c0c846e6e61718715a3c9437ccc625de26593fea60189567f0118dc9db7512", size = 5814292, upload-time = "2025-09-14T22:17:17.827Z" }, + { url = "https://files.pythonhosted.org/packages/fc/5f/75aafd4b9d11b5407b641b8e41a57864097663699f23e9ad4dbb91dc6bfe/zstandard-0.25.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:474d2596a2dbc241a556e965fb76002c1ce655445e4e3bf38e5477d413165ffa", size = 5360237, upload-time = "2025-09-14T22:17:19.954Z" }, + { url = "https://files.pythonhosted.org/packages/ff/8d/0309daffea4fcac7981021dbf21cdb2e3427a9e76bafbcdbdf5392ff99a4/zstandard-0.25.0-cp312-cp312-win32.whl", hash = "sha256:23ebc8f17a03133b4426bcc04aabd68f8236eb78c3760f12783385171b0fd8bd", size = 436922, upload-time = "2025-09-14T22:17:24.398Z" }, + { url = "https://files.pythonhosted.org/packages/79/3b/fa54d9015f945330510cb5d0b0501e8253c127cca7ebe8ba46a965df18c5/zstandard-0.25.0-cp312-cp312-win_amd64.whl", hash = "sha256:ffef5a74088f1e09947aecf91011136665152e0b4b359c42be3373897fb39b01", size = 506276, upload-time = "2025-09-14T22:17:21.429Z" }, + { url = "https://files.pythonhosted.org/packages/ea/6b/8b51697e5319b1f9ac71087b0af9a40d8a6288ff8025c36486e0c12abcc4/zstandard-0.25.0-cp312-cp312-win_arm64.whl", hash = "sha256:181eb40e0b6a29b3cd2849f825e0fa34397f649170673d385f3598ae17cca2e9", size = 462679, upload-time = "2025-09-14T22:17:23.147Z" }, ] diff --git a/zensical.toml b/zensical.toml new file mode 100644 index 0000000000..7e5ca2c5db --- /dev/null +++ b/zensical.toml @@ -0,0 +1,81 @@ +[project] +site_name = "openpilot docs" +site_url = "https://docs.comma.ai" +repo_url = "https://github.com/commaai/openpilot/" + +docs_dir = "docs" +site_dir = "docs_site/" + +extra_css = ["stylesheets/extra.css"] + +nav = [ + { "What is openpilot?" = "index.md" }, + { "How-to" = [ + { "Turn the speed blue" = "how-to/turn-the-speed-blue.md" }, + { "Connect to a comma 3X or four" = "how-to/connect-to-comma.md" }, + { "Add support for a car" = "how-to/car-port.md" }, + ] }, + { "Concepts" = [ + { "Logs" = "concepts/logs.md" }, + { "Safety" = "concepts/safety.md" }, + { "Glossary" = "concepts/glossary.md" }, + ] }, + { "Contributing" = [ + { "Feedback" = "contributing/feedback.md" }, + { "Roadmap" = "contributing/roadmap.md" }, + { "Contributing Guide →" = "https://github.com/commaai/openpilot/blob/master/docs/CONTRIBUTING.md" }, + ] }, + { "Links" = [ + { "Blog →" = "https://blog.comma.ai" }, + { "Bounties →" = "https://comma.ai/bounties" }, + { "GitHub →" = "https://github.com/commaai" }, + { "Discord →" = "https://discord.comma.ai" }, + { "X →" = "https://x.com/comma_ai" }, + ] }, +] + +[project.theme] +logo = "assets/comma-logo.png" +features = [ + "navigation.expand", + "navigation.sections", + "navigation.instant", + "navigation.instant.prefetch", + "content.code.copy", + "content.action.edit", + "content.action.view", +] + +[[project.extra.social]] +icon = "fontawesome/brands/github" +link = "https://github.com/commaai" + +[[project.extra.social]] +icon = "fontawesome/brands/discord" +link = "https://discord.comma.ai" + +[[project.extra.social]] +icon = "fontawesome/brands/x-twitter" +link = "https://x.com/comma_ai" + +[project.markdown_extensions.attr_list] + +[project.markdown_extensions.admonition] + +[project.markdown_extensions.md_in_html] + +[project.markdown_extensions.pymdownx.highlight] +anchor_linenums = true +line_spans = "__span" +pygments_lang_class = true + +[project.markdown_extensions.pymdownx.inlinehilite] + +[project.markdown_extensions.pymdownx.magiclink] + +[project.markdown_extensions.pymdownx.superfences] +custom_fences = [{ name = "mermaid", class = "mermaid" }] + +[project.markdown_extensions.pymdownx.details] + +[project.markdown_extensions."ext.glossary"]
Disengaged